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.

273949 lines
7.3MB

  1. /*
  2. ==============================================================================
  3. This file is part of the JUCE library - "Jules' Utility Class Extensions"
  4. Copyright 2004-9 by Raw Material Software Ltd.
  5. ------------------------------------------------------------------------------
  6. JUCE can be redistributed and/or modified under the terms of the GNU General
  7. Public License (Version 2), as published by the Free Software Foundation.
  8. A copy of the license is included in the JUCE distribution, or can be found
  9. online at www.gnu.org/licenses.
  10. JUCE is distributed in the hope that it will be useful, but WITHOUT ANY
  11. WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR
  12. A PARTICULAR PURPOSE. See the GNU General Public License for more details.
  13. ------------------------------------------------------------------------------
  14. To release a closed-source product which uses JUCE, commercial licenses are
  15. available: visit www.rawmaterialsoftware.com/juce for more information.
  16. ==============================================================================
  17. */
  18. /*
  19. This monolithic file contains the entire Juce source tree!
  20. To build an app which uses Juce, all you need to do is to add this
  21. file to your project, and include juce.h in your own cpp files.
  22. */
  23. #ifdef __JUCE_JUCEHEADER__
  24. /* When you add the amalgamated cpp file to your project, you mustn't include it in
  25. a file where you've already included juce.h - just put it inside a file on its own,
  26. possibly with your config flags preceding it, but don't include anything else. */
  27. #error
  28. #endif
  29. /*** Start of inlined file: juce_TargetPlatform.h ***/
  30. #ifndef __JUCE_TARGETPLATFORM_JUCEHEADER__
  31. #define __JUCE_TARGETPLATFORM_JUCEHEADER__
  32. /* This file figures out which platform is being built, and defines some macros
  33. that the rest of the code can use for OS-specific compilation.
  34. Macros that will be set here are:
  35. - One of JUCE_WINDOWS, JUCE_MAC or JUCE_LINUX.
  36. - Either JUCE_32BIT or JUCE_64BIT, depending on the architecture.
  37. - Either JUCE_LITTLE_ENDIAN or JUCE_BIG_ENDIAN.
  38. - Either JUCE_INTEL or JUCE_PPC
  39. - Either JUCE_GCC or JUCE_MSVC
  40. */
  41. #if (defined (_WIN32) || defined (_WIN64))
  42. #define JUCE_WIN32 1
  43. #define JUCE_WINDOWS 1
  44. #elif defined (LINUX) || defined (__linux__)
  45. #define JUCE_LINUX 1
  46. #elif defined(__APPLE_CPP__) || defined(__APPLE_CC__)
  47. #include <CoreFoundation/CoreFoundation.h> // (needed to find out what platform we're using)
  48. #if TARGET_OS_IPHONE || TARGET_IPHONE_SIMULATOR
  49. #define JUCE_IPHONE 1
  50. #else
  51. #define JUCE_MAC 1
  52. #endif
  53. #else
  54. #error "Unknown platform!"
  55. #endif
  56. #if JUCE_WINDOWS
  57. #ifdef _MSC_VER
  58. #ifdef _WIN64
  59. #define JUCE_64BIT 1
  60. #else
  61. #define JUCE_32BIT 1
  62. #endif
  63. #endif
  64. #ifdef _DEBUG
  65. #define JUCE_DEBUG 1
  66. #endif
  67. #ifdef __MINGW32__
  68. #define JUCE_MINGW 1
  69. #endif
  70. /** If defined, this indicates that the processor is little-endian. */
  71. #define JUCE_LITTLE_ENDIAN 1
  72. #define JUCE_INTEL 1
  73. #endif
  74. #if JUCE_MAC
  75. #ifndef NDEBUG
  76. #define JUCE_DEBUG 1
  77. #endif
  78. #ifdef __LITTLE_ENDIAN__
  79. #define JUCE_LITTLE_ENDIAN 1
  80. #else
  81. #define JUCE_BIG_ENDIAN 1
  82. #endif
  83. #if defined (__ppc__) || defined (__ppc64__)
  84. #define JUCE_PPC 1
  85. #else
  86. #define JUCE_INTEL 1
  87. #endif
  88. #ifdef __LP64__
  89. #define JUCE_64BIT 1
  90. #else
  91. #define JUCE_32BIT 1
  92. #endif
  93. #if MAC_OS_X_VERSION_MIN_REQUIRED < MAC_OS_X_VERSION_10_4
  94. #error "Building for OSX 10.3 is no longer supported!"
  95. #endif
  96. #ifndef MAC_OS_X_VERSION_10_5
  97. #error "To build with 10.4 compatibility, use a 10.5 or 10.6 SDK and set the deployment target to 10.4"
  98. #endif
  99. #endif
  100. #if JUCE_IPHONE
  101. #ifndef NDEBUG
  102. #define JUCE_DEBUG 1
  103. #endif
  104. #ifdef __LITTLE_ENDIAN__
  105. #define JUCE_LITTLE_ENDIAN 1
  106. #else
  107. #define JUCE_BIG_ENDIAN 1
  108. #endif
  109. #endif
  110. #if JUCE_LINUX
  111. #ifdef _DEBUG
  112. #define JUCE_DEBUG 1
  113. #endif
  114. // Allow override for big-endian Linux platforms
  115. #ifndef JUCE_BIG_ENDIAN
  116. #define JUCE_LITTLE_ENDIAN 1
  117. #endif
  118. #if defined (__LP64__) || defined (_LP64)
  119. #define JUCE_64BIT 1
  120. #else
  121. #define JUCE_32BIT 1
  122. #endif
  123. #define JUCE_INTEL 1
  124. #endif
  125. // Compiler type macros.
  126. #ifdef __GNUC__
  127. #define JUCE_GCC 1
  128. #elif defined (_MSC_VER)
  129. #define JUCE_MSVC 1
  130. #if _MSC_VER >= 1400
  131. #define JUCE_USE_INTRINSICS 1
  132. #endif
  133. #else
  134. #error unknown compiler
  135. #endif
  136. #endif // __JUCE_TARGETPLATFORM_JUCEHEADER__
  137. /*** End of inlined file: juce_TargetPlatform.h ***/
  138. // FORCE_AMALGAMATOR_INCLUDE
  139. /*** Start of inlined file: juce_Config.h ***/
  140. #ifndef __JUCE_CONFIG_JUCEHEADER__
  141. #define __JUCE_CONFIG_JUCEHEADER__
  142. /*
  143. This file contains macros that enable/disable various JUCE features.
  144. */
  145. /** The name of the namespace that all Juce classes and functions will be
  146. put inside. If this is not defined, no namespace will be used.
  147. */
  148. #ifndef JUCE_NAMESPACE
  149. #define JUCE_NAMESPACE juce
  150. #endif
  151. /** JUCE_FORCE_DEBUG: Normally, JUCE_DEBUG is set to 1 or 0 based on compiler and
  152. project settings, but if you define this value, you can override this to force
  153. it to be true or false.
  154. */
  155. #ifndef JUCE_FORCE_DEBUG
  156. //#define JUCE_FORCE_DEBUG 0
  157. #endif
  158. /** JUCE_LOG_ASSERTIONS: If this flag is enabled, the the jassert and jassertfalse
  159. macros will always use Logger::writeToLog() to write a message when an assertion happens.
  160. Enabling it will also leave this turned on in release builds. When it's disabled,
  161. however, the jassert and jassertfalse macros will not be compiled in a
  162. release build.
  163. @see jassert, jassertfalse, Logger
  164. */
  165. #ifndef JUCE_LOG_ASSERTIONS
  166. #define JUCE_LOG_ASSERTIONS 0
  167. #endif
  168. /** JUCE_ASIO: Enables ASIO audio devices (MS Windows only).
  169. Turning this on means that you'll need to have the Steinberg ASIO SDK installed
  170. on your Windows build machine.
  171. See the comments in the ASIOAudioIODevice class's header file for more
  172. info about this.
  173. */
  174. #ifndef JUCE_ASIO
  175. #define JUCE_ASIO 0
  176. #endif
  177. /** JUCE_WASAPI: Enables WASAPI audio devices (Windows Vista and above).
  178. */
  179. #ifndef JUCE_WASAPI
  180. #define JUCE_WASAPI 0
  181. #endif
  182. /** JUCE_DIRECTSOUND: Enables DirectSound audio (MS Windows only).
  183. */
  184. #ifndef JUCE_DIRECTSOUND
  185. #define JUCE_DIRECTSOUND 1
  186. #endif
  187. /** JUCE_ALSA: Enables ALSA audio devices (Linux only). */
  188. #ifndef JUCE_ALSA
  189. #define JUCE_ALSA 1
  190. #endif
  191. /** JUCE_JACK: Enables JACK audio devices (Linux only). */
  192. #ifndef JUCE_JACK
  193. #define JUCE_JACK 0
  194. #endif
  195. /** JUCE_QUICKTIME: Enables the QuickTimeMovieComponent class (Mac and Windows).
  196. If you're building on Windows, you'll need to have the Apple QuickTime SDK
  197. installed, and its header files will need to be on your include path.
  198. */
  199. #if ! (defined (JUCE_QUICKTIME) || JUCE_LINUX || JUCE_IPHONE || (JUCE_WINDOWS && ! JUCE_MSVC))
  200. #define JUCE_QUICKTIME 0
  201. #endif
  202. #if (JUCE_IPHONE || JUCE_LINUX) && JUCE_QUICKTIME
  203. #undef JUCE_QUICKTIME
  204. #endif
  205. /** JUCE_OPENGL: Enables the OpenGLComponent class (available on all platforms).
  206. If you're not using OpenGL, you might want to turn this off to reduce your binary's size.
  207. */
  208. #ifndef JUCE_OPENGL
  209. #define JUCE_OPENGL 1
  210. #endif
  211. /** JUCE_USE_FLAC: Enables the FLAC audio codec classes (available on all platforms).
  212. If your app doesn't need to read FLAC files, you might want to disable this to
  213. reduce the size of your codebase and build time.
  214. */
  215. #ifndef JUCE_USE_FLAC
  216. #define JUCE_USE_FLAC 1
  217. #endif
  218. /** JUCE_USE_OGGVORBIS: Enables the Ogg-Vorbis audio codec classes (available on all platforms).
  219. If your app doesn't need to read Ogg-Vorbis files, you might want to disable this to
  220. reduce the size of your codebase and build time.
  221. */
  222. #ifndef JUCE_USE_OGGVORBIS
  223. #define JUCE_USE_OGGVORBIS 1
  224. #endif
  225. /** JUCE_USE_CDBURNER: Enables the audio CD reader code (Mac and Windows only).
  226. Unless you're using CD-burning, you should probably turn this flag off to
  227. reduce code size.
  228. */
  229. #if (! defined (JUCE_USE_CDBURNER)) && ! (JUCE_WINDOWS && ! JUCE_MSVC)
  230. #define JUCE_USE_CDBURNER 0
  231. #endif
  232. /** JUCE_USE_CDREADER: Enables the audio CD reader code (Mac and Windows only).
  233. Unless you're using CD-reading, you should probably turn this flag off to
  234. reduce code size.
  235. */
  236. #ifndef JUCE_USE_CDREADER
  237. #define JUCE_USE_CDREADER 0
  238. #endif
  239. /** JUCE_USE_CAMERA: Enables web-cam support using the CameraDevice class (Mac and Windows).
  240. */
  241. #if (JUCE_QUICKTIME || JUCE_WINDOWS) && ! defined (JUCE_USE_CAMERA)
  242. #define JUCE_USE_CAMERA 0
  243. #endif
  244. /** JUCE_ENABLE_REPAINT_DEBUGGING: If this option is turned on, each area of the screen that
  245. gets repainted will flash in a random colour, so that you can check exactly how much and how
  246. often your components are being drawn.
  247. */
  248. #ifndef JUCE_ENABLE_REPAINT_DEBUGGING
  249. #define JUCE_ENABLE_REPAINT_DEBUGGING 0
  250. #endif
  251. /** JUCE_USE_XINERAMA: Enables Xinerama multi-monitor support (Linux only).
  252. Unless you specifically want to disable this, it's best to leave this option turned on.
  253. */
  254. #ifndef JUCE_USE_XINERAMA
  255. #define JUCE_USE_XINERAMA 1
  256. #endif
  257. /** JUCE_USE_XSHM: Enables X shared memory for faster rendering on Linux. This is best left
  258. turned on unless you have a good reason to disable it.
  259. */
  260. #ifndef JUCE_USE_XSHM
  261. #define JUCE_USE_XSHM 1
  262. #endif
  263. /** JUCE_USE_XRENDER: Uses XRender to allow semi-transparent windowing on Linux.
  264. */
  265. #ifndef JUCE_USE_XRENDER
  266. #define JUCE_USE_XRENDER 0
  267. #endif
  268. /** JUCE_USE_XCURSOR: Uses XCursor to allow ARGB cursor on Linux. This is best left turned on
  269. unless you have a good reason to disable it.
  270. */
  271. #ifndef JUCE_USE_XCURSOR
  272. #define JUCE_USE_XCURSOR 1
  273. #endif
  274. /** JUCE_PLUGINHOST_VST: Enables the VST audio plugin hosting classes. This requires the
  275. Steinberg VST SDK to be installed on your machine, and should be left turned off unless
  276. you're building a plugin hosting app.
  277. @see VSTPluginFormat, AudioPluginFormat, AudioPluginFormatManager, JUCE_PLUGINHOST_AU
  278. */
  279. #ifndef JUCE_PLUGINHOST_VST
  280. #define JUCE_PLUGINHOST_VST 0
  281. #endif
  282. /** JUCE_PLUGINHOST_AU: Enables the AudioUnit plugin hosting classes. This is Mac-only,
  283. of course, and should only be enabled if you're building a plugin hosting app.
  284. @see AudioUnitPluginFormat, AudioPluginFormat, AudioPluginFormatManager, JUCE_PLUGINHOST_VST
  285. */
  286. #ifndef JUCE_PLUGINHOST_AU
  287. #define JUCE_PLUGINHOST_AU 0
  288. #endif
  289. /** JUCE_ONLY_BUILD_CORE_LIBRARY: Enabling this will avoid including any UI classes in the build.
  290. This should be enabled if you're writing a console application.
  291. */
  292. #ifndef JUCE_ONLY_BUILD_CORE_LIBRARY
  293. #define JUCE_ONLY_BUILD_CORE_LIBRARY 0
  294. #endif
  295. /** JUCE_WEB_BROWSER: This lets you disable the WebBrowserComponent class (Mac and Windows).
  296. If you're not using any embedded web-pages, turning this off may reduce your code size.
  297. */
  298. #ifndef JUCE_WEB_BROWSER
  299. #define JUCE_WEB_BROWSER 1
  300. #endif
  301. /** JUCE_SUPPORT_CARBON: Enabling this allows the Mac code to use old Carbon library functions.
  302. Carbon isn't required for a normal app, but may be needed by specialised classes like
  303. plugin-hosts, which support older APIs.
  304. */
  305. #ifndef JUCE_SUPPORT_CARBON
  306. #define JUCE_SUPPORT_CARBON 1
  307. #endif
  308. /* JUCE_INCLUDE_ZLIB_CODE: Can be used to disable Juce's embedded 3rd-party zlib code.
  309. You might need to tweak this if you're linking to an external zlib library in your app,
  310. but for normal apps, this option should be left alone.
  311. */
  312. #ifndef JUCE_INCLUDE_ZLIB_CODE
  313. #define JUCE_INCLUDE_ZLIB_CODE 1
  314. #endif
  315. #ifndef JUCE_INCLUDE_FLAC_CODE
  316. #define JUCE_INCLUDE_FLAC_CODE 1
  317. #endif
  318. #ifndef JUCE_INCLUDE_OGGVORBIS_CODE
  319. #define JUCE_INCLUDE_OGGVORBIS_CODE 1
  320. #endif
  321. #ifndef JUCE_INCLUDE_PNGLIB_CODE
  322. #define JUCE_INCLUDE_PNGLIB_CODE 1
  323. #endif
  324. #ifndef JUCE_INCLUDE_JPEGLIB_CODE
  325. #define JUCE_INCLUDE_JPEGLIB_CODE 1
  326. #endif
  327. /** JUCE_CHECK_MEMORY_LEAKS: Enables a memory-leak check when an app terminates.
  328. (Currently, this only affects Windows builds in debug mode).
  329. */
  330. #ifndef JUCE_CHECK_MEMORY_LEAKS
  331. #define JUCE_CHECK_MEMORY_LEAKS 1
  332. #endif
  333. /** JUCE_CATCH_UNHANDLED_EXCEPTIONS: Turn on juce's internal catching of exceptions
  334. that are thrown by the message dispatch loop. With it enabled, any unhandled exceptions
  335. are passed to the JUCEApplication::unhandledException() callback for logging.
  336. */
  337. #ifndef JUCE_CATCH_UNHANDLED_EXCEPTIONS
  338. #define JUCE_CATCH_UNHANDLED_EXCEPTIONS 1
  339. #endif
  340. // If only building the core classes, we can explicitly turn off some features to avoid including them:
  341. #if JUCE_ONLY_BUILD_CORE_LIBRARY
  342. #undef JUCE_QUICKTIME
  343. #define JUCE_QUICKTIME 0
  344. #undef JUCE_OPENGL
  345. #define JUCE_OPENGL 0
  346. #undef JUCE_USE_CDBURNER
  347. #define JUCE_USE_CDBURNER 0
  348. #undef JUCE_USE_CDREADER
  349. #define JUCE_USE_CDREADER 0
  350. #undef JUCE_WEB_BROWSER
  351. #define JUCE_WEB_BROWSER 0
  352. #undef JUCE_PLUGINHOST_AU
  353. #define JUCE_PLUGINHOST_AU 0
  354. #undef JUCE_PLUGINHOST_VST
  355. #define JUCE_PLUGINHOST_VST 0
  356. #endif
  357. #endif
  358. /*** End of inlined file: juce_Config.h ***/
  359. // FORCE_AMALGAMATOR_INCLUDE
  360. #ifndef JUCE_BUILD_CORE
  361. #define JUCE_BUILD_CORE 1
  362. #endif
  363. #ifndef JUCE_BUILD_MISC
  364. #define JUCE_BUILD_MISC 1
  365. #endif
  366. #ifndef JUCE_BUILD_GUI
  367. #define JUCE_BUILD_GUI 1
  368. #endif
  369. #ifndef JUCE_BUILD_NATIVE
  370. #define JUCE_BUILD_NATIVE 1
  371. #endif
  372. #if JUCE_ONLY_BUILD_CORE_LIBRARY
  373. #undef JUCE_BUILD_MISC
  374. #undef JUCE_BUILD_GUI
  375. #endif
  376. //==============================================================================
  377. #if JUCE_BUILD_NATIVE || JUCE_BUILD_CORE || (JUCE_BUILD_MISC && (JUCE_PLUGINHOST_VST || JUCE_PLUGINHOST_AU))
  378. #if JUCE_WINDOWS
  379. /*** Start of inlined file: juce_win32_NativeIncludes.h ***/
  380. #ifndef __JUCE_WIN32_NATIVEINCLUDES_JUCEHEADER__
  381. #define __JUCE_WIN32_NATIVEINCLUDES_JUCEHEADER__
  382. #ifndef STRICT
  383. #define STRICT 1
  384. #endif
  385. #undef WIN32_LEAN_AND_MEAN
  386. #define WIN32_LEAN_AND_MEAN 1
  387. #ifdef _MSC_VER
  388. #pragma warning (push)
  389. #pragma warning (disable : 4100 4201 4514 4312 4995)
  390. #endif
  391. #define _WIN32_WINNT 0x0500
  392. #define _UNICODE 1
  393. #define UNICODE 1
  394. #ifndef _WIN32_IE
  395. #define _WIN32_IE 0x0400
  396. #endif
  397. #include <windows.h>
  398. #include <windowsx.h>
  399. #include <commdlg.h>
  400. #include <shellapi.h>
  401. #include <mmsystem.h>
  402. #include <vfw.h>
  403. #include <tchar.h>
  404. #include <stddef.h>
  405. #include <ctime>
  406. #include <wininet.h>
  407. #include <nb30.h>
  408. #include <iphlpapi.h>
  409. #include <mapi.h>
  410. #include <float.h>
  411. #include <process.h>
  412. #include <Exdisp.h>
  413. #include <exdispid.h>
  414. #include <shlobj.h>
  415. #if ! JUCE_MINGW
  416. #include <crtdbg.h>
  417. #include <comutil.h>
  418. #endif
  419. #if JUCE_OPENGL
  420. #include <gl/gl.h>
  421. #endif
  422. #undef PACKED
  423. #if JUCE_ASIO
  424. /*
  425. This is very frustrating - we only need to use a handful of definitions from
  426. a couple of the header files in Steinberg's ASIO SDK, and it'd be easy to copy
  427. about 30 lines of code into this cpp file to create a fully stand-alone ASIO
  428. implementation...
  429. ..unfortunately that would break Steinberg's license agreement for use of
  430. their SDK, so I'm not allowed to do this.
  431. This means that anyone who wants to use JUCE's ASIO abilities will have to:
  432. 1) Agree to Steinberg's licensing terms and download the ASIO SDK
  433. (see www.steinberg.net/Steinberg/Developers.asp).
  434. 2) Rebuild the whole of JUCE, setting the global definition JUCE_ASIO (you
  435. can un-comment the "#define JUCE_ASIO" line in juce_Config.h
  436. if you prefer). Make sure that your header search path will find the
  437. iasiodrv.h file that comes with the SDK. (Only about 2-3 of the SDK header
  438. files are actually needed - so to simplify things, you could just copy
  439. these into your JUCE directory).
  440. If you're compiling and you get an error here because you don't have the
  441. ASIO SDK installed, you can disable ASIO support by commenting-out the
  442. "#define JUCE_ASIO" line in juce_Config.h, and rebuild your Juce library.
  443. */
  444. #include "iasiodrv.h"
  445. #endif
  446. #if JUCE_USE_CDBURNER
  447. /* You'll need the Platform SDK for these headers - if you don't have it and don't
  448. need to use CD-burning, then you might just want to disable the JUCE_USE_CDBURNER
  449. flag in juce_Config.h to avoid these includes.
  450. */
  451. #include <imapi.h>
  452. #include <imapierror.h>
  453. #endif
  454. #if JUCE_USE_CAMERA
  455. /* If you're using the camera classes, you'll need access to a few DirectShow headers.
  456. These files are provided in the normal Windows SDK, but some Microsoft plonker
  457. didn't realise that qedit.h doesn't actually compile without the rest of the DirectShow SDK..
  458. Microsoft's suggested fix for this is to hack their qedit.h file! See:
  459. http://social.msdn.microsoft.com/Forums/en-US/windowssdk/thread/ed097d2c-3d68-4f48-8448-277eaaf68252
  460. .. which is a bit of a bodge, but a lot less hassle than installing the full DShow SDK.
  461. An alternative workaround is to create a dummy dxtrans.h file and put it in your include path.
  462. The dummy file just needs to contain the following content:
  463. #define __IDxtCompositor_INTERFACE_DEFINED__
  464. #define __IDxtAlphaSetter_INTERFACE_DEFINED__
  465. #define __IDxtJpeg_INTERFACE_DEFINED__
  466. #define __IDxtKey_INTERFACE_DEFINED__
  467. ..and that should be enough to convince qedit.h that you have the SDK!
  468. */
  469. #include <dshow.h>
  470. #include <qedit.h>
  471. #include <dshowasf.h>
  472. #endif
  473. #if JUCE_WASAPI
  474. #include <MMReg.h>
  475. #include <mmdeviceapi.h>
  476. #include <Audioclient.h>
  477. #include <Avrt.h>
  478. #include <functiondiscoverykeys.h>
  479. #endif
  480. #if JUCE_QUICKTIME
  481. /* If you've got an include error here, you probably need to install the QuickTime SDK and
  482. add its header directory to your include path.
  483. Alternatively, if you don't need any QuickTime services, just turn off the JUCE_QUICKTIME
  484. flag in juce_Config.h
  485. */
  486. #include <Movies.h>
  487. #include <QTML.h>
  488. #include <QuickTimeComponents.h>
  489. #include <MediaHandlers.h>
  490. #include <ImageCodec.h>
  491. /* If you've got QuickTime 7 installed, then these COM objects should be found in
  492. the "\Program Files\Quicktime" directory. You'll need to add this directory to
  493. your include search path to make these import statements work.
  494. */
  495. #import <QTOLibrary.dll>
  496. #import <QTOControl.dll>
  497. #endif
  498. #ifdef _MSC_VER
  499. #pragma warning (pop)
  500. #endif
  501. /** A simple COM smart pointer.
  502. Avoids having to include ATL just to get one of these.
  503. */
  504. template <class ComClass>
  505. class ComSmartPtr
  506. {
  507. public:
  508. ComSmartPtr() throw() : p (0) {}
  509. ComSmartPtr (ComClass* const p_) : p (p_) { if (p_ != 0) p_->AddRef(); }
  510. ComSmartPtr (const ComSmartPtr<ComClass>& p_) : p (p_.p) { if (p != 0) p->AddRef(); }
  511. ~ComSmartPtr() { if (p != 0) p->Release(); }
  512. operator ComClass*() const throw() { return p; }
  513. ComClass& operator*() const throw() { return *p; }
  514. ComClass** operator&() throw() { return &p; }
  515. ComClass* operator->() const throw() { return p; }
  516. ComClass* operator= (ComClass* const newP)
  517. {
  518. if (newP != 0) newP->AddRef();
  519. if (p != 0) p->Release();
  520. p = newP;
  521. return newP;
  522. }
  523. ComClass* operator= (const ComSmartPtr<ComClass>& newP) { return operator= (newP.p); }
  524. HRESULT CoCreateInstance (REFCLSID rclsid, DWORD dwClsContext = CLSCTX_INPROC_SERVER)
  525. {
  526. #ifndef __MINGW32__
  527. operator= (0);
  528. return ::CoCreateInstance (rclsid, 0, dwClsContext, __uuidof (ComClass), (void**) &p);
  529. #else
  530. return S_FALSE;
  531. #endif
  532. }
  533. private:
  534. ComClass* p;
  535. };
  536. /** Handy base class for writing COM objects, providing ref-counting and a basic QueryInterface method.
  537. */
  538. template <class ComClass>
  539. class ComBaseClassHelper : public ComClass
  540. {
  541. public:
  542. ComBaseClassHelper() : refCount (1) {}
  543. virtual ~ComBaseClassHelper() {}
  544. HRESULT __stdcall QueryInterface (REFIID refId, void __RPC_FAR* __RPC_FAR* result)
  545. {
  546. if (refId == __uuidof (ComClass)) { AddRef(); *result = dynamic_cast <ComClass*> (this); return S_OK; }
  547. if (refId == IID_IUnknown) { AddRef(); *result = dynamic_cast <IUnknown*> (this); return S_OK; }
  548. *result = 0;
  549. return E_NOINTERFACE;
  550. }
  551. ULONG __stdcall AddRef() { return ++refCount; }
  552. ULONG __stdcall Release() { const int r = --refCount; if (r == 0) delete this; return r; }
  553. protected:
  554. int refCount;
  555. };
  556. #endif // __JUCE_WIN32_NATIVEINCLUDES_JUCEHEADER__
  557. /*** End of inlined file: juce_win32_NativeIncludes.h ***/
  558. #elif JUCE_LINUX
  559. /*** Start of inlined file: juce_linux_NativeIncludes.h ***/
  560. #ifndef __JUCE_LINUX_NATIVEINCLUDES_JUCEHEADER__
  561. #define __JUCE_LINUX_NATIVEINCLUDES_JUCEHEADER__
  562. /*
  563. This file wraps together all the linux-specific headers, so
  564. that we can include them all just once, and compile all our
  565. platform-specific stuff in one big lump, keeping it out of the
  566. way of the rest of the codebase.
  567. */
  568. #include <sched.h>
  569. #include <pthread.h>
  570. #include <sys/time.h>
  571. #include <errno.h>
  572. #include <sys/stat.h>
  573. #include <sys/dir.h>
  574. #include <sys/ptrace.h>
  575. #include <sys/vfs.h>
  576. #include <sys/wait.h>
  577. #include <fnmatch.h>
  578. #include <utime.h>
  579. #include <pwd.h>
  580. #include <fcntl.h>
  581. #include <dlfcn.h>
  582. #include <netdb.h>
  583. #include <arpa/inet.h>
  584. #include <netinet/in.h>
  585. #include <sys/types.h>
  586. #include <sys/ioctl.h>
  587. #include <sys/socket.h>
  588. #include <linux/if.h>
  589. #include <sys/sysinfo.h>
  590. #include <sys/file.h>
  591. #include <signal.h>
  592. /* Got a build error here? You'll need to install the freetype library...
  593. The name of the package to install is "libfreetype6-dev".
  594. */
  595. #include <ft2build.h>
  596. #include FT_FREETYPE_H
  597. #include <X11/Xlib.h>
  598. #include <X11/Xatom.h>
  599. #include <X11/Xresource.h>
  600. #include <X11/Xutil.h>
  601. #include <X11/Xmd.h>
  602. #include <X11/keysym.h>
  603. #include <X11/cursorfont.h>
  604. #if JUCE_USE_XINERAMA
  605. /* If you're trying to use Xinerama, you'll need to install the "libxinerama-dev" package.. */
  606. #include <X11/extensions/Xinerama.h>
  607. #endif
  608. #if JUCE_USE_XSHM
  609. #include <X11/extensions/XShm.h>
  610. #include <sys/shm.h>
  611. #include <sys/ipc.h>
  612. #endif
  613. #if JUCE_USE_XRENDER
  614. // If you're missing these headers, try installing the libxrender-dev and libxcomposite-dev
  615. #include <X11/extensions/Xrender.h>
  616. #include <X11/extensions/Xcomposite.h>
  617. #endif
  618. #if JUCE_USE_XCURSOR
  619. // If you're missing this header, try installing the libxcursor-dev package
  620. #include <X11/Xcursor/Xcursor.h>
  621. #endif
  622. #if JUCE_OPENGL
  623. /* Got an include error here?
  624. If you want to install OpenGL support, the packages to get are "mesa-common-dev"
  625. and "freeglut3-dev".
  626. Alternatively, you can turn off the JUCE_OPENGL flag in juce_Config.h if you
  627. want to disable it.
  628. */
  629. #include <GL/glx.h>
  630. #endif
  631. #undef KeyPress
  632. #if JUCE_ALSA
  633. /* Got an include error here? If so, you've either not got ALSA installed, or you've
  634. not got your paths set up correctly to find its header files.
  635. The package you need to install to get ASLA support is "libasound2-dev".
  636. If you don't have the ALSA library and don't want to build Juce with audio support,
  637. just disable the JUCE_ALSA flag in juce_Config.h
  638. */
  639. #include <alsa/asoundlib.h>
  640. #endif
  641. #if JUCE_JACK
  642. /* Got an include error here? If so, you've either not got jack-audio-connection-kit
  643. installed, or you've not got your paths set up correctly to find its header files.
  644. The package you need to install to get JACK support is "libjack-dev".
  645. If you don't have the jack-audio-connection-kit library and don't want to build
  646. Juce with low latency audio support, just disable the JUCE_JACK flag in juce_Config.h
  647. */
  648. #include <jack/jack.h>
  649. //#include <jack/transport.h>
  650. #endif
  651. #undef SIZEOF
  652. #endif // __JUCE_LINUX_NATIVEINCLUDES_JUCEHEADER__
  653. /*** End of inlined file: juce_linux_NativeIncludes.h ***/
  654. #elif JUCE_MAC || JUCE_IPHONE
  655. /*** Start of inlined file: juce_mac_NativeIncludes.h ***/
  656. #ifndef __JUCE_MAC_NATIVEINCLUDES_JUCEHEADER__
  657. #define __JUCE_MAC_NATIVEINCLUDES_JUCEHEADER__
  658. /*
  659. This file wraps together all the mac-specific code, so that
  660. we can include all the native headers just once, and compile all our
  661. platform-specific stuff in one big lump, keeping it out of the way of
  662. the rest of the codebase.
  663. */
  664. #define USE_COREGRAPHICS_RENDERING 1
  665. #if JUCE_IPHONE
  666. #import <Foundation/Foundation.h>
  667. #import <UIKit/UIKit.h>
  668. #import <AudioToolbox/AudioToolbox.h>
  669. #import <AVFoundation/AVFoundation.h>
  670. #import <CoreData/CoreData.h>
  671. #import <MobileCoreServices/MobileCoreServices.h>
  672. #import <QuartzCore/QuartzCore.h>
  673. #include <sys/fcntl.h>
  674. #if JUCE_OPENGL
  675. #include <OpenGLES/ES1/gl.h>
  676. #include <OpenGLES/ES1/glext.h>
  677. #endif
  678. #else
  679. #import <Cocoa/Cocoa.h>
  680. #import <CoreAudio/HostTime.h>
  681. #import <CoreAudio/AudioHardware.h>
  682. #import <CoreMIDI/MIDIServices.h>
  683. #import <QTKit/QTKit.h>
  684. #import <WebKit/WebKit.h>
  685. #import <DiscRecording/DiscRecording.h>
  686. #import <IOKit/IOKitLib.h>
  687. #import <IOKit/IOCFPlugIn.h>
  688. #import <IOKit/hid/IOHIDLib.h>
  689. #import <IOKit/hid/IOHIDKeys.h>
  690. #import <IOKit/pwr_mgt/IOPMLib.h>
  691. #include <Carbon/Carbon.h>
  692. #include <sys/dir.h>
  693. #endif
  694. #include <sys/socket.h>
  695. #include <sys/sysctl.h>
  696. #include <sys/stat.h>
  697. #include <sys/param.h>
  698. #include <sys/mount.h>
  699. #include <fnmatch.h>
  700. #include <utime.h>
  701. #include <dlfcn.h>
  702. #include <ifaddrs.h>
  703. #include <net/if_dl.h>
  704. #include <mach/mach_time.h>
  705. #if MACOS_10_4_OR_EARLIER
  706. #include <GLUT/glut.h>
  707. #endif
  708. #if ! CGFLOAT_DEFINED
  709. #define CGFloat float
  710. #endif
  711. #endif // __JUCE_MAC_NATIVEINCLUDES_JUCEHEADER__
  712. /*** End of inlined file: juce_mac_NativeIncludes.h ***/
  713. #else
  714. #error "Unknown platform!"
  715. #endif
  716. #endif
  717. //==============================================================================
  718. #define DONT_SET_USING_JUCE_NAMESPACE 1
  719. #undef max
  720. #undef min
  721. #define NO_DUMMY_DECL
  722. #if JUCE_BUILD_NATIVE
  723. #include "juce_amalgamated.h" // FORCE_AMALGAMATOR_INCLUDE
  724. #endif
  725. #if (defined(_MSC_VER) && (_MSC_VER <= 1200))
  726. #pragma warning (disable: 4309 4305)
  727. #endif
  728. #if JUCE_MAC && JUCE_32BIT && JUCE_SUPPORT_CARBON && JUCE_BUILD_NATIVE && ! JUCE_ONLY_BUILD_CORE_LIBRARY
  729. BEGIN_JUCE_NAMESPACE
  730. /*** Start of inlined file: juce_mac_CarbonViewWrapperComponent.h ***/
  731. #ifndef __JUCE_MAC_CARBONVIEWWRAPPERCOMPONENT_JUCEHEADER__
  732. #define __JUCE_MAC_CARBONVIEWWRAPPERCOMPONENT_JUCEHEADER__
  733. /**
  734. Creates a floating carbon window that can be used to hold a carbon UI.
  735. This is a handy class that's designed to be inlined where needed, e.g.
  736. in the audio plugin hosting code.
  737. */
  738. class CarbonViewWrapperComponent : public Component,
  739. public ComponentMovementWatcher,
  740. public Timer
  741. {
  742. public:
  743. CarbonViewWrapperComponent()
  744. : ComponentMovementWatcher (this),
  745. wrapperWindow (0),
  746. embeddedView (0),
  747. recursiveResize (false)
  748. {
  749. }
  750. virtual ~CarbonViewWrapperComponent()
  751. {
  752. jassert (embeddedView == 0); // must call deleteWindow() in the subclass's destructor!
  753. }
  754. virtual HIViewRef attachView (WindowRef windowRef, HIViewRef rootView) = 0;
  755. virtual void removeView (HIViewRef embeddedView) = 0;
  756. virtual void mouseDown (int x, int y) {}
  757. virtual void paint() {}
  758. virtual bool getEmbeddedViewSize (int& w, int& h)
  759. {
  760. if (embeddedView == 0)
  761. return false;
  762. HIRect bounds;
  763. HIViewGetBounds (embeddedView, &bounds);
  764. w = jmax (1, roundToInt (bounds.size.width));
  765. h = jmax (1, roundToInt (bounds.size.height));
  766. return true;
  767. }
  768. void createWindow()
  769. {
  770. if (wrapperWindow == 0)
  771. {
  772. Rect r;
  773. r.left = getScreenX();
  774. r.top = getScreenY();
  775. r.right = r.left + getWidth();
  776. r.bottom = r.top + getHeight();
  777. CreateNewWindow (kDocumentWindowClass,
  778. (WindowAttributes) (kWindowStandardHandlerAttribute | kWindowCompositingAttribute
  779. | kWindowNoShadowAttribute | kWindowNoTitleBarAttribute),
  780. &r, &wrapperWindow);
  781. jassert (wrapperWindow != 0);
  782. if (wrapperWindow == 0)
  783. return;
  784. NSWindow* carbonWindow = [[NSWindow alloc] initWithWindowRef: wrapperWindow];
  785. NSWindow* ownerWindow = [((NSView*) getWindowHandle()) window];
  786. [ownerWindow addChildWindow: carbonWindow
  787. ordered: NSWindowAbove];
  788. embeddedView = attachView (wrapperWindow, HIViewGetRoot (wrapperWindow));
  789. EventTypeSpec windowEventTypes[] = { { kEventClassWindow, kEventWindowGetClickActivation },
  790. { kEventClassWindow, kEventWindowHandleDeactivate } };
  791. EventHandlerUPP upp = NewEventHandlerUPP (carbonEventCallback);
  792. InstallWindowEventHandler (wrapperWindow, upp,
  793. sizeof (windowEventTypes) / sizeof (EventTypeSpec),
  794. windowEventTypes, this, &eventHandlerRef);
  795. setOurSizeToEmbeddedViewSize();
  796. setEmbeddedWindowToOurSize();
  797. creationTime = Time::getCurrentTime();
  798. }
  799. }
  800. void deleteWindow()
  801. {
  802. removeView (embeddedView);
  803. embeddedView = 0;
  804. if (wrapperWindow != 0)
  805. {
  806. RemoveEventHandler (eventHandlerRef);
  807. DisposeWindow (wrapperWindow);
  808. wrapperWindow = 0;
  809. }
  810. }
  811. void setOurSizeToEmbeddedViewSize()
  812. {
  813. int w, h;
  814. if (getEmbeddedViewSize (w, h))
  815. {
  816. if (w != getWidth() || h != getHeight())
  817. {
  818. startTimer (50);
  819. setSize (w, h);
  820. if (getParentComponent() != 0)
  821. getParentComponent()->setSize (w, h);
  822. }
  823. else
  824. {
  825. startTimer (jlimit (50, 500, getTimerInterval() + 20));
  826. }
  827. }
  828. else
  829. {
  830. stopTimer();
  831. }
  832. }
  833. void setEmbeddedWindowToOurSize()
  834. {
  835. if (! recursiveResize)
  836. {
  837. recursiveResize = true;
  838. if (embeddedView != 0)
  839. {
  840. HIRect r;
  841. r.origin.x = 0;
  842. r.origin.y = 0;
  843. r.size.width = (float) getWidth();
  844. r.size.height = (float) getHeight();
  845. HIViewSetFrame (embeddedView, &r);
  846. }
  847. if (wrapperWindow != 0)
  848. {
  849. Rect wr;
  850. wr.left = getScreenX();
  851. wr.top = getScreenY();
  852. wr.right = wr.left + getWidth();
  853. wr.bottom = wr.top + getHeight();
  854. SetWindowBounds (wrapperWindow, kWindowContentRgn, &wr);
  855. ShowWindow (wrapperWindow);
  856. }
  857. recursiveResize = false;
  858. }
  859. }
  860. void componentMovedOrResized (bool /*wasMoved*/, bool /*wasResized*/)
  861. {
  862. setEmbeddedWindowToOurSize();
  863. }
  864. void componentPeerChanged()
  865. {
  866. deleteWindow();
  867. createWindow();
  868. }
  869. void componentVisibilityChanged (Component&)
  870. {
  871. if (isShowing())
  872. createWindow();
  873. else
  874. deleteWindow();
  875. setEmbeddedWindowToOurSize();
  876. }
  877. static void recursiveHIViewRepaint (HIViewRef view)
  878. {
  879. HIViewSetNeedsDisplay (view, true);
  880. HIViewRef child = HIViewGetFirstSubview (view);
  881. while (child != 0)
  882. {
  883. recursiveHIViewRepaint (child);
  884. child = HIViewGetNextView (child);
  885. }
  886. }
  887. void timerCallback()
  888. {
  889. setOurSizeToEmbeddedViewSize();
  890. // To avoid strange overpainting problems when the UI is first opened, we'll
  891. // repaint it a few times during the first second that it's on-screen..
  892. if ((Time::getCurrentTime() - creationTime).inMilliseconds() < 1000)
  893. recursiveHIViewRepaint (HIViewGetRoot (wrapperWindow));
  894. }
  895. OSStatus carbonEventHandler (EventHandlerCallRef nextHandlerRef,
  896. EventRef event)
  897. {
  898. switch (GetEventKind (event))
  899. {
  900. case kEventWindowHandleDeactivate:
  901. ActivateWindow (wrapperWindow, TRUE);
  902. break;
  903. case kEventWindowGetClickActivation:
  904. {
  905. getTopLevelComponent()->toFront (false);
  906. ClickActivationResult howToHandleClick = kActivateAndHandleClick;
  907. SetEventParameter (event, kEventParamClickActivation, typeClickActivationResult,
  908. sizeof (ClickActivationResult), &howToHandleClick);
  909. HIViewSetNeedsDisplay (embeddedView, true);
  910. }
  911. break;
  912. }
  913. return noErr;
  914. }
  915. static pascal OSStatus carbonEventCallback (EventHandlerCallRef nextHandlerRef,
  916. EventRef event, void* userData)
  917. {
  918. return ((CarbonViewWrapperComponent*) userData)->carbonEventHandler (nextHandlerRef, event);
  919. }
  920. protected:
  921. WindowRef wrapperWindow;
  922. HIViewRef embeddedView;
  923. bool recursiveResize;
  924. Time creationTime;
  925. EventHandlerRef eventHandlerRef;
  926. };
  927. #endif // __JUCE_MAC_CARBONVIEWWRAPPERCOMPONENT_JUCEHEADER__
  928. /*** End of inlined file: juce_mac_CarbonViewWrapperComponent.h ***/
  929. END_JUCE_NAMESPACE
  930. #endif
  931. #define JUCE_AMALGAMATED_TEMPLATE 1
  932. //==============================================================================
  933. #if JUCE_BUILD_CORE
  934. /*** Start of inlined file: juce_FileLogger.cpp ***/
  935. BEGIN_JUCE_NAMESPACE
  936. FileLogger::FileLogger (const File& logFile_,
  937. const String& welcomeMessage,
  938. const int maxInitialFileSizeBytes)
  939. : logFile (logFile_)
  940. {
  941. if (maxInitialFileSizeBytes >= 0)
  942. trimFileSize (maxInitialFileSizeBytes);
  943. if (! logFile_.exists())
  944. {
  945. // do this so that the parent directories get created..
  946. logFile_.create();
  947. }
  948. logStream = logFile_.createOutputStream (256);
  949. jassert (logStream != 0);
  950. String welcome;
  951. welcome << "\r\n**********************************************************\r\n"
  952. << welcomeMessage
  953. << "\r\nLog started: " << Time::getCurrentTime().toString (true, true)
  954. << "\r\n";
  955. logMessage (welcome);
  956. }
  957. FileLogger::~FileLogger()
  958. {
  959. }
  960. void FileLogger::logMessage (const String& message)
  961. {
  962. if (logStream != 0)
  963. {
  964. DBG (message);
  965. const ScopedLock sl (logLock);
  966. (*logStream) << message << "\r\n";
  967. logStream->flush();
  968. }
  969. }
  970. void FileLogger::trimFileSize (int maxFileSizeBytes) const
  971. {
  972. if (maxFileSizeBytes <= 0)
  973. {
  974. logFile.deleteFile();
  975. }
  976. else
  977. {
  978. const int64 fileSize = logFile.getSize();
  979. if (fileSize > maxFileSizeBytes)
  980. {
  981. ScopedPointer <FileInputStream> in (logFile.createInputStream());
  982. jassert (in != 0);
  983. if (in != 0)
  984. {
  985. in->setPosition (fileSize - maxFileSizeBytes);
  986. String content;
  987. {
  988. MemoryBlock contentToSave;
  989. contentToSave.setSize (maxFileSizeBytes + 4);
  990. contentToSave.fillWith (0);
  991. in->read (contentToSave.getData(), maxFileSizeBytes);
  992. in = 0;
  993. content = contentToSave.toString();
  994. }
  995. int newStart = 0;
  996. while (newStart < fileSize
  997. && content[newStart] != '\n'
  998. && content[newStart] != '\r')
  999. ++newStart;
  1000. logFile.deleteFile();
  1001. logFile.appendText (content.substring (newStart), false, false);
  1002. }
  1003. }
  1004. }
  1005. }
  1006. FileLogger* FileLogger::createDefaultAppLogger (const String& logFileSubDirectoryName,
  1007. const String& logFileName,
  1008. const String& welcomeMessage,
  1009. const int maxInitialFileSizeBytes)
  1010. {
  1011. #if JUCE_MAC
  1012. File logFile ("~/Library/Logs");
  1013. logFile = logFile.getChildFile (logFileSubDirectoryName)
  1014. .getChildFile (logFileName);
  1015. #else
  1016. File logFile (File::getSpecialLocation (File::userApplicationDataDirectory));
  1017. if (logFile.isDirectory())
  1018. {
  1019. logFile = logFile.getChildFile (logFileSubDirectoryName)
  1020. .getChildFile (logFileName);
  1021. }
  1022. #endif
  1023. return new FileLogger (logFile, welcomeMessage, maxInitialFileSizeBytes);
  1024. }
  1025. END_JUCE_NAMESPACE
  1026. /*** End of inlined file: juce_FileLogger.cpp ***/
  1027. /*** Start of inlined file: juce_Logger.cpp ***/
  1028. BEGIN_JUCE_NAMESPACE
  1029. Logger::Logger()
  1030. {
  1031. }
  1032. Logger::~Logger()
  1033. {
  1034. }
  1035. static Logger* currentLogger = 0;
  1036. void Logger::setCurrentLogger (Logger* const newLogger,
  1037. const bool deleteOldLogger)
  1038. {
  1039. Logger* const oldLogger = currentLogger;
  1040. currentLogger = newLogger;
  1041. if (deleteOldLogger)
  1042. delete oldLogger;
  1043. }
  1044. void Logger::writeToLog (const String& message)
  1045. {
  1046. if (currentLogger != 0)
  1047. currentLogger->logMessage (message);
  1048. else
  1049. outputDebugString (message);
  1050. }
  1051. #if JUCE_LOG_ASSERTIONS
  1052. void JUCE_API juce_LogAssertion (const char* filename, const int lineNum) throw()
  1053. {
  1054. String m ("JUCE Assertion failure in ");
  1055. m << filename << ", line " << lineNum;
  1056. Logger::writeToLog (m);
  1057. }
  1058. #endif
  1059. END_JUCE_NAMESPACE
  1060. /*** End of inlined file: juce_Logger.cpp ***/
  1061. /*** Start of inlined file: juce_Random.cpp ***/
  1062. BEGIN_JUCE_NAMESPACE
  1063. Random::Random (const int64 seedValue) throw()
  1064. : seed (seedValue)
  1065. {
  1066. }
  1067. Random::~Random() throw()
  1068. {
  1069. }
  1070. void Random::setSeed (const int64 newSeed) throw()
  1071. {
  1072. seed = newSeed;
  1073. }
  1074. void Random::combineSeed (const int64 seedValue) throw()
  1075. {
  1076. seed ^= nextInt64() ^ seedValue;
  1077. }
  1078. void Random::setSeedRandomly()
  1079. {
  1080. combineSeed ((int64) (pointer_sized_int) this);
  1081. combineSeed (Time::getMillisecondCounter());
  1082. combineSeed (Time::getHighResolutionTicks());
  1083. combineSeed (Time::getHighResolutionTicksPerSecond());
  1084. combineSeed (Time::currentTimeMillis());
  1085. }
  1086. int Random::nextInt() throw()
  1087. {
  1088. seed = (seed * literal64bit (0x5deece66d) + 11) & literal64bit (0xffffffffffff);
  1089. return (int) (seed >> 16);
  1090. }
  1091. int Random::nextInt (const int maxValue) throw()
  1092. {
  1093. jassert (maxValue > 0);
  1094. return (nextInt() & 0x7fffffff) % maxValue;
  1095. }
  1096. int64 Random::nextInt64() throw()
  1097. {
  1098. return (((int64) nextInt()) << 32) | (int64) (uint64) (uint32) nextInt();
  1099. }
  1100. bool Random::nextBool() throw()
  1101. {
  1102. return (nextInt() & 0x80000000) != 0;
  1103. }
  1104. float Random::nextFloat() throw()
  1105. {
  1106. return static_cast <uint32> (nextInt()) / (float) 0xffffffff;
  1107. }
  1108. double Random::nextDouble() throw()
  1109. {
  1110. return static_cast <uint32> (nextInt()) / (double) 0xffffffff;
  1111. }
  1112. const BigInteger Random::nextLargeNumber (const BigInteger& maximumValue)
  1113. {
  1114. BigInteger n;
  1115. do
  1116. {
  1117. fillBitsRandomly (n, 0, maximumValue.getHighestBit() + 1);
  1118. }
  1119. while (n >= maximumValue);
  1120. return n;
  1121. }
  1122. void Random::fillBitsRandomly (BigInteger& arrayToChange, int startBit, int numBits)
  1123. {
  1124. arrayToChange.setBit (startBit + numBits - 1, true); // to force the array to pre-allocate space
  1125. while ((startBit & 31) != 0 && numBits > 0)
  1126. {
  1127. arrayToChange.setBit (startBit++, nextBool());
  1128. --numBits;
  1129. }
  1130. while (numBits >= 32)
  1131. {
  1132. arrayToChange.setBitRangeAsInt (startBit, 32, (unsigned int) nextInt());
  1133. startBit += 32;
  1134. numBits -= 32;
  1135. }
  1136. while (--numBits >= 0)
  1137. arrayToChange.setBit (startBit + numBits, nextBool());
  1138. }
  1139. Random& Random::getSystemRandom() throw()
  1140. {
  1141. static Random sysRand (1);
  1142. return sysRand;
  1143. }
  1144. END_JUCE_NAMESPACE
  1145. /*** End of inlined file: juce_Random.cpp ***/
  1146. /*** Start of inlined file: juce_RelativeTime.cpp ***/
  1147. BEGIN_JUCE_NAMESPACE
  1148. RelativeTime::RelativeTime (const double seconds_) throw()
  1149. : seconds (seconds_)
  1150. {
  1151. }
  1152. RelativeTime::RelativeTime (const RelativeTime& other) throw()
  1153. : seconds (other.seconds)
  1154. {
  1155. }
  1156. RelativeTime::~RelativeTime() throw()
  1157. {
  1158. }
  1159. const RelativeTime RelativeTime::milliseconds (const int milliseconds) throw()
  1160. {
  1161. return RelativeTime (milliseconds * 0.001);
  1162. }
  1163. const RelativeTime RelativeTime::milliseconds (const int64 milliseconds) throw()
  1164. {
  1165. return RelativeTime (milliseconds * 0.001);
  1166. }
  1167. const RelativeTime RelativeTime::minutes (const double numberOfMinutes) throw()
  1168. {
  1169. return RelativeTime (numberOfMinutes * 60.0);
  1170. }
  1171. const RelativeTime RelativeTime::hours (const double numberOfHours) throw()
  1172. {
  1173. return RelativeTime (numberOfHours * (60.0 * 60.0));
  1174. }
  1175. const RelativeTime RelativeTime::days (const double numberOfDays) throw()
  1176. {
  1177. return RelativeTime (numberOfDays * (60.0 * 60.0 * 24.0));
  1178. }
  1179. const RelativeTime RelativeTime::weeks (const double numberOfWeeks) throw()
  1180. {
  1181. return RelativeTime (numberOfWeeks * (60.0 * 60.0 * 24.0 * 7.0));
  1182. }
  1183. int64 RelativeTime::inMilliseconds() const throw()
  1184. {
  1185. return (int64)(seconds * 1000.0);
  1186. }
  1187. double RelativeTime::inMinutes() const throw()
  1188. {
  1189. return seconds / 60.0;
  1190. }
  1191. double RelativeTime::inHours() const throw()
  1192. {
  1193. return seconds / (60.0 * 60.0);
  1194. }
  1195. double RelativeTime::inDays() const throw()
  1196. {
  1197. return seconds / (60.0 * 60.0 * 24.0);
  1198. }
  1199. double RelativeTime::inWeeks() const throw()
  1200. {
  1201. return seconds / (60.0 * 60.0 * 24.0 * 7.0);
  1202. }
  1203. const String RelativeTime::getDescription (const String& returnValueForZeroTime) const throw()
  1204. {
  1205. if (seconds < 0.001 && seconds > -0.001)
  1206. return returnValueForZeroTime;
  1207. String result;
  1208. if (seconds < 0)
  1209. result = "-";
  1210. int fieldsShown = 0;
  1211. int n = abs ((int) inWeeks());
  1212. if (n > 0)
  1213. {
  1214. result << n << ((n == 1) ? TRANS(" week ")
  1215. : TRANS(" weeks "));
  1216. ++fieldsShown;
  1217. }
  1218. n = abs ((int) inDays()) % 7;
  1219. if (n > 0)
  1220. {
  1221. result << n << ((n == 1) ? TRANS(" day ")
  1222. : TRANS(" days "));
  1223. ++fieldsShown;
  1224. }
  1225. if (fieldsShown < 2)
  1226. {
  1227. n = abs ((int) inHours()) % 24;
  1228. if (n > 0)
  1229. {
  1230. result << n << ((n == 1) ? TRANS(" hr ")
  1231. : TRANS(" hrs "));
  1232. ++fieldsShown;
  1233. }
  1234. if (fieldsShown < 2)
  1235. {
  1236. n = abs ((int) inMinutes()) % 60;
  1237. if (n > 0)
  1238. {
  1239. result << n << ((n == 1) ? TRANS(" min ")
  1240. : TRANS(" mins "));
  1241. ++fieldsShown;
  1242. }
  1243. if (fieldsShown < 2)
  1244. {
  1245. n = abs ((int) inSeconds()) % 60;
  1246. if (n > 0)
  1247. {
  1248. result << n << ((n == 1) ? TRANS(" sec ")
  1249. : TRANS(" secs "));
  1250. ++fieldsShown;
  1251. }
  1252. if (fieldsShown < 1)
  1253. {
  1254. n = abs ((int) inMilliseconds()) % 1000;
  1255. if (n > 0)
  1256. {
  1257. result << n << TRANS(" ms");
  1258. ++fieldsShown;
  1259. }
  1260. }
  1261. }
  1262. }
  1263. }
  1264. return result.trimEnd();
  1265. }
  1266. RelativeTime& RelativeTime::operator= (const RelativeTime& other) throw()
  1267. {
  1268. seconds = other.seconds;
  1269. return *this;
  1270. }
  1271. bool RelativeTime::operator== (const RelativeTime& other) const throw()
  1272. {
  1273. return seconds == other.seconds;
  1274. }
  1275. bool RelativeTime::operator!= (const RelativeTime& other) const throw()
  1276. {
  1277. return seconds != other.seconds;
  1278. }
  1279. bool RelativeTime::operator> (const RelativeTime& other) const throw()
  1280. {
  1281. return seconds > other.seconds;
  1282. }
  1283. bool RelativeTime::operator< (const RelativeTime& other) const throw()
  1284. {
  1285. return seconds < other.seconds;
  1286. }
  1287. bool RelativeTime::operator>= (const RelativeTime& other) const throw()
  1288. {
  1289. return seconds >= other.seconds;
  1290. }
  1291. bool RelativeTime::operator<= (const RelativeTime& other) const throw()
  1292. {
  1293. return seconds <= other.seconds;
  1294. }
  1295. const RelativeTime RelativeTime::operator+ (const RelativeTime& timeToAdd) const throw()
  1296. {
  1297. return RelativeTime (seconds + timeToAdd.seconds);
  1298. }
  1299. const RelativeTime RelativeTime::operator- (const RelativeTime& timeToSubtract) const throw()
  1300. {
  1301. return RelativeTime (seconds - timeToSubtract.seconds);
  1302. }
  1303. const RelativeTime RelativeTime::operator+ (const double secondsToAdd) const throw()
  1304. {
  1305. return RelativeTime (seconds + secondsToAdd);
  1306. }
  1307. const RelativeTime RelativeTime::operator- (const double secondsToSubtract) const throw()
  1308. {
  1309. return RelativeTime (seconds - secondsToSubtract);
  1310. }
  1311. const RelativeTime& RelativeTime::operator+= (const RelativeTime& timeToAdd) throw()
  1312. {
  1313. seconds += timeToAdd.seconds;
  1314. return *this;
  1315. }
  1316. const RelativeTime& RelativeTime::operator-= (const RelativeTime& timeToSubtract) throw()
  1317. {
  1318. seconds -= timeToSubtract.seconds;
  1319. return *this;
  1320. }
  1321. const RelativeTime& RelativeTime::operator+= (const double secondsToAdd) throw()
  1322. {
  1323. seconds += secondsToAdd;
  1324. return *this;
  1325. }
  1326. const RelativeTime& RelativeTime::operator-= (const double secondsToSubtract) throw()
  1327. {
  1328. seconds -= secondsToSubtract;
  1329. return *this;
  1330. }
  1331. END_JUCE_NAMESPACE
  1332. /*** End of inlined file: juce_RelativeTime.cpp ***/
  1333. /*** Start of inlined file: juce_SystemStats.cpp ***/
  1334. BEGIN_JUCE_NAMESPACE
  1335. const String SystemStats::getJUCEVersion() throw()
  1336. {
  1337. return "JUCE v" + String (JUCE_MAJOR_VERSION)
  1338. + "." + String (JUCE_MINOR_VERSION)
  1339. + "." + String (JUCE_BUILDNUMBER);
  1340. }
  1341. const StringArray SystemStats::getMACAddressStrings()
  1342. {
  1343. int64 macAddresses [16];
  1344. const int numAddresses = getMACAddresses (macAddresses, numElementsInArray (macAddresses), false);
  1345. StringArray s;
  1346. for (int i = 0; i < numAddresses; ++i)
  1347. {
  1348. s.add (String::toHexString (0xff & (int) (macAddresses [i] >> 40)).paddedLeft ('0', 2)
  1349. + "-" + String::toHexString (0xff & (int) (macAddresses [i] >> 32)).paddedLeft ('0', 2)
  1350. + "-" + String::toHexString (0xff & (int) (macAddresses [i] >> 24)).paddedLeft ('0', 2)
  1351. + "-" + String::toHexString (0xff & (int) (macAddresses [i] >> 16)).paddedLeft ('0', 2)
  1352. + "-" + String::toHexString (0xff & (int) (macAddresses [i] >> 8)).paddedLeft ('0', 2)
  1353. + "-" + String::toHexString (0xff & (int) (macAddresses [i] >> 0)).paddedLeft ('0', 2));
  1354. }
  1355. return s;
  1356. }
  1357. static bool juceInitialisedNonGUI = false;
  1358. #if JUCE_DEBUG
  1359. template <typename Type>
  1360. static void juce_testAtomicType (Type)
  1361. {
  1362. Atomic<Type> a;
  1363. a.set ((Type) 10);
  1364. a += (Type) 15;
  1365. a.memoryBarrier();
  1366. a -= (Type) 5;
  1367. ++a;
  1368. ++a;
  1369. --a;
  1370. a.memoryBarrier();
  1371. /* These are some simple test cases to check the atomics - let me know
  1372. if any of these assertions fail on your system!
  1373. */
  1374. jassert (a.get() == (Type) 21);
  1375. jassert (a.compareAndSetValue ((Type) 100, (Type) 50) == (Type) 21);
  1376. jassert (a.get() == (Type) 21);
  1377. jassert (a.compareAndSetValue ((Type) 101, a.get()) == (Type) 21);
  1378. jassert (a.get() == (Type) 101);
  1379. jassert (! a.compareAndSetBool ((Type) 300, (Type) 200));
  1380. jassert (a.get() == (Type) 101);
  1381. jassert (a.compareAndSetBool ((Type) 200, a.get()));
  1382. jassert (a.get() == (Type) 200);
  1383. jassert (a.exchange ((Type) 300) == (Type) 200);
  1384. jassert (a.get() == (Type) 300);
  1385. }
  1386. static void juce_testAtomics()
  1387. {
  1388. juce_testAtomicType ((int) 0);
  1389. juce_testAtomicType ((unsigned int) 0);
  1390. juce_testAtomicType ((int32) 0);
  1391. juce_testAtomicType ((uint32) 0);
  1392. juce_testAtomicType ((long) 0);
  1393. juce_testAtomicType ((void*) 0);
  1394. juce_testAtomicType ((int*) 0);
  1395. #if ! (JUCE_WINDOWS && JUCE_32BIT) // some 64-bit intrinsics aren't available on win32
  1396. juce_testAtomicType ((int64) 0);
  1397. juce_testAtomicType ((uint64) 0);
  1398. #endif
  1399. }
  1400. #endif
  1401. void JUCE_PUBLIC_FUNCTION initialiseJuce_NonGUI()
  1402. {
  1403. if (! juceInitialisedNonGUI)
  1404. {
  1405. #if JUCE_MAC || JUCE_IPHONE
  1406. const ScopedAutoReleasePool pool;
  1407. #endif
  1408. #if JUCE_DEBUG
  1409. {
  1410. // Some simple test code to keep an eye on things and make sure these functions
  1411. // work ok on all platforms. Let me know if any of these assertions fail!
  1412. static_jassert (sizeof (pointer_sized_int) == sizeof (void*));
  1413. static_jassert (sizeof (int8) == 1);
  1414. static_jassert (sizeof (uint8) == 1);
  1415. static_jassert (sizeof (int16) == 2);
  1416. static_jassert (sizeof (uint16) == 2);
  1417. static_jassert (sizeof (int32) == 4);
  1418. static_jassert (sizeof (uint32) == 4);
  1419. static_jassert (sizeof (int64) == 8);
  1420. static_jassert (sizeof (uint64) == 8);
  1421. char a1[7];
  1422. jassert (numElementsInArray(a1) == 7);
  1423. int a2[3];
  1424. jassert (numElementsInArray(a2) == 3);
  1425. juce_testAtomics();
  1426. jassert (ByteOrder::swap ((uint16) 0x1122) == 0x2211);
  1427. jassert (ByteOrder::swap ((uint32) 0x11223344) == 0x44332211);
  1428. // Some quick stream tests..
  1429. int randomInt = Random::getSystemRandom().nextInt();
  1430. int64 randomInt64 = Random::getSystemRandom().nextInt64();
  1431. double randomDouble = Random::getSystemRandom().nextDouble();
  1432. String randomString;
  1433. for (int i = 50; --i >= 0;)
  1434. randomString << (juce_wchar) (Random::getSystemRandom().nextInt() & 0xffff);
  1435. MemoryOutputStream mo;
  1436. mo.writeInt (randomInt);
  1437. mo.writeIntBigEndian (randomInt);
  1438. mo.writeCompressedInt (randomInt);
  1439. mo.writeString (randomString);
  1440. mo.writeInt64 (randomInt64);
  1441. mo.writeInt64BigEndian (randomInt64);
  1442. mo.writeDouble (randomDouble);
  1443. mo.writeDoubleBigEndian (randomDouble);
  1444. MemoryInputStream mi (mo.getData(), mo.getDataSize(), false);
  1445. jassert (mi.readInt() == randomInt);
  1446. jassert (mi.readIntBigEndian() == randomInt);
  1447. jassert (mi.readCompressedInt() == randomInt);
  1448. jassert (mi.readString() == randomString);
  1449. jassert (mi.readInt64() == randomInt64);
  1450. jassert (mi.readInt64BigEndian() == randomInt64);
  1451. jassert (mi.readDouble() == randomDouble);
  1452. jassert (mi.readDoubleBigEndian() == randomDouble);
  1453. }
  1454. #endif
  1455. // Now the real initialisation..
  1456. juceInitialisedNonGUI = true;
  1457. DBG (SystemStats::getJUCEVersion());
  1458. SystemStats::initialiseStats();
  1459. Random::getSystemRandom().setSeedRandomly(); // (mustn't call this before initialiseStats() because it relies on the time being set up)
  1460. }
  1461. }
  1462. #if JUCE_WINDOWS
  1463. // This is imported from the sockets code..
  1464. typedef int (__stdcall juce_CloseWin32SocketLibCall) (void);
  1465. extern juce_CloseWin32SocketLibCall* juce_CloseWin32SocketLib;
  1466. #endif
  1467. #if JUCE_DEBUG
  1468. extern void juce_CheckForDanglingStreams();
  1469. #endif
  1470. void JUCE_PUBLIC_FUNCTION shutdownJuce_NonGUI()
  1471. {
  1472. if (juceInitialisedNonGUI)
  1473. {
  1474. #if JUCE_MAC || JUCE_IPHONE
  1475. const ScopedAutoReleasePool pool;
  1476. #endif
  1477. #if JUCE_WINDOWS
  1478. // need to shut down sockets if they were used..
  1479. if (juce_CloseWin32SocketLib != 0)
  1480. (*juce_CloseWin32SocketLib)();
  1481. #endif
  1482. LocalisedStrings::setCurrentMappings (0);
  1483. Thread::stopAllThreads (3000);
  1484. #if JUCE_DEBUG
  1485. juce_CheckForDanglingStreams();
  1486. #endif
  1487. juceInitialisedNonGUI = false;
  1488. }
  1489. }
  1490. #ifdef JUCE_DLL
  1491. void* juce_Malloc (const int size)
  1492. {
  1493. return malloc (size);
  1494. }
  1495. void* juce_Calloc (const int size)
  1496. {
  1497. return calloc (1, size);
  1498. }
  1499. void* juce_Realloc (void* const block, const int size)
  1500. {
  1501. return realloc (block, size);
  1502. }
  1503. void juce_Free (void* const block)
  1504. {
  1505. free (block);
  1506. }
  1507. #if JUCE_DEBUG && JUCE_MSVC && JUCE_CHECK_MEMORY_LEAKS
  1508. void* juce_DebugMalloc (const int size, const char* file, const int line)
  1509. {
  1510. return _malloc_dbg (size, _NORMAL_BLOCK, file, line);
  1511. }
  1512. void* juce_DebugCalloc (const int size, const char* file, const int line)
  1513. {
  1514. return _calloc_dbg (1, size, _NORMAL_BLOCK, file, line);
  1515. }
  1516. void* juce_DebugRealloc (void* const block, const int size, const char* file, const int line)
  1517. {
  1518. return _realloc_dbg (block, size, _NORMAL_BLOCK, file, line);
  1519. }
  1520. void juce_DebugFree (void* const block)
  1521. {
  1522. _free_dbg (block, _NORMAL_BLOCK);
  1523. }
  1524. #endif
  1525. #endif
  1526. END_JUCE_NAMESPACE
  1527. /*** End of inlined file: juce_SystemStats.cpp ***/
  1528. /*** Start of inlined file: juce_Time.cpp ***/
  1529. #ifdef _MSC_VER
  1530. #pragma warning (disable: 4514)
  1531. #pragma warning (push)
  1532. #endif
  1533. #ifndef JUCE_WINDOWS
  1534. #include <sys/time.h>
  1535. #else
  1536. #include <ctime>
  1537. #endif
  1538. #include <sys/timeb.h>
  1539. BEGIN_JUCE_NAMESPACE
  1540. #ifdef _MSC_VER
  1541. #pragma warning (pop)
  1542. #ifdef _INC_TIME_INL
  1543. #define USE_NEW_SECURE_TIME_FNS
  1544. #endif
  1545. #endif
  1546. namespace TimeHelpers
  1547. {
  1548. static struct tm millisToLocal (const int64 millis) throw()
  1549. {
  1550. struct tm result;
  1551. const int64 seconds = millis / 1000;
  1552. if (seconds < literal64bit (86400) || seconds >= literal64bit (2145916800))
  1553. {
  1554. // use extended maths for dates beyond 1970 to 2037..
  1555. const int timeZoneAdjustment = 31536000 - (int) (Time (1971, 0, 1, 0, 0).toMilliseconds() / 1000);
  1556. const int64 jdm = seconds + timeZoneAdjustment + literal64bit (210866803200);
  1557. const int days = (int) (jdm / literal64bit (86400));
  1558. const int a = 32044 + days;
  1559. const int b = (4 * a + 3) / 146097;
  1560. const int c = a - (b * 146097) / 4;
  1561. const int d = (4 * c + 3) / 1461;
  1562. const int e = c - (d * 1461) / 4;
  1563. const int m = (5 * e + 2) / 153;
  1564. result.tm_mday = e - (153 * m + 2) / 5 + 1;
  1565. result.tm_mon = m + 2 - 12 * (m / 10);
  1566. result.tm_year = b * 100 + d - 6700 + (m / 10);
  1567. result.tm_wday = (days + 1) % 7;
  1568. result.tm_yday = -1;
  1569. int t = (int) (jdm % literal64bit (86400));
  1570. result.tm_hour = t / 3600;
  1571. t %= 3600;
  1572. result.tm_min = t / 60;
  1573. result.tm_sec = t % 60;
  1574. result.tm_isdst = -1;
  1575. }
  1576. else
  1577. {
  1578. time_t now = static_cast <time_t> (seconds);
  1579. #if JUCE_WINDOWS
  1580. #ifdef USE_NEW_SECURE_TIME_FNS
  1581. if (now >= 0 && now <= 0x793406fff)
  1582. localtime_s (&result, &now);
  1583. else
  1584. zeromem (&result, sizeof (result));
  1585. #else
  1586. result = *localtime (&now);
  1587. #endif
  1588. #else
  1589. // more thread-safe
  1590. localtime_r (&now, &result);
  1591. #endif
  1592. }
  1593. return result;
  1594. }
  1595. static int extendedModulo (const int64 value, const int modulo) throw()
  1596. {
  1597. return (int) (value >= 0 ? (value % modulo)
  1598. : (value - ((value / modulo) + 1) * modulo));
  1599. }
  1600. static uint32 lastMSCounterValue = 0;
  1601. }
  1602. Time::Time() throw()
  1603. : millisSinceEpoch (0)
  1604. {
  1605. }
  1606. Time::Time (const Time& other) throw()
  1607. : millisSinceEpoch (other.millisSinceEpoch)
  1608. {
  1609. }
  1610. Time::Time (const int64 ms) throw()
  1611. : millisSinceEpoch (ms)
  1612. {
  1613. }
  1614. Time::Time (const int year,
  1615. const int month,
  1616. const int day,
  1617. const int hours,
  1618. const int minutes,
  1619. const int seconds,
  1620. const int milliseconds,
  1621. const bool useLocalTime) throw()
  1622. {
  1623. jassert (year > 100); // year must be a 4-digit version
  1624. if (year < 1971 || year >= 2038 || ! useLocalTime)
  1625. {
  1626. // use extended maths for dates beyond 1970 to 2037..
  1627. const int timeZoneAdjustment = useLocalTime ? (31536000 - (int) (Time (1971, 0, 1, 0, 0).toMilliseconds() / 1000))
  1628. : 0;
  1629. const int a = (13 - month) / 12;
  1630. const int y = year + 4800 - a;
  1631. const int jd = day + (153 * (month + 12 * a - 2) + 2) / 5
  1632. + (y * 365) + (y / 4) - (y / 100) + (y / 400)
  1633. - 32045;
  1634. const int64 s = ((int64) jd) * literal64bit (86400) - literal64bit (210866803200);
  1635. millisSinceEpoch = 1000 * (s + (hours * 3600 + minutes * 60 + seconds - timeZoneAdjustment))
  1636. + milliseconds;
  1637. }
  1638. else
  1639. {
  1640. struct tm t;
  1641. t.tm_year = year - 1900;
  1642. t.tm_mon = month;
  1643. t.tm_mday = day;
  1644. t.tm_hour = hours;
  1645. t.tm_min = minutes;
  1646. t.tm_sec = seconds;
  1647. t.tm_isdst = -1;
  1648. millisSinceEpoch = 1000 * (int64) mktime (&t);
  1649. if (millisSinceEpoch < 0)
  1650. millisSinceEpoch = 0;
  1651. else
  1652. millisSinceEpoch += milliseconds;
  1653. }
  1654. }
  1655. Time::~Time() throw()
  1656. {
  1657. }
  1658. Time& Time::operator= (const Time& other) throw()
  1659. {
  1660. millisSinceEpoch = other.millisSinceEpoch;
  1661. return *this;
  1662. }
  1663. int64 Time::currentTimeMillis() throw()
  1664. {
  1665. static uint32 lastCounterResult = 0xffffffff;
  1666. static int64 correction = 0;
  1667. const uint32 now = getMillisecondCounter();
  1668. // check the counter hasn't wrapped (also triggered the first time this function is called)
  1669. if (now < lastCounterResult)
  1670. {
  1671. // double-check it's actually wrapped, in case multi-cpu machines have timers that drift a bit.
  1672. if (lastCounterResult == 0xffffffff || now < lastCounterResult - 10)
  1673. {
  1674. // get the time once using normal library calls, and store the difference needed to
  1675. // turn the millisecond counter into a real time.
  1676. #if JUCE_WINDOWS
  1677. struct _timeb t;
  1678. #ifdef USE_NEW_SECURE_TIME_FNS
  1679. _ftime_s (&t);
  1680. #else
  1681. _ftime (&t);
  1682. #endif
  1683. correction = (((int64) t.time) * 1000 + t.millitm) - now;
  1684. #else
  1685. struct timeval tv;
  1686. struct timezone tz;
  1687. gettimeofday (&tv, &tz);
  1688. correction = (((int64) tv.tv_sec) * 1000 + tv.tv_usec / 1000) - now;
  1689. #endif
  1690. }
  1691. }
  1692. lastCounterResult = now;
  1693. return correction + now;
  1694. }
  1695. uint32 juce_millisecondsSinceStartup() throw();
  1696. uint32 Time::getMillisecondCounter() throw()
  1697. {
  1698. const uint32 now = juce_millisecondsSinceStartup();
  1699. if (now < TimeHelpers::lastMSCounterValue)
  1700. {
  1701. // in multi-threaded apps this might be called concurrently, so
  1702. // make sure that our last counter value only increases and doesn't
  1703. // go backwards..
  1704. if (now < TimeHelpers::lastMSCounterValue - 1000)
  1705. TimeHelpers::lastMSCounterValue = now;
  1706. }
  1707. else
  1708. {
  1709. TimeHelpers::lastMSCounterValue = now;
  1710. }
  1711. return now;
  1712. }
  1713. uint32 Time::getApproximateMillisecondCounter() throw()
  1714. {
  1715. jassert (TimeHelpers::lastMSCounterValue != 0);
  1716. return TimeHelpers::lastMSCounterValue;
  1717. }
  1718. void Time::waitForMillisecondCounter (const uint32 targetTime) throw()
  1719. {
  1720. for (;;)
  1721. {
  1722. const uint32 now = getMillisecondCounter();
  1723. if (now >= targetTime)
  1724. break;
  1725. const int toWait = targetTime - now;
  1726. if (toWait > 2)
  1727. {
  1728. Thread::sleep (jmin (20, toWait >> 1));
  1729. }
  1730. else
  1731. {
  1732. // xxx should consider using mutex_pause on the mac as it apparently
  1733. // makes it seem less like a spinlock and avoids lowering the thread pri.
  1734. for (int i = 10; --i >= 0;)
  1735. Thread::yield();
  1736. }
  1737. }
  1738. }
  1739. double Time::highResolutionTicksToSeconds (const int64 ticks) throw()
  1740. {
  1741. return ticks / (double) getHighResolutionTicksPerSecond();
  1742. }
  1743. int64 Time::secondsToHighResolutionTicks (const double seconds) throw()
  1744. {
  1745. return (int64) (seconds * (double) getHighResolutionTicksPerSecond());
  1746. }
  1747. const Time JUCE_CALLTYPE Time::getCurrentTime() throw()
  1748. {
  1749. return Time (currentTimeMillis());
  1750. }
  1751. const String Time::toString (const bool includeDate,
  1752. const bool includeTime,
  1753. const bool includeSeconds,
  1754. const bool use24HourClock) const throw()
  1755. {
  1756. String result;
  1757. if (includeDate)
  1758. {
  1759. result << getDayOfMonth() << ' '
  1760. << getMonthName (true) << ' '
  1761. << getYear();
  1762. if (includeTime)
  1763. result << ' ';
  1764. }
  1765. if (includeTime)
  1766. {
  1767. const int mins = getMinutes();
  1768. result << (use24HourClock ? getHours() : getHoursInAmPmFormat())
  1769. << (mins < 10 ? ":0" : ":") << mins;
  1770. if (includeSeconds)
  1771. {
  1772. const int secs = getSeconds();
  1773. result << (secs < 10 ? ":0" : ":") << secs;
  1774. }
  1775. if (! use24HourClock)
  1776. result << (isAfternoon() ? "pm" : "am");
  1777. }
  1778. return result.trimEnd();
  1779. }
  1780. const String Time::formatted (const String& format) const throw()
  1781. {
  1782. String buffer;
  1783. int bufferSize = 128;
  1784. buffer.preallocateStorage (bufferSize);
  1785. struct tm t (TimeHelpers::millisToLocal (millisSinceEpoch));
  1786. while (CharacterFunctions::ftime (static_cast <juce_wchar*> (buffer), bufferSize, format, &t) <= 0)
  1787. {
  1788. bufferSize += 128;
  1789. buffer.preallocateStorage (bufferSize);
  1790. }
  1791. return buffer;
  1792. }
  1793. int Time::getYear() const throw()
  1794. {
  1795. return TimeHelpers::millisToLocal (millisSinceEpoch).tm_year + 1900;
  1796. }
  1797. int Time::getMonth() const throw()
  1798. {
  1799. return TimeHelpers::millisToLocal (millisSinceEpoch).tm_mon;
  1800. }
  1801. int Time::getDayOfMonth() const throw()
  1802. {
  1803. return TimeHelpers::millisToLocal (millisSinceEpoch).tm_mday;
  1804. }
  1805. int Time::getDayOfWeek() const throw()
  1806. {
  1807. return TimeHelpers::millisToLocal (millisSinceEpoch).tm_wday;
  1808. }
  1809. int Time::getHours() const throw()
  1810. {
  1811. return TimeHelpers::millisToLocal (millisSinceEpoch).tm_hour;
  1812. }
  1813. int Time::getHoursInAmPmFormat() const throw()
  1814. {
  1815. const int hours = getHours();
  1816. if (hours == 0)
  1817. return 12;
  1818. else if (hours <= 12)
  1819. return hours;
  1820. else
  1821. return hours - 12;
  1822. }
  1823. bool Time::isAfternoon() const throw()
  1824. {
  1825. return getHours() >= 12;
  1826. }
  1827. int Time::getMinutes() const throw()
  1828. {
  1829. return TimeHelpers::millisToLocal (millisSinceEpoch).tm_min;
  1830. }
  1831. int Time::getSeconds() const throw()
  1832. {
  1833. return TimeHelpers::extendedModulo (millisSinceEpoch / 1000, 60);
  1834. }
  1835. int Time::getMilliseconds() const throw()
  1836. {
  1837. return TimeHelpers::extendedModulo (millisSinceEpoch, 1000);
  1838. }
  1839. bool Time::isDaylightSavingTime() const throw()
  1840. {
  1841. return TimeHelpers::millisToLocal (millisSinceEpoch).tm_isdst != 0;
  1842. }
  1843. const String Time::getTimeZone() const throw()
  1844. {
  1845. String zone[2];
  1846. #if JUCE_WINDOWS
  1847. _tzset();
  1848. #ifdef USE_NEW_SECURE_TIME_FNS
  1849. {
  1850. char name [128];
  1851. size_t length;
  1852. for (int i = 0; i < 2; ++i)
  1853. {
  1854. zeromem (name, sizeof (name));
  1855. _get_tzname (&length, name, 127, i);
  1856. zone[i] = name;
  1857. }
  1858. }
  1859. #else
  1860. const char** const zonePtr = (const char**) _tzname;
  1861. zone[0] = zonePtr[0];
  1862. zone[1] = zonePtr[1];
  1863. #endif
  1864. #else
  1865. tzset();
  1866. const char** const zonePtr = (const char**) tzname;
  1867. zone[0] = zonePtr[0];
  1868. zone[1] = zonePtr[1];
  1869. #endif
  1870. if (isDaylightSavingTime())
  1871. {
  1872. zone[0] = zone[1];
  1873. if (zone[0].length() > 3
  1874. && zone[0].containsIgnoreCase ("daylight")
  1875. && zone[0].contains ("GMT"))
  1876. zone[0] = "BST";
  1877. }
  1878. return zone[0].substring (0, 3);
  1879. }
  1880. const String Time::getMonthName (const bool threeLetterVersion) const throw()
  1881. {
  1882. return getMonthName (getMonth(), threeLetterVersion);
  1883. }
  1884. const String Time::getWeekdayName (const bool threeLetterVersion) const throw()
  1885. {
  1886. return getWeekdayName (getDayOfWeek(), threeLetterVersion);
  1887. }
  1888. const String Time::getMonthName (int monthNumber, const bool threeLetterVersion) throw()
  1889. {
  1890. const char* const shortMonthNames[] = { "Jan", "Feb", "Mar", "Apr", "May", "Jun", "Jul", "Aug", "Sep", "Oct", "Nov", "Dec" };
  1891. const char* const longMonthNames[] = { "January", "February", "March", "April", "May", "June", "July", "August", "September", "October", "November", "December" };
  1892. monthNumber %= 12;
  1893. return TRANS (threeLetterVersion ? shortMonthNames [monthNumber]
  1894. : longMonthNames [monthNumber]);
  1895. }
  1896. const String Time::getWeekdayName (int day, const bool threeLetterVersion) throw()
  1897. {
  1898. const char* const shortDayNames[] = { "Sun", "Mon", "Tue", "Wed", "Thu", "Fri", "Sat" };
  1899. const char* const longDayNames[] = { "Sunday", "Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday" };
  1900. day %= 7;
  1901. return TRANS (threeLetterVersion ? shortDayNames [day]
  1902. : longDayNames [day]);
  1903. }
  1904. END_JUCE_NAMESPACE
  1905. /*** End of inlined file: juce_Time.cpp ***/
  1906. /*** Start of inlined file: juce_BitArray.cpp ***/
  1907. BEGIN_JUCE_NAMESPACE
  1908. BigInteger::BigInteger()
  1909. : numValues (4),
  1910. highestBit (-1),
  1911. negative (false)
  1912. {
  1913. values.calloc (numValues + 1);
  1914. }
  1915. BigInteger::BigInteger (const int value)
  1916. : numValues (4),
  1917. highestBit (31),
  1918. negative (value < 0)
  1919. {
  1920. values.calloc (numValues + 1);
  1921. values[0] = abs (value);
  1922. highestBit = getHighestBit();
  1923. }
  1924. BigInteger::BigInteger (int64 value)
  1925. : numValues (4),
  1926. highestBit (63),
  1927. negative (value < 0)
  1928. {
  1929. values.calloc (numValues + 1);
  1930. if (value < 0)
  1931. value = -value;
  1932. values[0] = (unsigned int) value;
  1933. values[1] = (unsigned int) (value >> 32);
  1934. highestBit = getHighestBit();
  1935. }
  1936. BigInteger::BigInteger (const unsigned int value)
  1937. : numValues (4),
  1938. highestBit (31),
  1939. negative (false)
  1940. {
  1941. values.calloc (numValues + 1);
  1942. values[0] = value;
  1943. highestBit = getHighestBit();
  1944. }
  1945. BigInteger::BigInteger (const BigInteger& other)
  1946. : numValues (jmax (4, (other.highestBit >> 5) + 1)),
  1947. highestBit (other.getHighestBit()),
  1948. negative (other.negative)
  1949. {
  1950. values.malloc (numValues + 1);
  1951. memcpy (values, other.values, sizeof (unsigned int) * (numValues + 1));
  1952. }
  1953. BigInteger::~BigInteger()
  1954. {
  1955. }
  1956. void BigInteger::swapWith (BigInteger& other) throw()
  1957. {
  1958. values.swapWith (other.values);
  1959. swapVariables (numValues, other.numValues);
  1960. swapVariables (highestBit, other.highestBit);
  1961. swapVariables (negative, other.negative);
  1962. }
  1963. BigInteger& BigInteger::operator= (const BigInteger& other)
  1964. {
  1965. if (this != &other)
  1966. {
  1967. highestBit = other.getHighestBit();
  1968. numValues = jmax (4, (highestBit >> 5) + 1);
  1969. negative = other.negative;
  1970. values.malloc (numValues + 1);
  1971. memcpy (values, other.values, sizeof (unsigned int) * (numValues + 1));
  1972. }
  1973. return *this;
  1974. }
  1975. void BigInteger::ensureSize (const int numVals)
  1976. {
  1977. if (numVals + 2 >= numValues)
  1978. {
  1979. int oldSize = numValues;
  1980. numValues = ((numVals + 2) * 3) / 2;
  1981. values.realloc (numValues + 1);
  1982. while (oldSize < numValues)
  1983. values [oldSize++] = 0;
  1984. }
  1985. }
  1986. bool BigInteger::operator[] (const int bit) const throw()
  1987. {
  1988. return bit <= highestBit && bit >= 0
  1989. && ((values [bit >> 5] & (1 << (bit & 31))) != 0);
  1990. }
  1991. int BigInteger::toInteger() const throw()
  1992. {
  1993. const int n = (int) (values[0] & 0x7fffffff);
  1994. return negative ? -n : n;
  1995. }
  1996. const BigInteger BigInteger::getBitRange (int startBit, int numBits) const
  1997. {
  1998. BigInteger r;
  1999. numBits = jmin (numBits, getHighestBit() + 1 - startBit);
  2000. r.ensureSize (numBits >> 5);
  2001. r.highestBit = numBits;
  2002. int i = 0;
  2003. while (numBits > 0)
  2004. {
  2005. r.values[i++] = getBitRangeAsInt (startBit, jmin (32, numBits));
  2006. numBits -= 32;
  2007. startBit += 32;
  2008. }
  2009. r.highestBit = r.getHighestBit();
  2010. return r;
  2011. }
  2012. int BigInteger::getBitRangeAsInt (const int startBit, int numBits) const throw()
  2013. {
  2014. if (numBits > 32)
  2015. {
  2016. jassertfalse // use getBitRange() if you need more than 32 bits..
  2017. numBits = 32;
  2018. }
  2019. numBits = jmin (numBits, highestBit + 1 - startBit);
  2020. if (numBits <= 0)
  2021. return 0;
  2022. const int pos = startBit >> 5;
  2023. const int offset = startBit & 31;
  2024. const int endSpace = 32 - numBits;
  2025. uint32 n = ((uint32) values [pos]) >> offset;
  2026. if (offset > endSpace)
  2027. n |= ((uint32) values [pos + 1]) << (32 - offset);
  2028. return (int) (n & (((uint32) 0xffffffff) >> endSpace));
  2029. }
  2030. void BigInteger::setBitRangeAsInt (const int startBit, int numBits, unsigned int valueToSet)
  2031. {
  2032. if (numBits > 32)
  2033. {
  2034. jassertfalse
  2035. numBits = 32;
  2036. }
  2037. for (int i = 0; i < numBits; ++i)
  2038. {
  2039. setBit (startBit + i, (valueToSet & 1) != 0);
  2040. valueToSet >>= 1;
  2041. }
  2042. }
  2043. void BigInteger::clear()
  2044. {
  2045. if (numValues > 16)
  2046. {
  2047. numValues = 4;
  2048. values.calloc (numValues + 1);
  2049. }
  2050. else
  2051. {
  2052. zeromem (values, sizeof (unsigned int) * (numValues + 1));
  2053. }
  2054. highestBit = -1;
  2055. negative = false;
  2056. }
  2057. void BigInteger::setBit (const int bit)
  2058. {
  2059. if (bit >= 0)
  2060. {
  2061. if (bit > highestBit)
  2062. {
  2063. ensureSize (bit >> 5);
  2064. highestBit = bit;
  2065. }
  2066. values [bit >> 5] |= (1 << (bit & 31));
  2067. }
  2068. }
  2069. void BigInteger::setBit (const int bit, const bool shouldBeSet)
  2070. {
  2071. if (shouldBeSet)
  2072. setBit (bit);
  2073. else
  2074. clearBit (bit);
  2075. }
  2076. void BigInteger::clearBit (const int bit) throw()
  2077. {
  2078. if (bit >= 0 && bit <= highestBit)
  2079. values [bit >> 5] &= ~(1 << (bit & 31));
  2080. }
  2081. void BigInteger::setRange (int startBit, int numBits, const bool shouldBeSet)
  2082. {
  2083. while (--numBits >= 0)
  2084. setBit (startBit++, shouldBeSet);
  2085. }
  2086. void BigInteger::insertBit (const int bit, const bool shouldBeSet)
  2087. {
  2088. if (bit >= 0)
  2089. shiftBits (1, bit);
  2090. setBit (bit, shouldBeSet);
  2091. }
  2092. bool BigInteger::isZero() const throw()
  2093. {
  2094. return getHighestBit() < 0;
  2095. }
  2096. bool BigInteger::isOne() const throw()
  2097. {
  2098. return getHighestBit() == 0 && ! negative;
  2099. }
  2100. bool BigInteger::isNegative() const throw()
  2101. {
  2102. return negative && ! isZero();
  2103. }
  2104. void BigInteger::setNegative (const bool neg) throw()
  2105. {
  2106. negative = neg;
  2107. }
  2108. void BigInteger::negate() throw()
  2109. {
  2110. negative = (! negative) && ! isZero();
  2111. }
  2112. int BigInteger::countNumberOfSetBits() const throw()
  2113. {
  2114. int total = 0;
  2115. for (int i = (highestBit >> 5) + 1; --i >= 0;)
  2116. {
  2117. unsigned int n = values[i];
  2118. if (n == 0xffffffff)
  2119. {
  2120. total += 32;
  2121. }
  2122. else
  2123. {
  2124. while (n != 0)
  2125. {
  2126. total += (n & 1);
  2127. n >>= 1;
  2128. }
  2129. }
  2130. }
  2131. return total;
  2132. }
  2133. int BigInteger::getHighestBit() const throw()
  2134. {
  2135. for (int i = highestBit + 1; --i >= 0;)
  2136. if ((values [i >> 5] & (1 << (i & 31))) != 0)
  2137. return i;
  2138. return -1;
  2139. }
  2140. int BigInteger::findNextSetBit (int i) const throw()
  2141. {
  2142. for (; i <= highestBit; ++i)
  2143. if ((values [i >> 5] & (1 << (i & 31))) != 0)
  2144. return i;
  2145. return -1;
  2146. }
  2147. int BigInteger::findNextClearBit (int i) const throw()
  2148. {
  2149. for (; i <= highestBit; ++i)
  2150. if ((values [i >> 5] & (1 << (i & 31))) == 0)
  2151. break;
  2152. return i;
  2153. }
  2154. BigInteger& BigInteger::operator+= (const BigInteger& other)
  2155. {
  2156. if (other.isNegative())
  2157. return operator-= (-other);
  2158. if (isNegative())
  2159. {
  2160. if (compareAbsolute (other) < 0)
  2161. {
  2162. BigInteger temp (*this);
  2163. temp.negate();
  2164. *this = other;
  2165. operator-= (temp);
  2166. }
  2167. else
  2168. {
  2169. negate();
  2170. operator-= (other);
  2171. negate();
  2172. }
  2173. }
  2174. else
  2175. {
  2176. if (other.highestBit > highestBit)
  2177. highestBit = other.highestBit;
  2178. ++highestBit;
  2179. const int numInts = (highestBit >> 5) + 1;
  2180. ensureSize (numInts);
  2181. int64 remainder = 0;
  2182. for (int i = 0; i <= numInts; ++i)
  2183. {
  2184. if (i < numValues)
  2185. remainder += values[i];
  2186. if (i < other.numValues)
  2187. remainder += other.values[i];
  2188. values[i] = (unsigned int) remainder;
  2189. remainder >>= 32;
  2190. }
  2191. jassert (remainder == 0);
  2192. highestBit = getHighestBit();
  2193. }
  2194. return *this;
  2195. }
  2196. BigInteger& BigInteger::operator-= (const BigInteger& other)
  2197. {
  2198. if (other.isNegative())
  2199. return operator+= (-other);
  2200. if (! isNegative())
  2201. {
  2202. if (compareAbsolute (other) < 0)
  2203. {
  2204. BigInteger temp (other);
  2205. swapWith (temp);
  2206. operator-= (temp);
  2207. negate();
  2208. return *this;
  2209. }
  2210. }
  2211. else
  2212. {
  2213. negate();
  2214. operator+= (other);
  2215. negate();
  2216. return *this;
  2217. }
  2218. const int numInts = (highestBit >> 5) + 1;
  2219. const int maxOtherInts = (other.highestBit >> 5) + 1;
  2220. int64 amountToSubtract = 0;
  2221. for (int i = 0; i <= numInts; ++i)
  2222. {
  2223. if (i <= maxOtherInts)
  2224. amountToSubtract += (int64) other.values[i];
  2225. if (values[i] >= amountToSubtract)
  2226. {
  2227. values[i] = (unsigned int) (values[i] - amountToSubtract);
  2228. amountToSubtract = 0;
  2229. }
  2230. else
  2231. {
  2232. const int64 n = ((int64) values[i] + (((int64) 1) << 32)) - amountToSubtract;
  2233. values[i] = (unsigned int) n;
  2234. amountToSubtract = 1;
  2235. }
  2236. }
  2237. return *this;
  2238. }
  2239. BigInteger& BigInteger::operator*= (const BigInteger& other)
  2240. {
  2241. BigInteger total;
  2242. highestBit = getHighestBit();
  2243. const bool wasNegative = isNegative();
  2244. setNegative (false);
  2245. for (int i = 0; i <= highestBit; ++i)
  2246. {
  2247. if (operator[](i))
  2248. {
  2249. BigInteger n (other);
  2250. n.setNegative (false);
  2251. n <<= i;
  2252. total += n;
  2253. }
  2254. }
  2255. total.setNegative (wasNegative ^ other.isNegative());
  2256. swapWith (total);
  2257. return *this;
  2258. }
  2259. void BigInteger::divideBy (const BigInteger& divisor, BigInteger& remainder)
  2260. {
  2261. jassert (this != &remainder); // (can't handle passing itself in to get the remainder)
  2262. const int divHB = divisor.getHighestBit();
  2263. const int ourHB = getHighestBit();
  2264. if (divHB < 0 || ourHB < 0)
  2265. {
  2266. // division by zero
  2267. remainder.clear();
  2268. clear();
  2269. }
  2270. else
  2271. {
  2272. const bool wasNegative = isNegative();
  2273. swapWith (remainder);
  2274. remainder.setNegative (false);
  2275. clear();
  2276. BigInteger temp (divisor);
  2277. temp.setNegative (false);
  2278. int leftShift = ourHB - divHB;
  2279. temp <<= leftShift;
  2280. while (leftShift >= 0)
  2281. {
  2282. if (remainder.compareAbsolute (temp) >= 0)
  2283. {
  2284. remainder -= temp;
  2285. setBit (leftShift);
  2286. }
  2287. if (--leftShift >= 0)
  2288. temp >>= 1;
  2289. }
  2290. negative = wasNegative ^ divisor.isNegative();
  2291. remainder.setNegative (wasNegative);
  2292. }
  2293. }
  2294. BigInteger& BigInteger::operator/= (const BigInteger& other)
  2295. {
  2296. BigInteger remainder;
  2297. divideBy (other, remainder);
  2298. return *this;
  2299. }
  2300. BigInteger& BigInteger::operator|= (const BigInteger& other)
  2301. {
  2302. // this operation doesn't take into account negative values..
  2303. jassert (isNegative() == other.isNegative());
  2304. if (other.highestBit >= 0)
  2305. {
  2306. ensureSize (other.highestBit >> 5);
  2307. int n = (other.highestBit >> 5) + 1;
  2308. while (--n >= 0)
  2309. values[n] |= other.values[n];
  2310. if (other.highestBit > highestBit)
  2311. highestBit = other.highestBit;
  2312. highestBit = getHighestBit();
  2313. }
  2314. return *this;
  2315. }
  2316. BigInteger& BigInteger::operator&= (const BigInteger& other)
  2317. {
  2318. // this operation doesn't take into account negative values..
  2319. jassert (isNegative() == other.isNegative());
  2320. int n = numValues;
  2321. while (n > other.numValues)
  2322. values[--n] = 0;
  2323. while (--n >= 0)
  2324. values[n] &= other.values[n];
  2325. if (other.highestBit < highestBit)
  2326. highestBit = other.highestBit;
  2327. highestBit = getHighestBit();
  2328. return *this;
  2329. }
  2330. BigInteger& BigInteger::operator^= (const BigInteger& other)
  2331. {
  2332. // this operation will only work with the absolute values
  2333. jassert (isNegative() == other.isNegative());
  2334. if (other.highestBit >= 0)
  2335. {
  2336. ensureSize (other.highestBit >> 5);
  2337. int n = (other.highestBit >> 5) + 1;
  2338. while (--n >= 0)
  2339. values[n] ^= other.values[n];
  2340. if (other.highestBit > highestBit)
  2341. highestBit = other.highestBit;
  2342. highestBit = getHighestBit();
  2343. }
  2344. return *this;
  2345. }
  2346. BigInteger& BigInteger::operator%= (const BigInteger& divisor)
  2347. {
  2348. BigInteger remainder;
  2349. divideBy (divisor, remainder);
  2350. swapWith (remainder);
  2351. return *this;
  2352. }
  2353. BigInteger& BigInteger::operator<<= (int numBitsToShift)
  2354. {
  2355. shiftBits (numBitsToShift, 0);
  2356. return *this;
  2357. }
  2358. BigInteger& BigInteger::operator>>= (int numBitsToShift)
  2359. {
  2360. return operator<<= (-numBitsToShift);
  2361. }
  2362. BigInteger& BigInteger::operator++() { return operator+= (1); }
  2363. BigInteger& BigInteger::operator--() { return operator-= (1); }
  2364. const BigInteger BigInteger::operator++ (int) { const BigInteger old (*this); operator+= (1); return old; }
  2365. const BigInteger BigInteger::operator-- (int) { const BigInteger old (*this); operator-= (1); return old; }
  2366. const BigInteger BigInteger::operator+ (const BigInteger& other) const { BigInteger b (*this); return b += other; }
  2367. const BigInteger BigInteger::operator- (const BigInteger& other) const { BigInteger b (*this); return b -= other; }
  2368. const BigInteger BigInteger::operator* (const BigInteger& other) const { BigInteger b (*this); return b *= other; }
  2369. const BigInteger BigInteger::operator/ (const BigInteger& other) const { BigInteger b (*this); return b /= other; }
  2370. const BigInteger BigInteger::operator| (const BigInteger& other) const { BigInteger b (*this); return b |= other; }
  2371. const BigInteger BigInteger::operator& (const BigInteger& other) const { BigInteger b (*this); return b &= other; }
  2372. const BigInteger BigInteger::operator^ (const BigInteger& other) const { BigInteger b (*this); return b ^= other; }
  2373. const BigInteger BigInteger::operator% (const BigInteger& other) const { BigInteger b (*this); return b %= other; }
  2374. const BigInteger BigInteger::operator<< (const int numBits) const { BigInteger b (*this); return b <<= numBits; }
  2375. const BigInteger BigInteger::operator>> (const int numBits) const { BigInteger b (*this); return b >>= numBits; }
  2376. const BigInteger BigInteger::operator-() const { BigInteger b (*this); b.negate(); return b; }
  2377. int BigInteger::compare (const BigInteger& other) const throw()
  2378. {
  2379. if (isNegative() == other.isNegative())
  2380. {
  2381. const int absComp = compareAbsolute (other);
  2382. return isNegative() ? -absComp : absComp;
  2383. }
  2384. else
  2385. {
  2386. return isNegative() ? -1 : 1;
  2387. }
  2388. }
  2389. int BigInteger::compareAbsolute (const BigInteger& other) const throw()
  2390. {
  2391. const int h1 = getHighestBit();
  2392. const int h2 = other.getHighestBit();
  2393. if (h1 > h2)
  2394. return 1;
  2395. else if (h1 < h2)
  2396. return -1;
  2397. for (int i = (h1 >> 5) + 1; --i >= 0;)
  2398. if (values[i] != other.values[i])
  2399. return (values[i] > other.values[i]) ? 1 : -1;
  2400. return 0;
  2401. }
  2402. bool BigInteger::operator== (const BigInteger& other) const throw() { return compare (other) == 0; }
  2403. bool BigInteger::operator!= (const BigInteger& other) const throw() { return compare (other) != 0; }
  2404. bool BigInteger::operator< (const BigInteger& other) const throw() { return compare (other) < 0; }
  2405. bool BigInteger::operator<= (const BigInteger& other) const throw() { return compare (other) <= 0; }
  2406. bool BigInteger::operator> (const BigInteger& other) const throw() { return compare (other) > 0; }
  2407. bool BigInteger::operator>= (const BigInteger& other) const throw() { return compare (other) >= 0; }
  2408. void BigInteger::shiftBits (int bits, const int startBit)
  2409. {
  2410. if (highestBit < 0)
  2411. return;
  2412. if (startBit > 0)
  2413. {
  2414. if (bits < 0)
  2415. {
  2416. // right shift
  2417. for (int i = startBit; i <= highestBit; ++i)
  2418. setBit (i, operator[] (i - bits));
  2419. highestBit = getHighestBit();
  2420. }
  2421. else if (bits > 0)
  2422. {
  2423. // left shift
  2424. for (int i = highestBit + 1; --i >= startBit;)
  2425. setBit (i + bits, operator[] (i));
  2426. while (--bits >= 0)
  2427. clearBit (bits + startBit);
  2428. }
  2429. }
  2430. else
  2431. {
  2432. if (bits < 0)
  2433. {
  2434. // right shift
  2435. bits = -bits;
  2436. if (bits > highestBit)
  2437. {
  2438. clear();
  2439. }
  2440. else
  2441. {
  2442. const int wordsToMove = bits >> 5;
  2443. int top = 1 + (highestBit >> 5) - wordsToMove;
  2444. highestBit -= bits;
  2445. if (wordsToMove > 0)
  2446. {
  2447. int i;
  2448. for (i = 0; i < top; ++i)
  2449. values [i] = values [i + wordsToMove];
  2450. for (i = 0; i < wordsToMove; ++i)
  2451. values [top + i] = 0;
  2452. bits &= 31;
  2453. }
  2454. if (bits != 0)
  2455. {
  2456. const int invBits = 32 - bits;
  2457. --top;
  2458. for (int i = 0; i < top; ++i)
  2459. values[i] = (values[i] >> bits) | (values [i + 1] << invBits);
  2460. values[top] = (values[top] >> bits);
  2461. }
  2462. highestBit = getHighestBit();
  2463. }
  2464. }
  2465. else if (bits > 0)
  2466. {
  2467. // left shift
  2468. ensureSize (((highestBit + bits) >> 5) + 1);
  2469. const int wordsToMove = bits >> 5;
  2470. int top = 1 + (highestBit >> 5);
  2471. highestBit += bits;
  2472. if (wordsToMove > 0)
  2473. {
  2474. int i;
  2475. for (i = top; --i >= 0;)
  2476. values [i + wordsToMove] = values [i];
  2477. for (i = 0; i < wordsToMove; ++i)
  2478. values [i] = 0;
  2479. bits &= 31;
  2480. }
  2481. if (bits != 0)
  2482. {
  2483. const int invBits = 32 - bits;
  2484. for (int i = top + 1 + wordsToMove; --i > wordsToMove;)
  2485. values[i] = (values[i] << bits) | (values [i - 1] >> invBits);
  2486. values [wordsToMove] = values [wordsToMove] << bits;
  2487. }
  2488. highestBit = getHighestBit();
  2489. }
  2490. }
  2491. }
  2492. const BigInteger BigInteger::simpleGCD (BigInteger* m, BigInteger* n)
  2493. {
  2494. while (! m->isZero())
  2495. {
  2496. if (n->compareAbsolute (*m) > 0)
  2497. swapVariables (m, n);
  2498. *m -= *n;
  2499. }
  2500. return *n;
  2501. }
  2502. const BigInteger BigInteger::findGreatestCommonDivisor (BigInteger n) const
  2503. {
  2504. BigInteger m (*this);
  2505. while (! n.isZero())
  2506. {
  2507. if (abs (m.getHighestBit() - n.getHighestBit()) <= 16)
  2508. return simpleGCD (&m, &n);
  2509. BigInteger temp1 (m), temp2;
  2510. temp1.divideBy (n, temp2);
  2511. m = n;
  2512. n = temp2;
  2513. }
  2514. return m;
  2515. }
  2516. void BigInteger::exponentModulo (const BigInteger& exponent, const BigInteger& modulus)
  2517. {
  2518. BigInteger exp (exponent);
  2519. exp %= modulus;
  2520. BigInteger value (1);
  2521. swapWith (value);
  2522. value %= modulus;
  2523. while (! exp.isZero())
  2524. {
  2525. if (exp [0])
  2526. {
  2527. operator*= (value);
  2528. operator%= (modulus);
  2529. }
  2530. value *= value;
  2531. value %= modulus;
  2532. exp >>= 1;
  2533. }
  2534. }
  2535. void BigInteger::inverseModulo (const BigInteger& modulus)
  2536. {
  2537. if (modulus.isOne() || modulus.isNegative())
  2538. {
  2539. clear();
  2540. return;
  2541. }
  2542. if (isNegative() || compareAbsolute (modulus) >= 0)
  2543. operator%= (modulus);
  2544. if (isOne())
  2545. return;
  2546. if (! (*this)[0])
  2547. {
  2548. // not invertible
  2549. clear();
  2550. return;
  2551. }
  2552. BigInteger a1 (modulus);
  2553. BigInteger a2 (*this);
  2554. BigInteger b1 (modulus);
  2555. BigInteger b2 (1);
  2556. while (! a2.isOne())
  2557. {
  2558. BigInteger temp1, temp2, multiplier (a1);
  2559. multiplier.divideBy (a2, temp1);
  2560. temp1 = a2;
  2561. temp1 *= multiplier;
  2562. temp2 = a1;
  2563. temp2 -= temp1;
  2564. a1 = a2;
  2565. a2 = temp2;
  2566. temp1 = b2;
  2567. temp1 *= multiplier;
  2568. temp2 = b1;
  2569. temp2 -= temp1;
  2570. b1 = b2;
  2571. b2 = temp2;
  2572. }
  2573. while (b2.isNegative())
  2574. b2 += modulus;
  2575. b2 %= modulus;
  2576. swapWith (b2);
  2577. }
  2578. OutputStream& JUCE_CALLTYPE operator<< (OutputStream& stream, const BigInteger& value)
  2579. {
  2580. return stream << value.toString (10);
  2581. }
  2582. const String BigInteger::toString (const int base, const int minimumNumCharacters) const
  2583. {
  2584. String s;
  2585. BigInteger v (*this);
  2586. if (base == 2 || base == 8 || base == 16)
  2587. {
  2588. const int bits = (base == 2) ? 1 : (base == 8 ? 3 : 4);
  2589. static const char* const hexDigits = "0123456789abcdef";
  2590. for (;;)
  2591. {
  2592. const int remainder = v.getBitRangeAsInt (0, bits);
  2593. v >>= bits;
  2594. if (remainder == 0 && v.isZero())
  2595. break;
  2596. s = String::charToString (hexDigits [remainder]) + s;
  2597. }
  2598. }
  2599. else if (base == 10)
  2600. {
  2601. const BigInteger ten (10);
  2602. BigInteger remainder;
  2603. for (;;)
  2604. {
  2605. v.divideBy (ten, remainder);
  2606. if (remainder.isZero() && v.isZero())
  2607. break;
  2608. s = String (remainder.getBitRangeAsInt (0, 8)) + s;
  2609. }
  2610. }
  2611. else
  2612. {
  2613. jassertfalse // can't do the specified base!
  2614. return String::empty;
  2615. }
  2616. s = s.paddedLeft ('0', minimumNumCharacters);
  2617. return isNegative() ? "-" + s : s;
  2618. }
  2619. void BigInteger::parseString (const String& text, const int base)
  2620. {
  2621. clear();
  2622. const juce_wchar* t = text;
  2623. if (base == 2 || base == 8 || base == 16)
  2624. {
  2625. const int bits = (base == 2) ? 1 : (base == 8 ? 3 : 4);
  2626. for (;;)
  2627. {
  2628. const juce_wchar c = *t++;
  2629. const int digit = CharacterFunctions::getHexDigitValue (c);
  2630. if (((unsigned int) digit) < (unsigned int) base)
  2631. {
  2632. operator<<= (bits);
  2633. operator+= (digit);
  2634. }
  2635. else if (c == 0)
  2636. {
  2637. break;
  2638. }
  2639. }
  2640. }
  2641. else if (base == 10)
  2642. {
  2643. const BigInteger ten ((unsigned int) 10);
  2644. for (;;)
  2645. {
  2646. const juce_wchar c = *t++;
  2647. if (c >= '0' && c <= '9')
  2648. {
  2649. operator*= (ten);
  2650. operator+= ((int) (c - '0'));
  2651. }
  2652. else if (c == 0)
  2653. {
  2654. break;
  2655. }
  2656. }
  2657. }
  2658. setNegative (text.trimStart().startsWithChar ('-'));
  2659. }
  2660. const MemoryBlock BigInteger::toMemoryBlock() const
  2661. {
  2662. const int numBytes = (getHighestBit() + 8) >> 3;
  2663. MemoryBlock mb ((size_t) numBytes);
  2664. for (int i = 0; i < numBytes; ++i)
  2665. mb[i] = (uint8) getBitRangeAsInt (i << 3, 8);
  2666. return mb;
  2667. }
  2668. void BigInteger::loadFromMemoryBlock (const MemoryBlock& data)
  2669. {
  2670. clear();
  2671. for (int i = (int) data.getSize(); --i >= 0;)
  2672. this->setBitRangeAsInt ((int) (i << 3), 8, data [i]);
  2673. }
  2674. END_JUCE_NAMESPACE
  2675. /*** End of inlined file: juce_BitArray.cpp ***/
  2676. /*** Start of inlined file: juce_MemoryBlock.cpp ***/
  2677. BEGIN_JUCE_NAMESPACE
  2678. MemoryBlock::MemoryBlock() throw()
  2679. : size (0)
  2680. {
  2681. }
  2682. MemoryBlock::MemoryBlock (const size_t initialSize,
  2683. const bool initialiseToZero) throw()
  2684. {
  2685. if (initialSize > 0)
  2686. {
  2687. size = initialSize;
  2688. data.allocate (initialSize, initialiseToZero);
  2689. }
  2690. else
  2691. {
  2692. size = 0;
  2693. }
  2694. }
  2695. MemoryBlock::MemoryBlock (const MemoryBlock& other) throw()
  2696. : size (other.size)
  2697. {
  2698. if (size > 0)
  2699. {
  2700. jassert (other.data != 0);
  2701. data.malloc (size);
  2702. memcpy (data, other.data, size);
  2703. }
  2704. }
  2705. MemoryBlock::MemoryBlock (const void* const dataToInitialiseFrom,
  2706. const size_t sizeInBytes) throw()
  2707. : size (jmax ((size_t) 0, sizeInBytes))
  2708. {
  2709. jassert (sizeInBytes >= 0);
  2710. if (size > 0)
  2711. {
  2712. jassert (dataToInitialiseFrom != 0); // non-zero size, but a zero pointer passed-in?
  2713. data.malloc (size);
  2714. if (dataToInitialiseFrom != 0)
  2715. memcpy (data, dataToInitialiseFrom, size);
  2716. }
  2717. }
  2718. MemoryBlock::~MemoryBlock() throw()
  2719. {
  2720. jassert (size >= 0); // should never happen
  2721. jassert (size == 0 || data != 0); // non-zero size but no data allocated?
  2722. }
  2723. MemoryBlock& MemoryBlock::operator= (const MemoryBlock& other) throw()
  2724. {
  2725. if (this != &other)
  2726. {
  2727. setSize (other.size, false);
  2728. memcpy (data, other.data, size);
  2729. }
  2730. return *this;
  2731. }
  2732. bool MemoryBlock::operator== (const MemoryBlock& other) const throw()
  2733. {
  2734. return matches (other.data, other.size);
  2735. }
  2736. bool MemoryBlock::operator!= (const MemoryBlock& other) const throw()
  2737. {
  2738. return ! operator== (other);
  2739. }
  2740. bool MemoryBlock::matches (const void* dataToCompare, size_t dataSize) const throw()
  2741. {
  2742. return size == dataSize
  2743. && memcmp (data, dataToCompare, size) == 0;
  2744. }
  2745. // this will resize the block to this size
  2746. void MemoryBlock::setSize (const size_t newSize,
  2747. const bool initialiseToZero) throw()
  2748. {
  2749. if (size != newSize)
  2750. {
  2751. if (newSize <= 0)
  2752. {
  2753. data.free();
  2754. size = 0;
  2755. }
  2756. else
  2757. {
  2758. if (data != 0)
  2759. {
  2760. data.realloc (newSize);
  2761. if (initialiseToZero && (newSize > size))
  2762. zeromem (data + size, newSize - size);
  2763. }
  2764. else
  2765. {
  2766. data.allocate (newSize, initialiseToZero);
  2767. }
  2768. size = newSize;
  2769. }
  2770. }
  2771. }
  2772. void MemoryBlock::ensureSize (const size_t minimumSize,
  2773. const bool initialiseToZero) throw()
  2774. {
  2775. if (size < minimumSize)
  2776. setSize (minimumSize, initialiseToZero);
  2777. }
  2778. void MemoryBlock::swapWith (MemoryBlock& other) throw()
  2779. {
  2780. swapVariables (size, other.size);
  2781. data.swapWith (other.data);
  2782. }
  2783. void MemoryBlock::fillWith (const uint8 value) throw()
  2784. {
  2785. memset (data, (int) value, size);
  2786. }
  2787. void MemoryBlock::append (const void* const srcData,
  2788. const size_t numBytes) throw()
  2789. {
  2790. if (numBytes > 0)
  2791. {
  2792. const size_t oldSize = size;
  2793. setSize (size + numBytes);
  2794. memcpy (data + oldSize, srcData, numBytes);
  2795. }
  2796. }
  2797. void MemoryBlock::copyFrom (const void* const src, int offset, size_t num) throw()
  2798. {
  2799. const char* d = static_cast<const char*> (src);
  2800. if (offset < 0)
  2801. {
  2802. d -= offset;
  2803. num -= offset;
  2804. offset = 0;
  2805. }
  2806. if (offset + num > size)
  2807. num = size - offset;
  2808. if (num > 0)
  2809. memcpy (data + offset, d, num);
  2810. }
  2811. void MemoryBlock::copyTo (void* const dst, int offset, size_t num) const throw()
  2812. {
  2813. char* d = static_cast<char*> (dst);
  2814. if (offset < 0)
  2815. {
  2816. zeromem (d, -offset);
  2817. d -= offset;
  2818. num += offset;
  2819. offset = 0;
  2820. }
  2821. if (offset + num > size)
  2822. {
  2823. const size_t newNum = size - offset;
  2824. zeromem (d + newNum, num - newNum);
  2825. num = newNum;
  2826. }
  2827. if (num > 0)
  2828. memcpy (d, data + offset, num);
  2829. }
  2830. void MemoryBlock::removeSection (size_t startByte, size_t numBytesToRemove) throw()
  2831. {
  2832. if (startByte < 0)
  2833. {
  2834. numBytesToRemove += startByte;
  2835. startByte = 0;
  2836. }
  2837. if (startByte + numBytesToRemove >= size)
  2838. {
  2839. setSize (startByte);
  2840. }
  2841. else if (numBytesToRemove > 0)
  2842. {
  2843. memmove (data + startByte,
  2844. data + startByte + numBytesToRemove,
  2845. size - (startByte + numBytesToRemove));
  2846. setSize (size - numBytesToRemove);
  2847. }
  2848. }
  2849. const String MemoryBlock::toString() const throw()
  2850. {
  2851. return String (static_cast <const char*> (getData()), size);
  2852. }
  2853. int MemoryBlock::getBitRange (const size_t bitRangeStart, size_t numBits) const throw()
  2854. {
  2855. int res = 0;
  2856. size_t byte = bitRangeStart >> 3;
  2857. int offsetInByte = (int) bitRangeStart & 7;
  2858. size_t bitsSoFar = 0;
  2859. while (numBits > 0 && (size_t) byte < size)
  2860. {
  2861. const int bitsThisTime = jmin ((int) numBits, 8 - offsetInByte);
  2862. const int mask = (0xff >> (8 - bitsThisTime)) << offsetInByte;
  2863. res |= (((data[byte] & mask) >> offsetInByte) << bitsSoFar);
  2864. bitsSoFar += bitsThisTime;
  2865. numBits -= bitsThisTime;
  2866. ++byte;
  2867. offsetInByte = 0;
  2868. }
  2869. return res;
  2870. }
  2871. void MemoryBlock::setBitRange (const size_t bitRangeStart, size_t numBits, int bitsToSet) throw()
  2872. {
  2873. size_t byte = bitRangeStart >> 3;
  2874. int offsetInByte = (int) bitRangeStart & 7;
  2875. unsigned int mask = ~((((unsigned int) 0xffffffff) << (32 - numBits)) >> (32 - numBits));
  2876. while (numBits > 0 && (size_t) byte < size)
  2877. {
  2878. const int bitsThisTime = jmin ((int) numBits, 8 - offsetInByte);
  2879. const unsigned int tempMask = (mask << offsetInByte) | ~((((unsigned int) 0xffffffff) >> offsetInByte) << offsetInByte);
  2880. const unsigned int tempBits = bitsToSet << offsetInByte;
  2881. data[byte] = (char) ((data[byte] & tempMask) | tempBits);
  2882. ++byte;
  2883. numBits -= bitsThisTime;
  2884. bitsToSet >>= bitsThisTime;
  2885. mask >>= bitsThisTime;
  2886. offsetInByte = 0;
  2887. }
  2888. }
  2889. void MemoryBlock::loadFromHexString (const String& hex) throw()
  2890. {
  2891. ensureSize (hex.length() >> 1);
  2892. char* dest = data;
  2893. int i = 0;
  2894. for (;;)
  2895. {
  2896. int byte = 0;
  2897. for (int loop = 2; --loop >= 0;)
  2898. {
  2899. byte <<= 4;
  2900. for (;;)
  2901. {
  2902. const juce_wchar c = hex [i++];
  2903. if (c >= '0' && c <= '9')
  2904. {
  2905. byte |= c - '0';
  2906. break;
  2907. }
  2908. else if (c >= 'a' && c <= 'z')
  2909. {
  2910. byte |= c - ('a' - 10);
  2911. break;
  2912. }
  2913. else if (c >= 'A' && c <= 'Z')
  2914. {
  2915. byte |= c - ('A' - 10);
  2916. break;
  2917. }
  2918. else if (c == 0)
  2919. {
  2920. setSize (static_cast <size_t> (dest - data));
  2921. return;
  2922. }
  2923. }
  2924. }
  2925. *dest++ = (char) byte;
  2926. }
  2927. }
  2928. static const char* const encodingTable
  2929. = ".ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+";
  2930. const String MemoryBlock::toBase64Encoding() const throw()
  2931. {
  2932. const size_t numChars = ((size << 3) + 5) / 6;
  2933. String destString ((unsigned int) size); // store the length, followed by a '.', and then the data.
  2934. const int initialLen = destString.length();
  2935. destString.preallocateStorage (initialLen + 2 + numChars);
  2936. juce_wchar* d = destString;
  2937. d += initialLen;
  2938. *d++ = '.';
  2939. for (size_t i = 0; i < numChars; ++i)
  2940. *d++ = encodingTable [getBitRange (i * 6, 6)];
  2941. *d++ = 0;
  2942. return destString;
  2943. }
  2944. bool MemoryBlock::fromBase64Encoding (const String& s) throw()
  2945. {
  2946. const int startPos = s.indexOfChar ('.') + 1;
  2947. if (startPos <= 0)
  2948. return false;
  2949. const int numBytesNeeded = s.substring (0, startPos - 1).getIntValue();
  2950. setSize (numBytesNeeded, true);
  2951. const int numChars = s.length() - startPos;
  2952. const juce_wchar* srcChars = s;
  2953. srcChars += startPos;
  2954. int pos = 0;
  2955. for (int i = 0; i < numChars; ++i)
  2956. {
  2957. const char c = (char) srcChars[i];
  2958. for (int j = 0; j < 64; ++j)
  2959. {
  2960. if (encodingTable[j] == c)
  2961. {
  2962. setBitRange (pos, 6, j);
  2963. pos += 6;
  2964. break;
  2965. }
  2966. }
  2967. }
  2968. return true;
  2969. }
  2970. END_JUCE_NAMESPACE
  2971. /*** End of inlined file: juce_MemoryBlock.cpp ***/
  2972. /*** Start of inlined file: juce_PropertySet.cpp ***/
  2973. BEGIN_JUCE_NAMESPACE
  2974. PropertySet::PropertySet (const bool ignoreCaseOfKeyNames) throw()
  2975. : properties (ignoreCaseOfKeyNames),
  2976. fallbackProperties (0),
  2977. ignoreCaseOfKeys (ignoreCaseOfKeyNames)
  2978. {
  2979. }
  2980. PropertySet::PropertySet (const PropertySet& other) throw()
  2981. : properties (other.properties),
  2982. fallbackProperties (other.fallbackProperties),
  2983. ignoreCaseOfKeys (other.ignoreCaseOfKeys)
  2984. {
  2985. }
  2986. PropertySet& PropertySet::operator= (const PropertySet& other) throw()
  2987. {
  2988. properties = other.properties;
  2989. fallbackProperties = other.fallbackProperties;
  2990. ignoreCaseOfKeys = other.ignoreCaseOfKeys;
  2991. propertyChanged();
  2992. return *this;
  2993. }
  2994. PropertySet::~PropertySet()
  2995. {
  2996. }
  2997. void PropertySet::clear()
  2998. {
  2999. const ScopedLock sl (lock);
  3000. if (properties.size() > 0)
  3001. {
  3002. properties.clear();
  3003. propertyChanged();
  3004. }
  3005. }
  3006. const String PropertySet::getValue (const String& keyName,
  3007. const String& defaultValue) const throw()
  3008. {
  3009. const ScopedLock sl (lock);
  3010. const int index = properties.getAllKeys().indexOf (keyName, ignoreCaseOfKeys);
  3011. if (index >= 0)
  3012. return properties.getAllValues() [index];
  3013. return fallbackProperties != 0 ? fallbackProperties->getValue (keyName, defaultValue)
  3014. : defaultValue;
  3015. }
  3016. int PropertySet::getIntValue (const String& keyName,
  3017. const int defaultValue) const throw()
  3018. {
  3019. const ScopedLock sl (lock);
  3020. const int index = properties.getAllKeys().indexOf (keyName, ignoreCaseOfKeys);
  3021. if (index >= 0)
  3022. return properties.getAllValues() [index].getIntValue();
  3023. return fallbackProperties != 0 ? fallbackProperties->getIntValue (keyName, defaultValue)
  3024. : defaultValue;
  3025. }
  3026. double PropertySet::getDoubleValue (const String& keyName,
  3027. const double defaultValue) const throw()
  3028. {
  3029. const ScopedLock sl (lock);
  3030. const int index = properties.getAllKeys().indexOf (keyName, ignoreCaseOfKeys);
  3031. if (index >= 0)
  3032. return properties.getAllValues()[index].getDoubleValue();
  3033. return fallbackProperties != 0 ? fallbackProperties->getDoubleValue (keyName, defaultValue)
  3034. : defaultValue;
  3035. }
  3036. bool PropertySet::getBoolValue (const String& keyName,
  3037. const bool defaultValue) const throw()
  3038. {
  3039. const ScopedLock sl (lock);
  3040. const int index = properties.getAllKeys().indexOf (keyName, ignoreCaseOfKeys);
  3041. if (index >= 0)
  3042. return properties.getAllValues() [index].getIntValue() != 0;
  3043. return fallbackProperties != 0 ? fallbackProperties->getBoolValue (keyName, defaultValue)
  3044. : defaultValue;
  3045. }
  3046. XmlElement* PropertySet::getXmlValue (const String& keyName) const
  3047. {
  3048. XmlDocument doc (getValue (keyName));
  3049. return doc.getDocumentElement();
  3050. }
  3051. void PropertySet::setValue (const String& keyName,
  3052. const String& value) throw()
  3053. {
  3054. jassert (keyName.isNotEmpty()); // shouldn't use an empty key name!
  3055. if (keyName.isNotEmpty())
  3056. {
  3057. const ScopedLock sl (lock);
  3058. const int index = properties.getAllKeys().indexOf (keyName, ignoreCaseOfKeys);
  3059. if (index < 0 || properties.getAllValues() [index] != value)
  3060. {
  3061. properties.set (keyName, value);
  3062. propertyChanged();
  3063. }
  3064. }
  3065. }
  3066. void PropertySet::removeValue (const String& keyName) throw()
  3067. {
  3068. if (keyName.isNotEmpty())
  3069. {
  3070. const ScopedLock sl (lock);
  3071. const int index = properties.getAllKeys().indexOf (keyName, ignoreCaseOfKeys);
  3072. if (index >= 0)
  3073. {
  3074. properties.remove (keyName);
  3075. propertyChanged();
  3076. }
  3077. }
  3078. }
  3079. void PropertySet::setValue (const String& keyName, const int value) throw()
  3080. {
  3081. setValue (keyName, String (value));
  3082. }
  3083. void PropertySet::setValue (const String& keyName, const double value) throw()
  3084. {
  3085. setValue (keyName, String (value));
  3086. }
  3087. void PropertySet::setValue (const String& keyName, const bool value) throw()
  3088. {
  3089. setValue (keyName, String (value ? "1" : "0"));
  3090. }
  3091. void PropertySet::setValue (const String& keyName, const XmlElement* const xml)
  3092. {
  3093. setValue (keyName, (xml == 0) ? String::empty
  3094. : xml->createDocument (String::empty, true));
  3095. }
  3096. bool PropertySet::containsKey (const String& keyName) const throw()
  3097. {
  3098. const ScopedLock sl (lock);
  3099. return properties.getAllKeys().contains (keyName, ignoreCaseOfKeys);
  3100. }
  3101. void PropertySet::setFallbackPropertySet (PropertySet* fallbackProperties_) throw()
  3102. {
  3103. const ScopedLock sl (lock);
  3104. fallbackProperties = fallbackProperties_;
  3105. }
  3106. XmlElement* PropertySet::createXml (const String& nodeName) const throw()
  3107. {
  3108. const ScopedLock sl (lock);
  3109. XmlElement* const xml = new XmlElement (nodeName);
  3110. for (int i = 0; i < properties.getAllKeys().size(); ++i)
  3111. {
  3112. XmlElement* const e = xml->createNewChildElement ("VALUE");
  3113. e->setAttribute ("name", properties.getAllKeys()[i]);
  3114. e->setAttribute ("val", properties.getAllValues()[i]);
  3115. }
  3116. return xml;
  3117. }
  3118. void PropertySet::restoreFromXml (const XmlElement& xml) throw()
  3119. {
  3120. const ScopedLock sl (lock);
  3121. clear();
  3122. forEachXmlChildElementWithTagName (xml, e, "VALUE")
  3123. {
  3124. if (e->hasAttribute ("name")
  3125. && e->hasAttribute ("val"))
  3126. {
  3127. properties.set (e->getStringAttribute ("name"),
  3128. e->getStringAttribute ("val"));
  3129. }
  3130. }
  3131. if (properties.size() > 0)
  3132. propertyChanged();
  3133. }
  3134. void PropertySet::propertyChanged()
  3135. {
  3136. }
  3137. END_JUCE_NAMESPACE
  3138. /*** End of inlined file: juce_PropertySet.cpp ***/
  3139. /*** Start of inlined file: juce_Variant.cpp ***/
  3140. BEGIN_JUCE_NAMESPACE
  3141. var::var() throw()
  3142. : type (voidType)
  3143. {
  3144. value.doubleValue = 0;
  3145. }
  3146. var::~var() throw()
  3147. {
  3148. if (type == stringType)
  3149. delete value.stringValue;
  3150. else if (type == objectType && value.objectValue != 0)
  3151. value.objectValue->decReferenceCount();
  3152. }
  3153. const var var::null;
  3154. var::var (const var& valueToCopy)
  3155. : type (valueToCopy.type),
  3156. value (valueToCopy.value)
  3157. {
  3158. if (type == stringType)
  3159. value.stringValue = new String (*(value.stringValue));
  3160. else if (type == objectType && value.objectValue != 0)
  3161. value.objectValue->incReferenceCount();
  3162. }
  3163. var::var (const int value_) throw()
  3164. : type (intType)
  3165. {
  3166. value.intValue = value_;
  3167. }
  3168. var::var (const bool value_) throw()
  3169. : type (boolType)
  3170. {
  3171. value.boolValue = value_;
  3172. }
  3173. var::var (const double value_) throw()
  3174. : type (doubleType)
  3175. {
  3176. value.doubleValue = value_;
  3177. }
  3178. var::var (const String& value_)
  3179. : type (stringType)
  3180. {
  3181. value.stringValue = new String (value_);
  3182. }
  3183. var::var (const char* const value_)
  3184. : type (stringType)
  3185. {
  3186. value.stringValue = new String (value_);
  3187. }
  3188. var::var (const juce_wchar* const value_)
  3189. : type (stringType)
  3190. {
  3191. value.stringValue = new String (value_);
  3192. }
  3193. var::var (DynamicObject* const object)
  3194. : type (objectType)
  3195. {
  3196. value.objectValue = object;
  3197. if (object != 0)
  3198. object->incReferenceCount();
  3199. }
  3200. var::var (MethodFunction method_) throw()
  3201. : type (methodType)
  3202. {
  3203. value.methodValue = method_;
  3204. }
  3205. void var::swapWith (var& other) throw()
  3206. {
  3207. swapVariables (type, other.type);
  3208. swapVariables (value, other.value);
  3209. }
  3210. var& var::operator= (const var& value_) { var newValue (value_); swapWith (newValue); return *this; }
  3211. var& var::operator= (int value_) { var newValue (value_); swapWith (newValue); return *this; }
  3212. var& var::operator= (bool value_) { var newValue (value_); swapWith (newValue); return *this; }
  3213. var& var::operator= (double value_) { var newValue (value_); swapWith (newValue); return *this; }
  3214. var& var::operator= (const char* value_) { var newValue (value_); swapWith (newValue); return *this; }
  3215. var& var::operator= (const juce_wchar* value_) { var newValue (value_); swapWith (newValue); return *this; }
  3216. var& var::operator= (const String& value_) { var newValue (value_); swapWith (newValue); return *this; }
  3217. var& var::operator= (DynamicObject* value_) { var newValue (value_); swapWith (newValue); return *this; }
  3218. var& var::operator= (MethodFunction value_) { var newValue (value_); swapWith (newValue); return *this; }
  3219. var::operator int() const
  3220. {
  3221. switch (type)
  3222. {
  3223. case voidType: break;
  3224. case intType: return value.intValue;
  3225. case boolType: return value.boolValue ? 1 : 0;
  3226. case doubleType: return static_cast <int> (value.doubleValue);
  3227. case stringType: return value.stringValue->getIntValue();
  3228. case objectType: break;
  3229. default: jassertfalse; break;
  3230. }
  3231. return 0;
  3232. }
  3233. var::operator bool() const
  3234. {
  3235. switch (type)
  3236. {
  3237. case voidType: break;
  3238. case intType: return value.intValue != 0;
  3239. case boolType: return value.boolValue;
  3240. case doubleType: return value.doubleValue != 0;
  3241. case stringType: return value.stringValue->getIntValue() != 0
  3242. || value.stringValue->trim().equalsIgnoreCase ("true")
  3243. || value.stringValue->trim().equalsIgnoreCase ("yes");
  3244. case objectType: return value.objectValue != 0;
  3245. default: jassertfalse; break;
  3246. }
  3247. return false;
  3248. }
  3249. var::operator float() const
  3250. {
  3251. return (float) operator double();
  3252. }
  3253. var::operator double() const
  3254. {
  3255. switch (type)
  3256. {
  3257. case voidType: break;
  3258. case intType: return value.intValue;
  3259. case boolType: return value.boolValue ? 1.0 : 0.0;
  3260. case doubleType: return value.doubleValue;
  3261. case stringType: return value.stringValue->getDoubleValue();
  3262. case objectType: break;
  3263. default: jassertfalse; break;
  3264. }
  3265. return 0.0;
  3266. }
  3267. const String var::toString() const
  3268. {
  3269. switch (type)
  3270. {
  3271. case voidType: return String::empty;
  3272. case intType: return String (value.intValue);
  3273. case boolType: return String::charToString (value.boolValue ? '1' : '0');
  3274. case doubleType: return String (value.doubleValue);
  3275. case stringType: return *(value.stringValue);
  3276. case objectType: return "Object 0x" + String::toHexString ((int) (pointer_sized_int) value.objectValue);
  3277. case methodType: return "Method";
  3278. default: jassertfalse; break;
  3279. }
  3280. return String::empty;
  3281. }
  3282. var::operator const String() const
  3283. {
  3284. return toString();
  3285. }
  3286. DynamicObject* var::getObject() const
  3287. {
  3288. return type == objectType ? value.objectValue : 0;
  3289. }
  3290. bool var::equals (const var& other) const throw()
  3291. {
  3292. switch (type)
  3293. {
  3294. case voidType: return other.isVoid();
  3295. case intType: return value.intValue == static_cast <int> (other);
  3296. case boolType: return value.boolValue == static_cast <bool> (other);
  3297. case doubleType: return value.doubleValue == static_cast <double> (other);
  3298. case stringType: return (*(value.stringValue)) == other.toString();
  3299. case objectType: return value.objectValue == other.getObject();
  3300. case methodType: return value.methodValue == other.value.methodValue && other.isMethod();
  3301. default: jassertfalse; break;
  3302. }
  3303. return false;
  3304. }
  3305. bool operator== (const var& v1, const var& v2) throw() { return v1.equals (v2); }
  3306. bool operator!= (const var& v1, const var& v2) throw() { return ! v1.equals (v2); }
  3307. bool operator== (const var& v1, const String& v2) throw() { return v1.toString() == v2; }
  3308. bool operator!= (const var& v1, const String& v2) throw() { return v1.toString() != v2; }
  3309. void var::writeToStream (OutputStream& output) const
  3310. {
  3311. switch (type)
  3312. {
  3313. case voidType: output.writeCompressedInt (0); break;
  3314. case intType: output.writeCompressedInt (5); output.writeByte (1); output.writeInt (value.intValue); break;
  3315. case boolType: output.writeCompressedInt (1); output.writeByte (value.boolValue ? 2 : 3); break;
  3316. case doubleType: output.writeCompressedInt (9); output.writeByte (4); output.writeDouble (value.doubleValue); break;
  3317. case stringType:
  3318. {
  3319. const int len = value.stringValue->getNumBytesAsUTF8() + 1;
  3320. output.writeCompressedInt (len + 1);
  3321. output.writeByte (5);
  3322. HeapBlock<char> temp (len);
  3323. value.stringValue->copyToUTF8 (temp, len);
  3324. output.write (temp, len);
  3325. break;
  3326. }
  3327. case objectType:
  3328. case methodType: output.writeCompressedInt (0); jassertfalse; break; // Can't write an object to a stream!
  3329. default: jassertfalse; break; // Is this a corrupted object?
  3330. }
  3331. }
  3332. const var var::readFromStream (InputStream& input)
  3333. {
  3334. const int numBytes = input.readCompressedInt();
  3335. if (numBytes > 0)
  3336. {
  3337. switch (input.readByte())
  3338. {
  3339. case 1: return var (input.readInt());
  3340. case 2: return var (true);
  3341. case 3: return var (false);
  3342. case 4: return var (input.readDouble());
  3343. case 5:
  3344. {
  3345. MemoryBlock mb;
  3346. input.readIntoMemoryBlock (mb, numBytes - 1);
  3347. return var (String::fromUTF8 (static_cast <const char*> (mb.getData()), (int) mb.getSize()));
  3348. }
  3349. default: input.skipNextBytes (numBytes - 1); break;
  3350. }
  3351. }
  3352. return var::null;
  3353. }
  3354. const var var::operator[] (const var::identifier& propertyName) const
  3355. {
  3356. if (type == objectType && value.objectValue != 0)
  3357. return value.objectValue->getProperty (propertyName);
  3358. return var::null;
  3359. }
  3360. const var var::invoke (const var::identifier& method, const var* arguments, int numArguments) const
  3361. {
  3362. if (type == objectType && value.objectValue != 0)
  3363. return value.objectValue->invokeMethod (method, arguments, numArguments);
  3364. return var::null;
  3365. }
  3366. const var var::invoke (const var& targetObject, const var* arguments, int numArguments) const
  3367. {
  3368. if (isMethod())
  3369. {
  3370. DynamicObject* const target = targetObject.getObject();
  3371. if (target != 0)
  3372. return (target->*(value.methodValue)) (arguments, numArguments);
  3373. }
  3374. return var::null;
  3375. }
  3376. const var var::call (const var::identifier& method) const
  3377. {
  3378. return invoke (method, 0, 0);
  3379. }
  3380. const var var::call (const var::identifier& method, const var& arg1) const
  3381. {
  3382. return invoke (method, &arg1, 1);
  3383. }
  3384. const var var::call (const var::identifier& method, const var& arg1, const var& arg2) const
  3385. {
  3386. var args[] = { arg1, arg2 };
  3387. return invoke (method, args, 2);
  3388. }
  3389. const var var::call (const var::identifier& method, const var& arg1, const var& arg2, const var& arg3)
  3390. {
  3391. var args[] = { arg1, arg2, arg3 };
  3392. return invoke (method, args, 3);
  3393. }
  3394. const var var::call (const var::identifier& method, const var& arg1, const var& arg2, const var& arg3, const var& arg4) const
  3395. {
  3396. var args[] = { arg1, arg2, arg3, arg4 };
  3397. return invoke (method, args, 4);
  3398. }
  3399. const var var::call (const var::identifier& method, const var& arg1, const var& arg2, const var& arg3, const var& arg4, const var& arg5) const
  3400. {
  3401. var args[] = { arg1, arg2, arg3, arg4, arg5 };
  3402. return invoke (method, args, 5);
  3403. }
  3404. var::identifier::identifier() throw()
  3405. : hashCode (0)
  3406. {
  3407. }
  3408. var::identifier::identifier (const String& name_)
  3409. : name (name_),
  3410. hashCode (name_.hashCode())
  3411. {
  3412. /* An identifier string must be suitable for use as a script variable or XML
  3413. attribute, so it can only contain this limited set of characters.. */
  3414. jassert (name.containsOnly ("abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789_") && name.isNotEmpty());
  3415. }
  3416. var::identifier::identifier (const char* const name_)
  3417. : name (name_),
  3418. hashCode (name.hashCode())
  3419. {
  3420. /* An identifier string must be suitable for use as a script variable or XML
  3421. attribute, so it can only contain this limited set of characters.. */
  3422. jassert (name.containsOnly ("abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789_") && name.isNotEmpty());
  3423. }
  3424. var::identifier::~identifier()
  3425. {
  3426. }
  3427. END_JUCE_NAMESPACE
  3428. /*** End of inlined file: juce_Variant.cpp ***/
  3429. /*** Start of inlined file: juce_NamedValueSet.cpp ***/
  3430. BEGIN_JUCE_NAMESPACE
  3431. NamedValueSet::NamedValue::NamedValue() throw()
  3432. {
  3433. }
  3434. inline NamedValueSet::NamedValue::NamedValue (const var::identifier& name_, const var& value_)
  3435. : name (name_), value (value_)
  3436. {
  3437. }
  3438. NamedValueSet::NamedValueSet() throw()
  3439. {
  3440. }
  3441. NamedValueSet::NamedValueSet (const NamedValueSet& other)
  3442. : values (other.values)
  3443. {
  3444. }
  3445. NamedValueSet& NamedValueSet::operator= (const NamedValueSet& other)
  3446. {
  3447. values = other.values;
  3448. return *this;
  3449. }
  3450. NamedValueSet::~NamedValueSet()
  3451. {
  3452. }
  3453. int NamedValueSet::size() const throw()
  3454. {
  3455. return values.size();
  3456. }
  3457. const var& NamedValueSet::operator[] (const var::identifier& name) const
  3458. {
  3459. for (int i = values.size(); --i >= 0;)
  3460. {
  3461. const NamedValue& v = values.getReference(i);
  3462. if (v.name == name)
  3463. return v.value;
  3464. }
  3465. return var::null;
  3466. }
  3467. const var NamedValueSet::getWithDefault (const var::identifier& name, const var& defaultReturnValue) const
  3468. {
  3469. const var* v = getItem (name);
  3470. return v != 0 ? *v : defaultReturnValue;
  3471. }
  3472. var* NamedValueSet::getItem (const var::identifier& name) const
  3473. {
  3474. for (int i = values.size(); --i >= 0;)
  3475. {
  3476. NamedValue& v = values.getReference(i);
  3477. if (v.name == name)
  3478. return &(v.value);
  3479. }
  3480. return 0;
  3481. }
  3482. bool NamedValueSet::set (const var::identifier& name, const var& newValue)
  3483. {
  3484. for (int i = values.size(); --i >= 0;)
  3485. {
  3486. NamedValue& v = values.getReference(i);
  3487. if (v.name == name)
  3488. {
  3489. if (v.value == newValue)
  3490. return false;
  3491. v.value = newValue;
  3492. return true;
  3493. }
  3494. }
  3495. values.add (NamedValue (name, newValue));
  3496. return true;
  3497. }
  3498. bool NamedValueSet::contains (const var::identifier& name) const
  3499. {
  3500. return getItem (name) != 0;
  3501. }
  3502. bool NamedValueSet::remove (const var::identifier& name)
  3503. {
  3504. for (int i = values.size(); --i >= 0;)
  3505. {
  3506. if (values.getReference(i).name == name)
  3507. {
  3508. values.remove (i);
  3509. return true;
  3510. }
  3511. }
  3512. return false;
  3513. }
  3514. const var::identifier NamedValueSet::getName (int index) const
  3515. {
  3516. jassert (((unsigned int) index) < (unsigned int) values.size());
  3517. return values [index].name;
  3518. }
  3519. void NamedValueSet::clear()
  3520. {
  3521. values.clear();
  3522. }
  3523. END_JUCE_NAMESPACE
  3524. /*** End of inlined file: juce_NamedValueSet.cpp ***/
  3525. /*** Start of inlined file: juce_DynamicObject.cpp ***/
  3526. BEGIN_JUCE_NAMESPACE
  3527. DynamicObject::DynamicObject()
  3528. {
  3529. }
  3530. DynamicObject::~DynamicObject()
  3531. {
  3532. }
  3533. bool DynamicObject::hasProperty (const var::identifier& propertyName) const
  3534. {
  3535. var* const v = properties.getItem (propertyName);
  3536. return v != 0 && ! v->isMethod();
  3537. }
  3538. const var DynamicObject::getProperty (const var::identifier& propertyName) const
  3539. {
  3540. return properties [propertyName];
  3541. }
  3542. void DynamicObject::setProperty (const var::identifier& propertyName, const var& newValue)
  3543. {
  3544. properties.set (propertyName, newValue);
  3545. }
  3546. void DynamicObject::removeProperty (const var::identifier& propertyName)
  3547. {
  3548. properties.remove (propertyName);
  3549. }
  3550. bool DynamicObject::hasMethod (const var::identifier& methodName) const
  3551. {
  3552. return getProperty (methodName).isMethod();
  3553. }
  3554. const var DynamicObject::invokeMethod (const var::identifier& methodName,
  3555. const var* parameters,
  3556. int numParameters)
  3557. {
  3558. return properties [methodName].invoke (var (this), parameters, numParameters);
  3559. }
  3560. void DynamicObject::setMethod (const var::identifier& name,
  3561. var::MethodFunction methodFunction)
  3562. {
  3563. properties.set (name, var (methodFunction));
  3564. }
  3565. void DynamicObject::clear()
  3566. {
  3567. properties.clear();
  3568. }
  3569. END_JUCE_NAMESPACE
  3570. /*** End of inlined file: juce_DynamicObject.cpp ***/
  3571. /*** Start of inlined file: juce_BlowFish.cpp ***/
  3572. BEGIN_JUCE_NAMESPACE
  3573. BlowFish::BlowFish (const void* const keyData, const int keyBytes)
  3574. {
  3575. jassert (keyData != 0);
  3576. jassert (keyBytes > 0);
  3577. static const uint32 initialPValues [18] =
  3578. {
  3579. 0x243f6a88, 0x85a308d3, 0x13198a2e, 0x03707344, 0xa4093822, 0x299f31d0, 0x082efa98, 0xec4e6c89,
  3580. 0x452821e6, 0x38d01377, 0xbe5466cf, 0x34e90c6c, 0xc0ac29b7, 0xc97c50dd, 0x3f84d5b5, 0xb5470917,
  3581. 0x9216d5d9, 0x8979fb1b
  3582. };
  3583. static const uint32 initialSValues [4 * 256] =
  3584. {
  3585. 0xd1310ba6, 0x98dfb5ac, 0x2ffd72db, 0xd01adfb7, 0xb8e1afed, 0x6a267e96, 0xba7c9045, 0xf12c7f99,
  3586. 0x24a19947, 0xb3916cf7, 0x0801f2e2, 0x858efc16, 0x636920d8, 0x71574e69, 0xa458fea3, 0xf4933d7e,
  3587. 0x0d95748f, 0x728eb658, 0x718bcd58, 0x82154aee, 0x7b54a41d, 0xc25a59b5, 0x9c30d539, 0x2af26013,
  3588. 0xc5d1b023, 0x286085f0, 0xca417918, 0xb8db38ef, 0x8e79dcb0, 0x603a180e, 0x6c9e0e8b, 0xb01e8a3e,
  3589. 0xd71577c1, 0xbd314b27, 0x78af2fda, 0x55605c60, 0xe65525f3, 0xaa55ab94, 0x57489862, 0x63e81440,
  3590. 0x55ca396a, 0x2aab10b6, 0xb4cc5c34, 0x1141e8ce, 0xa15486af, 0x7c72e993, 0xb3ee1411, 0x636fbc2a,
  3591. 0x2ba9c55d, 0x741831f6, 0xce5c3e16, 0x9b87931e, 0xafd6ba33, 0x6c24cf5c, 0x7a325381, 0x28958677,
  3592. 0x3b8f4898, 0x6b4bb9af, 0xc4bfe81b, 0x66282193, 0x61d809cc, 0xfb21a991, 0x487cac60, 0x5dec8032,
  3593. 0xef845d5d, 0xe98575b1, 0xdc262302, 0xeb651b88, 0x23893e81, 0xd396acc5, 0x0f6d6ff3, 0x83f44239,
  3594. 0x2e0b4482, 0xa4842004, 0x69c8f04a, 0x9e1f9b5e, 0x21c66842, 0xf6e96c9a, 0x670c9c61, 0xabd388f0,
  3595. 0x6a51a0d2, 0xd8542f68, 0x960fa728, 0xab5133a3, 0x6eef0b6c, 0x137a3be4, 0xba3bf050, 0x7efb2a98,
  3596. 0xa1f1651d, 0x39af0176, 0x66ca593e, 0x82430e88, 0x8cee8619, 0x456f9fb4, 0x7d84a5c3, 0x3b8b5ebe,
  3597. 0xe06f75d8, 0x85c12073, 0x401a449f, 0x56c16aa6, 0x4ed3aa62, 0x363f7706, 0x1bfedf72, 0x429b023d,
  3598. 0x37d0d724, 0xd00a1248, 0xdb0fead3, 0x49f1c09b, 0x075372c9, 0x80991b7b, 0x25d479d8, 0xf6e8def7,
  3599. 0xe3fe501a, 0xb6794c3b, 0x976ce0bd, 0x04c006ba, 0xc1a94fb6, 0x409f60c4, 0x5e5c9ec2, 0x196a2463,
  3600. 0x68fb6faf, 0x3e6c53b5, 0x1339b2eb, 0x3b52ec6f, 0x6dfc511f, 0x9b30952c, 0xcc814544, 0xaf5ebd09,
  3601. 0xbee3d004, 0xde334afd, 0x660f2807, 0x192e4bb3, 0xc0cba857, 0x45c8740f, 0xd20b5f39, 0xb9d3fbdb,
  3602. 0x5579c0bd, 0x1a60320a, 0xd6a100c6, 0x402c7279, 0x679f25fe, 0xfb1fa3cc, 0x8ea5e9f8, 0xdb3222f8,
  3603. 0x3c7516df, 0xfd616b15, 0x2f501ec8, 0xad0552ab, 0x323db5fa, 0xfd238760, 0x53317b48, 0x3e00df82,
  3604. 0x9e5c57bb, 0xca6f8ca0, 0x1a87562e, 0xdf1769db, 0xd542a8f6, 0x287effc3, 0xac6732c6, 0x8c4f5573,
  3605. 0x695b27b0, 0xbbca58c8, 0xe1ffa35d, 0xb8f011a0, 0x10fa3d98, 0xfd2183b8, 0x4afcb56c, 0x2dd1d35b,
  3606. 0x9a53e479, 0xb6f84565, 0xd28e49bc, 0x4bfb9790, 0xe1ddf2da, 0xa4cb7e33, 0x62fb1341, 0xcee4c6e8,
  3607. 0xef20cada, 0x36774c01, 0xd07e9efe, 0x2bf11fb4, 0x95dbda4d, 0xae909198, 0xeaad8e71, 0x6b93d5a0,
  3608. 0xd08ed1d0, 0xafc725e0, 0x8e3c5b2f, 0x8e7594b7, 0x8ff6e2fb, 0xf2122b64, 0x8888b812, 0x900df01c,
  3609. 0x4fad5ea0, 0x688fc31c, 0xd1cff191, 0xb3a8c1ad, 0x2f2f2218, 0xbe0e1777, 0xea752dfe, 0x8b021fa1,
  3610. 0xe5a0cc0f, 0xb56f74e8, 0x18acf3d6, 0xce89e299, 0xb4a84fe0, 0xfd13e0b7, 0x7cc43b81, 0xd2ada8d9,
  3611. 0x165fa266, 0x80957705, 0x93cc7314, 0x211a1477, 0xe6ad2065, 0x77b5fa86, 0xc75442f5, 0xfb9d35cf,
  3612. 0xebcdaf0c, 0x7b3e89a0, 0xd6411bd3, 0xae1e7e49, 0x00250e2d, 0x2071b35e, 0x226800bb, 0x57b8e0af,
  3613. 0x2464369b, 0xf009b91e, 0x5563911d, 0x59dfa6aa, 0x78c14389, 0xd95a537f, 0x207d5ba2, 0x02e5b9c5,
  3614. 0x83260376, 0x6295cfa9, 0x11c81968, 0x4e734a41, 0xb3472dca, 0x7b14a94a, 0x1b510052, 0x9a532915,
  3615. 0xd60f573f, 0xbc9bc6e4, 0x2b60a476, 0x81e67400, 0x08ba6fb5, 0x571be91f, 0xf296ec6b, 0x2a0dd915,
  3616. 0xb6636521, 0xe7b9f9b6, 0xff34052e, 0xc5855664, 0x53b02d5d, 0xa99f8fa1, 0x08ba4799, 0x6e85076a,
  3617. 0x4b7a70e9, 0xb5b32944, 0xdb75092e, 0xc4192623, 0xad6ea6b0, 0x49a7df7d, 0x9cee60b8, 0x8fedb266,
  3618. 0xecaa8c71, 0x699a17ff, 0x5664526c, 0xc2b19ee1, 0x193602a5, 0x75094c29, 0xa0591340, 0xe4183a3e,
  3619. 0x3f54989a, 0x5b429d65, 0x6b8fe4d6, 0x99f73fd6, 0xa1d29c07, 0xefe830f5, 0x4d2d38e6, 0xf0255dc1,
  3620. 0x4cdd2086, 0x8470eb26, 0x6382e9c6, 0x021ecc5e, 0x09686b3f, 0x3ebaefc9, 0x3c971814, 0x6b6a70a1,
  3621. 0x687f3584, 0x52a0e286, 0xb79c5305, 0xaa500737, 0x3e07841c, 0x7fdeae5c, 0x8e7d44ec, 0x5716f2b8,
  3622. 0xb03ada37, 0xf0500c0d, 0xf01c1f04, 0x0200b3ff, 0xae0cf51a, 0x3cb574b2, 0x25837a58, 0xdc0921bd,
  3623. 0xd19113f9, 0x7ca92ff6, 0x94324773, 0x22f54701, 0x3ae5e581, 0x37c2dadc, 0xc8b57634, 0x9af3dda7,
  3624. 0xa9446146, 0x0fd0030e, 0xecc8c73e, 0xa4751e41, 0xe238cd99, 0x3bea0e2f, 0x3280bba1, 0x183eb331,
  3625. 0x4e548b38, 0x4f6db908, 0x6f420d03, 0xf60a04bf, 0x2cb81290, 0x24977c79, 0x5679b072, 0xbcaf89af,
  3626. 0xde9a771f, 0xd9930810, 0xb38bae12, 0xdccf3f2e, 0x5512721f, 0x2e6b7124, 0x501adde6, 0x9f84cd87,
  3627. 0x7a584718, 0x7408da17, 0xbc9f9abc, 0xe94b7d8c, 0xec7aec3a, 0xdb851dfa, 0x63094366, 0xc464c3d2,
  3628. 0xef1c1847, 0x3215d908, 0xdd433b37, 0x24c2ba16, 0x12a14d43, 0x2a65c451, 0x50940002, 0x133ae4dd,
  3629. 0x71dff89e, 0x10314e55, 0x81ac77d6, 0x5f11199b, 0x043556f1, 0xd7a3c76b, 0x3c11183b, 0x5924a509,
  3630. 0xf28fe6ed, 0x97f1fbfa, 0x9ebabf2c, 0x1e153c6e, 0x86e34570, 0xeae96fb1, 0x860e5e0a, 0x5a3e2ab3,
  3631. 0x771fe71c, 0x4e3d06fa, 0x2965dcb9, 0x99e71d0f, 0x803e89d6, 0x5266c825, 0x2e4cc978, 0x9c10b36a,
  3632. 0xc6150eba, 0x94e2ea78, 0xa5fc3c53, 0x1e0a2df4, 0xf2f74ea7, 0x361d2b3d, 0x1939260f, 0x19c27960,
  3633. 0x5223a708, 0xf71312b6, 0xebadfe6e, 0xeac31f66, 0xe3bc4595, 0xa67bc883, 0xb17f37d1, 0x018cff28,
  3634. 0xc332ddef, 0xbe6c5aa5, 0x65582185, 0x68ab9802, 0xeecea50f, 0xdb2f953b, 0x2aef7dad, 0x5b6e2f84,
  3635. 0x1521b628, 0x29076170, 0xecdd4775, 0x619f1510, 0x13cca830, 0xeb61bd96, 0x0334fe1e, 0xaa0363cf,
  3636. 0xb5735c90, 0x4c70a239, 0xd59e9e0b, 0xcbaade14, 0xeecc86bc, 0x60622ca7, 0x9cab5cab, 0xb2f3846e,
  3637. 0x648b1eaf, 0x19bdf0ca, 0xa02369b9, 0x655abb50, 0x40685a32, 0x3c2ab4b3, 0x319ee9d5, 0xc021b8f7,
  3638. 0x9b540b19, 0x875fa099, 0x95f7997e, 0x623d7da8, 0xf837889a, 0x97e32d77, 0x11ed935f, 0x16681281,
  3639. 0x0e358829, 0xc7e61fd6, 0x96dedfa1, 0x7858ba99, 0x57f584a5, 0x1b227263, 0x9b83c3ff, 0x1ac24696,
  3640. 0xcdb30aeb, 0x532e3054, 0x8fd948e4, 0x6dbc3128, 0x58ebf2ef, 0x34c6ffea, 0xfe28ed61, 0xee7c3c73,
  3641. 0x5d4a14d9, 0xe864b7e3, 0x42105d14, 0x203e13e0, 0x45eee2b6, 0xa3aaabea, 0xdb6c4f15, 0xfacb4fd0,
  3642. 0xc742f442, 0xef6abbb5, 0x654f3b1d, 0x41cd2105, 0xd81e799e, 0x86854dc7, 0xe44b476a, 0x3d816250,
  3643. 0xcf62a1f2, 0x5b8d2646, 0xfc8883a0, 0xc1c7b6a3, 0x7f1524c3, 0x69cb7492, 0x47848a0b, 0x5692b285,
  3644. 0x095bbf00, 0xad19489d, 0x1462b174, 0x23820e00, 0x58428d2a, 0x0c55f5ea, 0x1dadf43e, 0x233f7061,
  3645. 0x3372f092, 0x8d937e41, 0xd65fecf1, 0x6c223bdb, 0x7cde3759, 0xcbee7460, 0x4085f2a7, 0xce77326e,
  3646. 0xa6078084, 0x19f8509e, 0xe8efd855, 0x61d99735, 0xa969a7aa, 0xc50c06c2, 0x5a04abfc, 0x800bcadc,
  3647. 0x9e447a2e, 0xc3453484, 0xfdd56705, 0x0e1e9ec9, 0xdb73dbd3, 0x105588cd, 0x675fda79, 0xe3674340,
  3648. 0xc5c43465, 0x713e38d8, 0x3d28f89e, 0xf16dff20, 0x153e21e7, 0x8fb03d4a, 0xe6e39f2b, 0xdb83adf7,
  3649. 0xe93d5a68, 0x948140f7, 0xf64c261c, 0x94692934, 0x411520f7, 0x7602d4f7, 0xbcf46b2e, 0xd4a20068,
  3650. 0xd4082471, 0x3320f46a, 0x43b7d4b7, 0x500061af, 0x1e39f62e, 0x97244546, 0x14214f74, 0xbf8b8840,
  3651. 0x4d95fc1d, 0x96b591af, 0x70f4ddd3, 0x66a02f45, 0xbfbc09ec, 0x03bd9785, 0x7fac6dd0, 0x31cb8504,
  3652. 0x96eb27b3, 0x55fd3941, 0xda2547e6, 0xabca0a9a, 0x28507825, 0x530429f4, 0x0a2c86da, 0xe9b66dfb,
  3653. 0x68dc1462, 0xd7486900, 0x680ec0a4, 0x27a18dee, 0x4f3ffea2, 0xe887ad8c, 0xb58ce006, 0x7af4d6b6,
  3654. 0xaace1e7c, 0xd3375fec, 0xce78a399, 0x406b2a42, 0x20fe9e35, 0xd9f385b9, 0xee39d7ab, 0x3b124e8b,
  3655. 0x1dc9faf7, 0x4b6d1856, 0x26a36631, 0xeae397b2, 0x3a6efa74, 0xdd5b4332, 0x6841e7f7, 0xca7820fb,
  3656. 0xfb0af54e, 0xd8feb397, 0x454056ac, 0xba489527, 0x55533a3a, 0x20838d87, 0xfe6ba9b7, 0xd096954b,
  3657. 0x55a867bc, 0xa1159a58, 0xcca92963, 0x99e1db33, 0xa62a4a56, 0x3f3125f9, 0x5ef47e1c, 0x9029317c,
  3658. 0xfdf8e802, 0x04272f70, 0x80bb155c, 0x05282ce3, 0x95c11548, 0xe4c66d22, 0x48c1133f, 0xc70f86dc,
  3659. 0x07f9c9ee, 0x41041f0f, 0x404779a4, 0x5d886e17, 0x325f51eb, 0xd59bc0d1, 0xf2bcc18f, 0x41113564,
  3660. 0x257b7834, 0x602a9c60, 0xdff8e8a3, 0x1f636c1b, 0x0e12b4c2, 0x02e1329e, 0xaf664fd1, 0xcad18115,
  3661. 0x6b2395e0, 0x333e92e1, 0x3b240b62, 0xeebeb922, 0x85b2a20e, 0xe6ba0d99, 0xde720c8c, 0x2da2f728,
  3662. 0xd0127845, 0x95b794fd, 0x647d0862, 0xe7ccf5f0, 0x5449a36f, 0x877d48fa, 0xc39dfd27, 0xf33e8d1e,
  3663. 0x0a476341, 0x992eff74, 0x3a6f6eab, 0xf4f8fd37, 0xa812dc60, 0xa1ebddf8, 0x991be14c, 0xdb6e6b0d,
  3664. 0xc67b5510, 0x6d672c37, 0x2765d43b, 0xdcd0e804, 0xf1290dc7, 0xcc00ffa3, 0xb5390f92, 0x690fed0b,
  3665. 0x667b9ffb, 0xcedb7d9c, 0xa091cf0b, 0xd9155ea3, 0xbb132f88, 0x515bad24, 0x7b9479bf, 0x763bd6eb,
  3666. 0x37392eb3, 0xcc115979, 0x8026e297, 0xf42e312d, 0x6842ada7, 0xc66a2b3b, 0x12754ccc, 0x782ef11c,
  3667. 0x6a124237, 0xb79251e7, 0x06a1bbe6, 0x4bfb6350, 0x1a6b1018, 0x11caedfa, 0x3d25bdd8, 0xe2e1c3c9,
  3668. 0x44421659, 0x0a121386, 0xd90cec6e, 0xd5abea2a, 0x64af674e, 0xda86a85f, 0xbebfe988, 0x64e4c3fe,
  3669. 0x9dbc8057, 0xf0f7c086, 0x60787bf8, 0x6003604d, 0xd1fd8346, 0xf6381fb0, 0x7745ae04, 0xd736fccc,
  3670. 0x83426b33, 0xf01eab71, 0xb0804187, 0x3c005e5f, 0x77a057be, 0xbde8ae24, 0x55464299, 0xbf582e61,
  3671. 0x4e58f48f, 0xf2ddfda2, 0xf474ef38, 0x8789bdc2, 0x5366f9c3, 0xc8b38e74, 0xb475f255, 0x46fcd9b9,
  3672. 0x7aeb2661, 0x8b1ddf84, 0x846a0e79, 0x915f95e2, 0x466e598e, 0x20b45770, 0x8cd55591, 0xc902de4c,
  3673. 0xb90bace1, 0xbb8205d0, 0x11a86248, 0x7574a99e, 0xb77f19b6, 0xe0a9dc09, 0x662d09a1, 0xc4324633,
  3674. 0xe85a1f02, 0x09f0be8c, 0x4a99a025, 0x1d6efe10, 0x1ab93d1d, 0x0ba5a4df, 0xa186f20f, 0x2868f169,
  3675. 0xdcb7da83, 0x573906fe, 0xa1e2ce9b, 0x4fcd7f52, 0x50115e01, 0xa70683fa, 0xa002b5c4, 0x0de6d027,
  3676. 0x9af88c27, 0x773f8641, 0xc3604c06, 0x61a806b5, 0xf0177a28, 0xc0f586e0, 0x006058aa, 0x30dc7d62,
  3677. 0x11e69ed7, 0x2338ea63, 0x53c2dd94, 0xc2c21634, 0xbbcbee56, 0x90bcb6de, 0xebfc7da1, 0xce591d76,
  3678. 0x6f05e409, 0x4b7c0188, 0x39720a3d, 0x7c927c24, 0x86e3725f, 0x724d9db9, 0x1ac15bb4, 0xd39eb8fc,
  3679. 0xed545578, 0x08fca5b5, 0xd83d7cd3, 0x4dad0fc4, 0x1e50ef5e, 0xb161e6f8, 0xa28514d9, 0x6c51133c,
  3680. 0x6fd5c7e7, 0x56e14ec4, 0x362abfce, 0xddc6c837, 0xd79a3234, 0x92638212, 0x670efa8e, 0x406000e0,
  3681. 0x3a39ce37, 0xd3faf5cf, 0xabc27737, 0x5ac52d1b, 0x5cb0679e, 0x4fa33742, 0xd3822740, 0x99bc9bbe,
  3682. 0xd5118e9d, 0xbf0f7315, 0xd62d1c7e, 0xc700c47b, 0xb78c1b6b, 0x21a19045, 0xb26eb1be, 0x6a366eb4,
  3683. 0x5748ab2f, 0xbc946e79, 0xc6a376d2, 0x6549c2c8, 0x530ff8ee, 0x468dde7d, 0xd5730a1d, 0x4cd04dc6,
  3684. 0x2939bbdb, 0xa9ba4650, 0xac9526e8, 0xbe5ee304, 0xa1fad5f0, 0x6a2d519a, 0x63ef8ce2, 0x9a86ee22,
  3685. 0xc089c2b8, 0x43242ef6, 0xa51e03aa, 0x9cf2d0a4, 0x83c061ba, 0x9be96a4d, 0x8fe51550, 0xba645bd6,
  3686. 0x2826a2f9, 0xa73a3ae1, 0x4ba99586, 0xef5562e9, 0xc72fefd3, 0xf752f7da, 0x3f046f69, 0x77fa0a59,
  3687. 0x80e4a915, 0x87b08601, 0x9b09e6ad, 0x3b3ee593, 0xe990fd5a, 0x9e34d797, 0x2cf0b7d9, 0x022b8b51,
  3688. 0x96d5ac3a, 0x017da67d, 0xd1cf3ed6, 0x7c7d2d28, 0x1f9f25cf, 0xadf2b89b, 0x5ad6b472, 0x5a88f54c,
  3689. 0xe029ac71, 0xe019a5e6, 0x47b0acfd, 0xed93fa9b, 0xe8d3c48d, 0x283b57cc, 0xf8d56629, 0x79132e28,
  3690. 0x785f0191, 0xed756055, 0xf7960e44, 0xe3d35e8c, 0x15056dd4, 0x88f46dba, 0x03a16125, 0x0564f0bd,
  3691. 0xc3eb9e15, 0x3c9057a2, 0x97271aec, 0xa93a072a, 0x1b3f6d9b, 0x1e6321f5, 0xf59c66fb, 0x26dcf319,
  3692. 0x7533d928, 0xb155fdf5, 0x03563482, 0x8aba3cbb, 0x28517711, 0xc20ad9f8, 0xabcc5167, 0xccad925f,
  3693. 0x4de81751, 0x3830dc8e, 0x379d5862, 0x9320f991, 0xea7a90c2, 0xfb3e7bce, 0x5121ce64, 0x774fbe32,
  3694. 0xa8b6e37e, 0xc3293d46, 0x48de5369, 0x6413e680, 0xa2ae0810, 0xdd6db224, 0x69852dfd, 0x09072166,
  3695. 0xb39a460a, 0x6445c0dd, 0x586cdecf, 0x1c20c8ae, 0x5bbef7dd, 0x1b588d40, 0xccd2017f, 0x6bb4e3bb,
  3696. 0xdda26a7e, 0x3a59ff45, 0x3e350a44, 0xbcb4cdd5, 0x72eacea8, 0xfa6484bb, 0x8d6612ae, 0xbf3c6f47,
  3697. 0xd29be463, 0x542f5d9e, 0xaec2771b, 0xf64e6370, 0x740e0d8d, 0xe75b1357, 0xf8721671, 0xaf537d5d,
  3698. 0x4040cb08, 0x4eb4e2cc, 0x34d2466a, 0x0115af84, 0xe1b00428, 0x95983a1d, 0x06b89fb4, 0xce6ea048,
  3699. 0x6f3f3b82, 0x3520ab82, 0x011a1d4b, 0x277227f8, 0x611560b1, 0xe7933fdc, 0xbb3a792b, 0x344525bd,
  3700. 0xa08839e1, 0x51ce794b, 0x2f32c9b7, 0xa01fbac9, 0xe01cc87e, 0xbcc7d1f6, 0xcf0111c3, 0xa1e8aac7,
  3701. 0x1a908749, 0xd44fbd9a, 0xd0dadecb, 0xd50ada38, 0x0339c32a, 0xc6913667, 0x8df9317c, 0xe0b12b4f,
  3702. 0xf79e59b7, 0x43f5bb3a, 0xf2d519ff, 0x27d9459c, 0xbf97222c, 0x15e6fc2a, 0x0f91fc71, 0x9b941525,
  3703. 0xfae59361, 0xceb69ceb, 0xc2a86459, 0x12baa8d1, 0xb6c1075e, 0xe3056a0c, 0x10d25065, 0xcb03a442,
  3704. 0xe0ec6e0e, 0x1698db3b, 0x4c98a0be, 0x3278e964, 0x9f1f9532, 0xe0d392df, 0xd3a0342b, 0x8971f21e,
  3705. 0x1b0a7441, 0x4ba3348c, 0xc5be7120, 0xc37632d8, 0xdf359f8d, 0x9b992f2e, 0xe60b6f47, 0x0fe3f11d,
  3706. 0xe54cda54, 0x1edad891, 0xce6279cf, 0xcd3e7e6f, 0x1618b166, 0xfd2c1d05, 0x848fd2c5, 0xf6fb2299,
  3707. 0xf523f357, 0xa6327623, 0x93a83531, 0x56cccd02, 0xacf08162, 0x5a75ebb5, 0x6e163697, 0x88d273cc,
  3708. 0xde966292, 0x81b949d0, 0x4c50901b, 0x71c65614, 0xe6c6c7bd, 0x327a140a, 0x45e1d006, 0xc3f27b9a,
  3709. 0xc9aa53fd, 0x62a80f00, 0xbb25bfe2, 0x35bdd2f6, 0x71126905, 0xb2040222, 0xb6cbcf7c, 0xcd769c2b,
  3710. 0x53113ec0, 0x1640e3d3, 0x38abbd60, 0x2547adf0, 0xba38209c, 0xf746ce76, 0x77afa1c5, 0x20756060,
  3711. 0x85cbfe4e, 0x8ae88dd8, 0x7aaaf9b0, 0x4cf9aa7e, 0x1948c25c, 0x02fb8a8c, 0x01c36ae4, 0xd6ebe1f9,
  3712. 0x90d4f869, 0xa65cdea0, 0x3f09252d, 0xc208e69f, 0xb74e6132, 0xce77e25b, 0x578fdfe3, 0x3ac372e6
  3713. };
  3714. memcpy (p, initialPValues, sizeof (p));
  3715. int i, j = 0;
  3716. for (i = 4; --i >= 0;)
  3717. {
  3718. s[i].malloc (256);
  3719. memcpy (s[i], initialSValues + i * 256, 256 * sizeof (uint32));
  3720. }
  3721. for (i = 0; i < 18; ++i)
  3722. {
  3723. uint32 d = 0;
  3724. for (int k = 0; k < 4; ++k)
  3725. {
  3726. d = (d << 8) | static_cast <const uint8*> (keyData)[j];
  3727. if (++j >= keyBytes)
  3728. j = 0;
  3729. }
  3730. p[i] = initialPValues[i] ^ d;
  3731. }
  3732. uint32 l = 0, r = 0;
  3733. for (i = 0; i < 18; i += 2)
  3734. {
  3735. encrypt (l, r);
  3736. p[i] = l;
  3737. p[i + 1] = r;
  3738. }
  3739. for (i = 0; i < 4; ++i)
  3740. {
  3741. for (j = 0; j < 256; j += 2)
  3742. {
  3743. encrypt (l, r);
  3744. s[i][j] = l;
  3745. s[i][j + 1] = r;
  3746. }
  3747. }
  3748. }
  3749. BlowFish::BlowFish (const BlowFish& other)
  3750. {
  3751. for (int i = 4; --i >= 0;)
  3752. s[i].malloc (256);
  3753. operator= (other);
  3754. }
  3755. BlowFish& BlowFish::operator= (const BlowFish& other)
  3756. {
  3757. memcpy (p, other.p, sizeof (p));
  3758. for (int i = 4; --i >= 0;)
  3759. memcpy (s[i], other.s[i], 256 * sizeof (uint32));
  3760. return *this;
  3761. }
  3762. BlowFish::~BlowFish()
  3763. {
  3764. }
  3765. uint32 BlowFish::F (const uint32 x) const throw()
  3766. {
  3767. return ((s[0][(x >> 24) & 0xff] + s[1][(x >> 16) & 0xff])
  3768. ^ s[2][(x >> 8) & 0xff]) + s[3][x & 0xff];
  3769. }
  3770. void BlowFish::encrypt (uint32& data1, uint32& data2) const throw()
  3771. {
  3772. uint32 l = data1;
  3773. uint32 r = data2;
  3774. for (int i = 0; i < 16; ++i)
  3775. {
  3776. l ^= p[i];
  3777. r ^= F(l);
  3778. swapVariables (l, r);
  3779. }
  3780. data1 = r ^ p[17];
  3781. data2 = l ^ p[16];
  3782. }
  3783. void BlowFish::decrypt (uint32& data1, uint32& data2) const throw()
  3784. {
  3785. uint32 l = data1;
  3786. uint32 r = data2;
  3787. for (int i = 17; i > 1; --i)
  3788. {
  3789. l ^= p[i];
  3790. r ^= F(l);
  3791. swapVariables (l, r);
  3792. }
  3793. data1 = r ^ p[0];
  3794. data2 = l ^ p[1];
  3795. }
  3796. END_JUCE_NAMESPACE
  3797. /*** End of inlined file: juce_BlowFish.cpp ***/
  3798. /*** Start of inlined file: juce_MD5.cpp ***/
  3799. BEGIN_JUCE_NAMESPACE
  3800. MD5::MD5()
  3801. {
  3802. zerostruct (result);
  3803. }
  3804. MD5::MD5 (const MD5& other)
  3805. {
  3806. memcpy (result, other.result, sizeof (result));
  3807. }
  3808. MD5& MD5::operator= (const MD5& other)
  3809. {
  3810. memcpy (result, other.result, sizeof (result));
  3811. return *this;
  3812. }
  3813. MD5::MD5 (const MemoryBlock& data)
  3814. {
  3815. ProcessContext context;
  3816. context.processBlock (data.getData(), data.getSize());
  3817. context.finish (result);
  3818. }
  3819. MD5::MD5 (const void* data, const size_t numBytes)
  3820. {
  3821. ProcessContext context;
  3822. context.processBlock (data, numBytes);
  3823. context.finish (result);
  3824. }
  3825. MD5::MD5 (const String& text)
  3826. {
  3827. ProcessContext context;
  3828. const int len = text.length();
  3829. const juce_wchar* const t = text;
  3830. for (int i = 0; i < len; ++i)
  3831. {
  3832. // force the string into integer-sized unicode characters, to try to make it
  3833. // get the same results on all platforms + compilers.
  3834. uint32 unicodeChar = ByteOrder::swapIfBigEndian ((uint32) t[i]);
  3835. context.processBlock (&unicodeChar, sizeof (unicodeChar));
  3836. }
  3837. context.finish (result);
  3838. }
  3839. void MD5::processStream (InputStream& input, int64 numBytesToRead)
  3840. {
  3841. ProcessContext context;
  3842. if (numBytesToRead < 0)
  3843. numBytesToRead = std::numeric_limits<int64>::max();
  3844. while (numBytesToRead > 0)
  3845. {
  3846. uint8 tempBuffer [512];
  3847. const int bytesRead = input.read (tempBuffer, (int) jmin (numBytesToRead, (int64) sizeof (tempBuffer)));
  3848. if (bytesRead <= 0)
  3849. break;
  3850. numBytesToRead -= bytesRead;
  3851. context.processBlock (tempBuffer, bytesRead);
  3852. }
  3853. context.finish (result);
  3854. }
  3855. MD5::MD5 (InputStream& input, int64 numBytesToRead)
  3856. {
  3857. processStream (input, numBytesToRead);
  3858. }
  3859. MD5::MD5 (const File& file)
  3860. {
  3861. const ScopedPointer <FileInputStream> fin (file.createInputStream());
  3862. if (fin != 0)
  3863. processStream (*fin, -1);
  3864. else
  3865. zerostruct (result);
  3866. }
  3867. MD5::~MD5()
  3868. {
  3869. }
  3870. namespace MD5Functions
  3871. {
  3872. static void encode (void* const output, const void* const input, const int numBytes) throw()
  3873. {
  3874. for (int i = 0; i < (numBytes >> 2); ++i)
  3875. static_cast<uint32*> (output)[i] = ByteOrder::swapIfBigEndian (static_cast<const uint32*> (input) [i]);
  3876. }
  3877. static inline uint32 F (const uint32 x, const uint32 y, const uint32 z) throw() { return (x & y) | (~x & z); }
  3878. static inline uint32 G (const uint32 x, const uint32 y, const uint32 z) throw() { return (x & z) | (y & ~z); }
  3879. static inline uint32 H (const uint32 x, const uint32 y, const uint32 z) throw() { return x ^ y ^ z; }
  3880. static inline uint32 I (const uint32 x, const uint32 y, const uint32 z) throw() { return y ^ (x | ~z); }
  3881. static inline uint32 rotateLeft (const uint32 x, const uint32 n) throw() { return (x << n) | (x >> (32 - n)); }
  3882. static void FF (uint32& a, const uint32 b, const uint32 c, const uint32 d, const uint32 x, const uint32 s, const uint32 ac) throw()
  3883. {
  3884. a += F (b, c, d) + x + ac;
  3885. a = rotateLeft (a, s) + b;
  3886. }
  3887. static void GG (uint32& a, const uint32 b, const uint32 c, const uint32 d, const uint32 x, const uint32 s, const uint32 ac) throw()
  3888. {
  3889. a += G (b, c, d) + x + ac;
  3890. a = rotateLeft (a, s) + b;
  3891. }
  3892. static void HH (uint32& a, const uint32 b, const uint32 c, const uint32 d, const uint32 x, const uint32 s, const uint32 ac) throw()
  3893. {
  3894. a += H (b, c, d) + x + ac;
  3895. a = rotateLeft (a, s) + b;
  3896. }
  3897. static void II (uint32& a, const uint32 b, const uint32 c, const uint32 d, const uint32 x, const uint32 s, const uint32 ac) throw()
  3898. {
  3899. a += I (b, c, d) + x + ac;
  3900. a = rotateLeft (a, s) + b;
  3901. }
  3902. }
  3903. MD5::ProcessContext::ProcessContext()
  3904. {
  3905. state[0] = 0x67452301;
  3906. state[1] = 0xefcdab89;
  3907. state[2] = 0x98badcfe;
  3908. state[3] = 0x10325476;
  3909. count[0] = 0;
  3910. count[1] = 0;
  3911. }
  3912. void MD5::ProcessContext::processBlock (const void* const data, const size_t dataSize)
  3913. {
  3914. int bufferPos = ((count[0] >> 3) & 0x3F);
  3915. count[0] += (uint32) (dataSize << 3);
  3916. if (count[0] < ((uint32) dataSize << 3))
  3917. count[1]++;
  3918. count[1] += (uint32) (dataSize >> 29);
  3919. const size_t spaceLeft = 64 - bufferPos;
  3920. size_t i = 0;
  3921. if (dataSize >= spaceLeft)
  3922. {
  3923. memcpy (buffer + bufferPos, data, spaceLeft);
  3924. transform (buffer);
  3925. for (i = spaceLeft; i + 64 <= dataSize; i += 64)
  3926. transform (static_cast <const char*> (data) + i);
  3927. bufferPos = 0;
  3928. }
  3929. memcpy (buffer + bufferPos, static_cast <const char*> (data) + i, dataSize - i);
  3930. }
  3931. void MD5::ProcessContext::finish (void* const result)
  3932. {
  3933. unsigned char encodedLength[8];
  3934. MD5Functions::encode (encodedLength, count, 8);
  3935. // Pad out to 56 mod 64.
  3936. const int index = (uint32) ((count[0] >> 3) & 0x3f);
  3937. const int paddingLength = (index < 56) ? (56 - index)
  3938. : (120 - index);
  3939. uint8 paddingBuffer [64];
  3940. zeromem (paddingBuffer, paddingLength);
  3941. paddingBuffer [0] = 0x80;
  3942. processBlock (paddingBuffer, paddingLength);
  3943. processBlock (encodedLength, 8);
  3944. MD5Functions::encode (result, state, 16);
  3945. zerostruct (buffer);
  3946. }
  3947. void MD5::ProcessContext::transform (const void* const bufferToTransform)
  3948. {
  3949. using namespace MD5Functions;
  3950. uint32 a = state[0];
  3951. uint32 b = state[1];
  3952. uint32 c = state[2];
  3953. uint32 d = state[3];
  3954. uint32 x[16];
  3955. encode (x, bufferToTransform, 64);
  3956. enum Constants
  3957. {
  3958. S11 = 7, S12 = 12, S13 = 17, S14 = 22, S21 = 5, S22 = 9, S23 = 14, S24 = 20,
  3959. S31 = 4, S32 = 11, S33 = 16, S34 = 23, S41 = 6, S42 = 10, S43 = 15, S44 = 21
  3960. };
  3961. FF (a, b, c, d, x[ 0], S11, 0xd76aa478); FF (d, a, b, c, x[ 1], S12, 0xe8c7b756);
  3962. FF (c, d, a, b, x[ 2], S13, 0x242070db); FF (b, c, d, a, x[ 3], S14, 0xc1bdceee);
  3963. FF (a, b, c, d, x[ 4], S11, 0xf57c0faf); FF (d, a, b, c, x[ 5], S12, 0x4787c62a);
  3964. FF (c, d, a, b, x[ 6], S13, 0xa8304613); FF (b, c, d, a, x[ 7], S14, 0xfd469501);
  3965. FF (a, b, c, d, x[ 8], S11, 0x698098d8); FF (d, a, b, c, x[ 9], S12, 0x8b44f7af);
  3966. FF (c, d, a, b, x[10], S13, 0xffff5bb1); FF (b, c, d, a, x[11], S14, 0x895cd7be);
  3967. FF (a, b, c, d, x[12], S11, 0x6b901122); FF (d, a, b, c, x[13], S12, 0xfd987193);
  3968. FF (c, d, a, b, x[14], S13, 0xa679438e); FF (b, c, d, a, x[15], S14, 0x49b40821);
  3969. GG (a, b, c, d, x[ 1], S21, 0xf61e2562); GG (d, a, b, c, x[ 6], S22, 0xc040b340);
  3970. GG (c, d, a, b, x[11], S23, 0x265e5a51); GG (b, c, d, a, x[ 0], S24, 0xe9b6c7aa);
  3971. GG (a, b, c, d, x[ 5], S21, 0xd62f105d); GG (d, a, b, c, x[10], S22, 0x02441453);
  3972. GG (c, d, a, b, x[15], S23, 0xd8a1e681); GG (b, c, d, a, x[ 4], S24, 0xe7d3fbc8);
  3973. GG (a, b, c, d, x[ 9], S21, 0x21e1cde6); GG (d, a, b, c, x[14], S22, 0xc33707d6);
  3974. GG (c, d, a, b, x[ 3], S23, 0xf4d50d87); GG (b, c, d, a, x[ 8], S24, 0x455a14ed);
  3975. GG (a, b, c, d, x[13], S21, 0xa9e3e905); GG (d, a, b, c, x[ 2], S22, 0xfcefa3f8);
  3976. GG (c, d, a, b, x[ 7], S23, 0x676f02d9); GG (b, c, d, a, x[12], S24, 0x8d2a4c8a);
  3977. HH (a, b, c, d, x[ 5], S31, 0xfffa3942); HH (d, a, b, c, x[ 8], S32, 0x8771f681);
  3978. HH (c, d, a, b, x[11], S33, 0x6d9d6122); HH (b, c, d, a, x[14], S34, 0xfde5380c);
  3979. HH (a, b, c, d, x[ 1], S31, 0xa4beea44); HH (d, a, b, c, x[ 4], S32, 0x4bdecfa9);
  3980. HH (c, d, a, b, x[ 7], S33, 0xf6bb4b60); HH (b, c, d, a, x[10], S34, 0xbebfbc70);
  3981. HH (a, b, c, d, x[13], S31, 0x289b7ec6); HH (d, a, b, c, x[ 0], S32, 0xeaa127fa);
  3982. HH (c, d, a, b, x[ 3], S33, 0xd4ef3085); HH (b, c, d, a, x[ 6], S34, 0x04881d05);
  3983. HH (a, b, c, d, x[ 9], S31, 0xd9d4d039); HH (d, a, b, c, x[12], S32, 0xe6db99e5);
  3984. HH (c, d, a, b, x[15], S33, 0x1fa27cf8); HH (b, c, d, a, x[ 2], S34, 0xc4ac5665);
  3985. II (a, b, c, d, x[ 0], S41, 0xf4292244); II (d, a, b, c, x[ 7], S42, 0x432aff97);
  3986. II (c, d, a, b, x[14], S43, 0xab9423a7); II (b, c, d, a, x[ 5], S44, 0xfc93a039);
  3987. II (a, b, c, d, x[12], S41, 0x655b59c3); II (d, a, b, c, x[ 3], S42, 0x8f0ccc92);
  3988. II (c, d, a, b, x[10], S43, 0xffeff47d); II (b, c, d, a, x[ 1], S44, 0x85845dd1);
  3989. II (a, b, c, d, x[ 8], S41, 0x6fa87e4f); II (d, a, b, c, x[15], S42, 0xfe2ce6e0);
  3990. II (c, d, a, b, x[ 6], S43, 0xa3014314); II (b, c, d, a, x[13], S44, 0x4e0811a1);
  3991. II (a, b, c, d, x[ 4], S41, 0xf7537e82); II (d, a, b, c, x[11], S42, 0xbd3af235);
  3992. II (c, d, a, b, x[ 2], S43, 0x2ad7d2bb); II (b, c, d, a, x[ 9], S44, 0xeb86d391);
  3993. state[0] += a;
  3994. state[1] += b;
  3995. state[2] += c;
  3996. state[3] += d;
  3997. zerostruct (x);
  3998. }
  3999. const MemoryBlock MD5::getRawChecksumData() const
  4000. {
  4001. return MemoryBlock (result, sizeof (result));
  4002. }
  4003. const String MD5::toHexString() const
  4004. {
  4005. return String::toHexString (result, sizeof (result), 0);
  4006. }
  4007. bool MD5::operator== (const MD5& other) const
  4008. {
  4009. return memcmp (result, other.result, sizeof (result)) == 0;
  4010. }
  4011. bool MD5::operator!= (const MD5& other) const
  4012. {
  4013. return ! operator== (other);
  4014. }
  4015. END_JUCE_NAMESPACE
  4016. /*** End of inlined file: juce_MD5.cpp ***/
  4017. /*** Start of inlined file: juce_Primes.cpp ***/
  4018. BEGIN_JUCE_NAMESPACE
  4019. namespace PrimesHelpers
  4020. {
  4021. static void createSmallSieve (const int numBits, BigInteger& result)
  4022. {
  4023. result.setBit (numBits);
  4024. result.clearBit (numBits); // to enlarge the array
  4025. result.setBit (0);
  4026. int n = 2;
  4027. do
  4028. {
  4029. for (int i = n + n; i < numBits; i += n)
  4030. result.setBit (i);
  4031. n = result.findNextClearBit (n + 1);
  4032. }
  4033. while (n <= (numBits >> 1));
  4034. }
  4035. static void bigSieve (const BigInteger& base, const int numBits, BigInteger& result,
  4036. const BigInteger& smallSieve, const int smallSieveSize)
  4037. {
  4038. jassert (! base[0]); // must be even!
  4039. result.setBit (numBits);
  4040. result.clearBit (numBits); // to enlarge the array
  4041. int index = smallSieve.findNextClearBit (0);
  4042. do
  4043. {
  4044. const int prime = (index << 1) + 1;
  4045. BigInteger r (base), remainder;
  4046. r.divideBy (prime, remainder);
  4047. int i = prime - remainder.getBitRangeAsInt (0, 32);
  4048. if (r.isZero())
  4049. i += prime;
  4050. if ((i & 1) == 0)
  4051. i += prime;
  4052. i = (i - 1) >> 1;
  4053. while (i < numBits)
  4054. {
  4055. result.setBit (i);
  4056. i += prime;
  4057. }
  4058. index = smallSieve.findNextClearBit (index + 1);
  4059. }
  4060. while (index < smallSieveSize);
  4061. }
  4062. static bool findCandidate (const BigInteger& base, const BigInteger& sieve,
  4063. const int numBits, BigInteger& result, const int certainty)
  4064. {
  4065. for (int i = 0; i < numBits; ++i)
  4066. {
  4067. if (! sieve[i])
  4068. {
  4069. result = base + (unsigned int) ((i << 1) + 1);
  4070. if (Primes::isProbablyPrime (result, certainty))
  4071. return true;
  4072. }
  4073. }
  4074. return false;
  4075. }
  4076. static bool passesMillerRabin (const BigInteger& n, int iterations)
  4077. {
  4078. const BigInteger one (1), two (2);
  4079. const BigInteger nMinusOne (n - one);
  4080. BigInteger d (nMinusOne);
  4081. const int s = d.findNextSetBit (0);
  4082. d >>= s;
  4083. BigInteger smallPrimes;
  4084. int numBitsInSmallPrimes = 0;
  4085. for (;;)
  4086. {
  4087. numBitsInSmallPrimes += 256;
  4088. createSmallSieve (numBitsInSmallPrimes, smallPrimes);
  4089. const int numPrimesFound = numBitsInSmallPrimes - smallPrimes.countNumberOfSetBits();
  4090. if (numPrimesFound > iterations + 1)
  4091. break;
  4092. }
  4093. int smallPrime = 2;
  4094. while (--iterations >= 0)
  4095. {
  4096. smallPrime = smallPrimes.findNextClearBit (smallPrime + 1);
  4097. BigInteger r (smallPrime);
  4098. r.exponentModulo (d, n);
  4099. if (r != one && r != nMinusOne)
  4100. {
  4101. for (int j = 0; j < s; ++j)
  4102. {
  4103. r.exponentModulo (two, n);
  4104. if (r == nMinusOne)
  4105. break;
  4106. }
  4107. if (r != nMinusOne)
  4108. return false;
  4109. }
  4110. }
  4111. return true;
  4112. }
  4113. }
  4114. const BigInteger Primes::createProbablePrime (const int bitLength,
  4115. const int certainty,
  4116. const int* randomSeeds,
  4117. int numRandomSeeds)
  4118. {
  4119. using namespace PrimesHelpers;
  4120. int defaultSeeds [16];
  4121. if (numRandomSeeds <= 0)
  4122. {
  4123. randomSeeds = defaultSeeds;
  4124. numRandomSeeds = numElementsInArray (defaultSeeds);
  4125. Random r (0);
  4126. for (int j = 10; --j >= 0;)
  4127. {
  4128. r.setSeedRandomly();
  4129. for (int i = numRandomSeeds; --i >= 0;)
  4130. defaultSeeds[i] ^= r.nextInt() ^ Random::getSystemRandom().nextInt();
  4131. }
  4132. }
  4133. BigInteger smallSieve;
  4134. const int smallSieveSize = 15000;
  4135. createSmallSieve (smallSieveSize, smallSieve);
  4136. BigInteger p;
  4137. for (int i = numRandomSeeds; --i >= 0;)
  4138. {
  4139. BigInteger p2;
  4140. Random r (randomSeeds[i]);
  4141. r.fillBitsRandomly (p2, 0, bitLength);
  4142. p ^= p2;
  4143. }
  4144. p.setBit (bitLength - 1);
  4145. p.clearBit (0);
  4146. const int searchLen = jmax (1024, (bitLength / 20) * 64);
  4147. while (p.getHighestBit() < bitLength)
  4148. {
  4149. p += 2 * searchLen;
  4150. BigInteger sieve;
  4151. bigSieve (p, searchLen, sieve,
  4152. smallSieve, smallSieveSize);
  4153. BigInteger candidate;
  4154. if (findCandidate (p, sieve, searchLen, candidate, certainty))
  4155. return candidate;
  4156. }
  4157. jassertfalse
  4158. return BigInteger();
  4159. }
  4160. bool Primes::isProbablyPrime (const BigInteger& number, const int certainty)
  4161. {
  4162. using namespace PrimesHelpers;
  4163. if (! number[0])
  4164. return false;
  4165. if (number.getHighestBit() <= 10)
  4166. {
  4167. const int num = number.getBitRangeAsInt (0, 10);
  4168. for (int i = num / 2; --i > 1;)
  4169. if (num % i == 0)
  4170. return false;
  4171. return true;
  4172. }
  4173. else
  4174. {
  4175. if (number.findGreatestCommonDivisor (2 * 3 * 5 * 7 * 11 * 13 * 17 * 19 * 23) != 1)
  4176. return false;
  4177. return passesMillerRabin (number, certainty);
  4178. }
  4179. }
  4180. END_JUCE_NAMESPACE
  4181. /*** End of inlined file: juce_Primes.cpp ***/
  4182. /*** Start of inlined file: juce_RSAKey.cpp ***/
  4183. BEGIN_JUCE_NAMESPACE
  4184. RSAKey::RSAKey()
  4185. {
  4186. }
  4187. RSAKey::RSAKey (const String& s)
  4188. {
  4189. if (s.containsChar (','))
  4190. {
  4191. part1.parseString (s.upToFirstOccurrenceOf (",", false, false), 16);
  4192. part2.parseString (s.fromFirstOccurrenceOf (",", false, false), 16);
  4193. }
  4194. else
  4195. {
  4196. // the string needs to be two hex numbers, comma-separated..
  4197. jassertfalse;
  4198. }
  4199. }
  4200. RSAKey::~RSAKey()
  4201. {
  4202. }
  4203. const String RSAKey::toString() const
  4204. {
  4205. return part1.toString (16) + "," + part2.toString (16);
  4206. }
  4207. bool RSAKey::applyToValue (BigInteger& value) const
  4208. {
  4209. if (part1.isZero() || part2.isZero() || value <= 0)
  4210. {
  4211. jassertfalse // using an uninitialised key
  4212. value.clear();
  4213. return false;
  4214. }
  4215. BigInteger result;
  4216. while (! value.isZero())
  4217. {
  4218. result *= part2;
  4219. BigInteger remainder;
  4220. value.divideBy (part2, remainder);
  4221. remainder.exponentModulo (part1, part2);
  4222. result += remainder;
  4223. }
  4224. value.swapWith (result);
  4225. return true;
  4226. }
  4227. static const BigInteger findBestCommonDivisor (const BigInteger& p, const BigInteger& q)
  4228. {
  4229. // try 3, 5, 9, 17, etc first because these only contain 2 bits and so
  4230. // are fast to divide + multiply
  4231. for (int i = 2; i <= 65536; i *= 2)
  4232. {
  4233. const BigInteger e (1 + i);
  4234. if (e.findGreatestCommonDivisor (p).isOne() && e.findGreatestCommonDivisor (q).isOne())
  4235. return e;
  4236. }
  4237. BigInteger e (4);
  4238. while (! (e.findGreatestCommonDivisor (p).isOne() && e.findGreatestCommonDivisor (q).isOne()))
  4239. ++e;
  4240. return e;
  4241. }
  4242. void RSAKey::createKeyPair (RSAKey& publicKey, RSAKey& privateKey,
  4243. const int numBits, const int* randomSeeds, const int numRandomSeeds)
  4244. {
  4245. jassert (numBits > 16); // not much point using less than this..
  4246. BigInteger p (Primes::createProbablePrime (numBits / 2, 30, randomSeeds, numRandomSeeds));
  4247. BigInteger q (Primes::createProbablePrime (numBits - numBits / 2, 30, randomSeeds, numRandomSeeds));
  4248. const BigInteger n (p * q);
  4249. const BigInteger m (--p * --q);
  4250. const BigInteger e (findBestCommonDivisor (p, q));
  4251. BigInteger d (e);
  4252. d.inverseModulo (m);
  4253. publicKey.part1 = e;
  4254. publicKey.part2 = n;
  4255. privateKey.part1 = d;
  4256. privateKey.part2 = n;
  4257. }
  4258. END_JUCE_NAMESPACE
  4259. /*** End of inlined file: juce_RSAKey.cpp ***/
  4260. /*** Start of inlined file: juce_InputStream.cpp ***/
  4261. BEGIN_JUCE_NAMESPACE
  4262. char InputStream::readByte()
  4263. {
  4264. char temp = 0;
  4265. read (&temp, 1);
  4266. return temp;
  4267. }
  4268. bool InputStream::readBool()
  4269. {
  4270. return readByte() != 0;
  4271. }
  4272. short InputStream::readShort()
  4273. {
  4274. char temp[2];
  4275. if (read (temp, 2) == 2)
  4276. return (short) ByteOrder::littleEndianShort (temp);
  4277. return 0;
  4278. }
  4279. short InputStream::readShortBigEndian()
  4280. {
  4281. char temp[2];
  4282. if (read (temp, 2) == 2)
  4283. return (short) ByteOrder::bigEndianShort (temp);
  4284. return 0;
  4285. }
  4286. int InputStream::readInt()
  4287. {
  4288. char temp[4];
  4289. if (read (temp, 4) == 4)
  4290. return (int) ByteOrder::littleEndianInt (temp);
  4291. return 0;
  4292. }
  4293. int InputStream::readIntBigEndian()
  4294. {
  4295. char temp[4];
  4296. if (read (temp, 4) == 4)
  4297. return (int) ByteOrder::bigEndianInt (temp);
  4298. return 0;
  4299. }
  4300. int InputStream::readCompressedInt()
  4301. {
  4302. const unsigned char sizeByte = readByte();
  4303. if (sizeByte == 0)
  4304. return 0;
  4305. const int numBytes = (sizeByte & 0x7f);
  4306. if (numBytes > 4)
  4307. {
  4308. jassertfalse // trying to read corrupt data - this method must only be used
  4309. // to read data that was written by OutputStream::writeCompressedInt()
  4310. return 0;
  4311. }
  4312. char bytes[4] = { 0, 0, 0, 0 };
  4313. if (read (bytes, numBytes) != numBytes)
  4314. return 0;
  4315. const int num = (int) ByteOrder::littleEndianInt (bytes);
  4316. return (sizeByte >> 7) ? -num : num;
  4317. }
  4318. int64 InputStream::readInt64()
  4319. {
  4320. union { uint8 asBytes[8]; uint64 asInt64; } n;
  4321. if (read (n.asBytes, 8) == 8)
  4322. return (int64) ByteOrder::swapIfBigEndian (n.asInt64);
  4323. return 0;
  4324. }
  4325. int64 InputStream::readInt64BigEndian()
  4326. {
  4327. union { uint8 asBytes[8]; uint64 asInt64; } n;
  4328. if (read (n.asBytes, 8) == 8)
  4329. return (int64) ByteOrder::swapIfLittleEndian (n.asInt64);
  4330. return 0;
  4331. }
  4332. float InputStream::readFloat()
  4333. {
  4334. // the union below relies on these types being the same size...
  4335. static_jassert (sizeof (int32) == sizeof (float));
  4336. union { int32 asInt; float asFloat; } n;
  4337. n.asInt = (int32) readInt();
  4338. return n.asFloat;
  4339. }
  4340. float InputStream::readFloatBigEndian()
  4341. {
  4342. union { int32 asInt; float asFloat; } n;
  4343. n.asInt = (int32) readIntBigEndian();
  4344. return n.asFloat;
  4345. }
  4346. double InputStream::readDouble()
  4347. {
  4348. union { int64 asInt; double asDouble; } n;
  4349. n.asInt = readInt64();
  4350. return n.asDouble;
  4351. }
  4352. double InputStream::readDoubleBigEndian()
  4353. {
  4354. union { int64 asInt; double asDouble; } n;
  4355. n.asInt = readInt64BigEndian();
  4356. return n.asDouble;
  4357. }
  4358. const String InputStream::readString()
  4359. {
  4360. MemoryBlock buffer (256);
  4361. char* data = static_cast<char*> (buffer.getData());
  4362. size_t i = 0;
  4363. while ((data[i] = readByte()) != 0)
  4364. {
  4365. if (++i >= buffer.getSize())
  4366. {
  4367. buffer.setSize (buffer.getSize() + 512);
  4368. data = static_cast<char*> (buffer.getData());
  4369. }
  4370. }
  4371. return String::fromUTF8 (data, (int) i);
  4372. }
  4373. const String InputStream::readNextLine()
  4374. {
  4375. MemoryBlock buffer (256);
  4376. char* data = static_cast<char*> (buffer.getData());
  4377. size_t i = 0;
  4378. while ((data[i] = readByte()) != 0)
  4379. {
  4380. if (data[i] == '\n')
  4381. break;
  4382. if (data[i] == '\r')
  4383. {
  4384. const int64 lastPos = getPosition();
  4385. if (readByte() != '\n')
  4386. setPosition (lastPos);
  4387. break;
  4388. }
  4389. if (++i >= buffer.getSize())
  4390. {
  4391. buffer.setSize (buffer.getSize() + 512);
  4392. data = static_cast<char*> (buffer.getData());
  4393. }
  4394. }
  4395. return String::fromUTF8 (data, (int) i);
  4396. }
  4397. int InputStream::readIntoMemoryBlock (MemoryBlock& block, int numBytes)
  4398. {
  4399. const int64 totalLength = getTotalLength();
  4400. if (totalLength >= 0)
  4401. {
  4402. const int totalBytesRemaining = (int) jmin ((int64) 0x7fffffff,
  4403. totalLength - getPosition());
  4404. if (numBytes < 0)
  4405. numBytes = totalBytesRemaining;
  4406. else if (numBytes > 0)
  4407. numBytes = jmin (numBytes, totalBytesRemaining);
  4408. else
  4409. return 0;
  4410. }
  4411. const size_t originalBlockSize = block.getSize();
  4412. int totalBytesRead = 0;
  4413. if (numBytes > 0)
  4414. {
  4415. // know how many bytes we want, so we can resize the block first..
  4416. block.setSize (originalBlockSize + numBytes, false);
  4417. totalBytesRead = read (static_cast<char*> (block.getData()) + originalBlockSize, numBytes);
  4418. }
  4419. else
  4420. {
  4421. // read until end of stram..
  4422. const int chunkSize = 32768;
  4423. for (;;)
  4424. {
  4425. block.ensureSize (originalBlockSize + totalBytesRead + chunkSize, false);
  4426. const int bytesJustIn = read (static_cast<char*> (block.getData())
  4427. + originalBlockSize
  4428. + totalBytesRead,
  4429. chunkSize);
  4430. if (bytesJustIn == 0)
  4431. break;
  4432. totalBytesRead += bytesJustIn;
  4433. }
  4434. }
  4435. // trim off any excess left at the end
  4436. block.setSize (originalBlockSize + totalBytesRead, false);
  4437. return totalBytesRead;
  4438. }
  4439. const String InputStream::readEntireStreamAsString()
  4440. {
  4441. MemoryBlock mb;
  4442. const int size = readIntoMemoryBlock (mb);
  4443. return String::createStringFromData (static_cast<const char*> (mb.getData()), size);
  4444. }
  4445. void InputStream::skipNextBytes (int64 numBytesToSkip)
  4446. {
  4447. if (numBytesToSkip > 0)
  4448. {
  4449. const int skipBufferSize = (int) jmin (numBytesToSkip, (int64) 16384);
  4450. HeapBlock<char> temp (skipBufferSize);
  4451. while (numBytesToSkip > 0 && ! isExhausted())
  4452. numBytesToSkip -= read (temp, (int) jmin (numBytesToSkip, (int64) skipBufferSize));
  4453. }
  4454. }
  4455. END_JUCE_NAMESPACE
  4456. /*** End of inlined file: juce_InputStream.cpp ***/
  4457. /*** Start of inlined file: juce_OutputStream.cpp ***/
  4458. BEGIN_JUCE_NAMESPACE
  4459. #if JUCE_DEBUG
  4460. static CriticalSection activeStreamLock;
  4461. static VoidArray activeStreams;
  4462. void juce_CheckForDanglingStreams()
  4463. {
  4464. /*
  4465. It's always a bad idea to leak any object, but if you're leaking output
  4466. streams, then there's a good chance that you're failing to flush a file
  4467. to disk properly, which could result in corrupted data and other similar
  4468. nastiness..
  4469. */
  4470. jassert (activeStreams.size() == 0);
  4471. };
  4472. #endif
  4473. OutputStream::OutputStream()
  4474. {
  4475. #if JUCE_DEBUG
  4476. const ScopedLock sl (activeStreamLock);
  4477. activeStreams.add (this);
  4478. #endif
  4479. }
  4480. OutputStream::~OutputStream()
  4481. {
  4482. #if JUCE_DEBUG
  4483. const ScopedLock sl (activeStreamLock);
  4484. activeStreams.removeValue (this);
  4485. #endif
  4486. }
  4487. void OutputStream::writeBool (const bool b)
  4488. {
  4489. writeByte (b ? (char) 1
  4490. : (char) 0);
  4491. }
  4492. void OutputStream::writeByte (char byte)
  4493. {
  4494. write (&byte, 1);
  4495. }
  4496. void OutputStream::writeShort (short value)
  4497. {
  4498. const unsigned short v = ByteOrder::swapIfBigEndian ((unsigned short) value);
  4499. write (&v, 2);
  4500. }
  4501. void OutputStream::writeShortBigEndian (short value)
  4502. {
  4503. const unsigned short v = ByteOrder::swapIfLittleEndian ((unsigned short) value);
  4504. write (&v, 2);
  4505. }
  4506. void OutputStream::writeInt (int value)
  4507. {
  4508. const unsigned int v = ByteOrder::swapIfBigEndian ((unsigned int) value);
  4509. write (&v, 4);
  4510. }
  4511. void OutputStream::writeIntBigEndian (int value)
  4512. {
  4513. const unsigned int v = ByteOrder::swapIfLittleEndian ((unsigned int) value);
  4514. write (&v, 4);
  4515. }
  4516. void OutputStream::writeCompressedInt (int value)
  4517. {
  4518. unsigned int un = (value < 0) ? (unsigned int) -value
  4519. : (unsigned int) value;
  4520. uint8 data[5];
  4521. int num = 0;
  4522. while (un > 0)
  4523. {
  4524. data[++num] = (uint8) un;
  4525. un >>= 8;
  4526. }
  4527. data[0] = (uint8) num;
  4528. if (value < 0)
  4529. data[0] |= 0x80;
  4530. write (data, num + 1);
  4531. }
  4532. void OutputStream::writeInt64 (int64 value)
  4533. {
  4534. const uint64 v = ByteOrder::swapIfBigEndian ((uint64) value);
  4535. write (&v, 8);
  4536. }
  4537. void OutputStream::writeInt64BigEndian (int64 value)
  4538. {
  4539. const uint64 v = ByteOrder::swapIfLittleEndian ((uint64) value);
  4540. write (&v, 8);
  4541. }
  4542. void OutputStream::writeFloat (float value)
  4543. {
  4544. union { int asInt; float asFloat; } n;
  4545. n.asFloat = value;
  4546. writeInt (n.asInt);
  4547. }
  4548. void OutputStream::writeFloatBigEndian (float value)
  4549. {
  4550. union { int asInt; float asFloat; } n;
  4551. n.asFloat = value;
  4552. writeIntBigEndian (n.asInt);
  4553. }
  4554. void OutputStream::writeDouble (double value)
  4555. {
  4556. union { int64 asInt; double asDouble; } n;
  4557. n.asDouble = value;
  4558. writeInt64 (n.asInt);
  4559. }
  4560. void OutputStream::writeDoubleBigEndian (double value)
  4561. {
  4562. union { int64 asInt; double asDouble; } n;
  4563. n.asDouble = value;
  4564. writeInt64BigEndian (n.asInt);
  4565. }
  4566. void OutputStream::writeString (const String& text)
  4567. {
  4568. // (This avoids using toUTF8() to prevent the memory bloat that it would leave behind
  4569. // if lots of large, persistent strings were to be written to streams).
  4570. const int numBytes = text.getNumBytesAsUTF8() + 1;
  4571. HeapBlock<char> temp (numBytes);
  4572. text.copyToUTF8 (temp, numBytes);
  4573. write (temp, numBytes);
  4574. }
  4575. void OutputStream::writeText (const String& text, const bool asUnicode,
  4576. const bool writeUnicodeHeaderBytes)
  4577. {
  4578. if (asUnicode)
  4579. {
  4580. if (writeUnicodeHeaderBytes)
  4581. write ("\x0ff\x0fe", 2);
  4582. const juce_wchar* src = text;
  4583. bool lastCharWasReturn = false;
  4584. while (*src != 0)
  4585. {
  4586. if (*src == L'\n' && ! lastCharWasReturn)
  4587. writeShort ((short) L'\r');
  4588. lastCharWasReturn = (*src == L'\r');
  4589. writeShort ((short) *src++);
  4590. }
  4591. }
  4592. else
  4593. {
  4594. const char* src = text.toUTF8();
  4595. const char* t = src;
  4596. for (;;)
  4597. {
  4598. if (*t == '\n')
  4599. {
  4600. if (t > src)
  4601. write (src, (int) (t - src));
  4602. write ("\r\n", 2);
  4603. src = t + 1;
  4604. }
  4605. else if (*t == '\r')
  4606. {
  4607. if (t[1] == '\n')
  4608. ++t;
  4609. }
  4610. else if (*t == 0)
  4611. {
  4612. if (t > src)
  4613. write (src, (int) (t - src));
  4614. break;
  4615. }
  4616. ++t;
  4617. }
  4618. }
  4619. }
  4620. int OutputStream::writeFromInputStream (InputStream& source, int64 numBytesToWrite)
  4621. {
  4622. if (numBytesToWrite < 0)
  4623. numBytesToWrite = std::numeric_limits<int64>::max();
  4624. int numWritten = 0;
  4625. while (numBytesToWrite > 0 && ! source.isExhausted())
  4626. {
  4627. char buffer [8192];
  4628. const int num = source.read (buffer, (int) jmin (numBytesToWrite, (int64) sizeof (buffer)));
  4629. if (num <= 0)
  4630. break;
  4631. write (buffer, num);
  4632. numBytesToWrite -= num;
  4633. numWritten += num;
  4634. }
  4635. return numWritten;
  4636. }
  4637. OutputStream& JUCE_CALLTYPE operator<< (OutputStream& stream, const int number)
  4638. {
  4639. return stream << String (number);
  4640. }
  4641. OutputStream& JUCE_CALLTYPE operator<< (OutputStream& stream, const double number)
  4642. {
  4643. return stream << String (number);
  4644. }
  4645. OutputStream& JUCE_CALLTYPE operator<< (OutputStream& stream, const char character)
  4646. {
  4647. stream.writeByte (character);
  4648. return stream;
  4649. }
  4650. OutputStream& JUCE_CALLTYPE operator<< (OutputStream& stream, const char* const text)
  4651. {
  4652. stream.write (text, (int) strlen (text));
  4653. return stream;
  4654. }
  4655. OutputStream& JUCE_CALLTYPE operator<< (OutputStream& stream, const MemoryBlock& data)
  4656. {
  4657. stream.write (data.getData(), (int) data.getSize());
  4658. return stream;
  4659. }
  4660. OutputStream& JUCE_CALLTYPE operator<< (OutputStream& stream, const File& fileToRead)
  4661. {
  4662. const ScopedPointer<FileInputStream> in (fileToRead.createInputStream());
  4663. if (in != 0)
  4664. stream.writeFromInputStream (*in, -1);
  4665. return stream;
  4666. }
  4667. END_JUCE_NAMESPACE
  4668. /*** End of inlined file: juce_OutputStream.cpp ***/
  4669. /*** Start of inlined file: juce_DirectoryIterator.cpp ***/
  4670. BEGIN_JUCE_NAMESPACE
  4671. DirectoryIterator::DirectoryIterator (const File& directory,
  4672. bool isRecursive_,
  4673. const String& wildCard_,
  4674. const int whatToLookFor_)
  4675. : fileFinder (directory, isRecursive ? "*" : wildCard_),
  4676. wildCard (wildCard_),
  4677. path (File::addTrailingSeparator (directory.getFullPathName())),
  4678. index (-1),
  4679. totalNumFiles (-1),
  4680. whatToLookFor (whatToLookFor_),
  4681. isRecursive (isRecursive_)
  4682. {
  4683. // you have to specify the type of files you're looking for!
  4684. jassert ((whatToLookFor_ & (File::findFiles | File::findDirectories)) != 0);
  4685. jassert (whatToLookFor_ > 0 && whatToLookFor_ <= 7);
  4686. }
  4687. DirectoryIterator::~DirectoryIterator()
  4688. {
  4689. }
  4690. bool DirectoryIterator::next()
  4691. {
  4692. return next (0, 0, 0, 0, 0, 0);
  4693. }
  4694. bool DirectoryIterator::next (bool* const isDirResult, bool* const isHiddenResult, int64* const fileSize,
  4695. Time* const modTime, Time* const creationTime, bool* const isReadOnly)
  4696. {
  4697. if (subIterator != 0)
  4698. {
  4699. if (subIterator->next (isDirResult, isHiddenResult, fileSize, modTime, creationTime, isReadOnly))
  4700. return true;
  4701. subIterator = 0;
  4702. }
  4703. String filename;
  4704. bool isDirectory, isHidden;
  4705. while (fileFinder.next (filename, &isDirectory, &isHidden, fileSize, modTime, creationTime, isReadOnly))
  4706. {
  4707. ++index;
  4708. if (! filename.containsOnly ("."))
  4709. {
  4710. const File fileFound (path + filename, 0);
  4711. bool matches = false;
  4712. if (isDirectory)
  4713. {
  4714. if (isRecursive && ((whatToLookFor & File::ignoreHiddenFiles) == 0 || ! isHidden))
  4715. subIterator = new DirectoryIterator (fileFound, true, wildCard, whatToLookFor);
  4716. matches = (whatToLookFor & File::findDirectories) != 0;
  4717. }
  4718. else
  4719. {
  4720. matches = (whatToLookFor & File::findFiles) != 0;
  4721. }
  4722. // if recursive, we're not relying on the OS iterator to do the wildcard match, so do it now..
  4723. if (matches && isRecursive)
  4724. matches = filename.matchesWildcard (wildCard, ! File::areFileNamesCaseSensitive());
  4725. if (matches && (whatToLookFor & File::ignoreHiddenFiles) != 0)
  4726. matches = ! isHidden;
  4727. if (matches)
  4728. {
  4729. currentFile = fileFound;
  4730. if (isHiddenResult != 0) *isHiddenResult = isHidden;
  4731. if (isDirResult != 0) *isDirResult = isDirectory;
  4732. return true;
  4733. }
  4734. else if (subIterator != 0)
  4735. {
  4736. return next();
  4737. }
  4738. }
  4739. }
  4740. return false;
  4741. }
  4742. const File DirectoryIterator::getFile() const
  4743. {
  4744. if (subIterator != 0)
  4745. return subIterator->getFile();
  4746. return currentFile;
  4747. }
  4748. float DirectoryIterator::getEstimatedProgress() const
  4749. {
  4750. if (totalNumFiles < 0)
  4751. totalNumFiles = File (path).getNumberOfChildFiles (File::findFilesAndDirectories);
  4752. if (totalNumFiles <= 0)
  4753. return 0.0f;
  4754. const float detailedIndex = (subIterator != 0) ? index + subIterator->getEstimatedProgress()
  4755. : (float) index;
  4756. return detailedIndex / totalNumFiles;
  4757. }
  4758. END_JUCE_NAMESPACE
  4759. /*** End of inlined file: juce_DirectoryIterator.cpp ***/
  4760. /*** Start of inlined file: juce_File.cpp ***/
  4761. #if ! JUCE_WINDOWS
  4762. #include <pwd.h>
  4763. #endif
  4764. BEGIN_JUCE_NAMESPACE
  4765. File::File (const String& fullPathName)
  4766. : fullPath (parseAbsolutePath (fullPathName))
  4767. {
  4768. }
  4769. File::File (const String& path, int)
  4770. : fullPath (path)
  4771. {
  4772. }
  4773. const File File::createFileWithoutCheckingPath (const String& path)
  4774. {
  4775. return File (path, 0);
  4776. }
  4777. File::File (const File& other)
  4778. : fullPath (other.fullPath)
  4779. {
  4780. }
  4781. File& File::operator= (const String& newPath)
  4782. {
  4783. fullPath = parseAbsolutePath (newPath);
  4784. return *this;
  4785. }
  4786. File& File::operator= (const File& other)
  4787. {
  4788. fullPath = other.fullPath;
  4789. return *this;
  4790. }
  4791. const File File::nonexistent;
  4792. const String File::parseAbsolutePath (const String& p)
  4793. {
  4794. if (p.isEmpty())
  4795. return String::empty;
  4796. #if JUCE_WINDOWS
  4797. // Windows..
  4798. String path (p.replaceCharacter ('/', '\\'));
  4799. if (path.startsWithChar (File::separator))
  4800. {
  4801. if (path[1] != File::separator)
  4802. {
  4803. /* When you supply a raw string to the File object constructor, it must be an absolute path.
  4804. If you're trying to parse a string that may be either a relative path or an absolute path,
  4805. you MUST provide a context against which the partial path can be evaluated - you can do
  4806. this by simply using File::getChildFile() instead of the File constructor. E.g. saying
  4807. "File::getCurrentWorkingDirectory().getChildFile (myUnknownPath)" would return an absolute
  4808. path if that's what was supplied, or would evaluate a partial path relative to the CWD.
  4809. */
  4810. jassertfalse
  4811. path = File::getCurrentWorkingDirectory().getFullPathName().substring (0, 2) + path;
  4812. }
  4813. }
  4814. else if (! path.containsChar (':'))
  4815. {
  4816. /* When you supply a raw string to the File object constructor, it must be an absolute path.
  4817. If you're trying to parse a string that may be either a relative path or an absolute path,
  4818. you MUST provide a context against which the partial path can be evaluated - you can do
  4819. this by simply using File::getChildFile() instead of the File constructor. E.g. saying
  4820. "File::getCurrentWorkingDirectory().getChildFile (myUnknownPath)" would return an absolute
  4821. path if that's what was supplied, or would evaluate a partial path relative to the CWD.
  4822. */
  4823. jassertfalse
  4824. return File::getCurrentWorkingDirectory().getChildFile (path).getFullPathName();
  4825. }
  4826. #else
  4827. // Mac or Linux..
  4828. String path (p.replaceCharacter ('\\', '/'));
  4829. if (path.startsWithChar ('~'))
  4830. {
  4831. if (path[1] == File::separator || path[1] == 0)
  4832. {
  4833. // expand a name of the form "~/abc"
  4834. path = File::getSpecialLocation (File::userHomeDirectory).getFullPathName()
  4835. + path.substring (1);
  4836. }
  4837. else
  4838. {
  4839. // expand a name of type "~dave/abc"
  4840. const String userName (path.substring (1).upToFirstOccurrenceOf ("/", false, false));
  4841. struct passwd* const pw = getpwnam (userName.toUTF8());
  4842. if (pw != 0)
  4843. path = addTrailingSeparator (pw->pw_dir) + path.fromFirstOccurrenceOf ("/", false, false);
  4844. }
  4845. }
  4846. else if (! path.startsWithChar (File::separator))
  4847. {
  4848. /* When you supply a raw string to the File object constructor, it must be an absolute path.
  4849. If you're trying to parse a string that may be either a relative path or an absolute path,
  4850. you MUST provide a context against which the partial path can be evaluated - you can do
  4851. this by simply using File::getChildFile() instead of the File constructor. E.g. saying
  4852. "File::getCurrentWorkingDirectory().getChildFile (myUnknownPath)" would return an absolute
  4853. path if that's what was supplied, or would evaluate a partial path relative to the CWD.
  4854. */
  4855. jassert (path.startsWith ("./") || path.startsWith ("../")); // (assume that a path "./xyz" is deliberately intended to be relative to the CWD)
  4856. return File::getCurrentWorkingDirectory().getChildFile (path).getFullPathName();
  4857. }
  4858. #endif
  4859. return path.trimCharactersAtEnd (separatorString);
  4860. }
  4861. const String File::addTrailingSeparator (const String& path)
  4862. {
  4863. return path.endsWithChar (File::separator) ? path
  4864. : path + File::separator;
  4865. }
  4866. #if JUCE_LINUX
  4867. #define NAMES_ARE_CASE_SENSITIVE 1
  4868. #endif
  4869. bool File::areFileNamesCaseSensitive()
  4870. {
  4871. #if NAMES_ARE_CASE_SENSITIVE
  4872. return true;
  4873. #else
  4874. return false;
  4875. #endif
  4876. }
  4877. bool File::operator== (const File& other) const
  4878. {
  4879. #if NAMES_ARE_CASE_SENSITIVE
  4880. return fullPath == other.fullPath;
  4881. #else
  4882. return fullPath.equalsIgnoreCase (other.fullPath);
  4883. #endif
  4884. }
  4885. bool File::operator!= (const File& other) const
  4886. {
  4887. return ! operator== (other);
  4888. }
  4889. bool File::operator< (const File& other) const
  4890. {
  4891. #if NAMES_ARE_CASE_SENSITIVE
  4892. return fullPath < other.fullPath;
  4893. #else
  4894. return fullPath.compareIgnoreCase (other.fullPath) < 0;
  4895. #endif
  4896. }
  4897. bool File::operator> (const File& other) const
  4898. {
  4899. #if NAMES_ARE_CASE_SENSITIVE
  4900. return fullPath > other.fullPath;
  4901. #else
  4902. return fullPath.compareIgnoreCase (other.fullPath) > 0;
  4903. #endif
  4904. }
  4905. bool File::setReadOnly (const bool shouldBeReadOnly,
  4906. const bool applyRecursively) const
  4907. {
  4908. bool worked = true;
  4909. if (applyRecursively && isDirectory())
  4910. {
  4911. Array <File> subFiles;
  4912. findChildFiles (subFiles, File::findFilesAndDirectories, false);
  4913. for (int i = subFiles.size(); --i >= 0;)
  4914. worked = subFiles.getReference(i).setReadOnly (shouldBeReadOnly, true) && worked;
  4915. }
  4916. return setFileReadOnlyInternal (shouldBeReadOnly) && worked;
  4917. }
  4918. bool File::deleteRecursively() const
  4919. {
  4920. bool worked = true;
  4921. if (isDirectory())
  4922. {
  4923. Array<File> subFiles;
  4924. findChildFiles (subFiles, File::findFilesAndDirectories, false);
  4925. for (int i = subFiles.size(); --i >= 0;)
  4926. worked = subFiles.getReference(i).deleteRecursively() && worked;
  4927. }
  4928. return deleteFile() && worked;
  4929. }
  4930. bool File::moveFileTo (const File& newFile) const
  4931. {
  4932. if (newFile.fullPath == fullPath)
  4933. return true;
  4934. #if ! NAMES_ARE_CASE_SENSITIVE
  4935. if (*this != newFile)
  4936. #endif
  4937. if (! newFile.deleteFile())
  4938. return false;
  4939. return moveInternal (newFile);
  4940. }
  4941. bool File::copyFileTo (const File& newFile) const
  4942. {
  4943. return (*this == newFile)
  4944. || (exists() && newFile.deleteFile() && copyInternal (newFile));
  4945. }
  4946. bool File::copyDirectoryTo (const File& newDirectory) const
  4947. {
  4948. if (isDirectory() && newDirectory.createDirectory())
  4949. {
  4950. Array<File> subFiles;
  4951. findChildFiles (subFiles, File::findFiles, false);
  4952. int i;
  4953. for (i = 0; i < subFiles.size(); ++i)
  4954. if (! subFiles.getReference(i).copyFileTo (newDirectory.getChildFile (subFiles.getReference(i).getFileName())))
  4955. return false;
  4956. subFiles.clear();
  4957. findChildFiles (subFiles, File::findDirectories, false);
  4958. for (i = 0; i < subFiles.size(); ++i)
  4959. if (! subFiles.getReference(i).copyDirectoryTo (newDirectory.getChildFile (subFiles.getReference(i).getFileName())))
  4960. return false;
  4961. return true;
  4962. }
  4963. return false;
  4964. }
  4965. const String File::getPathUpToLastSlash() const
  4966. {
  4967. const int lastSlash = fullPath.lastIndexOfChar (separator);
  4968. if (lastSlash > 0)
  4969. return fullPath.substring (0, lastSlash);
  4970. else if (lastSlash == 0)
  4971. return separatorString;
  4972. else
  4973. return fullPath;
  4974. }
  4975. const File File::getParentDirectory() const
  4976. {
  4977. return File (getPathUpToLastSlash());
  4978. }
  4979. const String File::getFileName() const
  4980. {
  4981. return fullPath.substring (fullPath.lastIndexOfChar (separator) + 1);
  4982. }
  4983. int File::hashCode() const
  4984. {
  4985. return fullPath.hashCode();
  4986. }
  4987. int64 File::hashCode64() const
  4988. {
  4989. return fullPath.hashCode64();
  4990. }
  4991. const String File::getFileNameWithoutExtension() const
  4992. {
  4993. const int lastSlash = fullPath.lastIndexOfChar (separator) + 1;
  4994. const int lastDot = fullPath.lastIndexOfChar ('.');
  4995. if (lastDot > lastSlash)
  4996. return fullPath.substring (lastSlash, lastDot);
  4997. else
  4998. return fullPath.substring (lastSlash);
  4999. }
  5000. bool File::isAChildOf (const File& potentialParent) const
  5001. {
  5002. if (potentialParent == File::nonexistent)
  5003. return false;
  5004. const String ourPath (getPathUpToLastSlash());
  5005. #if NAMES_ARE_CASE_SENSITIVE
  5006. if (potentialParent.fullPath == ourPath)
  5007. #else
  5008. if (potentialParent.fullPath.equalsIgnoreCase (ourPath))
  5009. #endif
  5010. {
  5011. return true;
  5012. }
  5013. else if (potentialParent.fullPath.length() >= ourPath.length())
  5014. {
  5015. return false;
  5016. }
  5017. else
  5018. {
  5019. return getParentDirectory().isAChildOf (potentialParent);
  5020. }
  5021. }
  5022. bool File::isAbsolutePath (const String& path)
  5023. {
  5024. return path.startsWithChar ('/') || path.startsWithChar ('\\')
  5025. #if JUCE_WINDOWS
  5026. || (path.isNotEmpty() && path[1] == ':');
  5027. #else
  5028. || path.startsWithChar ('~');
  5029. #endif
  5030. }
  5031. const File File::getChildFile (String relativePath) const
  5032. {
  5033. if (isAbsolutePath (relativePath))
  5034. {
  5035. // the path is really absolute..
  5036. return File (relativePath);
  5037. }
  5038. else
  5039. {
  5040. // it's relative, so remove any ../ or ./ bits at the start.
  5041. String path (fullPath);
  5042. if (relativePath[0] == '.')
  5043. {
  5044. #if JUCE_WINDOWS
  5045. relativePath = relativePath.replaceCharacter ('/', '\\').trimStart();
  5046. #else
  5047. relativePath = relativePath.replaceCharacter ('\\', '/').trimStart();
  5048. #endif
  5049. while (relativePath[0] == '.')
  5050. {
  5051. if (relativePath[1] == '.')
  5052. {
  5053. if (relativePath [2] == 0 || relativePath[2] == separator)
  5054. {
  5055. const int lastSlash = path.lastIndexOfChar (separator);
  5056. if (lastSlash >= 0)
  5057. path = path.substring (0, lastSlash);
  5058. relativePath = relativePath.substring (3);
  5059. }
  5060. else
  5061. {
  5062. break;
  5063. }
  5064. }
  5065. else if (relativePath[1] == separator)
  5066. {
  5067. relativePath = relativePath.substring (2);
  5068. }
  5069. else
  5070. {
  5071. break;
  5072. }
  5073. }
  5074. }
  5075. return File (addTrailingSeparator (path) + relativePath);
  5076. }
  5077. }
  5078. const File File::getSiblingFile (const String& fileName) const
  5079. {
  5080. return getParentDirectory().getChildFile (fileName);
  5081. }
  5082. const String File::descriptionOfSizeInBytes (const int64 bytes)
  5083. {
  5084. if (bytes == 1)
  5085. {
  5086. return "1 byte";
  5087. }
  5088. else if (bytes < 1024)
  5089. {
  5090. return String ((int) bytes) + " bytes";
  5091. }
  5092. else if (bytes < 1024 * 1024)
  5093. {
  5094. return String (bytes / 1024.0, 1) + " KB";
  5095. }
  5096. else if (bytes < 1024 * 1024 * 1024)
  5097. {
  5098. return String (bytes / (1024.0 * 1024.0), 1) + " MB";
  5099. }
  5100. else
  5101. {
  5102. return String (bytes / (1024.0 * 1024.0 * 1024.0), 1) + " GB";
  5103. }
  5104. }
  5105. bool File::create() const
  5106. {
  5107. if (exists())
  5108. return true;
  5109. {
  5110. const File parentDir (getParentDirectory());
  5111. if (parentDir == *this || ! parentDir.createDirectory())
  5112. return false;
  5113. FileOutputStream fo (*this, 8);
  5114. }
  5115. return exists();
  5116. }
  5117. bool File::createDirectory() const
  5118. {
  5119. if (! isDirectory())
  5120. {
  5121. const File parentDir (getParentDirectory());
  5122. if (parentDir == *this || ! parentDir.createDirectory())
  5123. return false;
  5124. createDirectoryInternal (fullPath.trimCharactersAtEnd (separatorString));
  5125. return isDirectory();
  5126. }
  5127. return true;
  5128. }
  5129. const Time File::getCreationTime() const
  5130. {
  5131. int64 m, a, c;
  5132. getFileTimesInternal (m, a, c);
  5133. return Time (c);
  5134. }
  5135. const Time File::getLastModificationTime() const
  5136. {
  5137. int64 m, a, c;
  5138. getFileTimesInternal (m, a, c);
  5139. return Time (m);
  5140. }
  5141. const Time File::getLastAccessTime() const
  5142. {
  5143. int64 m, a, c;
  5144. getFileTimesInternal (m, a, c);
  5145. return Time (a);
  5146. }
  5147. bool File::setLastModificationTime (const Time& t) const { return setFileTimesInternal (t.toMilliseconds(), 0, 0); }
  5148. bool File::setLastAccessTime (const Time& t) const { return setFileTimesInternal (0, t.toMilliseconds(), 0); }
  5149. bool File::setCreationTime (const Time& t) const { return setFileTimesInternal (0, 0, t.toMilliseconds()); }
  5150. bool File::loadFileAsData (MemoryBlock& destBlock) const
  5151. {
  5152. if (! existsAsFile())
  5153. return false;
  5154. FileInputStream in (*this);
  5155. return getSize() == in.readIntoMemoryBlock (destBlock);
  5156. }
  5157. const String File::loadFileAsString() const
  5158. {
  5159. if (! existsAsFile())
  5160. return String::empty;
  5161. FileInputStream in (*this);
  5162. return in.readEntireStreamAsString();
  5163. }
  5164. bool File::fileTypeMatches (const int whatToLookFor, const bool isDir, const bool isHidden)
  5165. {
  5166. return (whatToLookFor & (isDir ? findDirectories
  5167. : findFiles)) != 0
  5168. && ((! isHidden) || (whatToLookFor & File::ignoreHiddenFiles) == 0);
  5169. }
  5170. int File::findChildFiles (Array<File>& results,
  5171. const int whatToLookFor,
  5172. const bool searchRecursively,
  5173. const String& wildCardPattern) const
  5174. {
  5175. // you have to specify the type of files you're looking for!
  5176. jassert ((whatToLookFor & (findFiles | findDirectories)) != 0);
  5177. int total = 0;
  5178. if (isDirectory())
  5179. {
  5180. // find child files or directories in this directory first..
  5181. String path (addTrailingSeparator (fullPath)), filename;
  5182. bool itemIsDirectory, itemIsHidden;
  5183. DirectoryIterator::NativeIterator i (path, wildCardPattern);
  5184. while (i.next (filename, &itemIsDirectory, &itemIsHidden, 0, 0, 0, 0))
  5185. {
  5186. if (! filename.containsOnly ("."))
  5187. {
  5188. const File fileFound (path + filename, 0);
  5189. if (fileTypeMatches (whatToLookFor, itemIsDirectory, itemIsHidden))
  5190. {
  5191. results.add (fileFound);
  5192. ++total;
  5193. }
  5194. if (searchRecursively && itemIsDirectory
  5195. && fileTypeMatches (whatToLookFor | findDirectories, true, itemIsHidden))
  5196. {
  5197. total += fileFound.findChildFiles (results, whatToLookFor, true, wildCardPattern);
  5198. }
  5199. }
  5200. }
  5201. }
  5202. return total;
  5203. }
  5204. int File::getNumberOfChildFiles (const int whatToLookFor,
  5205. const String& wildCardPattern) const
  5206. {
  5207. // you have to specify the type of files you're looking for!
  5208. jassert (whatToLookFor > 0 && whatToLookFor <= 3);
  5209. int count = 0;
  5210. if (isDirectory())
  5211. {
  5212. String filename;
  5213. bool itemIsDirectory, itemIsHidden;
  5214. DirectoryIterator::NativeIterator i (*this, wildCardPattern);
  5215. while (i.next (filename, &itemIsDirectory, &itemIsHidden, 0, 0, 0, 0))
  5216. if (fileTypeMatches (whatToLookFor, itemIsDirectory, itemIsHidden)
  5217. && ! filename.containsOnly ("."))
  5218. ++count;
  5219. }
  5220. else
  5221. {
  5222. // trying to search for files inside a non-directory?
  5223. jassertfalse
  5224. }
  5225. return count;
  5226. }
  5227. bool File::containsSubDirectories() const
  5228. {
  5229. if (isDirectory())
  5230. {
  5231. String filename;
  5232. bool itemIsDirectory;
  5233. DirectoryIterator::NativeIterator i (*this, "*");
  5234. while (i.next (filename, &itemIsDirectory, 0, 0, 0, 0, 0))
  5235. if (itemIsDirectory)
  5236. return true;
  5237. }
  5238. return false;
  5239. }
  5240. const File File::getNonexistentChildFile (const String& prefix_,
  5241. const String& suffix,
  5242. bool putNumbersInBrackets) const
  5243. {
  5244. File f (getChildFile (prefix_ + suffix));
  5245. if (f.exists())
  5246. {
  5247. int num = 2;
  5248. String prefix (prefix_);
  5249. // remove any bracketed numbers that may already be on the end..
  5250. if (prefix.trim().endsWithChar (')'))
  5251. {
  5252. putNumbersInBrackets = true;
  5253. const int openBracks = prefix.lastIndexOfChar ('(');
  5254. const int closeBracks = prefix.lastIndexOfChar (')');
  5255. if (openBracks > 0
  5256. && closeBracks > openBracks
  5257. && prefix.substring (openBracks + 1, closeBracks).containsOnly ("0123456789"))
  5258. {
  5259. num = prefix.substring (openBracks + 1, closeBracks).getIntValue() + 1;
  5260. prefix = prefix.substring (0, openBracks);
  5261. }
  5262. }
  5263. // also use brackets if it ends in a digit.
  5264. putNumbersInBrackets = putNumbersInBrackets
  5265. || CharacterFunctions::isDigit (prefix.getLastCharacter());
  5266. do
  5267. {
  5268. if (putNumbersInBrackets)
  5269. f = getChildFile (prefix + '(' + String (num++) + ')' + suffix);
  5270. else
  5271. f = getChildFile (prefix + String (num++) + suffix);
  5272. } while (f.exists());
  5273. }
  5274. return f;
  5275. }
  5276. const File File::getNonexistentSibling (const bool putNumbersInBrackets) const
  5277. {
  5278. if (exists())
  5279. {
  5280. return getParentDirectory()
  5281. .getNonexistentChildFile (getFileNameWithoutExtension(),
  5282. getFileExtension(),
  5283. putNumbersInBrackets);
  5284. }
  5285. else
  5286. {
  5287. return *this;
  5288. }
  5289. }
  5290. const String File::getFileExtension() const
  5291. {
  5292. String ext;
  5293. if (! isDirectory())
  5294. {
  5295. const int indexOfDot = fullPath.lastIndexOfChar ('.');
  5296. if (indexOfDot > fullPath.lastIndexOfChar (separator))
  5297. ext = fullPath.substring (indexOfDot);
  5298. }
  5299. return ext;
  5300. }
  5301. bool File::hasFileExtension (const String& possibleSuffix) const
  5302. {
  5303. if (possibleSuffix.isEmpty())
  5304. return fullPath.lastIndexOfChar ('.') <= fullPath.lastIndexOfChar (separator);
  5305. const int semicolon = possibleSuffix.indexOfChar (0, ';');
  5306. if (semicolon >= 0)
  5307. {
  5308. return hasFileExtension (possibleSuffix.substring (0, semicolon).trimEnd())
  5309. || hasFileExtension (possibleSuffix.substring (semicolon + 1).trimStart());
  5310. }
  5311. else
  5312. {
  5313. if (fullPath.endsWithIgnoreCase (possibleSuffix))
  5314. {
  5315. if (possibleSuffix.startsWithChar ('.'))
  5316. return true;
  5317. const int dotPos = fullPath.length() - possibleSuffix.length() - 1;
  5318. if (dotPos >= 0)
  5319. return fullPath [dotPos] == '.';
  5320. }
  5321. }
  5322. return false;
  5323. }
  5324. const File File::withFileExtension (const String& newExtension) const
  5325. {
  5326. if (fullPath.isEmpty())
  5327. return File::nonexistent;
  5328. String filePart (getFileName());
  5329. int i = filePart.lastIndexOfChar ('.');
  5330. if (i >= 0)
  5331. filePart = filePart.substring (0, i);
  5332. if (newExtension.isNotEmpty() && ! newExtension.startsWithChar ('.'))
  5333. filePart << '.';
  5334. return getSiblingFile (filePart + newExtension);
  5335. }
  5336. bool File::startAsProcess (const String& parameters) const
  5337. {
  5338. return exists() && PlatformUtilities::openDocument (fullPath, parameters);
  5339. }
  5340. FileInputStream* File::createInputStream() const
  5341. {
  5342. if (existsAsFile())
  5343. return new FileInputStream (*this);
  5344. return 0;
  5345. }
  5346. FileOutputStream* File::createOutputStream (const int bufferSize) const
  5347. {
  5348. ScopedPointer <FileOutputStream> out (new FileOutputStream (*this, bufferSize));
  5349. if (out->failedToOpen())
  5350. return 0;
  5351. return out.release();
  5352. }
  5353. bool File::appendData (const void* const dataToAppend,
  5354. const int numberOfBytes) const
  5355. {
  5356. if (numberOfBytes > 0)
  5357. {
  5358. const ScopedPointer <FileOutputStream> out (createOutputStream());
  5359. if (out == 0)
  5360. return false;
  5361. out->write (dataToAppend, numberOfBytes);
  5362. }
  5363. return true;
  5364. }
  5365. bool File::replaceWithData (const void* const dataToWrite,
  5366. const int numberOfBytes) const
  5367. {
  5368. jassert (numberOfBytes >= 0); // a negative number of bytes??
  5369. if (numberOfBytes <= 0)
  5370. return deleteFile();
  5371. TemporaryFile tempFile (*this, TemporaryFile::useHiddenFile);
  5372. tempFile.getFile().appendData (dataToWrite, numberOfBytes);
  5373. return tempFile.overwriteTargetFileWithTemporary();
  5374. }
  5375. bool File::appendText (const String& text,
  5376. const bool asUnicode,
  5377. const bool writeUnicodeHeaderBytes) const
  5378. {
  5379. const ScopedPointer <FileOutputStream> out (createOutputStream());
  5380. if (out != 0)
  5381. {
  5382. out->writeText (text, asUnicode, writeUnicodeHeaderBytes);
  5383. return true;
  5384. }
  5385. return false;
  5386. }
  5387. bool File::replaceWithText (const String& textToWrite,
  5388. const bool asUnicode,
  5389. const bool writeUnicodeHeaderBytes) const
  5390. {
  5391. TemporaryFile tempFile (*this, TemporaryFile::useHiddenFile);
  5392. tempFile.getFile().appendText (textToWrite, asUnicode, writeUnicodeHeaderBytes);
  5393. return tempFile.overwriteTargetFileWithTemporary();
  5394. }
  5395. const String File::createLegalPathName (const String& original)
  5396. {
  5397. String s (original);
  5398. String start;
  5399. if (s[1] == ':')
  5400. {
  5401. start = s.substring (0, 2);
  5402. s = s.substring (2);
  5403. }
  5404. return start + s.removeCharacters ("\"#@,;:<>*^|?")
  5405. .substring (0, 1024);
  5406. }
  5407. const String File::createLegalFileName (const String& original)
  5408. {
  5409. String s (original.removeCharacters ("\"#@,;:<>*^|?\\/"));
  5410. const int maxLength = 128; // only the length of the filename, not the whole path
  5411. const int len = s.length();
  5412. if (len > maxLength)
  5413. {
  5414. const int lastDot = s.lastIndexOfChar ('.');
  5415. if (lastDot > jmax (0, len - 12))
  5416. {
  5417. s = s.substring (0, maxLength - (len - lastDot))
  5418. + s.substring (lastDot);
  5419. }
  5420. else
  5421. {
  5422. s = s.substring (0, maxLength);
  5423. }
  5424. }
  5425. return s;
  5426. }
  5427. const String File::getRelativePathFrom (const File& dir) const
  5428. {
  5429. String thisPath (fullPath);
  5430. {
  5431. int len = thisPath.length();
  5432. while (--len >= 0 && thisPath [len] == File::separator)
  5433. thisPath [len] = 0;
  5434. }
  5435. String dirPath (addTrailingSeparator (dir.existsAsFile() ? dir.getParentDirectory().getFullPathName()
  5436. : dir.fullPath));
  5437. const int len = jmin (thisPath.length(), dirPath.length());
  5438. int commonBitLength = 0;
  5439. for (int i = 0; i < len; ++i)
  5440. {
  5441. #if NAMES_ARE_CASE_SENSITIVE
  5442. if (thisPath[i] != dirPath[i])
  5443. #else
  5444. if (CharacterFunctions::toLowerCase (thisPath[i])
  5445. != CharacterFunctions::toLowerCase (dirPath[i]))
  5446. #endif
  5447. {
  5448. break;
  5449. }
  5450. ++commonBitLength;
  5451. }
  5452. while (commonBitLength > 0 && thisPath [commonBitLength - 1] != File::separator)
  5453. --commonBitLength;
  5454. // if the only common bit is the root, then just return the full path..
  5455. if (commonBitLength <= 0
  5456. || (commonBitLength == 1 && thisPath [1] == File::separator))
  5457. return fullPath;
  5458. thisPath = thisPath.substring (commonBitLength);
  5459. dirPath = dirPath.substring (commonBitLength);
  5460. while (dirPath.isNotEmpty())
  5461. {
  5462. #if JUCE_WINDOWS
  5463. thisPath = "..\\" + thisPath;
  5464. #else
  5465. thisPath = "../" + thisPath;
  5466. #endif
  5467. const int sep = dirPath.indexOfChar (separator);
  5468. if (sep >= 0)
  5469. dirPath = dirPath.substring (sep + 1);
  5470. else
  5471. dirPath = String::empty;
  5472. }
  5473. return thisPath;
  5474. }
  5475. const File File::createTempFile (const String& fileNameEnding)
  5476. {
  5477. const File tempFile (getSpecialLocation (tempDirectory)
  5478. .getChildFile ("temp_" + String (Random::getSystemRandom().nextInt()))
  5479. .withFileExtension (fileNameEnding));
  5480. if (tempFile.exists())
  5481. return createTempFile (fileNameEnding);
  5482. else
  5483. return tempFile;
  5484. }
  5485. END_JUCE_NAMESPACE
  5486. /*** End of inlined file: juce_File.cpp ***/
  5487. /*** Start of inlined file: juce_FileInputStream.cpp ***/
  5488. BEGIN_JUCE_NAMESPACE
  5489. void* juce_fileOpen (const File& file, bool forWriting);
  5490. void juce_fileClose (void* handle);
  5491. int juce_fileRead (void* handle, void* buffer, int size);
  5492. int64 juce_fileSetPosition (void* handle, int64 pos);
  5493. FileInputStream::FileInputStream (const File& f)
  5494. : file (f),
  5495. currentPosition (0),
  5496. needToSeek (true)
  5497. {
  5498. totalSize = f.getSize();
  5499. fileHandle = juce_fileOpen (f, false);
  5500. }
  5501. FileInputStream::~FileInputStream()
  5502. {
  5503. juce_fileClose (fileHandle);
  5504. }
  5505. int64 FileInputStream::getTotalLength()
  5506. {
  5507. return totalSize;
  5508. }
  5509. int FileInputStream::read (void* buffer, int bytesToRead)
  5510. {
  5511. int num = 0;
  5512. if (needToSeek)
  5513. {
  5514. if (juce_fileSetPosition (fileHandle, currentPosition) < 0)
  5515. return 0;
  5516. needToSeek = false;
  5517. }
  5518. num = juce_fileRead (fileHandle, buffer, bytesToRead);
  5519. currentPosition += num;
  5520. return num;
  5521. }
  5522. bool FileInputStream::isExhausted()
  5523. {
  5524. return currentPosition >= totalSize;
  5525. }
  5526. int64 FileInputStream::getPosition()
  5527. {
  5528. return currentPosition;
  5529. }
  5530. bool FileInputStream::setPosition (int64 pos)
  5531. {
  5532. pos = jlimit ((int64) 0, totalSize, pos);
  5533. needToSeek |= (currentPosition != pos);
  5534. currentPosition = pos;
  5535. return true;
  5536. }
  5537. END_JUCE_NAMESPACE
  5538. /*** End of inlined file: juce_FileInputStream.cpp ***/
  5539. /*** Start of inlined file: juce_FileOutputStream.cpp ***/
  5540. BEGIN_JUCE_NAMESPACE
  5541. void* juce_fileOpen (const File& file, bool forWriting);
  5542. void juce_fileClose (void* handle);
  5543. int juce_fileWrite (void* handle, const void* buffer, int size);
  5544. int64 juce_fileSetPosition (void* handle, int64 pos);
  5545. FileOutputStream::FileOutputStream (const File& f,
  5546. const int bufferSize_)
  5547. : file (f),
  5548. bufferSize (bufferSize_),
  5549. bytesInBuffer (0)
  5550. {
  5551. fileHandle = juce_fileOpen (f, true);
  5552. if (fileHandle != 0)
  5553. {
  5554. currentPosition = getPositionInternal();
  5555. if (currentPosition < 0)
  5556. {
  5557. jassertfalse
  5558. juce_fileClose (fileHandle);
  5559. fileHandle = 0;
  5560. }
  5561. }
  5562. buffer.malloc (jmax (bufferSize_, 16));
  5563. }
  5564. FileOutputStream::~FileOutputStream()
  5565. {
  5566. flush();
  5567. juce_fileClose (fileHandle);
  5568. }
  5569. int64 FileOutputStream::getPosition()
  5570. {
  5571. return currentPosition;
  5572. }
  5573. bool FileOutputStream::setPosition (int64 newPosition)
  5574. {
  5575. if (newPosition != currentPosition)
  5576. {
  5577. flush();
  5578. currentPosition = juce_fileSetPosition (fileHandle, newPosition);
  5579. }
  5580. return newPosition == currentPosition;
  5581. }
  5582. void FileOutputStream::flush()
  5583. {
  5584. if (bytesInBuffer > 0)
  5585. {
  5586. juce_fileWrite (fileHandle, buffer, bytesInBuffer);
  5587. bytesInBuffer = 0;
  5588. }
  5589. flushInternal();
  5590. }
  5591. bool FileOutputStream::write (const void* const src, const int numBytes)
  5592. {
  5593. if (bytesInBuffer + numBytes < bufferSize)
  5594. {
  5595. memcpy (buffer + bytesInBuffer, src, numBytes);
  5596. bytesInBuffer += numBytes;
  5597. currentPosition += numBytes;
  5598. }
  5599. else
  5600. {
  5601. if (bytesInBuffer > 0)
  5602. {
  5603. // flush the reservoir
  5604. const bool wroteOk = (juce_fileWrite (fileHandle, buffer, bytesInBuffer) == bytesInBuffer);
  5605. bytesInBuffer = 0;
  5606. if (! wroteOk)
  5607. return false;
  5608. }
  5609. if (numBytes < bufferSize)
  5610. {
  5611. memcpy (buffer + bytesInBuffer, src, numBytes);
  5612. bytesInBuffer += numBytes;
  5613. currentPosition += numBytes;
  5614. }
  5615. else
  5616. {
  5617. const int bytesWritten = juce_fileWrite (fileHandle, src, numBytes);
  5618. currentPosition += bytesWritten;
  5619. return bytesWritten == numBytes;
  5620. }
  5621. }
  5622. return true;
  5623. }
  5624. END_JUCE_NAMESPACE
  5625. /*** End of inlined file: juce_FileOutputStream.cpp ***/
  5626. /*** Start of inlined file: juce_FileSearchPath.cpp ***/
  5627. BEGIN_JUCE_NAMESPACE
  5628. FileSearchPath::FileSearchPath()
  5629. {
  5630. }
  5631. FileSearchPath::FileSearchPath (const String& path)
  5632. {
  5633. init (path);
  5634. }
  5635. FileSearchPath::FileSearchPath (const FileSearchPath& other)
  5636. : directories (other.directories)
  5637. {
  5638. }
  5639. FileSearchPath::~FileSearchPath()
  5640. {
  5641. }
  5642. FileSearchPath& FileSearchPath::operator= (const String& path)
  5643. {
  5644. init (path);
  5645. return *this;
  5646. }
  5647. void FileSearchPath::init (const String& path)
  5648. {
  5649. directories.clear();
  5650. directories.addTokens (path, ";", "\"");
  5651. directories.trim();
  5652. directories.removeEmptyStrings();
  5653. for (int i = directories.size(); --i >= 0;)
  5654. directories.set (i, directories[i].unquoted());
  5655. }
  5656. int FileSearchPath::getNumPaths() const
  5657. {
  5658. return directories.size();
  5659. }
  5660. const File FileSearchPath::operator[] (const int index) const
  5661. {
  5662. return File (directories [index]);
  5663. }
  5664. const String FileSearchPath::toString() const
  5665. {
  5666. StringArray directories2 (directories);
  5667. for (int i = directories2.size(); --i >= 0;)
  5668. if (directories2[i].containsChar (';'))
  5669. directories2.set (i, directories2[i].quoted());
  5670. return directories2.joinIntoString (";");
  5671. }
  5672. void FileSearchPath::add (const File& dir, const int insertIndex)
  5673. {
  5674. directories.insert (insertIndex, dir.getFullPathName());
  5675. }
  5676. void FileSearchPath::addIfNotAlreadyThere (const File& dir)
  5677. {
  5678. for (int i = 0; i < directories.size(); ++i)
  5679. if (File (directories[i]) == dir)
  5680. return;
  5681. add (dir);
  5682. }
  5683. void FileSearchPath::remove (const int index)
  5684. {
  5685. directories.remove (index);
  5686. }
  5687. void FileSearchPath::addPath (const FileSearchPath& other)
  5688. {
  5689. for (int i = 0; i < other.getNumPaths(); ++i)
  5690. addIfNotAlreadyThere (other[i]);
  5691. }
  5692. void FileSearchPath::removeRedundantPaths()
  5693. {
  5694. for (int i = directories.size(); --i >= 0;)
  5695. {
  5696. const File d1 (directories[i]);
  5697. for (int j = directories.size(); --j >= 0;)
  5698. {
  5699. const File d2 (directories[j]);
  5700. if ((i != j) && (d1.isAChildOf (d2) || d1 == d2))
  5701. {
  5702. directories.remove (i);
  5703. break;
  5704. }
  5705. }
  5706. }
  5707. }
  5708. void FileSearchPath::removeNonExistentPaths()
  5709. {
  5710. for (int i = directories.size(); --i >= 0;)
  5711. if (! File (directories[i]).isDirectory())
  5712. directories.remove (i);
  5713. }
  5714. int FileSearchPath::findChildFiles (Array<File>& results,
  5715. const int whatToLookFor,
  5716. const bool searchRecursively,
  5717. const String& wildCardPattern) const
  5718. {
  5719. int total = 0;
  5720. for (int i = 0; i < directories.size(); ++i)
  5721. total += operator[] (i).findChildFiles (results,
  5722. whatToLookFor,
  5723. searchRecursively,
  5724. wildCardPattern);
  5725. return total;
  5726. }
  5727. bool FileSearchPath::isFileInPath (const File& fileToCheck,
  5728. const bool checkRecursively) const
  5729. {
  5730. for (int i = directories.size(); --i >= 0;)
  5731. {
  5732. const File d (directories[i]);
  5733. if (checkRecursively)
  5734. {
  5735. if (fileToCheck.isAChildOf (d))
  5736. return true;
  5737. }
  5738. else
  5739. {
  5740. if (fileToCheck.getParentDirectory() == d)
  5741. return true;
  5742. }
  5743. }
  5744. return false;
  5745. }
  5746. END_JUCE_NAMESPACE
  5747. /*** End of inlined file: juce_FileSearchPath.cpp ***/
  5748. /*** Start of inlined file: juce_NamedPipe.cpp ***/
  5749. BEGIN_JUCE_NAMESPACE
  5750. NamedPipe::NamedPipe()
  5751. : internal (0)
  5752. {
  5753. }
  5754. NamedPipe::~NamedPipe()
  5755. {
  5756. close();
  5757. }
  5758. bool NamedPipe::openExisting (const String& pipeName)
  5759. {
  5760. currentPipeName = pipeName;
  5761. return openInternal (pipeName, false);
  5762. }
  5763. bool NamedPipe::createNewPipe (const String& pipeName)
  5764. {
  5765. currentPipeName = pipeName;
  5766. return openInternal (pipeName, true);
  5767. }
  5768. bool NamedPipe::isOpen() const
  5769. {
  5770. return internal != 0;
  5771. }
  5772. const String NamedPipe::getName() const
  5773. {
  5774. return currentPipeName;
  5775. }
  5776. // other methods for this class are implemented in the platform-specific files
  5777. END_JUCE_NAMESPACE
  5778. /*** End of inlined file: juce_NamedPipe.cpp ***/
  5779. /*** Start of inlined file: juce_TemporaryFile.cpp ***/
  5780. BEGIN_JUCE_NAMESPACE
  5781. TemporaryFile::TemporaryFile (const String& suffix, const int optionFlags)
  5782. {
  5783. createTempFile (File::getSpecialLocation (File::tempDirectory),
  5784. "temp_" + String (Random::getSystemRandom().nextInt()),
  5785. suffix,
  5786. optionFlags);
  5787. }
  5788. TemporaryFile::TemporaryFile (const File& targetFile_, const int optionFlags)
  5789. : targetFile (targetFile_)
  5790. {
  5791. // If you use this constructor, you need to give it a valid target file!
  5792. jassert (targetFile != File::nonexistent);
  5793. createTempFile (targetFile.getParentDirectory(),
  5794. targetFile.getFileNameWithoutExtension() + "_temp" + String (Random::getSystemRandom().nextInt()),
  5795. targetFile.getFileExtension(),
  5796. optionFlags);
  5797. }
  5798. void TemporaryFile::createTempFile (const File& parentDirectory, String name,
  5799. const String& suffix, const int optionFlags)
  5800. {
  5801. if ((optionFlags & useHiddenFile) != 0)
  5802. name = "." + name;
  5803. temporaryFile = parentDirectory.getNonexistentChildFile (name, suffix, (optionFlags & putNumbersInBrackets) != 0);
  5804. }
  5805. TemporaryFile::~TemporaryFile()
  5806. {
  5807. // Have a few attempts at deleting the file before giving up..
  5808. for (int i = 5; --i >= 0;)
  5809. {
  5810. if (temporaryFile.deleteFile())
  5811. return;
  5812. Thread::sleep (50);
  5813. }
  5814. // Failed to delete our temporary file! Check that you've deleted all the
  5815. // file output streams that were using it!
  5816. jassertfalse;
  5817. }
  5818. bool TemporaryFile::overwriteTargetFileWithTemporary() const
  5819. {
  5820. // This method only works if you created this object with the constructor
  5821. // that takes a target file!
  5822. jassert (targetFile != File::nonexistent);
  5823. if (temporaryFile.exists())
  5824. {
  5825. // Have a few attempts at overwriting the file before giving up..
  5826. for (int i = 5; --i >= 0;)
  5827. {
  5828. if (temporaryFile.moveFileTo (targetFile))
  5829. return true;
  5830. Thread::sleep (100);
  5831. }
  5832. }
  5833. else
  5834. {
  5835. // There's no temporary file to use. If your write failed, you should
  5836. // probably check, and not bother calling this method.
  5837. jassertfalse
  5838. }
  5839. return false;
  5840. }
  5841. END_JUCE_NAMESPACE
  5842. /*** End of inlined file: juce_TemporaryFile.cpp ***/
  5843. /*** Start of inlined file: juce_Socket.cpp ***/
  5844. #if JUCE_WINDOWS
  5845. #include <winsock2.h>
  5846. #ifdef _MSC_VER
  5847. #pragma warning (disable : 4127 4389 4018)
  5848. #endif
  5849. #else
  5850. #if JUCE_LINUX
  5851. #include <sys/types.h>
  5852. #include <sys/socket.h>
  5853. #include <sys/errno.h>
  5854. #include <unistd.h>
  5855. #include <netinet/in.h>
  5856. #elif (MACOSX_DEPLOYMENT_TARGET <= MAC_OS_X_VERSION_10_4) && ! JUCE_IPHONE
  5857. #include <CoreServices/CoreServices.h>
  5858. #endif
  5859. #include <fcntl.h>
  5860. #include <netdb.h>
  5861. #include <arpa/inet.h>
  5862. #include <netinet/tcp.h>
  5863. #endif
  5864. BEGIN_JUCE_NAMESPACE
  5865. #if defined (JUCE_LINUX) || defined (JUCE_MAC) || defined (JUCE_IPHONE)
  5866. typedef socklen_t juce_socklen_t;
  5867. #else
  5868. typedef int juce_socklen_t;
  5869. #endif
  5870. #if JUCE_WINDOWS
  5871. typedef int (__stdcall juce_CloseWin32SocketLibCall) (void);
  5872. juce_CloseWin32SocketLibCall* juce_CloseWin32SocketLib = 0;
  5873. static void initWin32Sockets()
  5874. {
  5875. static CriticalSection lock;
  5876. const ScopedLock sl (lock);
  5877. if (juce_CloseWin32SocketLib == 0)
  5878. {
  5879. WSADATA wsaData;
  5880. const WORD wVersionRequested = MAKEWORD (1, 1);
  5881. WSAStartup (wVersionRequested, &wsaData);
  5882. juce_CloseWin32SocketLib = &WSACleanup;
  5883. }
  5884. }
  5885. #endif
  5886. static bool resetSocketOptions (const int handle, const bool isDatagram, const bool allowBroadcast) throw()
  5887. {
  5888. const int sndBufSize = 65536;
  5889. const int rcvBufSize = 65536;
  5890. const int one = 1;
  5891. return handle > 0
  5892. && setsockopt (handle, SOL_SOCKET, SO_RCVBUF, (const char*) &rcvBufSize, sizeof (rcvBufSize)) == 0
  5893. && setsockopt (handle, SOL_SOCKET, SO_SNDBUF, (const char*) &sndBufSize, sizeof (sndBufSize)) == 0
  5894. && (isDatagram ? ((! allowBroadcast) || setsockopt (handle, SOL_SOCKET, SO_BROADCAST, (const char*) &one, sizeof (one)) == 0)
  5895. : (setsockopt (handle, IPPROTO_TCP, TCP_NODELAY, (const char*) &one, sizeof (one)) == 0));
  5896. }
  5897. static bool bindSocketToPort (const int handle, const int port) throw()
  5898. {
  5899. if (handle <= 0 || port <= 0)
  5900. return false;
  5901. struct sockaddr_in servTmpAddr;
  5902. zerostruct (servTmpAddr);
  5903. servTmpAddr.sin_family = PF_INET;
  5904. servTmpAddr.sin_addr.s_addr = htonl (INADDR_ANY);
  5905. servTmpAddr.sin_port = htons ((uint16) port);
  5906. return bind (handle, (struct sockaddr*) &servTmpAddr, sizeof (struct sockaddr_in)) >= 0;
  5907. }
  5908. static int readSocket (const int handle,
  5909. void* const destBuffer, const int maxBytesToRead,
  5910. bool volatile& connected,
  5911. const bool blockUntilSpecifiedAmountHasArrived) throw()
  5912. {
  5913. int bytesRead = 0;
  5914. while (bytesRead < maxBytesToRead)
  5915. {
  5916. int bytesThisTime;
  5917. #if JUCE_WINDOWS
  5918. bytesThisTime = recv (handle, ((char*) destBuffer) + bytesRead, maxBytesToRead - bytesRead, 0);
  5919. #else
  5920. while ((bytesThisTime = (int) ::read (handle, ((char*) destBuffer) + bytesRead, maxBytesToRead - bytesRead)) < 0
  5921. && errno == EINTR
  5922. && connected)
  5923. {
  5924. }
  5925. #endif
  5926. if (bytesThisTime <= 0 || ! connected)
  5927. {
  5928. if (bytesRead == 0)
  5929. bytesRead = -1;
  5930. break;
  5931. }
  5932. bytesRead += bytesThisTime;
  5933. if (! blockUntilSpecifiedAmountHasArrived)
  5934. break;
  5935. }
  5936. return bytesRead;
  5937. }
  5938. static int waitForReadiness (const int handle, const bool forReading,
  5939. const int timeoutMsecs) throw()
  5940. {
  5941. struct timeval timeout;
  5942. struct timeval* timeoutp;
  5943. if (timeoutMsecs >= 0)
  5944. {
  5945. timeout.tv_sec = timeoutMsecs / 1000;
  5946. timeout.tv_usec = (timeoutMsecs % 1000) * 1000;
  5947. timeoutp = &timeout;
  5948. }
  5949. else
  5950. {
  5951. timeoutp = 0;
  5952. }
  5953. fd_set rset, wset;
  5954. FD_ZERO (&rset);
  5955. FD_SET (handle, &rset);
  5956. FD_ZERO (&wset);
  5957. FD_SET (handle, &wset);
  5958. fd_set* const prset = forReading ? &rset : 0;
  5959. fd_set* const pwset = forReading ? 0 : &wset;
  5960. #if JUCE_WINDOWS
  5961. if (select (handle + 1, prset, pwset, 0, timeoutp) < 0)
  5962. return -1;
  5963. #else
  5964. {
  5965. int result;
  5966. while ((result = select (handle + 1, prset, pwset, 0, timeoutp)) < 0
  5967. && errno == EINTR)
  5968. {
  5969. }
  5970. if (result < 0)
  5971. return -1;
  5972. }
  5973. #endif
  5974. {
  5975. int opt;
  5976. juce_socklen_t len = sizeof (opt);
  5977. if (getsockopt (handle, SOL_SOCKET, SO_ERROR, (char*) &opt, &len) < 0
  5978. || opt != 0)
  5979. return -1;
  5980. }
  5981. if ((forReading && FD_ISSET (handle, &rset))
  5982. || ((! forReading) && FD_ISSET (handle, &wset)))
  5983. return 1;
  5984. return 0;
  5985. }
  5986. static bool setSocketBlockingState (const int handle, const bool shouldBlock) throw()
  5987. {
  5988. #if JUCE_WINDOWS
  5989. u_long nonBlocking = shouldBlock ? 0 : 1;
  5990. if (ioctlsocket (handle, FIONBIO, &nonBlocking) != 0)
  5991. return false;
  5992. #else
  5993. int socketFlags = fcntl (handle, F_GETFL, 0);
  5994. if (socketFlags == -1)
  5995. return false;
  5996. if (shouldBlock)
  5997. socketFlags &= ~O_NONBLOCK;
  5998. else
  5999. socketFlags |= O_NONBLOCK;
  6000. if (fcntl (handle, F_SETFL, socketFlags) != 0)
  6001. return false;
  6002. #endif
  6003. return true;
  6004. }
  6005. static bool connectSocket (int volatile& handle,
  6006. const bool isDatagram,
  6007. void** serverAddress,
  6008. const String& hostName,
  6009. const int portNumber,
  6010. const int timeOutMillisecs) throw()
  6011. {
  6012. struct hostent* const hostEnt = gethostbyname (hostName.toUTF8());
  6013. if (hostEnt == 0)
  6014. return false;
  6015. struct in_addr targetAddress;
  6016. memcpy (&targetAddress.s_addr,
  6017. *(hostEnt->h_addr_list),
  6018. sizeof (targetAddress.s_addr));
  6019. struct sockaddr_in servTmpAddr;
  6020. zerostruct (servTmpAddr);
  6021. servTmpAddr.sin_family = PF_INET;
  6022. servTmpAddr.sin_addr = targetAddress;
  6023. servTmpAddr.sin_port = htons ((uint16) portNumber);
  6024. if (handle < 0)
  6025. handle = (int) socket (AF_INET, isDatagram ? SOCK_DGRAM : SOCK_STREAM, 0);
  6026. if (handle < 0)
  6027. return false;
  6028. if (isDatagram)
  6029. {
  6030. *serverAddress = new struct sockaddr_in();
  6031. *((struct sockaddr_in*) *serverAddress) = servTmpAddr;
  6032. return true;
  6033. }
  6034. setSocketBlockingState (handle, false);
  6035. const int result = ::connect (handle, (struct sockaddr*) &servTmpAddr, sizeof (struct sockaddr_in));
  6036. if (result < 0)
  6037. {
  6038. #if JUCE_WINDOWS
  6039. if (result == SOCKET_ERROR && WSAGetLastError() == WSAEWOULDBLOCK)
  6040. #else
  6041. if (errno == EINPROGRESS)
  6042. #endif
  6043. {
  6044. if (waitForReadiness (handle, false, timeOutMillisecs) != 1)
  6045. {
  6046. setSocketBlockingState (handle, true);
  6047. return false;
  6048. }
  6049. }
  6050. }
  6051. setSocketBlockingState (handle, true);
  6052. resetSocketOptions (handle, false, false);
  6053. return true;
  6054. }
  6055. StreamingSocket::StreamingSocket()
  6056. : portNumber (0),
  6057. handle (-1),
  6058. connected (false),
  6059. isListener (false)
  6060. {
  6061. #if JUCE_WINDOWS
  6062. initWin32Sockets();
  6063. #endif
  6064. }
  6065. StreamingSocket::StreamingSocket (const String& hostName_,
  6066. const int portNumber_,
  6067. const int handle_)
  6068. : hostName (hostName_),
  6069. portNumber (portNumber_),
  6070. handle (handle_),
  6071. connected (true),
  6072. isListener (false)
  6073. {
  6074. #if JUCE_WINDOWS
  6075. initWin32Sockets();
  6076. #endif
  6077. resetSocketOptions (handle_, false, false);
  6078. }
  6079. StreamingSocket::~StreamingSocket()
  6080. {
  6081. close();
  6082. }
  6083. int StreamingSocket::read (void* destBuffer, const int maxBytesToRead, const bool blockUntilSpecifiedAmountHasArrived)
  6084. {
  6085. return (connected && ! isListener) ? readSocket (handle, destBuffer, maxBytesToRead, connected, blockUntilSpecifiedAmountHasArrived)
  6086. : -1;
  6087. }
  6088. int StreamingSocket::write (const void* sourceBuffer, const int numBytesToWrite)
  6089. {
  6090. if (isListener || ! connected)
  6091. return -1;
  6092. #if JUCE_WINDOWS
  6093. return send (handle, (const char*) sourceBuffer, numBytesToWrite, 0);
  6094. #else
  6095. int result;
  6096. while ((result = (int) ::write (handle, sourceBuffer, numBytesToWrite)) < 0
  6097. && errno == EINTR)
  6098. {
  6099. }
  6100. return result;
  6101. #endif
  6102. }
  6103. int StreamingSocket::waitUntilReady (const bool readyForReading,
  6104. const int timeoutMsecs) const
  6105. {
  6106. return connected ? waitForReadiness (handle, readyForReading, timeoutMsecs)
  6107. : -1;
  6108. }
  6109. bool StreamingSocket::bindToPort (const int port)
  6110. {
  6111. return bindSocketToPort (handle, port);
  6112. }
  6113. bool StreamingSocket::connect (const String& remoteHostName,
  6114. const int remotePortNumber,
  6115. const int timeOutMillisecs)
  6116. {
  6117. if (isListener)
  6118. {
  6119. jassertfalse // a listener socket can't connect to another one!
  6120. return false;
  6121. }
  6122. if (connected)
  6123. close();
  6124. hostName = remoteHostName;
  6125. portNumber = remotePortNumber;
  6126. isListener = false;
  6127. connected = connectSocket (handle, false, 0, remoteHostName,
  6128. remotePortNumber, timeOutMillisecs);
  6129. if (! (connected && resetSocketOptions (handle, false, false)))
  6130. {
  6131. close();
  6132. return false;
  6133. }
  6134. return true;
  6135. }
  6136. void StreamingSocket::close()
  6137. {
  6138. #if JUCE_WINDOWS
  6139. if (handle != SOCKET_ERROR || connected)
  6140. closesocket (handle);
  6141. connected = false;
  6142. #else
  6143. if (connected)
  6144. {
  6145. connected = false;
  6146. if (isListener)
  6147. {
  6148. // need to do this to interrupt the accept() function..
  6149. StreamingSocket temp;
  6150. temp.connect ("localhost", portNumber, 1000);
  6151. }
  6152. }
  6153. if (handle != -1)
  6154. ::close (handle);
  6155. #endif
  6156. hostName = String::empty;
  6157. portNumber = 0;
  6158. handle = -1;
  6159. isListener = false;
  6160. }
  6161. bool StreamingSocket::createListener (const int newPortNumber, const String& localHostName)
  6162. {
  6163. if (connected)
  6164. close();
  6165. hostName = "listener";
  6166. portNumber = newPortNumber;
  6167. isListener = true;
  6168. struct sockaddr_in servTmpAddr;
  6169. zerostruct (servTmpAddr);
  6170. servTmpAddr.sin_family = PF_INET;
  6171. servTmpAddr.sin_addr.s_addr = htonl (INADDR_ANY);
  6172. if (localHostName.isNotEmpty())
  6173. servTmpAddr.sin_addr.s_addr = ::inet_addr (localHostName.toUTF8());
  6174. servTmpAddr.sin_port = htons ((uint16) portNumber);
  6175. handle = (int) socket (AF_INET, SOCK_STREAM, 0);
  6176. if (handle < 0)
  6177. return false;
  6178. const int reuse = 1;
  6179. setsockopt (handle, SOL_SOCKET, SO_REUSEADDR, (const char*) &reuse, sizeof (reuse));
  6180. if (bind (handle, (struct sockaddr*) &servTmpAddr, sizeof (struct sockaddr_in)) < 0
  6181. || listen (handle, SOMAXCONN) < 0)
  6182. {
  6183. close();
  6184. return false;
  6185. }
  6186. connected = true;
  6187. return true;
  6188. }
  6189. StreamingSocket* StreamingSocket::waitForNextConnection() const
  6190. {
  6191. jassert (isListener || ! connected); // to call this method, you first have to use createListener() to
  6192. // prepare this socket as a listener.
  6193. if (connected && isListener)
  6194. {
  6195. struct sockaddr address;
  6196. juce_socklen_t len = sizeof (sockaddr);
  6197. const int newSocket = (int) accept (handle, &address, &len);
  6198. if (newSocket >= 0 && connected)
  6199. return new StreamingSocket (inet_ntoa (((struct sockaddr_in*) &address)->sin_addr),
  6200. portNumber, newSocket);
  6201. }
  6202. return 0;
  6203. }
  6204. bool StreamingSocket::isLocal() const throw()
  6205. {
  6206. return hostName == "127.0.0.1";
  6207. }
  6208. DatagramSocket::DatagramSocket (const int localPortNumber, const bool allowBroadcast_)
  6209. : portNumber (0),
  6210. handle (-1),
  6211. connected (true),
  6212. allowBroadcast (allowBroadcast_),
  6213. serverAddress (0)
  6214. {
  6215. #if JUCE_WINDOWS
  6216. initWin32Sockets();
  6217. #endif
  6218. handle = (int) socket (AF_INET, SOCK_DGRAM, 0);
  6219. bindToPort (localPortNumber);
  6220. }
  6221. DatagramSocket::DatagramSocket (const String& hostName_, const int portNumber_,
  6222. const int handle_, const int localPortNumber)
  6223. : hostName (hostName_),
  6224. portNumber (portNumber_),
  6225. handle (handle_),
  6226. connected (true),
  6227. allowBroadcast (false),
  6228. serverAddress (0)
  6229. {
  6230. #if JUCE_WINDOWS
  6231. initWin32Sockets();
  6232. #endif
  6233. resetSocketOptions (handle_, true, allowBroadcast);
  6234. bindToPort (localPortNumber);
  6235. }
  6236. DatagramSocket::~DatagramSocket()
  6237. {
  6238. close();
  6239. delete ((struct sockaddr_in*) serverAddress);
  6240. serverAddress = 0;
  6241. }
  6242. void DatagramSocket::close()
  6243. {
  6244. #if JUCE_WINDOWS
  6245. closesocket (handle);
  6246. connected = false;
  6247. #else
  6248. connected = false;
  6249. ::close (handle);
  6250. #endif
  6251. hostName = String::empty;
  6252. portNumber = 0;
  6253. handle = -1;
  6254. }
  6255. bool DatagramSocket::bindToPort (const int port)
  6256. {
  6257. return bindSocketToPort (handle, port);
  6258. }
  6259. bool DatagramSocket::connect (const String& remoteHostName,
  6260. const int remotePortNumber,
  6261. const int timeOutMillisecs)
  6262. {
  6263. if (connected)
  6264. close();
  6265. hostName = remoteHostName;
  6266. portNumber = remotePortNumber;
  6267. connected = connectSocket (handle, true, &serverAddress,
  6268. remoteHostName, remotePortNumber,
  6269. timeOutMillisecs);
  6270. if (! (connected && resetSocketOptions (handle, true, allowBroadcast)))
  6271. {
  6272. close();
  6273. return false;
  6274. }
  6275. return true;
  6276. }
  6277. DatagramSocket* DatagramSocket::waitForNextConnection() const
  6278. {
  6279. struct sockaddr address;
  6280. juce_socklen_t len = sizeof (sockaddr);
  6281. while (waitUntilReady (true, -1) == 1)
  6282. {
  6283. char buf[1];
  6284. if (recvfrom (handle, buf, 0, 0, &address, &len) > 0)
  6285. {
  6286. return new DatagramSocket (inet_ntoa (((struct sockaddr_in*) &address)->sin_addr),
  6287. ntohs (((struct sockaddr_in*) &address)->sin_port),
  6288. -1, -1);
  6289. }
  6290. }
  6291. return 0;
  6292. }
  6293. int DatagramSocket::waitUntilReady (const bool readyForReading,
  6294. const int timeoutMsecs) const
  6295. {
  6296. return connected ? waitForReadiness (handle, readyForReading, timeoutMsecs)
  6297. : -1;
  6298. }
  6299. int DatagramSocket::read (void* destBuffer, const int maxBytesToRead, const bool blockUntilSpecifiedAmountHasArrived)
  6300. {
  6301. return connected ? readSocket (handle, destBuffer, maxBytesToRead, connected, blockUntilSpecifiedAmountHasArrived)
  6302. : -1;
  6303. }
  6304. int DatagramSocket::write (const void* sourceBuffer, const int numBytesToWrite)
  6305. {
  6306. // You need to call connect() first to set the server address..
  6307. jassert (serverAddress != 0 && connected);
  6308. return connected ? (int) sendto (handle, (const char*) sourceBuffer,
  6309. numBytesToWrite, 0,
  6310. (const struct sockaddr*) serverAddress,
  6311. sizeof (struct sockaddr_in))
  6312. : -1;
  6313. }
  6314. bool DatagramSocket::isLocal() const throw()
  6315. {
  6316. return hostName == "127.0.0.1";
  6317. }
  6318. END_JUCE_NAMESPACE
  6319. /*** End of inlined file: juce_Socket.cpp ***/
  6320. /*** Start of inlined file: juce_URL.cpp ***/
  6321. BEGIN_JUCE_NAMESPACE
  6322. URL::URL()
  6323. {
  6324. }
  6325. URL::URL (const String& url_)
  6326. : url (url_)
  6327. {
  6328. int i = url.indexOfChar ('?');
  6329. if (i >= 0)
  6330. {
  6331. do
  6332. {
  6333. const int nextAmp = url.indexOfChar (i + 1, '&');
  6334. const int equalsPos = url.indexOfChar (i + 1, '=');
  6335. if (equalsPos > i + 1)
  6336. {
  6337. if (nextAmp < 0)
  6338. {
  6339. parameters.set (removeEscapeChars (url.substring (i + 1, equalsPos)),
  6340. removeEscapeChars (url.substring (equalsPos + 1)));
  6341. }
  6342. else if (nextAmp > 0 && equalsPos < nextAmp)
  6343. {
  6344. parameters.set (removeEscapeChars (url.substring (i + 1, equalsPos)),
  6345. removeEscapeChars (url.substring (equalsPos + 1, nextAmp)));
  6346. }
  6347. }
  6348. i = nextAmp;
  6349. }
  6350. while (i >= 0);
  6351. url = url.upToFirstOccurrenceOf ("?", false, false);
  6352. }
  6353. }
  6354. URL::URL (const URL& other)
  6355. : url (other.url),
  6356. postData (other.postData),
  6357. parameters (other.parameters),
  6358. filesToUpload (other.filesToUpload),
  6359. mimeTypes (other.mimeTypes)
  6360. {
  6361. }
  6362. URL& URL::operator= (const URL& other)
  6363. {
  6364. url = other.url;
  6365. postData = other.postData;
  6366. parameters = other.parameters;
  6367. filesToUpload = other.filesToUpload;
  6368. mimeTypes = other.mimeTypes;
  6369. return *this;
  6370. }
  6371. URL::~URL()
  6372. {
  6373. }
  6374. static const String getMangledParameters (const StringPairArray& parameters)
  6375. {
  6376. String p;
  6377. for (int i = 0; i < parameters.size(); ++i)
  6378. {
  6379. if (i > 0)
  6380. p += '&';
  6381. p << URL::addEscapeChars (parameters.getAllKeys() [i], true)
  6382. << '='
  6383. << URL::addEscapeChars (parameters.getAllValues() [i], true);
  6384. }
  6385. return p;
  6386. }
  6387. const String URL::toString (const bool includeGetParameters) const
  6388. {
  6389. if (includeGetParameters && parameters.size() > 0)
  6390. return url + "?" + getMangledParameters (parameters);
  6391. else
  6392. return url;
  6393. }
  6394. bool URL::isWellFormed() const
  6395. {
  6396. //xxx TODO
  6397. return url.isNotEmpty();
  6398. }
  6399. static int findStartOfDomain (const String& url)
  6400. {
  6401. int i = 0;
  6402. while (CharacterFunctions::isLetterOrDigit (url[i])
  6403. || CharacterFunctions::indexOfChar (L"+-.", url[i], false) >= 0)
  6404. ++i;
  6405. return url[i] == ':' ? i + 1 : 0;
  6406. }
  6407. const String URL::getDomain() const
  6408. {
  6409. int start = findStartOfDomain (url);
  6410. while (url[start] == '/')
  6411. ++start;
  6412. const int end1 = url.indexOfChar (start, '/');
  6413. const int end2 = url.indexOfChar (start, ':');
  6414. const int end = (end1 < 0 || end2 < 0) ? jmax (end1, end2)
  6415. : jmin (end1, end2);
  6416. return url.substring (start, end);
  6417. }
  6418. const String URL::getSubPath() const
  6419. {
  6420. int start = findStartOfDomain (url);
  6421. while (url[start] == '/')
  6422. ++start;
  6423. const int startOfPath = url.indexOfChar (start, '/') + 1;
  6424. return startOfPath <= 0 ? String::empty
  6425. : url.substring (startOfPath);
  6426. }
  6427. const String URL::getScheme() const
  6428. {
  6429. return url.substring (0, findStartOfDomain (url) - 1);
  6430. }
  6431. const URL URL::withNewSubPath (const String& newPath) const
  6432. {
  6433. int start = findStartOfDomain (url);
  6434. while (url[start] == '/')
  6435. ++start;
  6436. const int startOfPath = url.indexOfChar (start, '/') + 1;
  6437. URL u (*this);
  6438. if (startOfPath > 0)
  6439. u.url = url.substring (0, startOfPath);
  6440. if (! u.url.endsWithChar ('/'))
  6441. u.url << '/';
  6442. if (newPath.startsWithChar ('/'))
  6443. u.url << newPath.substring (1);
  6444. else
  6445. u.url << newPath;
  6446. return u;
  6447. }
  6448. bool URL::isProbablyAWebsiteURL (const String& possibleURL)
  6449. {
  6450. if (possibleURL.startsWithIgnoreCase ("http:")
  6451. || possibleURL.startsWithIgnoreCase ("ftp:"))
  6452. return true;
  6453. if (possibleURL.startsWithIgnoreCase ("file:")
  6454. || possibleURL.containsChar ('@')
  6455. || possibleURL.endsWithChar ('.')
  6456. || (! possibleURL.containsChar ('.')))
  6457. return false;
  6458. if (possibleURL.startsWithIgnoreCase ("www.")
  6459. && possibleURL.substring (5).containsChar ('.'))
  6460. return true;
  6461. const char* commonTLDs[] = { "com", "net", "org", "uk", "de", "fr", "jp" };
  6462. for (int i = 0; i < numElementsInArray (commonTLDs); ++i)
  6463. if ((possibleURL + "/").containsIgnoreCase ("." + String (commonTLDs[i]) + "/"))
  6464. return true;
  6465. return false;
  6466. }
  6467. bool URL::isProbablyAnEmailAddress (const String& possibleEmailAddress)
  6468. {
  6469. const int atSign = possibleEmailAddress.indexOfChar ('@');
  6470. return atSign > 0
  6471. && possibleEmailAddress.lastIndexOfChar ('.') > (atSign + 1)
  6472. && (! possibleEmailAddress.endsWithChar ('.'));
  6473. }
  6474. void* juce_openInternetFile (const String& url,
  6475. const String& headers,
  6476. const MemoryBlock& optionalPostData,
  6477. const bool isPost,
  6478. URL::OpenStreamProgressCallback* callback,
  6479. void* callbackContext,
  6480. int timeOutMs);
  6481. void juce_closeInternetFile (void* handle);
  6482. int juce_readFromInternetFile (void* handle, void* dest, int bytesToRead);
  6483. int juce_seekInInternetFile (void* handle, int newPosition);
  6484. int64 juce_getInternetFileContentLength (void* handle);
  6485. class WebInputStream : public InputStream
  6486. {
  6487. public:
  6488. WebInputStream (const URL& url,
  6489. const bool isPost_,
  6490. URL::OpenStreamProgressCallback* const progressCallback_,
  6491. void* const progressCallbackContext_,
  6492. const String& extraHeaders,
  6493. int timeOutMs_)
  6494. : position (0),
  6495. finished (false),
  6496. isPost (isPost_),
  6497. progressCallback (progressCallback_),
  6498. progressCallbackContext (progressCallbackContext_),
  6499. timeOutMs (timeOutMs_)
  6500. {
  6501. server = url.toString (! isPost);
  6502. if (isPost_)
  6503. createHeadersAndPostData (url);
  6504. headers += extraHeaders;
  6505. if (! headers.endsWithChar ('\n'))
  6506. headers << "\r\n";
  6507. handle = juce_openInternetFile (server, headers, postData, isPost,
  6508. progressCallback_, progressCallbackContext_,
  6509. timeOutMs);
  6510. }
  6511. ~WebInputStream()
  6512. {
  6513. juce_closeInternetFile (handle);
  6514. }
  6515. bool isError() const { return handle == 0; }
  6516. int64 getTotalLength() { return juce_getInternetFileContentLength (handle); }
  6517. bool isExhausted() { return finished; }
  6518. int64 getPosition() { return position; }
  6519. int read (void* dest, int bytes)
  6520. {
  6521. if (finished || isError())
  6522. {
  6523. return 0;
  6524. }
  6525. else
  6526. {
  6527. const int bytesRead = juce_readFromInternetFile (handle, dest, bytes);
  6528. position += bytesRead;
  6529. if (bytesRead == 0)
  6530. finished = true;
  6531. return bytesRead;
  6532. }
  6533. }
  6534. bool setPosition (int64 wantedPos)
  6535. {
  6536. if (wantedPos != position)
  6537. {
  6538. finished = false;
  6539. const int actualPos = juce_seekInInternetFile (handle, (int) wantedPos);
  6540. if (actualPos == wantedPos)
  6541. {
  6542. position = wantedPos;
  6543. }
  6544. else
  6545. {
  6546. if (wantedPos < position)
  6547. {
  6548. juce_closeInternetFile (handle);
  6549. position = 0;
  6550. finished = false;
  6551. handle = juce_openInternetFile (server, headers, postData, isPost,
  6552. progressCallback, progressCallbackContext,
  6553. timeOutMs);
  6554. }
  6555. skipNextBytes (wantedPos - position);
  6556. }
  6557. }
  6558. return true;
  6559. }
  6560. juce_UseDebuggingNewOperator
  6561. private:
  6562. String server, headers;
  6563. MemoryBlock postData;
  6564. int64 position;
  6565. bool finished;
  6566. const bool isPost;
  6567. void* handle;
  6568. URL::OpenStreamProgressCallback* const progressCallback;
  6569. void* const progressCallbackContext;
  6570. const int timeOutMs;
  6571. void createHeadersAndPostData (const URL& url)
  6572. {
  6573. MemoryOutputStream data (256, 256, &postData);
  6574. if (url.getFilesToUpload().size() > 0)
  6575. {
  6576. // need to upload some files, so do it as multi-part...
  6577. const String boundary (String::toHexString (Random::getSystemRandom().nextInt64()));
  6578. headers << "Content-Type: multipart/form-data; boundary=" << boundary << "\r\n";
  6579. data << "--" << boundary;
  6580. int i;
  6581. for (i = 0; i < url.getParameters().size(); ++i)
  6582. {
  6583. data << "\r\nContent-Disposition: form-data; name=\""
  6584. << url.getParameters().getAllKeys() [i]
  6585. << "\"\r\n\r\n"
  6586. << url.getParameters().getAllValues() [i]
  6587. << "\r\n--"
  6588. << boundary;
  6589. }
  6590. for (i = 0; i < url.getFilesToUpload().size(); ++i)
  6591. {
  6592. const File file (url.getFilesToUpload().getAllValues() [i]);
  6593. const String paramName (url.getFilesToUpload().getAllKeys() [i]);
  6594. data << "\r\nContent-Disposition: form-data; name=\"" << paramName
  6595. << "\"; filename=\"" << file.getFileName() << "\"\r\n";
  6596. const String mimeType (url.getMimeTypesOfUploadFiles()
  6597. .getValue (paramName, String::empty));
  6598. if (mimeType.isNotEmpty())
  6599. data << "Content-Type: " << mimeType << "\r\n";
  6600. data << "Content-Transfer-Encoding: binary\r\n\r\n"
  6601. << file << "\r\n--" << boundary;
  6602. }
  6603. data << "--\r\n";
  6604. }
  6605. else
  6606. {
  6607. data << getMangledParameters (url.getParameters())
  6608. << url.getPostData();
  6609. // just a short text attachment, so use simple url encoding..
  6610. headers = "Content-Type: application/x-www-form-urlencoded\r\nContent-length: "
  6611. + String ((unsigned int) postData.getSize())
  6612. + "\r\n";
  6613. }
  6614. }
  6615. WebInputStream (const WebInputStream&);
  6616. WebInputStream& operator= (const WebInputStream&);
  6617. };
  6618. InputStream* URL::createInputStream (const bool usePostCommand,
  6619. OpenStreamProgressCallback* const progressCallback,
  6620. void* const progressCallbackContext,
  6621. const String& extraHeaders,
  6622. const int timeOutMs) const
  6623. {
  6624. ScopedPointer <WebInputStream> wi (new WebInputStream (*this, usePostCommand,
  6625. progressCallback, progressCallbackContext,
  6626. extraHeaders,
  6627. timeOutMs));
  6628. return wi->isError() ? 0 : wi.release();
  6629. }
  6630. bool URL::readEntireBinaryStream (MemoryBlock& destData,
  6631. const bool usePostCommand) const
  6632. {
  6633. const ScopedPointer <InputStream> in (createInputStream (usePostCommand));
  6634. if (in != 0)
  6635. {
  6636. in->readIntoMemoryBlock (destData, -1);
  6637. return true;
  6638. }
  6639. return false;
  6640. }
  6641. const String URL::readEntireTextStream (const bool usePostCommand) const
  6642. {
  6643. const ScopedPointer <InputStream> in (createInputStream (usePostCommand));
  6644. if (in != 0)
  6645. return in->readEntireStreamAsString();
  6646. return String::empty;
  6647. }
  6648. XmlElement* URL::readEntireXmlStream (const bool usePostCommand) const
  6649. {
  6650. XmlDocument doc (readEntireTextStream (usePostCommand));
  6651. return doc.getDocumentElement();
  6652. }
  6653. const URL URL::withParameter (const String& parameterName,
  6654. const String& parameterValue) const
  6655. {
  6656. URL u (*this);
  6657. u.parameters.set (parameterName, parameterValue);
  6658. return u;
  6659. }
  6660. const URL URL::withFileToUpload (const String& parameterName,
  6661. const File& fileToUpload,
  6662. const String& mimeType) const
  6663. {
  6664. jassert (mimeType.isNotEmpty()); // You need to supply a mime type!
  6665. URL u (*this);
  6666. u.filesToUpload.set (parameterName, fileToUpload.getFullPathName());
  6667. u.mimeTypes.set (parameterName, mimeType);
  6668. return u;
  6669. }
  6670. const URL URL::withPOSTData (const String& postData_) const
  6671. {
  6672. URL u (*this);
  6673. u.postData = postData_;
  6674. return u;
  6675. }
  6676. const StringPairArray& URL::getParameters() const
  6677. {
  6678. return parameters;
  6679. }
  6680. const StringPairArray& URL::getFilesToUpload() const
  6681. {
  6682. return filesToUpload;
  6683. }
  6684. const StringPairArray& URL::getMimeTypesOfUploadFiles() const
  6685. {
  6686. return mimeTypes;
  6687. }
  6688. const String URL::removeEscapeChars (const String& s)
  6689. {
  6690. String result (s.replaceCharacter ('+', ' '));
  6691. int nextPercent = 0;
  6692. for (;;)
  6693. {
  6694. nextPercent = result.indexOfChar (nextPercent, '%');
  6695. if (nextPercent < 0)
  6696. break;
  6697. juce_wchar replacementChar = (juce_wchar) result.substring (nextPercent + 1, nextPercent + 3).getHexValue32();
  6698. result = result.replaceSection (nextPercent, 3, String::charToString (replacementChar));
  6699. ++nextPercent;
  6700. }
  6701. return result;
  6702. }
  6703. const String URL::addEscapeChars (const String& s, const bool isParameter)
  6704. {
  6705. String result;
  6706. result.preallocateStorage (s.length() + 8);
  6707. const char* utf8 = s.toUTF8();
  6708. const char* legalChars = isParameter ? "_-.*!'()"
  6709. : "_-$.*!'(),";
  6710. while (*utf8 != 0)
  6711. {
  6712. const char c = *utf8++;
  6713. if (CharacterFunctions::isLetterOrDigit (c)
  6714. || CharacterFunctions::indexOfChar (legalChars, c, false) >= 0)
  6715. {
  6716. result << c;
  6717. }
  6718. else
  6719. {
  6720. const int v = (int) (uint8) c;
  6721. result << (v < 0x10 ? "%0" : "%") << String::toHexString (v);
  6722. }
  6723. }
  6724. return result;
  6725. }
  6726. bool URL::launchInDefaultBrowser() const
  6727. {
  6728. String u (toString (true));
  6729. if (u.containsChar ('@') && ! u.containsChar (':'))
  6730. u = "mailto:" + u;
  6731. return PlatformUtilities::openDocument (u, String::empty);
  6732. }
  6733. END_JUCE_NAMESPACE
  6734. /*** End of inlined file: juce_URL.cpp ***/
  6735. /*** Start of inlined file: juce_BufferedInputStream.cpp ***/
  6736. BEGIN_JUCE_NAMESPACE
  6737. BufferedInputStream::BufferedInputStream (InputStream* const source_,
  6738. const int bufferSize_,
  6739. const bool deleteSourceWhenDestroyed)
  6740. : source (source_),
  6741. sourceToDelete (deleteSourceWhenDestroyed ? source_ : 0),
  6742. bufferSize (jmax (256, bufferSize_)),
  6743. position (source_->getPosition()),
  6744. lastReadPos (0),
  6745. bufferOverlap (128)
  6746. {
  6747. const int sourceSize = (int) source_->getTotalLength();
  6748. if (sourceSize >= 0)
  6749. bufferSize = jmin (jmax (32, sourceSize), bufferSize);
  6750. bufferStart = position;
  6751. buffer.malloc (bufferSize);
  6752. }
  6753. BufferedInputStream::~BufferedInputStream()
  6754. {
  6755. }
  6756. int64 BufferedInputStream::getTotalLength()
  6757. {
  6758. return source->getTotalLength();
  6759. }
  6760. int64 BufferedInputStream::getPosition()
  6761. {
  6762. return position;
  6763. }
  6764. bool BufferedInputStream::setPosition (int64 newPosition)
  6765. {
  6766. position = jmax ((int64) 0, newPosition);
  6767. return true;
  6768. }
  6769. bool BufferedInputStream::isExhausted()
  6770. {
  6771. return (position >= lastReadPos)
  6772. && source->isExhausted();
  6773. }
  6774. void BufferedInputStream::ensureBuffered()
  6775. {
  6776. const int64 bufferEndOverlap = lastReadPos - bufferOverlap;
  6777. if (position < bufferStart || position >= bufferEndOverlap)
  6778. {
  6779. int bytesRead;
  6780. if (position < lastReadPos
  6781. && position >= bufferEndOverlap
  6782. && position >= bufferStart)
  6783. {
  6784. const int bytesToKeep = (int) (lastReadPos - position);
  6785. memmove (buffer, buffer + (int) (position - bufferStart), bytesToKeep);
  6786. bufferStart = position;
  6787. bytesRead = source->read (buffer + bytesToKeep,
  6788. bufferSize - bytesToKeep);
  6789. lastReadPos += bytesRead;
  6790. bytesRead += bytesToKeep;
  6791. }
  6792. else
  6793. {
  6794. bufferStart = position;
  6795. source->setPosition (bufferStart);
  6796. bytesRead = source->read (buffer, bufferSize);
  6797. lastReadPos = bufferStart + bytesRead;
  6798. }
  6799. while (bytesRead < bufferSize)
  6800. buffer [bytesRead++] = 0;
  6801. }
  6802. }
  6803. int BufferedInputStream::read (void* destBuffer, int maxBytesToRead)
  6804. {
  6805. if (position >= bufferStart
  6806. && position + maxBytesToRead <= lastReadPos)
  6807. {
  6808. memcpy (destBuffer, buffer + (int) (position - bufferStart), maxBytesToRead);
  6809. position += maxBytesToRead;
  6810. return maxBytesToRead;
  6811. }
  6812. else
  6813. {
  6814. if (position < bufferStart || position >= lastReadPos)
  6815. ensureBuffered();
  6816. int bytesRead = 0;
  6817. while (maxBytesToRead > 0)
  6818. {
  6819. const int bytesAvailable = jmin (maxBytesToRead, (int) (lastReadPos - position));
  6820. if (bytesAvailable > 0)
  6821. {
  6822. memcpy (destBuffer, buffer + (int) (position - bufferStart), bytesAvailable);
  6823. maxBytesToRead -= bytesAvailable;
  6824. bytesRead += bytesAvailable;
  6825. position += bytesAvailable;
  6826. destBuffer = static_cast <char*> (destBuffer) + bytesAvailable;
  6827. }
  6828. const int64 oldLastReadPos = lastReadPos;
  6829. ensureBuffered();
  6830. if (oldLastReadPos == lastReadPos)
  6831. break; // if ensureBuffered() failed to read any more data, bail out
  6832. if (isExhausted())
  6833. break;
  6834. }
  6835. return bytesRead;
  6836. }
  6837. }
  6838. const String BufferedInputStream::readString()
  6839. {
  6840. if (position >= bufferStart
  6841. && position < lastReadPos)
  6842. {
  6843. const int maxChars = (int) (lastReadPos - position);
  6844. const char* const src = buffer + (int) (position - bufferStart);
  6845. for (int i = 0; i < maxChars; ++i)
  6846. {
  6847. if (src[i] == 0)
  6848. {
  6849. position += i + 1;
  6850. return String::fromUTF8 (src, i);
  6851. }
  6852. }
  6853. }
  6854. return InputStream::readString();
  6855. }
  6856. END_JUCE_NAMESPACE
  6857. /*** End of inlined file: juce_BufferedInputStream.cpp ***/
  6858. /*** Start of inlined file: juce_FileInputSource.cpp ***/
  6859. BEGIN_JUCE_NAMESPACE
  6860. FileInputSource::FileInputSource (const File& file_)
  6861. : file (file_)
  6862. {
  6863. }
  6864. FileInputSource::~FileInputSource()
  6865. {
  6866. }
  6867. InputStream* FileInputSource::createInputStream()
  6868. {
  6869. return file.createInputStream();
  6870. }
  6871. InputStream* FileInputSource::createInputStreamFor (const String& relatedItemPath)
  6872. {
  6873. return file.getSiblingFile (relatedItemPath).createInputStream();
  6874. }
  6875. int64 FileInputSource::hashCode() const
  6876. {
  6877. return file.hashCode();
  6878. }
  6879. END_JUCE_NAMESPACE
  6880. /*** End of inlined file: juce_FileInputSource.cpp ***/
  6881. /*** Start of inlined file: juce_MemoryInputStream.cpp ***/
  6882. BEGIN_JUCE_NAMESPACE
  6883. MemoryInputStream::MemoryInputStream (const void* const sourceData,
  6884. const size_t sourceDataSize,
  6885. const bool keepInternalCopy)
  6886. : data (static_cast <const char*> (sourceData)),
  6887. dataSize (sourceDataSize),
  6888. position (0)
  6889. {
  6890. if (keepInternalCopy)
  6891. {
  6892. internalCopy.append (data, sourceDataSize);
  6893. data = static_cast <const char*> (internalCopy.getData());
  6894. }
  6895. }
  6896. MemoryInputStream::MemoryInputStream (const MemoryBlock& sourceData,
  6897. const bool keepInternalCopy)
  6898. : data (static_cast <const char*> (sourceData.getData())),
  6899. dataSize (sourceData.getSize()),
  6900. position (0)
  6901. {
  6902. if (keepInternalCopy)
  6903. {
  6904. internalCopy = sourceData;
  6905. data = static_cast <const char*> (internalCopy.getData());
  6906. }
  6907. }
  6908. MemoryInputStream::~MemoryInputStream()
  6909. {
  6910. }
  6911. int64 MemoryInputStream::getTotalLength()
  6912. {
  6913. return dataSize;
  6914. }
  6915. int MemoryInputStream::read (void* const buffer, const int howMany)
  6916. {
  6917. jassert (howMany >= 0);
  6918. const int num = jmin (howMany, (int) (dataSize - position));
  6919. memcpy (buffer, data + position, num);
  6920. position += num;
  6921. return (int) num;
  6922. }
  6923. bool MemoryInputStream::isExhausted()
  6924. {
  6925. return (position >= dataSize);
  6926. }
  6927. bool MemoryInputStream::setPosition (const int64 pos)
  6928. {
  6929. position = (int) jlimit ((int64) 0, (int64) dataSize, pos);
  6930. return true;
  6931. }
  6932. int64 MemoryInputStream::getPosition()
  6933. {
  6934. return position;
  6935. }
  6936. END_JUCE_NAMESPACE
  6937. /*** End of inlined file: juce_MemoryInputStream.cpp ***/
  6938. /*** Start of inlined file: juce_MemoryOutputStream.cpp ***/
  6939. BEGIN_JUCE_NAMESPACE
  6940. MemoryOutputStream::MemoryOutputStream (const size_t initialSize,
  6941. const size_t blockSizeToIncreaseBy,
  6942. MemoryBlock* const memoryBlockToWriteTo)
  6943. : data (memoryBlockToWriteTo),
  6944. position (0),
  6945. size (0),
  6946. blockSize (jmax ((size_t) 16, blockSizeToIncreaseBy))
  6947. {
  6948. if (data == 0)
  6949. dataToDelete = data = new MemoryBlock (initialSize);
  6950. else
  6951. data->setSize (initialSize, false);
  6952. }
  6953. MemoryOutputStream::~MemoryOutputStream()
  6954. {
  6955. flush();
  6956. }
  6957. void MemoryOutputStream::flush()
  6958. {
  6959. if (dataToDelete == 0)
  6960. data->setSize (size, false);
  6961. }
  6962. void MemoryOutputStream::reset() throw()
  6963. {
  6964. position = 0;
  6965. size = 0;
  6966. }
  6967. bool MemoryOutputStream::write (const void* const buffer, int howMany)
  6968. {
  6969. if (howMany > 0)
  6970. {
  6971. size_t storageNeeded = position + howMany;
  6972. if (storageNeeded >= data->getSize())
  6973. {
  6974. // if we need more space, increase the block by at least 10%..
  6975. storageNeeded += jmax (blockSize, storageNeeded / 10);
  6976. storageNeeded = storageNeeded - (storageNeeded % blockSize) + blockSize;
  6977. data->ensureSize (storageNeeded);
  6978. }
  6979. data->copyFrom (buffer, (int) position, howMany);
  6980. position += howMany;
  6981. size = jmax (size, position);
  6982. }
  6983. return true;
  6984. }
  6985. const char* MemoryOutputStream::getData() const throw()
  6986. {
  6987. char* const d = static_cast <char*> (data->getData());
  6988. if (data->getSize() > size)
  6989. d [size] = 0;
  6990. return d;
  6991. }
  6992. bool MemoryOutputStream::setPosition (int64 newPosition)
  6993. {
  6994. if (newPosition <= (int64) size)
  6995. {
  6996. // ok to seek backwards
  6997. position = jlimit ((size_t) 0, size, (size_t) newPosition);
  6998. return true;
  6999. }
  7000. else
  7001. {
  7002. // trying to make it bigger isn't a good thing to do..
  7003. return false;
  7004. }
  7005. }
  7006. const String MemoryOutputStream::toUTF8() const
  7007. {
  7008. return String (getData(), getDataSize());
  7009. }
  7010. END_JUCE_NAMESPACE
  7011. /*** End of inlined file: juce_MemoryOutputStream.cpp ***/
  7012. /*** Start of inlined file: juce_SubregionStream.cpp ***/
  7013. BEGIN_JUCE_NAMESPACE
  7014. SubregionStream::SubregionStream (InputStream* const sourceStream,
  7015. const int64 startPositionInSourceStream_,
  7016. const int64 lengthOfSourceStream_,
  7017. const bool deleteSourceWhenDestroyed) throw()
  7018. : source (sourceStream),
  7019. startPositionInSourceStream (startPositionInSourceStream_),
  7020. lengthOfSourceStream (lengthOfSourceStream_)
  7021. {
  7022. if (deleteSourceWhenDestroyed)
  7023. sourceToDelete = source;
  7024. setPosition (0);
  7025. }
  7026. SubregionStream::~SubregionStream() throw()
  7027. {
  7028. }
  7029. int64 SubregionStream::getTotalLength()
  7030. {
  7031. const int64 srcLen = source->getTotalLength() - startPositionInSourceStream;
  7032. return (lengthOfSourceStream >= 0) ? jmin (lengthOfSourceStream, srcLen)
  7033. : srcLen;
  7034. }
  7035. int64 SubregionStream::getPosition()
  7036. {
  7037. return source->getPosition() - startPositionInSourceStream;
  7038. }
  7039. bool SubregionStream::setPosition (int64 newPosition)
  7040. {
  7041. return source->setPosition (jmax ((int64) 0, newPosition + startPositionInSourceStream));
  7042. }
  7043. int SubregionStream::read (void* destBuffer, int maxBytesToRead)
  7044. {
  7045. if (lengthOfSourceStream < 0)
  7046. {
  7047. return source->read (destBuffer, maxBytesToRead);
  7048. }
  7049. else
  7050. {
  7051. maxBytesToRead = (int) jmin ((int64) maxBytesToRead, lengthOfSourceStream - getPosition());
  7052. if (maxBytesToRead <= 0)
  7053. return 0;
  7054. return source->read (destBuffer, maxBytesToRead);
  7055. }
  7056. }
  7057. bool SubregionStream::isExhausted()
  7058. {
  7059. if (lengthOfSourceStream >= 0)
  7060. return (getPosition() >= lengthOfSourceStream) || source->isExhausted();
  7061. else
  7062. return source->isExhausted();
  7063. }
  7064. END_JUCE_NAMESPACE
  7065. /*** End of inlined file: juce_SubregionStream.cpp ***/
  7066. /*** Start of inlined file: juce_PerformanceCounter.cpp ***/
  7067. BEGIN_JUCE_NAMESPACE
  7068. PerformanceCounter::PerformanceCounter (const String& name_,
  7069. int runsPerPrintout,
  7070. const File& loggingFile)
  7071. : name (name_),
  7072. numRuns (0),
  7073. runsPerPrint (runsPerPrintout),
  7074. totalTime (0),
  7075. outputFile (loggingFile)
  7076. {
  7077. if (outputFile != File::nonexistent)
  7078. {
  7079. String s ("**** Counter for \"");
  7080. s << name_ << "\" started at: "
  7081. << Time::getCurrentTime().toString (true, true)
  7082. << "\r\n";
  7083. outputFile.appendText (s, false, false);
  7084. }
  7085. }
  7086. PerformanceCounter::~PerformanceCounter()
  7087. {
  7088. printStatistics();
  7089. }
  7090. void PerformanceCounter::start()
  7091. {
  7092. started = Time::getHighResolutionTicks();
  7093. }
  7094. void PerformanceCounter::stop()
  7095. {
  7096. const int64 now = Time::getHighResolutionTicks();
  7097. totalTime += 1000.0 * Time::highResolutionTicksToSeconds (now - started);
  7098. if (++numRuns == runsPerPrint)
  7099. printStatistics();
  7100. }
  7101. void PerformanceCounter::printStatistics()
  7102. {
  7103. if (numRuns > 0)
  7104. {
  7105. String s ("Performance count for \"");
  7106. s << name << "\" - average over " << numRuns << " run(s) = ";
  7107. const int micros = (int) (totalTime * (1000.0 / numRuns));
  7108. if (micros > 10000)
  7109. s << (micros/1000) << " millisecs";
  7110. else
  7111. s << micros << " microsecs";
  7112. s << ", total = " << String (totalTime / 1000, 5) << " seconds";
  7113. Logger::outputDebugString (s);
  7114. s << "\r\n";
  7115. if (outputFile != File::nonexistent)
  7116. outputFile.appendText (s, false, false);
  7117. numRuns = 0;
  7118. totalTime = 0;
  7119. }
  7120. }
  7121. END_JUCE_NAMESPACE
  7122. /*** End of inlined file: juce_PerformanceCounter.cpp ***/
  7123. /*** Start of inlined file: juce_Uuid.cpp ***/
  7124. BEGIN_JUCE_NAMESPACE
  7125. Uuid::Uuid()
  7126. {
  7127. // Mix up any available MAC addresses with some time-based pseudo-random numbers
  7128. // to make it very very unlikely that two UUIDs will ever be the same..
  7129. static int64 macAddresses[2];
  7130. static bool hasCheckedMacAddresses = false;
  7131. if (! hasCheckedMacAddresses)
  7132. {
  7133. hasCheckedMacAddresses = true;
  7134. SystemStats::getMACAddresses (macAddresses, 2);
  7135. }
  7136. value.asInt64[0] = macAddresses[0];
  7137. value.asInt64[1] = macAddresses[1];
  7138. // We'll use both a local RNG that is re-seeded, plus the shared RNG,
  7139. // whose seed will carry over between calls to this method.
  7140. Random r (macAddresses[0] ^ macAddresses[1]
  7141. ^ Random::getSystemRandom().nextInt64());
  7142. for (int i = 4; --i >= 0;)
  7143. {
  7144. r.setSeedRandomly(); // calling this repeatedly improves randomness
  7145. value.asInt[i] ^= r.nextInt();
  7146. value.asInt[i] ^= Random::getSystemRandom().nextInt();
  7147. }
  7148. }
  7149. Uuid::~Uuid() throw()
  7150. {
  7151. }
  7152. Uuid::Uuid (const Uuid& other)
  7153. : value (other.value)
  7154. {
  7155. }
  7156. Uuid& Uuid::operator= (const Uuid& other)
  7157. {
  7158. value = other.value;
  7159. return *this;
  7160. }
  7161. bool Uuid::operator== (const Uuid& other) const
  7162. {
  7163. return value.asInt64[0] == other.value.asInt64[0]
  7164. && value.asInt64[1] == other.value.asInt64[1];
  7165. }
  7166. bool Uuid::operator!= (const Uuid& other) const
  7167. {
  7168. return ! operator== (other);
  7169. }
  7170. bool Uuid::isNull() const throw()
  7171. {
  7172. return (value.asInt64 [0] == 0) && (value.asInt64 [1] == 0);
  7173. }
  7174. const String Uuid::toString() const
  7175. {
  7176. return String::toHexString (value.asBytes, sizeof (value.asBytes), 0);
  7177. }
  7178. Uuid::Uuid (const String& uuidString)
  7179. {
  7180. operator= (uuidString);
  7181. }
  7182. Uuid& Uuid::operator= (const String& uuidString)
  7183. {
  7184. MemoryBlock mb;
  7185. mb.loadFromHexString (uuidString);
  7186. mb.ensureSize (sizeof (value.asBytes), true);
  7187. mb.copyTo (value.asBytes, 0, sizeof (value.asBytes));
  7188. return *this;
  7189. }
  7190. Uuid::Uuid (const uint8* const rawData)
  7191. {
  7192. operator= (rawData);
  7193. }
  7194. Uuid& Uuid::operator= (const uint8* const rawData)
  7195. {
  7196. if (rawData != 0)
  7197. memcpy (value.asBytes, rawData, sizeof (value.asBytes));
  7198. else
  7199. zeromem (value.asBytes, sizeof (value.asBytes));
  7200. return *this;
  7201. }
  7202. END_JUCE_NAMESPACE
  7203. /*** End of inlined file: juce_Uuid.cpp ***/
  7204. /*** Start of inlined file: juce_ZipFile.cpp ***/
  7205. BEGIN_JUCE_NAMESPACE
  7206. class ZipFile::ZipEntryInfo
  7207. {
  7208. public:
  7209. ZipFile::ZipEntry entry;
  7210. int streamOffset;
  7211. int compressedSize;
  7212. bool compressed;
  7213. };
  7214. class ZipFile::ZipInputStream : public InputStream
  7215. {
  7216. public:
  7217. ZipInputStream (ZipFile& file_, ZipFile::ZipEntryInfo& zei)
  7218. : file (file_),
  7219. zipEntryInfo (zei),
  7220. pos (0),
  7221. headerSize (0),
  7222. inputStream (0)
  7223. {
  7224. inputStream = file_.inputStream;
  7225. if (file_.inputSource != 0)
  7226. {
  7227. inputStream = file.inputSource->createInputStream();
  7228. }
  7229. else
  7230. {
  7231. #if JUCE_DEBUG
  7232. file_.numOpenStreams++;
  7233. #endif
  7234. }
  7235. char buffer [30];
  7236. if (inputStream != 0
  7237. && inputStream->setPosition (zei.streamOffset)
  7238. && inputStream->read (buffer, 30) == 30
  7239. && ByteOrder::littleEndianInt (buffer) == 0x04034b50)
  7240. {
  7241. headerSize = 30 + ByteOrder::littleEndianShort (buffer + 26)
  7242. + ByteOrder::littleEndianShort (buffer + 28);
  7243. }
  7244. }
  7245. ~ZipInputStream() throw()
  7246. {
  7247. #if JUCE_DEBUG
  7248. if (inputStream != 0 && inputStream == file.inputStream)
  7249. file.numOpenStreams--;
  7250. #endif
  7251. if (inputStream != file.inputStream)
  7252. delete inputStream;
  7253. }
  7254. int64 getTotalLength() throw()
  7255. {
  7256. return zipEntryInfo.compressedSize;
  7257. }
  7258. int read (void* buffer, int howMany) throw()
  7259. {
  7260. if (headerSize <= 0)
  7261. return 0;
  7262. howMany = (int) jmin ((int64) howMany, zipEntryInfo.compressedSize - pos);
  7263. if (inputStream == 0)
  7264. return 0;
  7265. int num;
  7266. if (inputStream == file.inputStream)
  7267. {
  7268. const ScopedLock sl (file.lock);
  7269. inputStream->setPosition (pos + zipEntryInfo.streamOffset + headerSize);
  7270. num = inputStream->read (buffer, howMany);
  7271. }
  7272. else
  7273. {
  7274. inputStream->setPosition (pos + zipEntryInfo.streamOffset + headerSize);
  7275. num = inputStream->read (buffer, howMany);
  7276. }
  7277. pos += num;
  7278. return num;
  7279. }
  7280. bool isExhausted() throw()
  7281. {
  7282. return headerSize <= 0 || pos >= zipEntryInfo.compressedSize;
  7283. }
  7284. int64 getPosition() throw()
  7285. {
  7286. return pos;
  7287. }
  7288. bool setPosition (int64 newPos) throw()
  7289. {
  7290. pos = jlimit ((int64) 0, (int64) zipEntryInfo.compressedSize, newPos);
  7291. return true;
  7292. }
  7293. private:
  7294. ZipFile& file;
  7295. ZipEntryInfo zipEntryInfo;
  7296. int64 pos;
  7297. int headerSize;
  7298. InputStream* inputStream;
  7299. ZipInputStream (const ZipInputStream&);
  7300. ZipInputStream& operator= (const ZipInputStream&);
  7301. };
  7302. ZipFile::ZipFile (InputStream* const source_,
  7303. const bool deleteStreamWhenDestroyed) throw()
  7304. : inputStream (source_)
  7305. #if JUCE_DEBUG
  7306. , numOpenStreams (0)
  7307. #endif
  7308. {
  7309. if (deleteStreamWhenDestroyed)
  7310. streamToDelete = inputStream;
  7311. init();
  7312. }
  7313. ZipFile::ZipFile (const File& file)
  7314. : inputStream (0)
  7315. #if JUCE_DEBUG
  7316. , numOpenStreams (0)
  7317. #endif
  7318. {
  7319. inputSource = new FileInputSource (file);
  7320. init();
  7321. }
  7322. ZipFile::ZipFile (InputSource* const inputSource_)
  7323. : inputStream (0),
  7324. inputSource (inputSource_)
  7325. #if JUCE_DEBUG
  7326. , numOpenStreams (0)
  7327. #endif
  7328. {
  7329. init();
  7330. }
  7331. ZipFile::~ZipFile() throw()
  7332. {
  7333. #if JUCE_DEBUG
  7334. entries.clear();
  7335. // If you hit this assertion, it means you've created a stream to read
  7336. // one of the items in the zipfile, but you've forgotten to delete that
  7337. // stream object before deleting the file.. Streams can't be kept open
  7338. // after the file is deleted because they need to share the input
  7339. // stream that the file uses to read itself.
  7340. jassert (numOpenStreams == 0);
  7341. #endif
  7342. }
  7343. int ZipFile::getNumEntries() const throw()
  7344. {
  7345. return entries.size();
  7346. }
  7347. const ZipFile::ZipEntry* ZipFile::getEntry (const int index) const throw()
  7348. {
  7349. ZipEntryInfo* const zei = entries [index];
  7350. return zei != 0 ? &(zei->entry) : 0;
  7351. }
  7352. int ZipFile::getIndexOfFileName (const String& fileName) const throw()
  7353. {
  7354. for (int i = 0; i < entries.size(); ++i)
  7355. if (entries.getUnchecked (i)->entry.filename == fileName)
  7356. return i;
  7357. return -1;
  7358. }
  7359. const ZipFile::ZipEntry* ZipFile::getEntry (const String& fileName) const throw()
  7360. {
  7361. return getEntry (getIndexOfFileName (fileName));
  7362. }
  7363. InputStream* ZipFile::createStreamForEntry (const int index)
  7364. {
  7365. ZipEntryInfo* const zei = entries[index];
  7366. InputStream* stream = 0;
  7367. if (zei != 0)
  7368. {
  7369. stream = new ZipInputStream (*this, *zei);
  7370. if (zei->compressed)
  7371. {
  7372. stream = new GZIPDecompressorInputStream (stream, true, true,
  7373. zei->entry.uncompressedSize);
  7374. // (much faster to unzip in big blocks using a buffer..)
  7375. stream = new BufferedInputStream (stream, 32768, true);
  7376. }
  7377. }
  7378. return stream;
  7379. }
  7380. class ZipFile::ZipFilenameComparator
  7381. {
  7382. public:
  7383. int compareElements (const ZipFile::ZipEntryInfo* first, const ZipFile::ZipEntryInfo* second)
  7384. {
  7385. return first->entry.filename.compare (second->entry.filename);
  7386. }
  7387. };
  7388. void ZipFile::sortEntriesByFilename()
  7389. {
  7390. ZipFilenameComparator sorter;
  7391. entries.sort (sorter);
  7392. }
  7393. void ZipFile::init()
  7394. {
  7395. ScopedPointer <InputStream> toDelete;
  7396. InputStream* in = inputStream;
  7397. if (inputSource != 0)
  7398. {
  7399. in = inputSource->createInputStream();
  7400. toDelete = in;
  7401. }
  7402. if (in != 0)
  7403. {
  7404. int numEntries = 0;
  7405. int pos = findEndOfZipEntryTable (in, numEntries);
  7406. if (pos >= 0 && pos < in->getTotalLength())
  7407. {
  7408. const int size = (int) (in->getTotalLength() - pos);
  7409. in->setPosition (pos);
  7410. MemoryBlock headerData;
  7411. if (in->readIntoMemoryBlock (headerData, size) == size)
  7412. {
  7413. pos = 0;
  7414. for (int i = 0; i < numEntries; ++i)
  7415. {
  7416. if (pos + 46 > size)
  7417. break;
  7418. const char* const buffer = static_cast <const char*> (headerData.getData()) + pos;
  7419. const int fileNameLen = ByteOrder::littleEndianShort (buffer + 28);
  7420. if (pos + 46 + fileNameLen > size)
  7421. break;
  7422. ZipEntryInfo* const zei = new ZipEntryInfo();
  7423. zei->entry.filename = String::fromUTF8 (buffer + 46, fileNameLen);
  7424. const int time = ByteOrder::littleEndianShort (buffer + 12);
  7425. const int date = ByteOrder::littleEndianShort (buffer + 14);
  7426. const int year = 1980 + (date >> 9);
  7427. const int month = ((date >> 5) & 15) - 1;
  7428. const int day = date & 31;
  7429. const int hours = time >> 11;
  7430. const int minutes = (time >> 5) & 63;
  7431. const int seconds = (time & 31) << 1;
  7432. zei->entry.fileTime = Time (year, month, day, hours, minutes, seconds);
  7433. zei->compressed = ByteOrder::littleEndianShort (buffer + 10) != 0;
  7434. zei->compressedSize = ByteOrder::littleEndianInt (buffer + 20);
  7435. zei->entry.uncompressedSize = ByteOrder::littleEndianInt (buffer + 24);
  7436. zei->streamOffset = ByteOrder::littleEndianInt (buffer + 42);
  7437. entries.add (zei);
  7438. pos += 46 + fileNameLen
  7439. + ByteOrder::littleEndianShort (buffer + 30)
  7440. + ByteOrder::littleEndianShort (buffer + 32);
  7441. }
  7442. }
  7443. }
  7444. }
  7445. }
  7446. int ZipFile::findEndOfZipEntryTable (InputStream* input, int& numEntries)
  7447. {
  7448. BufferedInputStream in (input, 8192, false);
  7449. in.setPosition (in.getTotalLength());
  7450. int64 pos = in.getPosition();
  7451. const int64 lowestPos = jmax ((int64) 0, pos - 1024);
  7452. char buffer [32];
  7453. zeromem (buffer, sizeof (buffer));
  7454. while (pos > lowestPos)
  7455. {
  7456. in.setPosition (pos - 22);
  7457. pos = in.getPosition();
  7458. memcpy (buffer + 22, buffer, 4);
  7459. if (in.read (buffer, 22) != 22)
  7460. return 0;
  7461. for (int i = 0; i < 22; ++i)
  7462. {
  7463. if (ByteOrder::littleEndianInt (buffer + i) == 0x06054b50)
  7464. {
  7465. in.setPosition (pos + i);
  7466. in.read (buffer, 22);
  7467. numEntries = ByteOrder::littleEndianShort (buffer + 10);
  7468. return ByteOrder::littleEndianInt (buffer + 16);
  7469. }
  7470. }
  7471. }
  7472. return 0;
  7473. }
  7474. void ZipFile::uncompressTo (const File& targetDirectory,
  7475. const bool shouldOverwriteFiles)
  7476. {
  7477. for (int i = 0; i < entries.size(); ++i)
  7478. {
  7479. const ZipEntry& zei = entries.getUnchecked(i)->entry;
  7480. const File targetFile (targetDirectory.getChildFile (zei.filename));
  7481. if (zei.filename.endsWithChar ('/'))
  7482. {
  7483. targetFile.createDirectory(); // (entry is a directory, not a file)
  7484. }
  7485. else
  7486. {
  7487. ScopedPointer <InputStream> in (createStreamForEntry (i));
  7488. if (in != 0)
  7489. {
  7490. if (shouldOverwriteFiles)
  7491. targetFile.deleteFile();
  7492. if ((! targetFile.exists())
  7493. && targetFile.getParentDirectory().createDirectory())
  7494. {
  7495. ScopedPointer <FileOutputStream> out (targetFile.createOutputStream());
  7496. if (out != 0)
  7497. {
  7498. out->writeFromInputStream (*in, -1);
  7499. out = 0;
  7500. targetFile.setCreationTime (zei.fileTime);
  7501. targetFile.setLastModificationTime (zei.fileTime);
  7502. targetFile.setLastAccessTime (zei.fileTime);
  7503. }
  7504. }
  7505. }
  7506. }
  7507. }
  7508. }
  7509. END_JUCE_NAMESPACE
  7510. /*** End of inlined file: juce_ZipFile.cpp ***/
  7511. /*** Start of inlined file: juce_CharacterFunctions.cpp ***/
  7512. #ifdef _MSC_VER
  7513. #pragma warning (disable: 4514 4996)
  7514. #pragma warning (push)
  7515. #endif
  7516. #include <cwctype>
  7517. #include <cctype>
  7518. #include <ctime>
  7519. #ifdef _MSC_VER
  7520. #pragma warning (pop)
  7521. #endif
  7522. BEGIN_JUCE_NAMESPACE
  7523. int CharacterFunctions::length (const char* const s) throw()
  7524. {
  7525. return (int) strlen (s);
  7526. }
  7527. int CharacterFunctions::length (const juce_wchar* const s) throw()
  7528. {
  7529. return (int) wcslen (s);
  7530. }
  7531. void CharacterFunctions::copy (char* dest, const char* src, const int maxChars) throw()
  7532. {
  7533. strncpy (dest, src, maxChars);
  7534. }
  7535. void CharacterFunctions::copy (juce_wchar* dest, const juce_wchar* src, int maxChars) throw()
  7536. {
  7537. wcsncpy (dest, src, maxChars);
  7538. }
  7539. void CharacterFunctions::copy (juce_wchar* dest, const char* src, const int maxChars) throw()
  7540. {
  7541. mbstowcs (dest, src, maxChars);
  7542. }
  7543. void CharacterFunctions::copy (char* dest, const juce_wchar* src, const int maxChars) throw()
  7544. {
  7545. wcstombs (dest, src, maxChars);
  7546. }
  7547. int CharacterFunctions::bytesRequiredForCopy (const juce_wchar* src) throw()
  7548. {
  7549. return (int) wcstombs (0, src, 0);
  7550. }
  7551. void CharacterFunctions::append (char* dest, const char* src) throw()
  7552. {
  7553. strcat (dest, src);
  7554. }
  7555. void CharacterFunctions::append (juce_wchar* dest, const juce_wchar* src) throw()
  7556. {
  7557. wcscat (dest, src);
  7558. }
  7559. int CharacterFunctions::compare (const char* const s1, const char* const s2) throw()
  7560. {
  7561. return strcmp (s1, s2);
  7562. }
  7563. int CharacterFunctions::compare (const juce_wchar* s1, const juce_wchar* s2) throw()
  7564. {
  7565. jassert (s1 != 0 && s2 != 0);
  7566. return wcscmp (s1, s2);
  7567. }
  7568. int CharacterFunctions::compare (const char* const s1, const char* const s2, const int maxChars) throw()
  7569. {
  7570. jassert (s1 != 0 && s2 != 0);
  7571. return strncmp (s1, s2, maxChars);
  7572. }
  7573. int CharacterFunctions::compare (const juce_wchar* s1, const juce_wchar* s2, int maxChars) throw()
  7574. {
  7575. jassert (s1 != 0 && s2 != 0);
  7576. return wcsncmp (s1, s2, maxChars);
  7577. }
  7578. int CharacterFunctions::compare (const juce_wchar* s1, const char* s2) throw()
  7579. {
  7580. jassert (s1 != 0 && s2 != 0);
  7581. for (;;)
  7582. {
  7583. const int diff = (int) (*s1 - (juce_wchar) (unsigned char) *s2);
  7584. if (diff != 0)
  7585. return diff;
  7586. else if (*s1 == 0)
  7587. break;
  7588. ++s1;
  7589. ++s2;
  7590. }
  7591. return 0;
  7592. }
  7593. int CharacterFunctions::compare (const char* s1, const juce_wchar* s2) throw()
  7594. {
  7595. return -compare (s2, s1);
  7596. }
  7597. int CharacterFunctions::compareIgnoreCase (const char* const s1, const char* const s2) throw()
  7598. {
  7599. jassert (s1 != 0 && s2 != 0);
  7600. #if JUCE_WIN32
  7601. return stricmp (s1, s2);
  7602. #else
  7603. return strcasecmp (s1, s2);
  7604. #endif
  7605. }
  7606. int CharacterFunctions::compareIgnoreCase (const juce_wchar* s1, const juce_wchar* s2) throw()
  7607. {
  7608. jassert (s1 != 0 && s2 != 0);
  7609. #if JUCE_WIN32
  7610. return _wcsicmp (s1, s2);
  7611. #else
  7612. for (;;)
  7613. {
  7614. if (*s1 != *s2)
  7615. {
  7616. const int diff = toUpperCase (*s1) - toUpperCase (*s2);
  7617. if (diff != 0)
  7618. return diff < 0 ? -1 : 1;
  7619. }
  7620. else if (*s1 == 0)
  7621. break;
  7622. ++s1;
  7623. ++s2;
  7624. }
  7625. return 0;
  7626. #endif
  7627. }
  7628. int CharacterFunctions::compareIgnoreCase (const juce_wchar* s1, const char* s2) throw()
  7629. {
  7630. jassert (s1 != 0 && s2 != 0);
  7631. for (;;)
  7632. {
  7633. if (*s1 != *s2)
  7634. {
  7635. const int diff = toUpperCase (*s1) - toUpperCase (*s2);
  7636. if (diff != 0)
  7637. return diff < 0 ? -1 : 1;
  7638. }
  7639. else if (*s1 == 0)
  7640. break;
  7641. ++s1;
  7642. ++s2;
  7643. }
  7644. return 0;
  7645. }
  7646. int CharacterFunctions::compareIgnoreCase (const char* const s1, const char* const s2, const int maxChars) throw()
  7647. {
  7648. jassert (s1 != 0 && s2 != 0);
  7649. #if JUCE_WIN32
  7650. return strnicmp (s1, s2, maxChars);
  7651. #else
  7652. return strncasecmp (s1, s2, maxChars);
  7653. #endif
  7654. }
  7655. int CharacterFunctions::compareIgnoreCase (const juce_wchar* s1, const juce_wchar* s2, int maxChars) throw()
  7656. {
  7657. jassert (s1 != 0 && s2 != 0);
  7658. #if JUCE_WIN32
  7659. return _wcsnicmp (s1, s2, maxChars);
  7660. #else
  7661. while (--maxChars >= 0)
  7662. {
  7663. if (*s1 != *s2)
  7664. {
  7665. const int diff = toUpperCase (*s1) - toUpperCase (*s2);
  7666. if (diff != 0)
  7667. return diff < 0 ? -1 : 1;
  7668. }
  7669. else if (*s1 == 0)
  7670. break;
  7671. ++s1;
  7672. ++s2;
  7673. }
  7674. return 0;
  7675. #endif
  7676. }
  7677. const char* CharacterFunctions::find (const char* const haystack, const char* const needle) throw()
  7678. {
  7679. return strstr (haystack, needle);
  7680. }
  7681. const juce_wchar* CharacterFunctions::find (const juce_wchar* haystack, const juce_wchar* const needle) throw()
  7682. {
  7683. return wcsstr (haystack, needle);
  7684. }
  7685. int CharacterFunctions::indexOfChar (const char* const haystack, const char needle, const bool ignoreCase) throw()
  7686. {
  7687. if (haystack != 0)
  7688. {
  7689. int i = 0;
  7690. if (ignoreCase)
  7691. {
  7692. const char n1 = toLowerCase (needle);
  7693. const char n2 = toUpperCase (needle);
  7694. if (n1 != n2) // if the char is the same in upper/lower case, fall through to the normal search
  7695. {
  7696. while (haystack[i] != 0)
  7697. {
  7698. if (haystack[i] == n1 || haystack[i] == n2)
  7699. return i;
  7700. ++i;
  7701. }
  7702. return -1;
  7703. }
  7704. jassert (n1 == needle);
  7705. }
  7706. while (haystack[i] != 0)
  7707. {
  7708. if (haystack[i] == needle)
  7709. return i;
  7710. ++i;
  7711. }
  7712. }
  7713. return -1;
  7714. }
  7715. int CharacterFunctions::indexOfChar (const juce_wchar* const haystack, const juce_wchar needle, const bool ignoreCase) throw()
  7716. {
  7717. if (haystack != 0)
  7718. {
  7719. int i = 0;
  7720. if (ignoreCase)
  7721. {
  7722. const juce_wchar n1 = toLowerCase (needle);
  7723. const juce_wchar n2 = toUpperCase (needle);
  7724. if (n1 != n2) // if the char is the same in upper/lower case, fall through to the normal search
  7725. {
  7726. while (haystack[i] != 0)
  7727. {
  7728. if (haystack[i] == n1 || haystack[i] == n2)
  7729. return i;
  7730. ++i;
  7731. }
  7732. return -1;
  7733. }
  7734. jassert (n1 == needle);
  7735. }
  7736. while (haystack[i] != 0)
  7737. {
  7738. if (haystack[i] == needle)
  7739. return i;
  7740. ++i;
  7741. }
  7742. }
  7743. return -1;
  7744. }
  7745. int CharacterFunctions::indexOfCharFast (const char* const haystack, const char needle) throw()
  7746. {
  7747. jassert (haystack != 0);
  7748. int i = 0;
  7749. while (haystack[i] != 0)
  7750. {
  7751. if (haystack[i] == needle)
  7752. return i;
  7753. ++i;
  7754. }
  7755. return -1;
  7756. }
  7757. int CharacterFunctions::indexOfCharFast (const juce_wchar* const haystack, const juce_wchar needle) throw()
  7758. {
  7759. jassert (haystack != 0);
  7760. int i = 0;
  7761. while (haystack[i] != 0)
  7762. {
  7763. if (haystack[i] == needle)
  7764. return i;
  7765. ++i;
  7766. }
  7767. return -1;
  7768. }
  7769. int CharacterFunctions::getIntialSectionContainingOnly (const char* const text, const char* const allowedChars) throw()
  7770. {
  7771. return allowedChars == 0 ? 0 : (int) strspn (text, allowedChars);
  7772. }
  7773. int CharacterFunctions::getIntialSectionContainingOnly (const juce_wchar* const text, const juce_wchar* const allowedChars) throw()
  7774. {
  7775. if (allowedChars == 0)
  7776. return 0;
  7777. int i = 0;
  7778. for (;;)
  7779. {
  7780. if (indexOfCharFast (allowedChars, text[i]) < 0)
  7781. break;
  7782. ++i;
  7783. }
  7784. return i;
  7785. }
  7786. int CharacterFunctions::ftime (char* const dest, const int maxChars, const char* const format, const struct tm* const tm) throw()
  7787. {
  7788. return (int) strftime (dest, maxChars, format, tm);
  7789. }
  7790. int CharacterFunctions::ftime (juce_wchar* const dest, const int maxChars, const juce_wchar* const format, const struct tm* const tm) throw()
  7791. {
  7792. return (int) wcsftime (dest, maxChars, format, tm);
  7793. }
  7794. int CharacterFunctions::getIntValue (const char* const s) throw()
  7795. {
  7796. return atoi (s);
  7797. }
  7798. int CharacterFunctions::getIntValue (const juce_wchar* s) throw()
  7799. {
  7800. #if JUCE_WIN32
  7801. return _wtoi (s);
  7802. #else
  7803. int v = 0;
  7804. while (isWhitespace (*s))
  7805. ++s;
  7806. const bool isNeg = *s == '-';
  7807. if (isNeg)
  7808. ++s;
  7809. for (;;)
  7810. {
  7811. const wchar_t c = *s++;
  7812. if (c >= '0' && c <= '9')
  7813. v = v * 10 + (int) (c - '0');
  7814. else
  7815. break;
  7816. }
  7817. return isNeg ? -v : v;
  7818. #endif
  7819. }
  7820. int64 CharacterFunctions::getInt64Value (const char* s) throw()
  7821. {
  7822. #if JUCE_LINUX
  7823. return atoll (s);
  7824. #elif defined (JUCE_WIN32)
  7825. return _atoi64 (s);
  7826. #else
  7827. int64 v = 0;
  7828. while (isWhitespace (*s))
  7829. ++s;
  7830. const bool isNeg = *s == '-';
  7831. if (isNeg)
  7832. ++s;
  7833. for (;;)
  7834. {
  7835. const char c = *s++;
  7836. if (c >= '0' && c <= '9')
  7837. v = v * 10 + (int64) (c - '0');
  7838. else
  7839. break;
  7840. }
  7841. return isNeg ? -v : v;
  7842. #endif
  7843. }
  7844. int64 CharacterFunctions::getInt64Value (const juce_wchar* s) throw()
  7845. {
  7846. #if JUCE_WIN32
  7847. return _wtoi64 (s);
  7848. #else
  7849. int64 v = 0;
  7850. while (isWhitespace (*s))
  7851. ++s;
  7852. const bool isNeg = *s == '-';
  7853. if (isNeg)
  7854. ++s;
  7855. for (;;)
  7856. {
  7857. const juce_wchar c = *s++;
  7858. if (c >= '0' && c <= '9')
  7859. v = v * 10 + (int64) (c - '0');
  7860. else
  7861. break;
  7862. }
  7863. return isNeg ? -v : v;
  7864. #endif
  7865. }
  7866. static double juce_mulexp10 (const double value, int exponent) throw()
  7867. {
  7868. if (exponent == 0)
  7869. return value;
  7870. if (value == 0)
  7871. return 0;
  7872. const bool negative = (exponent < 0);
  7873. if (negative)
  7874. exponent = -exponent;
  7875. double result = 1.0, power = 10.0;
  7876. for (int bit = 1; exponent != 0; bit <<= 1)
  7877. {
  7878. if ((exponent & bit) != 0)
  7879. {
  7880. exponent ^= bit;
  7881. result *= power;
  7882. if (exponent == 0)
  7883. break;
  7884. }
  7885. power *= power;
  7886. }
  7887. return negative ? (value / result) : (value * result);
  7888. }
  7889. template <class CharType>
  7890. double juce_atof (const CharType* const original) throw()
  7891. {
  7892. double result[3] = { 0, 0, 0 }, accumulator[2] = { 0, 0 };
  7893. int exponentAdjustment[2] = { 0, 0 }, exponentAccumulator[2] = { -1, -1 };
  7894. int exponent = 0, decPointIndex = 0, digit = 0;
  7895. int lastDigit = 0, numSignificantDigits = 0;
  7896. bool isNegative = false, digitsFound = false;
  7897. const int maxSignificantDigits = 15 + 2;
  7898. const CharType* s = original;
  7899. while (CharacterFunctions::isWhitespace (*s))
  7900. ++s;
  7901. switch (*s)
  7902. {
  7903. case '-': isNegative = true; // fall-through..
  7904. case '+': ++s;
  7905. }
  7906. if (*s == 'n' || *s == 'N' || *s == 'i' || *s == 'I')
  7907. return atof (String (original).toUTF8()); // Let the c library deal with NAN and INF
  7908. for (;;)
  7909. {
  7910. if (CharacterFunctions::isDigit (*s))
  7911. {
  7912. lastDigit = digit;
  7913. digit = *s++ - '0';
  7914. digitsFound = true;
  7915. if (decPointIndex != 0)
  7916. exponentAdjustment[1]++;
  7917. if (numSignificantDigits == 0 && digit == 0)
  7918. continue;
  7919. if (++numSignificantDigits > maxSignificantDigits)
  7920. {
  7921. if (digit > 5)
  7922. ++accumulator [decPointIndex];
  7923. else if (digit == 5 && (lastDigit & 1) != 0)
  7924. ++accumulator [decPointIndex];
  7925. if (decPointIndex > 0)
  7926. exponentAdjustment[1]--;
  7927. else
  7928. exponentAdjustment[0]++;
  7929. while (CharacterFunctions::isDigit (*s))
  7930. {
  7931. ++s;
  7932. if (decPointIndex == 0)
  7933. exponentAdjustment[0]++;
  7934. }
  7935. }
  7936. else
  7937. {
  7938. const double maxAccumulatorValue = (double) ((std::numeric_limits<unsigned int>::max() - 9) / 10);
  7939. if (accumulator [decPointIndex] > maxAccumulatorValue)
  7940. {
  7941. result [decPointIndex] = juce_mulexp10 (result [decPointIndex], exponentAccumulator [decPointIndex])
  7942. + accumulator [decPointIndex];
  7943. accumulator [decPointIndex] = 0;
  7944. exponentAccumulator [decPointIndex] = 0;
  7945. }
  7946. accumulator [decPointIndex] = accumulator[decPointIndex] * 10 + digit;
  7947. exponentAccumulator [decPointIndex]++;
  7948. }
  7949. }
  7950. else if (decPointIndex == 0 && *s == '.')
  7951. {
  7952. ++s;
  7953. decPointIndex = 1;
  7954. if (numSignificantDigits > maxSignificantDigits)
  7955. {
  7956. while (CharacterFunctions::isDigit (*s))
  7957. ++s;
  7958. break;
  7959. }
  7960. }
  7961. else
  7962. {
  7963. break;
  7964. }
  7965. }
  7966. result[0] = juce_mulexp10 (result[0], exponentAccumulator[0]) + accumulator[0];
  7967. if (decPointIndex != 0)
  7968. result[1] = juce_mulexp10 (result[1], exponentAccumulator[1]) + accumulator[1];
  7969. if ((*s == 'e' || *s == 'E') && digitsFound)
  7970. {
  7971. bool negativeExponent = false;
  7972. switch (*++s)
  7973. {
  7974. case '-': negativeExponent = true; // fall-through..
  7975. case '+': ++s;
  7976. }
  7977. while (CharacterFunctions::isDigit (*s))
  7978. exponent = (exponent * 10) + (*s++ - '0');
  7979. if (negativeExponent)
  7980. exponent = -exponent;
  7981. }
  7982. double r = juce_mulexp10 (result[0], exponent + exponentAdjustment[0]);
  7983. if (decPointIndex != 0)
  7984. r += juce_mulexp10 (result[1], exponent - exponentAdjustment[1]);
  7985. return isNegative ? -r : r;
  7986. }
  7987. double CharacterFunctions::getDoubleValue (const char* const s) throw()
  7988. {
  7989. return juce_atof <char> (s);
  7990. }
  7991. double CharacterFunctions::getDoubleValue (const juce_wchar* const s) throw()
  7992. {
  7993. return juce_atof <juce_wchar> (s);
  7994. }
  7995. char CharacterFunctions::toUpperCase (const char character) throw()
  7996. {
  7997. return (char) toupper (character);
  7998. }
  7999. juce_wchar CharacterFunctions::toUpperCase (const juce_wchar character) throw()
  8000. {
  8001. return towupper (character);
  8002. }
  8003. void CharacterFunctions::toUpperCase (char* s) throw()
  8004. {
  8005. #if JUCE_WIN32
  8006. strupr (s);
  8007. #else
  8008. while (*s != 0)
  8009. {
  8010. *s = toUpperCase (*s);
  8011. ++s;
  8012. }
  8013. #endif
  8014. }
  8015. void CharacterFunctions::toUpperCase (juce_wchar* s) throw()
  8016. {
  8017. #if JUCE_WIN32
  8018. _wcsupr (s);
  8019. #else
  8020. while (*s != 0)
  8021. {
  8022. *s = toUpperCase (*s);
  8023. ++s;
  8024. }
  8025. #endif
  8026. }
  8027. bool CharacterFunctions::isUpperCase (const char character) throw()
  8028. {
  8029. return isupper (character) != 0;
  8030. }
  8031. bool CharacterFunctions::isUpperCase (const juce_wchar character) throw()
  8032. {
  8033. #if JUCE_WIN32
  8034. return iswupper (character) != 0;
  8035. #else
  8036. return toLowerCase (character) != character;
  8037. #endif
  8038. }
  8039. char CharacterFunctions::toLowerCase (const char character) throw()
  8040. {
  8041. return (char) tolower (character);
  8042. }
  8043. juce_wchar CharacterFunctions::toLowerCase (const juce_wchar character) throw()
  8044. {
  8045. return towlower (character);
  8046. }
  8047. void CharacterFunctions::toLowerCase (char* s) throw()
  8048. {
  8049. #if JUCE_WIN32
  8050. strlwr (s);
  8051. #else
  8052. while (*s != 0)
  8053. {
  8054. *s = toLowerCase (*s);
  8055. ++s;
  8056. }
  8057. #endif
  8058. }
  8059. void CharacterFunctions::toLowerCase (juce_wchar* s) throw()
  8060. {
  8061. #if JUCE_WIN32
  8062. _wcslwr (s);
  8063. #else
  8064. while (*s != 0)
  8065. {
  8066. *s = toLowerCase (*s);
  8067. ++s;
  8068. }
  8069. #endif
  8070. }
  8071. bool CharacterFunctions::isLowerCase (const char character) throw()
  8072. {
  8073. return islower (character) != 0;
  8074. }
  8075. bool CharacterFunctions::isLowerCase (const juce_wchar character) throw()
  8076. {
  8077. #if JUCE_WIN32
  8078. return iswlower (character) != 0;
  8079. #else
  8080. return toUpperCase (character) != character;
  8081. #endif
  8082. }
  8083. bool CharacterFunctions::isWhitespace (const char character) throw()
  8084. {
  8085. return character == ' ' || (character <= 13 && character >= 9);
  8086. }
  8087. bool CharacterFunctions::isWhitespace (const juce_wchar character) throw()
  8088. {
  8089. return iswspace (character) != 0;
  8090. }
  8091. bool CharacterFunctions::isDigit (const char character) throw()
  8092. {
  8093. return (character >= '0' && character <= '9');
  8094. }
  8095. bool CharacterFunctions::isDigit (const juce_wchar character) throw()
  8096. {
  8097. return iswdigit (character) != 0;
  8098. }
  8099. bool CharacterFunctions::isLetter (const char character) throw()
  8100. {
  8101. return (character >= 'a' && character <= 'z')
  8102. || (character >= 'A' && character <= 'Z');
  8103. }
  8104. bool CharacterFunctions::isLetter (const juce_wchar character) throw()
  8105. {
  8106. return iswalpha (character) != 0;
  8107. }
  8108. bool CharacterFunctions::isLetterOrDigit (const char character) throw()
  8109. {
  8110. return (character >= 'a' && character <= 'z')
  8111. || (character >= 'A' && character <= 'Z')
  8112. || (character >= '0' && character <= '9');
  8113. }
  8114. bool CharacterFunctions::isLetterOrDigit (const juce_wchar character) throw()
  8115. {
  8116. return iswalnum (character) != 0;
  8117. }
  8118. int CharacterFunctions::getHexDigitValue (const juce_wchar digit) throw()
  8119. {
  8120. if (digit >= '0' && digit <= '9')
  8121. return digit - '0';
  8122. else if (digit >= 'a' && digit <= 'f')
  8123. return digit - ('a' - 10);
  8124. else if (digit >= 'A' && digit <= 'F')
  8125. return digit - ('A' - 10);
  8126. return -1;
  8127. }
  8128. END_JUCE_NAMESPACE
  8129. /*** End of inlined file: juce_CharacterFunctions.cpp ***/
  8130. /*** Start of inlined file: juce_LocalisedStrings.cpp ***/
  8131. BEGIN_JUCE_NAMESPACE
  8132. LocalisedStrings::LocalisedStrings (const String& fileContents)
  8133. {
  8134. loadFromText (fileContents);
  8135. }
  8136. LocalisedStrings::LocalisedStrings (const File& fileToLoad)
  8137. {
  8138. loadFromText (fileToLoad.loadFileAsString());
  8139. }
  8140. LocalisedStrings::~LocalisedStrings()
  8141. {
  8142. }
  8143. const String LocalisedStrings::translate (const String& text) const
  8144. {
  8145. return translations.getValue (text, text);
  8146. }
  8147. static int findCloseQuote (const String& text, int startPos)
  8148. {
  8149. juce_wchar lastChar = 0;
  8150. for (;;)
  8151. {
  8152. const juce_wchar c = text [startPos];
  8153. if (c == 0 || (c == '"' && lastChar != '\\'))
  8154. break;
  8155. lastChar = c;
  8156. ++startPos;
  8157. }
  8158. return startPos;
  8159. }
  8160. static const String unescapeString (const String& s)
  8161. {
  8162. return s.replace ("\\\"", "\"")
  8163. .replace ("\\\'", "\'")
  8164. .replace ("\\t", "\t")
  8165. .replace ("\\r", "\r")
  8166. .replace ("\\n", "\n");
  8167. }
  8168. void LocalisedStrings::loadFromText (const String& fileContents)
  8169. {
  8170. StringArray lines;
  8171. lines.addLines (fileContents);
  8172. for (int i = 0; i < lines.size(); ++i)
  8173. {
  8174. String line (lines[i].trim());
  8175. if (line.startsWithChar ('"'))
  8176. {
  8177. int closeQuote = findCloseQuote (line, 1);
  8178. const String originalText (unescapeString (line.substring (1, closeQuote)));
  8179. if (originalText.isNotEmpty())
  8180. {
  8181. const int openingQuote = findCloseQuote (line, closeQuote + 1);
  8182. closeQuote = findCloseQuote (line, openingQuote + 1);
  8183. const String newText (unescapeString (line.substring (openingQuote + 1, closeQuote)));
  8184. if (newText.isNotEmpty())
  8185. translations.set (originalText, newText);
  8186. }
  8187. }
  8188. else if (line.startsWithIgnoreCase ("language:"))
  8189. {
  8190. languageName = line.substring (9).trim();
  8191. }
  8192. else if (line.startsWithIgnoreCase ("countries:"))
  8193. {
  8194. countryCodes.addTokens (line.substring (10).trim(), true);
  8195. countryCodes.trim();
  8196. countryCodes.removeEmptyStrings();
  8197. }
  8198. }
  8199. }
  8200. void LocalisedStrings::setIgnoresCase (const bool shouldIgnoreCase)
  8201. {
  8202. translations.setIgnoresCase (shouldIgnoreCase);
  8203. }
  8204. static CriticalSection currentMappingsLock;
  8205. static LocalisedStrings* currentMappings = 0;
  8206. void LocalisedStrings::setCurrentMappings (LocalisedStrings* newTranslations)
  8207. {
  8208. const ScopedLock sl (currentMappingsLock);
  8209. delete currentMappings;
  8210. currentMappings = newTranslations;
  8211. }
  8212. LocalisedStrings* LocalisedStrings::getCurrentMappings()
  8213. {
  8214. return currentMappings;
  8215. }
  8216. const String LocalisedStrings::translateWithCurrentMappings (const String& text)
  8217. {
  8218. const ScopedLock sl (currentMappingsLock);
  8219. if (currentMappings != 0)
  8220. return currentMappings->translate (text);
  8221. return text;
  8222. }
  8223. const String LocalisedStrings::translateWithCurrentMappings (const char* text)
  8224. {
  8225. return translateWithCurrentMappings (String (text));
  8226. }
  8227. END_JUCE_NAMESPACE
  8228. /*** End of inlined file: juce_LocalisedStrings.cpp ***/
  8229. /*** Start of inlined file: juce_String.cpp ***/
  8230. #ifdef _MSC_VER
  8231. #pragma warning (push)
  8232. #pragma warning (disable: 4514)
  8233. #endif
  8234. #include <locale>
  8235. #if JUCE_MSVC
  8236. #include <float.h>
  8237. #endif
  8238. BEGIN_JUCE_NAMESPACE
  8239. #ifdef _MSC_VER
  8240. #pragma warning (pop)
  8241. #endif
  8242. #if defined (JUCE_STRINGS_ARE_UNICODE) && ! JUCE_STRINGS_ARE_UNICODE
  8243. #error "JUCE_STRINGS_ARE_UNICODE is deprecated! All strings are now unicode by default."
  8244. #endif
  8245. class StringHolder
  8246. {
  8247. public:
  8248. StringHolder()
  8249. : refCount (0x3fffffff), allocatedNumChars (0)
  8250. {
  8251. text[0] = 0;
  8252. }
  8253. static juce_wchar* createUninitialised (const size_t numChars)
  8254. {
  8255. StringHolder* const s = reinterpret_cast <StringHolder*> (new char [sizeof (StringHolder) + numChars * sizeof (juce_wchar)]);
  8256. s->refCount.value = 0;
  8257. s->allocatedNumChars = numChars;
  8258. return &(s->text[0]);
  8259. }
  8260. static juce_wchar* createCopy (const juce_wchar* const src, const size_t numChars)
  8261. {
  8262. juce_wchar* const dest = createUninitialised (numChars);
  8263. copyChars (dest, src, numChars);
  8264. return dest;
  8265. }
  8266. static juce_wchar* createCopy (const char* const src, const size_t numChars)
  8267. {
  8268. juce_wchar* const dest = createUninitialised (numChars);
  8269. CharacterFunctions::copy (dest, src, (int) numChars);
  8270. dest [numChars] = 0;
  8271. return dest;
  8272. }
  8273. static inline juce_wchar* getEmpty() throw()
  8274. {
  8275. return &(empty.text[0]);
  8276. }
  8277. static void retain (juce_wchar* const text) throw()
  8278. {
  8279. ++(bufferFromText (text)->refCount);
  8280. }
  8281. static inline void release (StringHolder* const b) throw()
  8282. {
  8283. if (--(b->refCount) == -1 && b != &empty)
  8284. delete[] reinterpret_cast <char*> (b);
  8285. }
  8286. static void release (juce_wchar* const text) throw()
  8287. {
  8288. release (bufferFromText (text));
  8289. }
  8290. static juce_wchar* makeUnique (juce_wchar* const text)
  8291. {
  8292. StringHolder* const b = bufferFromText (text);
  8293. if (b->refCount.get() <= 0)
  8294. return text;
  8295. juce_wchar* const newText = createCopy (text, b->allocatedNumChars);
  8296. release (b);
  8297. return newText;
  8298. }
  8299. static juce_wchar* makeUniqueWithSize (juce_wchar* const text, size_t numChars)
  8300. {
  8301. StringHolder* const b = bufferFromText (text);
  8302. if (b->refCount.get() <= 0 && b->allocatedNumChars >= numChars)
  8303. return text;
  8304. juce_wchar* const newText = createUninitialised (jmax (b->allocatedNumChars, numChars));
  8305. copyChars (newText, text, b->allocatedNumChars);
  8306. release (b);
  8307. return newText;
  8308. }
  8309. static size_t getAllocatedNumChars (juce_wchar* const text) throw()
  8310. {
  8311. return bufferFromText (text)->allocatedNumChars;
  8312. }
  8313. static void copyChars (juce_wchar* const dest, const juce_wchar* const src, const size_t numChars) throw()
  8314. {
  8315. memcpy (dest, src, numChars * sizeof (juce_wchar));
  8316. dest [numChars] = 0;
  8317. }
  8318. Atomic<int> refCount;
  8319. size_t allocatedNumChars;
  8320. juce_wchar text[1];
  8321. static StringHolder empty;
  8322. private:
  8323. static inline StringHolder* bufferFromText (void* const text) throw()
  8324. {
  8325. // (Can't use offsetof() here because of warnings about this not being a POD)
  8326. return reinterpret_cast <StringHolder*> (static_cast <char*> (text)
  8327. - (reinterpret_cast <size_t> (reinterpret_cast <StringHolder*> (1)->text) - 1));
  8328. }
  8329. };
  8330. StringHolder StringHolder::empty;
  8331. const String String::empty;
  8332. void String::createInternal (const juce_wchar* const t, const size_t numChars)
  8333. {
  8334. jassert (t[numChars] == 0); // must have a null terminator
  8335. text = StringHolder::createCopy (t, numChars);
  8336. }
  8337. void String::appendInternal (const juce_wchar* const newText, const int numExtraChars)
  8338. {
  8339. if (numExtraChars > 0)
  8340. {
  8341. const int oldLen = length();
  8342. const int newTotalLen = oldLen + numExtraChars;
  8343. text = StringHolder::makeUniqueWithSize (text, newTotalLen);
  8344. StringHolder::copyChars (text + oldLen, newText, numExtraChars);
  8345. }
  8346. }
  8347. void String::preallocateStorage (const size_t numChars)
  8348. {
  8349. text = StringHolder::makeUniqueWithSize (text, numChars);
  8350. }
  8351. String::String() throw()
  8352. : text (StringHolder::getEmpty())
  8353. {
  8354. }
  8355. String::~String() throw()
  8356. {
  8357. StringHolder::release (text);
  8358. }
  8359. String::String (const String& other) throw()
  8360. : text (other.text)
  8361. {
  8362. StringHolder::retain (text);
  8363. }
  8364. void String::swapWith (String& other) throw()
  8365. {
  8366. swapVariables (text, other.text);
  8367. }
  8368. String& String::operator= (const String& other) throw()
  8369. {
  8370. juce_wchar* const newText = other.text;
  8371. StringHolder::retain (newText);
  8372. StringHolder::release (reinterpret_cast <Atomic<juce_wchar*>*> (&text)->exchange (newText));
  8373. return *this;
  8374. }
  8375. String::String (const size_t numChars, const int /*dummyVariable*/)
  8376. : text (StringHolder::createUninitialised (numChars))
  8377. {
  8378. }
  8379. String::String (const String& stringToCopy, const size_t charsToAllocate)
  8380. {
  8381. const size_t otherSize = StringHolder::getAllocatedNumChars (stringToCopy.text);
  8382. text = StringHolder::createUninitialised (jmax (charsToAllocate, otherSize));
  8383. StringHolder::copyChars (text, stringToCopy.text, otherSize);
  8384. }
  8385. String::String (const char* const t)
  8386. {
  8387. if (t != 0 && *t != 0)
  8388. text = StringHolder::createCopy (t, CharacterFunctions::length (t));
  8389. else
  8390. text = StringHolder::getEmpty();
  8391. }
  8392. String::String (const juce_wchar* const t)
  8393. {
  8394. if (t != 0 && *t != 0)
  8395. text = StringHolder::createCopy (t, CharacterFunctions::length (t));
  8396. else
  8397. text = StringHolder::getEmpty();
  8398. }
  8399. String::String (const char* const t, const size_t maxChars)
  8400. {
  8401. int i;
  8402. for (i = 0; (size_t) i < maxChars; ++i)
  8403. if (t[i] == 0)
  8404. break;
  8405. if (i > 0)
  8406. text = StringHolder::createCopy (t, i);
  8407. else
  8408. text = StringHolder::getEmpty();
  8409. }
  8410. String::String (const juce_wchar* const t, const size_t maxChars)
  8411. {
  8412. int i;
  8413. for (i = 0; (size_t) i < maxChars; ++i)
  8414. if (t[i] == 0)
  8415. break;
  8416. if (i > 0)
  8417. text = StringHolder::createCopy (t, i);
  8418. else
  8419. text = StringHolder::getEmpty();
  8420. }
  8421. const String String::charToString (const juce_wchar character)
  8422. {
  8423. String result ((size_t) 1, (int) 0);
  8424. result.text[0] = character;
  8425. result.text[1] = 0;
  8426. return result;
  8427. }
  8428. namespace NumberToStringConverters
  8429. {
  8430. // pass in a pointer to the END of a buffer..
  8431. static juce_wchar* int64ToString (juce_wchar* t, const int64 n) throw()
  8432. {
  8433. *--t = 0;
  8434. int64 v = (n >= 0) ? n : -n;
  8435. do
  8436. {
  8437. *--t = (juce_wchar) ('0' + (int) (v % 10));
  8438. v /= 10;
  8439. } while (v > 0);
  8440. if (n < 0)
  8441. *--t = '-';
  8442. return t;
  8443. }
  8444. static juce_wchar* uint64ToString (juce_wchar* t, int64 v) throw()
  8445. {
  8446. *--t = 0;
  8447. do
  8448. {
  8449. *--t = (juce_wchar) ('0' + (int) (v % 10));
  8450. v /= 10;
  8451. } while (v > 0);
  8452. return t;
  8453. }
  8454. static juce_wchar* intToString (juce_wchar* t, const int n) throw()
  8455. {
  8456. if (n == (int) 0x80000000) // (would cause an overflow)
  8457. return int64ToString (t, n);
  8458. *--t = 0;
  8459. int v = abs (n);
  8460. do
  8461. {
  8462. *--t = (juce_wchar) ('0' + (v % 10));
  8463. v /= 10;
  8464. } while (v > 0);
  8465. if (n < 0)
  8466. *--t = '-';
  8467. return t;
  8468. }
  8469. static juce_wchar* uintToString (juce_wchar* t, unsigned int v) throw()
  8470. {
  8471. *--t = 0;
  8472. do
  8473. {
  8474. *--t = (juce_wchar) ('0' + (v % 10));
  8475. v /= 10;
  8476. } while (v > 0);
  8477. return t;
  8478. }
  8479. static juce_wchar getDecimalPoint()
  8480. {
  8481. #if JUCE_WINDOWS && _MSC_VER < 1400
  8482. static juce_wchar dp = std::_USE (std::locale(), std::numpunct <wchar_t>).decimal_point();
  8483. #else
  8484. static juce_wchar dp = std::use_facet <std::numpunct <wchar_t> > (std::locale()).decimal_point();
  8485. #endif
  8486. return dp;
  8487. }
  8488. static juce_wchar* doubleToString (juce_wchar* buffer, int numChars, double n, int numDecPlaces, size_t& len) throw()
  8489. {
  8490. if (numDecPlaces > 0 && n > -1.0e20 && n < 1.0e20)
  8491. {
  8492. juce_wchar* const end = buffer + numChars;
  8493. juce_wchar* t = end;
  8494. int64 v = (int64) (pow (10.0, numDecPlaces) * fabs (n) + 0.5);
  8495. *--t = (juce_wchar) 0;
  8496. while (numDecPlaces >= 0 || v > 0)
  8497. {
  8498. if (numDecPlaces == 0)
  8499. *--t = getDecimalPoint();
  8500. *--t = (juce_wchar) ('0' + (v % 10));
  8501. v /= 10;
  8502. --numDecPlaces;
  8503. }
  8504. if (n < 0)
  8505. *--t = '-';
  8506. len = end - t - 1;
  8507. return t;
  8508. }
  8509. else
  8510. {
  8511. #if JUCE_WIN32
  8512. #if _MSC_VER <= 1400
  8513. len = _snwprintf (buffer, numChars, L"%.9g", n);
  8514. #else
  8515. len = _snwprintf_s (buffer, numChars, _TRUNCATE, L"%.9g", n);
  8516. #endif
  8517. #else
  8518. len = swprintf (buffer, numChars, L"%.9g", n);
  8519. #endif
  8520. return buffer;
  8521. }
  8522. }
  8523. }
  8524. String::String (const int number)
  8525. {
  8526. juce_wchar buffer [16];
  8527. juce_wchar* const end = buffer + numElementsInArray (buffer);
  8528. juce_wchar* const start = NumberToStringConverters::intToString (end, number);
  8529. createInternal (start, end - start - 1);
  8530. }
  8531. String::String (const unsigned int number)
  8532. {
  8533. juce_wchar buffer [16];
  8534. juce_wchar* const end = buffer + numElementsInArray (buffer);
  8535. juce_wchar* const start = NumberToStringConverters::uintToString (end, number);
  8536. createInternal (start, end - start - 1);
  8537. }
  8538. String::String (const short number)
  8539. {
  8540. juce_wchar buffer [16];
  8541. juce_wchar* const end = buffer + numElementsInArray (buffer);
  8542. juce_wchar* const start = NumberToStringConverters::intToString (end, (int) number);
  8543. createInternal (start, end - start - 1);
  8544. }
  8545. String::String (const unsigned short number)
  8546. {
  8547. juce_wchar buffer [16];
  8548. juce_wchar* const end = buffer + numElementsInArray (buffer);
  8549. juce_wchar* const start = NumberToStringConverters::uintToString (end, (unsigned int) number);
  8550. createInternal (start, end - start - 1);
  8551. }
  8552. String::String (const int64 number)
  8553. {
  8554. juce_wchar buffer [32];
  8555. juce_wchar* const end = buffer + numElementsInArray (buffer);
  8556. juce_wchar* const start = NumberToStringConverters::int64ToString (end, number);
  8557. createInternal (start, end - start - 1);
  8558. }
  8559. String::String (const uint64 number)
  8560. {
  8561. juce_wchar buffer [32];
  8562. juce_wchar* const end = buffer + numElementsInArray (buffer);
  8563. juce_wchar* const start = NumberToStringConverters::uint64ToString (end, number);
  8564. createInternal (start, end - start - 1);
  8565. }
  8566. String::String (const float number, const int numberOfDecimalPlaces)
  8567. {
  8568. juce_wchar buffer [48];
  8569. size_t len;
  8570. juce_wchar* start = NumberToStringConverters::doubleToString (buffer, numElementsInArray (buffer), (double) number, numberOfDecimalPlaces, len);
  8571. createInternal (start, len);
  8572. }
  8573. String::String (const double number, const int numberOfDecimalPlaces)
  8574. {
  8575. juce_wchar buffer [48];
  8576. size_t len;
  8577. juce_wchar* start = NumberToStringConverters::doubleToString (buffer, numElementsInArray (buffer), number, numberOfDecimalPlaces, len);
  8578. createInternal (start, len);
  8579. }
  8580. int String::length() const throw()
  8581. {
  8582. return CharacterFunctions::length (text);
  8583. }
  8584. int String::hashCode() const throw()
  8585. {
  8586. const juce_wchar* t = text;
  8587. int result = 0;
  8588. while (*t != (juce_wchar) 0)
  8589. result = 31 * result + *t++;
  8590. return result;
  8591. }
  8592. int64 String::hashCode64() const throw()
  8593. {
  8594. const juce_wchar* t = text;
  8595. int64 result = 0;
  8596. while (*t != (juce_wchar) 0)
  8597. result = 101 * result + *t++;
  8598. return result;
  8599. }
  8600. bool JUCE_CALLTYPE operator== (const String& string1, const String& string2) throw()
  8601. {
  8602. return string1.compare (string2) == 0;
  8603. }
  8604. bool JUCE_CALLTYPE operator== (const String& string1, const char* string2) throw()
  8605. {
  8606. return string1.compare (string2) == 0;
  8607. }
  8608. bool JUCE_CALLTYPE operator== (const String& string1, const juce_wchar* string2) throw()
  8609. {
  8610. return string1.compare (string2) == 0;
  8611. }
  8612. bool JUCE_CALLTYPE operator!= (const String& string1, const String& string2) throw()
  8613. {
  8614. return string1.compare (string2) != 0;
  8615. }
  8616. bool JUCE_CALLTYPE operator!= (const String& string1, const char* string2) throw()
  8617. {
  8618. return string1.compare (string2) != 0;
  8619. }
  8620. bool JUCE_CALLTYPE operator!= (const String& string1, const juce_wchar* string2) throw()
  8621. {
  8622. return string1.compare (string2) != 0;
  8623. }
  8624. bool JUCE_CALLTYPE operator> (const String& string1, const String& string2) throw()
  8625. {
  8626. return string1.compare (string2) > 0;
  8627. }
  8628. bool JUCE_CALLTYPE operator< (const String& string1, const String& string2) throw()
  8629. {
  8630. return string1.compare (string2) < 0;
  8631. }
  8632. bool JUCE_CALLTYPE operator>= (const String& string1, const String& string2) throw()
  8633. {
  8634. return string1.compare (string2) >= 0;
  8635. }
  8636. bool JUCE_CALLTYPE operator<= (const String& string1, const String& string2) throw()
  8637. {
  8638. return string1.compare (string2) <= 0;
  8639. }
  8640. bool String::equalsIgnoreCase (const juce_wchar* t) const throw()
  8641. {
  8642. return t != 0 ? CharacterFunctions::compareIgnoreCase (text, t) == 0
  8643. : isEmpty();
  8644. }
  8645. bool String::equalsIgnoreCase (const char* t) const throw()
  8646. {
  8647. return t != 0 ? CharacterFunctions::compareIgnoreCase (text, t) == 0
  8648. : isEmpty();
  8649. }
  8650. bool String::equalsIgnoreCase (const String& other) const throw()
  8651. {
  8652. return text == other.text
  8653. || CharacterFunctions::compareIgnoreCase (text, other.text) == 0;
  8654. }
  8655. int String::compare (const String& other) const throw()
  8656. {
  8657. return (text == other.text) ? 0 : CharacterFunctions::compare (text, other.text);
  8658. }
  8659. int String::compare (const char* other) const throw()
  8660. {
  8661. return other == 0 ? isEmpty() : CharacterFunctions::compare (text, other);
  8662. }
  8663. int String::compare (const juce_wchar* other) const throw()
  8664. {
  8665. return other == 0 ? isEmpty() : CharacterFunctions::compare (text, other);
  8666. }
  8667. int String::compareIgnoreCase (const String& other) const throw()
  8668. {
  8669. return (text == other.text) ? 0 : CharacterFunctions::compareIgnoreCase (text, other.text);
  8670. }
  8671. int String::compareLexicographically (const String& other) const throw()
  8672. {
  8673. const juce_wchar* s1 = text;
  8674. while (*s1 != 0 && ! CharacterFunctions::isLetterOrDigit (*s1))
  8675. ++s1;
  8676. const juce_wchar* s2 = other.text;
  8677. while (*s2 != 0 && ! CharacterFunctions::isLetterOrDigit (*s2))
  8678. ++s2;
  8679. return CharacterFunctions::compareIgnoreCase (s1, s2);
  8680. }
  8681. String& String::operator+= (const juce_wchar* const t)
  8682. {
  8683. if (t != 0)
  8684. appendInternal (t, CharacterFunctions::length (t));
  8685. return *this;
  8686. }
  8687. String& String::operator+= (const String& other)
  8688. {
  8689. if (isEmpty())
  8690. operator= (other);
  8691. else
  8692. appendInternal (other.text, other.length());
  8693. return *this;
  8694. }
  8695. String& String::operator+= (const char ch)
  8696. {
  8697. const juce_wchar asString[] = { (juce_wchar) ch, 0 };
  8698. return operator+= (static_cast <const juce_wchar*> (asString));
  8699. }
  8700. String& String::operator+= (const juce_wchar ch)
  8701. {
  8702. const juce_wchar asString[] = { (juce_wchar) ch, 0 };
  8703. return operator+= (static_cast <const juce_wchar*> (asString));
  8704. }
  8705. String& String::operator+= (const int number)
  8706. {
  8707. juce_wchar buffer [16];
  8708. juce_wchar* const end = buffer + numElementsInArray (buffer);
  8709. juce_wchar* const start = NumberToStringConverters::intToString (end, number);
  8710. appendInternal (start, (int) (end - start));
  8711. return *this;
  8712. }
  8713. String& String::operator+= (const unsigned int number)
  8714. {
  8715. juce_wchar buffer [16];
  8716. juce_wchar* const end = buffer + numElementsInArray (buffer);
  8717. juce_wchar* const start = NumberToStringConverters::uintToString (end, number);
  8718. appendInternal (start, (int) (end - start));
  8719. return *this;
  8720. }
  8721. void String::append (const juce_wchar* const other, const int howMany)
  8722. {
  8723. if (howMany > 0)
  8724. {
  8725. int i;
  8726. for (i = 0; i < howMany; ++i)
  8727. if (other[i] == 0)
  8728. break;
  8729. appendInternal (other, i);
  8730. }
  8731. }
  8732. const String JUCE_CALLTYPE operator+ (const char* const string1, const String& string2)
  8733. {
  8734. String s (string1);
  8735. return s += string2;
  8736. }
  8737. const String JUCE_CALLTYPE operator+ (const juce_wchar* const string1, const String& string2)
  8738. {
  8739. String s (string1);
  8740. return s += string2;
  8741. }
  8742. const String JUCE_CALLTYPE operator+ (const char string1, const String& string2)
  8743. {
  8744. return String::charToString (string1) + string2;
  8745. }
  8746. const String JUCE_CALLTYPE operator+ (const juce_wchar string1, const String& string2)
  8747. {
  8748. return String::charToString (string1) + string2;
  8749. }
  8750. const String JUCE_CALLTYPE operator+ (String string1, const String& string2)
  8751. {
  8752. return string1 += string2;
  8753. }
  8754. const String JUCE_CALLTYPE operator+ (String string1, const char* const string2)
  8755. {
  8756. return string1 += string2;
  8757. }
  8758. const String JUCE_CALLTYPE operator+ (String string1, const juce_wchar* const string2)
  8759. {
  8760. return string1 += string2;
  8761. }
  8762. const String JUCE_CALLTYPE operator+ (String string1, const char string2)
  8763. {
  8764. return string1 += string2;
  8765. }
  8766. const String JUCE_CALLTYPE operator+ (String string1, const juce_wchar string2)
  8767. {
  8768. return string1 += string2;
  8769. }
  8770. String& JUCE_CALLTYPE operator<< (String& string1, const char characterToAppend)
  8771. {
  8772. return string1 += characterToAppend;
  8773. }
  8774. String& JUCE_CALLTYPE operator<< (String& string1, const juce_wchar characterToAppend)
  8775. {
  8776. return string1 += characterToAppend;
  8777. }
  8778. String& JUCE_CALLTYPE operator<< (String& string1, const char* const string2)
  8779. {
  8780. return string1 += string2;
  8781. }
  8782. String& JUCE_CALLTYPE operator<< (String& string1, const juce_wchar* const string2)
  8783. {
  8784. return string1 += string2;
  8785. }
  8786. String& JUCE_CALLTYPE operator<< (String& string1, const String& string2)
  8787. {
  8788. return string1 += string2;
  8789. }
  8790. String& JUCE_CALLTYPE operator<< (String& string1, const short number)
  8791. {
  8792. return string1 += (int) number;
  8793. }
  8794. String& JUCE_CALLTYPE operator<< (String& string1, const int number)
  8795. {
  8796. return string1 += number;
  8797. }
  8798. String& JUCE_CALLTYPE operator<< (String& string1, const unsigned int number)
  8799. {
  8800. return string1 += number;
  8801. }
  8802. String& JUCE_CALLTYPE operator<< (String& string1, const long number)
  8803. {
  8804. return string1 += (int) number;
  8805. }
  8806. String& JUCE_CALLTYPE operator<< (String& string1, const unsigned long number)
  8807. {
  8808. return string1 += (unsigned int) number;
  8809. }
  8810. String& JUCE_CALLTYPE operator<< (String& string1, const float number)
  8811. {
  8812. return string1 += String (number);
  8813. }
  8814. String& JUCE_CALLTYPE operator<< (String& string1, const double number)
  8815. {
  8816. return string1 += String (number);
  8817. }
  8818. OutputStream& JUCE_CALLTYPE operator<< (OutputStream& stream, const String& text)
  8819. {
  8820. // (This avoids using toUTF8() to prevent the memory bloat that it would leave behind
  8821. // if lots of large, persistent strings were to be written to streams).
  8822. const int numBytes = text.getNumBytesAsUTF8();
  8823. HeapBlock<char> temp (numBytes + 1);
  8824. text.copyToUTF8 (temp, numBytes + 1);
  8825. stream.write (temp, numBytes);
  8826. return stream;
  8827. }
  8828. int String::indexOfChar (const juce_wchar character) const throw()
  8829. {
  8830. const juce_wchar* t = text;
  8831. for (;;)
  8832. {
  8833. if (*t == character)
  8834. return (int) (t - text);
  8835. if (*t++ == 0)
  8836. return -1;
  8837. }
  8838. }
  8839. int String::lastIndexOfChar (const juce_wchar character) const throw()
  8840. {
  8841. for (int i = length(); --i >= 0;)
  8842. if (text[i] == character)
  8843. return i;
  8844. return -1;
  8845. }
  8846. int String::indexOf (const String& t) const throw()
  8847. {
  8848. const juce_wchar* const r = CharacterFunctions::find (text, t.text);
  8849. return r == 0 ? -1 : (int) (r - text);
  8850. }
  8851. int String::indexOfChar (const int startIndex,
  8852. const juce_wchar character) const throw()
  8853. {
  8854. if (startIndex > 0 && startIndex >= length())
  8855. return -1;
  8856. const juce_wchar* t = text + jmax (0, startIndex);
  8857. for (;;)
  8858. {
  8859. if (*t == character)
  8860. return (int) (t - text);
  8861. if (*t == 0)
  8862. return -1;
  8863. ++t;
  8864. }
  8865. }
  8866. int String::indexOfAnyOf (const String& charactersToLookFor,
  8867. const int startIndex,
  8868. const bool ignoreCase) const throw()
  8869. {
  8870. if (startIndex > 0 && startIndex >= length())
  8871. return -1;
  8872. const juce_wchar* t = text + jmax (0, startIndex);
  8873. while (*t != 0)
  8874. {
  8875. if (CharacterFunctions::indexOfChar (charactersToLookFor.text, *t, ignoreCase) >= 0)
  8876. return (int) (t - text);
  8877. ++t;
  8878. }
  8879. return -1;
  8880. }
  8881. int String::indexOf (const int startIndex, const String& other) const throw()
  8882. {
  8883. if (startIndex > 0 && startIndex >= length())
  8884. return -1;
  8885. const juce_wchar* const found = CharacterFunctions::find (text + jmax (0, startIndex), other.text);
  8886. return found == 0 ? -1 : (int) (found - text);
  8887. }
  8888. int String::indexOfIgnoreCase (const String& other) const throw()
  8889. {
  8890. if (other.isNotEmpty())
  8891. {
  8892. const int len = other.length();
  8893. const int end = length() - len;
  8894. for (int i = 0; i <= end; ++i)
  8895. if (CharacterFunctions::compareIgnoreCase (text + i, other.text, len) == 0)
  8896. return i;
  8897. }
  8898. return -1;
  8899. }
  8900. int String::indexOfIgnoreCase (const int startIndex, const String& other) const throw()
  8901. {
  8902. if (other.isNotEmpty())
  8903. {
  8904. const int len = other.length();
  8905. const int end = length() - len;
  8906. for (int i = jmax (0, startIndex); i <= end; ++i)
  8907. if (CharacterFunctions::compareIgnoreCase (text + i, other.text, len) == 0)
  8908. return i;
  8909. }
  8910. return -1;
  8911. }
  8912. int String::lastIndexOf (const String& other) const throw()
  8913. {
  8914. if (other.isNotEmpty())
  8915. {
  8916. const int len = other.length();
  8917. int i = length() - len;
  8918. if (i >= 0)
  8919. {
  8920. const juce_wchar* n = text + i;
  8921. while (i >= 0)
  8922. {
  8923. if (CharacterFunctions::compare (n--, other.text, len) == 0)
  8924. return i;
  8925. --i;
  8926. }
  8927. }
  8928. }
  8929. return -1;
  8930. }
  8931. int String::lastIndexOfIgnoreCase (const String& other) const throw()
  8932. {
  8933. if (other.isNotEmpty())
  8934. {
  8935. const int len = other.length();
  8936. int i = length() - len;
  8937. if (i >= 0)
  8938. {
  8939. const juce_wchar* n = text + i;
  8940. while (i >= 0)
  8941. {
  8942. if (CharacterFunctions::compareIgnoreCase (n--, other.text, len) == 0)
  8943. return i;
  8944. --i;
  8945. }
  8946. }
  8947. }
  8948. return -1;
  8949. }
  8950. int String::lastIndexOfAnyOf (const String& charactersToLookFor, const bool ignoreCase) const throw()
  8951. {
  8952. for (int i = length(); --i >= 0;)
  8953. if (CharacterFunctions::indexOfChar (charactersToLookFor.text, text[i], ignoreCase) >= 0)
  8954. return i;
  8955. return -1;
  8956. }
  8957. bool String::contains (const String& other) const throw()
  8958. {
  8959. return indexOf (other) >= 0;
  8960. }
  8961. bool String::containsChar (const juce_wchar character) const throw()
  8962. {
  8963. const juce_wchar* t = text;
  8964. for (;;)
  8965. {
  8966. if (*t == 0)
  8967. return false;
  8968. if (*t == character)
  8969. return true;
  8970. ++t;
  8971. }
  8972. }
  8973. bool String::containsIgnoreCase (const String& t) const throw()
  8974. {
  8975. return indexOfIgnoreCase (t) >= 0;
  8976. }
  8977. int String::indexOfWholeWord (const String& word) const throw()
  8978. {
  8979. if (word.isNotEmpty())
  8980. {
  8981. const int wordLen = word.length();
  8982. const int end = length() - wordLen;
  8983. const juce_wchar* t = text;
  8984. for (int i = 0; i <= end; ++i)
  8985. {
  8986. if (CharacterFunctions::compare (t, word.text, wordLen) == 0
  8987. && (i == 0 || ! CharacterFunctions::isLetterOrDigit (* (t - 1)))
  8988. && ! CharacterFunctions::isLetterOrDigit (t [wordLen]))
  8989. {
  8990. return i;
  8991. }
  8992. ++t;
  8993. }
  8994. }
  8995. return -1;
  8996. }
  8997. int String::indexOfWholeWordIgnoreCase (const String& word) const throw()
  8998. {
  8999. if (word.isNotEmpty())
  9000. {
  9001. const int wordLen = word.length();
  9002. const int end = length() - wordLen;
  9003. const juce_wchar* t = text;
  9004. for (int i = 0; i <= end; ++i)
  9005. {
  9006. if (CharacterFunctions::compareIgnoreCase (t, word.text, wordLen) == 0
  9007. && (i == 0 || ! CharacterFunctions::isLetterOrDigit (* (t - 1)))
  9008. && ! CharacterFunctions::isLetterOrDigit (t [wordLen]))
  9009. {
  9010. return i;
  9011. }
  9012. ++t;
  9013. }
  9014. }
  9015. return -1;
  9016. }
  9017. bool String::containsWholeWord (const String& wordToLookFor) const throw()
  9018. {
  9019. return indexOfWholeWord (wordToLookFor) >= 0;
  9020. }
  9021. bool String::containsWholeWordIgnoreCase (const String& wordToLookFor) const throw()
  9022. {
  9023. return indexOfWholeWordIgnoreCase (wordToLookFor) >= 0;
  9024. }
  9025. static int indexOfMatch (const juce_wchar* const wildcard,
  9026. const juce_wchar* const test,
  9027. const bool ignoreCase) throw()
  9028. {
  9029. int start = 0;
  9030. while (test [start] != 0)
  9031. {
  9032. int i = 0;
  9033. for (;;)
  9034. {
  9035. const juce_wchar wc = wildcard [i];
  9036. const juce_wchar c = test [i + start];
  9037. if (wc == c
  9038. || (ignoreCase && CharacterFunctions::toLowerCase (wc) == CharacterFunctions::toLowerCase (c))
  9039. || (wc == '?' && c != 0))
  9040. {
  9041. if (wc == 0)
  9042. return start;
  9043. ++i;
  9044. }
  9045. else
  9046. {
  9047. if (wc == '*' && (wildcard [i + 1] == 0
  9048. || indexOfMatch (wildcard + i + 1,
  9049. test + start + i,
  9050. ignoreCase) >= 0))
  9051. {
  9052. return start;
  9053. }
  9054. break;
  9055. }
  9056. }
  9057. ++start;
  9058. }
  9059. return -1;
  9060. }
  9061. bool String::matchesWildcard (const String& wildcard, const bool ignoreCase) const throw()
  9062. {
  9063. int i = 0;
  9064. for (;;)
  9065. {
  9066. const juce_wchar wc = wildcard.text [i];
  9067. const juce_wchar c = text [i];
  9068. if (wc == c
  9069. || (ignoreCase && CharacterFunctions::toLowerCase (wc) == CharacterFunctions::toLowerCase (c))
  9070. || (wc == '?' && c != 0))
  9071. {
  9072. if (wc == 0)
  9073. return true;
  9074. ++i;
  9075. }
  9076. else
  9077. {
  9078. return wc == '*' && (wildcard [i + 1] == 0
  9079. || indexOfMatch (wildcard.text + i + 1,
  9080. text + i,
  9081. ignoreCase) >= 0);
  9082. }
  9083. }
  9084. }
  9085. const String String::repeatedString (const String& stringToRepeat, int numberOfTimesToRepeat)
  9086. {
  9087. const int len = stringToRepeat.length();
  9088. String result ((size_t) (len * numberOfTimesToRepeat + 1), (int) 0);
  9089. juce_wchar* n = result.text;
  9090. *n = 0;
  9091. while (--numberOfTimesToRepeat >= 0)
  9092. {
  9093. StringHolder::copyChars (n, stringToRepeat.text, len);
  9094. n += len;
  9095. }
  9096. return result;
  9097. }
  9098. const String String::paddedLeft (const juce_wchar padCharacter, int minimumLength) const
  9099. {
  9100. jassert (padCharacter != 0);
  9101. const int len = length();
  9102. if (len >= minimumLength || padCharacter == 0)
  9103. return *this;
  9104. String result ((size_t) minimumLength + 1, (int) 0);
  9105. juce_wchar* n = result.text;
  9106. minimumLength -= len;
  9107. while (--minimumLength >= 0)
  9108. *n++ = padCharacter;
  9109. StringHolder::copyChars (n, text, len);
  9110. return result;
  9111. }
  9112. const String String::paddedRight (const juce_wchar padCharacter, int minimumLength) const
  9113. {
  9114. jassert (padCharacter != 0);
  9115. const int len = length();
  9116. if (len >= minimumLength || padCharacter == 0)
  9117. return *this;
  9118. String result (*this, (size_t) minimumLength);
  9119. juce_wchar* n = result.text + len;
  9120. minimumLength -= len;
  9121. while (--minimumLength >= 0)
  9122. *n++ = padCharacter;
  9123. *n = 0;
  9124. return result;
  9125. }
  9126. const String String::replaceSection (int index, int numCharsToReplace, const String& stringToInsert) const
  9127. {
  9128. if (index < 0)
  9129. {
  9130. // a negative index to replace from?
  9131. jassertfalse
  9132. index = 0;
  9133. }
  9134. if (numCharsToReplace < 0)
  9135. {
  9136. // replacing a negative number of characters?
  9137. numCharsToReplace = 0;
  9138. jassertfalse;
  9139. }
  9140. const int len = length();
  9141. if (index + numCharsToReplace > len)
  9142. {
  9143. if (index > len)
  9144. {
  9145. // replacing beyond the end of the string?
  9146. index = len;
  9147. jassertfalse
  9148. }
  9149. numCharsToReplace = len - index;
  9150. }
  9151. const int newStringLen = stringToInsert.length();
  9152. const int newTotalLen = len + newStringLen - numCharsToReplace;
  9153. if (newTotalLen <= 0)
  9154. return String::empty;
  9155. String result ((size_t) newTotalLen, (int) 0);
  9156. StringHolder::copyChars (result.text, text, index);
  9157. if (newStringLen > 0)
  9158. StringHolder::copyChars (result.text + index, stringToInsert.text, newStringLen);
  9159. const int endStringLen = newTotalLen - (index + newStringLen);
  9160. if (endStringLen > 0)
  9161. StringHolder::copyChars (result.text + (index + newStringLen),
  9162. text + (index + numCharsToReplace),
  9163. endStringLen);
  9164. return result;
  9165. }
  9166. const String String::replace (const String& stringToReplace, const String& stringToInsert, const bool ignoreCase) const
  9167. {
  9168. const int stringToReplaceLen = stringToReplace.length();
  9169. const int stringToInsertLen = stringToInsert.length();
  9170. int i = 0;
  9171. String result (*this);
  9172. while ((i = (ignoreCase ? result.indexOfIgnoreCase (i, stringToReplace)
  9173. : result.indexOf (i, stringToReplace))) >= 0)
  9174. {
  9175. result = result.replaceSection (i, stringToReplaceLen, stringToInsert);
  9176. i += stringToInsertLen;
  9177. }
  9178. return result;
  9179. }
  9180. const String String::replaceCharacter (const juce_wchar charToReplace, const juce_wchar charToInsert) const
  9181. {
  9182. const int index = indexOfChar (charToReplace);
  9183. if (index < 0)
  9184. return *this;
  9185. String result (*this, size_t());
  9186. juce_wchar* t = result.text + index;
  9187. while (*t != 0)
  9188. {
  9189. if (*t == charToReplace)
  9190. *t = charToInsert;
  9191. ++t;
  9192. }
  9193. return result;
  9194. }
  9195. const String String::replaceCharacters (const String& charactersToReplace,
  9196. const String& charactersToInsertInstead) const
  9197. {
  9198. String result (*this, size_t());
  9199. juce_wchar* t = result.text;
  9200. const int len2 = charactersToInsertInstead.length();
  9201. // the two strings passed in are supposed to be the same length!
  9202. jassert (len2 == charactersToReplace.length());
  9203. while (*t != 0)
  9204. {
  9205. const int index = charactersToReplace.indexOfChar (*t);
  9206. if (((unsigned int) index) < (unsigned int) len2)
  9207. *t = charactersToInsertInstead [index];
  9208. ++t;
  9209. }
  9210. return result;
  9211. }
  9212. bool String::startsWith (const String& other) const throw()
  9213. {
  9214. return CharacterFunctions::compare (text, other.text, other.length()) == 0;
  9215. }
  9216. bool String::startsWithIgnoreCase (const String& other) const throw()
  9217. {
  9218. return CharacterFunctions::compareIgnoreCase (text, other.text, other.length()) == 0;
  9219. }
  9220. bool String::startsWithChar (const juce_wchar character) const throw()
  9221. {
  9222. jassert (character != 0); // strings can't contain a null character!
  9223. return text[0] == character;
  9224. }
  9225. bool String::endsWithChar (const juce_wchar character) const throw()
  9226. {
  9227. jassert (character != 0); // strings can't contain a null character!
  9228. return text[0] != 0
  9229. && text [length() - 1] == character;
  9230. }
  9231. bool String::endsWith (const String& other) const throw()
  9232. {
  9233. const int thisLen = length();
  9234. const int otherLen = other.length();
  9235. return thisLen >= otherLen
  9236. && CharacterFunctions::compare (text + thisLen - otherLen, other.text) == 0;
  9237. }
  9238. bool String::endsWithIgnoreCase (const String& other) const throw()
  9239. {
  9240. const int thisLen = length();
  9241. const int otherLen = other.length();
  9242. return thisLen >= otherLen
  9243. && CharacterFunctions::compareIgnoreCase (text + thisLen - otherLen, other.text) == 0;
  9244. }
  9245. const String String::toUpperCase() const
  9246. {
  9247. String result (*this, size_t());
  9248. CharacterFunctions::toUpperCase (result.text);
  9249. return result;
  9250. }
  9251. const String String::toLowerCase() const
  9252. {
  9253. String result (*this, size_t());
  9254. CharacterFunctions::toLowerCase (result.text);
  9255. return result;
  9256. }
  9257. juce_wchar& String::operator[] (const int index)
  9258. {
  9259. jassert (((unsigned int) index) <= (unsigned int) length());
  9260. text = StringHolder::makeUnique (text);
  9261. return text [index];
  9262. }
  9263. juce_wchar String::getLastCharacter() const throw()
  9264. {
  9265. return isEmpty() ? juce_wchar() : text [length() - 1];
  9266. }
  9267. const String String::substring (int start, int end) const
  9268. {
  9269. if (start < 0)
  9270. start = 0;
  9271. else if (end <= start)
  9272. return empty;
  9273. int len = 0;
  9274. while (len <= end && text [len] != 0)
  9275. ++len;
  9276. if (end >= len)
  9277. {
  9278. if (start == 0)
  9279. return *this;
  9280. end = len;
  9281. }
  9282. return String (text + start, end - start);
  9283. }
  9284. const String String::substring (const int start) const
  9285. {
  9286. if (start <= 0)
  9287. return *this;
  9288. const int len = length();
  9289. if (start >= len)
  9290. return empty;
  9291. return String (text + start, len - start);
  9292. }
  9293. const String String::dropLastCharacters (const int numberToDrop) const
  9294. {
  9295. return String (text, jmax (0, length() - numberToDrop));
  9296. }
  9297. const String String::getLastCharacters (const int numCharacters) const
  9298. {
  9299. return String (text + jmax (0, length() - jmax (0, numCharacters)));
  9300. }
  9301. const String String::fromFirstOccurrenceOf (const String& sub,
  9302. const bool includeSubString,
  9303. const bool ignoreCase) const
  9304. {
  9305. const int i = ignoreCase ? indexOfIgnoreCase (sub)
  9306. : indexOf (sub);
  9307. if (i < 0)
  9308. return empty;
  9309. return substring (includeSubString ? i : i + sub.length());
  9310. }
  9311. const String String::fromLastOccurrenceOf (const String& sub,
  9312. const bool includeSubString,
  9313. const bool ignoreCase) const
  9314. {
  9315. const int i = ignoreCase ? lastIndexOfIgnoreCase (sub)
  9316. : lastIndexOf (sub);
  9317. if (i < 0)
  9318. return *this;
  9319. return substring (includeSubString ? i : i + sub.length());
  9320. }
  9321. const String String::upToFirstOccurrenceOf (const String& sub,
  9322. const bool includeSubString,
  9323. const bool ignoreCase) const
  9324. {
  9325. const int i = ignoreCase ? indexOfIgnoreCase (sub)
  9326. : indexOf (sub);
  9327. if (i < 0)
  9328. return *this;
  9329. return substring (0, includeSubString ? i + sub.length() : i);
  9330. }
  9331. const String String::upToLastOccurrenceOf (const String& sub,
  9332. const bool includeSubString,
  9333. const bool ignoreCase) const
  9334. {
  9335. const int i = ignoreCase ? lastIndexOfIgnoreCase (sub)
  9336. : lastIndexOf (sub);
  9337. if (i < 0)
  9338. return *this;
  9339. return substring (0, includeSubString ? i + sub.length() : i);
  9340. }
  9341. bool String::isQuotedString() const
  9342. {
  9343. const String trimmed (trimStart());
  9344. return trimmed[0] == '"'
  9345. || trimmed[0] == '\'';
  9346. }
  9347. const String String::unquoted() const
  9348. {
  9349. String s (*this);
  9350. if (s.text[0] == '"' || s.text[0] == '\'')
  9351. s = s.substring (1);
  9352. const int lastCharIndex = s.length() - 1;
  9353. if (lastCharIndex >= 0
  9354. && (s [lastCharIndex] == '"' || s[lastCharIndex] == '\''))
  9355. s [lastCharIndex] = 0;
  9356. return s;
  9357. }
  9358. const String String::quoted (const juce_wchar quoteCharacter) const
  9359. {
  9360. if (isEmpty())
  9361. return charToString (quoteCharacter) + quoteCharacter;
  9362. String t (*this);
  9363. if (! t.startsWithChar (quoteCharacter))
  9364. t = charToString (quoteCharacter) + t;
  9365. if (! t.endsWithChar (quoteCharacter))
  9366. t += quoteCharacter;
  9367. return t;
  9368. }
  9369. const String String::trim() const
  9370. {
  9371. if (isEmpty())
  9372. return empty;
  9373. int start = 0;
  9374. while (CharacterFunctions::isWhitespace (text [start]))
  9375. ++start;
  9376. const int len = length();
  9377. int end = len - 1;
  9378. while ((end >= start) && CharacterFunctions::isWhitespace (text [end]))
  9379. --end;
  9380. ++end;
  9381. if (end <= start)
  9382. return empty;
  9383. else if (start > 0 || end < len)
  9384. return String (text + start, end - start);
  9385. return *this;
  9386. }
  9387. const String String::trimStart() const
  9388. {
  9389. if (isEmpty())
  9390. return empty;
  9391. const juce_wchar* t = text;
  9392. while (CharacterFunctions::isWhitespace (*t))
  9393. ++t;
  9394. if (t == text)
  9395. return *this;
  9396. return String (t);
  9397. }
  9398. const String String::trimEnd() const
  9399. {
  9400. if (isEmpty())
  9401. return empty;
  9402. const juce_wchar* endT = text + (length() - 1);
  9403. while ((endT >= text) && CharacterFunctions::isWhitespace (*endT))
  9404. --endT;
  9405. return String (text, (int) (++endT - text));
  9406. }
  9407. const String String::trimCharactersAtStart (const String& charactersToTrim) const
  9408. {
  9409. const juce_wchar* t = text;
  9410. while (charactersToTrim.containsChar (*t))
  9411. ++t;
  9412. return t == text ? *this : String (t);
  9413. }
  9414. const String String::trimCharactersAtEnd (const String& charactersToTrim) const
  9415. {
  9416. if (isEmpty())
  9417. return empty;
  9418. const int len = length();
  9419. const juce_wchar* endT = text + (len - 1);
  9420. int numToRemove = 0;
  9421. while (numToRemove < len && charactersToTrim.containsChar (*endT))
  9422. {
  9423. ++numToRemove;
  9424. --endT;
  9425. }
  9426. return numToRemove > 0 ? String (text, len - numToRemove) : *this;
  9427. }
  9428. const String String::retainCharacters (const String& charactersToRetain) const
  9429. {
  9430. if (isEmpty())
  9431. return empty;
  9432. String result (StringHolder::getAllocatedNumChars (text), (int) 0);
  9433. juce_wchar* dst = result.text;
  9434. const juce_wchar* src = text;
  9435. while (*src != 0)
  9436. {
  9437. if (charactersToRetain.containsChar (*src))
  9438. *dst++ = *src;
  9439. ++src;
  9440. }
  9441. *dst = 0;
  9442. return result;
  9443. }
  9444. const String String::removeCharacters (const String& charactersToRemove) const
  9445. {
  9446. if (isEmpty())
  9447. return empty;
  9448. String result (StringHolder::getAllocatedNumChars (text), (int) 0);
  9449. juce_wchar* dst = result.text;
  9450. const juce_wchar* src = text;
  9451. while (*src != 0)
  9452. {
  9453. if (! charactersToRemove.containsChar (*src))
  9454. *dst++ = *src;
  9455. ++src;
  9456. }
  9457. *dst = 0;
  9458. return result;
  9459. }
  9460. const String String::initialSectionContainingOnly (const String& permittedCharacters) const
  9461. {
  9462. int i = 0;
  9463. for (;;)
  9464. {
  9465. if (! permittedCharacters.containsChar (text[i]))
  9466. break;
  9467. ++i;
  9468. }
  9469. return substring (0, i);
  9470. }
  9471. const String String::initialSectionNotContaining (const String& charactersToStopAt) const
  9472. {
  9473. const juce_wchar* const t = text;
  9474. int i = 0;
  9475. while (t[i] != 0)
  9476. {
  9477. if (charactersToStopAt.containsChar (t[i]))
  9478. return String (text, i);
  9479. ++i;
  9480. }
  9481. return empty;
  9482. }
  9483. bool String::containsOnly (const String& chars) const throw()
  9484. {
  9485. const juce_wchar* t = text;
  9486. while (*t != 0)
  9487. if (! chars.containsChar (*t++))
  9488. return false;
  9489. return true;
  9490. }
  9491. bool String::containsAnyOf (const String& chars) const throw()
  9492. {
  9493. const juce_wchar* t = text;
  9494. while (*t != 0)
  9495. if (chars.containsChar (*t++))
  9496. return true;
  9497. return false;
  9498. }
  9499. bool String::containsNonWhitespaceChars() const throw()
  9500. {
  9501. const juce_wchar* t = text;
  9502. while (*t != 0)
  9503. if (! CharacterFunctions::isWhitespace (*t++))
  9504. return true;
  9505. return false;
  9506. }
  9507. const String String::formatted (const juce_wchar* const pf, ... )
  9508. {
  9509. jassert (pf != 0);
  9510. va_list args;
  9511. va_start (args, pf);
  9512. size_t bufferSize = 256;
  9513. String result (bufferSize, (int) 0);
  9514. result.text[0] = 0;
  9515. for (;;)
  9516. {
  9517. #if JUCE_LINUX && JUCE_64BIT
  9518. va_list tempArgs;
  9519. va_copy (tempArgs, args);
  9520. const int num = (int) vswprintf (result.text, bufferSize - 1, pf, tempArgs);
  9521. va_end (tempArgs);
  9522. #elif JUCE_WINDOWS
  9523. #ifdef _MSC_VER
  9524. #pragma warning (push)
  9525. #pragma warning (disable: 4996)
  9526. #endif
  9527. const int num = (int) _vsnwprintf (result.text, bufferSize - 1, pf, args);
  9528. #ifdef _MSC_VER
  9529. #pragma warning (pop)
  9530. #endif
  9531. #else
  9532. const int num = (int) vswprintf (result.text, bufferSize - 1, pf, args);
  9533. #endif
  9534. if (num > 0)
  9535. return result;
  9536. bufferSize += 256;
  9537. if (num == 0 || bufferSize > 65536) // the upper limit is a sanity check to avoid situations where vprintf repeatedly
  9538. break; // returns -1 because of an error rather than because it needs more space.
  9539. result.preallocateStorage (bufferSize);
  9540. }
  9541. return empty;
  9542. }
  9543. int String::getIntValue() const throw()
  9544. {
  9545. return CharacterFunctions::getIntValue (text);
  9546. }
  9547. int String::getTrailingIntValue() const throw()
  9548. {
  9549. int n = 0;
  9550. int mult = 1;
  9551. const juce_wchar* t = text + length();
  9552. while (--t >= text)
  9553. {
  9554. const juce_wchar c = *t;
  9555. if (! CharacterFunctions::isDigit (c))
  9556. {
  9557. if (c == '-')
  9558. n = -n;
  9559. break;
  9560. }
  9561. n += mult * (c - '0');
  9562. mult *= 10;
  9563. }
  9564. return n;
  9565. }
  9566. int64 String::getLargeIntValue() const throw()
  9567. {
  9568. return CharacterFunctions::getInt64Value (text);
  9569. }
  9570. float String::getFloatValue() const throw()
  9571. {
  9572. return (float) CharacterFunctions::getDoubleValue (text);
  9573. }
  9574. double String::getDoubleValue() const throw()
  9575. {
  9576. return CharacterFunctions::getDoubleValue (text);
  9577. }
  9578. static const juce_wchar* const hexDigits = T("0123456789abcdef");
  9579. const String String::toHexString (const int number)
  9580. {
  9581. juce_wchar buffer[32];
  9582. juce_wchar* const end = buffer + 32;
  9583. juce_wchar* t = end;
  9584. *--t = 0;
  9585. unsigned int v = (unsigned int) number;
  9586. do
  9587. {
  9588. *--t = hexDigits [v & 15];
  9589. v >>= 4;
  9590. } while (v != 0);
  9591. return String (t, (int) (((char*) end) - (char*) t) - 1);
  9592. }
  9593. const String String::toHexString (const int64 number)
  9594. {
  9595. juce_wchar buffer[32];
  9596. juce_wchar* const end = buffer + 32;
  9597. juce_wchar* t = end;
  9598. *--t = 0;
  9599. uint64 v = (uint64) number;
  9600. do
  9601. {
  9602. *--t = hexDigits [(int) (v & 15)];
  9603. v >>= 4;
  9604. } while (v != 0);
  9605. return String (t, (int) (((char*) end) - (char*) t));
  9606. }
  9607. const String String::toHexString (const short number)
  9608. {
  9609. return toHexString ((int) (unsigned short) number);
  9610. }
  9611. const String String::toHexString (const unsigned char* data,
  9612. const int size,
  9613. const int groupSize)
  9614. {
  9615. if (size <= 0)
  9616. return empty;
  9617. int numChars = (size * 2) + 2;
  9618. if (groupSize > 0)
  9619. numChars += size / groupSize;
  9620. String s ((size_t) numChars, (int) 0);
  9621. juce_wchar* d = s.text;
  9622. for (int i = 0; i < size; ++i)
  9623. {
  9624. *d++ = hexDigits [(*data) >> 4];
  9625. *d++ = hexDigits [(*data) & 0xf];
  9626. ++data;
  9627. if (groupSize > 0 && (i % groupSize) == (groupSize - 1) && i < (size - 1))
  9628. *d++ = ' ';
  9629. }
  9630. *d = 0;
  9631. return s;
  9632. }
  9633. int String::getHexValue32() const throw()
  9634. {
  9635. int result = 0;
  9636. const juce_wchar* c = text;
  9637. for (;;)
  9638. {
  9639. const int hexValue = CharacterFunctions::getHexDigitValue (*c);
  9640. if (hexValue >= 0)
  9641. result = (result << 4) | hexValue;
  9642. else if (*c == 0)
  9643. break;
  9644. ++c;
  9645. }
  9646. return result;
  9647. }
  9648. int64 String::getHexValue64() const throw()
  9649. {
  9650. int64 result = 0;
  9651. const juce_wchar* c = text;
  9652. for (;;)
  9653. {
  9654. const int hexValue = CharacterFunctions::getHexDigitValue (*c);
  9655. if (hexValue >= 0)
  9656. result = (result << 4) | hexValue;
  9657. else if (*c == 0)
  9658. break;
  9659. ++c;
  9660. }
  9661. return result;
  9662. }
  9663. const String String::createStringFromData (const void* const data_, const int size)
  9664. {
  9665. const char* const data = static_cast <const char*> (data_);
  9666. if (size <= 0 || data == 0)
  9667. {
  9668. return empty;
  9669. }
  9670. else if (size < 2)
  9671. {
  9672. return charToString (data[0]);
  9673. }
  9674. else if ((data[0] == (char)-2 && data[1] == (char)-1)
  9675. || (data[0] == (char)-1 && data[1] == (char)-2))
  9676. {
  9677. // assume it's 16-bit unicode
  9678. const bool bigEndian = (data[0] == (char)-2);
  9679. const int numChars = size / 2 - 1;
  9680. String result;
  9681. result.preallocateStorage (numChars + 2);
  9682. const uint16* const src = (const uint16*) (data + 2);
  9683. juce_wchar* const dst = const_cast <juce_wchar*> (static_cast <const juce_wchar*> (result));
  9684. if (bigEndian)
  9685. {
  9686. for (int i = 0; i < numChars; ++i)
  9687. dst[i] = (juce_wchar) ByteOrder::swapIfLittleEndian (src[i]);
  9688. }
  9689. else
  9690. {
  9691. for (int i = 0; i < numChars; ++i)
  9692. dst[i] = (juce_wchar) ByteOrder::swapIfBigEndian (src[i]);
  9693. }
  9694. dst [numChars] = 0;
  9695. return result;
  9696. }
  9697. else
  9698. {
  9699. return String::fromUTF8 (data, size);
  9700. }
  9701. }
  9702. const char* String::toUTF8() const
  9703. {
  9704. if (isEmpty())
  9705. {
  9706. return reinterpret_cast <const char*> (text);
  9707. }
  9708. else
  9709. {
  9710. const int currentLen = length() + 1;
  9711. const int utf8BytesNeeded = getNumBytesAsUTF8();
  9712. String* const mutableThis = const_cast <String*> (this);
  9713. mutableThis->text = StringHolder::makeUniqueWithSize (mutableThis->text, currentLen + 1 + utf8BytesNeeded / sizeof (juce_wchar));
  9714. char* const otherCopy = reinterpret_cast <char*> (mutableThis->text + currentLen);
  9715. copyToUTF8 (otherCopy, std::numeric_limits<int>::max());
  9716. return otherCopy;
  9717. }
  9718. }
  9719. int String::copyToUTF8 (char* const buffer, const int maxBufferSizeBytes) const throw()
  9720. {
  9721. jassert (maxBufferSizeBytes >= 0); // keep this value positive, or no characters will be copied!
  9722. int num = 0, index = 0;
  9723. for (;;)
  9724. {
  9725. const uint32 c = (uint32) text [index++];
  9726. if (c >= 0x80)
  9727. {
  9728. int numExtraBytes = 1;
  9729. if (c >= 0x800)
  9730. {
  9731. ++numExtraBytes;
  9732. if (c >= 0x10000)
  9733. {
  9734. ++numExtraBytes;
  9735. if (c >= 0x200000)
  9736. {
  9737. ++numExtraBytes;
  9738. if (c >= 0x4000000)
  9739. ++numExtraBytes;
  9740. }
  9741. }
  9742. }
  9743. if (buffer != 0)
  9744. {
  9745. if (num + numExtraBytes >= maxBufferSizeBytes)
  9746. {
  9747. buffer [num++] = 0;
  9748. break;
  9749. }
  9750. else
  9751. {
  9752. buffer [num++] = (uint8) ((0xff << (7 - numExtraBytes)) | (c >> (numExtraBytes * 6)));
  9753. while (--numExtraBytes >= 0)
  9754. buffer [num++] = (uint8) (0x80 | (0x3f & (c >> (numExtraBytes * 6))));
  9755. }
  9756. }
  9757. else
  9758. {
  9759. num += numExtraBytes + 1;
  9760. }
  9761. }
  9762. else
  9763. {
  9764. if (buffer != 0)
  9765. {
  9766. if (num + 1 >= maxBufferSizeBytes)
  9767. {
  9768. buffer [num++] = 0;
  9769. break;
  9770. }
  9771. buffer [num] = (uint8) c;
  9772. }
  9773. ++num;
  9774. }
  9775. if (c == 0)
  9776. break;
  9777. }
  9778. return num;
  9779. }
  9780. int String::getNumBytesAsUTF8() const throw()
  9781. {
  9782. int num = 0;
  9783. const juce_wchar* t = text;
  9784. for (;;)
  9785. {
  9786. const uint32 c = (uint32) *t;
  9787. if (c >= 0x80)
  9788. {
  9789. ++num;
  9790. if (c >= 0x800)
  9791. {
  9792. ++num;
  9793. if (c >= 0x10000)
  9794. {
  9795. ++num;
  9796. if (c >= 0x200000)
  9797. {
  9798. ++num;
  9799. if (c >= 0x4000000)
  9800. ++num;
  9801. }
  9802. }
  9803. }
  9804. }
  9805. else if (c == 0)
  9806. break;
  9807. ++num;
  9808. ++t;
  9809. }
  9810. return num;
  9811. }
  9812. const String String::fromUTF8 (const char* const buffer, int bufferSizeBytes)
  9813. {
  9814. if (buffer == 0)
  9815. return empty;
  9816. if (bufferSizeBytes < 0)
  9817. bufferSizeBytes = std::numeric_limits<int>::max();
  9818. size_t numBytes;
  9819. for (numBytes = 0; numBytes < (size_t) bufferSizeBytes; ++numBytes)
  9820. if (buffer [numBytes] == 0)
  9821. break;
  9822. String result ((size_t) numBytes + 1, (int) 0);
  9823. juce_wchar* dest = result.text;
  9824. size_t i = 0;
  9825. while (i < numBytes)
  9826. {
  9827. const char c = buffer [i++];
  9828. if (c < 0)
  9829. {
  9830. unsigned int mask = 0x7f;
  9831. int bit = 0x40;
  9832. int numExtraValues = 0;
  9833. while (bit != 0 && (c & bit) != 0)
  9834. {
  9835. bit >>= 1;
  9836. mask >>= 1;
  9837. ++numExtraValues;
  9838. }
  9839. int n = (mask & (unsigned char) c);
  9840. while (--numExtraValues >= 0 && i < (size_t) bufferSizeBytes)
  9841. {
  9842. const char nextByte = buffer[i];
  9843. if ((nextByte & 0xc0) != 0x80)
  9844. break;
  9845. n <<= 6;
  9846. n |= (nextByte & 0x3f);
  9847. ++i;
  9848. }
  9849. *dest++ = (juce_wchar) n;
  9850. }
  9851. else
  9852. {
  9853. *dest++ = (juce_wchar) c;
  9854. }
  9855. }
  9856. *dest = 0;
  9857. return result;
  9858. }
  9859. const char* String::toCString() const
  9860. {
  9861. if (isEmpty())
  9862. {
  9863. return reinterpret_cast <const char*> (text);
  9864. }
  9865. else
  9866. {
  9867. const int len = length();
  9868. String* const mutableThis = const_cast <String*> (this);
  9869. mutableThis->text = StringHolder::makeUniqueWithSize (mutableThis->text, (len + 1) * 2);
  9870. char* otherCopy = reinterpret_cast <char*> (mutableThis->text + len + 1);
  9871. CharacterFunctions::copy (otherCopy, text, len);
  9872. otherCopy [len] = 0;
  9873. return otherCopy;
  9874. }
  9875. }
  9876. #ifdef _MSC_VER
  9877. #pragma warning (disable: 4514 4996)
  9878. #pragma warning (push)
  9879. #endif
  9880. int String::getNumBytesAsCString() const throw()
  9881. {
  9882. return (int) wcstombs (0, text, 0);
  9883. }
  9884. int String::copyToCString (char* destBuffer, const int maxBufferSizeBytes) const throw()
  9885. {
  9886. const int numBytes = (int) wcstombs (destBuffer, text, maxBufferSizeBytes);
  9887. if (destBuffer != 0 && numBytes >= 0)
  9888. destBuffer [numBytes] = 0;
  9889. return numBytes;
  9890. }
  9891. #ifdef _MSC_VER
  9892. #pragma warning (pop)
  9893. #endif
  9894. void String::copyToUnicode (juce_wchar* const destBuffer, const int maxCharsToCopy) const throw()
  9895. {
  9896. StringHolder::copyChars (destBuffer, text, jmin (maxCharsToCopy, length()));
  9897. }
  9898. String::Concatenator::Concatenator (String& stringToAppendTo)
  9899. : result (stringToAppendTo),
  9900. nextIndex (stringToAppendTo.length())
  9901. {
  9902. }
  9903. String::Concatenator::~Concatenator()
  9904. {
  9905. }
  9906. void String::Concatenator::append (const String& s)
  9907. {
  9908. const int len = s.length();
  9909. if (len > 0)
  9910. {
  9911. result.preallocateStorage (nextIndex + len);
  9912. s.copyToUnicode (static_cast <juce_wchar*> (result) + nextIndex, len);
  9913. nextIndex += len;
  9914. }
  9915. }
  9916. END_JUCE_NAMESPACE
  9917. /*** End of inlined file: juce_String.cpp ***/
  9918. /*** Start of inlined file: juce_StringArray.cpp ***/
  9919. BEGIN_JUCE_NAMESPACE
  9920. StringArray::StringArray() throw()
  9921. {
  9922. }
  9923. StringArray::StringArray (const StringArray& other)
  9924. : strings (other.strings)
  9925. {
  9926. }
  9927. StringArray::StringArray (const String& firstValue)
  9928. {
  9929. strings.add (firstValue);
  9930. }
  9931. StringArray::StringArray (const juce_wchar** const initialStrings,
  9932. const int numberOfStrings)
  9933. {
  9934. for (int i = 0; i < numberOfStrings; ++i)
  9935. strings.add (initialStrings [i]);
  9936. }
  9937. StringArray::StringArray (const char** const initialStrings,
  9938. const int numberOfStrings)
  9939. {
  9940. for (int i = 0; i < numberOfStrings; ++i)
  9941. strings.add (initialStrings [i]);
  9942. }
  9943. StringArray::StringArray (const juce_wchar** const initialStrings)
  9944. {
  9945. int i = 0;
  9946. while (initialStrings[i] != 0)
  9947. strings.add (initialStrings [i++]);
  9948. }
  9949. StringArray::StringArray (const char** const initialStrings)
  9950. {
  9951. int i = 0;
  9952. while (initialStrings[i] != 0)
  9953. strings.add (initialStrings [i++]);
  9954. }
  9955. StringArray& StringArray::operator= (const StringArray& other)
  9956. {
  9957. strings = other.strings;
  9958. return *this;
  9959. }
  9960. StringArray::~StringArray()
  9961. {
  9962. }
  9963. bool StringArray::operator== (const StringArray& other) const throw()
  9964. {
  9965. if (other.size() != size())
  9966. return false;
  9967. for (int i = size(); --i >= 0;)
  9968. if (other.strings.getReference(i) != strings.getReference(i))
  9969. return false;
  9970. return true;
  9971. }
  9972. bool StringArray::operator!= (const StringArray& other) const throw()
  9973. {
  9974. return ! operator== (other);
  9975. }
  9976. void StringArray::clear()
  9977. {
  9978. strings.clear();
  9979. }
  9980. const String& StringArray::operator[] (const int index) const throw()
  9981. {
  9982. if (((unsigned int) index) < (unsigned int) strings.size())
  9983. return strings.getReference (index);
  9984. return String::empty;
  9985. }
  9986. String& StringArray::getReference (const int index) throw()
  9987. {
  9988. jassert (((unsigned int) index) < (unsigned int) strings.size());
  9989. return strings.getReference (index);
  9990. }
  9991. void StringArray::add (const String& newString)
  9992. {
  9993. strings.add (newString);
  9994. }
  9995. void StringArray::insert (const int index, const String& newString)
  9996. {
  9997. strings.insert (index, newString);
  9998. }
  9999. void StringArray::addIfNotAlreadyThere (const String& newString, const bool ignoreCase)
  10000. {
  10001. if (! contains (newString, ignoreCase))
  10002. add (newString);
  10003. }
  10004. void StringArray::addArray (const StringArray& otherArray, int startIndex, int numElementsToAdd)
  10005. {
  10006. if (startIndex < 0)
  10007. {
  10008. jassertfalse
  10009. startIndex = 0;
  10010. }
  10011. if (numElementsToAdd < 0 || startIndex + numElementsToAdd > otherArray.size())
  10012. numElementsToAdd = otherArray.size() - startIndex;
  10013. while (--numElementsToAdd >= 0)
  10014. strings.add (otherArray.strings.getReference (startIndex++));
  10015. }
  10016. void StringArray::set (const int index, const String& newString)
  10017. {
  10018. strings.set (index, newString);
  10019. }
  10020. bool StringArray::contains (const String& stringToLookFor, const bool ignoreCase) const
  10021. {
  10022. if (ignoreCase)
  10023. {
  10024. for (int i = size(); --i >= 0;)
  10025. if (strings.getReference(i).equalsIgnoreCase (stringToLookFor))
  10026. return true;
  10027. }
  10028. else
  10029. {
  10030. for (int i = size(); --i >= 0;)
  10031. if (stringToLookFor == strings.getReference(i))
  10032. return true;
  10033. }
  10034. return false;
  10035. }
  10036. int StringArray::indexOf (const String& stringToLookFor, const bool ignoreCase, int i) const
  10037. {
  10038. if (i < 0)
  10039. i = 0;
  10040. const int numElements = size();
  10041. if (ignoreCase)
  10042. {
  10043. while (i < numElements)
  10044. {
  10045. if (strings.getReference(i).equalsIgnoreCase (stringToLookFor))
  10046. return i;
  10047. ++i;
  10048. }
  10049. }
  10050. else
  10051. {
  10052. while (i < numElements)
  10053. {
  10054. if (stringToLookFor == strings.getReference (i))
  10055. return i;
  10056. ++i;
  10057. }
  10058. }
  10059. return -1;
  10060. }
  10061. void StringArray::remove (const int index)
  10062. {
  10063. strings.remove (index);
  10064. }
  10065. void StringArray::removeString (const String& stringToRemove,
  10066. const bool ignoreCase)
  10067. {
  10068. if (ignoreCase)
  10069. {
  10070. for (int i = size(); --i >= 0;)
  10071. if (strings.getReference(i).equalsIgnoreCase (stringToRemove))
  10072. strings.remove (i);
  10073. }
  10074. else
  10075. {
  10076. for (int i = size(); --i >= 0;)
  10077. if (stringToRemove == strings.getReference (i))
  10078. strings.remove (i);
  10079. }
  10080. }
  10081. void StringArray::removeRange (int startIndex, int numberToRemove)
  10082. {
  10083. strings.removeRange (startIndex, numberToRemove);
  10084. }
  10085. void StringArray::removeEmptyStrings (const bool removeWhitespaceStrings)
  10086. {
  10087. if (removeWhitespaceStrings)
  10088. {
  10089. for (int i = size(); --i >= 0;)
  10090. if (! strings.getReference(i).containsNonWhitespaceChars())
  10091. strings.remove (i);
  10092. }
  10093. else
  10094. {
  10095. for (int i = size(); --i >= 0;)
  10096. if (strings.getReference(i).isEmpty())
  10097. strings.remove (i);
  10098. }
  10099. }
  10100. void StringArray::trim()
  10101. {
  10102. for (int i = size(); --i >= 0;)
  10103. {
  10104. String& s = strings.getReference(i);
  10105. s = s.trim();
  10106. }
  10107. }
  10108. class InternalStringArrayComparator_CaseSensitive
  10109. {
  10110. public:
  10111. static int compareElements (String& first, String& second) { return first.compare (second); }
  10112. };
  10113. class InternalStringArrayComparator_CaseInsensitive
  10114. {
  10115. public:
  10116. static int compareElements (String& first, String& second) { return first.compareIgnoreCase (second); }
  10117. };
  10118. void StringArray::sort (const bool ignoreCase)
  10119. {
  10120. if (ignoreCase)
  10121. {
  10122. InternalStringArrayComparator_CaseInsensitive comp;
  10123. strings.sort (comp);
  10124. }
  10125. else
  10126. {
  10127. InternalStringArrayComparator_CaseSensitive comp;
  10128. strings.sort (comp);
  10129. }
  10130. }
  10131. void StringArray::move (const int currentIndex, int newIndex) throw()
  10132. {
  10133. strings.move (currentIndex, newIndex);
  10134. }
  10135. const String StringArray::joinIntoString (const String& separator, int start, int numberToJoin) const
  10136. {
  10137. const int last = (numberToJoin < 0) ? size()
  10138. : jmin (size(), start + numberToJoin);
  10139. if (start < 0)
  10140. start = 0;
  10141. if (start >= last)
  10142. return String::empty;
  10143. if (start == last - 1)
  10144. return strings.getReference (start);
  10145. const int separatorLen = separator.length();
  10146. int charsNeeded = separatorLen * (last - start - 1);
  10147. for (int i = start; i < last; ++i)
  10148. charsNeeded += strings.getReference(i).length();
  10149. String result;
  10150. result.preallocateStorage (charsNeeded);
  10151. juce_wchar* dest = result;
  10152. while (start < last)
  10153. {
  10154. const String& s = strings.getReference (start);
  10155. const int len = s.length();
  10156. if (len > 0)
  10157. {
  10158. s.copyToUnicode (dest, len);
  10159. dest += len;
  10160. }
  10161. if (++start < last && separatorLen > 0)
  10162. {
  10163. separator.copyToUnicode (dest, separatorLen);
  10164. dest += separatorLen;
  10165. }
  10166. }
  10167. *dest = 0;
  10168. return result;
  10169. }
  10170. int StringArray::addTokens (const String& text, const bool preserveQuotedStrings)
  10171. {
  10172. return addTokens (text, " \n\r\t", preserveQuotedStrings ? "\"" : "");
  10173. }
  10174. int StringArray::addTokens (const String& text, const String& breakCharacters, const String& quoteCharacters)
  10175. {
  10176. int num = 0;
  10177. if (text.isNotEmpty())
  10178. {
  10179. bool insideQuotes = false;
  10180. juce_wchar currentQuoteChar = 0;
  10181. int i = 0;
  10182. int tokenStart = 0;
  10183. for (;;)
  10184. {
  10185. const juce_wchar c = text[i];
  10186. const bool isBreak = (c == 0) || ((! insideQuotes) && breakCharacters.containsChar (c));
  10187. if (! isBreak)
  10188. {
  10189. if (quoteCharacters.containsChar (c))
  10190. {
  10191. if (insideQuotes)
  10192. {
  10193. // only break out of quotes-mode if we find a matching quote to the
  10194. // one that we opened with..
  10195. if (currentQuoteChar == c)
  10196. insideQuotes = false;
  10197. }
  10198. else
  10199. {
  10200. insideQuotes = true;
  10201. currentQuoteChar = c;
  10202. }
  10203. }
  10204. }
  10205. else
  10206. {
  10207. add (String (static_cast <const juce_wchar*> (text) + tokenStart, i - tokenStart));
  10208. ++num;
  10209. tokenStart = i + 1;
  10210. }
  10211. if (c == 0)
  10212. break;
  10213. ++i;
  10214. }
  10215. }
  10216. return num;
  10217. }
  10218. int StringArray::addLines (const String& sourceText)
  10219. {
  10220. int numLines = 0;
  10221. const juce_wchar* text = sourceText;
  10222. while (*text != 0)
  10223. {
  10224. const juce_wchar* const startOfLine = text;
  10225. while (*text != 0)
  10226. {
  10227. if (*text == '\r')
  10228. {
  10229. ++text;
  10230. if (*text == '\n')
  10231. ++text;
  10232. break;
  10233. }
  10234. if (*text == '\n')
  10235. {
  10236. ++text;
  10237. break;
  10238. }
  10239. ++text;
  10240. }
  10241. const juce_wchar* endOfLine = text;
  10242. if (endOfLine > startOfLine && (*(endOfLine - 1) == '\r' || *(endOfLine - 1) == '\n'))
  10243. --endOfLine;
  10244. if (endOfLine > startOfLine && (*(endOfLine - 1) == '\r' || *(endOfLine - 1) == '\n'))
  10245. --endOfLine;
  10246. add (String (startOfLine, jmax (0, (int) (endOfLine - startOfLine))));
  10247. ++numLines;
  10248. }
  10249. return numLines;
  10250. }
  10251. void StringArray::removeDuplicates (const bool ignoreCase)
  10252. {
  10253. for (int i = 0; i < size() - 1; ++i)
  10254. {
  10255. const String s (strings.getReference(i));
  10256. int nextIndex = i + 1;
  10257. for (;;)
  10258. {
  10259. nextIndex = indexOf (s, ignoreCase, nextIndex);
  10260. if (nextIndex < 0)
  10261. break;
  10262. strings.remove (nextIndex);
  10263. }
  10264. }
  10265. }
  10266. void StringArray::appendNumbersToDuplicates (const bool ignoreCase,
  10267. const bool appendNumberToFirstInstance,
  10268. const juce_wchar* preNumberString,
  10269. const juce_wchar* postNumberString)
  10270. {
  10271. if (preNumberString == 0)
  10272. preNumberString = L" (";
  10273. if (postNumberString == 0)
  10274. postNumberString = L")";
  10275. for (int i = 0; i < size() - 1; ++i)
  10276. {
  10277. String& s = strings.getReference(i);
  10278. int nextIndex = indexOf (s, ignoreCase, i + 1);
  10279. if (nextIndex >= 0)
  10280. {
  10281. const String original (s);
  10282. int number = 0;
  10283. if (appendNumberToFirstInstance)
  10284. s = original + preNumberString + String (++number) + postNumberString;
  10285. else
  10286. ++number;
  10287. while (nextIndex >= 0)
  10288. {
  10289. set (nextIndex, (*this)[nextIndex] + preNumberString + String (++number) + postNumberString);
  10290. nextIndex = indexOf (original, ignoreCase, nextIndex + 1);
  10291. }
  10292. }
  10293. }
  10294. }
  10295. void StringArray::minimiseStorageOverheads()
  10296. {
  10297. strings.minimiseStorageOverheads();
  10298. }
  10299. END_JUCE_NAMESPACE
  10300. /*** End of inlined file: juce_StringArray.cpp ***/
  10301. /*** Start of inlined file: juce_StringPairArray.cpp ***/
  10302. BEGIN_JUCE_NAMESPACE
  10303. StringPairArray::StringPairArray (const bool ignoreCase_)
  10304. : ignoreCase (ignoreCase_)
  10305. {
  10306. }
  10307. StringPairArray::StringPairArray (const StringPairArray& other)
  10308. : keys (other.keys),
  10309. values (other.values),
  10310. ignoreCase (other.ignoreCase)
  10311. {
  10312. }
  10313. StringPairArray::~StringPairArray()
  10314. {
  10315. }
  10316. StringPairArray& StringPairArray::operator= (const StringPairArray& other)
  10317. {
  10318. keys = other.keys;
  10319. values = other.values;
  10320. return *this;
  10321. }
  10322. bool StringPairArray::operator== (const StringPairArray& other) const
  10323. {
  10324. for (int i = keys.size(); --i >= 0;)
  10325. if (other [keys[i]] != values[i])
  10326. return false;
  10327. return true;
  10328. }
  10329. bool StringPairArray::operator!= (const StringPairArray& other) const
  10330. {
  10331. return ! operator== (other);
  10332. }
  10333. const String& StringPairArray::operator[] (const String& key) const
  10334. {
  10335. return values [keys.indexOf (key, ignoreCase)];
  10336. }
  10337. const String StringPairArray::getValue (const String& key, const String& defaultReturnValue) const
  10338. {
  10339. const int i = keys.indexOf (key, ignoreCase);
  10340. if (i >= 0)
  10341. return values[i];
  10342. return defaultReturnValue;
  10343. }
  10344. void StringPairArray::set (const String& key, const String& value)
  10345. {
  10346. const int i = keys.indexOf (key, ignoreCase);
  10347. if (i >= 0)
  10348. {
  10349. values.set (i, value);
  10350. }
  10351. else
  10352. {
  10353. keys.add (key);
  10354. values.add (value);
  10355. }
  10356. }
  10357. void StringPairArray::addArray (const StringPairArray& other)
  10358. {
  10359. for (int i = 0; i < other.size(); ++i)
  10360. set (other.keys[i], other.values[i]);
  10361. }
  10362. void StringPairArray::clear()
  10363. {
  10364. keys.clear();
  10365. values.clear();
  10366. }
  10367. void StringPairArray::remove (const String& key)
  10368. {
  10369. remove (keys.indexOf (key, ignoreCase));
  10370. }
  10371. void StringPairArray::remove (const int index)
  10372. {
  10373. keys.remove (index);
  10374. values.remove (index);
  10375. }
  10376. void StringPairArray::setIgnoresCase (const bool shouldIgnoreCase)
  10377. {
  10378. ignoreCase = shouldIgnoreCase;
  10379. }
  10380. const String StringPairArray::getDescription() const
  10381. {
  10382. String s;
  10383. for (int i = 0; i < keys.size(); ++i)
  10384. {
  10385. s << keys[i] << " = " << values[i];
  10386. if (i < keys.size())
  10387. s << ", ";
  10388. }
  10389. return s;
  10390. }
  10391. void StringPairArray::minimiseStorageOverheads()
  10392. {
  10393. keys.minimiseStorageOverheads();
  10394. values.minimiseStorageOverheads();
  10395. }
  10396. END_JUCE_NAMESPACE
  10397. /*** End of inlined file: juce_StringPairArray.cpp ***/
  10398. /*** Start of inlined file: juce_XmlDocument.cpp ***/
  10399. BEGIN_JUCE_NAMESPACE
  10400. XmlDocument::XmlDocument (const String& documentText)
  10401. : originalText (documentText),
  10402. ignoreEmptyTextElements (true)
  10403. {
  10404. }
  10405. XmlDocument::XmlDocument (const File& file)
  10406. : ignoreEmptyTextElements (true)
  10407. {
  10408. inputSource = new FileInputSource (file);
  10409. }
  10410. XmlDocument::~XmlDocument()
  10411. {
  10412. }
  10413. void XmlDocument::setInputSource (InputSource* const newSource) throw()
  10414. {
  10415. inputSource = newSource;
  10416. }
  10417. void XmlDocument::setEmptyTextElementsIgnored (const bool shouldBeIgnored) throw()
  10418. {
  10419. ignoreEmptyTextElements = shouldBeIgnored;
  10420. }
  10421. bool XmlDocument::isXmlIdentifierCharSlow (const juce_wchar c) throw()
  10422. {
  10423. return CharacterFunctions::isLetterOrDigit (c)
  10424. || c == '_' || c == '-' || c == ':' || c == '.';
  10425. }
  10426. inline bool XmlDocument::isXmlIdentifierChar (const juce_wchar c) const throw()
  10427. {
  10428. return (c > 0 && c <= 127) ? identifierLookupTable [(int) c]
  10429. : isXmlIdentifierCharSlow (c);
  10430. }
  10431. XmlElement* XmlDocument::getDocumentElement (const bool onlyReadOuterDocumentElement)
  10432. {
  10433. String textToParse (originalText);
  10434. if (textToParse.isEmpty() && inputSource != 0)
  10435. {
  10436. ScopedPointer <InputStream> in (inputSource->createInputStream());
  10437. if (in != 0)
  10438. {
  10439. MemoryBlock data;
  10440. in->readIntoMemoryBlock (data, onlyReadOuterDocumentElement ? 8192 : -1);
  10441. if (data.getSize() >= 2
  10442. && ((data[0] == (char)-2 && data[1] == (char)-1)
  10443. || (data[0] == (char)-1 && data[1] == (char)-2)))
  10444. {
  10445. textToParse = String::createStringFromData (static_cast <const char*> (data.getData()), (int) data.getSize());
  10446. }
  10447. else
  10448. {
  10449. textToParse = String::fromUTF8 (static_cast <const char*> (data.getData()), (int) data.getSize());
  10450. }
  10451. if (! onlyReadOuterDocumentElement)
  10452. originalText = textToParse;
  10453. }
  10454. }
  10455. input = textToParse;
  10456. lastError = String::empty;
  10457. errorOccurred = false;
  10458. outOfData = false;
  10459. needToLoadDTD = true;
  10460. for (int i = 0; i < 128; ++i)
  10461. identifierLookupTable[i] = isXmlIdentifierCharSlow ((juce_wchar) i);
  10462. if (textToParse.isEmpty())
  10463. {
  10464. lastError = "not enough input";
  10465. }
  10466. else
  10467. {
  10468. skipHeader();
  10469. if (input != 0)
  10470. {
  10471. ScopedPointer <XmlElement> result (readNextElement (! onlyReadOuterDocumentElement));
  10472. if (! errorOccurred)
  10473. return result.release();
  10474. }
  10475. else
  10476. {
  10477. lastError = "incorrect xml header";
  10478. }
  10479. }
  10480. return 0;
  10481. }
  10482. const String& XmlDocument::getLastParseError() const throw()
  10483. {
  10484. return lastError;
  10485. }
  10486. void XmlDocument::setLastError (const String& desc, const bool carryOn)
  10487. {
  10488. lastError = desc;
  10489. errorOccurred = ! carryOn;
  10490. }
  10491. const String XmlDocument::getFileContents (const String& filename) const
  10492. {
  10493. if (inputSource != 0)
  10494. {
  10495. const ScopedPointer <InputStream> in (inputSource->createInputStreamFor (filename.trim().unquoted()));
  10496. if (in != 0)
  10497. return in->readEntireStreamAsString();
  10498. }
  10499. return String::empty;
  10500. }
  10501. juce_wchar XmlDocument::readNextChar() throw()
  10502. {
  10503. if (*input != 0)
  10504. {
  10505. return *input++;
  10506. }
  10507. else
  10508. {
  10509. outOfData = true;
  10510. return 0;
  10511. }
  10512. }
  10513. int XmlDocument::findNextTokenLength() throw()
  10514. {
  10515. int len = 0;
  10516. juce_wchar c = *input;
  10517. while (isXmlIdentifierChar (c))
  10518. c = input [++len];
  10519. return len;
  10520. }
  10521. void XmlDocument::skipHeader()
  10522. {
  10523. const juce_wchar* const found = CharacterFunctions::find (input, T("<?xml"));
  10524. if (found != 0)
  10525. {
  10526. input = found;
  10527. input = CharacterFunctions::find (input, T("?>"));
  10528. if (input == 0)
  10529. return;
  10530. input += 2;
  10531. }
  10532. skipNextWhiteSpace();
  10533. const juce_wchar* docType = CharacterFunctions::find (input, T("<!DOCTYPE"));
  10534. if (docType == 0)
  10535. return;
  10536. input = docType + 9;
  10537. int n = 1;
  10538. while (n > 0)
  10539. {
  10540. const juce_wchar c = readNextChar();
  10541. if (outOfData)
  10542. return;
  10543. if (c == '<')
  10544. ++n;
  10545. else if (c == '>')
  10546. --n;
  10547. }
  10548. docType += 9;
  10549. dtdText = String (docType, (int) (input - (docType + 1))).trim();
  10550. }
  10551. void XmlDocument::skipNextWhiteSpace()
  10552. {
  10553. for (;;)
  10554. {
  10555. juce_wchar c = *input;
  10556. while (CharacterFunctions::isWhitespace (c))
  10557. c = *++input;
  10558. if (c == 0)
  10559. {
  10560. outOfData = true;
  10561. break;
  10562. }
  10563. else if (c == '<')
  10564. {
  10565. if (input[1] == '!'
  10566. && input[2] == '-'
  10567. && input[3] == '-')
  10568. {
  10569. const juce_wchar* const closeComment = CharacterFunctions::find (input, T("-->"));
  10570. if (closeComment == 0)
  10571. {
  10572. outOfData = true;
  10573. break;
  10574. }
  10575. input = closeComment + 3;
  10576. continue;
  10577. }
  10578. else if (input[1] == '?')
  10579. {
  10580. const juce_wchar* const closeBracket = CharacterFunctions::find (input, T("?>"));
  10581. if (closeBracket == 0)
  10582. {
  10583. outOfData = true;
  10584. break;
  10585. }
  10586. input = closeBracket + 2;
  10587. continue;
  10588. }
  10589. }
  10590. break;
  10591. }
  10592. }
  10593. void XmlDocument::readQuotedString (String& result)
  10594. {
  10595. const juce_wchar quote = readNextChar();
  10596. while (! outOfData)
  10597. {
  10598. const juce_wchar c = readNextChar();
  10599. if (c == quote)
  10600. break;
  10601. if (c == '&')
  10602. {
  10603. --input;
  10604. readEntity (result);
  10605. }
  10606. else
  10607. {
  10608. --input;
  10609. const juce_wchar* const start = input;
  10610. for (;;)
  10611. {
  10612. const juce_wchar character = *input;
  10613. if (character == quote)
  10614. {
  10615. result.append (start, (int) (input - start));
  10616. ++input;
  10617. return;
  10618. }
  10619. else if (character == '&')
  10620. {
  10621. result.append (start, (int) (input - start));
  10622. break;
  10623. }
  10624. else if (character == 0)
  10625. {
  10626. outOfData = true;
  10627. setLastError ("unmatched quotes", false);
  10628. break;
  10629. }
  10630. ++input;
  10631. }
  10632. }
  10633. }
  10634. }
  10635. XmlElement* XmlDocument::readNextElement (const bool alsoParseSubElements)
  10636. {
  10637. XmlElement* node = 0;
  10638. skipNextWhiteSpace();
  10639. if (outOfData)
  10640. return 0;
  10641. input = CharacterFunctions::find (input, T("<"));
  10642. if (input != 0)
  10643. {
  10644. ++input;
  10645. int tagLen = findNextTokenLength();
  10646. if (tagLen == 0)
  10647. {
  10648. // no tag name - but allow for a gap after the '<' before giving an error
  10649. skipNextWhiteSpace();
  10650. tagLen = findNextTokenLength();
  10651. if (tagLen == 0)
  10652. {
  10653. setLastError ("tag name missing", false);
  10654. return node;
  10655. }
  10656. }
  10657. node = new XmlElement (String (input, tagLen));
  10658. input += tagLen;
  10659. XmlElement::XmlAttributeNode* lastAttribute = 0;
  10660. // look for attributes
  10661. for (;;)
  10662. {
  10663. skipNextWhiteSpace();
  10664. const juce_wchar c = *input;
  10665. // empty tag..
  10666. if (c == '/' && input[1] == '>')
  10667. {
  10668. input += 2;
  10669. break;
  10670. }
  10671. // parse the guts of the element..
  10672. if (c == '>')
  10673. {
  10674. ++input;
  10675. skipNextWhiteSpace();
  10676. if (alsoParseSubElements)
  10677. readChildElements (node);
  10678. break;
  10679. }
  10680. // get an attribute..
  10681. if (isXmlIdentifierChar (c))
  10682. {
  10683. const int attNameLen = findNextTokenLength();
  10684. if (attNameLen > 0)
  10685. {
  10686. const juce_wchar* attNameStart = input;
  10687. input += attNameLen;
  10688. skipNextWhiteSpace();
  10689. if (readNextChar() == '=')
  10690. {
  10691. skipNextWhiteSpace();
  10692. const juce_wchar nextChar = *input;
  10693. if (nextChar == '"' || nextChar == '\'')
  10694. {
  10695. XmlElement::XmlAttributeNode* const newAtt
  10696. = new XmlElement::XmlAttributeNode (String (attNameStart, attNameLen),
  10697. String::empty);
  10698. readQuotedString (newAtt->value);
  10699. if (lastAttribute == 0)
  10700. node->attributes = newAtt;
  10701. else
  10702. lastAttribute->next = newAtt;
  10703. lastAttribute = newAtt;
  10704. continue;
  10705. }
  10706. }
  10707. }
  10708. }
  10709. else
  10710. {
  10711. if (! outOfData)
  10712. setLastError ("illegal character found in " + node->getTagName() + ": '" + c + "'", false);
  10713. }
  10714. break;
  10715. }
  10716. }
  10717. return node;
  10718. }
  10719. void XmlDocument::readChildElements (XmlElement* parent)
  10720. {
  10721. XmlElement* lastChildNode = 0;
  10722. for (;;)
  10723. {
  10724. skipNextWhiteSpace();
  10725. if (outOfData)
  10726. {
  10727. setLastError ("unmatched tags", false);
  10728. break;
  10729. }
  10730. if (*input == '<')
  10731. {
  10732. if (input[1] == '/')
  10733. {
  10734. // our close tag..
  10735. input = CharacterFunctions::find (input, T(">"));
  10736. ++input;
  10737. break;
  10738. }
  10739. else if (input[1] == '!'
  10740. && input[2] == '['
  10741. && input[3] == 'C'
  10742. && input[4] == 'D'
  10743. && input[5] == 'A'
  10744. && input[6] == 'T'
  10745. && input[7] == 'A'
  10746. && input[8] == '[')
  10747. {
  10748. input += 9;
  10749. const juce_wchar* const inputStart = input;
  10750. int len = 0;
  10751. for (;;)
  10752. {
  10753. if (*input == 0)
  10754. {
  10755. setLastError ("unterminated CDATA section", false);
  10756. outOfData = true;
  10757. break;
  10758. }
  10759. else if (input[0] == ']'
  10760. && input[1] == ']'
  10761. && input[2] == '>')
  10762. {
  10763. input += 3;
  10764. break;
  10765. }
  10766. ++input;
  10767. ++len;
  10768. }
  10769. XmlElement* const e = new XmlElement ((int) 0);
  10770. e->setText (String (inputStart, len));
  10771. if (lastChildNode != 0)
  10772. lastChildNode->nextElement = e;
  10773. else
  10774. parent->addChildElement (e);
  10775. lastChildNode = e;
  10776. }
  10777. else
  10778. {
  10779. // this is some other element, so parse and add it..
  10780. XmlElement* const n = readNextElement (true);
  10781. if (n != 0)
  10782. {
  10783. if (lastChildNode == 0)
  10784. parent->addChildElement (n);
  10785. else
  10786. lastChildNode->nextElement = n;
  10787. lastChildNode = n;
  10788. }
  10789. else
  10790. {
  10791. return;
  10792. }
  10793. }
  10794. }
  10795. else
  10796. {
  10797. // read character block..
  10798. XmlElement* const e = new XmlElement ((int)0);
  10799. if (lastChildNode != 0)
  10800. lastChildNode->nextElement = e;
  10801. else
  10802. parent->addChildElement (e);
  10803. lastChildNode = e;
  10804. String textElementContent;
  10805. for (;;)
  10806. {
  10807. const juce_wchar c = *input;
  10808. if (c == '<')
  10809. break;
  10810. if (c == 0)
  10811. {
  10812. setLastError ("unmatched tags", false);
  10813. outOfData = true;
  10814. return;
  10815. }
  10816. if (c == '&')
  10817. {
  10818. String entity;
  10819. readEntity (entity);
  10820. if (entity.startsWithChar ('<') && entity [1] != 0)
  10821. {
  10822. const juce_wchar* const oldInput = input;
  10823. const bool oldOutOfData = outOfData;
  10824. input = entity;
  10825. outOfData = false;
  10826. for (;;)
  10827. {
  10828. XmlElement* const n = readNextElement (true);
  10829. if (n == 0)
  10830. break;
  10831. if (lastChildNode == 0)
  10832. parent->addChildElement (n);
  10833. else
  10834. lastChildNode->nextElement = n;
  10835. lastChildNode = n;
  10836. }
  10837. input = oldInput;
  10838. outOfData = oldOutOfData;
  10839. }
  10840. else
  10841. {
  10842. textElementContent += entity;
  10843. }
  10844. }
  10845. else
  10846. {
  10847. const juce_wchar* start = input;
  10848. int len = 0;
  10849. for (;;)
  10850. {
  10851. const juce_wchar nextChar = *input;
  10852. if (nextChar == '<' || nextChar == '&')
  10853. {
  10854. break;
  10855. }
  10856. else if (nextChar == 0)
  10857. {
  10858. setLastError ("unmatched tags", false);
  10859. outOfData = true;
  10860. return;
  10861. }
  10862. ++input;
  10863. ++len;
  10864. }
  10865. textElementContent.append (start, len);
  10866. }
  10867. }
  10868. if (ignoreEmptyTextElements ? textElementContent.containsNonWhitespaceChars()
  10869. : textElementContent.isNotEmpty())
  10870. e->setText (textElementContent);
  10871. }
  10872. }
  10873. }
  10874. void XmlDocument::readEntity (String& result)
  10875. {
  10876. // skip over the ampersand
  10877. ++input;
  10878. if (CharacterFunctions::compareIgnoreCase (input, T("amp;"), 4) == 0)
  10879. {
  10880. input += 4;
  10881. result += '&';
  10882. }
  10883. else if (CharacterFunctions::compareIgnoreCase (input, T("quot;"), 5) == 0)
  10884. {
  10885. input += 5;
  10886. result += '"';
  10887. }
  10888. else if (CharacterFunctions::compareIgnoreCase (input, T("apos;"), 5) == 0)
  10889. {
  10890. input += 5;
  10891. result += '\'';
  10892. }
  10893. else if (CharacterFunctions::compareIgnoreCase (input, T("lt;"), 3) == 0)
  10894. {
  10895. input += 3;
  10896. result += '<';
  10897. }
  10898. else if (CharacterFunctions::compareIgnoreCase (input, T("gt;"), 3) == 0)
  10899. {
  10900. input += 3;
  10901. result += '>';
  10902. }
  10903. else if (*input == '#')
  10904. {
  10905. int charCode = 0;
  10906. ++input;
  10907. if (*input == 'x' || *input == 'X')
  10908. {
  10909. ++input;
  10910. int numChars = 0;
  10911. while (input[0] != ';')
  10912. {
  10913. const int hexValue = CharacterFunctions::getHexDigitValue (input[0]);
  10914. if (hexValue < 0 || ++numChars > 8)
  10915. {
  10916. setLastError ("illegal escape sequence", true);
  10917. break;
  10918. }
  10919. charCode = (charCode << 4) | hexValue;
  10920. ++input;
  10921. }
  10922. ++input;
  10923. }
  10924. else if (input[0] >= '0' && input[0] <= '9')
  10925. {
  10926. int numChars = 0;
  10927. while (input[0] != ';')
  10928. {
  10929. if (++numChars > 12)
  10930. {
  10931. setLastError ("illegal escape sequence", true);
  10932. break;
  10933. }
  10934. charCode = charCode * 10 + (input[0] - '0');
  10935. ++input;
  10936. }
  10937. ++input;
  10938. }
  10939. else
  10940. {
  10941. setLastError ("illegal escape sequence", true);
  10942. result += '&';
  10943. return;
  10944. }
  10945. result << (juce_wchar) charCode;
  10946. }
  10947. else
  10948. {
  10949. const juce_wchar* const entityNameStart = input;
  10950. const juce_wchar* const closingSemiColon = CharacterFunctions::find (input, T(";"));
  10951. if (closingSemiColon == 0)
  10952. {
  10953. outOfData = true;
  10954. result += '&';
  10955. }
  10956. else
  10957. {
  10958. input = closingSemiColon + 1;
  10959. result += expandExternalEntity (String (entityNameStart,
  10960. (int) (closingSemiColon - entityNameStart)));
  10961. }
  10962. }
  10963. }
  10964. const String XmlDocument::expandEntity (const String& ent)
  10965. {
  10966. if (ent.equalsIgnoreCase ("amp"))
  10967. return String::charToString ('&');
  10968. if (ent.equalsIgnoreCase ("quot"))
  10969. return String::charToString ('"');
  10970. if (ent.equalsIgnoreCase ("apos"))
  10971. return String::charToString ('\'');
  10972. if (ent.equalsIgnoreCase ("lt"))
  10973. return String::charToString ('<');
  10974. if (ent.equalsIgnoreCase ("gt"))
  10975. return String::charToString ('>');
  10976. if (ent[0] == '#')
  10977. {
  10978. if (ent[1] == 'x' || ent[1] == 'X')
  10979. return String::charToString (static_cast <juce_wchar> (ent.substring (2).getHexValue32()));
  10980. if (ent[1] >= '0' && ent[1] <= '9')
  10981. return String::charToString (static_cast <juce_wchar> (ent.substring (1).getIntValue()));
  10982. setLastError ("illegal escape sequence", false);
  10983. return String::charToString ('&');
  10984. }
  10985. return expandExternalEntity (ent);
  10986. }
  10987. const String XmlDocument::expandExternalEntity (const String& entity)
  10988. {
  10989. if (needToLoadDTD)
  10990. {
  10991. if (dtdText.isNotEmpty())
  10992. {
  10993. dtdText = dtdText.trimCharactersAtEnd (">");
  10994. tokenisedDTD.addTokens (dtdText, true);
  10995. if (tokenisedDTD [tokenisedDTD.size() - 2].equalsIgnoreCase ("system")
  10996. && tokenisedDTD [tokenisedDTD.size() - 1].isQuotedString())
  10997. {
  10998. const String fn (tokenisedDTD [tokenisedDTD.size() - 1]);
  10999. tokenisedDTD.clear();
  11000. tokenisedDTD.addTokens (getFileContents (fn), true);
  11001. }
  11002. else
  11003. {
  11004. tokenisedDTD.clear();
  11005. const int openBracket = dtdText.indexOfChar ('[');
  11006. if (openBracket > 0)
  11007. {
  11008. const int closeBracket = dtdText.lastIndexOfChar (']');
  11009. if (closeBracket > openBracket)
  11010. tokenisedDTD.addTokens (dtdText.substring (openBracket + 1,
  11011. closeBracket), true);
  11012. }
  11013. }
  11014. for (int i = tokenisedDTD.size(); --i >= 0;)
  11015. {
  11016. if (tokenisedDTD[i].startsWithChar ('%')
  11017. && tokenisedDTD[i].endsWithChar (';'))
  11018. {
  11019. const String parsed (getParameterEntity (tokenisedDTD[i].substring (1, tokenisedDTD[i].length() - 1)));
  11020. StringArray newToks;
  11021. newToks.addTokens (parsed, true);
  11022. tokenisedDTD.remove (i);
  11023. for (int j = newToks.size(); --j >= 0;)
  11024. tokenisedDTD.insert (i, newToks[j]);
  11025. }
  11026. }
  11027. }
  11028. needToLoadDTD = false;
  11029. }
  11030. for (int i = 0; i < tokenisedDTD.size(); ++i)
  11031. {
  11032. if (tokenisedDTD[i] == entity)
  11033. {
  11034. if (tokenisedDTD[i - 1].equalsIgnoreCase ("<!entity"))
  11035. {
  11036. String ent (tokenisedDTD [i + 1].trimCharactersAtEnd (">").trim().unquoted());
  11037. // check for sub-entities..
  11038. int ampersand = ent.indexOfChar ('&');
  11039. while (ampersand >= 0)
  11040. {
  11041. const int semiColon = ent.indexOf (i + 1, ";");
  11042. if (semiColon < 0)
  11043. {
  11044. setLastError ("entity without terminating semi-colon", false);
  11045. break;
  11046. }
  11047. const String resolved (expandEntity (ent.substring (i + 1, semiColon)));
  11048. ent = ent.substring (0, ampersand)
  11049. + resolved
  11050. + ent.substring (semiColon + 1);
  11051. ampersand = ent.indexOfChar (semiColon + 1, '&');
  11052. }
  11053. return ent;
  11054. }
  11055. }
  11056. }
  11057. setLastError ("unknown entity", true);
  11058. return entity;
  11059. }
  11060. const String XmlDocument::getParameterEntity (const String& entity)
  11061. {
  11062. for (int i = 0; i < tokenisedDTD.size(); ++i)
  11063. {
  11064. if (tokenisedDTD[i] == entity)
  11065. {
  11066. if (tokenisedDTD [i - 1] == "%"
  11067. && tokenisedDTD [i - 2].equalsIgnoreCase ("<!entity"))
  11068. {
  11069. const String ent (tokenisedDTD [i + 1].trimCharactersAtEnd (">"));
  11070. if (ent.equalsIgnoreCase ("system"))
  11071. return getFileContents (tokenisedDTD [i + 2].trimCharactersAtEnd (">"));
  11072. else
  11073. return ent.trim().unquoted();
  11074. }
  11075. }
  11076. }
  11077. return entity;
  11078. }
  11079. END_JUCE_NAMESPACE
  11080. /*** End of inlined file: juce_XmlDocument.cpp ***/
  11081. /*** Start of inlined file: juce_XmlElement.cpp ***/
  11082. BEGIN_JUCE_NAMESPACE
  11083. XmlElement::XmlAttributeNode::XmlAttributeNode (const XmlAttributeNode& other) throw()
  11084. : name (other.name),
  11085. value (other.value),
  11086. next (0)
  11087. {
  11088. }
  11089. XmlElement::XmlAttributeNode::XmlAttributeNode (const String& name_, const String& value_) throw()
  11090. : name (name_),
  11091. value (value_),
  11092. next (0)
  11093. {
  11094. }
  11095. XmlElement::XmlElement (const String& tagName_) throw()
  11096. : tagName (tagName_),
  11097. firstChildElement (0),
  11098. nextElement (0),
  11099. attributes (0)
  11100. {
  11101. // the tag name mustn't be empty, or it'll look like a text element!
  11102. jassert (tagName_.containsNonWhitespaceChars())
  11103. // The tag can't contain spaces or other characters that would create invalid XML!
  11104. jassert (! tagName_.containsAnyOf (" <>/&"));
  11105. }
  11106. XmlElement::XmlElement (int /*dummy*/) throw()
  11107. : firstChildElement (0),
  11108. nextElement (0),
  11109. attributes (0)
  11110. {
  11111. }
  11112. XmlElement::XmlElement (const XmlElement& other) throw()
  11113. : tagName (other.tagName),
  11114. firstChildElement (0),
  11115. nextElement (0),
  11116. attributes (0)
  11117. {
  11118. copyChildrenAndAttributesFrom (other);
  11119. }
  11120. XmlElement& XmlElement::operator= (const XmlElement& other) throw()
  11121. {
  11122. if (this != &other)
  11123. {
  11124. removeAllAttributes();
  11125. deleteAllChildElements();
  11126. tagName = other.tagName;
  11127. copyChildrenAndAttributesFrom (other);
  11128. }
  11129. return *this;
  11130. }
  11131. void XmlElement::copyChildrenAndAttributesFrom (const XmlElement& other) throw()
  11132. {
  11133. XmlElement* child = other.firstChildElement;
  11134. XmlElement* lastChild = 0;
  11135. while (child != 0)
  11136. {
  11137. XmlElement* const copiedChild = new XmlElement (*child);
  11138. if (lastChild != 0)
  11139. lastChild->nextElement = copiedChild;
  11140. else
  11141. firstChildElement = copiedChild;
  11142. lastChild = copiedChild;
  11143. child = child->nextElement;
  11144. }
  11145. const XmlAttributeNode* att = other.attributes;
  11146. XmlAttributeNode* lastAtt = 0;
  11147. while (att != 0)
  11148. {
  11149. XmlAttributeNode* const newAtt = new XmlAttributeNode (*att);
  11150. if (lastAtt != 0)
  11151. lastAtt->next = newAtt;
  11152. else
  11153. attributes = newAtt;
  11154. lastAtt = newAtt;
  11155. att = att->next;
  11156. }
  11157. }
  11158. XmlElement::~XmlElement() throw()
  11159. {
  11160. XmlElement* child = firstChildElement;
  11161. while (child != 0)
  11162. {
  11163. XmlElement* const nextChild = child->nextElement;
  11164. delete child;
  11165. child = nextChild;
  11166. }
  11167. XmlAttributeNode* att = attributes;
  11168. while (att != 0)
  11169. {
  11170. XmlAttributeNode* const nextAtt = att->next;
  11171. delete att;
  11172. att = nextAtt;
  11173. }
  11174. }
  11175. namespace XmlOutputFunctions
  11176. {
  11177. /*static bool isLegalXmlCharSlow (const juce_wchar character) throw()
  11178. {
  11179. if ((character >= 'a' && character <= 'z')
  11180. || (character >= 'A' && character <= 'Z')
  11181. || (character >= '0' && character <= '9'))
  11182. return true;
  11183. const char* t = " .,;:-()_+=?!'#@[]/\\*%~{}";
  11184. do
  11185. {
  11186. if (((juce_wchar) (uint8) *t) == character)
  11187. return true;
  11188. }
  11189. while (*++t != 0);
  11190. return false;
  11191. }
  11192. static void generateLegalCharConstants()
  11193. {
  11194. uint8 n[32];
  11195. zerostruct (n);
  11196. for (int i = 0; i < 256; ++i)
  11197. if (isLegalXmlCharSlow (i))
  11198. n[i >> 3] |= (1 << (i & 7));
  11199. String s;
  11200. for (int i = 0; i < 32; ++i)
  11201. s << (int) n[i] << ", ";
  11202. DBG (s);
  11203. }*/
  11204. static bool isLegalXmlChar (const uint32 c) throw()
  11205. {
  11206. static const unsigned char legalChars[] = { 0, 0, 0, 0, 171, 255, 255, 175, 255, 255, 255, 191, 254, 255, 255, 111 };
  11207. return c < sizeof (legalChars) * 8
  11208. && (legalChars [c >> 3] & (1 << (c & 7))) != 0;
  11209. }
  11210. static void escapeIllegalXmlChars (OutputStream& outputStream, const String& text, const bool changeNewLines)
  11211. {
  11212. const juce_wchar* t = text;
  11213. for (;;)
  11214. {
  11215. const juce_wchar character = *t++;
  11216. if (character == 0)
  11217. {
  11218. break;
  11219. }
  11220. else if (isLegalXmlChar ((uint32) character))
  11221. {
  11222. outputStream << (char) character;
  11223. }
  11224. else
  11225. {
  11226. switch (character)
  11227. {
  11228. case '&': outputStream << "&amp;"; break;
  11229. case '"': outputStream << "&quot;"; break;
  11230. case '>': outputStream << "&gt;"; break;
  11231. case '<': outputStream << "&lt;"; break;
  11232. case '\n':
  11233. if (changeNewLines)
  11234. outputStream << "&#10;";
  11235. else
  11236. outputStream << (char) character;
  11237. break;
  11238. case '\r':
  11239. if (changeNewLines)
  11240. outputStream << "&#13;";
  11241. else
  11242. outputStream << (char) character;
  11243. break;
  11244. default:
  11245. outputStream << "&#" << ((int) (unsigned int) character) << ';';
  11246. break;
  11247. }
  11248. }
  11249. }
  11250. }
  11251. static void writeSpaces (OutputStream& out, int numSpaces)
  11252. {
  11253. if (numSpaces > 0)
  11254. {
  11255. const char* const blanks = " ";
  11256. const int blankSize = (int) sizeof (blanks) - 1;
  11257. while (numSpaces > blankSize)
  11258. {
  11259. out.write (blanks, blankSize);
  11260. numSpaces -= blankSize;
  11261. }
  11262. out.write (blanks, numSpaces);
  11263. }
  11264. }
  11265. }
  11266. void XmlElement::writeElementAsText (OutputStream& outputStream,
  11267. const int indentationLevel,
  11268. const int lineWrapLength) const
  11269. {
  11270. using namespace XmlOutputFunctions;
  11271. writeSpaces (outputStream, indentationLevel);
  11272. if (! isTextElement())
  11273. {
  11274. outputStream.writeByte ('<');
  11275. outputStream << tagName;
  11276. const int attIndent = indentationLevel + tagName.length() + 1;
  11277. int lineLen = 0;
  11278. const XmlAttributeNode* att = attributes;
  11279. while (att != 0)
  11280. {
  11281. if (lineLen > lineWrapLength && indentationLevel >= 0)
  11282. {
  11283. outputStream.write ("\r\n", 2);
  11284. writeSpaces (outputStream, attIndent);
  11285. lineLen = 0;
  11286. }
  11287. const int64 startPos = outputStream.getPosition();
  11288. outputStream.writeByte (' ');
  11289. outputStream << att->name;
  11290. outputStream.write ("=\"", 2);
  11291. escapeIllegalXmlChars (outputStream, att->value, true);
  11292. outputStream.writeByte ('"');
  11293. lineLen += (int) (outputStream.getPosition() - startPos);
  11294. att = att->next;
  11295. }
  11296. if (firstChildElement != 0)
  11297. {
  11298. XmlElement* child = firstChildElement;
  11299. if (child->nextElement == 0 && child->isTextElement())
  11300. {
  11301. outputStream.writeByte ('>');
  11302. escapeIllegalXmlChars (outputStream, child->getText(), false);
  11303. }
  11304. else
  11305. {
  11306. if (indentationLevel >= 0)
  11307. outputStream.write (">\r\n", 3);
  11308. else
  11309. outputStream.writeByte ('>');
  11310. bool lastWasTextNode = false;
  11311. while (child != 0)
  11312. {
  11313. if (child->isTextElement())
  11314. {
  11315. if ((! lastWasTextNode) && (indentationLevel >= 0))
  11316. writeSpaces (outputStream, indentationLevel + 2);
  11317. escapeIllegalXmlChars (outputStream, child->getText(), false);
  11318. lastWasTextNode = true;
  11319. }
  11320. else
  11321. {
  11322. if (indentationLevel >= 0)
  11323. {
  11324. if (lastWasTextNode)
  11325. outputStream.write ("\r\n", 2);
  11326. child->writeElementAsText (outputStream, indentationLevel + 2, lineWrapLength);
  11327. }
  11328. else
  11329. {
  11330. child->writeElementAsText (outputStream, indentationLevel, lineWrapLength);
  11331. }
  11332. lastWasTextNode = false;
  11333. }
  11334. child = child->nextElement;
  11335. }
  11336. if (indentationLevel >= 0)
  11337. {
  11338. if (lastWasTextNode)
  11339. outputStream.write ("\r\n", 2);
  11340. writeSpaces (outputStream, indentationLevel);
  11341. }
  11342. }
  11343. outputStream.write ("</", 2);
  11344. outputStream << tagName;
  11345. if (indentationLevel >= 0)
  11346. outputStream.write (">\r\n", 3);
  11347. else
  11348. outputStream.writeByte ('>');
  11349. }
  11350. else
  11351. {
  11352. if (indentationLevel >= 0)
  11353. outputStream.write ("/>\r\n", 4);
  11354. else
  11355. outputStream.write ("/>", 2);
  11356. }
  11357. }
  11358. else
  11359. {
  11360. if (indentationLevel >= 0)
  11361. writeSpaces (outputStream, indentationLevel + 2);
  11362. escapeIllegalXmlChars (outputStream, getText(), false);
  11363. }
  11364. }
  11365. const String XmlElement::createDocument (const String& dtdToUse,
  11366. const bool allOnOneLine,
  11367. const bool includeXmlHeader,
  11368. const String& encodingType,
  11369. const int lineWrapLength) const
  11370. {
  11371. MemoryOutputStream mem (2048, 4096);
  11372. writeToStream (mem, dtdToUse, allOnOneLine, includeXmlHeader, encodingType, lineWrapLength);
  11373. return mem.toUTF8();
  11374. }
  11375. void XmlElement::writeToStream (OutputStream& output,
  11376. const String& dtdToUse,
  11377. const bool allOnOneLine,
  11378. const bool includeXmlHeader,
  11379. const String& encodingType,
  11380. const int lineWrapLength) const
  11381. {
  11382. if (includeXmlHeader)
  11383. output << "<?xml version=\"1.0\" encoding=\"" << encodingType
  11384. << (allOnOneLine ? "\"?> " : "\"?>\r\n\r\n");
  11385. if (dtdToUse.isNotEmpty())
  11386. output << dtdToUse << (allOnOneLine ? " " : "\r\n");
  11387. writeElementAsText (output, allOnOneLine ? -1 : 0, lineWrapLength);
  11388. }
  11389. bool XmlElement::writeToFile (const File& file,
  11390. const String& dtdToUse,
  11391. const String& encodingType,
  11392. const int lineWrapLength) const
  11393. {
  11394. if (file.hasWriteAccess())
  11395. {
  11396. TemporaryFile tempFile (file);
  11397. ScopedPointer <FileOutputStream> out (tempFile.getFile().createOutputStream());
  11398. if (out != 0)
  11399. {
  11400. writeToStream (*out, dtdToUse, false, true, encodingType, lineWrapLength);
  11401. out = 0;
  11402. return tempFile.overwriteTargetFileWithTemporary();
  11403. }
  11404. }
  11405. return false;
  11406. }
  11407. bool XmlElement::hasTagName (const String& tagNameWanted) const throw()
  11408. {
  11409. #if JUCE_DEBUG
  11410. // if debugging, check that the case is actually the same, because
  11411. // valid xml is case-sensitive, and although this lets it pass, it's
  11412. // better not to..
  11413. if (tagName.equalsIgnoreCase (tagNameWanted))
  11414. {
  11415. jassert (tagName == tagNameWanted);
  11416. return true;
  11417. }
  11418. else
  11419. {
  11420. return false;
  11421. }
  11422. #else
  11423. return tagName.equalsIgnoreCase (tagNameWanted);
  11424. #endif
  11425. }
  11426. XmlElement* XmlElement::getNextElementWithTagName (const String& requiredTagName) const
  11427. {
  11428. XmlElement* e = nextElement;
  11429. while (e != 0 && ! e->hasTagName (requiredTagName))
  11430. e = e->nextElement;
  11431. return e;
  11432. }
  11433. int XmlElement::getNumAttributes() const throw()
  11434. {
  11435. const XmlAttributeNode* att = attributes;
  11436. int count = 0;
  11437. while (att != 0)
  11438. {
  11439. att = att->next;
  11440. ++count;
  11441. }
  11442. return count;
  11443. }
  11444. const String& XmlElement::getAttributeName (const int index) const throw()
  11445. {
  11446. const XmlAttributeNode* att = attributes;
  11447. int count = 0;
  11448. while (att != 0)
  11449. {
  11450. if (count == index)
  11451. return att->name;
  11452. att = att->next;
  11453. ++count;
  11454. }
  11455. return String::empty;
  11456. }
  11457. const String& XmlElement::getAttributeValue (const int index) const throw()
  11458. {
  11459. const XmlAttributeNode* att = attributes;
  11460. int count = 0;
  11461. while (att != 0)
  11462. {
  11463. if (count == index)
  11464. return att->value;
  11465. att = att->next;
  11466. ++count;
  11467. }
  11468. return String::empty;
  11469. }
  11470. bool XmlElement::hasAttribute (const String& attributeName) const throw()
  11471. {
  11472. const XmlAttributeNode* att = attributes;
  11473. while (att != 0)
  11474. {
  11475. if (att->name.equalsIgnoreCase (attributeName))
  11476. return true;
  11477. att = att->next;
  11478. }
  11479. return false;
  11480. }
  11481. const String& XmlElement::getStringAttribute (const String& attributeName) const throw()
  11482. {
  11483. const XmlAttributeNode* att = attributes;
  11484. while (att != 0)
  11485. {
  11486. if (att->name.equalsIgnoreCase (attributeName))
  11487. return att->value;
  11488. att = att->next;
  11489. }
  11490. return String::empty;
  11491. }
  11492. const String XmlElement::getStringAttribute (const String& attributeName, const String& defaultReturnValue) const
  11493. {
  11494. const XmlAttributeNode* att = attributes;
  11495. while (att != 0)
  11496. {
  11497. if (att->name.equalsIgnoreCase (attributeName))
  11498. return att->value;
  11499. att = att->next;
  11500. }
  11501. return defaultReturnValue;
  11502. }
  11503. int XmlElement::getIntAttribute (const String& attributeName, const int defaultReturnValue) const
  11504. {
  11505. const XmlAttributeNode* att = attributes;
  11506. while (att != 0)
  11507. {
  11508. if (att->name.equalsIgnoreCase (attributeName))
  11509. return att->value.getIntValue();
  11510. att = att->next;
  11511. }
  11512. return defaultReturnValue;
  11513. }
  11514. double XmlElement::getDoubleAttribute (const String& attributeName, const double defaultReturnValue) const
  11515. {
  11516. const XmlAttributeNode* att = attributes;
  11517. while (att != 0)
  11518. {
  11519. if (att->name.equalsIgnoreCase (attributeName))
  11520. return att->value.getDoubleValue();
  11521. att = att->next;
  11522. }
  11523. return defaultReturnValue;
  11524. }
  11525. bool XmlElement::getBoolAttribute (const String& attributeName, const bool defaultReturnValue) const
  11526. {
  11527. const XmlAttributeNode* att = attributes;
  11528. while (att != 0)
  11529. {
  11530. if (att->name.equalsIgnoreCase (attributeName))
  11531. {
  11532. juce_wchar firstChar = att->value[0];
  11533. if (CharacterFunctions::isWhitespace (firstChar))
  11534. firstChar = att->value.trimStart() [0];
  11535. return firstChar == '1'
  11536. || firstChar == 't'
  11537. || firstChar == 'y'
  11538. || firstChar == 'T'
  11539. || firstChar == 'Y';
  11540. }
  11541. att = att->next;
  11542. }
  11543. return defaultReturnValue;
  11544. }
  11545. bool XmlElement::compareAttribute (const String& attributeName,
  11546. const String& stringToCompareAgainst,
  11547. const bool ignoreCase) const throw()
  11548. {
  11549. const XmlAttributeNode* att = attributes;
  11550. while (att != 0)
  11551. {
  11552. if (att->name.equalsIgnoreCase (attributeName))
  11553. {
  11554. if (ignoreCase)
  11555. return att->value.equalsIgnoreCase (stringToCompareAgainst);
  11556. else
  11557. return att->value == stringToCompareAgainst;
  11558. }
  11559. att = att->next;
  11560. }
  11561. return false;
  11562. }
  11563. void XmlElement::setAttribute (const String& attributeName, const String& value)
  11564. {
  11565. #if JUCE_DEBUG
  11566. // check the identifier being passed in is legal..
  11567. const juce_wchar* t = attributeName;
  11568. while (*t != 0)
  11569. {
  11570. jassert (CharacterFunctions::isLetterOrDigit (*t)
  11571. || *t == '_'
  11572. || *t == '-'
  11573. || *t == ':');
  11574. ++t;
  11575. }
  11576. #endif
  11577. if (attributes == 0)
  11578. {
  11579. attributes = new XmlAttributeNode (attributeName, value);
  11580. }
  11581. else
  11582. {
  11583. XmlAttributeNode* att = attributes;
  11584. for (;;)
  11585. {
  11586. if (att->name.equalsIgnoreCase (attributeName))
  11587. {
  11588. att->value = value;
  11589. break;
  11590. }
  11591. else if (att->next == 0)
  11592. {
  11593. att->next = new XmlAttributeNode (attributeName, value);
  11594. break;
  11595. }
  11596. att = att->next;
  11597. }
  11598. }
  11599. }
  11600. void XmlElement::setAttribute (const String& attributeName, const int number)
  11601. {
  11602. setAttribute (attributeName, String (number));
  11603. }
  11604. void XmlElement::setAttribute (const String& attributeName, const double number)
  11605. {
  11606. setAttribute (attributeName, String (number));
  11607. }
  11608. void XmlElement::removeAttribute (const String& attributeName) throw()
  11609. {
  11610. XmlAttributeNode* att = attributes;
  11611. XmlAttributeNode* lastAtt = 0;
  11612. while (att != 0)
  11613. {
  11614. if (att->name.equalsIgnoreCase (attributeName))
  11615. {
  11616. if (lastAtt == 0)
  11617. attributes = att->next;
  11618. else
  11619. lastAtt->next = att->next;
  11620. delete att;
  11621. break;
  11622. }
  11623. lastAtt = att;
  11624. att = att->next;
  11625. }
  11626. }
  11627. void XmlElement::removeAllAttributes() throw()
  11628. {
  11629. while (attributes != 0)
  11630. {
  11631. XmlAttributeNode* const nextAtt = attributes->next;
  11632. delete attributes;
  11633. attributes = nextAtt;
  11634. }
  11635. }
  11636. int XmlElement::getNumChildElements() const throw()
  11637. {
  11638. int count = 0;
  11639. const XmlElement* child = firstChildElement;
  11640. while (child != 0)
  11641. {
  11642. ++count;
  11643. child = child->nextElement;
  11644. }
  11645. return count;
  11646. }
  11647. XmlElement* XmlElement::getChildElement (const int index) const throw()
  11648. {
  11649. int count = 0;
  11650. XmlElement* child = firstChildElement;
  11651. while (child != 0 && count < index)
  11652. {
  11653. child = child->nextElement;
  11654. ++count;
  11655. }
  11656. return child;
  11657. }
  11658. XmlElement* XmlElement::getChildByName (const String& childName) const throw()
  11659. {
  11660. XmlElement* child = firstChildElement;
  11661. while (child != 0)
  11662. {
  11663. if (child->hasTagName (childName))
  11664. break;
  11665. child = child->nextElement;
  11666. }
  11667. return child;
  11668. }
  11669. void XmlElement::addChildElement (XmlElement* const newNode) throw()
  11670. {
  11671. if (newNode != 0)
  11672. {
  11673. if (firstChildElement == 0)
  11674. {
  11675. firstChildElement = newNode;
  11676. }
  11677. else
  11678. {
  11679. XmlElement* child = firstChildElement;
  11680. while (child->nextElement != 0)
  11681. child = child->nextElement;
  11682. child->nextElement = newNode;
  11683. // if this is non-zero, then something's probably
  11684. // gone wrong..
  11685. jassert (newNode->nextElement == 0);
  11686. }
  11687. }
  11688. }
  11689. void XmlElement::insertChildElement (XmlElement* const newNode,
  11690. int indexToInsertAt) throw()
  11691. {
  11692. if (newNode != 0)
  11693. {
  11694. removeChildElement (newNode, false);
  11695. if (indexToInsertAt == 0)
  11696. {
  11697. newNode->nextElement = firstChildElement;
  11698. firstChildElement = newNode;
  11699. }
  11700. else
  11701. {
  11702. if (firstChildElement == 0)
  11703. {
  11704. firstChildElement = newNode;
  11705. }
  11706. else
  11707. {
  11708. if (indexToInsertAt < 0)
  11709. indexToInsertAt = std::numeric_limits<int>::max();
  11710. XmlElement* child = firstChildElement;
  11711. while (child->nextElement != 0 && --indexToInsertAt > 0)
  11712. child = child->nextElement;
  11713. newNode->nextElement = child->nextElement;
  11714. child->nextElement = newNode;
  11715. }
  11716. }
  11717. }
  11718. }
  11719. XmlElement* XmlElement::createNewChildElement (const String& tagName)
  11720. {
  11721. XmlElement* const newElement = new XmlElement (tagName);
  11722. addChildElement (newElement);
  11723. return newElement;
  11724. }
  11725. bool XmlElement::replaceChildElement (XmlElement* const currentChildElement,
  11726. XmlElement* const newNode) throw()
  11727. {
  11728. if (newNode != 0)
  11729. {
  11730. XmlElement* child = firstChildElement;
  11731. XmlElement* previousNode = 0;
  11732. while (child != 0)
  11733. {
  11734. if (child == currentChildElement)
  11735. {
  11736. if (child != newNode)
  11737. {
  11738. if (previousNode == 0)
  11739. firstChildElement = newNode;
  11740. else
  11741. previousNode->nextElement = newNode;
  11742. newNode->nextElement = child->nextElement;
  11743. delete child;
  11744. }
  11745. return true;
  11746. }
  11747. previousNode = child;
  11748. child = child->nextElement;
  11749. }
  11750. }
  11751. return false;
  11752. }
  11753. void XmlElement::removeChildElement (XmlElement* const childToRemove,
  11754. const bool shouldDeleteTheChild) throw()
  11755. {
  11756. if (childToRemove != 0)
  11757. {
  11758. if (firstChildElement == childToRemove)
  11759. {
  11760. firstChildElement = childToRemove->nextElement;
  11761. childToRemove->nextElement = 0;
  11762. }
  11763. else
  11764. {
  11765. XmlElement* child = firstChildElement;
  11766. XmlElement* last = 0;
  11767. while (child != 0)
  11768. {
  11769. if (child == childToRemove)
  11770. {
  11771. if (last == 0)
  11772. firstChildElement = child->nextElement;
  11773. else
  11774. last->nextElement = child->nextElement;
  11775. childToRemove->nextElement = 0;
  11776. break;
  11777. }
  11778. last = child;
  11779. child = child->nextElement;
  11780. }
  11781. }
  11782. if (shouldDeleteTheChild)
  11783. delete childToRemove;
  11784. }
  11785. }
  11786. bool XmlElement::isEquivalentTo (const XmlElement* const other,
  11787. const bool ignoreOrderOfAttributes) const throw()
  11788. {
  11789. if (this != other)
  11790. {
  11791. if (other == 0 || tagName != other->tagName)
  11792. {
  11793. return false;
  11794. }
  11795. if (ignoreOrderOfAttributes)
  11796. {
  11797. int totalAtts = 0;
  11798. const XmlAttributeNode* att = attributes;
  11799. while (att != 0)
  11800. {
  11801. if (! other->compareAttribute (att->name, att->value))
  11802. return false;
  11803. att = att->next;
  11804. ++totalAtts;
  11805. }
  11806. if (totalAtts != other->getNumAttributes())
  11807. return false;
  11808. }
  11809. else
  11810. {
  11811. const XmlAttributeNode* thisAtt = attributes;
  11812. const XmlAttributeNode* otherAtt = other->attributes;
  11813. for (;;)
  11814. {
  11815. if (thisAtt == 0 || otherAtt == 0)
  11816. {
  11817. if (thisAtt == otherAtt) // both 0, so it's a match
  11818. break;
  11819. return false;
  11820. }
  11821. if (thisAtt->name != otherAtt->name
  11822. || thisAtt->value != otherAtt->value)
  11823. {
  11824. return false;
  11825. }
  11826. thisAtt = thisAtt->next;
  11827. otherAtt = otherAtt->next;
  11828. }
  11829. }
  11830. const XmlElement* thisChild = firstChildElement;
  11831. const XmlElement* otherChild = other->firstChildElement;
  11832. for (;;)
  11833. {
  11834. if (thisChild == 0 || otherChild == 0)
  11835. {
  11836. if (thisChild == otherChild) // both 0, so it's a match
  11837. break;
  11838. return false;
  11839. }
  11840. if (! thisChild->isEquivalentTo (otherChild, ignoreOrderOfAttributes))
  11841. return false;
  11842. thisChild = thisChild->nextElement;
  11843. otherChild = otherChild->nextElement;
  11844. }
  11845. }
  11846. return true;
  11847. }
  11848. void XmlElement::deleteAllChildElements() throw()
  11849. {
  11850. while (firstChildElement != 0)
  11851. {
  11852. XmlElement* const nextChild = firstChildElement->nextElement;
  11853. delete firstChildElement;
  11854. firstChildElement = nextChild;
  11855. }
  11856. }
  11857. void XmlElement::deleteAllChildElementsWithTagName (const String& name) throw()
  11858. {
  11859. XmlElement* child = firstChildElement;
  11860. while (child != 0)
  11861. {
  11862. if (child->hasTagName (name))
  11863. {
  11864. XmlElement* const nextChild = child->nextElement;
  11865. removeChildElement (child, true);
  11866. child = nextChild;
  11867. }
  11868. else
  11869. {
  11870. child = child->nextElement;
  11871. }
  11872. }
  11873. }
  11874. bool XmlElement::containsChildElement (const XmlElement* const possibleChild) const throw()
  11875. {
  11876. const XmlElement* child = firstChildElement;
  11877. while (child != 0)
  11878. {
  11879. if (child == possibleChild)
  11880. return true;
  11881. child = child->nextElement;
  11882. }
  11883. return false;
  11884. }
  11885. XmlElement* XmlElement::findParentElementOf (const XmlElement* const elementToLookFor) throw()
  11886. {
  11887. if (this == elementToLookFor || elementToLookFor == 0)
  11888. return 0;
  11889. XmlElement* child = firstChildElement;
  11890. while (child != 0)
  11891. {
  11892. if (elementToLookFor == child)
  11893. return this;
  11894. XmlElement* const found = child->findParentElementOf (elementToLookFor);
  11895. if (found != 0)
  11896. return found;
  11897. child = child->nextElement;
  11898. }
  11899. return 0;
  11900. }
  11901. void XmlElement::getChildElementsAsArray (XmlElement** elems) const throw()
  11902. {
  11903. XmlElement* e = firstChildElement;
  11904. while (e != 0)
  11905. {
  11906. *elems++ = e;
  11907. e = e->nextElement;
  11908. }
  11909. }
  11910. void XmlElement::reorderChildElements (XmlElement** const elems, const int num) throw()
  11911. {
  11912. XmlElement* e = firstChildElement = elems[0];
  11913. for (int i = 1; i < num; ++i)
  11914. {
  11915. e->nextElement = elems[i];
  11916. e = e->nextElement;
  11917. }
  11918. e->nextElement = 0;
  11919. }
  11920. bool XmlElement::isTextElement() const throw()
  11921. {
  11922. return tagName.isEmpty();
  11923. }
  11924. static const juce_wchar* const juce_xmltextContentAttributeName = L"text";
  11925. const String XmlElement::getText() const throw()
  11926. {
  11927. jassert (isTextElement()); // you're trying to get the text from an element that
  11928. // isn't actually a text element.. If this contains text sub-nodes, you
  11929. // probably want to use getAllSubText instead.
  11930. return getStringAttribute (juce_xmltextContentAttributeName);
  11931. }
  11932. void XmlElement::setText (const String& newText) throw()
  11933. {
  11934. if (isTextElement())
  11935. {
  11936. setAttribute (juce_xmltextContentAttributeName, newText);
  11937. }
  11938. else
  11939. {
  11940. jassertfalse // you can only change the text in a text element, not a normal one.
  11941. }
  11942. }
  11943. const String XmlElement::getAllSubText() const throw()
  11944. {
  11945. String result;
  11946. String::Concatenator concatenator (result);
  11947. const XmlElement* child = firstChildElement;
  11948. while (child != 0)
  11949. {
  11950. if (child->isTextElement())
  11951. concatenator.append (child->getText());
  11952. child = child->nextElement;
  11953. }
  11954. return result;
  11955. }
  11956. const String XmlElement::getChildElementAllSubText (const String& childTagName,
  11957. const String& defaultReturnValue) const throw()
  11958. {
  11959. const XmlElement* const child = getChildByName (childTagName);
  11960. if (child != 0)
  11961. return child->getAllSubText();
  11962. return defaultReturnValue;
  11963. }
  11964. XmlElement* XmlElement::createTextElement (const String& text) throw()
  11965. {
  11966. XmlElement* const e = new XmlElement ((int) 0);
  11967. e->setAttribute (juce_xmltextContentAttributeName, text);
  11968. return e;
  11969. }
  11970. void XmlElement::addTextElement (const String& text) throw()
  11971. {
  11972. addChildElement (createTextElement (text));
  11973. }
  11974. void XmlElement::deleteAllTextElements() throw()
  11975. {
  11976. XmlElement* child = firstChildElement;
  11977. while (child != 0)
  11978. {
  11979. XmlElement* const next = child->nextElement;
  11980. if (child->isTextElement())
  11981. removeChildElement (child, true);
  11982. child = next;
  11983. }
  11984. }
  11985. END_JUCE_NAMESPACE
  11986. /*** End of inlined file: juce_XmlElement.cpp ***/
  11987. /*** Start of inlined file: juce_ReadWriteLock.cpp ***/
  11988. BEGIN_JUCE_NAMESPACE
  11989. ReadWriteLock::ReadWriteLock() throw()
  11990. : numWaitingWriters (0),
  11991. numWriters (0),
  11992. writerThreadId (0)
  11993. {
  11994. }
  11995. ReadWriteLock::~ReadWriteLock() throw()
  11996. {
  11997. jassert (readerThreads.size() == 0);
  11998. jassert (numWriters == 0);
  11999. }
  12000. void ReadWriteLock::enterRead() const throw()
  12001. {
  12002. const Thread::ThreadID threadId = Thread::getCurrentThreadId();
  12003. const ScopedLock sl (accessLock);
  12004. for (;;)
  12005. {
  12006. jassert (readerThreads.size() % 2 == 0);
  12007. int i;
  12008. for (i = 0; i < readerThreads.size(); i += 2)
  12009. if (readerThreads.getUnchecked(i) == threadId)
  12010. break;
  12011. if (i < readerThreads.size()
  12012. || numWriters + numWaitingWriters == 0
  12013. || (threadId == writerThreadId && numWriters > 0))
  12014. {
  12015. if (i < readerThreads.size())
  12016. {
  12017. readerThreads.set (i + 1, (Thread::ThreadID) (1 + (pointer_sized_int) readerThreads.getUnchecked (i + 1)));
  12018. }
  12019. else
  12020. {
  12021. readerThreads.add (threadId);
  12022. readerThreads.add ((Thread::ThreadID) 1);
  12023. }
  12024. return;
  12025. }
  12026. const ScopedUnlock ul (accessLock);
  12027. waitEvent.wait (100);
  12028. }
  12029. }
  12030. void ReadWriteLock::exitRead() const throw()
  12031. {
  12032. const Thread::ThreadID threadId = Thread::getCurrentThreadId();
  12033. const ScopedLock sl (accessLock);
  12034. for (int i = 0; i < readerThreads.size(); i += 2)
  12035. {
  12036. if (readerThreads.getUnchecked(i) == threadId)
  12037. {
  12038. const pointer_sized_int newCount = ((pointer_sized_int) readerThreads.getUnchecked (i + 1)) - 1;
  12039. if (newCount == 0)
  12040. {
  12041. readerThreads.removeRange (i, 2);
  12042. waitEvent.signal();
  12043. }
  12044. else
  12045. {
  12046. readerThreads.set (i + 1, (Thread::ThreadID) newCount);
  12047. }
  12048. return;
  12049. }
  12050. }
  12051. jassertfalse // unlocking a lock that wasn't locked..
  12052. }
  12053. void ReadWriteLock::enterWrite() const throw()
  12054. {
  12055. const Thread::ThreadID threadId = Thread::getCurrentThreadId();
  12056. const ScopedLock sl (accessLock);
  12057. for (;;)
  12058. {
  12059. if (readerThreads.size() + numWriters == 0
  12060. || threadId == writerThreadId
  12061. || (readerThreads.size() == 2
  12062. && readerThreads.getUnchecked(0) == threadId))
  12063. {
  12064. writerThreadId = threadId;
  12065. ++numWriters;
  12066. break;
  12067. }
  12068. ++numWaitingWriters;
  12069. accessLock.exit();
  12070. waitEvent.wait (100);
  12071. accessLock.enter();
  12072. --numWaitingWriters;
  12073. }
  12074. }
  12075. bool ReadWriteLock::tryEnterWrite() const throw()
  12076. {
  12077. const Thread::ThreadID threadId = Thread::getCurrentThreadId();
  12078. const ScopedLock sl (accessLock);
  12079. if (readerThreads.size() + numWriters == 0
  12080. || threadId == writerThreadId
  12081. || (readerThreads.size() == 2
  12082. && readerThreads.getUnchecked(0) == threadId))
  12083. {
  12084. writerThreadId = threadId;
  12085. ++numWriters;
  12086. return true;
  12087. }
  12088. return false;
  12089. }
  12090. void ReadWriteLock::exitWrite() const throw()
  12091. {
  12092. const ScopedLock sl (accessLock);
  12093. // check this thread actually had the lock..
  12094. jassert (numWriters > 0 && writerThreadId == Thread::getCurrentThreadId());
  12095. if (--numWriters == 0)
  12096. {
  12097. writerThreadId = 0;
  12098. waitEvent.signal();
  12099. }
  12100. }
  12101. END_JUCE_NAMESPACE
  12102. /*** End of inlined file: juce_ReadWriteLock.cpp ***/
  12103. /*** Start of inlined file: juce_Thread.cpp ***/
  12104. BEGIN_JUCE_NAMESPACE
  12105. // these functions are implemented in the platform-specific code.
  12106. void* juce_createThread (void* userData);
  12107. void juce_killThread (void* handle);
  12108. bool juce_setThreadPriority (void* handle, int priority);
  12109. void juce_setCurrentThreadName (const String& name);
  12110. #if JUCE_WIN32
  12111. void juce_CloseThreadHandle (void* handle);
  12112. #endif
  12113. void Thread::threadEntryPoint (Thread* const thread)
  12114. {
  12115. {
  12116. const ScopedLock sl (runningThreadsLock);
  12117. runningThreads.add (thread);
  12118. }
  12119. JUCE_TRY
  12120. {
  12121. thread->threadId_ = Thread::getCurrentThreadId();
  12122. if (thread->threadName_.isNotEmpty())
  12123. juce_setCurrentThreadName (thread->threadName_);
  12124. if (thread->startSuspensionEvent_.wait (10000))
  12125. {
  12126. if (thread->affinityMask_ != 0)
  12127. setCurrentThreadAffinityMask (thread->affinityMask_);
  12128. thread->run();
  12129. }
  12130. }
  12131. JUCE_CATCH_ALL_ASSERT
  12132. {
  12133. const ScopedLock sl (runningThreadsLock);
  12134. jassert (runningThreads.contains (thread));
  12135. runningThreads.removeValue (thread);
  12136. }
  12137. #if JUCE_WIN32
  12138. juce_CloseThreadHandle (thread->threadHandle_);
  12139. #endif
  12140. thread->threadHandle_ = 0;
  12141. thread->threadId_ = 0;
  12142. }
  12143. // used to wrap the incoming call from the platform-specific code
  12144. void JUCE_API juce_threadEntryPoint (void* userData)
  12145. {
  12146. Thread::threadEntryPoint (static_cast <Thread*> (userData));
  12147. }
  12148. Thread::Thread (const String& threadName)
  12149. : threadName_ (threadName),
  12150. threadHandle_ (0),
  12151. threadPriority_ (5),
  12152. threadId_ (0),
  12153. affinityMask_ (0),
  12154. threadShouldExit_ (false)
  12155. {
  12156. }
  12157. Thread::~Thread()
  12158. {
  12159. stopThread (100);
  12160. }
  12161. void Thread::startThread()
  12162. {
  12163. const ScopedLock sl (startStopLock);
  12164. threadShouldExit_ = false;
  12165. if (threadHandle_ == 0)
  12166. {
  12167. threadHandle_ = juce_createThread (this);
  12168. juce_setThreadPriority (threadHandle_, threadPriority_);
  12169. startSuspensionEvent_.signal();
  12170. }
  12171. }
  12172. void Thread::startThread (const int priority)
  12173. {
  12174. const ScopedLock sl (startStopLock);
  12175. if (threadHandle_ == 0)
  12176. {
  12177. threadPriority_ = priority;
  12178. startThread();
  12179. }
  12180. else
  12181. {
  12182. setPriority (priority);
  12183. }
  12184. }
  12185. bool Thread::isThreadRunning() const
  12186. {
  12187. return threadHandle_ != 0;
  12188. }
  12189. void Thread::signalThreadShouldExit()
  12190. {
  12191. threadShouldExit_ = true;
  12192. }
  12193. bool Thread::waitForThreadToExit (const int timeOutMilliseconds) const
  12194. {
  12195. // Doh! So how exactly do you expect this thread to wait for itself to stop??
  12196. jassert (getThreadId() != getCurrentThreadId());
  12197. const int sleepMsPerIteration = 5;
  12198. int count = timeOutMilliseconds / sleepMsPerIteration;
  12199. while (isThreadRunning())
  12200. {
  12201. if (timeOutMilliseconds > 0 && --count < 0)
  12202. return false;
  12203. sleep (sleepMsPerIteration);
  12204. }
  12205. return true;
  12206. }
  12207. void Thread::stopThread (const int timeOutMilliseconds)
  12208. {
  12209. // agh! You can't stop the thread that's calling this method! How on earth
  12210. // would that work??
  12211. jassert (getCurrentThreadId() != getThreadId());
  12212. const ScopedLock sl (startStopLock);
  12213. if (isThreadRunning())
  12214. {
  12215. signalThreadShouldExit();
  12216. notify();
  12217. if (timeOutMilliseconds != 0)
  12218. waitForThreadToExit (timeOutMilliseconds);
  12219. if (isThreadRunning())
  12220. {
  12221. // very bad karma if this point is reached, as
  12222. // there are bound to be locks and events left in
  12223. // silly states when a thread is killed by force..
  12224. jassertfalse
  12225. Logger::writeToLog ("!! killing thread by force !!");
  12226. juce_killThread (threadHandle_);
  12227. threadHandle_ = 0;
  12228. threadId_ = 0;
  12229. const ScopedLock sl2 (runningThreadsLock);
  12230. runningThreads.removeValue (this);
  12231. }
  12232. }
  12233. }
  12234. bool Thread::setPriority (const int priority)
  12235. {
  12236. const ScopedLock sl (startStopLock);
  12237. const bool worked = juce_setThreadPriority (threadHandle_, priority);
  12238. if (worked)
  12239. threadPriority_ = priority;
  12240. return worked;
  12241. }
  12242. bool Thread::setCurrentThreadPriority (const int priority)
  12243. {
  12244. return juce_setThreadPriority (0, priority);
  12245. }
  12246. void Thread::setAffinityMask (const uint32 affinityMask)
  12247. {
  12248. affinityMask_ = affinityMask;
  12249. }
  12250. bool Thread::wait (const int timeOutMilliseconds) const
  12251. {
  12252. return defaultEvent_.wait (timeOutMilliseconds);
  12253. }
  12254. void Thread::notify() const
  12255. {
  12256. defaultEvent_.signal();
  12257. }
  12258. int Thread::getNumRunningThreads()
  12259. {
  12260. return runningThreads.size();
  12261. }
  12262. Thread* Thread::getCurrentThread()
  12263. {
  12264. const ThreadID thisId = getCurrentThreadId();
  12265. const ScopedLock sl (runningThreadsLock);
  12266. for (int i = runningThreads.size(); --i >= 0;)
  12267. {
  12268. Thread* const t = runningThreads.getUnchecked(i);
  12269. if (t->threadId_ == thisId)
  12270. return t;
  12271. }
  12272. return 0;
  12273. }
  12274. void Thread::stopAllThreads (const int timeOutMilliseconds)
  12275. {
  12276. {
  12277. const ScopedLock sl (runningThreadsLock);
  12278. for (int i = runningThreads.size(); --i >= 0;)
  12279. runningThreads.getUnchecked(i)->signalThreadShouldExit();
  12280. }
  12281. for (;;)
  12282. {
  12283. Thread* firstThread;
  12284. {
  12285. const ScopedLock sl (runningThreadsLock);
  12286. firstThread = runningThreads.getFirst();
  12287. }
  12288. if (firstThread == 0)
  12289. break;
  12290. firstThread->stopThread (timeOutMilliseconds);
  12291. }
  12292. }
  12293. Array<Thread*> Thread::runningThreads;
  12294. CriticalSection Thread::runningThreadsLock;
  12295. END_JUCE_NAMESPACE
  12296. /*** End of inlined file: juce_Thread.cpp ***/
  12297. /*** Start of inlined file: juce_ThreadPool.cpp ***/
  12298. BEGIN_JUCE_NAMESPACE
  12299. ThreadPoolJob::ThreadPoolJob (const String& name)
  12300. : jobName (name),
  12301. pool (0),
  12302. shouldStop (false),
  12303. isActive (false),
  12304. shouldBeDeleted (false)
  12305. {
  12306. }
  12307. ThreadPoolJob::~ThreadPoolJob()
  12308. {
  12309. // you mustn't delete a job while it's still in a pool! Use ThreadPool::removeJob()
  12310. // to remove it first!
  12311. jassert (pool == 0 || ! pool->contains (this));
  12312. }
  12313. const String ThreadPoolJob::getJobName() const
  12314. {
  12315. return jobName;
  12316. }
  12317. void ThreadPoolJob::setJobName (const String& newName)
  12318. {
  12319. jobName = newName;
  12320. }
  12321. void ThreadPoolJob::signalJobShouldExit()
  12322. {
  12323. shouldStop = true;
  12324. }
  12325. class ThreadPool::ThreadPoolThread : public Thread
  12326. {
  12327. public:
  12328. ThreadPoolThread (ThreadPool& pool_)
  12329. : Thread ("Pool"),
  12330. pool (pool_),
  12331. busy (false)
  12332. {
  12333. }
  12334. ~ThreadPoolThread()
  12335. {
  12336. }
  12337. void run()
  12338. {
  12339. while (! threadShouldExit())
  12340. {
  12341. if (! pool.runNextJob())
  12342. wait (500);
  12343. }
  12344. }
  12345. private:
  12346. ThreadPool& pool;
  12347. bool volatile busy;
  12348. ThreadPoolThread (const ThreadPoolThread&);
  12349. ThreadPoolThread& operator= (const ThreadPoolThread&);
  12350. };
  12351. ThreadPool::ThreadPool (const int numThreads,
  12352. const bool startThreadsOnlyWhenNeeded,
  12353. const int stopThreadsWhenNotUsedTimeoutMs)
  12354. : threadStopTimeout (stopThreadsWhenNotUsedTimeoutMs),
  12355. priority (5)
  12356. {
  12357. jassert (numThreads > 0); // not much point having one of these with no threads in it.
  12358. for (int i = jmax (1, numThreads); --i >= 0;)
  12359. threads.add (new ThreadPoolThread (*this));
  12360. if (! startThreadsOnlyWhenNeeded)
  12361. for (int i = threads.size(); --i >= 0;)
  12362. threads.getUnchecked(i)->startThread (priority);
  12363. }
  12364. ThreadPool::~ThreadPool()
  12365. {
  12366. removeAllJobs (true, 4000);
  12367. int i;
  12368. for (i = threads.size(); --i >= 0;)
  12369. threads.getUnchecked(i)->signalThreadShouldExit();
  12370. for (i = threads.size(); --i >= 0;)
  12371. threads.getUnchecked(i)->stopThread (500);
  12372. }
  12373. void ThreadPool::addJob (ThreadPoolJob* const job)
  12374. {
  12375. jassert (job != 0);
  12376. jassert (job->pool == 0);
  12377. if (job->pool == 0)
  12378. {
  12379. job->pool = this;
  12380. job->shouldStop = false;
  12381. job->isActive = false;
  12382. {
  12383. const ScopedLock sl (lock);
  12384. jobs.add (job);
  12385. int numRunning = 0;
  12386. for (int i = threads.size(); --i >= 0;)
  12387. if (threads.getUnchecked(i)->isThreadRunning() && ! threads.getUnchecked(i)->threadShouldExit())
  12388. ++numRunning;
  12389. if (numRunning < threads.size())
  12390. {
  12391. bool startedOne = false;
  12392. int n = 1000;
  12393. while (--n >= 0 && ! startedOne)
  12394. {
  12395. for (int i = threads.size(); --i >= 0;)
  12396. {
  12397. if (! threads.getUnchecked(i)->isThreadRunning())
  12398. {
  12399. threads.getUnchecked(i)->startThread (priority);
  12400. startedOne = true;
  12401. break;
  12402. }
  12403. }
  12404. if (! startedOne)
  12405. Thread::sleep (2);
  12406. }
  12407. }
  12408. }
  12409. for (int i = threads.size(); --i >= 0;)
  12410. threads.getUnchecked(i)->notify();
  12411. }
  12412. }
  12413. int ThreadPool::getNumJobs() const
  12414. {
  12415. return jobs.size();
  12416. }
  12417. ThreadPoolJob* ThreadPool::getJob (const int index) const
  12418. {
  12419. const ScopedLock sl (lock);
  12420. return jobs [index];
  12421. }
  12422. bool ThreadPool::contains (const ThreadPoolJob* const job) const
  12423. {
  12424. const ScopedLock sl (lock);
  12425. return jobs.contains (const_cast <ThreadPoolJob*> (job));
  12426. }
  12427. bool ThreadPool::isJobRunning (const ThreadPoolJob* const job) const
  12428. {
  12429. const ScopedLock sl (lock);
  12430. return jobs.contains (const_cast <ThreadPoolJob*> (job)) && job->isActive;
  12431. }
  12432. bool ThreadPool::waitForJobToFinish (const ThreadPoolJob* const job,
  12433. const int timeOutMs) const
  12434. {
  12435. if (job != 0)
  12436. {
  12437. const uint32 start = Time::getMillisecondCounter();
  12438. while (contains (job))
  12439. {
  12440. if (timeOutMs >= 0 && Time::getMillisecondCounter() >= start + timeOutMs)
  12441. return false;
  12442. jobFinishedSignal.wait (2);
  12443. }
  12444. }
  12445. return true;
  12446. }
  12447. bool ThreadPool::removeJob (ThreadPoolJob* const job,
  12448. const bool interruptIfRunning,
  12449. const int timeOutMs)
  12450. {
  12451. bool dontWait = true;
  12452. if (job != 0)
  12453. {
  12454. const ScopedLock sl (lock);
  12455. if (jobs.contains (job))
  12456. {
  12457. if (job->isActive)
  12458. {
  12459. if (interruptIfRunning)
  12460. job->signalJobShouldExit();
  12461. dontWait = false;
  12462. }
  12463. else
  12464. {
  12465. jobs.removeValue (job);
  12466. }
  12467. }
  12468. }
  12469. return dontWait || waitForJobToFinish (job, timeOutMs);
  12470. }
  12471. bool ThreadPool::removeAllJobs (const bool interruptRunningJobs,
  12472. const int timeOutMs,
  12473. const bool deleteInactiveJobs,
  12474. ThreadPool::JobSelector* selectedJobsToRemove)
  12475. {
  12476. Array <ThreadPoolJob*> jobsToWaitFor;
  12477. {
  12478. const ScopedLock sl (lock);
  12479. for (int i = jobs.size(); --i >= 0;)
  12480. {
  12481. ThreadPoolJob* const job = jobs.getUnchecked(i);
  12482. if (selectedJobsToRemove == 0 || selectedJobsToRemove->isJobSuitable (job))
  12483. {
  12484. if (job->isActive)
  12485. {
  12486. jobsToWaitFor.add (job);
  12487. if (interruptRunningJobs)
  12488. job->signalJobShouldExit();
  12489. }
  12490. else
  12491. {
  12492. jobs.remove (i);
  12493. if (deleteInactiveJobs)
  12494. delete job;
  12495. }
  12496. }
  12497. }
  12498. }
  12499. const uint32 start = Time::getMillisecondCounter();
  12500. for (;;)
  12501. {
  12502. for (int i = jobsToWaitFor.size(); --i >= 0;)
  12503. if (! isJobRunning (jobsToWaitFor.getUnchecked (i)))
  12504. jobsToWaitFor.remove (i);
  12505. if (jobsToWaitFor.size() == 0)
  12506. break;
  12507. if (timeOutMs >= 0 && Time::getMillisecondCounter() >= start + timeOutMs)
  12508. return false;
  12509. jobFinishedSignal.wait (20);
  12510. }
  12511. return true;
  12512. }
  12513. const StringArray ThreadPool::getNamesOfAllJobs (const bool onlyReturnActiveJobs) const
  12514. {
  12515. StringArray s;
  12516. const ScopedLock sl (lock);
  12517. for (int i = 0; i < jobs.size(); ++i)
  12518. {
  12519. const ThreadPoolJob* const job = jobs.getUnchecked(i);
  12520. if (job->isActive || ! onlyReturnActiveJobs)
  12521. s.add (job->getJobName());
  12522. }
  12523. return s;
  12524. }
  12525. bool ThreadPool::setThreadPriorities (const int newPriority)
  12526. {
  12527. bool ok = true;
  12528. if (priority != newPriority)
  12529. {
  12530. priority = newPriority;
  12531. for (int i = threads.size(); --i >= 0;)
  12532. if (! threads.getUnchecked(i)->setPriority (newPriority))
  12533. ok = false;
  12534. }
  12535. return ok;
  12536. }
  12537. bool ThreadPool::runNextJob()
  12538. {
  12539. ThreadPoolJob* job = 0;
  12540. {
  12541. const ScopedLock sl (lock);
  12542. for (int i = 0; i < jobs.size(); ++i)
  12543. {
  12544. job = jobs[i];
  12545. if (job != 0 && ! (job->isActive || job->shouldStop))
  12546. break;
  12547. job = 0;
  12548. }
  12549. if (job != 0)
  12550. job->isActive = true;
  12551. }
  12552. if (job != 0)
  12553. {
  12554. JUCE_TRY
  12555. {
  12556. ThreadPoolJob::JobStatus result = job->runJob();
  12557. lastJobEndTime = Time::getApproximateMillisecondCounter();
  12558. const ScopedLock sl (lock);
  12559. if (jobs.contains (job))
  12560. {
  12561. job->isActive = false;
  12562. if (result != ThreadPoolJob::jobNeedsRunningAgain || job->shouldStop)
  12563. {
  12564. job->pool = 0;
  12565. job->shouldStop = true;
  12566. jobs.removeValue (job);
  12567. if (result == ThreadPoolJob::jobHasFinishedAndShouldBeDeleted)
  12568. delete job;
  12569. jobFinishedSignal.signal();
  12570. }
  12571. else
  12572. {
  12573. // move the job to the end of the queue if it wants another go
  12574. jobs.move (jobs.indexOf (job), -1);
  12575. }
  12576. }
  12577. }
  12578. #if JUCE_CATCH_UNHANDLED_EXCEPTIONS
  12579. catch (...)
  12580. {
  12581. const ScopedLock sl (lock);
  12582. jobs.removeValue (job);
  12583. }
  12584. #endif
  12585. }
  12586. else
  12587. {
  12588. if (threadStopTimeout > 0
  12589. && Time::getApproximateMillisecondCounter() > lastJobEndTime + threadStopTimeout)
  12590. {
  12591. const ScopedLock sl (lock);
  12592. if (jobs.size() == 0)
  12593. for (int i = threads.size(); --i >= 0;)
  12594. threads.getUnchecked(i)->signalThreadShouldExit();
  12595. }
  12596. else
  12597. {
  12598. return false;
  12599. }
  12600. }
  12601. return true;
  12602. }
  12603. END_JUCE_NAMESPACE
  12604. /*** End of inlined file: juce_ThreadPool.cpp ***/
  12605. /*** Start of inlined file: juce_TimeSliceThread.cpp ***/
  12606. BEGIN_JUCE_NAMESPACE
  12607. TimeSliceThread::TimeSliceThread (const String& threadName)
  12608. : Thread (threadName),
  12609. index (0),
  12610. clientBeingCalled (0),
  12611. clientsChanged (false)
  12612. {
  12613. }
  12614. TimeSliceThread::~TimeSliceThread()
  12615. {
  12616. stopThread (2000);
  12617. }
  12618. void TimeSliceThread::addTimeSliceClient (TimeSliceClient* const client)
  12619. {
  12620. const ScopedLock sl (listLock);
  12621. clients.addIfNotAlreadyThere (client);
  12622. clientsChanged = true;
  12623. notify();
  12624. }
  12625. void TimeSliceThread::removeTimeSliceClient (TimeSliceClient* const client)
  12626. {
  12627. const ScopedLock sl1 (listLock);
  12628. clientsChanged = true;
  12629. // if there's a chance we're in the middle of calling this client, we need to
  12630. // also lock the outer lock..
  12631. if (clientBeingCalled == client)
  12632. {
  12633. const ScopedUnlock ul (listLock); // unlock first to get the order right..
  12634. const ScopedLock sl2 (callbackLock);
  12635. const ScopedLock sl3 (listLock);
  12636. clients.removeValue (client);
  12637. }
  12638. else
  12639. {
  12640. clients.removeValue (client);
  12641. }
  12642. }
  12643. int TimeSliceThread::getNumClients() const
  12644. {
  12645. return clients.size();
  12646. }
  12647. TimeSliceClient* TimeSliceThread::getClient (const int i) const
  12648. {
  12649. const ScopedLock sl (listLock);
  12650. return clients [i];
  12651. }
  12652. void TimeSliceThread::run()
  12653. {
  12654. int numCallsSinceBusy = 0;
  12655. while (! threadShouldExit())
  12656. {
  12657. int timeToWait = 500;
  12658. {
  12659. const ScopedLock sl (callbackLock);
  12660. {
  12661. const ScopedLock sl2 (listLock);
  12662. if (clients.size() > 0)
  12663. {
  12664. index = (index + 1) % clients.size();
  12665. clientBeingCalled = clients [index];
  12666. }
  12667. else
  12668. {
  12669. index = 0;
  12670. clientBeingCalled = 0;
  12671. }
  12672. if (clientsChanged)
  12673. {
  12674. clientsChanged = false;
  12675. numCallsSinceBusy = 0;
  12676. }
  12677. }
  12678. if (clientBeingCalled != 0)
  12679. {
  12680. if (clientBeingCalled->useTimeSlice())
  12681. numCallsSinceBusy = 0;
  12682. else
  12683. ++numCallsSinceBusy;
  12684. if (numCallsSinceBusy >= clients.size())
  12685. timeToWait = 500;
  12686. else if (index == 0)
  12687. timeToWait = 1; // throw in an occasional pause, to stop everything locking up
  12688. else
  12689. timeToWait = 0;
  12690. }
  12691. }
  12692. if (timeToWait > 0)
  12693. wait (timeToWait);
  12694. }
  12695. }
  12696. END_JUCE_NAMESPACE
  12697. /*** End of inlined file: juce_TimeSliceThread.cpp ***/
  12698. #endif
  12699. #if JUCE_BUILD_MISC
  12700. /*** Start of inlined file: juce_ValueTree.cpp ***/
  12701. BEGIN_JUCE_NAMESPACE
  12702. class ValueTree::SetPropertyAction : public UndoableAction
  12703. {
  12704. public:
  12705. SetPropertyAction (const SharedObjectPtr& target_, const var::identifier& name_,
  12706. const var& newValue_, const bool isAddingNewProperty_, const bool isDeletingProperty_)
  12707. : target (target_), name (name_), newValue (newValue_),
  12708. isAddingNewProperty (isAddingNewProperty_),
  12709. isDeletingProperty (isDeletingProperty_)
  12710. {
  12711. if (! isAddingNewProperty)
  12712. oldValue = target_->getProperty (name_);
  12713. }
  12714. ~SetPropertyAction() {}
  12715. bool perform()
  12716. {
  12717. jassert (! (isAddingNewProperty && target->hasProperty (name)));
  12718. if (isDeletingProperty)
  12719. target->removeProperty (name, 0);
  12720. else
  12721. target->setProperty (name, newValue, 0);
  12722. return true;
  12723. }
  12724. bool undo()
  12725. {
  12726. if (isAddingNewProperty)
  12727. target->removeProperty (name, 0);
  12728. else
  12729. target->setProperty (name, oldValue, 0);
  12730. return true;
  12731. }
  12732. int getSizeInUnits()
  12733. {
  12734. return (int) sizeof (*this); //xxx should be more accurate
  12735. }
  12736. private:
  12737. const SharedObjectPtr target;
  12738. const var::identifier name;
  12739. const var newValue;
  12740. var oldValue;
  12741. const bool isAddingNewProperty, isDeletingProperty;
  12742. SetPropertyAction (const SetPropertyAction&);
  12743. SetPropertyAction& operator= (const SetPropertyAction&);
  12744. };
  12745. class ValueTree::AddOrRemoveChildAction : public UndoableAction
  12746. {
  12747. public:
  12748. AddOrRemoveChildAction (const SharedObjectPtr& target_, const int childIndex_,
  12749. const SharedObjectPtr& newChild_)
  12750. : target (target_),
  12751. child (newChild_ != 0 ? newChild_ : target_->children [childIndex_]),
  12752. childIndex (childIndex_),
  12753. isDeleting (newChild_ == 0)
  12754. {
  12755. jassert (child != 0);
  12756. }
  12757. ~AddOrRemoveChildAction() {}
  12758. bool perform()
  12759. {
  12760. if (isDeleting)
  12761. target->removeChild (childIndex, 0);
  12762. else
  12763. target->addChild (child, childIndex, 0);
  12764. return true;
  12765. }
  12766. bool undo()
  12767. {
  12768. if (isDeleting)
  12769. {
  12770. target->addChild (child, childIndex, 0);
  12771. }
  12772. else
  12773. {
  12774. // If you hit this, it seems that your object's state is getting confused - probably
  12775. // because you've interleaved some undoable and non-undoable operations?
  12776. jassert (childIndex < target->children.size());
  12777. target->removeChild (childIndex, 0);
  12778. }
  12779. return true;
  12780. }
  12781. int getSizeInUnits()
  12782. {
  12783. return (int) sizeof (*this); //xxx should be more accurate
  12784. }
  12785. private:
  12786. const SharedObjectPtr target, child;
  12787. const int childIndex;
  12788. const bool isDeleting;
  12789. AddOrRemoveChildAction (const AddOrRemoveChildAction&);
  12790. AddOrRemoveChildAction& operator= (const AddOrRemoveChildAction&);
  12791. };
  12792. class ValueTree::MoveChildAction : public UndoableAction
  12793. {
  12794. public:
  12795. MoveChildAction (const SharedObjectPtr& target_,
  12796. const int startIndex_, const int endIndex_)
  12797. : target (target_),
  12798. startIndex (startIndex_),
  12799. endIndex (endIndex_)
  12800. {
  12801. }
  12802. ~MoveChildAction() {}
  12803. bool perform()
  12804. {
  12805. target->moveChild (startIndex, endIndex, 0);
  12806. return true;
  12807. }
  12808. bool undo()
  12809. {
  12810. target->moveChild (endIndex, startIndex, 0);
  12811. return true;
  12812. }
  12813. int getSizeInUnits()
  12814. {
  12815. return (int) sizeof (*this); //xxx should be more accurate
  12816. }
  12817. private:
  12818. const SharedObjectPtr target, child;
  12819. const int startIndex, endIndex;
  12820. MoveChildAction (const MoveChildAction&);
  12821. MoveChildAction& operator= (const MoveChildAction&);
  12822. };
  12823. ValueTree::SharedObject::SharedObject (const String& type_)
  12824. : type (type_), parent (0)
  12825. {
  12826. }
  12827. ValueTree::SharedObject::SharedObject (const SharedObject& other)
  12828. : type (other.type), properties (other.properties), parent (0)
  12829. {
  12830. for (int i = 0; i < other.children.size(); ++i)
  12831. {
  12832. SharedObject* const child = new SharedObject (*other.children.getUnchecked(i));
  12833. child->parent = this;
  12834. children.add (child);
  12835. }
  12836. }
  12837. ValueTree::SharedObject::~SharedObject()
  12838. {
  12839. jassert (parent == 0); // this should never happen unless something isn't obeying the ref-counting!
  12840. for (int i = children.size(); --i >= 0;)
  12841. {
  12842. const SharedObjectPtr c (children.getUnchecked(i));
  12843. c->parent = 0;
  12844. children.remove (i);
  12845. c->sendParentChangeMessage();
  12846. }
  12847. }
  12848. void ValueTree::SharedObject::sendPropertyChangeMessage (ValueTree& tree, const var::identifier& property)
  12849. {
  12850. for (int i = valueTreesWithListeners.size(); --i >= 0;)
  12851. {
  12852. ValueTree* const v = valueTreesWithListeners[i];
  12853. if (v != 0)
  12854. v->listeners.call (&ValueTree::Listener::valueTreePropertyChanged, tree, property);
  12855. }
  12856. }
  12857. void ValueTree::SharedObject::sendPropertyChangeMessage (const var::identifier& property)
  12858. {
  12859. ValueTree tree (this);
  12860. ValueTree::SharedObject* t = this;
  12861. while (t != 0)
  12862. {
  12863. t->sendPropertyChangeMessage (tree, property);
  12864. t = t->parent;
  12865. }
  12866. }
  12867. void ValueTree::SharedObject::sendChildChangeMessage (ValueTree& tree)
  12868. {
  12869. for (int i = valueTreesWithListeners.size(); --i >= 0;)
  12870. {
  12871. ValueTree* const v = valueTreesWithListeners[i];
  12872. if (v != 0)
  12873. v->listeners.call (&ValueTree::Listener::valueTreeChildrenChanged, tree);
  12874. }
  12875. }
  12876. void ValueTree::SharedObject::sendChildChangeMessage()
  12877. {
  12878. ValueTree tree (this);
  12879. ValueTree::SharedObject* t = this;
  12880. while (t != 0)
  12881. {
  12882. t->sendChildChangeMessage (tree);
  12883. t = t->parent;
  12884. }
  12885. }
  12886. void ValueTree::SharedObject::sendParentChangeMessage()
  12887. {
  12888. ValueTree tree (this);
  12889. int i;
  12890. for (i = children.size(); --i >= 0;)
  12891. {
  12892. SharedObject* const t = children[i];
  12893. if (t != 0)
  12894. t->sendParentChangeMessage();
  12895. }
  12896. for (i = valueTreesWithListeners.size(); --i >= 0;)
  12897. {
  12898. ValueTree* const v = valueTreesWithListeners[i];
  12899. if (v != 0)
  12900. v->listeners.call (&ValueTree::Listener::valueTreeParentChanged, tree);
  12901. }
  12902. }
  12903. const var& ValueTree::SharedObject::getProperty (const var::identifier& name) const
  12904. {
  12905. return properties [name];
  12906. }
  12907. const var ValueTree::SharedObject::getProperty (const var::identifier& name, const var& defaultReturnValue) const
  12908. {
  12909. return properties.getWithDefault (name, defaultReturnValue);
  12910. }
  12911. void ValueTree::SharedObject::setProperty (const var::identifier& name, const var& newValue, UndoManager* const undoManager)
  12912. {
  12913. if (undoManager == 0)
  12914. {
  12915. if (properties.set (name, newValue))
  12916. sendPropertyChangeMessage (name);
  12917. }
  12918. else
  12919. {
  12920. var* const existingValue = properties.getItem (name);
  12921. if (existingValue != 0)
  12922. {
  12923. if (*existingValue != newValue)
  12924. undoManager->perform (new SetPropertyAction (this, name, newValue, false, false));
  12925. }
  12926. else
  12927. {
  12928. undoManager->perform (new SetPropertyAction (this, name, newValue, true, false));
  12929. }
  12930. }
  12931. }
  12932. bool ValueTree::SharedObject::hasProperty (const var::identifier& name) const
  12933. {
  12934. return properties.contains (name);
  12935. }
  12936. void ValueTree::SharedObject::removeProperty (const var::identifier& name, UndoManager* const undoManager)
  12937. {
  12938. if (undoManager == 0)
  12939. {
  12940. if (properties.remove (name))
  12941. sendPropertyChangeMessage (name);
  12942. }
  12943. else
  12944. {
  12945. if (properties.contains (name))
  12946. undoManager->perform (new SetPropertyAction (this, name, var::null, false, true));
  12947. }
  12948. }
  12949. void ValueTree::SharedObject::removeAllProperties (UndoManager* const undoManager)
  12950. {
  12951. if (undoManager == 0)
  12952. {
  12953. while (properties.size() > 0)
  12954. {
  12955. const var::identifier name (properties.getName (properties.size() - 1));
  12956. properties.remove (name);
  12957. sendPropertyChangeMessage (name);
  12958. }
  12959. }
  12960. else
  12961. {
  12962. for (int i = properties.size(); --i >= 0;)
  12963. undoManager->perform (new SetPropertyAction (this, properties.getName(i), var::null, false, true));
  12964. }
  12965. }
  12966. ValueTree ValueTree::SharedObject::getChildWithName (const String& typeToMatch) const
  12967. {
  12968. for (int i = 0; i < children.size(); ++i)
  12969. if (children.getUnchecked(i)->type == typeToMatch)
  12970. return ValueTree (static_cast <SharedObject*> (children.getUnchecked(i)));
  12971. return ValueTree::invalid;
  12972. }
  12973. ValueTree ValueTree::SharedObject::getChildWithProperty (const var::identifier& propertyName, const var& propertyValue) const
  12974. {
  12975. for (int i = 0; i < children.size(); ++i)
  12976. if (children.getUnchecked(i)->getProperty (propertyName) == propertyValue)
  12977. return ValueTree (static_cast <SharedObject*> (children.getUnchecked(i)));
  12978. return ValueTree::invalid;
  12979. }
  12980. bool ValueTree::SharedObject::isAChildOf (const SharedObject* const possibleParent) const
  12981. {
  12982. const SharedObject* p = parent;
  12983. while (p != 0)
  12984. {
  12985. if (p == possibleParent)
  12986. return true;
  12987. p = p->parent;
  12988. }
  12989. return false;
  12990. }
  12991. int ValueTree::SharedObject::indexOf (const ValueTree& child) const
  12992. {
  12993. return children.indexOf (child.object);
  12994. }
  12995. void ValueTree::SharedObject::addChild (SharedObject* child, int index, UndoManager* const undoManager)
  12996. {
  12997. if (child != 0 && child->parent != this)
  12998. {
  12999. if (child != this && ! isAChildOf (child))
  13000. {
  13001. // You should always make sure that a child is removed from its previous parent before
  13002. // adding it somewhere else - otherwise, it's ambiguous as to whether a different
  13003. // undomanager should be used when removing it from its current parent..
  13004. jassert (child->parent == 0);
  13005. if (child->parent != 0)
  13006. {
  13007. jassert (child->parent->children.indexOf (child) >= 0);
  13008. child->parent->removeChild (child->parent->children.indexOf (child), undoManager);
  13009. }
  13010. if (undoManager == 0)
  13011. {
  13012. children.insert (index, child);
  13013. child->parent = this;
  13014. sendChildChangeMessage();
  13015. child->sendParentChangeMessage();
  13016. }
  13017. else
  13018. {
  13019. if (index < 0)
  13020. index = children.size();
  13021. undoManager->perform (new AddOrRemoveChildAction (this, index, child));
  13022. }
  13023. }
  13024. else
  13025. {
  13026. // You're attempting to create a recursive loop! A node
  13027. // can't be a child of one of its own children!
  13028. jassertfalse
  13029. }
  13030. }
  13031. }
  13032. void ValueTree::SharedObject::removeChild (const int childIndex, UndoManager* const undoManager)
  13033. {
  13034. const SharedObjectPtr child (children [childIndex]);
  13035. if (child != 0)
  13036. {
  13037. if (undoManager == 0)
  13038. {
  13039. children.remove (childIndex);
  13040. child->parent = 0;
  13041. sendChildChangeMessage();
  13042. child->sendParentChangeMessage();
  13043. }
  13044. else
  13045. {
  13046. undoManager->perform (new AddOrRemoveChildAction (this, childIndex, 0));
  13047. }
  13048. }
  13049. }
  13050. void ValueTree::SharedObject::removeAllChildren (UndoManager* const undoManager)
  13051. {
  13052. while (children.size() > 0)
  13053. removeChild (children.size() - 1, undoManager);
  13054. }
  13055. void ValueTree::SharedObject::moveChild (int currentIndex, int newIndex, UndoManager* undoManager)
  13056. {
  13057. // The source index must be a valid index!
  13058. jassert (((unsigned int) currentIndex) < (unsigned int) children.size());
  13059. if (currentIndex != newIndex
  13060. && ((unsigned int) currentIndex) < (unsigned int) children.size())
  13061. {
  13062. if (undoManager == 0)
  13063. {
  13064. children.move (currentIndex, newIndex);
  13065. sendChildChangeMessage();
  13066. }
  13067. else
  13068. {
  13069. if (((unsigned int) newIndex) >= (unsigned int) children.size())
  13070. newIndex = children.size() - 1;
  13071. undoManager->perform (new MoveChildAction (this, currentIndex, newIndex));
  13072. }
  13073. }
  13074. }
  13075. ValueTree::ValueTree() throw()
  13076. : object (0)
  13077. {
  13078. }
  13079. const ValueTree ValueTree::invalid;
  13080. ValueTree::ValueTree (const String& type_)
  13081. : object (new ValueTree::SharedObject (type_))
  13082. {
  13083. jassert (type_.isNotEmpty()); // All objects should be given a sensible type name!
  13084. }
  13085. ValueTree::ValueTree (SharedObject* const object_)
  13086. : object (object_)
  13087. {
  13088. }
  13089. ValueTree::ValueTree (const ValueTree& other)
  13090. : object (other.object)
  13091. {
  13092. }
  13093. ValueTree& ValueTree::operator= (const ValueTree& other)
  13094. {
  13095. if (listeners.size() > 0)
  13096. {
  13097. if (object != 0)
  13098. object->valueTreesWithListeners.removeValue (this);
  13099. if (other.object != 0)
  13100. other.object->valueTreesWithListeners.add (this);
  13101. }
  13102. object = other.object;
  13103. return *this;
  13104. }
  13105. ValueTree::~ValueTree()
  13106. {
  13107. if (listeners.size() > 0 && object != 0)
  13108. object->valueTreesWithListeners.removeValue (this);
  13109. }
  13110. bool ValueTree::operator== (const ValueTree& other) const
  13111. {
  13112. return object == other.object;
  13113. }
  13114. bool ValueTree::operator!= (const ValueTree& other) const
  13115. {
  13116. return object != other.object;
  13117. }
  13118. ValueTree ValueTree::createCopy() const
  13119. {
  13120. return ValueTree (object != 0 ? new SharedObject (*object) : 0);
  13121. }
  13122. bool ValueTree::hasType (const String& typeName) const
  13123. {
  13124. return object != 0 && object->type == typeName;
  13125. }
  13126. const String ValueTree::getType() const
  13127. {
  13128. return object != 0 ? object->type : String::empty;
  13129. }
  13130. ValueTree ValueTree::getParent() const
  13131. {
  13132. return ValueTree (object != 0 ? object->parent : (SharedObject*) 0);
  13133. }
  13134. const var& ValueTree::operator[] (const var::identifier& name) const
  13135. {
  13136. return object == 0 ? var::null : object->getProperty (name);
  13137. }
  13138. const var& ValueTree::getProperty (const var::identifier& name) const
  13139. {
  13140. return object == 0 ? var::null : object->getProperty (name);
  13141. }
  13142. const var ValueTree::getProperty (const var::identifier& name, const var& defaultReturnValue) const
  13143. {
  13144. return object == 0 ? defaultReturnValue : object->getProperty (name, defaultReturnValue);
  13145. }
  13146. void ValueTree::setProperty (const var::identifier& name, const var& newValue, UndoManager* const undoManager)
  13147. {
  13148. jassert (name.name.isNotEmpty());
  13149. if (object != 0 && name.name.isNotEmpty())
  13150. object->setProperty (name, newValue, undoManager);
  13151. }
  13152. bool ValueTree::hasProperty (const var::identifier& name) const
  13153. {
  13154. return object != 0 && object->hasProperty (name);
  13155. }
  13156. void ValueTree::removeProperty (const var::identifier& name, UndoManager* const undoManager)
  13157. {
  13158. if (object != 0)
  13159. object->removeProperty (name, undoManager);
  13160. }
  13161. void ValueTree::removeAllProperties (UndoManager* const undoManager)
  13162. {
  13163. if (object != 0)
  13164. object->removeAllProperties (undoManager);
  13165. }
  13166. int ValueTree::getNumProperties() const
  13167. {
  13168. return object == 0 ? 0 : object->properties.size();
  13169. }
  13170. const var::identifier ValueTree::getPropertyName (const int index) const
  13171. {
  13172. return object == 0 ? var::identifier()
  13173. : object->properties.getName (index);
  13174. }
  13175. class ValueTreePropertyValueSource : public Value::ValueSource,
  13176. public ValueTree::Listener
  13177. {
  13178. public:
  13179. ValueTreePropertyValueSource (const ValueTree& tree_,
  13180. const var::identifier& property_,
  13181. UndoManager* const undoManager_)
  13182. : tree (tree_),
  13183. property (property_),
  13184. undoManager (undoManager_)
  13185. {
  13186. tree.addListener (this);
  13187. }
  13188. ~ValueTreePropertyValueSource()
  13189. {
  13190. tree.removeListener (this);
  13191. }
  13192. const var getValue() const
  13193. {
  13194. return tree [property];
  13195. }
  13196. void setValue (const var& newValue)
  13197. {
  13198. tree.setProperty (property, newValue, undoManager);
  13199. }
  13200. void valueTreePropertyChanged (ValueTree& treeWhosePropertyHasChanged, const var::identifier& changedProperty)
  13201. {
  13202. if (tree == treeWhosePropertyHasChanged && property == changedProperty)
  13203. sendChangeMessage (false);
  13204. }
  13205. void valueTreeChildrenChanged (ValueTree&) {}
  13206. void valueTreeParentChanged (ValueTree&) {}
  13207. private:
  13208. ValueTree tree;
  13209. const var::identifier property;
  13210. UndoManager* const undoManager;
  13211. ValueTreePropertyValueSource& operator= (const ValueTreePropertyValueSource&);
  13212. };
  13213. Value ValueTree::getPropertyAsValue (const var::identifier& name, UndoManager* const undoManager) const
  13214. {
  13215. return Value (new ValueTreePropertyValueSource (*this, name, undoManager));
  13216. }
  13217. int ValueTree::getNumChildren() const
  13218. {
  13219. return object == 0 ? 0 : object->children.size();
  13220. }
  13221. ValueTree ValueTree::getChild (int index) const
  13222. {
  13223. return ValueTree (object != 0 ? (SharedObject*) object->children [index] : (SharedObject*) 0);
  13224. }
  13225. ValueTree ValueTree::getChildWithName (const String& type) const
  13226. {
  13227. return object != 0 ? object->getChildWithName (type) : ValueTree::invalid;
  13228. }
  13229. ValueTree ValueTree::getChildWithProperty (const var::identifier& propertyName, const var& propertyValue) const
  13230. {
  13231. return object != 0 ? object->getChildWithProperty (propertyName, propertyValue) : ValueTree::invalid;
  13232. }
  13233. bool ValueTree::isAChildOf (const ValueTree& possibleParent) const
  13234. {
  13235. return object != 0 && object->isAChildOf (possibleParent.object);
  13236. }
  13237. int ValueTree::indexOf (const ValueTree& child) const
  13238. {
  13239. return object != 0 ? object->indexOf (child) : -1;
  13240. }
  13241. void ValueTree::addChild (ValueTree child, int index, UndoManager* const undoManager)
  13242. {
  13243. if (object != 0)
  13244. object->addChild (child.object, index, undoManager);
  13245. }
  13246. void ValueTree::removeChild (const int childIndex, UndoManager* const undoManager)
  13247. {
  13248. if (object != 0)
  13249. object->removeChild (childIndex, undoManager);
  13250. }
  13251. void ValueTree::removeChild (const ValueTree& child, UndoManager* const undoManager)
  13252. {
  13253. if (object != 0)
  13254. object->removeChild (object->children.indexOf (child.object), undoManager);
  13255. }
  13256. void ValueTree::removeAllChildren (UndoManager* const undoManager)
  13257. {
  13258. if (object != 0)
  13259. object->removeAllChildren (undoManager);
  13260. }
  13261. void ValueTree::moveChild (int currentIndex, int newIndex, UndoManager* undoManager)
  13262. {
  13263. if (object != 0)
  13264. object->moveChild (currentIndex, newIndex, undoManager);
  13265. }
  13266. void ValueTree::addListener (Listener* listener)
  13267. {
  13268. if (listener != 0)
  13269. {
  13270. if (listeners.size() == 0 && object != 0)
  13271. object->valueTreesWithListeners.add (this);
  13272. listeners.add (listener);
  13273. }
  13274. }
  13275. void ValueTree::removeListener (Listener* listener)
  13276. {
  13277. listeners.remove (listener);
  13278. if (listeners.size() == 0 && object != 0)
  13279. object->valueTreesWithListeners.removeValue (this);
  13280. }
  13281. XmlElement* ValueTree::SharedObject::createXml() const
  13282. {
  13283. XmlElement* xml = new XmlElement (type);
  13284. int i;
  13285. for (i = 0; i < properties.size(); ++i)
  13286. {
  13287. var::identifier name (properties.getName(i));
  13288. const var& v = properties [name];
  13289. jassert (! v.isObject()); // DynamicObjects can't be stored as XML!
  13290. xml->setAttribute (name.name, v.toString());
  13291. }
  13292. for (i = 0; i < children.size(); ++i)
  13293. xml->addChildElement (children.getUnchecked(i)->createXml());
  13294. return xml;
  13295. }
  13296. XmlElement* ValueTree::createXml() const
  13297. {
  13298. return object != 0 ? object->createXml() : 0;
  13299. }
  13300. ValueTree ValueTree::fromXml (const XmlElement& xml)
  13301. {
  13302. ValueTree v (xml.getTagName());
  13303. const int numAtts = xml.getNumAttributes(); // xxx inefficient - should write an att iterator..
  13304. for (int i = 0; i < numAtts; ++i)
  13305. v.setProperty (xml.getAttributeName (i), var (xml.getAttributeValue (i)), 0);
  13306. forEachXmlChildElement (xml, e)
  13307. {
  13308. v.addChild (fromXml (*e), -1, 0);
  13309. }
  13310. return v;
  13311. }
  13312. void ValueTree::writeToStream (OutputStream& output)
  13313. {
  13314. output.writeString (getType());
  13315. const int numProps = getNumProperties();
  13316. output.writeCompressedInt (numProps);
  13317. int i;
  13318. for (i = 0; i < numProps; ++i)
  13319. {
  13320. const var::identifier name (getPropertyName(i));
  13321. output.writeString (name.name);
  13322. getProperty(name).writeToStream (output);
  13323. }
  13324. const int numChildren = getNumChildren();
  13325. output.writeCompressedInt (numChildren);
  13326. for (i = 0; i < numChildren; ++i)
  13327. getChild (i).writeToStream (output);
  13328. }
  13329. ValueTree ValueTree::readFromStream (InputStream& input)
  13330. {
  13331. String type (input.readString());
  13332. if (type.isEmpty())
  13333. return ValueTree::invalid;
  13334. ValueTree v (type);
  13335. const int numProps = input.readCompressedInt();
  13336. if (numProps < 0)
  13337. {
  13338. jassertfalse // trying to read corrupted data!
  13339. return v;
  13340. }
  13341. int i;
  13342. for (i = 0; i < numProps; ++i)
  13343. {
  13344. const String name (input.readString());
  13345. jassert (name.isNotEmpty());
  13346. const var value (var::readFromStream (input));
  13347. v.setProperty (name, value, 0);
  13348. }
  13349. const int numChildren = input.readCompressedInt();
  13350. for (i = 0; i < numChildren; ++i)
  13351. v.addChild (readFromStream (input), -1, 0);
  13352. return v;
  13353. }
  13354. END_JUCE_NAMESPACE
  13355. /*** End of inlined file: juce_ValueTree.cpp ***/
  13356. /*** Start of inlined file: juce_Value.cpp ***/
  13357. BEGIN_JUCE_NAMESPACE
  13358. Value::ValueSource::ValueSource()
  13359. {
  13360. }
  13361. Value::ValueSource::~ValueSource()
  13362. {
  13363. }
  13364. void Value::ValueSource::sendChangeMessage (const bool synchronous)
  13365. {
  13366. if (synchronous)
  13367. {
  13368. for (int i = valuesWithListeners.size(); --i >= 0;)
  13369. {
  13370. Value* const v = valuesWithListeners[i];
  13371. if (v != 0)
  13372. v->callListeners();
  13373. }
  13374. }
  13375. else
  13376. {
  13377. triggerAsyncUpdate();
  13378. }
  13379. }
  13380. void Value::ValueSource::handleAsyncUpdate()
  13381. {
  13382. sendChangeMessage (true);
  13383. }
  13384. class SimpleValueSource : public Value::ValueSource
  13385. {
  13386. public:
  13387. SimpleValueSource()
  13388. {
  13389. }
  13390. SimpleValueSource (const var& initialValue)
  13391. : value (initialValue)
  13392. {
  13393. }
  13394. ~SimpleValueSource()
  13395. {
  13396. }
  13397. const var getValue() const
  13398. {
  13399. return value;
  13400. }
  13401. void setValue (const var& newValue)
  13402. {
  13403. if (newValue != value)
  13404. {
  13405. value = newValue;
  13406. sendChangeMessage (false);
  13407. }
  13408. }
  13409. private:
  13410. var value;
  13411. SimpleValueSource (const SimpleValueSource&);
  13412. SimpleValueSource& operator= (const SimpleValueSource&);
  13413. };
  13414. Value::Value()
  13415. : value (new SimpleValueSource())
  13416. {
  13417. }
  13418. Value::Value (ValueSource* const value_)
  13419. : value (value_)
  13420. {
  13421. jassert (value_ != 0);
  13422. }
  13423. Value::Value (const var& initialValue)
  13424. : value (new SimpleValueSource (initialValue))
  13425. {
  13426. }
  13427. Value::Value (const Value& other)
  13428. : value (other.value)
  13429. {
  13430. }
  13431. Value& Value::operator= (const Value& other)
  13432. {
  13433. value = other.value;
  13434. return *this;
  13435. }
  13436. Value::~Value()
  13437. {
  13438. if (listeners.size() > 0)
  13439. value->valuesWithListeners.removeValue (this);
  13440. }
  13441. const var Value::getValue() const
  13442. {
  13443. return value->getValue();
  13444. }
  13445. Value::operator const var() const
  13446. {
  13447. return getValue();
  13448. }
  13449. void Value::setValue (const var& newValue)
  13450. {
  13451. value->setValue (newValue);
  13452. }
  13453. const String Value::toString() const
  13454. {
  13455. return value->getValue().toString();
  13456. }
  13457. Value& Value::operator= (const var& newValue)
  13458. {
  13459. value->setValue (newValue);
  13460. return *this;
  13461. }
  13462. void Value::referTo (const Value& valueToReferTo)
  13463. {
  13464. if (valueToReferTo.value != value)
  13465. {
  13466. if (listeners.size() > 0)
  13467. {
  13468. value->valuesWithListeners.removeValue (this);
  13469. valueToReferTo.value->valuesWithListeners.add (this);
  13470. }
  13471. value = valueToReferTo.value;
  13472. callListeners();
  13473. }
  13474. }
  13475. bool Value::refersToSameSourceAs (const Value& other) const
  13476. {
  13477. return value == other.value;
  13478. }
  13479. bool Value::operator== (const Value& other) const
  13480. {
  13481. return value == other.value || value->getValue() == other.getValue();
  13482. }
  13483. bool Value::operator!= (const Value& other) const
  13484. {
  13485. return value != other.value && value->getValue() != other.getValue();
  13486. }
  13487. void Value::addListener (Listener* const listener)
  13488. {
  13489. if (listener != 0)
  13490. {
  13491. if (listeners.size() == 0)
  13492. value->valuesWithListeners.add (this);
  13493. listeners.add (listener);
  13494. }
  13495. }
  13496. void Value::removeListener (Listener* const listener)
  13497. {
  13498. listeners.remove (listener);
  13499. if (listeners.size() == 0)
  13500. value->valuesWithListeners.removeValue (this);
  13501. }
  13502. void Value::callListeners()
  13503. {
  13504. Value v (*this); // (create a copy in case this gets deleted by a callback)
  13505. listeners.call (&Listener::valueChanged, v);
  13506. }
  13507. OutputStream& JUCE_CALLTYPE operator<< (OutputStream& stream, const Value& value)
  13508. {
  13509. return stream << value.toString();
  13510. }
  13511. END_JUCE_NAMESPACE
  13512. /*** End of inlined file: juce_Value.cpp ***/
  13513. /*** Start of inlined file: juce_Application.cpp ***/
  13514. #if JUCE_MSVC
  13515. #pragma warning (push)
  13516. #pragma warning (disable: 4245 4514 4100)
  13517. #include <crtdbg.h>
  13518. #pragma warning (pop)
  13519. #endif
  13520. BEGIN_JUCE_NAMESPACE
  13521. void juce_setCurrentThreadName (const String& name);
  13522. static JUCEApplication* appInstance = 0;
  13523. JUCEApplication::JUCEApplication()
  13524. : appReturnValue (0),
  13525. stillInitialising (true)
  13526. {
  13527. }
  13528. JUCEApplication::~JUCEApplication()
  13529. {
  13530. if (appLock != 0)
  13531. {
  13532. appLock->exit();
  13533. appLock = 0;
  13534. }
  13535. }
  13536. JUCEApplication* JUCEApplication::getInstance() throw()
  13537. {
  13538. return appInstance;
  13539. }
  13540. bool JUCEApplication::isInitialising() const throw()
  13541. {
  13542. return stillInitialising;
  13543. }
  13544. const String JUCEApplication::getApplicationVersion()
  13545. {
  13546. return String::empty;
  13547. }
  13548. bool JUCEApplication::moreThanOneInstanceAllowed()
  13549. {
  13550. return true;
  13551. }
  13552. void JUCEApplication::anotherInstanceStarted (const String&)
  13553. {
  13554. }
  13555. void JUCEApplication::systemRequestedQuit()
  13556. {
  13557. quit();
  13558. }
  13559. void JUCEApplication::quit()
  13560. {
  13561. MessageManager::getInstance()->stopDispatchLoop();
  13562. }
  13563. void JUCEApplication::setApplicationReturnValue (const int newReturnValue) throw()
  13564. {
  13565. appReturnValue = newReturnValue;
  13566. }
  13567. void JUCEApplication::unhandledException (const std::exception*,
  13568. const String&,
  13569. const int)
  13570. {
  13571. jassertfalse
  13572. }
  13573. void JUCEApplication::sendUnhandledException (const std::exception* const e,
  13574. const char* const sourceFile,
  13575. const int lineNumber)
  13576. {
  13577. if (appInstance != 0)
  13578. appInstance->unhandledException (e, sourceFile, lineNumber);
  13579. }
  13580. ApplicationCommandTarget* JUCEApplication::getNextCommandTarget()
  13581. {
  13582. return 0;
  13583. }
  13584. void JUCEApplication::getAllCommands (Array <CommandID>& commands)
  13585. {
  13586. commands.add (StandardApplicationCommandIDs::quit);
  13587. }
  13588. void JUCEApplication::getCommandInfo (const CommandID commandID, ApplicationCommandInfo& result)
  13589. {
  13590. if (commandID == StandardApplicationCommandIDs::quit)
  13591. {
  13592. result.setInfo (TRANS("Quit"),
  13593. TRANS("Quits the application"),
  13594. "Application",
  13595. 0);
  13596. result.defaultKeypresses.add (KeyPress ('q', ModifierKeys::commandModifier, 0));
  13597. }
  13598. }
  13599. bool JUCEApplication::perform (const InvocationInfo& info)
  13600. {
  13601. if (info.commandID == StandardApplicationCommandIDs::quit)
  13602. {
  13603. systemRequestedQuit();
  13604. return true;
  13605. }
  13606. return false;
  13607. }
  13608. int JUCEApplication::main (String& commandLine, JUCEApplication* const app)
  13609. {
  13610. if (! app->initialiseApp (commandLine))
  13611. return 0;
  13612. // now loop until a quit message is received..
  13613. JUCE_TRY
  13614. {
  13615. MessageManager::getInstance()->runDispatchLoop();
  13616. }
  13617. #if JUCE_CATCH_UNHANDLED_EXCEPTIONS
  13618. catch (const std::exception& e)
  13619. {
  13620. app->unhandledException (&e, __FILE__, __LINE__);
  13621. }
  13622. catch (...)
  13623. {
  13624. app->unhandledException (0, __FILE__, __LINE__);
  13625. }
  13626. #endif
  13627. return shutdownAppAndClearUp();
  13628. }
  13629. bool JUCEApplication::initialiseApp (String& commandLine)
  13630. {
  13631. jassert (appInstance == 0);
  13632. appInstance = this;
  13633. commandLineParameters = commandLine.trim();
  13634. commandLine = String::empty;
  13635. initialiseJuce_GUI();
  13636. #if ! JUCE_IPHONE
  13637. jassert (appLock == 0); // initialiseApp must only be called once!
  13638. if (! moreThanOneInstanceAllowed())
  13639. {
  13640. appLock = new InterProcessLock ("juceAppLock_" + getApplicationName());
  13641. if (! appLock->enter(0))
  13642. {
  13643. MessageManager::broadcastMessage (getApplicationName() + "/" + commandLineParameters);
  13644. delete appInstance;
  13645. appInstance = 0;
  13646. DBG ("Another instance is running - quitting...");
  13647. return false;
  13648. }
  13649. }
  13650. #endif
  13651. // let the app do its setting-up..
  13652. initialise (commandLineParameters);
  13653. // register for broadcast new app messages
  13654. MessageManager::getInstance()->registerBroadcastListener (this);
  13655. stillInitialising = false;
  13656. return true;
  13657. }
  13658. int JUCEApplication::shutdownAppAndClearUp()
  13659. {
  13660. jassert (appInstance != 0);
  13661. ScopedPointer<JUCEApplication> app (appInstance);
  13662. int returnValue = 0;
  13663. MessageManager::getInstance()->deregisterBroadcastListener (static_cast <JUCEApplication*> (app));
  13664. static bool reentrancyCheck = false;
  13665. if (! reentrancyCheck)
  13666. {
  13667. reentrancyCheck = true;
  13668. JUCE_TRY
  13669. {
  13670. // give the app a chance to clean up..
  13671. app->shutdown();
  13672. }
  13673. #if JUCE_CATCH_UNHANDLED_EXCEPTIONS
  13674. catch (const std::exception& e)
  13675. {
  13676. app->unhandledException (&e, __FILE__, __LINE__);
  13677. }
  13678. catch (...)
  13679. {
  13680. app->unhandledException (0, __FILE__, __LINE__);
  13681. }
  13682. #endif
  13683. JUCE_TRY
  13684. {
  13685. shutdownJuce_GUI();
  13686. returnValue = app->getApplicationReturnValue();
  13687. appInstance = 0;
  13688. app = 0;
  13689. }
  13690. JUCE_CATCH_ALL_ASSERT
  13691. reentrancyCheck = false;
  13692. }
  13693. return returnValue;
  13694. }
  13695. #if JUCE_IPHONE
  13696. extern int juce_IPhoneMain (int argc, const char* argv[], JUCEApplication* app);
  13697. #endif
  13698. #if ! JUCE_WINDOWS
  13699. extern const char* juce_Argv0;
  13700. #endif
  13701. int JUCEApplication::main (int argc, const char* argv[], JUCEApplication* const newApp)
  13702. {
  13703. #if ! JUCE_WINDOWS
  13704. juce_Argv0 = argv[0];
  13705. #endif
  13706. #if JUCE_IPHONE
  13707. const ScopedAutoReleasePool pool;
  13708. return juce_IPhoneMain (argc, argv, newApp);
  13709. #else
  13710. #if JUCE_MAC
  13711. const ScopedAutoReleasePool pool;
  13712. #endif
  13713. String cmd;
  13714. for (int i = 1; i < argc; ++i)
  13715. cmd << argv[i] << ' ';
  13716. return JUCEApplication::main (cmd, newApp);
  13717. #endif
  13718. }
  13719. void JUCEApplication::actionListenerCallback (const String& message)
  13720. {
  13721. if (message.startsWith (getApplicationName() + "/"))
  13722. anotherInstanceStarted (message.substring (getApplicationName().length() + 1));
  13723. }
  13724. static bool juceInitialisedGUI = false;
  13725. void JUCE_PUBLIC_FUNCTION initialiseJuce_GUI()
  13726. {
  13727. if (! juceInitialisedGUI)
  13728. {
  13729. #if JUCE_MAC || JUCE_IPHONE
  13730. const ScopedAutoReleasePool pool;
  13731. #endif
  13732. juceInitialisedGUI = true;
  13733. initialiseJuce_NonGUI();
  13734. MessageManager::getInstance();
  13735. LookAndFeel::setDefaultLookAndFeel (0);
  13736. juce_setCurrentThreadName ("Juce Message Thread");
  13737. #if JUCE_WINDOWS && JUCE_DEBUG
  13738. // This section is just for catching people who mess up their project settings and
  13739. // turn RTTI off..
  13740. try
  13741. {
  13742. TextButton tb (String::empty);
  13743. Component* c = &tb;
  13744. // Got an exception here? Then TURN ON RTTI in your compiler settings!!
  13745. c = dynamic_cast <Button*> (c);
  13746. }
  13747. catch (...)
  13748. {
  13749. // Ended up here? If so, TURN ON RTTI in your compiler settings!! And if you
  13750. // got as far as this catch statement, then why haven't you got exception catching
  13751. // turned on in the debugger???
  13752. jassertfalse
  13753. }
  13754. #endif
  13755. }
  13756. }
  13757. void JUCE_PUBLIC_FUNCTION shutdownJuce_GUI()
  13758. {
  13759. if (juceInitialisedGUI)
  13760. {
  13761. #if JUCE_MAC
  13762. const ScopedAutoReleasePool pool;
  13763. #endif
  13764. {
  13765. DeletedAtShutdown::deleteAll();
  13766. LookAndFeel::clearDefaultLookAndFeel();
  13767. }
  13768. delete MessageManager::getInstance();
  13769. shutdownJuce_NonGUI();
  13770. juceInitialisedGUI = false;
  13771. }
  13772. }
  13773. END_JUCE_NAMESPACE
  13774. /*** End of inlined file: juce_Application.cpp ***/
  13775. /*** Start of inlined file: juce_ApplicationCommandInfo.cpp ***/
  13776. BEGIN_JUCE_NAMESPACE
  13777. ApplicationCommandInfo::ApplicationCommandInfo (const CommandID commandID_) throw()
  13778. : commandID (commandID_),
  13779. flags (0)
  13780. {
  13781. }
  13782. void ApplicationCommandInfo::setInfo (const String& shortName_,
  13783. const String& description_,
  13784. const String& categoryName_,
  13785. const int flags_) throw()
  13786. {
  13787. shortName = shortName_;
  13788. description = description_;
  13789. categoryName = categoryName_;
  13790. flags = flags_;
  13791. }
  13792. void ApplicationCommandInfo::setActive (const bool b) throw()
  13793. {
  13794. if (b)
  13795. flags &= ~isDisabled;
  13796. else
  13797. flags |= isDisabled;
  13798. }
  13799. void ApplicationCommandInfo::setTicked (const bool b) throw()
  13800. {
  13801. if (b)
  13802. flags |= isTicked;
  13803. else
  13804. flags &= ~isTicked;
  13805. }
  13806. void ApplicationCommandInfo::addDefaultKeypress (const int keyCode, const ModifierKeys& modifiers) throw()
  13807. {
  13808. defaultKeypresses.add (KeyPress (keyCode, modifiers, 0));
  13809. }
  13810. END_JUCE_NAMESPACE
  13811. /*** End of inlined file: juce_ApplicationCommandInfo.cpp ***/
  13812. /*** Start of inlined file: juce_ApplicationCommandManager.cpp ***/
  13813. BEGIN_JUCE_NAMESPACE
  13814. ApplicationCommandManager::ApplicationCommandManager()
  13815. : firstTarget (0)
  13816. {
  13817. keyMappings = new KeyPressMappingSet (this);
  13818. Desktop::getInstance().addFocusChangeListener (this);
  13819. }
  13820. ApplicationCommandManager::~ApplicationCommandManager()
  13821. {
  13822. Desktop::getInstance().removeFocusChangeListener (this);
  13823. keyMappings = 0;
  13824. }
  13825. void ApplicationCommandManager::clearCommands()
  13826. {
  13827. commands.clear();
  13828. keyMappings->clearAllKeyPresses();
  13829. triggerAsyncUpdate();
  13830. }
  13831. void ApplicationCommandManager::registerCommand (const ApplicationCommandInfo& newCommand)
  13832. {
  13833. // zero isn't a valid command ID!
  13834. jassert (newCommand.commandID != 0);
  13835. // the name isn't optional!
  13836. jassert (newCommand.shortName.isNotEmpty());
  13837. if (getCommandForID (newCommand.commandID) == 0)
  13838. {
  13839. ApplicationCommandInfo* const newInfo = new ApplicationCommandInfo (newCommand);
  13840. newInfo->flags &= ~ApplicationCommandInfo::isTicked;
  13841. commands.add (newInfo);
  13842. keyMappings->resetToDefaultMapping (newCommand.commandID);
  13843. triggerAsyncUpdate();
  13844. }
  13845. else
  13846. {
  13847. // trying to re-register the same command with different parameters?
  13848. jassert (newCommand.shortName == getCommandForID (newCommand.commandID)->shortName
  13849. && (newCommand.description == getCommandForID (newCommand.commandID)->description || newCommand.description.isEmpty())
  13850. && newCommand.categoryName == getCommandForID (newCommand.commandID)->categoryName
  13851. && newCommand.defaultKeypresses == getCommandForID (newCommand.commandID)->defaultKeypresses
  13852. && (newCommand.flags & (ApplicationCommandInfo::wantsKeyUpDownCallbacks | ApplicationCommandInfo::hiddenFromKeyEditor | ApplicationCommandInfo::readOnlyInKeyEditor))
  13853. == (getCommandForID (newCommand.commandID)->flags & (ApplicationCommandInfo::wantsKeyUpDownCallbacks | ApplicationCommandInfo::hiddenFromKeyEditor | ApplicationCommandInfo::readOnlyInKeyEditor)));
  13854. }
  13855. }
  13856. void ApplicationCommandManager::registerAllCommandsForTarget (ApplicationCommandTarget* target)
  13857. {
  13858. if (target != 0)
  13859. {
  13860. Array <CommandID> commandIDs;
  13861. target->getAllCommands (commandIDs);
  13862. for (int i = 0; i < commandIDs.size(); ++i)
  13863. {
  13864. ApplicationCommandInfo info (commandIDs.getUnchecked(i));
  13865. target->getCommandInfo (info.commandID, info);
  13866. registerCommand (info);
  13867. }
  13868. }
  13869. }
  13870. void ApplicationCommandManager::removeCommand (const CommandID commandID)
  13871. {
  13872. for (int i = commands.size(); --i >= 0;)
  13873. {
  13874. if (commands.getUnchecked (i)->commandID == commandID)
  13875. {
  13876. commands.remove (i);
  13877. triggerAsyncUpdate();
  13878. const Array <KeyPress> keys (keyMappings->getKeyPressesAssignedToCommand (commandID));
  13879. for (int j = keys.size(); --j >= 0;)
  13880. keyMappings->removeKeyPress (keys.getReference (j));
  13881. }
  13882. }
  13883. }
  13884. void ApplicationCommandManager::commandStatusChanged()
  13885. {
  13886. triggerAsyncUpdate();
  13887. }
  13888. const ApplicationCommandInfo* ApplicationCommandManager::getCommandForID (const CommandID commandID) const throw()
  13889. {
  13890. for (int i = commands.size(); --i >= 0;)
  13891. if (commands.getUnchecked(i)->commandID == commandID)
  13892. return commands.getUnchecked(i);
  13893. return 0;
  13894. }
  13895. const String ApplicationCommandManager::getNameOfCommand (const CommandID commandID) const throw()
  13896. {
  13897. const ApplicationCommandInfo* const ci = getCommandForID (commandID);
  13898. return (ci != 0) ? ci->shortName : String::empty;
  13899. }
  13900. const String ApplicationCommandManager::getDescriptionOfCommand (const CommandID commandID) const throw()
  13901. {
  13902. const ApplicationCommandInfo* const ci = getCommandForID (commandID);
  13903. return (ci != 0) ? (ci->description.isNotEmpty() ? ci->description : ci->shortName)
  13904. : String::empty;
  13905. }
  13906. const StringArray ApplicationCommandManager::getCommandCategories() const throw()
  13907. {
  13908. StringArray s;
  13909. for (int i = 0; i < commands.size(); ++i)
  13910. s.addIfNotAlreadyThere (commands.getUnchecked(i)->categoryName, false);
  13911. return s;
  13912. }
  13913. const Array <CommandID> ApplicationCommandManager::getCommandsInCategory (const String& categoryName) const throw()
  13914. {
  13915. Array <CommandID> results;
  13916. for (int i = 0; i < commands.size(); ++i)
  13917. if (commands.getUnchecked(i)->categoryName == categoryName)
  13918. results.add (commands.getUnchecked(i)->commandID);
  13919. return results;
  13920. }
  13921. bool ApplicationCommandManager::invokeDirectly (const CommandID commandID, const bool asynchronously)
  13922. {
  13923. ApplicationCommandTarget::InvocationInfo info (commandID);
  13924. info.invocationMethod = ApplicationCommandTarget::InvocationInfo::direct;
  13925. return invoke (info, asynchronously);
  13926. }
  13927. bool ApplicationCommandManager::invoke (const ApplicationCommandTarget::InvocationInfo& info_, const bool asynchronously)
  13928. {
  13929. // This call isn't thread-safe for use from a non-UI thread without locking the message
  13930. // manager first..
  13931. jassert (MessageManager::getInstance()->currentThreadHasLockedMessageManager());
  13932. ApplicationCommandTarget* const target = getFirstCommandTarget (info_.commandID);
  13933. if (target == 0)
  13934. return false;
  13935. ApplicationCommandInfo commandInfo (0);
  13936. target->getCommandInfo (info_.commandID, commandInfo);
  13937. ApplicationCommandTarget::InvocationInfo info (info_);
  13938. info.commandFlags = commandInfo.flags;
  13939. sendListenerInvokeCallback (info);
  13940. const bool ok = target->invoke (info, asynchronously);
  13941. commandStatusChanged();
  13942. return ok;
  13943. }
  13944. ApplicationCommandTarget* ApplicationCommandManager::getFirstCommandTarget (const CommandID)
  13945. {
  13946. return firstTarget != 0 ? firstTarget
  13947. : findDefaultComponentTarget();
  13948. }
  13949. void ApplicationCommandManager::setFirstCommandTarget (ApplicationCommandTarget* const newTarget) throw()
  13950. {
  13951. firstTarget = newTarget;
  13952. }
  13953. ApplicationCommandTarget* ApplicationCommandManager::getTargetForCommand (const CommandID commandID,
  13954. ApplicationCommandInfo& upToDateInfo)
  13955. {
  13956. ApplicationCommandTarget* target = getFirstCommandTarget (commandID);
  13957. if (target == 0)
  13958. target = JUCEApplication::getInstance();
  13959. if (target != 0)
  13960. target = target->getTargetForCommand (commandID);
  13961. if (target != 0)
  13962. target->getCommandInfo (commandID, upToDateInfo);
  13963. return target;
  13964. }
  13965. ApplicationCommandTarget* ApplicationCommandManager::findTargetForComponent (Component* c)
  13966. {
  13967. ApplicationCommandTarget* target = dynamic_cast <ApplicationCommandTarget*> (c);
  13968. if (target == 0 && c != 0)
  13969. // (unable to use the syntax findParentComponentOfClass <ApplicationCommandTarget> () because of a VC6 compiler bug)
  13970. target = c->findParentComponentOfClass ((ApplicationCommandTarget*) 0);
  13971. return target;
  13972. }
  13973. ApplicationCommandTarget* ApplicationCommandManager::findDefaultComponentTarget()
  13974. {
  13975. Component* c = Component::getCurrentlyFocusedComponent();
  13976. if (c == 0)
  13977. {
  13978. TopLevelWindow* const activeWindow = TopLevelWindow::getActiveTopLevelWindow();
  13979. if (activeWindow != 0)
  13980. {
  13981. c = activeWindow->getPeer()->getLastFocusedSubcomponent();
  13982. if (c == 0)
  13983. c = activeWindow;
  13984. }
  13985. }
  13986. if (c == 0 && Process::isForegroundProcess())
  13987. {
  13988. // getting a bit desperate now - try all desktop comps..
  13989. for (int i = Desktop::getInstance().getNumComponents(); --i >= 0;)
  13990. {
  13991. ApplicationCommandTarget* const target
  13992. = findTargetForComponent (Desktop::getInstance().getComponent (i)
  13993. ->getPeer()->getLastFocusedSubcomponent());
  13994. if (target != 0)
  13995. return target;
  13996. }
  13997. }
  13998. if (c != 0)
  13999. {
  14000. ResizableWindow* const resizableWindow = dynamic_cast <ResizableWindow*> (c);
  14001. // if we're focused on a ResizableWindow, chances are that it's the content
  14002. // component that really should get the event. And if not, the event will
  14003. // still be passed up to the top level window anyway, so let's send it to the
  14004. // content comp.
  14005. if (resizableWindow != 0 && resizableWindow->getContentComponent() != 0)
  14006. c = resizableWindow->getContentComponent();
  14007. ApplicationCommandTarget* const target = findTargetForComponent (c);
  14008. if (target != 0)
  14009. return target;
  14010. }
  14011. return JUCEApplication::getInstance();
  14012. }
  14013. void ApplicationCommandManager::addListener (ApplicationCommandManagerListener* const listener) throw()
  14014. {
  14015. listeners.add (listener);
  14016. }
  14017. void ApplicationCommandManager::removeListener (ApplicationCommandManagerListener* const listener) throw()
  14018. {
  14019. listeners.remove (listener);
  14020. }
  14021. void ApplicationCommandManager::sendListenerInvokeCallback (const ApplicationCommandTarget::InvocationInfo& info)
  14022. {
  14023. listeners.call (&ApplicationCommandManagerListener::applicationCommandInvoked, info);
  14024. }
  14025. void ApplicationCommandManager::handleAsyncUpdate()
  14026. {
  14027. listeners.call (&ApplicationCommandManagerListener::applicationCommandListChanged);
  14028. }
  14029. void ApplicationCommandManager::globalFocusChanged (Component*)
  14030. {
  14031. commandStatusChanged();
  14032. }
  14033. END_JUCE_NAMESPACE
  14034. /*** End of inlined file: juce_ApplicationCommandManager.cpp ***/
  14035. /*** Start of inlined file: juce_ApplicationCommandTarget.cpp ***/
  14036. BEGIN_JUCE_NAMESPACE
  14037. ApplicationCommandTarget::ApplicationCommandTarget()
  14038. {
  14039. }
  14040. ApplicationCommandTarget::~ApplicationCommandTarget()
  14041. {
  14042. messageInvoker = 0;
  14043. }
  14044. bool ApplicationCommandTarget::tryToInvoke (const InvocationInfo& info, const bool async)
  14045. {
  14046. if (isCommandActive (info.commandID))
  14047. {
  14048. if (async)
  14049. {
  14050. if (messageInvoker == 0)
  14051. messageInvoker = new CommandTargetMessageInvoker (this);
  14052. messageInvoker->postMessage (new Message (0, 0, 0, new ApplicationCommandTarget::InvocationInfo (info)));
  14053. return true;
  14054. }
  14055. else
  14056. {
  14057. const bool success = perform (info);
  14058. jassert (success); // hmm - your target should have been able to perform this command. If it can't
  14059. // do it at the moment for some reason, it should clear the 'isActive' flag when it
  14060. // returns the command's info.
  14061. return success;
  14062. }
  14063. }
  14064. return false;
  14065. }
  14066. ApplicationCommandTarget* ApplicationCommandTarget::findFirstTargetParentComponent()
  14067. {
  14068. Component* c = dynamic_cast <Component*> (this);
  14069. if (c != 0)
  14070. // (unable to use the syntax findParentComponentOfClass <ApplicationCommandTarget> () because of a VC6 compiler bug)
  14071. return c->findParentComponentOfClass ((ApplicationCommandTarget*) 0);
  14072. return 0;
  14073. }
  14074. ApplicationCommandTarget* ApplicationCommandTarget::getTargetForCommand (const CommandID commandID)
  14075. {
  14076. ApplicationCommandTarget* target = this;
  14077. int depth = 0;
  14078. while (target != 0)
  14079. {
  14080. Array <CommandID> commandIDs;
  14081. target->getAllCommands (commandIDs);
  14082. if (commandIDs.contains (commandID))
  14083. return target;
  14084. target = target->getNextCommandTarget();
  14085. ++depth;
  14086. jassert (depth < 100); // could be a recursive command chain??
  14087. jassert (target != this); // definitely a recursive command chain!
  14088. if (depth > 100 || target == this)
  14089. break;
  14090. }
  14091. if (target == 0)
  14092. {
  14093. target = JUCEApplication::getInstance();
  14094. if (target != 0)
  14095. {
  14096. Array <CommandID> commandIDs;
  14097. target->getAllCommands (commandIDs);
  14098. if (commandIDs.contains (commandID))
  14099. return target;
  14100. }
  14101. }
  14102. return 0;
  14103. }
  14104. bool ApplicationCommandTarget::isCommandActive (const CommandID commandID)
  14105. {
  14106. ApplicationCommandInfo info (commandID);
  14107. info.flags = ApplicationCommandInfo::isDisabled;
  14108. getCommandInfo (commandID, info);
  14109. return (info.flags & ApplicationCommandInfo::isDisabled) == 0;
  14110. }
  14111. bool ApplicationCommandTarget::invoke (const InvocationInfo& info, const bool async)
  14112. {
  14113. ApplicationCommandTarget* target = this;
  14114. int depth = 0;
  14115. while (target != 0)
  14116. {
  14117. if (target->tryToInvoke (info, async))
  14118. return true;
  14119. target = target->getNextCommandTarget();
  14120. ++depth;
  14121. jassert (depth < 100); // could be a recursive command chain??
  14122. jassert (target != this); // definitely a recursive command chain!
  14123. if (depth > 100 || target == this)
  14124. break;
  14125. }
  14126. if (target == 0)
  14127. {
  14128. target = JUCEApplication::getInstance();
  14129. if (target != 0)
  14130. return target->tryToInvoke (info, async);
  14131. }
  14132. return false;
  14133. }
  14134. bool ApplicationCommandTarget::invokeDirectly (const CommandID commandID, const bool asynchronously)
  14135. {
  14136. ApplicationCommandTarget::InvocationInfo info (commandID);
  14137. info.invocationMethod = ApplicationCommandTarget::InvocationInfo::direct;
  14138. return invoke (info, asynchronously);
  14139. }
  14140. ApplicationCommandTarget::InvocationInfo::InvocationInfo (const CommandID commandID_) throw()
  14141. : commandID (commandID_),
  14142. commandFlags (0),
  14143. invocationMethod (direct),
  14144. originatingComponent (0),
  14145. isKeyDown (false),
  14146. millisecsSinceKeyPressed (0)
  14147. {
  14148. }
  14149. ApplicationCommandTarget::CommandTargetMessageInvoker::CommandTargetMessageInvoker (ApplicationCommandTarget* const owner_)
  14150. : owner (owner_)
  14151. {
  14152. }
  14153. ApplicationCommandTarget::CommandTargetMessageInvoker::~CommandTargetMessageInvoker()
  14154. {
  14155. }
  14156. void ApplicationCommandTarget::CommandTargetMessageInvoker::handleMessage (const Message& message)
  14157. {
  14158. const ScopedPointer <InvocationInfo> info (static_cast <InvocationInfo*> (message.pointerParameter));
  14159. owner->tryToInvoke (*info, false);
  14160. }
  14161. END_JUCE_NAMESPACE
  14162. /*** End of inlined file: juce_ApplicationCommandTarget.cpp ***/
  14163. /*** Start of inlined file: juce_ApplicationProperties.cpp ***/
  14164. BEGIN_JUCE_NAMESPACE
  14165. juce_ImplementSingleton (ApplicationProperties)
  14166. ApplicationProperties::ApplicationProperties() throw()
  14167. : msBeforeSaving (3000),
  14168. options (PropertiesFile::storeAsBinary),
  14169. commonSettingsAreReadOnly (0)
  14170. {
  14171. }
  14172. ApplicationProperties::~ApplicationProperties()
  14173. {
  14174. closeFiles();
  14175. clearSingletonInstance();
  14176. }
  14177. void ApplicationProperties::setStorageParameters (const String& applicationName,
  14178. const String& fileNameSuffix,
  14179. const String& folderName_,
  14180. const int millisecondsBeforeSaving,
  14181. const int propertiesFileOptions) throw()
  14182. {
  14183. appName = applicationName;
  14184. fileSuffix = fileNameSuffix;
  14185. folderName = folderName_;
  14186. msBeforeSaving = millisecondsBeforeSaving;
  14187. options = propertiesFileOptions;
  14188. }
  14189. bool ApplicationProperties::testWriteAccess (const bool testUserSettings,
  14190. const bool testCommonSettings,
  14191. const bool showWarningDialogOnFailure)
  14192. {
  14193. const bool userOk = (! testUserSettings) || getUserSettings()->save();
  14194. const bool commonOk = (! testCommonSettings) || getCommonSettings (false)->save();
  14195. if (! (userOk && commonOk))
  14196. {
  14197. if (showWarningDialogOnFailure)
  14198. {
  14199. String filenames;
  14200. if (userProps != 0 && ! userOk)
  14201. filenames << '\n' << userProps->getFile().getFullPathName();
  14202. if (commonProps != 0 && ! commonOk)
  14203. filenames << '\n' << commonProps->getFile().getFullPathName();
  14204. AlertWindow::showMessageBox (AlertWindow::WarningIcon,
  14205. appName + TRANS(" - Unable to save settings"),
  14206. TRANS("An error occurred when trying to save the application's settings file...\n\nIn order to save and restore its settings, ")
  14207. + appName + TRANS(" needs to be able to write to the following files:\n")
  14208. + filenames
  14209. + TRANS("\n\nMake sure that these files aren't read-only, and that the disk isn't full."));
  14210. }
  14211. return false;
  14212. }
  14213. return true;
  14214. }
  14215. void ApplicationProperties::openFiles() throw()
  14216. {
  14217. // You need to call setStorageParameters() before trying to get hold of the
  14218. // properties!
  14219. jassert (appName.isNotEmpty());
  14220. if (appName.isNotEmpty())
  14221. {
  14222. if (userProps == 0)
  14223. userProps = PropertiesFile::createDefaultAppPropertiesFile (appName, fileSuffix, folderName,
  14224. false, msBeforeSaving, options);
  14225. if (commonProps == 0)
  14226. commonProps = PropertiesFile::createDefaultAppPropertiesFile (appName, fileSuffix, folderName,
  14227. true, msBeforeSaving, options);
  14228. userProps->setFallbackPropertySet (commonProps);
  14229. }
  14230. }
  14231. PropertiesFile* ApplicationProperties::getUserSettings() throw()
  14232. {
  14233. if (userProps == 0)
  14234. openFiles();
  14235. return userProps;
  14236. }
  14237. PropertiesFile* ApplicationProperties::getCommonSettings (const bool returnUserPropsIfReadOnly) throw()
  14238. {
  14239. if (commonProps == 0)
  14240. openFiles();
  14241. if (returnUserPropsIfReadOnly)
  14242. {
  14243. if (commonSettingsAreReadOnly == 0)
  14244. commonSettingsAreReadOnly = commonProps->save() ? -1 : 1;
  14245. if (commonSettingsAreReadOnly > 0)
  14246. return userProps;
  14247. }
  14248. return commonProps;
  14249. }
  14250. bool ApplicationProperties::saveIfNeeded()
  14251. {
  14252. return (userProps == 0 || userProps->saveIfNeeded())
  14253. && (commonProps == 0 || commonProps->saveIfNeeded());
  14254. }
  14255. void ApplicationProperties::closeFiles()
  14256. {
  14257. userProps = 0;
  14258. commonProps = 0;
  14259. }
  14260. END_JUCE_NAMESPACE
  14261. /*** End of inlined file: juce_ApplicationProperties.cpp ***/
  14262. /*** Start of inlined file: juce_DeletedAtShutdown.cpp ***/
  14263. BEGIN_JUCE_NAMESPACE
  14264. static VoidArray objectsToDelete;
  14265. static CriticalSection lock;
  14266. DeletedAtShutdown::DeletedAtShutdown()
  14267. {
  14268. const ScopedLock sl (lock);
  14269. objectsToDelete.add (this);
  14270. }
  14271. DeletedAtShutdown::~DeletedAtShutdown()
  14272. {
  14273. const ScopedLock sl (lock);
  14274. objectsToDelete.removeValue (this);
  14275. }
  14276. void DeletedAtShutdown::deleteAll()
  14277. {
  14278. // make a local copy of the array, so it can't get into a loop if something
  14279. // creates another DeletedAtShutdown object during its destructor.
  14280. VoidArray localCopy;
  14281. {
  14282. const ScopedLock sl (lock);
  14283. localCopy = objectsToDelete;
  14284. }
  14285. for (int i = localCopy.size(); --i >= 0;)
  14286. {
  14287. JUCE_TRY
  14288. {
  14289. DeletedAtShutdown* deletee = static_cast <DeletedAtShutdown*> (localCopy.getUnchecked(i));
  14290. // double-check that it's not already been deleted during another object's destructor.
  14291. {
  14292. const ScopedLock sl (lock);
  14293. if (! objectsToDelete.contains (deletee))
  14294. deletee = 0;
  14295. }
  14296. delete deletee;
  14297. }
  14298. JUCE_CATCH_EXCEPTION
  14299. }
  14300. // if no objects got re-created during shutdown, this should have been emptied by their
  14301. // destructors
  14302. jassert (objectsToDelete.size() == 0);
  14303. objectsToDelete.clear(); // just to make sure the array doesn't have any memory still allocated
  14304. }
  14305. END_JUCE_NAMESPACE
  14306. /*** End of inlined file: juce_DeletedAtShutdown.cpp ***/
  14307. /*** Start of inlined file: juce_PropertiesFile.cpp ***/
  14308. BEGIN_JUCE_NAMESPACE
  14309. namespace PropertyFileConstants
  14310. {
  14311. static const int magicNumber = (int) ByteOrder::littleEndianInt ("PROP");
  14312. static const int magicNumberCompressed = (int) ByteOrder::littleEndianInt ("CPRP");
  14313. static const char* const fileTag = "PROPERTIES";
  14314. static const char* const valueTag = "VALUE";
  14315. static const char* const nameAttribute = "name";
  14316. static const char* const valueAttribute = "val";
  14317. }
  14318. PropertiesFile::PropertiesFile (const File& f, const int millisecondsBeforeSaving,
  14319. const int options_, InterProcessLock* const processLock_)
  14320. : PropertySet (ignoreCaseOfKeyNames),
  14321. file (f),
  14322. timerInterval (millisecondsBeforeSaving),
  14323. options (options_),
  14324. loadedOk (false),
  14325. needsWriting (false),
  14326. processLock (processLock_)
  14327. {
  14328. // You need to correctly specify just one storage format for the file
  14329. jassert ((options_ & (storeAsBinary | storeAsCompressedBinary | storeAsXML)) == storeAsBinary
  14330. || (options_ & (storeAsBinary | storeAsCompressedBinary | storeAsXML)) == storeAsCompressedBinary
  14331. || (options_ & (storeAsBinary | storeAsCompressedBinary | storeAsXML)) == storeAsXML);
  14332. ProcessScopedLock pl (createProcessLock());
  14333. if (pl != 0 && ! pl->isLocked())
  14334. return; // locking failure..
  14335. ScopedPointer<InputStream> fileStream (f.createInputStream());
  14336. if (fileStream != 0)
  14337. {
  14338. int magicNumber = fileStream->readInt();
  14339. if (magicNumber == PropertyFileConstants::magicNumberCompressed)
  14340. {
  14341. fileStream = new GZIPDecompressorInputStream (new SubregionStream (fileStream.release(), 4, -1, true), true);
  14342. magicNumber = PropertyFileConstants::magicNumber;
  14343. }
  14344. if (magicNumber == PropertyFileConstants::magicNumber)
  14345. {
  14346. loadedOk = true;
  14347. BufferedInputStream in (fileStream.release(), 2048, true);
  14348. int numValues = in.readInt();
  14349. while (--numValues >= 0 && ! in.isExhausted())
  14350. {
  14351. const String key (in.readString());
  14352. const String value (in.readString());
  14353. jassert (key.isNotEmpty());
  14354. if (key.isNotEmpty())
  14355. getAllProperties().set (key, value);
  14356. }
  14357. }
  14358. else
  14359. {
  14360. // Not a binary props file - let's see if it's XML..
  14361. fileStream = 0;
  14362. XmlDocument parser (f);
  14363. ScopedPointer<XmlElement> doc (parser.getDocumentElement (true));
  14364. if (doc != 0 && doc->hasTagName (PropertyFileConstants::fileTag))
  14365. {
  14366. doc = parser.getDocumentElement();
  14367. if (doc != 0)
  14368. {
  14369. loadedOk = true;
  14370. forEachXmlChildElementWithTagName (*doc, e, PropertyFileConstants::valueTag)
  14371. {
  14372. const String name (e->getStringAttribute (PropertyFileConstants::nameAttribute));
  14373. if (name.isNotEmpty())
  14374. {
  14375. getAllProperties().set (name,
  14376. e->getFirstChildElement() != 0
  14377. ? e->getFirstChildElement()->createDocument (String::empty, true)
  14378. : e->getStringAttribute (PropertyFileConstants::valueAttribute));
  14379. }
  14380. }
  14381. }
  14382. else
  14383. {
  14384. // must be a pretty broken XML file we're trying to parse here,
  14385. // or a sign that this object needs an InterProcessLock,
  14386. // or just a failure reading the file. This last reason is why
  14387. // we don't jassertfalse here.
  14388. }
  14389. }
  14390. }
  14391. }
  14392. else
  14393. {
  14394. loadedOk = ! f.exists();
  14395. }
  14396. }
  14397. PropertiesFile::~PropertiesFile()
  14398. {
  14399. if (! saveIfNeeded())
  14400. jassertfalse;
  14401. }
  14402. InterProcessLock::ScopedLockType* PropertiesFile::createProcessLock() const
  14403. {
  14404. return processLock != 0 ? new InterProcessLock::ScopedLockType (*processLock) : 0;
  14405. }
  14406. bool PropertiesFile::saveIfNeeded()
  14407. {
  14408. const ScopedLock sl (getLock());
  14409. return (! needsWriting) || save();
  14410. }
  14411. bool PropertiesFile::needsToBeSaved() const
  14412. {
  14413. const ScopedLock sl (getLock());
  14414. return needsWriting;
  14415. }
  14416. void PropertiesFile::setNeedsToBeSaved (const bool needsToBeSaved)
  14417. {
  14418. const ScopedLock sl (getLock());
  14419. needsWriting = needsToBeSaved;
  14420. }
  14421. bool PropertiesFile::save()
  14422. {
  14423. const ScopedLock sl (getLock());
  14424. stopTimer();
  14425. if (file == File::nonexistent
  14426. || file.isDirectory()
  14427. || ! file.getParentDirectory().createDirectory())
  14428. return false;
  14429. if ((options & storeAsXML) != 0)
  14430. {
  14431. XmlElement doc (PropertyFileConstants::fileTag);
  14432. for (int i = 0; i < getAllProperties().size(); ++i)
  14433. {
  14434. XmlElement* const e = doc.createNewChildElement (PropertyFileConstants::valueTag);
  14435. e->setAttribute (PropertyFileConstants::nameAttribute, getAllProperties().getAllKeys() [i]);
  14436. // if the value seems to contain xml, store it as such..
  14437. XmlDocument xmlContent (getAllProperties().getAllValues() [i]);
  14438. XmlElement* const childElement = xmlContent.getDocumentElement();
  14439. if (childElement != 0)
  14440. e->addChildElement (childElement);
  14441. else
  14442. e->setAttribute (PropertyFileConstants::valueAttribute,
  14443. getAllProperties().getAllValues() [i]);
  14444. }
  14445. ProcessScopedLock pl (createProcessLock());
  14446. if (pl != 0 && ! pl->isLocked())
  14447. return false; // locking failure..
  14448. if (doc.writeToFile (file, String::empty))
  14449. {
  14450. needsWriting = false;
  14451. return true;
  14452. }
  14453. }
  14454. else
  14455. {
  14456. ProcessScopedLock pl (createProcessLock());
  14457. if (pl != 0 && ! pl->isLocked())
  14458. return false; // locking failure..
  14459. TemporaryFile tempFile (file);
  14460. ScopedPointer <OutputStream> out (tempFile.getFile().createOutputStream());
  14461. if (out != 0)
  14462. {
  14463. if ((options & storeAsCompressedBinary) != 0)
  14464. {
  14465. out->writeInt (PropertyFileConstants::magicNumberCompressed);
  14466. out->flush();
  14467. out = new GZIPCompressorOutputStream (out.release(), 9, true);
  14468. }
  14469. else
  14470. {
  14471. // have you set up the storage option flags correctly?
  14472. jassert ((options & storeAsBinary) != 0);
  14473. out->writeInt (PropertyFileConstants::magicNumber);
  14474. }
  14475. const int numProperties = getAllProperties().size();
  14476. out->writeInt (numProperties);
  14477. for (int i = 0; i < numProperties; ++i)
  14478. {
  14479. out->writeString (getAllProperties().getAllKeys() [i]);
  14480. out->writeString (getAllProperties().getAllValues() [i]);
  14481. }
  14482. out = 0;
  14483. if (tempFile.overwriteTargetFileWithTemporary())
  14484. {
  14485. needsWriting = false;
  14486. return true;
  14487. }
  14488. }
  14489. }
  14490. return false;
  14491. }
  14492. void PropertiesFile::timerCallback()
  14493. {
  14494. saveIfNeeded();
  14495. }
  14496. void PropertiesFile::propertyChanged()
  14497. {
  14498. sendChangeMessage (this);
  14499. needsWriting = true;
  14500. if (timerInterval > 0)
  14501. startTimer (timerInterval);
  14502. else if (timerInterval == 0)
  14503. saveIfNeeded();
  14504. }
  14505. const File PropertiesFile::getDefaultAppSettingsFile (const String& applicationName,
  14506. const String& fileNameSuffix,
  14507. const String& folderName,
  14508. const bool commonToAllUsers)
  14509. {
  14510. // mustn't have illegal characters in this name..
  14511. jassert (applicationName == File::createLegalFileName (applicationName));
  14512. #if JUCE_MAC || JUCE_IPHONE
  14513. File dir (commonToAllUsers ? "/Library/Preferences"
  14514. : "~/Library/Preferences");
  14515. if (folderName.isNotEmpty())
  14516. dir = dir.getChildFile (folderName);
  14517. #endif
  14518. #ifdef JUCE_LINUX
  14519. const File dir ((commonToAllUsers ? "/var/" : "~/")
  14520. + (folderName.isNotEmpty() ? folderName
  14521. : ("." + applicationName)));
  14522. #endif
  14523. #if JUCE_WIN32
  14524. File dir (File::getSpecialLocation (commonToAllUsers ? File::commonApplicationDataDirectory
  14525. : File::userApplicationDataDirectory));
  14526. if (dir == File::nonexistent)
  14527. return File::nonexistent;
  14528. dir = dir.getChildFile (folderName.isNotEmpty() ? folderName
  14529. : applicationName);
  14530. #endif
  14531. return dir.getChildFile (applicationName)
  14532. .withFileExtension (fileNameSuffix);
  14533. }
  14534. PropertiesFile* PropertiesFile::createDefaultAppPropertiesFile (const String& applicationName,
  14535. const String& fileNameSuffix,
  14536. const String& folderName,
  14537. const bool commonToAllUsers,
  14538. const int millisecondsBeforeSaving,
  14539. const int propertiesFileOptions,
  14540. InterProcessLock* processLock_)
  14541. {
  14542. const File file (getDefaultAppSettingsFile (applicationName,
  14543. fileNameSuffix,
  14544. folderName,
  14545. commonToAllUsers));
  14546. jassert (file != File::nonexistent);
  14547. if (file == File::nonexistent)
  14548. return 0;
  14549. return new PropertiesFile (file, millisecondsBeforeSaving, propertiesFileOptions,processLock_);
  14550. }
  14551. END_JUCE_NAMESPACE
  14552. /*** End of inlined file: juce_PropertiesFile.cpp ***/
  14553. /*** Start of inlined file: juce_FileBasedDocument.cpp ***/
  14554. BEGIN_JUCE_NAMESPACE
  14555. FileBasedDocument::FileBasedDocument (const String& fileExtension_,
  14556. const String& fileWildcard_,
  14557. const String& openFileDialogTitle_,
  14558. const String& saveFileDialogTitle_)
  14559. : changedSinceSave (false),
  14560. fileExtension (fileExtension_),
  14561. fileWildcard (fileWildcard_),
  14562. openFileDialogTitle (openFileDialogTitle_),
  14563. saveFileDialogTitle (saveFileDialogTitle_)
  14564. {
  14565. }
  14566. FileBasedDocument::~FileBasedDocument()
  14567. {
  14568. }
  14569. void FileBasedDocument::setChangedFlag (const bool hasChanged)
  14570. {
  14571. if (changedSinceSave != hasChanged)
  14572. {
  14573. changedSinceSave = hasChanged;
  14574. sendChangeMessage (this);
  14575. }
  14576. }
  14577. void FileBasedDocument::changed()
  14578. {
  14579. changedSinceSave = true;
  14580. sendChangeMessage (this);
  14581. }
  14582. void FileBasedDocument::setFile (const File& newFile)
  14583. {
  14584. if (documentFile != newFile)
  14585. {
  14586. documentFile = newFile;
  14587. changed();
  14588. }
  14589. }
  14590. bool FileBasedDocument::loadFrom (const File& newFile,
  14591. const bool showMessageOnFailure)
  14592. {
  14593. MouseCursor::showWaitCursor();
  14594. const File oldFile (documentFile);
  14595. documentFile = newFile;
  14596. String error;
  14597. if (newFile.existsAsFile())
  14598. {
  14599. error = loadDocument (newFile);
  14600. if (error.isEmpty())
  14601. {
  14602. setChangedFlag (false);
  14603. MouseCursor::hideWaitCursor();
  14604. setLastDocumentOpened (newFile);
  14605. return true;
  14606. }
  14607. }
  14608. else
  14609. {
  14610. error = "The file doesn't exist";
  14611. }
  14612. documentFile = oldFile;
  14613. MouseCursor::hideWaitCursor();
  14614. if (showMessageOnFailure)
  14615. {
  14616. AlertWindow::showMessageBox (AlertWindow::WarningIcon,
  14617. TRANS("Failed to open file..."),
  14618. TRANS("There was an error while trying to load the file:\n\n")
  14619. + newFile.getFullPathName()
  14620. + "\n\n"
  14621. + error);
  14622. }
  14623. return false;
  14624. }
  14625. bool FileBasedDocument::loadFromUserSpecifiedFile (const bool showMessageOnFailure)
  14626. {
  14627. FileChooser fc (openFileDialogTitle,
  14628. getLastDocumentOpened(),
  14629. fileWildcard);
  14630. if (fc.browseForFileToOpen())
  14631. return loadFrom (fc.getResult(), showMessageOnFailure);
  14632. return false;
  14633. }
  14634. FileBasedDocument::SaveResult FileBasedDocument::save (const bool askUserForFileIfNotSpecified,
  14635. const bool showMessageOnFailure)
  14636. {
  14637. return saveAs (documentFile,
  14638. false,
  14639. askUserForFileIfNotSpecified,
  14640. showMessageOnFailure);
  14641. }
  14642. FileBasedDocument::SaveResult FileBasedDocument::saveAs (const File& newFile,
  14643. const bool warnAboutOverwritingExistingFiles,
  14644. const bool askUserForFileIfNotSpecified,
  14645. const bool showMessageOnFailure)
  14646. {
  14647. if (newFile == File::nonexistent)
  14648. {
  14649. if (askUserForFileIfNotSpecified)
  14650. {
  14651. return saveAsInteractive (true);
  14652. }
  14653. else
  14654. {
  14655. // can't save to an unspecified file
  14656. jassertfalse
  14657. return failedToWriteToFile;
  14658. }
  14659. }
  14660. if (warnAboutOverwritingExistingFiles && newFile.exists())
  14661. {
  14662. if (! AlertWindow::showOkCancelBox (AlertWindow::WarningIcon,
  14663. TRANS("File already exists"),
  14664. TRANS("There's already a file called:\n\n")
  14665. + newFile.getFullPathName()
  14666. + TRANS("\n\nAre you sure you want to overwrite it?"),
  14667. TRANS("overwrite"),
  14668. TRANS("cancel")))
  14669. {
  14670. return userCancelledSave;
  14671. }
  14672. }
  14673. MouseCursor::showWaitCursor();
  14674. const File oldFile (documentFile);
  14675. documentFile = newFile;
  14676. String error (saveDocument (newFile));
  14677. if (error.isEmpty())
  14678. {
  14679. setChangedFlag (false);
  14680. MouseCursor::hideWaitCursor();
  14681. return savedOk;
  14682. }
  14683. documentFile = oldFile;
  14684. MouseCursor::hideWaitCursor();
  14685. if (showMessageOnFailure)
  14686. {
  14687. AlertWindow::showMessageBox (AlertWindow::WarningIcon,
  14688. TRANS("Error writing to file..."),
  14689. TRANS("An error occurred while trying to save \"")
  14690. + getDocumentTitle()
  14691. + TRANS("\" to the file:\n\n")
  14692. + newFile.getFullPathName()
  14693. + "\n\n"
  14694. + error);
  14695. }
  14696. return failedToWriteToFile;
  14697. }
  14698. FileBasedDocument::SaveResult FileBasedDocument::saveIfNeededAndUserAgrees()
  14699. {
  14700. if (! hasChangedSinceSaved())
  14701. return savedOk;
  14702. const int r = AlertWindow::showYesNoCancelBox (AlertWindow::QuestionIcon,
  14703. TRANS("Closing document..."),
  14704. TRANS("Do you want to save the changes to \"")
  14705. + getDocumentTitle() + "\"?",
  14706. TRANS("save"),
  14707. TRANS("discard changes"),
  14708. TRANS("cancel"));
  14709. if (r == 1)
  14710. {
  14711. // save changes
  14712. return save (true, true);
  14713. }
  14714. else if (r == 2)
  14715. {
  14716. // discard changes
  14717. return savedOk;
  14718. }
  14719. return userCancelledSave;
  14720. }
  14721. FileBasedDocument::SaveResult FileBasedDocument::saveAsInteractive (const bool warnAboutOverwritingExistingFiles)
  14722. {
  14723. File f;
  14724. if (documentFile.existsAsFile())
  14725. f = documentFile;
  14726. else
  14727. f = getLastDocumentOpened();
  14728. String legalFilename (File::createLegalFileName (getDocumentTitle()));
  14729. if (legalFilename.isEmpty())
  14730. legalFilename = "unnamed";
  14731. if (f.existsAsFile() || f.getParentDirectory().isDirectory())
  14732. f = f.getSiblingFile (legalFilename);
  14733. else
  14734. f = File::getSpecialLocation (File::userDocumentsDirectory).getChildFile (legalFilename);
  14735. f = f.withFileExtension (fileExtension)
  14736. .getNonexistentSibling (true);
  14737. FileChooser fc (saveFileDialogTitle, f, fileWildcard);
  14738. if (fc.browseForFileToSave (warnAboutOverwritingExistingFiles))
  14739. {
  14740. setLastDocumentOpened (fc.getResult());
  14741. File chosen (fc.getResult());
  14742. if (chosen.getFileExtension().isEmpty())
  14743. {
  14744. chosen = chosen.withFileExtension (fileExtension);
  14745. if (chosen.exists())
  14746. {
  14747. if (! AlertWindow::showOkCancelBox (AlertWindow::WarningIcon,
  14748. TRANS("File already exists"),
  14749. TRANS("There's already a file called:")
  14750. + "\n\n" + chosen.getFullPathName()
  14751. + "\n\n" + TRANS("Are you sure you want to overwrite it?"),
  14752. TRANS("overwrite"),
  14753. TRANS("cancel")))
  14754. {
  14755. return userCancelledSave;
  14756. }
  14757. }
  14758. }
  14759. return saveAs (chosen, false, false, true);
  14760. }
  14761. return userCancelledSave;
  14762. }
  14763. END_JUCE_NAMESPACE
  14764. /*** End of inlined file: juce_FileBasedDocument.cpp ***/
  14765. /*** Start of inlined file: juce_RecentlyOpenedFilesList.cpp ***/
  14766. BEGIN_JUCE_NAMESPACE
  14767. RecentlyOpenedFilesList::RecentlyOpenedFilesList()
  14768. : maxNumberOfItems (10)
  14769. {
  14770. }
  14771. RecentlyOpenedFilesList::~RecentlyOpenedFilesList()
  14772. {
  14773. }
  14774. void RecentlyOpenedFilesList::setMaxNumberOfItems (const int newMaxNumber)
  14775. {
  14776. maxNumberOfItems = jmax (1, newMaxNumber);
  14777. while (getNumFiles() > maxNumberOfItems)
  14778. files.remove (getNumFiles() - 1);
  14779. }
  14780. int RecentlyOpenedFilesList::getNumFiles() const
  14781. {
  14782. return files.size();
  14783. }
  14784. const File RecentlyOpenedFilesList::getFile (const int index) const
  14785. {
  14786. return File (files [index]);
  14787. }
  14788. void RecentlyOpenedFilesList::clear()
  14789. {
  14790. files.clear();
  14791. }
  14792. void RecentlyOpenedFilesList::addFile (const File& file)
  14793. {
  14794. const String path (file.getFullPathName());
  14795. files.removeString (path, true);
  14796. files.insert (0, path);
  14797. setMaxNumberOfItems (maxNumberOfItems);
  14798. }
  14799. void RecentlyOpenedFilesList::removeNonExistentFiles()
  14800. {
  14801. for (int i = getNumFiles(); --i >= 0;)
  14802. if (! getFile(i).exists())
  14803. files.remove (i);
  14804. }
  14805. int RecentlyOpenedFilesList::createPopupMenuItems (PopupMenu& menuToAddTo,
  14806. const int baseItemId,
  14807. const bool showFullPaths,
  14808. const bool dontAddNonExistentFiles,
  14809. const File** filesToAvoid)
  14810. {
  14811. int num = 0;
  14812. for (int i = 0; i < getNumFiles(); ++i)
  14813. {
  14814. const File f (getFile(i));
  14815. if ((! dontAddNonExistentFiles) || f.exists())
  14816. {
  14817. bool needsAvoiding = false;
  14818. if (filesToAvoid != 0)
  14819. {
  14820. const File** avoid = filesToAvoid;
  14821. while (*avoid != 0)
  14822. {
  14823. if (f == **avoid)
  14824. {
  14825. needsAvoiding = true;
  14826. break;
  14827. }
  14828. ++avoid;
  14829. }
  14830. }
  14831. if (! needsAvoiding)
  14832. {
  14833. menuToAddTo.addItem (baseItemId + i,
  14834. showFullPaths ? f.getFullPathName()
  14835. : f.getFileName());
  14836. ++num;
  14837. }
  14838. }
  14839. }
  14840. return num;
  14841. }
  14842. const String RecentlyOpenedFilesList::toString() const
  14843. {
  14844. return files.joinIntoString ("\n");
  14845. }
  14846. void RecentlyOpenedFilesList::restoreFromString (const String& stringifiedVersion)
  14847. {
  14848. clear();
  14849. files.addLines (stringifiedVersion);
  14850. setMaxNumberOfItems (maxNumberOfItems);
  14851. }
  14852. END_JUCE_NAMESPACE
  14853. /*** End of inlined file: juce_RecentlyOpenedFilesList.cpp ***/
  14854. /*** Start of inlined file: juce_UndoManager.cpp ***/
  14855. BEGIN_JUCE_NAMESPACE
  14856. UndoManager::UndoManager (const int maxNumberOfUnitsToKeep,
  14857. const int minimumTransactions)
  14858. : totalUnitsStored (0),
  14859. nextIndex (0),
  14860. newTransaction (true),
  14861. reentrancyCheck (false)
  14862. {
  14863. setMaxNumberOfStoredUnits (maxNumberOfUnitsToKeep,
  14864. minimumTransactions);
  14865. }
  14866. UndoManager::~UndoManager()
  14867. {
  14868. clearUndoHistory();
  14869. }
  14870. void UndoManager::clearUndoHistory()
  14871. {
  14872. transactions.clear();
  14873. transactionNames.clear();
  14874. totalUnitsStored = 0;
  14875. nextIndex = 0;
  14876. sendChangeMessage (this);
  14877. }
  14878. int UndoManager::getNumberOfUnitsTakenUpByStoredCommands() const
  14879. {
  14880. return totalUnitsStored;
  14881. }
  14882. void UndoManager::setMaxNumberOfStoredUnits (const int maxNumberOfUnitsToKeep,
  14883. const int minimumTransactions)
  14884. {
  14885. maxNumUnitsToKeep = jmax (1, maxNumberOfUnitsToKeep);
  14886. minimumTransactionsToKeep = jmax (1, minimumTransactions);
  14887. }
  14888. bool UndoManager::perform (UndoableAction* const command, const String& actionName)
  14889. {
  14890. if (command != 0)
  14891. {
  14892. if (actionName.isNotEmpty())
  14893. currentTransactionName = actionName;
  14894. if (reentrancyCheck)
  14895. {
  14896. jassertfalse // don't call perform() recursively from the UndoableAction::perform() or
  14897. // undo() methods, or else these actions won't actually get done.
  14898. return false;
  14899. }
  14900. else
  14901. {
  14902. bool success = false;
  14903. JUCE_TRY
  14904. {
  14905. success = command->perform();
  14906. }
  14907. JUCE_CATCH_EXCEPTION
  14908. jassert (success);
  14909. if (success)
  14910. {
  14911. if (nextIndex > 0 && ! newTransaction)
  14912. {
  14913. OwnedArray<UndoableAction>* commandSet = transactions [nextIndex - 1];
  14914. jassert (commandSet != 0);
  14915. if (commandSet == 0)
  14916. return false;
  14917. commandSet->add (command);
  14918. }
  14919. else
  14920. {
  14921. OwnedArray<UndoableAction>* commandSet = new OwnedArray<UndoableAction>();
  14922. commandSet->add (command);
  14923. transactions.insert (nextIndex, commandSet);
  14924. transactionNames.insert (nextIndex, currentTransactionName);
  14925. ++nextIndex;
  14926. }
  14927. totalUnitsStored += command->getSizeInUnits();
  14928. newTransaction = false;
  14929. }
  14930. while (nextIndex < transactions.size())
  14931. {
  14932. const OwnedArray <UndoableAction>* const lastSet = transactions.getLast();
  14933. for (int i = lastSet->size(); --i >= 0;)
  14934. totalUnitsStored -= lastSet->getUnchecked (i)->getSizeInUnits();
  14935. transactions.removeLast();
  14936. transactionNames.remove (transactionNames.size() - 1);
  14937. }
  14938. while (nextIndex > 0
  14939. && totalUnitsStored > maxNumUnitsToKeep
  14940. && transactions.size() > minimumTransactionsToKeep)
  14941. {
  14942. const OwnedArray <UndoableAction>* const firstSet = transactions.getFirst();
  14943. for (int i = firstSet->size(); --i >= 0;)
  14944. totalUnitsStored -= firstSet->getUnchecked (i)->getSizeInUnits();
  14945. jassert (totalUnitsStored >= 0); // something fishy going on if this fails!
  14946. transactions.remove (0);
  14947. transactionNames.remove (0);
  14948. --nextIndex;
  14949. }
  14950. sendChangeMessage (this);
  14951. return success;
  14952. }
  14953. }
  14954. return false;
  14955. }
  14956. void UndoManager::beginNewTransaction (const String& actionName)
  14957. {
  14958. newTransaction = true;
  14959. currentTransactionName = actionName;
  14960. }
  14961. void UndoManager::setCurrentTransactionName (const String& newName)
  14962. {
  14963. currentTransactionName = newName;
  14964. }
  14965. bool UndoManager::canUndo() const
  14966. {
  14967. return nextIndex > 0;
  14968. }
  14969. bool UndoManager::canRedo() const
  14970. {
  14971. return nextIndex < transactions.size();
  14972. }
  14973. const String UndoManager::getUndoDescription() const
  14974. {
  14975. return transactionNames [nextIndex - 1];
  14976. }
  14977. const String UndoManager::getRedoDescription() const
  14978. {
  14979. return transactionNames [nextIndex];
  14980. }
  14981. bool UndoManager::undo()
  14982. {
  14983. const OwnedArray<UndoableAction>* const commandSet = transactions [nextIndex - 1];
  14984. if (commandSet == 0)
  14985. return false;
  14986. reentrancyCheck = true;
  14987. bool failed = false;
  14988. for (int i = commandSet->size(); --i >= 0;)
  14989. {
  14990. if (! commandSet->getUnchecked(i)->undo())
  14991. {
  14992. jassertfalse
  14993. failed = true;
  14994. break;
  14995. }
  14996. }
  14997. reentrancyCheck = false;
  14998. if (failed)
  14999. {
  15000. clearUndoHistory();
  15001. }
  15002. else
  15003. {
  15004. --nextIndex;
  15005. }
  15006. beginNewTransaction();
  15007. sendChangeMessage (this);
  15008. return true;
  15009. }
  15010. bool UndoManager::redo()
  15011. {
  15012. const OwnedArray<UndoableAction>* const commandSet = transactions [nextIndex];
  15013. if (commandSet == 0)
  15014. return false;
  15015. reentrancyCheck = true;
  15016. bool failed = false;
  15017. for (int i = 0; i < commandSet->size(); ++i)
  15018. {
  15019. if (! commandSet->getUnchecked(i)->perform())
  15020. {
  15021. jassertfalse
  15022. failed = true;
  15023. break;
  15024. }
  15025. }
  15026. reentrancyCheck = false;
  15027. if (failed)
  15028. {
  15029. clearUndoHistory();
  15030. }
  15031. else
  15032. {
  15033. ++nextIndex;
  15034. }
  15035. beginNewTransaction();
  15036. sendChangeMessage (this);
  15037. return true;
  15038. }
  15039. bool UndoManager::undoCurrentTransactionOnly()
  15040. {
  15041. return newTransaction ? false
  15042. : undo();
  15043. }
  15044. void UndoManager::getActionsInCurrentTransaction (Array <const UndoableAction*>& actionsFound) const
  15045. {
  15046. const OwnedArray <UndoableAction>* const commandSet = transactions [nextIndex - 1];
  15047. if (commandSet != 0 && ! newTransaction)
  15048. {
  15049. for (int i = 0; i < commandSet->size(); ++i)
  15050. actionsFound.add (commandSet->getUnchecked(i));
  15051. }
  15052. }
  15053. int UndoManager::getNumActionsInCurrentTransaction() const
  15054. {
  15055. const OwnedArray <UndoableAction>* const commandSet = transactions [nextIndex - 1];
  15056. if (commandSet != 0 && ! newTransaction)
  15057. return commandSet->size();
  15058. return 0;
  15059. }
  15060. END_JUCE_NAMESPACE
  15061. /*** End of inlined file: juce_UndoManager.cpp ***/
  15062. /*** Start of inlined file: juce_AiffAudioFormat.cpp ***/
  15063. BEGIN_JUCE_NAMESPACE
  15064. static const char* const aiffFormatName = "AIFF file";
  15065. static const juce_wchar* const aiffExtensions[] = { T(".aiff"), T(".aif"), 0 };
  15066. class AiffAudioFormatReader : public AudioFormatReader
  15067. {
  15068. public:
  15069. int bytesPerFrame;
  15070. int64 dataChunkStart;
  15071. bool littleEndian;
  15072. AiffAudioFormatReader (InputStream* in)
  15073. : AudioFormatReader (in, TRANS (aiffFormatName))
  15074. {
  15075. if (input->readInt() == chunkName ("FORM"))
  15076. {
  15077. const int len = input->readIntBigEndian();
  15078. const int64 end = input->getPosition() + len;
  15079. const int nextType = input->readInt();
  15080. if (nextType == chunkName ("AIFF") || nextType == chunkName ("AIFC"))
  15081. {
  15082. bool hasGotVer = false;
  15083. bool hasGotData = false;
  15084. bool hasGotType = false;
  15085. while (input->getPosition() < end)
  15086. {
  15087. const int type = input->readInt();
  15088. const uint32 length = (uint32) input->readIntBigEndian();
  15089. const int64 chunkEnd = input->getPosition() + length;
  15090. if (type == chunkName ("FVER"))
  15091. {
  15092. hasGotVer = true;
  15093. const int ver = input->readIntBigEndian();
  15094. if (ver != 0 && ver != (int)0xa2805140)
  15095. break;
  15096. }
  15097. else if (type == chunkName ("COMM"))
  15098. {
  15099. hasGotType = true;
  15100. numChannels = (unsigned int)input->readShortBigEndian();
  15101. lengthInSamples = input->readIntBigEndian();
  15102. bitsPerSample = input->readShortBigEndian();
  15103. bytesPerFrame = (numChannels * bitsPerSample) >> 3;
  15104. unsigned char sampleRateBytes[10];
  15105. input->read (sampleRateBytes, 10);
  15106. const int byte0 = sampleRateBytes[0];
  15107. if ((byte0 & 0x80) != 0
  15108. || byte0 <= 0x3F || byte0 > 0x40
  15109. || (byte0 == 0x40 && sampleRateBytes[1] > 0x1C))
  15110. break;
  15111. unsigned int sampRate = ByteOrder::bigEndianInt (sampleRateBytes + 2);
  15112. sampRate >>= (16414 - ByteOrder::bigEndianShort (sampleRateBytes));
  15113. sampleRate = (int) sampRate;
  15114. if (length <= 18)
  15115. {
  15116. // some types don't have a chunk large enough to include a compression
  15117. // type, so assume it's just big-endian pcm
  15118. littleEndian = false;
  15119. }
  15120. else
  15121. {
  15122. const int compType = input->readInt();
  15123. if (compType == chunkName ("NONE") || compType == chunkName ("twos"))
  15124. {
  15125. littleEndian = false;
  15126. }
  15127. else if (compType == chunkName ("sowt"))
  15128. {
  15129. littleEndian = true;
  15130. }
  15131. else
  15132. {
  15133. sampleRate = 0;
  15134. break;
  15135. }
  15136. }
  15137. }
  15138. else if (type == chunkName ("SSND"))
  15139. {
  15140. hasGotData = true;
  15141. const int offset = input->readIntBigEndian();
  15142. dataChunkStart = input->getPosition() + 4 + offset;
  15143. lengthInSamples = (bytesPerFrame > 0) ? jmin (lengthInSamples, (int64) (length / bytesPerFrame)) : 0;
  15144. }
  15145. else if ((hasGotVer && hasGotData && hasGotType)
  15146. || chunkEnd < input->getPosition()
  15147. || input->isExhausted())
  15148. {
  15149. break;
  15150. }
  15151. input->setPosition (chunkEnd);
  15152. }
  15153. }
  15154. }
  15155. }
  15156. ~AiffAudioFormatReader()
  15157. {
  15158. }
  15159. bool readSamples (int** destSamples, int numDestChannels, int startOffsetInDestBuffer,
  15160. int64 startSampleInFile, int numSamples)
  15161. {
  15162. const int64 samplesAvailable = lengthInSamples - startSampleInFile;
  15163. if (samplesAvailable < numSamples)
  15164. {
  15165. for (int i = numDestChannels; --i >= 0;)
  15166. if (destSamples[i] != 0)
  15167. zeromem (destSamples[i] + startOffsetInDestBuffer, sizeof (int) * numSamples);
  15168. numSamples = (int) samplesAvailable;
  15169. }
  15170. if (numSamples <= 0)
  15171. return true;
  15172. input->setPosition (dataChunkStart + startSampleInFile * bytesPerFrame);
  15173. const int tempBufSize = 480 * 3 * 4; // (keep this a multiple of 3)
  15174. char tempBuffer [tempBufSize];
  15175. while (numSamples > 0)
  15176. {
  15177. int* left = destSamples[0];
  15178. if (left != 0)
  15179. left += startOffsetInDestBuffer;
  15180. int* right = numDestChannels > 1 ? destSamples[1] : 0;
  15181. if (right != 0)
  15182. right += startOffsetInDestBuffer;
  15183. const int numThisTime = jmin (tempBufSize / bytesPerFrame, numSamples);
  15184. const int bytesRead = input->read (tempBuffer, numThisTime * bytesPerFrame);
  15185. if (bytesRead < numThisTime * bytesPerFrame)
  15186. zeromem (tempBuffer + bytesRead, numThisTime * bytesPerFrame - bytesRead);
  15187. if (bitsPerSample == 16)
  15188. {
  15189. if (littleEndian)
  15190. {
  15191. const short* src = reinterpret_cast <const short*> (tempBuffer);
  15192. if (numChannels > 1)
  15193. {
  15194. if (left == 0)
  15195. {
  15196. for (int i = numThisTime; --i >= 0;)
  15197. {
  15198. *right++ = (int) ByteOrder::swapIfBigEndian ((unsigned short) *src++) << 16;
  15199. ++src;
  15200. }
  15201. }
  15202. else if (right == 0)
  15203. {
  15204. for (int i = numThisTime; --i >= 0;)
  15205. {
  15206. ++src;
  15207. *left++ = (int) ByteOrder::swapIfBigEndian ((unsigned short) *src++) << 16;
  15208. }
  15209. }
  15210. else
  15211. {
  15212. for (int i = numThisTime; --i >= 0;)
  15213. {
  15214. *left++ = (int) ByteOrder::swapIfBigEndian ((unsigned short) *src++) << 16;
  15215. *right++ = (int) ByteOrder::swapIfBigEndian ((unsigned short) *src++) << 16;
  15216. }
  15217. }
  15218. }
  15219. else
  15220. {
  15221. for (int i = numThisTime; --i >= 0;)
  15222. {
  15223. *left++ = (int) ByteOrder::swapIfBigEndian ((unsigned short) *src++) << 16;
  15224. }
  15225. }
  15226. }
  15227. else
  15228. {
  15229. const char* src = tempBuffer;
  15230. if (numChannels > 1)
  15231. {
  15232. if (left == 0)
  15233. {
  15234. for (int i = numThisTime; --i >= 0;)
  15235. {
  15236. *right++ = ByteOrder::bigEndianShort (src) << 16;
  15237. src += 4;
  15238. }
  15239. }
  15240. else if (right == 0)
  15241. {
  15242. for (int i = numThisTime; --i >= 0;)
  15243. {
  15244. src += 2;
  15245. *left++ = ByteOrder::bigEndianShort (src) << 16;
  15246. src += 2;
  15247. }
  15248. }
  15249. else
  15250. {
  15251. for (int i = numThisTime; --i >= 0;)
  15252. {
  15253. *left++ = ByteOrder::bigEndianShort (src) << 16;
  15254. src += 2;
  15255. *right++ = ByteOrder::bigEndianShort (src) << 16;
  15256. src += 2;
  15257. }
  15258. }
  15259. }
  15260. else
  15261. {
  15262. for (int i = numThisTime; --i >= 0;)
  15263. {
  15264. *left++ = ByteOrder::bigEndianShort (src) << 16;
  15265. src += 2;
  15266. }
  15267. }
  15268. }
  15269. }
  15270. else if (bitsPerSample == 24)
  15271. {
  15272. const char* src = (const char*)tempBuffer;
  15273. if (littleEndian)
  15274. {
  15275. if (numChannels > 1)
  15276. {
  15277. if (left == 0)
  15278. {
  15279. for (int i = numThisTime; --i >= 0;)
  15280. {
  15281. *right++ = ByteOrder::littleEndian24Bit (src) << 8;
  15282. src += 6;
  15283. }
  15284. }
  15285. else if (right == 0)
  15286. {
  15287. for (int i = numThisTime; --i >= 0;)
  15288. {
  15289. src += 3;
  15290. *left++ = ByteOrder::littleEndian24Bit (src) << 8;
  15291. src += 3;
  15292. }
  15293. }
  15294. else
  15295. {
  15296. for (int i = numThisTime; --i >= 0;)
  15297. {
  15298. *left++ = ByteOrder::littleEndian24Bit (src) << 8;
  15299. src += 3;
  15300. *right++ = ByteOrder::littleEndian24Bit (src) << 8;
  15301. src += 3;
  15302. }
  15303. }
  15304. }
  15305. else
  15306. {
  15307. for (int i = numThisTime; --i >= 0;)
  15308. {
  15309. *left++ = ByteOrder::littleEndian24Bit (src) << 8;
  15310. src += 3;
  15311. }
  15312. }
  15313. }
  15314. else
  15315. {
  15316. if (numChannels > 1)
  15317. {
  15318. if (left == 0)
  15319. {
  15320. for (int i = numThisTime; --i >= 0;)
  15321. {
  15322. *right++ = ByteOrder::bigEndian24Bit (src) << 8;
  15323. src += 6;
  15324. }
  15325. }
  15326. else if (right == 0)
  15327. {
  15328. for (int i = numThisTime; --i >= 0;)
  15329. {
  15330. src += 3;
  15331. *left++ = ByteOrder::bigEndian24Bit (src) << 8;
  15332. src += 3;
  15333. }
  15334. }
  15335. else
  15336. {
  15337. for (int i = numThisTime; --i >= 0;)
  15338. {
  15339. *left++ = ByteOrder::bigEndian24Bit (src) << 8;
  15340. src += 3;
  15341. *right++ = ByteOrder::bigEndian24Bit (src) << 8;
  15342. src += 3;
  15343. }
  15344. }
  15345. }
  15346. else
  15347. {
  15348. for (int i = numThisTime; --i >= 0;)
  15349. {
  15350. *left++ = ByteOrder::bigEndian24Bit (src) << 8;
  15351. src += 3;
  15352. }
  15353. }
  15354. }
  15355. }
  15356. else if (bitsPerSample == 32)
  15357. {
  15358. const unsigned int* src = reinterpret_cast <const unsigned int*> (tempBuffer);
  15359. unsigned int* l = reinterpret_cast <unsigned int*> (left);
  15360. unsigned int* r = reinterpret_cast <unsigned int*> (right);
  15361. if (littleEndian)
  15362. {
  15363. if (numChannels > 1)
  15364. {
  15365. if (l == 0)
  15366. {
  15367. for (int i = numThisTime; --i >= 0;)
  15368. {
  15369. ++src;
  15370. *r++ = ByteOrder::swapIfBigEndian (*src++);
  15371. }
  15372. }
  15373. else if (r == 0)
  15374. {
  15375. for (int i = numThisTime; --i >= 0;)
  15376. {
  15377. *l++ = ByteOrder::swapIfBigEndian (*src++);
  15378. ++src;
  15379. }
  15380. }
  15381. else
  15382. {
  15383. for (int i = numThisTime; --i >= 0;)
  15384. {
  15385. *l++ = ByteOrder::swapIfBigEndian (*src++);
  15386. *r++ = ByteOrder::swapIfBigEndian (*src++);
  15387. }
  15388. }
  15389. }
  15390. else
  15391. {
  15392. for (int i = numThisTime; --i >= 0;)
  15393. {
  15394. *l++ = ByteOrder::swapIfBigEndian (*src++);
  15395. }
  15396. }
  15397. }
  15398. else
  15399. {
  15400. if (numChannels > 1)
  15401. {
  15402. if (l == 0)
  15403. {
  15404. for (int i = numThisTime; --i >= 0;)
  15405. {
  15406. ++src;
  15407. *r++ = ByteOrder::swapIfLittleEndian (*src++);
  15408. }
  15409. }
  15410. else if (r == 0)
  15411. {
  15412. for (int i = numThisTime; --i >= 0;)
  15413. {
  15414. *l++ = ByteOrder::swapIfLittleEndian (*src++);
  15415. ++src;
  15416. }
  15417. }
  15418. else
  15419. {
  15420. for (int i = numThisTime; --i >= 0;)
  15421. {
  15422. *l++ = ByteOrder::swapIfLittleEndian (*src++);
  15423. *r++ = ByteOrder::swapIfLittleEndian (*src++);
  15424. }
  15425. }
  15426. }
  15427. else
  15428. {
  15429. for (int i = numThisTime; --i >= 0;)
  15430. {
  15431. *l++ = ByteOrder::swapIfLittleEndian (*src++);
  15432. }
  15433. }
  15434. }
  15435. left = reinterpret_cast <int*> (l);
  15436. right = reinterpret_cast <int*> (r);
  15437. }
  15438. else if (bitsPerSample == 8)
  15439. {
  15440. const char* src = tempBuffer;
  15441. if (numChannels > 1)
  15442. {
  15443. if (left == 0)
  15444. {
  15445. for (int i = numThisTime; --i >= 0;)
  15446. {
  15447. *right++ = ((int) *src++) << 24;
  15448. ++src;
  15449. }
  15450. }
  15451. else if (right == 0)
  15452. {
  15453. for (int i = numThisTime; --i >= 0;)
  15454. {
  15455. ++src;
  15456. *left++ = ((int) *src++) << 24;
  15457. }
  15458. }
  15459. else
  15460. {
  15461. for (int i = numThisTime; --i >= 0;)
  15462. {
  15463. *left++ = ((int) *src++) << 24;
  15464. *right++ = ((int) *src++) << 24;
  15465. }
  15466. }
  15467. }
  15468. else
  15469. {
  15470. for (int i = numThisTime; --i >= 0;)
  15471. {
  15472. *left++ = ((int) *src++) << 24;
  15473. }
  15474. }
  15475. }
  15476. startOffsetInDestBuffer += numThisTime;
  15477. numSamples -= numThisTime;
  15478. }
  15479. if (numSamples > 0)
  15480. {
  15481. for (int i = numDestChannels; --i >= 0;)
  15482. if (destSamples[i] != 0)
  15483. zeromem (destSamples[i] + startOffsetInDestBuffer,
  15484. sizeof (int) * numSamples);
  15485. }
  15486. return true;
  15487. }
  15488. juce_UseDebuggingNewOperator
  15489. private:
  15490. AiffAudioFormatReader (const AiffAudioFormatReader&);
  15491. AiffAudioFormatReader& operator= (const AiffAudioFormatReader&);
  15492. static inline int chunkName (const char* const name) { return (int) ByteOrder::littleEndianInt (name); }
  15493. };
  15494. class AiffAudioFormatWriter : public AudioFormatWriter
  15495. {
  15496. MemoryBlock tempBlock;
  15497. uint32 lengthInSamples, bytesWritten;
  15498. int64 headerPosition;
  15499. bool writeFailed;
  15500. static inline int chunkName (const char* const name) { return (int) ByteOrder::littleEndianInt (name); }
  15501. AiffAudioFormatWriter (const AiffAudioFormatWriter&);
  15502. AiffAudioFormatWriter& operator= (const AiffAudioFormatWriter&);
  15503. void writeHeader()
  15504. {
  15505. const bool couldSeekOk = output->setPosition (headerPosition);
  15506. (void) couldSeekOk;
  15507. // if this fails, you've given it an output stream that can't seek! It needs
  15508. // to be able to seek back to write the header
  15509. jassert (couldSeekOk);
  15510. const int headerLen = 54;
  15511. int audioBytes = lengthInSamples * ((bitsPerSample * numChannels) / 8);
  15512. audioBytes += (audioBytes & 1);
  15513. output->writeInt (chunkName ("FORM"));
  15514. output->writeIntBigEndian (headerLen + audioBytes - 8);
  15515. output->writeInt (chunkName ("AIFF"));
  15516. output->writeInt (chunkName ("COMM"));
  15517. output->writeIntBigEndian (18);
  15518. output->writeShortBigEndian ((short) numChannels);
  15519. output->writeIntBigEndian (lengthInSamples);
  15520. output->writeShortBigEndian ((short) bitsPerSample);
  15521. uint8 sampleRateBytes[10];
  15522. zeromem (sampleRateBytes, 10);
  15523. if (sampleRate <= 1)
  15524. {
  15525. sampleRateBytes[0] = 0x3f;
  15526. sampleRateBytes[1] = 0xff;
  15527. sampleRateBytes[2] = 0x80;
  15528. }
  15529. else
  15530. {
  15531. int mask = 0x40000000;
  15532. sampleRateBytes[0] = 0x40;
  15533. if (sampleRate >= mask)
  15534. {
  15535. jassertfalse
  15536. sampleRateBytes[1] = 0x1d;
  15537. }
  15538. else
  15539. {
  15540. int n = (int) sampleRate;
  15541. int i;
  15542. for (i = 0; i <= 32 ; ++i)
  15543. {
  15544. if ((n & mask) != 0)
  15545. break;
  15546. mask >>= 1;
  15547. }
  15548. n = n << (i + 1);
  15549. sampleRateBytes[1] = (uint8) (29 - i);
  15550. sampleRateBytes[2] = (uint8) ((n >> 24) & 0xff);
  15551. sampleRateBytes[3] = (uint8) ((n >> 16) & 0xff);
  15552. sampleRateBytes[4] = (uint8) ((n >> 8) & 0xff);
  15553. sampleRateBytes[5] = (uint8) (n & 0xff);
  15554. }
  15555. }
  15556. output->write (sampleRateBytes, 10);
  15557. output->writeInt (chunkName ("SSND"));
  15558. output->writeIntBigEndian (audioBytes + 8);
  15559. output->writeInt (0);
  15560. output->writeInt (0);
  15561. jassert (output->getPosition() == headerLen);
  15562. }
  15563. public:
  15564. AiffAudioFormatWriter (OutputStream* out,
  15565. const double sampleRate_,
  15566. const unsigned int chans,
  15567. const int bits)
  15568. : AudioFormatWriter (out,
  15569. TRANS (aiffFormatName),
  15570. sampleRate_,
  15571. chans,
  15572. bits),
  15573. lengthInSamples (0),
  15574. bytesWritten (0),
  15575. writeFailed (false)
  15576. {
  15577. headerPosition = out->getPosition();
  15578. writeHeader();
  15579. }
  15580. ~AiffAudioFormatWriter()
  15581. {
  15582. if ((bytesWritten & 1) != 0)
  15583. output->writeByte (0);
  15584. writeHeader();
  15585. }
  15586. bool write (const int** data, int numSamples)
  15587. {
  15588. if (writeFailed)
  15589. return false;
  15590. const int bytes = numChannels * numSamples * bitsPerSample / 8;
  15591. tempBlock.ensureSize (bytes, false);
  15592. char* buffer = static_cast <char*> (tempBlock.getData());
  15593. const int* left = data[0];
  15594. const int* right = data[1];
  15595. if (right == 0)
  15596. right = left;
  15597. if (bitsPerSample == 16)
  15598. {
  15599. short* b = reinterpret_cast <short*> (buffer);
  15600. if (numChannels > 1)
  15601. {
  15602. for (int i = numSamples; --i >= 0;)
  15603. {
  15604. *b++ = (short) ByteOrder::swapIfLittleEndian ((uint16) (*left++ >> 16));
  15605. *b++ = (short) ByteOrder::swapIfLittleEndian ((uint16) (*right++ >> 16));
  15606. }
  15607. }
  15608. else
  15609. {
  15610. for (int i = numSamples; --i >= 0;)
  15611. {
  15612. *b++ = (short) ByteOrder::swapIfLittleEndian ((uint16) (*left++ >> 16));
  15613. }
  15614. }
  15615. }
  15616. else if (bitsPerSample == 24)
  15617. {
  15618. char* b = buffer;
  15619. if (numChannels > 1)
  15620. {
  15621. for (int i = numSamples; --i >= 0;)
  15622. {
  15623. ByteOrder::bigEndian24BitToChars (*left++ >> 8, b);
  15624. b += 3;
  15625. ByteOrder::bigEndian24BitToChars (*right++ >> 8, b);
  15626. b += 3;
  15627. }
  15628. }
  15629. else
  15630. {
  15631. for (int i = numSamples; --i >= 0;)
  15632. {
  15633. ByteOrder::bigEndian24BitToChars (*left++ >> 8, b);
  15634. b += 3;
  15635. }
  15636. }
  15637. }
  15638. else if (bitsPerSample == 32)
  15639. {
  15640. uint32* b = reinterpret_cast <uint32*> (buffer);
  15641. if (numChannels > 1)
  15642. {
  15643. for (int i = numSamples; --i >= 0;)
  15644. {
  15645. *b++ = ByteOrder::swapIfLittleEndian ((uint32) *left++);
  15646. *b++ = ByteOrder::swapIfLittleEndian ((uint32) *right++);
  15647. }
  15648. }
  15649. else
  15650. {
  15651. for (int i = numSamples; --i >= 0;)
  15652. {
  15653. *b++ = ByteOrder::swapIfLittleEndian ((uint32) *left++);
  15654. }
  15655. }
  15656. }
  15657. else if (bitsPerSample == 8)
  15658. {
  15659. char* b = buffer;
  15660. if (numChannels > 1)
  15661. {
  15662. for (int i = numSamples; --i >= 0;)
  15663. {
  15664. *b++ = (char) (*left++ >> 24);
  15665. *b++ = (char) (*right++ >> 24);
  15666. }
  15667. }
  15668. else
  15669. {
  15670. for (int i = numSamples; --i >= 0;)
  15671. {
  15672. *b++ = (char) (*left++ >> 24);
  15673. }
  15674. }
  15675. }
  15676. if (bytesWritten + bytes >= (uint32) 0xfff00000
  15677. || ! output->write (buffer, bytes))
  15678. {
  15679. // failed to write to disk, so let's try writing the header.
  15680. // If it's just run out of disk space, then if it does manage
  15681. // to write the header, we'll still have a useable file..
  15682. writeHeader();
  15683. writeFailed = true;
  15684. return false;
  15685. }
  15686. else
  15687. {
  15688. bytesWritten += bytes;
  15689. lengthInSamples += numSamples;
  15690. return true;
  15691. }
  15692. }
  15693. juce_UseDebuggingNewOperator
  15694. };
  15695. AiffAudioFormat::AiffAudioFormat()
  15696. : AudioFormat (TRANS (aiffFormatName), (const juce_wchar**) aiffExtensions)
  15697. {
  15698. }
  15699. AiffAudioFormat::~AiffAudioFormat()
  15700. {
  15701. }
  15702. const Array <int> AiffAudioFormat::getPossibleSampleRates()
  15703. {
  15704. const int rates[] = { 22050, 32000, 44100, 48000, 88200, 96000, 176400, 192000, 0 };
  15705. return Array <int> (rates);
  15706. }
  15707. const Array <int> AiffAudioFormat::getPossibleBitDepths()
  15708. {
  15709. const int depths[] = { 8, 16, 24, 0 };
  15710. return Array <int> (depths);
  15711. }
  15712. bool AiffAudioFormat::canDoStereo()
  15713. {
  15714. return true;
  15715. }
  15716. bool AiffAudioFormat::canDoMono()
  15717. {
  15718. return true;
  15719. }
  15720. #if JUCE_MAC
  15721. bool AiffAudioFormat::canHandleFile (const File& f)
  15722. {
  15723. if (AudioFormat::canHandleFile (f))
  15724. return true;
  15725. const OSType type = PlatformUtilities::getTypeOfFile (f.getFullPathName());
  15726. return type == 'AIFF' || type == 'AIFC'
  15727. || type == 'aiff' || type == 'aifc';
  15728. }
  15729. #endif
  15730. AudioFormatReader* AiffAudioFormat::createReaderFor (InputStream* sourceStream,
  15731. const bool deleteStreamIfOpeningFails)
  15732. {
  15733. ScopedPointer <AiffAudioFormatReader> w (new AiffAudioFormatReader (sourceStream));
  15734. if (w->sampleRate != 0)
  15735. return w.release();
  15736. if (! deleteStreamIfOpeningFails)
  15737. w->input = 0;
  15738. return 0;
  15739. }
  15740. AudioFormatWriter* AiffAudioFormat::createWriterFor (OutputStream* out,
  15741. double sampleRate,
  15742. unsigned int chans,
  15743. int bitsPerSample,
  15744. const StringPairArray& /*metadataValues*/,
  15745. int /*qualityOptionIndex*/)
  15746. {
  15747. if (getPossibleBitDepths().contains (bitsPerSample))
  15748. {
  15749. return new AiffAudioFormatWriter (out,
  15750. sampleRate,
  15751. chans,
  15752. bitsPerSample);
  15753. }
  15754. return 0;
  15755. }
  15756. END_JUCE_NAMESPACE
  15757. /*** End of inlined file: juce_AiffAudioFormat.cpp ***/
  15758. /*** Start of inlined file: juce_AudioCDReader.cpp ***/
  15759. BEGIN_JUCE_NAMESPACE
  15760. #if JUCE_MAC && JUCE_USE_CDREADER
  15761. // Mac version doesn't need any native code because it's all done with files..
  15762. // Windows + Linux versions are in the platform-dependent code sections.
  15763. static void findCDs (Array<File>& cds)
  15764. {
  15765. File volumes ("/Volumes");
  15766. volumes.findChildFiles (cds, File::findDirectories, false);
  15767. for (int i = cds.size(); --i >= 0;)
  15768. if (! cds.getReference(i).getChildFile (".TOC.plist").exists())
  15769. cds.remove (i);
  15770. }
  15771. const StringArray AudioCDReader::getAvailableCDNames()
  15772. {
  15773. Array<File> cds;
  15774. findCDs (cds);
  15775. StringArray names;
  15776. for (int i = 0; i < cds.size(); ++i)
  15777. names.add (cds.getReference(i).getFileName());
  15778. return names;
  15779. }
  15780. AudioCDReader* AudioCDReader::createReaderForCD (const int index)
  15781. {
  15782. Array<File> cds;
  15783. findCDs (cds);
  15784. if (cds[index] != File::nonexistent)
  15785. return new AudioCDReader (cds[index]);
  15786. else
  15787. return 0;
  15788. }
  15789. AudioCDReader::AudioCDReader (const File& volume)
  15790. : AudioFormatReader (0, "CD Audio"),
  15791. volumeDir (volume),
  15792. currentReaderTrack (-1),
  15793. reader (0)
  15794. {
  15795. sampleRate = 44100.0;
  15796. bitsPerSample = 16;
  15797. numChannels = 2;
  15798. usesFloatingPointData = false;
  15799. refreshTrackLengths();
  15800. }
  15801. AudioCDReader::~AudioCDReader()
  15802. {
  15803. }
  15804. static int getTrackNumber (const File& file)
  15805. {
  15806. return file.getFileName()
  15807. .initialSectionContainingOnly ("0123456789")
  15808. .getIntValue();
  15809. }
  15810. int AudioCDReader::compareElements (const File& first, const File& second)
  15811. {
  15812. const int firstTrack = getTrackNumber (first);
  15813. const int secondTrack = getTrackNumber (second);
  15814. jassert (firstTrack > 0 && secondTrack > 0);
  15815. return firstTrack - secondTrack;
  15816. }
  15817. void AudioCDReader::refreshTrackLengths()
  15818. {
  15819. tracks.clear();
  15820. trackStartSamples.clear();
  15821. volumeDir.findChildFiles (tracks, File::findFiles | File::ignoreHiddenFiles, false, "*.aiff");
  15822. tracks.sort (*this);
  15823. AiffAudioFormat format;
  15824. int sample = 0;
  15825. for (int i = 0; i < tracks.size(); ++i)
  15826. {
  15827. trackStartSamples.add (sample);
  15828. FileInputStream* const in = tracks.getReference(i).createInputStream();
  15829. if (in != 0)
  15830. {
  15831. ScopedPointer <AudioFormatReader> r (format.createReaderFor (in, true));
  15832. if (r != 0)
  15833. sample += (int) r->lengthInSamples;
  15834. }
  15835. }
  15836. trackStartSamples.add (sample);
  15837. lengthInSamples = sample;
  15838. }
  15839. bool AudioCDReader::readSamples (int** destSamples, int numDestChannels, int startOffsetInDestBuffer,
  15840. int64 startSampleInFile, int numSamples)
  15841. {
  15842. while (numSamples > 0)
  15843. {
  15844. int track = -1;
  15845. for (int i = 0; i < trackStartSamples.size() - 1; ++i)
  15846. {
  15847. if (startSampleInFile < trackStartSamples.getUnchecked (i + 1))
  15848. {
  15849. track = i;
  15850. break;
  15851. }
  15852. }
  15853. if (track < 0)
  15854. return false;
  15855. if (track != currentReaderTrack)
  15856. {
  15857. reader = 0;
  15858. FileInputStream* const in = tracks [track].createInputStream();
  15859. if (in != 0)
  15860. {
  15861. BufferedInputStream* const bin = new BufferedInputStream (in, 65536, true);
  15862. AiffAudioFormat format;
  15863. reader = format.createReaderFor (bin, true);
  15864. if (reader == 0)
  15865. currentReaderTrack = -1;
  15866. else
  15867. currentReaderTrack = track;
  15868. }
  15869. }
  15870. if (reader == 0)
  15871. return false;
  15872. const int startPos = (int) (startSampleInFile - trackStartSamples.getUnchecked (track));
  15873. const int numAvailable = (int) jmin ((int64) numSamples, reader->lengthInSamples - startPos);
  15874. reader->readSamples (destSamples, numDestChannels, startOffsetInDestBuffer, startPos, numAvailable);
  15875. numSamples -= numAvailable;
  15876. startSampleInFile += numAvailable;
  15877. }
  15878. return true;
  15879. }
  15880. bool AudioCDReader::isCDStillPresent() const
  15881. {
  15882. return volumeDir.exists();
  15883. }
  15884. int AudioCDReader::getNumTracks() const
  15885. {
  15886. return tracks.size();
  15887. }
  15888. int AudioCDReader::getPositionOfTrackStart (int trackNum) const
  15889. {
  15890. return trackStartSamples [trackNum];
  15891. }
  15892. bool AudioCDReader::isTrackAudio (int trackNum) const
  15893. {
  15894. return tracks [trackNum] != File::nonexistent;
  15895. }
  15896. void AudioCDReader::enableIndexScanning (bool b)
  15897. {
  15898. // any way to do this on a Mac??
  15899. }
  15900. int AudioCDReader::getLastIndex() const
  15901. {
  15902. return 0;
  15903. }
  15904. const Array <int> AudioCDReader::findIndexesInTrack (const int trackNumber)
  15905. {
  15906. return Array <int>();
  15907. }
  15908. int AudioCDReader::getCDDBId()
  15909. {
  15910. return 0; //xxx
  15911. }
  15912. #endif
  15913. END_JUCE_NAMESPACE
  15914. /*** End of inlined file: juce_AudioCDReader.cpp ***/
  15915. /*** Start of inlined file: juce_AudioFormat.cpp ***/
  15916. BEGIN_JUCE_NAMESPACE
  15917. AudioFormatReader::AudioFormatReader (InputStream* const in,
  15918. const String& formatName_)
  15919. : sampleRate (0),
  15920. bitsPerSample (0),
  15921. lengthInSamples (0),
  15922. numChannels (0),
  15923. usesFloatingPointData (false),
  15924. input (in),
  15925. formatName (formatName_)
  15926. {
  15927. }
  15928. AudioFormatReader::~AudioFormatReader()
  15929. {
  15930. delete input;
  15931. }
  15932. bool AudioFormatReader::read (int** destSamples,
  15933. int numDestChannels,
  15934. int64 startSampleInSource,
  15935. int numSamplesToRead,
  15936. const bool fillLeftoverChannelsWithCopies)
  15937. {
  15938. jassert (numDestChannels > 0); // you have to actually give this some channels to work with!
  15939. int startOffsetInDestBuffer = 0;
  15940. if (startSampleInSource < 0)
  15941. {
  15942. const int silence = (int) jmin (-startSampleInSource, (int64) numSamplesToRead);
  15943. for (int i = numDestChannels; --i >= 0;)
  15944. if (destSamples[i] != 0)
  15945. zeromem (destSamples[i], sizeof (int) * silence);
  15946. startOffsetInDestBuffer += silence;
  15947. numSamplesToRead -= silence;
  15948. startSampleInSource = 0;
  15949. }
  15950. if (numSamplesToRead <= 0)
  15951. return true;
  15952. if (! readSamples (destSamples, jmin ((int) numChannels, numDestChannels), startOffsetInDestBuffer,
  15953. startSampleInSource, numSamplesToRead))
  15954. return false;
  15955. if (numDestChannels > (int) numChannels)
  15956. {
  15957. if (fillLeftoverChannelsWithCopies)
  15958. {
  15959. int* lastFullChannel = destSamples[0];
  15960. for (int i = numDestChannels; --i > 0;)
  15961. {
  15962. if (destSamples[i] != 0)
  15963. {
  15964. lastFullChannel = destSamples[i];
  15965. break;
  15966. }
  15967. }
  15968. if (lastFullChannel != 0)
  15969. for (int i = numChannels; i < numDestChannels; ++i)
  15970. if (destSamples[i] != 0)
  15971. memcpy (destSamples[i], lastFullChannel, sizeof (int) * numSamplesToRead);
  15972. }
  15973. else
  15974. {
  15975. for (int i = numChannels; i < numDestChannels; ++i)
  15976. if (destSamples[i] != 0)
  15977. zeromem (destSamples[i], sizeof (int) * numSamplesToRead);
  15978. }
  15979. }
  15980. return true;
  15981. }
  15982. static void findAudioBufferMaxMin (const float* const buffer, const int num, float& maxVal, float& minVal) throw()
  15983. {
  15984. float mn = buffer[0];
  15985. float mx = mn;
  15986. for (int i = 1; i < num; ++i)
  15987. {
  15988. const float s = buffer[i];
  15989. if (s > mx) mx = s;
  15990. if (s < mn) mn = s;
  15991. }
  15992. maxVal = mx;
  15993. minVal = mn;
  15994. }
  15995. void AudioFormatReader::readMaxLevels (int64 startSampleInFile,
  15996. int64 numSamples,
  15997. float& lowestLeft, float& highestLeft,
  15998. float& lowestRight, float& highestRight)
  15999. {
  16000. if (numSamples <= 0)
  16001. {
  16002. lowestLeft = 0;
  16003. lowestRight = 0;
  16004. highestLeft = 0;
  16005. highestRight = 0;
  16006. return;
  16007. }
  16008. const int bufferSize = (int) jmin (numSamples, (int64) 4096);
  16009. MemoryBlock tempSpace (bufferSize * sizeof (int) * 2 + 64);
  16010. int* tempBuffer[3];
  16011. tempBuffer[0] = (int*) tempSpace.getData();
  16012. tempBuffer[1] = ((int*) tempSpace.getData()) + bufferSize;
  16013. tempBuffer[2] = 0;
  16014. if (usesFloatingPointData)
  16015. {
  16016. float lmin = 1.0e6f;
  16017. float lmax = -lmin;
  16018. float rmin = lmin;
  16019. float rmax = lmax;
  16020. while (numSamples > 0)
  16021. {
  16022. const int numToDo = (int) jmin (numSamples, (int64) bufferSize);
  16023. read ((int**) tempBuffer, 2, startSampleInFile, numToDo, false);
  16024. numSamples -= numToDo;
  16025. startSampleInFile += numToDo;
  16026. float bufmin, bufmax;
  16027. findAudioBufferMaxMin ((float*) tempBuffer[0], numToDo, bufmax, bufmin);
  16028. lmin = jmin (lmin, bufmin);
  16029. lmax = jmax (lmax, bufmax);
  16030. if (numChannels > 1)
  16031. {
  16032. findAudioBufferMaxMin ((float*) tempBuffer[1], numToDo, bufmax, bufmin);
  16033. rmin = jmin (rmin, bufmin);
  16034. rmax = jmax (rmax, bufmax);
  16035. }
  16036. }
  16037. if (numChannels <= 1)
  16038. {
  16039. rmax = lmax;
  16040. rmin = lmin;
  16041. }
  16042. lowestLeft = lmin;
  16043. highestLeft = lmax;
  16044. lowestRight = rmin;
  16045. highestRight = rmax;
  16046. }
  16047. else
  16048. {
  16049. int lmax = std::numeric_limits<int>::min();
  16050. int lmin = std::numeric_limits<int>::max();
  16051. int rmax = std::numeric_limits<int>::min();
  16052. int rmin = std::numeric_limits<int>::max();
  16053. while (numSamples > 0)
  16054. {
  16055. const int numToDo = (int) jmin (numSamples, (int64) bufferSize);
  16056. read ((int**) tempBuffer, 2, startSampleInFile, numToDo, false);
  16057. numSamples -= numToDo;
  16058. startSampleInFile += numToDo;
  16059. for (int j = numChannels; --j >= 0;)
  16060. {
  16061. int bufMax = std::numeric_limits<int>::min();
  16062. int bufMin = std::numeric_limits<int>::max();
  16063. const int* const b = tempBuffer[j];
  16064. for (int i = 0; i < numToDo; ++i)
  16065. {
  16066. const int samp = b[i];
  16067. if (samp < bufMin)
  16068. bufMin = samp;
  16069. if (samp > bufMax)
  16070. bufMax = samp;
  16071. }
  16072. if (j == 0)
  16073. {
  16074. lmax = jmax (lmax, bufMax);
  16075. lmin = jmin (lmin, bufMin);
  16076. }
  16077. else
  16078. {
  16079. rmax = jmax (rmax, bufMax);
  16080. rmin = jmin (rmin, bufMin);
  16081. }
  16082. }
  16083. }
  16084. if (numChannels <= 1)
  16085. {
  16086. rmax = lmax;
  16087. rmin = lmin;
  16088. }
  16089. lowestLeft = lmin / (float) std::numeric_limits<int>::max();
  16090. highestLeft = lmax / (float) std::numeric_limits<int>::max();
  16091. lowestRight = rmin / (float) std::numeric_limits<int>::max();
  16092. highestRight = rmax / (float) std::numeric_limits<int>::max();
  16093. }
  16094. }
  16095. int64 AudioFormatReader::searchForLevel (int64 startSample,
  16096. int64 numSamplesToSearch,
  16097. const double magnitudeRangeMinimum,
  16098. const double magnitudeRangeMaximum,
  16099. const int minimumConsecutiveSamples)
  16100. {
  16101. if (numSamplesToSearch == 0)
  16102. return -1;
  16103. const int bufferSize = 4096;
  16104. MemoryBlock tempSpace (bufferSize * sizeof (int) * 2 + 64);
  16105. int* tempBuffer[3];
  16106. tempBuffer[0] = (int*) tempSpace.getData();
  16107. tempBuffer[1] = ((int*) tempSpace.getData()) + bufferSize;
  16108. tempBuffer[2] = 0;
  16109. int consecutive = 0;
  16110. int64 firstMatchPos = -1;
  16111. jassert (magnitudeRangeMaximum > magnitudeRangeMinimum);
  16112. const double doubleMin = jlimit (0.0, (double) std::numeric_limits<int>::max(), magnitudeRangeMinimum * std::numeric_limits<int>::max());
  16113. const double doubleMax = jlimit (doubleMin, (double) std::numeric_limits<int>::max(), magnitudeRangeMaximum * std::numeric_limits<int>::max());
  16114. const int intMagnitudeRangeMinimum = roundToInt (doubleMin);
  16115. const int intMagnitudeRangeMaximum = roundToInt (doubleMax);
  16116. while (numSamplesToSearch != 0)
  16117. {
  16118. const int numThisTime = (int) jmin (abs64 (numSamplesToSearch), (int64) bufferSize);
  16119. int64 bufferStart = startSample;
  16120. if (numSamplesToSearch < 0)
  16121. bufferStart -= numThisTime;
  16122. if (bufferStart >= (int) lengthInSamples)
  16123. break;
  16124. read ((int**) tempBuffer, 2, bufferStart, numThisTime, false);
  16125. int num = numThisTime;
  16126. while (--num >= 0)
  16127. {
  16128. if (numSamplesToSearch < 0)
  16129. --startSample;
  16130. bool matches = false;
  16131. const int index = (int) (startSample - bufferStart);
  16132. if (usesFloatingPointData)
  16133. {
  16134. const float sample1 = fabsf (((float*) tempBuffer[0]) [index]);
  16135. if (sample1 >= magnitudeRangeMinimum
  16136. && sample1 <= magnitudeRangeMaximum)
  16137. {
  16138. matches = true;
  16139. }
  16140. else if (numChannels > 1)
  16141. {
  16142. const float sample2 = fabsf (((float*) tempBuffer[1]) [index]);
  16143. matches = (sample2 >= magnitudeRangeMinimum
  16144. && sample2 <= magnitudeRangeMaximum);
  16145. }
  16146. }
  16147. else
  16148. {
  16149. const int sample1 = abs (tempBuffer[0] [index]);
  16150. if (sample1 >= intMagnitudeRangeMinimum
  16151. && sample1 <= intMagnitudeRangeMaximum)
  16152. {
  16153. matches = true;
  16154. }
  16155. else if (numChannels > 1)
  16156. {
  16157. const int sample2 = abs (tempBuffer[1][index]);
  16158. matches = (sample2 >= intMagnitudeRangeMinimum
  16159. && sample2 <= intMagnitudeRangeMaximum);
  16160. }
  16161. }
  16162. if (matches)
  16163. {
  16164. if (firstMatchPos < 0)
  16165. firstMatchPos = startSample;
  16166. if (++consecutive >= minimumConsecutiveSamples)
  16167. {
  16168. if (firstMatchPos < 0 || firstMatchPos >= lengthInSamples)
  16169. return -1;
  16170. return firstMatchPos;
  16171. }
  16172. }
  16173. else
  16174. {
  16175. consecutive = 0;
  16176. firstMatchPos = -1;
  16177. }
  16178. if (numSamplesToSearch > 0)
  16179. ++startSample;
  16180. }
  16181. if (numSamplesToSearch > 0)
  16182. numSamplesToSearch -= numThisTime;
  16183. else
  16184. numSamplesToSearch += numThisTime;
  16185. }
  16186. return -1;
  16187. }
  16188. AudioFormatWriter::AudioFormatWriter (OutputStream* const out,
  16189. const String& formatName_,
  16190. const double rate,
  16191. const unsigned int numChannels_,
  16192. const unsigned int bitsPerSample_)
  16193. : sampleRate (rate),
  16194. numChannels (numChannels_),
  16195. bitsPerSample (bitsPerSample_),
  16196. usesFloatingPointData (false),
  16197. output (out),
  16198. formatName (formatName_)
  16199. {
  16200. }
  16201. AudioFormatWriter::~AudioFormatWriter()
  16202. {
  16203. delete output;
  16204. }
  16205. bool AudioFormatWriter::writeFromAudioReader (AudioFormatReader& reader,
  16206. int64 startSample,
  16207. int64 numSamplesToRead)
  16208. {
  16209. const int bufferSize = 16384;
  16210. const int maxChans = 128;
  16211. AudioSampleBuffer tempBuffer (reader.numChannels, bufferSize);
  16212. int* buffers [maxChans];
  16213. for (int i = maxChans; --i >= 0;)
  16214. buffers[i] = 0;
  16215. if (numSamplesToRead < 0)
  16216. numSamplesToRead = reader.lengthInSamples;
  16217. while (numSamplesToRead > 0)
  16218. {
  16219. const int numToDo = (int) jmin (numSamplesToRead, (int64) bufferSize);
  16220. for (int i = tempBuffer.getNumChannels(); --i >= 0;)
  16221. buffers[i] = (int*) tempBuffer.getSampleData (i, 0);
  16222. if (! reader.read (buffers, maxChans, startSample, numToDo, false))
  16223. return false;
  16224. if (reader.usesFloatingPointData != isFloatingPoint())
  16225. {
  16226. int** bufferChan = buffers;
  16227. while (*bufferChan != 0)
  16228. {
  16229. int* b = *bufferChan++;
  16230. if (isFloatingPoint())
  16231. {
  16232. // int -> float
  16233. const double factor = 1.0 / std::numeric_limits<int>::max();
  16234. for (int i = 0; i < numToDo; ++i)
  16235. ((float*) b)[i] = (float) (factor * b[i]);
  16236. }
  16237. else
  16238. {
  16239. // float -> int
  16240. for (int i = 0; i < numToDo; ++i)
  16241. {
  16242. const double samp = *(const float*) b;
  16243. if (samp <= -1.0)
  16244. *b++ = std::numeric_limits<int>::min();
  16245. else if (samp >= 1.0)
  16246. *b++ = std::numeric_limits<int>::max();
  16247. else
  16248. *b++ = roundToInt (std::numeric_limits<int>::max() * samp);
  16249. }
  16250. }
  16251. }
  16252. }
  16253. if (! write ((const int**) buffers, numToDo))
  16254. return false;
  16255. numSamplesToRead -= numToDo;
  16256. startSample += numToDo;
  16257. }
  16258. return true;
  16259. }
  16260. bool AudioFormatWriter::writeFromAudioSource (AudioSource& source,
  16261. int numSamplesToRead,
  16262. const int samplesPerBlock)
  16263. {
  16264. const int maxChans = 128;
  16265. AudioSampleBuffer tempBuffer (getNumChannels(), samplesPerBlock);
  16266. int* buffers [maxChans];
  16267. while (numSamplesToRead > 0)
  16268. {
  16269. const int numToDo = jmin (numSamplesToRead, samplesPerBlock);
  16270. AudioSourceChannelInfo info;
  16271. info.buffer = &tempBuffer;
  16272. info.startSample = 0;
  16273. info.numSamples = numToDo;
  16274. info.clearActiveBufferRegion();
  16275. source.getNextAudioBlock (info);
  16276. int i;
  16277. for (i = maxChans; --i >= 0;)
  16278. buffers[i] = 0;
  16279. for (i = tempBuffer.getNumChannels(); --i >= 0;)
  16280. buffers[i] = (int*) tempBuffer.getSampleData (i, 0);
  16281. if (! isFloatingPoint())
  16282. {
  16283. int** bufferChan = buffers;
  16284. while (*bufferChan != 0)
  16285. {
  16286. int* b = *bufferChan++;
  16287. // float -> int
  16288. for (int j = numToDo; --j >= 0;)
  16289. {
  16290. const double samp = *(const float*) b;
  16291. if (samp <= -1.0)
  16292. *b++ = std::numeric_limits<int>::min();
  16293. else if (samp >= 1.0)
  16294. *b++ = std::numeric_limits<int>::max();
  16295. else
  16296. *b++ = roundToInt (std::numeric_limits<int>::max() * samp);
  16297. }
  16298. }
  16299. }
  16300. if (! write ((const int**) buffers, numToDo))
  16301. return false;
  16302. numSamplesToRead -= numToDo;
  16303. }
  16304. return true;
  16305. }
  16306. AudioFormat::AudioFormat (const String& name,
  16307. const juce_wchar** const extensions)
  16308. : formatName (name),
  16309. fileExtensions (extensions)
  16310. {
  16311. }
  16312. AudioFormat::~AudioFormat()
  16313. {
  16314. }
  16315. const String& AudioFormat::getFormatName() const
  16316. {
  16317. return formatName;
  16318. }
  16319. const StringArray& AudioFormat::getFileExtensions() const
  16320. {
  16321. return fileExtensions;
  16322. }
  16323. bool AudioFormat::canHandleFile (const File& f)
  16324. {
  16325. for (int i = 0; i < fileExtensions.size(); ++i)
  16326. if (f.hasFileExtension (fileExtensions[i]))
  16327. return true;
  16328. return false;
  16329. }
  16330. bool AudioFormat::isCompressed()
  16331. {
  16332. return false;
  16333. }
  16334. const StringArray AudioFormat::getQualityOptions()
  16335. {
  16336. return StringArray();
  16337. }
  16338. END_JUCE_NAMESPACE
  16339. /*** End of inlined file: juce_AudioFormat.cpp ***/
  16340. /*** Start of inlined file: juce_AudioFormatManager.cpp ***/
  16341. BEGIN_JUCE_NAMESPACE
  16342. AudioFormatManager::AudioFormatManager()
  16343. : defaultFormatIndex (0)
  16344. {
  16345. }
  16346. AudioFormatManager::~AudioFormatManager()
  16347. {
  16348. clearFormats();
  16349. clearSingletonInstance();
  16350. }
  16351. juce_ImplementSingleton (AudioFormatManager);
  16352. void AudioFormatManager::registerFormat (AudioFormat* newFormat,
  16353. const bool makeThisTheDefaultFormat)
  16354. {
  16355. jassert (newFormat != 0);
  16356. if (newFormat != 0)
  16357. {
  16358. #if JUCE_DEBUG
  16359. for (int i = getNumKnownFormats(); --i >= 0;)
  16360. {
  16361. if (getKnownFormat (i)->getFormatName() == newFormat->getFormatName())
  16362. {
  16363. jassertfalse // trying to add the same format twice!
  16364. }
  16365. }
  16366. #endif
  16367. if (makeThisTheDefaultFormat)
  16368. defaultFormatIndex = getNumKnownFormats();
  16369. knownFormats.add (newFormat);
  16370. }
  16371. }
  16372. void AudioFormatManager::registerBasicFormats()
  16373. {
  16374. #if JUCE_MAC
  16375. registerFormat (new AiffAudioFormat(), true);
  16376. registerFormat (new WavAudioFormat(), false);
  16377. #else
  16378. registerFormat (new WavAudioFormat(), true);
  16379. registerFormat (new AiffAudioFormat(), false);
  16380. #endif
  16381. #if JUCE_USE_FLAC
  16382. registerFormat (new FlacAudioFormat(), false);
  16383. #endif
  16384. #if JUCE_USE_OGGVORBIS
  16385. registerFormat (new OggVorbisAudioFormat(), false);
  16386. #endif
  16387. }
  16388. void AudioFormatManager::clearFormats()
  16389. {
  16390. knownFormats.clear();
  16391. defaultFormatIndex = 0;
  16392. }
  16393. int AudioFormatManager::getNumKnownFormats() const
  16394. {
  16395. return knownFormats.size();
  16396. }
  16397. AudioFormat* AudioFormatManager::getKnownFormat (const int index) const
  16398. {
  16399. return knownFormats [index];
  16400. }
  16401. AudioFormat* AudioFormatManager::getDefaultFormat() const
  16402. {
  16403. return getKnownFormat (defaultFormatIndex);
  16404. }
  16405. AudioFormat* AudioFormatManager::findFormatForFileExtension (const String& fileExtension) const
  16406. {
  16407. String e (fileExtension);
  16408. if (! e.startsWithChar ('.'))
  16409. e = "." + e;
  16410. for (int i = 0; i < getNumKnownFormats(); ++i)
  16411. if (getKnownFormat(i)->getFileExtensions().contains (e, true))
  16412. return getKnownFormat(i);
  16413. return 0;
  16414. }
  16415. const String AudioFormatManager::getWildcardForAllFormats() const
  16416. {
  16417. StringArray allExtensions;
  16418. int i;
  16419. for (i = 0; i < getNumKnownFormats(); ++i)
  16420. allExtensions.addArray (getKnownFormat (i)->getFileExtensions());
  16421. allExtensions.trim();
  16422. allExtensions.removeEmptyStrings();
  16423. String s;
  16424. for (i = 0; i < allExtensions.size(); ++i)
  16425. {
  16426. s << '*';
  16427. if (! allExtensions[i].startsWithChar ('.'))
  16428. s << '.';
  16429. s << allExtensions[i];
  16430. if (i < allExtensions.size() - 1)
  16431. s << ';';
  16432. }
  16433. return s;
  16434. }
  16435. AudioFormatReader* AudioFormatManager::createReaderFor (const File& file)
  16436. {
  16437. // you need to actually register some formats before the manager can
  16438. // use them to open a file!
  16439. jassert (getNumKnownFormats() > 0);
  16440. for (int i = 0; i < getNumKnownFormats(); ++i)
  16441. {
  16442. AudioFormat* const af = getKnownFormat(i);
  16443. if (af->canHandleFile (file))
  16444. {
  16445. InputStream* const in = file.createInputStream();
  16446. if (in != 0)
  16447. {
  16448. AudioFormatReader* const r = af->createReaderFor (in, true);
  16449. if (r != 0)
  16450. return r;
  16451. }
  16452. }
  16453. }
  16454. return 0;
  16455. }
  16456. AudioFormatReader* AudioFormatManager::createReaderFor (InputStream* audioFileStream)
  16457. {
  16458. // you need to actually register some formats before the manager can
  16459. // use them to open a file!
  16460. jassert (getNumKnownFormats() > 0);
  16461. ScopedPointer <InputStream> in (audioFileStream);
  16462. if (in != 0)
  16463. {
  16464. const int64 originalStreamPos = in->getPosition();
  16465. for (int i = 0; i < getNumKnownFormats(); ++i)
  16466. {
  16467. AudioFormatReader* const r = getKnownFormat(i)->createReaderFor (in, false);
  16468. if (r != 0)
  16469. {
  16470. in.release();
  16471. return r;
  16472. }
  16473. in->setPosition (originalStreamPos);
  16474. // the stream that is passed-in must be capable of being repositioned so
  16475. // that all the formats can have a go at opening it.
  16476. jassert (in->getPosition() == originalStreamPos);
  16477. }
  16478. }
  16479. return 0;
  16480. }
  16481. END_JUCE_NAMESPACE
  16482. /*** End of inlined file: juce_AudioFormatManager.cpp ***/
  16483. /*** Start of inlined file: juce_AudioSubsectionReader.cpp ***/
  16484. BEGIN_JUCE_NAMESPACE
  16485. AudioSubsectionReader::AudioSubsectionReader (AudioFormatReader* const source_,
  16486. const int64 startSample_,
  16487. const int64 length_,
  16488. const bool deleteSourceWhenDeleted_)
  16489. : AudioFormatReader (0, source_->getFormatName()),
  16490. source (source_),
  16491. startSample (startSample_),
  16492. deleteSourceWhenDeleted (deleteSourceWhenDeleted_)
  16493. {
  16494. length = jmin (jmax ((int64) 0, source->lengthInSamples - startSample), length_);
  16495. sampleRate = source->sampleRate;
  16496. bitsPerSample = source->bitsPerSample;
  16497. lengthInSamples = length;
  16498. numChannels = source->numChannels;
  16499. usesFloatingPointData = source->usesFloatingPointData;
  16500. }
  16501. AudioSubsectionReader::~AudioSubsectionReader()
  16502. {
  16503. if (deleteSourceWhenDeleted)
  16504. delete source;
  16505. }
  16506. bool AudioSubsectionReader::readSamples (int** destSamples, int numDestChannels, int startOffsetInDestBuffer,
  16507. int64 startSampleInFile, int numSamples)
  16508. {
  16509. if (startSampleInFile + numSamples > length)
  16510. {
  16511. for (int i = numDestChannels; --i >= 0;)
  16512. if (destSamples[i] != 0)
  16513. zeromem (destSamples[i], sizeof (int) * numSamples);
  16514. numSamples = jmin (numSamples, (int) (length - startSampleInFile));
  16515. if (numSamples <= 0)
  16516. return true;
  16517. }
  16518. return source->readSamples (destSamples, numDestChannels, startOffsetInDestBuffer,
  16519. startSampleInFile + startSample, numSamples);
  16520. }
  16521. void AudioSubsectionReader::readMaxLevels (int64 startSampleInFile,
  16522. int64 numSamples,
  16523. float& lowestLeft,
  16524. float& highestLeft,
  16525. float& lowestRight,
  16526. float& highestRight)
  16527. {
  16528. startSampleInFile = jmax ((int64) 0, startSampleInFile);
  16529. numSamples = jmax ((int64) 0, jmin (numSamples, length - startSampleInFile));
  16530. source->readMaxLevels (startSampleInFile + startSample,
  16531. numSamples,
  16532. lowestLeft,
  16533. highestLeft,
  16534. lowestRight,
  16535. highestRight);
  16536. }
  16537. END_JUCE_NAMESPACE
  16538. /*** End of inlined file: juce_AudioSubsectionReader.cpp ***/
  16539. /*** Start of inlined file: juce_AudioThumbnail.cpp ***/
  16540. BEGIN_JUCE_NAMESPACE
  16541. const int timeBeforeDeletingReader = 2000;
  16542. struct AudioThumbnailDataFormat
  16543. {
  16544. char thumbnailMagic[4];
  16545. int samplesPerThumbSample;
  16546. int64 totalSamples; // source samples
  16547. int64 numFinishedSamples; // source samples
  16548. int numThumbnailSamples;
  16549. int numChannels;
  16550. int sampleRate;
  16551. char future[16];
  16552. char data[1];
  16553. void swapEndiannessIfNeeded() throw()
  16554. {
  16555. #if JUCE_BIG_ENDIAN
  16556. flip (samplesPerThumbSample);
  16557. flip (totalSamples);
  16558. flip (numFinishedSamples);
  16559. flip (numThumbnailSamples);
  16560. flip (numChannels);
  16561. flip (sampleRate);
  16562. #endif
  16563. }
  16564. private:
  16565. #if JUCE_BIG_ENDIAN
  16566. static void flip (int& n) { n = (int) ByteOrder::swap ((uint32) n); }
  16567. static void flip (int64& n) { n = (int64) ByteOrder::swap ((uint64) n); }
  16568. #endif
  16569. };
  16570. AudioThumbnail::AudioThumbnail (const int orginalSamplesPerThumbnailSample_,
  16571. AudioFormatManager& formatManagerToUse_,
  16572. AudioThumbnailCache& cacheToUse)
  16573. : formatManagerToUse (formatManagerToUse_),
  16574. cache (cacheToUse),
  16575. orginalSamplesPerThumbnailSample (orginalSamplesPerThumbnailSample_)
  16576. {
  16577. clear();
  16578. }
  16579. AudioThumbnail::~AudioThumbnail()
  16580. {
  16581. cache.removeThumbnail (this);
  16582. const ScopedLock sl (readerLock);
  16583. reader = 0;
  16584. }
  16585. void AudioThumbnail::setSource (InputSource* const newSource)
  16586. {
  16587. cache.removeThumbnail (this);
  16588. timerCallback(); // stops the timer and deletes the reader
  16589. source = newSource;
  16590. clear();
  16591. if (newSource != 0
  16592. && ! (cache.loadThumb (*this, newSource->hashCode())
  16593. && isFullyLoaded()))
  16594. {
  16595. {
  16596. const ScopedLock sl (readerLock);
  16597. reader = createReader();
  16598. }
  16599. if (reader != 0)
  16600. {
  16601. initialiseFromAudioFile (*reader);
  16602. cache.addThumbnail (this);
  16603. }
  16604. }
  16605. sendChangeMessage (this);
  16606. }
  16607. bool AudioThumbnail::useTimeSlice()
  16608. {
  16609. const ScopedLock sl (readerLock);
  16610. if (isFullyLoaded())
  16611. {
  16612. if (reader != 0)
  16613. startTimer (timeBeforeDeletingReader);
  16614. cache.removeThumbnail (this);
  16615. return false;
  16616. }
  16617. if (reader == 0)
  16618. reader = createReader();
  16619. if (reader != 0)
  16620. {
  16621. readNextBlockFromAudioFile (*reader);
  16622. stopTimer();
  16623. sendChangeMessage (this);
  16624. const bool justFinished = isFullyLoaded();
  16625. if (justFinished)
  16626. cache.storeThumb (*this, source->hashCode());
  16627. return ! justFinished;
  16628. }
  16629. return false;
  16630. }
  16631. AudioFormatReader* AudioThumbnail::createReader() const
  16632. {
  16633. if (source != 0)
  16634. {
  16635. InputStream* const audioFileStream = source->createInputStream();
  16636. if (audioFileStream != 0)
  16637. return formatManagerToUse.createReaderFor (audioFileStream);
  16638. }
  16639. return 0;
  16640. }
  16641. void AudioThumbnail::timerCallback()
  16642. {
  16643. stopTimer();
  16644. const ScopedLock sl (readerLock);
  16645. reader = 0;
  16646. }
  16647. void AudioThumbnail::clear()
  16648. {
  16649. data.setSize (sizeof (AudioThumbnailDataFormat) + 3);
  16650. AudioThumbnailDataFormat* const d = (AudioThumbnailDataFormat*) data.getData();
  16651. d->thumbnailMagic[0] = 'j';
  16652. d->thumbnailMagic[1] = 'a';
  16653. d->thumbnailMagic[2] = 't';
  16654. d->thumbnailMagic[3] = 'm';
  16655. d->samplesPerThumbSample = orginalSamplesPerThumbnailSample;
  16656. d->totalSamples = 0;
  16657. d->numFinishedSamples = 0;
  16658. d->numThumbnailSamples = 0;
  16659. d->numChannels = 0;
  16660. d->sampleRate = 0;
  16661. numSamplesCached = 0;
  16662. cacheNeedsRefilling = true;
  16663. }
  16664. void AudioThumbnail::loadFrom (InputStream& input)
  16665. {
  16666. const ScopedLock sl (readerLock);
  16667. data.setSize (0);
  16668. input.readIntoMemoryBlock (data);
  16669. AudioThumbnailDataFormat* const d = (AudioThumbnailDataFormat*) data.getData();
  16670. d->swapEndiannessIfNeeded();
  16671. if (! (d->thumbnailMagic[0] == 'j'
  16672. && d->thumbnailMagic[1] == 'a'
  16673. && d->thumbnailMagic[2] == 't'
  16674. && d->thumbnailMagic[3] == 'm'))
  16675. {
  16676. clear();
  16677. }
  16678. numSamplesCached = 0;
  16679. cacheNeedsRefilling = true;
  16680. }
  16681. void AudioThumbnail::saveTo (OutputStream& output) const
  16682. {
  16683. AudioThumbnailDataFormat* const d = (AudioThumbnailDataFormat*) data.getData();
  16684. d->swapEndiannessIfNeeded();
  16685. output.write (data.getData(), (int) data.getSize());
  16686. d->swapEndiannessIfNeeded();
  16687. }
  16688. bool AudioThumbnail::initialiseFromAudioFile (AudioFormatReader& fileReader)
  16689. {
  16690. AudioThumbnailDataFormat* d = (AudioThumbnailDataFormat*) data.getData();
  16691. d->totalSamples = fileReader.lengthInSamples;
  16692. d->numChannels = jmin ((uint32) 2, fileReader.numChannels);
  16693. d->numFinishedSamples = 0;
  16694. d->sampleRate = roundToInt (fileReader.sampleRate);
  16695. d->numThumbnailSamples = (int) (d->totalSamples / d->samplesPerThumbSample) + 1;
  16696. data.setSize (sizeof (AudioThumbnailDataFormat) + 3 + d->numThumbnailSamples * d->numChannels * 2);
  16697. d = (AudioThumbnailDataFormat*) data.getData();
  16698. zeromem (&(d->data[0]), d->numThumbnailSamples * d->numChannels * 2);
  16699. return d->totalSamples > 0;
  16700. }
  16701. bool AudioThumbnail::readNextBlockFromAudioFile (AudioFormatReader& fileReader)
  16702. {
  16703. AudioThumbnailDataFormat* const d = (AudioThumbnailDataFormat*) data.getData();
  16704. if (d->numFinishedSamples < d->totalSamples)
  16705. {
  16706. const int numToDo = (int) jmin ((int64) 65536, d->totalSamples - d->numFinishedSamples);
  16707. generateSection (fileReader,
  16708. d->numFinishedSamples,
  16709. numToDo);
  16710. d->numFinishedSamples += numToDo;
  16711. }
  16712. cacheNeedsRefilling = true;
  16713. return (d->numFinishedSamples < d->totalSamples);
  16714. }
  16715. int AudioThumbnail::getNumChannels() const throw()
  16716. {
  16717. const AudioThumbnailDataFormat* const d = (const AudioThumbnailDataFormat*) data.getData();
  16718. jassert (d != 0);
  16719. return d->numChannels;
  16720. }
  16721. double AudioThumbnail::getTotalLength() const throw()
  16722. {
  16723. const AudioThumbnailDataFormat* const d = (const AudioThumbnailDataFormat*) data.getData();
  16724. jassert (d != 0);
  16725. if (d->sampleRate > 0)
  16726. return d->totalSamples / (double)d->sampleRate;
  16727. else
  16728. return 0.0;
  16729. }
  16730. void AudioThumbnail::generateSection (AudioFormatReader& fileReader,
  16731. int64 startSample,
  16732. int numSamples)
  16733. {
  16734. AudioThumbnailDataFormat* const d = (AudioThumbnailDataFormat*) data.getData();
  16735. jassert (d != 0);
  16736. int firstDataPos = (int) (startSample / d->samplesPerThumbSample);
  16737. int lastDataPos = (int) ((startSample + numSamples) / d->samplesPerThumbSample);
  16738. char* l = getChannelData (0);
  16739. char* r = getChannelData (1);
  16740. for (int i = firstDataPos; i < lastDataPos; ++i)
  16741. {
  16742. const int sourceStart = i * d->samplesPerThumbSample;
  16743. const int sourceEnd = sourceStart + d->samplesPerThumbSample;
  16744. float lowestLeft, highestLeft, lowestRight, highestRight;
  16745. fileReader.readMaxLevels (sourceStart,
  16746. sourceEnd - sourceStart,
  16747. lowestLeft,
  16748. highestLeft,
  16749. lowestRight,
  16750. highestRight);
  16751. int n = i * 2;
  16752. if (r != 0)
  16753. {
  16754. l [n] = (char) jlimit (-128.0f, 127.0f, lowestLeft * 127.0f);
  16755. r [n++] = (char) jlimit (-128.0f, 127.0f, lowestRight * 127.0f);
  16756. l [n] = (char) jlimit (-128.0f, 127.0f, highestLeft * 127.0f);
  16757. r [n++] = (char) jlimit (-128.0f, 127.0f, highestRight * 127.0f);
  16758. }
  16759. else
  16760. {
  16761. l [n++] = (char) jlimit (-128.0f, 127.0f, lowestLeft * 127.0f);
  16762. l [n++] = (char) jlimit (-128.0f, 127.0f, highestLeft * 127.0f);
  16763. }
  16764. }
  16765. }
  16766. char* AudioThumbnail::getChannelData (int channel) const
  16767. {
  16768. AudioThumbnailDataFormat* const d = (AudioThumbnailDataFormat*) data.getData();
  16769. jassert (d != 0);
  16770. if (channel >= 0 && channel < d->numChannels)
  16771. return d->data + (channel * 2 * d->numThumbnailSamples);
  16772. return 0;
  16773. }
  16774. bool AudioThumbnail::isFullyLoaded() const throw()
  16775. {
  16776. const AudioThumbnailDataFormat* const d = (const AudioThumbnailDataFormat*) data.getData();
  16777. jassert (d != 0);
  16778. return d->numFinishedSamples >= d->totalSamples;
  16779. }
  16780. void AudioThumbnail::refillCache (const int numSamples,
  16781. double startTime,
  16782. const double timePerPixel)
  16783. {
  16784. const AudioThumbnailDataFormat* const d = (const AudioThumbnailDataFormat*) data.getData();
  16785. jassert (d != 0);
  16786. if (numSamples <= 0
  16787. || timePerPixel <= 0.0
  16788. || d->sampleRate <= 0)
  16789. {
  16790. numSamplesCached = 0;
  16791. cacheNeedsRefilling = true;
  16792. return;
  16793. }
  16794. if (numSamples == numSamplesCached
  16795. && numChannelsCached == d->numChannels
  16796. && startTime == cachedStart
  16797. && timePerPixel == cachedTimePerPixel
  16798. && ! cacheNeedsRefilling)
  16799. {
  16800. return;
  16801. }
  16802. numSamplesCached = numSamples;
  16803. numChannelsCached = d->numChannels;
  16804. cachedStart = startTime;
  16805. cachedTimePerPixel = timePerPixel;
  16806. cachedLevels.ensureSize (2 * numChannelsCached * numSamples);
  16807. const bool needExtraDetail = (timePerPixel * d->sampleRate <= d->samplesPerThumbSample);
  16808. const ScopedLock sl (readerLock);
  16809. cacheNeedsRefilling = false;
  16810. if (needExtraDetail && reader == 0)
  16811. reader = createReader();
  16812. if (reader != 0 && timePerPixel * d->sampleRate <= d->samplesPerThumbSample)
  16813. {
  16814. startTimer (timeBeforeDeletingReader);
  16815. char* cacheData = static_cast <char*> (cachedLevels.getData());
  16816. int sample = roundToInt (startTime * d->sampleRate);
  16817. for (int i = numSamples; --i >= 0;)
  16818. {
  16819. const int nextSample = roundToInt ((startTime + timePerPixel) * d->sampleRate);
  16820. if (sample >= 0)
  16821. {
  16822. if (sample >= reader->lengthInSamples)
  16823. break;
  16824. float lmin, lmax, rmin, rmax;
  16825. reader->readMaxLevels (sample,
  16826. jmax (1, nextSample - sample),
  16827. lmin, lmax, rmin, rmax);
  16828. cacheData[0] = (char) jlimit (-128, 127, roundFloatToInt (lmin * 127.0f));
  16829. cacheData[1] = (char) jlimit (-128, 127, roundFloatToInt (lmax * 127.0f));
  16830. if (numChannelsCached > 1)
  16831. {
  16832. cacheData[2] = (char) jlimit (-128, 127, roundFloatToInt (rmin * 127.0f));
  16833. cacheData[3] = (char) jlimit (-128, 127, roundFloatToInt (rmax * 127.0f));
  16834. }
  16835. cacheData += 2 * numChannelsCached;
  16836. }
  16837. startTime += timePerPixel;
  16838. sample = nextSample;
  16839. }
  16840. }
  16841. else
  16842. {
  16843. for (int channelNum = 0; channelNum < numChannelsCached; ++channelNum)
  16844. {
  16845. char* const channelData = getChannelData (channelNum);
  16846. char* cacheData = static_cast <char*> (cachedLevels.getData()) + channelNum * 2;
  16847. const double timeToThumbSampleFactor = d->sampleRate / (double) d->samplesPerThumbSample;
  16848. startTime = cachedStart;
  16849. int sample = roundToInt (startTime * timeToThumbSampleFactor);
  16850. const int numFinished = (int) (d->numFinishedSamples / d->samplesPerThumbSample);
  16851. for (int i = numSamples; --i >= 0;)
  16852. {
  16853. const int nextSample = roundToInt ((startTime + timePerPixel) * timeToThumbSampleFactor);
  16854. if (sample >= 0 && channelData != 0)
  16855. {
  16856. char mx = -128;
  16857. char mn = 127;
  16858. while (sample <= nextSample)
  16859. {
  16860. if (sample >= numFinished)
  16861. break;
  16862. const int n = sample << 1;
  16863. const char sampMin = channelData [n];
  16864. const char sampMax = channelData [n + 1];
  16865. if (sampMin < mn)
  16866. mn = sampMin;
  16867. if (sampMax > mx)
  16868. mx = sampMax;
  16869. ++sample;
  16870. }
  16871. if (mn <= mx)
  16872. {
  16873. cacheData[0] = mn;
  16874. cacheData[1] = mx;
  16875. }
  16876. else
  16877. {
  16878. cacheData[0] = 1;
  16879. cacheData[1] = 0;
  16880. }
  16881. }
  16882. else
  16883. {
  16884. cacheData[0] = 1;
  16885. cacheData[1] = 0;
  16886. }
  16887. cacheData += numChannelsCached * 2;
  16888. startTime += timePerPixel;
  16889. sample = nextSample;
  16890. }
  16891. }
  16892. }
  16893. }
  16894. void AudioThumbnail::drawChannel (Graphics& g,
  16895. int x, int y, int w, int h,
  16896. double startTime,
  16897. double endTime,
  16898. int channelNum,
  16899. const float verticalZoomFactor)
  16900. {
  16901. refillCache (w, startTime, (endTime - startTime) / w);
  16902. if (numSamplesCached >= w
  16903. && channelNum >= 0
  16904. && channelNum < numChannelsCached)
  16905. {
  16906. const float topY = (float) y;
  16907. const float bottomY = topY + h;
  16908. const float midY = topY + h * 0.5f;
  16909. const float vscale = verticalZoomFactor * h / 256.0f;
  16910. const Rectangle<int> clip (g.getClipBounds());
  16911. const int skipLeft = jlimit (0, w, clip.getX() - x);
  16912. w -= skipLeft;
  16913. x += skipLeft;
  16914. const char* cacheData = static_cast <const char*> (cachedLevels.getData())
  16915. + (channelNum << 1)
  16916. + skipLeft * (numChannelsCached << 1);
  16917. while (--w >= 0)
  16918. {
  16919. const char mn = cacheData[0];
  16920. const char mx = cacheData[1];
  16921. cacheData += numChannelsCached << 1;
  16922. if (mn <= mx) // if the wrong way round, signifies that the sample's not yet known
  16923. g.drawLine ((float) x, jmax (midY - mx * vscale - 0.3f, topY),
  16924. (float) x, jmin (midY - mn * vscale + 0.3f, bottomY));
  16925. ++x;
  16926. if (x >= clip.getRight())
  16927. break;
  16928. }
  16929. }
  16930. }
  16931. END_JUCE_NAMESPACE
  16932. /*** End of inlined file: juce_AudioThumbnail.cpp ***/
  16933. /*** Start of inlined file: juce_AudioThumbnailCache.cpp ***/
  16934. BEGIN_JUCE_NAMESPACE
  16935. struct ThumbnailCacheEntry
  16936. {
  16937. int64 hash;
  16938. uint32 lastUsed;
  16939. MemoryBlock data;
  16940. juce_UseDebuggingNewOperator
  16941. };
  16942. AudioThumbnailCache::AudioThumbnailCache (const int maxNumThumbsToStore_)
  16943. : TimeSliceThread ("thumb cache"),
  16944. maxNumThumbsToStore (maxNumThumbsToStore_)
  16945. {
  16946. startThread (2);
  16947. }
  16948. AudioThumbnailCache::~AudioThumbnailCache()
  16949. {
  16950. }
  16951. bool AudioThumbnailCache::loadThumb (AudioThumbnail& thumb, const int64 hashCode)
  16952. {
  16953. for (int i = thumbs.size(); --i >= 0;)
  16954. {
  16955. if (thumbs[i]->hash == hashCode)
  16956. {
  16957. MemoryInputStream in (thumbs[i]->data, false);
  16958. thumb.loadFrom (in);
  16959. thumbs[i]->lastUsed = Time::getMillisecondCounter();
  16960. return true;
  16961. }
  16962. }
  16963. return false;
  16964. }
  16965. void AudioThumbnailCache::storeThumb (const AudioThumbnail& thumb,
  16966. const int64 hashCode)
  16967. {
  16968. MemoryOutputStream out;
  16969. thumb.saveTo (out);
  16970. ThumbnailCacheEntry* te = 0;
  16971. for (int i = thumbs.size(); --i >= 0;)
  16972. {
  16973. if (thumbs[i]->hash == hashCode)
  16974. {
  16975. te = thumbs[i];
  16976. break;
  16977. }
  16978. }
  16979. if (te == 0)
  16980. {
  16981. te = new ThumbnailCacheEntry();
  16982. te->hash = hashCode;
  16983. if (thumbs.size() < maxNumThumbsToStore)
  16984. {
  16985. thumbs.add (te);
  16986. }
  16987. else
  16988. {
  16989. int oldest = 0;
  16990. unsigned int oldestTime = Time::getMillisecondCounter() + 1;
  16991. int i;
  16992. for (i = thumbs.size(); --i >= 0;)
  16993. if (thumbs[i]->lastUsed < oldestTime)
  16994. oldest = i;
  16995. thumbs.set (i, te);
  16996. }
  16997. }
  16998. te->lastUsed = Time::getMillisecondCounter();
  16999. te->data.setSize (0);
  17000. te->data.append (out.getData(), out.getDataSize());
  17001. }
  17002. void AudioThumbnailCache::clear()
  17003. {
  17004. thumbs.clear();
  17005. }
  17006. void AudioThumbnailCache::addThumbnail (AudioThumbnail* const thumb)
  17007. {
  17008. addTimeSliceClient (thumb);
  17009. }
  17010. void AudioThumbnailCache::removeThumbnail (AudioThumbnail* const thumb)
  17011. {
  17012. removeTimeSliceClient (thumb);
  17013. }
  17014. END_JUCE_NAMESPACE
  17015. /*** End of inlined file: juce_AudioThumbnailCache.cpp ***/
  17016. /*** Start of inlined file: juce_QuickTimeAudioFormat.cpp ***/
  17017. #if JUCE_QUICKTIME && ! (JUCE_64BIT || JUCE_IPHONE)
  17018. #if ! JUCE_WINDOWS
  17019. #include <QuickTime/Movies.h>
  17020. #include <QuickTime/QTML.h>
  17021. #include <QuickTime/QuickTimeComponents.h>
  17022. #include <QuickTime/MediaHandlers.h>
  17023. #include <QuickTime/ImageCodec.h>
  17024. #else
  17025. #if JUCE_MSVC
  17026. #pragma warning (push)
  17027. #pragma warning (disable : 4100)
  17028. #endif
  17029. /* If you've got an include error here, you probably need to install the QuickTime SDK and
  17030. add its header directory to your include path.
  17031. Alternatively, if you don't need any QuickTime services, just turn off the JUC_QUICKTIME
  17032. flag in juce_Config.h
  17033. */
  17034. #include <Movies.h>
  17035. #include <QTML.h>
  17036. #include <QuickTimeComponents.h>
  17037. #include <MediaHandlers.h>
  17038. #include <ImageCodec.h>
  17039. #if JUCE_MSVC
  17040. #pragma warning (pop)
  17041. #endif
  17042. #endif
  17043. BEGIN_JUCE_NAMESPACE
  17044. bool juce_OpenQuickTimeMovieFromStream (InputStream* input, Movie& movie, Handle& dataHandle);
  17045. static const char* const quickTimeFormatName = "QuickTime file";
  17046. static const juce_wchar* const quickTimeExtensions[] = { T(".mov"), T(".mp3"), T(".mp4"), 0 };
  17047. class QTAudioReader : public AudioFormatReader
  17048. {
  17049. public:
  17050. QTAudioReader (InputStream* const input_, const int trackNum_)
  17051. : AudioFormatReader (input_, TRANS (quickTimeFormatName)),
  17052. ok (false),
  17053. movie (0),
  17054. trackNum (trackNum_),
  17055. lastSampleRead (0),
  17056. lastThreadId (0),
  17057. extractor (0),
  17058. dataHandle (0)
  17059. {
  17060. bufferList.calloc (256, 1);
  17061. #ifdef WIN32
  17062. if (InitializeQTML (0) != noErr)
  17063. return;
  17064. #endif
  17065. if (EnterMovies() != noErr)
  17066. return;
  17067. bool opened = juce_OpenQuickTimeMovieFromStream (input_, movie, dataHandle);
  17068. if (! opened)
  17069. return;
  17070. {
  17071. const int numTracks = GetMovieTrackCount (movie);
  17072. int trackCount = 0;
  17073. for (int i = 1; i <= numTracks; ++i)
  17074. {
  17075. track = GetMovieIndTrack (movie, i);
  17076. media = GetTrackMedia (track);
  17077. OSType mediaType;
  17078. GetMediaHandlerDescription (media, &mediaType, 0, 0);
  17079. if (mediaType == SoundMediaType
  17080. && trackCount++ == trackNum_)
  17081. {
  17082. ok = true;
  17083. break;
  17084. }
  17085. }
  17086. }
  17087. if (! ok)
  17088. return;
  17089. ok = false;
  17090. lengthInSamples = GetMediaDecodeDuration (media);
  17091. usesFloatingPointData = false;
  17092. samplesPerFrame = (int) (GetMediaDecodeDuration (media) / GetMediaSampleCount (media));
  17093. trackUnitsPerFrame = GetMovieTimeScale (movie) * samplesPerFrame
  17094. / GetMediaTimeScale (media);
  17095. OSStatus err = MovieAudioExtractionBegin (movie, 0, &extractor);
  17096. unsigned long output_layout_size;
  17097. err = MovieAudioExtractionGetPropertyInfo (extractor,
  17098. kQTPropertyClass_MovieAudioExtraction_Audio,
  17099. kQTMovieAudioExtractionAudioPropertyID_AudioChannelLayout,
  17100. 0, &output_layout_size, 0);
  17101. if (err != noErr)
  17102. return;
  17103. HeapBlock <AudioChannelLayout> qt_audio_channel_layout;
  17104. qt_audio_channel_layout.calloc (output_layout_size, 1);
  17105. err = MovieAudioExtractionGetProperty (extractor,
  17106. kQTPropertyClass_MovieAudioExtraction_Audio,
  17107. kQTMovieAudioExtractionAudioPropertyID_AudioChannelLayout,
  17108. output_layout_size, qt_audio_channel_layout, 0);
  17109. qt_audio_channel_layout[0].mChannelLayoutTag = kAudioChannelLayoutTag_Stereo;
  17110. err = MovieAudioExtractionSetProperty (extractor,
  17111. kQTPropertyClass_MovieAudioExtraction_Audio,
  17112. kQTMovieAudioExtractionAudioPropertyID_AudioChannelLayout,
  17113. output_layout_size,
  17114. qt_audio_channel_layout);
  17115. err = MovieAudioExtractionGetProperty (extractor,
  17116. kQTPropertyClass_MovieAudioExtraction_Audio,
  17117. kQTMovieAudioExtractionAudioPropertyID_AudioStreamBasicDescription,
  17118. sizeof (inputStreamDesc),
  17119. &inputStreamDesc, 0);
  17120. if (err != noErr)
  17121. return;
  17122. inputStreamDesc.mFormatFlags = kAudioFormatFlagIsSignedInteger
  17123. | kAudioFormatFlagIsPacked
  17124. | kAudioFormatFlagsNativeEndian;
  17125. inputStreamDesc.mBitsPerChannel = sizeof (SInt16) * 8;
  17126. inputStreamDesc.mChannelsPerFrame = jmin ((UInt32) 2, inputStreamDesc.mChannelsPerFrame);
  17127. inputStreamDesc.mBytesPerFrame = sizeof (SInt16) * inputStreamDesc.mChannelsPerFrame;
  17128. inputStreamDesc.mBytesPerPacket = inputStreamDesc.mBytesPerFrame;
  17129. err = MovieAudioExtractionSetProperty (extractor,
  17130. kQTPropertyClass_MovieAudioExtraction_Audio,
  17131. kQTMovieAudioExtractionAudioPropertyID_AudioStreamBasicDescription,
  17132. sizeof (inputStreamDesc),
  17133. &inputStreamDesc);
  17134. if (err != noErr)
  17135. return;
  17136. Boolean allChannelsDiscrete = false;
  17137. err = MovieAudioExtractionSetProperty (extractor,
  17138. kQTPropertyClass_MovieAudioExtraction_Movie,
  17139. kQTMovieAudioExtractionMoviePropertyID_AllChannelsDiscrete,
  17140. sizeof (allChannelsDiscrete),
  17141. &allChannelsDiscrete);
  17142. if (err != noErr)
  17143. return;
  17144. bufferList->mNumberBuffers = 1;
  17145. bufferList->mBuffers[0].mNumberChannels = inputStreamDesc.mChannelsPerFrame;
  17146. bufferList->mBuffers[0].mDataByteSize = (UInt32) (samplesPerFrame * inputStreamDesc.mBytesPerFrame) + 16;
  17147. dataBuffer.malloc (bufferList->mBuffers[0].mDataByteSize);
  17148. bufferList->mBuffers[0].mData = dataBuffer;
  17149. sampleRate = inputStreamDesc.mSampleRate;
  17150. bitsPerSample = 16;
  17151. numChannels = inputStreamDesc.mChannelsPerFrame;
  17152. detachThread();
  17153. ok = true;
  17154. }
  17155. ~QTAudioReader()
  17156. {
  17157. if (dataHandle != 0)
  17158. DisposeHandle (dataHandle);
  17159. if (extractor != 0)
  17160. {
  17161. MovieAudioExtractionEnd (extractor);
  17162. extractor = 0;
  17163. }
  17164. checkThreadIsAttached();
  17165. DisposeMovie (movie);
  17166. #if JUCE_MAC
  17167. ExitMoviesOnThread ();
  17168. #endif
  17169. }
  17170. bool readSamples (int** destSamples, int numDestChannels, int startOffsetInDestBuffer,
  17171. int64 startSampleInFile, int numSamples)
  17172. {
  17173. checkThreadIsAttached();
  17174. while (numSamples > 0)
  17175. {
  17176. if (! loadFrame ((int) startSampleInFile))
  17177. return false;
  17178. const int numToDo = jmin (numSamples, samplesPerFrame);
  17179. for (int j = numDestChannels; --j >= 0;)
  17180. {
  17181. if (destSamples[j] != 0)
  17182. {
  17183. const short* const src = ((const short*) bufferList->mBuffers[0].mData) + j;
  17184. for (int i = 0; i < numToDo; ++i)
  17185. destSamples[j][startOffsetInDestBuffer + i] = src [i << 1] << 16;
  17186. }
  17187. }
  17188. startOffsetInDestBuffer += numToDo;
  17189. startSampleInFile += numToDo;
  17190. numSamples -= numToDo;
  17191. }
  17192. detachThread();
  17193. return true;
  17194. }
  17195. bool loadFrame (const int sampleNum)
  17196. {
  17197. if (lastSampleRead != sampleNum)
  17198. {
  17199. TimeRecord time;
  17200. time.scale = (TimeScale) inputStreamDesc.mSampleRate;
  17201. time.base = 0;
  17202. time.value.hi = 0;
  17203. time.value.lo = (UInt32) sampleNum;
  17204. OSStatus err = MovieAudioExtractionSetProperty (extractor,
  17205. kQTPropertyClass_MovieAudioExtraction_Movie,
  17206. kQTMovieAudioExtractionMoviePropertyID_CurrentTime,
  17207. sizeof (time), &time);
  17208. if (err != noErr)
  17209. return false;
  17210. }
  17211. bufferList->mBuffers[0].mDataByteSize = inputStreamDesc.mBytesPerFrame * samplesPerFrame;
  17212. UInt32 outFlags = 0;
  17213. UInt32 actualNumSamples = samplesPerFrame;
  17214. OSStatus err = MovieAudioExtractionFillBuffer (extractor, &actualNumSamples,
  17215. bufferList, &outFlags);
  17216. lastSampleRead = sampleNum + samplesPerFrame;
  17217. return err == noErr;
  17218. }
  17219. juce_UseDebuggingNewOperator
  17220. bool ok;
  17221. private:
  17222. Movie movie;
  17223. Media media;
  17224. Track track;
  17225. const int trackNum;
  17226. double trackUnitsPerFrame;
  17227. int samplesPerFrame;
  17228. int lastSampleRead;
  17229. Thread::ThreadID lastThreadId;
  17230. MovieAudioExtractionRef extractor;
  17231. AudioStreamBasicDescription inputStreamDesc;
  17232. HeapBlock <AudioBufferList> bufferList;
  17233. HeapBlock <char> dataBuffer;
  17234. Handle dataHandle;
  17235. void checkThreadIsAttached()
  17236. {
  17237. #if JUCE_MAC
  17238. if (Thread::getCurrentThreadId() != lastThreadId)
  17239. EnterMoviesOnThread (0);
  17240. AttachMovieToCurrentThread (movie);
  17241. #endif
  17242. }
  17243. void detachThread()
  17244. {
  17245. #if JUCE_MAC
  17246. DetachMovieFromCurrentThread (movie);
  17247. #endif
  17248. }
  17249. QTAudioReader (const QTAudioReader&);
  17250. QTAudioReader& operator= (const QTAudioReader&);
  17251. };
  17252. QuickTimeAudioFormat::QuickTimeAudioFormat()
  17253. : AudioFormat (TRANS (quickTimeFormatName), (const juce_wchar**) quickTimeExtensions)
  17254. {
  17255. }
  17256. QuickTimeAudioFormat::~QuickTimeAudioFormat()
  17257. {
  17258. }
  17259. const Array <int> QuickTimeAudioFormat::getPossibleSampleRates()
  17260. {
  17261. return Array<int>();
  17262. }
  17263. const Array <int> QuickTimeAudioFormat::getPossibleBitDepths()
  17264. {
  17265. return Array<int>();
  17266. }
  17267. bool QuickTimeAudioFormat::canDoStereo()
  17268. {
  17269. return true;
  17270. }
  17271. bool QuickTimeAudioFormat::canDoMono()
  17272. {
  17273. return true;
  17274. }
  17275. AudioFormatReader* QuickTimeAudioFormat::createReaderFor (InputStream* sourceStream,
  17276. const bool deleteStreamIfOpeningFails)
  17277. {
  17278. ScopedPointer <QTAudioReader> r (new QTAudioReader (sourceStream, 0));
  17279. if (r->ok)
  17280. return r.release();
  17281. if (! deleteStreamIfOpeningFails)
  17282. r->input = 0;
  17283. return 0;
  17284. }
  17285. AudioFormatWriter* QuickTimeAudioFormat::createWriterFor (OutputStream* /*streamToWriteTo*/,
  17286. double /*sampleRateToUse*/,
  17287. unsigned int /*numberOfChannels*/,
  17288. int /*bitsPerSample*/,
  17289. const StringPairArray& /*metadataValues*/,
  17290. int /*qualityOptionIndex*/)
  17291. {
  17292. jassertfalse // not yet implemented!
  17293. return 0;
  17294. }
  17295. END_JUCE_NAMESPACE
  17296. #endif
  17297. /*** End of inlined file: juce_QuickTimeAudioFormat.cpp ***/
  17298. /*** Start of inlined file: juce_WavAudioFormat.cpp ***/
  17299. BEGIN_JUCE_NAMESPACE
  17300. static const char* const wavFormatName = "WAV file";
  17301. static const juce_wchar* const wavExtensions[] = { T(".wav"), T(".bwf"), 0 };
  17302. const char* const WavAudioFormat::bwavDescription = "bwav description";
  17303. const char* const WavAudioFormat::bwavOriginator = "bwav originator";
  17304. const char* const WavAudioFormat::bwavOriginatorRef = "bwav originator ref";
  17305. const char* const WavAudioFormat::bwavOriginationDate = "bwav origination date";
  17306. const char* const WavAudioFormat::bwavOriginationTime = "bwav origination time";
  17307. const char* const WavAudioFormat::bwavTimeReference = "bwav time reference";
  17308. const char* const WavAudioFormat::bwavCodingHistory = "bwav coding history";
  17309. const StringPairArray WavAudioFormat::createBWAVMetadata (const String& description,
  17310. const String& originator,
  17311. const String& originatorRef,
  17312. const Time& date,
  17313. const int64 timeReferenceSamples,
  17314. const String& codingHistory)
  17315. {
  17316. StringPairArray m;
  17317. m.set (bwavDescription, description);
  17318. m.set (bwavOriginator, originator);
  17319. m.set (bwavOriginatorRef, originatorRef);
  17320. m.set (bwavOriginationDate, date.formatted ("%Y-%m-%d"));
  17321. m.set (bwavOriginationTime, date.formatted ("%H:%M:%S"));
  17322. m.set (bwavTimeReference, String (timeReferenceSamples));
  17323. m.set (bwavCodingHistory, codingHistory);
  17324. return m;
  17325. }
  17326. #if JUCE_MSVC
  17327. #pragma pack (push, 1)
  17328. #define PACKED
  17329. #elif JUCE_GCC
  17330. #define PACKED __attribute__((packed))
  17331. #else
  17332. #define PACKED
  17333. #endif
  17334. struct BWAVChunk
  17335. {
  17336. char description [256];
  17337. char originator [32];
  17338. char originatorRef [32];
  17339. char originationDate [10];
  17340. char originationTime [8];
  17341. uint32 timeRefLow;
  17342. uint32 timeRefHigh;
  17343. uint16 version;
  17344. uint8 umid[64];
  17345. uint8 reserved[190];
  17346. char codingHistory[1];
  17347. void copyTo (StringPairArray& values) const
  17348. {
  17349. values.set (WavAudioFormat::bwavDescription, String::fromUTF8 (description, 256));
  17350. values.set (WavAudioFormat::bwavOriginator, String::fromUTF8 (originator, 32));
  17351. values.set (WavAudioFormat::bwavOriginatorRef, String::fromUTF8 (originatorRef, 32));
  17352. values.set (WavAudioFormat::bwavOriginationDate, String::fromUTF8 (originationDate, 10));
  17353. values.set (WavAudioFormat::bwavOriginationTime, String::fromUTF8 (originationTime, 8));
  17354. const uint32 timeLow = ByteOrder::swapIfBigEndian (timeRefLow);
  17355. const uint32 timeHigh = ByteOrder::swapIfBigEndian (timeRefHigh);
  17356. const int64 time = (((int64)timeHigh) << 32) + timeLow;
  17357. values.set (WavAudioFormat::bwavTimeReference, String (time));
  17358. values.set (WavAudioFormat::bwavCodingHistory, String::fromUTF8 (codingHistory));
  17359. }
  17360. static MemoryBlock createFrom (const StringPairArray& values)
  17361. {
  17362. const size_t sizeNeeded = sizeof (BWAVChunk) + values [WavAudioFormat::bwavCodingHistory].getNumBytesAsUTF8();
  17363. MemoryBlock data ((sizeNeeded + 3) & ~3);
  17364. data.fillWith (0);
  17365. BWAVChunk* b = (BWAVChunk*) data.getData();
  17366. // Allow these calls to overwrite an extra byte at the end, which is fine as long
  17367. // as they get called in the right order..
  17368. values [WavAudioFormat::bwavDescription].copyToUTF8 (b->description, 257);
  17369. values [WavAudioFormat::bwavOriginator].copyToUTF8 (b->originator, 33);
  17370. values [WavAudioFormat::bwavOriginatorRef].copyToUTF8 (b->originatorRef, 33);
  17371. values [WavAudioFormat::bwavOriginationDate].copyToUTF8 (b->originationDate, 11);
  17372. values [WavAudioFormat::bwavOriginationTime].copyToUTF8 (b->originationTime, 9);
  17373. const int64 time = values [WavAudioFormat::bwavTimeReference].getLargeIntValue();
  17374. b->timeRefLow = ByteOrder::swapIfBigEndian ((uint32) (time & 0xffffffff));
  17375. b->timeRefHigh = ByteOrder::swapIfBigEndian ((uint32) (time >> 32));
  17376. values [WavAudioFormat::bwavCodingHistory].copyToUTF8 (b->codingHistory, 0x7fffffff);
  17377. if (b->description[0] != 0
  17378. || b->originator[0] != 0
  17379. || b->originationDate[0] != 0
  17380. || b->originationTime[0] != 0
  17381. || b->codingHistory[0] != 0
  17382. || time != 0)
  17383. {
  17384. return data;
  17385. }
  17386. return MemoryBlock();
  17387. }
  17388. } PACKED;
  17389. struct SMPLChunk
  17390. {
  17391. struct SampleLoop
  17392. {
  17393. uint32 identifier;
  17394. uint32 type;
  17395. uint32 start;
  17396. uint32 end;
  17397. uint32 fraction;
  17398. uint32 playCount;
  17399. } PACKED;
  17400. uint32 manufacturer;
  17401. uint32 product;
  17402. uint32 samplePeriod;
  17403. uint32 midiUnityNote;
  17404. uint32 midiPitchFraction;
  17405. uint32 smpteFormat;
  17406. uint32 smpteOffset;
  17407. uint32 numSampleLoops;
  17408. uint32 samplerData;
  17409. SampleLoop loops[1];
  17410. void copyTo (StringPairArray& values, const int totalSize) const
  17411. {
  17412. values.set ("Manufacturer", String (ByteOrder::swapIfBigEndian (manufacturer)));
  17413. values.set ("Product", String (ByteOrder::swapIfBigEndian (product)));
  17414. values.set ("SamplePeriod", String (ByteOrder::swapIfBigEndian (samplePeriod)));
  17415. values.set ("MidiUnityNote", String (ByteOrder::swapIfBigEndian (midiUnityNote)));
  17416. values.set ("MidiPitchFraction", String (ByteOrder::swapIfBigEndian (midiPitchFraction)));
  17417. values.set ("SmpteFormat", String (ByteOrder::swapIfBigEndian (smpteFormat)));
  17418. values.set ("SmpteOffset", String (ByteOrder::swapIfBigEndian (smpteOffset)));
  17419. values.set ("NumSampleLoops", String (ByteOrder::swapIfBigEndian (numSampleLoops)));
  17420. values.set ("SamplerData", String (ByteOrder::swapIfBigEndian (samplerData)));
  17421. for (uint32 i = 0; i < numSampleLoops; ++i)
  17422. {
  17423. if ((uint8*) (loops + (i + 1)) > ((uint8*) this) + totalSize)
  17424. break;
  17425. const String prefix ("Loop" + String(i));
  17426. values.set (prefix + "Identifier", String (ByteOrder::swapIfBigEndian (loops[i].identifier)));
  17427. values.set (prefix + "Type", String (ByteOrder::swapIfBigEndian (loops[i].type)));
  17428. values.set (prefix + "Start", String (ByteOrder::swapIfBigEndian (loops[i].start)));
  17429. values.set (prefix + "End", String (ByteOrder::swapIfBigEndian (loops[i].end)));
  17430. values.set (prefix + "Fraction", String (ByteOrder::swapIfBigEndian (loops[i].fraction)));
  17431. values.set (prefix + "PlayCount", String (ByteOrder::swapIfBigEndian (loops[i].playCount)));
  17432. }
  17433. }
  17434. static MemoryBlock createFrom (const StringPairArray& values)
  17435. {
  17436. const int numLoops = jmin (64, values.getValue ("NumSampleLoops", "0").getIntValue());
  17437. if (numLoops <= 0)
  17438. return MemoryBlock();
  17439. const size_t sizeNeeded = sizeof (SMPLChunk) + (numLoops - 1) * sizeof (SampleLoop);
  17440. MemoryBlock data ((sizeNeeded + 3) & ~3);
  17441. data.fillWith (0);
  17442. SMPLChunk* s = (SMPLChunk*) data.getData();
  17443. // Allow these calls to overwrite an extra byte at the end, which is fine as long
  17444. // as they get called in the right order..
  17445. s->manufacturer = ByteOrder::swapIfBigEndian ((uint32) values.getValue ("Manufacturer", "0").getIntValue());
  17446. s->product = ByteOrder::swapIfBigEndian ((uint32) values.getValue ("Product", "0").getIntValue());
  17447. s->samplePeriod = ByteOrder::swapIfBigEndian ((uint32) values.getValue ("SamplePeriod", "0").getIntValue());
  17448. s->midiUnityNote = ByteOrder::swapIfBigEndian ((uint32) values.getValue ("MidiUnityNote", "60").getIntValue());
  17449. s->midiPitchFraction = ByteOrder::swapIfBigEndian ((uint32) values.getValue ("MidiPitchFraction", "0").getIntValue());
  17450. s->smpteFormat = ByteOrder::swapIfBigEndian ((uint32) values.getValue ("SmpteFormat", "0").getIntValue());
  17451. s->smpteOffset = ByteOrder::swapIfBigEndian ((uint32) values.getValue ("SmpteOffset", "0").getIntValue());
  17452. s->numSampleLoops = ByteOrder::swapIfBigEndian ((uint32) numLoops);
  17453. s->samplerData = ByteOrder::swapIfBigEndian ((uint32) values.getValue ("SamplerData", "0").getIntValue());
  17454. for (int i = 0; i < numLoops; ++i)
  17455. {
  17456. const String prefix ("Loop" + String(i));
  17457. s->loops[i].identifier = ByteOrder::swapIfBigEndian ((uint32) values.getValue (prefix + "Identifier", "0").getIntValue());
  17458. s->loops[i].type = ByteOrder::swapIfBigEndian ((uint32) values.getValue (prefix + "Type", "0").getIntValue());
  17459. s->loops[i].start = ByteOrder::swapIfBigEndian ((uint32) values.getValue (prefix + "Start", "0").getIntValue());
  17460. s->loops[i].end = ByteOrder::swapIfBigEndian ((uint32) values.getValue (prefix + "End", "0").getIntValue());
  17461. s->loops[i].fraction = ByteOrder::swapIfBigEndian ((uint32) values.getValue (prefix + "Fraction", "0").getIntValue());
  17462. s->loops[i].playCount = ByteOrder::swapIfBigEndian ((uint32) values.getValue (prefix + "PlayCount", "0").getIntValue());
  17463. }
  17464. return data;
  17465. }
  17466. } PACKED;
  17467. struct ExtensibleWavSubFormat
  17468. {
  17469. uint32 data1;
  17470. uint16 data2;
  17471. uint16 data3;
  17472. uint8 data4[8];
  17473. } PACKED;
  17474. #if JUCE_MSVC
  17475. #pragma pack (pop)
  17476. #endif
  17477. #undef PACKED
  17478. class WavAudioFormatReader : public AudioFormatReader
  17479. {
  17480. int bytesPerFrame;
  17481. int64 dataChunkStart, dataLength;
  17482. static inline int chunkName (const char* const name) { return (int) ByteOrder::littleEndianInt (name); }
  17483. WavAudioFormatReader (const WavAudioFormatReader&);
  17484. WavAudioFormatReader& operator= (const WavAudioFormatReader&);
  17485. public:
  17486. int64 bwavChunkStart, bwavSize;
  17487. WavAudioFormatReader (InputStream* const in)
  17488. : AudioFormatReader (in, TRANS (wavFormatName)),
  17489. dataLength (0),
  17490. bwavChunkStart (0),
  17491. bwavSize (0)
  17492. {
  17493. if (input->readInt() == chunkName ("RIFF"))
  17494. {
  17495. const uint32 len = (uint32) input->readInt();
  17496. const int64 end = input->getPosition() + len;
  17497. bool hasGotType = false;
  17498. bool hasGotData = false;
  17499. if (input->readInt() == chunkName ("WAVE"))
  17500. {
  17501. while (input->getPosition() < end
  17502. && ! input->isExhausted())
  17503. {
  17504. const int chunkType = input->readInt();
  17505. uint32 length = (uint32) input->readInt();
  17506. const int64 chunkEnd = input->getPosition() + length + (length & 1);
  17507. if (chunkType == chunkName ("fmt "))
  17508. {
  17509. // read the format chunk
  17510. const unsigned short format = input->readShort();
  17511. const short numChans = input->readShort();
  17512. sampleRate = input->readInt();
  17513. const int bytesPerSec = input->readInt();
  17514. numChannels = numChans;
  17515. bytesPerFrame = bytesPerSec / (int)sampleRate;
  17516. bitsPerSample = 8 * bytesPerFrame / numChans;
  17517. if (format == 3)
  17518. {
  17519. usesFloatingPointData = true;
  17520. }
  17521. else if (format == 0xfffe /*WAVE_FORMAT_EXTENSIBLE*/)
  17522. {
  17523. if (length < 40) // too short
  17524. {
  17525. bytesPerFrame = 0;
  17526. }
  17527. else
  17528. {
  17529. input->skipNextBytes (12); // skip over blockAlign, bitsPerSample and speakerPosition mask
  17530. ExtensibleWavSubFormat subFormat;
  17531. subFormat.data1 = input->readInt();
  17532. subFormat.data2 = input->readShort();
  17533. subFormat.data3 = input->readShort();
  17534. input->read (subFormat.data4, sizeof (subFormat.data4));
  17535. const ExtensibleWavSubFormat pcmFormat
  17536. = { 0x00000001, 0x0000, 0x0010, { 0x80, 0x00, 0x00, 0xaa, 0x00, 0x38, 0x9b, 0x71 } };
  17537. if (memcmp (&subFormat, &pcmFormat, sizeof (subFormat)) != 0)
  17538. {
  17539. const ExtensibleWavSubFormat ambisonicFormat
  17540. = { 0x00000001, 0x0721, 0x11d3, { 0x86, 0x44, 0xC8, 0xC1, 0xCA, 0x00, 0x00, 0x00 } };
  17541. if (memcmp (&subFormat, &ambisonicFormat, sizeof (subFormat)) != 0)
  17542. bytesPerFrame = 0;
  17543. }
  17544. }
  17545. }
  17546. else if (format != 1)
  17547. {
  17548. bytesPerFrame = 0;
  17549. }
  17550. hasGotType = true;
  17551. }
  17552. else if (chunkType == chunkName ("data"))
  17553. {
  17554. // get the data chunk's position
  17555. dataLength = length;
  17556. dataChunkStart = input->getPosition();
  17557. lengthInSamples = (bytesPerFrame > 0) ? (dataLength / bytesPerFrame) : 0;
  17558. hasGotData = true;
  17559. }
  17560. else if (chunkType == chunkName ("bext"))
  17561. {
  17562. bwavChunkStart = input->getPosition();
  17563. bwavSize = length;
  17564. // Broadcast-wav extension chunk..
  17565. HeapBlock <BWAVChunk> bwav;
  17566. bwav.calloc (jmax ((size_t) length + 1, sizeof (BWAVChunk)), 1);
  17567. input->read (bwav, length);
  17568. bwav->copyTo (metadataValues);
  17569. }
  17570. else if (chunkType == chunkName ("smpl"))
  17571. {
  17572. HeapBlock <SMPLChunk> smpl;
  17573. smpl.calloc (jmax ((size_t) length + 1, sizeof (SMPLChunk)), 1);
  17574. input->read (smpl, length);
  17575. smpl->copyTo (metadataValues, length);
  17576. }
  17577. else if (chunkEnd <= input->getPosition())
  17578. {
  17579. break;
  17580. }
  17581. input->setPosition (chunkEnd);
  17582. }
  17583. }
  17584. }
  17585. }
  17586. ~WavAudioFormatReader()
  17587. {
  17588. }
  17589. bool readSamples (int** destSamples, int numDestChannels, int startOffsetInDestBuffer,
  17590. int64 startSampleInFile, int numSamples)
  17591. {
  17592. const int64 samplesAvailable = lengthInSamples - startSampleInFile;
  17593. if (samplesAvailable < numSamples)
  17594. {
  17595. for (int i = numDestChannels; --i >= 0;)
  17596. if (destSamples[i] != 0)
  17597. zeromem (destSamples[i] + startOffsetInDestBuffer, sizeof (int) * numSamples);
  17598. numSamples = (int) samplesAvailable;
  17599. }
  17600. if (numSamples <= 0)
  17601. return true;
  17602. input->setPosition (dataChunkStart + startSampleInFile * bytesPerFrame);
  17603. const int tempBufSize = 480 * 3 * 4; // (keep this a multiple of 3)
  17604. char tempBuffer [tempBufSize];
  17605. while (numSamples > 0)
  17606. {
  17607. int* left = destSamples[0];
  17608. if (left != 0)
  17609. left += startOffsetInDestBuffer;
  17610. int* right = numDestChannels > 1 ? destSamples[1] : 0;
  17611. if (right != 0)
  17612. right += startOffsetInDestBuffer;
  17613. const int numThisTime = jmin (tempBufSize / bytesPerFrame, numSamples);
  17614. const int bytesRead = input->read (tempBuffer, numThisTime * bytesPerFrame);
  17615. if (bytesRead < numThisTime * bytesPerFrame)
  17616. zeromem (tempBuffer + bytesRead, numThisTime * bytesPerFrame - bytesRead);
  17617. if (bitsPerSample == 16)
  17618. {
  17619. const short* src = reinterpret_cast <const short*> (tempBuffer);
  17620. if (numChannels > 1)
  17621. {
  17622. if (left == 0)
  17623. {
  17624. for (int i = numThisTime; --i >= 0;)
  17625. {
  17626. ++src;
  17627. *right++ = (int) ByteOrder::swapIfBigEndian ((unsigned short) *src++) << 16;
  17628. }
  17629. }
  17630. else if (right == 0)
  17631. {
  17632. for (int i = numThisTime; --i >= 0;)
  17633. {
  17634. *left++ = (int) ByteOrder::swapIfBigEndian ((unsigned short) *src++) << 16;
  17635. ++src;
  17636. }
  17637. }
  17638. else
  17639. {
  17640. for (int i = numThisTime; --i >= 0;)
  17641. {
  17642. *left++ = (int) ByteOrder::swapIfBigEndian ((unsigned short) *src++) << 16;
  17643. *right++ = (int) ByteOrder::swapIfBigEndian ((unsigned short) *src++) << 16;
  17644. }
  17645. }
  17646. }
  17647. else
  17648. {
  17649. for (int i = numThisTime; --i >= 0;)
  17650. {
  17651. *left++ = (int) ByteOrder::swapIfBigEndian ((unsigned short) *src++) << 16;
  17652. }
  17653. }
  17654. }
  17655. else if (bitsPerSample == 24)
  17656. {
  17657. const char* src = tempBuffer;
  17658. if (numChannels > 1)
  17659. {
  17660. if (left == 0)
  17661. {
  17662. for (int i = numThisTime; --i >= 0;)
  17663. {
  17664. src += 3;
  17665. *right++ = ByteOrder::littleEndian24Bit (src) << 8;
  17666. src += 3;
  17667. }
  17668. }
  17669. else if (right == 0)
  17670. {
  17671. for (int i = numThisTime; --i >= 0;)
  17672. {
  17673. *left++ = ByteOrder::littleEndian24Bit (src) << 8;
  17674. src += 6;
  17675. }
  17676. }
  17677. else
  17678. {
  17679. for (int i = 0; i < numThisTime; ++i)
  17680. {
  17681. *left++ = ByteOrder::littleEndian24Bit (src) << 8;
  17682. src += 3;
  17683. *right++ = ByteOrder::littleEndian24Bit (src) << 8;
  17684. src += 3;
  17685. }
  17686. }
  17687. }
  17688. else
  17689. {
  17690. for (int i = 0; i < numThisTime; ++i)
  17691. {
  17692. *left++ = ByteOrder::littleEndian24Bit (src) << 8;
  17693. src += 3;
  17694. }
  17695. }
  17696. }
  17697. else if (bitsPerSample == 32)
  17698. {
  17699. const unsigned int* src = (const unsigned int*) tempBuffer;
  17700. unsigned int* l = (unsigned int*) left;
  17701. unsigned int* r = (unsigned int*) right;
  17702. if (numChannels > 1)
  17703. {
  17704. if (l == 0)
  17705. {
  17706. for (int i = numThisTime; --i >= 0;)
  17707. {
  17708. ++src;
  17709. *r++ = ByteOrder::swapIfBigEndian (*src++);
  17710. }
  17711. }
  17712. else if (r == 0)
  17713. {
  17714. for (int i = numThisTime; --i >= 0;)
  17715. {
  17716. *l++ = ByteOrder::swapIfBigEndian (*src++);
  17717. ++src;
  17718. }
  17719. }
  17720. else
  17721. {
  17722. for (int i = numThisTime; --i >= 0;)
  17723. {
  17724. *l++ = ByteOrder::swapIfBigEndian (*src++);
  17725. *r++ = ByteOrder::swapIfBigEndian (*src++);
  17726. }
  17727. }
  17728. }
  17729. else
  17730. {
  17731. for (int i = numThisTime; --i >= 0;)
  17732. {
  17733. *l++ = ByteOrder::swapIfBigEndian (*src++);
  17734. }
  17735. }
  17736. left = (int*)l;
  17737. right = (int*)r;
  17738. }
  17739. else if (bitsPerSample == 8)
  17740. {
  17741. const unsigned char* src = (const unsigned char*) tempBuffer;
  17742. if (numChannels > 1)
  17743. {
  17744. if (left == 0)
  17745. {
  17746. for (int i = numThisTime; --i >= 0;)
  17747. {
  17748. ++src;
  17749. *right++ = ((int) *src++ - 128) << 24;
  17750. }
  17751. }
  17752. else if (right == 0)
  17753. {
  17754. for (int i = numThisTime; --i >= 0;)
  17755. {
  17756. *left++ = ((int) *src++ - 128) << 24;
  17757. ++src;
  17758. }
  17759. }
  17760. else
  17761. {
  17762. for (int i = numThisTime; --i >= 0;)
  17763. {
  17764. *left++ = ((int) *src++ - 128) << 24;
  17765. *right++ = ((int) *src++ - 128) << 24;
  17766. }
  17767. }
  17768. }
  17769. else
  17770. {
  17771. for (int i = numThisTime; --i >= 0;)
  17772. {
  17773. *left++ = ((int)*src++ - 128) << 24;
  17774. }
  17775. }
  17776. }
  17777. startOffsetInDestBuffer += numThisTime;
  17778. numSamples -= numThisTime;
  17779. }
  17780. if (numSamples > 0)
  17781. {
  17782. for (int i = numDestChannels; --i >= 0;)
  17783. if (destSamples[i] != 0)
  17784. zeromem (destSamples[i] + startOffsetInDestBuffer,
  17785. sizeof (int) * numSamples);
  17786. }
  17787. return true;
  17788. }
  17789. juce_UseDebuggingNewOperator
  17790. };
  17791. class WavAudioFormatWriter : public AudioFormatWriter
  17792. {
  17793. MemoryBlock tempBlock, bwavChunk, smplChunk;
  17794. uint32 lengthInSamples, bytesWritten;
  17795. int64 headerPosition;
  17796. bool writeFailed;
  17797. static inline int chunkName (const char* const name) { return (int) ByteOrder::littleEndianInt (name); }
  17798. WavAudioFormatWriter (const WavAudioFormatWriter&);
  17799. WavAudioFormatWriter& operator= (const WavAudioFormatWriter&);
  17800. void writeHeader()
  17801. {
  17802. const bool seekedOk = output->setPosition (headerPosition);
  17803. (void) seekedOk;
  17804. // if this fails, you've given it an output stream that can't seek! It needs
  17805. // to be able to seek back to write the header
  17806. jassert (seekedOk);
  17807. const int bytesPerFrame = numChannels * bitsPerSample / 8;
  17808. output->writeInt (chunkName ("RIFF"));
  17809. output->writeInt ((int) (lengthInSamples * bytesPerFrame
  17810. + ((bwavChunk.getSize() > 0) ? (44 + bwavChunk.getSize()) : 36)));
  17811. output->writeInt (chunkName ("WAVE"));
  17812. output->writeInt (chunkName ("fmt "));
  17813. output->writeInt (16);
  17814. output->writeShort ((bitsPerSample < 32) ? (short) 1 /*WAVE_FORMAT_PCM*/
  17815. : (short) 3 /*WAVE_FORMAT_IEEE_FLOAT*/);
  17816. output->writeShort ((short) numChannels);
  17817. output->writeInt ((int) sampleRate);
  17818. output->writeInt (bytesPerFrame * (int) sampleRate);
  17819. output->writeShort ((short) bytesPerFrame);
  17820. output->writeShort ((short) bitsPerSample);
  17821. if (bwavChunk.getSize() > 0)
  17822. {
  17823. output->writeInt (chunkName ("bext"));
  17824. output->writeInt ((int) bwavChunk.getSize());
  17825. output->write (bwavChunk.getData(), (int) bwavChunk.getSize());
  17826. }
  17827. if (smplChunk.getSize() > 0)
  17828. {
  17829. output->writeInt (chunkName ("smpl"));
  17830. output->writeInt ((int) smplChunk.getSize());
  17831. output->write (smplChunk.getData(), (int) smplChunk.getSize());
  17832. }
  17833. output->writeInt (chunkName ("data"));
  17834. output->writeInt (lengthInSamples * bytesPerFrame);
  17835. usesFloatingPointData = (bitsPerSample == 32);
  17836. }
  17837. public:
  17838. WavAudioFormatWriter (OutputStream* const out,
  17839. const double sampleRate_,
  17840. const unsigned int numChannels_,
  17841. const int bits,
  17842. const StringPairArray& metadataValues)
  17843. : AudioFormatWriter (out,
  17844. TRANS (wavFormatName),
  17845. sampleRate_,
  17846. numChannels_,
  17847. bits),
  17848. lengthInSamples (0),
  17849. bytesWritten (0),
  17850. writeFailed (false)
  17851. {
  17852. if (metadataValues.size() > 0)
  17853. {
  17854. bwavChunk = BWAVChunk::createFrom (metadataValues);
  17855. smplChunk = SMPLChunk::createFrom (metadataValues);
  17856. }
  17857. headerPosition = out->getPosition();
  17858. writeHeader();
  17859. }
  17860. ~WavAudioFormatWriter()
  17861. {
  17862. writeHeader();
  17863. }
  17864. bool write (const int** data, int numSamples)
  17865. {
  17866. if (writeFailed)
  17867. return false;
  17868. const int bytes = numChannels * numSamples * bitsPerSample / 8;
  17869. tempBlock.ensureSize (bytes, false);
  17870. char* buffer = static_cast <char*> (tempBlock.getData());
  17871. const int* left = data[0];
  17872. const int* right = data[1];
  17873. if (right == 0)
  17874. right = left;
  17875. if (bitsPerSample == 16)
  17876. {
  17877. short* b = (short*) buffer;
  17878. if (numChannels > 1)
  17879. {
  17880. for (int i = numSamples; --i >= 0;)
  17881. {
  17882. *b++ = (short) ByteOrder::swapIfBigEndian ((unsigned short) (*left++ >> 16));
  17883. *b++ = (short) ByteOrder::swapIfBigEndian ((unsigned short) (*right++ >> 16));
  17884. }
  17885. }
  17886. else
  17887. {
  17888. for (int i = numSamples; --i >= 0;)
  17889. {
  17890. *b++ = (short) ByteOrder::swapIfBigEndian ((unsigned short) (*left++ >> 16));
  17891. }
  17892. }
  17893. }
  17894. else if (bitsPerSample == 24)
  17895. {
  17896. char* b = buffer;
  17897. if (numChannels > 1)
  17898. {
  17899. for (int i = numSamples; --i >= 0;)
  17900. {
  17901. ByteOrder::littleEndian24BitToChars ((*left++) >> 8, b);
  17902. b += 3;
  17903. ByteOrder::littleEndian24BitToChars ((*right++) >> 8, b);
  17904. b += 3;
  17905. }
  17906. }
  17907. else
  17908. {
  17909. for (int i = numSamples; --i >= 0;)
  17910. {
  17911. ByteOrder::littleEndian24BitToChars ((*left++) >> 8, b);
  17912. b += 3;
  17913. }
  17914. }
  17915. }
  17916. else if (bitsPerSample == 32)
  17917. {
  17918. unsigned int* b = (unsigned int*) buffer;
  17919. if (numChannels > 1)
  17920. {
  17921. for (int i = numSamples; --i >= 0;)
  17922. {
  17923. *b++ = ByteOrder::swapIfBigEndian ((unsigned int) *left++);
  17924. *b++ = ByteOrder::swapIfBigEndian ((unsigned int) *right++);
  17925. }
  17926. }
  17927. else
  17928. {
  17929. for (int i = numSamples; --i >= 0;)
  17930. {
  17931. *b++ = ByteOrder::swapIfBigEndian ((unsigned int) *left++);
  17932. }
  17933. }
  17934. }
  17935. else if (bitsPerSample == 8)
  17936. {
  17937. unsigned char* b = (unsigned char*) buffer;
  17938. if (numChannels > 1)
  17939. {
  17940. for (int i = numSamples; --i >= 0;)
  17941. {
  17942. *b++ = (unsigned char) (128 + (*left++ >> 24));
  17943. *b++ = (unsigned char) (128 + (*right++ >> 24));
  17944. }
  17945. }
  17946. else
  17947. {
  17948. for (int i = numSamples; --i >= 0;)
  17949. {
  17950. *b++ = (unsigned char) (128 + (*left++ >> 24));
  17951. }
  17952. }
  17953. }
  17954. if (bytesWritten + bytes >= (uint32) 0xfff00000
  17955. || ! output->write (buffer, bytes))
  17956. {
  17957. // failed to write to disk, so let's try writing the header.
  17958. // If it's just run out of disk space, then if it does manage
  17959. // to write the header, we'll still have a useable file..
  17960. writeHeader();
  17961. writeFailed = true;
  17962. return false;
  17963. }
  17964. else
  17965. {
  17966. bytesWritten += bytes;
  17967. lengthInSamples += numSamples;
  17968. return true;
  17969. }
  17970. }
  17971. juce_UseDebuggingNewOperator
  17972. };
  17973. WavAudioFormat::WavAudioFormat()
  17974. : AudioFormat (TRANS (wavFormatName), (const juce_wchar**) wavExtensions)
  17975. {
  17976. }
  17977. WavAudioFormat::~WavAudioFormat()
  17978. {
  17979. }
  17980. const Array <int> WavAudioFormat::getPossibleSampleRates()
  17981. {
  17982. const int rates[] = { 22050, 32000, 44100, 48000, 88200, 96000, 176400, 192000, 0 };
  17983. return Array <int> (rates);
  17984. }
  17985. const Array <int> WavAudioFormat::getPossibleBitDepths()
  17986. {
  17987. const int depths[] = { 8, 16, 24, 32, 0 };
  17988. return Array <int> (depths);
  17989. }
  17990. bool WavAudioFormat::canDoStereo()
  17991. {
  17992. return true;
  17993. }
  17994. bool WavAudioFormat::canDoMono()
  17995. {
  17996. return true;
  17997. }
  17998. AudioFormatReader* WavAudioFormat::createReaderFor (InputStream* sourceStream,
  17999. const bool deleteStreamIfOpeningFails)
  18000. {
  18001. ScopedPointer <WavAudioFormatReader> r (new WavAudioFormatReader (sourceStream));
  18002. if (r->sampleRate != 0)
  18003. return r.release();
  18004. if (! deleteStreamIfOpeningFails)
  18005. r->input = 0;
  18006. return 0;
  18007. }
  18008. AudioFormatWriter* WavAudioFormat::createWriterFor (OutputStream* out,
  18009. double sampleRate,
  18010. unsigned int numChannels,
  18011. int bitsPerSample,
  18012. const StringPairArray& metadataValues,
  18013. int /*qualityOptionIndex*/)
  18014. {
  18015. if (getPossibleBitDepths().contains (bitsPerSample))
  18016. {
  18017. return new WavAudioFormatWriter (out,
  18018. sampleRate,
  18019. numChannels,
  18020. bitsPerSample,
  18021. metadataValues);
  18022. }
  18023. return 0;
  18024. }
  18025. static bool juce_slowCopyOfWavFileWithNewMetadata (const File& file, const StringPairArray& metadata)
  18026. {
  18027. TemporaryFile tempFile (file);
  18028. WavAudioFormat wav;
  18029. ScopedPointer <AudioFormatReader> reader (wav.createReaderFor (file.createInputStream(), true));
  18030. if (reader != 0)
  18031. {
  18032. ScopedPointer <OutputStream> outStream (tempFile.getFile().createOutputStream());
  18033. if (outStream != 0)
  18034. {
  18035. ScopedPointer <AudioFormatWriter> writer (wav.createWriterFor (outStream, reader->sampleRate,
  18036. reader->numChannels, reader->bitsPerSample,
  18037. metadata, 0));
  18038. if (writer != 0)
  18039. {
  18040. outStream.release();
  18041. bool ok = writer->writeFromAudioReader (*reader, 0, -1);
  18042. writer = 0;
  18043. reader = 0;
  18044. return ok && tempFile.overwriteTargetFileWithTemporary();
  18045. }
  18046. }
  18047. }
  18048. return false;
  18049. }
  18050. bool WavAudioFormat::replaceMetadataInFile (const File& wavFile, const StringPairArray& newMetadata)
  18051. {
  18052. ScopedPointer <WavAudioFormatReader> reader ((WavAudioFormatReader*) createReaderFor (wavFile.createInputStream(), true));
  18053. if (reader != 0)
  18054. {
  18055. const int64 bwavPos = reader->bwavChunkStart;
  18056. const int64 bwavSize = reader->bwavSize;
  18057. reader = 0;
  18058. if (bwavSize > 0)
  18059. {
  18060. MemoryBlock chunk = BWAVChunk::createFrom (newMetadata);
  18061. if (chunk.getSize() <= (size_t) bwavSize)
  18062. {
  18063. // the new one will fit in the space available, so write it directly..
  18064. const int64 oldSize = wavFile.getSize();
  18065. {
  18066. ScopedPointer <FileOutputStream> out (wavFile.createOutputStream());
  18067. out->setPosition (bwavPos);
  18068. out->write (chunk.getData(), (int) chunk.getSize());
  18069. out->setPosition (oldSize);
  18070. }
  18071. jassert (wavFile.getSize() == oldSize);
  18072. return true;
  18073. }
  18074. }
  18075. }
  18076. return juce_slowCopyOfWavFileWithNewMetadata (wavFile, newMetadata);
  18077. }
  18078. END_JUCE_NAMESPACE
  18079. /*** End of inlined file: juce_WavAudioFormat.cpp ***/
  18080. /*** Start of inlined file: juce_AudioFormatReaderSource.cpp ***/
  18081. BEGIN_JUCE_NAMESPACE
  18082. AudioFormatReaderSource::AudioFormatReaderSource (AudioFormatReader* const reader_,
  18083. const bool deleteReaderWhenThisIsDeleted)
  18084. : reader (reader_),
  18085. deleteReader (deleteReaderWhenThisIsDeleted),
  18086. nextPlayPos (0),
  18087. looping (false)
  18088. {
  18089. jassert (reader != 0);
  18090. }
  18091. AudioFormatReaderSource::~AudioFormatReaderSource()
  18092. {
  18093. releaseResources();
  18094. if (deleteReader)
  18095. delete reader;
  18096. }
  18097. void AudioFormatReaderSource::setNextReadPosition (int newPosition)
  18098. {
  18099. nextPlayPos = newPosition;
  18100. }
  18101. void AudioFormatReaderSource::setLooping (const bool shouldLoop) throw()
  18102. {
  18103. looping = shouldLoop;
  18104. }
  18105. int AudioFormatReaderSource::getNextReadPosition() const
  18106. {
  18107. return (looping) ? (nextPlayPos % (int) reader->lengthInSamples)
  18108. : nextPlayPos;
  18109. }
  18110. int AudioFormatReaderSource::getTotalLength() const
  18111. {
  18112. return (int) reader->lengthInSamples;
  18113. }
  18114. void AudioFormatReaderSource::prepareToPlay (int /*samplesPerBlockExpected*/,
  18115. double /*sampleRate*/)
  18116. {
  18117. }
  18118. void AudioFormatReaderSource::releaseResources()
  18119. {
  18120. }
  18121. void AudioFormatReaderSource::getNextAudioBlock (const AudioSourceChannelInfo& info)
  18122. {
  18123. if (info.numSamples > 0)
  18124. {
  18125. const int start = nextPlayPos;
  18126. if (looping)
  18127. {
  18128. const int newStart = start % (int) reader->lengthInSamples;
  18129. const int newEnd = (start + info.numSamples) % (int) reader->lengthInSamples;
  18130. if (newEnd > newStart)
  18131. {
  18132. info.buffer->readFromAudioReader (reader,
  18133. info.startSample,
  18134. newEnd - newStart,
  18135. newStart,
  18136. true, true);
  18137. }
  18138. else
  18139. {
  18140. const int endSamps = (int) reader->lengthInSamples - newStart;
  18141. info.buffer->readFromAudioReader (reader,
  18142. info.startSample,
  18143. endSamps,
  18144. newStart,
  18145. true, true);
  18146. info.buffer->readFromAudioReader (reader,
  18147. info.startSample + endSamps,
  18148. newEnd,
  18149. 0,
  18150. true, true);
  18151. }
  18152. nextPlayPos = newEnd;
  18153. }
  18154. else
  18155. {
  18156. info.buffer->readFromAudioReader (reader,
  18157. info.startSample,
  18158. info.numSamples,
  18159. start,
  18160. true, true);
  18161. nextPlayPos += info.numSamples;
  18162. }
  18163. }
  18164. }
  18165. END_JUCE_NAMESPACE
  18166. /*** End of inlined file: juce_AudioFormatReaderSource.cpp ***/
  18167. /*** Start of inlined file: juce_AudioSourcePlayer.cpp ***/
  18168. BEGIN_JUCE_NAMESPACE
  18169. AudioSourcePlayer::AudioSourcePlayer()
  18170. : source (0),
  18171. sampleRate (0),
  18172. bufferSize (0),
  18173. tempBuffer (2, 8),
  18174. lastGain (1.0f),
  18175. gain (1.0f)
  18176. {
  18177. }
  18178. AudioSourcePlayer::~AudioSourcePlayer()
  18179. {
  18180. setSource (0);
  18181. }
  18182. void AudioSourcePlayer::setSource (AudioSource* newSource)
  18183. {
  18184. if (source != newSource)
  18185. {
  18186. AudioSource* const oldSource = source;
  18187. if (newSource != 0 && bufferSize > 0 && sampleRate > 0)
  18188. newSource->prepareToPlay (bufferSize, sampleRate);
  18189. {
  18190. const ScopedLock sl (readLock);
  18191. source = newSource;
  18192. }
  18193. if (oldSource != 0)
  18194. oldSource->releaseResources();
  18195. }
  18196. }
  18197. void AudioSourcePlayer::setGain (const float newGain) throw()
  18198. {
  18199. gain = newGain;
  18200. }
  18201. void AudioSourcePlayer::audioDeviceIOCallback (const float** inputChannelData,
  18202. int totalNumInputChannels,
  18203. float** outputChannelData,
  18204. int totalNumOutputChannels,
  18205. int numSamples)
  18206. {
  18207. // these should have been prepared by audioDeviceAboutToStart()...
  18208. jassert (sampleRate > 0 && bufferSize > 0);
  18209. const ScopedLock sl (readLock);
  18210. if (source != 0)
  18211. {
  18212. AudioSourceChannelInfo info;
  18213. int i, numActiveChans = 0, numInputs = 0, numOutputs = 0;
  18214. // messy stuff needed to compact the channels down into an array
  18215. // of non-zero pointers..
  18216. for (i = 0; i < totalNumInputChannels; ++i)
  18217. {
  18218. if (inputChannelData[i] != 0)
  18219. {
  18220. inputChans [numInputs++] = inputChannelData[i];
  18221. if (numInputs >= numElementsInArray (inputChans))
  18222. break;
  18223. }
  18224. }
  18225. for (i = 0; i < totalNumOutputChannels; ++i)
  18226. {
  18227. if (outputChannelData[i] != 0)
  18228. {
  18229. outputChans [numOutputs++] = outputChannelData[i];
  18230. if (numOutputs >= numElementsInArray (outputChans))
  18231. break;
  18232. }
  18233. }
  18234. if (numInputs > numOutputs)
  18235. {
  18236. // if there aren't enough output channels for the number of
  18237. // inputs, we need to create some temporary extra ones (can't
  18238. // use the input data in case it gets written to)
  18239. tempBuffer.setSize (numInputs - numOutputs, numSamples,
  18240. false, false, true);
  18241. for (i = 0; i < numOutputs; ++i)
  18242. {
  18243. channels[numActiveChans] = outputChans[i];
  18244. memcpy (channels[numActiveChans], inputChans[i], sizeof (float) * numSamples);
  18245. ++numActiveChans;
  18246. }
  18247. for (i = numOutputs; i < numInputs; ++i)
  18248. {
  18249. channels[numActiveChans] = tempBuffer.getSampleData (i - numOutputs, 0);
  18250. memcpy (channels[numActiveChans], inputChans[i], sizeof (float) * numSamples);
  18251. ++numActiveChans;
  18252. }
  18253. }
  18254. else
  18255. {
  18256. for (i = 0; i < numInputs; ++i)
  18257. {
  18258. channels[numActiveChans] = outputChans[i];
  18259. memcpy (channels[numActiveChans], inputChans[i], sizeof (float) * numSamples);
  18260. ++numActiveChans;
  18261. }
  18262. for (i = numInputs; i < numOutputs; ++i)
  18263. {
  18264. channels[numActiveChans] = outputChans[i];
  18265. zeromem (channels[numActiveChans], sizeof (float) * numSamples);
  18266. ++numActiveChans;
  18267. }
  18268. }
  18269. AudioSampleBuffer buffer (channels, numActiveChans, numSamples);
  18270. info.buffer = &buffer;
  18271. info.startSample = 0;
  18272. info.numSamples = numSamples;
  18273. source->getNextAudioBlock (info);
  18274. for (i = info.buffer->getNumChannels(); --i >= 0;)
  18275. info.buffer->applyGainRamp (i, info.startSample, info.numSamples, lastGain, gain);
  18276. lastGain = gain;
  18277. }
  18278. else
  18279. {
  18280. for (int i = 0; i < totalNumOutputChannels; ++i)
  18281. if (outputChannelData[i] != 0)
  18282. zeromem (outputChannelData[i], sizeof (float) * numSamples);
  18283. }
  18284. }
  18285. void AudioSourcePlayer::audioDeviceAboutToStart (AudioIODevice* device)
  18286. {
  18287. sampleRate = device->getCurrentSampleRate();
  18288. bufferSize = device->getCurrentBufferSizeSamples();
  18289. zeromem (channels, sizeof (channels));
  18290. if (source != 0)
  18291. source->prepareToPlay (bufferSize, sampleRate);
  18292. }
  18293. void AudioSourcePlayer::audioDeviceStopped()
  18294. {
  18295. if (source != 0)
  18296. source->releaseResources();
  18297. sampleRate = 0.0;
  18298. bufferSize = 0;
  18299. tempBuffer.setSize (2, 8);
  18300. }
  18301. END_JUCE_NAMESPACE
  18302. /*** End of inlined file: juce_AudioSourcePlayer.cpp ***/
  18303. /*** Start of inlined file: juce_AudioTransportSource.cpp ***/
  18304. BEGIN_JUCE_NAMESPACE
  18305. AudioTransportSource::AudioTransportSource()
  18306. : source (0),
  18307. resamplerSource (0),
  18308. bufferingSource (0),
  18309. positionableSource (0),
  18310. masterSource (0),
  18311. gain (1.0f),
  18312. lastGain (1.0f),
  18313. playing (false),
  18314. stopped (true),
  18315. sampleRate (44100.0),
  18316. sourceSampleRate (0.0),
  18317. blockSize (128),
  18318. readAheadBufferSize (0),
  18319. isPrepared (false),
  18320. inputStreamEOF (false)
  18321. {
  18322. }
  18323. AudioTransportSource::~AudioTransportSource()
  18324. {
  18325. setSource (0);
  18326. releaseResources();
  18327. }
  18328. void AudioTransportSource::setSource (PositionableAudioSource* const newSource,
  18329. int readAheadBufferSize_,
  18330. double sourceSampleRateToCorrectFor)
  18331. {
  18332. if (source == newSource)
  18333. {
  18334. if (source == 0)
  18335. return;
  18336. setSource (0, 0, 0); // deselect and reselect to avoid releasing resources wrongly
  18337. }
  18338. readAheadBufferSize = readAheadBufferSize_;
  18339. sourceSampleRate = sourceSampleRateToCorrectFor;
  18340. ResamplingAudioSource* newResamplerSource = 0;
  18341. BufferingAudioSource* newBufferingSource = 0;
  18342. PositionableAudioSource* newPositionableSource = 0;
  18343. AudioSource* newMasterSource = 0;
  18344. ScopedPointer <ResamplingAudioSource> oldResamplerSource (resamplerSource);
  18345. ScopedPointer <BufferingAudioSource> oldBufferingSource (bufferingSource);
  18346. AudioSource* oldMasterSource = masterSource;
  18347. if (newSource != 0)
  18348. {
  18349. newPositionableSource = newSource;
  18350. if (readAheadBufferSize_ > 0)
  18351. newPositionableSource = newBufferingSource
  18352. = new BufferingAudioSource (newPositionableSource, false, readAheadBufferSize_);
  18353. newPositionableSource->setNextReadPosition (0);
  18354. if (sourceSampleRateToCorrectFor != 0)
  18355. newMasterSource = newResamplerSource
  18356. = new ResamplingAudioSource (newPositionableSource, false);
  18357. else
  18358. newMasterSource = newPositionableSource;
  18359. if (isPrepared)
  18360. {
  18361. if (newResamplerSource != 0 && sourceSampleRate > 0 && sampleRate > 0)
  18362. newResamplerSource->setResamplingRatio (sourceSampleRate / sampleRate);
  18363. newMasterSource->prepareToPlay (blockSize, sampleRate);
  18364. }
  18365. }
  18366. {
  18367. const ScopedLock sl (callbackLock);
  18368. source = newSource;
  18369. resamplerSource = newResamplerSource;
  18370. bufferingSource = newBufferingSource;
  18371. masterSource = newMasterSource;
  18372. positionableSource = newPositionableSource;
  18373. playing = false;
  18374. }
  18375. if (oldMasterSource != 0)
  18376. oldMasterSource->releaseResources();
  18377. }
  18378. void AudioTransportSource::start()
  18379. {
  18380. if ((! playing) && masterSource != 0)
  18381. {
  18382. {
  18383. const ScopedLock sl (callbackLock);
  18384. playing = true;
  18385. stopped = false;
  18386. inputStreamEOF = false;
  18387. }
  18388. sendChangeMessage (this);
  18389. }
  18390. }
  18391. void AudioTransportSource::stop()
  18392. {
  18393. if (playing)
  18394. {
  18395. {
  18396. const ScopedLock sl (callbackLock);
  18397. playing = false;
  18398. }
  18399. int n = 500;
  18400. while (--n >= 0 && ! stopped)
  18401. Thread::sleep (2);
  18402. sendChangeMessage (this);
  18403. }
  18404. }
  18405. void AudioTransportSource::setPosition (double newPosition)
  18406. {
  18407. if (sampleRate > 0.0)
  18408. setNextReadPosition (roundToInt (newPosition * sampleRate));
  18409. }
  18410. double AudioTransportSource::getCurrentPosition() const
  18411. {
  18412. if (sampleRate > 0.0)
  18413. return getNextReadPosition() / sampleRate;
  18414. else
  18415. return 0.0;
  18416. }
  18417. void AudioTransportSource::setNextReadPosition (int newPosition)
  18418. {
  18419. if (positionableSource != 0)
  18420. {
  18421. if (sampleRate > 0 && sourceSampleRate > 0)
  18422. newPosition = roundToInt (newPosition * sourceSampleRate / sampleRate);
  18423. positionableSource->setNextReadPosition (newPosition);
  18424. }
  18425. }
  18426. int AudioTransportSource::getNextReadPosition() const
  18427. {
  18428. if (positionableSource != 0)
  18429. {
  18430. const double ratio = (sampleRate > 0 && sourceSampleRate > 0) ? sampleRate / sourceSampleRate : 1.0;
  18431. return roundToInt (positionableSource->getNextReadPosition() * ratio);
  18432. }
  18433. return 0;
  18434. }
  18435. int AudioTransportSource::getTotalLength() const
  18436. {
  18437. const ScopedLock sl (callbackLock);
  18438. if (positionableSource != 0)
  18439. {
  18440. const double ratio = (sampleRate > 0 && sourceSampleRate > 0) ? sampleRate / sourceSampleRate : 1.0;
  18441. return roundToInt (positionableSource->getTotalLength() * ratio);
  18442. }
  18443. return 0;
  18444. }
  18445. bool AudioTransportSource::isLooping() const
  18446. {
  18447. const ScopedLock sl (callbackLock);
  18448. return positionableSource != 0
  18449. && positionableSource->isLooping();
  18450. }
  18451. void AudioTransportSource::setGain (const float newGain) throw()
  18452. {
  18453. gain = newGain;
  18454. }
  18455. void AudioTransportSource::prepareToPlay (int samplesPerBlockExpected,
  18456. double sampleRate_)
  18457. {
  18458. const ScopedLock sl (callbackLock);
  18459. sampleRate = sampleRate_;
  18460. blockSize = samplesPerBlockExpected;
  18461. if (masterSource != 0)
  18462. masterSource->prepareToPlay (samplesPerBlockExpected, sampleRate);
  18463. if (resamplerSource != 0 && sourceSampleRate != 0)
  18464. resamplerSource->setResamplingRatio (sourceSampleRate / sampleRate);
  18465. isPrepared = true;
  18466. }
  18467. void AudioTransportSource::releaseResources()
  18468. {
  18469. const ScopedLock sl (callbackLock);
  18470. if (masterSource != 0)
  18471. masterSource->releaseResources();
  18472. isPrepared = false;
  18473. }
  18474. void AudioTransportSource::getNextAudioBlock (const AudioSourceChannelInfo& info)
  18475. {
  18476. const ScopedLock sl (callbackLock);
  18477. inputStreamEOF = false;
  18478. if (masterSource != 0 && ! stopped)
  18479. {
  18480. masterSource->getNextAudioBlock (info);
  18481. if (! playing)
  18482. {
  18483. // just stopped playing, so fade out the last block..
  18484. for (int i = info.buffer->getNumChannels(); --i >= 0;)
  18485. info.buffer->applyGainRamp (i, info.startSample, jmin (256, info.numSamples), 1.0f, 0.0f);
  18486. if (info.numSamples > 256)
  18487. info.buffer->clear (info.startSample + 256, info.numSamples - 256);
  18488. }
  18489. if (positionableSource->getNextReadPosition() > positionableSource->getTotalLength() + 1
  18490. && ! positionableSource->isLooping())
  18491. {
  18492. playing = false;
  18493. inputStreamEOF = true;
  18494. sendChangeMessage (this);
  18495. }
  18496. stopped = ! playing;
  18497. for (int i = info.buffer->getNumChannels(); --i >= 0;)
  18498. {
  18499. info.buffer->applyGainRamp (i, info.startSample, info.numSamples,
  18500. lastGain, gain);
  18501. }
  18502. }
  18503. else
  18504. {
  18505. info.clearActiveBufferRegion();
  18506. stopped = true;
  18507. }
  18508. lastGain = gain;
  18509. }
  18510. END_JUCE_NAMESPACE
  18511. /*** End of inlined file: juce_AudioTransportSource.cpp ***/
  18512. /*** Start of inlined file: juce_BufferingAudioSource.cpp ***/
  18513. BEGIN_JUCE_NAMESPACE
  18514. class SharedBufferingAudioSourceThread : public DeletedAtShutdown,
  18515. public Thread,
  18516. private Timer
  18517. {
  18518. public:
  18519. SharedBufferingAudioSourceThread()
  18520. : Thread ("Audio Buffer")
  18521. {
  18522. }
  18523. ~SharedBufferingAudioSourceThread()
  18524. {
  18525. stopThread (10000);
  18526. clearSingletonInstance();
  18527. }
  18528. juce_DeclareSingleton (SharedBufferingAudioSourceThread, false)
  18529. void addSource (BufferingAudioSource* source)
  18530. {
  18531. const ScopedLock sl (lock);
  18532. if (! sources.contains (source))
  18533. {
  18534. sources.add (source);
  18535. startThread();
  18536. stopTimer();
  18537. }
  18538. notify();
  18539. }
  18540. void removeSource (BufferingAudioSource* source)
  18541. {
  18542. const ScopedLock sl (lock);
  18543. sources.removeValue (source);
  18544. if (sources.size() == 0)
  18545. startTimer (5000);
  18546. }
  18547. private:
  18548. Array <BufferingAudioSource*> sources;
  18549. CriticalSection lock;
  18550. void run()
  18551. {
  18552. while (! threadShouldExit())
  18553. {
  18554. bool busy = false;
  18555. for (int i = sources.size(); --i >= 0;)
  18556. {
  18557. if (threadShouldExit())
  18558. return;
  18559. const ScopedLock sl (lock);
  18560. BufferingAudioSource* const b = sources[i];
  18561. if (b != 0 && b->readNextBufferChunk())
  18562. busy = true;
  18563. }
  18564. if (! busy)
  18565. wait (500);
  18566. }
  18567. }
  18568. void timerCallback()
  18569. {
  18570. stopTimer();
  18571. if (sources.size() == 0)
  18572. deleteInstance();
  18573. }
  18574. SharedBufferingAudioSourceThread (const SharedBufferingAudioSourceThread&);
  18575. SharedBufferingAudioSourceThread& operator= (const SharedBufferingAudioSourceThread&);
  18576. };
  18577. juce_ImplementSingleton (SharedBufferingAudioSourceThread)
  18578. BufferingAudioSource::BufferingAudioSource (PositionableAudioSource* source_,
  18579. const bool deleteSourceWhenDeleted_,
  18580. int numberOfSamplesToBuffer_)
  18581. : source (source_),
  18582. deleteSourceWhenDeleted (deleteSourceWhenDeleted_),
  18583. numberOfSamplesToBuffer (jmax (1024, numberOfSamplesToBuffer_)),
  18584. buffer (2, 0),
  18585. bufferValidStart (0),
  18586. bufferValidEnd (0),
  18587. nextPlayPos (0),
  18588. wasSourceLooping (false)
  18589. {
  18590. jassert (source_ != 0);
  18591. jassert (numberOfSamplesToBuffer_ > 1024); // not much point using this class if you're
  18592. // not using a larger buffer..
  18593. }
  18594. BufferingAudioSource::~BufferingAudioSource()
  18595. {
  18596. SharedBufferingAudioSourceThread* const thread = SharedBufferingAudioSourceThread::getInstanceWithoutCreating();
  18597. if (thread != 0)
  18598. thread->removeSource (this);
  18599. if (deleteSourceWhenDeleted)
  18600. delete source;
  18601. }
  18602. void BufferingAudioSource::prepareToPlay (int samplesPerBlockExpected, double sampleRate_)
  18603. {
  18604. source->prepareToPlay (samplesPerBlockExpected, sampleRate_);
  18605. sampleRate = sampleRate_;
  18606. buffer.setSize (2, jmax (samplesPerBlockExpected * 2, numberOfSamplesToBuffer));
  18607. buffer.clear();
  18608. bufferValidStart = 0;
  18609. bufferValidEnd = 0;
  18610. SharedBufferingAudioSourceThread::getInstance()->addSource (this);
  18611. while (bufferValidEnd - bufferValidStart < jmin (((int) sampleRate_) / 4,
  18612. buffer.getNumSamples() / 2))
  18613. {
  18614. SharedBufferingAudioSourceThread::getInstance()->notify();
  18615. Thread::sleep (5);
  18616. }
  18617. }
  18618. void BufferingAudioSource::releaseResources()
  18619. {
  18620. SharedBufferingAudioSourceThread* const thread = SharedBufferingAudioSourceThread::getInstanceWithoutCreating();
  18621. if (thread != 0)
  18622. thread->removeSource (this);
  18623. buffer.setSize (2, 0);
  18624. source->releaseResources();
  18625. }
  18626. void BufferingAudioSource::getNextAudioBlock (const AudioSourceChannelInfo& info)
  18627. {
  18628. const ScopedLock sl (bufferStartPosLock);
  18629. const int validStart = jlimit (bufferValidStart, bufferValidEnd, nextPlayPos) - nextPlayPos;
  18630. const int validEnd = jlimit (bufferValidStart, bufferValidEnd, nextPlayPos + info.numSamples) - nextPlayPos;
  18631. if (validStart == validEnd)
  18632. {
  18633. // total cache miss
  18634. info.clearActiveBufferRegion();
  18635. }
  18636. else
  18637. {
  18638. if (validStart > 0)
  18639. info.buffer->clear (info.startSample, validStart); // partial cache miss at start
  18640. if (validEnd < info.numSamples)
  18641. info.buffer->clear (info.startSample + validEnd,
  18642. info.numSamples - validEnd); // partial cache miss at end
  18643. if (validStart < validEnd)
  18644. {
  18645. for (int chan = jmin (2, info.buffer->getNumChannels()); --chan >= 0;)
  18646. {
  18647. const int startBufferIndex = (validStart + nextPlayPos) % buffer.getNumSamples();
  18648. const int endBufferIndex = (validEnd + nextPlayPos) % buffer.getNumSamples();
  18649. if (startBufferIndex < endBufferIndex)
  18650. {
  18651. info.buffer->copyFrom (chan, info.startSample + validStart,
  18652. buffer,
  18653. chan, startBufferIndex,
  18654. validEnd - validStart);
  18655. }
  18656. else
  18657. {
  18658. const int initialSize = buffer.getNumSamples() - startBufferIndex;
  18659. info.buffer->copyFrom (chan, info.startSample + validStart,
  18660. buffer,
  18661. chan, startBufferIndex,
  18662. initialSize);
  18663. info.buffer->copyFrom (chan, info.startSample + validStart + initialSize,
  18664. buffer,
  18665. chan, 0,
  18666. (validEnd - validStart) - initialSize);
  18667. }
  18668. }
  18669. }
  18670. nextPlayPos += info.numSamples;
  18671. if (source->isLooping() && nextPlayPos > 0)
  18672. nextPlayPos %= source->getTotalLength();
  18673. }
  18674. SharedBufferingAudioSourceThread* const thread = SharedBufferingAudioSourceThread::getInstanceWithoutCreating();
  18675. if (thread != 0)
  18676. thread->notify();
  18677. }
  18678. int BufferingAudioSource::getNextReadPosition() const
  18679. {
  18680. return (source->isLooping() && nextPlayPos > 0)
  18681. ? nextPlayPos % source->getTotalLength()
  18682. : nextPlayPos;
  18683. }
  18684. void BufferingAudioSource::setNextReadPosition (int newPosition)
  18685. {
  18686. const ScopedLock sl (bufferStartPosLock);
  18687. nextPlayPos = newPosition;
  18688. SharedBufferingAudioSourceThread* const thread = SharedBufferingAudioSourceThread::getInstanceWithoutCreating();
  18689. if (thread != 0)
  18690. thread->notify();
  18691. }
  18692. bool BufferingAudioSource::readNextBufferChunk()
  18693. {
  18694. int newBVS, newBVE, sectionToReadStart, sectionToReadEnd;
  18695. {
  18696. const ScopedLock sl (bufferStartPosLock);
  18697. if (wasSourceLooping != isLooping())
  18698. {
  18699. wasSourceLooping = isLooping();
  18700. bufferValidStart = 0;
  18701. bufferValidEnd = 0;
  18702. }
  18703. newBVS = jmax (0, nextPlayPos);
  18704. newBVE = newBVS + buffer.getNumSamples() - 4;
  18705. sectionToReadStart = 0;
  18706. sectionToReadEnd = 0;
  18707. const int maxChunkSize = 2048;
  18708. if (newBVS < bufferValidStart || newBVS >= bufferValidEnd)
  18709. {
  18710. newBVE = jmin (newBVE, newBVS + maxChunkSize);
  18711. sectionToReadStart = newBVS;
  18712. sectionToReadEnd = newBVE;
  18713. bufferValidStart = 0;
  18714. bufferValidEnd = 0;
  18715. }
  18716. else if (abs (newBVS - bufferValidStart) > 512
  18717. || abs (newBVE - bufferValidEnd) > 512)
  18718. {
  18719. newBVE = jmin (newBVE, bufferValidEnd + maxChunkSize);
  18720. sectionToReadStart = bufferValidEnd;
  18721. sectionToReadEnd = newBVE;
  18722. bufferValidStart = newBVS;
  18723. bufferValidEnd = jmin (bufferValidEnd, newBVE);
  18724. }
  18725. }
  18726. if (sectionToReadStart != sectionToReadEnd)
  18727. {
  18728. const int bufferIndexStart = sectionToReadStart % buffer.getNumSamples();
  18729. const int bufferIndexEnd = sectionToReadEnd % buffer.getNumSamples();
  18730. if (bufferIndexStart < bufferIndexEnd)
  18731. {
  18732. readBufferSection (sectionToReadStart,
  18733. sectionToReadEnd - sectionToReadStart,
  18734. bufferIndexStart);
  18735. }
  18736. else
  18737. {
  18738. const int initialSize = buffer.getNumSamples() - bufferIndexStart;
  18739. readBufferSection (sectionToReadStart,
  18740. initialSize,
  18741. bufferIndexStart);
  18742. readBufferSection (sectionToReadStart + initialSize,
  18743. (sectionToReadEnd - sectionToReadStart) - initialSize,
  18744. 0);
  18745. }
  18746. const ScopedLock sl2 (bufferStartPosLock);
  18747. bufferValidStart = newBVS;
  18748. bufferValidEnd = newBVE;
  18749. return true;
  18750. }
  18751. else
  18752. {
  18753. return false;
  18754. }
  18755. }
  18756. void BufferingAudioSource::readBufferSection (int start, int length, int bufferOffset)
  18757. {
  18758. if (source->getNextReadPosition() != start)
  18759. source->setNextReadPosition (start);
  18760. AudioSourceChannelInfo info;
  18761. info.buffer = &buffer;
  18762. info.startSample = bufferOffset;
  18763. info.numSamples = length;
  18764. source->getNextAudioBlock (info);
  18765. }
  18766. END_JUCE_NAMESPACE
  18767. /*** End of inlined file: juce_BufferingAudioSource.cpp ***/
  18768. /*** Start of inlined file: juce_ChannelRemappingAudioSource.cpp ***/
  18769. BEGIN_JUCE_NAMESPACE
  18770. ChannelRemappingAudioSource::ChannelRemappingAudioSource (AudioSource* const source_,
  18771. const bool deleteSourceWhenDeleted_)
  18772. : requiredNumberOfChannels (2),
  18773. source (source_),
  18774. deleteSourceWhenDeleted (deleteSourceWhenDeleted_),
  18775. buffer (2, 16)
  18776. {
  18777. remappedInfo.buffer = &buffer;
  18778. remappedInfo.startSample = 0;
  18779. }
  18780. ChannelRemappingAudioSource::~ChannelRemappingAudioSource()
  18781. {
  18782. if (deleteSourceWhenDeleted)
  18783. delete source;
  18784. }
  18785. void ChannelRemappingAudioSource::setNumberOfChannelsToProduce (const int requiredNumberOfChannels_) throw()
  18786. {
  18787. const ScopedLock sl (lock);
  18788. requiredNumberOfChannels = requiredNumberOfChannels_;
  18789. }
  18790. void ChannelRemappingAudioSource::clearAllMappings() throw()
  18791. {
  18792. const ScopedLock sl (lock);
  18793. remappedInputs.clear();
  18794. remappedOutputs.clear();
  18795. }
  18796. void ChannelRemappingAudioSource::setInputChannelMapping (const int destIndex, const int sourceIndex) throw()
  18797. {
  18798. const ScopedLock sl (lock);
  18799. while (remappedInputs.size() < destIndex)
  18800. remappedInputs.add (-1);
  18801. remappedInputs.set (destIndex, sourceIndex);
  18802. }
  18803. void ChannelRemappingAudioSource::setOutputChannelMapping (const int sourceIndex, const int destIndex) throw()
  18804. {
  18805. const ScopedLock sl (lock);
  18806. while (remappedOutputs.size() < sourceIndex)
  18807. remappedOutputs.add (-1);
  18808. remappedOutputs.set (sourceIndex, destIndex);
  18809. }
  18810. int ChannelRemappingAudioSource::getRemappedInputChannel (const int inputChannelIndex) const throw()
  18811. {
  18812. const ScopedLock sl (lock);
  18813. if (inputChannelIndex >= 0 && inputChannelIndex < remappedInputs.size())
  18814. return remappedInputs.getUnchecked (inputChannelIndex);
  18815. return -1;
  18816. }
  18817. int ChannelRemappingAudioSource::getRemappedOutputChannel (const int outputChannelIndex) const throw()
  18818. {
  18819. const ScopedLock sl (lock);
  18820. if (outputChannelIndex >= 0 && outputChannelIndex < remappedOutputs.size())
  18821. return remappedOutputs .getUnchecked (outputChannelIndex);
  18822. return -1;
  18823. }
  18824. void ChannelRemappingAudioSource::prepareToPlay (int samplesPerBlockExpected, double sampleRate)
  18825. {
  18826. source->prepareToPlay (samplesPerBlockExpected, sampleRate);
  18827. }
  18828. void ChannelRemappingAudioSource::releaseResources()
  18829. {
  18830. source->releaseResources();
  18831. }
  18832. void ChannelRemappingAudioSource::getNextAudioBlock (const AudioSourceChannelInfo& bufferToFill)
  18833. {
  18834. const ScopedLock sl (lock);
  18835. buffer.setSize (requiredNumberOfChannels, bufferToFill.numSamples, false, false, true);
  18836. const int numChans = bufferToFill.buffer->getNumChannels();
  18837. int i;
  18838. for (i = 0; i < buffer.getNumChannels(); ++i)
  18839. {
  18840. const int remappedChan = getRemappedInputChannel (i);
  18841. if (remappedChan >= 0 && remappedChan < numChans)
  18842. {
  18843. buffer.copyFrom (i, 0, *bufferToFill.buffer,
  18844. remappedChan,
  18845. bufferToFill.startSample,
  18846. bufferToFill.numSamples);
  18847. }
  18848. else
  18849. {
  18850. buffer.clear (i, 0, bufferToFill.numSamples);
  18851. }
  18852. }
  18853. remappedInfo.numSamples = bufferToFill.numSamples;
  18854. source->getNextAudioBlock (remappedInfo);
  18855. bufferToFill.clearActiveBufferRegion();
  18856. for (i = 0; i < requiredNumberOfChannels; ++i)
  18857. {
  18858. const int remappedChan = getRemappedOutputChannel (i);
  18859. if (remappedChan >= 0 && remappedChan < numChans)
  18860. {
  18861. bufferToFill.buffer->addFrom (remappedChan, bufferToFill.startSample,
  18862. buffer, i, 0, bufferToFill.numSamples);
  18863. }
  18864. }
  18865. }
  18866. XmlElement* ChannelRemappingAudioSource::createXml() const throw()
  18867. {
  18868. XmlElement* e = new XmlElement ("MAPPINGS");
  18869. String ins, outs;
  18870. int i;
  18871. const ScopedLock sl (lock);
  18872. for (i = 0; i < remappedInputs.size(); ++i)
  18873. ins << remappedInputs.getUnchecked(i) << ' ';
  18874. for (i = 0; i < remappedOutputs.size(); ++i)
  18875. outs << remappedOutputs.getUnchecked(i) << ' ';
  18876. e->setAttribute ("inputs", ins.trimEnd());
  18877. e->setAttribute ("outputs", outs.trimEnd());
  18878. return e;
  18879. }
  18880. void ChannelRemappingAudioSource::restoreFromXml (const XmlElement& e) throw()
  18881. {
  18882. if (e.hasTagName ("MAPPINGS"))
  18883. {
  18884. const ScopedLock sl (lock);
  18885. clearAllMappings();
  18886. StringArray ins, outs;
  18887. ins.addTokens (e.getStringAttribute ("inputs"), false);
  18888. outs.addTokens (e.getStringAttribute ("outputs"), false);
  18889. int i;
  18890. for (i = 0; i < ins.size(); ++i)
  18891. remappedInputs.add (ins[i].getIntValue());
  18892. for (i = 0; i < outs.size(); ++i)
  18893. remappedOutputs.add (outs[i].getIntValue());
  18894. }
  18895. }
  18896. END_JUCE_NAMESPACE
  18897. /*** End of inlined file: juce_ChannelRemappingAudioSource.cpp ***/
  18898. /*** Start of inlined file: juce_IIRFilterAudioSource.cpp ***/
  18899. BEGIN_JUCE_NAMESPACE
  18900. IIRFilterAudioSource::IIRFilterAudioSource (AudioSource* const inputSource,
  18901. const bool deleteInputWhenDeleted_)
  18902. : input (inputSource),
  18903. deleteInputWhenDeleted (deleteInputWhenDeleted_)
  18904. {
  18905. jassert (inputSource != 0);
  18906. for (int i = 2; --i >= 0;)
  18907. iirFilters.add (new IIRFilter());
  18908. }
  18909. IIRFilterAudioSource::~IIRFilterAudioSource()
  18910. {
  18911. if (deleteInputWhenDeleted)
  18912. delete input;
  18913. }
  18914. void IIRFilterAudioSource::setFilterParameters (const IIRFilter& newSettings)
  18915. {
  18916. for (int i = iirFilters.size(); --i >= 0;)
  18917. iirFilters.getUnchecked(i)->copyCoefficientsFrom (newSettings);
  18918. }
  18919. void IIRFilterAudioSource::prepareToPlay (int samplesPerBlockExpected, double sampleRate)
  18920. {
  18921. input->prepareToPlay (samplesPerBlockExpected, sampleRate);
  18922. for (int i = iirFilters.size(); --i >= 0;)
  18923. iirFilters.getUnchecked(i)->reset();
  18924. }
  18925. void IIRFilterAudioSource::releaseResources()
  18926. {
  18927. input->releaseResources();
  18928. }
  18929. void IIRFilterAudioSource::getNextAudioBlock (const AudioSourceChannelInfo& bufferToFill)
  18930. {
  18931. input->getNextAudioBlock (bufferToFill);
  18932. const int numChannels = bufferToFill.buffer->getNumChannels();
  18933. while (numChannels > iirFilters.size())
  18934. iirFilters.add (new IIRFilter (*iirFilters.getUnchecked (0)));
  18935. for (int i = 0; i < numChannels; ++i)
  18936. iirFilters.getUnchecked(i)
  18937. ->processSamples (bufferToFill.buffer->getSampleData (i, bufferToFill.startSample),
  18938. bufferToFill.numSamples);
  18939. }
  18940. END_JUCE_NAMESPACE
  18941. /*** End of inlined file: juce_IIRFilterAudioSource.cpp ***/
  18942. /*** Start of inlined file: juce_MixerAudioSource.cpp ***/
  18943. BEGIN_JUCE_NAMESPACE
  18944. MixerAudioSource::MixerAudioSource()
  18945. : tempBuffer (2, 0),
  18946. currentSampleRate (0.0),
  18947. bufferSizeExpected (0)
  18948. {
  18949. }
  18950. MixerAudioSource::~MixerAudioSource()
  18951. {
  18952. removeAllInputs();
  18953. }
  18954. void MixerAudioSource::addInputSource (AudioSource* input, const bool deleteWhenRemoved)
  18955. {
  18956. if (input != 0 && ! inputs.contains (input))
  18957. {
  18958. double localRate;
  18959. int localBufferSize;
  18960. {
  18961. const ScopedLock sl (lock);
  18962. localRate = currentSampleRate;
  18963. localBufferSize = bufferSizeExpected;
  18964. }
  18965. if (localRate != 0.0)
  18966. input->prepareToPlay (localBufferSize, localRate);
  18967. const ScopedLock sl (lock);
  18968. inputsToDelete.setBit (inputs.size(), deleteWhenRemoved);
  18969. inputs.add (input);
  18970. }
  18971. }
  18972. void MixerAudioSource::removeInputSource (AudioSource* input, const bool deleteInput)
  18973. {
  18974. if (input != 0)
  18975. {
  18976. int index;
  18977. {
  18978. const ScopedLock sl (lock);
  18979. index = inputs.indexOf (input);
  18980. if (index >= 0)
  18981. {
  18982. inputsToDelete.shiftBits (index, 1);
  18983. inputs.remove (index);
  18984. }
  18985. }
  18986. if (index >= 0)
  18987. {
  18988. input->releaseResources();
  18989. if (deleteInput)
  18990. delete input;
  18991. }
  18992. }
  18993. }
  18994. void MixerAudioSource::removeAllInputs()
  18995. {
  18996. VoidArray inputsCopy;
  18997. BigInteger inputsToDeleteCopy;
  18998. {
  18999. const ScopedLock sl (lock);
  19000. inputsCopy = inputs;
  19001. inputsToDeleteCopy = inputsToDelete;
  19002. }
  19003. for (int i = inputsCopy.size(); --i >= 0;)
  19004. if (inputsToDeleteCopy[i])
  19005. delete (AudioSource*) inputsCopy[i];
  19006. }
  19007. void MixerAudioSource::prepareToPlay (int samplesPerBlockExpected, double sampleRate)
  19008. {
  19009. tempBuffer.setSize (2, samplesPerBlockExpected);
  19010. const ScopedLock sl (lock);
  19011. currentSampleRate = sampleRate;
  19012. bufferSizeExpected = samplesPerBlockExpected;
  19013. for (int i = inputs.size(); --i >= 0;)
  19014. ((AudioSource*) inputs.getUnchecked(i))->prepareToPlay (samplesPerBlockExpected,
  19015. sampleRate);
  19016. }
  19017. void MixerAudioSource::releaseResources()
  19018. {
  19019. const ScopedLock sl (lock);
  19020. for (int i = inputs.size(); --i >= 0;)
  19021. ((AudioSource*) inputs.getUnchecked(i))->releaseResources();
  19022. tempBuffer.setSize (2, 0);
  19023. currentSampleRate = 0;
  19024. bufferSizeExpected = 0;
  19025. }
  19026. void MixerAudioSource::getNextAudioBlock (const AudioSourceChannelInfo& info)
  19027. {
  19028. const ScopedLock sl (lock);
  19029. if (inputs.size() > 0)
  19030. {
  19031. ((AudioSource*) inputs.getUnchecked(0))->getNextAudioBlock (info);
  19032. if (inputs.size() > 1)
  19033. {
  19034. tempBuffer.setSize (jmax (1, info.buffer->getNumChannels()),
  19035. info.buffer->getNumSamples());
  19036. AudioSourceChannelInfo info2;
  19037. info2.buffer = &tempBuffer;
  19038. info2.numSamples = info.numSamples;
  19039. info2.startSample = 0;
  19040. for (int i = 1; i < inputs.size(); ++i)
  19041. {
  19042. ((AudioSource*) inputs.getUnchecked(i))->getNextAudioBlock (info2);
  19043. for (int chan = 0; chan < info.buffer->getNumChannels(); ++chan)
  19044. info.buffer->addFrom (chan, info.startSample, tempBuffer, chan, 0, info.numSamples);
  19045. }
  19046. }
  19047. }
  19048. else
  19049. {
  19050. info.clearActiveBufferRegion();
  19051. }
  19052. }
  19053. END_JUCE_NAMESPACE
  19054. /*** End of inlined file: juce_MixerAudioSource.cpp ***/
  19055. /*** Start of inlined file: juce_ResamplingAudioSource.cpp ***/
  19056. BEGIN_JUCE_NAMESPACE
  19057. ResamplingAudioSource::ResamplingAudioSource (AudioSource* const inputSource,
  19058. const bool deleteInputWhenDeleted_)
  19059. : input (inputSource),
  19060. deleteInputWhenDeleted (deleteInputWhenDeleted_),
  19061. ratio (1.0),
  19062. lastRatio (1.0),
  19063. buffer (2, 0),
  19064. sampsInBuffer (0)
  19065. {
  19066. jassert (input != 0);
  19067. }
  19068. ResamplingAudioSource::~ResamplingAudioSource()
  19069. {
  19070. if (deleteInputWhenDeleted)
  19071. delete input;
  19072. }
  19073. void ResamplingAudioSource::setResamplingRatio (const double samplesInPerOutputSample)
  19074. {
  19075. jassert (samplesInPerOutputSample > 0);
  19076. const ScopedLock sl (ratioLock);
  19077. ratio = jmax (0.0, samplesInPerOutputSample);
  19078. }
  19079. void ResamplingAudioSource::prepareToPlay (int samplesPerBlockExpected,
  19080. double sampleRate)
  19081. {
  19082. const ScopedLock sl (ratioLock);
  19083. input->prepareToPlay (samplesPerBlockExpected, sampleRate);
  19084. buffer.setSize (2, roundToInt (samplesPerBlockExpected * ratio) + 32);
  19085. buffer.clear();
  19086. sampsInBuffer = 0;
  19087. bufferPos = 0;
  19088. subSampleOffset = 0.0;
  19089. createLowPass (ratio);
  19090. resetFilters();
  19091. }
  19092. void ResamplingAudioSource::releaseResources()
  19093. {
  19094. input->releaseResources();
  19095. buffer.setSize (2, 0);
  19096. }
  19097. void ResamplingAudioSource::getNextAudioBlock (const AudioSourceChannelInfo& info)
  19098. {
  19099. const ScopedLock sl (ratioLock);
  19100. if (lastRatio != ratio)
  19101. {
  19102. createLowPass (ratio);
  19103. lastRatio = ratio;
  19104. }
  19105. const int sampsNeeded = roundToInt (info.numSamples * ratio) + 2;
  19106. int bufferSize = buffer.getNumSamples();
  19107. if (bufferSize < sampsNeeded + 8)
  19108. {
  19109. bufferPos %= bufferSize;
  19110. bufferSize = sampsNeeded + 32;
  19111. buffer.setSize (buffer.getNumChannels(), bufferSize, true, true);
  19112. }
  19113. bufferPos %= bufferSize;
  19114. int endOfBufferPos = bufferPos + sampsInBuffer;
  19115. while (sampsNeeded > sampsInBuffer)
  19116. {
  19117. endOfBufferPos %= bufferSize;
  19118. int numToDo = jmin (sampsNeeded - sampsInBuffer,
  19119. bufferSize - endOfBufferPos);
  19120. AudioSourceChannelInfo readInfo;
  19121. readInfo.buffer = &buffer;
  19122. readInfo.numSamples = numToDo;
  19123. readInfo.startSample = endOfBufferPos;
  19124. input->getNextAudioBlock (readInfo);
  19125. if (ratio > 1.0001)
  19126. {
  19127. // for down-sampling, pre-apply the filter..
  19128. for (int i = jmin (2, info.buffer->getNumChannels()); --i >= 0;)
  19129. applyFilter (buffer.getSampleData (i, endOfBufferPos), numToDo, filterStates[i]);
  19130. }
  19131. sampsInBuffer += numToDo;
  19132. endOfBufferPos += numToDo;
  19133. }
  19134. float* dl = info.buffer->getSampleData (0, info.startSample);
  19135. float* dr = (info.buffer->getNumChannels() > 1) ? info.buffer->getSampleData (1, info.startSample) : 0;
  19136. const float* const bl = buffer.getSampleData (0, 0);
  19137. const float* const br = buffer.getSampleData (1, 0);
  19138. int nextPos = (bufferPos + 1) % bufferSize;
  19139. for (int m = info.numSamples; --m >= 0;)
  19140. {
  19141. const float alpha = (float) subSampleOffset;
  19142. const float invAlpha = 1.0f - alpha;
  19143. *dl++ = bl [bufferPos] * invAlpha + bl [nextPos] * alpha;
  19144. if (dr != 0)
  19145. *dr++ = br [bufferPos] * invAlpha + br [nextPos] * alpha;
  19146. subSampleOffset += ratio;
  19147. jassert (sampsInBuffer > 0);
  19148. while (subSampleOffset >= 1.0)
  19149. {
  19150. if (++bufferPos >= bufferSize)
  19151. bufferPos = 0;
  19152. --sampsInBuffer;
  19153. nextPos = (bufferPos + 1) % bufferSize;
  19154. subSampleOffset -= 1.0;
  19155. }
  19156. }
  19157. if (ratio < 0.9999)
  19158. {
  19159. // for up-sampling, apply the filter after transposing..
  19160. for (int i = jmin (2, info.buffer->getNumChannels()); --i >= 0;)
  19161. applyFilter (info.buffer->getSampleData (i, info.startSample), info.numSamples, filterStates[i]);
  19162. }
  19163. else if (ratio <= 1.0001)
  19164. {
  19165. // if the filter's not currently being applied, keep it stoked with the last couple of samples to avoid discontinuities
  19166. for (int i = jmin (2, info.buffer->getNumChannels()); --i >= 0;)
  19167. {
  19168. const float* const endOfBuffer = info.buffer->getSampleData (i, info.startSample + info.numSamples - 1);
  19169. FilterState& fs = filterStates[i];
  19170. if (info.numSamples > 1)
  19171. {
  19172. fs.y2 = fs.x2 = *(endOfBuffer - 1);
  19173. }
  19174. else
  19175. {
  19176. fs.y2 = fs.y1;
  19177. fs.x2 = fs.x1;
  19178. }
  19179. fs.y1 = fs.x1 = *endOfBuffer;
  19180. }
  19181. }
  19182. jassert (sampsInBuffer >= 0);
  19183. }
  19184. void ResamplingAudioSource::createLowPass (const double frequencyRatio)
  19185. {
  19186. const double proportionalRate = (frequencyRatio > 1.0) ? 0.5 / frequencyRatio
  19187. : 0.5 * frequencyRatio;
  19188. const double n = 1.0 / tan (double_Pi * jmax (0.001, proportionalRate));
  19189. const double nSquared = n * n;
  19190. const double c1 = 1.0 / (1.0 + sqrt (2.0) * n + nSquared);
  19191. setFilterCoefficients (c1,
  19192. c1 * 2.0f,
  19193. c1,
  19194. 1.0,
  19195. c1 * 2.0 * (1.0 - nSquared),
  19196. c1 * (1.0 - sqrt (2.0) * n + nSquared));
  19197. }
  19198. void ResamplingAudioSource::setFilterCoefficients (double c1, double c2, double c3, double c4, double c5, double c6)
  19199. {
  19200. const double a = 1.0 / c4;
  19201. c1 *= a;
  19202. c2 *= a;
  19203. c3 *= a;
  19204. c5 *= a;
  19205. c6 *= a;
  19206. coefficients[0] = c1;
  19207. coefficients[1] = c2;
  19208. coefficients[2] = c3;
  19209. coefficients[3] = c4;
  19210. coefficients[4] = c5;
  19211. coefficients[5] = c6;
  19212. }
  19213. void ResamplingAudioSource::resetFilters()
  19214. {
  19215. zeromem (filterStates, sizeof (filterStates));
  19216. }
  19217. void ResamplingAudioSource::applyFilter (float* samples, int num, FilterState& fs)
  19218. {
  19219. while (--num >= 0)
  19220. {
  19221. const double in = *samples;
  19222. double out = coefficients[0] * in
  19223. + coefficients[1] * fs.x1
  19224. + coefficients[2] * fs.x2
  19225. - coefficients[4] * fs.y1
  19226. - coefficients[5] * fs.y2;
  19227. #if JUCE_INTEL
  19228. if (! (out < -1.0e-8 || out > 1.0e-8))
  19229. out = 0;
  19230. #endif
  19231. fs.x2 = fs.x1;
  19232. fs.x1 = in;
  19233. fs.y2 = fs.y1;
  19234. fs.y1 = out;
  19235. *samples++ = (float) out;
  19236. }
  19237. }
  19238. END_JUCE_NAMESPACE
  19239. /*** End of inlined file: juce_ResamplingAudioSource.cpp ***/
  19240. /*** Start of inlined file: juce_ToneGeneratorAudioSource.cpp ***/
  19241. BEGIN_JUCE_NAMESPACE
  19242. ToneGeneratorAudioSource::ToneGeneratorAudioSource()
  19243. : frequency (1000.0),
  19244. sampleRate (44100.0),
  19245. currentPhase (0.0),
  19246. phasePerSample (0.0),
  19247. amplitude (0.5f)
  19248. {
  19249. }
  19250. ToneGeneratorAudioSource::~ToneGeneratorAudioSource()
  19251. {
  19252. }
  19253. void ToneGeneratorAudioSource::setAmplitude (const float newAmplitude)
  19254. {
  19255. amplitude = newAmplitude;
  19256. }
  19257. void ToneGeneratorAudioSource::setFrequency (const double newFrequencyHz)
  19258. {
  19259. frequency = newFrequencyHz;
  19260. phasePerSample = 0.0;
  19261. }
  19262. void ToneGeneratorAudioSource::prepareToPlay (int /*samplesPerBlockExpected*/,
  19263. double sampleRate_)
  19264. {
  19265. currentPhase = 0.0;
  19266. phasePerSample = 0.0;
  19267. sampleRate = sampleRate_;
  19268. }
  19269. void ToneGeneratorAudioSource::releaseResources()
  19270. {
  19271. }
  19272. void ToneGeneratorAudioSource::getNextAudioBlock (const AudioSourceChannelInfo& info)
  19273. {
  19274. if (phasePerSample == 0.0)
  19275. phasePerSample = double_Pi * 2.0 / (sampleRate / frequency);
  19276. for (int i = 0; i < info.numSamples; ++i)
  19277. {
  19278. const float sample = amplitude * (float) sin (currentPhase);
  19279. currentPhase += phasePerSample;
  19280. for (int j = info.buffer->getNumChannels(); --j >= 0;)
  19281. *info.buffer->getSampleData (j, info.startSample + i) = sample;
  19282. }
  19283. }
  19284. END_JUCE_NAMESPACE
  19285. /*** End of inlined file: juce_ToneGeneratorAudioSource.cpp ***/
  19286. /*** Start of inlined file: juce_AudioDeviceManager.cpp ***/
  19287. BEGIN_JUCE_NAMESPACE
  19288. AudioDeviceManager::AudioDeviceSetup::AudioDeviceSetup()
  19289. : sampleRate (0),
  19290. bufferSize (0),
  19291. useDefaultInputChannels (true),
  19292. useDefaultOutputChannels (true)
  19293. {
  19294. }
  19295. bool AudioDeviceManager::AudioDeviceSetup::operator== (const AudioDeviceManager::AudioDeviceSetup& other) const
  19296. {
  19297. return outputDeviceName == other.outputDeviceName
  19298. && inputDeviceName == other.inputDeviceName
  19299. && sampleRate == other.sampleRate
  19300. && bufferSize == other.bufferSize
  19301. && inputChannels == other.inputChannels
  19302. && useDefaultInputChannels == other.useDefaultInputChannels
  19303. && outputChannels == other.outputChannels
  19304. && useDefaultOutputChannels == other.useDefaultOutputChannels;
  19305. }
  19306. AudioDeviceManager::AudioDeviceManager()
  19307. : currentAudioDevice (0),
  19308. numInputChansNeeded (0),
  19309. numOutputChansNeeded (2),
  19310. listNeedsScanning (true),
  19311. useInputNames (false),
  19312. inputLevelMeasurementEnabledCount (0),
  19313. inputLevel (0),
  19314. tempBuffer (2, 2),
  19315. defaultMidiOutput (0),
  19316. cpuUsageMs (0),
  19317. timeToCpuScale (0)
  19318. {
  19319. callbackHandler.owner = this;
  19320. }
  19321. AudioDeviceManager::~AudioDeviceManager()
  19322. {
  19323. currentAudioDevice = 0;
  19324. defaultMidiOutput = 0;
  19325. }
  19326. void AudioDeviceManager::createDeviceTypesIfNeeded()
  19327. {
  19328. if (availableDeviceTypes.size() == 0)
  19329. {
  19330. createAudioDeviceTypes (availableDeviceTypes);
  19331. while (lastDeviceTypeConfigs.size() < availableDeviceTypes.size())
  19332. lastDeviceTypeConfigs.add (new AudioDeviceSetup());
  19333. if (availableDeviceTypes.size() > 0)
  19334. currentDeviceType = availableDeviceTypes.getUnchecked(0)->getTypeName();
  19335. }
  19336. }
  19337. const OwnedArray <AudioIODeviceType>& AudioDeviceManager::getAvailableDeviceTypes()
  19338. {
  19339. scanDevicesIfNeeded();
  19340. return availableDeviceTypes;
  19341. }
  19342. AudioIODeviceType* juce_createAudioIODeviceType_CoreAudio();
  19343. AudioIODeviceType* juce_createAudioIODeviceType_iPhoneAudio();
  19344. AudioIODeviceType* juce_createAudioIODeviceType_WASAPI();
  19345. AudioIODeviceType* juce_createAudioIODeviceType_DirectSound();
  19346. AudioIODeviceType* juce_createAudioIODeviceType_ASIO();
  19347. AudioIODeviceType* juce_createAudioIODeviceType_ALSA();
  19348. AudioIODeviceType* juce_createAudioIODeviceType_JACK();
  19349. void AudioDeviceManager::createAudioDeviceTypes (OwnedArray <AudioIODeviceType>& list)
  19350. {
  19351. (void) list; // (to avoid 'unused param' warnings)
  19352. #if JUCE_WINDOWS
  19353. #if JUCE_WASAPI
  19354. if (SystemStats::getOperatingSystemType() >= SystemStats::WinVista)
  19355. list.add (juce_createAudioIODeviceType_WASAPI());
  19356. #endif
  19357. #if JUCE_DIRECTSOUND
  19358. list.add (juce_createAudioIODeviceType_DirectSound());
  19359. #endif
  19360. #if JUCE_ASIO
  19361. list.add (juce_createAudioIODeviceType_ASIO());
  19362. #endif
  19363. #endif
  19364. #if JUCE_MAC
  19365. list.add (juce_createAudioIODeviceType_CoreAudio());
  19366. #endif
  19367. #if JUCE_IPHONE
  19368. list.add (juce_createAudioIODeviceType_iPhoneAudio());
  19369. #endif
  19370. #if JUCE_LINUX && JUCE_ALSA
  19371. list.add (juce_createAudioIODeviceType_ALSA());
  19372. #endif
  19373. #if JUCE_LINUX && JUCE_JACK
  19374. list.add (juce_createAudioIODeviceType_JACK());
  19375. #endif
  19376. }
  19377. const String AudioDeviceManager::initialise (const int numInputChannelsNeeded,
  19378. const int numOutputChannelsNeeded,
  19379. const XmlElement* const e,
  19380. const bool selectDefaultDeviceOnFailure,
  19381. const String& preferredDefaultDeviceName,
  19382. const AudioDeviceSetup* preferredSetupOptions)
  19383. {
  19384. scanDevicesIfNeeded();
  19385. numInputChansNeeded = numInputChannelsNeeded;
  19386. numOutputChansNeeded = numOutputChannelsNeeded;
  19387. if (e != 0 && e->hasTagName ("DEVICESETUP"))
  19388. {
  19389. lastExplicitSettings = new XmlElement (*e);
  19390. String error;
  19391. AudioDeviceSetup setup;
  19392. if (preferredSetupOptions != 0)
  19393. setup = *preferredSetupOptions;
  19394. if (e->getStringAttribute ("audioDeviceName").isNotEmpty())
  19395. {
  19396. setup.inputDeviceName = setup.outputDeviceName
  19397. = e->getStringAttribute ("audioDeviceName");
  19398. }
  19399. else
  19400. {
  19401. setup.inputDeviceName = e->getStringAttribute ("audioInputDeviceName");
  19402. setup.outputDeviceName = e->getStringAttribute ("audioOutputDeviceName");
  19403. }
  19404. currentDeviceType = e->getStringAttribute ("deviceType");
  19405. if (currentDeviceType.isEmpty())
  19406. {
  19407. AudioIODeviceType* const type = findType (setup.inputDeviceName, setup.outputDeviceName);
  19408. if (type != 0)
  19409. currentDeviceType = type->getTypeName();
  19410. else if (availableDeviceTypes.size() > 0)
  19411. currentDeviceType = availableDeviceTypes[0]->getTypeName();
  19412. }
  19413. setup.bufferSize = e->getIntAttribute ("audioDeviceBufferSize");
  19414. setup.sampleRate = e->getDoubleAttribute ("audioDeviceRate");
  19415. setup.inputChannels.parseString (e->getStringAttribute ("audioDeviceInChans", "11"), 2);
  19416. setup.outputChannels.parseString (e->getStringAttribute ("audioDeviceOutChans", "11"), 2);
  19417. setup.useDefaultInputChannels = ! e->hasAttribute ("audioDeviceInChans");
  19418. setup.useDefaultOutputChannels = ! e->hasAttribute ("audioDeviceOutChans");
  19419. error = setAudioDeviceSetup (setup, true);
  19420. midiInsFromXml.clear();
  19421. forEachXmlChildElementWithTagName (*e, c, "MIDIINPUT")
  19422. midiInsFromXml.add (c->getStringAttribute ("name"));
  19423. const StringArray allMidiIns (MidiInput::getDevices());
  19424. for (int i = allMidiIns.size(); --i >= 0;)
  19425. setMidiInputEnabled (allMidiIns[i], midiInsFromXml.contains (allMidiIns[i]));
  19426. if (error.isNotEmpty() && selectDefaultDeviceOnFailure)
  19427. error = initialise (numInputChannelsNeeded, numOutputChannelsNeeded, 0,
  19428. false, preferredDefaultDeviceName);
  19429. setDefaultMidiOutput (e->getStringAttribute ("defaultMidiOutput"));
  19430. return error;
  19431. }
  19432. else
  19433. {
  19434. AudioDeviceSetup setup;
  19435. if (preferredSetupOptions != 0)
  19436. {
  19437. setup = *preferredSetupOptions;
  19438. }
  19439. else if (preferredDefaultDeviceName.isNotEmpty())
  19440. {
  19441. for (int j = availableDeviceTypes.size(); --j >= 0;)
  19442. {
  19443. AudioIODeviceType* const type = availableDeviceTypes.getUnchecked(j);
  19444. StringArray outs (type->getDeviceNames (false));
  19445. int i;
  19446. for (i = 0; i < outs.size(); ++i)
  19447. {
  19448. if (outs[i].matchesWildcard (preferredDefaultDeviceName, true))
  19449. {
  19450. setup.outputDeviceName = outs[i];
  19451. break;
  19452. }
  19453. }
  19454. StringArray ins (type->getDeviceNames (true));
  19455. for (i = 0; i < ins.size(); ++i)
  19456. {
  19457. if (ins[i].matchesWildcard (preferredDefaultDeviceName, true))
  19458. {
  19459. setup.inputDeviceName = ins[i];
  19460. break;
  19461. }
  19462. }
  19463. }
  19464. }
  19465. insertDefaultDeviceNames (setup);
  19466. return setAudioDeviceSetup (setup, false);
  19467. }
  19468. }
  19469. void AudioDeviceManager::insertDefaultDeviceNames (AudioDeviceSetup& setup) const
  19470. {
  19471. AudioIODeviceType* type = getCurrentDeviceTypeObject();
  19472. if (type != 0)
  19473. {
  19474. if (setup.outputDeviceName.isEmpty())
  19475. setup.outputDeviceName = type->getDeviceNames (false) [type->getDefaultDeviceIndex (false)];
  19476. if (setup.inputDeviceName.isEmpty())
  19477. setup.inputDeviceName = type->getDeviceNames (true) [type->getDefaultDeviceIndex (true)];
  19478. }
  19479. }
  19480. XmlElement* AudioDeviceManager::createStateXml() const
  19481. {
  19482. return lastExplicitSettings != 0 ? new XmlElement (*lastExplicitSettings) : 0;
  19483. }
  19484. void AudioDeviceManager::scanDevicesIfNeeded()
  19485. {
  19486. if (listNeedsScanning)
  19487. {
  19488. listNeedsScanning = false;
  19489. createDeviceTypesIfNeeded();
  19490. for (int i = availableDeviceTypes.size(); --i >= 0;)
  19491. availableDeviceTypes.getUnchecked(i)->scanForDevices();
  19492. }
  19493. }
  19494. AudioIODeviceType* AudioDeviceManager::findType (const String& inputName, const String& outputName)
  19495. {
  19496. scanDevicesIfNeeded();
  19497. for (int i = availableDeviceTypes.size(); --i >= 0;)
  19498. {
  19499. AudioIODeviceType* const type = availableDeviceTypes.getUnchecked(i);
  19500. if ((inputName.isNotEmpty() && type->getDeviceNames (true).contains (inputName, true))
  19501. || (outputName.isNotEmpty() && type->getDeviceNames (false).contains (outputName, true)))
  19502. {
  19503. return type;
  19504. }
  19505. }
  19506. return 0;
  19507. }
  19508. void AudioDeviceManager::getAudioDeviceSetup (AudioDeviceSetup& setup)
  19509. {
  19510. setup = currentSetup;
  19511. }
  19512. void AudioDeviceManager::deleteCurrentDevice()
  19513. {
  19514. currentAudioDevice = 0;
  19515. currentSetup.inputDeviceName = String::empty;
  19516. currentSetup.outputDeviceName = String::empty;
  19517. }
  19518. void AudioDeviceManager::setCurrentAudioDeviceType (const String& type,
  19519. const bool treatAsChosenDevice)
  19520. {
  19521. for (int i = 0; i < availableDeviceTypes.size(); ++i)
  19522. {
  19523. if (availableDeviceTypes.getUnchecked(i)->getTypeName() == type
  19524. && currentDeviceType != type)
  19525. {
  19526. currentDeviceType = type;
  19527. AudioDeviceSetup s (*lastDeviceTypeConfigs.getUnchecked(i));
  19528. insertDefaultDeviceNames (s);
  19529. setAudioDeviceSetup (s, treatAsChosenDevice);
  19530. sendChangeMessage (this);
  19531. break;
  19532. }
  19533. }
  19534. }
  19535. AudioIODeviceType* AudioDeviceManager::getCurrentDeviceTypeObject() const
  19536. {
  19537. for (int i = 0; i < availableDeviceTypes.size(); ++i)
  19538. if (availableDeviceTypes[i]->getTypeName() == currentDeviceType)
  19539. return availableDeviceTypes[i];
  19540. return availableDeviceTypes[0];
  19541. }
  19542. const String AudioDeviceManager::setAudioDeviceSetup (const AudioDeviceSetup& newSetup,
  19543. const bool treatAsChosenDevice)
  19544. {
  19545. jassert (&newSetup != &currentSetup); // this will have no effect
  19546. if (newSetup == currentSetup && currentAudioDevice != 0)
  19547. return String::empty;
  19548. if (! (newSetup == currentSetup))
  19549. sendChangeMessage (this);
  19550. stopDevice();
  19551. const String newInputDeviceName (numInputChansNeeded == 0 ? String::empty : newSetup.inputDeviceName);
  19552. const String newOutputDeviceName (numOutputChansNeeded == 0 ? String::empty : newSetup.outputDeviceName);
  19553. String error;
  19554. AudioIODeviceType* type = getCurrentDeviceTypeObject();
  19555. if (type == 0 || (newInputDeviceName.isEmpty() && newOutputDeviceName.isEmpty()))
  19556. {
  19557. deleteCurrentDevice();
  19558. if (treatAsChosenDevice)
  19559. updateXml();
  19560. return String::empty;
  19561. }
  19562. if (currentSetup.inputDeviceName != newInputDeviceName
  19563. || currentSetup.outputDeviceName != newOutputDeviceName
  19564. || currentAudioDevice == 0)
  19565. {
  19566. deleteCurrentDevice();
  19567. scanDevicesIfNeeded();
  19568. if (newOutputDeviceName.isNotEmpty()
  19569. && ! type->getDeviceNames (false).contains (newOutputDeviceName))
  19570. {
  19571. return "No such device: " + newOutputDeviceName;
  19572. }
  19573. if (newInputDeviceName.isNotEmpty()
  19574. && ! type->getDeviceNames (true).contains (newInputDeviceName))
  19575. {
  19576. return "No such device: " + newInputDeviceName;
  19577. }
  19578. currentAudioDevice = type->createDevice (newOutputDeviceName, newInputDeviceName);
  19579. if (currentAudioDevice == 0)
  19580. 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!";
  19581. else
  19582. error = currentAudioDevice->getLastError();
  19583. if (error.isNotEmpty())
  19584. {
  19585. deleteCurrentDevice();
  19586. return error;
  19587. }
  19588. if (newSetup.useDefaultInputChannels)
  19589. {
  19590. inputChannels.clear();
  19591. inputChannels.setRange (0, numInputChansNeeded, true);
  19592. }
  19593. if (newSetup.useDefaultOutputChannels)
  19594. {
  19595. outputChannels.clear();
  19596. outputChannels.setRange (0, numOutputChansNeeded, true);
  19597. }
  19598. if (newInputDeviceName.isEmpty())
  19599. inputChannels.clear();
  19600. if (newOutputDeviceName.isEmpty())
  19601. outputChannels.clear();
  19602. }
  19603. if (! newSetup.useDefaultInputChannels)
  19604. inputChannels = newSetup.inputChannels;
  19605. if (! newSetup.useDefaultOutputChannels)
  19606. outputChannels = newSetup.outputChannels;
  19607. currentSetup = newSetup;
  19608. currentSetup.sampleRate = chooseBestSampleRate (newSetup.sampleRate);
  19609. error = currentAudioDevice->open (inputChannels,
  19610. outputChannels,
  19611. currentSetup.sampleRate,
  19612. currentSetup.bufferSize);
  19613. if (error.isEmpty())
  19614. {
  19615. currentDeviceType = currentAudioDevice->getTypeName();
  19616. currentAudioDevice->start (&callbackHandler);
  19617. currentSetup.sampleRate = currentAudioDevice->getCurrentSampleRate();
  19618. currentSetup.bufferSize = currentAudioDevice->getCurrentBufferSizeSamples();
  19619. currentSetup.inputChannels = currentAudioDevice->getActiveInputChannels();
  19620. currentSetup.outputChannels = currentAudioDevice->getActiveOutputChannels();
  19621. for (int i = 0; i < availableDeviceTypes.size(); ++i)
  19622. if (availableDeviceTypes.getUnchecked (i)->getTypeName() == currentDeviceType)
  19623. *(lastDeviceTypeConfigs.getUnchecked (i)) = currentSetup;
  19624. if (treatAsChosenDevice)
  19625. updateXml();
  19626. }
  19627. else
  19628. {
  19629. deleteCurrentDevice();
  19630. }
  19631. return error;
  19632. }
  19633. double AudioDeviceManager::chooseBestSampleRate (double rate) const
  19634. {
  19635. jassert (currentAudioDevice != 0);
  19636. if (rate > 0)
  19637. {
  19638. bool ok = false;
  19639. for (int i = currentAudioDevice->getNumSampleRates(); --i >= 0;)
  19640. {
  19641. const double sr = currentAudioDevice->getSampleRate (i);
  19642. if (sr == rate)
  19643. ok = true;
  19644. }
  19645. if (! ok)
  19646. rate = 0;
  19647. }
  19648. if (rate == 0)
  19649. {
  19650. double lowestAbove44 = 0.0;
  19651. for (int i = currentAudioDevice->getNumSampleRates(); --i >= 0;)
  19652. {
  19653. const double sr = currentAudioDevice->getSampleRate (i);
  19654. if (sr >= 44100.0 && (lowestAbove44 == 0 || sr < lowestAbove44))
  19655. lowestAbove44 = sr;
  19656. }
  19657. if (lowestAbove44 == 0.0)
  19658. rate = currentAudioDevice->getSampleRate (0);
  19659. else
  19660. rate = lowestAbove44;
  19661. }
  19662. return rate;
  19663. }
  19664. void AudioDeviceManager::stopDevice()
  19665. {
  19666. if (currentAudioDevice != 0)
  19667. currentAudioDevice->stop();
  19668. testSound = 0;
  19669. }
  19670. void AudioDeviceManager::closeAudioDevice()
  19671. {
  19672. stopDevice();
  19673. currentAudioDevice = 0;
  19674. }
  19675. void AudioDeviceManager::restartLastAudioDevice()
  19676. {
  19677. if (currentAudioDevice == 0)
  19678. {
  19679. if (currentSetup.inputDeviceName.isEmpty()
  19680. && currentSetup.outputDeviceName.isEmpty())
  19681. {
  19682. // This method will only reload the last device that was running
  19683. // before closeAudioDevice() was called - you need to actually open
  19684. // one first, with setAudioDevice().
  19685. jassertfalse
  19686. return;
  19687. }
  19688. AudioDeviceSetup s (currentSetup);
  19689. setAudioDeviceSetup (s, false);
  19690. }
  19691. }
  19692. void AudioDeviceManager::updateXml()
  19693. {
  19694. lastExplicitSettings = new XmlElement ("DEVICESETUP");
  19695. lastExplicitSettings->setAttribute ("deviceType", currentDeviceType);
  19696. lastExplicitSettings->setAttribute ("audioOutputDeviceName", currentSetup.outputDeviceName);
  19697. lastExplicitSettings->setAttribute ("audioInputDeviceName", currentSetup.inputDeviceName);
  19698. if (currentAudioDevice != 0)
  19699. {
  19700. lastExplicitSettings->setAttribute ("audioDeviceRate", currentAudioDevice->getCurrentSampleRate());
  19701. if (currentAudioDevice->getDefaultBufferSize() != currentAudioDevice->getCurrentBufferSizeSamples())
  19702. lastExplicitSettings->setAttribute ("audioDeviceBufferSize", currentAudioDevice->getCurrentBufferSizeSamples());
  19703. if (! currentSetup.useDefaultInputChannels)
  19704. lastExplicitSettings->setAttribute ("audioDeviceInChans", currentSetup.inputChannels.toString (2));
  19705. if (! currentSetup.useDefaultOutputChannels)
  19706. lastExplicitSettings->setAttribute ("audioDeviceOutChans", currentSetup.outputChannels.toString (2));
  19707. }
  19708. for (int i = 0; i < enabledMidiInputs.size(); ++i)
  19709. {
  19710. XmlElement* const m = lastExplicitSettings->createNewChildElement ("MIDIINPUT");
  19711. m->setAttribute ("name", enabledMidiInputs[i]->getName());
  19712. }
  19713. if (midiInsFromXml.size() > 0)
  19714. {
  19715. // Add any midi devices that have been enabled before, but which aren't currently
  19716. // open because the device has been disconnected.
  19717. const StringArray availableMidiDevices (MidiInput::getDevices());
  19718. for (int i = 0; i < midiInsFromXml.size(); ++i)
  19719. {
  19720. if (! availableMidiDevices.contains (midiInsFromXml[i], true))
  19721. {
  19722. XmlElement* const m = lastExplicitSettings->createNewChildElement ("MIDIINPUT");
  19723. m->setAttribute ("name", midiInsFromXml[i]);
  19724. }
  19725. }
  19726. }
  19727. if (defaultMidiOutputName.isNotEmpty())
  19728. lastExplicitSettings->setAttribute ("defaultMidiOutput", defaultMidiOutputName);
  19729. }
  19730. void AudioDeviceManager::addAudioCallback (AudioIODeviceCallback* newCallback)
  19731. {
  19732. {
  19733. const ScopedLock sl (audioCallbackLock);
  19734. if (callbacks.contains (newCallback))
  19735. return;
  19736. }
  19737. if (currentAudioDevice != 0 && newCallback != 0)
  19738. newCallback->audioDeviceAboutToStart (currentAudioDevice);
  19739. const ScopedLock sl (audioCallbackLock);
  19740. callbacks.add (newCallback);
  19741. }
  19742. void AudioDeviceManager::removeAudioCallback (AudioIODeviceCallback* callback)
  19743. {
  19744. if (callback != 0)
  19745. {
  19746. bool needsDeinitialising = currentAudioDevice != 0;
  19747. {
  19748. const ScopedLock sl (audioCallbackLock);
  19749. needsDeinitialising = needsDeinitialising && callbacks.contains (callback);
  19750. callbacks.removeValue (callback);
  19751. }
  19752. if (needsDeinitialising)
  19753. callback->audioDeviceStopped();
  19754. }
  19755. }
  19756. void AudioDeviceManager::audioDeviceIOCallbackInt (const float** inputChannelData,
  19757. int numInputChannels,
  19758. float** outputChannelData,
  19759. int numOutputChannels,
  19760. int numSamples)
  19761. {
  19762. const ScopedLock sl (audioCallbackLock);
  19763. if (inputLevelMeasurementEnabledCount > 0)
  19764. {
  19765. for (int j = 0; j < numSamples; ++j)
  19766. {
  19767. float s = 0;
  19768. for (int i = 0; i < numInputChannels; ++i)
  19769. s += fabsf (inputChannelData[i][j]);
  19770. s /= numInputChannels;
  19771. const double decayFactor = 0.99992;
  19772. if (s > inputLevel)
  19773. inputLevel = s;
  19774. else if (inputLevel > 0.001f)
  19775. inputLevel *= decayFactor;
  19776. else
  19777. inputLevel = 0;
  19778. }
  19779. }
  19780. if (callbacks.size() > 0)
  19781. {
  19782. const double callbackStartTime = Time::getMillisecondCounterHiRes();
  19783. tempBuffer.setSize (jmax (1, numOutputChannels), jmax (1, numSamples), false, false, true);
  19784. callbacks.getUnchecked(0)->audioDeviceIOCallback (inputChannelData, numInputChannels,
  19785. outputChannelData, numOutputChannels, numSamples);
  19786. float** const tempChans = tempBuffer.getArrayOfChannels();
  19787. for (int i = callbacks.size(); --i > 0;)
  19788. {
  19789. callbacks.getUnchecked(i)->audioDeviceIOCallback (inputChannelData, numInputChannels,
  19790. tempChans, numOutputChannels, numSamples);
  19791. for (int chan = 0; chan < numOutputChannels; ++chan)
  19792. {
  19793. const float* const src = tempChans [chan];
  19794. float* const dst = outputChannelData [chan];
  19795. if (src != 0 && dst != 0)
  19796. for (int j = 0; j < numSamples; ++j)
  19797. dst[j] += src[j];
  19798. }
  19799. }
  19800. const double msTaken = Time::getMillisecondCounterHiRes() - callbackStartTime;
  19801. const double filterAmount = 0.2;
  19802. cpuUsageMs += filterAmount * (msTaken - cpuUsageMs);
  19803. }
  19804. else
  19805. {
  19806. for (int i = 0; i < numOutputChannels; ++i)
  19807. zeromem (outputChannelData[i], sizeof (float) * numSamples);
  19808. }
  19809. if (testSound != 0)
  19810. {
  19811. const int numSamps = jmin (numSamples, testSound->getNumSamples() - testSoundPosition);
  19812. const float* const src = testSound->getSampleData (0, testSoundPosition);
  19813. for (int i = 0; i < numOutputChannels; ++i)
  19814. for (int j = 0; j < numSamps; ++j)
  19815. outputChannelData [i][j] += src[j];
  19816. testSoundPosition += numSamps;
  19817. if (testSoundPosition >= testSound->getNumSamples())
  19818. testSound = 0;
  19819. }
  19820. }
  19821. void AudioDeviceManager::audioDeviceAboutToStartInt (AudioIODevice* const device)
  19822. {
  19823. cpuUsageMs = 0;
  19824. const double sampleRate = device->getCurrentSampleRate();
  19825. const int blockSize = device->getCurrentBufferSizeSamples();
  19826. if (sampleRate > 0.0 && blockSize > 0)
  19827. {
  19828. const double msPerBlock = 1000.0 * blockSize / sampleRate;
  19829. timeToCpuScale = (msPerBlock > 0.0) ? (1.0 / msPerBlock) : 0.0;
  19830. }
  19831. {
  19832. const ScopedLock sl (audioCallbackLock);
  19833. for (int i = callbacks.size(); --i >= 0;)
  19834. callbacks.getUnchecked(i)->audioDeviceAboutToStart (device);
  19835. }
  19836. sendChangeMessage (this);
  19837. }
  19838. void AudioDeviceManager::audioDeviceStoppedInt()
  19839. {
  19840. cpuUsageMs = 0;
  19841. timeToCpuScale = 0;
  19842. sendChangeMessage (this);
  19843. const ScopedLock sl (audioCallbackLock);
  19844. for (int i = callbacks.size(); --i >= 0;)
  19845. callbacks.getUnchecked(i)->audioDeviceStopped();
  19846. }
  19847. double AudioDeviceManager::getCpuUsage() const
  19848. {
  19849. return jlimit (0.0, 1.0, timeToCpuScale * cpuUsageMs);
  19850. }
  19851. void AudioDeviceManager::setMidiInputEnabled (const String& name,
  19852. const bool enabled)
  19853. {
  19854. if (enabled != isMidiInputEnabled (name))
  19855. {
  19856. if (enabled)
  19857. {
  19858. const int index = MidiInput::getDevices().indexOf (name);
  19859. if (index >= 0)
  19860. {
  19861. MidiInput* const min = MidiInput::openDevice (index, &callbackHandler);
  19862. if (min != 0)
  19863. {
  19864. enabledMidiInputs.add (min);
  19865. min->start();
  19866. }
  19867. }
  19868. }
  19869. else
  19870. {
  19871. for (int i = enabledMidiInputs.size(); --i >= 0;)
  19872. if (enabledMidiInputs[i]->getName() == name)
  19873. enabledMidiInputs.remove (i);
  19874. }
  19875. updateXml();
  19876. sendChangeMessage (this);
  19877. }
  19878. }
  19879. bool AudioDeviceManager::isMidiInputEnabled (const String& name) const
  19880. {
  19881. for (int i = enabledMidiInputs.size(); --i >= 0;)
  19882. if (enabledMidiInputs[i]->getName() == name)
  19883. return true;
  19884. return false;
  19885. }
  19886. void AudioDeviceManager::addMidiInputCallback (const String& name,
  19887. MidiInputCallback* callback)
  19888. {
  19889. removeMidiInputCallback (name, callback);
  19890. if (name.isEmpty())
  19891. {
  19892. midiCallbacks.add (callback);
  19893. midiCallbackDevices.add (0);
  19894. }
  19895. else
  19896. {
  19897. for (int i = enabledMidiInputs.size(); --i >= 0;)
  19898. {
  19899. if (enabledMidiInputs[i]->getName() == name)
  19900. {
  19901. const ScopedLock sl (midiCallbackLock);
  19902. midiCallbacks.add (callback);
  19903. midiCallbackDevices.add (enabledMidiInputs[i]);
  19904. break;
  19905. }
  19906. }
  19907. }
  19908. }
  19909. void AudioDeviceManager::removeMidiInputCallback (const String& name,
  19910. MidiInputCallback* /*callback*/)
  19911. {
  19912. const ScopedLock sl (midiCallbackLock);
  19913. for (int i = midiCallbacks.size(); --i >= 0;)
  19914. {
  19915. String devName;
  19916. if (midiCallbackDevices.getUnchecked(i) != 0)
  19917. devName = midiCallbackDevices.getUnchecked(i)->getName();
  19918. if (devName == name)
  19919. {
  19920. midiCallbacks.remove (i);
  19921. midiCallbackDevices.remove (i);
  19922. }
  19923. }
  19924. }
  19925. void AudioDeviceManager::handleIncomingMidiMessageInt (MidiInput* source,
  19926. const MidiMessage& message)
  19927. {
  19928. if (! message.isActiveSense())
  19929. {
  19930. const bool isDefaultSource = (source == 0 || source == enabledMidiInputs.getFirst());
  19931. const ScopedLock sl (midiCallbackLock);
  19932. for (int i = midiCallbackDevices.size(); --i >= 0;)
  19933. {
  19934. MidiInput* const md = midiCallbackDevices.getUnchecked(i);
  19935. if (md == source || (md == 0 && isDefaultSource))
  19936. midiCallbacks.getUnchecked(i)->handleIncomingMidiMessage (source, message);
  19937. }
  19938. }
  19939. }
  19940. void AudioDeviceManager::setDefaultMidiOutput (const String& deviceName)
  19941. {
  19942. if (defaultMidiOutputName != deviceName)
  19943. {
  19944. SortedSet <AudioIODeviceCallback*> oldCallbacks;
  19945. {
  19946. const ScopedLock sl (audioCallbackLock);
  19947. oldCallbacks = callbacks;
  19948. callbacks.clear();
  19949. }
  19950. if (currentAudioDevice != 0)
  19951. for (int i = oldCallbacks.size(); --i >= 0;)
  19952. oldCallbacks.getUnchecked(i)->audioDeviceStopped();
  19953. defaultMidiOutput = 0;
  19954. defaultMidiOutputName = deviceName;
  19955. if (deviceName.isNotEmpty())
  19956. defaultMidiOutput = MidiOutput::openDevice (MidiOutput::getDevices().indexOf (deviceName));
  19957. if (currentAudioDevice != 0)
  19958. for (int i = oldCallbacks.size(); --i >= 0;)
  19959. oldCallbacks.getUnchecked(i)->audioDeviceAboutToStart (currentAudioDevice);
  19960. {
  19961. const ScopedLock sl (audioCallbackLock);
  19962. callbacks = oldCallbacks;
  19963. }
  19964. updateXml();
  19965. sendChangeMessage (this);
  19966. }
  19967. }
  19968. void AudioDeviceManager::CallbackHandler::audioDeviceIOCallback (const float** inputChannelData,
  19969. int numInputChannels,
  19970. float** outputChannelData,
  19971. int numOutputChannels,
  19972. int numSamples)
  19973. {
  19974. owner->audioDeviceIOCallbackInt (inputChannelData, numInputChannels, outputChannelData, numOutputChannels, numSamples);
  19975. }
  19976. void AudioDeviceManager::CallbackHandler::audioDeviceAboutToStart (AudioIODevice* device)
  19977. {
  19978. owner->audioDeviceAboutToStartInt (device);
  19979. }
  19980. void AudioDeviceManager::CallbackHandler::audioDeviceStopped()
  19981. {
  19982. owner->audioDeviceStoppedInt();
  19983. }
  19984. void AudioDeviceManager::CallbackHandler::handleIncomingMidiMessage (MidiInput* source, const MidiMessage& message)
  19985. {
  19986. owner->handleIncomingMidiMessageInt (source, message);
  19987. }
  19988. void AudioDeviceManager::playTestSound()
  19989. {
  19990. { // cunningly nested to swap, unlock and delete in that order.
  19991. ScopedPointer <AudioSampleBuffer> oldSound;
  19992. {
  19993. const ScopedLock sl (audioCallbackLock);
  19994. oldSound = testSound;
  19995. }
  19996. }
  19997. testSoundPosition = 0;
  19998. if (currentAudioDevice != 0)
  19999. {
  20000. const double sampleRate = currentAudioDevice->getCurrentSampleRate();
  20001. const int soundLength = (int) sampleRate;
  20002. AudioSampleBuffer* const newSound = new AudioSampleBuffer (1, soundLength);
  20003. float* samples = newSound->getSampleData (0);
  20004. const double frequency = MidiMessage::getMidiNoteInHertz (80);
  20005. const float amplitude = 0.5f;
  20006. const double phasePerSample = double_Pi * 2.0 / (sampleRate / frequency);
  20007. for (int i = 0; i < soundLength; ++i)
  20008. samples[i] = amplitude * (float) sin (i * phasePerSample);
  20009. newSound->applyGainRamp (0, 0, soundLength / 10, 0.0f, 1.0f);
  20010. newSound->applyGainRamp (0, soundLength - soundLength / 4, soundLength / 4, 1.0f, 0.0f);
  20011. const ScopedLock sl (audioCallbackLock);
  20012. testSound = newSound;
  20013. }
  20014. }
  20015. void AudioDeviceManager::enableInputLevelMeasurement (const bool enableMeasurement)
  20016. {
  20017. const ScopedLock sl (audioCallbackLock);
  20018. if (enableMeasurement)
  20019. ++inputLevelMeasurementEnabledCount;
  20020. else
  20021. --inputLevelMeasurementEnabledCount;
  20022. inputLevel = 0;
  20023. }
  20024. double AudioDeviceManager::getCurrentInputLevel() const
  20025. {
  20026. jassert (inputLevelMeasurementEnabledCount > 0); // you need to call enableInputLevelMeasurement() before using this!
  20027. return inputLevel;
  20028. }
  20029. END_JUCE_NAMESPACE
  20030. /*** End of inlined file: juce_AudioDeviceManager.cpp ***/
  20031. /*** Start of inlined file: juce_AudioIODevice.cpp ***/
  20032. BEGIN_JUCE_NAMESPACE
  20033. AudioIODevice::AudioIODevice (const String& deviceName, const String& typeName_)
  20034. : name (deviceName),
  20035. typeName (typeName_)
  20036. {
  20037. }
  20038. AudioIODevice::~AudioIODevice()
  20039. {
  20040. }
  20041. bool AudioIODevice::hasControlPanel() const
  20042. {
  20043. return false;
  20044. }
  20045. bool AudioIODevice::showControlPanel()
  20046. {
  20047. jassertfalse // this should only be called for devices which return true from
  20048. // their hasControlPanel() method.
  20049. return false;
  20050. }
  20051. END_JUCE_NAMESPACE
  20052. /*** End of inlined file: juce_AudioIODevice.cpp ***/
  20053. /*** Start of inlined file: juce_AudioIODeviceType.cpp ***/
  20054. BEGIN_JUCE_NAMESPACE
  20055. AudioIODeviceType::AudioIODeviceType (const String& name)
  20056. : typeName (name)
  20057. {
  20058. }
  20059. AudioIODeviceType::~AudioIODeviceType()
  20060. {
  20061. }
  20062. END_JUCE_NAMESPACE
  20063. /*** End of inlined file: juce_AudioIODeviceType.cpp ***/
  20064. /*** Start of inlined file: juce_MidiOutput.cpp ***/
  20065. BEGIN_JUCE_NAMESPACE
  20066. MidiOutput::MidiOutput()
  20067. : Thread ("midi out"),
  20068. internal (0),
  20069. firstMessage (0)
  20070. {
  20071. }
  20072. MidiOutput::PendingMessage::PendingMessage (const uint8* const data, const int len,
  20073. const double sampleNumber)
  20074. : message (data, len, sampleNumber)
  20075. {
  20076. }
  20077. void MidiOutput::sendBlockOfMessages (const MidiBuffer& buffer,
  20078. const double millisecondCounterToStartAt,
  20079. double samplesPerSecondForBuffer)
  20080. {
  20081. // You've got to call startBackgroundThread() for this to actually work..
  20082. jassert (isThreadRunning());
  20083. // this needs to be a value in the future - RTFM for this method!
  20084. jassert (millisecondCounterToStartAt > 0);
  20085. const double timeScaleFactor = 1000.0 / samplesPerSecondForBuffer;
  20086. MidiBuffer::Iterator i (buffer);
  20087. const uint8* data;
  20088. int len, time;
  20089. while (i.getNextEvent (data, len, time))
  20090. {
  20091. const double eventTime = millisecondCounterToStartAt + timeScaleFactor * time;
  20092. PendingMessage* const m
  20093. = new PendingMessage (data, len, eventTime);
  20094. const ScopedLock sl (lock);
  20095. if (firstMessage == 0 || firstMessage->message.getTimeStamp() > eventTime)
  20096. {
  20097. m->next = firstMessage;
  20098. firstMessage = m;
  20099. }
  20100. else
  20101. {
  20102. PendingMessage* mm = firstMessage;
  20103. while (mm->next != 0 && mm->next->message.getTimeStamp() <= eventTime)
  20104. mm = mm->next;
  20105. m->next = mm->next;
  20106. mm->next = m;
  20107. }
  20108. }
  20109. notify();
  20110. }
  20111. void MidiOutput::clearAllPendingMessages()
  20112. {
  20113. const ScopedLock sl (lock);
  20114. while (firstMessage != 0)
  20115. {
  20116. PendingMessage* const m = firstMessage;
  20117. firstMessage = firstMessage->next;
  20118. delete m;
  20119. }
  20120. }
  20121. void MidiOutput::startBackgroundThread()
  20122. {
  20123. startThread (9);
  20124. }
  20125. void MidiOutput::stopBackgroundThread()
  20126. {
  20127. stopThread (5000);
  20128. }
  20129. void MidiOutput::run()
  20130. {
  20131. while (! threadShouldExit())
  20132. {
  20133. uint32 now = Time::getMillisecondCounter();
  20134. uint32 eventTime = 0;
  20135. uint32 timeToWait = 500;
  20136. PendingMessage* message;
  20137. {
  20138. const ScopedLock sl (lock);
  20139. message = firstMessage;
  20140. if (message != 0)
  20141. {
  20142. eventTime = roundToInt (message->message.getTimeStamp());
  20143. if (eventTime > now + 20)
  20144. {
  20145. timeToWait = eventTime - (now + 20);
  20146. message = 0;
  20147. }
  20148. else
  20149. {
  20150. firstMessage = message->next;
  20151. }
  20152. }
  20153. }
  20154. if (message != 0)
  20155. {
  20156. if (eventTime > now)
  20157. {
  20158. Time::waitForMillisecondCounter (eventTime);
  20159. if (threadShouldExit())
  20160. break;
  20161. }
  20162. if (eventTime > now - 200)
  20163. sendMessageNow (message->message);
  20164. delete message;
  20165. }
  20166. else
  20167. {
  20168. jassert (timeToWait < 1000 * 30);
  20169. wait (timeToWait);
  20170. }
  20171. }
  20172. clearAllPendingMessages();
  20173. }
  20174. END_JUCE_NAMESPACE
  20175. /*** End of inlined file: juce_MidiOutput.cpp ***/
  20176. /*** Start of inlined file: juce_AudioDataConverters.cpp ***/
  20177. BEGIN_JUCE_NAMESPACE
  20178. void AudioDataConverters::convertFloatToInt16LE (const float* source, void* dest, int numSamples, const int destBytesPerSample)
  20179. {
  20180. const double maxVal = (double) 0x7fff;
  20181. char* intData = static_cast <char*> (dest);
  20182. if (dest != (void*) source || destBytesPerSample <= 4)
  20183. {
  20184. for (int i = 0; i < numSamples; ++i)
  20185. {
  20186. *(uint16*) intData = ByteOrder::swapIfBigEndian ((uint16) (short) roundToInt (jlimit (-maxVal, maxVal, maxVal * source[i])));
  20187. intData += destBytesPerSample;
  20188. }
  20189. }
  20190. else
  20191. {
  20192. intData += destBytesPerSample * numSamples;
  20193. for (int i = numSamples; --i >= 0;)
  20194. {
  20195. intData -= destBytesPerSample;
  20196. *(uint16*) intData = ByteOrder::swapIfBigEndian ((uint16) (short) roundToInt (jlimit (-maxVal, maxVal, maxVal * source[i])));
  20197. }
  20198. }
  20199. }
  20200. void AudioDataConverters::convertFloatToInt16BE (const float* source, void* dest, int numSamples, const int destBytesPerSample)
  20201. {
  20202. const double maxVal = (double) 0x7fff;
  20203. char* intData = static_cast <char*> (dest);
  20204. if (dest != (void*) source || destBytesPerSample <= 4)
  20205. {
  20206. for (int i = 0; i < numSamples; ++i)
  20207. {
  20208. *(uint16*) intData = ByteOrder::swapIfLittleEndian ((uint16) (short) roundToInt (jlimit (-maxVal, maxVal, maxVal * source[i])));
  20209. intData += destBytesPerSample;
  20210. }
  20211. }
  20212. else
  20213. {
  20214. intData += destBytesPerSample * numSamples;
  20215. for (int i = numSamples; --i >= 0;)
  20216. {
  20217. intData -= destBytesPerSample;
  20218. *(uint16*) intData = ByteOrder::swapIfLittleEndian ((uint16) (short) roundToInt (jlimit (-maxVal, maxVal, maxVal * source[i])));
  20219. }
  20220. }
  20221. }
  20222. void AudioDataConverters::convertFloatToInt24LE (const float* source, void* dest, int numSamples, const int destBytesPerSample)
  20223. {
  20224. const double maxVal = (double) 0x7fffff;
  20225. char* intData = static_cast <char*> (dest);
  20226. if (dest != (void*) source || destBytesPerSample <= 4)
  20227. {
  20228. for (int i = 0; i < numSamples; ++i)
  20229. {
  20230. ByteOrder::littleEndian24BitToChars ((uint32) roundToInt (jlimit (-maxVal, maxVal, maxVal * source[i])), intData);
  20231. intData += destBytesPerSample;
  20232. }
  20233. }
  20234. else
  20235. {
  20236. intData += destBytesPerSample * numSamples;
  20237. for (int i = numSamples; --i >= 0;)
  20238. {
  20239. intData -= destBytesPerSample;
  20240. ByteOrder::littleEndian24BitToChars ((uint32) roundToInt (jlimit (-maxVal, maxVal, maxVal * source[i])), intData);
  20241. }
  20242. }
  20243. }
  20244. void AudioDataConverters::convertFloatToInt24BE (const float* source, void* dest, int numSamples, const int destBytesPerSample)
  20245. {
  20246. const double maxVal = (double) 0x7fffff;
  20247. char* intData = static_cast <char*> (dest);
  20248. if (dest != (void*) source || destBytesPerSample <= 4)
  20249. {
  20250. for (int i = 0; i < numSamples; ++i)
  20251. {
  20252. ByteOrder::bigEndian24BitToChars ((uint32) roundToInt (jlimit (-maxVal, maxVal, maxVal * source[i])), intData);
  20253. intData += destBytesPerSample;
  20254. }
  20255. }
  20256. else
  20257. {
  20258. intData += destBytesPerSample * numSamples;
  20259. for (int i = numSamples; --i >= 0;)
  20260. {
  20261. intData -= destBytesPerSample;
  20262. ByteOrder::bigEndian24BitToChars ((uint32) roundToInt (jlimit (-maxVal, maxVal, maxVal * source[i])), intData);
  20263. }
  20264. }
  20265. }
  20266. void AudioDataConverters::convertFloatToInt32LE (const float* source, void* dest, int numSamples, const int destBytesPerSample)
  20267. {
  20268. const double maxVal = (double) 0x7fffffff;
  20269. char* intData = static_cast <char*> (dest);
  20270. if (dest != (void*) source || destBytesPerSample <= 4)
  20271. {
  20272. for (int i = 0; i < numSamples; ++i)
  20273. {
  20274. *(uint32*)intData = ByteOrder::swapIfBigEndian ((uint32) roundToInt (jlimit (-maxVal, maxVal, maxVal * source[i])));
  20275. intData += destBytesPerSample;
  20276. }
  20277. }
  20278. else
  20279. {
  20280. intData += destBytesPerSample * numSamples;
  20281. for (int i = numSamples; --i >= 0;)
  20282. {
  20283. intData -= destBytesPerSample;
  20284. *(uint32*)intData = ByteOrder::swapIfBigEndian ((uint32) roundToInt (jlimit (-maxVal, maxVal, maxVal * source[i])));
  20285. }
  20286. }
  20287. }
  20288. void AudioDataConverters::convertFloatToInt32BE (const float* source, void* dest, int numSamples, const int destBytesPerSample)
  20289. {
  20290. const double maxVal = (double) 0x7fffffff;
  20291. char* intData = static_cast <char*> (dest);
  20292. if (dest != (void*) source || destBytesPerSample <= 4)
  20293. {
  20294. for (int i = 0; i < numSamples; ++i)
  20295. {
  20296. *(uint32*)intData = ByteOrder::swapIfLittleEndian ((uint32) roundToInt (jlimit (-maxVal, maxVal, maxVal * source[i])));
  20297. intData += destBytesPerSample;
  20298. }
  20299. }
  20300. else
  20301. {
  20302. intData += destBytesPerSample * numSamples;
  20303. for (int i = numSamples; --i >= 0;)
  20304. {
  20305. intData -= destBytesPerSample;
  20306. *(uint32*)intData = ByteOrder::swapIfLittleEndian ((uint32) roundToInt (jlimit (-maxVal, maxVal, maxVal * source[i])));
  20307. }
  20308. }
  20309. }
  20310. void AudioDataConverters::convertFloatToFloat32LE (const float* source, void* dest, int numSamples, const int destBytesPerSample)
  20311. {
  20312. jassert (dest != (void*) source || destBytesPerSample <= 4); // This op can't be performed on in-place data!
  20313. char* d = static_cast <char*> (dest);
  20314. for (int i = 0; i < numSamples; ++i)
  20315. {
  20316. *(float*) d = source[i];
  20317. #if JUCE_BIG_ENDIAN
  20318. *(uint32*) d = ByteOrder::swap (*(uint32*) d);
  20319. #endif
  20320. d += destBytesPerSample;
  20321. }
  20322. }
  20323. void AudioDataConverters::convertFloatToFloat32BE (const float* source, void* dest, int numSamples, const int destBytesPerSample)
  20324. {
  20325. jassert (dest != (void*) source || destBytesPerSample <= 4); // This op can't be performed on in-place data!
  20326. char* d = static_cast <char*> (dest);
  20327. for (int i = 0; i < numSamples; ++i)
  20328. {
  20329. *(float*) d = source[i];
  20330. #if JUCE_LITTLE_ENDIAN
  20331. *(uint32*) d = ByteOrder::swap (*(uint32*) d);
  20332. #endif
  20333. d += destBytesPerSample;
  20334. }
  20335. }
  20336. void AudioDataConverters::convertInt16LEToFloat (const void* const source, float* const dest, int numSamples, const int srcBytesPerSample)
  20337. {
  20338. const float scale = 1.0f / 0x7fff;
  20339. const char* intData = static_cast <const char*> (source);
  20340. if (source != (void*) dest || srcBytesPerSample >= 4)
  20341. {
  20342. for (int i = 0; i < numSamples; ++i)
  20343. {
  20344. dest[i] = scale * (short) ByteOrder::swapIfBigEndian (*(uint16*)intData);
  20345. intData += srcBytesPerSample;
  20346. }
  20347. }
  20348. else
  20349. {
  20350. intData += srcBytesPerSample * numSamples;
  20351. for (int i = numSamples; --i >= 0;)
  20352. {
  20353. intData -= srcBytesPerSample;
  20354. dest[i] = scale * (short) ByteOrder::swapIfBigEndian (*(uint16*)intData);
  20355. }
  20356. }
  20357. }
  20358. void AudioDataConverters::convertInt16BEToFloat (const void* const source, float* const dest, int numSamples, const int srcBytesPerSample)
  20359. {
  20360. const float scale = 1.0f / 0x7fff;
  20361. const char* intData = static_cast <const char*> (source);
  20362. if (source != (void*) dest || srcBytesPerSample >= 4)
  20363. {
  20364. for (int i = 0; i < numSamples; ++i)
  20365. {
  20366. dest[i] = scale * (short) ByteOrder::swapIfLittleEndian (*(uint16*)intData);
  20367. intData += srcBytesPerSample;
  20368. }
  20369. }
  20370. else
  20371. {
  20372. intData += srcBytesPerSample * numSamples;
  20373. for (int i = numSamples; --i >= 0;)
  20374. {
  20375. intData -= srcBytesPerSample;
  20376. dest[i] = scale * (short) ByteOrder::swapIfLittleEndian (*(uint16*)intData);
  20377. }
  20378. }
  20379. }
  20380. void AudioDataConverters::convertInt24LEToFloat (const void* const source, float* const dest, int numSamples, const int srcBytesPerSample)
  20381. {
  20382. const float scale = 1.0f / 0x7fffff;
  20383. const char* intData = static_cast <const char*> (source);
  20384. if (source != (void*) dest || srcBytesPerSample >= 4)
  20385. {
  20386. for (int i = 0; i < numSamples; ++i)
  20387. {
  20388. dest[i] = scale * (short) ByteOrder::littleEndian24Bit (intData);
  20389. intData += srcBytesPerSample;
  20390. }
  20391. }
  20392. else
  20393. {
  20394. intData += srcBytesPerSample * numSamples;
  20395. for (int i = numSamples; --i >= 0;)
  20396. {
  20397. intData -= srcBytesPerSample;
  20398. dest[i] = scale * (short) ByteOrder::littleEndian24Bit (intData);
  20399. }
  20400. }
  20401. }
  20402. void AudioDataConverters::convertInt24BEToFloat (const void* const source, float* const dest, int numSamples, const int srcBytesPerSample)
  20403. {
  20404. const float scale = 1.0f / 0x7fffff;
  20405. const char* intData = static_cast <const char*> (source);
  20406. if (source != (void*) dest || srcBytesPerSample >= 4)
  20407. {
  20408. for (int i = 0; i < numSamples; ++i)
  20409. {
  20410. dest[i] = scale * (short) ByteOrder::bigEndian24Bit (intData);
  20411. intData += srcBytesPerSample;
  20412. }
  20413. }
  20414. else
  20415. {
  20416. intData += srcBytesPerSample * numSamples;
  20417. for (int i = numSamples; --i >= 0;)
  20418. {
  20419. intData -= srcBytesPerSample;
  20420. dest[i] = scale * (short) ByteOrder::bigEndian24Bit (intData);
  20421. }
  20422. }
  20423. }
  20424. void AudioDataConverters::convertInt32LEToFloat (const void* const source, float* const dest, int numSamples, const int srcBytesPerSample)
  20425. {
  20426. const float scale = 1.0f / 0x7fffffff;
  20427. const char* intData = static_cast <const char*> (source);
  20428. if (source != (void*) dest || srcBytesPerSample >= 4)
  20429. {
  20430. for (int i = 0; i < numSamples; ++i)
  20431. {
  20432. dest[i] = scale * (int) ByteOrder::swapIfBigEndian (*(uint32*) intData);
  20433. intData += srcBytesPerSample;
  20434. }
  20435. }
  20436. else
  20437. {
  20438. intData += srcBytesPerSample * numSamples;
  20439. for (int i = numSamples; --i >= 0;)
  20440. {
  20441. intData -= srcBytesPerSample;
  20442. dest[i] = scale * (int) ByteOrder::swapIfBigEndian (*(uint32*) intData);
  20443. }
  20444. }
  20445. }
  20446. void AudioDataConverters::convertInt32BEToFloat (const void* const source, float* const dest, int numSamples, const int srcBytesPerSample)
  20447. {
  20448. const float scale = 1.0f / 0x7fffffff;
  20449. const char* intData = static_cast <const char*> (source);
  20450. if (source != (void*) dest || srcBytesPerSample >= 4)
  20451. {
  20452. for (int i = 0; i < numSamples; ++i)
  20453. {
  20454. dest[i] = scale * (int) ByteOrder::swapIfLittleEndian (*(uint32*) intData);
  20455. intData += srcBytesPerSample;
  20456. }
  20457. }
  20458. else
  20459. {
  20460. intData += srcBytesPerSample * numSamples;
  20461. for (int i = numSamples; --i >= 0;)
  20462. {
  20463. intData -= srcBytesPerSample;
  20464. dest[i] = scale * (int) ByteOrder::swapIfLittleEndian (*(uint32*) intData);
  20465. }
  20466. }
  20467. }
  20468. void AudioDataConverters::convertFloat32LEToFloat (const void* const source, float* const dest, int numSamples, const int srcBytesPerSample)
  20469. {
  20470. const char* s = static_cast <const char*> (source);
  20471. for (int i = 0; i < numSamples; ++i)
  20472. {
  20473. dest[i] = *(float*)s;
  20474. #if JUCE_BIG_ENDIAN
  20475. uint32* const d = (uint32*) (dest + i);
  20476. *d = ByteOrder::swap (*d);
  20477. #endif
  20478. s += srcBytesPerSample;
  20479. }
  20480. }
  20481. void AudioDataConverters::convertFloat32BEToFloat (const void* const source, float* const dest, int numSamples, const int srcBytesPerSample)
  20482. {
  20483. const char* s = static_cast <const char*> (source);
  20484. for (int i = 0; i < numSamples; ++i)
  20485. {
  20486. dest[i] = *(float*)s;
  20487. #if JUCE_LITTLE_ENDIAN
  20488. uint32* const d = (uint32*) (dest + i);
  20489. *d = ByteOrder::swap (*d);
  20490. #endif
  20491. s += srcBytesPerSample;
  20492. }
  20493. }
  20494. void AudioDataConverters::convertFloatToFormat (const DataFormat destFormat,
  20495. const float* const source,
  20496. void* const dest,
  20497. const int numSamples)
  20498. {
  20499. switch (destFormat)
  20500. {
  20501. case int16LE:
  20502. convertFloatToInt16LE (source, dest, numSamples);
  20503. break;
  20504. case int16BE:
  20505. convertFloatToInt16BE (source, dest, numSamples);
  20506. break;
  20507. case int24LE:
  20508. convertFloatToInt24LE (source, dest, numSamples);
  20509. break;
  20510. case int24BE:
  20511. convertFloatToInt24BE (source, dest, numSamples);
  20512. break;
  20513. case int32LE:
  20514. convertFloatToInt32LE (source, dest, numSamples);
  20515. break;
  20516. case int32BE:
  20517. convertFloatToInt32BE (source, dest, numSamples);
  20518. break;
  20519. case float32LE:
  20520. convertFloatToFloat32LE (source, dest, numSamples);
  20521. break;
  20522. case float32BE:
  20523. convertFloatToFloat32BE (source, dest, numSamples);
  20524. break;
  20525. default:
  20526. jassertfalse
  20527. break;
  20528. }
  20529. }
  20530. void AudioDataConverters::convertFormatToFloat (const DataFormat sourceFormat,
  20531. const void* const source,
  20532. float* const dest,
  20533. const int numSamples)
  20534. {
  20535. switch (sourceFormat)
  20536. {
  20537. case int16LE:
  20538. convertInt16LEToFloat (source, dest, numSamples);
  20539. break;
  20540. case int16BE:
  20541. convertInt16BEToFloat (source, dest, numSamples);
  20542. break;
  20543. case int24LE:
  20544. convertInt24LEToFloat (source, dest, numSamples);
  20545. break;
  20546. case int24BE:
  20547. convertInt24BEToFloat (source, dest, numSamples);
  20548. break;
  20549. case int32LE:
  20550. convertInt32LEToFloat (source, dest, numSamples);
  20551. break;
  20552. case int32BE:
  20553. convertInt32BEToFloat (source, dest, numSamples);
  20554. break;
  20555. case float32LE:
  20556. convertFloat32LEToFloat (source, dest, numSamples);
  20557. break;
  20558. case float32BE:
  20559. convertFloat32BEToFloat (source, dest, numSamples);
  20560. break;
  20561. default:
  20562. jassertfalse
  20563. break;
  20564. }
  20565. }
  20566. void AudioDataConverters::interleaveSamples (const float** const source,
  20567. float* const dest,
  20568. const int numSamples,
  20569. const int numChannels)
  20570. {
  20571. for (int chan = 0; chan < numChannels; ++chan)
  20572. {
  20573. int i = chan;
  20574. const float* src = source [chan];
  20575. for (int j = 0; j < numSamples; ++j)
  20576. {
  20577. dest [i] = src [j];
  20578. i += numChannels;
  20579. }
  20580. }
  20581. }
  20582. void AudioDataConverters::deinterleaveSamples (const float* const source,
  20583. float** const dest,
  20584. const int numSamples,
  20585. const int numChannels)
  20586. {
  20587. for (int chan = 0; chan < numChannels; ++chan)
  20588. {
  20589. int i = chan;
  20590. float* dst = dest [chan];
  20591. for (int j = 0; j < numSamples; ++j)
  20592. {
  20593. dst [j] = source [i];
  20594. i += numChannels;
  20595. }
  20596. }
  20597. }
  20598. END_JUCE_NAMESPACE
  20599. /*** End of inlined file: juce_AudioDataConverters.cpp ***/
  20600. /*** Start of inlined file: juce_AudioSampleBuffer.cpp ***/
  20601. BEGIN_JUCE_NAMESPACE
  20602. AudioSampleBuffer::AudioSampleBuffer (const int numChannels_,
  20603. const int numSamples) throw()
  20604. : numChannels (numChannels_),
  20605. size (numSamples)
  20606. {
  20607. jassert (numSamples >= 0);
  20608. jassert (numChannels_ > 0);
  20609. allocateData();
  20610. }
  20611. AudioSampleBuffer::AudioSampleBuffer (const AudioSampleBuffer& other) throw()
  20612. : numChannels (other.numChannels),
  20613. size (other.size)
  20614. {
  20615. allocateData();
  20616. const size_t numBytes = size * sizeof (float);
  20617. for (int i = 0; i < numChannels; ++i)
  20618. memcpy (channels[i], other.channels[i], numBytes);
  20619. }
  20620. void AudioSampleBuffer::allocateData()
  20621. {
  20622. const size_t channelListSize = (numChannels + 1) * sizeof (float*);
  20623. allocatedBytes = (int) (numChannels * size * sizeof (float) + channelListSize + 32);
  20624. allocatedData.malloc (allocatedBytes);
  20625. channels = reinterpret_cast <float**> (allocatedData.getData());
  20626. float* chan = (float*) (allocatedData + channelListSize);
  20627. for (int i = 0; i < numChannels; ++i)
  20628. {
  20629. channels[i] = chan;
  20630. chan += size;
  20631. }
  20632. channels [numChannels] = 0;
  20633. }
  20634. AudioSampleBuffer::AudioSampleBuffer (float** dataToReferTo,
  20635. const int numChannels_,
  20636. const int numSamples) throw()
  20637. : numChannels (numChannels_),
  20638. size (numSamples),
  20639. allocatedBytes (0)
  20640. {
  20641. jassert (numChannels_ > 0);
  20642. allocateChannels (dataToReferTo);
  20643. }
  20644. void AudioSampleBuffer::setDataToReferTo (float** dataToReferTo,
  20645. const int newNumChannels,
  20646. const int newNumSamples) throw()
  20647. {
  20648. jassert (newNumChannels > 0);
  20649. allocatedBytes = 0;
  20650. allocatedData.free();
  20651. numChannels = newNumChannels;
  20652. size = newNumSamples;
  20653. allocateChannels (dataToReferTo);
  20654. }
  20655. void AudioSampleBuffer::allocateChannels (float** const dataToReferTo)
  20656. {
  20657. // (try to avoid doing a malloc here, as that'll blow up things like Pro-Tools)
  20658. if (numChannels < numElementsInArray (preallocatedChannelSpace))
  20659. {
  20660. channels = static_cast <float**> (preallocatedChannelSpace);
  20661. }
  20662. else
  20663. {
  20664. allocatedData.malloc (numChannels + 1, sizeof (float*));
  20665. channels = reinterpret_cast <float**> (allocatedData.getData());
  20666. }
  20667. for (int i = 0; i < numChannels; ++i)
  20668. {
  20669. // you have to pass in the same number of valid pointers as numChannels
  20670. jassert (dataToReferTo[i] != 0);
  20671. channels[i] = dataToReferTo[i];
  20672. }
  20673. channels [numChannels] = 0;
  20674. }
  20675. AudioSampleBuffer& AudioSampleBuffer::operator= (const AudioSampleBuffer& other) throw()
  20676. {
  20677. if (this != &other)
  20678. {
  20679. setSize (other.getNumChannels(), other.getNumSamples(), false, false, false);
  20680. const size_t numBytes = size * sizeof (float);
  20681. for (int i = 0; i < numChannels; ++i)
  20682. memcpy (channels[i], other.channels[i], numBytes);
  20683. }
  20684. return *this;
  20685. }
  20686. AudioSampleBuffer::~AudioSampleBuffer() throw()
  20687. {
  20688. }
  20689. void AudioSampleBuffer::setSize (const int newNumChannels,
  20690. const int newNumSamples,
  20691. const bool keepExistingContent,
  20692. const bool clearExtraSpace,
  20693. const bool avoidReallocating) throw()
  20694. {
  20695. jassert (newNumChannels > 0);
  20696. if (newNumSamples != size || newNumChannels != numChannels)
  20697. {
  20698. const size_t channelListSize = (newNumChannels + 1) * sizeof (float*);
  20699. const size_t newTotalBytes = (newNumChannels * newNumSamples * sizeof (float)) + channelListSize + 32;
  20700. if (keepExistingContent)
  20701. {
  20702. HeapBlock <char> newData;
  20703. newData.allocate (newTotalBytes, clearExtraSpace);
  20704. const int numChansToCopy = jmin (numChannels, newNumChannels);
  20705. const size_t numBytesToCopy = sizeof (float) * jmin (newNumSamples, size);
  20706. float** const newChannels = reinterpret_cast <float**> (newData.getData());
  20707. float* newChan = reinterpret_cast <float*> (newData + channelListSize);
  20708. for (int i = 0; i < numChansToCopy; ++i)
  20709. {
  20710. memcpy (newChan, channels[i], numBytesToCopy);
  20711. newChannels[i] = newChan;
  20712. newChan += newNumSamples;
  20713. }
  20714. allocatedData.swapWith (newData);
  20715. allocatedBytes = (int) newTotalBytes;
  20716. channels = newChannels;
  20717. }
  20718. else
  20719. {
  20720. if (avoidReallocating && allocatedBytes >= newTotalBytes)
  20721. {
  20722. if (clearExtraSpace)
  20723. zeromem (allocatedData, newTotalBytes);
  20724. }
  20725. else
  20726. {
  20727. allocatedBytes = newTotalBytes;
  20728. allocatedData.allocate (newTotalBytes, clearExtraSpace);
  20729. channels = reinterpret_cast <float**> (allocatedData.getData());
  20730. }
  20731. float* chan = reinterpret_cast <float*> (allocatedData + channelListSize);
  20732. for (int i = 0; i < newNumChannels; ++i)
  20733. {
  20734. channels[i] = chan;
  20735. chan += newNumSamples;
  20736. }
  20737. }
  20738. channels [newNumChannels] = 0;
  20739. size = newNumSamples;
  20740. numChannels = newNumChannels;
  20741. }
  20742. }
  20743. void AudioSampleBuffer::clear() throw()
  20744. {
  20745. for (int i = 0; i < numChannels; ++i)
  20746. zeromem (channels[i], size * sizeof (float));
  20747. }
  20748. void AudioSampleBuffer::clear (const int startSample,
  20749. const int numSamples) throw()
  20750. {
  20751. jassert (startSample >= 0 && startSample + numSamples <= size);
  20752. for (int i = 0; i < numChannels; ++i)
  20753. zeromem (channels [i] + startSample, numSamples * sizeof (float));
  20754. }
  20755. void AudioSampleBuffer::clear (const int channel,
  20756. const int startSample,
  20757. const int numSamples) throw()
  20758. {
  20759. jassert (((unsigned int) channel) < (unsigned int) numChannels);
  20760. jassert (startSample >= 0 && startSample + numSamples <= size);
  20761. zeromem (channels [channel] + startSample, numSamples * sizeof (float));
  20762. }
  20763. void AudioSampleBuffer::applyGain (const int channel,
  20764. const int startSample,
  20765. int numSamples,
  20766. const float gain) throw()
  20767. {
  20768. jassert (((unsigned int) channel) < (unsigned int) numChannels);
  20769. jassert (startSample >= 0 && startSample + numSamples <= size);
  20770. if (gain != 1.0f)
  20771. {
  20772. float* d = channels [channel] + startSample;
  20773. if (gain == 0.0f)
  20774. {
  20775. zeromem (d, sizeof (float) * numSamples);
  20776. }
  20777. else
  20778. {
  20779. while (--numSamples >= 0)
  20780. *d++ *= gain;
  20781. }
  20782. }
  20783. }
  20784. void AudioSampleBuffer::applyGainRamp (const int channel,
  20785. const int startSample,
  20786. int numSamples,
  20787. float startGain,
  20788. float endGain) throw()
  20789. {
  20790. if (startGain == endGain)
  20791. {
  20792. applyGain (channel, startSample, numSamples, startGain);
  20793. }
  20794. else
  20795. {
  20796. jassert (((unsigned int) channel) < (unsigned int) numChannels);
  20797. jassert (startSample >= 0 && startSample + numSamples <= size);
  20798. const float increment = (endGain - startGain) / numSamples;
  20799. float* d = channels [channel] + startSample;
  20800. while (--numSamples >= 0)
  20801. {
  20802. *d++ *= startGain;
  20803. startGain += increment;
  20804. }
  20805. }
  20806. }
  20807. void AudioSampleBuffer::applyGain (const int startSample,
  20808. const int numSamples,
  20809. const float gain) throw()
  20810. {
  20811. for (int i = 0; i < numChannels; ++i)
  20812. applyGain (i, startSample, numSamples, gain);
  20813. }
  20814. void AudioSampleBuffer::addFrom (const int destChannel,
  20815. const int destStartSample,
  20816. const AudioSampleBuffer& source,
  20817. const int sourceChannel,
  20818. const int sourceStartSample,
  20819. int numSamples,
  20820. const float gain) throw()
  20821. {
  20822. jassert (&source != this || sourceChannel != destChannel);
  20823. jassert (((unsigned int) destChannel) < (unsigned int) numChannels);
  20824. jassert (destStartSample >= 0 && destStartSample + numSamples <= size);
  20825. jassert (((unsigned int) sourceChannel) < (unsigned int) source.numChannels);
  20826. jassert (sourceStartSample >= 0 && sourceStartSample + numSamples <= source.size);
  20827. if (gain != 0.0f && numSamples > 0)
  20828. {
  20829. float* d = channels [destChannel] + destStartSample;
  20830. const float* s = source.channels [sourceChannel] + sourceStartSample;
  20831. if (gain != 1.0f)
  20832. {
  20833. while (--numSamples >= 0)
  20834. *d++ += gain * *s++;
  20835. }
  20836. else
  20837. {
  20838. while (--numSamples >= 0)
  20839. *d++ += *s++;
  20840. }
  20841. }
  20842. }
  20843. void AudioSampleBuffer::addFrom (const int destChannel,
  20844. const int destStartSample,
  20845. const float* source,
  20846. int numSamples,
  20847. const float gain) throw()
  20848. {
  20849. jassert (((unsigned int) destChannel) < (unsigned int) numChannels);
  20850. jassert (destStartSample >= 0 && destStartSample + numSamples <= size);
  20851. jassert (source != 0);
  20852. if (gain != 0.0f && numSamples > 0)
  20853. {
  20854. float* d = channels [destChannel] + destStartSample;
  20855. if (gain != 1.0f)
  20856. {
  20857. while (--numSamples >= 0)
  20858. *d++ += gain * *source++;
  20859. }
  20860. else
  20861. {
  20862. while (--numSamples >= 0)
  20863. *d++ += *source++;
  20864. }
  20865. }
  20866. }
  20867. void AudioSampleBuffer::addFromWithRamp (const int destChannel,
  20868. const int destStartSample,
  20869. const float* source,
  20870. int numSamples,
  20871. float startGain,
  20872. const float endGain) throw()
  20873. {
  20874. jassert (((unsigned int) destChannel) < (unsigned int) numChannels);
  20875. jassert (destStartSample >= 0 && destStartSample + numSamples <= size);
  20876. jassert (source != 0);
  20877. if (startGain == endGain)
  20878. {
  20879. addFrom (destChannel,
  20880. destStartSample,
  20881. source,
  20882. numSamples,
  20883. startGain);
  20884. }
  20885. else
  20886. {
  20887. if (numSamples > 0 && (startGain != 0.0f || endGain != 0.0f))
  20888. {
  20889. const float increment = (endGain - startGain) / numSamples;
  20890. float* d = channels [destChannel] + destStartSample;
  20891. while (--numSamples >= 0)
  20892. {
  20893. *d++ += startGain * *source++;
  20894. startGain += increment;
  20895. }
  20896. }
  20897. }
  20898. }
  20899. void AudioSampleBuffer::copyFrom (const int destChannel,
  20900. const int destStartSample,
  20901. const AudioSampleBuffer& source,
  20902. const int sourceChannel,
  20903. const int sourceStartSample,
  20904. int numSamples) throw()
  20905. {
  20906. jassert (&source != this || sourceChannel != destChannel);
  20907. jassert (((unsigned int) destChannel) < (unsigned int) numChannels);
  20908. jassert (destStartSample >= 0 && destStartSample + numSamples <= size);
  20909. jassert (((unsigned int) sourceChannel) < (unsigned int) source.numChannels);
  20910. jassert (sourceStartSample >= 0 && sourceStartSample + numSamples <= source.size);
  20911. if (numSamples > 0)
  20912. {
  20913. memcpy (channels [destChannel] + destStartSample,
  20914. source.channels [sourceChannel] + sourceStartSample,
  20915. sizeof (float) * numSamples);
  20916. }
  20917. }
  20918. void AudioSampleBuffer::copyFrom (const int destChannel,
  20919. const int destStartSample,
  20920. const float* source,
  20921. int numSamples) throw()
  20922. {
  20923. jassert (((unsigned int) destChannel) < (unsigned int) numChannels);
  20924. jassert (destStartSample >= 0 && destStartSample + numSamples <= size);
  20925. jassert (source != 0);
  20926. if (numSamples > 0)
  20927. {
  20928. memcpy (channels [destChannel] + destStartSample,
  20929. source,
  20930. sizeof (float) * numSamples);
  20931. }
  20932. }
  20933. void AudioSampleBuffer::copyFrom (const int destChannel,
  20934. const int destStartSample,
  20935. const float* source,
  20936. int numSamples,
  20937. const float gain) throw()
  20938. {
  20939. jassert (((unsigned int) destChannel) < (unsigned int) numChannels);
  20940. jassert (destStartSample >= 0 && destStartSample + numSamples <= size);
  20941. jassert (source != 0);
  20942. if (numSamples > 0)
  20943. {
  20944. float* d = channels [destChannel] + destStartSample;
  20945. if (gain != 1.0f)
  20946. {
  20947. if (gain == 0)
  20948. {
  20949. zeromem (d, sizeof (float) * numSamples);
  20950. }
  20951. else
  20952. {
  20953. while (--numSamples >= 0)
  20954. *d++ = gain * *source++;
  20955. }
  20956. }
  20957. else
  20958. {
  20959. memcpy (d, source, sizeof (float) * numSamples);
  20960. }
  20961. }
  20962. }
  20963. void AudioSampleBuffer::copyFromWithRamp (const int destChannel,
  20964. const int destStartSample,
  20965. const float* source,
  20966. int numSamples,
  20967. float startGain,
  20968. float endGain) throw()
  20969. {
  20970. jassert (((unsigned int) destChannel) < (unsigned int) numChannels);
  20971. jassert (destStartSample >= 0 && destStartSample + numSamples <= size);
  20972. jassert (source != 0);
  20973. if (startGain == endGain)
  20974. {
  20975. copyFrom (destChannel,
  20976. destStartSample,
  20977. source,
  20978. numSamples,
  20979. startGain);
  20980. }
  20981. else
  20982. {
  20983. if (numSamples > 0 && (startGain != 0.0f || endGain != 0.0f))
  20984. {
  20985. const float increment = (endGain - startGain) / numSamples;
  20986. float* d = channels [destChannel] + destStartSample;
  20987. while (--numSamples >= 0)
  20988. {
  20989. *d++ = startGain * *source++;
  20990. startGain += increment;
  20991. }
  20992. }
  20993. }
  20994. }
  20995. void AudioSampleBuffer::findMinMax (const int channel,
  20996. const int startSample,
  20997. int numSamples,
  20998. float& minVal,
  20999. float& maxVal) const throw()
  21000. {
  21001. jassert (((unsigned int) channel) < (unsigned int) numChannels);
  21002. jassert (startSample >= 0 && startSample + numSamples <= size);
  21003. if (numSamples <= 0)
  21004. {
  21005. minVal = 0.0f;
  21006. maxVal = 0.0f;
  21007. }
  21008. else
  21009. {
  21010. const float* d = channels [channel] + startSample;
  21011. float mn = *d++;
  21012. float mx = mn;
  21013. while (--numSamples > 0) // (> 0 rather than >= 0 because we've already taken the first sample)
  21014. {
  21015. const float samp = *d++;
  21016. if (samp > mx)
  21017. mx = samp;
  21018. if (samp < mn)
  21019. mn = samp;
  21020. }
  21021. maxVal = mx;
  21022. minVal = mn;
  21023. }
  21024. }
  21025. float AudioSampleBuffer::getMagnitude (const int channel,
  21026. const int startSample,
  21027. const int numSamples) const throw()
  21028. {
  21029. jassert (((unsigned int) channel) < (unsigned int) numChannels);
  21030. jassert (startSample >= 0 && startSample + numSamples <= size);
  21031. float mn, mx;
  21032. findMinMax (channel, startSample, numSamples, mn, mx);
  21033. return jmax (mn, -mn, mx, -mx);
  21034. }
  21035. float AudioSampleBuffer::getMagnitude (const int startSample,
  21036. const int numSamples) const throw()
  21037. {
  21038. float mag = 0.0f;
  21039. for (int i = 0; i < numChannels; ++i)
  21040. mag = jmax (mag, getMagnitude (i, startSample, numSamples));
  21041. return mag;
  21042. }
  21043. float AudioSampleBuffer::getRMSLevel (const int channel,
  21044. const int startSample,
  21045. const int numSamples) const throw()
  21046. {
  21047. jassert (((unsigned int) channel) < (unsigned int) numChannels);
  21048. jassert (startSample >= 0 && startSample + numSamples <= size);
  21049. if (numSamples <= 0 || channel < 0 || channel >= numChannels)
  21050. return 0.0f;
  21051. const float* const data = channels [channel] + startSample;
  21052. double sum = 0.0;
  21053. for (int i = 0; i < numSamples; ++i)
  21054. {
  21055. const float sample = data [i];
  21056. sum += sample * sample;
  21057. }
  21058. return (float) sqrt (sum / numSamples);
  21059. }
  21060. void AudioSampleBuffer::readFromAudioReader (AudioFormatReader* reader,
  21061. const int startSample,
  21062. const int numSamples,
  21063. const int readerStartSample,
  21064. const bool useLeftChan,
  21065. const bool useRightChan) throw()
  21066. {
  21067. jassert (reader != 0);
  21068. jassert (startSample >= 0 && startSample + numSamples <= size);
  21069. if (numSamples > 0)
  21070. {
  21071. int* chans[3];
  21072. if (useLeftChan == useRightChan)
  21073. {
  21074. chans[0] = (int*) getSampleData (0, startSample);
  21075. chans[1] = (reader->numChannels > 1 && getNumChannels() > 1) ? (int*) getSampleData (1, startSample) : 0;
  21076. }
  21077. else if (useLeftChan || (reader->numChannels == 1))
  21078. {
  21079. chans[0] = (int*) getSampleData (0, startSample);
  21080. chans[1] = 0;
  21081. }
  21082. else if (useRightChan)
  21083. {
  21084. chans[0] = 0;
  21085. chans[1] = (int*) getSampleData (0, startSample);
  21086. }
  21087. chans[2] = 0;
  21088. reader->read (chans, 2, readerStartSample, numSamples, true);
  21089. if (! reader->usesFloatingPointData)
  21090. {
  21091. for (int j = 0; j < 2; ++j)
  21092. {
  21093. float* const d = reinterpret_cast <float*> (chans[j]);
  21094. if (d != 0)
  21095. {
  21096. const float multiplier = 1.0f / 0x7fffffff;
  21097. for (int i = 0; i < numSamples; ++i)
  21098. d[i] = *(int*)(d + i) * multiplier;
  21099. }
  21100. }
  21101. }
  21102. if (numChannels > 1 && (chans[0] == 0 || chans[1] == 0))
  21103. {
  21104. // if this is a stereo buffer and the source was mono, dupe the first channel..
  21105. memcpy (getSampleData (1, startSample),
  21106. getSampleData (0, startSample),
  21107. sizeof (float) * numSamples);
  21108. }
  21109. }
  21110. }
  21111. void AudioSampleBuffer::writeToAudioWriter (AudioFormatWriter* writer,
  21112. const int startSample,
  21113. const int numSamples) const throw()
  21114. {
  21115. jassert (startSample >= 0 && startSample + numSamples <= size);
  21116. if (numSamples > 0)
  21117. {
  21118. int* chans [3];
  21119. if (writer->isFloatingPoint())
  21120. {
  21121. chans[0] = (int*) getSampleData (0, startSample);
  21122. if (numChannels > 1)
  21123. chans[1] = (int*) getSampleData (1, startSample);
  21124. else
  21125. chans[1] = 0;
  21126. chans[2] = 0;
  21127. writer->write ((const int**) chans, numSamples);
  21128. }
  21129. else
  21130. {
  21131. HeapBlock <int> tempBuffer (numSamples * 2);
  21132. chans[0] = tempBuffer;
  21133. if (numChannels > 1)
  21134. chans[1] = chans[0] + numSamples;
  21135. else
  21136. chans[1] = 0;
  21137. chans[2] = 0;
  21138. for (int j = 0; j < 2; ++j)
  21139. {
  21140. int* const dest = chans[j];
  21141. if (dest != 0)
  21142. {
  21143. const float* const src = channels [j] + startSample;
  21144. for (int i = 0; i < numSamples; ++i)
  21145. {
  21146. const double samp = src[i];
  21147. if (samp <= -1.0)
  21148. dest[i] = std::numeric_limits<int>::min();
  21149. else if (samp >= 1.0)
  21150. dest[i] = std::numeric_limits<int>::max();
  21151. else
  21152. dest[i] = roundToInt (std::numeric_limits<int>::max() * samp);
  21153. }
  21154. }
  21155. }
  21156. writer->write ((const int**) chans, numSamples);
  21157. }
  21158. }
  21159. }
  21160. END_JUCE_NAMESPACE
  21161. /*** End of inlined file: juce_AudioSampleBuffer.cpp ***/
  21162. /*** Start of inlined file: juce_IIRFilter.cpp ***/
  21163. BEGIN_JUCE_NAMESPACE
  21164. IIRFilter::IIRFilter()
  21165. : active (false)
  21166. {
  21167. reset();
  21168. }
  21169. IIRFilter::IIRFilter (const IIRFilter& other)
  21170. : active (other.active)
  21171. {
  21172. const ScopedLock sl (other.processLock);
  21173. memcpy (coefficients, other.coefficients, sizeof (coefficients));
  21174. reset();
  21175. }
  21176. IIRFilter::~IIRFilter()
  21177. {
  21178. }
  21179. void IIRFilter::reset() throw()
  21180. {
  21181. const ScopedLock sl (processLock);
  21182. x1 = 0;
  21183. x2 = 0;
  21184. y1 = 0;
  21185. y2 = 0;
  21186. }
  21187. float IIRFilter::processSingleSampleRaw (const float in) throw()
  21188. {
  21189. float out = coefficients[0] * in
  21190. + coefficients[1] * x1
  21191. + coefficients[2] * x2
  21192. - coefficients[4] * y1
  21193. - coefficients[5] * y2;
  21194. #if JUCE_INTEL
  21195. if (! (out < -1.0e-8 || out > 1.0e-8))
  21196. out = 0;
  21197. #endif
  21198. x2 = x1;
  21199. x1 = in;
  21200. y2 = y1;
  21201. y1 = out;
  21202. return out;
  21203. }
  21204. void IIRFilter::processSamples (float* const samples,
  21205. const int numSamples) throw()
  21206. {
  21207. const ScopedLock sl (processLock);
  21208. if (active)
  21209. {
  21210. for (int i = 0; i < numSamples; ++i)
  21211. {
  21212. const float in = samples[i];
  21213. float out = coefficients[0] * in
  21214. + coefficients[1] * x1
  21215. + coefficients[2] * x2
  21216. - coefficients[4] * y1
  21217. - coefficients[5] * y2;
  21218. #if JUCE_INTEL
  21219. if (! (out < -1.0e-8 || out > 1.0e-8))
  21220. out = 0;
  21221. #endif
  21222. x2 = x1;
  21223. x1 = in;
  21224. y2 = y1;
  21225. y1 = out;
  21226. samples[i] = out;
  21227. }
  21228. }
  21229. }
  21230. void IIRFilter::makeLowPass (const double sampleRate,
  21231. const double frequency) throw()
  21232. {
  21233. jassert (sampleRate > 0);
  21234. const double n = 1.0 / tan (double_Pi * frequency / sampleRate);
  21235. const double nSquared = n * n;
  21236. const double c1 = 1.0 / (1.0 + sqrt (2.0) * n + nSquared);
  21237. setCoefficients (c1,
  21238. c1 * 2.0f,
  21239. c1,
  21240. 1.0,
  21241. c1 * 2.0 * (1.0 - nSquared),
  21242. c1 * (1.0 - sqrt (2.0) * n + nSquared));
  21243. }
  21244. void IIRFilter::makeHighPass (const double sampleRate,
  21245. const double frequency) throw()
  21246. {
  21247. const double n = tan (double_Pi * frequency / sampleRate);
  21248. const double nSquared = n * n;
  21249. const double c1 = 1.0 / (1.0 + sqrt (2.0) * n + nSquared);
  21250. setCoefficients (c1,
  21251. c1 * -2.0f,
  21252. c1,
  21253. 1.0,
  21254. c1 * 2.0 * (nSquared - 1.0),
  21255. c1 * (1.0 - sqrt (2.0) * n + nSquared));
  21256. }
  21257. void IIRFilter::makeLowShelf (const double sampleRate,
  21258. const double cutOffFrequency,
  21259. const double Q,
  21260. const float gainFactor) throw()
  21261. {
  21262. jassert (sampleRate > 0);
  21263. jassert (Q > 0);
  21264. const double A = jmax (0.0f, gainFactor);
  21265. const double aminus1 = A - 1.0;
  21266. const double aplus1 = A + 1.0;
  21267. const double omega = (double_Pi * 2.0 * jmax (cutOffFrequency, 2.0)) / sampleRate;
  21268. const double coso = cos (omega);
  21269. const double beta = sin (omega) * sqrt (A) / Q;
  21270. const double aminus1TimesCoso = aminus1 * coso;
  21271. setCoefficients (A * (aplus1 - aminus1TimesCoso + beta),
  21272. A * 2.0 * (aminus1 - aplus1 * coso),
  21273. A * (aplus1 - aminus1TimesCoso - beta),
  21274. aplus1 + aminus1TimesCoso + beta,
  21275. -2.0 * (aminus1 + aplus1 * coso),
  21276. aplus1 + aminus1TimesCoso - beta);
  21277. }
  21278. void IIRFilter::makeHighShelf (const double sampleRate,
  21279. const double cutOffFrequency,
  21280. const double Q,
  21281. const float gainFactor) throw()
  21282. {
  21283. jassert (sampleRate > 0);
  21284. jassert (Q > 0);
  21285. const double A = jmax (0.0f, gainFactor);
  21286. const double aminus1 = A - 1.0;
  21287. const double aplus1 = A + 1.0;
  21288. const double omega = (double_Pi * 2.0 * jmax (cutOffFrequency, 2.0)) / sampleRate;
  21289. const double coso = cos (omega);
  21290. const double beta = sin (omega) * sqrt (A) / Q;
  21291. const double aminus1TimesCoso = aminus1 * coso;
  21292. setCoefficients (A * (aplus1 + aminus1TimesCoso + beta),
  21293. A * -2.0 * (aminus1 + aplus1 * coso),
  21294. A * (aplus1 + aminus1TimesCoso - beta),
  21295. aplus1 - aminus1TimesCoso + beta,
  21296. 2.0 * (aminus1 - aplus1 * coso),
  21297. aplus1 - aminus1TimesCoso - beta);
  21298. }
  21299. void IIRFilter::makeBandPass (const double sampleRate,
  21300. const double centreFrequency,
  21301. const double Q,
  21302. const float gainFactor) throw()
  21303. {
  21304. jassert (sampleRate > 0);
  21305. jassert (Q > 0);
  21306. const double A = jmax (0.0f, gainFactor);
  21307. const double omega = (double_Pi * 2.0 * jmax (centreFrequency, 2.0)) / sampleRate;
  21308. const double alpha = 0.5 * sin (omega) / Q;
  21309. const double c2 = -2.0 * cos (omega);
  21310. const double alphaTimesA = alpha * A;
  21311. const double alphaOverA = alpha / A;
  21312. setCoefficients (1.0 + alphaTimesA,
  21313. c2,
  21314. 1.0 - alphaTimesA,
  21315. 1.0 + alphaOverA,
  21316. c2,
  21317. 1.0 - alphaOverA);
  21318. }
  21319. void IIRFilter::makeInactive() throw()
  21320. {
  21321. const ScopedLock sl (processLock);
  21322. active = false;
  21323. }
  21324. void IIRFilter::copyCoefficientsFrom (const IIRFilter& other) throw()
  21325. {
  21326. const ScopedLock sl (processLock);
  21327. memcpy (coefficients, other.coefficients, sizeof (coefficients));
  21328. active = other.active;
  21329. }
  21330. void IIRFilter::setCoefficients (double c1,
  21331. double c2,
  21332. double c3,
  21333. double c4,
  21334. double c5,
  21335. double c6) throw()
  21336. {
  21337. const double a = 1.0 / c4;
  21338. c1 *= a;
  21339. c2 *= a;
  21340. c3 *= a;
  21341. c5 *= a;
  21342. c6 *= a;
  21343. const ScopedLock sl (processLock);
  21344. coefficients[0] = (float) c1;
  21345. coefficients[1] = (float) c2;
  21346. coefficients[2] = (float) c3;
  21347. coefficients[3] = (float) c4;
  21348. coefficients[4] = (float) c5;
  21349. coefficients[5] = (float) c6;
  21350. active = true;
  21351. }
  21352. END_JUCE_NAMESPACE
  21353. /*** End of inlined file: juce_IIRFilter.cpp ***/
  21354. /*** Start of inlined file: juce_MidiBuffer.cpp ***/
  21355. BEGIN_JUCE_NAMESPACE
  21356. MidiBuffer::MidiBuffer() throw()
  21357. : bytesUsed (0)
  21358. {
  21359. }
  21360. MidiBuffer::MidiBuffer (const MidiMessage& message) throw()
  21361. : bytesUsed (0)
  21362. {
  21363. addEvent (message, 0);
  21364. }
  21365. MidiBuffer::MidiBuffer (const MidiBuffer& other) throw()
  21366. : data (other.data),
  21367. bytesUsed (other.bytesUsed)
  21368. {
  21369. }
  21370. MidiBuffer& MidiBuffer::operator= (const MidiBuffer& other) throw()
  21371. {
  21372. bytesUsed = other.bytesUsed;
  21373. data = other.data;
  21374. return *this;
  21375. }
  21376. void MidiBuffer::swapWith (MidiBuffer& other)
  21377. {
  21378. data.swapWith (other.data);
  21379. swapVariables <int> (bytesUsed, other.bytesUsed);
  21380. }
  21381. MidiBuffer::~MidiBuffer() throw()
  21382. {
  21383. }
  21384. inline uint8* MidiBuffer::getData() const throw()
  21385. {
  21386. return static_cast <uint8*> (data.getData());
  21387. }
  21388. inline int MidiBuffer::getEventTime (const void* const d) throw()
  21389. {
  21390. return *static_cast <const int*> (d);
  21391. }
  21392. inline uint16 MidiBuffer::getEventDataSize (const void* const d) throw()
  21393. {
  21394. return *reinterpret_cast <const uint16*> (static_cast <const char*> (d) + sizeof (int));
  21395. }
  21396. inline uint16 MidiBuffer::getEventTotalSize (const void* const d) throw()
  21397. {
  21398. return getEventDataSize (d) + sizeof (int) + sizeof (uint16);
  21399. }
  21400. void MidiBuffer::clear() throw()
  21401. {
  21402. bytesUsed = 0;
  21403. }
  21404. void MidiBuffer::clear (const int startSample,
  21405. const int numSamples) throw()
  21406. {
  21407. uint8* const start = findEventAfter (getData(), startSample - 1);
  21408. uint8* const end = findEventAfter (start, startSample + numSamples - 1);
  21409. if (end > start)
  21410. {
  21411. const int bytesToMove = bytesUsed - (int) (end - getData());
  21412. if (bytesToMove > 0)
  21413. memmove (start, end, bytesToMove);
  21414. bytesUsed -= (int) (end - start);
  21415. }
  21416. }
  21417. void MidiBuffer::addEvent (const MidiMessage& m,
  21418. const int sampleNumber) throw()
  21419. {
  21420. addEvent (m.getRawData(), m.getRawDataSize(), sampleNumber);
  21421. }
  21422. static int findActualEventLength (const uint8* const data,
  21423. const int maxBytes) throw()
  21424. {
  21425. unsigned int byte = (unsigned int) *data;
  21426. int size = 0;
  21427. if (byte == 0xf0 || byte == 0xf7)
  21428. {
  21429. const uint8* d = data + 1;
  21430. while (d < data + maxBytes)
  21431. if (*d++ == 0xf7)
  21432. break;
  21433. size = (int) (d - data);
  21434. }
  21435. else if (byte == 0xff)
  21436. {
  21437. int n;
  21438. const int bytesLeft = MidiMessage::readVariableLengthVal (data + 1, n);
  21439. size = jmin (maxBytes, n + 2 + bytesLeft);
  21440. }
  21441. else if (byte >= 0x80)
  21442. {
  21443. size = jmin (maxBytes, MidiMessage::getMessageLengthFromFirstByte ((uint8) byte));
  21444. }
  21445. return size;
  21446. }
  21447. void MidiBuffer::addEvent (const uint8* const newData,
  21448. const int maxBytes,
  21449. const int sampleNumber) throw()
  21450. {
  21451. const int numBytes = findActualEventLength (newData, maxBytes);
  21452. if (numBytes > 0)
  21453. {
  21454. int spaceNeeded = bytesUsed + numBytes + sizeof (int) + sizeof (uint16);
  21455. data.ensureSize ((spaceNeeded + spaceNeeded / 2 + 8) & ~7);
  21456. uint8* d = findEventAfter (getData(), sampleNumber);
  21457. const int bytesToMove = bytesUsed - (int) (d - getData());
  21458. if (bytesToMove > 0)
  21459. memmove (d + numBytes + sizeof (int) + sizeof (uint16), d, bytesToMove);
  21460. *reinterpret_cast <int*> (d) = sampleNumber;
  21461. d += sizeof (int);
  21462. *reinterpret_cast <uint16*> (d) = (uint16) numBytes;
  21463. d += sizeof (uint16);
  21464. memcpy (d, newData, numBytes);
  21465. bytesUsed += numBytes + sizeof (int) + sizeof (uint16);
  21466. }
  21467. }
  21468. void MidiBuffer::addEvents (const MidiBuffer& otherBuffer,
  21469. const int startSample,
  21470. const int numSamples,
  21471. const int sampleDeltaToAdd) throw()
  21472. {
  21473. Iterator i (otherBuffer);
  21474. i.setNextSamplePosition (startSample);
  21475. const uint8* eventData;
  21476. int eventSize, position;
  21477. while (i.getNextEvent (eventData, eventSize, position)
  21478. && (position < startSample + numSamples || numSamples < 0))
  21479. {
  21480. addEvent (eventData, eventSize, position + sampleDeltaToAdd);
  21481. }
  21482. }
  21483. void MidiBuffer::ensureSize (size_t minimumNumBytes)
  21484. {
  21485. data.ensureSize (minimumNumBytes);
  21486. }
  21487. bool MidiBuffer::isEmpty() const throw()
  21488. {
  21489. return bytesUsed == 0;
  21490. }
  21491. int MidiBuffer::getNumEvents() const throw()
  21492. {
  21493. int n = 0;
  21494. const uint8* d = getData();
  21495. const uint8* const end = d + bytesUsed;
  21496. while (d < end)
  21497. {
  21498. d += getEventTotalSize (d);
  21499. ++n;
  21500. }
  21501. return n;
  21502. }
  21503. int MidiBuffer::getFirstEventTime() const throw()
  21504. {
  21505. return bytesUsed > 0 ? getEventTime (data.getData()) : 0;
  21506. }
  21507. int MidiBuffer::getLastEventTime() const throw()
  21508. {
  21509. if (bytesUsed == 0)
  21510. return 0;
  21511. const uint8* d = getData();
  21512. const uint8* const endData = d + bytesUsed;
  21513. for (;;)
  21514. {
  21515. const uint8* const nextOne = d + getEventTotalSize (d);
  21516. if (nextOne >= endData)
  21517. return getEventTime (d);
  21518. d = nextOne;
  21519. }
  21520. }
  21521. uint8* MidiBuffer::findEventAfter (uint8* d, const int samplePosition) const throw()
  21522. {
  21523. const uint8* const endData = getData() + bytesUsed;
  21524. while (d < endData && getEventTime (d) <= samplePosition)
  21525. d += getEventTotalSize (d);
  21526. return d;
  21527. }
  21528. MidiBuffer::Iterator::Iterator (const MidiBuffer& buffer_) throw()
  21529. : buffer (buffer_),
  21530. data (buffer_.getData())
  21531. {
  21532. }
  21533. MidiBuffer::Iterator::~Iterator() throw()
  21534. {
  21535. }
  21536. void MidiBuffer::Iterator::setNextSamplePosition (const int samplePosition) throw()
  21537. {
  21538. data = buffer.getData();
  21539. const uint8* dataEnd = data + buffer.bytesUsed;
  21540. while (data < dataEnd && getEventTime (data) < samplePosition)
  21541. data += getEventTotalSize (data);
  21542. }
  21543. bool MidiBuffer::Iterator::getNextEvent (const uint8* &midiData, int& numBytes, int& samplePosition) throw()
  21544. {
  21545. if (data >= buffer.getData() + buffer.bytesUsed)
  21546. return false;
  21547. samplePosition = getEventTime (data);
  21548. numBytes = getEventDataSize (data);
  21549. data += sizeof (int) + sizeof (uint16);
  21550. midiData = data;
  21551. data += numBytes;
  21552. return true;
  21553. }
  21554. bool MidiBuffer::Iterator::getNextEvent (MidiMessage& result, int& samplePosition) throw()
  21555. {
  21556. if (data >= buffer.getData() + buffer.bytesUsed)
  21557. return false;
  21558. samplePosition = getEventTime (data);
  21559. const int numBytes = getEventDataSize (data);
  21560. data += sizeof (int) + sizeof (uint16);
  21561. result = MidiMessage (data, numBytes, samplePosition);
  21562. data += numBytes;
  21563. return true;
  21564. }
  21565. END_JUCE_NAMESPACE
  21566. /*** End of inlined file: juce_MidiBuffer.cpp ***/
  21567. /*** Start of inlined file: juce_MidiFile.cpp ***/
  21568. BEGIN_JUCE_NAMESPACE
  21569. namespace MidiFileHelpers
  21570. {
  21571. static void writeVariableLengthInt (OutputStream& out, unsigned int v)
  21572. {
  21573. unsigned int buffer = v & 0x7F;
  21574. while ((v >>= 7) != 0)
  21575. {
  21576. buffer <<= 8;
  21577. buffer |= ((v & 0x7F) | 0x80);
  21578. }
  21579. for (;;)
  21580. {
  21581. out.writeByte ((char) buffer);
  21582. if (buffer & 0x80)
  21583. buffer >>= 8;
  21584. else
  21585. break;
  21586. }
  21587. }
  21588. static bool parseMidiHeader (const uint8* &data, short& timeFormat, short& fileType, short& numberOfTracks) throw()
  21589. {
  21590. unsigned int ch = (int) ByteOrder::bigEndianInt (data);
  21591. data += 4;
  21592. if (ch != ByteOrder::bigEndianInt ("MThd"))
  21593. {
  21594. bool ok = false;
  21595. if (ch == ByteOrder::bigEndianInt ("RIFF"))
  21596. {
  21597. for (int i = 0; i < 8; ++i)
  21598. {
  21599. ch = ByteOrder::bigEndianInt (data);
  21600. data += 4;
  21601. if (ch == ByteOrder::bigEndianInt ("MThd"))
  21602. {
  21603. ok = true;
  21604. break;
  21605. }
  21606. }
  21607. }
  21608. if (! ok)
  21609. return false;
  21610. }
  21611. unsigned int bytesRemaining = ByteOrder::bigEndianInt (data);
  21612. data += 4;
  21613. fileType = (short) ByteOrder::bigEndianShort (data);
  21614. data += 2;
  21615. numberOfTracks = (short) ByteOrder::bigEndianShort (data);
  21616. data += 2;
  21617. timeFormat = (short) ByteOrder::bigEndianShort (data);
  21618. data += 2;
  21619. bytesRemaining -= 6;
  21620. data += bytesRemaining;
  21621. return true;
  21622. }
  21623. static double convertTicksToSeconds (const double time,
  21624. const MidiMessageSequence& tempoEvents,
  21625. const int timeFormat)
  21626. {
  21627. if (timeFormat > 0)
  21628. {
  21629. int numer = 4, denom = 4;
  21630. double tempoTime = 0.0, correctedTempoTime = 0.0;
  21631. const double tickLen = 1.0 / (timeFormat & 0x7fff);
  21632. double secsPerTick = 0.5 * tickLen;
  21633. const int numEvents = tempoEvents.getNumEvents();
  21634. for (int i = 0; i < numEvents; ++i)
  21635. {
  21636. const MidiMessage& m = tempoEvents.getEventPointer(i)->message;
  21637. if (time <= m.getTimeStamp())
  21638. break;
  21639. if (timeFormat > 0)
  21640. {
  21641. correctedTempoTime = correctedTempoTime
  21642. + (m.getTimeStamp() - tempoTime) * secsPerTick;
  21643. }
  21644. else
  21645. {
  21646. correctedTempoTime = tickLen * m.getTimeStamp() / (((timeFormat & 0x7fff) >> 8) * (timeFormat & 0xff));
  21647. }
  21648. tempoTime = m.getTimeStamp();
  21649. if (m.isTempoMetaEvent())
  21650. secsPerTick = tickLen * m.getTempoSecondsPerQuarterNote();
  21651. else if (m.isTimeSignatureMetaEvent())
  21652. m.getTimeSignatureInfo (numer, denom);
  21653. while (i + 1 < numEvents)
  21654. {
  21655. const MidiMessage& m2 = tempoEvents.getEventPointer(i + 1)->message;
  21656. if (m2.getTimeStamp() == tempoTime)
  21657. {
  21658. ++i;
  21659. if (m2.isTempoMetaEvent())
  21660. secsPerTick = tickLen * m2.getTempoSecondsPerQuarterNote();
  21661. else if (m2.isTimeSignatureMetaEvent())
  21662. m2.getTimeSignatureInfo (numer, denom);
  21663. }
  21664. else
  21665. {
  21666. break;
  21667. }
  21668. }
  21669. }
  21670. return correctedTempoTime + (time - tempoTime) * secsPerTick;
  21671. }
  21672. else
  21673. {
  21674. return time / (((timeFormat & 0x7fff) >> 8) * (timeFormat & 0xff));
  21675. }
  21676. }
  21677. }
  21678. MidiFile::MidiFile()
  21679. : timeFormat ((short) (unsigned short) 0xe728)
  21680. {
  21681. }
  21682. MidiFile::~MidiFile()
  21683. {
  21684. clear();
  21685. }
  21686. void MidiFile::clear()
  21687. {
  21688. tracks.clear();
  21689. }
  21690. int MidiFile::getNumTracks() const throw()
  21691. {
  21692. return tracks.size();
  21693. }
  21694. const MidiMessageSequence* MidiFile::getTrack (const int index) const throw()
  21695. {
  21696. return tracks [index];
  21697. }
  21698. void MidiFile::addTrack (const MidiMessageSequence& trackSequence)
  21699. {
  21700. tracks.add (new MidiMessageSequence (trackSequence));
  21701. }
  21702. short MidiFile::getTimeFormat() const throw()
  21703. {
  21704. return timeFormat;
  21705. }
  21706. void MidiFile::setTicksPerQuarterNote (const int ticks) throw()
  21707. {
  21708. timeFormat = (short) ticks;
  21709. }
  21710. void MidiFile::setSmpteTimeFormat (const int framesPerSecond,
  21711. const int subframeResolution) throw()
  21712. {
  21713. timeFormat = (short) (((-framesPerSecond) << 8) | subframeResolution);
  21714. }
  21715. void MidiFile::findAllTempoEvents (MidiMessageSequence& tempoChangeEvents) const
  21716. {
  21717. for (int i = tracks.size(); --i >= 0;)
  21718. {
  21719. const int numEvents = tracks.getUnchecked(i)->getNumEvents();
  21720. for (int j = 0; j < numEvents; ++j)
  21721. {
  21722. const MidiMessage& m = tracks.getUnchecked(i)->getEventPointer (j)->message;
  21723. if (m.isTempoMetaEvent())
  21724. tempoChangeEvents.addEvent (m);
  21725. }
  21726. }
  21727. }
  21728. void MidiFile::findAllTimeSigEvents (MidiMessageSequence& timeSigEvents) const
  21729. {
  21730. for (int i = tracks.size(); --i >= 0;)
  21731. {
  21732. const int numEvents = tracks.getUnchecked(i)->getNumEvents();
  21733. for (int j = 0; j < numEvents; ++j)
  21734. {
  21735. const MidiMessage& m = tracks.getUnchecked(i)->getEventPointer (j)->message;
  21736. if (m.isTimeSignatureMetaEvent())
  21737. timeSigEvents.addEvent (m);
  21738. }
  21739. }
  21740. }
  21741. double MidiFile::getLastTimestamp() const
  21742. {
  21743. double t = 0.0;
  21744. for (int i = tracks.size(); --i >= 0;)
  21745. t = jmax (t, tracks.getUnchecked(i)->getEndTime());
  21746. return t;
  21747. }
  21748. bool MidiFile::readFrom (InputStream& sourceStream)
  21749. {
  21750. clear();
  21751. MemoryBlock data;
  21752. const int maxSensibleMidiFileSize = 2 * 1024 * 1024;
  21753. // (put a sanity-check on the file size, as midi files are generally small)
  21754. if (sourceStream.readIntoMemoryBlock (data, maxSensibleMidiFileSize))
  21755. {
  21756. size_t size = data.getSize();
  21757. const uint8* d = static_cast <const uint8*> (data.getData());
  21758. short fileType, expectedTracks;
  21759. if (size > 16 && MidiFileHelpers::parseMidiHeader (d, timeFormat, fileType, expectedTracks))
  21760. {
  21761. size -= (int) (d - static_cast <const uint8*> (data.getData()));
  21762. int track = 0;
  21763. while (size > 0 && track < expectedTracks)
  21764. {
  21765. const int chunkType = (int) ByteOrder::bigEndianInt (d);
  21766. d += 4;
  21767. const int chunkSize = (int) ByteOrder::bigEndianInt (d);
  21768. d += 4;
  21769. if (chunkSize <= 0)
  21770. break;
  21771. if (size < 0)
  21772. return false;
  21773. if (chunkType == (int) ByteOrder::bigEndianInt ("MTrk"))
  21774. {
  21775. readNextTrack (d, chunkSize);
  21776. }
  21777. size -= chunkSize + 8;
  21778. d += chunkSize;
  21779. ++track;
  21780. }
  21781. return true;
  21782. }
  21783. }
  21784. return false;
  21785. }
  21786. // a comparator that puts all the note-offs before note-ons that have the same time
  21787. int MidiFile::compareElements (const MidiMessageSequence::MidiEventHolder* const first,
  21788. const MidiMessageSequence::MidiEventHolder* const second)
  21789. {
  21790. const double diff = (first->message.getTimeStamp() - second->message.getTimeStamp());
  21791. if (diff == 0)
  21792. {
  21793. if (first->message.isNoteOff() && second->message.isNoteOn())
  21794. return -1;
  21795. else if (first->message.isNoteOn() && second->message.isNoteOff())
  21796. return 1;
  21797. else
  21798. return 0;
  21799. }
  21800. else
  21801. {
  21802. return (diff > 0) ? 1 : -1;
  21803. }
  21804. }
  21805. void MidiFile::readNextTrack (const uint8* data, int size)
  21806. {
  21807. double time = 0;
  21808. char lastStatusByte = 0;
  21809. MidiMessageSequence result;
  21810. while (size > 0)
  21811. {
  21812. int bytesUsed;
  21813. const int delay = MidiMessage::readVariableLengthVal (data, bytesUsed);
  21814. data += bytesUsed;
  21815. size -= bytesUsed;
  21816. time += delay;
  21817. int messSize = 0;
  21818. const MidiMessage mm (data, size, messSize, lastStatusByte, time);
  21819. if (messSize <= 0)
  21820. break;
  21821. size -= messSize;
  21822. data += messSize;
  21823. result.addEvent (mm);
  21824. const char firstByte = *(mm.getRawData());
  21825. if ((firstByte & 0xf0) != 0xf0)
  21826. lastStatusByte = firstByte;
  21827. }
  21828. // use a sort that puts all the note-offs before note-ons that have the same time
  21829. result.list.sort (*this, true);
  21830. result.updateMatchedPairs();
  21831. addTrack (result);
  21832. }
  21833. void MidiFile::convertTimestampTicksToSeconds()
  21834. {
  21835. MidiMessageSequence tempoEvents;
  21836. findAllTempoEvents (tempoEvents);
  21837. findAllTimeSigEvents (tempoEvents);
  21838. for (int i = 0; i < tracks.size(); ++i)
  21839. {
  21840. MidiMessageSequence& ms = *tracks.getUnchecked(i);
  21841. for (int j = ms.getNumEvents(); --j >= 0;)
  21842. {
  21843. MidiMessage& m = ms.getEventPointer(j)->message;
  21844. m.setTimeStamp (MidiFileHelpers::convertTicksToSeconds (m.getTimeStamp(),
  21845. tempoEvents,
  21846. timeFormat));
  21847. }
  21848. }
  21849. }
  21850. bool MidiFile::writeTo (OutputStream& out)
  21851. {
  21852. out.writeIntBigEndian ((int) ByteOrder::bigEndianInt ("MThd"));
  21853. out.writeIntBigEndian (6);
  21854. out.writeShortBigEndian (1); // type
  21855. out.writeShortBigEndian ((short) tracks.size());
  21856. out.writeShortBigEndian (timeFormat);
  21857. for (int i = 0; i < tracks.size(); ++i)
  21858. writeTrack (out, i);
  21859. out.flush();
  21860. return true;
  21861. }
  21862. void MidiFile::writeTrack (OutputStream& mainOut,
  21863. const int trackNum)
  21864. {
  21865. MemoryOutputStream out;
  21866. const MidiMessageSequence& ms = *tracks[trackNum];
  21867. int lastTick = 0;
  21868. char lastStatusByte = 0;
  21869. for (int i = 0; i < ms.getNumEvents(); ++i)
  21870. {
  21871. const MidiMessage& mm = ms.getEventPointer(i)->message;
  21872. const int tick = roundToInt (mm.getTimeStamp());
  21873. const int delta = jmax (0, tick - lastTick);
  21874. MidiFileHelpers::writeVariableLengthInt (out, delta);
  21875. lastTick = tick;
  21876. const char statusByte = *(mm.getRawData());
  21877. if ((statusByte == lastStatusByte)
  21878. && ((statusByte & 0xf0) != 0xf0)
  21879. && i > 0
  21880. && mm.getRawDataSize() > 1)
  21881. {
  21882. out.write (mm.getRawData() + 1, mm.getRawDataSize() - 1);
  21883. }
  21884. else
  21885. {
  21886. out.write (mm.getRawData(), mm.getRawDataSize());
  21887. }
  21888. lastStatusByte = statusByte;
  21889. }
  21890. out.writeByte (0);
  21891. const MidiMessage m (MidiMessage::endOfTrack());
  21892. out.write (m.getRawData(),
  21893. m.getRawDataSize());
  21894. mainOut.writeIntBigEndian ((int) ByteOrder::bigEndianInt ("MTrk"));
  21895. mainOut.writeIntBigEndian ((int) out.getDataSize());
  21896. mainOut.write (out.getData(), (int) out.getDataSize());
  21897. }
  21898. END_JUCE_NAMESPACE
  21899. /*** End of inlined file: juce_MidiFile.cpp ***/
  21900. /*** Start of inlined file: juce_MidiKeyboardState.cpp ***/
  21901. BEGIN_JUCE_NAMESPACE
  21902. MidiKeyboardState::MidiKeyboardState()
  21903. {
  21904. zerostruct (noteStates);
  21905. }
  21906. MidiKeyboardState::~MidiKeyboardState()
  21907. {
  21908. }
  21909. void MidiKeyboardState::reset()
  21910. {
  21911. const ScopedLock sl (lock);
  21912. zerostruct (noteStates);
  21913. eventsToAdd.clear();
  21914. }
  21915. bool MidiKeyboardState::isNoteOn (const int midiChannel, const int n) const throw()
  21916. {
  21917. jassert (midiChannel >= 0 && midiChannel <= 16);
  21918. return ((unsigned int) n) < 128
  21919. && (noteStates[n] & (1 << (midiChannel - 1))) != 0;
  21920. }
  21921. bool MidiKeyboardState::isNoteOnForChannels (const int midiChannelMask, const int n) const throw()
  21922. {
  21923. return ((unsigned int) n) < 128
  21924. && (noteStates[n] & midiChannelMask) != 0;
  21925. }
  21926. void MidiKeyboardState::noteOn (const int midiChannel, const int midiNoteNumber, const float velocity)
  21927. {
  21928. jassert (midiChannel >= 0 && midiChannel <= 16);
  21929. jassert (((unsigned int) midiNoteNumber) < 128);
  21930. const ScopedLock sl (lock);
  21931. if (((unsigned int) midiNoteNumber) < 128)
  21932. {
  21933. const int timeNow = (int) Time::getMillisecondCounter();
  21934. eventsToAdd.addEvent (MidiMessage::noteOn (midiChannel, midiNoteNumber, velocity), timeNow);
  21935. eventsToAdd.clear (0, timeNow - 500);
  21936. noteOnInternal (midiChannel, midiNoteNumber, velocity);
  21937. }
  21938. }
  21939. void MidiKeyboardState::noteOnInternal (const int midiChannel, const int midiNoteNumber, const float velocity)
  21940. {
  21941. if (((unsigned int) midiNoteNumber) < 128)
  21942. {
  21943. noteStates [midiNoteNumber] |= (1 << (midiChannel - 1));
  21944. for (int i = listeners.size(); --i >= 0;)
  21945. listeners.getUnchecked(i)->handleNoteOn (this, midiChannel, midiNoteNumber, velocity);
  21946. }
  21947. }
  21948. void MidiKeyboardState::noteOff (const int midiChannel, const int midiNoteNumber)
  21949. {
  21950. const ScopedLock sl (lock);
  21951. if (isNoteOn (midiChannel, midiNoteNumber))
  21952. {
  21953. const int timeNow = (int) Time::getMillisecondCounter();
  21954. eventsToAdd.addEvent (MidiMessage::noteOff (midiChannel, midiNoteNumber), timeNow);
  21955. eventsToAdd.clear (0, timeNow - 500);
  21956. noteOffInternal (midiChannel, midiNoteNumber);
  21957. }
  21958. }
  21959. void MidiKeyboardState::noteOffInternal (const int midiChannel, const int midiNoteNumber)
  21960. {
  21961. if (isNoteOn (midiChannel, midiNoteNumber))
  21962. {
  21963. noteStates [midiNoteNumber] &= ~(1 << (midiChannel - 1));
  21964. for (int i = listeners.size(); --i >= 0;)
  21965. listeners.getUnchecked(i)->handleNoteOff (this, midiChannel, midiNoteNumber);
  21966. }
  21967. }
  21968. void MidiKeyboardState::allNotesOff (const int midiChannel)
  21969. {
  21970. const ScopedLock sl (lock);
  21971. if (midiChannel <= 0)
  21972. {
  21973. for (int i = 1; i <= 16; ++i)
  21974. allNotesOff (i);
  21975. }
  21976. else
  21977. {
  21978. for (int i = 0; i < 128; ++i)
  21979. noteOff (midiChannel, i);
  21980. }
  21981. }
  21982. void MidiKeyboardState::processNextMidiEvent (const MidiMessage& message)
  21983. {
  21984. if (message.isNoteOn())
  21985. {
  21986. noteOnInternal (message.getChannel(), message.getNoteNumber(), message.getFloatVelocity());
  21987. }
  21988. else if (message.isNoteOff())
  21989. {
  21990. noteOffInternal (message.getChannel(), message.getNoteNumber());
  21991. }
  21992. else if (message.isAllNotesOff())
  21993. {
  21994. for (int i = 0; i < 128; ++i)
  21995. noteOffInternal (message.getChannel(), i);
  21996. }
  21997. }
  21998. void MidiKeyboardState::processNextMidiBuffer (MidiBuffer& buffer,
  21999. const int startSample,
  22000. const int numSamples,
  22001. const bool injectIndirectEvents)
  22002. {
  22003. MidiBuffer::Iterator i (buffer);
  22004. MidiMessage message (0xf4, 0.0);
  22005. int time;
  22006. const ScopedLock sl (lock);
  22007. while (i.getNextEvent (message, time))
  22008. processNextMidiEvent (message);
  22009. if (injectIndirectEvents)
  22010. {
  22011. MidiBuffer::Iterator i2 (eventsToAdd);
  22012. const int firstEventToAdd = eventsToAdd.getFirstEventTime();
  22013. const double scaleFactor = numSamples / (double) (eventsToAdd.getLastEventTime() + 1 - firstEventToAdd);
  22014. while (i2.getNextEvent (message, time))
  22015. {
  22016. const int pos = jlimit (0, numSamples - 1, roundToInt ((time - firstEventToAdd) * scaleFactor));
  22017. buffer.addEvent (message, startSample + pos);
  22018. }
  22019. }
  22020. eventsToAdd.clear();
  22021. }
  22022. void MidiKeyboardState::addListener (MidiKeyboardStateListener* const listener) throw()
  22023. {
  22024. const ScopedLock sl (lock);
  22025. listeners.addIfNotAlreadyThere (listener);
  22026. }
  22027. void MidiKeyboardState::removeListener (MidiKeyboardStateListener* const listener) throw()
  22028. {
  22029. const ScopedLock sl (lock);
  22030. listeners.removeValue (listener);
  22031. }
  22032. END_JUCE_NAMESPACE
  22033. /*** End of inlined file: juce_MidiKeyboardState.cpp ***/
  22034. /*** Start of inlined file: juce_MidiMessage.cpp ***/
  22035. BEGIN_JUCE_NAMESPACE
  22036. int MidiMessage::readVariableLengthVal (const uint8* data,
  22037. int& numBytesUsed) throw()
  22038. {
  22039. numBytesUsed = 0;
  22040. int v = 0;
  22041. int i;
  22042. do
  22043. {
  22044. i = (int) *data++;
  22045. if (++numBytesUsed > 6)
  22046. break;
  22047. v = (v << 7) + (i & 0x7f);
  22048. } while (i & 0x80);
  22049. return v;
  22050. }
  22051. int MidiMessage::getMessageLengthFromFirstByte (const uint8 firstByte) throw()
  22052. {
  22053. // this method only works for valid starting bytes of a short midi message
  22054. jassert (firstByte >= 0x80
  22055. && firstByte != 0xf0
  22056. && firstByte != 0xf7);
  22057. static const char messageLengths[] =
  22058. {
  22059. 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3,
  22060. 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3,
  22061. 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3,
  22062. 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3,
  22063. 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2,
  22064. 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2,
  22065. 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3,
  22066. 1, 2, 3, 2, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1
  22067. };
  22068. return messageLengths [firstByte & 0x7f];
  22069. }
  22070. MidiMessage::MidiMessage (const void* const d, const int dataSize, const double t)
  22071. : timeStamp (t),
  22072. size (dataSize)
  22073. {
  22074. jassert (dataSize > 0);
  22075. if (dataSize <= 4)
  22076. data = static_cast<uint8*> (preallocatedData.asBytes);
  22077. else
  22078. data = new uint8 [dataSize];
  22079. memcpy (data, d, dataSize);
  22080. // check that the length matches the data..
  22081. jassert (size > 3 || data[0] >= 0xf0 || getMessageLengthFromFirstByte (data[0]) == size);
  22082. }
  22083. MidiMessage::MidiMessage (const int byte1, const double t) throw()
  22084. : timeStamp (t),
  22085. data (static_cast<uint8*> (preallocatedData.asBytes)),
  22086. size (1)
  22087. {
  22088. data[0] = (uint8) byte1;
  22089. // check that the length matches the data..
  22090. jassert (byte1 >= 0xf0 || getMessageLengthFromFirstByte ((uint8) byte1) == 1);
  22091. }
  22092. MidiMessage::MidiMessage (const int byte1, const int byte2, const double t) throw()
  22093. : timeStamp (t),
  22094. data (static_cast<uint8*> (preallocatedData.asBytes)),
  22095. size (2)
  22096. {
  22097. data[0] = (uint8) byte1;
  22098. data[1] = (uint8) byte2;
  22099. // check that the length matches the data..
  22100. jassert (byte1 >= 0xf0 || getMessageLengthFromFirstByte ((uint8) byte1) == 2);
  22101. }
  22102. MidiMessage::MidiMessage (const int byte1, const int byte2, const int byte3, const double t) throw()
  22103. : timeStamp (t),
  22104. data (static_cast<uint8*> (preallocatedData.asBytes)),
  22105. size (3)
  22106. {
  22107. data[0] = (uint8) byte1;
  22108. data[1] = (uint8) byte2;
  22109. data[2] = (uint8) byte3;
  22110. // check that the length matches the data..
  22111. jassert (byte1 >= 0xf0 || getMessageLengthFromFirstByte ((uint8) byte1) == 3);
  22112. }
  22113. MidiMessage::MidiMessage (const MidiMessage& other)
  22114. : timeStamp (other.timeStamp),
  22115. size (other.size)
  22116. {
  22117. if (other.data != static_cast <const uint8*> (other.preallocatedData.asBytes))
  22118. {
  22119. data = new uint8 [size];
  22120. memcpy (data, other.data, size);
  22121. }
  22122. else
  22123. {
  22124. data = static_cast<uint8*> (preallocatedData.asBytes);
  22125. preallocatedData.asInt32 = other.preallocatedData.asInt32;
  22126. }
  22127. }
  22128. MidiMessage::MidiMessage (const MidiMessage& other, const double newTimeStamp)
  22129. : timeStamp (newTimeStamp),
  22130. size (other.size)
  22131. {
  22132. if (other.data != static_cast <const uint8*> (other.preallocatedData.asBytes))
  22133. {
  22134. data = new uint8 [size];
  22135. memcpy (data, other.data, size);
  22136. }
  22137. else
  22138. {
  22139. data = static_cast<uint8*> (preallocatedData.asBytes);
  22140. preallocatedData.asInt32 = other.preallocatedData.asInt32;
  22141. }
  22142. }
  22143. MidiMessage::MidiMessage (const void* src_, int sz, int& numBytesUsed, const uint8 lastStatusByte, double t)
  22144. : timeStamp (t),
  22145. data (static_cast<uint8*> (preallocatedData.asBytes))
  22146. {
  22147. const uint8* src = static_cast <const uint8*> (src_);
  22148. unsigned int byte = (unsigned int) *src;
  22149. if (byte < 0x80)
  22150. {
  22151. byte = (unsigned int) (uint8) lastStatusByte;
  22152. numBytesUsed = -1;
  22153. }
  22154. else
  22155. {
  22156. numBytesUsed = 0;
  22157. --sz;
  22158. ++src;
  22159. }
  22160. if (byte >= 0x80)
  22161. {
  22162. if (byte == 0xf0)
  22163. {
  22164. const uint8* d = src;
  22165. while (d < src + sz)
  22166. {
  22167. if (*d >= 0x80) // stop if we hit a status byte, and don't include it in this message
  22168. {
  22169. if (*d == 0xf7) // include an 0xf7 if we hit one
  22170. ++d;
  22171. break;
  22172. }
  22173. ++d;
  22174. }
  22175. size = 1 + (int) (d - src);
  22176. data = new uint8 [size];
  22177. *data = (uint8) byte;
  22178. memcpy (data + 1, src, size - 1);
  22179. }
  22180. else if (byte == 0xff)
  22181. {
  22182. int n;
  22183. const int bytesLeft = readVariableLengthVal (src + 1, n);
  22184. size = jmin (sz + 1, n + 2 + bytesLeft);
  22185. data = new uint8 [size];
  22186. *data = (uint8) byte;
  22187. memcpy (data + 1, src, size - 1);
  22188. }
  22189. else
  22190. {
  22191. preallocatedData.asInt32 = 0;
  22192. size = getMessageLengthFromFirstByte ((uint8) byte);
  22193. data[0] = (uint8) byte;
  22194. if (size > 1)
  22195. {
  22196. data[1] = src[0];
  22197. if (size > 2)
  22198. data[2] = src[1];
  22199. }
  22200. }
  22201. numBytesUsed += size;
  22202. }
  22203. else
  22204. {
  22205. preallocatedData.asInt32 = 0;
  22206. size = 0;
  22207. }
  22208. }
  22209. MidiMessage& MidiMessage::operator= (const MidiMessage& other)
  22210. {
  22211. if (this != &other)
  22212. {
  22213. timeStamp = other.timeStamp;
  22214. size = other.size;
  22215. if (data != static_cast <const uint8*> (preallocatedData.asBytes))
  22216. delete[] data;
  22217. if (other.data != static_cast <const uint8*> (other.preallocatedData.asBytes))
  22218. {
  22219. data = new uint8 [size];
  22220. memcpy (data, other.data, size);
  22221. }
  22222. else
  22223. {
  22224. data = static_cast<uint8*> (preallocatedData.asBytes);
  22225. preallocatedData.asInt32 = other.preallocatedData.asInt32;
  22226. }
  22227. }
  22228. return *this;
  22229. }
  22230. MidiMessage::~MidiMessage()
  22231. {
  22232. if (data != static_cast <const uint8*> (preallocatedData.asBytes))
  22233. delete[] data;
  22234. }
  22235. int MidiMessage::getChannel() const throw()
  22236. {
  22237. if ((data[0] & 0xf0) != 0xf0)
  22238. return (data[0] & 0xf) + 1;
  22239. else
  22240. return 0;
  22241. }
  22242. bool MidiMessage::isForChannel (const int channel) const throw()
  22243. {
  22244. jassert (channel > 0 && channel <= 16); // valid channels are numbered 1 to 16
  22245. return ((data[0] & 0xf) == channel - 1)
  22246. && ((data[0] & 0xf0) != 0xf0);
  22247. }
  22248. void MidiMessage::setChannel (const int channel) throw()
  22249. {
  22250. jassert (channel > 0 && channel <= 16); // valid channels are numbered 1 to 16
  22251. if ((data[0] & 0xf0) != (uint8) 0xf0)
  22252. data[0] = (uint8) ((data[0] & (uint8)0xf0)
  22253. | (uint8)(channel - 1));
  22254. }
  22255. bool MidiMessage::isNoteOn (const bool returnTrueForVelocity0) const throw()
  22256. {
  22257. return ((data[0] & 0xf0) == 0x90)
  22258. && (returnTrueForVelocity0 || data[2] != 0);
  22259. }
  22260. bool MidiMessage::isNoteOff (const bool returnTrueForNoteOnVelocity0) const throw()
  22261. {
  22262. return ((data[0] & 0xf0) == 0x80)
  22263. || (returnTrueForNoteOnVelocity0 && (data[2] == 0) && ((data[0] & 0xf0) == 0x90));
  22264. }
  22265. bool MidiMessage::isNoteOnOrOff() const throw()
  22266. {
  22267. const int d = data[0] & 0xf0;
  22268. return (d == 0x90) || (d == 0x80);
  22269. }
  22270. int MidiMessage::getNoteNumber() const throw()
  22271. {
  22272. return data[1];
  22273. }
  22274. void MidiMessage::setNoteNumber (const int newNoteNumber) throw()
  22275. {
  22276. if (isNoteOnOrOff())
  22277. data[1] = (uint8) jlimit (0, 127, newNoteNumber);
  22278. }
  22279. uint8 MidiMessage::getVelocity() const throw()
  22280. {
  22281. if (isNoteOnOrOff())
  22282. return data[2];
  22283. else
  22284. return 0;
  22285. }
  22286. float MidiMessage::getFloatVelocity() const throw()
  22287. {
  22288. return getVelocity() * (1.0f / 127.0f);
  22289. }
  22290. void MidiMessage::setVelocity (const float newVelocity) throw()
  22291. {
  22292. if (isNoteOnOrOff())
  22293. data[2] = (uint8) jlimit (0, 0x7f, roundToInt (newVelocity * 127.0f));
  22294. }
  22295. void MidiMessage::multiplyVelocity (const float scaleFactor) throw()
  22296. {
  22297. if (isNoteOnOrOff())
  22298. data[2] = (uint8) jlimit (0, 0x7f, roundToInt (scaleFactor * data[2]));
  22299. }
  22300. bool MidiMessage::isAftertouch() const throw()
  22301. {
  22302. return (data[0] & 0xf0) == 0xa0;
  22303. }
  22304. int MidiMessage::getAfterTouchValue() const throw()
  22305. {
  22306. return data[2];
  22307. }
  22308. const MidiMessage MidiMessage::aftertouchChange (const int channel,
  22309. const int noteNum,
  22310. const int aftertouchValue) throw()
  22311. {
  22312. jassert (channel > 0 && channel <= 16); // valid channels are numbered 1 to 16
  22313. jassert (((unsigned int) noteNum) <= 127);
  22314. jassert (((unsigned int) aftertouchValue) <= 127);
  22315. return MidiMessage (0xa0 | jlimit (0, 15, channel - 1),
  22316. noteNum & 0x7f,
  22317. aftertouchValue & 0x7f);
  22318. }
  22319. bool MidiMessage::isChannelPressure() const throw()
  22320. {
  22321. return (data[0] & 0xf0) == 0xd0;
  22322. }
  22323. int MidiMessage::getChannelPressureValue() const throw()
  22324. {
  22325. jassert (isChannelPressure());
  22326. return data[1];
  22327. }
  22328. const MidiMessage MidiMessage::channelPressureChange (const int channel,
  22329. const int pressure) throw()
  22330. {
  22331. jassert (channel > 0 && channel <= 16); // valid channels are numbered 1 to 16
  22332. jassert (((unsigned int) pressure) <= 127);
  22333. return MidiMessage (0xd0 | jlimit (0, 15, channel - 1),
  22334. pressure & 0x7f);
  22335. }
  22336. bool MidiMessage::isProgramChange() const throw()
  22337. {
  22338. return (data[0] & 0xf0) == 0xc0;
  22339. }
  22340. int MidiMessage::getProgramChangeNumber() const throw()
  22341. {
  22342. return data[1];
  22343. }
  22344. const MidiMessage MidiMessage::programChange (const int channel,
  22345. const int programNumber) throw()
  22346. {
  22347. jassert (channel > 0 && channel <= 16); // valid channels are numbered 1 to 16
  22348. return MidiMessage (0xc0 | jlimit (0, 15, channel - 1),
  22349. programNumber & 0x7f);
  22350. }
  22351. bool MidiMessage::isPitchWheel() const throw()
  22352. {
  22353. return (data[0] & 0xf0) == 0xe0;
  22354. }
  22355. int MidiMessage::getPitchWheelValue() const throw()
  22356. {
  22357. return data[1] | (data[2] << 7);
  22358. }
  22359. const MidiMessage MidiMessage::pitchWheel (const int channel,
  22360. const int position) throw()
  22361. {
  22362. jassert (channel > 0 && channel <= 16); // valid channels are numbered 1 to 16
  22363. jassert (((unsigned int) position) <= 0x3fff);
  22364. return MidiMessage (0xe0 | jlimit (0, 15, channel - 1),
  22365. position & 127,
  22366. (position >> 7) & 127);
  22367. }
  22368. bool MidiMessage::isController() const throw()
  22369. {
  22370. return (data[0] & 0xf0) == 0xb0;
  22371. }
  22372. int MidiMessage::getControllerNumber() const throw()
  22373. {
  22374. jassert (isController());
  22375. return data[1];
  22376. }
  22377. int MidiMessage::getControllerValue() const throw()
  22378. {
  22379. jassert (isController());
  22380. return data[2];
  22381. }
  22382. const MidiMessage MidiMessage::controllerEvent (const int channel,
  22383. const int controllerType,
  22384. const int value) throw()
  22385. {
  22386. // the channel must be between 1 and 16 inclusive
  22387. jassert (channel > 0 && channel <= 16);
  22388. return MidiMessage (0xb0 | jlimit (0, 15, channel - 1),
  22389. controllerType & 127,
  22390. value & 127);
  22391. }
  22392. const MidiMessage MidiMessage::noteOn (const int channel,
  22393. const int noteNumber,
  22394. const float velocity) throw()
  22395. {
  22396. return noteOn (channel, noteNumber, (uint8)(velocity * 127.0f));
  22397. }
  22398. const MidiMessage MidiMessage::noteOn (const int channel,
  22399. const int noteNumber,
  22400. const uint8 velocity) throw()
  22401. {
  22402. jassert (channel > 0 && channel <= 16);
  22403. jassert (((unsigned int) noteNumber) <= 127);
  22404. return MidiMessage (0x90 | jlimit (0, 15, channel - 1),
  22405. noteNumber & 127,
  22406. jlimit (0, 127, roundToInt (velocity)));
  22407. }
  22408. const MidiMessage MidiMessage::noteOff (const int channel,
  22409. const int noteNumber) throw()
  22410. {
  22411. jassert (channel > 0 && channel <= 16);
  22412. jassert (((unsigned int) noteNumber) <= 127);
  22413. return MidiMessage (0x80 | jlimit (0, 15, channel - 1), noteNumber & 127, 0);
  22414. }
  22415. const MidiMessage MidiMessage::allNotesOff (const int channel) throw()
  22416. {
  22417. jassert (channel > 0 && channel <= 16);
  22418. return controllerEvent (channel, 123, 0);
  22419. }
  22420. bool MidiMessage::isAllNotesOff() const throw()
  22421. {
  22422. return (data[0] & 0xf0) == 0xb0
  22423. && data[1] == 123;
  22424. }
  22425. const MidiMessage MidiMessage::allSoundOff (const int channel) throw()
  22426. {
  22427. return controllerEvent (channel, 120, 0);
  22428. }
  22429. bool MidiMessage::isAllSoundOff() const throw()
  22430. {
  22431. return (data[0] & 0xf0) == 0xb0
  22432. && data[1] == 120;
  22433. }
  22434. const MidiMessage MidiMessage::allControllersOff (const int channel) throw()
  22435. {
  22436. return controllerEvent (channel, 121, 0);
  22437. }
  22438. const MidiMessage MidiMessage::masterVolume (const float volume)
  22439. {
  22440. const int vol = jlimit (0, 0x3fff, roundToInt (volume * 0x4000));
  22441. uint8 buf[8];
  22442. buf[0] = 0xf0;
  22443. buf[1] = 0x7f;
  22444. buf[2] = 0x7f;
  22445. buf[3] = 0x04;
  22446. buf[4] = 0x01;
  22447. buf[5] = (uint8) (vol & 0x7f);
  22448. buf[6] = (uint8) (vol >> 7);
  22449. buf[7] = 0xf7;
  22450. return MidiMessage (buf, 8);
  22451. }
  22452. bool MidiMessage::isSysEx() const throw()
  22453. {
  22454. return *data == 0xf0;
  22455. }
  22456. const MidiMessage MidiMessage::createSysExMessage (const uint8* sysexData, const int dataSize)
  22457. {
  22458. MemoryBlock mm (dataSize + 2);
  22459. uint8* const m = static_cast <uint8*> (mm.getData());
  22460. m[0] = 0xf0;
  22461. memcpy (m + 1, sysexData, dataSize);
  22462. m[dataSize + 1] = 0xf7;
  22463. return MidiMessage (m, dataSize + 2);
  22464. }
  22465. const uint8* MidiMessage::getSysExData() const throw()
  22466. {
  22467. return (isSysEx()) ? getRawData() + 1 : 0;
  22468. }
  22469. int MidiMessage::getSysExDataSize() const throw()
  22470. {
  22471. return (isSysEx()) ? size - 2 : 0;
  22472. }
  22473. bool MidiMessage::isMetaEvent() const throw()
  22474. {
  22475. return *data == 0xff;
  22476. }
  22477. bool MidiMessage::isActiveSense() const throw()
  22478. {
  22479. return *data == 0xfe;
  22480. }
  22481. int MidiMessage::getMetaEventType() const throw()
  22482. {
  22483. if (*data != 0xff)
  22484. return -1;
  22485. else
  22486. return data[1];
  22487. }
  22488. int MidiMessage::getMetaEventLength() const throw()
  22489. {
  22490. if (*data == 0xff)
  22491. {
  22492. int n;
  22493. return jmin (size - 2, readVariableLengthVal (data + 2, n));
  22494. }
  22495. return 0;
  22496. }
  22497. const uint8* MidiMessage::getMetaEventData() const throw()
  22498. {
  22499. int n;
  22500. const uint8* d = data + 2;
  22501. readVariableLengthVal (d, n);
  22502. return d + n;
  22503. }
  22504. bool MidiMessage::isTrackMetaEvent() const throw()
  22505. {
  22506. return getMetaEventType() == 0;
  22507. }
  22508. bool MidiMessage::isEndOfTrackMetaEvent() const throw()
  22509. {
  22510. return getMetaEventType() == 47;
  22511. }
  22512. bool MidiMessage::isTextMetaEvent() const throw()
  22513. {
  22514. const int t = getMetaEventType();
  22515. return t > 0 && t < 16;
  22516. }
  22517. const String MidiMessage::getTextFromTextMetaEvent() const
  22518. {
  22519. return String (reinterpret_cast <const char*> (getMetaEventData()), getMetaEventLength());
  22520. }
  22521. bool MidiMessage::isTrackNameEvent() const throw()
  22522. {
  22523. return (data[1] == 3)
  22524. && (*data == 0xff);
  22525. }
  22526. bool MidiMessage::isTempoMetaEvent() const throw()
  22527. {
  22528. return (data[1] == 81)
  22529. && (*data == 0xff);
  22530. }
  22531. bool MidiMessage::isMidiChannelMetaEvent() const throw()
  22532. {
  22533. return (data[1] == 0x20)
  22534. && (*data == 0xff)
  22535. && (data[2] == 1);
  22536. }
  22537. int MidiMessage::getMidiChannelMetaEventChannel() const throw()
  22538. {
  22539. return data[3] + 1;
  22540. }
  22541. double MidiMessage::getTempoSecondsPerQuarterNote() const throw()
  22542. {
  22543. if (! isTempoMetaEvent())
  22544. return 0.0;
  22545. const uint8* const d = getMetaEventData();
  22546. return (((unsigned int) d[0] << 16)
  22547. | ((unsigned int) d[1] << 8)
  22548. | d[2])
  22549. / 1000000.0;
  22550. }
  22551. double MidiMessage::getTempoMetaEventTickLength (const short timeFormat) const throw()
  22552. {
  22553. if (timeFormat > 0)
  22554. {
  22555. if (! isTempoMetaEvent())
  22556. return 0.5 / timeFormat;
  22557. return getTempoSecondsPerQuarterNote() / timeFormat;
  22558. }
  22559. else
  22560. {
  22561. const int frameCode = (-timeFormat) >> 8;
  22562. double framesPerSecond;
  22563. switch (frameCode)
  22564. {
  22565. case 24: framesPerSecond = 24.0; break;
  22566. case 25: framesPerSecond = 25.0; break;
  22567. case 29: framesPerSecond = 29.97; break;
  22568. case 30: framesPerSecond = 30.0; break;
  22569. default: framesPerSecond = 30.0; break;
  22570. }
  22571. return (1.0 / framesPerSecond) / (timeFormat & 0xff);
  22572. }
  22573. }
  22574. const MidiMessage MidiMessage::tempoMetaEvent (int microsecondsPerQuarterNote) throw()
  22575. {
  22576. uint8 d[8];
  22577. d[0] = 0xff;
  22578. d[1] = 81;
  22579. d[2] = 3;
  22580. d[3] = (uint8) (microsecondsPerQuarterNote >> 16);
  22581. d[4] = (uint8) ((microsecondsPerQuarterNote >> 8) & 0xff);
  22582. d[5] = (uint8) (microsecondsPerQuarterNote & 0xff);
  22583. return MidiMessage (d, 6, 0.0);
  22584. }
  22585. bool MidiMessage::isTimeSignatureMetaEvent() const throw()
  22586. {
  22587. return (data[1] == 0x58)
  22588. && (*data == (uint8) 0xff);
  22589. }
  22590. void MidiMessage::getTimeSignatureInfo (int& numerator, int& denominator) const throw()
  22591. {
  22592. if (isTimeSignatureMetaEvent())
  22593. {
  22594. const uint8* const d = getMetaEventData();
  22595. numerator = d[0];
  22596. denominator = 1 << d[1];
  22597. }
  22598. else
  22599. {
  22600. numerator = 4;
  22601. denominator = 4;
  22602. }
  22603. }
  22604. const MidiMessage MidiMessage::timeSignatureMetaEvent (const int numerator, const int denominator)
  22605. {
  22606. uint8 d[8];
  22607. d[0] = 0xff;
  22608. d[1] = 0x58;
  22609. d[2] = 0x04;
  22610. d[3] = (uint8) numerator;
  22611. int n = 1;
  22612. int powerOfTwo = 0;
  22613. while (n < denominator)
  22614. {
  22615. n <<= 1;
  22616. ++powerOfTwo;
  22617. }
  22618. d[4] = (uint8) powerOfTwo;
  22619. d[5] = 0x01;
  22620. d[6] = 96;
  22621. return MidiMessage (d, 7, 0.0);
  22622. }
  22623. const MidiMessage MidiMessage::midiChannelMetaEvent (const int channel) throw()
  22624. {
  22625. uint8 d[8];
  22626. d[0] = 0xff;
  22627. d[1] = 0x20;
  22628. d[2] = 0x01;
  22629. d[3] = (uint8) jlimit (0, 0xff, channel - 1);
  22630. return MidiMessage (d, 4, 0.0);
  22631. }
  22632. bool MidiMessage::isKeySignatureMetaEvent() const throw()
  22633. {
  22634. return getMetaEventType() == 89;
  22635. }
  22636. int MidiMessage::getKeySignatureNumberOfSharpsOrFlats() const throw()
  22637. {
  22638. return (int) *getMetaEventData();
  22639. }
  22640. const MidiMessage MidiMessage::endOfTrack() throw()
  22641. {
  22642. return MidiMessage (0xff, 0x2f, 0, 0.0);
  22643. }
  22644. bool MidiMessage::isSongPositionPointer() const throw()
  22645. {
  22646. return *data == 0xf2;
  22647. }
  22648. int MidiMessage::getSongPositionPointerMidiBeat() const throw()
  22649. {
  22650. return data[1] | (data[2] << 7);
  22651. }
  22652. const MidiMessage MidiMessage::songPositionPointer (const int positionInMidiBeats) throw()
  22653. {
  22654. return MidiMessage (0xf2,
  22655. positionInMidiBeats & 127,
  22656. (positionInMidiBeats >> 7) & 127);
  22657. }
  22658. bool MidiMessage::isMidiStart() const throw()
  22659. {
  22660. return *data == 0xfa;
  22661. }
  22662. const MidiMessage MidiMessage::midiStart() throw()
  22663. {
  22664. return MidiMessage (0xfa);
  22665. }
  22666. bool MidiMessage::isMidiContinue() const throw()
  22667. {
  22668. return *data == 0xfb;
  22669. }
  22670. const MidiMessage MidiMessage::midiContinue() throw()
  22671. {
  22672. return MidiMessage (0xfb);
  22673. }
  22674. bool MidiMessage::isMidiStop() const throw()
  22675. {
  22676. return *data == 0xfc;
  22677. }
  22678. const MidiMessage MidiMessage::midiStop() throw()
  22679. {
  22680. return MidiMessage (0xfc);
  22681. }
  22682. bool MidiMessage::isMidiClock() const throw()
  22683. {
  22684. return *data == 0xf8;
  22685. }
  22686. const MidiMessage MidiMessage::midiClock() throw()
  22687. {
  22688. return MidiMessage (0xf8);
  22689. }
  22690. bool MidiMessage::isQuarterFrame() const throw()
  22691. {
  22692. return *data == 0xf1;
  22693. }
  22694. int MidiMessage::getQuarterFrameSequenceNumber() const throw()
  22695. {
  22696. return ((int) data[1]) >> 4;
  22697. }
  22698. int MidiMessage::getQuarterFrameValue() const throw()
  22699. {
  22700. return ((int) data[1]) & 0x0f;
  22701. }
  22702. const MidiMessage MidiMessage::quarterFrame (const int sequenceNumber,
  22703. const int value) throw()
  22704. {
  22705. return MidiMessage (0xf1, (sequenceNumber << 4) | value);
  22706. }
  22707. bool MidiMessage::isFullFrame() const throw()
  22708. {
  22709. return data[0] == 0xf0
  22710. && data[1] == 0x7f
  22711. && size >= 10
  22712. && data[3] == 0x01
  22713. && data[4] == 0x01;
  22714. }
  22715. void MidiMessage::getFullFrameParameters (int& hours,
  22716. int& minutes,
  22717. int& seconds,
  22718. int& frames,
  22719. MidiMessage::SmpteTimecodeType& timecodeType) const throw()
  22720. {
  22721. jassert (isFullFrame());
  22722. timecodeType = (SmpteTimecodeType) (data[5] >> 5);
  22723. hours = data[5] & 0x1f;
  22724. minutes = data[6];
  22725. seconds = data[7];
  22726. frames = data[8];
  22727. }
  22728. const MidiMessage MidiMessage::fullFrame (const int hours,
  22729. const int minutes,
  22730. const int seconds,
  22731. const int frames,
  22732. MidiMessage::SmpteTimecodeType timecodeType)
  22733. {
  22734. uint8 d[10];
  22735. d[0] = 0xf0;
  22736. d[1] = 0x7f;
  22737. d[2] = 0x7f;
  22738. d[3] = 0x01;
  22739. d[4] = 0x01;
  22740. d[5] = (uint8) ((hours & 0x01f) | (timecodeType << 5));
  22741. d[6] = (uint8) minutes;
  22742. d[7] = (uint8) seconds;
  22743. d[8] = (uint8) frames;
  22744. d[9] = 0xf7;
  22745. return MidiMessage (d, 10, 0.0);
  22746. }
  22747. bool MidiMessage::isMidiMachineControlMessage() const throw()
  22748. {
  22749. return data[0] == 0xf0
  22750. && data[1] == 0x7f
  22751. && data[3] == 0x06
  22752. && size > 5;
  22753. }
  22754. MidiMessage::MidiMachineControlCommand MidiMessage::getMidiMachineControlCommand() const throw()
  22755. {
  22756. jassert (isMidiMachineControlMessage());
  22757. return (MidiMachineControlCommand) data[4];
  22758. }
  22759. const MidiMessage MidiMessage::midiMachineControlCommand (MidiMessage::MidiMachineControlCommand command)
  22760. {
  22761. uint8 d[6];
  22762. d[0] = 0xf0;
  22763. d[1] = 0x7f;
  22764. d[2] = 0x00;
  22765. d[3] = 0x06;
  22766. d[4] = (uint8) command;
  22767. d[5] = 0xf7;
  22768. return MidiMessage (d, 6, 0.0);
  22769. }
  22770. bool MidiMessage::isMidiMachineControlGoto (int& hours,
  22771. int& minutes,
  22772. int& seconds,
  22773. int& frames) const throw()
  22774. {
  22775. if (size >= 12
  22776. && data[0] == 0xf0
  22777. && data[1] == 0x7f
  22778. && data[3] == 0x06
  22779. && data[4] == 0x44
  22780. && data[5] == 0x06
  22781. && data[6] == 0x01)
  22782. {
  22783. hours = data[7] % 24; // (that some machines send out hours > 24)
  22784. minutes = data[8];
  22785. seconds = data[9];
  22786. frames = data[10];
  22787. return true;
  22788. }
  22789. return false;
  22790. }
  22791. const MidiMessage MidiMessage::midiMachineControlGoto (int hours,
  22792. int minutes,
  22793. int seconds,
  22794. int frames)
  22795. {
  22796. uint8 d[12];
  22797. d[0] = 0xf0;
  22798. d[1] = 0x7f;
  22799. d[2] = 0x00;
  22800. d[3] = 0x06;
  22801. d[4] = 0x44;
  22802. d[5] = 0x06;
  22803. d[6] = 0x01;
  22804. d[7] = (uint8) hours;
  22805. d[8] = (uint8) minutes;
  22806. d[9] = (uint8) seconds;
  22807. d[10] = (uint8) frames;
  22808. d[11] = 0xf7;
  22809. return MidiMessage (d, 12, 0.0);
  22810. }
  22811. const String MidiMessage::getMidiNoteName (int note,
  22812. bool useSharps,
  22813. bool includeOctaveNumber,
  22814. int octaveNumForMiddleC) throw()
  22815. {
  22816. static const char* const sharpNoteNames[] = { "C", "C#", "D", "D#", "E",
  22817. "F", "F#", "G", "G#", "A",
  22818. "A#", "B" };
  22819. static const char* const flatNoteNames[] = { "C", "Db", "D", "Eb", "E",
  22820. "F", "Gb", "G", "Ab", "A",
  22821. "Bb", "B" };
  22822. if (((unsigned int) note) < 128)
  22823. {
  22824. const String s ((useSharps) ? sharpNoteNames [note % 12]
  22825. : flatNoteNames [note % 12]);
  22826. if (includeOctaveNumber)
  22827. return s + String (note / 12 + (octaveNumForMiddleC - 5));
  22828. else
  22829. return s;
  22830. }
  22831. return String::empty;
  22832. }
  22833. const double MidiMessage::getMidiNoteInHertz (int noteNumber) throw()
  22834. {
  22835. noteNumber -= 12 * 6 + 9; // now 0 = A440
  22836. return 440.0 * pow (2.0, noteNumber / 12.0);
  22837. }
  22838. const String MidiMessage::getGMInstrumentName (int n) throw()
  22839. {
  22840. const char *names[] =
  22841. {
  22842. "Acoustic Grand Piano", "Bright Acoustic Piano", "Electric Grand Piano", "Honky-tonk Piano",
  22843. "Electric Piano 1", "Electric Piano 2", "Harpsichord", "Clavinet", "Celesta", "Glockenspiel",
  22844. "Music Box", "Vibraphone", "Marimba", "Xylophone", "Tubular Bells", "Dulcimer", "Drawbar Organ",
  22845. "Percussive Organ", "Rock Organ", "Church Organ", "Reed Organ", "Accordion", "Harmonica",
  22846. "Tango Accordion", "Acoustic Guitar (nylon)", "Acoustic Guitar (steel)", "Electric Guitar (jazz)",
  22847. "Electric Guitar (clean)", "Electric Guitar (mute)", "Overdriven Guitar", "Distortion Guitar",
  22848. "Guitar Harmonics", "Acoustic Bass", "Electric Bass (finger)", "Electric Bass (pick)",
  22849. "Fretless Bass", "Slap Bass 1", "Slap Bass 2", "Synth Bass 1", "Synth Bass 2", "Violin",
  22850. "Viola", "Cello", "Contrabass", "Tremolo Strings", "Pizzicato Strings", "Orchestral Harp",
  22851. "Timpani", "String Ensemble 1", "String Ensemble 2", "SynthStrings 1", "SynthStrings 2",
  22852. "Choir Aahs", "Voice Oohs", "Synth Voice", "Orchestra Hit", "Trumpet", "Trombone", "Tuba",
  22853. "Muted Trumpet", "French Horn", "Brass Section", "SynthBrass 1", "SynthBrass 2", "Soprano Sax",
  22854. "Alto Sax", "Tenor Sax", "Baritone Sax", "Oboe", "English Horn", "Bassoon", "Clarinet",
  22855. "Piccolo", "Flute", "Recorder", "Pan Flute", "Blown Bottle", "Shakuhachi", "Whistle",
  22856. "Ocarina", "Lead 1 (square)", "Lead 2 (sawtooth)", "Lead 3 (calliope)", "Lead 4 (chiff)",
  22857. "Lead 5 (charang)", "Lead 6 (voice)", "Lead 7 (fifths)", "Lead 8 (bass+lead)", "Pad 1 (new age)",
  22858. "Pad 2 (warm)", "Pad 3 (polysynth)", "Pad 4 (choir)", "Pad 5 (bowed)", "Pad 6 (metallic)",
  22859. "Pad 7 (halo)", "Pad 8 (sweep)", "FX 1 (rain)", "FX 2 (soundtrack)", "FX 3 (crystal)",
  22860. "FX 4 (atmosphere)", "FX 5 (brightness)", "FX 6 (goblins)", "FX 7 (echoes)", "FX 8 (sci-fi)",
  22861. "Sitar", "Banjo", "Shamisen", "Koto", "Kalimba", "Bag pipe", "Fiddle", "Shanai", "Tinkle Bell",
  22862. "Agogo", "Steel Drums", "Woodblock", "Taiko Drum", "Melodic Tom", "Synth Drum", "Reverse Cymbal",
  22863. "Guitar Fret Noise", "Breath Noise", "Seashore", "Bird Tweet", "Telephone Ring", "Helicopter",
  22864. "Applause", "Gunshot"
  22865. };
  22866. return (((unsigned int) n) < 128) ? names[n]
  22867. : (const char*)0;
  22868. }
  22869. const String MidiMessage::getGMInstrumentBankName (int n) throw()
  22870. {
  22871. const char* names[] =
  22872. {
  22873. "Piano", "Chromatic Percussion", "Organ", "Guitar",
  22874. "Bass", "Strings", "Ensemble", "Brass",
  22875. "Reed", "Pipe", "Synth Lead", "Synth Pad",
  22876. "Synth Effects", "Ethnic", "Percussive", "Sound Effects"
  22877. };
  22878. return (((unsigned int) n) <= 15) ? names[n]
  22879. : (const char*)0;
  22880. }
  22881. const String MidiMessage::getRhythmInstrumentName (int n) throw()
  22882. {
  22883. const char* names[] =
  22884. {
  22885. "Acoustic Bass Drum", "Bass Drum 1", "Side Stick", "Acoustic Snare",
  22886. "Hand Clap", "Electric Snare", "Low Floor Tom", "Closed Hi-Hat", "High Floor Tom",
  22887. "Pedal Hi-Hat", "Low Tom", "Open Hi-Hat", "Low-Mid Tom", "Hi-Mid Tom", "Crash Cymbal 1",
  22888. "High Tom", "Ride Cymbal 1", "Chinese Cymbal", "Ride Bell", "Tambourine", "Splash Cymbal",
  22889. "Cowbell", "Crash Cymbal 2", "Vibraslap", "Ride Cymbal 2", "Hi Bongo", "Low Bongo",
  22890. "Mute Hi Conga", "Open Hi Conga", "Low Conga", "High Timbale", "Low Timbale", "High Agogo",
  22891. "Low Agogo", "Cabasa", "Maracas", "Short Whistle", "Long Whistle", "Short Guiro",
  22892. "Long Guiro", "Claves", "Hi Wood Block", "Low Wood Block", "Mute Cuica", "Open Cuica",
  22893. "Mute Triangle", "Open Triangle"
  22894. };
  22895. return (n >= 35 && n <= 81) ? names [n - 35]
  22896. : (const char*)0;
  22897. }
  22898. const String MidiMessage::getControllerName (int n) throw()
  22899. {
  22900. const char* names[] =
  22901. {
  22902. "Bank Select", "Modulation Wheel (coarse)", "Breath controller (coarse)",
  22903. 0, "Foot Pedal (coarse)", "Portamento Time (coarse)",
  22904. "Data Entry (coarse)", "Volume (coarse)", "Balance (coarse)",
  22905. 0, "Pan position (coarse)", "Expression (coarse)", "Effect Control 1 (coarse)",
  22906. "Effect Control 2 (coarse)", 0, 0, "General Purpose Slider 1", "General Purpose Slider 2",
  22907. "General Purpose Slider 3", "General Purpose Slider 4", 0, 0, 0, 0, 0, 0, 0, 0,
  22908. 0, 0, 0, 0, "Bank Select (fine)", "Modulation Wheel (fine)", "Breath controller (fine)",
  22909. 0, "Foot Pedal (fine)", "Portamento Time (fine)", "Data Entry (fine)", "Volume (fine)",
  22910. "Balance (fine)", 0, "Pan position (fine)", "Expression (fine)", "Effect Control 1 (fine)",
  22911. "Effect Control 2 (fine)", 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  22912. "Hold Pedal (on/off)", "Portamento (on/off)", "Sustenuto Pedal (on/off)", "Soft Pedal (on/off)",
  22913. "Legato Pedal (on/off)", "Hold 2 Pedal (on/off)", "Sound Variation", "Sound Timbre",
  22914. "Sound Release Time", "Sound Attack Time", "Sound Brightness", "Sound Control 6",
  22915. "Sound Control 7", "Sound Control 8", "Sound Control 9", "Sound Control 10",
  22916. "General Purpose Button 1 (on/off)", "General Purpose Button 2 (on/off)",
  22917. "General Purpose Button 3 (on/off)", "General Purpose Button 4 (on/off)",
  22918. 0, 0, 0, 0, 0, 0, 0, "Reverb Level", "Tremolo Level", "Chorus Level", "Celeste Level",
  22919. "Phaser Level", "Data Button increment", "Data Button decrement", "Non-registered Parameter (fine)",
  22920. "Non-registered Parameter (coarse)", "Registered Parameter (fine)", "Registered Parameter (coarse)",
  22921. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, "All Sound Off", "All Controllers Off",
  22922. "Local Keyboard (on/off)", "All Notes Off", "Omni Mode Off", "Omni Mode On", "Mono Operation",
  22923. "Poly Operation"
  22924. };
  22925. return (((unsigned int) n) < 128) ? names[n]
  22926. : (const char*)0;
  22927. }
  22928. END_JUCE_NAMESPACE
  22929. /*** End of inlined file: juce_MidiMessage.cpp ***/
  22930. /*** Start of inlined file: juce_MidiMessageCollector.cpp ***/
  22931. BEGIN_JUCE_NAMESPACE
  22932. MidiMessageCollector::MidiMessageCollector()
  22933. : lastCallbackTime (0),
  22934. sampleRate (44100.0001)
  22935. {
  22936. }
  22937. MidiMessageCollector::~MidiMessageCollector()
  22938. {
  22939. }
  22940. void MidiMessageCollector::reset (const double sampleRate_)
  22941. {
  22942. jassert (sampleRate_ > 0);
  22943. const ScopedLock sl (midiCallbackLock);
  22944. sampleRate = sampleRate_;
  22945. incomingMessages.clear();
  22946. lastCallbackTime = Time::getMillisecondCounterHiRes();
  22947. }
  22948. void MidiMessageCollector::addMessageToQueue (const MidiMessage& message)
  22949. {
  22950. // you need to call reset() to set the correct sample rate before using this object
  22951. jassert (sampleRate != 44100.0001);
  22952. // the messages that come in here need to be time-stamped correctly - see MidiInput
  22953. // for details of what the number should be.
  22954. jassert (message.getTimeStamp() != 0);
  22955. const ScopedLock sl (midiCallbackLock);
  22956. const int sampleNumber
  22957. = (int) ((message.getTimeStamp() - 0.001 * lastCallbackTime) * sampleRate);
  22958. incomingMessages.addEvent (message, sampleNumber);
  22959. // if the messages don't get used for over a second, we'd better
  22960. // get rid of any old ones to avoid the queue getting too big
  22961. if (sampleNumber > sampleRate)
  22962. incomingMessages.clear (0, sampleNumber - (int) sampleRate);
  22963. }
  22964. void MidiMessageCollector::removeNextBlockOfMessages (MidiBuffer& destBuffer,
  22965. const int numSamples)
  22966. {
  22967. // you need to call reset() to set the correct sample rate before using this object
  22968. jassert (sampleRate != 44100.0001);
  22969. const double timeNow = Time::getMillisecondCounterHiRes();
  22970. const double msElapsed = timeNow - lastCallbackTime;
  22971. const ScopedLock sl (midiCallbackLock);
  22972. lastCallbackTime = timeNow;
  22973. if (! incomingMessages.isEmpty())
  22974. {
  22975. int numSourceSamples = jmax (1, roundToInt (msElapsed * 0.001 * sampleRate));
  22976. int startSample = 0;
  22977. int scale = 1 << 16;
  22978. const uint8* midiData;
  22979. int numBytes, samplePosition;
  22980. MidiBuffer::Iterator iter (incomingMessages);
  22981. if (numSourceSamples > numSamples)
  22982. {
  22983. // if our list of events is longer than the buffer we're being
  22984. // asked for, scale them down to squeeze them all in..
  22985. const int maxBlockLengthToUse = numSamples << 5;
  22986. if (numSourceSamples > maxBlockLengthToUse)
  22987. {
  22988. startSample = numSourceSamples - maxBlockLengthToUse;
  22989. numSourceSamples = maxBlockLengthToUse;
  22990. iter.setNextSamplePosition (startSample);
  22991. }
  22992. scale = (numSamples << 10) / numSourceSamples;
  22993. while (iter.getNextEvent (midiData, numBytes, samplePosition))
  22994. {
  22995. samplePosition = ((samplePosition - startSample) * scale) >> 10;
  22996. destBuffer.addEvent (midiData, numBytes,
  22997. jlimit (0, numSamples - 1, samplePosition));
  22998. }
  22999. }
  23000. else
  23001. {
  23002. // if our event list is shorter than the number we need, put them
  23003. // towards the end of the buffer
  23004. startSample = numSamples - numSourceSamples;
  23005. while (iter.getNextEvent (midiData, numBytes, samplePosition))
  23006. {
  23007. destBuffer.addEvent (midiData, numBytes,
  23008. jlimit (0, numSamples - 1, samplePosition + startSample));
  23009. }
  23010. }
  23011. incomingMessages.clear();
  23012. }
  23013. }
  23014. void MidiMessageCollector::handleNoteOn (MidiKeyboardState*, int midiChannel, int midiNoteNumber, float velocity)
  23015. {
  23016. MidiMessage m (MidiMessage::noteOn (midiChannel, midiNoteNumber, velocity));
  23017. m.setTimeStamp (Time::getMillisecondCounterHiRes() * 0.001);
  23018. addMessageToQueue (m);
  23019. }
  23020. void MidiMessageCollector::handleNoteOff (MidiKeyboardState*, int midiChannel, int midiNoteNumber)
  23021. {
  23022. MidiMessage m (MidiMessage::noteOff (midiChannel, midiNoteNumber));
  23023. m.setTimeStamp (Time::getMillisecondCounterHiRes() * 0.001);
  23024. addMessageToQueue (m);
  23025. }
  23026. void MidiMessageCollector::handleIncomingMidiMessage (MidiInput*, const MidiMessage& message)
  23027. {
  23028. addMessageToQueue (message);
  23029. }
  23030. END_JUCE_NAMESPACE
  23031. /*** End of inlined file: juce_MidiMessageCollector.cpp ***/
  23032. /*** Start of inlined file: juce_MidiMessageSequence.cpp ***/
  23033. BEGIN_JUCE_NAMESPACE
  23034. MidiMessageSequence::MidiMessageSequence()
  23035. {
  23036. }
  23037. MidiMessageSequence::MidiMessageSequence (const MidiMessageSequence& other)
  23038. {
  23039. list.ensureStorageAllocated (other.list.size());
  23040. for (int i = 0; i < other.list.size(); ++i)
  23041. list.add (new MidiEventHolder (other.list.getUnchecked(i)->message));
  23042. }
  23043. MidiMessageSequence& MidiMessageSequence::operator= (const MidiMessageSequence& other)
  23044. {
  23045. MidiMessageSequence otherCopy (other);
  23046. swapWith (otherCopy);
  23047. return *this;
  23048. }
  23049. void MidiMessageSequence::swapWith (MidiMessageSequence& other) throw()
  23050. {
  23051. list.swapWithArray (other.list);
  23052. }
  23053. MidiMessageSequence::~MidiMessageSequence()
  23054. {
  23055. }
  23056. void MidiMessageSequence::clear()
  23057. {
  23058. list.clear();
  23059. }
  23060. int MidiMessageSequence::getNumEvents() const
  23061. {
  23062. return list.size();
  23063. }
  23064. MidiMessageSequence::MidiEventHolder* MidiMessageSequence::getEventPointer (const int index) const
  23065. {
  23066. return list [index];
  23067. }
  23068. double MidiMessageSequence::getTimeOfMatchingKeyUp (const int index) const
  23069. {
  23070. const MidiEventHolder* const meh = list [index];
  23071. if (meh != 0 && meh->noteOffObject != 0)
  23072. return meh->noteOffObject->message.getTimeStamp();
  23073. else
  23074. return 0.0;
  23075. }
  23076. int MidiMessageSequence::getIndexOfMatchingKeyUp (const int index) const
  23077. {
  23078. const MidiEventHolder* const meh = list [index];
  23079. return (meh != 0) ? list.indexOf (meh->noteOffObject) : -1;
  23080. }
  23081. int MidiMessageSequence::getIndexOf (MidiEventHolder* const event) const
  23082. {
  23083. return list.indexOf (event);
  23084. }
  23085. int MidiMessageSequence::getNextIndexAtTime (const double timeStamp) const
  23086. {
  23087. const int numEvents = list.size();
  23088. int i;
  23089. for (i = 0; i < numEvents; ++i)
  23090. if (list.getUnchecked(i)->message.getTimeStamp() >= timeStamp)
  23091. break;
  23092. return i;
  23093. }
  23094. double MidiMessageSequence::getStartTime() const
  23095. {
  23096. if (list.size() > 0)
  23097. return list.getUnchecked(0)->message.getTimeStamp();
  23098. else
  23099. return 0;
  23100. }
  23101. double MidiMessageSequence::getEndTime() const
  23102. {
  23103. if (list.size() > 0)
  23104. return list.getLast()->message.getTimeStamp();
  23105. else
  23106. return 0;
  23107. }
  23108. double MidiMessageSequence::getEventTime (const int index) const
  23109. {
  23110. if (((unsigned int) index) < (unsigned int) list.size())
  23111. return list.getUnchecked (index)->message.getTimeStamp();
  23112. return 0.0;
  23113. }
  23114. void MidiMessageSequence::addEvent (const MidiMessage& newMessage,
  23115. double timeAdjustment)
  23116. {
  23117. MidiEventHolder* const newOne = new MidiEventHolder (newMessage);
  23118. timeAdjustment += newMessage.getTimeStamp();
  23119. newOne->message.setTimeStamp (timeAdjustment);
  23120. int i;
  23121. for (i = list.size(); --i >= 0;)
  23122. if (list.getUnchecked(i)->message.getTimeStamp() <= timeAdjustment)
  23123. break;
  23124. list.insert (i + 1, newOne);
  23125. }
  23126. void MidiMessageSequence::deleteEvent (const int index,
  23127. const bool deleteMatchingNoteUp)
  23128. {
  23129. if (((unsigned int) index) < (unsigned int) list.size())
  23130. {
  23131. if (deleteMatchingNoteUp)
  23132. deleteEvent (getIndexOfMatchingKeyUp (index), false);
  23133. list.remove (index);
  23134. }
  23135. }
  23136. void MidiMessageSequence::addSequence (const MidiMessageSequence& other,
  23137. double timeAdjustment,
  23138. double firstAllowableTime,
  23139. double endOfAllowableDestTimes)
  23140. {
  23141. firstAllowableTime -= timeAdjustment;
  23142. endOfAllowableDestTimes -= timeAdjustment;
  23143. for (int i = 0; i < other.list.size(); ++i)
  23144. {
  23145. const MidiMessage& m = other.list.getUnchecked(i)->message;
  23146. const double t = m.getTimeStamp();
  23147. if (t >= firstAllowableTime && t < endOfAllowableDestTimes)
  23148. {
  23149. MidiEventHolder* const newOne = new MidiEventHolder (m);
  23150. newOne->message.setTimeStamp (timeAdjustment + t);
  23151. list.add (newOne);
  23152. }
  23153. }
  23154. sort();
  23155. }
  23156. int MidiMessageSequence::compareElements (const MidiMessageSequence::MidiEventHolder* const first,
  23157. const MidiMessageSequence::MidiEventHolder* const second) throw()
  23158. {
  23159. const double diff = first->message.getTimeStamp()
  23160. - second->message.getTimeStamp();
  23161. return (diff > 0) - (diff < 0);
  23162. }
  23163. void MidiMessageSequence::sort()
  23164. {
  23165. list.sort (*this, true);
  23166. }
  23167. void MidiMessageSequence::updateMatchedPairs()
  23168. {
  23169. for (int i = 0; i < list.size(); ++i)
  23170. {
  23171. const MidiMessage& m1 = list.getUnchecked(i)->message;
  23172. if (m1.isNoteOn())
  23173. {
  23174. list.getUnchecked(i)->noteOffObject = 0;
  23175. const int note = m1.getNoteNumber();
  23176. const int chan = m1.getChannel();
  23177. const int len = list.size();
  23178. for (int j = i + 1; j < len; ++j)
  23179. {
  23180. const MidiMessage& m = list.getUnchecked(j)->message;
  23181. if (m.getNoteNumber() == note && m.getChannel() == chan)
  23182. {
  23183. if (m.isNoteOff())
  23184. {
  23185. list.getUnchecked(i)->noteOffObject = list[j];
  23186. break;
  23187. }
  23188. else if (m.isNoteOn())
  23189. {
  23190. list.insert (j, new MidiEventHolder (MidiMessage::noteOff (chan, note)));
  23191. list.getUnchecked(j)->message.setTimeStamp (m.getTimeStamp());
  23192. list.getUnchecked(i)->noteOffObject = list[j];
  23193. break;
  23194. }
  23195. }
  23196. }
  23197. }
  23198. }
  23199. }
  23200. void MidiMessageSequence::addTimeToMessages (const double delta)
  23201. {
  23202. for (int i = list.size(); --i >= 0;)
  23203. list.getUnchecked (i)->message.setTimeStamp (list.getUnchecked (i)->message.getTimeStamp()
  23204. + delta);
  23205. }
  23206. void MidiMessageSequence::extractMidiChannelMessages (const int channelNumberToExtract,
  23207. MidiMessageSequence& destSequence,
  23208. const bool alsoIncludeMetaEvents) const
  23209. {
  23210. for (int i = 0; i < list.size(); ++i)
  23211. {
  23212. const MidiMessage& mm = list.getUnchecked(i)->message;
  23213. if (mm.isForChannel (channelNumberToExtract)
  23214. || (alsoIncludeMetaEvents && mm.isMetaEvent()))
  23215. {
  23216. destSequence.addEvent (mm);
  23217. }
  23218. }
  23219. }
  23220. void MidiMessageSequence::extractSysExMessages (MidiMessageSequence& destSequence) const
  23221. {
  23222. for (int i = 0; i < list.size(); ++i)
  23223. {
  23224. const MidiMessage& mm = list.getUnchecked(i)->message;
  23225. if (mm.isSysEx())
  23226. destSequence.addEvent (mm);
  23227. }
  23228. }
  23229. void MidiMessageSequence::deleteMidiChannelMessages (const int channelNumberToRemove)
  23230. {
  23231. for (int i = list.size(); --i >= 0;)
  23232. if (list.getUnchecked(i)->message.isForChannel (channelNumberToRemove))
  23233. list.remove(i);
  23234. }
  23235. void MidiMessageSequence::deleteSysExMessages()
  23236. {
  23237. for (int i = list.size(); --i >= 0;)
  23238. if (list.getUnchecked(i)->message.isSysEx())
  23239. list.remove(i);
  23240. }
  23241. void MidiMessageSequence::createControllerUpdatesForTime (const int channelNumber,
  23242. const double time,
  23243. OwnedArray<MidiMessage>& dest)
  23244. {
  23245. bool doneProg = false;
  23246. bool donePitchWheel = false;
  23247. Array <int> doneControllers;
  23248. doneControllers.ensureStorageAllocated (32);
  23249. for (int i = list.size(); --i >= 0;)
  23250. {
  23251. const MidiMessage& mm = list.getUnchecked(i)->message;
  23252. if (mm.isForChannel (channelNumber)
  23253. && mm.getTimeStamp() <= time)
  23254. {
  23255. if (mm.isProgramChange())
  23256. {
  23257. if (! doneProg)
  23258. {
  23259. dest.add (new MidiMessage (mm, 0.0));
  23260. doneProg = true;
  23261. }
  23262. }
  23263. else if (mm.isController())
  23264. {
  23265. if (! doneControllers.contains (mm.getControllerNumber()))
  23266. {
  23267. dest.add (new MidiMessage (mm, 0.0));
  23268. doneControllers.add (mm.getControllerNumber());
  23269. }
  23270. }
  23271. else if (mm.isPitchWheel())
  23272. {
  23273. if (! donePitchWheel)
  23274. {
  23275. dest.add (new MidiMessage (mm, 0.0));
  23276. donePitchWheel = true;
  23277. }
  23278. }
  23279. }
  23280. }
  23281. }
  23282. MidiMessageSequence::MidiEventHolder::MidiEventHolder (const MidiMessage& message_)
  23283. : message (message_),
  23284. noteOffObject (0)
  23285. {
  23286. }
  23287. MidiMessageSequence::MidiEventHolder::~MidiEventHolder()
  23288. {
  23289. }
  23290. END_JUCE_NAMESPACE
  23291. /*** End of inlined file: juce_MidiMessageSequence.cpp ***/
  23292. /*** Start of inlined file: juce_AudioPluginFormat.cpp ***/
  23293. BEGIN_JUCE_NAMESPACE
  23294. AudioPluginFormat::AudioPluginFormat() throw()
  23295. {
  23296. }
  23297. AudioPluginFormat::~AudioPluginFormat()
  23298. {
  23299. }
  23300. END_JUCE_NAMESPACE
  23301. /*** End of inlined file: juce_AudioPluginFormat.cpp ***/
  23302. /*** Start of inlined file: juce_AudioPluginFormatManager.cpp ***/
  23303. BEGIN_JUCE_NAMESPACE
  23304. AudioPluginFormatManager::AudioPluginFormatManager() throw()
  23305. {
  23306. }
  23307. AudioPluginFormatManager::~AudioPluginFormatManager() throw()
  23308. {
  23309. clearSingletonInstance();
  23310. }
  23311. juce_ImplementSingleton_SingleThreaded (AudioPluginFormatManager);
  23312. void AudioPluginFormatManager::addDefaultFormats()
  23313. {
  23314. #if JUCE_DEBUG
  23315. // you should only call this method once!
  23316. for (int i = formats.size(); --i >= 0;)
  23317. {
  23318. #if JUCE_PLUGINHOST_VST && ! (JUCE_MAC && JUCE_64BIT)
  23319. jassert (dynamic_cast <VSTPluginFormat*> (formats[i]) == 0);
  23320. #endif
  23321. #if JUCE_PLUGINHOST_AU && JUCE_MAC
  23322. jassert (dynamic_cast <AudioUnitPluginFormat*> (formats[i]) == 0);
  23323. #endif
  23324. #if JUCE_PLUGINHOST_DX && JUCE_WIN32
  23325. jassert (dynamic_cast <DirectXPluginFormat*> (formats[i]) == 0);
  23326. #endif
  23327. #if JUCE_PLUGINHOST_LADSPA && JUCE_LINUX
  23328. jassert (dynamic_cast <LADSPAPluginFormat*> (formats[i]) == 0);
  23329. #endif
  23330. }
  23331. #endif
  23332. #if JUCE_PLUGINHOST_AU && JUCE_MAC
  23333. formats.add (new AudioUnitPluginFormat());
  23334. #endif
  23335. #if JUCE_PLUGINHOST_VST && ! (JUCE_MAC && JUCE_64BIT)
  23336. formats.add (new VSTPluginFormat());
  23337. #endif
  23338. #if JUCE_PLUGINHOST_DX && JUCE_WIN32
  23339. formats.add (new DirectXPluginFormat());
  23340. #endif
  23341. #if JUCE_PLUGINHOST_LADSPA && JUCE_LINUX
  23342. formats.add (new LADSPAPluginFormat());
  23343. #endif
  23344. }
  23345. int AudioPluginFormatManager::getNumFormats() throw()
  23346. {
  23347. return formats.size();
  23348. }
  23349. AudioPluginFormat* AudioPluginFormatManager::getFormat (const int index) throw()
  23350. {
  23351. return formats [index];
  23352. }
  23353. void AudioPluginFormatManager::addFormat (AudioPluginFormat* const format) throw()
  23354. {
  23355. formats.add (format);
  23356. }
  23357. AudioPluginInstance* AudioPluginFormatManager::createPluginInstance (const PluginDescription& description,
  23358. String& errorMessage) const
  23359. {
  23360. AudioPluginInstance* result = 0;
  23361. for (int i = 0; i < formats.size(); ++i)
  23362. {
  23363. result = formats.getUnchecked(i)->createInstanceFromDescription (description);
  23364. if (result != 0)
  23365. break;
  23366. }
  23367. if (result == 0)
  23368. {
  23369. if (! doesPluginStillExist (description))
  23370. errorMessage = TRANS ("This plug-in file no longer exists");
  23371. else
  23372. errorMessage = TRANS ("This plug-in failed to load correctly");
  23373. }
  23374. return result;
  23375. }
  23376. bool AudioPluginFormatManager::doesPluginStillExist (const PluginDescription& description) const
  23377. {
  23378. for (int i = 0; i < formats.size(); ++i)
  23379. if (formats.getUnchecked(i)->getName() == description.pluginFormatName)
  23380. return formats.getUnchecked(i)->doesPluginStillExist (description);
  23381. return false;
  23382. }
  23383. END_JUCE_NAMESPACE
  23384. /*** End of inlined file: juce_AudioPluginFormatManager.cpp ***/
  23385. /*** Start of inlined file: juce_AudioPluginInstance.cpp ***/
  23386. #define JUCE_PLUGIN_HOST 1
  23387. BEGIN_JUCE_NAMESPACE
  23388. AudioPluginInstance::AudioPluginInstance()
  23389. {
  23390. }
  23391. AudioPluginInstance::~AudioPluginInstance()
  23392. {
  23393. }
  23394. END_JUCE_NAMESPACE
  23395. /*** End of inlined file: juce_AudioPluginInstance.cpp ***/
  23396. /*** Start of inlined file: juce_KnownPluginList.cpp ***/
  23397. BEGIN_JUCE_NAMESPACE
  23398. KnownPluginList::KnownPluginList()
  23399. {
  23400. }
  23401. KnownPluginList::~KnownPluginList()
  23402. {
  23403. }
  23404. void KnownPluginList::clear()
  23405. {
  23406. if (types.size() > 0)
  23407. {
  23408. types.clear();
  23409. sendChangeMessage (this);
  23410. }
  23411. }
  23412. PluginDescription* KnownPluginList::getTypeForFile (const String& fileOrIdentifier) const throw()
  23413. {
  23414. for (int i = 0; i < types.size(); ++i)
  23415. if (types.getUnchecked(i)->fileOrIdentifier == fileOrIdentifier)
  23416. return types.getUnchecked(i);
  23417. return 0;
  23418. }
  23419. PluginDescription* KnownPluginList::getTypeForIdentifierString (const String& identifierString) const throw()
  23420. {
  23421. for (int i = 0; i < types.size(); ++i)
  23422. if (types.getUnchecked(i)->createIdentifierString() == identifierString)
  23423. return types.getUnchecked(i);
  23424. return 0;
  23425. }
  23426. bool KnownPluginList::addType (const PluginDescription& type)
  23427. {
  23428. for (int i = types.size(); --i >= 0;)
  23429. {
  23430. if (types.getUnchecked(i)->isDuplicateOf (type))
  23431. {
  23432. // strange - found a duplicate plugin with different info..
  23433. jassert (types.getUnchecked(i)->name == type.name);
  23434. jassert (types.getUnchecked(i)->isInstrument == type.isInstrument);
  23435. *types.getUnchecked(i) = type;
  23436. return false;
  23437. }
  23438. }
  23439. types.add (new PluginDescription (type));
  23440. sendChangeMessage (this);
  23441. return true;
  23442. }
  23443. void KnownPluginList::removeType (const int index) throw()
  23444. {
  23445. types.remove (index);
  23446. sendChangeMessage (this);
  23447. }
  23448. static Time getFileModTime (const String& fileOrIdentifier) throw()
  23449. {
  23450. if (fileOrIdentifier.startsWithChar ('/')
  23451. || fileOrIdentifier[1] == ':')
  23452. {
  23453. return File (fileOrIdentifier).getLastModificationTime();
  23454. }
  23455. return Time (0);
  23456. }
  23457. static bool timesAreDifferent (const Time& t1, const Time& t2) throw()
  23458. {
  23459. return t1 != t2 || t1 == Time (0);
  23460. }
  23461. bool KnownPluginList::isListingUpToDate (const String& fileOrIdentifier) const throw()
  23462. {
  23463. if (getTypeForFile (fileOrIdentifier) == 0)
  23464. return false;
  23465. for (int i = types.size(); --i >= 0;)
  23466. {
  23467. const PluginDescription* const d = types.getUnchecked(i);
  23468. if (d->fileOrIdentifier == fileOrIdentifier
  23469. && timesAreDifferent (d->lastFileModTime, getFileModTime (fileOrIdentifier)))
  23470. {
  23471. return false;
  23472. }
  23473. }
  23474. return true;
  23475. }
  23476. bool KnownPluginList::scanAndAddFile (const String& fileOrIdentifier,
  23477. const bool dontRescanIfAlreadyInList,
  23478. OwnedArray <PluginDescription>& typesFound,
  23479. AudioPluginFormat& format)
  23480. {
  23481. bool addedOne = false;
  23482. if (dontRescanIfAlreadyInList
  23483. && getTypeForFile (fileOrIdentifier) != 0)
  23484. {
  23485. bool needsRescanning = false;
  23486. for (int i = types.size(); --i >= 0;)
  23487. {
  23488. const PluginDescription* const d = types.getUnchecked(i);
  23489. if (d->fileOrIdentifier == fileOrIdentifier)
  23490. {
  23491. if (timesAreDifferent (d->lastFileModTime, getFileModTime (fileOrIdentifier)))
  23492. needsRescanning = true;
  23493. else
  23494. typesFound.add (new PluginDescription (*d));
  23495. }
  23496. }
  23497. if (! needsRescanning)
  23498. return false;
  23499. }
  23500. OwnedArray <PluginDescription> found;
  23501. format.findAllTypesForFile (found, fileOrIdentifier);
  23502. for (int i = 0; i < found.size(); ++i)
  23503. {
  23504. PluginDescription* const desc = found.getUnchecked(i);
  23505. jassert (desc != 0);
  23506. if (addType (*desc))
  23507. addedOne = true;
  23508. typesFound.add (new PluginDescription (*desc));
  23509. }
  23510. return addedOne;
  23511. }
  23512. void KnownPluginList::scanAndAddDragAndDroppedFiles (const StringArray& files,
  23513. OwnedArray <PluginDescription>& typesFound)
  23514. {
  23515. for (int i = 0; i < files.size(); ++i)
  23516. {
  23517. bool loaded = false;
  23518. for (int j = 0; j < AudioPluginFormatManager::getInstance()->getNumFormats(); ++j)
  23519. {
  23520. AudioPluginFormat* const format = AudioPluginFormatManager::getInstance()->getFormat (j);
  23521. if (scanAndAddFile (files[i], true, typesFound, *format))
  23522. loaded = true;
  23523. }
  23524. if (! loaded)
  23525. {
  23526. const File f (files[i]);
  23527. if (f.isDirectory())
  23528. {
  23529. StringArray s;
  23530. {
  23531. Array<File> subFiles;
  23532. f.findChildFiles (subFiles, File::findFilesAndDirectories, false);
  23533. for (int j = 0; j < subFiles.size(); ++j)
  23534. s.add (subFiles.getReference(j).getFullPathName());
  23535. }
  23536. scanAndAddDragAndDroppedFiles (s, typesFound);
  23537. }
  23538. }
  23539. }
  23540. }
  23541. class PluginSorter
  23542. {
  23543. public:
  23544. KnownPluginList::SortMethod method;
  23545. PluginSorter() throw() {}
  23546. int compareElements (const PluginDescription* const first,
  23547. const PluginDescription* const second) const throw()
  23548. {
  23549. int diff = 0;
  23550. if (method == KnownPluginList::sortByCategory)
  23551. diff = first->category.compareLexicographically (second->category);
  23552. else if (method == KnownPluginList::sortByManufacturer)
  23553. diff = first->manufacturerName.compareLexicographically (second->manufacturerName);
  23554. else if (method == KnownPluginList::sortByFileSystemLocation)
  23555. diff = first->fileOrIdentifier.replaceCharacter ('\\', '/')
  23556. .upToLastOccurrenceOf ("/", false, false)
  23557. .compare (second->fileOrIdentifier.replaceCharacter ('\\', '/')
  23558. .upToLastOccurrenceOf ("/", false, false));
  23559. if (diff == 0)
  23560. diff = first->name.compareLexicographically (second->name);
  23561. return diff;
  23562. }
  23563. };
  23564. void KnownPluginList::sort (const SortMethod method)
  23565. {
  23566. if (method != defaultOrder)
  23567. {
  23568. PluginSorter sorter;
  23569. sorter.method = method;
  23570. types.sort (sorter, true);
  23571. sendChangeMessage (this);
  23572. }
  23573. }
  23574. XmlElement* KnownPluginList::createXml() const
  23575. {
  23576. XmlElement* const e = new XmlElement ("KNOWNPLUGINS");
  23577. for (int i = 0; i < types.size(); ++i)
  23578. e->addChildElement (types.getUnchecked(i)->createXml());
  23579. return e;
  23580. }
  23581. void KnownPluginList::recreateFromXml (const XmlElement& xml)
  23582. {
  23583. clear();
  23584. if (xml.hasTagName ("KNOWNPLUGINS"))
  23585. {
  23586. forEachXmlChildElement (xml, e)
  23587. {
  23588. PluginDescription info;
  23589. if (info.loadFromXml (*e))
  23590. addType (info);
  23591. }
  23592. }
  23593. }
  23594. const int menuIdBase = 0x324503f4;
  23595. // This is used to turn a bunch of paths into a nested menu structure.
  23596. struct PluginFilesystemTree
  23597. {
  23598. private:
  23599. String folder;
  23600. OwnedArray <PluginFilesystemTree> subFolders;
  23601. Array <PluginDescription*> plugins;
  23602. void addPlugin (PluginDescription* const pd, const String& path)
  23603. {
  23604. if (path.isEmpty())
  23605. {
  23606. plugins.add (pd);
  23607. }
  23608. else
  23609. {
  23610. const String firstSubFolder (path.upToFirstOccurrenceOf ("/", false, false));
  23611. const String remainingPath (path.fromFirstOccurrenceOf ("/", false, false));
  23612. for (int i = subFolders.size(); --i >= 0;)
  23613. {
  23614. if (subFolders.getUnchecked(i)->folder.equalsIgnoreCase (firstSubFolder))
  23615. {
  23616. subFolders.getUnchecked(i)->addPlugin (pd, remainingPath);
  23617. return;
  23618. }
  23619. }
  23620. PluginFilesystemTree* const newFolder = new PluginFilesystemTree();
  23621. newFolder->folder = firstSubFolder;
  23622. subFolders.add (newFolder);
  23623. newFolder->addPlugin (pd, remainingPath);
  23624. }
  23625. }
  23626. // removes any deeply nested folders that don't contain any actual plugins
  23627. void optimise()
  23628. {
  23629. for (int i = subFolders.size(); --i >= 0;)
  23630. {
  23631. PluginFilesystemTree* const sub = subFolders.getUnchecked(i);
  23632. sub->optimise();
  23633. if (sub->plugins.size() == 0)
  23634. {
  23635. for (int j = 0; j < sub->subFolders.size(); ++j)
  23636. subFolders.add (sub->subFolders.getUnchecked(j));
  23637. sub->subFolders.clear (false);
  23638. subFolders.remove (i);
  23639. }
  23640. }
  23641. }
  23642. public:
  23643. void buildTree (const Array <PluginDescription*>& allPlugins)
  23644. {
  23645. for (int i = 0; i < allPlugins.size(); ++i)
  23646. {
  23647. String path (allPlugins.getUnchecked(i)
  23648. ->fileOrIdentifier.replaceCharacter ('\\', '/')
  23649. .upToLastOccurrenceOf ("/", false, false));
  23650. if (path.substring (1, 2) == ":")
  23651. path = path.substring (2);
  23652. addPlugin (allPlugins.getUnchecked(i), path);
  23653. }
  23654. optimise();
  23655. }
  23656. void addToMenu (PopupMenu& m, const OwnedArray <PluginDescription>& allPlugins) const
  23657. {
  23658. int i;
  23659. for (i = 0; i < subFolders.size(); ++i)
  23660. {
  23661. const PluginFilesystemTree* const sub = subFolders.getUnchecked(i);
  23662. PopupMenu subMenu;
  23663. sub->addToMenu (subMenu, allPlugins);
  23664. #if JUCE_MAC
  23665. // avoid the special AU formatting nonsense on Mac..
  23666. m.addSubMenu (sub->folder.fromFirstOccurrenceOf (":", false, false), subMenu);
  23667. #else
  23668. m.addSubMenu (sub->folder, subMenu);
  23669. #endif
  23670. }
  23671. for (i = 0; i < plugins.size(); ++i)
  23672. {
  23673. PluginDescription* const plugin = plugins.getUnchecked(i);
  23674. m.addItem (allPlugins.indexOf (plugin) + menuIdBase,
  23675. plugin->name, true, false);
  23676. }
  23677. }
  23678. };
  23679. void KnownPluginList::addToMenu (PopupMenu& menu, const SortMethod sortMethod) const
  23680. {
  23681. Array <PluginDescription*> sorted;
  23682. {
  23683. PluginSorter sorter;
  23684. sorter.method = sortMethod;
  23685. for (int i = 0; i < types.size(); ++i)
  23686. sorted.addSorted (sorter, types.getUnchecked(i));
  23687. }
  23688. if (sortMethod == sortByCategory
  23689. || sortMethod == sortByManufacturer)
  23690. {
  23691. String lastSubMenuName;
  23692. PopupMenu sub;
  23693. for (int i = 0; i < sorted.size(); ++i)
  23694. {
  23695. const PluginDescription* const pd = sorted.getUnchecked(i);
  23696. String thisSubMenuName (sortMethod == sortByCategory ? pd->category
  23697. : pd->manufacturerName);
  23698. if (! thisSubMenuName.containsNonWhitespaceChars())
  23699. thisSubMenuName = "Other";
  23700. if (thisSubMenuName != lastSubMenuName)
  23701. {
  23702. if (sub.getNumItems() > 0)
  23703. {
  23704. menu.addSubMenu (lastSubMenuName, sub);
  23705. sub.clear();
  23706. }
  23707. lastSubMenuName = thisSubMenuName;
  23708. }
  23709. sub.addItem (types.indexOf (pd) + menuIdBase, pd->name, true, false);
  23710. }
  23711. if (sub.getNumItems() > 0)
  23712. menu.addSubMenu (lastSubMenuName, sub);
  23713. }
  23714. else if (sortMethod == sortByFileSystemLocation)
  23715. {
  23716. PluginFilesystemTree root;
  23717. root.buildTree (sorted);
  23718. root.addToMenu (menu, types);
  23719. }
  23720. else
  23721. {
  23722. for (int i = 0; i < sorted.size(); ++i)
  23723. {
  23724. const PluginDescription* const pd = sorted.getUnchecked(i);
  23725. menu.addItem (types.indexOf (pd) + menuIdBase, pd->name, true, false);
  23726. }
  23727. }
  23728. }
  23729. int KnownPluginList::getIndexChosenByMenu (const int menuResultCode) const
  23730. {
  23731. const int i = menuResultCode - menuIdBase;
  23732. return (((unsigned int) i) < (unsigned int) types.size()) ? i : -1;
  23733. }
  23734. END_JUCE_NAMESPACE
  23735. /*** End of inlined file: juce_KnownPluginList.cpp ***/
  23736. /*** Start of inlined file: juce_PluginDescription.cpp ***/
  23737. BEGIN_JUCE_NAMESPACE
  23738. PluginDescription::PluginDescription() throw()
  23739. : uid (0),
  23740. isInstrument (false),
  23741. numInputChannels (0),
  23742. numOutputChannels (0)
  23743. {
  23744. }
  23745. PluginDescription::~PluginDescription() throw()
  23746. {
  23747. }
  23748. PluginDescription::PluginDescription (const PluginDescription& other) throw()
  23749. : name (other.name),
  23750. pluginFormatName (other.pluginFormatName),
  23751. category (other.category),
  23752. manufacturerName (other.manufacturerName),
  23753. version (other.version),
  23754. fileOrIdentifier (other.fileOrIdentifier),
  23755. lastFileModTime (other.lastFileModTime),
  23756. uid (other.uid),
  23757. isInstrument (other.isInstrument),
  23758. numInputChannels (other.numInputChannels),
  23759. numOutputChannels (other.numOutputChannels)
  23760. {
  23761. }
  23762. PluginDescription& PluginDescription::operator= (const PluginDescription& other) throw()
  23763. {
  23764. name = other.name;
  23765. pluginFormatName = other.pluginFormatName;
  23766. category = other.category;
  23767. manufacturerName = other.manufacturerName;
  23768. version = other.version;
  23769. fileOrIdentifier = other.fileOrIdentifier;
  23770. uid = other.uid;
  23771. isInstrument = other.isInstrument;
  23772. lastFileModTime = other.lastFileModTime;
  23773. numInputChannels = other.numInputChannels;
  23774. numOutputChannels = other.numOutputChannels;
  23775. return *this;
  23776. }
  23777. bool PluginDescription::isDuplicateOf (const PluginDescription& other) const
  23778. {
  23779. return fileOrIdentifier == other.fileOrIdentifier
  23780. && uid == other.uid;
  23781. }
  23782. const String PluginDescription::createIdentifierString() const throw()
  23783. {
  23784. return pluginFormatName
  23785. + "-" + name
  23786. + "-" + String::toHexString (fileOrIdentifier.hashCode())
  23787. + "-" + String::toHexString (uid);
  23788. }
  23789. XmlElement* PluginDescription::createXml() const
  23790. {
  23791. XmlElement* const e = new XmlElement ("PLUGIN");
  23792. e->setAttribute ("name", name);
  23793. e->setAttribute ("format", pluginFormatName);
  23794. e->setAttribute ("category", category);
  23795. e->setAttribute ("manufacturer", manufacturerName);
  23796. e->setAttribute ("version", version);
  23797. e->setAttribute ("file", fileOrIdentifier);
  23798. e->setAttribute ("uid", String::toHexString (uid));
  23799. e->setAttribute ("isInstrument", isInstrument);
  23800. e->setAttribute ("fileTime", String::toHexString (lastFileModTime.toMilliseconds()));
  23801. e->setAttribute ("numInputs", numInputChannels);
  23802. e->setAttribute ("numOutputs", numOutputChannels);
  23803. return e;
  23804. }
  23805. bool PluginDescription::loadFromXml (const XmlElement& xml)
  23806. {
  23807. if (xml.hasTagName ("PLUGIN"))
  23808. {
  23809. name = xml.getStringAttribute ("name");
  23810. pluginFormatName = xml.getStringAttribute ("format");
  23811. category = xml.getStringAttribute ("category");
  23812. manufacturerName = xml.getStringAttribute ("manufacturer");
  23813. version = xml.getStringAttribute ("version");
  23814. fileOrIdentifier = xml.getStringAttribute ("file");
  23815. uid = xml.getStringAttribute ("uid").getHexValue32();
  23816. isInstrument = xml.getBoolAttribute ("isInstrument", false);
  23817. lastFileModTime = Time (xml.getStringAttribute ("fileTime").getHexValue64());
  23818. numInputChannels = xml.getIntAttribute ("numInputs");
  23819. numOutputChannels = xml.getIntAttribute ("numOutputs");
  23820. return true;
  23821. }
  23822. return false;
  23823. }
  23824. END_JUCE_NAMESPACE
  23825. /*** End of inlined file: juce_PluginDescription.cpp ***/
  23826. /*** Start of inlined file: juce_PluginDirectoryScanner.cpp ***/
  23827. BEGIN_JUCE_NAMESPACE
  23828. PluginDirectoryScanner::PluginDirectoryScanner (KnownPluginList& listToAddTo,
  23829. AudioPluginFormat& formatToLookFor,
  23830. FileSearchPath directoriesToSearch,
  23831. const bool recursive,
  23832. const File& deadMansPedalFile_)
  23833. : list (listToAddTo),
  23834. format (formatToLookFor),
  23835. deadMansPedalFile (deadMansPedalFile_),
  23836. nextIndex (0),
  23837. progress (0)
  23838. {
  23839. directoriesToSearch.removeRedundantPaths();
  23840. filesOrIdentifiersToScan = format.searchPathsForPlugins (directoriesToSearch, recursive);
  23841. // If any plugins have crashed recently when being loaded, move them to the
  23842. // end of the list to give the others a chance to load correctly..
  23843. const StringArray crashedPlugins (getDeadMansPedalFile());
  23844. for (int i = 0; i < crashedPlugins.size(); ++i)
  23845. {
  23846. const String f = crashedPlugins[i];
  23847. for (int j = filesOrIdentifiersToScan.size(); --j >= 0;)
  23848. if (f == filesOrIdentifiersToScan[j])
  23849. filesOrIdentifiersToScan.move (j, -1);
  23850. }
  23851. }
  23852. PluginDirectoryScanner::~PluginDirectoryScanner()
  23853. {
  23854. }
  23855. const String PluginDirectoryScanner::getNextPluginFileThatWillBeScanned() const throw()
  23856. {
  23857. return format.getNameOfPluginFromIdentifier (filesOrIdentifiersToScan [nextIndex]);
  23858. }
  23859. bool PluginDirectoryScanner::scanNextFile (const bool dontRescanIfAlreadyInList)
  23860. {
  23861. String file (filesOrIdentifiersToScan [nextIndex]);
  23862. if (file.isNotEmpty())
  23863. {
  23864. if (! list.isListingUpToDate (file))
  23865. {
  23866. OwnedArray <PluginDescription> typesFound;
  23867. // Add this plugin to the end of the dead-man's pedal list in case it crashes...
  23868. StringArray crashedPlugins (getDeadMansPedalFile());
  23869. crashedPlugins.removeString (file);
  23870. crashedPlugins.add (file);
  23871. setDeadMansPedalFile (crashedPlugins);
  23872. list.scanAndAddFile (file,
  23873. dontRescanIfAlreadyInList,
  23874. typesFound,
  23875. format);
  23876. // Managed to load without crashing, so remove it from the dead-man's-pedal..
  23877. crashedPlugins.removeString (file);
  23878. setDeadMansPedalFile (crashedPlugins);
  23879. if (typesFound.size() == 0)
  23880. failedFiles.add (file);
  23881. }
  23882. ++nextIndex;
  23883. progress = nextIndex / (float) filesOrIdentifiersToScan.size();
  23884. }
  23885. return nextIndex < filesOrIdentifiersToScan.size();
  23886. }
  23887. const StringArray PluginDirectoryScanner::getDeadMansPedalFile() throw()
  23888. {
  23889. StringArray lines;
  23890. if (deadMansPedalFile != File::nonexistent)
  23891. {
  23892. lines.addLines (deadMansPedalFile.loadFileAsString());
  23893. lines.removeEmptyStrings();
  23894. }
  23895. return lines;
  23896. }
  23897. void PluginDirectoryScanner::setDeadMansPedalFile (const StringArray& newContents) throw()
  23898. {
  23899. if (deadMansPedalFile != File::nonexistent)
  23900. deadMansPedalFile.replaceWithText (newContents.joinIntoString ("\n"), true, true);
  23901. }
  23902. END_JUCE_NAMESPACE
  23903. /*** End of inlined file: juce_PluginDirectoryScanner.cpp ***/
  23904. /*** Start of inlined file: juce_PluginListComponent.cpp ***/
  23905. BEGIN_JUCE_NAMESPACE
  23906. PluginListComponent::PluginListComponent (KnownPluginList& listToEdit,
  23907. const File& deadMansPedalFile_,
  23908. PropertiesFile* const propertiesToUse_)
  23909. : list (listToEdit),
  23910. deadMansPedalFile (deadMansPedalFile_),
  23911. propertiesToUse (propertiesToUse_)
  23912. {
  23913. addAndMakeVisible (listBox = new ListBox (String::empty, this));
  23914. addAndMakeVisible (optionsButton = new TextButton ("Options..."));
  23915. optionsButton->addButtonListener (this);
  23916. optionsButton->setTriggeredOnMouseDown (true);
  23917. setSize (400, 600);
  23918. list.addChangeListener (this);
  23919. }
  23920. PluginListComponent::~PluginListComponent()
  23921. {
  23922. list.removeChangeListener (this);
  23923. deleteAllChildren();
  23924. }
  23925. void PluginListComponent::resized()
  23926. {
  23927. listBox->setBounds (0, 0, getWidth(), getHeight() - 30);
  23928. optionsButton->changeWidthToFitText (24);
  23929. optionsButton->setTopLeftPosition (8, getHeight() - 28);
  23930. }
  23931. void PluginListComponent::changeListenerCallback (void*)
  23932. {
  23933. listBox->updateContent();
  23934. listBox->repaint();
  23935. }
  23936. int PluginListComponent::getNumRows()
  23937. {
  23938. return list.getNumTypes();
  23939. }
  23940. void PluginListComponent::paintListBoxItem (int row,
  23941. Graphics& g,
  23942. int width, int height,
  23943. bool rowIsSelected)
  23944. {
  23945. if (rowIsSelected)
  23946. g.fillAll (findColour (TextEditor::highlightColourId));
  23947. const PluginDescription* const pd = list.getType (row);
  23948. if (pd != 0)
  23949. {
  23950. GlyphArrangement ga;
  23951. ga.addCurtailedLineOfText (Font (height * 0.7f, Font::bold), pd->name, 8.0f, height * 0.8f, width - 10.0f, true);
  23952. g.setColour (Colours::black);
  23953. ga.draw (g);
  23954. const Rectangle<float> bb (ga.getBoundingBox (0, -1, false));
  23955. String desc;
  23956. desc << pd->pluginFormatName
  23957. << (pd->isInstrument ? " instrument" : " effect")
  23958. << " - "
  23959. << pd->numInputChannels << (pd->numInputChannels == 1 ? " in" : " ins")
  23960. << " / "
  23961. << pd->numOutputChannels << (pd->numOutputChannels == 1 ? " out" : " outs");
  23962. if (pd->manufacturerName.isNotEmpty())
  23963. desc << " - " << pd->manufacturerName;
  23964. if (pd->version.isNotEmpty())
  23965. desc << " - " << pd->version;
  23966. if (pd->category.isNotEmpty())
  23967. desc << " - category: '" << pd->category << '\'';
  23968. g.setColour (Colours::grey);
  23969. ga.clear();
  23970. ga.addCurtailedLineOfText (Font (height * 0.6f), desc, bb.getRight() + 10.0f, height * 0.8f, width - bb.getRight() - 12.0f, true);
  23971. ga.draw (g);
  23972. }
  23973. }
  23974. void PluginListComponent::deleteKeyPressed (int lastRowSelected)
  23975. {
  23976. list.removeType (lastRowSelected);
  23977. }
  23978. void PluginListComponent::buttonClicked (Button* b)
  23979. {
  23980. if (optionsButton == b)
  23981. {
  23982. PopupMenu menu;
  23983. menu.addItem (1, TRANS("Clear list"));
  23984. menu.addItem (5, TRANS("Remove selected plugin from list"), listBox->getNumSelectedRows() > 0);
  23985. menu.addItem (6, TRANS("Show folder containing selected plugin"), listBox->getNumSelectedRows() > 0);
  23986. menu.addItem (7, TRANS("Remove any plugins whose files no longer exist"));
  23987. menu.addSeparator();
  23988. menu.addItem (2, TRANS("Sort alphabetically"));
  23989. menu.addItem (3, TRANS("Sort by category"));
  23990. menu.addItem (4, TRANS("Sort by manufacturer"));
  23991. menu.addSeparator();
  23992. for (int i = 0; i < AudioPluginFormatManager::getInstance()->getNumFormats(); ++i)
  23993. {
  23994. AudioPluginFormat* const format = AudioPluginFormatManager::getInstance()->getFormat (i);
  23995. if (format->getDefaultLocationsToSearch().getNumPaths() > 0)
  23996. menu.addItem (10 + i, "Scan for new or updated " + format->getName() + " plugins...");
  23997. }
  23998. const int r = menu.showAt (optionsButton);
  23999. if (r == 1)
  24000. {
  24001. list.clear();
  24002. }
  24003. else if (r == 2)
  24004. {
  24005. list.sort (KnownPluginList::sortAlphabetically);
  24006. }
  24007. else if (r == 3)
  24008. {
  24009. list.sort (KnownPluginList::sortByCategory);
  24010. }
  24011. else if (r == 4)
  24012. {
  24013. list.sort (KnownPluginList::sortByManufacturer);
  24014. }
  24015. else if (r == 5)
  24016. {
  24017. const SparseSet <int> selected (listBox->getSelectedRows());
  24018. for (int i = list.getNumTypes(); --i >= 0;)
  24019. if (selected.contains (i))
  24020. list.removeType (i);
  24021. }
  24022. else if (r == 6)
  24023. {
  24024. const PluginDescription* const desc = list.getType (listBox->getSelectedRow());
  24025. if (desc != 0)
  24026. {
  24027. if (File (desc->fileOrIdentifier).existsAsFile())
  24028. File (desc->fileOrIdentifier).getParentDirectory().startAsProcess();
  24029. }
  24030. }
  24031. else if (r == 7)
  24032. {
  24033. for (int i = list.getNumTypes(); --i >= 0;)
  24034. {
  24035. if (! AudioPluginFormatManager::getInstance()->doesPluginStillExist (*list.getType (i)))
  24036. {
  24037. list.removeType (i);
  24038. }
  24039. }
  24040. }
  24041. else if (r != 0)
  24042. {
  24043. typeToScan = r - 10;
  24044. startTimer (1);
  24045. }
  24046. }
  24047. }
  24048. void PluginListComponent::timerCallback()
  24049. {
  24050. stopTimer();
  24051. scanFor (AudioPluginFormatManager::getInstance()->getFormat (typeToScan));
  24052. }
  24053. bool PluginListComponent::isInterestedInFileDrag (const StringArray& /*files*/)
  24054. {
  24055. return true;
  24056. }
  24057. void PluginListComponent::filesDropped (const StringArray& files, int, int)
  24058. {
  24059. OwnedArray <PluginDescription> typesFound;
  24060. list.scanAndAddDragAndDroppedFiles (files, typesFound);
  24061. }
  24062. void PluginListComponent::scanFor (AudioPluginFormat* format)
  24063. {
  24064. if (format == 0)
  24065. return;
  24066. FileSearchPath path (format->getDefaultLocationsToSearch());
  24067. if (propertiesToUse != 0)
  24068. path = propertiesToUse->getValue ("lastPluginScanPath_" + format->getName(), path.toString());
  24069. {
  24070. AlertWindow aw (TRANS("Select folders to scan..."), String::empty, AlertWindow::NoIcon);
  24071. FileSearchPathListComponent pathList;
  24072. pathList.setSize (500, 300);
  24073. pathList.setPath (path);
  24074. aw.addCustomComponent (&pathList);
  24075. aw.addButton (TRANS("Scan"), 1, KeyPress::returnKey);
  24076. aw.addButton (TRANS("Cancel"), 0, KeyPress (KeyPress::escapeKey));
  24077. if (aw.runModalLoop() == 0)
  24078. return;
  24079. path = pathList.getPath();
  24080. }
  24081. if (propertiesToUse != 0)
  24082. {
  24083. propertiesToUse->setValue ("lastPluginScanPath_" + format->getName(), path.toString());
  24084. propertiesToUse->saveIfNeeded();
  24085. }
  24086. double progress = 0.0;
  24087. AlertWindow aw (TRANS("Scanning for plugins..."),
  24088. TRANS("Searching for all possible plugin files..."), AlertWindow::NoIcon);
  24089. aw.addButton (TRANS("Cancel"), 0, KeyPress (KeyPress::escapeKey));
  24090. aw.addProgressBarComponent (progress);
  24091. aw.enterModalState();
  24092. MessageManager::getInstance()->runDispatchLoopUntil (300);
  24093. PluginDirectoryScanner scanner (list, *format, path, true, deadMansPedalFile);
  24094. for (;;)
  24095. {
  24096. aw.setMessage (TRANS("Testing:\n\n")
  24097. + scanner.getNextPluginFileThatWillBeScanned());
  24098. MessageManager::getInstance()->runDispatchLoopUntil (20);
  24099. if (! scanner.scanNextFile (true))
  24100. break;
  24101. if (! aw.isCurrentlyModal())
  24102. break;
  24103. progress = scanner.getProgress();
  24104. }
  24105. if (scanner.getFailedFiles().size() > 0)
  24106. {
  24107. StringArray shortNames;
  24108. for (int i = 0; i < scanner.getFailedFiles().size(); ++i)
  24109. shortNames.add (File (scanner.getFailedFiles()[i]).getFileName());
  24110. AlertWindow::showMessageBox (AlertWindow::InfoIcon,
  24111. TRANS("Scan complete"),
  24112. TRANS("Note that the following files appeared to be plugin files, but failed to load correctly:\n\n")
  24113. + shortNames.joinIntoString (", "));
  24114. }
  24115. }
  24116. END_JUCE_NAMESPACE
  24117. /*** End of inlined file: juce_PluginListComponent.cpp ***/
  24118. /*** Start of inlined file: juce_AudioUnitPluginFormat.mm ***/
  24119. #if JUCE_PLUGINHOST_AU && ! (JUCE_LINUX || JUCE_WINDOWS)
  24120. #include <AudioUnit/AudioUnit.h>
  24121. #include <AudioUnit/AUCocoaUIView.h>
  24122. #include <CoreAudioKit/AUGenericView.h>
  24123. #if JUCE_SUPPORT_CARBON
  24124. #include <AudioToolbox/AudioUnitUtilities.h>
  24125. #include <AudioUnit/AudioUnitCarbonView.h>
  24126. #endif
  24127. BEGIN_JUCE_NAMESPACE
  24128. #if JUCE_MAC && JUCE_SUPPORT_CARBON
  24129. #endif
  24130. #if JUCE_MAC
  24131. // Change this to disable logging of various activities
  24132. #ifndef AU_LOGGING
  24133. #define AU_LOGGING 1
  24134. #endif
  24135. #if AU_LOGGING
  24136. #define log(a) Logger::writeToLog(a);
  24137. #else
  24138. #define log(a)
  24139. #endif
  24140. static int insideCallback = 0;
  24141. static const String osTypeToString (OSType type)
  24142. {
  24143. char s[4];
  24144. s[0] = (char) (((uint32) type) >> 24);
  24145. s[1] = (char) (((uint32) type) >> 16);
  24146. s[2] = (char) (((uint32) type) >> 8);
  24147. s[3] = (char) ((uint32) type);
  24148. return String (s, 4);
  24149. }
  24150. static OSType stringToOSType (const String& s1)
  24151. {
  24152. const String s (s1 + " ");
  24153. return (((OSType) (unsigned char) s[0]) << 24)
  24154. | (((OSType) (unsigned char) s[1]) << 16)
  24155. | (((OSType) (unsigned char) s[2]) << 8)
  24156. | ((OSType) (unsigned char) s[3]);
  24157. }
  24158. static const char* auIdentifierPrefix = "AudioUnit:";
  24159. static const String createAUPluginIdentifier (const ComponentDescription& desc)
  24160. {
  24161. jassert (osTypeToString ('abcd') == "abcd"); // agh, must have got the endianness wrong..
  24162. jassert (stringToOSType ("abcd") == (OSType) 'abcd'); // ditto
  24163. String s (auIdentifierPrefix);
  24164. if (desc.componentType == kAudioUnitType_MusicDevice)
  24165. s << "Synths/";
  24166. else if (desc.componentType == kAudioUnitType_MusicEffect
  24167. || desc.componentType == kAudioUnitType_Effect)
  24168. s << "Effects/";
  24169. else if (desc.componentType == kAudioUnitType_Generator)
  24170. s << "Generators/";
  24171. else if (desc.componentType == kAudioUnitType_Panner)
  24172. s << "Panners/";
  24173. s << osTypeToString (desc.componentType) << ","
  24174. << osTypeToString (desc.componentSubType) << ","
  24175. << osTypeToString (desc.componentManufacturer);
  24176. return s;
  24177. }
  24178. static void getAUDetails (ComponentRecord* comp, String& name, String& manufacturer)
  24179. {
  24180. Handle componentNameHandle = NewHandle (sizeof (void*));
  24181. Handle componentInfoHandle = NewHandle (sizeof (void*));
  24182. if (componentNameHandle != 0 && componentInfoHandle != 0)
  24183. {
  24184. ComponentDescription desc;
  24185. if (GetComponentInfo (comp, &desc, componentNameHandle, componentInfoHandle, 0) == noErr)
  24186. {
  24187. ConstStr255Param nameString = (ConstStr255Param) (*componentNameHandle);
  24188. ConstStr255Param infoString = (ConstStr255Param) (*componentInfoHandle);
  24189. if (nameString != 0 && nameString[0] != 0)
  24190. {
  24191. const String all ((const char*) nameString + 1, nameString[0]);
  24192. DBG ("name: "+ all);
  24193. manufacturer = all.upToFirstOccurrenceOf (":", false, false).trim();
  24194. name = all.fromFirstOccurrenceOf (":", false, false).trim();
  24195. }
  24196. if (infoString != 0 && infoString[0] != 0)
  24197. {
  24198. DBG ("info: " + String ((const char*) infoString + 1, infoString[0]));
  24199. }
  24200. if (name.isEmpty())
  24201. name = "<Unknown>";
  24202. }
  24203. DisposeHandle (componentNameHandle);
  24204. DisposeHandle (componentInfoHandle);
  24205. }
  24206. }
  24207. static bool getComponentDescFromIdentifier (const String& fileOrIdentifier, ComponentDescription& desc,
  24208. String& name, String& version, String& manufacturer)
  24209. {
  24210. zerostruct (desc);
  24211. if (fileOrIdentifier.startsWithIgnoreCase (auIdentifierPrefix))
  24212. {
  24213. String s (fileOrIdentifier.substring (jmax (fileOrIdentifier.lastIndexOfChar (':'),
  24214. fileOrIdentifier.lastIndexOfChar ('/')) + 1));
  24215. StringArray tokens;
  24216. tokens.addTokens (s, ",", String::empty);
  24217. tokens.trim();
  24218. tokens.removeEmptyStrings();
  24219. if (tokens.size() == 3)
  24220. {
  24221. desc.componentType = stringToOSType (tokens[0]);
  24222. desc.componentSubType = stringToOSType (tokens[1]);
  24223. desc.componentManufacturer = stringToOSType (tokens[2]);
  24224. ComponentRecord* comp = FindNextComponent (0, &desc);
  24225. if (comp != 0)
  24226. {
  24227. getAUDetails (comp, name, manufacturer);
  24228. return true;
  24229. }
  24230. }
  24231. }
  24232. return false;
  24233. }
  24234. class AudioUnitPluginWindowCarbon;
  24235. class AudioUnitPluginWindowCocoa;
  24236. class AudioUnitPluginInstance : public AudioPluginInstance
  24237. {
  24238. public:
  24239. ~AudioUnitPluginInstance();
  24240. // AudioPluginInstance methods:
  24241. void fillInPluginDescription (PluginDescription& desc) const
  24242. {
  24243. desc.name = pluginName;
  24244. desc.fileOrIdentifier = createAUPluginIdentifier (componentDesc);
  24245. desc.uid = ((int) componentDesc.componentType)
  24246. ^ ((int) componentDesc.componentSubType)
  24247. ^ ((int) componentDesc.componentManufacturer);
  24248. desc.lastFileModTime = 0;
  24249. desc.pluginFormatName = "AudioUnit";
  24250. desc.category = getCategory();
  24251. desc.manufacturerName = manufacturer;
  24252. desc.version = version;
  24253. desc.numInputChannels = getNumInputChannels();
  24254. desc.numOutputChannels = getNumOutputChannels();
  24255. desc.isInstrument = (componentDesc.componentType == kAudioUnitType_MusicDevice);
  24256. }
  24257. const String getName() const { return pluginName; }
  24258. bool acceptsMidi() const { return wantsMidiMessages; }
  24259. bool producesMidi() const { return false; }
  24260. // AudioProcessor methods:
  24261. void prepareToPlay (double sampleRate, int estimatedSamplesPerBlock);
  24262. void releaseResources();
  24263. void processBlock (AudioSampleBuffer& buffer,
  24264. MidiBuffer& midiMessages);
  24265. AudioProcessorEditor* createEditor();
  24266. const String getInputChannelName (const int index) const;
  24267. bool isInputChannelStereoPair (int index) const;
  24268. const String getOutputChannelName (const int index) const;
  24269. bool isOutputChannelStereoPair (int index) const;
  24270. int getNumParameters();
  24271. float getParameter (int index);
  24272. void setParameter (int index, float newValue);
  24273. const String getParameterName (int index);
  24274. const String getParameterText (int index);
  24275. bool isParameterAutomatable (int index) const;
  24276. int getNumPrograms();
  24277. int getCurrentProgram();
  24278. void setCurrentProgram (int index);
  24279. const String getProgramName (int index);
  24280. void changeProgramName (int index, const String& newName);
  24281. void getStateInformation (MemoryBlock& destData);
  24282. void getCurrentProgramStateInformation (MemoryBlock& destData);
  24283. void setStateInformation (const void* data, int sizeInBytes);
  24284. void setCurrentProgramStateInformation (const void* data, int sizeInBytes);
  24285. juce_UseDebuggingNewOperator
  24286. private:
  24287. friend class AudioUnitPluginWindowCarbon;
  24288. friend class AudioUnitPluginWindowCocoa;
  24289. friend class AudioUnitPluginFormat;
  24290. ComponentDescription componentDesc;
  24291. String pluginName, manufacturer, version;
  24292. String fileOrIdentifier;
  24293. CriticalSection lock;
  24294. bool initialised, wantsMidiMessages, wasPlaying;
  24295. HeapBlock <AudioBufferList> outputBufferList;
  24296. AudioTimeStamp timeStamp;
  24297. AudioSampleBuffer* currentBuffer;
  24298. AudioUnit audioUnit;
  24299. Array <int> parameterIds;
  24300. bool getComponentDescFromFile (const String& fileOrIdentifier);
  24301. void initialise();
  24302. OSStatus renderGetInput (AudioUnitRenderActionFlags* ioActionFlags,
  24303. const AudioTimeStamp* inTimeStamp,
  24304. UInt32 inBusNumber,
  24305. UInt32 inNumberFrames,
  24306. AudioBufferList* ioData) const;
  24307. static OSStatus renderGetInputCallback (void* inRefCon,
  24308. AudioUnitRenderActionFlags* ioActionFlags,
  24309. const AudioTimeStamp* inTimeStamp,
  24310. UInt32 inBusNumber,
  24311. UInt32 inNumberFrames,
  24312. AudioBufferList* ioData)
  24313. {
  24314. return ((AudioUnitPluginInstance*) inRefCon)
  24315. ->renderGetInput (ioActionFlags, inTimeStamp, inBusNumber, inNumberFrames, ioData);
  24316. }
  24317. OSStatus getBeatAndTempo (Float64* outCurrentBeat, Float64* outCurrentTempo) const;
  24318. OSStatus getMusicalTimeLocation (UInt32* outDeltaSampleOffsetToNextBeat, Float32* outTimeSig_Numerator,
  24319. UInt32* outTimeSig_Denominator, Float64* outCurrentMeasureDownBeat) const;
  24320. OSStatus getTransportState (Boolean* outIsPlaying, Boolean* outTransportStateChanged,
  24321. Float64* outCurrentSampleInTimeLine, Boolean* outIsCycling,
  24322. Float64* outCycleStartBeat, Float64* outCycleEndBeat);
  24323. static OSStatus getBeatAndTempoCallback (void* inHostUserData, Float64* outCurrentBeat, Float64* outCurrentTempo)
  24324. {
  24325. return ((AudioUnitPluginInstance*) inHostUserData)->getBeatAndTempo (outCurrentBeat, outCurrentTempo);
  24326. }
  24327. static OSStatus getMusicalTimeLocationCallback (void* inHostUserData, UInt32* outDeltaSampleOffsetToNextBeat,
  24328. Float32* outTimeSig_Numerator, UInt32* outTimeSig_Denominator,
  24329. Float64* outCurrentMeasureDownBeat)
  24330. {
  24331. return ((AudioUnitPluginInstance*) inHostUserData)
  24332. ->getMusicalTimeLocation (outDeltaSampleOffsetToNextBeat, outTimeSig_Numerator,
  24333. outTimeSig_Denominator, outCurrentMeasureDownBeat);
  24334. }
  24335. static OSStatus getTransportStateCallback (void* inHostUserData, Boolean* outIsPlaying, Boolean* outTransportStateChanged,
  24336. Float64* outCurrentSampleInTimeLine, Boolean* outIsCycling,
  24337. Float64* outCycleStartBeat, Float64* outCycleEndBeat)
  24338. {
  24339. return ((AudioUnitPluginInstance*) inHostUserData)
  24340. ->getTransportState (outIsPlaying, outTransportStateChanged,
  24341. outCurrentSampleInTimeLine, outIsCycling,
  24342. outCycleStartBeat, outCycleEndBeat);
  24343. }
  24344. void getNumChannels (int& numIns, int& numOuts)
  24345. {
  24346. numIns = 0;
  24347. numOuts = 0;
  24348. AUChannelInfo supportedChannels [128];
  24349. UInt32 supportedChannelsSize = sizeof (supportedChannels);
  24350. if (AudioUnitGetProperty (audioUnit, kAudioUnitProperty_SupportedNumChannels, kAudioUnitScope_Global,
  24351. 0, supportedChannels, &supportedChannelsSize) == noErr
  24352. && supportedChannelsSize > 0)
  24353. {
  24354. for (int i = 0; i < supportedChannelsSize / sizeof (AUChannelInfo); ++i)
  24355. {
  24356. numIns = jmax (numIns, (int) supportedChannels[i].inChannels);
  24357. numOuts = jmax (numOuts, (int) supportedChannels[i].outChannels);
  24358. }
  24359. }
  24360. else
  24361. {
  24362. // (this really means the plugin will take any number of ins/outs as long
  24363. // as they are the same)
  24364. numIns = numOuts = 2;
  24365. }
  24366. }
  24367. const String getCategory() const;
  24368. AudioUnitPluginInstance (const String& fileOrIdentifier);
  24369. };
  24370. AudioUnitPluginInstance::AudioUnitPluginInstance (const String& fileOrIdentifier)
  24371. : fileOrIdentifier (fileOrIdentifier),
  24372. initialised (false),
  24373. wantsMidiMessages (false),
  24374. audioUnit (0),
  24375. currentBuffer (0)
  24376. {
  24377. try
  24378. {
  24379. ++insideCallback;
  24380. log ("Opening AU: " + fileOrIdentifier);
  24381. if (getComponentDescFromFile (fileOrIdentifier))
  24382. {
  24383. ComponentRecord* const comp = FindNextComponent (0, &componentDesc);
  24384. if (comp != 0)
  24385. {
  24386. audioUnit = (AudioUnit) OpenComponent (comp);
  24387. wantsMidiMessages = componentDesc.componentType == kAudioUnitType_MusicDevice
  24388. || componentDesc.componentType == kAudioUnitType_MusicEffect;
  24389. }
  24390. }
  24391. --insideCallback;
  24392. }
  24393. catch (...)
  24394. {
  24395. --insideCallback;
  24396. }
  24397. }
  24398. AudioUnitPluginInstance::~AudioUnitPluginInstance()
  24399. {
  24400. const ScopedLock sl (lock);
  24401. jassert (insideCallback == 0);
  24402. if (audioUnit != 0)
  24403. {
  24404. AudioUnitUninitialize (audioUnit);
  24405. CloseComponent (audioUnit);
  24406. audioUnit = 0;
  24407. }
  24408. }
  24409. bool AudioUnitPluginInstance::getComponentDescFromFile (const String& fileOrIdentifier)
  24410. {
  24411. zerostruct (componentDesc);
  24412. if (getComponentDescFromIdentifier (fileOrIdentifier, componentDesc, pluginName, version, manufacturer))
  24413. return true;
  24414. const File file (fileOrIdentifier);
  24415. if (! file.hasFileExtension (".component"))
  24416. return false;
  24417. const char* const utf8 = fileOrIdentifier.toUTF8();
  24418. CFURLRef url = CFURLCreateFromFileSystemRepresentation (0, (const UInt8*) utf8,
  24419. strlen (utf8), file.isDirectory());
  24420. if (url != 0)
  24421. {
  24422. CFBundleRef bundleRef = CFBundleCreate (kCFAllocatorDefault, url);
  24423. CFRelease (url);
  24424. if (bundleRef != 0)
  24425. {
  24426. CFTypeRef name = CFBundleGetValueForInfoDictionaryKey (bundleRef, CFSTR("CFBundleName"));
  24427. if (name != 0 && CFGetTypeID (name) == CFStringGetTypeID())
  24428. pluginName = PlatformUtilities::cfStringToJuceString ((CFStringRef) name);
  24429. if (pluginName.isEmpty())
  24430. pluginName = file.getFileNameWithoutExtension();
  24431. CFTypeRef versionString = CFBundleGetValueForInfoDictionaryKey (bundleRef, CFSTR("CFBundleVersion"));
  24432. if (versionString != 0 && CFGetTypeID (versionString) == CFStringGetTypeID())
  24433. version = PlatformUtilities::cfStringToJuceString ((CFStringRef) versionString);
  24434. CFTypeRef manuString = CFBundleGetValueForInfoDictionaryKey (bundleRef, CFSTR("CFBundleGetInfoString"));
  24435. if (manuString != 0 && CFGetTypeID (manuString) == CFStringGetTypeID())
  24436. manufacturer = PlatformUtilities::cfStringToJuceString ((CFStringRef) manuString);
  24437. short resFileId = CFBundleOpenBundleResourceMap (bundleRef);
  24438. UseResFile (resFileId);
  24439. for (int i = 1; i <= Count1Resources ('thng'); ++i)
  24440. {
  24441. Handle h = Get1IndResource ('thng', i);
  24442. if (h != 0)
  24443. {
  24444. HLock (h);
  24445. const uint32* const types = (const uint32*) *h;
  24446. if (types[0] == kAudioUnitType_MusicDevice
  24447. || types[0] == kAudioUnitType_MusicEffect
  24448. || types[0] == kAudioUnitType_Effect
  24449. || types[0] == kAudioUnitType_Generator
  24450. || types[0] == kAudioUnitType_Panner)
  24451. {
  24452. componentDesc.componentType = types[0];
  24453. componentDesc.componentSubType = types[1];
  24454. componentDesc.componentManufacturer = types[2];
  24455. break;
  24456. }
  24457. HUnlock (h);
  24458. ReleaseResource (h);
  24459. }
  24460. }
  24461. CFBundleCloseBundleResourceMap (bundleRef, resFileId);
  24462. CFRelease (bundleRef);
  24463. }
  24464. }
  24465. return componentDesc.componentType != 0 && componentDesc.componentSubType != 0;
  24466. }
  24467. void AudioUnitPluginInstance::initialise()
  24468. {
  24469. if (initialised || audioUnit == 0)
  24470. return;
  24471. log ("Initialising AU: " + pluginName);
  24472. parameterIds.clear();
  24473. {
  24474. UInt32 paramListSize = 0;
  24475. AudioUnitGetProperty (audioUnit, kAudioUnitProperty_ParameterList, kAudioUnitScope_Global,
  24476. 0, 0, &paramListSize);
  24477. if (paramListSize > 0)
  24478. {
  24479. parameterIds.insertMultiple (0, 0, paramListSize / sizeof (int));
  24480. AudioUnitGetProperty (audioUnit, kAudioUnitProperty_ParameterList, kAudioUnitScope_Global,
  24481. 0, &parameterIds.getReference(0), &paramListSize);
  24482. }
  24483. }
  24484. {
  24485. AURenderCallbackStruct info;
  24486. zerostruct (info);
  24487. info.inputProcRefCon = this;
  24488. info.inputProc = renderGetInputCallback;
  24489. AudioUnitSetProperty (audioUnit, kAudioUnitProperty_SetRenderCallback, kAudioUnitScope_Input,
  24490. 0, &info, sizeof (info));
  24491. }
  24492. {
  24493. HostCallbackInfo info;
  24494. zerostruct (info);
  24495. info.hostUserData = this;
  24496. info.beatAndTempoProc = getBeatAndTempoCallback;
  24497. info.musicalTimeLocationProc = getMusicalTimeLocationCallback;
  24498. info.transportStateProc = getTransportStateCallback;
  24499. AudioUnitSetProperty (audioUnit, kAudioUnitProperty_HostCallbacks, kAudioUnitScope_Global,
  24500. 0, &info, sizeof (info));
  24501. }
  24502. int numIns, numOuts;
  24503. getNumChannels (numIns, numOuts);
  24504. setPlayConfigDetails (numIns, numOuts, 0, 0);
  24505. initialised = AudioUnitInitialize (audioUnit) == noErr;
  24506. setLatencySamples (0);
  24507. }
  24508. void AudioUnitPluginInstance::prepareToPlay (double sampleRate_,
  24509. int samplesPerBlockExpected)
  24510. {
  24511. initialise();
  24512. if (initialised)
  24513. {
  24514. int numIns, numOuts;
  24515. getNumChannels (numIns, numOuts);
  24516. setPlayConfigDetails (numIns, numOuts, sampleRate_, samplesPerBlockExpected);
  24517. Float64 latencySecs = 0.0;
  24518. UInt32 latencySize = sizeof (latencySecs);
  24519. AudioUnitGetProperty (audioUnit, kAudioUnitProperty_Latency, kAudioUnitScope_Global,
  24520. 0, &latencySecs, &latencySize);
  24521. setLatencySamples (roundToInt (latencySecs * sampleRate_));
  24522. AudioUnitReset (audioUnit, kAudioUnitScope_Input, 0);
  24523. AudioUnitReset (audioUnit, kAudioUnitScope_Output, 0);
  24524. AudioUnitReset (audioUnit, kAudioUnitScope_Global, 0);
  24525. AudioStreamBasicDescription stream;
  24526. zerostruct (stream);
  24527. stream.mSampleRate = sampleRate_;
  24528. stream.mFormatID = kAudioFormatLinearPCM;
  24529. stream.mFormatFlags = kAudioFormatFlagsNativeFloatPacked | kAudioFormatFlagIsNonInterleaved;
  24530. stream.mFramesPerPacket = 1;
  24531. stream.mBytesPerPacket = 4;
  24532. stream.mBytesPerFrame = 4;
  24533. stream.mBitsPerChannel = 32;
  24534. stream.mChannelsPerFrame = numIns;
  24535. OSStatus err = AudioUnitSetProperty (audioUnit,
  24536. kAudioUnitProperty_StreamFormat,
  24537. kAudioUnitScope_Input,
  24538. 0, &stream, sizeof (stream));
  24539. stream.mChannelsPerFrame = numOuts;
  24540. err = AudioUnitSetProperty (audioUnit,
  24541. kAudioUnitProperty_StreamFormat,
  24542. kAudioUnitScope_Output,
  24543. 0, &stream, sizeof (stream));
  24544. outputBufferList.calloc (sizeof (AudioBufferList) + sizeof (AudioBuffer) * (numOuts + 1), 1);
  24545. outputBufferList->mNumberBuffers = numOuts;
  24546. for (int i = numOuts; --i >= 0;)
  24547. outputBufferList->mBuffers[i].mNumberChannels = 1;
  24548. zerostruct (timeStamp);
  24549. timeStamp.mSampleTime = 0;
  24550. timeStamp.mHostTime = AudioGetCurrentHostTime();
  24551. timeStamp.mFlags = kAudioTimeStampSampleTimeValid | kAudioTimeStampHostTimeValid;
  24552. currentBuffer = 0;
  24553. wasPlaying = false;
  24554. }
  24555. }
  24556. void AudioUnitPluginInstance::releaseResources()
  24557. {
  24558. if (initialised)
  24559. {
  24560. AudioUnitReset (audioUnit, kAudioUnitScope_Input, 0);
  24561. AudioUnitReset (audioUnit, kAudioUnitScope_Output, 0);
  24562. AudioUnitReset (audioUnit, kAudioUnitScope_Global, 0);
  24563. outputBufferList.free();
  24564. currentBuffer = 0;
  24565. }
  24566. }
  24567. OSStatus AudioUnitPluginInstance::renderGetInput (AudioUnitRenderActionFlags* ioActionFlags,
  24568. const AudioTimeStamp* inTimeStamp,
  24569. UInt32 inBusNumber,
  24570. UInt32 inNumberFrames,
  24571. AudioBufferList* ioData) const
  24572. {
  24573. if (inBusNumber == 0
  24574. && currentBuffer != 0)
  24575. {
  24576. jassert (inNumberFrames == currentBuffer->getNumSamples()); // if this ever happens, might need to add extra handling
  24577. for (int i = 0; i < ioData->mNumberBuffers; ++i)
  24578. {
  24579. if (i < currentBuffer->getNumChannels())
  24580. {
  24581. memcpy (ioData->mBuffers[i].mData,
  24582. currentBuffer->getSampleData (i, 0),
  24583. sizeof (float) * inNumberFrames);
  24584. }
  24585. else
  24586. {
  24587. zeromem (ioData->mBuffers[i].mData, sizeof (float) * inNumberFrames);
  24588. }
  24589. }
  24590. }
  24591. return noErr;
  24592. }
  24593. void AudioUnitPluginInstance::processBlock (AudioSampleBuffer& buffer,
  24594. MidiBuffer& midiMessages)
  24595. {
  24596. const int numSamples = buffer.getNumSamples();
  24597. if (initialised)
  24598. {
  24599. AudioUnitRenderActionFlags flags = 0;
  24600. timeStamp.mHostTime = AudioGetCurrentHostTime();
  24601. for (int i = getNumOutputChannels(); --i >= 0;)
  24602. {
  24603. outputBufferList->mBuffers[i].mDataByteSize = sizeof (float) * numSamples;
  24604. outputBufferList->mBuffers[i].mData = buffer.getSampleData (i, 0);
  24605. }
  24606. currentBuffer = &buffer;
  24607. if (wantsMidiMessages)
  24608. {
  24609. const uint8* midiEventData;
  24610. int midiEventSize, midiEventPosition;
  24611. MidiBuffer::Iterator i (midiMessages);
  24612. while (i.getNextEvent (midiEventData, midiEventSize, midiEventPosition))
  24613. {
  24614. if (midiEventSize <= 3)
  24615. MusicDeviceMIDIEvent (audioUnit,
  24616. midiEventData[0], midiEventData[1], midiEventData[2],
  24617. midiEventPosition);
  24618. else
  24619. MusicDeviceSysEx (audioUnit, midiEventData, midiEventSize);
  24620. }
  24621. midiMessages.clear();
  24622. }
  24623. AudioUnitRender (audioUnit, &flags, &timeStamp,
  24624. 0, numSamples, outputBufferList);
  24625. timeStamp.mSampleTime += numSamples;
  24626. }
  24627. else
  24628. {
  24629. // Not initialised, so just bypass..
  24630. for (int i = getNumInputChannels(); i < getNumOutputChannels(); ++i)
  24631. buffer.clear (i, 0, buffer.getNumSamples());
  24632. }
  24633. }
  24634. OSStatus AudioUnitPluginInstance::getBeatAndTempo (Float64* outCurrentBeat, Float64* outCurrentTempo) const
  24635. {
  24636. AudioPlayHead* const ph = getPlayHead();
  24637. AudioPlayHead::CurrentPositionInfo result;
  24638. if (ph != 0 && ph->getCurrentPosition (result))
  24639. {
  24640. if (outCurrentBeat != 0)
  24641. *outCurrentBeat = result.ppqPosition;
  24642. if (outCurrentTempo != 0)
  24643. *outCurrentTempo = result.bpm;
  24644. }
  24645. else
  24646. {
  24647. if (outCurrentBeat != 0)
  24648. *outCurrentBeat = 0;
  24649. if (outCurrentTempo != 0)
  24650. *outCurrentTempo = 120.0;
  24651. }
  24652. return noErr;
  24653. }
  24654. OSStatus AudioUnitPluginInstance::getMusicalTimeLocation (UInt32* outDeltaSampleOffsetToNextBeat,
  24655. Float32* outTimeSig_Numerator,
  24656. UInt32* outTimeSig_Denominator,
  24657. Float64* outCurrentMeasureDownBeat) const
  24658. {
  24659. AudioPlayHead* const ph = getPlayHead();
  24660. AudioPlayHead::CurrentPositionInfo result;
  24661. if (ph != 0 && ph->getCurrentPosition (result))
  24662. {
  24663. if (outTimeSig_Numerator != 0)
  24664. *outTimeSig_Numerator = result.timeSigNumerator;
  24665. if (outTimeSig_Denominator != 0)
  24666. *outTimeSig_Denominator = result.timeSigDenominator;
  24667. if (outDeltaSampleOffsetToNextBeat != 0)
  24668. *outDeltaSampleOffsetToNextBeat = 0; //xxx
  24669. if (outCurrentMeasureDownBeat != 0)
  24670. *outCurrentMeasureDownBeat = result.ppqPositionOfLastBarStart; //xxx wrong
  24671. }
  24672. else
  24673. {
  24674. if (outDeltaSampleOffsetToNextBeat != 0)
  24675. *outDeltaSampleOffsetToNextBeat = 0;
  24676. if (outTimeSig_Numerator != 0)
  24677. *outTimeSig_Numerator = 4;
  24678. if (outTimeSig_Denominator != 0)
  24679. *outTimeSig_Denominator = 4;
  24680. if (outCurrentMeasureDownBeat != 0)
  24681. *outCurrentMeasureDownBeat = 0;
  24682. }
  24683. return noErr;
  24684. }
  24685. OSStatus AudioUnitPluginInstance::getTransportState (Boolean* outIsPlaying,
  24686. Boolean* outTransportStateChanged,
  24687. Float64* outCurrentSampleInTimeLine,
  24688. Boolean* outIsCycling,
  24689. Float64* outCycleStartBeat,
  24690. Float64* outCycleEndBeat)
  24691. {
  24692. AudioPlayHead* const ph = getPlayHead();
  24693. AudioPlayHead::CurrentPositionInfo result;
  24694. if (ph != 0 && ph->getCurrentPosition (result))
  24695. {
  24696. if (outIsPlaying != 0)
  24697. *outIsPlaying = result.isPlaying;
  24698. if (outTransportStateChanged != 0)
  24699. {
  24700. *outTransportStateChanged = result.isPlaying != wasPlaying;
  24701. wasPlaying = result.isPlaying;
  24702. }
  24703. if (outCurrentSampleInTimeLine != 0)
  24704. *outCurrentSampleInTimeLine = roundToInt (result.timeInSeconds * getSampleRate());
  24705. if (outIsCycling != 0)
  24706. *outIsCycling = false;
  24707. if (outCycleStartBeat != 0)
  24708. *outCycleStartBeat = 0;
  24709. if (outCycleEndBeat != 0)
  24710. *outCycleEndBeat = 0;
  24711. }
  24712. else
  24713. {
  24714. if (outIsPlaying != 0)
  24715. *outIsPlaying = false;
  24716. if (outTransportStateChanged != 0)
  24717. *outTransportStateChanged = false;
  24718. if (outCurrentSampleInTimeLine != 0)
  24719. *outCurrentSampleInTimeLine = 0;
  24720. if (outIsCycling != 0)
  24721. *outIsCycling = false;
  24722. if (outCycleStartBeat != 0)
  24723. *outCycleStartBeat = 0;
  24724. if (outCycleEndBeat != 0)
  24725. *outCycleEndBeat = 0;
  24726. }
  24727. return noErr;
  24728. }
  24729. static VoidArray activeWindows;
  24730. class AudioUnitPluginWindowCocoa : public AudioProcessorEditor
  24731. {
  24732. public:
  24733. AudioUnitPluginWindowCocoa (AudioUnitPluginInstance& plugin_, const bool createGenericViewIfNeeded)
  24734. : AudioProcessorEditor (&plugin_),
  24735. plugin (plugin_),
  24736. wrapper (0)
  24737. {
  24738. addAndMakeVisible (wrapper = new NSViewComponent());
  24739. activeWindows.add (this);
  24740. setOpaque (true);
  24741. setVisible (true);
  24742. setSize (100, 100);
  24743. createView (createGenericViewIfNeeded);
  24744. }
  24745. ~AudioUnitPluginWindowCocoa()
  24746. {
  24747. const bool wasValid = isValid();
  24748. wrapper->setView (0);
  24749. activeWindows.removeValue (this);
  24750. if (wasValid)
  24751. plugin.editorBeingDeleted (this);
  24752. delete wrapper;
  24753. }
  24754. bool isValid() const { return wrapper->getView() != 0; }
  24755. void paint (Graphics& g)
  24756. {
  24757. g.fillAll (Colours::white);
  24758. }
  24759. void resized()
  24760. {
  24761. wrapper->setSize (getWidth(), getHeight());
  24762. }
  24763. private:
  24764. AudioUnitPluginInstance& plugin;
  24765. NSViewComponent* wrapper;
  24766. bool createView (const bool createGenericViewIfNeeded)
  24767. {
  24768. NSView* pluginView = 0;
  24769. UInt32 dataSize = 0;
  24770. Boolean isWritable = false;
  24771. if (AudioUnitGetPropertyInfo (plugin.audioUnit, kAudioUnitProperty_CocoaUI, kAudioUnitScope_Global,
  24772. 0, &dataSize, &isWritable) == noErr
  24773. && dataSize != 0
  24774. && AudioUnitGetPropertyInfo (plugin.audioUnit, kAudioUnitProperty_CocoaUI, kAudioUnitScope_Global,
  24775. 0, &dataSize, &isWritable) == noErr)
  24776. {
  24777. HeapBlock <AudioUnitCocoaViewInfo> info;
  24778. info.calloc (dataSize, 1);
  24779. if (AudioUnitGetProperty (plugin.audioUnit, kAudioUnitProperty_CocoaUI, kAudioUnitScope_Global,
  24780. 0, info, &dataSize) == noErr)
  24781. {
  24782. NSString* viewClassName = (NSString*) (info->mCocoaAUViewClass[0]);
  24783. NSString* path = (NSString*) CFURLCopyPath (info->mCocoaAUViewBundleLocation);
  24784. NSBundle* viewBundle = [NSBundle bundleWithPath: [path autorelease]];
  24785. Class viewClass = [viewBundle classNamed: viewClassName];
  24786. if ([viewClass conformsToProtocol: @protocol (AUCocoaUIBase)]
  24787. && [viewClass instancesRespondToSelector: @selector (interfaceVersion)]
  24788. && [viewClass instancesRespondToSelector: @selector (uiViewForAudioUnit: withSize:)])
  24789. {
  24790. id factory = [[[viewClass alloc] init] autorelease];
  24791. pluginView = [factory uiViewForAudioUnit: plugin.audioUnit
  24792. withSize: NSMakeSize (getWidth(), getHeight())];
  24793. }
  24794. for (int i = (dataSize - sizeof (CFURLRef)) / sizeof (CFStringRef); --i >= 0;)
  24795. {
  24796. CFRelease (info->mCocoaAUViewClass[i]);
  24797. CFRelease (info->mCocoaAUViewBundleLocation);
  24798. }
  24799. }
  24800. }
  24801. if (createGenericViewIfNeeded && (pluginView == 0))
  24802. pluginView = [[AUGenericView alloc] initWithAudioUnit: plugin.audioUnit];
  24803. wrapper->setView (pluginView);
  24804. if (pluginView != 0)
  24805. setSize ([pluginView frame].size.width,
  24806. [pluginView frame].size.height);
  24807. return pluginView != 0;
  24808. }
  24809. };
  24810. #if JUCE_SUPPORT_CARBON
  24811. class AudioUnitPluginWindowCarbon : public AudioProcessorEditor
  24812. {
  24813. public:
  24814. AudioUnitPluginWindowCarbon (AudioUnitPluginInstance& plugin_)
  24815. : AudioProcessorEditor (&plugin_),
  24816. plugin (plugin_),
  24817. viewComponent (0)
  24818. {
  24819. addAndMakeVisible (innerWrapper = new InnerWrapperComponent (this));
  24820. activeWindows.add (this);
  24821. setOpaque (true);
  24822. setVisible (true);
  24823. setSize (400, 300);
  24824. ComponentDescription viewList [16];
  24825. UInt32 viewListSize = sizeof (viewList);
  24826. AudioUnitGetProperty (plugin.audioUnit, kAudioUnitProperty_GetUIComponentList, kAudioUnitScope_Global,
  24827. 0, &viewList, &viewListSize);
  24828. componentRecord = FindNextComponent (0, &viewList[0]);
  24829. }
  24830. ~AudioUnitPluginWindowCarbon()
  24831. {
  24832. innerWrapper = 0;
  24833. activeWindows.removeValue (this);
  24834. if (isValid())
  24835. plugin.editorBeingDeleted (this);
  24836. }
  24837. bool isValid() const throw() { return componentRecord != 0; }
  24838. void paint (Graphics& g)
  24839. {
  24840. g.fillAll (Colours::black);
  24841. }
  24842. void resized()
  24843. {
  24844. innerWrapper->setSize (getWidth(), getHeight());
  24845. }
  24846. bool keyStateChanged (bool)
  24847. {
  24848. return false;
  24849. }
  24850. bool keyPressed (const KeyPress&)
  24851. {
  24852. return false;
  24853. }
  24854. void broughtToFront()
  24855. {
  24856. activeWindows.removeValue (this);
  24857. activeWindows.add (this);
  24858. }
  24859. AudioUnit getAudioUnit() const { return plugin.audioUnit; }
  24860. AudioUnitCarbonView getViewComponent()
  24861. {
  24862. if (viewComponent == 0 && componentRecord != 0)
  24863. viewComponent = (AudioUnitCarbonView) OpenComponent (componentRecord);
  24864. return viewComponent;
  24865. }
  24866. void closeViewComponent()
  24867. {
  24868. if (viewComponent != 0)
  24869. {
  24870. CloseComponent (viewComponent);
  24871. viewComponent = 0;
  24872. }
  24873. }
  24874. juce_UseDebuggingNewOperator
  24875. private:
  24876. AudioUnitPluginInstance& plugin;
  24877. ComponentRecord* componentRecord;
  24878. AudioUnitCarbonView viewComponent;
  24879. class InnerWrapperComponent : public CarbonViewWrapperComponent
  24880. {
  24881. public:
  24882. InnerWrapperComponent (AudioUnitPluginWindowCarbon* const owner_)
  24883. : owner (owner_)
  24884. {
  24885. }
  24886. ~InnerWrapperComponent()
  24887. {
  24888. deleteWindow();
  24889. }
  24890. HIViewRef attachView (WindowRef windowRef, HIViewRef rootView)
  24891. {
  24892. log ("Opening AU GUI: " + owner->plugin.getName());
  24893. AudioUnitCarbonView viewComponent = owner->getViewComponent();
  24894. if (viewComponent == 0)
  24895. return 0;
  24896. Float32Point pos = { 0, 0 };
  24897. Float32Point size = { 250, 200 };
  24898. HIViewRef pluginView = 0;
  24899. AudioUnitCarbonViewCreate (viewComponent,
  24900. owner->getAudioUnit(),
  24901. windowRef,
  24902. rootView,
  24903. &pos,
  24904. &size,
  24905. (ControlRef*) &pluginView);
  24906. return pluginView;
  24907. }
  24908. void removeView (HIViewRef)
  24909. {
  24910. log ("Closing AU GUI: " + owner->plugin.getName());
  24911. owner->closeViewComponent();
  24912. }
  24913. private:
  24914. AudioUnitPluginWindowCarbon* const owner;
  24915. };
  24916. friend class InnerWrapperComponent;
  24917. ScopedPointer<InnerWrapperComponent> innerWrapper;
  24918. };
  24919. #endif
  24920. AudioProcessorEditor* AudioUnitPluginInstance::createEditor()
  24921. {
  24922. ScopedPointer<AudioProcessorEditor> w (new AudioUnitPluginWindowCocoa (*this, false));
  24923. if (! static_cast <AudioUnitPluginWindowCocoa*> (static_cast <AudioProcessorEditor*> (w))->isValid())
  24924. w = 0;
  24925. #if JUCE_SUPPORT_CARBON
  24926. if (w == 0)
  24927. {
  24928. w = new AudioUnitPluginWindowCarbon (*this);
  24929. if (! static_cast <AudioUnitPluginWindowCarbon*> (static_cast <AudioProcessorEditor*> (w))->isValid())
  24930. w = 0;
  24931. }
  24932. #endif
  24933. if (w == 0)
  24934. w = new AudioUnitPluginWindowCocoa (*this, true); // use AUGenericView as a fallback
  24935. return w.release();
  24936. }
  24937. const String AudioUnitPluginInstance::getCategory() const
  24938. {
  24939. const char* result = 0;
  24940. switch (componentDesc.componentType)
  24941. {
  24942. case kAudioUnitType_Effect:
  24943. case kAudioUnitType_MusicEffect:
  24944. result = "Effect";
  24945. break;
  24946. case kAudioUnitType_MusicDevice:
  24947. result = "Synth";
  24948. break;
  24949. case kAudioUnitType_Generator:
  24950. result = "Generator";
  24951. break;
  24952. case kAudioUnitType_Panner:
  24953. result = "Panner";
  24954. break;
  24955. default:
  24956. break;
  24957. }
  24958. return result;
  24959. }
  24960. int AudioUnitPluginInstance::getNumParameters()
  24961. {
  24962. return parameterIds.size();
  24963. }
  24964. float AudioUnitPluginInstance::getParameter (int index)
  24965. {
  24966. const ScopedLock sl (lock);
  24967. Float32 value = 0.0f;
  24968. if (audioUnit != 0 && ((unsigned int) index) < (unsigned int) parameterIds.size())
  24969. {
  24970. AudioUnitGetParameter (audioUnit,
  24971. (UInt32) parameterIds.getUnchecked (index),
  24972. kAudioUnitScope_Global, 0,
  24973. &value);
  24974. }
  24975. return value;
  24976. }
  24977. void AudioUnitPluginInstance::setParameter (int index, float newValue)
  24978. {
  24979. const ScopedLock sl (lock);
  24980. if (audioUnit != 0 && ((unsigned int) index) < (unsigned int) parameterIds.size())
  24981. {
  24982. AudioUnitSetParameter (audioUnit,
  24983. (UInt32) parameterIds.getUnchecked (index),
  24984. kAudioUnitScope_Global, 0,
  24985. newValue, 0);
  24986. }
  24987. }
  24988. const String AudioUnitPluginInstance::getParameterName (int index)
  24989. {
  24990. AudioUnitParameterInfo info;
  24991. zerostruct (info);
  24992. UInt32 sz = sizeof (info);
  24993. String name;
  24994. if (AudioUnitGetProperty (audioUnit,
  24995. kAudioUnitProperty_ParameterInfo,
  24996. kAudioUnitScope_Global,
  24997. parameterIds [index], &info, &sz) == noErr)
  24998. {
  24999. if ((info.flags & kAudioUnitParameterFlag_HasCFNameString) != 0)
  25000. name = PlatformUtilities::cfStringToJuceString (info.cfNameString);
  25001. else
  25002. name = String (info.name, sizeof (info.name));
  25003. }
  25004. return name;
  25005. }
  25006. const String AudioUnitPluginInstance::getParameterText (int index)
  25007. {
  25008. return String (getParameter (index));
  25009. }
  25010. bool AudioUnitPluginInstance::isParameterAutomatable (int index) const
  25011. {
  25012. AudioUnitParameterInfo info;
  25013. UInt32 sz = sizeof (info);
  25014. if (AudioUnitGetProperty (audioUnit,
  25015. kAudioUnitProperty_ParameterInfo,
  25016. kAudioUnitScope_Global,
  25017. parameterIds [index], &info, &sz) == noErr)
  25018. {
  25019. return (info.flags & kAudioUnitParameterFlag_NonRealTime) == 0;
  25020. }
  25021. return true;
  25022. }
  25023. int AudioUnitPluginInstance::getNumPrograms()
  25024. {
  25025. CFArrayRef presets;
  25026. UInt32 sz = sizeof (CFArrayRef);
  25027. int num = 0;
  25028. if (AudioUnitGetProperty (audioUnit,
  25029. kAudioUnitProperty_FactoryPresets,
  25030. kAudioUnitScope_Global,
  25031. 0, &presets, &sz) == noErr)
  25032. {
  25033. num = (int) CFArrayGetCount (presets);
  25034. CFRelease (presets);
  25035. }
  25036. return num;
  25037. }
  25038. int AudioUnitPluginInstance::getCurrentProgram()
  25039. {
  25040. AUPreset current;
  25041. current.presetNumber = 0;
  25042. UInt32 sz = sizeof (AUPreset);
  25043. AudioUnitGetProperty (audioUnit,
  25044. kAudioUnitProperty_FactoryPresets,
  25045. kAudioUnitScope_Global,
  25046. 0, &current, &sz);
  25047. return current.presetNumber;
  25048. }
  25049. void AudioUnitPluginInstance::setCurrentProgram (int newIndex)
  25050. {
  25051. AUPreset current;
  25052. current.presetNumber = newIndex;
  25053. current.presetName = 0;
  25054. AudioUnitSetProperty (audioUnit,
  25055. kAudioUnitProperty_FactoryPresets,
  25056. kAudioUnitScope_Global,
  25057. 0, &current, sizeof (AUPreset));
  25058. }
  25059. const String AudioUnitPluginInstance::getProgramName (int index)
  25060. {
  25061. String s;
  25062. CFArrayRef presets;
  25063. UInt32 sz = sizeof (CFArrayRef);
  25064. if (AudioUnitGetProperty (audioUnit,
  25065. kAudioUnitProperty_FactoryPresets,
  25066. kAudioUnitScope_Global,
  25067. 0, &presets, &sz) == noErr)
  25068. {
  25069. for (CFIndex i = 0; i < CFArrayGetCount (presets); ++i)
  25070. {
  25071. const AUPreset* p = (const AUPreset*) CFArrayGetValueAtIndex (presets, i);
  25072. if (p != 0 && p->presetNumber == index)
  25073. {
  25074. s = PlatformUtilities::cfStringToJuceString (p->presetName);
  25075. break;
  25076. }
  25077. }
  25078. CFRelease (presets);
  25079. }
  25080. return s;
  25081. }
  25082. void AudioUnitPluginInstance::changeProgramName (int index, const String& newName)
  25083. {
  25084. jassertfalse // xxx not implemented!
  25085. }
  25086. const String AudioUnitPluginInstance::getInputChannelName (const int index) const
  25087. {
  25088. if (((unsigned int) index) < (unsigned int) getNumInputChannels())
  25089. return "Input " + String (index + 1);
  25090. return String::empty;
  25091. }
  25092. bool AudioUnitPluginInstance::isInputChannelStereoPair (int index) const
  25093. {
  25094. if (((unsigned int) index) >= (unsigned int) getNumInputChannels())
  25095. return false;
  25096. return true;
  25097. }
  25098. const String AudioUnitPluginInstance::getOutputChannelName (const int index) const
  25099. {
  25100. if (((unsigned int) index) < (unsigned int) getNumOutputChannels())
  25101. return "Output " + String (index + 1);
  25102. return String::empty;
  25103. }
  25104. bool AudioUnitPluginInstance::isOutputChannelStereoPair (int index) const
  25105. {
  25106. if (((unsigned int) index) >= (unsigned int) getNumOutputChannels())
  25107. return false;
  25108. return true;
  25109. }
  25110. void AudioUnitPluginInstance::getStateInformation (MemoryBlock& destData)
  25111. {
  25112. getCurrentProgramStateInformation (destData);
  25113. }
  25114. void AudioUnitPluginInstance::getCurrentProgramStateInformation (MemoryBlock& destData)
  25115. {
  25116. CFPropertyListRef propertyList = 0;
  25117. UInt32 sz = sizeof (CFPropertyListRef);
  25118. if (AudioUnitGetProperty (audioUnit,
  25119. kAudioUnitProperty_ClassInfo,
  25120. kAudioUnitScope_Global,
  25121. 0, &propertyList, &sz) == noErr)
  25122. {
  25123. CFWriteStreamRef stream = CFWriteStreamCreateWithAllocatedBuffers (kCFAllocatorDefault, kCFAllocatorDefault);
  25124. CFWriteStreamOpen (stream);
  25125. CFIndex bytesWritten = CFPropertyListWriteToStream (propertyList, stream, kCFPropertyListBinaryFormat_v1_0, 0);
  25126. CFWriteStreamClose (stream);
  25127. CFDataRef data = (CFDataRef) CFWriteStreamCopyProperty (stream, kCFStreamPropertyDataWritten);
  25128. destData.setSize (bytesWritten);
  25129. destData.copyFrom (CFDataGetBytePtr (data), 0, destData.getSize());
  25130. CFRelease (data);
  25131. CFRelease (stream);
  25132. CFRelease (propertyList);
  25133. }
  25134. }
  25135. void AudioUnitPluginInstance::setStateInformation (const void* data, int sizeInBytes)
  25136. {
  25137. setCurrentProgramStateInformation (data, sizeInBytes);
  25138. }
  25139. void AudioUnitPluginInstance::setCurrentProgramStateInformation (const void* data, int sizeInBytes)
  25140. {
  25141. CFReadStreamRef stream = CFReadStreamCreateWithBytesNoCopy (kCFAllocatorDefault,
  25142. (const UInt8*) data,
  25143. sizeInBytes,
  25144. kCFAllocatorNull);
  25145. CFReadStreamOpen (stream);
  25146. CFPropertyListFormat format = kCFPropertyListBinaryFormat_v1_0;
  25147. CFPropertyListRef propertyList = CFPropertyListCreateFromStream (kCFAllocatorDefault,
  25148. stream,
  25149. 0,
  25150. kCFPropertyListImmutable,
  25151. &format,
  25152. 0);
  25153. CFRelease (stream);
  25154. if (propertyList != 0)
  25155. AudioUnitSetProperty (audioUnit,
  25156. kAudioUnitProperty_ClassInfo,
  25157. kAudioUnitScope_Global,
  25158. 0, &propertyList, sizeof (propertyList));
  25159. }
  25160. AudioUnitPluginFormat::AudioUnitPluginFormat()
  25161. {
  25162. }
  25163. AudioUnitPluginFormat::~AudioUnitPluginFormat()
  25164. {
  25165. }
  25166. void AudioUnitPluginFormat::findAllTypesForFile (OwnedArray <PluginDescription>& results,
  25167. const String& fileOrIdentifier)
  25168. {
  25169. if (! fileMightContainThisPluginType (fileOrIdentifier))
  25170. return;
  25171. PluginDescription desc;
  25172. desc.fileOrIdentifier = fileOrIdentifier;
  25173. desc.uid = 0;
  25174. try
  25175. {
  25176. ScopedPointer <AudioPluginInstance> createdInstance (createInstanceFromDescription (desc));
  25177. AudioUnitPluginInstance* const auInstance = dynamic_cast <AudioUnitPluginInstance*> ((AudioPluginInstance*) createdInstance);
  25178. if (auInstance != 0)
  25179. {
  25180. auInstance->fillInPluginDescription (desc);
  25181. results.add (new PluginDescription (desc));
  25182. }
  25183. }
  25184. catch (...)
  25185. {
  25186. // crashed while loading...
  25187. }
  25188. }
  25189. AudioPluginInstance* AudioUnitPluginFormat::createInstanceFromDescription (const PluginDescription& desc)
  25190. {
  25191. if (fileMightContainThisPluginType (desc.fileOrIdentifier))
  25192. {
  25193. ScopedPointer <AudioUnitPluginInstance> result (new AudioUnitPluginInstance (desc.fileOrIdentifier));
  25194. if (result->audioUnit != 0)
  25195. {
  25196. result->initialise();
  25197. return result.release();
  25198. }
  25199. }
  25200. return 0;
  25201. }
  25202. const StringArray AudioUnitPluginFormat::searchPathsForPlugins (const FileSearchPath& /*directoriesToSearch*/,
  25203. const bool /*recursive*/)
  25204. {
  25205. StringArray result;
  25206. ComponentRecord* comp = 0;
  25207. ComponentDescription desc;
  25208. zerostruct (desc);
  25209. for (;;)
  25210. {
  25211. zerostruct (desc);
  25212. comp = FindNextComponent (comp, &desc);
  25213. if (comp == 0)
  25214. break;
  25215. GetComponentInfo (comp, &desc, 0, 0, 0);
  25216. if (desc.componentType == kAudioUnitType_MusicDevice
  25217. || desc.componentType == kAudioUnitType_MusicEffect
  25218. || desc.componentType == kAudioUnitType_Effect
  25219. || desc.componentType == kAudioUnitType_Generator
  25220. || desc.componentType == kAudioUnitType_Panner)
  25221. {
  25222. const String s (createAUPluginIdentifier (desc));
  25223. DBG (s);
  25224. result.add (s);
  25225. }
  25226. }
  25227. return result;
  25228. }
  25229. bool AudioUnitPluginFormat::fileMightContainThisPluginType (const String& fileOrIdentifier)
  25230. {
  25231. ComponentDescription desc;
  25232. String name, version, manufacturer;
  25233. if (getComponentDescFromIdentifier (fileOrIdentifier, desc, name, version, manufacturer))
  25234. return FindNextComponent (0, &desc) != 0;
  25235. const File f (fileOrIdentifier);
  25236. return f.hasFileExtension (".component")
  25237. && f.isDirectory();
  25238. }
  25239. const String AudioUnitPluginFormat::getNameOfPluginFromIdentifier (const String& fileOrIdentifier)
  25240. {
  25241. ComponentDescription desc;
  25242. String name, version, manufacturer;
  25243. getComponentDescFromIdentifier (fileOrIdentifier, desc, name, version, manufacturer);
  25244. if (name.isEmpty())
  25245. name = fileOrIdentifier;
  25246. return name;
  25247. }
  25248. bool AudioUnitPluginFormat::doesPluginStillExist (const PluginDescription& desc)
  25249. {
  25250. if (desc.fileOrIdentifier.startsWithIgnoreCase (auIdentifierPrefix))
  25251. return fileMightContainThisPluginType (desc.fileOrIdentifier);
  25252. else
  25253. return File (desc.fileOrIdentifier).exists();
  25254. }
  25255. const FileSearchPath AudioUnitPluginFormat::getDefaultLocationsToSearch()
  25256. {
  25257. return FileSearchPath ("/(Default AudioUnit locations)");
  25258. }
  25259. #endif
  25260. END_JUCE_NAMESPACE
  25261. #undef log
  25262. #endif
  25263. /*** End of inlined file: juce_AudioUnitPluginFormat.mm ***/
  25264. /*** Start of inlined file: juce_VSTPluginFormat.mm ***/
  25265. // This file just wraps juce_VSTPluginFormat.cpp in an objective-C wrapper
  25266. #define JUCE_MAC_VST_INCLUDED 1
  25267. /*** Start of inlined file: juce_VSTPluginFormat.cpp ***/
  25268. #if JUCE_PLUGINHOST_VST
  25269. #if JUCE_WINDOWS
  25270. #undef _WIN32_WINNT
  25271. #define _WIN32_WINNT 0x500
  25272. #undef STRICT
  25273. #define STRICT
  25274. #include <windows.h>
  25275. #include <float.h>
  25276. #pragma warning (disable : 4312 4355)
  25277. #elif JUCE_LINUX
  25278. #include <float.h>
  25279. #include <sys/time.h>
  25280. #include <X11/Xlib.h>
  25281. #include <X11/Xutil.h>
  25282. #include <X11/Xatom.h>
  25283. #undef Font
  25284. #undef KeyPress
  25285. #undef Drawable
  25286. #undef Time
  25287. #else
  25288. #ifndef JUCE_MAC_VST_INCLUDED
  25289. // On the mac, this file needs to be compiled indirectly, by using
  25290. // juce_VSTPluginFormat.mm instead - that wraps it as an objective-C file for cocoa
  25291. #error
  25292. #endif
  25293. #include <Cocoa/Cocoa.h>
  25294. #include <Carbon/Carbon.h>
  25295. #endif
  25296. #if ! (JUCE_MAC && JUCE_64BIT)
  25297. BEGIN_JUCE_NAMESPACE
  25298. #if JUCE_MAC && JUCE_SUPPORT_CARBON
  25299. #endif
  25300. #undef PRAGMA_ALIGN_SUPPORTED
  25301. #define VST_FORCE_DEPRECATED 0
  25302. #ifdef _MSC_VER
  25303. #pragma warning (push)
  25304. #pragma warning (disable: 4996)
  25305. #endif
  25306. /* Obviously you're going to need the Steinberg vstsdk2.4 folder in
  25307. your include path if you want to add VST support.
  25308. If you're not interested in VSTs, you can disable them by changing the
  25309. JUCE_PLUGINHOST_VST flag in juce_Config.h
  25310. */
  25311. #include "pluginterfaces/vst2.x/aeffectx.h"
  25312. #ifdef _MSC_VER
  25313. #pragma warning (pop)
  25314. #endif
  25315. #if JUCE_LINUX
  25316. #define Font JUCE_NAMESPACE::Font
  25317. #define KeyPress JUCE_NAMESPACE::KeyPress
  25318. #define Drawable JUCE_NAMESPACE::Drawable
  25319. #define Time JUCE_NAMESPACE::Time
  25320. #endif
  25321. /*** Start of inlined file: juce_VSTMidiEventList.h ***/
  25322. #ifdef __aeffect__
  25323. #ifndef __JUCE_VSTMIDIEVENTLIST_JUCEHEADER__
  25324. #define __JUCE_VSTMIDIEVENTLIST_JUCEHEADER__
  25325. /** Holds a set of VSTMidiEvent objects and makes it easy to add
  25326. events to the list.
  25327. This is used by both the VST hosting code and the plugin wrapper.
  25328. */
  25329. class VSTMidiEventList
  25330. {
  25331. public:
  25332. VSTMidiEventList()
  25333. : numEventsUsed (0), numEventsAllocated (0)
  25334. {
  25335. }
  25336. ~VSTMidiEventList()
  25337. {
  25338. freeEvents();
  25339. }
  25340. void clear()
  25341. {
  25342. numEventsUsed = 0;
  25343. if (events != 0)
  25344. events->numEvents = 0;
  25345. }
  25346. void addEvent (const void* const midiData, const int numBytes, const int frameOffset)
  25347. {
  25348. ensureSize (numEventsUsed + 1);
  25349. VstMidiEvent* const e = (VstMidiEvent*) (events->events [numEventsUsed]);
  25350. events->numEvents = ++numEventsUsed;
  25351. if (numBytes <= 4)
  25352. {
  25353. if (e->type == kVstSysExType)
  25354. {
  25355. juce_free (((VstMidiSysexEvent*) e)->sysexDump);
  25356. e->type = kVstMidiType;
  25357. e->byteSize = sizeof (VstMidiEvent);
  25358. e->noteLength = 0;
  25359. e->noteOffset = 0;
  25360. e->detune = 0;
  25361. e->noteOffVelocity = 0;
  25362. }
  25363. e->deltaFrames = frameOffset;
  25364. memcpy (e->midiData, midiData, numBytes);
  25365. }
  25366. else
  25367. {
  25368. VstMidiSysexEvent* const se = (VstMidiSysexEvent*) e;
  25369. if (se->type == kVstSysExType)
  25370. se->sysexDump = (char*) juce_realloc (se->sysexDump, numBytes);
  25371. else
  25372. se->sysexDump = (char*) juce_malloc (numBytes);
  25373. memcpy (se->sysexDump, midiData, numBytes);
  25374. se->type = kVstSysExType;
  25375. se->byteSize = sizeof (VstMidiSysexEvent);
  25376. se->deltaFrames = frameOffset;
  25377. se->flags = 0;
  25378. se->dumpBytes = numBytes;
  25379. se->resvd1 = 0;
  25380. se->resvd2 = 0;
  25381. }
  25382. }
  25383. // Handy method to pull the events out of an event buffer supplied by the host
  25384. // or plugin.
  25385. static void addEventsToMidiBuffer (const VstEvents* events, MidiBuffer& dest)
  25386. {
  25387. for (int i = 0; i < events->numEvents; ++i)
  25388. {
  25389. const VstEvent* const e = events->events[i];
  25390. if (e != 0)
  25391. {
  25392. if (e->type == kVstMidiType)
  25393. {
  25394. dest.addEvent ((const JUCE_NAMESPACE::uint8*) ((const VstMidiEvent*) e)->midiData,
  25395. 4, e->deltaFrames);
  25396. }
  25397. else if (e->type == kVstSysExType)
  25398. {
  25399. dest.addEvent ((const JUCE_NAMESPACE::uint8*) ((const VstMidiSysexEvent*) e)->sysexDump,
  25400. (int) ((const VstMidiSysexEvent*) e)->dumpBytes,
  25401. e->deltaFrames);
  25402. }
  25403. }
  25404. }
  25405. }
  25406. void ensureSize (int numEventsNeeded)
  25407. {
  25408. if (numEventsNeeded > numEventsAllocated)
  25409. {
  25410. numEventsNeeded = (numEventsNeeded + 32) & ~31;
  25411. const int size = 20 + sizeof (VstEvent*) * numEventsNeeded;
  25412. if (events == 0)
  25413. events.calloc (size, 1);
  25414. else
  25415. events.realloc (size, 1);
  25416. for (int i = numEventsAllocated; i < numEventsNeeded; ++i)
  25417. {
  25418. VstMidiEvent* const e = (VstMidiEvent*) juce_calloc (jmax ((int) sizeof (VstMidiEvent),
  25419. (int) sizeof (VstMidiSysexEvent)));
  25420. e->type = kVstMidiType;
  25421. e->byteSize = sizeof (VstMidiEvent);
  25422. events->events[i] = (VstEvent*) e;
  25423. }
  25424. numEventsAllocated = numEventsNeeded;
  25425. }
  25426. }
  25427. void freeEvents()
  25428. {
  25429. if (events != 0)
  25430. {
  25431. for (int i = numEventsAllocated; --i >= 0;)
  25432. {
  25433. VstMidiEvent* const e = (VstMidiEvent*) (events->events[i]);
  25434. if (e->type == kVstSysExType)
  25435. juce_free (((VstMidiSysexEvent*) e)->sysexDump);
  25436. juce_free (e);
  25437. }
  25438. events.free();
  25439. numEventsUsed = 0;
  25440. numEventsAllocated = 0;
  25441. }
  25442. }
  25443. HeapBlock <VstEvents> events;
  25444. private:
  25445. int numEventsUsed, numEventsAllocated;
  25446. };
  25447. #endif // __JUCE_VSTMIDIEVENTLIST_JUCEHEADER__
  25448. #endif // __JUCE_VSTMIDIEVENTLIST_JUCEHEADER__
  25449. /*** End of inlined file: juce_VSTMidiEventList.h ***/
  25450. #if ! JUCE_WIN32
  25451. static void _fpreset() {}
  25452. static void _clearfp() {}
  25453. #endif
  25454. extern void juce_callAnyTimersSynchronously();
  25455. const int fxbVersionNum = 1;
  25456. struct fxProgram
  25457. {
  25458. long chunkMagic; // 'CcnK'
  25459. long byteSize; // of this chunk, excl. magic + byteSize
  25460. long fxMagic; // 'FxCk'
  25461. long version;
  25462. long fxID; // fx unique id
  25463. long fxVersion;
  25464. long numParams;
  25465. char prgName[28];
  25466. float params[1]; // variable no. of parameters
  25467. };
  25468. struct fxSet
  25469. {
  25470. long chunkMagic; // 'CcnK'
  25471. long byteSize; // of this chunk, excl. magic + byteSize
  25472. long fxMagic; // 'FxBk'
  25473. long version;
  25474. long fxID; // fx unique id
  25475. long fxVersion;
  25476. long numPrograms;
  25477. char future[128];
  25478. fxProgram programs[1]; // variable no. of programs
  25479. };
  25480. struct fxChunkSet
  25481. {
  25482. long chunkMagic; // 'CcnK'
  25483. long byteSize; // of this chunk, excl. magic + byteSize
  25484. long fxMagic; // 'FxCh', 'FPCh', or 'FBCh'
  25485. long version;
  25486. long fxID; // fx unique id
  25487. long fxVersion;
  25488. long numPrograms;
  25489. char future[128];
  25490. long chunkSize;
  25491. char chunk[8]; // variable
  25492. };
  25493. struct fxProgramSet
  25494. {
  25495. long chunkMagic; // 'CcnK'
  25496. long byteSize; // of this chunk, excl. magic + byteSize
  25497. long fxMagic; // 'FxCh', 'FPCh', or 'FBCh'
  25498. long version;
  25499. long fxID; // fx unique id
  25500. long fxVersion;
  25501. long numPrograms;
  25502. char name[28];
  25503. long chunkSize;
  25504. char chunk[8]; // variable
  25505. };
  25506. static long vst_swap (const long x) throw()
  25507. {
  25508. #ifdef JUCE_LITTLE_ENDIAN
  25509. return (long) ByteOrder::swap ((uint32) x);
  25510. #else
  25511. return x;
  25512. #endif
  25513. }
  25514. static float vst_swapFloat (const float x) throw()
  25515. {
  25516. #ifdef JUCE_LITTLE_ENDIAN
  25517. union { uint32 asInt; float asFloat; } n;
  25518. n.asFloat = x;
  25519. n.asInt = ByteOrder::swap (n.asInt);
  25520. return n.asFloat;
  25521. #else
  25522. return x;
  25523. #endif
  25524. }
  25525. typedef AEffect* (*MainCall) (audioMasterCallback);
  25526. static VstIntPtr VSTCALLBACK audioMaster (AEffect* effect, VstInt32 opcode, VstInt32 index, VstIntPtr value, void* ptr, float opt);
  25527. static int shellUIDToCreate = 0;
  25528. static int insideVSTCallback = 0;
  25529. class VSTPluginWindow;
  25530. // Change this to disable logging of various VST activities
  25531. #ifndef VST_LOGGING
  25532. #define VST_LOGGING 1
  25533. #endif
  25534. #if VST_LOGGING
  25535. #define log(a) Logger::writeToLog(a);
  25536. #else
  25537. #define log(a)
  25538. #endif
  25539. #if JUCE_MAC && JUCE_PPC
  25540. static void* NewCFMFromMachO (void* const machofp) throw()
  25541. {
  25542. void* result = juce_malloc (8);
  25543. ((void**) result)[0] = machofp;
  25544. ((void**) result)[1] = result;
  25545. return result;
  25546. }
  25547. #endif
  25548. #if JUCE_LINUX
  25549. extern Display* display;
  25550. extern XContext improbableNumber;
  25551. typedef void (*EventProcPtr) (XEvent* ev);
  25552. static bool xErrorTriggered;
  25553. static int temporaryErrorHandler (Display*, XErrorEvent*)
  25554. {
  25555. xErrorTriggered = true;
  25556. return 0;
  25557. }
  25558. static int getPropertyFromXWindow (Window handle, Atom atom)
  25559. {
  25560. XErrorHandler oldErrorHandler = XSetErrorHandler (temporaryErrorHandler);
  25561. xErrorTriggered = false;
  25562. int userSize;
  25563. unsigned long bytes, userCount;
  25564. unsigned char* data;
  25565. Atom userType;
  25566. XGetWindowProperty (display, handle, atom, 0, 1, false, AnyPropertyType,
  25567. &userType, &userSize, &userCount, &bytes, &data);
  25568. XSetErrorHandler (oldErrorHandler);
  25569. return (userCount == 1 && ! xErrorTriggered) ? *(int*) data
  25570. : 0;
  25571. }
  25572. static Window getChildWindow (Window windowToCheck)
  25573. {
  25574. Window rootWindow, parentWindow;
  25575. Window* childWindows;
  25576. unsigned int numChildren;
  25577. XQueryTree (display,
  25578. windowToCheck,
  25579. &rootWindow,
  25580. &parentWindow,
  25581. &childWindows,
  25582. &numChildren);
  25583. if (numChildren > 0)
  25584. return childWindows [0];
  25585. return 0;
  25586. }
  25587. static void translateJuceToXButtonModifiers (const MouseEvent& e, XEvent& ev) throw()
  25588. {
  25589. if (e.mods.isLeftButtonDown())
  25590. {
  25591. ev.xbutton.button = Button1;
  25592. ev.xbutton.state |= Button1Mask;
  25593. }
  25594. else if (e.mods.isRightButtonDown())
  25595. {
  25596. ev.xbutton.button = Button3;
  25597. ev.xbutton.state |= Button3Mask;
  25598. }
  25599. else if (e.mods.isMiddleButtonDown())
  25600. {
  25601. ev.xbutton.button = Button2;
  25602. ev.xbutton.state |= Button2Mask;
  25603. }
  25604. }
  25605. static void translateJuceToXMotionModifiers (const MouseEvent& e, XEvent& ev) throw()
  25606. {
  25607. if (e.mods.isLeftButtonDown())
  25608. ev.xmotion.state |= Button1Mask;
  25609. else if (e.mods.isRightButtonDown())
  25610. ev.xmotion.state |= Button3Mask;
  25611. else if (e.mods.isMiddleButtonDown())
  25612. ev.xmotion.state |= Button2Mask;
  25613. }
  25614. static void translateJuceToXCrossingModifiers (const MouseEvent& e, XEvent& ev) throw()
  25615. {
  25616. if (e.mods.isLeftButtonDown())
  25617. ev.xcrossing.state |= Button1Mask;
  25618. else if (e.mods.isRightButtonDown())
  25619. ev.xcrossing.state |= Button3Mask;
  25620. else if (e.mods.isMiddleButtonDown())
  25621. ev.xcrossing.state |= Button2Mask;
  25622. }
  25623. static void translateJuceToXMouseWheelModifiers (const MouseEvent& e, const float increment, XEvent& ev) throw()
  25624. {
  25625. if (increment < 0)
  25626. {
  25627. ev.xbutton.button = Button5;
  25628. ev.xbutton.state |= Button5Mask;
  25629. }
  25630. else if (increment > 0)
  25631. {
  25632. ev.xbutton.button = Button4;
  25633. ev.xbutton.state |= Button4Mask;
  25634. }
  25635. }
  25636. #endif
  25637. static VoidArray activeModules;
  25638. class ModuleHandle : public ReferenceCountedObject
  25639. {
  25640. public:
  25641. File file;
  25642. MainCall moduleMain;
  25643. String pluginName;
  25644. static ModuleHandle* findOrCreateModule (const File& file)
  25645. {
  25646. for (int i = activeModules.size(); --i >= 0;)
  25647. {
  25648. ModuleHandle* const module = (ModuleHandle*) activeModules.getUnchecked(i);
  25649. if (module->file == file)
  25650. return module;
  25651. }
  25652. _fpreset(); // (doesn't do any harm)
  25653. ++insideVSTCallback;
  25654. shellUIDToCreate = 0;
  25655. log ("Attempting to load VST: " + file.getFullPathName());
  25656. ScopedPointer <ModuleHandle> m (new ModuleHandle (file));
  25657. if (! m->open())
  25658. m = 0;
  25659. --insideVSTCallback;
  25660. _fpreset(); // (doesn't do any harm)
  25661. return m.release();
  25662. }
  25663. ModuleHandle (const File& file_)
  25664. : file (file_),
  25665. moduleMain (0),
  25666. #if JUCE_WIN32 || JUCE_LINUX
  25667. hModule (0)
  25668. #elif JUCE_MAC
  25669. fragId (0),
  25670. resHandle (0),
  25671. bundleRef (0),
  25672. resFileId (0)
  25673. #endif
  25674. {
  25675. activeModules.add (this);
  25676. #if JUCE_WIN32 || JUCE_LINUX
  25677. fullParentDirectoryPathName = file_.getParentDirectory().getFullPathName();
  25678. #elif JUCE_MAC
  25679. FSRef ref;
  25680. PlatformUtilities::makeFSRefFromPath (&ref, file_.getParentDirectory().getFullPathName());
  25681. FSGetCatalogInfo (&ref, kFSCatInfoNone, 0, 0, &parentDirFSSpec, 0);
  25682. #endif
  25683. }
  25684. ~ModuleHandle()
  25685. {
  25686. activeModules.removeValue (this);
  25687. close();
  25688. }
  25689. juce_UseDebuggingNewOperator
  25690. #if JUCE_WIN32 || JUCE_LINUX
  25691. void* hModule;
  25692. String fullParentDirectoryPathName;
  25693. bool open()
  25694. {
  25695. #if JUCE_WIN32
  25696. static bool timePeriodSet = false;
  25697. if (! timePeriodSet)
  25698. {
  25699. timePeriodSet = true;
  25700. timeBeginPeriod (2);
  25701. }
  25702. #endif
  25703. pluginName = file.getFileNameWithoutExtension();
  25704. hModule = PlatformUtilities::loadDynamicLibrary (file.getFullPathName());
  25705. moduleMain = (MainCall) PlatformUtilities::getProcedureEntryPoint (hModule, "VSTPluginMain");
  25706. if (moduleMain == 0)
  25707. moduleMain = (MainCall) PlatformUtilities::getProcedureEntryPoint (hModule, "main");
  25708. return moduleMain != 0;
  25709. }
  25710. void close()
  25711. {
  25712. _fpreset(); // (doesn't do any harm)
  25713. PlatformUtilities::freeDynamicLibrary (hModule);
  25714. }
  25715. void closeEffect (AEffect* eff)
  25716. {
  25717. eff->dispatcher (eff, effClose, 0, 0, 0, 0);
  25718. }
  25719. #else
  25720. CFragConnectionID fragId;
  25721. Handle resHandle;
  25722. CFBundleRef bundleRef;
  25723. FSSpec parentDirFSSpec;
  25724. short resFileId;
  25725. bool open()
  25726. {
  25727. bool ok = false;
  25728. const String filename (file.getFullPathName());
  25729. if (file.hasFileExtension (".vst"))
  25730. {
  25731. const char* const utf8 = filename.toUTF8();
  25732. CFURLRef url = CFURLCreateFromFileSystemRepresentation (0, (const UInt8*) utf8,
  25733. strlen (utf8), file.isDirectory());
  25734. if (url != 0)
  25735. {
  25736. bundleRef = CFBundleCreate (kCFAllocatorDefault, url);
  25737. CFRelease (url);
  25738. if (bundleRef != 0)
  25739. {
  25740. if (CFBundleLoadExecutable (bundleRef))
  25741. {
  25742. moduleMain = (MainCall) CFBundleGetFunctionPointerForName (bundleRef, CFSTR("main_macho"));
  25743. if (moduleMain == 0)
  25744. moduleMain = (MainCall) CFBundleGetFunctionPointerForName (bundleRef, CFSTR("VSTPluginMain"));
  25745. if (moduleMain != 0)
  25746. {
  25747. CFTypeRef name = CFBundleGetValueForInfoDictionaryKey (bundleRef, CFSTR("CFBundleName"));
  25748. if (name != 0)
  25749. {
  25750. if (CFGetTypeID (name) == CFStringGetTypeID())
  25751. {
  25752. char buffer[1024];
  25753. if (CFStringGetCString ((CFStringRef) name, buffer, sizeof (buffer), CFStringGetSystemEncoding()))
  25754. pluginName = buffer;
  25755. }
  25756. }
  25757. if (pluginName.isEmpty())
  25758. pluginName = file.getFileNameWithoutExtension();
  25759. resFileId = CFBundleOpenBundleResourceMap (bundleRef);
  25760. ok = true;
  25761. }
  25762. }
  25763. if (! ok)
  25764. {
  25765. CFBundleUnloadExecutable (bundleRef);
  25766. CFRelease (bundleRef);
  25767. bundleRef = 0;
  25768. }
  25769. }
  25770. }
  25771. }
  25772. #if JUCE_PPC
  25773. else
  25774. {
  25775. FSRef fn;
  25776. if (FSPathMakeRef ((UInt8*) filename.toUTF8(), &fn, 0) == noErr)
  25777. {
  25778. resFileId = FSOpenResFile (&fn, fsRdPerm);
  25779. if (resFileId != -1)
  25780. {
  25781. const int numEffs = Count1Resources ('aEff');
  25782. for (int i = 0; i < numEffs; ++i)
  25783. {
  25784. resHandle = Get1IndResource ('aEff', i + 1);
  25785. if (resHandle != 0)
  25786. {
  25787. OSType type;
  25788. Str255 name;
  25789. SInt16 id;
  25790. GetResInfo (resHandle, &id, &type, name);
  25791. pluginName = String ((const char*) name + 1, name[0]);
  25792. DetachResource (resHandle);
  25793. HLock (resHandle);
  25794. Ptr ptr;
  25795. Str255 errorText;
  25796. OSErr err = GetMemFragment (*resHandle, GetHandleSize (resHandle),
  25797. name, kPrivateCFragCopy,
  25798. &fragId, &ptr, errorText);
  25799. if (err == noErr)
  25800. {
  25801. moduleMain = (MainCall) newMachOFromCFM (ptr);
  25802. ok = true;
  25803. }
  25804. else
  25805. {
  25806. HUnlock (resHandle);
  25807. }
  25808. break;
  25809. }
  25810. }
  25811. if (! ok)
  25812. CloseResFile (resFileId);
  25813. }
  25814. }
  25815. }
  25816. #endif
  25817. return ok;
  25818. }
  25819. void close()
  25820. {
  25821. #if JUCE_PPC
  25822. if (fragId != 0)
  25823. {
  25824. if (moduleMain != 0)
  25825. disposeMachOFromCFM ((void*) moduleMain);
  25826. CloseConnection (&fragId);
  25827. HUnlock (resHandle);
  25828. if (resFileId != 0)
  25829. CloseResFile (resFileId);
  25830. }
  25831. else
  25832. #endif
  25833. if (bundleRef != 0)
  25834. {
  25835. CFBundleCloseBundleResourceMap (bundleRef, resFileId);
  25836. if (CFGetRetainCount (bundleRef) == 1)
  25837. CFBundleUnloadExecutable (bundleRef);
  25838. if (CFGetRetainCount (bundleRef) > 0)
  25839. CFRelease (bundleRef);
  25840. }
  25841. }
  25842. void closeEffect (AEffect* eff)
  25843. {
  25844. #if JUCE_PPC
  25845. if (fragId != 0)
  25846. {
  25847. VoidArray thingsToDelete;
  25848. thingsToDelete.add ((void*) eff->dispatcher);
  25849. thingsToDelete.add ((void*) eff->process);
  25850. thingsToDelete.add ((void*) eff->setParameter);
  25851. thingsToDelete.add ((void*) eff->getParameter);
  25852. thingsToDelete.add ((void*) eff->processReplacing);
  25853. eff->dispatcher (eff, effClose, 0, 0, 0, 0);
  25854. for (int i = thingsToDelete.size(); --i >= 0;)
  25855. disposeMachOFromCFM (thingsToDelete[i]);
  25856. }
  25857. else
  25858. #endif
  25859. {
  25860. eff->dispatcher (eff, effClose, 0, 0, 0, 0);
  25861. }
  25862. }
  25863. #if JUCE_PPC
  25864. static void* newMachOFromCFM (void* cfmfp)
  25865. {
  25866. if (cfmfp == 0)
  25867. return 0;
  25868. UInt32* const mfp = new UInt32[6];
  25869. mfp[0] = 0x3d800000 | ((UInt32) cfmfp >> 16);
  25870. mfp[1] = 0x618c0000 | ((UInt32) cfmfp & 0xffff);
  25871. mfp[2] = 0x800c0000;
  25872. mfp[3] = 0x804c0004;
  25873. mfp[4] = 0x7c0903a6;
  25874. mfp[5] = 0x4e800420;
  25875. MakeDataExecutable (mfp, sizeof (UInt32) * 6);
  25876. return mfp;
  25877. }
  25878. static void disposeMachOFromCFM (void* ptr)
  25879. {
  25880. delete[] static_cast <UInt32*> (ptr);
  25881. }
  25882. void coerceAEffectFunctionCalls (AEffect* eff)
  25883. {
  25884. if (fragId != 0)
  25885. {
  25886. eff->dispatcher = (AEffectDispatcherProc) newMachOFromCFM ((void*) eff->dispatcher);
  25887. eff->process = (AEffectProcessProc) newMachOFromCFM ((void*) eff->process);
  25888. eff->setParameter = (AEffectSetParameterProc) newMachOFromCFM ((void*) eff->setParameter);
  25889. eff->getParameter = (AEffectGetParameterProc) newMachOFromCFM ((void*) eff->getParameter);
  25890. eff->processReplacing = (AEffectProcessProc) newMachOFromCFM ((void*) eff->processReplacing);
  25891. }
  25892. }
  25893. #endif
  25894. #endif
  25895. };
  25896. /**
  25897. An instance of a plugin, created by a VSTPluginFormat.
  25898. */
  25899. class VSTPluginInstance : public AudioPluginInstance,
  25900. private Timer,
  25901. private AsyncUpdater
  25902. {
  25903. public:
  25904. ~VSTPluginInstance();
  25905. // AudioPluginInstance methods:
  25906. void fillInPluginDescription (PluginDescription& desc) const
  25907. {
  25908. desc.name = name;
  25909. desc.fileOrIdentifier = module->file.getFullPathName();
  25910. desc.uid = getUID();
  25911. desc.lastFileModTime = module->file.getLastModificationTime();
  25912. desc.pluginFormatName = "VST";
  25913. desc.category = getCategory();
  25914. {
  25915. char buffer [kVstMaxVendorStrLen + 8];
  25916. zerostruct (buffer);
  25917. dispatch (effGetVendorString, 0, 0, buffer, 0);
  25918. desc.manufacturerName = buffer;
  25919. }
  25920. desc.version = getVersion();
  25921. desc.numInputChannels = getNumInputChannels();
  25922. desc.numOutputChannels = getNumOutputChannels();
  25923. desc.isInstrument = (effect != 0 && (effect->flags & effFlagsIsSynth) != 0);
  25924. }
  25925. const String getName() const { return name; }
  25926. int getUID() const throw();
  25927. bool acceptsMidi() const { return wantsMidiMessages; }
  25928. bool producesMidi() const { return dispatch (effCanDo, 0, 0, (void*) "sendVstMidiEvent", 0) > 0; }
  25929. // AudioProcessor methods:
  25930. void prepareToPlay (double sampleRate, int estimatedSamplesPerBlock);
  25931. void releaseResources();
  25932. void processBlock (AudioSampleBuffer& buffer,
  25933. MidiBuffer& midiMessages);
  25934. AudioProcessorEditor* createEditor();
  25935. const String getInputChannelName (const int index) const;
  25936. bool isInputChannelStereoPair (int index) const;
  25937. const String getOutputChannelName (const int index) const;
  25938. bool isOutputChannelStereoPair (int index) const;
  25939. int getNumParameters() { return effect != 0 ? effect->numParams : 0; }
  25940. float getParameter (int index);
  25941. void setParameter (int index, float newValue);
  25942. const String getParameterName (int index);
  25943. const String getParameterText (int index);
  25944. bool isParameterAutomatable (int index) const;
  25945. int getNumPrograms() { return effect != 0 ? effect->numPrograms : 0; }
  25946. int getCurrentProgram() { return dispatch (effGetProgram, 0, 0, 0, 0); }
  25947. void setCurrentProgram (int index);
  25948. const String getProgramName (int index);
  25949. void changeProgramName (int index, const String& newName);
  25950. void getStateInformation (MemoryBlock& destData);
  25951. void getCurrentProgramStateInformation (MemoryBlock& destData);
  25952. void setStateInformation (const void* data, int sizeInBytes);
  25953. void setCurrentProgramStateInformation (const void* data, int sizeInBytes);
  25954. void timerCallback();
  25955. void handleAsyncUpdate();
  25956. VstIntPtr handleCallback (VstInt32 opcode, VstInt32 index, VstInt32 value, void *ptr, float opt);
  25957. juce_UseDebuggingNewOperator
  25958. private:
  25959. friend class VSTPluginWindow;
  25960. friend class VSTPluginFormat;
  25961. AEffect* effect;
  25962. String name;
  25963. CriticalSection lock;
  25964. bool wantsMidiMessages, initialised, isPowerOn;
  25965. mutable StringArray programNames;
  25966. AudioSampleBuffer tempBuffer;
  25967. CriticalSection midiInLock;
  25968. MidiBuffer incomingMidi;
  25969. VSTMidiEventList midiEventsToSend;
  25970. VstTimeInfo vstHostTime;
  25971. HeapBlock <float*> channels;
  25972. ReferenceCountedObjectPtr <ModuleHandle> module;
  25973. int dispatch (const int opcode, const int index, const int value, void* const ptr, float opt) const;
  25974. bool restoreProgramSettings (const fxProgram* const prog);
  25975. const String getCurrentProgramName();
  25976. void setParamsInProgramBlock (fxProgram* const prog) throw();
  25977. void updateStoredProgramNames();
  25978. void initialise();
  25979. void handleMidiFromPlugin (const VstEvents* const events);
  25980. void createTempParameterStore (MemoryBlock& dest);
  25981. void restoreFromTempParameterStore (const MemoryBlock& mb);
  25982. const String getParameterLabel (int index) const;
  25983. bool usesChunks() const throw() { return effect != 0 && (effect->flags & effFlagsProgramChunks) != 0; }
  25984. void getChunkData (MemoryBlock& mb, bool isPreset, int maxSizeMB) const;
  25985. void setChunkData (const char* data, int size, bool isPreset);
  25986. bool loadFromFXBFile (const void* data, int numBytes);
  25987. bool saveToFXBFile (MemoryBlock& dest, bool isFXB, int maxSizeMB);
  25988. int getVersionNumber() const throw() { return effect != 0 ? effect->version : 0; }
  25989. const String getVersion() const throw();
  25990. const String getCategory() const throw();
  25991. bool hasEditor() const throw() { return effect != 0 && (effect->flags & effFlagsHasEditor) != 0; }
  25992. void setPower (const bool on);
  25993. VSTPluginInstance (const ReferenceCountedObjectPtr <ModuleHandle>& module);
  25994. };
  25995. VSTPluginInstance::VSTPluginInstance (const ReferenceCountedObjectPtr <ModuleHandle>& module_)
  25996. : effect (0),
  25997. wantsMidiMessages (false),
  25998. initialised (false),
  25999. isPowerOn (false),
  26000. tempBuffer (1, 1),
  26001. module (module_)
  26002. {
  26003. try
  26004. {
  26005. _fpreset();
  26006. ++insideVSTCallback;
  26007. name = module->pluginName;
  26008. log ("Creating VST instance: " + name);
  26009. #if JUCE_MAC
  26010. if (module->resFileId != 0)
  26011. UseResFile (module->resFileId);
  26012. #if JUCE_PPC
  26013. if (module->fragId != 0)
  26014. {
  26015. static void* audioMasterCoerced = 0;
  26016. if (audioMasterCoerced == 0)
  26017. audioMasterCoerced = NewCFMFromMachO ((void*) &audioMaster);
  26018. effect = module->moduleMain ((audioMasterCallback) audioMasterCoerced);
  26019. }
  26020. else
  26021. #endif
  26022. #endif
  26023. {
  26024. effect = module->moduleMain (&audioMaster);
  26025. }
  26026. --insideVSTCallback;
  26027. if (effect != 0 && effect->magic == kEffectMagic)
  26028. {
  26029. #if JUCE_PPC
  26030. module->coerceAEffectFunctionCalls (effect);
  26031. #endif
  26032. jassert (effect->resvd2 == 0);
  26033. jassert (effect->object != 0);
  26034. _fpreset(); // some dodgy plugs fuck around with this
  26035. }
  26036. else
  26037. {
  26038. effect = 0;
  26039. }
  26040. }
  26041. catch (...)
  26042. {
  26043. --insideVSTCallback;
  26044. }
  26045. }
  26046. VSTPluginInstance::~VSTPluginInstance()
  26047. {
  26048. {
  26049. const ScopedLock sl (lock);
  26050. jassert (insideVSTCallback == 0);
  26051. if (effect != 0 && effect->magic == kEffectMagic)
  26052. {
  26053. try
  26054. {
  26055. #if JUCE_MAC
  26056. if (module->resFileId != 0)
  26057. UseResFile (module->resFileId);
  26058. #endif
  26059. // Must delete any editors before deleting the plugin instance!
  26060. jassert (getActiveEditor() == 0);
  26061. _fpreset(); // some dodgy plugs fuck around with this
  26062. module->closeEffect (effect);
  26063. }
  26064. catch (...)
  26065. {}
  26066. }
  26067. module = 0;
  26068. effect = 0;
  26069. }
  26070. }
  26071. void VSTPluginInstance::initialise()
  26072. {
  26073. if (initialised || effect == 0)
  26074. return;
  26075. log ("Initialising VST: " + module->pluginName);
  26076. initialised = true;
  26077. dispatch (effIdentify, 0, 0, 0, 0);
  26078. // this code would ask the plugin for its name, but so few plugins
  26079. // actually bother implementing this correctly, that it's better to
  26080. // just ignore it and use the file name instead.
  26081. /* {
  26082. char buffer [256];
  26083. zerostruct (buffer);
  26084. dispatch (effGetEffectName, 0, 0, buffer, 0);
  26085. name = String (buffer).trim();
  26086. if (name.isEmpty())
  26087. name = module->pluginName;
  26088. }
  26089. */
  26090. if (getSampleRate() > 0)
  26091. dispatch (effSetSampleRate, 0, 0, 0, (float) getSampleRate());
  26092. if (getBlockSize() > 0)
  26093. dispatch (effSetBlockSize, 0, jmax (32, getBlockSize()), 0, 0);
  26094. dispatch (effOpen, 0, 0, 0, 0);
  26095. setPlayConfigDetails (effect->numInputs, effect->numOutputs,
  26096. getSampleRate(), getBlockSize());
  26097. if (getNumPrograms() > 1)
  26098. setCurrentProgram (0);
  26099. else
  26100. dispatch (effSetProgram, 0, 0, 0, 0);
  26101. int i;
  26102. for (i = effect->numInputs; --i >= 0;)
  26103. dispatch (effConnectInput, i, 1, 0, 0);
  26104. for (i = effect->numOutputs; --i >= 0;)
  26105. dispatch (effConnectOutput, i, 1, 0, 0);
  26106. updateStoredProgramNames();
  26107. wantsMidiMessages = dispatch (effCanDo, 0, 0, (void*) "receiveVstMidiEvent", 0) > 0;
  26108. setLatencySamples (effect->initialDelay);
  26109. }
  26110. void VSTPluginInstance::prepareToPlay (double sampleRate_,
  26111. int samplesPerBlockExpected)
  26112. {
  26113. setPlayConfigDetails (effect->numInputs, effect->numOutputs,
  26114. sampleRate_, samplesPerBlockExpected);
  26115. setLatencySamples (effect->initialDelay);
  26116. channels.calloc (jmax (16, getNumOutputChannels(), getNumInputChannels()) + 2);
  26117. vstHostTime.tempo = 120.0;
  26118. vstHostTime.timeSigNumerator = 4;
  26119. vstHostTime.timeSigDenominator = 4;
  26120. vstHostTime.sampleRate = sampleRate_;
  26121. vstHostTime.samplePos = 0;
  26122. vstHostTime.flags = kVstNanosValid; /*| kVstTransportPlaying | kVstTempoValid | kVstTimeSigValid*/;
  26123. initialise();
  26124. if (initialised)
  26125. {
  26126. wantsMidiMessages = wantsMidiMessages
  26127. || (dispatch (effCanDo, 0, 0, (void*) "receiveVstMidiEvent", 0) > 0);
  26128. if (wantsMidiMessages)
  26129. midiEventsToSend.ensureSize (256);
  26130. else
  26131. midiEventsToSend.freeEvents();
  26132. incomingMidi.clear();
  26133. dispatch (effSetSampleRate, 0, 0, 0, (float) sampleRate_);
  26134. dispatch (effSetBlockSize, 0, jmax (16, samplesPerBlockExpected), 0, 0);
  26135. tempBuffer.setSize (jmax (1, effect->numOutputs), samplesPerBlockExpected);
  26136. if (! isPowerOn)
  26137. setPower (true);
  26138. // dodgy hack to force some plugins to initialise the sample rate..
  26139. if ((! hasEditor()) && getNumParameters() > 0)
  26140. {
  26141. const float old = getParameter (0);
  26142. setParameter (0, (old < 0.5f) ? 1.0f : 0.0f);
  26143. setParameter (0, old);
  26144. }
  26145. dispatch (effStartProcess, 0, 0, 0, 0);
  26146. }
  26147. }
  26148. void VSTPluginInstance::releaseResources()
  26149. {
  26150. if (initialised)
  26151. {
  26152. dispatch (effStopProcess, 0, 0, 0, 0);
  26153. setPower (false);
  26154. }
  26155. tempBuffer.setSize (1, 1);
  26156. incomingMidi.clear();
  26157. midiEventsToSend.freeEvents();
  26158. channels.free();
  26159. }
  26160. void VSTPluginInstance::processBlock (AudioSampleBuffer& buffer,
  26161. MidiBuffer& midiMessages)
  26162. {
  26163. const int numSamples = buffer.getNumSamples();
  26164. if (initialised)
  26165. {
  26166. AudioPlayHead* playHead = getPlayHead();
  26167. if (playHead != 0)
  26168. {
  26169. AudioPlayHead::CurrentPositionInfo position;
  26170. playHead->getCurrentPosition (position);
  26171. vstHostTime.tempo = position.bpm;
  26172. vstHostTime.timeSigNumerator = position.timeSigNumerator;
  26173. vstHostTime.timeSigDenominator = position.timeSigDenominator;
  26174. vstHostTime.ppqPos = position.ppqPosition;
  26175. vstHostTime.barStartPos = position.ppqPositionOfLastBarStart;
  26176. vstHostTime.flags |= kVstTempoValid | kVstTimeSigValid | kVstPpqPosValid | kVstBarsValid;
  26177. if (position.isPlaying)
  26178. vstHostTime.flags |= kVstTransportPlaying;
  26179. else
  26180. vstHostTime.flags &= ~kVstTransportPlaying;
  26181. }
  26182. #if JUCE_WIN32
  26183. vstHostTime.nanoSeconds = timeGetTime() * 1000000.0;
  26184. #elif JUCE_LINUX
  26185. timeval micro;
  26186. gettimeofday (&micro, 0);
  26187. vstHostTime.nanoSeconds = micro.tv_usec * 1000.0;
  26188. #elif JUCE_MAC
  26189. UnsignedWide micro;
  26190. Microseconds (&micro);
  26191. vstHostTime.nanoSeconds = micro.lo * 1000.0;
  26192. #endif
  26193. if (wantsMidiMessages)
  26194. {
  26195. midiEventsToSend.clear();
  26196. midiEventsToSend.ensureSize (1);
  26197. MidiBuffer::Iterator iter (midiMessages);
  26198. const uint8* midiData;
  26199. int numBytesOfMidiData, samplePosition;
  26200. while (iter.getNextEvent (midiData, numBytesOfMidiData, samplePosition))
  26201. {
  26202. midiEventsToSend.addEvent (midiData, numBytesOfMidiData,
  26203. jlimit (0, numSamples - 1, samplePosition));
  26204. }
  26205. try
  26206. {
  26207. effect->dispatcher (effect, effProcessEvents, 0, 0, midiEventsToSend.events, 0);
  26208. }
  26209. catch (...)
  26210. {}
  26211. }
  26212. int i;
  26213. const int maxChans = jmax (effect->numInputs, effect->numOutputs);
  26214. for (i = 0; i < maxChans; ++i)
  26215. channels[i] = buffer.getSampleData (i);
  26216. channels [maxChans] = 0;
  26217. _clearfp();
  26218. if ((effect->flags & effFlagsCanReplacing) != 0)
  26219. {
  26220. try
  26221. {
  26222. effect->processReplacing (effect, channels, channels, numSamples);
  26223. }
  26224. catch (...)
  26225. {}
  26226. }
  26227. else
  26228. {
  26229. tempBuffer.setSize (effect->numOutputs, numSamples);
  26230. tempBuffer.clear();
  26231. float* outs [64];
  26232. for (i = effect->numOutputs; --i >= 0;)
  26233. outs[i] = tempBuffer.getSampleData (i);
  26234. outs [effect->numOutputs] = 0;
  26235. try
  26236. {
  26237. effect->process (effect, channels, outs, numSamples);
  26238. }
  26239. catch (...)
  26240. {}
  26241. for (i = effect->numOutputs; --i >= 0;)
  26242. buffer.copyFrom (i, 0, outs[i], numSamples);
  26243. }
  26244. }
  26245. else
  26246. {
  26247. // Not initialised, so just bypass..
  26248. for (int i = getNumInputChannels(); i < getNumOutputChannels(); ++i)
  26249. buffer.clear (i, 0, buffer.getNumSamples());
  26250. }
  26251. {
  26252. // copy any incoming midi..
  26253. const ScopedLock sl (midiInLock);
  26254. midiMessages.swapWith (incomingMidi);
  26255. incomingMidi.clear();
  26256. }
  26257. }
  26258. void VSTPluginInstance::handleMidiFromPlugin (const VstEvents* const events)
  26259. {
  26260. if (events != 0)
  26261. {
  26262. const ScopedLock sl (midiInLock);
  26263. VSTMidiEventList::addEventsToMidiBuffer (events, incomingMidi);
  26264. }
  26265. }
  26266. static Array <VSTPluginWindow*> activeVSTWindows;
  26267. class VSTPluginWindow : public AudioProcessorEditor,
  26268. #if ! JUCE_MAC
  26269. public ComponentMovementWatcher,
  26270. #endif
  26271. public Timer
  26272. {
  26273. public:
  26274. VSTPluginWindow (VSTPluginInstance& plugin_)
  26275. : AudioProcessorEditor (&plugin_),
  26276. #if ! JUCE_MAC
  26277. ComponentMovementWatcher (this),
  26278. #endif
  26279. plugin (plugin_),
  26280. isOpen (false),
  26281. wasShowing (false),
  26282. pluginRefusesToResize (false),
  26283. pluginWantsKeys (false),
  26284. alreadyInside (false),
  26285. recursiveResize (false)
  26286. {
  26287. #if JUCE_WIN32
  26288. sizeCheckCount = 0;
  26289. pluginHWND = 0;
  26290. #elif JUCE_LINUX
  26291. pluginWindow = None;
  26292. pluginProc = None;
  26293. #else
  26294. addAndMakeVisible (innerWrapper = new InnerWrapperComponent (this));
  26295. #endif
  26296. activeVSTWindows.add (this);
  26297. setSize (1, 1);
  26298. setOpaque (true);
  26299. setVisible (true);
  26300. }
  26301. ~VSTPluginWindow()
  26302. {
  26303. #if JUCE_MAC
  26304. innerWrapper = 0;
  26305. #else
  26306. closePluginWindow();
  26307. #endif
  26308. activeVSTWindows.removeValue (this);
  26309. plugin.editorBeingDeleted (this);
  26310. }
  26311. #if ! JUCE_MAC
  26312. void componentMovedOrResized (bool /*wasMoved*/, bool /*wasResized*/)
  26313. {
  26314. if (recursiveResize)
  26315. return;
  26316. Component* const topComp = getTopLevelComponent();
  26317. if (topComp->getPeer() != 0)
  26318. {
  26319. const Point<int> pos (relativePositionToOtherComponent (topComp, Point<int>()));
  26320. recursiveResize = true;
  26321. #if JUCE_WIN32
  26322. if (pluginHWND != 0)
  26323. MoveWindow (pluginHWND, pos.getX(), pos.getY(), getWidth(), getHeight(), TRUE);
  26324. #elif JUCE_LINUX
  26325. if (pluginWindow != 0)
  26326. {
  26327. XResizeWindow (display, pluginWindow, getWidth(), getHeight());
  26328. XMoveWindow (display, pluginWindow, pos.getX(), pos.getY());
  26329. XMapRaised (display, pluginWindow);
  26330. }
  26331. #endif
  26332. recursiveResize = false;
  26333. }
  26334. }
  26335. void componentVisibilityChanged (Component&)
  26336. {
  26337. const bool isShowingNow = isShowing();
  26338. if (wasShowing != isShowingNow)
  26339. {
  26340. wasShowing = isShowingNow;
  26341. if (isShowingNow)
  26342. openPluginWindow();
  26343. else
  26344. closePluginWindow();
  26345. }
  26346. componentMovedOrResized (true, true);
  26347. }
  26348. void componentPeerChanged()
  26349. {
  26350. closePluginWindow();
  26351. openPluginWindow();
  26352. }
  26353. #endif
  26354. bool keyStateChanged (bool)
  26355. {
  26356. return pluginWantsKeys;
  26357. }
  26358. bool keyPressed (const KeyPress&)
  26359. {
  26360. return pluginWantsKeys;
  26361. }
  26362. #if JUCE_MAC
  26363. void paint (Graphics& g)
  26364. {
  26365. g.fillAll (Colours::black);
  26366. }
  26367. #else
  26368. void paint (Graphics& g)
  26369. {
  26370. if (isOpen)
  26371. {
  26372. ComponentPeer* const peer = getPeer();
  26373. if (peer != 0)
  26374. {
  26375. const Point<int> pos (getScreenPosition() - peer->getScreenPosition());
  26376. peer->addMaskedRegion (pos.getX(), pos.getY(), getWidth(), getHeight());
  26377. #if JUCE_LINUX
  26378. if (pluginWindow != 0)
  26379. {
  26380. const Rectangle<int> clip (g.getClipBounds());
  26381. XEvent ev;
  26382. zerostruct (ev);
  26383. ev.xexpose.type = Expose;
  26384. ev.xexpose.display = display;
  26385. ev.xexpose.window = pluginWindow;
  26386. ev.xexpose.x = clip.getX();
  26387. ev.xexpose.y = clip.getY();
  26388. ev.xexpose.width = clip.getWidth();
  26389. ev.xexpose.height = clip.getHeight();
  26390. sendEventToChild (&ev);
  26391. }
  26392. #endif
  26393. }
  26394. }
  26395. else
  26396. {
  26397. g.fillAll (Colours::black);
  26398. }
  26399. }
  26400. #endif
  26401. void timerCallback()
  26402. {
  26403. #if JUCE_WIN32
  26404. if (--sizeCheckCount <= 0)
  26405. {
  26406. sizeCheckCount = 10;
  26407. checkPluginWindowSize();
  26408. }
  26409. #endif
  26410. try
  26411. {
  26412. static bool reentrant = false;
  26413. if (! reentrant)
  26414. {
  26415. reentrant = true;
  26416. plugin.dispatch (effEditIdle, 0, 0, 0, 0);
  26417. reentrant = false;
  26418. }
  26419. }
  26420. catch (...)
  26421. {}
  26422. }
  26423. void mouseDown (const MouseEvent& e)
  26424. {
  26425. #if JUCE_LINUX
  26426. if (pluginWindow == 0)
  26427. return;
  26428. toFront (true);
  26429. XEvent ev;
  26430. zerostruct (ev);
  26431. ev.xbutton.display = display;
  26432. ev.xbutton.type = ButtonPress;
  26433. ev.xbutton.window = pluginWindow;
  26434. ev.xbutton.root = RootWindow (display, DefaultScreen (display));
  26435. ev.xbutton.time = CurrentTime;
  26436. ev.xbutton.x = e.x;
  26437. ev.xbutton.y = e.y;
  26438. ev.xbutton.x_root = e.getScreenX();
  26439. ev.xbutton.y_root = e.getScreenY();
  26440. translateJuceToXButtonModifiers (e, ev);
  26441. sendEventToChild (&ev);
  26442. #elif JUCE_WIN32
  26443. (void) e;
  26444. toFront (true);
  26445. #endif
  26446. }
  26447. void broughtToFront()
  26448. {
  26449. activeVSTWindows.removeValue (this);
  26450. activeVSTWindows.add (this);
  26451. #if JUCE_MAC
  26452. dispatch (effEditTop, 0, 0, 0, 0);
  26453. #endif
  26454. }
  26455. juce_UseDebuggingNewOperator
  26456. private:
  26457. VSTPluginInstance& plugin;
  26458. bool isOpen, wasShowing, recursiveResize;
  26459. bool pluginWantsKeys, pluginRefusesToResize, alreadyInside;
  26460. #if JUCE_WIN32
  26461. HWND pluginHWND;
  26462. void* originalWndProc;
  26463. int sizeCheckCount;
  26464. #elif JUCE_LINUX
  26465. Window pluginWindow;
  26466. EventProcPtr pluginProc;
  26467. #endif
  26468. #if JUCE_MAC
  26469. void openPluginWindow (WindowRef parentWindow)
  26470. {
  26471. if (isOpen || parentWindow == 0)
  26472. return;
  26473. isOpen = true;
  26474. ERect* rect = 0;
  26475. dispatch (effEditGetRect, 0, 0, &rect, 0);
  26476. dispatch (effEditOpen, 0, 0, parentWindow, 0);
  26477. // do this before and after like in the steinberg example
  26478. dispatch (effEditGetRect, 0, 0, &rect, 0);
  26479. dispatch (effGetProgram, 0, 0, 0, 0); // also in steinberg code
  26480. // Install keyboard hooks
  26481. pluginWantsKeys = (dispatch (effKeysRequired, 0, 0, 0, 0) == 0);
  26482. // double-check it's not too tiny
  26483. int w = 250, h = 150;
  26484. if (rect != 0)
  26485. {
  26486. w = rect->right - rect->left;
  26487. h = rect->bottom - rect->top;
  26488. if (w == 0 || h == 0)
  26489. {
  26490. w = 250;
  26491. h = 150;
  26492. }
  26493. }
  26494. w = jmax (w, 32);
  26495. h = jmax (h, 32);
  26496. setSize (w, h);
  26497. startTimer (18 + JUCE_NAMESPACE::Random::getSystemRandom().nextInt (5));
  26498. repaint();
  26499. }
  26500. #else
  26501. void openPluginWindow()
  26502. {
  26503. if (isOpen || getWindowHandle() == 0)
  26504. return;
  26505. log ("Opening VST UI: " + plugin.name);
  26506. isOpen = true;
  26507. ERect* rect = 0;
  26508. dispatch (effEditGetRect, 0, 0, &rect, 0);
  26509. dispatch (effEditOpen, 0, 0, getWindowHandle(), 0);
  26510. // do this before and after like in the steinberg example
  26511. dispatch (effEditGetRect, 0, 0, &rect, 0);
  26512. dispatch (effGetProgram, 0, 0, 0, 0); // also in steinberg code
  26513. // Install keyboard hooks
  26514. pluginWantsKeys = (dispatch (effKeysRequired, 0, 0, 0, 0) == 0);
  26515. #if JUCE_WIN32
  26516. originalWndProc = 0;
  26517. pluginHWND = GetWindow ((HWND) getWindowHandle(), GW_CHILD);
  26518. if (pluginHWND == 0)
  26519. {
  26520. isOpen = false;
  26521. setSize (300, 150);
  26522. return;
  26523. }
  26524. #pragma warning (push)
  26525. #pragma warning (disable: 4244)
  26526. originalWndProc = (void*) GetWindowLongPtr (pluginHWND, GWL_WNDPROC);
  26527. if (! pluginWantsKeys)
  26528. SetWindowLongPtr (pluginHWND, GWLP_WNDPROC, (LONG_PTR) vstHookWndProc);
  26529. #pragma warning (pop)
  26530. int w, h;
  26531. RECT r;
  26532. GetWindowRect (pluginHWND, &r);
  26533. w = r.right - r.left;
  26534. h = r.bottom - r.top;
  26535. if (rect != 0)
  26536. {
  26537. const int rw = rect->right - rect->left;
  26538. const int rh = rect->bottom - rect->top;
  26539. if ((rw > 50 && rh > 50 && rw < 2000 && rh < 2000 && rw != w && rh != h)
  26540. || ((w == 0 && rw > 0) || (h == 0 && rh > 0)))
  26541. {
  26542. // very dodgy logic to decide which size is right.
  26543. if (abs (rw - w) > 350 || abs (rh - h) > 350)
  26544. {
  26545. SetWindowPos (pluginHWND, 0,
  26546. 0, 0, rw, rh,
  26547. SWP_NOMOVE | SWP_NOACTIVATE | SWP_NOOWNERZORDER | SWP_NOZORDER);
  26548. GetWindowRect (pluginHWND, &r);
  26549. w = r.right - r.left;
  26550. h = r.bottom - r.top;
  26551. pluginRefusesToResize = (w != rw) || (h != rh);
  26552. w = rw;
  26553. h = rh;
  26554. }
  26555. }
  26556. }
  26557. #elif JUCE_LINUX
  26558. pluginWindow = getChildWindow ((Window) getWindowHandle());
  26559. if (pluginWindow != 0)
  26560. pluginProc = (EventProcPtr) getPropertyFromXWindow (pluginWindow,
  26561. XInternAtom (display, "_XEventProc", False));
  26562. int w = 250, h = 150;
  26563. if (rect != 0)
  26564. {
  26565. w = rect->right - rect->left;
  26566. h = rect->bottom - rect->top;
  26567. if (w == 0 || h == 0)
  26568. {
  26569. w = 250;
  26570. h = 150;
  26571. }
  26572. }
  26573. if (pluginWindow != 0)
  26574. XMapRaised (display, pluginWindow);
  26575. #endif
  26576. // double-check it's not too tiny
  26577. w = jmax (w, 32);
  26578. h = jmax (h, 32);
  26579. setSize (w, h);
  26580. #if JUCE_WIN32
  26581. checkPluginWindowSize();
  26582. #endif
  26583. startTimer (18 + JUCE_NAMESPACE::Random::getSystemRandom().nextInt (5));
  26584. repaint();
  26585. }
  26586. #endif
  26587. #if ! JUCE_MAC
  26588. void closePluginWindow()
  26589. {
  26590. if (isOpen)
  26591. {
  26592. log ("Closing VST UI: " + plugin.getName());
  26593. isOpen = false;
  26594. dispatch (effEditClose, 0, 0, 0, 0);
  26595. #if JUCE_WIN32
  26596. #pragma warning (push)
  26597. #pragma warning (disable: 4244)
  26598. if (pluginHWND != 0 && IsWindow (pluginHWND))
  26599. SetWindowLongPtr (pluginHWND, GWLP_WNDPROC, (LONG_PTR) originalWndProc);
  26600. #pragma warning (pop)
  26601. stopTimer();
  26602. if (pluginHWND != 0 && IsWindow (pluginHWND))
  26603. DestroyWindow (pluginHWND);
  26604. pluginHWND = 0;
  26605. #elif JUCE_LINUX
  26606. stopTimer();
  26607. pluginWindow = 0;
  26608. pluginProc = 0;
  26609. #endif
  26610. }
  26611. }
  26612. #endif
  26613. int dispatch (const int opcode, const int index, const int value, void* const ptr, float opt)
  26614. {
  26615. return plugin.dispatch (opcode, index, value, ptr, opt);
  26616. }
  26617. #if JUCE_WIN32
  26618. void checkPluginWindowSize() throw()
  26619. {
  26620. RECT r;
  26621. GetWindowRect (pluginHWND, &r);
  26622. const int w = r.right - r.left;
  26623. const int h = r.bottom - r.top;
  26624. if (isShowing() && w > 0 && h > 0
  26625. && (w != getWidth() || h != getHeight())
  26626. && ! pluginRefusesToResize)
  26627. {
  26628. setSize (w, h);
  26629. sizeCheckCount = 0;
  26630. }
  26631. }
  26632. // hooks to get keyboard events from VST windows..
  26633. static LRESULT CALLBACK vstHookWndProc (HWND hW, UINT message, WPARAM wParam, LPARAM lParam)
  26634. {
  26635. for (int i = activeVSTWindows.size(); --i >= 0;)
  26636. {
  26637. const VSTPluginWindow* const w = (const VSTPluginWindow*) activeVSTWindows.getUnchecked (i);
  26638. if (w->pluginHWND == hW)
  26639. {
  26640. if (message == WM_CHAR
  26641. || message == WM_KEYDOWN
  26642. || message == WM_SYSKEYDOWN
  26643. || message == WM_KEYUP
  26644. || message == WM_SYSKEYUP
  26645. || message == WM_APPCOMMAND)
  26646. {
  26647. SendMessage ((HWND) w->getTopLevelComponent()->getWindowHandle(),
  26648. message, wParam, lParam);
  26649. }
  26650. return CallWindowProc ((WNDPROC) (w->originalWndProc),
  26651. (HWND) w->pluginHWND,
  26652. message,
  26653. wParam,
  26654. lParam);
  26655. }
  26656. }
  26657. return DefWindowProc (hW, message, wParam, lParam);
  26658. }
  26659. #endif
  26660. #if JUCE_LINUX
  26661. // overload mouse/keyboard events to forward them to the plugin's inner window..
  26662. void sendEventToChild (XEvent* event)
  26663. {
  26664. if (pluginProc != 0)
  26665. {
  26666. // if the plugin publishes an event procedure, pass the event directly..
  26667. pluginProc (event);
  26668. }
  26669. else if (pluginWindow != 0)
  26670. {
  26671. // if the plugin has a window, then send the event to the window so that
  26672. // its message thread will pick it up..
  26673. XSendEvent (display, pluginWindow, False, 0L, event);
  26674. XFlush (display);
  26675. }
  26676. }
  26677. void mouseEnter (const MouseEvent& e)
  26678. {
  26679. if (pluginWindow != 0)
  26680. {
  26681. XEvent ev;
  26682. zerostruct (ev);
  26683. ev.xcrossing.display = display;
  26684. ev.xcrossing.type = EnterNotify;
  26685. ev.xcrossing.window = pluginWindow;
  26686. ev.xcrossing.root = RootWindow (display, DefaultScreen (display));
  26687. ev.xcrossing.time = CurrentTime;
  26688. ev.xcrossing.x = e.x;
  26689. ev.xcrossing.y = e.y;
  26690. ev.xcrossing.x_root = e.getScreenX();
  26691. ev.xcrossing.y_root = e.getScreenY();
  26692. ev.xcrossing.mode = NotifyNormal; // NotifyGrab, NotifyUngrab
  26693. ev.xcrossing.detail = NotifyAncestor; // NotifyVirtual, NotifyInferior, NotifyNonlinear,NotifyNonlinearVirtual
  26694. translateJuceToXCrossingModifiers (e, ev);
  26695. sendEventToChild (&ev);
  26696. }
  26697. }
  26698. void mouseExit (const MouseEvent& e)
  26699. {
  26700. if (pluginWindow != 0)
  26701. {
  26702. XEvent ev;
  26703. zerostruct (ev);
  26704. ev.xcrossing.display = display;
  26705. ev.xcrossing.type = LeaveNotify;
  26706. ev.xcrossing.window = pluginWindow;
  26707. ev.xcrossing.root = RootWindow (display, DefaultScreen (display));
  26708. ev.xcrossing.time = CurrentTime;
  26709. ev.xcrossing.x = e.x;
  26710. ev.xcrossing.y = e.y;
  26711. ev.xcrossing.x_root = e.getScreenX();
  26712. ev.xcrossing.y_root = e.getScreenY();
  26713. ev.xcrossing.mode = NotifyNormal; // NotifyGrab, NotifyUngrab
  26714. ev.xcrossing.detail = NotifyAncestor; // NotifyVirtual, NotifyInferior, NotifyNonlinear,NotifyNonlinearVirtual
  26715. ev.xcrossing.focus = hasKeyboardFocus (true); // TODO - yes ?
  26716. translateJuceToXCrossingModifiers (e, ev);
  26717. sendEventToChild (&ev);
  26718. }
  26719. }
  26720. void mouseMove (const MouseEvent& e)
  26721. {
  26722. if (pluginWindow != 0)
  26723. {
  26724. XEvent ev;
  26725. zerostruct (ev);
  26726. ev.xmotion.display = display;
  26727. ev.xmotion.type = MotionNotify;
  26728. ev.xmotion.window = pluginWindow;
  26729. ev.xmotion.root = RootWindow (display, DefaultScreen (display));
  26730. ev.xmotion.time = CurrentTime;
  26731. ev.xmotion.is_hint = NotifyNormal;
  26732. ev.xmotion.x = e.x;
  26733. ev.xmotion.y = e.y;
  26734. ev.xmotion.x_root = e.getScreenX();
  26735. ev.xmotion.y_root = e.getScreenY();
  26736. sendEventToChild (&ev);
  26737. }
  26738. }
  26739. void mouseDrag (const MouseEvent& e)
  26740. {
  26741. if (pluginWindow != 0)
  26742. {
  26743. XEvent ev;
  26744. zerostruct (ev);
  26745. ev.xmotion.display = display;
  26746. ev.xmotion.type = MotionNotify;
  26747. ev.xmotion.window = pluginWindow;
  26748. ev.xmotion.root = RootWindow (display, DefaultScreen (display));
  26749. ev.xmotion.time = CurrentTime;
  26750. ev.xmotion.x = e.x ;
  26751. ev.xmotion.y = e.y;
  26752. ev.xmotion.x_root = e.getScreenX();
  26753. ev.xmotion.y_root = e.getScreenY();
  26754. ev.xmotion.is_hint = NotifyNormal;
  26755. translateJuceToXMotionModifiers (e, ev);
  26756. sendEventToChild (&ev);
  26757. }
  26758. }
  26759. void mouseUp (const MouseEvent& e)
  26760. {
  26761. if (pluginWindow != 0)
  26762. {
  26763. XEvent ev;
  26764. zerostruct (ev);
  26765. ev.xbutton.display = display;
  26766. ev.xbutton.type = ButtonRelease;
  26767. ev.xbutton.window = pluginWindow;
  26768. ev.xbutton.root = RootWindow (display, DefaultScreen (display));
  26769. ev.xbutton.time = CurrentTime;
  26770. ev.xbutton.x = e.x;
  26771. ev.xbutton.y = e.y;
  26772. ev.xbutton.x_root = e.getScreenX();
  26773. ev.xbutton.y_root = e.getScreenY();
  26774. translateJuceToXButtonModifiers (e, ev);
  26775. sendEventToChild (&ev);
  26776. }
  26777. }
  26778. void mouseWheelMove (const MouseEvent& e,
  26779. float incrementX,
  26780. float incrementY)
  26781. {
  26782. if (pluginWindow != 0)
  26783. {
  26784. XEvent ev;
  26785. zerostruct (ev);
  26786. ev.xbutton.display = display;
  26787. ev.xbutton.type = ButtonPress;
  26788. ev.xbutton.window = pluginWindow;
  26789. ev.xbutton.root = RootWindow (display, DefaultScreen (display));
  26790. ev.xbutton.time = CurrentTime;
  26791. ev.xbutton.x = e.x;
  26792. ev.xbutton.y = e.y;
  26793. ev.xbutton.x_root = e.getScreenX();
  26794. ev.xbutton.y_root = e.getScreenY();
  26795. translateJuceToXMouseWheelModifiers (e, incrementY, ev);
  26796. sendEventToChild (&ev);
  26797. // TODO - put a usleep here ?
  26798. ev.xbutton.type = ButtonRelease;
  26799. sendEventToChild (&ev);
  26800. }
  26801. }
  26802. #endif
  26803. #if JUCE_MAC
  26804. #if ! JUCE_SUPPORT_CARBON
  26805. #error "To build VSTs, you need to enable the JUCE_SUPPORT_CARBON flag in your config!"
  26806. #endif
  26807. class InnerWrapperComponent : public CarbonViewWrapperComponent
  26808. {
  26809. public:
  26810. InnerWrapperComponent (VSTPluginWindow* const owner_)
  26811. : owner (owner_),
  26812. alreadyInside (false)
  26813. {
  26814. }
  26815. ~InnerWrapperComponent()
  26816. {
  26817. deleteWindow();
  26818. }
  26819. HIViewRef attachView (WindowRef windowRef, HIViewRef rootView)
  26820. {
  26821. owner->openPluginWindow (windowRef);
  26822. return 0;
  26823. }
  26824. void removeView (HIViewRef)
  26825. {
  26826. owner->dispatch (effEditClose, 0, 0, 0, 0);
  26827. owner->dispatch (effEditSleep, 0, 0, 0, 0);
  26828. }
  26829. bool getEmbeddedViewSize (int& w, int& h)
  26830. {
  26831. ERect* rect = 0;
  26832. owner->dispatch (effEditGetRect, 0, 0, &rect, 0);
  26833. w = rect->right - rect->left;
  26834. h = rect->bottom - rect->top;
  26835. return true;
  26836. }
  26837. void mouseDown (int x, int y)
  26838. {
  26839. if (! alreadyInside)
  26840. {
  26841. alreadyInside = true;
  26842. getTopLevelComponent()->toFront (true);
  26843. owner->dispatch (effEditMouse, x, y, 0, 0);
  26844. alreadyInside = false;
  26845. }
  26846. else
  26847. {
  26848. PostEvent (::mouseDown, 0);
  26849. }
  26850. }
  26851. void paint()
  26852. {
  26853. ComponentPeer* const peer = getPeer();
  26854. if (peer != 0)
  26855. {
  26856. const Point<int> pos (getScreenPosition() - peer->getScreenPosition());
  26857. ERect r;
  26858. r.left = pos.getX();
  26859. r.right = r.left + getWidth();
  26860. r.top = pos.getY();
  26861. r.bottom = r.top + getHeight();
  26862. owner->dispatch (effEditDraw, 0, 0, &r, 0);
  26863. }
  26864. }
  26865. private:
  26866. VSTPluginWindow* const owner;
  26867. bool alreadyInside;
  26868. };
  26869. friend class InnerWrapperComponent;
  26870. ScopedPointer <InnerWrapperComponent> innerWrapper;
  26871. void resized()
  26872. {
  26873. innerWrapper->setSize (getWidth(), getHeight());
  26874. }
  26875. #endif
  26876. };
  26877. AudioProcessorEditor* VSTPluginInstance::createEditor()
  26878. {
  26879. if (hasEditor())
  26880. return new VSTPluginWindow (*this);
  26881. return 0;
  26882. }
  26883. void VSTPluginInstance::handleAsyncUpdate()
  26884. {
  26885. // indicates that something about the plugin has changed..
  26886. updateHostDisplay();
  26887. }
  26888. bool VSTPluginInstance::restoreProgramSettings (const fxProgram* const prog)
  26889. {
  26890. if (vst_swap (prog->chunkMagic) == 'CcnK' && vst_swap (prog->fxMagic) == 'FxCk')
  26891. {
  26892. changeProgramName (getCurrentProgram(), prog->prgName);
  26893. for (int i = 0; i < vst_swap (prog->numParams); ++i)
  26894. setParameter (i, vst_swapFloat (prog->params[i]));
  26895. return true;
  26896. }
  26897. return false;
  26898. }
  26899. bool VSTPluginInstance::loadFromFXBFile (const void* const data,
  26900. const int dataSize)
  26901. {
  26902. if (dataSize < 28)
  26903. return false;
  26904. const fxSet* const set = (const fxSet*) data;
  26905. if ((vst_swap (set->chunkMagic) != 'CcnK' && vst_swap (set->chunkMagic) != 'KncC')
  26906. || vst_swap (set->version) > fxbVersionNum)
  26907. return false;
  26908. if (vst_swap (set->fxMagic) == 'FxBk')
  26909. {
  26910. // bank of programs
  26911. if (vst_swap (set->numPrograms) >= 0)
  26912. {
  26913. const int oldProg = getCurrentProgram();
  26914. const int numParams = vst_swap (((const fxProgram*) (set->programs))->numParams);
  26915. const int progLen = sizeof (fxProgram) + (numParams - 1) * sizeof (float);
  26916. for (int i = 0; i < vst_swap (set->numPrograms); ++i)
  26917. {
  26918. if (i != oldProg)
  26919. {
  26920. const fxProgram* const prog = (const fxProgram*) (((const char*) (set->programs)) + i * progLen);
  26921. if (((const char*) prog) - ((const char*) set) >= dataSize)
  26922. return false;
  26923. if (vst_swap (set->numPrograms) > 0)
  26924. setCurrentProgram (i);
  26925. if (! restoreProgramSettings (prog))
  26926. return false;
  26927. }
  26928. }
  26929. if (vst_swap (set->numPrograms) > 0)
  26930. setCurrentProgram (oldProg);
  26931. const fxProgram* const prog = (const fxProgram*) (((const char*) (set->programs)) + oldProg * progLen);
  26932. if (((const char*) prog) - ((const char*) set) >= dataSize)
  26933. return false;
  26934. if (! restoreProgramSettings (prog))
  26935. return false;
  26936. }
  26937. }
  26938. else if (vst_swap (set->fxMagic) == 'FxCk')
  26939. {
  26940. // single program
  26941. const fxProgram* const prog = (const fxProgram*) data;
  26942. if (vst_swap (prog->chunkMagic) != 'CcnK')
  26943. return false;
  26944. changeProgramName (getCurrentProgram(), prog->prgName);
  26945. for (int i = 0; i < vst_swap (prog->numParams); ++i)
  26946. setParameter (i, vst_swapFloat (prog->params[i]));
  26947. }
  26948. else if (vst_swap (set->fxMagic) == 'FBCh' || vst_swap (set->fxMagic) == 'hCBF')
  26949. {
  26950. // non-preset chunk
  26951. const fxChunkSet* const cset = (const fxChunkSet*) data;
  26952. if (vst_swap (cset->chunkSize) + sizeof (fxChunkSet) - 8 > (unsigned int) dataSize)
  26953. return false;
  26954. setChunkData (cset->chunk, vst_swap (cset->chunkSize), false);
  26955. }
  26956. else if (vst_swap (set->fxMagic) == 'FPCh' || vst_swap (set->fxMagic) == 'hCPF')
  26957. {
  26958. // preset chunk
  26959. const fxProgramSet* const cset = (const fxProgramSet*) data;
  26960. if (vst_swap (cset->chunkSize) + sizeof (fxProgramSet) - 8 > (unsigned int) dataSize)
  26961. return false;
  26962. setChunkData (cset->chunk, vst_swap (cset->chunkSize), true);
  26963. changeProgramName (getCurrentProgram(), cset->name);
  26964. }
  26965. else
  26966. {
  26967. return false;
  26968. }
  26969. return true;
  26970. }
  26971. void VSTPluginInstance::setParamsInProgramBlock (fxProgram* const prog) throw()
  26972. {
  26973. const int numParams = getNumParameters();
  26974. prog->chunkMagic = vst_swap ('CcnK');
  26975. prog->byteSize = 0;
  26976. prog->fxMagic = vst_swap ('FxCk');
  26977. prog->version = vst_swap (fxbVersionNum);
  26978. prog->fxID = vst_swap (getUID());
  26979. prog->fxVersion = vst_swap (getVersionNumber());
  26980. prog->numParams = vst_swap (numParams);
  26981. getCurrentProgramName().copyToCString (prog->prgName, sizeof (prog->prgName) - 1);
  26982. for (int i = 0; i < numParams; ++i)
  26983. prog->params[i] = vst_swapFloat (getParameter (i));
  26984. }
  26985. bool VSTPluginInstance::saveToFXBFile (MemoryBlock& dest, bool isFXB, int maxSizeMB)
  26986. {
  26987. const int numPrograms = getNumPrograms();
  26988. const int numParams = getNumParameters();
  26989. if (usesChunks())
  26990. {
  26991. if (isFXB)
  26992. {
  26993. MemoryBlock chunk;
  26994. getChunkData (chunk, false, maxSizeMB);
  26995. const size_t totalLen = sizeof (fxChunkSet) + chunk.getSize() - 8;
  26996. dest.setSize (totalLen, true);
  26997. fxChunkSet* const set = (fxChunkSet*) dest.getData();
  26998. set->chunkMagic = vst_swap ('CcnK');
  26999. set->byteSize = 0;
  27000. set->fxMagic = vst_swap ('FBCh');
  27001. set->version = vst_swap (fxbVersionNum);
  27002. set->fxID = vst_swap (getUID());
  27003. set->fxVersion = vst_swap (getVersionNumber());
  27004. set->numPrograms = vst_swap (numPrograms);
  27005. set->chunkSize = vst_swap ((long) chunk.getSize());
  27006. chunk.copyTo (set->chunk, 0, chunk.getSize());
  27007. }
  27008. else
  27009. {
  27010. MemoryBlock chunk;
  27011. getChunkData (chunk, true, maxSizeMB);
  27012. const size_t totalLen = sizeof (fxProgramSet) + chunk.getSize() - 8;
  27013. dest.setSize (totalLen, true);
  27014. fxProgramSet* const set = (fxProgramSet*) dest.getData();
  27015. set->chunkMagic = vst_swap ('CcnK');
  27016. set->byteSize = 0;
  27017. set->fxMagic = vst_swap ('FPCh');
  27018. set->version = vst_swap (fxbVersionNum);
  27019. set->fxID = vst_swap (getUID());
  27020. set->fxVersion = vst_swap (getVersionNumber());
  27021. set->numPrograms = vst_swap (numPrograms);
  27022. set->chunkSize = vst_swap ((long) chunk.getSize());
  27023. getCurrentProgramName().copyToCString (set->name, sizeof (set->name) - 1);
  27024. chunk.copyTo (set->chunk, 0, chunk.getSize());
  27025. }
  27026. }
  27027. else
  27028. {
  27029. if (isFXB)
  27030. {
  27031. const int progLen = sizeof (fxProgram) + (numParams - 1) * sizeof (float);
  27032. const int len = (sizeof (fxSet) - sizeof (fxProgram)) + progLen * jmax (1, numPrograms);
  27033. dest.setSize (len, true);
  27034. fxSet* const set = (fxSet*) dest.getData();
  27035. set->chunkMagic = vst_swap ('CcnK');
  27036. set->byteSize = 0;
  27037. set->fxMagic = vst_swap ('FxBk');
  27038. set->version = vst_swap (fxbVersionNum);
  27039. set->fxID = vst_swap (getUID());
  27040. set->fxVersion = vst_swap (getVersionNumber());
  27041. set->numPrograms = vst_swap (numPrograms);
  27042. const int oldProgram = getCurrentProgram();
  27043. MemoryBlock oldSettings;
  27044. createTempParameterStore (oldSettings);
  27045. setParamsInProgramBlock ((fxProgram*) (((char*) (set->programs)) + oldProgram * progLen));
  27046. for (int i = 0; i < numPrograms; ++i)
  27047. {
  27048. if (i != oldProgram)
  27049. {
  27050. setCurrentProgram (i);
  27051. setParamsInProgramBlock ((fxProgram*) (((char*) (set->programs)) + i * progLen));
  27052. }
  27053. }
  27054. setCurrentProgram (oldProgram);
  27055. restoreFromTempParameterStore (oldSettings);
  27056. }
  27057. else
  27058. {
  27059. const int totalLen = sizeof (fxProgram) + (numParams - 1) * sizeof (float);
  27060. dest.setSize (totalLen, true);
  27061. setParamsInProgramBlock ((fxProgram*) dest.getData());
  27062. }
  27063. }
  27064. return true;
  27065. }
  27066. void VSTPluginInstance::getChunkData (MemoryBlock& mb, bool isPreset, int maxSizeMB) const
  27067. {
  27068. if (usesChunks())
  27069. {
  27070. void* data = 0;
  27071. const int bytes = dispatch (effGetChunk, isPreset ? 1 : 0, 0, &data, 0.0f);
  27072. if (data != 0 && bytes <= maxSizeMB * 1024 * 1024)
  27073. {
  27074. mb.setSize (bytes);
  27075. mb.copyFrom (data, 0, bytes);
  27076. }
  27077. }
  27078. }
  27079. void VSTPluginInstance::setChunkData (const char* data, int size, bool isPreset)
  27080. {
  27081. if (size > 0 && usesChunks())
  27082. {
  27083. dispatch (effSetChunk, isPreset ? 1 : 0, size, (void*) data, 0.0f);
  27084. if (! isPreset)
  27085. updateStoredProgramNames();
  27086. }
  27087. }
  27088. void VSTPluginInstance::timerCallback()
  27089. {
  27090. if (dispatch (effIdle, 0, 0, 0, 0) == 0)
  27091. stopTimer();
  27092. }
  27093. int VSTPluginInstance::dispatch (const int opcode, const int index, const int value, void* const ptr, float opt) const
  27094. {
  27095. const ScopedLock sl (lock);
  27096. ++insideVSTCallback;
  27097. int result = 0;
  27098. try
  27099. {
  27100. if (effect != 0)
  27101. {
  27102. #if JUCE_MAC
  27103. if (module->resFileId != 0)
  27104. UseResFile (module->resFileId);
  27105. CGrafPtr oldPort;
  27106. if (getActiveEditor() != 0)
  27107. {
  27108. const Point<int> pos (getActiveEditor()->relativePositionToOtherComponent (getActiveEditor()->getTopLevelComponent(), Point<int>()));
  27109. GetPort (&oldPort);
  27110. SetPortWindowPort ((WindowRef) getActiveEditor()->getWindowHandle());
  27111. SetOrigin (-pos.getX(), -pos.getY());
  27112. }
  27113. #endif
  27114. result = effect->dispatcher (effect, opcode, index, value, ptr, opt);
  27115. #if JUCE_MAC
  27116. if (getActiveEditor() != 0)
  27117. SetPort (oldPort);
  27118. module->resFileId = CurResFile();
  27119. #endif
  27120. --insideVSTCallback;
  27121. return result;
  27122. }
  27123. }
  27124. catch (...)
  27125. {
  27126. }
  27127. --insideVSTCallback;
  27128. return result;
  27129. }
  27130. // handles non plugin-specific callbacks..
  27131. static const int defaultVSTSampleRateValue = 16384;
  27132. static const int defaultVSTBlockSizeValue = 512;
  27133. static VstIntPtr handleGeneralCallback (VstInt32 opcode, VstInt32 index, VstInt32 value, void *ptr, float opt)
  27134. {
  27135. (void) index;
  27136. (void) value;
  27137. (void) opt;
  27138. switch (opcode)
  27139. {
  27140. case audioMasterCanDo:
  27141. {
  27142. static const char* canDos[] = { "supplyIdle",
  27143. "sendVstEvents",
  27144. "sendVstMidiEvent",
  27145. "sendVstTimeInfo",
  27146. "receiveVstEvents",
  27147. "receiveVstMidiEvent",
  27148. "supportShell",
  27149. "shellCategory" };
  27150. for (int i = 0; i < numElementsInArray (canDos); ++i)
  27151. if (strcmp (canDos[i], (const char*) ptr) == 0)
  27152. return 1;
  27153. return 0;
  27154. }
  27155. case audioMasterVersion:
  27156. return 0x2400;
  27157. case audioMasterCurrentId:
  27158. return shellUIDToCreate;
  27159. case audioMasterGetNumAutomatableParameters:
  27160. return 0;
  27161. case audioMasterGetAutomationState:
  27162. return 1;
  27163. case audioMasterGetVendorVersion:
  27164. return 0x0101;
  27165. case audioMasterGetVendorString:
  27166. case audioMasterGetProductString:
  27167. {
  27168. String hostName ("Juce VST Host");
  27169. if (JUCEApplication::getInstance() != 0)
  27170. hostName = JUCEApplication::getInstance()->getApplicationName();
  27171. hostName.copyToCString ((char*) ptr, jmin (kVstMaxVendorStrLen, kVstMaxProductStrLen) - 1);
  27172. }
  27173. break;
  27174. case audioMasterGetSampleRate:
  27175. return (VstIntPtr) defaultVSTSampleRateValue;
  27176. case audioMasterGetBlockSize:
  27177. return (VstIntPtr) defaultVSTBlockSizeValue;
  27178. case audioMasterSetOutputSampleRate:
  27179. return 0;
  27180. default:
  27181. DBG ("*** Unhandled VST Callback: " + String ((int) opcode));
  27182. break;
  27183. }
  27184. return 0;
  27185. }
  27186. // handles callbacks for a specific plugin
  27187. VstIntPtr VSTPluginInstance::handleCallback (VstInt32 opcode, VstInt32 index, VstInt32 value, void *ptr, float opt)
  27188. {
  27189. switch (opcode)
  27190. {
  27191. case audioMasterAutomate:
  27192. sendParamChangeMessageToListeners (index, opt);
  27193. break;
  27194. case audioMasterProcessEvents:
  27195. handleMidiFromPlugin ((const VstEvents*) ptr);
  27196. break;
  27197. case audioMasterGetTime:
  27198. #ifdef _MSC_VER
  27199. #pragma warning (push)
  27200. #pragma warning (disable: 4311)
  27201. #endif
  27202. return (VstIntPtr) &vstHostTime;
  27203. #ifdef _MSC_VER
  27204. #pragma warning (pop)
  27205. #endif
  27206. break;
  27207. case audioMasterIdle:
  27208. if (insideVSTCallback == 0 && MessageManager::getInstance()->isThisTheMessageThread())
  27209. {
  27210. ++insideVSTCallback;
  27211. #if JUCE_MAC
  27212. if (getActiveEditor() != 0)
  27213. dispatch (effEditIdle, 0, 0, 0, 0);
  27214. #endif
  27215. juce_callAnyTimersSynchronously();
  27216. handleUpdateNowIfNeeded();
  27217. for (int i = ComponentPeer::getNumPeers(); --i >= 0;)
  27218. ComponentPeer::getPeer (i)->performAnyPendingRepaintsNow();
  27219. --insideVSTCallback;
  27220. }
  27221. break;
  27222. case audioMasterUpdateDisplay:
  27223. triggerAsyncUpdate();
  27224. break;
  27225. case audioMasterTempoAt:
  27226. // returns (10000 * bpm)
  27227. break;
  27228. case audioMasterNeedIdle:
  27229. startTimer (50);
  27230. break;
  27231. case audioMasterSizeWindow:
  27232. if (getActiveEditor() != 0)
  27233. getActiveEditor()->setSize (index, value);
  27234. return 1;
  27235. case audioMasterGetSampleRate:
  27236. return (VstIntPtr) (getSampleRate() > 0 ? getSampleRate() : defaultVSTSampleRateValue);
  27237. case audioMasterGetBlockSize:
  27238. return (VstIntPtr) (getBlockSize() > 0 ? getBlockSize() : defaultVSTBlockSizeValue);
  27239. case audioMasterWantMidi:
  27240. wantsMidiMessages = true;
  27241. break;
  27242. case audioMasterGetDirectory:
  27243. #if JUCE_MAC
  27244. return (VstIntPtr) (void*) &module->parentDirFSSpec;
  27245. #else
  27246. return (VstIntPtr) (pointer_sized_uint) module->fullParentDirectoryPathName.toUTF8();
  27247. #endif
  27248. case audioMasterGetAutomationState:
  27249. // returns 0: not supported, 1: off, 2:read, 3:write, 4:read/write
  27250. break;
  27251. // none of these are handled (yet)..
  27252. case audioMasterBeginEdit:
  27253. case audioMasterEndEdit:
  27254. case audioMasterSetTime:
  27255. case audioMasterPinConnected:
  27256. case audioMasterGetParameterQuantization:
  27257. case audioMasterIOChanged:
  27258. case audioMasterGetInputLatency:
  27259. case audioMasterGetOutputLatency:
  27260. case audioMasterGetPreviousPlug:
  27261. case audioMasterGetNextPlug:
  27262. case audioMasterWillReplaceOrAccumulate:
  27263. case audioMasterGetCurrentProcessLevel:
  27264. case audioMasterOfflineStart:
  27265. case audioMasterOfflineRead:
  27266. case audioMasterOfflineWrite:
  27267. case audioMasterOfflineGetCurrentPass:
  27268. case audioMasterOfflineGetCurrentMetaPass:
  27269. case audioMasterVendorSpecific:
  27270. case audioMasterSetIcon:
  27271. case audioMasterGetLanguage:
  27272. case audioMasterOpenWindow:
  27273. case audioMasterCloseWindow:
  27274. break;
  27275. default:
  27276. return handleGeneralCallback (opcode, index, value, ptr, opt);
  27277. }
  27278. return 0;
  27279. }
  27280. // entry point for all callbacks from the plugin
  27281. static VstIntPtr VSTCALLBACK audioMaster (AEffect* effect, VstInt32 opcode, VstInt32 index, VstIntPtr value, void* ptr, float opt)
  27282. {
  27283. try
  27284. {
  27285. if (effect != 0 && effect->resvd2 != 0)
  27286. {
  27287. return ((VSTPluginInstance*)(effect->resvd2))
  27288. ->handleCallback (opcode, index, value, ptr, opt);
  27289. }
  27290. return handleGeneralCallback (opcode, index, value, ptr, opt);
  27291. }
  27292. catch (...)
  27293. {
  27294. return 0;
  27295. }
  27296. }
  27297. const String VSTPluginInstance::getVersion() const throw()
  27298. {
  27299. unsigned int v = dispatch (effGetVendorVersion, 0, 0, 0, 0);
  27300. String s;
  27301. if (v == 0 || v == -1)
  27302. v = getVersionNumber();
  27303. if (v != 0)
  27304. {
  27305. int versionBits[4];
  27306. int n = 0;
  27307. while (v != 0)
  27308. {
  27309. versionBits [n++] = (v & 0xff);
  27310. v >>= 8;
  27311. }
  27312. s << 'V';
  27313. while (n > 0)
  27314. {
  27315. s << versionBits [--n];
  27316. if (n > 0)
  27317. s << '.';
  27318. }
  27319. }
  27320. return s;
  27321. }
  27322. int VSTPluginInstance::getUID() const throw()
  27323. {
  27324. int uid = effect != 0 ? effect->uniqueID : 0;
  27325. if (uid == 0)
  27326. uid = module->file.hashCode();
  27327. return uid;
  27328. }
  27329. const String VSTPluginInstance::getCategory() const throw()
  27330. {
  27331. const char* result = 0;
  27332. switch (dispatch (effGetPlugCategory, 0, 0, 0, 0))
  27333. {
  27334. case kPlugCategEffect:
  27335. result = "Effect";
  27336. break;
  27337. case kPlugCategSynth:
  27338. result = "Synth";
  27339. break;
  27340. case kPlugCategAnalysis:
  27341. result = "Anaylsis";
  27342. break;
  27343. case kPlugCategMastering:
  27344. result = "Mastering";
  27345. break;
  27346. case kPlugCategSpacializer:
  27347. result = "Spacial";
  27348. break;
  27349. case kPlugCategRoomFx:
  27350. result = "Reverb";
  27351. break;
  27352. case kPlugSurroundFx:
  27353. result = "Surround";
  27354. break;
  27355. case kPlugCategRestoration:
  27356. result = "Restoration";
  27357. break;
  27358. case kPlugCategGenerator:
  27359. result = "Tone generation";
  27360. break;
  27361. default:
  27362. break;
  27363. }
  27364. return result;
  27365. }
  27366. float VSTPluginInstance::getParameter (int index)
  27367. {
  27368. if (effect != 0 && ((unsigned int) index) < (unsigned int) effect->numParams)
  27369. {
  27370. try
  27371. {
  27372. const ScopedLock sl (lock);
  27373. return effect->getParameter (effect, index);
  27374. }
  27375. catch (...)
  27376. {
  27377. }
  27378. }
  27379. return 0.0f;
  27380. }
  27381. void VSTPluginInstance::setParameter (int index, float newValue)
  27382. {
  27383. if (effect != 0 && ((unsigned int) index) < (unsigned int) effect->numParams)
  27384. {
  27385. try
  27386. {
  27387. const ScopedLock sl (lock);
  27388. if (effect->getParameter (effect, index) != newValue)
  27389. effect->setParameter (effect, index, newValue);
  27390. }
  27391. catch (...)
  27392. {
  27393. }
  27394. }
  27395. }
  27396. const String VSTPluginInstance::getParameterName (int index)
  27397. {
  27398. if (effect != 0)
  27399. {
  27400. jassert (index >= 0 && index < effect->numParams);
  27401. char nm [256];
  27402. zerostruct (nm);
  27403. dispatch (effGetParamName, index, 0, nm, 0);
  27404. return String (nm).trim();
  27405. }
  27406. return String::empty;
  27407. }
  27408. const String VSTPluginInstance::getParameterLabel (int index) const
  27409. {
  27410. if (effect != 0)
  27411. {
  27412. jassert (index >= 0 && index < effect->numParams);
  27413. char nm [256];
  27414. zerostruct (nm);
  27415. dispatch (effGetParamLabel, index, 0, nm, 0);
  27416. return String (nm).trim();
  27417. }
  27418. return String::empty;
  27419. }
  27420. const String VSTPluginInstance::getParameterText (int index)
  27421. {
  27422. if (effect != 0)
  27423. {
  27424. jassert (index >= 0 && index < effect->numParams);
  27425. char nm [256];
  27426. zerostruct (nm);
  27427. dispatch (effGetParamDisplay, index, 0, nm, 0);
  27428. return String (nm).trim();
  27429. }
  27430. return String::empty;
  27431. }
  27432. bool VSTPluginInstance::isParameterAutomatable (int index) const
  27433. {
  27434. if (effect != 0)
  27435. {
  27436. jassert (index >= 0 && index < effect->numParams);
  27437. return dispatch (effCanBeAutomated, index, 0, 0, 0) != 0;
  27438. }
  27439. return false;
  27440. }
  27441. void VSTPluginInstance::createTempParameterStore (MemoryBlock& dest)
  27442. {
  27443. dest.setSize (64 + 4 * getNumParameters());
  27444. dest.fillWith (0);
  27445. getCurrentProgramName().copyToCString ((char*) dest.getData(), 63);
  27446. float* const p = (float*) (((char*) dest.getData()) + 64);
  27447. for (int i = 0; i < getNumParameters(); ++i)
  27448. p[i] = getParameter(i);
  27449. }
  27450. void VSTPluginInstance::restoreFromTempParameterStore (const MemoryBlock& m)
  27451. {
  27452. changeProgramName (getCurrentProgram(), (const char*) m.getData());
  27453. float* p = (float*) (((char*) m.getData()) + 64);
  27454. for (int i = 0; i < getNumParameters(); ++i)
  27455. setParameter (i, p[i]);
  27456. }
  27457. void VSTPluginInstance::setCurrentProgram (int newIndex)
  27458. {
  27459. if (getNumPrograms() > 0 && newIndex != getCurrentProgram())
  27460. dispatch (effSetProgram, 0, jlimit (0, getNumPrograms() - 1, newIndex), 0, 0);
  27461. }
  27462. const String VSTPluginInstance::getProgramName (int index)
  27463. {
  27464. if (index == getCurrentProgram())
  27465. {
  27466. return getCurrentProgramName();
  27467. }
  27468. else if (effect != 0)
  27469. {
  27470. char nm [256];
  27471. zerostruct (nm);
  27472. if (dispatch (effGetProgramNameIndexed,
  27473. jlimit (0, getNumPrograms(), index),
  27474. -1, nm, 0) != 0)
  27475. {
  27476. return String (nm).trim();
  27477. }
  27478. }
  27479. return programNames [index];
  27480. }
  27481. void VSTPluginInstance::changeProgramName (int index, const String& newName)
  27482. {
  27483. if (index == getCurrentProgram())
  27484. {
  27485. if (getNumPrograms() > 0 && newName != getCurrentProgramName())
  27486. dispatch (effSetProgramName, 0, 0, (void*) newName.substring (0, 24).toCString(), 0.0f);
  27487. }
  27488. else
  27489. {
  27490. jassertfalse // xxx not implemented!
  27491. }
  27492. }
  27493. void VSTPluginInstance::updateStoredProgramNames()
  27494. {
  27495. if (effect != 0 && getNumPrograms() > 0)
  27496. {
  27497. char nm [256];
  27498. zerostruct (nm);
  27499. // only do this if the plugin can't use indexed names..
  27500. if (dispatch (effGetProgramNameIndexed, 0, -1, nm, 0) == 0)
  27501. {
  27502. const int oldProgram = getCurrentProgram();
  27503. MemoryBlock oldSettings;
  27504. createTempParameterStore (oldSettings);
  27505. for (int i = 0; i < getNumPrograms(); ++i)
  27506. {
  27507. setCurrentProgram (i);
  27508. getCurrentProgramName(); // (this updates the list)
  27509. }
  27510. setCurrentProgram (oldProgram);
  27511. restoreFromTempParameterStore (oldSettings);
  27512. }
  27513. }
  27514. }
  27515. const String VSTPluginInstance::getCurrentProgramName()
  27516. {
  27517. if (effect != 0)
  27518. {
  27519. char nm [256];
  27520. zerostruct (nm);
  27521. dispatch (effGetProgramName, 0, 0, nm, 0);
  27522. const int index = getCurrentProgram();
  27523. if (programNames[index].isEmpty())
  27524. {
  27525. while (programNames.size() < index)
  27526. programNames.add (String::empty);
  27527. programNames.set (index, String (nm).trim());
  27528. }
  27529. return String (nm).trim();
  27530. }
  27531. return String::empty;
  27532. }
  27533. const String VSTPluginInstance::getInputChannelName (const int index) const
  27534. {
  27535. if (index >= 0 && index < getNumInputChannels())
  27536. {
  27537. VstPinProperties pinProps;
  27538. if (dispatch (effGetInputProperties, index, 0, &pinProps, 0.0f) != 0)
  27539. return String (pinProps.label, sizeof (pinProps.label));
  27540. }
  27541. return String::empty;
  27542. }
  27543. bool VSTPluginInstance::isInputChannelStereoPair (int index) const
  27544. {
  27545. if (index < 0 || index >= getNumInputChannels())
  27546. return false;
  27547. VstPinProperties pinProps;
  27548. if (dispatch (effGetInputProperties, index, 0, &pinProps, 0.0f) != 0)
  27549. return (pinProps.flags & kVstPinIsStereo) != 0;
  27550. return true;
  27551. }
  27552. const String VSTPluginInstance::getOutputChannelName (const int index) const
  27553. {
  27554. if (index >= 0 && index < getNumOutputChannels())
  27555. {
  27556. VstPinProperties pinProps;
  27557. if (dispatch (effGetOutputProperties, index, 0, &pinProps, 0.0f) != 0)
  27558. return String (pinProps.label, sizeof (pinProps.label));
  27559. }
  27560. return String::empty;
  27561. }
  27562. bool VSTPluginInstance::isOutputChannelStereoPair (int index) const
  27563. {
  27564. if (index < 0 || index >= getNumOutputChannels())
  27565. return false;
  27566. VstPinProperties pinProps;
  27567. if (dispatch (effGetOutputProperties, index, 0, &pinProps, 0.0f) != 0)
  27568. return (pinProps.flags & kVstPinIsStereo) != 0;
  27569. return true;
  27570. }
  27571. void VSTPluginInstance::setPower (const bool on)
  27572. {
  27573. dispatch (effMainsChanged, 0, on ? 1 : 0, 0, 0);
  27574. isPowerOn = on;
  27575. }
  27576. const int defaultMaxSizeMB = 64;
  27577. void VSTPluginInstance::getStateInformation (MemoryBlock& destData)
  27578. {
  27579. saveToFXBFile (destData, true, defaultMaxSizeMB);
  27580. }
  27581. void VSTPluginInstance::getCurrentProgramStateInformation (MemoryBlock& destData)
  27582. {
  27583. saveToFXBFile (destData, false, defaultMaxSizeMB);
  27584. }
  27585. void VSTPluginInstance::setStateInformation (const void* data, int sizeInBytes)
  27586. {
  27587. loadFromFXBFile (data, sizeInBytes);
  27588. }
  27589. void VSTPluginInstance::setCurrentProgramStateInformation (const void* data, int sizeInBytes)
  27590. {
  27591. loadFromFXBFile (data, sizeInBytes);
  27592. }
  27593. VSTPluginFormat::VSTPluginFormat()
  27594. {
  27595. }
  27596. VSTPluginFormat::~VSTPluginFormat()
  27597. {
  27598. }
  27599. void VSTPluginFormat::findAllTypesForFile (OwnedArray <PluginDescription>& results,
  27600. const String& fileOrIdentifier)
  27601. {
  27602. if (! fileMightContainThisPluginType (fileOrIdentifier))
  27603. return;
  27604. PluginDescription desc;
  27605. desc.fileOrIdentifier = fileOrIdentifier;
  27606. desc.uid = 0;
  27607. ScopedPointer <VSTPluginInstance> instance (dynamic_cast <VSTPluginInstance*> (createInstanceFromDescription (desc)));
  27608. if (instance == 0)
  27609. return;
  27610. try
  27611. {
  27612. #if JUCE_MAC
  27613. if (instance->module->resFileId != 0)
  27614. UseResFile (instance->module->resFileId);
  27615. #endif
  27616. instance->fillInPluginDescription (desc);
  27617. VstPlugCategory category = (VstPlugCategory) instance->dispatch (effGetPlugCategory, 0, 0, 0, 0);
  27618. if (category != kPlugCategShell)
  27619. {
  27620. // Normal plugin...
  27621. results.add (new PluginDescription (desc));
  27622. ++insideVSTCallback;
  27623. instance->dispatch (effOpen, 0, 0, 0, 0);
  27624. --insideVSTCallback;
  27625. }
  27626. else
  27627. {
  27628. // It's a shell plugin, so iterate all the subtypes...
  27629. char shellEffectName [64];
  27630. for (;;)
  27631. {
  27632. zerostruct (shellEffectName);
  27633. const int uid = instance->dispatch (effShellGetNextPlugin, 0, 0, shellEffectName, 0);
  27634. if (uid == 0)
  27635. {
  27636. break;
  27637. }
  27638. else
  27639. {
  27640. desc.uid = uid;
  27641. desc.name = shellEffectName;
  27642. bool alreadyThere = false;
  27643. for (int i = results.size(); --i >= 0;)
  27644. {
  27645. PluginDescription* const d = results.getUnchecked(i);
  27646. if (d->isDuplicateOf (desc))
  27647. {
  27648. alreadyThere = true;
  27649. break;
  27650. }
  27651. }
  27652. if (! alreadyThere)
  27653. results.add (new PluginDescription (desc));
  27654. }
  27655. }
  27656. }
  27657. }
  27658. catch (...)
  27659. {
  27660. // crashed while loading...
  27661. }
  27662. }
  27663. AudioPluginInstance* VSTPluginFormat::createInstanceFromDescription (const PluginDescription& desc)
  27664. {
  27665. ScopedPointer <VSTPluginInstance> result;
  27666. if (fileMightContainThisPluginType (desc.fileOrIdentifier))
  27667. {
  27668. File file (desc.fileOrIdentifier);
  27669. const File previousWorkingDirectory (File::getCurrentWorkingDirectory());
  27670. file.getParentDirectory().setAsCurrentWorkingDirectory();
  27671. const ReferenceCountedObjectPtr <ModuleHandle> module (ModuleHandle::findOrCreateModule (file));
  27672. if (module != 0)
  27673. {
  27674. shellUIDToCreate = desc.uid;
  27675. result = new VSTPluginInstance (module);
  27676. if (result->effect != 0)
  27677. {
  27678. result->effect->resvd2 = (VstIntPtr) (pointer_sized_int) (VSTPluginInstance*) result;
  27679. result->initialise();
  27680. }
  27681. else
  27682. {
  27683. result = 0;
  27684. }
  27685. }
  27686. previousWorkingDirectory.setAsCurrentWorkingDirectory();
  27687. }
  27688. return result.release();
  27689. }
  27690. bool VSTPluginFormat::fileMightContainThisPluginType (const String& fileOrIdentifier)
  27691. {
  27692. const File f (fileOrIdentifier);
  27693. #if JUCE_MAC
  27694. if (f.isDirectory() && f.hasFileExtension (".vst"))
  27695. return true;
  27696. #if JUCE_PPC
  27697. FSRef fileRef;
  27698. if (PlatformUtilities::makeFSRefFromPath (&fileRef, f.getFullPathName()))
  27699. {
  27700. const short resFileId = FSOpenResFile (&fileRef, fsRdPerm);
  27701. if (resFileId != -1)
  27702. {
  27703. const int numEffects = Count1Resources ('aEff');
  27704. CloseResFile (resFileId);
  27705. if (numEffects > 0)
  27706. return true;
  27707. }
  27708. }
  27709. #endif
  27710. return false;
  27711. #elif JUCE_WIN32
  27712. return f.existsAsFile()
  27713. && f.hasFileExtension (".dll");
  27714. #elif JUCE_LINUX
  27715. return f.existsAsFile()
  27716. && f.hasFileExtension (".so");
  27717. #endif
  27718. }
  27719. const String VSTPluginFormat::getNameOfPluginFromIdentifier (const String& fileOrIdentifier)
  27720. {
  27721. return fileOrIdentifier;
  27722. }
  27723. bool VSTPluginFormat::doesPluginStillExist (const PluginDescription& desc)
  27724. {
  27725. return File (desc.fileOrIdentifier).exists();
  27726. }
  27727. const StringArray VSTPluginFormat::searchPathsForPlugins (const FileSearchPath& directoriesToSearch, const bool recursive)
  27728. {
  27729. StringArray results;
  27730. for (int j = 0; j < directoriesToSearch.getNumPaths(); ++j)
  27731. recursiveFileSearch (results, directoriesToSearch [j], recursive);
  27732. return results;
  27733. }
  27734. void VSTPluginFormat::recursiveFileSearch (StringArray& results, const File& dir, const bool recursive)
  27735. {
  27736. // avoid allowing the dir iterator to be recursive, because we want to avoid letting it delve inside
  27737. // .component or .vst directories.
  27738. DirectoryIterator iter (dir, false, "*", File::findFilesAndDirectories);
  27739. while (iter.next())
  27740. {
  27741. const File f (iter.getFile());
  27742. bool isPlugin = false;
  27743. if (fileMightContainThisPluginType (f.getFullPathName()))
  27744. {
  27745. isPlugin = true;
  27746. results.add (f.getFullPathName());
  27747. }
  27748. if (recursive && (! isPlugin) && f.isDirectory())
  27749. recursiveFileSearch (results, f, true);
  27750. }
  27751. }
  27752. const FileSearchPath VSTPluginFormat::getDefaultLocationsToSearch()
  27753. {
  27754. #if JUCE_MAC
  27755. return FileSearchPath ("~/Library/Audio/Plug-Ins/VST;/Library/Audio/Plug-Ins/VST");
  27756. #elif JUCE_WIN32
  27757. const String programFiles (File::getSpecialLocation (File::globalApplicationsDirectory).getFullPathName());
  27758. return FileSearchPath (programFiles + "\\Steinberg\\VstPlugins");
  27759. #elif JUCE_LINUX
  27760. return FileSearchPath ("/usr/lib/vst");
  27761. #endif
  27762. }
  27763. END_JUCE_NAMESPACE
  27764. #endif
  27765. #undef log
  27766. #endif
  27767. /*** End of inlined file: juce_VSTPluginFormat.cpp ***/
  27768. /*** End of inlined file: juce_VSTPluginFormat.mm ***/
  27769. /*** Start of inlined file: juce_AudioProcessor.cpp ***/
  27770. BEGIN_JUCE_NAMESPACE
  27771. AudioProcessor::AudioProcessor()
  27772. : playHead (0),
  27773. activeEditor (0),
  27774. sampleRate (0),
  27775. blockSize (0),
  27776. numInputChannels (0),
  27777. numOutputChannels (0),
  27778. latencySamples (0),
  27779. suspended (false),
  27780. nonRealtime (false)
  27781. {
  27782. }
  27783. AudioProcessor::~AudioProcessor()
  27784. {
  27785. // ooh, nasty - the editor should have been deleted before the filter
  27786. // that it refers to is deleted..
  27787. jassert (activeEditor == 0);
  27788. #if JUCE_DEBUG
  27789. // This will fail if you've called beginParameterChangeGesture() for one
  27790. // or more parameters without having made a corresponding call to endParameterChangeGesture...
  27791. jassert (changingParams.countNumberOfSetBits() == 0);
  27792. #endif
  27793. }
  27794. void AudioProcessor::setPlayHead (AudioPlayHead* const newPlayHead) throw()
  27795. {
  27796. playHead = newPlayHead;
  27797. }
  27798. void AudioProcessor::addListener (AudioProcessorListener* const newListener) throw()
  27799. {
  27800. const ScopedLock sl (listenerLock);
  27801. listeners.addIfNotAlreadyThere (newListener);
  27802. }
  27803. void AudioProcessor::removeListener (AudioProcessorListener* const listenerToRemove) throw()
  27804. {
  27805. const ScopedLock sl (listenerLock);
  27806. listeners.removeValue (listenerToRemove);
  27807. }
  27808. void AudioProcessor::setPlayConfigDetails (const int numIns,
  27809. const int numOuts,
  27810. const double sampleRate_,
  27811. const int blockSize_) throw()
  27812. {
  27813. numInputChannels = numIns;
  27814. numOutputChannels = numOuts;
  27815. sampleRate = sampleRate_;
  27816. blockSize = blockSize_;
  27817. }
  27818. void AudioProcessor::setNonRealtime (const bool nonRealtime_) throw()
  27819. {
  27820. nonRealtime = nonRealtime_;
  27821. }
  27822. void AudioProcessor::setLatencySamples (const int newLatency)
  27823. {
  27824. if (latencySamples != newLatency)
  27825. {
  27826. latencySamples = newLatency;
  27827. updateHostDisplay();
  27828. }
  27829. }
  27830. void AudioProcessor::setParameterNotifyingHost (const int parameterIndex,
  27831. const float newValue)
  27832. {
  27833. setParameter (parameterIndex, newValue);
  27834. sendParamChangeMessageToListeners (parameterIndex, newValue);
  27835. }
  27836. void AudioProcessor::sendParamChangeMessageToListeners (const int parameterIndex, const float newValue)
  27837. {
  27838. jassert (((unsigned int) parameterIndex) < (unsigned int) getNumParameters());
  27839. for (int i = listeners.size(); --i >= 0;)
  27840. {
  27841. AudioProcessorListener* l;
  27842. {
  27843. const ScopedLock sl (listenerLock);
  27844. l = (AudioProcessorListener*) listeners [i];
  27845. }
  27846. if (l != 0)
  27847. l->audioProcessorParameterChanged (this, parameterIndex, newValue);
  27848. }
  27849. }
  27850. void AudioProcessor::beginParameterChangeGesture (int parameterIndex)
  27851. {
  27852. jassert (((unsigned int) parameterIndex) < (unsigned int) getNumParameters());
  27853. #if JUCE_DEBUG
  27854. // This means you've called beginParameterChangeGesture twice in succession without a matching
  27855. // call to endParameterChangeGesture. That might be fine in most hosts, but better to avoid doing it.
  27856. jassert (! changingParams [parameterIndex]);
  27857. changingParams.setBit (parameterIndex);
  27858. #endif
  27859. for (int i = listeners.size(); --i >= 0;)
  27860. {
  27861. AudioProcessorListener* l;
  27862. {
  27863. const ScopedLock sl (listenerLock);
  27864. l = (AudioProcessorListener*) listeners [i];
  27865. }
  27866. if (l != 0)
  27867. l->audioProcessorParameterChangeGestureBegin (this, parameterIndex);
  27868. }
  27869. }
  27870. void AudioProcessor::endParameterChangeGesture (int parameterIndex)
  27871. {
  27872. jassert (((unsigned int) parameterIndex) < (unsigned int) getNumParameters());
  27873. #if JUCE_DEBUG
  27874. // This means you've called endParameterChangeGesture without having previously called
  27875. // endParameterChangeGesture. That might be fine in most hosts, but better to keep the
  27876. // calls matched correctly.
  27877. jassert (changingParams [parameterIndex]);
  27878. changingParams.clearBit (parameterIndex);
  27879. #endif
  27880. for (int i = listeners.size(); --i >= 0;)
  27881. {
  27882. AudioProcessorListener* l;
  27883. {
  27884. const ScopedLock sl (listenerLock);
  27885. l = (AudioProcessorListener*) listeners [i];
  27886. }
  27887. if (l != 0)
  27888. l->audioProcessorParameterChangeGestureEnd (this, parameterIndex);
  27889. }
  27890. }
  27891. void AudioProcessor::updateHostDisplay()
  27892. {
  27893. for (int i = listeners.size(); --i >= 0;)
  27894. {
  27895. AudioProcessorListener* l;
  27896. {
  27897. const ScopedLock sl (listenerLock);
  27898. l = (AudioProcessorListener*) listeners [i];
  27899. }
  27900. if (l != 0)
  27901. l->audioProcessorChanged (this);
  27902. }
  27903. }
  27904. bool AudioProcessor::isParameterAutomatable (int /*parameterIndex*/) const
  27905. {
  27906. return true;
  27907. }
  27908. bool AudioProcessor::isMetaParameter (int /*parameterIndex*/) const
  27909. {
  27910. return false;
  27911. }
  27912. void AudioProcessor::suspendProcessing (const bool shouldBeSuspended)
  27913. {
  27914. const ScopedLock sl (callbackLock);
  27915. suspended = shouldBeSuspended;
  27916. }
  27917. void AudioProcessor::reset()
  27918. {
  27919. }
  27920. void AudioProcessor::editorBeingDeleted (AudioProcessorEditor* const editor) throw()
  27921. {
  27922. const ScopedLock sl (callbackLock);
  27923. jassert (activeEditor == editor);
  27924. if (activeEditor == editor)
  27925. activeEditor = 0;
  27926. }
  27927. AudioProcessorEditor* AudioProcessor::createEditorIfNeeded()
  27928. {
  27929. if (activeEditor != 0)
  27930. return activeEditor;
  27931. AudioProcessorEditor* const ed = createEditor();
  27932. if (ed != 0)
  27933. {
  27934. // you must give your editor comp a size before returning it..
  27935. jassert (ed->getWidth() > 0 && ed->getHeight() > 0);
  27936. const ScopedLock sl (callbackLock);
  27937. activeEditor = ed;
  27938. }
  27939. return ed;
  27940. }
  27941. void AudioProcessor::getCurrentProgramStateInformation (JUCE_NAMESPACE::MemoryBlock& destData)
  27942. {
  27943. getStateInformation (destData);
  27944. }
  27945. void AudioProcessor::setCurrentProgramStateInformation (const void* data, int sizeInBytes)
  27946. {
  27947. setStateInformation (data, sizeInBytes);
  27948. }
  27949. // magic number to identify memory blocks that we've stored as XML
  27950. const uint32 magicXmlNumber = 0x21324356;
  27951. void AudioProcessor::copyXmlToBinary (const XmlElement& xml,
  27952. JUCE_NAMESPACE::MemoryBlock& destData)
  27953. {
  27954. const String xmlString (xml.createDocument (String::empty, true, false));
  27955. const int stringLength = xmlString.getNumBytesAsUTF8();
  27956. destData.setSize (stringLength + 10);
  27957. char* const d = (char*) destData.getData();
  27958. *(uint32*) d = ByteOrder::swapIfBigEndian ((const uint32) magicXmlNumber);
  27959. *(uint32*) (d + 4) = ByteOrder::swapIfBigEndian ((const uint32) stringLength);
  27960. xmlString.copyToUTF8 (d + 8, stringLength + 1);
  27961. }
  27962. XmlElement* AudioProcessor::getXmlFromBinary (const void* data,
  27963. const int sizeInBytes)
  27964. {
  27965. if (sizeInBytes > 8
  27966. && ByteOrder::littleEndianInt (data) == magicXmlNumber)
  27967. {
  27968. const int stringLength = (int) ByteOrder::littleEndianInt (((const char*) data) + 4);
  27969. if (stringLength > 0)
  27970. {
  27971. XmlDocument doc (String::fromUTF8 (((const char*) data) + 8,
  27972. jmin ((sizeInBytes - 8), stringLength)));
  27973. return doc.getDocumentElement();
  27974. }
  27975. }
  27976. return 0;
  27977. }
  27978. void AudioProcessorListener::audioProcessorParameterChangeGestureBegin (AudioProcessor*, int)
  27979. {
  27980. }
  27981. void AudioProcessorListener::audioProcessorParameterChangeGestureEnd (AudioProcessor*, int)
  27982. {
  27983. }
  27984. bool AudioPlayHead::CurrentPositionInfo::operator== (const CurrentPositionInfo& other) const throw()
  27985. {
  27986. return timeInSeconds == other.timeInSeconds
  27987. && ppqPosition == other.ppqPosition
  27988. && editOriginTime == other.editOriginTime
  27989. && ppqPositionOfLastBarStart == other.ppqPositionOfLastBarStart
  27990. && frameRate == other.frameRate
  27991. && isPlaying == other.isPlaying
  27992. && isRecording == other.isRecording
  27993. && bpm == other.bpm
  27994. && timeSigNumerator == other.timeSigNumerator
  27995. && timeSigDenominator == other.timeSigDenominator;
  27996. }
  27997. bool AudioPlayHead::CurrentPositionInfo::operator!= (const CurrentPositionInfo& other) const throw()
  27998. {
  27999. return ! operator== (other);
  28000. }
  28001. void AudioPlayHead::CurrentPositionInfo::resetToDefault()
  28002. {
  28003. zerostruct (*this);
  28004. timeSigNumerator = 4;
  28005. timeSigDenominator = 4;
  28006. bpm = 120;
  28007. }
  28008. END_JUCE_NAMESPACE
  28009. /*** End of inlined file: juce_AudioProcessor.cpp ***/
  28010. /*** Start of inlined file: juce_AudioProcessorEditor.cpp ***/
  28011. BEGIN_JUCE_NAMESPACE
  28012. AudioProcessorEditor::AudioProcessorEditor (AudioProcessor* const owner_)
  28013. : owner (owner_)
  28014. {
  28015. // the filter must be valid..
  28016. jassert (owner != 0);
  28017. }
  28018. AudioProcessorEditor::~AudioProcessorEditor()
  28019. {
  28020. // if this fails, then the wrapper hasn't called editorBeingDeleted() on the
  28021. // filter for some reason..
  28022. jassert (owner->getActiveEditor() != this);
  28023. }
  28024. END_JUCE_NAMESPACE
  28025. /*** End of inlined file: juce_AudioProcessorEditor.cpp ***/
  28026. /*** Start of inlined file: juce_AudioProcessorGraph.cpp ***/
  28027. BEGIN_JUCE_NAMESPACE
  28028. const int AudioProcessorGraph::midiChannelIndex = 0x1000;
  28029. AudioProcessorGraph::Node::Node (const uint32 id_, AudioProcessor* const processor_)
  28030. : id (id_),
  28031. processor (processor_),
  28032. isPrepared (false)
  28033. {
  28034. jassert (processor_ != 0);
  28035. }
  28036. AudioProcessorGraph::Node::~Node()
  28037. {
  28038. delete processor;
  28039. }
  28040. void AudioProcessorGraph::Node::prepare (const double sampleRate, const int blockSize,
  28041. AudioProcessorGraph* const graph)
  28042. {
  28043. if (! isPrepared)
  28044. {
  28045. isPrepared = true;
  28046. AudioProcessorGraph::AudioGraphIOProcessor* const ioProc
  28047. = dynamic_cast <AudioProcessorGraph::AudioGraphIOProcessor*> (processor);
  28048. if (ioProc != 0)
  28049. ioProc->setParentGraph (graph);
  28050. processor->setPlayConfigDetails (processor->getNumInputChannels(),
  28051. processor->getNumOutputChannels(),
  28052. sampleRate, blockSize);
  28053. processor->prepareToPlay (sampleRate, blockSize);
  28054. }
  28055. }
  28056. void AudioProcessorGraph::Node::unprepare()
  28057. {
  28058. if (isPrepared)
  28059. {
  28060. isPrepared = false;
  28061. processor->releaseResources();
  28062. }
  28063. }
  28064. AudioProcessorGraph::AudioProcessorGraph()
  28065. : lastNodeId (0),
  28066. renderingBuffers (1, 1),
  28067. currentAudioOutputBuffer (1, 1)
  28068. {
  28069. }
  28070. AudioProcessorGraph::~AudioProcessorGraph()
  28071. {
  28072. clearRenderingSequence();
  28073. clear();
  28074. }
  28075. const String AudioProcessorGraph::getName() const
  28076. {
  28077. return "Audio Graph";
  28078. }
  28079. void AudioProcessorGraph::clear()
  28080. {
  28081. nodes.clear();
  28082. connections.clear();
  28083. triggerAsyncUpdate();
  28084. }
  28085. AudioProcessorGraph::Node* AudioProcessorGraph::getNodeForId (const uint32 nodeId) const
  28086. {
  28087. for (int i = nodes.size(); --i >= 0;)
  28088. if (nodes.getUnchecked(i)->id == nodeId)
  28089. return nodes.getUnchecked(i);
  28090. return 0;
  28091. }
  28092. AudioProcessorGraph::Node* AudioProcessorGraph::addNode (AudioProcessor* const newProcessor,
  28093. uint32 nodeId)
  28094. {
  28095. if (newProcessor == 0)
  28096. {
  28097. jassertfalse
  28098. return 0;
  28099. }
  28100. if (nodeId == 0)
  28101. {
  28102. nodeId = ++lastNodeId;
  28103. }
  28104. else
  28105. {
  28106. // you can't add a node with an id that already exists in the graph..
  28107. jassert (getNodeForId (nodeId) == 0);
  28108. removeNode (nodeId);
  28109. }
  28110. lastNodeId = nodeId;
  28111. Node* const n = new Node (nodeId, newProcessor);
  28112. nodes.add (n);
  28113. triggerAsyncUpdate();
  28114. AudioProcessorGraph::AudioGraphIOProcessor* const ioProc
  28115. = dynamic_cast <AudioProcessorGraph::AudioGraphIOProcessor*> (n->processor);
  28116. if (ioProc != 0)
  28117. ioProc->setParentGraph (this);
  28118. return n;
  28119. }
  28120. bool AudioProcessorGraph::removeNode (const uint32 nodeId)
  28121. {
  28122. disconnectNode (nodeId);
  28123. for (int i = nodes.size(); --i >= 0;)
  28124. {
  28125. if (nodes.getUnchecked(i)->id == nodeId)
  28126. {
  28127. AudioProcessorGraph::AudioGraphIOProcessor* const ioProc
  28128. = dynamic_cast <AudioProcessorGraph::AudioGraphIOProcessor*> (nodes.getUnchecked(i)->processor);
  28129. if (ioProc != 0)
  28130. ioProc->setParentGraph (0);
  28131. nodes.remove (i);
  28132. triggerAsyncUpdate();
  28133. return true;
  28134. }
  28135. }
  28136. return false;
  28137. }
  28138. const AudioProcessorGraph::Connection* AudioProcessorGraph::getConnectionBetween (const uint32 sourceNodeId,
  28139. const int sourceChannelIndex,
  28140. const uint32 destNodeId,
  28141. const int destChannelIndex) const
  28142. {
  28143. for (int i = connections.size(); --i >= 0;)
  28144. {
  28145. const Connection* const c = connections.getUnchecked(i);
  28146. if (c->sourceNodeId == sourceNodeId
  28147. && c->destNodeId == destNodeId
  28148. && c->sourceChannelIndex == sourceChannelIndex
  28149. && c->destChannelIndex == destChannelIndex)
  28150. {
  28151. return c;
  28152. }
  28153. }
  28154. return 0;
  28155. }
  28156. bool AudioProcessorGraph::isConnected (const uint32 possibleSourceNodeId,
  28157. const uint32 possibleDestNodeId) const
  28158. {
  28159. for (int i = connections.size(); --i >= 0;)
  28160. {
  28161. const Connection* const c = connections.getUnchecked(i);
  28162. if (c->sourceNodeId == possibleSourceNodeId
  28163. && c->destNodeId == possibleDestNodeId)
  28164. {
  28165. return true;
  28166. }
  28167. }
  28168. return false;
  28169. }
  28170. bool AudioProcessorGraph::canConnect (const uint32 sourceNodeId,
  28171. const int sourceChannelIndex,
  28172. const uint32 destNodeId,
  28173. const int destChannelIndex) const
  28174. {
  28175. if (sourceChannelIndex < 0
  28176. || destChannelIndex < 0
  28177. || sourceNodeId == destNodeId
  28178. || (destChannelIndex == midiChannelIndex) != (sourceChannelIndex == midiChannelIndex))
  28179. return false;
  28180. const Node* const source = getNodeForId (sourceNodeId);
  28181. if (source == 0
  28182. || (sourceChannelIndex != midiChannelIndex && sourceChannelIndex >= source->processor->getNumOutputChannels())
  28183. || (sourceChannelIndex == midiChannelIndex && ! source->processor->producesMidi()))
  28184. return false;
  28185. const Node* const dest = getNodeForId (destNodeId);
  28186. if (dest == 0
  28187. || (destChannelIndex != midiChannelIndex && destChannelIndex >= dest->processor->getNumInputChannels())
  28188. || (destChannelIndex == midiChannelIndex && ! dest->processor->acceptsMidi()))
  28189. return false;
  28190. return getConnectionBetween (sourceNodeId, sourceChannelIndex,
  28191. destNodeId, destChannelIndex) == 0;
  28192. }
  28193. bool AudioProcessorGraph::addConnection (const uint32 sourceNodeId,
  28194. const int sourceChannelIndex,
  28195. const uint32 destNodeId,
  28196. const int destChannelIndex)
  28197. {
  28198. if (! canConnect (sourceNodeId, sourceChannelIndex, destNodeId, destChannelIndex))
  28199. return false;
  28200. Connection* const c = new Connection();
  28201. c->sourceNodeId = sourceNodeId;
  28202. c->sourceChannelIndex = sourceChannelIndex;
  28203. c->destNodeId = destNodeId;
  28204. c->destChannelIndex = destChannelIndex;
  28205. connections.add (c);
  28206. triggerAsyncUpdate();
  28207. return true;
  28208. }
  28209. void AudioProcessorGraph::removeConnection (const int index)
  28210. {
  28211. connections.remove (index);
  28212. triggerAsyncUpdate();
  28213. }
  28214. bool AudioProcessorGraph::removeConnection (const uint32 sourceNodeId, const int sourceChannelIndex,
  28215. const uint32 destNodeId, const int destChannelIndex)
  28216. {
  28217. bool doneAnything = false;
  28218. for (int i = connections.size(); --i >= 0;)
  28219. {
  28220. const Connection* const c = connections.getUnchecked(i);
  28221. if (c->sourceNodeId == sourceNodeId
  28222. && c->destNodeId == destNodeId
  28223. && c->sourceChannelIndex == sourceChannelIndex
  28224. && c->destChannelIndex == destChannelIndex)
  28225. {
  28226. removeConnection (i);
  28227. doneAnything = true;
  28228. triggerAsyncUpdate();
  28229. }
  28230. }
  28231. return doneAnything;
  28232. }
  28233. bool AudioProcessorGraph::disconnectNode (const uint32 nodeId)
  28234. {
  28235. bool doneAnything = false;
  28236. for (int i = connections.size(); --i >= 0;)
  28237. {
  28238. const Connection* const c = connections.getUnchecked(i);
  28239. if (c->sourceNodeId == nodeId || c->destNodeId == nodeId)
  28240. {
  28241. removeConnection (i);
  28242. doneAnything = true;
  28243. triggerAsyncUpdate();
  28244. }
  28245. }
  28246. return doneAnything;
  28247. }
  28248. bool AudioProcessorGraph::removeIllegalConnections()
  28249. {
  28250. bool doneAnything = false;
  28251. for (int i = connections.size(); --i >= 0;)
  28252. {
  28253. const Connection* const c = connections.getUnchecked(i);
  28254. const Node* const source = getNodeForId (c->sourceNodeId);
  28255. const Node* const dest = getNodeForId (c->destNodeId);
  28256. if (source == 0 || dest == 0
  28257. || (c->sourceChannelIndex != midiChannelIndex
  28258. && (((unsigned int) c->sourceChannelIndex) >= (unsigned int) source->processor->getNumOutputChannels()))
  28259. || (c->sourceChannelIndex == midiChannelIndex
  28260. && ! source->processor->producesMidi())
  28261. || (c->destChannelIndex != midiChannelIndex
  28262. && (((unsigned int) c->destChannelIndex) >= (unsigned int) dest->processor->getNumInputChannels()))
  28263. || (c->destChannelIndex == midiChannelIndex
  28264. && ! dest->processor->acceptsMidi()))
  28265. {
  28266. removeConnection (i);
  28267. doneAnything = true;
  28268. triggerAsyncUpdate();
  28269. }
  28270. }
  28271. return doneAnything;
  28272. }
  28273. namespace GraphRenderingOps
  28274. {
  28275. class AudioGraphRenderingOp
  28276. {
  28277. public:
  28278. AudioGraphRenderingOp() {}
  28279. virtual ~AudioGraphRenderingOp() {}
  28280. virtual void perform (AudioSampleBuffer& sharedBufferChans,
  28281. const OwnedArray <MidiBuffer>& sharedMidiBuffers,
  28282. const int numSamples) = 0;
  28283. juce_UseDebuggingNewOperator
  28284. };
  28285. class ClearChannelOp : public AudioGraphRenderingOp
  28286. {
  28287. public:
  28288. ClearChannelOp (const int channelNum_)
  28289. : channelNum (channelNum_)
  28290. {}
  28291. ~ClearChannelOp() {}
  28292. void perform (AudioSampleBuffer& sharedBufferChans, const OwnedArray <MidiBuffer>&, const int numSamples)
  28293. {
  28294. sharedBufferChans.clear (channelNum, 0, numSamples);
  28295. }
  28296. private:
  28297. const int channelNum;
  28298. ClearChannelOp (const ClearChannelOp&);
  28299. ClearChannelOp& operator= (const ClearChannelOp&);
  28300. };
  28301. class CopyChannelOp : public AudioGraphRenderingOp
  28302. {
  28303. public:
  28304. CopyChannelOp (const int srcChannelNum_, const int dstChannelNum_)
  28305. : srcChannelNum (srcChannelNum_),
  28306. dstChannelNum (dstChannelNum_)
  28307. {}
  28308. ~CopyChannelOp() {}
  28309. void perform (AudioSampleBuffer& sharedBufferChans, const OwnedArray <MidiBuffer>&, const int numSamples)
  28310. {
  28311. sharedBufferChans.copyFrom (dstChannelNum, 0, sharedBufferChans, srcChannelNum, 0, numSamples);
  28312. }
  28313. private:
  28314. const int srcChannelNum, dstChannelNum;
  28315. CopyChannelOp (const CopyChannelOp&);
  28316. CopyChannelOp& operator= (const CopyChannelOp&);
  28317. };
  28318. class AddChannelOp : public AudioGraphRenderingOp
  28319. {
  28320. public:
  28321. AddChannelOp (const int srcChannelNum_, const int dstChannelNum_)
  28322. : srcChannelNum (srcChannelNum_),
  28323. dstChannelNum (dstChannelNum_)
  28324. {}
  28325. ~AddChannelOp() {}
  28326. void perform (AudioSampleBuffer& sharedBufferChans, const OwnedArray <MidiBuffer>&, const int numSamples)
  28327. {
  28328. sharedBufferChans.addFrom (dstChannelNum, 0, sharedBufferChans, srcChannelNum, 0, numSamples);
  28329. }
  28330. private:
  28331. const int srcChannelNum, dstChannelNum;
  28332. AddChannelOp (const AddChannelOp&);
  28333. AddChannelOp& operator= (const AddChannelOp&);
  28334. };
  28335. class ClearMidiBufferOp : public AudioGraphRenderingOp
  28336. {
  28337. public:
  28338. ClearMidiBufferOp (const int bufferNum_)
  28339. : bufferNum (bufferNum_)
  28340. {}
  28341. ~ClearMidiBufferOp() {}
  28342. void perform (AudioSampleBuffer&, const OwnedArray <MidiBuffer>& sharedMidiBuffers, const int)
  28343. {
  28344. sharedMidiBuffers.getUnchecked (bufferNum)->clear();
  28345. }
  28346. private:
  28347. const int bufferNum;
  28348. ClearMidiBufferOp (const ClearMidiBufferOp&);
  28349. ClearMidiBufferOp& operator= (const ClearMidiBufferOp&);
  28350. };
  28351. class CopyMidiBufferOp : public AudioGraphRenderingOp
  28352. {
  28353. public:
  28354. CopyMidiBufferOp (const int srcBufferNum_, const int dstBufferNum_)
  28355. : srcBufferNum (srcBufferNum_),
  28356. dstBufferNum (dstBufferNum_)
  28357. {}
  28358. ~CopyMidiBufferOp() {}
  28359. void perform (AudioSampleBuffer&, const OwnedArray <MidiBuffer>& sharedMidiBuffers, const int)
  28360. {
  28361. *sharedMidiBuffers.getUnchecked (dstBufferNum) = *sharedMidiBuffers.getUnchecked (srcBufferNum);
  28362. }
  28363. private:
  28364. const int srcBufferNum, dstBufferNum;
  28365. CopyMidiBufferOp (const CopyMidiBufferOp&);
  28366. CopyMidiBufferOp& operator= (const CopyMidiBufferOp&);
  28367. };
  28368. class AddMidiBufferOp : public AudioGraphRenderingOp
  28369. {
  28370. public:
  28371. AddMidiBufferOp (const int srcBufferNum_, const int dstBufferNum_)
  28372. : srcBufferNum (srcBufferNum_),
  28373. dstBufferNum (dstBufferNum_)
  28374. {}
  28375. ~AddMidiBufferOp() {}
  28376. void perform (AudioSampleBuffer&, const OwnedArray <MidiBuffer>& sharedMidiBuffers, const int numSamples)
  28377. {
  28378. sharedMidiBuffers.getUnchecked (dstBufferNum)
  28379. ->addEvents (*sharedMidiBuffers.getUnchecked (srcBufferNum), 0, numSamples, 0);
  28380. }
  28381. private:
  28382. const int srcBufferNum, dstBufferNum;
  28383. AddMidiBufferOp (const AddMidiBufferOp&);
  28384. AddMidiBufferOp& operator= (const AddMidiBufferOp&);
  28385. };
  28386. class ProcessBufferOp : public AudioGraphRenderingOp
  28387. {
  28388. public:
  28389. ProcessBufferOp (const AudioProcessorGraph::Node::Ptr& node_,
  28390. const Array <int>& audioChannelsToUse_,
  28391. const int totalChans_,
  28392. const int midiBufferToUse_)
  28393. : node (node_),
  28394. processor (node_->processor),
  28395. audioChannelsToUse (audioChannelsToUse_),
  28396. totalChans (jmax (1, totalChans_)),
  28397. midiBufferToUse (midiBufferToUse_)
  28398. {
  28399. channels.calloc (totalChans);
  28400. while (audioChannelsToUse.size() < totalChans)
  28401. audioChannelsToUse.add (0);
  28402. }
  28403. ~ProcessBufferOp()
  28404. {
  28405. }
  28406. void perform (AudioSampleBuffer& sharedBufferChans, const OwnedArray <MidiBuffer>& sharedMidiBuffers, const int numSamples)
  28407. {
  28408. for (int i = totalChans; --i >= 0;)
  28409. channels[i] = sharedBufferChans.getSampleData (audioChannelsToUse.getUnchecked (i), 0);
  28410. AudioSampleBuffer buffer (channels, totalChans, numSamples);
  28411. processor->processBlock (buffer, *sharedMidiBuffers.getUnchecked (midiBufferToUse));
  28412. }
  28413. const AudioProcessorGraph::Node::Ptr node;
  28414. AudioProcessor* const processor;
  28415. private:
  28416. Array <int> audioChannelsToUse;
  28417. HeapBlock <float*> channels;
  28418. int totalChans;
  28419. int midiBufferToUse;
  28420. ProcessBufferOp (const ProcessBufferOp&);
  28421. ProcessBufferOp& operator= (const ProcessBufferOp&);
  28422. };
  28423. /** Used to calculate the correct sequence of rendering ops needed, based on
  28424. the best re-use of shared buffers at each stage.
  28425. */
  28426. class RenderingOpSequenceCalculator
  28427. {
  28428. public:
  28429. RenderingOpSequenceCalculator (AudioProcessorGraph& graph_,
  28430. const VoidArray& orderedNodes_,
  28431. VoidArray& renderingOps)
  28432. : graph (graph_),
  28433. orderedNodes (orderedNodes_)
  28434. {
  28435. nodeIds.add (-2); // first buffer is read-only zeros
  28436. channels.add (0);
  28437. midiNodeIds.add (-2);
  28438. for (int i = 0; i < orderedNodes.size(); ++i)
  28439. {
  28440. createRenderingOpsForNode ((AudioProcessorGraph::Node*) orderedNodes.getUnchecked(i),
  28441. renderingOps, i);
  28442. markAnyUnusedBuffersAsFree (i);
  28443. }
  28444. }
  28445. int getNumBuffersNeeded() const { return nodeIds.size(); }
  28446. int getNumMidiBuffersNeeded() const { return midiNodeIds.size(); }
  28447. juce_UseDebuggingNewOperator
  28448. private:
  28449. AudioProcessorGraph& graph;
  28450. const VoidArray& orderedNodes;
  28451. Array <int> nodeIds, channels, midiNodeIds;
  28452. void createRenderingOpsForNode (AudioProcessorGraph::Node* const node,
  28453. VoidArray& renderingOps,
  28454. const int ourRenderingIndex)
  28455. {
  28456. const int numIns = node->processor->getNumInputChannels();
  28457. const int numOuts = node->processor->getNumOutputChannels();
  28458. const int totalChans = jmax (numIns, numOuts);
  28459. Array <int> audioChannelsToUse;
  28460. int midiBufferToUse = -1;
  28461. for (int inputChan = 0; inputChan < numIns; ++inputChan)
  28462. {
  28463. // get a list of all the inputs to this node
  28464. Array <int> sourceNodes, sourceOutputChans;
  28465. for (int i = graph.getNumConnections(); --i >= 0;)
  28466. {
  28467. const AudioProcessorGraph::Connection* const c = graph.getConnection (i);
  28468. if (c->destNodeId == node->id && c->destChannelIndex == inputChan)
  28469. {
  28470. sourceNodes.add (c->sourceNodeId);
  28471. sourceOutputChans.add (c->sourceChannelIndex);
  28472. }
  28473. }
  28474. int bufIndex = -1;
  28475. if (sourceNodes.size() == 0)
  28476. {
  28477. // unconnected input channel
  28478. if (inputChan >= numOuts)
  28479. {
  28480. bufIndex = getReadOnlyEmptyBuffer();
  28481. jassert (bufIndex >= 0);
  28482. }
  28483. else
  28484. {
  28485. bufIndex = getFreeBuffer (false);
  28486. renderingOps.add (new ClearChannelOp (bufIndex));
  28487. }
  28488. }
  28489. else if (sourceNodes.size() == 1)
  28490. {
  28491. // channel with a straightforward single input..
  28492. const int srcNode = sourceNodes.getUnchecked(0);
  28493. const int srcChan = sourceOutputChans.getUnchecked(0);
  28494. bufIndex = getBufferContaining (srcNode, srcChan);
  28495. if (bufIndex < 0)
  28496. {
  28497. // if not found, this is probably a feedback loop
  28498. bufIndex = getReadOnlyEmptyBuffer();
  28499. jassert (bufIndex >= 0);
  28500. }
  28501. if (inputChan < numOuts
  28502. && isBufferNeededLater (ourRenderingIndex,
  28503. inputChan,
  28504. srcNode, srcChan))
  28505. {
  28506. // can't mess up this channel because it's needed later by another node, so we
  28507. // need to use a copy of it..
  28508. const int newFreeBuffer = getFreeBuffer (false);
  28509. renderingOps.add (new CopyChannelOp (bufIndex, newFreeBuffer));
  28510. bufIndex = newFreeBuffer;
  28511. }
  28512. }
  28513. else
  28514. {
  28515. // channel with a mix of several inputs..
  28516. // try to find a re-usable channel from our inputs..
  28517. int reusableInputIndex = -1;
  28518. for (int i = 0; i < sourceNodes.size(); ++i)
  28519. {
  28520. const int sourceBufIndex = getBufferContaining (sourceNodes.getUnchecked(i),
  28521. sourceOutputChans.getUnchecked(i));
  28522. if (sourceBufIndex >= 0
  28523. && ! isBufferNeededLater (ourRenderingIndex,
  28524. inputChan,
  28525. sourceNodes.getUnchecked(i),
  28526. sourceOutputChans.getUnchecked(i)))
  28527. {
  28528. // we've found one of our input chans that can be re-used..
  28529. reusableInputIndex = i;
  28530. bufIndex = sourceBufIndex;
  28531. break;
  28532. }
  28533. }
  28534. if (reusableInputIndex < 0)
  28535. {
  28536. // can't re-use any of our input chans, so get a new one and copy everything into it..
  28537. bufIndex = getFreeBuffer (false);
  28538. jassert (bufIndex != 0);
  28539. const int srcIndex = getBufferContaining (sourceNodes.getUnchecked (0),
  28540. sourceOutputChans.getUnchecked (0));
  28541. if (srcIndex < 0)
  28542. {
  28543. // if not found, this is probably a feedback loop
  28544. renderingOps.add (new ClearChannelOp (bufIndex));
  28545. }
  28546. else
  28547. {
  28548. renderingOps.add (new CopyChannelOp (srcIndex, bufIndex));
  28549. }
  28550. reusableInputIndex = 0;
  28551. }
  28552. for (int j = 0; j < sourceNodes.size(); ++j)
  28553. {
  28554. if (j != reusableInputIndex)
  28555. {
  28556. const int srcIndex = getBufferContaining (sourceNodes.getUnchecked(j),
  28557. sourceOutputChans.getUnchecked(j));
  28558. if (srcIndex >= 0)
  28559. renderingOps.add (new AddChannelOp (srcIndex, bufIndex));
  28560. }
  28561. }
  28562. }
  28563. jassert (bufIndex >= 0);
  28564. audioChannelsToUse.add (bufIndex);
  28565. if (inputChan < numOuts)
  28566. markBufferAsContaining (bufIndex, node->id, inputChan);
  28567. }
  28568. for (int outputChan = numIns; outputChan < numOuts; ++outputChan)
  28569. {
  28570. const int bufIndex = getFreeBuffer (false);
  28571. jassert (bufIndex != 0);
  28572. audioChannelsToUse.add (bufIndex);
  28573. markBufferAsContaining (bufIndex, node->id, outputChan);
  28574. }
  28575. // Now the same thing for midi..
  28576. Array <int> midiSourceNodes;
  28577. for (int i = graph.getNumConnections(); --i >= 0;)
  28578. {
  28579. const AudioProcessorGraph::Connection* const c = graph.getConnection (i);
  28580. if (c->destNodeId == node->id && c->destChannelIndex == AudioProcessorGraph::midiChannelIndex)
  28581. midiSourceNodes.add (c->sourceNodeId);
  28582. }
  28583. if (midiSourceNodes.size() == 0)
  28584. {
  28585. // No midi inputs..
  28586. midiBufferToUse = getFreeBuffer (true); // need to pick a buffer even if the processor doesn't use midi
  28587. if (node->processor->acceptsMidi() || node->processor->producesMidi())
  28588. renderingOps.add (new ClearMidiBufferOp (midiBufferToUse));
  28589. }
  28590. else if (midiSourceNodes.size() == 1)
  28591. {
  28592. // One midi input..
  28593. midiBufferToUse = getBufferContaining (midiSourceNodes.getUnchecked(0),
  28594. AudioProcessorGraph::midiChannelIndex);
  28595. if (midiBufferToUse >= 0)
  28596. {
  28597. if (isBufferNeededLater (ourRenderingIndex,
  28598. AudioProcessorGraph::midiChannelIndex,
  28599. midiSourceNodes.getUnchecked(0),
  28600. AudioProcessorGraph::midiChannelIndex))
  28601. {
  28602. // can't mess up this channel because it's needed later by another node, so we
  28603. // need to use a copy of it..
  28604. const int newFreeBuffer = getFreeBuffer (true);
  28605. renderingOps.add (new CopyMidiBufferOp (midiBufferToUse, newFreeBuffer));
  28606. midiBufferToUse = newFreeBuffer;
  28607. }
  28608. }
  28609. else
  28610. {
  28611. // probably a feedback loop, so just use an empty one..
  28612. midiBufferToUse = getFreeBuffer (true); // need to pick a buffer even if the processor doesn't use midi
  28613. }
  28614. }
  28615. else
  28616. {
  28617. // More than one midi input being mixed..
  28618. int reusableInputIndex = -1;
  28619. for (int i = 0; i < midiSourceNodes.size(); ++i)
  28620. {
  28621. const int sourceBufIndex = getBufferContaining (midiSourceNodes.getUnchecked(i),
  28622. AudioProcessorGraph::midiChannelIndex);
  28623. if (sourceBufIndex >= 0
  28624. && ! isBufferNeededLater (ourRenderingIndex,
  28625. AudioProcessorGraph::midiChannelIndex,
  28626. midiSourceNodes.getUnchecked(i),
  28627. AudioProcessorGraph::midiChannelIndex))
  28628. {
  28629. // we've found one of our input buffers that can be re-used..
  28630. reusableInputIndex = i;
  28631. midiBufferToUse = sourceBufIndex;
  28632. break;
  28633. }
  28634. }
  28635. if (reusableInputIndex < 0)
  28636. {
  28637. // can't re-use any of our input buffers, so get a new one and copy everything into it..
  28638. midiBufferToUse = getFreeBuffer (true);
  28639. jassert (midiBufferToUse >= 0);
  28640. const int srcIndex = getBufferContaining (midiSourceNodes.getUnchecked(0),
  28641. AudioProcessorGraph::midiChannelIndex);
  28642. if (srcIndex >= 0)
  28643. renderingOps.add (new CopyMidiBufferOp (srcIndex, midiBufferToUse));
  28644. else
  28645. renderingOps.add (new ClearMidiBufferOp (midiBufferToUse));
  28646. reusableInputIndex = 0;
  28647. }
  28648. for (int j = 0; j < midiSourceNodes.size(); ++j)
  28649. {
  28650. if (j != reusableInputIndex)
  28651. {
  28652. const int srcIndex = getBufferContaining (midiSourceNodes.getUnchecked(j),
  28653. AudioProcessorGraph::midiChannelIndex);
  28654. if (srcIndex >= 0)
  28655. renderingOps.add (new AddMidiBufferOp (srcIndex, midiBufferToUse));
  28656. }
  28657. }
  28658. }
  28659. if (node->processor->producesMidi())
  28660. markBufferAsContaining (midiBufferToUse, node->id,
  28661. AudioProcessorGraph::midiChannelIndex);
  28662. renderingOps.add (new ProcessBufferOp (node, audioChannelsToUse,
  28663. totalChans, midiBufferToUse));
  28664. }
  28665. int getFreeBuffer (const bool forMidi)
  28666. {
  28667. if (forMidi)
  28668. {
  28669. for (int i = 1; i < midiNodeIds.size(); ++i)
  28670. if (midiNodeIds.getUnchecked(i) < 0)
  28671. return i;
  28672. midiNodeIds.add (-1);
  28673. return midiNodeIds.size() - 1;
  28674. }
  28675. else
  28676. {
  28677. for (int i = 1; i < nodeIds.size(); ++i)
  28678. if (nodeIds.getUnchecked(i) < 0)
  28679. return i;
  28680. nodeIds.add (-1);
  28681. channels.add (0);
  28682. return nodeIds.size() - 1;
  28683. }
  28684. }
  28685. int getReadOnlyEmptyBuffer() const
  28686. {
  28687. return 0;
  28688. }
  28689. int getBufferContaining (const int nodeId, const int outputChannel) const
  28690. {
  28691. if (outputChannel == AudioProcessorGraph::midiChannelIndex)
  28692. {
  28693. for (int i = midiNodeIds.size(); --i >= 0;)
  28694. if (midiNodeIds.getUnchecked(i) == nodeId)
  28695. return i;
  28696. }
  28697. else
  28698. {
  28699. for (int i = nodeIds.size(); --i >= 0;)
  28700. if (nodeIds.getUnchecked(i) == nodeId
  28701. && channels.getUnchecked(i) == outputChannel)
  28702. return i;
  28703. }
  28704. return -1;
  28705. }
  28706. void markAnyUnusedBuffersAsFree (const int stepIndex)
  28707. {
  28708. int i;
  28709. for (i = 0; i < nodeIds.size(); ++i)
  28710. {
  28711. if (nodeIds.getUnchecked(i) >= 0
  28712. && ! isBufferNeededLater (stepIndex, -1,
  28713. nodeIds.getUnchecked(i),
  28714. channels.getUnchecked(i)))
  28715. {
  28716. nodeIds.set (i, -1);
  28717. }
  28718. }
  28719. for (i = 0; i < midiNodeIds.size(); ++i)
  28720. {
  28721. if (midiNodeIds.getUnchecked(i) >= 0
  28722. && ! isBufferNeededLater (stepIndex, -1,
  28723. midiNodeIds.getUnchecked(i),
  28724. AudioProcessorGraph::midiChannelIndex))
  28725. {
  28726. midiNodeIds.set (i, -1);
  28727. }
  28728. }
  28729. }
  28730. bool isBufferNeededLater (int stepIndexToSearchFrom,
  28731. int inputChannelOfIndexToIgnore,
  28732. const int nodeId,
  28733. const int outputChanIndex) const
  28734. {
  28735. while (stepIndexToSearchFrom < orderedNodes.size())
  28736. {
  28737. const AudioProcessorGraph::Node* const node = (const AudioProcessorGraph::Node*) orderedNodes.getUnchecked (stepIndexToSearchFrom);
  28738. if (outputChanIndex == AudioProcessorGraph::midiChannelIndex)
  28739. {
  28740. if (inputChannelOfIndexToIgnore != AudioProcessorGraph::midiChannelIndex
  28741. && graph.getConnectionBetween (nodeId, AudioProcessorGraph::midiChannelIndex,
  28742. node->id, AudioProcessorGraph::midiChannelIndex) != 0)
  28743. return true;
  28744. }
  28745. else
  28746. {
  28747. for (int i = 0; i < node->processor->getNumInputChannels(); ++i)
  28748. if (i != inputChannelOfIndexToIgnore
  28749. && graph.getConnectionBetween (nodeId, outputChanIndex,
  28750. node->id, i) != 0)
  28751. return true;
  28752. }
  28753. inputChannelOfIndexToIgnore = -1;
  28754. ++stepIndexToSearchFrom;
  28755. }
  28756. return false;
  28757. }
  28758. void markBufferAsContaining (int bufferNum, int nodeId, int outputIndex)
  28759. {
  28760. if (outputIndex == AudioProcessorGraph::midiChannelIndex)
  28761. {
  28762. jassert (bufferNum > 0 && bufferNum < midiNodeIds.size());
  28763. midiNodeIds.set (bufferNum, nodeId);
  28764. }
  28765. else
  28766. {
  28767. jassert (bufferNum >= 0 && bufferNum < nodeIds.size());
  28768. nodeIds.set (bufferNum, nodeId);
  28769. channels.set (bufferNum, outputIndex);
  28770. }
  28771. }
  28772. RenderingOpSequenceCalculator (const RenderingOpSequenceCalculator&);
  28773. RenderingOpSequenceCalculator& operator= (const RenderingOpSequenceCalculator&);
  28774. };
  28775. }
  28776. void AudioProcessorGraph::clearRenderingSequence()
  28777. {
  28778. const ScopedLock sl (renderLock);
  28779. for (int i = renderingOps.size(); --i >= 0;)
  28780. {
  28781. GraphRenderingOps::AudioGraphRenderingOp* const r
  28782. = (GraphRenderingOps::AudioGraphRenderingOp*) renderingOps.getUnchecked(i);
  28783. renderingOps.remove (i);
  28784. delete r;
  28785. }
  28786. }
  28787. bool AudioProcessorGraph::isAnInputTo (const uint32 possibleInputId,
  28788. const uint32 possibleDestinationId,
  28789. const int recursionCheck) const
  28790. {
  28791. if (recursionCheck > 0)
  28792. {
  28793. for (int i = connections.size(); --i >= 0;)
  28794. {
  28795. const AudioProcessorGraph::Connection* const c = connections.getUnchecked (i);
  28796. if (c->destNodeId == possibleDestinationId
  28797. && (c->sourceNodeId == possibleInputId
  28798. || isAnInputTo (possibleInputId, c->sourceNodeId, recursionCheck - 1)))
  28799. return true;
  28800. }
  28801. }
  28802. return false;
  28803. }
  28804. void AudioProcessorGraph::buildRenderingSequence()
  28805. {
  28806. VoidArray newRenderingOps;
  28807. int numRenderingBuffersNeeded = 2;
  28808. int numMidiBuffersNeeded = 1;
  28809. {
  28810. MessageManagerLock mml;
  28811. VoidArray orderedNodes;
  28812. int i;
  28813. for (i = 0; i < nodes.size(); ++i)
  28814. {
  28815. Node* const node = nodes.getUnchecked(i);
  28816. node->prepare (getSampleRate(), getBlockSize(), this);
  28817. int j = 0;
  28818. for (; j < orderedNodes.size(); ++j)
  28819. if (isAnInputTo (node->id,
  28820. ((Node*) orderedNodes.getUnchecked (j))->id,
  28821. nodes.size() + 1))
  28822. break;
  28823. orderedNodes.insert (j, node);
  28824. }
  28825. GraphRenderingOps::RenderingOpSequenceCalculator calculator (*this, orderedNodes, newRenderingOps);
  28826. numRenderingBuffersNeeded = calculator.getNumBuffersNeeded();
  28827. numMidiBuffersNeeded = calculator.getNumMidiBuffersNeeded();
  28828. }
  28829. VoidArray oldRenderingOps (renderingOps);
  28830. {
  28831. // swap over to the new rendering sequence..
  28832. const ScopedLock sl (renderLock);
  28833. renderingBuffers.setSize (numRenderingBuffersNeeded, getBlockSize());
  28834. renderingBuffers.clear();
  28835. for (int i = midiBuffers.size(); --i >= 0;)
  28836. midiBuffers.getUnchecked(i)->clear();
  28837. while (midiBuffers.size() < numMidiBuffersNeeded)
  28838. midiBuffers.add (new MidiBuffer());
  28839. renderingOps = newRenderingOps;
  28840. }
  28841. for (int i = oldRenderingOps.size(); --i >= 0;)
  28842. delete (GraphRenderingOps::AudioGraphRenderingOp*) oldRenderingOps.getUnchecked(i);
  28843. }
  28844. void AudioProcessorGraph::handleAsyncUpdate()
  28845. {
  28846. buildRenderingSequence();
  28847. }
  28848. void AudioProcessorGraph::prepareToPlay (double /*sampleRate*/, int estimatedSamplesPerBlock)
  28849. {
  28850. currentAudioInputBuffer = 0;
  28851. currentAudioOutputBuffer.setSize (jmax (1, getNumOutputChannels()), estimatedSamplesPerBlock);
  28852. currentMidiInputBuffer = 0;
  28853. currentMidiOutputBuffer.clear();
  28854. clearRenderingSequence();
  28855. buildRenderingSequence();
  28856. }
  28857. void AudioProcessorGraph::releaseResources()
  28858. {
  28859. for (int i = 0; i < nodes.size(); ++i)
  28860. nodes.getUnchecked(i)->unprepare();
  28861. renderingBuffers.setSize (1, 1);
  28862. midiBuffers.clear();
  28863. currentAudioInputBuffer = 0;
  28864. currentAudioOutputBuffer.setSize (1, 1);
  28865. currentMidiInputBuffer = 0;
  28866. currentMidiOutputBuffer.clear();
  28867. }
  28868. void AudioProcessorGraph::processBlock (AudioSampleBuffer& buffer, MidiBuffer& midiMessages)
  28869. {
  28870. const int numSamples = buffer.getNumSamples();
  28871. const ScopedLock sl (renderLock);
  28872. currentAudioInputBuffer = &buffer;
  28873. currentAudioOutputBuffer.setSize (jmax (1, buffer.getNumChannels()), numSamples);
  28874. currentAudioOutputBuffer.clear();
  28875. currentMidiInputBuffer = &midiMessages;
  28876. currentMidiOutputBuffer.clear();
  28877. int i;
  28878. for (i = 0; i < renderingOps.size(); ++i)
  28879. {
  28880. GraphRenderingOps::AudioGraphRenderingOp* const op
  28881. = (GraphRenderingOps::AudioGraphRenderingOp*) renderingOps.getUnchecked(i);
  28882. op->perform (renderingBuffers, midiBuffers, numSamples);
  28883. }
  28884. for (i = 0; i < buffer.getNumChannels(); ++i)
  28885. buffer.copyFrom (i, 0, currentAudioOutputBuffer, i, 0, numSamples);
  28886. midiMessages.clear();
  28887. midiMessages.addEvents (currentMidiOutputBuffer, 0, buffer.getNumSamples(), 0);
  28888. }
  28889. const String AudioProcessorGraph::getInputChannelName (const int channelIndex) const
  28890. {
  28891. return "Input " + String (channelIndex + 1);
  28892. }
  28893. const String AudioProcessorGraph::getOutputChannelName (const int channelIndex) const
  28894. {
  28895. return "Output " + String (channelIndex + 1);
  28896. }
  28897. bool AudioProcessorGraph::isInputChannelStereoPair (int /*index*/) const
  28898. {
  28899. return true;
  28900. }
  28901. bool AudioProcessorGraph::isOutputChannelStereoPair (int /*index*/) const
  28902. {
  28903. return true;
  28904. }
  28905. bool AudioProcessorGraph::acceptsMidi() const
  28906. {
  28907. return true;
  28908. }
  28909. bool AudioProcessorGraph::producesMidi() const
  28910. {
  28911. return true;
  28912. }
  28913. void AudioProcessorGraph::getStateInformation (JUCE_NAMESPACE::MemoryBlock& /*destData*/)
  28914. {
  28915. }
  28916. void AudioProcessorGraph::setStateInformation (const void* /*data*/, int /*sizeInBytes*/)
  28917. {
  28918. }
  28919. AudioProcessorGraph::AudioGraphIOProcessor::AudioGraphIOProcessor (const IODeviceType type_)
  28920. : type (type_),
  28921. graph (0)
  28922. {
  28923. }
  28924. AudioProcessorGraph::AudioGraphIOProcessor::~AudioGraphIOProcessor()
  28925. {
  28926. }
  28927. const String AudioProcessorGraph::AudioGraphIOProcessor::getName() const
  28928. {
  28929. switch (type)
  28930. {
  28931. case audioOutputNode:
  28932. return "Audio Output";
  28933. case audioInputNode:
  28934. return "Audio Input";
  28935. case midiOutputNode:
  28936. return "Midi Output";
  28937. case midiInputNode:
  28938. return "Midi Input";
  28939. default:
  28940. break;
  28941. }
  28942. return String::empty;
  28943. }
  28944. void AudioProcessorGraph::AudioGraphIOProcessor::fillInPluginDescription (PluginDescription& d) const
  28945. {
  28946. d.name = getName();
  28947. d.uid = d.name.hashCode();
  28948. d.category = "I/O devices";
  28949. d.pluginFormatName = "Internal";
  28950. d.manufacturerName = "Raw Material Software";
  28951. d.version = "1.0";
  28952. d.isInstrument = false;
  28953. d.numInputChannels = getNumInputChannels();
  28954. if (type == audioOutputNode && graph != 0)
  28955. d.numInputChannels = graph->getNumInputChannels();
  28956. d.numOutputChannels = getNumOutputChannels();
  28957. if (type == audioInputNode && graph != 0)
  28958. d.numOutputChannels = graph->getNumOutputChannels();
  28959. }
  28960. void AudioProcessorGraph::AudioGraphIOProcessor::prepareToPlay (double, int)
  28961. {
  28962. jassert (graph != 0);
  28963. }
  28964. void AudioProcessorGraph::AudioGraphIOProcessor::releaseResources()
  28965. {
  28966. }
  28967. void AudioProcessorGraph::AudioGraphIOProcessor::processBlock (AudioSampleBuffer& buffer,
  28968. MidiBuffer& midiMessages)
  28969. {
  28970. jassert (graph != 0);
  28971. switch (type)
  28972. {
  28973. case audioOutputNode:
  28974. {
  28975. for (int i = jmin (graph->currentAudioOutputBuffer.getNumChannels(),
  28976. buffer.getNumChannels()); --i >= 0;)
  28977. {
  28978. graph->currentAudioOutputBuffer.addFrom (i, 0, buffer, i, 0, buffer.getNumSamples());
  28979. }
  28980. break;
  28981. }
  28982. case audioInputNode:
  28983. {
  28984. for (int i = jmin (graph->currentAudioInputBuffer->getNumChannels(),
  28985. buffer.getNumChannels()); --i >= 0;)
  28986. {
  28987. buffer.copyFrom (i, 0, *graph->currentAudioInputBuffer, i, 0, buffer.getNumSamples());
  28988. }
  28989. break;
  28990. }
  28991. case midiOutputNode:
  28992. graph->currentMidiOutputBuffer.addEvents (midiMessages, 0, buffer.getNumSamples(), 0);
  28993. break;
  28994. case midiInputNode:
  28995. midiMessages.addEvents (*graph->currentMidiInputBuffer, 0, buffer.getNumSamples(), 0);
  28996. break;
  28997. default:
  28998. break;
  28999. }
  29000. }
  29001. bool AudioProcessorGraph::AudioGraphIOProcessor::acceptsMidi() const
  29002. {
  29003. return type == midiOutputNode;
  29004. }
  29005. bool AudioProcessorGraph::AudioGraphIOProcessor::producesMidi() const
  29006. {
  29007. return type == midiInputNode;
  29008. }
  29009. const String AudioProcessorGraph::AudioGraphIOProcessor::getInputChannelName (const int channelIndex) const
  29010. {
  29011. switch (type)
  29012. {
  29013. case audioOutputNode:
  29014. return "Output " + String (channelIndex + 1);
  29015. case midiOutputNode:
  29016. return "Midi Output";
  29017. default:
  29018. break;
  29019. }
  29020. return String::empty;
  29021. }
  29022. const String AudioProcessorGraph::AudioGraphIOProcessor::getOutputChannelName (const int channelIndex) const
  29023. {
  29024. switch (type)
  29025. {
  29026. case audioInputNode:
  29027. return "Input " + String (channelIndex + 1);
  29028. case midiInputNode:
  29029. return "Midi Input";
  29030. default:
  29031. break;
  29032. }
  29033. return String::empty;
  29034. }
  29035. bool AudioProcessorGraph::AudioGraphIOProcessor::isInputChannelStereoPair (int /*index*/) const
  29036. {
  29037. return type == audioInputNode || type == audioOutputNode;
  29038. }
  29039. bool AudioProcessorGraph::AudioGraphIOProcessor::isOutputChannelStereoPair (int index) const
  29040. {
  29041. return isInputChannelStereoPair (index);
  29042. }
  29043. bool AudioProcessorGraph::AudioGraphIOProcessor::isInput() const
  29044. {
  29045. return type == audioInputNode || type == midiInputNode;
  29046. }
  29047. bool AudioProcessorGraph::AudioGraphIOProcessor::isOutput() const
  29048. {
  29049. return type == audioOutputNode || type == midiOutputNode;
  29050. }
  29051. AudioProcessorEditor* AudioProcessorGraph::AudioGraphIOProcessor::createEditor()
  29052. {
  29053. return 0;
  29054. }
  29055. int AudioProcessorGraph::AudioGraphIOProcessor::getNumParameters() { return 0; }
  29056. const String AudioProcessorGraph::AudioGraphIOProcessor::getParameterName (int) { return String::empty; }
  29057. float AudioProcessorGraph::AudioGraphIOProcessor::getParameter (int) { return 0.0f; }
  29058. const String AudioProcessorGraph::AudioGraphIOProcessor::getParameterText (int) { return String::empty; }
  29059. void AudioProcessorGraph::AudioGraphIOProcessor::setParameter (int, float) { }
  29060. int AudioProcessorGraph::AudioGraphIOProcessor::getNumPrograms() { return 0; }
  29061. int AudioProcessorGraph::AudioGraphIOProcessor::getCurrentProgram() { return 0; }
  29062. void AudioProcessorGraph::AudioGraphIOProcessor::setCurrentProgram (int) { }
  29063. const String AudioProcessorGraph::AudioGraphIOProcessor::getProgramName (int) { return String::empty; }
  29064. void AudioProcessorGraph::AudioGraphIOProcessor::changeProgramName (int, const String&) { }
  29065. void AudioProcessorGraph::AudioGraphIOProcessor::getStateInformation (JUCE_NAMESPACE::MemoryBlock&)
  29066. {
  29067. }
  29068. void AudioProcessorGraph::AudioGraphIOProcessor::setStateInformation (const void*, int)
  29069. {
  29070. }
  29071. void AudioProcessorGraph::AudioGraphIOProcessor::setParentGraph (AudioProcessorGraph* const newGraph)
  29072. {
  29073. graph = newGraph;
  29074. if (graph != 0)
  29075. {
  29076. setPlayConfigDetails (type == audioOutputNode ? graph->getNumOutputChannels() : 0,
  29077. type == audioInputNode ? graph->getNumInputChannels() : 0,
  29078. getSampleRate(),
  29079. getBlockSize());
  29080. updateHostDisplay();
  29081. }
  29082. }
  29083. END_JUCE_NAMESPACE
  29084. /*** End of inlined file: juce_AudioProcessorGraph.cpp ***/
  29085. /*** Start of inlined file: juce_AudioProcessorPlayer.cpp ***/
  29086. BEGIN_JUCE_NAMESPACE
  29087. AudioProcessorPlayer::AudioProcessorPlayer()
  29088. : processor (0),
  29089. sampleRate (0),
  29090. blockSize (0),
  29091. isPrepared (false),
  29092. numInputChans (0),
  29093. numOutputChans (0),
  29094. tempBuffer (1, 1)
  29095. {
  29096. }
  29097. AudioProcessorPlayer::~AudioProcessorPlayer()
  29098. {
  29099. setProcessor (0);
  29100. }
  29101. void AudioProcessorPlayer::setProcessor (AudioProcessor* const processorToPlay)
  29102. {
  29103. if (processor != processorToPlay)
  29104. {
  29105. if (processorToPlay != 0 && sampleRate > 0 && blockSize > 0)
  29106. {
  29107. processorToPlay->setPlayConfigDetails (numInputChans, numOutputChans,
  29108. sampleRate, blockSize);
  29109. processorToPlay->prepareToPlay (sampleRate, blockSize);
  29110. }
  29111. AudioProcessor* oldOne;
  29112. {
  29113. const ScopedLock sl (lock);
  29114. oldOne = isPrepared ? processor : 0;
  29115. processor = processorToPlay;
  29116. isPrepared = true;
  29117. }
  29118. if (oldOne != 0)
  29119. oldOne->releaseResources();
  29120. }
  29121. }
  29122. void AudioProcessorPlayer::audioDeviceIOCallback (const float** inputChannelData,
  29123. int numInputChannels,
  29124. float** outputChannelData,
  29125. int numOutputChannels,
  29126. int numSamples)
  29127. {
  29128. // these should have been prepared by audioDeviceAboutToStart()...
  29129. jassert (sampleRate > 0 && blockSize > 0);
  29130. incomingMidi.clear();
  29131. messageCollector.removeNextBlockOfMessages (incomingMidi, numSamples);
  29132. int i, totalNumChans = 0;
  29133. if (numInputChannels > numOutputChannels)
  29134. {
  29135. // if there aren't enough output channels for the number of
  29136. // inputs, we need to create some temporary extra ones (can't
  29137. // use the input data in case it gets written to)
  29138. tempBuffer.setSize (numInputChannels - numOutputChannels, numSamples,
  29139. false, false, true);
  29140. for (i = 0; i < numOutputChannels; ++i)
  29141. {
  29142. channels[totalNumChans] = outputChannelData[i];
  29143. memcpy (channels[totalNumChans], inputChannelData[i], sizeof (float) * numSamples);
  29144. ++totalNumChans;
  29145. }
  29146. for (i = numOutputChannels; i < numInputChannels; ++i)
  29147. {
  29148. channels[totalNumChans] = tempBuffer.getSampleData (i - numOutputChannels, 0);
  29149. memcpy (channels[totalNumChans], inputChannelData[i], sizeof (float) * numSamples);
  29150. ++totalNumChans;
  29151. }
  29152. }
  29153. else
  29154. {
  29155. for (i = 0; i < numInputChannels; ++i)
  29156. {
  29157. channels[totalNumChans] = outputChannelData[i];
  29158. memcpy (channels[totalNumChans], inputChannelData[i], sizeof (float) * numSamples);
  29159. ++totalNumChans;
  29160. }
  29161. for (i = numInputChannels; i < numOutputChannels; ++i)
  29162. {
  29163. channels[totalNumChans] = outputChannelData[i];
  29164. zeromem (channels[totalNumChans], sizeof (float) * numSamples);
  29165. ++totalNumChans;
  29166. }
  29167. }
  29168. AudioSampleBuffer buffer (channels, totalNumChans, numSamples);
  29169. const ScopedLock sl (lock);
  29170. if (processor != 0)
  29171. processor->processBlock (buffer, incomingMidi);
  29172. }
  29173. void AudioProcessorPlayer::audioDeviceAboutToStart (AudioIODevice* device)
  29174. {
  29175. const ScopedLock sl (lock);
  29176. sampleRate = device->getCurrentSampleRate();
  29177. blockSize = device->getCurrentBufferSizeSamples();
  29178. numInputChans = device->getActiveInputChannels().countNumberOfSetBits();
  29179. numOutputChans = device->getActiveOutputChannels().countNumberOfSetBits();
  29180. messageCollector.reset (sampleRate);
  29181. zeromem (channels, sizeof (channels));
  29182. if (processor != 0)
  29183. {
  29184. if (isPrepared)
  29185. processor->releaseResources();
  29186. AudioProcessor* const oldProcessor = processor;
  29187. setProcessor (0);
  29188. setProcessor (oldProcessor);
  29189. }
  29190. }
  29191. void AudioProcessorPlayer::audioDeviceStopped()
  29192. {
  29193. const ScopedLock sl (lock);
  29194. if (processor != 0 && isPrepared)
  29195. processor->releaseResources();
  29196. sampleRate = 0.0;
  29197. blockSize = 0;
  29198. isPrepared = false;
  29199. tempBuffer.setSize (1, 1);
  29200. }
  29201. void AudioProcessorPlayer::handleIncomingMidiMessage (MidiInput*, const MidiMessage& message)
  29202. {
  29203. messageCollector.addMessageToQueue (message);
  29204. }
  29205. END_JUCE_NAMESPACE
  29206. /*** End of inlined file: juce_AudioProcessorPlayer.cpp ***/
  29207. /*** Start of inlined file: juce_GenericAudioProcessorEditor.cpp ***/
  29208. BEGIN_JUCE_NAMESPACE
  29209. class ProcessorParameterPropertyComp : public PropertyComponent,
  29210. public AudioProcessorListener,
  29211. public AsyncUpdater
  29212. {
  29213. public:
  29214. ProcessorParameterPropertyComp (const String& name,
  29215. AudioProcessor* const owner_,
  29216. const int index_)
  29217. : PropertyComponent (name),
  29218. owner (owner_),
  29219. index (index_)
  29220. {
  29221. addAndMakeVisible (slider = new ParamSlider (owner_, index_));
  29222. owner_->addListener (this);
  29223. }
  29224. ~ProcessorParameterPropertyComp()
  29225. {
  29226. owner->removeListener (this);
  29227. deleteAllChildren();
  29228. }
  29229. void refresh()
  29230. {
  29231. slider->setValue (owner->getParameter (index), false);
  29232. }
  29233. void audioProcessorChanged (AudioProcessor*) {}
  29234. void audioProcessorParameterChanged (AudioProcessor*, int parameterIndex, float)
  29235. {
  29236. if (parameterIndex == index)
  29237. triggerAsyncUpdate();
  29238. }
  29239. void handleAsyncUpdate()
  29240. {
  29241. refresh();
  29242. }
  29243. juce_UseDebuggingNewOperator
  29244. private:
  29245. AudioProcessor* const owner;
  29246. const int index;
  29247. Slider* slider;
  29248. class ParamSlider : public Slider
  29249. {
  29250. public:
  29251. ParamSlider (AudioProcessor* const owner_, const int index_)
  29252. : Slider (String::empty),
  29253. owner (owner_),
  29254. index (index_)
  29255. {
  29256. setRange (0.0, 1.0, 0.0);
  29257. setSliderStyle (Slider::LinearBar);
  29258. setTextBoxIsEditable (false);
  29259. setScrollWheelEnabled (false);
  29260. }
  29261. ~ParamSlider()
  29262. {
  29263. }
  29264. void valueChanged()
  29265. {
  29266. const float newVal = (float) getValue();
  29267. if (owner->getParameter (index) != newVal)
  29268. owner->setParameter (index, newVal);
  29269. }
  29270. const String getTextFromValue (double /*value*/)
  29271. {
  29272. return owner->getParameterText (index);
  29273. }
  29274. juce_UseDebuggingNewOperator
  29275. private:
  29276. AudioProcessor* const owner;
  29277. const int index;
  29278. ParamSlider (const ParamSlider&);
  29279. ParamSlider& operator= (const ParamSlider&);
  29280. };
  29281. ProcessorParameterPropertyComp (const ProcessorParameterPropertyComp&);
  29282. ProcessorParameterPropertyComp& operator= (const ProcessorParameterPropertyComp&);
  29283. };
  29284. GenericAudioProcessorEditor::GenericAudioProcessorEditor (AudioProcessor* const owner_)
  29285. : AudioProcessorEditor (owner_)
  29286. {
  29287. setOpaque (true);
  29288. addAndMakeVisible (panel = new PropertyPanel());
  29289. Array <PropertyComponent*> params;
  29290. const int numParams = owner_->getNumParameters();
  29291. int totalHeight = 0;
  29292. for (int i = 0; i < numParams; ++i)
  29293. {
  29294. String name (owner_->getParameterName (i));
  29295. if (name.trim().isEmpty())
  29296. name = "Unnamed";
  29297. ProcessorParameterPropertyComp* const pc = new ProcessorParameterPropertyComp (name, owner_, i);
  29298. params.add (pc);
  29299. totalHeight += pc->getPreferredHeight();
  29300. }
  29301. panel->addProperties (params);
  29302. setSize (400, jlimit (25, 400, totalHeight));
  29303. }
  29304. GenericAudioProcessorEditor::~GenericAudioProcessorEditor()
  29305. {
  29306. deleteAllChildren();
  29307. }
  29308. void GenericAudioProcessorEditor::paint (Graphics& g)
  29309. {
  29310. g.fillAll (Colours::white);
  29311. }
  29312. void GenericAudioProcessorEditor::resized()
  29313. {
  29314. panel->setSize (getWidth(), getHeight());
  29315. }
  29316. END_JUCE_NAMESPACE
  29317. /*** End of inlined file: juce_GenericAudioProcessorEditor.cpp ***/
  29318. /*** Start of inlined file: juce_Sampler.cpp ***/
  29319. BEGIN_JUCE_NAMESPACE
  29320. SamplerSound::SamplerSound (const String& name_,
  29321. AudioFormatReader& source,
  29322. const BigInteger& midiNotes_,
  29323. const int midiNoteForNormalPitch,
  29324. const double attackTimeSecs,
  29325. const double releaseTimeSecs,
  29326. const double maxSampleLengthSeconds)
  29327. : name (name_),
  29328. midiNotes (midiNotes_),
  29329. midiRootNote (midiNoteForNormalPitch)
  29330. {
  29331. sourceSampleRate = source.sampleRate;
  29332. if (sourceSampleRate <= 0 || source.lengthInSamples <= 0)
  29333. {
  29334. length = 0;
  29335. attackSamples = 0;
  29336. releaseSamples = 0;
  29337. }
  29338. else
  29339. {
  29340. length = jmin ((int) source.lengthInSamples,
  29341. (int) (maxSampleLengthSeconds * sourceSampleRate));
  29342. data = new AudioSampleBuffer (jmin (2, (int) source.numChannels), length + 4);
  29343. data->readFromAudioReader (&source, 0, length + 4, 0, true, true);
  29344. attackSamples = roundToInt (attackTimeSecs * sourceSampleRate);
  29345. releaseSamples = roundToInt (releaseTimeSecs * sourceSampleRate);
  29346. }
  29347. }
  29348. SamplerSound::~SamplerSound()
  29349. {
  29350. }
  29351. bool SamplerSound::appliesToNote (const int midiNoteNumber)
  29352. {
  29353. return midiNotes [midiNoteNumber];
  29354. }
  29355. bool SamplerSound::appliesToChannel (const int /*midiChannel*/)
  29356. {
  29357. return true;
  29358. }
  29359. SamplerVoice::SamplerVoice()
  29360. : pitchRatio (0.0),
  29361. sourceSamplePosition (0.0),
  29362. lgain (0.0f),
  29363. rgain (0.0f),
  29364. isInAttack (false),
  29365. isInRelease (false)
  29366. {
  29367. }
  29368. SamplerVoice::~SamplerVoice()
  29369. {
  29370. }
  29371. bool SamplerVoice::canPlaySound (SynthesiserSound* sound)
  29372. {
  29373. return dynamic_cast <const SamplerSound*> (sound) != 0;
  29374. }
  29375. void SamplerVoice::startNote (const int midiNoteNumber,
  29376. const float velocity,
  29377. SynthesiserSound* s,
  29378. const int /*currentPitchWheelPosition*/)
  29379. {
  29380. const SamplerSound* const sound = dynamic_cast <const SamplerSound*> (s);
  29381. jassert (sound != 0); // this object can only play SamplerSounds!
  29382. if (sound != 0)
  29383. {
  29384. const double targetFreq = MidiMessage::getMidiNoteInHertz (midiNoteNumber);
  29385. const double naturalFreq = MidiMessage::getMidiNoteInHertz (sound->midiRootNote);
  29386. pitchRatio = (targetFreq * sound->sourceSampleRate) / (naturalFreq * getSampleRate());
  29387. sourceSamplePosition = 0.0;
  29388. lgain = velocity;
  29389. rgain = velocity;
  29390. isInAttack = (sound->attackSamples > 0);
  29391. isInRelease = false;
  29392. if (isInAttack)
  29393. {
  29394. attackReleaseLevel = 0.0f;
  29395. attackDelta = (float) (pitchRatio / sound->attackSamples);
  29396. }
  29397. else
  29398. {
  29399. attackReleaseLevel = 1.0f;
  29400. attackDelta = 0.0f;
  29401. }
  29402. if (sound->releaseSamples > 0)
  29403. {
  29404. releaseDelta = (float) (-pitchRatio / sound->releaseSamples);
  29405. }
  29406. else
  29407. {
  29408. releaseDelta = 0.0f;
  29409. }
  29410. }
  29411. }
  29412. void SamplerVoice::stopNote (const bool allowTailOff)
  29413. {
  29414. if (allowTailOff)
  29415. {
  29416. isInAttack = false;
  29417. isInRelease = true;
  29418. }
  29419. else
  29420. {
  29421. clearCurrentNote();
  29422. }
  29423. }
  29424. void SamplerVoice::pitchWheelMoved (const int /*newValue*/)
  29425. {
  29426. }
  29427. void SamplerVoice::controllerMoved (const int /*controllerNumber*/,
  29428. const int /*newValue*/)
  29429. {
  29430. }
  29431. void SamplerVoice::renderNextBlock (AudioSampleBuffer& outputBuffer, int startSample, int numSamples)
  29432. {
  29433. const SamplerSound* const playingSound = static_cast <SamplerSound*> (getCurrentlyPlayingSound().getObject());
  29434. if (playingSound != 0)
  29435. {
  29436. const float* const inL = playingSound->data->getSampleData (0, 0);
  29437. const float* const inR = playingSound->data->getNumChannels() > 1
  29438. ? playingSound->data->getSampleData (1, 0) : 0;
  29439. float* outL = outputBuffer.getSampleData (0, startSample);
  29440. float* outR = outputBuffer.getNumChannels() > 1 ? outputBuffer.getSampleData (1, startSample) : 0;
  29441. while (--numSamples >= 0)
  29442. {
  29443. const int pos = (int) sourceSamplePosition;
  29444. const float alpha = (float) (sourceSamplePosition - pos);
  29445. const float invAlpha = 1.0f - alpha;
  29446. // just using a very simple linear interpolation here..
  29447. float l = (inL [pos] * invAlpha + inL [pos + 1] * alpha);
  29448. float r = (inR != 0) ? (inR [pos] * invAlpha + inR [pos + 1] * alpha)
  29449. : l;
  29450. l *= lgain;
  29451. r *= rgain;
  29452. if (isInAttack)
  29453. {
  29454. l *= attackReleaseLevel;
  29455. r *= attackReleaseLevel;
  29456. attackReleaseLevel += attackDelta;
  29457. if (attackReleaseLevel >= 1.0f)
  29458. {
  29459. attackReleaseLevel = 1.0f;
  29460. isInAttack = false;
  29461. }
  29462. }
  29463. else if (isInRelease)
  29464. {
  29465. l *= attackReleaseLevel;
  29466. r *= attackReleaseLevel;
  29467. attackReleaseLevel += releaseDelta;
  29468. if (attackReleaseLevel <= 0.0f)
  29469. {
  29470. stopNote (false);
  29471. break;
  29472. }
  29473. }
  29474. if (outR != 0)
  29475. {
  29476. *outL++ += l;
  29477. *outR++ += r;
  29478. }
  29479. else
  29480. {
  29481. *outL++ += (l + r) * 0.5f;
  29482. }
  29483. sourceSamplePosition += pitchRatio;
  29484. if (sourceSamplePosition > playingSound->length)
  29485. {
  29486. stopNote (false);
  29487. break;
  29488. }
  29489. }
  29490. }
  29491. }
  29492. END_JUCE_NAMESPACE
  29493. /*** End of inlined file: juce_Sampler.cpp ***/
  29494. /*** Start of inlined file: juce_Synthesiser.cpp ***/
  29495. BEGIN_JUCE_NAMESPACE
  29496. SynthesiserSound::SynthesiserSound()
  29497. {
  29498. }
  29499. SynthesiserSound::~SynthesiserSound()
  29500. {
  29501. }
  29502. SynthesiserVoice::SynthesiserVoice()
  29503. : currentSampleRate (44100.0),
  29504. currentlyPlayingNote (-1),
  29505. noteOnTime (0),
  29506. currentlyPlayingSound (0)
  29507. {
  29508. }
  29509. SynthesiserVoice::~SynthesiserVoice()
  29510. {
  29511. }
  29512. bool SynthesiserVoice::isPlayingChannel (const int midiChannel) const
  29513. {
  29514. return currentlyPlayingSound != 0
  29515. && currentlyPlayingSound->appliesToChannel (midiChannel);
  29516. }
  29517. void SynthesiserVoice::setCurrentPlaybackSampleRate (const double newRate)
  29518. {
  29519. currentSampleRate = newRate;
  29520. }
  29521. void SynthesiserVoice::clearCurrentNote()
  29522. {
  29523. currentlyPlayingNote = -1;
  29524. currentlyPlayingSound = 0;
  29525. }
  29526. Synthesiser::Synthesiser()
  29527. : sampleRate (0),
  29528. lastNoteOnCounter (0),
  29529. shouldStealNotes (true)
  29530. {
  29531. for (int i = 0; i < numElementsInArray (lastPitchWheelValues); ++i)
  29532. lastPitchWheelValues[i] = 0x2000;
  29533. }
  29534. Synthesiser::~Synthesiser()
  29535. {
  29536. }
  29537. SynthesiserVoice* Synthesiser::getVoice (const int index) const
  29538. {
  29539. const ScopedLock sl (lock);
  29540. return voices [index];
  29541. }
  29542. void Synthesiser::clearVoices()
  29543. {
  29544. const ScopedLock sl (lock);
  29545. voices.clear();
  29546. }
  29547. void Synthesiser::addVoice (SynthesiserVoice* const newVoice)
  29548. {
  29549. const ScopedLock sl (lock);
  29550. voices.add (newVoice);
  29551. }
  29552. void Synthesiser::removeVoice (const int index)
  29553. {
  29554. const ScopedLock sl (lock);
  29555. voices.remove (index);
  29556. }
  29557. void Synthesiser::clearSounds()
  29558. {
  29559. const ScopedLock sl (lock);
  29560. sounds.clear();
  29561. }
  29562. void Synthesiser::addSound (const SynthesiserSound::Ptr& newSound)
  29563. {
  29564. const ScopedLock sl (lock);
  29565. sounds.add (newSound);
  29566. }
  29567. void Synthesiser::removeSound (const int index)
  29568. {
  29569. const ScopedLock sl (lock);
  29570. sounds.remove (index);
  29571. }
  29572. void Synthesiser::setNoteStealingEnabled (const bool shouldStealNotes_)
  29573. {
  29574. shouldStealNotes = shouldStealNotes_;
  29575. }
  29576. void Synthesiser::setCurrentPlaybackSampleRate (const double newRate)
  29577. {
  29578. if (sampleRate != newRate)
  29579. {
  29580. const ScopedLock sl (lock);
  29581. allNotesOff (0, false);
  29582. sampleRate = newRate;
  29583. for (int i = voices.size(); --i >= 0;)
  29584. voices.getUnchecked (i)->setCurrentPlaybackSampleRate (newRate);
  29585. }
  29586. }
  29587. void Synthesiser::renderNextBlock (AudioSampleBuffer& outputBuffer,
  29588. const MidiBuffer& midiData,
  29589. int startSample,
  29590. int numSamples)
  29591. {
  29592. // must set the sample rate before using this!
  29593. jassert (sampleRate != 0);
  29594. const ScopedLock sl (lock);
  29595. MidiBuffer::Iterator midiIterator (midiData);
  29596. midiIterator.setNextSamplePosition (startSample);
  29597. MidiMessage m (0xf4, 0.0);
  29598. while (numSamples > 0)
  29599. {
  29600. int midiEventPos;
  29601. const bool useEvent = midiIterator.getNextEvent (m, midiEventPos)
  29602. && midiEventPos < startSample + numSamples;
  29603. const int numThisTime = useEvent ? midiEventPos - startSample
  29604. : numSamples;
  29605. if (numThisTime > 0)
  29606. {
  29607. for (int i = voices.size(); --i >= 0;)
  29608. voices.getUnchecked (i)->renderNextBlock (outputBuffer, startSample, numThisTime);
  29609. }
  29610. if (useEvent)
  29611. {
  29612. if (m.isNoteOn())
  29613. {
  29614. const int channel = m.getChannel();
  29615. noteOn (channel,
  29616. m.getNoteNumber(),
  29617. m.getFloatVelocity());
  29618. }
  29619. else if (m.isNoteOff())
  29620. {
  29621. noteOff (m.getChannel(),
  29622. m.getNoteNumber(),
  29623. true);
  29624. }
  29625. else if (m.isAllNotesOff() || m.isAllSoundOff())
  29626. {
  29627. allNotesOff (m.getChannel(), true);
  29628. }
  29629. else if (m.isPitchWheel())
  29630. {
  29631. const int channel = m.getChannel();
  29632. const int wheelPos = m.getPitchWheelValue();
  29633. lastPitchWheelValues [channel - 1] = wheelPos;
  29634. handlePitchWheel (channel, wheelPos);
  29635. }
  29636. else if (m.isController())
  29637. {
  29638. handleController (m.getChannel(),
  29639. m.getControllerNumber(),
  29640. m.getControllerValue());
  29641. }
  29642. }
  29643. startSample += numThisTime;
  29644. numSamples -= numThisTime;
  29645. }
  29646. }
  29647. void Synthesiser::noteOn (const int midiChannel,
  29648. const int midiNoteNumber,
  29649. const float velocity)
  29650. {
  29651. const ScopedLock sl (lock);
  29652. for (int i = sounds.size(); --i >= 0;)
  29653. {
  29654. SynthesiserSound* const sound = sounds.getUnchecked(i);
  29655. if (sound->appliesToNote (midiNoteNumber)
  29656. && sound->appliesToChannel (midiChannel))
  29657. {
  29658. startVoice (findFreeVoice (sound, shouldStealNotes),
  29659. sound, midiChannel, midiNoteNumber, velocity);
  29660. }
  29661. }
  29662. }
  29663. void Synthesiser::startVoice (SynthesiserVoice* const voice,
  29664. SynthesiserSound* const sound,
  29665. const int midiChannel,
  29666. const int midiNoteNumber,
  29667. const float velocity)
  29668. {
  29669. if (voice != 0 && sound != 0)
  29670. {
  29671. if (voice->currentlyPlayingSound != 0)
  29672. voice->stopNote (false);
  29673. voice->startNote (midiNoteNumber,
  29674. velocity,
  29675. sound,
  29676. lastPitchWheelValues [midiChannel - 1]);
  29677. voice->currentlyPlayingNote = midiNoteNumber;
  29678. voice->noteOnTime = ++lastNoteOnCounter;
  29679. voice->currentlyPlayingSound = sound;
  29680. }
  29681. }
  29682. void Synthesiser::noteOff (const int midiChannel,
  29683. const int midiNoteNumber,
  29684. const bool allowTailOff)
  29685. {
  29686. const ScopedLock sl (lock);
  29687. for (int i = voices.size(); --i >= 0;)
  29688. {
  29689. SynthesiserVoice* const voice = voices.getUnchecked (i);
  29690. if (voice->getCurrentlyPlayingNote() == midiNoteNumber)
  29691. {
  29692. SynthesiserSound* const sound = voice->getCurrentlyPlayingSound();
  29693. if (sound != 0
  29694. && sound->appliesToNote (midiNoteNumber)
  29695. && sound->appliesToChannel (midiChannel))
  29696. {
  29697. voice->stopNote (allowTailOff);
  29698. // the subclass MUST call clearCurrentNote() if it's not tailing off! RTFM for stopNote()!
  29699. jassert (allowTailOff || (voice->getCurrentlyPlayingNote() < 0 && voice->getCurrentlyPlayingSound() == 0));
  29700. }
  29701. }
  29702. }
  29703. }
  29704. void Synthesiser::allNotesOff (const int midiChannel,
  29705. const bool allowTailOff)
  29706. {
  29707. const ScopedLock sl (lock);
  29708. for (int i = voices.size(); --i >= 0;)
  29709. {
  29710. SynthesiserVoice* const voice = voices.getUnchecked (i);
  29711. if (midiChannel <= 0 || voice->isPlayingChannel (midiChannel))
  29712. voice->stopNote (allowTailOff);
  29713. }
  29714. }
  29715. void Synthesiser::handlePitchWheel (const int midiChannel,
  29716. const int wheelValue)
  29717. {
  29718. const ScopedLock sl (lock);
  29719. for (int i = voices.size(); --i >= 0;)
  29720. {
  29721. SynthesiserVoice* const voice = voices.getUnchecked (i);
  29722. if (midiChannel <= 0 || voice->isPlayingChannel (midiChannel))
  29723. {
  29724. voice->pitchWheelMoved (wheelValue);
  29725. }
  29726. }
  29727. }
  29728. void Synthesiser::handleController (const int midiChannel,
  29729. const int controllerNumber,
  29730. const int controllerValue)
  29731. {
  29732. const ScopedLock sl (lock);
  29733. for (int i = voices.size(); --i >= 0;)
  29734. {
  29735. SynthesiserVoice* const voice = voices.getUnchecked (i);
  29736. if (midiChannel <= 0 || voice->isPlayingChannel (midiChannel))
  29737. voice->controllerMoved (controllerNumber, controllerValue);
  29738. }
  29739. }
  29740. SynthesiserVoice* Synthesiser::findFreeVoice (SynthesiserSound* soundToPlay,
  29741. const bool stealIfNoneAvailable) const
  29742. {
  29743. const ScopedLock sl (lock);
  29744. for (int i = voices.size(); --i >= 0;)
  29745. if (voices.getUnchecked (i)->getCurrentlyPlayingNote() < 0
  29746. && voices.getUnchecked (i)->canPlaySound (soundToPlay))
  29747. return voices.getUnchecked (i);
  29748. if (stealIfNoneAvailable)
  29749. {
  29750. // currently this just steals the one that's been playing the longest, but could be made a bit smarter..
  29751. SynthesiserVoice* oldest = 0;
  29752. for (int i = voices.size(); --i >= 0;)
  29753. {
  29754. SynthesiserVoice* const voice = voices.getUnchecked (i);
  29755. if (voice->canPlaySound (soundToPlay)
  29756. && (oldest == 0 || oldest->noteOnTime > voice->noteOnTime))
  29757. oldest = voice;
  29758. }
  29759. jassert (oldest != 0);
  29760. return oldest;
  29761. }
  29762. return 0;
  29763. }
  29764. END_JUCE_NAMESPACE
  29765. /*** End of inlined file: juce_Synthesiser.cpp ***/
  29766. /*** Start of inlined file: juce_ActionBroadcaster.cpp ***/
  29767. BEGIN_JUCE_NAMESPACE
  29768. ActionBroadcaster::ActionBroadcaster() throw()
  29769. {
  29770. // are you trying to create this object before or after juce has been intialised??
  29771. jassert (MessageManager::instance != 0);
  29772. }
  29773. ActionBroadcaster::~ActionBroadcaster()
  29774. {
  29775. // all event-based objects must be deleted BEFORE juce is shut down!
  29776. jassert (MessageManager::instance != 0);
  29777. }
  29778. void ActionBroadcaster::addActionListener (ActionListener* const listener)
  29779. {
  29780. actionListenerList.addActionListener (listener);
  29781. }
  29782. void ActionBroadcaster::removeActionListener (ActionListener* const listener)
  29783. {
  29784. jassert (actionListenerList.isValidMessageListener());
  29785. if (actionListenerList.isValidMessageListener())
  29786. actionListenerList.removeActionListener (listener);
  29787. }
  29788. void ActionBroadcaster::removeAllActionListeners()
  29789. {
  29790. actionListenerList.removeAllActionListeners();
  29791. }
  29792. void ActionBroadcaster::sendActionMessage (const String& message) const
  29793. {
  29794. actionListenerList.sendActionMessage (message);
  29795. }
  29796. END_JUCE_NAMESPACE
  29797. /*** End of inlined file: juce_ActionBroadcaster.cpp ***/
  29798. /*** Start of inlined file: juce_ActionListenerList.cpp ***/
  29799. BEGIN_JUCE_NAMESPACE
  29800. // special message of our own with a string in it
  29801. class ActionMessage : public Message
  29802. {
  29803. public:
  29804. const String message;
  29805. ActionMessage (const String& messageText,
  29806. void* const listener_) throw()
  29807. : message (messageText)
  29808. {
  29809. pointerParameter = listener_;
  29810. }
  29811. ~ActionMessage() throw()
  29812. {
  29813. }
  29814. private:
  29815. ActionMessage (const ActionMessage&);
  29816. ActionMessage& operator= (const ActionMessage&);
  29817. };
  29818. ActionListenerList::ActionListenerList() throw()
  29819. {
  29820. }
  29821. ActionListenerList::~ActionListenerList() throw()
  29822. {
  29823. }
  29824. void ActionListenerList::addActionListener (ActionListener* const listener) throw()
  29825. {
  29826. const ScopedLock sl (actionListenerLock_);
  29827. jassert (listener != 0);
  29828. jassert (! actionListeners_.contains (listener)); // trying to add a listener to the list twice!
  29829. if (listener != 0)
  29830. actionListeners_.add (listener);
  29831. }
  29832. void ActionListenerList::removeActionListener (ActionListener* const listener) throw()
  29833. {
  29834. const ScopedLock sl (actionListenerLock_);
  29835. jassert (actionListeners_.contains (listener)); // trying to remove a listener that isn't on the list!
  29836. actionListeners_.removeValue (listener);
  29837. }
  29838. void ActionListenerList::removeAllActionListeners() throw()
  29839. {
  29840. const ScopedLock sl (actionListenerLock_);
  29841. actionListeners_.clear();
  29842. }
  29843. void ActionListenerList::sendActionMessage (const String& message) const
  29844. {
  29845. const ScopedLock sl (actionListenerLock_);
  29846. for (int i = actionListeners_.size(); --i >= 0;)
  29847. postMessage (new ActionMessage (message, static_cast <ActionListener*> (actionListeners_.getUnchecked(i))));
  29848. }
  29849. void ActionListenerList::handleMessage (const Message& message)
  29850. {
  29851. const ActionMessage& am = (const ActionMessage&) message;
  29852. if (actionListeners_.contains (am.pointerParameter))
  29853. static_cast <ActionListener*> (am.pointerParameter)->actionListenerCallback (am.message);
  29854. }
  29855. END_JUCE_NAMESPACE
  29856. /*** End of inlined file: juce_ActionListenerList.cpp ***/
  29857. /*** Start of inlined file: juce_AsyncUpdater.cpp ***/
  29858. BEGIN_JUCE_NAMESPACE
  29859. AsyncUpdater::AsyncUpdater() throw()
  29860. : asyncMessagePending (false)
  29861. {
  29862. internalAsyncHandler.owner = this;
  29863. }
  29864. AsyncUpdater::~AsyncUpdater()
  29865. {
  29866. }
  29867. void AsyncUpdater::triggerAsyncUpdate() throw()
  29868. {
  29869. if (! asyncMessagePending)
  29870. {
  29871. asyncMessagePending = true;
  29872. internalAsyncHandler.postMessage (new Message());
  29873. }
  29874. }
  29875. void AsyncUpdater::cancelPendingUpdate() throw()
  29876. {
  29877. asyncMessagePending = false;
  29878. }
  29879. void AsyncUpdater::handleUpdateNowIfNeeded()
  29880. {
  29881. if (asyncMessagePending)
  29882. {
  29883. asyncMessagePending = false;
  29884. handleAsyncUpdate();
  29885. }
  29886. }
  29887. void AsyncUpdater::AsyncUpdaterInternal::handleMessage (const Message&)
  29888. {
  29889. owner->handleUpdateNowIfNeeded();
  29890. }
  29891. END_JUCE_NAMESPACE
  29892. /*** End of inlined file: juce_AsyncUpdater.cpp ***/
  29893. /*** Start of inlined file: juce_ChangeBroadcaster.cpp ***/
  29894. BEGIN_JUCE_NAMESPACE
  29895. ChangeBroadcaster::ChangeBroadcaster() throw()
  29896. {
  29897. // are you trying to create this object before or after juce has been intialised??
  29898. jassert (MessageManager::instance != 0);
  29899. }
  29900. ChangeBroadcaster::~ChangeBroadcaster()
  29901. {
  29902. // all event-based objects must be deleted BEFORE juce is shut down!
  29903. jassert (MessageManager::instance != 0);
  29904. }
  29905. void ChangeBroadcaster::addChangeListener (ChangeListener* const listener) throw()
  29906. {
  29907. changeListenerList.addChangeListener (listener);
  29908. }
  29909. void ChangeBroadcaster::removeChangeListener (ChangeListener* const listener) throw()
  29910. {
  29911. jassert (changeListenerList.isValidMessageListener());
  29912. if (changeListenerList.isValidMessageListener())
  29913. changeListenerList.removeChangeListener (listener);
  29914. }
  29915. void ChangeBroadcaster::removeAllChangeListeners() throw()
  29916. {
  29917. changeListenerList.removeAllChangeListeners();
  29918. }
  29919. void ChangeBroadcaster::sendChangeMessage (void* objectThatHasChanged) throw()
  29920. {
  29921. changeListenerList.sendChangeMessage (objectThatHasChanged);
  29922. }
  29923. void ChangeBroadcaster::sendSynchronousChangeMessage (void* objectThatHasChanged)
  29924. {
  29925. changeListenerList.sendSynchronousChangeMessage (objectThatHasChanged);
  29926. }
  29927. void ChangeBroadcaster::dispatchPendingMessages()
  29928. {
  29929. changeListenerList.dispatchPendingMessages();
  29930. }
  29931. END_JUCE_NAMESPACE
  29932. /*** End of inlined file: juce_ChangeBroadcaster.cpp ***/
  29933. /*** Start of inlined file: juce_ChangeListenerList.cpp ***/
  29934. BEGIN_JUCE_NAMESPACE
  29935. ChangeListenerList::ChangeListenerList() throw()
  29936. : lastChangedObject (0),
  29937. messagePending (false)
  29938. {
  29939. }
  29940. ChangeListenerList::~ChangeListenerList() throw()
  29941. {
  29942. }
  29943. void ChangeListenerList::addChangeListener (ChangeListener* const listener) throw()
  29944. {
  29945. const ScopedLock sl (lock);
  29946. jassert (listener != 0);
  29947. if (listener != 0)
  29948. listeners.add (listener);
  29949. }
  29950. void ChangeListenerList::removeChangeListener (ChangeListener* const listener) throw()
  29951. {
  29952. const ScopedLock sl (lock);
  29953. listeners.removeValue (listener);
  29954. }
  29955. void ChangeListenerList::removeAllChangeListeners() throw()
  29956. {
  29957. const ScopedLock sl (lock);
  29958. listeners.clear();
  29959. }
  29960. void ChangeListenerList::sendChangeMessage (void* const objectThatHasChanged) throw()
  29961. {
  29962. const ScopedLock sl (lock);
  29963. if ((! messagePending) && (listeners.size() > 0))
  29964. {
  29965. lastChangedObject = objectThatHasChanged;
  29966. postMessage (new Message (0, 0, 0, objectThatHasChanged));
  29967. messagePending = true;
  29968. }
  29969. }
  29970. void ChangeListenerList::handleMessage (const Message& message)
  29971. {
  29972. sendSynchronousChangeMessage (message.pointerParameter);
  29973. }
  29974. void ChangeListenerList::sendSynchronousChangeMessage (void* const objectThatHasChanged)
  29975. {
  29976. const ScopedLock sl (lock);
  29977. messagePending = false;
  29978. for (int i = listeners.size(); --i >= 0;)
  29979. {
  29980. ChangeListener* const l = static_cast <ChangeListener*> (listeners.getUnchecked (i));
  29981. {
  29982. const ScopedUnlock tempUnlocker (lock);
  29983. l->changeListenerCallback (objectThatHasChanged);
  29984. }
  29985. i = jmin (i, listeners.size());
  29986. }
  29987. }
  29988. void ChangeListenerList::dispatchPendingMessages()
  29989. {
  29990. if (messagePending)
  29991. sendSynchronousChangeMessage (lastChangedObject);
  29992. }
  29993. END_JUCE_NAMESPACE
  29994. /*** End of inlined file: juce_ChangeListenerList.cpp ***/
  29995. /*** Start of inlined file: juce_InterprocessConnection.cpp ***/
  29996. BEGIN_JUCE_NAMESPACE
  29997. InterprocessConnection::InterprocessConnection (const bool callbacksOnMessageThread,
  29998. const uint32 magicMessageHeaderNumber)
  29999. : Thread ("Juce IPC connection"),
  30000. callbackConnectionState (false),
  30001. useMessageThread (callbacksOnMessageThread),
  30002. magicMessageHeader (magicMessageHeaderNumber),
  30003. pipeReceiveMessageTimeout (-1)
  30004. {
  30005. }
  30006. InterprocessConnection::~InterprocessConnection()
  30007. {
  30008. callbackConnectionState = false;
  30009. disconnect();
  30010. }
  30011. bool InterprocessConnection::connectToSocket (const String& hostName,
  30012. const int portNumber,
  30013. const int timeOutMillisecs)
  30014. {
  30015. disconnect();
  30016. const ScopedLock sl (pipeAndSocketLock);
  30017. socket = new StreamingSocket();
  30018. if (socket->connect (hostName, portNumber, timeOutMillisecs))
  30019. {
  30020. connectionMadeInt();
  30021. startThread();
  30022. return true;
  30023. }
  30024. else
  30025. {
  30026. socket = 0;
  30027. return false;
  30028. }
  30029. }
  30030. bool InterprocessConnection::connectToPipe (const String& pipeName,
  30031. const int pipeReceiveMessageTimeoutMs)
  30032. {
  30033. disconnect();
  30034. ScopedPointer <NamedPipe> newPipe (new NamedPipe());
  30035. if (newPipe->openExisting (pipeName))
  30036. {
  30037. const ScopedLock sl (pipeAndSocketLock);
  30038. pipeReceiveMessageTimeout = pipeReceiveMessageTimeoutMs;
  30039. initialiseWithPipe (newPipe.release());
  30040. return true;
  30041. }
  30042. return false;
  30043. }
  30044. bool InterprocessConnection::createPipe (const String& pipeName,
  30045. const int pipeReceiveMessageTimeoutMs)
  30046. {
  30047. disconnect();
  30048. ScopedPointer <NamedPipe> newPipe (new NamedPipe());
  30049. if (newPipe->createNewPipe (pipeName))
  30050. {
  30051. const ScopedLock sl (pipeAndSocketLock);
  30052. pipeReceiveMessageTimeout = pipeReceiveMessageTimeoutMs;
  30053. initialiseWithPipe (newPipe.release());
  30054. return true;
  30055. }
  30056. return false;
  30057. }
  30058. void InterprocessConnection::disconnect()
  30059. {
  30060. if (socket != 0)
  30061. socket->close();
  30062. if (pipe != 0)
  30063. {
  30064. pipe->cancelPendingReads();
  30065. pipe->close();
  30066. }
  30067. stopThread (4000);
  30068. {
  30069. const ScopedLock sl (pipeAndSocketLock);
  30070. socket = 0;
  30071. pipe = 0;
  30072. }
  30073. connectionLostInt();
  30074. }
  30075. bool InterprocessConnection::isConnected() const
  30076. {
  30077. const ScopedLock sl (pipeAndSocketLock);
  30078. return ((socket != 0 && socket->isConnected())
  30079. || (pipe != 0 && pipe->isOpen()))
  30080. && isThreadRunning();
  30081. }
  30082. const String InterprocessConnection::getConnectedHostName() const
  30083. {
  30084. if (pipe != 0)
  30085. {
  30086. return "localhost";
  30087. }
  30088. else if (socket != 0)
  30089. {
  30090. if (! socket->isLocal())
  30091. return socket->getHostName();
  30092. return "localhost";
  30093. }
  30094. return String::empty;
  30095. }
  30096. bool InterprocessConnection::sendMessage (const MemoryBlock& message)
  30097. {
  30098. uint32 messageHeader[2];
  30099. messageHeader [0] = ByteOrder::swapIfBigEndian (magicMessageHeader);
  30100. messageHeader [1] = ByteOrder::swapIfBigEndian ((uint32) message.getSize());
  30101. MemoryBlock messageData (sizeof (messageHeader) + message.getSize());
  30102. messageData.copyFrom (messageHeader, 0, sizeof (messageHeader));
  30103. messageData.copyFrom (message.getData(), sizeof (messageHeader), message.getSize());
  30104. size_t bytesWritten = 0;
  30105. const ScopedLock sl (pipeAndSocketLock);
  30106. if (socket != 0)
  30107. {
  30108. bytesWritten = socket->write (messageData.getData(), (int) messageData.getSize());
  30109. }
  30110. else if (pipe != 0)
  30111. {
  30112. bytesWritten = pipe->write (messageData.getData(), (int) messageData.getSize());
  30113. }
  30114. if (bytesWritten < 0)
  30115. {
  30116. // error..
  30117. return false;
  30118. }
  30119. return (bytesWritten == messageData.getSize());
  30120. }
  30121. void InterprocessConnection::initialiseWithSocket (StreamingSocket* const socket_)
  30122. {
  30123. jassert (socket == 0);
  30124. socket = socket_;
  30125. connectionMadeInt();
  30126. startThread();
  30127. }
  30128. void InterprocessConnection::initialiseWithPipe (NamedPipe* const pipe_)
  30129. {
  30130. jassert (pipe == 0);
  30131. pipe = pipe_;
  30132. connectionMadeInt();
  30133. startThread();
  30134. }
  30135. const int messageMagicNumber = 0xb734128b;
  30136. void InterprocessConnection::handleMessage (const Message& message)
  30137. {
  30138. if (message.intParameter1 == messageMagicNumber)
  30139. {
  30140. switch (message.intParameter2)
  30141. {
  30142. case 0:
  30143. {
  30144. ScopedPointer <MemoryBlock> data (static_cast <MemoryBlock*> (message.pointerParameter));
  30145. messageReceived (*data);
  30146. break;
  30147. }
  30148. case 1:
  30149. connectionMade();
  30150. break;
  30151. case 2:
  30152. connectionLost();
  30153. break;
  30154. }
  30155. }
  30156. }
  30157. void InterprocessConnection::connectionMadeInt()
  30158. {
  30159. if (! callbackConnectionState)
  30160. {
  30161. callbackConnectionState = true;
  30162. if (useMessageThread)
  30163. postMessage (new Message (messageMagicNumber, 1, 0, 0));
  30164. else
  30165. connectionMade();
  30166. }
  30167. }
  30168. void InterprocessConnection::connectionLostInt()
  30169. {
  30170. if (callbackConnectionState)
  30171. {
  30172. callbackConnectionState = false;
  30173. if (useMessageThread)
  30174. postMessage (new Message (messageMagicNumber, 2, 0, 0));
  30175. else
  30176. connectionLost();
  30177. }
  30178. }
  30179. void InterprocessConnection::deliverDataInt (const MemoryBlock& data)
  30180. {
  30181. jassert (callbackConnectionState);
  30182. if (useMessageThread)
  30183. postMessage (new Message (messageMagicNumber, 0, 0, new MemoryBlock (data)));
  30184. else
  30185. messageReceived (data);
  30186. }
  30187. bool InterprocessConnection::readNextMessageInt()
  30188. {
  30189. const int maximumMessageSize = 1024 * 1024 * 10; // sanity check
  30190. uint32 messageHeader[2];
  30191. const int bytes = (socket != 0) ? socket->read (messageHeader, sizeof (messageHeader), true)
  30192. : pipe->read (messageHeader, sizeof (messageHeader), pipeReceiveMessageTimeout);
  30193. if (bytes == sizeof (messageHeader)
  30194. && ByteOrder::swapIfBigEndian (messageHeader[0]) == magicMessageHeader)
  30195. {
  30196. int bytesInMessage = (int) ByteOrder::swapIfBigEndian (messageHeader[1]);
  30197. if (bytesInMessage > 0 && bytesInMessage < maximumMessageSize)
  30198. {
  30199. MemoryBlock messageData (bytesInMessage, true);
  30200. int bytesRead = 0;
  30201. while (bytesInMessage > 0)
  30202. {
  30203. if (threadShouldExit())
  30204. return false;
  30205. const int numThisTime = jmin (bytesInMessage, 65536);
  30206. const int bytesIn = (socket != 0) ? socket->read (static_cast <char*> (messageData.getData()) + bytesRead, numThisTime, true)
  30207. : pipe->read (static_cast <char*> (messageData.getData()) + bytesRead, numThisTime, pipeReceiveMessageTimeout);
  30208. if (bytesIn <= 0)
  30209. break;
  30210. bytesRead += bytesIn;
  30211. bytesInMessage -= bytesIn;
  30212. }
  30213. if (bytesRead >= 0)
  30214. deliverDataInt (messageData);
  30215. }
  30216. }
  30217. else if (bytes < 0)
  30218. {
  30219. {
  30220. const ScopedLock sl (pipeAndSocketLock);
  30221. socket = 0;
  30222. }
  30223. connectionLostInt();
  30224. return false;
  30225. }
  30226. return true;
  30227. }
  30228. void InterprocessConnection::run()
  30229. {
  30230. while (! threadShouldExit())
  30231. {
  30232. if (socket != 0)
  30233. {
  30234. const int ready = socket->waitUntilReady (true, 0);
  30235. if (ready < 0)
  30236. {
  30237. {
  30238. const ScopedLock sl (pipeAndSocketLock);
  30239. socket = 0;
  30240. }
  30241. connectionLostInt();
  30242. break;
  30243. }
  30244. else if (ready > 0)
  30245. {
  30246. if (! readNextMessageInt())
  30247. break;
  30248. }
  30249. else
  30250. {
  30251. Thread::sleep (2);
  30252. }
  30253. }
  30254. else if (pipe != 0)
  30255. {
  30256. if (! pipe->isOpen())
  30257. {
  30258. {
  30259. const ScopedLock sl (pipeAndSocketLock);
  30260. pipe = 0;
  30261. }
  30262. connectionLostInt();
  30263. break;
  30264. }
  30265. else
  30266. {
  30267. if (! readNextMessageInt())
  30268. break;
  30269. }
  30270. }
  30271. else
  30272. {
  30273. break;
  30274. }
  30275. }
  30276. }
  30277. END_JUCE_NAMESPACE
  30278. /*** End of inlined file: juce_InterprocessConnection.cpp ***/
  30279. /*** Start of inlined file: juce_InterprocessConnectionServer.cpp ***/
  30280. BEGIN_JUCE_NAMESPACE
  30281. InterprocessConnectionServer::InterprocessConnectionServer()
  30282. : Thread ("Juce IPC server")
  30283. {
  30284. }
  30285. InterprocessConnectionServer::~InterprocessConnectionServer()
  30286. {
  30287. stop();
  30288. }
  30289. bool InterprocessConnectionServer::beginWaitingForSocket (const int portNumber)
  30290. {
  30291. stop();
  30292. socket = new StreamingSocket();
  30293. if (socket->createListener (portNumber))
  30294. {
  30295. startThread();
  30296. return true;
  30297. }
  30298. socket = 0;
  30299. return false;
  30300. }
  30301. void InterprocessConnectionServer::stop()
  30302. {
  30303. signalThreadShouldExit();
  30304. if (socket != 0)
  30305. socket->close();
  30306. stopThread (4000);
  30307. socket = 0;
  30308. }
  30309. void InterprocessConnectionServer::run()
  30310. {
  30311. while ((! threadShouldExit()) && socket != 0)
  30312. {
  30313. ScopedPointer <StreamingSocket> clientSocket (socket->waitForNextConnection());
  30314. if (clientSocket != 0)
  30315. {
  30316. InterprocessConnection* newConnection = createConnectionObject();
  30317. if (newConnection != 0)
  30318. newConnection->initialiseWithSocket (clientSocket.release());
  30319. }
  30320. }
  30321. }
  30322. END_JUCE_NAMESPACE
  30323. /*** End of inlined file: juce_InterprocessConnectionServer.cpp ***/
  30324. /*** Start of inlined file: juce_Message.cpp ***/
  30325. BEGIN_JUCE_NAMESPACE
  30326. Message::Message() throw()
  30327. : intParameter1 (0),
  30328. intParameter2 (0),
  30329. intParameter3 (0),
  30330. pointerParameter (0)
  30331. {
  30332. }
  30333. Message::Message (const int intParameter1_,
  30334. const int intParameter2_,
  30335. const int intParameter3_,
  30336. void* const pointerParameter_) throw()
  30337. : intParameter1 (intParameter1_),
  30338. intParameter2 (intParameter2_),
  30339. intParameter3 (intParameter3_),
  30340. pointerParameter (pointerParameter_)
  30341. {
  30342. }
  30343. Message::~Message() throw()
  30344. {
  30345. }
  30346. END_JUCE_NAMESPACE
  30347. /*** End of inlined file: juce_Message.cpp ***/
  30348. /*** Start of inlined file: juce_MessageListener.cpp ***/
  30349. BEGIN_JUCE_NAMESPACE
  30350. MessageListener::MessageListener() throw()
  30351. {
  30352. // are you trying to create a messagelistener before or after juce has been intialised??
  30353. jassert (MessageManager::instance != 0);
  30354. if (MessageManager::instance != 0)
  30355. MessageManager::instance->messageListeners.add (this);
  30356. }
  30357. MessageListener::~MessageListener()
  30358. {
  30359. if (MessageManager::instance != 0)
  30360. MessageManager::instance->messageListeners.removeValue (this);
  30361. }
  30362. void MessageListener::postMessage (Message* const message) const throw()
  30363. {
  30364. message->messageRecipient = const_cast <MessageListener*> (this);
  30365. if (MessageManager::instance == 0)
  30366. MessageManager::getInstance();
  30367. MessageManager::instance->postMessageToQueue (message);
  30368. }
  30369. bool MessageListener::isValidMessageListener() const throw()
  30370. {
  30371. return (MessageManager::instance != 0)
  30372. && MessageManager::instance->messageListeners.contains (this);
  30373. }
  30374. END_JUCE_NAMESPACE
  30375. /*** End of inlined file: juce_MessageListener.cpp ***/
  30376. /*** Start of inlined file: juce_MessageManager.cpp ***/
  30377. BEGIN_JUCE_NAMESPACE
  30378. // platform-specific functions..
  30379. bool juce_dispatchNextMessageOnSystemQueue (bool returnIfNoPendingMessages);
  30380. bool juce_postMessageToSystemQueue (void* message);
  30381. MessageManager* MessageManager::instance = 0;
  30382. static const int quitMessageId = 0xfffff321;
  30383. MessageManager::MessageManager() throw()
  30384. : quitMessagePosted (false),
  30385. quitMessageReceived (false),
  30386. threadWithLock (0)
  30387. {
  30388. messageThreadId = Thread::getCurrentThreadId();
  30389. }
  30390. MessageManager::~MessageManager() throw()
  30391. {
  30392. broadcastListeners = 0;
  30393. doPlatformSpecificShutdown();
  30394. jassert (instance == this);
  30395. instance = 0; // do this last in case this instance is still needed by doPlatformSpecificShutdown()
  30396. }
  30397. MessageManager* MessageManager::getInstance() throw()
  30398. {
  30399. if (instance == 0)
  30400. {
  30401. instance = new MessageManager();
  30402. doPlatformSpecificInitialisation();
  30403. }
  30404. return instance;
  30405. }
  30406. void MessageManager::postMessageToQueue (Message* const message)
  30407. {
  30408. if (quitMessagePosted || ! juce_postMessageToSystemQueue (message))
  30409. delete message;
  30410. }
  30411. CallbackMessage::CallbackMessage() throw() {}
  30412. CallbackMessage::~CallbackMessage() throw() {}
  30413. void CallbackMessage::post()
  30414. {
  30415. if (MessageManager::instance != 0)
  30416. MessageManager::instance->postCallbackMessage (this);
  30417. }
  30418. void MessageManager::postCallbackMessage (Message* const message)
  30419. {
  30420. message->messageRecipient = 0;
  30421. postMessageToQueue (message);
  30422. }
  30423. // not for public use..
  30424. void MessageManager::deliverMessage (void* const message)
  30425. {
  30426. const ScopedPointer <Message> m (static_cast <Message*> (message));
  30427. MessageListener* const recipient = m->messageRecipient;
  30428. JUCE_TRY
  30429. {
  30430. if (messageListeners.contains (recipient))
  30431. {
  30432. recipient->handleMessage (*m);
  30433. }
  30434. else if (recipient == 0)
  30435. {
  30436. if (m->intParameter1 == quitMessageId)
  30437. {
  30438. quitMessageReceived = true;
  30439. }
  30440. else
  30441. {
  30442. CallbackMessage* const cm = dynamic_cast <CallbackMessage*> (static_cast <Message*> (m));
  30443. if (cm != 0)
  30444. cm->messageCallback();
  30445. }
  30446. }
  30447. }
  30448. JUCE_CATCH_EXCEPTION
  30449. }
  30450. #if ! (JUCE_MAC || JUCE_IPHONE)
  30451. void MessageManager::runDispatchLoop()
  30452. {
  30453. jassert (isThisTheMessageThread()); // must only be called by the message thread
  30454. runDispatchLoopUntil (-1);
  30455. }
  30456. void MessageManager::stopDispatchLoop()
  30457. {
  30458. Message* const m = new Message (quitMessageId, 0, 0, 0);
  30459. m->messageRecipient = 0;
  30460. postMessageToQueue (m);
  30461. quitMessagePosted = true;
  30462. }
  30463. bool MessageManager::runDispatchLoopUntil (int millisecondsToRunFor)
  30464. {
  30465. jassert (isThisTheMessageThread()); // must only be called by the message thread
  30466. const int64 endTime = Time::currentTimeMillis() + millisecondsToRunFor;
  30467. while ((millisecondsToRunFor < 0 || endTime > Time::currentTimeMillis())
  30468. && ! quitMessageReceived)
  30469. {
  30470. JUCE_TRY
  30471. {
  30472. if (! juce_dispatchNextMessageOnSystemQueue (millisecondsToRunFor >= 0))
  30473. {
  30474. const int msToWait = (int) (endTime - Time::currentTimeMillis());
  30475. if (msToWait > 0)
  30476. Thread::sleep (jmin (5, msToWait));
  30477. }
  30478. }
  30479. JUCE_CATCH_EXCEPTION
  30480. }
  30481. return ! quitMessageReceived;
  30482. }
  30483. #endif
  30484. void MessageManager::deliverBroadcastMessage (const String& value)
  30485. {
  30486. if (broadcastListeners != 0)
  30487. broadcastListeners->sendActionMessage (value);
  30488. }
  30489. void MessageManager::registerBroadcastListener (ActionListener* const listener) throw()
  30490. {
  30491. if (broadcastListeners == 0)
  30492. broadcastListeners = new ActionListenerList();
  30493. broadcastListeners->addActionListener (listener);
  30494. }
  30495. void MessageManager::deregisterBroadcastListener (ActionListener* const listener) throw()
  30496. {
  30497. if (broadcastListeners != 0)
  30498. broadcastListeners->removeActionListener (listener);
  30499. }
  30500. bool MessageManager::isThisTheMessageThread() const throw()
  30501. {
  30502. return Thread::getCurrentThreadId() == messageThreadId;
  30503. }
  30504. void MessageManager::setCurrentThreadAsMessageThread()
  30505. {
  30506. if (messageThreadId != Thread::getCurrentThreadId())
  30507. {
  30508. messageThreadId = Thread::getCurrentThreadId();
  30509. // This is needed on windows to make sure the message window is created by this thread
  30510. doPlatformSpecificShutdown();
  30511. doPlatformSpecificInitialisation();
  30512. }
  30513. }
  30514. bool MessageManager::currentThreadHasLockedMessageManager() const throw()
  30515. {
  30516. const Thread::ThreadID thisThread = Thread::getCurrentThreadId();
  30517. return thisThread == messageThreadId || thisThread == threadWithLock;
  30518. }
  30519. /* The only safe way to lock the message thread while another thread does
  30520. some work is by posting a special message, whose purpose is to tie up the event
  30521. loop until the other thread has finished its business.
  30522. Any other approach can get horribly deadlocked if the OS uses its own hidden locks which
  30523. get locked before making an event callback, because if the same OS lock gets indirectly
  30524. accessed from another thread inside a MM lock, you're screwed. (this is exactly what happens
  30525. in Cocoa).
  30526. */
  30527. class MessageManagerLock::SharedEvents : public ReferenceCountedObject
  30528. {
  30529. public:
  30530. SharedEvents() {}
  30531. ~SharedEvents() {}
  30532. /* This class just holds a couple of events to communicate between the BlockingMessage
  30533. and the MessageManagerLock. Because both of these objects may be deleted at any time,
  30534. this shared data must be kept in a separate, ref-counted container. */
  30535. WaitableEvent lockedEvent, releaseEvent;
  30536. private:
  30537. SharedEvents (const SharedEvents&);
  30538. SharedEvents& operator= (const SharedEvents&);
  30539. };
  30540. class MessageManagerLock::BlockingMessage : public CallbackMessage
  30541. {
  30542. public:
  30543. BlockingMessage (MessageManagerLock::SharedEvents* const events_) : events (events_) {}
  30544. ~BlockingMessage() throw() {}
  30545. void messageCallback()
  30546. {
  30547. events->lockedEvent.signal();
  30548. events->releaseEvent.wait();
  30549. }
  30550. juce_UseDebuggingNewOperator
  30551. private:
  30552. ReferenceCountedObjectPtr <MessageManagerLock::SharedEvents> events;
  30553. BlockingMessage (const BlockingMessage&);
  30554. BlockingMessage& operator= (const BlockingMessage&);
  30555. };
  30556. MessageManagerLock::MessageManagerLock (Thread* const threadToCheck) throw()
  30557. : sharedEvents (0),
  30558. locked (false)
  30559. {
  30560. init (threadToCheck, 0);
  30561. }
  30562. MessageManagerLock::MessageManagerLock (ThreadPoolJob* const jobToCheckForExitSignal) throw()
  30563. : sharedEvents (0),
  30564. locked (false)
  30565. {
  30566. init (0, jobToCheckForExitSignal);
  30567. }
  30568. void MessageManagerLock::init (Thread* const threadToCheck, ThreadPoolJob* const job) throw()
  30569. {
  30570. if (MessageManager::instance != 0)
  30571. {
  30572. if (MessageManager::instance->currentThreadHasLockedMessageManager())
  30573. {
  30574. locked = true; // either we're on the message thread, or this is a re-entrant call.
  30575. }
  30576. else
  30577. {
  30578. if (threadToCheck == 0 && job == 0)
  30579. {
  30580. MessageManager::instance->lockingLock.enter();
  30581. }
  30582. else
  30583. {
  30584. while (! MessageManager::instance->lockingLock.tryEnter())
  30585. {
  30586. if ((threadToCheck != 0 && threadToCheck->threadShouldExit())
  30587. || (job != 0 && job->shouldExit()))
  30588. return;
  30589. Thread::sleep (1);
  30590. }
  30591. }
  30592. sharedEvents = new SharedEvents();
  30593. sharedEvents->incReferenceCount();
  30594. (new BlockingMessage (sharedEvents))->post();
  30595. while (! sharedEvents->lockedEvent.wait (50))
  30596. {
  30597. if ((threadToCheck != 0 && threadToCheck->threadShouldExit())
  30598. || (job != 0 && job->shouldExit()))
  30599. {
  30600. sharedEvents->releaseEvent.signal();
  30601. sharedEvents->decReferenceCount();
  30602. sharedEvents = 0;
  30603. MessageManager::instance->lockingLock.exit();
  30604. return;
  30605. }
  30606. }
  30607. jassert (MessageManager::instance->threadWithLock == 0);
  30608. MessageManager::instance->threadWithLock = Thread::getCurrentThreadId();
  30609. locked = true;
  30610. }
  30611. }
  30612. }
  30613. MessageManagerLock::~MessageManagerLock() throw()
  30614. {
  30615. if (sharedEvents != 0)
  30616. {
  30617. jassert (MessageManager::instance == 0 || MessageManager::instance->currentThreadHasLockedMessageManager());
  30618. sharedEvents->releaseEvent.signal();
  30619. sharedEvents->decReferenceCount();
  30620. if (MessageManager::instance != 0)
  30621. {
  30622. MessageManager::instance->threadWithLock = 0;
  30623. MessageManager::instance->lockingLock.exit();
  30624. }
  30625. }
  30626. }
  30627. END_JUCE_NAMESPACE
  30628. /*** End of inlined file: juce_MessageManager.cpp ***/
  30629. /*** Start of inlined file: juce_MultiTimer.cpp ***/
  30630. BEGIN_JUCE_NAMESPACE
  30631. class MultiTimer::MultiTimerCallback : public Timer
  30632. {
  30633. public:
  30634. MultiTimerCallback (const int timerId_, MultiTimer& owner_)
  30635. : timerId (timerId_),
  30636. owner (owner_)
  30637. {
  30638. }
  30639. ~MultiTimerCallback()
  30640. {
  30641. }
  30642. void timerCallback()
  30643. {
  30644. owner.timerCallback (timerId);
  30645. }
  30646. const int timerId;
  30647. private:
  30648. MultiTimer& owner;
  30649. };
  30650. MultiTimer::MultiTimer() throw()
  30651. {
  30652. }
  30653. MultiTimer::MultiTimer (const MultiTimer&) throw()
  30654. {
  30655. }
  30656. MultiTimer::~MultiTimer()
  30657. {
  30658. const ScopedLock sl (timerListLock);
  30659. timers.clear();
  30660. }
  30661. void MultiTimer::startTimer (const int timerId, const int intervalInMilliseconds) throw()
  30662. {
  30663. const ScopedLock sl (timerListLock);
  30664. for (int i = timers.size(); --i >= 0;)
  30665. {
  30666. MultiTimerCallback* const t = timers.getUnchecked(i);
  30667. if (t->timerId == timerId)
  30668. {
  30669. t->startTimer (intervalInMilliseconds);
  30670. return;
  30671. }
  30672. }
  30673. MultiTimerCallback* const newTimer = new MultiTimerCallback (timerId, *this);
  30674. timers.add (newTimer);
  30675. newTimer->startTimer (intervalInMilliseconds);
  30676. }
  30677. void MultiTimer::stopTimer (const int timerId) throw()
  30678. {
  30679. const ScopedLock sl (timerListLock);
  30680. for (int i = timers.size(); --i >= 0;)
  30681. {
  30682. MultiTimerCallback* const t = timers.getUnchecked(i);
  30683. if (t->timerId == timerId)
  30684. t->stopTimer();
  30685. }
  30686. }
  30687. bool MultiTimer::isTimerRunning (const int timerId) const throw()
  30688. {
  30689. const ScopedLock sl (timerListLock);
  30690. for (int i = timers.size(); --i >= 0;)
  30691. {
  30692. const MultiTimerCallback* const t = timers.getUnchecked(i);
  30693. if (t->timerId == timerId)
  30694. return t->isTimerRunning();
  30695. }
  30696. return false;
  30697. }
  30698. int MultiTimer::getTimerInterval (const int timerId) const throw()
  30699. {
  30700. const ScopedLock sl (timerListLock);
  30701. for (int i = timers.size(); --i >= 0;)
  30702. {
  30703. const MultiTimerCallback* const t = timers.getUnchecked(i);
  30704. if (t->timerId == timerId)
  30705. return t->getTimerInterval();
  30706. }
  30707. return 0;
  30708. }
  30709. END_JUCE_NAMESPACE
  30710. /*** End of inlined file: juce_MultiTimer.cpp ***/
  30711. /*** Start of inlined file: juce_Timer.cpp ***/
  30712. BEGIN_JUCE_NAMESPACE
  30713. class InternalTimerThread : private Thread,
  30714. private MessageListener,
  30715. private DeletedAtShutdown,
  30716. private AsyncUpdater
  30717. {
  30718. public:
  30719. InternalTimerThread()
  30720. : Thread ("Juce Timer"),
  30721. firstTimer (0),
  30722. callbackNeeded (0)
  30723. {
  30724. triggerAsyncUpdate();
  30725. }
  30726. ~InternalTimerThread() throw()
  30727. {
  30728. stopThread (4000);
  30729. jassert (instance == this || instance == 0);
  30730. if (instance == this)
  30731. instance = 0;
  30732. }
  30733. void run()
  30734. {
  30735. uint32 lastTime = Time::getMillisecondCounter();
  30736. while (! threadShouldExit())
  30737. {
  30738. const uint32 now = Time::getMillisecondCounter();
  30739. if (now <= lastTime)
  30740. {
  30741. wait (2);
  30742. continue;
  30743. }
  30744. const int elapsed = now - lastTime;
  30745. lastTime = now;
  30746. int timeUntilFirstTimer = 1000;
  30747. {
  30748. const ScopedLock sl (lock);
  30749. decrementAllCounters (elapsed);
  30750. if (firstTimer != 0)
  30751. timeUntilFirstTimer = firstTimer->countdownMs;
  30752. }
  30753. if (timeUntilFirstTimer <= 0)
  30754. {
  30755. /* If we managed to set the atomic boolean to true then send a message, this is needed
  30756. as a memory barrier so the message won't be sent before callbackNeeded is set to true,
  30757. but if it fails it means the message-thread changed the value from under us so at least
  30758. some processing is happenening and we can just loop around and try again
  30759. */
  30760. if (callbackNeeded.compareAndSetBool (1, 0))
  30761. {
  30762. postMessage (new Message());
  30763. /* Sometimes our message can get discarded by the OS (e.g. when running as an RTAS
  30764. when the app has a modal loop), so this is how long to wait before assuming the
  30765. message has been lost and trying again.
  30766. */
  30767. const uint32 messageDeliveryTimeout = now + 2000;
  30768. while (callbackNeeded.get() != 0)
  30769. {
  30770. wait (4);
  30771. if (threadShouldExit())
  30772. return;
  30773. if (Time::getMillisecondCounter() > messageDeliveryTimeout)
  30774. break;
  30775. }
  30776. }
  30777. }
  30778. else
  30779. {
  30780. // don't wait for too long because running this loop also helps keep the
  30781. // Time::getApproximateMillisecondTimer value stay up-to-date
  30782. wait (jlimit (1, 50, timeUntilFirstTimer));
  30783. }
  30784. }
  30785. }
  30786. void callTimers()
  30787. {
  30788. const ScopedLock sl (lock);
  30789. while (firstTimer != 0 && firstTimer->countdownMs <= 0)
  30790. {
  30791. Timer* const t = firstTimer;
  30792. t->countdownMs = t->periodMs;
  30793. removeTimer (t);
  30794. addTimer (t);
  30795. const ScopedUnlock ul (lock);
  30796. JUCE_TRY
  30797. {
  30798. t->timerCallback();
  30799. }
  30800. JUCE_CATCH_EXCEPTION
  30801. }
  30802. /* This is needed as a memory barrier to make sure all processing of current timers is done
  30803. before the boolean is set. This set should never fail since if it was false in the first place,
  30804. we wouldn't get a message (so it can't be changed from false to true from under us), and if we
  30805. get a message then the value is true and the other thread can only set it to true again and
  30806. we will get another callback to set it to false.
  30807. */
  30808. callbackNeeded.set (0);
  30809. }
  30810. void handleMessage (const Message&)
  30811. {
  30812. callTimers();
  30813. }
  30814. void callTimersSynchronously()
  30815. {
  30816. if (! isThreadRunning())
  30817. {
  30818. // (This is relied on by some plugins in cases where the MM has
  30819. // had to restart and the async callback never started)
  30820. cancelPendingUpdate();
  30821. triggerAsyncUpdate();
  30822. }
  30823. callTimers();
  30824. }
  30825. static void callAnyTimersSynchronously()
  30826. {
  30827. if (InternalTimerThread::instance != 0)
  30828. InternalTimerThread::instance->callTimersSynchronously();
  30829. }
  30830. static inline void add (Timer* const tim) throw()
  30831. {
  30832. if (instance == 0)
  30833. instance = new InternalTimerThread();
  30834. const ScopedLock sl (instance->lock);
  30835. instance->addTimer (tim);
  30836. }
  30837. static inline void remove (Timer* const tim) throw()
  30838. {
  30839. if (instance != 0)
  30840. {
  30841. const ScopedLock sl (instance->lock);
  30842. instance->removeTimer (tim);
  30843. }
  30844. }
  30845. static inline void resetCounter (Timer* const tim,
  30846. const int newCounter) throw()
  30847. {
  30848. if (instance != 0)
  30849. {
  30850. tim->countdownMs = newCounter;
  30851. tim->periodMs = newCounter;
  30852. if ((tim->next != 0 && tim->next->countdownMs < tim->countdownMs)
  30853. || (tim->previous != 0 && tim->previous->countdownMs > tim->countdownMs))
  30854. {
  30855. const ScopedLock sl (instance->lock);
  30856. instance->removeTimer (tim);
  30857. instance->addTimer (tim);
  30858. }
  30859. }
  30860. }
  30861. private:
  30862. friend class Timer;
  30863. static InternalTimerThread* instance;
  30864. static CriticalSection lock;
  30865. Timer* volatile firstTimer;
  30866. Atomic <int> callbackNeeded;
  30867. void addTimer (Timer* const t) throw()
  30868. {
  30869. #if JUCE_DEBUG
  30870. Timer* tt = firstTimer;
  30871. while (tt != 0)
  30872. {
  30873. // trying to add a timer that's already here - shouldn't get to this point,
  30874. // so if you get this assertion, let me know!
  30875. jassert (tt != t);
  30876. tt = tt->next;
  30877. }
  30878. jassert (t->previous == 0 && t->next == 0);
  30879. #endif
  30880. Timer* i = firstTimer;
  30881. if (i == 0 || i->countdownMs > t->countdownMs)
  30882. {
  30883. t->next = firstTimer;
  30884. firstTimer = t;
  30885. }
  30886. else
  30887. {
  30888. while (i->next != 0 && i->next->countdownMs <= t->countdownMs)
  30889. i = i->next;
  30890. jassert (i != 0);
  30891. t->next = i->next;
  30892. t->previous = i;
  30893. i->next = t;
  30894. }
  30895. if (t->next != 0)
  30896. t->next->previous = t;
  30897. jassert ((t->next == 0 || t->next->countdownMs >= t->countdownMs)
  30898. && (t->previous == 0 || t->previous->countdownMs <= t->countdownMs));
  30899. notify();
  30900. }
  30901. void removeTimer (Timer* const t) throw()
  30902. {
  30903. #if JUCE_DEBUG
  30904. Timer* tt = firstTimer;
  30905. bool found = false;
  30906. while (tt != 0)
  30907. {
  30908. if (tt == t)
  30909. {
  30910. found = true;
  30911. break;
  30912. }
  30913. tt = tt->next;
  30914. }
  30915. // trying to remove a timer that's not here - shouldn't get to this point,
  30916. // so if you get this assertion, let me know!
  30917. jassert (found);
  30918. #endif
  30919. if (t->previous != 0)
  30920. {
  30921. jassert (firstTimer != t);
  30922. t->previous->next = t->next;
  30923. }
  30924. else
  30925. {
  30926. jassert (firstTimer == t);
  30927. firstTimer = t->next;
  30928. }
  30929. if (t->next != 0)
  30930. t->next->previous = t->previous;
  30931. t->next = 0;
  30932. t->previous = 0;
  30933. }
  30934. void decrementAllCounters (const int numMillisecs) const
  30935. {
  30936. Timer* t = firstTimer;
  30937. while (t != 0)
  30938. {
  30939. t->countdownMs -= numMillisecs;
  30940. t = t->next;
  30941. }
  30942. }
  30943. void handleAsyncUpdate()
  30944. {
  30945. startThread (7);
  30946. }
  30947. InternalTimerThread (const InternalTimerThread&);
  30948. InternalTimerThread& operator= (const InternalTimerThread&);
  30949. };
  30950. InternalTimerThread* InternalTimerThread::instance = 0;
  30951. CriticalSection InternalTimerThread::lock;
  30952. void juce_callAnyTimersSynchronously()
  30953. {
  30954. InternalTimerThread::callAnyTimersSynchronously();
  30955. }
  30956. #if JUCE_DEBUG
  30957. static SortedSet <Timer*> activeTimers;
  30958. #endif
  30959. Timer::Timer() throw()
  30960. : countdownMs (0),
  30961. periodMs (0),
  30962. previous (0),
  30963. next (0)
  30964. {
  30965. #if JUCE_DEBUG
  30966. activeTimers.add (this);
  30967. #endif
  30968. }
  30969. Timer::Timer (const Timer&) throw()
  30970. : countdownMs (0),
  30971. periodMs (0),
  30972. previous (0),
  30973. next (0)
  30974. {
  30975. #if JUCE_DEBUG
  30976. activeTimers.add (this);
  30977. #endif
  30978. }
  30979. Timer::~Timer()
  30980. {
  30981. stopTimer();
  30982. #if JUCE_DEBUG
  30983. activeTimers.removeValue (this);
  30984. #endif
  30985. }
  30986. void Timer::startTimer (const int interval) throw()
  30987. {
  30988. const ScopedLock sl (InternalTimerThread::lock);
  30989. #if JUCE_DEBUG
  30990. // this isn't a valid object! Your timer might be a dangling pointer or something..
  30991. jassert (activeTimers.contains (this));
  30992. #endif
  30993. if (periodMs == 0)
  30994. {
  30995. countdownMs = interval;
  30996. periodMs = jmax (1, interval);
  30997. InternalTimerThread::add (this);
  30998. }
  30999. else
  31000. {
  31001. InternalTimerThread::resetCounter (this, interval);
  31002. }
  31003. }
  31004. void Timer::stopTimer() throw()
  31005. {
  31006. const ScopedLock sl (InternalTimerThread::lock);
  31007. #if JUCE_DEBUG
  31008. // this isn't a valid object! Your timer might be a dangling pointer or something..
  31009. jassert (activeTimers.contains (this));
  31010. #endif
  31011. if (periodMs > 0)
  31012. {
  31013. InternalTimerThread::remove (this);
  31014. periodMs = 0;
  31015. }
  31016. }
  31017. END_JUCE_NAMESPACE
  31018. /*** End of inlined file: juce_Timer.cpp ***/
  31019. #endif
  31020. #if JUCE_BUILD_GUI
  31021. /*** Start of inlined file: juce_Component.cpp ***/
  31022. BEGIN_JUCE_NAMESPACE
  31023. Component* Component::currentlyFocusedComponent = 0;
  31024. static Array <Component*> modalComponentStack, modalComponentReturnValueKeys;
  31025. static Array <int> modalReturnValues;
  31026. enum ComponentMessageNumbers
  31027. {
  31028. customCommandMessage = 0x7fff0001,
  31029. exitModalStateMessage = 0x7fff0002
  31030. };
  31031. #define checkMessageManagerIsLocked jassert (MessageManager::getInstance()->currentThreadHasLockedMessageManager());
  31032. static uint32 nextComponentUID = 0;
  31033. Component::Component()
  31034. : parentComponent_ (0),
  31035. componentUID (++nextComponentUID),
  31036. numDeepMouseListeners (0),
  31037. lookAndFeel_ (0),
  31038. effect_ (0),
  31039. bufferedImage_ (0),
  31040. mouseListeners_ (0),
  31041. keyListeners_ (0),
  31042. componentFlags_ (0)
  31043. {
  31044. }
  31045. Component::Component (const String& name)
  31046. : componentName_ (name),
  31047. parentComponent_ (0),
  31048. componentUID (++nextComponentUID),
  31049. numDeepMouseListeners (0),
  31050. lookAndFeel_ (0),
  31051. effect_ (0),
  31052. bufferedImage_ (0),
  31053. mouseListeners_ (0),
  31054. keyListeners_ (0),
  31055. componentFlags_ (0)
  31056. {
  31057. }
  31058. Component::~Component()
  31059. {
  31060. componentListeners.call (&ComponentListener::componentBeingDeleted, *this);
  31061. if (parentComponent_ != 0)
  31062. {
  31063. parentComponent_->removeChildComponent (this);
  31064. }
  31065. else if ((currentlyFocusedComponent == this)
  31066. || isParentOf (currentlyFocusedComponent))
  31067. {
  31068. giveAwayFocus();
  31069. }
  31070. if (flags.hasHeavyweightPeerFlag)
  31071. removeFromDesktop();
  31072. modalComponentStack.removeValue (this);
  31073. for (int i = childComponentList_.size(); --i >= 0;)
  31074. childComponentList_.getUnchecked(i)->parentComponent_ = 0;
  31075. delete bufferedImage_;
  31076. delete mouseListeners_;
  31077. delete keyListeners_;
  31078. }
  31079. void Component::setName (const String& name)
  31080. {
  31081. // if component methods are being called from threads other than the message
  31082. // thread, you'll need to use a MessageManagerLock object to make sure it's thread-safe.
  31083. checkMessageManagerIsLocked
  31084. if (componentName_ != name)
  31085. {
  31086. componentName_ = name;
  31087. if (flags.hasHeavyweightPeerFlag)
  31088. {
  31089. ComponentPeer* const peer = getPeer();
  31090. jassert (peer != 0);
  31091. if (peer != 0)
  31092. peer->setTitle (name);
  31093. }
  31094. BailOutChecker checker (this);
  31095. componentListeners.callChecked (checker, &ComponentListener::componentNameChanged, *this);
  31096. }
  31097. }
  31098. void Component::setVisible (bool shouldBeVisible)
  31099. {
  31100. if (flags.visibleFlag != shouldBeVisible)
  31101. {
  31102. // if component methods are being called from threads other than the message
  31103. // thread, you'll need to use a MessageManagerLock object to make sure it's thread-safe.
  31104. checkMessageManagerIsLocked
  31105. SafePointer<Component> safePointer (this);
  31106. flags.visibleFlag = shouldBeVisible;
  31107. internalRepaint (0, 0, getWidth(), getHeight());
  31108. sendFakeMouseMove();
  31109. if (! shouldBeVisible)
  31110. {
  31111. if (currentlyFocusedComponent == this
  31112. || isParentOf (currentlyFocusedComponent))
  31113. {
  31114. if (parentComponent_ != 0)
  31115. parentComponent_->grabKeyboardFocus();
  31116. else
  31117. giveAwayFocus();
  31118. }
  31119. }
  31120. if (safePointer != 0)
  31121. {
  31122. sendVisibilityChangeMessage();
  31123. if (safePointer != 0 && flags.hasHeavyweightPeerFlag)
  31124. {
  31125. ComponentPeer* const peer = getPeer();
  31126. jassert (peer != 0);
  31127. if (peer != 0)
  31128. {
  31129. peer->setVisible (shouldBeVisible);
  31130. internalHierarchyChanged();
  31131. }
  31132. }
  31133. }
  31134. }
  31135. }
  31136. void Component::visibilityChanged()
  31137. {
  31138. }
  31139. void Component::sendVisibilityChangeMessage()
  31140. {
  31141. BailOutChecker checker (this);
  31142. visibilityChanged();
  31143. if (! checker.shouldBailOut())
  31144. componentListeners.callChecked (checker, &ComponentListener::componentVisibilityChanged, *this);
  31145. }
  31146. bool Component::isShowing() const
  31147. {
  31148. if (flags.visibleFlag)
  31149. {
  31150. if (parentComponent_ != 0)
  31151. {
  31152. return parentComponent_->isShowing();
  31153. }
  31154. else
  31155. {
  31156. const ComponentPeer* const peer = getPeer();
  31157. return peer != 0 && ! peer->isMinimised();
  31158. }
  31159. }
  31160. return false;
  31161. }
  31162. class FadeOutProxyComponent : public Component,
  31163. public Timer
  31164. {
  31165. public:
  31166. FadeOutProxyComponent (Component* comp,
  31167. const int fadeLengthMs,
  31168. const int deltaXToMove,
  31169. const int deltaYToMove,
  31170. const float scaleFactorAtEnd)
  31171. : lastTime (0),
  31172. alpha (1.0f),
  31173. scale (1.0f)
  31174. {
  31175. image = comp->createComponentSnapshot (comp->getLocalBounds());
  31176. setBounds (comp->getBounds());
  31177. comp->getParentComponent()->addAndMakeVisible (this);
  31178. toBehind (comp);
  31179. alphaChangePerMs = -1.0f / (float)fadeLengthMs;
  31180. centreX = comp->getX() + comp->getWidth() * 0.5f;
  31181. xChangePerMs = deltaXToMove / (float)fadeLengthMs;
  31182. centreY = comp->getY() + comp->getHeight() * 0.5f;
  31183. yChangePerMs = deltaYToMove / (float)fadeLengthMs;
  31184. scaleChangePerMs = (scaleFactorAtEnd - 1.0f) / (float)fadeLengthMs;
  31185. setInterceptsMouseClicks (false, false);
  31186. // 30 fps is enough for a fade, but we need a higher rate if it's moving as well..
  31187. startTimer (1000 / ((deltaXToMove == 0 && deltaYToMove == 0) ? 30 : 50));
  31188. }
  31189. ~FadeOutProxyComponent()
  31190. {
  31191. delete image;
  31192. }
  31193. void paint (Graphics& g)
  31194. {
  31195. g.setOpacity (alpha);
  31196. g.drawImage (image,
  31197. 0, 0, getWidth(), getHeight(),
  31198. 0, 0, image->getWidth(), image->getHeight());
  31199. }
  31200. void timerCallback()
  31201. {
  31202. const uint32 now = Time::getMillisecondCounter();
  31203. if (lastTime == 0)
  31204. lastTime = now;
  31205. const int msPassed = (now > lastTime) ? now - lastTime : 0;
  31206. lastTime = now;
  31207. alpha += alphaChangePerMs * msPassed;
  31208. if (alpha > 0)
  31209. {
  31210. if (xChangePerMs != 0.0f || yChangePerMs != 0.0f || scaleChangePerMs != 0.0f)
  31211. {
  31212. centreX += xChangePerMs * msPassed;
  31213. centreY += yChangePerMs * msPassed;
  31214. scale += scaleChangePerMs * msPassed;
  31215. const int w = roundToInt (image->getWidth() * scale);
  31216. const int h = roundToInt (image->getHeight() * scale);
  31217. setBounds (roundToInt (centreX) - w / 2,
  31218. roundToInt (centreY) - h / 2,
  31219. w, h);
  31220. }
  31221. repaint();
  31222. }
  31223. else
  31224. {
  31225. delete this;
  31226. }
  31227. }
  31228. juce_UseDebuggingNewOperator
  31229. private:
  31230. Image* image;
  31231. uint32 lastTime;
  31232. float alpha, alphaChangePerMs;
  31233. float centreX, xChangePerMs;
  31234. float centreY, yChangePerMs;
  31235. float scale, scaleChangePerMs;
  31236. FadeOutProxyComponent (const FadeOutProxyComponent&);
  31237. FadeOutProxyComponent& operator= (const FadeOutProxyComponent&);
  31238. };
  31239. void Component::fadeOutComponent (const int millisecondsToFade,
  31240. const int deltaXToMove,
  31241. const int deltaYToMove,
  31242. const float scaleFactorAtEnd)
  31243. {
  31244. //xxx won't work for comps without parents
  31245. if (isShowing() && millisecondsToFade > 0)
  31246. new FadeOutProxyComponent (this, millisecondsToFade,
  31247. deltaXToMove, deltaYToMove, scaleFactorAtEnd);
  31248. setVisible (false);
  31249. }
  31250. bool Component::isValidComponent() const
  31251. {
  31252. return (this != 0) && isValidMessageListener();
  31253. }
  31254. void* Component::getWindowHandle() const
  31255. {
  31256. const ComponentPeer* const peer = getPeer();
  31257. if (peer != 0)
  31258. return peer->getNativeHandle();
  31259. return 0;
  31260. }
  31261. void Component::addToDesktop (int styleWanted, void* nativeWindowToAttachTo)
  31262. {
  31263. // if component methods are being called from threads other than the message
  31264. // thread, you'll need to use a MessageManagerLock object to make sure it's thread-safe.
  31265. checkMessageManagerIsLocked
  31266. if (isOpaque())
  31267. styleWanted &= ~ComponentPeer::windowIsSemiTransparent;
  31268. else
  31269. styleWanted |= ComponentPeer::windowIsSemiTransparent;
  31270. int currentStyleFlags = 0;
  31271. // don't use getPeer(), so that we only get the peer that's specifically
  31272. // for this comp, and not for one of its parents.
  31273. ComponentPeer* peer = ComponentPeer::getPeerFor (this);
  31274. if (peer != 0)
  31275. currentStyleFlags = peer->getStyleFlags();
  31276. if (styleWanted != currentStyleFlags || ! flags.hasHeavyweightPeerFlag)
  31277. {
  31278. SafePointer<Component> safePointer (this);
  31279. #if JUCE_LINUX
  31280. // it's wise to give the component a non-zero size before
  31281. // putting it on the desktop, as X windows get confused by this, and
  31282. // a (1, 1) minimum size is enforced here.
  31283. setSize (jmax (1, getWidth()),
  31284. jmax (1, getHeight()));
  31285. #endif
  31286. const Point<int> topLeft (relativePositionToGlobal (Point<int> (0, 0)));
  31287. bool wasFullscreen = false;
  31288. bool wasMinimised = false;
  31289. ComponentBoundsConstrainer* currentConstainer = 0;
  31290. Rectangle<int> oldNonFullScreenBounds;
  31291. if (peer != 0)
  31292. {
  31293. wasFullscreen = peer->isFullScreen();
  31294. wasMinimised = peer->isMinimised();
  31295. currentConstainer = peer->getConstrainer();
  31296. oldNonFullScreenBounds = peer->getNonFullScreenBounds();
  31297. removeFromDesktop();
  31298. setTopLeftPosition (topLeft.getX(), topLeft.getY());
  31299. }
  31300. if (parentComponent_ != 0)
  31301. parentComponent_->removeChildComponent (this);
  31302. if (safePointer != 0)
  31303. {
  31304. flags.hasHeavyweightPeerFlag = true;
  31305. peer = createNewPeer (styleWanted, nativeWindowToAttachTo);
  31306. Desktop::getInstance().addDesktopComponent (this);
  31307. bounds_.setPosition (topLeft);
  31308. peer->setBounds (topLeft.getX(), topLeft.getY(), getWidth(), getHeight(), false);
  31309. peer->setVisible (isVisible());
  31310. if (wasFullscreen)
  31311. {
  31312. peer->setFullScreen (true);
  31313. peer->setNonFullScreenBounds (oldNonFullScreenBounds);
  31314. }
  31315. if (wasMinimised)
  31316. peer->setMinimised (true);
  31317. if (isAlwaysOnTop())
  31318. peer->setAlwaysOnTop (true);
  31319. peer->setConstrainer (currentConstainer);
  31320. repaint();
  31321. }
  31322. internalHierarchyChanged();
  31323. }
  31324. }
  31325. void Component::removeFromDesktop()
  31326. {
  31327. // if component methods are being called from threads other than the message
  31328. // thread, you'll need to use a MessageManagerLock object to make sure it's thread-safe.
  31329. checkMessageManagerIsLocked
  31330. if (flags.hasHeavyweightPeerFlag)
  31331. {
  31332. ComponentPeer* const peer = ComponentPeer::getPeerFor (this);
  31333. flags.hasHeavyweightPeerFlag = false;
  31334. jassert (peer != 0);
  31335. delete peer;
  31336. Desktop::getInstance().removeDesktopComponent (this);
  31337. }
  31338. }
  31339. bool Component::isOnDesktop() const throw()
  31340. {
  31341. return flags.hasHeavyweightPeerFlag;
  31342. }
  31343. void Component::userTriedToCloseWindow()
  31344. {
  31345. /* This means that the user's trying to get rid of your window with the 'close window' system
  31346. menu option (on windows) or possibly the task manager - you should really handle this
  31347. and delete or hide your component in an appropriate way.
  31348. If you want to ignore the event and don't want to trigger this assertion, just override
  31349. this method and do nothing.
  31350. */
  31351. jassertfalse
  31352. }
  31353. void Component::minimisationStateChanged (bool)
  31354. {
  31355. }
  31356. void Component::setOpaque (const bool shouldBeOpaque)
  31357. {
  31358. if (shouldBeOpaque != flags.opaqueFlag)
  31359. {
  31360. flags.opaqueFlag = shouldBeOpaque;
  31361. if (flags.hasHeavyweightPeerFlag)
  31362. {
  31363. const ComponentPeer* const peer = ComponentPeer::getPeerFor (this);
  31364. if (peer != 0)
  31365. {
  31366. // to make it recreate the heavyweight window
  31367. addToDesktop (peer->getStyleFlags());
  31368. }
  31369. }
  31370. repaint();
  31371. }
  31372. }
  31373. bool Component::isOpaque() const throw()
  31374. {
  31375. return flags.opaqueFlag;
  31376. }
  31377. void Component::setBufferedToImage (const bool shouldBeBuffered)
  31378. {
  31379. if (shouldBeBuffered != flags.bufferToImageFlag)
  31380. {
  31381. deleteAndZero (bufferedImage_);
  31382. flags.bufferToImageFlag = shouldBeBuffered;
  31383. }
  31384. }
  31385. void Component::toFront (const bool setAsForeground)
  31386. {
  31387. // if component methods are being called from threads other than the message
  31388. // thread, you'll need to use a MessageManagerLock object to make sure it's thread-safe.
  31389. checkMessageManagerIsLocked
  31390. if (flags.hasHeavyweightPeerFlag)
  31391. {
  31392. ComponentPeer* const peer = getPeer();
  31393. if (peer != 0)
  31394. {
  31395. peer->toFront (setAsForeground);
  31396. if (setAsForeground && ! hasKeyboardFocus (true))
  31397. grabKeyboardFocus();
  31398. }
  31399. }
  31400. else if (parentComponent_ != 0)
  31401. {
  31402. Array<Component*>& childList = parentComponent_->childComponentList_;
  31403. if (childList.getLast() != this)
  31404. {
  31405. const int index = childList.indexOf (this);
  31406. if (index >= 0)
  31407. {
  31408. int insertIndex = -1;
  31409. if (! flags.alwaysOnTopFlag)
  31410. {
  31411. insertIndex = childList.size() - 1;
  31412. while (insertIndex > 0 && childList.getUnchecked (insertIndex)->isAlwaysOnTop())
  31413. --insertIndex;
  31414. }
  31415. if (index != insertIndex)
  31416. {
  31417. childList.move (index, insertIndex);
  31418. sendFakeMouseMove();
  31419. repaintParent();
  31420. }
  31421. }
  31422. }
  31423. if (setAsForeground)
  31424. {
  31425. internalBroughtToFront();
  31426. grabKeyboardFocus();
  31427. }
  31428. }
  31429. }
  31430. void Component::toBehind (Component* const other)
  31431. {
  31432. if (other != 0 && other != this)
  31433. {
  31434. // the two components must belong to the same parent..
  31435. jassert (parentComponent_ == other->parentComponent_);
  31436. if (parentComponent_ != 0)
  31437. {
  31438. Array<Component*>& childList = parentComponent_->childComponentList_;
  31439. const int index = childList.indexOf (this);
  31440. if (index >= 0 && childList [index + 1] != other)
  31441. {
  31442. int otherIndex = childList.indexOf (other);
  31443. if (otherIndex >= 0)
  31444. {
  31445. if (index < otherIndex)
  31446. --otherIndex;
  31447. childList.move (index, otherIndex);
  31448. sendFakeMouseMove();
  31449. repaintParent();
  31450. }
  31451. }
  31452. }
  31453. else if (isOnDesktop())
  31454. {
  31455. jassert (other->isOnDesktop());
  31456. if (other->isOnDesktop())
  31457. {
  31458. ComponentPeer* const us = getPeer();
  31459. ComponentPeer* const them = other->getPeer();
  31460. jassert (us != 0 && them != 0);
  31461. if (us != 0 && them != 0)
  31462. us->toBehind (them);
  31463. }
  31464. }
  31465. }
  31466. }
  31467. void Component::toBack()
  31468. {
  31469. Array<Component*>& childList = parentComponent_->childComponentList_;
  31470. if (isOnDesktop())
  31471. {
  31472. jassertfalse //xxx need to add this to native window
  31473. }
  31474. else if (parentComponent_ != 0 && childList.getFirst() != this)
  31475. {
  31476. const int index = childList.indexOf (this);
  31477. if (index > 0)
  31478. {
  31479. int insertIndex = 0;
  31480. if (flags.alwaysOnTopFlag)
  31481. {
  31482. while (insertIndex < childList.size()
  31483. && ! childList.getUnchecked (insertIndex)->isAlwaysOnTop())
  31484. {
  31485. ++insertIndex;
  31486. }
  31487. }
  31488. if (index != insertIndex)
  31489. {
  31490. childList.move (index, insertIndex);
  31491. sendFakeMouseMove();
  31492. repaintParent();
  31493. }
  31494. }
  31495. }
  31496. }
  31497. void Component::setAlwaysOnTop (const bool shouldStayOnTop)
  31498. {
  31499. if (shouldStayOnTop != flags.alwaysOnTopFlag)
  31500. {
  31501. flags.alwaysOnTopFlag = shouldStayOnTop;
  31502. if (isOnDesktop())
  31503. {
  31504. ComponentPeer* const peer = getPeer();
  31505. jassert (peer != 0);
  31506. if (peer != 0)
  31507. {
  31508. if (! peer->setAlwaysOnTop (shouldStayOnTop))
  31509. {
  31510. // some kinds of peer can't change their always-on-top status, so
  31511. // for these, we'll need to create a new window
  31512. const int oldFlags = peer->getStyleFlags();
  31513. removeFromDesktop();
  31514. addToDesktop (oldFlags);
  31515. }
  31516. }
  31517. }
  31518. if (shouldStayOnTop)
  31519. toFront (false);
  31520. internalHierarchyChanged();
  31521. }
  31522. }
  31523. bool Component::isAlwaysOnTop() const throw()
  31524. {
  31525. return flags.alwaysOnTopFlag;
  31526. }
  31527. int Component::proportionOfWidth (const float proportion) const throw()
  31528. {
  31529. return roundToInt (proportion * bounds_.getWidth());
  31530. }
  31531. int Component::proportionOfHeight (const float proportion) const throw()
  31532. {
  31533. return roundToInt (proportion * bounds_.getHeight());
  31534. }
  31535. int Component::getParentWidth() const throw()
  31536. {
  31537. return (parentComponent_ != 0) ? parentComponent_->getWidth()
  31538. : getParentMonitorArea().getWidth();
  31539. }
  31540. int Component::getParentHeight() const throw()
  31541. {
  31542. return (parentComponent_ != 0) ? parentComponent_->getHeight()
  31543. : getParentMonitorArea().getHeight();
  31544. }
  31545. int Component::getScreenX() const
  31546. {
  31547. return getScreenPosition().getX();
  31548. }
  31549. int Component::getScreenY() const
  31550. {
  31551. return getScreenPosition().getY();
  31552. }
  31553. const Point<int> Component::getScreenPosition() const
  31554. {
  31555. return (parentComponent_ != 0) ? parentComponent_->getScreenPosition() + getPosition()
  31556. : (flags.hasHeavyweightPeerFlag ? getPeer()->getScreenPosition()
  31557. : getPosition());
  31558. }
  31559. const Rectangle<int> Component::getScreenBounds() const
  31560. {
  31561. return bounds_.withPosition (getScreenPosition());
  31562. }
  31563. const Point<int> Component::relativePositionToGlobal (const Point<int>& relativePosition) const
  31564. {
  31565. const Component* c = this;
  31566. Point<int> p (relativePosition);
  31567. do
  31568. {
  31569. if (c->flags.hasHeavyweightPeerFlag)
  31570. return c->getPeer()->relativePositionToGlobal (p);
  31571. p += c->getPosition();
  31572. c = c->parentComponent_;
  31573. }
  31574. while (c != 0);
  31575. return p;
  31576. }
  31577. const Point<int> Component::globalPositionToRelative (const Point<int>& screenPosition) const
  31578. {
  31579. if (flags.hasHeavyweightPeerFlag)
  31580. {
  31581. return getPeer()->globalPositionToRelative (screenPosition);
  31582. }
  31583. else
  31584. {
  31585. if (parentComponent_ != 0)
  31586. return parentComponent_->globalPositionToRelative (screenPosition) - getPosition();
  31587. return screenPosition - getPosition();
  31588. }
  31589. }
  31590. const Point<int> Component::relativePositionToOtherComponent (const Component* const targetComponent, const Point<int>& positionRelativeToThis) const
  31591. {
  31592. Point<int> p (positionRelativeToThis);
  31593. if (targetComponent != 0)
  31594. {
  31595. const Component* c = this;
  31596. do
  31597. {
  31598. if (c == targetComponent)
  31599. return p;
  31600. if (c->flags.hasHeavyweightPeerFlag)
  31601. {
  31602. p = c->getPeer()->relativePositionToGlobal (p);
  31603. break;
  31604. }
  31605. p += c->getPosition();
  31606. c = c->parentComponent_;
  31607. }
  31608. while (c != 0);
  31609. p = targetComponent->globalPositionToRelative (p);
  31610. }
  31611. return p;
  31612. }
  31613. void Component::setBounds (int x, int y, int w, int h)
  31614. {
  31615. // if component methods are being called from threads other than the message
  31616. // thread, you'll need to use a MessageManagerLock object to make sure it's thread-safe.
  31617. checkMessageManagerIsLocked
  31618. if (w < 0) w = 0;
  31619. if (h < 0) h = 0;
  31620. const bool wasResized = (getWidth() != w || getHeight() != h);
  31621. const bool wasMoved = (getX() != x || getY() != y);
  31622. #if JUCE_DEBUG
  31623. // It's a very bad idea to try to resize a window during its paint() method!
  31624. jassert (! (flags.isInsidePaintCall && wasResized && isOnDesktop()));
  31625. #endif
  31626. if (wasMoved || wasResized)
  31627. {
  31628. if (flags.visibleFlag)
  31629. {
  31630. // send a fake mouse move to trigger enter/exit messages if needed..
  31631. sendFakeMouseMove();
  31632. if (! flags.hasHeavyweightPeerFlag)
  31633. repaintParent();
  31634. }
  31635. bounds_.setBounds (x, y, w, h);
  31636. if (wasResized)
  31637. repaint();
  31638. else if (! flags.hasHeavyweightPeerFlag)
  31639. repaintParent();
  31640. if (flags.hasHeavyweightPeerFlag)
  31641. {
  31642. ComponentPeer* const peer = getPeer();
  31643. if (peer != 0)
  31644. {
  31645. if (wasMoved && wasResized)
  31646. peer->setBounds (getX(), getY(), getWidth(), getHeight(), false);
  31647. else if (wasMoved)
  31648. peer->setPosition (getX(), getY());
  31649. else if (wasResized)
  31650. peer->setSize (getWidth(), getHeight());
  31651. }
  31652. }
  31653. sendMovedResizedMessages (wasMoved, wasResized);
  31654. }
  31655. }
  31656. void Component::sendMovedResizedMessages (const bool wasMoved, const bool wasResized)
  31657. {
  31658. JUCE_TRY
  31659. {
  31660. if (wasMoved)
  31661. moved();
  31662. if (wasResized)
  31663. {
  31664. resized();
  31665. for (int i = childComponentList_.size(); --i >= 0;)
  31666. {
  31667. childComponentList_.getUnchecked(i)->parentSizeChanged();
  31668. i = jmin (i, childComponentList_.size());
  31669. }
  31670. }
  31671. BailOutChecker checker (this);
  31672. if (parentComponent_ != 0)
  31673. parentComponent_->childBoundsChanged (this);
  31674. if (! checker.shouldBailOut())
  31675. componentListeners.callChecked (checker, &ComponentListener::componentMovedOrResized,
  31676. *this, wasMoved, wasResized);
  31677. }
  31678. JUCE_CATCH_EXCEPTION
  31679. }
  31680. void Component::setSize (const int w, const int h)
  31681. {
  31682. setBounds (getX(), getY(), w, h);
  31683. }
  31684. void Component::setTopLeftPosition (const int x, const int y)
  31685. {
  31686. setBounds (x, y, getWidth(), getHeight());
  31687. }
  31688. void Component::setTopRightPosition (const int x, const int y)
  31689. {
  31690. setTopLeftPosition (x - getWidth(), y);
  31691. }
  31692. void Component::setBounds (const Rectangle<int>& r)
  31693. {
  31694. setBounds (r.getX(),
  31695. r.getY(),
  31696. r.getWidth(),
  31697. r.getHeight());
  31698. }
  31699. void Component::setBoundsRelative (const float x, const float y,
  31700. const float w, const float h)
  31701. {
  31702. const int pw = getParentWidth();
  31703. const int ph = getParentHeight();
  31704. setBounds (roundToInt (x * pw),
  31705. roundToInt (y * ph),
  31706. roundToInt (w * pw),
  31707. roundToInt (h * ph));
  31708. }
  31709. void Component::setCentrePosition (const int x, const int y)
  31710. {
  31711. setTopLeftPosition (x - getWidth() / 2,
  31712. y - getHeight() / 2);
  31713. }
  31714. void Component::setCentreRelative (const float x, const float y)
  31715. {
  31716. setCentrePosition (roundToInt (getParentWidth() * x),
  31717. roundToInt (getParentHeight() * y));
  31718. }
  31719. void Component::centreWithSize (const int width, const int height)
  31720. {
  31721. setBounds ((getParentWidth() - width) / 2,
  31722. (getParentHeight() - height) / 2,
  31723. width,
  31724. height);
  31725. }
  31726. void Component::setBoundsInset (const BorderSize& borders)
  31727. {
  31728. setBounds (borders.getLeft(),
  31729. borders.getTop(),
  31730. getParentWidth() - (borders.getLeftAndRight()),
  31731. getParentHeight() - (borders.getTopAndBottom()));
  31732. }
  31733. void Component::setBoundsToFit (int x, int y, int width, int height,
  31734. const Justification& justification,
  31735. const bool onlyReduceInSize)
  31736. {
  31737. // it's no good calling this method unless both the component and
  31738. // target rectangle have a finite size.
  31739. jassert (getWidth() > 0 && getHeight() > 0 && width > 0 && height > 0);
  31740. if (getWidth() > 0 && getHeight() > 0
  31741. && width > 0 && height > 0)
  31742. {
  31743. int newW, newH;
  31744. if (onlyReduceInSize && getWidth() <= width && getHeight() <= height)
  31745. {
  31746. newW = getWidth();
  31747. newH = getHeight();
  31748. }
  31749. else
  31750. {
  31751. const double imageRatio = getHeight() / (double) getWidth();
  31752. const double targetRatio = height / (double) width;
  31753. if (imageRatio <= targetRatio)
  31754. {
  31755. newW = width;
  31756. newH = jmin (height, roundToInt (newW * imageRatio));
  31757. }
  31758. else
  31759. {
  31760. newH = height;
  31761. newW = jmin (width, roundToInt (newH / imageRatio));
  31762. }
  31763. }
  31764. if (newW > 0 && newH > 0)
  31765. {
  31766. int newX, newY;
  31767. justification.applyToRectangle (newX, newY, newW, newH,
  31768. x, y, width, height);
  31769. setBounds (newX, newY, newW, newH);
  31770. }
  31771. }
  31772. }
  31773. bool Component::hitTest (int x, int y)
  31774. {
  31775. if (! flags.ignoresMouseClicksFlag)
  31776. return true;
  31777. if (flags.allowChildMouseClicksFlag)
  31778. {
  31779. for (int i = getNumChildComponents(); --i >= 0;)
  31780. {
  31781. Component* const c = getChildComponent (i);
  31782. if (c->isVisible()
  31783. && c->bounds_.contains (x, y)
  31784. && c->hitTest (x - c->getX(),
  31785. y - c->getY()))
  31786. {
  31787. return true;
  31788. }
  31789. }
  31790. }
  31791. return false;
  31792. }
  31793. void Component::setInterceptsMouseClicks (const bool allowClicks,
  31794. const bool allowClicksOnChildComponents) throw()
  31795. {
  31796. flags.ignoresMouseClicksFlag = ! allowClicks;
  31797. flags.allowChildMouseClicksFlag = allowClicksOnChildComponents;
  31798. }
  31799. void Component::getInterceptsMouseClicks (bool& allowsClicksOnThisComponent,
  31800. bool& allowsClicksOnChildComponents) const throw()
  31801. {
  31802. allowsClicksOnThisComponent = ! flags.ignoresMouseClicksFlag;
  31803. allowsClicksOnChildComponents = flags.allowChildMouseClicksFlag;
  31804. }
  31805. bool Component::contains (const int x, const int y)
  31806. {
  31807. if (((unsigned int) x) < (unsigned int) getWidth()
  31808. && ((unsigned int) y) < (unsigned int) getHeight()
  31809. && hitTest (x, y))
  31810. {
  31811. if (parentComponent_ != 0)
  31812. {
  31813. return parentComponent_->contains (x + getX(),
  31814. y + getY());
  31815. }
  31816. else if (flags.hasHeavyweightPeerFlag)
  31817. {
  31818. const ComponentPeer* const peer = getPeer();
  31819. if (peer != 0)
  31820. return peer->contains (Point<int> (x, y), true);
  31821. }
  31822. }
  31823. return false;
  31824. }
  31825. bool Component::reallyContains (int x, int y, const bool returnTrueIfWithinAChild)
  31826. {
  31827. if (! contains (x, y))
  31828. return false;
  31829. Component* p = this;
  31830. while (p->parentComponent_ != 0)
  31831. {
  31832. x += p->getX();
  31833. y += p->getY();
  31834. p = p->parentComponent_;
  31835. }
  31836. const Component* const c = p->getComponentAt (x, y);
  31837. return (c == this) || (returnTrueIfWithinAChild && isParentOf (c));
  31838. }
  31839. Component* Component::getComponentAt (const Point<int>& position)
  31840. {
  31841. return getComponentAt (position.getX(), position.getY());
  31842. }
  31843. Component* Component::getComponentAt (const int x, const int y)
  31844. {
  31845. if (flags.visibleFlag
  31846. && ((unsigned int) x) < (unsigned int) getWidth()
  31847. && ((unsigned int) y) < (unsigned int) getHeight()
  31848. && hitTest (x, y))
  31849. {
  31850. for (int i = childComponentList_.size(); --i >= 0;)
  31851. {
  31852. Component* const child = childComponentList_.getUnchecked(i);
  31853. Component* const c = child->getComponentAt (x - child->getX(),
  31854. y - child->getY());
  31855. if (c != 0)
  31856. return c;
  31857. }
  31858. return this;
  31859. }
  31860. return 0;
  31861. }
  31862. void Component::addChildComponent (Component* const child, int zOrder)
  31863. {
  31864. // if component methods are being called from threads other than the message
  31865. // thread, you'll need to use a MessageManagerLock object to make sure it's thread-safe.
  31866. checkMessageManagerIsLocked
  31867. if (child != 0 && child->parentComponent_ != this)
  31868. {
  31869. if (child->parentComponent_ != 0)
  31870. child->parentComponent_->removeChildComponent (child);
  31871. else
  31872. child->removeFromDesktop();
  31873. child->parentComponent_ = this;
  31874. if (child->isVisible())
  31875. child->repaintParent();
  31876. if (! child->isAlwaysOnTop())
  31877. {
  31878. if (zOrder < 0 || zOrder > childComponentList_.size())
  31879. zOrder = childComponentList_.size();
  31880. while (zOrder > 0)
  31881. {
  31882. if (! childComponentList_.getUnchecked (zOrder - 1)->isAlwaysOnTop())
  31883. break;
  31884. --zOrder;
  31885. }
  31886. }
  31887. childComponentList_.insert (zOrder, child);
  31888. child->internalHierarchyChanged();
  31889. internalChildrenChanged();
  31890. }
  31891. }
  31892. void Component::addAndMakeVisible (Component* const child, int zOrder)
  31893. {
  31894. if (child != 0)
  31895. {
  31896. child->setVisible (true);
  31897. addChildComponent (child, zOrder);
  31898. }
  31899. }
  31900. void Component::removeChildComponent (Component* const child)
  31901. {
  31902. removeChildComponent (childComponentList_.indexOf (child));
  31903. }
  31904. Component* Component::removeChildComponent (const int index)
  31905. {
  31906. // if component methods are being called from threads other than the message
  31907. // thread, you'll need to use a MessageManagerLock object to make sure it's thread-safe.
  31908. checkMessageManagerIsLocked
  31909. Component* const child = childComponentList_ [index];
  31910. if (child != 0)
  31911. {
  31912. sendFakeMouseMove();
  31913. child->repaintParent();
  31914. childComponentList_.remove (index);
  31915. child->parentComponent_ = 0;
  31916. JUCE_TRY
  31917. {
  31918. if ((currentlyFocusedComponent == child)
  31919. || child->isParentOf (currentlyFocusedComponent))
  31920. {
  31921. // get rid first to force the grabKeyboardFocus to change to us.
  31922. giveAwayFocus();
  31923. grabKeyboardFocus();
  31924. }
  31925. }
  31926. #if JUCE_CATCH_UNHANDLED_EXCEPTIONS
  31927. catch (const std::exception& e)
  31928. {
  31929. currentlyFocusedComponent = 0;
  31930. Desktop::getInstance().triggerFocusCallback();
  31931. JUCEApplication::sendUnhandledException (&e, __FILE__, __LINE__);
  31932. }
  31933. catch (...)
  31934. {
  31935. currentlyFocusedComponent = 0;
  31936. Desktop::getInstance().triggerFocusCallback();
  31937. JUCEApplication::sendUnhandledException (0, __FILE__, __LINE__);
  31938. }
  31939. #endif
  31940. child->internalHierarchyChanged();
  31941. internalChildrenChanged();
  31942. }
  31943. return child;
  31944. }
  31945. void Component::removeAllChildren()
  31946. {
  31947. while (childComponentList_.size() > 0)
  31948. removeChildComponent (childComponentList_.size() - 1);
  31949. }
  31950. void Component::deleteAllChildren()
  31951. {
  31952. while (childComponentList_.size() > 0)
  31953. delete (removeChildComponent (childComponentList_.size() - 1));
  31954. }
  31955. int Component::getNumChildComponents() const throw()
  31956. {
  31957. return childComponentList_.size();
  31958. }
  31959. Component* Component::getChildComponent (const int index) const throw()
  31960. {
  31961. return childComponentList_ [index];
  31962. }
  31963. int Component::getIndexOfChildComponent (const Component* const child) const throw()
  31964. {
  31965. return childComponentList_.indexOf (const_cast <Component*> (child));
  31966. }
  31967. Component* Component::getTopLevelComponent() const throw()
  31968. {
  31969. const Component* comp = this;
  31970. while (comp->parentComponent_ != 0)
  31971. comp = comp->parentComponent_;
  31972. return const_cast <Component*> (comp);
  31973. }
  31974. bool Component::isParentOf (const Component* possibleChild) const throw()
  31975. {
  31976. if (! possibleChild->isValidComponent())
  31977. {
  31978. jassert (possibleChild == 0);
  31979. return false;
  31980. }
  31981. while (possibleChild != 0)
  31982. {
  31983. possibleChild = possibleChild->parentComponent_;
  31984. if (possibleChild == this)
  31985. return true;
  31986. }
  31987. return false;
  31988. }
  31989. void Component::parentHierarchyChanged()
  31990. {
  31991. }
  31992. void Component::childrenChanged()
  31993. {
  31994. }
  31995. void Component::internalChildrenChanged()
  31996. {
  31997. if (componentListeners.isEmpty())
  31998. {
  31999. childrenChanged();
  32000. }
  32001. else
  32002. {
  32003. BailOutChecker checker (this);
  32004. childrenChanged();
  32005. if (! checker.shouldBailOut())
  32006. componentListeners.callChecked (checker, &ComponentListener::componentChildrenChanged, *this);
  32007. }
  32008. }
  32009. void Component::internalHierarchyChanged()
  32010. {
  32011. BailOutChecker checker (this);
  32012. parentHierarchyChanged();
  32013. if (checker.shouldBailOut())
  32014. return;
  32015. componentListeners.callChecked (checker, &ComponentListener::componentParentHierarchyChanged, *this);
  32016. if (checker.shouldBailOut())
  32017. return;
  32018. for (int i = childComponentList_.size(); --i >= 0;)
  32019. {
  32020. childComponentList_.getUnchecked (i)->internalHierarchyChanged();
  32021. if (checker.shouldBailOut())
  32022. {
  32023. // you really shouldn't delete the parent component during a callback telling you
  32024. // that it's changed..
  32025. jassertfalse;
  32026. return;
  32027. }
  32028. i = jmin (i, childComponentList_.size());
  32029. }
  32030. }
  32031. void* Component::runModalLoopCallback (void* userData)
  32032. {
  32033. return (void*) (pointer_sized_int) static_cast <Component*> (userData)->runModalLoop();
  32034. }
  32035. int Component::runModalLoop()
  32036. {
  32037. if (! MessageManager::getInstance()->isThisTheMessageThread())
  32038. {
  32039. // use a callback so this can be called from non-gui threads
  32040. return (int) (pointer_sized_int)
  32041. MessageManager::getInstance()
  32042. ->callFunctionOnMessageThread (&runModalLoopCallback, this);
  32043. }
  32044. SafePointer<Component> prevFocused (getCurrentlyFocusedComponent());
  32045. if (! isCurrentlyModal())
  32046. enterModalState();
  32047. JUCE_TRY
  32048. {
  32049. while (flags.currentlyModalFlag && flags.visibleFlag)
  32050. {
  32051. if (! MessageManager::getInstance()->runDispatchLoopUntil (20))
  32052. break;
  32053. // check whether this component was deleted during the last message
  32054. if (! isValidMessageListener())
  32055. break;
  32056. }
  32057. }
  32058. #if JUCE_CATCH_UNHANDLED_EXCEPTIONS
  32059. catch (const std::exception& e)
  32060. {
  32061. JUCEApplication::sendUnhandledException (&e, __FILE__, __LINE__);
  32062. return 0;
  32063. }
  32064. catch (...)
  32065. {
  32066. JUCEApplication::sendUnhandledException (0, __FILE__, __LINE__);
  32067. return 0;
  32068. }
  32069. #endif
  32070. const int modalIndex = modalComponentReturnValueKeys.indexOf (this);
  32071. int returnValue = 0;
  32072. if (modalIndex >= 0)
  32073. {
  32074. modalComponentReturnValueKeys.remove (modalIndex);
  32075. returnValue = modalReturnValues.remove (modalIndex);
  32076. }
  32077. modalComponentStack.removeValue (this);
  32078. if (prevFocused != 0)
  32079. prevFocused->grabKeyboardFocus();
  32080. return returnValue;
  32081. }
  32082. void Component::enterModalState (const bool takeKeyboardFocus_)
  32083. {
  32084. // if component methods are being called from threads other than the message
  32085. // thread, you'll need to use a MessageManagerLock object to make sure it's thread-safe.
  32086. checkMessageManagerIsLocked
  32087. // Check for an attempt to make a component modal when it already is!
  32088. // This can cause nasty problems..
  32089. jassert (! flags.currentlyModalFlag);
  32090. if (! isCurrentlyModal())
  32091. {
  32092. modalComponentStack.add (this);
  32093. modalComponentReturnValueKeys.add (this);
  32094. modalReturnValues.add (0);
  32095. flags.currentlyModalFlag = true;
  32096. setVisible (true);
  32097. if (takeKeyboardFocus_)
  32098. grabKeyboardFocus();
  32099. }
  32100. }
  32101. void Component::exitModalState (const int returnValue)
  32102. {
  32103. if (isCurrentlyModal())
  32104. {
  32105. if (MessageManager::getInstance()->isThisTheMessageThread())
  32106. {
  32107. const int modalIndex = modalComponentReturnValueKeys.indexOf (this);
  32108. if (modalIndex >= 0)
  32109. {
  32110. modalReturnValues.set (modalIndex, returnValue);
  32111. }
  32112. else
  32113. {
  32114. modalComponentReturnValueKeys.add (this);
  32115. modalReturnValues.add (returnValue);
  32116. }
  32117. modalComponentStack.removeValue (this);
  32118. flags.currentlyModalFlag = false;
  32119. bringModalComponentToFront();
  32120. }
  32121. else
  32122. {
  32123. postMessage (new Message (exitModalStateMessage, returnValue, 0, 0));
  32124. }
  32125. }
  32126. }
  32127. bool Component::isCurrentlyModal() const throw()
  32128. {
  32129. return flags.currentlyModalFlag
  32130. && getCurrentlyModalComponent() == this;
  32131. }
  32132. bool Component::isCurrentlyBlockedByAnotherModalComponent() const
  32133. {
  32134. Component* const mc = getCurrentlyModalComponent();
  32135. return mc != 0
  32136. && mc != this
  32137. && (! mc->isParentOf (this))
  32138. && ! mc->canModalEventBeSentToComponent (this);
  32139. }
  32140. int JUCE_CALLTYPE Component::getNumCurrentlyModalComponents() throw()
  32141. {
  32142. return modalComponentStack.size();
  32143. }
  32144. Component* JUCE_CALLTYPE Component::getCurrentlyModalComponent (int index) throw()
  32145. {
  32146. Component* const c = static_cast <Component*> (modalComponentStack [modalComponentStack.size() - index - 1]);
  32147. return c->isValidComponent() ? c : 0;
  32148. }
  32149. void Component::bringModalComponentToFront()
  32150. {
  32151. ComponentPeer* lastOne = 0;
  32152. for (int i = 0; i < getNumCurrentlyModalComponents(); ++i)
  32153. {
  32154. Component* const c = getCurrentlyModalComponent (i);
  32155. if (c == 0)
  32156. break;
  32157. ComponentPeer* peer = c->getPeer();
  32158. if (peer != 0 && peer != lastOne)
  32159. {
  32160. if (lastOne == 0)
  32161. {
  32162. peer->toFront (true);
  32163. peer->grabFocus();
  32164. }
  32165. else
  32166. peer->toBehind (lastOne);
  32167. lastOne = peer;
  32168. }
  32169. }
  32170. }
  32171. void Component::setBroughtToFrontOnMouseClick (const bool shouldBeBroughtToFront) throw()
  32172. {
  32173. flags.bringToFrontOnClickFlag = shouldBeBroughtToFront;
  32174. }
  32175. bool Component::isBroughtToFrontOnMouseClick() const throw()
  32176. {
  32177. return flags.bringToFrontOnClickFlag;
  32178. }
  32179. void Component::setMouseCursor (const MouseCursor& cursor)
  32180. {
  32181. if (cursor_ != cursor)
  32182. {
  32183. cursor_ = cursor;
  32184. if (flags.visibleFlag)
  32185. updateMouseCursor();
  32186. }
  32187. }
  32188. const MouseCursor Component::getMouseCursor()
  32189. {
  32190. return cursor_;
  32191. }
  32192. void Component::updateMouseCursor() const
  32193. {
  32194. sendFakeMouseMove();
  32195. }
  32196. void Component::setRepaintsOnMouseActivity (const bool shouldRepaint) throw()
  32197. {
  32198. flags.repaintOnMouseActivityFlag = shouldRepaint;
  32199. }
  32200. void Component::repaintParent()
  32201. {
  32202. if (flags.visibleFlag)
  32203. internalRepaint (0, 0, getWidth(), getHeight());
  32204. }
  32205. void Component::repaint()
  32206. {
  32207. repaint (0, 0, getWidth(), getHeight());
  32208. }
  32209. void Component::repaint (const int x, const int y,
  32210. const int w, const int h)
  32211. {
  32212. deleteAndZero (bufferedImage_);
  32213. if (flags.visibleFlag)
  32214. internalRepaint (x, y, w, h);
  32215. }
  32216. void Component::internalRepaint (int x, int y, int w, int h)
  32217. {
  32218. // if component methods are being called from threads other than the message
  32219. // thread, you'll need to use a MessageManagerLock object to make sure it's thread-safe.
  32220. checkMessageManagerIsLocked
  32221. if (x < 0)
  32222. {
  32223. w += x;
  32224. x = 0;
  32225. }
  32226. if (x + w > getWidth())
  32227. w = getWidth() - x;
  32228. if (w > 0)
  32229. {
  32230. if (y < 0)
  32231. {
  32232. h += y;
  32233. y = 0;
  32234. }
  32235. if (y + h > getHeight())
  32236. h = getHeight() - y;
  32237. if (h > 0)
  32238. {
  32239. if (parentComponent_ != 0)
  32240. {
  32241. x += getX();
  32242. y += getY();
  32243. if (parentComponent_->flags.visibleFlag)
  32244. parentComponent_->internalRepaint (x, y, w, h);
  32245. }
  32246. else if (flags.hasHeavyweightPeerFlag)
  32247. {
  32248. ComponentPeer* const peer = getPeer();
  32249. if (peer != 0)
  32250. peer->repaint (x, y, w, h);
  32251. }
  32252. }
  32253. }
  32254. }
  32255. void Component::renderComponent (Graphics& g)
  32256. {
  32257. const Rectangle<int> clipBounds (g.getClipBounds());
  32258. g.saveState();
  32259. clipObscuredRegions (g, clipBounds, 0, 0);
  32260. if (! g.isClipEmpty())
  32261. {
  32262. if (flags.bufferToImageFlag)
  32263. {
  32264. if (bufferedImage_ == 0)
  32265. {
  32266. bufferedImage_ = Image::createNativeImage (flags.opaqueFlag ? Image::RGB : Image::ARGB,
  32267. getWidth(), getHeight(), ! flags.opaqueFlag);
  32268. Graphics imG (*bufferedImage_);
  32269. paint (imG);
  32270. }
  32271. g.setColour (Colours::black);
  32272. g.drawImageAt (bufferedImage_, 0, 0);
  32273. }
  32274. else
  32275. {
  32276. paint (g);
  32277. }
  32278. }
  32279. g.restoreState();
  32280. for (int i = 0; i < childComponentList_.size(); ++i)
  32281. {
  32282. Component* const child = childComponentList_.getUnchecked (i);
  32283. if (child->isVisible() && clipBounds.intersects (child->getBounds()))
  32284. {
  32285. g.saveState();
  32286. if (g.reduceClipRegion (child->getX(), child->getY(),
  32287. child->getWidth(), child->getHeight()))
  32288. {
  32289. for (int j = i + 1; j < childComponentList_.size(); ++j)
  32290. {
  32291. const Component* const sibling = childComponentList_.getUnchecked (j);
  32292. if (sibling->flags.opaqueFlag && sibling->isVisible())
  32293. g.excludeClipRegion (sibling->getBounds());
  32294. }
  32295. if (! g.isClipEmpty())
  32296. {
  32297. g.setOrigin (child->getX(), child->getY());
  32298. child->paintEntireComponent (g);
  32299. }
  32300. }
  32301. g.restoreState();
  32302. }
  32303. }
  32304. g.saveState();
  32305. paintOverChildren (g);
  32306. g.restoreState();
  32307. }
  32308. void Component::paintEntireComponent (Graphics& g)
  32309. {
  32310. jassert (! g.isClipEmpty());
  32311. #if JUCE_DEBUG
  32312. flags.isInsidePaintCall = true;
  32313. #endif
  32314. if (effect_ != 0)
  32315. {
  32316. ScopedPointer<Image> effectImage (Image::createNativeImage (flags.opaqueFlag ? Image::RGB : Image::ARGB,
  32317. getWidth(), getHeight(),
  32318. ! flags.opaqueFlag));
  32319. {
  32320. Graphics g2 (*effectImage);
  32321. renderComponent (g2);
  32322. }
  32323. effect_->applyEffect (*effectImage, g);
  32324. }
  32325. else
  32326. {
  32327. renderComponent (g);
  32328. }
  32329. #if JUCE_DEBUG
  32330. flags.isInsidePaintCall = false;
  32331. #endif
  32332. }
  32333. Image* Component::createComponentSnapshot (const Rectangle<int>& areaToGrab,
  32334. const bool clipImageToComponentBounds)
  32335. {
  32336. Rectangle<int> r (areaToGrab);
  32337. if (clipImageToComponentBounds)
  32338. r = r.getIntersection (getLocalBounds());
  32339. ScopedPointer<Image> componentImage (Image::createNativeImage (flags.opaqueFlag ? Image::RGB : Image::ARGB,
  32340. jmax (1, r.getWidth()),
  32341. jmax (1, r.getHeight()),
  32342. true));
  32343. Graphics imageContext (*componentImage);
  32344. imageContext.setOrigin (-r.getX(), -r.getY());
  32345. paintEntireComponent (imageContext);
  32346. return componentImage.release();
  32347. }
  32348. void Component::setComponentEffect (ImageEffectFilter* const effect)
  32349. {
  32350. if (effect_ != effect)
  32351. {
  32352. effect_ = effect;
  32353. repaint();
  32354. }
  32355. }
  32356. LookAndFeel& Component::getLookAndFeel() const throw()
  32357. {
  32358. const Component* c = this;
  32359. do
  32360. {
  32361. if (c->lookAndFeel_ != 0)
  32362. return *(c->lookAndFeel_);
  32363. c = c->parentComponent_;
  32364. }
  32365. while (c != 0);
  32366. return LookAndFeel::getDefaultLookAndFeel();
  32367. }
  32368. void Component::setLookAndFeel (LookAndFeel* const newLookAndFeel)
  32369. {
  32370. if (lookAndFeel_ != newLookAndFeel)
  32371. {
  32372. lookAndFeel_ = newLookAndFeel;
  32373. sendLookAndFeelChange();
  32374. }
  32375. }
  32376. void Component::lookAndFeelChanged()
  32377. {
  32378. }
  32379. void Component::sendLookAndFeelChange()
  32380. {
  32381. repaint();
  32382. lookAndFeelChanged();
  32383. // (it's not a great idea to do anything that would delete this component
  32384. // during the lookAndFeelChanged() callback)
  32385. jassert (isValidComponent());
  32386. SafePointer<Component> safePointer (this);
  32387. for (int i = childComponentList_.size(); --i >= 0;)
  32388. {
  32389. childComponentList_.getUnchecked (i)->sendLookAndFeelChange();
  32390. if (safePointer == 0)
  32391. return;
  32392. i = jmin (i, childComponentList_.size());
  32393. }
  32394. }
  32395. static const var::identifier getColourPropertyId (const int colourId)
  32396. {
  32397. String s;
  32398. s.preallocateStorage (18);
  32399. s << "jcclr_" << String::toHexString (colourId);
  32400. return s;
  32401. }
  32402. const Colour Component::findColour (const int colourId, const bool inheritFromParent) const
  32403. {
  32404. var* v = properties.getItem (getColourPropertyId (colourId));
  32405. if (v != 0)
  32406. return Colour ((int) *v);
  32407. if (inheritFromParent && parentComponent_ != 0)
  32408. return parentComponent_->findColour (colourId, true);
  32409. return getLookAndFeel().findColour (colourId);
  32410. }
  32411. bool Component::isColourSpecified (const int colourId) const
  32412. {
  32413. return properties.contains (getColourPropertyId (colourId));
  32414. }
  32415. void Component::removeColour (const int colourId)
  32416. {
  32417. if (properties.remove (getColourPropertyId (colourId)))
  32418. colourChanged();
  32419. }
  32420. void Component::setColour (const int colourId, const Colour& colour)
  32421. {
  32422. if (properties.set (getColourPropertyId (colourId), (int) colour.getARGB()))
  32423. colourChanged();
  32424. }
  32425. void Component::copyAllExplicitColoursTo (Component& target) const
  32426. {
  32427. bool changed = false;
  32428. for (int i = properties.size(); --i >= 0;)
  32429. {
  32430. const var::identifier name (properties.getName(i));
  32431. if (name.name.startsWith ("jcclr_"))
  32432. if (target.properties.set (name, properties [name]))
  32433. changed = true;
  32434. }
  32435. if (changed)
  32436. target.colourChanged();
  32437. }
  32438. void Component::colourChanged()
  32439. {
  32440. }
  32441. const Rectangle<int> Component::getLocalBounds() const throw()
  32442. {
  32443. return Rectangle<int> (0, 0, getWidth(), getHeight());
  32444. }
  32445. const Rectangle<int> Component::getUnclippedArea() const
  32446. {
  32447. int x = 0, y = 0, w = getWidth(), h = getHeight();
  32448. Component* p = parentComponent_;
  32449. int px = getX();
  32450. int py = getY();
  32451. while (p != 0)
  32452. {
  32453. if (! Rectangle<int>::intersectRectangles (x, y, w, h, -px, -py, p->getWidth(), p->getHeight()))
  32454. return Rectangle<int>();
  32455. px += p->getX();
  32456. py += p->getY();
  32457. p = p->parentComponent_;
  32458. }
  32459. return Rectangle<int> (x, y, w, h);
  32460. }
  32461. void Component::clipObscuredRegions (Graphics& g, const Rectangle<int>& clipRect,
  32462. const int deltaX, const int deltaY) const
  32463. {
  32464. for (int i = childComponentList_.size(); --i >= 0;)
  32465. {
  32466. const Component* const c = childComponentList_.getUnchecked(i);
  32467. if (c->isVisible())
  32468. {
  32469. const Rectangle<int> newClip (clipRect.getIntersection (c->bounds_));
  32470. if (! newClip.isEmpty())
  32471. {
  32472. if (c->isOpaque())
  32473. {
  32474. g.excludeClipRegion (newClip.translated (deltaX, deltaY));
  32475. }
  32476. else
  32477. {
  32478. c->clipObscuredRegions (g, newClip.translated (-c->getX(), -c->getY()),
  32479. c->getX() + deltaX,
  32480. c->getY() + deltaY);
  32481. }
  32482. }
  32483. }
  32484. }
  32485. }
  32486. void Component::getVisibleArea (RectangleList& result, const bool includeSiblings) const
  32487. {
  32488. result.clear();
  32489. const Rectangle<int> unclipped (getUnclippedArea());
  32490. if (! unclipped.isEmpty())
  32491. {
  32492. result.add (unclipped);
  32493. if (includeSiblings)
  32494. {
  32495. const Component* const c = getTopLevelComponent();
  32496. c->subtractObscuredRegions (result, c->relativePositionToOtherComponent (this, Point<int>()),
  32497. c->getLocalBounds(), this);
  32498. }
  32499. subtractObscuredRegions (result, Point<int>(), unclipped, 0);
  32500. result.consolidate();
  32501. }
  32502. }
  32503. void Component::subtractObscuredRegions (RectangleList& result,
  32504. const Point<int>& delta,
  32505. const Rectangle<int>& clipRect,
  32506. const Component* const compToAvoid) const
  32507. {
  32508. for (int i = childComponentList_.size(); --i >= 0;)
  32509. {
  32510. const Component* const c = childComponentList_.getUnchecked(i);
  32511. if (c != compToAvoid && c->isVisible())
  32512. {
  32513. if (c->isOpaque())
  32514. {
  32515. Rectangle<int> childBounds (c->bounds_.getIntersection (clipRect));
  32516. childBounds.translate (delta.getX(), delta.getY());
  32517. result.subtract (childBounds);
  32518. }
  32519. else
  32520. {
  32521. Rectangle<int> newClip (clipRect.getIntersection (c->bounds_));
  32522. newClip.translate (-c->getX(), -c->getY());
  32523. c->subtractObscuredRegions (result, c->getPosition() + delta,
  32524. newClip, compToAvoid);
  32525. }
  32526. }
  32527. }
  32528. }
  32529. void Component::mouseEnter (const MouseEvent&)
  32530. {
  32531. // base class does nothing
  32532. }
  32533. void Component::mouseExit (const MouseEvent&)
  32534. {
  32535. // base class does nothing
  32536. }
  32537. void Component::mouseDown (const MouseEvent&)
  32538. {
  32539. // base class does nothing
  32540. }
  32541. void Component::mouseUp (const MouseEvent&)
  32542. {
  32543. // base class does nothing
  32544. }
  32545. void Component::mouseDrag (const MouseEvent&)
  32546. {
  32547. // base class does nothing
  32548. }
  32549. void Component::mouseMove (const MouseEvent&)
  32550. {
  32551. // base class does nothing
  32552. }
  32553. void Component::mouseDoubleClick (const MouseEvent&)
  32554. {
  32555. // base class does nothing
  32556. }
  32557. void Component::mouseWheelMove (const MouseEvent& e, float wheelIncrementX, float wheelIncrementY)
  32558. {
  32559. // the base class just passes this event up to its parent..
  32560. if (parentComponent_ != 0)
  32561. parentComponent_->mouseWheelMove (e.getEventRelativeTo (parentComponent_),
  32562. wheelIncrementX, wheelIncrementY);
  32563. }
  32564. void Component::resized()
  32565. {
  32566. // base class does nothing
  32567. }
  32568. void Component::moved()
  32569. {
  32570. // base class does nothing
  32571. }
  32572. void Component::childBoundsChanged (Component*)
  32573. {
  32574. // base class does nothing
  32575. }
  32576. void Component::parentSizeChanged()
  32577. {
  32578. // base class does nothing
  32579. }
  32580. void Component::addComponentListener (ComponentListener* const newListener)
  32581. {
  32582. jassert (isValidComponent());
  32583. componentListeners.add (newListener);
  32584. }
  32585. void Component::removeComponentListener (ComponentListener* const listenerToRemove)
  32586. {
  32587. jassert (isValidComponent());
  32588. componentListeners.remove (listenerToRemove);
  32589. }
  32590. void Component::inputAttemptWhenModal()
  32591. {
  32592. bringModalComponentToFront();
  32593. getLookAndFeel().playAlertSound();
  32594. }
  32595. bool Component::canModalEventBeSentToComponent (const Component*)
  32596. {
  32597. return false;
  32598. }
  32599. void Component::internalModalInputAttempt()
  32600. {
  32601. Component* const current = getCurrentlyModalComponent();
  32602. if (current != 0)
  32603. current->inputAttemptWhenModal();
  32604. }
  32605. void Component::paint (Graphics&)
  32606. {
  32607. // all painting is done in the subclasses
  32608. jassert (! isOpaque()); // if your component's opaque, you've gotta paint it!
  32609. }
  32610. void Component::paintOverChildren (Graphics&)
  32611. {
  32612. // all painting is done in the subclasses
  32613. }
  32614. void Component::handleMessage (const Message& message)
  32615. {
  32616. if (message.intParameter1 == exitModalStateMessage)
  32617. {
  32618. exitModalState (message.intParameter2);
  32619. }
  32620. else if (message.intParameter1 == customCommandMessage)
  32621. {
  32622. handleCommandMessage (message.intParameter2);
  32623. }
  32624. }
  32625. void Component::postCommandMessage (const int commandId)
  32626. {
  32627. postMessage (new Message (customCommandMessage, commandId, 0, 0));
  32628. }
  32629. void Component::handleCommandMessage (int)
  32630. {
  32631. // used by subclasses
  32632. }
  32633. void Component::addMouseListener (MouseListener* const newListener,
  32634. const bool wantsEventsForAllNestedChildComponents)
  32635. {
  32636. // if component methods are being called from threads other than the message
  32637. // thread, you'll need to use a MessageManagerLock object to make sure it's thread-safe.
  32638. checkMessageManagerIsLocked
  32639. if (mouseListeners_ == 0)
  32640. mouseListeners_ = new Array<MouseListener*>();
  32641. if (! mouseListeners_->contains (newListener))
  32642. {
  32643. if (wantsEventsForAllNestedChildComponents)
  32644. {
  32645. mouseListeners_->insert (0, newListener);
  32646. ++numDeepMouseListeners;
  32647. }
  32648. else
  32649. {
  32650. mouseListeners_->add (newListener);
  32651. }
  32652. }
  32653. }
  32654. void Component::removeMouseListener (MouseListener* const listenerToRemove)
  32655. {
  32656. // if component methods are being called from threads other than the message
  32657. // thread, you'll need to use a MessageManagerLock object to make sure it's thread-safe.
  32658. checkMessageManagerIsLocked
  32659. if (mouseListeners_ != 0)
  32660. {
  32661. const int index = mouseListeners_->indexOf (listenerToRemove);
  32662. if (index >= 0)
  32663. {
  32664. if (index < numDeepMouseListeners)
  32665. --numDeepMouseListeners;
  32666. mouseListeners_->remove (index);
  32667. }
  32668. }
  32669. }
  32670. void Component::internalMouseEnter (MouseInputSource& source, const Point<int>& relativePos, const Time& time)
  32671. {
  32672. if (isCurrentlyBlockedByAnotherModalComponent())
  32673. {
  32674. // if something else is modal, always just show a normal mouse cursor
  32675. source.showMouseCursor (MouseCursor::NormalCursor);
  32676. return;
  32677. }
  32678. if (! flags.mouseInsideFlag)
  32679. {
  32680. flags.mouseInsideFlag = true;
  32681. flags.mouseOverFlag = true;
  32682. flags.draggingFlag = false;
  32683. BailOutChecker checker (this);
  32684. if (flags.repaintOnMouseActivityFlag)
  32685. repaint();
  32686. const MouseEvent me (source, relativePos, source.getCurrentModifiers(),
  32687. this, time, relativePos,
  32688. time, 0, false);
  32689. mouseEnter (me);
  32690. if (checker.shouldBailOut())
  32691. return;
  32692. Desktop::getInstance().resetTimer();
  32693. Desktop::getInstance().mouseListeners.callChecked (checker, &MouseListener::mouseEnter, me);
  32694. if (checker.shouldBailOut())
  32695. return;
  32696. if (mouseListeners_ != 0)
  32697. {
  32698. for (int i = mouseListeners_->size(); --i >= 0;)
  32699. {
  32700. mouseListeners_->getUnchecked(i)->mouseEnter (me);
  32701. if (checker.shouldBailOut())
  32702. return;
  32703. i = jmin (i, mouseListeners_->size());
  32704. }
  32705. }
  32706. Component* p = parentComponent_;
  32707. while (p != 0)
  32708. {
  32709. if (p->numDeepMouseListeners > 0)
  32710. {
  32711. BailOutChecker checker (this, p);
  32712. for (int i = p->numDeepMouseListeners; --i >= 0;)
  32713. {
  32714. p->mouseListeners_->getUnchecked(i)->mouseEnter (me);
  32715. if (checker.shouldBailOut())
  32716. return;
  32717. i = jmin (i, p->numDeepMouseListeners);
  32718. }
  32719. }
  32720. p = p->parentComponent_;
  32721. }
  32722. }
  32723. }
  32724. void Component::internalMouseExit (MouseInputSource& source, const Point<int>& relativePos, const Time& time)
  32725. {
  32726. BailOutChecker checker (this);
  32727. if (flags.draggingFlag)
  32728. {
  32729. internalMouseUp (source, relativePos, time, source.getCurrentModifiers().getRawFlags());
  32730. if (checker.shouldBailOut())
  32731. return;
  32732. }
  32733. if (flags.mouseInsideFlag || flags.mouseOverFlag)
  32734. {
  32735. flags.mouseInsideFlag = false;
  32736. flags.mouseOverFlag = false;
  32737. flags.draggingFlag = false;
  32738. if (flags.repaintOnMouseActivityFlag)
  32739. repaint();
  32740. const MouseEvent me (source, relativePos, source.getCurrentModifiers(),
  32741. this, time, relativePos,
  32742. time, 0, false);
  32743. mouseExit (me);
  32744. if (checker.shouldBailOut())
  32745. return;
  32746. Desktop::getInstance().resetTimer();
  32747. Desktop::getInstance().mouseListeners.callChecked (checker, &MouseListener::mouseExit, me);
  32748. if (checker.shouldBailOut())
  32749. return;
  32750. if (mouseListeners_ != 0)
  32751. {
  32752. for (int i = mouseListeners_->size(); --i >= 0;)
  32753. {
  32754. ((MouseListener*) mouseListeners_->getUnchecked (i))->mouseExit (me);
  32755. if (checker.shouldBailOut())
  32756. return;
  32757. i = jmin (i, mouseListeners_->size());
  32758. }
  32759. }
  32760. Component* p = parentComponent_;
  32761. while (p != 0)
  32762. {
  32763. if (p->numDeepMouseListeners > 0)
  32764. {
  32765. BailOutChecker checker (this, p);
  32766. for (int i = p->numDeepMouseListeners; --i >= 0;)
  32767. {
  32768. p->mouseListeners_->getUnchecked (i)->mouseExit (me);
  32769. if (checker.shouldBailOut())
  32770. return;
  32771. i = jmin (i, p->numDeepMouseListeners);
  32772. }
  32773. }
  32774. p = p->parentComponent_;
  32775. }
  32776. }
  32777. }
  32778. class InternalDragRepeater : public Timer
  32779. {
  32780. public:
  32781. InternalDragRepeater()
  32782. {}
  32783. ~InternalDragRepeater()
  32784. {
  32785. clearSingletonInstance();
  32786. }
  32787. juce_DeclareSingleton_SingleThreaded_Minimal (InternalDragRepeater)
  32788. void timerCallback()
  32789. {
  32790. Desktop& desktop = Desktop::getInstance();
  32791. int numMiceDown = 0;
  32792. for (int i = desktop.getNumMouseSources(); --i >= 0;)
  32793. {
  32794. MouseInputSource* const source = desktop.getMouseSource(i);
  32795. if (source->isDragging())
  32796. {
  32797. source->triggerFakeMove();
  32798. ++numMiceDown;
  32799. }
  32800. }
  32801. if (numMiceDown == 0)
  32802. deleteInstance();
  32803. }
  32804. juce_UseDebuggingNewOperator
  32805. private:
  32806. InternalDragRepeater (const InternalDragRepeater&);
  32807. InternalDragRepeater& operator= (const InternalDragRepeater&);
  32808. };
  32809. juce_ImplementSingleton_SingleThreaded (InternalDragRepeater)
  32810. void Component::beginDragAutoRepeat (const int interval)
  32811. {
  32812. if (interval > 0)
  32813. {
  32814. if (InternalDragRepeater::getInstance()->getTimerInterval() != interval)
  32815. InternalDragRepeater::getInstance()->startTimer (interval);
  32816. }
  32817. else
  32818. {
  32819. InternalDragRepeater::deleteInstance();
  32820. }
  32821. }
  32822. void Component::internalMouseDown (MouseInputSource& source, const Point<int>& relativePos, const Time& time)
  32823. {
  32824. Desktop& desktop = Desktop::getInstance();
  32825. BailOutChecker checker (this);
  32826. if (isCurrentlyBlockedByAnotherModalComponent())
  32827. {
  32828. internalModalInputAttempt();
  32829. if (checker.shouldBailOut())
  32830. return;
  32831. // If processing the input attempt has exited the modal loop, we'll allow the event
  32832. // to be delivered..
  32833. if (isCurrentlyBlockedByAnotherModalComponent())
  32834. {
  32835. // allow blocked mouse-events to go to global listeners..
  32836. const MouseEvent me (source, relativePos, source.getCurrentModifiers(),
  32837. this, time, relativePos, time,
  32838. source.getNumberOfMultipleClicks(), false);
  32839. desktop.resetTimer();
  32840. desktop.mouseListeners.callChecked (checker, &MouseListener::mouseDown, me);
  32841. return;
  32842. }
  32843. }
  32844. {
  32845. Component* c = this;
  32846. while (c != 0)
  32847. {
  32848. if (c->isBroughtToFrontOnMouseClick())
  32849. {
  32850. c->toFront (true);
  32851. if (checker.shouldBailOut())
  32852. return;
  32853. }
  32854. c = c->parentComponent_;
  32855. }
  32856. }
  32857. if (! flags.dontFocusOnMouseClickFlag)
  32858. {
  32859. grabFocusInternal (focusChangedByMouseClick);
  32860. if (checker.shouldBailOut())
  32861. return;
  32862. }
  32863. flags.draggingFlag = true;
  32864. flags.mouseOverFlag = true;
  32865. if (flags.repaintOnMouseActivityFlag)
  32866. repaint();
  32867. const MouseEvent me (source, relativePos, source.getCurrentModifiers(),
  32868. this, time, relativePos, time,
  32869. source.getNumberOfMultipleClicks(), false);
  32870. mouseDown (me);
  32871. if (checker.shouldBailOut())
  32872. return;
  32873. desktop.resetTimer();
  32874. desktop.mouseListeners.callChecked (checker, &MouseListener::mouseDown, me);
  32875. if (checker.shouldBailOut())
  32876. return;
  32877. if (mouseListeners_ != 0)
  32878. {
  32879. for (int i = mouseListeners_->size(); --i >= 0;)
  32880. {
  32881. ((MouseListener*) mouseListeners_->getUnchecked (i))->mouseDown (me);
  32882. if (checker.shouldBailOut())
  32883. return;
  32884. i = jmin (i, mouseListeners_->size());
  32885. }
  32886. }
  32887. Component* p = parentComponent_;
  32888. while (p != 0)
  32889. {
  32890. if (p->numDeepMouseListeners > 0)
  32891. {
  32892. BailOutChecker checker (this, p);
  32893. for (int i = p->numDeepMouseListeners; --i >= 0;)
  32894. {
  32895. p->mouseListeners_->getUnchecked (i)->mouseDown (me);
  32896. if (checker.shouldBailOut())
  32897. return;
  32898. i = jmin (i, p->numDeepMouseListeners);
  32899. }
  32900. }
  32901. p = p->parentComponent_;
  32902. }
  32903. }
  32904. void Component::internalMouseUp (MouseInputSource& source, const Point<int>& relativePos, const Time& time, const ModifierKeys& oldModifiers)
  32905. {
  32906. if (flags.draggingFlag)
  32907. {
  32908. Desktop& desktop = Desktop::getInstance();
  32909. flags.draggingFlag = false;
  32910. BailOutChecker checker (this);
  32911. if (flags.repaintOnMouseActivityFlag)
  32912. repaint();
  32913. const MouseEvent me (source, relativePos,
  32914. oldModifiers, this, time,
  32915. globalPositionToRelative (source.getLastMouseDownPosition()),
  32916. source.getLastMouseDownTime(),
  32917. source.getNumberOfMultipleClicks(),
  32918. source.hasMouseMovedSignificantlySincePressed());
  32919. mouseUp (me);
  32920. if (checker.shouldBailOut())
  32921. return;
  32922. desktop.resetTimer();
  32923. desktop.mouseListeners.callChecked (checker, &MouseListener::mouseUp, me);
  32924. if (checker.shouldBailOut())
  32925. return;
  32926. if (mouseListeners_ != 0)
  32927. {
  32928. for (int i = mouseListeners_->size(); --i >= 0;)
  32929. {
  32930. ((MouseListener*) mouseListeners_->getUnchecked (i))->mouseUp (me);
  32931. if (checker.shouldBailOut())
  32932. return;
  32933. i = jmin (i, mouseListeners_->size());
  32934. }
  32935. }
  32936. {
  32937. Component* p = parentComponent_;
  32938. while (p != 0)
  32939. {
  32940. if (p->numDeepMouseListeners > 0)
  32941. {
  32942. BailOutChecker checker (this, p);
  32943. for (int i = p->numDeepMouseListeners; --i >= 0;)
  32944. {
  32945. p->mouseListeners_->getUnchecked (i)->mouseUp (me);
  32946. if (checker.shouldBailOut())
  32947. return;
  32948. i = jmin (i, p->numDeepMouseListeners);
  32949. }
  32950. }
  32951. p = p->parentComponent_;
  32952. }
  32953. }
  32954. // check for double-click
  32955. if (me.getNumberOfClicks() >= 2)
  32956. {
  32957. const int numListeners = (mouseListeners_ != 0) ? mouseListeners_->size() : 0;
  32958. mouseDoubleClick (me);
  32959. if (checker.shouldBailOut())
  32960. return;
  32961. desktop.mouseListeners.callChecked (checker, &MouseListener::mouseDoubleClick, me);
  32962. if (checker.shouldBailOut())
  32963. return;
  32964. for (int i = numListeners; --i >= 0;)
  32965. {
  32966. if (checker.shouldBailOut())
  32967. return;
  32968. MouseListener* const ml = (MouseListener*)((*mouseListeners_)[i]);
  32969. if (ml != 0)
  32970. ml->mouseDoubleClick (me);
  32971. }
  32972. if (checker.shouldBailOut())
  32973. return;
  32974. Component* p = parentComponent_;
  32975. while (p != 0)
  32976. {
  32977. if (p->numDeepMouseListeners > 0)
  32978. {
  32979. BailOutChecker checker (this, p);
  32980. for (int i = p->numDeepMouseListeners; --i >= 0;)
  32981. {
  32982. p->mouseListeners_->getUnchecked (i)->mouseDoubleClick (me);
  32983. if (checker.shouldBailOut())
  32984. return;
  32985. i = jmin (i, p->numDeepMouseListeners);
  32986. }
  32987. }
  32988. p = p->parentComponent_;
  32989. }
  32990. }
  32991. }
  32992. }
  32993. void Component::internalMouseDrag (MouseInputSource& source, const Point<int>& relativePos, const Time& time)
  32994. {
  32995. if (flags.draggingFlag)
  32996. {
  32997. Desktop& desktop = Desktop::getInstance();
  32998. flags.mouseOverFlag = reallyContains (relativePos.getX(), relativePos.getY(), false);
  32999. BailOutChecker checker (this);
  33000. const MouseEvent me (source, relativePos,
  33001. source.getCurrentModifiers(), this, time,
  33002. globalPositionToRelative (source.getLastMouseDownPosition()),
  33003. source.getLastMouseDownTime(),
  33004. source.getNumberOfMultipleClicks(),
  33005. source.hasMouseMovedSignificantlySincePressed());
  33006. mouseDrag (me);
  33007. if (checker.shouldBailOut())
  33008. return;
  33009. desktop.resetTimer();
  33010. desktop.mouseListeners.callChecked (checker, &MouseListener::mouseDrag, me);
  33011. if (checker.shouldBailOut())
  33012. return;
  33013. if (mouseListeners_ != 0)
  33014. {
  33015. for (int i = mouseListeners_->size(); --i >= 0;)
  33016. {
  33017. ((MouseListener*) mouseListeners_->getUnchecked (i))->mouseDrag (me);
  33018. if (checker.shouldBailOut())
  33019. return;
  33020. i = jmin (i, mouseListeners_->size());
  33021. }
  33022. }
  33023. Component* p = parentComponent_;
  33024. while (p != 0)
  33025. {
  33026. if (p->numDeepMouseListeners > 0)
  33027. {
  33028. BailOutChecker checker (this, p);
  33029. for (int i = p->numDeepMouseListeners; --i >= 0;)
  33030. {
  33031. p->mouseListeners_->getUnchecked (i)->mouseDrag (me);
  33032. if (checker.shouldBailOut())
  33033. return;
  33034. i = jmin (i, p->numDeepMouseListeners);
  33035. }
  33036. }
  33037. p = p->parentComponent_;
  33038. }
  33039. }
  33040. }
  33041. void Component::internalMouseMove (MouseInputSource& source, const Point<int>& relativePos, const Time& time)
  33042. {
  33043. Desktop& desktop = Desktop::getInstance();
  33044. BailOutChecker checker (this);
  33045. const MouseEvent me (source, relativePos, source.getCurrentModifiers(),
  33046. this, time, relativePos,
  33047. time, 0, false);
  33048. if (isCurrentlyBlockedByAnotherModalComponent())
  33049. {
  33050. // allow blocked mouse-events to go to global listeners..
  33051. desktop.sendMouseMove();
  33052. }
  33053. else
  33054. {
  33055. flags.mouseOverFlag = true;
  33056. mouseMove (me);
  33057. if (checker.shouldBailOut())
  33058. return;
  33059. desktop.resetTimer();
  33060. desktop.mouseListeners.callChecked (checker, &MouseListener::mouseMove, me);
  33061. if (checker.shouldBailOut())
  33062. return;
  33063. if (mouseListeners_ != 0)
  33064. {
  33065. for (int i = mouseListeners_->size(); --i >= 0;)
  33066. {
  33067. ((MouseListener*) mouseListeners_->getUnchecked (i))->mouseMove (me);
  33068. if (checker.shouldBailOut())
  33069. return;
  33070. i = jmin (i, mouseListeners_->size());
  33071. }
  33072. }
  33073. Component* p = parentComponent_;
  33074. while (p != 0)
  33075. {
  33076. if (p->numDeepMouseListeners > 0)
  33077. {
  33078. BailOutChecker checker (this, p);
  33079. for (int i = p->numDeepMouseListeners; --i >= 0;)
  33080. {
  33081. p->mouseListeners_->getUnchecked (i)->mouseMove (me);
  33082. if (checker.shouldBailOut())
  33083. return;
  33084. i = jmin (i, p->numDeepMouseListeners);
  33085. }
  33086. }
  33087. p = p->parentComponent_;
  33088. }
  33089. }
  33090. }
  33091. void Component::internalMouseWheel (MouseInputSource& source, const Point<int>& relativePos,
  33092. const Time& time, const float amountX, const float amountY)
  33093. {
  33094. Desktop& desktop = Desktop::getInstance();
  33095. BailOutChecker checker (this);
  33096. const float wheelIncrementX = amountX * (1.0f / 256.0f);
  33097. const float wheelIncrementY = amountY * (1.0f / 256.0f);
  33098. const MouseEvent me (source, relativePos, source.getCurrentModifiers(),
  33099. this, time, relativePos, time, 0, false);
  33100. if (isCurrentlyBlockedByAnotherModalComponent())
  33101. {
  33102. // allow blocked mouse-events to go to global listeners..
  33103. desktop.mouseListeners.callChecked (checker, &MouseListener::mouseWheelMove, me, wheelIncrementX, wheelIncrementY);
  33104. }
  33105. else
  33106. {
  33107. mouseWheelMove (me, wheelIncrementX, wheelIncrementY);
  33108. if (checker.shouldBailOut())
  33109. return;
  33110. desktop.mouseListeners.callChecked (checker, &MouseListener::mouseWheelMove, me, wheelIncrementX, wheelIncrementY);
  33111. if (checker.shouldBailOut())
  33112. return;
  33113. if (mouseListeners_ != 0)
  33114. {
  33115. for (int i = mouseListeners_->size(); --i >= 0;)
  33116. {
  33117. ((MouseListener*) mouseListeners_->getUnchecked (i))->mouseWheelMove (me, wheelIncrementX, wheelIncrementY);
  33118. if (checker.shouldBailOut())
  33119. return;
  33120. i = jmin (i, mouseListeners_->size());
  33121. }
  33122. }
  33123. Component* p = parentComponent_;
  33124. while (p != 0)
  33125. {
  33126. if (p->numDeepMouseListeners > 0)
  33127. {
  33128. BailOutChecker checker (this, p);
  33129. for (int i = p->numDeepMouseListeners; --i >= 0;)
  33130. {
  33131. p->mouseListeners_->getUnchecked (i)->mouseWheelMove (me, wheelIncrementX, wheelIncrementY);
  33132. if (checker.shouldBailOut())
  33133. return;
  33134. i = jmin (i, p->numDeepMouseListeners);
  33135. }
  33136. }
  33137. p = p->parentComponent_;
  33138. }
  33139. }
  33140. }
  33141. void Component::sendFakeMouseMove() const
  33142. {
  33143. Desktop::getInstance().getMainMouseSource().triggerFakeMove();
  33144. }
  33145. void Component::broughtToFront()
  33146. {
  33147. }
  33148. void Component::internalBroughtToFront()
  33149. {
  33150. if (! isValidComponent())
  33151. return;
  33152. if (flags.hasHeavyweightPeerFlag)
  33153. Desktop::getInstance().componentBroughtToFront (this);
  33154. BailOutChecker checker (this);
  33155. broughtToFront();
  33156. if (checker.shouldBailOut())
  33157. return;
  33158. componentListeners.callChecked (checker, &ComponentListener::componentBroughtToFront, *this);
  33159. if (checker.shouldBailOut())
  33160. return;
  33161. // When brought to the front and there's a modal component blocking this one,
  33162. // we need to bring the modal one to the front instead..
  33163. Component* const cm = getCurrentlyModalComponent();
  33164. if (cm != 0 && cm->getTopLevelComponent() != getTopLevelComponent())
  33165. bringModalComponentToFront();
  33166. }
  33167. void Component::focusGained (FocusChangeType)
  33168. {
  33169. // base class does nothing
  33170. }
  33171. void Component::internalFocusGain (const FocusChangeType cause)
  33172. {
  33173. SafePointer<Component> safePointer (this);
  33174. focusGained (cause);
  33175. if (safePointer != 0)
  33176. internalChildFocusChange (cause);
  33177. }
  33178. void Component::focusLost (FocusChangeType)
  33179. {
  33180. // base class does nothing
  33181. }
  33182. void Component::internalFocusLoss (const FocusChangeType cause)
  33183. {
  33184. SafePointer<Component> safePointer (this);
  33185. focusLost (focusChangedDirectly);
  33186. if (safePointer != 0)
  33187. internalChildFocusChange (cause);
  33188. }
  33189. void Component::focusOfChildComponentChanged (FocusChangeType /*cause*/)
  33190. {
  33191. // base class does nothing
  33192. }
  33193. void Component::internalChildFocusChange (FocusChangeType cause)
  33194. {
  33195. const bool childIsNowFocused = hasKeyboardFocus (true);
  33196. if (flags.childCompFocusedFlag != childIsNowFocused)
  33197. {
  33198. flags.childCompFocusedFlag = childIsNowFocused;
  33199. SafePointer<Component> safePointer (this);
  33200. focusOfChildComponentChanged (cause);
  33201. if (safePointer == 0)
  33202. return;
  33203. }
  33204. if (parentComponent_ != 0)
  33205. parentComponent_->internalChildFocusChange (cause);
  33206. }
  33207. bool Component::isEnabled() const throw()
  33208. {
  33209. return (! flags.isDisabledFlag)
  33210. && (parentComponent_ == 0 || parentComponent_->isEnabled());
  33211. }
  33212. void Component::setEnabled (const bool shouldBeEnabled)
  33213. {
  33214. if (flags.isDisabledFlag == shouldBeEnabled)
  33215. {
  33216. flags.isDisabledFlag = ! shouldBeEnabled;
  33217. // if any parent components are disabled, setting our flag won't make a difference,
  33218. // so no need to send a change message
  33219. if (parentComponent_ == 0 || parentComponent_->isEnabled())
  33220. sendEnablementChangeMessage();
  33221. }
  33222. }
  33223. void Component::sendEnablementChangeMessage()
  33224. {
  33225. SafePointer<Component> safePointer (this);
  33226. enablementChanged();
  33227. if (safePointer == 0)
  33228. return;
  33229. for (int i = getNumChildComponents(); --i >= 0;)
  33230. {
  33231. Component* const c = getChildComponent (i);
  33232. if (c != 0)
  33233. {
  33234. c->sendEnablementChangeMessage();
  33235. if (safePointer == 0)
  33236. return;
  33237. }
  33238. }
  33239. }
  33240. void Component::enablementChanged()
  33241. {
  33242. }
  33243. void Component::setWantsKeyboardFocus (const bool wantsFocus) throw()
  33244. {
  33245. flags.wantsFocusFlag = wantsFocus;
  33246. }
  33247. void Component::setMouseClickGrabsKeyboardFocus (const bool shouldGrabFocus)
  33248. {
  33249. flags.dontFocusOnMouseClickFlag = ! shouldGrabFocus;
  33250. }
  33251. bool Component::getMouseClickGrabsKeyboardFocus() const throw()
  33252. {
  33253. return ! flags.dontFocusOnMouseClickFlag;
  33254. }
  33255. bool Component::getWantsKeyboardFocus() const throw()
  33256. {
  33257. return flags.wantsFocusFlag && ! flags.isDisabledFlag;
  33258. }
  33259. void Component::setFocusContainer (const bool shouldBeFocusContainer) throw()
  33260. {
  33261. flags.isFocusContainerFlag = shouldBeFocusContainer;
  33262. }
  33263. bool Component::isFocusContainer() const throw()
  33264. {
  33265. return flags.isFocusContainerFlag;
  33266. }
  33267. int Component::getExplicitFocusOrder() const
  33268. {
  33269. return properties ["_jexfo"];
  33270. }
  33271. void Component::setExplicitFocusOrder (const int newFocusOrderIndex)
  33272. {
  33273. properties.set ("_jexfo", newFocusOrderIndex);
  33274. }
  33275. KeyboardFocusTraverser* Component::createFocusTraverser()
  33276. {
  33277. if (flags.isFocusContainerFlag || parentComponent_ == 0)
  33278. return new KeyboardFocusTraverser();
  33279. return parentComponent_->createFocusTraverser();
  33280. }
  33281. void Component::takeKeyboardFocus (const FocusChangeType cause)
  33282. {
  33283. // give the focus to this component
  33284. if (currentlyFocusedComponent != this)
  33285. {
  33286. JUCE_TRY
  33287. {
  33288. // get the focus onto our desktop window
  33289. ComponentPeer* const peer = getPeer();
  33290. if (peer != 0)
  33291. {
  33292. SafePointer<Component> safePointer (this);
  33293. peer->grabFocus();
  33294. if (peer->isFocused() && currentlyFocusedComponent != this)
  33295. {
  33296. Component* const componentLosingFocus = currentlyFocusedComponent;
  33297. currentlyFocusedComponent = this;
  33298. Desktop::getInstance().triggerFocusCallback();
  33299. // call this after setting currentlyFocusedComponent so that the one that's
  33300. // losing it has a chance to see where focus is going
  33301. if (componentLosingFocus->isValidComponent())
  33302. componentLosingFocus->internalFocusLoss (cause);
  33303. if (currentlyFocusedComponent == this)
  33304. {
  33305. focusGained (cause);
  33306. if (safePointer != 0)
  33307. internalChildFocusChange (cause);
  33308. }
  33309. }
  33310. }
  33311. }
  33312. #if JUCE_CATCH_UNHANDLED_EXCEPTIONS
  33313. catch (const std::exception& e)
  33314. {
  33315. currentlyFocusedComponent = 0;
  33316. Desktop::getInstance().triggerFocusCallback();
  33317. JUCEApplication::sendUnhandledException (&e, __FILE__, __LINE__);
  33318. }
  33319. catch (...)
  33320. {
  33321. currentlyFocusedComponent = 0;
  33322. Desktop::getInstance().triggerFocusCallback();
  33323. JUCEApplication::sendUnhandledException (0, __FILE__, __LINE__);
  33324. }
  33325. #endif
  33326. }
  33327. }
  33328. void Component::grabFocusInternal (const FocusChangeType cause, const bool canTryParent)
  33329. {
  33330. if (isShowing())
  33331. {
  33332. if (flags.wantsFocusFlag && (isEnabled() || parentComponent_ == 0))
  33333. {
  33334. takeKeyboardFocus (cause);
  33335. }
  33336. else
  33337. {
  33338. if (isParentOf (currentlyFocusedComponent)
  33339. && currentlyFocusedComponent->isShowing())
  33340. {
  33341. // do nothing if the focused component is actually a child of ours..
  33342. }
  33343. else
  33344. {
  33345. // find the default child component..
  33346. ScopedPointer <KeyboardFocusTraverser> traverser (createFocusTraverser());
  33347. if (traverser != 0)
  33348. {
  33349. Component* const defaultComp = traverser->getDefaultComponent (this);
  33350. traverser = 0;
  33351. if (defaultComp != 0)
  33352. {
  33353. defaultComp->grabFocusInternal (cause, false);
  33354. return;
  33355. }
  33356. }
  33357. if (canTryParent && parentComponent_ != 0)
  33358. {
  33359. // if no children want it and we're allowed to try our parent comp,
  33360. // then pass up to parent, which will try our siblings.
  33361. parentComponent_->grabFocusInternal (cause, true);
  33362. }
  33363. }
  33364. }
  33365. }
  33366. }
  33367. void Component::grabKeyboardFocus()
  33368. {
  33369. // if component methods are being called from threads other than the message
  33370. // thread, you'll need to use a MessageManagerLock object to make sure it's thread-safe.
  33371. checkMessageManagerIsLocked
  33372. grabFocusInternal (focusChangedDirectly);
  33373. }
  33374. void Component::moveKeyboardFocusToSibling (const bool moveToNext)
  33375. {
  33376. // if component methods are being called from threads other than the message
  33377. // thread, you'll need to use a MessageManagerLock object to make sure it's thread-safe.
  33378. checkMessageManagerIsLocked
  33379. if (parentComponent_ != 0)
  33380. {
  33381. ScopedPointer <KeyboardFocusTraverser> traverser (createFocusTraverser());
  33382. if (traverser != 0)
  33383. {
  33384. Component* const nextComp = moveToNext ? traverser->getNextComponent (this)
  33385. : traverser->getPreviousComponent (this);
  33386. traverser = 0;
  33387. if (nextComp != 0)
  33388. {
  33389. if (nextComp->isCurrentlyBlockedByAnotherModalComponent())
  33390. {
  33391. SafePointer<Component> nextCompPointer (nextComp);
  33392. internalModalInputAttempt();
  33393. if (nextCompPointer == 0 || nextComp->isCurrentlyBlockedByAnotherModalComponent())
  33394. return;
  33395. }
  33396. nextComp->grabFocusInternal (focusChangedByTabKey);
  33397. return;
  33398. }
  33399. }
  33400. parentComponent_->moveKeyboardFocusToSibling (moveToNext);
  33401. }
  33402. }
  33403. bool Component::hasKeyboardFocus (const bool trueIfChildIsFocused) const
  33404. {
  33405. return (currentlyFocusedComponent == this)
  33406. || (trueIfChildIsFocused && isParentOf (currentlyFocusedComponent));
  33407. }
  33408. Component* JUCE_CALLTYPE Component::getCurrentlyFocusedComponent() throw()
  33409. {
  33410. return currentlyFocusedComponent;
  33411. }
  33412. void Component::giveAwayFocus()
  33413. {
  33414. // use a copy so we can clear the value before the call
  33415. Component* const componentLosingFocus = currentlyFocusedComponent;
  33416. currentlyFocusedComponent = 0;
  33417. Desktop::getInstance().triggerFocusCallback();
  33418. if (componentLosingFocus->isValidComponent())
  33419. componentLosingFocus->internalFocusLoss (focusChangedDirectly);
  33420. }
  33421. bool Component::isMouseOver() const throw()
  33422. {
  33423. return flags.mouseOverFlag;
  33424. }
  33425. bool Component::isMouseButtonDown() const throw()
  33426. {
  33427. return flags.draggingFlag;
  33428. }
  33429. bool Component::isMouseOverOrDragging() const throw()
  33430. {
  33431. return flags.mouseOverFlag || flags.draggingFlag;
  33432. }
  33433. bool JUCE_CALLTYPE Component::isMouseButtonDownAnywhere() throw()
  33434. {
  33435. return ModifierKeys::getCurrentModifiers().isAnyMouseButtonDown();
  33436. }
  33437. const Point<int> Component::getMouseXYRelative() const
  33438. {
  33439. return globalPositionToRelative (Desktop::getMousePosition());
  33440. }
  33441. const Rectangle<int> Component::getParentMonitorArea() const
  33442. {
  33443. return Desktop::getInstance()
  33444. .getMonitorAreaContaining (relativePositionToGlobal (Point<int> (getWidth() / 2,
  33445. getHeight() / 2)));
  33446. }
  33447. void Component::addKeyListener (KeyListener* const newListener)
  33448. {
  33449. if (keyListeners_ == 0)
  33450. keyListeners_ = new VoidArray();
  33451. keyListeners_->addIfNotAlreadyThere (newListener);
  33452. }
  33453. void Component::removeKeyListener (KeyListener* const listenerToRemove)
  33454. {
  33455. if (keyListeners_ != 0)
  33456. keyListeners_->removeValue (listenerToRemove);
  33457. }
  33458. bool Component::keyPressed (const KeyPress&)
  33459. {
  33460. return false;
  33461. }
  33462. bool Component::keyStateChanged (const bool /*isKeyDown*/)
  33463. {
  33464. return false;
  33465. }
  33466. void Component::modifierKeysChanged (const ModifierKeys& modifiers)
  33467. {
  33468. if (parentComponent_ != 0)
  33469. parentComponent_->modifierKeysChanged (modifiers);
  33470. }
  33471. void Component::internalModifierKeysChanged()
  33472. {
  33473. sendFakeMouseMove();
  33474. modifierKeysChanged (ModifierKeys::getCurrentModifiers());
  33475. }
  33476. ComponentPeer* Component::getPeer() const
  33477. {
  33478. if (flags.hasHeavyweightPeerFlag)
  33479. return ComponentPeer::getPeerFor (this);
  33480. else if (parentComponent_ != 0)
  33481. return parentComponent_->getPeer();
  33482. else
  33483. return 0;
  33484. }
  33485. Component::BailOutChecker::BailOutChecker (Component* const component1, Component* const component2_)
  33486. : safePointer1 (component1), safePointer2 (component2_), component2 (component2_)
  33487. {
  33488. jassert (component1 != 0);
  33489. }
  33490. bool Component::BailOutChecker::shouldBailOut() const throw()
  33491. {
  33492. return safePointer1 == 0 || safePointer2.getComponent() != component2;
  33493. }
  33494. END_JUCE_NAMESPACE
  33495. /*** End of inlined file: juce_Component.cpp ***/
  33496. /*** Start of inlined file: juce_ComponentListener.cpp ***/
  33497. BEGIN_JUCE_NAMESPACE
  33498. void ComponentListener::componentMovedOrResized (Component&, bool, bool) {}
  33499. void ComponentListener::componentBroughtToFront (Component&) {}
  33500. void ComponentListener::componentVisibilityChanged (Component&) {}
  33501. void ComponentListener::componentChildrenChanged (Component&) {}
  33502. void ComponentListener::componentParentHierarchyChanged (Component&) {}
  33503. void ComponentListener::componentNameChanged (Component&) {}
  33504. void ComponentListener::componentBeingDeleted (Component&) {}
  33505. END_JUCE_NAMESPACE
  33506. /*** End of inlined file: juce_ComponentListener.cpp ***/
  33507. /*** Start of inlined file: juce_Desktop.cpp ***/
  33508. BEGIN_JUCE_NAMESPACE
  33509. Desktop::Desktop()
  33510. : mouseClickCounter (0),
  33511. kioskModeComponent (0)
  33512. {
  33513. createMouseInputSources();
  33514. refreshMonitorSizes();
  33515. }
  33516. Desktop::~Desktop()
  33517. {
  33518. jassert (instance == this);
  33519. instance = 0;
  33520. // doh! If you don't delete all your windows before exiting, you're going to
  33521. // be leaking memory!
  33522. jassert (desktopComponents.size() == 0);
  33523. }
  33524. Desktop& JUCE_CALLTYPE Desktop::getInstance()
  33525. {
  33526. if (instance == 0)
  33527. instance = new Desktop();
  33528. return *instance;
  33529. }
  33530. Desktop* Desktop::instance = 0;
  33531. extern void juce_updateMultiMonitorInfo (Array <Rectangle<int> >& monitorCoords,
  33532. const bool clipToWorkArea);
  33533. void Desktop::refreshMonitorSizes()
  33534. {
  33535. const Array <Rectangle<int> > oldClipped (monitorCoordsClipped);
  33536. const Array <Rectangle<int> > oldUnclipped (monitorCoordsUnclipped);
  33537. monitorCoordsClipped.clear();
  33538. monitorCoordsUnclipped.clear();
  33539. juce_updateMultiMonitorInfo (monitorCoordsClipped, true);
  33540. juce_updateMultiMonitorInfo (monitorCoordsUnclipped, false);
  33541. jassert (monitorCoordsClipped.size() > 0
  33542. && monitorCoordsClipped.size() == monitorCoordsUnclipped.size());
  33543. if (oldClipped != monitorCoordsClipped
  33544. || oldUnclipped != monitorCoordsUnclipped)
  33545. {
  33546. for (int i = ComponentPeer::getNumPeers(); --i >= 0;)
  33547. {
  33548. ComponentPeer* const p = ComponentPeer::getPeer (i);
  33549. if (p != 0)
  33550. p->handleScreenSizeChange();
  33551. }
  33552. }
  33553. }
  33554. int Desktop::getNumDisplayMonitors() const throw()
  33555. {
  33556. return monitorCoordsClipped.size();
  33557. }
  33558. const Rectangle<int> Desktop::getDisplayMonitorCoordinates (const int index, const bool clippedToWorkArea) const throw()
  33559. {
  33560. return clippedToWorkArea ? monitorCoordsClipped [index]
  33561. : monitorCoordsUnclipped [index];
  33562. }
  33563. const RectangleList Desktop::getAllMonitorDisplayAreas (const bool clippedToWorkArea) const throw()
  33564. {
  33565. RectangleList rl;
  33566. for (int i = 0; i < getNumDisplayMonitors(); ++i)
  33567. rl.addWithoutMerging (getDisplayMonitorCoordinates (i, clippedToWorkArea));
  33568. return rl;
  33569. }
  33570. const Rectangle<int> Desktop::getMainMonitorArea (const bool clippedToWorkArea) const throw()
  33571. {
  33572. return getDisplayMonitorCoordinates (0, clippedToWorkArea);
  33573. }
  33574. const Rectangle<int> Desktop::getMonitorAreaContaining (const Point<int>& position, const bool clippedToWorkArea) const
  33575. {
  33576. Rectangle<int> best (getMainMonitorArea (clippedToWorkArea));
  33577. double bestDistance = 1.0e10;
  33578. for (int i = getNumDisplayMonitors(); --i >= 0;)
  33579. {
  33580. const Rectangle<int> rect (getDisplayMonitorCoordinates (i, clippedToWorkArea));
  33581. if (rect.contains (position))
  33582. return rect;
  33583. const double distance = rect.getCentre().getDistanceFrom (position);
  33584. if (distance < bestDistance)
  33585. {
  33586. bestDistance = distance;
  33587. best = rect;
  33588. }
  33589. }
  33590. return best;
  33591. }
  33592. int Desktop::getNumComponents() const throw()
  33593. {
  33594. return desktopComponents.size();
  33595. }
  33596. Component* Desktop::getComponent (const int index) const throw()
  33597. {
  33598. return desktopComponents [index];
  33599. }
  33600. Component* Desktop::findComponentAt (const Point<int>& screenPosition) const
  33601. {
  33602. for (int i = desktopComponents.size(); --i >= 0;)
  33603. {
  33604. Component* const c = desktopComponents.getUnchecked(i);
  33605. const Point<int> relative (c->globalPositionToRelative (screenPosition));
  33606. if (c->contains (relative.getX(), relative.getY()))
  33607. return c->getComponentAt (relative.getX(), relative.getY());
  33608. }
  33609. return 0;
  33610. }
  33611. void Desktop::addDesktopComponent (Component* const c)
  33612. {
  33613. jassert (c != 0);
  33614. jassert (! desktopComponents.contains (c));
  33615. desktopComponents.addIfNotAlreadyThere (c);
  33616. }
  33617. void Desktop::removeDesktopComponent (Component* const c)
  33618. {
  33619. desktopComponents.removeValue (c);
  33620. }
  33621. void Desktop::componentBroughtToFront (Component* const c)
  33622. {
  33623. const int index = desktopComponents.indexOf (c);
  33624. jassert (index >= 0);
  33625. if (index >= 0)
  33626. {
  33627. int newIndex = -1;
  33628. if (! c->isAlwaysOnTop())
  33629. {
  33630. newIndex = desktopComponents.size();
  33631. while (newIndex > 0 && desktopComponents.getUnchecked (newIndex - 1)->isAlwaysOnTop())
  33632. --newIndex;
  33633. --newIndex;
  33634. }
  33635. desktopComponents.move (index, newIndex);
  33636. }
  33637. }
  33638. const Point<int> Desktop::getLastMouseDownPosition() throw()
  33639. {
  33640. return getInstance().getMainMouseSource().getLastMouseDownPosition();
  33641. }
  33642. int Desktop::getMouseButtonClickCounter() throw()
  33643. {
  33644. return getInstance().mouseClickCounter;
  33645. }
  33646. void Desktop::incrementMouseClickCounter() throw()
  33647. {
  33648. ++mouseClickCounter;
  33649. }
  33650. int Desktop::getNumDraggingMouseSources() const throw()
  33651. {
  33652. int num = 0;
  33653. for (int i = mouseSources.size(); --i >= 0;)
  33654. if (mouseSources.getUnchecked(i)->isDragging())
  33655. ++num;
  33656. return num;
  33657. }
  33658. MouseInputSource* Desktop::getDraggingMouseSource (int index) const throw()
  33659. {
  33660. int num = 0;
  33661. for (int i = mouseSources.size(); --i >= 0;)
  33662. {
  33663. MouseInputSource* const mi = mouseSources.getUnchecked(i);
  33664. if (mi->isDragging())
  33665. {
  33666. if (index == num)
  33667. return mi;
  33668. ++num;
  33669. }
  33670. }
  33671. return 0;
  33672. }
  33673. void Desktop::addFocusChangeListener (FocusChangeListener* const listener)
  33674. {
  33675. focusListeners.add (listener);
  33676. }
  33677. void Desktop::removeFocusChangeListener (FocusChangeListener* const listener)
  33678. {
  33679. focusListeners.remove (listener);
  33680. }
  33681. void Desktop::triggerFocusCallback()
  33682. {
  33683. triggerAsyncUpdate();
  33684. }
  33685. void Desktop::handleAsyncUpdate()
  33686. {
  33687. Component* currentFocus = Component::getCurrentlyFocusedComponent();
  33688. focusListeners.call (&FocusChangeListener::globalFocusChanged, currentFocus);
  33689. }
  33690. void Desktop::addGlobalMouseListener (MouseListener* const listener)
  33691. {
  33692. mouseListeners.add (listener);
  33693. resetTimer();
  33694. }
  33695. void Desktop::removeGlobalMouseListener (MouseListener* const listener)
  33696. {
  33697. mouseListeners.remove (listener);
  33698. resetTimer();
  33699. }
  33700. void Desktop::timerCallback()
  33701. {
  33702. if (lastFakeMouseMove != getMousePosition())
  33703. sendMouseMove();
  33704. }
  33705. void Desktop::sendMouseMove()
  33706. {
  33707. if (! mouseListeners.isEmpty())
  33708. {
  33709. startTimer (20);
  33710. lastFakeMouseMove = getMousePosition();
  33711. Component* const target = findComponentAt (lastFakeMouseMove);
  33712. if (target != 0)
  33713. {
  33714. Component::BailOutChecker checker (target);
  33715. const Point<int> pos (target->globalPositionToRelative (lastFakeMouseMove));
  33716. const Time now (Time::getCurrentTime());
  33717. const MouseEvent me (getMainMouseSource(), pos, ModifierKeys::getCurrentModifiers(),
  33718. target, now, pos, now, 0, false);
  33719. if (me.mods.isAnyMouseButtonDown())
  33720. mouseListeners.callChecked (checker, &MouseListener::mouseDrag, me);
  33721. else
  33722. mouseListeners.callChecked (checker, &MouseListener::mouseMove, me);
  33723. }
  33724. }
  33725. }
  33726. void Desktop::resetTimer()
  33727. {
  33728. if (mouseListeners.size() == 0)
  33729. stopTimer();
  33730. else
  33731. startTimer (100);
  33732. lastFakeMouseMove = getMousePosition();
  33733. }
  33734. extern void juce_setKioskComponent (Component* kioskModeComponent, bool enableOrDisable, bool allowMenusAndBars);
  33735. void Desktop::setKioskModeComponent (Component* componentToUse, const bool allowMenusAndBars)
  33736. {
  33737. if (kioskModeComponent != componentToUse)
  33738. {
  33739. // agh! Don't delete a component without first stopping it being the kiosk comp
  33740. jassert (kioskModeComponent == 0 || kioskModeComponent->isValidComponent());
  33741. // agh! Don't remove a component from the desktop if it's the kiosk comp!
  33742. jassert (kioskModeComponent == 0 || kioskModeComponent->isOnDesktop());
  33743. if (kioskModeComponent->isValidComponent())
  33744. {
  33745. juce_setKioskComponent (kioskModeComponent, false, allowMenusAndBars);
  33746. kioskModeComponent->setBounds (kioskComponentOriginalBounds);
  33747. }
  33748. kioskModeComponent = componentToUse;
  33749. if (kioskModeComponent != 0)
  33750. {
  33751. jassert (kioskModeComponent->isValidComponent());
  33752. // Only components that are already on the desktop can be put into kiosk mode!
  33753. jassert (kioskModeComponent->isOnDesktop());
  33754. kioskComponentOriginalBounds = kioskModeComponent->getBounds();
  33755. juce_setKioskComponent (kioskModeComponent, true, allowMenusAndBars);
  33756. }
  33757. }
  33758. }
  33759. END_JUCE_NAMESPACE
  33760. /*** End of inlined file: juce_Desktop.cpp ***/
  33761. /*** Start of inlined file: juce_ArrowButton.cpp ***/
  33762. BEGIN_JUCE_NAMESPACE
  33763. ArrowButton::ArrowButton (const String& name,
  33764. float arrowDirectionInRadians,
  33765. const Colour& arrowColour)
  33766. : Button (name),
  33767. colour (arrowColour)
  33768. {
  33769. path.lineTo (0.0f, 1.0f);
  33770. path.lineTo (1.0f, 0.5f);
  33771. path.closeSubPath();
  33772. path.applyTransform (AffineTransform::rotation (float_Pi * 2.0f * arrowDirectionInRadians,
  33773. 0.5f, 0.5f));
  33774. setComponentEffect (&shadow);
  33775. buttonStateChanged();
  33776. }
  33777. ArrowButton::~ArrowButton()
  33778. {
  33779. }
  33780. void ArrowButton::paintButton (Graphics& g,
  33781. bool /*isMouseOverButton*/,
  33782. bool /*isButtonDown*/)
  33783. {
  33784. g.setColour (colour);
  33785. g.fillPath (path, path.getTransformToScaleToFit ((float) offset,
  33786. (float) offset,
  33787. (float) (getWidth() - 3),
  33788. (float) (getHeight() - 3),
  33789. false));
  33790. }
  33791. void ArrowButton::buttonStateChanged()
  33792. {
  33793. offset = (isDown()) ? 1 : 0;
  33794. shadow.setShadowProperties ((isDown()) ? 1.2f : 3.0f,
  33795. 0.3f, -1, 0);
  33796. }
  33797. END_JUCE_NAMESPACE
  33798. /*** End of inlined file: juce_ArrowButton.cpp ***/
  33799. /*** Start of inlined file: juce_Button.cpp ***/
  33800. BEGIN_JUCE_NAMESPACE
  33801. class Button::RepeatTimer : public Timer
  33802. {
  33803. public:
  33804. RepeatTimer (Button& owner_) : owner (owner_) {}
  33805. void timerCallback() { owner.repeatTimerCallback(); }
  33806. juce_UseDebuggingNewOperator
  33807. private:
  33808. Button& owner;
  33809. RepeatTimer (const RepeatTimer&);
  33810. RepeatTimer& operator= (const RepeatTimer&);
  33811. };
  33812. Button::Button (const String& name)
  33813. : Component (name),
  33814. text (name),
  33815. buttonPressTime (0),
  33816. lastTimeCallbackTime (0),
  33817. commandManagerToUse (0),
  33818. autoRepeatDelay (-1),
  33819. autoRepeatSpeed (0),
  33820. autoRepeatMinimumDelay (-1),
  33821. radioGroupId (0),
  33822. commandID (0),
  33823. connectedEdgeFlags (0),
  33824. buttonState (buttonNormal),
  33825. lastToggleState (false),
  33826. clickTogglesState (false),
  33827. needsToRelease (false),
  33828. needsRepainting (false),
  33829. isKeyDown (false),
  33830. triggerOnMouseDown (false),
  33831. generateTooltip (false)
  33832. {
  33833. setWantsKeyboardFocus (true);
  33834. isOn.addListener (this);
  33835. }
  33836. Button::~Button()
  33837. {
  33838. isOn.removeListener (this);
  33839. if (commandManagerToUse != 0)
  33840. commandManagerToUse->removeListener (this);
  33841. repeatTimer = 0;
  33842. clearShortcuts();
  33843. }
  33844. void Button::setButtonText (const String& newText)
  33845. {
  33846. if (text != newText)
  33847. {
  33848. text = newText;
  33849. repaint();
  33850. }
  33851. }
  33852. void Button::setTooltip (const String& newTooltip)
  33853. {
  33854. SettableTooltipClient::setTooltip (newTooltip);
  33855. generateTooltip = false;
  33856. }
  33857. const String Button::getTooltip()
  33858. {
  33859. if (generateTooltip && commandManagerToUse != 0 && commandID != 0)
  33860. {
  33861. String tt (commandManagerToUse->getDescriptionOfCommand (commandID));
  33862. Array <KeyPress> keyPresses (commandManagerToUse->getKeyMappings()->getKeyPressesAssignedToCommand (commandID));
  33863. for (int i = 0; i < keyPresses.size(); ++i)
  33864. {
  33865. const String key (keyPresses.getReference(i).getTextDescription());
  33866. tt << " [";
  33867. if (key.length() == 1)
  33868. tt << TRANS("shortcut") << ": '" << key << "']";
  33869. else
  33870. tt << key << ']';
  33871. }
  33872. return tt;
  33873. }
  33874. return SettableTooltipClient::getTooltip();
  33875. }
  33876. void Button::setConnectedEdges (const int connectedEdgeFlags_)
  33877. {
  33878. if (connectedEdgeFlags != connectedEdgeFlags_)
  33879. {
  33880. connectedEdgeFlags = connectedEdgeFlags_;
  33881. repaint();
  33882. }
  33883. }
  33884. void Button::setToggleState (const bool shouldBeOn,
  33885. const bool sendChangeNotification)
  33886. {
  33887. if (shouldBeOn != lastToggleState)
  33888. {
  33889. isOn = shouldBeOn;
  33890. lastToggleState = shouldBeOn;
  33891. repaint();
  33892. if (sendChangeNotification)
  33893. {
  33894. Component::SafePointer<Component> deletionWatcher (this);
  33895. sendClickMessage (ModifierKeys());
  33896. if (deletionWatcher == 0)
  33897. return;
  33898. }
  33899. if (lastToggleState)
  33900. turnOffOtherButtonsInGroup (sendChangeNotification);
  33901. }
  33902. }
  33903. void Button::setClickingTogglesState (const bool shouldToggle) throw()
  33904. {
  33905. clickTogglesState = shouldToggle;
  33906. // if you've got clickTogglesState turned on, you shouldn't also connect the button
  33907. // up to be a command invoker. Instead, your command handler must flip the state of whatever
  33908. // it is that this button represents, and the button will update its state to reflect this
  33909. // in the applicationCommandListChanged() method.
  33910. jassert (commandManagerToUse == 0 || ! clickTogglesState);
  33911. }
  33912. bool Button::getClickingTogglesState() const throw()
  33913. {
  33914. return clickTogglesState;
  33915. }
  33916. void Button::valueChanged (Value& value)
  33917. {
  33918. if (value.refersToSameSourceAs (isOn))
  33919. setToggleState (isOn.getValue(), true);
  33920. }
  33921. void Button::setRadioGroupId (const int newGroupId)
  33922. {
  33923. if (radioGroupId != newGroupId)
  33924. {
  33925. radioGroupId = newGroupId;
  33926. if (lastToggleState)
  33927. turnOffOtherButtonsInGroup (true);
  33928. }
  33929. }
  33930. void Button::turnOffOtherButtonsInGroup (const bool sendChangeNotification)
  33931. {
  33932. Component* const p = getParentComponent();
  33933. if (p != 0 && radioGroupId != 0)
  33934. {
  33935. Component::SafePointer<Component> deletionWatcher (this);
  33936. for (int i = p->getNumChildComponents(); --i >= 0;)
  33937. {
  33938. Component* const c = p->getChildComponent (i);
  33939. if (c != this)
  33940. {
  33941. Button* const b = dynamic_cast <Button*> (c);
  33942. if (b != 0 && b->getRadioGroupId() == radioGroupId)
  33943. {
  33944. b->setToggleState (false, sendChangeNotification);
  33945. if (deletionWatcher == 0)
  33946. return;
  33947. }
  33948. }
  33949. }
  33950. }
  33951. }
  33952. void Button::enablementChanged()
  33953. {
  33954. updateState (0);
  33955. repaint();
  33956. }
  33957. Button::ButtonState Button::updateState (const MouseEvent* const e)
  33958. {
  33959. ButtonState state = buttonNormal;
  33960. if (isEnabled() && isVisible() && ! isCurrentlyBlockedByAnotherModalComponent())
  33961. {
  33962. Point<int> mousePos;
  33963. if (e == 0)
  33964. mousePos = getMouseXYRelative();
  33965. else
  33966. mousePos = e->getEventRelativeTo (this).getPosition();
  33967. const bool over = reallyContains (mousePos.getX(), mousePos.getY(), true);
  33968. const bool down = isMouseButtonDown();
  33969. if ((down && (over || (triggerOnMouseDown && buttonState == buttonDown))) || isKeyDown)
  33970. state = buttonDown;
  33971. else if (over)
  33972. state = buttonOver;
  33973. }
  33974. setState (state);
  33975. return state;
  33976. }
  33977. void Button::setState (const ButtonState newState)
  33978. {
  33979. if (buttonState != newState)
  33980. {
  33981. buttonState = newState;
  33982. repaint();
  33983. if (buttonState == buttonDown)
  33984. {
  33985. buttonPressTime = Time::getApproximateMillisecondCounter();
  33986. lastTimeCallbackTime = buttonPressTime;
  33987. }
  33988. sendStateMessage();
  33989. }
  33990. }
  33991. bool Button::isDown() const throw()
  33992. {
  33993. return buttonState == buttonDown;
  33994. }
  33995. bool Button::isOver() const throw()
  33996. {
  33997. return buttonState != buttonNormal;
  33998. }
  33999. void Button::buttonStateChanged()
  34000. {
  34001. }
  34002. uint32 Button::getMillisecondsSinceButtonDown() const throw()
  34003. {
  34004. const uint32 now = Time::getApproximateMillisecondCounter();
  34005. return now > buttonPressTime ? now - buttonPressTime : 0;
  34006. }
  34007. void Button::setTriggeredOnMouseDown (const bool isTriggeredOnMouseDown) throw()
  34008. {
  34009. triggerOnMouseDown = isTriggeredOnMouseDown;
  34010. }
  34011. void Button::clicked()
  34012. {
  34013. }
  34014. void Button::clicked (const ModifierKeys& /*modifiers*/)
  34015. {
  34016. clicked();
  34017. }
  34018. static const int clickMessageId = 0x2f3f4f99;
  34019. void Button::triggerClick()
  34020. {
  34021. postCommandMessage (clickMessageId);
  34022. }
  34023. void Button::internalClickCallback (const ModifierKeys& modifiers)
  34024. {
  34025. if (clickTogglesState)
  34026. setToggleState ((radioGroupId != 0) || ! lastToggleState, false);
  34027. sendClickMessage (modifiers);
  34028. }
  34029. void Button::flashButtonState()
  34030. {
  34031. if (isEnabled())
  34032. {
  34033. needsToRelease = true;
  34034. setState (buttonDown);
  34035. getRepeatTimer().startTimer (100);
  34036. }
  34037. }
  34038. void Button::handleCommandMessage (int commandId)
  34039. {
  34040. if (commandId == clickMessageId)
  34041. {
  34042. if (isEnabled())
  34043. {
  34044. flashButtonState();
  34045. internalClickCallback (ModifierKeys::getCurrentModifiers());
  34046. }
  34047. }
  34048. else
  34049. {
  34050. Component::handleCommandMessage (commandId);
  34051. }
  34052. }
  34053. void Button::addButtonListener (ButtonListener* const newListener)
  34054. {
  34055. buttonListeners.add (newListener);
  34056. }
  34057. void Button::removeButtonListener (ButtonListener* const listener)
  34058. {
  34059. buttonListeners.remove (listener);
  34060. }
  34061. void Button::sendClickMessage (const ModifierKeys& modifiers)
  34062. {
  34063. Component::BailOutChecker checker (this);
  34064. if (commandManagerToUse != 0 && commandID != 0)
  34065. {
  34066. ApplicationCommandTarget::InvocationInfo info (commandID);
  34067. info.invocationMethod = ApplicationCommandTarget::InvocationInfo::fromButton;
  34068. info.originatingComponent = this;
  34069. commandManagerToUse->invoke (info, true);
  34070. }
  34071. clicked (modifiers);
  34072. if (! checker.shouldBailOut())
  34073. buttonListeners.callChecked (checker, &ButtonListener::buttonClicked, this);
  34074. }
  34075. void Button::sendStateMessage()
  34076. {
  34077. Component::BailOutChecker checker (this);
  34078. buttonStateChanged();
  34079. if (! checker.shouldBailOut())
  34080. buttonListeners.callChecked (checker, &ButtonListener::buttonStateChanged, this);
  34081. }
  34082. void Button::paint (Graphics& g)
  34083. {
  34084. if (needsToRelease && isEnabled())
  34085. {
  34086. needsToRelease = false;
  34087. needsRepainting = true;
  34088. }
  34089. paintButton (g, isOver(), isDown());
  34090. }
  34091. void Button::mouseEnter (const MouseEvent& e)
  34092. {
  34093. updateState (&e);
  34094. }
  34095. void Button::mouseExit (const MouseEvent& e)
  34096. {
  34097. updateState (&e);
  34098. }
  34099. void Button::mouseDown (const MouseEvent& e)
  34100. {
  34101. updateState (&e);
  34102. if (isDown())
  34103. {
  34104. if (autoRepeatDelay >= 0)
  34105. getRepeatTimer().startTimer (autoRepeatDelay);
  34106. if (triggerOnMouseDown)
  34107. internalClickCallback (e.mods);
  34108. }
  34109. }
  34110. void Button::mouseUp (const MouseEvent& e)
  34111. {
  34112. const bool wasDown = isDown();
  34113. updateState (&e);
  34114. if (wasDown && isOver() && ! triggerOnMouseDown)
  34115. internalClickCallback (e.mods);
  34116. }
  34117. void Button::mouseDrag (const MouseEvent& e)
  34118. {
  34119. const ButtonState oldState = buttonState;
  34120. updateState (&e);
  34121. if (autoRepeatDelay >= 0 && buttonState != oldState && isDown())
  34122. getRepeatTimer().startTimer (autoRepeatSpeed);
  34123. }
  34124. void Button::focusGained (FocusChangeType)
  34125. {
  34126. updateState (0);
  34127. repaint();
  34128. }
  34129. void Button::focusLost (FocusChangeType)
  34130. {
  34131. updateState (0);
  34132. repaint();
  34133. }
  34134. void Button::setVisible (bool shouldBeVisible)
  34135. {
  34136. if (shouldBeVisible != isVisible())
  34137. {
  34138. Component::setVisible (shouldBeVisible);
  34139. if (! shouldBeVisible)
  34140. needsToRelease = false;
  34141. updateState (0);
  34142. }
  34143. else
  34144. {
  34145. Component::setVisible (shouldBeVisible);
  34146. }
  34147. }
  34148. void Button::parentHierarchyChanged()
  34149. {
  34150. Component* const newKeySource = (shortcuts.size() == 0) ? 0 : getTopLevelComponent();
  34151. if (newKeySource != keySource.getComponent())
  34152. {
  34153. if (keySource != 0)
  34154. keySource->removeKeyListener (this);
  34155. keySource = newKeySource;
  34156. if (keySource != 0)
  34157. keySource->addKeyListener (this);
  34158. }
  34159. }
  34160. void Button::setCommandToTrigger (ApplicationCommandManager* const commandManagerToUse_,
  34161. const int commandID_,
  34162. const bool generateTooltip_)
  34163. {
  34164. commandID = commandID_;
  34165. generateTooltip = generateTooltip_;
  34166. if (commandManagerToUse != commandManagerToUse_)
  34167. {
  34168. if (commandManagerToUse != 0)
  34169. commandManagerToUse->removeListener (this);
  34170. commandManagerToUse = commandManagerToUse_;
  34171. if (commandManagerToUse != 0)
  34172. commandManagerToUse->addListener (this);
  34173. // if you've got clickTogglesState turned on, you shouldn't also connect the button
  34174. // up to be a command invoker. Instead, your command handler must flip the state of whatever
  34175. // it is that this button represents, and the button will update its state to reflect this
  34176. // in the applicationCommandListChanged() method.
  34177. jassert (commandManagerToUse == 0 || ! clickTogglesState);
  34178. }
  34179. if (commandManagerToUse != 0)
  34180. applicationCommandListChanged();
  34181. else
  34182. setEnabled (true);
  34183. }
  34184. void Button::applicationCommandInvoked (const ApplicationCommandTarget::InvocationInfo& info)
  34185. {
  34186. if (info.commandID == commandID
  34187. && (info.commandFlags & ApplicationCommandInfo::dontTriggerVisualFeedback) == 0)
  34188. {
  34189. flashButtonState();
  34190. }
  34191. }
  34192. void Button::applicationCommandListChanged()
  34193. {
  34194. if (commandManagerToUse != 0)
  34195. {
  34196. ApplicationCommandInfo info (0);
  34197. ApplicationCommandTarget* const target = commandManagerToUse->getTargetForCommand (commandID, info);
  34198. setEnabled (target != 0 && (info.flags & ApplicationCommandInfo::isDisabled) == 0);
  34199. if (target != 0)
  34200. setToggleState ((info.flags & ApplicationCommandInfo::isTicked) != 0, false);
  34201. }
  34202. }
  34203. void Button::addShortcut (const KeyPress& key)
  34204. {
  34205. if (key.isValid())
  34206. {
  34207. jassert (! isRegisteredForShortcut (key)); // already registered!
  34208. shortcuts.add (key);
  34209. parentHierarchyChanged();
  34210. }
  34211. }
  34212. void Button::clearShortcuts()
  34213. {
  34214. shortcuts.clear();
  34215. parentHierarchyChanged();
  34216. }
  34217. bool Button::isShortcutPressed() const
  34218. {
  34219. if (! isCurrentlyBlockedByAnotherModalComponent())
  34220. {
  34221. for (int i = shortcuts.size(); --i >= 0;)
  34222. if (shortcuts.getReference(i).isCurrentlyDown())
  34223. return true;
  34224. }
  34225. return false;
  34226. }
  34227. bool Button::isRegisteredForShortcut (const KeyPress& key) const
  34228. {
  34229. for (int i = shortcuts.size(); --i >= 0;)
  34230. if (key == shortcuts.getReference(i))
  34231. return true;
  34232. return false;
  34233. }
  34234. bool Button::keyStateChanged (const bool, Component*)
  34235. {
  34236. if (! isEnabled())
  34237. return false;
  34238. const bool wasDown = isKeyDown;
  34239. isKeyDown = isShortcutPressed();
  34240. if (autoRepeatDelay >= 0 && (isKeyDown && ! wasDown))
  34241. getRepeatTimer().startTimer (autoRepeatDelay);
  34242. updateState (0);
  34243. if (isEnabled() && wasDown && ! isKeyDown)
  34244. {
  34245. internalClickCallback (ModifierKeys::getCurrentModifiers());
  34246. // (return immediately - this button may now have been deleted)
  34247. return true;
  34248. }
  34249. return wasDown || isKeyDown;
  34250. }
  34251. bool Button::keyPressed (const KeyPress&, Component*)
  34252. {
  34253. // returning true will avoid forwarding events for keys that we're using as shortcuts
  34254. return isShortcutPressed();
  34255. }
  34256. bool Button::keyPressed (const KeyPress& key)
  34257. {
  34258. if (isEnabled() && key.isKeyCode (KeyPress::returnKey))
  34259. {
  34260. triggerClick();
  34261. return true;
  34262. }
  34263. return false;
  34264. }
  34265. void Button::setRepeatSpeed (const int initialDelayMillisecs,
  34266. const int repeatMillisecs,
  34267. const int minimumDelayInMillisecs) throw()
  34268. {
  34269. autoRepeatDelay = initialDelayMillisecs;
  34270. autoRepeatSpeed = repeatMillisecs;
  34271. autoRepeatMinimumDelay = jmin (autoRepeatSpeed, minimumDelayInMillisecs);
  34272. }
  34273. void Button::repeatTimerCallback()
  34274. {
  34275. if (needsRepainting)
  34276. {
  34277. getRepeatTimer().stopTimer();
  34278. updateState (0);
  34279. needsRepainting = false;
  34280. }
  34281. else if (autoRepeatSpeed > 0 && (isKeyDown || (updateState (0) == buttonDown)))
  34282. {
  34283. int repeatSpeed = autoRepeatSpeed;
  34284. if (autoRepeatMinimumDelay >= 0)
  34285. {
  34286. double timeHeldDown = jmin (1.0, getMillisecondsSinceButtonDown() / 4000.0);
  34287. timeHeldDown *= timeHeldDown;
  34288. repeatSpeed = repeatSpeed + (int) (timeHeldDown * (autoRepeatMinimumDelay - repeatSpeed));
  34289. }
  34290. repeatSpeed = jmax (1, repeatSpeed);
  34291. getRepeatTimer().startTimer (repeatSpeed);
  34292. const uint32 now = Time::getApproximateMillisecondCounter();
  34293. const int numTimesToCallback = (now > lastTimeCallbackTime) ? jmax (1, (int) (now - lastTimeCallbackTime) / repeatSpeed) : 1;
  34294. lastTimeCallbackTime = now;
  34295. Component::SafePointer<Component> deletionWatcher (this);
  34296. for (int i = numTimesToCallback; --i >= 0;)
  34297. {
  34298. internalClickCallback (ModifierKeys::getCurrentModifiers());
  34299. if (deletionWatcher == 0 || ! isDown())
  34300. return;
  34301. }
  34302. }
  34303. else if (! needsToRelease)
  34304. {
  34305. getRepeatTimer().stopTimer();
  34306. }
  34307. }
  34308. Button::RepeatTimer& Button::getRepeatTimer()
  34309. {
  34310. if (repeatTimer == 0)
  34311. repeatTimer = new RepeatTimer (*this);
  34312. return *repeatTimer;
  34313. }
  34314. END_JUCE_NAMESPACE
  34315. /*** End of inlined file: juce_Button.cpp ***/
  34316. /*** Start of inlined file: juce_DrawableButton.cpp ***/
  34317. BEGIN_JUCE_NAMESPACE
  34318. DrawableButton::DrawableButton (const String& name,
  34319. const DrawableButton::ButtonStyle buttonStyle)
  34320. : Button (name),
  34321. style (buttonStyle),
  34322. edgeIndent (3)
  34323. {
  34324. if (buttonStyle == ImageOnButtonBackground)
  34325. {
  34326. backgroundOff = Colour (0xffbbbbff);
  34327. backgroundOn = Colour (0xff3333ff);
  34328. }
  34329. else
  34330. {
  34331. backgroundOff = Colours::transparentBlack;
  34332. backgroundOn = Colour (0xaabbbbff);
  34333. }
  34334. }
  34335. DrawableButton::~DrawableButton()
  34336. {
  34337. deleteImages();
  34338. }
  34339. void DrawableButton::deleteImages()
  34340. {
  34341. }
  34342. void DrawableButton::setImages (const Drawable* normal,
  34343. const Drawable* over,
  34344. const Drawable* down,
  34345. const Drawable* disabled,
  34346. const Drawable* normalOn,
  34347. const Drawable* overOn,
  34348. const Drawable* downOn,
  34349. const Drawable* disabledOn)
  34350. {
  34351. deleteImages();
  34352. jassert (normal != 0); // you really need to give it at least a normal image..
  34353. if (normal != 0)
  34354. normalImage = normal->createCopy();
  34355. if (over != 0)
  34356. overImage = over->createCopy();
  34357. if (down != 0)
  34358. downImage = down->createCopy();
  34359. if (disabled != 0)
  34360. disabledImage = disabled->createCopy();
  34361. if (normalOn != 0)
  34362. normalImageOn = normalOn->createCopy();
  34363. if (overOn != 0)
  34364. overImageOn = overOn->createCopy();
  34365. if (downOn != 0)
  34366. downImageOn = downOn->createCopy();
  34367. if (disabledOn != 0)
  34368. disabledImageOn = disabledOn->createCopy();
  34369. repaint();
  34370. }
  34371. void DrawableButton::setButtonStyle (const DrawableButton::ButtonStyle newStyle)
  34372. {
  34373. if (style != newStyle)
  34374. {
  34375. style = newStyle;
  34376. repaint();
  34377. }
  34378. }
  34379. void DrawableButton::setBackgroundColours (const Colour& toggledOffColour,
  34380. const Colour& toggledOnColour)
  34381. {
  34382. if (backgroundOff != toggledOffColour
  34383. || backgroundOn != toggledOnColour)
  34384. {
  34385. backgroundOff = toggledOffColour;
  34386. backgroundOn = toggledOnColour;
  34387. repaint();
  34388. }
  34389. }
  34390. const Colour& DrawableButton::getBackgroundColour() const throw()
  34391. {
  34392. return getToggleState() ? backgroundOn
  34393. : backgroundOff;
  34394. }
  34395. void DrawableButton::setEdgeIndent (const int numPixelsIndent)
  34396. {
  34397. edgeIndent = numPixelsIndent;
  34398. repaint();
  34399. }
  34400. void DrawableButton::paintButton (Graphics& g,
  34401. bool isMouseOverButton,
  34402. bool isButtonDown)
  34403. {
  34404. Rectangle<int> imageSpace;
  34405. if (style == ImageOnButtonBackground)
  34406. {
  34407. const int insetX = getWidth() / 4;
  34408. const int insetY = getHeight() / 4;
  34409. imageSpace.setBounds (insetX, insetY, getWidth() - insetX * 2, getHeight() - insetY * 2);
  34410. getLookAndFeel().drawButtonBackground (g, *this,
  34411. getBackgroundColour(),
  34412. isMouseOverButton,
  34413. isButtonDown);
  34414. }
  34415. else
  34416. {
  34417. g.fillAll (getBackgroundColour());
  34418. const int textH = (style == ImageAboveTextLabel)
  34419. ? jmin (16, proportionOfHeight (0.25f))
  34420. : 0;
  34421. const int indentX = jmin (edgeIndent, proportionOfWidth (0.3f));
  34422. const int indentY = jmin (edgeIndent, proportionOfHeight (0.3f));
  34423. imageSpace.setBounds (indentX, indentY,
  34424. getWidth() - indentX * 2,
  34425. getHeight() - indentY * 2 - textH);
  34426. if (textH > 0)
  34427. {
  34428. g.setFont ((float) textH);
  34429. g.setColour (Colours::black.withAlpha (isEnabled() ? 1.0f : 0.4f));
  34430. g.drawFittedText (getButtonText(),
  34431. 2, getHeight() - textH - 1,
  34432. getWidth() - 4, textH,
  34433. Justification::centred, 1);
  34434. }
  34435. }
  34436. g.setImageResamplingQuality (Graphics::mediumResamplingQuality);
  34437. g.setOpacity (1.0f);
  34438. const Drawable* imageToDraw = 0;
  34439. if (isEnabled())
  34440. {
  34441. imageToDraw = getCurrentImage();
  34442. }
  34443. else
  34444. {
  34445. imageToDraw = getToggleState() ? disabledImageOn
  34446. : disabledImage;
  34447. if (imageToDraw == 0)
  34448. {
  34449. g.setOpacity (0.4f);
  34450. imageToDraw = getNormalImage();
  34451. }
  34452. }
  34453. if (imageToDraw != 0)
  34454. {
  34455. if (style == ImageRaw)
  34456. {
  34457. imageToDraw->draw (g, 1.0f);
  34458. }
  34459. else
  34460. {
  34461. imageToDraw->drawWithin (g,
  34462. imageSpace.getX(),
  34463. imageSpace.getY(),
  34464. imageSpace.getWidth(),
  34465. imageSpace.getHeight(),
  34466. RectanglePlacement::centred,
  34467. 1.0f);
  34468. }
  34469. }
  34470. }
  34471. const Drawable* DrawableButton::getCurrentImage() const throw()
  34472. {
  34473. if (isDown())
  34474. return getDownImage();
  34475. if (isOver())
  34476. return getOverImage();
  34477. return getNormalImage();
  34478. }
  34479. const Drawable* DrawableButton::getNormalImage() const throw()
  34480. {
  34481. return (getToggleState() && normalImageOn != 0) ? normalImageOn
  34482. : normalImage;
  34483. }
  34484. const Drawable* DrawableButton::getOverImage() const throw()
  34485. {
  34486. const Drawable* d = normalImage;
  34487. if (getToggleState())
  34488. {
  34489. if (overImageOn != 0)
  34490. d = overImageOn;
  34491. else if (normalImageOn != 0)
  34492. d = normalImageOn;
  34493. else if (overImage != 0)
  34494. d = overImage;
  34495. }
  34496. else
  34497. {
  34498. if (overImage != 0)
  34499. d = overImage;
  34500. }
  34501. return d;
  34502. }
  34503. const Drawable* DrawableButton::getDownImage() const throw()
  34504. {
  34505. const Drawable* d = normalImage;
  34506. if (getToggleState())
  34507. {
  34508. if (downImageOn != 0)
  34509. d = downImageOn;
  34510. else if (overImageOn != 0)
  34511. d = overImageOn;
  34512. else if (normalImageOn != 0)
  34513. d = normalImageOn;
  34514. else if (downImage != 0)
  34515. d = downImage;
  34516. else
  34517. d = getOverImage();
  34518. }
  34519. else
  34520. {
  34521. if (downImage != 0)
  34522. d = downImage;
  34523. else
  34524. d = getOverImage();
  34525. }
  34526. return d;
  34527. }
  34528. END_JUCE_NAMESPACE
  34529. /*** End of inlined file: juce_DrawableButton.cpp ***/
  34530. /*** Start of inlined file: juce_HyperlinkButton.cpp ***/
  34531. BEGIN_JUCE_NAMESPACE
  34532. HyperlinkButton::HyperlinkButton (const String& linkText,
  34533. const URL& linkURL)
  34534. : Button (linkText),
  34535. url (linkURL),
  34536. font (14.0f, Font::underlined),
  34537. resizeFont (true),
  34538. justification (Justification::centred)
  34539. {
  34540. setMouseCursor (MouseCursor::PointingHandCursor);
  34541. setTooltip (linkURL.toString (false));
  34542. }
  34543. HyperlinkButton::~HyperlinkButton()
  34544. {
  34545. }
  34546. void HyperlinkButton::setFont (const Font& newFont,
  34547. const bool resizeToMatchComponentHeight,
  34548. const Justification& justificationType)
  34549. {
  34550. font = newFont;
  34551. resizeFont = resizeToMatchComponentHeight;
  34552. justification = justificationType;
  34553. repaint();
  34554. }
  34555. void HyperlinkButton::setURL (const URL& newURL) throw()
  34556. {
  34557. url = newURL;
  34558. setTooltip (newURL.toString (false));
  34559. }
  34560. const Font HyperlinkButton::getFontToUse() const
  34561. {
  34562. Font f (font);
  34563. if (resizeFont)
  34564. f.setHeight (getHeight() * 0.7f);
  34565. return f;
  34566. }
  34567. void HyperlinkButton::changeWidthToFitText()
  34568. {
  34569. setSize (getFontToUse().getStringWidth (getName()) + 6, getHeight());
  34570. }
  34571. void HyperlinkButton::colourChanged()
  34572. {
  34573. repaint();
  34574. }
  34575. void HyperlinkButton::clicked()
  34576. {
  34577. if (url.isWellFormed())
  34578. url.launchInDefaultBrowser();
  34579. }
  34580. void HyperlinkButton::paintButton (Graphics& g,
  34581. bool isMouseOverButton,
  34582. bool isButtonDown)
  34583. {
  34584. const Colour textColour (findColour (textColourId));
  34585. if (isEnabled())
  34586. g.setColour ((isMouseOverButton) ? textColour.darker ((isButtonDown) ? 1.3f : 0.4f)
  34587. : textColour);
  34588. else
  34589. g.setColour (textColour.withMultipliedAlpha (0.4f));
  34590. g.setFont (getFontToUse());
  34591. g.drawText (getButtonText(),
  34592. 2, 0, getWidth() - 2, getHeight(),
  34593. justification.getOnlyHorizontalFlags() | Justification::verticallyCentred,
  34594. true);
  34595. }
  34596. END_JUCE_NAMESPACE
  34597. /*** End of inlined file: juce_HyperlinkButton.cpp ***/
  34598. /*** Start of inlined file: juce_ImageButton.cpp ***/
  34599. BEGIN_JUCE_NAMESPACE
  34600. ImageButton::ImageButton (const String& text_)
  34601. : Button (text_),
  34602. scaleImageToFit (true),
  34603. preserveProportions (true),
  34604. alphaThreshold (0),
  34605. imageX (0),
  34606. imageY (0),
  34607. imageW (0),
  34608. imageH (0),
  34609. normalImage (0),
  34610. overImage (0),
  34611. downImage (0)
  34612. {
  34613. }
  34614. ImageButton::~ImageButton()
  34615. {
  34616. deleteImages();
  34617. }
  34618. void ImageButton::deleteImages()
  34619. {
  34620. ImageCache::releaseOrDelete (normalImage);
  34621. ImageCache::releaseOrDelete (overImage);
  34622. ImageCache::releaseOrDelete (downImage);
  34623. }
  34624. void ImageButton::setImages (const bool resizeButtonNowToFitThisImage,
  34625. const bool rescaleImagesWhenButtonSizeChanges,
  34626. const bool preserveImageProportions,
  34627. Image* const normalImage_,
  34628. const float imageOpacityWhenNormal,
  34629. const Colour& overlayColourWhenNormal,
  34630. Image* const overImage_,
  34631. const float imageOpacityWhenOver,
  34632. const Colour& overlayColourWhenOver,
  34633. Image* const downImage_,
  34634. const float imageOpacityWhenDown,
  34635. const Colour& overlayColourWhenDown,
  34636. const float hitTestAlphaThreshold)
  34637. {
  34638. deleteImages();
  34639. normalImage = normalImage_;
  34640. overImage = overImage_;
  34641. downImage = downImage_;
  34642. if (resizeButtonNowToFitThisImage && normalImage != 0)
  34643. {
  34644. imageW = normalImage->getWidth();
  34645. imageH = normalImage->getHeight();
  34646. setSize (imageW, imageH);
  34647. }
  34648. scaleImageToFit = rescaleImagesWhenButtonSizeChanges;
  34649. preserveProportions = preserveImageProportions;
  34650. normalOpacity = imageOpacityWhenNormal;
  34651. normalOverlay = overlayColourWhenNormal;
  34652. overOpacity = imageOpacityWhenOver;
  34653. overOverlay = overlayColourWhenOver;
  34654. downOpacity = imageOpacityWhenDown;
  34655. downOverlay = overlayColourWhenDown;
  34656. alphaThreshold = (unsigned char) jlimit (0, 0xff, roundToInt (255.0f * hitTestAlphaThreshold));
  34657. repaint();
  34658. }
  34659. Image* ImageButton::getCurrentImage() const
  34660. {
  34661. if (isDown() || getToggleState())
  34662. return getDownImage();
  34663. if (isOver())
  34664. return getOverImage();
  34665. return getNormalImage();
  34666. }
  34667. Image* ImageButton::getNormalImage() const throw()
  34668. {
  34669. return normalImage;
  34670. }
  34671. Image* ImageButton::getOverImage() const throw()
  34672. {
  34673. return (overImage != 0) ? overImage
  34674. : normalImage;
  34675. }
  34676. Image* ImageButton::getDownImage() const throw()
  34677. {
  34678. return (downImage != 0) ? downImage
  34679. : getOverImage();
  34680. }
  34681. void ImageButton::paintButton (Graphics& g,
  34682. bool isMouseOverButton,
  34683. bool isButtonDown)
  34684. {
  34685. if (! isEnabled())
  34686. {
  34687. isMouseOverButton = false;
  34688. isButtonDown = false;
  34689. }
  34690. Image* const im = getCurrentImage();
  34691. if (im != 0)
  34692. {
  34693. const int iw = im->getWidth();
  34694. const int ih = im->getHeight();
  34695. imageW = getWidth();
  34696. imageH = getHeight();
  34697. imageX = (imageW - iw) >> 1;
  34698. imageY = (imageH - ih) >> 1;
  34699. if (scaleImageToFit)
  34700. {
  34701. if (preserveProportions)
  34702. {
  34703. int newW, newH;
  34704. const float imRatio = ih / (float)iw;
  34705. const float destRatio = imageH / (float)imageW;
  34706. if (imRatio > destRatio)
  34707. {
  34708. newW = roundToInt (imageH / imRatio);
  34709. newH = imageH;
  34710. }
  34711. else
  34712. {
  34713. newW = imageW;
  34714. newH = roundToInt (imageW * imRatio);
  34715. }
  34716. imageX = (imageW - newW) / 2;
  34717. imageY = (imageH - newH) / 2;
  34718. imageW = newW;
  34719. imageH = newH;
  34720. }
  34721. else
  34722. {
  34723. imageX = 0;
  34724. imageY = 0;
  34725. }
  34726. }
  34727. if (! scaleImageToFit)
  34728. {
  34729. imageW = iw;
  34730. imageH = ih;
  34731. }
  34732. getLookAndFeel().drawImageButton (g, im, imageX, imageY, imageW, imageH,
  34733. isButtonDown ? downOverlay
  34734. : (isMouseOverButton ? overOverlay
  34735. : normalOverlay),
  34736. isButtonDown ? downOpacity
  34737. : (isMouseOverButton ? overOpacity
  34738. : normalOpacity),
  34739. *this);
  34740. }
  34741. }
  34742. bool ImageButton::hitTest (int x, int y)
  34743. {
  34744. if (alphaThreshold == 0)
  34745. return true;
  34746. Image* const im = getCurrentImage();
  34747. return im == 0
  34748. || (imageW > 0 && imageH > 0
  34749. && alphaThreshold < im->getPixelAt (((x - imageX) * im->getWidth()) / imageW,
  34750. ((y - imageY) * im->getHeight()) / imageH).getAlpha());
  34751. }
  34752. END_JUCE_NAMESPACE
  34753. /*** End of inlined file: juce_ImageButton.cpp ***/
  34754. /*** Start of inlined file: juce_ShapeButton.cpp ***/
  34755. BEGIN_JUCE_NAMESPACE
  34756. ShapeButton::ShapeButton (const String& text_,
  34757. const Colour& normalColour_,
  34758. const Colour& overColour_,
  34759. const Colour& downColour_)
  34760. : Button (text_),
  34761. normalColour (normalColour_),
  34762. overColour (overColour_),
  34763. downColour (downColour_),
  34764. maintainShapeProportions (false),
  34765. outlineWidth (0.0f)
  34766. {
  34767. }
  34768. ShapeButton::~ShapeButton()
  34769. {
  34770. }
  34771. void ShapeButton::setColours (const Colour& newNormalColour,
  34772. const Colour& newOverColour,
  34773. const Colour& newDownColour)
  34774. {
  34775. normalColour = newNormalColour;
  34776. overColour = newOverColour;
  34777. downColour = newDownColour;
  34778. }
  34779. void ShapeButton::setOutline (const Colour& newOutlineColour,
  34780. const float newOutlineWidth)
  34781. {
  34782. outlineColour = newOutlineColour;
  34783. outlineWidth = newOutlineWidth;
  34784. }
  34785. void ShapeButton::setShape (const Path& newShape,
  34786. const bool resizeNowToFitThisShape,
  34787. const bool maintainShapeProportions_,
  34788. const bool hasShadow)
  34789. {
  34790. shape = newShape;
  34791. maintainShapeProportions = maintainShapeProportions_;
  34792. shadow.setShadowProperties (3.0f, 0.5f, 0, 0);
  34793. setComponentEffect ((hasShadow) ? &shadow : 0);
  34794. if (resizeNowToFitThisShape)
  34795. {
  34796. Rectangle<float> bounds (shape.getBounds());
  34797. if (hasShadow)
  34798. bounds.expand (4.0f, 4.0f);
  34799. shape.applyTransform (AffineTransform::translation (-bounds.getX(), -bounds.getY()));
  34800. setSize (1 + (int) (bounds.getWidth() + outlineWidth),
  34801. 1 + (int) (bounds.getHeight() + outlineWidth));
  34802. }
  34803. }
  34804. void ShapeButton::paintButton (Graphics& g, bool isMouseOverButton, bool isButtonDown)
  34805. {
  34806. if (! isEnabled())
  34807. {
  34808. isMouseOverButton = false;
  34809. isButtonDown = false;
  34810. }
  34811. g.setColour ((isButtonDown) ? downColour
  34812. : (isMouseOverButton) ? overColour
  34813. : normalColour);
  34814. int w = getWidth();
  34815. int h = getHeight();
  34816. if (getComponentEffect() != 0)
  34817. {
  34818. w -= 4;
  34819. h -= 4;
  34820. }
  34821. const float offset = (outlineWidth * 0.5f) + (isButtonDown ? 1.5f : 0.0f);
  34822. const AffineTransform trans (shape.getTransformToScaleToFit (offset, offset,
  34823. w - offset - outlineWidth,
  34824. h - offset - outlineWidth,
  34825. maintainShapeProportions));
  34826. g.fillPath (shape, trans);
  34827. if (outlineWidth > 0.0f)
  34828. {
  34829. g.setColour (outlineColour);
  34830. g.strokePath (shape, PathStrokeType (outlineWidth), trans);
  34831. }
  34832. }
  34833. END_JUCE_NAMESPACE
  34834. /*** End of inlined file: juce_ShapeButton.cpp ***/
  34835. /*** Start of inlined file: juce_TextButton.cpp ***/
  34836. BEGIN_JUCE_NAMESPACE
  34837. TextButton::TextButton (const String& name,
  34838. const String& toolTip)
  34839. : Button (name)
  34840. {
  34841. setTooltip (toolTip);
  34842. }
  34843. TextButton::~TextButton()
  34844. {
  34845. }
  34846. void TextButton::paintButton (Graphics& g,
  34847. bool isMouseOverButton,
  34848. bool isButtonDown)
  34849. {
  34850. getLookAndFeel().drawButtonBackground (g, *this,
  34851. findColour (getToggleState() ? buttonOnColourId
  34852. : buttonColourId),
  34853. isMouseOverButton,
  34854. isButtonDown);
  34855. getLookAndFeel().drawButtonText (g, *this,
  34856. isMouseOverButton,
  34857. isButtonDown);
  34858. }
  34859. void TextButton::colourChanged()
  34860. {
  34861. repaint();
  34862. }
  34863. const Font TextButton::getFont()
  34864. {
  34865. return Font (jmin (15.0f, getHeight() * 0.6f));
  34866. }
  34867. void TextButton::changeWidthToFitText (const int newHeight)
  34868. {
  34869. if (newHeight >= 0)
  34870. setSize (jmax (1, getWidth()), newHeight);
  34871. setSize (getFont().getStringWidth (getButtonText()) + getHeight(),
  34872. getHeight());
  34873. }
  34874. END_JUCE_NAMESPACE
  34875. /*** End of inlined file: juce_TextButton.cpp ***/
  34876. /*** Start of inlined file: juce_ToggleButton.cpp ***/
  34877. BEGIN_JUCE_NAMESPACE
  34878. ToggleButton::ToggleButton (const String& buttonText)
  34879. : Button (buttonText)
  34880. {
  34881. setClickingTogglesState (true);
  34882. }
  34883. ToggleButton::~ToggleButton()
  34884. {
  34885. }
  34886. void ToggleButton::paintButton (Graphics& g,
  34887. bool isMouseOverButton,
  34888. bool isButtonDown)
  34889. {
  34890. getLookAndFeel().drawToggleButton (g, *this,
  34891. isMouseOverButton,
  34892. isButtonDown);
  34893. }
  34894. void ToggleButton::changeWidthToFitText()
  34895. {
  34896. getLookAndFeel().changeToggleButtonWidthToFitText (*this);
  34897. }
  34898. void ToggleButton::colourChanged()
  34899. {
  34900. repaint();
  34901. }
  34902. END_JUCE_NAMESPACE
  34903. /*** End of inlined file: juce_ToggleButton.cpp ***/
  34904. /*** Start of inlined file: juce_ToolbarButton.cpp ***/
  34905. BEGIN_JUCE_NAMESPACE
  34906. ToolbarButton::ToolbarButton (const int itemId_,
  34907. const String& buttonText,
  34908. Drawable* const normalImage_,
  34909. Drawable* const toggledOnImage_)
  34910. : ToolbarItemComponent (itemId_, buttonText, true),
  34911. normalImage (normalImage_),
  34912. toggledOnImage (toggledOnImage_)
  34913. {
  34914. jassert (normalImage_ != 0);
  34915. }
  34916. ToolbarButton::~ToolbarButton()
  34917. {
  34918. }
  34919. bool ToolbarButton::getToolbarItemSizes (int toolbarDepth,
  34920. bool /*isToolbarVertical*/,
  34921. int& preferredSize,
  34922. int& minSize, int& maxSize)
  34923. {
  34924. preferredSize = minSize = maxSize = toolbarDepth;
  34925. return true;
  34926. }
  34927. void ToolbarButton::paintButtonArea (Graphics& g,
  34928. int width, int height,
  34929. bool /*isMouseOver*/,
  34930. bool /*isMouseDown*/)
  34931. {
  34932. Drawable* d = normalImage;
  34933. if (getToggleState() && toggledOnImage != 0)
  34934. d = toggledOnImage;
  34935. if (! isEnabled())
  34936. {
  34937. Image im (Image::ARGB, width, height, true);
  34938. Graphics g2 (im);
  34939. d->drawWithin (g2, 0, 0, width, height, RectanglePlacement::centred, 1.0f);
  34940. im.desaturate();
  34941. g.drawImageAt (&im, 0, 0);
  34942. }
  34943. else
  34944. {
  34945. d->drawWithin (g, 0, 0, width, height, RectanglePlacement::centred, 1.0f);
  34946. }
  34947. }
  34948. void ToolbarButton::contentAreaChanged (const Rectangle<int>&)
  34949. {
  34950. }
  34951. END_JUCE_NAMESPACE
  34952. /*** End of inlined file: juce_ToolbarButton.cpp ***/
  34953. /*** Start of inlined file: juce_CodeDocument.cpp ***/
  34954. BEGIN_JUCE_NAMESPACE
  34955. class CodeDocumentLine
  34956. {
  34957. public:
  34958. CodeDocumentLine (const juce_wchar* const line_,
  34959. const int lineLength_,
  34960. const int numNewLineChars,
  34961. const int lineStartInFile_)
  34962. : line (line_, lineLength_),
  34963. lineStartInFile (lineStartInFile_),
  34964. lineLength (lineLength_),
  34965. lineLengthWithoutNewLines (lineLength_ - numNewLineChars)
  34966. {
  34967. }
  34968. ~CodeDocumentLine()
  34969. {
  34970. }
  34971. static void createLines (Array <CodeDocumentLine*>& newLines, const String& text)
  34972. {
  34973. const juce_wchar* const t = text;
  34974. int pos = 0;
  34975. while (t [pos] != 0)
  34976. {
  34977. const int startOfLine = pos;
  34978. int numNewLineChars = 0;
  34979. while (t[pos] != 0)
  34980. {
  34981. if (t[pos] == '\r')
  34982. {
  34983. ++numNewLineChars;
  34984. ++pos;
  34985. if (t[pos] == '\n')
  34986. {
  34987. ++numNewLineChars;
  34988. ++pos;
  34989. }
  34990. break;
  34991. }
  34992. if (t[pos] == '\n')
  34993. {
  34994. ++numNewLineChars;
  34995. ++pos;
  34996. break;
  34997. }
  34998. ++pos;
  34999. }
  35000. newLines.add (new CodeDocumentLine (t + startOfLine, pos - startOfLine,
  35001. numNewLineChars, startOfLine));
  35002. }
  35003. jassert (pos == text.length());
  35004. }
  35005. bool endsWithLineBreak() const throw()
  35006. {
  35007. return lineLengthWithoutNewLines != lineLength;
  35008. }
  35009. void updateLength() throw()
  35010. {
  35011. lineLengthWithoutNewLines = lineLength = line.length();
  35012. while (lineLengthWithoutNewLines > 0
  35013. && (line [lineLengthWithoutNewLines - 1] == '\n'
  35014. || line [lineLengthWithoutNewLines - 1] == '\r'))
  35015. {
  35016. --lineLengthWithoutNewLines;
  35017. }
  35018. }
  35019. String line;
  35020. int lineStartInFile, lineLength, lineLengthWithoutNewLines;
  35021. };
  35022. CodeDocument::Iterator::Iterator (CodeDocument* const document_)
  35023. : document (document_),
  35024. currentLine (document_->lines[0]),
  35025. line (0),
  35026. position (0)
  35027. {
  35028. }
  35029. CodeDocument::Iterator::Iterator (const CodeDocument::Iterator& other)
  35030. : document (other.document),
  35031. currentLine (other.currentLine),
  35032. line (other.line),
  35033. position (other.position)
  35034. {
  35035. }
  35036. CodeDocument::Iterator& CodeDocument::Iterator::operator= (const CodeDocument::Iterator& other) throw()
  35037. {
  35038. document = other.document;
  35039. currentLine = other.currentLine;
  35040. line = other.line;
  35041. position = other.position;
  35042. return *this;
  35043. }
  35044. CodeDocument::Iterator::~Iterator() throw()
  35045. {
  35046. }
  35047. juce_wchar CodeDocument::Iterator::nextChar()
  35048. {
  35049. if (currentLine == 0)
  35050. return 0;
  35051. jassert (currentLine == document->lines.getUnchecked (line));
  35052. const juce_wchar result = currentLine->line [position - currentLine->lineStartInFile];
  35053. if (++position >= currentLine->lineStartInFile + currentLine->lineLength)
  35054. {
  35055. ++line;
  35056. currentLine = document->lines [line];
  35057. }
  35058. return result;
  35059. }
  35060. void CodeDocument::Iterator::skip()
  35061. {
  35062. if (currentLine != 0)
  35063. {
  35064. jassert (currentLine == document->lines.getUnchecked (line));
  35065. if (++position >= currentLine->lineStartInFile + currentLine->lineLength)
  35066. {
  35067. ++line;
  35068. currentLine = document->lines [line];
  35069. }
  35070. }
  35071. }
  35072. void CodeDocument::Iterator::skipToEndOfLine()
  35073. {
  35074. if (currentLine != 0)
  35075. {
  35076. jassert (currentLine == document->lines.getUnchecked (line));
  35077. ++line;
  35078. currentLine = document->lines [line];
  35079. if (currentLine != 0)
  35080. position = currentLine->lineStartInFile;
  35081. else
  35082. position = document->getNumCharacters();
  35083. }
  35084. }
  35085. juce_wchar CodeDocument::Iterator::peekNextChar() const
  35086. {
  35087. if (currentLine == 0)
  35088. return 0;
  35089. jassert (currentLine == document->lines.getUnchecked (line));
  35090. return const_cast <const String&> (currentLine->line) [position - currentLine->lineStartInFile];
  35091. }
  35092. void CodeDocument::Iterator::skipWhitespace()
  35093. {
  35094. while (CharacterFunctions::isWhitespace (peekNextChar()))
  35095. skip();
  35096. }
  35097. bool CodeDocument::Iterator::isEOF() const throw()
  35098. {
  35099. return currentLine == 0;
  35100. }
  35101. CodeDocument::Position::Position() throw()
  35102. : owner (0), characterPos (0), line (0),
  35103. indexInLine (0), positionMaintained (false)
  35104. {
  35105. }
  35106. CodeDocument::Position::Position (const CodeDocument* const ownerDocument,
  35107. const int line_, const int indexInLine_) throw()
  35108. : owner (const_cast <CodeDocument*> (ownerDocument)),
  35109. characterPos (0), line (line_),
  35110. indexInLine (indexInLine_), positionMaintained (false)
  35111. {
  35112. setLineAndIndex (line_, indexInLine_);
  35113. }
  35114. CodeDocument::Position::Position (const CodeDocument* const ownerDocument,
  35115. const int characterPos_) throw()
  35116. : owner (const_cast <CodeDocument*> (ownerDocument)),
  35117. positionMaintained (false)
  35118. {
  35119. setPosition (characterPos_);
  35120. }
  35121. CodeDocument::Position::Position (const Position& other) throw()
  35122. : owner (other.owner), characterPos (other.characterPos), line (other.line),
  35123. indexInLine (other.indexInLine), positionMaintained (false)
  35124. {
  35125. jassert (*this == other);
  35126. }
  35127. CodeDocument::Position::~Position() throw()
  35128. {
  35129. setPositionMaintained (false);
  35130. }
  35131. CodeDocument::Position& CodeDocument::Position::operator= (const Position& other) throw()
  35132. {
  35133. if (this != &other)
  35134. {
  35135. const bool wasPositionMaintained = positionMaintained;
  35136. if (owner != other.owner)
  35137. setPositionMaintained (false);
  35138. owner = other.owner;
  35139. line = other.line;
  35140. indexInLine = other.indexInLine;
  35141. characterPos = other.characterPos;
  35142. setPositionMaintained (wasPositionMaintained);
  35143. jassert (*this == other);
  35144. }
  35145. return *this;
  35146. }
  35147. bool CodeDocument::Position::operator== (const Position& other) const throw()
  35148. {
  35149. jassert ((characterPos == other.characterPos)
  35150. == (line == other.line && indexInLine == other.indexInLine));
  35151. return characterPos == other.characterPos
  35152. && line == other.line
  35153. && indexInLine == other.indexInLine
  35154. && owner == other.owner;
  35155. }
  35156. bool CodeDocument::Position::operator!= (const Position& other) const throw()
  35157. {
  35158. return ! operator== (other);
  35159. }
  35160. void CodeDocument::Position::setLineAndIndex (const int newLine, const int newIndexInLine) throw()
  35161. {
  35162. jassert (owner != 0);
  35163. if (owner->lines.size() == 0)
  35164. {
  35165. line = 0;
  35166. indexInLine = 0;
  35167. characterPos = 0;
  35168. }
  35169. else
  35170. {
  35171. if (newLine >= owner->lines.size())
  35172. {
  35173. line = owner->lines.size() - 1;
  35174. CodeDocumentLine* const l = owner->lines.getUnchecked (line);
  35175. jassert (l != 0);
  35176. indexInLine = l->lineLengthWithoutNewLines;
  35177. characterPos = l->lineStartInFile + indexInLine;
  35178. }
  35179. else
  35180. {
  35181. line = jmax (0, newLine);
  35182. CodeDocumentLine* const l = owner->lines.getUnchecked (line);
  35183. jassert (l != 0);
  35184. if (l->lineLengthWithoutNewLines > 0)
  35185. indexInLine = jlimit (0, l->lineLengthWithoutNewLines, newIndexInLine);
  35186. else
  35187. indexInLine = 0;
  35188. characterPos = l->lineStartInFile + indexInLine;
  35189. }
  35190. }
  35191. }
  35192. void CodeDocument::Position::setPosition (const int newPosition) throw()
  35193. {
  35194. jassert (owner != 0);
  35195. line = 0;
  35196. indexInLine = 0;
  35197. characterPos = 0;
  35198. if (newPosition > 0)
  35199. {
  35200. int lineStart = 0;
  35201. int lineEnd = owner->lines.size();
  35202. for (;;)
  35203. {
  35204. if (lineEnd - lineStart < 4)
  35205. {
  35206. for (int i = lineStart; i < lineEnd; ++i)
  35207. {
  35208. CodeDocumentLine* const l = owner->lines.getUnchecked (i);
  35209. int index = newPosition - l->lineStartInFile;
  35210. if (index >= 0 && (index < l->lineLength || i == lineEnd - 1))
  35211. {
  35212. line = i;
  35213. indexInLine = jmin (l->lineLengthWithoutNewLines, index);
  35214. characterPos = l->lineStartInFile + indexInLine;
  35215. }
  35216. }
  35217. break;
  35218. }
  35219. else
  35220. {
  35221. const int midIndex = (lineStart + lineEnd + 1) / 2;
  35222. CodeDocumentLine* const mid = owner->lines.getUnchecked (midIndex);
  35223. if (newPosition >= mid->lineStartInFile)
  35224. lineStart = midIndex;
  35225. else
  35226. lineEnd = midIndex;
  35227. }
  35228. }
  35229. }
  35230. }
  35231. void CodeDocument::Position::moveBy (int characterDelta) throw()
  35232. {
  35233. jassert (owner != 0);
  35234. if (characterDelta == 1)
  35235. {
  35236. setPosition (getPosition());
  35237. // If moving right, make sure we don't get stuck between the \r and \n characters..
  35238. if (line < owner->lines.size())
  35239. {
  35240. CodeDocumentLine* const l = owner->lines.getUnchecked (line);
  35241. if (indexInLine + characterDelta < l->lineLength
  35242. && indexInLine + characterDelta >= l->lineLengthWithoutNewLines + 1)
  35243. ++characterDelta;
  35244. }
  35245. }
  35246. setPosition (characterPos + characterDelta);
  35247. }
  35248. const CodeDocument::Position CodeDocument::Position::movedBy (const int characterDelta) const throw()
  35249. {
  35250. CodeDocument::Position p (*this);
  35251. p.moveBy (characterDelta);
  35252. return p;
  35253. }
  35254. const CodeDocument::Position CodeDocument::Position::movedByLines (const int deltaLines) const throw()
  35255. {
  35256. CodeDocument::Position p (*this);
  35257. p.setLineAndIndex (getLineNumber() + deltaLines, getIndexInLine());
  35258. return p;
  35259. }
  35260. const juce_wchar CodeDocument::Position::getCharacter() const throw()
  35261. {
  35262. const CodeDocumentLine* const l = owner->lines [line];
  35263. return l == 0 ? 0 : l->line [getIndexInLine()];
  35264. }
  35265. const String CodeDocument::Position::getLineText() const throw()
  35266. {
  35267. const CodeDocumentLine* const l = owner->lines [line];
  35268. return l == 0 ? String::empty : l->line;
  35269. }
  35270. void CodeDocument::Position::setPositionMaintained (const bool isMaintained) throw()
  35271. {
  35272. if (isMaintained != positionMaintained)
  35273. {
  35274. positionMaintained = isMaintained;
  35275. if (owner != 0)
  35276. {
  35277. if (isMaintained)
  35278. {
  35279. jassert (! owner->positionsToMaintain.contains (this));
  35280. owner->positionsToMaintain.add (this);
  35281. }
  35282. else
  35283. {
  35284. // If this happens, you may have deleted the document while there are Position objects that are still using it...
  35285. jassert (owner->positionsToMaintain.contains (this));
  35286. owner->positionsToMaintain.removeValue (this);
  35287. }
  35288. }
  35289. }
  35290. }
  35291. CodeDocument::CodeDocument()
  35292. : undoManager (std::numeric_limits<int>::max(), 10000),
  35293. currentActionIndex (0),
  35294. indexOfSavedState (-1),
  35295. maximumLineLength (-1),
  35296. newLineChars ("\r\n")
  35297. {
  35298. }
  35299. CodeDocument::~CodeDocument()
  35300. {
  35301. }
  35302. const String CodeDocument::getAllContent() const throw()
  35303. {
  35304. return getTextBetween (Position (this, 0),
  35305. Position (this, lines.size(), 0));
  35306. }
  35307. const String CodeDocument::getTextBetween (const Position& start, const Position& end) const throw()
  35308. {
  35309. if (end.getPosition() <= start.getPosition())
  35310. return String::empty;
  35311. const int startLine = start.getLineNumber();
  35312. const int endLine = end.getLineNumber();
  35313. if (startLine == endLine)
  35314. {
  35315. CodeDocumentLine* const line = lines [startLine];
  35316. return (line == 0) ? String::empty : line->line.substring (start.getIndexInLine(), end.getIndexInLine());
  35317. }
  35318. String result;
  35319. result.preallocateStorage (end.getPosition() - start.getPosition() + 4);
  35320. String::Concatenator concatenator (result);
  35321. const int maxLine = jmin (lines.size() - 1, endLine);
  35322. for (int i = jmax (0, startLine); i <= maxLine; ++i)
  35323. {
  35324. const CodeDocumentLine* line = lines.getUnchecked(i);
  35325. int len = line->lineLength;
  35326. if (i == startLine)
  35327. {
  35328. const int index = start.getIndexInLine();
  35329. concatenator.append (line->line.substring (index, len));
  35330. }
  35331. else if (i == endLine)
  35332. {
  35333. len = end.getIndexInLine();
  35334. concatenator.append (line->line.substring (0, len));
  35335. }
  35336. else
  35337. {
  35338. concatenator.append (line->line);
  35339. }
  35340. }
  35341. return result;
  35342. }
  35343. int CodeDocument::getNumCharacters() const throw()
  35344. {
  35345. const CodeDocumentLine* const lastLine = lines.getLast();
  35346. return (lastLine == 0) ? 0 : lastLine->lineStartInFile + lastLine->lineLength;
  35347. }
  35348. const String CodeDocument::getLine (const int lineIndex) const throw()
  35349. {
  35350. const CodeDocumentLine* const line = lines [lineIndex];
  35351. return (line == 0) ? String::empty : line->line;
  35352. }
  35353. int CodeDocument::getMaximumLineLength() throw()
  35354. {
  35355. if (maximumLineLength < 0)
  35356. {
  35357. maximumLineLength = 0;
  35358. for (int i = lines.size(); --i >= 0;)
  35359. maximumLineLength = jmax (maximumLineLength, lines.getUnchecked(i)->lineLength);
  35360. }
  35361. return maximumLineLength;
  35362. }
  35363. void CodeDocument::deleteSection (const Position& startPosition, const Position& endPosition)
  35364. {
  35365. remove (startPosition.getPosition(), endPosition.getPosition(), true);
  35366. }
  35367. void CodeDocument::insertText (const Position& position, const String& text)
  35368. {
  35369. insert (text, position.getPosition(), true);
  35370. }
  35371. void CodeDocument::replaceAllContent (const String& newContent)
  35372. {
  35373. remove (0, getNumCharacters(), true);
  35374. insert (newContent, 0, true);
  35375. }
  35376. bool CodeDocument::loadFromStream (InputStream& stream)
  35377. {
  35378. replaceAllContent (stream.readEntireStreamAsString());
  35379. setSavePoint();
  35380. clearUndoHistory();
  35381. return true;
  35382. }
  35383. bool CodeDocument::writeToStream (OutputStream& stream)
  35384. {
  35385. for (int i = 0; i < lines.size(); ++i)
  35386. {
  35387. String temp (lines.getUnchecked(i)->line); // use a copy to avoid bloating the memory footprint of the stored string.
  35388. const char* utf8 = temp.toUTF8();
  35389. if (! stream.write (utf8, (int) strlen (utf8)))
  35390. return false;
  35391. }
  35392. return true;
  35393. }
  35394. void CodeDocument::setNewLineCharacters (const String& newLine) throw()
  35395. {
  35396. jassert (newLine == "\r\n" || newLine == "\n" || newLine == "\r");
  35397. newLineChars = newLine;
  35398. }
  35399. void CodeDocument::newTransaction()
  35400. {
  35401. undoManager.beginNewTransaction (String::empty);
  35402. }
  35403. void CodeDocument::undo()
  35404. {
  35405. newTransaction();
  35406. undoManager.undo();
  35407. }
  35408. void CodeDocument::redo()
  35409. {
  35410. undoManager.redo();
  35411. }
  35412. void CodeDocument::clearUndoHistory()
  35413. {
  35414. undoManager.clearUndoHistory();
  35415. }
  35416. void CodeDocument::setSavePoint() throw()
  35417. {
  35418. indexOfSavedState = currentActionIndex;
  35419. }
  35420. bool CodeDocument::hasChangedSinceSavePoint() const throw()
  35421. {
  35422. return currentActionIndex != indexOfSavedState;
  35423. }
  35424. static int getCodeCharacterCategory (const juce_wchar character) throw()
  35425. {
  35426. return (CharacterFunctions::isLetterOrDigit (character) || character == '_')
  35427. ? 2 : (CharacterFunctions::isWhitespace (character) ? 0 : 1);
  35428. }
  35429. const CodeDocument::Position CodeDocument::findWordBreakAfter (const Position& position) const throw()
  35430. {
  35431. Position p (position);
  35432. const int maxDistance = 256;
  35433. int i = 0;
  35434. while (i < maxDistance
  35435. && CharacterFunctions::isWhitespace (p.getCharacter())
  35436. && (i == 0 || (p.getCharacter() != '\n'
  35437. && p.getCharacter() != '\r')))
  35438. {
  35439. ++i;
  35440. p.moveBy (1);
  35441. }
  35442. if (i == 0)
  35443. {
  35444. const int type = getCodeCharacterCategory (p.getCharacter());
  35445. while (i < maxDistance && type == getCodeCharacterCategory (p.getCharacter()))
  35446. {
  35447. ++i;
  35448. p.moveBy (1);
  35449. }
  35450. while (i < maxDistance
  35451. && CharacterFunctions::isWhitespace (p.getCharacter())
  35452. && (i == 0 || (p.getCharacter() != '\n'
  35453. && p.getCharacter() != '\r')))
  35454. {
  35455. ++i;
  35456. p.moveBy (1);
  35457. }
  35458. }
  35459. return p;
  35460. }
  35461. const CodeDocument::Position CodeDocument::findWordBreakBefore (const Position& position) const throw()
  35462. {
  35463. Position p (position);
  35464. const int maxDistance = 256;
  35465. int i = 0;
  35466. bool stoppedAtLineStart = false;
  35467. while (i < maxDistance)
  35468. {
  35469. const juce_wchar c = p.movedBy (-1).getCharacter();
  35470. if (c == '\r' || c == '\n')
  35471. {
  35472. stoppedAtLineStart = true;
  35473. if (i > 0)
  35474. break;
  35475. }
  35476. if (! CharacterFunctions::isWhitespace (c))
  35477. break;
  35478. p.moveBy (-1);
  35479. ++i;
  35480. }
  35481. if (i < maxDistance && ! stoppedAtLineStart)
  35482. {
  35483. const int type = getCodeCharacterCategory (p.movedBy (-1).getCharacter());
  35484. while (i < maxDistance && type == getCodeCharacterCategory (p.movedBy (-1).getCharacter()))
  35485. {
  35486. p.moveBy (-1);
  35487. ++i;
  35488. }
  35489. }
  35490. return p;
  35491. }
  35492. void CodeDocument::checkLastLineStatus()
  35493. {
  35494. while (lines.size() > 0
  35495. && lines.getLast()->lineLength == 0
  35496. && (lines.size() == 1 || ! lines.getUnchecked (lines.size() - 2)->endsWithLineBreak()))
  35497. {
  35498. // remove any empty lines at the end if the preceding line doesn't end in a newline.
  35499. lines.removeLast();
  35500. }
  35501. const CodeDocumentLine* const lastLine = lines.getLast();
  35502. if (lastLine != 0 && lastLine->endsWithLineBreak())
  35503. {
  35504. // check that there's an empty line at the end if the preceding one ends in a newline..
  35505. lines.add (new CodeDocumentLine (String::empty, 0, 0, lastLine->lineStartInFile + lastLine->lineLength));
  35506. }
  35507. }
  35508. void CodeDocument::addListener (CodeDocument::Listener* const listener) throw()
  35509. {
  35510. listeners.add (listener);
  35511. }
  35512. void CodeDocument::removeListener (CodeDocument::Listener* const listener) throw()
  35513. {
  35514. listeners.remove (listener);
  35515. }
  35516. void CodeDocument::sendListenerChangeMessage (const int startLine, const int endLine)
  35517. {
  35518. Position startPos (this, startLine, 0);
  35519. Position endPos (this, endLine, 0);
  35520. listeners.call (&Listener::codeDocumentChanged, startPos, endPos);
  35521. }
  35522. class CodeDocumentInsertAction : public UndoableAction
  35523. {
  35524. CodeDocument& owner;
  35525. const String text;
  35526. int insertPos;
  35527. CodeDocumentInsertAction (const CodeDocumentInsertAction&);
  35528. CodeDocumentInsertAction& operator= (const CodeDocumentInsertAction&);
  35529. public:
  35530. CodeDocumentInsertAction (CodeDocument& owner_, const String& text_, const int insertPos_) throw()
  35531. : owner (owner_),
  35532. text (text_),
  35533. insertPos (insertPos_)
  35534. {
  35535. }
  35536. ~CodeDocumentInsertAction() {}
  35537. bool perform()
  35538. {
  35539. owner.currentActionIndex++;
  35540. owner.insert (text, insertPos, false);
  35541. return true;
  35542. }
  35543. bool undo()
  35544. {
  35545. owner.currentActionIndex--;
  35546. owner.remove (insertPos, insertPos + text.length(), false);
  35547. return true;
  35548. }
  35549. int getSizeInUnits() { return text.length() + 32; }
  35550. };
  35551. void CodeDocument::insert (const String& text, const int insertPos, const bool undoable)
  35552. {
  35553. if (text.isEmpty())
  35554. return;
  35555. if (undoable)
  35556. {
  35557. undoManager.perform (new CodeDocumentInsertAction (*this, text, insertPos));
  35558. }
  35559. else
  35560. {
  35561. Position pos (this, insertPos);
  35562. const int firstAffectedLine = pos.getLineNumber();
  35563. int lastAffectedLine = firstAffectedLine + 1;
  35564. CodeDocumentLine* const firstLine = lines [firstAffectedLine];
  35565. String textInsideOriginalLine (text);
  35566. if (firstLine != 0)
  35567. {
  35568. const int index = pos.getIndexInLine();
  35569. textInsideOriginalLine = firstLine->line.substring (0, index)
  35570. + textInsideOriginalLine
  35571. + firstLine->line.substring (index);
  35572. }
  35573. maximumLineLength = -1;
  35574. Array <CodeDocumentLine*> newLines;
  35575. CodeDocumentLine::createLines (newLines, textInsideOriginalLine);
  35576. jassert (newLines.size() > 0);
  35577. CodeDocumentLine* const newFirstLine = newLines.getUnchecked (0);
  35578. newFirstLine->lineStartInFile = firstLine != 0 ? firstLine->lineStartInFile : 0;
  35579. lines.set (firstAffectedLine, newFirstLine);
  35580. if (newLines.size() > 1)
  35581. {
  35582. for (int i = 1; i < newLines.size(); ++i)
  35583. {
  35584. CodeDocumentLine* const l = newLines.getUnchecked (i);
  35585. lines.insert (firstAffectedLine + i, l);
  35586. }
  35587. lastAffectedLine = lines.size();
  35588. }
  35589. int i, lineStart = newFirstLine->lineStartInFile;
  35590. for (i = firstAffectedLine; i < lines.size(); ++i)
  35591. {
  35592. CodeDocumentLine* const l = lines.getUnchecked (i);
  35593. l->lineStartInFile = lineStart;
  35594. lineStart += l->lineLength;
  35595. }
  35596. checkLastLineStatus();
  35597. const int newTextLength = text.length();
  35598. for (i = 0; i < positionsToMaintain.size(); ++i)
  35599. {
  35600. CodeDocument::Position* const p = positionsToMaintain.getUnchecked(i);
  35601. if (p->getPosition() >= insertPos)
  35602. p->setPosition (p->getPosition() + newTextLength);
  35603. }
  35604. sendListenerChangeMessage (firstAffectedLine, lastAffectedLine);
  35605. }
  35606. }
  35607. class CodeDocumentDeleteAction : public UndoableAction
  35608. {
  35609. CodeDocument& owner;
  35610. int startPos, endPos;
  35611. String removedText;
  35612. CodeDocumentDeleteAction (const CodeDocumentDeleteAction&);
  35613. CodeDocumentDeleteAction& operator= (const CodeDocumentDeleteAction&);
  35614. public:
  35615. CodeDocumentDeleteAction (CodeDocument& owner_, const int startPos_, const int endPos_) throw()
  35616. : owner (owner_),
  35617. startPos (startPos_),
  35618. endPos (endPos_)
  35619. {
  35620. removedText = owner.getTextBetween (CodeDocument::Position (&owner, startPos),
  35621. CodeDocument::Position (&owner, endPos));
  35622. }
  35623. ~CodeDocumentDeleteAction() {}
  35624. bool perform()
  35625. {
  35626. owner.currentActionIndex++;
  35627. owner.remove (startPos, endPos, false);
  35628. return true;
  35629. }
  35630. bool undo()
  35631. {
  35632. owner.currentActionIndex--;
  35633. owner.insert (removedText, startPos, false);
  35634. return true;
  35635. }
  35636. int getSizeInUnits() { return removedText.length() + 32; }
  35637. };
  35638. void CodeDocument::remove (const int startPos, const int endPos, const bool undoable)
  35639. {
  35640. if (endPos <= startPos)
  35641. return;
  35642. if (undoable)
  35643. {
  35644. undoManager.perform (new CodeDocumentDeleteAction (*this, startPos, endPos));
  35645. }
  35646. else
  35647. {
  35648. Position startPosition (this, startPos);
  35649. Position endPosition (this, endPos);
  35650. maximumLineLength = -1;
  35651. const int firstAffectedLine = startPosition.getLineNumber();
  35652. const int endLine = endPosition.getLineNumber();
  35653. int lastAffectedLine = firstAffectedLine + 1;
  35654. CodeDocumentLine* const firstLine = lines.getUnchecked (firstAffectedLine);
  35655. if (firstAffectedLine == endLine)
  35656. {
  35657. firstLine->line = firstLine->line.substring (0, startPosition.getIndexInLine())
  35658. + firstLine->line.substring (endPosition.getIndexInLine());
  35659. firstLine->updateLength();
  35660. }
  35661. else
  35662. {
  35663. lastAffectedLine = lines.size();
  35664. CodeDocumentLine* const lastLine = lines.getUnchecked (endLine);
  35665. jassert (lastLine != 0);
  35666. firstLine->line = firstLine->line.substring (0, startPosition.getIndexInLine())
  35667. + lastLine->line.substring (endPosition.getIndexInLine());
  35668. firstLine->updateLength();
  35669. int numLinesToRemove = endLine - firstAffectedLine;
  35670. lines.removeRange (firstAffectedLine + 1, numLinesToRemove);
  35671. }
  35672. int i;
  35673. for (i = firstAffectedLine + 1; i < lines.size(); ++i)
  35674. {
  35675. CodeDocumentLine* const l = lines.getUnchecked (i);
  35676. const CodeDocumentLine* const previousLine = lines.getUnchecked (i - 1);
  35677. l->lineStartInFile = previousLine->lineStartInFile + previousLine->lineLength;
  35678. }
  35679. checkLastLineStatus();
  35680. const int totalChars = getNumCharacters();
  35681. for (i = 0; i < positionsToMaintain.size(); ++i)
  35682. {
  35683. CodeDocument::Position* p = positionsToMaintain.getUnchecked(i);
  35684. if (p->getPosition() > startPosition.getPosition())
  35685. p->setPosition (jmax (startPos, p->getPosition() + startPos - endPos));
  35686. if (p->getPosition() > totalChars)
  35687. p->setPosition (totalChars);
  35688. }
  35689. sendListenerChangeMessage (firstAffectedLine, lastAffectedLine);
  35690. }
  35691. }
  35692. END_JUCE_NAMESPACE
  35693. /*** End of inlined file: juce_CodeDocument.cpp ***/
  35694. /*** Start of inlined file: juce_CodeEditorComponent.cpp ***/
  35695. BEGIN_JUCE_NAMESPACE
  35696. class CodeEditorComponent::CaretComponent : public Component,
  35697. public Timer
  35698. {
  35699. public:
  35700. CaretComponent (CodeEditorComponent& owner_)
  35701. : owner (owner_)
  35702. {
  35703. setAlwaysOnTop (true);
  35704. setInterceptsMouseClicks (false, false);
  35705. }
  35706. ~CaretComponent()
  35707. {
  35708. }
  35709. void paint (Graphics& g)
  35710. {
  35711. g.fillAll (findColour (CodeEditorComponent::caretColourId));
  35712. }
  35713. void timerCallback()
  35714. {
  35715. setVisible (shouldBeShown() && ! isVisible());
  35716. }
  35717. void updatePosition()
  35718. {
  35719. startTimer (400);
  35720. setVisible (shouldBeShown());
  35721. setBounds (owner.getCharacterBounds (owner.getCaretPos()).withWidth (2));
  35722. }
  35723. private:
  35724. CodeEditorComponent& owner;
  35725. CaretComponent (const CaretComponent&);
  35726. CaretComponent& operator= (const CaretComponent&);
  35727. bool shouldBeShown() const { return owner.hasKeyboardFocus (true); }
  35728. };
  35729. class CodeEditorComponent::CodeEditorLine
  35730. {
  35731. public:
  35732. CodeEditorLine() throw()
  35733. : highlightColumnStart (0), highlightColumnEnd (0)
  35734. {
  35735. }
  35736. ~CodeEditorLine() throw()
  35737. {
  35738. }
  35739. bool update (CodeDocument& document, int lineNum,
  35740. CodeDocument::Iterator& source,
  35741. CodeTokeniser* analyser, const int spacesPerTab,
  35742. const CodeDocument::Position& selectionStart,
  35743. const CodeDocument::Position& selectionEnd)
  35744. {
  35745. Array <SyntaxToken> newTokens;
  35746. newTokens.ensureStorageAllocated (8);
  35747. if (analyser == 0)
  35748. {
  35749. newTokens.add (SyntaxToken (document.getLine (lineNum), -1));
  35750. }
  35751. else if (lineNum < document.getNumLines())
  35752. {
  35753. const CodeDocument::Position pos (&document, lineNum, 0);
  35754. createTokens (pos.getPosition(), pos.getLineText(),
  35755. source, analyser, newTokens);
  35756. }
  35757. replaceTabsWithSpaces (newTokens, spacesPerTab);
  35758. int newHighlightStart = 0;
  35759. int newHighlightEnd = 0;
  35760. if (selectionStart.getLineNumber() <= lineNum && selectionEnd.getLineNumber() >= lineNum)
  35761. {
  35762. const String line (document.getLine (lineNum));
  35763. CodeDocument::Position lineStart (&document, lineNum, 0), lineEnd (&document, lineNum + 1, 0);
  35764. newHighlightStart = indexToColumn (jmax (0, selectionStart.getPosition() - lineStart.getPosition()),
  35765. line, spacesPerTab);
  35766. newHighlightEnd = indexToColumn (jmin (lineEnd.getPosition() - lineStart.getPosition(), selectionEnd.getPosition() - lineStart.getPosition()),
  35767. line, spacesPerTab);
  35768. }
  35769. if (newHighlightStart != highlightColumnStart || newHighlightEnd != highlightColumnEnd)
  35770. {
  35771. highlightColumnStart = newHighlightStart;
  35772. highlightColumnEnd = newHighlightEnd;
  35773. }
  35774. else
  35775. {
  35776. if (tokens.size() == newTokens.size())
  35777. {
  35778. bool allTheSame = true;
  35779. for (int i = newTokens.size(); --i >= 0;)
  35780. {
  35781. if (tokens.getReference(i) != newTokens.getReference(i))
  35782. {
  35783. allTheSame = false;
  35784. break;
  35785. }
  35786. }
  35787. if (allTheSame)
  35788. return false;
  35789. }
  35790. }
  35791. tokens.swapWithArray (newTokens);
  35792. return true;
  35793. }
  35794. void draw (CodeEditorComponent& owner, Graphics& g, const Font& font,
  35795. float x, const int y, const int baselineOffset, const int lineHeight,
  35796. const Colour& highlightColour) const throw()
  35797. {
  35798. if (highlightColumnStart < highlightColumnEnd)
  35799. {
  35800. g.setColour (highlightColour);
  35801. g.fillRect (roundToInt (x + highlightColumnStart * owner.getCharWidth()), y,
  35802. roundToInt ((highlightColumnEnd - highlightColumnStart) * owner.getCharWidth()), lineHeight);
  35803. }
  35804. int lastType = std::numeric_limits<int>::min();
  35805. for (int i = 0; i < tokens.size(); ++i)
  35806. {
  35807. SyntaxToken& token = tokens.getReference(i);
  35808. if (lastType != token.tokenType)
  35809. {
  35810. lastType = token.tokenType;
  35811. g.setColour (owner.getColourForTokenType (lastType));
  35812. }
  35813. g.drawSingleLineText (token.text, roundToInt (x), y + baselineOffset);
  35814. if (i < tokens.size() - 1)
  35815. {
  35816. if (token.width < 0)
  35817. token.width = font.getStringWidthFloat (token.text);
  35818. x += token.width;
  35819. }
  35820. }
  35821. }
  35822. private:
  35823. struct SyntaxToken
  35824. {
  35825. String text;
  35826. int tokenType;
  35827. float width;
  35828. SyntaxToken (const String& text_, const int type) throw()
  35829. : text (text_), tokenType (type), width (-1.0f)
  35830. {
  35831. }
  35832. bool operator!= (const SyntaxToken& other) const throw()
  35833. {
  35834. return text != other.text || tokenType != other.tokenType;
  35835. }
  35836. };
  35837. Array <SyntaxToken> tokens;
  35838. int highlightColumnStart, highlightColumnEnd;
  35839. static void createTokens (int startPosition, const String& lineText,
  35840. CodeDocument::Iterator& source,
  35841. CodeTokeniser* analyser,
  35842. Array <SyntaxToken>& newTokens)
  35843. {
  35844. CodeDocument::Iterator lastIterator (source);
  35845. const int lineLength = lineText.length();
  35846. for (;;)
  35847. {
  35848. int tokenType = analyser->readNextToken (source);
  35849. int tokenStart = lastIterator.getPosition();
  35850. int tokenEnd = source.getPosition();
  35851. if (tokenEnd <= tokenStart)
  35852. break;
  35853. tokenEnd -= startPosition;
  35854. if (tokenEnd > 0)
  35855. {
  35856. tokenStart -= startPosition;
  35857. newTokens.add (SyntaxToken (lineText.substring (jmax (0, tokenStart), tokenEnd),
  35858. tokenType));
  35859. if (tokenEnd >= lineLength)
  35860. break;
  35861. }
  35862. lastIterator = source;
  35863. }
  35864. source = lastIterator;
  35865. }
  35866. static void replaceTabsWithSpaces (Array <SyntaxToken>& tokens, const int spacesPerTab) throw()
  35867. {
  35868. int x = 0;
  35869. for (int i = 0; i < tokens.size(); ++i)
  35870. {
  35871. SyntaxToken& t = tokens.getReference(i);
  35872. for (;;)
  35873. {
  35874. int tabPos = t.text.indexOfChar ('\t');
  35875. if (tabPos < 0)
  35876. break;
  35877. const int spacesNeeded = spacesPerTab - ((tabPos + x) % spacesPerTab);
  35878. t.text = t.text.replaceSection (tabPos, 1, String::repeatedString (" ", spacesNeeded));
  35879. }
  35880. x += t.text.length();
  35881. }
  35882. }
  35883. int indexToColumn (int index, const String& line, int spacesPerTab) const throw()
  35884. {
  35885. jassert (index <= line.length());
  35886. int col = 0;
  35887. for (int i = 0; i < index; ++i)
  35888. {
  35889. if (line[i] != '\t')
  35890. ++col;
  35891. else
  35892. col += spacesPerTab - (col % spacesPerTab);
  35893. }
  35894. return col;
  35895. }
  35896. };
  35897. CodeEditorComponent::CodeEditorComponent (CodeDocument& document_,
  35898. CodeTokeniser* const codeTokeniser_)
  35899. : document (document_),
  35900. firstLineOnScreen (0),
  35901. gutter (5),
  35902. spacesPerTab (4),
  35903. lineHeight (0),
  35904. linesOnScreen (0),
  35905. columnsOnScreen (0),
  35906. scrollbarThickness (16),
  35907. columnToTryToMaintain (-1),
  35908. useSpacesForTabs (false),
  35909. xOffset (0),
  35910. codeTokeniser (codeTokeniser_)
  35911. {
  35912. caretPos = CodeDocument::Position (&document_, 0, 0);
  35913. caretPos.setPositionMaintained (true);
  35914. selectionStart = CodeDocument::Position (&document_, 0, 0);
  35915. selectionStart.setPositionMaintained (true);
  35916. selectionEnd = CodeDocument::Position (&document_, 0, 0);
  35917. selectionEnd.setPositionMaintained (true);
  35918. setOpaque (true);
  35919. setMouseCursor (MouseCursor (MouseCursor::IBeamCursor));
  35920. setWantsKeyboardFocus (true);
  35921. addAndMakeVisible (verticalScrollBar = new ScrollBar (true));
  35922. verticalScrollBar->setSingleStepSize (1.0);
  35923. addAndMakeVisible (horizontalScrollBar = new ScrollBar (false));
  35924. horizontalScrollBar->setSingleStepSize (1.0);
  35925. addAndMakeVisible (caret = new CaretComponent (*this));
  35926. Font f (12.0f);
  35927. f.setTypefaceName (Font::getDefaultMonospacedFontName());
  35928. setFont (f);
  35929. resetToDefaultColours();
  35930. verticalScrollBar->addListener (this);
  35931. horizontalScrollBar->addListener (this);
  35932. document.addListener (this);
  35933. }
  35934. CodeEditorComponent::~CodeEditorComponent()
  35935. {
  35936. document.removeListener (this);
  35937. deleteAllChildren();
  35938. }
  35939. void CodeEditorComponent::loadContent (const String& newContent)
  35940. {
  35941. clearCachedIterators (0);
  35942. document.replaceAllContent (newContent);
  35943. document.clearUndoHistory();
  35944. document.setSavePoint();
  35945. caretPos.setPosition (0);
  35946. selectionStart.setPosition (0);
  35947. selectionEnd.setPosition (0);
  35948. scrollToLine (0);
  35949. }
  35950. bool CodeEditorComponent::isTextInputActive() const
  35951. {
  35952. return true;
  35953. }
  35954. void CodeEditorComponent::codeDocumentChanged (const CodeDocument::Position& affectedTextStart,
  35955. const CodeDocument::Position& affectedTextEnd)
  35956. {
  35957. clearCachedIterators (affectedTextStart.getLineNumber());
  35958. triggerAsyncUpdate();
  35959. caret->updatePosition();
  35960. columnToTryToMaintain = -1;
  35961. if (affectedTextEnd.getPosition() >= selectionStart.getPosition()
  35962. && affectedTextStart.getPosition() <= selectionEnd.getPosition())
  35963. deselectAll();
  35964. if (caretPos.getPosition() > affectedTextEnd.getPosition()
  35965. || caretPos.getPosition() < affectedTextStart.getPosition())
  35966. moveCaretTo (affectedTextStart, false);
  35967. updateScrollBars();
  35968. }
  35969. void CodeEditorComponent::resized()
  35970. {
  35971. linesOnScreen = (getHeight() - scrollbarThickness) / lineHeight;
  35972. columnsOnScreen = (int) ((getWidth() - scrollbarThickness) / charWidth);
  35973. lines.clear();
  35974. rebuildLineTokens();
  35975. caret->updatePosition();
  35976. verticalScrollBar->setBounds (getWidth() - scrollbarThickness, 0, scrollbarThickness, getHeight() - scrollbarThickness);
  35977. horizontalScrollBar->setBounds (gutter, getHeight() - scrollbarThickness, getWidth() - scrollbarThickness - gutter, scrollbarThickness);
  35978. updateScrollBars();
  35979. }
  35980. void CodeEditorComponent::paint (Graphics& g)
  35981. {
  35982. handleUpdateNowIfNeeded();
  35983. g.fillAll (findColour (CodeEditorComponent::backgroundColourId));
  35984. g.reduceClipRegion (gutter, 0, verticalScrollBar->getX() - gutter, horizontalScrollBar->getY());
  35985. g.setFont (font);
  35986. const int baselineOffset = (int) font.getAscent();
  35987. const Colour defaultColour (findColour (CodeEditorComponent::defaultTextColourId));
  35988. const Colour highlightColour (findColour (CodeEditorComponent::highlightColourId));
  35989. const Rectangle<int> clip (g.getClipBounds());
  35990. const int firstLineToDraw = jmax (0, clip.getY() / lineHeight);
  35991. const int lastLineToDraw = jmin (lines.size(), clip.getBottom() / lineHeight + 1);
  35992. for (int j = firstLineToDraw; j < lastLineToDraw; ++j)
  35993. {
  35994. lines.getUnchecked(j)->draw (*this, g, font,
  35995. (float) (gutter - xOffset * charWidth),
  35996. lineHeight * j, baselineOffset, lineHeight,
  35997. highlightColour);
  35998. }
  35999. }
  36000. void CodeEditorComponent::setScrollbarThickness (const int thickness) throw()
  36001. {
  36002. if (scrollbarThickness != thickness)
  36003. {
  36004. scrollbarThickness = thickness;
  36005. resized();
  36006. }
  36007. }
  36008. void CodeEditorComponent::handleAsyncUpdate()
  36009. {
  36010. rebuildLineTokens();
  36011. }
  36012. void CodeEditorComponent::rebuildLineTokens()
  36013. {
  36014. cancelPendingUpdate();
  36015. const int numNeeded = linesOnScreen + 1;
  36016. int minLineToRepaint = numNeeded;
  36017. int maxLineToRepaint = 0;
  36018. if (numNeeded != lines.size())
  36019. {
  36020. lines.clear();
  36021. for (int i = numNeeded; --i >= 0;)
  36022. lines.add (new CodeEditorLine());
  36023. minLineToRepaint = 0;
  36024. maxLineToRepaint = numNeeded;
  36025. }
  36026. jassert (numNeeded == lines.size());
  36027. CodeDocument::Iterator source (&document);
  36028. getIteratorForPosition (CodeDocument::Position (&document, firstLineOnScreen, 0).getPosition(), source);
  36029. for (int i = 0; i < numNeeded; ++i)
  36030. {
  36031. CodeEditorLine* const line = lines.getUnchecked(i);
  36032. if (line->update (document, firstLineOnScreen + i, source, codeTokeniser, spacesPerTab,
  36033. selectionStart, selectionEnd))
  36034. {
  36035. minLineToRepaint = jmin (minLineToRepaint, i);
  36036. maxLineToRepaint = jmax (maxLineToRepaint, i);
  36037. }
  36038. }
  36039. if (minLineToRepaint <= maxLineToRepaint)
  36040. {
  36041. repaint (gutter, lineHeight * minLineToRepaint - 1,
  36042. verticalScrollBar->getX() - gutter,
  36043. lineHeight * (1 + maxLineToRepaint - minLineToRepaint) + 2);
  36044. }
  36045. }
  36046. void CodeEditorComponent::moveCaretTo (const CodeDocument::Position& newPos, const bool highlighting)
  36047. {
  36048. caretPos = newPos;
  36049. columnToTryToMaintain = -1;
  36050. if (highlighting)
  36051. {
  36052. if (dragType == notDragging)
  36053. {
  36054. if (abs (caretPos.getPosition() - selectionStart.getPosition())
  36055. < abs (caretPos.getPosition() - selectionEnd.getPosition()))
  36056. dragType = draggingSelectionStart;
  36057. else
  36058. dragType = draggingSelectionEnd;
  36059. }
  36060. if (dragType == draggingSelectionStart)
  36061. {
  36062. selectionStart = caretPos;
  36063. if (selectionEnd.getPosition() < selectionStart.getPosition())
  36064. {
  36065. const CodeDocument::Position temp (selectionStart);
  36066. selectionStart = selectionEnd;
  36067. selectionEnd = temp;
  36068. dragType = draggingSelectionEnd;
  36069. }
  36070. }
  36071. else
  36072. {
  36073. selectionEnd = caretPos;
  36074. if (selectionEnd.getPosition() < selectionStart.getPosition())
  36075. {
  36076. const CodeDocument::Position temp (selectionStart);
  36077. selectionStart = selectionEnd;
  36078. selectionEnd = temp;
  36079. dragType = draggingSelectionStart;
  36080. }
  36081. }
  36082. triggerAsyncUpdate();
  36083. }
  36084. else
  36085. {
  36086. deselectAll();
  36087. }
  36088. caret->updatePosition();
  36089. scrollToKeepCaretOnScreen();
  36090. updateScrollBars();
  36091. }
  36092. void CodeEditorComponent::deselectAll()
  36093. {
  36094. if (selectionStart != selectionEnd)
  36095. triggerAsyncUpdate();
  36096. selectionStart = caretPos;
  36097. selectionEnd = caretPos;
  36098. }
  36099. void CodeEditorComponent::updateScrollBars()
  36100. {
  36101. verticalScrollBar->setRangeLimits (0, jmax (document.getNumLines(), firstLineOnScreen + linesOnScreen));
  36102. verticalScrollBar->setCurrentRange (firstLineOnScreen, linesOnScreen);
  36103. horizontalScrollBar->setRangeLimits (0, jmax ((double) document.getMaximumLineLength(), xOffset + columnsOnScreen));
  36104. horizontalScrollBar->setCurrentRange (xOffset, columnsOnScreen);
  36105. }
  36106. void CodeEditorComponent::scrollToLineInternal (int newFirstLineOnScreen)
  36107. {
  36108. newFirstLineOnScreen = jlimit (0, jmax (0, document.getNumLines() - 1),
  36109. newFirstLineOnScreen);
  36110. if (newFirstLineOnScreen != firstLineOnScreen)
  36111. {
  36112. firstLineOnScreen = newFirstLineOnScreen;
  36113. caret->updatePosition();
  36114. updateCachedIterators (firstLineOnScreen);
  36115. triggerAsyncUpdate();
  36116. }
  36117. }
  36118. void CodeEditorComponent::scrollToColumnInternal (double column)
  36119. {
  36120. const double newOffset = jlimit (0.0, document.getMaximumLineLength() + 3.0, column);
  36121. if (xOffset != newOffset)
  36122. {
  36123. xOffset = newOffset;
  36124. caret->updatePosition();
  36125. repaint();
  36126. }
  36127. }
  36128. void CodeEditorComponent::scrollToLine (int newFirstLineOnScreen)
  36129. {
  36130. scrollToLineInternal (newFirstLineOnScreen);
  36131. updateScrollBars();
  36132. }
  36133. void CodeEditorComponent::scrollToColumn (int newFirstColumnOnScreen)
  36134. {
  36135. scrollToColumnInternal (newFirstColumnOnScreen);
  36136. updateScrollBars();
  36137. }
  36138. void CodeEditorComponent::scrollBy (int deltaLines)
  36139. {
  36140. scrollToLine (firstLineOnScreen + deltaLines);
  36141. }
  36142. void CodeEditorComponent::scrollToKeepCaretOnScreen()
  36143. {
  36144. if (caretPos.getLineNumber() < firstLineOnScreen)
  36145. scrollBy (caretPos.getLineNumber() - firstLineOnScreen);
  36146. else if (caretPos.getLineNumber() >= firstLineOnScreen + linesOnScreen)
  36147. scrollBy (caretPos.getLineNumber() - (firstLineOnScreen + linesOnScreen - 1));
  36148. const int column = indexToColumn (caretPos.getLineNumber(), caretPos.getIndexInLine());
  36149. if (column >= xOffset + columnsOnScreen - 1)
  36150. scrollToColumn (column + 1 - columnsOnScreen);
  36151. else if (column < xOffset)
  36152. scrollToColumn (column);
  36153. }
  36154. const Rectangle<int> CodeEditorComponent::getCharacterBounds (const CodeDocument::Position& pos) const throw()
  36155. {
  36156. return Rectangle<int> (roundToInt ((gutter - xOffset * charWidth) + indexToColumn (pos.getLineNumber(), pos.getIndexInLine()) * charWidth),
  36157. (pos.getLineNumber() - firstLineOnScreen) * lineHeight,
  36158. roundToInt (charWidth),
  36159. lineHeight);
  36160. }
  36161. const CodeDocument::Position CodeEditorComponent::getPositionAt (int x, int y)
  36162. {
  36163. const int line = y / lineHeight + firstLineOnScreen;
  36164. const int column = roundToInt ((x - (gutter - xOffset * charWidth)) / charWidth);
  36165. const int index = columnToIndex (line, column);
  36166. return CodeDocument::Position (&document, line, index);
  36167. }
  36168. void CodeEditorComponent::insertTextAtCaret (const String& newText)
  36169. {
  36170. document.deleteSection (selectionStart, selectionEnd);
  36171. if (newText.isNotEmpty())
  36172. document.insertText (caretPos, newText);
  36173. scrollToKeepCaretOnScreen();
  36174. }
  36175. void CodeEditorComponent::insertTabAtCaret()
  36176. {
  36177. if (CharacterFunctions::isWhitespace (caretPos.getCharacter())
  36178. && caretPos.getLineNumber() == caretPos.movedBy (1).getLineNumber())
  36179. {
  36180. moveCaretTo (document.findWordBreakAfter (caretPos), false);
  36181. }
  36182. if (useSpacesForTabs)
  36183. {
  36184. const int caretCol = indexToColumn (caretPos.getLineNumber(), caretPos.getIndexInLine());
  36185. const int spacesNeeded = spacesPerTab - (caretCol % spacesPerTab);
  36186. insertTextAtCaret (String::repeatedString (" ", spacesNeeded));
  36187. }
  36188. else
  36189. {
  36190. insertTextAtCaret ("\t");
  36191. }
  36192. }
  36193. void CodeEditorComponent::cut()
  36194. {
  36195. insertTextAtCaret (String::empty);
  36196. }
  36197. void CodeEditorComponent::copy()
  36198. {
  36199. newTransaction();
  36200. const String selection (document.getTextBetween (selectionStart, selectionEnd));
  36201. if (selection.isNotEmpty())
  36202. SystemClipboard::copyTextToClipboard (selection);
  36203. }
  36204. void CodeEditorComponent::copyThenCut()
  36205. {
  36206. copy();
  36207. cut();
  36208. newTransaction();
  36209. }
  36210. void CodeEditorComponent::paste()
  36211. {
  36212. newTransaction();
  36213. const String clip (SystemClipboard::getTextFromClipboard());
  36214. if (clip.isNotEmpty())
  36215. insertTextAtCaret (clip);
  36216. newTransaction();
  36217. }
  36218. void CodeEditorComponent::cursorLeft (const bool moveInWholeWordSteps, const bool selecting)
  36219. {
  36220. newTransaction();
  36221. if (moveInWholeWordSteps)
  36222. moveCaretTo (document.findWordBreakBefore (caretPos), selecting);
  36223. else
  36224. moveCaretTo (caretPos.movedBy (-1), selecting);
  36225. }
  36226. void CodeEditorComponent::cursorRight (const bool moveInWholeWordSteps, const bool selecting)
  36227. {
  36228. newTransaction();
  36229. if (moveInWholeWordSteps)
  36230. moveCaretTo (document.findWordBreakAfter (caretPos), selecting);
  36231. else
  36232. moveCaretTo (caretPos.movedBy (1), selecting);
  36233. }
  36234. void CodeEditorComponent::moveLineDelta (const int delta, const bool selecting)
  36235. {
  36236. CodeDocument::Position pos (caretPos);
  36237. const int newLineNum = pos.getLineNumber() + delta;
  36238. if (columnToTryToMaintain < 0)
  36239. columnToTryToMaintain = indexToColumn (pos.getLineNumber(), pos.getIndexInLine());
  36240. pos.setLineAndIndex (newLineNum, columnToIndex (newLineNum, columnToTryToMaintain));
  36241. const int colToMaintain = columnToTryToMaintain;
  36242. moveCaretTo (pos, selecting);
  36243. columnToTryToMaintain = colToMaintain;
  36244. }
  36245. void CodeEditorComponent::cursorDown (const bool selecting)
  36246. {
  36247. newTransaction();
  36248. if (caretPos.getLineNumber() == document.getNumLines() - 1)
  36249. moveCaretTo (CodeDocument::Position (&document, std::numeric_limits<int>::max(), std::numeric_limits<int>::max()), selecting);
  36250. else
  36251. moveLineDelta (1, selecting);
  36252. }
  36253. void CodeEditorComponent::cursorUp (const bool selecting)
  36254. {
  36255. newTransaction();
  36256. if (caretPos.getLineNumber() == 0)
  36257. moveCaretTo (CodeDocument::Position (&document, 0, 0), selecting);
  36258. else
  36259. moveLineDelta (-1, selecting);
  36260. }
  36261. void CodeEditorComponent::pageDown (const bool selecting)
  36262. {
  36263. newTransaction();
  36264. scrollBy (jlimit (0, linesOnScreen, 1 + document.getNumLines() - firstLineOnScreen - linesOnScreen));
  36265. moveLineDelta (linesOnScreen, selecting);
  36266. }
  36267. void CodeEditorComponent::pageUp (const bool selecting)
  36268. {
  36269. newTransaction();
  36270. scrollBy (-linesOnScreen);
  36271. moveLineDelta (-linesOnScreen, selecting);
  36272. }
  36273. void CodeEditorComponent::scrollUp()
  36274. {
  36275. newTransaction();
  36276. scrollBy (1);
  36277. if (caretPos.getLineNumber() < firstLineOnScreen)
  36278. moveLineDelta (1, false);
  36279. }
  36280. void CodeEditorComponent::scrollDown()
  36281. {
  36282. newTransaction();
  36283. scrollBy (-1);
  36284. if (caretPos.getLineNumber() >= firstLineOnScreen + linesOnScreen)
  36285. moveLineDelta (-1, false);
  36286. }
  36287. void CodeEditorComponent::goToStartOfDocument (const bool selecting)
  36288. {
  36289. newTransaction();
  36290. moveCaretTo (CodeDocument::Position (&document, 0, 0), selecting);
  36291. }
  36292. static int findFirstNonWhitespaceChar (const String& line) throw()
  36293. {
  36294. const int len = line.length();
  36295. for (int i = 0; i < len; ++i)
  36296. if (! CharacterFunctions::isWhitespace (line [i]))
  36297. return i;
  36298. return 0;
  36299. }
  36300. void CodeEditorComponent::goToStartOfLine (const bool selecting)
  36301. {
  36302. newTransaction();
  36303. int index = findFirstNonWhitespaceChar (caretPos.getLineText());
  36304. if (index >= caretPos.getIndexInLine() && caretPos.getIndexInLine() > 0)
  36305. index = 0;
  36306. moveCaretTo (CodeDocument::Position (&document, caretPos.getLineNumber(), index), selecting);
  36307. }
  36308. void CodeEditorComponent::goToEndOfDocument (const bool selecting)
  36309. {
  36310. newTransaction();
  36311. moveCaretTo (CodeDocument::Position (&document, std::numeric_limits<int>::max(), std::numeric_limits<int>::max()), selecting);
  36312. }
  36313. void CodeEditorComponent::goToEndOfLine (const bool selecting)
  36314. {
  36315. newTransaction();
  36316. moveCaretTo (CodeDocument::Position (&document, caretPos.getLineNumber(), std::numeric_limits<int>::max()), selecting);
  36317. }
  36318. void CodeEditorComponent::backspace (const bool moveInWholeWordSteps)
  36319. {
  36320. if (moveInWholeWordSteps)
  36321. {
  36322. cut(); // in case something is already highlighted
  36323. moveCaretTo (document.findWordBreakBefore (caretPos), true);
  36324. }
  36325. else
  36326. {
  36327. if (selectionStart == selectionEnd)
  36328. selectionStart.moveBy (-1);
  36329. }
  36330. cut();
  36331. }
  36332. void CodeEditorComponent::deleteForward (const bool moveInWholeWordSteps)
  36333. {
  36334. if (moveInWholeWordSteps)
  36335. {
  36336. cut(); // in case something is already highlighted
  36337. moveCaretTo (document.findWordBreakAfter (caretPos), true);
  36338. }
  36339. else
  36340. {
  36341. if (selectionStart == selectionEnd)
  36342. selectionEnd.moveBy (1);
  36343. else
  36344. newTransaction();
  36345. }
  36346. cut();
  36347. }
  36348. void CodeEditorComponent::selectAll()
  36349. {
  36350. newTransaction();
  36351. moveCaretTo (CodeDocument::Position (&document, std::numeric_limits<int>::max(), std::numeric_limits<int>::max()), false);
  36352. moveCaretTo (CodeDocument::Position (&document, 0, 0), true);
  36353. }
  36354. void CodeEditorComponent::undo()
  36355. {
  36356. document.undo();
  36357. scrollToKeepCaretOnScreen();
  36358. }
  36359. void CodeEditorComponent::redo()
  36360. {
  36361. document.redo();
  36362. scrollToKeepCaretOnScreen();
  36363. }
  36364. void CodeEditorComponent::newTransaction()
  36365. {
  36366. document.newTransaction();
  36367. startTimer (600);
  36368. }
  36369. void CodeEditorComponent::timerCallback()
  36370. {
  36371. newTransaction();
  36372. }
  36373. const Range<int> CodeEditorComponent::getHighlightedRegion() const
  36374. {
  36375. return Range<int> (selectionStart.getPosition(), selectionEnd.getPosition());
  36376. }
  36377. void CodeEditorComponent::setHighlightedRegion (const Range<int>& newRange)
  36378. {
  36379. moveCaretTo (CodeDocument::Position (&document, newRange.getStart()), false);
  36380. moveCaretTo (CodeDocument::Position (&document, newRange.getEnd()), true);
  36381. }
  36382. const String CodeEditorComponent::getTextInRange (const Range<int>& range) const
  36383. {
  36384. return document.getTextBetween (CodeDocument::Position (&document, range.getStart()),
  36385. CodeDocument::Position (&document, range.getEnd()));
  36386. }
  36387. bool CodeEditorComponent::keyPressed (const KeyPress& key)
  36388. {
  36389. const bool moveInWholeWordSteps = key.getModifiers().isCtrlDown() || key.getModifiers().isAltDown();
  36390. const bool shiftDown = key.getModifiers().isShiftDown();
  36391. if (key.isKeyCode (KeyPress::leftKey))
  36392. {
  36393. cursorLeft (moveInWholeWordSteps, shiftDown);
  36394. }
  36395. else if (key.isKeyCode (KeyPress::rightKey))
  36396. {
  36397. cursorRight (moveInWholeWordSteps, shiftDown);
  36398. }
  36399. else if (key.isKeyCode (KeyPress::upKey))
  36400. {
  36401. if (key.getModifiers().isCtrlDown() && ! shiftDown)
  36402. scrollDown();
  36403. #if JUCE_MAC
  36404. else if (key.getModifiers().isCommandDown())
  36405. goToStartOfDocument (shiftDown);
  36406. #endif
  36407. else
  36408. cursorUp (shiftDown);
  36409. }
  36410. else if (key.isKeyCode (KeyPress::downKey))
  36411. {
  36412. if (key.getModifiers().isCtrlDown() && ! shiftDown)
  36413. scrollUp();
  36414. #if JUCE_MAC
  36415. else if (key.getModifiers().isCommandDown())
  36416. goToEndOfDocument (shiftDown);
  36417. #endif
  36418. else
  36419. cursorDown (shiftDown);
  36420. }
  36421. else if (key.isKeyCode (KeyPress::pageDownKey))
  36422. {
  36423. pageDown (shiftDown);
  36424. }
  36425. else if (key.isKeyCode (KeyPress::pageUpKey))
  36426. {
  36427. pageUp (shiftDown);
  36428. }
  36429. else if (key.isKeyCode (KeyPress::homeKey))
  36430. {
  36431. if (moveInWholeWordSteps)
  36432. goToStartOfDocument (shiftDown);
  36433. else
  36434. goToStartOfLine (shiftDown);
  36435. }
  36436. else if (key.isKeyCode (KeyPress::endKey))
  36437. {
  36438. if (moveInWholeWordSteps)
  36439. goToEndOfDocument (shiftDown);
  36440. else
  36441. goToEndOfLine (shiftDown);
  36442. }
  36443. else if (key.isKeyCode (KeyPress::backspaceKey))
  36444. {
  36445. backspace (moveInWholeWordSteps);
  36446. }
  36447. else if (key.isKeyCode (KeyPress::deleteKey))
  36448. {
  36449. deleteForward (moveInWholeWordSteps);
  36450. }
  36451. else if (key == KeyPress ('c', ModifierKeys::commandModifier, 0))
  36452. {
  36453. copy();
  36454. }
  36455. else if (key == KeyPress ('x', ModifierKeys::commandModifier, 0))
  36456. {
  36457. copyThenCut();
  36458. }
  36459. else if (key == KeyPress ('v', ModifierKeys::commandModifier, 0))
  36460. {
  36461. paste();
  36462. }
  36463. else if (key == KeyPress ('z', ModifierKeys::commandModifier, 0))
  36464. {
  36465. undo();
  36466. }
  36467. else if (key == KeyPress ('y', ModifierKeys::commandModifier, 0)
  36468. || key == KeyPress ('z', ModifierKeys::commandModifier | ModifierKeys::shiftModifier, 0))
  36469. {
  36470. redo();
  36471. }
  36472. else if (key == KeyPress ('a', ModifierKeys::commandModifier, 0))
  36473. {
  36474. selectAll();
  36475. }
  36476. else if (key == KeyPress::tabKey || key.getTextCharacter() == '\t')
  36477. {
  36478. insertTabAtCaret();
  36479. }
  36480. else if (key == KeyPress::returnKey)
  36481. {
  36482. newTransaction();
  36483. insertTextAtCaret (document.getNewLineCharacters());
  36484. }
  36485. else if (key.isKeyCode (KeyPress::escapeKey))
  36486. {
  36487. newTransaction();
  36488. }
  36489. else if (key.getTextCharacter() >= ' ')
  36490. {
  36491. insertTextAtCaret (String::charToString (key.getTextCharacter()));
  36492. }
  36493. else
  36494. {
  36495. return false;
  36496. }
  36497. return true;
  36498. }
  36499. void CodeEditorComponent::mouseDown (const MouseEvent& e)
  36500. {
  36501. newTransaction();
  36502. dragType = notDragging;
  36503. if (! e.mods.isPopupMenu())
  36504. {
  36505. beginDragAutoRepeat (100);
  36506. moveCaretTo (getPositionAt (e.x, e.y), e.mods.isShiftDown());
  36507. }
  36508. else
  36509. {
  36510. /*PopupMenu m;
  36511. addPopupMenuItems (m, &e);
  36512. const int result = m.show();
  36513. if (result != 0)
  36514. performPopupMenuAction (result);
  36515. */
  36516. }
  36517. }
  36518. void CodeEditorComponent::mouseDrag (const MouseEvent& e)
  36519. {
  36520. if (! e.mods.isPopupMenu())
  36521. moveCaretTo (getPositionAt (e.x, e.y), true);
  36522. }
  36523. void CodeEditorComponent::mouseUp (const MouseEvent&)
  36524. {
  36525. newTransaction();
  36526. beginDragAutoRepeat (0);
  36527. dragType = notDragging;
  36528. }
  36529. void CodeEditorComponent::mouseDoubleClick (const MouseEvent& e)
  36530. {
  36531. CodeDocument::Position tokenStart (getPositionAt (e.x, e.y));
  36532. CodeDocument::Position tokenEnd (tokenStart);
  36533. if (e.getNumberOfClicks() > 2)
  36534. {
  36535. tokenStart.setLineAndIndex (tokenStart.getLineNumber(), 0);
  36536. tokenEnd.setLineAndIndex (tokenStart.getLineNumber() + 1, 0);
  36537. }
  36538. else
  36539. {
  36540. while (CharacterFunctions::isLetterOrDigit (tokenEnd.getCharacter()))
  36541. tokenEnd.moveBy (1);
  36542. tokenStart = tokenEnd;
  36543. while (tokenStart.getIndexInLine() > 0
  36544. && CharacterFunctions::isLetterOrDigit (tokenStart.movedBy (-1).getCharacter()))
  36545. tokenStart.moveBy (-1);
  36546. }
  36547. moveCaretTo (tokenEnd, false);
  36548. moveCaretTo (tokenStart, true);
  36549. }
  36550. void CodeEditorComponent::mouseWheelMove (const MouseEvent& e, float wheelIncrementX, float wheelIncrementY)
  36551. {
  36552. if ((verticalScrollBar->isVisible() && wheelIncrementY != 0)
  36553. || (horizontalScrollBar->isVisible() && wheelIncrementX != 0))
  36554. {
  36555. verticalScrollBar->mouseWheelMove (e, 0, wheelIncrementY);
  36556. horizontalScrollBar->mouseWheelMove (e, wheelIncrementX, 0);
  36557. }
  36558. else
  36559. {
  36560. Component::mouseWheelMove (e, wheelIncrementX, wheelIncrementY);
  36561. }
  36562. }
  36563. void CodeEditorComponent::scrollBarMoved (ScrollBar* scrollBarThatHasMoved, double newRangeStart)
  36564. {
  36565. if (scrollBarThatHasMoved == verticalScrollBar)
  36566. scrollToLineInternal ((int) newRangeStart);
  36567. else
  36568. scrollToColumnInternal (newRangeStart);
  36569. }
  36570. void CodeEditorComponent::focusGained (FocusChangeType cause)
  36571. {
  36572. caret->updatePosition();
  36573. }
  36574. void CodeEditorComponent::focusLost (FocusChangeType cause)
  36575. {
  36576. caret->updatePosition();
  36577. }
  36578. void CodeEditorComponent::setTabSize (const int numSpaces, const bool insertSpaces) throw()
  36579. {
  36580. useSpacesForTabs = insertSpaces;
  36581. if (spacesPerTab != numSpaces)
  36582. {
  36583. spacesPerTab = numSpaces;
  36584. triggerAsyncUpdate();
  36585. }
  36586. }
  36587. int CodeEditorComponent::indexToColumn (int lineNum, int index) const throw()
  36588. {
  36589. const String line (document.getLine (lineNum));
  36590. jassert (index <= line.length());
  36591. int col = 0;
  36592. for (int i = 0; i < index; ++i)
  36593. {
  36594. if (line[i] != '\t')
  36595. ++col;
  36596. else
  36597. col += getTabSize() - (col % getTabSize());
  36598. }
  36599. return col;
  36600. }
  36601. int CodeEditorComponent::columnToIndex (int lineNum, int column) const throw()
  36602. {
  36603. const String line (document.getLine (lineNum));
  36604. const int lineLength = line.length();
  36605. int i, col = 0;
  36606. for (i = 0; i < lineLength; ++i)
  36607. {
  36608. if (line[i] != '\t')
  36609. ++col;
  36610. else
  36611. col += getTabSize() - (col % getTabSize());
  36612. if (col > column)
  36613. break;
  36614. }
  36615. return i;
  36616. }
  36617. void CodeEditorComponent::setFont (const Font& newFont)
  36618. {
  36619. font = newFont;
  36620. charWidth = font.getStringWidthFloat ("0");
  36621. lineHeight = roundToInt (font.getHeight());
  36622. resized();
  36623. }
  36624. void CodeEditorComponent::resetToDefaultColours()
  36625. {
  36626. coloursForTokenCategories.clear();
  36627. if (codeTokeniser != 0)
  36628. {
  36629. for (int i = codeTokeniser->getTokenTypes().size(); --i >= 0;)
  36630. setColourForTokenType (i, codeTokeniser->getDefaultColour (i));
  36631. }
  36632. }
  36633. void CodeEditorComponent::setColourForTokenType (const int tokenType, const Colour& colour)
  36634. {
  36635. jassert (tokenType < 256);
  36636. while (coloursForTokenCategories.size() < tokenType)
  36637. coloursForTokenCategories.add (Colours::black);
  36638. coloursForTokenCategories.set (tokenType, colour);
  36639. repaint();
  36640. }
  36641. const Colour CodeEditorComponent::getColourForTokenType (const int tokenType) const throw()
  36642. {
  36643. if (((unsigned int) tokenType) >= (unsigned int) coloursForTokenCategories.size())
  36644. return findColour (CodeEditorComponent::defaultTextColourId);
  36645. return coloursForTokenCategories.getReference (tokenType);
  36646. }
  36647. void CodeEditorComponent::clearCachedIterators (const int firstLineToBeInvalid) throw()
  36648. {
  36649. int i;
  36650. for (i = cachedIterators.size(); --i >= 0;)
  36651. if (cachedIterators.getUnchecked (i)->getLine() < firstLineToBeInvalid)
  36652. break;
  36653. cachedIterators.removeRange (jmax (0, i - 1), cachedIterators.size());
  36654. }
  36655. void CodeEditorComponent::updateCachedIterators (int maxLineNum)
  36656. {
  36657. const int maxNumCachedPositions = 5000;
  36658. const int linesBetweenCachedSources = jmax (10, document.getNumLines() / maxNumCachedPositions);
  36659. if (cachedIterators.size() == 0)
  36660. cachedIterators.add (new CodeDocument::Iterator (&document));
  36661. if (codeTokeniser == 0)
  36662. return;
  36663. for (;;)
  36664. {
  36665. CodeDocument::Iterator* last = cachedIterators.getLast();
  36666. if (last->getLine() >= maxLineNum)
  36667. break;
  36668. CodeDocument::Iterator* t = new CodeDocument::Iterator (*last);
  36669. cachedIterators.add (t);
  36670. const int targetLine = last->getLine() + linesBetweenCachedSources;
  36671. for (;;)
  36672. {
  36673. codeTokeniser->readNextToken (*t);
  36674. if (t->getLine() >= targetLine)
  36675. break;
  36676. if (t->isEOF())
  36677. return;
  36678. }
  36679. }
  36680. }
  36681. void CodeEditorComponent::getIteratorForPosition (int position, CodeDocument::Iterator& source)
  36682. {
  36683. if (codeTokeniser == 0)
  36684. return;
  36685. for (int i = cachedIterators.size(); --i >= 0;)
  36686. {
  36687. CodeDocument::Iterator* t = cachedIterators.getUnchecked (i);
  36688. if (t->getPosition() <= position)
  36689. {
  36690. source = *t;
  36691. break;
  36692. }
  36693. }
  36694. while (source.getPosition() < position)
  36695. {
  36696. const CodeDocument::Iterator original (source);
  36697. codeTokeniser->readNextToken (source);
  36698. if (source.getPosition() > position || source.isEOF())
  36699. {
  36700. source = original;
  36701. break;
  36702. }
  36703. }
  36704. }
  36705. END_JUCE_NAMESPACE
  36706. /*** End of inlined file: juce_CodeEditorComponent.cpp ***/
  36707. /*** Start of inlined file: juce_CPlusPlusCodeTokeniser.cpp ***/
  36708. BEGIN_JUCE_NAMESPACE
  36709. CPlusPlusCodeTokeniser::CPlusPlusCodeTokeniser()
  36710. {
  36711. }
  36712. CPlusPlusCodeTokeniser::~CPlusPlusCodeTokeniser()
  36713. {
  36714. }
  36715. namespace CppTokeniser
  36716. {
  36717. static bool isIdentifierStart (const juce_wchar c) throw()
  36718. {
  36719. return CharacterFunctions::isLetter (c)
  36720. || c == '_' || c == '@';
  36721. }
  36722. static bool isIdentifierBody (const juce_wchar c) throw()
  36723. {
  36724. return CharacterFunctions::isLetter (c)
  36725. || CharacterFunctions::isDigit (c)
  36726. || c == '_' || c == '@';
  36727. }
  36728. static int parseIdentifier (CodeDocument::Iterator& source) throw()
  36729. {
  36730. static const juce_wchar* keywords2Char[] =
  36731. { T("if"), T("do"), T("or"), 0 };
  36732. static const juce_wchar* keywords3Char[] =
  36733. { T("for"), T("int"), T("new"), T("try"), T("xor"), T("and"), T("asm"), T("not"), 0 };
  36734. static const juce_wchar* keywords4Char[] =
  36735. { T("bool"), T("void"), T("this"), T("true"), T("long"), T("else"), T("char"),
  36736. T("enum"), T("case"), T("goto"), T("auto"), 0 };
  36737. static const juce_wchar* keywords5Char[] =
  36738. { T("while"), T("bitor"), T("break"), T("catch"), T("class"), T("compl"), T("const"), T("false"),
  36739. T("float"), T("short"), T("throw"), T("union"), T("using"), T("or_eq"), 0 };
  36740. static const juce_wchar* keywords6Char[] =
  36741. { T("return"), T("struct"), T("and_eq"), T("bitand"), T("delete"), T("double"), T("extern"),
  36742. T("friend"), T("inline"), T("not_eq"), T("public"), T("sizeof"), T("static"), T("signed"),
  36743. T("switch"), T("typeid"), T("wchar_t"), T("xor_eq"), 0};
  36744. static const juce_wchar* keywordsOther[] =
  36745. { T("const_cast"), T("continue"), T("default"), T("explicit"), T("mutable"), T("namespace"),
  36746. T("operator"), T("private"), T("protected"), T("register"), T("reinterpret_cast"), T("static_cast"),
  36747. T("template"), T("typedef"), T("typename"), T("unsigned"), T("virtual"), T("volatile"),
  36748. T("@implementation"), T("@interface"), T("@end"), T("@synthesize"), T("@dynamic"), T("@public"),
  36749. T("@private"), T("@property"), T("@protected"), T("@class"), 0 };
  36750. int tokenLength = 0;
  36751. juce_wchar possibleIdentifier [19];
  36752. while (isIdentifierBody (source.peekNextChar()))
  36753. {
  36754. const juce_wchar c = source.nextChar();
  36755. if (tokenLength < numElementsInArray (possibleIdentifier) - 1)
  36756. possibleIdentifier [tokenLength] = c;
  36757. ++tokenLength;
  36758. }
  36759. if (tokenLength > 1 && tokenLength <= 16)
  36760. {
  36761. possibleIdentifier [tokenLength] = 0;
  36762. const juce_wchar** k;
  36763. switch (tokenLength)
  36764. {
  36765. case 2: k = keywords2Char; break;
  36766. case 3: k = keywords3Char; break;
  36767. case 4: k = keywords4Char; break;
  36768. case 5: k = keywords5Char; break;
  36769. case 6: k = keywords6Char; break;
  36770. default: k = keywordsOther; break;
  36771. }
  36772. int i = 0;
  36773. while (k[i] != 0)
  36774. {
  36775. if (k[i][0] == possibleIdentifier[0] && CharacterFunctions::compare (k[i], possibleIdentifier) == 0)
  36776. return CPlusPlusCodeTokeniser::tokenType_builtInKeyword;
  36777. ++i;
  36778. }
  36779. }
  36780. return CPlusPlusCodeTokeniser::tokenType_identifier;
  36781. }
  36782. static bool skipNumberSuffix (CodeDocument::Iterator& source)
  36783. {
  36784. const juce_wchar c = source.peekNextChar();
  36785. if (c == 'l' || c == 'L' || c == 'u' || c == 'U')
  36786. source.skip();
  36787. if (CharacterFunctions::isLetterOrDigit (source.peekNextChar()))
  36788. return false;
  36789. return true;
  36790. }
  36791. static bool isHexDigit (const juce_wchar c) throw()
  36792. {
  36793. return (c >= '0' && c <= '9')
  36794. || (c >= 'a' && c <= 'f')
  36795. || (c >= 'A' && c <= 'F');
  36796. }
  36797. static bool parseHexLiteral (CodeDocument::Iterator& source) throw()
  36798. {
  36799. if (source.nextChar() != '0')
  36800. return false;
  36801. juce_wchar c = source.nextChar();
  36802. if (c != 'x' && c != 'X')
  36803. return false;
  36804. int numDigits = 0;
  36805. while (isHexDigit (source.peekNextChar()))
  36806. {
  36807. ++numDigits;
  36808. source.skip();
  36809. }
  36810. if (numDigits == 0)
  36811. return false;
  36812. return skipNumberSuffix (source);
  36813. }
  36814. static bool isOctalDigit (const juce_wchar c) throw()
  36815. {
  36816. return c >= '0' && c <= '7';
  36817. }
  36818. static bool parseOctalLiteral (CodeDocument::Iterator& source) throw()
  36819. {
  36820. if (source.nextChar() != '0')
  36821. return false;
  36822. if (! isOctalDigit (source.nextChar()))
  36823. return false;
  36824. while (isOctalDigit (source.peekNextChar()))
  36825. source.skip();
  36826. return skipNumberSuffix (source);
  36827. }
  36828. static bool isDecimalDigit (const juce_wchar c) throw()
  36829. {
  36830. return c >= '0' && c <= '9';
  36831. }
  36832. static bool parseDecimalLiteral (CodeDocument::Iterator& source) throw()
  36833. {
  36834. int numChars = 0;
  36835. while (isDecimalDigit (source.peekNextChar()))
  36836. {
  36837. ++numChars;
  36838. source.skip();
  36839. }
  36840. if (numChars == 0)
  36841. return false;
  36842. return skipNumberSuffix (source);
  36843. }
  36844. static bool parseFloatLiteral (CodeDocument::Iterator& source) throw()
  36845. {
  36846. int numDigits = 0;
  36847. while (isDecimalDigit (source.peekNextChar()))
  36848. {
  36849. source.skip();
  36850. ++numDigits;
  36851. }
  36852. const bool hasPoint = (source.peekNextChar() == '.');
  36853. if (hasPoint)
  36854. {
  36855. source.skip();
  36856. while (isDecimalDigit (source.peekNextChar()))
  36857. {
  36858. source.skip();
  36859. ++numDigits;
  36860. }
  36861. }
  36862. if (numDigits == 0)
  36863. return false;
  36864. juce_wchar c = source.peekNextChar();
  36865. const bool hasExponent = (c == 'e' || c == 'E');
  36866. if (hasExponent)
  36867. {
  36868. source.skip();
  36869. c = source.peekNextChar();
  36870. if (c == '+' || c == '-')
  36871. source.skip();
  36872. int numExpDigits = 0;
  36873. while (isDecimalDigit (source.peekNextChar()))
  36874. {
  36875. source.skip();
  36876. ++numExpDigits;
  36877. }
  36878. if (numExpDigits == 0)
  36879. return false;
  36880. }
  36881. c = source.peekNextChar();
  36882. if (c == 'f' || c == 'F')
  36883. source.skip();
  36884. else if (! (hasExponent || hasPoint))
  36885. return false;
  36886. return true;
  36887. }
  36888. static int parseNumber (CodeDocument::Iterator& source)
  36889. {
  36890. const CodeDocument::Iterator original (source);
  36891. if (parseFloatLiteral (source))
  36892. return CPlusPlusCodeTokeniser::tokenType_floatLiteral;
  36893. source = original;
  36894. if (parseHexLiteral (source))
  36895. return CPlusPlusCodeTokeniser::tokenType_integerLiteral;
  36896. source = original;
  36897. if (parseOctalLiteral (source))
  36898. return CPlusPlusCodeTokeniser::tokenType_integerLiteral;
  36899. source = original;
  36900. if (parseDecimalLiteral (source))
  36901. return CPlusPlusCodeTokeniser::tokenType_integerLiteral;
  36902. source = original;
  36903. source.skip();
  36904. return CPlusPlusCodeTokeniser::tokenType_error;
  36905. }
  36906. static void skipQuotedString (CodeDocument::Iterator& source) throw()
  36907. {
  36908. const juce_wchar quote = source.nextChar();
  36909. for (;;)
  36910. {
  36911. const juce_wchar c = source.nextChar();
  36912. if (c == quote || c == 0)
  36913. break;
  36914. if (c == '\\')
  36915. source.skip();
  36916. }
  36917. }
  36918. static void skipComment (CodeDocument::Iterator& source) throw()
  36919. {
  36920. bool lastWasStar = false;
  36921. for (;;)
  36922. {
  36923. const juce_wchar c = source.nextChar();
  36924. if (c == 0 || (c == '/' && lastWasStar))
  36925. break;
  36926. lastWasStar = (c == '*');
  36927. }
  36928. }
  36929. }
  36930. int CPlusPlusCodeTokeniser::readNextToken (CodeDocument::Iterator& source)
  36931. {
  36932. int result = tokenType_error;
  36933. source.skipWhitespace();
  36934. juce_wchar firstChar = source.peekNextChar();
  36935. switch (firstChar)
  36936. {
  36937. case 0:
  36938. source.skip();
  36939. break;
  36940. case '0':
  36941. case '1':
  36942. case '2':
  36943. case '3':
  36944. case '4':
  36945. case '5':
  36946. case '6':
  36947. case '7':
  36948. case '8':
  36949. case '9':
  36950. result = CppTokeniser::parseNumber (source);
  36951. break;
  36952. case '.':
  36953. result = CppTokeniser::parseNumber (source);
  36954. if (result == tokenType_error)
  36955. result = tokenType_punctuation;
  36956. break;
  36957. case ',':
  36958. case ';':
  36959. case ':':
  36960. source.skip();
  36961. result = tokenType_punctuation;
  36962. break;
  36963. case '(':
  36964. case ')':
  36965. case '{':
  36966. case '}':
  36967. case '[':
  36968. case ']':
  36969. source.skip();
  36970. result = tokenType_bracket;
  36971. break;
  36972. case '"':
  36973. case '\'':
  36974. CppTokeniser::skipQuotedString (source);
  36975. result = tokenType_stringLiteral;
  36976. break;
  36977. case '+':
  36978. result = tokenType_operator;
  36979. source.skip();
  36980. if (source.peekNextChar() == '+')
  36981. source.skip();
  36982. else if (source.peekNextChar() == '=')
  36983. source.skip();
  36984. break;
  36985. case '-':
  36986. source.skip();
  36987. result = CppTokeniser::parseNumber (source);
  36988. if (result == tokenType_error)
  36989. {
  36990. result = tokenType_operator;
  36991. if (source.peekNextChar() == '-')
  36992. source.skip();
  36993. else if (source.peekNextChar() == '=')
  36994. source.skip();
  36995. }
  36996. break;
  36997. case '*':
  36998. case '%':
  36999. case '=':
  37000. case '!':
  37001. result = tokenType_operator;
  37002. source.skip();
  37003. if (source.peekNextChar() == '=')
  37004. source.skip();
  37005. break;
  37006. case '/':
  37007. result = tokenType_operator;
  37008. source.skip();
  37009. if (source.peekNextChar() == '=')
  37010. {
  37011. source.skip();
  37012. }
  37013. else if (source.peekNextChar() == '/')
  37014. {
  37015. result = tokenType_comment;
  37016. source.skipToEndOfLine();
  37017. }
  37018. else if (source.peekNextChar() == '*')
  37019. {
  37020. source.skip();
  37021. result = tokenType_comment;
  37022. CppTokeniser::skipComment (source);
  37023. }
  37024. break;
  37025. case '?':
  37026. case '~':
  37027. source.skip();
  37028. result = tokenType_operator;
  37029. break;
  37030. case '<':
  37031. source.skip();
  37032. result = tokenType_operator;
  37033. if (source.peekNextChar() == '=')
  37034. {
  37035. source.skip();
  37036. }
  37037. else if (source.peekNextChar() == '<')
  37038. {
  37039. source.skip();
  37040. if (source.peekNextChar() == '=')
  37041. source.skip();
  37042. }
  37043. break;
  37044. case '>':
  37045. source.skip();
  37046. result = tokenType_operator;
  37047. if (source.peekNextChar() == '=')
  37048. {
  37049. source.skip();
  37050. }
  37051. else if (source.peekNextChar() == '<')
  37052. {
  37053. source.skip();
  37054. if (source.peekNextChar() == '=')
  37055. source.skip();
  37056. }
  37057. break;
  37058. case '|':
  37059. source.skip();
  37060. result = tokenType_operator;
  37061. if (source.peekNextChar() == '=')
  37062. {
  37063. source.skip();
  37064. }
  37065. else if (source.peekNextChar() == '|')
  37066. {
  37067. source.skip();
  37068. if (source.peekNextChar() == '=')
  37069. source.skip();
  37070. }
  37071. break;
  37072. case '&':
  37073. source.skip();
  37074. result = tokenType_operator;
  37075. if (source.peekNextChar() == '=')
  37076. {
  37077. source.skip();
  37078. }
  37079. else if (source.peekNextChar() == '&')
  37080. {
  37081. source.skip();
  37082. if (source.peekNextChar() == '=')
  37083. source.skip();
  37084. }
  37085. break;
  37086. case '^':
  37087. source.skip();
  37088. result = tokenType_operator;
  37089. if (source.peekNextChar() == '=')
  37090. {
  37091. source.skip();
  37092. }
  37093. else if (source.peekNextChar() == '^')
  37094. {
  37095. source.skip();
  37096. if (source.peekNextChar() == '=')
  37097. source.skip();
  37098. }
  37099. break;
  37100. case '#':
  37101. result = tokenType_preprocessor;
  37102. source.skipToEndOfLine();
  37103. break;
  37104. default:
  37105. if (CppTokeniser::isIdentifierStart (firstChar))
  37106. result = CppTokeniser::parseIdentifier (source);
  37107. else
  37108. source.skip();
  37109. break;
  37110. }
  37111. //jassert (result != tokenType_unknown);
  37112. return result;
  37113. }
  37114. const StringArray CPlusPlusCodeTokeniser::getTokenTypes()
  37115. {
  37116. StringArray s;
  37117. s.add ("Error");
  37118. s.add ("Comment");
  37119. s.add ("C++ keyword");
  37120. s.add ("Identifier");
  37121. s.add ("Integer literal");
  37122. s.add ("Float literal");
  37123. s.add ("String literal");
  37124. s.add ("Operator");
  37125. s.add ("Bracket");
  37126. s.add ("Punctuation");
  37127. s.add ("Preprocessor line");
  37128. return s;
  37129. }
  37130. const Colour CPlusPlusCodeTokeniser::getDefaultColour (const int tokenType)
  37131. {
  37132. const uint32 colours[] =
  37133. {
  37134. 0xffcc0000, // error
  37135. 0xff00aa00, // comment
  37136. 0xff0000cc, // keyword
  37137. 0xff000000, // identifier
  37138. 0xff880000, // int literal
  37139. 0xff885500, // float literal
  37140. 0xff990099, // string literal
  37141. 0xff225500, // operator
  37142. 0xff000055, // bracket
  37143. 0xff004400, // punctuation
  37144. 0xff660000 // preprocessor
  37145. };
  37146. if (tokenType >= 0 && tokenType < numElementsInArray (colours))
  37147. return Colour (colours [tokenType]);
  37148. return Colours::black;
  37149. }
  37150. END_JUCE_NAMESPACE
  37151. /*** End of inlined file: juce_CPlusPlusCodeTokeniser.cpp ***/
  37152. /*** Start of inlined file: juce_ComboBox.cpp ***/
  37153. BEGIN_JUCE_NAMESPACE
  37154. ComboBox::ComboBox (const String& name)
  37155. : Component (name),
  37156. lastCurrentId (0),
  37157. isButtonDown (false),
  37158. separatorPending (false),
  37159. menuActive (false),
  37160. label (0)
  37161. {
  37162. noChoicesMessage = TRANS("(no choices)");
  37163. setRepaintsOnMouseActivity (true);
  37164. lookAndFeelChanged();
  37165. currentId.addListener (this);
  37166. }
  37167. ComboBox::~ComboBox()
  37168. {
  37169. currentId.removeListener (this);
  37170. if (menuActive)
  37171. PopupMenu::dismissAllActiveMenus();
  37172. label = 0;
  37173. deleteAllChildren();
  37174. }
  37175. void ComboBox::setEditableText (const bool isEditable)
  37176. {
  37177. label->setEditable (isEditable, isEditable, false);
  37178. setWantsKeyboardFocus (! isEditable);
  37179. resized();
  37180. }
  37181. bool ComboBox::isTextEditable() const throw()
  37182. {
  37183. return label->isEditable();
  37184. }
  37185. void ComboBox::setJustificationType (const Justification& justification) throw()
  37186. {
  37187. label->setJustificationType (justification);
  37188. }
  37189. const Justification ComboBox::getJustificationType() const throw()
  37190. {
  37191. return label->getJustificationType();
  37192. }
  37193. void ComboBox::setTooltip (const String& newTooltip)
  37194. {
  37195. SettableTooltipClient::setTooltip (newTooltip);
  37196. label->setTooltip (newTooltip);
  37197. }
  37198. void ComboBox::addItem (const String& newItemText,
  37199. const int newItemId) throw()
  37200. {
  37201. // you can't add empty strings to the list..
  37202. jassert (newItemText.isNotEmpty());
  37203. // IDs must be non-zero, as zero is used to indicate a lack of selecion.
  37204. jassert (newItemId != 0);
  37205. // you shouldn't use duplicate item IDs!
  37206. jassert (getItemForId (newItemId) == 0);
  37207. if (newItemText.isNotEmpty() && newItemId != 0)
  37208. {
  37209. if (separatorPending)
  37210. {
  37211. separatorPending = false;
  37212. ItemInfo* const item = new ItemInfo();
  37213. item->itemId = 0;
  37214. item->isEnabled = false;
  37215. item->isHeading = false;
  37216. items.add (item);
  37217. }
  37218. ItemInfo* const item = new ItemInfo();
  37219. item->name = newItemText;
  37220. item->itemId = newItemId;
  37221. item->isEnabled = true;
  37222. item->isHeading = false;
  37223. items.add (item);
  37224. }
  37225. }
  37226. void ComboBox::addSeparator() throw()
  37227. {
  37228. separatorPending = (items.size() > 0);
  37229. }
  37230. void ComboBox::addSectionHeading (const String& headingName) throw()
  37231. {
  37232. // you can't add empty strings to the list..
  37233. jassert (headingName.isNotEmpty());
  37234. if (headingName.isNotEmpty())
  37235. {
  37236. if (separatorPending)
  37237. {
  37238. separatorPending = false;
  37239. ItemInfo* const item = new ItemInfo();
  37240. item->itemId = 0;
  37241. item->isEnabled = false;
  37242. item->isHeading = false;
  37243. items.add (item);
  37244. }
  37245. ItemInfo* const item = new ItemInfo();
  37246. item->name = headingName;
  37247. item->itemId = 0;
  37248. item->isEnabled = true;
  37249. item->isHeading = true;
  37250. items.add (item);
  37251. }
  37252. }
  37253. void ComboBox::setItemEnabled (const int itemId,
  37254. const bool shouldBeEnabled) throw()
  37255. {
  37256. ItemInfo* const item = getItemForId (itemId);
  37257. if (item != 0)
  37258. item->isEnabled = shouldBeEnabled;
  37259. }
  37260. void ComboBox::changeItemText (const int itemId,
  37261. const String& newText) throw()
  37262. {
  37263. ItemInfo* const item = getItemForId (itemId);
  37264. jassert (item != 0);
  37265. if (item != 0)
  37266. item->name = newText;
  37267. }
  37268. void ComboBox::clear (const bool dontSendChangeMessage)
  37269. {
  37270. items.clear();
  37271. separatorPending = false;
  37272. if (! label->isEditable())
  37273. setSelectedItemIndex (-1, dontSendChangeMessage);
  37274. }
  37275. bool ComboBox::ItemInfo::isSeparator() const throw()
  37276. {
  37277. return name.isEmpty();
  37278. }
  37279. bool ComboBox::ItemInfo::isRealItem() const throw()
  37280. {
  37281. return ! (isHeading || name.isEmpty());
  37282. }
  37283. ComboBox::ItemInfo* ComboBox::getItemForId (const int itemId) const throw()
  37284. {
  37285. if (itemId != 0)
  37286. {
  37287. for (int i = items.size(); --i >= 0;)
  37288. if (items.getUnchecked(i)->itemId == itemId)
  37289. return items.getUnchecked(i);
  37290. }
  37291. return 0;
  37292. }
  37293. ComboBox::ItemInfo* ComboBox::getItemForIndex (const int index) const throw()
  37294. {
  37295. int n = 0;
  37296. for (int i = 0; i < items.size(); ++i)
  37297. {
  37298. ItemInfo* const item = items.getUnchecked(i);
  37299. if (item->isRealItem())
  37300. if (n++ == index)
  37301. return item;
  37302. }
  37303. return 0;
  37304. }
  37305. int ComboBox::getNumItems() const throw()
  37306. {
  37307. int n = 0;
  37308. for (int i = items.size(); --i >= 0;)
  37309. if (items.getUnchecked(i)->isRealItem())
  37310. ++n;
  37311. return n;
  37312. }
  37313. const String ComboBox::getItemText (const int index) const throw()
  37314. {
  37315. const ItemInfo* const item = getItemForIndex (index);
  37316. if (item != 0)
  37317. return item->name;
  37318. return String::empty;
  37319. }
  37320. int ComboBox::getItemId (const int index) const throw()
  37321. {
  37322. const ItemInfo* const item = getItemForIndex (index);
  37323. return (item != 0) ? item->itemId : 0;
  37324. }
  37325. int ComboBox::indexOfItemId (const int itemId) const throw()
  37326. {
  37327. int n = 0;
  37328. for (int i = 0; i < items.size(); ++i)
  37329. {
  37330. const ItemInfo* const item = items.getUnchecked(i);
  37331. if (item->isRealItem())
  37332. {
  37333. if (item->itemId == itemId)
  37334. return n;
  37335. ++n;
  37336. }
  37337. }
  37338. return -1;
  37339. }
  37340. int ComboBox::getSelectedItemIndex() const throw()
  37341. {
  37342. int index = indexOfItemId (currentId.getValue());
  37343. if (getText() != getItemText (index))
  37344. index = -1;
  37345. return index;
  37346. }
  37347. void ComboBox::setSelectedItemIndex (const int index,
  37348. const bool dontSendChangeMessage) throw()
  37349. {
  37350. setSelectedId (getItemId (index), dontSendChangeMessage);
  37351. }
  37352. int ComboBox::getSelectedId() const throw()
  37353. {
  37354. const ItemInfo* const item = getItemForId (currentId.getValue());
  37355. return (item != 0 && getText() == item->name)
  37356. ? item->itemId
  37357. : 0;
  37358. }
  37359. void ComboBox::setSelectedId (const int newItemId,
  37360. const bool dontSendChangeMessage) throw()
  37361. {
  37362. const ItemInfo* const item = getItemForId (newItemId);
  37363. const String newItemText (item != 0 ? item->name : String::empty);
  37364. if (lastCurrentId != newItemId || label->getText() != newItemText)
  37365. {
  37366. if (! dontSendChangeMessage)
  37367. triggerAsyncUpdate();
  37368. label->setText (newItemText, false);
  37369. lastCurrentId = newItemId;
  37370. currentId = newItemId;
  37371. repaint(); // for the benefit of the 'none selected' text
  37372. }
  37373. }
  37374. void ComboBox::valueChanged (Value&)
  37375. {
  37376. if (lastCurrentId != (int) currentId.getValue())
  37377. setSelectedId (currentId.getValue(), false);
  37378. }
  37379. const String ComboBox::getText() const throw()
  37380. {
  37381. return label->getText();
  37382. }
  37383. void ComboBox::setText (const String& newText,
  37384. const bool dontSendChangeMessage) throw()
  37385. {
  37386. for (int i = items.size(); --i >= 0;)
  37387. {
  37388. const ItemInfo* const item = items.getUnchecked(i);
  37389. if (item->isRealItem()
  37390. && item->name == newText)
  37391. {
  37392. setSelectedId (item->itemId, dontSendChangeMessage);
  37393. return;
  37394. }
  37395. }
  37396. lastCurrentId = 0;
  37397. currentId = 0;
  37398. if (label->getText() != newText)
  37399. {
  37400. label->setText (newText, false);
  37401. if (! dontSendChangeMessage)
  37402. triggerAsyncUpdate();
  37403. }
  37404. repaint();
  37405. }
  37406. void ComboBox::showEditor()
  37407. {
  37408. jassert (isTextEditable()); // you probably shouldn't do this to a non-editable combo box?
  37409. label->showEditor();
  37410. }
  37411. void ComboBox::setTextWhenNothingSelected (const String& newMessage) throw()
  37412. {
  37413. textWhenNothingSelected = newMessage;
  37414. repaint();
  37415. }
  37416. const String ComboBox::getTextWhenNothingSelected() const throw()
  37417. {
  37418. return textWhenNothingSelected;
  37419. }
  37420. void ComboBox::setTextWhenNoChoicesAvailable (const String& newMessage) throw()
  37421. {
  37422. noChoicesMessage = newMessage;
  37423. }
  37424. const String ComboBox::getTextWhenNoChoicesAvailable() const throw()
  37425. {
  37426. return noChoicesMessage;
  37427. }
  37428. void ComboBox::paint (Graphics& g)
  37429. {
  37430. getLookAndFeel().drawComboBox (g,
  37431. getWidth(),
  37432. getHeight(),
  37433. isButtonDown,
  37434. label->getRight(),
  37435. 0,
  37436. getWidth() - label->getRight(),
  37437. getHeight(),
  37438. *this);
  37439. if (textWhenNothingSelected.isNotEmpty()
  37440. && label->getText().isEmpty()
  37441. && ! label->isBeingEdited())
  37442. {
  37443. g.setColour (findColour (textColourId).withMultipliedAlpha (0.5f));
  37444. g.setFont (label->getFont());
  37445. g.drawFittedText (textWhenNothingSelected,
  37446. label->getX() + 2, label->getY() + 1,
  37447. label->getWidth() - 4, label->getHeight() - 2,
  37448. label->getJustificationType(),
  37449. jmax (1, (int) (label->getHeight() / label->getFont().getHeight())));
  37450. }
  37451. }
  37452. void ComboBox::resized()
  37453. {
  37454. if (getHeight() > 0 && getWidth() > 0)
  37455. getLookAndFeel().positionComboBoxText (*this, *label);
  37456. }
  37457. void ComboBox::enablementChanged()
  37458. {
  37459. repaint();
  37460. }
  37461. void ComboBox::lookAndFeelChanged()
  37462. {
  37463. repaint();
  37464. Label* const newLabel = getLookAndFeel().createComboBoxTextBox (*this);
  37465. if (label != 0)
  37466. {
  37467. newLabel->setEditable (label->isEditable());
  37468. newLabel->setJustificationType (label->getJustificationType());
  37469. newLabel->setTooltip (label->getTooltip());
  37470. newLabel->setText (label->getText(), false);
  37471. }
  37472. label = newLabel;
  37473. addAndMakeVisible (newLabel);
  37474. newLabel->addListener (this);
  37475. newLabel->addMouseListener (this, false);
  37476. newLabel->setColour (Label::backgroundColourId, Colours::transparentBlack);
  37477. newLabel->setColour (Label::textColourId, findColour (ComboBox::textColourId));
  37478. newLabel->setColour (TextEditor::textColourId, findColour (ComboBox::textColourId));
  37479. newLabel->setColour (TextEditor::backgroundColourId, Colours::transparentBlack);
  37480. newLabel->setColour (TextEditor::highlightColourId, findColour (TextEditor::highlightColourId));
  37481. newLabel->setColour (TextEditor::outlineColourId, Colours::transparentBlack);
  37482. resized();
  37483. }
  37484. void ComboBox::colourChanged()
  37485. {
  37486. lookAndFeelChanged();
  37487. }
  37488. bool ComboBox::keyPressed (const KeyPress& key)
  37489. {
  37490. bool used = false;
  37491. if (key.isKeyCode (KeyPress::upKey)
  37492. || key.isKeyCode (KeyPress::leftKey))
  37493. {
  37494. setSelectedItemIndex (jmax (0, getSelectedItemIndex() - 1));
  37495. used = true;
  37496. }
  37497. else if (key.isKeyCode (KeyPress::downKey)
  37498. || key.isKeyCode (KeyPress::rightKey))
  37499. {
  37500. setSelectedItemIndex (jmin (getSelectedItemIndex() + 1, getNumItems() - 1));
  37501. used = true;
  37502. }
  37503. else if (key.isKeyCode (KeyPress::returnKey))
  37504. {
  37505. showPopup();
  37506. used = true;
  37507. }
  37508. return used;
  37509. }
  37510. bool ComboBox::keyStateChanged (const bool isKeyDown)
  37511. {
  37512. // only forward key events that aren't used by this component
  37513. return isKeyDown
  37514. && (KeyPress::isKeyCurrentlyDown (KeyPress::upKey)
  37515. || KeyPress::isKeyCurrentlyDown (KeyPress::leftKey)
  37516. || KeyPress::isKeyCurrentlyDown (KeyPress::downKey)
  37517. || KeyPress::isKeyCurrentlyDown (KeyPress::rightKey));
  37518. }
  37519. void ComboBox::focusGained (FocusChangeType)
  37520. {
  37521. repaint();
  37522. }
  37523. void ComboBox::focusLost (FocusChangeType)
  37524. {
  37525. repaint();
  37526. }
  37527. void ComboBox::labelTextChanged (Label*)
  37528. {
  37529. triggerAsyncUpdate();
  37530. }
  37531. void ComboBox::showPopup()
  37532. {
  37533. if (! menuActive)
  37534. {
  37535. const int selectedId = getSelectedId();
  37536. Component::SafePointer<Component> deletionWatcher (this);
  37537. PopupMenu menu;
  37538. menu.setLookAndFeel (&getLookAndFeel());
  37539. for (int i = 0; i < items.size(); ++i)
  37540. {
  37541. const ItemInfo* const item = items.getUnchecked(i);
  37542. if (item->isSeparator())
  37543. menu.addSeparator();
  37544. else if (item->isHeading)
  37545. menu.addSectionHeader (item->name);
  37546. else
  37547. menu.addItem (item->itemId, item->name,
  37548. item->isEnabled, item->itemId == selectedId);
  37549. }
  37550. if (items.size() == 0)
  37551. menu.addItem (1, noChoicesMessage, false);
  37552. const int itemHeight = jlimit (12, 24, getHeight());
  37553. menuActive = true;
  37554. const int resultId = menu.showAt (this, selectedId,
  37555. getWidth(), 1, itemHeight);
  37556. if (deletionWatcher == 0)
  37557. return;
  37558. menuActive = false;
  37559. if (resultId != 0)
  37560. setSelectedId (resultId);
  37561. }
  37562. }
  37563. void ComboBox::mouseDown (const MouseEvent& e)
  37564. {
  37565. beginDragAutoRepeat (300);
  37566. isButtonDown = isEnabled();
  37567. if (isButtonDown
  37568. && (e.eventComponent == this || ! label->isEditable()))
  37569. {
  37570. showPopup();
  37571. }
  37572. }
  37573. void ComboBox::mouseDrag (const MouseEvent& e)
  37574. {
  37575. beginDragAutoRepeat (50);
  37576. if (isButtonDown && ! e.mouseWasClicked())
  37577. showPopup();
  37578. }
  37579. void ComboBox::mouseUp (const MouseEvent& e2)
  37580. {
  37581. if (isButtonDown)
  37582. {
  37583. isButtonDown = false;
  37584. repaint();
  37585. const MouseEvent e (e2.getEventRelativeTo (this));
  37586. if (reallyContains (e.x, e.y, true)
  37587. && (e2.eventComponent == this || ! label->isEditable()))
  37588. {
  37589. showPopup();
  37590. }
  37591. }
  37592. }
  37593. void ComboBox::addListener (ComboBoxListener* const listener) throw()
  37594. {
  37595. listeners.add (listener);
  37596. }
  37597. void ComboBox::removeListener (ComboBoxListener* const listener) throw()
  37598. {
  37599. listeners.remove (listener);
  37600. }
  37601. void ComboBox::handleAsyncUpdate()
  37602. {
  37603. Component::BailOutChecker checker (this);
  37604. listeners.callChecked (checker, &ComboBoxListener::comboBoxChanged, this);
  37605. }
  37606. END_JUCE_NAMESPACE
  37607. /*** End of inlined file: juce_ComboBox.cpp ***/
  37608. /*** Start of inlined file: juce_Label.cpp ***/
  37609. BEGIN_JUCE_NAMESPACE
  37610. Label::Label (const String& componentName,
  37611. const String& labelText)
  37612. : Component (componentName),
  37613. textValue (labelText),
  37614. lastTextValue (labelText),
  37615. font (15.0f),
  37616. justification (Justification::centredLeft),
  37617. ownerComponent (0),
  37618. horizontalBorderSize (5),
  37619. verticalBorderSize (1),
  37620. minimumHorizontalScale (0.7f),
  37621. editSingleClick (false),
  37622. editDoubleClick (false),
  37623. lossOfFocusDiscardsChanges (false)
  37624. {
  37625. setColour (TextEditor::textColourId, Colours::black);
  37626. setColour (TextEditor::backgroundColourId, Colours::transparentBlack);
  37627. setColour (TextEditor::outlineColourId, Colours::transparentBlack);
  37628. textValue.addListener (this);
  37629. }
  37630. Label::~Label()
  37631. {
  37632. textValue.removeListener (this);
  37633. if (ownerComponent != 0)
  37634. ownerComponent->removeComponentListener (this);
  37635. editor = 0;
  37636. }
  37637. void Label::setText (const String& newText,
  37638. const bool broadcastChangeMessage)
  37639. {
  37640. hideEditor (true);
  37641. if (lastTextValue != newText)
  37642. {
  37643. lastTextValue = newText;
  37644. textValue = newText;
  37645. repaint();
  37646. textWasChanged();
  37647. if (ownerComponent != 0)
  37648. componentMovedOrResized (*ownerComponent, true, true);
  37649. if (broadcastChangeMessage)
  37650. callChangeListeners();
  37651. }
  37652. }
  37653. const String Label::getText (const bool returnActiveEditorContents) const throw()
  37654. {
  37655. return (returnActiveEditorContents && isBeingEdited())
  37656. ? editor->getText()
  37657. : textValue.toString();
  37658. }
  37659. void Label::valueChanged (Value&)
  37660. {
  37661. if (lastTextValue != textValue.toString())
  37662. setText (textValue.toString(), true);
  37663. }
  37664. void Label::setFont (const Font& newFont) throw()
  37665. {
  37666. font = newFont;
  37667. repaint();
  37668. }
  37669. const Font& Label::getFont() const throw()
  37670. {
  37671. return font;
  37672. }
  37673. void Label::setEditable (const bool editOnSingleClick,
  37674. const bool editOnDoubleClick,
  37675. const bool lossOfFocusDiscardsChanges_) throw()
  37676. {
  37677. editSingleClick = editOnSingleClick;
  37678. editDoubleClick = editOnDoubleClick;
  37679. lossOfFocusDiscardsChanges = lossOfFocusDiscardsChanges_;
  37680. setWantsKeyboardFocus (editOnSingleClick || editOnDoubleClick);
  37681. setFocusContainer (editOnSingleClick || editOnDoubleClick);
  37682. }
  37683. void Label::setJustificationType (const Justification& justification_) throw()
  37684. {
  37685. justification = justification_;
  37686. repaint();
  37687. }
  37688. void Label::setBorderSize (int h, int v)
  37689. {
  37690. horizontalBorderSize = h;
  37691. verticalBorderSize = v;
  37692. repaint();
  37693. }
  37694. Component* Label::getAttachedComponent() const
  37695. {
  37696. return static_cast<Component*> (ownerComponent);
  37697. }
  37698. void Label::attachToComponent (Component* owner,
  37699. const bool onLeft)
  37700. {
  37701. if (ownerComponent != 0)
  37702. ownerComponent->removeComponentListener (this);
  37703. ownerComponent = owner;
  37704. leftOfOwnerComp = onLeft;
  37705. if (ownerComponent != 0)
  37706. {
  37707. setVisible (owner->isVisible());
  37708. ownerComponent->addComponentListener (this);
  37709. componentParentHierarchyChanged (*ownerComponent);
  37710. componentMovedOrResized (*ownerComponent, true, true);
  37711. }
  37712. }
  37713. void Label::componentMovedOrResized (Component& component,
  37714. bool /*wasMoved*/,
  37715. bool /*wasResized*/)
  37716. {
  37717. if (leftOfOwnerComp)
  37718. {
  37719. setSize (jmin (getFont().getStringWidth (textValue.toString()) + 8, component.getX()),
  37720. component.getHeight());
  37721. setTopRightPosition (component.getX(), component.getY());
  37722. }
  37723. else
  37724. {
  37725. setSize (component.getWidth(),
  37726. 8 + roundToInt (getFont().getHeight()));
  37727. setTopLeftPosition (component.getX(), component.getY() - getHeight());
  37728. }
  37729. }
  37730. void Label::componentParentHierarchyChanged (Component& component)
  37731. {
  37732. if (component.getParentComponent() != 0)
  37733. component.getParentComponent()->addChildComponent (this);
  37734. }
  37735. void Label::componentVisibilityChanged (Component& component)
  37736. {
  37737. setVisible (component.isVisible());
  37738. }
  37739. void Label::textWasEdited()
  37740. {
  37741. }
  37742. void Label::textWasChanged()
  37743. {
  37744. }
  37745. void Label::showEditor()
  37746. {
  37747. if (editor == 0)
  37748. {
  37749. addAndMakeVisible (editor = createEditorComponent());
  37750. editor->setText (getText(), false);
  37751. editor->addListener (this);
  37752. editor->grabKeyboardFocus();
  37753. editor->setHighlightedRegion (Range<int> (0, textValue.toString().length()));
  37754. editor->addListener (this);
  37755. resized();
  37756. repaint();
  37757. editorShown (editor);
  37758. enterModalState (false);
  37759. editor->grabKeyboardFocus();
  37760. }
  37761. }
  37762. void Label::editorShown (TextEditor* /*editorComponent*/)
  37763. {
  37764. }
  37765. void Label::editorAboutToBeHidden (TextEditor* /*editorComponent*/)
  37766. {
  37767. }
  37768. bool Label::updateFromTextEditorContents()
  37769. {
  37770. jassert (editor != 0);
  37771. const String newText (editor->getText());
  37772. if (textValue.toString() != newText)
  37773. {
  37774. lastTextValue = newText;
  37775. textValue = newText;
  37776. repaint();
  37777. textWasChanged();
  37778. if (ownerComponent != 0)
  37779. componentMovedOrResized (*ownerComponent, true, true);
  37780. return true;
  37781. }
  37782. return false;
  37783. }
  37784. void Label::hideEditor (const bool discardCurrentEditorContents)
  37785. {
  37786. if (editor != 0)
  37787. {
  37788. Component::SafePointer<Component> deletionChecker (this);
  37789. editorAboutToBeHidden (editor);
  37790. const bool changed = (! discardCurrentEditorContents)
  37791. && updateFromTextEditorContents();
  37792. editor = 0;
  37793. repaint();
  37794. if (changed)
  37795. textWasEdited();
  37796. if (deletionChecker != 0)
  37797. exitModalState (0);
  37798. if (changed && deletionChecker != 0)
  37799. callChangeListeners();
  37800. }
  37801. }
  37802. void Label::inputAttemptWhenModal()
  37803. {
  37804. if (editor != 0)
  37805. {
  37806. if (lossOfFocusDiscardsChanges)
  37807. textEditorEscapeKeyPressed (*editor);
  37808. else
  37809. textEditorReturnKeyPressed (*editor);
  37810. }
  37811. }
  37812. bool Label::isBeingEdited() const throw()
  37813. {
  37814. return editor != 0;
  37815. }
  37816. TextEditor* Label::createEditorComponent()
  37817. {
  37818. TextEditor* const ed = new TextEditor (getName());
  37819. ed->setFont (font);
  37820. // copy these colours from our own settings..
  37821. const int cols[] = { TextEditor::backgroundColourId,
  37822. TextEditor::textColourId,
  37823. TextEditor::highlightColourId,
  37824. TextEditor::highlightedTextColourId,
  37825. TextEditor::caretColourId,
  37826. TextEditor::outlineColourId,
  37827. TextEditor::focusedOutlineColourId,
  37828. TextEditor::shadowColourId };
  37829. for (int i = 0; i < numElementsInArray (cols); ++i)
  37830. ed->setColour (cols[i], findColour (cols[i]));
  37831. return ed;
  37832. }
  37833. void Label::paint (Graphics& g)
  37834. {
  37835. getLookAndFeel().drawLabel (g, *this);
  37836. }
  37837. void Label::mouseUp (const MouseEvent& e)
  37838. {
  37839. if (editSingleClick
  37840. && e.mouseWasClicked()
  37841. && contains (e.x, e.y)
  37842. && ! e.mods.isPopupMenu())
  37843. {
  37844. showEditor();
  37845. }
  37846. }
  37847. void Label::mouseDoubleClick (const MouseEvent& e)
  37848. {
  37849. if (editDoubleClick && ! e.mods.isPopupMenu())
  37850. showEditor();
  37851. }
  37852. void Label::resized()
  37853. {
  37854. if (editor != 0)
  37855. editor->setBoundsInset (BorderSize (0));
  37856. }
  37857. void Label::focusGained (FocusChangeType cause)
  37858. {
  37859. if (editSingleClick && cause == focusChangedByTabKey)
  37860. showEditor();
  37861. }
  37862. void Label::enablementChanged()
  37863. {
  37864. repaint();
  37865. }
  37866. void Label::colourChanged()
  37867. {
  37868. repaint();
  37869. }
  37870. void Label::setMinimumHorizontalScale (const float newScale)
  37871. {
  37872. if (minimumHorizontalScale != newScale)
  37873. {
  37874. minimumHorizontalScale = newScale;
  37875. repaint();
  37876. }
  37877. }
  37878. // We'll use a custom focus traverser here to make sure focus goes from the
  37879. // text editor to another component rather than back to the label itself.
  37880. class LabelKeyboardFocusTraverser : public KeyboardFocusTraverser
  37881. {
  37882. public:
  37883. LabelKeyboardFocusTraverser() {}
  37884. Component* getNextComponent (Component* current)
  37885. {
  37886. return KeyboardFocusTraverser::getNextComponent (dynamic_cast <TextEditor*> (current) != 0
  37887. ? current->getParentComponent() : current);
  37888. }
  37889. Component* getPreviousComponent (Component* current)
  37890. {
  37891. return KeyboardFocusTraverser::getPreviousComponent (dynamic_cast <TextEditor*> (current) != 0
  37892. ? current->getParentComponent() : current);
  37893. }
  37894. };
  37895. KeyboardFocusTraverser* Label::createFocusTraverser()
  37896. {
  37897. return new LabelKeyboardFocusTraverser();
  37898. }
  37899. void Label::addListener (LabelListener* const listener) throw()
  37900. {
  37901. listeners.add (listener);
  37902. }
  37903. void Label::removeListener (LabelListener* const listener) throw()
  37904. {
  37905. listeners.remove (listener);
  37906. }
  37907. void Label::callChangeListeners()
  37908. {
  37909. Component::BailOutChecker checker (this);
  37910. listeners.callChecked (checker, &LabelListener::labelTextChanged, this);
  37911. }
  37912. void Label::textEditorTextChanged (TextEditor& ed)
  37913. {
  37914. if (editor != 0)
  37915. {
  37916. jassert (&ed == editor);
  37917. if (! (hasKeyboardFocus (true) || isCurrentlyBlockedByAnotherModalComponent()))
  37918. {
  37919. if (lossOfFocusDiscardsChanges)
  37920. textEditorEscapeKeyPressed (ed);
  37921. else
  37922. textEditorReturnKeyPressed (ed);
  37923. }
  37924. }
  37925. }
  37926. void Label::textEditorReturnKeyPressed (TextEditor& ed)
  37927. {
  37928. if (editor != 0)
  37929. {
  37930. jassert (&ed == editor);
  37931. (void) ed;
  37932. const bool changed = updateFromTextEditorContents();
  37933. hideEditor (true);
  37934. if (changed)
  37935. {
  37936. Component::SafePointer<Component> deletionChecker (this);
  37937. textWasEdited();
  37938. if (deletionChecker != 0)
  37939. callChangeListeners();
  37940. }
  37941. }
  37942. }
  37943. void Label::textEditorEscapeKeyPressed (TextEditor& ed)
  37944. {
  37945. if (editor != 0)
  37946. {
  37947. jassert (&ed == editor);
  37948. (void) ed;
  37949. editor->setText (textValue.toString(), false);
  37950. hideEditor (true);
  37951. }
  37952. }
  37953. void Label::textEditorFocusLost (TextEditor& ed)
  37954. {
  37955. textEditorTextChanged (ed);
  37956. }
  37957. END_JUCE_NAMESPACE
  37958. /*** End of inlined file: juce_Label.cpp ***/
  37959. /*** Start of inlined file: juce_ListBox.cpp ***/
  37960. BEGIN_JUCE_NAMESPACE
  37961. class ListBoxRowComponent : public Component,
  37962. public TooltipClient
  37963. {
  37964. public:
  37965. ListBoxRowComponent (ListBox& owner_)
  37966. : owner (owner_),
  37967. row (-1),
  37968. selected (false),
  37969. isDragging (false)
  37970. {
  37971. }
  37972. ~ListBoxRowComponent()
  37973. {
  37974. deleteAllChildren();
  37975. }
  37976. void paint (Graphics& g)
  37977. {
  37978. if (owner.getModel() != 0)
  37979. owner.getModel()->paintListBoxItem (row, g, getWidth(), getHeight(), selected);
  37980. }
  37981. void update (const int row_, const bool selected_)
  37982. {
  37983. if (row != row_ || selected != selected_)
  37984. {
  37985. repaint();
  37986. row = row_;
  37987. selected = selected_;
  37988. }
  37989. if (owner.getModel() != 0)
  37990. {
  37991. Component* const customComp = owner.getModel()->refreshComponentForRow (row_, selected_, getChildComponent (0));
  37992. if (customComp != 0)
  37993. {
  37994. addAndMakeVisible (customComp);
  37995. customComp->setBounds (0, 0, getWidth(), getHeight());
  37996. for (int i = getNumChildComponents(); --i >= 0;)
  37997. if (getChildComponent (i) != customComp)
  37998. delete getChildComponent (i);
  37999. }
  38000. else
  38001. {
  38002. deleteAllChildren();
  38003. }
  38004. }
  38005. }
  38006. void mouseDown (const MouseEvent& e)
  38007. {
  38008. isDragging = false;
  38009. selectRowOnMouseUp = false;
  38010. if (isEnabled())
  38011. {
  38012. if (! selected)
  38013. {
  38014. owner.selectRowsBasedOnModifierKeys (row, e.mods);
  38015. if (owner.getModel() != 0)
  38016. owner.getModel()->listBoxItemClicked (row, e);
  38017. }
  38018. else
  38019. {
  38020. selectRowOnMouseUp = true;
  38021. }
  38022. }
  38023. }
  38024. void mouseUp (const MouseEvent& e)
  38025. {
  38026. if (isEnabled() && selectRowOnMouseUp && ! isDragging)
  38027. {
  38028. owner.selectRowsBasedOnModifierKeys (row, e.mods);
  38029. if (owner.getModel() != 0)
  38030. owner.getModel()->listBoxItemClicked (row, e);
  38031. }
  38032. }
  38033. void mouseDoubleClick (const MouseEvent& e)
  38034. {
  38035. if (owner.getModel() != 0 && isEnabled())
  38036. owner.getModel()->listBoxItemDoubleClicked (row, e);
  38037. }
  38038. void mouseDrag (const MouseEvent& e)
  38039. {
  38040. if (isEnabled() && owner.getModel() != 0 && ! (e.mouseWasClicked() || isDragging))
  38041. {
  38042. const SparseSet<int> selectedRows (owner.getSelectedRows());
  38043. if (selectedRows.size() > 0)
  38044. {
  38045. const String dragDescription (owner.getModel()->getDragSourceDescription (selectedRows));
  38046. if (dragDescription.isNotEmpty())
  38047. {
  38048. isDragging = true;
  38049. owner.startDragAndDrop (e, dragDescription);
  38050. }
  38051. }
  38052. }
  38053. }
  38054. void resized()
  38055. {
  38056. if (getNumChildComponents() > 0)
  38057. getChildComponent(0)->setBounds (0, 0, getWidth(), getHeight());
  38058. }
  38059. const String getTooltip()
  38060. {
  38061. if (owner.getModel() != 0)
  38062. return owner.getModel()->getTooltipForRow (row);
  38063. return String::empty;
  38064. }
  38065. juce_UseDebuggingNewOperator
  38066. bool neededFlag;
  38067. private:
  38068. ListBox& owner;
  38069. int row;
  38070. bool selected, isDragging, selectRowOnMouseUp;
  38071. ListBoxRowComponent (const ListBoxRowComponent&);
  38072. ListBoxRowComponent& operator= (const ListBoxRowComponent&);
  38073. };
  38074. class ListViewport : public Viewport
  38075. {
  38076. public:
  38077. int firstIndex, firstWholeIndex, lastWholeIndex;
  38078. bool hasUpdated;
  38079. ListViewport (ListBox& owner_)
  38080. : owner (owner_)
  38081. {
  38082. setWantsKeyboardFocus (false);
  38083. setViewedComponent (new Component());
  38084. getViewedComponent()->addMouseListener (this, false);
  38085. getViewedComponent()->setWantsKeyboardFocus (false);
  38086. }
  38087. ~ListViewport()
  38088. {
  38089. getViewedComponent()->removeMouseListener (this);
  38090. getViewedComponent()->deleteAllChildren();
  38091. }
  38092. ListBoxRowComponent* getComponentForRow (const int row) const throw()
  38093. {
  38094. return static_cast <ListBoxRowComponent*>
  38095. (getViewedComponent()->getChildComponent (row % jmax (1, getViewedComponent()->getNumChildComponents())));
  38096. }
  38097. int getRowNumberOfComponent (Component* const rowComponent) const throw()
  38098. {
  38099. const int index = getIndexOfChildComponent (rowComponent);
  38100. const int num = getViewedComponent()->getNumChildComponents();
  38101. for (int i = num; --i >= 0;)
  38102. if (((firstIndex + i) % jmax (1, num)) == index)
  38103. return firstIndex + i;
  38104. return -1;
  38105. }
  38106. Component* getComponentForRowIfOnscreen (const int row) const throw()
  38107. {
  38108. return (row >= firstIndex && row < firstIndex + getViewedComponent()->getNumChildComponents())
  38109. ? getComponentForRow (row) : 0;
  38110. }
  38111. void visibleAreaChanged (int, int, int, int)
  38112. {
  38113. updateVisibleArea (true);
  38114. if (owner.getModel() != 0)
  38115. owner.getModel()->listWasScrolled();
  38116. }
  38117. void updateVisibleArea (const bool makeSureItUpdatesContent)
  38118. {
  38119. hasUpdated = false;
  38120. const int newX = getViewedComponent()->getX();
  38121. int newY = getViewedComponent()->getY();
  38122. const int newW = jmax (owner.minimumRowWidth, getMaximumVisibleWidth());
  38123. const int newH = owner.totalItems * owner.getRowHeight();
  38124. if (newY + newH < getMaximumVisibleHeight() && newH > getMaximumVisibleHeight())
  38125. newY = getMaximumVisibleHeight() - newH;
  38126. getViewedComponent()->setBounds (newX, newY, newW, newH);
  38127. if (makeSureItUpdatesContent && ! hasUpdated)
  38128. updateContents();
  38129. }
  38130. void updateContents()
  38131. {
  38132. hasUpdated = true;
  38133. const int rowHeight = owner.getRowHeight();
  38134. if (rowHeight > 0)
  38135. {
  38136. const int y = getViewPositionY();
  38137. const int w = getViewedComponent()->getWidth();
  38138. const int numNeeded = 2 + getMaximumVisibleHeight() / rowHeight;
  38139. while (numNeeded > getViewedComponent()->getNumChildComponents())
  38140. getViewedComponent()->addAndMakeVisible (new ListBoxRowComponent (owner));
  38141. jassert (numNeeded >= 0);
  38142. while (numNeeded < getViewedComponent()->getNumChildComponents())
  38143. {
  38144. Component* const rowToRemove
  38145. = getViewedComponent()->getChildComponent (getViewedComponent()->getNumChildComponents() - 1);
  38146. delete rowToRemove;
  38147. }
  38148. firstIndex = y / rowHeight;
  38149. firstWholeIndex = (y + rowHeight - 1) / rowHeight;
  38150. lastWholeIndex = (y + getMaximumVisibleHeight() - 1) / rowHeight;
  38151. for (int i = 0; i < numNeeded; ++i)
  38152. {
  38153. const int row = i + firstIndex;
  38154. ListBoxRowComponent* const rowComp = getComponentForRow (row);
  38155. if (rowComp != 0)
  38156. {
  38157. rowComp->setBounds (0, row * rowHeight, w, rowHeight);
  38158. rowComp->update (row, owner.isRowSelected (row));
  38159. }
  38160. }
  38161. }
  38162. if (owner.headerComponent != 0)
  38163. owner.headerComponent->setBounds (owner.outlineThickness + getViewedComponent()->getX(),
  38164. owner.outlineThickness,
  38165. jmax (owner.getWidth() - owner.outlineThickness * 2,
  38166. getViewedComponent()->getWidth()),
  38167. owner.headerComponent->getHeight());
  38168. }
  38169. void paint (Graphics& g)
  38170. {
  38171. if (isOpaque())
  38172. g.fillAll (owner.findColour (ListBox::backgroundColourId));
  38173. }
  38174. bool keyPressed (const KeyPress& key)
  38175. {
  38176. if (key.isKeyCode (KeyPress::upKey)
  38177. || key.isKeyCode (KeyPress::downKey)
  38178. || key.isKeyCode (KeyPress::pageUpKey)
  38179. || key.isKeyCode (KeyPress::pageDownKey)
  38180. || key.isKeyCode (KeyPress::homeKey)
  38181. || key.isKeyCode (KeyPress::endKey))
  38182. {
  38183. // we want to avoid these keypresses going to the viewport, and instead allow
  38184. // them to pass up to our listbox..
  38185. return false;
  38186. }
  38187. return Viewport::keyPressed (key);
  38188. }
  38189. juce_UseDebuggingNewOperator
  38190. private:
  38191. ListBox& owner;
  38192. ListViewport (const ListViewport&);
  38193. ListViewport& operator= (const ListViewport&);
  38194. };
  38195. ListBox::ListBox (const String& name, ListBoxModel* const model_)
  38196. : Component (name),
  38197. model (model_),
  38198. headerComponent (0),
  38199. totalItems (0),
  38200. rowHeight (22),
  38201. minimumRowWidth (0),
  38202. outlineThickness (0),
  38203. lastRowSelected (-1),
  38204. mouseMoveSelects (false),
  38205. multipleSelection (false),
  38206. hasDoneInitialUpdate (false)
  38207. {
  38208. addAndMakeVisible (viewport = new ListViewport (*this));
  38209. setWantsKeyboardFocus (true);
  38210. colourChanged();
  38211. }
  38212. ListBox::~ListBox()
  38213. {
  38214. deleteAllChildren();
  38215. }
  38216. void ListBox::setModel (ListBoxModel* const newModel)
  38217. {
  38218. if (model != newModel)
  38219. {
  38220. model = newModel;
  38221. updateContent();
  38222. }
  38223. }
  38224. void ListBox::setMultipleSelectionEnabled (bool b)
  38225. {
  38226. multipleSelection = b;
  38227. }
  38228. void ListBox::setMouseMoveSelectsRows (bool b)
  38229. {
  38230. mouseMoveSelects = b;
  38231. if (b)
  38232. addMouseListener (this, true);
  38233. }
  38234. void ListBox::paint (Graphics& g)
  38235. {
  38236. if (! hasDoneInitialUpdate)
  38237. updateContent();
  38238. g.fillAll (findColour (backgroundColourId));
  38239. }
  38240. void ListBox::paintOverChildren (Graphics& g)
  38241. {
  38242. if (outlineThickness > 0)
  38243. {
  38244. g.setColour (findColour (outlineColourId));
  38245. g.drawRect (0, 0, getWidth(), getHeight(), outlineThickness);
  38246. }
  38247. }
  38248. void ListBox::resized()
  38249. {
  38250. viewport->setBoundsInset (BorderSize (outlineThickness + ((headerComponent != 0) ? headerComponent->getHeight() : 0),
  38251. outlineThickness,
  38252. outlineThickness,
  38253. outlineThickness));
  38254. viewport->setSingleStepSizes (20, getRowHeight());
  38255. viewport->updateVisibleArea (false);
  38256. }
  38257. void ListBox::visibilityChanged()
  38258. {
  38259. viewport->updateVisibleArea (true);
  38260. }
  38261. Viewport* ListBox::getViewport() const throw()
  38262. {
  38263. return viewport;
  38264. }
  38265. void ListBox::updateContent()
  38266. {
  38267. hasDoneInitialUpdate = true;
  38268. totalItems = (model != 0) ? model->getNumRows() : 0;
  38269. bool selectionChanged = false;
  38270. if (selected [selected.size() - 1] >= totalItems)
  38271. {
  38272. selected.removeRange (Range <int> (totalItems, std::numeric_limits<int>::max()));
  38273. lastRowSelected = getSelectedRow (0);
  38274. selectionChanged = true;
  38275. }
  38276. viewport->updateVisibleArea (isVisible());
  38277. viewport->resized();
  38278. if (selectionChanged && model != 0)
  38279. model->selectedRowsChanged (lastRowSelected);
  38280. }
  38281. void ListBox::selectRow (const int row,
  38282. bool dontScroll,
  38283. bool deselectOthersFirst)
  38284. {
  38285. selectRowInternal (row, dontScroll, deselectOthersFirst, false);
  38286. }
  38287. void ListBox::selectRowInternal (const int row,
  38288. bool dontScroll,
  38289. bool deselectOthersFirst,
  38290. bool isMouseClick)
  38291. {
  38292. if (! multipleSelection)
  38293. deselectOthersFirst = true;
  38294. if ((! isRowSelected (row))
  38295. || (deselectOthersFirst && getNumSelectedRows() > 1))
  38296. {
  38297. if (((unsigned int) row) < (unsigned int) totalItems)
  38298. {
  38299. if (deselectOthersFirst)
  38300. selected.clear();
  38301. selected.addRange (Range<int> (row, row + 1));
  38302. if (getHeight() == 0 || getWidth() == 0)
  38303. dontScroll = true;
  38304. viewport->hasUpdated = false;
  38305. if (row < viewport->firstWholeIndex && ! dontScroll)
  38306. {
  38307. viewport->setViewPosition (viewport->getViewPositionX(),
  38308. row * getRowHeight());
  38309. }
  38310. else if (row >= viewport->lastWholeIndex && ! dontScroll)
  38311. {
  38312. const int rowsOnScreen = viewport->lastWholeIndex - viewport->firstWholeIndex;
  38313. if (row >= lastRowSelected + rowsOnScreen
  38314. && rowsOnScreen < totalItems - 1
  38315. && ! isMouseClick)
  38316. {
  38317. viewport->setViewPosition (viewport->getViewPositionX(),
  38318. jlimit (0, jmax (0, totalItems - rowsOnScreen), row)
  38319. * getRowHeight());
  38320. }
  38321. else
  38322. {
  38323. viewport->setViewPosition (viewport->getViewPositionX(),
  38324. jmax (0, (row + 1) * getRowHeight() - viewport->getMaximumVisibleHeight()));
  38325. }
  38326. }
  38327. if (! viewport->hasUpdated)
  38328. viewport->updateContents();
  38329. lastRowSelected = row;
  38330. model->selectedRowsChanged (row);
  38331. }
  38332. else
  38333. {
  38334. if (deselectOthersFirst)
  38335. deselectAllRows();
  38336. }
  38337. }
  38338. }
  38339. void ListBox::deselectRow (const int row)
  38340. {
  38341. if (selected.contains (row))
  38342. {
  38343. selected.removeRange (Range <int> (row, row + 1));
  38344. if (row == lastRowSelected)
  38345. lastRowSelected = getSelectedRow (0);
  38346. viewport->updateContents();
  38347. model->selectedRowsChanged (lastRowSelected);
  38348. }
  38349. }
  38350. void ListBox::setSelectedRows (const SparseSet<int>& setOfRowsToBeSelected,
  38351. const bool sendNotificationEventToModel)
  38352. {
  38353. selected = setOfRowsToBeSelected;
  38354. selected.removeRange (Range <int> (totalItems, std::numeric_limits<int>::max()));
  38355. if (! isRowSelected (lastRowSelected))
  38356. lastRowSelected = getSelectedRow (0);
  38357. viewport->updateContents();
  38358. if ((model != 0) && sendNotificationEventToModel)
  38359. model->selectedRowsChanged (lastRowSelected);
  38360. }
  38361. const SparseSet<int> ListBox::getSelectedRows() const
  38362. {
  38363. return selected;
  38364. }
  38365. void ListBox::selectRangeOfRows (int firstRow, int lastRow)
  38366. {
  38367. if (multipleSelection && (firstRow != lastRow))
  38368. {
  38369. const int numRows = totalItems - 1;
  38370. firstRow = jlimit (0, jmax (0, numRows), firstRow);
  38371. lastRow = jlimit (0, jmax (0, numRows), lastRow);
  38372. selected.addRange (Range <int> (jmin (firstRow, lastRow),
  38373. jmax (firstRow, lastRow) + 1));
  38374. selected.removeRange (Range <int> (lastRow, lastRow + 1));
  38375. }
  38376. selectRowInternal (lastRow, false, false, true);
  38377. }
  38378. void ListBox::flipRowSelection (const int row)
  38379. {
  38380. if (isRowSelected (row))
  38381. deselectRow (row);
  38382. else
  38383. selectRowInternal (row, false, false, true);
  38384. }
  38385. void ListBox::deselectAllRows()
  38386. {
  38387. if (! selected.isEmpty())
  38388. {
  38389. selected.clear();
  38390. lastRowSelected = -1;
  38391. viewport->updateContents();
  38392. if (model != 0)
  38393. model->selectedRowsChanged (lastRowSelected);
  38394. }
  38395. }
  38396. void ListBox::selectRowsBasedOnModifierKeys (const int row,
  38397. const ModifierKeys& mods)
  38398. {
  38399. if (multipleSelection && mods.isCommandDown())
  38400. {
  38401. flipRowSelection (row);
  38402. }
  38403. else if (multipleSelection && mods.isShiftDown() && lastRowSelected >= 0)
  38404. {
  38405. selectRangeOfRows (lastRowSelected, row);
  38406. }
  38407. else if ((! mods.isPopupMenu()) || ! isRowSelected (row))
  38408. {
  38409. selectRowInternal (row, false, true, true);
  38410. }
  38411. }
  38412. int ListBox::getNumSelectedRows() const
  38413. {
  38414. return selected.size();
  38415. }
  38416. int ListBox::getSelectedRow (const int index) const
  38417. {
  38418. return (((unsigned int) index) < (unsigned int) selected.size())
  38419. ? selected [index] : -1;
  38420. }
  38421. bool ListBox::isRowSelected (const int row) const
  38422. {
  38423. return selected.contains (row);
  38424. }
  38425. int ListBox::getLastRowSelected() const
  38426. {
  38427. return (isRowSelected (lastRowSelected)) ? lastRowSelected : -1;
  38428. }
  38429. int ListBox::getRowContainingPosition (const int x, const int y) const throw()
  38430. {
  38431. if (((unsigned int) x) < (unsigned int) getWidth())
  38432. {
  38433. const int row = (viewport->getViewPositionY() + y - viewport->getY()) / rowHeight;
  38434. if (((unsigned int) row) < (unsigned int) totalItems)
  38435. return row;
  38436. }
  38437. return -1;
  38438. }
  38439. int ListBox::getInsertionIndexForPosition (const int x, const int y) const throw()
  38440. {
  38441. if (((unsigned int) x) < (unsigned int) getWidth())
  38442. {
  38443. const int row = (viewport->getViewPositionY() + y + rowHeight / 2 - viewport->getY()) / rowHeight;
  38444. return jlimit (0, totalItems, row);
  38445. }
  38446. return -1;
  38447. }
  38448. Component* ListBox::getComponentForRowNumber (const int row) const throw()
  38449. {
  38450. Component* const listRowComp = viewport->getComponentForRowIfOnscreen (row);
  38451. return listRowComp != 0 ? listRowComp->getChildComponent (0) : 0;
  38452. }
  38453. int ListBox::getRowNumberOfComponent (Component* const rowComponent) const throw()
  38454. {
  38455. return viewport->getRowNumberOfComponent (rowComponent);
  38456. }
  38457. const Rectangle<int> ListBox::getRowPosition (const int rowNumber,
  38458. const bool relativeToComponentTopLeft) const throw()
  38459. {
  38460. const int rowHeight = getRowHeight();
  38461. int y = viewport->getY() + rowHeight * rowNumber;
  38462. if (relativeToComponentTopLeft)
  38463. y -= viewport->getViewPositionY();
  38464. return Rectangle<int> (viewport->getX(), y,
  38465. viewport->getViewedComponent()->getWidth(), rowHeight);
  38466. }
  38467. void ListBox::setVerticalPosition (const double proportion)
  38468. {
  38469. const int offscreen = viewport->getViewedComponent()->getHeight() - viewport->getHeight();
  38470. viewport->setViewPosition (viewport->getViewPositionX(),
  38471. jmax (0, roundToInt (proportion * offscreen)));
  38472. }
  38473. double ListBox::getVerticalPosition() const
  38474. {
  38475. const int offscreen = viewport->getViewedComponent()->getHeight() - viewport->getHeight();
  38476. return (offscreen > 0) ? viewport->getViewPositionY() / (double) offscreen
  38477. : 0;
  38478. }
  38479. int ListBox::getVisibleRowWidth() const throw()
  38480. {
  38481. return viewport->getViewWidth();
  38482. }
  38483. void ListBox::scrollToEnsureRowIsOnscreen (const int row)
  38484. {
  38485. if (row < viewport->firstWholeIndex)
  38486. {
  38487. viewport->setViewPosition (viewport->getViewPositionX(),
  38488. row * getRowHeight());
  38489. }
  38490. else if (row >= viewport->lastWholeIndex)
  38491. {
  38492. viewport->setViewPosition (viewport->getViewPositionX(),
  38493. jmax (0, (row + 1) * getRowHeight() - viewport->getMaximumVisibleHeight()));
  38494. }
  38495. }
  38496. bool ListBox::keyPressed (const KeyPress& key)
  38497. {
  38498. const int numVisibleRows = viewport->getHeight() / getRowHeight();
  38499. const bool multiple = multipleSelection
  38500. && (lastRowSelected >= 0)
  38501. && (key.getModifiers().isShiftDown()
  38502. || key.getModifiers().isCtrlDown()
  38503. || key.getModifiers().isCommandDown());
  38504. if (key.isKeyCode (KeyPress::upKey))
  38505. {
  38506. if (multiple)
  38507. selectRangeOfRows (lastRowSelected, lastRowSelected - 1);
  38508. else
  38509. selectRow (jmax (0, lastRowSelected - 1));
  38510. }
  38511. else if (key.isKeyCode (KeyPress::returnKey)
  38512. && isRowSelected (lastRowSelected))
  38513. {
  38514. if (model != 0)
  38515. model->returnKeyPressed (lastRowSelected);
  38516. }
  38517. else if (key.isKeyCode (KeyPress::pageUpKey))
  38518. {
  38519. if (multiple)
  38520. selectRangeOfRows (lastRowSelected, lastRowSelected - numVisibleRows);
  38521. else
  38522. selectRow (jmax (0, jmax (0, lastRowSelected) - numVisibleRows));
  38523. }
  38524. else if (key.isKeyCode (KeyPress::pageDownKey))
  38525. {
  38526. if (multiple)
  38527. selectRangeOfRows (lastRowSelected, lastRowSelected + numVisibleRows);
  38528. else
  38529. selectRow (jmin (totalItems - 1, jmax (0, lastRowSelected) + numVisibleRows));
  38530. }
  38531. else if (key.isKeyCode (KeyPress::homeKey))
  38532. {
  38533. if (multiple && key.getModifiers().isShiftDown())
  38534. selectRangeOfRows (lastRowSelected, 0);
  38535. else
  38536. selectRow (0);
  38537. }
  38538. else if (key.isKeyCode (KeyPress::endKey))
  38539. {
  38540. if (multiple && key.getModifiers().isShiftDown())
  38541. selectRangeOfRows (lastRowSelected, totalItems - 1);
  38542. else
  38543. selectRow (totalItems - 1);
  38544. }
  38545. else if (key.isKeyCode (KeyPress::downKey))
  38546. {
  38547. if (multiple)
  38548. selectRangeOfRows (lastRowSelected, lastRowSelected + 1);
  38549. else
  38550. selectRow (jmin (totalItems - 1, jmax (0, lastRowSelected) + 1));
  38551. }
  38552. else if ((key.isKeyCode (KeyPress::deleteKey) || key.isKeyCode (KeyPress::backspaceKey))
  38553. && isRowSelected (lastRowSelected))
  38554. {
  38555. if (model != 0)
  38556. model->deleteKeyPressed (lastRowSelected);
  38557. }
  38558. else if (multiple && key == KeyPress ('a', ModifierKeys::commandModifier, 0))
  38559. {
  38560. selectRangeOfRows (0, std::numeric_limits<int>::max());
  38561. }
  38562. else
  38563. {
  38564. return false;
  38565. }
  38566. return true;
  38567. }
  38568. bool ListBox::keyStateChanged (const bool isKeyDown)
  38569. {
  38570. return isKeyDown
  38571. && (KeyPress::isKeyCurrentlyDown (KeyPress::upKey)
  38572. || KeyPress::isKeyCurrentlyDown (KeyPress::pageUpKey)
  38573. || KeyPress::isKeyCurrentlyDown (KeyPress::downKey)
  38574. || KeyPress::isKeyCurrentlyDown (KeyPress::pageDownKey)
  38575. || KeyPress::isKeyCurrentlyDown (KeyPress::homeKey)
  38576. || KeyPress::isKeyCurrentlyDown (KeyPress::endKey)
  38577. || KeyPress::isKeyCurrentlyDown (KeyPress::returnKey));
  38578. }
  38579. void ListBox::mouseWheelMove (const MouseEvent& e, float wheelIncrementX, float wheelIncrementY)
  38580. {
  38581. getHorizontalScrollBar()->mouseWheelMove (e, wheelIncrementX, 0);
  38582. getVerticalScrollBar()->mouseWheelMove (e, 0, wheelIncrementY);
  38583. }
  38584. void ListBox::mouseMove (const MouseEvent& e)
  38585. {
  38586. if (mouseMoveSelects)
  38587. {
  38588. const MouseEvent e2 (e.getEventRelativeTo (this));
  38589. selectRow (getRowContainingPosition (e2.x, e2.y), true);
  38590. }
  38591. }
  38592. void ListBox::mouseExit (const MouseEvent& e)
  38593. {
  38594. mouseMove (e);
  38595. }
  38596. void ListBox::mouseUp (const MouseEvent& e)
  38597. {
  38598. if (e.mouseWasClicked() && model != 0)
  38599. model->backgroundClicked();
  38600. }
  38601. void ListBox::setRowHeight (const int newHeight)
  38602. {
  38603. rowHeight = jmax (1, newHeight);
  38604. viewport->setSingleStepSizes (20, rowHeight);
  38605. updateContent();
  38606. }
  38607. int ListBox::getNumRowsOnScreen() const throw()
  38608. {
  38609. return viewport->getMaximumVisibleHeight() / rowHeight;
  38610. }
  38611. void ListBox::setMinimumContentWidth (const int newMinimumWidth)
  38612. {
  38613. minimumRowWidth = newMinimumWidth;
  38614. updateContent();
  38615. }
  38616. int ListBox::getVisibleContentWidth() const throw()
  38617. {
  38618. return viewport->getMaximumVisibleWidth();
  38619. }
  38620. ScrollBar* ListBox::getVerticalScrollBar() const throw()
  38621. {
  38622. return viewport->getVerticalScrollBar();
  38623. }
  38624. ScrollBar* ListBox::getHorizontalScrollBar() const throw()
  38625. {
  38626. return viewport->getHorizontalScrollBar();
  38627. }
  38628. void ListBox::colourChanged()
  38629. {
  38630. setOpaque (findColour (backgroundColourId).isOpaque());
  38631. viewport->setOpaque (isOpaque());
  38632. repaint();
  38633. }
  38634. void ListBox::setOutlineThickness (const int outlineThickness_)
  38635. {
  38636. outlineThickness = outlineThickness_;
  38637. resized();
  38638. }
  38639. void ListBox::setHeaderComponent (Component* const newHeaderComponent)
  38640. {
  38641. if (headerComponent != newHeaderComponent)
  38642. {
  38643. delete headerComponent;
  38644. headerComponent = newHeaderComponent;
  38645. addAndMakeVisible (newHeaderComponent);
  38646. ListBox::resized();
  38647. }
  38648. }
  38649. void ListBox::repaintRow (const int rowNumber) throw()
  38650. {
  38651. const Rectangle<int> r (getRowPosition (rowNumber, true));
  38652. repaint (r.getX(), r.getY(), r.getWidth(), r.getHeight());
  38653. }
  38654. Image* ListBox::createSnapshotOfSelectedRows (int& imageX, int& imageY)
  38655. {
  38656. Rectangle<int> imageArea;
  38657. const int firstRow = getRowContainingPosition (0, 0);
  38658. int i;
  38659. for (i = getNumRowsOnScreen() + 2; --i >= 0;)
  38660. {
  38661. Component* rowComp = viewport->getComponentForRowIfOnscreen (firstRow + i);
  38662. if (rowComp != 0 && isRowSelected (firstRow + i))
  38663. {
  38664. const Point<int> pos (rowComp->relativePositionToOtherComponent (this, Point<int>()));
  38665. const Rectangle<int> rowRect (pos.getX(), pos.getY(), rowComp->getWidth(), rowComp->getHeight());
  38666. if (imageArea.isEmpty())
  38667. imageArea = rowRect;
  38668. else
  38669. imageArea = imageArea.getUnion (rowRect);
  38670. }
  38671. }
  38672. imageArea = imageArea.getIntersection (getLocalBounds());
  38673. imageX = imageArea.getX();
  38674. imageY = imageArea.getY();
  38675. Image* snapshot = Image::createNativeImage (Image::ARGB, imageArea.getWidth(), imageArea.getHeight(), true);
  38676. for (i = getNumRowsOnScreen() + 2; --i >= 0;)
  38677. {
  38678. Component* rowComp = viewport->getComponentForRowIfOnscreen (firstRow + i);
  38679. if (rowComp != 0 && isRowSelected (firstRow + i))
  38680. {
  38681. const Point<int> pos (rowComp->relativePositionToOtherComponent (this, Point<int>()));
  38682. Graphics g (*snapshot);
  38683. g.setOrigin (pos.getX() - imageX, pos.getY() - imageY);
  38684. if (g.reduceClipRegion (0, 0, rowComp->getWidth(), rowComp->getHeight()))
  38685. rowComp->paintEntireComponent (g);
  38686. }
  38687. }
  38688. return snapshot;
  38689. }
  38690. void ListBox::startDragAndDrop (const MouseEvent& e, const String& dragDescription)
  38691. {
  38692. DragAndDropContainer* const dragContainer
  38693. = DragAndDropContainer::findParentDragContainerFor (this);
  38694. if (dragContainer != 0)
  38695. {
  38696. int x, y;
  38697. Image* dragImage = createSnapshotOfSelectedRows (x, y);
  38698. dragImage->multiplyAllAlphas (0.6f);
  38699. MouseEvent e2 (e.getEventRelativeTo (this));
  38700. const Point<int> p (x - e2.x, y - e2.y);
  38701. dragContainer->startDragging (dragDescription, this, dragImage, true, &p);
  38702. }
  38703. else
  38704. {
  38705. // to be able to do a drag-and-drop operation, the listbox needs to
  38706. // be inside a component which is also a DragAndDropContainer.
  38707. jassertfalse
  38708. }
  38709. }
  38710. Component* ListBoxModel::refreshComponentForRow (int, bool, Component* existingComponentToUpdate)
  38711. {
  38712. (void) existingComponentToUpdate;
  38713. jassert (existingComponentToUpdate == 0); // indicates a failure in the code the recycles the components
  38714. return 0;
  38715. }
  38716. void ListBoxModel::listBoxItemClicked (int, const MouseEvent&)
  38717. {
  38718. }
  38719. void ListBoxModel::listBoxItemDoubleClicked (int, const MouseEvent&)
  38720. {
  38721. }
  38722. void ListBoxModel::backgroundClicked()
  38723. {
  38724. }
  38725. void ListBoxModel::selectedRowsChanged (int)
  38726. {
  38727. }
  38728. void ListBoxModel::deleteKeyPressed (int)
  38729. {
  38730. }
  38731. void ListBoxModel::returnKeyPressed (int)
  38732. {
  38733. }
  38734. void ListBoxModel::listWasScrolled()
  38735. {
  38736. }
  38737. const String ListBoxModel::getDragSourceDescription (const SparseSet<int>&)
  38738. {
  38739. return String::empty;
  38740. }
  38741. const String ListBoxModel::getTooltipForRow (int)
  38742. {
  38743. return String::empty;
  38744. }
  38745. END_JUCE_NAMESPACE
  38746. /*** End of inlined file: juce_ListBox.cpp ***/
  38747. /*** Start of inlined file: juce_ProgressBar.cpp ***/
  38748. BEGIN_JUCE_NAMESPACE
  38749. ProgressBar::ProgressBar (double& progress_)
  38750. : progress (progress_),
  38751. displayPercentage (true),
  38752. lastCallbackTime (0)
  38753. {
  38754. currentValue = jlimit (0.0, 1.0, progress);
  38755. }
  38756. ProgressBar::~ProgressBar()
  38757. {
  38758. }
  38759. void ProgressBar::setPercentageDisplay (const bool shouldDisplayPercentage)
  38760. {
  38761. displayPercentage = shouldDisplayPercentage;
  38762. repaint();
  38763. }
  38764. void ProgressBar::setTextToDisplay (const String& text)
  38765. {
  38766. displayPercentage = false;
  38767. displayedMessage = text;
  38768. }
  38769. void ProgressBar::lookAndFeelChanged()
  38770. {
  38771. setOpaque (findColour (backgroundColourId).isOpaque());
  38772. }
  38773. void ProgressBar::colourChanged()
  38774. {
  38775. lookAndFeelChanged();
  38776. }
  38777. void ProgressBar::paint (Graphics& g)
  38778. {
  38779. String text;
  38780. if (displayPercentage)
  38781. {
  38782. if (currentValue >= 0 && currentValue <= 1.0)
  38783. text << roundToInt (currentValue * 100.0) << '%';
  38784. }
  38785. else
  38786. {
  38787. text = displayedMessage;
  38788. }
  38789. getLookAndFeel().drawProgressBar (g, *this,
  38790. getWidth(), getHeight(),
  38791. currentValue, text);
  38792. }
  38793. void ProgressBar::visibilityChanged()
  38794. {
  38795. if (isVisible())
  38796. startTimer (30);
  38797. else
  38798. stopTimer();
  38799. }
  38800. void ProgressBar::timerCallback()
  38801. {
  38802. double newProgress = progress;
  38803. const uint32 now = Time::getMillisecondCounter();
  38804. const int timeSinceLastCallback = (int) (now - lastCallbackTime);
  38805. lastCallbackTime = now;
  38806. if (currentValue != newProgress
  38807. || newProgress < 0 || newProgress >= 1.0
  38808. || currentMessage != displayedMessage)
  38809. {
  38810. if (currentValue < newProgress
  38811. && newProgress >= 0 && newProgress < 1.0
  38812. && currentValue >= 0 && currentValue < 1.0)
  38813. {
  38814. newProgress = jmin (currentValue + 0.0008 * timeSinceLastCallback,
  38815. newProgress);
  38816. }
  38817. currentValue = newProgress;
  38818. currentMessage = displayedMessage;
  38819. repaint();
  38820. }
  38821. }
  38822. END_JUCE_NAMESPACE
  38823. /*** End of inlined file: juce_ProgressBar.cpp ***/
  38824. /*** Start of inlined file: juce_Slider.cpp ***/
  38825. BEGIN_JUCE_NAMESPACE
  38826. class SliderPopupDisplayComponent : public BubbleComponent
  38827. {
  38828. public:
  38829. SliderPopupDisplayComponent (Slider* const owner_)
  38830. : owner (owner_),
  38831. font (15.0f, Font::bold)
  38832. {
  38833. setAlwaysOnTop (true);
  38834. }
  38835. ~SliderPopupDisplayComponent()
  38836. {
  38837. }
  38838. void paintContent (Graphics& g, int w, int h)
  38839. {
  38840. g.setFont (font);
  38841. g.setColour (Colours::black);
  38842. g.drawFittedText (text, 0, 0, w, h, Justification::centred, 1);
  38843. }
  38844. void getContentSize (int& w, int& h)
  38845. {
  38846. w = font.getStringWidth (text) + 18;
  38847. h = (int) (font.getHeight() * 1.6f);
  38848. }
  38849. void updatePosition (const String& newText)
  38850. {
  38851. if (text != newText)
  38852. {
  38853. text = newText;
  38854. repaint();
  38855. }
  38856. BubbleComponent::setPosition (owner);
  38857. }
  38858. juce_UseDebuggingNewOperator
  38859. private:
  38860. Slider* owner;
  38861. Font font;
  38862. String text;
  38863. SliderPopupDisplayComponent (const SliderPopupDisplayComponent&);
  38864. SliderPopupDisplayComponent& operator= (const SliderPopupDisplayComponent&);
  38865. };
  38866. Slider::Slider (const String& name)
  38867. : Component (name),
  38868. lastCurrentValue (0),
  38869. lastValueMin (0),
  38870. lastValueMax (0),
  38871. minimum (0),
  38872. maximum (10),
  38873. interval (0),
  38874. skewFactor (1.0),
  38875. velocityModeSensitivity (1.0),
  38876. velocityModeOffset (0.0),
  38877. velocityModeThreshold (1),
  38878. rotaryStart (float_Pi * 1.2f),
  38879. rotaryEnd (float_Pi * 2.8f),
  38880. numDecimalPlaces (7),
  38881. sliderRegionStart (0),
  38882. sliderRegionSize (1),
  38883. sliderBeingDragged (-1),
  38884. pixelsForFullDragExtent (250),
  38885. style (LinearHorizontal),
  38886. textBoxPos (TextBoxLeft),
  38887. textBoxWidth (80),
  38888. textBoxHeight (20),
  38889. incDecButtonMode (incDecButtonsNotDraggable),
  38890. editableText (true),
  38891. doubleClickToValue (false),
  38892. isVelocityBased (false),
  38893. userKeyOverridesVelocity (true),
  38894. rotaryStop (true),
  38895. incDecButtonsSideBySide (false),
  38896. sendChangeOnlyOnRelease (false),
  38897. popupDisplayEnabled (false),
  38898. menuEnabled (false),
  38899. menuShown (false),
  38900. scrollWheelEnabled (true),
  38901. snapsToMousePos (true),
  38902. valueBox (0),
  38903. incButton (0),
  38904. decButton (0),
  38905. popupDisplay (0),
  38906. parentForPopupDisplay (0)
  38907. {
  38908. setWantsKeyboardFocus (false);
  38909. setRepaintsOnMouseActivity (true);
  38910. lookAndFeelChanged();
  38911. updateText();
  38912. currentValue.addListener (this);
  38913. valueMin.addListener (this);
  38914. valueMax.addListener (this);
  38915. }
  38916. Slider::~Slider()
  38917. {
  38918. currentValue.removeListener (this);
  38919. valueMin.removeListener (this);
  38920. valueMax.removeListener (this);
  38921. popupDisplay = 0;
  38922. deleteAllChildren();
  38923. }
  38924. void Slider::handleAsyncUpdate()
  38925. {
  38926. cancelPendingUpdate();
  38927. Component::BailOutChecker checker (this);
  38928. listeners.callChecked (checker, &SliderListener::sliderValueChanged, this);
  38929. }
  38930. void Slider::sendDragStart()
  38931. {
  38932. startedDragging();
  38933. Component::BailOutChecker checker (this);
  38934. listeners.callChecked (checker, &SliderListener::sliderDragStarted, this);
  38935. }
  38936. void Slider::sendDragEnd()
  38937. {
  38938. stoppedDragging();
  38939. sliderBeingDragged = -1;
  38940. Component::BailOutChecker checker (this);
  38941. listeners.callChecked (checker, &SliderListener::sliderDragEnded, this);
  38942. }
  38943. void Slider::addListener (SliderListener* const listener)
  38944. {
  38945. listeners.add (listener);
  38946. }
  38947. void Slider::removeListener (SliderListener* const listener)
  38948. {
  38949. listeners.remove (listener);
  38950. }
  38951. void Slider::setSliderStyle (const SliderStyle newStyle)
  38952. {
  38953. if (style != newStyle)
  38954. {
  38955. style = newStyle;
  38956. repaint();
  38957. lookAndFeelChanged();
  38958. }
  38959. }
  38960. void Slider::setRotaryParameters (const float startAngleRadians,
  38961. const float endAngleRadians,
  38962. const bool stopAtEnd)
  38963. {
  38964. // make sure the values are sensible..
  38965. jassert (rotaryStart >= 0 && rotaryEnd >= 0);
  38966. jassert (rotaryStart < float_Pi * 4.0f && rotaryEnd < float_Pi * 4.0f);
  38967. jassert (rotaryStart < rotaryEnd);
  38968. rotaryStart = startAngleRadians;
  38969. rotaryEnd = endAngleRadians;
  38970. rotaryStop = stopAtEnd;
  38971. }
  38972. void Slider::setVelocityBasedMode (const bool velBased)
  38973. {
  38974. isVelocityBased = velBased;
  38975. }
  38976. void Slider::setVelocityModeParameters (const double sensitivity,
  38977. const int threshold,
  38978. const double offset,
  38979. const bool userCanPressKeyToSwapMode)
  38980. {
  38981. jassert (threshold >= 0);
  38982. jassert (sensitivity > 0);
  38983. jassert (offset >= 0);
  38984. velocityModeSensitivity = sensitivity;
  38985. velocityModeOffset = offset;
  38986. velocityModeThreshold = threshold;
  38987. userKeyOverridesVelocity = userCanPressKeyToSwapMode;
  38988. }
  38989. void Slider::setSkewFactor (const double factor)
  38990. {
  38991. skewFactor = factor;
  38992. }
  38993. void Slider::setSkewFactorFromMidPoint (const double sliderValueToShowAtMidPoint)
  38994. {
  38995. if (maximum > minimum)
  38996. skewFactor = log (0.5) / log ((sliderValueToShowAtMidPoint - minimum)
  38997. / (maximum - minimum));
  38998. }
  38999. void Slider::setMouseDragSensitivity (const int distanceForFullScaleDrag)
  39000. {
  39001. jassert (distanceForFullScaleDrag > 0);
  39002. pixelsForFullDragExtent = distanceForFullScaleDrag;
  39003. }
  39004. void Slider::setIncDecButtonsMode (const IncDecButtonMode mode)
  39005. {
  39006. if (incDecButtonMode != mode)
  39007. {
  39008. incDecButtonMode = mode;
  39009. lookAndFeelChanged();
  39010. }
  39011. }
  39012. void Slider::setTextBoxStyle (const TextEntryBoxPosition newPosition,
  39013. const bool isReadOnly,
  39014. const int textEntryBoxWidth,
  39015. const int textEntryBoxHeight)
  39016. {
  39017. textBoxPos = newPosition;
  39018. editableText = ! isReadOnly;
  39019. textBoxWidth = textEntryBoxWidth;
  39020. textBoxHeight = textEntryBoxHeight;
  39021. repaint();
  39022. lookAndFeelChanged();
  39023. }
  39024. void Slider::setTextBoxIsEditable (const bool shouldBeEditable)
  39025. {
  39026. editableText = shouldBeEditable;
  39027. if (valueBox != 0)
  39028. valueBox->setEditable (shouldBeEditable && isEnabled());
  39029. }
  39030. void Slider::showTextBox()
  39031. {
  39032. jassert (editableText); // this should probably be avoided in read-only sliders.
  39033. if (valueBox != 0)
  39034. valueBox->showEditor();
  39035. }
  39036. void Slider::hideTextBox (const bool discardCurrentEditorContents)
  39037. {
  39038. if (valueBox != 0)
  39039. {
  39040. valueBox->hideEditor (discardCurrentEditorContents);
  39041. if (discardCurrentEditorContents)
  39042. updateText();
  39043. }
  39044. }
  39045. void Slider::setChangeNotificationOnlyOnRelease (const bool onlyNotifyOnRelease)
  39046. {
  39047. sendChangeOnlyOnRelease = onlyNotifyOnRelease;
  39048. }
  39049. void Slider::setSliderSnapsToMousePosition (const bool shouldSnapToMouse)
  39050. {
  39051. snapsToMousePos = shouldSnapToMouse;
  39052. }
  39053. void Slider::setPopupDisplayEnabled (const bool enabled,
  39054. Component* const parentComponentToUse)
  39055. {
  39056. popupDisplayEnabled = enabled;
  39057. parentForPopupDisplay = parentComponentToUse;
  39058. }
  39059. void Slider::colourChanged()
  39060. {
  39061. lookAndFeelChanged();
  39062. }
  39063. void Slider::lookAndFeelChanged()
  39064. {
  39065. const String previousTextBoxContent (valueBox != 0 ? valueBox->getText()
  39066. : getTextFromValue (currentValue.getValue()));
  39067. deleteAllChildren();
  39068. valueBox = 0;
  39069. LookAndFeel& lf = getLookAndFeel();
  39070. if (textBoxPos != NoTextBox)
  39071. {
  39072. addAndMakeVisible (valueBox = getLookAndFeel().createSliderTextBox (*this));
  39073. valueBox->setWantsKeyboardFocus (false);
  39074. valueBox->setText (previousTextBoxContent, false);
  39075. valueBox->setEditable (editableText && isEnabled());
  39076. valueBox->addListener (this);
  39077. if (style == LinearBar)
  39078. valueBox->addMouseListener (this, false);
  39079. valueBox->setTooltip (getTooltip());
  39080. }
  39081. if (style == IncDecButtons)
  39082. {
  39083. addAndMakeVisible (incButton = lf.createSliderButton (true));
  39084. incButton->addButtonListener (this);
  39085. addAndMakeVisible (decButton = lf.createSliderButton (false));
  39086. decButton->addButtonListener (this);
  39087. if (incDecButtonMode != incDecButtonsNotDraggable)
  39088. {
  39089. incButton->addMouseListener (this, false);
  39090. decButton->addMouseListener (this, false);
  39091. }
  39092. else
  39093. {
  39094. incButton->setRepeatSpeed (300, 100, 20);
  39095. incButton->addMouseListener (decButton, false);
  39096. decButton->setRepeatSpeed (300, 100, 20);
  39097. decButton->addMouseListener (incButton, false);
  39098. }
  39099. incButton->setTooltip (getTooltip());
  39100. decButton->setTooltip (getTooltip());
  39101. }
  39102. setComponentEffect (lf.getSliderEffect());
  39103. resized();
  39104. repaint();
  39105. }
  39106. void Slider::setRange (const double newMin,
  39107. const double newMax,
  39108. const double newInt)
  39109. {
  39110. if (minimum != newMin
  39111. || maximum != newMax
  39112. || interval != newInt)
  39113. {
  39114. minimum = newMin;
  39115. maximum = newMax;
  39116. interval = newInt;
  39117. // figure out the number of DPs needed to display all values at this
  39118. // interval setting.
  39119. numDecimalPlaces = 7;
  39120. if (newInt != 0)
  39121. {
  39122. int v = abs ((int) (newInt * 10000000));
  39123. while ((v % 10) == 0)
  39124. {
  39125. --numDecimalPlaces;
  39126. v /= 10;
  39127. }
  39128. }
  39129. // keep the current values inside the new range..
  39130. if (style != TwoValueHorizontal && style != TwoValueVertical)
  39131. {
  39132. setValue (getValue(), false, false);
  39133. }
  39134. else
  39135. {
  39136. setMinValue (getMinValue(), false, false);
  39137. setMaxValue (getMaxValue(), false, false);
  39138. }
  39139. updateText();
  39140. }
  39141. }
  39142. void Slider::triggerChangeMessage (const bool synchronous)
  39143. {
  39144. if (synchronous)
  39145. handleAsyncUpdate();
  39146. else
  39147. triggerAsyncUpdate();
  39148. valueChanged();
  39149. }
  39150. void Slider::valueChanged (Value& value)
  39151. {
  39152. if (value.refersToSameSourceAs (currentValue))
  39153. {
  39154. if (style != TwoValueHorizontal && style != TwoValueVertical)
  39155. setValue (currentValue.getValue(), false, false);
  39156. }
  39157. else if (value.refersToSameSourceAs (valueMin))
  39158. setMinValue (valueMin.getValue(), false, false, true);
  39159. else if (value.refersToSameSourceAs (valueMax))
  39160. setMaxValue (valueMax.getValue(), false, false, true);
  39161. }
  39162. double Slider::getValue() const
  39163. {
  39164. // for a two-value style slider, you should use the getMinValue() and getMaxValue()
  39165. // methods to get the two values.
  39166. jassert (style != TwoValueHorizontal && style != TwoValueVertical);
  39167. return currentValue.getValue();
  39168. }
  39169. void Slider::setValue (double newValue,
  39170. const bool sendUpdateMessage,
  39171. const bool sendMessageSynchronously)
  39172. {
  39173. // for a two-value style slider, you should use the setMinValue() and setMaxValue()
  39174. // methods to set the two values.
  39175. jassert (style != TwoValueHorizontal && style != TwoValueVertical);
  39176. newValue = constrainedValue (newValue);
  39177. if (style == ThreeValueHorizontal || style == ThreeValueVertical)
  39178. {
  39179. jassert ((double) valueMin.getValue() <= (double) valueMax.getValue());
  39180. newValue = jlimit ((double) valueMin.getValue(),
  39181. (double) valueMax.getValue(),
  39182. newValue);
  39183. }
  39184. if (newValue != lastCurrentValue)
  39185. {
  39186. if (valueBox != 0)
  39187. valueBox->hideEditor (true);
  39188. lastCurrentValue = newValue;
  39189. currentValue = newValue;
  39190. updateText();
  39191. repaint();
  39192. if (popupDisplay != 0)
  39193. {
  39194. static_cast <SliderPopupDisplayComponent*> (static_cast <Component*> (popupDisplay))
  39195. ->updatePosition (getTextFromValue (newValue));
  39196. popupDisplay->repaint();
  39197. }
  39198. if (sendUpdateMessage)
  39199. triggerChangeMessage (sendMessageSynchronously);
  39200. }
  39201. }
  39202. double Slider::getMinValue() const
  39203. {
  39204. // The minimum value only applies to sliders that are in two- or three-value mode.
  39205. jassert (style == TwoValueHorizontal || style == TwoValueVertical
  39206. || style == ThreeValueHorizontal || style == ThreeValueVertical);
  39207. return valueMin.getValue();
  39208. }
  39209. double Slider::getMaxValue() const
  39210. {
  39211. // The maximum value only applies to sliders that are in two- or three-value mode.
  39212. jassert (style == TwoValueHorizontal || style == TwoValueVertical
  39213. || style == ThreeValueHorizontal || style == ThreeValueVertical);
  39214. return valueMax.getValue();
  39215. }
  39216. void Slider::setMinValue (double newValue, const bool sendUpdateMessage, const bool sendMessageSynchronously, const bool allowNudgingOfOtherValues)
  39217. {
  39218. // The minimum value only applies to sliders that are in two- or three-value mode.
  39219. jassert (style == TwoValueHorizontal || style == TwoValueVertical
  39220. || style == ThreeValueHorizontal || style == ThreeValueVertical);
  39221. newValue = constrainedValue (newValue);
  39222. if (style == TwoValueHorizontal || style == TwoValueVertical)
  39223. {
  39224. if (allowNudgingOfOtherValues && newValue > (double) valueMax.getValue())
  39225. setMaxValue (newValue, sendUpdateMessage, sendMessageSynchronously);
  39226. newValue = jmin ((double) valueMax.getValue(), newValue);
  39227. }
  39228. else
  39229. {
  39230. if (allowNudgingOfOtherValues && newValue > lastCurrentValue)
  39231. setValue (newValue, sendUpdateMessage, sendMessageSynchronously);
  39232. newValue = jmin (lastCurrentValue, newValue);
  39233. }
  39234. if (lastValueMin != newValue)
  39235. {
  39236. lastValueMin = newValue;
  39237. valueMin = newValue;
  39238. repaint();
  39239. if (popupDisplay != 0)
  39240. {
  39241. static_cast <SliderPopupDisplayComponent*> (static_cast <Component*> (popupDisplay))
  39242. ->updatePosition (getTextFromValue (newValue));
  39243. popupDisplay->repaint();
  39244. }
  39245. if (sendUpdateMessage)
  39246. triggerChangeMessage (sendMessageSynchronously);
  39247. }
  39248. }
  39249. void Slider::setMaxValue (double newValue, const bool sendUpdateMessage, const bool sendMessageSynchronously, const bool allowNudgingOfOtherValues)
  39250. {
  39251. // The maximum value only applies to sliders that are in two- or three-value mode.
  39252. jassert (style == TwoValueHorizontal || style == TwoValueVertical
  39253. || style == ThreeValueHorizontal || style == ThreeValueVertical);
  39254. newValue = constrainedValue (newValue);
  39255. if (style == TwoValueHorizontal || style == TwoValueVertical)
  39256. {
  39257. if (allowNudgingOfOtherValues && newValue < (double) valueMin.getValue())
  39258. setMinValue (newValue, sendUpdateMessage, sendMessageSynchronously);
  39259. newValue = jmax ((double) valueMin.getValue(), newValue);
  39260. }
  39261. else
  39262. {
  39263. if (allowNudgingOfOtherValues && newValue < lastCurrentValue)
  39264. setValue (newValue, sendUpdateMessage, sendMessageSynchronously);
  39265. newValue = jmax (lastCurrentValue, newValue);
  39266. }
  39267. if (lastValueMax != newValue)
  39268. {
  39269. lastValueMax = newValue;
  39270. valueMax = newValue;
  39271. repaint();
  39272. if (popupDisplay != 0)
  39273. {
  39274. static_cast <SliderPopupDisplayComponent*> (static_cast <Component*> (popupDisplay))
  39275. ->updatePosition (getTextFromValue (valueMax.getValue()));
  39276. popupDisplay->repaint();
  39277. }
  39278. if (sendUpdateMessage)
  39279. triggerChangeMessage (sendMessageSynchronously);
  39280. }
  39281. }
  39282. void Slider::setDoubleClickReturnValue (const bool isDoubleClickEnabled,
  39283. const double valueToSetOnDoubleClick)
  39284. {
  39285. doubleClickToValue = isDoubleClickEnabled;
  39286. doubleClickReturnValue = valueToSetOnDoubleClick;
  39287. }
  39288. double Slider::getDoubleClickReturnValue (bool& isEnabled_) const
  39289. {
  39290. isEnabled_ = doubleClickToValue;
  39291. return doubleClickReturnValue;
  39292. }
  39293. void Slider::updateText()
  39294. {
  39295. if (valueBox != 0)
  39296. valueBox->setText (getTextFromValue (currentValue.getValue()), false);
  39297. }
  39298. void Slider::setTextValueSuffix (const String& suffix)
  39299. {
  39300. if (textSuffix != suffix)
  39301. {
  39302. textSuffix = suffix;
  39303. updateText();
  39304. }
  39305. }
  39306. const String Slider::getTextValueSuffix() const
  39307. {
  39308. return textSuffix;
  39309. }
  39310. const String Slider::getTextFromValue (double v)
  39311. {
  39312. if (getNumDecimalPlacesToDisplay() > 0)
  39313. return String (v, getNumDecimalPlacesToDisplay()) + getTextValueSuffix();
  39314. else
  39315. return String (roundToInt (v)) + getTextValueSuffix();
  39316. }
  39317. double Slider::getValueFromText (const String& text)
  39318. {
  39319. String t (text.trimStart());
  39320. if (t.endsWith (textSuffix))
  39321. t = t.substring (0, t.length() - textSuffix.length());
  39322. while (t.startsWithChar ('+'))
  39323. t = t.substring (1).trimStart();
  39324. return t.initialSectionContainingOnly ("0123456789.,-")
  39325. .getDoubleValue();
  39326. }
  39327. double Slider::proportionOfLengthToValue (double proportion)
  39328. {
  39329. if (skewFactor != 1.0 && proportion > 0.0)
  39330. proportion = exp (log (proportion) / skewFactor);
  39331. return minimum + (maximum - minimum) * proportion;
  39332. }
  39333. double Slider::valueToProportionOfLength (double value)
  39334. {
  39335. const double n = (value - minimum) / (maximum - minimum);
  39336. return skewFactor == 1.0 ? n : pow (n, skewFactor);
  39337. }
  39338. double Slider::snapValue (double attemptedValue, const bool)
  39339. {
  39340. return attemptedValue;
  39341. }
  39342. void Slider::startedDragging()
  39343. {
  39344. }
  39345. void Slider::stoppedDragging()
  39346. {
  39347. }
  39348. void Slider::valueChanged()
  39349. {
  39350. }
  39351. void Slider::enablementChanged()
  39352. {
  39353. repaint();
  39354. }
  39355. void Slider::setPopupMenuEnabled (const bool menuEnabled_)
  39356. {
  39357. menuEnabled = menuEnabled_;
  39358. }
  39359. void Slider::setScrollWheelEnabled (const bool enabled)
  39360. {
  39361. scrollWheelEnabled = enabled;
  39362. }
  39363. void Slider::labelTextChanged (Label* label)
  39364. {
  39365. const double newValue = snapValue (getValueFromText (label->getText()), false);
  39366. if (newValue != (double) currentValue.getValue())
  39367. {
  39368. sendDragStart();
  39369. setValue (newValue, true, true);
  39370. sendDragEnd();
  39371. }
  39372. updateText(); // force a clean-up of the text, needed in case setValue() hasn't done this.
  39373. }
  39374. void Slider::buttonClicked (Button* button)
  39375. {
  39376. if (style == IncDecButtons)
  39377. {
  39378. sendDragStart();
  39379. if (button == incButton)
  39380. setValue (snapValue (getValue() + interval, false), true, true);
  39381. else if (button == decButton)
  39382. setValue (snapValue (getValue() - interval, false), true, true);
  39383. sendDragEnd();
  39384. }
  39385. }
  39386. double Slider::constrainedValue (double value) const
  39387. {
  39388. if (interval > 0)
  39389. value = minimum + interval * floor ((value - minimum) / interval + 0.5);
  39390. if (value <= minimum || maximum <= minimum)
  39391. value = minimum;
  39392. else if (value >= maximum)
  39393. value = maximum;
  39394. return value;
  39395. }
  39396. float Slider::getLinearSliderPos (const double value)
  39397. {
  39398. double sliderPosProportional;
  39399. if (maximum > minimum)
  39400. {
  39401. if (value < minimum)
  39402. {
  39403. sliderPosProportional = 0.0;
  39404. }
  39405. else if (value > maximum)
  39406. {
  39407. sliderPosProportional = 1.0;
  39408. }
  39409. else
  39410. {
  39411. sliderPosProportional = valueToProportionOfLength (value);
  39412. jassert (sliderPosProportional >= 0 && sliderPosProportional <= 1.0);
  39413. }
  39414. }
  39415. else
  39416. {
  39417. sliderPosProportional = 0.5;
  39418. }
  39419. if (isVertical() || style == IncDecButtons)
  39420. sliderPosProportional = 1.0 - sliderPosProportional;
  39421. return (float) (sliderRegionStart + sliderPosProportional * sliderRegionSize);
  39422. }
  39423. bool Slider::isHorizontal() const
  39424. {
  39425. return style == LinearHorizontal
  39426. || style == LinearBar
  39427. || style == TwoValueHorizontal
  39428. || style == ThreeValueHorizontal;
  39429. }
  39430. bool Slider::isVertical() const
  39431. {
  39432. return style == LinearVertical
  39433. || style == TwoValueVertical
  39434. || style == ThreeValueVertical;
  39435. }
  39436. bool Slider::incDecDragDirectionIsHorizontal() const
  39437. {
  39438. return incDecButtonMode == incDecButtonsDraggable_Horizontal
  39439. || (incDecButtonMode == incDecButtonsDraggable_AutoDirection && incDecButtonsSideBySide);
  39440. }
  39441. float Slider::getPositionOfValue (const double value)
  39442. {
  39443. if (isHorizontal() || isVertical())
  39444. {
  39445. return getLinearSliderPos (value);
  39446. }
  39447. else
  39448. {
  39449. jassertfalse // not a valid call on a slider that doesn't work linearly!
  39450. return 0.0f;
  39451. }
  39452. }
  39453. void Slider::paint (Graphics& g)
  39454. {
  39455. if (style != IncDecButtons)
  39456. {
  39457. if (style == Rotary || style == RotaryHorizontalDrag || style == RotaryVerticalDrag)
  39458. {
  39459. const float sliderPos = (float) valueToProportionOfLength (lastCurrentValue);
  39460. jassert (sliderPos >= 0 && sliderPos <= 1.0f);
  39461. getLookAndFeel().drawRotarySlider (g,
  39462. sliderRect.getX(),
  39463. sliderRect.getY(),
  39464. sliderRect.getWidth(),
  39465. sliderRect.getHeight(),
  39466. sliderPos,
  39467. rotaryStart, rotaryEnd,
  39468. *this);
  39469. }
  39470. else
  39471. {
  39472. getLookAndFeel().drawLinearSlider (g,
  39473. sliderRect.getX(),
  39474. sliderRect.getY(),
  39475. sliderRect.getWidth(),
  39476. sliderRect.getHeight(),
  39477. getLinearSliderPos (lastCurrentValue),
  39478. getLinearSliderPos (lastValueMin),
  39479. getLinearSliderPos (lastValueMax),
  39480. style,
  39481. *this);
  39482. }
  39483. if (style == LinearBar && valueBox == 0)
  39484. {
  39485. g.setColour (findColour (Slider::textBoxOutlineColourId));
  39486. g.drawRect (0, 0, getWidth(), getHeight(), 1);
  39487. }
  39488. }
  39489. }
  39490. void Slider::resized()
  39491. {
  39492. int minXSpace = 0;
  39493. int minYSpace = 0;
  39494. if (textBoxPos == TextBoxLeft || textBoxPos == TextBoxRight)
  39495. minXSpace = 30;
  39496. else
  39497. minYSpace = 15;
  39498. const int tbw = jmax (0, jmin (textBoxWidth, getWidth() - minXSpace));
  39499. const int tbh = jmax (0, jmin (textBoxHeight, getHeight() - minYSpace));
  39500. if (style == LinearBar)
  39501. {
  39502. if (valueBox != 0)
  39503. valueBox->setBounds (0, 0, getWidth(), getHeight());
  39504. }
  39505. else
  39506. {
  39507. if (textBoxPos == NoTextBox)
  39508. {
  39509. sliderRect.setBounds (0, 0, getWidth(), getHeight());
  39510. }
  39511. else if (textBoxPos == TextBoxLeft)
  39512. {
  39513. valueBox->setBounds (0, (getHeight() - tbh) / 2, tbw, tbh);
  39514. sliderRect.setBounds (tbw, 0, getWidth() - tbw, getHeight());
  39515. }
  39516. else if (textBoxPos == TextBoxRight)
  39517. {
  39518. valueBox->setBounds (getWidth() - tbw, (getHeight() - tbh) / 2, tbw, tbh);
  39519. sliderRect.setBounds (0, 0, getWidth() - tbw, getHeight());
  39520. }
  39521. else if (textBoxPos == TextBoxAbove)
  39522. {
  39523. valueBox->setBounds ((getWidth() - tbw) / 2, 0, tbw, tbh);
  39524. sliderRect.setBounds (0, tbh, getWidth(), getHeight() - tbh);
  39525. }
  39526. else if (textBoxPos == TextBoxBelow)
  39527. {
  39528. valueBox->setBounds ((getWidth() - tbw) / 2, getHeight() - tbh, tbw, tbh);
  39529. sliderRect.setBounds (0, 0, getWidth(), getHeight() - tbh);
  39530. }
  39531. }
  39532. const int indent = getLookAndFeel().getSliderThumbRadius (*this);
  39533. if (style == LinearBar)
  39534. {
  39535. const int barIndent = 1;
  39536. sliderRegionStart = barIndent;
  39537. sliderRegionSize = getWidth() - barIndent * 2;
  39538. sliderRect.setBounds (sliderRegionStart, barIndent,
  39539. sliderRegionSize, getHeight() - barIndent * 2);
  39540. }
  39541. else if (isHorizontal())
  39542. {
  39543. sliderRegionStart = sliderRect.getX() + indent;
  39544. sliderRegionSize = jmax (1, sliderRect.getWidth() - indent * 2);
  39545. sliderRect.setBounds (sliderRegionStart, sliderRect.getY(),
  39546. sliderRegionSize, sliderRect.getHeight());
  39547. }
  39548. else if (isVertical())
  39549. {
  39550. sliderRegionStart = sliderRect.getY() + indent;
  39551. sliderRegionSize = jmax (1, sliderRect.getHeight() - indent * 2);
  39552. sliderRect.setBounds (sliderRect.getX(), sliderRegionStart,
  39553. sliderRect.getWidth(), sliderRegionSize);
  39554. }
  39555. else
  39556. {
  39557. sliderRegionStart = 0;
  39558. sliderRegionSize = 100;
  39559. }
  39560. if (style == IncDecButtons)
  39561. {
  39562. Rectangle<int> buttonRect (sliderRect);
  39563. if (textBoxPos == TextBoxLeft || textBoxPos == TextBoxRight)
  39564. buttonRect.expand (-2, 0);
  39565. else
  39566. buttonRect.expand (0, -2);
  39567. incDecButtonsSideBySide = buttonRect.getWidth() > buttonRect.getHeight();
  39568. if (incDecButtonsSideBySide)
  39569. {
  39570. decButton->setBounds (buttonRect.getX(),
  39571. buttonRect.getY(),
  39572. buttonRect.getWidth() / 2,
  39573. buttonRect.getHeight());
  39574. decButton->setConnectedEdges (Button::ConnectedOnRight);
  39575. incButton->setBounds (buttonRect.getCentreX(),
  39576. buttonRect.getY(),
  39577. buttonRect.getWidth() / 2,
  39578. buttonRect.getHeight());
  39579. incButton->setConnectedEdges (Button::ConnectedOnLeft);
  39580. }
  39581. else
  39582. {
  39583. incButton->setBounds (buttonRect.getX(),
  39584. buttonRect.getY(),
  39585. buttonRect.getWidth(),
  39586. buttonRect.getHeight() / 2);
  39587. incButton->setConnectedEdges (Button::ConnectedOnBottom);
  39588. decButton->setBounds (buttonRect.getX(),
  39589. buttonRect.getCentreY(),
  39590. buttonRect.getWidth(),
  39591. buttonRect.getHeight() / 2);
  39592. decButton->setConnectedEdges (Button::ConnectedOnTop);
  39593. }
  39594. }
  39595. }
  39596. void Slider::focusOfChildComponentChanged (FocusChangeType)
  39597. {
  39598. repaint();
  39599. }
  39600. void Slider::mouseDown (const MouseEvent& e)
  39601. {
  39602. mouseWasHidden = false;
  39603. incDecDragged = false;
  39604. mouseXWhenLastDragged = e.x;
  39605. mouseYWhenLastDragged = e.y;
  39606. mouseDragStartX = e.getMouseDownX();
  39607. mouseDragStartY = e.getMouseDownY();
  39608. if (isEnabled())
  39609. {
  39610. if (e.mods.isPopupMenu() && menuEnabled)
  39611. {
  39612. menuShown = true;
  39613. PopupMenu m;
  39614. m.setLookAndFeel (&getLookAndFeel());
  39615. m.addItem (1, TRANS ("velocity-sensitive mode"), true, isVelocityBased);
  39616. m.addSeparator();
  39617. if (style == Rotary || style == RotaryHorizontalDrag || style == RotaryVerticalDrag)
  39618. {
  39619. PopupMenu rotaryMenu;
  39620. rotaryMenu.addItem (2, TRANS ("use circular dragging"), true, style == Rotary);
  39621. rotaryMenu.addItem (3, TRANS ("use left-right dragging"), true, style == RotaryHorizontalDrag);
  39622. rotaryMenu.addItem (4, TRANS ("use up-down dragging"), true, style == RotaryVerticalDrag);
  39623. m.addSubMenu (TRANS ("rotary mode"), rotaryMenu);
  39624. }
  39625. const int r = m.show();
  39626. if (r == 1)
  39627. {
  39628. setVelocityBasedMode (! isVelocityBased);
  39629. }
  39630. else if (r == 2)
  39631. {
  39632. setSliderStyle (Rotary);
  39633. }
  39634. else if (r == 3)
  39635. {
  39636. setSliderStyle (RotaryHorizontalDrag);
  39637. }
  39638. else if (r == 4)
  39639. {
  39640. setSliderStyle (RotaryVerticalDrag);
  39641. }
  39642. }
  39643. else if (maximum > minimum)
  39644. {
  39645. menuShown = false;
  39646. if (valueBox != 0)
  39647. valueBox->hideEditor (true);
  39648. sliderBeingDragged = 0;
  39649. if (style == TwoValueHorizontal
  39650. || style == TwoValueVertical
  39651. || style == ThreeValueHorizontal
  39652. || style == ThreeValueVertical)
  39653. {
  39654. const float mousePos = (float) (isVertical() ? e.y : e.x);
  39655. const float normalPosDistance = fabsf (getLinearSliderPos (currentValue.getValue()) - mousePos);
  39656. const float minPosDistance = fabsf (getLinearSliderPos (valueMin.getValue()) - 0.1f - mousePos);
  39657. const float maxPosDistance = fabsf (getLinearSliderPos (valueMax.getValue()) + 0.1f - mousePos);
  39658. if (style == TwoValueHorizontal || style == TwoValueVertical)
  39659. {
  39660. if (maxPosDistance <= minPosDistance)
  39661. sliderBeingDragged = 2;
  39662. else
  39663. sliderBeingDragged = 1;
  39664. }
  39665. else if (style == ThreeValueHorizontal || style == ThreeValueVertical)
  39666. {
  39667. if (normalPosDistance >= minPosDistance && maxPosDistance >= minPosDistance)
  39668. sliderBeingDragged = 1;
  39669. else if (normalPosDistance >= maxPosDistance)
  39670. sliderBeingDragged = 2;
  39671. }
  39672. }
  39673. minMaxDiff = (double) valueMax.getValue() - (double) valueMin.getValue();
  39674. lastAngle = rotaryStart + (rotaryEnd - rotaryStart)
  39675. * valueToProportionOfLength (currentValue.getValue());
  39676. valueWhenLastDragged = ((sliderBeingDragged == 2) ? valueMax
  39677. : ((sliderBeingDragged == 1) ? valueMin
  39678. : currentValue)).getValue();
  39679. valueOnMouseDown = valueWhenLastDragged;
  39680. if (popupDisplayEnabled)
  39681. {
  39682. SliderPopupDisplayComponent* const popup = new SliderPopupDisplayComponent (this);
  39683. popupDisplay = popup;
  39684. if (parentForPopupDisplay != 0)
  39685. {
  39686. parentForPopupDisplay->addChildComponent (popup);
  39687. }
  39688. else
  39689. {
  39690. popup->addToDesktop (0);
  39691. }
  39692. popup->setVisible (true);
  39693. }
  39694. sendDragStart();
  39695. mouseDrag (e);
  39696. }
  39697. }
  39698. }
  39699. void Slider::mouseUp (const MouseEvent&)
  39700. {
  39701. if (isEnabled()
  39702. && (! menuShown)
  39703. && (maximum > minimum)
  39704. && (style != IncDecButtons || incDecDragged))
  39705. {
  39706. restoreMouseIfHidden();
  39707. if (sendChangeOnlyOnRelease && valueOnMouseDown != (double) currentValue.getValue())
  39708. triggerChangeMessage (false);
  39709. sendDragEnd();
  39710. popupDisplay = 0;
  39711. if (style == IncDecButtons)
  39712. {
  39713. incButton->setState (Button::buttonNormal);
  39714. decButton->setState (Button::buttonNormal);
  39715. }
  39716. }
  39717. }
  39718. void Slider::restoreMouseIfHidden()
  39719. {
  39720. if (mouseWasHidden)
  39721. {
  39722. mouseWasHidden = false;
  39723. for (int i = Desktop::getInstance().getNumMouseSources(); --i >= 0;)
  39724. Desktop::getInstance().getMouseSource(i)->enableUnboundedMouseMovement (false);
  39725. const double pos = (sliderBeingDragged == 2) ? getMaxValue()
  39726. : ((sliderBeingDragged == 1) ? getMinValue()
  39727. : (double) currentValue.getValue());
  39728. Point<int> mousePos;
  39729. if (style == RotaryHorizontalDrag || style == RotaryVerticalDrag)
  39730. {
  39731. mousePos = Desktop::getLastMouseDownPosition();
  39732. if (style == RotaryHorizontalDrag)
  39733. {
  39734. const double posDiff = valueToProportionOfLength (pos) - valueToProportionOfLength (valueOnMouseDown);
  39735. mousePos += Point<int> (roundToInt (pixelsForFullDragExtent * posDiff), 0);
  39736. }
  39737. else
  39738. {
  39739. const double posDiff = valueToProportionOfLength (valueOnMouseDown) - valueToProportionOfLength (pos);
  39740. mousePos += Point<int> (0, roundToInt (pixelsForFullDragExtent * posDiff));
  39741. }
  39742. }
  39743. else
  39744. {
  39745. const int pixelPos = (int) getLinearSliderPos (pos);
  39746. mousePos = relativePositionToGlobal (Point<int> (isHorizontal() ? pixelPos : (getWidth() / 2),
  39747. isVertical() ? pixelPos : (getHeight() / 2)));
  39748. }
  39749. Desktop::setMousePosition (mousePos);
  39750. }
  39751. }
  39752. void Slider::modifierKeysChanged (const ModifierKeys& modifiers)
  39753. {
  39754. if (isEnabled()
  39755. && style != IncDecButtons
  39756. && style != Rotary
  39757. && isVelocityBased == modifiers.isAnyModifierKeyDown())
  39758. {
  39759. restoreMouseIfHidden();
  39760. }
  39761. }
  39762. static double smallestAngleBetween (double a1, double a2)
  39763. {
  39764. return jmin (fabs (a1 - a2),
  39765. fabs (a1 + double_Pi * 2.0 - a2),
  39766. fabs (a2 + double_Pi * 2.0 - a1));
  39767. }
  39768. void Slider::mouseDrag (const MouseEvent& e)
  39769. {
  39770. if (isEnabled()
  39771. && (! menuShown)
  39772. && (maximum > minimum))
  39773. {
  39774. if (style == Rotary)
  39775. {
  39776. int dx = e.x - sliderRect.getCentreX();
  39777. int dy = e.y - sliderRect.getCentreY();
  39778. if (dx * dx + dy * dy > 25)
  39779. {
  39780. double angle = atan2 ((double) dx, (double) -dy);
  39781. while (angle < 0.0)
  39782. angle += double_Pi * 2.0;
  39783. if (rotaryStop && ! e.mouseWasClicked())
  39784. {
  39785. if (fabs (angle - lastAngle) > double_Pi)
  39786. {
  39787. if (angle >= lastAngle)
  39788. angle -= double_Pi * 2.0;
  39789. else
  39790. angle += double_Pi * 2.0;
  39791. }
  39792. if (angle >= lastAngle)
  39793. angle = jmin (angle, (double) jmax (rotaryStart, rotaryEnd));
  39794. else
  39795. angle = jmax (angle, (double) jmin (rotaryStart, rotaryEnd));
  39796. }
  39797. else
  39798. {
  39799. while (angle < rotaryStart)
  39800. angle += double_Pi * 2.0;
  39801. if (angle > rotaryEnd)
  39802. {
  39803. if (smallestAngleBetween (angle, rotaryStart) <= smallestAngleBetween (angle, rotaryEnd))
  39804. angle = rotaryStart;
  39805. else
  39806. angle = rotaryEnd;
  39807. }
  39808. }
  39809. const double proportion = (angle - rotaryStart) / (rotaryEnd - rotaryStart);
  39810. valueWhenLastDragged = proportionOfLengthToValue (jlimit (0.0, 1.0, proportion));
  39811. lastAngle = angle;
  39812. }
  39813. }
  39814. else
  39815. {
  39816. if (style == LinearBar && e.mouseWasClicked()
  39817. && valueBox != 0 && valueBox->isEditable())
  39818. return;
  39819. if (style == IncDecButtons && ! incDecDragged)
  39820. {
  39821. if (e.getDistanceFromDragStart() < 10 || e.mouseWasClicked())
  39822. return;
  39823. incDecDragged = true;
  39824. mouseDragStartX = e.x;
  39825. mouseDragStartY = e.y;
  39826. }
  39827. if ((isVelocityBased == (userKeyOverridesVelocity ? e.mods.testFlags (ModifierKeys::ctrlModifier | ModifierKeys::commandModifier | ModifierKeys::altModifier)
  39828. : false))
  39829. || ((maximum - minimum) / sliderRegionSize < interval))
  39830. {
  39831. const int mousePos = (isHorizontal() || style == RotaryHorizontalDrag) ? e.x : e.y;
  39832. double scaledMousePos = (mousePos - sliderRegionStart) / (double) sliderRegionSize;
  39833. if (style == RotaryHorizontalDrag
  39834. || style == RotaryVerticalDrag
  39835. || style == IncDecButtons
  39836. || ((style == LinearHorizontal || style == LinearVertical || style == LinearBar)
  39837. && ! snapsToMousePos))
  39838. {
  39839. const int mouseDiff = (style == RotaryHorizontalDrag
  39840. || style == LinearHorizontal
  39841. || style == LinearBar
  39842. || (style == IncDecButtons && incDecDragDirectionIsHorizontal()))
  39843. ? e.x - mouseDragStartX
  39844. : mouseDragStartY - e.y;
  39845. double newPos = valueToProportionOfLength (valueOnMouseDown)
  39846. + mouseDiff * (1.0 / pixelsForFullDragExtent);
  39847. valueWhenLastDragged = proportionOfLengthToValue (jlimit (0.0, 1.0, newPos));
  39848. if (style == IncDecButtons)
  39849. {
  39850. incButton->setState (mouseDiff < 0 ? Button::buttonNormal : Button::buttonDown);
  39851. decButton->setState (mouseDiff > 0 ? Button::buttonNormal : Button::buttonDown);
  39852. }
  39853. }
  39854. else
  39855. {
  39856. if (isVertical())
  39857. scaledMousePos = 1.0 - scaledMousePos;
  39858. valueWhenLastDragged = proportionOfLengthToValue (jlimit (0.0, 1.0, scaledMousePos));
  39859. }
  39860. }
  39861. else
  39862. {
  39863. const int mouseDiff = (isHorizontal() || style == RotaryHorizontalDrag
  39864. || (style == IncDecButtons && incDecDragDirectionIsHorizontal()))
  39865. ? e.x - mouseXWhenLastDragged
  39866. : e.y - mouseYWhenLastDragged;
  39867. const double maxSpeed = jmax (200, sliderRegionSize);
  39868. double speed = jlimit (0.0, maxSpeed, (double) abs (mouseDiff));
  39869. if (speed != 0)
  39870. {
  39871. speed = 0.2 * velocityModeSensitivity
  39872. * (1.0 + sin (double_Pi * (1.5 + jmin (0.5, velocityModeOffset
  39873. + jmax (0.0, (double) (speed - velocityModeThreshold))
  39874. / maxSpeed))));
  39875. if (mouseDiff < 0)
  39876. speed = -speed;
  39877. if (isVertical() || style == RotaryVerticalDrag
  39878. || (style == IncDecButtons && ! incDecDragDirectionIsHorizontal()))
  39879. speed = -speed;
  39880. const double currentPos = valueToProportionOfLength (valueWhenLastDragged);
  39881. valueWhenLastDragged = proportionOfLengthToValue (jlimit (0.0, 1.0, currentPos + speed));
  39882. e.source.enableUnboundedMouseMovement (true, false);
  39883. mouseWasHidden = true;
  39884. }
  39885. }
  39886. }
  39887. valueWhenLastDragged = jlimit (minimum, maximum, valueWhenLastDragged);
  39888. if (sliderBeingDragged == 0)
  39889. {
  39890. setValue (snapValue (valueWhenLastDragged, true),
  39891. ! sendChangeOnlyOnRelease, true);
  39892. }
  39893. else if (sliderBeingDragged == 1)
  39894. {
  39895. setMinValue (snapValue (valueWhenLastDragged, true),
  39896. ! sendChangeOnlyOnRelease, false, true);
  39897. if (e.mods.isShiftDown())
  39898. setMaxValue (getMinValue() + minMaxDiff, false, false, true);
  39899. else
  39900. minMaxDiff = (double) valueMax.getValue() - (double) valueMin.getValue();
  39901. }
  39902. else
  39903. {
  39904. jassert (sliderBeingDragged == 2);
  39905. setMaxValue (snapValue (valueWhenLastDragged, true),
  39906. ! sendChangeOnlyOnRelease, false, true);
  39907. if (e.mods.isShiftDown())
  39908. setMinValue (getMaxValue() - minMaxDiff, false, false, true);
  39909. else
  39910. minMaxDiff = (double) valueMax.getValue() - (double) valueMin.getValue();
  39911. }
  39912. mouseXWhenLastDragged = e.x;
  39913. mouseYWhenLastDragged = e.y;
  39914. }
  39915. }
  39916. void Slider::mouseDoubleClick (const MouseEvent&)
  39917. {
  39918. if (doubleClickToValue
  39919. && isEnabled()
  39920. && style != IncDecButtons
  39921. && minimum <= doubleClickReturnValue
  39922. && maximum >= doubleClickReturnValue)
  39923. {
  39924. sendDragStart();
  39925. setValue (doubleClickReturnValue, true, true);
  39926. sendDragEnd();
  39927. }
  39928. }
  39929. void Slider::mouseWheelMove (const MouseEvent& e, float wheelIncrementX, float wheelIncrementY)
  39930. {
  39931. if (scrollWheelEnabled && isEnabled()
  39932. && style != TwoValueHorizontal
  39933. && style != TwoValueVertical)
  39934. {
  39935. if (maximum > minimum && ! e.mods.isAnyMouseButtonDown())
  39936. {
  39937. if (valueBox != 0)
  39938. valueBox->hideEditor (false);
  39939. const double value = (double) currentValue.getValue();
  39940. const double proportionDelta = (wheelIncrementX != 0 ? -wheelIncrementX : wheelIncrementY) * 0.15f;
  39941. const double currentPos = valueToProportionOfLength (value);
  39942. const double newValue = proportionOfLengthToValue (jlimit (0.0, 1.0, currentPos + proportionDelta));
  39943. double delta = (newValue != value)
  39944. ? jmax (fabs (newValue - value), interval) : 0;
  39945. if (value > newValue)
  39946. delta = -delta;
  39947. sendDragStart();
  39948. setValue (snapValue (value + delta, false), true, true);
  39949. sendDragEnd();
  39950. }
  39951. }
  39952. else
  39953. {
  39954. Component::mouseWheelMove (e, wheelIncrementX, wheelIncrementY);
  39955. }
  39956. }
  39957. void SliderListener::sliderDragStarted (Slider*)
  39958. {
  39959. }
  39960. void SliderListener::sliderDragEnded (Slider*)
  39961. {
  39962. }
  39963. END_JUCE_NAMESPACE
  39964. /*** End of inlined file: juce_Slider.cpp ***/
  39965. /*** Start of inlined file: juce_TableHeaderComponent.cpp ***/
  39966. BEGIN_JUCE_NAMESPACE
  39967. class DragOverlayComp : public Component
  39968. {
  39969. public:
  39970. DragOverlayComp (Image* const image_)
  39971. : image (image_)
  39972. {
  39973. image->multiplyAllAlphas (0.8f);
  39974. setAlwaysOnTop (true);
  39975. }
  39976. ~DragOverlayComp()
  39977. {
  39978. }
  39979. void paint (Graphics& g)
  39980. {
  39981. g.drawImageAt (image, 0, 0);
  39982. }
  39983. private:
  39984. ScopedPointer <Image> image;
  39985. DragOverlayComp (const DragOverlayComp&);
  39986. DragOverlayComp& operator= (const DragOverlayComp&);
  39987. };
  39988. TableHeaderComponent::TableHeaderComponent()
  39989. : columnsChanged (false),
  39990. columnsResized (false),
  39991. sortChanged (false),
  39992. menuActive (true),
  39993. stretchToFit (false),
  39994. columnIdBeingResized (0),
  39995. columnIdBeingDragged (0),
  39996. columnIdUnderMouse (0),
  39997. lastDeliberateWidth (0)
  39998. {
  39999. }
  40000. TableHeaderComponent::~TableHeaderComponent()
  40001. {
  40002. dragOverlayComp = 0;
  40003. }
  40004. void TableHeaderComponent::setPopupMenuActive (const bool hasMenu)
  40005. {
  40006. menuActive = hasMenu;
  40007. }
  40008. bool TableHeaderComponent::isPopupMenuActive() const { return menuActive; }
  40009. int TableHeaderComponent::getNumColumns (const bool onlyCountVisibleColumns) const
  40010. {
  40011. if (onlyCountVisibleColumns)
  40012. {
  40013. int num = 0;
  40014. for (int i = columns.size(); --i >= 0;)
  40015. if (columns.getUnchecked(i)->isVisible())
  40016. ++num;
  40017. return num;
  40018. }
  40019. else
  40020. {
  40021. return columns.size();
  40022. }
  40023. }
  40024. const String TableHeaderComponent::getColumnName (const int columnId) const
  40025. {
  40026. const ColumnInfo* const ci = getInfoForId (columnId);
  40027. return ci != 0 ? ci->name : String::empty;
  40028. }
  40029. void TableHeaderComponent::setColumnName (const int columnId, const String& newName)
  40030. {
  40031. ColumnInfo* const ci = getInfoForId (columnId);
  40032. if (ci != 0 && ci->name != newName)
  40033. {
  40034. ci->name = newName;
  40035. sendColumnsChanged();
  40036. }
  40037. }
  40038. void TableHeaderComponent::addColumn (const String& columnName,
  40039. const int columnId,
  40040. const int width,
  40041. const int minimumWidth,
  40042. const int maximumWidth,
  40043. const int propertyFlags,
  40044. const int insertIndex)
  40045. {
  40046. // can't have a duplicate or null ID!
  40047. jassert (columnId != 0 && getIndexOfColumnId (columnId, false) < 0);
  40048. jassert (width > 0);
  40049. ColumnInfo* const ci = new ColumnInfo();
  40050. ci->name = columnName;
  40051. ci->id = columnId;
  40052. ci->width = width;
  40053. ci->lastDeliberateWidth = width;
  40054. ci->minimumWidth = minimumWidth;
  40055. ci->maximumWidth = maximumWidth;
  40056. if (ci->maximumWidth < 0)
  40057. ci->maximumWidth = std::numeric_limits<int>::max();
  40058. jassert (ci->maximumWidth >= ci->minimumWidth);
  40059. ci->propertyFlags = propertyFlags;
  40060. columns.insert (insertIndex, ci);
  40061. sendColumnsChanged();
  40062. }
  40063. void TableHeaderComponent::removeColumn (const int columnIdToRemove)
  40064. {
  40065. const int index = getIndexOfColumnId (columnIdToRemove, false);
  40066. if (index >= 0)
  40067. {
  40068. columns.remove (index);
  40069. sortChanged = true;
  40070. sendColumnsChanged();
  40071. }
  40072. }
  40073. void TableHeaderComponent::removeAllColumns()
  40074. {
  40075. if (columns.size() > 0)
  40076. {
  40077. columns.clear();
  40078. sendColumnsChanged();
  40079. }
  40080. }
  40081. void TableHeaderComponent::moveColumn (const int columnId, int newIndex)
  40082. {
  40083. const int currentIndex = getIndexOfColumnId (columnId, false);
  40084. newIndex = visibleIndexToTotalIndex (newIndex);
  40085. if (columns [currentIndex] != 0 && currentIndex != newIndex)
  40086. {
  40087. columns.move (currentIndex, newIndex);
  40088. sendColumnsChanged();
  40089. }
  40090. }
  40091. int TableHeaderComponent::getColumnWidth (const int columnId) const
  40092. {
  40093. const ColumnInfo* const ci = getInfoForId (columnId);
  40094. return ci != 0 ? ci->width : 0;
  40095. }
  40096. void TableHeaderComponent::setColumnWidth (const int columnId, const int newWidth)
  40097. {
  40098. ColumnInfo* const ci = getInfoForId (columnId);
  40099. if (ci != 0 && ci->width != newWidth)
  40100. {
  40101. const int numColumns = getNumColumns (true);
  40102. ci->lastDeliberateWidth = ci->width
  40103. = jlimit (ci->minimumWidth, ci->maximumWidth, newWidth);
  40104. if (stretchToFit)
  40105. {
  40106. const int index = getIndexOfColumnId (columnId, true) + 1;
  40107. if (((unsigned int) index) < (unsigned int) numColumns)
  40108. {
  40109. const int x = getColumnPosition (index).getX();
  40110. if (lastDeliberateWidth == 0)
  40111. lastDeliberateWidth = getTotalWidth();
  40112. resizeColumnsToFit (visibleIndexToTotalIndex (index), lastDeliberateWidth - x);
  40113. }
  40114. }
  40115. repaint();
  40116. columnsResized = true;
  40117. triggerAsyncUpdate();
  40118. }
  40119. }
  40120. int TableHeaderComponent::getIndexOfColumnId (const int columnId, const bool onlyCountVisibleColumns) const
  40121. {
  40122. int n = 0;
  40123. for (int i = 0; i < columns.size(); ++i)
  40124. {
  40125. if ((! onlyCountVisibleColumns) || columns.getUnchecked(i)->isVisible())
  40126. {
  40127. if (columns.getUnchecked(i)->id == columnId)
  40128. return n;
  40129. ++n;
  40130. }
  40131. }
  40132. return -1;
  40133. }
  40134. int TableHeaderComponent::getColumnIdOfIndex (int index, const bool onlyCountVisibleColumns) const
  40135. {
  40136. if (onlyCountVisibleColumns)
  40137. index = visibleIndexToTotalIndex (index);
  40138. const ColumnInfo* const ci = columns [index];
  40139. return (ci != 0) ? ci->id : 0;
  40140. }
  40141. const Rectangle<int> TableHeaderComponent::getColumnPosition (const int index) const
  40142. {
  40143. int x = 0, width = 0, n = 0;
  40144. for (int i = 0; i < columns.size(); ++i)
  40145. {
  40146. x += width;
  40147. if (columns.getUnchecked(i)->isVisible())
  40148. {
  40149. width = columns.getUnchecked(i)->width;
  40150. if (n++ == index)
  40151. break;
  40152. }
  40153. else
  40154. {
  40155. width = 0;
  40156. }
  40157. }
  40158. return Rectangle<int> (x, 0, width, getHeight());
  40159. }
  40160. int TableHeaderComponent::getColumnIdAtX (const int xToFind) const
  40161. {
  40162. if (xToFind >= 0)
  40163. {
  40164. int x = 0;
  40165. for (int i = 0; i < columns.size(); ++i)
  40166. {
  40167. const ColumnInfo* const ci = columns.getUnchecked(i);
  40168. if (ci->isVisible())
  40169. {
  40170. x += ci->width;
  40171. if (xToFind < x)
  40172. return ci->id;
  40173. }
  40174. }
  40175. }
  40176. return 0;
  40177. }
  40178. int TableHeaderComponent::getTotalWidth() const
  40179. {
  40180. int w = 0;
  40181. for (int i = columns.size(); --i >= 0;)
  40182. if (columns.getUnchecked(i)->isVisible())
  40183. w += columns.getUnchecked(i)->width;
  40184. return w;
  40185. }
  40186. void TableHeaderComponent::setStretchToFitActive (const bool shouldStretchToFit)
  40187. {
  40188. stretchToFit = shouldStretchToFit;
  40189. lastDeliberateWidth = getTotalWidth();
  40190. resized();
  40191. }
  40192. bool TableHeaderComponent::isStretchToFitActive() const
  40193. {
  40194. return stretchToFit;
  40195. }
  40196. void TableHeaderComponent::resizeAllColumnsToFit (int targetTotalWidth)
  40197. {
  40198. if (stretchToFit && getWidth() > 0
  40199. && columnIdBeingResized == 0 && columnIdBeingDragged == 0)
  40200. {
  40201. lastDeliberateWidth = targetTotalWidth;
  40202. resizeColumnsToFit (0, targetTotalWidth);
  40203. }
  40204. }
  40205. void TableHeaderComponent::resizeColumnsToFit (int firstColumnIndex, int targetTotalWidth)
  40206. {
  40207. targetTotalWidth = jmax (targetTotalWidth, 0);
  40208. StretchableObjectResizer sor;
  40209. int i;
  40210. for (i = firstColumnIndex; i < columns.size(); ++i)
  40211. {
  40212. ColumnInfo* const ci = columns.getUnchecked(i);
  40213. if (ci->isVisible())
  40214. sor.addItem (ci->lastDeliberateWidth, ci->minimumWidth, ci->maximumWidth);
  40215. }
  40216. sor.resizeToFit (targetTotalWidth);
  40217. int visIndex = 0;
  40218. for (i = firstColumnIndex; i < columns.size(); ++i)
  40219. {
  40220. ColumnInfo* const ci = columns.getUnchecked(i);
  40221. if (ci->isVisible())
  40222. {
  40223. const int newWidth = jlimit (ci->minimumWidth, ci->maximumWidth,
  40224. (int) floor (sor.getItemSize (visIndex++)));
  40225. if (newWidth != ci->width)
  40226. {
  40227. ci->width = newWidth;
  40228. repaint();
  40229. columnsResized = true;
  40230. triggerAsyncUpdate();
  40231. }
  40232. }
  40233. }
  40234. }
  40235. void TableHeaderComponent::setColumnVisible (const int columnId, const bool shouldBeVisible)
  40236. {
  40237. ColumnInfo* const ci = getInfoForId (columnId);
  40238. if (ci != 0 && shouldBeVisible != ci->isVisible())
  40239. {
  40240. if (shouldBeVisible)
  40241. ci->propertyFlags |= visible;
  40242. else
  40243. ci->propertyFlags &= ~visible;
  40244. sendColumnsChanged();
  40245. resized();
  40246. }
  40247. }
  40248. bool TableHeaderComponent::isColumnVisible (const int columnId) const
  40249. {
  40250. const ColumnInfo* const ci = getInfoForId (columnId);
  40251. return ci != 0 && ci->isVisible();
  40252. }
  40253. void TableHeaderComponent::setSortColumnId (const int columnId, const bool sortForwards)
  40254. {
  40255. if (getSortColumnId() != columnId || isSortedForwards() != sortForwards)
  40256. {
  40257. for (int i = columns.size(); --i >= 0;)
  40258. columns.getUnchecked(i)->propertyFlags &= ~(sortedForwards | sortedBackwards);
  40259. ColumnInfo* const ci = getInfoForId (columnId);
  40260. if (ci != 0)
  40261. ci->propertyFlags |= (sortForwards ? sortedForwards : sortedBackwards);
  40262. reSortTable();
  40263. }
  40264. }
  40265. int TableHeaderComponent::getSortColumnId() const
  40266. {
  40267. for (int i = columns.size(); --i >= 0;)
  40268. if ((columns.getUnchecked(i)->propertyFlags & (sortedForwards | sortedBackwards)) != 0)
  40269. return columns.getUnchecked(i)->id;
  40270. return 0;
  40271. }
  40272. bool TableHeaderComponent::isSortedForwards() const
  40273. {
  40274. for (int i = columns.size(); --i >= 0;)
  40275. if ((columns.getUnchecked(i)->propertyFlags & (sortedForwards | sortedBackwards)) != 0)
  40276. return (columns.getUnchecked(i)->propertyFlags & sortedForwards) != 0;
  40277. return true;
  40278. }
  40279. void TableHeaderComponent::reSortTable()
  40280. {
  40281. sortChanged = true;
  40282. repaint();
  40283. triggerAsyncUpdate();
  40284. }
  40285. const String TableHeaderComponent::toString() const
  40286. {
  40287. String s;
  40288. XmlElement doc ("TABLELAYOUT");
  40289. doc.setAttribute ("sortedCol", getSortColumnId());
  40290. doc.setAttribute ("sortForwards", isSortedForwards());
  40291. for (int i = 0; i < columns.size(); ++i)
  40292. {
  40293. const ColumnInfo* const ci = columns.getUnchecked (i);
  40294. XmlElement* const e = doc.createNewChildElement ("COLUMN");
  40295. e->setAttribute ("id", ci->id);
  40296. e->setAttribute ("visible", ci->isVisible());
  40297. e->setAttribute ("width", ci->width);
  40298. }
  40299. return doc.createDocument (String::empty, true, false);
  40300. }
  40301. void TableHeaderComponent::restoreFromString (const String& storedVersion)
  40302. {
  40303. XmlDocument doc (storedVersion);
  40304. ScopedPointer <XmlElement> storedXml (doc.getDocumentElement());
  40305. int index = 0;
  40306. if (storedXml != 0 && storedXml->hasTagName ("TABLELAYOUT"))
  40307. {
  40308. forEachXmlChildElement (*storedXml, col)
  40309. {
  40310. const int tabId = col->getIntAttribute ("id");
  40311. ColumnInfo* const ci = getInfoForId (tabId);
  40312. if (ci != 0)
  40313. {
  40314. columns.move (columns.indexOf (ci), index);
  40315. ci->width = col->getIntAttribute ("width");
  40316. setColumnVisible (tabId, col->getBoolAttribute ("visible"));
  40317. }
  40318. ++index;
  40319. }
  40320. columnsResized = true;
  40321. sendColumnsChanged();
  40322. setSortColumnId (storedXml->getIntAttribute ("sortedCol"),
  40323. storedXml->getBoolAttribute ("sortForwards", true));
  40324. }
  40325. }
  40326. void TableHeaderComponent::addListener (TableHeaderListener* const newListener)
  40327. {
  40328. listeners.addIfNotAlreadyThere (newListener);
  40329. }
  40330. void TableHeaderComponent::removeListener (TableHeaderListener* const listenerToRemove)
  40331. {
  40332. listeners.removeValue (listenerToRemove);
  40333. }
  40334. void TableHeaderComponent::columnClicked (int columnId, const ModifierKeys& mods)
  40335. {
  40336. const ColumnInfo* const ci = getInfoForId (columnId);
  40337. if (ci != 0 && (ci->propertyFlags & sortable) != 0 && ! mods.isPopupMenu())
  40338. setSortColumnId (columnId, (ci->propertyFlags & sortedForwards) == 0);
  40339. }
  40340. void TableHeaderComponent::addMenuItems (PopupMenu& menu, const int /*columnIdClicked*/)
  40341. {
  40342. for (int i = 0; i < columns.size(); ++i)
  40343. {
  40344. const ColumnInfo* const ci = columns.getUnchecked(i);
  40345. if ((ci->propertyFlags & appearsOnColumnMenu) != 0)
  40346. menu.addItem (ci->id, ci->name,
  40347. (ci->propertyFlags & (sortedForwards | sortedBackwards)) == 0,
  40348. isColumnVisible (ci->id));
  40349. }
  40350. }
  40351. void TableHeaderComponent::reactToMenuItem (const int menuReturnId, const int /*columnIdClicked*/)
  40352. {
  40353. if (getIndexOfColumnId (menuReturnId, false) >= 0)
  40354. setColumnVisible (menuReturnId, ! isColumnVisible (menuReturnId));
  40355. }
  40356. void TableHeaderComponent::paint (Graphics& g)
  40357. {
  40358. LookAndFeel& lf = getLookAndFeel();
  40359. lf.drawTableHeaderBackground (g, *this);
  40360. const Rectangle<int> clip (g.getClipBounds());
  40361. int x = 0;
  40362. for (int i = 0; i < columns.size(); ++i)
  40363. {
  40364. const ColumnInfo* const ci = columns.getUnchecked(i);
  40365. if (ci->isVisible())
  40366. {
  40367. if (x + ci->width > clip.getX()
  40368. && (ci->id != columnIdBeingDragged
  40369. || dragOverlayComp == 0
  40370. || ! dragOverlayComp->isVisible()))
  40371. {
  40372. g.saveState();
  40373. g.setOrigin (x, 0);
  40374. g.reduceClipRegion (0, 0, ci->width, getHeight());
  40375. lf.drawTableHeaderColumn (g, ci->name, ci->id, ci->width, getHeight(),
  40376. ci->id == columnIdUnderMouse,
  40377. ci->id == columnIdUnderMouse && isMouseButtonDown(),
  40378. ci->propertyFlags);
  40379. g.restoreState();
  40380. }
  40381. x += ci->width;
  40382. if (x >= clip.getRight())
  40383. break;
  40384. }
  40385. }
  40386. }
  40387. void TableHeaderComponent::resized()
  40388. {
  40389. }
  40390. void TableHeaderComponent::mouseMove (const MouseEvent& e)
  40391. {
  40392. updateColumnUnderMouse (e.x, e.y);
  40393. }
  40394. void TableHeaderComponent::mouseEnter (const MouseEvent& e)
  40395. {
  40396. updateColumnUnderMouse (e.x, e.y);
  40397. }
  40398. void TableHeaderComponent::mouseExit (const MouseEvent& e)
  40399. {
  40400. updateColumnUnderMouse (e.x, e.y);
  40401. }
  40402. void TableHeaderComponent::mouseDown (const MouseEvent& e)
  40403. {
  40404. repaint();
  40405. columnIdBeingResized = 0;
  40406. columnIdBeingDragged = 0;
  40407. if (columnIdUnderMouse != 0)
  40408. {
  40409. draggingColumnOffset = e.x - getColumnPosition (getIndexOfColumnId (columnIdUnderMouse, true)).getX();
  40410. if (e.mods.isPopupMenu())
  40411. columnClicked (columnIdUnderMouse, e.mods);
  40412. }
  40413. if (menuActive && e.mods.isPopupMenu())
  40414. showColumnChooserMenu (columnIdUnderMouse);
  40415. }
  40416. void TableHeaderComponent::mouseDrag (const MouseEvent& e)
  40417. {
  40418. if (columnIdBeingResized == 0
  40419. && columnIdBeingDragged == 0
  40420. && ! (e.mouseWasClicked() || e.mods.isPopupMenu()))
  40421. {
  40422. dragOverlayComp = 0;
  40423. columnIdBeingResized = getResizeDraggerAt (e.getMouseDownX());
  40424. if (columnIdBeingResized != 0)
  40425. {
  40426. const ColumnInfo* const ci = getInfoForId (columnIdBeingResized);
  40427. initialColumnWidth = ci->width;
  40428. }
  40429. else
  40430. {
  40431. beginDrag (e);
  40432. }
  40433. }
  40434. if (columnIdBeingResized != 0)
  40435. {
  40436. const ColumnInfo* const ci = getInfoForId (columnIdBeingResized);
  40437. if (ci != 0)
  40438. {
  40439. int w = jlimit (ci->minimumWidth, ci->maximumWidth,
  40440. initialColumnWidth + e.getDistanceFromDragStartX());
  40441. if (stretchToFit)
  40442. {
  40443. // prevent us dragging a column too far right if we're in stretch-to-fit mode
  40444. int minWidthOnRight = 0;
  40445. for (int i = getIndexOfColumnId (columnIdBeingResized, false) + 1; i < columns.size(); ++i)
  40446. if (columns.getUnchecked (i)->isVisible())
  40447. minWidthOnRight += columns.getUnchecked (i)->minimumWidth;
  40448. const Rectangle<int> currentPos (getColumnPosition (getIndexOfColumnId (columnIdBeingResized, true)));
  40449. w = jmax (ci->minimumWidth, jmin (w, getWidth() - minWidthOnRight - currentPos.getX()));
  40450. }
  40451. setColumnWidth (columnIdBeingResized, w);
  40452. }
  40453. }
  40454. else if (columnIdBeingDragged != 0)
  40455. {
  40456. if (e.y >= -50 && e.y < getHeight() + 50)
  40457. {
  40458. if (dragOverlayComp != 0)
  40459. {
  40460. dragOverlayComp->setVisible (true);
  40461. dragOverlayComp->setBounds (jlimit (0,
  40462. jmax (0, getTotalWidth() - dragOverlayComp->getWidth()),
  40463. e.x - draggingColumnOffset),
  40464. 0,
  40465. dragOverlayComp->getWidth(),
  40466. getHeight());
  40467. for (int i = columns.size(); --i >= 0;)
  40468. {
  40469. const int currentIndex = getIndexOfColumnId (columnIdBeingDragged, true);
  40470. int newIndex = currentIndex;
  40471. if (newIndex > 0)
  40472. {
  40473. // if the previous column isn't draggable, we can't move our column
  40474. // past it, because that'd change the undraggable column's position..
  40475. const ColumnInfo* const previous = columns.getUnchecked (newIndex - 1);
  40476. if ((previous->propertyFlags & draggable) != 0)
  40477. {
  40478. const int leftOfPrevious = getColumnPosition (newIndex - 1).getX();
  40479. const int rightOfCurrent = getColumnPosition (newIndex).getRight();
  40480. if (abs (dragOverlayComp->getX() - leftOfPrevious)
  40481. < abs (dragOverlayComp->getRight() - rightOfCurrent))
  40482. {
  40483. --newIndex;
  40484. }
  40485. }
  40486. }
  40487. if (newIndex < columns.size() - 1)
  40488. {
  40489. // if the next column isn't draggable, we can't move our column
  40490. // past it, because that'd change the undraggable column's position..
  40491. const ColumnInfo* const nextCol = columns.getUnchecked (newIndex + 1);
  40492. if ((nextCol->propertyFlags & draggable) != 0)
  40493. {
  40494. const int leftOfCurrent = getColumnPosition (newIndex).getX();
  40495. const int rightOfNext = getColumnPosition (newIndex + 1).getRight();
  40496. if (abs (dragOverlayComp->getX() - leftOfCurrent)
  40497. > abs (dragOverlayComp->getRight() - rightOfNext))
  40498. {
  40499. ++newIndex;
  40500. }
  40501. }
  40502. }
  40503. if (newIndex != currentIndex)
  40504. moveColumn (columnIdBeingDragged, newIndex);
  40505. else
  40506. break;
  40507. }
  40508. }
  40509. }
  40510. else
  40511. {
  40512. endDrag (draggingColumnOriginalIndex);
  40513. }
  40514. }
  40515. }
  40516. void TableHeaderComponent::beginDrag (const MouseEvent& e)
  40517. {
  40518. if (columnIdBeingDragged == 0)
  40519. {
  40520. columnIdBeingDragged = getColumnIdAtX (e.getMouseDownX());
  40521. const ColumnInfo* const ci = getInfoForId (columnIdBeingDragged);
  40522. if (ci == 0 || (ci->propertyFlags & draggable) == 0)
  40523. {
  40524. columnIdBeingDragged = 0;
  40525. }
  40526. else
  40527. {
  40528. draggingColumnOriginalIndex = getIndexOfColumnId (columnIdBeingDragged, true);
  40529. const Rectangle<int> columnRect (getColumnPosition (draggingColumnOriginalIndex));
  40530. const int temp = columnIdBeingDragged;
  40531. columnIdBeingDragged = 0;
  40532. addAndMakeVisible (dragOverlayComp = new DragOverlayComp (createComponentSnapshot (columnRect, false)));
  40533. columnIdBeingDragged = temp;
  40534. dragOverlayComp->setBounds (columnRect);
  40535. for (int i = listeners.size(); --i >= 0;)
  40536. {
  40537. listeners.getUnchecked(i)->tableColumnDraggingChanged (this, columnIdBeingDragged);
  40538. i = jmin (i, listeners.size() - 1);
  40539. }
  40540. }
  40541. }
  40542. }
  40543. void TableHeaderComponent::endDrag (const int finalIndex)
  40544. {
  40545. if (columnIdBeingDragged != 0)
  40546. {
  40547. moveColumn (columnIdBeingDragged, finalIndex);
  40548. columnIdBeingDragged = 0;
  40549. repaint();
  40550. for (int i = listeners.size(); --i >= 0;)
  40551. {
  40552. listeners.getUnchecked(i)->tableColumnDraggingChanged (this, 0);
  40553. i = jmin (i, listeners.size() - 1);
  40554. }
  40555. }
  40556. }
  40557. void TableHeaderComponent::mouseUp (const MouseEvent& e)
  40558. {
  40559. mouseDrag (e);
  40560. for (int i = columns.size(); --i >= 0;)
  40561. if (columns.getUnchecked (i)->isVisible())
  40562. columns.getUnchecked (i)->lastDeliberateWidth = columns.getUnchecked (i)->width;
  40563. columnIdBeingResized = 0;
  40564. repaint();
  40565. endDrag (getIndexOfColumnId (columnIdBeingDragged, true));
  40566. updateColumnUnderMouse (e.x, e.y);
  40567. if (columnIdUnderMouse != 0 && e.mouseWasClicked() && ! e.mods.isPopupMenu())
  40568. columnClicked (columnIdUnderMouse, e.mods);
  40569. dragOverlayComp = 0;
  40570. }
  40571. const MouseCursor TableHeaderComponent::getMouseCursor()
  40572. {
  40573. if (columnIdBeingResized != 0 || (getResizeDraggerAt (getMouseXYRelative().getX()) != 0 && ! isMouseButtonDown()))
  40574. return MouseCursor (MouseCursor::LeftRightResizeCursor);
  40575. return Component::getMouseCursor();
  40576. }
  40577. bool TableHeaderComponent::ColumnInfo::isVisible() const
  40578. {
  40579. return (propertyFlags & TableHeaderComponent::visible) != 0;
  40580. }
  40581. TableHeaderComponent::ColumnInfo* TableHeaderComponent::getInfoForId (const int id) const
  40582. {
  40583. for (int i = columns.size(); --i >= 0;)
  40584. if (columns.getUnchecked(i)->id == id)
  40585. return columns.getUnchecked(i);
  40586. return 0;
  40587. }
  40588. int TableHeaderComponent::visibleIndexToTotalIndex (const int visibleIndex) const
  40589. {
  40590. int n = 0;
  40591. for (int i = 0; i < columns.size(); ++i)
  40592. {
  40593. if (columns.getUnchecked(i)->isVisible())
  40594. {
  40595. if (n == visibleIndex)
  40596. return i;
  40597. ++n;
  40598. }
  40599. }
  40600. return -1;
  40601. }
  40602. void TableHeaderComponent::sendColumnsChanged()
  40603. {
  40604. if (stretchToFit && lastDeliberateWidth > 0)
  40605. resizeAllColumnsToFit (lastDeliberateWidth);
  40606. repaint();
  40607. columnsChanged = true;
  40608. triggerAsyncUpdate();
  40609. }
  40610. void TableHeaderComponent::handleAsyncUpdate()
  40611. {
  40612. const bool changed = columnsChanged || sortChanged;
  40613. const bool sized = columnsResized || changed;
  40614. const bool sorted = sortChanged;
  40615. columnsChanged = false;
  40616. columnsResized = false;
  40617. sortChanged = false;
  40618. if (sorted)
  40619. {
  40620. for (int i = listeners.size(); --i >= 0;)
  40621. {
  40622. listeners.getUnchecked(i)->tableSortOrderChanged (this);
  40623. i = jmin (i, listeners.size() - 1);
  40624. }
  40625. }
  40626. if (changed)
  40627. {
  40628. for (int i = listeners.size(); --i >= 0;)
  40629. {
  40630. listeners.getUnchecked(i)->tableColumnsChanged (this);
  40631. i = jmin (i, listeners.size() - 1);
  40632. }
  40633. }
  40634. if (sized)
  40635. {
  40636. for (int i = listeners.size(); --i >= 0;)
  40637. {
  40638. listeners.getUnchecked(i)->tableColumnsResized (this);
  40639. i = jmin (i, listeners.size() - 1);
  40640. }
  40641. }
  40642. }
  40643. int TableHeaderComponent::getResizeDraggerAt (const int mouseX) const
  40644. {
  40645. if (((unsigned int) mouseX) < (unsigned int) getWidth())
  40646. {
  40647. const int draggableDistance = 3;
  40648. int x = 0;
  40649. for (int i = 0; i < columns.size(); ++i)
  40650. {
  40651. const ColumnInfo* const ci = columns.getUnchecked(i);
  40652. if (ci->isVisible())
  40653. {
  40654. if (abs (mouseX - (x + ci->width)) <= draggableDistance
  40655. && (ci->propertyFlags & resizable) != 0)
  40656. return ci->id;
  40657. x += ci->width;
  40658. }
  40659. }
  40660. }
  40661. return 0;
  40662. }
  40663. void TableHeaderComponent::updateColumnUnderMouse (int x, int y)
  40664. {
  40665. const int newCol = (reallyContains (x, y, true) && getResizeDraggerAt (x) == 0)
  40666. ? getColumnIdAtX (x) : 0;
  40667. if (newCol != columnIdUnderMouse)
  40668. {
  40669. columnIdUnderMouse = newCol;
  40670. repaint();
  40671. }
  40672. }
  40673. void TableHeaderComponent::showColumnChooserMenu (const int columnIdClicked)
  40674. {
  40675. PopupMenu m;
  40676. addMenuItems (m, columnIdClicked);
  40677. if (m.getNumItems() > 0)
  40678. {
  40679. m.setLookAndFeel (&getLookAndFeel());
  40680. const int result = m.show();
  40681. if (result != 0)
  40682. reactToMenuItem (result, columnIdClicked);
  40683. }
  40684. }
  40685. void TableHeaderListener::tableColumnDraggingChanged (TableHeaderComponent*, int)
  40686. {
  40687. }
  40688. END_JUCE_NAMESPACE
  40689. /*** End of inlined file: juce_TableHeaderComponent.cpp ***/
  40690. /*** Start of inlined file: juce_TableListBox.cpp ***/
  40691. BEGIN_JUCE_NAMESPACE
  40692. static const char* const tableColumnPropertyTag = "_tableColumnID";
  40693. class TableListRowComp : public Component,
  40694. public TooltipClient
  40695. {
  40696. public:
  40697. TableListRowComp (TableListBox& owner_)
  40698. : owner (owner_),
  40699. row (-1),
  40700. isSelected (false)
  40701. {
  40702. }
  40703. ~TableListRowComp()
  40704. {
  40705. deleteAllChildren();
  40706. }
  40707. void paint (Graphics& g)
  40708. {
  40709. TableListBoxModel* const model = owner.getModel();
  40710. if (model != 0)
  40711. {
  40712. const TableHeaderComponent* const header = owner.getHeader();
  40713. model->paintRowBackground (g, row, getWidth(), getHeight(), isSelected);
  40714. const int numColumns = header->getNumColumns (true);
  40715. for (int i = 0; i < numColumns; ++i)
  40716. {
  40717. if (! columnsWithComponents [i])
  40718. {
  40719. const int columnId = header->getColumnIdOfIndex (i, true);
  40720. Rectangle<int> columnRect (header->getColumnPosition (i));
  40721. columnRect.setSize (columnRect.getWidth(), getHeight());
  40722. g.saveState();
  40723. g.reduceClipRegion (columnRect);
  40724. g.setOrigin (columnRect.getX(), 0);
  40725. model->paintCell (g, row, columnId, columnRect.getWidth(), columnRect.getHeight(), isSelected);
  40726. g.restoreState();
  40727. }
  40728. }
  40729. }
  40730. }
  40731. void update (const int newRow, const bool isNowSelected)
  40732. {
  40733. if (newRow != row || isNowSelected != isSelected)
  40734. {
  40735. row = newRow;
  40736. isSelected = isNowSelected;
  40737. repaint();
  40738. }
  40739. if (row < owner.getNumRows())
  40740. {
  40741. jassert (row >= 0);
  40742. const var::identifier tagPropertyName ("_tableLastUseNum");
  40743. const int newTag = Random::getSystemRandom().nextInt();
  40744. const TableHeaderComponent* const header = owner.getHeader();
  40745. const int numColumns = header->getNumColumns (true);
  40746. int i;
  40747. columnsWithComponents.clear();
  40748. if (owner.getModel() != 0)
  40749. {
  40750. for (i = 0; i < numColumns; ++i)
  40751. {
  40752. const int columnId = header->getColumnIdOfIndex (i, true);
  40753. Component* const newComp
  40754. = owner.getModel()->refreshComponentForCell (row, columnId, isSelected,
  40755. findChildComponentForColumn (columnId));
  40756. if (newComp != 0)
  40757. {
  40758. addAndMakeVisible (newComp);
  40759. newComp->getProperties().set (tagPropertyName, newTag);
  40760. newComp->getProperties().set (tableColumnPropertyTag, columnId);
  40761. const Rectangle<int> columnRect (header->getColumnPosition (i));
  40762. newComp->setBounds (columnRect.getX(), 0, columnRect.getWidth(), getHeight());
  40763. columnsWithComponents.setBit (i);
  40764. }
  40765. }
  40766. }
  40767. for (i = getNumChildComponents(); --i >= 0;)
  40768. {
  40769. Component* const c = getChildComponent (i);
  40770. if ((int) c->getProperties() [tagPropertyName] != newTag)
  40771. delete c;
  40772. }
  40773. }
  40774. else
  40775. {
  40776. columnsWithComponents.clear();
  40777. deleteAllChildren();
  40778. }
  40779. }
  40780. void resized()
  40781. {
  40782. for (int i = getNumChildComponents(); --i >= 0;)
  40783. {
  40784. Component* const c = getChildComponent (i);
  40785. const int columnId = c->getProperties() [tableColumnPropertyTag];
  40786. if (columnId != 0)
  40787. {
  40788. const Rectangle<int> columnRect (owner.getHeader()->getColumnPosition (owner.getHeader()->getIndexOfColumnId (columnId, true)));
  40789. c->setBounds (columnRect.getX(), 0, columnRect.getWidth(), getHeight());
  40790. }
  40791. }
  40792. }
  40793. void mouseDown (const MouseEvent& e)
  40794. {
  40795. isDragging = false;
  40796. selectRowOnMouseUp = false;
  40797. if (isEnabled())
  40798. {
  40799. if (! isSelected)
  40800. {
  40801. owner.selectRowsBasedOnModifierKeys (row, e.mods);
  40802. const int columnId = owner.getHeader()->getColumnIdAtX (e.x);
  40803. if (columnId != 0 && owner.getModel() != 0)
  40804. owner.getModel()->cellClicked (row, columnId, e);
  40805. }
  40806. else
  40807. {
  40808. selectRowOnMouseUp = true;
  40809. }
  40810. }
  40811. }
  40812. void mouseDrag (const MouseEvent& e)
  40813. {
  40814. if (isEnabled() && owner.getModel() != 0 && ! (e.mouseWasClicked() || isDragging))
  40815. {
  40816. const SparseSet<int> selectedRows (owner.getSelectedRows());
  40817. if (selectedRows.size() > 0)
  40818. {
  40819. const String dragDescription (owner.getModel()->getDragSourceDescription (selectedRows));
  40820. if (dragDescription.isNotEmpty())
  40821. {
  40822. isDragging = true;
  40823. owner.startDragAndDrop (e, dragDescription);
  40824. }
  40825. }
  40826. }
  40827. }
  40828. void mouseUp (const MouseEvent& e)
  40829. {
  40830. if (selectRowOnMouseUp && e.mouseWasClicked() && isEnabled())
  40831. {
  40832. owner.selectRowsBasedOnModifierKeys (row, e.mods);
  40833. const int columnId = owner.getHeader()->getColumnIdAtX (e.x);
  40834. if (columnId != 0 && owner.getModel() != 0)
  40835. owner.getModel()->cellClicked (row, columnId, e);
  40836. }
  40837. }
  40838. void mouseDoubleClick (const MouseEvent& e)
  40839. {
  40840. const int columnId = owner.getHeader()->getColumnIdAtX (e.x);
  40841. if (columnId != 0 && owner.getModel() != 0)
  40842. owner.getModel()->cellDoubleClicked (row, columnId, e);
  40843. }
  40844. const String getTooltip()
  40845. {
  40846. const int columnId = owner.getHeader()->getColumnIdAtX (getMouseXYRelative().getX());
  40847. if (columnId != 0 && owner.getModel() != 0)
  40848. return owner.getModel()->getCellTooltip (row, columnId);
  40849. return String::empty;
  40850. }
  40851. juce_UseDebuggingNewOperator
  40852. private:
  40853. TableListBox& owner;
  40854. int row;
  40855. bool isSelected, isDragging, selectRowOnMouseUp;
  40856. BigInteger columnsWithComponents;
  40857. Component* findChildComponentForColumn (const int columnId) const
  40858. {
  40859. for (int i = getNumChildComponents(); --i >= 0;)
  40860. {
  40861. Component* const c = getChildComponent (i);
  40862. if ((int) c->getProperties() [tableColumnPropertyTag] == columnId)
  40863. return c;
  40864. }
  40865. return 0;
  40866. }
  40867. TableListRowComp (const TableListRowComp&);
  40868. TableListRowComp& operator= (const TableListRowComp&);
  40869. };
  40870. class TableListBoxHeader : public TableHeaderComponent
  40871. {
  40872. public:
  40873. TableListBoxHeader (TableListBox& owner_)
  40874. : owner (owner_)
  40875. {
  40876. }
  40877. ~TableListBoxHeader()
  40878. {
  40879. }
  40880. void addMenuItems (PopupMenu& menu, int columnIdClicked)
  40881. {
  40882. if (owner.isAutoSizeMenuOptionShown())
  40883. {
  40884. menu.addItem (0xf836743, TRANS("Auto-size this column"), columnIdClicked != 0);
  40885. menu.addItem (0xf836744, TRANS("Auto-size all columns"), owner.getHeader()->getNumColumns (true) > 0);
  40886. menu.addSeparator();
  40887. }
  40888. TableHeaderComponent::addMenuItems (menu, columnIdClicked);
  40889. }
  40890. void reactToMenuItem (int menuReturnId, int columnIdClicked)
  40891. {
  40892. if (menuReturnId == 0xf836743)
  40893. {
  40894. owner.autoSizeColumn (columnIdClicked);
  40895. }
  40896. else if (menuReturnId == 0xf836744)
  40897. {
  40898. owner.autoSizeAllColumns();
  40899. }
  40900. else
  40901. {
  40902. TableHeaderComponent::reactToMenuItem (menuReturnId, columnIdClicked);
  40903. }
  40904. }
  40905. juce_UseDebuggingNewOperator
  40906. private:
  40907. TableListBox& owner;
  40908. TableListBoxHeader (const TableListBoxHeader&);
  40909. TableListBoxHeader& operator= (const TableListBoxHeader&);
  40910. };
  40911. TableListBox::TableListBox (const String& name, TableListBoxModel* const model_)
  40912. : ListBox (name, 0),
  40913. model (model_),
  40914. autoSizeOptionsShown (true)
  40915. {
  40916. ListBox::model = this;
  40917. header = new TableListBoxHeader (*this);
  40918. header->setSize (100, 28);
  40919. header->addListener (this);
  40920. setHeaderComponent (header);
  40921. }
  40922. TableListBox::~TableListBox()
  40923. {
  40924. deleteAllChildren();
  40925. }
  40926. void TableListBox::setModel (TableListBoxModel* const newModel)
  40927. {
  40928. if (model != newModel)
  40929. {
  40930. model = newModel;
  40931. updateContent();
  40932. }
  40933. }
  40934. int TableListBox::getHeaderHeight() const
  40935. {
  40936. return header->getHeight();
  40937. }
  40938. void TableListBox::setHeaderHeight (const int newHeight)
  40939. {
  40940. header->setSize (header->getWidth(), newHeight);
  40941. resized();
  40942. }
  40943. void TableListBox::autoSizeColumn (const int columnId)
  40944. {
  40945. const int width = model != 0 ? model->getColumnAutoSizeWidth (columnId) : 0;
  40946. if (width > 0)
  40947. header->setColumnWidth (columnId, width);
  40948. }
  40949. void TableListBox::autoSizeAllColumns()
  40950. {
  40951. for (int i = 0; i < header->getNumColumns (true); ++i)
  40952. autoSizeColumn (header->getColumnIdOfIndex (i, true));
  40953. }
  40954. void TableListBox::setAutoSizeMenuOptionShown (const bool shouldBeShown)
  40955. {
  40956. autoSizeOptionsShown = shouldBeShown;
  40957. }
  40958. bool TableListBox::isAutoSizeMenuOptionShown() const
  40959. {
  40960. return autoSizeOptionsShown;
  40961. }
  40962. const Rectangle<int> TableListBox::getCellPosition (const int columnId,
  40963. const int rowNumber,
  40964. const bool relativeToComponentTopLeft) const
  40965. {
  40966. Rectangle<int> headerCell (header->getColumnPosition (header->getIndexOfColumnId (columnId, true)));
  40967. if (relativeToComponentTopLeft)
  40968. headerCell.translate (header->getX(), 0);
  40969. const Rectangle<int> row (getRowPosition (rowNumber, relativeToComponentTopLeft));
  40970. return Rectangle<int> (headerCell.getX(), row.getY(),
  40971. headerCell.getWidth(), row.getHeight());
  40972. }
  40973. void TableListBox::scrollToEnsureColumnIsOnscreen (const int columnId)
  40974. {
  40975. ScrollBar* const scrollbar = getHorizontalScrollBar();
  40976. if (scrollbar != 0)
  40977. {
  40978. const Rectangle<int> pos (header->getColumnPosition (header->getIndexOfColumnId (columnId, true)));
  40979. double x = scrollbar->getCurrentRangeStart();
  40980. const double w = scrollbar->getCurrentRangeSize();
  40981. if (pos.getX() < x)
  40982. x = pos.getX();
  40983. else if (pos.getRight() > x + w)
  40984. x += jmax (0.0, pos.getRight() - (x + w));
  40985. scrollbar->setCurrentRangeStart (x);
  40986. }
  40987. }
  40988. int TableListBox::getNumRows()
  40989. {
  40990. return model != 0 ? model->getNumRows() : 0;
  40991. }
  40992. void TableListBox::paintListBoxItem (int, Graphics&, int, int, bool)
  40993. {
  40994. }
  40995. Component* TableListBox::refreshComponentForRow (int rowNumber, bool isRowSelected_, Component* existingComponentToUpdate)
  40996. {
  40997. if (existingComponentToUpdate == 0)
  40998. existingComponentToUpdate = new TableListRowComp (*this);
  40999. static_cast <TableListRowComp*> (existingComponentToUpdate)->update (rowNumber, isRowSelected_);
  41000. return existingComponentToUpdate;
  41001. }
  41002. void TableListBox::selectedRowsChanged (int row)
  41003. {
  41004. if (model != 0)
  41005. model->selectedRowsChanged (row);
  41006. }
  41007. void TableListBox::deleteKeyPressed (int row)
  41008. {
  41009. if (model != 0)
  41010. model->deleteKeyPressed (row);
  41011. }
  41012. void TableListBox::returnKeyPressed (int row)
  41013. {
  41014. if (model != 0)
  41015. model->returnKeyPressed (row);
  41016. }
  41017. void TableListBox::backgroundClicked()
  41018. {
  41019. if (model != 0)
  41020. model->backgroundClicked();
  41021. }
  41022. void TableListBox::listWasScrolled()
  41023. {
  41024. if (model != 0)
  41025. model->listWasScrolled();
  41026. }
  41027. void TableListBox::tableColumnsChanged (TableHeaderComponent*)
  41028. {
  41029. setMinimumContentWidth (header->getTotalWidth());
  41030. repaint();
  41031. updateColumnComponents();
  41032. }
  41033. void TableListBox::tableColumnsResized (TableHeaderComponent*)
  41034. {
  41035. setMinimumContentWidth (header->getTotalWidth());
  41036. repaint();
  41037. updateColumnComponents();
  41038. }
  41039. void TableListBox::tableSortOrderChanged (TableHeaderComponent*)
  41040. {
  41041. if (model != 0)
  41042. model->sortOrderChanged (header->getSortColumnId(),
  41043. header->isSortedForwards());
  41044. }
  41045. void TableListBox::tableColumnDraggingChanged (TableHeaderComponent*, int columnIdNowBeingDragged_)
  41046. {
  41047. columnIdNowBeingDragged = columnIdNowBeingDragged_;
  41048. repaint();
  41049. }
  41050. void TableListBox::resized()
  41051. {
  41052. ListBox::resized();
  41053. header->resizeAllColumnsToFit (getVisibleContentWidth());
  41054. setMinimumContentWidth (header->getTotalWidth());
  41055. }
  41056. void TableListBox::updateColumnComponents() const
  41057. {
  41058. const int firstRow = getRowContainingPosition (0, 0);
  41059. for (int i = firstRow + getNumRowsOnScreen() + 2; --i >= firstRow;)
  41060. {
  41061. TableListRowComp* const rowComp = dynamic_cast <TableListRowComp*> (getComponentForRowNumber (i));
  41062. if (rowComp != 0)
  41063. rowComp->resized();
  41064. }
  41065. }
  41066. void TableListBoxModel::cellClicked (int, int, const MouseEvent&)
  41067. {
  41068. }
  41069. void TableListBoxModel::cellDoubleClicked (int, int, const MouseEvent&)
  41070. {
  41071. }
  41072. void TableListBoxModel::backgroundClicked()
  41073. {
  41074. }
  41075. void TableListBoxModel::sortOrderChanged (int, const bool)
  41076. {
  41077. }
  41078. int TableListBoxModel::getColumnAutoSizeWidth (int)
  41079. {
  41080. return 0;
  41081. }
  41082. void TableListBoxModel::selectedRowsChanged (int)
  41083. {
  41084. }
  41085. void TableListBoxModel::deleteKeyPressed (int)
  41086. {
  41087. }
  41088. void TableListBoxModel::returnKeyPressed (int)
  41089. {
  41090. }
  41091. void TableListBoxModel::listWasScrolled()
  41092. {
  41093. }
  41094. const String TableListBoxModel::getCellTooltip (int /*rowNumber*/, int /*columnId*/)
  41095. {
  41096. return String::empty;
  41097. }
  41098. const String TableListBoxModel::getDragSourceDescription (const SparseSet<int>&)
  41099. {
  41100. return String::empty;
  41101. }
  41102. Component* TableListBoxModel::refreshComponentForCell (int, int, bool, Component* existingComponentToUpdate)
  41103. {
  41104. (void) existingComponentToUpdate;
  41105. jassert (existingComponentToUpdate == 0); // indicates a failure in the code the recycles the components
  41106. return 0;
  41107. }
  41108. END_JUCE_NAMESPACE
  41109. /*** End of inlined file: juce_TableListBox.cpp ***/
  41110. /*** Start of inlined file: juce_TextEditor.cpp ***/
  41111. BEGIN_JUCE_NAMESPACE
  41112. // a word or space that can't be broken down any further
  41113. struct TextAtom
  41114. {
  41115. String atomText;
  41116. float width;
  41117. uint16 numChars;
  41118. bool isWhitespace() const { return CharacterFunctions::isWhitespace (atomText[0]); }
  41119. bool isNewLine() const { return atomText[0] == '\r' || atomText[0] == '\n'; }
  41120. const String getText (const juce_wchar passwordCharacter) const
  41121. {
  41122. if (passwordCharacter == 0)
  41123. return atomText;
  41124. else
  41125. return String::repeatedString (String::charToString (passwordCharacter),
  41126. atomText.length());
  41127. }
  41128. const String getTrimmedText (const juce_wchar passwordCharacter) const
  41129. {
  41130. if (passwordCharacter == 0)
  41131. return atomText.substring (0, numChars);
  41132. else if (isNewLine())
  41133. return String::empty;
  41134. else
  41135. return String::repeatedString (String::charToString (passwordCharacter), numChars);
  41136. }
  41137. };
  41138. // a run of text with a single font and colour
  41139. class TextEditor::UniformTextSection
  41140. {
  41141. public:
  41142. UniformTextSection (const String& text,
  41143. const Font& font_,
  41144. const Colour& colour_,
  41145. const juce_wchar passwordCharacter)
  41146. : font (font_),
  41147. colour (colour_)
  41148. {
  41149. initialiseAtoms (text, passwordCharacter);
  41150. }
  41151. UniformTextSection (const UniformTextSection& other)
  41152. : font (other.font),
  41153. colour (other.colour)
  41154. {
  41155. atoms.ensureStorageAllocated (other.atoms.size());
  41156. for (int i = 0; i < other.atoms.size(); ++i)
  41157. atoms.add (new TextAtom (*other.atoms.getUnchecked(i)));
  41158. }
  41159. ~UniformTextSection()
  41160. {
  41161. // (no need to delete the atoms, as they're explicitly deleted by the caller)
  41162. }
  41163. void clear()
  41164. {
  41165. for (int i = atoms.size(); --i >= 0;)
  41166. delete getAtom(i);
  41167. atoms.clear();
  41168. }
  41169. int getNumAtoms() const
  41170. {
  41171. return atoms.size();
  41172. }
  41173. TextAtom* getAtom (const int index) const throw()
  41174. {
  41175. return atoms.getUnchecked (index);
  41176. }
  41177. void append (const UniformTextSection& other, const juce_wchar passwordCharacter)
  41178. {
  41179. if (other.atoms.size() > 0)
  41180. {
  41181. TextAtom* const lastAtom = atoms.getLast();
  41182. int i = 0;
  41183. if (lastAtom != 0)
  41184. {
  41185. if (! CharacterFunctions::isWhitespace (lastAtom->atomText.getLastCharacter()))
  41186. {
  41187. TextAtom* const first = other.getAtom(0);
  41188. if (! CharacterFunctions::isWhitespace (first->atomText[0]))
  41189. {
  41190. lastAtom->atomText += first->atomText;
  41191. lastAtom->numChars = (uint16) (lastAtom->numChars + first->numChars);
  41192. lastAtom->width = font.getStringWidthFloat (lastAtom->getText (passwordCharacter));
  41193. delete first;
  41194. ++i;
  41195. }
  41196. }
  41197. }
  41198. atoms.ensureStorageAllocated (atoms.size() + other.atoms.size() - i);
  41199. while (i < other.atoms.size())
  41200. {
  41201. atoms.add (other.getAtom(i));
  41202. ++i;
  41203. }
  41204. }
  41205. }
  41206. UniformTextSection* split (const int indexToBreakAt,
  41207. const juce_wchar passwordCharacter)
  41208. {
  41209. UniformTextSection* const section2 = new UniformTextSection (String::empty,
  41210. font, colour,
  41211. passwordCharacter);
  41212. int index = 0;
  41213. for (int i = 0; i < atoms.size(); ++i)
  41214. {
  41215. TextAtom* const atom = getAtom(i);
  41216. const int nextIndex = index + atom->numChars;
  41217. if (index == indexToBreakAt)
  41218. {
  41219. int j;
  41220. for (j = i; j < atoms.size(); ++j)
  41221. section2->atoms.add (getAtom (j));
  41222. for (j = atoms.size(); --j >= i;)
  41223. atoms.remove (j);
  41224. break;
  41225. }
  41226. else if (indexToBreakAt >= index && indexToBreakAt < nextIndex)
  41227. {
  41228. TextAtom* const secondAtom = new TextAtom();
  41229. secondAtom->atomText = atom->atomText.substring (indexToBreakAt - index);
  41230. secondAtom->width = font.getStringWidthFloat (secondAtom->getText (passwordCharacter));
  41231. secondAtom->numChars = (uint16) secondAtom->atomText.length();
  41232. section2->atoms.add (secondAtom);
  41233. atom->atomText = atom->atomText.substring (0, indexToBreakAt - index);
  41234. atom->width = font.getStringWidthFloat (atom->getText (passwordCharacter));
  41235. atom->numChars = (uint16) (indexToBreakAt - index);
  41236. int j;
  41237. for (j = i + 1; j < atoms.size(); ++j)
  41238. section2->atoms.add (getAtom (j));
  41239. for (j = atoms.size(); --j > i;)
  41240. atoms.remove (j);
  41241. break;
  41242. }
  41243. index = nextIndex;
  41244. }
  41245. return section2;
  41246. }
  41247. void appendAllText (String::Concatenator& concatenator) const
  41248. {
  41249. for (int i = 0; i < atoms.size(); ++i)
  41250. concatenator.append (getAtom(i)->atomText);
  41251. }
  41252. void appendSubstring (String::Concatenator& concatenator,
  41253. const Range<int>& range) const
  41254. {
  41255. int index = 0;
  41256. for (int i = 0; i < atoms.size(); ++i)
  41257. {
  41258. const TextAtom* const atom = getAtom (i);
  41259. const int nextIndex = index + atom->numChars;
  41260. if (range.getStart() < nextIndex)
  41261. {
  41262. if (range.getEnd() <= index)
  41263. break;
  41264. const Range<int> r ((range - index).getIntersectionWith (Range<int> (0, (int) atom->numChars)));
  41265. if (! r.isEmpty())
  41266. concatenator.append (atom->atomText.substring (r.getStart(), r.getEnd()));
  41267. }
  41268. index = nextIndex;
  41269. }
  41270. }
  41271. int getTotalLength() const
  41272. {
  41273. int total = 0;
  41274. for (int i = atoms.size(); --i >= 0;)
  41275. total += getAtom(i)->numChars;
  41276. return total;
  41277. }
  41278. void setFont (const Font& newFont,
  41279. const juce_wchar passwordCharacter)
  41280. {
  41281. if (font != newFont)
  41282. {
  41283. font = newFont;
  41284. for (int i = atoms.size(); --i >= 0;)
  41285. {
  41286. TextAtom* const atom = atoms.getUnchecked(i);
  41287. atom->width = newFont.getStringWidthFloat (atom->getText (passwordCharacter));
  41288. }
  41289. }
  41290. }
  41291. juce_UseDebuggingNewOperator
  41292. Font font;
  41293. Colour colour;
  41294. private:
  41295. Array <TextAtom*> atoms;
  41296. void initialiseAtoms (const String& textToParse,
  41297. const juce_wchar passwordCharacter)
  41298. {
  41299. int i = 0;
  41300. const int len = textToParse.length();
  41301. const juce_wchar* const text = textToParse;
  41302. while (i < len)
  41303. {
  41304. int start = i;
  41305. // create a whitespace atom unless it starts with non-ws
  41306. if (CharacterFunctions::isWhitespace (text[i])
  41307. && text[i] != '\r'
  41308. && text[i] != '\n')
  41309. {
  41310. while (i < len
  41311. && CharacterFunctions::isWhitespace (text[i])
  41312. && text[i] != '\r'
  41313. && text[i] != '\n')
  41314. {
  41315. ++i;
  41316. }
  41317. }
  41318. else
  41319. {
  41320. if (text[i] == '\r')
  41321. {
  41322. ++i;
  41323. if ((i < len) && (text[i] == '\n'))
  41324. {
  41325. ++start;
  41326. ++i;
  41327. }
  41328. }
  41329. else if (text[i] == '\n')
  41330. {
  41331. ++i;
  41332. }
  41333. else
  41334. {
  41335. while ((i < len) && ! CharacterFunctions::isWhitespace (text[i]))
  41336. ++i;
  41337. }
  41338. }
  41339. TextAtom* const atom = new TextAtom();
  41340. atom->atomText = String (text + start, i - start);
  41341. atom->width = font.getStringWidthFloat (atom->getText (passwordCharacter));
  41342. atom->numChars = (uint16) (i - start);
  41343. atoms.add (atom);
  41344. }
  41345. }
  41346. UniformTextSection& operator= (const UniformTextSection& other);
  41347. };
  41348. class TextEditor::Iterator
  41349. {
  41350. public:
  41351. Iterator (const Array <UniformTextSection*>& sections_,
  41352. const float wordWrapWidth_,
  41353. const juce_wchar passwordCharacter_)
  41354. : indexInText (0),
  41355. lineY (0),
  41356. lineHeight (0),
  41357. maxDescent (0),
  41358. atomX (0),
  41359. atomRight (0),
  41360. atom (0),
  41361. currentSection (0),
  41362. sections (sections_),
  41363. sectionIndex (0),
  41364. atomIndex (0),
  41365. wordWrapWidth (wordWrapWidth_),
  41366. passwordCharacter (passwordCharacter_)
  41367. {
  41368. jassert (wordWrapWidth_ > 0);
  41369. if (sections.size() > 0)
  41370. {
  41371. currentSection = sections.getUnchecked (sectionIndex);
  41372. if (currentSection != 0)
  41373. beginNewLine();
  41374. }
  41375. }
  41376. Iterator (const Iterator& other)
  41377. : indexInText (other.indexInText),
  41378. lineY (other.lineY),
  41379. lineHeight (other.lineHeight),
  41380. maxDescent (other.maxDescent),
  41381. atomX (other.atomX),
  41382. atomRight (other.atomRight),
  41383. atom (other.atom),
  41384. currentSection (other.currentSection),
  41385. sections (other.sections),
  41386. sectionIndex (other.sectionIndex),
  41387. atomIndex (other.atomIndex),
  41388. wordWrapWidth (other.wordWrapWidth),
  41389. passwordCharacter (other.passwordCharacter),
  41390. tempAtom (other.tempAtom)
  41391. {
  41392. }
  41393. ~Iterator()
  41394. {
  41395. }
  41396. bool next()
  41397. {
  41398. if (atom == &tempAtom)
  41399. {
  41400. const int numRemaining = tempAtom.atomText.length() - tempAtom.numChars;
  41401. if (numRemaining > 0)
  41402. {
  41403. tempAtom.atomText = tempAtom.atomText.substring (tempAtom.numChars);
  41404. atomX = 0;
  41405. if (tempAtom.numChars > 0)
  41406. lineY += lineHeight;
  41407. indexInText += tempAtom.numChars;
  41408. GlyphArrangement g;
  41409. g.addLineOfText (currentSection->font, atom->getText (passwordCharacter), 0.0f, 0.0f);
  41410. int split;
  41411. for (split = 0; split < g.getNumGlyphs(); ++split)
  41412. if (shouldWrap (g.getGlyph (split).getRight()))
  41413. break;
  41414. if (split > 0 && split <= numRemaining)
  41415. {
  41416. tempAtom.numChars = (uint16) split;
  41417. tempAtom.width = g.getGlyph (split - 1).getRight();
  41418. atomRight = atomX + tempAtom.width;
  41419. return true;
  41420. }
  41421. }
  41422. }
  41423. bool forceNewLine = false;
  41424. if (sectionIndex >= sections.size())
  41425. {
  41426. moveToEndOfLastAtom();
  41427. return false;
  41428. }
  41429. else if (atomIndex >= currentSection->getNumAtoms() - 1)
  41430. {
  41431. if (atomIndex >= currentSection->getNumAtoms())
  41432. {
  41433. if (++sectionIndex >= sections.size())
  41434. {
  41435. moveToEndOfLastAtom();
  41436. return false;
  41437. }
  41438. atomIndex = 0;
  41439. currentSection = sections.getUnchecked (sectionIndex);
  41440. }
  41441. else
  41442. {
  41443. const TextAtom* const lastAtom = currentSection->getAtom (atomIndex);
  41444. if (! lastAtom->isWhitespace())
  41445. {
  41446. // handle the case where the last atom in a section is actually part of the same
  41447. // word as the first atom of the next section...
  41448. float right = atomRight + lastAtom->width;
  41449. float lineHeight2 = lineHeight;
  41450. float maxDescent2 = maxDescent;
  41451. for (int section = sectionIndex + 1; section < sections.size(); ++section)
  41452. {
  41453. const UniformTextSection* const s = sections.getUnchecked (section);
  41454. if (s->getNumAtoms() == 0)
  41455. break;
  41456. const TextAtom* const nextAtom = s->getAtom (0);
  41457. if (nextAtom->isWhitespace())
  41458. break;
  41459. right += nextAtom->width;
  41460. lineHeight2 = jmax (lineHeight2, s->font.getHeight());
  41461. maxDescent2 = jmax (maxDescent2, s->font.getDescent());
  41462. if (shouldWrap (right))
  41463. {
  41464. lineHeight = lineHeight2;
  41465. maxDescent = maxDescent2;
  41466. forceNewLine = true;
  41467. break;
  41468. }
  41469. if (s->getNumAtoms() > 1)
  41470. break;
  41471. }
  41472. }
  41473. }
  41474. }
  41475. if (atom != 0)
  41476. {
  41477. atomX = atomRight;
  41478. indexInText += atom->numChars;
  41479. if (atom->isNewLine())
  41480. beginNewLine();
  41481. }
  41482. atom = currentSection->getAtom (atomIndex);
  41483. atomRight = atomX + atom->width;
  41484. ++atomIndex;
  41485. if (shouldWrap (atomRight) || forceNewLine)
  41486. {
  41487. if (atom->isWhitespace())
  41488. {
  41489. // leave whitespace at the end of a line, but truncate it to avoid scrolling
  41490. atomRight = jmin (atomRight, wordWrapWidth);
  41491. }
  41492. else
  41493. {
  41494. atomRight = atom->width;
  41495. if (shouldWrap (atomRight)) // atom too big to fit on a line, so break it up..
  41496. {
  41497. tempAtom = *atom;
  41498. tempAtom.width = 0;
  41499. tempAtom.numChars = 0;
  41500. atom = &tempAtom;
  41501. if (atomX > 0)
  41502. beginNewLine();
  41503. return next();
  41504. }
  41505. beginNewLine();
  41506. return true;
  41507. }
  41508. }
  41509. return true;
  41510. }
  41511. void beginNewLine()
  41512. {
  41513. atomX = 0;
  41514. lineY += lineHeight;
  41515. int tempSectionIndex = sectionIndex;
  41516. int tempAtomIndex = atomIndex;
  41517. const UniformTextSection* section = sections.getUnchecked (tempSectionIndex);
  41518. lineHeight = section->font.getHeight();
  41519. maxDescent = section->font.getDescent();
  41520. float x = (atom != 0) ? atom->width : 0;
  41521. while (! shouldWrap (x))
  41522. {
  41523. if (tempSectionIndex >= sections.size())
  41524. break;
  41525. bool checkSize = false;
  41526. if (tempAtomIndex >= section->getNumAtoms())
  41527. {
  41528. if (++tempSectionIndex >= sections.size())
  41529. break;
  41530. tempAtomIndex = 0;
  41531. section = sections.getUnchecked (tempSectionIndex);
  41532. checkSize = true;
  41533. }
  41534. const TextAtom* const nextAtom = section->getAtom (tempAtomIndex);
  41535. if (nextAtom == 0)
  41536. break;
  41537. x += nextAtom->width;
  41538. if (shouldWrap (x) || nextAtom->isNewLine())
  41539. break;
  41540. if (checkSize)
  41541. {
  41542. lineHeight = jmax (lineHeight, section->font.getHeight());
  41543. maxDescent = jmax (maxDescent, section->font.getDescent());
  41544. }
  41545. ++tempAtomIndex;
  41546. }
  41547. }
  41548. void draw (Graphics& g, const UniformTextSection*& lastSection) const
  41549. {
  41550. if (passwordCharacter != 0 || ! atom->isWhitespace())
  41551. {
  41552. if (lastSection != currentSection)
  41553. {
  41554. lastSection = currentSection;
  41555. g.setColour (currentSection->colour);
  41556. g.setFont (currentSection->font);
  41557. }
  41558. jassert (atom->getTrimmedText (passwordCharacter).isNotEmpty());
  41559. GlyphArrangement ga;
  41560. ga.addLineOfText (currentSection->font,
  41561. atom->getTrimmedText (passwordCharacter),
  41562. atomX,
  41563. (float) roundToInt (lineY + lineHeight - maxDescent));
  41564. ga.draw (g);
  41565. }
  41566. }
  41567. void drawSelection (Graphics& g,
  41568. const Range<int>& selection) const
  41569. {
  41570. const int startX = roundToInt (indexToX (selection.getStart()));
  41571. const int endX = roundToInt (indexToX (selection.getEnd()));
  41572. const int y = roundToInt (lineY);
  41573. const int nextY = roundToInt (lineY + lineHeight);
  41574. g.fillRect (startX, y, endX - startX, nextY - y);
  41575. }
  41576. void drawSelectedText (Graphics& g,
  41577. const Range<int>& selection,
  41578. const Colour& selectedTextColour) const
  41579. {
  41580. if (passwordCharacter != 0 || ! atom->isWhitespace())
  41581. {
  41582. GlyphArrangement ga;
  41583. ga.addLineOfText (currentSection->font,
  41584. atom->getTrimmedText (passwordCharacter),
  41585. atomX,
  41586. (float) roundToInt (lineY + lineHeight - maxDescent));
  41587. if (selection.getEnd() < indexInText + atom->numChars)
  41588. {
  41589. GlyphArrangement ga2 (ga);
  41590. ga2.removeRangeOfGlyphs (0, selection.getEnd() - indexInText);
  41591. ga.removeRangeOfGlyphs (selection.getEnd() - indexInText, -1);
  41592. g.setColour (currentSection->colour);
  41593. ga2.draw (g);
  41594. }
  41595. if (selection.getStart() > indexInText)
  41596. {
  41597. GlyphArrangement ga2 (ga);
  41598. ga2.removeRangeOfGlyphs (selection.getStart() - indexInText, -1);
  41599. ga.removeRangeOfGlyphs (0, selection.getStart() - indexInText);
  41600. g.setColour (currentSection->colour);
  41601. ga2.draw (g);
  41602. }
  41603. g.setColour (selectedTextColour);
  41604. ga.draw (g);
  41605. }
  41606. }
  41607. float indexToX (const int indexToFind) const
  41608. {
  41609. if (indexToFind <= indexInText)
  41610. return atomX;
  41611. if (indexToFind >= indexInText + atom->numChars)
  41612. return atomRight;
  41613. GlyphArrangement g;
  41614. g.addLineOfText (currentSection->font,
  41615. atom->getText (passwordCharacter),
  41616. atomX, 0.0f);
  41617. if (indexToFind - indexInText >= g.getNumGlyphs())
  41618. return atomRight;
  41619. return jmin (atomRight, g.getGlyph (indexToFind - indexInText).getLeft());
  41620. }
  41621. int xToIndex (const float xToFind) const
  41622. {
  41623. if (xToFind <= atomX || atom->isNewLine())
  41624. return indexInText;
  41625. if (xToFind >= atomRight)
  41626. return indexInText + atom->numChars;
  41627. GlyphArrangement g;
  41628. g.addLineOfText (currentSection->font,
  41629. atom->getText (passwordCharacter),
  41630. atomX, 0.0f);
  41631. int j;
  41632. for (j = 0; j < g.getNumGlyphs(); ++j)
  41633. if ((g.getGlyph(j).getLeft() + g.getGlyph(j).getRight()) / 2 > xToFind)
  41634. break;
  41635. return indexInText + j;
  41636. }
  41637. bool getCharPosition (const int index, float& cx, float& cy, float& lineHeight_)
  41638. {
  41639. while (next())
  41640. {
  41641. if (indexInText + atom->numChars > index)
  41642. {
  41643. cx = indexToX (index);
  41644. cy = lineY;
  41645. lineHeight_ = lineHeight;
  41646. return true;
  41647. }
  41648. }
  41649. cx = atomX;
  41650. cy = lineY;
  41651. lineHeight_ = lineHeight;
  41652. return false;
  41653. }
  41654. juce_UseDebuggingNewOperator
  41655. int indexInText;
  41656. float lineY, lineHeight, maxDescent;
  41657. float atomX, atomRight;
  41658. const TextAtom* atom;
  41659. const UniformTextSection* currentSection;
  41660. private:
  41661. const Array <UniformTextSection*>& sections;
  41662. int sectionIndex, atomIndex;
  41663. const float wordWrapWidth;
  41664. const juce_wchar passwordCharacter;
  41665. TextAtom tempAtom;
  41666. Iterator& operator= (const Iterator&);
  41667. void moveToEndOfLastAtom()
  41668. {
  41669. if (atom != 0)
  41670. {
  41671. atomX = atomRight;
  41672. if (atom->isNewLine())
  41673. {
  41674. atomX = 0.0f;
  41675. lineY += lineHeight;
  41676. }
  41677. }
  41678. }
  41679. bool shouldWrap (const float x) const
  41680. {
  41681. return (x - 0.0001f) >= wordWrapWidth;
  41682. }
  41683. };
  41684. class TextEditor::InsertAction : public UndoableAction
  41685. {
  41686. TextEditor& owner;
  41687. const String text;
  41688. const int insertIndex, oldCaretPos, newCaretPos;
  41689. const Font font;
  41690. const Colour colour;
  41691. InsertAction (const InsertAction&);
  41692. InsertAction& operator= (const InsertAction&);
  41693. public:
  41694. InsertAction (TextEditor& owner_,
  41695. const String& text_,
  41696. const int insertIndex_,
  41697. const Font& font_,
  41698. const Colour& colour_,
  41699. const int oldCaretPos_,
  41700. const int newCaretPos_)
  41701. : owner (owner_),
  41702. text (text_),
  41703. insertIndex (insertIndex_),
  41704. oldCaretPos (oldCaretPos_),
  41705. newCaretPos (newCaretPos_),
  41706. font (font_),
  41707. colour (colour_)
  41708. {
  41709. }
  41710. ~InsertAction()
  41711. {
  41712. }
  41713. bool perform()
  41714. {
  41715. owner.insert (text, insertIndex, font, colour, 0, newCaretPos);
  41716. return true;
  41717. }
  41718. bool undo()
  41719. {
  41720. owner.remove (Range<int> (insertIndex, insertIndex + text.length()), 0, oldCaretPos);
  41721. return true;
  41722. }
  41723. int getSizeInUnits()
  41724. {
  41725. return text.length() + 16;
  41726. }
  41727. };
  41728. class TextEditor::RemoveAction : public UndoableAction
  41729. {
  41730. TextEditor& owner;
  41731. const Range<int> range;
  41732. const int oldCaretPos, newCaretPos;
  41733. Array <UniformTextSection*> removedSections;
  41734. RemoveAction (const RemoveAction&);
  41735. RemoveAction& operator= (const RemoveAction&);
  41736. public:
  41737. RemoveAction (TextEditor& owner_,
  41738. const Range<int> range_,
  41739. const int oldCaretPos_,
  41740. const int newCaretPos_,
  41741. const Array <UniformTextSection*>& removedSections_)
  41742. : owner (owner_),
  41743. range (range_),
  41744. oldCaretPos (oldCaretPos_),
  41745. newCaretPos (newCaretPos_),
  41746. removedSections (removedSections_)
  41747. {
  41748. }
  41749. ~RemoveAction()
  41750. {
  41751. for (int i = removedSections.size(); --i >= 0;)
  41752. {
  41753. UniformTextSection* const section = removedSections.getUnchecked (i);
  41754. section->clear();
  41755. delete section;
  41756. }
  41757. }
  41758. bool perform()
  41759. {
  41760. owner.remove (range, 0, newCaretPos);
  41761. return true;
  41762. }
  41763. bool undo()
  41764. {
  41765. owner.reinsert (range.getStart(), removedSections);
  41766. owner.moveCursorTo (oldCaretPos, false);
  41767. return true;
  41768. }
  41769. int getSizeInUnits()
  41770. {
  41771. int n = 0;
  41772. for (int i = removedSections.size(); --i >= 0;)
  41773. n += removedSections.getUnchecked (i)->getTotalLength();
  41774. return n + 16;
  41775. }
  41776. };
  41777. class TextEditor::TextHolderComponent : public Component,
  41778. public Timer,
  41779. public Value::Listener
  41780. {
  41781. public:
  41782. TextHolderComponent (TextEditor& owner_)
  41783. : owner (owner_)
  41784. {
  41785. setWantsKeyboardFocus (false);
  41786. setInterceptsMouseClicks (false, true);
  41787. owner.getTextValue().addListener (this);
  41788. }
  41789. ~TextHolderComponent()
  41790. {
  41791. owner.getTextValue().removeListener (this);
  41792. }
  41793. void paint (Graphics& g)
  41794. {
  41795. owner.drawContent (g);
  41796. }
  41797. void timerCallback()
  41798. {
  41799. owner.timerCallbackInt();
  41800. }
  41801. const MouseCursor getMouseCursor()
  41802. {
  41803. return owner.getMouseCursor();
  41804. }
  41805. void valueChanged (Value&)
  41806. {
  41807. owner.textWasChangedByValue();
  41808. }
  41809. private:
  41810. TextEditor& owner;
  41811. TextHolderComponent (const TextHolderComponent&);
  41812. TextHolderComponent& operator= (const TextHolderComponent&);
  41813. };
  41814. class TextEditorViewport : public Viewport
  41815. {
  41816. public:
  41817. TextEditorViewport (TextEditor* const owner_)
  41818. : owner (owner_),
  41819. lastWordWrapWidth (0)
  41820. {
  41821. }
  41822. ~TextEditorViewport()
  41823. {
  41824. }
  41825. void visibleAreaChanged (int, int, int, int)
  41826. {
  41827. const float wordWrapWidth = owner->getWordWrapWidth();
  41828. if (wordWrapWidth != lastWordWrapWidth)
  41829. {
  41830. lastWordWrapWidth = wordWrapWidth;
  41831. owner->updateTextHolderSize();
  41832. }
  41833. }
  41834. private:
  41835. TextEditor* const owner;
  41836. float lastWordWrapWidth;
  41837. TextEditorViewport (const TextEditorViewport&);
  41838. TextEditorViewport& operator= (const TextEditorViewport&);
  41839. };
  41840. namespace TextEditorDefs
  41841. {
  41842. const int flashSpeedIntervalMs = 380;
  41843. const int textChangeMessageId = 0x10003001;
  41844. const int returnKeyMessageId = 0x10003002;
  41845. const int escapeKeyMessageId = 0x10003003;
  41846. const int focusLossMessageId = 0x10003004;
  41847. const int maxActionsPerTransaction = 100;
  41848. }
  41849. TextEditor::TextEditor (const String& name,
  41850. const juce_wchar passwordCharacter_)
  41851. : Component (name),
  41852. borderSize (1, 1, 1, 3),
  41853. readOnly (false),
  41854. multiline (false),
  41855. wordWrap (false),
  41856. returnKeyStartsNewLine (false),
  41857. caretVisible (true),
  41858. popupMenuEnabled (true),
  41859. selectAllTextWhenFocused (false),
  41860. scrollbarVisible (true),
  41861. wasFocused (false),
  41862. caretFlashState (true),
  41863. keepCursorOnScreen (true),
  41864. tabKeyUsed (false),
  41865. menuActive (false),
  41866. valueTextNeedsUpdating (false),
  41867. cursorX (0),
  41868. cursorY (0),
  41869. cursorHeight (0),
  41870. maxTextLength (0),
  41871. leftIndent (4),
  41872. topIndent (4),
  41873. lastTransactionTime (0),
  41874. currentFont (14.0f),
  41875. totalNumChars (0),
  41876. caretPosition (0),
  41877. passwordCharacter (passwordCharacter_),
  41878. dragType (notDragging)
  41879. {
  41880. setOpaque (true);
  41881. addAndMakeVisible (viewport = new TextEditorViewport (this));
  41882. viewport->setViewedComponent (textHolder = new TextHolderComponent (*this));
  41883. viewport->setWantsKeyboardFocus (false);
  41884. viewport->setScrollBarsShown (false, false);
  41885. setMouseCursor (MouseCursor::IBeamCursor);
  41886. setWantsKeyboardFocus (true);
  41887. }
  41888. TextEditor::~TextEditor()
  41889. {
  41890. textValue.referTo (Value());
  41891. clearInternal (0);
  41892. viewport = 0;
  41893. textHolder = 0;
  41894. }
  41895. void TextEditor::newTransaction()
  41896. {
  41897. lastTransactionTime = Time::getApproximateMillisecondCounter();
  41898. undoManager.beginNewTransaction();
  41899. }
  41900. void TextEditor::doUndoRedo (const bool isRedo)
  41901. {
  41902. if (! isReadOnly())
  41903. {
  41904. if (isRedo ? undoManager.redo()
  41905. : undoManager.undo())
  41906. {
  41907. scrollToMakeSureCursorIsVisible();
  41908. repaint();
  41909. textChanged();
  41910. }
  41911. }
  41912. }
  41913. void TextEditor::setMultiLine (const bool shouldBeMultiLine,
  41914. const bool shouldWordWrap)
  41915. {
  41916. multiline = shouldBeMultiLine;
  41917. wordWrap = shouldWordWrap && shouldBeMultiLine;
  41918. setScrollbarsShown (scrollbarVisible);
  41919. viewport->setViewPosition (0, 0);
  41920. resized();
  41921. scrollToMakeSureCursorIsVisible();
  41922. }
  41923. bool TextEditor::isMultiLine() const
  41924. {
  41925. return multiline;
  41926. }
  41927. void TextEditor::setScrollbarsShown (bool enabled)
  41928. {
  41929. scrollbarVisible = enabled;
  41930. enabled = enabled && isMultiLine();
  41931. viewport->setScrollBarsShown (enabled, enabled);
  41932. }
  41933. void TextEditor::setReadOnly (const bool shouldBeReadOnly)
  41934. {
  41935. readOnly = shouldBeReadOnly;
  41936. enablementChanged();
  41937. }
  41938. bool TextEditor::isReadOnly() const
  41939. {
  41940. return readOnly || ! isEnabled();
  41941. }
  41942. bool TextEditor::isTextInputActive() const
  41943. {
  41944. return ! isReadOnly();
  41945. }
  41946. void TextEditor::setReturnKeyStartsNewLine (const bool shouldStartNewLine)
  41947. {
  41948. returnKeyStartsNewLine = shouldStartNewLine;
  41949. }
  41950. void TextEditor::setTabKeyUsedAsCharacter (const bool shouldTabKeyBeUsed)
  41951. {
  41952. tabKeyUsed = shouldTabKeyBeUsed;
  41953. }
  41954. void TextEditor::setPopupMenuEnabled (const bool b)
  41955. {
  41956. popupMenuEnabled = b;
  41957. }
  41958. void TextEditor::setSelectAllWhenFocused (const bool b)
  41959. {
  41960. selectAllTextWhenFocused = b;
  41961. }
  41962. const Font TextEditor::getFont() const
  41963. {
  41964. return currentFont;
  41965. }
  41966. void TextEditor::setFont (const Font& newFont)
  41967. {
  41968. currentFont = newFont;
  41969. scrollToMakeSureCursorIsVisible();
  41970. }
  41971. void TextEditor::applyFontToAllText (const Font& newFont)
  41972. {
  41973. currentFont = newFont;
  41974. const Colour overallColour (findColour (textColourId));
  41975. for (int i = sections.size(); --i >= 0;)
  41976. {
  41977. UniformTextSection* const uts = sections.getUnchecked (i);
  41978. uts->setFont (newFont, passwordCharacter);
  41979. uts->colour = overallColour;
  41980. }
  41981. coalesceSimilarSections();
  41982. updateTextHolderSize();
  41983. scrollToMakeSureCursorIsVisible();
  41984. repaint();
  41985. }
  41986. void TextEditor::colourChanged()
  41987. {
  41988. setOpaque (findColour (backgroundColourId).isOpaque());
  41989. repaint();
  41990. }
  41991. void TextEditor::setCaretVisible (const bool shouldCaretBeVisible)
  41992. {
  41993. caretVisible = shouldCaretBeVisible;
  41994. if (shouldCaretBeVisible)
  41995. textHolder->startTimer (TextEditorDefs::flashSpeedIntervalMs);
  41996. setMouseCursor (shouldCaretBeVisible ? MouseCursor::IBeamCursor
  41997. : MouseCursor::NormalCursor);
  41998. }
  41999. void TextEditor::setInputRestrictions (const int maxLen,
  42000. const String& chars)
  42001. {
  42002. maxTextLength = jmax (0, maxLen);
  42003. allowedCharacters = chars;
  42004. }
  42005. void TextEditor::setTextToShowWhenEmpty (const String& text, const Colour& colourToUse)
  42006. {
  42007. textToShowWhenEmpty = text;
  42008. colourForTextWhenEmpty = colourToUse;
  42009. }
  42010. void TextEditor::setPasswordCharacter (const juce_wchar newPasswordCharacter)
  42011. {
  42012. if (passwordCharacter != newPasswordCharacter)
  42013. {
  42014. passwordCharacter = newPasswordCharacter;
  42015. resized();
  42016. repaint();
  42017. }
  42018. }
  42019. void TextEditor::setScrollBarThickness (const int newThicknessPixels)
  42020. {
  42021. viewport->setScrollBarThickness (newThicknessPixels);
  42022. }
  42023. void TextEditor::setScrollBarButtonVisibility (const bool buttonsVisible)
  42024. {
  42025. viewport->setScrollBarButtonVisibility (buttonsVisible);
  42026. }
  42027. void TextEditor::clear()
  42028. {
  42029. clearInternal (0);
  42030. updateTextHolderSize();
  42031. undoManager.clearUndoHistory();
  42032. }
  42033. void TextEditor::setText (const String& newText,
  42034. const bool sendTextChangeMessage)
  42035. {
  42036. const int newLength = newText.length();
  42037. if (newLength != getTotalNumChars() || getText() != newText)
  42038. {
  42039. const int oldCursorPos = caretPosition;
  42040. const bool cursorWasAtEnd = oldCursorPos >= getTotalNumChars();
  42041. clearInternal (0);
  42042. insert (newText, 0, currentFont, findColour (textColourId), 0, caretPosition);
  42043. // if you're adding text with line-feeds to a single-line text editor, it
  42044. // ain't gonna look right!
  42045. jassert (multiline || ! newText.containsAnyOf ("\r\n"));
  42046. if (cursorWasAtEnd && ! isMultiLine())
  42047. moveCursorTo (getTotalNumChars(), false);
  42048. else
  42049. moveCursorTo (oldCursorPos, false);
  42050. if (sendTextChangeMessage)
  42051. textChanged();
  42052. repaint();
  42053. }
  42054. updateTextHolderSize();
  42055. scrollToMakeSureCursorIsVisible();
  42056. undoManager.clearUndoHistory();
  42057. }
  42058. Value& TextEditor::getTextValue()
  42059. {
  42060. if (valueTextNeedsUpdating)
  42061. {
  42062. valueTextNeedsUpdating = false;
  42063. textValue = getText();
  42064. }
  42065. return textValue;
  42066. }
  42067. void TextEditor::textWasChangedByValue()
  42068. {
  42069. if (textValue.getValueSource().getReferenceCount() > 1)
  42070. setText (textValue.getValue());
  42071. }
  42072. void TextEditor::textChanged()
  42073. {
  42074. updateTextHolderSize();
  42075. postCommandMessage (TextEditorDefs::textChangeMessageId);
  42076. if (textValue.getValueSource().getReferenceCount() > 1)
  42077. {
  42078. valueTextNeedsUpdating = false;
  42079. textValue = getText();
  42080. }
  42081. }
  42082. void TextEditor::returnPressed()
  42083. {
  42084. postCommandMessage (TextEditorDefs::returnKeyMessageId);
  42085. }
  42086. void TextEditor::escapePressed()
  42087. {
  42088. postCommandMessage (TextEditorDefs::escapeKeyMessageId);
  42089. }
  42090. void TextEditor::addListener (TextEditorListener* const newListener)
  42091. {
  42092. listeners.add (newListener);
  42093. }
  42094. void TextEditor::removeListener (TextEditorListener* const listenerToRemove)
  42095. {
  42096. listeners.remove (listenerToRemove);
  42097. }
  42098. void TextEditor::timerCallbackInt()
  42099. {
  42100. const bool newState = (! caretFlashState) && ! isCurrentlyBlockedByAnotherModalComponent();
  42101. if (caretFlashState != newState)
  42102. {
  42103. caretFlashState = newState;
  42104. if (caretFlashState)
  42105. wasFocused = true;
  42106. if (caretVisible
  42107. && hasKeyboardFocus (false)
  42108. && ! isReadOnly())
  42109. {
  42110. repaintCaret();
  42111. }
  42112. }
  42113. const unsigned int now = Time::getApproximateMillisecondCounter();
  42114. if (now > lastTransactionTime + 200)
  42115. newTransaction();
  42116. }
  42117. void TextEditor::repaintCaret()
  42118. {
  42119. if (! findColour (caretColourId).isTransparent())
  42120. repaint (borderSize.getLeft() + textHolder->getX() + leftIndent + roundToInt (cursorX) - 1,
  42121. borderSize.getTop() + textHolder->getY() + topIndent + roundToInt (cursorY) - 1,
  42122. 4,
  42123. roundToInt (cursorHeight) + 2);
  42124. }
  42125. void TextEditor::repaintText (const Range<int>& range)
  42126. {
  42127. if (! range.isEmpty())
  42128. {
  42129. float x = 0, y = 0, lh = currentFont.getHeight();
  42130. const float wordWrapWidth = getWordWrapWidth();
  42131. if (wordWrapWidth > 0)
  42132. {
  42133. Iterator i (sections, wordWrapWidth, passwordCharacter);
  42134. i.getCharPosition (range.getStart(), x, y, lh);
  42135. const int y1 = (int) y;
  42136. int y2;
  42137. if (range.getEnd() >= getTotalNumChars())
  42138. {
  42139. y2 = textHolder->getHeight();
  42140. }
  42141. else
  42142. {
  42143. i.getCharPosition (range.getEnd(), x, y, lh);
  42144. y2 = (int) (y + lh * 2.0f);
  42145. }
  42146. textHolder->repaint (0, y1, textHolder->getWidth(), y2 - y1);
  42147. }
  42148. }
  42149. }
  42150. void TextEditor::moveCaret (int newCaretPos)
  42151. {
  42152. if (newCaretPos < 0)
  42153. newCaretPos = 0;
  42154. else if (newCaretPos > getTotalNumChars())
  42155. newCaretPos = getTotalNumChars();
  42156. if (newCaretPos != getCaretPosition())
  42157. {
  42158. repaintCaret();
  42159. caretFlashState = true;
  42160. caretPosition = newCaretPos;
  42161. textHolder->startTimer (TextEditorDefs::flashSpeedIntervalMs);
  42162. scrollToMakeSureCursorIsVisible();
  42163. repaintCaret();
  42164. }
  42165. }
  42166. void TextEditor::setCaretPosition (const int newIndex)
  42167. {
  42168. moveCursorTo (newIndex, false);
  42169. }
  42170. int TextEditor::getCaretPosition() const
  42171. {
  42172. return caretPosition;
  42173. }
  42174. void TextEditor::scrollEditorToPositionCaret (const int desiredCaretX,
  42175. const int desiredCaretY)
  42176. {
  42177. updateCaretPosition();
  42178. int vx = roundToInt (cursorX) - desiredCaretX;
  42179. int vy = roundToInt (cursorY) - desiredCaretY;
  42180. if (desiredCaretX < jmax (1, proportionOfWidth (0.05f)))
  42181. {
  42182. vx += desiredCaretX - proportionOfWidth (0.2f);
  42183. }
  42184. else if (desiredCaretX > jmax (0, viewport->getMaximumVisibleWidth() - (wordWrap ? 2 : 10)))
  42185. {
  42186. vx += desiredCaretX + (isMultiLine() ? proportionOfWidth (0.2f) : 10) - viewport->getMaximumVisibleWidth();
  42187. }
  42188. vx = jlimit (0, jmax (0, textHolder->getWidth() + 8 - viewport->getMaximumVisibleWidth()), vx);
  42189. if (! isMultiLine())
  42190. {
  42191. vy = viewport->getViewPositionY();
  42192. }
  42193. else
  42194. {
  42195. vy = jlimit (0, jmax (0, textHolder->getHeight() - viewport->getMaximumVisibleHeight()), vy);
  42196. const int curH = roundToInt (cursorHeight);
  42197. if (desiredCaretY < 0)
  42198. {
  42199. vy = jmax (0, desiredCaretY + vy);
  42200. }
  42201. else if (desiredCaretY > jmax (0, viewport->getMaximumVisibleHeight() - topIndent - curH))
  42202. {
  42203. vy += desiredCaretY + 2 + curH + topIndent - viewport->getMaximumVisibleHeight();
  42204. }
  42205. }
  42206. viewport->setViewPosition (vx, vy);
  42207. }
  42208. const Rectangle<int> TextEditor::getCaretRectangle()
  42209. {
  42210. updateCaretPosition();
  42211. return Rectangle<int> (roundToInt (cursorX) - viewport->getX(),
  42212. roundToInt (cursorY) - viewport->getY(),
  42213. 1, roundToInt (cursorHeight));
  42214. }
  42215. float TextEditor::getWordWrapWidth() const
  42216. {
  42217. return (wordWrap) ? (float) (viewport->getMaximumVisibleWidth() - leftIndent - leftIndent / 2)
  42218. : 1.0e10f;
  42219. }
  42220. void TextEditor::updateTextHolderSize()
  42221. {
  42222. const float wordWrapWidth = getWordWrapWidth();
  42223. if (wordWrapWidth > 0)
  42224. {
  42225. float maxWidth = 0.0f;
  42226. Iterator i (sections, wordWrapWidth, passwordCharacter);
  42227. while (i.next())
  42228. maxWidth = jmax (maxWidth, i.atomRight);
  42229. const int w = leftIndent + roundToInt (maxWidth);
  42230. const int h = topIndent + roundToInt (jmax (i.lineY + i.lineHeight,
  42231. currentFont.getHeight()));
  42232. textHolder->setSize (w + 1, h + 1);
  42233. }
  42234. }
  42235. int TextEditor::getTextWidth() const
  42236. {
  42237. return textHolder->getWidth();
  42238. }
  42239. int TextEditor::getTextHeight() const
  42240. {
  42241. return textHolder->getHeight();
  42242. }
  42243. void TextEditor::setIndents (const int newLeftIndent,
  42244. const int newTopIndent)
  42245. {
  42246. leftIndent = newLeftIndent;
  42247. topIndent = newTopIndent;
  42248. }
  42249. void TextEditor::setBorder (const BorderSize& border)
  42250. {
  42251. borderSize = border;
  42252. resized();
  42253. }
  42254. const BorderSize TextEditor::getBorder() const
  42255. {
  42256. return borderSize;
  42257. }
  42258. void TextEditor::setScrollToShowCursor (const bool shouldScrollToShowCursor)
  42259. {
  42260. keepCursorOnScreen = shouldScrollToShowCursor;
  42261. }
  42262. void TextEditor::updateCaretPosition()
  42263. {
  42264. cursorHeight = currentFont.getHeight(); // (in case the text is empty and the call below doesn't set this value)
  42265. getCharPosition (caretPosition, cursorX, cursorY, cursorHeight);
  42266. }
  42267. void TextEditor::scrollToMakeSureCursorIsVisible()
  42268. {
  42269. updateCaretPosition();
  42270. if (keepCursorOnScreen)
  42271. {
  42272. int x = viewport->getViewPositionX();
  42273. int y = viewport->getViewPositionY();
  42274. const int relativeCursorX = roundToInt (cursorX) - x;
  42275. const int relativeCursorY = roundToInt (cursorY) - y;
  42276. if (relativeCursorX < jmax (1, proportionOfWidth (0.05f)))
  42277. {
  42278. x += relativeCursorX - proportionOfWidth (0.2f);
  42279. }
  42280. else if (relativeCursorX > jmax (0, viewport->getMaximumVisibleWidth() - (wordWrap ? 2 : 10)))
  42281. {
  42282. x += relativeCursorX + (isMultiLine() ? proportionOfWidth (0.2f) : 10) - viewport->getMaximumVisibleWidth();
  42283. }
  42284. x = jlimit (0, jmax (0, textHolder->getWidth() + 8 - viewport->getMaximumVisibleWidth()), x);
  42285. if (! isMultiLine())
  42286. {
  42287. y = (getHeight() - textHolder->getHeight() - topIndent) / -2;
  42288. }
  42289. else
  42290. {
  42291. const int curH = roundToInt (cursorHeight);
  42292. if (relativeCursorY < 0)
  42293. {
  42294. y = jmax (0, relativeCursorY + y);
  42295. }
  42296. else if (relativeCursorY > jmax (0, viewport->getMaximumVisibleHeight() - topIndent - curH))
  42297. {
  42298. y += relativeCursorY + 2 + curH + topIndent - viewport->getMaximumVisibleHeight();
  42299. }
  42300. }
  42301. viewport->setViewPosition (x, y);
  42302. }
  42303. }
  42304. void TextEditor::moveCursorTo (const int newPosition,
  42305. const bool isSelecting)
  42306. {
  42307. if (isSelecting)
  42308. {
  42309. moveCaret (newPosition);
  42310. const Range<int> oldSelection (selection);
  42311. if (dragType == notDragging)
  42312. {
  42313. if (abs (getCaretPosition() - selection.getStart()) < abs (getCaretPosition() - selection.getEnd()))
  42314. dragType = draggingSelectionStart;
  42315. else
  42316. dragType = draggingSelectionEnd;
  42317. }
  42318. if (dragType == draggingSelectionStart)
  42319. {
  42320. if (getCaretPosition() >= selection.getEnd())
  42321. dragType = draggingSelectionEnd;
  42322. selection = Range<int>::between (getCaretPosition(), selection.getEnd());
  42323. }
  42324. else
  42325. {
  42326. if (getCaretPosition() < selection.getStart())
  42327. dragType = draggingSelectionStart;
  42328. selection = Range<int>::between (getCaretPosition(), selection.getStart());
  42329. }
  42330. repaintText (selection.getUnionWith (oldSelection));
  42331. }
  42332. else
  42333. {
  42334. dragType = notDragging;
  42335. repaintText (selection);
  42336. moveCaret (newPosition);
  42337. selection = Range<int>::emptyRange (getCaretPosition());
  42338. }
  42339. }
  42340. int TextEditor::getTextIndexAt (const int x,
  42341. const int y)
  42342. {
  42343. return indexAtPosition ((float) (x + viewport->getViewPositionX() - leftIndent),
  42344. (float) (y + viewport->getViewPositionY() - topIndent));
  42345. }
  42346. void TextEditor::insertTextAtCaret (const String& newText_)
  42347. {
  42348. String newText (newText_);
  42349. if (allowedCharacters.isNotEmpty())
  42350. newText = newText.retainCharacters (allowedCharacters);
  42351. if ((! returnKeyStartsNewLine) && newText == "\n")
  42352. {
  42353. returnPressed();
  42354. return;
  42355. }
  42356. if (! isMultiLine())
  42357. newText = newText.replaceCharacters ("\r\n", " ");
  42358. else
  42359. newText = newText.replace ("\r\n", "\n");
  42360. const int newCaretPos = selection.getStart() + newText.length();
  42361. const int insertIndex = selection.getStart();
  42362. remove (selection, getUndoManager(),
  42363. newText.isNotEmpty() ? newCaretPos - 1 : newCaretPos);
  42364. if (maxTextLength > 0)
  42365. newText = newText.substring (0, maxTextLength - getTotalNumChars());
  42366. if (newText.isNotEmpty())
  42367. insert (newText,
  42368. insertIndex,
  42369. currentFont,
  42370. findColour (textColourId),
  42371. getUndoManager(),
  42372. newCaretPos);
  42373. textChanged();
  42374. }
  42375. void TextEditor::setHighlightedRegion (const Range<int>& newSelection)
  42376. {
  42377. moveCursorTo (newSelection.getStart(), false);
  42378. moveCursorTo (newSelection.getEnd(), true);
  42379. }
  42380. void TextEditor::copy()
  42381. {
  42382. if (passwordCharacter == 0)
  42383. {
  42384. const String selection (getHighlightedText());
  42385. if (selection.isNotEmpty())
  42386. SystemClipboard::copyTextToClipboard (selection);
  42387. }
  42388. }
  42389. void TextEditor::paste()
  42390. {
  42391. if (! isReadOnly())
  42392. {
  42393. const String clip (SystemClipboard::getTextFromClipboard());
  42394. if (clip.isNotEmpty())
  42395. insertTextAtCaret (clip);
  42396. }
  42397. }
  42398. void TextEditor::cut()
  42399. {
  42400. if (! isReadOnly())
  42401. {
  42402. moveCaret (selection.getEnd());
  42403. insertTextAtCaret (String::empty);
  42404. }
  42405. }
  42406. void TextEditor::drawContent (Graphics& g)
  42407. {
  42408. const float wordWrapWidth = getWordWrapWidth();
  42409. if (wordWrapWidth > 0)
  42410. {
  42411. g.setOrigin (leftIndent, topIndent);
  42412. const Rectangle<int> clip (g.getClipBounds());
  42413. Colour selectedTextColour;
  42414. Iterator i (sections, wordWrapWidth, passwordCharacter);
  42415. while (i.lineY + 200.0 < clip.getY() && i.next())
  42416. {}
  42417. if (! selection.isEmpty())
  42418. {
  42419. g.setColour (findColour (highlightColourId)
  42420. .withMultipliedAlpha (hasKeyboardFocus (true) ? 1.0f : 0.5f));
  42421. selectedTextColour = findColour (highlightedTextColourId);
  42422. Iterator i2 (i);
  42423. while (i2.next() && i2.lineY < clip.getBottom())
  42424. {
  42425. if (i2.lineY + i2.lineHeight >= clip.getY()
  42426. && selection.intersects (Range<int> (i2.indexInText, i2.indexInText + i2.atom->numChars)))
  42427. {
  42428. i2.drawSelection (g, selection);
  42429. }
  42430. }
  42431. }
  42432. const UniformTextSection* lastSection = 0;
  42433. while (i.next() && i.lineY < clip.getBottom())
  42434. {
  42435. if (i.lineY + i.lineHeight >= clip.getY())
  42436. {
  42437. if (selection.intersects (Range<int> (i.indexInText, i.indexInText + i.atom->numChars)))
  42438. {
  42439. i.drawSelectedText (g, selection, selectedTextColour);
  42440. lastSection = 0;
  42441. }
  42442. else
  42443. {
  42444. i.draw (g, lastSection);
  42445. }
  42446. }
  42447. }
  42448. }
  42449. }
  42450. void TextEditor::paint (Graphics& g)
  42451. {
  42452. getLookAndFeel().fillTextEditorBackground (g, getWidth(), getHeight(), *this);
  42453. }
  42454. void TextEditor::paintOverChildren (Graphics& g)
  42455. {
  42456. if (caretFlashState
  42457. && hasKeyboardFocus (false)
  42458. && caretVisible
  42459. && ! isReadOnly())
  42460. {
  42461. g.setColour (findColour (caretColourId));
  42462. g.fillRect (borderSize.getLeft() + textHolder->getX() + leftIndent + cursorX,
  42463. borderSize.getTop() + textHolder->getY() + topIndent + cursorY,
  42464. 2.0f, cursorHeight);
  42465. }
  42466. if (textToShowWhenEmpty.isNotEmpty()
  42467. && (! hasKeyboardFocus (false))
  42468. && getTotalNumChars() == 0)
  42469. {
  42470. g.setColour (colourForTextWhenEmpty);
  42471. g.setFont (getFont());
  42472. if (isMultiLine())
  42473. {
  42474. g.drawText (textToShowWhenEmpty,
  42475. 0, 0, getWidth(), getHeight(),
  42476. Justification::centred, true);
  42477. }
  42478. else
  42479. {
  42480. g.drawText (textToShowWhenEmpty,
  42481. leftIndent, topIndent,
  42482. viewport->getWidth() - leftIndent,
  42483. viewport->getHeight() - topIndent,
  42484. Justification::centredLeft, true);
  42485. }
  42486. }
  42487. getLookAndFeel().drawTextEditorOutline (g, getWidth(), getHeight(), *this);
  42488. }
  42489. void TextEditor::mouseDown (const MouseEvent& e)
  42490. {
  42491. beginDragAutoRepeat (100);
  42492. newTransaction();
  42493. if (wasFocused || ! selectAllTextWhenFocused)
  42494. {
  42495. if (! (popupMenuEnabled && e.mods.isPopupMenu()))
  42496. {
  42497. moveCursorTo (getTextIndexAt (e.x, e.y),
  42498. e.mods.isShiftDown());
  42499. }
  42500. else
  42501. {
  42502. PopupMenu m;
  42503. m.setLookAndFeel (&getLookAndFeel());
  42504. addPopupMenuItems (m, &e);
  42505. menuActive = true;
  42506. const int result = m.show();
  42507. menuActive = false;
  42508. if (result != 0)
  42509. performPopupMenuAction (result);
  42510. }
  42511. }
  42512. }
  42513. void TextEditor::mouseDrag (const MouseEvent& e)
  42514. {
  42515. if (wasFocused || ! selectAllTextWhenFocused)
  42516. {
  42517. if (! (popupMenuEnabled && e.mods.isPopupMenu()))
  42518. {
  42519. moveCursorTo (getTextIndexAt (e.x, e.y), true);
  42520. }
  42521. }
  42522. }
  42523. void TextEditor::mouseUp (const MouseEvent& e)
  42524. {
  42525. newTransaction();
  42526. textHolder->startTimer (TextEditorDefs::flashSpeedIntervalMs);
  42527. if (wasFocused || ! selectAllTextWhenFocused)
  42528. {
  42529. if (e.mouseWasClicked() && ! (popupMenuEnabled && e.mods.isPopupMenu()))
  42530. {
  42531. moveCaret (getTextIndexAt (e.x, e.y));
  42532. }
  42533. }
  42534. wasFocused = true;
  42535. }
  42536. void TextEditor::mouseDoubleClick (const MouseEvent& e)
  42537. {
  42538. int tokenEnd = getTextIndexAt (e.x, e.y);
  42539. int tokenStart = tokenEnd;
  42540. if (e.getNumberOfClicks() > 3)
  42541. {
  42542. tokenStart = 0;
  42543. tokenEnd = getTotalNumChars();
  42544. }
  42545. else
  42546. {
  42547. const String t (getText());
  42548. const int totalLength = getTotalNumChars();
  42549. while (tokenEnd < totalLength)
  42550. {
  42551. if (CharacterFunctions::isLetterOrDigit (t [tokenEnd]))
  42552. ++tokenEnd;
  42553. else
  42554. break;
  42555. }
  42556. tokenStart = tokenEnd;
  42557. while (tokenStart > 0)
  42558. {
  42559. if (CharacterFunctions::isLetterOrDigit (t [tokenStart - 1]))
  42560. --tokenStart;
  42561. else
  42562. break;
  42563. }
  42564. if (e.getNumberOfClicks() > 2)
  42565. {
  42566. while (tokenEnd < totalLength)
  42567. {
  42568. if (t [tokenEnd] != '\r' && t [tokenEnd] != '\n')
  42569. ++tokenEnd;
  42570. else
  42571. break;
  42572. }
  42573. while (tokenStart > 0)
  42574. {
  42575. if (t [tokenStart - 1] != '\r' && t [tokenStart - 1] != '\n')
  42576. --tokenStart;
  42577. else
  42578. break;
  42579. }
  42580. }
  42581. }
  42582. moveCursorTo (tokenEnd, false);
  42583. moveCursorTo (tokenStart, true);
  42584. }
  42585. void TextEditor::mouseWheelMove (const MouseEvent& e, float wheelIncrementX, float wheelIncrementY)
  42586. {
  42587. if (! viewport->useMouseWheelMoveIfNeeded (e, wheelIncrementX, wheelIncrementY))
  42588. Component::mouseWheelMove (e, wheelIncrementX, wheelIncrementY);
  42589. }
  42590. bool TextEditor::keyPressed (const KeyPress& key)
  42591. {
  42592. if (isReadOnly() && key != KeyPress ('c', ModifierKeys::commandModifier, 0))
  42593. return false;
  42594. const bool moveInWholeWordSteps = key.getModifiers().isCtrlDown() || key.getModifiers().isAltDown();
  42595. if (key.isKeyCode (KeyPress::leftKey)
  42596. || key.isKeyCode (KeyPress::upKey))
  42597. {
  42598. newTransaction();
  42599. int newPos;
  42600. if (isMultiLine() && key.isKeyCode (KeyPress::upKey))
  42601. newPos = indexAtPosition (cursorX, cursorY - 1);
  42602. else if (moveInWholeWordSteps)
  42603. newPos = findWordBreakBefore (getCaretPosition());
  42604. else
  42605. newPos = getCaretPosition() - 1;
  42606. moveCursorTo (newPos, key.getModifiers().isShiftDown());
  42607. }
  42608. else if (key.isKeyCode (KeyPress::rightKey)
  42609. || key.isKeyCode (KeyPress::downKey))
  42610. {
  42611. newTransaction();
  42612. int newPos;
  42613. if (isMultiLine() && key.isKeyCode (KeyPress::downKey))
  42614. newPos = indexAtPosition (cursorX, cursorY + cursorHeight + 1);
  42615. else if (moveInWholeWordSteps)
  42616. newPos = findWordBreakAfter (getCaretPosition());
  42617. else
  42618. newPos = getCaretPosition() + 1;
  42619. moveCursorTo (newPos, key.getModifiers().isShiftDown());
  42620. }
  42621. else if (key.isKeyCode (KeyPress::pageDownKey) && isMultiLine())
  42622. {
  42623. newTransaction();
  42624. moveCursorTo (indexAtPosition (cursorX, cursorY + cursorHeight + viewport->getViewHeight()),
  42625. key.getModifiers().isShiftDown());
  42626. }
  42627. else if (key.isKeyCode (KeyPress::pageUpKey) && isMultiLine())
  42628. {
  42629. newTransaction();
  42630. moveCursorTo (indexAtPosition (cursorX, cursorY - viewport->getViewHeight()),
  42631. key.getModifiers().isShiftDown());
  42632. }
  42633. else if (key.isKeyCode (KeyPress::homeKey))
  42634. {
  42635. newTransaction();
  42636. if (isMultiLine() && ! moveInWholeWordSteps)
  42637. moveCursorTo (indexAtPosition (0.0f, cursorY),
  42638. key.getModifiers().isShiftDown());
  42639. else
  42640. moveCursorTo (0, key.getModifiers().isShiftDown());
  42641. }
  42642. else if (key.isKeyCode (KeyPress::endKey))
  42643. {
  42644. newTransaction();
  42645. if (isMultiLine() && ! moveInWholeWordSteps)
  42646. moveCursorTo (indexAtPosition ((float) textHolder->getWidth(), cursorY),
  42647. key.getModifiers().isShiftDown());
  42648. else
  42649. moveCursorTo (getTotalNumChars(), key.getModifiers().isShiftDown());
  42650. }
  42651. else if (key.isKeyCode (KeyPress::backspaceKey))
  42652. {
  42653. if (moveInWholeWordSteps)
  42654. {
  42655. moveCursorTo (findWordBreakBefore (getCaretPosition()), true);
  42656. }
  42657. else
  42658. {
  42659. if (selection.isEmpty() && selection.getStart() > 0)
  42660. selection.setStart (selection.getEnd() - 1);
  42661. }
  42662. cut();
  42663. }
  42664. else if (key.isKeyCode (KeyPress::deleteKey))
  42665. {
  42666. if (key.getModifiers().isShiftDown())
  42667. copy();
  42668. if (selection.isEmpty() && selection.getStart() < getTotalNumChars())
  42669. selection.setEnd (selection.getStart() + 1);
  42670. cut();
  42671. }
  42672. else if (key == KeyPress ('c', ModifierKeys::commandModifier, 0)
  42673. || key == KeyPress (KeyPress::insertKey, ModifierKeys::ctrlModifier, 0))
  42674. {
  42675. newTransaction();
  42676. copy();
  42677. }
  42678. else if (key == KeyPress ('x', ModifierKeys::commandModifier, 0))
  42679. {
  42680. newTransaction();
  42681. copy();
  42682. cut();
  42683. }
  42684. else if (key == KeyPress ('v', ModifierKeys::commandModifier, 0)
  42685. || key == KeyPress (KeyPress::insertKey, ModifierKeys::shiftModifier, 0))
  42686. {
  42687. newTransaction();
  42688. paste();
  42689. }
  42690. else if (key == KeyPress ('z', ModifierKeys::commandModifier, 0))
  42691. {
  42692. newTransaction();
  42693. doUndoRedo (false);
  42694. }
  42695. else if (key == KeyPress ('y', ModifierKeys::commandModifier, 0))
  42696. {
  42697. newTransaction();
  42698. doUndoRedo (true);
  42699. }
  42700. else if (key == KeyPress ('a', ModifierKeys::commandModifier, 0))
  42701. {
  42702. newTransaction();
  42703. moveCursorTo (getTotalNumChars(), false);
  42704. moveCursorTo (0, true);
  42705. }
  42706. else if (key == KeyPress::returnKey)
  42707. {
  42708. newTransaction();
  42709. insertTextAtCaret ("\n");
  42710. }
  42711. else if (key.isKeyCode (KeyPress::escapeKey))
  42712. {
  42713. newTransaction();
  42714. moveCursorTo (getCaretPosition(), false);
  42715. escapePressed();
  42716. }
  42717. else if (key.getTextCharacter() >= ' '
  42718. || (tabKeyUsed && (key.getTextCharacter() == '\t')))
  42719. {
  42720. insertTextAtCaret (String::charToString (key.getTextCharacter()));
  42721. lastTransactionTime = Time::getApproximateMillisecondCounter();
  42722. }
  42723. else
  42724. {
  42725. return false;
  42726. }
  42727. return true;
  42728. }
  42729. bool TextEditor::keyStateChanged (const bool isKeyDown)
  42730. {
  42731. if (! isKeyDown)
  42732. return false;
  42733. #if JUCE_WIN32
  42734. if (KeyPress (KeyPress::F4Key, ModifierKeys::altModifier, 0).isCurrentlyDown())
  42735. return false; // We need to explicitly allow alt-F4 to pass through on Windows
  42736. #endif
  42737. // (overridden to avoid forwarding key events to the parent)
  42738. return ! ModifierKeys::getCurrentModifiers().isCommandDown();
  42739. }
  42740. const int baseMenuItemID = 0x7fff0000;
  42741. void TextEditor::addPopupMenuItems (PopupMenu& m, const MouseEvent*)
  42742. {
  42743. const bool writable = ! isReadOnly();
  42744. if (passwordCharacter == 0)
  42745. {
  42746. m.addItem (baseMenuItemID + 1, TRANS("cut"), writable);
  42747. m.addItem (baseMenuItemID + 2, TRANS("copy"), ! selection.isEmpty());
  42748. m.addItem (baseMenuItemID + 3, TRANS("paste"), writable);
  42749. }
  42750. m.addItem (baseMenuItemID + 4, TRANS("delete"), writable);
  42751. m.addSeparator();
  42752. m.addItem (baseMenuItemID + 5, TRANS("select all"));
  42753. m.addSeparator();
  42754. if (getUndoManager() != 0)
  42755. {
  42756. m.addItem (baseMenuItemID + 6, TRANS("undo"), undoManager.canUndo());
  42757. m.addItem (baseMenuItemID + 7, TRANS("redo"), undoManager.canRedo());
  42758. }
  42759. }
  42760. void TextEditor::performPopupMenuAction (const int menuItemID)
  42761. {
  42762. switch (menuItemID)
  42763. {
  42764. case baseMenuItemID + 1:
  42765. copy();
  42766. cut();
  42767. break;
  42768. case baseMenuItemID + 2:
  42769. copy();
  42770. break;
  42771. case baseMenuItemID + 3:
  42772. paste();
  42773. break;
  42774. case baseMenuItemID + 4:
  42775. cut();
  42776. break;
  42777. case baseMenuItemID + 5:
  42778. moveCursorTo (getTotalNumChars(), false);
  42779. moveCursorTo (0, true);
  42780. break;
  42781. case baseMenuItemID + 6:
  42782. doUndoRedo (false);
  42783. break;
  42784. case baseMenuItemID + 7:
  42785. doUndoRedo (true);
  42786. break;
  42787. default:
  42788. break;
  42789. }
  42790. }
  42791. void TextEditor::focusGained (FocusChangeType)
  42792. {
  42793. newTransaction();
  42794. caretFlashState = true;
  42795. if (selectAllTextWhenFocused)
  42796. {
  42797. moveCursorTo (0, false);
  42798. moveCursorTo (getTotalNumChars(), true);
  42799. }
  42800. repaint();
  42801. if (caretVisible)
  42802. textHolder->startTimer (TextEditorDefs::flashSpeedIntervalMs);
  42803. ComponentPeer* const peer = getPeer();
  42804. if (peer != 0 && ! isReadOnly())
  42805. peer->textInputRequired (getScreenPosition() - peer->getScreenPosition());
  42806. }
  42807. void TextEditor::focusLost (FocusChangeType)
  42808. {
  42809. newTransaction();
  42810. wasFocused = false;
  42811. textHolder->stopTimer();
  42812. caretFlashState = false;
  42813. postCommandMessage (TextEditorDefs::focusLossMessageId);
  42814. repaint();
  42815. }
  42816. void TextEditor::resized()
  42817. {
  42818. viewport->setBoundsInset (borderSize);
  42819. viewport->setSingleStepSizes (16, roundToInt (currentFont.getHeight()));
  42820. updateTextHolderSize();
  42821. if (! isMultiLine())
  42822. {
  42823. scrollToMakeSureCursorIsVisible();
  42824. }
  42825. else
  42826. {
  42827. updateCaretPosition();
  42828. }
  42829. }
  42830. void TextEditor::handleCommandMessage (const int commandId)
  42831. {
  42832. Component::BailOutChecker checker (this);
  42833. switch (commandId)
  42834. {
  42835. case TextEditorDefs::textChangeMessageId:
  42836. listeners.callChecked (checker, &TextEditorListener::textEditorTextChanged, (TextEditor&) *this);
  42837. break;
  42838. case TextEditorDefs::returnKeyMessageId:
  42839. listeners.callChecked (checker, &TextEditorListener::textEditorReturnKeyPressed, (TextEditor&) *this);
  42840. break;
  42841. case TextEditorDefs::escapeKeyMessageId:
  42842. listeners.callChecked (checker, &TextEditorListener::textEditorEscapeKeyPressed, (TextEditor&) *this);
  42843. break;
  42844. case TextEditorDefs::focusLossMessageId:
  42845. listeners.callChecked (checker, &TextEditorListener::textEditorFocusLost, (TextEditor&) *this);
  42846. break;
  42847. default:
  42848. jassertfalse
  42849. break;
  42850. }
  42851. }
  42852. void TextEditor::enablementChanged()
  42853. {
  42854. setMouseCursor (isReadOnly() ? MouseCursor::NormalCursor
  42855. : MouseCursor::IBeamCursor);
  42856. repaint();
  42857. }
  42858. UndoManager* TextEditor::getUndoManager() throw()
  42859. {
  42860. return isReadOnly() ? &undoManager : 0;
  42861. }
  42862. void TextEditor::clearInternal (UndoManager* const um)
  42863. {
  42864. remove (Range<int> (0, getTotalNumChars()), um, caretPosition);
  42865. }
  42866. void TextEditor::insert (const String& text,
  42867. const int insertIndex,
  42868. const Font& font,
  42869. const Colour& colour,
  42870. UndoManager* const um,
  42871. const int caretPositionToMoveTo)
  42872. {
  42873. if (text.isNotEmpty())
  42874. {
  42875. if (um != 0)
  42876. {
  42877. if (um->getNumActionsInCurrentTransaction() > TextEditorDefs::maxActionsPerTransaction)
  42878. newTransaction();
  42879. um->perform (new InsertAction (*this, text, insertIndex, font, colour,
  42880. caretPosition, caretPositionToMoveTo));
  42881. }
  42882. else
  42883. {
  42884. repaintText (Range<int> (insertIndex, getTotalNumChars())); // must do this before and after changing the data, in case
  42885. // a line gets moved due to word wrap
  42886. int index = 0;
  42887. int nextIndex = 0;
  42888. for (int i = 0; i < sections.size(); ++i)
  42889. {
  42890. nextIndex = index + sections.getUnchecked (i)->getTotalLength();
  42891. if (insertIndex == index)
  42892. {
  42893. sections.insert (i, new UniformTextSection (text,
  42894. font, colour,
  42895. passwordCharacter));
  42896. break;
  42897. }
  42898. else if (insertIndex > index && insertIndex < nextIndex)
  42899. {
  42900. splitSection (i, insertIndex - index);
  42901. sections.insert (i + 1, new UniformTextSection (text,
  42902. font, colour,
  42903. passwordCharacter));
  42904. break;
  42905. }
  42906. index = nextIndex;
  42907. }
  42908. if (nextIndex == insertIndex)
  42909. sections.add (new UniformTextSection (text,
  42910. font, colour,
  42911. passwordCharacter));
  42912. coalesceSimilarSections();
  42913. totalNumChars = -1;
  42914. valueTextNeedsUpdating = true;
  42915. moveCursorTo (caretPositionToMoveTo, false);
  42916. repaintText (Range<int> (insertIndex, getTotalNumChars()));
  42917. }
  42918. }
  42919. }
  42920. void TextEditor::reinsert (const int insertIndex,
  42921. const Array <UniformTextSection*>& sectionsToInsert)
  42922. {
  42923. int index = 0;
  42924. int nextIndex = 0;
  42925. for (int i = 0; i < sections.size(); ++i)
  42926. {
  42927. nextIndex = index + sections.getUnchecked (i)->getTotalLength();
  42928. if (insertIndex == index)
  42929. {
  42930. for (int j = sectionsToInsert.size(); --j >= 0;)
  42931. sections.insert (i, new UniformTextSection (*sectionsToInsert.getUnchecked(j)));
  42932. break;
  42933. }
  42934. else if (insertIndex > index && insertIndex < nextIndex)
  42935. {
  42936. splitSection (i, insertIndex - index);
  42937. for (int j = sectionsToInsert.size(); --j >= 0;)
  42938. sections.insert (i + 1, new UniformTextSection (*sectionsToInsert.getUnchecked(j)));
  42939. break;
  42940. }
  42941. index = nextIndex;
  42942. }
  42943. if (nextIndex == insertIndex)
  42944. {
  42945. for (int j = 0; j < sectionsToInsert.size(); ++j)
  42946. sections.add (new UniformTextSection (*sectionsToInsert.getUnchecked(j)));
  42947. }
  42948. coalesceSimilarSections();
  42949. totalNumChars = -1;
  42950. valueTextNeedsUpdating = true;
  42951. }
  42952. void TextEditor::remove (const Range<int>& range,
  42953. UndoManager* const um,
  42954. const int caretPositionToMoveTo)
  42955. {
  42956. if (! range.isEmpty())
  42957. {
  42958. int index = 0;
  42959. for (int i = 0; i < sections.size(); ++i)
  42960. {
  42961. const int nextIndex = index + sections.getUnchecked(i)->getTotalLength();
  42962. if (range.getStart() > index && range.getStart() < nextIndex)
  42963. {
  42964. splitSection (i, range.getStart() - index);
  42965. --i;
  42966. }
  42967. else if (range.getEnd() > index && range.getEnd() < nextIndex)
  42968. {
  42969. splitSection (i, range.getEnd() - index);
  42970. --i;
  42971. }
  42972. else
  42973. {
  42974. index = nextIndex;
  42975. if (index > range.getEnd())
  42976. break;
  42977. }
  42978. }
  42979. index = 0;
  42980. if (um != 0)
  42981. {
  42982. Array <UniformTextSection*> removedSections;
  42983. for (int i = 0; i < sections.size(); ++i)
  42984. {
  42985. if (range.getEnd() <= range.getStart())
  42986. break;
  42987. UniformTextSection* const section = sections.getUnchecked (i);
  42988. const int nextIndex = index + section->getTotalLength();
  42989. if (range.getStart() <= index && range.getEnd() >= nextIndex)
  42990. removedSections.add (new UniformTextSection (*section));
  42991. index = nextIndex;
  42992. }
  42993. if (um->getNumActionsInCurrentTransaction() > TextEditorDefs::maxActionsPerTransaction)
  42994. newTransaction();
  42995. um->perform (new RemoveAction (*this, range, caretPosition,
  42996. caretPositionToMoveTo, removedSections));
  42997. }
  42998. else
  42999. {
  43000. Range<int> remainingRange (range);
  43001. for (int i = 0; i < sections.size(); ++i)
  43002. {
  43003. UniformTextSection* const section = sections.getUnchecked (i);
  43004. const int nextIndex = index + section->getTotalLength();
  43005. if (remainingRange.getStart() <= index && remainingRange.getEnd() >= nextIndex)
  43006. {
  43007. sections.remove(i);
  43008. section->clear();
  43009. delete section;
  43010. remainingRange.setEnd (remainingRange.getEnd() - (nextIndex - index));
  43011. if (remainingRange.isEmpty())
  43012. break;
  43013. --i;
  43014. }
  43015. else
  43016. {
  43017. index = nextIndex;
  43018. }
  43019. }
  43020. coalesceSimilarSections();
  43021. totalNumChars = -1;
  43022. valueTextNeedsUpdating = true;
  43023. moveCursorTo (caretPositionToMoveTo, false);
  43024. repaintText (Range<int> (range.getStart(), getTotalNumChars()));
  43025. }
  43026. }
  43027. }
  43028. const String TextEditor::getText() const
  43029. {
  43030. String t;
  43031. t.preallocateStorage (getTotalNumChars());
  43032. String::Concatenator concatenator (t);
  43033. for (int i = 0; i < sections.size(); ++i)
  43034. sections.getUnchecked (i)->appendAllText (concatenator);
  43035. return t;
  43036. }
  43037. const String TextEditor::getTextInRange (const Range<int>& range) const
  43038. {
  43039. String t;
  43040. if (! range.isEmpty())
  43041. {
  43042. t.preallocateStorage (jmin (getTotalNumChars(), range.getLength()));
  43043. String::Concatenator concatenator (t);
  43044. int index = 0;
  43045. for (int i = 0; i < sections.size(); ++i)
  43046. {
  43047. const UniformTextSection* const s = sections.getUnchecked (i);
  43048. const int nextIndex = index + s->getTotalLength();
  43049. if (range.getStart() < nextIndex)
  43050. {
  43051. if (range.getEnd() <= index)
  43052. break;
  43053. s->appendSubstring (concatenator, range - index);
  43054. }
  43055. index = nextIndex;
  43056. }
  43057. }
  43058. return t;
  43059. }
  43060. const String TextEditor::getHighlightedText() const
  43061. {
  43062. return getTextInRange (selection);
  43063. }
  43064. int TextEditor::getTotalNumChars() const
  43065. {
  43066. if (totalNumChars < 0)
  43067. {
  43068. totalNumChars = 0;
  43069. for (int i = sections.size(); --i >= 0;)
  43070. totalNumChars += sections.getUnchecked (i)->getTotalLength();
  43071. }
  43072. return totalNumChars;
  43073. }
  43074. bool TextEditor::isEmpty() const
  43075. {
  43076. return getTotalNumChars() == 0;
  43077. }
  43078. void TextEditor::getCharPosition (const int index, float& cx, float& cy, float& lineHeight) const
  43079. {
  43080. const float wordWrapWidth = getWordWrapWidth();
  43081. if (wordWrapWidth > 0 && sections.size() > 0)
  43082. {
  43083. Iterator i (sections, wordWrapWidth, passwordCharacter);
  43084. i.getCharPosition (index, cx, cy, lineHeight);
  43085. }
  43086. else
  43087. {
  43088. cx = cy = 0;
  43089. lineHeight = currentFont.getHeight();
  43090. }
  43091. }
  43092. int TextEditor::indexAtPosition (const float x, const float y)
  43093. {
  43094. const float wordWrapWidth = getWordWrapWidth();
  43095. if (wordWrapWidth > 0)
  43096. {
  43097. Iterator i (sections, wordWrapWidth, passwordCharacter);
  43098. while (i.next())
  43099. {
  43100. if (i.lineY + i.lineHeight > y)
  43101. {
  43102. if (i.lineY > y)
  43103. return jmax (0, i.indexInText - 1);
  43104. if (i.atomX >= x)
  43105. return i.indexInText;
  43106. if (x < i.atomRight)
  43107. return i.xToIndex (x);
  43108. }
  43109. }
  43110. }
  43111. return getTotalNumChars();
  43112. }
  43113. static int getCharacterCategory (const juce_wchar character)
  43114. {
  43115. return CharacterFunctions::isLetterOrDigit (character)
  43116. ? 2 : (CharacterFunctions::isWhitespace (character) ? 0 : 1);
  43117. }
  43118. int TextEditor::findWordBreakAfter (const int position) const
  43119. {
  43120. const String t (getTextInRange (Range<int> (position, position + 512)));
  43121. const int totalLength = t.length();
  43122. int i = 0;
  43123. while (i < totalLength && CharacterFunctions::isWhitespace (t[i]))
  43124. ++i;
  43125. const int type = getCharacterCategory (t[i]);
  43126. while (i < totalLength && type == getCharacterCategory (t[i]))
  43127. ++i;
  43128. while (i < totalLength && CharacterFunctions::isWhitespace (t[i]))
  43129. ++i;
  43130. return position + i;
  43131. }
  43132. int TextEditor::findWordBreakBefore (const int position) const
  43133. {
  43134. if (position <= 0)
  43135. return 0;
  43136. const int startOfBuffer = jmax (0, position - 512);
  43137. const String t (getTextInRange (Range<int> (startOfBuffer, position)));
  43138. int i = position - startOfBuffer;
  43139. while (i > 0 && CharacterFunctions::isWhitespace (t [i - 1]))
  43140. --i;
  43141. if (i > 0)
  43142. {
  43143. const int type = getCharacterCategory (t [i - 1]);
  43144. while (i > 0 && type == getCharacterCategory (t [i - 1]))
  43145. --i;
  43146. }
  43147. jassert (startOfBuffer + i >= 0);
  43148. return startOfBuffer + i;
  43149. }
  43150. void TextEditor::splitSection (const int sectionIndex,
  43151. const int charToSplitAt)
  43152. {
  43153. jassert (sections[sectionIndex] != 0);
  43154. sections.insert (sectionIndex + 1,
  43155. sections.getUnchecked (sectionIndex)->split (charToSplitAt, passwordCharacter));
  43156. }
  43157. void TextEditor::coalesceSimilarSections()
  43158. {
  43159. for (int i = 0; i < sections.size() - 1; ++i)
  43160. {
  43161. UniformTextSection* const s1 = sections.getUnchecked (i);
  43162. UniformTextSection* const s2 = sections.getUnchecked (i + 1);
  43163. if (s1->font == s2->font
  43164. && s1->colour == s2->colour)
  43165. {
  43166. s1->append (*s2, passwordCharacter);
  43167. sections.remove (i + 1);
  43168. delete s2;
  43169. --i;
  43170. }
  43171. }
  43172. }
  43173. END_JUCE_NAMESPACE
  43174. /*** End of inlined file: juce_TextEditor.cpp ***/
  43175. /*** Start of inlined file: juce_Toolbar.cpp ***/
  43176. BEGIN_JUCE_NAMESPACE
  43177. const char* const Toolbar::toolbarDragDescriptor = "_toolbarItem_";
  43178. class ToolbarSpacerComp : public ToolbarItemComponent
  43179. {
  43180. public:
  43181. ToolbarSpacerComp (const int itemId_, const float fixedSize_, const bool drawBar_)
  43182. : ToolbarItemComponent (itemId_, String::empty, false),
  43183. fixedSize (fixedSize_),
  43184. drawBar (drawBar_)
  43185. {
  43186. }
  43187. ~ToolbarSpacerComp()
  43188. {
  43189. }
  43190. bool getToolbarItemSizes (int toolbarThickness, bool /*isToolbarVertical*/,
  43191. int& preferredSize, int& minSize, int& maxSize)
  43192. {
  43193. if (fixedSize <= 0)
  43194. {
  43195. preferredSize = toolbarThickness * 2;
  43196. minSize = 4;
  43197. maxSize = 32768;
  43198. }
  43199. else
  43200. {
  43201. maxSize = roundToInt (toolbarThickness * fixedSize);
  43202. minSize = drawBar ? maxSize : jmin (4, maxSize);
  43203. preferredSize = maxSize;
  43204. if (getEditingMode() == editableOnPalette)
  43205. preferredSize = maxSize = toolbarThickness / (drawBar ? 3 : 2);
  43206. }
  43207. return true;
  43208. }
  43209. void paintButtonArea (Graphics&, int, int, bool, bool)
  43210. {
  43211. }
  43212. void contentAreaChanged (const Rectangle<int>&)
  43213. {
  43214. }
  43215. int getResizeOrder() const throw()
  43216. {
  43217. return fixedSize <= 0 ? 0 : 1;
  43218. }
  43219. void paint (Graphics& g)
  43220. {
  43221. const int w = getWidth();
  43222. const int h = getHeight();
  43223. if (drawBar)
  43224. {
  43225. g.setColour (findColour (Toolbar::separatorColourId, true));
  43226. const float thickness = 0.2f;
  43227. if (isToolbarVertical())
  43228. g.fillRect (w * 0.1f, h * (0.5f - thickness * 0.5f), w * 0.8f, h * thickness);
  43229. else
  43230. g.fillRect (w * (0.5f - thickness * 0.5f), h * 0.1f, w * thickness, h * 0.8f);
  43231. }
  43232. if (getEditingMode() != normalMode && ! drawBar)
  43233. {
  43234. g.setColour (findColour (Toolbar::separatorColourId, true));
  43235. const int indentX = jmin (2, (w - 3) / 2);
  43236. const int indentY = jmin (2, (h - 3) / 2);
  43237. g.drawRect (indentX, indentY, w - indentX * 2, h - indentY * 2, 1);
  43238. if (fixedSize <= 0)
  43239. {
  43240. float x1, y1, x2, y2, x3, y3, x4, y4, hw, hl;
  43241. if (isToolbarVertical())
  43242. {
  43243. x1 = w * 0.5f;
  43244. y1 = h * 0.4f;
  43245. x2 = x1;
  43246. y2 = indentX * 2.0f;
  43247. x3 = x1;
  43248. y3 = h * 0.6f;
  43249. x4 = x1;
  43250. y4 = h - y2;
  43251. hw = w * 0.15f;
  43252. hl = w * 0.2f;
  43253. }
  43254. else
  43255. {
  43256. x1 = w * 0.4f;
  43257. y1 = h * 0.5f;
  43258. x2 = indentX * 2.0f;
  43259. y2 = y1;
  43260. x3 = w * 0.6f;
  43261. y3 = y1;
  43262. x4 = w - x2;
  43263. y4 = y1;
  43264. hw = h * 0.15f;
  43265. hl = h * 0.2f;
  43266. }
  43267. Path p;
  43268. p.addArrow (x1, y1, x2, y2, 1.5f, hw, hl);
  43269. p.addArrow (x3, y3, x4, y4, 1.5f, hw, hl);
  43270. g.fillPath (p);
  43271. }
  43272. }
  43273. }
  43274. juce_UseDebuggingNewOperator
  43275. private:
  43276. const float fixedSize;
  43277. const bool drawBar;
  43278. ToolbarSpacerComp (const ToolbarSpacerComp&);
  43279. ToolbarSpacerComp& operator= (const ToolbarSpacerComp&);
  43280. };
  43281. class MissingItemsComponent : public PopupMenuCustomComponent
  43282. {
  43283. public:
  43284. MissingItemsComponent (Toolbar& owner_, const int height_)
  43285. : PopupMenuCustomComponent (true),
  43286. owner (owner_),
  43287. height (height_)
  43288. {
  43289. for (int i = owner_.items.size(); --i >= 0;)
  43290. {
  43291. ToolbarItemComponent* const tc = owner_.items.getUnchecked(i);
  43292. if (dynamic_cast <ToolbarSpacerComp*> (tc) == 0 && ! tc->isVisible())
  43293. {
  43294. oldIndexes.insert (0, i);
  43295. addAndMakeVisible (tc, 0);
  43296. }
  43297. }
  43298. layout (400);
  43299. }
  43300. ~MissingItemsComponent()
  43301. {
  43302. // deleting the toolbar while its menu it open??
  43303. jassert (owner.isValidComponent());
  43304. for (int i = 0; i < getNumChildComponents(); ++i)
  43305. {
  43306. ToolbarItemComponent* const tc = dynamic_cast <ToolbarItemComponent*> (getChildComponent (i));
  43307. if (tc != 0)
  43308. {
  43309. tc->setVisible (false);
  43310. const int index = oldIndexes.remove (i);
  43311. owner.addChildComponent (tc, index);
  43312. --i;
  43313. }
  43314. }
  43315. owner.resized();
  43316. }
  43317. void layout (const int preferredWidth)
  43318. {
  43319. const int indent = 8;
  43320. int x = indent;
  43321. int y = indent;
  43322. int maxX = 0;
  43323. for (int i = 0; i < getNumChildComponents(); ++i)
  43324. {
  43325. ToolbarItemComponent* const tc = dynamic_cast <ToolbarItemComponent*> (getChildComponent (i));
  43326. if (tc != 0)
  43327. {
  43328. int preferredSize = 1, minSize = 1, maxSize = 1;
  43329. if (tc->getToolbarItemSizes (height, false, preferredSize, minSize, maxSize))
  43330. {
  43331. if (x + preferredSize > preferredWidth && x > indent)
  43332. {
  43333. x = indent;
  43334. y += height;
  43335. }
  43336. tc->setBounds (x, y, preferredSize, height);
  43337. x += preferredSize;
  43338. maxX = jmax (maxX, x);
  43339. }
  43340. }
  43341. }
  43342. setSize (maxX + 8, y + height + 8);
  43343. }
  43344. void getIdealSize (int& idealWidth, int& idealHeight)
  43345. {
  43346. idealWidth = getWidth();
  43347. idealHeight = getHeight();
  43348. }
  43349. juce_UseDebuggingNewOperator
  43350. private:
  43351. Toolbar& owner;
  43352. const int height;
  43353. Array <int> oldIndexes;
  43354. MissingItemsComponent (const MissingItemsComponent&);
  43355. MissingItemsComponent& operator= (const MissingItemsComponent&);
  43356. };
  43357. Toolbar::Toolbar()
  43358. : vertical (false),
  43359. isEditingActive (false),
  43360. toolbarStyle (Toolbar::iconsOnly)
  43361. {
  43362. addChildComponent (missingItemsButton = getLookAndFeel().createToolbarMissingItemsButton (*this));
  43363. missingItemsButton->setAlwaysOnTop (true);
  43364. missingItemsButton->addButtonListener (this);
  43365. }
  43366. Toolbar::~Toolbar()
  43367. {
  43368. animator.cancelAllAnimations (true);
  43369. deleteAllChildren();
  43370. }
  43371. void Toolbar::setVertical (const bool shouldBeVertical)
  43372. {
  43373. if (vertical != shouldBeVertical)
  43374. {
  43375. vertical = shouldBeVertical;
  43376. resized();
  43377. }
  43378. }
  43379. void Toolbar::clear()
  43380. {
  43381. for (int i = items.size(); --i >= 0;)
  43382. {
  43383. ToolbarItemComponent* const tc = items.getUnchecked(i);
  43384. items.remove (i);
  43385. delete tc;
  43386. }
  43387. resized();
  43388. }
  43389. ToolbarItemComponent* Toolbar::createItem (ToolbarItemFactory& factory, const int itemId)
  43390. {
  43391. if (itemId == ToolbarItemFactory::separatorBarId)
  43392. return new ToolbarSpacerComp (itemId, 0.1f, true);
  43393. else if (itemId == ToolbarItemFactory::spacerId)
  43394. return new ToolbarSpacerComp (itemId, 0.5f, false);
  43395. else if (itemId == ToolbarItemFactory::flexibleSpacerId)
  43396. return new ToolbarSpacerComp (itemId, 0, false);
  43397. return factory.createItem (itemId);
  43398. }
  43399. void Toolbar::addItemInternal (ToolbarItemFactory& factory,
  43400. const int itemId,
  43401. const int insertIndex)
  43402. {
  43403. // An ID can't be zero - this might indicate a mistake somewhere?
  43404. jassert (itemId != 0);
  43405. ToolbarItemComponent* const tc = createItem (factory, itemId);
  43406. if (tc != 0)
  43407. {
  43408. #if JUCE_DEBUG
  43409. Array <int> allowedIds;
  43410. factory.getAllToolbarItemIds (allowedIds);
  43411. // If your factory can create an item for a given ID, it must also return
  43412. // that ID from its getAllToolbarItemIds() method!
  43413. jassert (allowedIds.contains (itemId));
  43414. #endif
  43415. items.insert (insertIndex, tc);
  43416. addAndMakeVisible (tc, insertIndex);
  43417. }
  43418. }
  43419. void Toolbar::addItem (ToolbarItemFactory& factory,
  43420. const int itemId,
  43421. const int insertIndex)
  43422. {
  43423. addItemInternal (factory, itemId, insertIndex);
  43424. resized();
  43425. }
  43426. void Toolbar::addDefaultItems (ToolbarItemFactory& factoryToUse)
  43427. {
  43428. Array <int> ids;
  43429. factoryToUse.getDefaultItemSet (ids);
  43430. clear();
  43431. for (int i = 0; i < ids.size(); ++i)
  43432. addItemInternal (factoryToUse, ids.getUnchecked (i), -1);
  43433. resized();
  43434. }
  43435. void Toolbar::removeToolbarItem (const int itemIndex)
  43436. {
  43437. ToolbarItemComponent* const tc = getItemComponent (itemIndex);
  43438. if (tc != 0)
  43439. {
  43440. items.removeValue (tc);
  43441. delete tc;
  43442. resized();
  43443. }
  43444. }
  43445. int Toolbar::getNumItems() const throw()
  43446. {
  43447. return items.size();
  43448. }
  43449. int Toolbar::getItemId (const int itemIndex) const throw()
  43450. {
  43451. ToolbarItemComponent* const tc = getItemComponent (itemIndex);
  43452. return tc != 0 ? tc->getItemId() : 0;
  43453. }
  43454. ToolbarItemComponent* Toolbar::getItemComponent (const int itemIndex) const throw()
  43455. {
  43456. return items [itemIndex];
  43457. }
  43458. ToolbarItemComponent* Toolbar::getNextActiveComponent (int index, const int delta) const
  43459. {
  43460. for (;;)
  43461. {
  43462. index += delta;
  43463. ToolbarItemComponent* const tc = getItemComponent (index);
  43464. if (tc == 0)
  43465. break;
  43466. if (tc->isActive)
  43467. return tc;
  43468. }
  43469. return 0;
  43470. }
  43471. void Toolbar::setStyle (const ToolbarItemStyle& newStyle)
  43472. {
  43473. if (toolbarStyle != newStyle)
  43474. {
  43475. toolbarStyle = newStyle;
  43476. updateAllItemPositions (false);
  43477. }
  43478. }
  43479. const String Toolbar::toString() const
  43480. {
  43481. String s ("TB:");
  43482. for (int i = 0; i < getNumItems(); ++i)
  43483. s << getItemId(i) << ' ';
  43484. return s.trimEnd();
  43485. }
  43486. bool Toolbar::restoreFromString (ToolbarItemFactory& factoryToUse,
  43487. const String& savedVersion)
  43488. {
  43489. if (! savedVersion.startsWith ("TB:"))
  43490. return false;
  43491. StringArray tokens;
  43492. tokens.addTokens (savedVersion.substring (3), false);
  43493. clear();
  43494. for (int i = 0; i < tokens.size(); ++i)
  43495. addItemInternal (factoryToUse, tokens[i].getIntValue(), -1);
  43496. resized();
  43497. return true;
  43498. }
  43499. void Toolbar::paint (Graphics& g)
  43500. {
  43501. getLookAndFeel().paintToolbarBackground (g, getWidth(), getHeight(), *this);
  43502. }
  43503. int Toolbar::getThickness() const throw()
  43504. {
  43505. return vertical ? getWidth() : getHeight();
  43506. }
  43507. int Toolbar::getLength() const throw()
  43508. {
  43509. return vertical ? getHeight() : getWidth();
  43510. }
  43511. void Toolbar::setEditingActive (const bool active)
  43512. {
  43513. if (isEditingActive != active)
  43514. {
  43515. isEditingActive = active;
  43516. updateAllItemPositions (false);
  43517. }
  43518. }
  43519. void Toolbar::resized()
  43520. {
  43521. updateAllItemPositions (false);
  43522. }
  43523. void Toolbar::updateAllItemPositions (const bool animate)
  43524. {
  43525. if (getWidth() > 0 && getHeight() > 0)
  43526. {
  43527. StretchableObjectResizer resizer;
  43528. int i;
  43529. for (i = 0; i < items.size(); ++i)
  43530. {
  43531. ToolbarItemComponent* const tc = items.getUnchecked(i);
  43532. tc->setEditingMode (isEditingActive ? ToolbarItemComponent::editableOnToolbar
  43533. : ToolbarItemComponent::normalMode);
  43534. tc->setStyle (toolbarStyle);
  43535. ToolbarSpacerComp* const spacer = dynamic_cast <ToolbarSpacerComp*> (tc);
  43536. int preferredSize = 1, minSize = 1, maxSize = 1;
  43537. if (tc->getToolbarItemSizes (getThickness(), isVertical(),
  43538. preferredSize, minSize, maxSize))
  43539. {
  43540. tc->isActive = true;
  43541. resizer.addItem (preferredSize, minSize, maxSize,
  43542. spacer != 0 ? spacer->getResizeOrder() : 2);
  43543. }
  43544. else
  43545. {
  43546. tc->isActive = false;
  43547. tc->setVisible (false);
  43548. }
  43549. }
  43550. resizer.resizeToFit (getLength());
  43551. int totalLength = 0;
  43552. for (i = 0; i < resizer.getNumItems(); ++i)
  43553. totalLength += (int) resizer.getItemSize (i);
  43554. const bool itemsOffTheEnd = totalLength > getLength();
  43555. const int extrasButtonSize = getThickness() / 2;
  43556. missingItemsButton->setSize (extrasButtonSize, extrasButtonSize);
  43557. missingItemsButton->setVisible (itemsOffTheEnd);
  43558. missingItemsButton->setEnabled (! isEditingActive);
  43559. if (vertical)
  43560. missingItemsButton->setCentrePosition (getWidth() / 2,
  43561. getHeight() - 4 - extrasButtonSize / 2);
  43562. else
  43563. missingItemsButton->setCentrePosition (getWidth() - 4 - extrasButtonSize / 2,
  43564. getHeight() / 2);
  43565. const int maxLength = itemsOffTheEnd ? (vertical ? missingItemsButton->getY()
  43566. : missingItemsButton->getX()) - 4
  43567. : getLength();
  43568. int pos = 0, activeIndex = 0;
  43569. for (i = 0; i < items.size(); ++i)
  43570. {
  43571. ToolbarItemComponent* const tc = items.getUnchecked(i);
  43572. if (tc->isActive)
  43573. {
  43574. const int size = (int) resizer.getItemSize (activeIndex++);
  43575. Rectangle<int> newBounds;
  43576. if (vertical)
  43577. newBounds.setBounds (0, pos, getWidth(), size);
  43578. else
  43579. newBounds.setBounds (pos, 0, size, getHeight());
  43580. if (animate)
  43581. {
  43582. animator.animateComponent (tc, newBounds, 200, 3.0, 0.0);
  43583. }
  43584. else
  43585. {
  43586. animator.cancelAnimation (tc, false);
  43587. tc->setBounds (newBounds);
  43588. }
  43589. pos += size;
  43590. tc->setVisible (pos <= maxLength
  43591. && ((! tc->isBeingDragged)
  43592. || tc->getEditingMode() == ToolbarItemComponent::editableOnPalette));
  43593. }
  43594. }
  43595. }
  43596. }
  43597. void Toolbar::buttonClicked (Button*)
  43598. {
  43599. jassert (missingItemsButton->isShowing());
  43600. if (missingItemsButton->isShowing())
  43601. {
  43602. PopupMenu m;
  43603. m.addCustomItem (1, new MissingItemsComponent (*this, getThickness()));
  43604. m.showAt (missingItemsButton);
  43605. }
  43606. }
  43607. bool Toolbar::isInterestedInDragSource (const String& sourceDescription,
  43608. Component* /*sourceComponent*/)
  43609. {
  43610. return sourceDescription == toolbarDragDescriptor && isEditingActive;
  43611. }
  43612. void Toolbar::itemDragMove (const String&, Component* sourceComponent, int x, int y)
  43613. {
  43614. ToolbarItemComponent* const tc = dynamic_cast <ToolbarItemComponent*> (sourceComponent);
  43615. if (tc != 0)
  43616. {
  43617. if (getNumItems() == 0)
  43618. {
  43619. if (tc->getEditingMode() == ToolbarItemComponent::editableOnPalette)
  43620. {
  43621. ToolbarItemPalette* const palette = tc->findParentComponentOfClass ((ToolbarItemPalette*) 0);
  43622. if (palette != 0)
  43623. palette->replaceComponent (tc);
  43624. }
  43625. else
  43626. {
  43627. jassert (tc->getEditingMode() == ToolbarItemComponent::editableOnToolbar);
  43628. }
  43629. items.add (tc);
  43630. addChildComponent (tc);
  43631. updateAllItemPositions (false);
  43632. }
  43633. else
  43634. {
  43635. for (int i = getNumItems(); --i >= 0;)
  43636. {
  43637. int currentIndex = getIndexOfChildComponent (tc);
  43638. if (currentIndex < 0)
  43639. {
  43640. if (tc->getEditingMode() == ToolbarItemComponent::editableOnPalette)
  43641. {
  43642. ToolbarItemPalette* const palette = tc->findParentComponentOfClass ((ToolbarItemPalette*) 0);
  43643. if (palette != 0)
  43644. palette->replaceComponent (tc);
  43645. }
  43646. else
  43647. {
  43648. jassert (tc->getEditingMode() == ToolbarItemComponent::editableOnToolbar);
  43649. }
  43650. items.add (tc);
  43651. addChildComponent (tc);
  43652. currentIndex = getIndexOfChildComponent (tc);
  43653. updateAllItemPositions (true);
  43654. }
  43655. int newIndex = currentIndex;
  43656. const int dragObjectLeft = vertical ? (y - tc->dragOffsetY) : (x - tc->dragOffsetX);
  43657. const int dragObjectRight = dragObjectLeft + (vertical ? tc->getHeight() : tc->getWidth());
  43658. const Rectangle<int> current (animator.getComponentDestination (getChildComponent (newIndex)));
  43659. ToolbarItemComponent* const prev = getNextActiveComponent (newIndex, -1);
  43660. if (prev != 0)
  43661. {
  43662. const Rectangle<int> previousPos (animator.getComponentDestination (prev));
  43663. if (abs (dragObjectLeft - (vertical ? previousPos.getY() : previousPos.getX())
  43664. < abs (dragObjectRight - (vertical ? current.getBottom() : current.getRight()))))
  43665. {
  43666. newIndex = getIndexOfChildComponent (prev);
  43667. }
  43668. }
  43669. ToolbarItemComponent* const next = getNextActiveComponent (newIndex, 1);
  43670. if (next != 0)
  43671. {
  43672. const Rectangle<int> nextPos (animator.getComponentDestination (next));
  43673. if (abs (dragObjectLeft - (vertical ? current.getY() : current.getX())
  43674. > abs (dragObjectRight - (vertical ? nextPos.getBottom() : nextPos.getRight()))))
  43675. {
  43676. newIndex = getIndexOfChildComponent (next) + 1;
  43677. }
  43678. }
  43679. if (newIndex != currentIndex)
  43680. {
  43681. items.removeValue (tc);
  43682. removeChildComponent (tc);
  43683. addChildComponent (tc, newIndex);
  43684. items.insert (newIndex, tc);
  43685. updateAllItemPositions (true);
  43686. }
  43687. else
  43688. {
  43689. break;
  43690. }
  43691. }
  43692. }
  43693. }
  43694. }
  43695. void Toolbar::itemDragExit (const String&, Component* sourceComponent)
  43696. {
  43697. ToolbarItemComponent* const tc = dynamic_cast <ToolbarItemComponent*> (sourceComponent);
  43698. if (tc != 0)
  43699. {
  43700. if (isParentOf (tc))
  43701. {
  43702. items.removeValue (tc);
  43703. removeChildComponent (tc);
  43704. updateAllItemPositions (true);
  43705. }
  43706. }
  43707. }
  43708. void Toolbar::itemDropped (const String&, Component*, int, int)
  43709. {
  43710. }
  43711. void Toolbar::mouseDown (const MouseEvent& e)
  43712. {
  43713. if (e.mods.isPopupMenu())
  43714. {
  43715. }
  43716. }
  43717. class ToolbarCustomisationDialog : public DialogWindow
  43718. {
  43719. public:
  43720. ToolbarCustomisationDialog (ToolbarItemFactory& factory,
  43721. Toolbar* const toolbar_,
  43722. const int optionFlags)
  43723. : DialogWindow (TRANS("Add/remove items from toolbar"), Colours::white, true, true),
  43724. toolbar (toolbar_)
  43725. {
  43726. setContentComponent (new CustomiserPanel (factory, toolbar, optionFlags), true, true);
  43727. setResizable (true, true);
  43728. setResizeLimits (400, 300, 1500, 1000);
  43729. positionNearBar();
  43730. }
  43731. ~ToolbarCustomisationDialog()
  43732. {
  43733. setContentComponent (0, true);
  43734. }
  43735. void closeButtonPressed()
  43736. {
  43737. setVisible (false);
  43738. }
  43739. bool canModalEventBeSentToComponent (const Component* comp)
  43740. {
  43741. return toolbar->isParentOf (comp);
  43742. }
  43743. void positionNearBar()
  43744. {
  43745. const Rectangle<int> screenSize (toolbar->getParentMonitorArea());
  43746. const int tbx = toolbar->getScreenX();
  43747. const int tby = toolbar->getScreenY();
  43748. const int gap = 8;
  43749. int x, y;
  43750. if (toolbar->isVertical())
  43751. {
  43752. y = tby;
  43753. if (tbx > screenSize.getCentreX())
  43754. x = tbx - getWidth() - gap;
  43755. else
  43756. x = tbx + toolbar->getWidth() + gap;
  43757. }
  43758. else
  43759. {
  43760. x = tbx + (toolbar->getWidth() - getWidth()) / 2;
  43761. if (tby > screenSize.getCentreY())
  43762. y = tby - getHeight() - gap;
  43763. else
  43764. y = tby + toolbar->getHeight() + gap;
  43765. }
  43766. setTopLeftPosition (x, y);
  43767. }
  43768. private:
  43769. Toolbar* const toolbar;
  43770. class CustomiserPanel : public Component,
  43771. private ComboBoxListener,
  43772. private ButtonListener
  43773. {
  43774. public:
  43775. CustomiserPanel (ToolbarItemFactory& factory_,
  43776. Toolbar* const toolbar_,
  43777. const int optionFlags)
  43778. : factory (factory_),
  43779. toolbar (toolbar_),
  43780. styleBox (0),
  43781. defaultButton (0)
  43782. {
  43783. addAndMakeVisible (palette = new ToolbarItemPalette (factory, toolbar));
  43784. if ((optionFlags & (Toolbar::allowIconsOnlyChoice
  43785. | Toolbar::allowIconsWithTextChoice
  43786. | Toolbar::allowTextOnlyChoice)) != 0)
  43787. {
  43788. addAndMakeVisible (styleBox = new ComboBox (String::empty));
  43789. styleBox->setEditableText (false);
  43790. if ((optionFlags & Toolbar::allowIconsOnlyChoice) != 0)
  43791. styleBox->addItem (TRANS("Show icons only"), 1);
  43792. if ((optionFlags & Toolbar::allowIconsWithTextChoice) != 0)
  43793. styleBox->addItem (TRANS("Show icons and descriptions"), 2);
  43794. if ((optionFlags & Toolbar::allowTextOnlyChoice) != 0)
  43795. styleBox->addItem (TRANS("Show descriptions only"), 3);
  43796. if (toolbar_->getStyle() == Toolbar::iconsOnly)
  43797. styleBox->setSelectedId (1);
  43798. else if (toolbar_->getStyle() == Toolbar::iconsWithText)
  43799. styleBox->setSelectedId (2);
  43800. else if (toolbar_->getStyle() == Toolbar::textOnly)
  43801. styleBox->setSelectedId (3);
  43802. styleBox->addListener (this);
  43803. }
  43804. if ((optionFlags & Toolbar::showResetToDefaultsButton) != 0)
  43805. {
  43806. addAndMakeVisible (defaultButton = new TextButton (TRANS ("Restore to default set of items")));
  43807. defaultButton->addButtonListener (this);
  43808. }
  43809. addAndMakeVisible (instructions = new Label (String::empty,
  43810. 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.")));
  43811. instructions->setFont (Font (13.0f));
  43812. setSize (500, 300);
  43813. }
  43814. ~CustomiserPanel()
  43815. {
  43816. deleteAllChildren();
  43817. }
  43818. void comboBoxChanged (ComboBox*)
  43819. {
  43820. if (styleBox->getSelectedId() == 1)
  43821. toolbar->setStyle (Toolbar::iconsOnly);
  43822. else if (styleBox->getSelectedId() == 2)
  43823. toolbar->setStyle (Toolbar::iconsWithText);
  43824. else if (styleBox->getSelectedId() == 3)
  43825. toolbar->setStyle (Toolbar::textOnly);
  43826. palette->resized(); // to make it update the styles
  43827. }
  43828. void buttonClicked (Button*)
  43829. {
  43830. toolbar->addDefaultItems (factory);
  43831. }
  43832. void paint (Graphics& g)
  43833. {
  43834. Colour background;
  43835. DialogWindow* const dw = findParentComponentOfClass ((DialogWindow*) 0);
  43836. if (dw != 0)
  43837. background = dw->getBackgroundColour();
  43838. g.setColour (background.contrasting().withAlpha (0.3f));
  43839. g.fillRect (palette->getX(), palette->getBottom() - 1, palette->getWidth(), 1);
  43840. }
  43841. void resized()
  43842. {
  43843. palette->setBounds (0, 0, getWidth(), getHeight() - 120);
  43844. if (styleBox != 0)
  43845. styleBox->setBounds (10, getHeight() - 110, 200, 22);
  43846. if (defaultButton != 0)
  43847. {
  43848. defaultButton->changeWidthToFitText (22);
  43849. defaultButton->setTopLeftPosition (240, getHeight() - 110);
  43850. }
  43851. instructions->setBounds (10, getHeight() - 80, getWidth() - 20, 80);
  43852. }
  43853. private:
  43854. ToolbarItemFactory& factory;
  43855. Toolbar* const toolbar;
  43856. Label* instructions;
  43857. ToolbarItemPalette* palette;
  43858. ComboBox* styleBox;
  43859. TextButton* defaultButton;
  43860. };
  43861. };
  43862. void Toolbar::showCustomisationDialog (ToolbarItemFactory& factory, const int optionFlags)
  43863. {
  43864. setEditingActive (true);
  43865. ToolbarCustomisationDialog dw (factory, this, optionFlags);
  43866. dw.runModalLoop();
  43867. jassert (isValidComponent()); // ? deleting the toolbar while it's being edited?
  43868. setEditingActive (false);
  43869. }
  43870. END_JUCE_NAMESPACE
  43871. /*** End of inlined file: juce_Toolbar.cpp ***/
  43872. /*** Start of inlined file: juce_ToolbarItemComponent.cpp ***/
  43873. BEGIN_JUCE_NAMESPACE
  43874. ToolbarItemFactory::ToolbarItemFactory()
  43875. {
  43876. }
  43877. ToolbarItemFactory::~ToolbarItemFactory()
  43878. {
  43879. }
  43880. class ItemDragAndDropOverlayComponent : public Component
  43881. {
  43882. public:
  43883. ItemDragAndDropOverlayComponent()
  43884. : isDragging (false)
  43885. {
  43886. setAlwaysOnTop (true);
  43887. setRepaintsOnMouseActivity (true);
  43888. setMouseCursor (MouseCursor::DraggingHandCursor);
  43889. }
  43890. ~ItemDragAndDropOverlayComponent()
  43891. {
  43892. }
  43893. void paint (Graphics& g)
  43894. {
  43895. ToolbarItemComponent* const tc = dynamic_cast <ToolbarItemComponent*> (getParentComponent());
  43896. if (isMouseOverOrDragging()
  43897. && tc != 0
  43898. && tc->getEditingMode() == ToolbarItemComponent::editableOnToolbar)
  43899. {
  43900. g.setColour (findColour (Toolbar::editingModeOutlineColourId, true));
  43901. g.drawRect (0, 0, getWidth(), getHeight(),
  43902. jmin (2, (getWidth() - 1) / 2, (getHeight() - 1) / 2));
  43903. }
  43904. }
  43905. void mouseDown (const MouseEvent& e)
  43906. {
  43907. isDragging = false;
  43908. ToolbarItemComponent* const tc = dynamic_cast <ToolbarItemComponent*> (getParentComponent());
  43909. if (tc != 0)
  43910. {
  43911. tc->dragOffsetX = e.x;
  43912. tc->dragOffsetY = e.y;
  43913. }
  43914. }
  43915. void mouseDrag (const MouseEvent& e)
  43916. {
  43917. if (! (isDragging || e.mouseWasClicked()))
  43918. {
  43919. isDragging = true;
  43920. DragAndDropContainer* const dnd = DragAndDropContainer::findParentDragContainerFor (this);
  43921. if (dnd != 0)
  43922. {
  43923. dnd->startDragging (Toolbar::toolbarDragDescriptor, getParentComponent(), 0, true);
  43924. ToolbarItemComponent* const tc = dynamic_cast <ToolbarItemComponent*> (getParentComponent());
  43925. if (tc != 0)
  43926. {
  43927. tc->isBeingDragged = true;
  43928. if (tc->getEditingMode() == ToolbarItemComponent::editableOnToolbar)
  43929. tc->setVisible (false);
  43930. }
  43931. }
  43932. }
  43933. }
  43934. void mouseUp (const MouseEvent&)
  43935. {
  43936. isDragging = false;
  43937. ToolbarItemComponent* const tc = dynamic_cast <ToolbarItemComponent*> (getParentComponent());
  43938. if (tc != 0)
  43939. {
  43940. tc->isBeingDragged = false;
  43941. Toolbar* const tb = tc->getToolbar();
  43942. if (tb != 0)
  43943. tb->updateAllItemPositions (true);
  43944. else if (tc->getEditingMode() == ToolbarItemComponent::editableOnToolbar)
  43945. delete tc;
  43946. }
  43947. }
  43948. void parentSizeChanged()
  43949. {
  43950. setBounds (0, 0, getParentWidth(), getParentHeight());
  43951. }
  43952. juce_UseDebuggingNewOperator
  43953. private:
  43954. bool isDragging;
  43955. ItemDragAndDropOverlayComponent (const ItemDragAndDropOverlayComponent&);
  43956. ItemDragAndDropOverlayComponent& operator= (const ItemDragAndDropOverlayComponent&);
  43957. };
  43958. ToolbarItemComponent::ToolbarItemComponent (const int itemId_,
  43959. const String& labelText,
  43960. const bool isBeingUsedAsAButton_)
  43961. : Button (labelText),
  43962. itemId (itemId_),
  43963. mode (normalMode),
  43964. toolbarStyle (Toolbar::iconsOnly),
  43965. dragOffsetX (0),
  43966. dragOffsetY (0),
  43967. isActive (true),
  43968. isBeingDragged (false),
  43969. isBeingUsedAsAButton (isBeingUsedAsAButton_)
  43970. {
  43971. // Your item ID can't be 0!
  43972. jassert (itemId_ != 0);
  43973. }
  43974. ToolbarItemComponent::~ToolbarItemComponent()
  43975. {
  43976. jassert (overlayComp == 0 || overlayComp->isValidComponent());
  43977. overlayComp = 0;
  43978. }
  43979. Toolbar* ToolbarItemComponent::getToolbar() const
  43980. {
  43981. return dynamic_cast <Toolbar*> (getParentComponent());
  43982. }
  43983. bool ToolbarItemComponent::isToolbarVertical() const
  43984. {
  43985. const Toolbar* const t = getToolbar();
  43986. return t != 0 && t->isVertical();
  43987. }
  43988. void ToolbarItemComponent::setStyle (const Toolbar::ToolbarItemStyle& newStyle)
  43989. {
  43990. if (toolbarStyle != newStyle)
  43991. {
  43992. toolbarStyle = newStyle;
  43993. repaint();
  43994. resized();
  43995. }
  43996. }
  43997. void ToolbarItemComponent::paintButton (Graphics& g, bool isMouseOver, bool isMouseDown)
  43998. {
  43999. if (isBeingUsedAsAButton)
  44000. getLookAndFeel().paintToolbarButtonBackground (g, getWidth(), getHeight(),
  44001. isMouseOver, isMouseDown, *this);
  44002. if (toolbarStyle != Toolbar::iconsOnly)
  44003. {
  44004. const int indent = contentArea.getX();
  44005. int y = indent;
  44006. int h = getHeight() - indent * 2;
  44007. if (toolbarStyle == Toolbar::iconsWithText)
  44008. {
  44009. y = contentArea.getBottom() + indent / 2;
  44010. h -= contentArea.getHeight();
  44011. }
  44012. getLookAndFeel().paintToolbarButtonLabel (g, indent, y, getWidth() - indent * 2, h,
  44013. getButtonText(), *this);
  44014. }
  44015. if (! contentArea.isEmpty())
  44016. {
  44017. g.saveState();
  44018. g.setOrigin (contentArea.getX(), contentArea.getY());
  44019. g.reduceClipRegion (0, 0, contentArea.getWidth(), contentArea.getHeight());
  44020. paintButtonArea (g, contentArea.getWidth(), contentArea.getHeight(), isMouseOver, isMouseDown);
  44021. g.restoreState();
  44022. }
  44023. }
  44024. void ToolbarItemComponent::resized()
  44025. {
  44026. if (toolbarStyle != Toolbar::textOnly)
  44027. {
  44028. const int indent = jmin (proportionOfWidth (0.08f),
  44029. proportionOfHeight (0.08f));
  44030. contentArea = Rectangle<int> (indent, indent,
  44031. getWidth() - indent * 2,
  44032. toolbarStyle == Toolbar::iconsWithText ? proportionOfHeight (0.55f)
  44033. : (getHeight() - indent * 2));
  44034. }
  44035. else
  44036. {
  44037. contentArea = Rectangle<int>();
  44038. }
  44039. contentAreaChanged (contentArea);
  44040. }
  44041. void ToolbarItemComponent::setEditingMode (const ToolbarEditingMode newMode)
  44042. {
  44043. if (mode != newMode)
  44044. {
  44045. mode = newMode;
  44046. repaint();
  44047. if (mode == normalMode)
  44048. {
  44049. jassert (overlayComp == 0 || overlayComp->isValidComponent());
  44050. overlayComp = 0;
  44051. }
  44052. else if (overlayComp == 0)
  44053. {
  44054. addAndMakeVisible (overlayComp = new ItemDragAndDropOverlayComponent());
  44055. overlayComp->parentSizeChanged();
  44056. }
  44057. resized();
  44058. }
  44059. }
  44060. END_JUCE_NAMESPACE
  44061. /*** End of inlined file: juce_ToolbarItemComponent.cpp ***/
  44062. /*** Start of inlined file: juce_ToolbarItemPalette.cpp ***/
  44063. BEGIN_JUCE_NAMESPACE
  44064. ToolbarItemPalette::ToolbarItemPalette (ToolbarItemFactory& factory_,
  44065. Toolbar* const toolbar_)
  44066. : factory (factory_),
  44067. toolbar (toolbar_)
  44068. {
  44069. Component* const itemHolder = new Component();
  44070. Array <int> allIds;
  44071. factory_.getAllToolbarItemIds (allIds);
  44072. for (int i = 0; i < allIds.size(); ++i)
  44073. {
  44074. ToolbarItemComponent* const tc = Toolbar::createItem (factory_, allIds.getUnchecked (i));
  44075. jassert (tc != 0);
  44076. if (tc != 0)
  44077. {
  44078. itemHolder->addAndMakeVisible (tc);
  44079. tc->setEditingMode (ToolbarItemComponent::editableOnPalette);
  44080. }
  44081. }
  44082. viewport = new Viewport();
  44083. viewport->setViewedComponent (itemHolder);
  44084. addAndMakeVisible (viewport);
  44085. }
  44086. ToolbarItemPalette::~ToolbarItemPalette()
  44087. {
  44088. viewport->getViewedComponent()->deleteAllChildren();
  44089. deleteAllChildren();
  44090. }
  44091. void ToolbarItemPalette::resized()
  44092. {
  44093. viewport->setBoundsInset (BorderSize (1));
  44094. Component* const itemHolder = viewport->getViewedComponent();
  44095. const int indent = 8;
  44096. const int preferredWidth = viewport->getWidth() - viewport->getScrollBarThickness() - indent;
  44097. const int height = toolbar->getThickness();
  44098. int x = indent;
  44099. int y = indent;
  44100. int maxX = 0;
  44101. for (int i = 0; i < itemHolder->getNumChildComponents(); ++i)
  44102. {
  44103. ToolbarItemComponent* const tc = dynamic_cast <ToolbarItemComponent*> (itemHolder->getChildComponent (i));
  44104. if (tc != 0)
  44105. {
  44106. tc->setStyle (toolbar->getStyle());
  44107. int preferredSize = 1, minSize = 1, maxSize = 1;
  44108. if (tc->getToolbarItemSizes (height, false, preferredSize, minSize, maxSize))
  44109. {
  44110. if (x + preferredSize > preferredWidth && x > indent)
  44111. {
  44112. x = indent;
  44113. y += height;
  44114. }
  44115. tc->setBounds (x, y, preferredSize, height);
  44116. x += preferredSize + 8;
  44117. maxX = jmax (maxX, x);
  44118. }
  44119. }
  44120. }
  44121. itemHolder->setSize (maxX, y + height + 8);
  44122. }
  44123. void ToolbarItemPalette::replaceComponent (ToolbarItemComponent* const comp)
  44124. {
  44125. ToolbarItemComponent* const tc = Toolbar::createItem (factory, comp->getItemId());
  44126. jassert (tc != 0);
  44127. if (tc != 0)
  44128. {
  44129. tc->setBounds (comp->getBounds());
  44130. tc->setStyle (toolbar->getStyle());
  44131. tc->setEditingMode (comp->getEditingMode());
  44132. viewport->getViewedComponent()->addAndMakeVisible (tc, getIndexOfChildComponent (comp));
  44133. }
  44134. }
  44135. END_JUCE_NAMESPACE
  44136. /*** End of inlined file: juce_ToolbarItemPalette.cpp ***/
  44137. /*** Start of inlined file: juce_TreeView.cpp ***/
  44138. BEGIN_JUCE_NAMESPACE
  44139. class TreeViewContentComponent : public Component,
  44140. public TooltipClient
  44141. {
  44142. public:
  44143. TreeViewContentComponent (TreeView& owner_)
  44144. : owner (owner_),
  44145. buttonUnderMouse (0),
  44146. isDragging (false)
  44147. {
  44148. }
  44149. ~TreeViewContentComponent()
  44150. {
  44151. deleteAllChildren();
  44152. }
  44153. void mouseDown (const MouseEvent& e)
  44154. {
  44155. updateButtonUnderMouse (e);
  44156. isDragging = false;
  44157. needSelectionOnMouseUp = false;
  44158. Rectangle<int> pos;
  44159. TreeViewItem* const item = findItemAt (e.y, pos);
  44160. if (item == 0)
  44161. return;
  44162. // (if the open/close buttons are hidden, we'll treat clicks to the left of the item
  44163. // as selection clicks)
  44164. if (e.x < pos.getX() && owner.openCloseButtonsVisible)
  44165. {
  44166. if (e.x >= pos.getX() - owner.getIndentSize())
  44167. item->setOpen (! item->isOpen());
  44168. // (clicks to the left of an open/close button are ignored)
  44169. }
  44170. else
  44171. {
  44172. // mouse-down inside the body of the item..
  44173. if (! owner.isMultiSelectEnabled())
  44174. item->setSelected (true, true);
  44175. else if (item->isSelected())
  44176. needSelectionOnMouseUp = ! e.mods.isPopupMenu();
  44177. else
  44178. selectBasedOnModifiers (item, e.mods);
  44179. if (e.x >= pos.getX())
  44180. item->itemClicked (e.withNewPosition (e.getPosition() - pos.getPosition()));
  44181. }
  44182. }
  44183. void mouseUp (const MouseEvent& e)
  44184. {
  44185. updateButtonUnderMouse (e);
  44186. if (needSelectionOnMouseUp && e.mouseWasClicked())
  44187. {
  44188. Rectangle<int> pos;
  44189. TreeViewItem* const item = findItemAt (e.y, pos);
  44190. if (item != 0)
  44191. selectBasedOnModifiers (item, e.mods);
  44192. }
  44193. }
  44194. void mouseDoubleClick (const MouseEvent& e)
  44195. {
  44196. if (e.getNumberOfClicks() != 3) // ignore triple clicks
  44197. {
  44198. Rectangle<int> pos;
  44199. TreeViewItem* const item = findItemAt (e.y, pos);
  44200. if (item != 0 && (e.x >= pos.getX() || ! owner.openCloseButtonsVisible))
  44201. item->itemDoubleClicked (e.withNewPosition (e.getPosition() - pos.getPosition()));
  44202. }
  44203. }
  44204. void mouseDrag (const MouseEvent& e)
  44205. {
  44206. if (isEnabled()
  44207. && ! (isDragging || e.mouseWasClicked()
  44208. || e.getDistanceFromDragStart() < 5
  44209. || e.mods.isPopupMenu()))
  44210. {
  44211. isDragging = true;
  44212. Rectangle<int> pos;
  44213. TreeViewItem* const item = findItemAt (e.getMouseDownY(), pos);
  44214. if (item != 0 && e.getMouseDownX() >= pos.getX())
  44215. {
  44216. const String dragDescription (item->getDragSourceDescription());
  44217. if (dragDescription.isNotEmpty())
  44218. {
  44219. DragAndDropContainer* const dragContainer
  44220. = DragAndDropContainer::findParentDragContainerFor (this);
  44221. if (dragContainer != 0)
  44222. {
  44223. pos.setSize (pos.getWidth(), item->itemHeight);
  44224. Image* dragImage = Component::createComponentSnapshot (pos, true);
  44225. dragImage->multiplyAllAlphas (0.6f);
  44226. Point<int> imageOffset (pos.getX() - e.x, pos.getY() - e.y);
  44227. dragContainer->startDragging (dragDescription, &owner, dragImage, true, &imageOffset);
  44228. }
  44229. else
  44230. {
  44231. // to be able to do a drag-and-drop operation, the treeview needs to
  44232. // be inside a component which is also a DragAndDropContainer.
  44233. jassertfalse
  44234. }
  44235. }
  44236. }
  44237. }
  44238. }
  44239. void mouseMove (const MouseEvent& e)
  44240. {
  44241. updateButtonUnderMouse (e);
  44242. }
  44243. void mouseExit (const MouseEvent& e)
  44244. {
  44245. updateButtonUnderMouse (e);
  44246. }
  44247. void paint (Graphics& g)
  44248. {
  44249. if (owner.rootItem != 0)
  44250. {
  44251. owner.handleAsyncUpdate();
  44252. if (! owner.rootItemVisible)
  44253. g.setOrigin (0, -owner.rootItem->itemHeight);
  44254. owner.rootItem->paintRecursively (g, getWidth());
  44255. }
  44256. }
  44257. TreeViewItem* findItemAt (int y, Rectangle<int>& itemPosition) const
  44258. {
  44259. if (owner.rootItem != 0)
  44260. {
  44261. owner.handleAsyncUpdate();
  44262. if (! owner.rootItemVisible)
  44263. y += owner.rootItem->itemHeight;
  44264. TreeViewItem* const ti = owner.rootItem->findItemRecursively (y);
  44265. if (ti != 0)
  44266. itemPosition = ti->getItemPosition (false);
  44267. return ti;
  44268. }
  44269. return 0;
  44270. }
  44271. void updateComponents()
  44272. {
  44273. const int visibleTop = -getY();
  44274. const int visibleBottom = visibleTop + getParentHeight();
  44275. BigInteger itemsToKeep;
  44276. TreeViewItem* item = owner.rootItem;
  44277. int y = (item != 0 && ! owner.rootItemVisible) ? -item->itemHeight : 0;
  44278. while (item != 0 && y < visibleBottom)
  44279. {
  44280. y += item->itemHeight;
  44281. if (y >= visibleTop)
  44282. {
  44283. const int index = rowComponentIds.indexOf (item->uid);
  44284. if (index < 0)
  44285. {
  44286. Component* const comp = item->createItemComponent();
  44287. if (comp != 0)
  44288. {
  44289. addAndMakeVisible (comp);
  44290. itemsToKeep.setBit (rowComponentItems.size());
  44291. rowComponentItems.add (item);
  44292. rowComponentIds.add (item->uid);
  44293. rowComponents.add (comp);
  44294. }
  44295. }
  44296. else
  44297. {
  44298. itemsToKeep.setBit (index);
  44299. }
  44300. }
  44301. item = item->getNextVisibleItem (true);
  44302. }
  44303. for (int i = rowComponentItems.size(); --i >= 0;)
  44304. {
  44305. Component* const comp = rowComponents.getUnchecked(i);
  44306. bool keep = false;
  44307. if (isParentOf (comp))
  44308. {
  44309. if (itemsToKeep[i])
  44310. {
  44311. const TreeViewItem* const item = rowComponentItems.getUnchecked(i);
  44312. Rectangle<int> pos (item->getItemPosition (false));
  44313. pos.setSize (pos.getWidth(), item->itemHeight);
  44314. if (pos.getBottom() >= visibleTop && pos.getY() < visibleBottom)
  44315. {
  44316. keep = true;
  44317. comp->setBounds (pos);
  44318. }
  44319. }
  44320. if ((! keep) && isMouseDraggingInChildCompOf (comp))
  44321. {
  44322. keep = true;
  44323. comp->setSize (0, 0);
  44324. }
  44325. }
  44326. if (! keep)
  44327. {
  44328. delete comp;
  44329. rowComponents.remove (i);
  44330. rowComponentIds.remove (i);
  44331. rowComponentItems.remove (i);
  44332. }
  44333. }
  44334. }
  44335. void updateButtonUnderMouse (const MouseEvent& e)
  44336. {
  44337. TreeViewItem* newItem = 0;
  44338. if (owner.openCloseButtonsVisible)
  44339. {
  44340. Rectangle<int> pos;
  44341. TreeViewItem* item = findItemAt (e.y, pos);
  44342. if (item != 0 && e.x < pos.getX() && e.x >= pos.getX() - owner.getIndentSize())
  44343. {
  44344. newItem = item;
  44345. if (! newItem->mightContainSubItems())
  44346. newItem = 0;
  44347. }
  44348. }
  44349. if (buttonUnderMouse != newItem)
  44350. {
  44351. if (buttonUnderMouse != 0 && containsItem (buttonUnderMouse))
  44352. {
  44353. const Rectangle<int> r (buttonUnderMouse->getItemPosition (false));
  44354. repaint (0, r.getY(), r.getX(), buttonUnderMouse->getItemHeight());
  44355. }
  44356. buttonUnderMouse = newItem;
  44357. if (buttonUnderMouse != 0)
  44358. {
  44359. const Rectangle<int> r (buttonUnderMouse->getItemPosition (false));
  44360. repaint (0, r.getY(), r.getX(), buttonUnderMouse->getItemHeight());
  44361. }
  44362. }
  44363. }
  44364. bool isMouseOverButton (TreeViewItem* const item) const throw()
  44365. {
  44366. return item == buttonUnderMouse;
  44367. }
  44368. void resized()
  44369. {
  44370. owner.itemsChanged();
  44371. }
  44372. const String getTooltip()
  44373. {
  44374. Rectangle<int> pos;
  44375. TreeViewItem* const item = findItemAt (getMouseXYRelative().getY(), pos);
  44376. if (item != 0)
  44377. return item->getTooltip();
  44378. return owner.getTooltip();
  44379. }
  44380. juce_UseDebuggingNewOperator
  44381. private:
  44382. TreeView& owner;
  44383. Array <TreeViewItem*> rowComponentItems;
  44384. Array <int> rowComponentIds;
  44385. Array <Component*> rowComponents;
  44386. TreeViewItem* buttonUnderMouse;
  44387. bool isDragging, needSelectionOnMouseUp;
  44388. void selectBasedOnModifiers (TreeViewItem* const item, const ModifierKeys& modifiers)
  44389. {
  44390. TreeViewItem* firstSelected = 0;
  44391. if (modifiers.isShiftDown() && ((firstSelected = owner.getSelectedItem (0)) != 0))
  44392. {
  44393. TreeViewItem* const lastSelected = owner.getSelectedItem (owner.getNumSelectedItems() - 1);
  44394. jassert (lastSelected != 0);
  44395. int rowStart = firstSelected->getRowNumberInTree();
  44396. int rowEnd = lastSelected->getRowNumberInTree();
  44397. if (rowStart > rowEnd)
  44398. swapVariables (rowStart, rowEnd);
  44399. int ourRow = item->getRowNumberInTree();
  44400. int otherEnd = ourRow < rowEnd ? rowStart : rowEnd;
  44401. if (ourRow > otherEnd)
  44402. swapVariables (ourRow, otherEnd);
  44403. for (int i = ourRow; i <= otherEnd; ++i)
  44404. owner.getItemOnRow (i)->setSelected (true, false);
  44405. }
  44406. else
  44407. {
  44408. const bool cmd = modifiers.isCommandDown();
  44409. item->setSelected ((! cmd) || ! item->isSelected(), ! cmd);
  44410. }
  44411. }
  44412. bool containsItem (TreeViewItem* const item) const
  44413. {
  44414. for (int i = rowComponentItems.size(); --i >= 0;)
  44415. if (rowComponentItems.getUnchecked(i) == item)
  44416. return true;
  44417. return false;
  44418. }
  44419. static bool isMouseDraggingInChildCompOf (Component* const comp)
  44420. {
  44421. for (int i = Desktop::getInstance().getNumMouseSources(); --i >= 0;)
  44422. {
  44423. MouseInputSource* const source = Desktop::getInstance().getMouseSource(i);
  44424. if (source->isDragging())
  44425. {
  44426. Component* const underMouse = source->getComponentUnderMouse();
  44427. if (underMouse != 0 && (comp == underMouse || comp->isParentOf (underMouse)))
  44428. return true;
  44429. }
  44430. }
  44431. return false;
  44432. }
  44433. TreeViewContentComponent (const TreeViewContentComponent&);
  44434. TreeViewContentComponent& operator= (const TreeViewContentComponent&);
  44435. };
  44436. class TreeView::TreeViewport : public Viewport
  44437. {
  44438. public:
  44439. TreeViewport() throw() : lastX (-1) {}
  44440. ~TreeViewport() throw() {}
  44441. void updateComponents (const bool triggerResize = false)
  44442. {
  44443. TreeViewContentComponent* const tvc = static_cast <TreeViewContentComponent*> (getViewedComponent());
  44444. if (tvc != 0)
  44445. {
  44446. if (triggerResize)
  44447. tvc->resized();
  44448. else
  44449. tvc->updateComponents();
  44450. }
  44451. repaint();
  44452. }
  44453. void visibleAreaChanged (int x, int, int, int)
  44454. {
  44455. const bool hasScrolledSideways = (x != lastX);
  44456. lastX = x;
  44457. updateComponents (hasScrolledSideways);
  44458. }
  44459. juce_UseDebuggingNewOperator
  44460. private:
  44461. int lastX;
  44462. TreeViewport (const TreeViewport&);
  44463. TreeViewport& operator= (const TreeViewport&);
  44464. };
  44465. TreeView::TreeView (const String& componentName)
  44466. : Component (componentName),
  44467. rootItem (0),
  44468. dragInsertPointHighlight (0),
  44469. dragTargetGroupHighlight (0),
  44470. indentSize (24),
  44471. defaultOpenness (false),
  44472. needsRecalculating (true),
  44473. rootItemVisible (true),
  44474. multiSelectEnabled (false),
  44475. openCloseButtonsVisible (true)
  44476. {
  44477. addAndMakeVisible (viewport = new TreeViewport());
  44478. viewport->setViewedComponent (new TreeViewContentComponent (*this));
  44479. viewport->setWantsKeyboardFocus (false);
  44480. setWantsKeyboardFocus (true);
  44481. }
  44482. TreeView::~TreeView()
  44483. {
  44484. if (rootItem != 0)
  44485. rootItem->setOwnerView (0);
  44486. deleteAllChildren();
  44487. }
  44488. void TreeView::setRootItem (TreeViewItem* const newRootItem)
  44489. {
  44490. if (rootItem != newRootItem)
  44491. {
  44492. if (newRootItem != 0)
  44493. {
  44494. jassert (newRootItem->ownerView == 0); // can't use a tree item in more than one tree at once..
  44495. if (newRootItem->ownerView != 0)
  44496. newRootItem->ownerView->setRootItem (0);
  44497. }
  44498. if (rootItem != 0)
  44499. rootItem->setOwnerView (0);
  44500. rootItem = newRootItem;
  44501. if (newRootItem != 0)
  44502. newRootItem->setOwnerView (this);
  44503. needsRecalculating = true;
  44504. handleAsyncUpdate();
  44505. if (rootItem != 0 && (defaultOpenness || ! rootItemVisible))
  44506. {
  44507. rootItem->setOpen (false); // force a re-open
  44508. rootItem->setOpen (true);
  44509. }
  44510. }
  44511. }
  44512. void TreeView::deleteRootItem()
  44513. {
  44514. const ScopedPointer <TreeViewItem> deleter (rootItem);
  44515. setRootItem (0);
  44516. }
  44517. void TreeView::setRootItemVisible (const bool shouldBeVisible)
  44518. {
  44519. rootItemVisible = shouldBeVisible;
  44520. if (rootItem != 0 && (defaultOpenness || ! rootItemVisible))
  44521. {
  44522. rootItem->setOpen (false); // force a re-open
  44523. rootItem->setOpen (true);
  44524. }
  44525. itemsChanged();
  44526. }
  44527. void TreeView::colourChanged()
  44528. {
  44529. setOpaque (findColour (backgroundColourId).isOpaque());
  44530. repaint();
  44531. }
  44532. void TreeView::setIndentSize (const int newIndentSize)
  44533. {
  44534. if (indentSize != newIndentSize)
  44535. {
  44536. indentSize = newIndentSize;
  44537. resized();
  44538. }
  44539. }
  44540. void TreeView::setDefaultOpenness (const bool isOpenByDefault)
  44541. {
  44542. if (defaultOpenness != isOpenByDefault)
  44543. {
  44544. defaultOpenness = isOpenByDefault;
  44545. itemsChanged();
  44546. }
  44547. }
  44548. void TreeView::setMultiSelectEnabled (const bool canMultiSelect)
  44549. {
  44550. multiSelectEnabled = canMultiSelect;
  44551. }
  44552. void TreeView::setOpenCloseButtonsVisible (const bool shouldBeVisible)
  44553. {
  44554. if (openCloseButtonsVisible != shouldBeVisible)
  44555. {
  44556. openCloseButtonsVisible = shouldBeVisible;
  44557. itemsChanged();
  44558. }
  44559. }
  44560. Viewport* TreeView::getViewport() const throw()
  44561. {
  44562. return viewport;
  44563. }
  44564. void TreeView::clearSelectedItems()
  44565. {
  44566. if (rootItem != 0)
  44567. rootItem->deselectAllRecursively();
  44568. }
  44569. int TreeView::getNumSelectedItems() const throw()
  44570. {
  44571. return (rootItem != 0) ? rootItem->countSelectedItemsRecursively() : 0;
  44572. }
  44573. TreeViewItem* TreeView::getSelectedItem (const int index) const throw()
  44574. {
  44575. return (rootItem != 0) ? rootItem->getSelectedItemWithIndex (index) : 0;
  44576. }
  44577. int TreeView::getNumRowsInTree() const
  44578. {
  44579. if (rootItem != 0)
  44580. return rootItem->getNumRows() - (rootItemVisible ? 0 : 1);
  44581. return 0;
  44582. }
  44583. TreeViewItem* TreeView::getItemOnRow (int index) const
  44584. {
  44585. if (! rootItemVisible)
  44586. ++index;
  44587. if (rootItem != 0 && index >= 0)
  44588. return rootItem->getItemOnRow (index);
  44589. return 0;
  44590. }
  44591. TreeViewItem* TreeView::getItemAt (int y) const throw()
  44592. {
  44593. TreeViewContentComponent* const tc = static_cast <TreeViewContentComponent*> (viewport->getViewedComponent());
  44594. Rectangle<int> pos;
  44595. return tc->findItemAt (relativePositionToOtherComponent (tc, Point<int> (0, y)).getY(), pos);
  44596. }
  44597. TreeViewItem* TreeView::findItemFromIdentifierString (const String& identifierString) const
  44598. {
  44599. if (rootItem == 0)
  44600. return 0;
  44601. return rootItem->findItemFromIdentifierString (identifierString);
  44602. }
  44603. XmlElement* TreeView::getOpennessState (const bool alsoIncludeScrollPosition) const
  44604. {
  44605. XmlElement* e = 0;
  44606. if (rootItem != 0)
  44607. {
  44608. e = rootItem->getOpennessState();
  44609. if (e != 0 && alsoIncludeScrollPosition)
  44610. e->setAttribute ("scrollPos", viewport->getViewPositionY());
  44611. }
  44612. return e;
  44613. }
  44614. void TreeView::restoreOpennessState (const XmlElement& newState)
  44615. {
  44616. if (rootItem != 0)
  44617. {
  44618. rootItem->restoreOpennessState (newState);
  44619. if (newState.hasAttribute ("scrollPos"))
  44620. viewport->setViewPosition (viewport->getViewPositionX(),
  44621. newState.getIntAttribute ("scrollPos"));
  44622. }
  44623. }
  44624. void TreeView::paint (Graphics& g)
  44625. {
  44626. g.fillAll (findColour (backgroundColourId));
  44627. }
  44628. void TreeView::resized()
  44629. {
  44630. viewport->setBounds (0, 0, getWidth(), getHeight());
  44631. itemsChanged();
  44632. handleAsyncUpdate();
  44633. }
  44634. void TreeView::enablementChanged()
  44635. {
  44636. repaint();
  44637. }
  44638. void TreeView::moveSelectedRow (int delta)
  44639. {
  44640. if (delta == 0)
  44641. return;
  44642. int rowSelected = 0;
  44643. TreeViewItem* const firstSelected = getSelectedItem (0);
  44644. if (firstSelected != 0)
  44645. rowSelected = firstSelected->getRowNumberInTree();
  44646. rowSelected = jlimit (0, getNumRowsInTree() - 1, rowSelected + delta);
  44647. for (;;)
  44648. {
  44649. TreeViewItem* item = getItemOnRow (rowSelected);
  44650. if (item != 0)
  44651. {
  44652. if (! item->canBeSelected())
  44653. {
  44654. // if the row we want to highlight doesn't allow it, try skipping
  44655. // to the next item..
  44656. const int nextRowToTry = jlimit (0, getNumRowsInTree() - 1,
  44657. rowSelected + (delta < 0 ? -1 : 1));
  44658. if (rowSelected != nextRowToTry)
  44659. {
  44660. rowSelected = nextRowToTry;
  44661. continue;
  44662. }
  44663. else
  44664. {
  44665. break;
  44666. }
  44667. }
  44668. item->setSelected (true, true);
  44669. scrollToKeepItemVisible (item);
  44670. }
  44671. break;
  44672. }
  44673. }
  44674. void TreeView::scrollToKeepItemVisible (TreeViewItem* item)
  44675. {
  44676. if (item != 0 && item->ownerView == this)
  44677. {
  44678. handleAsyncUpdate();
  44679. item = item->getDeepestOpenParentItem();
  44680. int y = item->y;
  44681. int viewTop = viewport->getViewPositionY();
  44682. if (y < viewTop)
  44683. {
  44684. viewport->setViewPosition (viewport->getViewPositionX(), y);
  44685. }
  44686. else if (y + item->itemHeight > viewTop + viewport->getViewHeight())
  44687. {
  44688. viewport->setViewPosition (viewport->getViewPositionX(),
  44689. (y + item->itemHeight) - viewport->getViewHeight());
  44690. }
  44691. }
  44692. }
  44693. bool TreeView::keyPressed (const KeyPress& key)
  44694. {
  44695. if (key.isKeyCode (KeyPress::upKey))
  44696. {
  44697. moveSelectedRow (-1);
  44698. }
  44699. else if (key.isKeyCode (KeyPress::downKey))
  44700. {
  44701. moveSelectedRow (1);
  44702. }
  44703. else if (key.isKeyCode (KeyPress::pageDownKey) || key.isKeyCode (KeyPress::pageUpKey))
  44704. {
  44705. if (rootItem != 0)
  44706. {
  44707. int rowsOnScreen = getHeight() / jmax (1, rootItem->itemHeight);
  44708. if (key.isKeyCode (KeyPress::pageUpKey))
  44709. rowsOnScreen = -rowsOnScreen;
  44710. moveSelectedRow (rowsOnScreen);
  44711. }
  44712. }
  44713. else if (key.isKeyCode (KeyPress::homeKey))
  44714. {
  44715. moveSelectedRow (-0x3fffffff);
  44716. }
  44717. else if (key.isKeyCode (KeyPress::endKey))
  44718. {
  44719. moveSelectedRow (0x3fffffff);
  44720. }
  44721. else if (key.isKeyCode (KeyPress::returnKey))
  44722. {
  44723. TreeViewItem* const firstSelected = getSelectedItem (0);
  44724. if (firstSelected != 0)
  44725. firstSelected->setOpen (! firstSelected->isOpen());
  44726. }
  44727. else if (key.isKeyCode (KeyPress::leftKey))
  44728. {
  44729. TreeViewItem* const firstSelected = getSelectedItem (0);
  44730. if (firstSelected != 0)
  44731. {
  44732. if (firstSelected->isOpen())
  44733. {
  44734. firstSelected->setOpen (false);
  44735. }
  44736. else
  44737. {
  44738. TreeViewItem* parent = firstSelected->parentItem;
  44739. if ((! rootItemVisible) && parent == rootItem)
  44740. parent = 0;
  44741. if (parent != 0)
  44742. {
  44743. parent->setSelected (true, true);
  44744. scrollToKeepItemVisible (parent);
  44745. }
  44746. }
  44747. }
  44748. }
  44749. else if (key.isKeyCode (KeyPress::rightKey))
  44750. {
  44751. TreeViewItem* const firstSelected = getSelectedItem (0);
  44752. if (firstSelected != 0)
  44753. {
  44754. if (firstSelected->isOpen() || ! firstSelected->mightContainSubItems())
  44755. moveSelectedRow (1);
  44756. else
  44757. firstSelected->setOpen (true);
  44758. }
  44759. }
  44760. else
  44761. {
  44762. return false;
  44763. }
  44764. return true;
  44765. }
  44766. void TreeView::itemsChanged() throw()
  44767. {
  44768. needsRecalculating = true;
  44769. repaint();
  44770. triggerAsyncUpdate();
  44771. }
  44772. void TreeView::handleAsyncUpdate()
  44773. {
  44774. if (needsRecalculating)
  44775. {
  44776. needsRecalculating = false;
  44777. const ScopedLock sl (nodeAlterationLock);
  44778. if (rootItem != 0)
  44779. rootItem->updatePositions (rootItemVisible ? 0 : -rootItem->itemHeight);
  44780. viewport->updateComponents();
  44781. if (rootItem != 0)
  44782. {
  44783. viewport->getViewedComponent()
  44784. ->setSize (jmax (viewport->getMaximumVisibleWidth(), rootItem->totalWidth),
  44785. rootItem->totalHeight - (rootItemVisible ? 0 : rootItem->itemHeight));
  44786. }
  44787. else
  44788. {
  44789. viewport->getViewedComponent()->setSize (0, 0);
  44790. }
  44791. }
  44792. }
  44793. class TreeView::InsertPointHighlight : public Component
  44794. {
  44795. public:
  44796. InsertPointHighlight()
  44797. : lastItem (0)
  44798. {
  44799. setSize (100, 12);
  44800. setAlwaysOnTop (true);
  44801. setInterceptsMouseClicks (false, false);
  44802. }
  44803. ~InsertPointHighlight() {}
  44804. void setTargetPosition (TreeViewItem* const item, int insertIndex, const int x, const int y, const int width) throw()
  44805. {
  44806. lastItem = item;
  44807. lastIndex = insertIndex;
  44808. const int offset = getHeight() / 2;
  44809. setBounds (x - offset, y - offset, width - (x - offset), getHeight());
  44810. }
  44811. void paint (Graphics& g)
  44812. {
  44813. Path p;
  44814. const float h = (float) getHeight();
  44815. p.addEllipse (2.0f, 2.0f, h - 4.0f, h - 4.0f);
  44816. p.startNewSubPath (h - 2.0f, h / 2.0f);
  44817. p.lineTo ((float) getWidth(), h / 2.0f);
  44818. g.setColour (findColour (TreeView::dragAndDropIndicatorColourId, true));
  44819. g.strokePath (p, PathStrokeType (2.0f));
  44820. }
  44821. TreeViewItem* lastItem;
  44822. int lastIndex;
  44823. private:
  44824. InsertPointHighlight (const InsertPointHighlight&);
  44825. InsertPointHighlight& operator= (const InsertPointHighlight&);
  44826. };
  44827. class TreeView::TargetGroupHighlight : public Component
  44828. {
  44829. public:
  44830. TargetGroupHighlight()
  44831. {
  44832. setAlwaysOnTop (true);
  44833. setInterceptsMouseClicks (false, false);
  44834. }
  44835. ~TargetGroupHighlight() {}
  44836. void setTargetPosition (TreeViewItem* const item) throw()
  44837. {
  44838. Rectangle<int> r (item->getItemPosition (true));
  44839. r.setHeight (item->getItemHeight());
  44840. setBounds (r);
  44841. }
  44842. void paint (Graphics& g)
  44843. {
  44844. g.setColour (findColour (TreeView::dragAndDropIndicatorColourId, true));
  44845. g.drawRoundedRectangle (1.0f, 1.0f, getWidth() - 2.0f, getHeight() - 2.0f, 3.0f, 2.0f);
  44846. }
  44847. private:
  44848. TargetGroupHighlight (const TargetGroupHighlight&);
  44849. TargetGroupHighlight& operator= (const TargetGroupHighlight&);
  44850. };
  44851. void TreeView::showDragHighlight (TreeViewItem* item, int insertIndex, int x, int y) throw()
  44852. {
  44853. beginDragAutoRepeat (1000 / 30);
  44854. if (dragInsertPointHighlight == 0)
  44855. {
  44856. addAndMakeVisible (dragInsertPointHighlight = new InsertPointHighlight());
  44857. addAndMakeVisible (dragTargetGroupHighlight = new TargetGroupHighlight());
  44858. }
  44859. dragInsertPointHighlight->setTargetPosition (item, insertIndex, x, y, viewport->getViewWidth());
  44860. dragTargetGroupHighlight->setTargetPosition (item);
  44861. }
  44862. void TreeView::hideDragHighlight() throw()
  44863. {
  44864. deleteAndZero (dragInsertPointHighlight);
  44865. deleteAndZero (dragTargetGroupHighlight);
  44866. }
  44867. TreeViewItem* TreeView::getInsertPosition (int& x, int& y, int& insertIndex,
  44868. const StringArray& files, const String& sourceDescription,
  44869. Component* sourceComponent) const throw()
  44870. {
  44871. insertIndex = 0;
  44872. TreeViewItem* item = getItemAt (y);
  44873. if (item == 0)
  44874. return 0;
  44875. Rectangle<int> itemPos (item->getItemPosition (true));
  44876. insertIndex = item->getIndexInParent();
  44877. const int oldY = y;
  44878. y = itemPos.getY();
  44879. if (item->getNumSubItems() == 0 || ! item->isOpen())
  44880. {
  44881. if (files.size() > 0 ? item->isInterestedInFileDrag (files)
  44882. : item->isInterestedInDragSource (sourceDescription, sourceComponent))
  44883. {
  44884. // Check if we're trying to drag into an empty group item..
  44885. if (oldY > itemPos.getY() + itemPos.getHeight() / 4
  44886. && oldY < itemPos.getBottom() - itemPos.getHeight() / 4)
  44887. {
  44888. insertIndex = 0;
  44889. x = itemPos.getX() + getIndentSize();
  44890. y = itemPos.getBottom();
  44891. return item;
  44892. }
  44893. }
  44894. }
  44895. if (oldY > itemPos.getCentreY())
  44896. {
  44897. y += item->getItemHeight();
  44898. while (item->isLastOfSiblings() && item->parentItem != 0
  44899. && item->parentItem->parentItem != 0)
  44900. {
  44901. if (x > itemPos.getX())
  44902. break;
  44903. item = item->parentItem;
  44904. itemPos = item->getItemPosition (true);
  44905. insertIndex = item->getIndexInParent();
  44906. }
  44907. ++insertIndex;
  44908. }
  44909. x = itemPos.getX();
  44910. return item->parentItem;
  44911. }
  44912. void TreeView::handleDrag (const StringArray& files, const String& sourceDescription, Component* sourceComponent, int x, int y)
  44913. {
  44914. const bool scrolled = viewport->autoScroll (x, y, 20, 10);
  44915. int insertIndex;
  44916. TreeViewItem* const item = getInsertPosition (x, y, insertIndex, files, sourceDescription, sourceComponent);
  44917. if (item != 0)
  44918. {
  44919. if (scrolled || dragInsertPointHighlight == 0
  44920. || dragInsertPointHighlight->lastItem != item
  44921. || dragInsertPointHighlight->lastIndex != insertIndex)
  44922. {
  44923. if (files.size() > 0 ? item->isInterestedInFileDrag (files)
  44924. : item->isInterestedInDragSource (sourceDescription, sourceComponent))
  44925. showDragHighlight (item, insertIndex, x, y);
  44926. else
  44927. hideDragHighlight();
  44928. }
  44929. }
  44930. else
  44931. {
  44932. hideDragHighlight();
  44933. }
  44934. }
  44935. void TreeView::handleDrop (const StringArray& files, const String& sourceDescription, Component* sourceComponent, int x, int y)
  44936. {
  44937. hideDragHighlight();
  44938. int insertIndex;
  44939. TreeViewItem* const item = getInsertPosition (x, y, insertIndex, files, sourceDescription, sourceComponent);
  44940. if (item != 0)
  44941. {
  44942. if (files.size() > 0)
  44943. {
  44944. if (item->isInterestedInFileDrag (files))
  44945. item->filesDropped (files, insertIndex);
  44946. }
  44947. else
  44948. {
  44949. if (item->isInterestedInDragSource (sourceDescription, sourceComponent))
  44950. item->itemDropped (sourceDescription, sourceComponent, insertIndex);
  44951. }
  44952. }
  44953. }
  44954. bool TreeView::isInterestedInFileDrag (const StringArray&)
  44955. {
  44956. return true;
  44957. }
  44958. void TreeView::fileDragEnter (const StringArray& files, int x, int y)
  44959. {
  44960. fileDragMove (files, x, y);
  44961. }
  44962. void TreeView::fileDragMove (const StringArray& files, int x, int y)
  44963. {
  44964. handleDrag (files, String::empty, 0, x, y);
  44965. }
  44966. void TreeView::fileDragExit (const StringArray&)
  44967. {
  44968. hideDragHighlight();
  44969. }
  44970. void TreeView::filesDropped (const StringArray& files, int x, int y)
  44971. {
  44972. handleDrop (files, String::empty, 0, x, y);
  44973. }
  44974. bool TreeView::isInterestedInDragSource (const String& /*sourceDescription*/, Component* /*sourceComponent*/)
  44975. {
  44976. return true;
  44977. }
  44978. void TreeView::itemDragEnter (const String& sourceDescription, Component* sourceComponent, int x, int y)
  44979. {
  44980. itemDragMove (sourceDescription, sourceComponent, x, y);
  44981. }
  44982. void TreeView::itemDragMove (const String& sourceDescription, Component* sourceComponent, int x, int y)
  44983. {
  44984. handleDrag (StringArray(), sourceDescription, sourceComponent, x, y);
  44985. }
  44986. void TreeView::itemDragExit (const String& /*sourceDescription*/, Component* /*sourceComponent*/)
  44987. {
  44988. hideDragHighlight();
  44989. }
  44990. void TreeView::itemDropped (const String& sourceDescription, Component* sourceComponent, int x, int y)
  44991. {
  44992. handleDrop (StringArray(), sourceDescription, sourceComponent, x, y);
  44993. }
  44994. enum TreeViewOpenness
  44995. {
  44996. opennessDefault = 0,
  44997. opennessClosed = 1,
  44998. opennessOpen = 2
  44999. };
  45000. TreeViewItem::TreeViewItem()
  45001. : ownerView (0),
  45002. parentItem (0),
  45003. y (0),
  45004. itemHeight (0),
  45005. totalHeight (0),
  45006. selected (false),
  45007. redrawNeeded (true),
  45008. drawLinesInside (true),
  45009. drawsInLeftMargin (false),
  45010. openness (opennessDefault)
  45011. {
  45012. static int nextUID = 0;
  45013. uid = nextUID++;
  45014. }
  45015. TreeViewItem::~TreeViewItem()
  45016. {
  45017. }
  45018. const String TreeViewItem::getUniqueName() const
  45019. {
  45020. return String::empty;
  45021. }
  45022. void TreeViewItem::itemOpennessChanged (bool)
  45023. {
  45024. }
  45025. int TreeViewItem::getNumSubItems() const throw()
  45026. {
  45027. return subItems.size();
  45028. }
  45029. TreeViewItem* TreeViewItem::getSubItem (const int index) const throw()
  45030. {
  45031. return subItems [index];
  45032. }
  45033. void TreeViewItem::clearSubItems()
  45034. {
  45035. if (subItems.size() > 0)
  45036. {
  45037. if (ownerView != 0)
  45038. {
  45039. const ScopedLock sl (ownerView->nodeAlterationLock);
  45040. subItems.clear();
  45041. treeHasChanged();
  45042. }
  45043. else
  45044. {
  45045. subItems.clear();
  45046. }
  45047. }
  45048. }
  45049. void TreeViewItem::addSubItem (TreeViewItem* const newItem, const int insertPosition)
  45050. {
  45051. if (newItem != 0)
  45052. {
  45053. newItem->parentItem = this;
  45054. newItem->setOwnerView (ownerView);
  45055. newItem->y = 0;
  45056. newItem->itemHeight = newItem->getItemHeight();
  45057. newItem->totalHeight = 0;
  45058. newItem->itemWidth = newItem->getItemWidth();
  45059. newItem->totalWidth = 0;
  45060. if (ownerView != 0)
  45061. {
  45062. const ScopedLock sl (ownerView->nodeAlterationLock);
  45063. subItems.insert (insertPosition, newItem);
  45064. treeHasChanged();
  45065. if (newItem->isOpen())
  45066. newItem->itemOpennessChanged (true);
  45067. }
  45068. else
  45069. {
  45070. subItems.insert (insertPosition, newItem);
  45071. if (newItem->isOpen())
  45072. newItem->itemOpennessChanged (true);
  45073. }
  45074. }
  45075. }
  45076. void TreeViewItem::removeSubItem (const int index, const bool deleteItem)
  45077. {
  45078. if (ownerView != 0)
  45079. {
  45080. const ScopedLock sl (ownerView->nodeAlterationLock);
  45081. if (((unsigned int) index) < (unsigned int) subItems.size())
  45082. {
  45083. subItems.remove (index, deleteItem);
  45084. treeHasChanged();
  45085. }
  45086. }
  45087. else
  45088. {
  45089. subItems.remove (index, deleteItem);
  45090. }
  45091. }
  45092. bool TreeViewItem::isOpen() const throw()
  45093. {
  45094. if (openness == opennessDefault)
  45095. return ownerView != 0 && ownerView->defaultOpenness;
  45096. else
  45097. return openness == opennessOpen;
  45098. }
  45099. void TreeViewItem::setOpen (const bool shouldBeOpen)
  45100. {
  45101. if (isOpen() != shouldBeOpen)
  45102. {
  45103. openness = shouldBeOpen ? opennessOpen
  45104. : opennessClosed;
  45105. treeHasChanged();
  45106. itemOpennessChanged (isOpen());
  45107. }
  45108. }
  45109. bool TreeViewItem::isSelected() const throw()
  45110. {
  45111. return selected;
  45112. }
  45113. void TreeViewItem::deselectAllRecursively()
  45114. {
  45115. setSelected (false, false);
  45116. for (int i = 0; i < subItems.size(); ++i)
  45117. subItems.getUnchecked(i)->deselectAllRecursively();
  45118. }
  45119. void TreeViewItem::setSelected (const bool shouldBeSelected,
  45120. const bool deselectOtherItemsFirst)
  45121. {
  45122. if (shouldBeSelected && ! canBeSelected())
  45123. return;
  45124. if (deselectOtherItemsFirst)
  45125. getTopLevelItem()->deselectAllRecursively();
  45126. if (shouldBeSelected != selected)
  45127. {
  45128. selected = shouldBeSelected;
  45129. if (ownerView != 0)
  45130. ownerView->repaint();
  45131. itemSelectionChanged (shouldBeSelected);
  45132. }
  45133. }
  45134. void TreeViewItem::paintItem (Graphics&, int, int)
  45135. {
  45136. }
  45137. void TreeViewItem::paintOpenCloseButton (Graphics& g, int width, int height, bool isMouseOver)
  45138. {
  45139. ownerView->getLookAndFeel()
  45140. .drawTreeviewPlusMinusBox (g, 0, 0, width, height, ! isOpen(), isMouseOver);
  45141. }
  45142. void TreeViewItem::itemClicked (const MouseEvent&)
  45143. {
  45144. }
  45145. void TreeViewItem::itemDoubleClicked (const MouseEvent&)
  45146. {
  45147. if (mightContainSubItems())
  45148. setOpen (! isOpen());
  45149. }
  45150. void TreeViewItem::itemSelectionChanged (bool)
  45151. {
  45152. }
  45153. const String TreeViewItem::getTooltip()
  45154. {
  45155. return String::empty;
  45156. }
  45157. const String TreeViewItem::getDragSourceDescription()
  45158. {
  45159. return String::empty;
  45160. }
  45161. bool TreeViewItem::isInterestedInFileDrag (const StringArray&)
  45162. {
  45163. return false;
  45164. }
  45165. void TreeViewItem::filesDropped (const StringArray& /*files*/, int /*insertIndex*/)
  45166. {
  45167. }
  45168. bool TreeViewItem::isInterestedInDragSource (const String& /*sourceDescription*/, Component* /*sourceComponent*/)
  45169. {
  45170. return false;
  45171. }
  45172. void TreeViewItem::itemDropped (const String& /*sourceDescription*/, Component* /*sourceComponent*/, int /*insertIndex*/)
  45173. {
  45174. }
  45175. const Rectangle<int> TreeViewItem::getItemPosition (const bool relativeToTreeViewTopLeft) const throw()
  45176. {
  45177. const int indentX = getIndentX();
  45178. int width = itemWidth;
  45179. if (ownerView != 0 && width < 0)
  45180. width = ownerView->viewport->getViewWidth() - indentX;
  45181. Rectangle<int> r (indentX, y, jmax (0, width), totalHeight);
  45182. if (relativeToTreeViewTopLeft)
  45183. r -= ownerView->viewport->getViewPosition();
  45184. return r;
  45185. }
  45186. void TreeViewItem::treeHasChanged() const throw()
  45187. {
  45188. if (ownerView != 0)
  45189. ownerView->itemsChanged();
  45190. }
  45191. void TreeViewItem::repaintItem() const
  45192. {
  45193. if (ownerView != 0 && areAllParentsOpen())
  45194. {
  45195. const Rectangle<int> r (getItemPosition (true));
  45196. ownerView->viewport->repaint (0, r.getY(), r.getRight(), r.getHeight());
  45197. }
  45198. }
  45199. bool TreeViewItem::areAllParentsOpen() const throw()
  45200. {
  45201. return parentItem == 0
  45202. || (parentItem->isOpen() && parentItem->areAllParentsOpen());
  45203. }
  45204. void TreeViewItem::updatePositions (int newY)
  45205. {
  45206. y = newY;
  45207. itemHeight = getItemHeight();
  45208. totalHeight = itemHeight;
  45209. itemWidth = getItemWidth();
  45210. totalWidth = jmax (itemWidth, 0) + getIndentX();
  45211. if (isOpen())
  45212. {
  45213. newY += totalHeight;
  45214. for (int i = 0; i < subItems.size(); ++i)
  45215. {
  45216. TreeViewItem* const ti = subItems.getUnchecked(i);
  45217. ti->updatePositions (newY);
  45218. newY += ti->totalHeight;
  45219. totalHeight += ti->totalHeight;
  45220. totalWidth = jmax (totalWidth, ti->totalWidth);
  45221. }
  45222. }
  45223. }
  45224. TreeViewItem* TreeViewItem::getDeepestOpenParentItem() throw()
  45225. {
  45226. TreeViewItem* result = this;
  45227. TreeViewItem* item = this;
  45228. while (item->parentItem != 0)
  45229. {
  45230. item = item->parentItem;
  45231. if (! item->isOpen())
  45232. result = item;
  45233. }
  45234. return result;
  45235. }
  45236. void TreeViewItem::setOwnerView (TreeView* const newOwner) throw()
  45237. {
  45238. ownerView = newOwner;
  45239. for (int i = subItems.size(); --i >= 0;)
  45240. subItems.getUnchecked(i)->setOwnerView (newOwner);
  45241. }
  45242. int TreeViewItem::getIndentX() const throw()
  45243. {
  45244. const int indentWidth = ownerView->getIndentSize();
  45245. int x = ownerView->rootItemVisible ? indentWidth : 0;
  45246. if (! ownerView->openCloseButtonsVisible)
  45247. x -= indentWidth;
  45248. TreeViewItem* p = parentItem;
  45249. while (p != 0)
  45250. {
  45251. x += indentWidth;
  45252. p = p->parentItem;
  45253. }
  45254. return x;
  45255. }
  45256. void TreeViewItem::setDrawsInLeftMargin (bool canDrawInLeftMargin) throw()
  45257. {
  45258. drawsInLeftMargin = canDrawInLeftMargin;
  45259. }
  45260. void TreeViewItem::paintRecursively (Graphics& g, int width)
  45261. {
  45262. jassert (ownerView != 0);
  45263. if (ownerView == 0)
  45264. return;
  45265. const int indent = getIndentX();
  45266. const int itemW = itemWidth < 0 ? width - indent : itemWidth;
  45267. g.setColour (ownerView->findColour (TreeView::linesColourId));
  45268. const float halfH = itemHeight * 0.5f;
  45269. int depth = 0;
  45270. TreeViewItem* p = parentItem;
  45271. while (p != 0)
  45272. {
  45273. ++depth;
  45274. p = p->parentItem;
  45275. }
  45276. if (! ownerView->rootItemVisible)
  45277. --depth;
  45278. const int indentWidth = ownerView->getIndentSize();
  45279. if (depth >= 0 && ownerView->openCloseButtonsVisible)
  45280. {
  45281. float x = (depth + 0.5f) * indentWidth;
  45282. if (depth >= 0)
  45283. {
  45284. if (parentItem != 0 && parentItem->drawLinesInside)
  45285. g.drawLine (x, 0, x, isLastOfSiblings() ? halfH : (float) itemHeight);
  45286. if ((parentItem != 0 && parentItem->drawLinesInside)
  45287. || (parentItem == 0 && drawLinesInside))
  45288. g.drawLine (x, halfH, x + indentWidth / 2, halfH);
  45289. }
  45290. p = parentItem;
  45291. int d = depth;
  45292. while (p != 0 && --d >= 0)
  45293. {
  45294. x -= (float) indentWidth;
  45295. if ((p->parentItem == 0 || p->parentItem->drawLinesInside)
  45296. && ! p->isLastOfSiblings())
  45297. {
  45298. g.drawLine (x, 0, x, (float) itemHeight);
  45299. }
  45300. p = p->parentItem;
  45301. }
  45302. if (mightContainSubItems())
  45303. {
  45304. g.saveState();
  45305. g.setOrigin (depth * indentWidth, 0);
  45306. g.reduceClipRegion (0, 0, indentWidth, itemHeight);
  45307. paintOpenCloseButton (g, indentWidth, itemHeight,
  45308. static_cast <TreeViewContentComponent*> (ownerView->viewport->getViewedComponent())
  45309. ->isMouseOverButton (this));
  45310. g.restoreState();
  45311. }
  45312. }
  45313. {
  45314. g.saveState();
  45315. g.setOrigin (indent, 0);
  45316. if (g.reduceClipRegion (drawsInLeftMargin ? -indent : 0, 0,
  45317. drawsInLeftMargin ? itemW + indent : itemW, itemHeight))
  45318. paintItem (g, itemW, itemHeight);
  45319. g.restoreState();
  45320. }
  45321. if (isOpen())
  45322. {
  45323. const Rectangle<int> clip (g.getClipBounds());
  45324. for (int i = 0; i < subItems.size(); ++i)
  45325. {
  45326. TreeViewItem* const ti = subItems.getUnchecked(i);
  45327. const int relY = ti->y - y;
  45328. if (relY >= clip.getBottom())
  45329. break;
  45330. if (relY + ti->totalHeight >= clip.getY())
  45331. {
  45332. g.saveState();
  45333. g.setOrigin (0, relY);
  45334. if (g.reduceClipRegion (0, 0, width, ti->totalHeight))
  45335. ti->paintRecursively (g, width);
  45336. g.restoreState();
  45337. }
  45338. }
  45339. }
  45340. }
  45341. bool TreeViewItem::isLastOfSiblings() const throw()
  45342. {
  45343. return parentItem == 0
  45344. || parentItem->subItems.getLast() == this;
  45345. }
  45346. int TreeViewItem::getIndexInParent() const throw()
  45347. {
  45348. if (parentItem == 0)
  45349. return 0;
  45350. return parentItem->subItems.indexOf (this);
  45351. }
  45352. TreeViewItem* TreeViewItem::getTopLevelItem() throw()
  45353. {
  45354. return (parentItem == 0) ? this
  45355. : parentItem->getTopLevelItem();
  45356. }
  45357. int TreeViewItem::getNumRows() const throw()
  45358. {
  45359. int num = 1;
  45360. if (isOpen())
  45361. {
  45362. for (int i = subItems.size(); --i >= 0;)
  45363. num += subItems.getUnchecked(i)->getNumRows();
  45364. }
  45365. return num;
  45366. }
  45367. TreeViewItem* TreeViewItem::getItemOnRow (int index) throw()
  45368. {
  45369. if (index == 0)
  45370. return this;
  45371. if (index > 0 && isOpen())
  45372. {
  45373. --index;
  45374. for (int i = 0; i < subItems.size(); ++i)
  45375. {
  45376. TreeViewItem* const item = subItems.getUnchecked(i);
  45377. if (index == 0)
  45378. return item;
  45379. const int numRows = item->getNumRows();
  45380. if (numRows > index)
  45381. return item->getItemOnRow (index);
  45382. index -= numRows;
  45383. }
  45384. }
  45385. return 0;
  45386. }
  45387. TreeViewItem* TreeViewItem::findItemRecursively (int targetY) throw()
  45388. {
  45389. if (((unsigned int) targetY) < (unsigned int) totalHeight)
  45390. {
  45391. const int h = itemHeight;
  45392. if (targetY < h)
  45393. return this;
  45394. if (isOpen())
  45395. {
  45396. targetY -= h;
  45397. for (int i = 0; i < subItems.size(); ++i)
  45398. {
  45399. TreeViewItem* const ti = subItems.getUnchecked(i);
  45400. if (targetY < ti->totalHeight)
  45401. return ti->findItemRecursively (targetY);
  45402. targetY -= ti->totalHeight;
  45403. }
  45404. }
  45405. }
  45406. return 0;
  45407. }
  45408. int TreeViewItem::countSelectedItemsRecursively() const throw()
  45409. {
  45410. int total = 0;
  45411. if (isSelected())
  45412. ++total;
  45413. for (int i = subItems.size(); --i >= 0;)
  45414. total += subItems.getUnchecked(i)->countSelectedItemsRecursively();
  45415. return total;
  45416. }
  45417. TreeViewItem* TreeViewItem::getSelectedItemWithIndex (int index) throw()
  45418. {
  45419. if (isSelected())
  45420. {
  45421. if (index == 0)
  45422. return this;
  45423. --index;
  45424. }
  45425. if (index >= 0)
  45426. {
  45427. for (int i = 0; i < subItems.size(); ++i)
  45428. {
  45429. TreeViewItem* const item = subItems.getUnchecked(i);
  45430. TreeViewItem* const found = item->getSelectedItemWithIndex (index);
  45431. if (found != 0)
  45432. return found;
  45433. index -= item->countSelectedItemsRecursively();
  45434. }
  45435. }
  45436. return 0;
  45437. }
  45438. int TreeViewItem::getRowNumberInTree() const throw()
  45439. {
  45440. if (parentItem != 0 && ownerView != 0)
  45441. {
  45442. int n = 1 + parentItem->getRowNumberInTree();
  45443. int ourIndex = parentItem->subItems.indexOf (this);
  45444. jassert (ourIndex >= 0);
  45445. while (--ourIndex >= 0)
  45446. n += parentItem->subItems [ourIndex]->getNumRows();
  45447. if (parentItem->parentItem == 0
  45448. && ! ownerView->rootItemVisible)
  45449. --n;
  45450. return n;
  45451. }
  45452. else
  45453. {
  45454. return 0;
  45455. }
  45456. }
  45457. void TreeViewItem::setLinesDrawnForSubItems (const bool drawLines) throw()
  45458. {
  45459. drawLinesInside = drawLines;
  45460. }
  45461. TreeViewItem* TreeViewItem::getNextVisibleItem (const bool recurse) const throw()
  45462. {
  45463. if (recurse && isOpen() && subItems.size() > 0)
  45464. return subItems [0];
  45465. if (parentItem != 0)
  45466. {
  45467. const int nextIndex = parentItem->subItems.indexOf (this) + 1;
  45468. if (nextIndex >= parentItem->subItems.size())
  45469. return parentItem->getNextVisibleItem (false);
  45470. return parentItem->subItems [nextIndex];
  45471. }
  45472. return 0;
  45473. }
  45474. const String TreeViewItem::getItemIdentifierString() const
  45475. {
  45476. String s;
  45477. if (parentItem != 0)
  45478. s = parentItem->getItemIdentifierString();
  45479. return s + "/" + getUniqueName().replaceCharacter ('/', '\\');
  45480. }
  45481. TreeViewItem* TreeViewItem::findItemFromIdentifierString (const String& identifierString)
  45482. {
  45483. const String uid (getUniqueName());
  45484. if (uid == identifierString)
  45485. return this;
  45486. if (identifierString.startsWith (uid + "/"))
  45487. {
  45488. const String remainingPath (identifierString.substring (uid.length() + 1));
  45489. bool wasOpen = isOpen();
  45490. setOpen (true);
  45491. for (int i = subItems.size(); --i >= 0;)
  45492. {
  45493. TreeViewItem* item = subItems.getUnchecked(i)->findItemFromIdentifierString (remainingPath);
  45494. if (item != 0)
  45495. return item;
  45496. }
  45497. setOpen (wasOpen);
  45498. }
  45499. return 0;
  45500. }
  45501. void TreeViewItem::restoreOpennessState (const XmlElement& e) throw()
  45502. {
  45503. if (e.hasTagName ("CLOSED"))
  45504. {
  45505. setOpen (false);
  45506. }
  45507. else if (e.hasTagName ("OPEN"))
  45508. {
  45509. setOpen (true);
  45510. forEachXmlChildElement (e, n)
  45511. {
  45512. const String id (n->getStringAttribute ("id"));
  45513. for (int i = 0; i < subItems.size(); ++i)
  45514. {
  45515. TreeViewItem* const ti = subItems.getUnchecked(i);
  45516. if (ti->getUniqueName() == id)
  45517. {
  45518. ti->restoreOpennessState (*n);
  45519. break;
  45520. }
  45521. }
  45522. }
  45523. }
  45524. }
  45525. XmlElement* TreeViewItem::getOpennessState() const throw()
  45526. {
  45527. const String name (getUniqueName());
  45528. if (name.isNotEmpty())
  45529. {
  45530. XmlElement* e;
  45531. if (isOpen())
  45532. {
  45533. e = new XmlElement ("OPEN");
  45534. for (int i = 0; i < subItems.size(); ++i)
  45535. e->addChildElement (subItems.getUnchecked(i)->getOpennessState());
  45536. }
  45537. else
  45538. {
  45539. e = new XmlElement ("CLOSED");
  45540. }
  45541. e->setAttribute ("id", name);
  45542. return e;
  45543. }
  45544. else
  45545. {
  45546. // trying to save the openness for an element that has no name - this won't
  45547. // work because it needs the names to identify what to open.
  45548. jassertfalse
  45549. }
  45550. return 0;
  45551. }
  45552. END_JUCE_NAMESPACE
  45553. /*** End of inlined file: juce_TreeView.cpp ***/
  45554. /*** Start of inlined file: juce_DirectoryContentsDisplayComponent.cpp ***/
  45555. BEGIN_JUCE_NAMESPACE
  45556. DirectoryContentsDisplayComponent::DirectoryContentsDisplayComponent (DirectoryContentsList& listToShow)
  45557. : fileList (listToShow)
  45558. {
  45559. }
  45560. DirectoryContentsDisplayComponent::~DirectoryContentsDisplayComponent()
  45561. {
  45562. }
  45563. FileBrowserListener::~FileBrowserListener()
  45564. {
  45565. }
  45566. void DirectoryContentsDisplayComponent::addListener (FileBrowserListener* const listener)
  45567. {
  45568. listeners.add (listener);
  45569. }
  45570. void DirectoryContentsDisplayComponent::removeListener (FileBrowserListener* const listener)
  45571. {
  45572. listeners.remove (listener);
  45573. }
  45574. void DirectoryContentsDisplayComponent::sendSelectionChangeMessage()
  45575. {
  45576. Component::BailOutChecker checker (dynamic_cast <Component*> (this));
  45577. listeners.callChecked (checker, &FileBrowserListener::selectionChanged);
  45578. }
  45579. void DirectoryContentsDisplayComponent::sendMouseClickMessage (const File& file, const MouseEvent& e)
  45580. {
  45581. if (fileList.getDirectory().exists())
  45582. {
  45583. Component::BailOutChecker checker (dynamic_cast <Component*> (this));
  45584. listeners.callChecked (checker, &FileBrowserListener::fileClicked, file, e);
  45585. }
  45586. }
  45587. void DirectoryContentsDisplayComponent::sendDoubleClickMessage (const File& file)
  45588. {
  45589. if (fileList.getDirectory().exists())
  45590. {
  45591. Component::BailOutChecker checker (dynamic_cast <Component*> (this));
  45592. listeners.callChecked (checker, &FileBrowserListener::fileDoubleClicked, file);
  45593. }
  45594. }
  45595. END_JUCE_NAMESPACE
  45596. /*** End of inlined file: juce_DirectoryContentsDisplayComponent.cpp ***/
  45597. /*** Start of inlined file: juce_DirectoryContentsList.cpp ***/
  45598. BEGIN_JUCE_NAMESPACE
  45599. DirectoryContentsList::DirectoryContentsList (const FileFilter* const fileFilter_,
  45600. TimeSliceThread& thread_)
  45601. : fileFilter (fileFilter_),
  45602. thread (thread_),
  45603. fileTypeFlags (File::ignoreHiddenFiles | File::findFiles),
  45604. fileFindHandle (0),
  45605. shouldStop (true)
  45606. {
  45607. }
  45608. DirectoryContentsList::~DirectoryContentsList()
  45609. {
  45610. clear();
  45611. }
  45612. void DirectoryContentsList::setIgnoresHiddenFiles (const bool shouldIgnoreHiddenFiles)
  45613. {
  45614. setTypeFlags (shouldIgnoreHiddenFiles ? (fileTypeFlags | File::ignoreHiddenFiles)
  45615. : (fileTypeFlags & ~File::ignoreHiddenFiles));
  45616. }
  45617. bool DirectoryContentsList::ignoresHiddenFiles() const
  45618. {
  45619. return (fileTypeFlags & File::ignoreHiddenFiles) != 0;
  45620. }
  45621. const File& DirectoryContentsList::getDirectory() const
  45622. {
  45623. return root;
  45624. }
  45625. void DirectoryContentsList::setDirectory (const File& directory,
  45626. const bool includeDirectories,
  45627. const bool includeFiles)
  45628. {
  45629. jassert (includeDirectories || includeFiles); // you have to speciify at least one of these!
  45630. if (directory != root)
  45631. {
  45632. clear();
  45633. root = directory;
  45634. // (this forces a refresh when setTypeFlags() is called, rather than triggering two refreshes)
  45635. fileTypeFlags &= ~(File::findDirectories | File::findFiles);
  45636. }
  45637. int newFlags = fileTypeFlags;
  45638. if (includeDirectories) newFlags |= File::findDirectories; else newFlags &= ~File::findDirectories;
  45639. if (includeFiles) newFlags |= File::findFiles; else newFlags &= ~File::findFiles;
  45640. setTypeFlags (newFlags);
  45641. }
  45642. void DirectoryContentsList::setTypeFlags (const int newFlags)
  45643. {
  45644. if (fileTypeFlags != newFlags)
  45645. {
  45646. fileTypeFlags = newFlags;
  45647. refresh();
  45648. }
  45649. }
  45650. void DirectoryContentsList::clear()
  45651. {
  45652. shouldStop = true;
  45653. thread.removeTimeSliceClient (this);
  45654. fileFindHandle = 0;
  45655. if (files.size() > 0)
  45656. {
  45657. files.clear();
  45658. changed();
  45659. }
  45660. }
  45661. void DirectoryContentsList::refresh()
  45662. {
  45663. clear();
  45664. if (root.isDirectory())
  45665. {
  45666. fileFindHandle = new DirectoryIterator (root, false, "*", fileTypeFlags);
  45667. shouldStop = false;
  45668. thread.addTimeSliceClient (this);
  45669. }
  45670. }
  45671. int DirectoryContentsList::getNumFiles() const
  45672. {
  45673. return files.size();
  45674. }
  45675. bool DirectoryContentsList::getFileInfo (const int index,
  45676. FileInfo& result) const
  45677. {
  45678. const ScopedLock sl (fileListLock);
  45679. const FileInfo* const info = files [index];
  45680. if (info != 0)
  45681. {
  45682. result = *info;
  45683. return true;
  45684. }
  45685. return false;
  45686. }
  45687. const File DirectoryContentsList::getFile (const int index) const
  45688. {
  45689. const ScopedLock sl (fileListLock);
  45690. const FileInfo* const info = files [index];
  45691. if (info != 0)
  45692. return root.getChildFile (info->filename);
  45693. return File::nonexistent;
  45694. }
  45695. bool DirectoryContentsList::isStillLoading() const
  45696. {
  45697. return fileFindHandle != 0;
  45698. }
  45699. void DirectoryContentsList::changed()
  45700. {
  45701. sendChangeMessage (this);
  45702. }
  45703. bool DirectoryContentsList::useTimeSlice()
  45704. {
  45705. const uint32 startTime = Time::getApproximateMillisecondCounter();
  45706. bool hasChanged = false;
  45707. for (int i = 100; --i >= 0;)
  45708. {
  45709. if (! checkNextFile (hasChanged))
  45710. {
  45711. if (hasChanged)
  45712. changed();
  45713. return false;
  45714. }
  45715. if (shouldStop || (Time::getApproximateMillisecondCounter() > startTime + 150))
  45716. break;
  45717. }
  45718. if (hasChanged)
  45719. changed();
  45720. return true;
  45721. }
  45722. bool DirectoryContentsList::checkNextFile (bool& hasChanged)
  45723. {
  45724. if (fileFindHandle != 0)
  45725. {
  45726. bool fileFoundIsDir, isHidden, isReadOnly;
  45727. int64 fileSize;
  45728. Time modTime, creationTime;
  45729. if (fileFindHandle->next (&fileFoundIsDir, &isHidden, &fileSize,
  45730. &modTime, &creationTime, &isReadOnly))
  45731. {
  45732. if (addFile (fileFindHandle->getFile(), fileFoundIsDir,
  45733. fileSize, modTime, creationTime, isReadOnly))
  45734. {
  45735. hasChanged = true;
  45736. }
  45737. return true;
  45738. }
  45739. else
  45740. {
  45741. fileFindHandle = 0;
  45742. }
  45743. }
  45744. return false;
  45745. }
  45746. int DirectoryContentsList::compareElements (const DirectoryContentsList::FileInfo* const first,
  45747. const DirectoryContentsList::FileInfo* const second)
  45748. {
  45749. #if JUCE_WINDOWS
  45750. if (first->isDirectory != second->isDirectory)
  45751. return first->isDirectory ? -1 : 1;
  45752. #endif
  45753. return first->filename.compareIgnoreCase (second->filename);
  45754. }
  45755. bool DirectoryContentsList::addFile (const File& file,
  45756. const bool isDir,
  45757. const int64 fileSize,
  45758. const Time& modTime,
  45759. const Time& creationTime,
  45760. const bool isReadOnly)
  45761. {
  45762. if (fileFilter == 0
  45763. || ((! isDir) && fileFilter->isFileSuitable (file))
  45764. || (isDir && fileFilter->isDirectorySuitable (file)))
  45765. {
  45766. ScopedPointer <FileInfo> info (new FileInfo());
  45767. info->filename = file.getFileName();
  45768. info->fileSize = fileSize;
  45769. info->modificationTime = modTime;
  45770. info->creationTime = creationTime;
  45771. info->isDirectory = isDir;
  45772. info->isReadOnly = isReadOnly;
  45773. const ScopedLock sl (fileListLock);
  45774. for (int i = files.size(); --i >= 0;)
  45775. if (files.getUnchecked(i)->filename == info->filename)
  45776. return false;
  45777. files.addSorted (*this, info.release());
  45778. return true;
  45779. }
  45780. return false;
  45781. }
  45782. END_JUCE_NAMESPACE
  45783. /*** End of inlined file: juce_DirectoryContentsList.cpp ***/
  45784. /*** Start of inlined file: juce_FileBrowserComponent.cpp ***/
  45785. BEGIN_JUCE_NAMESPACE
  45786. FileBrowserComponent::FileBrowserComponent (int flags_,
  45787. const File& initialFileOrDirectory,
  45788. const FileFilter* fileFilter_,
  45789. FilePreviewComponent* previewComp_)
  45790. : FileFilter (String::empty),
  45791. fileFilter (fileFilter_),
  45792. flags (flags_),
  45793. previewComp (previewComp_),
  45794. thread ("Juce FileBrowser")
  45795. {
  45796. // You need to specify one or other of the open/save flags..
  45797. jassert ((flags & (saveMode | openMode)) != 0);
  45798. jassert ((flags & (saveMode | openMode)) != (saveMode | openMode));
  45799. // You need to specify at least one of these flags..
  45800. jassert ((flags & (canSelectFiles | canSelectDirectories)) != 0);
  45801. String filename;
  45802. if (initialFileOrDirectory == File::nonexistent)
  45803. {
  45804. currentRoot = File::getCurrentWorkingDirectory();
  45805. }
  45806. else if (initialFileOrDirectory.isDirectory())
  45807. {
  45808. currentRoot = initialFileOrDirectory;
  45809. }
  45810. else
  45811. {
  45812. chosenFiles.add (initialFileOrDirectory);
  45813. currentRoot = initialFileOrDirectory.getParentDirectory();
  45814. filename = initialFileOrDirectory.getFileName();
  45815. }
  45816. fileList = new DirectoryContentsList (this, thread);
  45817. if ((flags & useTreeView) != 0)
  45818. {
  45819. FileTreeComponent* const tree = new FileTreeComponent (*fileList);
  45820. if ((flags & canSelectMultipleItems) != 0)
  45821. tree->setMultiSelectEnabled (true);
  45822. addAndMakeVisible (tree);
  45823. fileListComponent = tree;
  45824. }
  45825. else
  45826. {
  45827. FileListComponent* const list = new FileListComponent (*fileList);
  45828. list->setOutlineThickness (1);
  45829. if ((flags & canSelectMultipleItems) != 0)
  45830. list->setMultipleSelectionEnabled (true);
  45831. addAndMakeVisible (list);
  45832. fileListComponent = list;
  45833. }
  45834. fileListComponent->addListener (this);
  45835. addAndMakeVisible (currentPathBox = new ComboBox ("path"));
  45836. currentPathBox->setEditableText (true);
  45837. StringArray rootNames, rootPaths;
  45838. const BigInteger separators (getRoots (rootNames, rootPaths));
  45839. for (int i = 0; i < rootNames.size(); ++i)
  45840. {
  45841. if (separators [i])
  45842. currentPathBox->addSeparator();
  45843. currentPathBox->addItem (rootNames[i], i + 1);
  45844. }
  45845. currentPathBox->addSeparator();
  45846. currentPathBox->addListener (this);
  45847. addAndMakeVisible (filenameBox = new TextEditor());
  45848. filenameBox->setMultiLine (false);
  45849. filenameBox->setSelectAllWhenFocused (true);
  45850. filenameBox->setText (filename, false);
  45851. filenameBox->addListener (this);
  45852. filenameBox->setReadOnly ((flags & (filenameBoxIsReadOnly | canSelectMultipleItems)) != 0);
  45853. Label* label = new Label ("f", TRANS("file:"));
  45854. addAndMakeVisible (label);
  45855. label->attachToComponent (filenameBox, true);
  45856. addAndMakeVisible (goUpButton = getLookAndFeel().createFileBrowserGoUpButton());
  45857. goUpButton->addButtonListener (this);
  45858. goUpButton->setTooltip (TRANS ("go up to parent directory"));
  45859. if (previewComp != 0)
  45860. addAndMakeVisible (previewComp);
  45861. setRoot (currentRoot);
  45862. thread.startThread (4);
  45863. }
  45864. FileBrowserComponent::~FileBrowserComponent()
  45865. {
  45866. if (previewComp != 0)
  45867. removeChildComponent (previewComp);
  45868. deleteAllChildren();
  45869. fileList = 0;
  45870. thread.stopThread (10000);
  45871. }
  45872. void FileBrowserComponent::addListener (FileBrowserListener* const newListener)
  45873. {
  45874. listeners.add (newListener);
  45875. }
  45876. void FileBrowserComponent::removeListener (FileBrowserListener* const listener)
  45877. {
  45878. listeners.remove (listener);
  45879. }
  45880. bool FileBrowserComponent::isSaveMode() const throw()
  45881. {
  45882. return (flags & saveMode) != 0;
  45883. }
  45884. int FileBrowserComponent::getNumSelectedFiles() const throw()
  45885. {
  45886. if (chosenFiles.size() == 0 && currentFileIsValid())
  45887. return 1;
  45888. return chosenFiles.size();
  45889. }
  45890. const File FileBrowserComponent::getSelectedFile (int index) const throw()
  45891. {
  45892. if ((flags & canSelectDirectories) != 0 && filenameBox->getText().isEmpty())
  45893. return currentRoot;
  45894. if (! filenameBox->isReadOnly())
  45895. return currentRoot.getChildFile (filenameBox->getText());
  45896. return chosenFiles[index];
  45897. }
  45898. bool FileBrowserComponent::currentFileIsValid() const
  45899. {
  45900. if (isSaveMode())
  45901. return ! getSelectedFile (0).isDirectory();
  45902. else
  45903. return getSelectedFile (0).exists();
  45904. }
  45905. const File FileBrowserComponent::getHighlightedFile() const throw()
  45906. {
  45907. return fileListComponent->getSelectedFile (0);
  45908. }
  45909. void FileBrowserComponent::deselectAllFiles()
  45910. {
  45911. fileListComponent->deselectAllFiles();
  45912. }
  45913. bool FileBrowserComponent::isFileSuitable (const File& file) const
  45914. {
  45915. return (flags & canSelectFiles) != 0 ? (fileFilter == 0 || fileFilter->isFileSuitable (file))
  45916. : false;
  45917. }
  45918. bool FileBrowserComponent::isDirectorySuitable (const File&) const
  45919. {
  45920. return true;
  45921. }
  45922. bool FileBrowserComponent::isFileOrDirSuitable (const File& f) const
  45923. {
  45924. if (f.isDirectory())
  45925. return (flags & canSelectDirectories) != 0 && (fileFilter == 0 || fileFilter->isDirectorySuitable (f));
  45926. return (flags & canSelectFiles) != 0 && f.exists()
  45927. && (fileFilter == 0 || fileFilter->isFileSuitable (f));
  45928. }
  45929. const File FileBrowserComponent::getRoot() const
  45930. {
  45931. return currentRoot;
  45932. }
  45933. void FileBrowserComponent::setRoot (const File& newRootDirectory)
  45934. {
  45935. if (currentRoot != newRootDirectory)
  45936. {
  45937. fileListComponent->scrollToTop();
  45938. String path (newRootDirectory.getFullPathName());
  45939. if (path.isEmpty())
  45940. path = File::separatorString;
  45941. StringArray rootNames, rootPaths;
  45942. getRoots (rootNames, rootPaths);
  45943. if (! rootPaths.contains (path, true))
  45944. {
  45945. bool alreadyListed = false;
  45946. for (int i = currentPathBox->getNumItems(); --i >= 0;)
  45947. {
  45948. if (currentPathBox->getItemText (i).equalsIgnoreCase (path))
  45949. {
  45950. alreadyListed = true;
  45951. break;
  45952. }
  45953. }
  45954. if (! alreadyListed)
  45955. currentPathBox->addItem (path, currentPathBox->getNumItems() + 2);
  45956. }
  45957. }
  45958. currentRoot = newRootDirectory;
  45959. fileList->setDirectory (currentRoot, true, true);
  45960. String currentRootName (currentRoot.getFullPathName());
  45961. if (currentRootName.isEmpty())
  45962. currentRootName = File::separatorString;
  45963. currentPathBox->setText (currentRootName, true);
  45964. goUpButton->setEnabled (currentRoot.getParentDirectory().isDirectory()
  45965. && currentRoot.getParentDirectory() != currentRoot);
  45966. }
  45967. void FileBrowserComponent::goUp()
  45968. {
  45969. setRoot (getRoot().getParentDirectory());
  45970. }
  45971. void FileBrowserComponent::refresh()
  45972. {
  45973. fileList->refresh();
  45974. }
  45975. const String FileBrowserComponent::getActionVerb() const
  45976. {
  45977. return isSaveMode() ? TRANS("Save") : TRANS("Open");
  45978. }
  45979. FilePreviewComponent* FileBrowserComponent::getPreviewComponent() const throw()
  45980. {
  45981. return previewComp;
  45982. }
  45983. void FileBrowserComponent::resized()
  45984. {
  45985. getLookAndFeel()
  45986. .layoutFileBrowserComponent (*this, fileListComponent,
  45987. previewComp, currentPathBox,
  45988. filenameBox, goUpButton);
  45989. }
  45990. void FileBrowserComponent::sendListenerChangeMessage()
  45991. {
  45992. Component::BailOutChecker checker (this);
  45993. if (previewComp != 0)
  45994. previewComp->selectedFileChanged (getSelectedFile (0));
  45995. // You shouldn't delete the browser when the file gets changed!
  45996. jassert (! checker.shouldBailOut());
  45997. listeners.callChecked (checker, &FileBrowserListener::selectionChanged);
  45998. }
  45999. void FileBrowserComponent::selectionChanged()
  46000. {
  46001. StringArray newFilenames;
  46002. bool resetChosenFiles = true;
  46003. for (int i = 0; i < fileListComponent->getNumSelectedFiles(); ++i)
  46004. {
  46005. const File f (fileListComponent->getSelectedFile (i));
  46006. if (isFileOrDirSuitable (f))
  46007. {
  46008. if (resetChosenFiles)
  46009. {
  46010. chosenFiles.clear();
  46011. resetChosenFiles = false;
  46012. }
  46013. chosenFiles.add (f);
  46014. newFilenames.add (f.getRelativePathFrom (getRoot()));
  46015. }
  46016. }
  46017. if (newFilenames.size() > 0)
  46018. filenameBox->setText (newFilenames.joinIntoString (", "), false);
  46019. sendListenerChangeMessage();
  46020. }
  46021. void FileBrowserComponent::fileClicked (const File& f, const MouseEvent& e)
  46022. {
  46023. Component::BailOutChecker checker (this);
  46024. listeners.callChecked (checker, &FileBrowserListener::fileClicked, f, e);
  46025. }
  46026. void FileBrowserComponent::fileDoubleClicked (const File& f)
  46027. {
  46028. if (f.isDirectory())
  46029. {
  46030. setRoot (f);
  46031. if ((flags & canSelectDirectories) != 0)
  46032. filenameBox->setText (String::empty);
  46033. }
  46034. else
  46035. {
  46036. Component::BailOutChecker checker (this);
  46037. listeners.callChecked (checker, &FileBrowserListener::fileDoubleClicked, f);
  46038. }
  46039. }
  46040. bool FileBrowserComponent::keyPressed (const KeyPress& key)
  46041. {
  46042. #if JUCE_LINUX || JUCE_WINDOWS
  46043. if (key.getModifiers().isCommandDown()
  46044. && (key.getKeyCode() == 'H' || key.getKeyCode() == 'h'))
  46045. {
  46046. fileList->setIgnoresHiddenFiles (! fileList->ignoresHiddenFiles());
  46047. fileList->refresh();
  46048. return true;
  46049. }
  46050. #endif
  46051. return false;
  46052. }
  46053. void FileBrowserComponent::textEditorTextChanged (TextEditor&)
  46054. {
  46055. sendListenerChangeMessage();
  46056. }
  46057. void FileBrowserComponent::textEditorReturnKeyPressed (TextEditor&)
  46058. {
  46059. if (filenameBox->getText().containsChar (File::separator))
  46060. {
  46061. const File f (currentRoot.getChildFile (filenameBox->getText()));
  46062. if (f.isDirectory())
  46063. {
  46064. setRoot (f);
  46065. chosenFiles.clear();
  46066. filenameBox->setText (String::empty);
  46067. }
  46068. else
  46069. {
  46070. setRoot (f.getParentDirectory());
  46071. chosenFiles.clear();
  46072. chosenFiles.add (f);
  46073. filenameBox->setText (f.getFileName());
  46074. }
  46075. }
  46076. else
  46077. {
  46078. fileDoubleClicked (getSelectedFile (0));
  46079. }
  46080. }
  46081. void FileBrowserComponent::textEditorEscapeKeyPressed (TextEditor&)
  46082. {
  46083. }
  46084. void FileBrowserComponent::textEditorFocusLost (TextEditor&)
  46085. {
  46086. if (! isSaveMode())
  46087. selectionChanged();
  46088. }
  46089. void FileBrowserComponent::buttonClicked (Button*)
  46090. {
  46091. goUp();
  46092. }
  46093. void FileBrowserComponent::comboBoxChanged (ComboBox*)
  46094. {
  46095. const String newText (currentPathBox->getText().trim().unquoted());
  46096. if (newText.isNotEmpty())
  46097. {
  46098. const int index = currentPathBox->getSelectedId() - 1;
  46099. StringArray rootNames, rootPaths;
  46100. getRoots (rootNames, rootPaths);
  46101. if (rootPaths [index].isNotEmpty())
  46102. {
  46103. setRoot (File (rootPaths [index]));
  46104. }
  46105. else
  46106. {
  46107. File f (newText);
  46108. for (;;)
  46109. {
  46110. if (f.isDirectory())
  46111. {
  46112. setRoot (f);
  46113. break;
  46114. }
  46115. if (f.getParentDirectory() == f)
  46116. break;
  46117. f = f.getParentDirectory();
  46118. }
  46119. }
  46120. }
  46121. }
  46122. const BigInteger FileBrowserComponent::getRoots (StringArray& rootNames, StringArray& rootPaths)
  46123. {
  46124. BigInteger separators;
  46125. #if JUCE_WINDOWS
  46126. Array<File> roots;
  46127. File::findFileSystemRoots (roots);
  46128. rootPaths.clear();
  46129. for (int i = 0; i < roots.size(); ++i)
  46130. {
  46131. const File& drive = roots.getReference(i);
  46132. String name (drive.getFullPathName());
  46133. rootPaths.add (name);
  46134. if (drive.isOnHardDisk())
  46135. {
  46136. String volume (drive.getVolumeLabel());
  46137. if (volume.isEmpty())
  46138. volume = TRANS("Hard Drive");
  46139. name << " [" << drive.getVolumeLabel() << ']';
  46140. }
  46141. else if (drive.isOnCDRomDrive())
  46142. {
  46143. name << TRANS(" [CD/DVD drive]");
  46144. }
  46145. rootNames.add (name);
  46146. }
  46147. separators.setBit (rootPaths.size());
  46148. rootPaths.add (File::getSpecialLocation (File::userDocumentsDirectory).getFullPathName());
  46149. rootNames.add ("Documents");
  46150. rootPaths.add (File::getSpecialLocation (File::userDesktopDirectory).getFullPathName());
  46151. rootNames.add ("Desktop");
  46152. #endif
  46153. #if JUCE_MAC
  46154. rootPaths.add (File::getSpecialLocation (File::userHomeDirectory).getFullPathName());
  46155. rootNames.add ("Home folder");
  46156. rootPaths.add (File::getSpecialLocation (File::userDocumentsDirectory).getFullPathName());
  46157. rootNames.add ("Documents");
  46158. rootPaths.add (File::getSpecialLocation (File::userDesktopDirectory).getFullPathName());
  46159. rootNames.add ("Desktop");
  46160. separators.setBit (rootPaths.size());
  46161. Array <File> volumes;
  46162. File vol ("/Volumes");
  46163. vol.findChildFiles (volumes, File::findDirectories, false);
  46164. for (int i = 0; i < volumes.size(); ++i)
  46165. {
  46166. const File& volume = volumes.getReference(i);
  46167. if (volume.isDirectory() && ! volume.getFileName().startsWithChar ('.'))
  46168. {
  46169. rootPaths.add (volume.getFullPathName());
  46170. rootNames.add (volume.getFileName());
  46171. }
  46172. }
  46173. #endif
  46174. #if JUCE_LINUX
  46175. rootPaths.add ("/");
  46176. rootNames.add ("/");
  46177. rootPaths.add (File::getSpecialLocation (File::userHomeDirectory).getFullPathName());
  46178. rootNames.add ("Home folder");
  46179. rootPaths.add (File::getSpecialLocation (File::userDesktopDirectory).getFullPathName());
  46180. rootNames.add ("Desktop");
  46181. #endif
  46182. return separators;
  46183. }
  46184. END_JUCE_NAMESPACE
  46185. /*** End of inlined file: juce_FileBrowserComponent.cpp ***/
  46186. /*** Start of inlined file: juce_FileChooser.cpp ***/
  46187. BEGIN_JUCE_NAMESPACE
  46188. FileChooser::FileChooser (const String& chooserBoxTitle,
  46189. const File& currentFileOrDirectory,
  46190. const String& fileFilters,
  46191. const bool useNativeDialogBox_)
  46192. : title (chooserBoxTitle),
  46193. filters (fileFilters),
  46194. startingFile (currentFileOrDirectory),
  46195. useNativeDialogBox (useNativeDialogBox_)
  46196. {
  46197. #if JUCE_LINUX
  46198. useNativeDialogBox = false;
  46199. #endif
  46200. if (! fileFilters.containsNonWhitespaceChars())
  46201. filters = "*";
  46202. }
  46203. FileChooser::~FileChooser()
  46204. {
  46205. }
  46206. bool FileChooser::browseForFileToOpen (FilePreviewComponent* previewComponent)
  46207. {
  46208. return showDialog (false, true, false, false, false, previewComponent);
  46209. }
  46210. bool FileChooser::browseForMultipleFilesToOpen (FilePreviewComponent* previewComponent)
  46211. {
  46212. return showDialog (false, true, false, false, true, previewComponent);
  46213. }
  46214. bool FileChooser::browseForMultipleFilesOrDirectories (FilePreviewComponent* previewComponent)
  46215. {
  46216. return showDialog (true, true, false, false, true, previewComponent);
  46217. }
  46218. bool FileChooser::browseForFileToSave (const bool warnAboutOverwritingExistingFiles)
  46219. {
  46220. return showDialog (false, true, true, warnAboutOverwritingExistingFiles, false, 0);
  46221. }
  46222. bool FileChooser::browseForDirectory()
  46223. {
  46224. return showDialog (true, false, false, false, false, 0);
  46225. }
  46226. const File FileChooser::getResult() const
  46227. {
  46228. // if you've used a multiple-file select, you should use the getResults() method
  46229. // to retrieve all the files that were chosen.
  46230. jassert (results.size() <= 1);
  46231. return results.getFirst();
  46232. }
  46233. const Array<File>& FileChooser::getResults() const
  46234. {
  46235. return results;
  46236. }
  46237. bool FileChooser::showDialog (const bool selectsDirectories,
  46238. const bool selectsFiles,
  46239. const bool isSave,
  46240. const bool warnAboutOverwritingExistingFiles,
  46241. const bool selectMultipleFiles,
  46242. FilePreviewComponent* const previewComponent)
  46243. {
  46244. Component::SafePointer<Component> previouslyFocused (Component::getCurrentlyFocusedComponent());
  46245. results.clear();
  46246. // the preview component needs to be the right size before you pass it in here..
  46247. jassert (previewComponent == 0 || (previewComponent->getWidth() > 10
  46248. && previewComponent->getHeight() > 10));
  46249. #if JUCE_WINDOWS
  46250. if (useNativeDialogBox && ! (selectsFiles && selectsDirectories))
  46251. #elif JUCE_MAC
  46252. if (useNativeDialogBox && (previewComponent == 0))
  46253. #else
  46254. if (false)
  46255. #endif
  46256. {
  46257. showPlatformDialog (results, title, startingFile, filters,
  46258. selectsDirectories, selectsFiles, isSave,
  46259. warnAboutOverwritingExistingFiles,
  46260. selectMultipleFiles,
  46261. previewComponent);
  46262. }
  46263. else
  46264. {
  46265. WildcardFileFilter wildcard (selectsFiles ? filters : String::empty,
  46266. selectsDirectories ? "*" : String::empty,
  46267. String::empty);
  46268. int flags = isSave ? FileBrowserComponent::saveMode
  46269. : FileBrowserComponent::openMode;
  46270. if (selectsFiles)
  46271. flags |= FileBrowserComponent::canSelectFiles;
  46272. if (selectsDirectories)
  46273. {
  46274. flags |= FileBrowserComponent::canSelectDirectories;
  46275. if (! isSave)
  46276. flags |= FileBrowserComponent::filenameBoxIsReadOnly;
  46277. }
  46278. if (selectMultipleFiles)
  46279. flags |= FileBrowserComponent::canSelectMultipleItems;
  46280. FileBrowserComponent browserComponent (flags, startingFile, &wildcard, previewComponent);
  46281. FileChooserDialogBox box (title, String::empty,
  46282. browserComponent,
  46283. warnAboutOverwritingExistingFiles,
  46284. browserComponent.findColour (AlertWindow::backgroundColourId));
  46285. if (box.show())
  46286. {
  46287. for (int i = 0; i < browserComponent.getNumSelectedFiles(); ++i)
  46288. results.add (browserComponent.getSelectedFile (i));
  46289. }
  46290. }
  46291. if (previouslyFocused != 0)
  46292. previouslyFocused->grabKeyboardFocus();
  46293. return results.size() > 0;
  46294. }
  46295. FilePreviewComponent::FilePreviewComponent()
  46296. {
  46297. }
  46298. FilePreviewComponent::~FilePreviewComponent()
  46299. {
  46300. }
  46301. END_JUCE_NAMESPACE
  46302. /*** End of inlined file: juce_FileChooser.cpp ***/
  46303. /*** Start of inlined file: juce_FileChooserDialogBox.cpp ***/
  46304. BEGIN_JUCE_NAMESPACE
  46305. FileChooserDialogBox::FileChooserDialogBox (const String& name,
  46306. const String& instructions,
  46307. FileBrowserComponent& chooserComponent,
  46308. const bool warnAboutOverwritingExistingFiles_,
  46309. const Colour& backgroundColour)
  46310. : ResizableWindow (name, backgroundColour, true),
  46311. warnAboutOverwritingExistingFiles (warnAboutOverwritingExistingFiles_)
  46312. {
  46313. content = new ContentComponent();
  46314. content->setName (name);
  46315. content->instructions = instructions;
  46316. content->chooserComponent = &chooserComponent;
  46317. content->addAndMakeVisible (&chooserComponent);
  46318. content->okButton = new TextButton (chooserComponent.getActionVerb());
  46319. content->addAndMakeVisible (content->okButton);
  46320. content->okButton->addButtonListener (this);
  46321. content->okButton->setEnabled (chooserComponent.currentFileIsValid());
  46322. content->okButton->addShortcut (KeyPress (KeyPress::returnKey, 0, 0));
  46323. content->cancelButton = new TextButton (TRANS("Cancel"));
  46324. content->addAndMakeVisible (content->cancelButton);
  46325. content->cancelButton->addButtonListener (this);
  46326. content->cancelButton->addShortcut (KeyPress (KeyPress::escapeKey, 0, 0));
  46327. setContentComponent (content);
  46328. setResizable (true, true);
  46329. setResizeLimits (300, 300, 1200, 1000);
  46330. content->chooserComponent->addListener (this);
  46331. }
  46332. FileChooserDialogBox::~FileChooserDialogBox()
  46333. {
  46334. content->chooserComponent->removeListener (this);
  46335. }
  46336. bool FileChooserDialogBox::show (int w, int h)
  46337. {
  46338. if (w <= 0)
  46339. {
  46340. Component* const previewComp = content->chooserComponent->getPreviewComponent();
  46341. if (previewComp != 0)
  46342. w = 400 + previewComp->getWidth();
  46343. else
  46344. w = 600;
  46345. }
  46346. if (h <= 0)
  46347. h = 500;
  46348. centreWithSize (w, h);
  46349. const bool ok = (runModalLoop() != 0);
  46350. setVisible (false);
  46351. return ok;
  46352. }
  46353. void FileChooserDialogBox::buttonClicked (Button* button)
  46354. {
  46355. if (button == content->okButton)
  46356. {
  46357. if (warnAboutOverwritingExistingFiles
  46358. && content->chooserComponent->isSaveMode()
  46359. && content->chooserComponent->getSelectedFile(0).exists())
  46360. {
  46361. if (! AlertWindow::showOkCancelBox (AlertWindow::WarningIcon,
  46362. TRANS("File already exists"),
  46363. TRANS("There's already a file called:")
  46364. + "\n\n" + content->chooserComponent->getSelectedFile(0).getFullPathName()
  46365. + "\n\n" + TRANS("Are you sure you want to overwrite it?"),
  46366. TRANS("overwrite"),
  46367. TRANS("cancel")))
  46368. {
  46369. return;
  46370. }
  46371. }
  46372. exitModalState (1);
  46373. }
  46374. else if (button == content->cancelButton)
  46375. closeButtonPressed();
  46376. }
  46377. void FileChooserDialogBox::closeButtonPressed()
  46378. {
  46379. setVisible (false);
  46380. }
  46381. void FileChooserDialogBox::selectionChanged()
  46382. {
  46383. content->okButton->setEnabled (content->chooserComponent->currentFileIsValid());
  46384. }
  46385. void FileChooserDialogBox::fileClicked (const File&, const MouseEvent&)
  46386. {
  46387. }
  46388. void FileChooserDialogBox::fileDoubleClicked (const File&)
  46389. {
  46390. selectionChanged();
  46391. content->okButton->triggerClick();
  46392. }
  46393. FileChooserDialogBox::ContentComponent::ContentComponent()
  46394. {
  46395. setInterceptsMouseClicks (false, true);
  46396. }
  46397. FileChooserDialogBox::ContentComponent::~ContentComponent()
  46398. {
  46399. delete okButton;
  46400. delete cancelButton;
  46401. }
  46402. void FileChooserDialogBox::ContentComponent::paint (Graphics& g)
  46403. {
  46404. g.setColour (getLookAndFeel().findColour (FileChooserDialogBox::titleTextColourId));
  46405. text.draw (g);
  46406. }
  46407. void FileChooserDialogBox::ContentComponent::resized()
  46408. {
  46409. getLookAndFeel().createFileChooserHeaderText (getName(), instructions, text, getWidth());
  46410. const Rectangle<float> bb (text.getBoundingBox (0, text.getNumGlyphs(), false));
  46411. const int y = roundToInt (bb.getBottom()) + 10;
  46412. const int buttonHeight = 26;
  46413. const int buttonY = getHeight() - buttonHeight - 8;
  46414. chooserComponent->setBounds (0, y, getWidth(), buttonY - y - 20);
  46415. okButton->setBounds (proportionOfWidth (0.25f), buttonY,
  46416. proportionOfWidth (0.2f), buttonHeight);
  46417. cancelButton->setBounds (proportionOfWidth (0.55f), buttonY,
  46418. proportionOfWidth (0.2f), buttonHeight);
  46419. }
  46420. END_JUCE_NAMESPACE
  46421. /*** End of inlined file: juce_FileChooserDialogBox.cpp ***/
  46422. /*** Start of inlined file: juce_FileFilter.cpp ***/
  46423. BEGIN_JUCE_NAMESPACE
  46424. FileFilter::FileFilter (const String& filterDescription)
  46425. : description (filterDescription)
  46426. {
  46427. }
  46428. FileFilter::~FileFilter()
  46429. {
  46430. }
  46431. const String& FileFilter::getDescription() const throw()
  46432. {
  46433. return description;
  46434. }
  46435. END_JUCE_NAMESPACE
  46436. /*** End of inlined file: juce_FileFilter.cpp ***/
  46437. /*** Start of inlined file: juce_FileListComponent.cpp ***/
  46438. BEGIN_JUCE_NAMESPACE
  46439. Image* juce_createIconForFile (const File& file);
  46440. FileListComponent::FileListComponent (DirectoryContentsList& listToShow)
  46441. : ListBox (String::empty, 0),
  46442. DirectoryContentsDisplayComponent (listToShow)
  46443. {
  46444. setModel (this);
  46445. fileList.addChangeListener (this);
  46446. }
  46447. FileListComponent::~FileListComponent()
  46448. {
  46449. fileList.removeChangeListener (this);
  46450. deleteAllChildren();
  46451. }
  46452. int FileListComponent::getNumSelectedFiles() const
  46453. {
  46454. return getNumSelectedRows();
  46455. }
  46456. const File FileListComponent::getSelectedFile (int index) const
  46457. {
  46458. return fileList.getFile (getSelectedRow (index));
  46459. }
  46460. void FileListComponent::deselectAllFiles()
  46461. {
  46462. deselectAllRows();
  46463. }
  46464. void FileListComponent::scrollToTop()
  46465. {
  46466. getVerticalScrollBar()->setCurrentRangeStart (0);
  46467. }
  46468. void FileListComponent::changeListenerCallback (void*)
  46469. {
  46470. updateContent();
  46471. if (lastDirectory != fileList.getDirectory())
  46472. {
  46473. lastDirectory = fileList.getDirectory();
  46474. deselectAllRows();
  46475. }
  46476. }
  46477. class FileListItemComponent : public Component,
  46478. public TimeSliceClient,
  46479. public AsyncUpdater
  46480. {
  46481. public:
  46482. FileListItemComponent (FileListComponent& owner_, TimeSliceThread& thread_)
  46483. : owner (owner_), thread (thread_),
  46484. highlighted (false), index (0), icon (0)
  46485. {
  46486. }
  46487. ~FileListItemComponent()
  46488. {
  46489. thread.removeTimeSliceClient (this);
  46490. clearIcon();
  46491. }
  46492. void paint (Graphics& g)
  46493. {
  46494. getLookAndFeel().drawFileBrowserRow (g, getWidth(), getHeight(),
  46495. file.getFileName(),
  46496. icon,
  46497. fileSize, modTime,
  46498. isDirectory, highlighted,
  46499. index);
  46500. }
  46501. void mouseDown (const MouseEvent& e)
  46502. {
  46503. owner.selectRowsBasedOnModifierKeys (index, e.mods);
  46504. owner.sendMouseClickMessage (file, e);
  46505. }
  46506. void mouseDoubleClick (const MouseEvent&)
  46507. {
  46508. owner.sendDoubleClickMessage (file);
  46509. }
  46510. void update (const File& root,
  46511. const DirectoryContentsList::FileInfo* const fileInfo,
  46512. const int index_,
  46513. const bool highlighted_)
  46514. {
  46515. thread.removeTimeSliceClient (this);
  46516. if (highlighted_ != highlighted
  46517. || index_ != index)
  46518. {
  46519. index = index_;
  46520. highlighted = highlighted_;
  46521. repaint();
  46522. }
  46523. File newFile;
  46524. String newFileSize;
  46525. String newModTime;
  46526. if (fileInfo != 0)
  46527. {
  46528. newFile = root.getChildFile (fileInfo->filename);
  46529. newFileSize = File::descriptionOfSizeInBytes (fileInfo->fileSize);
  46530. newModTime = fileInfo->modificationTime.formatted ("%d %b '%y %H:%M");
  46531. }
  46532. if (newFile != file
  46533. || fileSize != newFileSize
  46534. || modTime != newModTime)
  46535. {
  46536. file = newFile;
  46537. fileSize = newFileSize;
  46538. modTime = newModTime;
  46539. isDirectory = fileInfo != 0 && fileInfo->isDirectory;
  46540. repaint();
  46541. clearIcon();
  46542. }
  46543. if (file != File::nonexistent
  46544. && icon == 0 && ! isDirectory)
  46545. {
  46546. updateIcon (true);
  46547. if (icon == 0)
  46548. thread.addTimeSliceClient (this);
  46549. }
  46550. }
  46551. bool useTimeSlice()
  46552. {
  46553. updateIcon (false);
  46554. return false;
  46555. }
  46556. void handleAsyncUpdate()
  46557. {
  46558. repaint();
  46559. }
  46560. juce_UseDebuggingNewOperator
  46561. private:
  46562. FileListComponent& owner;
  46563. TimeSliceThread& thread;
  46564. bool highlighted;
  46565. int index;
  46566. File file;
  46567. String fileSize;
  46568. String modTime;
  46569. Image* icon;
  46570. bool isDirectory;
  46571. void clearIcon()
  46572. {
  46573. ImageCache::release (icon);
  46574. icon = 0;
  46575. }
  46576. void updateIcon (const bool onlyUpdateIfCached)
  46577. {
  46578. if (icon == 0)
  46579. {
  46580. const int hashCode = (file.getFullPathName() + "_iconCacheSalt").hashCode();
  46581. Image* im = ImageCache::getFromHashCode (hashCode);
  46582. if (im == 0 && ! onlyUpdateIfCached)
  46583. {
  46584. im = juce_createIconForFile (file);
  46585. if (im != 0)
  46586. ImageCache::addImageToCache (im, hashCode);
  46587. }
  46588. if (im != 0)
  46589. {
  46590. icon = im;
  46591. triggerAsyncUpdate();
  46592. }
  46593. }
  46594. }
  46595. };
  46596. int FileListComponent::getNumRows()
  46597. {
  46598. return fileList.getNumFiles();
  46599. }
  46600. void FileListComponent::paintListBoxItem (int, Graphics&, int, int, bool)
  46601. {
  46602. }
  46603. Component* FileListComponent::refreshComponentForRow (int row, bool isSelected, Component* existingComponentToUpdate)
  46604. {
  46605. FileListItemComponent* comp = dynamic_cast <FileListItemComponent*> (existingComponentToUpdate);
  46606. if (comp == 0)
  46607. {
  46608. delete existingComponentToUpdate;
  46609. comp = new FileListItemComponent (*this, fileList.getTimeSliceThread());
  46610. }
  46611. DirectoryContentsList::FileInfo fileInfo;
  46612. if (fileList.getFileInfo (row, fileInfo))
  46613. comp->update (fileList.getDirectory(), &fileInfo, row, isSelected);
  46614. else
  46615. comp->update (fileList.getDirectory(), 0, row, isSelected);
  46616. return comp;
  46617. }
  46618. void FileListComponent::selectedRowsChanged (int /*lastRowSelected*/)
  46619. {
  46620. sendSelectionChangeMessage();
  46621. }
  46622. void FileListComponent::deleteKeyPressed (int /*currentSelectedRow*/)
  46623. {
  46624. }
  46625. void FileListComponent::returnKeyPressed (int currentSelectedRow)
  46626. {
  46627. sendDoubleClickMessage (fileList.getFile (currentSelectedRow));
  46628. }
  46629. END_JUCE_NAMESPACE
  46630. /*** End of inlined file: juce_FileListComponent.cpp ***/
  46631. /*** Start of inlined file: juce_FilenameComponent.cpp ***/
  46632. BEGIN_JUCE_NAMESPACE
  46633. FilenameComponent::FilenameComponent (const String& name,
  46634. const File& currentFile,
  46635. const bool canEditFilename,
  46636. const bool isDirectory,
  46637. const bool isForSaving,
  46638. const String& fileBrowserWildcard,
  46639. const String& enforcedSuffix_,
  46640. const String& textWhenNothingSelected)
  46641. : Component (name),
  46642. maxRecentFiles (30),
  46643. isDir (isDirectory),
  46644. isSaving (isForSaving),
  46645. isFileDragOver (false),
  46646. wildcard (fileBrowserWildcard),
  46647. enforcedSuffix (enforcedSuffix_)
  46648. {
  46649. addAndMakeVisible (filenameBox = new ComboBox ("fn"));
  46650. filenameBox->setEditableText (canEditFilename);
  46651. filenameBox->addListener (this);
  46652. filenameBox->setTextWhenNothingSelected (textWhenNothingSelected);
  46653. filenameBox->setTextWhenNoChoicesAvailable (TRANS("(no recently seleced files)"));
  46654. browseButton = 0;
  46655. setBrowseButtonText ("...");
  46656. setCurrentFile (currentFile, true);
  46657. }
  46658. FilenameComponent::~FilenameComponent()
  46659. {
  46660. deleteAllChildren();
  46661. }
  46662. void FilenameComponent::paintOverChildren (Graphics& g)
  46663. {
  46664. if (isFileDragOver)
  46665. {
  46666. g.setColour (Colours::red.withAlpha (0.2f));
  46667. g.drawRect (0, 0, getWidth(), getHeight(), 3);
  46668. }
  46669. }
  46670. void FilenameComponent::resized()
  46671. {
  46672. getLookAndFeel().layoutFilenameComponent (*this, filenameBox, browseButton);
  46673. }
  46674. void FilenameComponent::setBrowseButtonText (const String& newBrowseButtonText)
  46675. {
  46676. browseButtonText = newBrowseButtonText;
  46677. lookAndFeelChanged();
  46678. }
  46679. void FilenameComponent::lookAndFeelChanged()
  46680. {
  46681. deleteAndZero (browseButton);
  46682. addAndMakeVisible (browseButton = getLookAndFeel().createFilenameComponentBrowseButton (browseButtonText));
  46683. browseButton->setConnectedEdges (Button::ConnectedOnLeft);
  46684. resized();
  46685. browseButton->addButtonListener (this);
  46686. }
  46687. void FilenameComponent::setTooltip (const String& newTooltip)
  46688. {
  46689. SettableTooltipClient::setTooltip (newTooltip);
  46690. filenameBox->setTooltip (newTooltip);
  46691. }
  46692. void FilenameComponent::setDefaultBrowseTarget (const File& newDefaultDirectory)
  46693. {
  46694. defaultBrowseFile = newDefaultDirectory;
  46695. }
  46696. void FilenameComponent::buttonClicked (Button*)
  46697. {
  46698. FileChooser fc (TRANS("Choose a new file"),
  46699. getCurrentFile() == File::nonexistent ? defaultBrowseFile
  46700. : getCurrentFile(),
  46701. wildcard);
  46702. if (isDir ? fc.browseForDirectory()
  46703. : (isSaving ? fc.browseForFileToSave (false)
  46704. : fc.browseForFileToOpen()))
  46705. {
  46706. setCurrentFile (fc.getResult(), true);
  46707. }
  46708. }
  46709. void FilenameComponent::comboBoxChanged (ComboBox*)
  46710. {
  46711. setCurrentFile (getCurrentFile(), true);
  46712. }
  46713. bool FilenameComponent::isInterestedInFileDrag (const StringArray&)
  46714. {
  46715. return true;
  46716. }
  46717. void FilenameComponent::filesDropped (const StringArray& filenames, int, int)
  46718. {
  46719. isFileDragOver = false;
  46720. repaint();
  46721. const File f (filenames[0]);
  46722. if (f.exists() && (f.isDirectory() == isDir))
  46723. setCurrentFile (f, true);
  46724. }
  46725. void FilenameComponent::fileDragEnter (const StringArray&, int, int)
  46726. {
  46727. isFileDragOver = true;
  46728. repaint();
  46729. }
  46730. void FilenameComponent::fileDragExit (const StringArray&)
  46731. {
  46732. isFileDragOver = false;
  46733. repaint();
  46734. }
  46735. const File FilenameComponent::getCurrentFile() const
  46736. {
  46737. File f (filenameBox->getText());
  46738. if (enforcedSuffix.isNotEmpty())
  46739. f = f.withFileExtension (enforcedSuffix);
  46740. return f;
  46741. }
  46742. void FilenameComponent::setCurrentFile (File newFile,
  46743. const bool addToRecentlyUsedList,
  46744. const bool sendChangeNotification)
  46745. {
  46746. if (enforcedSuffix.isNotEmpty())
  46747. newFile = newFile.withFileExtension (enforcedSuffix);
  46748. if (newFile.getFullPathName() != lastFilename)
  46749. {
  46750. lastFilename = newFile.getFullPathName();
  46751. if (addToRecentlyUsedList)
  46752. addRecentlyUsedFile (newFile);
  46753. filenameBox->setText (lastFilename, true);
  46754. if (sendChangeNotification)
  46755. triggerAsyncUpdate();
  46756. }
  46757. }
  46758. void FilenameComponent::setFilenameIsEditable (const bool shouldBeEditable)
  46759. {
  46760. filenameBox->setEditableText (shouldBeEditable);
  46761. }
  46762. const StringArray FilenameComponent::getRecentlyUsedFilenames() const
  46763. {
  46764. StringArray names;
  46765. for (int i = 0; i < filenameBox->getNumItems(); ++i)
  46766. names.add (filenameBox->getItemText (i));
  46767. return names;
  46768. }
  46769. void FilenameComponent::setRecentlyUsedFilenames (const StringArray& filenames)
  46770. {
  46771. if (filenames != getRecentlyUsedFilenames())
  46772. {
  46773. filenameBox->clear();
  46774. for (int i = 0; i < jmin (filenames.size(), maxRecentFiles); ++i)
  46775. filenameBox->addItem (filenames[i], i + 1);
  46776. }
  46777. }
  46778. void FilenameComponent::setMaxNumberOfRecentFiles (const int newMaximum)
  46779. {
  46780. maxRecentFiles = jmax (1, newMaximum);
  46781. setRecentlyUsedFilenames (getRecentlyUsedFilenames());
  46782. }
  46783. void FilenameComponent::addRecentlyUsedFile (const File& file)
  46784. {
  46785. StringArray files (getRecentlyUsedFilenames());
  46786. if (file.getFullPathName().isNotEmpty())
  46787. {
  46788. files.removeString (file.getFullPathName(), true);
  46789. files.insert (0, file.getFullPathName());
  46790. setRecentlyUsedFilenames (files);
  46791. }
  46792. }
  46793. void FilenameComponent::addListener (FilenameComponentListener* const listener)
  46794. {
  46795. listeners.add (listener);
  46796. }
  46797. void FilenameComponent::removeListener (FilenameComponentListener* const listener)
  46798. {
  46799. listeners.remove (listener);
  46800. }
  46801. void FilenameComponent::handleAsyncUpdate()
  46802. {
  46803. Component::BailOutChecker checker (this);
  46804. listeners.callChecked (checker, &FilenameComponentListener::filenameComponentChanged, this);
  46805. }
  46806. END_JUCE_NAMESPACE
  46807. /*** End of inlined file: juce_FilenameComponent.cpp ***/
  46808. /*** Start of inlined file: juce_FileSearchPathListComponent.cpp ***/
  46809. BEGIN_JUCE_NAMESPACE
  46810. FileSearchPathListComponent::FileSearchPathListComponent()
  46811. {
  46812. addAndMakeVisible (listBox = new ListBox (String::empty, this));
  46813. listBox->setColour (ListBox::backgroundColourId, Colours::black.withAlpha (0.02f));
  46814. listBox->setColour (ListBox::outlineColourId, Colours::black.withAlpha (0.1f));
  46815. listBox->setOutlineThickness (1);
  46816. addAndMakeVisible (addButton = new TextButton ("+"));
  46817. addButton->addButtonListener (this);
  46818. addButton->setConnectedEdges (Button::ConnectedOnLeft | Button::ConnectedOnRight | Button::ConnectedOnBottom | Button::ConnectedOnTop);
  46819. addAndMakeVisible (removeButton = new TextButton ("-"));
  46820. removeButton->addButtonListener (this);
  46821. removeButton->setConnectedEdges (Button::ConnectedOnLeft | Button::ConnectedOnRight | Button::ConnectedOnBottom | Button::ConnectedOnTop);
  46822. addAndMakeVisible (changeButton = new TextButton (TRANS("change...")));
  46823. changeButton->addButtonListener (this);
  46824. addAndMakeVisible (upButton = new DrawableButton (String::empty, DrawableButton::ImageOnButtonBackground));
  46825. upButton->addButtonListener (this);
  46826. {
  46827. Path arrowPath;
  46828. arrowPath.addArrow (50.0f, 100.0f, 50.0f, 0.0f, 40.0f, 100.0f, 50.0f);
  46829. DrawablePath arrowImage;
  46830. arrowImage.setFill (Colours::black.withAlpha (0.4f));
  46831. arrowImage.setPath (arrowPath);
  46832. upButton->setImages (&arrowImage);
  46833. }
  46834. addAndMakeVisible (downButton = new DrawableButton (String::empty, DrawableButton::ImageOnButtonBackground));
  46835. downButton->addButtonListener (this);
  46836. {
  46837. Path arrowPath;
  46838. arrowPath.addArrow (50.0f, 0.0f, 50.0f, 100.0f, 40.0f, 100.0f, 50.0f);
  46839. DrawablePath arrowImage;
  46840. arrowImage.setFill (Colours::black.withAlpha (0.4f));
  46841. arrowImage.setPath (arrowPath);
  46842. downButton->setImages (&arrowImage);
  46843. }
  46844. updateButtons();
  46845. }
  46846. FileSearchPathListComponent::~FileSearchPathListComponent()
  46847. {
  46848. deleteAllChildren();
  46849. }
  46850. void FileSearchPathListComponent::updateButtons()
  46851. {
  46852. const bool anythingSelected = listBox->getNumSelectedRows() > 0;
  46853. removeButton->setEnabled (anythingSelected);
  46854. changeButton->setEnabled (anythingSelected);
  46855. upButton->setEnabled (anythingSelected);
  46856. downButton->setEnabled (anythingSelected);
  46857. }
  46858. void FileSearchPathListComponent::changed()
  46859. {
  46860. listBox->updateContent();
  46861. listBox->repaint();
  46862. updateButtons();
  46863. }
  46864. void FileSearchPathListComponent::setPath (const FileSearchPath& newPath)
  46865. {
  46866. if (newPath.toString() != path.toString())
  46867. {
  46868. path = newPath;
  46869. changed();
  46870. }
  46871. }
  46872. void FileSearchPathListComponent::setDefaultBrowseTarget (const File& newDefaultDirectory)
  46873. {
  46874. defaultBrowseTarget = newDefaultDirectory;
  46875. }
  46876. int FileSearchPathListComponent::getNumRows()
  46877. {
  46878. return path.getNumPaths();
  46879. }
  46880. void FileSearchPathListComponent::paintListBoxItem (int rowNumber, Graphics& g, int width, int height, bool rowIsSelected)
  46881. {
  46882. if (rowIsSelected)
  46883. g.fillAll (findColour (TextEditor::highlightColourId));
  46884. g.setColour (findColour (ListBox::textColourId));
  46885. Font f (height * 0.7f);
  46886. f.setHorizontalScale (0.9f);
  46887. g.setFont (f);
  46888. g.drawText (path [rowNumber].getFullPathName(),
  46889. 4, 0, width - 6, height,
  46890. Justification::centredLeft, true);
  46891. }
  46892. void FileSearchPathListComponent::deleteKeyPressed (int row)
  46893. {
  46894. if (((unsigned int) row) < (unsigned int) path.getNumPaths())
  46895. {
  46896. path.remove (row);
  46897. changed();
  46898. }
  46899. }
  46900. void FileSearchPathListComponent::returnKeyPressed (int row)
  46901. {
  46902. FileChooser chooser (TRANS("Change folder..."), path [row], "*");
  46903. if (chooser.browseForDirectory())
  46904. {
  46905. path.remove (row);
  46906. path.add (chooser.getResult(), row);
  46907. changed();
  46908. }
  46909. }
  46910. void FileSearchPathListComponent::listBoxItemDoubleClicked (int row, const MouseEvent&)
  46911. {
  46912. returnKeyPressed (row);
  46913. }
  46914. void FileSearchPathListComponent::selectedRowsChanged (int)
  46915. {
  46916. updateButtons();
  46917. }
  46918. void FileSearchPathListComponent::paint (Graphics& g)
  46919. {
  46920. g.fillAll (findColour (backgroundColourId));
  46921. }
  46922. void FileSearchPathListComponent::resized()
  46923. {
  46924. const int buttonH = 22;
  46925. const int buttonY = getHeight() - buttonH - 4;
  46926. listBox->setBounds (2, 2, getWidth() - 4, buttonY - 5);
  46927. addButton->setBounds (2, buttonY, buttonH, buttonH);
  46928. removeButton->setBounds (addButton->getRight(), buttonY, buttonH, buttonH);
  46929. changeButton->changeWidthToFitText (buttonH);
  46930. downButton->setSize (buttonH * 2, buttonH);
  46931. upButton->setSize (buttonH * 2, buttonH);
  46932. downButton->setTopRightPosition (getWidth() - 2, buttonY);
  46933. upButton->setTopRightPosition (downButton->getX() - 4, buttonY);
  46934. changeButton->setTopRightPosition (upButton->getX() - 8, buttonY);
  46935. }
  46936. bool FileSearchPathListComponent::isInterestedInFileDrag (const StringArray&)
  46937. {
  46938. return true;
  46939. }
  46940. void FileSearchPathListComponent::filesDropped (const StringArray& filenames, int, int mouseY)
  46941. {
  46942. for (int i = filenames.size(); --i >= 0;)
  46943. {
  46944. const File f (filenames[i]);
  46945. if (f.isDirectory())
  46946. {
  46947. const int row = listBox->getRowContainingPosition (0, mouseY - listBox->getY());
  46948. path.add (f, row);
  46949. changed();
  46950. }
  46951. }
  46952. }
  46953. void FileSearchPathListComponent::buttonClicked (Button* button)
  46954. {
  46955. const int currentRow = listBox->getSelectedRow();
  46956. if (button == removeButton)
  46957. {
  46958. deleteKeyPressed (currentRow);
  46959. }
  46960. else if (button == addButton)
  46961. {
  46962. File start (defaultBrowseTarget);
  46963. if (start == File::nonexistent)
  46964. start = path [0];
  46965. if (start == File::nonexistent)
  46966. start = File::getCurrentWorkingDirectory();
  46967. FileChooser chooser (TRANS("Add a folder..."), start, "*");
  46968. if (chooser.browseForDirectory())
  46969. {
  46970. path.add (chooser.getResult(), currentRow);
  46971. }
  46972. }
  46973. else if (button == changeButton)
  46974. {
  46975. returnKeyPressed (currentRow);
  46976. }
  46977. else if (button == upButton)
  46978. {
  46979. if (currentRow > 0 && currentRow < path.getNumPaths())
  46980. {
  46981. const File f (path[currentRow]);
  46982. path.remove (currentRow);
  46983. path.add (f, currentRow - 1);
  46984. listBox->selectRow (currentRow - 1);
  46985. }
  46986. }
  46987. else if (button == downButton)
  46988. {
  46989. if (currentRow >= 0 && currentRow < path.getNumPaths() - 1)
  46990. {
  46991. const File f (path[currentRow]);
  46992. path.remove (currentRow);
  46993. path.add (f, currentRow + 1);
  46994. listBox->selectRow (currentRow + 1);
  46995. }
  46996. }
  46997. changed();
  46998. }
  46999. END_JUCE_NAMESPACE
  47000. /*** End of inlined file: juce_FileSearchPathListComponent.cpp ***/
  47001. /*** Start of inlined file: juce_FileTreeComponent.cpp ***/
  47002. BEGIN_JUCE_NAMESPACE
  47003. Image* juce_createIconForFile (const File& file);
  47004. class FileListTreeItem : public TreeViewItem,
  47005. public TimeSliceClient,
  47006. public AsyncUpdater,
  47007. public ChangeListener
  47008. {
  47009. public:
  47010. FileListTreeItem (FileTreeComponent& owner_,
  47011. DirectoryContentsList* const parentContentsList_,
  47012. const int indexInContentsList_,
  47013. const File& file_,
  47014. TimeSliceThread& thread_)
  47015. : file (file_),
  47016. owner (owner_),
  47017. parentContentsList (parentContentsList_),
  47018. indexInContentsList (indexInContentsList_),
  47019. subContentsList (0),
  47020. canDeleteSubContentsList (false),
  47021. thread (thread_),
  47022. icon (0)
  47023. {
  47024. DirectoryContentsList::FileInfo fileInfo;
  47025. if (parentContentsList_ != 0
  47026. && parentContentsList_->getFileInfo (indexInContentsList_, fileInfo))
  47027. {
  47028. fileSize = File::descriptionOfSizeInBytes (fileInfo.fileSize);
  47029. modTime = fileInfo.modificationTime.formatted ("%d %b '%y %H:%M");
  47030. isDirectory = fileInfo.isDirectory;
  47031. }
  47032. else
  47033. {
  47034. isDirectory = true;
  47035. }
  47036. }
  47037. ~FileListTreeItem()
  47038. {
  47039. thread.removeTimeSliceClient (this);
  47040. clearSubItems();
  47041. ImageCache::release (icon);
  47042. if (canDeleteSubContentsList)
  47043. delete subContentsList;
  47044. }
  47045. bool mightContainSubItems() { return isDirectory; }
  47046. const String getUniqueName() const { return file.getFullPathName(); }
  47047. int getItemHeight() const { return 22; }
  47048. const String getDragSourceDescription() { return owner.getDragAndDropDescription(); }
  47049. void itemOpennessChanged (bool isNowOpen)
  47050. {
  47051. if (isNowOpen)
  47052. {
  47053. clearSubItems();
  47054. isDirectory = file.isDirectory();
  47055. if (isDirectory)
  47056. {
  47057. if (subContentsList == 0)
  47058. {
  47059. jassert (parentContentsList != 0);
  47060. DirectoryContentsList* const l = new DirectoryContentsList (parentContentsList->getFilter(), thread);
  47061. l->setDirectory (file, true, true);
  47062. setSubContentsList (l);
  47063. canDeleteSubContentsList = true;
  47064. }
  47065. changeListenerCallback (0);
  47066. }
  47067. }
  47068. }
  47069. void setSubContentsList (DirectoryContentsList* newList)
  47070. {
  47071. jassert (subContentsList == 0);
  47072. subContentsList = newList;
  47073. newList->addChangeListener (this);
  47074. }
  47075. void changeListenerCallback (void*)
  47076. {
  47077. clearSubItems();
  47078. if (isOpen() && subContentsList != 0)
  47079. {
  47080. for (int i = 0; i < subContentsList->getNumFiles(); ++i)
  47081. {
  47082. FileListTreeItem* const item
  47083. = new FileListTreeItem (owner, subContentsList, i, subContentsList->getFile(i), thread);
  47084. addSubItem (item);
  47085. }
  47086. }
  47087. }
  47088. void paintItem (Graphics& g, int width, int height)
  47089. {
  47090. if (file != File::nonexistent)
  47091. {
  47092. updateIcon (true);
  47093. if (icon == 0)
  47094. thread.addTimeSliceClient (this);
  47095. }
  47096. owner.getLookAndFeel()
  47097. .drawFileBrowserRow (g, width, height,
  47098. file.getFileName(),
  47099. icon,
  47100. fileSize, modTime,
  47101. isDirectory, isSelected(),
  47102. indexInContentsList);
  47103. }
  47104. void itemClicked (const MouseEvent& e)
  47105. {
  47106. owner.sendMouseClickMessage (file, e);
  47107. }
  47108. void itemDoubleClicked (const MouseEvent& e)
  47109. {
  47110. TreeViewItem::itemDoubleClicked (e);
  47111. owner.sendDoubleClickMessage (file);
  47112. }
  47113. void itemSelectionChanged (bool)
  47114. {
  47115. owner.sendSelectionChangeMessage();
  47116. }
  47117. bool useTimeSlice()
  47118. {
  47119. updateIcon (false);
  47120. thread.removeTimeSliceClient (this);
  47121. return false;
  47122. }
  47123. void handleAsyncUpdate()
  47124. {
  47125. owner.repaint();
  47126. }
  47127. const File file;
  47128. juce_UseDebuggingNewOperator
  47129. private:
  47130. FileTreeComponent& owner;
  47131. DirectoryContentsList* parentContentsList;
  47132. int indexInContentsList;
  47133. DirectoryContentsList* subContentsList;
  47134. bool isDirectory, canDeleteSubContentsList;
  47135. TimeSliceThread& thread;
  47136. Image* icon;
  47137. String fileSize;
  47138. String modTime;
  47139. void updateIcon (const bool onlyUpdateIfCached)
  47140. {
  47141. if (icon == 0)
  47142. {
  47143. const int hashCode = (file.getFullPathName() + "_iconCacheSalt").hashCode();
  47144. Image* im = ImageCache::getFromHashCode (hashCode);
  47145. if (im == 0 && ! onlyUpdateIfCached)
  47146. {
  47147. im = juce_createIconForFile (file);
  47148. if (im != 0)
  47149. ImageCache::addImageToCache (im, hashCode);
  47150. }
  47151. if (im != 0)
  47152. {
  47153. icon = im;
  47154. triggerAsyncUpdate();
  47155. }
  47156. }
  47157. }
  47158. };
  47159. FileTreeComponent::FileTreeComponent (DirectoryContentsList& listToShow)
  47160. : DirectoryContentsDisplayComponent (listToShow)
  47161. {
  47162. FileListTreeItem* const root
  47163. = new FileListTreeItem (*this, 0, 0, listToShow.getDirectory(),
  47164. listToShow.getTimeSliceThread());
  47165. root->setSubContentsList (&listToShow);
  47166. setRootItemVisible (false);
  47167. setRootItem (root);
  47168. }
  47169. FileTreeComponent::~FileTreeComponent()
  47170. {
  47171. deleteRootItem();
  47172. }
  47173. const File FileTreeComponent::getSelectedFile (const int index) const
  47174. {
  47175. const FileListTreeItem* const item = dynamic_cast <const FileListTreeItem*> (getSelectedItem (index));
  47176. return item != 0 ? item->file
  47177. : File::nonexistent;
  47178. }
  47179. void FileTreeComponent::deselectAllFiles()
  47180. {
  47181. clearSelectedItems();
  47182. }
  47183. void FileTreeComponent::scrollToTop()
  47184. {
  47185. getViewport()->getVerticalScrollBar()->setCurrentRangeStart (0);
  47186. }
  47187. void FileTreeComponent::setDragAndDropDescription (const String& description)
  47188. {
  47189. dragAndDropDescription = description;
  47190. }
  47191. END_JUCE_NAMESPACE
  47192. /*** End of inlined file: juce_FileTreeComponent.cpp ***/
  47193. /*** Start of inlined file: juce_ImagePreviewComponent.cpp ***/
  47194. BEGIN_JUCE_NAMESPACE
  47195. ImagePreviewComponent::ImagePreviewComponent()
  47196. {
  47197. }
  47198. ImagePreviewComponent::~ImagePreviewComponent()
  47199. {
  47200. }
  47201. void ImagePreviewComponent::getThumbSize (int& w, int& h) const
  47202. {
  47203. const int availableW = proportionOfWidth (0.97f);
  47204. const int availableH = getHeight() - 13 * 4;
  47205. const double scale = jmin (1.0,
  47206. availableW / (double) w,
  47207. availableH / (double) h);
  47208. w = roundToInt (scale * w);
  47209. h = roundToInt (scale * h);
  47210. }
  47211. void ImagePreviewComponent::selectedFileChanged (const File& file)
  47212. {
  47213. if (fileToLoad != file)
  47214. {
  47215. fileToLoad = file;
  47216. startTimer (100);
  47217. }
  47218. }
  47219. void ImagePreviewComponent::timerCallback()
  47220. {
  47221. stopTimer();
  47222. currentThumbnail = 0;
  47223. currentDetails = String::empty;
  47224. repaint();
  47225. ScopedPointer <FileInputStream> in (fileToLoad.createInputStream());
  47226. if (in != 0)
  47227. {
  47228. ImageFileFormat* const format = ImageFileFormat::findImageFormatForStream (*in);
  47229. if (format != 0)
  47230. {
  47231. currentThumbnail = format->decodeImage (*in);
  47232. if (currentThumbnail != 0)
  47233. {
  47234. int w = currentThumbnail->getWidth();
  47235. int h = currentThumbnail->getHeight();
  47236. currentDetails
  47237. << fileToLoad.getFileName() << "\n"
  47238. << format->getFormatName() << "\n"
  47239. << w << " x " << h << " pixels\n"
  47240. << File::descriptionOfSizeInBytes (fileToLoad.getSize());
  47241. getThumbSize (w, h);
  47242. currentThumbnail = currentThumbnail->createCopy (w, h);
  47243. }
  47244. }
  47245. }
  47246. }
  47247. void ImagePreviewComponent::paint (Graphics& g)
  47248. {
  47249. if (currentThumbnail != 0)
  47250. {
  47251. g.setFont (13.0f);
  47252. int w = currentThumbnail->getWidth();
  47253. int h = currentThumbnail->getHeight();
  47254. getThumbSize (w, h);
  47255. const int numLines = 4;
  47256. const int totalH = 13 * numLines + h + 4;
  47257. const int y = (getHeight() - totalH) / 2;
  47258. g.drawImageWithin (currentThumbnail,
  47259. (getWidth() - w) / 2, y, w, h,
  47260. RectanglePlacement::centred | RectanglePlacement::onlyReduceInSize,
  47261. false);
  47262. g.drawFittedText (currentDetails,
  47263. 0, y + h + 4, getWidth(), 100,
  47264. Justification::centredTop, numLines);
  47265. }
  47266. }
  47267. END_JUCE_NAMESPACE
  47268. /*** End of inlined file: juce_ImagePreviewComponent.cpp ***/
  47269. /*** Start of inlined file: juce_WildcardFileFilter.cpp ***/
  47270. BEGIN_JUCE_NAMESPACE
  47271. WildcardFileFilter::WildcardFileFilter (const String& fileWildcardPatterns,
  47272. const String& directoryWildcardPatterns,
  47273. const String& description_)
  47274. : FileFilter (description_.isEmpty() ? fileWildcardPatterns
  47275. : (description_ + " (" + fileWildcardPatterns + ")"))
  47276. {
  47277. parse (fileWildcardPatterns, fileWildcards);
  47278. parse (directoryWildcardPatterns, directoryWildcards);
  47279. }
  47280. WildcardFileFilter::~WildcardFileFilter()
  47281. {
  47282. }
  47283. bool WildcardFileFilter::isFileSuitable (const File& file) const
  47284. {
  47285. return match (file, fileWildcards);
  47286. }
  47287. bool WildcardFileFilter::isDirectorySuitable (const File& file) const
  47288. {
  47289. return match (file, directoryWildcards);
  47290. }
  47291. void WildcardFileFilter::parse (const String& pattern, StringArray& result)
  47292. {
  47293. result.addTokens (pattern.toLowerCase(), ";,", "\"'");
  47294. result.trim();
  47295. result.removeEmptyStrings();
  47296. // special case for *.*, because people use it to mean "any file", but it
  47297. // would actually ignore files with no extension.
  47298. for (int i = result.size(); --i >= 0;)
  47299. if (result[i] == "*.*")
  47300. result.set (i, "*");
  47301. }
  47302. bool WildcardFileFilter::match (const File& file, const StringArray& wildcards)
  47303. {
  47304. const String filename (file.getFileName());
  47305. for (int i = wildcards.size(); --i >= 0;)
  47306. if (filename.matchesWildcard (wildcards[i], true))
  47307. return true;
  47308. return false;
  47309. }
  47310. END_JUCE_NAMESPACE
  47311. /*** End of inlined file: juce_WildcardFileFilter.cpp ***/
  47312. /*** Start of inlined file: juce_KeyboardFocusTraverser.cpp ***/
  47313. BEGIN_JUCE_NAMESPACE
  47314. KeyboardFocusTraverser::KeyboardFocusTraverser()
  47315. {
  47316. }
  47317. KeyboardFocusTraverser::~KeyboardFocusTraverser()
  47318. {
  47319. }
  47320. namespace KeyboardFocusHelpers
  47321. {
  47322. // This will sort a set of components, so that they are ordered in terms of
  47323. // left-to-right and then top-to-bottom.
  47324. class ScreenPositionComparator
  47325. {
  47326. public:
  47327. ScreenPositionComparator() {}
  47328. static int compareElements (const Component* const first, const Component* const second)
  47329. {
  47330. int explicitOrder1 = first->getExplicitFocusOrder();
  47331. if (explicitOrder1 <= 0)
  47332. explicitOrder1 = std::numeric_limits<int>::max() / 2;
  47333. int explicitOrder2 = second->getExplicitFocusOrder();
  47334. if (explicitOrder2 <= 0)
  47335. explicitOrder2 = std::numeric_limits<int>::max() / 2;
  47336. if (explicitOrder1 != explicitOrder2)
  47337. return explicitOrder1 - explicitOrder2;
  47338. const int diff = first->getY() - second->getY();
  47339. return (diff == 0) ? first->getX() - second->getX()
  47340. : diff;
  47341. }
  47342. };
  47343. static void findAllFocusableComponents (Component* const parent, Array <Component*>& comps)
  47344. {
  47345. if (parent->getNumChildComponents() > 0)
  47346. {
  47347. Array <Component*> localComps;
  47348. ScreenPositionComparator comparator;
  47349. int i;
  47350. for (i = parent->getNumChildComponents(); --i >= 0;)
  47351. {
  47352. Component* const c = parent->getChildComponent (i);
  47353. if (c->isVisible() && c->isEnabled())
  47354. localComps.addSorted (comparator, c);
  47355. }
  47356. for (i = 0; i < localComps.size(); ++i)
  47357. {
  47358. Component* const c = localComps.getUnchecked (i);
  47359. if (c->getWantsKeyboardFocus())
  47360. comps.add (c);
  47361. if (! c->isFocusContainer())
  47362. findAllFocusableComponents (c, comps);
  47363. }
  47364. }
  47365. }
  47366. }
  47367. static Component* getIncrementedComponent (Component* const current, const int delta)
  47368. {
  47369. Component* focusContainer = current->getParentComponent();
  47370. if (focusContainer != 0)
  47371. {
  47372. while (focusContainer->getParentComponent() != 0 && ! focusContainer->isFocusContainer())
  47373. focusContainer = focusContainer->getParentComponent();
  47374. if (focusContainer != 0)
  47375. {
  47376. Array <Component*> comps;
  47377. KeyboardFocusHelpers::findAllFocusableComponents (focusContainer, comps);
  47378. if (comps.size() > 0)
  47379. {
  47380. const int index = comps.indexOf (current);
  47381. return comps [(index + comps.size() + delta) % comps.size()];
  47382. }
  47383. }
  47384. }
  47385. return 0;
  47386. }
  47387. Component* KeyboardFocusTraverser::getNextComponent (Component* current)
  47388. {
  47389. return getIncrementedComponent (current, 1);
  47390. }
  47391. Component* KeyboardFocusTraverser::getPreviousComponent (Component* current)
  47392. {
  47393. return getIncrementedComponent (current, -1);
  47394. }
  47395. Component* KeyboardFocusTraverser::getDefaultComponent (Component* parentComponent)
  47396. {
  47397. Array <Component*> comps;
  47398. if (parentComponent != 0)
  47399. KeyboardFocusHelpers::findAllFocusableComponents (parentComponent, comps);
  47400. return comps.getFirst();
  47401. }
  47402. END_JUCE_NAMESPACE
  47403. /*** End of inlined file: juce_KeyboardFocusTraverser.cpp ***/
  47404. /*** Start of inlined file: juce_KeyListener.cpp ***/
  47405. BEGIN_JUCE_NAMESPACE
  47406. bool KeyListener::keyStateChanged (const bool, Component*)
  47407. {
  47408. return false;
  47409. }
  47410. END_JUCE_NAMESPACE
  47411. /*** End of inlined file: juce_KeyListener.cpp ***/
  47412. /*** Start of inlined file: juce_KeyMappingEditorComponent.cpp ***/
  47413. BEGIN_JUCE_NAMESPACE
  47414. // N.B. these two includes are put here deliberately to avoid problems with
  47415. // old GCCs failing on long include paths
  47416. const int maxKeys = 3;
  47417. class KeyMappingChangeButton : public Button
  47418. {
  47419. public:
  47420. KeyMappingChangeButton (KeyMappingEditorComponent* const owner_,
  47421. const CommandID commandID_,
  47422. const String& keyName,
  47423. const int keyNum_)
  47424. : Button (keyName),
  47425. owner (owner_),
  47426. commandID (commandID_),
  47427. keyNum (keyNum_)
  47428. {
  47429. setWantsKeyboardFocus (false);
  47430. setTriggeredOnMouseDown (keyNum >= 0);
  47431. if (keyNum_ < 0)
  47432. setTooltip (TRANS("adds a new key-mapping"));
  47433. else
  47434. setTooltip (TRANS("click to change this key-mapping"));
  47435. }
  47436. ~KeyMappingChangeButton()
  47437. {
  47438. }
  47439. void paintButton (Graphics& g, bool /*isOver*/, bool /*isDown*/)
  47440. {
  47441. getLookAndFeel().drawKeymapChangeButton (g, getWidth(), getHeight(), *this,
  47442. keyNum >= 0 ? getName() : String::empty);
  47443. }
  47444. void clicked()
  47445. {
  47446. if (keyNum >= 0)
  47447. {
  47448. // existing key clicked..
  47449. PopupMenu m;
  47450. m.addItem (1, TRANS("change this key-mapping"));
  47451. m.addSeparator();
  47452. m.addItem (2, TRANS("remove this key-mapping"));
  47453. const int res = m.show();
  47454. if (res == 1)
  47455. {
  47456. owner->assignNewKey (commandID, keyNum);
  47457. }
  47458. else if (res == 2)
  47459. {
  47460. owner->getMappings()->removeKeyPress (commandID, keyNum);
  47461. }
  47462. }
  47463. else
  47464. {
  47465. // + button pressed..
  47466. owner->assignNewKey (commandID, -1);
  47467. }
  47468. }
  47469. void fitToContent (const int h) throw()
  47470. {
  47471. if (keyNum < 0)
  47472. {
  47473. setSize (h, h);
  47474. }
  47475. else
  47476. {
  47477. Font f (h * 0.6f);
  47478. setSize (jlimit (h * 4, h * 8, 6 + f.getStringWidth (getName())), h);
  47479. }
  47480. }
  47481. juce_UseDebuggingNewOperator
  47482. private:
  47483. KeyMappingEditorComponent* const owner;
  47484. const CommandID commandID;
  47485. const int keyNum;
  47486. KeyMappingChangeButton (const KeyMappingChangeButton&);
  47487. KeyMappingChangeButton& operator= (const KeyMappingChangeButton&);
  47488. };
  47489. class KeyMappingItemComponent : public Component
  47490. {
  47491. public:
  47492. KeyMappingItemComponent (KeyMappingEditorComponent* const owner_,
  47493. const CommandID commandID_)
  47494. : owner (owner_),
  47495. commandID (commandID_)
  47496. {
  47497. setInterceptsMouseClicks (false, true);
  47498. const bool isReadOnly = owner_->isCommandReadOnly (commandID);
  47499. const Array <KeyPress> keyPresses (owner_->getMappings()->getKeyPressesAssignedToCommand (commandID));
  47500. for (int i = 0; i < jmin (maxKeys, keyPresses.size()); ++i)
  47501. {
  47502. KeyMappingChangeButton* const kb
  47503. = new KeyMappingChangeButton (owner_, commandID,
  47504. owner_->getDescriptionForKeyPress (keyPresses.getReference (i)), i);
  47505. kb->setEnabled (! isReadOnly);
  47506. addAndMakeVisible (kb);
  47507. }
  47508. KeyMappingChangeButton* const kb
  47509. = new KeyMappingChangeButton (owner_, commandID, String::empty, -1);
  47510. addChildComponent (kb);
  47511. kb->setVisible (keyPresses.size() < maxKeys && ! isReadOnly);
  47512. }
  47513. ~KeyMappingItemComponent()
  47514. {
  47515. deleteAllChildren();
  47516. }
  47517. void paint (Graphics& g)
  47518. {
  47519. g.setFont (getHeight() * 0.7f);
  47520. g.setColour (findColour (KeyMappingEditorComponent::textColourId));
  47521. g.drawFittedText (owner->getMappings()->getCommandManager()->getNameOfCommand (commandID),
  47522. 4, 0, jmax (40, getChildComponent (0)->getX() - 5), getHeight(),
  47523. Justification::centredLeft, true);
  47524. }
  47525. void resized()
  47526. {
  47527. int x = getWidth() - 4;
  47528. for (int i = getNumChildComponents(); --i >= 0;)
  47529. {
  47530. KeyMappingChangeButton* const kb = dynamic_cast <KeyMappingChangeButton*> (getChildComponent (i));
  47531. kb->fitToContent (getHeight() - 2);
  47532. kb->setTopRightPosition (x, 1);
  47533. x -= kb->getWidth() + 5;
  47534. }
  47535. }
  47536. juce_UseDebuggingNewOperator
  47537. private:
  47538. KeyMappingEditorComponent* const owner;
  47539. const CommandID commandID;
  47540. KeyMappingItemComponent (const KeyMappingItemComponent&);
  47541. KeyMappingItemComponent& operator= (const KeyMappingItemComponent&);
  47542. };
  47543. class KeyMappingTreeViewItem : public TreeViewItem
  47544. {
  47545. public:
  47546. KeyMappingTreeViewItem (KeyMappingEditorComponent* const owner_,
  47547. const CommandID commandID_)
  47548. : owner (owner_),
  47549. commandID (commandID_)
  47550. {
  47551. }
  47552. ~KeyMappingTreeViewItem()
  47553. {
  47554. }
  47555. const String getUniqueName() const { return String ((int) commandID) + "_id"; }
  47556. bool mightContainSubItems() { return false; }
  47557. int getItemHeight() const { return 20; }
  47558. Component* createItemComponent()
  47559. {
  47560. return new KeyMappingItemComponent (owner, commandID);
  47561. }
  47562. juce_UseDebuggingNewOperator
  47563. private:
  47564. KeyMappingEditorComponent* const owner;
  47565. const CommandID commandID;
  47566. KeyMappingTreeViewItem (const KeyMappingTreeViewItem&);
  47567. KeyMappingTreeViewItem& operator= (const KeyMappingTreeViewItem&);
  47568. };
  47569. class KeyCategoryTreeViewItem : public TreeViewItem
  47570. {
  47571. public:
  47572. KeyCategoryTreeViewItem (KeyMappingEditorComponent* const owner_,
  47573. const String& name)
  47574. : owner (owner_),
  47575. categoryName (name)
  47576. {
  47577. }
  47578. ~KeyCategoryTreeViewItem()
  47579. {
  47580. }
  47581. const String getUniqueName() const { return categoryName + "_cat"; }
  47582. bool mightContainSubItems() { return true; }
  47583. int getItemHeight() const { return 28; }
  47584. void paintItem (Graphics& g, int width, int height)
  47585. {
  47586. g.setFont (height * 0.6f, Font::bold);
  47587. g.setColour (owner->findColour (KeyMappingEditorComponent::textColourId));
  47588. g.drawText (categoryName,
  47589. 2, 0, width - 2, height,
  47590. Justification::centredLeft, true);
  47591. }
  47592. void itemOpennessChanged (bool isNowOpen)
  47593. {
  47594. if (isNowOpen)
  47595. {
  47596. if (getNumSubItems() == 0)
  47597. {
  47598. Array <CommandID> commands (owner->getMappings()->getCommandManager()->getCommandsInCategory (categoryName));
  47599. for (int i = 0; i < commands.size(); ++i)
  47600. {
  47601. if (owner->shouldCommandBeIncluded (commands[i]))
  47602. addSubItem (new KeyMappingTreeViewItem (owner, commands[i]));
  47603. }
  47604. }
  47605. }
  47606. else
  47607. {
  47608. clearSubItems();
  47609. }
  47610. }
  47611. juce_UseDebuggingNewOperator
  47612. private:
  47613. KeyMappingEditorComponent* owner;
  47614. String categoryName;
  47615. KeyCategoryTreeViewItem (const KeyCategoryTreeViewItem&);
  47616. KeyCategoryTreeViewItem& operator= (const KeyCategoryTreeViewItem&);
  47617. };
  47618. KeyMappingEditorComponent::KeyMappingEditorComponent (KeyPressMappingSet* const mappingManager,
  47619. const bool showResetToDefaultButton)
  47620. : mappings (mappingManager)
  47621. {
  47622. jassert (mappingManager != 0); // can't be null!
  47623. mappingManager->addChangeListener (this);
  47624. setLinesDrawnForSubItems (false);
  47625. resetButton = 0;
  47626. if (showResetToDefaultButton)
  47627. {
  47628. addAndMakeVisible (resetButton = new TextButton (TRANS("reset to defaults")));
  47629. resetButton->addButtonListener (this);
  47630. }
  47631. addAndMakeVisible (tree = new TreeView());
  47632. tree->setColour (TreeView::backgroundColourId, findColour (backgroundColourId));
  47633. tree->setRootItemVisible (false);
  47634. tree->setDefaultOpenness (true);
  47635. tree->setRootItem (this);
  47636. }
  47637. KeyMappingEditorComponent::~KeyMappingEditorComponent()
  47638. {
  47639. mappings->removeChangeListener (this);
  47640. deleteAllChildren();
  47641. }
  47642. bool KeyMappingEditorComponent::mightContainSubItems()
  47643. {
  47644. return true;
  47645. }
  47646. const String KeyMappingEditorComponent::getUniqueName() const
  47647. {
  47648. return "keys";
  47649. }
  47650. void KeyMappingEditorComponent::setColours (const Colour& mainBackground,
  47651. const Colour& textColour)
  47652. {
  47653. setColour (backgroundColourId, mainBackground);
  47654. setColour (textColourId, textColour);
  47655. tree->setColour (TreeView::backgroundColourId, mainBackground);
  47656. }
  47657. void KeyMappingEditorComponent::parentHierarchyChanged()
  47658. {
  47659. changeListenerCallback (0);
  47660. }
  47661. void KeyMappingEditorComponent::resized()
  47662. {
  47663. int h = getHeight();
  47664. if (resetButton != 0)
  47665. {
  47666. const int buttonHeight = 20;
  47667. h -= buttonHeight + 8;
  47668. int x = getWidth() - 8;
  47669. const int y = h + 6;
  47670. resetButton->changeWidthToFitText (buttonHeight);
  47671. resetButton->setTopRightPosition (x, y);
  47672. }
  47673. tree->setBounds (0, 0, getWidth(), h);
  47674. }
  47675. void KeyMappingEditorComponent::buttonClicked (Button* button)
  47676. {
  47677. if (button == resetButton)
  47678. {
  47679. if (AlertWindow::showOkCancelBox (AlertWindow::QuestionIcon,
  47680. TRANS("Reset to defaults"),
  47681. TRANS("Are you sure you want to reset all the key-mappings to their default state?"),
  47682. TRANS("Reset")))
  47683. {
  47684. mappings->resetToDefaultMappings();
  47685. }
  47686. }
  47687. }
  47688. void KeyMappingEditorComponent::changeListenerCallback (void*)
  47689. {
  47690. ScopedPointer <XmlElement> openness (tree->getOpennessState (true));
  47691. clearSubItems();
  47692. const StringArray categories (mappings->getCommandManager()->getCommandCategories());
  47693. for (int i = 0; i < categories.size(); ++i)
  47694. {
  47695. const Array <CommandID> commands (mappings->getCommandManager()->getCommandsInCategory (categories[i]));
  47696. int count = 0;
  47697. for (int j = 0; j < commands.size(); ++j)
  47698. if (shouldCommandBeIncluded (commands[j]))
  47699. ++count;
  47700. if (count > 0)
  47701. addSubItem (new KeyCategoryTreeViewItem (this, categories[i]));
  47702. }
  47703. if (openness != 0)
  47704. tree->restoreOpennessState (*openness);
  47705. }
  47706. class KeyEntryWindow : public AlertWindow
  47707. {
  47708. public:
  47709. KeyEntryWindow (KeyMappingEditorComponent* const owner_)
  47710. : AlertWindow (TRANS("New key-mapping"),
  47711. TRANS("Please press a key combination now..."),
  47712. AlertWindow::NoIcon),
  47713. owner (owner_)
  47714. {
  47715. addButton (TRANS("ok"), 1);
  47716. addButton (TRANS("cancel"), 0);
  47717. // (avoid return + escape keys getting processed by the buttons..)
  47718. for (int i = getNumChildComponents(); --i >= 0;)
  47719. getChildComponent (i)->setWantsKeyboardFocus (false);
  47720. setWantsKeyboardFocus (true);
  47721. grabKeyboardFocus();
  47722. }
  47723. ~KeyEntryWindow()
  47724. {
  47725. }
  47726. bool keyPressed (const KeyPress& key)
  47727. {
  47728. lastPress = key;
  47729. String message (TRANS("Key: ") + owner->getDescriptionForKeyPress (key));
  47730. const CommandID previousCommand = owner->getMappings()->findCommandForKeyPress (key);
  47731. if (previousCommand != 0)
  47732. {
  47733. message << "\n\n"
  47734. << TRANS("(Currently assigned to \"")
  47735. << owner->getMappings()->getCommandManager()->getNameOfCommand (previousCommand)
  47736. << "\")";
  47737. }
  47738. setMessage (message);
  47739. return true;
  47740. }
  47741. bool keyStateChanged (bool)
  47742. {
  47743. return true;
  47744. }
  47745. KeyPress lastPress;
  47746. juce_UseDebuggingNewOperator
  47747. private:
  47748. KeyMappingEditorComponent* owner;
  47749. KeyEntryWindow (const KeyEntryWindow&);
  47750. KeyEntryWindow& operator= (const KeyEntryWindow&);
  47751. };
  47752. void KeyMappingEditorComponent::assignNewKey (const CommandID commandID, const int index)
  47753. {
  47754. KeyEntryWindow entryWindow (this);
  47755. if (entryWindow.runModalLoop() != 0)
  47756. {
  47757. entryWindow.setVisible (false);
  47758. if (entryWindow.lastPress.isValid())
  47759. {
  47760. const CommandID previousCommand = mappings->findCommandForKeyPress (entryWindow.lastPress);
  47761. if (previousCommand != 0)
  47762. {
  47763. if (! AlertWindow::showOkCancelBox (AlertWindow::WarningIcon,
  47764. TRANS("Change key-mapping"),
  47765. TRANS("This key is already assigned to the command \"")
  47766. + mappings->getCommandManager()->getNameOfCommand (previousCommand)
  47767. + TRANS("\"\n\nDo you want to re-assign it to this new command instead?"),
  47768. TRANS("re-assign"),
  47769. TRANS("cancel")))
  47770. {
  47771. return;
  47772. }
  47773. }
  47774. mappings->removeKeyPress (entryWindow.lastPress);
  47775. if (index >= 0)
  47776. mappings->removeKeyPress (commandID, index);
  47777. mappings->addKeyPress (commandID, entryWindow.lastPress, index);
  47778. }
  47779. }
  47780. }
  47781. bool KeyMappingEditorComponent::shouldCommandBeIncluded (const CommandID commandID)
  47782. {
  47783. const ApplicationCommandInfo* const ci = mappings->getCommandManager()->getCommandForID (commandID);
  47784. return (ci != 0) && ((ci->flags & ApplicationCommandInfo::hiddenFromKeyEditor) == 0);
  47785. }
  47786. bool KeyMappingEditorComponent::isCommandReadOnly (const CommandID commandID)
  47787. {
  47788. const ApplicationCommandInfo* const ci = mappings->getCommandManager()->getCommandForID (commandID);
  47789. return (ci != 0) && ((ci->flags & ApplicationCommandInfo::readOnlyInKeyEditor) != 0);
  47790. }
  47791. const String KeyMappingEditorComponent::getDescriptionForKeyPress (const KeyPress& key)
  47792. {
  47793. return key.getTextDescription();
  47794. }
  47795. END_JUCE_NAMESPACE
  47796. /*** End of inlined file: juce_KeyMappingEditorComponent.cpp ***/
  47797. /*** Start of inlined file: juce_KeyPress.cpp ***/
  47798. BEGIN_JUCE_NAMESPACE
  47799. KeyPress::KeyPress() throw()
  47800. : keyCode (0),
  47801. mods (0),
  47802. textCharacter (0)
  47803. {
  47804. }
  47805. KeyPress::KeyPress (const int keyCode_,
  47806. const ModifierKeys& mods_,
  47807. const juce_wchar textCharacter_) throw()
  47808. : keyCode (keyCode_),
  47809. mods (mods_),
  47810. textCharacter (textCharacter_)
  47811. {
  47812. }
  47813. KeyPress::KeyPress (const int keyCode_) throw()
  47814. : keyCode (keyCode_),
  47815. textCharacter (0)
  47816. {
  47817. }
  47818. KeyPress::KeyPress (const KeyPress& other) throw()
  47819. : keyCode (other.keyCode),
  47820. mods (other.mods),
  47821. textCharacter (other.textCharacter)
  47822. {
  47823. }
  47824. KeyPress& KeyPress::operator= (const KeyPress& other) throw()
  47825. {
  47826. keyCode = other.keyCode;
  47827. mods = other.mods;
  47828. textCharacter = other.textCharacter;
  47829. return *this;
  47830. }
  47831. bool KeyPress::operator== (const KeyPress& other) const throw()
  47832. {
  47833. return mods.getRawFlags() == other.mods.getRawFlags()
  47834. && (textCharacter == other.textCharacter
  47835. || textCharacter == 0
  47836. || other.textCharacter == 0)
  47837. && (keyCode == other.keyCode
  47838. || (keyCode < 256
  47839. && other.keyCode < 256
  47840. && CharacterFunctions::toLowerCase ((juce_wchar) keyCode)
  47841. == CharacterFunctions::toLowerCase ((juce_wchar) other.keyCode)));
  47842. }
  47843. bool KeyPress::operator!= (const KeyPress& other) const throw()
  47844. {
  47845. return ! operator== (other);
  47846. }
  47847. bool KeyPress::isCurrentlyDown() const
  47848. {
  47849. return isKeyCurrentlyDown (keyCode)
  47850. && (ModifierKeys::getCurrentModifiers().getRawFlags() & ModifierKeys::allKeyboardModifiers)
  47851. == (mods.getRawFlags() & ModifierKeys::allKeyboardModifiers);
  47852. }
  47853. namespace KeyPressHelpers
  47854. {
  47855. struct KeyNameAndCode
  47856. {
  47857. const char* name;
  47858. int code;
  47859. };
  47860. static const KeyNameAndCode translations[] =
  47861. {
  47862. { "spacebar", KeyPress::spaceKey },
  47863. { "return", KeyPress::returnKey },
  47864. { "escape", KeyPress::escapeKey },
  47865. { "backspace", KeyPress::backspaceKey },
  47866. { "cursor left", KeyPress::leftKey },
  47867. { "cursor right", KeyPress::rightKey },
  47868. { "cursor up", KeyPress::upKey },
  47869. { "cursor down", KeyPress::downKey },
  47870. { "page up", KeyPress::pageUpKey },
  47871. { "page down", KeyPress::pageDownKey },
  47872. { "home", KeyPress::homeKey },
  47873. { "end", KeyPress::endKey },
  47874. { "delete", KeyPress::deleteKey },
  47875. { "insert", KeyPress::insertKey },
  47876. { "tab", KeyPress::tabKey },
  47877. { "play", KeyPress::playKey },
  47878. { "stop", KeyPress::stopKey },
  47879. { "fast forward", KeyPress::fastForwardKey },
  47880. { "rewind", KeyPress::rewindKey }
  47881. };
  47882. static const String numberPadPrefix() { return "numpad "; }
  47883. }
  47884. const KeyPress KeyPress::createFromDescription (const String& desc)
  47885. {
  47886. int modifiers = 0;
  47887. if (desc.containsWholeWordIgnoreCase ("ctrl")
  47888. || desc.containsWholeWordIgnoreCase ("control")
  47889. || desc.containsWholeWordIgnoreCase ("ctl"))
  47890. modifiers |= ModifierKeys::ctrlModifier;
  47891. if (desc.containsWholeWordIgnoreCase ("shift")
  47892. || desc.containsWholeWordIgnoreCase ("shft"))
  47893. modifiers |= ModifierKeys::shiftModifier;
  47894. if (desc.containsWholeWordIgnoreCase ("alt")
  47895. || desc.containsWholeWordIgnoreCase ("option"))
  47896. modifiers |= ModifierKeys::altModifier;
  47897. if (desc.containsWholeWordIgnoreCase ("command")
  47898. || desc.containsWholeWordIgnoreCase ("cmd"))
  47899. modifiers |= ModifierKeys::commandModifier;
  47900. int key = 0;
  47901. for (int i = 0; i < numElementsInArray (KeyPressHelpers::translations); ++i)
  47902. {
  47903. if (desc.containsWholeWordIgnoreCase (String (KeyPressHelpers::translations[i].name)))
  47904. {
  47905. key = KeyPressHelpers::translations[i].code;
  47906. break;
  47907. }
  47908. }
  47909. if (key == 0)
  47910. {
  47911. // see if it's a numpad key..
  47912. if (desc.containsIgnoreCase (KeyPressHelpers::numberPadPrefix()))
  47913. {
  47914. const juce_wchar lastChar = desc.trimEnd().getLastCharacter();
  47915. if (lastChar >= '0' && lastChar <= '9')
  47916. key = numberPad0 + lastChar - '0';
  47917. else if (lastChar == '+')
  47918. key = numberPadAdd;
  47919. else if (lastChar == '-')
  47920. key = numberPadSubtract;
  47921. else if (lastChar == '*')
  47922. key = numberPadMultiply;
  47923. else if (lastChar == '/')
  47924. key = numberPadDivide;
  47925. else if (lastChar == '.')
  47926. key = numberPadDecimalPoint;
  47927. else if (lastChar == '=')
  47928. key = numberPadEquals;
  47929. else if (desc.endsWith ("separator"))
  47930. key = numberPadSeparator;
  47931. else if (desc.endsWith ("delete"))
  47932. key = numberPadDelete;
  47933. }
  47934. if (key == 0)
  47935. {
  47936. // see if it's a function key..
  47937. for (int i = 1; i <= 12; ++i)
  47938. if (desc.containsWholeWordIgnoreCase ("f" + String (i)))
  47939. key = F1Key + i - 1;
  47940. if (key == 0)
  47941. {
  47942. // give up and use the hex code..
  47943. const int hexCode = desc.fromFirstOccurrenceOf ("#", false, false)
  47944. .toLowerCase()
  47945. .retainCharacters ("0123456789abcdef")
  47946. .getHexValue32();
  47947. if (hexCode > 0)
  47948. key = hexCode;
  47949. else
  47950. key = CharacterFunctions::toUpperCase (desc.getLastCharacter());
  47951. }
  47952. }
  47953. }
  47954. return KeyPress (key, ModifierKeys (modifiers), 0);
  47955. }
  47956. const String KeyPress::getTextDescription() const
  47957. {
  47958. String desc;
  47959. if (keyCode > 0)
  47960. {
  47961. // some keyboard layouts use a shift-key to get the slash, but in those cases, we
  47962. // want to store it as being a slash, not shift+whatever.
  47963. if (textCharacter == '/')
  47964. return "/";
  47965. if (mods.isCtrlDown())
  47966. desc << "ctrl + ";
  47967. if (mods.isShiftDown())
  47968. desc << "shift + ";
  47969. #if JUCE_MAC
  47970. // only do this on the mac, because on Windows ctrl and command are the same,
  47971. // and this would get confusing
  47972. if (mods.isCommandDown())
  47973. desc << "command + ";
  47974. if (mods.isAltDown())
  47975. desc << "option + ";
  47976. #else
  47977. if (mods.isAltDown())
  47978. desc << "alt + ";
  47979. #endif
  47980. for (int i = 0; i < numElementsInArray (KeyPressHelpers::translations); ++i)
  47981. if (keyCode == KeyPressHelpers::translations[i].code)
  47982. return desc + KeyPressHelpers::translations[i].name;
  47983. if (keyCode >= F1Key && keyCode <= F16Key)
  47984. desc << 'F' << (1 + keyCode - F1Key);
  47985. else if (keyCode >= numberPad0 && keyCode <= numberPad9)
  47986. desc << KeyPressHelpers::numberPadPrefix() << (keyCode - numberPad0);
  47987. else if (keyCode >= 33 && keyCode < 176)
  47988. desc += CharacterFunctions::toUpperCase ((juce_wchar) keyCode);
  47989. else if (keyCode == numberPadAdd)
  47990. desc << KeyPressHelpers::numberPadPrefix() << '+';
  47991. else if (keyCode == numberPadSubtract)
  47992. desc << KeyPressHelpers::numberPadPrefix() << '-';
  47993. else if (keyCode == numberPadMultiply)
  47994. desc << KeyPressHelpers::numberPadPrefix() << '*';
  47995. else if (keyCode == numberPadDivide)
  47996. desc << KeyPressHelpers::numberPadPrefix() << '/';
  47997. else if (keyCode == numberPadSeparator)
  47998. desc << KeyPressHelpers::numberPadPrefix() << "separator";
  47999. else if (keyCode == numberPadDecimalPoint)
  48000. desc << KeyPressHelpers::numberPadPrefix() << '.';
  48001. else if (keyCode == numberPadDelete)
  48002. desc << KeyPressHelpers::numberPadPrefix() << "delete";
  48003. else
  48004. desc << '#' << String::toHexString (keyCode);
  48005. }
  48006. return desc;
  48007. }
  48008. END_JUCE_NAMESPACE
  48009. /*** End of inlined file: juce_KeyPress.cpp ***/
  48010. /*** Start of inlined file: juce_KeyPressMappingSet.cpp ***/
  48011. BEGIN_JUCE_NAMESPACE
  48012. KeyPressMappingSet::KeyPressMappingSet (ApplicationCommandManager* const commandManager_)
  48013. : commandManager (commandManager_)
  48014. {
  48015. // A manager is needed to get the descriptions of commands, and will be called when
  48016. // a command is invoked. So you can't leave this null..
  48017. jassert (commandManager_ != 0);
  48018. Desktop::getInstance().addFocusChangeListener (this);
  48019. }
  48020. KeyPressMappingSet::KeyPressMappingSet (const KeyPressMappingSet& other)
  48021. : commandManager (other.commandManager)
  48022. {
  48023. Desktop::getInstance().addFocusChangeListener (this);
  48024. }
  48025. KeyPressMappingSet::~KeyPressMappingSet()
  48026. {
  48027. Desktop::getInstance().removeFocusChangeListener (this);
  48028. }
  48029. const Array <KeyPress> KeyPressMappingSet::getKeyPressesAssignedToCommand (const CommandID commandID) const
  48030. {
  48031. for (int i = 0; i < mappings.size(); ++i)
  48032. if (mappings.getUnchecked(i)->commandID == commandID)
  48033. return mappings.getUnchecked (i)->keypresses;
  48034. return Array <KeyPress> ();
  48035. }
  48036. void KeyPressMappingSet::addKeyPress (const CommandID commandID,
  48037. const KeyPress& newKeyPress,
  48038. int insertIndex)
  48039. {
  48040. // If you specify an upper-case letter but no shift key, how is the user supposed to press it!?
  48041. // Stick to lower-case letters when defining a keypress, to avoid ambiguity.
  48042. jassert (! (CharacterFunctions::isUpperCase (newKeyPress.getTextCharacter())
  48043. && ! newKeyPress.getModifiers().isShiftDown()));
  48044. if (findCommandForKeyPress (newKeyPress) != commandID)
  48045. {
  48046. removeKeyPress (newKeyPress);
  48047. if (newKeyPress.isValid())
  48048. {
  48049. for (int i = mappings.size(); --i >= 0;)
  48050. {
  48051. if (mappings.getUnchecked(i)->commandID == commandID)
  48052. {
  48053. mappings.getUnchecked(i)->keypresses.insert (insertIndex, newKeyPress);
  48054. sendChangeMessage (this);
  48055. return;
  48056. }
  48057. }
  48058. const ApplicationCommandInfo* const ci = commandManager->getCommandForID (commandID);
  48059. if (ci != 0)
  48060. {
  48061. CommandMapping* const cm = new CommandMapping();
  48062. cm->commandID = commandID;
  48063. cm->keypresses.add (newKeyPress);
  48064. cm->wantsKeyUpDownCallbacks = (ci->flags & ApplicationCommandInfo::wantsKeyUpDownCallbacks) != 0;
  48065. mappings.add (cm);
  48066. sendChangeMessage (this);
  48067. }
  48068. }
  48069. }
  48070. }
  48071. void KeyPressMappingSet::resetToDefaultMappings()
  48072. {
  48073. mappings.clear();
  48074. for (int i = 0; i < commandManager->getNumCommands(); ++i)
  48075. {
  48076. const ApplicationCommandInfo* const ci = commandManager->getCommandForIndex (i);
  48077. for (int j = 0; j < ci->defaultKeypresses.size(); ++j)
  48078. {
  48079. addKeyPress (ci->commandID,
  48080. ci->defaultKeypresses.getReference (j));
  48081. }
  48082. }
  48083. sendChangeMessage (this);
  48084. }
  48085. void KeyPressMappingSet::resetToDefaultMapping (const CommandID commandID)
  48086. {
  48087. clearAllKeyPresses (commandID);
  48088. const ApplicationCommandInfo* const ci = commandManager->getCommandForID (commandID);
  48089. for (int j = 0; j < ci->defaultKeypresses.size(); ++j)
  48090. {
  48091. addKeyPress (ci->commandID,
  48092. ci->defaultKeypresses.getReference (j));
  48093. }
  48094. }
  48095. void KeyPressMappingSet::clearAllKeyPresses()
  48096. {
  48097. if (mappings.size() > 0)
  48098. {
  48099. sendChangeMessage (this);
  48100. mappings.clear();
  48101. }
  48102. }
  48103. void KeyPressMappingSet::clearAllKeyPresses (const CommandID commandID)
  48104. {
  48105. for (int i = mappings.size(); --i >= 0;)
  48106. {
  48107. if (mappings.getUnchecked(i)->commandID == commandID)
  48108. {
  48109. mappings.remove (i);
  48110. sendChangeMessage (this);
  48111. }
  48112. }
  48113. }
  48114. void KeyPressMappingSet::removeKeyPress (const KeyPress& keypress)
  48115. {
  48116. if (keypress.isValid())
  48117. {
  48118. for (int i = mappings.size(); --i >= 0;)
  48119. {
  48120. CommandMapping* const cm = mappings.getUnchecked(i);
  48121. for (int j = cm->keypresses.size(); --j >= 0;)
  48122. {
  48123. if (keypress == cm->keypresses [j])
  48124. {
  48125. cm->keypresses.remove (j);
  48126. sendChangeMessage (this);
  48127. }
  48128. }
  48129. }
  48130. }
  48131. }
  48132. void KeyPressMappingSet::removeKeyPress (const CommandID commandID, const int keyPressIndex)
  48133. {
  48134. for (int i = mappings.size(); --i >= 0;)
  48135. {
  48136. if (mappings.getUnchecked(i)->commandID == commandID)
  48137. {
  48138. mappings.getUnchecked(i)->keypresses.remove (keyPressIndex);
  48139. sendChangeMessage (this);
  48140. break;
  48141. }
  48142. }
  48143. }
  48144. CommandID KeyPressMappingSet::findCommandForKeyPress (const KeyPress& keyPress) const throw()
  48145. {
  48146. for (int i = 0; i < mappings.size(); ++i)
  48147. if (mappings.getUnchecked(i)->keypresses.contains (keyPress))
  48148. return mappings.getUnchecked(i)->commandID;
  48149. return 0;
  48150. }
  48151. bool KeyPressMappingSet::containsMapping (const CommandID commandID, const KeyPress& keyPress) const throw()
  48152. {
  48153. for (int i = mappings.size(); --i >= 0;)
  48154. if (mappings.getUnchecked(i)->commandID == commandID)
  48155. return mappings.getUnchecked(i)->keypresses.contains (keyPress);
  48156. return false;
  48157. }
  48158. void KeyPressMappingSet::invokeCommand (const CommandID commandID,
  48159. const KeyPress& key,
  48160. const bool isKeyDown,
  48161. const int millisecsSinceKeyPressed,
  48162. Component* const originatingComponent) const
  48163. {
  48164. ApplicationCommandTarget::InvocationInfo info (commandID);
  48165. info.invocationMethod = ApplicationCommandTarget::InvocationInfo::fromKeyPress;
  48166. info.isKeyDown = isKeyDown;
  48167. info.keyPress = key;
  48168. info.millisecsSinceKeyPressed = millisecsSinceKeyPressed;
  48169. info.originatingComponent = originatingComponent;
  48170. commandManager->invoke (info, false);
  48171. }
  48172. bool KeyPressMappingSet::restoreFromXml (const XmlElement& xmlVersion)
  48173. {
  48174. if (xmlVersion.hasTagName ("KEYMAPPINGS"))
  48175. {
  48176. if (xmlVersion.getBoolAttribute ("basedOnDefaults", true))
  48177. {
  48178. // if the XML was created as a set of differences from the default mappings,
  48179. // (i.e. by calling createXml (true)), then we need to first restore the defaults.
  48180. resetToDefaultMappings();
  48181. }
  48182. else
  48183. {
  48184. // if the XML was created calling createXml (false), then we need to clear all
  48185. // the keys and treat the xml as describing the entire set of mappings.
  48186. clearAllKeyPresses();
  48187. }
  48188. forEachXmlChildElement (xmlVersion, map)
  48189. {
  48190. const CommandID commandId = map->getStringAttribute ("commandId").getHexValue32();
  48191. if (commandId != 0)
  48192. {
  48193. const KeyPress key (KeyPress::createFromDescription (map->getStringAttribute ("key")));
  48194. if (map->hasTagName ("MAPPING"))
  48195. {
  48196. addKeyPress (commandId, key);
  48197. }
  48198. else if (map->hasTagName ("UNMAPPING"))
  48199. {
  48200. if (containsMapping (commandId, key))
  48201. removeKeyPress (key);
  48202. }
  48203. }
  48204. }
  48205. return true;
  48206. }
  48207. return false;
  48208. }
  48209. XmlElement* KeyPressMappingSet::createXml (const bool saveDifferencesFromDefaultSet) const
  48210. {
  48211. ScopedPointer <KeyPressMappingSet> defaultSet;
  48212. if (saveDifferencesFromDefaultSet)
  48213. {
  48214. defaultSet = new KeyPressMappingSet (commandManager);
  48215. defaultSet->resetToDefaultMappings();
  48216. }
  48217. XmlElement* const doc = new XmlElement ("KEYMAPPINGS");
  48218. doc->setAttribute ("basedOnDefaults", saveDifferencesFromDefaultSet);
  48219. int i;
  48220. for (i = 0; i < mappings.size(); ++i)
  48221. {
  48222. const CommandMapping* const cm = mappings.getUnchecked(i);
  48223. for (int j = 0; j < cm->keypresses.size(); ++j)
  48224. {
  48225. if (defaultSet == 0
  48226. || ! defaultSet->containsMapping (cm->commandID, cm->keypresses.getReference (j)))
  48227. {
  48228. XmlElement* const map = doc->createNewChildElement ("MAPPING");
  48229. map->setAttribute ("commandId", String::toHexString ((int) cm->commandID));
  48230. map->setAttribute ("description", commandManager->getDescriptionOfCommand (cm->commandID));
  48231. map->setAttribute ("key", cm->keypresses.getReference (j).getTextDescription());
  48232. }
  48233. }
  48234. }
  48235. if (defaultSet != 0)
  48236. {
  48237. for (i = 0; i < defaultSet->mappings.size(); ++i)
  48238. {
  48239. const CommandMapping* const cm = defaultSet->mappings.getUnchecked(i);
  48240. for (int j = 0; j < cm->keypresses.size(); ++j)
  48241. {
  48242. if (! containsMapping (cm->commandID, cm->keypresses.getReference (j)))
  48243. {
  48244. XmlElement* const map = doc->createNewChildElement ("UNMAPPING");
  48245. map->setAttribute ("commandId", String::toHexString ((int) cm->commandID));
  48246. map->setAttribute ("description", commandManager->getDescriptionOfCommand (cm->commandID));
  48247. map->setAttribute ("key", cm->keypresses.getReference (j).getTextDescription());
  48248. }
  48249. }
  48250. }
  48251. }
  48252. return doc;
  48253. }
  48254. bool KeyPressMappingSet::keyPressed (const KeyPress& key,
  48255. Component* originatingComponent)
  48256. {
  48257. bool used = false;
  48258. const CommandID commandID = findCommandForKeyPress (key);
  48259. const ApplicationCommandInfo* const ci = commandManager->getCommandForID (commandID);
  48260. if (ci != 0
  48261. && (ci->flags & ApplicationCommandInfo::wantsKeyUpDownCallbacks) == 0)
  48262. {
  48263. ApplicationCommandInfo info (0);
  48264. if (commandManager->getTargetForCommand (commandID, info) != 0
  48265. && (info.flags & ApplicationCommandInfo::isDisabled) == 0)
  48266. {
  48267. invokeCommand (commandID, key, true, 0, originatingComponent);
  48268. used = true;
  48269. }
  48270. else
  48271. {
  48272. if (originatingComponent != 0)
  48273. originatingComponent->getLookAndFeel().playAlertSound();
  48274. }
  48275. }
  48276. return used;
  48277. }
  48278. bool KeyPressMappingSet::keyStateChanged (const bool /*isKeyDown*/, Component* originatingComponent)
  48279. {
  48280. bool used = false;
  48281. const uint32 now = Time::getMillisecondCounter();
  48282. for (int i = mappings.size(); --i >= 0;)
  48283. {
  48284. CommandMapping* const cm = mappings.getUnchecked(i);
  48285. if (cm->wantsKeyUpDownCallbacks)
  48286. {
  48287. for (int j = cm->keypresses.size(); --j >= 0;)
  48288. {
  48289. const KeyPress key (cm->keypresses.getReference (j));
  48290. const bool isDown = key.isCurrentlyDown();
  48291. int keyPressEntryIndex = 0;
  48292. bool wasDown = false;
  48293. for (int k = keysDown.size(); --k >= 0;)
  48294. {
  48295. if (key == keysDown.getUnchecked(k)->key)
  48296. {
  48297. keyPressEntryIndex = k;
  48298. wasDown = true;
  48299. used = true;
  48300. break;
  48301. }
  48302. }
  48303. if (isDown != wasDown)
  48304. {
  48305. int millisecs = 0;
  48306. if (isDown)
  48307. {
  48308. KeyPressTime* const k = new KeyPressTime();
  48309. k->key = key;
  48310. k->timeWhenPressed = now;
  48311. keysDown.add (k);
  48312. }
  48313. else
  48314. {
  48315. const uint32 pressTime = keysDown.getUnchecked (keyPressEntryIndex)->timeWhenPressed;
  48316. if (now > pressTime)
  48317. millisecs = now - pressTime;
  48318. keysDown.remove (keyPressEntryIndex);
  48319. }
  48320. invokeCommand (cm->commandID, key, isDown, millisecs, originatingComponent);
  48321. used = true;
  48322. }
  48323. }
  48324. }
  48325. }
  48326. return used;
  48327. }
  48328. void KeyPressMappingSet::globalFocusChanged (Component* focusedComponent)
  48329. {
  48330. if (focusedComponent != 0)
  48331. focusedComponent->keyStateChanged (false);
  48332. }
  48333. END_JUCE_NAMESPACE
  48334. /*** End of inlined file: juce_KeyPressMappingSet.cpp ***/
  48335. /*** Start of inlined file: juce_ModifierKeys.cpp ***/
  48336. BEGIN_JUCE_NAMESPACE
  48337. ModifierKeys::ModifierKeys (const int flags_) throw()
  48338. : flags (flags_)
  48339. {
  48340. }
  48341. ModifierKeys::ModifierKeys (const ModifierKeys& other) throw()
  48342. : flags (other.flags)
  48343. {
  48344. }
  48345. ModifierKeys& ModifierKeys::operator= (const ModifierKeys& other) throw()
  48346. {
  48347. flags = other.flags;
  48348. return *this;
  48349. }
  48350. ModifierKeys ModifierKeys::currentModifiers;
  48351. const ModifierKeys ModifierKeys::getCurrentModifiers() throw()
  48352. {
  48353. return currentModifiers;
  48354. }
  48355. int ModifierKeys::getNumMouseButtonsDown() const throw()
  48356. {
  48357. int num = 0;
  48358. if (isLeftButtonDown()) ++num;
  48359. if (isRightButtonDown()) ++num;
  48360. if (isMiddleButtonDown()) ++num;
  48361. return num;
  48362. }
  48363. END_JUCE_NAMESPACE
  48364. /*** End of inlined file: juce_ModifierKeys.cpp ***/
  48365. /*** Start of inlined file: juce_ComponentAnimator.cpp ***/
  48366. BEGIN_JUCE_NAMESPACE
  48367. class ComponentAnimator::AnimationTask
  48368. {
  48369. public:
  48370. AnimationTask (Component* const comp)
  48371. : component (comp)
  48372. {
  48373. }
  48374. Component::SafePointer<Component> component;
  48375. Rectangle<int> destination;
  48376. int msElapsed, msTotal;
  48377. double startSpeed, midSpeed, endSpeed, lastProgress;
  48378. double left, top, right, bottom;
  48379. bool useTimeslice (const int elapsed)
  48380. {
  48381. if (component == 0)
  48382. return false;
  48383. msElapsed += elapsed;
  48384. double newProgress = msElapsed / (double) msTotal;
  48385. if (newProgress >= 0 && newProgress < 1.0)
  48386. {
  48387. newProgress = timeToDistance (newProgress);
  48388. const double delta = (newProgress - lastProgress) / (1.0 - lastProgress);
  48389. jassert (newProgress >= lastProgress);
  48390. lastProgress = newProgress;
  48391. left += (destination.getX() - left) * delta;
  48392. top += (destination.getY() - top) * delta;
  48393. right += (destination.getRight() - right) * delta;
  48394. bottom += (destination.getBottom() - bottom) * delta;
  48395. if (delta < 1.0)
  48396. {
  48397. const Rectangle<int> newBounds (roundToInt (left),
  48398. roundToInt (top),
  48399. roundToInt (right - left),
  48400. roundToInt (bottom - top));
  48401. if (newBounds != destination)
  48402. {
  48403. component->setBounds (newBounds);
  48404. return true;
  48405. }
  48406. }
  48407. }
  48408. component->setBounds (destination);
  48409. return false;
  48410. }
  48411. void moveToFinalDestination()
  48412. {
  48413. if (component != 0)
  48414. component->setBounds (destination);
  48415. }
  48416. private:
  48417. inline double timeToDistance (const double time) const
  48418. {
  48419. return (time < 0.5) ? time * (startSpeed + time * (midSpeed - startSpeed))
  48420. : 0.5 * (startSpeed + 0.5 * (midSpeed - startSpeed))
  48421. + (time - 0.5) * (midSpeed + (time - 0.5) * (endSpeed - midSpeed));
  48422. }
  48423. };
  48424. ComponentAnimator::ComponentAnimator()
  48425. : lastTime (0)
  48426. {
  48427. }
  48428. ComponentAnimator::~ComponentAnimator()
  48429. {
  48430. cancelAllAnimations (false);
  48431. jassert (tasks.size() == 0);
  48432. }
  48433. ComponentAnimator::AnimationTask* ComponentAnimator::findTaskFor (Component* const component) const
  48434. {
  48435. for (int i = tasks.size(); --i >= 0;)
  48436. if (component == tasks.getUnchecked(i)->component.getComponent())
  48437. return tasks.getUnchecked(i);
  48438. return 0;
  48439. }
  48440. void ComponentAnimator::animateComponent (Component* const component,
  48441. const Rectangle<int>& finalPosition,
  48442. const int millisecondsToSpendMoving,
  48443. const double startSpeed,
  48444. const double endSpeed)
  48445. {
  48446. if (component != 0)
  48447. {
  48448. AnimationTask* at = findTaskFor (component);
  48449. if (at == 0)
  48450. {
  48451. at = new AnimationTask (component);
  48452. tasks.add (at);
  48453. sendChangeMessage (this);
  48454. }
  48455. at->msElapsed = 0;
  48456. at->lastProgress = 0;
  48457. at->msTotal = jmax (1, millisecondsToSpendMoving);
  48458. at->destination = finalPosition;
  48459. // the speeds must be 0 or greater!
  48460. jassert (startSpeed >= 0 && endSpeed >= 0)
  48461. const double invTotalDistance = 4.0 / (startSpeed + endSpeed + 2.0);
  48462. at->startSpeed = jmax (0.0, startSpeed * invTotalDistance);
  48463. at->midSpeed = invTotalDistance;
  48464. at->endSpeed = jmax (0.0, endSpeed * invTotalDistance);
  48465. at->left = component->getX();
  48466. at->top = component->getY();
  48467. at->right = component->getRight();
  48468. at->bottom = component->getBottom();
  48469. if (! isTimerRunning())
  48470. {
  48471. lastTime = Time::getMillisecondCounter();
  48472. startTimer (1000 / 50);
  48473. }
  48474. }
  48475. }
  48476. void ComponentAnimator::cancelAllAnimations (const bool moveComponentsToTheirFinalPositions)
  48477. {
  48478. for (int i = tasks.size(); --i >= 0;)
  48479. {
  48480. AnimationTask* const at = tasks.getUnchecked(i);
  48481. if (moveComponentsToTheirFinalPositions)
  48482. at->moveToFinalDestination();
  48483. delete at;
  48484. tasks.remove (i);
  48485. sendChangeMessage (this);
  48486. }
  48487. }
  48488. void ComponentAnimator::cancelAnimation (Component* const component,
  48489. const bool moveComponentToItsFinalPosition)
  48490. {
  48491. AnimationTask* const at = findTaskFor (component);
  48492. if (at != 0)
  48493. {
  48494. if (moveComponentToItsFinalPosition)
  48495. at->moveToFinalDestination();
  48496. tasks.removeValue (at);
  48497. delete at;
  48498. sendChangeMessage (this);
  48499. }
  48500. }
  48501. const Rectangle<int> ComponentAnimator::getComponentDestination (Component* const component)
  48502. {
  48503. AnimationTask* const at = findTaskFor (component);
  48504. if (at != 0)
  48505. return at->destination;
  48506. else if (component != 0)
  48507. return component->getBounds();
  48508. return Rectangle<int>();
  48509. }
  48510. bool ComponentAnimator::isAnimating (Component* component) const
  48511. {
  48512. return findTaskFor (component) != 0;
  48513. }
  48514. void ComponentAnimator::timerCallback()
  48515. {
  48516. const uint32 timeNow = Time::getMillisecondCounter();
  48517. if (lastTime == 0 || lastTime == timeNow)
  48518. lastTime = timeNow;
  48519. const int elapsed = timeNow - lastTime;
  48520. for (int i = tasks.size(); --i >= 0;)
  48521. {
  48522. AnimationTask* const at = tasks.getUnchecked(i);
  48523. if (! at->useTimeslice (elapsed))
  48524. {
  48525. tasks.remove (i);
  48526. delete at;
  48527. sendChangeMessage (this);
  48528. }
  48529. }
  48530. lastTime = timeNow;
  48531. if (tasks.size() == 0)
  48532. stopTimer();
  48533. }
  48534. END_JUCE_NAMESPACE
  48535. /*** End of inlined file: juce_ComponentAnimator.cpp ***/
  48536. /*** Start of inlined file: juce_ComponentBoundsConstrainer.cpp ***/
  48537. BEGIN_JUCE_NAMESPACE
  48538. ComponentBoundsConstrainer::ComponentBoundsConstrainer() throw()
  48539. : minW (0),
  48540. maxW (0x3fffffff),
  48541. minH (0),
  48542. maxH (0x3fffffff),
  48543. minOffTop (0),
  48544. minOffLeft (0),
  48545. minOffBottom (0),
  48546. minOffRight (0),
  48547. aspectRatio (0.0)
  48548. {
  48549. }
  48550. ComponentBoundsConstrainer::~ComponentBoundsConstrainer()
  48551. {
  48552. }
  48553. void ComponentBoundsConstrainer::setMinimumWidth (const int minimumWidth) throw()
  48554. {
  48555. minW = minimumWidth;
  48556. }
  48557. void ComponentBoundsConstrainer::setMaximumWidth (const int maximumWidth) throw()
  48558. {
  48559. maxW = maximumWidth;
  48560. }
  48561. void ComponentBoundsConstrainer::setMinimumHeight (const int minimumHeight) throw()
  48562. {
  48563. minH = minimumHeight;
  48564. }
  48565. void ComponentBoundsConstrainer::setMaximumHeight (const int maximumHeight) throw()
  48566. {
  48567. maxH = maximumHeight;
  48568. }
  48569. void ComponentBoundsConstrainer::setMinimumSize (const int minimumWidth, const int minimumHeight) throw()
  48570. {
  48571. jassert (maxW >= minimumWidth);
  48572. jassert (maxH >= minimumHeight);
  48573. jassert (minimumWidth > 0 && minimumHeight > 0);
  48574. minW = minimumWidth;
  48575. minH = minimumHeight;
  48576. if (minW > maxW)
  48577. maxW = minW;
  48578. if (minH > maxH)
  48579. maxH = minH;
  48580. }
  48581. void ComponentBoundsConstrainer::setMaximumSize (const int maximumWidth, const int maximumHeight) throw()
  48582. {
  48583. jassert (maximumWidth >= minW);
  48584. jassert (maximumHeight >= minH);
  48585. jassert (maximumWidth > 0 && maximumHeight > 0);
  48586. maxW = jmax (minW, maximumWidth);
  48587. maxH = jmax (minH, maximumHeight);
  48588. }
  48589. void ComponentBoundsConstrainer::setSizeLimits (const int minimumWidth,
  48590. const int minimumHeight,
  48591. const int maximumWidth,
  48592. const int maximumHeight) throw()
  48593. {
  48594. jassert (maximumWidth >= minimumWidth);
  48595. jassert (maximumHeight >= minimumHeight);
  48596. jassert (maximumWidth > 0 && maximumHeight > 0);
  48597. jassert (minimumWidth > 0 && minimumHeight > 0);
  48598. minW = jmax (0, minimumWidth);
  48599. minH = jmax (0, minimumHeight);
  48600. maxW = jmax (minW, maximumWidth);
  48601. maxH = jmax (minH, maximumHeight);
  48602. }
  48603. void ComponentBoundsConstrainer::setMinimumOnscreenAmounts (const int minimumWhenOffTheTop,
  48604. const int minimumWhenOffTheLeft,
  48605. const int minimumWhenOffTheBottom,
  48606. const int minimumWhenOffTheRight) throw()
  48607. {
  48608. minOffTop = minimumWhenOffTheTop;
  48609. minOffLeft = minimumWhenOffTheLeft;
  48610. minOffBottom = minimumWhenOffTheBottom;
  48611. minOffRight = minimumWhenOffTheRight;
  48612. }
  48613. void ComponentBoundsConstrainer::setFixedAspectRatio (const double widthOverHeight) throw()
  48614. {
  48615. aspectRatio = jmax (0.0, widthOverHeight);
  48616. }
  48617. double ComponentBoundsConstrainer::getFixedAspectRatio() const throw()
  48618. {
  48619. return aspectRatio;
  48620. }
  48621. void ComponentBoundsConstrainer::setBoundsForComponent (Component* const component,
  48622. const Rectangle<int>& targetBounds,
  48623. const bool isStretchingTop,
  48624. const bool isStretchingLeft,
  48625. const bool isStretchingBottom,
  48626. const bool isStretchingRight)
  48627. {
  48628. jassert (component != 0);
  48629. Rectangle<int> limits, bounds (targetBounds);
  48630. BorderSize border;
  48631. Component* const parent = component->getParentComponent();
  48632. if (parent == 0)
  48633. {
  48634. ComponentPeer* peer = component->getPeer();
  48635. if (peer != 0)
  48636. border = peer->getFrameSize();
  48637. limits = Desktop::getInstance().getMonitorAreaContaining (bounds.getCentre());
  48638. }
  48639. else
  48640. {
  48641. limits.setSize (parent->getWidth(), parent->getHeight());
  48642. }
  48643. border.addTo (bounds);
  48644. checkBounds (bounds,
  48645. border.addedTo (component->getBounds()), limits,
  48646. isStretchingTop, isStretchingLeft,
  48647. isStretchingBottom, isStretchingRight);
  48648. border.subtractFrom (bounds);
  48649. applyBoundsToComponent (component, bounds);
  48650. }
  48651. void ComponentBoundsConstrainer::checkComponentBounds (Component* component)
  48652. {
  48653. setBoundsForComponent (component, component->getBounds(),
  48654. false, false, false, false);
  48655. }
  48656. void ComponentBoundsConstrainer::applyBoundsToComponent (Component* component,
  48657. const Rectangle<int>& bounds)
  48658. {
  48659. component->setBounds (bounds);
  48660. }
  48661. void ComponentBoundsConstrainer::resizeStart()
  48662. {
  48663. }
  48664. void ComponentBoundsConstrainer::resizeEnd()
  48665. {
  48666. }
  48667. void ComponentBoundsConstrainer::checkBounds (Rectangle<int>& bounds,
  48668. const Rectangle<int>& old,
  48669. const Rectangle<int>& limits,
  48670. const bool isStretchingTop,
  48671. const bool isStretchingLeft,
  48672. const bool isStretchingBottom,
  48673. const bool isStretchingRight)
  48674. {
  48675. int x = bounds.getX();
  48676. int y = bounds.getY();
  48677. int w = bounds.getWidth();
  48678. int h = bounds.getHeight();
  48679. // constrain the size if it's being stretched..
  48680. if (isStretchingLeft)
  48681. {
  48682. x = jlimit (old.getRight() - maxW, old.getRight() - minW, x);
  48683. w = old.getRight() - x;
  48684. }
  48685. if (isStretchingRight)
  48686. {
  48687. w = jlimit (minW, maxW, w);
  48688. }
  48689. if (isStretchingTop)
  48690. {
  48691. y = jlimit (old.getBottom() - maxH, old.getBottom() - minH, y);
  48692. h = old.getBottom() - y;
  48693. }
  48694. if (isStretchingBottom)
  48695. {
  48696. h = jlimit (minH, maxH, h);
  48697. }
  48698. // constrain the aspect ratio if one has been specified..
  48699. if (aspectRatio > 0.0 && w > 0 && h > 0)
  48700. {
  48701. bool adjustWidth;
  48702. if ((isStretchingTop || isStretchingBottom) && ! (isStretchingLeft || isStretchingRight))
  48703. {
  48704. adjustWidth = true;
  48705. }
  48706. else if ((isStretchingLeft || isStretchingRight) && ! (isStretchingTop || isStretchingBottom))
  48707. {
  48708. adjustWidth = false;
  48709. }
  48710. else
  48711. {
  48712. const double oldRatio = (old.getHeight() > 0) ? fabs (old.getWidth() / (double) old.getHeight()) : 0.0;
  48713. const double newRatio = fabs (w / (double) h);
  48714. adjustWidth = (oldRatio > newRatio);
  48715. }
  48716. if (adjustWidth)
  48717. {
  48718. w = roundToInt (h * aspectRatio);
  48719. if (w > maxW || w < minW)
  48720. {
  48721. w = jlimit (minW, maxW, w);
  48722. h = roundToInt (w / aspectRatio);
  48723. }
  48724. }
  48725. else
  48726. {
  48727. h = roundToInt (w / aspectRatio);
  48728. if (h > maxH || h < minH)
  48729. {
  48730. h = jlimit (minH, maxH, h);
  48731. w = roundToInt (h * aspectRatio);
  48732. }
  48733. }
  48734. if ((isStretchingTop || isStretchingBottom) && ! (isStretchingLeft || isStretchingRight))
  48735. {
  48736. x = old.getX() + (old.getWidth() - w) / 2;
  48737. }
  48738. else if ((isStretchingLeft || isStretchingRight) && ! (isStretchingTop || isStretchingBottom))
  48739. {
  48740. y = old.getY() + (old.getHeight() - h) / 2;
  48741. }
  48742. else
  48743. {
  48744. if (isStretchingLeft)
  48745. x = old.getRight() - w;
  48746. if (isStretchingTop)
  48747. y = old.getBottom() - h;
  48748. }
  48749. }
  48750. // ...and constrain the position if limits have been set for that.
  48751. if (minOffTop > 0 || minOffLeft > 0 || minOffBottom > 0 || minOffRight > 0)
  48752. {
  48753. if (minOffTop > 0)
  48754. {
  48755. const int limit = limits.getY() + jmin (minOffTop - h, 0);
  48756. if (y < limit)
  48757. {
  48758. if (isStretchingTop)
  48759. h -= (limit - y);
  48760. y = limit;
  48761. }
  48762. }
  48763. if (minOffLeft > 0)
  48764. {
  48765. const int limit = limits.getX() + jmin (minOffLeft - w, 0);
  48766. if (x < limit)
  48767. {
  48768. if (isStretchingLeft)
  48769. w -= (limit - x);
  48770. x = limit;
  48771. }
  48772. }
  48773. if (minOffBottom > 0)
  48774. {
  48775. const int limit = limits.getBottom() - jmin (minOffBottom, h);
  48776. if (y > limit)
  48777. {
  48778. if (isStretchingBottom)
  48779. h += (limit - y);
  48780. else
  48781. y = limit;
  48782. }
  48783. }
  48784. if (minOffRight > 0)
  48785. {
  48786. const int limit = limits.getRight() - jmin (minOffRight, w);
  48787. if (x > limit)
  48788. {
  48789. if (isStretchingRight)
  48790. w += (limit - x);
  48791. else
  48792. x = limit;
  48793. }
  48794. }
  48795. }
  48796. jassert (w >= 0 && h >= 0);
  48797. bounds = Rectangle<int> (x, y, w, h);
  48798. }
  48799. END_JUCE_NAMESPACE
  48800. /*** End of inlined file: juce_ComponentBoundsConstrainer.cpp ***/
  48801. /*** Start of inlined file: juce_ComponentMovementWatcher.cpp ***/
  48802. BEGIN_JUCE_NAMESPACE
  48803. ComponentMovementWatcher::ComponentMovementWatcher (Component* const component_)
  48804. : component (component_),
  48805. lastPeer (0),
  48806. reentrant (false)
  48807. {
  48808. jassert (component != 0); // can't use this with a null pointer..
  48809. component->addComponentListener (this);
  48810. registerWithParentComps();
  48811. }
  48812. ComponentMovementWatcher::~ComponentMovementWatcher()
  48813. {
  48814. component->removeComponentListener (this);
  48815. unregister();
  48816. }
  48817. void ComponentMovementWatcher::componentParentHierarchyChanged (Component&)
  48818. {
  48819. // agh! don't delete the target component without deleting this object first!
  48820. jassert (component != 0);
  48821. if (! reentrant)
  48822. {
  48823. reentrant = true;
  48824. ComponentPeer* const peer = component->getPeer();
  48825. if (peer != lastPeer)
  48826. {
  48827. componentPeerChanged();
  48828. if (component == 0)
  48829. return;
  48830. lastPeer = peer;
  48831. }
  48832. unregister();
  48833. registerWithParentComps();
  48834. reentrant = false;
  48835. componentMovedOrResized (*component, true, true);
  48836. }
  48837. }
  48838. void ComponentMovementWatcher::componentMovedOrResized (Component&, bool wasMoved, bool wasResized)
  48839. {
  48840. // agh! don't delete the target component without deleting this object first!
  48841. jassert (component != 0);
  48842. if (wasMoved)
  48843. {
  48844. const Point<int> pos (component->relativePositionToOtherComponent (component->getTopLevelComponent(), Point<int>()));
  48845. wasMoved = lastBounds.getPosition() != pos;
  48846. lastBounds.setPosition (pos);
  48847. }
  48848. wasResized = (lastBounds.getWidth() != component->getWidth() || lastBounds.getHeight() != component->getHeight());
  48849. lastBounds.setSize (component->getWidth(), component->getHeight());
  48850. if (wasMoved || wasResized)
  48851. componentMovedOrResized (wasMoved, wasResized);
  48852. }
  48853. void ComponentMovementWatcher::registerWithParentComps() throw()
  48854. {
  48855. Component* p = component->getParentComponent();
  48856. while (p != 0)
  48857. {
  48858. p->addComponentListener (this);
  48859. registeredParentComps.add (p);
  48860. p = p->getParentComponent();
  48861. }
  48862. }
  48863. void ComponentMovementWatcher::unregister() throw()
  48864. {
  48865. for (int i = registeredParentComps.size(); --i >= 0;)
  48866. static_cast <Component*> (registeredParentComps.getUnchecked(i))->removeComponentListener (this);
  48867. registeredParentComps.clear();
  48868. }
  48869. END_JUCE_NAMESPACE
  48870. /*** End of inlined file: juce_ComponentMovementWatcher.cpp ***/
  48871. /*** Start of inlined file: juce_GroupComponent.cpp ***/
  48872. BEGIN_JUCE_NAMESPACE
  48873. GroupComponent::GroupComponent (const String& componentName,
  48874. const String& labelText)
  48875. : Component (componentName),
  48876. text (labelText),
  48877. justification (Justification::left)
  48878. {
  48879. setInterceptsMouseClicks (false, true);
  48880. }
  48881. GroupComponent::~GroupComponent()
  48882. {
  48883. }
  48884. void GroupComponent::setText (const String& newText)
  48885. {
  48886. if (text != newText)
  48887. {
  48888. text = newText;
  48889. repaint();
  48890. }
  48891. }
  48892. const String GroupComponent::getText() const
  48893. {
  48894. return text;
  48895. }
  48896. void GroupComponent::setTextLabelPosition (const Justification& newJustification)
  48897. {
  48898. if (justification.getFlags() != newJustification.getFlags())
  48899. {
  48900. justification = newJustification;
  48901. repaint();
  48902. }
  48903. }
  48904. void GroupComponent::paint (Graphics& g)
  48905. {
  48906. getLookAndFeel()
  48907. .drawGroupComponentOutline (g, getWidth(), getHeight(),
  48908. text, justification,
  48909. *this);
  48910. }
  48911. void GroupComponent::enablementChanged()
  48912. {
  48913. repaint();
  48914. }
  48915. void GroupComponent::colourChanged()
  48916. {
  48917. repaint();
  48918. }
  48919. END_JUCE_NAMESPACE
  48920. /*** End of inlined file: juce_GroupComponent.cpp ***/
  48921. /*** Start of inlined file: juce_MultiDocumentPanel.cpp ***/
  48922. BEGIN_JUCE_NAMESPACE
  48923. MultiDocumentPanelWindow::MultiDocumentPanelWindow (const Colour& backgroundColour)
  48924. : DocumentWindow (String::empty, backgroundColour,
  48925. DocumentWindow::maximiseButton | DocumentWindow::closeButton, false)
  48926. {
  48927. }
  48928. MultiDocumentPanelWindow::~MultiDocumentPanelWindow()
  48929. {
  48930. }
  48931. void MultiDocumentPanelWindow::maximiseButtonPressed()
  48932. {
  48933. MultiDocumentPanel* const owner = getOwner();
  48934. jassert (owner != 0); // these windows are only designed to be used inside a MultiDocumentPanel!
  48935. if (owner != 0)
  48936. owner->setLayoutMode (MultiDocumentPanel::MaximisedWindowsWithTabs);
  48937. }
  48938. void MultiDocumentPanelWindow::closeButtonPressed()
  48939. {
  48940. MultiDocumentPanel* const owner = getOwner();
  48941. jassert (owner != 0); // these windows are only designed to be used inside a MultiDocumentPanel!
  48942. if (owner != 0)
  48943. owner->closeDocument (getContentComponent(), true);
  48944. }
  48945. void MultiDocumentPanelWindow::activeWindowStatusChanged()
  48946. {
  48947. DocumentWindow::activeWindowStatusChanged();
  48948. updateOrder();
  48949. }
  48950. void MultiDocumentPanelWindow::broughtToFront()
  48951. {
  48952. DocumentWindow::broughtToFront();
  48953. updateOrder();
  48954. }
  48955. void MultiDocumentPanelWindow::updateOrder()
  48956. {
  48957. MultiDocumentPanel* const owner = getOwner();
  48958. if (owner != 0)
  48959. owner->updateOrder();
  48960. }
  48961. MultiDocumentPanel* MultiDocumentPanelWindow::getOwner() const throw()
  48962. {
  48963. // (unable to use the syntax findParentComponentOfClass <MultiDocumentPanel> () because of a VC6 compiler bug)
  48964. return findParentComponentOfClass ((MultiDocumentPanel*) 0);
  48965. }
  48966. class MDITabbedComponentInternal : public TabbedComponent
  48967. {
  48968. public:
  48969. MDITabbedComponentInternal()
  48970. : TabbedComponent (TabbedButtonBar::TabsAtTop)
  48971. {
  48972. }
  48973. ~MDITabbedComponentInternal()
  48974. {
  48975. }
  48976. void currentTabChanged (int, const String&)
  48977. {
  48978. // (unable to use the syntax findParentComponentOfClass <MultiDocumentPanel> () because of a VC6 compiler bug)
  48979. MultiDocumentPanel* const owner = findParentComponentOfClass ((MultiDocumentPanel*) 0);
  48980. if (owner != 0)
  48981. owner->updateOrder();
  48982. }
  48983. };
  48984. MultiDocumentPanel::MultiDocumentPanel()
  48985. : mode (MaximisedWindowsWithTabs),
  48986. tabComponent (0),
  48987. backgroundColour (Colours::lightblue),
  48988. maximumNumDocuments (0),
  48989. numDocsBeforeTabsUsed (0)
  48990. {
  48991. setOpaque (true);
  48992. }
  48993. MultiDocumentPanel::~MultiDocumentPanel()
  48994. {
  48995. closeAllDocuments (false);
  48996. }
  48997. static bool shouldDeleteComp (Component* const c)
  48998. {
  48999. return c->getProperties() ["mdiDocumentDelete_"];
  49000. }
  49001. bool MultiDocumentPanel::closeAllDocuments (const bool checkItsOkToCloseFirst)
  49002. {
  49003. while (components.size() > 0)
  49004. if (! closeDocument (components.getLast(), checkItsOkToCloseFirst))
  49005. return false;
  49006. return true;
  49007. }
  49008. MultiDocumentPanelWindow* MultiDocumentPanel::createNewDocumentWindow()
  49009. {
  49010. return new MultiDocumentPanelWindow (backgroundColour);
  49011. }
  49012. void MultiDocumentPanel::addWindow (Component* component)
  49013. {
  49014. MultiDocumentPanelWindow* const dw = createNewDocumentWindow();
  49015. dw->setResizable (true, false);
  49016. dw->setContentComponent (component, false, true);
  49017. dw->setName (component->getName());
  49018. const var bkg (component->getProperties() ["mdiDocumentBkg_"]);
  49019. dw->setBackgroundColour (bkg.isVoid() ? backgroundColour : Colour ((int) bkg));
  49020. int x = 4;
  49021. Component* const topComp = getChildComponent (getNumChildComponents() - 1);
  49022. if (topComp != 0 && topComp->getX() == x && topComp->getY() == x)
  49023. x += 16;
  49024. dw->setTopLeftPosition (x, x);
  49025. const var pos (component->getProperties() ["mdiDocumentPos_"]);
  49026. if (pos.toString().isNotEmpty())
  49027. dw->restoreWindowStateFromString (pos.toString());
  49028. addAndMakeVisible (dw);
  49029. dw->toFront (true);
  49030. }
  49031. bool MultiDocumentPanel::addDocument (Component* const component,
  49032. const Colour& docColour,
  49033. const bool deleteWhenRemoved)
  49034. {
  49035. // If you try passing a full DocumentWindow or ResizableWindow in here, you'll end up
  49036. // with a frame-within-a-frame! Just pass in the bare content component.
  49037. jassert (dynamic_cast <ResizableWindow*> (component) == 0);
  49038. if (component == 0 || (maximumNumDocuments > 0 && components.size() >= maximumNumDocuments))
  49039. return false;
  49040. components.add (component);
  49041. component->getProperties().set ("mdiDocumentDelete_", deleteWhenRemoved);
  49042. component->getProperties().set ("mdiDocumentBkg_", (int) docColour.getARGB());
  49043. component->addComponentListener (this);
  49044. if (mode == FloatingWindows)
  49045. {
  49046. if (isFullscreenWhenOneDocument())
  49047. {
  49048. if (components.size() == 1)
  49049. {
  49050. addAndMakeVisible (component);
  49051. }
  49052. else
  49053. {
  49054. if (components.size() == 2)
  49055. addWindow (components.getFirst());
  49056. addWindow (component);
  49057. }
  49058. }
  49059. else
  49060. {
  49061. addWindow (component);
  49062. }
  49063. }
  49064. else
  49065. {
  49066. if (tabComponent == 0 && components.size() > numDocsBeforeTabsUsed)
  49067. {
  49068. addAndMakeVisible (tabComponent = new MDITabbedComponentInternal());
  49069. Array <Component*> temp (components);
  49070. for (int i = 0; i < temp.size(); ++i)
  49071. tabComponent->addTab (temp[i]->getName(), docColour, temp[i], false);
  49072. resized();
  49073. }
  49074. else
  49075. {
  49076. if (tabComponent != 0)
  49077. tabComponent->addTab (component->getName(), docColour, component, false);
  49078. else
  49079. addAndMakeVisible (component);
  49080. }
  49081. setActiveDocument (component);
  49082. }
  49083. resized();
  49084. activeDocumentChanged();
  49085. return true;
  49086. }
  49087. bool MultiDocumentPanel::closeDocument (Component* component,
  49088. const bool checkItsOkToCloseFirst)
  49089. {
  49090. if (components.contains (component))
  49091. {
  49092. if (checkItsOkToCloseFirst && ! tryToCloseDocument (component))
  49093. return false;
  49094. component->removeComponentListener (this);
  49095. const bool shouldDelete = shouldDeleteComp (component);
  49096. component->getProperties().remove ("mdiDocumentDelete_");
  49097. component->getProperties().remove ("mdiDocumentBkg_");
  49098. if (mode == FloatingWindows)
  49099. {
  49100. for (int i = getNumChildComponents(); --i >= 0;)
  49101. {
  49102. MultiDocumentPanelWindow* const dw = dynamic_cast <MultiDocumentPanelWindow*> (getChildComponent (i));
  49103. if (dw != 0 && dw->getContentComponent() == component)
  49104. {
  49105. dw->setContentComponent (0, false);
  49106. delete dw;
  49107. break;
  49108. }
  49109. }
  49110. if (shouldDelete)
  49111. delete component;
  49112. components.removeValue (component);
  49113. if (isFullscreenWhenOneDocument() && components.size() == 1)
  49114. {
  49115. for (int i = getNumChildComponents(); --i >= 0;)
  49116. {
  49117. MultiDocumentPanelWindow* const dw = dynamic_cast <MultiDocumentPanelWindow*> (getChildComponent (i));
  49118. if (dw != 0)
  49119. {
  49120. dw->setContentComponent (0, false);
  49121. delete dw;
  49122. }
  49123. }
  49124. addAndMakeVisible (components.getFirst());
  49125. }
  49126. }
  49127. else
  49128. {
  49129. jassert (components.indexOf (component) >= 0);
  49130. if (tabComponent != 0)
  49131. {
  49132. for (int i = tabComponent->getNumTabs(); --i >= 0;)
  49133. if (tabComponent->getTabContentComponent (i) == component)
  49134. tabComponent->removeTab (i);
  49135. }
  49136. else
  49137. {
  49138. removeChildComponent (component);
  49139. }
  49140. if (shouldDelete)
  49141. delete component;
  49142. if (tabComponent != 0 && tabComponent->getNumTabs() <= numDocsBeforeTabsUsed)
  49143. deleteAndZero (tabComponent);
  49144. components.removeValue (component);
  49145. if (components.size() > 0 && tabComponent == 0)
  49146. addAndMakeVisible (components.getFirst());
  49147. }
  49148. resized();
  49149. activeDocumentChanged();
  49150. }
  49151. else
  49152. {
  49153. jassertfalse
  49154. }
  49155. return true;
  49156. }
  49157. int MultiDocumentPanel::getNumDocuments() const throw()
  49158. {
  49159. return components.size();
  49160. }
  49161. Component* MultiDocumentPanel::getDocument (const int index) const throw()
  49162. {
  49163. return components [index];
  49164. }
  49165. Component* MultiDocumentPanel::getActiveDocument() const throw()
  49166. {
  49167. if (mode == FloatingWindows)
  49168. {
  49169. for (int i = getNumChildComponents(); --i >= 0;)
  49170. {
  49171. MultiDocumentPanelWindow* const dw = dynamic_cast <MultiDocumentPanelWindow*> (getChildComponent (i));
  49172. if (dw != 0 && dw->isActiveWindow())
  49173. return dw->getContentComponent();
  49174. }
  49175. }
  49176. return components.getLast();
  49177. }
  49178. void MultiDocumentPanel::setActiveDocument (Component* component)
  49179. {
  49180. if (mode == FloatingWindows)
  49181. {
  49182. component = getContainerComp (component);
  49183. if (component != 0)
  49184. component->toFront (true);
  49185. }
  49186. else if (tabComponent != 0)
  49187. {
  49188. jassert (components.indexOf (component) >= 0);
  49189. for (int i = tabComponent->getNumTabs(); --i >= 0;)
  49190. {
  49191. if (tabComponent->getTabContentComponent (i) == component)
  49192. {
  49193. tabComponent->setCurrentTabIndex (i);
  49194. break;
  49195. }
  49196. }
  49197. }
  49198. else
  49199. {
  49200. component->grabKeyboardFocus();
  49201. }
  49202. }
  49203. void MultiDocumentPanel::activeDocumentChanged()
  49204. {
  49205. }
  49206. void MultiDocumentPanel::setMaximumNumDocuments (const int newNumber)
  49207. {
  49208. maximumNumDocuments = newNumber;
  49209. }
  49210. void MultiDocumentPanel::useFullscreenWhenOneDocument (const bool shouldUseTabs)
  49211. {
  49212. numDocsBeforeTabsUsed = shouldUseTabs ? 1 : 0;
  49213. }
  49214. bool MultiDocumentPanel::isFullscreenWhenOneDocument() const throw()
  49215. {
  49216. return numDocsBeforeTabsUsed != 0;
  49217. }
  49218. void MultiDocumentPanel::setLayoutMode (const LayoutMode newLayoutMode)
  49219. {
  49220. if (mode != newLayoutMode)
  49221. {
  49222. mode = newLayoutMode;
  49223. if (mode == FloatingWindows)
  49224. {
  49225. deleteAndZero (tabComponent);
  49226. }
  49227. else
  49228. {
  49229. for (int i = getNumChildComponents(); --i >= 0;)
  49230. {
  49231. MultiDocumentPanelWindow* const dw = dynamic_cast <MultiDocumentPanelWindow*> (getChildComponent (i));
  49232. if (dw != 0)
  49233. {
  49234. dw->getContentComponent()->getProperties().set ("mdiDocumentPos_", dw->getWindowStateAsString());
  49235. dw->setContentComponent (0, false);
  49236. delete dw;
  49237. }
  49238. }
  49239. }
  49240. resized();
  49241. const Array <Component*> tempComps (components);
  49242. components.clear();
  49243. for (int i = 0; i < tempComps.size(); ++i)
  49244. {
  49245. Component* const c = tempComps.getUnchecked(i);
  49246. addDocument (c,
  49247. Colour ((int) c->getProperties().getWithDefault ("mdiDocumentBkg_", (int) Colours::white.getARGB())),
  49248. shouldDeleteComp (c));
  49249. }
  49250. }
  49251. }
  49252. void MultiDocumentPanel::setBackgroundColour (const Colour& newBackgroundColour)
  49253. {
  49254. if (backgroundColour != newBackgroundColour)
  49255. {
  49256. backgroundColour = newBackgroundColour;
  49257. setOpaque (newBackgroundColour.isOpaque());
  49258. repaint();
  49259. }
  49260. }
  49261. void MultiDocumentPanel::paint (Graphics& g)
  49262. {
  49263. g.fillAll (backgroundColour);
  49264. }
  49265. void MultiDocumentPanel::resized()
  49266. {
  49267. if (mode == MaximisedWindowsWithTabs || components.size() == numDocsBeforeTabsUsed)
  49268. {
  49269. for (int i = getNumChildComponents(); --i >= 0;)
  49270. getChildComponent (i)->setBounds (0, 0, getWidth(), getHeight());
  49271. }
  49272. setWantsKeyboardFocus (components.size() == 0);
  49273. }
  49274. Component* MultiDocumentPanel::getContainerComp (Component* c) const
  49275. {
  49276. if (mode == FloatingWindows)
  49277. {
  49278. for (int i = 0; i < getNumChildComponents(); ++i)
  49279. {
  49280. MultiDocumentPanelWindow* const dw = dynamic_cast <MultiDocumentPanelWindow*> (getChildComponent (i));
  49281. if (dw != 0 && dw->getContentComponent() == c)
  49282. {
  49283. c = dw;
  49284. break;
  49285. }
  49286. }
  49287. }
  49288. return c;
  49289. }
  49290. void MultiDocumentPanel::componentNameChanged (Component&)
  49291. {
  49292. if (mode == FloatingWindows)
  49293. {
  49294. for (int i = 0; i < getNumChildComponents(); ++i)
  49295. {
  49296. MultiDocumentPanelWindow* const dw = dynamic_cast <MultiDocumentPanelWindow*> (getChildComponent (i));
  49297. if (dw != 0)
  49298. dw->setName (dw->getContentComponent()->getName());
  49299. }
  49300. }
  49301. else if (tabComponent != 0)
  49302. {
  49303. for (int i = tabComponent->getNumTabs(); --i >= 0;)
  49304. tabComponent->setTabName (i, tabComponent->getTabContentComponent (i)->getName());
  49305. }
  49306. }
  49307. void MultiDocumentPanel::updateOrder()
  49308. {
  49309. const Array <Component*> oldList (components);
  49310. if (mode == FloatingWindows)
  49311. {
  49312. components.clear();
  49313. for (int i = 0; i < getNumChildComponents(); ++i)
  49314. {
  49315. MultiDocumentPanelWindow* const dw = dynamic_cast <MultiDocumentPanelWindow*> (getChildComponent (i));
  49316. if (dw != 0)
  49317. components.add (dw->getContentComponent());
  49318. }
  49319. }
  49320. else
  49321. {
  49322. if (tabComponent != 0)
  49323. {
  49324. Component* const current = tabComponent->getCurrentContentComponent();
  49325. if (current != 0)
  49326. {
  49327. components.removeValue (current);
  49328. components.add (current);
  49329. }
  49330. }
  49331. }
  49332. if (components != oldList)
  49333. activeDocumentChanged();
  49334. }
  49335. END_JUCE_NAMESPACE
  49336. /*** End of inlined file: juce_MultiDocumentPanel.cpp ***/
  49337. /*** Start of inlined file: juce_ResizableBorderComponent.cpp ***/
  49338. BEGIN_JUCE_NAMESPACE
  49339. ResizableBorderComponent::Zone::Zone (int zoneFlags) throw()
  49340. : zone (zoneFlags)
  49341. {
  49342. }
  49343. ResizableBorderComponent::Zone::Zone (const ResizableBorderComponent::Zone& other) throw() : zone (other.zone) {}
  49344. ResizableBorderComponent::Zone& ResizableBorderComponent::Zone::operator= (const ResizableBorderComponent::Zone& other) throw() { zone = other.zone; return *this; }
  49345. bool ResizableBorderComponent::Zone::operator== (const ResizableBorderComponent::Zone& other) const throw() { return zone == other.zone; }
  49346. bool ResizableBorderComponent::Zone::operator!= (const ResizableBorderComponent::Zone& other) const throw() { return zone != other.zone; }
  49347. const ResizableBorderComponent::Zone ResizableBorderComponent::Zone::fromPositionOnBorder (const Rectangle<int>& totalSize,
  49348. const BorderSize& border,
  49349. const Point<int>& position)
  49350. {
  49351. int z = 0;
  49352. if (totalSize.contains (position)
  49353. && ! border.subtractedFrom (totalSize).contains (position))
  49354. {
  49355. const int minW = jmax (totalSize.getWidth() / 10, jmin (10, totalSize.getWidth() / 3));
  49356. if (position.getX() < jmax (border.getLeft(), minW))
  49357. z |= left;
  49358. else if (position.getX() >= totalSize.getWidth() - jmax (border.getRight(), minW))
  49359. z |= right;
  49360. const int minH = jmax (totalSize.getHeight() / 10, jmin (10, totalSize.getHeight() / 3));
  49361. if (position.getY() < jmax (border.getTop(), minH))
  49362. z |= top;
  49363. else if (position.getY() >= totalSize.getHeight() - jmax (border.getBottom(), minH))
  49364. z |= bottom;
  49365. }
  49366. return Zone (z);
  49367. }
  49368. const MouseCursor ResizableBorderComponent::Zone::getMouseCursor() const throw()
  49369. {
  49370. MouseCursor::StandardCursorType mc = MouseCursor::NormalCursor;
  49371. switch (zone)
  49372. {
  49373. case (left | top): mc = MouseCursor::TopLeftCornerResizeCursor; break;
  49374. case top: mc = MouseCursor::TopEdgeResizeCursor; break;
  49375. case (right | top): mc = MouseCursor::TopRightCornerResizeCursor; break;
  49376. case left: mc = MouseCursor::LeftEdgeResizeCursor; break;
  49377. case right: mc = MouseCursor::RightEdgeResizeCursor; break;
  49378. case (left | bottom): mc = MouseCursor::BottomLeftCornerResizeCursor; break;
  49379. case bottom: mc = MouseCursor::BottomEdgeResizeCursor; break;
  49380. case (right | bottom): mc = MouseCursor::BottomRightCornerResizeCursor; break;
  49381. default: break;
  49382. }
  49383. return mc;
  49384. }
  49385. const Rectangle<int> ResizableBorderComponent::Zone::resizeRectangleBy (Rectangle<int> b, const Point<int>& offset) const throw()
  49386. {
  49387. if (isDraggingWholeObject())
  49388. return b + offset;
  49389. if (isDraggingLeftEdge())
  49390. b.setLeft (b.getX() + offset.getX());
  49391. if (isDraggingRightEdge())
  49392. b.setWidth (jmax (0, b.getWidth() + offset.getX()));
  49393. if (isDraggingTopEdge())
  49394. b.setTop (b.getY() + offset.getY());
  49395. if (isDraggingBottomEdge())
  49396. b.setHeight (jmax (0, b.getHeight() + offset.getY()));
  49397. return b;
  49398. }
  49399. const Rectangle<float> ResizableBorderComponent::Zone::resizeRectangleBy (Rectangle<float> b, const Point<float>& offset) const throw()
  49400. {
  49401. if (isDraggingWholeObject())
  49402. return b + offset;
  49403. if (isDraggingLeftEdge())
  49404. b.setLeft (b.getX() + offset.getX());
  49405. if (isDraggingRightEdge())
  49406. b.setWidth (jmax (0.0f, b.getWidth() + offset.getX()));
  49407. if (isDraggingTopEdge())
  49408. b.setTop (b.getY() + offset.getY());
  49409. if (isDraggingBottomEdge())
  49410. b.setHeight (jmax (0.0f, b.getHeight() + offset.getY()));
  49411. return b;
  49412. }
  49413. ResizableBorderComponent::ResizableBorderComponent (Component* const componentToResize,
  49414. ComponentBoundsConstrainer* const constrainer_)
  49415. : component (componentToResize),
  49416. constrainer (constrainer_),
  49417. borderSize (5),
  49418. mouseZone (0)
  49419. {
  49420. }
  49421. ResizableBorderComponent::~ResizableBorderComponent()
  49422. {
  49423. }
  49424. void ResizableBorderComponent::paint (Graphics& g)
  49425. {
  49426. getLookAndFeel().drawResizableFrame (g, getWidth(), getHeight(), borderSize);
  49427. }
  49428. void ResizableBorderComponent::mouseEnter (const MouseEvent& e)
  49429. {
  49430. updateMouseZone (e);
  49431. }
  49432. void ResizableBorderComponent::mouseMove (const MouseEvent& e)
  49433. {
  49434. updateMouseZone (e);
  49435. }
  49436. void ResizableBorderComponent::mouseDown (const MouseEvent& e)
  49437. {
  49438. if (component == 0)
  49439. {
  49440. jassertfalse // You've deleted the component that this resizer was supposed to be using!
  49441. return;
  49442. }
  49443. updateMouseZone (e);
  49444. originalBounds = component->getBounds();
  49445. if (constrainer != 0)
  49446. constrainer->resizeStart();
  49447. }
  49448. void ResizableBorderComponent::mouseDrag (const MouseEvent& e)
  49449. {
  49450. if (component == 0)
  49451. {
  49452. jassertfalse // You've deleted the component that this resizer was supposed to be using!
  49453. return;
  49454. }
  49455. const Rectangle<int> bounds (mouseZone.resizeRectangleBy (originalBounds, e.getOffsetFromDragStart()));
  49456. if (constrainer != 0)
  49457. constrainer->setBoundsForComponent (component, bounds,
  49458. mouseZone.isDraggingTopEdge(),
  49459. mouseZone.isDraggingLeftEdge(),
  49460. mouseZone.isDraggingBottomEdge(),
  49461. mouseZone.isDraggingRightEdge());
  49462. else
  49463. component->setBounds (bounds);
  49464. }
  49465. void ResizableBorderComponent::mouseUp (const MouseEvent&)
  49466. {
  49467. if (constrainer != 0)
  49468. constrainer->resizeEnd();
  49469. }
  49470. bool ResizableBorderComponent::hitTest (int x, int y)
  49471. {
  49472. return x < borderSize.getLeft()
  49473. || x >= getWidth() - borderSize.getRight()
  49474. || y < borderSize.getTop()
  49475. || y >= getHeight() - borderSize.getBottom();
  49476. }
  49477. void ResizableBorderComponent::setBorderThickness (const BorderSize& newBorderSize)
  49478. {
  49479. if (borderSize != newBorderSize)
  49480. {
  49481. borderSize = newBorderSize;
  49482. repaint();
  49483. }
  49484. }
  49485. const BorderSize ResizableBorderComponent::getBorderThickness() const
  49486. {
  49487. return borderSize;
  49488. }
  49489. void ResizableBorderComponent::updateMouseZone (const MouseEvent& e)
  49490. {
  49491. Zone newZone (Zone::fromPositionOnBorder (getLocalBounds(), borderSize, e.getPosition()));
  49492. if (mouseZone != newZone)
  49493. {
  49494. mouseZone = newZone;
  49495. setMouseCursor (newZone.getMouseCursor());
  49496. }
  49497. }
  49498. END_JUCE_NAMESPACE
  49499. /*** End of inlined file: juce_ResizableBorderComponent.cpp ***/
  49500. /*** Start of inlined file: juce_ResizableCornerComponent.cpp ***/
  49501. BEGIN_JUCE_NAMESPACE
  49502. ResizableCornerComponent::ResizableCornerComponent (Component* const componentToResize,
  49503. ComponentBoundsConstrainer* const constrainer_)
  49504. : component (componentToResize),
  49505. constrainer (constrainer_)
  49506. {
  49507. setRepaintsOnMouseActivity (true);
  49508. setMouseCursor (MouseCursor::BottomRightCornerResizeCursor);
  49509. }
  49510. ResizableCornerComponent::~ResizableCornerComponent()
  49511. {
  49512. }
  49513. void ResizableCornerComponent::paint (Graphics& g)
  49514. {
  49515. getLookAndFeel()
  49516. .drawCornerResizer (g, getWidth(), getHeight(),
  49517. isMouseOverOrDragging(),
  49518. isMouseButtonDown());
  49519. }
  49520. void ResizableCornerComponent::mouseDown (const MouseEvent&)
  49521. {
  49522. if (component == 0)
  49523. {
  49524. jassertfalse; // You've deleted the component that this resizer is supposed to be controlling!
  49525. return;
  49526. }
  49527. originalBounds = component->getBounds();
  49528. if (constrainer != 0)
  49529. constrainer->resizeStart();
  49530. }
  49531. void ResizableCornerComponent::mouseDrag (const MouseEvent& e)
  49532. {
  49533. if (component == 0)
  49534. {
  49535. jassertfalse; // You've deleted the component that this resizer is supposed to be controlling!
  49536. return;
  49537. }
  49538. Rectangle<int> r (originalBounds.withSize (originalBounds.getWidth() + e.getDistanceFromDragStartX(),
  49539. originalBounds.getHeight() + e.getDistanceFromDragStartY()));
  49540. if (constrainer != 0)
  49541. constrainer->setBoundsForComponent (component, r, false, false, true, true);
  49542. else
  49543. component->setBounds (r);
  49544. }
  49545. void ResizableCornerComponent::mouseUp (const MouseEvent&)
  49546. {
  49547. if (constrainer != 0)
  49548. constrainer->resizeStart();
  49549. }
  49550. bool ResizableCornerComponent::hitTest (int x, int y)
  49551. {
  49552. if (getWidth() <= 0)
  49553. return false;
  49554. const int yAtX = getHeight() - (getHeight() * x / getWidth());
  49555. return y >= yAtX - getHeight() / 4;
  49556. }
  49557. END_JUCE_NAMESPACE
  49558. /*** End of inlined file: juce_ResizableCornerComponent.cpp ***/
  49559. /*** Start of inlined file: juce_ScrollBar.cpp ***/
  49560. BEGIN_JUCE_NAMESPACE
  49561. class ScrollBar::ScrollbarButton : public Button
  49562. {
  49563. public:
  49564. int direction;
  49565. ScrollbarButton (const int direction_, ScrollBar& owner_)
  49566. : Button (String::empty),
  49567. direction (direction_),
  49568. owner (owner_)
  49569. {
  49570. setWantsKeyboardFocus (false);
  49571. }
  49572. ~ScrollbarButton()
  49573. {
  49574. }
  49575. void paintButton (Graphics& g, bool isMouseOver, bool isMouseDown)
  49576. {
  49577. getLookAndFeel()
  49578. .drawScrollbarButton (g, owner,
  49579. getWidth(), getHeight(),
  49580. direction,
  49581. owner.isVertical(),
  49582. isMouseOver, isMouseDown);
  49583. }
  49584. void clicked()
  49585. {
  49586. owner.moveScrollbarInSteps ((direction == 1 || direction == 2) ? 1 : -1);
  49587. }
  49588. juce_UseDebuggingNewOperator
  49589. private:
  49590. ScrollBar& owner;
  49591. ScrollbarButton (const ScrollbarButton&);
  49592. ScrollbarButton& operator= (const ScrollbarButton&);
  49593. };
  49594. ScrollBar::ScrollBar (const bool vertical_,
  49595. const bool buttonsAreVisible)
  49596. : totalRange (0.0, 1.0),
  49597. visibleRange (0.0, 0.1),
  49598. singleStepSize (0.1),
  49599. thumbAreaStart (0),
  49600. thumbAreaSize (0),
  49601. thumbStart (0),
  49602. thumbSize (0),
  49603. initialDelayInMillisecs (100),
  49604. repeatDelayInMillisecs (50),
  49605. minimumDelayInMillisecs (10),
  49606. vertical (vertical_),
  49607. isDraggingThumb (false),
  49608. autohides (true),
  49609. upButton (0),
  49610. downButton (0)
  49611. {
  49612. setButtonVisibility (buttonsAreVisible);
  49613. setRepaintsOnMouseActivity (true);
  49614. setFocusContainer (true);
  49615. }
  49616. ScrollBar::~ScrollBar()
  49617. {
  49618. deleteAllChildren();
  49619. }
  49620. void ScrollBar::setRangeLimits (const Range<double>& newRangeLimit)
  49621. {
  49622. if (totalRange != newRangeLimit)
  49623. {
  49624. totalRange = newRangeLimit;
  49625. setCurrentRange (visibleRange);
  49626. updateThumbPosition();
  49627. }
  49628. }
  49629. void ScrollBar::setRangeLimits (const double newMinimum, const double newMaximum)
  49630. {
  49631. jassert (newMaximum >= newMinimum); // these can't be the wrong way round!
  49632. setRangeLimits (Range<double> (newMinimum, newMaximum));
  49633. }
  49634. void ScrollBar::setCurrentRange (const Range<double>& newRange)
  49635. {
  49636. const Range<double> constrainedRange (totalRange.constrainRange (newRange));
  49637. if (visibleRange != constrainedRange)
  49638. {
  49639. visibleRange = constrainedRange;
  49640. updateThumbPosition();
  49641. triggerAsyncUpdate();
  49642. }
  49643. }
  49644. void ScrollBar::setCurrentRange (const double newStart, const double newSize)
  49645. {
  49646. setCurrentRange (Range<double> (newStart, newStart + newSize));
  49647. }
  49648. void ScrollBar::setCurrentRangeStart (const double newStart)
  49649. {
  49650. setCurrentRange (visibleRange.movedToStartAt (newStart));
  49651. }
  49652. void ScrollBar::setSingleStepSize (const double newSingleStepSize)
  49653. {
  49654. singleStepSize = newSingleStepSize;
  49655. }
  49656. void ScrollBar::moveScrollbarInSteps (const int howManySteps)
  49657. {
  49658. setCurrentRange (visibleRange + howManySteps * singleStepSize);
  49659. }
  49660. void ScrollBar::moveScrollbarInPages (const int howManyPages)
  49661. {
  49662. setCurrentRange (visibleRange + howManyPages * visibleRange.getLength());
  49663. }
  49664. void ScrollBar::scrollToTop()
  49665. {
  49666. setCurrentRange (visibleRange.movedToStartAt (getMinimumRangeLimit()));
  49667. }
  49668. void ScrollBar::scrollToBottom()
  49669. {
  49670. setCurrentRange (visibleRange.movedToEndAt (getMaximumRangeLimit()));
  49671. }
  49672. void ScrollBar::setButtonRepeatSpeed (const int initialDelayInMillisecs_,
  49673. const int repeatDelayInMillisecs_,
  49674. const int minimumDelayInMillisecs_)
  49675. {
  49676. initialDelayInMillisecs = initialDelayInMillisecs_;
  49677. repeatDelayInMillisecs = repeatDelayInMillisecs_;
  49678. minimumDelayInMillisecs = minimumDelayInMillisecs_;
  49679. if (upButton != 0)
  49680. {
  49681. upButton->setRepeatSpeed (initialDelayInMillisecs, repeatDelayInMillisecs, minimumDelayInMillisecs);
  49682. downButton->setRepeatSpeed (initialDelayInMillisecs, repeatDelayInMillisecs, minimumDelayInMillisecs);
  49683. }
  49684. }
  49685. void ScrollBar::addListener (ScrollBarListener* const listener)
  49686. {
  49687. listeners.add (listener);
  49688. }
  49689. void ScrollBar::removeListener (ScrollBarListener* const listener)
  49690. {
  49691. listeners.remove (listener);
  49692. }
  49693. void ScrollBar::handleAsyncUpdate()
  49694. {
  49695. double start = visibleRange.getStart(); // (need to use a temp variable for VC7 compatibility)
  49696. listeners.call (&ScrollBarListener::scrollBarMoved, this, start);
  49697. }
  49698. void ScrollBar::updateThumbPosition()
  49699. {
  49700. int newThumbSize = roundToInt (totalRange.getLength() > 0 ? (visibleRange.getLength() * thumbAreaSize) / totalRange.getLength()
  49701. : thumbAreaSize);
  49702. if (newThumbSize < getLookAndFeel().getMinimumScrollbarThumbSize (*this))
  49703. newThumbSize = jmin (getLookAndFeel().getMinimumScrollbarThumbSize (*this), thumbAreaSize - 1);
  49704. if (newThumbSize > thumbAreaSize)
  49705. newThumbSize = thumbAreaSize;
  49706. int newThumbStart = thumbAreaStart;
  49707. if (totalRange.getLength() > visibleRange.getLength())
  49708. newThumbStart += roundToInt (((visibleRange.getStart() - totalRange.getStart()) * (thumbAreaSize - newThumbSize))
  49709. / (totalRange.getLength() - visibleRange.getLength()));
  49710. setVisible ((! autohides) || (totalRange.getLength() > visibleRange.getLength() && visibleRange.getLength() > 0.0));
  49711. if (thumbStart != newThumbStart || thumbSize != newThumbSize)
  49712. {
  49713. const int repaintStart = jmin (thumbStart, newThumbStart) - 4;
  49714. const int repaintSize = jmax (thumbStart + thumbSize, newThumbStart + newThumbSize) + 8 - repaintStart;
  49715. if (vertical)
  49716. repaint (0, repaintStart, getWidth(), repaintSize);
  49717. else
  49718. repaint (repaintStart, 0, repaintSize, getHeight());
  49719. thumbStart = newThumbStart;
  49720. thumbSize = newThumbSize;
  49721. }
  49722. }
  49723. void ScrollBar::setOrientation (const bool shouldBeVertical)
  49724. {
  49725. if (vertical != shouldBeVertical)
  49726. {
  49727. vertical = shouldBeVertical;
  49728. if (upButton != 0)
  49729. {
  49730. upButton->direction = vertical ? 0 : 3;
  49731. downButton->direction = vertical ? 2 : 1;
  49732. }
  49733. updateThumbPosition();
  49734. }
  49735. }
  49736. void ScrollBar::setButtonVisibility (const bool buttonsAreVisible)
  49737. {
  49738. delete upButton;
  49739. upButton = 0;
  49740. delete downButton;
  49741. downButton = 0;
  49742. if (buttonsAreVisible)
  49743. {
  49744. addAndMakeVisible (upButton = new ScrollbarButton (vertical ? 0 : 3, *this));
  49745. addAndMakeVisible (downButton = new ScrollbarButton (vertical ? 2 : 1, *this));
  49746. setButtonRepeatSpeed (initialDelayInMillisecs, repeatDelayInMillisecs, minimumDelayInMillisecs);
  49747. }
  49748. updateThumbPosition();
  49749. }
  49750. void ScrollBar::setAutoHide (const bool shouldHideWhenFullRange)
  49751. {
  49752. autohides = shouldHideWhenFullRange;
  49753. updateThumbPosition();
  49754. }
  49755. bool ScrollBar::autoHides() const throw()
  49756. {
  49757. return autohides;
  49758. }
  49759. void ScrollBar::paint (Graphics& g)
  49760. {
  49761. if (thumbAreaSize > 0)
  49762. {
  49763. LookAndFeel& lf = getLookAndFeel();
  49764. const int thumb = (thumbAreaSize > lf.getMinimumScrollbarThumbSize (*this))
  49765. ? thumbSize : 0;
  49766. if (vertical)
  49767. {
  49768. lf.drawScrollbar (g, *this,
  49769. 0, thumbAreaStart,
  49770. getWidth(), thumbAreaSize,
  49771. vertical,
  49772. thumbStart, thumb,
  49773. isMouseOver(), isMouseButtonDown());
  49774. }
  49775. else
  49776. {
  49777. lf.drawScrollbar (g, *this,
  49778. thumbAreaStart, 0,
  49779. thumbAreaSize, getHeight(),
  49780. vertical,
  49781. thumbStart, thumb,
  49782. isMouseOver(), isMouseButtonDown());
  49783. }
  49784. }
  49785. }
  49786. void ScrollBar::lookAndFeelChanged()
  49787. {
  49788. setComponentEffect (getLookAndFeel().getScrollbarEffect());
  49789. }
  49790. void ScrollBar::resized()
  49791. {
  49792. const int length = ((vertical) ? getHeight() : getWidth());
  49793. const int buttonSize = (upButton != 0) ? jmin (getLookAndFeel().getScrollbarButtonSize (*this), (length >> 1))
  49794. : 0;
  49795. if (length < 32 + getLookAndFeel().getMinimumScrollbarThumbSize (*this))
  49796. {
  49797. thumbAreaStart = length >> 1;
  49798. thumbAreaSize = 0;
  49799. }
  49800. else
  49801. {
  49802. thumbAreaStart = buttonSize;
  49803. thumbAreaSize = length - (buttonSize << 1);
  49804. }
  49805. if (upButton != 0)
  49806. {
  49807. if (vertical)
  49808. {
  49809. upButton->setBounds (0, 0, getWidth(), buttonSize);
  49810. downButton->setBounds (0, thumbAreaStart + thumbAreaSize, getWidth(), buttonSize);
  49811. }
  49812. else
  49813. {
  49814. upButton->setBounds (0, 0, buttonSize, getHeight());
  49815. downButton->setBounds (thumbAreaStart + thumbAreaSize, 0, buttonSize, getHeight());
  49816. }
  49817. }
  49818. updateThumbPosition();
  49819. }
  49820. void ScrollBar::mouseDown (const MouseEvent& e)
  49821. {
  49822. isDraggingThumb = false;
  49823. lastMousePos = vertical ? e.y : e.x;
  49824. dragStartMousePos = lastMousePos;
  49825. dragStartRange = visibleRange.getStart();
  49826. if (dragStartMousePos < thumbStart)
  49827. {
  49828. moveScrollbarInPages (-1);
  49829. startTimer (400);
  49830. }
  49831. else if (dragStartMousePos >= thumbStart + thumbSize)
  49832. {
  49833. moveScrollbarInPages (1);
  49834. startTimer (400);
  49835. }
  49836. else
  49837. {
  49838. isDraggingThumb = (thumbAreaSize > getLookAndFeel().getMinimumScrollbarThumbSize (*this))
  49839. && (thumbAreaSize > thumbSize);
  49840. }
  49841. }
  49842. void ScrollBar::mouseDrag (const MouseEvent& e)
  49843. {
  49844. if (isDraggingThumb)
  49845. {
  49846. const int deltaPixels = ((vertical) ? e.y : e.x) - dragStartMousePos;
  49847. setCurrentRangeStart (dragStartRange
  49848. + deltaPixels * (totalRange.getLength() - visibleRange.getLength())
  49849. / (thumbAreaSize - thumbSize));
  49850. }
  49851. else
  49852. {
  49853. lastMousePos = (vertical) ? e.y : e.x;
  49854. }
  49855. }
  49856. void ScrollBar::mouseUp (const MouseEvent&)
  49857. {
  49858. isDraggingThumb = false;
  49859. stopTimer();
  49860. repaint();
  49861. }
  49862. void ScrollBar::mouseWheelMove (const MouseEvent&,
  49863. float wheelIncrementX,
  49864. float wheelIncrementY)
  49865. {
  49866. float increment = vertical ? wheelIncrementY : wheelIncrementX;
  49867. if (increment < 0)
  49868. increment = jmin (increment * 10.0f, -1.0f);
  49869. else if (increment > 0)
  49870. increment = jmax (increment * 10.0f, 1.0f);
  49871. setCurrentRange (visibleRange - singleStepSize * increment);
  49872. }
  49873. void ScrollBar::timerCallback()
  49874. {
  49875. if (isMouseButtonDown())
  49876. {
  49877. startTimer (40);
  49878. if (lastMousePos < thumbStart)
  49879. setCurrentRange (visibleRange - visibleRange.getLength());
  49880. else if (lastMousePos > thumbStart + thumbSize)
  49881. setCurrentRangeStart (visibleRange.getEnd());
  49882. }
  49883. else
  49884. {
  49885. stopTimer();
  49886. }
  49887. }
  49888. bool ScrollBar::keyPressed (const KeyPress& key)
  49889. {
  49890. if (! isVisible())
  49891. return false;
  49892. if (key.isKeyCode (KeyPress::upKey) || key.isKeyCode (KeyPress::leftKey))
  49893. moveScrollbarInSteps (-1);
  49894. else if (key.isKeyCode (KeyPress::downKey) || key.isKeyCode (KeyPress::rightKey))
  49895. moveScrollbarInSteps (1);
  49896. else if (key.isKeyCode (KeyPress::pageUpKey))
  49897. moveScrollbarInPages (-1);
  49898. else if (key.isKeyCode (KeyPress::pageDownKey))
  49899. moveScrollbarInPages (1);
  49900. else if (key.isKeyCode (KeyPress::homeKey))
  49901. scrollToTop();
  49902. else if (key.isKeyCode (KeyPress::endKey))
  49903. scrollToBottom();
  49904. else
  49905. return false;
  49906. return true;
  49907. }
  49908. END_JUCE_NAMESPACE
  49909. /*** End of inlined file: juce_ScrollBar.cpp ***/
  49910. /*** Start of inlined file: juce_StretchableLayoutManager.cpp ***/
  49911. BEGIN_JUCE_NAMESPACE
  49912. StretchableLayoutManager::StretchableLayoutManager()
  49913. : totalSize (0)
  49914. {
  49915. }
  49916. StretchableLayoutManager::~StretchableLayoutManager()
  49917. {
  49918. }
  49919. void StretchableLayoutManager::clearAllItems()
  49920. {
  49921. items.clear();
  49922. totalSize = 0;
  49923. }
  49924. void StretchableLayoutManager::setItemLayout (const int itemIndex,
  49925. const double minimumSize,
  49926. const double maximumSize,
  49927. const double preferredSize)
  49928. {
  49929. ItemLayoutProperties* layout = getInfoFor (itemIndex);
  49930. if (layout == 0)
  49931. {
  49932. layout = new ItemLayoutProperties();
  49933. layout->itemIndex = itemIndex;
  49934. int i;
  49935. for (i = 0; i < items.size(); ++i)
  49936. if (items.getUnchecked (i)->itemIndex > itemIndex)
  49937. break;
  49938. items.insert (i, layout);
  49939. }
  49940. layout->minSize = minimumSize;
  49941. layout->maxSize = maximumSize;
  49942. layout->preferredSize = preferredSize;
  49943. layout->currentSize = 0;
  49944. }
  49945. bool StretchableLayoutManager::getItemLayout (const int itemIndex,
  49946. double& minimumSize,
  49947. double& maximumSize,
  49948. double& preferredSize) const
  49949. {
  49950. const ItemLayoutProperties* const layout = getInfoFor (itemIndex);
  49951. if (layout != 0)
  49952. {
  49953. minimumSize = layout->minSize;
  49954. maximumSize = layout->maxSize;
  49955. preferredSize = layout->preferredSize;
  49956. return true;
  49957. }
  49958. return false;
  49959. }
  49960. void StretchableLayoutManager::setTotalSize (const int newTotalSize)
  49961. {
  49962. totalSize = newTotalSize;
  49963. fitComponentsIntoSpace (0, items.size(), totalSize, 0);
  49964. }
  49965. int StretchableLayoutManager::getItemCurrentPosition (const int itemIndex) const
  49966. {
  49967. int pos = 0;
  49968. for (int i = 0; i < itemIndex; ++i)
  49969. {
  49970. const ItemLayoutProperties* const layout = getInfoFor (i);
  49971. if (layout != 0)
  49972. pos += layout->currentSize;
  49973. }
  49974. return pos;
  49975. }
  49976. int StretchableLayoutManager::getItemCurrentAbsoluteSize (const int itemIndex) const
  49977. {
  49978. const ItemLayoutProperties* const layout = getInfoFor (itemIndex);
  49979. if (layout != 0)
  49980. return layout->currentSize;
  49981. return 0;
  49982. }
  49983. double StretchableLayoutManager::getItemCurrentRelativeSize (const int itemIndex) const
  49984. {
  49985. const ItemLayoutProperties* const layout = getInfoFor (itemIndex);
  49986. if (layout != 0)
  49987. return -layout->currentSize / (double) totalSize;
  49988. return 0;
  49989. }
  49990. void StretchableLayoutManager::setItemPosition (const int itemIndex,
  49991. int newPosition)
  49992. {
  49993. for (int i = items.size(); --i >= 0;)
  49994. {
  49995. const ItemLayoutProperties* const layout = items.getUnchecked(i);
  49996. if (layout->itemIndex == itemIndex)
  49997. {
  49998. int realTotalSize = jmax (totalSize, getMinimumSizeOfItems (0, items.size()));
  49999. const int minSizeAfterThisComp = getMinimumSizeOfItems (i, items.size());
  50000. const int maxSizeAfterThisComp = getMaximumSizeOfItems (i + 1, items.size());
  50001. newPosition = jmax (newPosition, totalSize - maxSizeAfterThisComp - layout->currentSize);
  50002. newPosition = jmin (newPosition, realTotalSize - minSizeAfterThisComp);
  50003. int endPos = fitComponentsIntoSpace (0, i, newPosition, 0);
  50004. endPos += layout->currentSize;
  50005. fitComponentsIntoSpace (i + 1, items.size(), totalSize - endPos, endPos);
  50006. updatePrefSizesToMatchCurrentPositions();
  50007. break;
  50008. }
  50009. }
  50010. }
  50011. void StretchableLayoutManager::layOutComponents (Component** const components,
  50012. int numComponents,
  50013. int x, int y, int w, int h,
  50014. const bool vertically,
  50015. const bool resizeOtherDimension)
  50016. {
  50017. setTotalSize (vertically ? h : w);
  50018. int pos = vertically ? y : x;
  50019. for (int i = 0; i < numComponents; ++i)
  50020. {
  50021. const ItemLayoutProperties* const layout = getInfoFor (i);
  50022. if (layout != 0)
  50023. {
  50024. Component* const c = components[i];
  50025. if (c != 0)
  50026. {
  50027. if (i == numComponents - 1)
  50028. {
  50029. // if it's the last item, crop it to exactly fit the available space..
  50030. if (resizeOtherDimension)
  50031. {
  50032. if (vertically)
  50033. c->setBounds (x, pos, w, jmax (layout->currentSize, h - pos));
  50034. else
  50035. c->setBounds (pos, y, jmax (layout->currentSize, w - pos), h);
  50036. }
  50037. else
  50038. {
  50039. if (vertically)
  50040. c->setBounds (c->getX(), pos, c->getWidth(), jmax (layout->currentSize, h - pos));
  50041. else
  50042. c->setBounds (pos, c->getY(), jmax (layout->currentSize, w - pos), c->getHeight());
  50043. }
  50044. }
  50045. else
  50046. {
  50047. if (resizeOtherDimension)
  50048. {
  50049. if (vertically)
  50050. c->setBounds (x, pos, w, layout->currentSize);
  50051. else
  50052. c->setBounds (pos, y, layout->currentSize, h);
  50053. }
  50054. else
  50055. {
  50056. if (vertically)
  50057. c->setBounds (c->getX(), pos, c->getWidth(), layout->currentSize);
  50058. else
  50059. c->setBounds (pos, c->getY(), layout->currentSize, c->getHeight());
  50060. }
  50061. }
  50062. }
  50063. pos += layout->currentSize;
  50064. }
  50065. }
  50066. }
  50067. StretchableLayoutManager::ItemLayoutProperties* StretchableLayoutManager::getInfoFor (const int itemIndex) const
  50068. {
  50069. for (int i = items.size(); --i >= 0;)
  50070. if (items.getUnchecked(i)->itemIndex == itemIndex)
  50071. return items.getUnchecked(i);
  50072. return 0;
  50073. }
  50074. int StretchableLayoutManager::fitComponentsIntoSpace (const int startIndex,
  50075. const int endIndex,
  50076. const int availableSpace,
  50077. int startPos)
  50078. {
  50079. // calculate the total sizes
  50080. int i;
  50081. double totalIdealSize = 0.0;
  50082. int totalMinimums = 0;
  50083. for (i = startIndex; i < endIndex; ++i)
  50084. {
  50085. ItemLayoutProperties* const layout = items.getUnchecked (i);
  50086. layout->currentSize = sizeToRealSize (layout->minSize, totalSize);
  50087. totalMinimums += layout->currentSize;
  50088. totalIdealSize += sizeToRealSize (layout->preferredSize, availableSpace);
  50089. }
  50090. if (totalIdealSize <= 0)
  50091. totalIdealSize = 1.0;
  50092. // now calc the best sizes..
  50093. int extraSpace = availableSpace - totalMinimums;
  50094. while (extraSpace > 0)
  50095. {
  50096. int numWantingMoreSpace = 0;
  50097. int numHavingTakenExtraSpace = 0;
  50098. // first figure out how many comps want a slice of the extra space..
  50099. for (i = startIndex; i < endIndex; ++i)
  50100. {
  50101. ItemLayoutProperties* const layout = items.getUnchecked (i);
  50102. double sizeWanted = sizeToRealSize (layout->preferredSize, availableSpace);
  50103. const int bestSize = jlimit (layout->currentSize,
  50104. jmax (layout->currentSize,
  50105. sizeToRealSize (layout->maxSize, totalSize)),
  50106. roundToInt (sizeWanted * availableSpace / totalIdealSize));
  50107. if (bestSize > layout->currentSize)
  50108. ++numWantingMoreSpace;
  50109. }
  50110. // ..share out the extra space..
  50111. for (i = startIndex; i < endIndex; ++i)
  50112. {
  50113. ItemLayoutProperties* const layout = items.getUnchecked (i);
  50114. double sizeWanted = sizeToRealSize (layout->preferredSize, availableSpace);
  50115. int bestSize = jlimit (layout->currentSize,
  50116. jmax (layout->currentSize, sizeToRealSize (layout->maxSize, totalSize)),
  50117. roundToInt (sizeWanted * availableSpace / totalIdealSize));
  50118. const int extraWanted = bestSize - layout->currentSize;
  50119. if (extraWanted > 0)
  50120. {
  50121. const int extraAllowed = jmin (extraWanted,
  50122. extraSpace / jmax (1, numWantingMoreSpace));
  50123. if (extraAllowed > 0)
  50124. {
  50125. ++numHavingTakenExtraSpace;
  50126. --numWantingMoreSpace;
  50127. layout->currentSize += extraAllowed;
  50128. extraSpace -= extraAllowed;
  50129. }
  50130. }
  50131. }
  50132. if (numHavingTakenExtraSpace <= 0)
  50133. break;
  50134. }
  50135. // ..and calculate the end position
  50136. for (i = startIndex; i < endIndex; ++i)
  50137. {
  50138. ItemLayoutProperties* const layout = items.getUnchecked(i);
  50139. startPos += layout->currentSize;
  50140. }
  50141. return startPos;
  50142. }
  50143. int StretchableLayoutManager::getMinimumSizeOfItems (const int startIndex,
  50144. const int endIndex) const
  50145. {
  50146. int totalMinimums = 0;
  50147. for (int i = startIndex; i < endIndex; ++i)
  50148. totalMinimums += sizeToRealSize (items.getUnchecked (i)->minSize, totalSize);
  50149. return totalMinimums;
  50150. }
  50151. int StretchableLayoutManager::getMaximumSizeOfItems (const int startIndex, const int endIndex) const
  50152. {
  50153. int totalMaximums = 0;
  50154. for (int i = startIndex; i < endIndex; ++i)
  50155. totalMaximums += sizeToRealSize (items.getUnchecked (i)->maxSize, totalSize);
  50156. return totalMaximums;
  50157. }
  50158. void StretchableLayoutManager::updatePrefSizesToMatchCurrentPositions()
  50159. {
  50160. for (int i = 0; i < items.size(); ++i)
  50161. {
  50162. ItemLayoutProperties* const layout = items.getUnchecked (i);
  50163. layout->preferredSize
  50164. = (layout->preferredSize < 0) ? getItemCurrentRelativeSize (i)
  50165. : getItemCurrentAbsoluteSize (i);
  50166. }
  50167. }
  50168. int StretchableLayoutManager::sizeToRealSize (double size, int totalSpace)
  50169. {
  50170. if (size < 0)
  50171. size *= -totalSpace;
  50172. return roundToInt (size);
  50173. }
  50174. END_JUCE_NAMESPACE
  50175. /*** End of inlined file: juce_StretchableLayoutManager.cpp ***/
  50176. /*** Start of inlined file: juce_StretchableLayoutResizerBar.cpp ***/
  50177. BEGIN_JUCE_NAMESPACE
  50178. StretchableLayoutResizerBar::StretchableLayoutResizerBar (StretchableLayoutManager* layout_,
  50179. const int itemIndex_,
  50180. const bool isVertical_)
  50181. : layout (layout_),
  50182. itemIndex (itemIndex_),
  50183. isVertical (isVertical_)
  50184. {
  50185. setRepaintsOnMouseActivity (true);
  50186. setMouseCursor (MouseCursor (isVertical_ ? MouseCursor::LeftRightResizeCursor
  50187. : MouseCursor::UpDownResizeCursor));
  50188. }
  50189. StretchableLayoutResizerBar::~StretchableLayoutResizerBar()
  50190. {
  50191. }
  50192. void StretchableLayoutResizerBar::paint (Graphics& g)
  50193. {
  50194. getLookAndFeel().drawStretchableLayoutResizerBar (g,
  50195. getWidth(), getHeight(),
  50196. isVertical,
  50197. isMouseOver(),
  50198. isMouseButtonDown());
  50199. }
  50200. void StretchableLayoutResizerBar::mouseDown (const MouseEvent&)
  50201. {
  50202. mouseDownPos = layout->getItemCurrentPosition (itemIndex);
  50203. }
  50204. void StretchableLayoutResizerBar::mouseDrag (const MouseEvent& e)
  50205. {
  50206. const int desiredPos = mouseDownPos + (isVertical ? e.getDistanceFromDragStartX()
  50207. : e.getDistanceFromDragStartY());
  50208. layout->setItemPosition (itemIndex, desiredPos);
  50209. hasBeenMoved();
  50210. }
  50211. void StretchableLayoutResizerBar::hasBeenMoved()
  50212. {
  50213. if (getParentComponent() != 0)
  50214. getParentComponent()->resized();
  50215. }
  50216. END_JUCE_NAMESPACE
  50217. /*** End of inlined file: juce_StretchableLayoutResizerBar.cpp ***/
  50218. /*** Start of inlined file: juce_StretchableObjectResizer.cpp ***/
  50219. BEGIN_JUCE_NAMESPACE
  50220. StretchableObjectResizer::StretchableObjectResizer()
  50221. {
  50222. }
  50223. StretchableObjectResizer::~StretchableObjectResizer()
  50224. {
  50225. }
  50226. void StretchableObjectResizer::addItem (const double size,
  50227. const double minSize, const double maxSize,
  50228. const int order)
  50229. {
  50230. // the order must be >= 0 but less than the maximum integer value.
  50231. jassert (order >= 0 && order < std::numeric_limits<int>::max());
  50232. Item* const item = new Item();
  50233. item->size = size;
  50234. item->minSize = minSize;
  50235. item->maxSize = maxSize;
  50236. item->order = order;
  50237. items.add (item);
  50238. }
  50239. double StretchableObjectResizer::getItemSize (const int index) const throw()
  50240. {
  50241. const Item* const it = items [index];
  50242. return it != 0 ? it->size : 0;
  50243. }
  50244. void StretchableObjectResizer::resizeToFit (const double targetSize)
  50245. {
  50246. int order = 0;
  50247. for (;;)
  50248. {
  50249. double currentSize = 0;
  50250. double minSize = 0;
  50251. double maxSize = 0;
  50252. int nextHighestOrder = std::numeric_limits<int>::max();
  50253. for (int i = 0; i < items.size(); ++i)
  50254. {
  50255. const Item* const it = items.getUnchecked(i);
  50256. currentSize += it->size;
  50257. if (it->order <= order)
  50258. {
  50259. minSize += it->minSize;
  50260. maxSize += it->maxSize;
  50261. }
  50262. else
  50263. {
  50264. minSize += it->size;
  50265. maxSize += it->size;
  50266. nextHighestOrder = jmin (nextHighestOrder, it->order);
  50267. }
  50268. }
  50269. const double thisIterationTarget = jlimit (minSize, maxSize, targetSize);
  50270. if (thisIterationTarget >= currentSize)
  50271. {
  50272. const double availableExtraSpace = maxSize - currentSize;
  50273. const double targetAmountOfExtraSpace = thisIterationTarget - currentSize;
  50274. const double scale = targetAmountOfExtraSpace / availableExtraSpace;
  50275. for (int i = 0; i < items.size(); ++i)
  50276. {
  50277. Item* const it = items.getUnchecked(i);
  50278. if (it->order <= order)
  50279. it->size = jmin (it->maxSize, it->size + (it->maxSize - it->size) * scale);
  50280. }
  50281. }
  50282. else
  50283. {
  50284. const double amountOfSlack = currentSize - minSize;
  50285. const double targetAmountOfSlack = thisIterationTarget - minSize;
  50286. const double scale = targetAmountOfSlack / amountOfSlack;
  50287. for (int i = 0; i < items.size(); ++i)
  50288. {
  50289. Item* const it = items.getUnchecked(i);
  50290. if (it->order <= order)
  50291. it->size = jmax (it->minSize, it->minSize + (it->size - it->minSize) * scale);
  50292. }
  50293. }
  50294. if (nextHighestOrder < std::numeric_limits<int>::max())
  50295. order = nextHighestOrder;
  50296. else
  50297. break;
  50298. }
  50299. }
  50300. END_JUCE_NAMESPACE
  50301. /*** End of inlined file: juce_StretchableObjectResizer.cpp ***/
  50302. /*** Start of inlined file: juce_TabbedButtonBar.cpp ***/
  50303. BEGIN_JUCE_NAMESPACE
  50304. TabBarButton::TabBarButton (const String& name,
  50305. TabbedButtonBar* const owner_,
  50306. const int index)
  50307. : Button (name),
  50308. owner (owner_),
  50309. tabIndex (index),
  50310. overlapPixels (0)
  50311. {
  50312. shadow.setShadowProperties (2.2f, 0.7f, 0, 0);
  50313. setComponentEffect (&shadow);
  50314. setWantsKeyboardFocus (false);
  50315. }
  50316. TabBarButton::~TabBarButton()
  50317. {
  50318. }
  50319. void TabBarButton::paintButton (Graphics& g,
  50320. bool isMouseOverButton,
  50321. bool isButtonDown)
  50322. {
  50323. int x, y, w, h;
  50324. getActiveArea (x, y, w, h);
  50325. g.setOrigin (x, y);
  50326. getLookAndFeel()
  50327. .drawTabButton (g, w, h,
  50328. owner->getTabBackgroundColour (tabIndex),
  50329. tabIndex, getButtonText(), *this,
  50330. owner->getOrientation(),
  50331. isMouseOverButton, isButtonDown,
  50332. getToggleState());
  50333. }
  50334. void TabBarButton::clicked (const ModifierKeys& mods)
  50335. {
  50336. if (mods.isPopupMenu())
  50337. owner->popupMenuClickOnTab (tabIndex, getButtonText());
  50338. else
  50339. owner->setCurrentTabIndex (tabIndex);
  50340. }
  50341. bool TabBarButton::hitTest (int mx, int my)
  50342. {
  50343. int x, y, w, h;
  50344. getActiveArea (x, y, w, h);
  50345. if (owner->getOrientation() == TabbedButtonBar::TabsAtLeft
  50346. || owner->getOrientation() == TabbedButtonBar::TabsAtRight)
  50347. {
  50348. if (((unsigned int) mx) < (unsigned int) getWidth()
  50349. && my >= y + overlapPixels
  50350. && my < y + h - overlapPixels)
  50351. return true;
  50352. }
  50353. else
  50354. {
  50355. if (mx >= x + overlapPixels && mx < x + w - overlapPixels
  50356. && ((unsigned int) my) < (unsigned int) getHeight())
  50357. return true;
  50358. }
  50359. Path p;
  50360. getLookAndFeel()
  50361. .createTabButtonShape (p, w, h, tabIndex, getButtonText(), *this,
  50362. owner->getOrientation(),
  50363. false, false, getToggleState());
  50364. return p.contains ((float) (mx - x),
  50365. (float) (my - y));
  50366. }
  50367. int TabBarButton::getBestTabLength (const int depth)
  50368. {
  50369. return jlimit (depth * 2,
  50370. depth * 7,
  50371. getLookAndFeel().getTabButtonBestWidth (tabIndex, getButtonText(), depth, *this));
  50372. }
  50373. void TabBarButton::getActiveArea (int& x, int& y, int& w, int& h)
  50374. {
  50375. x = 0;
  50376. y = 0;
  50377. int r = getWidth();
  50378. int b = getHeight();
  50379. const int spaceAroundImage = getLookAndFeel().getTabButtonSpaceAroundImage();
  50380. if (owner->getOrientation() != TabbedButtonBar::TabsAtLeft)
  50381. r -= spaceAroundImage;
  50382. if (owner->getOrientation() != TabbedButtonBar::TabsAtRight)
  50383. x += spaceAroundImage;
  50384. if (owner->getOrientation() != TabbedButtonBar::TabsAtBottom)
  50385. y += spaceAroundImage;
  50386. if (owner->getOrientation() != TabbedButtonBar::TabsAtTop)
  50387. b -= spaceAroundImage;
  50388. w = r - x;
  50389. h = b - y;
  50390. }
  50391. class TabAreaBehindFrontButtonComponent : public Component
  50392. {
  50393. public:
  50394. TabAreaBehindFrontButtonComponent (TabbedButtonBar* const owner_)
  50395. : owner (owner_)
  50396. {
  50397. setInterceptsMouseClicks (false, false);
  50398. }
  50399. ~TabAreaBehindFrontButtonComponent()
  50400. {
  50401. }
  50402. void paint (Graphics& g)
  50403. {
  50404. getLookAndFeel()
  50405. .drawTabAreaBehindFrontButton (g, getWidth(), getHeight(),
  50406. *owner, owner->getOrientation());
  50407. }
  50408. void enablementChanged()
  50409. {
  50410. repaint();
  50411. }
  50412. private:
  50413. TabbedButtonBar* const owner;
  50414. TabAreaBehindFrontButtonComponent (const TabAreaBehindFrontButtonComponent&);
  50415. TabAreaBehindFrontButtonComponent& operator= (const TabAreaBehindFrontButtonComponent&);
  50416. };
  50417. TabbedButtonBar::TabbedButtonBar (const Orientation orientation_)
  50418. : orientation (orientation_),
  50419. currentTabIndex (-1),
  50420. extraTabsButton (0)
  50421. {
  50422. setInterceptsMouseClicks (false, true);
  50423. addAndMakeVisible (behindFrontTab = new TabAreaBehindFrontButtonComponent (this));
  50424. setFocusContainer (true);
  50425. }
  50426. TabbedButtonBar::~TabbedButtonBar()
  50427. {
  50428. deleteAllChildren();
  50429. }
  50430. void TabbedButtonBar::setOrientation (const Orientation newOrientation)
  50431. {
  50432. orientation = newOrientation;
  50433. for (int i = getNumChildComponents(); --i >= 0;)
  50434. getChildComponent (i)->resized();
  50435. resized();
  50436. }
  50437. TabBarButton* TabbedButtonBar::createTabButton (const String& name, const int index)
  50438. {
  50439. return new TabBarButton (name, this, index);
  50440. }
  50441. void TabbedButtonBar::clearTabs()
  50442. {
  50443. tabs.clear();
  50444. tabColours.clear();
  50445. currentTabIndex = -1;
  50446. deleteAndZero (extraTabsButton);
  50447. removeChildComponent (behindFrontTab);
  50448. deleteAllChildren();
  50449. addChildComponent (behindFrontTab);
  50450. setCurrentTabIndex (-1);
  50451. }
  50452. void TabbedButtonBar::addTab (const String& tabName,
  50453. const Colour& tabBackgroundColour,
  50454. int insertIndex)
  50455. {
  50456. jassert (tabName.isNotEmpty()); // you have to give them all a name..
  50457. if (tabName.isNotEmpty())
  50458. {
  50459. if (((unsigned int) insertIndex) > (unsigned int) tabs.size())
  50460. insertIndex = tabs.size();
  50461. for (int i = tabs.size(); --i >= insertIndex;)
  50462. {
  50463. TabBarButton* const tb = getTabButton (i);
  50464. if (tb != 0)
  50465. tb->tabIndex++;
  50466. }
  50467. tabs.insert (insertIndex, tabName);
  50468. tabColours.insert (insertIndex, tabBackgroundColour);
  50469. TabBarButton* const tb = createTabButton (tabName, insertIndex);
  50470. jassert (tb != 0); // your createTabButton() mustn't return zero!
  50471. addAndMakeVisible (tb, insertIndex);
  50472. resized();
  50473. if (currentTabIndex < 0)
  50474. setCurrentTabIndex (0);
  50475. }
  50476. }
  50477. void TabbedButtonBar::setTabName (const int tabIndex,
  50478. const String& newName)
  50479. {
  50480. if (((unsigned int) tabIndex) < (unsigned int) tabs.size()
  50481. && tabs[tabIndex] != newName)
  50482. {
  50483. tabs.set (tabIndex, newName);
  50484. TabBarButton* const tb = getTabButton (tabIndex);
  50485. if (tb != 0)
  50486. tb->setButtonText (newName);
  50487. resized();
  50488. }
  50489. }
  50490. void TabbedButtonBar::removeTab (const int tabIndex)
  50491. {
  50492. if (((unsigned int) tabIndex) < (unsigned int) tabs.size())
  50493. {
  50494. const int oldTabIndex = currentTabIndex;
  50495. if (currentTabIndex == tabIndex)
  50496. currentTabIndex = -1;
  50497. tabs.remove (tabIndex);
  50498. tabColours.remove (tabIndex);
  50499. delete getTabButton (tabIndex);
  50500. for (int i = tabIndex + 1; i <= tabs.size(); ++i)
  50501. {
  50502. TabBarButton* const tb = getTabButton (i);
  50503. if (tb != 0)
  50504. tb->tabIndex--;
  50505. }
  50506. resized();
  50507. setCurrentTabIndex (jlimit (0, jmax (0, tabs.size() - 1), oldTabIndex));
  50508. }
  50509. }
  50510. void TabbedButtonBar::moveTab (const int currentIndex,
  50511. const int newIndex)
  50512. {
  50513. tabs.move (currentIndex, newIndex);
  50514. tabColours.move (currentIndex, newIndex);
  50515. resized();
  50516. }
  50517. int TabbedButtonBar::getNumTabs() const
  50518. {
  50519. return tabs.size();
  50520. }
  50521. const StringArray TabbedButtonBar::getTabNames() const
  50522. {
  50523. return tabs;
  50524. }
  50525. void TabbedButtonBar::setCurrentTabIndex (int newIndex, const bool sendChangeMessage_)
  50526. {
  50527. if (currentTabIndex != newIndex)
  50528. {
  50529. if (((unsigned int) newIndex) >= (unsigned int) tabs.size())
  50530. newIndex = -1;
  50531. currentTabIndex = newIndex;
  50532. for (int i = 0; i < getNumChildComponents(); ++i)
  50533. {
  50534. TabBarButton* const tb = dynamic_cast <TabBarButton*> (getChildComponent (i));
  50535. if (tb != 0)
  50536. tb->setToggleState (tb->tabIndex == newIndex, false);
  50537. }
  50538. resized();
  50539. if (sendChangeMessage_)
  50540. sendChangeMessage (this);
  50541. currentTabChanged (newIndex, newIndex >= 0 ? tabs [newIndex] : String::empty);
  50542. }
  50543. }
  50544. TabBarButton* TabbedButtonBar::getTabButton (const int index) const
  50545. {
  50546. for (int i = getNumChildComponents(); --i >= 0;)
  50547. {
  50548. TabBarButton* const tb = dynamic_cast <TabBarButton*> (getChildComponent (i));
  50549. if (tb != 0 && tb->tabIndex == index)
  50550. return tb;
  50551. }
  50552. return 0;
  50553. }
  50554. void TabbedButtonBar::lookAndFeelChanged()
  50555. {
  50556. deleteAndZero (extraTabsButton);
  50557. resized();
  50558. }
  50559. void TabbedButtonBar::resized()
  50560. {
  50561. const double minimumScale = 0.7;
  50562. int depth = getWidth();
  50563. int length = getHeight();
  50564. if (orientation == TabsAtTop || orientation == TabsAtBottom)
  50565. swapVariables (depth, length);
  50566. const int overlap = getLookAndFeel().getTabButtonOverlap (depth)
  50567. + getLookAndFeel().getTabButtonSpaceAroundImage() * 2;
  50568. int i, totalLength = overlap;
  50569. int numVisibleButtons = tabs.size();
  50570. for (i = 0; i < getNumChildComponents(); ++i)
  50571. {
  50572. TabBarButton* const tb = dynamic_cast <TabBarButton*> (getChildComponent (i));
  50573. if (tb != 0)
  50574. {
  50575. totalLength += tb->getBestTabLength (depth) - overlap;
  50576. tb->overlapPixels = overlap / 2;
  50577. }
  50578. }
  50579. double scale = 1.0;
  50580. if (totalLength > length)
  50581. scale = jmax (minimumScale, length / (double) totalLength);
  50582. const bool isTooBig = totalLength * scale > length;
  50583. int tabsButtonPos = 0;
  50584. if (isTooBig)
  50585. {
  50586. if (extraTabsButton == 0)
  50587. {
  50588. addAndMakeVisible (extraTabsButton = getLookAndFeel().createTabBarExtrasButton());
  50589. extraTabsButton->addButtonListener (this);
  50590. extraTabsButton->setAlwaysOnTop (true);
  50591. extraTabsButton->setTriggeredOnMouseDown (true);
  50592. }
  50593. const int buttonSize = jmin (proportionOfWidth (0.7f), proportionOfHeight (0.7f));
  50594. extraTabsButton->setSize (buttonSize, buttonSize);
  50595. if (orientation == TabsAtTop || orientation == TabsAtBottom)
  50596. {
  50597. tabsButtonPos = getWidth() - buttonSize / 2 - 1;
  50598. extraTabsButton->setCentrePosition (tabsButtonPos, getHeight() / 2);
  50599. }
  50600. else
  50601. {
  50602. tabsButtonPos = getHeight() - buttonSize / 2 - 1;
  50603. extraTabsButton->setCentrePosition (getWidth() / 2, tabsButtonPos);
  50604. }
  50605. totalLength = 0;
  50606. for (i = 0; i < tabs.size(); ++i)
  50607. {
  50608. TabBarButton* const tb = getTabButton (i);
  50609. if (tb != 0)
  50610. {
  50611. const int newLength = totalLength + tb->getBestTabLength (depth);
  50612. if (i > 0 && newLength * minimumScale > tabsButtonPos)
  50613. {
  50614. totalLength += overlap;
  50615. break;
  50616. }
  50617. numVisibleButtons = i + 1;
  50618. totalLength = newLength - overlap;
  50619. }
  50620. }
  50621. scale = jmax (minimumScale, tabsButtonPos / (double) totalLength);
  50622. }
  50623. else
  50624. {
  50625. deleteAndZero (extraTabsButton);
  50626. }
  50627. int pos = 0;
  50628. TabBarButton* frontTab = 0;
  50629. for (i = 0; i < tabs.size(); ++i)
  50630. {
  50631. TabBarButton* const tb = getTabButton (i);
  50632. if (tb != 0)
  50633. {
  50634. const int bestLength = roundToInt (scale * tb->getBestTabLength (depth));
  50635. if (i < numVisibleButtons)
  50636. {
  50637. if (orientation == TabsAtTop || orientation == TabsAtBottom)
  50638. tb->setBounds (pos, 0, bestLength, getHeight());
  50639. else
  50640. tb->setBounds (0, pos, getWidth(), bestLength);
  50641. tb->toBack();
  50642. if (tb->tabIndex == currentTabIndex)
  50643. frontTab = tb;
  50644. tb->setVisible (true);
  50645. }
  50646. else
  50647. {
  50648. tb->setVisible (false);
  50649. }
  50650. pos += bestLength - overlap;
  50651. }
  50652. }
  50653. behindFrontTab->setBounds (0, 0, getWidth(), getHeight());
  50654. if (frontTab != 0)
  50655. {
  50656. frontTab->toFront (false);
  50657. behindFrontTab->toBehind (frontTab);
  50658. }
  50659. }
  50660. const Colour TabbedButtonBar::getTabBackgroundColour (const int tabIndex)
  50661. {
  50662. return tabColours [tabIndex];
  50663. }
  50664. void TabbedButtonBar::setTabBackgroundColour (const int tabIndex, const Colour& newColour)
  50665. {
  50666. if (((unsigned int) tabIndex) < (unsigned int) tabColours.size()
  50667. && tabColours [tabIndex] != newColour)
  50668. {
  50669. tabColours.set (tabIndex, newColour);
  50670. repaint();
  50671. }
  50672. }
  50673. void TabbedButtonBar::buttonClicked (Button* button)
  50674. {
  50675. if (extraTabsButton == button)
  50676. {
  50677. PopupMenu m;
  50678. for (int i = 0; i < tabs.size(); ++i)
  50679. {
  50680. TabBarButton* const tb = getTabButton (i);
  50681. if (tb != 0 && ! tb->isVisible())
  50682. m.addItem (tb->tabIndex + 1, tabs[i], true, i == currentTabIndex);
  50683. }
  50684. const int res = m.showAt (extraTabsButton);
  50685. if (res != 0)
  50686. setCurrentTabIndex (res - 1);
  50687. }
  50688. }
  50689. void TabbedButtonBar::currentTabChanged (const int, const String&)
  50690. {
  50691. }
  50692. void TabbedButtonBar::popupMenuClickOnTab (const int, const String&)
  50693. {
  50694. }
  50695. END_JUCE_NAMESPACE
  50696. /*** End of inlined file: juce_TabbedButtonBar.cpp ***/
  50697. /*** Start of inlined file: juce_TabbedComponent.cpp ***/
  50698. BEGIN_JUCE_NAMESPACE
  50699. class TabCompButtonBar : public TabbedButtonBar
  50700. {
  50701. public:
  50702. TabCompButtonBar (TabbedComponent* const owner_,
  50703. const TabbedButtonBar::Orientation orientation)
  50704. : TabbedButtonBar (orientation),
  50705. owner (owner_)
  50706. {
  50707. }
  50708. ~TabCompButtonBar()
  50709. {
  50710. }
  50711. void currentTabChanged (int newCurrentTabIndex,
  50712. const String& newTabName)
  50713. {
  50714. owner->changeCallback (newCurrentTabIndex, newTabName);
  50715. }
  50716. void popupMenuClickOnTab (int tabIndex,
  50717. const String& tabName)
  50718. {
  50719. owner->popupMenuClickOnTab (tabIndex, tabName);
  50720. }
  50721. const Colour getTabBackgroundColour (const int tabIndex)
  50722. {
  50723. return owner->tabs->getTabBackgroundColour (tabIndex);
  50724. }
  50725. TabBarButton* createTabButton (const String& tabName, int tabIndex)
  50726. {
  50727. return owner->createTabButton (tabName, tabIndex);
  50728. }
  50729. juce_UseDebuggingNewOperator
  50730. private:
  50731. TabbedComponent* const owner;
  50732. TabCompButtonBar (const TabCompButtonBar&);
  50733. TabCompButtonBar& operator= (const TabCompButtonBar&);
  50734. };
  50735. TabbedComponent::TabbedComponent (const TabbedButtonBar::Orientation orientation)
  50736. : panelComponent (0),
  50737. tabDepth (30),
  50738. outlineThickness (1),
  50739. edgeIndent (0)
  50740. {
  50741. addAndMakeVisible (tabs = new TabCompButtonBar (this, orientation));
  50742. }
  50743. TabbedComponent::~TabbedComponent()
  50744. {
  50745. clearTabs();
  50746. delete tabs;
  50747. }
  50748. void TabbedComponent::setOrientation (const TabbedButtonBar::Orientation orientation)
  50749. {
  50750. tabs->setOrientation (orientation);
  50751. resized();
  50752. }
  50753. TabbedButtonBar::Orientation TabbedComponent::getOrientation() const throw()
  50754. {
  50755. return tabs->getOrientation();
  50756. }
  50757. void TabbedComponent::setTabBarDepth (const int newDepth)
  50758. {
  50759. if (tabDepth != newDepth)
  50760. {
  50761. tabDepth = newDepth;
  50762. resized();
  50763. }
  50764. }
  50765. TabBarButton* TabbedComponent::createTabButton (const String& tabName, const int tabIndex)
  50766. {
  50767. return new TabBarButton (tabName, tabs, tabIndex);
  50768. }
  50769. void TabbedComponent::clearTabs()
  50770. {
  50771. if (panelComponent != 0)
  50772. {
  50773. panelComponent->setVisible (false);
  50774. removeChildComponent (panelComponent);
  50775. panelComponent = 0;
  50776. }
  50777. tabs->clearTabs();
  50778. for (int i = contentComponents.size(); --i >= 0;)
  50779. {
  50780. Component* const c = contentComponents.getUnchecked(i);
  50781. // be careful not to delete these components until they've been removed from the tab component
  50782. jassert (c == 0 || c->isValidComponent());
  50783. if (c != 0 && (bool) c->getProperties() ["deleteByTabComp_"])
  50784. delete c;
  50785. }
  50786. contentComponents.clear();
  50787. }
  50788. void TabbedComponent::addTab (const String& tabName,
  50789. const Colour& tabBackgroundColour,
  50790. Component* const contentComponent,
  50791. const bool deleteComponentWhenNotNeeded,
  50792. const int insertIndex)
  50793. {
  50794. contentComponents.insert (insertIndex, contentComponent);
  50795. if (contentComponent != 0)
  50796. contentComponent->getProperties().set ("deleteByTabComp_", deleteComponentWhenNotNeeded);
  50797. tabs->addTab (tabName, tabBackgroundColour, insertIndex);
  50798. }
  50799. void TabbedComponent::setTabName (const int tabIndex,
  50800. const String& newName)
  50801. {
  50802. tabs->setTabName (tabIndex, newName);
  50803. }
  50804. void TabbedComponent::removeTab (const int tabIndex)
  50805. {
  50806. Component* const c = contentComponents [tabIndex];
  50807. if (c != 0 && (bool) c->getProperties() ["deleteByTabComp_"])
  50808. {
  50809. if (c == panelComponent)
  50810. panelComponent = 0;
  50811. delete c;
  50812. }
  50813. contentComponents.remove (tabIndex);
  50814. tabs->removeTab (tabIndex);
  50815. }
  50816. int TabbedComponent::getNumTabs() const
  50817. {
  50818. return tabs->getNumTabs();
  50819. }
  50820. const StringArray TabbedComponent::getTabNames() const
  50821. {
  50822. return tabs->getTabNames();
  50823. }
  50824. Component* TabbedComponent::getTabContentComponent (const int tabIndex) const throw()
  50825. {
  50826. return contentComponents [tabIndex];
  50827. }
  50828. const Colour TabbedComponent::getTabBackgroundColour (const int tabIndex) const throw()
  50829. {
  50830. return tabs->getTabBackgroundColour (tabIndex);
  50831. }
  50832. void TabbedComponent::setTabBackgroundColour (const int tabIndex, const Colour& newColour)
  50833. {
  50834. tabs->setTabBackgroundColour (tabIndex, newColour);
  50835. if (getCurrentTabIndex() == tabIndex)
  50836. repaint();
  50837. }
  50838. void TabbedComponent::setCurrentTabIndex (const int newTabIndex, const bool sendChangeMessage)
  50839. {
  50840. tabs->setCurrentTabIndex (newTabIndex, sendChangeMessage);
  50841. }
  50842. int TabbedComponent::getCurrentTabIndex() const
  50843. {
  50844. return tabs->getCurrentTabIndex();
  50845. }
  50846. const String& TabbedComponent::getCurrentTabName() const
  50847. {
  50848. return tabs->getCurrentTabName();
  50849. }
  50850. void TabbedComponent::setOutline (int thickness)
  50851. {
  50852. outlineThickness = thickness;
  50853. repaint();
  50854. }
  50855. void TabbedComponent::setIndent (const int indentThickness)
  50856. {
  50857. edgeIndent = indentThickness;
  50858. }
  50859. void TabbedComponent::paint (Graphics& g)
  50860. {
  50861. g.fillAll (findColour (backgroundColourId));
  50862. const TabbedButtonBar::Orientation o = getOrientation();
  50863. int x = 0;
  50864. int y = 0;
  50865. int r = getWidth();
  50866. int b = getHeight();
  50867. if (o == TabbedButtonBar::TabsAtTop)
  50868. y += tabDepth;
  50869. else if (o == TabbedButtonBar::TabsAtBottom)
  50870. b -= tabDepth;
  50871. else if (o == TabbedButtonBar::TabsAtLeft)
  50872. x += tabDepth;
  50873. else if (o == TabbedButtonBar::TabsAtRight)
  50874. r -= tabDepth;
  50875. g.reduceClipRegion (x, y, r - x, b - y);
  50876. g.fillAll (tabs->getTabBackgroundColour (getCurrentTabIndex()));
  50877. if (outlineThickness > 0)
  50878. {
  50879. if (o == TabbedButtonBar::TabsAtTop)
  50880. --y;
  50881. else if (o == TabbedButtonBar::TabsAtBottom)
  50882. ++b;
  50883. else if (o == TabbedButtonBar::TabsAtLeft)
  50884. --x;
  50885. else if (o == TabbedButtonBar::TabsAtRight)
  50886. ++r;
  50887. g.setColour (findColour (outlineColourId));
  50888. g.drawRect (x, y, r - x, b - y, outlineThickness);
  50889. }
  50890. }
  50891. void TabbedComponent::resized()
  50892. {
  50893. const TabbedButtonBar::Orientation o = getOrientation();
  50894. const int indent = edgeIndent + outlineThickness;
  50895. BorderSize indents (indent);
  50896. if (o == TabbedButtonBar::TabsAtTop)
  50897. {
  50898. tabs->setBounds (0, 0, getWidth(), tabDepth);
  50899. indents.setTop (tabDepth + edgeIndent);
  50900. }
  50901. else if (o == TabbedButtonBar::TabsAtBottom)
  50902. {
  50903. tabs->setBounds (0, getHeight() - tabDepth, getWidth(), tabDepth);
  50904. indents.setBottom (tabDepth + edgeIndent);
  50905. }
  50906. else if (o == TabbedButtonBar::TabsAtLeft)
  50907. {
  50908. tabs->setBounds (0, 0, tabDepth, getHeight());
  50909. indents.setLeft (tabDepth + edgeIndent);
  50910. }
  50911. else if (o == TabbedButtonBar::TabsAtRight)
  50912. {
  50913. tabs->setBounds (getWidth() - tabDepth, 0, tabDepth, getHeight());
  50914. indents.setRight (tabDepth + edgeIndent);
  50915. }
  50916. const Rectangle<int> bounds (indents.subtractedFrom (getLocalBounds()));
  50917. for (int i = contentComponents.size(); --i >= 0;)
  50918. if (contentComponents.getUnchecked (i) != 0)
  50919. contentComponents.getUnchecked (i)->setBounds (bounds);
  50920. }
  50921. void TabbedComponent::lookAndFeelChanged()
  50922. {
  50923. for (int i = contentComponents.size(); --i >= 0;)
  50924. if (contentComponents.getUnchecked (i) != 0)
  50925. contentComponents.getUnchecked (i)->lookAndFeelChanged();
  50926. }
  50927. void TabbedComponent::changeCallback (const int newCurrentTabIndex,
  50928. const String& newTabName)
  50929. {
  50930. if (panelComponent != 0)
  50931. {
  50932. panelComponent->setVisible (false);
  50933. removeChildComponent (panelComponent);
  50934. panelComponent = 0;
  50935. }
  50936. if (getCurrentTabIndex() >= 0)
  50937. {
  50938. panelComponent = contentComponents [getCurrentTabIndex()];
  50939. if (panelComponent != 0)
  50940. {
  50941. // do these ops as two stages instead of addAndMakeVisible() so that the
  50942. // component has always got a parent when it gets the visibilityChanged() callback
  50943. addChildComponent (panelComponent);
  50944. panelComponent->setVisible (true);
  50945. panelComponent->toFront (true);
  50946. }
  50947. repaint();
  50948. }
  50949. resized();
  50950. currentTabChanged (newCurrentTabIndex, newTabName);
  50951. }
  50952. void TabbedComponent::currentTabChanged (const int, const String&)
  50953. {
  50954. }
  50955. void TabbedComponent::popupMenuClickOnTab (const int, const String&)
  50956. {
  50957. }
  50958. END_JUCE_NAMESPACE
  50959. /*** End of inlined file: juce_TabbedComponent.cpp ***/
  50960. /*** Start of inlined file: juce_Viewport.cpp ***/
  50961. BEGIN_JUCE_NAMESPACE
  50962. Viewport::Viewport (const String& componentName)
  50963. : Component (componentName),
  50964. contentComp (0),
  50965. scrollBarThickness (0),
  50966. singleStepX (16),
  50967. singleStepY (16),
  50968. showHScrollbar (true),
  50969. showVScrollbar (true)
  50970. {
  50971. // content holder is used to clip the contents so they don't overlap the scrollbars
  50972. addAndMakeVisible (contentHolder = new Component());
  50973. contentHolder->setInterceptsMouseClicks (false, true);
  50974. verticalScrollBar = new ScrollBar (true);
  50975. horizontalScrollBar = new ScrollBar (false);
  50976. addChildComponent (verticalScrollBar);
  50977. addChildComponent (horizontalScrollBar);
  50978. verticalScrollBar->addListener (this);
  50979. horizontalScrollBar->addListener (this);
  50980. setInterceptsMouseClicks (false, true);
  50981. setWantsKeyboardFocus (true);
  50982. }
  50983. Viewport::~Viewport()
  50984. {
  50985. contentHolder->deleteAllChildren();
  50986. deleteAllChildren();
  50987. }
  50988. void Viewport::visibleAreaChanged (int, int, int, int)
  50989. {
  50990. }
  50991. void Viewport::setViewedComponent (Component* const newViewedComponent)
  50992. {
  50993. if (contentComp.getComponent() != newViewedComponent)
  50994. {
  50995. {
  50996. ScopedPointer<Component> oldCompDeleter (contentComp);
  50997. contentComp = 0;
  50998. }
  50999. contentComp = newViewedComponent;
  51000. if (contentComp != 0)
  51001. {
  51002. contentComp->setTopLeftPosition (0, 0);
  51003. contentHolder->addAndMakeVisible (contentComp);
  51004. contentComp->addComponentListener (this);
  51005. }
  51006. updateVisibleRegion();
  51007. }
  51008. }
  51009. int Viewport::getMaximumVisibleWidth() const throw()
  51010. {
  51011. return jmax (0, getWidth() - (verticalScrollBar->isVisible() ? getScrollBarThickness() : 0));
  51012. }
  51013. int Viewport::getMaximumVisibleHeight() const throw()
  51014. {
  51015. return jmax (0, getHeight() - (horizontalScrollBar->isVisible() ? getScrollBarThickness() : 0));
  51016. }
  51017. void Viewport::setViewPosition (const int xPixelsOffset, const int yPixelsOffset)
  51018. {
  51019. if (contentComp != 0)
  51020. contentComp->setTopLeftPosition (-xPixelsOffset,
  51021. -yPixelsOffset);
  51022. }
  51023. void Viewport::setViewPositionProportionately (const double x, const double y)
  51024. {
  51025. if (contentComp != 0)
  51026. setViewPosition (jmax (0, roundToInt (x * (contentComp->getWidth() - getWidth()))),
  51027. jmax (0, roundToInt (y * (contentComp->getHeight() - getHeight()))));
  51028. }
  51029. bool Viewport::autoScroll (int mouseX, int mouseY, int activeBorderThickness, int maximumSpeed)
  51030. {
  51031. if (contentComp != 0)
  51032. {
  51033. int dx = 0, dy = 0;
  51034. if (horizontalScrollBar->isVisible())
  51035. {
  51036. if (mouseX < activeBorderThickness)
  51037. dx = activeBorderThickness - mouseX;
  51038. else if (mouseX >= contentHolder->getWidth() - activeBorderThickness)
  51039. dx = (contentHolder->getWidth() - activeBorderThickness) - mouseX;
  51040. if (dx < 0)
  51041. dx = jmax (dx, -maximumSpeed, contentHolder->getWidth() - contentComp->getRight());
  51042. else
  51043. dx = jmin (dx, maximumSpeed, -contentComp->getX());
  51044. }
  51045. if (verticalScrollBar->isVisible())
  51046. {
  51047. if (mouseY < activeBorderThickness)
  51048. dy = activeBorderThickness - mouseY;
  51049. else if (mouseY >= contentHolder->getHeight() - activeBorderThickness)
  51050. dy = (contentHolder->getHeight() - activeBorderThickness) - mouseY;
  51051. if (dy < 0)
  51052. dy = jmax (dy, -maximumSpeed, contentHolder->getHeight() - contentComp->getBottom());
  51053. else
  51054. dy = jmin (dy, maximumSpeed, -contentComp->getY());
  51055. }
  51056. if (dx != 0 || dy != 0)
  51057. {
  51058. contentComp->setTopLeftPosition (contentComp->getX() + dx,
  51059. contentComp->getY() + dy);
  51060. return true;
  51061. }
  51062. }
  51063. return false;
  51064. }
  51065. void Viewport::componentMovedOrResized (Component&, bool, bool)
  51066. {
  51067. updateVisibleRegion();
  51068. }
  51069. void Viewport::resized()
  51070. {
  51071. updateVisibleRegion();
  51072. }
  51073. void Viewport::updateVisibleRegion()
  51074. {
  51075. if (contentComp != 0)
  51076. {
  51077. Rectangle<int> newViewPos;
  51078. newViewPos.setPosition (-contentComp->getPosition());
  51079. if (newViewPos.getX() == 0 && newViewPos.getY() == 0
  51080. && contentComp->getWidth() <= getWidth()
  51081. && contentComp->getHeight() <= getHeight())
  51082. {
  51083. horizontalScrollBar->setVisible (! horizontalScrollBar->autoHides());
  51084. verticalScrollBar->setVisible (! verticalScrollBar->autoHides());
  51085. }
  51086. horizontalScrollBar->setRangeLimits (0.0, contentComp->getWidth());
  51087. horizontalScrollBar->setCurrentRange (newViewPos.getX(), getMaximumVisibleWidth());
  51088. horizontalScrollBar->setSingleStepSize (singleStepX);
  51089. if (! (contentComp->getWidth() > 0 && showHScrollbar && getHeight() > getScrollBarThickness()))
  51090. horizontalScrollBar->setVisible (! horizontalScrollBar->autoHides());
  51091. verticalScrollBar->setRangeLimits (0.0, contentComp->getHeight());
  51092. verticalScrollBar->setCurrentRange (newViewPos.getY(), getMaximumVisibleHeight());
  51093. verticalScrollBar->setSingleStepSize (singleStepY);
  51094. if (! (contentComp->getHeight() > 0 && showVScrollbar && getWidth() > getScrollBarThickness()))
  51095. verticalScrollBar->setVisible (! verticalScrollBar->autoHides());
  51096. if (verticalScrollBar->isVisible())
  51097. {
  51098. horizontalScrollBar->setCurrentRange (newViewPos.getX(), getMaximumVisibleWidth());
  51099. verticalScrollBar->setCurrentRange (newViewPos.getY(), getMaximumVisibleHeight());
  51100. verticalScrollBar
  51101. ->setBounds (getMaximumVisibleWidth(), 0,
  51102. getScrollBarThickness(), getMaximumVisibleHeight());
  51103. }
  51104. if (horizontalScrollBar->isVisible())
  51105. {
  51106. horizontalScrollBar->setCurrentRange (newViewPos.getX(), getMaximumVisibleWidth());
  51107. horizontalScrollBar
  51108. ->setBounds (0, getMaximumVisibleHeight(),
  51109. getMaximumVisibleWidth(), getScrollBarThickness());
  51110. }
  51111. contentHolder->setSize (getMaximumVisibleWidth(),
  51112. getMaximumVisibleHeight());
  51113. newViewPos.setSize (jmin (contentComp->getRight(), getMaximumVisibleWidth()),
  51114. jmin (contentComp->getBottom(), getMaximumVisibleHeight()));
  51115. if (lastViewPos != newViewPos)
  51116. {
  51117. lastViewPos = newViewPos;
  51118. visibleAreaChanged (newViewPos.getX(), newViewPos.getY(), newViewPos.getWidth(), newViewPos.getHeight());
  51119. }
  51120. horizontalScrollBar->handleUpdateNowIfNeeded();
  51121. verticalScrollBar->handleUpdateNowIfNeeded();
  51122. }
  51123. else
  51124. {
  51125. horizontalScrollBar->setVisible (! horizontalScrollBar->autoHides());
  51126. verticalScrollBar->setVisible (! verticalScrollBar->autoHides());
  51127. }
  51128. }
  51129. void Viewport::setSingleStepSizes (const int stepX, const int stepY)
  51130. {
  51131. singleStepX = stepX;
  51132. singleStepY = stepY;
  51133. updateVisibleRegion();
  51134. }
  51135. void Viewport::setScrollBarsShown (const bool showVerticalScrollbarIfNeeded,
  51136. const bool showHorizontalScrollbarIfNeeded)
  51137. {
  51138. showVScrollbar = showVerticalScrollbarIfNeeded;
  51139. showHScrollbar = showHorizontalScrollbarIfNeeded;
  51140. updateVisibleRegion();
  51141. }
  51142. void Viewport::setScrollBarThickness (const int thickness)
  51143. {
  51144. scrollBarThickness = thickness;
  51145. updateVisibleRegion();
  51146. }
  51147. int Viewport::getScrollBarThickness() const throw()
  51148. {
  51149. return (scrollBarThickness > 0) ? scrollBarThickness
  51150. : getLookAndFeel().getDefaultScrollbarWidth();
  51151. }
  51152. void Viewport::setScrollBarButtonVisibility (const bool buttonsVisible)
  51153. {
  51154. verticalScrollBar->setButtonVisibility (buttonsVisible);
  51155. horizontalScrollBar->setButtonVisibility (buttonsVisible);
  51156. }
  51157. void Viewport::scrollBarMoved (ScrollBar* scrollBarThatHasMoved, double newRangeStart)
  51158. {
  51159. if (scrollBarThatHasMoved == horizontalScrollBar)
  51160. {
  51161. setViewPosition (roundToInt (newRangeStart), getViewPositionY());
  51162. }
  51163. else if (scrollBarThatHasMoved == verticalScrollBar)
  51164. {
  51165. setViewPosition (getViewPositionX(), roundToInt (newRangeStart));
  51166. }
  51167. }
  51168. void Viewport::mouseWheelMove (const MouseEvent& e, float wheelIncrementX, float wheelIncrementY)
  51169. {
  51170. if (! useMouseWheelMoveIfNeeded (e, wheelIncrementX, wheelIncrementY))
  51171. Component::mouseWheelMove (e, wheelIncrementX, wheelIncrementY);
  51172. }
  51173. bool Viewport::useMouseWheelMoveIfNeeded (const MouseEvent& e, float wheelIncrementX, float wheelIncrementY)
  51174. {
  51175. if (! (e.mods.isAltDown() || e.mods.isCtrlDown()))
  51176. {
  51177. const bool hasVertBar = verticalScrollBar->isVisible();
  51178. const bool hasHorzBar = horizontalScrollBar->isVisible();
  51179. if (hasHorzBar && (wheelIncrementX != 0 || e.mods.isShiftDown() || ! hasVertBar))
  51180. {
  51181. if (wheelIncrementX == 0 && ! hasVertBar)
  51182. wheelIncrementX = wheelIncrementY;
  51183. horizontalScrollBar->mouseWheelMove (e.getEventRelativeTo (horizontalScrollBar),
  51184. wheelIncrementX, wheelIncrementY);
  51185. return true;
  51186. }
  51187. else if (hasVertBar && wheelIncrementY != 0)
  51188. {
  51189. verticalScrollBar->mouseWheelMove (e.getEventRelativeTo (verticalScrollBar),
  51190. wheelIncrementX, wheelIncrementY);
  51191. return true;
  51192. }
  51193. }
  51194. return false;
  51195. }
  51196. bool Viewport::keyPressed (const KeyPress& key)
  51197. {
  51198. const bool isUpDownKey = key.isKeyCode (KeyPress::upKey)
  51199. || key.isKeyCode (KeyPress::downKey)
  51200. || key.isKeyCode (KeyPress::pageUpKey)
  51201. || key.isKeyCode (KeyPress::pageDownKey)
  51202. || key.isKeyCode (KeyPress::homeKey)
  51203. || key.isKeyCode (KeyPress::endKey);
  51204. if (verticalScrollBar->isVisible() && isUpDownKey)
  51205. return verticalScrollBar->keyPressed (key);
  51206. const bool isLeftRightKey = key.isKeyCode (KeyPress::leftKey)
  51207. || key.isKeyCode (KeyPress::rightKey);
  51208. if (horizontalScrollBar->isVisible() && (isUpDownKey || isLeftRightKey))
  51209. return horizontalScrollBar->keyPressed (key);
  51210. return false;
  51211. }
  51212. END_JUCE_NAMESPACE
  51213. /*** End of inlined file: juce_Viewport.cpp ***/
  51214. /*** Start of inlined file: juce_LookAndFeel.cpp ***/
  51215. BEGIN_JUCE_NAMESPACE
  51216. static const Colour createBaseColour (const Colour& buttonColour,
  51217. const bool hasKeyboardFocus,
  51218. const bool isMouseOverButton,
  51219. const bool isButtonDown) throw()
  51220. {
  51221. const float sat = hasKeyboardFocus ? 1.3f : 0.9f;
  51222. const Colour baseColour (buttonColour.withMultipliedSaturation (sat));
  51223. if (isButtonDown)
  51224. return baseColour.contrasting (0.2f);
  51225. else if (isMouseOverButton)
  51226. return baseColour.contrasting (0.1f);
  51227. return baseColour;
  51228. }
  51229. LookAndFeel::LookAndFeel()
  51230. {
  51231. /* if this fails it means you're trying to create a LookAndFeel object before
  51232. the static Colours have been initialised. That ain't gonna work. It probably
  51233. means that you're using a static LookAndFeel object and that your compiler has
  51234. decided to intialise it before the Colours class.
  51235. */
  51236. jassert (Colours::white == Colour (0xffffffff));
  51237. // set up the standard set of colours..
  51238. const int textButtonColour = 0xffbbbbff;
  51239. const int textHighlightColour = 0x401111ee;
  51240. const int standardOutlineColour = 0xb2808080;
  51241. static const int standardColours[] =
  51242. {
  51243. TextButton::buttonColourId, textButtonColour,
  51244. TextButton::buttonOnColourId, 0xff4444ff,
  51245. TextButton::textColourOnId, 0xff000000,
  51246. TextButton::textColourOffId, 0xff000000,
  51247. ComboBox::buttonColourId, 0xffbbbbff,
  51248. ComboBox::outlineColourId, standardOutlineColour,
  51249. ToggleButton::textColourId, 0xff000000,
  51250. TextEditor::backgroundColourId, 0xffffffff,
  51251. TextEditor::textColourId, 0xff000000,
  51252. TextEditor::highlightColourId, textHighlightColour,
  51253. TextEditor::highlightedTextColourId, 0xff000000,
  51254. TextEditor::caretColourId, 0xff000000,
  51255. TextEditor::outlineColourId, 0x00000000,
  51256. TextEditor::focusedOutlineColourId, textButtonColour,
  51257. TextEditor::shadowColourId, 0x38000000,
  51258. Label::backgroundColourId, 0x00000000,
  51259. Label::textColourId, 0xff000000,
  51260. Label::outlineColourId, 0x00000000,
  51261. ScrollBar::backgroundColourId, 0x00000000,
  51262. ScrollBar::thumbColourId, 0xffffffff,
  51263. ScrollBar::trackColourId, 0xffffffff,
  51264. TreeView::linesColourId, 0x4c000000,
  51265. TreeView::backgroundColourId, 0x00000000,
  51266. TreeView::dragAndDropIndicatorColourId, 0x80ff0000,
  51267. PopupMenu::backgroundColourId, 0xffffffff,
  51268. PopupMenu::textColourId, 0xff000000,
  51269. PopupMenu::headerTextColourId, 0xff000000,
  51270. PopupMenu::highlightedTextColourId, 0xffffffff,
  51271. PopupMenu::highlightedBackgroundColourId, 0x991111aa,
  51272. ComboBox::textColourId, 0xff000000,
  51273. ComboBox::backgroundColourId, 0xffffffff,
  51274. ComboBox::arrowColourId, 0x99000000,
  51275. ListBox::backgroundColourId, 0xffffffff,
  51276. ListBox::outlineColourId, standardOutlineColour,
  51277. ListBox::textColourId, 0xff000000,
  51278. Slider::backgroundColourId, 0x00000000,
  51279. Slider::thumbColourId, textButtonColour,
  51280. Slider::trackColourId, 0x7fffffff,
  51281. Slider::rotarySliderFillColourId, 0x7f0000ff,
  51282. Slider::rotarySliderOutlineColourId, 0x66000000,
  51283. Slider::textBoxTextColourId, 0xff000000,
  51284. Slider::textBoxBackgroundColourId, 0xffffffff,
  51285. Slider::textBoxHighlightColourId, textHighlightColour,
  51286. Slider::textBoxOutlineColourId, standardOutlineColour,
  51287. ResizableWindow::backgroundColourId, 0xff777777,
  51288. //DocumentWindow::textColourId, 0xff000000, // (this is deliberately not set)
  51289. AlertWindow::backgroundColourId, 0xffededed,
  51290. AlertWindow::textColourId, 0xff000000,
  51291. AlertWindow::outlineColourId, 0xff666666,
  51292. ProgressBar::backgroundColourId, 0xffeeeeee,
  51293. ProgressBar::foregroundColourId, 0xffaaaaee,
  51294. TooltipWindow::backgroundColourId, 0xffeeeebb,
  51295. TooltipWindow::textColourId, 0xff000000,
  51296. TooltipWindow::outlineColourId, 0x4c000000,
  51297. TabbedComponent::backgroundColourId, 0x00000000,
  51298. TabbedComponent::outlineColourId, 0xff777777,
  51299. TabbedButtonBar::tabOutlineColourId, 0x80000000,
  51300. TabbedButtonBar::frontOutlineColourId, 0x90000000,
  51301. Toolbar::backgroundColourId, 0xfff6f8f9,
  51302. Toolbar::separatorColourId, 0x4c000000,
  51303. Toolbar::buttonMouseOverBackgroundColourId, 0x4c0000ff,
  51304. Toolbar::buttonMouseDownBackgroundColourId, 0x800000ff,
  51305. Toolbar::labelTextColourId, 0xff000000,
  51306. Toolbar::editingModeOutlineColourId, 0xffff0000,
  51307. HyperlinkButton::textColourId, 0xcc1111ee,
  51308. GroupComponent::outlineColourId, 0x66000000,
  51309. GroupComponent::textColourId, 0xff000000,
  51310. DirectoryContentsDisplayComponent::highlightColourId, textHighlightColour,
  51311. DirectoryContentsDisplayComponent::textColourId, 0xff000000,
  51312. 0x1000440, /*LassoComponent::lassoFillColourId*/ 0x66dddddd,
  51313. 0x1000441, /*LassoComponent::lassoOutlineColourId*/ 0x99111111,
  51314. MidiKeyboardComponent::whiteNoteColourId, 0xffffffff,
  51315. MidiKeyboardComponent::blackNoteColourId, 0xff000000,
  51316. MidiKeyboardComponent::keySeparatorLineColourId, 0x66000000,
  51317. MidiKeyboardComponent::mouseOverKeyOverlayColourId, 0x80ffff00,
  51318. MidiKeyboardComponent::keyDownOverlayColourId, 0xffb6b600,
  51319. MidiKeyboardComponent::textLabelColourId, 0xff000000,
  51320. MidiKeyboardComponent::upDownButtonBackgroundColourId, 0xffd3d3d3,
  51321. MidiKeyboardComponent::upDownButtonArrowColourId, 0xff000000,
  51322. CodeEditorComponent::backgroundColourId, 0xffffffff,
  51323. CodeEditorComponent::caretColourId, 0xff000000,
  51324. CodeEditorComponent::highlightColourId, textHighlightColour,
  51325. CodeEditorComponent::defaultTextColourId, 0xff000000,
  51326. ColourSelector::backgroundColourId, 0xffe5e5e5,
  51327. ColourSelector::labelTextColourId, 0xff000000,
  51328. KeyMappingEditorComponent::backgroundColourId, 0x00000000,
  51329. KeyMappingEditorComponent::textColourId, 0xff000000,
  51330. FileSearchPathListComponent::backgroundColourId, 0xffffffff,
  51331. FileChooserDialogBox::titleTextColourId, 0xff000000,
  51332. };
  51333. for (int i = 0; i < numElementsInArray (standardColours); i += 2)
  51334. setColour (standardColours [i], Colour (standardColours [i + 1]));
  51335. static String defaultSansName, defaultSerifName, defaultFixedName;
  51336. if (defaultSansName.isEmpty())
  51337. Font::getPlatformDefaultFontNames (defaultSansName, defaultSerifName, defaultFixedName);
  51338. defaultSans = defaultSansName;
  51339. defaultSerif = defaultSerifName;
  51340. defaultFixed = defaultFixedName;
  51341. }
  51342. LookAndFeel::~LookAndFeel()
  51343. {
  51344. }
  51345. const Colour LookAndFeel::findColour (const int colourId) const throw()
  51346. {
  51347. const int index = colourIds.indexOf (colourId);
  51348. if (index >= 0)
  51349. return colours [index];
  51350. jassertfalse
  51351. return Colours::black;
  51352. }
  51353. void LookAndFeel::setColour (const int colourId, const Colour& colour) throw()
  51354. {
  51355. const int index = colourIds.indexOf (colourId);
  51356. if (index >= 0)
  51357. colours.set (index, colour);
  51358. colourIds.add (colourId);
  51359. colours.add (colour);
  51360. }
  51361. bool LookAndFeel::isColourSpecified (const int colourId) const throw()
  51362. {
  51363. return colourIds.contains (colourId);
  51364. }
  51365. static LookAndFeel* defaultLF = 0;
  51366. static LookAndFeel* currentDefaultLF = 0;
  51367. LookAndFeel& LookAndFeel::getDefaultLookAndFeel() throw()
  51368. {
  51369. // if this happens, your app hasn't initialised itself properly.. if you're
  51370. // trying to hack your own main() function, have a look at
  51371. // JUCEApplication::initialiseForGUI()
  51372. jassert (currentDefaultLF != 0);
  51373. return *currentDefaultLF;
  51374. }
  51375. void LookAndFeel::setDefaultLookAndFeel (LookAndFeel* newDefaultLookAndFeel) throw()
  51376. {
  51377. if (newDefaultLookAndFeel == 0)
  51378. {
  51379. if (defaultLF == 0)
  51380. defaultLF = new LookAndFeel();
  51381. newDefaultLookAndFeel = defaultLF;
  51382. }
  51383. currentDefaultLF = newDefaultLookAndFeel;
  51384. for (int i = Desktop::getInstance().getNumComponents(); --i >= 0;)
  51385. {
  51386. Component* const c = Desktop::getInstance().getComponent (i);
  51387. if (c != 0)
  51388. c->sendLookAndFeelChange();
  51389. }
  51390. }
  51391. void LookAndFeel::clearDefaultLookAndFeel() throw()
  51392. {
  51393. if (currentDefaultLF == defaultLF)
  51394. currentDefaultLF = 0;
  51395. deleteAndZero (defaultLF);
  51396. }
  51397. const Typeface::Ptr LookAndFeel::getTypefaceForFont (const Font& font)
  51398. {
  51399. String faceName (font.getTypefaceName());
  51400. if (faceName == Font::getDefaultSansSerifFontName())
  51401. faceName = defaultSans;
  51402. else if (faceName == Font::getDefaultSerifFontName())
  51403. faceName = defaultSerif;
  51404. else if (faceName == Font::getDefaultMonospacedFontName())
  51405. faceName = defaultFixed;
  51406. Font f (font);
  51407. f.setTypefaceName (faceName);
  51408. return Typeface::createSystemTypefaceFor (f);
  51409. }
  51410. void LookAndFeel::setDefaultSansSerifTypefaceName (const String& newName)
  51411. {
  51412. defaultSans = newName;
  51413. }
  51414. const MouseCursor LookAndFeel::getMouseCursorFor (Component& component)
  51415. {
  51416. return component.getMouseCursor();
  51417. }
  51418. void LookAndFeel::drawButtonBackground (Graphics& g,
  51419. Button& button,
  51420. const Colour& backgroundColour,
  51421. bool isMouseOverButton,
  51422. bool isButtonDown)
  51423. {
  51424. const int width = button.getWidth();
  51425. const int height = button.getHeight();
  51426. const float outlineThickness = button.isEnabled() ? ((isButtonDown || isMouseOverButton) ? 1.2f : 0.7f) : 0.4f;
  51427. const float halfThickness = outlineThickness * 0.5f;
  51428. const float indentL = button.isConnectedOnLeft() ? 0.1f : halfThickness;
  51429. const float indentR = button.isConnectedOnRight() ? 0.1f : halfThickness;
  51430. const float indentT = button.isConnectedOnTop() ? 0.1f : halfThickness;
  51431. const float indentB = button.isConnectedOnBottom() ? 0.1f : halfThickness;
  51432. const Colour baseColour (createBaseColour (backgroundColour,
  51433. button.hasKeyboardFocus (true),
  51434. isMouseOverButton, isButtonDown)
  51435. .withMultipliedAlpha (button.isEnabled() ? 1.0f : 0.5f));
  51436. drawGlassLozenge (g,
  51437. indentL,
  51438. indentT,
  51439. width - indentL - indentR,
  51440. height - indentT - indentB,
  51441. baseColour, outlineThickness, -1.0f,
  51442. button.isConnectedOnLeft(),
  51443. button.isConnectedOnRight(),
  51444. button.isConnectedOnTop(),
  51445. button.isConnectedOnBottom());
  51446. }
  51447. const Font LookAndFeel::getFontForTextButton (TextButton& button)
  51448. {
  51449. return button.getFont();
  51450. }
  51451. void LookAndFeel::drawButtonText (Graphics& g, TextButton& button,
  51452. bool /*isMouseOverButton*/, bool /*isButtonDown*/)
  51453. {
  51454. Font font (getFontForTextButton (button));
  51455. g.setFont (font);
  51456. g.setColour (button.findColour (button.getToggleState() ? TextButton::textColourOnId
  51457. : TextButton::textColourOffId)
  51458. .withMultipliedAlpha (button.isEnabled() ? 1.0f : 0.5f));
  51459. const int yIndent = jmin (4, button.proportionOfHeight (0.3f));
  51460. const int cornerSize = jmin (button.getHeight(), button.getWidth()) / 2;
  51461. const int fontHeight = roundToInt (font.getHeight() * 0.6f);
  51462. const int leftIndent = jmin (fontHeight, 2 + cornerSize / (button.isConnectedOnLeft() ? 4 : 2));
  51463. const int rightIndent = jmin (fontHeight, 2 + cornerSize / (button.isConnectedOnRight() ? 4 : 2));
  51464. g.drawFittedText (button.getButtonText(),
  51465. leftIndent,
  51466. yIndent,
  51467. button.getWidth() - leftIndent - rightIndent,
  51468. button.getHeight() - yIndent * 2,
  51469. Justification::centred, 2);
  51470. }
  51471. void LookAndFeel::drawTickBox (Graphics& g,
  51472. Component& component,
  51473. float x, float y, float w, float h,
  51474. const bool ticked,
  51475. const bool isEnabled,
  51476. const bool isMouseOverButton,
  51477. const bool isButtonDown)
  51478. {
  51479. const float boxSize = w * 0.7f;
  51480. drawGlassSphere (g, x, y + (h - boxSize) * 0.5f, boxSize,
  51481. createBaseColour (component.findColour (TextButton::buttonColourId)
  51482. .withMultipliedAlpha (isEnabled ? 1.0f : 0.5f),
  51483. true,
  51484. isMouseOverButton,
  51485. isButtonDown),
  51486. isEnabled ? ((isButtonDown || isMouseOverButton) ? 1.1f : 0.5f) : 0.3f);
  51487. if (ticked)
  51488. {
  51489. Path tick;
  51490. tick.startNewSubPath (1.5f, 3.0f);
  51491. tick.lineTo (3.0f, 6.0f);
  51492. tick.lineTo (6.0f, 0.0f);
  51493. g.setColour (isEnabled ? Colours::black : Colours::grey);
  51494. const AffineTransform trans (AffineTransform::scale (w / 9.0f, h / 9.0f)
  51495. .translated (x, y));
  51496. g.strokePath (tick, PathStrokeType (2.5f), trans);
  51497. }
  51498. }
  51499. void LookAndFeel::drawToggleButton (Graphics& g,
  51500. ToggleButton& button,
  51501. bool isMouseOverButton,
  51502. bool isButtonDown)
  51503. {
  51504. if (button.hasKeyboardFocus (true))
  51505. {
  51506. g.setColour (button.findColour (TextEditor::focusedOutlineColourId));
  51507. g.drawRect (0, 0, button.getWidth(), button.getHeight());
  51508. }
  51509. float fontSize = jmin (15.0f, button.getHeight() * 0.75f);
  51510. const float tickWidth = fontSize * 1.1f;
  51511. drawTickBox (g, button, 4.0f, (button.getHeight() - tickWidth) * 0.5f,
  51512. tickWidth, tickWidth,
  51513. button.getToggleState(),
  51514. button.isEnabled(),
  51515. isMouseOverButton,
  51516. isButtonDown);
  51517. g.setColour (button.findColour (ToggleButton::textColourId));
  51518. g.setFont (fontSize);
  51519. if (! button.isEnabled())
  51520. g.setOpacity (0.5f);
  51521. const int textX = (int) tickWidth + 5;
  51522. g.drawFittedText (button.getButtonText(),
  51523. textX, 0,
  51524. button.getWidth() - textX - 2, button.getHeight(),
  51525. Justification::centredLeft, 10);
  51526. }
  51527. void LookAndFeel::changeToggleButtonWidthToFitText (ToggleButton& button)
  51528. {
  51529. Font font (jmin (15.0f, button.getHeight() * 0.6f));
  51530. const int tickWidth = jmin (24, button.getHeight());
  51531. button.setSize (font.getStringWidth (button.getButtonText()) + tickWidth + 8,
  51532. button.getHeight());
  51533. }
  51534. AlertWindow* LookAndFeel::createAlertWindow (const String& title,
  51535. const String& message,
  51536. const String& button1,
  51537. const String& button2,
  51538. const String& button3,
  51539. AlertWindow::AlertIconType iconType,
  51540. int numButtons,
  51541. Component* associatedComponent)
  51542. {
  51543. AlertWindow* aw = new AlertWindow (title, message, iconType, associatedComponent);
  51544. if (numButtons == 1)
  51545. {
  51546. aw->addButton (button1, 0,
  51547. KeyPress (KeyPress::escapeKey, 0, 0),
  51548. KeyPress (KeyPress::returnKey, 0, 0));
  51549. }
  51550. else
  51551. {
  51552. const KeyPress button1ShortCut (CharacterFunctions::toLowerCase (button1[0]), 0, 0);
  51553. KeyPress button2ShortCut (CharacterFunctions::toLowerCase (button2[0]), 0, 0);
  51554. if (button1ShortCut == button2ShortCut)
  51555. button2ShortCut = KeyPress();
  51556. if (numButtons == 2)
  51557. {
  51558. aw->addButton (button1, 1, KeyPress (KeyPress::returnKey, 0, 0), button1ShortCut);
  51559. aw->addButton (button2, 0, KeyPress (KeyPress::escapeKey, 0, 0), button2ShortCut);
  51560. }
  51561. else if (numButtons == 3)
  51562. {
  51563. aw->addButton (button1, 1, button1ShortCut);
  51564. aw->addButton (button2, 2, button2ShortCut);
  51565. aw->addButton (button3, 0, KeyPress (KeyPress::escapeKey, 0, 0));
  51566. }
  51567. }
  51568. return aw;
  51569. }
  51570. void LookAndFeel::drawAlertBox (Graphics& g,
  51571. AlertWindow& alert,
  51572. const Rectangle<int>& textArea,
  51573. TextLayout& textLayout)
  51574. {
  51575. g.fillAll (alert.findColour (AlertWindow::backgroundColourId));
  51576. int iconSpaceUsed = 0;
  51577. Justification alignment (Justification::horizontallyCentred);
  51578. const int iconWidth = 80;
  51579. int iconSize = jmin (iconWidth + 50, alert.getHeight() + 20);
  51580. if (alert.containsAnyExtraComponents() || alert.getNumButtons() > 2)
  51581. iconSize = jmin (iconSize, textArea.getHeight() + 50);
  51582. const Rectangle<int> iconRect (iconSize / -10, iconSize / -10,
  51583. iconSize, iconSize);
  51584. if (alert.getAlertType() != AlertWindow::NoIcon)
  51585. {
  51586. Path icon;
  51587. uint32 colour;
  51588. char character;
  51589. if (alert.getAlertType() == AlertWindow::WarningIcon)
  51590. {
  51591. colour = 0x55ff5555;
  51592. character = '!';
  51593. icon.addTriangle (iconRect.getX() + iconRect.getWidth() * 0.5f, (float) iconRect.getY(),
  51594. (float) iconRect.getRight(), (float) iconRect.getBottom(),
  51595. (float) iconRect.getX(), (float) iconRect.getBottom());
  51596. icon = icon.createPathWithRoundedCorners (5.0f);
  51597. }
  51598. else
  51599. {
  51600. colour = alert.getAlertType() == AlertWindow::InfoIcon ? 0x605555ff : 0x40b69900;
  51601. character = alert.getAlertType() == AlertWindow::InfoIcon ? 'i' : '?';
  51602. icon.addEllipse ((float) iconRect.getX(), (float) iconRect.getY(),
  51603. (float) iconRect.getWidth(), (float) iconRect.getHeight());
  51604. }
  51605. GlyphArrangement ga;
  51606. ga.addFittedText (Font (iconRect.getHeight() * 0.9f, Font::bold),
  51607. String::charToString (character),
  51608. (float) iconRect.getX(), (float) iconRect.getY(),
  51609. (float) iconRect.getWidth(), (float) iconRect.getHeight(),
  51610. Justification::centred, false);
  51611. ga.createPath (icon);
  51612. icon.setUsingNonZeroWinding (false);
  51613. g.setColour (Colour (colour));
  51614. g.fillPath (icon);
  51615. iconSpaceUsed = iconWidth;
  51616. alignment = Justification::left;
  51617. }
  51618. g.setColour (alert.findColour (AlertWindow::textColourId));
  51619. textLayout.drawWithin (g,
  51620. textArea.getX() + iconSpaceUsed, textArea.getY(),
  51621. textArea.getWidth() - iconSpaceUsed, textArea.getHeight(),
  51622. alignment.getFlags() | Justification::top);
  51623. g.setColour (alert.findColour (AlertWindow::outlineColourId));
  51624. g.drawRect (0, 0, alert.getWidth(), alert.getHeight());
  51625. }
  51626. int LookAndFeel::getAlertBoxWindowFlags()
  51627. {
  51628. return ComponentPeer::windowAppearsOnTaskbar
  51629. | ComponentPeer::windowHasDropShadow;
  51630. }
  51631. int LookAndFeel::getAlertWindowButtonHeight()
  51632. {
  51633. return 28;
  51634. }
  51635. const Font LookAndFeel::getAlertWindowFont()
  51636. {
  51637. return Font (12.0f);
  51638. }
  51639. void LookAndFeel::drawProgressBar (Graphics& g, ProgressBar& progressBar,
  51640. int width, int height,
  51641. double progress, const String& textToShow)
  51642. {
  51643. const Colour background (progressBar.findColour (ProgressBar::backgroundColourId));
  51644. const Colour foreground (progressBar.findColour (ProgressBar::foregroundColourId));
  51645. g.fillAll (background);
  51646. if (progress >= 0.0f && progress < 1.0f)
  51647. {
  51648. drawGlassLozenge (g, 1.0f, 1.0f,
  51649. (float) jlimit (0.0, width - 2.0, progress * (width - 2.0)),
  51650. (float) (height - 2),
  51651. foreground,
  51652. 0.5f, 0.0f,
  51653. true, true, true, true);
  51654. }
  51655. else
  51656. {
  51657. // spinning bar..
  51658. g.setColour (foreground);
  51659. const int stripeWidth = height * 2;
  51660. const int position = (Time::getMillisecondCounter() / 15) % stripeWidth;
  51661. Path p;
  51662. for (float x = (float) (- position); x < width + stripeWidth; x += stripeWidth)
  51663. p.addQuadrilateral (x, 0.0f,
  51664. x + stripeWidth * 0.5f, 0.0f,
  51665. x, (float) height,
  51666. x - stripeWidth * 0.5f, (float) height);
  51667. Image im (Image::ARGB, width, height, true);
  51668. {
  51669. Graphics g2 (im);
  51670. drawGlassLozenge (g2, 1.0f, 1.0f,
  51671. (float) (width - 2),
  51672. (float) (height - 2),
  51673. foreground,
  51674. 0.5f, 0.0f,
  51675. true, true, true, true);
  51676. }
  51677. g.setTiledImageFill (im, 0, 0, 0.85f);
  51678. g.fillPath (p);
  51679. }
  51680. if (textToShow.isNotEmpty())
  51681. {
  51682. g.setColour (Colour::contrasting (background, foreground));
  51683. g.setFont (height * 0.6f);
  51684. g.drawText (textToShow, 0, 0, width, height, Justification::centred, false);
  51685. }
  51686. }
  51687. void LookAndFeel::drawSpinningWaitAnimation (Graphics& g, const Colour& colour, int x, int y, int w, int h)
  51688. {
  51689. const float radius = jmin (w, h) * 0.4f;
  51690. const float thickness = radius * 0.15f;
  51691. Path p;
  51692. p.addRoundedRectangle (radius * 0.4f, thickness * -0.5f,
  51693. radius * 0.6f, thickness,
  51694. thickness * 0.5f);
  51695. const float cx = x + w * 0.5f;
  51696. const float cy = y + h * 0.5f;
  51697. const uint32 animationIndex = (Time::getMillisecondCounter() / (1000 / 10)) % 12;
  51698. for (int i = 0; i < 12; ++i)
  51699. {
  51700. const int n = (i + 12 - animationIndex) % 12;
  51701. g.setColour (colour.withMultipliedAlpha ((n + 1) / 12.0f));
  51702. g.fillPath (p, AffineTransform::rotation (i * (float_Pi / 6.0f))
  51703. .translated (cx, cy));
  51704. }
  51705. }
  51706. void LookAndFeel::drawScrollbarButton (Graphics& g,
  51707. ScrollBar& scrollbar,
  51708. int width, int height,
  51709. int buttonDirection,
  51710. bool /*isScrollbarVertical*/,
  51711. bool /*isMouseOverButton*/,
  51712. bool isButtonDown)
  51713. {
  51714. Path p;
  51715. if (buttonDirection == 0)
  51716. p.addTriangle (width * 0.5f, height * 0.2f,
  51717. width * 0.1f, height * 0.7f,
  51718. width * 0.9f, height * 0.7f);
  51719. else if (buttonDirection == 1)
  51720. p.addTriangle (width * 0.8f, height * 0.5f,
  51721. width * 0.3f, height * 0.1f,
  51722. width * 0.3f, height * 0.9f);
  51723. else if (buttonDirection == 2)
  51724. p.addTriangle (width * 0.5f, height * 0.8f,
  51725. width * 0.1f, height * 0.3f,
  51726. width * 0.9f, height * 0.3f);
  51727. else if (buttonDirection == 3)
  51728. p.addTriangle (width * 0.2f, height * 0.5f,
  51729. width * 0.7f, height * 0.1f,
  51730. width * 0.7f, height * 0.9f);
  51731. if (isButtonDown)
  51732. g.setColour (scrollbar.findColour (ScrollBar::thumbColourId).contrasting (0.2f));
  51733. else
  51734. g.setColour (scrollbar.findColour (ScrollBar::thumbColourId));
  51735. g.fillPath (p);
  51736. g.setColour (Colour (0x80000000));
  51737. g.strokePath (p, PathStrokeType (0.5f));
  51738. }
  51739. void LookAndFeel::drawScrollbar (Graphics& g,
  51740. ScrollBar& scrollbar,
  51741. int x, int y,
  51742. int width, int height,
  51743. bool isScrollbarVertical,
  51744. int thumbStartPosition,
  51745. int thumbSize,
  51746. bool /*isMouseOver*/,
  51747. bool /*isMouseDown*/)
  51748. {
  51749. g.fillAll (scrollbar.findColour (ScrollBar::backgroundColourId));
  51750. Path slotPath, thumbPath;
  51751. const float slotIndent = jmin (width, height) > 15 ? 1.0f : 0.0f;
  51752. const float slotIndentx2 = slotIndent * 2.0f;
  51753. const float thumbIndent = slotIndent + 1.0f;
  51754. const float thumbIndentx2 = thumbIndent * 2.0f;
  51755. float gx1 = 0.0f, gy1 = 0.0f, gx2 = 0.0f, gy2 = 0.0f;
  51756. if (isScrollbarVertical)
  51757. {
  51758. slotPath.addRoundedRectangle (x + slotIndent,
  51759. y + slotIndent,
  51760. width - slotIndentx2,
  51761. height - slotIndentx2,
  51762. (width - slotIndentx2) * 0.5f);
  51763. if (thumbSize > 0)
  51764. thumbPath.addRoundedRectangle (x + thumbIndent,
  51765. thumbStartPosition + thumbIndent,
  51766. width - thumbIndentx2,
  51767. thumbSize - thumbIndentx2,
  51768. (width - thumbIndentx2) * 0.5f);
  51769. gx1 = (float) x;
  51770. gx2 = x + width * 0.7f;
  51771. }
  51772. else
  51773. {
  51774. slotPath.addRoundedRectangle (x + slotIndent,
  51775. y + slotIndent,
  51776. width - slotIndentx2,
  51777. height - slotIndentx2,
  51778. (height - slotIndentx2) * 0.5f);
  51779. if (thumbSize > 0)
  51780. thumbPath.addRoundedRectangle (thumbStartPosition + thumbIndent,
  51781. y + thumbIndent,
  51782. thumbSize - thumbIndentx2,
  51783. height - thumbIndentx2,
  51784. (height - thumbIndentx2) * 0.5f);
  51785. gy1 = (float) y;
  51786. gy2 = y + height * 0.7f;
  51787. }
  51788. const Colour thumbColour (scrollbar.findColour (ScrollBar::thumbColourId));
  51789. g.setGradientFill (ColourGradient (thumbColour.overlaidWith (Colour (0x44000000)), gx1, gy1,
  51790. thumbColour.overlaidWith (Colour (0x19000000)), gx2, gy2, false));
  51791. g.fillPath (slotPath);
  51792. if (isScrollbarVertical)
  51793. {
  51794. gx1 = x + width * 0.6f;
  51795. gx2 = (float) x + width;
  51796. }
  51797. else
  51798. {
  51799. gy1 = y + height * 0.6f;
  51800. gy2 = (float) y + height;
  51801. }
  51802. g.setGradientFill (ColourGradient (Colours::transparentBlack,gx1, gy1,
  51803. Colour (0x19000000), gx2, gy2, false));
  51804. g.fillPath (slotPath);
  51805. g.setColour (thumbColour);
  51806. g.fillPath (thumbPath);
  51807. g.setGradientFill (ColourGradient (Colour (0x10000000), gx1, gy1,
  51808. Colours::transparentBlack, gx2, gy2, false));
  51809. g.saveState();
  51810. if (isScrollbarVertical)
  51811. g.reduceClipRegion (x + width / 2, y, width, height);
  51812. else
  51813. g.reduceClipRegion (x, y + height / 2, width, height);
  51814. g.fillPath (thumbPath);
  51815. g.restoreState();
  51816. g.setColour (Colour (0x4c000000));
  51817. g.strokePath (thumbPath, PathStrokeType (0.4f));
  51818. }
  51819. ImageEffectFilter* LookAndFeel::getScrollbarEffect()
  51820. {
  51821. return 0;
  51822. }
  51823. int LookAndFeel::getMinimumScrollbarThumbSize (ScrollBar& scrollbar)
  51824. {
  51825. return jmin (scrollbar.getWidth(), scrollbar.getHeight()) * 2;
  51826. }
  51827. int LookAndFeel::getDefaultScrollbarWidth()
  51828. {
  51829. return 18;
  51830. }
  51831. int LookAndFeel::getScrollbarButtonSize (ScrollBar& scrollbar)
  51832. {
  51833. return 2 + (scrollbar.isVertical() ? scrollbar.getWidth()
  51834. : scrollbar.getHeight());
  51835. }
  51836. const Path LookAndFeel::getTickShape (const float height)
  51837. {
  51838. static const unsigned char tickShapeData[] =
  51839. {
  51840. 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,
  51841. 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,
  51842. 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,
  51843. 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,
  51844. 96,140,68,0,128,188,67,0,224,168,68,0,0,119,67,99,101
  51845. };
  51846. Path p;
  51847. p.loadPathFromData (tickShapeData, sizeof (tickShapeData));
  51848. p.scaleToFit (0, 0, height * 2.0f, height, true);
  51849. return p;
  51850. }
  51851. const Path LookAndFeel::getCrossShape (const float height)
  51852. {
  51853. static const unsigned char crossShapeData[] =
  51854. {
  51855. 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,
  51856. 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,
  51857. 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,
  51858. 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,
  51859. 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,
  51860. 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,
  51861. 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
  51862. };
  51863. Path p;
  51864. p.loadPathFromData (crossShapeData, sizeof (crossShapeData));
  51865. p.scaleToFit (0, 0, height * 2.0f, height, true);
  51866. return p;
  51867. }
  51868. void LookAndFeel::drawTreeviewPlusMinusBox (Graphics& g, int x, int y, int w, int h, bool isPlus, bool /*isMouseOver*/)
  51869. {
  51870. const int boxSize = ((jmin (16, w, h) << 1) / 3) | 1;
  51871. x += (w - boxSize) >> 1;
  51872. y += (h - boxSize) >> 1;
  51873. w = boxSize;
  51874. h = boxSize;
  51875. g.setColour (Colour (0xe5ffffff));
  51876. g.fillRect (x, y, w, h);
  51877. g.setColour (Colour (0x80000000));
  51878. g.drawRect (x, y, w, h);
  51879. const float size = boxSize / 2 + 1.0f;
  51880. const float centre = (float) (boxSize / 2);
  51881. g.fillRect (x + (w - size) * 0.5f, y + centre, size, 1.0f);
  51882. if (isPlus)
  51883. g.fillRect (x + centre, y + (h - size) * 0.5f, 1.0f, size);
  51884. }
  51885. void LookAndFeel::drawBubble (Graphics& g,
  51886. float tipX, float tipY,
  51887. float boxX, float boxY,
  51888. float boxW, float boxH)
  51889. {
  51890. int side = 0;
  51891. if (tipX < boxX)
  51892. side = 1;
  51893. else if (tipX > boxX + boxW)
  51894. side = 3;
  51895. else if (tipY > boxY + boxH)
  51896. side = 2;
  51897. const float indent = 2.0f;
  51898. Path p;
  51899. p.addBubble (boxX + indent,
  51900. boxY + indent,
  51901. boxW - indent * 2.0f,
  51902. boxH - indent * 2.0f,
  51903. 5.0f,
  51904. tipX, tipY,
  51905. side,
  51906. 0.5f,
  51907. jmin (15.0f, boxW * 0.3f, boxH * 0.3f));
  51908. //xxx need to take comp as param for colour
  51909. g.setColour (findColour (TooltipWindow::backgroundColourId).withAlpha (0.9f));
  51910. g.fillPath (p);
  51911. //xxx as above
  51912. g.setColour (findColour (TooltipWindow::textColourId).withAlpha (0.4f));
  51913. g.strokePath (p, PathStrokeType (1.33f));
  51914. }
  51915. const Font LookAndFeel::getPopupMenuFont()
  51916. {
  51917. return Font (17.0f);
  51918. }
  51919. void LookAndFeel::getIdealPopupMenuItemSize (const String& text,
  51920. const bool isSeparator,
  51921. int standardMenuItemHeight,
  51922. int& idealWidth,
  51923. int& idealHeight)
  51924. {
  51925. if (isSeparator)
  51926. {
  51927. idealWidth = 50;
  51928. idealHeight = standardMenuItemHeight > 0 ? standardMenuItemHeight / 2 : 10;
  51929. }
  51930. else
  51931. {
  51932. Font font (getPopupMenuFont());
  51933. if (standardMenuItemHeight > 0 && font.getHeight() > standardMenuItemHeight / 1.3f)
  51934. font.setHeight (standardMenuItemHeight / 1.3f);
  51935. idealHeight = standardMenuItemHeight > 0 ? standardMenuItemHeight : roundToInt (font.getHeight() * 1.3f);
  51936. idealWidth = font.getStringWidth (text) + idealHeight * 2;
  51937. }
  51938. }
  51939. void LookAndFeel::drawPopupMenuBackground (Graphics& g, int width, int height)
  51940. {
  51941. const Colour background (findColour (PopupMenu::backgroundColourId));
  51942. g.fillAll (background);
  51943. g.setColour (background.overlaidWith (Colour (0x2badd8e6)));
  51944. for (int i = 0; i < height; i += 3)
  51945. g.fillRect (0, i, width, 1);
  51946. #if ! JUCE_MAC
  51947. g.setColour (findColour (PopupMenu::textColourId).withAlpha (0.6f));
  51948. g.drawRect (0, 0, width, height);
  51949. #endif
  51950. }
  51951. void LookAndFeel::drawPopupMenuUpDownArrow (Graphics& g,
  51952. int width, int height,
  51953. bool isScrollUpArrow)
  51954. {
  51955. const Colour background (findColour (PopupMenu::backgroundColourId));
  51956. g.setGradientFill (ColourGradient (background, 0.0f, height * 0.5f,
  51957. background.withAlpha (0.0f),
  51958. 0.0f, isScrollUpArrow ? ((float) height) : 0.0f,
  51959. false));
  51960. g.fillRect (1, 1, width - 2, height - 2);
  51961. const float hw = width * 0.5f;
  51962. const float arrowW = height * 0.3f;
  51963. const float y1 = height * (isScrollUpArrow ? 0.6f : 0.3f);
  51964. const float y2 = height * (isScrollUpArrow ? 0.3f : 0.6f);
  51965. Path p;
  51966. p.addTriangle (hw - arrowW, y1,
  51967. hw + arrowW, y1,
  51968. hw, y2);
  51969. g.setColour (findColour (PopupMenu::textColourId).withAlpha (0.5f));
  51970. g.fillPath (p);
  51971. }
  51972. void LookAndFeel::drawPopupMenuItem (Graphics& g,
  51973. int width, int height,
  51974. const bool isSeparator,
  51975. const bool isActive,
  51976. const bool isHighlighted,
  51977. const bool isTicked,
  51978. const bool hasSubMenu,
  51979. const String& text,
  51980. const String& shortcutKeyText,
  51981. Image* image,
  51982. const Colour* const textColourToUse)
  51983. {
  51984. const float halfH = height * 0.5f;
  51985. if (isSeparator)
  51986. {
  51987. const float separatorIndent = 5.5f;
  51988. g.setColour (Colour (0x33000000));
  51989. g.drawLine (separatorIndent, halfH, width - separatorIndent, halfH);
  51990. g.setColour (Colour (0x66ffffff));
  51991. g.drawLine (separatorIndent, halfH + 1.0f, width - separatorIndent, halfH + 1.0f);
  51992. }
  51993. else
  51994. {
  51995. Colour textColour (findColour (PopupMenu::textColourId));
  51996. if (textColourToUse != 0)
  51997. textColour = *textColourToUse;
  51998. if (isHighlighted)
  51999. {
  52000. g.setColour (findColour (PopupMenu::highlightedBackgroundColourId));
  52001. g.fillRect (1, 1, width - 2, height - 2);
  52002. g.setColour (findColour (PopupMenu::highlightedTextColourId));
  52003. }
  52004. else
  52005. {
  52006. g.setColour (textColour);
  52007. }
  52008. if (! isActive)
  52009. g.setOpacity (0.3f);
  52010. Font font (getPopupMenuFont());
  52011. if (font.getHeight() > height / 1.3f)
  52012. font.setHeight (height / 1.3f);
  52013. g.setFont (font);
  52014. const int leftBorder = (height * 5) / 4;
  52015. const int rightBorder = 4;
  52016. if (image != 0)
  52017. {
  52018. g.drawImageWithin (image,
  52019. 2, 1, leftBorder - 4, height - 2,
  52020. RectanglePlacement::centred | RectanglePlacement::onlyReduceInSize, false);
  52021. }
  52022. else if (isTicked)
  52023. {
  52024. const Path tick (getTickShape (1.0f));
  52025. const float th = font.getAscent();
  52026. const float ty = halfH - th * 0.5f;
  52027. g.fillPath (tick, tick.getTransformToScaleToFit (2.0f, ty, (float) (leftBorder - 4),
  52028. th, true));
  52029. }
  52030. g.drawFittedText (text,
  52031. leftBorder, 0,
  52032. width - (leftBorder + rightBorder), height,
  52033. Justification::centredLeft, 1);
  52034. if (shortcutKeyText.isNotEmpty())
  52035. {
  52036. Font f2 (font);
  52037. f2.setHeight (f2.getHeight() * 0.75f);
  52038. f2.setHorizontalScale (0.95f);
  52039. g.setFont (f2);
  52040. g.drawText (shortcutKeyText,
  52041. leftBorder,
  52042. 0,
  52043. width - (leftBorder + rightBorder + 4),
  52044. height,
  52045. Justification::centredRight,
  52046. true);
  52047. }
  52048. if (hasSubMenu)
  52049. {
  52050. const float arrowH = 0.6f * getPopupMenuFont().getAscent();
  52051. const float x = width - height * 0.6f;
  52052. Path p;
  52053. p.addTriangle (x, halfH - arrowH * 0.5f,
  52054. x, halfH + arrowH * 0.5f,
  52055. x + arrowH * 0.6f, halfH);
  52056. g.fillPath (p);
  52057. }
  52058. }
  52059. }
  52060. int LookAndFeel::getMenuWindowFlags()
  52061. {
  52062. return ComponentPeer::windowHasDropShadow;
  52063. }
  52064. void LookAndFeel::drawMenuBarBackground (Graphics& g, int width, int height,
  52065. bool, MenuBarComponent& menuBar)
  52066. {
  52067. const Colour baseColour (createBaseColour (menuBar.findColour (PopupMenu::backgroundColourId), false, false, false));
  52068. if (menuBar.isEnabled())
  52069. {
  52070. drawShinyButtonShape (g,
  52071. -4.0f, 0.0f,
  52072. width + 8.0f, (float) height,
  52073. 0.0f,
  52074. baseColour,
  52075. 0.4f,
  52076. true, true, true, true);
  52077. }
  52078. else
  52079. {
  52080. g.fillAll (baseColour);
  52081. }
  52082. }
  52083. const Font LookAndFeel::getMenuBarFont (MenuBarComponent& menuBar, int /*itemIndex*/, const String& /*itemText*/)
  52084. {
  52085. return Font (menuBar.getHeight() * 0.7f);
  52086. }
  52087. int LookAndFeel::getMenuBarItemWidth (MenuBarComponent& menuBar, int itemIndex, const String& itemText)
  52088. {
  52089. return getMenuBarFont (menuBar, itemIndex, itemText)
  52090. .getStringWidth (itemText) + menuBar.getHeight();
  52091. }
  52092. void LookAndFeel::drawMenuBarItem (Graphics& g,
  52093. int width, int height,
  52094. int itemIndex,
  52095. const String& itemText,
  52096. bool isMouseOverItem,
  52097. bool isMenuOpen,
  52098. bool /*isMouseOverBar*/,
  52099. MenuBarComponent& menuBar)
  52100. {
  52101. if (! menuBar.isEnabled())
  52102. {
  52103. g.setColour (menuBar.findColour (PopupMenu::textColourId)
  52104. .withMultipliedAlpha (0.5f));
  52105. }
  52106. else if (isMenuOpen || isMouseOverItem)
  52107. {
  52108. g.fillAll (menuBar.findColour (PopupMenu::highlightedBackgroundColourId));
  52109. g.setColour (menuBar.findColour (PopupMenu::highlightedTextColourId));
  52110. }
  52111. else
  52112. {
  52113. g.setColour (menuBar.findColour (PopupMenu::textColourId));
  52114. }
  52115. g.setFont (getMenuBarFont (menuBar, itemIndex, itemText));
  52116. g.drawFittedText (itemText, 0, 0, width, height, Justification::centred, 1);
  52117. }
  52118. void LookAndFeel::fillTextEditorBackground (Graphics& g, int /*width*/, int /*height*/,
  52119. TextEditor& textEditor)
  52120. {
  52121. g.fillAll (textEditor.findColour (TextEditor::backgroundColourId));
  52122. }
  52123. void LookAndFeel::drawTextEditorOutline (Graphics& g, int width, int height, TextEditor& textEditor)
  52124. {
  52125. if (textEditor.isEnabled())
  52126. {
  52127. if (textEditor.hasKeyboardFocus (true) && ! textEditor.isReadOnly())
  52128. {
  52129. const int border = 2;
  52130. g.setColour (textEditor.findColour (TextEditor::focusedOutlineColourId));
  52131. g.drawRect (0, 0, width, height, border);
  52132. g.setOpacity (1.0f);
  52133. const Colour shadowColour (textEditor.findColour (TextEditor::shadowColourId).withMultipliedAlpha (0.75f));
  52134. g.drawBevel (0, 0, width, height + 2, border + 2, shadowColour, shadowColour);
  52135. }
  52136. else
  52137. {
  52138. g.setColour (textEditor.findColour (TextEditor::outlineColourId));
  52139. g.drawRect (0, 0, width, height);
  52140. g.setOpacity (1.0f);
  52141. const Colour shadowColour (textEditor.findColour (TextEditor::shadowColourId));
  52142. g.drawBevel (0, 0, width, height + 2, 3, shadowColour, shadowColour);
  52143. }
  52144. }
  52145. }
  52146. void LookAndFeel::drawComboBox (Graphics& g, int width, int height,
  52147. const bool isButtonDown,
  52148. int buttonX, int buttonY,
  52149. int buttonW, int buttonH,
  52150. ComboBox& box)
  52151. {
  52152. g.fillAll (box.findColour (ComboBox::backgroundColourId));
  52153. if (box.isEnabled() && box.hasKeyboardFocus (false))
  52154. {
  52155. g.setColour (box.findColour (TextButton::buttonColourId));
  52156. g.drawRect (0, 0, width, height, 2);
  52157. }
  52158. else
  52159. {
  52160. g.setColour (box.findColour (ComboBox::outlineColourId));
  52161. g.drawRect (0, 0, width, height);
  52162. }
  52163. const float outlineThickness = box.isEnabled() ? (isButtonDown ? 1.2f : 0.5f) : 0.3f;
  52164. const Colour baseColour (createBaseColour (box.findColour (ComboBox::buttonColourId),
  52165. box.hasKeyboardFocus (true),
  52166. false, isButtonDown)
  52167. .withMultipliedAlpha (box.isEnabled() ? 1.0f : 0.5f));
  52168. drawGlassLozenge (g,
  52169. buttonX + outlineThickness, buttonY + outlineThickness,
  52170. buttonW - outlineThickness * 2.0f, buttonH - outlineThickness * 2.0f,
  52171. baseColour, outlineThickness, -1.0f,
  52172. true, true, true, true);
  52173. if (box.isEnabled())
  52174. {
  52175. const float arrowX = 0.3f;
  52176. const float arrowH = 0.2f;
  52177. Path p;
  52178. p.addTriangle (buttonX + buttonW * 0.5f, buttonY + buttonH * (0.45f - arrowH),
  52179. buttonX + buttonW * (1.0f - arrowX), buttonY + buttonH * 0.45f,
  52180. buttonX + buttonW * arrowX, buttonY + buttonH * 0.45f);
  52181. p.addTriangle (buttonX + buttonW * 0.5f, buttonY + buttonH * (0.55f + arrowH),
  52182. buttonX + buttonW * (1.0f - arrowX), buttonY + buttonH * 0.55f,
  52183. buttonX + buttonW * arrowX, buttonY + buttonH * 0.55f);
  52184. g.setColour (box.findColour (ComboBox::arrowColourId));
  52185. g.fillPath (p);
  52186. }
  52187. }
  52188. const Font LookAndFeel::getComboBoxFont (ComboBox& box)
  52189. {
  52190. return Font (jmin (15.0f, box.getHeight() * 0.85f));
  52191. }
  52192. Label* LookAndFeel::createComboBoxTextBox (ComboBox&)
  52193. {
  52194. return new Label (String::empty, String::empty);
  52195. }
  52196. void LookAndFeel::positionComboBoxText (ComboBox& box, Label& label)
  52197. {
  52198. label.setBounds (1, 1,
  52199. box.getWidth() + 3 - box.getHeight(),
  52200. box.getHeight() - 2);
  52201. label.setFont (getComboBoxFont (box));
  52202. }
  52203. void LookAndFeel::drawLabel (Graphics& g, Label& label)
  52204. {
  52205. g.fillAll (label.findColour (Label::backgroundColourId));
  52206. if (! label.isBeingEdited())
  52207. {
  52208. const float alpha = label.isEnabled() ? 1.0f : 0.5f;
  52209. g.setColour (label.findColour (Label::textColourId).withMultipliedAlpha (alpha));
  52210. g.setFont (label.getFont());
  52211. g.drawFittedText (label.getText(),
  52212. label.getHorizontalBorderSize(),
  52213. label.getVerticalBorderSize(),
  52214. label.getWidth() - 2 * label.getHorizontalBorderSize(),
  52215. label.getHeight() - 2 * label.getVerticalBorderSize(),
  52216. label.getJustificationType(),
  52217. jmax (1, (int) (label.getHeight() / label.getFont().getHeight())),
  52218. label.getMinimumHorizontalScale());
  52219. g.setColour (label.findColour (Label::outlineColourId).withMultipliedAlpha (alpha));
  52220. g.drawRect (0, 0, label.getWidth(), label.getHeight());
  52221. }
  52222. else if (label.isEnabled())
  52223. {
  52224. g.setColour (label.findColour (Label::outlineColourId));
  52225. g.drawRect (0, 0, label.getWidth(), label.getHeight());
  52226. }
  52227. }
  52228. void LookAndFeel::drawLinearSliderBackground (Graphics& g,
  52229. int x, int y,
  52230. int width, int height,
  52231. float /*sliderPos*/,
  52232. float /*minSliderPos*/,
  52233. float /*maxSliderPos*/,
  52234. const Slider::SliderStyle /*style*/,
  52235. Slider& slider)
  52236. {
  52237. const float sliderRadius = (float) (getSliderThumbRadius (slider) - 2);
  52238. const Colour trackColour (slider.findColour (Slider::trackColourId));
  52239. const Colour gradCol1 (trackColour.overlaidWith (Colours::black.withAlpha (slider.isEnabled() ? 0.25f : 0.13f)));
  52240. const Colour gradCol2 (trackColour.overlaidWith (Colour (0x14000000)));
  52241. Path indent;
  52242. if (slider.isHorizontal())
  52243. {
  52244. const float iy = y + height * 0.5f - sliderRadius * 0.5f;
  52245. const float ih = sliderRadius;
  52246. g.setGradientFill (ColourGradient (gradCol1, 0.0f, iy,
  52247. gradCol2, 0.0f, iy + ih, false));
  52248. indent.addRoundedRectangle (x - sliderRadius * 0.5f, iy,
  52249. width + sliderRadius, ih,
  52250. 5.0f);
  52251. g.fillPath (indent);
  52252. }
  52253. else
  52254. {
  52255. const float ix = x + width * 0.5f - sliderRadius * 0.5f;
  52256. const float iw = sliderRadius;
  52257. g.setGradientFill (ColourGradient (gradCol1, ix, 0.0f,
  52258. gradCol2, ix + iw, 0.0f, false));
  52259. indent.addRoundedRectangle (ix, y - sliderRadius * 0.5f,
  52260. iw, height + sliderRadius,
  52261. 5.0f);
  52262. g.fillPath (indent);
  52263. }
  52264. g.setColour (Colour (0x4c000000));
  52265. g.strokePath (indent, PathStrokeType (0.5f));
  52266. }
  52267. void LookAndFeel::drawLinearSliderThumb (Graphics& g,
  52268. int x, int y,
  52269. int width, int height,
  52270. float sliderPos,
  52271. float minSliderPos,
  52272. float maxSliderPos,
  52273. const Slider::SliderStyle style,
  52274. Slider& slider)
  52275. {
  52276. const float sliderRadius = (float) (getSliderThumbRadius (slider) - 2);
  52277. Colour knobColour (createBaseColour (slider.findColour (Slider::thumbColourId),
  52278. slider.hasKeyboardFocus (false) && slider.isEnabled(),
  52279. slider.isMouseOverOrDragging() && slider.isEnabled(),
  52280. slider.isMouseButtonDown() && slider.isEnabled()));
  52281. const float outlineThickness = slider.isEnabled() ? 0.8f : 0.3f;
  52282. if (style == Slider::LinearHorizontal || style == Slider::LinearVertical)
  52283. {
  52284. float kx, ky;
  52285. if (style == Slider::LinearVertical)
  52286. {
  52287. kx = x + width * 0.5f;
  52288. ky = sliderPos;
  52289. }
  52290. else
  52291. {
  52292. kx = sliderPos;
  52293. ky = y + height * 0.5f;
  52294. }
  52295. drawGlassSphere (g,
  52296. kx - sliderRadius,
  52297. ky - sliderRadius,
  52298. sliderRadius * 2.0f,
  52299. knobColour, outlineThickness);
  52300. }
  52301. else
  52302. {
  52303. if (style == Slider::ThreeValueVertical)
  52304. {
  52305. drawGlassSphere (g, x + width * 0.5f - sliderRadius,
  52306. sliderPos - sliderRadius,
  52307. sliderRadius * 2.0f,
  52308. knobColour, outlineThickness);
  52309. }
  52310. else if (style == Slider::ThreeValueHorizontal)
  52311. {
  52312. drawGlassSphere (g,sliderPos - sliderRadius,
  52313. y + height * 0.5f - sliderRadius,
  52314. sliderRadius * 2.0f,
  52315. knobColour, outlineThickness);
  52316. }
  52317. if (style == Slider::TwoValueVertical || style == Slider::ThreeValueVertical)
  52318. {
  52319. const float sr = jmin (sliderRadius, width * 0.4f);
  52320. drawGlassPointer (g, jmax (0.0f, x + width * 0.5f - sliderRadius * 2.0f),
  52321. minSliderPos - sliderRadius,
  52322. sliderRadius * 2.0f, knobColour, outlineThickness, 1);
  52323. drawGlassPointer (g, jmin (x + width - sliderRadius * 2.0f, x + width * 0.5f), maxSliderPos - sr,
  52324. sliderRadius * 2.0f, knobColour, outlineThickness, 3);
  52325. }
  52326. else if (style == Slider::TwoValueHorizontal || style == Slider::ThreeValueHorizontal)
  52327. {
  52328. const float sr = jmin (sliderRadius, height * 0.4f);
  52329. drawGlassPointer (g, minSliderPos - sr,
  52330. jmax (0.0f, y + height * 0.5f - sliderRadius * 2.0f),
  52331. sliderRadius * 2.0f, knobColour, outlineThickness, 2);
  52332. drawGlassPointer (g, maxSliderPos - sliderRadius,
  52333. jmin (y + height - sliderRadius * 2.0f, y + height * 0.5f),
  52334. sliderRadius * 2.0f, knobColour, outlineThickness, 4);
  52335. }
  52336. }
  52337. }
  52338. void LookAndFeel::drawLinearSlider (Graphics& g,
  52339. int x, int y,
  52340. int width, int height,
  52341. float sliderPos,
  52342. float minSliderPos,
  52343. float maxSliderPos,
  52344. const Slider::SliderStyle style,
  52345. Slider& slider)
  52346. {
  52347. g.fillAll (slider.findColour (Slider::backgroundColourId));
  52348. if (style == Slider::LinearBar)
  52349. {
  52350. const bool isMouseOver = slider.isMouseOverOrDragging() && slider.isEnabled();
  52351. Colour baseColour (createBaseColour (slider.findColour (Slider::thumbColourId)
  52352. .withMultipliedSaturation (slider.isEnabled() ? 1.0f : 0.5f),
  52353. false,
  52354. isMouseOver,
  52355. isMouseOver || slider.isMouseButtonDown()));
  52356. drawShinyButtonShape (g,
  52357. (float) x, (float) y, sliderPos - (float) x, (float) height, 0.0f,
  52358. baseColour,
  52359. slider.isEnabled() ? 0.9f : 0.3f,
  52360. true, true, true, true);
  52361. }
  52362. else
  52363. {
  52364. drawLinearSliderBackground (g, x, y, width, height, sliderPos, minSliderPos, maxSliderPos, style, slider);
  52365. drawLinearSliderThumb (g, x, y, width, height, sliderPos, minSliderPos, maxSliderPos, style, slider);
  52366. }
  52367. }
  52368. int LookAndFeel::getSliderThumbRadius (Slider& slider)
  52369. {
  52370. return jmin (7,
  52371. slider.getHeight() / 2,
  52372. slider.getWidth() / 2) + 2;
  52373. }
  52374. void LookAndFeel::drawRotarySlider (Graphics& g,
  52375. int x, int y,
  52376. int width, int height,
  52377. float sliderPos,
  52378. const float rotaryStartAngle,
  52379. const float rotaryEndAngle,
  52380. Slider& slider)
  52381. {
  52382. const float radius = jmin (width / 2, height / 2) - 2.0f;
  52383. const float centreX = x + width * 0.5f;
  52384. const float centreY = y + height * 0.5f;
  52385. const float rx = centreX - radius;
  52386. const float ry = centreY - radius;
  52387. const float rw = radius * 2.0f;
  52388. const float angle = rotaryStartAngle + sliderPos * (rotaryEndAngle - rotaryStartAngle);
  52389. const bool isMouseOver = slider.isMouseOverOrDragging() && slider.isEnabled();
  52390. if (radius > 12.0f)
  52391. {
  52392. if (slider.isEnabled())
  52393. g.setColour (slider.findColour (Slider::rotarySliderFillColourId).withAlpha (isMouseOver ? 1.0f : 0.7f));
  52394. else
  52395. g.setColour (Colour (0x80808080));
  52396. const float thickness = 0.7f;
  52397. {
  52398. Path filledArc;
  52399. filledArc.addPieSegment (rx, ry, rw, rw,
  52400. rotaryStartAngle,
  52401. angle,
  52402. thickness);
  52403. g.fillPath (filledArc);
  52404. }
  52405. if (thickness > 0)
  52406. {
  52407. const float innerRadius = radius * 0.2f;
  52408. Path p;
  52409. p.addTriangle (-innerRadius, 0.0f,
  52410. 0.0f, -radius * thickness * 1.1f,
  52411. innerRadius, 0.0f);
  52412. p.addEllipse (-innerRadius, -innerRadius, innerRadius * 2.0f, innerRadius * 2.0f);
  52413. g.fillPath (p, AffineTransform::rotation (angle).translated (centreX, centreY));
  52414. }
  52415. if (slider.isEnabled())
  52416. g.setColour (slider.findColour (Slider::rotarySliderOutlineColourId));
  52417. else
  52418. g.setColour (Colour (0x80808080));
  52419. Path outlineArc;
  52420. outlineArc.addPieSegment (rx, ry, rw, rw, rotaryStartAngle, rotaryEndAngle, thickness);
  52421. outlineArc.closeSubPath();
  52422. g.strokePath (outlineArc, PathStrokeType (slider.isEnabled() ? (isMouseOver ? 2.0f : 1.2f) : 0.3f));
  52423. }
  52424. else
  52425. {
  52426. if (slider.isEnabled())
  52427. g.setColour (slider.findColour (Slider::rotarySliderFillColourId).withAlpha (isMouseOver ? 1.0f : 0.7f));
  52428. else
  52429. g.setColour (Colour (0x80808080));
  52430. Path p;
  52431. p.addEllipse (-0.4f * rw, -0.4f * rw, rw * 0.8f, rw * 0.8f);
  52432. PathStrokeType (rw * 0.1f).createStrokedPath (p, p);
  52433. p.addLineSegment (0.0f, 0.0f, 0.0f, -radius, rw * 0.2f);
  52434. g.fillPath (p, AffineTransform::rotation (angle).translated (centreX, centreY));
  52435. }
  52436. }
  52437. Button* LookAndFeel::createSliderButton (const bool isIncrement)
  52438. {
  52439. return new TextButton (isIncrement ? "+" : "-", String::empty);
  52440. }
  52441. class SliderLabelComp : public Label
  52442. {
  52443. public:
  52444. SliderLabelComp() : Label (String::empty, String::empty) {}
  52445. ~SliderLabelComp() {}
  52446. void mouseWheelMove (const MouseEvent&, float, float) {}
  52447. };
  52448. Label* LookAndFeel::createSliderTextBox (Slider& slider)
  52449. {
  52450. Label* const l = new SliderLabelComp();
  52451. l->setJustificationType (Justification::centred);
  52452. l->setColour (Label::textColourId, slider.findColour (Slider::textBoxTextColourId));
  52453. l->setColour (Label::backgroundColourId,
  52454. (slider.getSliderStyle() == Slider::LinearBar) ? Colours::transparentBlack
  52455. : slider.findColour (Slider::textBoxBackgroundColourId));
  52456. l->setColour (Label::outlineColourId, slider.findColour (Slider::textBoxOutlineColourId));
  52457. l->setColour (TextEditor::textColourId, slider.findColour (Slider::textBoxTextColourId));
  52458. l->setColour (TextEditor::backgroundColourId,
  52459. slider.findColour (Slider::textBoxBackgroundColourId)
  52460. .withAlpha (slider.getSliderStyle() == Slider::LinearBar ? 0.7f : 1.0f));
  52461. l->setColour (TextEditor::outlineColourId, slider.findColour (Slider::textBoxOutlineColourId));
  52462. return l;
  52463. }
  52464. ImageEffectFilter* LookAndFeel::getSliderEffect()
  52465. {
  52466. return 0;
  52467. }
  52468. static const TextLayout layoutTooltipText (const String& text) throw()
  52469. {
  52470. const float tooltipFontSize = 12.0f;
  52471. const int maxToolTipWidth = 400;
  52472. const Font f (tooltipFontSize, Font::bold);
  52473. TextLayout tl (text, f);
  52474. tl.layout (maxToolTipWidth, Justification::left, true);
  52475. return tl;
  52476. }
  52477. void LookAndFeel::getTooltipSize (const String& tipText, int& width, int& height)
  52478. {
  52479. const TextLayout tl (layoutTooltipText (tipText));
  52480. width = tl.getWidth() + 14;
  52481. height = tl.getHeight() + 6;
  52482. }
  52483. void LookAndFeel::drawTooltip (Graphics& g, const String& text, int width, int height)
  52484. {
  52485. g.fillAll (findColour (TooltipWindow::backgroundColourId));
  52486. const Colour textCol (findColour (TooltipWindow::textColourId));
  52487. #if ! JUCE_MAC // The mac windows already have a non-optional 1 pix outline, so don't double it here..
  52488. g.setColour (findColour (TooltipWindow::outlineColourId));
  52489. g.drawRect (0, 0, width, height, 1);
  52490. #endif
  52491. const TextLayout tl (layoutTooltipText (text));
  52492. g.setColour (findColour (TooltipWindow::textColourId));
  52493. tl.drawWithin (g, 0, 0, width, height, Justification::centred);
  52494. }
  52495. Button* LookAndFeel::createFilenameComponentBrowseButton (const String& text)
  52496. {
  52497. return new TextButton (text, TRANS("click to browse for a different file"));
  52498. }
  52499. void LookAndFeel::layoutFilenameComponent (FilenameComponent& filenameComp,
  52500. ComboBox* filenameBox,
  52501. Button* browseButton)
  52502. {
  52503. browseButton->setSize (80, filenameComp.getHeight());
  52504. TextButton* const tb = dynamic_cast <TextButton*> (browseButton);
  52505. if (tb != 0)
  52506. tb->changeWidthToFitText();
  52507. browseButton->setTopRightPosition (filenameComp.getWidth(), 0);
  52508. filenameBox->setBounds (0, 0, browseButton->getX(), filenameComp.getHeight());
  52509. }
  52510. void LookAndFeel::drawImageButton (Graphics& g, Image* image,
  52511. int imageX, int imageY, int imageW, int imageH,
  52512. const Colour& overlayColour,
  52513. float imageOpacity,
  52514. ImageButton& button)
  52515. {
  52516. if (! button.isEnabled())
  52517. imageOpacity *= 0.3f;
  52518. if (! overlayColour.isOpaque())
  52519. {
  52520. g.setOpacity (imageOpacity);
  52521. g.drawImage (image, imageX, imageY, imageW, imageH,
  52522. 0, 0, image->getWidth(), image->getHeight(), false);
  52523. }
  52524. if (! overlayColour.isTransparent())
  52525. {
  52526. g.setColour (overlayColour);
  52527. g.drawImage (image, imageX, imageY, imageW, imageH,
  52528. 0, 0, image->getWidth(), image->getHeight(), true);
  52529. }
  52530. }
  52531. void LookAndFeel::drawCornerResizer (Graphics& g,
  52532. int w, int h,
  52533. bool /*isMouseOver*/,
  52534. bool /*isMouseDragging*/)
  52535. {
  52536. const float lineThickness = jmin (w, h) * 0.075f;
  52537. for (float i = 0.0f; i < 1.0f; i += 0.3f)
  52538. {
  52539. g.setColour (Colours::lightgrey);
  52540. g.drawLine (w * i,
  52541. h + 1.0f,
  52542. w + 1.0f,
  52543. h * i,
  52544. lineThickness);
  52545. g.setColour (Colours::darkgrey);
  52546. g.drawLine (w * i + lineThickness,
  52547. h + 1.0f,
  52548. w + 1.0f,
  52549. h * i + lineThickness,
  52550. lineThickness);
  52551. }
  52552. }
  52553. void LookAndFeel::drawResizableFrame (Graphics&, int /*w*/, int /*h*/,
  52554. const BorderSize& /*borders*/)
  52555. {
  52556. }
  52557. void LookAndFeel::fillResizableWindowBackground (Graphics& g, int /*w*/, int /*h*/,
  52558. const BorderSize& /*border*/, ResizableWindow& window)
  52559. {
  52560. g.fillAll (window.getBackgroundColour());
  52561. }
  52562. void LookAndFeel::drawResizableWindowBorder (Graphics& g, int w, int h,
  52563. const BorderSize& border, ResizableWindow&)
  52564. {
  52565. g.setColour (Colour (0x80000000));
  52566. g.drawRect (0, 0, w, h);
  52567. g.setColour (Colour (0x19000000));
  52568. g.drawRect (border.getLeft() - 1,
  52569. border.getTop() - 1,
  52570. w + 2 - border.getLeftAndRight(),
  52571. h + 2 - border.getTopAndBottom());
  52572. }
  52573. void LookAndFeel::drawDocumentWindowTitleBar (DocumentWindow& window,
  52574. Graphics& g, int w, int h,
  52575. int titleSpaceX, int titleSpaceW,
  52576. const Image* icon,
  52577. bool drawTitleTextOnLeft)
  52578. {
  52579. const bool isActive = window.isActiveWindow();
  52580. g.setGradientFill (ColourGradient (window.getBackgroundColour(),
  52581. 0.0f, 0.0f,
  52582. window.getBackgroundColour().contrasting (isActive ? 0.15f : 0.05f),
  52583. 0.0f, (float) h, false));
  52584. g.fillAll();
  52585. Font font (h * 0.65f, Font::bold);
  52586. g.setFont (font);
  52587. int textW = font.getStringWidth (window.getName());
  52588. int iconW = 0;
  52589. int iconH = 0;
  52590. if (icon != 0)
  52591. {
  52592. iconH = (int) font.getHeight();
  52593. iconW = icon->getWidth() * iconH / icon->getHeight() + 4;
  52594. }
  52595. textW = jmin (titleSpaceW, textW + iconW);
  52596. int textX = drawTitleTextOnLeft ? titleSpaceX
  52597. : jmax (titleSpaceX, (w - textW) / 2);
  52598. if (textX + textW > titleSpaceX + titleSpaceW)
  52599. textX = titleSpaceX + titleSpaceW - textW;
  52600. if (icon != 0)
  52601. {
  52602. g.setOpacity (isActive ? 1.0f : 0.6f);
  52603. g.drawImageWithin (icon, textX, (h - iconH) / 2, iconW, iconH,
  52604. RectanglePlacement::centred, false);
  52605. textX += iconW;
  52606. textW -= iconW;
  52607. }
  52608. if (window.isColourSpecified (DocumentWindow::textColourId) || isColourSpecified (DocumentWindow::textColourId))
  52609. g.setColour (findColour (DocumentWindow::textColourId));
  52610. else
  52611. g.setColour (window.getBackgroundColour().contrasting (isActive ? 0.7f : 0.4f));
  52612. g.drawText (window.getName(), textX, 0, textW, h, Justification::centredLeft, true);
  52613. }
  52614. class GlassWindowButton : public Button
  52615. {
  52616. public:
  52617. GlassWindowButton (const String& name, const Colour& col,
  52618. const Path& normalShape_,
  52619. const Path& toggledShape_) throw()
  52620. : Button (name),
  52621. colour (col),
  52622. normalShape (normalShape_),
  52623. toggledShape (toggledShape_)
  52624. {
  52625. }
  52626. ~GlassWindowButton()
  52627. {
  52628. }
  52629. void paintButton (Graphics& g, bool isMouseOverButton, bool isButtonDown)
  52630. {
  52631. float alpha = isMouseOverButton ? (isButtonDown ? 1.0f : 0.8f) : 0.55f;
  52632. if (! isEnabled())
  52633. alpha *= 0.5f;
  52634. float x = 0, y = 0, diam;
  52635. if (getWidth() < getHeight())
  52636. {
  52637. diam = (float) getWidth();
  52638. y = (getHeight() - getWidth()) * 0.5f;
  52639. }
  52640. else
  52641. {
  52642. diam = (float) getHeight();
  52643. y = (getWidth() - getHeight()) * 0.5f;
  52644. }
  52645. x += diam * 0.05f;
  52646. y += diam * 0.05f;
  52647. diam *= 0.9f;
  52648. g.setGradientFill (ColourGradient (Colour::greyLevel (0.9f).withAlpha (alpha), 0, y + diam,
  52649. Colour::greyLevel (0.6f).withAlpha (alpha), 0, y, false));
  52650. g.fillEllipse (x, y, diam, diam);
  52651. x += 2.0f;
  52652. y += 2.0f;
  52653. diam -= 4.0f;
  52654. LookAndFeel::drawGlassSphere (g, x, y, diam, colour.withAlpha (alpha), 1.0f);
  52655. Path& p = getToggleState() ? toggledShape : normalShape;
  52656. const AffineTransform t (p.getTransformToScaleToFit (x + diam * 0.3f, y + diam * 0.3f,
  52657. diam * 0.4f, diam * 0.4f, true));
  52658. g.setColour (Colours::black.withAlpha (alpha * 0.6f));
  52659. g.fillPath (p, t);
  52660. }
  52661. juce_UseDebuggingNewOperator
  52662. private:
  52663. Colour colour;
  52664. Path normalShape, toggledShape;
  52665. GlassWindowButton (const GlassWindowButton&);
  52666. GlassWindowButton& operator= (const GlassWindowButton&);
  52667. };
  52668. Button* LookAndFeel::createDocumentWindowButton (int buttonType)
  52669. {
  52670. Path shape;
  52671. const float crossThickness = 0.25f;
  52672. if (buttonType == DocumentWindow::closeButton)
  52673. {
  52674. shape.addLineSegment (0.0f, 0.0f, 1.0f, 1.0f, crossThickness * 1.4f);
  52675. shape.addLineSegment (1.0f, 0.0f, 0.0f, 1.0f, crossThickness * 1.4f);
  52676. return new GlassWindowButton ("close", Colour (0xffdd1100), shape, shape);
  52677. }
  52678. else if (buttonType == DocumentWindow::minimiseButton)
  52679. {
  52680. shape.addLineSegment (0.0f, 0.5f, 1.0f, 0.5f, crossThickness);
  52681. return new GlassWindowButton ("minimise", Colour (0xffaa8811), shape, shape);
  52682. }
  52683. else if (buttonType == DocumentWindow::maximiseButton)
  52684. {
  52685. shape.addLineSegment (0.5f, 0.0f, 0.5f, 1.0f, crossThickness);
  52686. shape.addLineSegment (0.0f, 0.5f, 1.0f, 0.5f, crossThickness);
  52687. Path fullscreenShape;
  52688. fullscreenShape.startNewSubPath (45.0f, 100.0f);
  52689. fullscreenShape.lineTo (0.0f, 100.0f);
  52690. fullscreenShape.lineTo (0.0f, 0.0f);
  52691. fullscreenShape.lineTo (100.0f, 0.0f);
  52692. fullscreenShape.lineTo (100.0f, 45.0f);
  52693. fullscreenShape.addRectangle (45.0f, 45.0f, 100.0f, 100.0f);
  52694. PathStrokeType (30.0f).createStrokedPath (fullscreenShape, fullscreenShape);
  52695. return new GlassWindowButton ("maximise", Colour (0xff119911), shape, fullscreenShape);
  52696. }
  52697. jassertfalse
  52698. return 0;
  52699. }
  52700. void LookAndFeel::positionDocumentWindowButtons (DocumentWindow&,
  52701. int titleBarX,
  52702. int titleBarY,
  52703. int titleBarW,
  52704. int titleBarH,
  52705. Button* minimiseButton,
  52706. Button* maximiseButton,
  52707. Button* closeButton,
  52708. bool positionTitleBarButtonsOnLeft)
  52709. {
  52710. const int buttonW = titleBarH - titleBarH / 8;
  52711. int x = positionTitleBarButtonsOnLeft ? titleBarX + 4
  52712. : titleBarX + titleBarW - buttonW - buttonW / 4;
  52713. if (closeButton != 0)
  52714. {
  52715. closeButton->setBounds (x, titleBarY, buttonW, titleBarH);
  52716. x += positionTitleBarButtonsOnLeft ? buttonW : -(buttonW + buttonW / 4);
  52717. }
  52718. if (positionTitleBarButtonsOnLeft)
  52719. swapVariables (minimiseButton, maximiseButton);
  52720. if (maximiseButton != 0)
  52721. {
  52722. maximiseButton->setBounds (x, titleBarY, buttonW, titleBarH);
  52723. x += positionTitleBarButtonsOnLeft ? buttonW : -buttonW;
  52724. }
  52725. if (minimiseButton != 0)
  52726. minimiseButton->setBounds (x, titleBarY, buttonW, titleBarH);
  52727. }
  52728. int LookAndFeel::getDefaultMenuBarHeight()
  52729. {
  52730. return 24;
  52731. }
  52732. DropShadower* LookAndFeel::createDropShadowerForComponent (Component*)
  52733. {
  52734. return new DropShadower (0.4f, 1, 5, 10);
  52735. }
  52736. void LookAndFeel::drawStretchableLayoutResizerBar (Graphics& g,
  52737. int w, int h,
  52738. bool /*isVerticalBar*/,
  52739. bool isMouseOver,
  52740. bool isMouseDragging)
  52741. {
  52742. float alpha = 0.5f;
  52743. if (isMouseOver || isMouseDragging)
  52744. {
  52745. g.fillAll (Colour (0x190000ff));
  52746. alpha = 1.0f;
  52747. }
  52748. const float cx = w * 0.5f;
  52749. const float cy = h * 0.5f;
  52750. const float cr = jmin (w, h) * 0.4f;
  52751. g.setGradientFill (ColourGradient (Colours::white.withAlpha (alpha), cx + cr * 0.1f, cy + cr,
  52752. Colours::black.withAlpha (alpha), cx, cy - cr * 4.0f,
  52753. true));
  52754. g.fillEllipse (cx - cr, cy - cr, cr * 2.0f, cr * 2.0f);
  52755. }
  52756. void LookAndFeel::drawGroupComponentOutline (Graphics& g, int width, int height,
  52757. const String& text,
  52758. const Justification& position,
  52759. GroupComponent& group)
  52760. {
  52761. const float textH = 15.0f;
  52762. const float indent = 3.0f;
  52763. const float textEdgeGap = 4.0f;
  52764. float cs = 5.0f;
  52765. Font f (textH);
  52766. Path p;
  52767. float x = indent;
  52768. float y = f.getAscent() - 3.0f;
  52769. float w = jmax (0.0f, width - x * 2.0f);
  52770. float h = jmax (0.0f, height - y - indent);
  52771. cs = jmin (cs, w * 0.5f, h * 0.5f);
  52772. const float cs2 = 2.0f * cs;
  52773. float textW = text.isEmpty() ? 0 : jlimit (0.0f, jmax (0.0f, w - cs2 - textEdgeGap * 2), f.getStringWidth (text) + textEdgeGap * 2.0f);
  52774. float textX = cs + textEdgeGap;
  52775. if (position.testFlags (Justification::horizontallyCentred))
  52776. textX = cs + (w - cs2 - textW) * 0.5f;
  52777. else if (position.testFlags (Justification::right))
  52778. textX = w - cs - textW - textEdgeGap;
  52779. p.startNewSubPath (x + textX + textW, y);
  52780. p.lineTo (x + w - cs, y);
  52781. p.addArc (x + w - cs2, y, cs2, cs2, 0, float_Pi * 0.5f);
  52782. p.lineTo (x + w, y + h - cs);
  52783. p.addArc (x + w - cs2, y + h - cs2, cs2, cs2, float_Pi * 0.5f, float_Pi);
  52784. p.lineTo (x + cs, y + h);
  52785. p.addArc (x, y + h - cs2, cs2, cs2, float_Pi, float_Pi * 1.5f);
  52786. p.lineTo (x, y + cs);
  52787. p.addArc (x, y, cs2, cs2, float_Pi * 1.5f, float_Pi * 2.0f);
  52788. p.lineTo (x + textX, y);
  52789. const float alpha = group.isEnabled() ? 1.0f : 0.5f;
  52790. g.setColour (group.findColour (GroupComponent::outlineColourId)
  52791. .withMultipliedAlpha (alpha));
  52792. g.strokePath (p, PathStrokeType (2.0f));
  52793. g.setColour (group.findColour (GroupComponent::textColourId)
  52794. .withMultipliedAlpha (alpha));
  52795. g.setFont (f);
  52796. g.drawText (text,
  52797. roundToInt (x + textX), 0,
  52798. roundToInt (textW),
  52799. roundToInt (textH),
  52800. Justification::centred, true);
  52801. }
  52802. int LookAndFeel::getTabButtonOverlap (int tabDepth)
  52803. {
  52804. return 1 + tabDepth / 3;
  52805. }
  52806. int LookAndFeel::getTabButtonSpaceAroundImage()
  52807. {
  52808. return 4;
  52809. }
  52810. void LookAndFeel::createTabButtonShape (Path& p,
  52811. int width, int height,
  52812. int /*tabIndex*/,
  52813. const String& /*text*/,
  52814. Button& /*button*/,
  52815. TabbedButtonBar::Orientation orientation,
  52816. const bool /*isMouseOver*/,
  52817. const bool /*isMouseDown*/,
  52818. const bool /*isFrontTab*/)
  52819. {
  52820. const float w = (float) width;
  52821. const float h = (float) height;
  52822. float length = w;
  52823. float depth = h;
  52824. if (orientation == TabbedButtonBar::TabsAtLeft
  52825. || orientation == TabbedButtonBar::TabsAtRight)
  52826. {
  52827. swapVariables (length, depth);
  52828. }
  52829. const float indent = (float) getTabButtonOverlap ((int) depth);
  52830. const float overhang = 4.0f;
  52831. if (orientation == TabbedButtonBar::TabsAtLeft)
  52832. {
  52833. p.startNewSubPath (w, 0.0f);
  52834. p.lineTo (0.0f, indent);
  52835. p.lineTo (0.0f, h - indent);
  52836. p.lineTo (w, h);
  52837. p.lineTo (w + overhang, h + overhang);
  52838. p.lineTo (w + overhang, -overhang);
  52839. }
  52840. else if (orientation == TabbedButtonBar::TabsAtRight)
  52841. {
  52842. p.startNewSubPath (0.0f, 0.0f);
  52843. p.lineTo (w, indent);
  52844. p.lineTo (w, h - indent);
  52845. p.lineTo (0.0f, h);
  52846. p.lineTo (-overhang, h + overhang);
  52847. p.lineTo (-overhang, -overhang);
  52848. }
  52849. else if (orientation == TabbedButtonBar::TabsAtBottom)
  52850. {
  52851. p.startNewSubPath (0.0f, 0.0f);
  52852. p.lineTo (indent, h);
  52853. p.lineTo (w - indent, h);
  52854. p.lineTo (w, 0.0f);
  52855. p.lineTo (w + overhang, -overhang);
  52856. p.lineTo (-overhang, -overhang);
  52857. }
  52858. else
  52859. {
  52860. p.startNewSubPath (0.0f, h);
  52861. p.lineTo (indent, 0.0f);
  52862. p.lineTo (w - indent, 0.0f);
  52863. p.lineTo (w, h);
  52864. p.lineTo (w + overhang, h + overhang);
  52865. p.lineTo (-overhang, h + overhang);
  52866. }
  52867. p.closeSubPath();
  52868. p = p.createPathWithRoundedCorners (3.0f);
  52869. }
  52870. void LookAndFeel::fillTabButtonShape (Graphics& g,
  52871. const Path& path,
  52872. const Colour& preferredColour,
  52873. int /*tabIndex*/,
  52874. const String& /*text*/,
  52875. Button& button,
  52876. TabbedButtonBar::Orientation /*orientation*/,
  52877. const bool /*isMouseOver*/,
  52878. const bool /*isMouseDown*/,
  52879. const bool isFrontTab)
  52880. {
  52881. g.setColour (isFrontTab ? preferredColour
  52882. : preferredColour.withMultipliedAlpha (0.9f));
  52883. g.fillPath (path);
  52884. g.setColour (button.findColour (isFrontTab ? TabbedButtonBar::frontOutlineColourId
  52885. : TabbedButtonBar::tabOutlineColourId, false)
  52886. .withMultipliedAlpha (button.isEnabled() ? 1.0f : 0.5f));
  52887. g.strokePath (path, PathStrokeType (isFrontTab ? 1.0f : 0.5f));
  52888. }
  52889. void LookAndFeel::drawTabButtonText (Graphics& g,
  52890. int x, int y, int w, int h,
  52891. const Colour& preferredBackgroundColour,
  52892. int /*tabIndex*/,
  52893. const String& text,
  52894. Button& button,
  52895. TabbedButtonBar::Orientation orientation,
  52896. const bool isMouseOver,
  52897. const bool isMouseDown,
  52898. const bool isFrontTab)
  52899. {
  52900. int length = w;
  52901. int depth = h;
  52902. if (orientation == TabbedButtonBar::TabsAtLeft
  52903. || orientation == TabbedButtonBar::TabsAtRight)
  52904. {
  52905. swapVariables (length, depth);
  52906. }
  52907. Font font (depth * 0.6f);
  52908. font.setUnderline (button.hasKeyboardFocus (false));
  52909. GlyphArrangement textLayout;
  52910. textLayout.addFittedText (font, text.trim(),
  52911. 0.0f, 0.0f, (float) length, (float) depth,
  52912. Justification::centred,
  52913. jmax (1, depth / 12));
  52914. AffineTransform transform;
  52915. if (orientation == TabbedButtonBar::TabsAtLeft)
  52916. {
  52917. transform = transform.rotated (float_Pi * -0.5f)
  52918. .translated ((float) x, (float) (y + h));
  52919. }
  52920. else if (orientation == TabbedButtonBar::TabsAtRight)
  52921. {
  52922. transform = transform.rotated (float_Pi * 0.5f)
  52923. .translated ((float) (x + w), (float) y);
  52924. }
  52925. else
  52926. {
  52927. transform = transform.translated ((float) x, (float) y);
  52928. }
  52929. if (isFrontTab && (button.isColourSpecified (TabbedButtonBar::frontTextColourId) || isColourSpecified (TabbedButtonBar::frontTextColourId)))
  52930. g.setColour (findColour (TabbedButtonBar::frontTextColourId));
  52931. else if (button.isColourSpecified (TabbedButtonBar::tabTextColourId) || isColourSpecified (TabbedButtonBar::tabTextColourId))
  52932. g.setColour (findColour (TabbedButtonBar::tabTextColourId));
  52933. else
  52934. g.setColour (preferredBackgroundColour.contrasting());
  52935. if (! (isMouseOver || isMouseDown))
  52936. g.setOpacity (0.8f);
  52937. if (! button.isEnabled())
  52938. g.setOpacity (0.3f);
  52939. textLayout.draw (g, transform);
  52940. }
  52941. int LookAndFeel::getTabButtonBestWidth (int /*tabIndex*/,
  52942. const String& text,
  52943. int tabDepth,
  52944. Button&)
  52945. {
  52946. Font f (tabDepth * 0.6f);
  52947. return f.getStringWidth (text.trim()) + getTabButtonOverlap (tabDepth) * 2;
  52948. }
  52949. void LookAndFeel::drawTabButton (Graphics& g,
  52950. int w, int h,
  52951. const Colour& preferredColour,
  52952. int tabIndex,
  52953. const String& text,
  52954. Button& button,
  52955. TabbedButtonBar::Orientation orientation,
  52956. const bool isMouseOver,
  52957. const bool isMouseDown,
  52958. const bool isFrontTab)
  52959. {
  52960. int length = w;
  52961. int depth = h;
  52962. if (orientation == TabbedButtonBar::TabsAtLeft
  52963. || orientation == TabbedButtonBar::TabsAtRight)
  52964. {
  52965. swapVariables (length, depth);
  52966. }
  52967. Path tabShape;
  52968. createTabButtonShape (tabShape, w, h,
  52969. tabIndex, text, button, orientation,
  52970. isMouseOver, isMouseDown, isFrontTab);
  52971. fillTabButtonShape (g, tabShape, preferredColour,
  52972. tabIndex, text, button, orientation,
  52973. isMouseOver, isMouseDown, isFrontTab);
  52974. const int indent = getTabButtonOverlap (depth);
  52975. int x = 0, y = 0;
  52976. if (orientation == TabbedButtonBar::TabsAtLeft
  52977. || orientation == TabbedButtonBar::TabsAtRight)
  52978. {
  52979. y += indent;
  52980. h -= indent * 2;
  52981. }
  52982. else
  52983. {
  52984. x += indent;
  52985. w -= indent * 2;
  52986. }
  52987. drawTabButtonText (g, x, y, w, h, preferredColour,
  52988. tabIndex, text, button, orientation,
  52989. isMouseOver, isMouseDown, isFrontTab);
  52990. }
  52991. void LookAndFeel::drawTabAreaBehindFrontButton (Graphics& g,
  52992. int w, int h,
  52993. TabbedButtonBar& tabBar,
  52994. TabbedButtonBar::Orientation orientation)
  52995. {
  52996. const float shadowSize = 0.2f;
  52997. float x1 = 0.0f, y1 = 0.0f, x2 = 0.0f, y2 = 0.0f;
  52998. Rectangle<int> shadowRect;
  52999. if (orientation == TabbedButtonBar::TabsAtLeft)
  53000. {
  53001. x1 = (float) w;
  53002. x2 = w * (1.0f - shadowSize);
  53003. shadowRect.setBounds ((int) x2, 0, w - (int) x2, h);
  53004. }
  53005. else if (orientation == TabbedButtonBar::TabsAtRight)
  53006. {
  53007. x2 = w * shadowSize;
  53008. shadowRect.setBounds (0, 0, (int) x2, h);
  53009. }
  53010. else if (orientation == TabbedButtonBar::TabsAtBottom)
  53011. {
  53012. y2 = h * shadowSize;
  53013. shadowRect.setBounds (0, 0, w, (int) y2);
  53014. }
  53015. else
  53016. {
  53017. y1 = (float) h;
  53018. y2 = h * (1.0f - shadowSize);
  53019. shadowRect.setBounds (0, (int) y2, w, h - (int) y2);
  53020. }
  53021. g.setGradientFill (ColourGradient (Colours::black.withAlpha (tabBar.isEnabled() ? 0.3f : 0.15f), x1, y1,
  53022. Colours::transparentBlack, x2, y2, false));
  53023. shadowRect.expand (2, 2);
  53024. g.fillRect (shadowRect);
  53025. g.setColour (Colour (0x80000000));
  53026. if (orientation == TabbedButtonBar::TabsAtLeft)
  53027. {
  53028. g.fillRect (w - 1, 0, 1, h);
  53029. }
  53030. else if (orientation == TabbedButtonBar::TabsAtRight)
  53031. {
  53032. g.fillRect (0, 0, 1, h);
  53033. }
  53034. else if (orientation == TabbedButtonBar::TabsAtBottom)
  53035. {
  53036. g.fillRect (0, 0, w, 1);
  53037. }
  53038. else
  53039. {
  53040. g.fillRect (0, h - 1, w, 1);
  53041. }
  53042. }
  53043. Button* LookAndFeel::createTabBarExtrasButton()
  53044. {
  53045. const float thickness = 7.0f;
  53046. const float indent = 22.0f;
  53047. Path p;
  53048. p.addEllipse (-10.0f, -10.0f, 120.0f, 120.0f);
  53049. DrawablePath ellipse;
  53050. ellipse.setPath (p);
  53051. ellipse.setFill (Colour (0x99ffffff));
  53052. p.clear();
  53053. p.addEllipse (0.0f, 0.0f, 100.0f, 100.0f);
  53054. p.addRectangle (indent, 50.0f - thickness, 100.0f - indent * 2.0f, thickness * 2.0f);
  53055. p.addRectangle (50.0f - thickness, indent, thickness * 2.0f, 50.0f - indent - thickness);
  53056. p.addRectangle (50.0f - thickness, 50.0f + thickness, thickness * 2.0f, 50.0f - indent - thickness);
  53057. p.setUsingNonZeroWinding (false);
  53058. DrawablePath dp;
  53059. dp.setPath (p);
  53060. dp.setFill (Colour (0x59000000));
  53061. DrawableComposite normalImage;
  53062. normalImage.insertDrawable (ellipse);
  53063. normalImage.insertDrawable (dp);
  53064. dp.setFill (Colour (0xcc000000));
  53065. DrawableComposite overImage;
  53066. overImage.insertDrawable (ellipse);
  53067. overImage.insertDrawable (dp);
  53068. DrawableButton* db = new DrawableButton ("tabs", DrawableButton::ImageFitted);
  53069. db->setImages (&normalImage, &overImage, 0);
  53070. return db;
  53071. }
  53072. void LookAndFeel::drawTableHeaderBackground (Graphics& g, TableHeaderComponent& header)
  53073. {
  53074. g.fillAll (Colours::white);
  53075. const int w = header.getWidth();
  53076. const int h = header.getHeight();
  53077. g.setGradientFill (ColourGradient (Colour (0xffe8ebf9), 0.0f, h * 0.5f,
  53078. Colour (0xfff6f8f9), 0.0f, h - 1.0f,
  53079. false));
  53080. g.fillRect (0, h / 2, w, h);
  53081. g.setColour (Colour (0x33000000));
  53082. g.fillRect (0, h - 1, w, 1);
  53083. for (int i = header.getNumColumns (true); --i >= 0;)
  53084. g.fillRect (header.getColumnPosition (i).getRight() - 1, 0, 1, h - 1);
  53085. }
  53086. void LookAndFeel::drawTableHeaderColumn (Graphics& g, const String& columnName, int /*columnId*/,
  53087. int width, int height,
  53088. bool isMouseOver, bool isMouseDown,
  53089. int columnFlags)
  53090. {
  53091. if (isMouseDown)
  53092. g.fillAll (Colour (0x8899aadd));
  53093. else if (isMouseOver)
  53094. g.fillAll (Colour (0x5599aadd));
  53095. int rightOfText = width - 4;
  53096. if ((columnFlags & (TableHeaderComponent::sortedForwards | TableHeaderComponent::sortedBackwards)) != 0)
  53097. {
  53098. const float top = height * ((columnFlags & TableHeaderComponent::sortedForwards) != 0 ? 0.35f : (1.0f - 0.35f));
  53099. const float bottom = height - top;
  53100. const float w = height * 0.5f;
  53101. const float x = rightOfText - (w * 1.25f);
  53102. rightOfText = (int) x;
  53103. Path sortArrow;
  53104. sortArrow.addTriangle (x, bottom, x + w * 0.5f, top, x + w, bottom);
  53105. g.setColour (Colour (0x99000000));
  53106. g.fillPath (sortArrow);
  53107. }
  53108. g.setColour (Colours::black);
  53109. g.setFont (height * 0.5f, Font::bold);
  53110. const int textX = 4;
  53111. g.drawFittedText (columnName, textX, 0, rightOfText - textX, height, Justification::centredLeft, 1);
  53112. }
  53113. void LookAndFeel::paintToolbarBackground (Graphics& g, int w, int h, Toolbar& toolbar)
  53114. {
  53115. const Colour background (toolbar.findColour (Toolbar::backgroundColourId));
  53116. g.setGradientFill (ColourGradient (background, 0.0f, 0.0f,
  53117. background.darker (0.1f),
  53118. toolbar.isVertical() ? w - 1.0f : 0.0f,
  53119. toolbar.isVertical() ? 0.0f : h - 1.0f,
  53120. false));
  53121. g.fillAll();
  53122. }
  53123. Button* LookAndFeel::createToolbarMissingItemsButton (Toolbar& /*toolbar*/)
  53124. {
  53125. return createTabBarExtrasButton();
  53126. }
  53127. void LookAndFeel::paintToolbarButtonBackground (Graphics& g, int /*width*/, int /*height*/,
  53128. bool isMouseOver, bool isMouseDown,
  53129. ToolbarItemComponent& component)
  53130. {
  53131. if (isMouseDown)
  53132. g.fillAll (component.findColour (Toolbar::buttonMouseDownBackgroundColourId, true));
  53133. else if (isMouseOver)
  53134. g.fillAll (component.findColour (Toolbar::buttonMouseOverBackgroundColourId, true));
  53135. }
  53136. void LookAndFeel::paintToolbarButtonLabel (Graphics& g, int x, int y, int width, int height,
  53137. const String& text, ToolbarItemComponent& component)
  53138. {
  53139. g.setColour (component.findColour (Toolbar::labelTextColourId, true)
  53140. .withAlpha (component.isEnabled() ? 1.0f : 0.25f));
  53141. const float fontHeight = jmin (14.0f, height * 0.85f);
  53142. g.setFont (fontHeight);
  53143. g.drawFittedText (text,
  53144. x, y, width, height,
  53145. Justification::centred,
  53146. jmax (1, height / (int) fontHeight));
  53147. }
  53148. void LookAndFeel::drawPropertyPanelSectionHeader (Graphics& g, const String& name,
  53149. bool isOpen, int width, int height)
  53150. {
  53151. const int buttonSize = (height * 3) / 4;
  53152. const int buttonIndent = (height - buttonSize) / 2;
  53153. drawTreeviewPlusMinusBox (g, buttonIndent, buttonIndent, buttonSize, buttonSize, ! isOpen, false);
  53154. const int textX = buttonIndent * 2 + buttonSize + 2;
  53155. g.setColour (Colours::black);
  53156. g.setFont (height * 0.7f, Font::bold);
  53157. g.drawText (name, textX, 0, width - textX - 4, height, Justification::centredLeft, true);
  53158. }
  53159. void LookAndFeel::drawPropertyComponentBackground (Graphics& g, int width, int height,
  53160. PropertyComponent&)
  53161. {
  53162. g.setColour (Colour (0x66ffffff));
  53163. g.fillRect (0, 0, width, height - 1);
  53164. }
  53165. void LookAndFeel::drawPropertyComponentLabel (Graphics& g, int, int height,
  53166. PropertyComponent& component)
  53167. {
  53168. g.setColour (Colours::black);
  53169. if (! component.isEnabled())
  53170. g.setOpacity (0.6f);
  53171. g.setFont (jmin (height, 24) * 0.65f);
  53172. const Rectangle<int> r (getPropertyComponentContentPosition (component));
  53173. g.drawFittedText (component.getName(),
  53174. 3, r.getY(), r.getX() - 5, r.getHeight(),
  53175. Justification::centredLeft, 2);
  53176. }
  53177. const Rectangle<int> LookAndFeel::getPropertyComponentContentPosition (PropertyComponent& component)
  53178. {
  53179. return Rectangle<int> (component.getWidth() / 3, 1,
  53180. component.getWidth() - component.getWidth() / 3 - 1, component.getHeight() - 3);
  53181. }
  53182. void LookAndFeel::createFileChooserHeaderText (const String& title,
  53183. const String& instructions,
  53184. GlyphArrangement& text,
  53185. int width)
  53186. {
  53187. text.clear();
  53188. text.addJustifiedText (Font (17.0f, Font::bold), title,
  53189. 8.0f, 22.0f, width - 16.0f,
  53190. Justification::centred);
  53191. text.addJustifiedText (Font (14.0f), instructions,
  53192. 8.0f, 24.0f + 16.0f, width - 16.0f,
  53193. Justification::centred);
  53194. }
  53195. void LookAndFeel::drawFileBrowserRow (Graphics& g, int width, int height,
  53196. const String& filename, Image* icon,
  53197. const String& fileSizeDescription,
  53198. const String& fileTimeDescription,
  53199. const bool isDirectory,
  53200. const bool isItemSelected,
  53201. const int /*itemIndex*/)
  53202. {
  53203. if (isItemSelected)
  53204. g.fillAll (findColour (DirectoryContentsDisplayComponent::highlightColourId));
  53205. g.setColour (findColour (DirectoryContentsDisplayComponent::textColourId));
  53206. g.setFont (height * 0.7f);
  53207. Image* im = icon;
  53208. Image* toRelease = 0;
  53209. if (im == 0)
  53210. {
  53211. toRelease = im = (isDirectory ? getDefaultFolderImage()
  53212. : getDefaultDocumentFileImage());
  53213. }
  53214. const int x = 32;
  53215. if (im != 0)
  53216. {
  53217. g.drawImageWithin (im, 2, 2, x - 4, height - 4,
  53218. RectanglePlacement::centred | RectanglePlacement::onlyReduceInSize,
  53219. false);
  53220. ImageCache::release (toRelease);
  53221. }
  53222. if (width > 450 && ! isDirectory)
  53223. {
  53224. const int sizeX = roundToInt (width * 0.7f);
  53225. const int dateX = roundToInt (width * 0.8f);
  53226. g.drawFittedText (filename,
  53227. x, 0, sizeX - x, height,
  53228. Justification::centredLeft, 1);
  53229. g.setFont (height * 0.5f);
  53230. g.setColour (Colours::darkgrey);
  53231. if (! isDirectory)
  53232. {
  53233. g.drawFittedText (fileSizeDescription,
  53234. sizeX, 0, dateX - sizeX - 8, height,
  53235. Justification::centredRight, 1);
  53236. g.drawFittedText (fileTimeDescription,
  53237. dateX, 0, width - 8 - dateX, height,
  53238. Justification::centredRight, 1);
  53239. }
  53240. }
  53241. else
  53242. {
  53243. g.drawFittedText (filename,
  53244. x, 0, width - x, height,
  53245. Justification::centredLeft, 1);
  53246. }
  53247. }
  53248. Button* LookAndFeel::createFileBrowserGoUpButton()
  53249. {
  53250. DrawableButton* goUpButton = new DrawableButton ("up", DrawableButton::ImageOnButtonBackground);
  53251. Path arrowPath;
  53252. arrowPath.addArrow (50.0f, 100.0f, 50.0f, 0.0f, 40.0f, 100.0f, 50.0f);
  53253. DrawablePath arrowImage;
  53254. arrowImage.setFill (Colours::black.withAlpha (0.4f));
  53255. arrowImage.setPath (arrowPath);
  53256. goUpButton->setImages (&arrowImage);
  53257. return goUpButton;
  53258. }
  53259. void LookAndFeel::layoutFileBrowserComponent (FileBrowserComponent& browserComp,
  53260. DirectoryContentsDisplayComponent* fileListComponent,
  53261. FilePreviewComponent* previewComp,
  53262. ComboBox* currentPathBox,
  53263. TextEditor* filenameBox,
  53264. Button* goUpButton)
  53265. {
  53266. const int x = 8;
  53267. int w = browserComp.getWidth() - x - x;
  53268. if (previewComp != 0)
  53269. {
  53270. const int previewWidth = w / 3;
  53271. previewComp->setBounds (x + w - previewWidth, 0, previewWidth, browserComp.getHeight());
  53272. w -= previewWidth + 4;
  53273. }
  53274. int y = 4;
  53275. const int controlsHeight = 22;
  53276. const int bottomSectionHeight = controlsHeight + 8;
  53277. const int upButtonWidth = 50;
  53278. currentPathBox->setBounds (x, y, w - upButtonWidth - 6, controlsHeight);
  53279. goUpButton->setBounds (x + w - upButtonWidth, y, upButtonWidth, controlsHeight);
  53280. y += controlsHeight + 4;
  53281. Component* const listAsComp = dynamic_cast <Component*> (fileListComponent);
  53282. listAsComp->setBounds (x, y, w, browserComp.getHeight() - y - bottomSectionHeight);
  53283. y = listAsComp->getBottom() + 4;
  53284. filenameBox->setBounds (x + 50, y, w - 50, controlsHeight);
  53285. }
  53286. Image* LookAndFeel::getDefaultFolderImage()
  53287. {
  53288. 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,
  53289. 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,
  53290. 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,
  53291. 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,
  53292. 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,
  53293. 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,
  53294. 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,
  53295. 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,
  53296. 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,
  53297. 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,
  53298. 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,
  53299. 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,
  53300. 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,
  53301. 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,
  53302. 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,
  53303. 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,
  53304. 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,
  53305. 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,
  53306. 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,
  53307. 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,
  53308. 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,
  53309. 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,
  53310. 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,
  53311. 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,
  53312. 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,
  53313. 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,
  53314. 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,
  53315. 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,
  53316. 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,
  53317. 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,
  53318. 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,
  53319. 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,
  53320. 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,
  53321. 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,
  53322. 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,
  53323. 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,
  53324. 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,
  53325. 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,
  53326. 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,
  53327. 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,
  53328. 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,
  53329. 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,
  53330. 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,
  53331. 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};
  53332. return ImageCache::getFromMemory (foldericon_png, sizeof (foldericon_png));
  53333. }
  53334. Image* LookAndFeel::getDefaultDocumentFileImage()
  53335. {
  53336. 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,
  53337. 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,
  53338. 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,
  53339. 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,
  53340. 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,
  53341. 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,
  53342. 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,
  53343. 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,
  53344. 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,
  53345. 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,
  53346. 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,
  53347. 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,
  53348. 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,
  53349. 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,
  53350. 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,
  53351. 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,
  53352. 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,
  53353. 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,
  53354. 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,
  53355. 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,
  53356. 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,
  53357. 174,66,96,130,0,0};
  53358. return ImageCache::getFromMemory (fileicon_png, sizeof (fileicon_png));
  53359. }
  53360. void LookAndFeel::playAlertSound()
  53361. {
  53362. PlatformUtilities::beep();
  53363. }
  53364. void LookAndFeel::drawLevelMeter (Graphics& g, int width, int height, float level)
  53365. {
  53366. g.setColour (Colours::white.withAlpha (0.7f));
  53367. g.fillRoundedRectangle (0.0f, 0.0f, (float) width, (float) height, 3.0f);
  53368. g.setColour (Colours::black.withAlpha (0.2f));
  53369. g.drawRoundedRectangle (1.0f, 1.0f, width - 2.0f, height - 2.0f, 3.0f, 1.0f);
  53370. const int totalBlocks = 7;
  53371. const int numBlocks = roundToInt (totalBlocks * level);
  53372. const float w = (width - 6.0f) / (float) totalBlocks;
  53373. for (int i = 0; i < totalBlocks; ++i)
  53374. {
  53375. if (i >= numBlocks)
  53376. g.setColour (Colours::lightblue.withAlpha (0.6f));
  53377. else
  53378. g.setColour (i < totalBlocks - 1 ? Colours::blue.withAlpha (0.5f)
  53379. : Colours::red);
  53380. g.fillRoundedRectangle (3.0f + i * w + w * 0.1f, 3.0f, w * 0.8f, height - 6.0f, w * 0.4f);
  53381. }
  53382. }
  53383. void LookAndFeel::drawKeymapChangeButton (Graphics& g, int width, int height, Button& button, const String& keyDescription)
  53384. {
  53385. const Colour textColour (button.findColour (KeyMappingEditorComponent::textColourId, true));
  53386. if (keyDescription.isNotEmpty())
  53387. {
  53388. if (button.isEnabled())
  53389. {
  53390. const float alpha = button.isDown() ? 0.3f : (button.isOver() ? 0.15f : 0.08f);
  53391. g.fillAll (textColour.withAlpha (alpha));
  53392. g.setOpacity (0.3f);
  53393. g.drawBevel (0, 0, width, height, 2);
  53394. }
  53395. g.setColour (textColour);
  53396. g.setFont (height * 0.6f);
  53397. g.drawFittedText (keyDescription,
  53398. 3, 0, width - 6, height,
  53399. Justification::centred, 1);
  53400. }
  53401. else
  53402. {
  53403. const float thickness = 7.0f;
  53404. const float indent = 22.0f;
  53405. Path p;
  53406. p.addEllipse (0.0f, 0.0f, 100.0f, 100.0f);
  53407. p.addRectangle (indent, 50.0f - thickness, 100.0f - indent * 2.0f, thickness * 2.0f);
  53408. p.addRectangle (50.0f - thickness, indent, thickness * 2.0f, 50.0f - indent - thickness);
  53409. p.addRectangle (50.0f - thickness, 50.0f + thickness, thickness * 2.0f, 50.0f - indent - thickness);
  53410. p.setUsingNonZeroWinding (false);
  53411. g.setColour (textColour.withAlpha (button.isDown() ? 0.7f : (button.isOver() ? 0.5f : 0.3f)));
  53412. g.fillPath (p, p.getTransformToScaleToFit (2.0f, 2.0f, width - 4.0f, height - 4.0f, true));
  53413. }
  53414. if (button.hasKeyboardFocus (false))
  53415. {
  53416. g.setColour (textColour.withAlpha (0.4f));
  53417. g.drawRect (0, 0, width, height);
  53418. }
  53419. }
  53420. static void createRoundedPath (Path& p,
  53421. const float x, const float y,
  53422. const float w, const float h,
  53423. const float cs,
  53424. const bool curveTopLeft, const bool curveTopRight,
  53425. const bool curveBottomLeft, const bool curveBottomRight) throw()
  53426. {
  53427. const float cs2 = 2.0f * cs;
  53428. if (curveTopLeft)
  53429. {
  53430. p.startNewSubPath (x, y + cs);
  53431. p.addArc (x, y, cs2, cs2, float_Pi * 1.5f, float_Pi * 2.0f);
  53432. }
  53433. else
  53434. {
  53435. p.startNewSubPath (x, y);
  53436. }
  53437. if (curveTopRight)
  53438. {
  53439. p.lineTo (x + w - cs, y);
  53440. p.addArc (x + w - cs2, y, cs2, cs2, 0.0f, float_Pi * 0.5f);
  53441. }
  53442. else
  53443. {
  53444. p.lineTo (x + w, y);
  53445. }
  53446. if (curveBottomRight)
  53447. {
  53448. p.lineTo (x + w, y + h - cs);
  53449. p.addArc (x + w - cs2, y + h - cs2, cs2, cs2, float_Pi * 0.5f, float_Pi);
  53450. }
  53451. else
  53452. {
  53453. p.lineTo (x + w, y + h);
  53454. }
  53455. if (curveBottomLeft)
  53456. {
  53457. p.lineTo (x + cs, y + h);
  53458. p.addArc (x, y + h - cs2, cs2, cs2, float_Pi, float_Pi * 1.5f);
  53459. }
  53460. else
  53461. {
  53462. p.lineTo (x, y + h);
  53463. }
  53464. p.closeSubPath();
  53465. }
  53466. void LookAndFeel::drawShinyButtonShape (Graphics& g,
  53467. float x, float y, float w, float h,
  53468. float maxCornerSize,
  53469. const Colour& baseColour,
  53470. const float strokeWidth,
  53471. const bool flatOnLeft,
  53472. const bool flatOnRight,
  53473. const bool flatOnTop,
  53474. const bool flatOnBottom) throw()
  53475. {
  53476. if (w <= strokeWidth * 1.1f || h <= strokeWidth * 1.1f)
  53477. return;
  53478. const float cs = jmin (maxCornerSize, w * 0.5f, h * 0.5f);
  53479. Path outline;
  53480. createRoundedPath (outline, x, y, w, h, cs,
  53481. ! (flatOnLeft || flatOnTop),
  53482. ! (flatOnRight || flatOnTop),
  53483. ! (flatOnLeft || flatOnBottom),
  53484. ! (flatOnRight || flatOnBottom));
  53485. ColourGradient cg (baseColour, 0.0f, y,
  53486. baseColour.overlaidWith (Colour (0x070000ff)), 0.0f, y + h,
  53487. false);
  53488. cg.addColour (0.5, baseColour.overlaidWith (Colour (0x33ffffff)));
  53489. cg.addColour (0.51, baseColour.overlaidWith (Colour (0x110000ff)));
  53490. g.setGradientFill (cg);
  53491. g.fillPath (outline);
  53492. g.setColour (Colour (0x80000000));
  53493. g.strokePath (outline, PathStrokeType (strokeWidth));
  53494. }
  53495. void LookAndFeel::drawGlassSphere (Graphics& g,
  53496. const float x, const float y,
  53497. const float diameter,
  53498. const Colour& colour,
  53499. const float outlineThickness) throw()
  53500. {
  53501. if (diameter <= outlineThickness)
  53502. return;
  53503. Path p;
  53504. p.addEllipse (x, y, diameter, diameter);
  53505. {
  53506. ColourGradient cg (Colours::white.overlaidWith (colour.withMultipliedAlpha (0.3f)), 0, y,
  53507. Colours::white.overlaidWith (colour.withMultipliedAlpha (0.3f)), 0, y + diameter, false);
  53508. cg.addColour (0.4, Colours::white.overlaidWith (colour));
  53509. g.setGradientFill (cg);
  53510. g.fillPath (p);
  53511. }
  53512. g.setGradientFill (ColourGradient (Colours::white, 0, y + diameter * 0.06f,
  53513. Colours::transparentWhite, 0, y + diameter * 0.3f, false));
  53514. g.fillEllipse (x + diameter * 0.2f, y + diameter * 0.05f, diameter * 0.6f, diameter * 0.4f);
  53515. ColourGradient cg (Colours::transparentBlack,
  53516. x + diameter * 0.5f, y + diameter * 0.5f,
  53517. Colours::black.withAlpha (0.5f * outlineThickness * colour.getFloatAlpha()),
  53518. x, y + diameter * 0.5f, true);
  53519. cg.addColour (0.7, Colours::transparentBlack);
  53520. cg.addColour (0.8, Colours::black.withAlpha (0.1f * outlineThickness));
  53521. g.setGradientFill (cg);
  53522. g.fillPath (p);
  53523. g.setColour (Colours::black.withAlpha (0.5f * colour.getFloatAlpha()));
  53524. g.drawEllipse (x, y, diameter, diameter, outlineThickness);
  53525. }
  53526. void LookAndFeel::drawGlassPointer (Graphics& g,
  53527. const float x, const float y,
  53528. const float diameter,
  53529. const Colour& colour, const float outlineThickness,
  53530. const int direction) throw()
  53531. {
  53532. if (diameter <= outlineThickness)
  53533. return;
  53534. Path p;
  53535. p.startNewSubPath (x + diameter * 0.5f, y);
  53536. p.lineTo (x + diameter, y + diameter * 0.6f);
  53537. p.lineTo (x + diameter, y + diameter);
  53538. p.lineTo (x, y + diameter);
  53539. p.lineTo (x, y + diameter * 0.6f);
  53540. p.closeSubPath();
  53541. p.applyTransform (AffineTransform::rotation (direction * (float_Pi * 0.5f), x + diameter * 0.5f, y + diameter * 0.5f));
  53542. {
  53543. ColourGradient cg (Colours::white.overlaidWith (colour.withMultipliedAlpha (0.3f)), 0, y,
  53544. Colours::white.overlaidWith (colour.withMultipliedAlpha (0.3f)), 0, y + diameter, false);
  53545. cg.addColour (0.4, Colours::white.overlaidWith (colour));
  53546. g.setGradientFill (cg);
  53547. g.fillPath (p);
  53548. }
  53549. ColourGradient cg (Colours::transparentBlack,
  53550. x + diameter * 0.5f, y + diameter * 0.5f,
  53551. Colours::black.withAlpha (0.5f * outlineThickness * colour.getFloatAlpha()),
  53552. x - diameter * 0.2f, y + diameter * 0.5f, true);
  53553. cg.addColour (0.5, Colours::transparentBlack);
  53554. cg.addColour (0.7, Colours::black.withAlpha (0.07f * outlineThickness));
  53555. g.setGradientFill (cg);
  53556. g.fillPath (p);
  53557. g.setColour (Colours::black.withAlpha (0.5f * colour.getFloatAlpha()));
  53558. g.strokePath (p, PathStrokeType (outlineThickness));
  53559. }
  53560. void LookAndFeel::drawGlassLozenge (Graphics& g,
  53561. const float x, const float y,
  53562. const float width, const float height,
  53563. const Colour& colour,
  53564. const float outlineThickness,
  53565. const float cornerSize,
  53566. const bool flatOnLeft,
  53567. const bool flatOnRight,
  53568. const bool flatOnTop,
  53569. const bool flatOnBottom) throw()
  53570. {
  53571. if (width <= outlineThickness || height <= outlineThickness)
  53572. return;
  53573. const int intX = (int) x;
  53574. const int intY = (int) y;
  53575. const int intW = (int) width;
  53576. const int intH = (int) height;
  53577. const float cs = cornerSize < 0 ? jmin (width * 0.5f, height * 0.5f) : cornerSize;
  53578. const float edgeBlurRadius = height * 0.75f + (height - cs * 2.0f);
  53579. const int intEdge = (int) edgeBlurRadius;
  53580. Path outline;
  53581. createRoundedPath (outline, x, y, width, height, cs,
  53582. ! (flatOnLeft || flatOnTop),
  53583. ! (flatOnRight || flatOnTop),
  53584. ! (flatOnLeft || flatOnBottom),
  53585. ! (flatOnRight || flatOnBottom));
  53586. {
  53587. ColourGradient cg (colour.darker (0.2f), 0, y,
  53588. colour.darker (0.2f), 0, y + height, false);
  53589. cg.addColour (0.03, colour.withMultipliedAlpha (0.3f));
  53590. cg.addColour (0.4, colour);
  53591. cg.addColour (0.97, colour.withMultipliedAlpha (0.3f));
  53592. g.setGradientFill (cg);
  53593. g.fillPath (outline);
  53594. }
  53595. ColourGradient cg (Colours::transparentBlack, x + edgeBlurRadius, y + height * 0.5f,
  53596. colour.darker (0.2f), x, y + height * 0.5f, true);
  53597. cg.addColour (jlimit (0.0, 1.0, 1.0 - (cs * 0.5f) / edgeBlurRadius), Colours::transparentBlack);
  53598. cg.addColour (jlimit (0.0, 1.0, 1.0 - (cs * 0.25f) / edgeBlurRadius), colour.darker (0.2f).withMultipliedAlpha (0.3f));
  53599. if (! (flatOnLeft || flatOnTop || flatOnBottom))
  53600. {
  53601. g.saveState();
  53602. g.setGradientFill (cg);
  53603. g.reduceClipRegion (intX, intY, intEdge, intH);
  53604. g.fillPath (outline);
  53605. g.restoreState();
  53606. }
  53607. if (! (flatOnRight || flatOnTop || flatOnBottom))
  53608. {
  53609. cg.x1 = x + width - edgeBlurRadius;
  53610. cg.x2 = x + width;
  53611. g.saveState();
  53612. g.setGradientFill (cg);
  53613. g.reduceClipRegion (intX + intW - intEdge, intY, 2 + intEdge, intH);
  53614. g.fillPath (outline);
  53615. g.restoreState();
  53616. }
  53617. {
  53618. const float leftIndent = flatOnLeft ? 0.0f : cs * 0.4f;
  53619. const float rightIndent = flatOnRight ? 0.0f : cs * 0.4f;
  53620. Path highlight;
  53621. createRoundedPath (highlight,
  53622. x + leftIndent,
  53623. y + cs * 0.1f,
  53624. width - (leftIndent + rightIndent),
  53625. height * 0.4f, cs * 0.4f,
  53626. ! (flatOnLeft || flatOnTop),
  53627. ! (flatOnRight || flatOnTop),
  53628. ! (flatOnLeft || flatOnBottom),
  53629. ! (flatOnRight || flatOnBottom));
  53630. g.setGradientFill (ColourGradient (colour.brighter (10.0f), 0, y + height * 0.06f,
  53631. Colours::transparentWhite, 0, y + height * 0.4f, false));
  53632. g.fillPath (highlight);
  53633. }
  53634. g.setColour (colour.darker().withMultipliedAlpha (1.5f));
  53635. g.strokePath (outline, PathStrokeType (outlineThickness));
  53636. }
  53637. END_JUCE_NAMESPACE
  53638. /*** End of inlined file: juce_LookAndFeel.cpp ***/
  53639. /*** Start of inlined file: juce_OldSchoolLookAndFeel.cpp ***/
  53640. BEGIN_JUCE_NAMESPACE
  53641. OldSchoolLookAndFeel::OldSchoolLookAndFeel()
  53642. {
  53643. setColour (TextButton::buttonColourId, Colour (0xffbbbbff));
  53644. setColour (ListBox::outlineColourId, findColour (ComboBox::outlineColourId));
  53645. setColour (ScrollBar::thumbColourId, Colour (0xffbbbbdd));
  53646. setColour (ScrollBar::backgroundColourId, Colours::transparentBlack);
  53647. setColour (Slider::thumbColourId, Colours::white);
  53648. setColour (Slider::trackColourId, Colour (0x7f000000));
  53649. setColour (Slider::textBoxOutlineColourId, Colours::grey);
  53650. setColour (ProgressBar::backgroundColourId, Colours::white.withAlpha (0.6f));
  53651. setColour (ProgressBar::foregroundColourId, Colours::green.withAlpha (0.7f));
  53652. setColour (PopupMenu::backgroundColourId, Colour (0xffeef5f8));
  53653. setColour (PopupMenu::highlightedBackgroundColourId, Colour (0xbfa4c2ce));
  53654. setColour (PopupMenu::highlightedTextColourId, Colours::black);
  53655. setColour (TextEditor::focusedOutlineColourId, findColour (TextButton::buttonColourId));
  53656. scrollbarShadow.setShadowProperties (2.2f, 0.5f, 0, 0);
  53657. }
  53658. OldSchoolLookAndFeel::~OldSchoolLookAndFeel()
  53659. {
  53660. }
  53661. void OldSchoolLookAndFeel::drawButtonBackground (Graphics& g,
  53662. Button& button,
  53663. const Colour& backgroundColour,
  53664. bool isMouseOverButton,
  53665. bool isButtonDown)
  53666. {
  53667. const int width = button.getWidth();
  53668. const int height = button.getHeight();
  53669. const float indent = 2.0f;
  53670. const int cornerSize = jmin (roundToInt (width * 0.4f),
  53671. roundToInt (height * 0.4f));
  53672. Path p;
  53673. p.addRoundedRectangle (indent, indent,
  53674. width - indent * 2.0f,
  53675. height - indent * 2.0f,
  53676. (float) cornerSize);
  53677. Colour bc (backgroundColour.withMultipliedSaturation (0.3f));
  53678. if (isMouseOverButton)
  53679. {
  53680. if (isButtonDown)
  53681. bc = bc.brighter();
  53682. else if (bc.getBrightness() > 0.5f)
  53683. bc = bc.darker (0.1f);
  53684. else
  53685. bc = bc.brighter (0.1f);
  53686. }
  53687. g.setColour (bc);
  53688. g.fillPath (p);
  53689. g.setColour (bc.contrasting().withAlpha ((isMouseOverButton) ? 0.6f : 0.4f));
  53690. g.strokePath (p, PathStrokeType ((isMouseOverButton) ? 2.0f : 1.4f));
  53691. }
  53692. void OldSchoolLookAndFeel::drawTickBox (Graphics& g,
  53693. Component& /*component*/,
  53694. float x, float y, float w, float h,
  53695. const bool ticked,
  53696. const bool isEnabled,
  53697. const bool /*isMouseOverButton*/,
  53698. const bool isButtonDown)
  53699. {
  53700. Path box;
  53701. box.addRoundedRectangle (0.0f, 2.0f, 6.0f, 6.0f, 1.0f);
  53702. g.setColour (isEnabled ? Colours::blue.withAlpha (isButtonDown ? 0.3f : 0.1f)
  53703. : Colours::lightgrey.withAlpha (0.1f));
  53704. AffineTransform trans (AffineTransform::scale (w / 9.0f, h / 9.0f).translated (x, y));
  53705. g.fillPath (box, trans);
  53706. g.setColour (Colours::black.withAlpha (0.6f));
  53707. g.strokePath (box, PathStrokeType (0.9f), trans);
  53708. if (ticked)
  53709. {
  53710. Path tick;
  53711. tick.startNewSubPath (1.5f, 3.0f);
  53712. tick.lineTo (3.0f, 6.0f);
  53713. tick.lineTo (6.0f, 0.0f);
  53714. g.setColour (isEnabled ? Colours::black : Colours::grey);
  53715. g.strokePath (tick, PathStrokeType (2.5f), trans);
  53716. }
  53717. }
  53718. void OldSchoolLookAndFeel::drawToggleButton (Graphics& g,
  53719. ToggleButton& button,
  53720. bool isMouseOverButton,
  53721. bool isButtonDown)
  53722. {
  53723. if (button.hasKeyboardFocus (true))
  53724. {
  53725. g.setColour (button.findColour (TextEditor::focusedOutlineColourId));
  53726. g.drawRect (0, 0, button.getWidth(), button.getHeight());
  53727. }
  53728. const int tickWidth = jmin (20, button.getHeight() - 4);
  53729. drawTickBox (g, button, 4.0f, (button.getHeight() - tickWidth) * 0.5f,
  53730. (float) tickWidth, (float) tickWidth,
  53731. button.getToggleState(),
  53732. button.isEnabled(),
  53733. isMouseOverButton,
  53734. isButtonDown);
  53735. g.setColour (button.findColour (ToggleButton::textColourId));
  53736. g.setFont (jmin (15.0f, button.getHeight() * 0.6f));
  53737. if (! button.isEnabled())
  53738. g.setOpacity (0.5f);
  53739. const int textX = tickWidth + 5;
  53740. g.drawFittedText (button.getButtonText(),
  53741. textX, 4,
  53742. button.getWidth() - textX - 2, button.getHeight() - 8,
  53743. Justification::centredLeft, 10);
  53744. }
  53745. void OldSchoolLookAndFeel::drawProgressBar (Graphics& g, ProgressBar& progressBar,
  53746. int width, int height,
  53747. double progress, const String& textToShow)
  53748. {
  53749. if (progress < 0 || progress >= 1.0)
  53750. {
  53751. LookAndFeel::drawProgressBar (g, progressBar, width, height, progress, textToShow);
  53752. }
  53753. else
  53754. {
  53755. const Colour background (progressBar.findColour (ProgressBar::backgroundColourId));
  53756. const Colour foreground (progressBar.findColour (ProgressBar::foregroundColourId));
  53757. g.fillAll (background);
  53758. g.setColour (foreground);
  53759. g.fillRect (1, 1,
  53760. jlimit (0, width - 2, roundToInt (progress * (width - 2))),
  53761. height - 2);
  53762. if (textToShow.isNotEmpty())
  53763. {
  53764. g.setColour (Colour::contrasting (background, foreground));
  53765. g.setFont (height * 0.6f);
  53766. g.drawText (textToShow, 0, 0, width, height, Justification::centred, false);
  53767. }
  53768. }
  53769. }
  53770. void OldSchoolLookAndFeel::drawScrollbarButton (Graphics& g,
  53771. ScrollBar& bar,
  53772. int width, int height,
  53773. int buttonDirection,
  53774. bool isScrollbarVertical,
  53775. bool isMouseOverButton,
  53776. bool isButtonDown)
  53777. {
  53778. if (isScrollbarVertical)
  53779. width -= 2;
  53780. else
  53781. height -= 2;
  53782. Path p;
  53783. if (buttonDirection == 0)
  53784. p.addTriangle (width * 0.5f, height * 0.2f,
  53785. width * 0.1f, height * 0.7f,
  53786. width * 0.9f, height * 0.7f);
  53787. else if (buttonDirection == 1)
  53788. p.addTriangle (width * 0.8f, height * 0.5f,
  53789. width * 0.3f, height * 0.1f,
  53790. width * 0.3f, height * 0.9f);
  53791. else if (buttonDirection == 2)
  53792. p.addTriangle (width * 0.5f, height * 0.8f,
  53793. width * 0.1f, height * 0.3f,
  53794. width * 0.9f, height * 0.3f);
  53795. else if (buttonDirection == 3)
  53796. p.addTriangle (width * 0.2f, height * 0.5f,
  53797. width * 0.7f, height * 0.1f,
  53798. width * 0.7f, height * 0.9f);
  53799. if (isButtonDown)
  53800. g.setColour (Colours::white);
  53801. else if (isMouseOverButton)
  53802. g.setColour (Colours::white.withAlpha (0.7f));
  53803. else
  53804. g.setColour (bar.findColour (ScrollBar::thumbColourId).withAlpha (0.5f));
  53805. g.fillPath (p);
  53806. g.setColour (Colours::black.withAlpha (0.5f));
  53807. g.strokePath (p, PathStrokeType (0.5f));
  53808. }
  53809. void OldSchoolLookAndFeel::drawScrollbar (Graphics& g,
  53810. ScrollBar& bar,
  53811. int x, int y,
  53812. int width, int height,
  53813. bool isScrollbarVertical,
  53814. int thumbStartPosition,
  53815. int thumbSize,
  53816. bool isMouseOver,
  53817. bool isMouseDown)
  53818. {
  53819. g.fillAll (bar.findColour (ScrollBar::backgroundColourId));
  53820. g.setColour (bar.findColour (ScrollBar::thumbColourId)
  53821. .withAlpha ((isMouseOver || isMouseDown) ? 0.4f : 0.15f));
  53822. if (thumbSize > 0.0f)
  53823. {
  53824. Rectangle<int> thumb;
  53825. if (isScrollbarVertical)
  53826. {
  53827. width -= 2;
  53828. g.fillRect (x + roundToInt (width * 0.35f), y,
  53829. roundToInt (width * 0.3f), height);
  53830. thumb.setBounds (x + 1, thumbStartPosition,
  53831. width - 2, thumbSize);
  53832. }
  53833. else
  53834. {
  53835. height -= 2;
  53836. g.fillRect (x, y + roundToInt (height * 0.35f),
  53837. width, roundToInt (height * 0.3f));
  53838. thumb.setBounds (thumbStartPosition, y + 1,
  53839. thumbSize, height - 2);
  53840. }
  53841. g.setColour (bar.findColour (ScrollBar::thumbColourId)
  53842. .withAlpha ((isMouseOver || isMouseDown) ? 0.95f : 0.7f));
  53843. g.fillRect (thumb);
  53844. g.setColour (Colours::black.withAlpha ((isMouseOver || isMouseDown) ? 0.4f : 0.25f));
  53845. g.drawRect (thumb.getX(), thumb.getY(), thumb.getWidth(), thumb.getHeight());
  53846. if (thumbSize > 16)
  53847. {
  53848. for (int i = 3; --i >= 0;)
  53849. {
  53850. const float linePos = thumbStartPosition + thumbSize / 2 + (i - 1) * 4.0f;
  53851. g.setColour (Colours::black.withAlpha (0.15f));
  53852. if (isScrollbarVertical)
  53853. {
  53854. g.drawLine (x + width * 0.2f, linePos, width * 0.8f, linePos);
  53855. g.setColour (Colours::white.withAlpha (0.15f));
  53856. g.drawLine (width * 0.2f, linePos - 1, width * 0.8f, linePos - 1);
  53857. }
  53858. else
  53859. {
  53860. g.drawLine (linePos, height * 0.2f, linePos, height * 0.8f);
  53861. g.setColour (Colours::white.withAlpha (0.15f));
  53862. g.drawLine (linePos - 1, height * 0.2f, linePos - 1, height * 0.8f);
  53863. }
  53864. }
  53865. }
  53866. }
  53867. }
  53868. ImageEffectFilter* OldSchoolLookAndFeel::getScrollbarEffect()
  53869. {
  53870. return &scrollbarShadow;
  53871. }
  53872. void OldSchoolLookAndFeel::drawPopupMenuBackground (Graphics& g, int width, int height)
  53873. {
  53874. g.fillAll (findColour (PopupMenu::backgroundColourId));
  53875. g.setColour (Colours::black.withAlpha (0.6f));
  53876. g.drawRect (0, 0, width, height);
  53877. }
  53878. void OldSchoolLookAndFeel::drawMenuBarBackground (Graphics& g, int /*width*/, int /*height*/,
  53879. bool, MenuBarComponent& menuBar)
  53880. {
  53881. g.fillAll (menuBar.findColour (PopupMenu::backgroundColourId));
  53882. }
  53883. void OldSchoolLookAndFeel::drawTextEditorOutline (Graphics& g, int width, int height, TextEditor& textEditor)
  53884. {
  53885. if (textEditor.isEnabled())
  53886. {
  53887. g.setColour (textEditor.findColour (TextEditor::outlineColourId));
  53888. g.drawRect (0, 0, width, height);
  53889. }
  53890. }
  53891. void OldSchoolLookAndFeel::drawComboBox (Graphics& g, int width, int height,
  53892. const bool isButtonDown,
  53893. int buttonX, int buttonY,
  53894. int buttonW, int buttonH,
  53895. ComboBox& box)
  53896. {
  53897. g.fillAll (box.findColour (ComboBox::backgroundColourId));
  53898. g.setColour (box.findColour ((isButtonDown) ? ComboBox::buttonColourId
  53899. : ComboBox::backgroundColourId));
  53900. g.fillRect (buttonX, buttonY, buttonW, buttonH);
  53901. g.setColour (box.findColour (ComboBox::outlineColourId));
  53902. g.drawRect (0, 0, width, height);
  53903. const float arrowX = 0.2f;
  53904. const float arrowH = 0.3f;
  53905. if (box.isEnabled())
  53906. {
  53907. Path p;
  53908. p.addTriangle (buttonX + buttonW * 0.5f, buttonY + buttonH * (0.45f - arrowH),
  53909. buttonX + buttonW * (1.0f - arrowX), buttonY + buttonH * 0.45f,
  53910. buttonX + buttonW * arrowX, buttonY + buttonH * 0.45f);
  53911. p.addTriangle (buttonX + buttonW * 0.5f, buttonY + buttonH * (0.55f + arrowH),
  53912. buttonX + buttonW * (1.0f - arrowX), buttonY + buttonH * 0.55f,
  53913. buttonX + buttonW * arrowX, buttonY + buttonH * 0.55f);
  53914. g.setColour (box.findColour ((isButtonDown) ? ComboBox::backgroundColourId
  53915. : ComboBox::buttonColourId));
  53916. g.fillPath (p);
  53917. }
  53918. }
  53919. const Font OldSchoolLookAndFeel::getComboBoxFont (ComboBox& box)
  53920. {
  53921. Font f (jmin (15.0f, box.getHeight() * 0.85f));
  53922. f.setHorizontalScale (0.9f);
  53923. return f;
  53924. }
  53925. static void drawTriangle (Graphics& g, float x1, float y1, float x2, float y2, float x3, float y3, const Colour& fill, const Colour& outline) throw()
  53926. {
  53927. Path p;
  53928. p.addTriangle (x1, y1, x2, y2, x3, y3);
  53929. g.setColour (fill);
  53930. g.fillPath (p);
  53931. g.setColour (outline);
  53932. g.strokePath (p, PathStrokeType (0.3f));
  53933. }
  53934. void OldSchoolLookAndFeel::drawLinearSlider (Graphics& g,
  53935. int x, int y,
  53936. int w, int h,
  53937. float sliderPos,
  53938. float minSliderPos,
  53939. float maxSliderPos,
  53940. const Slider::SliderStyle style,
  53941. Slider& slider)
  53942. {
  53943. g.fillAll (slider.findColour (Slider::backgroundColourId));
  53944. if (style == Slider::LinearBar)
  53945. {
  53946. g.setColour (slider.findColour (Slider::thumbColourId));
  53947. g.fillRect (x, y, (int) sliderPos - x, h);
  53948. g.setColour (slider.findColour (Slider::textBoxTextColourId).withMultipliedAlpha (0.5f));
  53949. g.drawRect (x, y, (int) sliderPos - x, h);
  53950. }
  53951. else
  53952. {
  53953. g.setColour (slider.findColour (Slider::trackColourId)
  53954. .withMultipliedAlpha (slider.isEnabled() ? 1.0f : 0.3f));
  53955. if (slider.isHorizontal())
  53956. {
  53957. g.fillRect (x, y + roundToInt (h * 0.6f),
  53958. w, roundToInt (h * 0.2f));
  53959. }
  53960. else
  53961. {
  53962. g.fillRect (x + roundToInt (w * 0.5f - jmin (3.0f, w * 0.1f)), y,
  53963. jmin (4, roundToInt (w * 0.2f)), h);
  53964. }
  53965. float alpha = 0.35f;
  53966. if (slider.isEnabled())
  53967. alpha = slider.isMouseOverOrDragging() ? 1.0f : 0.7f;
  53968. const Colour fill (slider.findColour (Slider::thumbColourId).withAlpha (alpha));
  53969. const Colour outline (Colours::black.withAlpha (slider.isEnabled() ? 0.7f : 0.35f));
  53970. if (style == Slider::TwoValueVertical || style == Slider::ThreeValueVertical)
  53971. {
  53972. drawTriangle (g, x + w * 0.5f + jmin (4.0f, w * 0.3f), minSliderPos,
  53973. x + w * 0.5f - jmin (8.0f, w * 0.4f), minSliderPos - 7.0f,
  53974. x + w * 0.5f - jmin (8.0f, w * 0.4f), minSliderPos,
  53975. fill, outline);
  53976. drawTriangle (g, x + w * 0.5f + jmin (4.0f, w * 0.3f), maxSliderPos,
  53977. x + w * 0.5f - jmin (8.0f, w * 0.4f), maxSliderPos,
  53978. x + w * 0.5f - jmin (8.0f, w * 0.4f), maxSliderPos + 7.0f,
  53979. fill, outline);
  53980. }
  53981. else if (style == Slider::TwoValueHorizontal || style == Slider::ThreeValueHorizontal)
  53982. {
  53983. drawTriangle (g, minSliderPos, y + h * 0.6f - jmin (4.0f, h * 0.3f),
  53984. minSliderPos - 7.0f, y + h * 0.9f ,
  53985. minSliderPos, y + h * 0.9f,
  53986. fill, outline);
  53987. drawTriangle (g, maxSliderPos, y + h * 0.6f - jmin (4.0f, h * 0.3f),
  53988. maxSliderPos, y + h * 0.9f,
  53989. maxSliderPos + 7.0f, y + h * 0.9f,
  53990. fill, outline);
  53991. }
  53992. if (style == Slider::LinearHorizontal || style == Slider::ThreeValueHorizontal)
  53993. {
  53994. drawTriangle (g, sliderPos, y + h * 0.9f,
  53995. sliderPos - 7.0f, y + h * 0.2f,
  53996. sliderPos + 7.0f, y + h * 0.2f,
  53997. fill, outline);
  53998. }
  53999. else if (style == Slider::LinearVertical || style == Slider::ThreeValueVertical)
  54000. {
  54001. drawTriangle (g, x + w * 0.5f - jmin (4.0f, w * 0.3f), sliderPos,
  54002. x + w * 0.5f + jmin (8.0f, w * 0.4f), sliderPos - 7.0f,
  54003. x + w * 0.5f + jmin (8.0f, w * 0.4f), sliderPos + 7.0f,
  54004. fill, outline);
  54005. }
  54006. }
  54007. }
  54008. Button* OldSchoolLookAndFeel::createSliderButton (const bool isIncrement)
  54009. {
  54010. if (isIncrement)
  54011. return new ArrowButton ("u", 0.75f, Colours::white.withAlpha (0.8f));
  54012. else
  54013. return new ArrowButton ("d", 0.25f, Colours::white.withAlpha (0.8f));
  54014. }
  54015. ImageEffectFilter* OldSchoolLookAndFeel::getSliderEffect()
  54016. {
  54017. return &scrollbarShadow;
  54018. }
  54019. int OldSchoolLookAndFeel::getSliderThumbRadius (Slider&)
  54020. {
  54021. return 8;
  54022. }
  54023. void OldSchoolLookAndFeel::drawCornerResizer (Graphics& g,
  54024. int w, int h,
  54025. bool isMouseOver,
  54026. bool isMouseDragging)
  54027. {
  54028. g.setColour ((isMouseOver || isMouseDragging) ? Colours::lightgrey
  54029. : Colours::darkgrey);
  54030. const float lineThickness = jmin (w, h) * 0.1f;
  54031. for (float i = 0.0f; i < 1.0f; i += 0.3f)
  54032. {
  54033. g.drawLine (w * i,
  54034. h + 1.0f,
  54035. w + 1.0f,
  54036. h * i,
  54037. lineThickness);
  54038. }
  54039. }
  54040. Button* OldSchoolLookAndFeel::createDocumentWindowButton (int buttonType)
  54041. {
  54042. Path shape;
  54043. if (buttonType == DocumentWindow::closeButton)
  54044. {
  54045. shape.addLineSegment (0.0f, 0.0f, 1.0f, 1.0f, 0.35f);
  54046. shape.addLineSegment (1.0f, 0.0f, 0.0f, 1.0f, 0.35f);
  54047. ShapeButton* const b = new ShapeButton ("close",
  54048. Colour (0x7fff3333),
  54049. Colour (0xd7ff3333),
  54050. Colour (0xf7ff3333));
  54051. b->setShape (shape, true, true, true);
  54052. return b;
  54053. }
  54054. else if (buttonType == DocumentWindow::minimiseButton)
  54055. {
  54056. shape.addLineSegment (0.0f, 0.5f, 1.0f, 0.5f, 0.25f);
  54057. DrawableButton* b = new DrawableButton ("minimise", DrawableButton::ImageFitted);
  54058. DrawablePath dp;
  54059. dp.setPath (shape);
  54060. dp.setFill (Colours::black.withAlpha (0.3f));
  54061. b->setImages (&dp);
  54062. return b;
  54063. }
  54064. else if (buttonType == DocumentWindow::maximiseButton)
  54065. {
  54066. shape.addLineSegment (0.5f, 0.0f, 0.5f, 1.0f, 0.25f);
  54067. shape.addLineSegment (0.0f, 0.5f, 1.0f, 0.5f, 0.25f);
  54068. DrawableButton* b = new DrawableButton ("maximise", DrawableButton::ImageFitted);
  54069. DrawablePath dp;
  54070. dp.setPath (shape);
  54071. dp.setFill (Colours::black.withAlpha (0.3f));
  54072. b->setImages (&dp);
  54073. return b;
  54074. }
  54075. jassertfalse
  54076. return 0;
  54077. }
  54078. void OldSchoolLookAndFeel::positionDocumentWindowButtons (DocumentWindow&,
  54079. int titleBarX,
  54080. int titleBarY,
  54081. int titleBarW,
  54082. int titleBarH,
  54083. Button* minimiseButton,
  54084. Button* maximiseButton,
  54085. Button* closeButton,
  54086. bool positionTitleBarButtonsOnLeft)
  54087. {
  54088. titleBarY += titleBarH / 8;
  54089. titleBarH -= titleBarH / 4;
  54090. const int buttonW = titleBarH;
  54091. int x = positionTitleBarButtonsOnLeft ? titleBarX + 4
  54092. : titleBarX + titleBarW - buttonW - 4;
  54093. if (closeButton != 0)
  54094. {
  54095. closeButton->setBounds (x, titleBarY, buttonW, titleBarH);
  54096. x += positionTitleBarButtonsOnLeft ? buttonW + buttonW / 5
  54097. : -(buttonW + buttonW / 5);
  54098. }
  54099. if (positionTitleBarButtonsOnLeft)
  54100. swapVariables (minimiseButton, maximiseButton);
  54101. if (maximiseButton != 0)
  54102. {
  54103. maximiseButton->setBounds (x, titleBarY - 2, buttonW, titleBarH);
  54104. x += positionTitleBarButtonsOnLeft ? buttonW : -buttonW;
  54105. }
  54106. if (minimiseButton != 0)
  54107. minimiseButton->setBounds (x, titleBarY - 2, buttonW, titleBarH);
  54108. }
  54109. END_JUCE_NAMESPACE
  54110. /*** End of inlined file: juce_OldSchoolLookAndFeel.cpp ***/
  54111. /*** Start of inlined file: juce_MenuBarComponent.cpp ***/
  54112. BEGIN_JUCE_NAMESPACE
  54113. class DummyMenuComponent : public Component
  54114. {
  54115. DummyMenuComponent (const DummyMenuComponent&);
  54116. DummyMenuComponent& operator= (const DummyMenuComponent&);
  54117. public:
  54118. DummyMenuComponent() {}
  54119. ~DummyMenuComponent() {}
  54120. void inputAttemptWhenModal()
  54121. {
  54122. exitModalState (0);
  54123. }
  54124. };
  54125. MenuBarComponent::MenuBarComponent (MenuBarModel* model_)
  54126. : model (0),
  54127. itemUnderMouse (-1),
  54128. currentPopupIndex (-1),
  54129. indexToShowAgain (-1),
  54130. lastMouseX (0),
  54131. lastMouseY (0),
  54132. inModalState (false)
  54133. {
  54134. setRepaintsOnMouseActivity (true);
  54135. setWantsKeyboardFocus (false);
  54136. setMouseClickGrabsKeyboardFocus (false);
  54137. setModel (model_);
  54138. }
  54139. MenuBarComponent::~MenuBarComponent()
  54140. {
  54141. setModel (0);
  54142. Desktop::getInstance().removeGlobalMouseListener (this);
  54143. currentPopup = 0;
  54144. }
  54145. void MenuBarComponent::setModel (MenuBarModel* const newModel)
  54146. {
  54147. if (model != newModel)
  54148. {
  54149. if (model != 0)
  54150. model->removeListener (this);
  54151. model = newModel;
  54152. if (model != 0)
  54153. model->addListener (this);
  54154. repaint();
  54155. menuBarItemsChanged (0);
  54156. }
  54157. }
  54158. void MenuBarComponent::paint (Graphics& g)
  54159. {
  54160. const bool isMouseOverBar = currentPopupIndex >= 0 || itemUnderMouse >= 0 || isMouseOver();
  54161. getLookAndFeel().drawMenuBarBackground (g,
  54162. getWidth(),
  54163. getHeight(),
  54164. isMouseOverBar,
  54165. *this);
  54166. if (model != 0)
  54167. {
  54168. for (int i = 0; i < menuNames.size(); ++i)
  54169. {
  54170. g.saveState();
  54171. g.setOrigin (xPositions [i], 0);
  54172. g.reduceClipRegion (0, 0, xPositions[i + 1] - xPositions[i], getHeight());
  54173. getLookAndFeel().drawMenuBarItem (g,
  54174. xPositions[i + 1] - xPositions[i],
  54175. getHeight(),
  54176. i,
  54177. menuNames[i],
  54178. i == itemUnderMouse,
  54179. i == currentPopupIndex,
  54180. isMouseOverBar,
  54181. *this);
  54182. g.restoreState();
  54183. }
  54184. }
  54185. }
  54186. void MenuBarComponent::resized()
  54187. {
  54188. xPositions.clear();
  54189. int x = 2;
  54190. xPositions.add (x);
  54191. for (int i = 0; i < menuNames.size(); ++i)
  54192. {
  54193. x += getLookAndFeel().getMenuBarItemWidth (*this, i, menuNames[i]);
  54194. xPositions.add (x);
  54195. }
  54196. }
  54197. int MenuBarComponent::getItemAt (const int x, const int y)
  54198. {
  54199. for (int i = 0; i < xPositions.size(); ++i)
  54200. if (x >= xPositions[i] && x < xPositions[i + 1])
  54201. return reallyContains (x, y, true) ? i : -1;
  54202. return -1;
  54203. }
  54204. void MenuBarComponent::repaintMenuItem (int index)
  54205. {
  54206. if (((unsigned int) index) < (unsigned int) xPositions.size())
  54207. {
  54208. const int x1 = xPositions [index];
  54209. const int x2 = xPositions [index + 1];
  54210. repaint (x1 - 2, 0, x2 - x1 + 4, getHeight());
  54211. }
  54212. }
  54213. void MenuBarComponent::updateItemUnderMouse (int x, int y)
  54214. {
  54215. const int newItem = getItemAt (x, y);
  54216. if (itemUnderMouse != newItem)
  54217. {
  54218. repaintMenuItem (itemUnderMouse);
  54219. itemUnderMouse = newItem;
  54220. repaintMenuItem (itemUnderMouse);
  54221. }
  54222. }
  54223. void MenuBarComponent::hideCurrentMenu()
  54224. {
  54225. currentPopup = 0;
  54226. repaint();
  54227. }
  54228. void MenuBarComponent::showMenu (int index)
  54229. {
  54230. if (index != currentPopupIndex)
  54231. {
  54232. if (inModalState)
  54233. {
  54234. hideCurrentMenu();
  54235. indexToShowAgain = index;
  54236. return;
  54237. }
  54238. indexToShowAgain = -1;
  54239. currentPopupIndex = -1;
  54240. itemUnderMouse = index;
  54241. currentPopup = 0;
  54242. menuBarItemsChanged (0);
  54243. Component::SafePointer<Component> prevFocused (getCurrentlyFocusedComponent());
  54244. Component::SafePointer<Component> deletionChecker (this);
  54245. enterModalState (false);
  54246. inModalState = true;
  54247. int result = 0;
  54248. ApplicationCommandManager* managerOfChosenCommand = 0;
  54249. Desktop::getInstance().addGlobalMouseListener (this);
  54250. for (;;)
  54251. {
  54252. const int x = getScreenX() + xPositions [itemUnderMouse];
  54253. const int w = xPositions [itemUnderMouse + 1] - xPositions [itemUnderMouse];
  54254. currentPopupIndex = itemUnderMouse;
  54255. indexToShowAgain = -1;
  54256. repaint();
  54257. if (((unsigned int) itemUnderMouse) < (unsigned int) menuNames.size())
  54258. {
  54259. PopupMenu m (model->getMenuForIndex (itemUnderMouse,
  54260. menuNames [itemUnderMouse]));
  54261. if (m.lookAndFeel == 0)
  54262. m.setLookAndFeel (&getLookAndFeel());
  54263. currentPopup = m.createMenuComponent (x, getScreenY(),
  54264. w, getHeight(),
  54265. 0, w, 0, 0,
  54266. true, this,
  54267. &managerOfChosenCommand,
  54268. this);
  54269. }
  54270. if (currentPopup == 0)
  54271. {
  54272. currentPopup = new DummyMenuComponent();
  54273. addAndMakeVisible (currentPopup);
  54274. }
  54275. currentPopup->enterModalState (false);
  54276. currentPopup->toFront (false); // need to do this after making it modal, or it could
  54277. // be stuck behind other comps that are already modal..
  54278. result = currentPopup->runModalLoop();
  54279. if (deletionChecker == 0)
  54280. return;
  54281. const int lastPopupIndex = currentPopupIndex;
  54282. currentPopup = 0;
  54283. currentPopupIndex = -1;
  54284. if (result != 0)
  54285. {
  54286. topLevelIndexClicked = lastPopupIndex;
  54287. break;
  54288. }
  54289. else if (indexToShowAgain >= 0)
  54290. {
  54291. menuBarItemsChanged (0);
  54292. repaint();
  54293. itemUnderMouse = indexToShowAgain;
  54294. if (((unsigned int) itemUnderMouse) >= (unsigned int) menuNames.size())
  54295. break;
  54296. }
  54297. else
  54298. {
  54299. break;
  54300. }
  54301. }
  54302. Desktop::getInstance().removeGlobalMouseListener (this);
  54303. inModalState = false;
  54304. exitModalState (0);
  54305. if (prevFocused != 0)
  54306. prevFocused->grabKeyboardFocus();
  54307. const Point<int> mousePos (getMouseXYRelative());
  54308. updateItemUnderMouse (mousePos.getX(), mousePos.getY());
  54309. repaint();
  54310. if (result != 0)
  54311. {
  54312. if (managerOfChosenCommand != 0)
  54313. {
  54314. ApplicationCommandTarget::InvocationInfo info (result);
  54315. info.invocationMethod = ApplicationCommandTarget::InvocationInfo::fromMenu;
  54316. managerOfChosenCommand->invoke (info, true);
  54317. }
  54318. postCommandMessage (result);
  54319. }
  54320. }
  54321. }
  54322. void MenuBarComponent::handleCommandMessage (int commandId)
  54323. {
  54324. if (model != 0)
  54325. model->menuItemSelected (commandId, topLevelIndexClicked);
  54326. }
  54327. void MenuBarComponent::mouseEnter (const MouseEvent& e)
  54328. {
  54329. if (e.eventComponent == this)
  54330. updateItemUnderMouse (e.x, e.y);
  54331. }
  54332. void MenuBarComponent::mouseExit (const MouseEvent& e)
  54333. {
  54334. if (e.eventComponent == this)
  54335. updateItemUnderMouse (e.x, e.y);
  54336. }
  54337. void MenuBarComponent::mouseDown (const MouseEvent& e)
  54338. {
  54339. if (currentPopupIndex < 0)
  54340. {
  54341. const MouseEvent e2 (e.getEventRelativeTo (this));
  54342. updateItemUnderMouse (e2.x, e2.y);
  54343. currentPopupIndex = -2;
  54344. showMenu (itemUnderMouse);
  54345. }
  54346. }
  54347. void MenuBarComponent::mouseDrag (const MouseEvent& e)
  54348. {
  54349. const MouseEvent e2 (e.getEventRelativeTo (this));
  54350. const int item = getItemAt (e2.x, e2.y);
  54351. if (item >= 0)
  54352. showMenu (item);
  54353. }
  54354. void MenuBarComponent::mouseUp (const MouseEvent& e)
  54355. {
  54356. const MouseEvent e2 (e.getEventRelativeTo (this));
  54357. updateItemUnderMouse (e2.x, e2.y);
  54358. if (itemUnderMouse < 0 && dynamic_cast <DummyMenuComponent*> (static_cast <Component*> (currentPopup)) != 0)
  54359. hideCurrentMenu();
  54360. }
  54361. void MenuBarComponent::mouseMove (const MouseEvent& e)
  54362. {
  54363. const MouseEvent e2 (e.getEventRelativeTo (this));
  54364. if (lastMouseX != e2.x || lastMouseY != e2.y)
  54365. {
  54366. if (currentPopupIndex >= 0)
  54367. {
  54368. const int item = getItemAt (e2.x, e2.y);
  54369. if (item >= 0)
  54370. showMenu (item);
  54371. }
  54372. else
  54373. {
  54374. updateItemUnderMouse (e2.x, e2.y);
  54375. }
  54376. lastMouseX = e2.x;
  54377. lastMouseY = e2.y;
  54378. }
  54379. }
  54380. bool MenuBarComponent::keyPressed (const KeyPress& key)
  54381. {
  54382. bool used = false;
  54383. const int numMenus = menuNames.size();
  54384. const int currentIndex = jlimit (0, menuNames.size() - 1, currentPopupIndex);
  54385. if (key.isKeyCode (KeyPress::leftKey))
  54386. {
  54387. showMenu ((currentIndex + numMenus - 1) % numMenus);
  54388. used = true;
  54389. }
  54390. else if (key.isKeyCode (KeyPress::rightKey))
  54391. {
  54392. showMenu ((currentIndex + 1) % numMenus);
  54393. used = true;
  54394. }
  54395. return used;
  54396. }
  54397. void MenuBarComponent::inputAttemptWhenModal()
  54398. {
  54399. hideCurrentMenu();
  54400. }
  54401. void MenuBarComponent::menuBarItemsChanged (MenuBarModel* /*menuBarModel*/)
  54402. {
  54403. StringArray newNames;
  54404. if (model != 0)
  54405. newNames = model->getMenuBarNames();
  54406. if (newNames != menuNames)
  54407. {
  54408. menuNames = newNames;
  54409. repaint();
  54410. resized();
  54411. }
  54412. }
  54413. void MenuBarComponent::menuCommandInvoked (MenuBarModel* /*menuBarModel*/,
  54414. const ApplicationCommandTarget::InvocationInfo& info)
  54415. {
  54416. if (model == 0
  54417. || (info.commandFlags & ApplicationCommandInfo::dontTriggerVisualFeedback) != 0)
  54418. return;
  54419. for (int i = 0; i < menuNames.size(); ++i)
  54420. {
  54421. const PopupMenu menu (model->getMenuForIndex (i, menuNames [i]));
  54422. if (menu.containsCommandItem (info.commandID))
  54423. {
  54424. itemUnderMouse = i;
  54425. repaintMenuItem (i);
  54426. startTimer (200);
  54427. break;
  54428. }
  54429. }
  54430. }
  54431. void MenuBarComponent::timerCallback()
  54432. {
  54433. stopTimer();
  54434. const Point<int> mousePos (getMouseXYRelative());
  54435. updateItemUnderMouse (mousePos.getX(), mousePos.getY());
  54436. }
  54437. END_JUCE_NAMESPACE
  54438. /*** End of inlined file: juce_MenuBarComponent.cpp ***/
  54439. /*** Start of inlined file: juce_MenuBarModel.cpp ***/
  54440. BEGIN_JUCE_NAMESPACE
  54441. MenuBarModel::MenuBarModel() throw()
  54442. : manager (0)
  54443. {
  54444. }
  54445. MenuBarModel::~MenuBarModel()
  54446. {
  54447. setApplicationCommandManagerToWatch (0);
  54448. }
  54449. void MenuBarModel::menuItemsChanged()
  54450. {
  54451. triggerAsyncUpdate();
  54452. }
  54453. void MenuBarModel::setApplicationCommandManagerToWatch (ApplicationCommandManager* const newManager) throw()
  54454. {
  54455. if (manager != newManager)
  54456. {
  54457. if (manager != 0)
  54458. manager->removeListener (this);
  54459. manager = newManager;
  54460. if (manager != 0)
  54461. manager->addListener (this);
  54462. }
  54463. }
  54464. void MenuBarModel::addListener (MenuBarModelListener* const newListener) throw()
  54465. {
  54466. listeners.add (newListener);
  54467. }
  54468. void MenuBarModel::removeListener (MenuBarModelListener* const listenerToRemove) throw()
  54469. {
  54470. // Trying to remove a listener that isn't on the list!
  54471. // If this assertion happens because this object is a dangling pointer, make sure you've not
  54472. // deleted this menu model while it's still being used by something (e.g. by a MenuBarComponent)
  54473. jassert (listeners.contains (listenerToRemove));
  54474. listeners.remove (listenerToRemove);
  54475. }
  54476. void MenuBarModel::handleAsyncUpdate()
  54477. {
  54478. listeners.call (&MenuBarModelListener::menuBarItemsChanged, this);
  54479. }
  54480. void MenuBarModel::applicationCommandInvoked (const ApplicationCommandTarget::InvocationInfo& info)
  54481. {
  54482. listeners.call (&MenuBarModelListener::menuCommandInvoked, this, info);
  54483. }
  54484. void MenuBarModel::applicationCommandListChanged()
  54485. {
  54486. menuItemsChanged();
  54487. }
  54488. END_JUCE_NAMESPACE
  54489. /*** End of inlined file: juce_MenuBarModel.cpp ***/
  54490. /*** Start of inlined file: juce_PopupMenu.cpp ***/
  54491. BEGIN_JUCE_NAMESPACE
  54492. class PopupMenu::Item
  54493. {
  54494. public:
  54495. Item()
  54496. : itemId (0), active (true), isSeparator (true), isTicked (false),
  54497. usesColour (false), customComp (0), commandManager (0)
  54498. {
  54499. }
  54500. Item (const int itemId_,
  54501. const String& text_,
  54502. const bool active_,
  54503. const bool isTicked_,
  54504. const Image* im,
  54505. const Colour& textColour_,
  54506. const bool usesColour_,
  54507. PopupMenuCustomComponent* const customComp_,
  54508. const PopupMenu* const subMenu_,
  54509. ApplicationCommandManager* const commandManager_)
  54510. : itemId (itemId_), text (text_), textColour (textColour_),
  54511. active (active_), isSeparator (false), isTicked (isTicked_),
  54512. usesColour (usesColour_), customComp (customComp_),
  54513. commandManager (commandManager_)
  54514. {
  54515. if (subMenu_ != 0)
  54516. subMenu = new PopupMenu (*subMenu_);
  54517. if (im != 0)
  54518. image = im->createCopy();
  54519. if (commandManager_ != 0 && itemId_ != 0)
  54520. {
  54521. String shortcutKey;
  54522. Array <KeyPress> keyPresses (commandManager_->getKeyMappings()
  54523. ->getKeyPressesAssignedToCommand (itemId_));
  54524. for (int i = 0; i < keyPresses.size(); ++i)
  54525. {
  54526. const String key (keyPresses.getReference(i).getTextDescription());
  54527. if (shortcutKey.isNotEmpty())
  54528. shortcutKey << ", ";
  54529. if (key.length() == 1)
  54530. shortcutKey << "shortcut: '" << key << '\'';
  54531. else
  54532. shortcutKey << key;
  54533. }
  54534. shortcutKey = shortcutKey.trim();
  54535. if (shortcutKey.isNotEmpty())
  54536. text << "<end>" << shortcutKey;
  54537. }
  54538. }
  54539. Item (const Item& other)
  54540. : itemId (other.itemId),
  54541. text (other.text),
  54542. textColour (other.textColour),
  54543. active (other.active),
  54544. isSeparator (other.isSeparator),
  54545. isTicked (other.isTicked),
  54546. usesColour (other.usesColour),
  54547. customComp (other.customComp),
  54548. commandManager (other.commandManager)
  54549. {
  54550. if (other.subMenu != 0)
  54551. subMenu = new PopupMenu (*(other.subMenu));
  54552. if (other.image != 0)
  54553. image = other.image->createCopy();
  54554. }
  54555. ~Item()
  54556. {
  54557. customComp = 0;
  54558. }
  54559. bool canBeTriggered() const throw()
  54560. {
  54561. return active && ! (isSeparator || (subMenu != 0));
  54562. }
  54563. bool hasActiveSubMenu() const throw()
  54564. {
  54565. return active && (subMenu != 0);
  54566. }
  54567. const int itemId;
  54568. String text;
  54569. const Colour textColour;
  54570. const bool active, isSeparator, isTicked, usesColour;
  54571. ScopedPointer <Image> image;
  54572. ReferenceCountedObjectPtr <PopupMenuCustomComponent> customComp;
  54573. ScopedPointer <PopupMenu> subMenu;
  54574. ApplicationCommandManager* const commandManager;
  54575. juce_UseDebuggingNewOperator
  54576. private:
  54577. Item& operator= (const Item&);
  54578. };
  54579. class PopupMenu::ItemComponent : public Component
  54580. {
  54581. public:
  54582. ItemComponent (const PopupMenu::Item& itemInfo_)
  54583. : itemInfo (itemInfo_),
  54584. isHighlighted (false)
  54585. {
  54586. if (itemInfo.customComp != 0)
  54587. addAndMakeVisible (itemInfo.customComp);
  54588. }
  54589. ~ItemComponent()
  54590. {
  54591. if (itemInfo.customComp != 0)
  54592. removeChildComponent (itemInfo.customComp);
  54593. }
  54594. void getIdealSize (int& idealWidth,
  54595. int& idealHeight,
  54596. const int standardItemHeight)
  54597. {
  54598. if (itemInfo.customComp != 0)
  54599. {
  54600. itemInfo.customComp->getIdealSize (idealWidth, idealHeight);
  54601. }
  54602. else
  54603. {
  54604. getLookAndFeel().getIdealPopupMenuItemSize (itemInfo.text,
  54605. itemInfo.isSeparator,
  54606. standardItemHeight,
  54607. idealWidth,
  54608. idealHeight);
  54609. }
  54610. }
  54611. void paint (Graphics& g)
  54612. {
  54613. if (itemInfo.customComp == 0)
  54614. {
  54615. String mainText (itemInfo.text);
  54616. String endText;
  54617. const int endIndex = mainText.indexOf ("<end>");
  54618. if (endIndex >= 0)
  54619. {
  54620. endText = mainText.substring (endIndex + 5).trim();
  54621. mainText = mainText.substring (0, endIndex);
  54622. }
  54623. getLookAndFeel()
  54624. .drawPopupMenuItem (g, getWidth(), getHeight(),
  54625. itemInfo.isSeparator,
  54626. itemInfo.active,
  54627. isHighlighted,
  54628. itemInfo.isTicked,
  54629. itemInfo.subMenu != 0,
  54630. mainText, endText,
  54631. itemInfo.image,
  54632. itemInfo.usesColour ? &(itemInfo.textColour) : 0);
  54633. }
  54634. }
  54635. void resized()
  54636. {
  54637. if (getNumChildComponents() > 0)
  54638. getChildComponent(0)->setBounds (2, 0, getWidth() - 4, getHeight());
  54639. }
  54640. void setHighlighted (bool shouldBeHighlighted)
  54641. {
  54642. shouldBeHighlighted = shouldBeHighlighted && itemInfo.active;
  54643. if (isHighlighted != shouldBeHighlighted)
  54644. {
  54645. isHighlighted = shouldBeHighlighted;
  54646. if (itemInfo.customComp != 0)
  54647. {
  54648. itemInfo.customComp->isHighlighted = shouldBeHighlighted;
  54649. itemInfo.customComp->repaint();
  54650. }
  54651. repaint();
  54652. }
  54653. }
  54654. PopupMenu::Item itemInfo;
  54655. juce_UseDebuggingNewOperator
  54656. private:
  54657. bool isHighlighted;
  54658. ItemComponent (const ItemComponent&);
  54659. ItemComponent& operator= (const ItemComponent&);
  54660. };
  54661. namespace PopupMenuSettings
  54662. {
  54663. static const int scrollZone = 24;
  54664. static const int borderSize = 2;
  54665. static const int timerInterval = 50;
  54666. static const int dismissCommandId = 0x6287345f;
  54667. }
  54668. class PopupMenu::Window : public Component,
  54669. private Timer
  54670. {
  54671. public:
  54672. Window()
  54673. : Component ("menu"),
  54674. owner (0),
  54675. currentChild (0),
  54676. activeSubMenu (0),
  54677. menuBarComponent (0),
  54678. managerOfChosenCommand (0),
  54679. minimumWidth (0),
  54680. maximumNumColumns (7),
  54681. standardItemHeight (0),
  54682. isOver (false),
  54683. hasBeenOver (false),
  54684. isDown (false),
  54685. needsToScroll (false),
  54686. hideOnExit (false),
  54687. disableMouseMoves (false),
  54688. hasAnyJuceCompHadFocus (false),
  54689. numColumns (0),
  54690. contentHeight (0),
  54691. childYOffset (0),
  54692. timeEnteredCurrentChildComp (0),
  54693. scrollAcceleration (1.0)
  54694. {
  54695. menuCreationTime = lastFocused = lastScroll = Time::getMillisecondCounter();
  54696. setWantsKeyboardFocus (true);
  54697. setMouseClickGrabsKeyboardFocus (false);
  54698. setOpaque (true);
  54699. setAlwaysOnTop (true);
  54700. Desktop::getInstance().addGlobalMouseListener (this);
  54701. getActiveWindows().add (this);
  54702. }
  54703. ~Window()
  54704. {
  54705. getActiveWindows().removeValue (this);
  54706. Desktop::getInstance().removeGlobalMouseListener (this);
  54707. jassert (activeSubMenu == 0 || activeSubMenu->isValidComponent());
  54708. activeSubMenu = 0;
  54709. deleteAllChildren();
  54710. }
  54711. static Window* create (const PopupMenu& menu,
  54712. const bool dismissOnMouseUp,
  54713. Window* const owner_,
  54714. const int minX, const int maxX,
  54715. const int minY, const int maxY,
  54716. const int minimumWidth,
  54717. const int maximumNumColumns,
  54718. const int standardItemHeight,
  54719. const bool alignToRectangle,
  54720. const int itemIdThatMustBeVisible,
  54721. Component* const menuBarComponent,
  54722. ApplicationCommandManager** managerOfChosenCommand,
  54723. Component* const componentAttachedTo)
  54724. {
  54725. if (menu.items.size() > 0)
  54726. {
  54727. int totalItems = 0;
  54728. ScopedPointer <Window> mw (new Window());
  54729. mw->setLookAndFeel (menu.lookAndFeel);
  54730. mw->setWantsKeyboardFocus (false);
  54731. mw->minimumWidth = minimumWidth;
  54732. mw->maximumNumColumns = maximumNumColumns;
  54733. mw->standardItemHeight = standardItemHeight;
  54734. mw->dismissOnMouseUp = dismissOnMouseUp;
  54735. for (int i = 0; i < menu.items.size(); ++i)
  54736. {
  54737. PopupMenu::Item* const item = menu.items.getUnchecked(i);
  54738. mw->addItem (*item);
  54739. ++totalItems;
  54740. }
  54741. if (totalItems > 0)
  54742. {
  54743. mw->owner = owner_;
  54744. mw->menuBarComponent = menuBarComponent;
  54745. mw->managerOfChosenCommand = managerOfChosenCommand;
  54746. mw->componentAttachedTo = componentAttachedTo;
  54747. mw->componentAttachedToOriginal = componentAttachedTo;
  54748. mw->calculateWindowPos (minX, maxX, minY, maxY, alignToRectangle);
  54749. mw->setTopLeftPosition (mw->windowPos.getX(),
  54750. mw->windowPos.getY());
  54751. mw->updateYPositions();
  54752. if (itemIdThatMustBeVisible != 0)
  54753. {
  54754. const int y = minY - mw->windowPos.getY();
  54755. mw->ensureItemIsVisible (itemIdThatMustBeVisible,
  54756. (((unsigned int) y) < (unsigned int) mw->windowPos.getHeight()) ? y : -1);
  54757. }
  54758. mw->resizeToBestWindowPos();
  54759. mw->addToDesktop (ComponentPeer::windowIsTemporary
  54760. | mw->getLookAndFeel().getMenuWindowFlags());
  54761. return mw.release();
  54762. }
  54763. }
  54764. return 0;
  54765. }
  54766. void paint (Graphics& g)
  54767. {
  54768. getLookAndFeel().drawPopupMenuBackground (g, getWidth(), getHeight());
  54769. }
  54770. void paintOverChildren (Graphics& g)
  54771. {
  54772. if (isScrolling())
  54773. {
  54774. LookAndFeel& lf = getLookAndFeel();
  54775. if (isScrollZoneActive (false))
  54776. lf.drawPopupMenuUpDownArrow (g, getWidth(), PopupMenuSettings::scrollZone, true);
  54777. if (isScrollZoneActive (true))
  54778. {
  54779. g.setOrigin (0, getHeight() - PopupMenuSettings::scrollZone);
  54780. lf.drawPopupMenuUpDownArrow (g, getWidth(), PopupMenuSettings::scrollZone, false);
  54781. }
  54782. }
  54783. }
  54784. bool isScrollZoneActive (bool bottomOne) const
  54785. {
  54786. return isScrolling()
  54787. && (bottomOne
  54788. ? childYOffset < contentHeight - windowPos.getHeight()
  54789. : childYOffset > 0);
  54790. }
  54791. void addItem (const PopupMenu::Item& item)
  54792. {
  54793. PopupMenu::ItemComponent* const mic = new PopupMenu::ItemComponent (item);
  54794. addAndMakeVisible (mic);
  54795. int itemW = 80;
  54796. int itemH = 16;
  54797. mic->getIdealSize (itemW, itemH, standardItemHeight);
  54798. mic->setSize (itemW, jlimit (2, 600, itemH));
  54799. mic->addMouseListener (this, false);
  54800. }
  54801. // hide this and all sub-comps
  54802. void hide (const PopupMenu::Item* const item)
  54803. {
  54804. if (isVisible())
  54805. {
  54806. jassert (activeSubMenu == 0 || activeSubMenu->isValidComponent());
  54807. activeSubMenu = 0;
  54808. currentChild = 0;
  54809. exitModalState (item != 0 ? item->itemId : 0);
  54810. setVisible (false);
  54811. if (item != 0
  54812. && item->commandManager != 0
  54813. && item->itemId != 0)
  54814. {
  54815. *managerOfChosenCommand = item->commandManager;
  54816. }
  54817. }
  54818. }
  54819. void dismissMenu (const PopupMenu::Item* const item)
  54820. {
  54821. if (owner != 0)
  54822. {
  54823. owner->dismissMenu (item);
  54824. }
  54825. else
  54826. {
  54827. if (item != 0)
  54828. {
  54829. // need a copy of this on the stack as the one passed in will get deleted during this call
  54830. const PopupMenu::Item mi (*item);
  54831. hide (&mi);
  54832. }
  54833. else
  54834. {
  54835. hide (0);
  54836. }
  54837. }
  54838. }
  54839. void mouseMove (const MouseEvent&)
  54840. {
  54841. timerCallback();
  54842. }
  54843. void mouseDown (const MouseEvent&)
  54844. {
  54845. timerCallback();
  54846. }
  54847. void mouseDrag (const MouseEvent&)
  54848. {
  54849. timerCallback();
  54850. }
  54851. void mouseUp (const MouseEvent&)
  54852. {
  54853. timerCallback();
  54854. }
  54855. void mouseWheelMove (const MouseEvent&, float /*amountX*/, float amountY)
  54856. {
  54857. alterChildYPos (roundToInt (-10.0f * amountY * PopupMenuSettings::scrollZone));
  54858. lastMouse = Point<int> (-1, -1);
  54859. }
  54860. bool keyPressed (const KeyPress& key)
  54861. {
  54862. if (key.isKeyCode (KeyPress::downKey))
  54863. {
  54864. selectNextItem (1);
  54865. }
  54866. else if (key.isKeyCode (KeyPress::upKey))
  54867. {
  54868. selectNextItem (-1);
  54869. }
  54870. else if (key.isKeyCode (KeyPress::leftKey))
  54871. {
  54872. if (owner != 0)
  54873. {
  54874. Component::SafePointer<Window> parentWindow (owner);
  54875. PopupMenu::ItemComponent* currentChildOfParent = parentWindow->currentChild;
  54876. hide (0);
  54877. if (parentWindow != 0)
  54878. parentWindow->setCurrentlyHighlightedChild (currentChildOfParent);
  54879. disableTimerUntilMouseMoves();
  54880. }
  54881. else if (menuBarComponent != 0)
  54882. {
  54883. menuBarComponent->keyPressed (key);
  54884. }
  54885. }
  54886. else if (key.isKeyCode (KeyPress::rightKey))
  54887. {
  54888. disableTimerUntilMouseMoves();
  54889. if (showSubMenuFor (currentChild))
  54890. {
  54891. jassert (activeSubMenu == 0 || activeSubMenu->isValidComponent());
  54892. if (activeSubMenu != 0 && activeSubMenu->isVisible())
  54893. activeSubMenu->selectNextItem (1);
  54894. }
  54895. else if (menuBarComponent != 0)
  54896. {
  54897. menuBarComponent->keyPressed (key);
  54898. }
  54899. }
  54900. else if (key.isKeyCode (KeyPress::returnKey))
  54901. {
  54902. triggerCurrentlyHighlightedItem();
  54903. }
  54904. else if (key.isKeyCode (KeyPress::escapeKey))
  54905. {
  54906. dismissMenu (0);
  54907. }
  54908. else
  54909. {
  54910. return false;
  54911. }
  54912. return true;
  54913. }
  54914. void inputAttemptWhenModal()
  54915. {
  54916. timerCallback();
  54917. if (! isOverAnyMenu())
  54918. {
  54919. if (componentAttachedTo != 0)
  54920. {
  54921. // we want to dismiss the menu, but if we do it synchronously, then
  54922. // the mouse-click will be allowed to pass through. That's good, except
  54923. // when the user clicks on the button that orginally popped the menu up,
  54924. // as they'll expect the menu to go away, and in fact it'll just
  54925. // come back. So only dismiss synchronously if they're not on the original
  54926. // comp that we're attached to.
  54927. const Point<int> mousePos (componentAttachedTo->getMouseXYRelative());
  54928. if (componentAttachedTo->reallyContains (mousePos.getX(), mousePos.getY(), true))
  54929. {
  54930. postCommandMessage (PopupMenuSettings::dismissCommandId); // dismiss asynchrounously
  54931. return;
  54932. }
  54933. }
  54934. dismissMenu (0);
  54935. }
  54936. }
  54937. void handleCommandMessage (int commandId)
  54938. {
  54939. Component::handleCommandMessage (commandId);
  54940. if (commandId == PopupMenuSettings::dismissCommandId)
  54941. dismissMenu (0);
  54942. }
  54943. void timerCallback()
  54944. {
  54945. if (! isVisible())
  54946. return;
  54947. if (componentAttachedTo != componentAttachedToOriginal)
  54948. {
  54949. dismissMenu (0);
  54950. return;
  54951. }
  54952. Window* currentlyModalWindow = dynamic_cast <Window*> (Component::getCurrentlyModalComponent());
  54953. if (currentlyModalWindow != 0 && ! treeContains (currentlyModalWindow))
  54954. return;
  54955. startTimer (PopupMenuSettings::timerInterval); // do this in case it was called from a mouse
  54956. // move rather than a real timer callback
  54957. const Point<int> globalMousePos (Desktop::getMousePosition());
  54958. const Point<int> localMousePos (globalPositionToRelative (globalMousePos));
  54959. const uint32 now = Time::getMillisecondCounter();
  54960. if (now > timeEnteredCurrentChildComp + 100
  54961. && reallyContains (localMousePos.getX(), localMousePos.getY(), true)
  54962. && currentChild->isValidComponent()
  54963. && (! disableMouseMoves)
  54964. && ! (activeSubMenu != 0 && activeSubMenu->isVisible()))
  54965. {
  54966. showSubMenuFor (currentChild);
  54967. }
  54968. if (globalMousePos != lastMouse || now > lastMouseMoveTime + 350)
  54969. {
  54970. highlightItemUnderMouse (globalMousePos, localMousePos);
  54971. }
  54972. bool overScrollArea = false;
  54973. if (isScrolling()
  54974. && (isOver || (isDown && ((unsigned int) localMousePos.getX()) < (unsigned int) getWidth()))
  54975. && ((isScrollZoneActive (false) && localMousePos.getY() < PopupMenuSettings::scrollZone)
  54976. || (isScrollZoneActive (true) && localMousePos.getY() > getHeight() - PopupMenuSettings::scrollZone)))
  54977. {
  54978. if (now > lastScroll + 20)
  54979. {
  54980. scrollAcceleration = jmin (4.0, scrollAcceleration * 1.04);
  54981. int amount = 0;
  54982. for (int i = 0; i < getNumChildComponents() && amount == 0; ++i)
  54983. amount = ((int) scrollAcceleration) * getChildComponent (i)->getHeight();
  54984. alterChildYPos (localMousePos.getY() < PopupMenuSettings::scrollZone ? -amount : amount);
  54985. lastScroll = now;
  54986. }
  54987. overScrollArea = true;
  54988. lastMouse = Point<int> (-1, -1); // trigger a mouse-move
  54989. }
  54990. else
  54991. {
  54992. scrollAcceleration = 1.0;
  54993. }
  54994. const bool wasDown = isDown;
  54995. bool isOverAny = isOverAnyMenu();
  54996. if (hideOnExit && hasBeenOver && (! isOverAny) && activeSubMenu != 0)
  54997. {
  54998. activeSubMenu->updateMouseOverStatus (globalMousePos);
  54999. isOverAny = isOverAnyMenu();
  55000. }
  55001. if (hideOnExit && hasBeenOver && ! isOverAny)
  55002. {
  55003. hide (0);
  55004. }
  55005. else
  55006. {
  55007. isDown = hasBeenOver
  55008. && (ModifierKeys::getCurrentModifiers().isAnyMouseButtonDown()
  55009. || ModifierKeys::getCurrentModifiersRealtime().isAnyMouseButtonDown());
  55010. bool anyFocused = Process::isForegroundProcess();
  55011. if (anyFocused && Component::getCurrentlyFocusedComponent() == 0)
  55012. {
  55013. // because no component at all may have focus, our test here will
  55014. // only be triggered when something has focus and then loses it.
  55015. anyFocused = ! hasAnyJuceCompHadFocus;
  55016. for (int i = ComponentPeer::getNumPeers(); --i >= 0;)
  55017. {
  55018. if (ComponentPeer::getPeer (i)->isFocused())
  55019. {
  55020. anyFocused = true;
  55021. hasAnyJuceCompHadFocus = true;
  55022. break;
  55023. }
  55024. }
  55025. }
  55026. if (! anyFocused)
  55027. {
  55028. if (now > lastFocused + 10)
  55029. {
  55030. wasHiddenBecauseOfAppChange() = true;
  55031. dismissMenu (0);
  55032. return; // may have been deleted by the previous call..
  55033. }
  55034. }
  55035. else if (wasDown && now > menuCreationTime + 250
  55036. && ! (isDown || overScrollArea))
  55037. {
  55038. isOver = reallyContains (localMousePos.getX(), localMousePos.getY(), true);
  55039. if (isOver)
  55040. {
  55041. triggerCurrentlyHighlightedItem();
  55042. }
  55043. else if ((hasBeenOver || ! dismissOnMouseUp) && ! isOverAny)
  55044. {
  55045. dismissMenu (0);
  55046. }
  55047. return; // may have been deleted by the previous calls..
  55048. }
  55049. else
  55050. {
  55051. lastFocused = now;
  55052. }
  55053. }
  55054. }
  55055. static Array<Window*>& getActiveWindows()
  55056. {
  55057. static Array<Window*> activeMenuWindows;
  55058. return activeMenuWindows;
  55059. }
  55060. static bool& wasHiddenBecauseOfAppChange() throw()
  55061. {
  55062. static bool b = false;
  55063. return b;
  55064. }
  55065. juce_UseDebuggingNewOperator
  55066. private:
  55067. Window* owner;
  55068. PopupMenu::ItemComponent* currentChild;
  55069. ScopedPointer <Window> activeSubMenu;
  55070. Component* menuBarComponent;
  55071. ApplicationCommandManager** managerOfChosenCommand;
  55072. Component::SafePointer<Component> componentAttachedTo;
  55073. Component* componentAttachedToOriginal;
  55074. Rectangle<int> windowPos;
  55075. Point<int> lastMouse;
  55076. int minimumWidth, maximumNumColumns, standardItemHeight;
  55077. bool isOver, hasBeenOver, isDown, needsToScroll;
  55078. bool dismissOnMouseUp, hideOnExit, disableMouseMoves, hasAnyJuceCompHadFocus;
  55079. int numColumns, contentHeight, childYOffset;
  55080. Array <int> columnWidths;
  55081. uint32 menuCreationTime, lastFocused, lastScroll, lastMouseMoveTime, timeEnteredCurrentChildComp;
  55082. double scrollAcceleration;
  55083. bool overlaps (const Rectangle<int>& r) const
  55084. {
  55085. return r.intersects (getBounds())
  55086. || (owner != 0 && owner->overlaps (r));
  55087. }
  55088. bool isOverAnyMenu() const
  55089. {
  55090. return (owner != 0) ? owner->isOverAnyMenu()
  55091. : isOverChildren();
  55092. }
  55093. bool isOverChildren() const
  55094. {
  55095. jassert (activeSubMenu == 0 || activeSubMenu->isValidComponent());
  55096. return isVisible()
  55097. && (isOver || (activeSubMenu != 0 && activeSubMenu->isOverChildren()));
  55098. }
  55099. void updateMouseOverStatus (const Point<int>& globalMousePos)
  55100. {
  55101. const Point<int> relPos (globalPositionToRelative (globalMousePos));
  55102. isOver = reallyContains (relPos.getX(), relPos.getY(), true);
  55103. if (activeSubMenu != 0)
  55104. activeSubMenu->updateMouseOverStatus (globalMousePos);
  55105. }
  55106. bool treeContains (const Window* const window) const throw()
  55107. {
  55108. const Window* mw = this;
  55109. while (mw->owner != 0)
  55110. mw = mw->owner;
  55111. while (mw != 0)
  55112. {
  55113. if (mw == window)
  55114. return true;
  55115. mw = mw->activeSubMenu;
  55116. }
  55117. return false;
  55118. }
  55119. void calculateWindowPos (const int minX, const int maxX,
  55120. const int minY, const int maxY,
  55121. const bool alignToRectangle)
  55122. {
  55123. const Rectangle<int> mon (Desktop::getInstance()
  55124. .getMonitorAreaContaining (Point<int> ((minX + maxX) / 2,
  55125. (minY + maxY) / 2),
  55126. #if JUCE_MAC
  55127. true));
  55128. #else
  55129. false)); // on windows, don't stop the menu overlapping the taskbar
  55130. #endif
  55131. int x, y, widthToUse, heightToUse;
  55132. layoutMenuItems (mon.getWidth() - 24, widthToUse, heightToUse);
  55133. if (alignToRectangle)
  55134. {
  55135. x = minX;
  55136. const int spaceUnder = mon.getHeight() - (maxY - mon.getY());
  55137. const int spaceOver = minY - mon.getY();
  55138. if (heightToUse < spaceUnder - 30 || spaceUnder >= spaceOver)
  55139. y = maxY;
  55140. else
  55141. y = minY - heightToUse;
  55142. }
  55143. else
  55144. {
  55145. bool tendTowardsRight = (minX + maxX) / 2 < mon.getCentreX();
  55146. if (owner != 0)
  55147. {
  55148. if (owner->owner != 0)
  55149. {
  55150. const bool ownerGoingRight = (owner->getX() + owner->getWidth() / 2
  55151. > owner->owner->getX() + owner->owner->getWidth() / 2);
  55152. if (ownerGoingRight && maxX + widthToUse < mon.getRight() - 4)
  55153. tendTowardsRight = true;
  55154. else if ((! ownerGoingRight) && minX > widthToUse + 4)
  55155. tendTowardsRight = false;
  55156. }
  55157. else if (maxX + widthToUse < mon.getRight() - 32)
  55158. {
  55159. tendTowardsRight = true;
  55160. }
  55161. }
  55162. const int biggestSpace = jmax (mon.getRight() - maxX,
  55163. minX - mon.getX()) - 32;
  55164. if (biggestSpace < widthToUse)
  55165. {
  55166. layoutMenuItems (biggestSpace + (maxX - minX) / 3, widthToUse, heightToUse);
  55167. if (numColumns > 1)
  55168. layoutMenuItems (biggestSpace - 4, widthToUse, heightToUse);
  55169. tendTowardsRight = (mon.getRight() - maxX) >= (minX - mon.getX());
  55170. }
  55171. if (tendTowardsRight)
  55172. x = jmin (mon.getRight() - widthToUse - 4, maxX);
  55173. else
  55174. x = jmax (mon.getX() + 4, minX - widthToUse);
  55175. y = minY;
  55176. if ((minY + maxY) / 2 > mon.getCentreY())
  55177. y = jmax (mon.getY(), maxY - heightToUse);
  55178. }
  55179. x = jmax (mon.getX() + 1, jmin (mon.getRight() - (widthToUse + 6), x));
  55180. y = jmax (mon.getY() + 1, jmin (mon.getBottom() - (heightToUse + 6), y));
  55181. windowPos.setBounds (x, y, widthToUse, heightToUse);
  55182. // sets this flag if it's big enough to obscure any of its parent menus
  55183. hideOnExit = (owner != 0)
  55184. && owner->windowPos.intersects (windowPos.expanded (-4, -4));
  55185. }
  55186. void layoutMenuItems (const int maxMenuW, int& width, int& height)
  55187. {
  55188. numColumns = 0;
  55189. contentHeight = 0;
  55190. const int maxMenuH = getParentHeight() - 24;
  55191. int totalW;
  55192. do
  55193. {
  55194. ++numColumns;
  55195. totalW = workOutBestSize (maxMenuW);
  55196. if (totalW > maxMenuW)
  55197. {
  55198. numColumns = jmax (1, numColumns - 1);
  55199. totalW = workOutBestSize (maxMenuW); // to update col widths
  55200. break;
  55201. }
  55202. else if (totalW > maxMenuW / 2 || contentHeight < maxMenuH)
  55203. {
  55204. break;
  55205. }
  55206. } while (numColumns < maximumNumColumns);
  55207. const int actualH = jmin (contentHeight, maxMenuH);
  55208. needsToScroll = contentHeight > actualH;
  55209. width = updateYPositions();
  55210. height = actualH + PopupMenuSettings::borderSize * 2;
  55211. }
  55212. int workOutBestSize (const int maxMenuW)
  55213. {
  55214. int totalW = 0;
  55215. contentHeight = 0;
  55216. int childNum = 0;
  55217. for (int col = 0; col < numColumns; ++col)
  55218. {
  55219. int i, colW = 50, colH = 0;
  55220. const int numChildren = jmin (getNumChildComponents() - childNum,
  55221. (getNumChildComponents() + numColumns - 1) / numColumns);
  55222. for (i = numChildren; --i >= 0;)
  55223. {
  55224. colW = jmax (colW, getChildComponent (childNum + i)->getWidth());
  55225. colH += getChildComponent (childNum + i)->getHeight();
  55226. }
  55227. colW = jmin (maxMenuW / jmax (1, numColumns - 2), colW + PopupMenuSettings::borderSize * 2);
  55228. columnWidths.set (col, colW);
  55229. totalW += colW;
  55230. contentHeight = jmax (contentHeight, colH);
  55231. childNum += numChildren;
  55232. }
  55233. if (totalW < minimumWidth)
  55234. {
  55235. totalW = minimumWidth;
  55236. for (int col = 0; col < numColumns; ++col)
  55237. columnWidths.set (0, totalW / numColumns);
  55238. }
  55239. return totalW;
  55240. }
  55241. void ensureItemIsVisible (const int itemId, int wantedY)
  55242. {
  55243. jassert (itemId != 0)
  55244. for (int i = getNumChildComponents(); --i >= 0;)
  55245. {
  55246. PopupMenu::ItemComponent* const m = static_cast <PopupMenu::ItemComponent*> (getChildComponent (i));
  55247. if (m != 0
  55248. && m->itemInfo.itemId == itemId
  55249. && windowPos.getHeight() > PopupMenuSettings::scrollZone * 4)
  55250. {
  55251. const int currentY = m->getY();
  55252. if (wantedY > 0 || currentY < 0 || m->getBottom() > windowPos.getHeight())
  55253. {
  55254. if (wantedY < 0)
  55255. wantedY = jlimit (PopupMenuSettings::scrollZone,
  55256. jmax (PopupMenuSettings::scrollZone,
  55257. windowPos.getHeight() - (PopupMenuSettings::scrollZone + m->getHeight())),
  55258. currentY);
  55259. const Rectangle<int> mon (Desktop::getInstance().getMonitorAreaContaining (windowPos.getPosition(), true));
  55260. int deltaY = wantedY - currentY;
  55261. windowPos.setSize (jmin (windowPos.getWidth(), mon.getWidth()),
  55262. jmin (windowPos.getHeight(), mon.getHeight()));
  55263. const int newY = jlimit (mon.getY(),
  55264. mon.getBottom() - windowPos.getHeight(),
  55265. windowPos.getY() + deltaY);
  55266. deltaY -= newY - windowPos.getY();
  55267. childYOffset -= deltaY;
  55268. windowPos.setPosition (windowPos.getX(), newY);
  55269. updateYPositions();
  55270. }
  55271. break;
  55272. }
  55273. }
  55274. }
  55275. void resizeToBestWindowPos()
  55276. {
  55277. Rectangle<int> r (windowPos);
  55278. if (childYOffset < 0)
  55279. {
  55280. r.setBounds (r.getX(), r.getY() - childYOffset,
  55281. r.getWidth(), r.getHeight() + childYOffset);
  55282. }
  55283. else if (childYOffset > 0)
  55284. {
  55285. const int spaceAtBottom = r.getHeight() - (contentHeight - childYOffset);
  55286. if (spaceAtBottom > 0)
  55287. r.setSize (r.getWidth(), r.getHeight() - spaceAtBottom);
  55288. }
  55289. setBounds (r);
  55290. updateYPositions();
  55291. }
  55292. void alterChildYPos (const int delta)
  55293. {
  55294. if (isScrolling())
  55295. {
  55296. childYOffset += delta;
  55297. if (delta < 0)
  55298. {
  55299. childYOffset = jmax (childYOffset, 0);
  55300. }
  55301. else if (delta > 0)
  55302. {
  55303. childYOffset = jmin (childYOffset,
  55304. contentHeight - windowPos.getHeight() + PopupMenuSettings::borderSize);
  55305. }
  55306. updateYPositions();
  55307. }
  55308. else
  55309. {
  55310. childYOffset = 0;
  55311. }
  55312. resizeToBestWindowPos();
  55313. repaint();
  55314. }
  55315. int updateYPositions()
  55316. {
  55317. int x = 0;
  55318. int childNum = 0;
  55319. for (int col = 0; col < numColumns; ++col)
  55320. {
  55321. const int numChildren = jmin (getNumChildComponents() - childNum,
  55322. (getNumChildComponents() + numColumns - 1) / numColumns);
  55323. const int colW = columnWidths [col];
  55324. int y = PopupMenuSettings::borderSize - (childYOffset + (getY() - windowPos.getY()));
  55325. for (int i = 0; i < numChildren; ++i)
  55326. {
  55327. Component* const c = getChildComponent (childNum + i);
  55328. c->setBounds (x, y, colW, c->getHeight());
  55329. y += c->getHeight();
  55330. }
  55331. x += colW;
  55332. childNum += numChildren;
  55333. }
  55334. return x;
  55335. }
  55336. bool isScrolling() const throw()
  55337. {
  55338. return childYOffset != 0 || needsToScroll;
  55339. }
  55340. void setCurrentlyHighlightedChild (PopupMenu::ItemComponent* const child)
  55341. {
  55342. if (currentChild->isValidComponent())
  55343. currentChild->setHighlighted (false);
  55344. currentChild = child;
  55345. if (currentChild != 0)
  55346. {
  55347. currentChild->setHighlighted (true);
  55348. timeEnteredCurrentChildComp = Time::getApproximateMillisecondCounter();
  55349. }
  55350. }
  55351. bool showSubMenuFor (PopupMenu::ItemComponent* const childComp)
  55352. {
  55353. jassert (activeSubMenu == 0 || activeSubMenu->isValidComponent());
  55354. activeSubMenu = 0;
  55355. if (childComp->isValidComponent() && childComp->itemInfo.hasActiveSubMenu())
  55356. {
  55357. const Point<int> topLeft (childComp->relativePositionToGlobal (Point<int>()));
  55358. const Point<int> bottomRight (childComp->relativePositionToGlobal (Point<int> (childComp->getWidth(), childComp->getHeight())));
  55359. activeSubMenu = Window::create (*(childComp->itemInfo.subMenu),
  55360. dismissOnMouseUp,
  55361. this,
  55362. topLeft.getX(), bottomRight.getX(), topLeft.getY(), bottomRight.getY(),
  55363. 0, maximumNumColumns,
  55364. standardItemHeight,
  55365. false, 0, menuBarComponent,
  55366. managerOfChosenCommand,
  55367. componentAttachedTo);
  55368. if (activeSubMenu != 0)
  55369. {
  55370. activeSubMenu->setVisible (true);
  55371. activeSubMenu->enterModalState (false);
  55372. activeSubMenu->toFront (false);
  55373. return true;
  55374. }
  55375. }
  55376. return false;
  55377. }
  55378. void highlightItemUnderMouse (const Point<int>& globalMousePos, const Point<int>& localMousePos)
  55379. {
  55380. isOver = reallyContains (localMousePos.getX(), localMousePos.getY(), true);
  55381. if (isOver)
  55382. hasBeenOver = true;
  55383. if (lastMouse.getDistanceFrom (globalMousePos) > 2)
  55384. {
  55385. lastMouseMoveTime = Time::getApproximateMillisecondCounter();
  55386. if (disableMouseMoves && isOver)
  55387. disableMouseMoves = false;
  55388. }
  55389. if (disableMouseMoves || (activeSubMenu != 0 && activeSubMenu->isOverChildren()))
  55390. return;
  55391. bool isMovingTowardsMenu = false;
  55392. jassert (activeSubMenu == 0 || activeSubMenu->isValidComponent())
  55393. if (isOver && (activeSubMenu != 0) && globalMousePos != lastMouse)
  55394. {
  55395. // try to intelligently guess whether the user is moving the mouse towards a currently-open
  55396. // submenu. To do this, look at whether the mouse stays inside a triangular region that
  55397. // extends from the last mouse pos to the submenu's rectangle..
  55398. float subX = (float) activeSubMenu->getScreenX();
  55399. if (activeSubMenu->getX() > getX())
  55400. {
  55401. lastMouse -= Point<int> (2, 0); // to enlarge the triangle a bit, in case the mouse only moves a couple of pixels
  55402. }
  55403. else
  55404. {
  55405. lastMouse += Point<int> (2, 0);
  55406. subX += activeSubMenu->getWidth();
  55407. }
  55408. Path areaTowardsSubMenu;
  55409. areaTowardsSubMenu.addTriangle ((float) lastMouse.getX(),
  55410. (float) lastMouse.getY(),
  55411. subX,
  55412. (float) activeSubMenu->getScreenY(),
  55413. subX,
  55414. (float) (activeSubMenu->getScreenY() + activeSubMenu->getHeight()));
  55415. isMovingTowardsMenu = areaTowardsSubMenu.contains ((float) globalMousePos.getX(), (float) globalMousePos.getY());
  55416. }
  55417. lastMouse = globalMousePos;
  55418. if (! isMovingTowardsMenu)
  55419. {
  55420. Component* c = getComponentAt (localMousePos.getX(), localMousePos.getY());
  55421. if (c == this)
  55422. c = 0;
  55423. PopupMenu::ItemComponent* mic = dynamic_cast <PopupMenu::ItemComponent*> (c);
  55424. if (mic == 0 && c != 0)
  55425. mic = c->findParentComponentOfClass ((PopupMenu::ItemComponent*) 0);
  55426. if (mic != currentChild
  55427. && (isOver || (activeSubMenu == 0) || ! activeSubMenu->isVisible()))
  55428. {
  55429. if (isOver && (c != 0) && (activeSubMenu != 0))
  55430. {
  55431. activeSubMenu->hide (0);
  55432. }
  55433. if (! isOver)
  55434. mic = 0;
  55435. setCurrentlyHighlightedChild (mic);
  55436. }
  55437. }
  55438. }
  55439. void triggerCurrentlyHighlightedItem()
  55440. {
  55441. if (currentChild->isValidComponent()
  55442. && currentChild->itemInfo.canBeTriggered()
  55443. && (currentChild->itemInfo.customComp == 0
  55444. || currentChild->itemInfo.customComp->isTriggeredAutomatically))
  55445. {
  55446. dismissMenu (&currentChild->itemInfo);
  55447. }
  55448. }
  55449. void selectNextItem (const int delta)
  55450. {
  55451. disableTimerUntilMouseMoves();
  55452. PopupMenu::ItemComponent* mic = 0;
  55453. bool wasLastOne = (currentChild == 0);
  55454. const int numItems = getNumChildComponents();
  55455. for (int i = 0; i < numItems + 1; ++i)
  55456. {
  55457. int index = (delta > 0) ? i : (numItems - 1 - i);
  55458. index = (index + numItems) % numItems;
  55459. mic = dynamic_cast <PopupMenu::ItemComponent*> (getChildComponent (index));
  55460. if (mic != 0 && (mic->itemInfo.canBeTriggered() || mic->itemInfo.hasActiveSubMenu())
  55461. && wasLastOne)
  55462. break;
  55463. if (mic == currentChild)
  55464. wasLastOne = true;
  55465. }
  55466. setCurrentlyHighlightedChild (mic);
  55467. }
  55468. void disableTimerUntilMouseMoves()
  55469. {
  55470. disableMouseMoves = true;
  55471. if (owner != 0)
  55472. owner->disableTimerUntilMouseMoves();
  55473. }
  55474. Window (const Window&);
  55475. Window& operator= (const Window&);
  55476. };
  55477. PopupMenu::PopupMenu()
  55478. : lookAndFeel (0),
  55479. separatorPending (false)
  55480. {
  55481. }
  55482. PopupMenu::PopupMenu (const PopupMenu& other)
  55483. : lookAndFeel (other.lookAndFeel),
  55484. separatorPending (false)
  55485. {
  55486. items.ensureStorageAllocated (other.items.size());
  55487. for (int i = 0; i < other.items.size(); ++i)
  55488. items.add (new Item (*other.items.getUnchecked(i)));
  55489. }
  55490. PopupMenu& PopupMenu::operator= (const PopupMenu& other)
  55491. {
  55492. if (this != &other)
  55493. {
  55494. lookAndFeel = other.lookAndFeel;
  55495. clear();
  55496. items.ensureStorageAllocated (other.items.size());
  55497. for (int i = 0; i < other.items.size(); ++i)
  55498. items.add (new Item (*other.items.getUnchecked(i)));
  55499. }
  55500. return *this;
  55501. }
  55502. PopupMenu::~PopupMenu()
  55503. {
  55504. clear();
  55505. }
  55506. void PopupMenu::clear()
  55507. {
  55508. items.clear();
  55509. separatorPending = false;
  55510. }
  55511. void PopupMenu::addSeparatorIfPending()
  55512. {
  55513. if (separatorPending)
  55514. {
  55515. separatorPending = false;
  55516. if (items.size() > 0)
  55517. items.add (new Item());
  55518. }
  55519. }
  55520. void PopupMenu::addItem (const int itemResultId,
  55521. const String& itemText,
  55522. const bool isActive,
  55523. const bool isTicked,
  55524. const Image* const iconToUse)
  55525. {
  55526. jassert (itemResultId != 0); // 0 is used as a return value to indicate that the user
  55527. // didn't pick anything, so you shouldn't use it as the id
  55528. // for an item..
  55529. addSeparatorIfPending();
  55530. items.add (new Item (itemResultId, itemText, isActive, isTicked,
  55531. iconToUse, Colours::black, false, 0, 0, 0));
  55532. }
  55533. void PopupMenu::addCommandItem (ApplicationCommandManager* commandManager,
  55534. const int commandID,
  55535. const String& displayName)
  55536. {
  55537. jassert (commandManager != 0 && commandID != 0);
  55538. const ApplicationCommandInfo* const registeredInfo = commandManager->getCommandForID (commandID);
  55539. if (registeredInfo != 0)
  55540. {
  55541. ApplicationCommandInfo info (*registeredInfo);
  55542. ApplicationCommandTarget* const target = commandManager->getTargetForCommand (commandID, info);
  55543. addSeparatorIfPending();
  55544. items.add (new Item (commandID,
  55545. displayName.isNotEmpty() ? displayName
  55546. : info.shortName,
  55547. target != 0 && (info.flags & ApplicationCommandInfo::isDisabled) == 0,
  55548. (info.flags & ApplicationCommandInfo::isTicked) != 0,
  55549. 0,
  55550. Colours::black,
  55551. false,
  55552. 0, 0,
  55553. commandManager));
  55554. }
  55555. }
  55556. void PopupMenu::addColouredItem (const int itemResultId,
  55557. const String& itemText,
  55558. const Colour& itemTextColour,
  55559. const bool isActive,
  55560. const bool isTicked,
  55561. const Image* const iconToUse)
  55562. {
  55563. jassert (itemResultId != 0); // 0 is used as a return value to indicate that the user
  55564. // didn't pick anything, so you shouldn't use it as the id
  55565. // for an item..
  55566. addSeparatorIfPending();
  55567. items.add (new Item (itemResultId, itemText, isActive, isTicked,
  55568. iconToUse, itemTextColour, true, 0, 0, 0));
  55569. }
  55570. void PopupMenu::addCustomItem (const int itemResultId,
  55571. PopupMenuCustomComponent* const customComponent)
  55572. {
  55573. jassert (itemResultId != 0); // 0 is used as a return value to indicate that the user
  55574. // didn't pick anything, so you shouldn't use it as the id
  55575. // for an item..
  55576. addSeparatorIfPending();
  55577. items.add (new Item (itemResultId, String::empty, true, false, 0,
  55578. Colours::black, false, customComponent, 0, 0));
  55579. }
  55580. class NormalComponentWrapper : public PopupMenuCustomComponent
  55581. {
  55582. public:
  55583. NormalComponentWrapper (Component* const comp,
  55584. const int w, const int h,
  55585. const bool triggerMenuItemAutomaticallyWhenClicked)
  55586. : PopupMenuCustomComponent (triggerMenuItemAutomaticallyWhenClicked),
  55587. width (w),
  55588. height (h)
  55589. {
  55590. addAndMakeVisible (comp);
  55591. }
  55592. ~NormalComponentWrapper() {}
  55593. void getIdealSize (int& idealWidth, int& idealHeight)
  55594. {
  55595. idealWidth = width;
  55596. idealHeight = height;
  55597. }
  55598. void resized()
  55599. {
  55600. if (getChildComponent(0) != 0)
  55601. getChildComponent(0)->setBounds (0, 0, getWidth(), getHeight());
  55602. }
  55603. juce_UseDebuggingNewOperator
  55604. private:
  55605. const int width, height;
  55606. NormalComponentWrapper (const NormalComponentWrapper&);
  55607. NormalComponentWrapper& operator= (const NormalComponentWrapper&);
  55608. };
  55609. void PopupMenu::addCustomItem (const int itemResultId,
  55610. Component* customComponent,
  55611. int idealWidth, int idealHeight,
  55612. const bool triggerMenuItemAutomaticallyWhenClicked)
  55613. {
  55614. addCustomItem (itemResultId,
  55615. new NormalComponentWrapper (customComponent,
  55616. idealWidth, idealHeight,
  55617. triggerMenuItemAutomaticallyWhenClicked));
  55618. }
  55619. void PopupMenu::addSubMenu (const String& subMenuName,
  55620. const PopupMenu& subMenu,
  55621. const bool isActive,
  55622. Image* const iconToUse,
  55623. const bool isTicked)
  55624. {
  55625. addSeparatorIfPending();
  55626. items.add (new Item (0, subMenuName, isActive && (subMenu.getNumItems() > 0), isTicked,
  55627. iconToUse, Colours::black, false, 0, &subMenu, 0));
  55628. }
  55629. void PopupMenu::addSeparator()
  55630. {
  55631. separatorPending = true;
  55632. }
  55633. class HeaderItemComponent : public PopupMenuCustomComponent
  55634. {
  55635. public:
  55636. HeaderItemComponent (const String& name)
  55637. : PopupMenuCustomComponent (false)
  55638. {
  55639. setName (name);
  55640. }
  55641. ~HeaderItemComponent()
  55642. {
  55643. }
  55644. void paint (Graphics& g)
  55645. {
  55646. Font f (getLookAndFeel().getPopupMenuFont());
  55647. f.setBold (true);
  55648. g.setFont (f);
  55649. g.setColour (findColour (PopupMenu::headerTextColourId));
  55650. g.drawFittedText (getName(),
  55651. 12, 0, getWidth() - 16, proportionOfHeight (0.8f),
  55652. Justification::bottomLeft, 1);
  55653. }
  55654. void getIdealSize (int& idealWidth,
  55655. int& idealHeight)
  55656. {
  55657. getLookAndFeel().getIdealPopupMenuItemSize (getName(), false, -1, idealWidth, idealHeight);
  55658. idealHeight += idealHeight / 2;
  55659. idealWidth += idealWidth / 4;
  55660. }
  55661. juce_UseDebuggingNewOperator
  55662. };
  55663. void PopupMenu::addSectionHeader (const String& title)
  55664. {
  55665. addCustomItem (0X4734a34f, new HeaderItemComponent (title));
  55666. }
  55667. Component* PopupMenu::createMenuComponent (const int x, const int y, const int w, const int h,
  55668. const int itemIdThatMustBeVisible,
  55669. const int minimumWidth,
  55670. const int maximumNumColumns,
  55671. const int standardItemHeight,
  55672. const bool alignToRectangle,
  55673. Component* menuBarComponent,
  55674. ApplicationCommandManager** managerOfChosenCommand,
  55675. Component* const componentAttachedTo)
  55676. {
  55677. Window* const pw
  55678. = Window::create (*this,
  55679. ModifierKeys::getCurrentModifiers().isAnyMouseButtonDown(),
  55680. 0,
  55681. x, x + w,
  55682. y, y + h,
  55683. minimumWidth,
  55684. maximumNumColumns,
  55685. standardItemHeight,
  55686. alignToRectangle,
  55687. itemIdThatMustBeVisible,
  55688. menuBarComponent,
  55689. managerOfChosenCommand,
  55690. componentAttachedTo);
  55691. if (pw != 0)
  55692. pw->setVisible (true);
  55693. return pw;
  55694. }
  55695. int PopupMenu::showMenu (const int x, const int y, const int w, const int h,
  55696. const int itemIdThatMustBeVisible,
  55697. const int minimumWidth,
  55698. const int maximumNumColumns,
  55699. const int standardItemHeight,
  55700. const bool alignToRectangle,
  55701. Component* const componentAttachedTo)
  55702. {
  55703. Component::SafePointer<Component> prevFocused (Component::getCurrentlyFocusedComponent());
  55704. Component::SafePointer<Component> prevTopLevel ((prevFocused != 0) ? prevFocused->getTopLevelComponent() : 0);
  55705. Window::wasHiddenBecauseOfAppChange() = false;
  55706. int result = 0;
  55707. ApplicationCommandManager* managerOfChosenCommand = 0;
  55708. ScopedPointer <Component> popupComp (createMenuComponent (x, y, w, h,
  55709. itemIdThatMustBeVisible,
  55710. minimumWidth,
  55711. maximumNumColumns > 0 ? maximumNumColumns : 7,
  55712. standardItemHeight,
  55713. alignToRectangle, 0,
  55714. &managerOfChosenCommand,
  55715. componentAttachedTo));
  55716. if (popupComp != 0)
  55717. {
  55718. popupComp->enterModalState (false);
  55719. popupComp->toFront (false); // need to do this after making it modal, or it could
  55720. // be stuck behind other comps that are already modal..
  55721. result = popupComp->runModalLoop();
  55722. popupComp = 0;
  55723. if (! Window::wasHiddenBecauseOfAppChange())
  55724. {
  55725. if (prevTopLevel != 0)
  55726. prevTopLevel->toFront (true);
  55727. if (prevFocused != 0)
  55728. prevFocused->grabKeyboardFocus();
  55729. }
  55730. }
  55731. if (managerOfChosenCommand != 0 && result != 0)
  55732. {
  55733. ApplicationCommandTarget::InvocationInfo info (result);
  55734. info.invocationMethod = ApplicationCommandTarget::InvocationInfo::fromMenu;
  55735. managerOfChosenCommand->invoke (info, true);
  55736. }
  55737. return result;
  55738. }
  55739. int PopupMenu::show (const int itemIdThatMustBeVisible,
  55740. const int minimumWidth,
  55741. const int maximumNumColumns,
  55742. const int standardItemHeight)
  55743. {
  55744. const Point<int> mousePos (Desktop::getMousePosition());
  55745. return showAt (mousePos.getX(), mousePos.getY(),
  55746. itemIdThatMustBeVisible,
  55747. minimumWidth,
  55748. maximumNumColumns,
  55749. standardItemHeight);
  55750. }
  55751. int PopupMenu::showAt (const int screenX,
  55752. const int screenY,
  55753. const int itemIdThatMustBeVisible,
  55754. const int minimumWidth,
  55755. const int maximumNumColumns,
  55756. const int standardItemHeight)
  55757. {
  55758. return showMenu (screenX, screenY, 1, 1,
  55759. itemIdThatMustBeVisible,
  55760. minimumWidth, maximumNumColumns,
  55761. standardItemHeight,
  55762. false, 0);
  55763. }
  55764. int PopupMenu::showAt (Component* componentToAttachTo,
  55765. const int itemIdThatMustBeVisible,
  55766. const int minimumWidth,
  55767. const int maximumNumColumns,
  55768. const int standardItemHeight)
  55769. {
  55770. if (componentToAttachTo != 0)
  55771. {
  55772. return showMenu (componentToAttachTo->getScreenX(),
  55773. componentToAttachTo->getScreenY(),
  55774. componentToAttachTo->getWidth(),
  55775. componentToAttachTo->getHeight(),
  55776. itemIdThatMustBeVisible,
  55777. minimumWidth,
  55778. maximumNumColumns,
  55779. standardItemHeight,
  55780. true, componentToAttachTo);
  55781. }
  55782. else
  55783. {
  55784. return show (itemIdThatMustBeVisible,
  55785. minimumWidth,
  55786. maximumNumColumns,
  55787. standardItemHeight);
  55788. }
  55789. }
  55790. void JUCE_CALLTYPE PopupMenu::dismissAllActiveMenus()
  55791. {
  55792. for (int i = Window::getActiveWindows().size(); --i >= 0;)
  55793. {
  55794. Window* const pmw = Window::getActiveWindows()[i];
  55795. if (pmw != 0)
  55796. pmw->dismissMenu (0);
  55797. }
  55798. }
  55799. int PopupMenu::getNumItems() const throw()
  55800. {
  55801. int num = 0;
  55802. for (int i = items.size(); --i >= 0;)
  55803. if (! (items.getUnchecked(i))->isSeparator)
  55804. ++num;
  55805. return num;
  55806. }
  55807. bool PopupMenu::containsCommandItem (const int commandID) const
  55808. {
  55809. for (int i = items.size(); --i >= 0;)
  55810. {
  55811. const Item* mi = items.getUnchecked (i);
  55812. if ((mi->itemId == commandID && mi->commandManager != 0)
  55813. || (mi->subMenu != 0 && mi->subMenu->containsCommandItem (commandID)))
  55814. {
  55815. return true;
  55816. }
  55817. }
  55818. return false;
  55819. }
  55820. bool PopupMenu::containsAnyActiveItems() const throw()
  55821. {
  55822. for (int i = items.size(); --i >= 0;)
  55823. {
  55824. const Item* const mi = items.getUnchecked (i);
  55825. if (mi->subMenu != 0)
  55826. {
  55827. if (mi->subMenu->containsAnyActiveItems())
  55828. return true;
  55829. }
  55830. else if (mi->active)
  55831. {
  55832. return true;
  55833. }
  55834. }
  55835. return false;
  55836. }
  55837. void PopupMenu::setLookAndFeel (LookAndFeel* const newLookAndFeel)
  55838. {
  55839. lookAndFeel = newLookAndFeel;
  55840. }
  55841. PopupMenuCustomComponent::PopupMenuCustomComponent (const bool isTriggeredAutomatically_)
  55842. : isHighlighted (false),
  55843. isTriggeredAutomatically (isTriggeredAutomatically_)
  55844. {
  55845. }
  55846. PopupMenuCustomComponent::~PopupMenuCustomComponent()
  55847. {
  55848. }
  55849. void PopupMenuCustomComponent::triggerMenuItem()
  55850. {
  55851. PopupMenu::ItemComponent* const mic = dynamic_cast <PopupMenu::ItemComponent*> (getParentComponent());
  55852. if (mic != 0)
  55853. {
  55854. PopupMenu::Window* const pmw = dynamic_cast <PopupMenu::Window*> (mic->getParentComponent());
  55855. if (pmw != 0)
  55856. {
  55857. pmw->dismissMenu (&mic->itemInfo);
  55858. }
  55859. else
  55860. {
  55861. // something must have gone wrong with the component hierarchy if this happens..
  55862. jassertfalse
  55863. }
  55864. }
  55865. else
  55866. {
  55867. // why isn't this component inside a menu? Not much point triggering the item if
  55868. // there's no menu.
  55869. jassertfalse
  55870. }
  55871. }
  55872. PopupMenu::MenuItemIterator::MenuItemIterator (const PopupMenu& menu_)
  55873. : subMenu (0),
  55874. itemId (0),
  55875. isSeparator (false),
  55876. isTicked (false),
  55877. isEnabled (false),
  55878. isCustomComponent (false),
  55879. isSectionHeader (false),
  55880. customColour (0),
  55881. customImage (0),
  55882. menu (menu_),
  55883. index (0)
  55884. {
  55885. }
  55886. PopupMenu::MenuItemIterator::~MenuItemIterator()
  55887. {
  55888. }
  55889. bool PopupMenu::MenuItemIterator::next()
  55890. {
  55891. if (index >= menu.items.size())
  55892. return false;
  55893. const Item* const item = menu.items.getUnchecked (index);
  55894. ++index;
  55895. itemName = item->customComp != 0 ? item->customComp->getName() : item->text;
  55896. subMenu = item->subMenu;
  55897. itemId = item->itemId;
  55898. isSeparator = item->isSeparator;
  55899. isTicked = item->isTicked;
  55900. isEnabled = item->active;
  55901. isSectionHeader = dynamic_cast <HeaderItemComponent*> ((PopupMenuCustomComponent*) item->customComp) != 0;
  55902. isCustomComponent = (! isSectionHeader) && item->customComp != 0;
  55903. customColour = item->usesColour ? &(item->textColour) : 0;
  55904. customImage = item->image;
  55905. commandManager = item->commandManager;
  55906. return true;
  55907. }
  55908. END_JUCE_NAMESPACE
  55909. /*** End of inlined file: juce_PopupMenu.cpp ***/
  55910. /*** Start of inlined file: juce_ComponentDragger.cpp ***/
  55911. BEGIN_JUCE_NAMESPACE
  55912. ComponentDragger::ComponentDragger()
  55913. : constrainer (0)
  55914. {
  55915. }
  55916. ComponentDragger::~ComponentDragger()
  55917. {
  55918. }
  55919. void ComponentDragger::startDraggingComponent (Component* const componentToDrag,
  55920. ComponentBoundsConstrainer* const constrainer_)
  55921. {
  55922. jassert (componentToDrag->isValidComponent());
  55923. if (componentToDrag != 0)
  55924. {
  55925. constrainer = constrainer_;
  55926. originalPos = componentToDrag->relativePositionToGlobal (Point<int>());
  55927. }
  55928. }
  55929. void ComponentDragger::dragComponent (Component* const componentToDrag, const MouseEvent& e)
  55930. {
  55931. jassert (componentToDrag->isValidComponent());
  55932. jassert (e.mods.isAnyMouseButtonDown()); // (the event has to be a drag event..)
  55933. if (componentToDrag != 0)
  55934. {
  55935. Rectangle<int> bounds (componentToDrag->getBounds().withPosition (originalPos));
  55936. const Component* const parentComp = componentToDrag->getParentComponent();
  55937. if (parentComp != 0)
  55938. bounds.setPosition (parentComp->globalPositionToRelative (originalPos));
  55939. bounds.setPosition (bounds.getPosition() + e.getOffsetFromDragStart());
  55940. if (constrainer != 0)
  55941. constrainer->setBoundsForComponent (componentToDrag, bounds, false, false, false, false);
  55942. else
  55943. componentToDrag->setBounds (bounds);
  55944. }
  55945. }
  55946. END_JUCE_NAMESPACE
  55947. /*** End of inlined file: juce_ComponentDragger.cpp ***/
  55948. /*** Start of inlined file: juce_DragAndDropContainer.cpp ***/
  55949. BEGIN_JUCE_NAMESPACE
  55950. bool juce_performDragDropFiles (const StringArray& files, const bool copyFiles, bool& shouldStop);
  55951. bool juce_performDragDropText (const String& text, bool& shouldStop);
  55952. class DragImageComponent : public Component,
  55953. public Timer
  55954. {
  55955. public:
  55956. DragImageComponent (Image* const im,
  55957. const String& desc,
  55958. Component* const sourceComponent,
  55959. Component* const mouseDragSource_,
  55960. DragAndDropContainer* const o,
  55961. const Point<int>& imageOffset_)
  55962. : image (im),
  55963. source (sourceComponent),
  55964. mouseDragSource (mouseDragSource_),
  55965. owner (o),
  55966. dragDesc (desc),
  55967. imageOffset (imageOffset_),
  55968. hasCheckedForExternalDrag (false),
  55969. drawImage (true)
  55970. {
  55971. setSize (im->getWidth(), im->getHeight());
  55972. if (mouseDragSource == 0)
  55973. mouseDragSource = source;
  55974. mouseDragSource->addMouseListener (this, false);
  55975. startTimer (200);
  55976. setInterceptsMouseClicks (false, false);
  55977. setAlwaysOnTop (true);
  55978. }
  55979. ~DragImageComponent()
  55980. {
  55981. if (owner->dragImageComponent == this)
  55982. owner->dragImageComponent.release();
  55983. if (mouseDragSource != 0)
  55984. {
  55985. mouseDragSource->removeMouseListener (this);
  55986. if (getCurrentlyOver() != 0 && getCurrentlyOver()->isInterestedInDragSource (dragDesc, source))
  55987. getCurrentlyOver()->itemDragExit (dragDesc, source);
  55988. }
  55989. }
  55990. void paint (Graphics& g)
  55991. {
  55992. if (isOpaque())
  55993. g.fillAll (Colours::white);
  55994. if (drawImage)
  55995. {
  55996. g.setOpacity (1.0f);
  55997. g.drawImageAt (image, 0, 0);
  55998. }
  55999. }
  56000. DragAndDropTarget* findTarget (const Point<int>& screenPos, Point<int>& relativePos)
  56001. {
  56002. Component* hit = getParentComponent();
  56003. if (hit == 0)
  56004. {
  56005. hit = Desktop::getInstance().findComponentAt (screenPos);
  56006. }
  56007. else
  56008. {
  56009. const Point<int> relPos (hit->globalPositionToRelative (screenPos));
  56010. hit = hit->getComponentAt (relPos.getX(), relPos.getY());
  56011. }
  56012. // (note: use a local copy of the dragDesc member in case the callback runs
  56013. // a modal loop and deletes this object before the method completes)
  56014. const String dragDescLocal (dragDesc);
  56015. while (hit != 0)
  56016. {
  56017. DragAndDropTarget* const ddt = dynamic_cast <DragAndDropTarget*> (hit);
  56018. if (ddt != 0 && ddt->isInterestedInDragSource (dragDescLocal, source))
  56019. {
  56020. relativePos = hit->globalPositionToRelative (screenPos);
  56021. return ddt;
  56022. }
  56023. hit = hit->getParentComponent();
  56024. }
  56025. return 0;
  56026. }
  56027. void mouseUp (const MouseEvent& e)
  56028. {
  56029. if (e.originalComponent != this)
  56030. {
  56031. if (mouseDragSource != 0)
  56032. mouseDragSource->removeMouseListener (this);
  56033. bool dropAccepted = false;
  56034. DragAndDropTarget* ddt = 0;
  56035. Point<int> relPos;
  56036. if (isVisible())
  56037. {
  56038. setVisible (false);
  56039. ddt = findTarget (e.getScreenPosition(), relPos);
  56040. // fade this component and remove it - it'll be deleted later by the timer callback
  56041. dropAccepted = ddt != 0;
  56042. setVisible (true);
  56043. if (dropAccepted || source == 0)
  56044. {
  56045. fadeOutComponent (120);
  56046. }
  56047. else
  56048. {
  56049. const Point<int> target (source->relativePositionToGlobal (Point<int> (source->getWidth() / 2,
  56050. source->getHeight() / 2)));
  56051. const Point<int> ourCentre (relativePositionToGlobal (Point<int> (getWidth() / 2,
  56052. getHeight() / 2)));
  56053. fadeOutComponent (120,
  56054. target.getX() - ourCentre.getX(),
  56055. target.getY() - ourCentre.getY());
  56056. }
  56057. }
  56058. if (getParentComponent() != 0)
  56059. getParentComponent()->removeChildComponent (this);
  56060. if (dropAccepted && ddt != 0)
  56061. {
  56062. // (note: use a local copy of the dragDesc member in case the callback runs
  56063. // a modal loop and deletes this object before the method completes)
  56064. const String dragDescLocal (dragDesc);
  56065. currentlyOverComp = 0;
  56066. ddt->itemDropped (dragDescLocal, source, relPos.getX(), relPos.getY());
  56067. }
  56068. // careful - this object could now be deleted..
  56069. }
  56070. }
  56071. void updateLocation (const bool canDoExternalDrag, const Point<int>& screenPos)
  56072. {
  56073. // (note: use a local copy of the dragDesc member in case the callback runs
  56074. // a modal loop and deletes this object before it returns)
  56075. const String dragDescLocal (dragDesc);
  56076. Point<int> newPos (screenPos + imageOffset);
  56077. if (getParentComponent() != 0)
  56078. newPos = getParentComponent()->globalPositionToRelative (newPos);
  56079. //if (newX != getX() || newY != getY())
  56080. {
  56081. setTopLeftPosition (newPos.getX(), newPos.getY());
  56082. Point<int> relPos;
  56083. DragAndDropTarget* const ddt = findTarget (screenPos, relPos);
  56084. Component* ddtComp = dynamic_cast <Component*> (ddt);
  56085. drawImage = (ddt == 0) || ddt->shouldDrawDragImageWhenOver();
  56086. if (ddtComp != currentlyOverComp)
  56087. {
  56088. if (currentlyOverComp != 0 && source != 0
  56089. && getCurrentlyOver()->isInterestedInDragSource (dragDescLocal, source))
  56090. {
  56091. getCurrentlyOver()->itemDragExit (dragDescLocal, source);
  56092. }
  56093. currentlyOverComp = ddtComp;
  56094. if (ddt != 0 && ddt->isInterestedInDragSource (dragDescLocal, source))
  56095. ddt->itemDragEnter (dragDescLocal, source, relPos.getX(), relPos.getY());
  56096. }
  56097. if (getCurrentlyOver() != 0 && getCurrentlyOver()->isInterestedInDragSource (dragDescLocal, source))
  56098. getCurrentlyOver()->itemDragMove (dragDescLocal, source, relPos.getX(), relPos.getY());
  56099. if (getCurrentlyOver() == 0
  56100. && canDoExternalDrag
  56101. && ! hasCheckedForExternalDrag)
  56102. {
  56103. if (Desktop::getInstance().findComponentAt (screenPos) == 0)
  56104. {
  56105. hasCheckedForExternalDrag = true;
  56106. StringArray files;
  56107. bool canMoveFiles = false;
  56108. if (owner->shouldDropFilesWhenDraggedExternally (dragDescLocal, source, files, canMoveFiles)
  56109. && files.size() > 0)
  56110. {
  56111. Component::SafePointer<Component> cdw (this);
  56112. setVisible (false);
  56113. if (ModifierKeys::getCurrentModifiersRealtime().isAnyMouseButtonDown())
  56114. DragAndDropContainer::performExternalDragDropOfFiles (files, canMoveFiles);
  56115. if (cdw != 0)
  56116. delete this;
  56117. return;
  56118. }
  56119. }
  56120. }
  56121. }
  56122. }
  56123. void mouseDrag (const MouseEvent& e)
  56124. {
  56125. if (e.originalComponent != this)
  56126. updateLocation (true, e.getScreenPosition());
  56127. }
  56128. void timerCallback()
  56129. {
  56130. if (source == 0)
  56131. {
  56132. delete this;
  56133. }
  56134. else if (! isMouseButtonDownAnywhere())
  56135. {
  56136. if (mouseDragSource != 0)
  56137. mouseDragSource->removeMouseListener (this);
  56138. delete this;
  56139. }
  56140. }
  56141. private:
  56142. ScopedPointer<Image> image;
  56143. Component::SafePointer<Component> source;
  56144. Component::SafePointer<Component> mouseDragSource;
  56145. DragAndDropContainer* const owner;
  56146. Component::SafePointer<Component> currentlyOverComp;
  56147. DragAndDropTarget* getCurrentlyOver()
  56148. {
  56149. return dynamic_cast <DragAndDropTarget*> (static_cast <Component*> (currentlyOverComp));
  56150. }
  56151. String dragDesc;
  56152. const Point<int> imageOffset;
  56153. bool hasCheckedForExternalDrag, drawImage;
  56154. DragImageComponent (const DragImageComponent&);
  56155. DragImageComponent& operator= (const DragImageComponent&);
  56156. };
  56157. DragAndDropContainer::DragAndDropContainer()
  56158. {
  56159. }
  56160. DragAndDropContainer::~DragAndDropContainer()
  56161. {
  56162. dragImageComponent = 0;
  56163. }
  56164. void DragAndDropContainer::startDragging (const String& sourceDescription,
  56165. Component* sourceComponent,
  56166. Image* dragImage_,
  56167. const bool allowDraggingToExternalWindows,
  56168. const Point<int>* imageOffsetFromMouse)
  56169. {
  56170. ScopedPointer <Image> dragImage (dragImage_);
  56171. if (dragImageComponent == 0)
  56172. {
  56173. Component* const thisComp = dynamic_cast <Component*> (this);
  56174. if (thisComp == 0)
  56175. {
  56176. jassertfalse; // Your DragAndDropContainer needs to be a Component!
  56177. return;
  56178. }
  56179. MouseInputSource* draggingSource = Desktop::getInstance().getDraggingMouseSource (0);
  56180. if (draggingSource == 0 || ! draggingSource->isDragging())
  56181. {
  56182. jassertfalse; // You must call startDragging() from within a mouseDown or mouseDrag callback!
  56183. return;
  56184. }
  56185. const Point<int> lastMouseDown (Desktop::getLastMouseDownPosition());
  56186. Point<int> imageOffset;
  56187. if (dragImage == 0)
  56188. {
  56189. dragImage = sourceComponent->createComponentSnapshot (sourceComponent->getLocalBounds());
  56190. if (dragImage->getFormat() != Image::ARGB)
  56191. {
  56192. Image* newIm = Image::createNativeImage (Image::ARGB, dragImage->getWidth(), dragImage->getHeight(), true);
  56193. Graphics g2 (*newIm);
  56194. g2.drawImageAt (dragImage, 0, 0);
  56195. dragImage = newIm;
  56196. }
  56197. dragImage->multiplyAllAlphas (0.6f);
  56198. const int lo = 150;
  56199. const int hi = 400;
  56200. Point<int> relPos (sourceComponent->globalPositionToRelative (lastMouseDown));
  56201. Point<int> clipped (dragImage->getBounds().getConstrainedPoint (relPos));
  56202. for (int y = dragImage->getHeight(); --y >= 0;)
  56203. {
  56204. const double dy = (y - clipped.getY()) * (y - clipped.getY());
  56205. for (int x = dragImage->getWidth(); --x >= 0;)
  56206. {
  56207. const int dx = x - clipped.getX();
  56208. const int distance = roundToInt (sqrt (dx * dx + dy));
  56209. if (distance > lo)
  56210. {
  56211. const float alpha = (distance > hi) ? 0
  56212. : (hi - distance) / (float) (hi - lo)
  56213. + Random::getSystemRandom().nextFloat() * 0.008f;
  56214. dragImage->multiplyAlphaAt (x, y, alpha);
  56215. }
  56216. }
  56217. }
  56218. imageOffset = -clipped;
  56219. }
  56220. else
  56221. {
  56222. if (imageOffsetFromMouse == 0)
  56223. imageOffset = -dragImage->getBounds().getCentre();
  56224. else
  56225. imageOffset = -(dragImage->getBounds().getConstrainedPoint (-*imageOffsetFromMouse));
  56226. }
  56227. dragImageComponent = new DragImageComponent (dragImage.release(), sourceDescription, sourceComponent,
  56228. draggingSource->getComponentUnderMouse(), this, imageOffset);
  56229. currentDragDesc = sourceDescription;
  56230. if (allowDraggingToExternalWindows)
  56231. {
  56232. if (! Desktop::canUseSemiTransparentWindows())
  56233. dragImageComponent->setOpaque (true);
  56234. dragImageComponent->addToDesktop (ComponentPeer::windowIgnoresMouseClicks
  56235. | ComponentPeer::windowIsTemporary
  56236. | ComponentPeer::windowIgnoresKeyPresses);
  56237. }
  56238. else
  56239. thisComp->addChildComponent (dragImageComponent);
  56240. static_cast <DragImageComponent*> (static_cast <Component*> (dragImageComponent))->updateLocation (false, lastMouseDown);
  56241. dragImageComponent->setVisible (true);
  56242. }
  56243. }
  56244. bool DragAndDropContainer::isDragAndDropActive() const
  56245. {
  56246. return dragImageComponent != 0;
  56247. }
  56248. const String DragAndDropContainer::getCurrentDragDescription() const
  56249. {
  56250. return (dragImageComponent != 0) ? currentDragDesc
  56251. : String::empty;
  56252. }
  56253. DragAndDropContainer* DragAndDropContainer::findParentDragContainerFor (Component* c)
  56254. {
  56255. if (c == 0)
  56256. return 0;
  56257. // (unable to use the syntax findParentComponentOfClass <DragAndDropContainer> () because of a VC6 compiler bug)
  56258. return c->findParentComponentOfClass ((DragAndDropContainer*) 0);
  56259. }
  56260. bool DragAndDropContainer::shouldDropFilesWhenDraggedExternally (const String&, Component*, StringArray&, bool&)
  56261. {
  56262. return false;
  56263. }
  56264. void DragAndDropTarget::itemDragEnter (const String&, Component*, int, int)
  56265. {
  56266. }
  56267. void DragAndDropTarget::itemDragMove (const String&, Component*, int, int)
  56268. {
  56269. }
  56270. void DragAndDropTarget::itemDragExit (const String&, Component*)
  56271. {
  56272. }
  56273. bool DragAndDropTarget::shouldDrawDragImageWhenOver()
  56274. {
  56275. return true;
  56276. }
  56277. void FileDragAndDropTarget::fileDragEnter (const StringArray&, int, int)
  56278. {
  56279. }
  56280. void FileDragAndDropTarget::fileDragMove (const StringArray&, int, int)
  56281. {
  56282. }
  56283. void FileDragAndDropTarget::fileDragExit (const StringArray&)
  56284. {
  56285. }
  56286. END_JUCE_NAMESPACE
  56287. /*** End of inlined file: juce_DragAndDropContainer.cpp ***/
  56288. /*** Start of inlined file: juce_MouseCursor.cpp ***/
  56289. BEGIN_JUCE_NAMESPACE
  56290. class MouseCursor::SharedCursorHandle
  56291. {
  56292. public:
  56293. explicit SharedCursorHandle (const MouseCursor::StandardCursorType type)
  56294. : handle (createStandardMouseCursor (type)),
  56295. refCount (1),
  56296. standardType (type),
  56297. isStandard (true)
  56298. {
  56299. }
  56300. SharedCursorHandle (const Image& image, const int hotSpotX, const int hotSpotY)
  56301. : handle (createMouseCursorFromImage (image, hotSpotX, hotSpotY)),
  56302. refCount (1),
  56303. standardType (MouseCursor::NormalCursor),
  56304. isStandard (false)
  56305. {
  56306. }
  56307. static SharedCursorHandle* createStandard (const MouseCursor::StandardCursorType type)
  56308. {
  56309. const ScopedLock sl (getLock());
  56310. for (int i = getCursors().size(); --i >= 0;)
  56311. {
  56312. SharedCursorHandle* const sc = getCursors().getUnchecked(i);
  56313. if (sc->standardType == type)
  56314. return sc->retain();
  56315. }
  56316. SharedCursorHandle* const sc = new SharedCursorHandle (type);
  56317. getCursors().add (sc);
  56318. return sc;
  56319. }
  56320. SharedCursorHandle* retain() throw()
  56321. {
  56322. ++refCount;
  56323. return this;
  56324. }
  56325. void release()
  56326. {
  56327. if (--refCount == 0)
  56328. {
  56329. if (isStandard)
  56330. {
  56331. const ScopedLock sl (getLock());
  56332. getCursors().removeValue (this);
  56333. }
  56334. delete this;
  56335. }
  56336. }
  56337. void* getHandle() const throw() { return handle; }
  56338. juce_UseDebuggingNewOperator
  56339. private:
  56340. void* const handle;
  56341. Atomic <int> refCount;
  56342. const MouseCursor::StandardCursorType standardType;
  56343. const bool isStandard;
  56344. static CriticalSection& getLock()
  56345. {
  56346. static CriticalSection lock;
  56347. return lock;
  56348. }
  56349. static Array <SharedCursorHandle*>& getCursors()
  56350. {
  56351. static Array <SharedCursorHandle*> cursors;
  56352. return cursors;
  56353. }
  56354. ~SharedCursorHandle()
  56355. {
  56356. deleteMouseCursor (handle, isStandard);
  56357. }
  56358. SharedCursorHandle& operator= (const SharedCursorHandle&);
  56359. };
  56360. MouseCursor::MouseCursor()
  56361. : cursorHandle (SharedCursorHandle::createStandard (NormalCursor))
  56362. {
  56363. jassert (cursorHandle != 0);
  56364. }
  56365. MouseCursor::MouseCursor (const StandardCursorType type)
  56366. : cursorHandle (SharedCursorHandle::createStandard (type))
  56367. {
  56368. jassert (cursorHandle != 0);
  56369. }
  56370. MouseCursor::MouseCursor (const Image& image, const int hotSpotX, const int hotSpotY)
  56371. : cursorHandle (new SharedCursorHandle (image, hotSpotX, hotSpotY))
  56372. {
  56373. }
  56374. MouseCursor::MouseCursor (const MouseCursor& other)
  56375. : cursorHandle (other.cursorHandle->retain())
  56376. {
  56377. }
  56378. MouseCursor::~MouseCursor()
  56379. {
  56380. cursorHandle->release();
  56381. }
  56382. MouseCursor& MouseCursor::operator= (const MouseCursor& other)
  56383. {
  56384. other.cursorHandle->retain();
  56385. cursorHandle->release();
  56386. cursorHandle = other.cursorHandle;
  56387. return *this;
  56388. }
  56389. bool MouseCursor::operator== (const MouseCursor& other) const throw()
  56390. {
  56391. return getHandle() == other.getHandle();
  56392. }
  56393. bool MouseCursor::operator!= (const MouseCursor& other) const throw()
  56394. {
  56395. return getHandle() != other.getHandle();
  56396. }
  56397. void* MouseCursor::getHandle() const throw()
  56398. {
  56399. return cursorHandle->getHandle();
  56400. }
  56401. void MouseCursor::showWaitCursor()
  56402. {
  56403. Desktop::getInstance().getMainMouseSource().showMouseCursor (MouseCursor::WaitCursor);
  56404. }
  56405. void MouseCursor::hideWaitCursor()
  56406. {
  56407. Desktop::getInstance().getMainMouseSource().revealCursor();
  56408. }
  56409. END_JUCE_NAMESPACE
  56410. /*** End of inlined file: juce_MouseCursor.cpp ***/
  56411. /*** Start of inlined file: juce_MouseEvent.cpp ***/
  56412. BEGIN_JUCE_NAMESPACE
  56413. MouseEvent::MouseEvent (MouseInputSource& source_,
  56414. const Point<int>& position,
  56415. const ModifierKeys& mods_,
  56416. Component* const originator,
  56417. const Time& eventTime_,
  56418. const Point<int> mouseDownPos_,
  56419. const Time& mouseDownTime_,
  56420. const int numberOfClicks_,
  56421. const bool mouseWasDragged) throw()
  56422. : x (position.getX()),
  56423. y (position.getY()),
  56424. mods (mods_),
  56425. eventComponent (originator),
  56426. originalComponent (originator),
  56427. eventTime (eventTime_),
  56428. source (source_),
  56429. mouseDownPos (mouseDownPos_),
  56430. mouseDownTime (mouseDownTime_),
  56431. numberOfClicks (numberOfClicks_),
  56432. wasMovedSinceMouseDown (mouseWasDragged)
  56433. {
  56434. }
  56435. MouseEvent::~MouseEvent() throw()
  56436. {
  56437. }
  56438. const MouseEvent MouseEvent::getEventRelativeTo (Component* const otherComponent) const throw()
  56439. {
  56440. if (otherComponent == 0)
  56441. {
  56442. jassertfalse
  56443. return *this;
  56444. }
  56445. return MouseEvent (source, eventComponent->relativePositionToOtherComponent (otherComponent, getPosition()),
  56446. mods, originalComponent, eventTime,
  56447. eventComponent->relativePositionToOtherComponent (otherComponent, mouseDownPos),
  56448. mouseDownTime, numberOfClicks, wasMovedSinceMouseDown);
  56449. }
  56450. const MouseEvent MouseEvent::withNewPosition (const Point<int>& newPosition) const throw()
  56451. {
  56452. return MouseEvent (source, newPosition, mods, originalComponent,
  56453. eventTime, mouseDownPos, mouseDownTime,
  56454. numberOfClicks, wasMovedSinceMouseDown);
  56455. }
  56456. bool MouseEvent::mouseWasClicked() const throw()
  56457. {
  56458. return ! wasMovedSinceMouseDown;
  56459. }
  56460. int MouseEvent::getMouseDownX() const throw()
  56461. {
  56462. return mouseDownPos.getX();
  56463. }
  56464. int MouseEvent::getMouseDownY() const throw()
  56465. {
  56466. return mouseDownPos.getY();
  56467. }
  56468. const Point<int> MouseEvent::getMouseDownPosition() const throw()
  56469. {
  56470. return mouseDownPos;
  56471. }
  56472. int MouseEvent::getDistanceFromDragStartX() const throw()
  56473. {
  56474. return x - mouseDownPos.getX();
  56475. }
  56476. int MouseEvent::getDistanceFromDragStartY() const throw()
  56477. {
  56478. return y - mouseDownPos.getY();
  56479. }
  56480. int MouseEvent::getDistanceFromDragStart() const throw()
  56481. {
  56482. return mouseDownPos.getDistanceFrom (getPosition());
  56483. }
  56484. const Point<int> MouseEvent::getOffsetFromDragStart() const throw()
  56485. {
  56486. return getPosition() - mouseDownPos;
  56487. }
  56488. int MouseEvent::getLengthOfMousePress() const throw()
  56489. {
  56490. if (mouseDownTime.toMilliseconds() > 0)
  56491. return jmax (0, (int) (eventTime - mouseDownTime).inMilliseconds());
  56492. return 0;
  56493. }
  56494. const Point<int> MouseEvent::getPosition() const throw()
  56495. {
  56496. return Point<int> (x, y);
  56497. }
  56498. int MouseEvent::getScreenX() const
  56499. {
  56500. return getScreenPosition().getX();
  56501. }
  56502. int MouseEvent::getScreenY() const
  56503. {
  56504. return getScreenPosition().getY();
  56505. }
  56506. const Point<int> MouseEvent::getScreenPosition() const
  56507. {
  56508. return eventComponent->relativePositionToGlobal (Point<int> (x, y));
  56509. }
  56510. int MouseEvent::getMouseDownScreenX() const
  56511. {
  56512. return getMouseDownScreenPosition().getX();
  56513. }
  56514. int MouseEvent::getMouseDownScreenY() const
  56515. {
  56516. return getMouseDownScreenPosition().getY();
  56517. }
  56518. const Point<int> MouseEvent::getMouseDownScreenPosition() const
  56519. {
  56520. return eventComponent->relativePositionToGlobal (mouseDownPos);
  56521. }
  56522. static int doubleClickTimeOutMs = 400;
  56523. void MouseEvent::setDoubleClickTimeout (const int newTime) throw()
  56524. {
  56525. doubleClickTimeOutMs = newTime;
  56526. }
  56527. int MouseEvent::getDoubleClickTimeout() throw()
  56528. {
  56529. return doubleClickTimeOutMs;
  56530. }
  56531. END_JUCE_NAMESPACE
  56532. /*** End of inlined file: juce_MouseEvent.cpp ***/
  56533. /*** Start of inlined file: juce_MouseInputSource.cpp ***/
  56534. BEGIN_JUCE_NAMESPACE
  56535. class MouseInputSourceInternal : public AsyncUpdater
  56536. {
  56537. public:
  56538. MouseInputSourceInternal (MouseInputSource& source_, const int index_, const bool isMouseDevice_)
  56539. : index (index_), isMouseDevice (isMouseDevice_), source (source_), lastPeer (0), lastTime (0),
  56540. isUnboundedMouseModeOn (false), isCursorVisibleUntilOffscreen (false), currentCursorHandle (0),
  56541. mouseEventCounter (0)
  56542. {
  56543. zerostruct (mouseDowns);
  56544. }
  56545. ~MouseInputSourceInternal()
  56546. {
  56547. }
  56548. bool isDragging() const throw()
  56549. {
  56550. return buttonState.isAnyMouseButtonDown();
  56551. }
  56552. Component* getComponentUnderMouse() const
  56553. {
  56554. return static_cast <Component*> (componentUnderMouse);
  56555. }
  56556. const ModifierKeys getCurrentModifiers() const
  56557. {
  56558. return ModifierKeys::getCurrentModifiers().withoutMouseButtons().withFlags (buttonState.getRawFlags());
  56559. }
  56560. ComponentPeer* getPeer()
  56561. {
  56562. if (! ComponentPeer::isValidPeer (lastPeer))
  56563. lastPeer = 0;
  56564. return lastPeer;
  56565. }
  56566. Component* findComponentAt (const Point<int>& screenPos)
  56567. {
  56568. ComponentPeer* const peer = getPeer();
  56569. if (peer != 0)
  56570. {
  56571. Component* const comp = peer->getComponent();
  56572. const Point<int> relativePos (comp->globalPositionToRelative (screenPos));
  56573. // (the contains() call is needed to test for overlapping desktop windows)
  56574. if (comp->contains (relativePos.getX(), relativePos.getY()))
  56575. return comp->getComponentAt (relativePos);
  56576. }
  56577. return 0;
  56578. }
  56579. const Point<int> getScreenPosition() const throw()
  56580. {
  56581. return lastScreenPos + unboundedMouseOffset;
  56582. }
  56583. void sendMouseEnter (Component* const comp, const Point<int>& screenPos, const int64 time)
  56584. {
  56585. //DBG ("Mouse " + String (source.getIndex()) + " enter: " + comp->globalPositionToRelative (screenPos).toString() + " - Comp: " + String::toHexString ((int) comp));
  56586. comp->internalMouseEnter (source, comp->globalPositionToRelative (screenPos), time);
  56587. }
  56588. void sendMouseExit (Component* const comp, const Point<int>& screenPos, const int64 time)
  56589. {
  56590. //DBG ("Mouse " + String (source.getIndex()) + " exit: " + comp->globalPositionToRelative (screenPos).toString() + " - Comp: " + String::toHexString ((int) comp));
  56591. comp->internalMouseExit (source, comp->globalPositionToRelative (screenPos), time);
  56592. }
  56593. void sendMouseMove (Component* const comp, const Point<int>& screenPos, const int64 time)
  56594. {
  56595. //DBG ("Mouse " + String (source.getIndex()) + " move: " + comp->globalPositionToRelative (screenPos).toString() + " - Comp: " + String::toHexString ((int) comp));
  56596. comp->internalMouseMove (source, comp->globalPositionToRelative (screenPos), time);
  56597. }
  56598. void sendMouseDown (Component* const comp, const Point<int>& screenPos, const int64 time)
  56599. {
  56600. //DBG ("Mouse " + String (source.getIndex()) + " down: " + comp->globalPositionToRelative (screenPos).toString() + " - Comp: " + String::toHexString ((int) comp));
  56601. comp->internalMouseDown (source, comp->globalPositionToRelative (screenPos), time);
  56602. }
  56603. void sendMouseDrag (Component* const comp, const Point<int>& screenPos, const int64 time)
  56604. {
  56605. //DBG ("Mouse " + String (source.getIndex()) + " drag: " + comp->globalPositionToRelative (screenPos).toString() + " - Comp: " + String::toHexString ((int) comp));
  56606. comp->internalMouseDrag (source, comp->globalPositionToRelative (screenPos), time);
  56607. }
  56608. void sendMouseUp (Component* const comp, const Point<int>& screenPos, const int64 time)
  56609. {
  56610. //DBG ("Mouse " + String (source.getIndex()) + " up: " + comp->globalPositionToRelative (screenPos).toString() + " - Comp: " + String::toHexString ((int) comp));
  56611. comp->internalMouseUp (source, comp->globalPositionToRelative (screenPos), time, getCurrentModifiers());
  56612. }
  56613. void sendMouseWheel (Component* const comp, const Point<int>& screenPos, const int64 time, float x, float y)
  56614. {
  56615. //DBG ("Mouse " + String (source.getIndex()) + " wheel: " + comp->globalPositionToRelative (screenPos).toString() + " - Comp: " + String::toHexString ((int) comp));
  56616. comp->internalMouseWheel (source, comp->globalPositionToRelative (screenPos), time, x, y);
  56617. }
  56618. // (returns true if the button change caused a modal event loop)
  56619. bool setButtons (const Point<int>& screenPos, const int64 time, const ModifierKeys& newButtonState)
  56620. {
  56621. if (buttonState == newButtonState)
  56622. return false;
  56623. // (ignore secondary clicks when there's already a button down)
  56624. if (buttonState.isAnyMouseButtonDown() == newButtonState.isAnyMouseButtonDown())
  56625. {
  56626. buttonState = newButtonState;
  56627. return false;
  56628. }
  56629. const int lastCounter = mouseEventCounter;
  56630. if (buttonState.isAnyMouseButtonDown())
  56631. {
  56632. Component* const current = getComponentUnderMouse();
  56633. if (current != 0)
  56634. sendMouseUp (current, screenPos + unboundedMouseOffset, time);
  56635. enableUnboundedMouseMovement (false, false);
  56636. }
  56637. buttonState = newButtonState;
  56638. if (buttonState.isAnyMouseButtonDown())
  56639. {
  56640. Desktop::getInstance().incrementMouseClickCounter();
  56641. Component* const current = getComponentUnderMouse();
  56642. if (current != 0)
  56643. {
  56644. registerMouseDown (screenPos, time, current);
  56645. sendMouseDown (current, screenPos, time);
  56646. }
  56647. }
  56648. return lastCounter != mouseEventCounter;
  56649. }
  56650. void setComponentUnderMouse (Component* const newComponent, const Point<int>& screenPos, const int64 time)
  56651. {
  56652. Component* current = getComponentUnderMouse();
  56653. if (newComponent != current)
  56654. {
  56655. Component::SafePointer<Component> safeNewComp (newComponent);
  56656. const ModifierKeys originalButtonState (buttonState);
  56657. if (current != 0)
  56658. {
  56659. setButtons (screenPos, time, ModifierKeys());
  56660. sendMouseExit (current, screenPos, time);
  56661. buttonState = originalButtonState;
  56662. }
  56663. componentUnderMouse = safeNewComp;
  56664. current = getComponentUnderMouse();
  56665. if (current != 0)
  56666. sendMouseEnter (current, screenPos, time);
  56667. revealCursor (false);
  56668. setButtons (screenPos, time, originalButtonState);
  56669. }
  56670. }
  56671. void setPeer (ComponentPeer* const newPeer, const Point<int>& screenPos, const int64 time)
  56672. {
  56673. ModifierKeys::updateCurrentModifiers();
  56674. if (newPeer != lastPeer)
  56675. {
  56676. setComponentUnderMouse (0, screenPos, time);
  56677. lastPeer = newPeer;
  56678. setComponentUnderMouse (findComponentAt (screenPos), screenPos, time);
  56679. }
  56680. }
  56681. void setScreenPos (const Point<int>& newScreenPos, const int64 time, const bool forceUpdate)
  56682. {
  56683. if (! isDragging())
  56684. setComponentUnderMouse (findComponentAt (newScreenPos), newScreenPos, time);
  56685. if (newScreenPos != lastScreenPos || forceUpdate)
  56686. {
  56687. cancelPendingUpdate();
  56688. lastScreenPos = newScreenPos;
  56689. Component* const current = getComponentUnderMouse();
  56690. if (current != 0)
  56691. {
  56692. if (isDragging())
  56693. {
  56694. registerMouseDrag (newScreenPos);
  56695. sendMouseDrag (current, newScreenPos + unboundedMouseOffset, time);
  56696. if (isUnboundedMouseModeOn)
  56697. handleUnboundedDrag (current);
  56698. }
  56699. else
  56700. {
  56701. sendMouseMove (current, newScreenPos, time);
  56702. }
  56703. }
  56704. revealCursor (false);
  56705. }
  56706. }
  56707. void handleEvent (ComponentPeer* const newPeer, const Point<int>& positionWithinPeer, const int64 time, const ModifierKeys& newMods)
  56708. {
  56709. jassert (newPeer != 0);
  56710. lastTime = time;
  56711. ++mouseEventCounter;
  56712. const Point<int> screenPos (newPeer->relativePositionToGlobal (positionWithinPeer));
  56713. if (isDragging() && newMods.isAnyMouseButtonDown())
  56714. {
  56715. setScreenPos (screenPos, time, false);
  56716. }
  56717. else
  56718. {
  56719. setPeer (newPeer, screenPos, time);
  56720. ComponentPeer* peer = getPeer();
  56721. if (peer != 0)
  56722. {
  56723. if (setButtons (screenPos, time, newMods))
  56724. return; // some modal events have been dispatched, so the current event is now out-of-date
  56725. peer = getPeer();
  56726. if (peer != 0)
  56727. setScreenPos (screenPos, time, false);
  56728. }
  56729. }
  56730. }
  56731. void handleWheel (ComponentPeer* const peer, const Point<int>& positionWithinPeer, int64 time, float x, float y)
  56732. {
  56733. jassert (peer != 0);
  56734. lastTime = time;
  56735. ++mouseEventCounter;
  56736. const Point<int> screenPos (peer->relativePositionToGlobal (positionWithinPeer));
  56737. setPeer (peer, screenPos, time);
  56738. setScreenPos (screenPos, time, false);
  56739. triggerFakeMove();
  56740. if (! isDragging())
  56741. {
  56742. Component* current = getComponentUnderMouse();
  56743. if (current != 0)
  56744. sendMouseWheel (current, screenPos, time, x, y);
  56745. }
  56746. }
  56747. const Time getLastMouseDownTime() const throw()
  56748. {
  56749. return Time (mouseDowns[0].time);
  56750. }
  56751. const Point<int> getLastMouseDownPosition() const throw()
  56752. {
  56753. return mouseDowns[0].position;
  56754. }
  56755. int getNumberOfMultipleClicks() const throw()
  56756. {
  56757. int numClicks = 0;
  56758. if (mouseDowns[0].time != 0)
  56759. {
  56760. if (! mouseMovedSignificantlySincePressed)
  56761. ++numClicks;
  56762. for (int i = 1; i < numElementsInArray (mouseDowns); ++i)
  56763. {
  56764. if (mouseDowns[0].time - mouseDowns[i].time < (int) (MouseEvent::getDoubleClickTimeout() * (1.0 + 0.25 * (i - 1)))
  56765. && abs (mouseDowns[0].position.getX() - mouseDowns[i].position.getX()) < 8
  56766. && abs (mouseDowns[0].position.getY() - mouseDowns[i].position.getY()) < 8
  56767. && mouseDowns[0].component == mouseDowns[i].component)
  56768. {
  56769. ++numClicks;
  56770. }
  56771. else
  56772. {
  56773. break;
  56774. }
  56775. }
  56776. }
  56777. return numClicks;
  56778. }
  56779. bool hasMouseMovedSignificantlySincePressed() const throw()
  56780. {
  56781. return mouseMovedSignificantlySincePressed
  56782. || lastTime > mouseDowns[0].time + 300;
  56783. }
  56784. void triggerFakeMove()
  56785. {
  56786. triggerAsyncUpdate();
  56787. }
  56788. void handleAsyncUpdate()
  56789. {
  56790. if (! isDragging())
  56791. setScreenPos (Desktop::getMousePosition(), jmax (lastTime, Time::currentTimeMillis()), true);
  56792. }
  56793. void enableUnboundedMouseMovement (bool enable, bool keepCursorVisibleUntilOffscreen)
  56794. {
  56795. enable = enable && isDragging();
  56796. isCursorVisibleUntilOffscreen = keepCursorVisibleUntilOffscreen;
  56797. if (enable != isUnboundedMouseModeOn)
  56798. {
  56799. if ((! enable) && ((! isCursorVisibleUntilOffscreen) || ! unboundedMouseOffset.isOrigin()))
  56800. {
  56801. // when released, return the mouse to within the component's bounds
  56802. Component* current = getComponentUnderMouse();
  56803. if (current != 0)
  56804. Desktop::setMousePosition (current->getScreenBounds()
  56805. .getConstrainedPoint (current->getMouseXYRelative()));
  56806. }
  56807. isUnboundedMouseModeOn = enable;
  56808. unboundedMouseOffset = Point<int>();
  56809. revealCursor (true);
  56810. }
  56811. }
  56812. void handleUnboundedDrag (Component* current)
  56813. {
  56814. const Rectangle<int> screenArea (current->getParentMonitorArea().expanded (-2, -2));
  56815. if (! screenArea.contains (lastScreenPos))
  56816. {
  56817. const Point<int> componentCentre (current->getScreenBounds().getCentre());
  56818. unboundedMouseOffset += (lastScreenPos - componentCentre);
  56819. Desktop::setMousePosition (componentCentre);
  56820. }
  56821. else if (isCursorVisibleUntilOffscreen
  56822. && (! unboundedMouseOffset.isOrigin())
  56823. && screenArea.contains (lastScreenPos + unboundedMouseOffset))
  56824. {
  56825. Desktop::setMousePosition (lastScreenPos + unboundedMouseOffset);
  56826. unboundedMouseOffset = Point<int>();
  56827. }
  56828. }
  56829. void showMouseCursor (MouseCursor cursor, bool forcedUpdate)
  56830. {
  56831. if (isUnboundedMouseModeOn && ((! unboundedMouseOffset.isOrigin()) || ! isCursorVisibleUntilOffscreen))
  56832. {
  56833. cursor = MouseCursor::NoCursor;
  56834. forcedUpdate = true;
  56835. }
  56836. if (forcedUpdate || cursor.getHandle() != currentCursorHandle)
  56837. {
  56838. currentCursorHandle = cursor.getHandle();
  56839. cursor.showInWindow (getPeer());
  56840. }
  56841. }
  56842. void hideCursor()
  56843. {
  56844. showMouseCursor (MouseCursor::NoCursor, true);
  56845. }
  56846. void revealCursor (bool forcedUpdate)
  56847. {
  56848. MouseCursor mc (MouseCursor::NormalCursor);
  56849. Component* current = getComponentUnderMouse();
  56850. if (current != 0)
  56851. mc = current->getLookAndFeel().getMouseCursorFor (*current);
  56852. showMouseCursor (mc, forcedUpdate);
  56853. }
  56854. int index;
  56855. bool isMouseDevice;
  56856. Point<int> lastScreenPos;
  56857. ModifierKeys buttonState;
  56858. private:
  56859. MouseInputSource& source;
  56860. Component::SafePointer<Component> componentUnderMouse;
  56861. ComponentPeer* lastPeer;
  56862. Point<int> unboundedMouseOffset;
  56863. bool isUnboundedMouseModeOn, isCursorVisibleUntilOffscreen;
  56864. void* currentCursorHandle;
  56865. int mouseEventCounter;
  56866. struct RecentMouseDown
  56867. {
  56868. Point<int> position;
  56869. int64 time;
  56870. Component* component;
  56871. };
  56872. RecentMouseDown mouseDowns[4];
  56873. bool mouseMovedSignificantlySincePressed;
  56874. int64 lastTime;
  56875. void registerMouseDown (const Point<int>& screenPos, const int64 time, Component* const component) throw()
  56876. {
  56877. for (int i = numElementsInArray (mouseDowns); --i > 0;)
  56878. mouseDowns[i] = mouseDowns[i - 1];
  56879. mouseDowns[0].position = screenPos;
  56880. mouseDowns[0].time = time;
  56881. mouseDowns[0].component = component;
  56882. mouseMovedSignificantlySincePressed = false;
  56883. }
  56884. void registerMouseDrag (const Point<int>& screenPos) throw()
  56885. {
  56886. mouseMovedSignificantlySincePressed = mouseMovedSignificantlySincePressed
  56887. || mouseDowns[0].position.getDistanceFrom (screenPos) >= 4;
  56888. }
  56889. MouseInputSourceInternal (const MouseInputSourceInternal&);
  56890. MouseInputSourceInternal& operator= (const MouseInputSourceInternal&);
  56891. };
  56892. MouseInputSource::MouseInputSource (const int index, const bool isMouseDevice)
  56893. {
  56894. pimpl = new MouseInputSourceInternal (*this, index, isMouseDevice);
  56895. }
  56896. MouseInputSource::~MouseInputSource()
  56897. {
  56898. }
  56899. bool MouseInputSource::isMouse() const { return pimpl->isMouseDevice; }
  56900. bool MouseInputSource::isTouch() const { return ! isMouse(); }
  56901. bool MouseInputSource::canHover() const { return isMouse(); }
  56902. bool MouseInputSource::hasMouseWheel() const { return isMouse(); }
  56903. int MouseInputSource::getIndex() const { return pimpl->index; }
  56904. bool MouseInputSource::isDragging() const { return pimpl->isDragging(); }
  56905. const Point<int> MouseInputSource::getScreenPosition() const { return pimpl->getScreenPosition(); }
  56906. const ModifierKeys MouseInputSource::getCurrentModifiers() const { return pimpl->getCurrentModifiers(); }
  56907. Component* MouseInputSource::getComponentUnderMouse() const { return pimpl->getComponentUnderMouse(); }
  56908. void MouseInputSource::triggerFakeMove() const { pimpl->triggerFakeMove(); }
  56909. int MouseInputSource::getNumberOfMultipleClicks() const throw() { return pimpl->getNumberOfMultipleClicks(); }
  56910. const Time MouseInputSource::getLastMouseDownTime() const throw() { return pimpl->getLastMouseDownTime(); }
  56911. const Point<int> MouseInputSource::getLastMouseDownPosition() const throw() { return pimpl->getLastMouseDownPosition(); }
  56912. bool MouseInputSource::hasMouseMovedSignificantlySincePressed() const throw() { return pimpl->hasMouseMovedSignificantlySincePressed(); }
  56913. bool MouseInputSource::canDoUnboundedMovement() const throw() { return isMouse(); }
  56914. void MouseInputSource::enableUnboundedMouseMovement (bool isEnabled, bool keepCursorVisibleUntilOffscreen) { pimpl->enableUnboundedMouseMovement (isEnabled, keepCursorVisibleUntilOffscreen); }
  56915. bool MouseInputSource::hasMouseCursor() const throw() { return isMouse(); }
  56916. void MouseInputSource::showMouseCursor (const MouseCursor& cursor) { pimpl->showMouseCursor (cursor, false); }
  56917. void MouseInputSource::hideCursor() { pimpl->hideCursor(); }
  56918. void MouseInputSource::revealCursor() { pimpl->revealCursor (false); }
  56919. void MouseInputSource::forceMouseCursorUpdate() { pimpl->revealCursor (true); }
  56920. void MouseInputSource::handleEvent (ComponentPeer* peer, const Point<int>& positionWithinPeer, const int64 time, const ModifierKeys& mods)
  56921. {
  56922. pimpl->handleEvent (peer, positionWithinPeer, time, mods.withOnlyMouseButtons());
  56923. }
  56924. void MouseInputSource::handleWheel (ComponentPeer* const peer, const Point<int>& positionWithinPeer, const int64 time, const float x, const float y)
  56925. {
  56926. pimpl->handleWheel (peer, positionWithinPeer, time, x, y);
  56927. }
  56928. END_JUCE_NAMESPACE
  56929. /*** End of inlined file: juce_MouseInputSource.cpp ***/
  56930. /*** Start of inlined file: juce_MouseHoverDetector.cpp ***/
  56931. BEGIN_JUCE_NAMESPACE
  56932. MouseHoverDetector::MouseHoverDetector (const int hoverTimeMillisecs_)
  56933. : source (0),
  56934. hoverTimeMillisecs (hoverTimeMillisecs_),
  56935. hasJustHovered (false)
  56936. {
  56937. internalTimer.owner = this;
  56938. }
  56939. MouseHoverDetector::~MouseHoverDetector()
  56940. {
  56941. setHoverComponent (0);
  56942. }
  56943. void MouseHoverDetector::setHoverTimeMillisecs (const int newTimeInMillisecs)
  56944. {
  56945. hoverTimeMillisecs = newTimeInMillisecs;
  56946. }
  56947. void MouseHoverDetector::setHoverComponent (Component* const newSourceComponent)
  56948. {
  56949. if (source != newSourceComponent)
  56950. {
  56951. internalTimer.stopTimer();
  56952. hasJustHovered = false;
  56953. if (source != 0)
  56954. {
  56955. // ! you need to delete the hover detector before deleting its component
  56956. jassert (source->isValidComponent());
  56957. source->removeMouseListener (&internalTimer);
  56958. }
  56959. source = newSourceComponent;
  56960. if (newSourceComponent != 0)
  56961. newSourceComponent->addMouseListener (&internalTimer, false);
  56962. }
  56963. }
  56964. void MouseHoverDetector::hoverTimerCallback()
  56965. {
  56966. internalTimer.stopTimer();
  56967. if (source != 0)
  56968. {
  56969. const Point<int> pos (source->getMouseXYRelative());
  56970. if (source->reallyContains (pos.getX(), pos.getY(), false))
  56971. {
  56972. hasJustHovered = true;
  56973. mouseHovered (pos.getX(), pos.getY());
  56974. }
  56975. }
  56976. }
  56977. void MouseHoverDetector::checkJustHoveredCallback()
  56978. {
  56979. if (hasJustHovered)
  56980. {
  56981. hasJustHovered = false;
  56982. mouseMovedAfterHover();
  56983. }
  56984. }
  56985. void MouseHoverDetector::HoverDetectorInternal::timerCallback()
  56986. {
  56987. owner->hoverTimerCallback();
  56988. }
  56989. void MouseHoverDetector::HoverDetectorInternal::mouseEnter (const MouseEvent&)
  56990. {
  56991. stopTimer();
  56992. owner->checkJustHoveredCallback();
  56993. }
  56994. void MouseHoverDetector::HoverDetectorInternal::mouseExit (const MouseEvent&)
  56995. {
  56996. stopTimer();
  56997. owner->checkJustHoveredCallback();
  56998. }
  56999. void MouseHoverDetector::HoverDetectorInternal::mouseDown (const MouseEvent&)
  57000. {
  57001. stopTimer();
  57002. owner->checkJustHoveredCallback();
  57003. }
  57004. void MouseHoverDetector::HoverDetectorInternal::mouseUp (const MouseEvent&)
  57005. {
  57006. stopTimer();
  57007. owner->checkJustHoveredCallback();
  57008. }
  57009. void MouseHoverDetector::HoverDetectorInternal::mouseMove (const MouseEvent& e)
  57010. {
  57011. if (lastX != e.x || lastY != e.y) // to avoid fake mouse-moves setting it off
  57012. {
  57013. lastX = e.x;
  57014. lastY = e.y;
  57015. if (owner->source != 0)
  57016. startTimer (owner->hoverTimeMillisecs);
  57017. owner->checkJustHoveredCallback();
  57018. }
  57019. }
  57020. void MouseHoverDetector::HoverDetectorInternal::mouseWheelMove (const MouseEvent&, float, float)
  57021. {
  57022. stopTimer();
  57023. owner->checkJustHoveredCallback();
  57024. }
  57025. END_JUCE_NAMESPACE
  57026. /*** End of inlined file: juce_MouseHoverDetector.cpp ***/
  57027. /*** Start of inlined file: juce_MouseListener.cpp ***/
  57028. BEGIN_JUCE_NAMESPACE
  57029. void MouseListener::mouseEnter (const MouseEvent&)
  57030. {
  57031. }
  57032. void MouseListener::mouseExit (const MouseEvent&)
  57033. {
  57034. }
  57035. void MouseListener::mouseDown (const MouseEvent&)
  57036. {
  57037. }
  57038. void MouseListener::mouseUp (const MouseEvent&)
  57039. {
  57040. }
  57041. void MouseListener::mouseDrag (const MouseEvent&)
  57042. {
  57043. }
  57044. void MouseListener::mouseMove (const MouseEvent&)
  57045. {
  57046. }
  57047. void MouseListener::mouseDoubleClick (const MouseEvent&)
  57048. {
  57049. }
  57050. void MouseListener::mouseWheelMove (const MouseEvent&, float, float)
  57051. {
  57052. }
  57053. END_JUCE_NAMESPACE
  57054. /*** End of inlined file: juce_MouseListener.cpp ***/
  57055. /*** Start of inlined file: juce_BooleanPropertyComponent.cpp ***/
  57056. BEGIN_JUCE_NAMESPACE
  57057. BooleanPropertyComponent::BooleanPropertyComponent (const String& name,
  57058. const String& buttonTextWhenTrue,
  57059. const String& buttonTextWhenFalse)
  57060. : PropertyComponent (name),
  57061. onText (buttonTextWhenTrue),
  57062. offText (buttonTextWhenFalse)
  57063. {
  57064. createButton();
  57065. button->addButtonListener (this);
  57066. }
  57067. BooleanPropertyComponent::BooleanPropertyComponent (const Value& valueToControl,
  57068. const String& name,
  57069. const String& buttonText)
  57070. : PropertyComponent (name),
  57071. onText (buttonText),
  57072. offText (buttonText)
  57073. {
  57074. createButton();
  57075. button->setButtonText (buttonText);
  57076. button->getToggleStateValue().referTo (valueToControl);
  57077. button->setClickingTogglesState (true);
  57078. }
  57079. BooleanPropertyComponent::~BooleanPropertyComponent()
  57080. {
  57081. deleteAllChildren();
  57082. }
  57083. void BooleanPropertyComponent::createButton()
  57084. {
  57085. addAndMakeVisible (button = new ToggleButton (String::empty));
  57086. button->setClickingTogglesState (false);
  57087. }
  57088. void BooleanPropertyComponent::setState (const bool newState)
  57089. {
  57090. button->setToggleState (newState, true);
  57091. }
  57092. bool BooleanPropertyComponent::getState() const
  57093. {
  57094. return button->getToggleState();
  57095. }
  57096. void BooleanPropertyComponent::paint (Graphics& g)
  57097. {
  57098. PropertyComponent::paint (g);
  57099. const Rectangle<int> r (button->getBounds());
  57100. g.setColour (Colours::white);
  57101. g.fillRect (r);
  57102. g.setColour (findColour (ComboBox::outlineColourId));
  57103. g.drawRect (r.getX(), r.getY(), r.getWidth(), r.getHeight());
  57104. }
  57105. void BooleanPropertyComponent::refresh()
  57106. {
  57107. button->setToggleState (getState(), false);
  57108. button->setButtonText (button->getToggleState() ? onText : offText);
  57109. }
  57110. void BooleanPropertyComponent::buttonClicked (Button*)
  57111. {
  57112. setState (! getState());
  57113. }
  57114. END_JUCE_NAMESPACE
  57115. /*** End of inlined file: juce_BooleanPropertyComponent.cpp ***/
  57116. /*** Start of inlined file: juce_ButtonPropertyComponent.cpp ***/
  57117. BEGIN_JUCE_NAMESPACE
  57118. ButtonPropertyComponent::ButtonPropertyComponent (const String& name,
  57119. const bool triggerOnMouseDown)
  57120. : PropertyComponent (name)
  57121. {
  57122. addAndMakeVisible (button = new TextButton (String::empty));
  57123. button->setTriggeredOnMouseDown (triggerOnMouseDown);
  57124. button->addButtonListener (this);
  57125. }
  57126. ButtonPropertyComponent::~ButtonPropertyComponent()
  57127. {
  57128. deleteAllChildren();
  57129. }
  57130. void ButtonPropertyComponent::refresh()
  57131. {
  57132. button->setButtonText (getButtonText());
  57133. }
  57134. void ButtonPropertyComponent::buttonClicked (Button*)
  57135. {
  57136. buttonClicked();
  57137. }
  57138. END_JUCE_NAMESPACE
  57139. /*** End of inlined file: juce_ButtonPropertyComponent.cpp ***/
  57140. /*** Start of inlined file: juce_ChoicePropertyComponent.cpp ***/
  57141. BEGIN_JUCE_NAMESPACE
  57142. ChoicePropertyComponent::ChoicePropertyComponent (const String& name)
  57143. : PropertyComponent (name),
  57144. comboBox (0)
  57145. {
  57146. }
  57147. ChoicePropertyComponent::ChoicePropertyComponent (const Value& valueToControl,
  57148. const String& name,
  57149. const StringArray& choices_,
  57150. const Array <int>* choiceIDs)
  57151. : PropertyComponent (name),
  57152. choices (choices_),
  57153. comboBox (0)
  57154. {
  57155. createComboBox (choiceIDs);
  57156. comboBox->getSelectedIdAsValue().referTo (valueToControl);
  57157. }
  57158. ChoicePropertyComponent::~ChoicePropertyComponent()
  57159. {
  57160. deleteAllChildren();
  57161. }
  57162. void ChoicePropertyComponent::createComboBox (const Array <int>* choiceIDs)
  57163. {
  57164. // The array of IDs must contain the same number of values as the choices list!
  57165. jassert (choiceIDs == 0 || choiceIDs->size() == choices.size());
  57166. addAndMakeVisible (comboBox = new ComboBox (String::empty));
  57167. for (int i = 0; i < choices.size(); ++i)
  57168. {
  57169. if (choices[i].isNotEmpty())
  57170. comboBox->addItem (choices[i], choiceIDs == 0 ? (i + 1)
  57171. : ((*choiceIDs)[i]));
  57172. else
  57173. comboBox->addSeparator();
  57174. }
  57175. comboBox->setEditableText (false);
  57176. }
  57177. void ChoicePropertyComponent::setIndex (const int newIndex)
  57178. {
  57179. comboBox->setSelectedId (comboBox->getItemId (newIndex));
  57180. }
  57181. int ChoicePropertyComponent::getIndex() const
  57182. {
  57183. return comboBox->getSelectedItemIndex();
  57184. }
  57185. const StringArray& ChoicePropertyComponent::getChoices() const
  57186. {
  57187. return choices;
  57188. }
  57189. void ChoicePropertyComponent::refresh()
  57190. {
  57191. if (comboBox == 0)
  57192. {
  57193. createComboBox (0);
  57194. comboBox->addListener (this);
  57195. }
  57196. comboBox->setSelectedId (getIndex() + 1, true);
  57197. }
  57198. void ChoicePropertyComponent::comboBoxChanged (ComboBox*)
  57199. {
  57200. const int newIndex = comboBox->getSelectedId() - 1;
  57201. if (newIndex != getIndex())
  57202. setIndex (newIndex);
  57203. }
  57204. END_JUCE_NAMESPACE
  57205. /*** End of inlined file: juce_ChoicePropertyComponent.cpp ***/
  57206. /*** Start of inlined file: juce_PropertyComponent.cpp ***/
  57207. BEGIN_JUCE_NAMESPACE
  57208. PropertyComponent::PropertyComponent (const String& name,
  57209. const int preferredHeight_)
  57210. : Component (name),
  57211. preferredHeight (preferredHeight_)
  57212. {
  57213. jassert (name.isNotEmpty());
  57214. }
  57215. PropertyComponent::~PropertyComponent()
  57216. {
  57217. }
  57218. void PropertyComponent::paint (Graphics& g)
  57219. {
  57220. getLookAndFeel().drawPropertyComponentBackground (g, getWidth(), getHeight(), *this);
  57221. getLookAndFeel().drawPropertyComponentLabel (g, getWidth(), getHeight(), *this);
  57222. }
  57223. void PropertyComponent::resized()
  57224. {
  57225. if (getNumChildComponents() > 0)
  57226. getChildComponent (0)->setBounds (getLookAndFeel().getPropertyComponentContentPosition (*this));
  57227. }
  57228. void PropertyComponent::enablementChanged()
  57229. {
  57230. repaint();
  57231. }
  57232. END_JUCE_NAMESPACE
  57233. /*** End of inlined file: juce_PropertyComponent.cpp ***/
  57234. /*** Start of inlined file: juce_PropertyPanel.cpp ***/
  57235. BEGIN_JUCE_NAMESPACE
  57236. class PropertyPanel::PropertyHolderComponent : public Component
  57237. {
  57238. public:
  57239. PropertyHolderComponent()
  57240. {
  57241. }
  57242. ~PropertyHolderComponent()
  57243. {
  57244. deleteAllChildren();
  57245. }
  57246. void paint (Graphics&)
  57247. {
  57248. }
  57249. void updateLayout (int width);
  57250. void refreshAll() const;
  57251. private:
  57252. PropertyHolderComponent (const PropertyHolderComponent&);
  57253. PropertyHolderComponent& operator= (const PropertyHolderComponent&);
  57254. };
  57255. class PropertySectionComponent : public Component
  57256. {
  57257. public:
  57258. PropertySectionComponent (const String& sectionTitle,
  57259. const Array <PropertyComponent*>& newProperties,
  57260. const bool open)
  57261. : Component (sectionTitle),
  57262. titleHeight (sectionTitle.isNotEmpty() ? 22 : 0),
  57263. isOpen_ (open)
  57264. {
  57265. for (int i = newProperties.size(); --i >= 0;)
  57266. {
  57267. addAndMakeVisible (newProperties.getUnchecked(i));
  57268. newProperties.getUnchecked(i)->refresh();
  57269. }
  57270. }
  57271. ~PropertySectionComponent()
  57272. {
  57273. deleteAllChildren();
  57274. }
  57275. void paint (Graphics& g)
  57276. {
  57277. if (titleHeight > 0)
  57278. getLookAndFeel().drawPropertyPanelSectionHeader (g, getName(), isOpen(), getWidth(), titleHeight);
  57279. }
  57280. void resized()
  57281. {
  57282. int y = titleHeight;
  57283. for (int i = getNumChildComponents(); --i >= 0;)
  57284. {
  57285. PropertyComponent* const pec = dynamic_cast <PropertyComponent*> (getChildComponent (i));
  57286. if (pec != 0)
  57287. {
  57288. const int prefH = pec->getPreferredHeight();
  57289. pec->setBounds (1, y, getWidth() - 2, prefH);
  57290. y += prefH;
  57291. }
  57292. }
  57293. }
  57294. int getPreferredHeight() const
  57295. {
  57296. int y = titleHeight;
  57297. if (isOpen())
  57298. {
  57299. for (int i = 0; i < getNumChildComponents(); ++i)
  57300. {
  57301. PropertyComponent* pec = dynamic_cast <PropertyComponent*> (getChildComponent (i));
  57302. if (pec != 0)
  57303. y += pec->getPreferredHeight();
  57304. }
  57305. }
  57306. return y;
  57307. }
  57308. void setOpen (const bool open)
  57309. {
  57310. if (isOpen_ != open)
  57311. {
  57312. isOpen_ = open;
  57313. for (int i = 0; i < getNumChildComponents(); ++i)
  57314. {
  57315. PropertyComponent* pec = dynamic_cast <PropertyComponent*> (getChildComponent (i));
  57316. if (pec != 0)
  57317. pec->setVisible (open);
  57318. }
  57319. // (unable to use the syntax findParentComponentOfClass <DragAndDropContainer> () because of a VC6 compiler bug)
  57320. PropertyPanel* const pp = findParentComponentOfClass ((PropertyPanel*) 0);
  57321. if (pp != 0)
  57322. pp->resized();
  57323. }
  57324. }
  57325. bool isOpen() const
  57326. {
  57327. return isOpen_;
  57328. }
  57329. void refreshAll() const
  57330. {
  57331. for (int i = 0; i < getNumChildComponents(); ++i)
  57332. {
  57333. PropertyComponent* pec = dynamic_cast <PropertyComponent*> (getChildComponent (i));
  57334. if (pec != 0)
  57335. pec->refresh();
  57336. }
  57337. }
  57338. void mouseDown (const MouseEvent&)
  57339. {
  57340. }
  57341. void mouseUp (const MouseEvent& e)
  57342. {
  57343. if (e.getMouseDownX() < titleHeight
  57344. && e.x < titleHeight
  57345. && e.y < titleHeight
  57346. && e.getNumberOfClicks() != 2)
  57347. {
  57348. setOpen (! isOpen());
  57349. }
  57350. }
  57351. void mouseDoubleClick (const MouseEvent& e)
  57352. {
  57353. if (e.y < titleHeight)
  57354. setOpen (! isOpen());
  57355. }
  57356. private:
  57357. int titleHeight;
  57358. bool isOpen_;
  57359. PropertySectionComponent (const PropertySectionComponent&);
  57360. PropertySectionComponent& operator= (const PropertySectionComponent&);
  57361. };
  57362. void PropertyPanel::PropertyHolderComponent::updateLayout (const int width)
  57363. {
  57364. int y = 0;
  57365. for (int i = getNumChildComponents(); --i >= 0;)
  57366. {
  57367. PropertySectionComponent* const section
  57368. = dynamic_cast <PropertySectionComponent*> (getChildComponent (i));
  57369. if (section != 0)
  57370. {
  57371. const int prefH = section->getPreferredHeight();
  57372. section->setBounds (0, y, width, prefH);
  57373. y += prefH;
  57374. }
  57375. }
  57376. setSize (width, y);
  57377. repaint();
  57378. }
  57379. void PropertyPanel::PropertyHolderComponent::refreshAll() const
  57380. {
  57381. for (int i = getNumChildComponents(); --i >= 0;)
  57382. {
  57383. PropertySectionComponent* const section
  57384. = dynamic_cast <PropertySectionComponent*> (getChildComponent (i));
  57385. if (section != 0)
  57386. section->refreshAll();
  57387. }
  57388. }
  57389. PropertyPanel::PropertyPanel()
  57390. {
  57391. messageWhenEmpty = TRANS("(nothing selected)");
  57392. addAndMakeVisible (viewport = new Viewport());
  57393. viewport->setViewedComponent (propertyHolderComponent = new PropertyHolderComponent());
  57394. viewport->setFocusContainer (true);
  57395. }
  57396. PropertyPanel::~PropertyPanel()
  57397. {
  57398. clear();
  57399. deleteAllChildren();
  57400. }
  57401. void PropertyPanel::paint (Graphics& g)
  57402. {
  57403. if (propertyHolderComponent->getNumChildComponents() == 0)
  57404. {
  57405. g.setColour (Colours::black.withAlpha (0.5f));
  57406. g.setFont (14.0f);
  57407. g.drawText (messageWhenEmpty, 0, 0, getWidth(), 30,
  57408. Justification::centred, true);
  57409. }
  57410. }
  57411. void PropertyPanel::resized()
  57412. {
  57413. viewport->setBounds (0, 0, getWidth(), getHeight());
  57414. updatePropHolderLayout();
  57415. }
  57416. void PropertyPanel::clear()
  57417. {
  57418. if (propertyHolderComponent->getNumChildComponents() > 0)
  57419. {
  57420. propertyHolderComponent->deleteAllChildren();
  57421. repaint();
  57422. }
  57423. }
  57424. void PropertyPanel::addProperties (const Array <PropertyComponent*>& newProperties)
  57425. {
  57426. if (propertyHolderComponent->getNumChildComponents() == 0)
  57427. repaint();
  57428. propertyHolderComponent->addAndMakeVisible (new PropertySectionComponent (String::empty,
  57429. newProperties,
  57430. true), 0);
  57431. updatePropHolderLayout();
  57432. }
  57433. void PropertyPanel::addSection (const String& sectionTitle,
  57434. const Array <PropertyComponent*>& newProperties,
  57435. const bool shouldBeOpen)
  57436. {
  57437. jassert (sectionTitle.isNotEmpty());
  57438. if (propertyHolderComponent->getNumChildComponents() == 0)
  57439. repaint();
  57440. propertyHolderComponent->addAndMakeVisible (new PropertySectionComponent (sectionTitle,
  57441. newProperties,
  57442. shouldBeOpen), 0);
  57443. updatePropHolderLayout();
  57444. }
  57445. void PropertyPanel::updatePropHolderLayout() const
  57446. {
  57447. const int maxWidth = viewport->getMaximumVisibleWidth();
  57448. propertyHolderComponent->updateLayout (maxWidth);
  57449. const int newMaxWidth = viewport->getMaximumVisibleWidth();
  57450. if (maxWidth != newMaxWidth)
  57451. {
  57452. // need to do this twice because of scrollbars changing the size, etc.
  57453. propertyHolderComponent->updateLayout (newMaxWidth);
  57454. }
  57455. }
  57456. void PropertyPanel::refreshAll() const
  57457. {
  57458. propertyHolderComponent->refreshAll();
  57459. }
  57460. const StringArray PropertyPanel::getSectionNames() const
  57461. {
  57462. StringArray s;
  57463. for (int i = 0; i < propertyHolderComponent->getNumChildComponents(); ++i)
  57464. {
  57465. PropertySectionComponent* const section = dynamic_cast <PropertySectionComponent*> (propertyHolderComponent->getChildComponent (i));
  57466. if (section != 0 && section->getName().isNotEmpty())
  57467. s.add (section->getName());
  57468. }
  57469. return s;
  57470. }
  57471. bool PropertyPanel::isSectionOpen (const int sectionIndex) const
  57472. {
  57473. int index = 0;
  57474. for (int i = 0; i < propertyHolderComponent->getNumChildComponents(); ++i)
  57475. {
  57476. PropertySectionComponent* const section = dynamic_cast <PropertySectionComponent*> (propertyHolderComponent->getChildComponent (i));
  57477. if (section != 0 && section->getName().isNotEmpty())
  57478. {
  57479. if (index == sectionIndex)
  57480. return section->isOpen();
  57481. ++index;
  57482. }
  57483. }
  57484. return false;
  57485. }
  57486. void PropertyPanel::setSectionOpen (const int sectionIndex, const bool shouldBeOpen)
  57487. {
  57488. int index = 0;
  57489. for (int i = 0; i < propertyHolderComponent->getNumChildComponents(); ++i)
  57490. {
  57491. PropertySectionComponent* const section = dynamic_cast <PropertySectionComponent*> (propertyHolderComponent->getChildComponent (i));
  57492. if (section != 0 && section->getName().isNotEmpty())
  57493. {
  57494. if (index == sectionIndex)
  57495. {
  57496. section->setOpen (shouldBeOpen);
  57497. break;
  57498. }
  57499. ++index;
  57500. }
  57501. }
  57502. }
  57503. void PropertyPanel::setSectionEnabled (const int sectionIndex, const bool shouldBeEnabled)
  57504. {
  57505. int index = 0;
  57506. for (int i = 0; i < propertyHolderComponent->getNumChildComponents(); ++i)
  57507. {
  57508. PropertySectionComponent* const section = dynamic_cast <PropertySectionComponent*> (propertyHolderComponent->getChildComponent (i));
  57509. if (section != 0 && section->getName().isNotEmpty())
  57510. {
  57511. if (index == sectionIndex)
  57512. {
  57513. section->setEnabled (shouldBeEnabled);
  57514. break;
  57515. }
  57516. ++index;
  57517. }
  57518. }
  57519. }
  57520. XmlElement* PropertyPanel::getOpennessState() const
  57521. {
  57522. XmlElement* const xml = new XmlElement ("PROPERTYPANELSTATE");
  57523. xml->setAttribute ("scrollPos", viewport->getViewPositionY());
  57524. const StringArray sections (getSectionNames());
  57525. for (int i = 0; i < sections.size(); ++i)
  57526. {
  57527. if (sections[i].isNotEmpty())
  57528. {
  57529. XmlElement* const e = xml->createNewChildElement ("SECTION");
  57530. e->setAttribute ("name", sections[i]);
  57531. e->setAttribute ("open", isSectionOpen (i) ? 1 : 0);
  57532. }
  57533. }
  57534. return xml;
  57535. }
  57536. void PropertyPanel::restoreOpennessState (const XmlElement& xml)
  57537. {
  57538. if (xml.hasTagName ("PROPERTYPANELSTATE"))
  57539. {
  57540. const StringArray sections (getSectionNames());
  57541. forEachXmlChildElementWithTagName (xml, e, "SECTION")
  57542. {
  57543. setSectionOpen (sections.indexOf (e->getStringAttribute ("name")),
  57544. e->getBoolAttribute ("open"));
  57545. }
  57546. viewport->setViewPosition (viewport->getViewPositionX(),
  57547. xml.getIntAttribute ("scrollPos", viewport->getViewPositionY()));
  57548. }
  57549. }
  57550. void PropertyPanel::setMessageWhenEmpty (const String& newMessage)
  57551. {
  57552. if (messageWhenEmpty != newMessage)
  57553. {
  57554. messageWhenEmpty = newMessage;
  57555. repaint();
  57556. }
  57557. }
  57558. const String& PropertyPanel::getMessageWhenEmpty() const
  57559. {
  57560. return messageWhenEmpty;
  57561. }
  57562. END_JUCE_NAMESPACE
  57563. /*** End of inlined file: juce_PropertyPanel.cpp ***/
  57564. /*** Start of inlined file: juce_SliderPropertyComponent.cpp ***/
  57565. BEGIN_JUCE_NAMESPACE
  57566. SliderPropertyComponent::SliderPropertyComponent (const String& name,
  57567. const double rangeMin,
  57568. const double rangeMax,
  57569. const double interval,
  57570. const double skewFactor)
  57571. : PropertyComponent (name)
  57572. {
  57573. addAndMakeVisible (slider = new Slider (name));
  57574. slider->setRange (rangeMin, rangeMax, interval);
  57575. slider->setSkewFactor (skewFactor);
  57576. slider->setSliderStyle (Slider::LinearBar);
  57577. slider->addListener (this);
  57578. }
  57579. SliderPropertyComponent::SliderPropertyComponent (const Value& valueToControl,
  57580. const String& name,
  57581. const double rangeMin,
  57582. const double rangeMax,
  57583. const double interval,
  57584. const double skewFactor)
  57585. : PropertyComponent (name)
  57586. {
  57587. addAndMakeVisible (slider = new Slider (name));
  57588. slider->setRange (rangeMin, rangeMax, interval);
  57589. slider->setSkewFactor (skewFactor);
  57590. slider->setSliderStyle (Slider::LinearBar);
  57591. slider->getValueObject().referTo (valueToControl);
  57592. }
  57593. SliderPropertyComponent::~SliderPropertyComponent()
  57594. {
  57595. deleteAllChildren();
  57596. }
  57597. void SliderPropertyComponent::setValue (const double /*newValue*/)
  57598. {
  57599. }
  57600. double SliderPropertyComponent::getValue() const
  57601. {
  57602. return slider->getValue();
  57603. }
  57604. void SliderPropertyComponent::refresh()
  57605. {
  57606. slider->setValue (getValue(), false);
  57607. }
  57608. void SliderPropertyComponent::sliderValueChanged (Slider*)
  57609. {
  57610. if (getValue() != slider->getValue())
  57611. setValue (slider->getValue());
  57612. }
  57613. END_JUCE_NAMESPACE
  57614. /*** End of inlined file: juce_SliderPropertyComponent.cpp ***/
  57615. /*** Start of inlined file: juce_TextPropertyComponent.cpp ***/
  57616. BEGIN_JUCE_NAMESPACE
  57617. class TextPropLabel : public Label
  57618. {
  57619. TextPropertyComponent& owner;
  57620. int maxChars;
  57621. bool isMultiline;
  57622. public:
  57623. TextPropLabel (TextPropertyComponent& owner_,
  57624. const int maxChars_, const bool isMultiline_)
  57625. : Label (String::empty, String::empty),
  57626. owner (owner_),
  57627. maxChars (maxChars_),
  57628. isMultiline (isMultiline_)
  57629. {
  57630. setEditable (true, true, false);
  57631. setColour (backgroundColourId, Colours::white);
  57632. setColour (outlineColourId, findColour (ComboBox::outlineColourId));
  57633. }
  57634. ~TextPropLabel()
  57635. {
  57636. }
  57637. TextEditor* createEditorComponent()
  57638. {
  57639. TextEditor* const textEditor = Label::createEditorComponent();
  57640. textEditor->setInputRestrictions (maxChars);
  57641. if (isMultiline)
  57642. {
  57643. textEditor->setMultiLine (true, true);
  57644. textEditor->setReturnKeyStartsNewLine (true);
  57645. }
  57646. return textEditor;
  57647. }
  57648. void textWasEdited()
  57649. {
  57650. owner.textWasEdited();
  57651. }
  57652. };
  57653. TextPropertyComponent::TextPropertyComponent (const String& name,
  57654. const int maxNumChars,
  57655. const bool isMultiLine)
  57656. : PropertyComponent (name)
  57657. {
  57658. createEditor (maxNumChars, isMultiLine);
  57659. }
  57660. TextPropertyComponent::TextPropertyComponent (const Value& valueToControl,
  57661. const String& name,
  57662. const int maxNumChars,
  57663. const bool isMultiLine)
  57664. : PropertyComponent (name)
  57665. {
  57666. createEditor (maxNumChars, isMultiLine);
  57667. textEditor->getTextValue().referTo (valueToControl);
  57668. }
  57669. TextPropertyComponent::~TextPropertyComponent()
  57670. {
  57671. deleteAllChildren();
  57672. }
  57673. void TextPropertyComponent::setText (const String& newText)
  57674. {
  57675. textEditor->setText (newText, true);
  57676. }
  57677. const String TextPropertyComponent::getText() const
  57678. {
  57679. return textEditor->getText();
  57680. }
  57681. void TextPropertyComponent::createEditor (const int maxNumChars, const bool isMultiLine)
  57682. {
  57683. addAndMakeVisible (textEditor = new TextPropLabel (*this, maxNumChars, isMultiLine));
  57684. if (isMultiLine)
  57685. {
  57686. textEditor->setJustificationType (Justification::topLeft);
  57687. preferredHeight = 120;
  57688. }
  57689. }
  57690. void TextPropertyComponent::refresh()
  57691. {
  57692. textEditor->setText (getText(), false);
  57693. }
  57694. void TextPropertyComponent::textWasEdited()
  57695. {
  57696. const String newText (textEditor->getText());
  57697. if (getText() != newText)
  57698. setText (newText);
  57699. }
  57700. END_JUCE_NAMESPACE
  57701. /*** End of inlined file: juce_TextPropertyComponent.cpp ***/
  57702. /*** Start of inlined file: juce_AudioDeviceSelectorComponent.cpp ***/
  57703. BEGIN_JUCE_NAMESPACE
  57704. class SimpleDeviceManagerInputLevelMeter : public Component,
  57705. public Timer
  57706. {
  57707. public:
  57708. SimpleDeviceManagerInputLevelMeter (AudioDeviceManager* const manager_)
  57709. : manager (manager_),
  57710. level (0)
  57711. {
  57712. startTimer (50);
  57713. manager->enableInputLevelMeasurement (true);
  57714. }
  57715. ~SimpleDeviceManagerInputLevelMeter()
  57716. {
  57717. manager->enableInputLevelMeasurement (false);
  57718. }
  57719. void timerCallback()
  57720. {
  57721. const float newLevel = (float) manager->getCurrentInputLevel();
  57722. if (fabsf (level - newLevel) > 0.005f)
  57723. {
  57724. level = newLevel;
  57725. repaint();
  57726. }
  57727. }
  57728. void paint (Graphics& g)
  57729. {
  57730. getLookAndFeel().drawLevelMeter (g, getWidth(), getHeight(),
  57731. (float) exp (log (level) / 3.0)); // (add a bit of a skew to make the level more obvious)
  57732. }
  57733. private:
  57734. AudioDeviceManager* const manager;
  57735. float level;
  57736. SimpleDeviceManagerInputLevelMeter (const SimpleDeviceManagerInputLevelMeter&);
  57737. SimpleDeviceManagerInputLevelMeter& operator= (const SimpleDeviceManagerInputLevelMeter&);
  57738. };
  57739. class AudioDeviceSelectorComponent::MidiInputSelectorComponentListBox : public ListBox,
  57740. public ListBoxModel
  57741. {
  57742. public:
  57743. MidiInputSelectorComponentListBox (AudioDeviceManager& deviceManager_,
  57744. const String& noItemsMessage_,
  57745. const int minNumber_,
  57746. const int maxNumber_)
  57747. : ListBox (String::empty, 0),
  57748. deviceManager (deviceManager_),
  57749. noItemsMessage (noItemsMessage_),
  57750. minNumber (minNumber_),
  57751. maxNumber (maxNumber_)
  57752. {
  57753. items = MidiInput::getDevices();
  57754. setModel (this);
  57755. setOutlineThickness (1);
  57756. }
  57757. ~MidiInputSelectorComponentListBox()
  57758. {
  57759. }
  57760. int getNumRows()
  57761. {
  57762. return items.size();
  57763. }
  57764. void paintListBoxItem (int row,
  57765. Graphics& g,
  57766. int width, int height,
  57767. bool rowIsSelected)
  57768. {
  57769. if (((unsigned int) row) < (unsigned int) items.size())
  57770. {
  57771. if (rowIsSelected)
  57772. g.fillAll (findColour (TextEditor::highlightColourId)
  57773. .withMultipliedAlpha (0.3f));
  57774. const String item (items [row]);
  57775. bool enabled = deviceManager.isMidiInputEnabled (item);
  57776. const int x = getTickX();
  57777. const float tickW = height * 0.75f;
  57778. getLookAndFeel().drawTickBox (g, *this, x - tickW, (height - tickW) / 2, tickW, tickW,
  57779. enabled, true, true, false);
  57780. g.setFont (height * 0.6f);
  57781. g.setColour (findColour (ListBox::textColourId, true).withMultipliedAlpha (enabled ? 1.0f : 0.6f));
  57782. g.drawText (item, x, 0, width - x - 2, height, Justification::centredLeft, true);
  57783. }
  57784. }
  57785. void listBoxItemClicked (int row, const MouseEvent& e)
  57786. {
  57787. selectRow (row);
  57788. if (e.x < getTickX())
  57789. flipEnablement (row);
  57790. }
  57791. void listBoxItemDoubleClicked (int row, const MouseEvent&)
  57792. {
  57793. flipEnablement (row);
  57794. }
  57795. void returnKeyPressed (int row)
  57796. {
  57797. flipEnablement (row);
  57798. }
  57799. void paint (Graphics& g)
  57800. {
  57801. ListBox::paint (g);
  57802. if (items.size() == 0)
  57803. {
  57804. g.setColour (Colours::grey);
  57805. g.setFont (13.0f);
  57806. g.drawText (noItemsMessage,
  57807. 0, 0, getWidth(), getHeight() / 2,
  57808. Justification::centred, true);
  57809. }
  57810. }
  57811. int getBestHeight (const int preferredHeight)
  57812. {
  57813. const int extra = getOutlineThickness() * 2;
  57814. return jmax (getRowHeight() * 2 + extra,
  57815. jmin (getRowHeight() * getNumRows() + extra,
  57816. preferredHeight));
  57817. }
  57818. juce_UseDebuggingNewOperator
  57819. private:
  57820. AudioDeviceManager& deviceManager;
  57821. const String noItemsMessage;
  57822. StringArray items;
  57823. int minNumber, maxNumber;
  57824. void flipEnablement (const int row)
  57825. {
  57826. if (((unsigned int) row) < (unsigned int) items.size())
  57827. {
  57828. const String item (items [row]);
  57829. deviceManager.setMidiInputEnabled (item, ! deviceManager.isMidiInputEnabled (item));
  57830. }
  57831. }
  57832. int getTickX() const
  57833. {
  57834. return getRowHeight() + 5;
  57835. }
  57836. MidiInputSelectorComponentListBox (const MidiInputSelectorComponentListBox&);
  57837. MidiInputSelectorComponentListBox& operator= (const MidiInputSelectorComponentListBox&);
  57838. };
  57839. class AudioDeviceSettingsPanel : public Component,
  57840. public ComboBoxListener,
  57841. public ChangeListener,
  57842. public ButtonListener
  57843. {
  57844. public:
  57845. AudioDeviceSettingsPanel (AudioIODeviceType* type_,
  57846. AudioIODeviceType::DeviceSetupDetails& setup_,
  57847. const bool hideAdvancedOptionsWithButton)
  57848. : type (type_),
  57849. setup (setup_)
  57850. {
  57851. sampleRateDropDown = 0;
  57852. sampleRateLabel = 0;
  57853. bufferSizeDropDown = 0;
  57854. bufferSizeLabel = 0;
  57855. outputDeviceDropDown = 0;
  57856. outputDeviceLabel = 0;
  57857. inputDeviceDropDown = 0;
  57858. inputDeviceLabel = 0;
  57859. testButton = 0;
  57860. inputLevelMeter = 0;
  57861. showUIButton = 0;
  57862. inputChanList = 0;
  57863. outputChanList = 0;
  57864. inputChanLabel = 0;
  57865. outputChanLabel = 0;
  57866. showAdvancedSettingsButton = 0;
  57867. if (hideAdvancedOptionsWithButton)
  57868. {
  57869. addAndMakeVisible (showAdvancedSettingsButton = new TextButton (TRANS("Show advanced settings...")));
  57870. showAdvancedSettingsButton->addButtonListener (this);
  57871. }
  57872. type->scanForDevices();
  57873. setup.manager->addChangeListener (this);
  57874. changeListenerCallback (0);
  57875. }
  57876. ~AudioDeviceSettingsPanel()
  57877. {
  57878. setup.manager->removeChangeListener (this);
  57879. deleteAndZero (outputDeviceLabel);
  57880. deleteAndZero (inputDeviceLabel);
  57881. deleteAndZero (sampleRateLabel);
  57882. deleteAndZero (bufferSizeLabel);
  57883. deleteAndZero (showUIButton);
  57884. deleteAndZero (inputChanLabel);
  57885. deleteAndZero (outputChanLabel);
  57886. deleteAndZero (showAdvancedSettingsButton);
  57887. deleteAllChildren();
  57888. }
  57889. void resized()
  57890. {
  57891. const int lx = proportionOfWidth (0.35f);
  57892. const int w = proportionOfWidth (0.4f);
  57893. const int h = 24;
  57894. const int space = 6;
  57895. const int dh = h + space;
  57896. int y = 0;
  57897. if (outputDeviceDropDown != 0)
  57898. {
  57899. outputDeviceDropDown->setBounds (lx, y, w, h);
  57900. if (testButton != 0)
  57901. testButton->setBounds (proportionOfWidth (0.77f),
  57902. outputDeviceDropDown->getY(),
  57903. proportionOfWidth (0.18f),
  57904. h);
  57905. y += dh;
  57906. }
  57907. if (inputDeviceDropDown != 0)
  57908. {
  57909. inputDeviceDropDown->setBounds (lx, y, w, h);
  57910. inputLevelMeter->setBounds (proportionOfWidth (0.77f),
  57911. inputDeviceDropDown->getY(),
  57912. proportionOfWidth (0.18f),
  57913. h);
  57914. y += dh;
  57915. }
  57916. const int maxBoxHeight = 100;//(getHeight() - y - dh * 2) / numBoxes;
  57917. if (outputChanList != 0)
  57918. {
  57919. const int bh = outputChanList->getBestHeight (maxBoxHeight);
  57920. outputChanList->setBounds (lx, y, proportionOfWidth (0.55f), bh);
  57921. y += bh + space;
  57922. }
  57923. if (inputChanList != 0)
  57924. {
  57925. const int bh = inputChanList->getBestHeight (maxBoxHeight);
  57926. inputChanList->setBounds (lx, y, proportionOfWidth (0.55f), bh);
  57927. y += bh + space;
  57928. }
  57929. y += space * 2;
  57930. if (showAdvancedSettingsButton != 0)
  57931. {
  57932. showAdvancedSettingsButton->changeWidthToFitText (h);
  57933. showAdvancedSettingsButton->setTopLeftPosition (lx, y);
  57934. }
  57935. if (sampleRateDropDown != 0)
  57936. {
  57937. sampleRateDropDown->setVisible (showAdvancedSettingsButton == 0
  57938. || ! showAdvancedSettingsButton->isVisible());
  57939. sampleRateDropDown->setBounds (lx, y, w, h);
  57940. y += dh;
  57941. }
  57942. if (bufferSizeDropDown != 0)
  57943. {
  57944. bufferSizeDropDown->setVisible (showAdvancedSettingsButton == 0
  57945. || ! showAdvancedSettingsButton->isVisible());
  57946. bufferSizeDropDown->setBounds (lx, y, w, h);
  57947. y += dh;
  57948. }
  57949. if (showUIButton != 0)
  57950. {
  57951. showUIButton->setVisible (showAdvancedSettingsButton == 0
  57952. || ! showAdvancedSettingsButton->isVisible());
  57953. showUIButton->changeWidthToFitText (h);
  57954. showUIButton->setTopLeftPosition (lx, y);
  57955. }
  57956. }
  57957. void comboBoxChanged (ComboBox* comboBoxThatHasChanged)
  57958. {
  57959. if (comboBoxThatHasChanged == 0)
  57960. return;
  57961. AudioDeviceManager::AudioDeviceSetup config;
  57962. setup.manager->getAudioDeviceSetup (config);
  57963. String error;
  57964. if (comboBoxThatHasChanged == outputDeviceDropDown
  57965. || comboBoxThatHasChanged == inputDeviceDropDown)
  57966. {
  57967. if (outputDeviceDropDown != 0)
  57968. config.outputDeviceName = outputDeviceDropDown->getSelectedId() < 0 ? String::empty
  57969. : outputDeviceDropDown->getText();
  57970. if (inputDeviceDropDown != 0)
  57971. config.inputDeviceName = inputDeviceDropDown->getSelectedId() < 0 ? String::empty
  57972. : inputDeviceDropDown->getText();
  57973. if (! type->hasSeparateInputsAndOutputs())
  57974. config.inputDeviceName = config.outputDeviceName;
  57975. if (comboBoxThatHasChanged == inputDeviceDropDown)
  57976. config.useDefaultInputChannels = true;
  57977. else
  57978. config.useDefaultOutputChannels = true;
  57979. error = setup.manager->setAudioDeviceSetup (config, true);
  57980. showCorrectDeviceName (inputDeviceDropDown, true);
  57981. showCorrectDeviceName (outputDeviceDropDown, false);
  57982. updateControlPanelButton();
  57983. resized();
  57984. }
  57985. else if (comboBoxThatHasChanged == sampleRateDropDown)
  57986. {
  57987. if (sampleRateDropDown->getSelectedId() > 0)
  57988. {
  57989. config.sampleRate = sampleRateDropDown->getSelectedId();
  57990. error = setup.manager->setAudioDeviceSetup (config, true);
  57991. }
  57992. }
  57993. else if (comboBoxThatHasChanged == bufferSizeDropDown)
  57994. {
  57995. if (bufferSizeDropDown->getSelectedId() > 0)
  57996. {
  57997. config.bufferSize = bufferSizeDropDown->getSelectedId();
  57998. error = setup.manager->setAudioDeviceSetup (config, true);
  57999. }
  58000. }
  58001. if (error.isNotEmpty())
  58002. {
  58003. AlertWindow::showMessageBox (AlertWindow::WarningIcon,
  58004. "Error when trying to open audio device!",
  58005. error);
  58006. }
  58007. }
  58008. void buttonClicked (Button* button)
  58009. {
  58010. if (button == showAdvancedSettingsButton)
  58011. {
  58012. showAdvancedSettingsButton->setVisible (false);
  58013. resized();
  58014. }
  58015. else if (button == showUIButton)
  58016. {
  58017. AudioIODevice* const device = setup.manager->getCurrentAudioDevice();
  58018. if (device != 0 && device->showControlPanel())
  58019. {
  58020. setup.manager->closeAudioDevice();
  58021. setup.manager->restartLastAudioDevice();
  58022. getTopLevelComponent()->toFront (true);
  58023. }
  58024. }
  58025. else if (button == testButton && testButton != 0)
  58026. {
  58027. setup.manager->playTestSound();
  58028. }
  58029. }
  58030. void updateControlPanelButton()
  58031. {
  58032. AudioIODevice* const currentDevice = setup.manager->getCurrentAudioDevice();
  58033. deleteAndZero (showUIButton);
  58034. if (currentDevice != 0 && currentDevice->hasControlPanel())
  58035. {
  58036. addAndMakeVisible (showUIButton = new TextButton (TRANS ("show this device's control panel"),
  58037. TRANS ("opens the device's own control panel")));
  58038. showUIButton->addButtonListener (this);
  58039. }
  58040. resized();
  58041. }
  58042. void changeListenerCallback (void*)
  58043. {
  58044. AudioIODevice* const currentDevice = setup.manager->getCurrentAudioDevice();
  58045. if (setup.maxNumOutputChannels > 0 || ! type->hasSeparateInputsAndOutputs())
  58046. {
  58047. if (outputDeviceDropDown == 0)
  58048. {
  58049. outputDeviceDropDown = new ComboBox (String::empty);
  58050. outputDeviceDropDown->addListener (this);
  58051. addAndMakeVisible (outputDeviceDropDown);
  58052. outputDeviceLabel = new Label (String::empty,
  58053. type->hasSeparateInputsAndOutputs() ? TRANS ("output:")
  58054. : TRANS ("device:"));
  58055. outputDeviceLabel->attachToComponent (outputDeviceDropDown, true);
  58056. if (setup.maxNumOutputChannels > 0)
  58057. {
  58058. addAndMakeVisible (testButton = new TextButton (TRANS ("Test")));
  58059. testButton->addButtonListener (this);
  58060. }
  58061. }
  58062. addNamesToDeviceBox (*outputDeviceDropDown, false);
  58063. }
  58064. if (setup.maxNumInputChannels > 0 && type->hasSeparateInputsAndOutputs())
  58065. {
  58066. if (inputDeviceDropDown == 0)
  58067. {
  58068. inputDeviceDropDown = new ComboBox (String::empty);
  58069. inputDeviceDropDown->addListener (this);
  58070. addAndMakeVisible (inputDeviceDropDown);
  58071. inputDeviceLabel = new Label (String::empty, TRANS ("input:"));
  58072. inputDeviceLabel->attachToComponent (inputDeviceDropDown, true);
  58073. addAndMakeVisible (inputLevelMeter
  58074. = new SimpleDeviceManagerInputLevelMeter (setup.manager));
  58075. }
  58076. addNamesToDeviceBox (*inputDeviceDropDown, true);
  58077. }
  58078. updateControlPanelButton();
  58079. showCorrectDeviceName (inputDeviceDropDown, true);
  58080. showCorrectDeviceName (outputDeviceDropDown, false);
  58081. if (currentDevice != 0)
  58082. {
  58083. if (setup.maxNumOutputChannels > 0
  58084. && setup.minNumOutputChannels < setup.manager->getCurrentAudioDevice()->getOutputChannelNames().size())
  58085. {
  58086. if (outputChanList == 0)
  58087. {
  58088. addAndMakeVisible (outputChanList
  58089. = new ChannelSelectorListBox (setup, ChannelSelectorListBox::audioOutputType,
  58090. TRANS ("(no audio output channels found)")));
  58091. outputChanLabel = new Label (String::empty, TRANS ("active output channels:"));
  58092. outputChanLabel->attachToComponent (outputChanList, true);
  58093. }
  58094. outputChanList->refresh();
  58095. }
  58096. else
  58097. {
  58098. deleteAndZero (outputChanLabel);
  58099. deleteAndZero (outputChanList);
  58100. }
  58101. if (setup.maxNumInputChannels > 0
  58102. && setup.minNumInputChannels < setup.manager->getCurrentAudioDevice()->getInputChannelNames().size())
  58103. {
  58104. if (inputChanList == 0)
  58105. {
  58106. addAndMakeVisible (inputChanList
  58107. = new ChannelSelectorListBox (setup, ChannelSelectorListBox::audioInputType,
  58108. TRANS ("(no audio input channels found)")));
  58109. inputChanLabel = new Label (String::empty, TRANS ("active input channels:"));
  58110. inputChanLabel->attachToComponent (inputChanList, true);
  58111. }
  58112. inputChanList->refresh();
  58113. }
  58114. else
  58115. {
  58116. deleteAndZero (inputChanLabel);
  58117. deleteAndZero (inputChanList);
  58118. }
  58119. // sample rate..
  58120. {
  58121. if (sampleRateDropDown == 0)
  58122. {
  58123. addAndMakeVisible (sampleRateDropDown = new ComboBox (String::empty));
  58124. sampleRateDropDown->addListener (this);
  58125. delete sampleRateLabel;
  58126. sampleRateLabel = new Label (String::empty, TRANS ("sample rate:"));
  58127. sampleRateLabel->attachToComponent (sampleRateDropDown, true);
  58128. }
  58129. else
  58130. {
  58131. sampleRateDropDown->clear();
  58132. sampleRateDropDown->removeListener (this);
  58133. }
  58134. const int numRates = currentDevice->getNumSampleRates();
  58135. for (int i = 0; i < numRates; ++i)
  58136. {
  58137. const int rate = roundToInt (currentDevice->getSampleRate (i));
  58138. sampleRateDropDown->addItem (String (rate) + " Hz", rate);
  58139. }
  58140. sampleRateDropDown->setSelectedId (roundToInt (currentDevice->getCurrentSampleRate()), true);
  58141. sampleRateDropDown->addListener (this);
  58142. }
  58143. // buffer size
  58144. {
  58145. if (bufferSizeDropDown == 0)
  58146. {
  58147. addAndMakeVisible (bufferSizeDropDown = new ComboBox (String::empty));
  58148. bufferSizeDropDown->addListener (this);
  58149. delete bufferSizeLabel;
  58150. bufferSizeLabel = new Label (String::empty, TRANS ("audio buffer size:"));
  58151. bufferSizeLabel->attachToComponent (bufferSizeDropDown, true);
  58152. }
  58153. else
  58154. {
  58155. bufferSizeDropDown->clear();
  58156. }
  58157. const int numBufferSizes = currentDevice->getNumBufferSizesAvailable();
  58158. double currentRate = currentDevice->getCurrentSampleRate();
  58159. if (currentRate == 0)
  58160. currentRate = 48000.0;
  58161. for (int i = 0; i < numBufferSizes; ++i)
  58162. {
  58163. const int bs = currentDevice->getBufferSizeSamples (i);
  58164. bufferSizeDropDown->addItem (String (bs)
  58165. + " samples ("
  58166. + String (bs * 1000.0 / currentRate, 1)
  58167. + " ms)",
  58168. bs);
  58169. }
  58170. bufferSizeDropDown->setSelectedId (currentDevice->getCurrentBufferSizeSamples(), true);
  58171. }
  58172. }
  58173. else
  58174. {
  58175. jassert (setup.manager->getCurrentAudioDevice() == 0); // not the correct device type!
  58176. deleteAndZero (sampleRateLabel);
  58177. deleteAndZero (bufferSizeLabel);
  58178. deleteAndZero (sampleRateDropDown);
  58179. deleteAndZero (bufferSizeDropDown);
  58180. if (outputDeviceDropDown != 0)
  58181. outputDeviceDropDown->setSelectedId (-1, true);
  58182. if (inputDeviceDropDown != 0)
  58183. inputDeviceDropDown->setSelectedId (-1, true);
  58184. }
  58185. resized();
  58186. setSize (getWidth(), getLowestY() + 4);
  58187. }
  58188. private:
  58189. AudioIODeviceType* const type;
  58190. const AudioIODeviceType::DeviceSetupDetails setup;
  58191. ComboBox* outputDeviceDropDown;
  58192. ComboBox* inputDeviceDropDown;
  58193. ComboBox* sampleRateDropDown;
  58194. ComboBox* bufferSizeDropDown;
  58195. Label* outputDeviceLabel;
  58196. Label* inputDeviceLabel;
  58197. Label* sampleRateLabel;
  58198. Label* bufferSizeLabel;
  58199. Label* inputChanLabel;
  58200. Label* outputChanLabel;
  58201. TextButton* testButton;
  58202. Component* inputLevelMeter;
  58203. TextButton* showUIButton;
  58204. TextButton* showAdvancedSettingsButton;
  58205. void showCorrectDeviceName (ComboBox* const box, const bool isInput)
  58206. {
  58207. if (box != 0)
  58208. {
  58209. AudioIODevice* const currentDevice = dynamic_cast <AudioIODevice*> (setup.manager->getCurrentAudioDevice());
  58210. const int index = type->getIndexOfDevice (currentDevice, isInput);
  58211. box->setSelectedId (index + 1, true);
  58212. if (testButton != 0 && ! isInput)
  58213. testButton->setEnabled (index >= 0);
  58214. }
  58215. }
  58216. void addNamesToDeviceBox (ComboBox& combo, bool isInputs)
  58217. {
  58218. const StringArray devs (type->getDeviceNames (isInputs));
  58219. combo.clear (true);
  58220. for (int i = 0; i < devs.size(); ++i)
  58221. combo.addItem (devs[i], i + 1);
  58222. combo.addItem (TRANS("<< none >>"), -1);
  58223. combo.setSelectedId (-1, true);
  58224. }
  58225. int getLowestY() const
  58226. {
  58227. int y = 0;
  58228. for (int i = getNumChildComponents(); --i >= 0;)
  58229. y = jmax (y, getChildComponent (i)->getBottom());
  58230. return y;
  58231. }
  58232. public:
  58233. class ChannelSelectorListBox : public ListBox,
  58234. public ListBoxModel
  58235. {
  58236. public:
  58237. enum BoxType
  58238. {
  58239. audioInputType,
  58240. audioOutputType
  58241. };
  58242. ChannelSelectorListBox (const AudioIODeviceType::DeviceSetupDetails& setup_,
  58243. const BoxType type_,
  58244. const String& noItemsMessage_)
  58245. : ListBox (String::empty, 0),
  58246. setup (setup_),
  58247. type (type_),
  58248. noItemsMessage (noItemsMessage_)
  58249. {
  58250. refresh();
  58251. setModel (this);
  58252. setOutlineThickness (1);
  58253. }
  58254. ~ChannelSelectorListBox()
  58255. {
  58256. }
  58257. void refresh()
  58258. {
  58259. items.clear();
  58260. AudioIODevice* const currentDevice = setup.manager->getCurrentAudioDevice();
  58261. if (currentDevice != 0)
  58262. {
  58263. if (type == audioInputType)
  58264. items = currentDevice->getInputChannelNames();
  58265. else if (type == audioOutputType)
  58266. items = currentDevice->getOutputChannelNames();
  58267. if (setup.useStereoPairs)
  58268. {
  58269. StringArray pairs;
  58270. for (int i = 0; i < items.size(); i += 2)
  58271. {
  58272. const String name (items[i]);
  58273. const String name2 (items[i + 1]);
  58274. String commonBit;
  58275. for (int j = 0; j < name.length(); ++j)
  58276. if (name.substring (0, j).equalsIgnoreCase (name2.substring (0, j)))
  58277. commonBit = name.substring (0, j);
  58278. // Make sure we only split the name at a space, because otherwise, things
  58279. // like "input 11" + "input 12" would become "input 11 + 2"
  58280. while (commonBit.isNotEmpty() && ! CharacterFunctions::isWhitespace (commonBit.getLastCharacter()))
  58281. commonBit = commonBit.dropLastCharacters (1);
  58282. pairs.add (name.trim() + " + " + name2.substring (commonBit.length()).trim());
  58283. }
  58284. items = pairs;
  58285. }
  58286. }
  58287. updateContent();
  58288. repaint();
  58289. }
  58290. int getNumRows()
  58291. {
  58292. return items.size();
  58293. }
  58294. void paintListBoxItem (int row,
  58295. Graphics& g,
  58296. int width, int height,
  58297. bool rowIsSelected)
  58298. {
  58299. if (((unsigned int) row) < (unsigned int) items.size())
  58300. {
  58301. if (rowIsSelected)
  58302. g.fillAll (findColour (TextEditor::highlightColourId)
  58303. .withMultipliedAlpha (0.3f));
  58304. const String item (items [row]);
  58305. bool enabled = false;
  58306. AudioDeviceManager::AudioDeviceSetup config;
  58307. setup.manager->getAudioDeviceSetup (config);
  58308. if (setup.useStereoPairs)
  58309. {
  58310. if (type == audioInputType)
  58311. enabled = config.inputChannels [row * 2] || config.inputChannels [row * 2 + 1];
  58312. else if (type == audioOutputType)
  58313. enabled = config.outputChannels [row * 2] || config.outputChannels [row * 2 + 1];
  58314. }
  58315. else
  58316. {
  58317. if (type == audioInputType)
  58318. enabled = config.inputChannels [row];
  58319. else if (type == audioOutputType)
  58320. enabled = config.outputChannels [row];
  58321. }
  58322. const int x = getTickX();
  58323. const float tickW = height * 0.75f;
  58324. getLookAndFeel().drawTickBox (g, *this, x - tickW, (height - tickW) / 2, tickW, tickW,
  58325. enabled, true, true, false);
  58326. g.setFont (height * 0.6f);
  58327. g.setColour (findColour (ListBox::textColourId, true).withMultipliedAlpha (enabled ? 1.0f : 0.6f));
  58328. g.drawText (item, x, 0, width - x - 2, height, Justification::centredLeft, true);
  58329. }
  58330. }
  58331. void listBoxItemClicked (int row, const MouseEvent& e)
  58332. {
  58333. selectRow (row);
  58334. if (e.x < getTickX())
  58335. flipEnablement (row);
  58336. }
  58337. void listBoxItemDoubleClicked (int row, const MouseEvent&)
  58338. {
  58339. flipEnablement (row);
  58340. }
  58341. void returnKeyPressed (int row)
  58342. {
  58343. flipEnablement (row);
  58344. }
  58345. void paint (Graphics& g)
  58346. {
  58347. ListBox::paint (g);
  58348. if (items.size() == 0)
  58349. {
  58350. g.setColour (Colours::grey);
  58351. g.setFont (13.0f);
  58352. g.drawText (noItemsMessage,
  58353. 0, 0, getWidth(), getHeight() / 2,
  58354. Justification::centred, true);
  58355. }
  58356. }
  58357. int getBestHeight (int maxHeight)
  58358. {
  58359. return getRowHeight() * jlimit (2, jmax (2, maxHeight / getRowHeight()),
  58360. getNumRows())
  58361. + getOutlineThickness() * 2;
  58362. }
  58363. juce_UseDebuggingNewOperator
  58364. private:
  58365. const AudioIODeviceType::DeviceSetupDetails setup;
  58366. const BoxType type;
  58367. const String noItemsMessage;
  58368. StringArray items;
  58369. void flipEnablement (const int row)
  58370. {
  58371. jassert (type == audioInputType || type == audioOutputType);
  58372. if (((unsigned int) row) < (unsigned int) items.size())
  58373. {
  58374. AudioDeviceManager::AudioDeviceSetup config;
  58375. setup.manager->getAudioDeviceSetup (config);
  58376. if (setup.useStereoPairs)
  58377. {
  58378. BigInteger bits;
  58379. BigInteger& original = (type == audioInputType ? config.inputChannels
  58380. : config.outputChannels);
  58381. int i;
  58382. for (i = 0; i < 256; i += 2)
  58383. bits.setBit (i / 2, original [i] || original [i + 1]);
  58384. if (type == audioInputType)
  58385. {
  58386. config.useDefaultInputChannels = false;
  58387. flipBit (bits, row, setup.minNumInputChannels / 2, setup.maxNumInputChannels / 2);
  58388. }
  58389. else
  58390. {
  58391. config.useDefaultOutputChannels = false;
  58392. flipBit (bits, row, setup.minNumOutputChannels / 2, setup.maxNumOutputChannels / 2);
  58393. }
  58394. for (i = 0; i < 256; ++i)
  58395. original.setBit (i, bits [i / 2]);
  58396. }
  58397. else
  58398. {
  58399. if (type == audioInputType)
  58400. {
  58401. config.useDefaultInputChannels = false;
  58402. flipBit (config.inputChannels, row, setup.minNumInputChannels, setup.maxNumInputChannels);
  58403. }
  58404. else
  58405. {
  58406. config.useDefaultOutputChannels = false;
  58407. flipBit (config.outputChannels, row, setup.minNumOutputChannels, setup.maxNumOutputChannels);
  58408. }
  58409. }
  58410. String error (setup.manager->setAudioDeviceSetup (config, true));
  58411. if (! error.isEmpty())
  58412. {
  58413. //xxx
  58414. }
  58415. }
  58416. }
  58417. static void flipBit (BigInteger& chans, int index, int minNumber, int maxNumber)
  58418. {
  58419. const int numActive = chans.countNumberOfSetBits();
  58420. if (chans [index])
  58421. {
  58422. if (numActive > minNumber)
  58423. chans.setBit (index, false);
  58424. }
  58425. else
  58426. {
  58427. if (numActive >= maxNumber)
  58428. {
  58429. const int firstActiveChan = chans.findNextSetBit();
  58430. chans.setBit (index > firstActiveChan
  58431. ? firstActiveChan : chans.getHighestBit(),
  58432. false);
  58433. }
  58434. chans.setBit (index, true);
  58435. }
  58436. }
  58437. int getTickX() const
  58438. {
  58439. return getRowHeight() + 5;
  58440. }
  58441. ChannelSelectorListBox (const ChannelSelectorListBox&);
  58442. ChannelSelectorListBox& operator= (const ChannelSelectorListBox&);
  58443. };
  58444. private:
  58445. ChannelSelectorListBox* inputChanList;
  58446. ChannelSelectorListBox* outputChanList;
  58447. AudioDeviceSettingsPanel (const AudioDeviceSettingsPanel&);
  58448. AudioDeviceSettingsPanel& operator= (const AudioDeviceSettingsPanel&);
  58449. };
  58450. AudioDeviceSelectorComponent::AudioDeviceSelectorComponent (AudioDeviceManager& deviceManager_,
  58451. const int minInputChannels_,
  58452. const int maxInputChannels_,
  58453. const int minOutputChannels_,
  58454. const int maxOutputChannels_,
  58455. const bool showMidiInputOptions,
  58456. const bool showMidiOutputSelector,
  58457. const bool showChannelsAsStereoPairs_,
  58458. const bool hideAdvancedOptionsWithButton_)
  58459. : deviceManager (deviceManager_),
  58460. deviceTypeDropDown (0),
  58461. deviceTypeDropDownLabel (0),
  58462. audioDeviceSettingsComp (0),
  58463. minOutputChannels (minOutputChannels_),
  58464. maxOutputChannels (maxOutputChannels_),
  58465. minInputChannels (minInputChannels_),
  58466. maxInputChannels (maxInputChannels_),
  58467. showChannelsAsStereoPairs (showChannelsAsStereoPairs_),
  58468. hideAdvancedOptionsWithButton (hideAdvancedOptionsWithButton_)
  58469. {
  58470. jassert (minOutputChannels >= 0 && minOutputChannels <= maxOutputChannels);
  58471. jassert (minInputChannels >= 0 && minInputChannels <= maxInputChannels);
  58472. if (deviceManager_.getAvailableDeviceTypes().size() > 1)
  58473. {
  58474. deviceTypeDropDown = new ComboBox (String::empty);
  58475. for (int i = 0; i < deviceManager_.getAvailableDeviceTypes().size(); ++i)
  58476. {
  58477. deviceTypeDropDown
  58478. ->addItem (deviceManager_.getAvailableDeviceTypes().getUnchecked(i)->getTypeName(),
  58479. i + 1);
  58480. }
  58481. addAndMakeVisible (deviceTypeDropDown);
  58482. deviceTypeDropDown->addListener (this);
  58483. deviceTypeDropDownLabel = new Label (String::empty, TRANS ("audio device type:"));
  58484. deviceTypeDropDownLabel->setJustificationType (Justification::centredRight);
  58485. deviceTypeDropDownLabel->attachToComponent (deviceTypeDropDown, true);
  58486. }
  58487. if (showMidiInputOptions)
  58488. {
  58489. addAndMakeVisible (midiInputsList
  58490. = new MidiInputSelectorComponentListBox (deviceManager,
  58491. TRANS("(no midi inputs available)"),
  58492. 0, 0));
  58493. midiInputsLabel = new Label (String::empty, TRANS ("active midi inputs:"));
  58494. midiInputsLabel->setJustificationType (Justification::topRight);
  58495. midiInputsLabel->attachToComponent (midiInputsList, true);
  58496. }
  58497. else
  58498. {
  58499. midiInputsList = 0;
  58500. midiInputsLabel = 0;
  58501. }
  58502. if (showMidiOutputSelector)
  58503. {
  58504. addAndMakeVisible (midiOutputSelector = new ComboBox (String::empty));
  58505. midiOutputSelector->addListener (this);
  58506. midiOutputLabel = new Label ("lm", TRANS("Midi Output:"));
  58507. midiOutputLabel->attachToComponent (midiOutputSelector, true);
  58508. }
  58509. else
  58510. {
  58511. midiOutputSelector = 0;
  58512. midiOutputLabel = 0;
  58513. }
  58514. deviceManager_.addChangeListener (this);
  58515. changeListenerCallback (0);
  58516. }
  58517. AudioDeviceSelectorComponent::~AudioDeviceSelectorComponent()
  58518. {
  58519. deviceManager.removeChangeListener (this);
  58520. deleteAllChildren();
  58521. }
  58522. void AudioDeviceSelectorComponent::resized()
  58523. {
  58524. const int lx = proportionOfWidth (0.35f);
  58525. const int w = proportionOfWidth (0.4f);
  58526. const int h = 24;
  58527. const int space = 6;
  58528. const int dh = h + space;
  58529. int y = 15;
  58530. if (deviceTypeDropDown != 0)
  58531. {
  58532. deviceTypeDropDown->setBounds (lx, y, proportionOfWidth (0.3f), h);
  58533. y += dh + space * 2;
  58534. }
  58535. if (audioDeviceSettingsComp != 0)
  58536. {
  58537. audioDeviceSettingsComp->setBounds (0, y, getWidth(), audioDeviceSettingsComp->getHeight());
  58538. y += audioDeviceSettingsComp->getHeight() + space;
  58539. }
  58540. if (midiInputsList != 0)
  58541. {
  58542. const int bh = midiInputsList->getBestHeight (jmin (h * 8, getHeight() - y - space - h));
  58543. midiInputsList->setBounds (lx, y, w, bh);
  58544. y += bh + space;
  58545. }
  58546. if (midiOutputSelector != 0)
  58547. midiOutputSelector->setBounds (lx, y, w, h);
  58548. }
  58549. void AudioDeviceSelectorComponent::childBoundsChanged (Component* child)
  58550. {
  58551. if (child == audioDeviceSettingsComp)
  58552. resized();
  58553. }
  58554. void AudioDeviceSelectorComponent::buttonClicked (Button*)
  58555. {
  58556. AudioIODevice* const device = deviceManager.getCurrentAudioDevice();
  58557. if (device != 0 && device->hasControlPanel())
  58558. {
  58559. if (device->showControlPanel())
  58560. deviceManager.restartLastAudioDevice();
  58561. getTopLevelComponent()->toFront (true);
  58562. }
  58563. }
  58564. void AudioDeviceSelectorComponent::comboBoxChanged (ComboBox* comboBoxThatHasChanged)
  58565. {
  58566. if (comboBoxThatHasChanged == deviceTypeDropDown)
  58567. {
  58568. AudioIODeviceType* const type = deviceManager.getAvailableDeviceTypes() [deviceTypeDropDown->getSelectedId() - 1];
  58569. if (type != 0)
  58570. {
  58571. deleteAndZero (audioDeviceSettingsComp);
  58572. deviceManager.setCurrentAudioDeviceType (type->getTypeName(), true);
  58573. changeListenerCallback (0); // needed in case the type hasn't actally changed
  58574. }
  58575. }
  58576. else if (comboBoxThatHasChanged == midiOutputSelector)
  58577. {
  58578. deviceManager.setDefaultMidiOutput (midiOutputSelector->getText());
  58579. }
  58580. }
  58581. void AudioDeviceSelectorComponent::changeListenerCallback (void*)
  58582. {
  58583. if (deviceTypeDropDown != 0)
  58584. {
  58585. deviceTypeDropDown->setText (deviceManager.getCurrentAudioDeviceType(), false);
  58586. }
  58587. if (audioDeviceSettingsComp == 0
  58588. || audioDeviceSettingsCompType != deviceManager.getCurrentAudioDeviceType())
  58589. {
  58590. audioDeviceSettingsCompType = deviceManager.getCurrentAudioDeviceType();
  58591. deleteAndZero (audioDeviceSettingsComp);
  58592. AudioIODeviceType* const type
  58593. = deviceManager.getAvailableDeviceTypes() [deviceTypeDropDown == 0
  58594. ? 0 : deviceTypeDropDown->getSelectedId() - 1];
  58595. if (type != 0)
  58596. {
  58597. AudioIODeviceType::DeviceSetupDetails details;
  58598. details.manager = &deviceManager;
  58599. details.minNumInputChannels = minInputChannels;
  58600. details.maxNumInputChannels = maxInputChannels;
  58601. details.minNumOutputChannels = minOutputChannels;
  58602. details.maxNumOutputChannels = maxOutputChannels;
  58603. details.useStereoPairs = showChannelsAsStereoPairs;
  58604. audioDeviceSettingsComp = new AudioDeviceSettingsPanel (type, details, hideAdvancedOptionsWithButton);
  58605. if (audioDeviceSettingsComp != 0)
  58606. {
  58607. addAndMakeVisible (audioDeviceSettingsComp);
  58608. audioDeviceSettingsComp->resized();
  58609. }
  58610. }
  58611. }
  58612. if (midiInputsList != 0)
  58613. {
  58614. midiInputsList->updateContent();
  58615. midiInputsList->repaint();
  58616. }
  58617. if (midiOutputSelector != 0)
  58618. {
  58619. midiOutputSelector->clear();
  58620. const StringArray midiOuts (MidiOutput::getDevices());
  58621. midiOutputSelector->addItem (TRANS("<< none >>"), -1);
  58622. midiOutputSelector->addSeparator();
  58623. for (int i = 0; i < midiOuts.size(); ++i)
  58624. midiOutputSelector->addItem (midiOuts[i], i + 1);
  58625. int current = -1;
  58626. if (deviceManager.getDefaultMidiOutput() != 0)
  58627. current = 1 + midiOuts.indexOf (deviceManager.getDefaultMidiOutputName());
  58628. midiOutputSelector->setSelectedId (current, true);
  58629. }
  58630. resized();
  58631. }
  58632. END_JUCE_NAMESPACE
  58633. /*** End of inlined file: juce_AudioDeviceSelectorComponent.cpp ***/
  58634. /*** Start of inlined file: juce_BubbleComponent.cpp ***/
  58635. BEGIN_JUCE_NAMESPACE
  58636. BubbleComponent::BubbleComponent()
  58637. : side (0),
  58638. allowablePlacements (above | below | left | right),
  58639. arrowTipX (0.0f),
  58640. arrowTipY (0.0f)
  58641. {
  58642. setInterceptsMouseClicks (false, false);
  58643. shadow.setShadowProperties (5.0f, 0.35f, 0, 0);
  58644. setComponentEffect (&shadow);
  58645. }
  58646. BubbleComponent::~BubbleComponent()
  58647. {
  58648. }
  58649. void BubbleComponent::paint (Graphics& g)
  58650. {
  58651. int x = content.getX();
  58652. int y = content.getY();
  58653. int w = content.getWidth();
  58654. int h = content.getHeight();
  58655. int cw, ch;
  58656. getContentSize (cw, ch);
  58657. if (side == 3)
  58658. x += w - cw;
  58659. else if (side != 1)
  58660. x += (w - cw) / 2;
  58661. w = cw;
  58662. if (side == 2)
  58663. y += h - ch;
  58664. else if (side != 0)
  58665. y += (h - ch) / 2;
  58666. h = ch;
  58667. getLookAndFeel().drawBubble (g, arrowTipX, arrowTipY,
  58668. (float) x, (float) y,
  58669. (float) w, (float) h);
  58670. const int cx = x + (w - cw) / 2;
  58671. const int cy = y + (h - ch) / 2;
  58672. const int indent = 3;
  58673. g.setOrigin (cx + indent, cy + indent);
  58674. g.reduceClipRegion (0, 0, cw - indent * 2, ch - indent * 2);
  58675. paintContent (g, cw - indent * 2, ch - indent * 2);
  58676. }
  58677. void BubbleComponent::setAllowedPlacement (const int newPlacement)
  58678. {
  58679. allowablePlacements = newPlacement;
  58680. }
  58681. void BubbleComponent::setPosition (Component* componentToPointTo)
  58682. {
  58683. jassert (componentToPointTo->isValidComponent());
  58684. Point<int> pos;
  58685. if (getParentComponent() != 0)
  58686. pos = componentToPointTo->relativePositionToOtherComponent (getParentComponent(), pos);
  58687. else
  58688. pos = componentToPointTo->relativePositionToGlobal (pos);
  58689. setPosition (Rectangle<int> (pos.getX(), pos.getY(), componentToPointTo->getWidth(), componentToPointTo->getHeight()));
  58690. }
  58691. void BubbleComponent::setPosition (const int arrowTipX_,
  58692. const int arrowTipY_)
  58693. {
  58694. setPosition (Rectangle<int> (arrowTipX_, arrowTipY_, 1, 1));
  58695. }
  58696. void BubbleComponent::setPosition (const Rectangle<int>& rectangleToPointTo)
  58697. {
  58698. Rectangle<int> availableSpace;
  58699. if (getParentComponent() != 0)
  58700. {
  58701. availableSpace.setSize (getParentComponent()->getWidth(),
  58702. getParentComponent()->getHeight());
  58703. }
  58704. else
  58705. {
  58706. availableSpace = getParentMonitorArea();
  58707. }
  58708. int x = 0;
  58709. int y = 0;
  58710. int w = 150;
  58711. int h = 30;
  58712. getContentSize (w, h);
  58713. w += 30;
  58714. h += 30;
  58715. const float edgeIndent = 2.0f;
  58716. const int arrowLength = jmin (10, h / 3, w / 3);
  58717. int spaceAbove = ((allowablePlacements & above) != 0) ? jmax (0, rectangleToPointTo.getY() - availableSpace.getY()) : -1;
  58718. int spaceBelow = ((allowablePlacements & below) != 0) ? jmax (0, availableSpace.getBottom() - rectangleToPointTo.getBottom()) : -1;
  58719. int spaceLeft = ((allowablePlacements & left) != 0) ? jmax (0, rectangleToPointTo.getX() - availableSpace.getX()) : -1;
  58720. int spaceRight = ((allowablePlacements & right) != 0) ? jmax (0, availableSpace.getRight() - rectangleToPointTo.getRight()) : -1;
  58721. // look at whether the component is elongated, and if so, try to position next to its longer dimension.
  58722. if (rectangleToPointTo.getWidth() > rectangleToPointTo.getHeight() * 2
  58723. && (spaceAbove > h + 20 || spaceBelow > h + 20))
  58724. {
  58725. spaceLeft = spaceRight = 0;
  58726. }
  58727. else if (rectangleToPointTo.getWidth() < rectangleToPointTo.getHeight() / 2
  58728. && (spaceLeft > w + 20 || spaceRight > w + 20))
  58729. {
  58730. spaceAbove = spaceBelow = 0;
  58731. }
  58732. if (jmax (spaceAbove, spaceBelow) >= jmax (spaceLeft, spaceRight))
  58733. {
  58734. x = rectangleToPointTo.getX() + (rectangleToPointTo.getWidth() - w) / 2;
  58735. arrowTipX = w * 0.5f;
  58736. content.setSize (w, h - arrowLength);
  58737. if (spaceAbove >= spaceBelow)
  58738. {
  58739. // above
  58740. y = rectangleToPointTo.getY() - h;
  58741. content.setPosition (0, 0);
  58742. arrowTipY = h - edgeIndent;
  58743. side = 2;
  58744. }
  58745. else
  58746. {
  58747. // below
  58748. y = rectangleToPointTo.getBottom();
  58749. content.setPosition (0, arrowLength);
  58750. arrowTipY = edgeIndent;
  58751. side = 0;
  58752. }
  58753. }
  58754. else
  58755. {
  58756. y = rectangleToPointTo.getY() + (rectangleToPointTo.getHeight() - h) / 2;
  58757. arrowTipY = h * 0.5f;
  58758. content.setSize (w - arrowLength, h);
  58759. if (spaceLeft > spaceRight)
  58760. {
  58761. // on the left
  58762. x = rectangleToPointTo.getX() - w;
  58763. content.setPosition (0, 0);
  58764. arrowTipX = w - edgeIndent;
  58765. side = 3;
  58766. }
  58767. else
  58768. {
  58769. // on the right
  58770. x = rectangleToPointTo.getRight();
  58771. content.setPosition (arrowLength, 0);
  58772. arrowTipX = edgeIndent;
  58773. side = 1;
  58774. }
  58775. }
  58776. setBounds (x, y, w, h);
  58777. }
  58778. END_JUCE_NAMESPACE
  58779. /*** End of inlined file: juce_BubbleComponent.cpp ***/
  58780. /*** Start of inlined file: juce_BubbleMessageComponent.cpp ***/
  58781. BEGIN_JUCE_NAMESPACE
  58782. BubbleMessageComponent::BubbleMessageComponent (int fadeOutLengthMs)
  58783. : fadeOutLength (fadeOutLengthMs),
  58784. deleteAfterUse (false)
  58785. {
  58786. }
  58787. BubbleMessageComponent::~BubbleMessageComponent()
  58788. {
  58789. fadeOutComponent (fadeOutLength);
  58790. }
  58791. void BubbleMessageComponent::showAt (int x, int y,
  58792. const String& text,
  58793. const int numMillisecondsBeforeRemoving,
  58794. const bool removeWhenMouseClicked,
  58795. const bool deleteSelfAfterUse)
  58796. {
  58797. textLayout.clear();
  58798. textLayout.setText (text, Font (14.0f));
  58799. textLayout.layout (256, Justification::centredLeft, true);
  58800. setPosition (x, y);
  58801. init (numMillisecondsBeforeRemoving, removeWhenMouseClicked, deleteSelfAfterUse);
  58802. }
  58803. void BubbleMessageComponent::showAt (Component* const component,
  58804. const String& text,
  58805. const int numMillisecondsBeforeRemoving,
  58806. const bool removeWhenMouseClicked,
  58807. const bool deleteSelfAfterUse)
  58808. {
  58809. textLayout.clear();
  58810. textLayout.setText (text, Font (14.0f));
  58811. textLayout.layout (256, Justification::centredLeft, true);
  58812. setPosition (component);
  58813. init (numMillisecondsBeforeRemoving, removeWhenMouseClicked, deleteSelfAfterUse);
  58814. }
  58815. void BubbleMessageComponent::init (const int numMillisecondsBeforeRemoving,
  58816. const bool removeWhenMouseClicked,
  58817. const bool deleteSelfAfterUse)
  58818. {
  58819. setVisible (true);
  58820. deleteAfterUse = deleteSelfAfterUse;
  58821. if (numMillisecondsBeforeRemoving > 0)
  58822. expiryTime = Time::getMillisecondCounter() + numMillisecondsBeforeRemoving;
  58823. else
  58824. expiryTime = 0;
  58825. startTimer (77);
  58826. mouseClickCounter = Desktop::getInstance().getMouseButtonClickCounter();
  58827. if (! (removeWhenMouseClicked && isShowing()))
  58828. mouseClickCounter += 0xfffff;
  58829. repaint();
  58830. }
  58831. void BubbleMessageComponent::getContentSize (int& w, int& h)
  58832. {
  58833. w = textLayout.getWidth() + 16;
  58834. h = textLayout.getHeight() + 16;
  58835. }
  58836. void BubbleMessageComponent::paintContent (Graphics& g, int w, int h)
  58837. {
  58838. g.setColour (findColour (TooltipWindow::textColourId));
  58839. textLayout.drawWithin (g, 0, 0, w, h, Justification::centred);
  58840. }
  58841. void BubbleMessageComponent::timerCallback()
  58842. {
  58843. if (Desktop::getInstance().getMouseButtonClickCounter() > mouseClickCounter)
  58844. {
  58845. stopTimer();
  58846. setVisible (false);
  58847. if (deleteAfterUse)
  58848. delete this;
  58849. }
  58850. else if (expiryTime != 0 && Time::getMillisecondCounter() > expiryTime)
  58851. {
  58852. stopTimer();
  58853. fadeOutComponent (fadeOutLength);
  58854. if (deleteAfterUse)
  58855. delete this;
  58856. }
  58857. }
  58858. END_JUCE_NAMESPACE
  58859. /*** End of inlined file: juce_BubbleMessageComponent.cpp ***/
  58860. /*** Start of inlined file: juce_ColourSelector.cpp ***/
  58861. BEGIN_JUCE_NAMESPACE
  58862. static const int swatchesPerRow = 8;
  58863. static const int swatchHeight = 22;
  58864. class ColourComponentSlider : public Slider
  58865. {
  58866. public:
  58867. ColourComponentSlider (const String& name)
  58868. : Slider (name)
  58869. {
  58870. setRange (0.0, 255.0, 1.0);
  58871. }
  58872. ~ColourComponentSlider()
  58873. {
  58874. }
  58875. const String getTextFromValue (double value)
  58876. {
  58877. return String::toHexString ((int) value).toUpperCase().paddedLeft ('0', 2);
  58878. }
  58879. double getValueFromText (const String& text)
  58880. {
  58881. return (double) text.getHexValue32();
  58882. }
  58883. private:
  58884. ColourComponentSlider (const ColourComponentSlider&);
  58885. ColourComponentSlider& operator= (const ColourComponentSlider&);
  58886. };
  58887. class ColourSpaceMarker : public Component
  58888. {
  58889. public:
  58890. ColourSpaceMarker()
  58891. {
  58892. setInterceptsMouseClicks (false, false);
  58893. }
  58894. ~ColourSpaceMarker()
  58895. {
  58896. }
  58897. void paint (Graphics& g)
  58898. {
  58899. g.setColour (Colour::greyLevel (0.1f));
  58900. g.drawEllipse (1.0f, 1.0f, getWidth() - 2.0f, getHeight() - 2.0f, 1.0f);
  58901. g.setColour (Colour::greyLevel (0.9f));
  58902. g.drawEllipse (2.0f, 2.0f, getWidth() - 4.0f, getHeight() - 4.0f, 1.0f);
  58903. }
  58904. private:
  58905. ColourSpaceMarker (const ColourSpaceMarker&);
  58906. ColourSpaceMarker& operator= (const ColourSpaceMarker&);
  58907. };
  58908. class ColourSelector::ColourSpaceView : public Component
  58909. {
  58910. public:
  58911. ColourSpaceView (ColourSelector* owner_,
  58912. float& h_, float& s_, float& v_,
  58913. const int edgeSize)
  58914. : owner (owner_),
  58915. h (h_), s (s_), v (v_),
  58916. lastHue (0.0f),
  58917. edge (edgeSize)
  58918. {
  58919. addAndMakeVisible (marker = new ColourSpaceMarker());
  58920. setMouseCursor (MouseCursor::CrosshairCursor);
  58921. }
  58922. ~ColourSpaceView()
  58923. {
  58924. deleteAllChildren();
  58925. }
  58926. void paint (Graphics& g)
  58927. {
  58928. if (colours == 0)
  58929. {
  58930. const int width = getWidth() / 2;
  58931. const int height = getHeight() / 2;
  58932. colours = new Image (Image::RGB, width, height, false);
  58933. Image::BitmapData pixels (*colours, 0, 0, width, height, true);
  58934. for (int y = 0; y < height; ++y)
  58935. {
  58936. const float v = 1.0f - y / (float) height;
  58937. for (int x = 0; x < width; ++x)
  58938. {
  58939. const float s = x / (float) width;
  58940. const Colour col (h, s, v, 1.0f);
  58941. PixelRGB* const pix = (PixelRGB*) pixels.getPixelPointer (x, y);
  58942. pix->set (col.getPixelARGB());
  58943. }
  58944. }
  58945. }
  58946. g.setOpacity (1.0f);
  58947. g.drawImage (colours, edge, edge, getWidth() - edge * 2, getHeight() - edge * 2,
  58948. 0, 0, colours->getWidth(), colours->getHeight());
  58949. }
  58950. void mouseDown (const MouseEvent& e)
  58951. {
  58952. mouseDrag (e);
  58953. }
  58954. void mouseDrag (const MouseEvent& e)
  58955. {
  58956. const float s = (e.x - edge) / (float) (getWidth() - edge * 2);
  58957. const float v = 1.0f - (e.y - edge) / (float) (getHeight() - edge * 2);
  58958. owner->setSV (s, v);
  58959. }
  58960. void updateIfNeeded()
  58961. {
  58962. if (lastHue != h)
  58963. {
  58964. lastHue = h;
  58965. colours = 0;
  58966. repaint();
  58967. }
  58968. updateMarker();
  58969. }
  58970. void resized()
  58971. {
  58972. colours = 0;
  58973. updateMarker();
  58974. }
  58975. private:
  58976. ColourSelector* const owner;
  58977. float& h;
  58978. float& s;
  58979. float& v;
  58980. float lastHue;
  58981. ColourSpaceMarker* marker;
  58982. const int edge;
  58983. ScopedPointer <Image> colours;
  58984. void updateMarker() const
  58985. {
  58986. marker->setBounds (roundToInt ((getWidth() - edge * 2) * s),
  58987. roundToInt ((getHeight() - edge * 2) * (1.0f - v)),
  58988. edge * 2, edge * 2);
  58989. }
  58990. ColourSpaceView (const ColourSpaceView&);
  58991. ColourSpaceView& operator= (const ColourSpaceView&);
  58992. };
  58993. class HueSelectorMarker : public Component
  58994. {
  58995. public:
  58996. HueSelectorMarker()
  58997. {
  58998. setInterceptsMouseClicks (false, false);
  58999. }
  59000. ~HueSelectorMarker()
  59001. {
  59002. }
  59003. void paint (Graphics& g)
  59004. {
  59005. Path p;
  59006. p.addTriangle (1.0f, 1.0f,
  59007. getWidth() * 0.3f, getHeight() * 0.5f,
  59008. 1.0f, getHeight() - 1.0f);
  59009. p.addTriangle (getWidth() - 1.0f, 1.0f,
  59010. getWidth() * 0.7f, getHeight() * 0.5f,
  59011. getWidth() - 1.0f, getHeight() - 1.0f);
  59012. g.setColour (Colours::white.withAlpha (0.75f));
  59013. g.fillPath (p);
  59014. g.setColour (Colours::black.withAlpha (0.75f));
  59015. g.strokePath (p, PathStrokeType (1.2f));
  59016. }
  59017. private:
  59018. HueSelectorMarker (const HueSelectorMarker&);
  59019. HueSelectorMarker& operator= (const HueSelectorMarker&);
  59020. };
  59021. class ColourSelector::HueSelectorComp : public Component
  59022. {
  59023. public:
  59024. HueSelectorComp (ColourSelector* owner_,
  59025. float& h_, float& s_, float& v_,
  59026. const int edgeSize)
  59027. : owner (owner_),
  59028. h (h_), s (s_), v (v_),
  59029. lastHue (0.0f),
  59030. edge (edgeSize)
  59031. {
  59032. addAndMakeVisible (marker = new HueSelectorMarker());
  59033. }
  59034. ~HueSelectorComp()
  59035. {
  59036. deleteAllChildren();
  59037. }
  59038. void paint (Graphics& g)
  59039. {
  59040. const float yScale = 1.0f / (getHeight() - edge * 2);
  59041. const Rectangle<int> clip (g.getClipBounds());
  59042. for (int y = jmin (clip.getBottom(), getHeight() - edge); --y >= jmax (edge, clip.getY());)
  59043. {
  59044. g.setColour (Colour ((y - edge) * yScale, 1.0f, 1.0f, 1.0f));
  59045. g.fillRect (edge, y, getWidth() - edge * 2, 1);
  59046. }
  59047. }
  59048. void resized()
  59049. {
  59050. marker->setBounds (0, roundToInt ((getHeight() - edge * 2) * h),
  59051. getWidth(), edge * 2);
  59052. }
  59053. void mouseDown (const MouseEvent& e)
  59054. {
  59055. mouseDrag (e);
  59056. }
  59057. void mouseDrag (const MouseEvent& e)
  59058. {
  59059. const float hue = (e.y - edge) / (float) (getHeight() - edge * 2);
  59060. owner->setHue (hue);
  59061. }
  59062. void updateIfNeeded()
  59063. {
  59064. resized();
  59065. }
  59066. private:
  59067. ColourSelector* const owner;
  59068. float& h;
  59069. float& s;
  59070. float& v;
  59071. float lastHue;
  59072. HueSelectorMarker* marker;
  59073. const int edge;
  59074. HueSelectorComp (const HueSelectorComp&);
  59075. HueSelectorComp& operator= (const HueSelectorComp&);
  59076. };
  59077. class ColourSelector::SwatchComponent : public Component
  59078. {
  59079. public:
  59080. SwatchComponent (ColourSelector* owner_, int index_)
  59081. : owner (owner_),
  59082. index (index_)
  59083. {
  59084. }
  59085. ~SwatchComponent()
  59086. {
  59087. }
  59088. void paint (Graphics& g)
  59089. {
  59090. const Colour colour (owner->getSwatchColour (index));
  59091. g.fillCheckerBoard (0, 0, getWidth(), getHeight(),
  59092. 6, 6,
  59093. Colour (0xffdddddd).overlaidWith (colour),
  59094. Colour (0xffffffff).overlaidWith (colour));
  59095. }
  59096. void mouseDown (const MouseEvent&)
  59097. {
  59098. PopupMenu m;
  59099. m.addItem (1, TRANS("Use this swatch as the current colour"));
  59100. m.addSeparator();
  59101. m.addItem (2, TRANS("Set this swatch to the current colour"));
  59102. const int r = m.showAt (this);
  59103. if (r == 1)
  59104. {
  59105. owner->setCurrentColour (owner->getSwatchColour (index));
  59106. }
  59107. else if (r == 2)
  59108. {
  59109. if (owner->getSwatchColour (index) != owner->getCurrentColour())
  59110. {
  59111. owner->setSwatchColour (index, owner->getCurrentColour());
  59112. repaint();
  59113. }
  59114. }
  59115. }
  59116. private:
  59117. ColourSelector* const owner;
  59118. const int index;
  59119. SwatchComponent (const SwatchComponent&);
  59120. SwatchComponent& operator= (const SwatchComponent&);
  59121. };
  59122. ColourSelector::ColourSelector (const int flags_,
  59123. const int edgeGap_,
  59124. const int gapAroundColourSpaceComponent)
  59125. : colour (Colours::white),
  59126. flags (flags_),
  59127. topSpace (0),
  59128. edgeGap (edgeGap_)
  59129. {
  59130. // not much point having a selector with no components in it!
  59131. jassert ((flags_ & (showColourAtTop | showSliders | showColourspace)) != 0);
  59132. updateHSV();
  59133. if ((flags & showSliders) != 0)
  59134. {
  59135. addAndMakeVisible (sliders[0] = new ColourComponentSlider (TRANS ("red")));
  59136. addAndMakeVisible (sliders[1] = new ColourComponentSlider (TRANS ("green")));
  59137. addAndMakeVisible (sliders[2] = new ColourComponentSlider (TRANS ("blue")));
  59138. addChildComponent (sliders[3] = new ColourComponentSlider (TRANS ("alpha")));
  59139. sliders[3]->setVisible ((flags & showAlphaChannel) != 0);
  59140. for (int i = 4; --i >= 0;)
  59141. sliders[i]->addListener (this);
  59142. }
  59143. else
  59144. {
  59145. zeromem (sliders, sizeof (sliders));
  59146. }
  59147. if ((flags & showColourspace) != 0)
  59148. {
  59149. addAndMakeVisible (colourSpace = new ColourSpaceView (this, h, s, v, gapAroundColourSpaceComponent));
  59150. addAndMakeVisible (hueSelector = new HueSelectorComp (this, h, s, v, gapAroundColourSpaceComponent));
  59151. }
  59152. else
  59153. {
  59154. colourSpace = 0;
  59155. hueSelector = 0;
  59156. }
  59157. update();
  59158. }
  59159. ColourSelector::~ColourSelector()
  59160. {
  59161. dispatchPendingMessages();
  59162. swatchComponents.clear();
  59163. deleteAllChildren();
  59164. }
  59165. const Colour ColourSelector::getCurrentColour() const
  59166. {
  59167. return ((flags & showAlphaChannel) != 0) ? colour
  59168. : colour.withAlpha ((uint8) 0xff);
  59169. }
  59170. void ColourSelector::setCurrentColour (const Colour& c)
  59171. {
  59172. if (c != colour)
  59173. {
  59174. colour = ((flags & showAlphaChannel) != 0) ? c : c.withAlpha ((uint8) 0xff);
  59175. updateHSV();
  59176. update();
  59177. }
  59178. }
  59179. void ColourSelector::setHue (float newH)
  59180. {
  59181. newH = jlimit (0.0f, 1.0f, newH);
  59182. if (h != newH)
  59183. {
  59184. h = newH;
  59185. colour = Colour (h, s, v, colour.getFloatAlpha());
  59186. update();
  59187. }
  59188. }
  59189. void ColourSelector::setSV (float newS, float newV)
  59190. {
  59191. newS = jlimit (0.0f, 1.0f, newS);
  59192. newV = jlimit (0.0f, 1.0f, newV);
  59193. if (s != newS || v != newV)
  59194. {
  59195. s = newS;
  59196. v = newV;
  59197. colour = Colour (h, s, v, colour.getFloatAlpha());
  59198. update();
  59199. }
  59200. }
  59201. void ColourSelector::updateHSV()
  59202. {
  59203. colour.getHSB (h, s, v);
  59204. }
  59205. void ColourSelector::update()
  59206. {
  59207. if (sliders[0] != 0)
  59208. {
  59209. sliders[0]->setValue ((int) colour.getRed());
  59210. sliders[1]->setValue ((int) colour.getGreen());
  59211. sliders[2]->setValue ((int) colour.getBlue());
  59212. sliders[3]->setValue ((int) colour.getAlpha());
  59213. }
  59214. if (colourSpace != 0)
  59215. {
  59216. colourSpace->updateIfNeeded();
  59217. hueSelector->updateIfNeeded();
  59218. }
  59219. if ((flags & showColourAtTop) != 0)
  59220. repaint (0, edgeGap, getWidth(), topSpace - edgeGap);
  59221. sendChangeMessage (this);
  59222. }
  59223. void ColourSelector::paint (Graphics& g)
  59224. {
  59225. g.fillAll (findColour (backgroundColourId));
  59226. if ((flags & showColourAtTop) != 0)
  59227. {
  59228. const Colour colour (getCurrentColour());
  59229. g.fillCheckerBoard (edgeGap, edgeGap, getWidth() - edgeGap - edgeGap, topSpace - edgeGap - edgeGap,
  59230. 10, 10,
  59231. Colour (0xffdddddd).overlaidWith (colour),
  59232. Colour (0xffffffff).overlaidWith (colour));
  59233. g.setColour (Colours::white.overlaidWith (colour).contrasting());
  59234. g.setFont (14.0f, true);
  59235. g.drawText (colour.toDisplayString ((flags & showAlphaChannel) != 0),
  59236. 0, edgeGap, getWidth(), topSpace - edgeGap * 2,
  59237. Justification::centred, false);
  59238. }
  59239. if ((flags & showSliders) != 0)
  59240. {
  59241. g.setColour (findColour (labelTextColourId));
  59242. g.setFont (11.0f);
  59243. for (int i = 4; --i >= 0;)
  59244. {
  59245. if (sliders[i]->isVisible())
  59246. g.drawText (sliders[i]->getName() + ":",
  59247. 0, sliders[i]->getY(),
  59248. sliders[i]->getX() - 8, sliders[i]->getHeight(),
  59249. Justification::centredRight, false);
  59250. }
  59251. }
  59252. }
  59253. void ColourSelector::resized()
  59254. {
  59255. const int numSliders = ((flags & showAlphaChannel) != 0) ? 4 : 3;
  59256. const int numSwatches = getNumSwatches();
  59257. const int swatchSpace = numSwatches > 0 ? edgeGap + swatchHeight * ((numSwatches + 7) / swatchesPerRow) : 0;
  59258. const int sliderSpace = ((flags & showSliders) != 0) ? jmin (22 * numSliders + edgeGap, proportionOfHeight (0.3f)) : 0;
  59259. topSpace = ((flags & showColourAtTop) != 0) ? jmin (30 + edgeGap * 2, proportionOfHeight (0.2f)) : edgeGap;
  59260. int y = topSpace;
  59261. if ((flags & showColourspace) != 0)
  59262. {
  59263. const int hueWidth = jmin (50, proportionOfWidth (0.15f));
  59264. colourSpace->setBounds (edgeGap, y,
  59265. getWidth() - hueWidth - edgeGap - 4,
  59266. getHeight() - topSpace - sliderSpace - swatchSpace - edgeGap);
  59267. hueSelector->setBounds (colourSpace->getRight() + 4, y,
  59268. getWidth() - edgeGap - (colourSpace->getRight() + 4),
  59269. colourSpace->getHeight());
  59270. y = getHeight() - sliderSpace - swatchSpace - edgeGap;
  59271. }
  59272. if ((flags & showSliders) != 0)
  59273. {
  59274. const int sliderHeight = jmax (4, sliderSpace / numSliders);
  59275. for (int i = 0; i < numSliders; ++i)
  59276. {
  59277. sliders[i]->setBounds (proportionOfWidth (0.2f), y,
  59278. proportionOfWidth (0.72f), sliderHeight - 2);
  59279. y += sliderHeight;
  59280. }
  59281. }
  59282. if (numSwatches > 0)
  59283. {
  59284. const int startX = 8;
  59285. const int xGap = 4;
  59286. const int yGap = 4;
  59287. const int swatchWidth = (getWidth() - startX * 2) / swatchesPerRow;
  59288. y += edgeGap;
  59289. if (swatchComponents.size() != numSwatches)
  59290. {
  59291. swatchComponents.clear();
  59292. for (int i = 0; i < numSwatches; ++i)
  59293. {
  59294. SwatchComponent* const sc = new SwatchComponent (this, i);
  59295. swatchComponents.add (sc);
  59296. addAndMakeVisible (sc);
  59297. }
  59298. }
  59299. int x = startX;
  59300. for (int i = 0; i < swatchComponents.size(); ++i)
  59301. {
  59302. SwatchComponent* const sc = swatchComponents.getUnchecked(i);
  59303. sc->setBounds (x + xGap / 2,
  59304. y + yGap / 2,
  59305. swatchWidth - xGap,
  59306. swatchHeight - yGap);
  59307. if (((i + 1) % swatchesPerRow) == 0)
  59308. {
  59309. x = startX;
  59310. y += swatchHeight;
  59311. }
  59312. else
  59313. {
  59314. x += swatchWidth;
  59315. }
  59316. }
  59317. }
  59318. }
  59319. void ColourSelector::sliderValueChanged (Slider*)
  59320. {
  59321. if (sliders[0] != 0)
  59322. setCurrentColour (Colour ((uint8) sliders[0]->getValue(),
  59323. (uint8) sliders[1]->getValue(),
  59324. (uint8) sliders[2]->getValue(),
  59325. (uint8) sliders[3]->getValue()));
  59326. }
  59327. int ColourSelector::getNumSwatches() const
  59328. {
  59329. return 0;
  59330. }
  59331. const Colour ColourSelector::getSwatchColour (const int) const
  59332. {
  59333. jassertfalse // if you've overridden getNumSwatches(), you also need to implement this method
  59334. return Colours::black;
  59335. }
  59336. void ColourSelector::setSwatchColour (const int, const Colour&) const
  59337. {
  59338. jassertfalse // if you've overridden getNumSwatches(), you also need to implement this method
  59339. }
  59340. END_JUCE_NAMESPACE
  59341. /*** End of inlined file: juce_ColourSelector.cpp ***/
  59342. /*** Start of inlined file: juce_DropShadower.cpp ***/
  59343. BEGIN_JUCE_NAMESPACE
  59344. class ShadowWindow : public Component
  59345. {
  59346. Component* owner;
  59347. Image** shadowImageSections;
  59348. const int type; // 0 = left, 1 = right, 2 = top, 3 = bottom. left + right are full-height
  59349. public:
  59350. ShadowWindow (Component* const owner_,
  59351. const int type_,
  59352. Image** const shadowImageSections_)
  59353. : owner (owner_),
  59354. shadowImageSections (shadowImageSections_),
  59355. type (type_)
  59356. {
  59357. setInterceptsMouseClicks (false, false);
  59358. if (owner_->isOnDesktop())
  59359. {
  59360. setSize (1, 1); // to keep the OS happy by not having zero-size windows
  59361. addToDesktop (ComponentPeer::windowIgnoresMouseClicks
  59362. | ComponentPeer::windowIsTemporary
  59363. | ComponentPeer::windowIgnoresKeyPresses);
  59364. }
  59365. else if (owner_->getParentComponent() != 0)
  59366. {
  59367. owner_->getParentComponent()->addChildComponent (this);
  59368. }
  59369. }
  59370. ~ShadowWindow()
  59371. {
  59372. }
  59373. void paint (Graphics& g)
  59374. {
  59375. Image* const topLeft = shadowImageSections [type * 3];
  59376. Image* const bottomRight = shadowImageSections [type * 3 + 1];
  59377. Image* const filler = shadowImageSections [type * 3 + 2];
  59378. g.setOpacity (1.0f);
  59379. if (type < 2)
  59380. {
  59381. int imH = jmin (topLeft->getHeight(), getHeight() / 2);
  59382. g.drawImage (topLeft,
  59383. 0, 0, topLeft->getWidth(), imH,
  59384. 0, 0, topLeft->getWidth(), imH);
  59385. imH = jmin (bottomRight->getHeight(), getHeight() - getHeight() / 2);
  59386. g.drawImage (bottomRight,
  59387. 0, getHeight() - imH, bottomRight->getWidth(), imH,
  59388. 0, bottomRight->getHeight() - imH, bottomRight->getWidth(), imH);
  59389. g.setTiledImageFill (*filler, 0, 0, 1.0f);
  59390. g.fillRect (0, topLeft->getHeight(), getWidth(), getHeight() - (topLeft->getHeight() + bottomRight->getHeight()));
  59391. }
  59392. else
  59393. {
  59394. int imW = jmin (topLeft->getWidth(), getWidth() / 2);
  59395. g.drawImage (topLeft,
  59396. 0, 0, imW, topLeft->getHeight(),
  59397. 0, 0, imW, topLeft->getHeight());
  59398. imW = jmin (bottomRight->getWidth(), getWidth() - getWidth() / 2);
  59399. g.drawImage (bottomRight,
  59400. getWidth() - imW, 0, imW, bottomRight->getHeight(),
  59401. bottomRight->getWidth() - imW, 0, imW, bottomRight->getHeight());
  59402. g.setTiledImageFill (*filler, 0, 0, 1.0f);
  59403. g.fillRect (topLeft->getWidth(), 0, getWidth() - (topLeft->getWidth() + bottomRight->getWidth()), getHeight());
  59404. }
  59405. }
  59406. void resized()
  59407. {
  59408. repaint(); // (needed for correct repainting)
  59409. }
  59410. private:
  59411. ShadowWindow (const ShadowWindow&);
  59412. ShadowWindow& operator= (const ShadowWindow&);
  59413. };
  59414. DropShadower::DropShadower (const float alpha_,
  59415. const int xOffset_,
  59416. const int yOffset_,
  59417. const float blurRadius_)
  59418. : owner (0),
  59419. numShadows (0),
  59420. shadowEdge (jmax (xOffset_, yOffset_) + (int) blurRadius_),
  59421. xOffset (xOffset_),
  59422. yOffset (yOffset_),
  59423. alpha (alpha_),
  59424. blurRadius (blurRadius_),
  59425. inDestructor (false),
  59426. reentrant (false)
  59427. {
  59428. }
  59429. DropShadower::~DropShadower()
  59430. {
  59431. if (owner != 0)
  59432. owner->removeComponentListener (this);
  59433. inDestructor = true;
  59434. deleteShadowWindows();
  59435. }
  59436. void DropShadower::deleteShadowWindows()
  59437. {
  59438. if (numShadows > 0)
  59439. {
  59440. int i;
  59441. for (i = numShadows; --i >= 0;)
  59442. delete shadowWindows[i];
  59443. for (i = 12; --i >= 0;)
  59444. delete shadowImageSections[i];
  59445. numShadows = 0;
  59446. }
  59447. }
  59448. void DropShadower::setOwner (Component* componentToFollow)
  59449. {
  59450. if (componentToFollow != owner)
  59451. {
  59452. if (owner != 0)
  59453. owner->removeComponentListener (this);
  59454. // (the component can't be null)
  59455. jassert (componentToFollow != 0);
  59456. owner = componentToFollow;
  59457. jassert (owner != 0);
  59458. jassert (owner->isOpaque()); // doesn't work properly for semi-transparent comps!
  59459. owner->addComponentListener (this);
  59460. updateShadows();
  59461. }
  59462. }
  59463. void DropShadower::componentMovedOrResized (Component&, bool /*wasMoved*/, bool /*wasResized*/)
  59464. {
  59465. updateShadows();
  59466. }
  59467. void DropShadower::componentBroughtToFront (Component&)
  59468. {
  59469. bringShadowWindowsToFront();
  59470. }
  59471. void DropShadower::componentChildrenChanged (Component&)
  59472. {
  59473. }
  59474. void DropShadower::componentParentHierarchyChanged (Component&)
  59475. {
  59476. deleteShadowWindows();
  59477. updateShadows();
  59478. }
  59479. void DropShadower::componentVisibilityChanged (Component&)
  59480. {
  59481. updateShadows();
  59482. }
  59483. void DropShadower::updateShadows()
  59484. {
  59485. if (reentrant || inDestructor || (owner == 0))
  59486. return;
  59487. reentrant = true;
  59488. ComponentPeer* const nw = owner->getPeer();
  59489. const bool isOwnerVisible = owner->isVisible()
  59490. && (nw == 0 || ! nw->isMinimised());
  59491. const bool createShadowWindows = numShadows == 0
  59492. && owner->getWidth() > 0
  59493. && owner->getHeight() > 0
  59494. && isOwnerVisible
  59495. && (Desktop::canUseSemiTransparentWindows()
  59496. || owner->getParentComponent() != 0);
  59497. if (createShadowWindows)
  59498. {
  59499. // keep a cached version of the image to save doing the gaussian too often
  59500. String imageId;
  59501. imageId << shadowEdge << ',' << xOffset << ',' << yOffset << ',' << alpha;
  59502. const int hash = imageId.hashCode();
  59503. Image* bigIm = ImageCache::getFromHashCode (hash);
  59504. if (bigIm == 0)
  59505. {
  59506. bigIm = Image::createNativeImage (Image::ARGB, shadowEdge * 5, shadowEdge * 5, true);
  59507. Graphics bigG (*bigIm);
  59508. bigG.setColour (Colours::black.withAlpha (alpha));
  59509. bigG.fillRect (shadowEdge + xOffset,
  59510. shadowEdge + yOffset,
  59511. bigIm->getWidth() - (shadowEdge * 2),
  59512. bigIm->getHeight() - (shadowEdge * 2));
  59513. ImageConvolutionKernel blurKernel (roundToInt (blurRadius * 2.0f));
  59514. blurKernel.createGaussianBlur (blurRadius);
  59515. blurKernel.applyToImage (*bigIm, 0,
  59516. Rectangle<int> (xOffset, yOffset,
  59517. bigIm->getWidth(), bigIm->getHeight()));
  59518. ImageCache::addImageToCache (bigIm, hash);
  59519. }
  59520. const int iw = bigIm->getWidth();
  59521. const int ih = bigIm->getHeight();
  59522. const int shadowEdge2 = shadowEdge * 2;
  59523. setShadowImage (bigIm, 0, shadowEdge, shadowEdge2, 0, 0);
  59524. setShadowImage (bigIm, 1, shadowEdge, shadowEdge2, 0, ih - shadowEdge2);
  59525. setShadowImage (bigIm, 2, shadowEdge, shadowEdge, 0, shadowEdge2);
  59526. setShadowImage (bigIm, 3, shadowEdge, shadowEdge2, iw - shadowEdge, 0);
  59527. setShadowImage (bigIm, 4, shadowEdge, shadowEdge2, iw - shadowEdge, ih - shadowEdge2);
  59528. setShadowImage (bigIm, 5, shadowEdge, shadowEdge, iw - shadowEdge, shadowEdge2);
  59529. setShadowImage (bigIm, 6, shadowEdge, shadowEdge, shadowEdge, 0);
  59530. setShadowImage (bigIm, 7, shadowEdge, shadowEdge, iw - shadowEdge2, 0);
  59531. setShadowImage (bigIm, 8, shadowEdge, shadowEdge, shadowEdge2, 0);
  59532. setShadowImage (bigIm, 9, shadowEdge, shadowEdge, shadowEdge, ih - shadowEdge);
  59533. setShadowImage (bigIm, 10, shadowEdge, shadowEdge, iw - shadowEdge2, ih - shadowEdge);
  59534. setShadowImage (bigIm, 11, shadowEdge, shadowEdge, shadowEdge2, ih - shadowEdge);
  59535. ImageCache::release (bigIm);
  59536. for (int i = 0; i < 4; ++i)
  59537. {
  59538. shadowWindows[numShadows] = new ShadowWindow (owner, i, shadowImageSections);
  59539. ++numShadows;
  59540. }
  59541. }
  59542. if (numShadows > 0)
  59543. {
  59544. for (int i = numShadows; --i >= 0;)
  59545. {
  59546. shadowWindows[i]->setAlwaysOnTop (owner->isAlwaysOnTop());
  59547. shadowWindows[i]->setVisible (isOwnerVisible);
  59548. }
  59549. const int x = owner->getX();
  59550. const int y = owner->getY() - shadowEdge;
  59551. const int w = owner->getWidth();
  59552. const int h = owner->getHeight() + shadowEdge + shadowEdge;
  59553. shadowWindows[0]->setBounds (x - shadowEdge,
  59554. y,
  59555. shadowEdge,
  59556. h);
  59557. shadowWindows[1]->setBounds (x + w,
  59558. y,
  59559. shadowEdge,
  59560. h);
  59561. shadowWindows[2]->setBounds (x,
  59562. y,
  59563. w,
  59564. shadowEdge);
  59565. shadowWindows[3]->setBounds (x,
  59566. owner->getBottom(),
  59567. w,
  59568. shadowEdge);
  59569. }
  59570. reentrant = false;
  59571. if (createShadowWindows)
  59572. bringShadowWindowsToFront();
  59573. }
  59574. void DropShadower::setShadowImage (Image* const src, const int num, const int w, const int h,
  59575. const int sx, const int sy)
  59576. {
  59577. shadowImageSections[num] = new Image (Image::ARGB, w, h, true);
  59578. Graphics g (*shadowImageSections[num]);
  59579. g.drawImage (src, 0, 0, w, h, sx, sy, w, h);
  59580. }
  59581. void DropShadower::bringShadowWindowsToFront()
  59582. {
  59583. if (! (inDestructor || reentrant))
  59584. {
  59585. updateShadows();
  59586. reentrant = true;
  59587. for (int i = numShadows; --i >= 0;)
  59588. shadowWindows[i]->toBehind (owner);
  59589. reentrant = false;
  59590. }
  59591. }
  59592. END_JUCE_NAMESPACE
  59593. /*** End of inlined file: juce_DropShadower.cpp ***/
  59594. /*** Start of inlined file: juce_MagnifierComponent.cpp ***/
  59595. BEGIN_JUCE_NAMESPACE
  59596. class MagnifyingPeer : public ComponentPeer
  59597. {
  59598. public:
  59599. MagnifyingPeer (Component* const component_,
  59600. MagnifierComponent* const magnifierComp_)
  59601. : ComponentPeer (component_, 0),
  59602. magnifierComp (magnifierComp_)
  59603. {
  59604. }
  59605. ~MagnifyingPeer()
  59606. {
  59607. }
  59608. void* getNativeHandle() const { return 0; }
  59609. void setVisible (bool) {}
  59610. void setTitle (const String&) {}
  59611. void setPosition (int, int) {}
  59612. void setSize (int, int) {}
  59613. void setBounds (int, int, int, int, bool) {}
  59614. void setMinimised (bool) {}
  59615. bool isMinimised() const { return false; }
  59616. void setFullScreen (bool) {}
  59617. bool isFullScreen() const { return false; }
  59618. const BorderSize getFrameSize() const { return BorderSize (0); }
  59619. bool setAlwaysOnTop (bool) { return true; }
  59620. void toFront (bool) {}
  59621. void toBehind (ComponentPeer*) {}
  59622. void setIcon (const Image&) {}
  59623. bool isFocused() const
  59624. {
  59625. return magnifierComp->hasKeyboardFocus (true);
  59626. }
  59627. void grabFocus()
  59628. {
  59629. ComponentPeer* peer = magnifierComp->getPeer();
  59630. if (peer != 0)
  59631. peer->grabFocus();
  59632. }
  59633. void textInputRequired (const Point<int>& position)
  59634. {
  59635. ComponentPeer* peer = magnifierComp->getPeer();
  59636. if (peer != 0)
  59637. peer->textInputRequired (position);
  59638. }
  59639. const Rectangle<int> getBounds() const
  59640. {
  59641. return Rectangle<int> (magnifierComp->getScreenX(), magnifierComp->getScreenY(),
  59642. component->getWidth(), component->getHeight());
  59643. }
  59644. const Point<int> getScreenPosition() const
  59645. {
  59646. return magnifierComp->getScreenPosition();
  59647. }
  59648. const Point<int> relativePositionToGlobal (const Point<int>& relativePosition)
  59649. {
  59650. const double zoom = magnifierComp->getScaleFactor();
  59651. return magnifierComp->relativePositionToGlobal (Point<int> (roundToInt (relativePosition.getX() * zoom),
  59652. roundToInt (relativePosition.getY() * zoom)));
  59653. }
  59654. const Point<int> globalPositionToRelative (const Point<int>& screenPosition)
  59655. {
  59656. const Point<int> p (magnifierComp->globalPositionToRelative (screenPosition));
  59657. const double zoom = magnifierComp->getScaleFactor();
  59658. return Point<int> (roundToInt (p.getX() / zoom),
  59659. roundToInt (p.getY() / zoom));
  59660. }
  59661. bool contains (const Point<int>& position, bool) const
  59662. {
  59663. return ((unsigned int) position.getX()) < (unsigned int) magnifierComp->getWidth()
  59664. && ((unsigned int) position.getY()) < (unsigned int) magnifierComp->getHeight();
  59665. }
  59666. void repaint (int x, int y, int w, int h)
  59667. {
  59668. const double zoom = magnifierComp->getScaleFactor();
  59669. magnifierComp->repaint ((int) (x * zoom),
  59670. (int) (y * zoom),
  59671. roundToInt (w * zoom) + 1,
  59672. roundToInt (h * zoom) + 1);
  59673. }
  59674. void performAnyPendingRepaintsNow()
  59675. {
  59676. }
  59677. juce_UseDebuggingNewOperator
  59678. private:
  59679. MagnifierComponent* const magnifierComp;
  59680. MagnifyingPeer (const MagnifyingPeer&);
  59681. MagnifyingPeer& operator= (const MagnifyingPeer&);
  59682. };
  59683. class PeerHolderComp : public Component
  59684. {
  59685. public:
  59686. PeerHolderComp (MagnifierComponent* const magnifierComp_)
  59687. : magnifierComp (magnifierComp_)
  59688. {
  59689. setVisible (true);
  59690. }
  59691. ~PeerHolderComp()
  59692. {
  59693. }
  59694. ComponentPeer* createNewPeer (int, void*)
  59695. {
  59696. return new MagnifyingPeer (this, magnifierComp);
  59697. }
  59698. void childBoundsChanged (Component* c)
  59699. {
  59700. if (c != 0)
  59701. {
  59702. setSize (c->getWidth(), c->getHeight());
  59703. magnifierComp->childBoundsChanged (this);
  59704. }
  59705. }
  59706. void mouseWheelMove (const MouseEvent& e, float ix, float iy)
  59707. {
  59708. // unhandled mouse wheel moves can be referred upwards to the parent comp..
  59709. Component* const p = magnifierComp->getParentComponent();
  59710. if (p != 0)
  59711. p->mouseWheelMove (e.getEventRelativeTo (p), ix, iy);
  59712. }
  59713. private:
  59714. MagnifierComponent* const magnifierComp;
  59715. PeerHolderComp (const PeerHolderComp&);
  59716. PeerHolderComp& operator= (const PeerHolderComp&);
  59717. };
  59718. MagnifierComponent::MagnifierComponent (Component* const content_,
  59719. const bool deleteContentCompWhenNoLongerNeeded)
  59720. : content (content_),
  59721. scaleFactor (0.0),
  59722. peer (0),
  59723. deleteContent (deleteContentCompWhenNoLongerNeeded),
  59724. quality (Graphics::lowResamplingQuality),
  59725. mouseSource (0, true)
  59726. {
  59727. holderComp = new PeerHolderComp (this);
  59728. setScaleFactor (1.0);
  59729. }
  59730. MagnifierComponent::~MagnifierComponent()
  59731. {
  59732. delete holderComp;
  59733. if (deleteContent)
  59734. delete content;
  59735. }
  59736. void MagnifierComponent::setScaleFactor (double newScaleFactor)
  59737. {
  59738. jassert (newScaleFactor > 0.0); // hmm - unlikely to work well with a negative scale factor
  59739. newScaleFactor = jlimit (1.0 / 8.0, 1000.0, newScaleFactor);
  59740. if (scaleFactor != newScaleFactor)
  59741. {
  59742. scaleFactor = newScaleFactor;
  59743. if (scaleFactor == 1.0)
  59744. {
  59745. holderComp->removeFromDesktop();
  59746. peer = 0;
  59747. addChildComponent (content);
  59748. childBoundsChanged (content);
  59749. }
  59750. else
  59751. {
  59752. holderComp->addAndMakeVisible (content);
  59753. holderComp->childBoundsChanged (content);
  59754. childBoundsChanged (holderComp);
  59755. holderComp->addToDesktop (0);
  59756. peer = holderComp->getPeer();
  59757. }
  59758. repaint();
  59759. }
  59760. }
  59761. void MagnifierComponent::setResamplingQuality (Graphics::ResamplingQuality newQuality)
  59762. {
  59763. quality = newQuality;
  59764. }
  59765. void MagnifierComponent::paint (Graphics& g)
  59766. {
  59767. const int w = holderComp->getWidth();
  59768. const int h = holderComp->getHeight();
  59769. if (w == 0 || h == 0)
  59770. return;
  59771. const Rectangle<int> r (g.getClipBounds());
  59772. const int srcX = (int) (r.getX() / scaleFactor);
  59773. const int srcY = (int) (r.getY() / scaleFactor);
  59774. int srcW = roundToInt (r.getRight() / scaleFactor) - srcX;
  59775. int srcH = roundToInt (r.getBottom() / scaleFactor) - srcY;
  59776. if (scaleFactor >= 1.0)
  59777. {
  59778. ++srcW;
  59779. ++srcH;
  59780. }
  59781. Image temp (Image::ARGB, jmax (w, srcX + srcW), jmax (h, srcY + srcH), false);
  59782. temp.clear (srcX, srcY, srcW, srcH);
  59783. {
  59784. Graphics g2 (temp);
  59785. g2.reduceClipRegion (srcX, srcY, srcW, srcH);
  59786. holderComp->paintEntireComponent (g2);
  59787. }
  59788. g.setImageResamplingQuality (quality);
  59789. g.drawImageTransformed (&temp, temp.getBounds(),
  59790. AffineTransform::scale ((float) scaleFactor, (float) scaleFactor),
  59791. false);
  59792. }
  59793. void MagnifierComponent::childBoundsChanged (Component* c)
  59794. {
  59795. if (c != 0)
  59796. setSize (roundToInt (c->getWidth() * scaleFactor),
  59797. roundToInt (c->getHeight() * scaleFactor));
  59798. }
  59799. void MagnifierComponent::passOnMouseEventToPeer (const MouseEvent& e)
  59800. {
  59801. if (peer != 0)
  59802. mouseSource.handleEvent (peer, Point<int> (scaleInt (e.x), scaleInt (e.y)),
  59803. e.eventTime.toMilliseconds(), ModifierKeys::getCurrentModifiers());
  59804. }
  59805. void MagnifierComponent::mouseDown (const MouseEvent& e)
  59806. {
  59807. passOnMouseEventToPeer (e);
  59808. }
  59809. void MagnifierComponent::mouseUp (const MouseEvent& e)
  59810. {
  59811. passOnMouseEventToPeer (e);
  59812. }
  59813. void MagnifierComponent::mouseDrag (const MouseEvent& e)
  59814. {
  59815. passOnMouseEventToPeer (e);
  59816. }
  59817. void MagnifierComponent::mouseMove (const MouseEvent& e)
  59818. {
  59819. passOnMouseEventToPeer (e);
  59820. }
  59821. void MagnifierComponent::mouseEnter (const MouseEvent& e)
  59822. {
  59823. passOnMouseEventToPeer (e);
  59824. }
  59825. void MagnifierComponent::mouseExit (const MouseEvent& e)
  59826. {
  59827. passOnMouseEventToPeer (e);
  59828. }
  59829. void MagnifierComponent::mouseWheelMove (const MouseEvent& e, float ix, float iy)
  59830. {
  59831. if (peer != 0)
  59832. peer->handleMouseWheel (e.source.getIndex(),
  59833. Point<int> (scaleInt (e.x), scaleInt (e.y)), e.eventTime.toMilliseconds(),
  59834. ix * 256.0f, iy * 256.0f);
  59835. else
  59836. Component::mouseWheelMove (e, ix, iy);
  59837. }
  59838. int MagnifierComponent::scaleInt (const int n) const
  59839. {
  59840. return roundToInt (n / scaleFactor);
  59841. }
  59842. END_JUCE_NAMESPACE
  59843. /*** End of inlined file: juce_MagnifierComponent.cpp ***/
  59844. /*** Start of inlined file: juce_MidiKeyboardComponent.cpp ***/
  59845. BEGIN_JUCE_NAMESPACE
  59846. class MidiKeyboardUpDownButton : public Button
  59847. {
  59848. public:
  59849. MidiKeyboardUpDownButton (MidiKeyboardComponent* const owner_,
  59850. const int delta_)
  59851. : Button (String::empty),
  59852. owner (owner_),
  59853. delta (delta_)
  59854. {
  59855. setOpaque (true);
  59856. }
  59857. ~MidiKeyboardUpDownButton()
  59858. {
  59859. }
  59860. void clicked()
  59861. {
  59862. int note = owner->getLowestVisibleKey();
  59863. if (delta < 0)
  59864. note = (note - 1) / 12;
  59865. else
  59866. note = note / 12 + 1;
  59867. owner->setLowestVisibleKey (note * 12);
  59868. }
  59869. void paintButton (Graphics& g,
  59870. bool isMouseOverButton,
  59871. bool isButtonDown)
  59872. {
  59873. owner->drawUpDownButton (g, getWidth(), getHeight(),
  59874. isMouseOverButton, isButtonDown,
  59875. delta > 0);
  59876. }
  59877. private:
  59878. MidiKeyboardComponent* const owner;
  59879. const int delta;
  59880. MidiKeyboardUpDownButton (const MidiKeyboardUpDownButton&);
  59881. MidiKeyboardUpDownButton& operator= (const MidiKeyboardUpDownButton&);
  59882. };
  59883. MidiKeyboardComponent::MidiKeyboardComponent (MidiKeyboardState& state_,
  59884. const Orientation orientation_)
  59885. : state (state_),
  59886. xOffset (0),
  59887. blackNoteLength (1),
  59888. keyWidth (16.0f),
  59889. orientation (orientation_),
  59890. midiChannel (1),
  59891. midiInChannelMask (0xffff),
  59892. velocity (1.0f),
  59893. noteUnderMouse (-1),
  59894. mouseDownNote (-1),
  59895. rangeStart (0),
  59896. rangeEnd (127),
  59897. firstKey (12 * 4),
  59898. canScroll (true),
  59899. mouseDragging (false),
  59900. useMousePositionForVelocity (true),
  59901. keyMappingOctave (6),
  59902. octaveNumForMiddleC (3)
  59903. {
  59904. addChildComponent (scrollDown = new MidiKeyboardUpDownButton (this, -1));
  59905. addChildComponent (scrollUp = new MidiKeyboardUpDownButton (this, 1));
  59906. // initialise with a default set of querty key-mappings..
  59907. const char* const keymap = "awsedftgyhujkolp;";
  59908. for (int i = String (keymap).length(); --i >= 0;)
  59909. setKeyPressForNote (KeyPress (keymap[i], 0, 0), i);
  59910. setOpaque (true);
  59911. setWantsKeyboardFocus (true);
  59912. state.addListener (this);
  59913. }
  59914. MidiKeyboardComponent::~MidiKeyboardComponent()
  59915. {
  59916. state.removeListener (this);
  59917. jassert (mouseDownNote < 0 && keysPressed.countNumberOfSetBits() == 0); // leaving stuck notes!
  59918. deleteAllChildren();
  59919. }
  59920. void MidiKeyboardComponent::setKeyWidth (const float widthInPixels)
  59921. {
  59922. keyWidth = widthInPixels;
  59923. resized();
  59924. }
  59925. void MidiKeyboardComponent::setOrientation (const Orientation newOrientation)
  59926. {
  59927. if (orientation != newOrientation)
  59928. {
  59929. orientation = newOrientation;
  59930. resized();
  59931. }
  59932. }
  59933. void MidiKeyboardComponent::setAvailableRange (const int lowestNote,
  59934. const int highestNote)
  59935. {
  59936. jassert (lowestNote >= 0 && lowestNote <= 127);
  59937. jassert (highestNote >= 0 && highestNote <= 127);
  59938. jassert (lowestNote <= highestNote);
  59939. if (rangeStart != lowestNote || rangeEnd != highestNote)
  59940. {
  59941. rangeStart = jlimit (0, 127, lowestNote);
  59942. rangeEnd = jlimit (0, 127, highestNote);
  59943. firstKey = jlimit (rangeStart, rangeEnd, firstKey);
  59944. resized();
  59945. }
  59946. }
  59947. void MidiKeyboardComponent::setLowestVisibleKey (int noteNumber)
  59948. {
  59949. noteNumber = jlimit (rangeStart, rangeEnd, noteNumber);
  59950. if (noteNumber != firstKey)
  59951. {
  59952. firstKey = noteNumber;
  59953. sendChangeMessage (this);
  59954. resized();
  59955. }
  59956. }
  59957. void MidiKeyboardComponent::setScrollButtonsVisible (const bool canScroll_)
  59958. {
  59959. if (canScroll != canScroll_)
  59960. {
  59961. canScroll = canScroll_;
  59962. resized();
  59963. }
  59964. }
  59965. void MidiKeyboardComponent::colourChanged()
  59966. {
  59967. repaint();
  59968. }
  59969. void MidiKeyboardComponent::setMidiChannel (const int midiChannelNumber)
  59970. {
  59971. jassert (midiChannelNumber > 0 && midiChannelNumber <= 16);
  59972. if (midiChannel != midiChannelNumber)
  59973. {
  59974. resetAnyKeysInUse();
  59975. midiChannel = jlimit (1, 16, midiChannelNumber);
  59976. }
  59977. }
  59978. void MidiKeyboardComponent::setMidiChannelsToDisplay (const int midiChannelMask)
  59979. {
  59980. midiInChannelMask = midiChannelMask;
  59981. triggerAsyncUpdate();
  59982. }
  59983. void MidiKeyboardComponent::setVelocity (const float velocity_, const bool useMousePositionForVelocity_)
  59984. {
  59985. velocity = jlimit (0.0f, 1.0f, velocity_);
  59986. useMousePositionForVelocity = useMousePositionForVelocity_;
  59987. }
  59988. void MidiKeyboardComponent::getKeyPosition (int midiNoteNumber, const float keyWidth, int& x, int& w) const
  59989. {
  59990. jassert (midiNoteNumber >= 0 && midiNoteNumber < 128);
  59991. static const float blackNoteWidth = 0.7f;
  59992. static const float notePos[] = { 0.0f, 1 - blackNoteWidth * 0.6f,
  59993. 1.0f, 2 - blackNoteWidth * 0.4f,
  59994. 2.0f, 3.0f, 4 - blackNoteWidth * 0.7f,
  59995. 4.0f, 5 - blackNoteWidth * 0.5f,
  59996. 5.0f, 6 - blackNoteWidth * 0.3f,
  59997. 6.0f };
  59998. static const float widths[] = { 1.0f, blackNoteWidth,
  59999. 1.0f, blackNoteWidth,
  60000. 1.0f, 1.0f, blackNoteWidth,
  60001. 1.0f, blackNoteWidth,
  60002. 1.0f, blackNoteWidth,
  60003. 1.0f };
  60004. const int octave = midiNoteNumber / 12;
  60005. const int note = midiNoteNumber % 12;
  60006. x = roundToInt (octave * 7.0f * keyWidth + notePos [note] * keyWidth);
  60007. w = roundToInt (widths [note] * keyWidth);
  60008. }
  60009. void MidiKeyboardComponent::getKeyPos (int midiNoteNumber, int& x, int& w) const
  60010. {
  60011. getKeyPosition (midiNoteNumber, keyWidth, x, w);
  60012. int rx, rw;
  60013. getKeyPosition (rangeStart, keyWidth, rx, rw);
  60014. x -= xOffset + rx;
  60015. }
  60016. int MidiKeyboardComponent::getKeyStartPosition (const int midiNoteNumber) const
  60017. {
  60018. int x, y;
  60019. getKeyPos (midiNoteNumber, x, y);
  60020. return x;
  60021. }
  60022. static const uint8 whiteNotes[] = { 0, 2, 4, 5, 7, 9, 11 };
  60023. static const uint8 blackNotes[] = { 1, 3, 6, 8, 10 };
  60024. int MidiKeyboardComponent::xyToNote (const Point<int>& pos, float& mousePositionVelocity)
  60025. {
  60026. if (! reallyContains (pos.getX(), pos.getY(), false))
  60027. return -1;
  60028. Point<int> p (pos);
  60029. if (orientation != horizontalKeyboard)
  60030. {
  60031. p = Point<int> (p.getY(), p.getX());
  60032. if (orientation == verticalKeyboardFacingLeft)
  60033. p = Point<int> (p.getX(), getWidth() - p.getY());
  60034. else
  60035. p = Point<int> (getHeight() - p.getX(), p.getY());
  60036. }
  60037. return remappedXYToNote (p + Point<int> (xOffset, 0), mousePositionVelocity);
  60038. }
  60039. int MidiKeyboardComponent::remappedXYToNote (const Point<int>& pos, float& mousePositionVelocity) const
  60040. {
  60041. if (pos.getY() < blackNoteLength)
  60042. {
  60043. for (int octaveStart = 12 * (rangeStart / 12); octaveStart <= rangeEnd; octaveStart += 12)
  60044. {
  60045. for (int i = 0; i < 5; ++i)
  60046. {
  60047. const int note = octaveStart + blackNotes [i];
  60048. if (note >= rangeStart && note <= rangeEnd)
  60049. {
  60050. int kx, kw;
  60051. getKeyPos (note, kx, kw);
  60052. kx += xOffset;
  60053. if (pos.getX() >= kx && pos.getX() < kx + kw)
  60054. {
  60055. mousePositionVelocity = pos.getY() / (float) blackNoteLength;
  60056. return note;
  60057. }
  60058. }
  60059. }
  60060. }
  60061. }
  60062. for (int octaveStart = 12 * (rangeStart / 12); octaveStart <= rangeEnd; octaveStart += 12)
  60063. {
  60064. for (int i = 0; i < 7; ++i)
  60065. {
  60066. const int note = octaveStart + whiteNotes [i];
  60067. if (note >= rangeStart && note <= rangeEnd)
  60068. {
  60069. int kx, kw;
  60070. getKeyPos (note, kx, kw);
  60071. kx += xOffset;
  60072. if (pos.getX() >= kx && pos.getX() < kx + kw)
  60073. {
  60074. const int whiteNoteLength = (orientation == horizontalKeyboard) ? getHeight() : getWidth();
  60075. mousePositionVelocity = pos.getY() / (float) whiteNoteLength;
  60076. return note;
  60077. }
  60078. }
  60079. }
  60080. }
  60081. mousePositionVelocity = 0;
  60082. return -1;
  60083. }
  60084. void MidiKeyboardComponent::repaintNote (const int noteNum)
  60085. {
  60086. if (noteNum >= rangeStart && noteNum <= rangeEnd)
  60087. {
  60088. int x, w;
  60089. getKeyPos (noteNum, x, w);
  60090. if (orientation == horizontalKeyboard)
  60091. repaint (x, 0, w, getHeight());
  60092. else if (orientation == verticalKeyboardFacingLeft)
  60093. repaint (0, x, getWidth(), w);
  60094. else if (orientation == verticalKeyboardFacingRight)
  60095. repaint (0, getHeight() - x - w, getWidth(), w);
  60096. }
  60097. }
  60098. void MidiKeyboardComponent::paint (Graphics& g)
  60099. {
  60100. g.fillAll (Colours::white.overlaidWith (findColour (whiteNoteColourId)));
  60101. const Colour lineColour (findColour (keySeparatorLineColourId));
  60102. const Colour textColour (findColour (textLabelColourId));
  60103. int x, w, octave;
  60104. for (octave = 0; octave < 128; octave += 12)
  60105. {
  60106. for (int white = 0; white < 7; ++white)
  60107. {
  60108. const int noteNum = octave + whiteNotes [white];
  60109. if (noteNum >= rangeStart && noteNum <= rangeEnd)
  60110. {
  60111. getKeyPos (noteNum, x, w);
  60112. if (orientation == horizontalKeyboard)
  60113. drawWhiteNote (noteNum, g, x, 0, w, getHeight(),
  60114. state.isNoteOnForChannels (midiInChannelMask, noteNum),
  60115. noteUnderMouse == noteNum,
  60116. lineColour, textColour);
  60117. else if (orientation == verticalKeyboardFacingLeft)
  60118. drawWhiteNote (noteNum, g, 0, x, getWidth(), w,
  60119. state.isNoteOnForChannels (midiInChannelMask, noteNum),
  60120. noteUnderMouse == noteNum,
  60121. lineColour, textColour);
  60122. else if (orientation == verticalKeyboardFacingRight)
  60123. drawWhiteNote (noteNum, g, 0, getHeight() - x - w, getWidth(), w,
  60124. state.isNoteOnForChannels (midiInChannelMask, noteNum),
  60125. noteUnderMouse == noteNum,
  60126. lineColour, textColour);
  60127. }
  60128. }
  60129. }
  60130. float x1 = 0.0f, y1 = 0.0f, x2 = 0.0f, y2 = 0.0f;
  60131. if (orientation == verticalKeyboardFacingLeft)
  60132. {
  60133. x1 = getWidth() - 1.0f;
  60134. x2 = getWidth() - 5.0f;
  60135. }
  60136. else if (orientation == verticalKeyboardFacingRight)
  60137. x2 = 5.0f;
  60138. else
  60139. y2 = 5.0f;
  60140. g.setGradientFill (ColourGradient (Colours::black.withAlpha (0.3f), x1, y1,
  60141. Colours::transparentBlack, x2, y2, false));
  60142. getKeyPos (rangeEnd, x, w);
  60143. x += w;
  60144. if (orientation == verticalKeyboardFacingLeft)
  60145. g.fillRect (getWidth() - 5, 0, 5, x);
  60146. else if (orientation == verticalKeyboardFacingRight)
  60147. g.fillRect (0, 0, 5, x);
  60148. else
  60149. g.fillRect (0, 0, x, 5);
  60150. g.setColour (lineColour);
  60151. if (orientation == verticalKeyboardFacingLeft)
  60152. g.fillRect (0, 0, 1, x);
  60153. else if (orientation == verticalKeyboardFacingRight)
  60154. g.fillRect (getWidth() - 1, 0, 1, x);
  60155. else
  60156. g.fillRect (0, getHeight() - 1, x, 1);
  60157. const Colour blackNoteColour (findColour (blackNoteColourId));
  60158. for (octave = 0; octave < 128; octave += 12)
  60159. {
  60160. for (int black = 0; black < 5; ++black)
  60161. {
  60162. const int noteNum = octave + blackNotes [black];
  60163. if (noteNum >= rangeStart && noteNum <= rangeEnd)
  60164. {
  60165. getKeyPos (noteNum, x, w);
  60166. if (orientation == horizontalKeyboard)
  60167. drawBlackNote (noteNum, g, x, 0, w, blackNoteLength,
  60168. state.isNoteOnForChannels (midiInChannelMask, noteNum),
  60169. noteUnderMouse == noteNum,
  60170. blackNoteColour);
  60171. else if (orientation == verticalKeyboardFacingLeft)
  60172. drawBlackNote (noteNum, g, getWidth() - blackNoteLength, x, blackNoteLength, w,
  60173. state.isNoteOnForChannels (midiInChannelMask, noteNum),
  60174. noteUnderMouse == noteNum,
  60175. blackNoteColour);
  60176. else if (orientation == verticalKeyboardFacingRight)
  60177. drawBlackNote (noteNum, g, 0, getHeight() - x - w, blackNoteLength, w,
  60178. state.isNoteOnForChannels (midiInChannelMask, noteNum),
  60179. noteUnderMouse == noteNum,
  60180. blackNoteColour);
  60181. }
  60182. }
  60183. }
  60184. }
  60185. void MidiKeyboardComponent::drawWhiteNote (int midiNoteNumber,
  60186. Graphics& g, int x, int y, int w, int h,
  60187. bool isDown, bool isOver,
  60188. const Colour& lineColour,
  60189. const Colour& textColour)
  60190. {
  60191. Colour c (Colours::transparentWhite);
  60192. if (isDown)
  60193. c = findColour (keyDownOverlayColourId);
  60194. if (isOver)
  60195. c = c.overlaidWith (findColour (mouseOverKeyOverlayColourId));
  60196. g.setColour (c);
  60197. g.fillRect (x, y, w, h);
  60198. const String text (getWhiteNoteText (midiNoteNumber));
  60199. if (! text.isEmpty())
  60200. {
  60201. g.setColour (textColour);
  60202. Font f (jmin (12.0f, keyWidth * 0.9f));
  60203. f.setHorizontalScale (0.8f);
  60204. g.setFont (f);
  60205. Justification justification (Justification::centredBottom);
  60206. if (orientation == verticalKeyboardFacingLeft)
  60207. justification = Justification::centredLeft;
  60208. else if (orientation == verticalKeyboardFacingRight)
  60209. justification = Justification::centredRight;
  60210. g.drawFittedText (text, x + 2, y + 2, w - 4, h - 4, justification, 1);
  60211. }
  60212. g.setColour (lineColour);
  60213. if (orientation == horizontalKeyboard)
  60214. g.fillRect (x, y, 1, h);
  60215. else if (orientation == verticalKeyboardFacingLeft)
  60216. g.fillRect (x, y, w, 1);
  60217. else if (orientation == verticalKeyboardFacingRight)
  60218. g.fillRect (x, y + h - 1, w, 1);
  60219. if (midiNoteNumber == rangeEnd)
  60220. {
  60221. if (orientation == horizontalKeyboard)
  60222. g.fillRect (x + w, y, 1, h);
  60223. else if (orientation == verticalKeyboardFacingLeft)
  60224. g.fillRect (x, y + h, w, 1);
  60225. else if (orientation == verticalKeyboardFacingRight)
  60226. g.fillRect (x, y - 1, w, 1);
  60227. }
  60228. }
  60229. void MidiKeyboardComponent::drawBlackNote (int /*midiNoteNumber*/,
  60230. Graphics& g, int x, int y, int w, int h,
  60231. bool isDown, bool isOver,
  60232. const Colour& noteFillColour)
  60233. {
  60234. Colour c (noteFillColour);
  60235. if (isDown)
  60236. c = c.overlaidWith (findColour (keyDownOverlayColourId));
  60237. if (isOver)
  60238. c = c.overlaidWith (findColour (mouseOverKeyOverlayColourId));
  60239. g.setColour (c);
  60240. g.fillRect (x, y, w, h);
  60241. if (isDown)
  60242. {
  60243. g.setColour (noteFillColour);
  60244. g.drawRect (x, y, w, h);
  60245. }
  60246. else
  60247. {
  60248. const int xIndent = jmax (1, jmin (w, h) / 8);
  60249. g.setColour (c.brighter());
  60250. if (orientation == horizontalKeyboard)
  60251. g.fillRect (x + xIndent, y, w - xIndent * 2, 7 * h / 8);
  60252. else if (orientation == verticalKeyboardFacingLeft)
  60253. g.fillRect (x + w / 8, y + xIndent, w - w / 8, h - xIndent * 2);
  60254. else if (orientation == verticalKeyboardFacingRight)
  60255. g.fillRect (x, y + xIndent, 7 * w / 8, h - xIndent * 2);
  60256. }
  60257. }
  60258. void MidiKeyboardComponent::setOctaveForMiddleC (const int octaveNumForMiddleC_)
  60259. {
  60260. octaveNumForMiddleC = octaveNumForMiddleC_;
  60261. repaint();
  60262. }
  60263. const String MidiKeyboardComponent::getWhiteNoteText (const int midiNoteNumber)
  60264. {
  60265. if (keyWidth > 14.0f && midiNoteNumber % 12 == 0)
  60266. return MidiMessage::getMidiNoteName (midiNoteNumber, true, true, octaveNumForMiddleC);
  60267. return String::empty;
  60268. }
  60269. void MidiKeyboardComponent::drawUpDownButton (Graphics& g, int w, int h,
  60270. const bool isMouseOver,
  60271. const bool isButtonDown,
  60272. const bool movesOctavesUp)
  60273. {
  60274. g.fillAll (findColour (upDownButtonBackgroundColourId));
  60275. float angle;
  60276. if (orientation == MidiKeyboardComponent::horizontalKeyboard)
  60277. angle = movesOctavesUp ? 0.0f : 0.5f;
  60278. else if (orientation == MidiKeyboardComponent::verticalKeyboardFacingLeft)
  60279. angle = movesOctavesUp ? 0.25f : 0.75f;
  60280. else
  60281. angle = movesOctavesUp ? 0.75f : 0.25f;
  60282. Path path;
  60283. path.lineTo (0.0f, 1.0f);
  60284. path.lineTo (1.0f, 0.5f);
  60285. path.closeSubPath();
  60286. path.applyTransform (AffineTransform::rotation (float_Pi * 2.0f * angle, 0.5f, 0.5f));
  60287. g.setColour (findColour (upDownButtonArrowColourId)
  60288. .withAlpha (isButtonDown ? 1.0f : (isMouseOver ? 0.6f : 0.4f)));
  60289. g.fillPath (path, path.getTransformToScaleToFit (1.0f, 1.0f,
  60290. w - 2.0f,
  60291. h - 2.0f,
  60292. true));
  60293. }
  60294. void MidiKeyboardComponent::resized()
  60295. {
  60296. int w = getWidth();
  60297. int h = getHeight();
  60298. if (w > 0 && h > 0)
  60299. {
  60300. if (orientation != horizontalKeyboard)
  60301. swapVariables (w, h);
  60302. blackNoteLength = roundToInt (h * 0.7f);
  60303. int kx2, kw2;
  60304. getKeyPos (rangeEnd, kx2, kw2);
  60305. kx2 += kw2;
  60306. if (firstKey != rangeStart)
  60307. {
  60308. int kx1, kw1;
  60309. getKeyPos (rangeStart, kx1, kw1);
  60310. if (kx2 - kx1 <= w)
  60311. {
  60312. firstKey = rangeStart;
  60313. sendChangeMessage (this);
  60314. repaint();
  60315. }
  60316. }
  60317. const bool showScrollButtons = canScroll && (firstKey > rangeStart || kx2 > w + xOffset * 2);
  60318. scrollDown->setVisible (showScrollButtons);
  60319. scrollUp->setVisible (showScrollButtons);
  60320. xOffset = 0;
  60321. if (showScrollButtons)
  60322. {
  60323. const int scrollButtonW = jmin (12, w / 2);
  60324. if (orientation == horizontalKeyboard)
  60325. {
  60326. scrollDown->setBounds (0, 0, scrollButtonW, getHeight());
  60327. scrollUp->setBounds (getWidth() - scrollButtonW, 0, scrollButtonW, getHeight());
  60328. }
  60329. else if (orientation == verticalKeyboardFacingLeft)
  60330. {
  60331. scrollDown->setBounds (0, 0, getWidth(), scrollButtonW);
  60332. scrollUp->setBounds (0, getHeight() - scrollButtonW, getWidth(), scrollButtonW);
  60333. }
  60334. else if (orientation == verticalKeyboardFacingRight)
  60335. {
  60336. scrollDown->setBounds (0, getHeight() - scrollButtonW, getWidth(), scrollButtonW);
  60337. scrollUp->setBounds (0, 0, getWidth(), scrollButtonW);
  60338. }
  60339. int endOfLastKey, kw;
  60340. getKeyPos (rangeEnd, endOfLastKey, kw);
  60341. endOfLastKey += kw;
  60342. float mousePositionVelocity;
  60343. const int spaceAvailable = w - scrollButtonW * 2;
  60344. const int lastStartKey = remappedXYToNote (Point<int> (endOfLastKey - spaceAvailable, 0), mousePositionVelocity) + 1;
  60345. if (lastStartKey >= 0 && firstKey > lastStartKey)
  60346. {
  60347. firstKey = jlimit (rangeStart, rangeEnd, lastStartKey);
  60348. sendChangeMessage (this);
  60349. }
  60350. int newOffset = 0;
  60351. getKeyPos (firstKey, newOffset, kw);
  60352. xOffset = newOffset - scrollButtonW;
  60353. }
  60354. else
  60355. {
  60356. firstKey = rangeStart;
  60357. }
  60358. timerCallback();
  60359. repaint();
  60360. }
  60361. }
  60362. void MidiKeyboardComponent::handleNoteOn (MidiKeyboardState*, int /*midiChannel*/, int /*midiNoteNumber*/, float /*velocity*/)
  60363. {
  60364. triggerAsyncUpdate();
  60365. }
  60366. void MidiKeyboardComponent::handleNoteOff (MidiKeyboardState*, int /*midiChannel*/, int /*midiNoteNumber*/)
  60367. {
  60368. triggerAsyncUpdate();
  60369. }
  60370. void MidiKeyboardComponent::handleAsyncUpdate()
  60371. {
  60372. for (int i = rangeStart; i <= rangeEnd; ++i)
  60373. {
  60374. if (keysCurrentlyDrawnDown[i] != state.isNoteOnForChannels (midiInChannelMask, i))
  60375. {
  60376. keysCurrentlyDrawnDown.setBit (i, state.isNoteOnForChannels (midiInChannelMask, i));
  60377. repaintNote (i);
  60378. }
  60379. }
  60380. }
  60381. void MidiKeyboardComponent::resetAnyKeysInUse()
  60382. {
  60383. if (keysPressed.countNumberOfSetBits() > 0 || mouseDownNote > 0)
  60384. {
  60385. state.allNotesOff (midiChannel);
  60386. keysPressed.clear();
  60387. mouseDownNote = -1;
  60388. }
  60389. }
  60390. void MidiKeyboardComponent::updateNoteUnderMouse (const Point<int>& pos)
  60391. {
  60392. float mousePositionVelocity = 0.0f;
  60393. const int newNote = (mouseDragging || isMouseOver())
  60394. ? xyToNote (pos, mousePositionVelocity) : -1;
  60395. if (noteUnderMouse != newNote)
  60396. {
  60397. if (mouseDownNote >= 0)
  60398. {
  60399. state.noteOff (midiChannel, mouseDownNote);
  60400. mouseDownNote = -1;
  60401. }
  60402. if (mouseDragging && newNote >= 0)
  60403. {
  60404. if (! useMousePositionForVelocity)
  60405. mousePositionVelocity = 1.0f;
  60406. state.noteOn (midiChannel, newNote, mousePositionVelocity * velocity);
  60407. mouseDownNote = newNote;
  60408. }
  60409. repaintNote (noteUnderMouse);
  60410. noteUnderMouse = newNote;
  60411. repaintNote (noteUnderMouse);
  60412. }
  60413. else if (mouseDownNote >= 0 && ! mouseDragging)
  60414. {
  60415. state.noteOff (midiChannel, mouseDownNote);
  60416. mouseDownNote = -1;
  60417. }
  60418. }
  60419. void MidiKeyboardComponent::mouseMove (const MouseEvent& e)
  60420. {
  60421. updateNoteUnderMouse (e.getPosition());
  60422. stopTimer();
  60423. }
  60424. void MidiKeyboardComponent::mouseDrag (const MouseEvent& e)
  60425. {
  60426. float mousePositionVelocity;
  60427. const int newNote = xyToNote (e.getPosition(), mousePositionVelocity);
  60428. if (newNote >= 0)
  60429. mouseDraggedToKey (newNote, e);
  60430. updateNoteUnderMouse (e.getPosition());
  60431. }
  60432. bool MidiKeyboardComponent::mouseDownOnKey (int /*midiNoteNumber*/, const MouseEvent&)
  60433. {
  60434. return true;
  60435. }
  60436. void MidiKeyboardComponent::mouseDraggedToKey (int /*midiNoteNumber*/, const MouseEvent&)
  60437. {
  60438. }
  60439. void MidiKeyboardComponent::mouseDown (const MouseEvent& e)
  60440. {
  60441. float mousePositionVelocity;
  60442. const int newNote = xyToNote (e.getPosition(), mousePositionVelocity);
  60443. mouseDragging = false;
  60444. if (newNote >= 0 && mouseDownOnKey (newNote, e))
  60445. {
  60446. repaintNote (noteUnderMouse);
  60447. noteUnderMouse = -1;
  60448. mouseDragging = true;
  60449. updateNoteUnderMouse (e.getPosition());
  60450. startTimer (500);
  60451. }
  60452. }
  60453. void MidiKeyboardComponent::mouseUp (const MouseEvent& e)
  60454. {
  60455. mouseDragging = false;
  60456. updateNoteUnderMouse (e.getPosition());
  60457. stopTimer();
  60458. }
  60459. void MidiKeyboardComponent::mouseEnter (const MouseEvent& e)
  60460. {
  60461. updateNoteUnderMouse (e.getPosition());
  60462. }
  60463. void MidiKeyboardComponent::mouseExit (const MouseEvent& e)
  60464. {
  60465. updateNoteUnderMouse (e.getPosition());
  60466. }
  60467. void MidiKeyboardComponent::mouseWheelMove (const MouseEvent&, float ix, float iy)
  60468. {
  60469. setLowestVisibleKey (getLowestVisibleKey() + roundToInt ((ix != 0 ? ix : iy) * 5.0f));
  60470. }
  60471. void MidiKeyboardComponent::timerCallback()
  60472. {
  60473. updateNoteUnderMouse (getMouseXYRelative());
  60474. }
  60475. void MidiKeyboardComponent::clearKeyMappings()
  60476. {
  60477. resetAnyKeysInUse();
  60478. keyPressNotes.clear();
  60479. keyPresses.clear();
  60480. }
  60481. void MidiKeyboardComponent::setKeyPressForNote (const KeyPress& key,
  60482. const int midiNoteOffsetFromC)
  60483. {
  60484. removeKeyPressForNote (midiNoteOffsetFromC);
  60485. keyPressNotes.add (midiNoteOffsetFromC);
  60486. keyPresses.add (key);
  60487. }
  60488. void MidiKeyboardComponent::removeKeyPressForNote (const int midiNoteOffsetFromC)
  60489. {
  60490. for (int i = keyPressNotes.size(); --i >= 0;)
  60491. {
  60492. if (keyPressNotes.getUnchecked (i) == midiNoteOffsetFromC)
  60493. {
  60494. keyPressNotes.remove (i);
  60495. keyPresses.remove (i);
  60496. }
  60497. }
  60498. }
  60499. void MidiKeyboardComponent::setKeyPressBaseOctave (const int newOctaveNumber)
  60500. {
  60501. jassert (newOctaveNumber >= 0 && newOctaveNumber <= 10);
  60502. keyMappingOctave = newOctaveNumber;
  60503. }
  60504. bool MidiKeyboardComponent::keyStateChanged (const bool /*isKeyDown*/)
  60505. {
  60506. bool keyPressUsed = false;
  60507. for (int i = keyPresses.size(); --i >= 0;)
  60508. {
  60509. const int note = 12 * keyMappingOctave + keyPressNotes.getUnchecked (i);
  60510. if (keyPresses.getReference(i).isCurrentlyDown())
  60511. {
  60512. if (! keysPressed [note])
  60513. {
  60514. keysPressed.setBit (note);
  60515. state.noteOn (midiChannel, note, velocity);
  60516. keyPressUsed = true;
  60517. }
  60518. }
  60519. else
  60520. {
  60521. if (keysPressed [note])
  60522. {
  60523. keysPressed.clearBit (note);
  60524. state.noteOff (midiChannel, note);
  60525. keyPressUsed = true;
  60526. }
  60527. }
  60528. }
  60529. return keyPressUsed;
  60530. }
  60531. void MidiKeyboardComponent::focusLost (FocusChangeType)
  60532. {
  60533. resetAnyKeysInUse();
  60534. }
  60535. END_JUCE_NAMESPACE
  60536. /*** End of inlined file: juce_MidiKeyboardComponent.cpp ***/
  60537. /*** Start of inlined file: juce_OpenGLComponent.cpp ***/
  60538. #if JUCE_OPENGL
  60539. BEGIN_JUCE_NAMESPACE
  60540. extern void juce_glViewport (const int w, const int h);
  60541. OpenGLPixelFormat::OpenGLPixelFormat (const int bitsPerRGBComponent,
  60542. const int alphaBits_,
  60543. const int depthBufferBits_,
  60544. const int stencilBufferBits_)
  60545. : redBits (bitsPerRGBComponent),
  60546. greenBits (bitsPerRGBComponent),
  60547. blueBits (bitsPerRGBComponent),
  60548. alphaBits (alphaBits_),
  60549. depthBufferBits (depthBufferBits_),
  60550. stencilBufferBits (stencilBufferBits_),
  60551. accumulationBufferRedBits (0),
  60552. accumulationBufferGreenBits (0),
  60553. accumulationBufferBlueBits (0),
  60554. accumulationBufferAlphaBits (0),
  60555. fullSceneAntiAliasingNumSamples (0)
  60556. {
  60557. }
  60558. OpenGLPixelFormat::OpenGLPixelFormat (const OpenGLPixelFormat& other)
  60559. : redBits (other.redBits),
  60560. greenBits (other.greenBits),
  60561. blueBits (other.blueBits),
  60562. alphaBits (other.alphaBits),
  60563. depthBufferBits (other.depthBufferBits),
  60564. stencilBufferBits (other.stencilBufferBits),
  60565. accumulationBufferRedBits (other.accumulationBufferRedBits),
  60566. accumulationBufferGreenBits (other.accumulationBufferGreenBits),
  60567. accumulationBufferBlueBits (other.accumulationBufferBlueBits),
  60568. accumulationBufferAlphaBits (other.accumulationBufferAlphaBits),
  60569. fullSceneAntiAliasingNumSamples (other.fullSceneAntiAliasingNumSamples)
  60570. {
  60571. }
  60572. OpenGLPixelFormat& OpenGLPixelFormat::operator= (const OpenGLPixelFormat& other)
  60573. {
  60574. redBits = other.redBits;
  60575. greenBits = other.greenBits;
  60576. blueBits = other.blueBits;
  60577. alphaBits = other.alphaBits;
  60578. depthBufferBits = other.depthBufferBits;
  60579. stencilBufferBits = other.stencilBufferBits;
  60580. accumulationBufferRedBits = other.accumulationBufferRedBits;
  60581. accumulationBufferGreenBits = other.accumulationBufferGreenBits;
  60582. accumulationBufferBlueBits = other.accumulationBufferBlueBits;
  60583. accumulationBufferAlphaBits = other.accumulationBufferAlphaBits;
  60584. fullSceneAntiAliasingNumSamples = other.fullSceneAntiAliasingNumSamples;
  60585. return *this;
  60586. }
  60587. bool OpenGLPixelFormat::operator== (const OpenGLPixelFormat& other) const
  60588. {
  60589. return redBits == other.redBits
  60590. && greenBits == other.greenBits
  60591. && blueBits == other.blueBits
  60592. && alphaBits == other.alphaBits
  60593. && depthBufferBits == other.depthBufferBits
  60594. && stencilBufferBits == other.stencilBufferBits
  60595. && accumulationBufferRedBits == other.accumulationBufferRedBits
  60596. && accumulationBufferGreenBits == other.accumulationBufferGreenBits
  60597. && accumulationBufferBlueBits == other.accumulationBufferBlueBits
  60598. && accumulationBufferAlphaBits == other.accumulationBufferAlphaBits
  60599. && fullSceneAntiAliasingNumSamples == other.fullSceneAntiAliasingNumSamples;
  60600. }
  60601. static VoidArray knownContexts;
  60602. OpenGLContext::OpenGLContext() throw()
  60603. {
  60604. knownContexts.add (this);
  60605. }
  60606. OpenGLContext::~OpenGLContext()
  60607. {
  60608. knownContexts.removeValue (this);
  60609. }
  60610. OpenGLContext* OpenGLContext::getCurrentContext()
  60611. {
  60612. for (int i = knownContexts.size(); --i >= 0;)
  60613. {
  60614. OpenGLContext* const oglc = (OpenGLContext*) knownContexts.getUnchecked(i);
  60615. if (oglc->isActive())
  60616. return oglc;
  60617. }
  60618. return 0;
  60619. }
  60620. class OpenGLComponent::OpenGLComponentWatcher : public ComponentMovementWatcher
  60621. {
  60622. public:
  60623. OpenGLComponentWatcher (OpenGLComponent* const owner_)
  60624. : ComponentMovementWatcher (owner_),
  60625. owner (owner_),
  60626. wasShowing (false)
  60627. {
  60628. }
  60629. ~OpenGLComponentWatcher() {}
  60630. void componentMovedOrResized (bool /*wasMoved*/, bool /*wasResized*/)
  60631. {
  60632. owner->updateContextPosition();
  60633. }
  60634. void componentPeerChanged()
  60635. {
  60636. const ScopedLock sl (owner->getContextLock());
  60637. owner->deleteContext();
  60638. }
  60639. void componentVisibilityChanged (Component&)
  60640. {
  60641. const bool isShowingNow = owner->isShowing();
  60642. if (wasShowing != isShowingNow)
  60643. {
  60644. wasShowing = isShowingNow;
  60645. owner->updateContextPosition();
  60646. }
  60647. }
  60648. juce_UseDebuggingNewOperator
  60649. private:
  60650. OpenGLComponent* const owner;
  60651. bool wasShowing;
  60652. };
  60653. OpenGLComponent::OpenGLComponent (const OpenGLType type_)
  60654. : type (type_),
  60655. contextToShareListsWith (0),
  60656. needToUpdateViewport (true)
  60657. {
  60658. setOpaque (true);
  60659. componentWatcher = new OpenGLComponentWatcher (this);
  60660. }
  60661. OpenGLComponent::~OpenGLComponent()
  60662. {
  60663. deleteContext();
  60664. componentWatcher = 0;
  60665. }
  60666. void OpenGLComponent::deleteContext()
  60667. {
  60668. const ScopedLock sl (contextLock);
  60669. context = 0;
  60670. }
  60671. void OpenGLComponent::updateContextPosition()
  60672. {
  60673. needToUpdateViewport = true;
  60674. if (getWidth() > 0 && getHeight() > 0)
  60675. {
  60676. Component* const topComp = getTopLevelComponent();
  60677. if (topComp->getPeer() != 0)
  60678. {
  60679. const ScopedLock sl (contextLock);
  60680. if (context != 0)
  60681. context->updateWindowPosition (getScreenX() - topComp->getScreenX(),
  60682. getScreenY() - topComp->getScreenY(),
  60683. getWidth(),
  60684. getHeight(),
  60685. topComp->getHeight());
  60686. }
  60687. }
  60688. }
  60689. const OpenGLPixelFormat OpenGLComponent::getPixelFormat() const
  60690. {
  60691. OpenGLPixelFormat pf;
  60692. const ScopedLock sl (contextLock);
  60693. if (context != 0)
  60694. pf = context->getPixelFormat();
  60695. return pf;
  60696. }
  60697. void OpenGLComponent::setPixelFormat (const OpenGLPixelFormat& formatToUse)
  60698. {
  60699. if (! (preferredPixelFormat == formatToUse))
  60700. {
  60701. const ScopedLock sl (contextLock);
  60702. deleteContext();
  60703. preferredPixelFormat = formatToUse;
  60704. }
  60705. }
  60706. void OpenGLComponent::shareWith (OpenGLContext* c)
  60707. {
  60708. if (contextToShareListsWith != c)
  60709. {
  60710. const ScopedLock sl (contextLock);
  60711. deleteContext();
  60712. contextToShareListsWith = c;
  60713. }
  60714. }
  60715. bool OpenGLComponent::makeCurrentContextActive()
  60716. {
  60717. if (context == 0)
  60718. {
  60719. const ScopedLock sl (contextLock);
  60720. if (isShowing() && getTopLevelComponent()->getPeer() != 0)
  60721. {
  60722. context = createContext();
  60723. if (context != 0)
  60724. {
  60725. updateContextPosition();
  60726. if (context->makeActive())
  60727. newOpenGLContextCreated();
  60728. }
  60729. }
  60730. }
  60731. return context != 0 && context->makeActive();
  60732. }
  60733. void OpenGLComponent::makeCurrentContextInactive()
  60734. {
  60735. if (context != 0)
  60736. context->makeInactive();
  60737. }
  60738. bool OpenGLComponent::isActiveContext() const throw()
  60739. {
  60740. return context != 0 && context->isActive();
  60741. }
  60742. void OpenGLComponent::swapBuffers()
  60743. {
  60744. if (context != 0)
  60745. context->swapBuffers();
  60746. }
  60747. void OpenGLComponent::paint (Graphics&)
  60748. {
  60749. if (renderAndSwapBuffers())
  60750. {
  60751. ComponentPeer* const peer = getPeer();
  60752. if (peer != 0)
  60753. {
  60754. const Point<int> topLeft (getScreenPosition() - peer->getScreenPosition());
  60755. peer->addMaskedRegion (topLeft.getX(), topLeft.getY(), getWidth(), getHeight());
  60756. }
  60757. }
  60758. }
  60759. bool OpenGLComponent::renderAndSwapBuffers()
  60760. {
  60761. const ScopedLock sl (contextLock);
  60762. if (! makeCurrentContextActive())
  60763. return false;
  60764. if (needToUpdateViewport)
  60765. {
  60766. needToUpdateViewport = false;
  60767. juce_glViewport (getWidth(), getHeight());
  60768. }
  60769. renderOpenGL();
  60770. swapBuffers();
  60771. return true;
  60772. }
  60773. void OpenGLComponent::internalRepaint (int x, int y, int w, int h)
  60774. {
  60775. Component::internalRepaint (x, y, w, h);
  60776. if (context != 0)
  60777. context->repaint();
  60778. }
  60779. END_JUCE_NAMESPACE
  60780. #endif
  60781. /*** End of inlined file: juce_OpenGLComponent.cpp ***/
  60782. /*** Start of inlined file: juce_PreferencesPanel.cpp ***/
  60783. BEGIN_JUCE_NAMESPACE
  60784. PreferencesPanel::PreferencesPanel()
  60785. : buttonSize (70)
  60786. {
  60787. }
  60788. PreferencesPanel::~PreferencesPanel()
  60789. {
  60790. currentPage = 0;
  60791. deleteAllChildren();
  60792. }
  60793. void PreferencesPanel::addSettingsPage (const String& title,
  60794. const Drawable* icon,
  60795. const Drawable* overIcon,
  60796. const Drawable* downIcon)
  60797. {
  60798. DrawableButton* button = new DrawableButton (title, DrawableButton::ImageAboveTextLabel);
  60799. button->setImages (icon, overIcon, downIcon);
  60800. button->setRadioGroupId (1);
  60801. button->addButtonListener (this);
  60802. button->setClickingTogglesState (true);
  60803. button->setWantsKeyboardFocus (false);
  60804. addAndMakeVisible (button);
  60805. resized();
  60806. if (currentPage == 0)
  60807. setCurrentPage (title);
  60808. }
  60809. void PreferencesPanel::addSettingsPage (const String& title,
  60810. const char* imageData,
  60811. const int imageDataSize)
  60812. {
  60813. DrawableImage icon, iconOver, iconDown;
  60814. icon.setImage (ImageCache::getFromMemory (imageData, imageDataSize), true);
  60815. iconOver.setImage (ImageCache::getFromMemory (imageData, imageDataSize), true);
  60816. iconOver.setOverlayColour (Colours::black.withAlpha (0.12f));
  60817. iconDown.setImage (ImageCache::getFromMemory (imageData, imageDataSize), true);
  60818. iconDown.setOverlayColour (Colours::black.withAlpha (0.25f));
  60819. addSettingsPage (title, &icon, &iconOver, &iconDown);
  60820. }
  60821. class PrefsDialogWindow : public DialogWindow
  60822. {
  60823. public:
  60824. PrefsDialogWindow (const String& dialogtitle,
  60825. const Colour& backgroundColour)
  60826. : DialogWindow (dialogtitle, backgroundColour, true)
  60827. {
  60828. }
  60829. ~PrefsDialogWindow()
  60830. {
  60831. }
  60832. void closeButtonPressed()
  60833. {
  60834. exitModalState (0);
  60835. }
  60836. private:
  60837. PrefsDialogWindow (const PrefsDialogWindow&);
  60838. PrefsDialogWindow& operator= (const PrefsDialogWindow&);
  60839. };
  60840. void PreferencesPanel::showInDialogBox (const String& dialogtitle,
  60841. int dialogWidth,
  60842. int dialogHeight,
  60843. const Colour& backgroundColour)
  60844. {
  60845. setSize (dialogWidth, dialogHeight);
  60846. PrefsDialogWindow dw (dialogtitle, backgroundColour);
  60847. dw.setContentComponent (this, true, true);
  60848. dw.centreAroundComponent (0, dw.getWidth(), dw.getHeight());
  60849. dw.runModalLoop();
  60850. dw.setContentComponent (0, false, false);
  60851. }
  60852. void PreferencesPanel::resized()
  60853. {
  60854. int x = 0;
  60855. for (int i = 0; i < getNumChildComponents(); ++i)
  60856. {
  60857. Component* c = getChildComponent (i);
  60858. if (dynamic_cast <DrawableButton*> (c) == 0)
  60859. {
  60860. c->setBounds (0, buttonSize + 5, getWidth(), getHeight() - buttonSize - 5);
  60861. }
  60862. else
  60863. {
  60864. c->setBounds (x, 0, buttonSize, buttonSize);
  60865. x += buttonSize;
  60866. }
  60867. }
  60868. }
  60869. void PreferencesPanel::paint (Graphics& g)
  60870. {
  60871. g.setColour (Colours::grey);
  60872. g.fillRect (0, buttonSize + 2, getWidth(), 1);
  60873. }
  60874. void PreferencesPanel::setCurrentPage (const String& pageName)
  60875. {
  60876. if (currentPageName != pageName)
  60877. {
  60878. currentPageName = pageName;
  60879. currentPage = 0;
  60880. currentPage = createComponentForPage (pageName);
  60881. if (currentPage != 0)
  60882. {
  60883. addAndMakeVisible (currentPage);
  60884. currentPage->toBack();
  60885. resized();
  60886. }
  60887. for (int i = 0; i < getNumChildComponents(); ++i)
  60888. {
  60889. DrawableButton* db = dynamic_cast <DrawableButton*> (getChildComponent (i));
  60890. if (db != 0 && db->getName() == pageName)
  60891. {
  60892. db->setToggleState (true, false);
  60893. break;
  60894. }
  60895. }
  60896. }
  60897. }
  60898. void PreferencesPanel::buttonClicked (Button*)
  60899. {
  60900. for (int i = 0; i < getNumChildComponents(); ++i)
  60901. {
  60902. DrawableButton* db = dynamic_cast <DrawableButton*> (getChildComponent (i));
  60903. if (db != 0 && db->getToggleState())
  60904. {
  60905. setCurrentPage (db->getName());
  60906. break;
  60907. }
  60908. }
  60909. }
  60910. END_JUCE_NAMESPACE
  60911. /*** End of inlined file: juce_PreferencesPanel.cpp ***/
  60912. /*** Start of inlined file: juce_SystemTrayIconComponent.cpp ***/
  60913. #if JUCE_WINDOWS || JUCE_LINUX
  60914. BEGIN_JUCE_NAMESPACE
  60915. SystemTrayIconComponent::SystemTrayIconComponent()
  60916. {
  60917. addToDesktop (0);
  60918. }
  60919. SystemTrayIconComponent::~SystemTrayIconComponent()
  60920. {
  60921. }
  60922. END_JUCE_NAMESPACE
  60923. #endif
  60924. /*** End of inlined file: juce_SystemTrayIconComponent.cpp ***/
  60925. /*** Start of inlined file: juce_AlertWindow.cpp ***/
  60926. BEGIN_JUCE_NAMESPACE
  60927. class AlertWindowTextEditor : public TextEditor
  60928. {
  60929. public:
  60930. AlertWindowTextEditor (const String& name, const bool isPasswordBox)
  60931. : TextEditor (name, isPasswordBox ? getDefaultPasswordChar() : 0)
  60932. {
  60933. setSelectAllWhenFocused (true);
  60934. }
  60935. ~AlertWindowTextEditor()
  60936. {
  60937. }
  60938. void returnPressed()
  60939. {
  60940. // pass these up the component hierarchy to be trigger the buttons
  60941. getParentComponent()->keyPressed (KeyPress (KeyPress::returnKey, 0, '\n'));
  60942. }
  60943. void escapePressed()
  60944. {
  60945. // pass these up the component hierarchy to be trigger the buttons
  60946. getParentComponent()->keyPressed (KeyPress (KeyPress::escapeKey, 0, 0));
  60947. }
  60948. private:
  60949. AlertWindowTextEditor (const AlertWindowTextEditor&);
  60950. AlertWindowTextEditor& operator= (const AlertWindowTextEditor&);
  60951. static juce_wchar getDefaultPasswordChar() throw()
  60952. {
  60953. #if JUCE_LINUX
  60954. return 0x2022;
  60955. #else
  60956. return 0x25cf;
  60957. #endif
  60958. }
  60959. };
  60960. AlertWindow::AlertWindow (const String& title,
  60961. const String& message,
  60962. AlertIconType iconType,
  60963. Component* associatedComponent_)
  60964. : TopLevelWindow (title, true),
  60965. alertIconType (iconType),
  60966. associatedComponent (associatedComponent_)
  60967. {
  60968. if (message.isEmpty())
  60969. text = " "; // to force an update if the message is empty
  60970. setMessage (message);
  60971. for (int i = Desktop::getInstance().getNumComponents(); --i >= 0;)
  60972. {
  60973. Component* const c = Desktop::getInstance().getComponent (i);
  60974. if (c != 0 && c->isAlwaysOnTop() && c->isShowing())
  60975. {
  60976. setAlwaysOnTop (true);
  60977. break;
  60978. }
  60979. }
  60980. if (JUCEApplication::getInstance() == 0)
  60981. setAlwaysOnTop (true); // for a plugin, make it always-on-top because the host windows are often top-level
  60982. lookAndFeelChanged();
  60983. constrainer.setMinimumOnscreenAmounts (0x10000, 0x10000, 0x10000, 0x10000);
  60984. }
  60985. AlertWindow::~AlertWindow()
  60986. {
  60987. for (int i = customComps.size(); --i >= 0;)
  60988. removeChildComponent ((Component*) customComps[i]);
  60989. deleteAllChildren();
  60990. }
  60991. void AlertWindow::userTriedToCloseWindow()
  60992. {
  60993. exitModalState (0);
  60994. }
  60995. void AlertWindow::setMessage (const String& message)
  60996. {
  60997. const String newMessage (message.substring (0, 2048));
  60998. if (text != newMessage)
  60999. {
  61000. text = newMessage;
  61001. font.setHeight (15.0f);
  61002. Font titleFont (font.getHeight() * 1.1f, Font::bold);
  61003. textLayout.setText (getName() + "\n\n", titleFont);
  61004. textLayout.appendText (text, font);
  61005. updateLayout (true);
  61006. repaint();
  61007. }
  61008. }
  61009. void AlertWindow::buttonClicked (Button* button)
  61010. {
  61011. for (int i = 0; i < buttons.size(); i++)
  61012. {
  61013. TextButton* const c = (TextButton*) buttons[i];
  61014. if (button->getName() == c->getName())
  61015. {
  61016. if (c->getParentComponent() != 0)
  61017. c->getParentComponent()->exitModalState (c->getCommandID());
  61018. break;
  61019. }
  61020. }
  61021. }
  61022. void AlertWindow::addButton (const String& name,
  61023. const int returnValue,
  61024. const KeyPress& shortcutKey1,
  61025. const KeyPress& shortcutKey2)
  61026. {
  61027. TextButton* const b = new TextButton (name, String::empty);
  61028. b->setWantsKeyboardFocus (true);
  61029. b->setMouseClickGrabsKeyboardFocus (false);
  61030. b->setCommandToTrigger (0, returnValue, false);
  61031. b->addShortcut (shortcutKey1);
  61032. b->addShortcut (shortcutKey2);
  61033. b->addButtonListener (this);
  61034. b->changeWidthToFitText (getLookAndFeel().getAlertWindowButtonHeight());
  61035. addAndMakeVisible (b, 0);
  61036. buttons.add (b);
  61037. updateLayout (false);
  61038. }
  61039. int AlertWindow::getNumButtons() const
  61040. {
  61041. return buttons.size();
  61042. }
  61043. void AlertWindow::addTextEditor (const String& name,
  61044. const String& initialContents,
  61045. const String& onScreenLabel,
  61046. const bool isPasswordBox)
  61047. {
  61048. AlertWindowTextEditor* const tc = new AlertWindowTextEditor (name, isPasswordBox);
  61049. tc->setColour (TextEditor::outlineColourId, findColour (ComboBox::outlineColourId));
  61050. tc->setFont (font);
  61051. tc->setText (initialContents);
  61052. tc->setCaretPosition (initialContents.length());
  61053. addAndMakeVisible (tc);
  61054. textBoxes.add (tc);
  61055. allComps.add (tc);
  61056. textboxNames.add (onScreenLabel);
  61057. updateLayout (false);
  61058. }
  61059. const String AlertWindow::getTextEditorContents (const String& nameOfTextEditor) const
  61060. {
  61061. for (int i = textBoxes.size(); --i >= 0;)
  61062. if (((TextEditor*)textBoxes[i])->getName() == nameOfTextEditor)
  61063. return ((TextEditor*)textBoxes[i])->getText();
  61064. return String::empty;
  61065. }
  61066. void AlertWindow::addComboBox (const String& name,
  61067. const StringArray& items,
  61068. const String& onScreenLabel)
  61069. {
  61070. ComboBox* const cb = new ComboBox (name);
  61071. for (int i = 0; i < items.size(); ++i)
  61072. cb->addItem (items[i], i + 1);
  61073. addAndMakeVisible (cb);
  61074. cb->setSelectedItemIndex (0);
  61075. comboBoxes.add (cb);
  61076. allComps.add (cb);
  61077. comboBoxNames.add (onScreenLabel);
  61078. updateLayout (false);
  61079. }
  61080. ComboBox* AlertWindow::getComboBoxComponent (const String& nameOfList) const
  61081. {
  61082. for (int i = comboBoxes.size(); --i >= 0;)
  61083. if (((ComboBox*) comboBoxes[i])->getName() == nameOfList)
  61084. return (ComboBox*) comboBoxes[i];
  61085. return 0;
  61086. }
  61087. class AlertTextComp : public TextEditor
  61088. {
  61089. public:
  61090. AlertTextComp (const String& message,
  61091. const Font& font)
  61092. {
  61093. setReadOnly (true);
  61094. setMultiLine (true, true);
  61095. setCaretVisible (false);
  61096. setScrollbarsShown (true);
  61097. lookAndFeelChanged();
  61098. setWantsKeyboardFocus (false);
  61099. setFont (font);
  61100. setText (message, false);
  61101. bestWidth = 2 * (int) sqrt (font.getHeight() * font.getStringWidth (message));
  61102. setColour (TextEditor::backgroundColourId, Colours::transparentBlack);
  61103. setColour (TextEditor::outlineColourId, Colours::transparentBlack);
  61104. setColour (TextEditor::shadowColourId, Colours::transparentBlack);
  61105. }
  61106. ~AlertTextComp()
  61107. {
  61108. }
  61109. int getPreferredWidth() const throw() { return bestWidth; }
  61110. void updateLayout (const int width)
  61111. {
  61112. TextLayout text;
  61113. text.appendText (getText(), getFont());
  61114. text.layout (width - 8, Justification::topLeft, true);
  61115. setSize (width, jmin (width, text.getHeight() + (int) getFont().getHeight()));
  61116. }
  61117. private:
  61118. int bestWidth;
  61119. AlertTextComp (const AlertTextComp&);
  61120. AlertTextComp& operator= (const AlertTextComp&);
  61121. };
  61122. void AlertWindow::addTextBlock (const String& text)
  61123. {
  61124. AlertTextComp* const c = new AlertTextComp (text, font);
  61125. textBlocks.add (c);
  61126. allComps.add (c);
  61127. addAndMakeVisible (c);
  61128. updateLayout (false);
  61129. }
  61130. void AlertWindow::addProgressBarComponent (double& progressValue)
  61131. {
  61132. ProgressBar* const pb = new ProgressBar (progressValue);
  61133. progressBars.add (pb);
  61134. allComps.add (pb);
  61135. addAndMakeVisible (pb);
  61136. updateLayout (false);
  61137. }
  61138. void AlertWindow::addCustomComponent (Component* const component)
  61139. {
  61140. customComps.add (component);
  61141. allComps.add (component);
  61142. addAndMakeVisible (component);
  61143. updateLayout (false);
  61144. }
  61145. int AlertWindow::getNumCustomComponents() const
  61146. {
  61147. return customComps.size();
  61148. }
  61149. Component* AlertWindow::getCustomComponent (const int index) const
  61150. {
  61151. return (Component*) customComps [index];
  61152. }
  61153. Component* AlertWindow::removeCustomComponent (const int index)
  61154. {
  61155. Component* const c = getCustomComponent (index);
  61156. if (c != 0)
  61157. {
  61158. customComps.removeValue (c);
  61159. allComps.removeValue (c);
  61160. removeChildComponent (c);
  61161. updateLayout (false);
  61162. }
  61163. return c;
  61164. }
  61165. void AlertWindow::paint (Graphics& g)
  61166. {
  61167. getLookAndFeel().drawAlertBox (g, *this, textArea, textLayout);
  61168. g.setColour (findColour (textColourId));
  61169. g.setFont (getLookAndFeel().getAlertWindowFont());
  61170. int i;
  61171. for (i = textBoxes.size(); --i >= 0;)
  61172. {
  61173. const TextEditor* const te = (TextEditor*) textBoxes[i];
  61174. g.drawFittedText (textboxNames[i],
  61175. te->getX(), te->getY() - 14,
  61176. te->getWidth(), 14,
  61177. Justification::centredLeft, 1);
  61178. }
  61179. for (i = comboBoxNames.size(); --i >= 0;)
  61180. {
  61181. const ComboBox* const cb = (ComboBox*) comboBoxes[i];
  61182. g.drawFittedText (comboBoxNames[i],
  61183. cb->getX(), cb->getY() - 14,
  61184. cb->getWidth(), 14,
  61185. Justification::centredLeft, 1);
  61186. }
  61187. for (i = customComps.size(); --i >= 0;)
  61188. {
  61189. const Component* const c = (Component*) customComps[i];
  61190. g.drawFittedText (c->getName(),
  61191. c->getX(), c->getY() - 14,
  61192. c->getWidth(), 14,
  61193. Justification::centredLeft, 1);
  61194. }
  61195. }
  61196. void AlertWindow::updateLayout (const bool onlyIncreaseSize)
  61197. {
  61198. const int titleH = 24;
  61199. const int iconWidth = 80;
  61200. const int wid = jmax (font.getStringWidth (text),
  61201. font.getStringWidth (getName()));
  61202. const int sw = (int) sqrt (font.getHeight() * wid);
  61203. int w = jmin (300 + sw * 2, (int) (getParentWidth() * 0.7f));
  61204. const int edgeGap = 10;
  61205. const int labelHeight = 18;
  61206. int iconSpace;
  61207. if (alertIconType == NoIcon)
  61208. {
  61209. textLayout.layout (w, Justification::horizontallyCentred, true);
  61210. iconSpace = 0;
  61211. }
  61212. else
  61213. {
  61214. textLayout.layout (w, Justification::left, true);
  61215. iconSpace = iconWidth;
  61216. }
  61217. w = jmax (350, textLayout.getWidth() + iconSpace + edgeGap * 4);
  61218. w = jmin (w, (int) (getParentWidth() * 0.7f));
  61219. const int textLayoutH = textLayout.getHeight();
  61220. const int textBottom = 16 + titleH + textLayoutH;
  61221. int h = textBottom;
  61222. int buttonW = 40;
  61223. int i;
  61224. for (i = 0; i < buttons.size(); ++i)
  61225. buttonW += 16 + ((const TextButton*) buttons[i])->getWidth();
  61226. w = jmax (buttonW, w);
  61227. h += (textBoxes.size() + comboBoxes.size() + progressBars.size()) * 50;
  61228. if (buttons.size() > 0)
  61229. h += 20 + ((TextButton*) buttons[0])->getHeight();
  61230. for (i = customComps.size(); --i >= 0;)
  61231. {
  61232. Component* c = (Component*) customComps[i];
  61233. w = jmax (w, (c->getWidth() * 100) / 80);
  61234. h += 10 + c->getHeight();
  61235. if (c->getName().isNotEmpty())
  61236. h += labelHeight;
  61237. }
  61238. for (i = textBlocks.size(); --i >= 0;)
  61239. {
  61240. const AlertTextComp* const ac = (AlertTextComp*) textBlocks[i];
  61241. w = jmax (w, ac->getPreferredWidth());
  61242. }
  61243. w = jmin (w, (int) (getParentWidth() * 0.7f));
  61244. for (i = textBlocks.size(); --i >= 0;)
  61245. {
  61246. AlertTextComp* const ac = (AlertTextComp*) textBlocks[i];
  61247. ac->updateLayout ((int) (w * 0.8f));
  61248. h += ac->getHeight() + 10;
  61249. }
  61250. h = jmin (getParentHeight() - 50, h);
  61251. if (onlyIncreaseSize)
  61252. {
  61253. w = jmax (w, getWidth());
  61254. h = jmax (h, getHeight());
  61255. }
  61256. if (! isVisible())
  61257. {
  61258. centreAroundComponent (associatedComponent, w, h);
  61259. }
  61260. else
  61261. {
  61262. const int cx = getX() + getWidth() / 2;
  61263. const int cy = getY() + getHeight() / 2;
  61264. setBounds (cx - w / 2,
  61265. cy - h / 2,
  61266. w, h);
  61267. }
  61268. textArea.setBounds (edgeGap, edgeGap, w - (edgeGap * 2), h - edgeGap);
  61269. const int spacer = 16;
  61270. int totalWidth = -spacer;
  61271. for (i = buttons.size(); --i >= 0;)
  61272. totalWidth += ((TextButton*) buttons[i])->getWidth() + spacer;
  61273. int x = (w - totalWidth) / 2;
  61274. int y = (int) (getHeight() * 0.95f);
  61275. for (i = 0; i < buttons.size(); ++i)
  61276. {
  61277. TextButton* const c = (TextButton*) buttons[i];
  61278. int ny = proportionOfHeight (0.95f) - c->getHeight();
  61279. c->setTopLeftPosition (x, ny);
  61280. if (ny < y)
  61281. y = ny;
  61282. x += c->getWidth() + spacer;
  61283. c->toFront (false);
  61284. }
  61285. y = textBottom;
  61286. for (i = 0; i < allComps.size(); ++i)
  61287. {
  61288. Component* const c = (Component*) allComps[i];
  61289. int h = 22;
  61290. const int comboIndex = comboBoxes.indexOf (c);
  61291. if (comboIndex >= 0 && comboBoxNames [comboIndex].isNotEmpty())
  61292. y += labelHeight;
  61293. const int tbIndex = textBoxes.indexOf (c);
  61294. if (tbIndex >= 0 && textboxNames[tbIndex].isNotEmpty())
  61295. y += labelHeight;
  61296. if (customComps.contains (c))
  61297. {
  61298. if (c->getName().isNotEmpty())
  61299. y += labelHeight;
  61300. c->setTopLeftPosition (proportionOfWidth (0.1f), y);
  61301. h = c->getHeight();
  61302. }
  61303. else if (textBlocks.contains (c))
  61304. {
  61305. c->setTopLeftPosition ((getWidth() - c->getWidth()) / 2, y);
  61306. h = c->getHeight();
  61307. }
  61308. else
  61309. {
  61310. c->setBounds (proportionOfWidth (0.1f), y, proportionOfWidth (0.8f), h);
  61311. }
  61312. y += h + 10;
  61313. }
  61314. setWantsKeyboardFocus (getNumChildComponents() == 0);
  61315. }
  61316. bool AlertWindow::containsAnyExtraComponents() const
  61317. {
  61318. return textBoxes.size()
  61319. + comboBoxes.size()
  61320. + progressBars.size()
  61321. + customComps.size() > 0;
  61322. }
  61323. void AlertWindow::mouseDown (const MouseEvent&)
  61324. {
  61325. dragger.startDraggingComponent (this, &constrainer);
  61326. }
  61327. void AlertWindow::mouseDrag (const MouseEvent& e)
  61328. {
  61329. dragger.dragComponent (this, e);
  61330. }
  61331. bool AlertWindow::keyPressed (const KeyPress& key)
  61332. {
  61333. for (int i = buttons.size(); --i >= 0;)
  61334. {
  61335. TextButton* const b = (TextButton*) buttons[i];
  61336. if (b->isRegisteredForShortcut (key))
  61337. {
  61338. b->triggerClick();
  61339. return true;
  61340. }
  61341. }
  61342. if (key.isKeyCode (KeyPress::escapeKey) && buttons.size() == 0)
  61343. {
  61344. exitModalState (0);
  61345. return true;
  61346. }
  61347. else if (key.isKeyCode (KeyPress::returnKey) && buttons.size() == 1)
  61348. {
  61349. ((TextButton*) buttons.getFirst())->triggerClick();
  61350. return true;
  61351. }
  61352. return false;
  61353. }
  61354. void AlertWindow::lookAndFeelChanged()
  61355. {
  61356. const int flags = getLookAndFeel().getAlertBoxWindowFlags();
  61357. setUsingNativeTitleBar ((flags & ComponentPeer::windowHasTitleBar) != 0);
  61358. setDropShadowEnabled (isOpaque() && (flags & ComponentPeer::windowHasDropShadow) != 0);
  61359. }
  61360. int AlertWindow::getDesktopWindowStyleFlags() const
  61361. {
  61362. return getLookAndFeel().getAlertBoxWindowFlags();
  61363. }
  61364. struct AlertWindowInfo
  61365. {
  61366. String title, message, button1, button2, button3;
  61367. AlertWindow::AlertIconType iconType;
  61368. int numButtons;
  61369. Component::SafePointer<Component> associatedComponent;
  61370. int run() const
  61371. {
  61372. return (int) (pointer_sized_int)
  61373. MessageManager::getInstance()->callFunctionOnMessageThread (showCallback, (void*) this);
  61374. }
  61375. private:
  61376. int show() const
  61377. {
  61378. LookAndFeel& lf = associatedComponent != 0 ? associatedComponent->getLookAndFeel()
  61379. : LookAndFeel::getDefaultLookAndFeel();
  61380. ScopedPointer <Component> alertBox (lf.createAlertWindow (title, message, button1, button2, button3,
  61381. iconType, numButtons, associatedComponent));
  61382. jassert (alertBox != 0); // you have to return one of these!
  61383. return alertBox->runModalLoop();
  61384. }
  61385. static void* showCallback (void* userData)
  61386. {
  61387. return (void*) (pointer_sized_int) ((const AlertWindowInfo*) userData)->show();
  61388. }
  61389. };
  61390. void AlertWindow::showMessageBox (AlertIconType iconType,
  61391. const String& title,
  61392. const String& message,
  61393. const String& buttonText,
  61394. Component* associatedComponent)
  61395. {
  61396. AlertWindowInfo info;
  61397. info.title = title;
  61398. info.message = message;
  61399. info.button1 = buttonText.isEmpty() ? TRANS("ok") : buttonText;
  61400. info.iconType = iconType;
  61401. info.numButtons = 1;
  61402. info.associatedComponent = associatedComponent;
  61403. info.run();
  61404. }
  61405. bool AlertWindow::showOkCancelBox (AlertIconType iconType,
  61406. const String& title,
  61407. const String& message,
  61408. const String& button1Text,
  61409. const String& button2Text,
  61410. Component* associatedComponent)
  61411. {
  61412. AlertWindowInfo info;
  61413. info.title = title;
  61414. info.message = message;
  61415. info.button1 = button1Text.isEmpty() ? TRANS("ok") : button1Text;
  61416. info.button2 = button2Text.isEmpty() ? TRANS("cancel") : button2Text;
  61417. info.iconType = iconType;
  61418. info.numButtons = 2;
  61419. info.associatedComponent = associatedComponent;
  61420. return info.run() != 0;
  61421. }
  61422. int AlertWindow::showYesNoCancelBox (AlertIconType iconType,
  61423. const String& title,
  61424. const String& message,
  61425. const String& button1Text,
  61426. const String& button2Text,
  61427. const String& button3Text,
  61428. Component* associatedComponent)
  61429. {
  61430. AlertWindowInfo info;
  61431. info.title = title;
  61432. info.message = message;
  61433. info.button1 = button1Text.isEmpty() ? TRANS("yes") : button1Text;
  61434. info.button2 = button2Text.isEmpty() ? TRANS("no") : button2Text;
  61435. info.button3 = button3Text.isEmpty() ? TRANS("cancel") : button3Text;
  61436. info.iconType = iconType;
  61437. info.numButtons = 3;
  61438. info.associatedComponent = associatedComponent;
  61439. return info.run();
  61440. }
  61441. END_JUCE_NAMESPACE
  61442. /*** End of inlined file: juce_AlertWindow.cpp ***/
  61443. /*** Start of inlined file: juce_ComponentPeer.cpp ***/
  61444. BEGIN_JUCE_NAMESPACE
  61445. //#define JUCE_ENABLE_REPAINT_DEBUGGING 1
  61446. static VoidArray heavyweightPeers;
  61447. ComponentPeer::ComponentPeer (Component* const component_, const int styleFlags_)
  61448. : component (component_),
  61449. styleFlags (styleFlags_),
  61450. lastPaintTime (0),
  61451. constrainer (0),
  61452. lastDragAndDropCompUnderMouse (0),
  61453. fakeMouseMessageSent (false),
  61454. isWindowMinimised (false)
  61455. {
  61456. heavyweightPeers.add (this);
  61457. }
  61458. ComponentPeer::~ComponentPeer()
  61459. {
  61460. heavyweightPeers.removeValue (this);
  61461. Desktop::getInstance().triggerFocusCallback();
  61462. }
  61463. int ComponentPeer::getNumPeers() throw()
  61464. {
  61465. return heavyweightPeers.size();
  61466. }
  61467. ComponentPeer* ComponentPeer::getPeer (const int index) throw()
  61468. {
  61469. return (ComponentPeer*) heavyweightPeers [index];
  61470. }
  61471. ComponentPeer* ComponentPeer::getPeerFor (const Component* const component) throw()
  61472. {
  61473. for (int i = heavyweightPeers.size(); --i >= 0;)
  61474. {
  61475. ComponentPeer* const peer = (ComponentPeer*) heavyweightPeers.getUnchecked(i);
  61476. if (peer->getComponent() == component)
  61477. return peer;
  61478. }
  61479. return 0;
  61480. }
  61481. bool ComponentPeer::isValidPeer (const ComponentPeer* const peer) throw()
  61482. {
  61483. return heavyweightPeers.contains (const_cast <ComponentPeer*> (peer));
  61484. }
  61485. void ComponentPeer::updateCurrentModifiers() throw()
  61486. {
  61487. ModifierKeys::updateCurrentModifiers();
  61488. }
  61489. void ComponentPeer::handleMouseEvent (const int touchIndex, const Point<int>& positionWithinPeer, const ModifierKeys& newMods, const int64 time)
  61490. {
  61491. MouseInputSource* const mouse = Desktop::getInstance().getMouseSource (touchIndex);
  61492. jassert (mouse != 0); // not enough sources!
  61493. mouse->handleEvent (this, positionWithinPeer, time, newMods);
  61494. }
  61495. void ComponentPeer::handleMouseWheel (const int touchIndex, const Point<int>& positionWithinPeer, const int64 time, const float x, const float y)
  61496. {
  61497. MouseInputSource* const mouse = Desktop::getInstance().getMouseSource (touchIndex);
  61498. jassert (mouse != 0); // not enough sources!
  61499. mouse->handleWheel (this, positionWithinPeer, time, x, y);
  61500. }
  61501. void ComponentPeer::handlePaint (LowLevelGraphicsContext& contextToPaintTo)
  61502. {
  61503. Graphics g (&contextToPaintTo);
  61504. #if JUCE_ENABLE_REPAINT_DEBUGGING
  61505. g.saveState();
  61506. #endif
  61507. JUCE_TRY
  61508. {
  61509. component->paintEntireComponent (g);
  61510. }
  61511. JUCE_CATCH_EXCEPTION
  61512. #if JUCE_ENABLE_REPAINT_DEBUGGING
  61513. // enabling this code will fill all areas that get repainted with a colour overlay, to show
  61514. // clearly when things are being repainted.
  61515. {
  61516. g.restoreState();
  61517. g.fillAll (Colour ((uint8) Random::getSystemRandom().nextInt (255),
  61518. (uint8) Random::getSystemRandom().nextInt (255),
  61519. (uint8) Random::getSystemRandom().nextInt (255),
  61520. (uint8) 0x50));
  61521. }
  61522. #endif
  61523. }
  61524. bool ComponentPeer::handleKeyPress (const int keyCode,
  61525. const juce_wchar textCharacter)
  61526. {
  61527. updateCurrentModifiers();
  61528. Component* target = Component::getCurrentlyFocusedComponent() != 0
  61529. ? Component::getCurrentlyFocusedComponent()
  61530. : component;
  61531. if (target->isCurrentlyBlockedByAnotherModalComponent())
  61532. {
  61533. Component* const currentModalComp = Component::getCurrentlyModalComponent();
  61534. if (currentModalComp != 0)
  61535. target = currentModalComp;
  61536. }
  61537. const KeyPress keyInfo (keyCode,
  61538. ModifierKeys::getCurrentModifiers().getRawFlags()
  61539. & ModifierKeys::allKeyboardModifiers,
  61540. textCharacter);
  61541. bool keyWasUsed = false;
  61542. while (target != 0)
  61543. {
  61544. const Component::SafePointer<Component> deletionChecker (target);
  61545. if (target->keyListeners_ != 0)
  61546. {
  61547. for (int i = target->keyListeners_->size(); --i >= 0;)
  61548. {
  61549. keyWasUsed = ((KeyListener*) target->keyListeners_->getUnchecked(i))->keyPressed (keyInfo, target);
  61550. if (keyWasUsed || deletionChecker == 0)
  61551. return keyWasUsed;
  61552. i = jmin (i, target->keyListeners_->size());
  61553. }
  61554. }
  61555. keyWasUsed = target->keyPressed (keyInfo);
  61556. if (keyWasUsed || deletionChecker == 0)
  61557. break;
  61558. if (keyInfo.isKeyCode (KeyPress::tabKey) && Component::getCurrentlyFocusedComponent() != 0)
  61559. {
  61560. Component* const currentlyFocused = Component::getCurrentlyFocusedComponent();
  61561. currentlyFocused->moveKeyboardFocusToSibling (! keyInfo.getModifiers().isShiftDown());
  61562. keyWasUsed = (currentlyFocused != Component::getCurrentlyFocusedComponent());
  61563. break;
  61564. }
  61565. target = target->parentComponent_;
  61566. }
  61567. return keyWasUsed;
  61568. }
  61569. bool ComponentPeer::handleKeyUpOrDown (const bool isKeyDown)
  61570. {
  61571. updateCurrentModifiers();
  61572. Component* target = Component::getCurrentlyFocusedComponent() != 0
  61573. ? Component::getCurrentlyFocusedComponent()
  61574. : component;
  61575. if (target->isCurrentlyBlockedByAnotherModalComponent())
  61576. {
  61577. Component* const currentModalComp = Component::getCurrentlyModalComponent();
  61578. if (currentModalComp != 0)
  61579. target = currentModalComp;
  61580. }
  61581. bool keyWasUsed = false;
  61582. while (target != 0)
  61583. {
  61584. const Component::SafePointer<Component> deletionChecker (target);
  61585. keyWasUsed = target->keyStateChanged (isKeyDown);
  61586. if (keyWasUsed || deletionChecker == 0)
  61587. break;
  61588. if (target->keyListeners_ != 0)
  61589. {
  61590. for (int i = target->keyListeners_->size(); --i >= 0;)
  61591. {
  61592. keyWasUsed = ((KeyListener*) target->keyListeners_->getUnchecked(i))->keyStateChanged (isKeyDown, target);
  61593. if (keyWasUsed || deletionChecker == 0)
  61594. return keyWasUsed;
  61595. i = jmin (i, target->keyListeners_->size());
  61596. }
  61597. }
  61598. target = target->parentComponent_;
  61599. }
  61600. return keyWasUsed;
  61601. }
  61602. void ComponentPeer::handleModifierKeysChange()
  61603. {
  61604. updateCurrentModifiers();
  61605. Component* target = Desktop::getInstance().getMainMouseSource().getComponentUnderMouse();
  61606. if (target == 0)
  61607. target = Component::getCurrentlyFocusedComponent();
  61608. if (target == 0)
  61609. target = component;
  61610. if (target != 0)
  61611. target->internalModifierKeysChanged();
  61612. }
  61613. TextInputTarget* ComponentPeer::findCurrentTextInputTarget()
  61614. {
  61615. Component* const c = Component::getCurrentlyFocusedComponent();
  61616. if (component->isParentOf (c))
  61617. {
  61618. TextInputTarget* const ti = dynamic_cast <TextInputTarget*> (c);
  61619. if (ti != 0 && ti->isTextInputActive())
  61620. return ti;
  61621. }
  61622. return 0;
  61623. }
  61624. void ComponentPeer::handleBroughtToFront()
  61625. {
  61626. updateCurrentModifiers();
  61627. if (component != 0)
  61628. component->internalBroughtToFront();
  61629. }
  61630. void ComponentPeer::setConstrainer (ComponentBoundsConstrainer* const newConstrainer) throw()
  61631. {
  61632. constrainer = newConstrainer;
  61633. }
  61634. void ComponentPeer::handleMovedOrResized()
  61635. {
  61636. jassert (component->isValidComponent());
  61637. updateCurrentModifiers();
  61638. const bool nowMinimised = isMinimised();
  61639. if (component->flags.hasHeavyweightPeerFlag && ! nowMinimised)
  61640. {
  61641. const Component::SafePointer<Component> deletionChecker (component);
  61642. const Rectangle<int> newBounds (getBounds());
  61643. const bool wasMoved = (component->getPosition() != newBounds.getPosition());
  61644. const bool wasResized = (component->getWidth() != newBounds.getWidth() || component->getHeight() != newBounds.getHeight());
  61645. if (wasMoved || wasResized)
  61646. {
  61647. component->bounds_ = newBounds;
  61648. if (wasResized)
  61649. component->repaint();
  61650. component->sendMovedResizedMessages (wasMoved, wasResized);
  61651. if (deletionChecker == 0)
  61652. return;
  61653. }
  61654. }
  61655. if (isWindowMinimised != nowMinimised)
  61656. {
  61657. isWindowMinimised = nowMinimised;
  61658. component->minimisationStateChanged (nowMinimised);
  61659. component->sendVisibilityChangeMessage();
  61660. }
  61661. if (! isFullScreen())
  61662. lastNonFullscreenBounds = component->getBounds();
  61663. }
  61664. void ComponentPeer::handleFocusGain()
  61665. {
  61666. updateCurrentModifiers();
  61667. if (component->isParentOf (lastFocusedComponent))
  61668. {
  61669. Component::currentlyFocusedComponent = lastFocusedComponent;
  61670. Desktop::getInstance().triggerFocusCallback();
  61671. lastFocusedComponent->internalFocusGain (Component::focusChangedDirectly);
  61672. }
  61673. else
  61674. {
  61675. if (! component->isCurrentlyBlockedByAnotherModalComponent())
  61676. component->grabKeyboardFocus();
  61677. else
  61678. Component::bringModalComponentToFront();
  61679. }
  61680. }
  61681. void ComponentPeer::handleFocusLoss()
  61682. {
  61683. updateCurrentModifiers();
  61684. if (component->hasKeyboardFocus (true))
  61685. {
  61686. lastFocusedComponent = Component::currentlyFocusedComponent;
  61687. if (lastFocusedComponent != 0)
  61688. {
  61689. Component::currentlyFocusedComponent = 0;
  61690. Desktop::getInstance().triggerFocusCallback();
  61691. lastFocusedComponent->internalFocusLoss (Component::focusChangedByMouseClick);
  61692. }
  61693. }
  61694. }
  61695. Component* ComponentPeer::getLastFocusedSubcomponent() const throw()
  61696. {
  61697. return (component->isParentOf (lastFocusedComponent) && lastFocusedComponent->isShowing())
  61698. ? static_cast <Component*> (lastFocusedComponent)
  61699. : component;
  61700. }
  61701. void ComponentPeer::handleScreenSizeChange()
  61702. {
  61703. updateCurrentModifiers();
  61704. component->parentSizeChanged();
  61705. handleMovedOrResized();
  61706. }
  61707. void ComponentPeer::setNonFullScreenBounds (const Rectangle<int>& newBounds) throw()
  61708. {
  61709. lastNonFullscreenBounds = newBounds;
  61710. }
  61711. const Rectangle<int>& ComponentPeer::getNonFullScreenBounds() const throw()
  61712. {
  61713. return lastNonFullscreenBounds;
  61714. }
  61715. static FileDragAndDropTarget* findDragAndDropTarget (Component* c,
  61716. const StringArray& files,
  61717. FileDragAndDropTarget* const lastOne)
  61718. {
  61719. while (c != 0)
  61720. {
  61721. FileDragAndDropTarget* const t = dynamic_cast <FileDragAndDropTarget*> (c);
  61722. if (t != 0 && (t == lastOne || t->isInterestedInFileDrag (files)))
  61723. return t;
  61724. c = c->getParentComponent();
  61725. }
  61726. return 0;
  61727. }
  61728. void ComponentPeer::handleFileDragMove (const StringArray& files, const Point<int>& position)
  61729. {
  61730. updateCurrentModifiers();
  61731. FileDragAndDropTarget* lastTarget
  61732. = dynamic_cast<FileDragAndDropTarget*> (static_cast<Component*> (dragAndDropTargetComponent));
  61733. FileDragAndDropTarget* newTarget = 0;
  61734. Component* const compUnderMouse = component->getComponentAt (position);
  61735. if (compUnderMouse != lastDragAndDropCompUnderMouse)
  61736. {
  61737. lastDragAndDropCompUnderMouse = compUnderMouse;
  61738. newTarget = findDragAndDropTarget (compUnderMouse, files, lastTarget);
  61739. if (newTarget != lastTarget)
  61740. {
  61741. if (lastTarget != 0)
  61742. lastTarget->fileDragExit (files);
  61743. dragAndDropTargetComponent = 0;
  61744. if (newTarget != 0)
  61745. {
  61746. dragAndDropTargetComponent = dynamic_cast <Component*> (newTarget);
  61747. const Point<int> pos (component->relativePositionToOtherComponent (dragAndDropTargetComponent, position));
  61748. newTarget->fileDragEnter (files, pos.getX(), pos.getY());
  61749. }
  61750. }
  61751. }
  61752. else
  61753. {
  61754. newTarget = lastTarget;
  61755. }
  61756. if (newTarget != 0)
  61757. {
  61758. Component* const targetComp = dynamic_cast <Component*> (newTarget);
  61759. const Point<int> pos (component->relativePositionToOtherComponent (targetComp, position));
  61760. newTarget->fileDragMove (files, pos.getX(), pos.getY());
  61761. }
  61762. }
  61763. void ComponentPeer::handleFileDragExit (const StringArray& files)
  61764. {
  61765. handleFileDragMove (files, Point<int> (-1, -1));
  61766. jassert (dragAndDropTargetComponent == 0);
  61767. lastDragAndDropCompUnderMouse = 0;
  61768. }
  61769. void ComponentPeer::handleFileDragDrop (const StringArray& files, const Point<int>& position)
  61770. {
  61771. handleFileDragMove (files, position);
  61772. if (dragAndDropTargetComponent != 0)
  61773. {
  61774. FileDragAndDropTarget* const target
  61775. = dynamic_cast<FileDragAndDropTarget*> (static_cast<Component*> (dragAndDropTargetComponent));
  61776. dragAndDropTargetComponent = 0;
  61777. lastDragAndDropCompUnderMouse = 0;
  61778. if (target != 0)
  61779. {
  61780. Component* const targetComp = dynamic_cast <Component*> (target);
  61781. if (targetComp->isCurrentlyBlockedByAnotherModalComponent())
  61782. {
  61783. targetComp->internalModalInputAttempt();
  61784. if (targetComp->isCurrentlyBlockedByAnotherModalComponent())
  61785. return;
  61786. }
  61787. const Point<int> pos (component->relativePositionToOtherComponent (targetComp, position));
  61788. target->filesDropped (files, pos.getX(), pos.getY());
  61789. }
  61790. }
  61791. }
  61792. void ComponentPeer::handleUserClosingWindow()
  61793. {
  61794. updateCurrentModifiers();
  61795. component->userTriedToCloseWindow();
  61796. }
  61797. void ComponentPeer::bringModalComponentToFront()
  61798. {
  61799. Component::bringModalComponentToFront();
  61800. }
  61801. void ComponentPeer::clearMaskedRegion()
  61802. {
  61803. maskedRegion.clear();
  61804. }
  61805. void ComponentPeer::addMaskedRegion (int x, int y, int w, int h)
  61806. {
  61807. maskedRegion.add (x, y, w, h);
  61808. }
  61809. const StringArray ComponentPeer::getAvailableRenderingEngines() throw()
  61810. {
  61811. StringArray s;
  61812. s.add ("Software Renderer");
  61813. return s;
  61814. }
  61815. int ComponentPeer::getCurrentRenderingEngine() throw()
  61816. {
  61817. return 0;
  61818. }
  61819. void ComponentPeer::setCurrentRenderingEngine (int /*index*/) throw()
  61820. {
  61821. }
  61822. END_JUCE_NAMESPACE
  61823. /*** End of inlined file: juce_ComponentPeer.cpp ***/
  61824. /*** Start of inlined file: juce_DialogWindow.cpp ***/
  61825. BEGIN_JUCE_NAMESPACE
  61826. DialogWindow::DialogWindow (const String& name,
  61827. const Colour& backgroundColour_,
  61828. const bool escapeKeyTriggersCloseButton_,
  61829. const bool addToDesktop_)
  61830. : DocumentWindow (name, backgroundColour_, DocumentWindow::closeButton, addToDesktop_),
  61831. escapeKeyTriggersCloseButton (escapeKeyTriggersCloseButton_)
  61832. {
  61833. }
  61834. DialogWindow::~DialogWindow()
  61835. {
  61836. }
  61837. void DialogWindow::resized()
  61838. {
  61839. DocumentWindow::resized();
  61840. const KeyPress esc (KeyPress::escapeKey, 0, 0);
  61841. if (escapeKeyTriggersCloseButton
  61842. && getCloseButton() != 0
  61843. && ! getCloseButton()->isRegisteredForShortcut (esc))
  61844. {
  61845. getCloseButton()->addShortcut (esc);
  61846. }
  61847. }
  61848. class TempDialogWindow : public DialogWindow
  61849. {
  61850. public:
  61851. TempDialogWindow (const String& title, const Colour& colour, const bool escapeCloses)
  61852. : DialogWindow (title, colour, escapeCloses, true)
  61853. {
  61854. }
  61855. ~TempDialogWindow()
  61856. {
  61857. }
  61858. void closeButtonPressed()
  61859. {
  61860. setVisible (false);
  61861. }
  61862. private:
  61863. TempDialogWindow (const TempDialogWindow&);
  61864. TempDialogWindow& operator= (const TempDialogWindow&);
  61865. };
  61866. int DialogWindow::showModalDialog (const String& dialogTitle,
  61867. Component* contentComponent,
  61868. Component* componentToCentreAround,
  61869. const Colour& colour,
  61870. const bool escapeKeyTriggersCloseButton,
  61871. const bool shouldBeResizable,
  61872. const bool useBottomRightCornerResizer)
  61873. {
  61874. TempDialogWindow dw (dialogTitle, colour, escapeKeyTriggersCloseButton);
  61875. dw.setContentComponent (contentComponent, true, true);
  61876. dw.centreAroundComponent (componentToCentreAround, dw.getWidth(), dw.getHeight());
  61877. dw.setResizable (shouldBeResizable, useBottomRightCornerResizer);
  61878. const int result = dw.runModalLoop();
  61879. dw.setContentComponent (0, false);
  61880. return result;
  61881. }
  61882. END_JUCE_NAMESPACE
  61883. /*** End of inlined file: juce_DialogWindow.cpp ***/
  61884. /*** Start of inlined file: juce_DocumentWindow.cpp ***/
  61885. BEGIN_JUCE_NAMESPACE
  61886. class DocumentWindow::ButtonListenerProxy : public ButtonListener
  61887. {
  61888. public:
  61889. ButtonListenerProxy (DocumentWindow& owner_)
  61890. : owner (owner_)
  61891. {
  61892. }
  61893. void buttonClicked (Button* button)
  61894. {
  61895. if (button == owner.getMinimiseButton())
  61896. owner.minimiseButtonPressed();
  61897. else if (button == owner.getMaximiseButton())
  61898. owner.maximiseButtonPressed();
  61899. else if (button == owner.getCloseButton())
  61900. owner.closeButtonPressed();
  61901. }
  61902. juce_UseDebuggingNewOperator
  61903. private:
  61904. DocumentWindow& owner;
  61905. ButtonListenerProxy (const ButtonListenerProxy&);
  61906. ButtonListenerProxy& operator= (const ButtonListenerProxy&);
  61907. };
  61908. DocumentWindow::DocumentWindow (const String& title,
  61909. const Colour& backgroundColour,
  61910. const int requiredButtons_,
  61911. const bool addToDesktop_)
  61912. : ResizableWindow (title, backgroundColour, addToDesktop_),
  61913. titleBarHeight (26),
  61914. menuBarHeight (24),
  61915. requiredButtons (requiredButtons_),
  61916. #if JUCE_MAC
  61917. positionTitleBarButtonsOnLeft (true),
  61918. #else
  61919. positionTitleBarButtonsOnLeft (false),
  61920. #endif
  61921. drawTitleTextCentred (true),
  61922. menuBarModel (0)
  61923. {
  61924. setResizeLimits (128, 128, 32768, 32768);
  61925. lookAndFeelChanged();
  61926. }
  61927. DocumentWindow::~DocumentWindow()
  61928. {
  61929. for (int i = numElementsInArray (titleBarButtons); --i >= 0;)
  61930. titleBarButtons[i] = 0;
  61931. menuBar = 0;
  61932. }
  61933. void DocumentWindow::repaintTitleBar()
  61934. {
  61935. const Rectangle<int> titleBarArea (getTitleBarArea());
  61936. repaint (titleBarArea.getX(), titleBarArea.getY(),
  61937. titleBarArea.getWidth(), titleBarArea.getHeight());
  61938. }
  61939. void DocumentWindow::setName (const String& newName)
  61940. {
  61941. if (newName != getName())
  61942. {
  61943. Component::setName (newName);
  61944. repaintTitleBar();
  61945. }
  61946. }
  61947. void DocumentWindow::setIcon (const Image* imageToUse)
  61948. {
  61949. titleBarIcon = imageToUse != 0 ? imageToUse->createCopy() : 0;
  61950. repaintTitleBar();
  61951. }
  61952. void DocumentWindow::setTitleBarHeight (const int newHeight)
  61953. {
  61954. titleBarHeight = newHeight;
  61955. resized();
  61956. repaintTitleBar();
  61957. }
  61958. void DocumentWindow::setTitleBarButtonsRequired (const int requiredButtons_,
  61959. const bool positionTitleBarButtonsOnLeft_)
  61960. {
  61961. requiredButtons = requiredButtons_;
  61962. positionTitleBarButtonsOnLeft = positionTitleBarButtonsOnLeft_;
  61963. lookAndFeelChanged();
  61964. }
  61965. void DocumentWindow::setTitleBarTextCentred (const bool textShouldBeCentred)
  61966. {
  61967. drawTitleTextCentred = textShouldBeCentred;
  61968. repaintTitleBar();
  61969. }
  61970. void DocumentWindow::setMenuBar (MenuBarModel* menuBarModel_,
  61971. const int menuBarHeight_)
  61972. {
  61973. if (menuBarModel != menuBarModel_)
  61974. {
  61975. menuBar = 0;
  61976. menuBarModel = menuBarModel_;
  61977. menuBarHeight = (menuBarHeight_ > 0) ? menuBarHeight_
  61978. : getLookAndFeel().getDefaultMenuBarHeight();
  61979. if (menuBarModel != 0)
  61980. {
  61981. // (call the Component method directly to avoid the assertion in ResizableWindow)
  61982. Component::addAndMakeVisible (menuBar = new MenuBarComponent (menuBarModel));
  61983. menuBar->setEnabled (isActiveWindow());
  61984. }
  61985. resized();
  61986. }
  61987. }
  61988. void DocumentWindow::closeButtonPressed()
  61989. {
  61990. /* If you've got a close button, you have to override this method to get
  61991. rid of your window!
  61992. If the window is just a pop-up, you should override this method and make
  61993. it delete the window in whatever way is appropriate for your app. E.g. you
  61994. might just want to call "delete this".
  61995. If your app is centred around this window such that the whole app should quit when
  61996. the window is closed, then you will probably want to use this method as an opportunity
  61997. to call JUCEApplication::quit(), and leave the window to be deleted later by your
  61998. JUCEApplication::shutdown() method. (Doing it this way means that your window will
  61999. still get cleaned-up if the app is quit by some other means (e.g. a cmd-Q on the mac
  62000. or closing it via the taskbar icon on Windows).
  62001. */
  62002. jassertfalse
  62003. }
  62004. void DocumentWindow::minimiseButtonPressed()
  62005. {
  62006. setMinimised (true);
  62007. }
  62008. void DocumentWindow::maximiseButtonPressed()
  62009. {
  62010. setFullScreen (! isFullScreen());
  62011. }
  62012. void DocumentWindow::paint (Graphics& g)
  62013. {
  62014. ResizableWindow::paint (g);
  62015. if (resizableBorder == 0)
  62016. {
  62017. g.setColour (getBackgroundColour().overlaidWith (Colour (0x80000000)));
  62018. const BorderSize border (getBorderThickness());
  62019. g.fillRect (0, 0, getWidth(), border.getTop());
  62020. g.fillRect (0, border.getTop(), border.getLeft(), getHeight() - border.getTopAndBottom());
  62021. g.fillRect (getWidth() - border.getRight(), border.getTop(), border.getRight(), getHeight() - border.getTopAndBottom());
  62022. g.fillRect (0, getHeight() - border.getBottom(), getWidth(), border.getBottom());
  62023. }
  62024. const Rectangle<int> titleBarArea (getTitleBarArea());
  62025. g.setOrigin (titleBarArea.getX(), titleBarArea.getY());
  62026. g.reduceClipRegion (0, 0, titleBarArea.getWidth(), titleBarArea.getHeight());
  62027. int titleSpaceX1 = 6;
  62028. int titleSpaceX2 = titleBarArea.getWidth() - 6;
  62029. for (int i = 0; i < 3; ++i)
  62030. {
  62031. if (titleBarButtons[i] != 0)
  62032. {
  62033. if (positionTitleBarButtonsOnLeft)
  62034. titleSpaceX1 = jmax (titleSpaceX1, titleBarButtons[i]->getRight() + (getWidth() - titleBarButtons[i]->getRight()) / 8);
  62035. else
  62036. titleSpaceX2 = jmin (titleSpaceX2, titleBarButtons[i]->getX() - (titleBarButtons[i]->getX() / 8));
  62037. }
  62038. }
  62039. getLookAndFeel().drawDocumentWindowTitleBar (*this, g,
  62040. titleBarArea.getWidth(),
  62041. titleBarArea.getHeight(),
  62042. titleSpaceX1,
  62043. jmax (1, titleSpaceX2 - titleSpaceX1),
  62044. titleBarIcon,
  62045. ! drawTitleTextCentred);
  62046. }
  62047. void DocumentWindow::resized()
  62048. {
  62049. ResizableWindow::resized();
  62050. if (titleBarButtons[1] != 0)
  62051. titleBarButtons[1]->setToggleState (isFullScreen(), false);
  62052. const Rectangle<int> titleBarArea (getTitleBarArea());
  62053. getLookAndFeel()
  62054. .positionDocumentWindowButtons (*this,
  62055. titleBarArea.getX(), titleBarArea.getY(),
  62056. titleBarArea.getWidth(), titleBarArea.getHeight(),
  62057. titleBarButtons[0],
  62058. titleBarButtons[1],
  62059. titleBarButtons[2],
  62060. positionTitleBarButtonsOnLeft);
  62061. if (menuBar != 0)
  62062. menuBar->setBounds (titleBarArea.getX(), titleBarArea.getBottom(),
  62063. titleBarArea.getWidth(), menuBarHeight);
  62064. }
  62065. const BorderSize DocumentWindow::getBorderThickness()
  62066. {
  62067. return BorderSize ((isFullScreen() || isUsingNativeTitleBar())
  62068. ? 0 : (resizableBorder != 0 ? 4 : 1));
  62069. }
  62070. const BorderSize DocumentWindow::getContentComponentBorder()
  62071. {
  62072. BorderSize border (getBorderThickness());
  62073. border.setTop (border.getTop()
  62074. + (isUsingNativeTitleBar() ? 0 : titleBarHeight)
  62075. + (menuBar != 0 ? menuBarHeight : 0));
  62076. return border;
  62077. }
  62078. int DocumentWindow::getTitleBarHeight() const
  62079. {
  62080. return isUsingNativeTitleBar() ? 0 : jmin (titleBarHeight, getHeight() - 4);
  62081. }
  62082. const Rectangle<int> DocumentWindow::getTitleBarArea()
  62083. {
  62084. const BorderSize border (getBorderThickness());
  62085. return Rectangle<int> (border.getLeft(), border.getTop(),
  62086. getWidth() - border.getLeftAndRight(),
  62087. getTitleBarHeight());
  62088. }
  62089. Button* DocumentWindow::getCloseButton() const throw()
  62090. {
  62091. return titleBarButtons[2];
  62092. }
  62093. Button* DocumentWindow::getMinimiseButton() const throw()
  62094. {
  62095. return titleBarButtons[0];
  62096. }
  62097. Button* DocumentWindow::getMaximiseButton() const throw()
  62098. {
  62099. return titleBarButtons[1];
  62100. }
  62101. int DocumentWindow::getDesktopWindowStyleFlags() const
  62102. {
  62103. int flags = ResizableWindow::getDesktopWindowStyleFlags();
  62104. if ((requiredButtons & minimiseButton) != 0)
  62105. flags |= ComponentPeer::windowHasMinimiseButton;
  62106. if ((requiredButtons & maximiseButton) != 0)
  62107. flags |= ComponentPeer::windowHasMaximiseButton;
  62108. if ((requiredButtons & closeButton) != 0)
  62109. flags |= ComponentPeer::windowHasCloseButton;
  62110. return flags;
  62111. }
  62112. void DocumentWindow::lookAndFeelChanged()
  62113. {
  62114. int i;
  62115. for (i = numElementsInArray (titleBarButtons); --i >= 0;)
  62116. titleBarButtons[i] = 0;
  62117. if (! isUsingNativeTitleBar())
  62118. {
  62119. titleBarButtons[0] = ((requiredButtons & minimiseButton) != 0)
  62120. ? getLookAndFeel().createDocumentWindowButton (minimiseButton) : 0;
  62121. titleBarButtons[1] = ((requiredButtons & maximiseButton) != 0)
  62122. ? getLookAndFeel().createDocumentWindowButton (maximiseButton) : 0;
  62123. titleBarButtons[2] = ((requiredButtons & closeButton) != 0)
  62124. ? getLookAndFeel().createDocumentWindowButton (closeButton) : 0;
  62125. for (i = 0; i < 3; ++i)
  62126. {
  62127. if (titleBarButtons[i] != 0)
  62128. {
  62129. if (buttonListener == 0)
  62130. buttonListener = new ButtonListenerProxy (*this);
  62131. titleBarButtons[i]->addButtonListener (buttonListener);
  62132. titleBarButtons[i]->setWantsKeyboardFocus (false);
  62133. // (call the Component method directly to avoid the assertion in ResizableWindow)
  62134. Component::addAndMakeVisible (titleBarButtons[i]);
  62135. }
  62136. }
  62137. if (getCloseButton() != 0)
  62138. {
  62139. #if JUCE_MAC
  62140. getCloseButton()->addShortcut (KeyPress ('w', ModifierKeys::commandModifier, 0));
  62141. #else
  62142. getCloseButton()->addShortcut (KeyPress (KeyPress::F4Key, ModifierKeys::altModifier, 0));
  62143. #endif
  62144. }
  62145. }
  62146. activeWindowStatusChanged();
  62147. ResizableWindow::lookAndFeelChanged();
  62148. }
  62149. void DocumentWindow::parentHierarchyChanged()
  62150. {
  62151. lookAndFeelChanged();
  62152. }
  62153. void DocumentWindow::activeWindowStatusChanged()
  62154. {
  62155. ResizableWindow::activeWindowStatusChanged();
  62156. for (int i = numElementsInArray (titleBarButtons); --i >= 0;)
  62157. if (titleBarButtons[i] != 0)
  62158. titleBarButtons[i]->setEnabled (isActiveWindow());
  62159. if (menuBar != 0)
  62160. menuBar->setEnabled (isActiveWindow());
  62161. }
  62162. void DocumentWindow::mouseDoubleClick (const MouseEvent& e)
  62163. {
  62164. if (getTitleBarArea().contains (e.x, e.y)
  62165. && getMaximiseButton() != 0)
  62166. {
  62167. getMaximiseButton()->triggerClick();
  62168. }
  62169. }
  62170. void DocumentWindow::userTriedToCloseWindow()
  62171. {
  62172. closeButtonPressed();
  62173. }
  62174. END_JUCE_NAMESPACE
  62175. /*** End of inlined file: juce_DocumentWindow.cpp ***/
  62176. /*** Start of inlined file: juce_ResizableWindow.cpp ***/
  62177. BEGIN_JUCE_NAMESPACE
  62178. ResizableWindow::ResizableWindow (const String& name,
  62179. const bool addToDesktop_)
  62180. : TopLevelWindow (name, addToDesktop_),
  62181. resizeToFitContent (false),
  62182. fullscreen (false),
  62183. lastNonFullScreenPos (50, 50, 256, 256),
  62184. constrainer (0)
  62185. #if JUCE_DEBUG
  62186. , hasBeenResized (false)
  62187. #endif
  62188. {
  62189. defaultConstrainer.setMinimumOnscreenAmounts (0x10000, 16, 24, 16);
  62190. lastNonFullScreenPos.setBounds (50, 50, 256, 256);
  62191. if (addToDesktop_)
  62192. Component::addToDesktop (getDesktopWindowStyleFlags());
  62193. }
  62194. ResizableWindow::ResizableWindow (const String& name,
  62195. const Colour& backgroundColour_,
  62196. const bool addToDesktop_)
  62197. : TopLevelWindow (name, addToDesktop_),
  62198. resizeToFitContent (false),
  62199. fullscreen (false),
  62200. lastNonFullScreenPos (50, 50, 256, 256),
  62201. constrainer (0)
  62202. #if JUCE_DEBUG
  62203. , hasBeenResized (false)
  62204. #endif
  62205. {
  62206. setBackgroundColour (backgroundColour_);
  62207. defaultConstrainer.setMinimumOnscreenAmounts (0x10000, 16, 24, 16);
  62208. if (addToDesktop_)
  62209. Component::addToDesktop (getDesktopWindowStyleFlags());
  62210. }
  62211. ResizableWindow::~ResizableWindow()
  62212. {
  62213. resizableCorner = 0;
  62214. resizableBorder = 0;
  62215. contentComponent = 0;
  62216. // have you been adding your own components directly to this window..? tut tut tut.
  62217. // Read the instructions for using a ResizableWindow!
  62218. jassert (getNumChildComponents() == 0);
  62219. }
  62220. int ResizableWindow::getDesktopWindowStyleFlags() const
  62221. {
  62222. int flags = TopLevelWindow::getDesktopWindowStyleFlags();
  62223. if (isResizable() && (flags & ComponentPeer::windowHasTitleBar) != 0)
  62224. flags |= ComponentPeer::windowIsResizable;
  62225. return flags;
  62226. }
  62227. void ResizableWindow::setContentComponent (Component* const newContentComponent,
  62228. const bool deleteOldOne,
  62229. const bool resizeToFit)
  62230. {
  62231. resizeToFitContent = resizeToFit;
  62232. if (newContentComponent != static_cast <Component*> (contentComponent))
  62233. {
  62234. if (! deleteOldOne)
  62235. removeChildComponent (contentComponent.release());
  62236. contentComponent = newContentComponent;
  62237. Component::addAndMakeVisible (contentComponent);
  62238. }
  62239. if (resizeToFit)
  62240. childBoundsChanged (contentComponent);
  62241. resized(); // must always be called to position the new content comp
  62242. }
  62243. void ResizableWindow::setContentComponentSize (int width, int height)
  62244. {
  62245. jassert (width > 0 && height > 0); // not a great idea to give it a zero size..
  62246. const BorderSize border (getContentComponentBorder());
  62247. setSize (width + border.getLeftAndRight(),
  62248. height + border.getTopAndBottom());
  62249. }
  62250. const BorderSize ResizableWindow::getBorderThickness()
  62251. {
  62252. return BorderSize (isUsingNativeTitleBar() ? 0 : ((resizableBorder != 0 && ! isFullScreen()) ? 5 : 3));
  62253. }
  62254. const BorderSize ResizableWindow::getContentComponentBorder()
  62255. {
  62256. return getBorderThickness();
  62257. }
  62258. void ResizableWindow::moved()
  62259. {
  62260. updateLastPos();
  62261. }
  62262. void ResizableWindow::visibilityChanged()
  62263. {
  62264. TopLevelWindow::visibilityChanged();
  62265. updateLastPos();
  62266. }
  62267. void ResizableWindow::resized()
  62268. {
  62269. if (resizableBorder != 0)
  62270. {
  62271. resizableBorder->setVisible (! isFullScreen());
  62272. resizableBorder->setBorderThickness (getBorderThickness());
  62273. resizableBorder->setSize (getWidth(), getHeight());
  62274. resizableBorder->toBack();
  62275. }
  62276. if (resizableCorner != 0)
  62277. {
  62278. resizableCorner->setVisible (! isFullScreen());
  62279. const int resizerSize = 18;
  62280. resizableCorner->setBounds (getWidth() - resizerSize,
  62281. getHeight() - resizerSize,
  62282. resizerSize, resizerSize);
  62283. }
  62284. if (contentComponent != 0)
  62285. contentComponent->setBoundsInset (getContentComponentBorder());
  62286. updateLastPos();
  62287. #if JUCE_DEBUG
  62288. hasBeenResized = true;
  62289. #endif
  62290. }
  62291. void ResizableWindow::childBoundsChanged (Component* child)
  62292. {
  62293. if ((child == contentComponent) && (child != 0) && resizeToFitContent)
  62294. {
  62295. // not going to look very good if this component has a zero size..
  62296. jassert (child->getWidth() > 0);
  62297. jassert (child->getHeight() > 0);
  62298. const BorderSize borders (getContentComponentBorder());
  62299. setSize (child->getWidth() + borders.getLeftAndRight(),
  62300. child->getHeight() + borders.getTopAndBottom());
  62301. }
  62302. }
  62303. void ResizableWindow::activeWindowStatusChanged()
  62304. {
  62305. const BorderSize borders (getContentComponentBorder());
  62306. repaint (0, 0, getWidth(), borders.getTop());
  62307. repaint (0, borders.getTop(), borders.getLeft(), getHeight() - borders.getBottom() - borders.getTop());
  62308. repaint (0, getHeight() - borders.getBottom(), getWidth(), borders.getBottom());
  62309. repaint (getWidth() - borders.getRight(), borders.getTop(), borders.getRight(), getHeight() - borders.getBottom() - borders.getTop());
  62310. }
  62311. void ResizableWindow::setResizable (const bool shouldBeResizable,
  62312. const bool useBottomRightCornerResizer)
  62313. {
  62314. if (shouldBeResizable)
  62315. {
  62316. if (useBottomRightCornerResizer)
  62317. {
  62318. resizableBorder = 0;
  62319. if (resizableCorner == 0)
  62320. {
  62321. Component::addChildComponent (resizableCorner = new ResizableCornerComponent (this, constrainer));
  62322. resizableCorner->setAlwaysOnTop (true);
  62323. }
  62324. }
  62325. else
  62326. {
  62327. resizableCorner = 0;
  62328. if (resizableBorder == 0)
  62329. Component::addChildComponent (resizableBorder = new ResizableBorderComponent (this, constrainer));
  62330. }
  62331. }
  62332. else
  62333. {
  62334. resizableCorner = 0;
  62335. resizableBorder = 0;
  62336. }
  62337. if (isUsingNativeTitleBar())
  62338. recreateDesktopWindow();
  62339. childBoundsChanged (contentComponent);
  62340. resized();
  62341. }
  62342. bool ResizableWindow::isResizable() const throw()
  62343. {
  62344. return resizableCorner != 0
  62345. || resizableBorder != 0;
  62346. }
  62347. void ResizableWindow::setResizeLimits (const int newMinimumWidth,
  62348. const int newMinimumHeight,
  62349. const int newMaximumWidth,
  62350. const int newMaximumHeight) throw()
  62351. {
  62352. // if you've set up a custom constrainer then these settings won't have any effect..
  62353. jassert (constrainer == &defaultConstrainer || constrainer == 0);
  62354. if (constrainer == 0)
  62355. setConstrainer (&defaultConstrainer);
  62356. defaultConstrainer.setSizeLimits (newMinimumWidth, newMinimumHeight,
  62357. newMaximumWidth, newMaximumHeight);
  62358. setBoundsConstrained (getBounds());
  62359. }
  62360. void ResizableWindow::setConstrainer (ComponentBoundsConstrainer* newConstrainer)
  62361. {
  62362. if (constrainer != newConstrainer)
  62363. {
  62364. constrainer = newConstrainer;
  62365. const bool useBottomRightCornerResizer = resizableCorner != 0;
  62366. const bool shouldBeResizable = useBottomRightCornerResizer || resizableBorder != 0;
  62367. resizableCorner = 0;
  62368. resizableBorder = 0;
  62369. setResizable (shouldBeResizable, useBottomRightCornerResizer);
  62370. ComponentPeer* const peer = getPeer();
  62371. if (peer != 0)
  62372. peer->setConstrainer (newConstrainer);
  62373. }
  62374. }
  62375. void ResizableWindow::setBoundsConstrained (const Rectangle<int>& bounds)
  62376. {
  62377. if (constrainer != 0)
  62378. constrainer->setBoundsForComponent (this, bounds, false, false, false, false);
  62379. else
  62380. setBounds (bounds);
  62381. }
  62382. void ResizableWindow::paint (Graphics& g)
  62383. {
  62384. getLookAndFeel().fillResizableWindowBackground (g, getWidth(), getHeight(),
  62385. getBorderThickness(), *this);
  62386. if (! isFullScreen())
  62387. {
  62388. getLookAndFeel().drawResizableWindowBorder (g, getWidth(), getHeight(),
  62389. getBorderThickness(), *this);
  62390. }
  62391. #if JUCE_DEBUG
  62392. /* If this fails, then you've probably written a subclass with a resized()
  62393. callback but forgotten to make it call its parent class's resized() method.
  62394. It's important when you override methods like resized(), moved(),
  62395. etc., that you make sure the base class methods also get called.
  62396. Of course you shouldn't really be overriding ResizableWindow::resized() anyway,
  62397. because your content should all be inside the content component - and it's the
  62398. content component's resized() method that you should be using to do your
  62399. layout.
  62400. */
  62401. jassert (hasBeenResized || (getWidth() == 0 && getHeight() == 0));
  62402. #endif
  62403. }
  62404. void ResizableWindow::lookAndFeelChanged()
  62405. {
  62406. resized();
  62407. if (isOnDesktop())
  62408. {
  62409. Component::addToDesktop (getDesktopWindowStyleFlags());
  62410. ComponentPeer* const peer = getPeer();
  62411. if (peer != 0)
  62412. peer->setConstrainer (constrainer);
  62413. }
  62414. }
  62415. const Colour ResizableWindow::getBackgroundColour() const throw()
  62416. {
  62417. return findColour (backgroundColourId, false);
  62418. }
  62419. void ResizableWindow::setBackgroundColour (const Colour& newColour)
  62420. {
  62421. Colour backgroundColour (newColour);
  62422. if (! Desktop::canUseSemiTransparentWindows())
  62423. backgroundColour = newColour.withAlpha (1.0f);
  62424. setColour (backgroundColourId, backgroundColour);
  62425. setOpaque (backgroundColour.isOpaque());
  62426. repaint();
  62427. }
  62428. bool ResizableWindow::isFullScreen() const
  62429. {
  62430. if (isOnDesktop())
  62431. {
  62432. ComponentPeer* const peer = getPeer();
  62433. return peer != 0 && peer->isFullScreen();
  62434. }
  62435. return fullscreen;
  62436. }
  62437. void ResizableWindow::setFullScreen (const bool shouldBeFullScreen)
  62438. {
  62439. if (shouldBeFullScreen != isFullScreen())
  62440. {
  62441. updateLastPos();
  62442. fullscreen = shouldBeFullScreen;
  62443. if (isOnDesktop())
  62444. {
  62445. ComponentPeer* const peer = getPeer();
  62446. if (peer != 0)
  62447. {
  62448. // keep a copy of this intact in case the real one gets messed-up while we're un-maximising
  62449. const Rectangle<int> lastPos (lastNonFullScreenPos);
  62450. peer->setFullScreen (shouldBeFullScreen);
  62451. if (! shouldBeFullScreen)
  62452. setBounds (lastPos);
  62453. }
  62454. else
  62455. {
  62456. jassertfalse
  62457. }
  62458. }
  62459. else
  62460. {
  62461. if (shouldBeFullScreen)
  62462. setBounds (0, 0, getParentWidth(), getParentHeight());
  62463. else
  62464. setBounds (lastNonFullScreenPos);
  62465. }
  62466. resized();
  62467. }
  62468. }
  62469. bool ResizableWindow::isMinimised() const
  62470. {
  62471. ComponentPeer* const peer = getPeer();
  62472. return (peer != 0) && peer->isMinimised();
  62473. }
  62474. void ResizableWindow::setMinimised (const bool shouldMinimise)
  62475. {
  62476. if (shouldMinimise != isMinimised())
  62477. {
  62478. ComponentPeer* const peer = getPeer();
  62479. if (peer != 0)
  62480. {
  62481. updateLastPos();
  62482. peer->setMinimised (shouldMinimise);
  62483. }
  62484. else
  62485. {
  62486. jassertfalse
  62487. }
  62488. }
  62489. }
  62490. void ResizableWindow::updateLastPos()
  62491. {
  62492. if (isShowing() && ! (isFullScreen() || isMinimised()))
  62493. {
  62494. lastNonFullScreenPos = getBounds();
  62495. }
  62496. }
  62497. void ResizableWindow::parentSizeChanged()
  62498. {
  62499. if (isFullScreen() && getParentComponent() != 0)
  62500. {
  62501. setBounds (0, 0, getParentWidth(), getParentHeight());
  62502. }
  62503. }
  62504. const String ResizableWindow::getWindowStateAsString()
  62505. {
  62506. updateLastPos();
  62507. return (isFullScreen() ? "fs " : "") + lastNonFullScreenPos.toString();
  62508. }
  62509. bool ResizableWindow::restoreWindowStateFromString (const String& s)
  62510. {
  62511. StringArray tokens;
  62512. tokens.addTokens (s, false);
  62513. tokens.removeEmptyStrings();
  62514. tokens.trim();
  62515. const bool fs = tokens[0].startsWithIgnoreCase ("fs");
  62516. const int firstCoord = fs ? 1 : 0;
  62517. if (tokens.size() != firstCoord + 4)
  62518. return false;
  62519. Rectangle<int> newPos (tokens[firstCoord].getIntValue(),
  62520. tokens[firstCoord + 1].getIntValue(),
  62521. tokens[firstCoord + 2].getIntValue(),
  62522. tokens[firstCoord + 3].getIntValue());
  62523. if (newPos.isEmpty())
  62524. return false;
  62525. const Rectangle<int> screen (Desktop::getInstance().getMonitorAreaContaining (newPos.getCentre()));
  62526. ComponentPeer* const peer = isOnDesktop() ? getPeer() : 0;
  62527. if (peer != 0)
  62528. peer->getFrameSize().addTo (newPos);
  62529. if (! screen.contains (newPos))
  62530. {
  62531. newPos.setSize (jmin (newPos.getWidth(), screen.getWidth()),
  62532. jmin (newPos.getHeight(), screen.getHeight()));
  62533. newPos.setPosition (jlimit (screen.getX(), screen.getRight() - newPos.getWidth(), newPos.getX()),
  62534. jlimit (screen.getY(), screen.getBottom() - newPos.getHeight(), newPos.getY()));
  62535. }
  62536. if (peer != 0)
  62537. {
  62538. peer->getFrameSize().subtractFrom (newPos);
  62539. peer->setNonFullScreenBounds (newPos);
  62540. }
  62541. lastNonFullScreenPos = newPos;
  62542. setFullScreen (fs);
  62543. if (! fs)
  62544. setBoundsConstrained (newPos);
  62545. return true;
  62546. }
  62547. void ResizableWindow::mouseDown (const MouseEvent&)
  62548. {
  62549. if (! isFullScreen())
  62550. dragger.startDraggingComponent (this, constrainer);
  62551. }
  62552. void ResizableWindow::mouseDrag (const MouseEvent& e)
  62553. {
  62554. if (! isFullScreen())
  62555. dragger.dragComponent (this, e);
  62556. }
  62557. #if JUCE_DEBUG
  62558. void ResizableWindow::addChildComponent (Component* const child, int zOrder)
  62559. {
  62560. /* Agh! You shouldn't add components directly to a ResizableWindow - this class
  62561. manages its child components automatically, and if you add your own it'll cause
  62562. trouble. Instead, use setContentComponent() to give it a component which
  62563. will be automatically resized and kept in the right place - then you can add
  62564. subcomponents to the content comp. See the notes for the ResizableWindow class
  62565. for more info.
  62566. If you really know what you're doing and want to avoid this assertion, just call
  62567. Component::addChildComponent directly.
  62568. */
  62569. jassertfalse
  62570. Component::addChildComponent (child, zOrder);
  62571. }
  62572. void ResizableWindow::addAndMakeVisible (Component* const child, int zOrder)
  62573. {
  62574. /* Agh! You shouldn't add components directly to a ResizableWindow - this class
  62575. manages its child components automatically, and if you add your own it'll cause
  62576. trouble. Instead, use setContentComponent() to give it a component which
  62577. will be automatically resized and kept in the right place - then you can add
  62578. subcomponents to the content comp. See the notes for the ResizableWindow class
  62579. for more info.
  62580. If you really know what you're doing and want to avoid this assertion, just call
  62581. Component::addAndMakeVisible directly.
  62582. */
  62583. jassertfalse
  62584. Component::addAndMakeVisible (child, zOrder);
  62585. }
  62586. #endif
  62587. END_JUCE_NAMESPACE
  62588. /*** End of inlined file: juce_ResizableWindow.cpp ***/
  62589. /*** Start of inlined file: juce_SplashScreen.cpp ***/
  62590. BEGIN_JUCE_NAMESPACE
  62591. SplashScreen::SplashScreen()
  62592. : backgroundImage (0)
  62593. {
  62594. setOpaque (true);
  62595. }
  62596. SplashScreen::~SplashScreen()
  62597. {
  62598. ImageCache::releaseOrDelete (backgroundImage);
  62599. }
  62600. void SplashScreen::show (const String& title,
  62601. Image* const backgroundImage_,
  62602. const int minimumTimeToDisplayFor,
  62603. const bool useDropShadow,
  62604. const bool removeOnMouseClick)
  62605. {
  62606. backgroundImage = backgroundImage_;
  62607. jassert (backgroundImage_ != 0);
  62608. if (backgroundImage_ != 0)
  62609. {
  62610. setOpaque (! backgroundImage_->hasAlphaChannel());
  62611. show (title,
  62612. backgroundImage_->getWidth(),
  62613. backgroundImage_->getHeight(),
  62614. minimumTimeToDisplayFor,
  62615. useDropShadow,
  62616. removeOnMouseClick);
  62617. }
  62618. }
  62619. void SplashScreen::show (const String& title,
  62620. const int width,
  62621. const int height,
  62622. const int minimumTimeToDisplayFor,
  62623. const bool useDropShadow,
  62624. const bool removeOnMouseClick)
  62625. {
  62626. setName (title);
  62627. setAlwaysOnTop (true);
  62628. setVisible (true);
  62629. centreWithSize (width, height);
  62630. addToDesktop (useDropShadow ? ComponentPeer::windowHasDropShadow : 0);
  62631. toFront (false);
  62632. MessageManager::getInstance()->runDispatchLoopUntil (300);
  62633. repaint();
  62634. originalClickCounter = removeOnMouseClick
  62635. ? Desktop::getMouseButtonClickCounter()
  62636. : std::numeric_limits<int>::max();
  62637. earliestTimeToDelete = Time::getCurrentTime() + RelativeTime::milliseconds (minimumTimeToDisplayFor);
  62638. startTimer (50);
  62639. }
  62640. void SplashScreen::paint (Graphics& g)
  62641. {
  62642. if (backgroundImage != 0)
  62643. {
  62644. g.setOpacity (1.0f);
  62645. g.drawImage (backgroundImage,
  62646. 0, 0, getWidth(), getHeight(),
  62647. 0, 0, backgroundImage->getWidth(), backgroundImage->getHeight());
  62648. }
  62649. }
  62650. void SplashScreen::timerCallback()
  62651. {
  62652. if (Time::getCurrentTime() > earliestTimeToDelete
  62653. || Desktop::getMouseButtonClickCounter() > originalClickCounter)
  62654. {
  62655. delete this;
  62656. }
  62657. }
  62658. END_JUCE_NAMESPACE
  62659. /*** End of inlined file: juce_SplashScreen.cpp ***/
  62660. /*** Start of inlined file: juce_ThreadWithProgressWindow.cpp ***/
  62661. BEGIN_JUCE_NAMESPACE
  62662. ThreadWithProgressWindow::ThreadWithProgressWindow (const String& title,
  62663. const bool hasProgressBar,
  62664. const bool hasCancelButton,
  62665. const int timeOutMsWhenCancelling_,
  62666. const String& cancelButtonText)
  62667. : Thread ("Juce Progress Window"),
  62668. progress (0.0),
  62669. timeOutMsWhenCancelling (timeOutMsWhenCancelling_)
  62670. {
  62671. alertWindow = LookAndFeel::getDefaultLookAndFeel()
  62672. .createAlertWindow (title, String::empty, cancelButtonText,
  62673. String::empty, String::empty,
  62674. AlertWindow::NoIcon, hasCancelButton ? 1 : 0, 0);
  62675. if (hasProgressBar)
  62676. alertWindow->addProgressBarComponent (progress);
  62677. }
  62678. ThreadWithProgressWindow::~ThreadWithProgressWindow()
  62679. {
  62680. stopThread (timeOutMsWhenCancelling);
  62681. }
  62682. bool ThreadWithProgressWindow::runThread (const int priority)
  62683. {
  62684. startThread (priority);
  62685. startTimer (100);
  62686. {
  62687. const ScopedLock sl (messageLock);
  62688. alertWindow->setMessage (message);
  62689. }
  62690. const bool finishedNaturally = alertWindow->runModalLoop() != 0;
  62691. stopThread (timeOutMsWhenCancelling);
  62692. alertWindow->setVisible (false);
  62693. return finishedNaturally;
  62694. }
  62695. void ThreadWithProgressWindow::setProgress (const double newProgress)
  62696. {
  62697. progress = newProgress;
  62698. }
  62699. void ThreadWithProgressWindow::setStatusMessage (const String& newStatusMessage)
  62700. {
  62701. const ScopedLock sl (messageLock);
  62702. message = newStatusMessage;
  62703. }
  62704. void ThreadWithProgressWindow::timerCallback()
  62705. {
  62706. if (! isThreadRunning())
  62707. {
  62708. // thread has finished normally..
  62709. alertWindow->exitModalState (1);
  62710. alertWindow->setVisible (false);
  62711. }
  62712. else
  62713. {
  62714. const ScopedLock sl (messageLock);
  62715. alertWindow->setMessage (message);
  62716. }
  62717. }
  62718. END_JUCE_NAMESPACE
  62719. /*** End of inlined file: juce_ThreadWithProgressWindow.cpp ***/
  62720. /*** Start of inlined file: juce_TooltipWindow.cpp ***/
  62721. BEGIN_JUCE_NAMESPACE
  62722. TooltipWindow::TooltipWindow (Component* const parentComponent,
  62723. const int millisecondsBeforeTipAppears_)
  62724. : Component ("tooltip"),
  62725. millisecondsBeforeTipAppears (millisecondsBeforeTipAppears_),
  62726. mouseClicks (0),
  62727. lastHideTime (0),
  62728. lastComponentUnderMouse (0),
  62729. changedCompsSinceShown (true)
  62730. {
  62731. if (Desktop::getInstance().getMainMouseSource().canHover())
  62732. startTimer (123);
  62733. setAlwaysOnTop (true);
  62734. setOpaque (true);
  62735. if (parentComponent != 0)
  62736. parentComponent->addChildComponent (this);
  62737. }
  62738. TooltipWindow::~TooltipWindow()
  62739. {
  62740. hide();
  62741. }
  62742. void TooltipWindow::setMillisecondsBeforeTipAppears (const int newTimeMs) throw()
  62743. {
  62744. millisecondsBeforeTipAppears = newTimeMs;
  62745. }
  62746. void TooltipWindow::paint (Graphics& g)
  62747. {
  62748. getLookAndFeel().drawTooltip (g, tipShowing, getWidth(), getHeight());
  62749. }
  62750. void TooltipWindow::mouseEnter (const MouseEvent&)
  62751. {
  62752. hide();
  62753. }
  62754. void TooltipWindow::showFor (const String& tip)
  62755. {
  62756. jassert (tip.isNotEmpty());
  62757. tipShowing = tip;
  62758. Point<int> mousePos (Desktop::getMousePosition());
  62759. if (getParentComponent() != 0)
  62760. mousePos = getParentComponent()->globalPositionToRelative (mousePos);
  62761. int x, y, w, h;
  62762. getLookAndFeel().getTooltipSize (tip, w, h);
  62763. if (mousePos.getX() > getParentWidth() / 2)
  62764. x = mousePos.getX() - (w + 12);
  62765. else
  62766. x = mousePos.getX() + 24;
  62767. if (mousePos.getY() > getParentHeight() / 2)
  62768. y = mousePos.getY() - (h + 6);
  62769. else
  62770. y = mousePos.getY() + 6;
  62771. setBounds (x, y, w, h);
  62772. setVisible (true);
  62773. if (getParentComponent() == 0)
  62774. {
  62775. addToDesktop (ComponentPeer::windowHasDropShadow
  62776. | ComponentPeer::windowIsTemporary
  62777. | ComponentPeer::windowIgnoresKeyPresses);
  62778. }
  62779. toFront (false);
  62780. }
  62781. const String TooltipWindow::getTipFor (Component* const c)
  62782. {
  62783. if (c != 0
  62784. && Process::isForegroundProcess()
  62785. && ! Component::isMouseButtonDownAnywhere())
  62786. {
  62787. TooltipClient* const ttc = dynamic_cast <TooltipClient*> (c);
  62788. if (ttc != 0 && ! c->isCurrentlyBlockedByAnotherModalComponent())
  62789. return ttc->getTooltip();
  62790. }
  62791. return String::empty;
  62792. }
  62793. void TooltipWindow::hide()
  62794. {
  62795. tipShowing = String::empty;
  62796. removeFromDesktop();
  62797. setVisible (false);
  62798. }
  62799. void TooltipWindow::timerCallback()
  62800. {
  62801. const unsigned int now = Time::getApproximateMillisecondCounter();
  62802. Component* const newComp = Desktop::getInstance().getMainMouseSource().getComponentUnderMouse();
  62803. const String newTip (getTipFor (newComp));
  62804. const bool tipChanged = (newTip != lastTipUnderMouse || newComp != lastComponentUnderMouse);
  62805. lastComponentUnderMouse = newComp;
  62806. lastTipUnderMouse = newTip;
  62807. const int clickCount = Desktop::getInstance().getMouseButtonClickCounter();
  62808. const bool mouseWasClicked = clickCount > mouseClicks;
  62809. mouseClicks = clickCount;
  62810. const Point<int> mousePos (Desktop::getMousePosition());
  62811. const bool mouseMovedQuickly = mousePos.getDistanceFrom (lastMousePos) > 12;
  62812. lastMousePos = mousePos;
  62813. if (tipChanged || mouseWasClicked || mouseMovedQuickly)
  62814. lastCompChangeTime = now;
  62815. if (isVisible() || now < lastHideTime + 500)
  62816. {
  62817. // if a tip is currently visible (or has just disappeared), update to a new one
  62818. // immediately if needed..
  62819. if (newComp == 0 || mouseWasClicked || newTip.isEmpty())
  62820. {
  62821. if (isVisible())
  62822. {
  62823. lastHideTime = now;
  62824. hide();
  62825. }
  62826. }
  62827. else if (tipChanged)
  62828. {
  62829. showFor (newTip);
  62830. }
  62831. }
  62832. else
  62833. {
  62834. // if there isn't currently a tip, but one is needed, only let it
  62835. // appear after a timeout..
  62836. if (newTip.isNotEmpty()
  62837. && newTip != tipShowing
  62838. && now > lastCompChangeTime + millisecondsBeforeTipAppears)
  62839. {
  62840. showFor (newTip);
  62841. }
  62842. }
  62843. }
  62844. END_JUCE_NAMESPACE
  62845. /*** End of inlined file: juce_TooltipWindow.cpp ***/
  62846. /*** Start of inlined file: juce_TopLevelWindow.cpp ***/
  62847. BEGIN_JUCE_NAMESPACE
  62848. /** Keeps track of the active top level window.
  62849. */
  62850. class TopLevelWindowManager : public Timer,
  62851. public DeletedAtShutdown
  62852. {
  62853. public:
  62854. TopLevelWindowManager()
  62855. : currentActive (0)
  62856. {
  62857. }
  62858. ~TopLevelWindowManager()
  62859. {
  62860. clearSingletonInstance();
  62861. }
  62862. juce_DeclareSingleton_SingleThreaded_Minimal (TopLevelWindowManager)
  62863. void timerCallback()
  62864. {
  62865. startTimer (jmin (1731, getTimerInterval() * 2));
  62866. TopLevelWindow* active = 0;
  62867. if (Process::isForegroundProcess())
  62868. {
  62869. active = currentActive;
  62870. Component* const c = Component::getCurrentlyFocusedComponent();
  62871. TopLevelWindow* tlw = dynamic_cast <TopLevelWindow*> (c);
  62872. if (tlw == 0 && c != 0)
  62873. // (unable to use the syntax findParentComponentOfClass <TopLevelWindow> () because of a VC6 compiler bug)
  62874. tlw = c->findParentComponentOfClass ((TopLevelWindow*) 0);
  62875. if (tlw != 0)
  62876. active = tlw;
  62877. }
  62878. if (active != currentActive)
  62879. {
  62880. currentActive = active;
  62881. for (int i = windows.size(); --i >= 0;)
  62882. {
  62883. TopLevelWindow* const tlw = (TopLevelWindow*) windows.getUnchecked (i);
  62884. tlw->setWindowActive (isWindowActive (tlw));
  62885. i = jmin (i, windows.size() - 1);
  62886. }
  62887. Desktop::getInstance().triggerFocusCallback();
  62888. }
  62889. }
  62890. bool addWindow (TopLevelWindow* const w)
  62891. {
  62892. windows.add (w);
  62893. startTimer (10);
  62894. return isWindowActive (w);
  62895. }
  62896. void removeWindow (TopLevelWindow* const w)
  62897. {
  62898. startTimer (10);
  62899. if (currentActive == w)
  62900. currentActive = 0;
  62901. windows.removeValue (w);
  62902. if (windows.size() == 0)
  62903. deleteInstance();
  62904. }
  62905. VoidArray windows;
  62906. private:
  62907. TopLevelWindow* currentActive;
  62908. bool isWindowActive (TopLevelWindow* const tlw) const
  62909. {
  62910. return (tlw == currentActive
  62911. || tlw->isParentOf (currentActive)
  62912. || tlw->hasKeyboardFocus (true))
  62913. && tlw->isShowing();
  62914. }
  62915. TopLevelWindowManager (const TopLevelWindowManager&);
  62916. TopLevelWindowManager& operator= (const TopLevelWindowManager&);
  62917. };
  62918. juce_ImplementSingleton_SingleThreaded (TopLevelWindowManager)
  62919. void juce_CheckCurrentlyFocusedTopLevelWindow()
  62920. {
  62921. if (TopLevelWindowManager::getInstanceWithoutCreating() != 0)
  62922. TopLevelWindowManager::getInstanceWithoutCreating()->startTimer (20);
  62923. }
  62924. TopLevelWindow::TopLevelWindow (const String& name,
  62925. const bool addToDesktop_)
  62926. : Component (name),
  62927. useDropShadow (true),
  62928. useNativeTitleBar (false),
  62929. windowIsActive_ (false)
  62930. {
  62931. setOpaque (true);
  62932. if (addToDesktop_)
  62933. Component::addToDesktop (getDesktopWindowStyleFlags());
  62934. else
  62935. setDropShadowEnabled (true);
  62936. setWantsKeyboardFocus (true);
  62937. setBroughtToFrontOnMouseClick (true);
  62938. windowIsActive_ = TopLevelWindowManager::getInstance()->addWindow (this);
  62939. }
  62940. TopLevelWindow::~TopLevelWindow()
  62941. {
  62942. shadower = 0;
  62943. TopLevelWindowManager::getInstance()->removeWindow (this);
  62944. }
  62945. void TopLevelWindow::focusOfChildComponentChanged (FocusChangeType)
  62946. {
  62947. if (hasKeyboardFocus (true))
  62948. TopLevelWindowManager::getInstance()->timerCallback();
  62949. else
  62950. TopLevelWindowManager::getInstance()->startTimer (10);
  62951. }
  62952. void TopLevelWindow::setWindowActive (const bool isNowActive)
  62953. {
  62954. if (windowIsActive_ != isNowActive)
  62955. {
  62956. windowIsActive_ = isNowActive;
  62957. activeWindowStatusChanged();
  62958. }
  62959. }
  62960. void TopLevelWindow::activeWindowStatusChanged()
  62961. {
  62962. }
  62963. void TopLevelWindow::parentHierarchyChanged()
  62964. {
  62965. setDropShadowEnabled (useDropShadow);
  62966. }
  62967. void TopLevelWindow::visibilityChanged()
  62968. {
  62969. if (isShowing())
  62970. toFront (true);
  62971. }
  62972. int TopLevelWindow::getDesktopWindowStyleFlags() const
  62973. {
  62974. int flags = ComponentPeer::windowAppearsOnTaskbar;
  62975. if (useDropShadow)
  62976. flags |= ComponentPeer::windowHasDropShadow;
  62977. if (useNativeTitleBar)
  62978. flags |= ComponentPeer::windowHasTitleBar;
  62979. return flags;
  62980. }
  62981. void TopLevelWindow::setDropShadowEnabled (const bool useShadow)
  62982. {
  62983. useDropShadow = useShadow;
  62984. if (isOnDesktop())
  62985. {
  62986. shadower = 0;
  62987. Component::addToDesktop (getDesktopWindowStyleFlags());
  62988. }
  62989. else
  62990. {
  62991. if (useShadow && isOpaque())
  62992. {
  62993. if (shadower == 0)
  62994. {
  62995. shadower = getLookAndFeel().createDropShadowerForComponent (this);
  62996. if (shadower != 0)
  62997. shadower->setOwner (this);
  62998. }
  62999. }
  63000. else
  63001. {
  63002. shadower = 0;
  63003. }
  63004. }
  63005. }
  63006. void TopLevelWindow::setUsingNativeTitleBar (const bool useNativeTitleBar_)
  63007. {
  63008. if (useNativeTitleBar != useNativeTitleBar_)
  63009. {
  63010. useNativeTitleBar = useNativeTitleBar_;
  63011. recreateDesktopWindow();
  63012. sendLookAndFeelChange();
  63013. }
  63014. }
  63015. void TopLevelWindow::recreateDesktopWindow()
  63016. {
  63017. if (isOnDesktop())
  63018. {
  63019. Component::addToDesktop (getDesktopWindowStyleFlags());
  63020. toFront (true);
  63021. }
  63022. }
  63023. void TopLevelWindow::addToDesktop (int windowStyleFlags, void* nativeWindowToAttachTo)
  63024. {
  63025. /* It's not recommended to change the desktop window flags directly for a TopLevelWindow,
  63026. because this class needs to make sure its layout corresponds with settings like whether
  63027. it's got a native title bar or not.
  63028. If you need custom flags for your window, you can override the getDesktopWindowStyleFlags()
  63029. method. If you do this, it's best to call the base class's getDesktopWindowStyleFlags()
  63030. method, then add or remove whatever flags are necessary from this value before returning it.
  63031. */
  63032. jassert ((windowStyleFlags & ~ComponentPeer::windowIsSemiTransparent)
  63033. == (getDesktopWindowStyleFlags() & ~ComponentPeer::windowIsSemiTransparent));
  63034. Component::addToDesktop (windowStyleFlags, nativeWindowToAttachTo);
  63035. if (windowStyleFlags != getDesktopWindowStyleFlags())
  63036. sendLookAndFeelChange();
  63037. }
  63038. void TopLevelWindow::centreAroundComponent (Component* c, const int width, const int height)
  63039. {
  63040. if (c == 0)
  63041. c = TopLevelWindow::getActiveTopLevelWindow();
  63042. if (c == 0)
  63043. {
  63044. centreWithSize (width, height);
  63045. }
  63046. else
  63047. {
  63048. Point<int> p (c->relativePositionToGlobal (Point<int> ((c->getWidth() - width) / 2,
  63049. (c->getHeight() - height) / 2)));
  63050. Rectangle<int> parentArea (c->getParentMonitorArea());
  63051. if (getParentComponent() != 0)
  63052. {
  63053. p = getParentComponent()->globalPositionToRelative (p);
  63054. parentArea.setBounds (0, 0, getParentWidth(), getParentHeight());
  63055. }
  63056. parentArea.reduce (12, 12);
  63057. setBounds (jlimit (parentArea.getX(), jmax (parentArea.getX(), parentArea.getRight() - width), p.getX()),
  63058. jlimit (parentArea.getY(), jmax (parentArea.getY(), parentArea.getBottom() - height), p.getY()),
  63059. width, height);
  63060. }
  63061. }
  63062. int TopLevelWindow::getNumTopLevelWindows() throw()
  63063. {
  63064. return TopLevelWindowManager::getInstance()->windows.size();
  63065. }
  63066. TopLevelWindow* TopLevelWindow::getTopLevelWindow (const int index) throw()
  63067. {
  63068. return static_cast <TopLevelWindow*> (TopLevelWindowManager::getInstance()->windows [index]);
  63069. }
  63070. TopLevelWindow* TopLevelWindow::getActiveTopLevelWindow() throw()
  63071. {
  63072. TopLevelWindow* best = 0;
  63073. int bestNumTWLParents = -1;
  63074. for (int i = TopLevelWindow::getNumTopLevelWindows(); --i >= 0;)
  63075. {
  63076. TopLevelWindow* const tlw = TopLevelWindow::getTopLevelWindow (i);
  63077. if (tlw->isActiveWindow())
  63078. {
  63079. int numTWLParents = 0;
  63080. const Component* c = tlw->getParentComponent();
  63081. while (c != 0)
  63082. {
  63083. if (dynamic_cast <const TopLevelWindow*> (c) != 0)
  63084. ++numTWLParents;
  63085. c = c->getParentComponent();
  63086. }
  63087. if (bestNumTWLParents < numTWLParents)
  63088. {
  63089. best = tlw;
  63090. bestNumTWLParents = numTWLParents;
  63091. }
  63092. }
  63093. }
  63094. return best;
  63095. }
  63096. END_JUCE_NAMESPACE
  63097. /*** End of inlined file: juce_TopLevelWindow.cpp ***/
  63098. #endif
  63099. #if JUCE_BUILD_MISC // (put these in misc to balance the file sizes and avoid problems in iphone build)
  63100. /*** Start of inlined file: juce_Colour.cpp ***/
  63101. BEGIN_JUCE_NAMESPACE
  63102. namespace ColourHelpers
  63103. {
  63104. static uint8 floatAlphaToInt (const float alpha) throw()
  63105. {
  63106. return (uint8) jlimit (0, 0xff, roundToInt (alpha * 255.0f));
  63107. }
  63108. static void convertHSBtoRGB (float h, float s, float v,
  63109. uint8& r, uint8& g, uint8& b) throw()
  63110. {
  63111. v = jlimit (0.0f, 1.0f, v);
  63112. v *= 255.0f;
  63113. const uint8 intV = (uint8) roundToInt (v);
  63114. if (s <= 0)
  63115. {
  63116. r = intV;
  63117. g = intV;
  63118. b = intV;
  63119. }
  63120. else
  63121. {
  63122. s = jmin (1.0f, s);
  63123. h = jlimit (0.0f, 1.0f, h);
  63124. h = (h - floorf (h)) * 6.0f + 0.00001f; // need a small adjustment to compensate for rounding errors
  63125. const float f = h - floorf (h);
  63126. const uint8 x = (uint8) roundToInt (v * (1.0f - s));
  63127. const float y = v * (1.0f - s * f);
  63128. const float z = v * (1.0f - (s * (1.0f - f)));
  63129. if (h < 1.0f)
  63130. {
  63131. r = intV;
  63132. g = (uint8) roundToInt (z);
  63133. b = x;
  63134. }
  63135. else if (h < 2.0f)
  63136. {
  63137. r = (uint8) roundToInt (y);
  63138. g = intV;
  63139. b = x;
  63140. }
  63141. else if (h < 3.0f)
  63142. {
  63143. r = x;
  63144. g = intV;
  63145. b = (uint8) roundToInt (z);
  63146. }
  63147. else if (h < 4.0f)
  63148. {
  63149. r = x;
  63150. g = (uint8) roundToInt (y);
  63151. b = intV;
  63152. }
  63153. else if (h < 5.0f)
  63154. {
  63155. r = (uint8) roundToInt (z);
  63156. g = x;
  63157. b = intV;
  63158. }
  63159. else if (h < 6.0f)
  63160. {
  63161. r = intV;
  63162. g = x;
  63163. b = (uint8) roundToInt (y);
  63164. }
  63165. else
  63166. {
  63167. r = 0;
  63168. g = 0;
  63169. b = 0;
  63170. }
  63171. }
  63172. }
  63173. }
  63174. Colour::Colour() throw()
  63175. : argb (0)
  63176. {
  63177. }
  63178. Colour::Colour (const Colour& other) throw()
  63179. : argb (other.argb)
  63180. {
  63181. }
  63182. Colour& Colour::operator= (const Colour& other) throw()
  63183. {
  63184. argb = other.argb;
  63185. return *this;
  63186. }
  63187. bool Colour::operator== (const Colour& other) const throw()
  63188. {
  63189. return argb.getARGB() == other.argb.getARGB();
  63190. }
  63191. bool Colour::operator!= (const Colour& other) const throw()
  63192. {
  63193. return argb.getARGB() != other.argb.getARGB();
  63194. }
  63195. Colour::Colour (const uint32 argb_) throw()
  63196. : argb (argb_)
  63197. {
  63198. }
  63199. Colour::Colour (const uint8 red,
  63200. const uint8 green,
  63201. const uint8 blue) throw()
  63202. {
  63203. argb.setARGB (0xff, red, green, blue);
  63204. }
  63205. const Colour Colour::fromRGB (const uint8 red,
  63206. const uint8 green,
  63207. const uint8 blue) throw()
  63208. {
  63209. return Colour (red, green, blue);
  63210. }
  63211. Colour::Colour (const uint8 red,
  63212. const uint8 green,
  63213. const uint8 blue,
  63214. const uint8 alpha) throw()
  63215. {
  63216. argb.setARGB (alpha, red, green, blue);
  63217. }
  63218. const Colour Colour::fromRGBA (const uint8 red,
  63219. const uint8 green,
  63220. const uint8 blue,
  63221. const uint8 alpha) throw()
  63222. {
  63223. return Colour (red, green, blue, alpha);
  63224. }
  63225. Colour::Colour (const uint8 red,
  63226. const uint8 green,
  63227. const uint8 blue,
  63228. const float alpha) throw()
  63229. {
  63230. argb.setARGB (ColourHelpers::floatAlphaToInt (alpha), red, green, blue);
  63231. }
  63232. const Colour Colour::fromRGBAFloat (const uint8 red,
  63233. const uint8 green,
  63234. const uint8 blue,
  63235. const float alpha) throw()
  63236. {
  63237. return Colour (red, green, blue, alpha);
  63238. }
  63239. Colour::Colour (const float hue,
  63240. const float saturation,
  63241. const float brightness,
  63242. const float alpha) throw()
  63243. {
  63244. uint8 r = getRed(), g = getGreen(), b = getBlue();
  63245. ColourHelpers::convertHSBtoRGB (hue, saturation, brightness, r, g, b);
  63246. argb.setARGB (ColourHelpers::floatAlphaToInt (alpha), r, g, b);
  63247. }
  63248. const Colour Colour::fromHSV (const float hue,
  63249. const float saturation,
  63250. const float brightness,
  63251. const float alpha) throw()
  63252. {
  63253. return Colour (hue, saturation, brightness, alpha);
  63254. }
  63255. Colour::Colour (const float hue,
  63256. const float saturation,
  63257. const float brightness,
  63258. const uint8 alpha) throw()
  63259. {
  63260. uint8 r = getRed(), g = getGreen(), b = getBlue();
  63261. ColourHelpers::convertHSBtoRGB (hue, saturation, brightness, r, g, b);
  63262. argb.setARGB (alpha, r, g, b);
  63263. }
  63264. Colour::~Colour() throw()
  63265. {
  63266. }
  63267. const PixelARGB Colour::getPixelARGB() const throw()
  63268. {
  63269. PixelARGB p (argb);
  63270. p.premultiply();
  63271. return p;
  63272. }
  63273. uint32 Colour::getARGB() const throw()
  63274. {
  63275. return argb.getARGB();
  63276. }
  63277. bool Colour::isTransparent() const throw()
  63278. {
  63279. return getAlpha() == 0;
  63280. }
  63281. bool Colour::isOpaque() const throw()
  63282. {
  63283. return getAlpha() == 0xff;
  63284. }
  63285. const Colour Colour::withAlpha (const uint8 newAlpha) const throw()
  63286. {
  63287. PixelARGB newCol (argb);
  63288. newCol.setAlpha (newAlpha);
  63289. return Colour (newCol.getARGB());
  63290. }
  63291. const Colour Colour::withAlpha (const float newAlpha) const throw()
  63292. {
  63293. jassert (newAlpha >= 0 && newAlpha <= 1.0f);
  63294. PixelARGB newCol (argb);
  63295. newCol.setAlpha (ColourHelpers::floatAlphaToInt (newAlpha));
  63296. return Colour (newCol.getARGB());
  63297. }
  63298. const Colour Colour::withMultipliedAlpha (const float alphaMultiplier) const throw()
  63299. {
  63300. jassert (alphaMultiplier >= 0);
  63301. PixelARGB newCol (argb);
  63302. newCol.setAlpha ((uint8) jmin (0xff, roundToInt (alphaMultiplier * newCol.getAlpha())));
  63303. return Colour (newCol.getARGB());
  63304. }
  63305. const Colour Colour::overlaidWith (const Colour& src) const throw()
  63306. {
  63307. const int destAlpha = getAlpha();
  63308. if (destAlpha > 0)
  63309. {
  63310. const int invA = 0xff - (int) src.getAlpha();
  63311. const int resA = 0xff - (((0xff - destAlpha) * invA) >> 8);
  63312. if (resA > 0)
  63313. {
  63314. const int da = (invA * destAlpha) / resA;
  63315. return Colour ((uint8) (src.getRed() + ((((int) getRed() - src.getRed()) * da) >> 8)),
  63316. (uint8) (src.getGreen() + ((((int) getGreen() - src.getGreen()) * da) >> 8)),
  63317. (uint8) (src.getBlue() + ((((int) getBlue() - src.getBlue()) * da) >> 8)),
  63318. (uint8) resA);
  63319. }
  63320. return *this;
  63321. }
  63322. else
  63323. {
  63324. return src;
  63325. }
  63326. }
  63327. const Colour Colour::interpolatedWith (const Colour& other, float proportionOfOther) const throw()
  63328. {
  63329. if (proportionOfOther <= 0)
  63330. return *this;
  63331. if (proportionOfOther >= 1.0f)
  63332. return other;
  63333. PixelARGB c1 (getPixelARGB());
  63334. const PixelARGB c2 (other.getPixelARGB());
  63335. c1.tween (c2, roundToInt (proportionOfOther * 255.0f));
  63336. c1.unpremultiply();
  63337. return Colour (c1.getARGB());
  63338. }
  63339. float Colour::getFloatRed() const throw()
  63340. {
  63341. return getRed() / 255.0f;
  63342. }
  63343. float Colour::getFloatGreen() const throw()
  63344. {
  63345. return getGreen() / 255.0f;
  63346. }
  63347. float Colour::getFloatBlue() const throw()
  63348. {
  63349. return getBlue() / 255.0f;
  63350. }
  63351. float Colour::getFloatAlpha() const throw()
  63352. {
  63353. return getAlpha() / 255.0f;
  63354. }
  63355. void Colour::getHSB (float& h, float& s, float& v) const throw()
  63356. {
  63357. const int r = getRed();
  63358. const int g = getGreen();
  63359. const int b = getBlue();
  63360. const int hi = jmax (r, g, b);
  63361. const int lo = jmin (r, g, b);
  63362. if (hi != 0)
  63363. {
  63364. s = (hi - lo) / (float) hi;
  63365. if (s != 0)
  63366. {
  63367. const float invDiff = 1.0f / (hi - lo);
  63368. const float red = (hi - r) * invDiff;
  63369. const float green = (hi - g) * invDiff;
  63370. const float blue = (hi - b) * invDiff;
  63371. if (r == hi)
  63372. h = blue - green;
  63373. else if (g == hi)
  63374. h = 2.0f + red - blue;
  63375. else
  63376. h = 4.0f + green - red;
  63377. h *= 1.0f / 6.0f;
  63378. if (h < 0)
  63379. ++h;
  63380. }
  63381. else
  63382. {
  63383. h = 0;
  63384. }
  63385. }
  63386. else
  63387. {
  63388. s = 0;
  63389. h = 0;
  63390. }
  63391. v = hi / 255.0f;
  63392. }
  63393. float Colour::getHue() const throw()
  63394. {
  63395. float h, s, b;
  63396. getHSB (h, s, b);
  63397. return h;
  63398. }
  63399. const Colour Colour::withHue (const float hue) const throw()
  63400. {
  63401. float h, s, b;
  63402. getHSB (h, s, b);
  63403. return Colour (hue, s, b, getAlpha());
  63404. }
  63405. const Colour Colour::withRotatedHue (const float amountToRotate) const throw()
  63406. {
  63407. float h, s, b;
  63408. getHSB (h, s, b);
  63409. h += amountToRotate;
  63410. h -= floorf (h);
  63411. return Colour (h, s, b, getAlpha());
  63412. }
  63413. float Colour::getSaturation() const throw()
  63414. {
  63415. float h, s, b;
  63416. getHSB (h, s, b);
  63417. return s;
  63418. }
  63419. const Colour Colour::withSaturation (const float saturation) const throw()
  63420. {
  63421. float h, s, b;
  63422. getHSB (h, s, b);
  63423. return Colour (h, saturation, b, getAlpha());
  63424. }
  63425. const Colour Colour::withMultipliedSaturation (const float amount) const throw()
  63426. {
  63427. float h, s, b;
  63428. getHSB (h, s, b);
  63429. return Colour (h, jmin (1.0f, s * amount), b, getAlpha());
  63430. }
  63431. float Colour::getBrightness() const throw()
  63432. {
  63433. float h, s, b;
  63434. getHSB (h, s, b);
  63435. return b;
  63436. }
  63437. const Colour Colour::withBrightness (const float brightness) const throw()
  63438. {
  63439. float h, s, b;
  63440. getHSB (h, s, b);
  63441. return Colour (h, s, brightness, getAlpha());
  63442. }
  63443. const Colour Colour::withMultipliedBrightness (const float amount) const throw()
  63444. {
  63445. float h, s, b;
  63446. getHSB (h, s, b);
  63447. b *= amount;
  63448. if (b > 1.0f)
  63449. b = 1.0f;
  63450. return Colour (h, s, b, getAlpha());
  63451. }
  63452. const Colour Colour::brighter (float amount) const throw()
  63453. {
  63454. amount = 1.0f / (1.0f + amount);
  63455. return Colour ((uint8) (255 - (amount * (255 - getRed()))),
  63456. (uint8) (255 - (amount * (255 - getGreen()))),
  63457. (uint8) (255 - (amount * (255 - getBlue()))),
  63458. getAlpha());
  63459. }
  63460. const Colour Colour::darker (float amount) const throw()
  63461. {
  63462. amount = 1.0f / (1.0f + amount);
  63463. return Colour ((uint8) (amount * getRed()),
  63464. (uint8) (amount * getGreen()),
  63465. (uint8) (amount * getBlue()),
  63466. getAlpha());
  63467. }
  63468. const Colour Colour::greyLevel (const float brightness) throw()
  63469. {
  63470. const uint8 level
  63471. = (uint8) jlimit (0x00, 0xff, roundToInt (brightness * 255.0f));
  63472. return Colour (level, level, level);
  63473. }
  63474. const Colour Colour::contrasting (const float amount) const throw()
  63475. {
  63476. return overlaidWith ((((int) getRed() + (int) getGreen() + (int) getBlue() >= 3 * 128)
  63477. ? Colours::black
  63478. : Colours::white).withAlpha (amount));
  63479. }
  63480. const Colour Colour::contrasting (const Colour& colour1,
  63481. const Colour& colour2) throw()
  63482. {
  63483. const float b1 = colour1.getBrightness();
  63484. const float b2 = colour2.getBrightness();
  63485. float best = 0.0f;
  63486. float bestDist = 0.0f;
  63487. for (float i = 0.0f; i < 1.0f; i += 0.02f)
  63488. {
  63489. const float d1 = fabsf (i - b1);
  63490. const float d2 = fabsf (i - b2);
  63491. const float dist = jmin (d1, d2, 1.0f - d1, 1.0f - d2);
  63492. if (dist > bestDist)
  63493. {
  63494. best = i;
  63495. bestDist = dist;
  63496. }
  63497. }
  63498. return colour1.overlaidWith (colour2.withMultipliedAlpha (0.5f))
  63499. .withBrightness (best);
  63500. }
  63501. const String Colour::toString() const
  63502. {
  63503. return String::toHexString ((int) argb.getARGB());
  63504. }
  63505. const Colour Colour::fromString (const String& encodedColourString)
  63506. {
  63507. return Colour ((uint32) encodedColourString.getHexValue32());
  63508. }
  63509. const String Colour::toDisplayString (const bool includeAlphaValue) const
  63510. {
  63511. return String::toHexString ((int) (argb.getARGB() & (includeAlphaValue ? 0xffffffff : 0xffffff)))
  63512. .paddedLeft ('0', includeAlphaValue ? 8 : 6)
  63513. .toUpperCase();
  63514. }
  63515. END_JUCE_NAMESPACE
  63516. /*** End of inlined file: juce_Colour.cpp ***/
  63517. /*** Start of inlined file: juce_ColourGradient.cpp ***/
  63518. BEGIN_JUCE_NAMESPACE
  63519. ColourGradient::ColourGradient() throw()
  63520. {
  63521. #if JUCE_DEBUG
  63522. x1 = 987654.0f;
  63523. #endif
  63524. }
  63525. ColourGradient::ColourGradient (const Colour& colour1,
  63526. const float x1_,
  63527. const float y1_,
  63528. const Colour& colour2,
  63529. const float x2_,
  63530. const float y2_,
  63531. const bool isRadial_)
  63532. : x1 (x1_),
  63533. y1 (y1_),
  63534. x2 (x2_),
  63535. y2 (y2_),
  63536. isRadial (isRadial_)
  63537. {
  63538. colours.add (0);
  63539. colours.add (colour1.getARGB());
  63540. colours.add (1 << 16);
  63541. colours.add (colour2.getARGB());
  63542. }
  63543. ColourGradient::~ColourGradient()
  63544. {
  63545. }
  63546. void ColourGradient::clearColours()
  63547. {
  63548. colours.clear();
  63549. }
  63550. void ColourGradient::addColour (const double proportionAlongGradient,
  63551. const Colour& colour)
  63552. {
  63553. // must be within the two end-points
  63554. jassert (proportionAlongGradient >= 0 && proportionAlongGradient <= 1.0);
  63555. const uint32 pos = jlimit (0, 65535, roundToInt (proportionAlongGradient * 65536.0));
  63556. int i;
  63557. for (i = 0; i < colours.size(); i += 2)
  63558. if (colours.getUnchecked(i) > pos)
  63559. break;
  63560. colours.insert (i, pos);
  63561. colours.insert (i + 1, colour.getARGB());
  63562. }
  63563. void ColourGradient::multiplyOpacity (const float multiplier) throw()
  63564. {
  63565. for (int i = 1; i < colours.size(); i += 2)
  63566. {
  63567. const Colour c (colours.getUnchecked(i));
  63568. colours.set (i, c.withMultipliedAlpha (multiplier).getARGB());
  63569. }
  63570. }
  63571. int ColourGradient::getNumColours() const throw()
  63572. {
  63573. return colours.size() >> 1;
  63574. }
  63575. double ColourGradient::getColourPosition (const int index) const throw()
  63576. {
  63577. return jlimit (0.0, 1.0, colours [index << 1] / 65535.0);
  63578. }
  63579. const Colour ColourGradient::getColour (const int index) const throw()
  63580. {
  63581. return Colour (colours [(index << 1) + 1]);
  63582. }
  63583. const Colour ColourGradient::getColourAtPosition (const float position) const throw()
  63584. {
  63585. jassert (colours.getUnchecked (0) == 0); // the first colour specified has to go at position 0
  63586. const int integerPos = jlimit (0, 65535, roundToInt (position * 65536.0f));
  63587. if (integerPos <= 0 || colours.size() <= 2)
  63588. return getColour (0);
  63589. int i = colours.size() - 2;
  63590. while (integerPos < (int) colours.getUnchecked(i))
  63591. i -= 2;
  63592. if (i >= colours.size() - 2)
  63593. return Colour (colours.getUnchecked(i));
  63594. const int pos1 = colours.getUnchecked (i);
  63595. const Colour col1 (colours.getUnchecked (i + 1));
  63596. const int pos2 = colours.getUnchecked (i + 2);
  63597. const Colour col2 (colours.getUnchecked (i + 3));
  63598. return col1.interpolatedWith (col2, (integerPos - pos1) / (float) (pos2 - pos1));
  63599. }
  63600. int ColourGradient::createLookupTable (const AffineTransform& transform, HeapBlock <PixelARGB>& lookupTable) const
  63601. {
  63602. #if JUCE_DEBUG
  63603. // trying to use the object without setting its co-ordinates? Have a careful read of
  63604. // the comments for the constructors.
  63605. jassert (x1 != 987654.0f);
  63606. #endif
  63607. const int numColours = colours.size() >> 1;
  63608. float tx1 = x1, ty1 = y1, tx2 = x2, ty2 = y2;
  63609. transform.transformPoint (tx1, ty1);
  63610. transform.transformPoint (tx2, ty2);
  63611. const double distance = juce_hypot (tx1 - tx2, ty1 - ty2);
  63612. const int numEntries = jlimit (1, (numColours - 1) << 8, 3 * (int) distance);
  63613. lookupTable.malloc (numEntries);
  63614. if (numColours >= 2)
  63615. {
  63616. jassert (colours.getUnchecked (0) == 0); // the first colour specified has to go at position 0
  63617. PixelARGB pix1 (colours.getUnchecked (1));
  63618. pix1.premultiply();
  63619. int index = 0;
  63620. for (int j = 2; j < colours.size(); j += 2)
  63621. {
  63622. const int numToDo = ((colours.getUnchecked (j) * (numEntries - 1)) >> 16) - index;
  63623. PixelARGB pix2 (colours.getUnchecked (j + 1));
  63624. pix2.premultiply();
  63625. for (int i = 0; i < numToDo; ++i)
  63626. {
  63627. jassert (index >= 0 && index < numEntries);
  63628. lookupTable[index] = pix1;
  63629. lookupTable[index].tween (pix2, (i << 8) / numToDo);
  63630. ++index;
  63631. }
  63632. pix1 = pix2;
  63633. }
  63634. while (index < numEntries)
  63635. lookupTable [index++] = pix1;
  63636. }
  63637. else
  63638. {
  63639. jassertfalse // no colours specified!
  63640. }
  63641. return numEntries;
  63642. }
  63643. bool ColourGradient::isOpaque() const throw()
  63644. {
  63645. for (int i = 1; i < colours.size(); i += 2)
  63646. if (PixelARGB (colours.getUnchecked(i)).getAlpha() < 0xff)
  63647. return false;
  63648. return true;
  63649. }
  63650. bool ColourGradient::isInvisible() const throw()
  63651. {
  63652. for (int i = 1; i < colours.size(); i += 2)
  63653. if (PixelARGB (colours.getUnchecked(i)).getAlpha() > 0)
  63654. return false;
  63655. return true;
  63656. }
  63657. END_JUCE_NAMESPACE
  63658. /*** End of inlined file: juce_ColourGradient.cpp ***/
  63659. /*** Start of inlined file: juce_Colours.cpp ***/
  63660. BEGIN_JUCE_NAMESPACE
  63661. const Colour Colours::transparentBlack (0);
  63662. const Colour Colours::transparentWhite (0x00ffffff);
  63663. const Colour Colours::aliceblue (0xfff0f8ff);
  63664. const Colour Colours::antiquewhite (0xfffaebd7);
  63665. const Colour Colours::aqua (0xff00ffff);
  63666. const Colour Colours::aquamarine (0xff7fffd4);
  63667. const Colour Colours::azure (0xfff0ffff);
  63668. const Colour Colours::beige (0xfff5f5dc);
  63669. const Colour Colours::bisque (0xffffe4c4);
  63670. const Colour Colours::black (0xff000000);
  63671. const Colour Colours::blanchedalmond (0xffffebcd);
  63672. const Colour Colours::blue (0xff0000ff);
  63673. const Colour Colours::blueviolet (0xff8a2be2);
  63674. const Colour Colours::brown (0xffa52a2a);
  63675. const Colour Colours::burlywood (0xffdeb887);
  63676. const Colour Colours::cadetblue (0xff5f9ea0);
  63677. const Colour Colours::chartreuse (0xff7fff00);
  63678. const Colour Colours::chocolate (0xffd2691e);
  63679. const Colour Colours::coral (0xffff7f50);
  63680. const Colour Colours::cornflowerblue (0xff6495ed);
  63681. const Colour Colours::cornsilk (0xfffff8dc);
  63682. const Colour Colours::crimson (0xffdc143c);
  63683. const Colour Colours::cyan (0xff00ffff);
  63684. const Colour Colours::darkblue (0xff00008b);
  63685. const Colour Colours::darkcyan (0xff008b8b);
  63686. const Colour Colours::darkgoldenrod (0xffb8860b);
  63687. const Colour Colours::darkgrey (0xff555555);
  63688. const Colour Colours::darkgreen (0xff006400);
  63689. const Colour Colours::darkkhaki (0xffbdb76b);
  63690. const Colour Colours::darkmagenta (0xff8b008b);
  63691. const Colour Colours::darkolivegreen (0xff556b2f);
  63692. const Colour Colours::darkorange (0xffff8c00);
  63693. const Colour Colours::darkorchid (0xff9932cc);
  63694. const Colour Colours::darkred (0xff8b0000);
  63695. const Colour Colours::darksalmon (0xffe9967a);
  63696. const Colour Colours::darkseagreen (0xff8fbc8f);
  63697. const Colour Colours::darkslateblue (0xff483d8b);
  63698. const Colour Colours::darkslategrey (0xff2f4f4f);
  63699. const Colour Colours::darkturquoise (0xff00ced1);
  63700. const Colour Colours::darkviolet (0xff9400d3);
  63701. const Colour Colours::deeppink (0xffff1493);
  63702. const Colour Colours::deepskyblue (0xff00bfff);
  63703. const Colour Colours::dimgrey (0xff696969);
  63704. const Colour Colours::dodgerblue (0xff1e90ff);
  63705. const Colour Colours::firebrick (0xffb22222);
  63706. const Colour Colours::floralwhite (0xfffffaf0);
  63707. const Colour Colours::forestgreen (0xff228b22);
  63708. const Colour Colours::fuchsia (0xffff00ff);
  63709. const Colour Colours::gainsboro (0xffdcdcdc);
  63710. const Colour Colours::gold (0xffffd700);
  63711. const Colour Colours::goldenrod (0xffdaa520);
  63712. const Colour Colours::grey (0xff808080);
  63713. const Colour Colours::green (0xff008000);
  63714. const Colour Colours::greenyellow (0xffadff2f);
  63715. const Colour Colours::honeydew (0xfff0fff0);
  63716. const Colour Colours::hotpink (0xffff69b4);
  63717. const Colour Colours::indianred (0xffcd5c5c);
  63718. const Colour Colours::indigo (0xff4b0082);
  63719. const Colour Colours::ivory (0xfffffff0);
  63720. const Colour Colours::khaki (0xfff0e68c);
  63721. const Colour Colours::lavender (0xffe6e6fa);
  63722. const Colour Colours::lavenderblush (0xfffff0f5);
  63723. const Colour Colours::lemonchiffon (0xfffffacd);
  63724. const Colour Colours::lightblue (0xffadd8e6);
  63725. const Colour Colours::lightcoral (0xfff08080);
  63726. const Colour Colours::lightcyan (0xffe0ffff);
  63727. const Colour Colours::lightgoldenrodyellow (0xfffafad2);
  63728. const Colour Colours::lightgreen (0xff90ee90);
  63729. const Colour Colours::lightgrey (0xffd3d3d3);
  63730. const Colour Colours::lightpink (0xffffb6c1);
  63731. const Colour Colours::lightsalmon (0xffffa07a);
  63732. const Colour Colours::lightseagreen (0xff20b2aa);
  63733. const Colour Colours::lightskyblue (0xff87cefa);
  63734. const Colour Colours::lightslategrey (0xff778899);
  63735. const Colour Colours::lightsteelblue (0xffb0c4de);
  63736. const Colour Colours::lightyellow (0xffffffe0);
  63737. const Colour Colours::lime (0xff00ff00);
  63738. const Colour Colours::limegreen (0xff32cd32);
  63739. const Colour Colours::linen (0xfffaf0e6);
  63740. const Colour Colours::magenta (0xffff00ff);
  63741. const Colour Colours::maroon (0xff800000);
  63742. const Colour Colours::mediumaquamarine (0xff66cdaa);
  63743. const Colour Colours::mediumblue (0xff0000cd);
  63744. const Colour Colours::mediumorchid (0xffba55d3);
  63745. const Colour Colours::mediumpurple (0xff9370db);
  63746. const Colour Colours::mediumseagreen (0xff3cb371);
  63747. const Colour Colours::mediumslateblue (0xff7b68ee);
  63748. const Colour Colours::mediumspringgreen (0xff00fa9a);
  63749. const Colour Colours::mediumturquoise (0xff48d1cc);
  63750. const Colour Colours::mediumvioletred (0xffc71585);
  63751. const Colour Colours::midnightblue (0xff191970);
  63752. const Colour Colours::mintcream (0xfff5fffa);
  63753. const Colour Colours::mistyrose (0xffffe4e1);
  63754. const Colour Colours::navajowhite (0xffffdead);
  63755. const Colour Colours::navy (0xff000080);
  63756. const Colour Colours::oldlace (0xfffdf5e6);
  63757. const Colour Colours::olive (0xff808000);
  63758. const Colour Colours::olivedrab (0xff6b8e23);
  63759. const Colour Colours::orange (0xffffa500);
  63760. const Colour Colours::orangered (0xffff4500);
  63761. const Colour Colours::orchid (0xffda70d6);
  63762. const Colour Colours::palegoldenrod (0xffeee8aa);
  63763. const Colour Colours::palegreen (0xff98fb98);
  63764. const Colour Colours::paleturquoise (0xffafeeee);
  63765. const Colour Colours::palevioletred (0xffdb7093);
  63766. const Colour Colours::papayawhip (0xffffefd5);
  63767. const Colour Colours::peachpuff (0xffffdab9);
  63768. const Colour Colours::peru (0xffcd853f);
  63769. const Colour Colours::pink (0xffffc0cb);
  63770. const Colour Colours::plum (0xffdda0dd);
  63771. const Colour Colours::powderblue (0xffb0e0e6);
  63772. const Colour Colours::purple (0xff800080);
  63773. const Colour Colours::red (0xffff0000);
  63774. const Colour Colours::rosybrown (0xffbc8f8f);
  63775. const Colour Colours::royalblue (0xff4169e1);
  63776. const Colour Colours::saddlebrown (0xff8b4513);
  63777. const Colour Colours::salmon (0xfffa8072);
  63778. const Colour Colours::sandybrown (0xfff4a460);
  63779. const Colour Colours::seagreen (0xff2e8b57);
  63780. const Colour Colours::seashell (0xfffff5ee);
  63781. const Colour Colours::sienna (0xffa0522d);
  63782. const Colour Colours::silver (0xffc0c0c0);
  63783. const Colour Colours::skyblue (0xff87ceeb);
  63784. const Colour Colours::slateblue (0xff6a5acd);
  63785. const Colour Colours::slategrey (0xff708090);
  63786. const Colour Colours::snow (0xfffffafa);
  63787. const Colour Colours::springgreen (0xff00ff7f);
  63788. const Colour Colours::steelblue (0xff4682b4);
  63789. const Colour Colours::tan (0xffd2b48c);
  63790. const Colour Colours::teal (0xff008080);
  63791. const Colour Colours::thistle (0xffd8bfd8);
  63792. const Colour Colours::tomato (0xffff6347);
  63793. const Colour Colours::turquoise (0xff40e0d0);
  63794. const Colour Colours::violet (0xffee82ee);
  63795. const Colour Colours::wheat (0xfff5deb3);
  63796. const Colour Colours::white (0xffffffff);
  63797. const Colour Colours::whitesmoke (0xfff5f5f5);
  63798. const Colour Colours::yellow (0xffffff00);
  63799. const Colour Colours::yellowgreen (0xff9acd32);
  63800. const Colour Colours::findColourForName (const String& colourName,
  63801. const Colour& defaultColour)
  63802. {
  63803. static const int presets[] =
  63804. {
  63805. // (first value is the string's hashcode, second is ARGB)
  63806. 0x05978fff, 0xff000000, /* black */
  63807. 0x06bdcc29, 0xffffffff, /* white */
  63808. 0x002e305a, 0xff0000ff, /* blue */
  63809. 0x00308adf, 0xff808080, /* grey */
  63810. 0x05e0cf03, 0xff008000, /* green */
  63811. 0x0001b891, 0xffff0000, /* red */
  63812. 0xd43c6474, 0xffffff00, /* yellow */
  63813. 0x620886da, 0xfff0f8ff, /* aliceblue */
  63814. 0x20a2676a, 0xfffaebd7, /* antiquewhite */
  63815. 0x002dcebc, 0xff00ffff, /* aqua */
  63816. 0x46bb5f7e, 0xff7fffd4, /* aquamarine */
  63817. 0x0590228f, 0xfff0ffff, /* azure */
  63818. 0x05947fe4, 0xfff5f5dc, /* beige */
  63819. 0xad388e35, 0xffffe4c4, /* bisque */
  63820. 0x00674f7e, 0xffffebcd, /* blanchedalmond */
  63821. 0x39129959, 0xff8a2be2, /* blueviolet */
  63822. 0x059a8136, 0xffa52a2a, /* brown */
  63823. 0x89cea8f9, 0xffdeb887, /* burlywood */
  63824. 0x0fa260cf, 0xff5f9ea0, /* cadetblue */
  63825. 0x6b748956, 0xff7fff00, /* chartreuse */
  63826. 0x2903623c, 0xffd2691e, /* chocolate */
  63827. 0x05a74431, 0xffff7f50, /* coral */
  63828. 0x618d42dd, 0xff6495ed, /* cornflowerblue */
  63829. 0xe4b479fd, 0xfffff8dc, /* cornsilk */
  63830. 0x3d8c4edf, 0xffdc143c, /* crimson */
  63831. 0x002ed323, 0xff00ffff, /* cyan */
  63832. 0x67cc74d0, 0xff00008b, /* darkblue */
  63833. 0x67cd1799, 0xff008b8b, /* darkcyan */
  63834. 0x31bbd168, 0xffb8860b, /* darkgoldenrod */
  63835. 0x67cecf55, 0xff555555, /* darkgrey */
  63836. 0x920b194d, 0xff006400, /* darkgreen */
  63837. 0x923edd4c, 0xffbdb76b, /* darkkhaki */
  63838. 0x5c293873, 0xff8b008b, /* darkmagenta */
  63839. 0x6b6671fe, 0xff556b2f, /* darkolivegreen */
  63840. 0xbcfd2524, 0xffff8c00, /* darkorange */
  63841. 0xbcfdf799, 0xff9932cc, /* darkorchid */
  63842. 0x55ee0d5b, 0xff8b0000, /* darkred */
  63843. 0xc2e5f564, 0xffe9967a, /* darksalmon */
  63844. 0x61be858a, 0xff8fbc8f, /* darkseagreen */
  63845. 0xc2b0f2bd, 0xff483d8b, /* darkslateblue */
  63846. 0xc2b34d42, 0xff2f4f4f, /* darkslategrey */
  63847. 0x7cf2b06b, 0xff00ced1, /* darkturquoise */
  63848. 0xc8769375, 0xff9400d3, /* darkviolet */
  63849. 0x25832862, 0xffff1493, /* deeppink */
  63850. 0xfcad568f, 0xff00bfff, /* deepskyblue */
  63851. 0x634c8b67, 0xff696969, /* dimgrey */
  63852. 0x45c1ce55, 0xff1e90ff, /* dodgerblue */
  63853. 0xef19e3cb, 0xffb22222, /* firebrick */
  63854. 0xb852b195, 0xfffffaf0, /* floralwhite */
  63855. 0xd086fd06, 0xff228b22, /* forestgreen */
  63856. 0xe106b6d7, 0xffff00ff, /* fuchsia */
  63857. 0x7880d61e, 0xffdcdcdc, /* gainsboro */
  63858. 0x00308060, 0xffffd700, /* gold */
  63859. 0xb3b3bc1e, 0xffdaa520, /* goldenrod */
  63860. 0xbab8a537, 0xffadff2f, /* greenyellow */
  63861. 0xe4cacafb, 0xfff0fff0, /* honeydew */
  63862. 0x41892743, 0xffff69b4, /* hotpink */
  63863. 0xd5796f1a, 0xffcd5c5c, /* indianred */
  63864. 0xb969fed2, 0xff4b0082, /* indigo */
  63865. 0x05fef6a9, 0xfffffff0, /* ivory */
  63866. 0x06149302, 0xfff0e68c, /* khaki */
  63867. 0xad5a05c7, 0xffe6e6fa, /* lavender */
  63868. 0x7c4d5b99, 0xfffff0f5, /* lavenderblush */
  63869. 0x195756f0, 0xfffffacd, /* lemonchiffon */
  63870. 0x28e4ea70, 0xffadd8e6, /* lightblue */
  63871. 0xf3c7ccdb, 0xfff08080, /* lightcoral */
  63872. 0x28e58d39, 0xffe0ffff, /* lightcyan */
  63873. 0x21234e3c, 0xfffafad2, /* lightgoldenrodyellow */
  63874. 0xf40157ad, 0xff90ee90, /* lightgreen */
  63875. 0x28e744f5, 0xffd3d3d3, /* lightgrey */
  63876. 0x28eb3b8c, 0xffffb6c1, /* lightpink */
  63877. 0x9fb78304, 0xffffa07a, /* lightsalmon */
  63878. 0x50632b2a, 0xff20b2aa, /* lightseagreen */
  63879. 0x68fb7b25, 0xff87cefa, /* lightskyblue */
  63880. 0xa8a35ba2, 0xff778899, /* lightslategrey */
  63881. 0xa20d484f, 0xffb0c4de, /* lightsteelblue */
  63882. 0xaa2cf10a, 0xffffffe0, /* lightyellow */
  63883. 0x0032afd5, 0xff00ff00, /* lime */
  63884. 0x607bbc4e, 0xff32cd32, /* limegreen */
  63885. 0x06234efa, 0xfffaf0e6, /* linen */
  63886. 0x316858a9, 0xffff00ff, /* magenta */
  63887. 0xbf8ca470, 0xff800000, /* maroon */
  63888. 0xbd58e0b3, 0xff66cdaa, /* mediumaquamarine */
  63889. 0x967dfd4f, 0xff0000cd, /* mediumblue */
  63890. 0x056f5c58, 0xffba55d3, /* mediumorchid */
  63891. 0x07556b71, 0xff9370db, /* mediumpurple */
  63892. 0x5369b689, 0xff3cb371, /* mediumseagreen */
  63893. 0x066be19e, 0xff7b68ee, /* mediumslateblue */
  63894. 0x3256b281, 0xff00fa9a, /* mediumspringgreen */
  63895. 0xc0ad9f4c, 0xff48d1cc, /* mediumturquoise */
  63896. 0x628e63dd, 0xffc71585, /* mediumvioletred */
  63897. 0x168eb32a, 0xff191970, /* midnightblue */
  63898. 0x4306b960, 0xfff5fffa, /* mintcream */
  63899. 0x4cbc0e6b, 0xffffe4e1, /* mistyrose */
  63900. 0xe97218a6, 0xffffdead, /* navajowhite */
  63901. 0x00337bb6, 0xff000080, /* navy */
  63902. 0xadd2d33e, 0xfffdf5e6, /* oldlace */
  63903. 0x064ee1db, 0xff808000, /* olive */
  63904. 0x9e33a98a, 0xff6b8e23, /* olivedrab */
  63905. 0xc3de262e, 0xffffa500, /* orange */
  63906. 0x58bebba3, 0xffff4500, /* orangered */
  63907. 0xc3def8a3, 0xffda70d6, /* orchid */
  63908. 0x28cb4834, 0xffeee8aa, /* palegoldenrod */
  63909. 0x3d9dd619, 0xff98fb98, /* palegreen */
  63910. 0x74022737, 0xffafeeee, /* paleturquoise */
  63911. 0x15e2ebc8, 0xffdb7093, /* palevioletred */
  63912. 0x5fd898e2, 0xffffefd5, /* papayawhip */
  63913. 0x93e1b776, 0xffffdab9, /* peachpuff */
  63914. 0x003472f8, 0xffcd853f, /* peru */
  63915. 0x00348176, 0xffffc0cb, /* pink */
  63916. 0x00348d94, 0xffdda0dd, /* plum */
  63917. 0xd036be93, 0xffb0e0e6, /* powderblue */
  63918. 0xc5c507bc, 0xff800080, /* purple */
  63919. 0xa89d65b3, 0xffbc8f8f, /* rosybrown */
  63920. 0xbd9413e1, 0xff4169e1, /* royalblue */
  63921. 0xf456044f, 0xff8b4513, /* saddlebrown */
  63922. 0xc9c6f66e, 0xfffa8072, /* salmon */
  63923. 0x0bb131e1, 0xfff4a460, /* sandybrown */
  63924. 0x34636c14, 0xff2e8b57, /* seagreen */
  63925. 0x3507fb41, 0xfffff5ee, /* seashell */
  63926. 0xca348772, 0xffa0522d, /* sienna */
  63927. 0xca37d30d, 0xffc0c0c0, /* silver */
  63928. 0x80da74fb, 0xff87ceeb, /* skyblue */
  63929. 0x44a8dd73, 0xff6a5acd, /* slateblue */
  63930. 0x44ab37f8, 0xff708090, /* slategrey */
  63931. 0x0035f183, 0xfffffafa, /* snow */
  63932. 0xd5440d16, 0xff00ff7f, /* springgreen */
  63933. 0x3e1524a5, 0xff4682b4, /* steelblue */
  63934. 0x0001bfa1, 0xffd2b48c, /* tan */
  63935. 0x0036425c, 0xff008080, /* teal */
  63936. 0xafc8858f, 0xffd8bfd8, /* thistle */
  63937. 0xcc41600a, 0xffff6347, /* tomato */
  63938. 0xfeea9b21, 0xff40e0d0, /* turquoise */
  63939. 0xcf57947f, 0xffee82ee, /* violet */
  63940. 0x06bdbae7, 0xfff5deb3, /* wheat */
  63941. 0x10802ee6, 0xfff5f5f5, /* whitesmoke */
  63942. 0xe1b5130f, 0xff9acd32 /* yellowgreen */
  63943. };
  63944. const int hash = colourName.trim().toLowerCase().hashCode();
  63945. for (int i = 0; i < numElementsInArray (presets); i += 2)
  63946. if (presets [i] == hash)
  63947. return Colour (presets [i + 1]);
  63948. return defaultColour;
  63949. }
  63950. END_JUCE_NAMESPACE
  63951. /*** End of inlined file: juce_Colours.cpp ***/
  63952. /*** Start of inlined file: juce_EdgeTable.cpp ***/
  63953. BEGIN_JUCE_NAMESPACE
  63954. const int juce_edgeTableDefaultEdgesPerLine = 32;
  63955. EdgeTable::EdgeTable (const Rectangle<int>& bounds_,
  63956. const Path& path, const AffineTransform& transform)
  63957. : bounds (bounds_),
  63958. maxEdgesPerLine (juce_edgeTableDefaultEdgesPerLine),
  63959. lineStrideElements ((juce_edgeTableDefaultEdgesPerLine << 1) + 1),
  63960. needToCheckEmptinesss (true)
  63961. {
  63962. table.malloc ((bounds.getHeight() + 1) * lineStrideElements);
  63963. int* t = table;
  63964. for (int i = bounds.getHeight(); --i >= 0;)
  63965. {
  63966. *t = 0;
  63967. t += lineStrideElements;
  63968. }
  63969. const int topLimit = bounds.getY() << 8;
  63970. const int heightLimit = bounds.getHeight() << 8;
  63971. const int leftLimit = bounds.getX() << 8;
  63972. const int rightLimit = bounds.getRight() << 8;
  63973. PathFlatteningIterator iter (path, transform);
  63974. while (iter.next())
  63975. {
  63976. int y1 = roundToInt (iter.y1 * 256.0f);
  63977. int y2 = roundToInt (iter.y2 * 256.0f);
  63978. if (y1 != y2)
  63979. {
  63980. y1 -= topLimit;
  63981. y2 -= topLimit;
  63982. const int startY = y1;
  63983. int direction = -1;
  63984. if (y1 > y2)
  63985. {
  63986. swapVariables (y1, y2);
  63987. direction = 1;
  63988. }
  63989. if (y1 < 0)
  63990. y1 = 0;
  63991. if (y2 > heightLimit)
  63992. y2 = heightLimit;
  63993. if (y1 < y2)
  63994. {
  63995. const double startX = 256.0f * iter.x1;
  63996. const double multiplier = (iter.x2 - iter.x1) / (iter.y2 - iter.y1);
  63997. const int stepSize = jlimit (1, 256, 256 / (1 + (int) fabs (multiplier)));
  63998. do
  63999. {
  64000. const int step = jmin (stepSize, y2 - y1, 256 - (y1 & 255));
  64001. int x = roundToInt (startX + multiplier * ((y1 + (step >> 1)) - startY));
  64002. if (x < leftLimit)
  64003. x = leftLimit;
  64004. else if (x >= rightLimit)
  64005. x = rightLimit - 1;
  64006. addEdgePoint (x, y1 >> 8, direction * step);
  64007. y1 += step;
  64008. }
  64009. while (y1 < y2);
  64010. }
  64011. }
  64012. }
  64013. sanitiseLevels (path.isUsingNonZeroWinding());
  64014. }
  64015. EdgeTable::EdgeTable (const Rectangle<int>& rectangleToAdd)
  64016. : bounds (rectangleToAdd),
  64017. maxEdgesPerLine (juce_edgeTableDefaultEdgesPerLine),
  64018. lineStrideElements ((juce_edgeTableDefaultEdgesPerLine << 1) + 1),
  64019. needToCheckEmptinesss (true)
  64020. {
  64021. table.malloc (jmax (1, bounds.getHeight()) * lineStrideElements);
  64022. table[0] = 0;
  64023. const int x1 = rectangleToAdd.getX() << 8;
  64024. const int x2 = rectangleToAdd.getRight() << 8;
  64025. int* t = table;
  64026. for (int i = rectangleToAdd.getHeight(); --i >= 0;)
  64027. {
  64028. t[0] = 2;
  64029. t[1] = x1;
  64030. t[2] = 255;
  64031. t[3] = x2;
  64032. t[4] = 0;
  64033. t += lineStrideElements;
  64034. }
  64035. }
  64036. EdgeTable::EdgeTable (const RectangleList& rectanglesToAdd)
  64037. : bounds (rectanglesToAdd.getBounds()),
  64038. maxEdgesPerLine (juce_edgeTableDefaultEdgesPerLine),
  64039. lineStrideElements ((juce_edgeTableDefaultEdgesPerLine << 1) + 1),
  64040. needToCheckEmptinesss (true)
  64041. {
  64042. table.malloc (jmax (1, bounds.getHeight()) * lineStrideElements);
  64043. int* t = table;
  64044. for (int i = bounds.getHeight(); --i >= 0;)
  64045. {
  64046. *t = 0;
  64047. t += lineStrideElements;
  64048. }
  64049. for (RectangleList::Iterator iter (rectanglesToAdd); iter.next();)
  64050. {
  64051. const Rectangle<int>* const r = iter.getRectangle();
  64052. const int x1 = r->getX() << 8;
  64053. const int x2 = r->getRight() << 8;
  64054. int y = r->getY() - bounds.getY();
  64055. for (int j = r->getHeight(); --j >= 0;)
  64056. {
  64057. addEdgePoint (x1, y, 255);
  64058. addEdgePoint (x2, y, -255);
  64059. ++y;
  64060. }
  64061. }
  64062. sanitiseLevels (true);
  64063. }
  64064. EdgeTable::EdgeTable (const float x, const float y, const float w, const float h)
  64065. : bounds (Rectangle<int> ((int) floorf (x), roundToInt (y * 256.0f) >> 8, 2 + (int) w, 2 + (int) h)),
  64066. maxEdgesPerLine (juce_edgeTableDefaultEdgesPerLine),
  64067. lineStrideElements ((juce_edgeTableDefaultEdgesPerLine << 1) + 1),
  64068. needToCheckEmptinesss (true)
  64069. {
  64070. jassert (w > 0 && h > 0);
  64071. table.malloc (jmax (1, bounds.getHeight()) * lineStrideElements);
  64072. table[0] = 0;
  64073. const int x1 = roundToInt (x * 256.0f);
  64074. const int x2 = roundToInt ((x + w) * 256.0f);
  64075. int y1 = roundToInt (y * 256.0f) - (bounds.getY() << 8);
  64076. jassert (y1 < 256);
  64077. int y2 = roundToInt ((y + h) * 256.0f) - (bounds.getY() << 8);
  64078. if (x2 <= x1 || y2 <= y1)
  64079. {
  64080. bounds.setHeight (0);
  64081. return;
  64082. }
  64083. int lineY = 0;
  64084. int* t = table;
  64085. if ((y1 >> 8) == (y2 >> 8))
  64086. {
  64087. t[0] = 2;
  64088. t[1] = x1;
  64089. t[2] = y2 - y1;
  64090. t[3] = x2;
  64091. t[4] = 0;
  64092. ++lineY;
  64093. t += lineStrideElements;
  64094. }
  64095. else
  64096. {
  64097. t[0] = 2;
  64098. t[1] = x1;
  64099. t[2] = 255 - (y1 & 255);
  64100. t[3] = x2;
  64101. t[4] = 0;
  64102. ++lineY;
  64103. t += lineStrideElements;
  64104. while (lineY < (y2 >> 8))
  64105. {
  64106. t[0] = 2;
  64107. t[1] = x1;
  64108. t[2] = 255;
  64109. t[3] = x2;
  64110. t[4] = 0;
  64111. ++lineY;
  64112. t += lineStrideElements;
  64113. }
  64114. jassert (lineY < bounds.getHeight());
  64115. t[0] = 2;
  64116. t[1] = x1;
  64117. t[2] = y2 & 255;
  64118. t[3] = x2;
  64119. t[4] = 0;
  64120. ++lineY;
  64121. t += lineStrideElements;
  64122. }
  64123. while (lineY < bounds.getHeight())
  64124. {
  64125. t[0] = 0;
  64126. t += lineStrideElements;
  64127. ++lineY;
  64128. }
  64129. }
  64130. EdgeTable::EdgeTable (const EdgeTable& other)
  64131. : table (0)
  64132. {
  64133. operator= (other);
  64134. }
  64135. EdgeTable& EdgeTable::operator= (const EdgeTable& other)
  64136. {
  64137. bounds = other.bounds;
  64138. maxEdgesPerLine = other.maxEdgesPerLine;
  64139. lineStrideElements = other.lineStrideElements;
  64140. needToCheckEmptinesss = other.needToCheckEmptinesss;
  64141. table.malloc (jmax (1, bounds.getHeight()) * lineStrideElements);
  64142. copyEdgeTableData (table, lineStrideElements, other.table, lineStrideElements, bounds.getHeight());
  64143. return *this;
  64144. }
  64145. EdgeTable::~EdgeTable()
  64146. {
  64147. }
  64148. void EdgeTable::copyEdgeTableData (int* dest, const int destLineStride, const int* src, const int srcLineStride, int numLines) throw()
  64149. {
  64150. while (--numLines >= 0)
  64151. {
  64152. memcpy (dest, src, (src[0] * 2 + 1) * sizeof (int));
  64153. src += srcLineStride;
  64154. dest += destLineStride;
  64155. }
  64156. }
  64157. void EdgeTable::sanitiseLevels (const bool useNonZeroWinding) throw()
  64158. {
  64159. // Convert the table from relative windings to absolute levels..
  64160. int* lineStart = table;
  64161. for (int i = bounds.getHeight(); --i >= 0;)
  64162. {
  64163. int* line = lineStart;
  64164. lineStart += lineStrideElements;
  64165. int num = *line;
  64166. if (num == 0)
  64167. continue;
  64168. int level = 0;
  64169. if (useNonZeroWinding)
  64170. {
  64171. while (--num > 0)
  64172. {
  64173. line += 2;
  64174. level += *line;
  64175. int corrected = abs (level);
  64176. if (corrected >> 8)
  64177. corrected = 255;
  64178. *line = corrected;
  64179. }
  64180. }
  64181. else
  64182. {
  64183. while (--num > 0)
  64184. {
  64185. line += 2;
  64186. level += *line;
  64187. int corrected = abs (level);
  64188. if (corrected >> 8)
  64189. {
  64190. corrected &= 511;
  64191. if (corrected >> 8)
  64192. corrected = 511 - corrected;
  64193. }
  64194. *line = corrected;
  64195. }
  64196. }
  64197. line[2] = 0; // force the last level to 0, just in case something went wrong in creating the table
  64198. }
  64199. }
  64200. void EdgeTable::remapTableForNumEdges (const int newNumEdgesPerLine) throw()
  64201. {
  64202. if (newNumEdgesPerLine != maxEdgesPerLine)
  64203. {
  64204. maxEdgesPerLine = newNumEdgesPerLine;
  64205. jassert (bounds.getHeight() > 0);
  64206. const int newLineStrideElements = maxEdgesPerLine * 2 + 1;
  64207. HeapBlock <int> newTable (bounds.getHeight() * newLineStrideElements);
  64208. copyEdgeTableData (newTable, newLineStrideElements, table, lineStrideElements, bounds.getHeight());
  64209. table.swapWith (newTable);
  64210. lineStrideElements = newLineStrideElements;
  64211. }
  64212. }
  64213. void EdgeTable::optimiseTable() throw()
  64214. {
  64215. int maxLineElements = 0;
  64216. for (int i = bounds.getHeight(); --i >= 0;)
  64217. maxLineElements = jmax (maxLineElements, table [i * lineStrideElements]);
  64218. remapTableForNumEdges (maxLineElements);
  64219. }
  64220. void EdgeTable::addEdgePoint (const int x, const int y, const int winding) throw()
  64221. {
  64222. jassert (y >= 0 && y < bounds.getHeight());
  64223. int* line = table + lineStrideElements * y;
  64224. const int numPoints = line[0];
  64225. int n = numPoints << 1;
  64226. if (n > 0)
  64227. {
  64228. while (n > 0)
  64229. {
  64230. const int cx = line [n - 1];
  64231. if (cx <= x)
  64232. {
  64233. if (cx == x)
  64234. {
  64235. line [n] += winding;
  64236. return;
  64237. }
  64238. break;
  64239. }
  64240. n -= 2;
  64241. }
  64242. if (numPoints >= maxEdgesPerLine)
  64243. {
  64244. remapTableForNumEdges (maxEdgesPerLine + juce_edgeTableDefaultEdgesPerLine);
  64245. jassert (numPoints < maxEdgesPerLine);
  64246. line = table + lineStrideElements * y;
  64247. }
  64248. memmove (line + (n + 3), line + (n + 1), sizeof (int) * ((numPoints << 1) - n));
  64249. }
  64250. line [n + 1] = x;
  64251. line [n + 2] = winding;
  64252. line[0]++;
  64253. }
  64254. void EdgeTable::translate (float dx, int dy) throw()
  64255. {
  64256. bounds.setPosition (bounds.getX() + (int) floorf (dx), bounds.getY() + dy);
  64257. int* lineStart = table;
  64258. const int intDx = (int) (dx * 256.0f);
  64259. for (int i = bounds.getHeight(); --i >= 0;)
  64260. {
  64261. int* line = lineStart;
  64262. lineStart += lineStrideElements;
  64263. int num = *line++;
  64264. while (--num >= 0)
  64265. {
  64266. *line += intDx;
  64267. line += 2;
  64268. }
  64269. }
  64270. }
  64271. void EdgeTable::intersectWithEdgeTableLine (const int y, const int* otherLine) throw()
  64272. {
  64273. jassert (y >= 0 && y < bounds.getHeight());
  64274. int* dest = table + lineStrideElements * y;
  64275. if (dest[0] == 0)
  64276. return;
  64277. int otherNumPoints = *otherLine;
  64278. if (otherNumPoints == 0)
  64279. {
  64280. *dest = 0;
  64281. return;
  64282. }
  64283. const int right = bounds.getRight() << 8;
  64284. // optimise for the common case where our line lies entirely within a
  64285. // single pair of points, as happens when clipping to a simple rect.
  64286. if (otherNumPoints == 2 && otherLine[2] >= 255)
  64287. {
  64288. clipEdgeTableLineToRange (dest, otherLine[1], jmin (right, otherLine[3]));
  64289. return;
  64290. }
  64291. ++otherLine;
  64292. const size_t lineSizeBytes = (dest[0] * 2 + 1) * sizeof (int);
  64293. int* temp = (int*) alloca (lineSizeBytes);
  64294. memcpy (temp, dest, lineSizeBytes);
  64295. const int* src1 = temp;
  64296. int srcNum1 = *src1++;
  64297. int x1 = *src1++;
  64298. const int* src2 = otherLine;
  64299. int srcNum2 = otherNumPoints;
  64300. int x2 = *src2++;
  64301. int destIndex = 0, destTotal = 0;
  64302. int level1 = 0, level2 = 0;
  64303. int lastX = std::numeric_limits<int>::min(), lastLevel = 0;
  64304. while (srcNum1 > 0 && srcNum2 > 0)
  64305. {
  64306. int nextX;
  64307. if (x1 < x2)
  64308. {
  64309. nextX = x1;
  64310. level1 = *src1++;
  64311. x1 = *src1++;
  64312. --srcNum1;
  64313. }
  64314. else if (x1 == x2)
  64315. {
  64316. nextX = x1;
  64317. level1 = *src1++;
  64318. level2 = *src2++;
  64319. x1 = *src1++;
  64320. x2 = *src2++;
  64321. --srcNum1;
  64322. --srcNum2;
  64323. }
  64324. else
  64325. {
  64326. nextX = x2;
  64327. level2 = *src2++;
  64328. x2 = *src2++;
  64329. --srcNum2;
  64330. }
  64331. if (nextX > lastX)
  64332. {
  64333. if (nextX >= right)
  64334. break;
  64335. lastX = nextX;
  64336. const int nextLevel = (level1 * (level2 + 1)) >> 8;
  64337. jassert (((unsigned int) nextLevel) < (unsigned int) 256);
  64338. if (nextLevel != lastLevel)
  64339. {
  64340. if (destTotal >= maxEdgesPerLine)
  64341. {
  64342. dest[0] = destTotal;
  64343. remapTableForNumEdges (maxEdgesPerLine + juce_edgeTableDefaultEdgesPerLine);
  64344. dest = table + lineStrideElements * y;
  64345. }
  64346. ++destTotal;
  64347. lastLevel = nextLevel;
  64348. dest[++destIndex] = nextX;
  64349. dest[++destIndex] = nextLevel;
  64350. }
  64351. }
  64352. }
  64353. if (lastLevel > 0)
  64354. {
  64355. if (destTotal >= maxEdgesPerLine)
  64356. {
  64357. dest[0] = destTotal;
  64358. remapTableForNumEdges (maxEdgesPerLine + juce_edgeTableDefaultEdgesPerLine);
  64359. dest = table + lineStrideElements * y;
  64360. }
  64361. ++destTotal;
  64362. dest[++destIndex] = right;
  64363. dest[++destIndex] = 0;
  64364. }
  64365. dest[0] = destTotal;
  64366. #if JUCE_DEBUG
  64367. int last = std::numeric_limits<int>::min();
  64368. for (int i = 0; i < dest[0]; ++i)
  64369. {
  64370. jassert (dest[i * 2 + 1] > last);
  64371. last = dest[i * 2 + 1];
  64372. }
  64373. jassert (dest [dest[0] * 2] == 0);
  64374. #endif
  64375. }
  64376. void EdgeTable::clipEdgeTableLineToRange (int* dest, const int x1, const int x2) throw()
  64377. {
  64378. int* lastItem = dest + (dest[0] * 2 - 1);
  64379. if (x2 < lastItem[0])
  64380. {
  64381. if (x2 <= dest[1])
  64382. {
  64383. dest[0] = 0;
  64384. return;
  64385. }
  64386. while (x2 < lastItem[-2])
  64387. {
  64388. --(dest[0]);
  64389. lastItem -= 2;
  64390. }
  64391. lastItem[0] = x2;
  64392. lastItem[1] = 0;
  64393. }
  64394. if (x1 > dest[1])
  64395. {
  64396. while (lastItem[0] > x1)
  64397. lastItem -= 2;
  64398. const int itemsRemoved = (int) (lastItem - (dest + 1)) / 2;
  64399. if (itemsRemoved > 0)
  64400. {
  64401. dest[0] -= itemsRemoved;
  64402. memmove (dest + 1, lastItem, dest[0] * (sizeof (int) * 2));
  64403. }
  64404. dest[1] = x1;
  64405. }
  64406. }
  64407. void EdgeTable::clipToRectangle (const Rectangle<int>& r) throw()
  64408. {
  64409. const Rectangle<int> clipped (r.getIntersection (bounds));
  64410. if (clipped.isEmpty())
  64411. {
  64412. needToCheckEmptinesss = false;
  64413. bounds.setHeight (0);
  64414. }
  64415. else
  64416. {
  64417. const int top = clipped.getY() - bounds.getY();
  64418. const int bottom = clipped.getBottom() - bounds.getY();
  64419. if (bottom < bounds.getHeight())
  64420. bounds.setHeight (bottom);
  64421. if (clipped.getRight() < bounds.getRight())
  64422. bounds.setRight (clipped.getRight());
  64423. for (int i = top; --i >= 0;)
  64424. table [lineStrideElements * i] = 0;
  64425. if (clipped.getX() > bounds.getX())
  64426. {
  64427. const int x1 = clipped.getX() << 8;
  64428. const int x2 = jmin (bounds.getRight(), clipped.getRight()) << 8;
  64429. int* line = table + lineStrideElements * top;
  64430. for (int i = bottom - top; --i >= 0;)
  64431. {
  64432. if (line[0] != 0)
  64433. clipEdgeTableLineToRange (line, x1, x2);
  64434. line += lineStrideElements;
  64435. }
  64436. }
  64437. needToCheckEmptinesss = true;
  64438. }
  64439. }
  64440. void EdgeTable::excludeRectangle (const Rectangle<int>& r) throw()
  64441. {
  64442. const Rectangle<int> clipped (r.getIntersection (bounds));
  64443. if (! clipped.isEmpty())
  64444. {
  64445. const int top = clipped.getY() - bounds.getY();
  64446. const int bottom = clipped.getBottom() - bounds.getY();
  64447. //XXX optimise here by shortening the table if it fills top or bottom
  64448. const int rectLine[] = { 4, std::numeric_limits<int>::min(), 255,
  64449. clipped.getX() << 8, 0,
  64450. clipped.getRight() << 8, 255,
  64451. std::numeric_limits<int>::max(), 0 };
  64452. for (int i = top; i < bottom; ++i)
  64453. intersectWithEdgeTableLine (i, rectLine);
  64454. needToCheckEmptinesss = true;
  64455. }
  64456. }
  64457. void EdgeTable::clipToEdgeTable (const EdgeTable& other)
  64458. {
  64459. const Rectangle<int> clipped (other.bounds.getIntersection (bounds));
  64460. if (clipped.isEmpty())
  64461. {
  64462. needToCheckEmptinesss = false;
  64463. bounds.setHeight (0);
  64464. }
  64465. else
  64466. {
  64467. const int top = clipped.getY() - bounds.getY();
  64468. const int bottom = clipped.getBottom() - bounds.getY();
  64469. if (bottom < bounds.getHeight())
  64470. bounds.setHeight (bottom);
  64471. if (clipped.getRight() < bounds.getRight())
  64472. bounds.setRight (clipped.getRight());
  64473. int i = 0;
  64474. for (i = top; --i >= 0;)
  64475. table [lineStrideElements * i] = 0;
  64476. const int* otherLine = other.table + other.lineStrideElements * (clipped.getY() - other.bounds.getY());
  64477. for (i = top; i < bottom; ++i)
  64478. {
  64479. intersectWithEdgeTableLine (i, otherLine);
  64480. otherLine += other.lineStrideElements;
  64481. }
  64482. needToCheckEmptinesss = true;
  64483. }
  64484. }
  64485. void EdgeTable::clipLineToMask (int x, int y, const uint8* mask, int maskStride, int numPixels) throw()
  64486. {
  64487. y -= bounds.getY();
  64488. if (y < 0 || y >= bounds.getHeight())
  64489. return;
  64490. needToCheckEmptinesss = true;
  64491. if (numPixels <= 0)
  64492. {
  64493. table [lineStrideElements * y] = 0;
  64494. return;
  64495. }
  64496. int* tempLine = (int*) alloca ((numPixels * 2 + 4) * sizeof (int));
  64497. int destIndex = 0, lastLevel = 0;
  64498. while (--numPixels >= 0)
  64499. {
  64500. const int alpha = *mask;
  64501. mask += maskStride;
  64502. if (alpha != lastLevel)
  64503. {
  64504. tempLine[++destIndex] = (x << 8);
  64505. tempLine[++destIndex] = alpha;
  64506. lastLevel = alpha;
  64507. }
  64508. ++x;
  64509. }
  64510. if (lastLevel > 0)
  64511. {
  64512. tempLine[++destIndex] = (x << 8);
  64513. tempLine[++destIndex] = 0;
  64514. }
  64515. tempLine[0] = destIndex >> 1;
  64516. intersectWithEdgeTableLine (y, tempLine);
  64517. }
  64518. bool EdgeTable::isEmpty() throw()
  64519. {
  64520. if (needToCheckEmptinesss)
  64521. {
  64522. needToCheckEmptinesss = false;
  64523. int* t = table;
  64524. for (int i = bounds.getHeight(); --i >= 0;)
  64525. {
  64526. if (t[0] > 1)
  64527. return false;
  64528. t += lineStrideElements;
  64529. }
  64530. bounds.setHeight (0);
  64531. }
  64532. return bounds.getHeight() == 0;
  64533. }
  64534. END_JUCE_NAMESPACE
  64535. /*** End of inlined file: juce_EdgeTable.cpp ***/
  64536. /*** Start of inlined file: juce_FillType.cpp ***/
  64537. BEGIN_JUCE_NAMESPACE
  64538. FillType::FillType() throw()
  64539. : colour (0xff000000), image (0)
  64540. {
  64541. }
  64542. FillType::FillType (const Colour& colour_) throw()
  64543. : colour (colour_), image (0)
  64544. {
  64545. }
  64546. FillType::FillType (const ColourGradient& gradient_)
  64547. : colour (0xff000000), gradient (new ColourGradient (gradient_)), image (0)
  64548. {
  64549. }
  64550. FillType::FillType (const Image& image_, const AffineTransform& transform_) throw()
  64551. : colour (0xff000000), image (&image_), transform (transform_)
  64552. {
  64553. }
  64554. FillType::FillType (const FillType& other)
  64555. : colour (other.colour),
  64556. gradient (other.gradient != 0 ? new ColourGradient (*other.gradient) : 0),
  64557. image (other.image), transform (other.transform)
  64558. {
  64559. }
  64560. FillType& FillType::operator= (const FillType& other)
  64561. {
  64562. if (this != &other)
  64563. {
  64564. colour = other.colour;
  64565. gradient = (other.gradient != 0 ? new ColourGradient (*other.gradient) : 0);
  64566. image = other.image;
  64567. transform = other.transform;
  64568. }
  64569. return *this;
  64570. }
  64571. FillType::~FillType() throw()
  64572. {
  64573. }
  64574. void FillType::setColour (const Colour& newColour) throw()
  64575. {
  64576. gradient = 0;
  64577. image = 0;
  64578. colour = newColour;
  64579. }
  64580. void FillType::setGradient (const ColourGradient& newGradient)
  64581. {
  64582. if (gradient != 0)
  64583. {
  64584. *gradient = newGradient;
  64585. }
  64586. else
  64587. {
  64588. image = 0;
  64589. gradient = new ColourGradient (newGradient);
  64590. colour = Colours::black;
  64591. }
  64592. }
  64593. void FillType::setTiledImage (const Image& image_, const AffineTransform& transform_) throw()
  64594. {
  64595. gradient = 0;
  64596. image = &image_;
  64597. transform = transform_;
  64598. colour = Colours::black;
  64599. }
  64600. void FillType::setOpacity (const float newOpacity) throw()
  64601. {
  64602. colour = colour.withAlpha (newOpacity);
  64603. }
  64604. END_JUCE_NAMESPACE
  64605. /*** End of inlined file: juce_FillType.cpp ***/
  64606. /*** Start of inlined file: juce_Graphics.cpp ***/
  64607. BEGIN_JUCE_NAMESPACE
  64608. static const Graphics::ResamplingQuality defaultQuality = Graphics::mediumResamplingQuality;
  64609. template <typename Type>
  64610. static bool areCoordsSensibleNumbers (Type x, Type y, Type w, Type h)
  64611. {
  64612. const int maxVal = 0x3fffffff;
  64613. return (int) x >= -maxVal && (int) x <= maxVal
  64614. && (int) y >= -maxVal && (int) y <= maxVal
  64615. && (int) w >= -maxVal && (int) w <= maxVal
  64616. && (int) h >= -maxVal && (int) h <= maxVal;
  64617. }
  64618. LowLevelGraphicsContext::LowLevelGraphicsContext()
  64619. {
  64620. }
  64621. LowLevelGraphicsContext::~LowLevelGraphicsContext()
  64622. {
  64623. }
  64624. Graphics::Graphics (Image& imageToDrawOnto)
  64625. : context (imageToDrawOnto.createLowLevelContext()),
  64626. contextToDelete (context),
  64627. saveStatePending (false)
  64628. {
  64629. }
  64630. Graphics::Graphics (LowLevelGraphicsContext* const internalContext) throw()
  64631. : context (internalContext),
  64632. saveStatePending (false)
  64633. {
  64634. }
  64635. Graphics::~Graphics()
  64636. {
  64637. }
  64638. void Graphics::resetToDefaultState()
  64639. {
  64640. saveStateIfPending();
  64641. context->setFill (FillType());
  64642. context->setFont (Font());
  64643. context->setInterpolationQuality (defaultQuality);
  64644. }
  64645. bool Graphics::isVectorDevice() const
  64646. {
  64647. return context->isVectorDevice();
  64648. }
  64649. bool Graphics::reduceClipRegion (const int x, const int y, const int w, const int h)
  64650. {
  64651. saveStateIfPending();
  64652. return context->clipToRectangle (Rectangle<int> (x, y, w, h));
  64653. }
  64654. bool Graphics::reduceClipRegion (const RectangleList& clipRegion)
  64655. {
  64656. saveStateIfPending();
  64657. return context->clipToRectangleList (clipRegion);
  64658. }
  64659. bool Graphics::reduceClipRegion (const Path& path, const AffineTransform& transform)
  64660. {
  64661. saveStateIfPending();
  64662. context->clipToPath (path, transform);
  64663. return ! context->isClipEmpty();
  64664. }
  64665. bool Graphics::reduceClipRegion (const Image& image, const Rectangle<int>& sourceClipRegion, const AffineTransform& transform)
  64666. {
  64667. saveStateIfPending();
  64668. context->clipToImageAlpha (image, sourceClipRegion, transform);
  64669. return ! context->isClipEmpty();
  64670. }
  64671. void Graphics::excludeClipRegion (const Rectangle<int>& rectangleToExclude)
  64672. {
  64673. saveStateIfPending();
  64674. context->excludeClipRectangle (rectangleToExclude);
  64675. }
  64676. bool Graphics::isClipEmpty() const
  64677. {
  64678. return context->isClipEmpty();
  64679. }
  64680. const Rectangle<int> Graphics::getClipBounds() const
  64681. {
  64682. return context->getClipBounds();
  64683. }
  64684. void Graphics::saveState()
  64685. {
  64686. saveStateIfPending();
  64687. saveStatePending = true;
  64688. }
  64689. void Graphics::restoreState()
  64690. {
  64691. if (saveStatePending)
  64692. saveStatePending = false;
  64693. else
  64694. context->restoreState();
  64695. }
  64696. void Graphics::saveStateIfPending()
  64697. {
  64698. if (saveStatePending)
  64699. {
  64700. saveStatePending = false;
  64701. context->saveState();
  64702. }
  64703. }
  64704. void Graphics::setOrigin (const int newOriginX, const int newOriginY)
  64705. {
  64706. saveStateIfPending();
  64707. context->setOrigin (newOriginX, newOriginY);
  64708. }
  64709. bool Graphics::clipRegionIntersects (const int x, const int y, const int w, const int h) const
  64710. {
  64711. return context->clipRegionIntersects (Rectangle<int> (x, y, w, h));
  64712. }
  64713. void Graphics::setColour (const Colour& newColour)
  64714. {
  64715. saveStateIfPending();
  64716. context->setFill (newColour);
  64717. }
  64718. void Graphics::setOpacity (const float newOpacity)
  64719. {
  64720. saveStateIfPending();
  64721. context->setOpacity (newOpacity);
  64722. }
  64723. void Graphics::setGradientFill (const ColourGradient& gradient)
  64724. {
  64725. setFillType (gradient);
  64726. }
  64727. void Graphics::setTiledImageFill (const Image& imageToUse, const int anchorX, const int anchorY, const float opacity)
  64728. {
  64729. saveStateIfPending();
  64730. context->setFill (FillType (imageToUse, AffineTransform::translation ((float) anchorX, (float) anchorY)));
  64731. context->setOpacity (opacity);
  64732. }
  64733. void Graphics::setFillType (const FillType& newFill)
  64734. {
  64735. saveStateIfPending();
  64736. context->setFill (newFill);
  64737. }
  64738. void Graphics::setFont (const Font& newFont)
  64739. {
  64740. saveStateIfPending();
  64741. context->setFont (newFont);
  64742. }
  64743. void Graphics::setFont (const float newFontHeight, const int newFontStyleFlags)
  64744. {
  64745. saveStateIfPending();
  64746. Font f (context->getFont());
  64747. f.setSizeAndStyle (newFontHeight, newFontStyleFlags, 1.0f, 0);
  64748. context->setFont (f);
  64749. }
  64750. void Graphics::drawSingleLineText (const String& text, const int startX, const int baselineY) const
  64751. {
  64752. if (text.isNotEmpty()
  64753. && startX < context->getClipBounds().getRight())
  64754. {
  64755. GlyphArrangement arr;
  64756. arr.addLineOfText (context->getFont(), text, (float) startX, (float) baselineY);
  64757. arr.draw (*this);
  64758. }
  64759. }
  64760. void Graphics::drawTextAsPath (const String& text, const AffineTransform& transform) const
  64761. {
  64762. if (text.isNotEmpty())
  64763. {
  64764. GlyphArrangement arr;
  64765. arr.addLineOfText (context->getFont(), text, 0.0f, 0.0f);
  64766. arr.draw (*this, transform);
  64767. }
  64768. }
  64769. void Graphics::drawMultiLineText (const String& text, const int startX, const int baselineY, const int maximumLineWidth) const
  64770. {
  64771. if (text.isNotEmpty()
  64772. && startX < context->getClipBounds().getRight())
  64773. {
  64774. GlyphArrangement arr;
  64775. arr.addJustifiedText (context->getFont(), text,
  64776. (float) startX, (float) baselineY, (float) maximumLineWidth,
  64777. Justification::left);
  64778. arr.draw (*this);
  64779. }
  64780. }
  64781. void Graphics::drawText (const String& text,
  64782. const int x, const int y, const int width, const int height,
  64783. const Justification& justificationType,
  64784. const bool useEllipsesIfTooBig) const
  64785. {
  64786. if (text.isNotEmpty() && context->clipRegionIntersects (Rectangle<int> (x, y, width, height)))
  64787. {
  64788. GlyphArrangement arr;
  64789. arr.addCurtailedLineOfText (context->getFont(), text,
  64790. 0.0f, 0.0f, (float) width,
  64791. useEllipsesIfTooBig);
  64792. arr.justifyGlyphs (0, arr.getNumGlyphs(),
  64793. (float) x, (float) y, (float) width, (float) height,
  64794. justificationType);
  64795. arr.draw (*this);
  64796. }
  64797. }
  64798. void Graphics::drawFittedText (const String& text,
  64799. const int x, const int y, const int width, const int height,
  64800. const Justification& justification,
  64801. const int maximumNumberOfLines,
  64802. const float minimumHorizontalScale) const
  64803. {
  64804. if (text.isNotEmpty()
  64805. && width > 0 && height > 0
  64806. && context->clipRegionIntersects (Rectangle<int> (x, y, width, height)))
  64807. {
  64808. GlyphArrangement arr;
  64809. arr.addFittedText (context->getFont(), text,
  64810. (float) x, (float) y, (float) width, (float) height,
  64811. justification,
  64812. maximumNumberOfLines,
  64813. minimumHorizontalScale);
  64814. arr.draw (*this);
  64815. }
  64816. }
  64817. void Graphics::fillRect (int x, int y, int width, int height) const
  64818. {
  64819. // passing in a silly number can cause maths problems in rendering!
  64820. jassert (areCoordsSensibleNumbers (x, y, width, height));
  64821. context->fillRect (Rectangle<int> (x, y, width, height), false);
  64822. }
  64823. void Graphics::fillRect (const Rectangle<int>& r) const
  64824. {
  64825. context->fillRect (r, false);
  64826. }
  64827. void Graphics::fillRect (const float x, const float y, const float width, const float height) const
  64828. {
  64829. // passing in a silly number can cause maths problems in rendering!
  64830. jassert (areCoordsSensibleNumbers (x, y, width, height));
  64831. Path p;
  64832. p.addRectangle (x, y, width, height);
  64833. fillPath (p);
  64834. }
  64835. void Graphics::setPixel (int x, int y) const
  64836. {
  64837. context->fillRect (Rectangle<int> (x, y, 1, 1), false);
  64838. }
  64839. void Graphics::fillAll() const
  64840. {
  64841. fillRect (context->getClipBounds());
  64842. }
  64843. void Graphics::fillAll (const Colour& colourToUse) const
  64844. {
  64845. if (! colourToUse.isTransparent())
  64846. {
  64847. const Rectangle<int> clip (context->getClipBounds());
  64848. context->saveState();
  64849. context->setFill (colourToUse);
  64850. context->fillRect (clip, false);
  64851. context->restoreState();
  64852. }
  64853. }
  64854. void Graphics::fillPath (const Path& path, const AffineTransform& transform) const
  64855. {
  64856. if ((! context->isClipEmpty()) && ! path.isEmpty())
  64857. context->fillPath (path, transform);
  64858. }
  64859. void Graphics::strokePath (const Path& path,
  64860. const PathStrokeType& strokeType,
  64861. const AffineTransform& transform) const
  64862. {
  64863. Path stroke;
  64864. strokeType.createStrokedPath (stroke, path, transform);
  64865. fillPath (stroke);
  64866. }
  64867. void Graphics::drawRect (const int x, const int y, const int width, const int height,
  64868. const int lineThickness) const
  64869. {
  64870. // passing in a silly number can cause maths problems in rendering!
  64871. jassert (areCoordsSensibleNumbers (x, y, width, height));
  64872. context->fillRect (Rectangle<int> (x, y, width, lineThickness), false);
  64873. context->fillRect (Rectangle<int> (x, y + lineThickness, lineThickness, height - lineThickness * 2), false);
  64874. context->fillRect (Rectangle<int> (x + width - lineThickness, y + lineThickness, lineThickness, height - lineThickness * 2), false);
  64875. context->fillRect (Rectangle<int> (x, y + height - lineThickness, width, lineThickness), false);
  64876. }
  64877. void Graphics::drawRect (const float x, const float y, const float width, const float height, const float lineThickness) const
  64878. {
  64879. // passing in a silly number can cause maths problems in rendering!
  64880. jassert (areCoordsSensibleNumbers (x, y, width, height));
  64881. Path p;
  64882. p.addRectangle (x, y, width, lineThickness);
  64883. p.addRectangle (x, y + lineThickness, lineThickness, height - lineThickness * 2.0f);
  64884. p.addRectangle (x + width - lineThickness, y + lineThickness, lineThickness, height - lineThickness * 2.0f);
  64885. p.addRectangle (x, y + height - lineThickness, width, lineThickness);
  64886. fillPath (p);
  64887. }
  64888. void Graphics::drawRect (const Rectangle<int>& r, const int lineThickness) const
  64889. {
  64890. drawRect (r.getX(), r.getY(), r.getWidth(), r.getHeight(), lineThickness);
  64891. }
  64892. void Graphics::drawBevel (const int x, const int y, const int width, const int height,
  64893. const int bevelThickness, const Colour& topLeftColour, const Colour& bottomRightColour,
  64894. const bool useGradient, const bool sharpEdgeOnOutside) const
  64895. {
  64896. // passing in a silly number can cause maths problems in rendering!
  64897. jassert (areCoordsSensibleNumbers (x, y, width, height));
  64898. if (clipRegionIntersects (x, y, width, height))
  64899. {
  64900. context->saveState();
  64901. const float oldOpacity = 1.0f;//xxx state->colour.getFloatAlpha();
  64902. const float ramp = oldOpacity / bevelThickness;
  64903. for (int i = bevelThickness; --i >= 0;)
  64904. {
  64905. const float op = useGradient ? ramp * (sharpEdgeOnOutside ? bevelThickness - i : i)
  64906. : oldOpacity;
  64907. context->setFill (topLeftColour.withMultipliedAlpha (op));
  64908. context->fillRect (Rectangle<int> (x + i, y + i, width - i * 2, 1), false);
  64909. context->setFill (topLeftColour.withMultipliedAlpha (op * 0.75f));
  64910. context->fillRect (Rectangle<int> (x + i, y + i + 1, 1, height - i * 2 - 2), false);
  64911. context->setFill (bottomRightColour.withMultipliedAlpha (op));
  64912. context->fillRect (Rectangle<int> (x + i, y + height - i - 1, width - i * 2, 1), false);
  64913. context->setFill (bottomRightColour.withMultipliedAlpha (op * 0.75f));
  64914. context->fillRect (Rectangle<int> (x + width - i - 1, y + i + 1, 1, height - i * 2 - 2), false);
  64915. }
  64916. context->restoreState();
  64917. }
  64918. }
  64919. void Graphics::fillEllipse (const float x, const float y, const float width, const float height) const
  64920. {
  64921. // passing in a silly number can cause maths problems in rendering!
  64922. jassert (areCoordsSensibleNumbers (x, y, width, height));
  64923. Path p;
  64924. p.addEllipse (x, y, width, height);
  64925. fillPath (p);
  64926. }
  64927. void Graphics::drawEllipse (const float x, const float y, const float width, const float height,
  64928. const float lineThickness) const
  64929. {
  64930. // passing in a silly number can cause maths problems in rendering!
  64931. jassert (areCoordsSensibleNumbers (x, y, width, height));
  64932. Path p;
  64933. p.addEllipse (x, y, width, height);
  64934. strokePath (p, PathStrokeType (lineThickness));
  64935. }
  64936. void Graphics::fillRoundedRectangle (const float x, const float y, const float width, const float height, const float cornerSize) const
  64937. {
  64938. // passing in a silly number can cause maths problems in rendering!
  64939. jassert (areCoordsSensibleNumbers (x, y, width, height));
  64940. Path p;
  64941. p.addRoundedRectangle (x, y, width, height, cornerSize);
  64942. fillPath (p);
  64943. }
  64944. void Graphics::fillRoundedRectangle (const Rectangle<float>& r, const float cornerSize) const
  64945. {
  64946. fillRoundedRectangle (r.getX(), r.getY(), r.getWidth(), r.getHeight(), cornerSize);
  64947. }
  64948. void Graphics::drawRoundedRectangle (const float x, const float y, const float width, const float height,
  64949. const float cornerSize, const float lineThickness) const
  64950. {
  64951. // passing in a silly number can cause maths problems in rendering!
  64952. jassert (areCoordsSensibleNumbers (x, y, width, height));
  64953. Path p;
  64954. p.addRoundedRectangle (x, y, width, height, cornerSize);
  64955. strokePath (p, PathStrokeType (lineThickness));
  64956. }
  64957. void Graphics::drawRoundedRectangle (const Rectangle<float>& r, const float cornerSize, const float lineThickness) const
  64958. {
  64959. drawRoundedRectangle (r.getX(), r.getY(), r.getWidth(), r.getHeight(), cornerSize, lineThickness);
  64960. }
  64961. void Graphics::drawArrow (const float startX, const float startY, const float endX, const float endY,
  64962. const float lineThickness, const float arrowheadWidth, const float arrowheadLength) const
  64963. {
  64964. Path p;
  64965. p.addArrow (startX, startY, endX, endY,
  64966. lineThickness, arrowheadWidth, arrowheadLength);
  64967. fillPath (p);
  64968. }
  64969. void Graphics::fillCheckerBoard (int x, int y, int width, int height,
  64970. const int checkWidth, const int checkHeight,
  64971. const Colour& colour1, const Colour& colour2) const
  64972. {
  64973. jassert (checkWidth > 0 && checkHeight > 0); // can't be zero or less!
  64974. if (checkWidth > 0 && checkHeight > 0)
  64975. {
  64976. context->saveState();
  64977. if (colour1 == colour2)
  64978. {
  64979. context->setFill (colour1);
  64980. context->fillRect (Rectangle<int> (x, y, width, height), false);
  64981. }
  64982. else
  64983. {
  64984. const Rectangle<int> clip (context->getClipBounds());
  64985. const int right = jmin (x + width, clip.getRight());
  64986. const int bottom = jmin (y + height, clip.getBottom());
  64987. int cy = 0;
  64988. while (y < bottom)
  64989. {
  64990. int cx = cy;
  64991. for (int xx = x; xx < right; xx += checkWidth)
  64992. {
  64993. context->setFill (((cx++ & 1) == 0) ? colour1 : colour2);
  64994. context->fillRect (Rectangle<int> (xx, y, jmin (checkWidth, right - xx), jmin (checkHeight, bottom - y)),
  64995. false);
  64996. }
  64997. ++cy;
  64998. y += checkHeight;
  64999. }
  65000. }
  65001. context->restoreState();
  65002. }
  65003. }
  65004. void Graphics::drawVerticalLine (const int x, float top, float bottom) const
  65005. {
  65006. context->drawVerticalLine (x, top, bottom);
  65007. }
  65008. void Graphics::drawHorizontalLine (const int y, float left, float right) const
  65009. {
  65010. context->drawHorizontalLine (y, left, right);
  65011. }
  65012. void Graphics::drawLine (float x1, float y1, float x2, float y2) const
  65013. {
  65014. context->drawLine (x1, y1, x2, y2);
  65015. }
  65016. void Graphics::drawLine (const float startX, const float startY,
  65017. const float endX, const float endY,
  65018. const float lineThickness) const
  65019. {
  65020. Path p;
  65021. p.addLineSegment (startX, startY, endX, endY, lineThickness);
  65022. fillPath (p);
  65023. }
  65024. void Graphics::drawLine (const Line<float>& line) const
  65025. {
  65026. drawLine (line.getStartX(), line.getStartY(), line.getEndX(), line.getEndY());
  65027. }
  65028. void Graphics::drawLine (const Line<float>& line, const float lineThickness) const
  65029. {
  65030. drawLine (line.getStartX(), line.getStartY(), line.getEndX(), line.getEndY(), lineThickness);
  65031. }
  65032. void Graphics::drawDashedLine (const float startX, const float startY,
  65033. const float endX, const float endY,
  65034. const float* const dashLengths,
  65035. const int numDashLengths,
  65036. const float lineThickness) const
  65037. {
  65038. const double dx = endX - startX;
  65039. const double dy = endY - startY;
  65040. const double totalLen = juce_hypot (dx, dy);
  65041. if (totalLen >= 0.5)
  65042. {
  65043. const double onePixAlpha = 1.0 / totalLen;
  65044. double alpha = 0.0;
  65045. float x = startX;
  65046. float y = startY;
  65047. int n = 0;
  65048. while (alpha < 1.0f)
  65049. {
  65050. alpha = jmin (1.0, alpha + dashLengths[n++] * onePixAlpha);
  65051. n = n % numDashLengths;
  65052. const float oldX = x;
  65053. const float oldY = y;
  65054. x = (float) (startX + dx * alpha);
  65055. y = (float) (startY + dy * alpha);
  65056. if ((n & 1) != 0)
  65057. {
  65058. if (lineThickness != 1.0f)
  65059. drawLine (oldX, oldY, x, y, lineThickness);
  65060. else
  65061. drawLine (oldX, oldY, x, y);
  65062. }
  65063. }
  65064. }
  65065. }
  65066. void Graphics::setImageResamplingQuality (const Graphics::ResamplingQuality newQuality)
  65067. {
  65068. saveStateIfPending();
  65069. context->setInterpolationQuality (newQuality);
  65070. }
  65071. void Graphics::drawImageAt (const Image* const imageToDraw,
  65072. const int topLeftX, const int topLeftY,
  65073. const bool fillAlphaChannelWithCurrentBrush) const
  65074. {
  65075. if (imageToDraw != 0)
  65076. {
  65077. const int imageW = imageToDraw->getWidth();
  65078. const int imageH = imageToDraw->getHeight();
  65079. drawImage (imageToDraw,
  65080. topLeftX, topLeftY, imageW, imageH,
  65081. 0, 0, imageW, imageH,
  65082. fillAlphaChannelWithCurrentBrush);
  65083. }
  65084. }
  65085. void Graphics::drawImageWithin (const Image* const imageToDraw,
  65086. const int destX, const int destY,
  65087. const int destW, const int destH,
  65088. const RectanglePlacement& placementWithinTarget,
  65089. const bool fillAlphaChannelWithCurrentBrush) const
  65090. {
  65091. // passing in a silly number can cause maths problems in rendering!
  65092. jassert (areCoordsSensibleNumbers (destX, destY, destW, destH));
  65093. if (imageToDraw != 0)
  65094. {
  65095. const int imageW = imageToDraw->getWidth();
  65096. const int imageH = imageToDraw->getHeight();
  65097. if (imageW > 0 && imageH > 0)
  65098. {
  65099. double newX = 0.0, newY = 0.0;
  65100. double newW = imageW;
  65101. double newH = imageH;
  65102. placementWithinTarget.applyTo (newX, newY, newW, newH,
  65103. destX, destY, destW, destH);
  65104. if (newW > 0 && newH > 0)
  65105. {
  65106. drawImage (imageToDraw,
  65107. roundToInt (newX), roundToInt (newY),
  65108. roundToInt (newW), roundToInt (newH),
  65109. 0, 0, imageW, imageH,
  65110. fillAlphaChannelWithCurrentBrush);
  65111. }
  65112. }
  65113. }
  65114. }
  65115. void Graphics::drawImage (const Image* const imageToDraw,
  65116. int dx, int dy, int dw, int dh,
  65117. int sx, int sy, int sw, int sh,
  65118. const bool fillAlphaChannelWithCurrentBrush) const
  65119. {
  65120. // passing in a silly number can cause maths problems in rendering!
  65121. jassert (areCoordsSensibleNumbers (dx, dy, dw, dh));
  65122. jassert (areCoordsSensibleNumbers (sx, sy, sw, sh));
  65123. if (context->clipRegionIntersects (Rectangle<int> (dx, dy, dw, dh)))
  65124. {
  65125. drawImageTransformed (imageToDraw, Rectangle<int> (sx, sy, sw, sh),
  65126. AffineTransform::scale (dw / (float) sw, dh / (float) sh)
  65127. .translated ((float) dx, (float) dy),
  65128. fillAlphaChannelWithCurrentBrush);
  65129. }
  65130. }
  65131. void Graphics::drawImageTransformed (const Image* const imageToDraw,
  65132. const Rectangle<int>& imageSubRegion,
  65133. const AffineTransform& transform,
  65134. const bool fillAlphaChannelWithCurrentBrush) const
  65135. {
  65136. if (imageToDraw != 0 && ! context->isClipEmpty())
  65137. {
  65138. const Rectangle<int> srcClip (imageSubRegion.getIntersection (imageToDraw->getBounds()));
  65139. if (fillAlphaChannelWithCurrentBrush)
  65140. {
  65141. context->saveState();
  65142. context->clipToImageAlpha (*imageToDraw, srcClip, transform);
  65143. fillAll();
  65144. context->restoreState();
  65145. }
  65146. else
  65147. {
  65148. context->drawImage (*imageToDraw, srcClip, transform, false);
  65149. }
  65150. }
  65151. }
  65152. END_JUCE_NAMESPACE
  65153. /*** End of inlined file: juce_Graphics.cpp ***/
  65154. /*** Start of inlined file: juce_Justification.cpp ***/
  65155. BEGIN_JUCE_NAMESPACE
  65156. Justification::Justification (const Justification& other) throw()
  65157. : flags (other.flags)
  65158. {
  65159. }
  65160. Justification& Justification::operator= (const Justification& other) throw()
  65161. {
  65162. flags = other.flags;
  65163. return *this;
  65164. }
  65165. int Justification::getOnlyVerticalFlags() const throw()
  65166. {
  65167. return flags & (top | bottom | verticallyCentred);
  65168. }
  65169. int Justification::getOnlyHorizontalFlags() const throw()
  65170. {
  65171. return flags & (left | right | horizontallyCentred | horizontallyJustified);
  65172. }
  65173. void Justification::applyToRectangle (int& x, int& y,
  65174. const int w, const int h,
  65175. const int spaceX, const int spaceY,
  65176. const int spaceW, const int spaceH) const throw()
  65177. {
  65178. if ((flags & horizontallyCentred) != 0)
  65179. {
  65180. x = spaceX + ((spaceW - w) >> 1);
  65181. }
  65182. else if ((flags & right) != 0)
  65183. {
  65184. x = spaceX + spaceW - w;
  65185. }
  65186. else
  65187. {
  65188. x = spaceX;
  65189. }
  65190. if ((flags & verticallyCentred) != 0)
  65191. {
  65192. y = spaceY + ((spaceH - h) >> 1);
  65193. }
  65194. else if ((flags & bottom) != 0)
  65195. {
  65196. y = spaceY + spaceH - h;
  65197. }
  65198. else
  65199. {
  65200. y = spaceY;
  65201. }
  65202. }
  65203. END_JUCE_NAMESPACE
  65204. /*** End of inlined file: juce_Justification.cpp ***/
  65205. /*** Start of inlined file: juce_LowLevelGraphicsPostScriptRenderer.cpp ***/
  65206. BEGIN_JUCE_NAMESPACE
  65207. // this will throw an assertion if you try to draw something that's not
  65208. // possible in postscript
  65209. #define WARN_ABOUT_NON_POSTSCRIPT_OPERATIONS 0
  65210. #if JUCE_DEBUG && WARN_ABOUT_NON_POSTSCRIPT_OPERATIONS
  65211. #define notPossibleInPostscriptAssert jassertfalse
  65212. #else
  65213. #define notPossibleInPostscriptAssert
  65214. #endif
  65215. LowLevelGraphicsPostScriptRenderer::LowLevelGraphicsPostScriptRenderer (OutputStream& resultingPostScript,
  65216. const String& documentTitle,
  65217. const int totalWidth_,
  65218. const int totalHeight_)
  65219. : out (resultingPostScript),
  65220. totalWidth (totalWidth_),
  65221. totalHeight (totalHeight_),
  65222. needToClip (true)
  65223. {
  65224. stateStack.add (new SavedState());
  65225. stateStack.getLast()->clip = Rectangle<int> (0, 0, totalWidth_, totalHeight_);
  65226. const float scale = jmin ((520.0f / totalWidth_), (750.0f / totalHeight));
  65227. out << "%!PS-Adobe-3.0 EPSF-3.0"
  65228. "\n%%BoundingBox: 0 0 600 824"
  65229. "\n%%Pages: 0"
  65230. "\n%%Creator: Raw Material Software JUCE"
  65231. "\n%%Title: " << documentTitle <<
  65232. "\n%%CreationDate: none"
  65233. "\n%%LanguageLevel: 2"
  65234. "\n%%EndComments"
  65235. "\n%%BeginProlog"
  65236. "\n%%BeginResource: JRes"
  65237. "\n/bd {bind def} bind def"
  65238. "\n/c {setrgbcolor} bd"
  65239. "\n/m {moveto} bd"
  65240. "\n/l {lineto} bd"
  65241. "\n/rl {rlineto} bd"
  65242. "\n/ct {curveto} bd"
  65243. "\n/cp {closepath} bd"
  65244. "\n/pr {3 index 3 index moveto 1 index 0 rlineto 0 1 index rlineto pop neg 0 rlineto pop pop closepath} bd"
  65245. "\n/doclip {initclip newpath} bd"
  65246. "\n/endclip {clip newpath} bd"
  65247. "\n%%EndResource"
  65248. "\n%%EndProlog"
  65249. "\n%%BeginSetup"
  65250. "\n%%EndSetup"
  65251. "\n%%Page: 1 1"
  65252. "\n%%BeginPageSetup"
  65253. "\n%%EndPageSetup\n\n"
  65254. << "40 800 translate\n"
  65255. << scale << ' ' << scale << " scale\n\n";
  65256. }
  65257. LowLevelGraphicsPostScriptRenderer::~LowLevelGraphicsPostScriptRenderer()
  65258. {
  65259. }
  65260. bool LowLevelGraphicsPostScriptRenderer::isVectorDevice() const
  65261. {
  65262. return true;
  65263. }
  65264. void LowLevelGraphicsPostScriptRenderer::setOrigin (int x, int y)
  65265. {
  65266. if (x != 0 || y != 0)
  65267. {
  65268. stateStack.getLast()->xOffset += x;
  65269. stateStack.getLast()->yOffset += y;
  65270. needToClip = true;
  65271. }
  65272. }
  65273. bool LowLevelGraphicsPostScriptRenderer::clipToRectangle (const Rectangle<int>& r)
  65274. {
  65275. needToClip = true;
  65276. return stateStack.getLast()->clip.clipTo (r.translated (stateStack.getLast()->xOffset, stateStack.getLast()->yOffset));
  65277. }
  65278. bool LowLevelGraphicsPostScriptRenderer::clipToRectangleList (const RectangleList& clipRegion)
  65279. {
  65280. needToClip = true;
  65281. return stateStack.getLast()->clip.clipTo (clipRegion);
  65282. }
  65283. void LowLevelGraphicsPostScriptRenderer::excludeClipRectangle (const Rectangle<int>& r)
  65284. {
  65285. needToClip = true;
  65286. stateStack.getLast()->clip.subtract (r.translated (stateStack.getLast()->xOffset, stateStack.getLast()->yOffset));
  65287. }
  65288. void LowLevelGraphicsPostScriptRenderer::clipToPath (const Path& path, const AffineTransform& transform)
  65289. {
  65290. writeClip();
  65291. Path p (path);
  65292. p.applyTransform (transform.translated ((float) stateStack.getLast()->xOffset, (float) stateStack.getLast()->yOffset));
  65293. writePath (p);
  65294. out << "clip\n";
  65295. }
  65296. void LowLevelGraphicsPostScriptRenderer::clipToImageAlpha (const Image& /*sourceImage*/, const Rectangle<int>& /*srcClip*/, const AffineTransform& /*transform*/)
  65297. {
  65298. needToClip = true;
  65299. jassertfalse // xxx
  65300. }
  65301. bool LowLevelGraphicsPostScriptRenderer::clipRegionIntersects (const Rectangle<int>& r)
  65302. {
  65303. return stateStack.getLast()->clip.intersectsRectangle (r.translated (stateStack.getLast()->xOffset, stateStack.getLast()->yOffset));
  65304. }
  65305. const Rectangle<int> LowLevelGraphicsPostScriptRenderer::getClipBounds() const
  65306. {
  65307. return stateStack.getLast()->clip.getBounds().translated (-stateStack.getLast()->xOffset,
  65308. -stateStack.getLast()->yOffset);
  65309. }
  65310. bool LowLevelGraphicsPostScriptRenderer::isClipEmpty() const
  65311. {
  65312. return stateStack.getLast()->clip.isEmpty();
  65313. }
  65314. LowLevelGraphicsPostScriptRenderer::SavedState::SavedState()
  65315. : xOffset (0),
  65316. yOffset (0)
  65317. {
  65318. }
  65319. LowLevelGraphicsPostScriptRenderer::SavedState::~SavedState()
  65320. {
  65321. }
  65322. void LowLevelGraphicsPostScriptRenderer::saveState()
  65323. {
  65324. stateStack.add (new SavedState (*stateStack.getLast()));
  65325. }
  65326. void LowLevelGraphicsPostScriptRenderer::restoreState()
  65327. {
  65328. jassert (stateStack.size() > 0);
  65329. if (stateStack.size() > 0)
  65330. stateStack.removeLast();
  65331. }
  65332. void LowLevelGraphicsPostScriptRenderer::writeClip()
  65333. {
  65334. if (needToClip)
  65335. {
  65336. needToClip = false;
  65337. out << "doclip ";
  65338. int itemsOnLine = 0;
  65339. for (RectangleList::Iterator i (stateStack.getLast()->clip); i.next();)
  65340. {
  65341. if (++itemsOnLine == 6)
  65342. {
  65343. itemsOnLine = 0;
  65344. out << '\n';
  65345. }
  65346. const Rectangle<int>& r = *i.getRectangle();
  65347. out << r.getX() << ' ' << -r.getY() << ' '
  65348. << r.getWidth() << ' ' << -r.getHeight() << " pr ";
  65349. }
  65350. out << "endclip\n";
  65351. }
  65352. }
  65353. void LowLevelGraphicsPostScriptRenderer::writeColour (const Colour& colour)
  65354. {
  65355. Colour c (Colours::white.overlaidWith (colour));
  65356. if (lastColour != c)
  65357. {
  65358. lastColour = c;
  65359. out << String (c.getFloatRed(), 3) << ' '
  65360. << String (c.getFloatGreen(), 3) << ' '
  65361. << String (c.getFloatBlue(), 3) << " c\n";
  65362. }
  65363. }
  65364. void LowLevelGraphicsPostScriptRenderer::writeXY (const float x, const float y) const
  65365. {
  65366. out << String (x, 2) << ' '
  65367. << String (-y, 2) << ' ';
  65368. }
  65369. void LowLevelGraphicsPostScriptRenderer::writePath (const Path& path) const
  65370. {
  65371. out << "newpath ";
  65372. float lastX = 0.0f;
  65373. float lastY = 0.0f;
  65374. int itemsOnLine = 0;
  65375. Path::Iterator i (path);
  65376. while (i.next())
  65377. {
  65378. if (++itemsOnLine == 4)
  65379. {
  65380. itemsOnLine = 0;
  65381. out << '\n';
  65382. }
  65383. switch (i.elementType)
  65384. {
  65385. case Path::Iterator::startNewSubPath:
  65386. writeXY (i.x1, i.y1);
  65387. lastX = i.x1;
  65388. lastY = i.y1;
  65389. out << "m ";
  65390. break;
  65391. case Path::Iterator::lineTo:
  65392. writeXY (i.x1, i.y1);
  65393. lastX = i.x1;
  65394. lastY = i.y1;
  65395. out << "l ";
  65396. break;
  65397. case Path::Iterator::quadraticTo:
  65398. {
  65399. const float cp1x = lastX + (i.x1 - lastX) * 2.0f / 3.0f;
  65400. const float cp1y = lastY + (i.y1 - lastY) * 2.0f / 3.0f;
  65401. const float cp2x = cp1x + (i.x2 - lastX) / 3.0f;
  65402. const float cp2y = cp1y + (i.y2 - lastY) / 3.0f;
  65403. writeXY (cp1x, cp1y);
  65404. writeXY (cp2x, cp2y);
  65405. writeXY (i.x2, i.y2);
  65406. out << "ct ";
  65407. lastX = i.x2;
  65408. lastY = i.y2;
  65409. }
  65410. break;
  65411. case Path::Iterator::cubicTo:
  65412. writeXY (i.x1, i.y1);
  65413. writeXY (i.x2, i.y2);
  65414. writeXY (i.x3, i.y3);
  65415. out << "ct ";
  65416. lastX = i.x3;
  65417. lastY = i.y3;
  65418. break;
  65419. case Path::Iterator::closePath:
  65420. out << "cp ";
  65421. break;
  65422. default:
  65423. jassertfalse
  65424. break;
  65425. }
  65426. }
  65427. out << '\n';
  65428. }
  65429. void LowLevelGraphicsPostScriptRenderer::writeTransform (const AffineTransform& trans) const
  65430. {
  65431. out << "[ "
  65432. << trans.mat00 << ' '
  65433. << trans.mat10 << ' '
  65434. << trans.mat01 << ' '
  65435. << trans.mat11 << ' '
  65436. << trans.mat02 << ' '
  65437. << trans.mat12 << " ] concat ";
  65438. }
  65439. void LowLevelGraphicsPostScriptRenderer::setFill (const FillType& fillType)
  65440. {
  65441. stateStack.getLast()->fillType = fillType;
  65442. }
  65443. void LowLevelGraphicsPostScriptRenderer::setOpacity (float /*opacity*/)
  65444. {
  65445. }
  65446. void LowLevelGraphicsPostScriptRenderer::setInterpolationQuality (Graphics::ResamplingQuality /*quality*/)
  65447. {
  65448. }
  65449. void LowLevelGraphicsPostScriptRenderer::fillRect (const Rectangle<int>& r, const bool /*replaceExistingContents*/)
  65450. {
  65451. if (stateStack.getLast()->fillType.isColour())
  65452. {
  65453. writeClip();
  65454. writeColour (stateStack.getLast()->fillType.colour);
  65455. Rectangle<int> r2 (r.translated (stateStack.getLast()->xOffset, stateStack.getLast()->yOffset));
  65456. out << r2.getX() << ' ' << -r2.getBottom() << ' ' << r2.getWidth() << ' ' << r2.getHeight() << " rectfill\n";
  65457. }
  65458. else
  65459. {
  65460. Path p;
  65461. p.addRectangle (r);
  65462. fillPath (p, AffineTransform::identity);
  65463. }
  65464. }
  65465. void LowLevelGraphicsPostScriptRenderer::fillPath (const Path& path, const AffineTransform& t)
  65466. {
  65467. if (stateStack.getLast()->fillType.isColour())
  65468. {
  65469. writeClip();
  65470. Path p (path);
  65471. p.applyTransform (t.translated ((float) stateStack.getLast()->xOffset,
  65472. (float) stateStack.getLast()->yOffset));
  65473. writePath (p);
  65474. writeColour (stateStack.getLast()->fillType.colour);
  65475. out << "fill\n";
  65476. }
  65477. else if (stateStack.getLast()->fillType.isGradient())
  65478. {
  65479. // this doesn't work correctly yet - it could be improved to handle solid gradients, but
  65480. // postscript can't do semi-transparent ones.
  65481. notPossibleInPostscriptAssert // you can disable this warning by setting the WARN_ABOUT_NON_POSTSCRIPT_OPERATIONS flag at the top of this file
  65482. writeClip();
  65483. out << "gsave ";
  65484. {
  65485. Path p (path);
  65486. p.applyTransform (t.translated ((float) stateStack.getLast()->xOffset, (float) stateStack.getLast()->yOffset));
  65487. writePath (p);
  65488. out << "clip\n";
  65489. }
  65490. const Rectangle<int> bounds (stateStack.getLast()->clip.getBounds());
  65491. // ideally this would draw lots of lines or ellipses to approximate the gradient, but for the
  65492. // time-being, this just fills it with the average colour..
  65493. writeColour (stateStack.getLast()->fillType.gradient->getColourAtPosition (0.5f));
  65494. out << bounds.getX() << ' ' << -bounds.getBottom() << ' ' << bounds.getWidth() << ' ' << bounds.getHeight() << " rectfill\n";
  65495. out << "grestore\n";
  65496. }
  65497. }
  65498. void LowLevelGraphicsPostScriptRenderer::writeImage (const Image& im,
  65499. const int sx, const int sy,
  65500. const int maxW, const int maxH) const
  65501. {
  65502. out << "{<\n";
  65503. const int w = jmin (maxW, im.getWidth());
  65504. const int h = jmin (maxH, im.getHeight());
  65505. int charsOnLine = 0;
  65506. const Image::BitmapData srcData (im, 0, 0, w, h);
  65507. Colour pixel;
  65508. for (int y = h; --y >= 0;)
  65509. {
  65510. for (int x = 0; x < w; ++x)
  65511. {
  65512. const uint8* pixelData = srcData.getPixelPointer (x, y);
  65513. if (x >= sx && y >= sy)
  65514. {
  65515. if (im.isARGB())
  65516. {
  65517. PixelARGB p (*(const PixelARGB*) pixelData);
  65518. p.unpremultiply();
  65519. pixel = Colours::white.overlaidWith (Colour (p.getARGB()));
  65520. }
  65521. else if (im.isRGB())
  65522. {
  65523. pixel = Colour (((const PixelRGB*) pixelData)->getARGB());
  65524. }
  65525. else
  65526. {
  65527. pixel = Colour ((uint8) 0, (uint8) 0, (uint8) 0, *pixelData);
  65528. }
  65529. }
  65530. else
  65531. {
  65532. pixel = Colours::transparentWhite;
  65533. }
  65534. const uint8 pixelValues[3] = { pixel.getRed(), pixel.getGreen(), pixel.getBlue() };
  65535. out << String::toHexString (pixelValues, 3, 0);
  65536. charsOnLine += 3;
  65537. if (charsOnLine > 100)
  65538. {
  65539. out << '\n';
  65540. charsOnLine = 0;
  65541. }
  65542. }
  65543. }
  65544. out << "\n>}\n";
  65545. }
  65546. void LowLevelGraphicsPostScriptRenderer::drawImage (const Image& sourceImage, const Rectangle<int>& srcClip,
  65547. const AffineTransform& transform, const bool /*fillEntireClipAsTiles*/)
  65548. {
  65549. const int w = jmin (sourceImage.getWidth(), srcClip.getRight());
  65550. const int h = jmin (sourceImage.getHeight(), srcClip.getBottom());
  65551. writeClip();
  65552. out << "gsave ";
  65553. writeTransform (transform.translated ((float) stateStack.getLast()->xOffset, (float) stateStack.getLast()->yOffset)
  65554. .scaled (1.0f, -1.0f));
  65555. RectangleList imageClip;
  65556. sourceImage.createSolidAreaMask (imageClip, 0.5f);
  65557. imageClip.clipTo (srcClip);
  65558. out << "newpath ";
  65559. int itemsOnLine = 0;
  65560. for (RectangleList::Iterator i (imageClip); i.next();)
  65561. {
  65562. if (++itemsOnLine == 6)
  65563. {
  65564. out << '\n';
  65565. itemsOnLine = 0;
  65566. }
  65567. const Rectangle<int>& r = *i.getRectangle();
  65568. out << r.getX() << ' ' << r.getY() << ' ' << r.getWidth() << ' ' << r.getHeight() << " pr ";
  65569. }
  65570. out << " clip newpath\n";
  65571. out << w << ' ' << h << " scale\n";
  65572. out << w << ' ' << h << " 8 [" << w << " 0 0 -" << h << ' ' << (int) 0 << ' ' << h << " ]\n";
  65573. writeImage (sourceImage, srcClip.getX(), srcClip.getY(), srcClip.getWidth(), srcClip.getHeight());
  65574. out << "false 3 colorimage grestore\n";
  65575. needToClip = true;
  65576. }
  65577. void LowLevelGraphicsPostScriptRenderer::drawLine (double x1, double y1, double x2, double y2)
  65578. {
  65579. Path p;
  65580. p.addLineSegment ((float) x1, (float) y1, (float) x2, (float) y2, 1.0f);
  65581. fillPath (p, AffineTransform::identity);
  65582. }
  65583. void LowLevelGraphicsPostScriptRenderer::drawVerticalLine (const int x, double top, double bottom)
  65584. {
  65585. drawLine (x, top, x, bottom);
  65586. }
  65587. void LowLevelGraphicsPostScriptRenderer::drawHorizontalLine (const int y, double left, double right)
  65588. {
  65589. drawLine (left, y, right, y);
  65590. }
  65591. void LowLevelGraphicsPostScriptRenderer::setFont (const Font& newFont)
  65592. {
  65593. stateStack.getLast()->font = newFont;
  65594. }
  65595. const Font LowLevelGraphicsPostScriptRenderer::getFont()
  65596. {
  65597. return stateStack.getLast()->font;
  65598. }
  65599. void LowLevelGraphicsPostScriptRenderer::drawGlyph (int glyphNumber, const AffineTransform& transform)
  65600. {
  65601. Path p;
  65602. Font& font = stateStack.getLast()->font;
  65603. font.getTypeface()->getOutlineForGlyph (glyphNumber, p);
  65604. fillPath (p, AffineTransform::scale (font.getHeight() * font.getHorizontalScale(), font.getHeight()).followedBy (transform));
  65605. }
  65606. END_JUCE_NAMESPACE
  65607. /*** End of inlined file: juce_LowLevelGraphicsPostScriptRenderer.cpp ***/
  65608. /*** Start of inlined file: juce_LowLevelGraphicsSoftwareRenderer.cpp ***/
  65609. BEGIN_JUCE_NAMESPACE
  65610. #if (JUCE_WINDOWS || JUCE_LINUX) && ! JUCE_64BIT
  65611. #define JUCE_USE_SSE_INSTRUCTIONS 1
  65612. #endif
  65613. #if JUCE_MSVC
  65614. #if JUCE_DEBUG
  65615. #pragma optimize ("t", on) // optimise just this file, to avoid sluggish graphics when debugging
  65616. #pragma warning (disable: 4714) // warning about forcedinline methods not being inlined
  65617. #endif
  65618. #pragma warning (push)
  65619. #pragma warning (disable: 4127) // "expression is constant" warning
  65620. #endif
  65621. template <class PixelType, bool replaceExisting = false>
  65622. class SolidColourEdgeTableRenderer
  65623. {
  65624. public:
  65625. SolidColourEdgeTableRenderer (const Image::BitmapData& data_, const PixelARGB& colour) throw()
  65626. : data (data_),
  65627. sourceColour (colour)
  65628. {
  65629. if (sizeof (PixelType) == 3)
  65630. {
  65631. areRGBComponentsEqual = sourceColour.getRed() == sourceColour.getGreen()
  65632. && sourceColour.getGreen() == sourceColour.getBlue();
  65633. filler[0].set (sourceColour);
  65634. filler[1].set (sourceColour);
  65635. filler[2].set (sourceColour);
  65636. filler[3].set (sourceColour);
  65637. }
  65638. }
  65639. forcedinline void setEdgeTableYPos (const int y) throw()
  65640. {
  65641. linePixels = (PixelType*) data.getLinePointer (y);
  65642. }
  65643. forcedinline void handleEdgeTablePixel (const int x, const int alphaLevel) const throw()
  65644. {
  65645. if (replaceExisting)
  65646. linePixels[x].set (sourceColour);
  65647. else
  65648. linePixels[x].blend (sourceColour, alphaLevel);
  65649. }
  65650. forcedinline void handleEdgeTableLine (const int x, int width, const int alphaLevel) const throw()
  65651. {
  65652. PixelARGB p (sourceColour);
  65653. p.multiplyAlpha (alphaLevel);
  65654. PixelType* dest = linePixels + x;
  65655. if (replaceExisting || p.getAlpha() >= 0xff)
  65656. replaceLine (dest, p, width);
  65657. else
  65658. blendLine (dest, p, width);
  65659. }
  65660. private:
  65661. const Image::BitmapData& data;
  65662. PixelType* linePixels;
  65663. PixelARGB sourceColour;
  65664. PixelRGB filler [4];
  65665. bool areRGBComponentsEqual;
  65666. inline void blendLine (PixelType* dest, const PixelARGB& colour, int width) const throw()
  65667. {
  65668. do
  65669. {
  65670. dest->blend (colour);
  65671. ++dest;
  65672. } while (--width > 0);
  65673. }
  65674. forcedinline void replaceLine (PixelRGB* dest, const PixelARGB& colour, int width) const throw()
  65675. {
  65676. if (areRGBComponentsEqual) // if all the component values are the same, we can cheat..
  65677. {
  65678. memset (dest, colour.getRed(), width * 3);
  65679. }
  65680. else
  65681. {
  65682. if (width >> 5)
  65683. {
  65684. const int* const intFiller = (const int*) filler;
  65685. while (width > 8 && (((pointer_sized_int) dest) & 7) != 0)
  65686. {
  65687. dest->set (colour);
  65688. ++dest;
  65689. --width;
  65690. }
  65691. while (width > 4)
  65692. {
  65693. ((int*) dest) [0] = intFiller[0];
  65694. ((int*) dest) [1] = intFiller[1];
  65695. ((int*) dest) [2] = intFiller[2];
  65696. dest = (PixelRGB*) (((uint8*) dest) + 12);
  65697. width -= 4;
  65698. }
  65699. }
  65700. while (--width >= 0)
  65701. {
  65702. dest->set (colour);
  65703. ++dest;
  65704. }
  65705. }
  65706. }
  65707. forcedinline void replaceLine (PixelAlpha* dest, const PixelARGB& colour, int width) const throw()
  65708. {
  65709. memset (dest, colour.getAlpha(), width);
  65710. }
  65711. forcedinline void replaceLine (PixelARGB* dest, const PixelARGB& colour, int width) const throw()
  65712. {
  65713. do
  65714. {
  65715. dest->set (colour);
  65716. ++dest;
  65717. } while (--width > 0);
  65718. }
  65719. SolidColourEdgeTableRenderer (const SolidColourEdgeTableRenderer&);
  65720. SolidColourEdgeTableRenderer& operator= (const SolidColourEdgeTableRenderer&);
  65721. };
  65722. class LinearGradientPixelGenerator
  65723. {
  65724. public:
  65725. LinearGradientPixelGenerator (const ColourGradient& gradient, const AffineTransform& transform, const PixelARGB* const lookupTable_, const int numEntries_)
  65726. : lookupTable (lookupTable_), numEntries (numEntries_)
  65727. {
  65728. jassert (numEntries_ >= 0);
  65729. Point<float> p1 (gradient.x1, gradient.y1);
  65730. Point<float> p2 (gradient.x2, gradient.y2);
  65731. if (! transform.isIdentity())
  65732. {
  65733. const Line<float> l (p2, p1);
  65734. Point<float> p3 = l.getPointAlongLine (0.0f, 100.0f);
  65735. p1.applyTransform (transform);
  65736. p2.applyTransform (transform);
  65737. p3.applyTransform (transform);
  65738. const Line<float> l2 (p2, p3);
  65739. p2 = l2.getPointAlongLineProportionally (l2.findNearestPointTo (p1));
  65740. }
  65741. vertical = fabs (p1.getX() - p2.getX()) < 0.001f;
  65742. horizontal = fabs (p1.getY() - p2.getY()) < 0.001f;
  65743. if (vertical)
  65744. {
  65745. scale = roundToInt ((numEntries << (int) numScaleBits) / (double) (p2.getY() - p1.getY()));
  65746. start = roundToInt (p1.getY() * scale);
  65747. }
  65748. else if (horizontal)
  65749. {
  65750. scale = roundToInt ((numEntries << (int) numScaleBits) / (double) (p2.getX() - p1.getX()));
  65751. start = roundToInt (p1.getX() * scale);
  65752. }
  65753. else
  65754. {
  65755. grad = (p2.getY() - p1.getY()) / (double) (p1.getX() - p2.getX());
  65756. yTerm = p1.getY() - p1.getX() / grad;
  65757. scale = roundToInt ((numEntries << (int) numScaleBits) / (yTerm * grad - (p2.getY() * grad - p2.getX())));
  65758. grad *= scale;
  65759. }
  65760. }
  65761. forcedinline void setY (const int y) throw()
  65762. {
  65763. if (vertical)
  65764. linePix = lookupTable [jlimit (0, numEntries, (y * scale - start) >> (int) numScaleBits)];
  65765. else if (! horizontal)
  65766. start = roundToInt ((y - yTerm) * grad);
  65767. }
  65768. inline const PixelARGB getPixel (const int x) const throw()
  65769. {
  65770. return vertical ? linePix
  65771. : lookupTable [jlimit (0, numEntries, (x * scale - start) >> (int) numScaleBits)];
  65772. }
  65773. private:
  65774. const PixelARGB* const lookupTable;
  65775. const int numEntries;
  65776. PixelARGB linePix;
  65777. int start, scale;
  65778. double grad, yTerm;
  65779. bool vertical, horizontal;
  65780. enum { numScaleBits = 12 };
  65781. LinearGradientPixelGenerator (const LinearGradientPixelGenerator&);
  65782. LinearGradientPixelGenerator& operator= (const LinearGradientPixelGenerator&);
  65783. };
  65784. class RadialGradientPixelGenerator
  65785. {
  65786. public:
  65787. RadialGradientPixelGenerator (const ColourGradient& gradient, const AffineTransform&,
  65788. const PixelARGB* const lookupTable_, const int numEntries_) throw()
  65789. : lookupTable (lookupTable_),
  65790. numEntries (numEntries_),
  65791. gx1 (gradient.x1),
  65792. gy1 (gradient.y1)
  65793. {
  65794. jassert (numEntries_ >= 0);
  65795. const float gdx = gradient.x1 - gradient.x2;
  65796. const float gdy = gradient.y1 - gradient.y2;
  65797. maxDist = gdx * gdx + gdy * gdy;
  65798. invScale = numEntries / sqrt (maxDist);
  65799. jassert (roundToInt (sqrt (maxDist) * invScale) <= numEntries);
  65800. }
  65801. forcedinline void setY (const int y) throw()
  65802. {
  65803. dy = y - gy1;
  65804. dy *= dy;
  65805. }
  65806. inline const PixelARGB getPixel (const int px) const throw()
  65807. {
  65808. double x = px - gx1;
  65809. x *= x;
  65810. x += dy;
  65811. return lookupTable [x >= maxDist ? numEntries : roundToInt (sqrt (x) * invScale)];
  65812. }
  65813. protected:
  65814. const PixelARGB* const lookupTable;
  65815. const int numEntries;
  65816. const double gx1, gy1;
  65817. double maxDist, invScale, dy;
  65818. RadialGradientPixelGenerator (const RadialGradientPixelGenerator&);
  65819. RadialGradientPixelGenerator& operator= (const RadialGradientPixelGenerator&);
  65820. };
  65821. class TransformedRadialGradientPixelGenerator : public RadialGradientPixelGenerator
  65822. {
  65823. public:
  65824. TransformedRadialGradientPixelGenerator (const ColourGradient& gradient, const AffineTransform& transform,
  65825. const PixelARGB* const lookupTable_, const int numEntries_) throw()
  65826. : RadialGradientPixelGenerator (gradient, transform, lookupTable_, numEntries_),
  65827. inverseTransform (transform.inverted())
  65828. {
  65829. tM10 = inverseTransform.mat10;
  65830. tM00 = inverseTransform.mat00;
  65831. }
  65832. forcedinline void setY (const int y) throw()
  65833. {
  65834. lineYM01 = inverseTransform.mat01 * y + inverseTransform.mat02 - gx1;
  65835. lineYM11 = inverseTransform.mat11 * y + inverseTransform.mat12 - gy1;
  65836. }
  65837. inline const PixelARGB getPixel (const int px) const throw()
  65838. {
  65839. double x = px;
  65840. const double y = tM10 * x + lineYM11;
  65841. x = tM00 * x + lineYM01;
  65842. x *= x;
  65843. x += y * y;
  65844. if (x >= maxDist)
  65845. return lookupTable [numEntries];
  65846. else
  65847. return lookupTable [jmin (numEntries, roundToInt (sqrt (x) * invScale))];
  65848. }
  65849. private:
  65850. double tM10, tM00, lineYM01, lineYM11;
  65851. const AffineTransform inverseTransform;
  65852. TransformedRadialGradientPixelGenerator (const TransformedRadialGradientPixelGenerator&);
  65853. TransformedRadialGradientPixelGenerator& operator= (const TransformedRadialGradientPixelGenerator&);
  65854. };
  65855. template <class PixelType, class GradientType>
  65856. class GradientEdgeTableRenderer : public GradientType
  65857. {
  65858. public:
  65859. GradientEdgeTableRenderer (const Image::BitmapData& destData_, const ColourGradient& gradient, const AffineTransform& transform,
  65860. const PixelARGB* const lookupTable_, const int numEntries_) throw()
  65861. : GradientType (gradient, transform, lookupTable_, numEntries_ - 1),
  65862. destData (destData_)
  65863. {
  65864. }
  65865. forcedinline void setEdgeTableYPos (const int y) throw()
  65866. {
  65867. linePixels = (PixelType*) destData.getLinePointer (y);
  65868. GradientType::setY (y);
  65869. }
  65870. forcedinline void handleEdgeTablePixel (const int x, const int alphaLevel) const throw()
  65871. {
  65872. linePixels[x].blend (GradientType::getPixel (x), alphaLevel);
  65873. }
  65874. forcedinline void handleEdgeTableLine (int x, int width, const int alphaLevel) const throw()
  65875. {
  65876. PixelType* dest = linePixels + x;
  65877. if (alphaLevel < 0xff)
  65878. {
  65879. do
  65880. {
  65881. (dest++)->blend (GradientType::getPixel (x++), alphaLevel);
  65882. } while (--width > 0);
  65883. }
  65884. else
  65885. {
  65886. do
  65887. {
  65888. (dest++)->blend (GradientType::getPixel (x++));
  65889. } while (--width > 0);
  65890. }
  65891. }
  65892. private:
  65893. const Image::BitmapData& destData;
  65894. PixelType* linePixels;
  65895. GradientEdgeTableRenderer (const GradientEdgeTableRenderer&);
  65896. GradientEdgeTableRenderer& operator= (const GradientEdgeTableRenderer&);
  65897. };
  65898. static forcedinline int safeModulo (int n, const int divisor) throw()
  65899. {
  65900. jassert (divisor > 0);
  65901. n %= divisor;
  65902. return (n < 0) ? (n + divisor) : n;
  65903. }
  65904. template <class DestPixelType, class SrcPixelType, bool repeatPattern>
  65905. class ImageFillEdgeTableRenderer
  65906. {
  65907. public:
  65908. ImageFillEdgeTableRenderer (const Image::BitmapData& destData_,
  65909. const Image::BitmapData& srcData_,
  65910. const int extraAlpha_,
  65911. const int x, const int y) throw()
  65912. : destData (destData_),
  65913. srcData (srcData_),
  65914. extraAlpha (extraAlpha_ + 1),
  65915. xOffset (repeatPattern ? safeModulo (x, srcData_.width) - srcData_.width : x),
  65916. yOffset (repeatPattern ? safeModulo (y, srcData_.height) - srcData_.height : y)
  65917. {
  65918. }
  65919. forcedinline void setEdgeTableYPos (int y) throw()
  65920. {
  65921. linePixels = (DestPixelType*) destData.getLinePointer (y);
  65922. y -= yOffset;
  65923. if (repeatPattern)
  65924. {
  65925. jassert (y >= 0);
  65926. y %= srcData.height;
  65927. }
  65928. sourceLineStart = (SrcPixelType*) srcData.getLinePointer (y);
  65929. }
  65930. forcedinline void handleEdgeTablePixel (int x, int alphaLevel) const throw()
  65931. {
  65932. alphaLevel = (alphaLevel * extraAlpha) >> 8;
  65933. linePixels[x].blend (sourceLineStart [repeatPattern ? ((x - xOffset) % srcData.width) : (x - xOffset)], alphaLevel);
  65934. }
  65935. forcedinline void handleEdgeTableLine (int x, int width, int alphaLevel) const throw()
  65936. {
  65937. DestPixelType* dest = linePixels + x;
  65938. alphaLevel = (alphaLevel * extraAlpha) >> 8;
  65939. x -= xOffset;
  65940. jassert (repeatPattern || (x >= 0 && x + width <= srcData.width));
  65941. if (alphaLevel < 0xfe)
  65942. {
  65943. do
  65944. {
  65945. dest++ ->blend (sourceLineStart [repeatPattern ? (x++ % srcData.width) : x++], alphaLevel);
  65946. } while (--width > 0);
  65947. }
  65948. else
  65949. {
  65950. if (repeatPattern)
  65951. {
  65952. do
  65953. {
  65954. dest++ ->blend (sourceLineStart [x++ % srcData.width]);
  65955. } while (--width > 0);
  65956. }
  65957. else
  65958. {
  65959. copyRow (dest, sourceLineStart + x, width);
  65960. }
  65961. }
  65962. }
  65963. void clipEdgeTableLine (EdgeTable& et, int x, int y, int width) throw()
  65964. {
  65965. jassert (x - xOffset >= 0 && x + width - xOffset <= srcData.width);
  65966. SrcPixelType* s = (SrcPixelType*) srcData.getLinePointer (y - yOffset);
  65967. uint8* mask = (uint8*) (s + x - xOffset);
  65968. if (sizeof (SrcPixelType) == sizeof (PixelARGB))
  65969. mask += PixelARGB::indexA;
  65970. et.clipLineToMask (x, y, mask, sizeof (SrcPixelType), width);
  65971. }
  65972. private:
  65973. const Image::BitmapData& destData;
  65974. const Image::BitmapData& srcData;
  65975. const int extraAlpha, xOffset, yOffset;
  65976. DestPixelType* linePixels;
  65977. SrcPixelType* sourceLineStart;
  65978. template <class PixelType1, class PixelType2>
  65979. forcedinline static void copyRow (PixelType1* dest, PixelType2* src, int width) throw()
  65980. {
  65981. do
  65982. {
  65983. dest++ ->blend (*src++);
  65984. } while (--width > 0);
  65985. }
  65986. forcedinline static void copyRow (PixelRGB* dest, PixelRGB* src, int width) throw()
  65987. {
  65988. memcpy (dest, src, width * sizeof (PixelRGB));
  65989. }
  65990. ImageFillEdgeTableRenderer (const ImageFillEdgeTableRenderer&);
  65991. ImageFillEdgeTableRenderer& operator= (const ImageFillEdgeTableRenderer&);
  65992. };
  65993. template <class DestPixelType, class SrcPixelType, bool repeatPattern>
  65994. class TransformedImageFillEdgeTableRenderer
  65995. {
  65996. public:
  65997. TransformedImageFillEdgeTableRenderer (const Image::BitmapData& destData_,
  65998. const Image::BitmapData& srcData_,
  65999. const AffineTransform& transform,
  66000. const int extraAlpha_,
  66001. const bool betterQuality_) throw()
  66002. : interpolator (transform),
  66003. destData (destData_),
  66004. srcData (srcData_),
  66005. extraAlpha (extraAlpha_ + 1),
  66006. betterQuality (betterQuality_),
  66007. pixelOffset (betterQuality_ ? 0.5f : 0.0f),
  66008. pixelOffsetInt (betterQuality_ ? -128 : 0),
  66009. maxX (srcData_.width - 1),
  66010. maxY (srcData_.height - 1),
  66011. scratchSize (2048)
  66012. {
  66013. scratchBuffer.malloc (scratchSize);
  66014. }
  66015. ~TransformedImageFillEdgeTableRenderer() throw()
  66016. {
  66017. }
  66018. forcedinline void setEdgeTableYPos (const int newY) throw()
  66019. {
  66020. y = newY;
  66021. linePixels = (DestPixelType*) destData.getLinePointer (newY);
  66022. }
  66023. forcedinline void handleEdgeTablePixel (const int x, int alphaLevel) throw()
  66024. {
  66025. alphaLevel *= extraAlpha;
  66026. alphaLevel >>= 8;
  66027. SrcPixelType p;
  66028. generate (&p, x, 1);
  66029. linePixels[x].blend (p, alphaLevel);
  66030. }
  66031. forcedinline void handleEdgeTableLine (const int x, int width, int alphaLevel) throw()
  66032. {
  66033. if (width > scratchSize)
  66034. {
  66035. scratchSize = width;
  66036. scratchBuffer.malloc (scratchSize);
  66037. }
  66038. SrcPixelType* span = scratchBuffer;
  66039. generate (span, x, width);
  66040. DestPixelType* dest = linePixels + x;
  66041. alphaLevel *= extraAlpha;
  66042. alphaLevel >>= 8;
  66043. if (alphaLevel < 0xfe)
  66044. {
  66045. do
  66046. {
  66047. dest++ ->blend (*span++, alphaLevel);
  66048. } while (--width > 0);
  66049. }
  66050. else
  66051. {
  66052. do
  66053. {
  66054. dest++ ->blend (*span++);
  66055. } while (--width > 0);
  66056. }
  66057. }
  66058. void clipEdgeTableLine (EdgeTable& et, int x, int y_, int width) throw()
  66059. {
  66060. if (width > scratchSize)
  66061. {
  66062. scratchSize = width;
  66063. scratchBuffer.malloc (scratchSize);
  66064. }
  66065. y = y_;
  66066. generate (scratchBuffer, x, width);
  66067. et.clipLineToMask (x, y_,
  66068. reinterpret_cast<uint8*> (scratchBuffer.getData()) + SrcPixelType::indexA,
  66069. sizeof (SrcPixelType), width);
  66070. }
  66071. private:
  66072. void generate (PixelARGB* dest, const int x, int numPixels) throw()
  66073. {
  66074. this->interpolator.setStartOfLine (x + pixelOffset, y + pixelOffset, numPixels);
  66075. do
  66076. {
  66077. int hiResX, hiResY;
  66078. this->interpolator.next (hiResX, hiResY);
  66079. hiResX += pixelOffsetInt;
  66080. hiResY += pixelOffsetInt;
  66081. int loResX = hiResX >> 8;
  66082. int loResY = hiResY >> 8;
  66083. if (repeatPattern)
  66084. {
  66085. loResX = safeModulo (loResX, srcData.width);
  66086. loResY = safeModulo (loResY, srcData.height);
  66087. }
  66088. if (betterQuality
  66089. && ((unsigned int) loResX) < (unsigned int) maxX
  66090. && ((unsigned int) loResY) < (unsigned int) maxY)
  66091. {
  66092. uint32 c[4] = { 256 * 128, 256 * 128, 256 * 128, 256 * 128 };
  66093. hiResX &= 255;
  66094. hiResY &= 255;
  66095. const uint8* src = this->srcData.getPixelPointer (loResX, loResY);
  66096. uint32 weight = (256 - hiResX) * (256 - hiResY);
  66097. c[0] += weight * src[0];
  66098. c[1] += weight * src[1];
  66099. c[2] += weight * src[2];
  66100. c[3] += weight * src[3];
  66101. weight = hiResX * (256 - hiResY);
  66102. c[0] += weight * src[4];
  66103. c[1] += weight * src[5];
  66104. c[2] += weight * src[6];
  66105. c[3] += weight * src[7];
  66106. src += this->srcData.lineStride;
  66107. weight = (256 - hiResX) * hiResY;
  66108. c[0] += weight * src[0];
  66109. c[1] += weight * src[1];
  66110. c[2] += weight * src[2];
  66111. c[3] += weight * src[3];
  66112. weight = hiResX * hiResY;
  66113. c[0] += weight * src[4];
  66114. c[1] += weight * src[5];
  66115. c[2] += weight * src[6];
  66116. c[3] += weight * src[7];
  66117. dest->setARGB ((uint8) (c[PixelARGB::indexA] >> 16),
  66118. (uint8) (c[PixelARGB::indexR] >> 16),
  66119. (uint8) (c[PixelARGB::indexG] >> 16),
  66120. (uint8) (c[PixelARGB::indexB] >> 16));
  66121. }
  66122. else
  66123. {
  66124. if (! repeatPattern)
  66125. {
  66126. // Beyond the edges, just repeat the edge pixels and leave the anti-aliasing to be handled by the edgetable
  66127. if (loResX < 0) loResX = 0;
  66128. if (loResY < 0) loResY = 0;
  66129. if (loResX > maxX) loResX = maxX;
  66130. if (loResY > maxY) loResY = maxY;
  66131. }
  66132. dest->set (*(const PixelARGB*) this->srcData.getPixelPointer (loResX, loResY));
  66133. }
  66134. ++dest;
  66135. } while (--numPixels > 0);
  66136. }
  66137. void generate (PixelRGB* dest, const int x, int numPixels) throw()
  66138. {
  66139. this->interpolator.setStartOfLine (x + pixelOffset, y + pixelOffset, numPixels);
  66140. do
  66141. {
  66142. int hiResX, hiResY;
  66143. this->interpolator.next (hiResX, hiResY);
  66144. hiResX += pixelOffsetInt;
  66145. hiResY += pixelOffsetInt;
  66146. int loResX = hiResX >> 8;
  66147. int loResY = hiResY >> 8;
  66148. if (repeatPattern)
  66149. {
  66150. loResX = safeModulo (loResX, srcData.width);
  66151. loResY = safeModulo (loResY, srcData.height);
  66152. }
  66153. if (betterQuality
  66154. && ((unsigned int) loResX) < (unsigned int) maxX
  66155. && ((unsigned int) loResY) < (unsigned int) maxY)
  66156. {
  66157. uint32 c[3] = { 256 * 128, 256 * 128, 256 * 128 };
  66158. hiResX &= 255;
  66159. hiResY &= 255;
  66160. const uint8* src = this->srcData.getPixelPointer (loResX, loResY);
  66161. unsigned int weight = (256 - hiResX) * (256 - hiResY);
  66162. c[0] += weight * src[0];
  66163. c[1] += weight * src[1];
  66164. c[2] += weight * src[2];
  66165. weight = hiResX * (256 - hiResY);
  66166. c[0] += weight * src[3];
  66167. c[1] += weight * src[4];
  66168. c[2] += weight * src[5];
  66169. src += this->srcData.lineStride;
  66170. weight = (256 - hiResX) * hiResY;
  66171. c[0] += weight * src[0];
  66172. c[1] += weight * src[1];
  66173. c[2] += weight * src[2];
  66174. weight = hiResX * hiResY;
  66175. c[0] += weight * src[3];
  66176. c[1] += weight * src[4];
  66177. c[2] += weight * src[5];
  66178. dest->setARGB ((uint8) 255,
  66179. (uint8) (c[PixelRGB::indexR] >> 16),
  66180. (uint8) (c[PixelRGB::indexG] >> 16),
  66181. (uint8) (c[PixelRGB::indexB] >> 16));
  66182. }
  66183. else
  66184. {
  66185. if (! repeatPattern)
  66186. {
  66187. // Beyond the edges, just repeat the edge pixels and leave the anti-aliasing to be handled by the edgetable
  66188. if (loResX < 0) loResX = 0;
  66189. if (loResY < 0) loResY = 0;
  66190. if (loResX > maxX) loResX = maxX;
  66191. if (loResY > maxY) loResY = maxY;
  66192. }
  66193. dest->set (*(const PixelRGB*) this->srcData.getPixelPointer (loResX, loResY));
  66194. }
  66195. ++dest;
  66196. } while (--numPixels > 0);
  66197. }
  66198. void generate (PixelAlpha* dest, const int x, int numPixels) throw()
  66199. {
  66200. this->interpolator.setStartOfLine (x + pixelOffset, y + pixelOffset, numPixels);
  66201. do
  66202. {
  66203. int hiResX, hiResY;
  66204. this->interpolator.next (hiResX, hiResY);
  66205. hiResX += pixelOffsetInt;
  66206. hiResY += pixelOffsetInt;
  66207. int loResX = hiResX >> 8;
  66208. int loResY = hiResY >> 8;
  66209. if (repeatPattern)
  66210. {
  66211. loResX = safeModulo (loResX, srcData.width);
  66212. loResY = safeModulo (loResY, srcData.height);
  66213. }
  66214. if (betterQuality
  66215. && ((unsigned int) loResX) < (unsigned int) maxX
  66216. && ((unsigned int) loResY) < (unsigned int) maxY)
  66217. {
  66218. hiResX &= 255;
  66219. hiResY &= 255;
  66220. const uint8* src = this->srcData.getPixelPointer (loResX, loResY);
  66221. uint32 c = 256 * 128;
  66222. c += src[0] * ((256 - hiResX) * (256 - hiResY));
  66223. c += src[1] * (hiResX * (256 - hiResY));
  66224. src += this->srcData.lineStride;
  66225. c += src[0] * ((256 - hiResX) * hiResY);
  66226. c += src[1] * (hiResX * hiResY);
  66227. *((uint8*) dest) = (uint8) c;
  66228. }
  66229. else
  66230. {
  66231. if (! repeatPattern)
  66232. {
  66233. // Beyond the edges, just repeat the edge pixels and leave the anti-aliasing to be handled by the edgetable
  66234. if (loResX < 0) loResX = 0;
  66235. if (loResY < 0) loResY = 0;
  66236. if (loResX > maxX) loResX = maxX;
  66237. if (loResY > maxY) loResY = maxY;
  66238. }
  66239. *((uint8*) dest) = *(this->srcData.getPixelPointer (loResX, loResY));
  66240. }
  66241. ++dest;
  66242. } while (--numPixels > 0);
  66243. }
  66244. class TransformedImageSpanInterpolator
  66245. {
  66246. public:
  66247. TransformedImageSpanInterpolator (const AffineTransform& transform) throw()
  66248. : inverseTransform (transform.inverted())
  66249. {}
  66250. void setStartOfLine (float x, float y, const int numPixels) throw()
  66251. {
  66252. float x1 = x, y1 = y;
  66253. inverseTransform.transformPoint (x1, y1);
  66254. x += numPixels;
  66255. inverseTransform.transformPoint (x, y);
  66256. xBresenham.set ((int) (x1 * 256.0f), (int) (x * 256.0f), numPixels);
  66257. yBresenham.set ((int) (y1 * 256.0f), (int) (y * 256.0f), numPixels);
  66258. }
  66259. void next (int& x, int& y) throw()
  66260. {
  66261. x = xBresenham.n;
  66262. xBresenham.stepToNext();
  66263. y = yBresenham.n;
  66264. yBresenham.stepToNext();
  66265. }
  66266. private:
  66267. class BresenhamInterpolator
  66268. {
  66269. public:
  66270. BresenhamInterpolator() throw() {}
  66271. void set (const int n1, const int n2, const int numSteps_) throw()
  66272. {
  66273. numSteps = jmax (1, numSteps_);
  66274. step = (n2 - n1) / numSteps;
  66275. remainder = modulo = (n2 - n1) % numSteps;
  66276. n = n1;
  66277. if (modulo <= 0)
  66278. {
  66279. modulo += numSteps;
  66280. remainder += numSteps;
  66281. --step;
  66282. }
  66283. modulo -= numSteps;
  66284. }
  66285. forcedinline void stepToNext() throw()
  66286. {
  66287. modulo += remainder;
  66288. n += step;
  66289. if (modulo > 0)
  66290. {
  66291. modulo -= numSteps;
  66292. ++n;
  66293. }
  66294. }
  66295. int n;
  66296. private:
  66297. int numSteps, step, modulo, remainder;
  66298. };
  66299. const AffineTransform inverseTransform;
  66300. BresenhamInterpolator xBresenham, yBresenham;
  66301. TransformedImageSpanInterpolator (const TransformedImageSpanInterpolator&);
  66302. TransformedImageSpanInterpolator& operator= (const TransformedImageSpanInterpolator&);
  66303. };
  66304. TransformedImageSpanInterpolator interpolator;
  66305. const Image::BitmapData& destData;
  66306. const Image::BitmapData& srcData;
  66307. const int extraAlpha;
  66308. const bool betterQuality;
  66309. const float pixelOffset;
  66310. const int pixelOffsetInt, maxX, maxY;
  66311. int y;
  66312. DestPixelType* linePixels;
  66313. HeapBlock <SrcPixelType> scratchBuffer;
  66314. int scratchSize;
  66315. TransformedImageFillEdgeTableRenderer (const TransformedImageFillEdgeTableRenderer&);
  66316. TransformedImageFillEdgeTableRenderer& operator= (const TransformedImageFillEdgeTableRenderer&);
  66317. };
  66318. class LLGCSavedState
  66319. {
  66320. public:
  66321. LLGCSavedState (const Rectangle<int>& clip_, const int xOffset_, const int yOffset_,
  66322. const Font& font_, const FillType& fillType_,
  66323. const Graphics::ResamplingQuality interpolationQuality_) throw()
  66324. : edgeTable (new EdgeTableHolder (EdgeTable (clip_))),
  66325. xOffset (xOffset_), yOffset (yOffset_),
  66326. font (font_), fillType (fillType_),
  66327. interpolationQuality (interpolationQuality_)
  66328. {
  66329. }
  66330. LLGCSavedState (const LLGCSavedState& other) throw()
  66331. : edgeTable (other.edgeTable), xOffset (other.xOffset),
  66332. yOffset (other.yOffset), font (other.font),
  66333. fillType (other.fillType), interpolationQuality (other.interpolationQuality)
  66334. {
  66335. }
  66336. ~LLGCSavedState() throw()
  66337. {
  66338. }
  66339. bool clipToRectangle (const Rectangle<int>& r) throw()
  66340. {
  66341. dupeEdgeTableIfMultiplyReferenced();
  66342. edgeTable->edgeTable.clipToRectangle (r.translated (xOffset, yOffset));
  66343. return ! edgeTable->edgeTable.isEmpty();
  66344. }
  66345. bool clipToRectangleList (const RectangleList& r) throw()
  66346. {
  66347. dupeEdgeTableIfMultiplyReferenced();
  66348. RectangleList offsetList (r);
  66349. offsetList.offsetAll (xOffset, yOffset);
  66350. EdgeTable e2 (offsetList);
  66351. edgeTable->edgeTable.clipToEdgeTable (e2);
  66352. return ! edgeTable->edgeTable.isEmpty();
  66353. }
  66354. bool excludeClipRectangle (const Rectangle<int>& r) throw()
  66355. {
  66356. dupeEdgeTableIfMultiplyReferenced();
  66357. edgeTable->edgeTable.excludeRectangle (r.translated (xOffset, yOffset));
  66358. return ! edgeTable->edgeTable.isEmpty();
  66359. }
  66360. void clipToPath (const Path& p, const AffineTransform& transform) throw()
  66361. {
  66362. dupeEdgeTableIfMultiplyReferenced();
  66363. EdgeTable et (edgeTable->edgeTable.getMaximumBounds(), p, transform.translated ((float) xOffset, (float) yOffset));
  66364. edgeTable->edgeTable.clipToEdgeTable (et);
  66365. }
  66366. void fillEdgeTable (Image& image, EdgeTable& et, const bool replaceContents = false) throw()
  66367. {
  66368. et.clipToEdgeTable (edgeTable->edgeTable);
  66369. Image::BitmapData destData (image, 0, 0, image.getWidth(), image.getHeight(), true);
  66370. if (fillType.isGradient())
  66371. {
  66372. jassert (! replaceContents); // that option is just for solid colours
  66373. ColourGradient g2 (*(fillType.gradient));
  66374. g2.multiplyOpacity (fillType.getOpacity());
  66375. g2.x1 -= 0.5f; g2.y1 -= 0.5f;
  66376. g2.x2 -= 0.5f; g2.y2 -= 0.5f;
  66377. AffineTransform transform (fillType.transform.translated ((float) xOffset, (float) yOffset));
  66378. const bool isIdentity = transform.isOnlyTranslation();
  66379. if (isIdentity)
  66380. {
  66381. // If our translation doesn't involve any distortion, we can speed it up..
  66382. transform.transformPoint (g2.x1, g2.y1);
  66383. transform.transformPoint (g2.x2, g2.y2);
  66384. transform = AffineTransform::identity;
  66385. }
  66386. HeapBlock <PixelARGB> lookupTable;
  66387. const int numLookupEntries = g2.createLookupTable (transform, lookupTable);
  66388. jassert (numLookupEntries > 0);
  66389. switch (image.getFormat())
  66390. {
  66391. case Image::ARGB: renderGradient (et, destData, g2, transform, lookupTable, numLookupEntries, isIdentity, (PixelARGB*) 0); break;
  66392. case Image::RGB: renderGradient (et, destData, g2, transform, lookupTable, numLookupEntries, isIdentity, (PixelRGB*) 0); break;
  66393. default: renderGradient (et, destData, g2, transform, lookupTable, numLookupEntries, isIdentity, (PixelAlpha*) 0); break;
  66394. }
  66395. }
  66396. else if (fillType.isTiledImage())
  66397. {
  66398. renderImage (image, *(fillType.image), fillType.image->getBounds(), fillType.transform, &et);
  66399. }
  66400. else
  66401. {
  66402. const PixelARGB fillColour (fillType.colour.getPixelARGB());
  66403. switch (image.getFormat())
  66404. {
  66405. case Image::ARGB: renderSolidFill (et, destData, fillColour, replaceContents, (PixelARGB*) 0); break;
  66406. case Image::RGB: renderSolidFill (et, destData, fillColour, replaceContents, (PixelRGB*) 0); break;
  66407. default: renderSolidFill (et, destData, fillColour, replaceContents, (PixelAlpha*) 0); break;
  66408. }
  66409. }
  66410. }
  66411. void renderImage (Image& destImage, const Image& sourceImage, const Rectangle<int>& srcClip,
  66412. const AffineTransform& t, const EdgeTable* const tiledFillClipRegion) throw()
  66413. {
  66414. const AffineTransform transform (t.translated ((float) xOffset, (float) yOffset));
  66415. const Image::BitmapData destData (destImage, 0, 0, destImage.getWidth(), destImage.getHeight(), true);
  66416. const Image::BitmapData srcData (sourceImage, srcClip.getX(), srcClip.getY(), srcClip.getWidth(), srcClip.getHeight());
  66417. const int alpha = fillType.colour.getAlpha();
  66418. const bool betterQuality = (interpolationQuality != Graphics::lowResamplingQuality);
  66419. if (transform.isOnlyTranslation())
  66420. {
  66421. // If our translation doesn't involve any distortion, just use a simple blit..
  66422. int tx = (int) (transform.getTranslationX() * 256.0f);
  66423. int ty = (int) (transform.getTranslationY() * 256.0f);
  66424. if ((! betterQuality) || ((tx | ty) & 224) == 0)
  66425. {
  66426. tx = ((tx + 128) >> 8);
  66427. ty = ((ty + 128) >> 8);
  66428. if (tiledFillClipRegion != 0)
  66429. {
  66430. blittedRenderImage (sourceImage, destImage, *tiledFillClipRegion, destData, srcData, alpha, tx, ty, true);
  66431. }
  66432. else
  66433. {
  66434. EdgeTable et (Rectangle<int> (tx, ty, srcClip.getWidth(), srcClip.getHeight()).getIntersection (destImage.getBounds()));
  66435. et.clipToEdgeTable (edgeTable->edgeTable);
  66436. if (! et.isEmpty())
  66437. blittedRenderImage (sourceImage, destImage, et, destData, srcData, alpha, tx, ty, false);
  66438. }
  66439. return;
  66440. }
  66441. }
  66442. if (transform.isSingularity())
  66443. return;
  66444. if (tiledFillClipRegion != 0)
  66445. {
  66446. transformedRenderImage (sourceImage, destImage, *tiledFillClipRegion, destData, srcData, alpha, transform, betterQuality, true);
  66447. }
  66448. else
  66449. {
  66450. Path p;
  66451. p.addRectangle (0.0f, 0.0f, (float) srcClip.getWidth(), (float) srcClip.getHeight());
  66452. EdgeTable et (edgeTable->edgeTable.getMaximumBounds(), p, transform);
  66453. et.clipToEdgeTable (edgeTable->edgeTable);
  66454. if (! et.isEmpty())
  66455. transformedRenderImage (sourceImage, destImage, et, destData, srcData, alpha, transform, betterQuality, false);
  66456. }
  66457. }
  66458. void clipToImageAlpha (const Image& image, const Rectangle<int>& srcClip, const AffineTransform& t) throw()
  66459. {
  66460. if (! image.hasAlphaChannel())
  66461. {
  66462. Path p;
  66463. p.addRectangle (srcClip);
  66464. clipToPath (p, t);
  66465. return;
  66466. }
  66467. dupeEdgeTableIfMultiplyReferenced();
  66468. const AffineTransform transform (t.translated ((float) xOffset, (float) yOffset));
  66469. const Image::BitmapData srcData (image, srcClip.getX(), srcClip.getY(), srcClip.getWidth(), srcClip.getHeight());
  66470. const bool betterQuality = (interpolationQuality != Graphics::lowResamplingQuality);
  66471. EdgeTable& et = edgeTable->edgeTable;
  66472. if (transform.isOnlyTranslation())
  66473. {
  66474. // If our translation doesn't involve any distortion, just use a simple blit..
  66475. const int tx = (int) (transform.getTranslationX() * 256.0f);
  66476. const int ty = (int) (transform.getTranslationY() * 256.0f);
  66477. if ((! betterQuality) || ((tx | ty) & 224) == 0)
  66478. {
  66479. const int imageX = ((tx + 128) >> 8);
  66480. const int imageY = ((ty + 128) >> 8);
  66481. if (image.getFormat() == Image::ARGB)
  66482. straightClipImage (et, srcData, imageX, imageY, (PixelARGB*)0);
  66483. else
  66484. straightClipImage (et, srcData, imageX, imageY, (PixelAlpha*)0);
  66485. return;
  66486. }
  66487. }
  66488. if (transform.isSingularity())
  66489. {
  66490. et.clipToRectangle (Rectangle<int>());
  66491. return;
  66492. }
  66493. {
  66494. Path p;
  66495. p.addRectangle (0, 0, (float) srcData.width, (float) srcData.height);
  66496. EdgeTable et2 (et.getMaximumBounds(), p, transform);
  66497. et.clipToEdgeTable (et2);
  66498. }
  66499. if (! et.isEmpty())
  66500. {
  66501. if (image.getFormat() == Image::ARGB)
  66502. transformedClipImage (et, srcData, transform, betterQuality, (PixelARGB*)0);
  66503. else
  66504. transformedClipImage (et, srcData, transform, betterQuality, (PixelAlpha*)0);
  66505. }
  66506. }
  66507. template <class SrcPixelType>
  66508. void transformedClipImage (EdgeTable& et, const Image::BitmapData& srcData, const AffineTransform& transform, const bool betterQuality, const SrcPixelType *) throw()
  66509. {
  66510. TransformedImageFillEdgeTableRenderer <SrcPixelType, SrcPixelType, false> renderer (srcData, srcData, transform, 255, betterQuality);
  66511. for (int y = 0; y < et.getMaximumBounds().getHeight(); ++y)
  66512. renderer.clipEdgeTableLine (et, et.getMaximumBounds().getX(), y + et.getMaximumBounds().getY(),
  66513. et.getMaximumBounds().getWidth());
  66514. }
  66515. template <class SrcPixelType>
  66516. void straightClipImage (EdgeTable& et, const Image::BitmapData& srcData, int imageX, int imageY, const SrcPixelType *) throw()
  66517. {
  66518. Rectangle<int> r (imageX, imageY, srcData.width, srcData.height);
  66519. et.clipToRectangle (r);
  66520. ImageFillEdgeTableRenderer <SrcPixelType, SrcPixelType, false> renderer (srcData, srcData, 255, imageX, imageY);
  66521. for (int y = 0; y < r.getHeight(); ++y)
  66522. renderer.clipEdgeTableLine (et, r.getX(), y + r.getY(), r.getWidth());
  66523. }
  66524. class EdgeTableHolder : public ReferenceCountedObject
  66525. {
  66526. public:
  66527. EdgeTableHolder (const EdgeTable& e) throw() : edgeTable (e) {}
  66528. EdgeTable edgeTable;
  66529. };
  66530. ReferenceCountedObjectPtr<EdgeTableHolder> edgeTable;
  66531. int xOffset, yOffset;
  66532. Font font;
  66533. FillType fillType;
  66534. Graphics::ResamplingQuality interpolationQuality;
  66535. private:
  66536. LLGCSavedState& operator= (const LLGCSavedState&);
  66537. void dupeEdgeTableIfMultiplyReferenced() throw()
  66538. {
  66539. if (edgeTable->getReferenceCount() > 1)
  66540. edgeTable = new EdgeTableHolder (edgeTable->edgeTable);
  66541. }
  66542. template <class DestPixelType>
  66543. void renderGradient (EdgeTable& et, const Image::BitmapData& destData, const ColourGradient& g, const AffineTransform& transform,
  66544. const PixelARGB* const lookupTable, const int numLookupEntries, const bool isIdentity, DestPixelType*) throw()
  66545. {
  66546. jassert (destData.pixelStride == sizeof (DestPixelType));
  66547. if (g.isRadial)
  66548. {
  66549. if (isIdentity)
  66550. {
  66551. GradientEdgeTableRenderer <DestPixelType, RadialGradientPixelGenerator> renderer (destData, g, transform, lookupTable, numLookupEntries);
  66552. et.iterate (renderer);
  66553. }
  66554. else
  66555. {
  66556. GradientEdgeTableRenderer <DestPixelType, TransformedRadialGradientPixelGenerator> renderer (destData, g, transform, lookupTable, numLookupEntries);
  66557. et.iterate (renderer);
  66558. }
  66559. }
  66560. else
  66561. {
  66562. GradientEdgeTableRenderer <DestPixelType, LinearGradientPixelGenerator> renderer (destData, g, transform, lookupTable, numLookupEntries);
  66563. et.iterate (renderer);
  66564. }
  66565. }
  66566. template <class DestPixelType>
  66567. void renderSolidFill (EdgeTable& et, const Image::BitmapData& destData, const PixelARGB& fillColour, const bool replaceContents, DestPixelType*) throw()
  66568. {
  66569. jassert (destData.pixelStride == sizeof (DestPixelType));
  66570. if (replaceContents)
  66571. {
  66572. SolidColourEdgeTableRenderer <DestPixelType, true> r (destData, fillColour);
  66573. et.iterate (r);
  66574. }
  66575. else
  66576. {
  66577. SolidColourEdgeTableRenderer <DestPixelType, false> r (destData, fillColour);
  66578. et.iterate (r);
  66579. }
  66580. }
  66581. void transformedRenderImage (const Image& srcImage, Image& destImage, const EdgeTable& et, const Image::BitmapData& destData, const Image::BitmapData& srcData,
  66582. const int alpha, const AffineTransform& transform, const bool betterQuality, const bool repeatPattern) throw()
  66583. {
  66584. switch (destImage.getFormat())
  66585. {
  66586. case Image::ARGB:
  66587. switch (srcImage.getFormat())
  66588. {
  66589. case Image::ARGB:
  66590. if (repeatPattern) { TransformedImageFillEdgeTableRenderer <PixelARGB, PixelARGB, true> r (destData, srcData, transform, alpha, betterQuality); et.iterate (r); }
  66591. else { TransformedImageFillEdgeTableRenderer <PixelARGB, PixelARGB, false> r (destData, srcData, transform, alpha, betterQuality); et.iterate (r); }
  66592. break;
  66593. case Image::RGB:
  66594. if (repeatPattern) { TransformedImageFillEdgeTableRenderer <PixelARGB, PixelRGB, true> r (destData, srcData, transform, alpha, betterQuality); et.iterate (r); }
  66595. else { TransformedImageFillEdgeTableRenderer <PixelARGB, PixelRGB, false> r (destData, srcData, transform, alpha, betterQuality); et.iterate (r); }
  66596. break;
  66597. default:
  66598. if (repeatPattern) { TransformedImageFillEdgeTableRenderer <PixelARGB, PixelAlpha, true> r (destData, srcData, transform, alpha, betterQuality); et.iterate (r); }
  66599. else { TransformedImageFillEdgeTableRenderer <PixelARGB, PixelAlpha, false> r (destData, srcData, transform, alpha, betterQuality); et.iterate (r); }
  66600. break;
  66601. }
  66602. break;
  66603. case Image::RGB:
  66604. switch (srcImage.getFormat())
  66605. {
  66606. case Image::ARGB:
  66607. if (repeatPattern) { TransformedImageFillEdgeTableRenderer <PixelRGB, PixelARGB, true> r (destData, srcData, transform, alpha, betterQuality); et.iterate (r); }
  66608. else { TransformedImageFillEdgeTableRenderer <PixelRGB, PixelARGB, false> r (destData, srcData, transform, alpha, betterQuality); et.iterate (r); }
  66609. break;
  66610. case Image::RGB:
  66611. if (repeatPattern) { TransformedImageFillEdgeTableRenderer <PixelRGB, PixelRGB, true> r (destData, srcData, transform, alpha, betterQuality); et.iterate (r); }
  66612. else { TransformedImageFillEdgeTableRenderer <PixelRGB, PixelRGB, false> r (destData, srcData, transform, alpha, betterQuality); et.iterate (r); }
  66613. break;
  66614. default:
  66615. if (repeatPattern) { TransformedImageFillEdgeTableRenderer <PixelRGB, PixelAlpha, true> r (destData, srcData, transform, alpha, betterQuality); et.iterate (r); }
  66616. else { TransformedImageFillEdgeTableRenderer <PixelRGB, PixelAlpha, false> r (destData, srcData, transform, alpha, betterQuality); et.iterate (r); }
  66617. break;
  66618. }
  66619. break;
  66620. default:
  66621. switch (srcImage.getFormat())
  66622. {
  66623. case Image::ARGB:
  66624. if (repeatPattern) { TransformedImageFillEdgeTableRenderer <PixelAlpha, PixelARGB, true> r (destData, srcData, transform, alpha, betterQuality); et.iterate (r); }
  66625. else { TransformedImageFillEdgeTableRenderer <PixelAlpha, PixelARGB, false> r (destData, srcData, transform, alpha, betterQuality); et.iterate (r); }
  66626. break;
  66627. case Image::RGB:
  66628. if (repeatPattern) { TransformedImageFillEdgeTableRenderer <PixelAlpha, PixelRGB, true> r (destData, srcData, transform, alpha, betterQuality); et.iterate (r); }
  66629. else { TransformedImageFillEdgeTableRenderer <PixelAlpha, PixelRGB, false> r (destData, srcData, transform, alpha, betterQuality); et.iterate (r); }
  66630. break;
  66631. default:
  66632. if (repeatPattern) { TransformedImageFillEdgeTableRenderer <PixelAlpha, PixelAlpha, true> r (destData, srcData, transform, alpha, betterQuality); et.iterate (r); }
  66633. else { TransformedImageFillEdgeTableRenderer <PixelAlpha, PixelAlpha, false> r (destData, srcData, transform, alpha, betterQuality); et.iterate (r); }
  66634. break;
  66635. }
  66636. break;
  66637. }
  66638. }
  66639. void blittedRenderImage (const Image& srcImage, Image& destImage, const EdgeTable& et, const Image::BitmapData& destData,
  66640. const Image::BitmapData& srcData, const int alpha, int x, int y, const bool repeatPattern) throw()
  66641. {
  66642. switch (destImage.getFormat())
  66643. {
  66644. case Image::ARGB:
  66645. switch (srcImage.getFormat())
  66646. {
  66647. case Image::ARGB:
  66648. if (repeatPattern) { ImageFillEdgeTableRenderer <PixelARGB, PixelARGB, true> r (destData, srcData, alpha, x, y); et.iterate (r); }
  66649. else { ImageFillEdgeTableRenderer <PixelARGB, PixelARGB, false> r (destData, srcData, alpha, x, y); et.iterate (r); }
  66650. break;
  66651. case Image::RGB:
  66652. if (repeatPattern) { ImageFillEdgeTableRenderer <PixelARGB, PixelRGB, true> r (destData, srcData, alpha, x, y); et.iterate (r); }
  66653. else { ImageFillEdgeTableRenderer <PixelARGB, PixelRGB, false> r (destData, srcData, alpha, x, y); et.iterate (r); }
  66654. break;
  66655. default:
  66656. if (repeatPattern) { ImageFillEdgeTableRenderer <PixelARGB, PixelAlpha, true> r (destData, srcData, alpha, x, y); et.iterate (r); }
  66657. else { ImageFillEdgeTableRenderer <PixelARGB, PixelAlpha, false> r (destData, srcData, alpha, x, y); et.iterate (r); }
  66658. break;
  66659. }
  66660. break;
  66661. case Image::RGB:
  66662. switch (srcImage.getFormat())
  66663. {
  66664. case Image::ARGB:
  66665. if (repeatPattern) { ImageFillEdgeTableRenderer <PixelRGB, PixelARGB, true> r (destData, srcData, alpha, x, y); et.iterate (r); }
  66666. else { ImageFillEdgeTableRenderer <PixelRGB, PixelARGB, false> r (destData, srcData, alpha, x, y); et.iterate (r); }
  66667. break;
  66668. case Image::RGB:
  66669. if (repeatPattern) { ImageFillEdgeTableRenderer <PixelRGB, PixelRGB, true> r (destData, srcData, alpha, x, y); et.iterate (r); }
  66670. else { ImageFillEdgeTableRenderer <PixelRGB, PixelRGB, false> r (destData, srcData, alpha, x, y); et.iterate (r); }
  66671. break;
  66672. default:
  66673. if (repeatPattern) { ImageFillEdgeTableRenderer <PixelRGB, PixelAlpha, true> r (destData, srcData, alpha, x, y); et.iterate (r); }
  66674. else { ImageFillEdgeTableRenderer <PixelRGB, PixelAlpha, false> r (destData, srcData, alpha, x, y); et.iterate (r); }
  66675. break;
  66676. }
  66677. break;
  66678. default:
  66679. switch (srcImage.getFormat())
  66680. {
  66681. case Image::ARGB:
  66682. if (repeatPattern) { ImageFillEdgeTableRenderer <PixelAlpha, PixelARGB, true> r (destData, srcData, alpha, x, y); et.iterate (r); }
  66683. else { ImageFillEdgeTableRenderer <PixelAlpha, PixelARGB, false> r (destData, srcData, alpha, x, y); et.iterate (r); }
  66684. break;
  66685. case Image::RGB:
  66686. if (repeatPattern) { ImageFillEdgeTableRenderer <PixelAlpha, PixelRGB, true> r (destData, srcData, alpha, x, y); et.iterate (r); }
  66687. else { ImageFillEdgeTableRenderer <PixelAlpha, PixelRGB, false> r (destData, srcData, alpha, x, y); et.iterate (r); }
  66688. break;
  66689. default:
  66690. if (repeatPattern) { ImageFillEdgeTableRenderer <PixelAlpha, PixelAlpha, true> r (destData, srcData, alpha, x, y); et.iterate (r); }
  66691. else { ImageFillEdgeTableRenderer <PixelAlpha, PixelAlpha, false> r (destData, srcData, alpha, x, y); et.iterate (r); }
  66692. break;
  66693. }
  66694. break;
  66695. }
  66696. }
  66697. };
  66698. LowLevelGraphicsSoftwareRenderer::LowLevelGraphicsSoftwareRenderer (Image& image_)
  66699. : image (image_)
  66700. {
  66701. currentState = new LLGCSavedState (image_.getBounds(), 0, 0, Font(),
  66702. FillType(), Graphics::mediumResamplingQuality);
  66703. }
  66704. LowLevelGraphicsSoftwareRenderer::~LowLevelGraphicsSoftwareRenderer()
  66705. {
  66706. }
  66707. bool LowLevelGraphicsSoftwareRenderer::isVectorDevice() const
  66708. {
  66709. return false;
  66710. }
  66711. void LowLevelGraphicsSoftwareRenderer::setOrigin (int x, int y)
  66712. {
  66713. currentState->xOffset += x;
  66714. currentState->yOffset += y;
  66715. }
  66716. bool LowLevelGraphicsSoftwareRenderer::clipToRectangle (const Rectangle<int>& r)
  66717. {
  66718. return currentState->clipToRectangle (r);
  66719. }
  66720. bool LowLevelGraphicsSoftwareRenderer::clipToRectangleList (const RectangleList& clipRegion)
  66721. {
  66722. return currentState->clipToRectangleList (clipRegion);
  66723. }
  66724. void LowLevelGraphicsSoftwareRenderer::excludeClipRectangle (const Rectangle<int>& r)
  66725. {
  66726. currentState->excludeClipRectangle (r);
  66727. }
  66728. void LowLevelGraphicsSoftwareRenderer::clipToPath (const Path& path, const AffineTransform& transform)
  66729. {
  66730. currentState->clipToPath (path, transform);
  66731. }
  66732. void LowLevelGraphicsSoftwareRenderer::clipToImageAlpha (const Image& sourceImage, const Rectangle<int>& srcClip, const AffineTransform& transform)
  66733. {
  66734. currentState->clipToImageAlpha (sourceImage, srcClip, transform);
  66735. }
  66736. bool LowLevelGraphicsSoftwareRenderer::clipRegionIntersects (const Rectangle<int>& r)
  66737. {
  66738. return currentState->edgeTable->edgeTable.getMaximumBounds()
  66739. .intersects (r.translated (currentState->xOffset, currentState->yOffset));
  66740. }
  66741. const Rectangle<int> LowLevelGraphicsSoftwareRenderer::getClipBounds() const
  66742. {
  66743. return currentState->edgeTable->edgeTable.getMaximumBounds().translated (-currentState->xOffset, -currentState->yOffset);
  66744. }
  66745. bool LowLevelGraphicsSoftwareRenderer::isClipEmpty() const
  66746. {
  66747. return currentState->edgeTable->edgeTable.isEmpty();
  66748. }
  66749. void LowLevelGraphicsSoftwareRenderer::saveState()
  66750. {
  66751. stateStack.add (new LLGCSavedState (*currentState));
  66752. }
  66753. void LowLevelGraphicsSoftwareRenderer::restoreState()
  66754. {
  66755. LLGCSavedState* const top = stateStack.getLast();
  66756. if (top != 0)
  66757. {
  66758. currentState = top;
  66759. stateStack.removeLast (1, false);
  66760. }
  66761. else
  66762. {
  66763. jassertfalse // trying to pop with an empty stack!
  66764. }
  66765. }
  66766. void LowLevelGraphicsSoftwareRenderer::setFill (const FillType& fillType)
  66767. {
  66768. currentState->fillType = fillType;
  66769. }
  66770. void LowLevelGraphicsSoftwareRenderer::setOpacity (float newOpacity)
  66771. {
  66772. currentState->fillType.setOpacity (newOpacity);
  66773. }
  66774. void LowLevelGraphicsSoftwareRenderer::setInterpolationQuality (Graphics::ResamplingQuality quality)
  66775. {
  66776. currentState->interpolationQuality = quality;
  66777. }
  66778. void LowLevelGraphicsSoftwareRenderer::fillRect (const Rectangle<int>& r, const bool replaceExistingContents)
  66779. {
  66780. const Rectangle<int>& totalClip = currentState->edgeTable->edgeTable.getMaximumBounds();
  66781. const Rectangle<int> clipped (totalClip.getIntersection (r.translated (currentState->xOffset, currentState->yOffset)));
  66782. if (! clipped.isEmpty())
  66783. {
  66784. EdgeTable et (clipped);
  66785. currentState->fillEdgeTable (image, et, replaceExistingContents);
  66786. }
  66787. }
  66788. void LowLevelGraphicsSoftwareRenderer::fillPath (const Path& path, const AffineTransform& transform)
  66789. {
  66790. EdgeTable et (currentState->edgeTable->edgeTable.getMaximumBounds(),
  66791. path, transform.translated ((float) currentState->xOffset,
  66792. (float) currentState->yOffset));
  66793. currentState->fillEdgeTable (image, et);
  66794. }
  66795. void LowLevelGraphicsSoftwareRenderer::drawImage (const Image& sourceImage, const Rectangle<int>& srcClip,
  66796. const AffineTransform& transform, const bool fillEntireClipAsTiles)
  66797. {
  66798. jassert (sourceImage.getBounds().contains (srcClip));
  66799. currentState->renderImage (image, sourceImage, srcClip, transform,
  66800. fillEntireClipAsTiles ? &(currentState->edgeTable->edgeTable) : 0);
  66801. }
  66802. void LowLevelGraphicsSoftwareRenderer::drawLine (double x1, double y1, double x2, double y2)
  66803. {
  66804. Path p;
  66805. p.addLineSegment ((float) x1, (float) y1, (float) x2, (float) y2, 1.0f);
  66806. fillPath (p, AffineTransform::identity);
  66807. }
  66808. void LowLevelGraphicsSoftwareRenderer::drawVerticalLine (const int x, double top, double bottom)
  66809. {
  66810. if (bottom > top)
  66811. {
  66812. EdgeTable et ((float) (x + currentState->xOffset), (float) (top + currentState->yOffset), 1.0f, (float) (bottom - top));
  66813. currentState->fillEdgeTable (image, et);
  66814. }
  66815. }
  66816. void LowLevelGraphicsSoftwareRenderer::drawHorizontalLine (const int y, double left, double right)
  66817. {
  66818. if (right > left)
  66819. {
  66820. EdgeTable et ((float) (left + currentState->xOffset), (float) (y + currentState->yOffset),
  66821. (float) (right - left), 1.0f);
  66822. currentState->fillEdgeTable (image, et);
  66823. }
  66824. }
  66825. class GlyphCache : private DeletedAtShutdown
  66826. {
  66827. public:
  66828. GlyphCache() throw()
  66829. : accessCounter (0), hits (0), misses (0)
  66830. {
  66831. for (int i = 120; --i >= 0;)
  66832. glyphs.add (new CachedGlyph());
  66833. }
  66834. ~GlyphCache() throw()
  66835. {
  66836. clearSingletonInstance();
  66837. }
  66838. juce_DeclareSingleton_SingleThreaded_Minimal (GlyphCache);
  66839. void drawGlyph (LLGCSavedState& state, Image& image, const Font& font, const int glyphNumber, float x, float y) throw()
  66840. {
  66841. ++accessCounter;
  66842. int oldestCounter = std::numeric_limits<int>::max();
  66843. CachedGlyph* oldest = 0;
  66844. for (int i = glyphs.size(); --i >= 0;)
  66845. {
  66846. CachedGlyph* const glyph = glyphs.getUnchecked (i);
  66847. if (glyph->glyph == glyphNumber && glyph->font == font)
  66848. {
  66849. ++hits;
  66850. glyph->lastAccessCount = accessCounter;
  66851. glyph->draw (state, image, x, y);
  66852. return;
  66853. }
  66854. if (glyph->lastAccessCount <= oldestCounter)
  66855. {
  66856. oldestCounter = glyph->lastAccessCount;
  66857. oldest = glyph;
  66858. }
  66859. }
  66860. if (hits + ++misses > (glyphs.size() << 4))
  66861. {
  66862. if (misses * 2 > hits)
  66863. {
  66864. for (int i = 32; --i >= 0;)
  66865. glyphs.add (new CachedGlyph());
  66866. }
  66867. hits = misses = 0;
  66868. oldest = glyphs.getLast();
  66869. }
  66870. jassert (oldest != 0);
  66871. oldest->lastAccessCount = accessCounter;
  66872. oldest->generate (font, glyphNumber);
  66873. oldest->draw (state, image, x, y);
  66874. }
  66875. class CachedGlyph
  66876. {
  66877. public:
  66878. CachedGlyph() : glyph (0), lastAccessCount (0) {}
  66879. ~CachedGlyph() {}
  66880. void draw (LLGCSavedState& state, Image& image, const float x, const float y) const throw()
  66881. {
  66882. if (edgeTable != 0)
  66883. {
  66884. EdgeTable et (*edgeTable);
  66885. et.translate (x, roundToInt (y));
  66886. state.fillEdgeTable (image, et, false);
  66887. }
  66888. }
  66889. void generate (const Font& newFont, const int glyphNumber) throw()
  66890. {
  66891. font = newFont;
  66892. glyph = glyphNumber;
  66893. edgeTable = 0;
  66894. Path glyphPath;
  66895. font.getTypeface()->getOutlineForGlyph (glyphNumber, glyphPath);
  66896. if (! glyphPath.isEmpty())
  66897. {
  66898. const float fontHeight = font.getHeight();
  66899. const AffineTransform transform (AffineTransform::scale (fontHeight * font.getHorizontalScale(), fontHeight)
  66900. .translated (0.0f, -0.5f));
  66901. edgeTable = new EdgeTable (glyphPath.getBoundsTransformed (transform).getSmallestIntegerContainer().expanded (1, 0),
  66902. glyphPath, transform);
  66903. }
  66904. }
  66905. int glyph, lastAccessCount;
  66906. Font font;
  66907. juce_UseDebuggingNewOperator
  66908. private:
  66909. ScopedPointer <EdgeTable> edgeTable;
  66910. CachedGlyph (const CachedGlyph&);
  66911. CachedGlyph& operator= (const CachedGlyph&);
  66912. };
  66913. juce_UseDebuggingNewOperator
  66914. private:
  66915. OwnedArray <CachedGlyph> glyphs;
  66916. int accessCounter, hits, misses;
  66917. GlyphCache (const GlyphCache&);
  66918. GlyphCache& operator= (const GlyphCache&);
  66919. };
  66920. juce_ImplementSingleton_SingleThreaded (GlyphCache);
  66921. void LowLevelGraphicsSoftwareRenderer::setFont (const Font& newFont)
  66922. {
  66923. currentState->font = newFont;
  66924. }
  66925. const Font LowLevelGraphicsSoftwareRenderer::getFont()
  66926. {
  66927. return currentState->font;
  66928. }
  66929. void LowLevelGraphicsSoftwareRenderer::drawGlyph (int glyphNumber, const AffineTransform& transform)
  66930. {
  66931. Font& f = currentState->font;
  66932. if (transform.isOnlyTranslation())
  66933. {
  66934. GlyphCache::getInstance()->drawGlyph (*currentState, image, f, glyphNumber,
  66935. transform.getTranslationX() + (float) currentState->xOffset,
  66936. transform.getTranslationY() + (float) currentState->yOffset);
  66937. }
  66938. else
  66939. {
  66940. Path p;
  66941. f.getTypeface()->getOutlineForGlyph (glyphNumber, p);
  66942. fillPath (p, AffineTransform::scale (f.getHeight() * f.getHorizontalScale(), f.getHeight()).followedBy (transform));
  66943. }
  66944. }
  66945. #if JUCE_MSVC
  66946. #pragma warning (pop)
  66947. #if JUCE_DEBUG
  66948. #pragma optimize ("", on) // resets optimisations to the project defaults
  66949. #endif
  66950. #endif
  66951. END_JUCE_NAMESPACE
  66952. /*** End of inlined file: juce_LowLevelGraphicsSoftwareRenderer.cpp ***/
  66953. /*** Start of inlined file: juce_RectanglePlacement.cpp ***/
  66954. BEGIN_JUCE_NAMESPACE
  66955. RectanglePlacement::RectanglePlacement (const RectanglePlacement& other) throw()
  66956. : flags (other.flags)
  66957. {
  66958. }
  66959. RectanglePlacement& RectanglePlacement::operator= (const RectanglePlacement& other) throw()
  66960. {
  66961. flags = other.flags;
  66962. return *this;
  66963. }
  66964. void RectanglePlacement::applyTo (double& x, double& y,
  66965. double& w, double& h,
  66966. const double dx, const double dy,
  66967. const double dw, const double dh) const throw()
  66968. {
  66969. if (w == 0 || h == 0)
  66970. return;
  66971. if ((flags & stretchToFit) != 0)
  66972. {
  66973. x = dx;
  66974. y = dy;
  66975. w = dw;
  66976. h = dh;
  66977. }
  66978. else
  66979. {
  66980. double scale = (flags & fillDestination) != 0 ? jmax (dw / w, dh / h)
  66981. : jmin (dw / w, dh / h);
  66982. if ((flags & onlyReduceInSize) != 0)
  66983. scale = jmin (scale, 1.0);
  66984. if ((flags & onlyIncreaseInSize) != 0)
  66985. scale = jmax (scale, 1.0);
  66986. w *= scale;
  66987. h *= scale;
  66988. if ((flags & xLeft) != 0)
  66989. x = dx;
  66990. else if ((flags & xRight) != 0)
  66991. x = dx + dw - w;
  66992. else
  66993. x = dx + (dw - w) * 0.5;
  66994. if ((flags & yTop) != 0)
  66995. y = dy;
  66996. else if ((flags & yBottom) != 0)
  66997. y = dy + dh - h;
  66998. else
  66999. y = dy + (dh - h) * 0.5;
  67000. }
  67001. }
  67002. const AffineTransform RectanglePlacement::getTransformToFit (float x, float y,
  67003. float w, float h,
  67004. const float dx, const float dy,
  67005. const float dw, const float dh) const throw()
  67006. {
  67007. if (w == 0 || h == 0)
  67008. return AffineTransform::identity;
  67009. const float scaleX = dw / w;
  67010. const float scaleY = dh / h;
  67011. if ((flags & stretchToFit) != 0)
  67012. return AffineTransform::translation (-x, -y)
  67013. .scaled (scaleX, scaleY)
  67014. .translated (dx, dy);
  67015. float scale = (flags & fillDestination) != 0 ? jmax (scaleX, scaleY)
  67016. : jmin (scaleX, scaleY);
  67017. if ((flags & onlyReduceInSize) != 0)
  67018. scale = jmin (scale, 1.0f);
  67019. if ((flags & onlyIncreaseInSize) != 0)
  67020. scale = jmax (scale, 1.0f);
  67021. w *= scale;
  67022. h *= scale;
  67023. float newX = dx;
  67024. if ((flags & xRight) != 0)
  67025. newX += dw - w; // right
  67026. else if ((flags & xLeft) == 0)
  67027. newX += (dw - w) / 2.0f; // centre
  67028. float newY = dy;
  67029. if ((flags & yBottom) != 0)
  67030. newY += dh - h; // bottom
  67031. else if ((flags & yTop) == 0)
  67032. newY += (dh - h) / 2.0f; // centre
  67033. return AffineTransform::translation (-x, -y)
  67034. .scaled (scale, scale)
  67035. .translated (newX, newY);
  67036. }
  67037. END_JUCE_NAMESPACE
  67038. /*** End of inlined file: juce_RectanglePlacement.cpp ***/
  67039. /*** Start of inlined file: juce_Drawable.cpp ***/
  67040. BEGIN_JUCE_NAMESPACE
  67041. Drawable::RenderingContext::RenderingContext (Graphics& g_,
  67042. const AffineTransform& transform_,
  67043. const float opacity_) throw()
  67044. : g (g_),
  67045. transform (transform_),
  67046. opacity (opacity_)
  67047. {
  67048. }
  67049. Drawable::Drawable()
  67050. {
  67051. }
  67052. Drawable::~Drawable()
  67053. {
  67054. }
  67055. void Drawable::draw (Graphics& g, const float opacity,
  67056. const AffineTransform& transform) const
  67057. {
  67058. render (RenderingContext (g, transform, opacity));
  67059. }
  67060. void Drawable::drawAt (Graphics& g, const float x, const float y, const float opacity) const
  67061. {
  67062. draw (g, opacity, AffineTransform::translation (x, y));
  67063. }
  67064. void Drawable::drawWithin (Graphics& g,
  67065. const int destX,
  67066. const int destY,
  67067. const int destW,
  67068. const int destH,
  67069. const RectanglePlacement& placement,
  67070. const float opacity) const
  67071. {
  67072. if (destW > 0 && destH > 0)
  67073. {
  67074. Rectangle<float> bounds (getBounds());
  67075. draw (g, opacity,
  67076. placement.getTransformToFit (bounds.getX(), bounds.getY(), bounds.getWidth(), bounds.getHeight(),
  67077. (float) destX, (float) destY,
  67078. (float) destW, (float) destH));
  67079. }
  67080. }
  67081. Drawable* Drawable::createFromImageData (const void* data, const size_t numBytes)
  67082. {
  67083. Drawable* result = 0;
  67084. Image* const image = ImageFileFormat::loadFrom (data, (int) numBytes);
  67085. if (image != 0)
  67086. {
  67087. DrawableImage* const di = new DrawableImage();
  67088. di->setImage (image, true);
  67089. result = di;
  67090. }
  67091. else
  67092. {
  67093. const String asString (String::createStringFromData (data, (int) numBytes));
  67094. XmlDocument doc (asString);
  67095. ScopedPointer <XmlElement> outer (doc.getDocumentElement (true));
  67096. if (outer != 0 && outer->hasTagName ("svg"))
  67097. {
  67098. ScopedPointer <XmlElement> svg (doc.getDocumentElement());
  67099. if (svg != 0)
  67100. result = Drawable::createFromSVG (*svg);
  67101. }
  67102. }
  67103. return result;
  67104. }
  67105. Drawable* Drawable::createFromImageDataStream (InputStream& dataSource)
  67106. {
  67107. MemoryBlock mb;
  67108. dataSource.readIntoMemoryBlock (mb);
  67109. return createFromImageData (mb.getData(), mb.getSize());
  67110. }
  67111. Drawable* Drawable::createFromImageFile (const File& file)
  67112. {
  67113. const ScopedPointer <FileInputStream> fin (file.createInputStream());
  67114. return fin != 0 ? createFromImageDataStream (*fin) : 0;
  67115. }
  67116. Drawable* Drawable::createFromValueTree (const ValueTree& tree)
  67117. {
  67118. Drawable* d = DrawablePath::createFromValueTree (tree);
  67119. if (d == 0)
  67120. {
  67121. d = DrawableComposite::createFromValueTree (tree);
  67122. if (d == 0)
  67123. {
  67124. d = DrawableImage::createFromValueTree (tree);
  67125. if (d == 0)
  67126. d = DrawableText::createFromValueTree (tree);
  67127. }
  67128. }
  67129. return d;
  67130. }
  67131. END_JUCE_NAMESPACE
  67132. /*** End of inlined file: juce_Drawable.cpp ***/
  67133. /*** Start of inlined file: juce_DrawableComposite.cpp ***/
  67134. BEGIN_JUCE_NAMESPACE
  67135. DrawableComposite::DrawableComposite()
  67136. {
  67137. }
  67138. DrawableComposite::~DrawableComposite()
  67139. {
  67140. }
  67141. void DrawableComposite::insertDrawable (Drawable* drawable,
  67142. const AffineTransform& transform,
  67143. const int index)
  67144. {
  67145. if (drawable != 0)
  67146. {
  67147. if (! drawables.contains (drawable))
  67148. {
  67149. drawables.insert (index, drawable);
  67150. if (transform.isIdentity())
  67151. transforms.insert (index, 0);
  67152. else
  67153. transforms.insert (index, new AffineTransform (transform));
  67154. }
  67155. else
  67156. {
  67157. jassertfalse // trying to add a drawable that's already in here!
  67158. }
  67159. }
  67160. }
  67161. void DrawableComposite::insertDrawable (const Drawable& drawable,
  67162. const AffineTransform& transform,
  67163. const int index)
  67164. {
  67165. insertDrawable (drawable.createCopy(), transform, index);
  67166. }
  67167. void DrawableComposite::removeDrawable (const int index, const bool deleteDrawable)
  67168. {
  67169. drawables.remove (index, deleteDrawable);
  67170. transforms.remove (index);
  67171. }
  67172. void DrawableComposite::bringToFront (const int index)
  67173. {
  67174. if (index >= 0 && index < drawables.size() - 1)
  67175. {
  67176. drawables.move (index, -1);
  67177. transforms.move (index, -1);
  67178. }
  67179. }
  67180. void DrawableComposite::render (const Drawable::RenderingContext& context) const
  67181. {
  67182. if (drawables.size() > 0 && context.opacity > 0)
  67183. {
  67184. if (context.opacity >= 1.0f || drawables.size() == 1)
  67185. {
  67186. Drawable::RenderingContext contextCopy (context);
  67187. for (int i = 0; i < drawables.size(); ++i)
  67188. {
  67189. const AffineTransform* const t = transforms.getUnchecked(i);
  67190. contextCopy.transform = (t == 0) ? context.transform
  67191. : t->followedBy (context.transform);
  67192. drawables.getUnchecked(i)->render (contextCopy);
  67193. }
  67194. }
  67195. else
  67196. {
  67197. // To correctly render a whole composite layer with an overall transparency,
  67198. // we need to render everything opaquely into a temp buffer, then blend that
  67199. // with the target opacity...
  67200. const Rectangle<int> clipBounds (context.g.getClipBounds());
  67201. Image tempImage (Image::ARGB, clipBounds.getWidth(), clipBounds.getHeight(), true);
  67202. {
  67203. Graphics tempG (tempImage);
  67204. tempG.setOrigin (-clipBounds.getX(), -clipBounds.getY());
  67205. Drawable::RenderingContext tempContext (tempG, context.transform, 1.0f);
  67206. render (tempContext);
  67207. }
  67208. context.g.setOpacity (context.opacity);
  67209. context.g.drawImageAt (&tempImage, clipBounds.getX(), clipBounds.getY());
  67210. }
  67211. }
  67212. }
  67213. const Rectangle<float> DrawableComposite::getBounds() const
  67214. {
  67215. Rectangle<float> bounds;
  67216. for (int i = 0; i < drawables.size(); ++i)
  67217. {
  67218. const Drawable* const d = drawables.getUnchecked(i);
  67219. const AffineTransform* const t = transforms.getUnchecked(i);
  67220. const Rectangle<float> childBounds (t == 0 ? d->getBounds()
  67221. : d->getBounds().transformed (*t));
  67222. if (bounds.isEmpty())
  67223. bounds = childBounds;
  67224. else if (! childBounds.isEmpty())
  67225. bounds = bounds.getUnion (childBounds);
  67226. }
  67227. return bounds;
  67228. }
  67229. bool DrawableComposite::hitTest (float x, float y) const
  67230. {
  67231. for (int i = 0; i < drawables.size(); ++i)
  67232. {
  67233. float tx = x;
  67234. float ty = y;
  67235. const AffineTransform* const t = transforms.getUnchecked(i);
  67236. if (t != 0)
  67237. t->inverted().transformPoint (tx, ty);
  67238. if (drawables.getUnchecked(i)->hitTest (tx, ty))
  67239. return true;
  67240. }
  67241. return false;
  67242. }
  67243. Drawable* DrawableComposite::createCopy() const
  67244. {
  67245. DrawableComposite* const dc = new DrawableComposite();
  67246. for (int i = 0; i < drawables.size(); ++i)
  67247. {
  67248. dc->drawables.add (drawables.getUnchecked(i)->createCopy());
  67249. const AffineTransform* const t = transforms.getUnchecked(i);
  67250. dc->transforms.add (t != 0 ? new AffineTransform (*t) : 0);
  67251. }
  67252. return dc;
  67253. }
  67254. ValueTree DrawableComposite::createValueTree() const
  67255. {
  67256. ValueTree v ("Group");
  67257. if (getName().isNotEmpty())
  67258. v.setProperty ("id", getName(), 0);
  67259. for (int i = 0; i < drawables.size(); ++i)
  67260. {
  67261. Drawable* const d = drawables.getUnchecked(i);
  67262. ValueTree child (d->createValueTree());
  67263. AffineTransform* transform = transforms.getUnchecked(i);
  67264. if (transform != 0)
  67265. {
  67266. String t;
  67267. t << transform->mat00 << " " << transform->mat01 << " " << transform->mat02 << " "
  67268. << transform->mat10 << " " << transform->mat11 << " " << transform->mat12;
  67269. child.setProperty ("transform", t, 0);
  67270. }
  67271. v.addChild (child, -1, 0);
  67272. }
  67273. return v;
  67274. }
  67275. DrawableComposite* DrawableComposite::createFromValueTree (const ValueTree& tree)
  67276. {
  67277. if (! tree.hasType ("Group"))
  67278. return 0;
  67279. DrawableComposite* dc = new DrawableComposite();
  67280. dc->setName (tree ["id"]);
  67281. for (int i = 0; i < tree.getNumChildren(); ++i)
  67282. {
  67283. ValueTree childTree (tree.getChild (i));
  67284. Drawable* d = Drawable::createFromValueTree (childTree);
  67285. if (d != 0)
  67286. {
  67287. AffineTransform transform;
  67288. const String transformAtt (childTree ["transform"].toString());
  67289. if (transformAtt.isNotEmpty())
  67290. {
  67291. StringArray tokens;
  67292. tokens.addTokens (transformAtt.trim(), false);
  67293. tokens.removeEmptyStrings (true);
  67294. if (tokens.size() == 6)
  67295. {
  67296. float f[6];
  67297. for (int j = 0; j < 6; ++j)
  67298. f[j] = (float) tokens[j].getDoubleValue();
  67299. transform = AffineTransform (f[0], f[1], f[2], f[3], f[4], f[5]);
  67300. }
  67301. }
  67302. dc->insertDrawable (d, transform);
  67303. }
  67304. }
  67305. return dc;
  67306. }
  67307. END_JUCE_NAMESPACE
  67308. /*** End of inlined file: juce_DrawableComposite.cpp ***/
  67309. /*** Start of inlined file: juce_DrawableImage.cpp ***/
  67310. BEGIN_JUCE_NAMESPACE
  67311. DrawableImage::DrawableImage()
  67312. : image (0),
  67313. canDeleteImage (false),
  67314. opacity (1.0f),
  67315. overlayColour (0x00000000)
  67316. {
  67317. }
  67318. DrawableImage::~DrawableImage()
  67319. {
  67320. clearImage();
  67321. }
  67322. void DrawableImage::clearImage()
  67323. {
  67324. if (canDeleteImage && image != 0)
  67325. ImageCache::releaseOrDelete (image);
  67326. image = 0;
  67327. }
  67328. void DrawableImage::setImage (const Image& imageToCopy)
  67329. {
  67330. clearImage();
  67331. image = new Image (imageToCopy);
  67332. canDeleteImage = true;
  67333. }
  67334. void DrawableImage::setImage (Image* imageToUse,
  67335. const bool releaseWhenNotNeeded)
  67336. {
  67337. clearImage();
  67338. image = imageToUse;
  67339. canDeleteImage = releaseWhenNotNeeded;
  67340. }
  67341. void DrawableImage::setOpacity (const float newOpacity)
  67342. {
  67343. opacity = newOpacity;
  67344. }
  67345. void DrawableImage::setOverlayColour (const Colour& newOverlayColour)
  67346. {
  67347. overlayColour = newOverlayColour;
  67348. }
  67349. void DrawableImage::render (const Drawable::RenderingContext& context) const
  67350. {
  67351. if (image != 0)
  67352. {
  67353. if (opacity > 0.0f && ! overlayColour.isOpaque())
  67354. {
  67355. context.g.setOpacity (context.opacity * opacity);
  67356. context.g.drawImageTransformed (image, image->getBounds(),
  67357. context.transform, false);
  67358. }
  67359. if (! overlayColour.isTransparent())
  67360. {
  67361. context.g.setColour (overlayColour.withMultipliedAlpha (context.opacity));
  67362. context.g.drawImageTransformed (image, image->getBounds(),
  67363. context.transform, true);
  67364. }
  67365. }
  67366. }
  67367. const Rectangle<float> DrawableImage::getBounds() const
  67368. {
  67369. if (image == 0)
  67370. return Rectangle<float>();
  67371. return Rectangle<float> (0, 0, (float) image->getWidth(), (float) image->getHeight());
  67372. }
  67373. bool DrawableImage::hitTest (float x, float y) const
  67374. {
  67375. return image != 0
  67376. && x >= 0.0f
  67377. && y >= 0.0f
  67378. && x < image->getWidth()
  67379. && y < image->getHeight()
  67380. && image->getPixelAt (roundToInt (x), roundToInt (y)).getAlpha() >= 127;
  67381. }
  67382. Drawable* DrawableImage::createCopy() const
  67383. {
  67384. DrawableImage* const di = new DrawableImage();
  67385. di->opacity = opacity;
  67386. di->overlayColour = overlayColour;
  67387. if (image != 0)
  67388. {
  67389. if ((! canDeleteImage) || ! ImageCache::isImageInCache (image))
  67390. {
  67391. di->setImage (*image);
  67392. }
  67393. else
  67394. {
  67395. ImageCache::incReferenceCount (image);
  67396. di->setImage (image, true);
  67397. }
  67398. }
  67399. return di;
  67400. }
  67401. ValueTree DrawableImage::createValueTree() const
  67402. {
  67403. ValueTree v ("Image");
  67404. if (getName().isNotEmpty())
  67405. v.setProperty ("id", getName(), 0);
  67406. if (opacity < 1.0f)
  67407. v.setProperty ("opacity", (double) opacity, 0);
  67408. if (! overlayColour.isTransparent())
  67409. v.setProperty ("overlay", String::toHexString ((int) overlayColour.getARGB()), 0);
  67410. if (image != 0)
  67411. {
  67412. MemoryOutputStream imageData;
  67413. PNGImageFormat pngFormat;
  67414. if (pngFormat.writeImageToStream (*image, imageData))
  67415. {
  67416. String base64 (MemoryBlock (imageData.getData(), imageData.getDataSize()).toBase64Encoding());
  67417. for (int i = (base64.length() & ~127); i >= 0; i -= 128)
  67418. base64 = base64.substring (0, i) + "\n" + base64.substring (i);
  67419. v.setProperty ("data", base64, 0);
  67420. }
  67421. }
  67422. return v;
  67423. }
  67424. DrawableImage* DrawableImage::createFromValueTree (const ValueTree& tree)
  67425. {
  67426. if (! tree.hasType ("Image"))
  67427. return 0;
  67428. DrawableImage* di = new DrawableImage();
  67429. di->setName (tree ["id"]);
  67430. di->opacity = tree.hasProperty ("opacity") ? (float) tree ["opacity"] : 1.0f;
  67431. di->overlayColour = Colour (tree ["overlay"].toString().getHexValue32());
  67432. MemoryBlock imageData;
  67433. if (imageData.fromBase64Encoding (tree ["data"]))
  67434. {
  67435. Image* const im = ImageFileFormat::loadFrom (imageData.getData(), (int) imageData.getSize());
  67436. if (im == 0)
  67437. return false;
  67438. di->setImage (im, true);
  67439. }
  67440. return di;
  67441. }
  67442. END_JUCE_NAMESPACE
  67443. /*** End of inlined file: juce_DrawableImage.cpp ***/
  67444. /*** Start of inlined file: juce_DrawablePath.cpp ***/
  67445. BEGIN_JUCE_NAMESPACE
  67446. DrawablePath::DrawablePath()
  67447. : mainFill (Colours::black),
  67448. strokeFill (Colours::transparentBlack),
  67449. strokeType (0.0f)
  67450. {
  67451. }
  67452. DrawablePath::~DrawablePath()
  67453. {
  67454. }
  67455. void DrawablePath::setPath (const Path& newPath)
  67456. {
  67457. path = newPath;
  67458. updateOutline();
  67459. }
  67460. void DrawablePath::setFill (const FillType& newFill)
  67461. {
  67462. mainFill = newFill;
  67463. }
  67464. void DrawablePath::setStrokeFill (const FillType& newFill)
  67465. {
  67466. strokeFill = newFill;
  67467. }
  67468. void DrawablePath::setStrokeType (const PathStrokeType& newStrokeType)
  67469. {
  67470. strokeType = newStrokeType;
  67471. updateOutline();
  67472. }
  67473. void DrawablePath::setStrokeThickness (const float newThickness)
  67474. {
  67475. setStrokeType (PathStrokeType (newThickness, strokeType.getJointStyle(), strokeType.getEndStyle()));
  67476. }
  67477. void DrawablePath::render (const Drawable::RenderingContext& context) const
  67478. {
  67479. {
  67480. FillType f (mainFill);
  67481. if (f.isGradient())
  67482. f.gradient->multiplyOpacity (context.opacity);
  67483. f.transform = f.transform.followedBy (context.transform);
  67484. context.g.setFillType (f);
  67485. context.g.fillPath (path, context.transform);
  67486. }
  67487. if (strokeType.getStrokeThickness() > 0.0f)
  67488. {
  67489. FillType f (strokeFill);
  67490. if (f.isGradient())
  67491. f.gradient->multiplyOpacity (context.opacity);
  67492. f.transform = f.transform.followedBy (context.transform);
  67493. context.g.setFillType (f);
  67494. context.g.fillPath (stroke, context.transform);
  67495. }
  67496. }
  67497. void DrawablePath::updateOutline()
  67498. {
  67499. stroke.clear();
  67500. strokeType.createStrokedPath (stroke, path, AffineTransform::identity, 4.0f);
  67501. }
  67502. const Rectangle<float> DrawablePath::getBounds() const
  67503. {
  67504. if (strokeType.getStrokeThickness() > 0.0f)
  67505. return stroke.getBounds();
  67506. else
  67507. return path.getBounds();
  67508. }
  67509. bool DrawablePath::hitTest (float x, float y) const
  67510. {
  67511. return path.contains (x, y)
  67512. || stroke.contains (x, y);
  67513. }
  67514. Drawable* DrawablePath::createCopy() const
  67515. {
  67516. DrawablePath* const dp = new DrawablePath();
  67517. dp->path = path;
  67518. dp->stroke = stroke;
  67519. dp->mainFill = mainFill;
  67520. dp->strokeFill = strokeFill;
  67521. dp->strokeType = strokeType;
  67522. return dp;
  67523. }
  67524. static const FillType readFillTypeFromTree (const ValueTree& v)
  67525. {
  67526. const String type (v["type"].toString());
  67527. if (type.equalsIgnoreCase ("solid"))
  67528. {
  67529. const String colour (v ["colour"].toString());
  67530. return Colour (colour.isEmpty() ? (uint32) 0xff000000
  67531. : (uint32) colour.getHexValue32());
  67532. }
  67533. else if (type.equalsIgnoreCase ("gradient"))
  67534. {
  67535. ColourGradient g;
  67536. g.x1 = v["x1"];
  67537. g.y1 = v["y1"];
  67538. g.x2 = v["x2"];
  67539. g.y2 = v["y2"];
  67540. g.isRadial = v["radial"];
  67541. StringArray colours;
  67542. colours.addTokens (v["colours"].toString(), false);
  67543. for (int i = 0; i < colours.size() / 2; ++i)
  67544. g.addColour (colours[i * 2].getDoubleValue(),
  67545. Colour ((uint32) colours[i * 2 + 1].getHexValue32()));
  67546. return g;
  67547. }
  67548. jassertfalse
  67549. return FillType();
  67550. }
  67551. static ValueTree createTreeForFillType (const String& tagName, const FillType& fillType)
  67552. {
  67553. ValueTree v (tagName);
  67554. if (fillType.isColour())
  67555. {
  67556. v.setProperty ("type", "solid", 0);
  67557. v.setProperty ("colour", String::toHexString ((int) fillType.colour.getARGB()), 0);
  67558. }
  67559. else if (fillType.isGradient())
  67560. {
  67561. v.setProperty ("type", "gradient", 0);
  67562. v.setProperty ("x1", fillType.gradient->x1, 0);
  67563. v.setProperty ("y1", fillType.gradient->y1, 0);
  67564. v.setProperty ("x2", fillType.gradient->x2, 0);
  67565. v.setProperty ("y2", fillType.gradient->y2, 0);
  67566. v.setProperty ("radial", fillType.gradient->isRadial, 0);
  67567. String s;
  67568. for (int i = 0; i < fillType.gradient->getNumColours(); ++i)
  67569. s << " " << fillType.gradient->getColourPosition (i)
  67570. << " " << String::toHexString ((int) fillType.gradient->getColour(i).getARGB());
  67571. v.setProperty ("colours", s.trimStart(), 0);
  67572. }
  67573. else
  67574. {
  67575. jassertfalse //xxx
  67576. }
  67577. return v;
  67578. }
  67579. ValueTree DrawablePath::createValueTree() const
  67580. {
  67581. ValueTree v ("Path");
  67582. v.addChild (createTreeForFillType ("fill", mainFill), -1, 0);
  67583. v.addChild (createTreeForFillType ("stroke", strokeFill), -1, 0);
  67584. if (getName().isNotEmpty())
  67585. v.setProperty ("id", getName(), 0);
  67586. v.setProperty ("strokeWidth", (double) strokeType.getStrokeThickness(), 0);
  67587. v.setProperty ("jointStyle", strokeType.getJointStyle() == PathStrokeType::mitered
  67588. ? "miter" : (strokeType.getJointStyle() == PathStrokeType::curved ? "curved" : "bevel"), 0);
  67589. v.setProperty ("capStyle", strokeType.getEndStyle() == PathStrokeType::butt
  67590. ? "butt" : (strokeType.getEndStyle() == PathStrokeType::square ? "square" : "round"), 0);
  67591. v.setProperty ("path", path.toString(), 0);
  67592. return v;
  67593. }
  67594. DrawablePath* DrawablePath::createFromValueTree (const ValueTree& tree)
  67595. {
  67596. if (! tree.hasType ("Path"))
  67597. return 0;
  67598. DrawablePath* p = new DrawablePath();
  67599. p->setName (tree ["id"]);
  67600. p->mainFill = readFillTypeFromTree (tree.getChildWithName ("fill"));
  67601. p->strokeFill = readFillTypeFromTree (tree.getChildWithName ("stroke"));
  67602. const String jointStyle (tree ["jointStyle"].toString());
  67603. const String endStyle (tree ["capStyle"].toString());
  67604. p->strokeType
  67605. = PathStrokeType (tree ["strokeWidth"],
  67606. jointStyle.equalsIgnoreCase ("curved") ? PathStrokeType::curved
  67607. : (jointStyle.equalsIgnoreCase ("bevel") ? PathStrokeType::beveled
  67608. : PathStrokeType::mitered),
  67609. endStyle.equalsIgnoreCase ("square") ? PathStrokeType::square
  67610. : (endStyle.equalsIgnoreCase ("round") ? PathStrokeType::rounded
  67611. : PathStrokeType::butt));
  67612. p->path.clear();
  67613. p->path.restoreFromString (tree ["path"]);
  67614. p->updateOutline();
  67615. return p;
  67616. }
  67617. END_JUCE_NAMESPACE
  67618. /*** End of inlined file: juce_DrawablePath.cpp ***/
  67619. /*** Start of inlined file: juce_DrawableText.cpp ***/
  67620. BEGIN_JUCE_NAMESPACE
  67621. DrawableText::DrawableText()
  67622. : colour (Colours::white)
  67623. {
  67624. }
  67625. DrawableText::~DrawableText()
  67626. {
  67627. }
  67628. void DrawableText::setText (const GlyphArrangement& newText)
  67629. {
  67630. text = newText;
  67631. }
  67632. void DrawableText::setText (const String& newText, const Font& fontToUse)
  67633. {
  67634. text.clear();
  67635. text.addLineOfText (fontToUse, newText, 0.0f, 0.0f);
  67636. }
  67637. void DrawableText::setColour (const Colour& newColour)
  67638. {
  67639. colour = newColour;
  67640. }
  67641. void DrawableText::render (const Drawable::RenderingContext& context) const
  67642. {
  67643. context.g.setColour (colour.withMultipliedAlpha (context.opacity));
  67644. text.draw (context.g, context.transform);
  67645. }
  67646. const Rectangle<float> DrawableText::getBounds() const
  67647. {
  67648. return text.getBoundingBox (0, -1, false);
  67649. }
  67650. bool DrawableText::hitTest (float x, float y) const
  67651. {
  67652. return text.findGlyphIndexAt (x, y) >= 0;
  67653. }
  67654. Drawable* DrawableText::createCopy() const
  67655. {
  67656. DrawableText* const dt = new DrawableText();
  67657. dt->text = text;
  67658. dt->colour = colour;
  67659. return dt;
  67660. }
  67661. ValueTree DrawableText::createValueTree() const
  67662. {
  67663. ValueTree v ("Text");
  67664. if (getName().isNotEmpty())
  67665. v.setProperty ("id", getName(), 0);
  67666. jassertfalse // xxx not finished!
  67667. return v;
  67668. }
  67669. DrawableText* DrawableText::createFromValueTree (const ValueTree& tree)
  67670. {
  67671. if (! tree.hasType ("Text"))
  67672. return 0;
  67673. DrawableText* dt = new DrawableText();
  67674. dt->setName (tree ["id"]);
  67675. jassertfalse // xxx not finished!
  67676. return dt;
  67677. }
  67678. END_JUCE_NAMESPACE
  67679. /*** End of inlined file: juce_DrawableText.cpp ***/
  67680. /*** Start of inlined file: juce_SVGParser.cpp ***/
  67681. BEGIN_JUCE_NAMESPACE
  67682. class SVGState
  67683. {
  67684. public:
  67685. SVGState (const XmlElement* const topLevel)
  67686. : topLevelXml (topLevel),
  67687. elementX (0), elementY (0),
  67688. width (512), height (512),
  67689. viewBoxW (0), viewBoxH (0)
  67690. {
  67691. }
  67692. ~SVGState()
  67693. {
  67694. }
  67695. Drawable* parseSVGElement (const XmlElement& xml)
  67696. {
  67697. if (! xml.hasTagName ("svg"))
  67698. return 0;
  67699. DrawableComposite* const drawable = new DrawableComposite();
  67700. drawable->setName (xml.getStringAttribute ("id"));
  67701. SVGState newState (*this);
  67702. if (xml.hasAttribute ("transform"))
  67703. newState.addTransform (xml);
  67704. newState.elementX = getCoordLength (xml.getStringAttribute ("x", String (newState.elementX)), viewBoxW);
  67705. newState.elementY = getCoordLength (xml.getStringAttribute ("y", String (newState.elementY)), viewBoxH);
  67706. newState.width = getCoordLength (xml.getStringAttribute ("width", String (newState.width)), viewBoxW);
  67707. newState.height = getCoordLength (xml.getStringAttribute ("height", String (newState.height)), viewBoxH);
  67708. if (xml.hasAttribute ("viewBox"))
  67709. {
  67710. const String viewParams (xml.getStringAttribute ("viewBox"));
  67711. int i = 0;
  67712. float vx, vy, vw, vh;
  67713. if (parseCoords (viewParams, vx, vy, i, true)
  67714. && parseCoords (viewParams, vw, vh, i, true)
  67715. && vw > 0
  67716. && vh > 0)
  67717. {
  67718. newState.viewBoxW = vw;
  67719. newState.viewBoxH = vh;
  67720. int placementFlags = 0;
  67721. const String aspect (xml.getStringAttribute ("preserveAspectRatio"));
  67722. if (aspect.containsIgnoreCase ("none"))
  67723. {
  67724. placementFlags = RectanglePlacement::stretchToFit;
  67725. }
  67726. else
  67727. {
  67728. if (aspect.containsIgnoreCase ("slice"))
  67729. placementFlags |= RectanglePlacement::fillDestination;
  67730. if (aspect.containsIgnoreCase ("xMin"))
  67731. placementFlags |= RectanglePlacement::xLeft;
  67732. else if (aspect.containsIgnoreCase ("xMax"))
  67733. placementFlags |= RectanglePlacement::xRight;
  67734. else
  67735. placementFlags |= RectanglePlacement::xMid;
  67736. if (aspect.containsIgnoreCase ("yMin"))
  67737. placementFlags |= RectanglePlacement::yTop;
  67738. else if (aspect.containsIgnoreCase ("yMax"))
  67739. placementFlags |= RectanglePlacement::yBottom;
  67740. else
  67741. placementFlags |= RectanglePlacement::yMid;
  67742. }
  67743. const RectanglePlacement placement (placementFlags);
  67744. newState.transform
  67745. = placement.getTransformToFit (vx, vy, vw, vh,
  67746. 0.0f, 0.0f, newState.width, newState.height)
  67747. .followedBy (newState.transform);
  67748. }
  67749. }
  67750. else
  67751. {
  67752. if (viewBoxW == 0)
  67753. newState.viewBoxW = newState.width;
  67754. if (viewBoxH == 0)
  67755. newState.viewBoxH = newState.height;
  67756. }
  67757. newState.parseSubElements (xml, drawable);
  67758. return drawable;
  67759. }
  67760. private:
  67761. const XmlElement* const topLevelXml;
  67762. float elementX, elementY, width, height, viewBoxW, viewBoxH;
  67763. AffineTransform transform;
  67764. String cssStyleText;
  67765. void parseSubElements (const XmlElement& xml, DrawableComposite* const parentDrawable)
  67766. {
  67767. forEachXmlChildElement (xml, e)
  67768. {
  67769. Drawable* d = 0;
  67770. if (e->hasTagName ("g"))
  67771. d = parseGroupElement (*e);
  67772. else if (e->hasTagName ("svg"))
  67773. d = parseSVGElement (*e);
  67774. else if (e->hasTagName ("path"))
  67775. d = parsePath (*e);
  67776. else if (e->hasTagName ("rect"))
  67777. d = parseRect (*e);
  67778. else if (e->hasTagName ("circle"))
  67779. d = parseCircle (*e);
  67780. else if (e->hasTagName ("ellipse"))
  67781. d = parseEllipse (*e);
  67782. else if (e->hasTagName ("line"))
  67783. d = parseLine (*e);
  67784. else if (e->hasTagName ("polyline"))
  67785. d = parsePolygon (*e, true);
  67786. else if (e->hasTagName ("polygon"))
  67787. d = parsePolygon (*e, false);
  67788. else if (e->hasTagName ("text"))
  67789. d = parseText (*e);
  67790. else if (e->hasTagName ("switch"))
  67791. d = parseSwitch (*e);
  67792. else if (e->hasTagName ("style"))
  67793. parseCSSStyle (*e);
  67794. parentDrawable->insertDrawable (d);
  67795. }
  67796. }
  67797. DrawableComposite* parseSwitch (const XmlElement& xml)
  67798. {
  67799. const XmlElement* const group = xml.getChildByName ("g");
  67800. if (group != 0)
  67801. return parseGroupElement (*group);
  67802. return 0;
  67803. }
  67804. DrawableComposite* parseGroupElement (const XmlElement& xml)
  67805. {
  67806. DrawableComposite* const drawable = new DrawableComposite();
  67807. drawable->setName (xml.getStringAttribute ("id"));
  67808. if (xml.hasAttribute ("transform"))
  67809. {
  67810. SVGState newState (*this);
  67811. newState.addTransform (xml);
  67812. newState.parseSubElements (xml, drawable);
  67813. }
  67814. else
  67815. {
  67816. parseSubElements (xml, drawable);
  67817. }
  67818. return drawable;
  67819. }
  67820. Drawable* parsePath (const XmlElement& xml) const
  67821. {
  67822. const String d (xml.getStringAttribute ("d").trimStart());
  67823. Path path;
  67824. if (getStyleAttribute (&xml, "fill-rule").trim().equalsIgnoreCase ("evenodd"))
  67825. path.setUsingNonZeroWinding (false);
  67826. int index = 0;
  67827. float lastX = 0, lastY = 0;
  67828. float lastX2 = 0, lastY2 = 0;
  67829. juce_wchar lastCommandChar = 0;
  67830. bool isRelative = true;
  67831. bool carryOn = true;
  67832. const String validCommandChars ("MmLlHhVvCcSsQqTtAaZz");
  67833. while (d[index] != 0)
  67834. {
  67835. float x, y, x2, y2, x3, y3;
  67836. if (validCommandChars.containsChar (d[index]))
  67837. {
  67838. lastCommandChar = d [index++];
  67839. isRelative = (lastCommandChar >= 'a' && lastCommandChar <= 'z');
  67840. }
  67841. switch (lastCommandChar)
  67842. {
  67843. case 'M':
  67844. case 'm':
  67845. case 'L':
  67846. case 'l':
  67847. if (parseCoords (d, x, y, index, false))
  67848. {
  67849. if (isRelative)
  67850. {
  67851. x += lastX;
  67852. y += lastY;
  67853. }
  67854. if (lastCommandChar == 'M' || lastCommandChar == 'm')
  67855. {
  67856. path.startNewSubPath (x, y);
  67857. lastCommandChar = 'l';
  67858. }
  67859. else
  67860. path.lineTo (x, y);
  67861. lastX2 = lastX;
  67862. lastY2 = lastY;
  67863. lastX = x;
  67864. lastY = y;
  67865. }
  67866. else
  67867. {
  67868. ++index;
  67869. }
  67870. break;
  67871. case 'H':
  67872. case 'h':
  67873. if (parseCoord (d, x, index, false, true))
  67874. {
  67875. if (isRelative)
  67876. x += lastX;
  67877. path.lineTo (x, lastY);
  67878. lastX2 = lastX;
  67879. lastX = x;
  67880. }
  67881. else
  67882. {
  67883. ++index;
  67884. }
  67885. break;
  67886. case 'V':
  67887. case 'v':
  67888. if (parseCoord (d, y, index, false, false))
  67889. {
  67890. if (isRelative)
  67891. y += lastY;
  67892. path.lineTo (lastX, y);
  67893. lastY2 = lastY;
  67894. lastY = y;
  67895. }
  67896. else
  67897. {
  67898. ++index;
  67899. }
  67900. break;
  67901. case 'C':
  67902. case 'c':
  67903. if (parseCoords (d, x, y, index, false)
  67904. && parseCoords (d, x2, y2, index, false)
  67905. && parseCoords (d, x3, y3, index, false))
  67906. {
  67907. if (isRelative)
  67908. {
  67909. x += lastX;
  67910. y += lastY;
  67911. x2 += lastX;
  67912. y2 += lastY;
  67913. x3 += lastX;
  67914. y3 += lastY;
  67915. }
  67916. path.cubicTo (x, y, x2, y2, x3, y3);
  67917. lastX2 = x2;
  67918. lastY2 = y2;
  67919. lastX = x3;
  67920. lastY = y3;
  67921. }
  67922. else
  67923. {
  67924. ++index;
  67925. }
  67926. break;
  67927. case 'S':
  67928. case 's':
  67929. if (parseCoords (d, x, y, index, false)
  67930. && parseCoords (d, x3, y3, index, false))
  67931. {
  67932. if (isRelative)
  67933. {
  67934. x += lastX;
  67935. y += lastY;
  67936. x3 += lastX;
  67937. y3 += lastY;
  67938. }
  67939. x2 = lastX + (lastX - lastX2);
  67940. y2 = lastY + (lastY - lastY2);
  67941. path.cubicTo (x2, y2, x, y, x3, y3);
  67942. lastX2 = x;
  67943. lastY2 = y;
  67944. lastX = x3;
  67945. lastY = y3;
  67946. }
  67947. else
  67948. {
  67949. ++index;
  67950. }
  67951. break;
  67952. case 'Q':
  67953. case 'q':
  67954. if (parseCoords (d, x, y, index, false)
  67955. && parseCoords (d, x2, y2, index, false))
  67956. {
  67957. if (isRelative)
  67958. {
  67959. x += lastX;
  67960. y += lastY;
  67961. x2 += lastX;
  67962. y2 += lastY;
  67963. }
  67964. path.quadraticTo (x, y, x2, y2);
  67965. lastX2 = x;
  67966. lastY2 = y;
  67967. lastX = x2;
  67968. lastY = y2;
  67969. }
  67970. else
  67971. {
  67972. ++index;
  67973. }
  67974. break;
  67975. case 'T':
  67976. case 't':
  67977. if (parseCoords (d, x, y, index, false))
  67978. {
  67979. if (isRelative)
  67980. {
  67981. x += lastX;
  67982. y += lastY;
  67983. }
  67984. x2 = lastX + (lastX - lastX2);
  67985. y2 = lastY + (lastY - lastY2);
  67986. path.quadraticTo (x2, y2, x, y);
  67987. lastX2 = x2;
  67988. lastY2 = y2;
  67989. lastX = x;
  67990. lastY = y;
  67991. }
  67992. else
  67993. {
  67994. ++index;
  67995. }
  67996. break;
  67997. case 'A':
  67998. case 'a':
  67999. if (parseCoords (d, x, y, index, false))
  68000. {
  68001. String num;
  68002. if (parseNextNumber (d, num, index, false))
  68003. {
  68004. const float angle = num.getFloatValue() * (180.0f / float_Pi);
  68005. if (parseNextNumber (d, num, index, false))
  68006. {
  68007. const bool largeArc = num.getIntValue() != 0;
  68008. if (parseNextNumber (d, num, index, false))
  68009. {
  68010. const bool sweep = num.getIntValue() != 0;
  68011. if (parseCoords (d, x2, y2, index, false))
  68012. {
  68013. if (isRelative)
  68014. {
  68015. x2 += lastX;
  68016. y2 += lastY;
  68017. }
  68018. if (lastX != x2 || lastY != y2)
  68019. {
  68020. double centreX, centreY, startAngle, deltaAngle;
  68021. double rx = x, ry = y;
  68022. endpointToCentreParameters (lastX, lastY, x2, y2,
  68023. angle, largeArc, sweep,
  68024. rx, ry, centreX, centreY,
  68025. startAngle, deltaAngle);
  68026. path.addCentredArc ((float) centreX, (float) centreY,
  68027. (float) rx, (float) ry,
  68028. angle, (float) startAngle, (float) (startAngle + deltaAngle),
  68029. false);
  68030. path.lineTo (x2, y2);
  68031. }
  68032. lastX2 = lastX;
  68033. lastY2 = lastY;
  68034. lastX = x2;
  68035. lastY = y2;
  68036. }
  68037. }
  68038. }
  68039. }
  68040. }
  68041. else
  68042. {
  68043. ++index;
  68044. }
  68045. break;
  68046. case 'Z':
  68047. case 'z':
  68048. path.closeSubPath();
  68049. while (CharacterFunctions::isWhitespace (d [index]))
  68050. ++index;
  68051. break;
  68052. default:
  68053. carryOn = false;
  68054. break;
  68055. }
  68056. if (! carryOn)
  68057. break;
  68058. }
  68059. return parseShape (xml, path);
  68060. }
  68061. Drawable* parseRect (const XmlElement& xml) const
  68062. {
  68063. Path rect;
  68064. const bool hasRX = xml.hasAttribute ("rx");
  68065. const bool hasRY = xml.hasAttribute ("ry");
  68066. if (hasRX || hasRY)
  68067. {
  68068. float rx = getCoordLength (xml.getStringAttribute ("rx"), viewBoxW);
  68069. float ry = getCoordLength (xml.getStringAttribute ("ry"), viewBoxH);
  68070. if (! hasRX)
  68071. rx = ry;
  68072. else if (! hasRY)
  68073. ry = rx;
  68074. rect.addRoundedRectangle (getCoordLength (xml.getStringAttribute ("x"), viewBoxW),
  68075. getCoordLength (xml.getStringAttribute ("y"), viewBoxH),
  68076. getCoordLength (xml.getStringAttribute ("width"), viewBoxW),
  68077. getCoordLength (xml.getStringAttribute ("height"), viewBoxH),
  68078. rx, ry);
  68079. }
  68080. else
  68081. {
  68082. rect.addRectangle (getCoordLength (xml.getStringAttribute ("x"), viewBoxW),
  68083. getCoordLength (xml.getStringAttribute ("y"), viewBoxH),
  68084. getCoordLength (xml.getStringAttribute ("width"), viewBoxW),
  68085. getCoordLength (xml.getStringAttribute ("height"), viewBoxH));
  68086. }
  68087. return parseShape (xml, rect);
  68088. }
  68089. Drawable* parseCircle (const XmlElement& xml) const
  68090. {
  68091. Path circle;
  68092. const float cx = getCoordLength (xml.getStringAttribute ("cx"), viewBoxW);
  68093. const float cy = getCoordLength (xml.getStringAttribute ("cy"), viewBoxH);
  68094. const float radius = getCoordLength (xml.getStringAttribute ("r"), viewBoxW);
  68095. circle.addEllipse (cx - radius, cy - radius, radius * 2.0f, radius * 2.0f);
  68096. return parseShape (xml, circle);
  68097. }
  68098. Drawable* parseEllipse (const XmlElement& xml) const
  68099. {
  68100. Path ellipse;
  68101. const float cx = getCoordLength (xml.getStringAttribute ("cx"), viewBoxW);
  68102. const float cy = getCoordLength (xml.getStringAttribute ("cy"), viewBoxH);
  68103. const float radiusX = getCoordLength (xml.getStringAttribute ("rx"), viewBoxW);
  68104. const float radiusY = getCoordLength (xml.getStringAttribute ("ry"), viewBoxH);
  68105. ellipse.addEllipse (cx - radiusX, cy - radiusY, radiusX * 2.0f, radiusY * 2.0f);
  68106. return parseShape (xml, ellipse);
  68107. }
  68108. Drawable* parseLine (const XmlElement& xml) const
  68109. {
  68110. Path line;
  68111. const float x1 = getCoordLength (xml.getStringAttribute ("x1"), viewBoxW);
  68112. const float y1 = getCoordLength (xml.getStringAttribute ("y1"), viewBoxH);
  68113. const float x2 = getCoordLength (xml.getStringAttribute ("x2"), viewBoxW);
  68114. const float y2 = getCoordLength (xml.getStringAttribute ("y2"), viewBoxH);
  68115. line.startNewSubPath (x1, y1);
  68116. line.lineTo (x2, y2);
  68117. return parseShape (xml, line);
  68118. }
  68119. Drawable* parsePolygon (const XmlElement& xml, const bool isPolyline) const
  68120. {
  68121. const String points (xml.getStringAttribute ("points"));
  68122. Path path;
  68123. int index = 0;
  68124. float x, y;
  68125. if (parseCoords (points, x, y, index, true))
  68126. {
  68127. float firstX = x;
  68128. float firstY = y;
  68129. float lastX = 0, lastY = 0;
  68130. path.startNewSubPath (x, y);
  68131. while (parseCoords (points, x, y, index, true))
  68132. {
  68133. lastX = x;
  68134. lastY = y;
  68135. path.lineTo (x, y);
  68136. }
  68137. if ((! isPolyline) || (firstX == lastX && firstY == lastY))
  68138. path.closeSubPath();
  68139. }
  68140. return parseShape (xml, path);
  68141. }
  68142. Drawable* parseShape (const XmlElement& xml, Path& path,
  68143. const bool shouldParseTransform = true) const
  68144. {
  68145. if (shouldParseTransform && xml.hasAttribute ("transform"))
  68146. {
  68147. SVGState newState (*this);
  68148. newState.addTransform (xml);
  68149. return newState.parseShape (xml, path, false);
  68150. }
  68151. DrawablePath* dp = new DrawablePath();
  68152. dp->setName (xml.getStringAttribute ("id"));
  68153. dp->setFill (Colours::transparentBlack);
  68154. path.applyTransform (transform);
  68155. dp->setPath (path);
  68156. Path::Iterator iter (path);
  68157. bool containsClosedSubPath = false;
  68158. while (iter.next())
  68159. {
  68160. if (iter.elementType == Path::Iterator::closePath)
  68161. {
  68162. containsClosedSubPath = true;
  68163. break;
  68164. }
  68165. }
  68166. dp->setFill (getPathFillType (path,
  68167. getStyleAttribute (&xml, "fill"),
  68168. getStyleAttribute (&xml, "fill-opacity"),
  68169. getStyleAttribute (&xml, "opacity"),
  68170. containsClosedSubPath ? Colours::black
  68171. : Colours::transparentBlack));
  68172. const String strokeType (getStyleAttribute (&xml, "stroke"));
  68173. if (strokeType.isNotEmpty() && ! strokeType.equalsIgnoreCase ("none"))
  68174. {
  68175. dp->setStrokeFill (getPathFillType (path, strokeType,
  68176. getStyleAttribute (&xml, "stroke-opacity"),
  68177. getStyleAttribute (&xml, "opacity"),
  68178. Colours::transparentBlack));
  68179. dp->setStrokeType (getStrokeFor (&xml));
  68180. }
  68181. return dp;
  68182. }
  68183. const XmlElement* findLinkedElement (const XmlElement* e) const
  68184. {
  68185. const String id (e->getStringAttribute ("xlink:href"));
  68186. if (! id.startsWithChar ('#'))
  68187. return 0;
  68188. return findElementForId (topLevelXml, id.substring (1));
  68189. }
  68190. void addGradientStopsIn (ColourGradient& cg, const XmlElement* const fillXml) const
  68191. {
  68192. if (fillXml == 0)
  68193. return;
  68194. forEachXmlChildElementWithTagName (*fillXml, e, "stop")
  68195. {
  68196. int index = 0;
  68197. Colour col (parseColour (getStyleAttribute (e, "stop-color"), index, Colours::black));
  68198. const String opacity (getStyleAttribute (e, "stop-opacity", "1"));
  68199. col = col.withMultipliedAlpha (jlimit (0.0f, 1.0f, opacity.getFloatValue()));
  68200. double offset = e->getDoubleAttribute ("offset");
  68201. if (e->getStringAttribute ("offset").containsChar ('%'))
  68202. offset *= 0.01;
  68203. cg.addColour (jlimit (0.0, 1.0, offset), col);
  68204. }
  68205. }
  68206. const FillType getPathFillType (const Path& path,
  68207. const String& fill,
  68208. const String& fillOpacity,
  68209. const String& overallOpacity,
  68210. const Colour& defaultColour) const
  68211. {
  68212. float opacity = 1.0f;
  68213. if (overallOpacity.isNotEmpty())
  68214. opacity = jlimit (0.0f, 1.0f, overallOpacity.getFloatValue());
  68215. if (fillOpacity.isNotEmpty())
  68216. opacity *= (jlimit (0.0f, 1.0f, fillOpacity.getFloatValue()));
  68217. if (fill.startsWithIgnoreCase ("url"))
  68218. {
  68219. const String id (fill.fromFirstOccurrenceOf ("#", false, false)
  68220. .upToLastOccurrenceOf (")", false, false).trim());
  68221. const XmlElement* const fillXml = findElementForId (topLevelXml, id);
  68222. if (fillXml != 0
  68223. && (fillXml->hasTagName ("linearGradient")
  68224. || fillXml->hasTagName ("radialGradient")))
  68225. {
  68226. const XmlElement* inheritedFrom = findLinkedElement (fillXml);
  68227. ColourGradient gradient;
  68228. addGradientStopsIn (gradient, inheritedFrom);
  68229. addGradientStopsIn (gradient, fillXml);
  68230. if (gradient.getNumColours() > 0)
  68231. {
  68232. gradient.addColour (0.0, gradient.getColour (0));
  68233. gradient.addColour (1.0, gradient.getColour (gradient.getNumColours() - 1));
  68234. }
  68235. else
  68236. {
  68237. gradient.addColour (0.0, Colours::black);
  68238. gradient.addColour (1.0, Colours::black);
  68239. }
  68240. if (overallOpacity.isNotEmpty())
  68241. gradient.multiplyOpacity (overallOpacity.getFloatValue());
  68242. jassert (gradient.getNumColours() > 0);
  68243. gradient.isRadial = fillXml->hasTagName ("radialGradient");
  68244. float width = viewBoxW;
  68245. float height = viewBoxH;
  68246. float dx = 0.0f;
  68247. float dy = 0.0f;
  68248. const bool userSpace = fillXml->getStringAttribute ("gradientUnits").equalsIgnoreCase ("userSpaceOnUse");
  68249. if (! userSpace)
  68250. {
  68251. const Rectangle<float> bounds (path.getBounds());
  68252. dx = bounds.getX();
  68253. dy = bounds.getY();
  68254. width = bounds.getWidth();
  68255. height = bounds.getHeight();
  68256. }
  68257. if (gradient.isRadial)
  68258. {
  68259. gradient.x1 = dx + getCoordLength (fillXml->getStringAttribute ("cx", "50%"), width);
  68260. gradient.y1 = dy + getCoordLength (fillXml->getStringAttribute ("cy", "50%"), height);
  68261. const float radius = getCoordLength (fillXml->getStringAttribute ("r", "50%"), width);
  68262. gradient.x2 = gradient.x1 + radius;
  68263. gradient.y2 = gradient.y1;
  68264. //xxx (the fx, fy focal point isn't handled properly here..)
  68265. }
  68266. else
  68267. {
  68268. gradient.x1 = dx + getCoordLength (fillXml->getStringAttribute ("x1", "0%"), width);
  68269. gradient.y1 = dy + getCoordLength (fillXml->getStringAttribute ("y1", "0%"), height);
  68270. gradient.x2 = dx + getCoordLength (fillXml->getStringAttribute ("x2", "100%"), width);
  68271. gradient.y2 = dy + getCoordLength (fillXml->getStringAttribute ("y2", "0%"), height);
  68272. if (gradient.x1 == gradient.x2 && gradient.y1 == gradient.y2)
  68273. return Colour (gradient.getColour (gradient.getNumColours() - 1));
  68274. }
  68275. FillType type (gradient);
  68276. type.transform = parseTransform (fillXml->getStringAttribute ("gradientTransform"))
  68277. .followedBy (transform);
  68278. return type;
  68279. }
  68280. }
  68281. if (fill.equalsIgnoreCase ("none"))
  68282. return Colours::transparentBlack;
  68283. int i = 0;
  68284. const Colour colour (parseColour (fill, i, defaultColour));
  68285. return colour.withMultipliedAlpha (opacity);
  68286. }
  68287. const PathStrokeType getStrokeFor (const XmlElement* const xml) const
  68288. {
  68289. const String width (getStyleAttribute (xml, "stroke-width"));
  68290. const String cap (getStyleAttribute (xml, "stroke-linecap"));
  68291. const String join (getStyleAttribute (xml, "stroke-linejoin"));
  68292. //const String mitreLimit (getStyleAttribute (xml, "stroke-miterlimit"));
  68293. //const String dashArray (getStyleAttribute (xml, "stroke-dasharray"));
  68294. //const String dashOffset (getStyleAttribute (xml, "stroke-dashoffset"));
  68295. PathStrokeType::JointStyle joinStyle = PathStrokeType::mitered;
  68296. PathStrokeType::EndCapStyle capStyle = PathStrokeType::butt;
  68297. if (join.equalsIgnoreCase ("round"))
  68298. joinStyle = PathStrokeType::curved;
  68299. else if (join.equalsIgnoreCase ("bevel"))
  68300. joinStyle = PathStrokeType::beveled;
  68301. if (cap.equalsIgnoreCase ("round"))
  68302. capStyle = PathStrokeType::rounded;
  68303. else if (cap.equalsIgnoreCase ("square"))
  68304. capStyle = PathStrokeType::square;
  68305. float ox = 0.0f, oy = 0.0f;
  68306. transform.transformPoint (ox, oy);
  68307. float x = getCoordLength (width, viewBoxW), y = 0.0f;
  68308. transform.transformPoint (x, y);
  68309. return PathStrokeType (width.isNotEmpty() ? juce_hypotf (x - ox, y - oy) : 1.0f,
  68310. joinStyle, capStyle);
  68311. }
  68312. Drawable* parseText (const XmlElement& xml)
  68313. {
  68314. Array <float> xCoords, yCoords, dxCoords, dyCoords;
  68315. getCoordList (xCoords, getInheritedAttribute (&xml, "x"), true, true);
  68316. getCoordList (yCoords, getInheritedAttribute (&xml, "y"), true, false);
  68317. getCoordList (dxCoords, getInheritedAttribute (&xml, "dx"), true, true);
  68318. getCoordList (dyCoords, getInheritedAttribute (&xml, "dy"), true, false);
  68319. //xxx not done text yet!
  68320. forEachXmlChildElement (xml, e)
  68321. {
  68322. if (e->isTextElement())
  68323. {
  68324. const String text (e->getText());
  68325. Path path;
  68326. Drawable* s = parseShape (*e, path);
  68327. delete s;
  68328. }
  68329. else if (e->hasTagName ("tspan"))
  68330. {
  68331. Drawable* s = parseText (*e);
  68332. delete s;
  68333. }
  68334. }
  68335. return 0;
  68336. }
  68337. void addTransform (const XmlElement& xml)
  68338. {
  68339. transform = parseTransform (xml.getStringAttribute ("transform"))
  68340. .followedBy (transform);
  68341. }
  68342. bool parseCoord (const String& s, float& value, int& index,
  68343. const bool allowUnits, const bool isX) const
  68344. {
  68345. String number;
  68346. if (! parseNextNumber (s, number, index, allowUnits))
  68347. {
  68348. value = 0;
  68349. return false;
  68350. }
  68351. value = getCoordLength (number, isX ? viewBoxW : viewBoxH);
  68352. return true;
  68353. }
  68354. bool parseCoords (const String& s, float& x, float& y,
  68355. int& index, const bool allowUnits) const
  68356. {
  68357. return parseCoord (s, x, index, allowUnits, true)
  68358. && parseCoord (s, y, index, allowUnits, false);
  68359. }
  68360. float getCoordLength (const String& s, const float sizeForProportions) const
  68361. {
  68362. float n = s.getFloatValue();
  68363. const int len = s.length();
  68364. if (len > 2)
  68365. {
  68366. const float dpi = 96.0f;
  68367. const juce_wchar n1 = s [len - 2];
  68368. const juce_wchar n2 = s [len - 1];
  68369. if (n1 == 'i' && n2 == 'n')
  68370. n *= dpi;
  68371. else if (n1 == 'm' && n2 == 'm')
  68372. n *= dpi / 25.4f;
  68373. else if (n1 == 'c' && n2 == 'm')
  68374. n *= dpi / 2.54f;
  68375. else if (n1 == 'p' && n2 == 'c')
  68376. n *= 15.0f;
  68377. else if (n2 == '%')
  68378. n *= 0.01f * sizeForProportions;
  68379. }
  68380. return n;
  68381. }
  68382. void getCoordList (Array <float>& coords, const String& list,
  68383. const bool allowUnits, const bool isX) const
  68384. {
  68385. int index = 0;
  68386. float value;
  68387. while (parseCoord (list, value, index, allowUnits, isX))
  68388. coords.add (value);
  68389. }
  68390. void parseCSSStyle (const XmlElement& xml)
  68391. {
  68392. cssStyleText = xml.getAllSubText() + "\n" + cssStyleText;
  68393. }
  68394. const String getStyleAttribute (const XmlElement* xml, const String& attributeName,
  68395. const String& defaultValue = String::empty) const
  68396. {
  68397. if (xml->hasAttribute (attributeName))
  68398. return xml->getStringAttribute (attributeName, defaultValue);
  68399. const String styleAtt (xml->getStringAttribute ("style"));
  68400. if (styleAtt.isNotEmpty())
  68401. {
  68402. const String value (getAttributeFromStyleList (styleAtt, attributeName, String::empty));
  68403. if (value.isNotEmpty())
  68404. return value;
  68405. }
  68406. else if (xml->hasAttribute ("class"))
  68407. {
  68408. const String className ("." + xml->getStringAttribute ("class"));
  68409. int index = cssStyleText.indexOfIgnoreCase (className + " ");
  68410. if (index < 0)
  68411. index = cssStyleText.indexOfIgnoreCase (className + "{");
  68412. if (index >= 0)
  68413. {
  68414. const int openBracket = cssStyleText.indexOfChar (index, '{');
  68415. if (openBracket > index)
  68416. {
  68417. const int closeBracket = cssStyleText.indexOfChar (openBracket, '}');
  68418. if (closeBracket > openBracket)
  68419. {
  68420. const String value (getAttributeFromStyleList (cssStyleText.substring (openBracket + 1, closeBracket), attributeName, defaultValue));
  68421. if (value.isNotEmpty())
  68422. return value;
  68423. }
  68424. }
  68425. }
  68426. }
  68427. xml = const_cast <XmlElement*> (topLevelXml)->findParentElementOf (xml);
  68428. if (xml != 0)
  68429. return getStyleAttribute (xml, attributeName, defaultValue);
  68430. return defaultValue;
  68431. }
  68432. const String getInheritedAttribute (const XmlElement* xml, const String& attributeName) const
  68433. {
  68434. if (xml->hasAttribute (attributeName))
  68435. return xml->getStringAttribute (attributeName);
  68436. xml = const_cast <XmlElement*> (topLevelXml)->findParentElementOf (xml);
  68437. if (xml != 0)
  68438. return getInheritedAttribute (xml, attributeName);
  68439. return String::empty;
  68440. }
  68441. static bool isIdentifierChar (const juce_wchar c)
  68442. {
  68443. return CharacterFunctions::isLetter (c) || c == '-';
  68444. }
  68445. static const String getAttributeFromStyleList (const String& list, const String& attributeName, const String& defaultValue)
  68446. {
  68447. int i = 0;
  68448. for (;;)
  68449. {
  68450. i = list.indexOf (i, attributeName);
  68451. if (i < 0)
  68452. break;
  68453. if ((i == 0 || (i > 0 && ! isIdentifierChar (list [i - 1])))
  68454. && ! isIdentifierChar (list [i + attributeName.length()]))
  68455. {
  68456. i = list.indexOfChar (i, ':');
  68457. if (i < 0)
  68458. break;
  68459. int end = list.indexOfChar (i, ';');
  68460. if (end < 0)
  68461. end = 0x7ffff;
  68462. return list.substring (i + 1, end).trim();
  68463. }
  68464. ++i;
  68465. }
  68466. return defaultValue;
  68467. }
  68468. static bool parseNextNumber (const String& source, String& value, int& index, const bool allowUnits)
  68469. {
  68470. const juce_wchar* const s = source;
  68471. while (CharacterFunctions::isWhitespace (s[index]) || s[index] == ',')
  68472. ++index;
  68473. int start = index;
  68474. if (CharacterFunctions::isDigit (s[index]) || s[index] == '.' || s[index] == '-')
  68475. ++index;
  68476. while (CharacterFunctions::isDigit (s[index]) || s[index] == '.')
  68477. ++index;
  68478. if ((s[index] == 'e' || s[index] == 'E')
  68479. && (CharacterFunctions::isDigit (s[index + 1])
  68480. || s[index + 1] == '-'
  68481. || s[index + 1] == '+'))
  68482. {
  68483. index += 2;
  68484. while (CharacterFunctions::isDigit (s[index]))
  68485. ++index;
  68486. }
  68487. if (allowUnits)
  68488. {
  68489. while (CharacterFunctions::isLetter (s[index]))
  68490. ++index;
  68491. }
  68492. if (index == start)
  68493. return false;
  68494. value = String (s + start, index - start);
  68495. while (CharacterFunctions::isWhitespace (s[index]) || s[index] == ',')
  68496. ++index;
  68497. return true;
  68498. }
  68499. static const Colour parseColour (const String& s, int& index, const Colour& defaultColour)
  68500. {
  68501. if (s [index] == '#')
  68502. {
  68503. uint32 hex [6];
  68504. zeromem (hex, sizeof (hex));
  68505. int numChars = 0;
  68506. for (int i = 6; --i >= 0;)
  68507. {
  68508. const int hexValue = CharacterFunctions::getHexDigitValue (s [++index]);
  68509. if (hexValue >= 0)
  68510. hex [numChars++] = hexValue;
  68511. else
  68512. break;
  68513. }
  68514. if (numChars <= 3)
  68515. return Colour ((uint8) (hex [0] * 0x11),
  68516. (uint8) (hex [1] * 0x11),
  68517. (uint8) (hex [2] * 0x11));
  68518. else
  68519. return Colour ((uint8) ((hex [0] << 4) + hex [1]),
  68520. (uint8) ((hex [2] << 4) + hex [3]),
  68521. (uint8) ((hex [4] << 4) + hex [5]));
  68522. }
  68523. else if (s [index] == 'r'
  68524. && s [index + 1] == 'g'
  68525. && s [index + 2] == 'b')
  68526. {
  68527. const int openBracket = s.indexOfChar (index, '(');
  68528. const int closeBracket = s.indexOfChar (openBracket, ')');
  68529. if (openBracket >= 3 && closeBracket > openBracket)
  68530. {
  68531. index = closeBracket;
  68532. StringArray tokens;
  68533. tokens.addTokens (s.substring (openBracket + 1, closeBracket), ",", "");
  68534. tokens.trim();
  68535. tokens.removeEmptyStrings();
  68536. if (tokens[0].containsChar ('%'))
  68537. return Colour ((uint8) roundToInt (2.55 * tokens[0].getDoubleValue()),
  68538. (uint8) roundToInt (2.55 * tokens[1].getDoubleValue()),
  68539. (uint8) roundToInt (2.55 * tokens[2].getDoubleValue()));
  68540. else
  68541. return Colour ((uint8) tokens[0].getIntValue(),
  68542. (uint8) tokens[1].getIntValue(),
  68543. (uint8) tokens[2].getIntValue());
  68544. }
  68545. }
  68546. return Colours::findColourForName (s, defaultColour);
  68547. }
  68548. static const AffineTransform parseTransform (String t)
  68549. {
  68550. AffineTransform result;
  68551. while (t.isNotEmpty())
  68552. {
  68553. StringArray tokens;
  68554. tokens.addTokens (t.fromFirstOccurrenceOf ("(", false, false)
  68555. .upToFirstOccurrenceOf (")", false, false),
  68556. ", ", String::empty);
  68557. tokens.removeEmptyStrings (true);
  68558. float numbers [6];
  68559. for (int i = 0; i < 6; ++i)
  68560. numbers[i] = tokens[i].getFloatValue();
  68561. AffineTransform trans;
  68562. if (t.startsWithIgnoreCase ("matrix"))
  68563. {
  68564. trans = AffineTransform (numbers[0], numbers[2], numbers[4],
  68565. numbers[1], numbers[3], numbers[5]);
  68566. }
  68567. else if (t.startsWithIgnoreCase ("translate"))
  68568. {
  68569. jassert (tokens.size() == 2);
  68570. trans = AffineTransform::translation (numbers[0], numbers[1]);
  68571. }
  68572. else if (t.startsWithIgnoreCase ("scale"))
  68573. {
  68574. if (tokens.size() == 1)
  68575. trans = AffineTransform::scale (numbers[0], numbers[0]);
  68576. else
  68577. trans = AffineTransform::scale (numbers[0], numbers[1]);
  68578. }
  68579. else if (t.startsWithIgnoreCase ("rotate"))
  68580. {
  68581. if (tokens.size() != 3)
  68582. trans = AffineTransform::rotation (numbers[0] / (180.0f / float_Pi));
  68583. else
  68584. trans = AffineTransform::rotation (numbers[0] / (180.0f / float_Pi),
  68585. numbers[1], numbers[2]);
  68586. }
  68587. else if (t.startsWithIgnoreCase ("skewX"))
  68588. {
  68589. trans = AffineTransform (1.0f, tanf (numbers[0] * (float_Pi / 180.0f)), 0.0f,
  68590. 0.0f, 1.0f, 0.0f);
  68591. }
  68592. else if (t.startsWithIgnoreCase ("skewY"))
  68593. {
  68594. trans = AffineTransform (1.0f, 0.0f, 0.0f,
  68595. tanf (numbers[0] * (float_Pi / 180.0f)), 1.0f, 0.0f);
  68596. }
  68597. result = trans.followedBy (result);
  68598. t = t.fromFirstOccurrenceOf (")", false, false).trimStart();
  68599. }
  68600. return result;
  68601. }
  68602. static void endpointToCentreParameters (const double x1, const double y1,
  68603. const double x2, const double y2,
  68604. const double angle,
  68605. const bool largeArc, const bool sweep,
  68606. double& rx, double& ry,
  68607. double& centreX, double& centreY,
  68608. double& startAngle, double& deltaAngle)
  68609. {
  68610. const double midX = (x1 - x2) * 0.5;
  68611. const double midY = (y1 - y2) * 0.5;
  68612. const double cosAngle = cos (angle);
  68613. const double sinAngle = sin (angle);
  68614. const double xp = cosAngle * midX + sinAngle * midY;
  68615. const double yp = cosAngle * midY - sinAngle * midX;
  68616. const double xp2 = xp * xp;
  68617. const double yp2 = yp * yp;
  68618. double rx2 = rx * rx;
  68619. double ry2 = ry * ry;
  68620. const double s = (xp2 / rx2) + (yp2 / ry2);
  68621. double c;
  68622. if (s <= 1.0)
  68623. {
  68624. c = sqrt (jmax (0.0, ((rx2 * ry2) - (rx2 * yp2) - (ry2 * xp2))
  68625. / (( rx2 * yp2) + (ry2 * xp2))));
  68626. if (largeArc == sweep)
  68627. c = -c;
  68628. }
  68629. else
  68630. {
  68631. const double s2 = sqrt (s);
  68632. rx *= s2;
  68633. ry *= s2;
  68634. rx2 = rx * rx;
  68635. ry2 = ry * ry;
  68636. c = 0;
  68637. }
  68638. const double cpx = ((rx * yp) / ry) * c;
  68639. const double cpy = ((-ry * xp) / rx) * c;
  68640. centreX = ((x1 + x2) * 0.5) + (cosAngle * cpx) - (sinAngle * cpy);
  68641. centreY = ((y1 + y2) * 0.5) + (sinAngle * cpx) + (cosAngle * cpy);
  68642. const double ux = (xp - cpx) / rx;
  68643. const double uy = (yp - cpy) / ry;
  68644. const double vx = (-xp - cpx) / rx;
  68645. const double vy = (-yp - cpy) / ry;
  68646. const double length = juce_hypot (ux, uy);
  68647. startAngle = acos (jlimit (-1.0, 1.0, ux / length));
  68648. if (uy < 0)
  68649. startAngle = -startAngle;
  68650. startAngle += double_Pi * 0.5;
  68651. deltaAngle = acos (jlimit (-1.0, 1.0, ((ux * vx) + (uy * vy))
  68652. / (length * juce_hypot (vx, vy))));
  68653. if ((ux * vy) - (uy * vx) < 0)
  68654. deltaAngle = -deltaAngle;
  68655. if (sweep)
  68656. {
  68657. if (deltaAngle < 0)
  68658. deltaAngle += double_Pi * 2.0;
  68659. }
  68660. else
  68661. {
  68662. if (deltaAngle > 0)
  68663. deltaAngle -= double_Pi * 2.0;
  68664. }
  68665. deltaAngle = fmod (deltaAngle, double_Pi * 2.0);
  68666. }
  68667. static const XmlElement* findElementForId (const XmlElement* const parent, const String& id)
  68668. {
  68669. forEachXmlChildElement (*parent, e)
  68670. {
  68671. if (e->compareAttribute ("id", id))
  68672. return e;
  68673. const XmlElement* const found = findElementForId (e, id);
  68674. if (found != 0)
  68675. return found;
  68676. }
  68677. return 0;
  68678. }
  68679. SVGState& operator= (const SVGState&);
  68680. };
  68681. Drawable* Drawable::createFromSVG (const XmlElement& svgDocument)
  68682. {
  68683. SVGState state (&svgDocument);
  68684. return state.parseSVGElement (svgDocument);
  68685. }
  68686. END_JUCE_NAMESPACE
  68687. /*** End of inlined file: juce_SVGParser.cpp ***/
  68688. /*** Start of inlined file: juce_DropShadowEffect.cpp ***/
  68689. BEGIN_JUCE_NAMESPACE
  68690. #if JUCE_MSVC
  68691. #pragma optimize ("t", on) // try to avoid slowing everything down in debug builds
  68692. #endif
  68693. DropShadowEffect::DropShadowEffect()
  68694. : offsetX (0),
  68695. offsetY (0),
  68696. radius (4),
  68697. opacity (0.6f)
  68698. {
  68699. }
  68700. DropShadowEffect::~DropShadowEffect()
  68701. {
  68702. }
  68703. void DropShadowEffect::setShadowProperties (const float newRadius,
  68704. const float newOpacity,
  68705. const int newShadowOffsetX,
  68706. const int newShadowOffsetY)
  68707. {
  68708. radius = jmax (1.1f, newRadius);
  68709. offsetX = newShadowOffsetX;
  68710. offsetY = newShadowOffsetY;
  68711. opacity = newOpacity;
  68712. }
  68713. void DropShadowEffect::applyEffect (Image& image, Graphics& g)
  68714. {
  68715. const int w = image.getWidth();
  68716. const int h = image.getHeight();
  68717. Image shadowImage (Image::SingleChannel, w, h, false);
  68718. const Image::BitmapData srcData (image, 0, 0, w, h);
  68719. const Image::BitmapData destData (shadowImage, 0, 0, w, h, true);
  68720. const int filter = roundToInt (63.0f / radius);
  68721. const int radiusMinus1 = roundToInt ((radius - 1.0f) * 63.0f);
  68722. for (int x = w; --x >= 0;)
  68723. {
  68724. int shadowAlpha = 0;
  68725. const PixelARGB* src = ((const PixelARGB*) srcData.data) + x;
  68726. uint8* shadowPix = destData.data + x;
  68727. for (int y = h; --y >= 0;)
  68728. {
  68729. shadowAlpha = ((shadowAlpha * radiusMinus1 + (src->getAlpha() << 6)) * filter) >> 12;
  68730. *shadowPix = (uint8) shadowAlpha;
  68731. src = (const PixelARGB*) (((const uint8*) src) + srcData.lineStride);
  68732. shadowPix += destData.lineStride;
  68733. }
  68734. }
  68735. for (int y = h; --y >= 0;)
  68736. {
  68737. int shadowAlpha = 0;
  68738. uint8* shadowPix = destData.getLinePointer (y);
  68739. for (int x = w; --x >= 0;)
  68740. {
  68741. shadowAlpha = ((shadowAlpha * radiusMinus1 + (*shadowPix << 6)) * filter) >> 12;
  68742. *shadowPix++ = (uint8) shadowAlpha;
  68743. }
  68744. }
  68745. g.setColour (Colours::black.withAlpha (opacity));
  68746. g.drawImageAt (&shadowImage, offsetX, offsetY, true);
  68747. g.setOpacity (1.0f);
  68748. g.drawImageAt (&image, 0, 0);
  68749. }
  68750. END_JUCE_NAMESPACE
  68751. /*** End of inlined file: juce_DropShadowEffect.cpp ***/
  68752. /*** Start of inlined file: juce_GlowEffect.cpp ***/
  68753. BEGIN_JUCE_NAMESPACE
  68754. GlowEffect::GlowEffect()
  68755. : radius (2.0f),
  68756. colour (Colours::white)
  68757. {
  68758. }
  68759. GlowEffect::~GlowEffect()
  68760. {
  68761. }
  68762. void GlowEffect::setGlowProperties (const float newRadius,
  68763. const Colour& newColour)
  68764. {
  68765. radius = newRadius;
  68766. colour = newColour;
  68767. }
  68768. void GlowEffect::applyEffect (Image& image, Graphics& g)
  68769. {
  68770. Image temp (image.getFormat(), image.getWidth(), image.getHeight(), true);
  68771. ImageConvolutionKernel blurKernel (roundToInt (radius * 2.0f));
  68772. blurKernel.createGaussianBlur (radius);
  68773. blurKernel.rescaleAllValues (radius);
  68774. blurKernel.applyToImage (temp, &image, image.getBounds());
  68775. g.setColour (colour);
  68776. g.drawImageAt (&temp, 0, 0, true);
  68777. g.setOpacity (1.0f);
  68778. g.drawImageAt (&image, 0, 0, false);
  68779. }
  68780. END_JUCE_NAMESPACE
  68781. /*** End of inlined file: juce_GlowEffect.cpp ***/
  68782. /*** Start of inlined file: juce_ReduceOpacityEffect.cpp ***/
  68783. BEGIN_JUCE_NAMESPACE
  68784. ReduceOpacityEffect::ReduceOpacityEffect (const float opacity_)
  68785. : opacity (opacity_)
  68786. {
  68787. }
  68788. ReduceOpacityEffect::~ReduceOpacityEffect()
  68789. {
  68790. }
  68791. void ReduceOpacityEffect::setOpacity (const float newOpacity)
  68792. {
  68793. opacity = jlimit (0.0f, 1.0f, newOpacity);
  68794. }
  68795. void ReduceOpacityEffect::applyEffect (Image& image, Graphics& g)
  68796. {
  68797. g.setOpacity (opacity);
  68798. g.drawImageAt (&image, 0, 0);
  68799. }
  68800. END_JUCE_NAMESPACE
  68801. /*** End of inlined file: juce_ReduceOpacityEffect.cpp ***/
  68802. /*** Start of inlined file: juce_Font.cpp ***/
  68803. BEGIN_JUCE_NAMESPACE
  68804. namespace FontValues
  68805. {
  68806. static float limitFontHeight (const float height) throw()
  68807. {
  68808. return jlimit (0.1f, 10000.0f, height);
  68809. }
  68810. static const float defaultFontHeight = 14.0f;
  68811. }
  68812. Font::SharedFontInternal::SharedFontInternal (const String& typefaceName_, const float height_, const float horizontalScale_,
  68813. const float kerning_, const float ascent_, const int styleFlags_,
  68814. Typeface* const typeface_) throw()
  68815. : typefaceName (typefaceName_),
  68816. height (height_),
  68817. horizontalScale (horizontalScale_),
  68818. kerning (kerning_),
  68819. ascent (ascent_),
  68820. styleFlags (styleFlags_),
  68821. typeface (typeface_)
  68822. {
  68823. }
  68824. Font::SharedFontInternal::SharedFontInternal (const SharedFontInternal& other) throw()
  68825. : typefaceName (other.typefaceName),
  68826. height (other.height),
  68827. horizontalScale (other.horizontalScale),
  68828. kerning (other.kerning),
  68829. ascent (other.ascent),
  68830. styleFlags (other.styleFlags),
  68831. typeface (other.typeface)
  68832. {
  68833. }
  68834. Font::Font() throw()
  68835. : font (new SharedFontInternal (getDefaultSansSerifFontName(), FontValues::defaultFontHeight,
  68836. 1.0f, 0, 0, Font::plain, 0))
  68837. {
  68838. }
  68839. Font::Font (const float fontHeight, const int styleFlags_) throw()
  68840. : font (new SharedFontInternal (getDefaultSansSerifFontName(), FontValues::limitFontHeight (fontHeight),
  68841. 1.0f, 0, 0, styleFlags_, 0))
  68842. {
  68843. }
  68844. Font::Font (const String& typefaceName_,
  68845. const float fontHeight,
  68846. const int styleFlags_) throw()
  68847. : font (new SharedFontInternal (typefaceName_, FontValues::limitFontHeight (fontHeight),
  68848. 1.0f, 0, 0, styleFlags_, 0))
  68849. {
  68850. }
  68851. Font::Font (const Font& other) throw()
  68852. : font (other.font)
  68853. {
  68854. }
  68855. Font& Font::operator= (const Font& other) throw()
  68856. {
  68857. font = other.font;
  68858. return *this;
  68859. }
  68860. Font::~Font() throw()
  68861. {
  68862. }
  68863. Font::Font (const Typeface::Ptr& typeface) throw()
  68864. : font (new SharedFontInternal (typeface->getName(), FontValues::defaultFontHeight,
  68865. 1.0f, 0, 0, Font::plain, typeface))
  68866. {
  68867. }
  68868. bool Font::operator== (const Font& other) const throw()
  68869. {
  68870. return font == other.font
  68871. || (font->height == other.font->height
  68872. && font->styleFlags == other.font->styleFlags
  68873. && font->horizontalScale == other.font->horizontalScale
  68874. && font->kerning == other.font->kerning
  68875. && font->typefaceName == other.font->typefaceName);
  68876. }
  68877. bool Font::operator!= (const Font& other) const throw()
  68878. {
  68879. return ! operator== (other);
  68880. }
  68881. void Font::dupeInternalIfShared() throw()
  68882. {
  68883. if (font->getReferenceCount() > 1)
  68884. font = new SharedFontInternal (*font);
  68885. }
  68886. const String Font::getDefaultSansSerifFontName() throw()
  68887. {
  68888. static const String name ("<Sans-Serif>");
  68889. return name;
  68890. }
  68891. const String Font::getDefaultSerifFontName() throw()
  68892. {
  68893. static const String name ("<Serif>");
  68894. return name;
  68895. }
  68896. const String Font::getDefaultMonospacedFontName() throw()
  68897. {
  68898. static const String name ("<Monospaced>");
  68899. return name;
  68900. }
  68901. void Font::setTypefaceName (const String& faceName) throw()
  68902. {
  68903. if (faceName != font->typefaceName)
  68904. {
  68905. dupeInternalIfShared();
  68906. font->typefaceName = faceName;
  68907. font->typeface = 0;
  68908. font->ascent = 0;
  68909. }
  68910. }
  68911. static String fallbackFont;
  68912. const String Font::getFallbackFontName() throw()
  68913. {
  68914. return fallbackFont;
  68915. }
  68916. void Font::setFallbackFontName (const String& name) throw()
  68917. {
  68918. fallbackFont = name;
  68919. }
  68920. void Font::setHeight (float newHeight) throw()
  68921. {
  68922. newHeight = FontValues::limitFontHeight (newHeight);
  68923. if (font->height != newHeight)
  68924. {
  68925. dupeInternalIfShared();
  68926. font->height = newHeight;
  68927. }
  68928. }
  68929. void Font::setHeightWithoutChangingWidth (float newHeight) throw()
  68930. {
  68931. newHeight = FontValues::limitFontHeight (newHeight);
  68932. if (font->height != newHeight)
  68933. {
  68934. dupeInternalIfShared();
  68935. font->horizontalScale *= (font->height / newHeight);
  68936. font->height = newHeight;
  68937. }
  68938. }
  68939. void Font::setStyleFlags (const int newFlags) throw()
  68940. {
  68941. if (font->styleFlags != newFlags)
  68942. {
  68943. dupeInternalIfShared();
  68944. font->styleFlags = newFlags;
  68945. font->typeface = 0;
  68946. font->ascent = 0;
  68947. }
  68948. }
  68949. void Font::setSizeAndStyle (float newHeight,
  68950. const int newStyleFlags,
  68951. const float newHorizontalScale,
  68952. const float newKerningAmount) throw()
  68953. {
  68954. newHeight = FontValues::limitFontHeight (newHeight);
  68955. if (font->height != newHeight
  68956. || font->horizontalScale != newHorizontalScale
  68957. || font->kerning != newKerningAmount)
  68958. {
  68959. dupeInternalIfShared();
  68960. font->height = newHeight;
  68961. font->horizontalScale = newHorizontalScale;
  68962. font->kerning = newKerningAmount;
  68963. }
  68964. setStyleFlags (newStyleFlags);
  68965. }
  68966. void Font::setHorizontalScale (const float scaleFactor) throw()
  68967. {
  68968. dupeInternalIfShared();
  68969. font->horizontalScale = scaleFactor;
  68970. }
  68971. void Font::setExtraKerningFactor (const float extraKerning) throw()
  68972. {
  68973. dupeInternalIfShared();
  68974. font->kerning = extraKerning;
  68975. }
  68976. void Font::setBold (const bool shouldBeBold) throw()
  68977. {
  68978. setStyleFlags (shouldBeBold ? (font->styleFlags | bold)
  68979. : (font->styleFlags & ~bold));
  68980. }
  68981. bool Font::isBold() const throw()
  68982. {
  68983. return (font->styleFlags & bold) != 0;
  68984. }
  68985. void Font::setItalic (const bool shouldBeItalic) throw()
  68986. {
  68987. setStyleFlags (shouldBeItalic ? (font->styleFlags | italic)
  68988. : (font->styleFlags & ~italic));
  68989. }
  68990. bool Font::isItalic() const throw()
  68991. {
  68992. return (font->styleFlags & italic) != 0;
  68993. }
  68994. void Font::setUnderline (const bool shouldBeUnderlined) throw()
  68995. {
  68996. setStyleFlags (shouldBeUnderlined ? (font->styleFlags | underlined)
  68997. : (font->styleFlags & ~underlined));
  68998. }
  68999. bool Font::isUnderlined() const throw()
  69000. {
  69001. return (font->styleFlags & underlined) != 0;
  69002. }
  69003. float Font::getAscent() const throw()
  69004. {
  69005. if (font->ascent == 0)
  69006. font->ascent = getTypeface()->getAscent();
  69007. return font->height * font->ascent;
  69008. }
  69009. float Font::getDescent() const throw()
  69010. {
  69011. return font->height - getAscent();
  69012. }
  69013. int Font::getStringWidth (const String& text) const throw()
  69014. {
  69015. return roundToInt (getStringWidthFloat (text));
  69016. }
  69017. float Font::getStringWidthFloat (const String& text) const throw()
  69018. {
  69019. float w = getTypeface()->getStringWidth (text);
  69020. if (font->kerning != 0)
  69021. w += font->kerning * text.length();
  69022. return w * font->height * font->horizontalScale;
  69023. }
  69024. void Font::getGlyphPositions (const String& text, Array <int>& glyphs, Array <float>& xOffsets) const throw()
  69025. {
  69026. getTypeface()->getGlyphPositions (text, glyphs, xOffsets);
  69027. const float scale = font->height * font->horizontalScale;
  69028. const int num = xOffsets.size();
  69029. if (num > 0)
  69030. {
  69031. float* const x = &(xOffsets.getReference(0));
  69032. if (font->kerning != 0)
  69033. {
  69034. for (int i = 0; i < num; ++i)
  69035. x[i] = (x[i] + i * font->kerning) * scale;
  69036. }
  69037. else
  69038. {
  69039. for (int i = 0; i < num; ++i)
  69040. x[i] *= scale;
  69041. }
  69042. }
  69043. }
  69044. void Font::findFonts (Array<Font>& destArray) throw()
  69045. {
  69046. const StringArray names (findAllTypefaceNames());
  69047. for (int i = 0; i < names.size(); ++i)
  69048. destArray.add (Font (names[i], FontValues::defaultFontHeight, Font::plain));
  69049. }
  69050. class TypefaceCache : public DeletedAtShutdown
  69051. {
  69052. public:
  69053. TypefaceCache (int numToCache = 10) throw()
  69054. : counter (1)
  69055. {
  69056. while (--numToCache >= 0)
  69057. faces.add (new CachedFace());
  69058. }
  69059. ~TypefaceCache()
  69060. {
  69061. clearSingletonInstance();
  69062. }
  69063. juce_DeclareSingleton_SingleThreaded_Minimal (TypefaceCache)
  69064. const Typeface::Ptr findTypefaceFor (const Font& font) throw()
  69065. {
  69066. const int flags = font.getStyleFlags() & (Font::bold | Font::italic);
  69067. const String faceName (font.getTypefaceName());
  69068. int i;
  69069. for (i = faces.size(); --i >= 0;)
  69070. {
  69071. CachedFace* const face = faces.getUnchecked(i);
  69072. if (face->flags == flags
  69073. && face->typefaceName == faceName)
  69074. {
  69075. face->lastUsageCount = ++counter;
  69076. return face->typeFace;
  69077. }
  69078. }
  69079. int replaceIndex = 0;
  69080. int bestLastUsageCount = std::numeric_limits<int>::max();
  69081. for (i = faces.size(); --i >= 0;)
  69082. {
  69083. const int lu = faces.getUnchecked(i)->lastUsageCount;
  69084. if (bestLastUsageCount > lu)
  69085. {
  69086. bestLastUsageCount = lu;
  69087. replaceIndex = i;
  69088. }
  69089. }
  69090. CachedFace* const face = faces.getUnchecked (replaceIndex);
  69091. face->typefaceName = faceName;
  69092. face->flags = flags;
  69093. face->lastUsageCount = ++counter;
  69094. face->typeFace = LookAndFeel::getDefaultLookAndFeel().getTypefaceForFont (font);
  69095. jassert (face->typeFace != 0); // the look and feel must return a typeface!
  69096. return face->typeFace;
  69097. }
  69098. juce_UseDebuggingNewOperator
  69099. private:
  69100. struct CachedFace
  69101. {
  69102. CachedFace() throw()
  69103. : lastUsageCount (0), flags (-1)
  69104. {
  69105. }
  69106. String typefaceName;
  69107. int lastUsageCount;
  69108. int flags;
  69109. Typeface::Ptr typeFace;
  69110. };
  69111. int counter;
  69112. OwnedArray <CachedFace> faces;
  69113. TypefaceCache (const TypefaceCache&);
  69114. TypefaceCache& operator= (const TypefaceCache&);
  69115. };
  69116. juce_ImplementSingleton_SingleThreaded (TypefaceCache)
  69117. Typeface* Font::getTypeface() const throw()
  69118. {
  69119. if (font->typeface == 0)
  69120. font->typeface = TypefaceCache::getInstance()->findTypefaceFor (*this);
  69121. return font->typeface;
  69122. }
  69123. END_JUCE_NAMESPACE
  69124. /*** End of inlined file: juce_Font.cpp ***/
  69125. /*** Start of inlined file: juce_GlyphArrangement.cpp ***/
  69126. BEGIN_JUCE_NAMESPACE
  69127. PositionedGlyph::PositionedGlyph (const float x_, const float y_, const float w_, const Font& font_,
  69128. const juce_wchar character_, const int glyph_)
  69129. : x (x_),
  69130. y (y_),
  69131. w (w_),
  69132. font (font_),
  69133. character (character_),
  69134. glyph (glyph_)
  69135. {
  69136. }
  69137. PositionedGlyph::PositionedGlyph (const PositionedGlyph& other)
  69138. : x (other.x),
  69139. y (other.y),
  69140. w (other.w),
  69141. font (other.font),
  69142. character (other.character),
  69143. glyph (other.glyph)
  69144. {
  69145. }
  69146. void PositionedGlyph::draw (const Graphics& g) const
  69147. {
  69148. if (! isWhitespace())
  69149. {
  69150. g.getInternalContext()->setFont (font);
  69151. g.getInternalContext()->drawGlyph (glyph, AffineTransform::translation (x, y));
  69152. }
  69153. }
  69154. void PositionedGlyph::draw (const Graphics& g,
  69155. const AffineTransform& transform) const
  69156. {
  69157. if (! isWhitespace())
  69158. {
  69159. g.getInternalContext()->setFont (font);
  69160. g.getInternalContext()->drawGlyph (glyph, AffineTransform::translation (x, y)
  69161. .followedBy (transform));
  69162. }
  69163. }
  69164. void PositionedGlyph::createPath (Path& path) const
  69165. {
  69166. if (! isWhitespace())
  69167. {
  69168. Typeface* const t = font.getTypeface();
  69169. if (t != 0)
  69170. {
  69171. Path p;
  69172. t->getOutlineForGlyph (glyph, p);
  69173. path.addPath (p, AffineTransform::scale (font.getHeight() * font.getHorizontalScale(), font.getHeight())
  69174. .translated (x, y));
  69175. }
  69176. }
  69177. }
  69178. bool PositionedGlyph::hitTest (float px, float py) const
  69179. {
  69180. if (getBounds().contains (px, py) && ! isWhitespace())
  69181. {
  69182. Typeface* const t = font.getTypeface();
  69183. if (t != 0)
  69184. {
  69185. Path p;
  69186. t->getOutlineForGlyph (glyph, p);
  69187. AffineTransform::translation (-x, -y)
  69188. .scaled (1.0f / (font.getHeight() * font.getHorizontalScale()), 1.0f / font.getHeight())
  69189. .transformPoint (px, py);
  69190. return p.contains (px, py);
  69191. }
  69192. }
  69193. return false;
  69194. }
  69195. void PositionedGlyph::moveBy (const float deltaX,
  69196. const float deltaY)
  69197. {
  69198. x += deltaX;
  69199. y += deltaY;
  69200. }
  69201. GlyphArrangement::GlyphArrangement()
  69202. {
  69203. glyphs.ensureStorageAllocated (128);
  69204. }
  69205. GlyphArrangement::GlyphArrangement (const GlyphArrangement& other)
  69206. {
  69207. addGlyphArrangement (other);
  69208. }
  69209. GlyphArrangement& GlyphArrangement::operator= (const GlyphArrangement& other)
  69210. {
  69211. if (this != &other)
  69212. {
  69213. clear();
  69214. addGlyphArrangement (other);
  69215. }
  69216. return *this;
  69217. }
  69218. GlyphArrangement::~GlyphArrangement()
  69219. {
  69220. }
  69221. void GlyphArrangement::clear()
  69222. {
  69223. glyphs.clear();
  69224. }
  69225. PositionedGlyph& GlyphArrangement::getGlyph (const int index) const
  69226. {
  69227. jassert (((unsigned int) index) < (unsigned int) glyphs.size());
  69228. return *glyphs [index];
  69229. }
  69230. void GlyphArrangement::addGlyphArrangement (const GlyphArrangement& other)
  69231. {
  69232. glyphs.ensureStorageAllocated (glyphs.size() + other.glyphs.size());
  69233. for (int i = 0; i < other.glyphs.size(); ++i)
  69234. glyphs.add (new PositionedGlyph (*other.glyphs.getUnchecked (i)));
  69235. }
  69236. void GlyphArrangement::removeRangeOfGlyphs (int startIndex, const int num)
  69237. {
  69238. glyphs.removeRange (startIndex, num < 0 ? glyphs.size() : num);
  69239. }
  69240. void GlyphArrangement::addLineOfText (const Font& font,
  69241. const String& text,
  69242. const float xOffset,
  69243. const float yOffset)
  69244. {
  69245. addCurtailedLineOfText (font, text,
  69246. xOffset, yOffset,
  69247. 1.0e10f, false);
  69248. }
  69249. void GlyphArrangement::addCurtailedLineOfText (const Font& font,
  69250. const String& text,
  69251. float xOffset,
  69252. const float yOffset,
  69253. const float maxWidthPixels,
  69254. const bool useEllipsis)
  69255. {
  69256. if (text.isNotEmpty())
  69257. {
  69258. Array <int> newGlyphs;
  69259. Array <float> xOffsets;
  69260. font.getGlyphPositions (text, newGlyphs, xOffsets);
  69261. const int textLen = newGlyphs.size();
  69262. const juce_wchar* const unicodeText = text;
  69263. for (int i = 0; i < textLen; ++i)
  69264. {
  69265. const float thisX = xOffsets.getUnchecked (i);
  69266. const float nextX = xOffsets.getUnchecked (i + 1);
  69267. if (nextX > maxWidthPixels + 1.0f)
  69268. {
  69269. // curtail the string if it's too wide..
  69270. if (useEllipsis && textLen > 3 && glyphs.size() >= 3)
  69271. insertEllipsis (font, xOffset + maxWidthPixels, 0, glyphs.size());
  69272. break;
  69273. }
  69274. else
  69275. {
  69276. glyphs.add (new PositionedGlyph (xOffset + thisX, yOffset, nextX - thisX,
  69277. font, unicodeText[i], newGlyphs.getUnchecked(i)));
  69278. }
  69279. }
  69280. }
  69281. }
  69282. int GlyphArrangement::insertEllipsis (const Font& font, const float maxXPos,
  69283. const int startIndex, int endIndex)
  69284. {
  69285. int numDeleted = 0;
  69286. if (glyphs.size() > 0)
  69287. {
  69288. Array<int> dotGlyphs;
  69289. Array<float> dotXs;
  69290. font.getGlyphPositions ("..", dotGlyphs, dotXs);
  69291. const float dx = dotXs[1];
  69292. float xOffset = 0.0f, yOffset = 0.0f;
  69293. while (endIndex > startIndex)
  69294. {
  69295. const PositionedGlyph* pg = glyphs.getUnchecked (--endIndex);
  69296. xOffset = pg->x;
  69297. yOffset = pg->y;
  69298. glyphs.remove (endIndex);
  69299. ++numDeleted;
  69300. if (xOffset + dx * 3 <= maxXPos)
  69301. break;
  69302. }
  69303. for (int i = 3; --i >= 0;)
  69304. {
  69305. glyphs.insert (endIndex++, new PositionedGlyph (xOffset, yOffset, dx,
  69306. font, '.', dotGlyphs.getFirst()));
  69307. --numDeleted;
  69308. xOffset += dx;
  69309. if (xOffset > maxXPos)
  69310. break;
  69311. }
  69312. }
  69313. return numDeleted;
  69314. }
  69315. void GlyphArrangement::addJustifiedText (const Font& font,
  69316. const String& text,
  69317. float x, float y,
  69318. const float maxLineWidth,
  69319. const Justification& horizontalLayout)
  69320. {
  69321. int lineStartIndex = glyphs.size();
  69322. addLineOfText (font, text, x, y);
  69323. const float originalY = y;
  69324. while (lineStartIndex < glyphs.size())
  69325. {
  69326. int i = lineStartIndex;
  69327. if (glyphs.getUnchecked(i)->getCharacter() != '\n'
  69328. && glyphs.getUnchecked(i)->getCharacter() != '\r')
  69329. ++i;
  69330. const float lineMaxX = glyphs.getUnchecked (lineStartIndex)->getLeft() + maxLineWidth;
  69331. int lastWordBreakIndex = -1;
  69332. while (i < glyphs.size())
  69333. {
  69334. const PositionedGlyph* pg = glyphs.getUnchecked (i);
  69335. const juce_wchar c = pg->getCharacter();
  69336. if (c == '\r' || c == '\n')
  69337. {
  69338. ++i;
  69339. if (c == '\r' && i < glyphs.size()
  69340. && glyphs.getUnchecked(i)->getCharacter() == '\n')
  69341. ++i;
  69342. break;
  69343. }
  69344. else if (pg->isWhitespace())
  69345. {
  69346. lastWordBreakIndex = i + 1;
  69347. }
  69348. else if (pg->getRight() - 0.0001f >= lineMaxX)
  69349. {
  69350. if (lastWordBreakIndex >= 0)
  69351. i = lastWordBreakIndex;
  69352. break;
  69353. }
  69354. ++i;
  69355. }
  69356. const float currentLineStartX = glyphs.getUnchecked (lineStartIndex)->getLeft();
  69357. float currentLineEndX = currentLineStartX;
  69358. for (int j = i; --j >= lineStartIndex;)
  69359. {
  69360. if (! glyphs.getUnchecked (j)->isWhitespace())
  69361. {
  69362. currentLineEndX = glyphs.getUnchecked (j)->getRight();
  69363. break;
  69364. }
  69365. }
  69366. float deltaX = 0.0f;
  69367. if (horizontalLayout.testFlags (Justification::horizontallyJustified))
  69368. spreadOutLine (lineStartIndex, i - lineStartIndex, maxLineWidth);
  69369. else if (horizontalLayout.testFlags (Justification::horizontallyCentred))
  69370. deltaX = (maxLineWidth - (currentLineEndX - currentLineStartX)) * 0.5f;
  69371. else if (horizontalLayout.testFlags (Justification::right))
  69372. deltaX = maxLineWidth - (currentLineEndX - currentLineStartX);
  69373. moveRangeOfGlyphs (lineStartIndex, i - lineStartIndex,
  69374. x + deltaX - currentLineStartX, y - originalY);
  69375. lineStartIndex = i;
  69376. y += font.getHeight();
  69377. }
  69378. }
  69379. void GlyphArrangement::addFittedText (const Font& f,
  69380. const String& text,
  69381. const float x, const float y,
  69382. const float width, const float height,
  69383. const Justification& layout,
  69384. int maximumLines,
  69385. const float minimumHorizontalScale)
  69386. {
  69387. // doesn't make much sense if this is outside a sensible range of 0.5 to 1.0
  69388. jassert (minimumHorizontalScale > 0 && minimumHorizontalScale <= 1.0f);
  69389. if (text.containsAnyOf ("\r\n"))
  69390. {
  69391. GlyphArrangement ga;
  69392. ga.addJustifiedText (f, text, x, y, width, layout);
  69393. const Rectangle<float> bb (ga.getBoundingBox (0, -1, false));
  69394. float dy = y - bb.getY();
  69395. if (layout.testFlags (Justification::verticallyCentred))
  69396. dy += (height - bb.getHeight()) * 0.5f;
  69397. else if (layout.testFlags (Justification::bottom))
  69398. dy += height - bb.getHeight();
  69399. ga.moveRangeOfGlyphs (0, -1, 0.0f, dy);
  69400. glyphs.ensureStorageAllocated (glyphs.size() + ga.glyphs.size());
  69401. for (int i = 0; i < ga.glyphs.size(); ++i)
  69402. glyphs.add (ga.glyphs.getUnchecked (i));
  69403. ga.glyphs.clear (false);
  69404. return;
  69405. }
  69406. int startIndex = glyphs.size();
  69407. addLineOfText (f, text.trim(), x, y);
  69408. if (glyphs.size() > startIndex)
  69409. {
  69410. float lineWidth = glyphs.getUnchecked (glyphs.size() - 1)->getRight()
  69411. - glyphs.getUnchecked (startIndex)->getLeft();
  69412. if (lineWidth <= 0)
  69413. return;
  69414. if (lineWidth * minimumHorizontalScale < width)
  69415. {
  69416. if (lineWidth > width)
  69417. stretchRangeOfGlyphs (startIndex, glyphs.size() - startIndex,
  69418. width / lineWidth);
  69419. justifyGlyphs (startIndex, glyphs.size() - startIndex,
  69420. x, y, width, height, layout);
  69421. }
  69422. else if (maximumLines <= 1)
  69423. {
  69424. fitLineIntoSpace (startIndex, glyphs.size() - startIndex,
  69425. x, y, width, height, f, layout, minimumHorizontalScale);
  69426. }
  69427. else
  69428. {
  69429. Font font (f);
  69430. String txt (text.trim());
  69431. const int length = txt.length();
  69432. const int originalStartIndex = startIndex;
  69433. int numLines = 1;
  69434. if (length <= 12 && ! txt.containsAnyOf (" -\t\r\n"))
  69435. maximumLines = 1;
  69436. maximumLines = jmin (maximumLines, length);
  69437. while (numLines < maximumLines)
  69438. {
  69439. ++numLines;
  69440. const float newFontHeight = height / (float) numLines;
  69441. if (newFontHeight < font.getHeight())
  69442. {
  69443. font.setHeight (jmax (8.0f, newFontHeight));
  69444. removeRangeOfGlyphs (startIndex, -1);
  69445. addLineOfText (font, txt, x, y);
  69446. lineWidth = glyphs.getUnchecked (glyphs.size() - 1)->getRight()
  69447. - glyphs.getUnchecked (startIndex)->getLeft();
  69448. }
  69449. if (numLines > lineWidth / width || newFontHeight < 8.0f)
  69450. break;
  69451. }
  69452. if (numLines < 1)
  69453. numLines = 1;
  69454. float lineY = y;
  69455. float widthPerLine = lineWidth / numLines;
  69456. int lastLineStartIndex = 0;
  69457. for (int line = 0; line < numLines; ++line)
  69458. {
  69459. int i = startIndex;
  69460. lastLineStartIndex = i;
  69461. float lineStartX = glyphs.getUnchecked (startIndex)->getLeft();
  69462. if (line == numLines - 1)
  69463. {
  69464. widthPerLine = width;
  69465. i = glyphs.size();
  69466. }
  69467. else
  69468. {
  69469. while (i < glyphs.size())
  69470. {
  69471. lineWidth = (glyphs.getUnchecked (i)->getRight() - lineStartX);
  69472. if (lineWidth > widthPerLine)
  69473. {
  69474. // got to a point where the line's too long, so skip forward to find a
  69475. // good place to break it..
  69476. const int searchStartIndex = i;
  69477. while (i < glyphs.size())
  69478. {
  69479. if ((glyphs.getUnchecked (i)->getRight() - lineStartX) * minimumHorizontalScale < width)
  69480. {
  69481. if (glyphs.getUnchecked (i)->isWhitespace()
  69482. || glyphs.getUnchecked (i)->getCharacter() == '-')
  69483. {
  69484. ++i;
  69485. break;
  69486. }
  69487. }
  69488. else
  69489. {
  69490. // can't find a suitable break, so try looking backwards..
  69491. i = searchStartIndex;
  69492. for (int back = 1; back < jmin (5, i - startIndex - 1); ++back)
  69493. {
  69494. if (glyphs.getUnchecked (i - back)->isWhitespace()
  69495. || glyphs.getUnchecked (i - back)->getCharacter() == '-')
  69496. {
  69497. i -= back - 1;
  69498. break;
  69499. }
  69500. }
  69501. break;
  69502. }
  69503. ++i;
  69504. }
  69505. break;
  69506. }
  69507. ++i;
  69508. }
  69509. int wsStart = i;
  69510. while (wsStart > 0 && glyphs.getUnchecked (wsStart - 1)->isWhitespace())
  69511. --wsStart;
  69512. int wsEnd = i;
  69513. while (wsEnd < glyphs.size() && glyphs.getUnchecked (wsEnd)->isWhitespace())
  69514. ++wsEnd;
  69515. removeRangeOfGlyphs (wsStart, wsEnd - wsStart);
  69516. i = jmax (wsStart, startIndex + 1);
  69517. }
  69518. i -= fitLineIntoSpace (startIndex, i - startIndex,
  69519. x, lineY, width, font.getHeight(), font,
  69520. layout.getOnlyHorizontalFlags() | Justification::verticallyCentred,
  69521. minimumHorizontalScale);
  69522. startIndex = i;
  69523. lineY += font.getHeight();
  69524. if (startIndex >= glyphs.size())
  69525. break;
  69526. }
  69527. justifyGlyphs (originalStartIndex, glyphs.size() - originalStartIndex,
  69528. x, y, width, height, layout.getFlags() & ~Justification::horizontallyJustified);
  69529. }
  69530. }
  69531. }
  69532. void GlyphArrangement::moveRangeOfGlyphs (int startIndex, int num,
  69533. const float dx, const float dy)
  69534. {
  69535. jassert (startIndex >= 0);
  69536. if (dx != 0.0f || dy != 0.0f)
  69537. {
  69538. if (num < 0 || startIndex + num > glyphs.size())
  69539. num = glyphs.size() - startIndex;
  69540. while (--num >= 0)
  69541. glyphs.getUnchecked (startIndex++)->moveBy (dx, dy);
  69542. }
  69543. }
  69544. int GlyphArrangement::fitLineIntoSpace (int start, int numGlyphs, float x, float y, float w, float h, const Font& font,
  69545. const Justification& justification, float minimumHorizontalScale)
  69546. {
  69547. int numDeleted = 0;
  69548. const float lineStartX = glyphs.getUnchecked (start)->getLeft();
  69549. float lineWidth = glyphs.getUnchecked (start + numGlyphs - 1)->getRight() - lineStartX;
  69550. if (lineWidth > w)
  69551. {
  69552. if (minimumHorizontalScale < 1.0f)
  69553. {
  69554. stretchRangeOfGlyphs (start, numGlyphs, jmax (minimumHorizontalScale, w / lineWidth));
  69555. lineWidth = glyphs.getUnchecked (start + numGlyphs - 1)->getRight() - lineStartX - 0.5f;
  69556. }
  69557. if (lineWidth > w)
  69558. {
  69559. numDeleted = insertEllipsis (font, lineStartX + w, start, start + numGlyphs);
  69560. numGlyphs -= numDeleted;
  69561. }
  69562. }
  69563. justifyGlyphs (start, numGlyphs, x, y, w, h, justification);
  69564. return numDeleted;
  69565. }
  69566. void GlyphArrangement::stretchRangeOfGlyphs (int startIndex, int num,
  69567. const float horizontalScaleFactor)
  69568. {
  69569. jassert (startIndex >= 0);
  69570. if (num < 0 || startIndex + num > glyphs.size())
  69571. num = glyphs.size() - startIndex;
  69572. if (num > 0)
  69573. {
  69574. const float xAnchor = glyphs.getUnchecked (startIndex)->getLeft();
  69575. while (--num >= 0)
  69576. {
  69577. PositionedGlyph* const pg = glyphs.getUnchecked (startIndex++);
  69578. pg->x = xAnchor + (pg->x - xAnchor) * horizontalScaleFactor;
  69579. pg->font.setHorizontalScale (pg->font.getHorizontalScale() * horizontalScaleFactor);
  69580. pg->w *= horizontalScaleFactor;
  69581. }
  69582. }
  69583. }
  69584. const Rectangle<float> GlyphArrangement::getBoundingBox (int startIndex, int num, const bool includeWhitespace) const
  69585. {
  69586. jassert (startIndex >= 0);
  69587. if (num < 0 || startIndex + num > glyphs.size())
  69588. num = glyphs.size() - startIndex;
  69589. Rectangle<float> result;
  69590. bool isFirst = true;
  69591. while (--num >= 0)
  69592. {
  69593. const PositionedGlyph* const pg = glyphs.getUnchecked (startIndex++);
  69594. if (includeWhitespace || ! pg->isWhitespace())
  69595. {
  69596. if (isFirst)
  69597. {
  69598. isFirst = false;
  69599. result = pg->getBounds();
  69600. }
  69601. else
  69602. {
  69603. result = result.getUnion (pg->getBounds());
  69604. }
  69605. }
  69606. }
  69607. return result;
  69608. }
  69609. void GlyphArrangement::justifyGlyphs (const int startIndex, const int num,
  69610. const float x, const float y, const float width, const float height,
  69611. const Justification& justification)
  69612. {
  69613. jassert (num >= 0 && startIndex >= 0);
  69614. if (glyphs.size() > 0 && num > 0)
  69615. {
  69616. const Rectangle<float> bb (getBoundingBox (startIndex, num, ! justification.testFlags (Justification::horizontallyJustified
  69617. | Justification::horizontallyCentred)));
  69618. float deltaX = 0.0f;
  69619. if (justification.testFlags (Justification::horizontallyJustified))
  69620. deltaX = x - bb.getX();
  69621. else if (justification.testFlags (Justification::horizontallyCentred))
  69622. deltaX = x + (width - bb.getWidth()) * 0.5f - bb.getX();
  69623. else if (justification.testFlags (Justification::right))
  69624. deltaX = (x + width) - bb.getRight();
  69625. else
  69626. deltaX = x - bb.getX();
  69627. float deltaY = 0.0f;
  69628. if (justification.testFlags (Justification::top))
  69629. deltaY = y - bb.getY();
  69630. else if (justification.testFlags (Justification::bottom))
  69631. deltaY = (y + height) - bb.getBottom();
  69632. else
  69633. deltaY = y + (height - bb.getHeight()) * 0.5f - bb.getY();
  69634. moveRangeOfGlyphs (startIndex, num, deltaX, deltaY);
  69635. if (justification.testFlags (Justification::horizontallyJustified))
  69636. {
  69637. int lineStart = 0;
  69638. float baseY = glyphs.getUnchecked (startIndex)->getBaselineY();
  69639. int i;
  69640. for (i = 0; i < num; ++i)
  69641. {
  69642. const float glyphY = glyphs.getUnchecked (startIndex + i)->getBaselineY();
  69643. if (glyphY != baseY)
  69644. {
  69645. spreadOutLine (startIndex + lineStart, i - lineStart, width);
  69646. lineStart = i;
  69647. baseY = glyphY;
  69648. }
  69649. }
  69650. if (i > lineStart)
  69651. spreadOutLine (startIndex + lineStart, i - lineStart, width);
  69652. }
  69653. }
  69654. }
  69655. void GlyphArrangement::spreadOutLine (const int start, const int num, const float targetWidth)
  69656. {
  69657. if (start + num < glyphs.size()
  69658. && glyphs.getUnchecked (start + num - 1)->getCharacter() != '\r'
  69659. && glyphs.getUnchecked (start + num - 1)->getCharacter() != '\n')
  69660. {
  69661. int numSpaces = 0;
  69662. int spacesAtEnd = 0;
  69663. for (int i = 0; i < num; ++i)
  69664. {
  69665. if (glyphs.getUnchecked (start + i)->isWhitespace())
  69666. {
  69667. ++spacesAtEnd;
  69668. ++numSpaces;
  69669. }
  69670. else
  69671. {
  69672. spacesAtEnd = 0;
  69673. }
  69674. }
  69675. numSpaces -= spacesAtEnd;
  69676. if (numSpaces > 0)
  69677. {
  69678. const float startX = glyphs.getUnchecked (start)->getLeft();
  69679. const float endX = glyphs.getUnchecked (start + num - 1 - spacesAtEnd)->getRight();
  69680. const float extraPaddingBetweenWords
  69681. = (targetWidth - (endX - startX)) / (float) numSpaces;
  69682. float deltaX = 0.0f;
  69683. for (int i = 0; i < num; ++i)
  69684. {
  69685. glyphs.getUnchecked (start + i)->moveBy (deltaX, 0.0f);
  69686. if (glyphs.getUnchecked (start + i)->isWhitespace())
  69687. deltaX += extraPaddingBetweenWords;
  69688. }
  69689. }
  69690. }
  69691. }
  69692. void GlyphArrangement::draw (const Graphics& g) const
  69693. {
  69694. for (int i = 0; i < glyphs.size(); ++i)
  69695. {
  69696. const PositionedGlyph* const pg = glyphs.getUnchecked(i);
  69697. if (pg->font.isUnderlined())
  69698. {
  69699. const float lineThickness = (pg->font.getDescent()) * 0.3f;
  69700. float nextX = pg->x + pg->w;
  69701. if (i < glyphs.size() - 1 && glyphs.getUnchecked (i + 1)->y == pg->y)
  69702. nextX = glyphs.getUnchecked (i + 1)->x;
  69703. g.fillRect (pg->x, pg->y + lineThickness * 2.0f,
  69704. nextX - pg->x, lineThickness);
  69705. }
  69706. pg->draw (g);
  69707. }
  69708. }
  69709. void GlyphArrangement::draw (const Graphics& g, const AffineTransform& transform) const
  69710. {
  69711. for (int i = 0; i < glyphs.size(); ++i)
  69712. {
  69713. const PositionedGlyph* const pg = glyphs.getUnchecked(i);
  69714. if (pg->font.isUnderlined())
  69715. {
  69716. const float lineThickness = (pg->font.getDescent()) * 0.3f;
  69717. float nextX = pg->x + pg->w;
  69718. if (i < glyphs.size() - 1 && glyphs.getUnchecked (i + 1)->y == pg->y)
  69719. nextX = glyphs.getUnchecked (i + 1)->x;
  69720. Path p;
  69721. p.addLineSegment (pg->x, pg->y + lineThickness * 2.0f,
  69722. nextX, pg->y + lineThickness * 2.0f,
  69723. lineThickness);
  69724. g.fillPath (p, transform);
  69725. }
  69726. pg->draw (g, transform);
  69727. }
  69728. }
  69729. void GlyphArrangement::createPath (Path& path) const
  69730. {
  69731. for (int i = 0; i < glyphs.size(); ++i)
  69732. glyphs.getUnchecked (i)->createPath (path);
  69733. }
  69734. int GlyphArrangement::findGlyphIndexAt (float x, float y) const
  69735. {
  69736. for (int i = 0; i < glyphs.size(); ++i)
  69737. if (glyphs.getUnchecked (i)->hitTest (x, y))
  69738. return i;
  69739. return -1;
  69740. }
  69741. END_JUCE_NAMESPACE
  69742. /*** End of inlined file: juce_GlyphArrangement.cpp ***/
  69743. /*** Start of inlined file: juce_TextLayout.cpp ***/
  69744. BEGIN_JUCE_NAMESPACE
  69745. class TextLayout::Token
  69746. {
  69747. public:
  69748. String text;
  69749. Font font;
  69750. int x, y, w, h;
  69751. int line, lineHeight;
  69752. bool isWhitespace, isNewLine;
  69753. Token (const String& t,
  69754. const Font& f,
  69755. const bool isWhitespace_)
  69756. : text (t),
  69757. font (f),
  69758. x(0),
  69759. y(0),
  69760. isWhitespace (isWhitespace_)
  69761. {
  69762. w = font.getStringWidth (t);
  69763. h = roundToInt (f.getHeight());
  69764. isNewLine = t.containsChar ('\n') || t.containsChar ('\r');
  69765. }
  69766. Token (const Token& other)
  69767. : text (other.text),
  69768. font (other.font),
  69769. x (other.x),
  69770. y (other.y),
  69771. w (other.w),
  69772. h (other.h),
  69773. line (other.line),
  69774. lineHeight (other.lineHeight),
  69775. isWhitespace (other.isWhitespace),
  69776. isNewLine (other.isNewLine)
  69777. {
  69778. }
  69779. ~Token()
  69780. {
  69781. }
  69782. void draw (Graphics& g,
  69783. const int xOffset,
  69784. const int yOffset)
  69785. {
  69786. if (! isWhitespace)
  69787. {
  69788. g.setFont (font);
  69789. g.drawSingleLineText (text.trimEnd(),
  69790. xOffset + x,
  69791. yOffset + y + (lineHeight - h)
  69792. + roundToInt (font.getAscent()));
  69793. }
  69794. }
  69795. juce_UseDebuggingNewOperator
  69796. };
  69797. TextLayout::TextLayout()
  69798. : totalLines (0)
  69799. {
  69800. tokens.ensureStorageAllocated (64);
  69801. }
  69802. TextLayout::TextLayout (const String& text, const Font& font)
  69803. : totalLines (0)
  69804. {
  69805. tokens.ensureStorageAllocated (64);
  69806. appendText (text, font);
  69807. }
  69808. TextLayout::TextLayout (const TextLayout& other)
  69809. : totalLines (0)
  69810. {
  69811. *this = other;
  69812. }
  69813. TextLayout& TextLayout::operator= (const TextLayout& other)
  69814. {
  69815. if (this != &other)
  69816. {
  69817. clear();
  69818. totalLines = other.totalLines;
  69819. for (int i = 0; i < other.tokens.size(); ++i)
  69820. tokens.add (new Token (*other.tokens.getUnchecked(i)));
  69821. }
  69822. return *this;
  69823. }
  69824. TextLayout::~TextLayout()
  69825. {
  69826. clear();
  69827. }
  69828. void TextLayout::clear()
  69829. {
  69830. tokens.clear();
  69831. totalLines = 0;
  69832. }
  69833. void TextLayout::appendText (const String& text, const Font& font)
  69834. {
  69835. const juce_wchar* t = text;
  69836. String currentString;
  69837. int lastCharType = 0;
  69838. for (;;)
  69839. {
  69840. const juce_wchar c = *t++;
  69841. if (c == 0)
  69842. break;
  69843. int charType;
  69844. if (c == '\r' || c == '\n')
  69845. {
  69846. charType = 0;
  69847. }
  69848. else if (CharacterFunctions::isWhitespace (c))
  69849. {
  69850. charType = 2;
  69851. }
  69852. else
  69853. {
  69854. charType = 1;
  69855. }
  69856. if (charType == 0 || charType != lastCharType)
  69857. {
  69858. if (currentString.isNotEmpty())
  69859. {
  69860. tokens.add (new Token (currentString, font,
  69861. lastCharType == 2 || lastCharType == 0));
  69862. }
  69863. currentString = String::charToString (c);
  69864. if (c == '\r' && *t == '\n')
  69865. currentString += *t++;
  69866. }
  69867. else
  69868. {
  69869. currentString += c;
  69870. }
  69871. lastCharType = charType;
  69872. }
  69873. if (currentString.isNotEmpty())
  69874. tokens.add (new Token (currentString, font, lastCharType == 2));
  69875. }
  69876. void TextLayout::setText (const String& text, const Font& font)
  69877. {
  69878. clear();
  69879. appendText (text, font);
  69880. }
  69881. void TextLayout::layout (int maxWidth,
  69882. const Justification& justification,
  69883. const bool attemptToBalanceLineLengths)
  69884. {
  69885. if (attemptToBalanceLineLengths)
  69886. {
  69887. const int originalW = maxWidth;
  69888. int bestWidth = maxWidth;
  69889. float bestLineProportion = 0.0f;
  69890. while (maxWidth > originalW / 2)
  69891. {
  69892. layout (maxWidth, justification, false);
  69893. if (getNumLines() <= 1)
  69894. return;
  69895. const int lastLineW = getLineWidth (getNumLines() - 1);
  69896. const int lastButOneLineW = getLineWidth (getNumLines() - 2);
  69897. const float prop = lastLineW / (float) lastButOneLineW;
  69898. if (prop > 0.9f)
  69899. return;
  69900. if (prop > bestLineProportion)
  69901. {
  69902. bestLineProportion = prop;
  69903. bestWidth = maxWidth;
  69904. }
  69905. maxWidth -= 10;
  69906. }
  69907. layout (bestWidth, justification, false);
  69908. }
  69909. else
  69910. {
  69911. int x = 0;
  69912. int y = 0;
  69913. int h = 0;
  69914. totalLines = 0;
  69915. int i;
  69916. for (i = 0; i < tokens.size(); ++i)
  69917. {
  69918. Token* const t = tokens.getUnchecked(i);
  69919. t->x = x;
  69920. t->y = y;
  69921. t->line = totalLines;
  69922. x += t->w;
  69923. h = jmax (h, t->h);
  69924. const Token* nextTok = tokens [i + 1];
  69925. if (nextTok == 0)
  69926. break;
  69927. if (t->isNewLine || ((! nextTok->isWhitespace) && x + nextTok->w > maxWidth))
  69928. {
  69929. // finished a line, so go back and update the heights of the things on it
  69930. for (int j = i; j >= 0; --j)
  69931. {
  69932. Token* const tok = tokens.getUnchecked(j);
  69933. if (tok->line == totalLines)
  69934. tok->lineHeight = h;
  69935. else
  69936. break;
  69937. }
  69938. x = 0;
  69939. y += h;
  69940. h = 0;
  69941. ++totalLines;
  69942. }
  69943. }
  69944. // finished a line, so go back and update the heights of the things on it
  69945. for (int j = jmin (i, tokens.size() - 1); j >= 0; --j)
  69946. {
  69947. Token* const t = tokens.getUnchecked(j);
  69948. if (t->line == totalLines)
  69949. t->lineHeight = h;
  69950. else
  69951. break;
  69952. }
  69953. ++totalLines;
  69954. if (! justification.testFlags (Justification::left))
  69955. {
  69956. int totalW = getWidth();
  69957. for (i = totalLines; --i >= 0;)
  69958. {
  69959. const int lineW = getLineWidth (i);
  69960. int dx = 0;
  69961. if (justification.testFlags (Justification::horizontallyCentred))
  69962. dx = (totalW - lineW) / 2;
  69963. else if (justification.testFlags (Justification::right))
  69964. dx = totalW - lineW;
  69965. for (int j = tokens.size(); --j >= 0;)
  69966. {
  69967. Token* const t = tokens.getUnchecked(j);
  69968. if (t->line == i)
  69969. t->x += dx;
  69970. }
  69971. }
  69972. }
  69973. }
  69974. }
  69975. int TextLayout::getLineWidth (const int lineNumber) const
  69976. {
  69977. int maxW = 0;
  69978. for (int i = tokens.size(); --i >= 0;)
  69979. {
  69980. const Token* const t = tokens.getUnchecked(i);
  69981. if (t->line == lineNumber && ! t->isWhitespace)
  69982. maxW = jmax (maxW, t->x + t->w);
  69983. }
  69984. return maxW;
  69985. }
  69986. int TextLayout::getWidth() const
  69987. {
  69988. int maxW = 0;
  69989. for (int i = tokens.size(); --i >= 0;)
  69990. {
  69991. const Token* const t = tokens.getUnchecked(i);
  69992. if (! t->isWhitespace)
  69993. maxW = jmax (maxW, t->x + t->w);
  69994. }
  69995. return maxW;
  69996. }
  69997. int TextLayout::getHeight() const
  69998. {
  69999. int maxH = 0;
  70000. for (int i = tokens.size(); --i >= 0;)
  70001. {
  70002. const Token* const t = tokens.getUnchecked(i);
  70003. if (! t->isWhitespace)
  70004. maxH = jmax (maxH, t->y + t->h);
  70005. }
  70006. return maxH;
  70007. }
  70008. void TextLayout::draw (Graphics& g,
  70009. const int xOffset,
  70010. const int yOffset) const
  70011. {
  70012. for (int i = tokens.size(); --i >= 0;)
  70013. tokens.getUnchecked(i)->draw (g, xOffset, yOffset);
  70014. }
  70015. void TextLayout::drawWithin (Graphics& g,
  70016. int x, int y, int w, int h,
  70017. const Justification& justification) const
  70018. {
  70019. justification.applyToRectangle (x, y, getWidth(), getHeight(),
  70020. x, y, w, h);
  70021. draw (g, x, y);
  70022. }
  70023. END_JUCE_NAMESPACE
  70024. /*** End of inlined file: juce_TextLayout.cpp ***/
  70025. /*** Start of inlined file: juce_Typeface.cpp ***/
  70026. BEGIN_JUCE_NAMESPACE
  70027. Typeface::Typeface (const String& name_) throw()
  70028. : name (name_)
  70029. {
  70030. }
  70031. Typeface::~Typeface()
  70032. {
  70033. }
  70034. class CustomTypeface::GlyphInfo
  70035. {
  70036. public:
  70037. GlyphInfo (const juce_wchar character_, const Path& path_, const float width_) throw()
  70038. : character (character_), path (path_), width (width_)
  70039. {
  70040. }
  70041. ~GlyphInfo() throw()
  70042. {
  70043. }
  70044. struct KerningPair
  70045. {
  70046. juce_wchar character2;
  70047. float kerningAmount;
  70048. };
  70049. void addKerningPair (const juce_wchar subsequentCharacter,
  70050. const float extraKerningAmount) throw()
  70051. {
  70052. KerningPair kp;
  70053. kp.character2 = subsequentCharacter;
  70054. kp.kerningAmount = extraKerningAmount;
  70055. kerningPairs.add (kp);
  70056. }
  70057. float getHorizontalSpacing (const juce_wchar subsequentCharacter) const throw()
  70058. {
  70059. if (subsequentCharacter != 0)
  70060. {
  70061. for (int i = kerningPairs.size(); --i >= 0;)
  70062. if (kerningPairs.getReference(i).character2 == subsequentCharacter)
  70063. return width + kerningPairs.getReference(i).kerningAmount;
  70064. }
  70065. return width;
  70066. }
  70067. const juce_wchar character;
  70068. const Path path;
  70069. float width;
  70070. Array <KerningPair> kerningPairs;
  70071. juce_UseDebuggingNewOperator
  70072. private:
  70073. GlyphInfo (const GlyphInfo&);
  70074. GlyphInfo& operator= (const GlyphInfo&);
  70075. };
  70076. CustomTypeface::CustomTypeface()
  70077. : Typeface (String::empty)
  70078. {
  70079. clear();
  70080. }
  70081. CustomTypeface::CustomTypeface (InputStream& serialisedTypefaceStream)
  70082. : Typeface (String::empty)
  70083. {
  70084. clear();
  70085. GZIPDecompressorInputStream gzin (&serialisedTypefaceStream, false);
  70086. BufferedInputStream in (&gzin, 32768, false);
  70087. name = in.readString();
  70088. isBold = in.readBool();
  70089. isItalic = in.readBool();
  70090. ascent = in.readFloat();
  70091. defaultCharacter = (juce_wchar) in.readShort();
  70092. int i, numChars = in.readInt();
  70093. for (i = 0; i < numChars; ++i)
  70094. {
  70095. const juce_wchar c = (juce_wchar) in.readShort();
  70096. const float width = in.readFloat();
  70097. Path p;
  70098. p.loadPathFromStream (in);
  70099. addGlyph (c, p, width);
  70100. }
  70101. const int numKerningPairs = in.readInt();
  70102. for (i = 0; i < numKerningPairs; ++i)
  70103. {
  70104. const juce_wchar char1 = (juce_wchar) in.readShort();
  70105. const juce_wchar char2 = (juce_wchar) in.readShort();
  70106. addKerningPair (char1, char2, in.readFloat());
  70107. }
  70108. }
  70109. CustomTypeface::~CustomTypeface()
  70110. {
  70111. }
  70112. void CustomTypeface::clear()
  70113. {
  70114. defaultCharacter = 0;
  70115. ascent = 1.0f;
  70116. isBold = isItalic = false;
  70117. zeromem (lookupTable, sizeof (lookupTable));
  70118. glyphs.clear();
  70119. }
  70120. void CustomTypeface::setCharacteristics (const String& name_, const float ascent_, const bool isBold_,
  70121. const bool isItalic_, const juce_wchar defaultCharacter_) throw()
  70122. {
  70123. name = name_;
  70124. defaultCharacter = defaultCharacter_;
  70125. ascent = ascent_;
  70126. isBold = isBold_;
  70127. isItalic = isItalic_;
  70128. }
  70129. void CustomTypeface::addGlyph (const juce_wchar character, const Path& path, const float width) throw()
  70130. {
  70131. // Check that you're not trying to add the same character twice..
  70132. jassert (findGlyph (character, false) == 0);
  70133. if (((unsigned int) character) < (unsigned int) numElementsInArray (lookupTable))
  70134. lookupTable [character] = (short) glyphs.size();
  70135. glyphs.add (new GlyphInfo (character, path, width));
  70136. }
  70137. void CustomTypeface::addKerningPair (const juce_wchar char1, const juce_wchar char2, const float extraAmount) throw()
  70138. {
  70139. if (extraAmount != 0)
  70140. {
  70141. GlyphInfo* const g = findGlyph (char1, true);
  70142. jassert (g != 0); // can only add kerning pairs for characters that exist!
  70143. if (g != 0)
  70144. g->addKerningPair (char2, extraAmount);
  70145. }
  70146. }
  70147. CustomTypeface::GlyphInfo* CustomTypeface::findGlyph (const juce_wchar character, const bool loadIfNeeded) throw()
  70148. {
  70149. if (((unsigned int) character) < (unsigned int) numElementsInArray (lookupTable) && lookupTable [character] > 0)
  70150. return glyphs [(int) lookupTable [(int) character]];
  70151. for (int i = 0; i < glyphs.size(); ++i)
  70152. {
  70153. GlyphInfo* const g = glyphs.getUnchecked(i);
  70154. if (g->character == character)
  70155. return g;
  70156. }
  70157. if (loadIfNeeded && loadGlyphIfPossible (character))
  70158. return findGlyph (character, false);
  70159. return 0;
  70160. }
  70161. CustomTypeface::GlyphInfo* CustomTypeface::findGlyphSubstituting (const juce_wchar character) throw()
  70162. {
  70163. GlyphInfo* glyph = findGlyph (character, true);
  70164. if (glyph == 0)
  70165. {
  70166. if (CharacterFunctions::isWhitespace (character) && character != L' ')
  70167. glyph = findGlyph (L' ', true);
  70168. if (glyph == 0)
  70169. {
  70170. const Font fallbackFont (Font::getFallbackFontName(), 10, 0);
  70171. Typeface* const fallbackTypeface = fallbackFont.getTypeface();
  70172. if (fallbackTypeface != 0 && fallbackTypeface != this)
  70173. {
  70174. //xxx
  70175. }
  70176. if (glyph == 0)
  70177. glyph = findGlyph (defaultCharacter, true);
  70178. }
  70179. }
  70180. return glyph;
  70181. }
  70182. bool CustomTypeface::loadGlyphIfPossible (const juce_wchar /*characterNeeded*/)
  70183. {
  70184. return false;
  70185. }
  70186. void CustomTypeface::addGlyphsFromOtherTypeface (Typeface& typefaceToCopy, juce_wchar characterStartIndex, int numCharacters) throw()
  70187. {
  70188. setCharacteristics (name, typefaceToCopy.getAscent(), isBold, isItalic, defaultCharacter);
  70189. for (int i = 0; i < numCharacters; ++i)
  70190. {
  70191. const juce_wchar c = (juce_wchar) (characterStartIndex + i);
  70192. Array <int> glyphIndexes;
  70193. Array <float> offsets;
  70194. typefaceToCopy.getGlyphPositions (String::charToString (c), glyphIndexes, offsets);
  70195. const int glyphIndex = glyphIndexes.getFirst();
  70196. if (glyphIndex >= 0 && glyphIndexes.size() > 0)
  70197. {
  70198. const float glyphWidth = offsets[1];
  70199. Path p;
  70200. typefaceToCopy.getOutlineForGlyph (glyphIndex, p);
  70201. addGlyph (c, p, glyphWidth);
  70202. for (int j = glyphs.size() - 1; --j >= 0;)
  70203. {
  70204. const juce_wchar char2 = glyphs.getUnchecked (j)->character;
  70205. glyphIndexes.clearQuick();
  70206. offsets.clearQuick();
  70207. typefaceToCopy.getGlyphPositions (String::charToString (c) + String::charToString (char2), glyphIndexes, offsets);
  70208. if (offsets.size() > 1)
  70209. addKerningPair (c, char2, offsets[1] - glyphWidth);
  70210. }
  70211. }
  70212. }
  70213. }
  70214. bool CustomTypeface::writeToStream (OutputStream& outputStream)
  70215. {
  70216. GZIPCompressorOutputStream out (&outputStream);
  70217. out.writeString (name);
  70218. out.writeBool (isBold);
  70219. out.writeBool (isItalic);
  70220. out.writeFloat (ascent);
  70221. out.writeShort ((short) (unsigned short) defaultCharacter);
  70222. out.writeInt (glyphs.size());
  70223. int i, numKerningPairs = 0;
  70224. for (i = 0; i < glyphs.size(); ++i)
  70225. {
  70226. const GlyphInfo* const g = glyphs.getUnchecked (i);
  70227. out.writeShort ((short) (unsigned short) g->character);
  70228. out.writeFloat (g->width);
  70229. g->path.writePathToStream (out);
  70230. numKerningPairs += g->kerningPairs.size();
  70231. }
  70232. out.writeInt (numKerningPairs);
  70233. for (i = 0; i < glyphs.size(); ++i)
  70234. {
  70235. const GlyphInfo* const g = glyphs.getUnchecked (i);
  70236. for (int j = 0; j < g->kerningPairs.size(); ++j)
  70237. {
  70238. const GlyphInfo::KerningPair& p = g->kerningPairs.getReference (j);
  70239. out.writeShort ((short) (unsigned short) g->character);
  70240. out.writeShort ((short) (unsigned short) p.character2);
  70241. out.writeFloat (p.kerningAmount);
  70242. }
  70243. }
  70244. return true;
  70245. }
  70246. float CustomTypeface::getAscent() const
  70247. {
  70248. return ascent;
  70249. }
  70250. float CustomTypeface::getDescent() const
  70251. {
  70252. return 1.0f - ascent;
  70253. }
  70254. float CustomTypeface::getStringWidth (const String& text)
  70255. {
  70256. float x = 0;
  70257. const juce_wchar* t = text;
  70258. while (*t != 0)
  70259. {
  70260. const GlyphInfo* const glyph = findGlyphSubstituting (*t++);
  70261. if (glyph != 0)
  70262. x += glyph->getHorizontalSpacing (*t);
  70263. }
  70264. return x;
  70265. }
  70266. void CustomTypeface::getGlyphPositions (const String& text, Array <int>& resultGlyphs, Array<float>& xOffsets)
  70267. {
  70268. xOffsets.add (0);
  70269. float x = 0;
  70270. const juce_wchar* t = text;
  70271. while (*t != 0)
  70272. {
  70273. const juce_wchar c = *t++;
  70274. const GlyphInfo* const glyph = findGlyphSubstituting (c);
  70275. if (glyph != 0)
  70276. {
  70277. x += glyph->getHorizontalSpacing (*t);
  70278. resultGlyphs.add ((int) glyph->character);
  70279. xOffsets.add (x);
  70280. }
  70281. }
  70282. }
  70283. bool CustomTypeface::getOutlineForGlyph (int glyphNumber, Path& path)
  70284. {
  70285. const GlyphInfo* const glyph = findGlyphSubstituting ((juce_wchar) glyphNumber);
  70286. if (glyph != 0)
  70287. {
  70288. path = glyph->path;
  70289. return true;
  70290. }
  70291. return false;
  70292. }
  70293. END_JUCE_NAMESPACE
  70294. /*** End of inlined file: juce_Typeface.cpp ***/
  70295. /*** Start of inlined file: juce_AffineTransform.cpp ***/
  70296. BEGIN_JUCE_NAMESPACE
  70297. AffineTransform::AffineTransform() throw()
  70298. : mat00 (1.0f),
  70299. mat01 (0),
  70300. mat02 (0),
  70301. mat10 (0),
  70302. mat11 (1.0f),
  70303. mat12 (0)
  70304. {
  70305. }
  70306. AffineTransform::AffineTransform (const AffineTransform& other) throw()
  70307. : mat00 (other.mat00),
  70308. mat01 (other.mat01),
  70309. mat02 (other.mat02),
  70310. mat10 (other.mat10),
  70311. mat11 (other.mat11),
  70312. mat12 (other.mat12)
  70313. {
  70314. }
  70315. AffineTransform::AffineTransform (const float mat00_,
  70316. const float mat01_,
  70317. const float mat02_,
  70318. const float mat10_,
  70319. const float mat11_,
  70320. const float mat12_) throw()
  70321. : mat00 (mat00_),
  70322. mat01 (mat01_),
  70323. mat02 (mat02_),
  70324. mat10 (mat10_),
  70325. mat11 (mat11_),
  70326. mat12 (mat12_)
  70327. {
  70328. }
  70329. AffineTransform& AffineTransform::operator= (const AffineTransform& other) throw()
  70330. {
  70331. mat00 = other.mat00;
  70332. mat01 = other.mat01;
  70333. mat02 = other.mat02;
  70334. mat10 = other.mat10;
  70335. mat11 = other.mat11;
  70336. mat12 = other.mat12;
  70337. return *this;
  70338. }
  70339. bool AffineTransform::operator== (const AffineTransform& other) const throw()
  70340. {
  70341. return mat00 == other.mat00
  70342. && mat01 == other.mat01
  70343. && mat02 == other.mat02
  70344. && mat10 == other.mat10
  70345. && mat11 == other.mat11
  70346. && mat12 == other.mat12;
  70347. }
  70348. bool AffineTransform::operator!= (const AffineTransform& other) const throw()
  70349. {
  70350. return ! operator== (other);
  70351. }
  70352. bool AffineTransform::isIdentity() const throw()
  70353. {
  70354. return (mat01 == 0)
  70355. && (mat02 == 0)
  70356. && (mat10 == 0)
  70357. && (mat12 == 0)
  70358. && (mat00 == 1.0f)
  70359. && (mat11 == 1.0f);
  70360. }
  70361. const AffineTransform AffineTransform::identity;
  70362. const AffineTransform AffineTransform::followedBy (const AffineTransform& other) const throw()
  70363. {
  70364. return AffineTransform (other.mat00 * mat00 + other.mat01 * mat10,
  70365. other.mat00 * mat01 + other.mat01 * mat11,
  70366. other.mat00 * mat02 + other.mat01 * mat12 + other.mat02,
  70367. other.mat10 * mat00 + other.mat11 * mat10,
  70368. other.mat10 * mat01 + other.mat11 * mat11,
  70369. other.mat10 * mat02 + other.mat11 * mat12 + other.mat12);
  70370. }
  70371. const AffineTransform AffineTransform::followedBy (const float omat00,
  70372. const float omat01,
  70373. const float omat02,
  70374. const float omat10,
  70375. const float omat11,
  70376. const float omat12) const throw()
  70377. {
  70378. return AffineTransform (omat00 * mat00 + omat01 * mat10,
  70379. omat00 * mat01 + omat01 * mat11,
  70380. omat00 * mat02 + omat01 * mat12 + omat02,
  70381. omat10 * mat00 + omat11 * mat10,
  70382. omat10 * mat01 + omat11 * mat11,
  70383. omat10 * mat02 + omat11 * mat12 + omat12);
  70384. }
  70385. const AffineTransform AffineTransform::translated (const float dx,
  70386. const float dy) const throw()
  70387. {
  70388. return AffineTransform (mat00, mat01, mat02 + dx,
  70389. mat10, mat11, mat12 + dy);
  70390. }
  70391. const AffineTransform AffineTransform::translation (const float dx,
  70392. const float dy) throw()
  70393. {
  70394. return AffineTransform (1.0f, 0, dx,
  70395. 0, 1.0f, dy);
  70396. }
  70397. const AffineTransform AffineTransform::rotated (const float rad) const throw()
  70398. {
  70399. const float cosRad = cosf (rad);
  70400. const float sinRad = sinf (rad);
  70401. return followedBy (cosRad, -sinRad, 0,
  70402. sinRad, cosRad, 0);
  70403. }
  70404. const AffineTransform AffineTransform::rotation (const float rad) throw()
  70405. {
  70406. const float cosRad = cosf (rad);
  70407. const float sinRad = sinf (rad);
  70408. return AffineTransform (cosRad, -sinRad, 0,
  70409. sinRad, cosRad, 0);
  70410. }
  70411. const AffineTransform AffineTransform::rotated (const float angle,
  70412. const float pivotX,
  70413. const float pivotY) const throw()
  70414. {
  70415. return translated (-pivotX, -pivotY)
  70416. .rotated (angle)
  70417. .translated (pivotX, pivotY);
  70418. }
  70419. const AffineTransform AffineTransform::rotation (const float angle,
  70420. const float pivotX,
  70421. const float pivotY) throw()
  70422. {
  70423. return translation (-pivotX, -pivotY)
  70424. .rotated (angle)
  70425. .translated (pivotX, pivotY);
  70426. }
  70427. const AffineTransform AffineTransform::scaled (const float factorX,
  70428. const float factorY) const throw()
  70429. {
  70430. return AffineTransform (factorX * mat00, factorX * mat01, factorX * mat02,
  70431. factorY * mat10, factorY * mat11, factorY * mat12);
  70432. }
  70433. const AffineTransform AffineTransform::scale (const float factorX,
  70434. const float factorY) throw()
  70435. {
  70436. return AffineTransform (factorX, 0, 0,
  70437. 0, factorY, 0);
  70438. }
  70439. const AffineTransform AffineTransform::sheared (const float shearX,
  70440. const float shearY) const throw()
  70441. {
  70442. return followedBy (1.0f, shearX, 0,
  70443. shearY, 1.0f, 0);
  70444. }
  70445. const AffineTransform AffineTransform::inverted() const throw()
  70446. {
  70447. double determinant = (mat00 * mat11 - mat10 * mat01);
  70448. if (determinant != 0.0)
  70449. {
  70450. determinant = 1.0 / determinant;
  70451. const float dst00 = (float) (mat11 * determinant);
  70452. const float dst10 = (float) (-mat10 * determinant);
  70453. const float dst01 = (float) (-mat01 * determinant);
  70454. const float dst11 = (float) (mat00 * determinant);
  70455. return AffineTransform (dst00, dst01, -mat02 * dst00 - mat12 * dst01,
  70456. dst10, dst11, -mat02 * dst10 - mat12 * dst11);
  70457. }
  70458. else
  70459. {
  70460. // singularity..
  70461. return *this;
  70462. }
  70463. }
  70464. bool AffineTransform::isSingularity() const throw()
  70465. {
  70466. return (mat00 * mat11 - mat10 * mat01) == 0.0;
  70467. }
  70468. bool AffineTransform::isOnlyTranslation() const throw()
  70469. {
  70470. return (mat01 == 0)
  70471. && (mat10 == 0)
  70472. && (mat00 == 1.0f)
  70473. && (mat11 == 1.0f);
  70474. }
  70475. void AffineTransform::transformPoint (float& x,
  70476. float& y) const throw()
  70477. {
  70478. const float oldX = x;
  70479. x = mat00 * oldX + mat01 * y + mat02;
  70480. y = mat10 * oldX + mat11 * y + mat12;
  70481. }
  70482. void AffineTransform::transformPoint (double& x,
  70483. double& y) const throw()
  70484. {
  70485. const double oldX = x;
  70486. x = mat00 * oldX + mat01 * y + mat02;
  70487. y = mat10 * oldX + mat11 * y + mat12;
  70488. }
  70489. END_JUCE_NAMESPACE
  70490. /*** End of inlined file: juce_AffineTransform.cpp ***/
  70491. /*** Start of inlined file: juce_BorderSize.cpp ***/
  70492. BEGIN_JUCE_NAMESPACE
  70493. BorderSize::BorderSize() throw()
  70494. : top (0),
  70495. left (0),
  70496. bottom (0),
  70497. right (0)
  70498. {
  70499. }
  70500. BorderSize::BorderSize (const BorderSize& other) throw()
  70501. : top (other.top),
  70502. left (other.left),
  70503. bottom (other.bottom),
  70504. right (other.right)
  70505. {
  70506. }
  70507. BorderSize::BorderSize (const int topGap,
  70508. const int leftGap,
  70509. const int bottomGap,
  70510. const int rightGap) throw()
  70511. : top (topGap),
  70512. left (leftGap),
  70513. bottom (bottomGap),
  70514. right (rightGap)
  70515. {
  70516. }
  70517. BorderSize::BorderSize (const int allGaps) throw()
  70518. : top (allGaps),
  70519. left (allGaps),
  70520. bottom (allGaps),
  70521. right (allGaps)
  70522. {
  70523. }
  70524. BorderSize::~BorderSize() throw()
  70525. {
  70526. }
  70527. void BorderSize::setTop (const int newTopGap) throw()
  70528. {
  70529. top = newTopGap;
  70530. }
  70531. void BorderSize::setLeft (const int newLeftGap) throw()
  70532. {
  70533. left = newLeftGap;
  70534. }
  70535. void BorderSize::setBottom (const int newBottomGap) throw()
  70536. {
  70537. bottom = newBottomGap;
  70538. }
  70539. void BorderSize::setRight (const int newRightGap) throw()
  70540. {
  70541. right = newRightGap;
  70542. }
  70543. const Rectangle<int> BorderSize::subtractedFrom (const Rectangle<int>& r) const throw()
  70544. {
  70545. return Rectangle<int> (r.getX() + left,
  70546. r.getY() + top,
  70547. r.getWidth() - (left + right),
  70548. r.getHeight() - (top + bottom));
  70549. }
  70550. void BorderSize::subtractFrom (Rectangle<int>& r) const throw()
  70551. {
  70552. r.setBounds (r.getX() + left,
  70553. r.getY() + top,
  70554. r.getWidth() - (left + right),
  70555. r.getHeight() - (top + bottom));
  70556. }
  70557. const Rectangle<int> BorderSize::addedTo (const Rectangle<int>& r) const throw()
  70558. {
  70559. return Rectangle<int> (r.getX() - left,
  70560. r.getY() - top,
  70561. r.getWidth() + (left + right),
  70562. r.getHeight() + (top + bottom));
  70563. }
  70564. void BorderSize::addTo (Rectangle<int>& r) const throw()
  70565. {
  70566. r.setBounds (r.getX() - left,
  70567. r.getY() - top,
  70568. r.getWidth() + (left + right),
  70569. r.getHeight() + (top + bottom));
  70570. }
  70571. bool BorderSize::operator== (const BorderSize& other) const throw()
  70572. {
  70573. return top == other.top
  70574. && left == other.left
  70575. && bottom == other.bottom
  70576. && right == other.right;
  70577. }
  70578. bool BorderSize::operator!= (const BorderSize& other) const throw()
  70579. {
  70580. return ! operator== (other);
  70581. }
  70582. END_JUCE_NAMESPACE
  70583. /*** End of inlined file: juce_BorderSize.cpp ***/
  70584. /*** Start of inlined file: juce_Line.cpp ***/
  70585. BEGIN_JUCE_NAMESPACE
  70586. END_JUCE_NAMESPACE
  70587. /*** End of inlined file: juce_Line.cpp ***/
  70588. /*** Start of inlined file: juce_Path.cpp ***/
  70589. BEGIN_JUCE_NAMESPACE
  70590. // tests that some co-ords aren't NaNs
  70591. #define CHECK_COORDS_ARE_VALID(x, y) \
  70592. jassert (x == x && y == y);
  70593. namespace PathHelpers
  70594. {
  70595. static const float ellipseAngularIncrement = 0.05f;
  70596. static void perpendicularOffset (const float x1, const float y1,
  70597. const float x2, const float y2,
  70598. const float offsetX, const float offsetY,
  70599. float& resultX, float& resultY) throw()
  70600. {
  70601. const float dx = x2 - x1;
  70602. const float dy = y2 - y1;
  70603. const float len = juce_hypotf (dx, dy);
  70604. if (len == 0)
  70605. {
  70606. resultX = x1;
  70607. resultY = y1;
  70608. }
  70609. else
  70610. {
  70611. resultX = x1 + ((dx * offsetX) - (dy * offsetY)) / len;
  70612. resultY = y1 + ((dy * offsetX) + (dx * offsetY)) / len;
  70613. }
  70614. }
  70615. static const String nextToken (const juce_wchar*& t)
  70616. {
  70617. while (CharacterFunctions::isWhitespace (*t))
  70618. ++t;
  70619. const juce_wchar* const start = t;
  70620. while (*t != 0 && ! CharacterFunctions::isWhitespace (*t))
  70621. ++t;
  70622. const int length = (int) (t - start);
  70623. while (CharacterFunctions::isWhitespace (*t))
  70624. ++t;
  70625. return String (start, length);
  70626. }
  70627. }
  70628. const float Path::lineMarker = 100001.0f;
  70629. const float Path::moveMarker = 100002.0f;
  70630. const float Path::quadMarker = 100003.0f;
  70631. const float Path::cubicMarker = 100004.0f;
  70632. const float Path::closeSubPathMarker = 100005.0f;
  70633. Path::Path()
  70634. : numElements (0),
  70635. pathXMin (0),
  70636. pathXMax (0),
  70637. pathYMin (0),
  70638. pathYMax (0),
  70639. useNonZeroWinding (true)
  70640. {
  70641. }
  70642. Path::~Path()
  70643. {
  70644. }
  70645. Path::Path (const Path& other)
  70646. : numElements (other.numElements),
  70647. pathXMin (other.pathXMin),
  70648. pathXMax (other.pathXMax),
  70649. pathYMin (other.pathYMin),
  70650. pathYMax (other.pathYMax),
  70651. useNonZeroWinding (other.useNonZeroWinding)
  70652. {
  70653. if (numElements > 0)
  70654. {
  70655. data.setAllocatedSize ((int) numElements);
  70656. memcpy (data.elements, other.data.elements, numElements * sizeof (float));
  70657. }
  70658. }
  70659. Path& Path::operator= (const Path& other)
  70660. {
  70661. if (this != &other)
  70662. {
  70663. data.ensureAllocatedSize ((int) other.numElements);
  70664. numElements = other.numElements;
  70665. pathXMin = other.pathXMin;
  70666. pathXMax = other.pathXMax;
  70667. pathYMin = other.pathYMin;
  70668. pathYMax = other.pathYMax;
  70669. useNonZeroWinding = other.useNonZeroWinding;
  70670. if (numElements > 0)
  70671. memcpy (data.elements, other.data.elements, numElements * sizeof (float));
  70672. }
  70673. return *this;
  70674. }
  70675. void Path::clear() throw()
  70676. {
  70677. numElements = 0;
  70678. pathXMin = 0;
  70679. pathYMin = 0;
  70680. pathYMax = 0;
  70681. pathXMax = 0;
  70682. }
  70683. void Path::swapWithPath (Path& other)
  70684. {
  70685. data.swapWith (other.data);
  70686. swapVariables <size_t> (numElements, other.numElements);
  70687. swapVariables <float> (pathXMin, other.pathXMin);
  70688. swapVariables <float> (pathXMax, other.pathXMax);
  70689. swapVariables <float> (pathYMin, other.pathYMin);
  70690. swapVariables <float> (pathYMax, other.pathYMax);
  70691. swapVariables <bool> (useNonZeroWinding, other.useNonZeroWinding);
  70692. }
  70693. void Path::setUsingNonZeroWinding (const bool isNonZero) throw()
  70694. {
  70695. useNonZeroWinding = isNonZero;
  70696. }
  70697. void Path::scaleToFit (const float x, const float y, const float w, const float h,
  70698. const bool preserveProportions) throw()
  70699. {
  70700. applyTransform (getTransformToScaleToFit (x, y, w, h, preserveProportions));
  70701. }
  70702. bool Path::isEmpty() const throw()
  70703. {
  70704. size_t i = 0;
  70705. while (i < numElements)
  70706. {
  70707. const float type = data.elements [i++];
  70708. if (type == moveMarker)
  70709. {
  70710. i += 2;
  70711. }
  70712. else if (type == lineMarker
  70713. || type == quadMarker
  70714. || type == cubicMarker)
  70715. {
  70716. return false;
  70717. }
  70718. }
  70719. return true;
  70720. }
  70721. const Rectangle<float> Path::getBounds() const throw()
  70722. {
  70723. return Rectangle<float> (pathXMin, pathYMin,
  70724. pathXMax - pathXMin,
  70725. pathYMax - pathYMin);
  70726. }
  70727. const Rectangle<float> Path::getBoundsTransformed (const AffineTransform& transform) const throw()
  70728. {
  70729. return getBounds().transformed (transform);
  70730. }
  70731. void Path::startNewSubPath (const float x, const float y)
  70732. {
  70733. CHECK_COORDS_ARE_VALID (x, y);
  70734. if (numElements == 0)
  70735. {
  70736. pathXMin = pathXMax = x;
  70737. pathYMin = pathYMax = y;
  70738. }
  70739. else
  70740. {
  70741. pathXMin = jmin (pathXMin, x);
  70742. pathXMax = jmax (pathXMax, x);
  70743. pathYMin = jmin (pathYMin, y);
  70744. pathYMax = jmax (pathYMax, y);
  70745. }
  70746. data.ensureAllocatedSize ((int) numElements + 3);
  70747. data.elements [numElements++] = moveMarker;
  70748. data.elements [numElements++] = x;
  70749. data.elements [numElements++] = y;
  70750. }
  70751. void Path::lineTo (const float x, const float y)
  70752. {
  70753. CHECK_COORDS_ARE_VALID (x, y);
  70754. if (numElements == 0)
  70755. startNewSubPath (0, 0);
  70756. data.ensureAllocatedSize ((int) numElements + 3);
  70757. data.elements [numElements++] = lineMarker;
  70758. data.elements [numElements++] = x;
  70759. data.elements [numElements++] = y;
  70760. pathXMin = jmin (pathXMin, x);
  70761. pathXMax = jmax (pathXMax, x);
  70762. pathYMin = jmin (pathYMin, y);
  70763. pathYMax = jmax (pathYMax, y);
  70764. }
  70765. void Path::quadraticTo (const float x1, const float y1,
  70766. const float x2, const float y2)
  70767. {
  70768. CHECK_COORDS_ARE_VALID (x1, y1);
  70769. CHECK_COORDS_ARE_VALID (x2, y2);
  70770. if (numElements == 0)
  70771. startNewSubPath (0, 0);
  70772. data.ensureAllocatedSize ((int) numElements + 5);
  70773. data.elements [numElements++] = quadMarker;
  70774. data.elements [numElements++] = x1;
  70775. data.elements [numElements++] = y1;
  70776. data.elements [numElements++] = x2;
  70777. data.elements [numElements++] = y2;
  70778. pathXMin = jmin (pathXMin, x1, x2);
  70779. pathXMax = jmax (pathXMax, x1, x2);
  70780. pathYMin = jmin (pathYMin, y1, y2);
  70781. pathYMax = jmax (pathYMax, y1, y2);
  70782. }
  70783. void Path::cubicTo (const float x1, const float y1,
  70784. const float x2, const float y2,
  70785. const float x3, const float y3)
  70786. {
  70787. CHECK_COORDS_ARE_VALID (x1, y1);
  70788. CHECK_COORDS_ARE_VALID (x2, y2);
  70789. CHECK_COORDS_ARE_VALID (x3, y3);
  70790. if (numElements == 0)
  70791. startNewSubPath (0, 0);
  70792. data.ensureAllocatedSize ((int) numElements + 7);
  70793. data.elements [numElements++] = cubicMarker;
  70794. data.elements [numElements++] = x1;
  70795. data.elements [numElements++] = y1;
  70796. data.elements [numElements++] = x2;
  70797. data.elements [numElements++] = y2;
  70798. data.elements [numElements++] = x3;
  70799. data.elements [numElements++] = y3;
  70800. pathXMin = jmin (pathXMin, x1, x2, x3);
  70801. pathXMax = jmax (pathXMax, x1, x2, x3);
  70802. pathYMin = jmin (pathYMin, y1, y2, y3);
  70803. pathYMax = jmax (pathYMax, y1, y2, y3);
  70804. }
  70805. void Path::closeSubPath()
  70806. {
  70807. if (numElements > 0
  70808. && data.elements [numElements - 1] != closeSubPathMarker)
  70809. {
  70810. data.ensureAllocatedSize ((int) numElements + 1);
  70811. data.elements [numElements++] = closeSubPathMarker;
  70812. }
  70813. }
  70814. const Point<float> Path::getCurrentPosition() const
  70815. {
  70816. size_t i = numElements - 1;
  70817. if (i > 0 && data.elements[i] == closeSubPathMarker)
  70818. {
  70819. while (i >= 0)
  70820. {
  70821. if (data.elements[i] == moveMarker)
  70822. {
  70823. i += 2;
  70824. break;
  70825. }
  70826. --i;
  70827. }
  70828. }
  70829. if (i > 0)
  70830. return Point<float> (data.elements [i - 1], data.elements [i]);
  70831. return Point<float>();
  70832. }
  70833. void Path::addRectangle (const float x, const float y,
  70834. const float w, const float h)
  70835. {
  70836. float x1 = x, y1 = y, x2 = x + w, y2 = y + h;
  70837. if (w < 0)
  70838. swapVariables (x1, x2);
  70839. if (h < 0)
  70840. swapVariables (y1, y2);
  70841. data.ensureAllocatedSize ((int) numElements + 13);
  70842. if (numElements == 0)
  70843. {
  70844. pathXMin = x1;
  70845. pathXMax = x2;
  70846. pathYMin = y1;
  70847. pathYMax = y2;
  70848. }
  70849. else
  70850. {
  70851. pathXMin = jmin (pathXMin, x1);
  70852. pathXMax = jmax (pathXMax, x2);
  70853. pathYMin = jmin (pathYMin, y1);
  70854. pathYMax = jmax (pathYMax, y2);
  70855. }
  70856. data.elements [numElements++] = moveMarker;
  70857. data.elements [numElements++] = x1;
  70858. data.elements [numElements++] = y2;
  70859. data.elements [numElements++] = lineMarker;
  70860. data.elements [numElements++] = x1;
  70861. data.elements [numElements++] = y1;
  70862. data.elements [numElements++] = lineMarker;
  70863. data.elements [numElements++] = x2;
  70864. data.elements [numElements++] = y1;
  70865. data.elements [numElements++] = lineMarker;
  70866. data.elements [numElements++] = x2;
  70867. data.elements [numElements++] = y2;
  70868. data.elements [numElements++] = closeSubPathMarker;
  70869. }
  70870. void Path::addRectangle (const Rectangle<int>& rectangle)
  70871. {
  70872. addRectangle ((float) rectangle.getX(), (float) rectangle.getY(),
  70873. (float) rectangle.getWidth(), (float) rectangle.getHeight());
  70874. }
  70875. void Path::addRoundedRectangle (const float x, const float y,
  70876. const float w, const float h,
  70877. float csx,
  70878. float csy)
  70879. {
  70880. csx = jmin (csx, w * 0.5f);
  70881. csy = jmin (csy, h * 0.5f);
  70882. const float cs45x = csx * 0.45f;
  70883. const float cs45y = csy * 0.45f;
  70884. const float x2 = x + w;
  70885. const float y2 = y + h;
  70886. startNewSubPath (x + csx, y);
  70887. lineTo (x2 - csx, y);
  70888. cubicTo (x2 - cs45x, y, x2, y + cs45y, x2, y + csy);
  70889. lineTo (x2, y2 - csy);
  70890. cubicTo (x2, y2 - cs45y, x2 - cs45x, y2, x2 - csx, y2);
  70891. lineTo (x + csx, y2);
  70892. cubicTo (x + cs45x, y2, x, y2 - cs45y, x, y2 - csy);
  70893. lineTo (x, y + csy);
  70894. cubicTo (x, y + cs45y, x + cs45x, y, x + csx, y);
  70895. closeSubPath();
  70896. }
  70897. void Path::addRoundedRectangle (const float x, const float y,
  70898. const float w, const float h,
  70899. float cs)
  70900. {
  70901. addRoundedRectangle (x, y, w, h, cs, cs);
  70902. }
  70903. void Path::addTriangle (const float x1, const float y1,
  70904. const float x2, const float y2,
  70905. const float x3, const float y3)
  70906. {
  70907. startNewSubPath (x1, y1);
  70908. lineTo (x2, y2);
  70909. lineTo (x3, y3);
  70910. closeSubPath();
  70911. }
  70912. void Path::addQuadrilateral (const float x1, const float y1,
  70913. const float x2, const float y2,
  70914. const float x3, const float y3,
  70915. const float x4, const float y4)
  70916. {
  70917. startNewSubPath (x1, y1);
  70918. lineTo (x2, y2);
  70919. lineTo (x3, y3);
  70920. lineTo (x4, y4);
  70921. closeSubPath();
  70922. }
  70923. void Path::addEllipse (const float x, const float y,
  70924. const float w, const float h)
  70925. {
  70926. const float hw = w * 0.5f;
  70927. const float hw55 = hw * 0.55f;
  70928. const float hh = h * 0.5f;
  70929. const float hh45 = hh * 0.55f;
  70930. const float cx = x + hw;
  70931. const float cy = y + hh;
  70932. startNewSubPath (cx, cy - hh);
  70933. cubicTo (cx + hw55, cy - hh, cx + hw, cy - hh45, cx + hw, cy);
  70934. cubicTo (cx + hw, cy + hh45, cx + hw55, cy + hh, cx, cy + hh);
  70935. cubicTo (cx - hw55, cy + hh, cx - hw, cy + hh45, cx - hw, cy);
  70936. cubicTo (cx - hw, cy - hh45, cx - hw55, cy - hh, cx, cy - hh);
  70937. closeSubPath();
  70938. }
  70939. void Path::addArc (const float x, const float y,
  70940. const float w, const float h,
  70941. const float fromRadians,
  70942. const float toRadians,
  70943. const bool startAsNewSubPath)
  70944. {
  70945. const float radiusX = w / 2.0f;
  70946. const float radiusY = h / 2.0f;
  70947. addCentredArc (x + radiusX,
  70948. y + radiusY,
  70949. radiusX, radiusY,
  70950. 0.0f,
  70951. fromRadians, toRadians,
  70952. startAsNewSubPath);
  70953. }
  70954. void Path::addCentredArc (const float centreX, const float centreY,
  70955. const float radiusX, const float radiusY,
  70956. const float rotationOfEllipse,
  70957. const float fromRadians,
  70958. const float toRadians,
  70959. const bool startAsNewSubPath)
  70960. {
  70961. if (radiusX > 0.0f && radiusY > 0.0f)
  70962. {
  70963. const AffineTransform rotation (AffineTransform::rotation (rotationOfEllipse, centreX, centreY));
  70964. float angle = fromRadians;
  70965. if (startAsNewSubPath)
  70966. {
  70967. float x = centreX + radiusX * sinf (angle);
  70968. float y = centreY - radiusY * cosf (angle);
  70969. if (rotationOfEllipse != 0)
  70970. rotation.transformPoint (x, y);
  70971. startNewSubPath (x, y);
  70972. }
  70973. if (fromRadians < toRadians)
  70974. {
  70975. if (startAsNewSubPath)
  70976. angle += PathHelpers::ellipseAngularIncrement;
  70977. while (angle < toRadians)
  70978. {
  70979. float x = centreX + radiusX * sinf (angle);
  70980. float y = centreY - radiusY * cosf (angle);
  70981. if (rotationOfEllipse != 0)
  70982. rotation.transformPoint (x, y);
  70983. lineTo (x, y);
  70984. angle += PathHelpers::ellipseAngularIncrement;
  70985. }
  70986. }
  70987. else
  70988. {
  70989. if (startAsNewSubPath)
  70990. angle -= PathHelpers::ellipseAngularIncrement;
  70991. while (angle > toRadians)
  70992. {
  70993. float x = centreX + radiusX * sinf (angle);
  70994. float y = centreY - radiusY * cosf (angle);
  70995. if (rotationOfEllipse != 0)
  70996. rotation.transformPoint (x, y);
  70997. lineTo (x, y);
  70998. angle -= PathHelpers::ellipseAngularIncrement;
  70999. }
  71000. }
  71001. float x = centreX + radiusX * sinf (toRadians);
  71002. float y = centreY - radiusY * cosf (toRadians);
  71003. if (rotationOfEllipse != 0)
  71004. rotation.transformPoint (x, y);
  71005. lineTo (x, y);
  71006. }
  71007. }
  71008. void Path::addPieSegment (const float x, const float y,
  71009. const float width, const float height,
  71010. const float fromRadians,
  71011. const float toRadians,
  71012. const float innerCircleProportionalSize)
  71013. {
  71014. float hw = width * 0.5f;
  71015. float hh = height * 0.5f;
  71016. const float centreX = x + hw;
  71017. const float centreY = y + hh;
  71018. startNewSubPath (centreX + hw * sinf (fromRadians),
  71019. centreY - hh * cosf (fromRadians));
  71020. addArc (x, y, width, height, fromRadians, toRadians);
  71021. if (fabs (fromRadians - toRadians) > float_Pi * 1.999f)
  71022. {
  71023. closeSubPath();
  71024. if (innerCircleProportionalSize > 0)
  71025. {
  71026. hw *= innerCircleProportionalSize;
  71027. hh *= innerCircleProportionalSize;
  71028. startNewSubPath (centreX + hw * sinf (toRadians),
  71029. centreY - hh * cosf (toRadians));
  71030. addArc (centreX - hw, centreY - hh, hw * 2.0f, hh * 2.0f,
  71031. toRadians, fromRadians);
  71032. }
  71033. }
  71034. else
  71035. {
  71036. if (innerCircleProportionalSize > 0)
  71037. {
  71038. hw *= innerCircleProportionalSize;
  71039. hh *= innerCircleProportionalSize;
  71040. addArc (centreX - hw, centreY - hh, hw * 2.0f, hh * 2.0f,
  71041. toRadians, fromRadians);
  71042. }
  71043. else
  71044. {
  71045. lineTo (centreX, centreY);
  71046. }
  71047. }
  71048. closeSubPath();
  71049. }
  71050. void Path::addLineSegment (const float startX, const float startY,
  71051. const float endX, const float endY,
  71052. float lineThickness)
  71053. {
  71054. lineThickness *= 0.5f;
  71055. float x, y;
  71056. PathHelpers::perpendicularOffset (startX, startY, endX, endY,
  71057. 0, lineThickness, x, y);
  71058. startNewSubPath (x, y);
  71059. PathHelpers::perpendicularOffset (startX, startY, endX, endY,
  71060. 0, -lineThickness, x, y);
  71061. lineTo (x, y);
  71062. PathHelpers::perpendicularOffset (endX, endY, startX, startY,
  71063. 0, lineThickness, x, y);
  71064. lineTo (x, y);
  71065. PathHelpers::perpendicularOffset (endX, endY, startX, startY,
  71066. 0, -lineThickness, x, y);
  71067. lineTo (x, y);
  71068. closeSubPath();
  71069. }
  71070. void Path::addArrow (const float startX, const float startY,
  71071. const float endX, const float endY,
  71072. float lineThickness,
  71073. float arrowheadWidth,
  71074. float arrowheadLength)
  71075. {
  71076. lineThickness *= 0.5f;
  71077. arrowheadWidth *= 0.5f;
  71078. arrowheadLength = jmin (arrowheadLength, 0.8f * juce_hypotf (startX - endX,
  71079. startY - endY));
  71080. float x, y;
  71081. PathHelpers::perpendicularOffset (startX, startY, endX, endY,
  71082. 0, lineThickness, x, y);
  71083. startNewSubPath (x, y);
  71084. PathHelpers::perpendicularOffset (startX, startY, endX, endY,
  71085. 0, -lineThickness, x, y);
  71086. lineTo (x, y);
  71087. PathHelpers::perpendicularOffset (endX, endY, startX, startY,
  71088. arrowheadLength, lineThickness, x, y);
  71089. lineTo (x, y);
  71090. PathHelpers::perpendicularOffset (endX, endY, startX, startY,
  71091. arrowheadLength, arrowheadWidth, x, y);
  71092. lineTo (x, y);
  71093. PathHelpers::perpendicularOffset (endX, endY, startX, startY,
  71094. 0, 0, x, y);
  71095. lineTo (x, y);
  71096. PathHelpers::perpendicularOffset (endX, endY, startX, startY,
  71097. arrowheadLength, -arrowheadWidth, x, y);
  71098. lineTo (x, y);
  71099. PathHelpers::perpendicularOffset (endX, endY, startX, startY,
  71100. arrowheadLength, -lineThickness, x, y);
  71101. lineTo (x, y);
  71102. closeSubPath();
  71103. }
  71104. void Path::addStar (const float centreX,
  71105. const float centreY,
  71106. const int numberOfPoints,
  71107. const float innerRadius,
  71108. const float outerRadius,
  71109. const float startAngle)
  71110. {
  71111. jassert (numberOfPoints > 1); // this would be silly.
  71112. if (numberOfPoints > 1)
  71113. {
  71114. const float angleBetweenPoints = float_Pi * 2.0f / numberOfPoints;
  71115. for (int i = 0; i < numberOfPoints; ++i)
  71116. {
  71117. float angle = startAngle + i * angleBetweenPoints;
  71118. const float x = centreX + outerRadius * sinf (angle);
  71119. const float y = centreY - outerRadius * cosf (angle);
  71120. if (i == 0)
  71121. startNewSubPath (x, y);
  71122. else
  71123. lineTo (x, y);
  71124. angle += angleBetweenPoints * 0.5f;
  71125. lineTo (centreX + innerRadius * sinf (angle),
  71126. centreY - innerRadius * cosf (angle));
  71127. }
  71128. closeSubPath();
  71129. }
  71130. }
  71131. void Path::addBubble (float x, float y,
  71132. float w, float h,
  71133. float cs,
  71134. float tipX,
  71135. float tipY,
  71136. int whichSide,
  71137. float arrowPos,
  71138. float arrowWidth)
  71139. {
  71140. if (w > 1.0f && h > 1.0f)
  71141. {
  71142. cs = jmin (cs, w * 0.5f, h * 0.5f);
  71143. const float cs2 = 2.0f * cs;
  71144. startNewSubPath (x + cs, y);
  71145. if (whichSide == 0)
  71146. {
  71147. const float halfArrowW = jmin (arrowWidth, w - cs2) * 0.5f;
  71148. const float arrowX1 = x + cs + jmax (0.0f, (w - cs2) * arrowPos - halfArrowW);
  71149. lineTo (arrowX1, y);
  71150. lineTo (tipX, tipY);
  71151. lineTo (arrowX1 + halfArrowW * 2.0f, y);
  71152. }
  71153. lineTo (x + w - cs, y);
  71154. if (cs > 0.0f)
  71155. addArc (x + w - cs2, y, cs2, cs2, 0, float_Pi * 0.5f);
  71156. if (whichSide == 3)
  71157. {
  71158. const float halfArrowH = jmin (arrowWidth, h - cs2) * 0.5f;
  71159. const float arrowY1 = y + cs + jmax (0.0f, (h - cs2) * arrowPos - halfArrowH);
  71160. lineTo (x + w, arrowY1);
  71161. lineTo (tipX, tipY);
  71162. lineTo (x + w, arrowY1 + halfArrowH * 2.0f);
  71163. }
  71164. lineTo (x + w, y + h - cs);
  71165. if (cs > 0.0f)
  71166. addArc (x + w - cs2, y + h - cs2, cs2, cs2, float_Pi * 0.5f, float_Pi);
  71167. if (whichSide == 2)
  71168. {
  71169. const float halfArrowW = jmin (arrowWidth, w - cs2) * 0.5f;
  71170. const float arrowX1 = x + cs + jmax (0.0f, (w - cs2) * arrowPos - halfArrowW);
  71171. lineTo (arrowX1 + halfArrowW * 2.0f, y + h);
  71172. lineTo (tipX, tipY);
  71173. lineTo (arrowX1, y + h);
  71174. }
  71175. lineTo (x + cs, y + h);
  71176. if (cs > 0.0f)
  71177. addArc (x, y + h - cs2, cs2, cs2, float_Pi, float_Pi * 1.5f);
  71178. if (whichSide == 1)
  71179. {
  71180. const float halfArrowH = jmin (arrowWidth, h - cs2) * 0.5f;
  71181. const float arrowY1 = y + cs + jmax (0.0f, (h - cs2) * arrowPos - halfArrowH);
  71182. lineTo (x, arrowY1 + halfArrowH * 2.0f);
  71183. lineTo (tipX, tipY);
  71184. lineTo (x, arrowY1);
  71185. }
  71186. lineTo (x, y + cs);
  71187. if (cs > 0.0f)
  71188. addArc (x, y, cs2, cs2, float_Pi * 1.5f, float_Pi * 2.0f - PathHelpers::ellipseAngularIncrement);
  71189. closeSubPath();
  71190. }
  71191. }
  71192. void Path::addPath (const Path& other)
  71193. {
  71194. size_t i = 0;
  71195. while (i < other.numElements)
  71196. {
  71197. const float type = other.data.elements [i++];
  71198. if (type == moveMarker)
  71199. {
  71200. startNewSubPath (other.data.elements [i],
  71201. other.data.elements [i + 1]);
  71202. i += 2;
  71203. }
  71204. else if (type == lineMarker)
  71205. {
  71206. lineTo (other.data.elements [i],
  71207. other.data.elements [i + 1]);
  71208. i += 2;
  71209. }
  71210. else if (type == quadMarker)
  71211. {
  71212. quadraticTo (other.data.elements [i],
  71213. other.data.elements [i + 1],
  71214. other.data.elements [i + 2],
  71215. other.data.elements [i + 3]);
  71216. i += 4;
  71217. }
  71218. else if (type == cubicMarker)
  71219. {
  71220. cubicTo (other.data.elements [i],
  71221. other.data.elements [i + 1],
  71222. other.data.elements [i + 2],
  71223. other.data.elements [i + 3],
  71224. other.data.elements [i + 4],
  71225. other.data.elements [i + 5]);
  71226. i += 6;
  71227. }
  71228. else if (type == closeSubPathMarker)
  71229. {
  71230. closeSubPath();
  71231. }
  71232. else
  71233. {
  71234. // something's gone wrong with the element list!
  71235. jassertfalse
  71236. }
  71237. }
  71238. }
  71239. void Path::addPath (const Path& other,
  71240. const AffineTransform& transformToApply)
  71241. {
  71242. size_t i = 0;
  71243. while (i < other.numElements)
  71244. {
  71245. const float type = other.data.elements [i++];
  71246. if (type == closeSubPathMarker)
  71247. {
  71248. closeSubPath();
  71249. }
  71250. else
  71251. {
  71252. float x = other.data.elements [i++];
  71253. float y = other.data.elements [i++];
  71254. transformToApply.transformPoint (x, y);
  71255. if (type == moveMarker)
  71256. {
  71257. startNewSubPath (x, y);
  71258. }
  71259. else if (type == lineMarker)
  71260. {
  71261. lineTo (x, y);
  71262. }
  71263. else if (type == quadMarker)
  71264. {
  71265. float x2 = other.data.elements [i++];
  71266. float y2 = other.data.elements [i++];
  71267. transformToApply.transformPoint (x2, y2);
  71268. quadraticTo (x, y, x2, y2);
  71269. }
  71270. else if (type == cubicMarker)
  71271. {
  71272. float x2 = other.data.elements [i++];
  71273. float y2 = other.data.elements [i++];
  71274. float x3 = other.data.elements [i++];
  71275. float y3 = other.data.elements [i++];
  71276. transformToApply.transformPoint (x2, y2);
  71277. transformToApply.transformPoint (x3, y3);
  71278. cubicTo (x, y, x2, y2, x3, y3);
  71279. }
  71280. else
  71281. {
  71282. // something's gone wrong with the element list!
  71283. jassertfalse
  71284. }
  71285. }
  71286. }
  71287. }
  71288. void Path::applyTransform (const AffineTransform& transform) throw()
  71289. {
  71290. size_t i = 0;
  71291. pathYMin = pathXMin = 0;
  71292. pathYMax = pathXMax = 0;
  71293. bool setMaxMin = false;
  71294. while (i < numElements)
  71295. {
  71296. const float type = data.elements [i++];
  71297. if (type == moveMarker)
  71298. {
  71299. transform.transformPoint (data.elements [i],
  71300. data.elements [i + 1]);
  71301. if (setMaxMin)
  71302. {
  71303. pathXMin = jmin (pathXMin, data.elements [i]);
  71304. pathXMax = jmax (pathXMax, data.elements [i]);
  71305. pathYMin = jmin (pathYMin, data.elements [i + 1]);
  71306. pathYMax = jmax (pathYMax, data.elements [i + 1]);
  71307. }
  71308. else
  71309. {
  71310. pathXMin = pathXMax = data.elements [i];
  71311. pathYMin = pathYMax = data.elements [i + 1];
  71312. setMaxMin = true;
  71313. }
  71314. i += 2;
  71315. }
  71316. else if (type == lineMarker)
  71317. {
  71318. transform.transformPoint (data.elements [i],
  71319. data.elements [i + 1]);
  71320. pathXMin = jmin (pathXMin, data.elements [i]);
  71321. pathXMax = jmax (pathXMax, data.elements [i]);
  71322. pathYMin = jmin (pathYMin, data.elements [i + 1]);
  71323. pathYMax = jmax (pathYMax, data.elements [i + 1]);
  71324. i += 2;
  71325. }
  71326. else if (type == quadMarker)
  71327. {
  71328. transform.transformPoint (data.elements [i],
  71329. data.elements [i + 1]);
  71330. transform.transformPoint (data.elements [i + 2],
  71331. data.elements [i + 3]);
  71332. pathXMin = jmin (pathXMin, data.elements [i], data.elements [i + 2]);
  71333. pathXMax = jmax (pathXMax, data.elements [i], data.elements [i + 2]);
  71334. pathYMin = jmin (pathYMin, data.elements [i + 1], data.elements [i + 3]);
  71335. pathYMax = jmax (pathYMax, data.elements [i + 1], data.elements [i + 3]);
  71336. i += 4;
  71337. }
  71338. else if (type == cubicMarker)
  71339. {
  71340. transform.transformPoint (data.elements [i],
  71341. data.elements [i + 1]);
  71342. transform.transformPoint (data.elements [i + 2],
  71343. data.elements [i + 3]);
  71344. transform.transformPoint (data.elements [i + 4],
  71345. data.elements [i + 5]);
  71346. pathXMin = jmin (pathXMin, data.elements [i], data.elements [i + 2], data.elements [i + 4]);
  71347. pathXMax = jmax (pathXMax, data.elements [i], data.elements [i + 2], data.elements [i + 4]);
  71348. pathYMin = jmin (pathYMin, data.elements [i + 1], data.elements [i + 3], data.elements [i + 5]);
  71349. pathYMax = jmax (pathYMax, data.elements [i + 1], data.elements [i + 3], data.elements [i + 5]);
  71350. i += 6;
  71351. }
  71352. }
  71353. }
  71354. const AffineTransform Path::getTransformToScaleToFit (const float x, const float y,
  71355. const float w, const float h,
  71356. const bool preserveProportions,
  71357. const Justification& justification) const
  71358. {
  71359. Rectangle<float> bounds (getBounds());
  71360. if (preserveProportions)
  71361. {
  71362. if (w <= 0 || h <= 0 || bounds.isEmpty())
  71363. return AffineTransform::identity;
  71364. float newW, newH;
  71365. const float srcRatio = bounds.getHeight() / bounds.getWidth();
  71366. if (srcRatio > h / w)
  71367. {
  71368. newW = h / srcRatio;
  71369. newH = h;
  71370. }
  71371. else
  71372. {
  71373. newW = w;
  71374. newH = w * srcRatio;
  71375. }
  71376. float newXCentre = x;
  71377. float newYCentre = y;
  71378. if (justification.testFlags (Justification::left))
  71379. newXCentre += newW * 0.5f;
  71380. else if (justification.testFlags (Justification::right))
  71381. newXCentre += w - newW * 0.5f;
  71382. else
  71383. newXCentre += w * 0.5f;
  71384. if (justification.testFlags (Justification::top))
  71385. newYCentre += newH * 0.5f;
  71386. else if (justification.testFlags (Justification::bottom))
  71387. newYCentre += h - newH * 0.5f;
  71388. else
  71389. newYCentre += h * 0.5f;
  71390. return AffineTransform::translation (bounds.getWidth() * -0.5f - bounds.getX(),
  71391. bounds.getHeight() * -0.5f - bounds.getY())
  71392. .scaled (newW / bounds.getWidth(), newH / bounds.getHeight())
  71393. .translated (newXCentre, newYCentre);
  71394. }
  71395. else
  71396. {
  71397. return AffineTransform::translation (-bounds.getX(), -bounds.getY())
  71398. .scaled (w / bounds.getWidth(), h / bounds.getHeight())
  71399. .translated (x, y);
  71400. }
  71401. }
  71402. bool Path::contains (const float x, const float y, const float tolerence) const
  71403. {
  71404. if (x <= pathXMin || x >= pathXMax
  71405. || y <= pathYMin || y >= pathYMax)
  71406. return false;
  71407. PathFlatteningIterator i (*this, AffineTransform::identity, tolerence);
  71408. int positiveCrossings = 0;
  71409. int negativeCrossings = 0;
  71410. while (i.next())
  71411. {
  71412. if ((i.y1 <= y && i.y2 > y) || (i.y2 <= y && i.y1 > y))
  71413. {
  71414. const float intersectX = i.x1 + (i.x2 - i.x1) * (y - i.y1) / (i.y2 - i.y1);
  71415. if (intersectX <= x)
  71416. {
  71417. if (i.y1 < i.y2)
  71418. ++positiveCrossings;
  71419. else
  71420. ++negativeCrossings;
  71421. }
  71422. }
  71423. }
  71424. return useNonZeroWinding ? (negativeCrossings != positiveCrossings)
  71425. : ((negativeCrossings + positiveCrossings) & 1) != 0;
  71426. }
  71427. bool Path::contains (const Point<float>& point, const float tolerence) const
  71428. {
  71429. return contains (point.getX(), point.getY(), tolerence);
  71430. }
  71431. bool Path::intersectsLine (const Line<float>& line, const float tolerence)
  71432. {
  71433. PathFlatteningIterator i (*this, AffineTransform::identity, tolerence);
  71434. Point<float> intersection;
  71435. while (i.next())
  71436. if (line.intersects (Line<float> (i.x1, i.y1, i.x2, i.y2), intersection))
  71437. return true;
  71438. return false;
  71439. }
  71440. const Line<float> Path::getClippedLine (const Line<float>& line, const bool keepSectionOutsidePath) const
  71441. {
  71442. Line<float> result (line);
  71443. const bool startInside = contains (line.getStart());
  71444. const bool endInside = contains (line.getEnd());
  71445. if (startInside == endInside)
  71446. {
  71447. if (keepSectionOutsidePath == startInside)
  71448. result = Line<float>();
  71449. }
  71450. else
  71451. {
  71452. PathFlatteningIterator i (*this, AffineTransform::identity);
  71453. Point<float> intersection;
  71454. while (i.next())
  71455. {
  71456. if (line.intersects (Line<float> (i.x1, i.y1, i.x2, i.y2), intersection))
  71457. {
  71458. if ((startInside && keepSectionOutsidePath) || (endInside && ! keepSectionOutsidePath))
  71459. result.setStart (intersection);
  71460. else
  71461. result.setEnd (intersection);
  71462. }
  71463. }
  71464. }
  71465. return result;
  71466. }
  71467. const Path Path::createPathWithRoundedCorners (const float cornerRadius) const
  71468. {
  71469. if (cornerRadius <= 0.01f)
  71470. return *this;
  71471. size_t indexOfPathStart = 0, indexOfPathStartThis = 0;
  71472. size_t n = 0;
  71473. bool lastWasLine = false, firstWasLine = false;
  71474. Path p;
  71475. while (n < numElements)
  71476. {
  71477. const float type = data.elements [n++];
  71478. if (type == moveMarker)
  71479. {
  71480. indexOfPathStart = p.numElements;
  71481. indexOfPathStartThis = n - 1;
  71482. const float x = data.elements [n++];
  71483. const float y = data.elements [n++];
  71484. p.startNewSubPath (x, y);
  71485. lastWasLine = false;
  71486. firstWasLine = (data.elements [n] == lineMarker);
  71487. }
  71488. else if (type == lineMarker || type == closeSubPathMarker)
  71489. {
  71490. float startX = 0, startY = 0, joinX = 0, joinY = 0, endX, endY;
  71491. if (type == lineMarker)
  71492. {
  71493. endX = data.elements [n++];
  71494. endY = data.elements [n++];
  71495. if (n > 8)
  71496. {
  71497. startX = data.elements [n - 8];
  71498. startY = data.elements [n - 7];
  71499. joinX = data.elements [n - 5];
  71500. joinY = data.elements [n - 4];
  71501. }
  71502. }
  71503. else
  71504. {
  71505. endX = data.elements [indexOfPathStartThis + 1];
  71506. endY = data.elements [indexOfPathStartThis + 2];
  71507. if (n > 6)
  71508. {
  71509. startX = data.elements [n - 6];
  71510. startY = data.elements [n - 5];
  71511. joinX = data.elements [n - 3];
  71512. joinY = data.elements [n - 2];
  71513. }
  71514. }
  71515. if (lastWasLine)
  71516. {
  71517. const double len1 = juce_hypot (startX - joinX,
  71518. startY - joinY);
  71519. if (len1 > 0)
  71520. {
  71521. const double propNeeded = jmin (0.5, cornerRadius / len1);
  71522. p.data.elements [p.numElements - 2] = (float) (joinX - (joinX - startX) * propNeeded);
  71523. p.data.elements [p.numElements - 1] = (float) (joinY - (joinY - startY) * propNeeded);
  71524. }
  71525. const double len2 = juce_hypot (endX - joinX,
  71526. endY - joinY);
  71527. if (len2 > 0)
  71528. {
  71529. const double propNeeded = jmin (0.5, cornerRadius / len2);
  71530. p.quadraticTo (joinX, joinY,
  71531. (float) (joinX + (endX - joinX) * propNeeded),
  71532. (float) (joinY + (endY - joinY) * propNeeded));
  71533. }
  71534. p.lineTo (endX, endY);
  71535. }
  71536. else if (type == lineMarker)
  71537. {
  71538. p.lineTo (endX, endY);
  71539. lastWasLine = true;
  71540. }
  71541. if (type == closeSubPathMarker)
  71542. {
  71543. if (firstWasLine)
  71544. {
  71545. startX = data.elements [n - 3];
  71546. startY = data.elements [n - 2];
  71547. joinX = endX;
  71548. joinY = endY;
  71549. endX = data.elements [indexOfPathStartThis + 4];
  71550. endY = data.elements [indexOfPathStartThis + 5];
  71551. const double len1 = juce_hypot (startX - joinX,
  71552. startY - joinY);
  71553. if (len1 > 0)
  71554. {
  71555. const double propNeeded = jmin (0.5, cornerRadius / len1);
  71556. p.data.elements [p.numElements - 2] = (float) (joinX - (joinX - startX) * propNeeded);
  71557. p.data.elements [p.numElements - 1] = (float) (joinY - (joinY - startY) * propNeeded);
  71558. }
  71559. const double len2 = juce_hypot (endX - joinX,
  71560. endY - joinY);
  71561. if (len2 > 0)
  71562. {
  71563. const double propNeeded = jmin (0.5, cornerRadius / len2);
  71564. endX = (float) (joinX + (endX - joinX) * propNeeded);
  71565. endY = (float) (joinY + (endY - joinY) * propNeeded);
  71566. p.quadraticTo (joinX, joinY, endX, endY);
  71567. p.data.elements [indexOfPathStart + 1] = endX;
  71568. p.data.elements [indexOfPathStart + 2] = endY;
  71569. }
  71570. }
  71571. p.closeSubPath();
  71572. }
  71573. }
  71574. else if (type == quadMarker)
  71575. {
  71576. lastWasLine = false;
  71577. const float x1 = data.elements [n++];
  71578. const float y1 = data.elements [n++];
  71579. const float x2 = data.elements [n++];
  71580. const float y2 = data.elements [n++];
  71581. p.quadraticTo (x1, y1, x2, y2);
  71582. }
  71583. else if (type == cubicMarker)
  71584. {
  71585. lastWasLine = false;
  71586. const float x1 = data.elements [n++];
  71587. const float y1 = data.elements [n++];
  71588. const float x2 = data.elements [n++];
  71589. const float y2 = data.elements [n++];
  71590. const float x3 = data.elements [n++];
  71591. const float y3 = data.elements [n++];
  71592. p.cubicTo (x1, y1, x2, y2, x3, y3);
  71593. }
  71594. }
  71595. return p;
  71596. }
  71597. void Path::loadPathFromStream (InputStream& source)
  71598. {
  71599. while (! source.isExhausted())
  71600. {
  71601. switch (source.readByte())
  71602. {
  71603. case 'm':
  71604. {
  71605. const float x = source.readFloat();
  71606. const float y = source.readFloat();
  71607. startNewSubPath (x, y);
  71608. break;
  71609. }
  71610. case 'l':
  71611. {
  71612. const float x = source.readFloat();
  71613. const float y = source.readFloat();
  71614. lineTo (x, y);
  71615. break;
  71616. }
  71617. case 'q':
  71618. {
  71619. const float x1 = source.readFloat();
  71620. const float y1 = source.readFloat();
  71621. const float x2 = source.readFloat();
  71622. const float y2 = source.readFloat();
  71623. quadraticTo (x1, y1, x2, y2);
  71624. break;
  71625. }
  71626. case 'b':
  71627. {
  71628. const float x1 = source.readFloat();
  71629. const float y1 = source.readFloat();
  71630. const float x2 = source.readFloat();
  71631. const float y2 = source.readFloat();
  71632. const float x3 = source.readFloat();
  71633. const float y3 = source.readFloat();
  71634. cubicTo (x1, y1, x2, y2, x3, y3);
  71635. break;
  71636. }
  71637. case 'c':
  71638. closeSubPath();
  71639. break;
  71640. case 'n':
  71641. useNonZeroWinding = true;
  71642. break;
  71643. case 'z':
  71644. useNonZeroWinding = false;
  71645. break;
  71646. case 'e':
  71647. return; // end of path marker
  71648. default:
  71649. jassertfalse // illegal char in the stream
  71650. break;
  71651. }
  71652. }
  71653. }
  71654. void Path::loadPathFromData (const void* const data, const int numberOfBytes)
  71655. {
  71656. MemoryInputStream in (data, numberOfBytes, false);
  71657. loadPathFromStream (in);
  71658. }
  71659. void Path::writePathToStream (OutputStream& dest) const
  71660. {
  71661. dest.writeByte (useNonZeroWinding ? 'n' : 'z');
  71662. size_t i = 0;
  71663. while (i < numElements)
  71664. {
  71665. const float type = data.elements [i++];
  71666. if (type == moveMarker)
  71667. {
  71668. dest.writeByte ('m');
  71669. dest.writeFloat (data.elements [i++]);
  71670. dest.writeFloat (data.elements [i++]);
  71671. }
  71672. else if (type == lineMarker)
  71673. {
  71674. dest.writeByte ('l');
  71675. dest.writeFloat (data.elements [i++]);
  71676. dest.writeFloat (data.elements [i++]);
  71677. }
  71678. else if (type == quadMarker)
  71679. {
  71680. dest.writeByte ('q');
  71681. dest.writeFloat (data.elements [i++]);
  71682. dest.writeFloat (data.elements [i++]);
  71683. dest.writeFloat (data.elements [i++]);
  71684. dest.writeFloat (data.elements [i++]);
  71685. }
  71686. else if (type == cubicMarker)
  71687. {
  71688. dest.writeByte ('b');
  71689. dest.writeFloat (data.elements [i++]);
  71690. dest.writeFloat (data.elements [i++]);
  71691. dest.writeFloat (data.elements [i++]);
  71692. dest.writeFloat (data.elements [i++]);
  71693. dest.writeFloat (data.elements [i++]);
  71694. dest.writeFloat (data.elements [i++]);
  71695. }
  71696. else if (type == closeSubPathMarker)
  71697. {
  71698. dest.writeByte ('c');
  71699. }
  71700. }
  71701. dest.writeByte ('e'); // marks the end-of-path
  71702. }
  71703. const String Path::toString() const
  71704. {
  71705. MemoryOutputStream s (2048, 2048);
  71706. if (! useNonZeroWinding)
  71707. s << 'a';
  71708. size_t i = 0;
  71709. float lastMarker = 0.0f;
  71710. while (i < numElements)
  71711. {
  71712. const float marker = data.elements [i++];
  71713. char markerChar = 0;
  71714. int numCoords = 0;
  71715. if (marker == moveMarker)
  71716. {
  71717. markerChar = 'm';
  71718. numCoords = 2;
  71719. }
  71720. else if (marker == lineMarker)
  71721. {
  71722. markerChar = 'l';
  71723. numCoords = 2;
  71724. }
  71725. else if (marker == quadMarker)
  71726. {
  71727. markerChar = 'q';
  71728. numCoords = 4;
  71729. }
  71730. else if (marker == cubicMarker)
  71731. {
  71732. markerChar = 'c';
  71733. numCoords = 6;
  71734. }
  71735. else
  71736. {
  71737. jassert (marker == closeSubPathMarker);
  71738. markerChar = 'z';
  71739. }
  71740. if (marker != lastMarker)
  71741. {
  71742. if (s.getDataSize() != 0)
  71743. s << ' ';
  71744. s << markerChar;
  71745. lastMarker = marker;
  71746. }
  71747. while (--numCoords >= 0 && i < numElements)
  71748. {
  71749. String coord (data.elements [i++], 3);
  71750. while (coord.endsWithChar ('0') && coord != "0")
  71751. coord = coord.dropLastCharacters (1);
  71752. if (coord.endsWithChar ('.'))
  71753. coord = coord.dropLastCharacters (1);
  71754. if (s.getDataSize() != 0)
  71755. s << ' ';
  71756. s << coord;
  71757. }
  71758. }
  71759. return s.toUTF8();
  71760. }
  71761. void Path::restoreFromString (const String& stringVersion)
  71762. {
  71763. clear();
  71764. setUsingNonZeroWinding (true);
  71765. const juce_wchar* t = stringVersion;
  71766. juce_wchar marker = 'm';
  71767. int numValues = 2;
  71768. float values [6];
  71769. while (*t != 0)
  71770. {
  71771. const String token (PathHelpers::nextToken (t));
  71772. const juce_wchar firstChar = token[0];
  71773. int startNum = 0;
  71774. if (firstChar == 'm' || firstChar == 'l')
  71775. {
  71776. marker = firstChar;
  71777. numValues = 2;
  71778. }
  71779. else if (firstChar == 'q')
  71780. {
  71781. marker = firstChar;
  71782. numValues = 4;
  71783. }
  71784. else if (firstChar == 'c')
  71785. {
  71786. marker = firstChar;
  71787. numValues = 6;
  71788. }
  71789. else if (firstChar == 'z')
  71790. {
  71791. marker = firstChar;
  71792. numValues = 0;
  71793. }
  71794. else if (firstChar == 'a')
  71795. {
  71796. setUsingNonZeroWinding (false);
  71797. continue;
  71798. }
  71799. else
  71800. {
  71801. ++startNum;
  71802. values [0] = token.getFloatValue();
  71803. }
  71804. for (int i = startNum; i < numValues; ++i)
  71805. values [i] = PathHelpers::nextToken (t).getFloatValue();
  71806. switch (marker)
  71807. {
  71808. case 'm':
  71809. startNewSubPath (values[0], values[1]);
  71810. break;
  71811. case 'l':
  71812. lineTo (values[0], values[1]);
  71813. break;
  71814. case 'q':
  71815. quadraticTo (values[0], values[1],
  71816. values[2], values[3]);
  71817. break;
  71818. case 'c':
  71819. cubicTo (values[0], values[1],
  71820. values[2], values[3],
  71821. values[4], values[5]);
  71822. break;
  71823. case 'z':
  71824. closeSubPath();
  71825. break;
  71826. default:
  71827. jassertfalse // illegal string format?
  71828. break;
  71829. }
  71830. }
  71831. }
  71832. Path::Iterator::Iterator (const Path& path_)
  71833. : path (path_),
  71834. index (0)
  71835. {
  71836. }
  71837. Path::Iterator::~Iterator()
  71838. {
  71839. }
  71840. bool Path::Iterator::next()
  71841. {
  71842. const float* const elements = path.data.elements;
  71843. if (index < path.numElements)
  71844. {
  71845. const float type = elements [index++];
  71846. if (type == moveMarker)
  71847. {
  71848. elementType = startNewSubPath;
  71849. x1 = elements [index++];
  71850. y1 = elements [index++];
  71851. }
  71852. else if (type == lineMarker)
  71853. {
  71854. elementType = lineTo;
  71855. x1 = elements [index++];
  71856. y1 = elements [index++];
  71857. }
  71858. else if (type == quadMarker)
  71859. {
  71860. elementType = quadraticTo;
  71861. x1 = elements [index++];
  71862. y1 = elements [index++];
  71863. x2 = elements [index++];
  71864. y2 = elements [index++];
  71865. }
  71866. else if (type == cubicMarker)
  71867. {
  71868. elementType = cubicTo;
  71869. x1 = elements [index++];
  71870. y1 = elements [index++];
  71871. x2 = elements [index++];
  71872. y2 = elements [index++];
  71873. x3 = elements [index++];
  71874. y3 = elements [index++];
  71875. }
  71876. else if (type == closeSubPathMarker)
  71877. {
  71878. elementType = closePath;
  71879. }
  71880. return true;
  71881. }
  71882. return false;
  71883. }
  71884. END_JUCE_NAMESPACE
  71885. /*** End of inlined file: juce_Path.cpp ***/
  71886. /*** Start of inlined file: juce_PathIterator.cpp ***/
  71887. BEGIN_JUCE_NAMESPACE
  71888. #if JUCE_MSVC
  71889. #pragma optimize ("t", on)
  71890. #endif
  71891. PathFlatteningIterator::PathFlatteningIterator (const Path& path_,
  71892. const AffineTransform& transform_,
  71893. float tolerence_)
  71894. : x2 (0),
  71895. y2 (0),
  71896. closesSubPath (false),
  71897. subPathIndex (-1),
  71898. path (path_),
  71899. transform (transform_),
  71900. points (path_.data.elements),
  71901. tolerence (tolerence_ * tolerence_),
  71902. subPathCloseX (0),
  71903. subPathCloseY (0),
  71904. isIdentityTransform (transform_.isIdentity()),
  71905. stackBase (32),
  71906. index (0),
  71907. stackSize (32)
  71908. {
  71909. stackPos = stackBase;
  71910. }
  71911. PathFlatteningIterator::~PathFlatteningIterator()
  71912. {
  71913. }
  71914. bool PathFlatteningIterator::next()
  71915. {
  71916. x1 = x2;
  71917. y1 = y2;
  71918. float x3 = 0;
  71919. float y3 = 0;
  71920. float x4 = 0;
  71921. float y4 = 0;
  71922. float type;
  71923. for (;;)
  71924. {
  71925. if (stackPos == stackBase)
  71926. {
  71927. if (index >= path.numElements)
  71928. {
  71929. return false;
  71930. }
  71931. else
  71932. {
  71933. type = points [index++];
  71934. if (type != Path::closeSubPathMarker)
  71935. {
  71936. x2 = points [index++];
  71937. y2 = points [index++];
  71938. if (! isIdentityTransform)
  71939. transform.transformPoint (x2, y2);
  71940. if (type == Path::quadMarker)
  71941. {
  71942. x3 = points [index++];
  71943. y3 = points [index++];
  71944. if (! isIdentityTransform)
  71945. transform.transformPoint (x3, y3);
  71946. }
  71947. else if (type == Path::cubicMarker)
  71948. {
  71949. x3 = points [index++];
  71950. y3 = points [index++];
  71951. x4 = points [index++];
  71952. y4 = points [index++];
  71953. if (! isIdentityTransform)
  71954. {
  71955. transform.transformPoint (x3, y3);
  71956. transform.transformPoint (x4, y4);
  71957. }
  71958. }
  71959. }
  71960. }
  71961. }
  71962. else
  71963. {
  71964. type = *--stackPos;
  71965. if (type != Path::closeSubPathMarker)
  71966. {
  71967. x2 = *--stackPos;
  71968. y2 = *--stackPos;
  71969. if (type == Path::quadMarker)
  71970. {
  71971. x3 = *--stackPos;
  71972. y3 = *--stackPos;
  71973. }
  71974. else if (type == Path::cubicMarker)
  71975. {
  71976. x3 = *--stackPos;
  71977. y3 = *--stackPos;
  71978. x4 = *--stackPos;
  71979. y4 = *--stackPos;
  71980. }
  71981. }
  71982. }
  71983. if (type == Path::lineMarker)
  71984. {
  71985. ++subPathIndex;
  71986. closesSubPath = (stackPos == stackBase)
  71987. && (index < path.numElements)
  71988. && (points [index] == Path::closeSubPathMarker)
  71989. && x2 == subPathCloseX
  71990. && y2 == subPathCloseY;
  71991. return true;
  71992. }
  71993. else if (type == Path::quadMarker)
  71994. {
  71995. const size_t offset = (size_t) (stackPos - stackBase);
  71996. if (offset >= stackSize - 10)
  71997. {
  71998. stackSize <<= 1;
  71999. stackBase.realloc (stackSize);
  72000. stackPos = stackBase + offset;
  72001. }
  72002. const float dx1 = x1 - x2;
  72003. const float dy1 = y1 - y2;
  72004. const float dx2 = x2 - x3;
  72005. const float dy2 = y2 - y3;
  72006. const float m1x = (x1 + x2) * 0.5f;
  72007. const float m1y = (y1 + y2) * 0.5f;
  72008. const float m2x = (x2 + x3) * 0.5f;
  72009. const float m2y = (y2 + y3) * 0.5f;
  72010. const float m3x = (m1x + m2x) * 0.5f;
  72011. const float m3y = (m1y + m2y) * 0.5f;
  72012. if (dx1*dx1 + dy1*dy1 + dx2*dx2 + dy2*dy2 > tolerence)
  72013. {
  72014. *stackPos++ = y3;
  72015. *stackPos++ = x3;
  72016. *stackPos++ = m2y;
  72017. *stackPos++ = m2x;
  72018. *stackPos++ = Path::quadMarker;
  72019. *stackPos++ = m3y;
  72020. *stackPos++ = m3x;
  72021. *stackPos++ = m1y;
  72022. *stackPos++ = m1x;
  72023. *stackPos++ = Path::quadMarker;
  72024. }
  72025. else
  72026. {
  72027. *stackPos++ = y3;
  72028. *stackPos++ = x3;
  72029. *stackPos++ = Path::lineMarker;
  72030. *stackPos++ = m3y;
  72031. *stackPos++ = m3x;
  72032. *stackPos++ = Path::lineMarker;
  72033. }
  72034. jassert (stackPos < stackBase + stackSize);
  72035. }
  72036. else if (type == Path::cubicMarker)
  72037. {
  72038. const size_t offset = (size_t) (stackPos - stackBase);
  72039. if (offset >= stackSize - 16)
  72040. {
  72041. stackSize <<= 1;
  72042. stackBase.realloc (stackSize);
  72043. stackPos = stackBase + offset;
  72044. }
  72045. const float dx1 = x1 - x2;
  72046. const float dy1 = y1 - y2;
  72047. const float dx2 = x2 - x3;
  72048. const float dy2 = y2 - y3;
  72049. const float dx3 = x3 - x4;
  72050. const float dy3 = y3 - y4;
  72051. const float m1x = (x1 + x2) * 0.5f;
  72052. const float m1y = (y1 + y2) * 0.5f;
  72053. const float m2x = (x3 + x2) * 0.5f;
  72054. const float m2y = (y3 + y2) * 0.5f;
  72055. const float m3x = (x3 + x4) * 0.5f;
  72056. const float m3y = (y3 + y4) * 0.5f;
  72057. const float m4x = (m1x + m2x) * 0.5f;
  72058. const float m4y = (m1y + m2y) * 0.5f;
  72059. const float m5x = (m3x + m2x) * 0.5f;
  72060. const float m5y = (m3y + m2y) * 0.5f;
  72061. if (dx1*dx1 + dy1*dy1 + dx2*dx2
  72062. + dy2*dy2 + dx3*dx3 + dy3*dy3 > tolerence)
  72063. {
  72064. *stackPos++ = y4;
  72065. *stackPos++ = x4;
  72066. *stackPos++ = m3y;
  72067. *stackPos++ = m3x;
  72068. *stackPos++ = m5y;
  72069. *stackPos++ = m5x;
  72070. *stackPos++ = Path::cubicMarker;
  72071. *stackPos++ = (m4y + m5y) * 0.5f;
  72072. *stackPos++ = (m4x + m5x) * 0.5f;
  72073. *stackPos++ = m4y;
  72074. *stackPos++ = m4x;
  72075. *stackPos++ = m1y;
  72076. *stackPos++ = m1x;
  72077. *stackPos++ = Path::cubicMarker;
  72078. }
  72079. else
  72080. {
  72081. *stackPos++ = y4;
  72082. *stackPos++ = x4;
  72083. *stackPos++ = Path::lineMarker;
  72084. *stackPos++ = m5y;
  72085. *stackPos++ = m5x;
  72086. *stackPos++ = Path::lineMarker;
  72087. *stackPos++ = m4y;
  72088. *stackPos++ = m4x;
  72089. *stackPos++ = Path::lineMarker;
  72090. }
  72091. }
  72092. else if (type == Path::closeSubPathMarker)
  72093. {
  72094. if (x2 != subPathCloseX || y2 != subPathCloseY)
  72095. {
  72096. x1 = x2;
  72097. y1 = y2;
  72098. x2 = subPathCloseX;
  72099. y2 = subPathCloseY;
  72100. closesSubPath = true;
  72101. return true;
  72102. }
  72103. }
  72104. else
  72105. {
  72106. jassert (type == Path::moveMarker);
  72107. subPathIndex = -1;
  72108. subPathCloseX = x1 = x2;
  72109. subPathCloseY = y1 = y2;
  72110. }
  72111. }
  72112. }
  72113. END_JUCE_NAMESPACE
  72114. /*** End of inlined file: juce_PathIterator.cpp ***/
  72115. /*** Start of inlined file: juce_PathStrokeType.cpp ***/
  72116. BEGIN_JUCE_NAMESPACE
  72117. PathStrokeType::PathStrokeType (const float strokeThickness,
  72118. const JointStyle jointStyle_,
  72119. const EndCapStyle endStyle_) throw()
  72120. : thickness (strokeThickness),
  72121. jointStyle (jointStyle_),
  72122. endStyle (endStyle_)
  72123. {
  72124. }
  72125. PathStrokeType::PathStrokeType (const PathStrokeType& other) throw()
  72126. : thickness (other.thickness),
  72127. jointStyle (other.jointStyle),
  72128. endStyle (other.endStyle)
  72129. {
  72130. }
  72131. PathStrokeType& PathStrokeType::operator= (const PathStrokeType& other) throw()
  72132. {
  72133. thickness = other.thickness;
  72134. jointStyle = other.jointStyle;
  72135. endStyle = other.endStyle;
  72136. return *this;
  72137. }
  72138. PathStrokeType::~PathStrokeType() throw()
  72139. {
  72140. }
  72141. bool PathStrokeType::operator== (const PathStrokeType& other) const throw()
  72142. {
  72143. return thickness == other.thickness
  72144. && jointStyle == other.jointStyle
  72145. && endStyle == other.endStyle;
  72146. }
  72147. bool PathStrokeType::operator!= (const PathStrokeType& other) const throw()
  72148. {
  72149. return ! operator== (other);
  72150. }
  72151. static bool lineIntersection (const float x1, const float y1,
  72152. const float x2, const float y2,
  72153. const float x3, const float y3,
  72154. const float x4, const float y4,
  72155. float& intersectionX,
  72156. float& intersectionY,
  72157. float& distanceBeyondLine1EndSquared) throw()
  72158. {
  72159. if (x2 != x3 || y2 != y3)
  72160. {
  72161. const float dx1 = x2 - x1;
  72162. const float dy1 = y2 - y1;
  72163. const float dx2 = x4 - x3;
  72164. const float dy2 = y4 - y3;
  72165. const float divisor = dx1 * dy2 - dx2 * dy1;
  72166. if (divisor == 0)
  72167. {
  72168. if (! ((dx1 == 0 && dy1 == 0) || (dx2 == 0 && dy2 == 0)))
  72169. {
  72170. if (dy1 == 0 && dy2 != 0)
  72171. {
  72172. const float along = (y1 - y3) / dy2;
  72173. intersectionX = x3 + along * dx2;
  72174. intersectionY = y1;
  72175. distanceBeyondLine1EndSquared = intersectionX - x2;
  72176. distanceBeyondLine1EndSquared *= distanceBeyondLine1EndSquared;
  72177. if ((x2 > x1) == (intersectionX < x2))
  72178. distanceBeyondLine1EndSquared = -distanceBeyondLine1EndSquared;
  72179. return along >= 0 && along <= 1.0f;
  72180. }
  72181. else if (dy2 == 0 && dy1 != 0)
  72182. {
  72183. const float along = (y3 - y1) / dy1;
  72184. intersectionX = x1 + along * dx1;
  72185. intersectionY = y3;
  72186. distanceBeyondLine1EndSquared = (along - 1.0f) * dx1;
  72187. distanceBeyondLine1EndSquared *= distanceBeyondLine1EndSquared;
  72188. if (along < 1.0f)
  72189. distanceBeyondLine1EndSquared = -distanceBeyondLine1EndSquared;
  72190. return along >= 0 && along <= 1.0f;
  72191. }
  72192. else if (dx1 == 0 && dx2 != 0)
  72193. {
  72194. const float along = (x1 - x3) / dx2;
  72195. intersectionX = x1;
  72196. intersectionY = y3 + along * dy2;
  72197. distanceBeyondLine1EndSquared = intersectionY - y2;
  72198. distanceBeyondLine1EndSquared *= distanceBeyondLine1EndSquared;
  72199. if ((y2 > y1) == (intersectionY < y2))
  72200. distanceBeyondLine1EndSquared = -distanceBeyondLine1EndSquared;
  72201. return along >= 0 && along <= 1.0f;
  72202. }
  72203. else if (dx2 == 0 && dx1 != 0)
  72204. {
  72205. const float along = (x3 - x1) / dx1;
  72206. intersectionX = x3;
  72207. intersectionY = y1 + along * dy1;
  72208. distanceBeyondLine1EndSquared = (along - 1.0f) * dy1;
  72209. distanceBeyondLine1EndSquared *= distanceBeyondLine1EndSquared;
  72210. if (along < 1.0f)
  72211. distanceBeyondLine1EndSquared = -distanceBeyondLine1EndSquared;
  72212. return along >= 0 && along <= 1.0f;
  72213. }
  72214. }
  72215. intersectionX = 0.5f * (x2 + x3);
  72216. intersectionY = 0.5f * (y2 + y3);
  72217. distanceBeyondLine1EndSquared = 0.0f;
  72218. return false;
  72219. }
  72220. else
  72221. {
  72222. const float along1 = ((y1 - y3) * dx2 - (x1 - x3) * dy2) / divisor;
  72223. intersectionX = x1 + along1 * dx1;
  72224. intersectionY = y1 + along1 * dy1;
  72225. if (along1 >= 0 && along1 <= 1.0f)
  72226. {
  72227. const float along2 = ((y1 - y3) * dx1 - (x1 - x3) * dy1);
  72228. if (along2 >= 0 && along2 <= divisor)
  72229. {
  72230. distanceBeyondLine1EndSquared = 0.0f;
  72231. return true;
  72232. }
  72233. }
  72234. distanceBeyondLine1EndSquared = along1 - 1.0f;
  72235. distanceBeyondLine1EndSquared *= distanceBeyondLine1EndSquared;
  72236. distanceBeyondLine1EndSquared *= (dx1 * dx1 + dy1 * dy1);
  72237. if (along1 < 1.0f)
  72238. distanceBeyondLine1EndSquared = -distanceBeyondLine1EndSquared;
  72239. return false;
  72240. }
  72241. }
  72242. intersectionX = x2;
  72243. intersectionY = y2;
  72244. distanceBeyondLine1EndSquared = 0.0f;
  72245. return true;
  72246. }
  72247. namespace PathFunctions
  72248. {
  72249. // part of stroke drawing stuff
  72250. static void addEdgeAndJoint (Path& destPath,
  72251. const PathStrokeType::JointStyle style,
  72252. const float maxMiterExtensionSquared, const float width,
  72253. const float x1, const float y1,
  72254. const float x2, const float y2,
  72255. const float x3, const float y3,
  72256. const float x4, const float y4,
  72257. const float midX, const float midY)
  72258. {
  72259. if (style == PathStrokeType::beveled
  72260. || (x3 == x4 && y3 == y4)
  72261. || (x1 == x2 && y1 == y2))
  72262. {
  72263. destPath.lineTo (x2, y2);
  72264. destPath.lineTo (x3, y3);
  72265. }
  72266. else
  72267. {
  72268. float jx, jy, distanceBeyondLine1EndSquared;
  72269. // if they intersect, use this point..
  72270. if (lineIntersection (x1, y1, x2, y2,
  72271. x3, y3, x4, y4,
  72272. jx, jy, distanceBeyondLine1EndSquared))
  72273. {
  72274. destPath.lineTo (jx, jy);
  72275. }
  72276. else
  72277. {
  72278. if (style == PathStrokeType::mitered)
  72279. {
  72280. if (distanceBeyondLine1EndSquared < maxMiterExtensionSquared
  72281. && distanceBeyondLine1EndSquared > 0.0f)
  72282. {
  72283. destPath.lineTo (jx, jy);
  72284. }
  72285. else
  72286. {
  72287. // the end sticks out too far, so just use a blunt joint
  72288. destPath.lineTo (x2, y2);
  72289. destPath.lineTo (x3, y3);
  72290. }
  72291. }
  72292. else
  72293. {
  72294. // curved joints
  72295. float angle1 = atan2f (x2 - midX, y2 - midY);
  72296. float angle2 = atan2f (x3 - midX, y3 - midY);
  72297. const float angleIncrement = 0.1f;
  72298. destPath.lineTo (x2, y2);
  72299. if (fabs (angle1 - angle2) > angleIncrement)
  72300. {
  72301. if (angle2 > angle1 + float_Pi
  72302. || (angle2 < angle1 && angle2 >= angle1 - float_Pi))
  72303. {
  72304. if (angle2 > angle1)
  72305. angle2 -= float_Pi * 2.0f;
  72306. jassert (angle1 <= angle2 + float_Pi);
  72307. angle1 -= angleIncrement;
  72308. while (angle1 > angle2)
  72309. {
  72310. destPath.lineTo (midX + width * sinf (angle1),
  72311. midY + width * cosf (angle1));
  72312. angle1 -= angleIncrement;
  72313. }
  72314. }
  72315. else
  72316. {
  72317. if (angle1 > angle2)
  72318. angle1 -= float_Pi * 2.0f;
  72319. jassert (angle1 >= angle2 - float_Pi);
  72320. angle1 += angleIncrement;
  72321. while (angle1 < angle2)
  72322. {
  72323. destPath.lineTo (midX + width * sinf (angle1),
  72324. midY + width * cosf (angle1));
  72325. angle1 += angleIncrement;
  72326. }
  72327. }
  72328. }
  72329. destPath.lineTo (x3, y3);
  72330. }
  72331. }
  72332. }
  72333. }
  72334. static void addLineEnd (Path& destPath,
  72335. const PathStrokeType::EndCapStyle style,
  72336. const float x1, const float y1,
  72337. const float x2, const float y2,
  72338. const float width)
  72339. {
  72340. if (style == PathStrokeType::butt)
  72341. {
  72342. destPath.lineTo (x2, y2);
  72343. }
  72344. else
  72345. {
  72346. float offx1, offy1, offx2, offy2;
  72347. float dx = x2 - x1;
  72348. float dy = y2 - y1;
  72349. const float len = juce_hypotf (dx, dy);
  72350. if (len == 0)
  72351. {
  72352. offx1 = offx2 = x1;
  72353. offy1 = offy2 = y1;
  72354. }
  72355. else
  72356. {
  72357. const float offset = width / len;
  72358. dx *= offset;
  72359. dy *= offset;
  72360. offx1 = x1 + dy;
  72361. offy1 = y1 - dx;
  72362. offx2 = x2 + dy;
  72363. offy2 = y2 - dx;
  72364. }
  72365. if (style == PathStrokeType::square)
  72366. {
  72367. // sqaure ends
  72368. destPath.lineTo (offx1, offy1);
  72369. destPath.lineTo (offx2, offy2);
  72370. destPath.lineTo (x2, y2);
  72371. }
  72372. else
  72373. {
  72374. // rounded ends
  72375. const float midx = (offx1 + offx2) * 0.5f;
  72376. const float midy = (offy1 + offy2) * 0.5f;
  72377. destPath.cubicTo (x1 + (offx1 - x1) * 0.55f, y1 + (offy1 - y1) * 0.55f,
  72378. offx1 + (midx - offx1) * 0.45f, offy1 + (midy - offy1) * 0.45f,
  72379. midx, midy);
  72380. destPath.cubicTo (midx + (offx2 - midx) * 0.55f, midy + (offy2 - midy) * 0.55f,
  72381. offx2 + (x2 - offx2) * 0.45f, offy2 + (y2 - offy2) * 0.45f,
  72382. x2, y2);
  72383. }
  72384. }
  72385. }
  72386. struct LineSection
  72387. {
  72388. LineSection() {}
  72389. LineSection (int) {}
  72390. float x1, y1, x2, y2; // original line
  72391. float lx1, ly1, lx2, ly2; // the left-hand stroke
  72392. float rx1, ry1, rx2, ry2; // the right-hand stroke
  72393. };
  72394. static void addSubPath (Path& destPath, const Array <LineSection>& subPath,
  72395. const bool isClosed,
  72396. const float width, const float maxMiterExtensionSquared,
  72397. const PathStrokeType::JointStyle jointStyle, const PathStrokeType::EndCapStyle endStyle)
  72398. {
  72399. jassert (subPath.size() > 0);
  72400. const LineSection& firstLine = subPath.getReference (0);
  72401. float lastX1 = firstLine.lx1;
  72402. float lastY1 = firstLine.ly1;
  72403. float lastX2 = firstLine.lx2;
  72404. float lastY2 = firstLine.ly2;
  72405. if (isClosed)
  72406. {
  72407. destPath.startNewSubPath (lastX1, lastY1);
  72408. }
  72409. else
  72410. {
  72411. destPath.startNewSubPath (firstLine.rx2, firstLine.ry2);
  72412. addLineEnd (destPath, endStyle,
  72413. firstLine.rx2, firstLine.ry2,
  72414. lastX1, lastY1,
  72415. width);
  72416. }
  72417. int i;
  72418. for (i = 1; i < subPath.size(); ++i)
  72419. {
  72420. const LineSection& l = subPath.getReference (i);
  72421. addEdgeAndJoint (destPath, jointStyle,
  72422. maxMiterExtensionSquared, width,
  72423. lastX1, lastY1, lastX2, lastY2,
  72424. l.lx1, l.ly1, l.lx2, l.ly2,
  72425. l.x1, l.y1);
  72426. lastX1 = l.lx1;
  72427. lastY1 = l.ly1;
  72428. lastX2 = l.lx2;
  72429. lastY2 = l.ly2;
  72430. }
  72431. const LineSection& lastLine = subPath.getReference (subPath.size() - 1);
  72432. if (isClosed)
  72433. {
  72434. const LineSection& l = subPath.getReference (0);
  72435. addEdgeAndJoint (destPath, jointStyle,
  72436. maxMiterExtensionSquared, width,
  72437. lastX1, lastY1, lastX2, lastY2,
  72438. l.lx1, l.ly1, l.lx2, l.ly2,
  72439. l.x1, l.y1);
  72440. destPath.closeSubPath();
  72441. destPath.startNewSubPath (lastLine.rx1, lastLine.ry1);
  72442. }
  72443. else
  72444. {
  72445. destPath.lineTo (lastX2, lastY2);
  72446. addLineEnd (destPath, endStyle,
  72447. lastX2, lastY2,
  72448. lastLine.rx1, lastLine.ry1,
  72449. width);
  72450. }
  72451. lastX1 = lastLine.rx1;
  72452. lastY1 = lastLine.ry1;
  72453. lastX2 = lastLine.rx2;
  72454. lastY2 = lastLine.ry2;
  72455. for (i = subPath.size() - 1; --i >= 0;)
  72456. {
  72457. const LineSection& l = subPath.getReference (i);
  72458. addEdgeAndJoint (destPath, jointStyle,
  72459. maxMiterExtensionSquared, width,
  72460. lastX1, lastY1, lastX2, lastY2,
  72461. l.rx1, l.ry1, l.rx2, l.ry2,
  72462. l.x2, l.y2);
  72463. lastX1 = l.rx1;
  72464. lastY1 = l.ry1;
  72465. lastX2 = l.rx2;
  72466. lastY2 = l.ry2;
  72467. }
  72468. if (isClosed)
  72469. {
  72470. addEdgeAndJoint (destPath, jointStyle,
  72471. maxMiterExtensionSquared, width,
  72472. lastX1, lastY1, lastX2, lastY2,
  72473. lastLine.rx1, lastLine.ry1, lastLine.rx2, lastLine.ry2,
  72474. lastLine.x2, lastLine.y2);
  72475. }
  72476. else
  72477. {
  72478. // do the last line
  72479. destPath.lineTo (lastX2, lastY2);
  72480. }
  72481. destPath.closeSubPath();
  72482. }
  72483. }
  72484. void PathStrokeType::createStrokedPath (Path& destPath,
  72485. const Path& source,
  72486. const AffineTransform& transform,
  72487. const float extraAccuracy) const
  72488. {
  72489. if (thickness <= 0)
  72490. {
  72491. destPath.clear();
  72492. return;
  72493. }
  72494. const Path* sourcePath = &source;
  72495. Path temp;
  72496. if (sourcePath == &destPath)
  72497. {
  72498. destPath.swapWithPath (temp);
  72499. sourcePath = &temp;
  72500. }
  72501. else
  72502. {
  72503. destPath.clear();
  72504. }
  72505. destPath.setUsingNonZeroWinding (true);
  72506. const float maxMiterExtensionSquared = 9.0f * thickness * thickness;
  72507. const float width = 0.5f * thickness;
  72508. // Iterate the path, creating a list of the
  72509. // left/right-hand lines along either side of it...
  72510. PathFlatteningIterator it (*sourcePath, transform, 9.0f / extraAccuracy);
  72511. using namespace PathFunctions;
  72512. Array <LineSection> subPath;
  72513. LineSection l;
  72514. l.x1 = 0;
  72515. l.y1 = 0;
  72516. const float minSegmentLength = 2.0f / (extraAccuracy * extraAccuracy);
  72517. while (it.next())
  72518. {
  72519. if (it.subPathIndex == 0)
  72520. {
  72521. if (subPath.size() > 0)
  72522. {
  72523. addSubPath (destPath, subPath, false, width, maxMiterExtensionSquared, jointStyle, endStyle);
  72524. subPath.clearQuick();
  72525. }
  72526. l.x1 = it.x1;
  72527. l.y1 = it.y1;
  72528. }
  72529. l.x2 = it.x2;
  72530. l.y2 = it.y2;
  72531. float dx = l.x2 - l.x1;
  72532. float dy = l.y2 - l.y1;
  72533. const float hypotSquared = dx*dx + dy*dy;
  72534. if (it.closesSubPath || hypotSquared > minSegmentLength || it.isLastInSubpath())
  72535. {
  72536. const float len = sqrtf (hypotSquared);
  72537. if (len == 0)
  72538. {
  72539. l.rx1 = l.rx2 = l.lx1 = l.lx2 = l.x1;
  72540. l.ry1 = l.ry2 = l.ly1 = l.ly2 = l.y1;
  72541. }
  72542. else
  72543. {
  72544. const float offset = width / len;
  72545. dx *= offset;
  72546. dy *= offset;
  72547. l.rx2 = l.x1 - dy;
  72548. l.ry2 = l.y1 + dx;
  72549. l.lx1 = l.x1 + dy;
  72550. l.ly1 = l.y1 - dx;
  72551. l.lx2 = l.x2 + dy;
  72552. l.ly2 = l.y2 - dx;
  72553. l.rx1 = l.x2 - dy;
  72554. l.ry1 = l.y2 + dx;
  72555. }
  72556. subPath.add (l);
  72557. if (it.closesSubPath)
  72558. {
  72559. addSubPath (destPath, subPath, true, width, maxMiterExtensionSquared, jointStyle, endStyle);
  72560. subPath.clearQuick();
  72561. }
  72562. else
  72563. {
  72564. l.x1 = it.x2;
  72565. l.y1 = it.y2;
  72566. }
  72567. }
  72568. }
  72569. if (subPath.size() > 0)
  72570. addSubPath (destPath, subPath, false, width, maxMiterExtensionSquared, jointStyle, endStyle);
  72571. }
  72572. void PathStrokeType::createDashedStroke (Path& destPath,
  72573. const Path& sourcePath,
  72574. const float* dashLengths,
  72575. int numDashLengths,
  72576. const AffineTransform& transform,
  72577. const float extraAccuracy) const
  72578. {
  72579. if (thickness <= 0)
  72580. return;
  72581. // this should really be an even number..
  72582. jassert ((numDashLengths & 1) == 0);
  72583. Path newDestPath;
  72584. PathFlatteningIterator it (sourcePath, transform, 9.0f / extraAccuracy);
  72585. bool first = true;
  72586. int dashNum = 0;
  72587. float pos = 0.0f, lineLen = 0.0f, lineEndPos = 0.0f;
  72588. float dx = 0.0f, dy = 0.0f;
  72589. for (;;)
  72590. {
  72591. const bool isSolid = ((dashNum & 1) == 0);
  72592. const float dashLen = dashLengths [dashNum++ % numDashLengths];
  72593. jassert (dashLen > 0); // must be a positive increment!
  72594. if (dashLen <= 0)
  72595. break;
  72596. pos += dashLen;
  72597. while (pos > lineEndPos)
  72598. {
  72599. if (! it.next())
  72600. {
  72601. if (isSolid && ! first)
  72602. newDestPath.lineTo (it.x2, it.y2);
  72603. createStrokedPath (destPath, newDestPath, AffineTransform::identity, extraAccuracy);
  72604. return;
  72605. }
  72606. if (isSolid && ! first)
  72607. newDestPath.lineTo (it.x1, it.y1);
  72608. else
  72609. newDestPath.startNewSubPath (it.x1, it.y1);
  72610. dx = it.x2 - it.x1;
  72611. dy = it.y2 - it.y1;
  72612. lineLen = juce_hypotf (dx, dy);
  72613. lineEndPos += lineLen;
  72614. first = it.closesSubPath;
  72615. }
  72616. const float alpha = (pos - (lineEndPos - lineLen)) / lineLen;
  72617. if (isSolid)
  72618. newDestPath.lineTo (it.x1 + dx * alpha,
  72619. it.y1 + dy * alpha);
  72620. else
  72621. newDestPath.startNewSubPath (it.x1 + dx * alpha,
  72622. it.y1 + dy * alpha);
  72623. }
  72624. }
  72625. END_JUCE_NAMESPACE
  72626. /*** End of inlined file: juce_PathStrokeType.cpp ***/
  72627. /*** Start of inlined file: juce_PositionedRectangle.cpp ***/
  72628. BEGIN_JUCE_NAMESPACE
  72629. PositionedRectangle::PositionedRectangle() throw()
  72630. : x (0.0),
  72631. y (0.0),
  72632. w (0.0),
  72633. h (0.0),
  72634. xMode (anchorAtLeftOrTop | absoluteFromParentTopLeft),
  72635. yMode (anchorAtLeftOrTop | absoluteFromParentTopLeft),
  72636. wMode (absoluteSize),
  72637. hMode (absoluteSize)
  72638. {
  72639. }
  72640. PositionedRectangle::PositionedRectangle (const PositionedRectangle& other) throw()
  72641. : x (other.x),
  72642. y (other.y),
  72643. w (other.w),
  72644. h (other.h),
  72645. xMode (other.xMode),
  72646. yMode (other.yMode),
  72647. wMode (other.wMode),
  72648. hMode (other.hMode)
  72649. {
  72650. }
  72651. PositionedRectangle& PositionedRectangle::operator= (const PositionedRectangle& other) throw()
  72652. {
  72653. x = other.x;
  72654. y = other.y;
  72655. w = other.w;
  72656. h = other.h;
  72657. xMode = other.xMode;
  72658. yMode = other.yMode;
  72659. wMode = other.wMode;
  72660. hMode = other.hMode;
  72661. return *this;
  72662. }
  72663. PositionedRectangle::~PositionedRectangle() throw()
  72664. {
  72665. }
  72666. bool PositionedRectangle::operator== (const PositionedRectangle& other) const throw()
  72667. {
  72668. return x == other.x
  72669. && y == other.y
  72670. && w == other.w
  72671. && h == other.h
  72672. && xMode == other.xMode
  72673. && yMode == other.yMode
  72674. && wMode == other.wMode
  72675. && hMode == other.hMode;
  72676. }
  72677. bool PositionedRectangle::operator!= (const PositionedRectangle& other) const throw()
  72678. {
  72679. return ! operator== (other);
  72680. }
  72681. PositionedRectangle::PositionedRectangle (const String& stringVersion) throw()
  72682. {
  72683. StringArray tokens;
  72684. tokens.addTokens (stringVersion, false);
  72685. decodePosString (tokens [0], xMode, x);
  72686. decodePosString (tokens [1], yMode, y);
  72687. decodeSizeString (tokens [2], wMode, w);
  72688. decodeSizeString (tokens [3], hMode, h);
  72689. }
  72690. const String PositionedRectangle::toString() const throw()
  72691. {
  72692. String s;
  72693. s.preallocateStorage (12);
  72694. addPosDescription (s, xMode, x);
  72695. s << ' ';
  72696. addPosDescription (s, yMode, y);
  72697. s << ' ';
  72698. addSizeDescription (s, wMode, w);
  72699. s << ' ';
  72700. addSizeDescription (s, hMode, h);
  72701. return s;
  72702. }
  72703. const Rectangle<int> PositionedRectangle::getRectangle (const Rectangle<int>& target) const throw()
  72704. {
  72705. jassert (! target.isEmpty());
  72706. double x_, y_, w_, h_;
  72707. applyPosAndSize (x_, w_, x, w, xMode, wMode, target.getX(), target.getWidth());
  72708. applyPosAndSize (y_, h_, y, h, yMode, hMode, target.getY(), target.getHeight());
  72709. return Rectangle<int> (roundToInt (x_), roundToInt (y_),
  72710. roundToInt (w_), roundToInt (h_));
  72711. }
  72712. void PositionedRectangle::getRectangleDouble (const Rectangle<int>& target,
  72713. double& x_, double& y_,
  72714. double& w_, double& h_) const throw()
  72715. {
  72716. jassert (! target.isEmpty());
  72717. applyPosAndSize (x_, w_, x, w, xMode, wMode, target.getX(), target.getWidth());
  72718. applyPosAndSize (y_, h_, y, h, yMode, hMode, target.getY(), target.getHeight());
  72719. }
  72720. void PositionedRectangle::applyToComponent (Component& comp) const throw()
  72721. {
  72722. comp.setBounds (getRectangle (Rectangle<int> (0, 0, comp.getParentWidth(), comp.getParentHeight())));
  72723. }
  72724. void PositionedRectangle::updateFrom (const Rectangle<int>& rectangle,
  72725. const Rectangle<int>& target) throw()
  72726. {
  72727. updatePosAndSize (x, w, rectangle.getX(), rectangle.getWidth(), xMode, wMode, target.getX(), target.getWidth());
  72728. updatePosAndSize (y, h, rectangle.getY(), rectangle.getHeight(), yMode, hMode, target.getY(), target.getHeight());
  72729. }
  72730. void PositionedRectangle::updateFromDouble (const double newX, const double newY,
  72731. const double newW, const double newH,
  72732. const Rectangle<int>& target) throw()
  72733. {
  72734. updatePosAndSize (x, w, newX, newW, xMode, wMode, target.getX(), target.getWidth());
  72735. updatePosAndSize (y, h, newY, newH, yMode, hMode, target.getY(), target.getHeight());
  72736. }
  72737. void PositionedRectangle::updateFromComponent (const Component& comp) throw()
  72738. {
  72739. if (comp.getParentComponent() == 0 && ! comp.isOnDesktop())
  72740. updateFrom (comp.getBounds(), Rectangle<int>());
  72741. else
  72742. updateFrom (comp.getBounds(), Rectangle<int> (0, 0, comp.getParentWidth(), comp.getParentHeight()));
  72743. }
  72744. PositionedRectangle::AnchorPoint PositionedRectangle::getAnchorPointX() const throw()
  72745. {
  72746. return (AnchorPoint) (xMode & (anchorAtLeftOrTop | anchorAtRightOrBottom | anchorAtCentre));
  72747. }
  72748. PositionedRectangle::PositionMode PositionedRectangle::getPositionModeX() const throw()
  72749. {
  72750. return (PositionMode) (xMode & (absoluteFromParentTopLeft
  72751. | absoluteFromParentBottomRight
  72752. | absoluteFromParentCentre
  72753. | proportionOfParentSize));
  72754. }
  72755. PositionedRectangle::AnchorPoint PositionedRectangle::getAnchorPointY() const throw()
  72756. {
  72757. return (AnchorPoint) (yMode & (anchorAtLeftOrTop | anchorAtRightOrBottom | anchorAtCentre));
  72758. }
  72759. PositionedRectangle::PositionMode PositionedRectangle::getPositionModeY() const throw()
  72760. {
  72761. return (PositionMode) (yMode & (absoluteFromParentTopLeft
  72762. | absoluteFromParentBottomRight
  72763. | absoluteFromParentCentre
  72764. | proportionOfParentSize));
  72765. }
  72766. PositionedRectangle::SizeMode PositionedRectangle::getWidthMode() const throw()
  72767. {
  72768. return (SizeMode) wMode;
  72769. }
  72770. PositionedRectangle::SizeMode PositionedRectangle::getHeightMode() const throw()
  72771. {
  72772. return (SizeMode) hMode;
  72773. }
  72774. void PositionedRectangle::setModes (const AnchorPoint xAnchor,
  72775. const PositionMode xMode_,
  72776. const AnchorPoint yAnchor,
  72777. const PositionMode yMode_,
  72778. const SizeMode widthMode,
  72779. const SizeMode heightMode,
  72780. const Rectangle<int>& target) throw()
  72781. {
  72782. if (xMode != (xAnchor | xMode_) || wMode != widthMode)
  72783. {
  72784. double tx, tw;
  72785. applyPosAndSize (tx, tw, x, w, xMode, wMode, target.getX(), target.getWidth());
  72786. xMode = (uint8) (xAnchor | xMode_);
  72787. wMode = (uint8) widthMode;
  72788. updatePosAndSize (x, w, tx, tw, xMode, wMode, target.getX(), target.getWidth());
  72789. }
  72790. if (yMode != (yAnchor | yMode_) || hMode != heightMode)
  72791. {
  72792. double ty, th;
  72793. applyPosAndSize (ty, th, y, h, yMode, hMode, target.getY(), target.getHeight());
  72794. yMode = (uint8) (yAnchor | yMode_);
  72795. hMode = (uint8) heightMode;
  72796. updatePosAndSize (y, h, ty, th, yMode, hMode, target.getY(), target.getHeight());
  72797. }
  72798. }
  72799. bool PositionedRectangle::isPositionAbsolute() const throw()
  72800. {
  72801. return xMode == absoluteFromParentTopLeft
  72802. && yMode == absoluteFromParentTopLeft
  72803. && wMode == absoluteSize
  72804. && hMode == absoluteSize;
  72805. }
  72806. void PositionedRectangle::addPosDescription (String& s, const uint8 mode, const double value) const throw()
  72807. {
  72808. if ((mode & proportionOfParentSize) != 0)
  72809. {
  72810. s << (roundToInt (value * 100000.0) / 1000.0) << '%';
  72811. }
  72812. else
  72813. {
  72814. s << (roundToInt (value * 100.0) / 100.0);
  72815. if ((mode & absoluteFromParentBottomRight) != 0)
  72816. s << 'R';
  72817. else if ((mode & absoluteFromParentCentre) != 0)
  72818. s << 'C';
  72819. }
  72820. if ((mode & anchorAtRightOrBottom) != 0)
  72821. s << 'r';
  72822. else if ((mode & anchorAtCentre) != 0)
  72823. s << 'c';
  72824. }
  72825. void PositionedRectangle::addSizeDescription (String& s, const uint8 mode, const double value) const throw()
  72826. {
  72827. if (mode == proportionalSize)
  72828. s << (roundToInt (value * 100000.0) / 1000.0) << '%';
  72829. else if (mode == parentSizeMinusAbsolute)
  72830. s << (roundToInt (value * 100.0) / 100.0) << 'M';
  72831. else
  72832. s << (roundToInt (value * 100.0) / 100.0);
  72833. }
  72834. void PositionedRectangle::decodePosString (const String& s, uint8& mode, double& value) throw()
  72835. {
  72836. if (s.containsChar ('r'))
  72837. mode = anchorAtRightOrBottom;
  72838. else if (s.containsChar ('c'))
  72839. mode = anchorAtCentre;
  72840. else
  72841. mode = anchorAtLeftOrTop;
  72842. if (s.containsChar ('%'))
  72843. {
  72844. mode |= proportionOfParentSize;
  72845. value = s.removeCharacters ("%rcRC").getDoubleValue() / 100.0;
  72846. }
  72847. else
  72848. {
  72849. if (s.containsChar ('R'))
  72850. mode |= absoluteFromParentBottomRight;
  72851. else if (s.containsChar ('C'))
  72852. mode |= absoluteFromParentCentre;
  72853. else
  72854. mode |= absoluteFromParentTopLeft;
  72855. value = s.removeCharacters ("rcRC").getDoubleValue();
  72856. }
  72857. }
  72858. void PositionedRectangle::decodeSizeString (const String& s, uint8& mode, double& value) throw()
  72859. {
  72860. if (s.containsChar ('%'))
  72861. {
  72862. mode = proportionalSize;
  72863. value = s.upToFirstOccurrenceOf ("%", false, false).getDoubleValue() / 100.0;
  72864. }
  72865. else if (s.containsChar ('M'))
  72866. {
  72867. mode = parentSizeMinusAbsolute;
  72868. value = s.getDoubleValue();
  72869. }
  72870. else
  72871. {
  72872. mode = absoluteSize;
  72873. value = s.getDoubleValue();
  72874. }
  72875. }
  72876. void PositionedRectangle::applyPosAndSize (double& xOut, double& wOut,
  72877. const double x_, const double w_,
  72878. const uint8 xMode_, const uint8 wMode_,
  72879. const int parentPos,
  72880. const int parentSize) const throw()
  72881. {
  72882. if (wMode_ == proportionalSize)
  72883. wOut = roundToInt (w_ * parentSize);
  72884. else if (wMode_ == parentSizeMinusAbsolute)
  72885. wOut = jmax (0, parentSize - roundToInt (w_));
  72886. else
  72887. wOut = roundToInt (w_);
  72888. if ((xMode_ & proportionOfParentSize) != 0)
  72889. xOut = parentPos + x_ * parentSize;
  72890. else if ((xMode_ & absoluteFromParentBottomRight) != 0)
  72891. xOut = (parentPos + parentSize) - x_;
  72892. else if ((xMode_ & absoluteFromParentCentre) != 0)
  72893. xOut = x_ + (parentPos + parentSize / 2);
  72894. else
  72895. xOut = x_ + parentPos;
  72896. if ((xMode_ & anchorAtRightOrBottom) != 0)
  72897. xOut -= wOut;
  72898. else if ((xMode_ & anchorAtCentre) != 0)
  72899. xOut -= wOut / 2;
  72900. }
  72901. void PositionedRectangle::updatePosAndSize (double& xOut, double& wOut,
  72902. double x_, const double w_,
  72903. const uint8 xMode_, const uint8 wMode_,
  72904. const int parentPos,
  72905. const int parentSize) const throw()
  72906. {
  72907. if (wMode_ == proportionalSize)
  72908. {
  72909. if (parentSize > 0)
  72910. wOut = w_ / parentSize;
  72911. }
  72912. else if (wMode_ == parentSizeMinusAbsolute)
  72913. wOut = parentSize - w_;
  72914. else
  72915. wOut = w_;
  72916. if ((xMode_ & anchorAtRightOrBottom) != 0)
  72917. x_ += w_;
  72918. else if ((xMode_ & anchorAtCentre) != 0)
  72919. x_ += w_ / 2;
  72920. if ((xMode_ & proportionOfParentSize) != 0)
  72921. {
  72922. if (parentSize > 0)
  72923. xOut = (x_ - parentPos) / parentSize;
  72924. }
  72925. else if ((xMode_ & absoluteFromParentBottomRight) != 0)
  72926. xOut = (parentPos + parentSize) - x_;
  72927. else if ((xMode_ & absoluteFromParentCentre) != 0)
  72928. xOut = x_ - (parentPos + parentSize / 2);
  72929. else
  72930. xOut = x_ - parentPos;
  72931. }
  72932. END_JUCE_NAMESPACE
  72933. /*** End of inlined file: juce_PositionedRectangle.cpp ***/
  72934. /*** Start of inlined file: juce_RectangleList.cpp ***/
  72935. BEGIN_JUCE_NAMESPACE
  72936. RectangleList::RectangleList() throw()
  72937. {
  72938. }
  72939. RectangleList::RectangleList (const Rectangle<int>& rect)
  72940. {
  72941. if (! rect.isEmpty())
  72942. rects.add (rect);
  72943. }
  72944. RectangleList::RectangleList (const RectangleList& other)
  72945. : rects (other.rects)
  72946. {
  72947. }
  72948. RectangleList& RectangleList::operator= (const RectangleList& other)
  72949. {
  72950. rects = other.rects;
  72951. return *this;
  72952. }
  72953. RectangleList::~RectangleList()
  72954. {
  72955. }
  72956. void RectangleList::clear()
  72957. {
  72958. rects.clearQuick();
  72959. }
  72960. const Rectangle<int> RectangleList::getRectangle (const int index) const throw()
  72961. {
  72962. if (((unsigned int) index) < (unsigned int) rects.size())
  72963. return rects.getReference (index);
  72964. return Rectangle<int>();
  72965. }
  72966. bool RectangleList::isEmpty() const throw()
  72967. {
  72968. return rects.size() == 0;
  72969. }
  72970. RectangleList::Iterator::Iterator (const RectangleList& list) throw()
  72971. : current (0),
  72972. owner (list),
  72973. index (list.rects.size())
  72974. {
  72975. }
  72976. RectangleList::Iterator::~Iterator()
  72977. {
  72978. }
  72979. bool RectangleList::Iterator::next() throw()
  72980. {
  72981. if (--index >= 0)
  72982. {
  72983. current = & (owner.rects.getReference (index));
  72984. return true;
  72985. }
  72986. return false;
  72987. }
  72988. void RectangleList::add (const Rectangle<int>& rect)
  72989. {
  72990. if (! rect.isEmpty())
  72991. {
  72992. if (rects.size() == 0)
  72993. {
  72994. rects.add (rect);
  72995. }
  72996. else
  72997. {
  72998. bool anyOverlaps = false;
  72999. int i;
  73000. for (i = rects.size(); --i >= 0;)
  73001. {
  73002. Rectangle<int>& ourRect = rects.getReference (i);
  73003. if (rect.intersects (ourRect))
  73004. {
  73005. if (rect.contains (ourRect))
  73006. rects.remove (i);
  73007. else if (! ourRect.reduceIfPartlyContainedIn (rect))
  73008. anyOverlaps = true;
  73009. }
  73010. }
  73011. if (anyOverlaps && rects.size() > 0)
  73012. {
  73013. RectangleList r (rect);
  73014. for (i = rects.size(); --i >= 0;)
  73015. {
  73016. const Rectangle<int>& ourRect = rects.getReference (i);
  73017. if (rect.intersects (ourRect))
  73018. {
  73019. r.subtract (ourRect);
  73020. if (r.rects.size() == 0)
  73021. return;
  73022. }
  73023. }
  73024. for (i = r.getNumRectangles(); --i >= 0;)
  73025. rects.add (r.rects.getReference (i));
  73026. }
  73027. else
  73028. {
  73029. rects.add (rect);
  73030. }
  73031. }
  73032. }
  73033. }
  73034. void RectangleList::addWithoutMerging (const Rectangle<int>& rect)
  73035. {
  73036. rects.add (rect);
  73037. }
  73038. void RectangleList::add (const int x, const int y, const int w, const int h)
  73039. {
  73040. if (rects.size() == 0)
  73041. {
  73042. if (w > 0 && h > 0)
  73043. rects.add (Rectangle<int> (x, y, w, h));
  73044. }
  73045. else
  73046. {
  73047. add (Rectangle<int> (x, y, w, h));
  73048. }
  73049. }
  73050. void RectangleList::add (const RectangleList& other)
  73051. {
  73052. for (int i = 0; i < other.rects.size(); ++i)
  73053. add (other.rects.getReference (i));
  73054. }
  73055. void RectangleList::subtract (const Rectangle<int>& rect)
  73056. {
  73057. const int originalNumRects = rects.size();
  73058. if (originalNumRects > 0)
  73059. {
  73060. const int x1 = rect.x;
  73061. const int y1 = rect.y;
  73062. const int x2 = x1 + rect.w;
  73063. const int y2 = y1 + rect.h;
  73064. for (int i = getNumRectangles(); --i >= 0;)
  73065. {
  73066. Rectangle<int>& r = rects.getReference (i);
  73067. const int rx1 = r.x;
  73068. const int ry1 = r.y;
  73069. const int rx2 = rx1 + r.w;
  73070. const int ry2 = ry1 + r.h;
  73071. if (! (x2 <= rx1 || x1 >= rx2 || y2 <= ry1 || y1 >= ry2))
  73072. {
  73073. if (x1 > rx1 && x1 < rx2)
  73074. {
  73075. if (y1 <= ry1 && y2 >= ry2 && x2 >= rx2)
  73076. {
  73077. r.w = x1 - rx1;
  73078. }
  73079. else
  73080. {
  73081. r.x = x1;
  73082. r.w = rx2 - x1;
  73083. rects.insert (i + 1, Rectangle<int> (rx1, ry1, x1 - rx1, ry2 - ry1));
  73084. i += 2;
  73085. }
  73086. }
  73087. else if (x2 > rx1 && x2 < rx2)
  73088. {
  73089. r.x = x2;
  73090. r.w = rx2 - x2;
  73091. if (y1 > ry1 || y2 < ry2 || x1 > rx1)
  73092. {
  73093. rects.insert (i + 1, Rectangle<int> (rx1, ry1, x2 - rx1, ry2 - ry1));
  73094. i += 2;
  73095. }
  73096. }
  73097. else if (y1 > ry1 && y1 < ry2)
  73098. {
  73099. if (x1 <= rx1 && x2 >= rx2 && y2 >= ry2)
  73100. {
  73101. r.h = y1 - ry1;
  73102. }
  73103. else
  73104. {
  73105. r.y = y1;
  73106. r.h = ry2 - y1;
  73107. rects.insert (i + 1, Rectangle<int> (rx1, ry1, rx2 - rx1, y1 - ry1));
  73108. i += 2;
  73109. }
  73110. }
  73111. else if (y2 > ry1 && y2 < ry2)
  73112. {
  73113. r.y = y2;
  73114. r.h = ry2 - y2;
  73115. if (x1 > rx1 || x2 < rx2 || y1 > ry1)
  73116. {
  73117. rects.insert (i + 1, Rectangle<int> (rx1, ry1, rx2 - rx1, y2 - ry1));
  73118. i += 2;
  73119. }
  73120. }
  73121. else
  73122. {
  73123. rects.remove (i);
  73124. }
  73125. }
  73126. }
  73127. if (rects.size() > originalNumRects + 10)
  73128. consolidate();
  73129. }
  73130. }
  73131. void RectangleList::subtract (const RectangleList& otherList)
  73132. {
  73133. for (int i = otherList.rects.size(); --i >= 0;)
  73134. subtract (otherList.rects.getReference (i));
  73135. }
  73136. bool RectangleList::clipTo (const Rectangle<int>& rect)
  73137. {
  73138. bool notEmpty = false;
  73139. if (rect.isEmpty())
  73140. {
  73141. clear();
  73142. }
  73143. else
  73144. {
  73145. for (int i = rects.size(); --i >= 0;)
  73146. {
  73147. Rectangle<int>& r = rects.getReference (i);
  73148. if (! rect.intersectRectangle (r.x, r.y, r.w, r.h))
  73149. rects.remove (i);
  73150. else
  73151. notEmpty = true;
  73152. }
  73153. }
  73154. return notEmpty;
  73155. }
  73156. bool RectangleList::clipTo (const RectangleList& other)
  73157. {
  73158. if (rects.size() == 0)
  73159. return false;
  73160. RectangleList result;
  73161. for (int j = 0; j < rects.size(); ++j)
  73162. {
  73163. const Rectangle<int>& rect = rects.getReference (j);
  73164. for (int i = other.rects.size(); --i >= 0;)
  73165. {
  73166. Rectangle<int> r (other.rects.getReference (i));
  73167. if (rect.intersectRectangle (r.x, r.y, r.w, r.h))
  73168. result.rects.add (r);
  73169. }
  73170. }
  73171. swapWith (result);
  73172. return ! isEmpty();
  73173. }
  73174. bool RectangleList::getIntersectionWith (const Rectangle<int>& rect, RectangleList& destRegion) const
  73175. {
  73176. destRegion.clear();
  73177. if (! rect.isEmpty())
  73178. {
  73179. for (int i = rects.size(); --i >= 0;)
  73180. {
  73181. Rectangle<int> r (rects.getReference (i));
  73182. if (rect.intersectRectangle (r.x, r.y, r.w, r.h))
  73183. destRegion.rects.add (r);
  73184. }
  73185. }
  73186. return destRegion.rects.size() > 0;
  73187. }
  73188. void RectangleList::swapWith (RectangleList& otherList) throw()
  73189. {
  73190. rects.swapWithArray (otherList.rects);
  73191. }
  73192. void RectangleList::consolidate()
  73193. {
  73194. int i;
  73195. for (i = 0; i < getNumRectangles() - 1; ++i)
  73196. {
  73197. Rectangle<int>& r = rects.getReference (i);
  73198. const int rx1 = r.x;
  73199. const int ry1 = r.y;
  73200. const int rx2 = rx1 + r.w;
  73201. const int ry2 = ry1 + r.h;
  73202. for (int j = rects.size(); --j > i;)
  73203. {
  73204. Rectangle<int>& r2 = rects.getReference (j);
  73205. const int jrx1 = r2.x;
  73206. const int jry1 = r2.y;
  73207. const int jrx2 = jrx1 + r2.w;
  73208. const int jry2 = jry1 + r2.h;
  73209. // if the vertical edges of any blocks are touching and their horizontals don't
  73210. // line up, split them horizontally..
  73211. if (jrx1 == rx2 || jrx2 == rx1)
  73212. {
  73213. if (jry1 > ry1 && jry1 < ry2)
  73214. {
  73215. r.h = jry1 - ry1;
  73216. rects.add (Rectangle<int> (rx1, jry1, rx2 - rx1, ry2 - jry1));
  73217. i = -1;
  73218. break;
  73219. }
  73220. if (jry2 > ry1 && jry2 < ry2)
  73221. {
  73222. r.h = jry2 - ry1;
  73223. rects.add (Rectangle<int> (rx1, jry2, rx2 - rx1, ry2 - jry2));
  73224. i = -1;
  73225. break;
  73226. }
  73227. else if (ry1 > jry1 && ry1 < jry2)
  73228. {
  73229. r2.h = ry1 - jry1;
  73230. rects.add (Rectangle<int> (jrx1, ry1, jrx2 - jrx1, jry2 - ry1));
  73231. i = -1;
  73232. break;
  73233. }
  73234. else if (ry2 > jry1 && ry2 < jry2)
  73235. {
  73236. r2.h = ry2 - jry1;
  73237. rects.add (Rectangle<int> (jrx1, ry2, jrx2 - jrx1, jry2 - ry2));
  73238. i = -1;
  73239. break;
  73240. }
  73241. }
  73242. }
  73243. }
  73244. for (i = 0; i < rects.size() - 1; ++i)
  73245. {
  73246. Rectangle<int>& r = rects.getReference (i);
  73247. for (int j = rects.size(); --j > i;)
  73248. {
  73249. if (r.enlargeIfAdjacent (rects.getReference (j)))
  73250. {
  73251. rects.remove (j);
  73252. i = -1;
  73253. break;
  73254. }
  73255. }
  73256. }
  73257. }
  73258. bool RectangleList::containsPoint (const int x, const int y) const throw()
  73259. {
  73260. for (int i = getNumRectangles(); --i >= 0;)
  73261. if (rects.getReference (i).contains (x, y))
  73262. return true;
  73263. return false;
  73264. }
  73265. bool RectangleList::containsRectangle (const Rectangle<int>& rectangleToCheck) const
  73266. {
  73267. if (rects.size() > 1)
  73268. {
  73269. RectangleList r (rectangleToCheck);
  73270. for (int i = rects.size(); --i >= 0;)
  73271. {
  73272. r.subtract (rects.getReference (i));
  73273. if (r.rects.size() == 0)
  73274. return true;
  73275. }
  73276. }
  73277. else if (rects.size() > 0)
  73278. {
  73279. return rects.getReference (0).contains (rectangleToCheck);
  73280. }
  73281. return false;
  73282. }
  73283. bool RectangleList::intersectsRectangle (const Rectangle<int>& rectangleToCheck) const throw()
  73284. {
  73285. for (int i = rects.size(); --i >= 0;)
  73286. if (rects.getReference (i).intersects (rectangleToCheck))
  73287. return true;
  73288. return false;
  73289. }
  73290. bool RectangleList::intersects (const RectangleList& other) const throw()
  73291. {
  73292. for (int i = rects.size(); --i >= 0;)
  73293. if (other.intersectsRectangle (rects.getReference (i)))
  73294. return true;
  73295. return false;
  73296. }
  73297. const Rectangle<int> RectangleList::getBounds() const throw()
  73298. {
  73299. if (rects.size() <= 1)
  73300. {
  73301. if (rects.size() == 0)
  73302. return Rectangle<int>();
  73303. else
  73304. return rects.getReference (0);
  73305. }
  73306. else
  73307. {
  73308. const Rectangle<int>& r = rects.getReference (0);
  73309. int minX = r.x;
  73310. int minY = r.y;
  73311. int maxX = minX + r.w;
  73312. int maxY = minY + r.h;
  73313. for (int i = rects.size(); --i > 0;)
  73314. {
  73315. const Rectangle<int>& r2 = rects.getReference (i);
  73316. minX = jmin (minX, r2.x);
  73317. minY = jmin (minY, r2.y);
  73318. maxX = jmax (maxX, r2.getRight());
  73319. maxY = jmax (maxY, r2.getBottom());
  73320. }
  73321. return Rectangle<int> (minX, minY, maxX - minX, maxY - minY);
  73322. }
  73323. }
  73324. void RectangleList::offsetAll (const int dx, const int dy) throw()
  73325. {
  73326. for (int i = rects.size(); --i >= 0;)
  73327. {
  73328. Rectangle<int>& r = rects.getReference (i);
  73329. r.x += dx;
  73330. r.y += dy;
  73331. }
  73332. }
  73333. const Path RectangleList::toPath() const
  73334. {
  73335. Path p;
  73336. for (int i = rects.size(); --i >= 0;)
  73337. {
  73338. const Rectangle<int>& r = rects.getReference (i);
  73339. p.addRectangle ((float) r.x,
  73340. (float) r.y,
  73341. (float) r.w,
  73342. (float) r.h);
  73343. }
  73344. return p;
  73345. }
  73346. END_JUCE_NAMESPACE
  73347. /*** End of inlined file: juce_RectangleList.cpp ***/
  73348. /*** Start of inlined file: juce_Image.cpp ***/
  73349. BEGIN_JUCE_NAMESPACE
  73350. static const int fullAlphaThreshold = 253;
  73351. Image::Image (const PixelFormat format_,
  73352. const int imageWidth_,
  73353. const int imageHeight_)
  73354. : format (format_),
  73355. imageWidth (imageWidth_),
  73356. imageHeight (imageHeight_),
  73357. imageData (0)
  73358. {
  73359. jassert (format_ == RGB || format_ == ARGB || format_ == SingleChannel);
  73360. jassert (imageWidth_ > 0 && imageHeight_ > 0); // it's illegal to create a zero-sized image - the
  73361. // actual image will be at least 1x1.
  73362. }
  73363. Image::Image (const PixelFormat format_,
  73364. const int imageWidth_,
  73365. const int imageHeight_,
  73366. const bool clearImage)
  73367. : format (format_),
  73368. imageWidth (imageWidth_),
  73369. imageHeight (imageHeight_)
  73370. {
  73371. jassert (format_ == RGB || format_ == ARGB || format_ == SingleChannel);
  73372. jassert (imageWidth_ > 0 && imageHeight_ > 0); // it's illegal to create a zero-sized image - the
  73373. // actual image will be at least 1x1.
  73374. pixelStride = (format == RGB) ? 3 : ((format == ARGB) ? 4 : 1);
  73375. lineStride = (pixelStride * jmax (1, imageWidth_) + 3) & ~3;
  73376. imageDataAllocated.allocate (lineStride * jmax (1, imageHeight_), clearImage);
  73377. imageData = imageDataAllocated;
  73378. }
  73379. Image::Image (const Image& other)
  73380. : format (other.format),
  73381. imageWidth (other.imageWidth),
  73382. imageHeight (other.imageHeight)
  73383. {
  73384. pixelStride = (format == RGB) ? 3 : ((format == ARGB) ? 4 : 1);
  73385. lineStride = (pixelStride * jmax (1, imageWidth) + 3) & ~3;
  73386. imageDataAllocated.malloc (lineStride * jmax (1, imageHeight));
  73387. imageData = imageDataAllocated;
  73388. BitmapData srcData (other, 0, 0, imageWidth, imageHeight);
  73389. setPixelData (0, 0, imageWidth, imageHeight, srcData.data, srcData.lineStride);
  73390. }
  73391. Image::~Image()
  73392. {
  73393. }
  73394. LowLevelGraphicsContext* Image::createLowLevelContext()
  73395. {
  73396. return new LowLevelGraphicsSoftwareRenderer (*this);
  73397. }
  73398. Image::BitmapData::BitmapData (Image& image, int x, int y, int w, int h, const bool /*makeWritable*/)
  73399. : data (image.imageData + image.lineStride * y + image.pixelStride * x),
  73400. lineStride (image.lineStride),
  73401. pixelStride (image.pixelStride),
  73402. width (w),
  73403. height (h)
  73404. {
  73405. jassert (x >= 0 && y >= 0 && w > 0 && h > 0 && x + w <= image.getWidth() && y + h <= image.getHeight());
  73406. }
  73407. Image::BitmapData::BitmapData (const Image& image, int x, int y, int w, int h)
  73408. : data (image.imageData + image.lineStride * y + image.pixelStride * x),
  73409. lineStride (image.lineStride),
  73410. pixelStride (image.pixelStride),
  73411. width (w),
  73412. height (h)
  73413. {
  73414. jassert (x >= 0 && y >= 0 && w > 0 && h > 0 && x + w <= image.getWidth() && y + h <= image.getHeight());
  73415. }
  73416. Image::BitmapData::~BitmapData()
  73417. {
  73418. }
  73419. void Image::setPixelData (int x, int y, int w, int h,
  73420. const uint8* sourcePixelData, int sourceLineStride)
  73421. {
  73422. jassert (x >= 0 && y >= 0 && w > 0 && h > 0 && x + w <= imageWidth && y + h <= imageHeight);
  73423. if (Rectangle<int>::intersectRectangles (x, y, w, h, 0, 0, imageWidth, imageHeight))
  73424. {
  73425. const BitmapData dest (*this, x, y, w, h, true);
  73426. for (int i = 0; i < h; ++i)
  73427. {
  73428. memcpy (dest.getLinePointer(i),
  73429. sourcePixelData + sourceLineStride * i,
  73430. w * dest.pixelStride);
  73431. }
  73432. }
  73433. }
  73434. void Image::clear (int dx, int dy, int dw, int dh, const Colour& colourToClearTo)
  73435. {
  73436. if (Rectangle<int>::intersectRectangles (dx, dy, dw, dh, 0, 0, imageWidth, imageHeight))
  73437. {
  73438. const PixelARGB col (colourToClearTo.getPixelARGB());
  73439. const BitmapData destData (*this, dx, dy, dw, dh, true);
  73440. uint8* dest = destData.data;
  73441. while (--dh >= 0)
  73442. {
  73443. uint8* line = dest;
  73444. dest += destData.lineStride;
  73445. if (isARGB())
  73446. {
  73447. for (int x = dw; --x >= 0;)
  73448. {
  73449. ((PixelARGB*) line)->set (col);
  73450. line += destData.pixelStride;
  73451. }
  73452. }
  73453. else if (isRGB())
  73454. {
  73455. for (int x = dw; --x >= 0;)
  73456. {
  73457. ((PixelRGB*) line)->set (col);
  73458. line += destData.pixelStride;
  73459. }
  73460. }
  73461. else
  73462. {
  73463. for (int x = dw; --x >= 0;)
  73464. {
  73465. *line = col.getAlpha();
  73466. line += destData.pixelStride;
  73467. }
  73468. }
  73469. }
  73470. }
  73471. }
  73472. Image* Image::createCopy (int newWidth, int newHeight,
  73473. const Graphics::ResamplingQuality quality) const
  73474. {
  73475. if (newWidth < 0)
  73476. newWidth = imageWidth;
  73477. if (newHeight < 0)
  73478. newHeight = imageHeight;
  73479. Image* const newImage = Image::createNativeImage (format, newWidth, newHeight, true);
  73480. Graphics g (*newImage);
  73481. g.setImageResamplingQuality (quality);
  73482. g.drawImage (this,
  73483. 0, 0, newWidth, newHeight,
  73484. 0, 0, imageWidth, imageHeight,
  73485. false);
  73486. return newImage;
  73487. }
  73488. Image* Image::createCopyOfAlphaChannel() const
  73489. {
  73490. jassert (format != SingleChannel);
  73491. Image* const newImage = Image::createNativeImage (SingleChannel, imageWidth, imageHeight, false);
  73492. if (! hasAlphaChannel())
  73493. {
  73494. newImage->clear (0, 0, imageWidth, imageHeight, Colours::black);
  73495. }
  73496. else
  73497. {
  73498. const BitmapData destData (*newImage, 0, 0, imageWidth, imageHeight, true);
  73499. const BitmapData srcData (*this, 0, 0, imageWidth, imageHeight);
  73500. for (int y = 0; y < imageHeight; ++y)
  73501. {
  73502. const PixelARGB* src = (const PixelARGB*) srcData.getLinePointer(y);
  73503. uint8* dst = destData.getLinePointer (y);
  73504. for (int x = imageWidth; --x >= 0;)
  73505. {
  73506. *dst++ = src->getAlpha();
  73507. ++src;
  73508. }
  73509. }
  73510. }
  73511. return newImage;
  73512. }
  73513. const Colour Image::getPixelAt (const int x, const int y) const
  73514. {
  73515. Colour c;
  73516. if (((unsigned int) x) < (unsigned int) imageWidth
  73517. && ((unsigned int) y) < (unsigned int) imageHeight)
  73518. {
  73519. const BitmapData srcData (*this, x, y, 1, 1);
  73520. if (isARGB())
  73521. {
  73522. PixelARGB p (*(const PixelARGB*) srcData.data);
  73523. p.unpremultiply();
  73524. c = Colour (p.getARGB());
  73525. }
  73526. else if (isRGB())
  73527. c = Colour (((const PixelRGB*) srcData.data)->getARGB());
  73528. else
  73529. c = Colour ((uint8) 0, (uint8) 0, (uint8) 0, *(srcData.data));
  73530. }
  73531. return c;
  73532. }
  73533. void Image::setPixelAt (const int x, const int y,
  73534. const Colour& colour)
  73535. {
  73536. if (((unsigned int) x) < (unsigned int) imageWidth
  73537. && ((unsigned int) y) < (unsigned int) imageHeight)
  73538. {
  73539. const BitmapData destData (*this, x, y, 1, 1, true);
  73540. const PixelARGB col (colour.getPixelARGB());
  73541. if (isARGB())
  73542. ((PixelARGB*) destData.data)->set (col);
  73543. else if (isRGB())
  73544. ((PixelRGB*) destData.data)->set (col);
  73545. else
  73546. *(destData.data) = col.getAlpha();
  73547. }
  73548. }
  73549. void Image::multiplyAlphaAt (const int x, const int y,
  73550. const float multiplier)
  73551. {
  73552. if (((unsigned int) x) < (unsigned int) imageWidth
  73553. && ((unsigned int) y) < (unsigned int) imageHeight
  73554. && hasAlphaChannel())
  73555. {
  73556. const BitmapData destData (*this, x, y, 1, 1, true);
  73557. if (isARGB())
  73558. ((PixelARGB*) destData.data)->multiplyAlpha (multiplier);
  73559. else
  73560. *(destData.data) = (uint8) (*(destData.data) * multiplier);
  73561. }
  73562. }
  73563. void Image::multiplyAllAlphas (const float amountToMultiplyBy)
  73564. {
  73565. if (hasAlphaChannel())
  73566. {
  73567. const BitmapData destData (*this, 0, 0, getWidth(), getHeight(), true);
  73568. if (isARGB())
  73569. {
  73570. for (int y = 0; y < imageHeight; ++y)
  73571. {
  73572. uint8* p = destData.getLinePointer (y);
  73573. for (int x = 0; x < imageWidth; ++x)
  73574. {
  73575. ((PixelARGB*) p)->multiplyAlpha (amountToMultiplyBy);
  73576. p += destData.pixelStride;
  73577. }
  73578. }
  73579. }
  73580. else
  73581. {
  73582. for (int y = 0; y < imageHeight; ++y)
  73583. {
  73584. uint8* p = destData.getLinePointer (y);
  73585. for (int x = 0; x < imageWidth; ++x)
  73586. {
  73587. *p = (uint8) (*p * amountToMultiplyBy);
  73588. p += destData.pixelStride;
  73589. }
  73590. }
  73591. }
  73592. }
  73593. else
  73594. {
  73595. jassertfalse // can't do this without an alpha-channel!
  73596. }
  73597. }
  73598. void Image::desaturate()
  73599. {
  73600. if (isARGB() || isRGB())
  73601. {
  73602. const BitmapData destData (*this, 0, 0, getWidth(), getHeight(), true);
  73603. if (isARGB())
  73604. {
  73605. for (int y = 0; y < imageHeight; ++y)
  73606. {
  73607. uint8* p = destData.getLinePointer (y);
  73608. for (int x = 0; x < imageWidth; ++x)
  73609. {
  73610. ((PixelARGB*) p)->desaturate();
  73611. p += destData.pixelStride;
  73612. }
  73613. }
  73614. }
  73615. else
  73616. {
  73617. for (int y = 0; y < imageHeight; ++y)
  73618. {
  73619. uint8* p = destData.getLinePointer (y);
  73620. for (int x = 0; x < imageWidth; ++x)
  73621. {
  73622. ((PixelRGB*) p)->desaturate();
  73623. p += destData.pixelStride;
  73624. }
  73625. }
  73626. }
  73627. }
  73628. }
  73629. void Image::createSolidAreaMask (RectangleList& result, const float alphaThreshold) const
  73630. {
  73631. if (hasAlphaChannel())
  73632. {
  73633. const uint8 threshold = (uint8) jlimit (0, 255, roundToInt (alphaThreshold * 255.0f));
  73634. SparseSet<int> pixelsOnRow;
  73635. const BitmapData srcData (*this, 0, 0, getWidth(), getHeight());
  73636. for (int y = 0; y < imageHeight; ++y)
  73637. {
  73638. pixelsOnRow.clear();
  73639. const uint8* lineData = srcData.getLinePointer (y);
  73640. if (isARGB())
  73641. {
  73642. for (int x = 0; x < imageWidth; ++x)
  73643. {
  73644. if (((const PixelARGB*) lineData)->getAlpha() >= threshold)
  73645. pixelsOnRow.addRange (Range<int> (x, x + 1));
  73646. lineData += srcData.pixelStride;
  73647. }
  73648. }
  73649. else
  73650. {
  73651. for (int x = 0; x < imageWidth; ++x)
  73652. {
  73653. if (*lineData >= threshold)
  73654. pixelsOnRow.addRange (Range<int> (x, x + 1));
  73655. lineData += srcData.pixelStride;
  73656. }
  73657. }
  73658. for (int i = 0; i < pixelsOnRow.getNumRanges(); ++i)
  73659. {
  73660. const Range<int> range (pixelsOnRow.getRange (i));
  73661. result.add (Rectangle<int> (range.getStart(), y, range.getLength(), 1));
  73662. }
  73663. result.consolidate();
  73664. }
  73665. }
  73666. else
  73667. {
  73668. result.add (0, 0, imageWidth, imageHeight);
  73669. }
  73670. }
  73671. void Image::moveImageSection (int dx, int dy,
  73672. int sx, int sy,
  73673. int w, int h)
  73674. {
  73675. if (dx < 0)
  73676. {
  73677. w += dx;
  73678. sx -= dx;
  73679. dx = 0;
  73680. }
  73681. if (dy < 0)
  73682. {
  73683. h += dy;
  73684. sy -= dy;
  73685. dy = 0;
  73686. }
  73687. if (sx < 0)
  73688. {
  73689. w += sx;
  73690. dx -= sx;
  73691. sx = 0;
  73692. }
  73693. if (sy < 0)
  73694. {
  73695. h += sy;
  73696. dy -= sy;
  73697. sy = 0;
  73698. }
  73699. const int minX = jmin (dx, sx);
  73700. const int minY = jmin (dy, sy);
  73701. w = jmin (w, getWidth() - jmax (sx, dx));
  73702. h = jmin (h, getHeight() - jmax (sy, dy));
  73703. if (w > 0 && h > 0)
  73704. {
  73705. const int maxX = jmax (dx, sx) + w;
  73706. const int maxY = jmax (dy, sy) + h;
  73707. const BitmapData destData (*this, minX, minY, maxX - minX, maxY - minY, true);
  73708. uint8* dst = destData.getPixelPointer (dx - minX, dy - minY);
  73709. const uint8* src = destData.getPixelPointer (sx - minX, sy - minY);
  73710. const int lineSize = destData.pixelStride * w;
  73711. if (dy > sy)
  73712. {
  73713. while (--h >= 0)
  73714. {
  73715. const int offset = h * destData.lineStride;
  73716. memmove (dst + offset, src + offset, lineSize);
  73717. }
  73718. }
  73719. else if (dst != src)
  73720. {
  73721. while (--h >= 0)
  73722. {
  73723. memmove (dst, src, lineSize);
  73724. dst += destData.lineStride;
  73725. src += destData.lineStride;
  73726. }
  73727. }
  73728. }
  73729. }
  73730. END_JUCE_NAMESPACE
  73731. /*** End of inlined file: juce_Image.cpp ***/
  73732. /*** Start of inlined file: juce_ImageCache.cpp ***/
  73733. BEGIN_JUCE_NAMESPACE
  73734. struct ImageCache::Item
  73735. {
  73736. ScopedPointer <Image> image;
  73737. int64 hashCode;
  73738. int refCount;
  73739. uint32 releaseTime;
  73740. juce_UseDebuggingNewOperator
  73741. };
  73742. ImageCache* ImageCache::instance = 0;
  73743. int ImageCache::cacheTimeout = 5000;
  73744. ImageCache::ImageCache()
  73745. {
  73746. }
  73747. ImageCache::~ImageCache()
  73748. {
  73749. jassert (instance == this);
  73750. instance = 0;
  73751. }
  73752. Image* ImageCache::getFromHashCode (const int64 hashCode)
  73753. {
  73754. if (instance != 0)
  73755. {
  73756. const ScopedLock sl (instance->lock);
  73757. for (int i = instance->images.size(); --i >= 0;)
  73758. {
  73759. Item* const ci = instance->images.getUnchecked(i);
  73760. if (ci->hashCode == hashCode)
  73761. {
  73762. ci->refCount++;
  73763. return ci->image;
  73764. }
  73765. }
  73766. }
  73767. return 0;
  73768. }
  73769. void ImageCache::addImageToCache (Image* const image, const int64 hashCode)
  73770. {
  73771. if (image != 0)
  73772. {
  73773. if (instance == 0)
  73774. instance = new ImageCache();
  73775. Item* const newC = new Item();
  73776. newC->hashCode = hashCode;
  73777. newC->image = image;
  73778. newC->refCount = 1;
  73779. newC->releaseTime = 0;
  73780. const ScopedLock sl (instance->lock);
  73781. instance->images.add (newC);
  73782. }
  73783. }
  73784. void ImageCache::release (Image* const imageToRelease)
  73785. {
  73786. if (imageToRelease != 0 && instance != 0)
  73787. {
  73788. const ScopedLock sl (instance->lock);
  73789. for (int i = instance->images.size(); --i >= 0;)
  73790. {
  73791. Item* const ci = instance->images.getUnchecked(i);
  73792. if (static_cast <Image*> (ci->image) == imageToRelease)
  73793. {
  73794. if (--(ci->refCount) == 0)
  73795. ci->releaseTime = Time::getApproximateMillisecondCounter();
  73796. if (! instance->isTimerRunning())
  73797. instance->startTimer (999);
  73798. break;
  73799. }
  73800. }
  73801. }
  73802. }
  73803. void ImageCache::releaseOrDelete (Image* const imageToRelease)
  73804. {
  73805. if (isImageInCache (imageToRelease))
  73806. release (imageToRelease);
  73807. else
  73808. delete imageToRelease;
  73809. }
  73810. bool ImageCache::isImageInCache (Image* const imageToLookFor)
  73811. {
  73812. if (instance != 0)
  73813. {
  73814. const ScopedLock sl (instance->lock);
  73815. for (int i = instance->images.size(); --i >= 0;)
  73816. if (static_cast <Image*> (instance->images.getUnchecked(i)->image) == imageToLookFor)
  73817. return true;
  73818. }
  73819. return false;
  73820. }
  73821. void ImageCache::incReferenceCount (Image* const image)
  73822. {
  73823. if (instance != 0)
  73824. {
  73825. const ScopedLock sl (instance->lock);
  73826. for (int i = instance->images.size(); --i >= 0;)
  73827. {
  73828. Item* const ci = instance->images.getUnchecked(i);
  73829. if (static_cast <Image*> (ci->image) == image)
  73830. {
  73831. ci->refCount++;
  73832. return;
  73833. }
  73834. }
  73835. }
  73836. jassertfalse // (trying to inc the ref count of an image that's not in the cache)
  73837. }
  73838. void ImageCache::timerCallback()
  73839. {
  73840. int numberStillNeedingReleasing = 0;
  73841. const uint32 now = Time::getApproximateMillisecondCounter();
  73842. const ScopedLock sl (lock);
  73843. for (int i = images.size(); --i >= 0;)
  73844. {
  73845. Item* const ci = images.getUnchecked(i);
  73846. if (ci->refCount <= 0)
  73847. {
  73848. if (now > ci->releaseTime + cacheTimeout
  73849. || now < ci->releaseTime - 1000)
  73850. {
  73851. images.remove (i);
  73852. }
  73853. else
  73854. {
  73855. ++numberStillNeedingReleasing;
  73856. }
  73857. }
  73858. }
  73859. if (numberStillNeedingReleasing == 0)
  73860. stopTimer();
  73861. }
  73862. Image* ImageCache::getFromFile (const File& file)
  73863. {
  73864. const int64 hashCode = file.hashCode64();
  73865. Image* image = getFromHashCode (hashCode);
  73866. if (image == 0)
  73867. {
  73868. image = ImageFileFormat::loadFrom (file);
  73869. addImageToCache (image, hashCode);
  73870. }
  73871. return image;
  73872. }
  73873. Image* ImageCache::getFromMemory (const void* imageData, const int dataSize)
  73874. {
  73875. const int64 hashCode = (int64) (pointer_sized_int) imageData;
  73876. Image* image = getFromHashCode (hashCode);
  73877. if (image == 0)
  73878. {
  73879. image = ImageFileFormat::loadFrom (imageData, dataSize);
  73880. addImageToCache (image, hashCode);
  73881. }
  73882. return image;
  73883. }
  73884. void ImageCache::setCacheTimeout (const int millisecs)
  73885. {
  73886. cacheTimeout = millisecs;
  73887. }
  73888. END_JUCE_NAMESPACE
  73889. /*** End of inlined file: juce_ImageCache.cpp ***/
  73890. /*** Start of inlined file: juce_ImageConvolutionKernel.cpp ***/
  73891. BEGIN_JUCE_NAMESPACE
  73892. ImageConvolutionKernel::ImageConvolutionKernel (const int size_)
  73893. : values (size_ * size_),
  73894. size (size_)
  73895. {
  73896. clear();
  73897. }
  73898. ImageConvolutionKernel::~ImageConvolutionKernel()
  73899. {
  73900. }
  73901. float ImageConvolutionKernel::getKernelValue (const int x, const int y) const throw()
  73902. {
  73903. if (((unsigned int) x) < (unsigned int) size
  73904. && ((unsigned int) y) < (unsigned int) size)
  73905. {
  73906. return values [x + y * size];
  73907. }
  73908. else
  73909. {
  73910. jassertfalse;
  73911. return 0;
  73912. }
  73913. }
  73914. void ImageConvolutionKernel::setKernelValue (const int x, const int y, const float value) throw()
  73915. {
  73916. if (((unsigned int) x) < (unsigned int) size
  73917. && ((unsigned int) y) < (unsigned int) size)
  73918. {
  73919. values [x + y * size] = value;
  73920. }
  73921. else
  73922. {
  73923. jassertfalse;
  73924. }
  73925. }
  73926. void ImageConvolutionKernel::clear()
  73927. {
  73928. for (int i = size * size; --i >= 0;)
  73929. values[i] = 0;
  73930. }
  73931. void ImageConvolutionKernel::setOverallSum (const float desiredTotalSum)
  73932. {
  73933. double currentTotal = 0.0;
  73934. for (int i = size * size; --i >= 0;)
  73935. currentTotal += values[i];
  73936. rescaleAllValues ((float) (desiredTotalSum / currentTotal));
  73937. }
  73938. void ImageConvolutionKernel::rescaleAllValues (const float multiplier)
  73939. {
  73940. for (int i = size * size; --i >= 0;)
  73941. values[i] *= multiplier;
  73942. }
  73943. void ImageConvolutionKernel::createGaussianBlur (const float radius)
  73944. {
  73945. const double radiusFactor = -1.0 / (radius * radius * 2);
  73946. const int centre = size >> 1;
  73947. for (int y = size; --y >= 0;)
  73948. {
  73949. for (int x = size; --x >= 0;)
  73950. {
  73951. const int cx = x - centre;
  73952. const int cy = y - centre;
  73953. values [x + y * size] = (float) exp (radiusFactor * (cx * cx + cy * cy));
  73954. }
  73955. }
  73956. setOverallSum (1.0f);
  73957. }
  73958. void ImageConvolutionKernel::applyToImage (Image& destImage,
  73959. const Image* sourceImage,
  73960. const Rectangle<int>& destinationArea) const
  73961. {
  73962. ScopedPointer <Image> imageCreated;
  73963. if (sourceImage == 0)
  73964. {
  73965. sourceImage = imageCreated = destImage.createCopy();
  73966. }
  73967. else
  73968. {
  73969. jassert (sourceImage->getWidth() == destImage.getWidth()
  73970. && sourceImage->getHeight() == destImage.getHeight()
  73971. && sourceImage->getFormat() == destImage.getFormat());
  73972. if (sourceImage->getWidth() != destImage.getWidth()
  73973. || sourceImage->getHeight() != destImage.getHeight()
  73974. || sourceImage->getFormat() != destImage.getFormat())
  73975. return;
  73976. }
  73977. const Rectangle<int> area (destinationArea.getIntersection (destImage.getBounds()));
  73978. if (area.isEmpty())
  73979. return;
  73980. const int right = area.getRight();
  73981. const int bottom = area.getBottom();
  73982. const Image::BitmapData destData (destImage, area.getX(), area.getY(), area.getWidth(), area.getHeight(), true);
  73983. uint8* line = destData.data;
  73984. const Image::BitmapData srcData (*sourceImage, 0, 0, sourceImage->getWidth(), sourceImage->getHeight());
  73985. if (destData.pixelStride == 4)
  73986. {
  73987. for (int y = area.getY(); y < bottom; ++y)
  73988. {
  73989. uint8* dest = line;
  73990. line += destData.lineStride;
  73991. for (int x = area.getX(); x < right; ++x)
  73992. {
  73993. float c1 = 0;
  73994. float c2 = 0;
  73995. float c3 = 0;
  73996. float c4 = 0;
  73997. for (int yy = 0; yy < size; ++yy)
  73998. {
  73999. const int sy = y + yy - (size >> 1);
  74000. if (sy >= srcData.height)
  74001. break;
  74002. if (sy >= 0)
  74003. {
  74004. int sx = x - (size >> 1);
  74005. const uint8* src = srcData.getPixelPointer (sx, sy);
  74006. for (int xx = 0; xx < size; ++xx)
  74007. {
  74008. if (sx >= srcData.width)
  74009. break;
  74010. if (sx >= 0)
  74011. {
  74012. const float kernelMult = values [xx + yy * size];
  74013. c1 += kernelMult * *src++;
  74014. c2 += kernelMult * *src++;
  74015. c3 += kernelMult * *src++;
  74016. c4 += kernelMult * *src++;
  74017. }
  74018. else
  74019. {
  74020. src += 4;
  74021. }
  74022. ++sx;
  74023. }
  74024. }
  74025. }
  74026. *dest++ = (uint8) jmin (0xff, roundToInt (c1));
  74027. *dest++ = (uint8) jmin (0xff, roundToInt (c2));
  74028. *dest++ = (uint8) jmin (0xff, roundToInt (c3));
  74029. *dest++ = (uint8) jmin (0xff, roundToInt (c4));
  74030. }
  74031. }
  74032. }
  74033. else if (destData.pixelStride == 3)
  74034. {
  74035. for (int y = area.getY(); y < bottom; ++y)
  74036. {
  74037. uint8* dest = line;
  74038. line += destData.lineStride;
  74039. for (int x = area.getX(); x < right; ++x)
  74040. {
  74041. float c1 = 0;
  74042. float c2 = 0;
  74043. float c3 = 0;
  74044. for (int yy = 0; yy < size; ++yy)
  74045. {
  74046. const int sy = y + yy - (size >> 1);
  74047. if (sy >= srcData.height)
  74048. break;
  74049. if (sy >= 0)
  74050. {
  74051. int sx = x - (size >> 1);
  74052. const uint8* src = srcData.getPixelPointer (sx, sy);
  74053. for (int xx = 0; xx < size; ++xx)
  74054. {
  74055. if (sx >= srcData.width)
  74056. break;
  74057. if (sx >= 0)
  74058. {
  74059. const float kernelMult = values [xx + yy * size];
  74060. c1 += kernelMult * *src++;
  74061. c2 += kernelMult * *src++;
  74062. c3 += kernelMult * *src++;
  74063. }
  74064. else
  74065. {
  74066. src += 3;
  74067. }
  74068. ++sx;
  74069. }
  74070. }
  74071. }
  74072. *dest++ = (uint8) roundToInt (c1);
  74073. *dest++ = (uint8) roundToInt (c2);
  74074. *dest++ = (uint8) roundToInt (c3);
  74075. }
  74076. }
  74077. }
  74078. }
  74079. END_JUCE_NAMESPACE
  74080. /*** End of inlined file: juce_ImageConvolutionKernel.cpp ***/
  74081. /*** Start of inlined file: juce_ImageFileFormat.cpp ***/
  74082. BEGIN_JUCE_NAMESPACE
  74083. /*** Start of inlined file: juce_GIFLoader.h ***/
  74084. #ifndef __JUCE_GIFLOADER_JUCEHEADER__
  74085. #define __JUCE_GIFLOADER_JUCEHEADER__
  74086. #ifndef DOXYGEN
  74087. /**
  74088. Used internally by ImageFileFormat - don't use this class directly in your
  74089. application.
  74090. @see ImageFileFormat
  74091. */
  74092. class GIFLoader
  74093. {
  74094. public:
  74095. GIFLoader (InputStream& in);
  74096. ~GIFLoader();
  74097. Image* getImage() const { return image; }
  74098. private:
  74099. Image* image;
  74100. InputStream& input;
  74101. uint8 buffer [300];
  74102. uint8 palette [256][4];
  74103. bool dataBlockIsZero, fresh, finished;
  74104. int currentBit, lastBit, lastByteIndex;
  74105. int codeSize, setCodeSize;
  74106. int maxCode, maxCodeSize;
  74107. int firstcode, oldcode;
  74108. int clearCode, end_code;
  74109. enum { maxGifCode = 1 << 12 };
  74110. int table [2] [maxGifCode];
  74111. int stack [2 * maxGifCode];
  74112. int *sp;
  74113. bool getSizeFromHeader (int& width, int& height);
  74114. bool readPalette (const int numCols);
  74115. int readDataBlock (unsigned char* dest);
  74116. int processExtension (int type, int& transparent);
  74117. int readLZWByte (bool initialise, int input_code_size);
  74118. int getCode (int code_size, bool initialise);
  74119. bool readImage (int width, int height, int interlace, int transparent);
  74120. static inline int makeWord (const uint8 a, const uint8 b) { return (b << 8) | a; }
  74121. GIFLoader (const GIFLoader&);
  74122. GIFLoader& operator= (const GIFLoader&);
  74123. };
  74124. #endif // DOXYGEN
  74125. #endif // __JUCE_GIFLOADER_JUCEHEADER__
  74126. /*** End of inlined file: juce_GIFLoader.h ***/
  74127. class GIFImageFormat : public ImageFileFormat
  74128. {
  74129. public:
  74130. GIFImageFormat() {}
  74131. ~GIFImageFormat() {}
  74132. const String getFormatName()
  74133. {
  74134. return "GIF";
  74135. }
  74136. bool canUnderstand (InputStream& in)
  74137. {
  74138. const int bytesNeeded = 4;
  74139. char header [bytesNeeded];
  74140. return (in.read (header, bytesNeeded) == bytesNeeded)
  74141. && header[0] == 'G'
  74142. && header[1] == 'I'
  74143. && header[2] == 'F';
  74144. }
  74145. Image* decodeImage (InputStream& in)
  74146. {
  74147. const ScopedPointer <GIFLoader> loader (new GIFLoader (in));
  74148. return loader->getImage();
  74149. }
  74150. bool writeImageToStream (const Image& /*sourceImage*/, OutputStream& /*destStream*/)
  74151. {
  74152. return false;
  74153. }
  74154. };
  74155. ImageFileFormat* ImageFileFormat::findImageFormatForStream (InputStream& input)
  74156. {
  74157. static PNGImageFormat png;
  74158. static JPEGImageFormat jpg;
  74159. static GIFImageFormat gif;
  74160. ImageFileFormat* formats[4];
  74161. int numFormats = 0;
  74162. formats [numFormats++] = &png;
  74163. formats [numFormats++] = &jpg;
  74164. formats [numFormats++] = &gif;
  74165. const int64 streamPos = input.getPosition();
  74166. for (int i = 0; i < numFormats; ++i)
  74167. {
  74168. const bool found = formats[i]->canUnderstand (input);
  74169. input.setPosition (streamPos);
  74170. if (found)
  74171. return formats[i];
  74172. }
  74173. return 0;
  74174. }
  74175. Image* ImageFileFormat::loadFrom (InputStream& input)
  74176. {
  74177. ImageFileFormat* const format = findImageFormatForStream (input);
  74178. if (format != 0)
  74179. return format->decodeImage (input);
  74180. return 0;
  74181. }
  74182. Image* ImageFileFormat::loadFrom (const File& file)
  74183. {
  74184. InputStream* const in = file.createInputStream();
  74185. if (in != 0)
  74186. {
  74187. BufferedInputStream b (in, 8192, true);
  74188. return loadFrom (b);
  74189. }
  74190. return 0;
  74191. }
  74192. Image* ImageFileFormat::loadFrom (const void* rawData, const int numBytes)
  74193. {
  74194. if (rawData != 0 && numBytes > 4)
  74195. {
  74196. MemoryInputStream stream (rawData, numBytes, false);
  74197. return loadFrom (stream);
  74198. }
  74199. return 0;
  74200. }
  74201. END_JUCE_NAMESPACE
  74202. /*** End of inlined file: juce_ImageFileFormat.cpp ***/
  74203. /*** Start of inlined file: juce_GIFLoader.cpp ***/
  74204. BEGIN_JUCE_NAMESPACE
  74205. GIFLoader::GIFLoader (InputStream& in)
  74206. : image (0),
  74207. input (in),
  74208. dataBlockIsZero (false),
  74209. fresh (false),
  74210. finished (false)
  74211. {
  74212. currentBit = lastBit = lastByteIndex = 0;
  74213. maxCode = maxCodeSize = codeSize = setCodeSize = 0;
  74214. firstcode = oldcode = 0;
  74215. clearCode = end_code = 0;
  74216. int imageWidth, imageHeight;
  74217. int transparent = -1;
  74218. if (! getSizeFromHeader (imageWidth, imageHeight))
  74219. return;
  74220. if ((imageWidth <= 0) || (imageHeight <= 0))
  74221. return;
  74222. unsigned char buf [16];
  74223. if (in.read (buf, 3) != 3)
  74224. return;
  74225. int numColours = 2 << (buf[0] & 7);
  74226. if ((buf[0] & 0x80) != 0)
  74227. readPalette (numColours);
  74228. for (;;)
  74229. {
  74230. if (input.read (buf, 1) != 1)
  74231. break;
  74232. if (buf[0] == ';')
  74233. break;
  74234. if (buf[0] == '!')
  74235. {
  74236. if (input.read (buf, 1) != 1)
  74237. break;
  74238. if (processExtension (buf[0], transparent) < 0)
  74239. break;
  74240. continue;
  74241. }
  74242. if (buf[0] != ',')
  74243. continue;
  74244. if (input.read (buf, 9) != 9)
  74245. break;
  74246. imageWidth = makeWord (buf[4], buf[5]);
  74247. imageHeight = makeWord (buf[6], buf[7]);
  74248. numColours = 2 << (buf[8] & 7);
  74249. if ((buf[8] & 0x80) != 0)
  74250. if (! readPalette (numColours))
  74251. break;
  74252. image = Image::createNativeImage ((transparent >= 0) ? Image::ARGB : Image::RGB,
  74253. imageWidth, imageHeight, (transparent >= 0));
  74254. readImage (imageWidth, imageHeight,
  74255. (buf[8] & 0x40) != 0,
  74256. transparent);
  74257. break;
  74258. }
  74259. }
  74260. GIFLoader::~GIFLoader()
  74261. {
  74262. }
  74263. bool GIFLoader::getSizeFromHeader (int& w, int& h)
  74264. {
  74265. char b[8];
  74266. if (input.read (b, 6) == 6)
  74267. {
  74268. if ((strncmp ("GIF87a", b, 6) == 0)
  74269. || (strncmp ("GIF89a", b, 6) == 0))
  74270. {
  74271. if (input.read (b, 4) == 4)
  74272. {
  74273. w = makeWord (b[0], b[1]);
  74274. h = makeWord (b[2], b[3]);
  74275. return true;
  74276. }
  74277. }
  74278. }
  74279. return false;
  74280. }
  74281. bool GIFLoader::readPalette (const int numCols)
  74282. {
  74283. unsigned char rgb[4];
  74284. for (int i = 0; i < numCols; ++i)
  74285. {
  74286. input.read (rgb, 3);
  74287. palette [i][0] = rgb[0];
  74288. palette [i][1] = rgb[1];
  74289. palette [i][2] = rgb[2];
  74290. palette [i][3] = 0xff;
  74291. }
  74292. return true;
  74293. }
  74294. int GIFLoader::readDataBlock (unsigned char* const dest)
  74295. {
  74296. unsigned char n;
  74297. if (input.read (&n, 1) == 1)
  74298. {
  74299. dataBlockIsZero = (n == 0);
  74300. if (dataBlockIsZero || (input.read (dest, n) == n))
  74301. return n;
  74302. }
  74303. return -1;
  74304. }
  74305. int GIFLoader::processExtension (const int type, int& transparent)
  74306. {
  74307. unsigned char b [300];
  74308. int n = 0;
  74309. if (type == 0xf9)
  74310. {
  74311. n = readDataBlock (b);
  74312. if (n < 0)
  74313. return 1;
  74314. if ((b[0] & 0x1) != 0)
  74315. transparent = b[3];
  74316. }
  74317. do
  74318. {
  74319. n = readDataBlock (b);
  74320. }
  74321. while (n > 0);
  74322. return n;
  74323. }
  74324. int GIFLoader::getCode (const int codeSize_, const bool initialise)
  74325. {
  74326. if (initialise)
  74327. {
  74328. currentBit = 0;
  74329. lastBit = 0;
  74330. finished = false;
  74331. return 0;
  74332. }
  74333. if ((currentBit + codeSize_) >= lastBit)
  74334. {
  74335. if (finished)
  74336. return -1;
  74337. buffer[0] = buffer [lastByteIndex - 2];
  74338. buffer[1] = buffer [lastByteIndex - 1];
  74339. const int n = readDataBlock (&buffer[2]);
  74340. if (n == 0)
  74341. finished = true;
  74342. lastByteIndex = 2 + n;
  74343. currentBit = (currentBit - lastBit) + 16;
  74344. lastBit = (2 + n) * 8 ;
  74345. }
  74346. int result = 0;
  74347. int i = currentBit;
  74348. for (int j = 0; j < codeSize_; ++j)
  74349. {
  74350. result |= ((buffer[i >> 3] & (1 << (i & 7))) != 0) << j;
  74351. ++i;
  74352. }
  74353. currentBit += codeSize_;
  74354. return result;
  74355. }
  74356. int GIFLoader::readLZWByte (const bool initialise, const int inputCodeSize)
  74357. {
  74358. int code, incode, i;
  74359. if (initialise)
  74360. {
  74361. setCodeSize = inputCodeSize;
  74362. codeSize = setCodeSize + 1;
  74363. clearCode = 1 << setCodeSize;
  74364. end_code = clearCode + 1;
  74365. maxCodeSize = 2 * clearCode;
  74366. maxCode = clearCode + 2;
  74367. getCode (0, true);
  74368. fresh = true;
  74369. for (i = 0; i < clearCode; ++i)
  74370. {
  74371. table[0][i] = 0;
  74372. table[1][i] = i;
  74373. }
  74374. for (; i < maxGifCode; ++i)
  74375. {
  74376. table[0][i] = 0;
  74377. table[1][i] = 0;
  74378. }
  74379. sp = stack;
  74380. return 0;
  74381. }
  74382. else if (fresh)
  74383. {
  74384. fresh = false;
  74385. do
  74386. {
  74387. firstcode = oldcode
  74388. = getCode (codeSize, false);
  74389. }
  74390. while (firstcode == clearCode);
  74391. return firstcode;
  74392. }
  74393. if (sp > stack)
  74394. return *--sp;
  74395. while ((code = getCode (codeSize, false)) >= 0)
  74396. {
  74397. if (code == clearCode)
  74398. {
  74399. for (i = 0; i < clearCode; ++i)
  74400. {
  74401. table[0][i] = 0;
  74402. table[1][i] = i;
  74403. }
  74404. for (; i < maxGifCode; ++i)
  74405. {
  74406. table[0][i] = 0;
  74407. table[1][i] = 0;
  74408. }
  74409. codeSize = setCodeSize + 1;
  74410. maxCodeSize = 2 * clearCode;
  74411. maxCode = clearCode + 2;
  74412. sp = stack;
  74413. firstcode = oldcode = getCode (codeSize, false);
  74414. return firstcode;
  74415. }
  74416. else if (code == end_code)
  74417. {
  74418. if (dataBlockIsZero)
  74419. return -2;
  74420. unsigned char buf [260];
  74421. int n;
  74422. while ((n = readDataBlock (buf)) > 0)
  74423. {}
  74424. if (n != 0)
  74425. return -2;
  74426. }
  74427. incode = code;
  74428. if (code >= maxCode)
  74429. {
  74430. *sp++ = firstcode;
  74431. code = oldcode;
  74432. }
  74433. while (code >= clearCode)
  74434. {
  74435. *sp++ = table[1][code];
  74436. if (code == table[0][code])
  74437. return -2;
  74438. code = table[0][code];
  74439. }
  74440. *sp++ = firstcode = table[1][code];
  74441. if ((code = maxCode) < maxGifCode)
  74442. {
  74443. table[0][code] = oldcode;
  74444. table[1][code] = firstcode;
  74445. ++maxCode;
  74446. if ((maxCode >= maxCodeSize)
  74447. && (maxCodeSize < maxGifCode))
  74448. {
  74449. maxCodeSize <<= 1;
  74450. ++codeSize;
  74451. }
  74452. }
  74453. oldcode = incode;
  74454. if (sp > stack)
  74455. return *--sp;
  74456. }
  74457. return code;
  74458. }
  74459. bool GIFLoader::readImage (const int width, const int height,
  74460. const int interlace, const int transparent)
  74461. {
  74462. unsigned char c;
  74463. if (input.read (&c, 1) != 1
  74464. || readLZWByte (true, c) < 0)
  74465. return false;
  74466. if (transparent >= 0)
  74467. {
  74468. palette [transparent][0] = 0;
  74469. palette [transparent][1] = 0;
  74470. palette [transparent][2] = 0;
  74471. palette [transparent][3] = 0;
  74472. }
  74473. int index;
  74474. int xpos = 0, ypos = 0, pass = 0;
  74475. const Image::BitmapData destData (*image, 0, 0, width, height, true);
  74476. uint8* p = destData.data;
  74477. const bool hasAlpha = image->hasAlphaChannel();
  74478. while ((index = readLZWByte (false, c)) >= 0)
  74479. {
  74480. const uint8* const paletteEntry = palette [index];
  74481. if (hasAlpha)
  74482. {
  74483. ((PixelARGB*) p)->setARGB (paletteEntry[3],
  74484. paletteEntry[0],
  74485. paletteEntry[1],
  74486. paletteEntry[2]);
  74487. ((PixelARGB*) p)->premultiply();
  74488. }
  74489. else
  74490. {
  74491. ((PixelRGB*) p)->setARGB (0,
  74492. paletteEntry[0],
  74493. paletteEntry[1],
  74494. paletteEntry[2]);
  74495. }
  74496. p += destData.pixelStride;
  74497. ++xpos;
  74498. if (xpos == width)
  74499. {
  74500. xpos = 0;
  74501. if (interlace)
  74502. {
  74503. switch (pass)
  74504. {
  74505. case 0:
  74506. case 1: ypos += 8; break;
  74507. case 2: ypos += 4; break;
  74508. case 3: ypos += 2; break;
  74509. }
  74510. while (ypos >= height)
  74511. {
  74512. ++pass;
  74513. switch (pass)
  74514. {
  74515. case 1: ypos = 4; break;
  74516. case 2: ypos = 2; break;
  74517. case 3: ypos = 1; break;
  74518. default: return true;
  74519. }
  74520. }
  74521. }
  74522. else
  74523. {
  74524. ++ypos;
  74525. }
  74526. p = destData.getPixelPointer (xpos, ypos);
  74527. }
  74528. if (ypos >= height)
  74529. break;
  74530. }
  74531. return true;
  74532. }
  74533. END_JUCE_NAMESPACE
  74534. /*** End of inlined file: juce_GIFLoader.cpp ***/
  74535. #endif
  74536. //==============================================================================
  74537. // some files include lots of library code, so leave them to the end to avoid cluttering
  74538. // up the build for the clean files.
  74539. #if JUCE_BUILD_CORE
  74540. /*** Start of inlined file: juce_GZIPCompressorOutputStream.cpp ***/
  74541. namespace zlibNamespace
  74542. {
  74543. #if JUCE_INCLUDE_ZLIB_CODE
  74544. #undef OS_CODE
  74545. #undef fdopen
  74546. /*** Start of inlined file: zlib.h ***/
  74547. #ifndef ZLIB_H
  74548. #define ZLIB_H
  74549. /*** Start of inlined file: zconf.h ***/
  74550. /* @(#) $Id: zconf.h,v 1.1 2007/06/07 17:54:37 jules_rms Exp $ */
  74551. #ifndef ZCONF_H
  74552. #define ZCONF_H
  74553. // *** Just a few hacks here to make it compile nicely with Juce..
  74554. #define Z_PREFIX 1
  74555. #undef __MACTYPES__
  74556. #ifdef _MSC_VER
  74557. #pragma warning (disable : 4131 4127 4244 4267)
  74558. #endif
  74559. /*
  74560. * If you *really* need a unique prefix for all types and library functions,
  74561. * compile with -DZ_PREFIX. The "standard" zlib should be compiled without it.
  74562. */
  74563. #ifdef Z_PREFIX
  74564. # define deflateInit_ z_deflateInit_
  74565. # define deflate z_deflate
  74566. # define deflateEnd z_deflateEnd
  74567. # define inflateInit_ z_inflateInit_
  74568. # define inflate z_inflate
  74569. # define inflateEnd z_inflateEnd
  74570. # define inflatePrime z_inflatePrime
  74571. # define inflateGetHeader z_inflateGetHeader
  74572. # define adler32_combine z_adler32_combine
  74573. # define crc32_combine z_crc32_combine
  74574. # define deflateInit2_ z_deflateInit2_
  74575. # define deflateSetDictionary z_deflateSetDictionary
  74576. # define deflateCopy z_deflateCopy
  74577. # define deflateReset z_deflateReset
  74578. # define deflateParams z_deflateParams
  74579. # define deflateBound z_deflateBound
  74580. # define deflatePrime z_deflatePrime
  74581. # define inflateInit2_ z_inflateInit2_
  74582. # define inflateSetDictionary z_inflateSetDictionary
  74583. # define inflateSync z_inflateSync
  74584. # define inflateSyncPoint z_inflateSyncPoint
  74585. # define inflateCopy z_inflateCopy
  74586. # define inflateReset z_inflateReset
  74587. # define inflateBack z_inflateBack
  74588. # define inflateBackEnd z_inflateBackEnd
  74589. # define compress z_compress
  74590. # define compress2 z_compress2
  74591. # define compressBound z_compressBound
  74592. # define uncompress z_uncompress
  74593. # define adler32 z_adler32
  74594. # define crc32 z_crc32
  74595. # define get_crc_table z_get_crc_table
  74596. # define zError z_zError
  74597. # define alloc_func z_alloc_func
  74598. # define free_func z_free_func
  74599. # define in_func z_in_func
  74600. # define out_func z_out_func
  74601. # define Byte z_Byte
  74602. # define uInt z_uInt
  74603. # define uLong z_uLong
  74604. # define Bytef z_Bytef
  74605. # define charf z_charf
  74606. # define intf z_intf
  74607. # define uIntf z_uIntf
  74608. # define uLongf z_uLongf
  74609. # define voidpf z_voidpf
  74610. # define voidp z_voidp
  74611. #endif
  74612. #if defined(__MSDOS__) && !defined(MSDOS)
  74613. # define MSDOS
  74614. #endif
  74615. #if (defined(OS_2) || defined(__OS2__)) && !defined(OS2)
  74616. # define OS2
  74617. #endif
  74618. #if defined(_WINDOWS) && !defined(WINDOWS)
  74619. # define WINDOWS
  74620. #endif
  74621. #if defined(_WIN32) || defined(_WIN32_WCE) || defined(__WIN32__)
  74622. # ifndef WIN32
  74623. # define WIN32
  74624. # endif
  74625. #endif
  74626. #if (defined(MSDOS) || defined(OS2) || defined(WINDOWS)) && !defined(WIN32)
  74627. # if !defined(__GNUC__) && !defined(__FLAT__) && !defined(__386__)
  74628. # ifndef SYS16BIT
  74629. # define SYS16BIT
  74630. # endif
  74631. # endif
  74632. #endif
  74633. /*
  74634. * Compile with -DMAXSEG_64K if the alloc function cannot allocate more
  74635. * than 64k bytes at a time (needed on systems with 16-bit int).
  74636. */
  74637. #ifdef SYS16BIT
  74638. # define MAXSEG_64K
  74639. #endif
  74640. #ifdef MSDOS
  74641. # define UNALIGNED_OK
  74642. #endif
  74643. #ifdef __STDC_VERSION__
  74644. # ifndef STDC
  74645. # define STDC
  74646. # endif
  74647. # if __STDC_VERSION__ >= 199901L
  74648. # ifndef STDC99
  74649. # define STDC99
  74650. # endif
  74651. # endif
  74652. #endif
  74653. #if !defined(STDC) && (defined(__STDC__) || defined(__cplusplus))
  74654. # define STDC
  74655. #endif
  74656. #if !defined(STDC) && (defined(__GNUC__) || defined(__BORLANDC__))
  74657. # define STDC
  74658. #endif
  74659. #if !defined(STDC) && (defined(MSDOS) || defined(WINDOWS) || defined(WIN32))
  74660. # define STDC
  74661. #endif
  74662. #if !defined(STDC) && (defined(OS2) || defined(__HOS_AIX__))
  74663. # define STDC
  74664. #endif
  74665. #if defined(__OS400__) && !defined(STDC) /* iSeries (formerly AS/400). */
  74666. # define STDC
  74667. #endif
  74668. #ifndef STDC
  74669. # ifndef const /* cannot use !defined(STDC) && !defined(const) on Mac */
  74670. # define const /* note: need a more gentle solution here */
  74671. # endif
  74672. #endif
  74673. /* Some Mac compilers merge all .h files incorrectly: */
  74674. #if defined(__MWERKS__)||defined(applec)||defined(THINK_C)||defined(__SC__)
  74675. # define NO_DUMMY_DECL
  74676. #endif
  74677. /* Maximum value for memLevel in deflateInit2 */
  74678. #ifndef MAX_MEM_LEVEL
  74679. # ifdef MAXSEG_64K
  74680. # define MAX_MEM_LEVEL 8
  74681. # else
  74682. # define MAX_MEM_LEVEL 9
  74683. # endif
  74684. #endif
  74685. /* Maximum value for windowBits in deflateInit2 and inflateInit2.
  74686. * WARNING: reducing MAX_WBITS makes minigzip unable to extract .gz files
  74687. * created by gzip. (Files created by minigzip can still be extracted by
  74688. * gzip.)
  74689. */
  74690. #ifndef MAX_WBITS
  74691. # define MAX_WBITS 15 /* 32K LZ77 window */
  74692. #endif
  74693. /* The memory requirements for deflate are (in bytes):
  74694. (1 << (windowBits+2)) + (1 << (memLevel+9))
  74695. that is: 128K for windowBits=15 + 128K for memLevel = 8 (default values)
  74696. plus a few kilobytes for small objects. For example, if you want to reduce
  74697. the default memory requirements from 256K to 128K, compile with
  74698. make CFLAGS="-O -DMAX_WBITS=14 -DMAX_MEM_LEVEL=7"
  74699. Of course this will generally degrade compression (there's no free lunch).
  74700. The memory requirements for inflate are (in bytes) 1 << windowBits
  74701. that is, 32K for windowBits=15 (default value) plus a few kilobytes
  74702. for small objects.
  74703. */
  74704. /* Type declarations */
  74705. #ifndef OF /* function prototypes */
  74706. # ifdef STDC
  74707. # define OF(args) args
  74708. # else
  74709. # define OF(args) ()
  74710. # endif
  74711. #endif
  74712. /* The following definitions for FAR are needed only for MSDOS mixed
  74713. * model programming (small or medium model with some far allocations).
  74714. * This was tested only with MSC; for other MSDOS compilers you may have
  74715. * to define NO_MEMCPY in zutil.h. If you don't need the mixed model,
  74716. * just define FAR to be empty.
  74717. */
  74718. #ifdef SYS16BIT
  74719. # if defined(M_I86SM) || defined(M_I86MM)
  74720. /* MSC small or medium model */
  74721. # define SMALL_MEDIUM
  74722. # ifdef _MSC_VER
  74723. # define FAR _far
  74724. # else
  74725. # define FAR far
  74726. # endif
  74727. # endif
  74728. # if (defined(__SMALL__) || defined(__MEDIUM__))
  74729. /* Turbo C small or medium model */
  74730. # define SMALL_MEDIUM
  74731. # ifdef __BORLANDC__
  74732. # define FAR _far
  74733. # else
  74734. # define FAR far
  74735. # endif
  74736. # endif
  74737. #endif
  74738. #if defined(WINDOWS) || defined(WIN32)
  74739. /* If building or using zlib as a DLL, define ZLIB_DLL.
  74740. * This is not mandatory, but it offers a little performance increase.
  74741. */
  74742. # ifdef ZLIB_DLL
  74743. # if defined(WIN32) && (!defined(__BORLANDC__) || (__BORLANDC__ >= 0x500))
  74744. # ifdef ZLIB_INTERNAL
  74745. # define ZEXTERN extern __declspec(dllexport)
  74746. # else
  74747. # define ZEXTERN extern __declspec(dllimport)
  74748. # endif
  74749. # endif
  74750. # endif /* ZLIB_DLL */
  74751. /* If building or using zlib with the WINAPI/WINAPIV calling convention,
  74752. * define ZLIB_WINAPI.
  74753. * Caution: the standard ZLIB1.DLL is NOT compiled using ZLIB_WINAPI.
  74754. */
  74755. # ifdef ZLIB_WINAPI
  74756. # ifdef FAR
  74757. # undef FAR
  74758. # endif
  74759. # include <windows.h>
  74760. /* No need for _export, use ZLIB.DEF instead. */
  74761. /* For complete Windows compatibility, use WINAPI, not __stdcall. */
  74762. # define ZEXPORT WINAPI
  74763. # ifdef WIN32
  74764. # define ZEXPORTVA WINAPIV
  74765. # else
  74766. # define ZEXPORTVA FAR CDECL
  74767. # endif
  74768. # endif
  74769. #endif
  74770. #if defined (__BEOS__)
  74771. # ifdef ZLIB_DLL
  74772. # ifdef ZLIB_INTERNAL
  74773. # define ZEXPORT __declspec(dllexport)
  74774. # define ZEXPORTVA __declspec(dllexport)
  74775. # else
  74776. # define ZEXPORT __declspec(dllimport)
  74777. # define ZEXPORTVA __declspec(dllimport)
  74778. # endif
  74779. # endif
  74780. #endif
  74781. #ifndef ZEXTERN
  74782. # define ZEXTERN extern
  74783. #endif
  74784. #ifndef ZEXPORT
  74785. # define ZEXPORT
  74786. #endif
  74787. #ifndef ZEXPORTVA
  74788. # define ZEXPORTVA
  74789. #endif
  74790. #ifndef FAR
  74791. # define FAR
  74792. #endif
  74793. #if !defined(__MACTYPES__)
  74794. typedef unsigned char Byte; /* 8 bits */
  74795. #endif
  74796. typedef unsigned int uInt; /* 16 bits or more */
  74797. typedef unsigned long uLong; /* 32 bits or more */
  74798. #ifdef SMALL_MEDIUM
  74799. /* Borland C/C++ and some old MSC versions ignore FAR inside typedef */
  74800. # define Bytef Byte FAR
  74801. #else
  74802. typedef Byte FAR Bytef;
  74803. #endif
  74804. typedef char FAR charf;
  74805. typedef int FAR intf;
  74806. typedef uInt FAR uIntf;
  74807. typedef uLong FAR uLongf;
  74808. #ifdef STDC
  74809. typedef void const *voidpc;
  74810. typedef void FAR *voidpf;
  74811. typedef void *voidp;
  74812. #else
  74813. typedef Byte const *voidpc;
  74814. typedef Byte FAR *voidpf;
  74815. typedef Byte *voidp;
  74816. #endif
  74817. #if 0 /* HAVE_UNISTD_H -- this line is updated by ./configure */
  74818. # include <sys/types.h> /* for off_t */
  74819. # include <unistd.h> /* for SEEK_* and off_t */
  74820. # ifdef VMS
  74821. # include <unixio.h> /* for off_t */
  74822. # endif
  74823. # define z_off_t off_t
  74824. #endif
  74825. #ifndef SEEK_SET
  74826. # define SEEK_SET 0 /* Seek from beginning of file. */
  74827. # define SEEK_CUR 1 /* Seek from current position. */
  74828. # define SEEK_END 2 /* Set file pointer to EOF plus "offset" */
  74829. #endif
  74830. #ifndef z_off_t
  74831. # define z_off_t long
  74832. #endif
  74833. #if defined(__OS400__)
  74834. # define NO_vsnprintf
  74835. #endif
  74836. #if defined(__MVS__)
  74837. # define NO_vsnprintf
  74838. # ifdef FAR
  74839. # undef FAR
  74840. # endif
  74841. #endif
  74842. /* MVS linker does not support external names larger than 8 bytes */
  74843. #if defined(__MVS__)
  74844. # pragma map(deflateInit_,"DEIN")
  74845. # pragma map(deflateInit2_,"DEIN2")
  74846. # pragma map(deflateEnd,"DEEND")
  74847. # pragma map(deflateBound,"DEBND")
  74848. # pragma map(inflateInit_,"ININ")
  74849. # pragma map(inflateInit2_,"ININ2")
  74850. # pragma map(inflateEnd,"INEND")
  74851. # pragma map(inflateSync,"INSY")
  74852. # pragma map(inflateSetDictionary,"INSEDI")
  74853. # pragma map(compressBound,"CMBND")
  74854. # pragma map(inflate_table,"INTABL")
  74855. # pragma map(inflate_fast,"INFA")
  74856. # pragma map(inflate_copyright,"INCOPY")
  74857. #endif
  74858. #endif /* ZCONF_H */
  74859. /*** End of inlined file: zconf.h ***/
  74860. #ifdef __cplusplus
  74861. extern "C" {
  74862. #endif
  74863. #define ZLIB_VERSION "1.2.3"
  74864. #define ZLIB_VERNUM 0x1230
  74865. /*
  74866. The 'zlib' compression library provides in-memory compression and
  74867. decompression functions, including integrity checks of the uncompressed
  74868. data. This version of the library supports only one compression method
  74869. (deflation) but other algorithms will be added later and will have the same
  74870. stream interface.
  74871. Compression can be done in a single step if the buffers are large
  74872. enough (for example if an input file is mmap'ed), or can be done by
  74873. repeated calls of the compression function. In the latter case, the
  74874. application must provide more input and/or consume the output
  74875. (providing more output space) before each call.
  74876. The compressed data format used by default by the in-memory functions is
  74877. the zlib format, which is a zlib wrapper documented in RFC 1950, wrapped
  74878. around a deflate stream, which is itself documented in RFC 1951.
  74879. The library also supports reading and writing files in gzip (.gz) format
  74880. with an interface similar to that of stdio using the functions that start
  74881. with "gz". The gzip format is different from the zlib format. gzip is a
  74882. gzip wrapper, documented in RFC 1952, wrapped around a deflate stream.
  74883. This library can optionally read and write gzip streams in memory as well.
  74884. The zlib format was designed to be compact and fast for use in memory
  74885. and on communications channels. The gzip format was designed for single-
  74886. file compression on file systems, has a larger header than zlib to maintain
  74887. directory information, and uses a different, slower check method than zlib.
  74888. The library does not install any signal handler. The decoder checks
  74889. the consistency of the compressed data, so the library should never
  74890. crash even in case of corrupted input.
  74891. */
  74892. typedef voidpf (*alloc_func) OF((voidpf opaque, uInt items, uInt size));
  74893. typedef void (*free_func) OF((voidpf opaque, voidpf address));
  74894. struct internal_state;
  74895. typedef struct z_stream_s {
  74896. Bytef *next_in; /* next input byte */
  74897. uInt avail_in; /* number of bytes available at next_in */
  74898. uLong total_in; /* total nb of input bytes read so far */
  74899. Bytef *next_out; /* next output byte should be put there */
  74900. uInt avail_out; /* remaining free space at next_out */
  74901. uLong total_out; /* total nb of bytes output so far */
  74902. char *msg; /* last error message, NULL if no error */
  74903. struct internal_state FAR *state; /* not visible by applications */
  74904. alloc_func zalloc; /* used to allocate the internal state */
  74905. free_func zfree; /* used to free the internal state */
  74906. voidpf opaque; /* private data object passed to zalloc and zfree */
  74907. int data_type; /* best guess about the data type: binary or text */
  74908. uLong adler; /* adler32 value of the uncompressed data */
  74909. uLong reserved; /* reserved for future use */
  74910. } z_stream;
  74911. typedef z_stream FAR *z_streamp;
  74912. /*
  74913. gzip header information passed to and from zlib routines. See RFC 1952
  74914. for more details on the meanings of these fields.
  74915. */
  74916. typedef struct gz_header_s {
  74917. int text; /* true if compressed data believed to be text */
  74918. uLong time; /* modification time */
  74919. int xflags; /* extra flags (not used when writing a gzip file) */
  74920. int os; /* operating system */
  74921. Bytef *extra; /* pointer to extra field or Z_NULL if none */
  74922. uInt extra_len; /* extra field length (valid if extra != Z_NULL) */
  74923. uInt extra_max; /* space at extra (only when reading header) */
  74924. Bytef *name; /* pointer to zero-terminated file name or Z_NULL */
  74925. uInt name_max; /* space at name (only when reading header) */
  74926. Bytef *comment; /* pointer to zero-terminated comment or Z_NULL */
  74927. uInt comm_max; /* space at comment (only when reading header) */
  74928. int hcrc; /* true if there was or will be a header crc */
  74929. int done; /* true when done reading gzip header (not used
  74930. when writing a gzip file) */
  74931. } gz_header;
  74932. typedef gz_header FAR *gz_headerp;
  74933. /*
  74934. The application must update next_in and avail_in when avail_in has
  74935. dropped to zero. It must update next_out and avail_out when avail_out
  74936. has dropped to zero. The application must initialize zalloc, zfree and
  74937. opaque before calling the init function. All other fields are set by the
  74938. compression library and must not be updated by the application.
  74939. The opaque value provided by the application will be passed as the first
  74940. parameter for calls of zalloc and zfree. This can be useful for custom
  74941. memory management. The compression library attaches no meaning to the
  74942. opaque value.
  74943. zalloc must return Z_NULL if there is not enough memory for the object.
  74944. If zlib is used in a multi-threaded application, zalloc and zfree must be
  74945. thread safe.
  74946. On 16-bit systems, the functions zalloc and zfree must be able to allocate
  74947. exactly 65536 bytes, but will not be required to allocate more than this
  74948. if the symbol MAXSEG_64K is defined (see zconf.h). WARNING: On MSDOS,
  74949. pointers returned by zalloc for objects of exactly 65536 bytes *must*
  74950. have their offset normalized to zero. The default allocation function
  74951. provided by this library ensures this (see zutil.c). To reduce memory
  74952. requirements and avoid any allocation of 64K objects, at the expense of
  74953. compression ratio, compile the library with -DMAX_WBITS=14 (see zconf.h).
  74954. The fields total_in and total_out can be used for statistics or
  74955. progress reports. After compression, total_in holds the total size of
  74956. the uncompressed data and may be saved for use in the decompressor
  74957. (particularly if the decompressor wants to decompress everything in
  74958. a single step).
  74959. */
  74960. /* constants */
  74961. #define Z_NO_FLUSH 0
  74962. #define Z_PARTIAL_FLUSH 1 /* will be removed, use Z_SYNC_FLUSH instead */
  74963. #define Z_SYNC_FLUSH 2
  74964. #define Z_FULL_FLUSH 3
  74965. #define Z_FINISH 4
  74966. #define Z_BLOCK 5
  74967. /* Allowed flush values; see deflate() and inflate() below for details */
  74968. #define Z_OK 0
  74969. #define Z_STREAM_END 1
  74970. #define Z_NEED_DICT 2
  74971. #define Z_ERRNO (-1)
  74972. #define Z_STREAM_ERROR (-2)
  74973. #define Z_DATA_ERROR (-3)
  74974. #define Z_MEM_ERROR (-4)
  74975. #define Z_BUF_ERROR (-5)
  74976. #define Z_VERSION_ERROR (-6)
  74977. /* Return codes for the compression/decompression functions. Negative
  74978. * values are errors, positive values are used for special but normal events.
  74979. */
  74980. #define Z_NO_COMPRESSION 0
  74981. #define Z_BEST_SPEED 1
  74982. #define Z_BEST_COMPRESSION 9
  74983. #define Z_DEFAULT_COMPRESSION (-1)
  74984. /* compression levels */
  74985. #define Z_FILTERED 1
  74986. #define Z_HUFFMAN_ONLY 2
  74987. #define Z_RLE 3
  74988. #define Z_FIXED 4
  74989. #define Z_DEFAULT_STRATEGY 0
  74990. /* compression strategy; see deflateInit2() below for details */
  74991. #define Z_BINARY 0
  74992. #define Z_TEXT 1
  74993. #define Z_ASCII Z_TEXT /* for compatibility with 1.2.2 and earlier */
  74994. #define Z_UNKNOWN 2
  74995. /* Possible values of the data_type field (though see inflate()) */
  74996. #define Z_DEFLATED 8
  74997. /* The deflate compression method (the only one supported in this version) */
  74998. #define Z_NULL 0 /* for initializing zalloc, zfree, opaque */
  74999. #define zlib_version zlibVersion()
  75000. /* for compatibility with versions < 1.0.2 */
  75001. /* basic functions */
  75002. //ZEXTERN const char * ZEXPORT zlibVersion OF((void));
  75003. /* The application can compare zlibVersion and ZLIB_VERSION for consistency.
  75004. If the first character differs, the library code actually used is
  75005. not compatible with the zlib.h header file used by the application.
  75006. This check is automatically made by deflateInit and inflateInit.
  75007. */
  75008. /*
  75009. ZEXTERN int ZEXPORT deflateInit OF((z_streamp strm, int level));
  75010. Initializes the internal stream state for compression. The fields
  75011. zalloc, zfree and opaque must be initialized before by the caller.
  75012. If zalloc and zfree are set to Z_NULL, deflateInit updates them to
  75013. use default allocation functions.
  75014. The compression level must be Z_DEFAULT_COMPRESSION, or between 0 and 9:
  75015. 1 gives best speed, 9 gives best compression, 0 gives no compression at
  75016. all (the input data is simply copied a block at a time).
  75017. Z_DEFAULT_COMPRESSION requests a default compromise between speed and
  75018. compression (currently equivalent to level 6).
  75019. deflateInit returns Z_OK if success, Z_MEM_ERROR if there was not
  75020. enough memory, Z_STREAM_ERROR if level is not a valid compression level,
  75021. Z_VERSION_ERROR if the zlib library version (zlib_version) is incompatible
  75022. with the version assumed by the caller (ZLIB_VERSION).
  75023. msg is set to null if there is no error message. deflateInit does not
  75024. perform any compression: this will be done by deflate().
  75025. */
  75026. ZEXTERN int ZEXPORT deflate OF((z_streamp strm, int flush));
  75027. /*
  75028. deflate compresses as much data as possible, and stops when the input
  75029. buffer becomes empty or the output buffer becomes full. It may introduce some
  75030. output latency (reading input without producing any output) except when
  75031. forced to flush.
  75032. The detailed semantics are as follows. deflate performs one or both of the
  75033. following actions:
  75034. - Compress more input starting at next_in and update next_in and avail_in
  75035. accordingly. If not all input can be processed (because there is not
  75036. enough room in the output buffer), next_in and avail_in are updated and
  75037. processing will resume at this point for the next call of deflate().
  75038. - Provide more output starting at next_out and update next_out and avail_out
  75039. accordingly. This action is forced if the parameter flush is non zero.
  75040. Forcing flush frequently degrades the compression ratio, so this parameter
  75041. should be set only when necessary (in interactive applications).
  75042. Some output may be provided even if flush is not set.
  75043. Before the call of deflate(), the application should ensure that at least
  75044. one of the actions is possible, by providing more input and/or consuming
  75045. more output, and updating avail_in or avail_out accordingly; avail_out
  75046. should never be zero before the call. The application can consume the
  75047. compressed output when it wants, for example when the output buffer is full
  75048. (avail_out == 0), or after each call of deflate(). If deflate returns Z_OK
  75049. and with zero avail_out, it must be called again after making room in the
  75050. output buffer because there might be more output pending.
  75051. Normally the parameter flush is set to Z_NO_FLUSH, which allows deflate to
  75052. decide how much data to accumualte before producing output, in order to
  75053. maximize compression.
  75054. If the parameter flush is set to Z_SYNC_FLUSH, all pending output is
  75055. flushed to the output buffer and the output is aligned on a byte boundary, so
  75056. that the decompressor can get all input data available so far. (In particular
  75057. avail_in is zero after the call if enough output space has been provided
  75058. before the call.) Flushing may degrade compression for some compression
  75059. algorithms and so it should be used only when necessary.
  75060. If flush is set to Z_FULL_FLUSH, all output is flushed as with
  75061. Z_SYNC_FLUSH, and the compression state is reset so that decompression can
  75062. restart from this point if previous compressed data has been damaged or if
  75063. random access is desired. Using Z_FULL_FLUSH too often can seriously degrade
  75064. compression.
  75065. If deflate returns with avail_out == 0, this function must be called again
  75066. with the same value of the flush parameter and more output space (updated
  75067. avail_out), until the flush is complete (deflate returns with non-zero
  75068. avail_out). In the case of a Z_FULL_FLUSH or Z_SYNC_FLUSH, make sure that
  75069. avail_out is greater than six to avoid repeated flush markers due to
  75070. avail_out == 0 on return.
  75071. If the parameter flush is set to Z_FINISH, pending input is processed,
  75072. pending output is flushed and deflate returns with Z_STREAM_END if there
  75073. was enough output space; if deflate returns with Z_OK, this function must be
  75074. called again with Z_FINISH and more output space (updated avail_out) but no
  75075. more input data, until it returns with Z_STREAM_END or an error. After
  75076. deflate has returned Z_STREAM_END, the only possible operations on the
  75077. stream are deflateReset or deflateEnd.
  75078. Z_FINISH can be used immediately after deflateInit if all the compression
  75079. is to be done in a single step. In this case, avail_out must be at least
  75080. the value returned by deflateBound (see below). If deflate does not return
  75081. Z_STREAM_END, then it must be called again as described above.
  75082. deflate() sets strm->adler to the adler32 checksum of all input read
  75083. so far (that is, total_in bytes).
  75084. deflate() may update strm->data_type if it can make a good guess about
  75085. the input data type (Z_BINARY or Z_TEXT). In doubt, the data is considered
  75086. binary. This field is only for information purposes and does not affect
  75087. the compression algorithm in any manner.
  75088. deflate() returns Z_OK if some progress has been made (more input
  75089. processed or more output produced), Z_STREAM_END if all input has been
  75090. consumed and all output has been produced (only when flush is set to
  75091. Z_FINISH), Z_STREAM_ERROR if the stream state was inconsistent (for example
  75092. if next_in or next_out was NULL), Z_BUF_ERROR if no progress is possible
  75093. (for example avail_in or avail_out was zero). Note that Z_BUF_ERROR is not
  75094. fatal, and deflate() can be called again with more input and more output
  75095. space to continue compressing.
  75096. */
  75097. ZEXTERN int ZEXPORT deflateEnd OF((z_streamp strm));
  75098. /*
  75099. All dynamically allocated data structures for this stream are freed.
  75100. This function discards any unprocessed input and does not flush any
  75101. pending output.
  75102. deflateEnd returns Z_OK if success, Z_STREAM_ERROR if the
  75103. stream state was inconsistent, Z_DATA_ERROR if the stream was freed
  75104. prematurely (some input or output was discarded). In the error case,
  75105. msg may be set but then points to a static string (which must not be
  75106. deallocated).
  75107. */
  75108. /*
  75109. ZEXTERN int ZEXPORT inflateInit OF((z_streamp strm));
  75110. Initializes the internal stream state for decompression. The fields
  75111. next_in, avail_in, zalloc, zfree and opaque must be initialized before by
  75112. the caller. If next_in is not Z_NULL and avail_in is large enough (the exact
  75113. value depends on the compression method), inflateInit determines the
  75114. compression method from the zlib header and allocates all data structures
  75115. accordingly; otherwise the allocation will be deferred to the first call of
  75116. inflate. If zalloc and zfree are set to Z_NULL, inflateInit updates them to
  75117. use default allocation functions.
  75118. inflateInit returns Z_OK if success, Z_MEM_ERROR if there was not enough
  75119. memory, Z_VERSION_ERROR if the zlib library version is incompatible with the
  75120. version assumed by the caller. msg is set to null if there is no error
  75121. message. inflateInit does not perform any decompression apart from reading
  75122. the zlib header if present: this will be done by inflate(). (So next_in and
  75123. avail_in may be modified, but next_out and avail_out are unchanged.)
  75124. */
  75125. ZEXTERN int ZEXPORT inflate OF((z_streamp strm, int flush));
  75126. /*
  75127. inflate decompresses as much data as possible, and stops when the input
  75128. buffer becomes empty or the output buffer becomes full. It may introduce
  75129. some output latency (reading input without producing any output) except when
  75130. forced to flush.
  75131. The detailed semantics are as follows. inflate performs one or both of the
  75132. following actions:
  75133. - Decompress more input starting at next_in and update next_in and avail_in
  75134. accordingly. If not all input can be processed (because there is not
  75135. enough room in the output buffer), next_in is updated and processing
  75136. will resume at this point for the next call of inflate().
  75137. - Provide more output starting at next_out and update next_out and avail_out
  75138. accordingly. inflate() provides as much output as possible, until there
  75139. is no more input data or no more space in the output buffer (see below
  75140. about the flush parameter).
  75141. Before the call of inflate(), the application should ensure that at least
  75142. one of the actions is possible, by providing more input and/or consuming
  75143. more output, and updating the next_* and avail_* values accordingly.
  75144. The application can consume the uncompressed output when it wants, for
  75145. example when the output buffer is full (avail_out == 0), or after each
  75146. call of inflate(). If inflate returns Z_OK and with zero avail_out, it
  75147. must be called again after making room in the output buffer because there
  75148. might be more output pending.
  75149. The flush parameter of inflate() can be Z_NO_FLUSH, Z_SYNC_FLUSH,
  75150. Z_FINISH, or Z_BLOCK. Z_SYNC_FLUSH requests that inflate() flush as much
  75151. output as possible to the output buffer. Z_BLOCK requests that inflate() stop
  75152. if and when it gets to the next deflate block boundary. When decoding the
  75153. zlib or gzip format, this will cause inflate() to return immediately after
  75154. the header and before the first block. When doing a raw inflate, inflate()
  75155. will go ahead and process the first block, and will return when it gets to
  75156. the end of that block, or when it runs out of data.
  75157. The Z_BLOCK option assists in appending to or combining deflate streams.
  75158. Also to assist in this, on return inflate() will set strm->data_type to the
  75159. number of unused bits in the last byte taken from strm->next_in, plus 64
  75160. if inflate() is currently decoding the last block in the deflate stream,
  75161. plus 128 if inflate() returned immediately after decoding an end-of-block
  75162. code or decoding the complete header up to just before the first byte of the
  75163. deflate stream. The end-of-block will not be indicated until all of the
  75164. uncompressed data from that block has been written to strm->next_out. The
  75165. number of unused bits may in general be greater than seven, except when
  75166. bit 7 of data_type is set, in which case the number of unused bits will be
  75167. less than eight.
  75168. inflate() should normally be called until it returns Z_STREAM_END or an
  75169. error. However if all decompression is to be performed in a single step
  75170. (a single call of inflate), the parameter flush should be set to
  75171. Z_FINISH. In this case all pending input is processed and all pending
  75172. output is flushed; avail_out must be large enough to hold all the
  75173. uncompressed data. (The size of the uncompressed data may have been saved
  75174. by the compressor for this purpose.) The next operation on this stream must
  75175. be inflateEnd to deallocate the decompression state. The use of Z_FINISH
  75176. is never required, but can be used to inform inflate that a faster approach
  75177. may be used for the single inflate() call.
  75178. In this implementation, inflate() always flushes as much output as
  75179. possible to the output buffer, and always uses the faster approach on the
  75180. first call. So the only effect of the flush parameter in this implementation
  75181. is on the return value of inflate(), as noted below, or when it returns early
  75182. because Z_BLOCK is used.
  75183. If a preset dictionary is needed after this call (see inflateSetDictionary
  75184. below), inflate sets strm->adler to the adler32 checksum of the dictionary
  75185. chosen by the compressor and returns Z_NEED_DICT; otherwise it sets
  75186. strm->adler to the adler32 checksum of all output produced so far (that is,
  75187. total_out bytes) and returns Z_OK, Z_STREAM_END or an error code as described
  75188. below. At the end of the stream, inflate() checks that its computed adler32
  75189. checksum is equal to that saved by the compressor and returns Z_STREAM_END
  75190. only if the checksum is correct.
  75191. inflate() will decompress and check either zlib-wrapped or gzip-wrapped
  75192. deflate data. The header type is detected automatically. Any information
  75193. contained in the gzip header is not retained, so applications that need that
  75194. information should instead use raw inflate, see inflateInit2() below, or
  75195. inflateBack() and perform their own processing of the gzip header and
  75196. trailer.
  75197. inflate() returns Z_OK if some progress has been made (more input processed
  75198. or more output produced), Z_STREAM_END if the end of the compressed data has
  75199. been reached and all uncompressed output has been produced, Z_NEED_DICT if a
  75200. preset dictionary is needed at this point, Z_DATA_ERROR if the input data was
  75201. corrupted (input stream not conforming to the zlib format or incorrect check
  75202. value), Z_STREAM_ERROR if the stream structure was inconsistent (for example
  75203. if next_in or next_out was NULL), Z_MEM_ERROR if there was not enough memory,
  75204. Z_BUF_ERROR if no progress is possible or if there was not enough room in the
  75205. output buffer when Z_FINISH is used. Note that Z_BUF_ERROR is not fatal, and
  75206. inflate() can be called again with more input and more output space to
  75207. continue decompressing. If Z_DATA_ERROR is returned, the application may then
  75208. call inflateSync() to look for a good compression block if a partial recovery
  75209. of the data is desired.
  75210. */
  75211. ZEXTERN int ZEXPORT inflateEnd OF((z_streamp strm));
  75212. /*
  75213. All dynamically allocated data structures for this stream are freed.
  75214. This function discards any unprocessed input and does not flush any
  75215. pending output.
  75216. inflateEnd returns Z_OK if success, Z_STREAM_ERROR if the stream state
  75217. was inconsistent. In the error case, msg may be set but then points to a
  75218. static string (which must not be deallocated).
  75219. */
  75220. /* Advanced functions */
  75221. /*
  75222. The following functions are needed only in some special applications.
  75223. */
  75224. /*
  75225. ZEXTERN int ZEXPORT deflateInit2 OF((z_streamp strm,
  75226. int level,
  75227. int method,
  75228. int windowBits,
  75229. int memLevel,
  75230. int strategy));
  75231. This is another version of deflateInit with more compression options. The
  75232. fields next_in, zalloc, zfree and opaque must be initialized before by
  75233. the caller.
  75234. The method parameter is the compression method. It must be Z_DEFLATED in
  75235. this version of the library.
  75236. The windowBits parameter is the base two logarithm of the window size
  75237. (the size of the history buffer). It should be in the range 8..15 for this
  75238. version of the library. Larger values of this parameter result in better
  75239. compression at the expense of memory usage. The default value is 15 if
  75240. deflateInit is used instead.
  75241. windowBits can also be -8..-15 for raw deflate. In this case, -windowBits
  75242. determines the window size. deflate() will then generate raw deflate data
  75243. with no zlib header or trailer, and will not compute an adler32 check value.
  75244. windowBits can also be greater than 15 for optional gzip encoding. Add
  75245. 16 to windowBits to write a simple gzip header and trailer around the
  75246. compressed data instead of a zlib wrapper. The gzip header will have no
  75247. file name, no extra data, no comment, no modification time (set to zero),
  75248. no header crc, and the operating system will be set to 255 (unknown). If a
  75249. gzip stream is being written, strm->adler is a crc32 instead of an adler32.
  75250. The memLevel parameter specifies how much memory should be allocated
  75251. for the internal compression state. memLevel=1 uses minimum memory but
  75252. is slow and reduces compression ratio; memLevel=9 uses maximum memory
  75253. for optimal speed. The default value is 8. See zconf.h for total memory
  75254. usage as a function of windowBits and memLevel.
  75255. The strategy parameter is used to tune the compression algorithm. Use the
  75256. value Z_DEFAULT_STRATEGY for normal data, Z_FILTERED for data produced by a
  75257. filter (or predictor), Z_HUFFMAN_ONLY to force Huffman encoding only (no
  75258. string match), or Z_RLE to limit match distances to one (run-length
  75259. encoding). Filtered data consists mostly of small values with a somewhat
  75260. random distribution. In this case, the compression algorithm is tuned to
  75261. compress them better. The effect of Z_FILTERED is to force more Huffman
  75262. coding and less string matching; it is somewhat intermediate between
  75263. Z_DEFAULT and Z_HUFFMAN_ONLY. Z_RLE is designed to be almost as fast as
  75264. Z_HUFFMAN_ONLY, but give better compression for PNG image data. The strategy
  75265. parameter only affects the compression ratio but not the correctness of the
  75266. compressed output even if it is not set appropriately. Z_FIXED prevents the
  75267. use of dynamic Huffman codes, allowing for a simpler decoder for special
  75268. applications.
  75269. deflateInit2 returns Z_OK if success, Z_MEM_ERROR if there was not enough
  75270. memory, Z_STREAM_ERROR if a parameter is invalid (such as an invalid
  75271. method). msg is set to null if there is no error message. deflateInit2 does
  75272. not perform any compression: this will be done by deflate().
  75273. */
  75274. ZEXTERN int ZEXPORT deflateSetDictionary OF((z_streamp strm,
  75275. const Bytef *dictionary,
  75276. uInt dictLength));
  75277. /*
  75278. Initializes the compression dictionary from the given byte sequence
  75279. without producing any compressed output. This function must be called
  75280. immediately after deflateInit, deflateInit2 or deflateReset, before any
  75281. call of deflate. The compressor and decompressor must use exactly the same
  75282. dictionary (see inflateSetDictionary).
  75283. The dictionary should consist of strings (byte sequences) that are likely
  75284. to be encountered later in the data to be compressed, with the most commonly
  75285. used strings preferably put towards the end of the dictionary. Using a
  75286. dictionary is most useful when the data to be compressed is short and can be
  75287. predicted with good accuracy; the data can then be compressed better than
  75288. with the default empty dictionary.
  75289. Depending on the size of the compression data structures selected by
  75290. deflateInit or deflateInit2, a part of the dictionary may in effect be
  75291. discarded, for example if the dictionary is larger than the window size in
  75292. deflate or deflate2. Thus the strings most likely to be useful should be
  75293. put at the end of the dictionary, not at the front. In addition, the
  75294. current implementation of deflate will use at most the window size minus
  75295. 262 bytes of the provided dictionary.
  75296. Upon return of this function, strm->adler is set to the adler32 value
  75297. of the dictionary; the decompressor may later use this value to determine
  75298. which dictionary has been used by the compressor. (The adler32 value
  75299. applies to the whole dictionary even if only a subset of the dictionary is
  75300. actually used by the compressor.) If a raw deflate was requested, then the
  75301. adler32 value is not computed and strm->adler is not set.
  75302. deflateSetDictionary returns Z_OK if success, or Z_STREAM_ERROR if a
  75303. parameter is invalid (such as NULL dictionary) or the stream state is
  75304. inconsistent (for example if deflate has already been called for this stream
  75305. or if the compression method is bsort). deflateSetDictionary does not
  75306. perform any compression: this will be done by deflate().
  75307. */
  75308. ZEXTERN int ZEXPORT deflateCopy OF((z_streamp dest,
  75309. z_streamp source));
  75310. /*
  75311. Sets the destination stream as a complete copy of the source stream.
  75312. This function can be useful when several compression strategies will be
  75313. tried, for example when there are several ways of pre-processing the input
  75314. data with a filter. The streams that will be discarded should then be freed
  75315. by calling deflateEnd. Note that deflateCopy duplicates the internal
  75316. compression state which can be quite large, so this strategy is slow and
  75317. can consume lots of memory.
  75318. deflateCopy returns Z_OK if success, Z_MEM_ERROR if there was not
  75319. enough memory, Z_STREAM_ERROR if the source stream state was inconsistent
  75320. (such as zalloc being NULL). msg is left unchanged in both source and
  75321. destination.
  75322. */
  75323. ZEXTERN int ZEXPORT deflateReset OF((z_streamp strm));
  75324. /*
  75325. This function is equivalent to deflateEnd followed by deflateInit,
  75326. but does not free and reallocate all the internal compression state.
  75327. The stream will keep the same compression level and any other attributes
  75328. that may have been set by deflateInit2.
  75329. deflateReset returns Z_OK if success, or Z_STREAM_ERROR if the source
  75330. stream state was inconsistent (such as zalloc or state being NULL).
  75331. */
  75332. ZEXTERN int ZEXPORT deflateParams OF((z_streamp strm,
  75333. int level,
  75334. int strategy));
  75335. /*
  75336. Dynamically update the compression level and compression strategy. The
  75337. interpretation of level and strategy is as in deflateInit2. This can be
  75338. used to switch between compression and straight copy of the input data, or
  75339. to switch to a different kind of input data requiring a different
  75340. strategy. If the compression level is changed, the input available so far
  75341. is compressed with the old level (and may be flushed); the new level will
  75342. take effect only at the next call of deflate().
  75343. Before the call of deflateParams, the stream state must be set as for
  75344. a call of deflate(), since the currently available input may have to
  75345. be compressed and flushed. In particular, strm->avail_out must be non-zero.
  75346. deflateParams returns Z_OK if success, Z_STREAM_ERROR if the source
  75347. stream state was inconsistent or if a parameter was invalid, Z_BUF_ERROR
  75348. if strm->avail_out was zero.
  75349. */
  75350. ZEXTERN int ZEXPORT deflateTune OF((z_streamp strm,
  75351. int good_length,
  75352. int max_lazy,
  75353. int nice_length,
  75354. int max_chain));
  75355. /*
  75356. Fine tune deflate's internal compression parameters. This should only be
  75357. used by someone who understands the algorithm used by zlib's deflate for
  75358. searching for the best matching string, and even then only by the most
  75359. fanatic optimizer trying to squeeze out the last compressed bit for their
  75360. specific input data. Read the deflate.c source code for the meaning of the
  75361. max_lazy, good_length, nice_length, and max_chain parameters.
  75362. deflateTune() can be called after deflateInit() or deflateInit2(), and
  75363. returns Z_OK on success, or Z_STREAM_ERROR for an invalid deflate stream.
  75364. */
  75365. ZEXTERN uLong ZEXPORT deflateBound OF((z_streamp strm,
  75366. uLong sourceLen));
  75367. /*
  75368. deflateBound() returns an upper bound on the compressed size after
  75369. deflation of sourceLen bytes. It must be called after deflateInit()
  75370. or deflateInit2(). This would be used to allocate an output buffer
  75371. for deflation in a single pass, and so would be called before deflate().
  75372. */
  75373. ZEXTERN int ZEXPORT deflatePrime OF((z_streamp strm,
  75374. int bits,
  75375. int value));
  75376. /*
  75377. deflatePrime() inserts bits in the deflate output stream. The intent
  75378. is that this function is used to start off the deflate output with the
  75379. bits leftover from a previous deflate stream when appending to it. As such,
  75380. this function can only be used for raw deflate, and must be used before the
  75381. first deflate() call after a deflateInit2() or deflateReset(). bits must be
  75382. less than or equal to 16, and that many of the least significant bits of
  75383. value will be inserted in the output.
  75384. deflatePrime returns Z_OK if success, or Z_STREAM_ERROR if the source
  75385. stream state was inconsistent.
  75386. */
  75387. ZEXTERN int ZEXPORT deflateSetHeader OF((z_streamp strm,
  75388. gz_headerp head));
  75389. /*
  75390. deflateSetHeader() provides gzip header information for when a gzip
  75391. stream is requested by deflateInit2(). deflateSetHeader() may be called
  75392. after deflateInit2() or deflateReset() and before the first call of
  75393. deflate(). The text, time, os, extra field, name, and comment information
  75394. in the provided gz_header structure are written to the gzip header (xflag is
  75395. ignored -- the extra flags are set according to the compression level). The
  75396. caller must assure that, if not Z_NULL, name and comment are terminated with
  75397. a zero byte, and that if extra is not Z_NULL, that extra_len bytes are
  75398. available there. If hcrc is true, a gzip header crc is included. Note that
  75399. the current versions of the command-line version of gzip (up through version
  75400. 1.3.x) do not support header crc's, and will report that it is a "multi-part
  75401. gzip file" and give up.
  75402. If deflateSetHeader is not used, the default gzip header has text false,
  75403. the time set to zero, and os set to 255, with no extra, name, or comment
  75404. fields. The gzip header is returned to the default state by deflateReset().
  75405. deflateSetHeader returns Z_OK if success, or Z_STREAM_ERROR if the source
  75406. stream state was inconsistent.
  75407. */
  75408. /*
  75409. ZEXTERN int ZEXPORT inflateInit2 OF((z_streamp strm,
  75410. int windowBits));
  75411. This is another version of inflateInit with an extra parameter. The
  75412. fields next_in, avail_in, zalloc, zfree and opaque must be initialized
  75413. before by the caller.
  75414. The windowBits parameter is the base two logarithm of the maximum window
  75415. size (the size of the history buffer). It should be in the range 8..15 for
  75416. this version of the library. The default value is 15 if inflateInit is used
  75417. instead. windowBits must be greater than or equal to the windowBits value
  75418. provided to deflateInit2() while compressing, or it must be equal to 15 if
  75419. deflateInit2() was not used. If a compressed stream with a larger window
  75420. size is given as input, inflate() will return with the error code
  75421. Z_DATA_ERROR instead of trying to allocate a larger window.
  75422. windowBits can also be -8..-15 for raw inflate. In this case, -windowBits
  75423. determines the window size. inflate() will then process raw deflate data,
  75424. not looking for a zlib or gzip header, not generating a check value, and not
  75425. looking for any check values for comparison at the end of the stream. This
  75426. is for use with other formats that use the deflate compressed data format
  75427. such as zip. Those formats provide their own check values. If a custom
  75428. format is developed using the raw deflate format for compressed data, it is
  75429. recommended that a check value such as an adler32 or a crc32 be applied to
  75430. the uncompressed data as is done in the zlib, gzip, and zip formats. For
  75431. most applications, the zlib format should be used as is. Note that comments
  75432. above on the use in deflateInit2() applies to the magnitude of windowBits.
  75433. windowBits can also be greater than 15 for optional gzip decoding. Add
  75434. 32 to windowBits to enable zlib and gzip decoding with automatic header
  75435. detection, or add 16 to decode only the gzip format (the zlib format will
  75436. return a Z_DATA_ERROR). If a gzip stream is being decoded, strm->adler is
  75437. a crc32 instead of an adler32.
  75438. inflateInit2 returns Z_OK if success, Z_MEM_ERROR if there was not enough
  75439. memory, Z_STREAM_ERROR if a parameter is invalid (such as a null strm). msg
  75440. is set to null if there is no error message. inflateInit2 does not perform
  75441. any decompression apart from reading the zlib header if present: this will
  75442. be done by inflate(). (So next_in and avail_in may be modified, but next_out
  75443. and avail_out are unchanged.)
  75444. */
  75445. ZEXTERN int ZEXPORT inflateSetDictionary OF((z_streamp strm,
  75446. const Bytef *dictionary,
  75447. uInt dictLength));
  75448. /*
  75449. Initializes the decompression dictionary from the given uncompressed byte
  75450. sequence. This function must be called immediately after a call of inflate,
  75451. if that call returned Z_NEED_DICT. The dictionary chosen by the compressor
  75452. can be determined from the adler32 value returned by that call of inflate.
  75453. The compressor and decompressor must use exactly the same dictionary (see
  75454. deflateSetDictionary). For raw inflate, this function can be called
  75455. immediately after inflateInit2() or inflateReset() and before any call of
  75456. inflate() to set the dictionary. The application must insure that the
  75457. dictionary that was used for compression is provided.
  75458. inflateSetDictionary returns Z_OK if success, Z_STREAM_ERROR if a
  75459. parameter is invalid (such as NULL dictionary) or the stream state is
  75460. inconsistent, Z_DATA_ERROR if the given dictionary doesn't match the
  75461. expected one (incorrect adler32 value). inflateSetDictionary does not
  75462. perform any decompression: this will be done by subsequent calls of
  75463. inflate().
  75464. */
  75465. ZEXTERN int ZEXPORT inflateSync OF((z_streamp strm));
  75466. /*
  75467. Skips invalid compressed data until a full flush point (see above the
  75468. description of deflate with Z_FULL_FLUSH) can be found, or until all
  75469. available input is skipped. No output is provided.
  75470. inflateSync returns Z_OK if a full flush point has been found, Z_BUF_ERROR
  75471. if no more input was provided, Z_DATA_ERROR if no flush point has been found,
  75472. or Z_STREAM_ERROR if the stream structure was inconsistent. In the success
  75473. case, the application may save the current current value of total_in which
  75474. indicates where valid compressed data was found. In the error case, the
  75475. application may repeatedly call inflateSync, providing more input each time,
  75476. until success or end of the input data.
  75477. */
  75478. ZEXTERN int ZEXPORT inflateCopy OF((z_streamp dest,
  75479. z_streamp source));
  75480. /*
  75481. Sets the destination stream as a complete copy of the source stream.
  75482. This function can be useful when randomly accessing a large stream. The
  75483. first pass through the stream can periodically record the inflate state,
  75484. allowing restarting inflate at those points when randomly accessing the
  75485. stream.
  75486. inflateCopy returns Z_OK if success, Z_MEM_ERROR if there was not
  75487. enough memory, Z_STREAM_ERROR if the source stream state was inconsistent
  75488. (such as zalloc being NULL). msg is left unchanged in both source and
  75489. destination.
  75490. */
  75491. ZEXTERN int ZEXPORT inflateReset OF((z_streamp strm));
  75492. /*
  75493. This function is equivalent to inflateEnd followed by inflateInit,
  75494. but does not free and reallocate all the internal decompression state.
  75495. The stream will keep attributes that may have been set by inflateInit2.
  75496. inflateReset returns Z_OK if success, or Z_STREAM_ERROR if the source
  75497. stream state was inconsistent (such as zalloc or state being NULL).
  75498. */
  75499. ZEXTERN int ZEXPORT inflatePrime OF((z_streamp strm,
  75500. int bits,
  75501. int value));
  75502. /*
  75503. This function inserts bits in the inflate input stream. The intent is
  75504. that this function is used to start inflating at a bit position in the
  75505. middle of a byte. The provided bits will be used before any bytes are used
  75506. from next_in. This function should only be used with raw inflate, and
  75507. should be used before the first inflate() call after inflateInit2() or
  75508. inflateReset(). bits must be less than or equal to 16, and that many of the
  75509. least significant bits of value will be inserted in the input.
  75510. inflatePrime returns Z_OK if success, or Z_STREAM_ERROR if the source
  75511. stream state was inconsistent.
  75512. */
  75513. ZEXTERN int ZEXPORT inflateGetHeader OF((z_streamp strm,
  75514. gz_headerp head));
  75515. /*
  75516. inflateGetHeader() requests that gzip header information be stored in the
  75517. provided gz_header structure. inflateGetHeader() may be called after
  75518. inflateInit2() or inflateReset(), and before the first call of inflate().
  75519. As inflate() processes the gzip stream, head->done is zero until the header
  75520. is completed, at which time head->done is set to one. If a zlib stream is
  75521. being decoded, then head->done is set to -1 to indicate that there will be
  75522. no gzip header information forthcoming. Note that Z_BLOCK can be used to
  75523. force inflate() to return immediately after header processing is complete
  75524. and before any actual data is decompressed.
  75525. The text, time, xflags, and os fields are filled in with the gzip header
  75526. contents. hcrc is set to true if there is a header CRC. (The header CRC
  75527. was valid if done is set to one.) If extra is not Z_NULL, then extra_max
  75528. contains the maximum number of bytes to write to extra. Once done is true,
  75529. extra_len contains the actual extra field length, and extra contains the
  75530. extra field, or that field truncated if extra_max is less than extra_len.
  75531. If name is not Z_NULL, then up to name_max characters are written there,
  75532. terminated with a zero unless the length is greater than name_max. If
  75533. comment is not Z_NULL, then up to comm_max characters are written there,
  75534. terminated with a zero unless the length is greater than comm_max. When
  75535. any of extra, name, or comment are not Z_NULL and the respective field is
  75536. not present in the header, then that field is set to Z_NULL to signal its
  75537. absence. This allows the use of deflateSetHeader() with the returned
  75538. structure to duplicate the header. However if those fields are set to
  75539. allocated memory, then the application will need to save those pointers
  75540. elsewhere so that they can be eventually freed.
  75541. If inflateGetHeader is not used, then the header information is simply
  75542. discarded. The header is always checked for validity, including the header
  75543. CRC if present. inflateReset() will reset the process to discard the header
  75544. information. The application would need to call inflateGetHeader() again to
  75545. retrieve the header from the next gzip stream.
  75546. inflateGetHeader returns Z_OK if success, or Z_STREAM_ERROR if the source
  75547. stream state was inconsistent.
  75548. */
  75549. /*
  75550. ZEXTERN int ZEXPORT inflateBackInit OF((z_streamp strm, int windowBits,
  75551. unsigned char FAR *window));
  75552. Initialize the internal stream state for decompression using inflateBack()
  75553. calls. The fields zalloc, zfree and opaque in strm must be initialized
  75554. before the call. If zalloc and zfree are Z_NULL, then the default library-
  75555. derived memory allocation routines are used. windowBits is the base two
  75556. logarithm of the window size, in the range 8..15. window is a caller
  75557. supplied buffer of that size. Except for special applications where it is
  75558. assured that deflate was used with small window sizes, windowBits must be 15
  75559. and a 32K byte window must be supplied to be able to decompress general
  75560. deflate streams.
  75561. See inflateBack() for the usage of these routines.
  75562. inflateBackInit will return Z_OK on success, Z_STREAM_ERROR if any of
  75563. the paramaters are invalid, Z_MEM_ERROR if the internal state could not
  75564. be allocated, or Z_VERSION_ERROR if the version of the library does not
  75565. match the version of the header file.
  75566. */
  75567. typedef unsigned (*in_func) OF((void FAR *, unsigned char FAR * FAR *));
  75568. typedef int (*out_func) OF((void FAR *, unsigned char FAR *, unsigned));
  75569. ZEXTERN int ZEXPORT inflateBack OF((z_streamp strm,
  75570. in_func in, void FAR *in_desc,
  75571. out_func out, void FAR *out_desc));
  75572. /*
  75573. inflateBack() does a raw inflate with a single call using a call-back
  75574. interface for input and output. This is more efficient than inflate() for
  75575. file i/o applications in that it avoids copying between the output and the
  75576. sliding window by simply making the window itself the output buffer. This
  75577. function trusts the application to not change the output buffer passed by
  75578. the output function, at least until inflateBack() returns.
  75579. inflateBackInit() must be called first to allocate the internal state
  75580. and to initialize the state with the user-provided window buffer.
  75581. inflateBack() may then be used multiple times to inflate a complete, raw
  75582. deflate stream with each call. inflateBackEnd() is then called to free
  75583. the allocated state.
  75584. A raw deflate stream is one with no zlib or gzip header or trailer.
  75585. This routine would normally be used in a utility that reads zip or gzip
  75586. files and writes out uncompressed files. The utility would decode the
  75587. header and process the trailer on its own, hence this routine expects
  75588. only the raw deflate stream to decompress. This is different from the
  75589. normal behavior of inflate(), which expects either a zlib or gzip header and
  75590. trailer around the deflate stream.
  75591. inflateBack() uses two subroutines supplied by the caller that are then
  75592. called by inflateBack() for input and output. inflateBack() calls those
  75593. routines until it reads a complete deflate stream and writes out all of the
  75594. uncompressed data, or until it encounters an error. The function's
  75595. parameters and return types are defined above in the in_func and out_func
  75596. typedefs. inflateBack() will call in(in_desc, &buf) which should return the
  75597. number of bytes of provided input, and a pointer to that input in buf. If
  75598. there is no input available, in() must return zero--buf is ignored in that
  75599. case--and inflateBack() will return a buffer error. inflateBack() will call
  75600. out(out_desc, buf, len) to write the uncompressed data buf[0..len-1]. out()
  75601. should return zero on success, or non-zero on failure. If out() returns
  75602. non-zero, inflateBack() will return with an error. Neither in() nor out()
  75603. are permitted to change the contents of the window provided to
  75604. inflateBackInit(), which is also the buffer that out() uses to write from.
  75605. The length written by out() will be at most the window size. Any non-zero
  75606. amount of input may be provided by in().
  75607. For convenience, inflateBack() can be provided input on the first call by
  75608. setting strm->next_in and strm->avail_in. If that input is exhausted, then
  75609. in() will be called. Therefore strm->next_in must be initialized before
  75610. calling inflateBack(). If strm->next_in is Z_NULL, then in() will be called
  75611. immediately for input. If strm->next_in is not Z_NULL, then strm->avail_in
  75612. must also be initialized, and then if strm->avail_in is not zero, input will
  75613. initially be taken from strm->next_in[0 .. strm->avail_in - 1].
  75614. The in_desc and out_desc parameters of inflateBack() is passed as the
  75615. first parameter of in() and out() respectively when they are called. These
  75616. descriptors can be optionally used to pass any information that the caller-
  75617. supplied in() and out() functions need to do their job.
  75618. On return, inflateBack() will set strm->next_in and strm->avail_in to
  75619. pass back any unused input that was provided by the last in() call. The
  75620. return values of inflateBack() can be Z_STREAM_END on success, Z_BUF_ERROR
  75621. if in() or out() returned an error, Z_DATA_ERROR if there was a format
  75622. error in the deflate stream (in which case strm->msg is set to indicate the
  75623. nature of the error), or Z_STREAM_ERROR if the stream was not properly
  75624. initialized. In the case of Z_BUF_ERROR, an input or output error can be
  75625. distinguished using strm->next_in which will be Z_NULL only if in() returned
  75626. an error. If strm->next is not Z_NULL, then the Z_BUF_ERROR was due to
  75627. out() returning non-zero. (in() will always be called before out(), so
  75628. strm->next_in is assured to be defined if out() returns non-zero.) Note
  75629. that inflateBack() cannot return Z_OK.
  75630. */
  75631. ZEXTERN int ZEXPORT inflateBackEnd OF((z_streamp strm));
  75632. /*
  75633. All memory allocated by inflateBackInit() is freed.
  75634. inflateBackEnd() returns Z_OK on success, or Z_STREAM_ERROR if the stream
  75635. state was inconsistent.
  75636. */
  75637. //ZEXTERN uLong ZEXPORT zlibCompileFlags OF((void));
  75638. /* Return flags indicating compile-time options.
  75639. Type sizes, two bits each, 00 = 16 bits, 01 = 32, 10 = 64, 11 = other:
  75640. 1.0: size of uInt
  75641. 3.2: size of uLong
  75642. 5.4: size of voidpf (pointer)
  75643. 7.6: size of z_off_t
  75644. Compiler, assembler, and debug options:
  75645. 8: DEBUG
  75646. 9: ASMV or ASMINF -- use ASM code
  75647. 10: ZLIB_WINAPI -- exported functions use the WINAPI calling convention
  75648. 11: 0 (reserved)
  75649. One-time table building (smaller code, but not thread-safe if true):
  75650. 12: BUILDFIXED -- build static block decoding tables when needed
  75651. 13: DYNAMIC_CRC_TABLE -- build CRC calculation tables when needed
  75652. 14,15: 0 (reserved)
  75653. Library content (indicates missing functionality):
  75654. 16: NO_GZCOMPRESS -- gz* functions cannot compress (to avoid linking
  75655. deflate code when not needed)
  75656. 17: NO_GZIP -- deflate can't write gzip streams, and inflate can't detect
  75657. and decode gzip streams (to avoid linking crc code)
  75658. 18-19: 0 (reserved)
  75659. Operation variations (changes in library functionality):
  75660. 20: PKZIP_BUG_WORKAROUND -- slightly more permissive inflate
  75661. 21: FASTEST -- deflate algorithm with only one, lowest compression level
  75662. 22,23: 0 (reserved)
  75663. The sprintf variant used by gzprintf (zero is best):
  75664. 24: 0 = vs*, 1 = s* -- 1 means limited to 20 arguments after the format
  75665. 25: 0 = *nprintf, 1 = *printf -- 1 means gzprintf() not secure!
  75666. 26: 0 = returns value, 1 = void -- 1 means inferred string length returned
  75667. Remainder:
  75668. 27-31: 0 (reserved)
  75669. */
  75670. /* utility functions */
  75671. /*
  75672. The following utility functions are implemented on top of the
  75673. basic stream-oriented functions. To simplify the interface, some
  75674. default options are assumed (compression level and memory usage,
  75675. standard memory allocation functions). The source code of these
  75676. utility functions can easily be modified if you need special options.
  75677. */
  75678. ZEXTERN int ZEXPORT compress OF((Bytef *dest, uLongf *destLen,
  75679. const Bytef *source, uLong sourceLen));
  75680. /*
  75681. Compresses the source buffer into the destination buffer. sourceLen is
  75682. the byte length of the source buffer. Upon entry, destLen is the total
  75683. size of the destination buffer, which must be at least the value returned
  75684. by compressBound(sourceLen). Upon exit, destLen is the actual size of the
  75685. compressed buffer.
  75686. This function can be used to compress a whole file at once if the
  75687. input file is mmap'ed.
  75688. compress returns Z_OK if success, Z_MEM_ERROR if there was not
  75689. enough memory, Z_BUF_ERROR if there was not enough room in the output
  75690. buffer.
  75691. */
  75692. ZEXTERN int ZEXPORT compress2 OF((Bytef *dest, uLongf *destLen,
  75693. const Bytef *source, uLong sourceLen,
  75694. int level));
  75695. /*
  75696. Compresses the source buffer into the destination buffer. The level
  75697. parameter has the same meaning as in deflateInit. sourceLen is the byte
  75698. length of the source buffer. Upon entry, destLen is the total size of the
  75699. destination buffer, which must be at least the value returned by
  75700. compressBound(sourceLen). Upon exit, destLen is the actual size of the
  75701. compressed buffer.
  75702. compress2 returns Z_OK if success, Z_MEM_ERROR if there was not enough
  75703. memory, Z_BUF_ERROR if there was not enough room in the output buffer,
  75704. Z_STREAM_ERROR if the level parameter is invalid.
  75705. */
  75706. ZEXTERN uLong ZEXPORT compressBound OF((uLong sourceLen));
  75707. /*
  75708. compressBound() returns an upper bound on the compressed size after
  75709. compress() or compress2() on sourceLen bytes. It would be used before
  75710. a compress() or compress2() call to allocate the destination buffer.
  75711. */
  75712. ZEXTERN int ZEXPORT uncompress OF((Bytef *dest, uLongf *destLen,
  75713. const Bytef *source, uLong sourceLen));
  75714. /*
  75715. Decompresses the source buffer into the destination buffer. sourceLen is
  75716. the byte length of the source buffer. Upon entry, destLen is the total
  75717. size of the destination buffer, which must be large enough to hold the
  75718. entire uncompressed data. (The size of the uncompressed data must have
  75719. been saved previously by the compressor and transmitted to the decompressor
  75720. by some mechanism outside the scope of this compression library.)
  75721. Upon exit, destLen is the actual size of the compressed buffer.
  75722. This function can be used to decompress a whole file at once if the
  75723. input file is mmap'ed.
  75724. uncompress returns Z_OK if success, Z_MEM_ERROR if there was not
  75725. enough memory, Z_BUF_ERROR if there was not enough room in the output
  75726. buffer, or Z_DATA_ERROR if the input data was corrupted or incomplete.
  75727. */
  75728. typedef voidp gzFile;
  75729. ZEXTERN gzFile ZEXPORT gzopen OF((const char *path, const char *mode));
  75730. /*
  75731. Opens a gzip (.gz) file for reading or writing. The mode parameter
  75732. is as in fopen ("rb" or "wb") but can also include a compression level
  75733. ("wb9") or a strategy: 'f' for filtered data as in "wb6f", 'h' for
  75734. Huffman only compression as in "wb1h", or 'R' for run-length encoding
  75735. as in "wb1R". (See the description of deflateInit2 for more information
  75736. about the strategy parameter.)
  75737. gzopen can be used to read a file which is not in gzip format; in this
  75738. case gzread will directly read from the file without decompression.
  75739. gzopen returns NULL if the file could not be opened or if there was
  75740. insufficient memory to allocate the (de)compression state; errno
  75741. can be checked to distinguish the two cases (if errno is zero, the
  75742. zlib error is Z_MEM_ERROR). */
  75743. ZEXTERN gzFile ZEXPORT gzdopen OF((int fd, const char *mode));
  75744. /*
  75745. gzdopen() associates a gzFile with the file descriptor fd. File
  75746. descriptors are obtained from calls like open, dup, creat, pipe or
  75747. fileno (in the file has been previously opened with fopen).
  75748. The mode parameter is as in gzopen.
  75749. The next call of gzclose on the returned gzFile will also close the
  75750. file descriptor fd, just like fclose(fdopen(fd), mode) closes the file
  75751. descriptor fd. If you want to keep fd open, use gzdopen(dup(fd), mode).
  75752. gzdopen returns NULL if there was insufficient memory to allocate
  75753. the (de)compression state.
  75754. */
  75755. ZEXTERN int ZEXPORT gzsetparams OF((gzFile file, int level, int strategy));
  75756. /*
  75757. Dynamically update the compression level or strategy. See the description
  75758. of deflateInit2 for the meaning of these parameters.
  75759. gzsetparams returns Z_OK if success, or Z_STREAM_ERROR if the file was not
  75760. opened for writing.
  75761. */
  75762. ZEXTERN int ZEXPORT gzread OF((gzFile file, voidp buf, unsigned len));
  75763. /*
  75764. Reads the given number of uncompressed bytes from the compressed file.
  75765. If the input file was not in gzip format, gzread copies the given number
  75766. of bytes into the buffer.
  75767. gzread returns the number of uncompressed bytes actually read (0 for
  75768. end of file, -1 for error). */
  75769. ZEXTERN int ZEXPORT gzwrite OF((gzFile file,
  75770. voidpc buf, unsigned len));
  75771. /*
  75772. Writes the given number of uncompressed bytes into the compressed file.
  75773. gzwrite returns the number of uncompressed bytes actually written
  75774. (0 in case of error).
  75775. */
  75776. ZEXTERN int ZEXPORTVA gzprintf OF((gzFile file, const char *format, ...));
  75777. /*
  75778. Converts, formats, and writes the args to the compressed file under
  75779. control of the format string, as in fprintf. gzprintf returns the number of
  75780. uncompressed bytes actually written (0 in case of error). The number of
  75781. uncompressed bytes written is limited to 4095. The caller should assure that
  75782. this limit is not exceeded. If it is exceeded, then gzprintf() will return
  75783. return an error (0) with nothing written. In this case, there may also be a
  75784. buffer overflow with unpredictable consequences, which is possible only if
  75785. zlib was compiled with the insecure functions sprintf() or vsprintf()
  75786. because the secure snprintf() or vsnprintf() functions were not available.
  75787. */
  75788. ZEXTERN int ZEXPORT gzputs OF((gzFile file, const char *s));
  75789. /*
  75790. Writes the given null-terminated string to the compressed file, excluding
  75791. the terminating null character.
  75792. gzputs returns the number of characters written, or -1 in case of error.
  75793. */
  75794. ZEXTERN char * ZEXPORT gzgets OF((gzFile file, char *buf, int len));
  75795. /*
  75796. Reads bytes from the compressed file until len-1 characters are read, or
  75797. a newline character is read and transferred to buf, or an end-of-file
  75798. condition is encountered. The string is then terminated with a null
  75799. character.
  75800. gzgets returns buf, or Z_NULL in case of error.
  75801. */
  75802. ZEXTERN int ZEXPORT gzputc OF((gzFile file, int c));
  75803. /*
  75804. Writes c, converted to an unsigned char, into the compressed file.
  75805. gzputc returns the value that was written, or -1 in case of error.
  75806. */
  75807. ZEXTERN int ZEXPORT gzgetc OF((gzFile file));
  75808. /*
  75809. Reads one byte from the compressed file. gzgetc returns this byte
  75810. or -1 in case of end of file or error.
  75811. */
  75812. ZEXTERN int ZEXPORT gzungetc OF((int c, gzFile file));
  75813. /*
  75814. Push one character back onto the stream to be read again later.
  75815. Only one character of push-back is allowed. gzungetc() returns the
  75816. character pushed, or -1 on failure. gzungetc() will fail if a
  75817. character has been pushed but not read yet, or if c is -1. The pushed
  75818. character will be discarded if the stream is repositioned with gzseek()
  75819. or gzrewind().
  75820. */
  75821. ZEXTERN int ZEXPORT gzflush OF((gzFile file, int flush));
  75822. /*
  75823. Flushes all pending output into the compressed file. The parameter
  75824. flush is as in the deflate() function. The return value is the zlib
  75825. error number (see function gzerror below). gzflush returns Z_OK if
  75826. the flush parameter is Z_FINISH and all output could be flushed.
  75827. gzflush should be called only when strictly necessary because it can
  75828. degrade compression.
  75829. */
  75830. ZEXTERN z_off_t ZEXPORT gzseek OF((gzFile file,
  75831. z_off_t offset, int whence));
  75832. /*
  75833. Sets the starting position for the next gzread or gzwrite on the
  75834. given compressed file. The offset represents a number of bytes in the
  75835. uncompressed data stream. The whence parameter is defined as in lseek(2);
  75836. the value SEEK_END is not supported.
  75837. If the file is opened for reading, this function is emulated but can be
  75838. extremely slow. If the file is opened for writing, only forward seeks are
  75839. supported; gzseek then compresses a sequence of zeroes up to the new
  75840. starting position.
  75841. gzseek returns the resulting offset location as measured in bytes from
  75842. the beginning of the uncompressed stream, or -1 in case of error, in
  75843. particular if the file is opened for writing and the new starting position
  75844. would be before the current position.
  75845. */
  75846. ZEXTERN int ZEXPORT gzrewind OF((gzFile file));
  75847. /*
  75848. Rewinds the given file. This function is supported only for reading.
  75849. gzrewind(file) is equivalent to (int)gzseek(file, 0L, SEEK_SET)
  75850. */
  75851. ZEXTERN z_off_t ZEXPORT gztell OF((gzFile file));
  75852. /*
  75853. Returns the starting position for the next gzread or gzwrite on the
  75854. given compressed file. This position represents a number of bytes in the
  75855. uncompressed data stream.
  75856. gztell(file) is equivalent to gzseek(file, 0L, SEEK_CUR)
  75857. */
  75858. ZEXTERN int ZEXPORT gzeof OF((gzFile file));
  75859. /*
  75860. Returns 1 when EOF has previously been detected reading the given
  75861. input stream, otherwise zero.
  75862. */
  75863. ZEXTERN int ZEXPORT gzdirect OF((gzFile file));
  75864. /*
  75865. Returns 1 if file is being read directly without decompression, otherwise
  75866. zero.
  75867. */
  75868. ZEXTERN int ZEXPORT gzclose OF((gzFile file));
  75869. /*
  75870. Flushes all pending output if necessary, closes the compressed file
  75871. and deallocates all the (de)compression state. The return value is the zlib
  75872. error number (see function gzerror below).
  75873. */
  75874. ZEXTERN const char * ZEXPORT gzerror OF((gzFile file, int *errnum));
  75875. /*
  75876. Returns the error message for the last error which occurred on the
  75877. given compressed file. errnum is set to zlib error number. If an
  75878. error occurred in the file system and not in the compression library,
  75879. errnum is set to Z_ERRNO and the application may consult errno
  75880. to get the exact error code.
  75881. */
  75882. ZEXTERN void ZEXPORT gzclearerr OF((gzFile file));
  75883. /*
  75884. Clears the error and end-of-file flags for file. This is analogous to the
  75885. clearerr() function in stdio. This is useful for continuing to read a gzip
  75886. file that is being written concurrently.
  75887. */
  75888. /* checksum functions */
  75889. /*
  75890. These functions are not related to compression but are exported
  75891. anyway because they might be useful in applications using the
  75892. compression library.
  75893. */
  75894. ZEXTERN uLong ZEXPORT adler32 OF((uLong adler, const Bytef *buf, uInt len));
  75895. /*
  75896. Update a running Adler-32 checksum with the bytes buf[0..len-1] and
  75897. return the updated checksum. If buf is NULL, this function returns
  75898. the required initial value for the checksum.
  75899. An Adler-32 checksum is almost as reliable as a CRC32 but can be computed
  75900. much faster. Usage example:
  75901. uLong adler = adler32(0L, Z_NULL, 0);
  75902. while (read_buffer(buffer, length) != EOF) {
  75903. adler = adler32(adler, buffer, length);
  75904. }
  75905. if (adler != original_adler) error();
  75906. */
  75907. ZEXTERN uLong ZEXPORT adler32_combine OF((uLong adler1, uLong adler2,
  75908. z_off_t len2));
  75909. /*
  75910. Combine two Adler-32 checksums into one. For two sequences of bytes, seq1
  75911. and seq2 with lengths len1 and len2, Adler-32 checksums were calculated for
  75912. each, adler1 and adler2. adler32_combine() returns the Adler-32 checksum of
  75913. seq1 and seq2 concatenated, requiring only adler1, adler2, and len2.
  75914. */
  75915. ZEXTERN uLong ZEXPORT crc32 OF((uLong crc, const Bytef *buf, uInt len));
  75916. /*
  75917. Update a running CRC-32 with the bytes buf[0..len-1] and return the
  75918. updated CRC-32. If buf is NULL, this function returns the required initial
  75919. value for the for the crc. Pre- and post-conditioning (one's complement) is
  75920. performed within this function so it shouldn't be done by the application.
  75921. Usage example:
  75922. uLong crc = crc32(0L, Z_NULL, 0);
  75923. while (read_buffer(buffer, length) != EOF) {
  75924. crc = crc32(crc, buffer, length);
  75925. }
  75926. if (crc != original_crc) error();
  75927. */
  75928. ZEXTERN uLong ZEXPORT crc32_combine OF((uLong crc1, uLong crc2, z_off_t len2));
  75929. /*
  75930. Combine two CRC-32 check values into one. For two sequences of bytes,
  75931. seq1 and seq2 with lengths len1 and len2, CRC-32 check values were
  75932. calculated for each, crc1 and crc2. crc32_combine() returns the CRC-32
  75933. check value of seq1 and seq2 concatenated, requiring only crc1, crc2, and
  75934. len2.
  75935. */
  75936. /* various hacks, don't look :) */
  75937. /* deflateInit and inflateInit are macros to allow checking the zlib version
  75938. * and the compiler's view of z_stream:
  75939. */
  75940. ZEXTERN int ZEXPORT deflateInit_ OF((z_streamp strm, int level,
  75941. const char *version, int stream_size));
  75942. ZEXTERN int ZEXPORT inflateInit_ OF((z_streamp strm,
  75943. const char *version, int stream_size));
  75944. ZEXTERN int ZEXPORT deflateInit2_ OF((z_streamp strm, int level, int method,
  75945. int windowBits, int memLevel,
  75946. int strategy, const char *version,
  75947. int stream_size));
  75948. ZEXTERN int ZEXPORT inflateInit2_ OF((z_streamp strm, int windowBits,
  75949. const char *version, int stream_size));
  75950. ZEXTERN int ZEXPORT inflateBackInit_ OF((z_streamp strm, int windowBits,
  75951. unsigned char FAR *window,
  75952. const char *version,
  75953. int stream_size));
  75954. #define deflateInit(strm, level) \
  75955. deflateInit_((strm), (level), ZLIB_VERSION, sizeof(z_stream))
  75956. #define inflateInit(strm) \
  75957. inflateInit_((strm), ZLIB_VERSION, sizeof(z_stream))
  75958. #define deflateInit2(strm, level, method, windowBits, memLevel, strategy) \
  75959. deflateInit2_((strm),(level),(method),(windowBits),(memLevel),\
  75960. (strategy), ZLIB_VERSION, sizeof(z_stream))
  75961. #define inflateInit2(strm, windowBits) \
  75962. inflateInit2_((strm), (windowBits), ZLIB_VERSION, sizeof(z_stream))
  75963. #define inflateBackInit(strm, windowBits, window) \
  75964. inflateBackInit_((strm), (windowBits), (window), \
  75965. ZLIB_VERSION, sizeof(z_stream))
  75966. #if !defined(ZUTIL_H) && !defined(NO_DUMMY_DECL)
  75967. struct internal_state {int dummy;}; /* hack for buggy compilers */
  75968. #endif
  75969. ZEXTERN const char * ZEXPORT zError OF((int));
  75970. ZEXTERN int ZEXPORT inflateSyncPoint OF((z_streamp z));
  75971. ZEXTERN const uLongf * ZEXPORT get_crc_table OF((void));
  75972. #ifdef __cplusplus
  75973. }
  75974. #endif
  75975. #endif /* ZLIB_H */
  75976. /*** End of inlined file: zlib.h ***/
  75977. #undef OS_CODE
  75978. #else
  75979. #include <zlib.h>
  75980. #endif
  75981. }
  75982. BEGIN_JUCE_NAMESPACE
  75983. // internal helper object that holds the zlib structures so they don't have to be
  75984. // included publicly.
  75985. class GZIPCompressorHelper
  75986. {
  75987. public:
  75988. GZIPCompressorHelper (const int compressionLevel, const bool nowrap)
  75989. : data (0),
  75990. dataSize (0),
  75991. compLevel (compressionLevel),
  75992. strategy (0),
  75993. setParams (true),
  75994. streamIsValid (false),
  75995. finished (false),
  75996. shouldFinish (false)
  75997. {
  75998. using namespace zlibNamespace;
  75999. zerostruct (stream);
  76000. streamIsValid = (deflateInit2 (&stream, compLevel, Z_DEFLATED,
  76001. nowrap ? -MAX_WBITS : MAX_WBITS,
  76002. 8, strategy) == Z_OK);
  76003. }
  76004. ~GZIPCompressorHelper()
  76005. {
  76006. using namespace zlibNamespace;
  76007. if (streamIsValid)
  76008. deflateEnd (&stream);
  76009. }
  76010. bool needsInput() const throw()
  76011. {
  76012. return dataSize <= 0;
  76013. }
  76014. void setInput (const uint8* const newData, const int size) throw()
  76015. {
  76016. data = newData;
  76017. dataSize = size;
  76018. }
  76019. int doNextBlock (uint8* const dest, const int destSize) throw()
  76020. {
  76021. using namespace zlibNamespace;
  76022. if (streamIsValid)
  76023. {
  76024. stream.next_in = const_cast <uint8*> (data);
  76025. stream.next_out = dest;
  76026. stream.avail_in = dataSize;
  76027. stream.avail_out = destSize;
  76028. const int result = setParams ? deflateParams (&stream, compLevel, strategy)
  76029. : deflate (&stream, shouldFinish ? Z_FINISH : Z_NO_FLUSH);
  76030. setParams = false;
  76031. switch (result)
  76032. {
  76033. case Z_STREAM_END:
  76034. finished = true;
  76035. // Deliberate fall-through..
  76036. case Z_OK:
  76037. data += dataSize - stream.avail_in;
  76038. dataSize = stream.avail_in;
  76039. return destSize - stream.avail_out;
  76040. default:
  76041. break;
  76042. }
  76043. }
  76044. return 0;
  76045. }
  76046. private:
  76047. zlibNamespace::z_stream stream;
  76048. const uint8* data;
  76049. int dataSize, compLevel, strategy;
  76050. bool setParams, streamIsValid;
  76051. public:
  76052. bool finished, shouldFinish;
  76053. };
  76054. const int gzipCompBufferSize = 32768;
  76055. GZIPCompressorOutputStream::GZIPCompressorOutputStream (OutputStream* const destStream_,
  76056. int compressionLevel,
  76057. const bool deleteDestStream,
  76058. const bool noWrap)
  76059. : destStream (destStream_),
  76060. streamToDelete (deleteDestStream ? destStream_ : 0),
  76061. buffer (gzipCompBufferSize)
  76062. {
  76063. if (compressionLevel < 1 || compressionLevel > 9)
  76064. compressionLevel = -1;
  76065. helper = new GZIPCompressorHelper (compressionLevel, noWrap);
  76066. }
  76067. GZIPCompressorOutputStream::~GZIPCompressorOutputStream()
  76068. {
  76069. flush();
  76070. }
  76071. void GZIPCompressorOutputStream::flush()
  76072. {
  76073. if (! helper->finished)
  76074. {
  76075. helper->shouldFinish = true;
  76076. while (! helper->finished)
  76077. doNextBlock();
  76078. }
  76079. destStream->flush();
  76080. }
  76081. bool GZIPCompressorOutputStream::write (const void* destBuffer, int howMany)
  76082. {
  76083. if (! helper->finished)
  76084. {
  76085. helper->setInput (static_cast <const uint8*> (destBuffer), howMany);
  76086. while (! helper->needsInput())
  76087. {
  76088. if (! doNextBlock())
  76089. return false;
  76090. }
  76091. }
  76092. return true;
  76093. }
  76094. bool GZIPCompressorOutputStream::doNextBlock()
  76095. {
  76096. const int len = helper->doNextBlock (buffer, gzipCompBufferSize);
  76097. if (len > 0)
  76098. return destStream->write (buffer, len);
  76099. else
  76100. return true;
  76101. }
  76102. int64 GZIPCompressorOutputStream::getPosition()
  76103. {
  76104. return destStream->getPosition();
  76105. }
  76106. bool GZIPCompressorOutputStream::setPosition (int64 /*newPosition*/)
  76107. {
  76108. jassertfalse // can't do it!
  76109. return false;
  76110. }
  76111. END_JUCE_NAMESPACE
  76112. /*** End of inlined file: juce_GZIPCompressorOutputStream.cpp ***/
  76113. /*** Start of inlined file: juce_GZIPDecompressorInputStream.cpp ***/
  76114. #if JUCE_MSVC
  76115. #pragma warning (push)
  76116. #pragma warning (disable: 4309 4305)
  76117. #endif
  76118. namespace zlibNamespace
  76119. {
  76120. #if JUCE_INCLUDE_ZLIB_CODE
  76121. extern "C"
  76122. {
  76123. #undef OS_CODE
  76124. #undef fdopen
  76125. #define ZLIB_INTERNAL
  76126. #define NO_DUMMY_DECL
  76127. /*** Start of inlined file: adler32.c ***/
  76128. /* @(#) $Id: adler32.c,v 1.1 2007/06/07 17:54:37 jules_rms Exp $ */
  76129. #define ZLIB_INTERNAL
  76130. #define BASE 65521UL /* largest prime smaller than 65536 */
  76131. #define NMAX 5552
  76132. /* NMAX is the largest n such that 255n(n+1)/2 + (n+1)(BASE-1) <= 2^32-1 */
  76133. #define DO1(buf,i) {adler += (buf)[i]; sum2 += adler;}
  76134. #define DO2(buf,i) DO1(buf,i); DO1(buf,i+1);
  76135. #define DO4(buf,i) DO2(buf,i); DO2(buf,i+2);
  76136. #define DO8(buf,i) DO4(buf,i); DO4(buf,i+4);
  76137. #define DO16(buf) DO8(buf,0); DO8(buf,8);
  76138. /* use NO_DIVIDE if your processor does not do division in hardware */
  76139. #ifdef NO_DIVIDE
  76140. # define MOD(a) \
  76141. do { \
  76142. if (a >= (BASE << 16)) a -= (BASE << 16); \
  76143. if (a >= (BASE << 15)) a -= (BASE << 15); \
  76144. if (a >= (BASE << 14)) a -= (BASE << 14); \
  76145. if (a >= (BASE << 13)) a -= (BASE << 13); \
  76146. if (a >= (BASE << 12)) a -= (BASE << 12); \
  76147. if (a >= (BASE << 11)) a -= (BASE << 11); \
  76148. if (a >= (BASE << 10)) a -= (BASE << 10); \
  76149. if (a >= (BASE << 9)) a -= (BASE << 9); \
  76150. if (a >= (BASE << 8)) a -= (BASE << 8); \
  76151. if (a >= (BASE << 7)) a -= (BASE << 7); \
  76152. if (a >= (BASE << 6)) a -= (BASE << 6); \
  76153. if (a >= (BASE << 5)) a -= (BASE << 5); \
  76154. if (a >= (BASE << 4)) a -= (BASE << 4); \
  76155. if (a >= (BASE << 3)) a -= (BASE << 3); \
  76156. if (a >= (BASE << 2)) a -= (BASE << 2); \
  76157. if (a >= (BASE << 1)) a -= (BASE << 1); \
  76158. if (a >= BASE) a -= BASE; \
  76159. } while (0)
  76160. # define MOD4(a) \
  76161. do { \
  76162. if (a >= (BASE << 4)) a -= (BASE << 4); \
  76163. if (a >= (BASE << 3)) a -= (BASE << 3); \
  76164. if (a >= (BASE << 2)) a -= (BASE << 2); \
  76165. if (a >= (BASE << 1)) a -= (BASE << 1); \
  76166. if (a >= BASE) a -= BASE; \
  76167. } while (0)
  76168. #else
  76169. # define MOD(a) a %= BASE
  76170. # define MOD4(a) a %= BASE
  76171. #endif
  76172. /* ========================================================================= */
  76173. uLong ZEXPORT adler32(uLong adler, const Bytef *buf, uInt len)
  76174. {
  76175. unsigned long sum2;
  76176. unsigned n;
  76177. /* split Adler-32 into component sums */
  76178. sum2 = (adler >> 16) & 0xffff;
  76179. adler &= 0xffff;
  76180. /* in case user likes doing a byte at a time, keep it fast */
  76181. if (len == 1) {
  76182. adler += buf[0];
  76183. if (adler >= BASE)
  76184. adler -= BASE;
  76185. sum2 += adler;
  76186. if (sum2 >= BASE)
  76187. sum2 -= BASE;
  76188. return adler | (sum2 << 16);
  76189. }
  76190. /* initial Adler-32 value (deferred check for len == 1 speed) */
  76191. if (buf == Z_NULL)
  76192. return 1L;
  76193. /* in case short lengths are provided, keep it somewhat fast */
  76194. if (len < 16) {
  76195. while (len--) {
  76196. adler += *buf++;
  76197. sum2 += adler;
  76198. }
  76199. if (adler >= BASE)
  76200. adler -= BASE;
  76201. MOD4(sum2); /* only added so many BASE's */
  76202. return adler | (sum2 << 16);
  76203. }
  76204. /* do length NMAX blocks -- requires just one modulo operation */
  76205. while (len >= NMAX) {
  76206. len -= NMAX;
  76207. n = NMAX / 16; /* NMAX is divisible by 16 */
  76208. do {
  76209. DO16(buf); /* 16 sums unrolled */
  76210. buf += 16;
  76211. } while (--n);
  76212. MOD(adler);
  76213. MOD(sum2);
  76214. }
  76215. /* do remaining bytes (less than NMAX, still just one modulo) */
  76216. if (len) { /* avoid modulos if none remaining */
  76217. while (len >= 16) {
  76218. len -= 16;
  76219. DO16(buf);
  76220. buf += 16;
  76221. }
  76222. while (len--) {
  76223. adler += *buf++;
  76224. sum2 += adler;
  76225. }
  76226. MOD(adler);
  76227. MOD(sum2);
  76228. }
  76229. /* return recombined sums */
  76230. return adler | (sum2 << 16);
  76231. }
  76232. /* ========================================================================= */
  76233. uLong ZEXPORT adler32_combine(uLong adler1, uLong adler2, z_off_t len2)
  76234. {
  76235. unsigned long sum1;
  76236. unsigned long sum2;
  76237. unsigned rem;
  76238. /* the derivation of this formula is left as an exercise for the reader */
  76239. rem = (unsigned)(len2 % BASE);
  76240. sum1 = adler1 & 0xffff;
  76241. sum2 = rem * sum1;
  76242. MOD(sum2);
  76243. sum1 += (adler2 & 0xffff) + BASE - 1;
  76244. sum2 += ((adler1 >> 16) & 0xffff) + ((adler2 >> 16) & 0xffff) + BASE - rem;
  76245. if (sum1 > BASE) sum1 -= BASE;
  76246. if (sum1 > BASE) sum1 -= BASE;
  76247. if (sum2 > (BASE << 1)) sum2 -= (BASE << 1);
  76248. if (sum2 > BASE) sum2 -= BASE;
  76249. return sum1 | (sum2 << 16);
  76250. }
  76251. /*** End of inlined file: adler32.c ***/
  76252. /*** Start of inlined file: compress.c ***/
  76253. /* @(#) $Id: compress.c,v 1.1 2007/06/07 17:54:37 jules_rms Exp $ */
  76254. #define ZLIB_INTERNAL
  76255. /* ===========================================================================
  76256. Compresses the source buffer into the destination buffer. The level
  76257. parameter has the same meaning as in deflateInit. sourceLen is the byte
  76258. length of the source buffer. Upon entry, destLen is the total size of the
  76259. destination buffer, which must be at least 0.1% larger than sourceLen plus
  76260. 12 bytes. Upon exit, destLen is the actual size of the compressed buffer.
  76261. compress2 returns Z_OK if success, Z_MEM_ERROR if there was not enough
  76262. memory, Z_BUF_ERROR if there was not enough room in the output buffer,
  76263. Z_STREAM_ERROR if the level parameter is invalid.
  76264. */
  76265. int ZEXPORT compress2 (Bytef *dest, uLongf *destLen, const Bytef *source,
  76266. uLong sourceLen, int level)
  76267. {
  76268. z_stream stream;
  76269. int err;
  76270. stream.next_in = (Bytef*)source;
  76271. stream.avail_in = (uInt)sourceLen;
  76272. #ifdef MAXSEG_64K
  76273. /* Check for source > 64K on 16-bit machine: */
  76274. if ((uLong)stream.avail_in != sourceLen) return Z_BUF_ERROR;
  76275. #endif
  76276. stream.next_out = dest;
  76277. stream.avail_out = (uInt)*destLen;
  76278. if ((uLong)stream.avail_out != *destLen) return Z_BUF_ERROR;
  76279. stream.zalloc = (alloc_func)0;
  76280. stream.zfree = (free_func)0;
  76281. stream.opaque = (voidpf)0;
  76282. err = deflateInit(&stream, level);
  76283. if (err != Z_OK) return err;
  76284. err = deflate(&stream, Z_FINISH);
  76285. if (err != Z_STREAM_END) {
  76286. deflateEnd(&stream);
  76287. return err == Z_OK ? Z_BUF_ERROR : err;
  76288. }
  76289. *destLen = stream.total_out;
  76290. err = deflateEnd(&stream);
  76291. return err;
  76292. }
  76293. /* ===========================================================================
  76294. */
  76295. int ZEXPORT compress (Bytef *dest, uLongf *destLen, const Bytef *source, uLong sourceLen)
  76296. {
  76297. return compress2(dest, destLen, source, sourceLen, Z_DEFAULT_COMPRESSION);
  76298. }
  76299. /* ===========================================================================
  76300. If the default memLevel or windowBits for deflateInit() is changed, then
  76301. this function needs to be updated.
  76302. */
  76303. uLong ZEXPORT compressBound (uLong sourceLen)
  76304. {
  76305. return sourceLen + (sourceLen >> 12) + (sourceLen >> 14) + 11;
  76306. }
  76307. /*** End of inlined file: compress.c ***/
  76308. #undef DO1
  76309. #undef DO8
  76310. /*** Start of inlined file: crc32.c ***/
  76311. /* @(#) $Id: crc32.c,v 1.1 2007/06/07 17:54:37 jules_rms Exp $ */
  76312. /*
  76313. Note on the use of DYNAMIC_CRC_TABLE: there is no mutex or semaphore
  76314. protection on the static variables used to control the first-use generation
  76315. of the crc tables. Therefore, if you #define DYNAMIC_CRC_TABLE, you should
  76316. first call get_crc_table() to initialize the tables before allowing more than
  76317. one thread to use crc32().
  76318. */
  76319. #ifdef MAKECRCH
  76320. # include <stdio.h>
  76321. # ifndef DYNAMIC_CRC_TABLE
  76322. # define DYNAMIC_CRC_TABLE
  76323. # endif /* !DYNAMIC_CRC_TABLE */
  76324. #endif /* MAKECRCH */
  76325. /*** Start of inlined file: zutil.h ***/
  76326. /* WARNING: this file should *not* be used by applications. It is
  76327. part of the implementation of the compression library and is
  76328. subject to change. Applications should only use zlib.h.
  76329. */
  76330. /* @(#) $Id: zutil.h,v 1.1 2007/06/07 17:54:37 jules_rms Exp $ */
  76331. #ifndef ZUTIL_H
  76332. #define ZUTIL_H
  76333. #define ZLIB_INTERNAL
  76334. #ifdef STDC
  76335. # ifndef _WIN32_WCE
  76336. # include <stddef.h>
  76337. # endif
  76338. # include <string.h>
  76339. # include <stdlib.h>
  76340. #endif
  76341. #ifdef NO_ERRNO_H
  76342. # ifdef _WIN32_WCE
  76343. /* The Microsoft C Run-Time Library for Windows CE doesn't have
  76344. * errno. We define it as a global variable to simplify porting.
  76345. * Its value is always 0 and should not be used. We rename it to
  76346. * avoid conflict with other libraries that use the same workaround.
  76347. */
  76348. # define errno z_errno
  76349. # endif
  76350. extern int errno;
  76351. #else
  76352. # ifndef _WIN32_WCE
  76353. # include <errno.h>
  76354. # endif
  76355. #endif
  76356. #ifndef local
  76357. # define local static
  76358. #endif
  76359. /* compile with -Dlocal if your debugger can't find static symbols */
  76360. typedef unsigned char uch;
  76361. typedef uch FAR uchf;
  76362. typedef unsigned short ush;
  76363. typedef ush FAR ushf;
  76364. typedef unsigned long ulg;
  76365. extern const char * const z_errmsg[10]; /* indexed by 2-zlib_error */
  76366. /* (size given to avoid silly warnings with Visual C++) */
  76367. #define ERR_MSG(err) z_errmsg[Z_NEED_DICT-(err)]
  76368. #define ERR_RETURN(strm,err) \
  76369. return (strm->msg = (char*)ERR_MSG(err), (err))
  76370. /* To be used only when the state is known to be valid */
  76371. /* common constants */
  76372. #ifndef DEF_WBITS
  76373. # define DEF_WBITS MAX_WBITS
  76374. #endif
  76375. /* default windowBits for decompression. MAX_WBITS is for compression only */
  76376. #if MAX_MEM_LEVEL >= 8
  76377. # define DEF_MEM_LEVEL 8
  76378. #else
  76379. # define DEF_MEM_LEVEL MAX_MEM_LEVEL
  76380. #endif
  76381. /* default memLevel */
  76382. #define STORED_BLOCK 0
  76383. #define STATIC_TREES 1
  76384. #define DYN_TREES 2
  76385. /* The three kinds of block type */
  76386. #define MIN_MATCH 3
  76387. #define MAX_MATCH 258
  76388. /* The minimum and maximum match lengths */
  76389. #define PRESET_DICT 0x20 /* preset dictionary flag in zlib header */
  76390. /* target dependencies */
  76391. #if defined(MSDOS) || (defined(WINDOWS) && !defined(WIN32))
  76392. # define OS_CODE 0x00
  76393. # if defined(__TURBOC__) || defined(__BORLANDC__)
  76394. # if(__STDC__ == 1) && (defined(__LARGE__) || defined(__COMPACT__))
  76395. /* Allow compilation with ANSI keywords only enabled */
  76396. void _Cdecl farfree( void *block );
  76397. void *_Cdecl farmalloc( unsigned long nbytes );
  76398. # else
  76399. # include <alloc.h>
  76400. # endif
  76401. # else /* MSC or DJGPP */
  76402. # include <malloc.h>
  76403. # endif
  76404. #endif
  76405. #ifdef AMIGA
  76406. # define OS_CODE 0x01
  76407. #endif
  76408. #if defined(VAXC) || defined(VMS)
  76409. # define OS_CODE 0x02
  76410. # define F_OPEN(name, mode) \
  76411. fopen((name), (mode), "mbc=60", "ctx=stm", "rfm=fix", "mrs=512")
  76412. #endif
  76413. #if defined(ATARI) || defined(atarist)
  76414. # define OS_CODE 0x05
  76415. #endif
  76416. #ifdef OS2
  76417. # define OS_CODE 0x06
  76418. # ifdef M_I86
  76419. #include <malloc.h>
  76420. # endif
  76421. #endif
  76422. #if defined(MACOS) || TARGET_OS_MAC
  76423. # define OS_CODE 0x07
  76424. # if defined(__MWERKS__) && __dest_os != __be_os && __dest_os != __win32_os
  76425. # include <unix.h> /* for fdopen */
  76426. # else
  76427. # ifndef fdopen
  76428. # define fdopen(fd,mode) NULL /* No fdopen() */
  76429. # endif
  76430. # endif
  76431. #endif
  76432. #ifdef TOPS20
  76433. # define OS_CODE 0x0a
  76434. #endif
  76435. #ifdef WIN32
  76436. # ifndef __CYGWIN__ /* Cygwin is Unix, not Win32 */
  76437. # define OS_CODE 0x0b
  76438. # endif
  76439. #endif
  76440. #ifdef __50SERIES /* Prime/PRIMOS */
  76441. # define OS_CODE 0x0f
  76442. #endif
  76443. #if defined(_BEOS_) || defined(RISCOS)
  76444. # define fdopen(fd,mode) NULL /* No fdopen() */
  76445. #endif
  76446. #if (defined(_MSC_VER) && (_MSC_VER > 600))
  76447. # if defined(_WIN32_WCE)
  76448. # define fdopen(fd,mode) NULL /* No fdopen() */
  76449. # ifndef _PTRDIFF_T_DEFINED
  76450. typedef int ptrdiff_t;
  76451. # define _PTRDIFF_T_DEFINED
  76452. # endif
  76453. # else
  76454. # define fdopen(fd,type) _fdopen(fd,type)
  76455. # endif
  76456. #endif
  76457. /* common defaults */
  76458. #ifndef OS_CODE
  76459. # define OS_CODE 0x03 /* assume Unix */
  76460. #endif
  76461. #ifndef F_OPEN
  76462. # define F_OPEN(name, mode) fopen((name), (mode))
  76463. #endif
  76464. /* functions */
  76465. #if defined(STDC99) || (defined(__TURBOC__) && __TURBOC__ >= 0x550)
  76466. # ifndef HAVE_VSNPRINTF
  76467. # define HAVE_VSNPRINTF
  76468. # endif
  76469. #endif
  76470. #if defined(__CYGWIN__)
  76471. # ifndef HAVE_VSNPRINTF
  76472. # define HAVE_VSNPRINTF
  76473. # endif
  76474. #endif
  76475. #ifndef HAVE_VSNPRINTF
  76476. # ifdef MSDOS
  76477. /* vsnprintf may exist on some MS-DOS compilers (DJGPP?),
  76478. but for now we just assume it doesn't. */
  76479. # define NO_vsnprintf
  76480. # endif
  76481. # ifdef __TURBOC__
  76482. # define NO_vsnprintf
  76483. # endif
  76484. # ifdef WIN32
  76485. /* In Win32, vsnprintf is available as the "non-ANSI" _vsnprintf. */
  76486. # if !defined(vsnprintf) && !defined(NO_vsnprintf)
  76487. # define vsnprintf _vsnprintf
  76488. # endif
  76489. # endif
  76490. # ifdef __SASC
  76491. # define NO_vsnprintf
  76492. # endif
  76493. #endif
  76494. #ifdef VMS
  76495. # define NO_vsnprintf
  76496. #endif
  76497. #if defined(pyr)
  76498. # define NO_MEMCPY
  76499. #endif
  76500. #if defined(SMALL_MEDIUM) && !defined(_MSC_VER) && !defined(__SC__)
  76501. /* Use our own functions for small and medium model with MSC <= 5.0.
  76502. * You may have to use the same strategy for Borland C (untested).
  76503. * The __SC__ check is for Symantec.
  76504. */
  76505. # define NO_MEMCPY
  76506. #endif
  76507. #if defined(STDC) && !defined(HAVE_MEMCPY) && !defined(NO_MEMCPY)
  76508. # define HAVE_MEMCPY
  76509. #endif
  76510. #ifdef HAVE_MEMCPY
  76511. # ifdef SMALL_MEDIUM /* MSDOS small or medium model */
  76512. # define zmemcpy _fmemcpy
  76513. # define zmemcmp _fmemcmp
  76514. # define zmemzero(dest, len) _fmemset(dest, 0, len)
  76515. # else
  76516. # define zmemcpy memcpy
  76517. # define zmemcmp memcmp
  76518. # define zmemzero(dest, len) memset(dest, 0, len)
  76519. # endif
  76520. #else
  76521. extern void zmemcpy OF((Bytef* dest, const Bytef* source, uInt len));
  76522. extern int zmemcmp OF((const Bytef* s1, const Bytef* s2, uInt len));
  76523. extern void zmemzero OF((Bytef* dest, uInt len));
  76524. #endif
  76525. /* Diagnostic functions */
  76526. #ifdef DEBUG
  76527. # include <stdio.h>
  76528. extern int z_verbose;
  76529. extern void z_error OF((const char *m));
  76530. # define Assert(cond,msg) {if(!(cond)) z_error(msg);}
  76531. # define Trace(x) {if (z_verbose>=0) fprintf x ;}
  76532. # define Tracev(x) {if (z_verbose>0) fprintf x ;}
  76533. # define Tracevv(x) {if (z_verbose>1) fprintf x ;}
  76534. # define Tracec(c,x) {if (z_verbose>0 && (c)) fprintf x ;}
  76535. # define Tracecv(c,x) {if (z_verbose>1 && (c)) fprintf x ;}
  76536. #else
  76537. # define Assert(cond,msg)
  76538. # define Trace(x)
  76539. # define Tracev(x)
  76540. # define Tracevv(x)
  76541. # define Tracec(c,x)
  76542. # define Tracecv(c,x)
  76543. #endif
  76544. voidpf zcalloc OF((voidpf opaque, unsigned items, unsigned size));
  76545. void zcfree OF((voidpf opaque, voidpf ptr));
  76546. #define ZALLOC(strm, items, size) \
  76547. (*((strm)->zalloc))((strm)->opaque, (items), (size))
  76548. #define ZFREE(strm, addr) (*((strm)->zfree))((strm)->opaque, (voidpf)(addr))
  76549. #define TRY_FREE(s, p) {if (p) ZFREE(s, p);}
  76550. #endif /* ZUTIL_H */
  76551. /*** End of inlined file: zutil.h ***/
  76552. /* for STDC and FAR definitions */
  76553. #define local static
  76554. /* Find a four-byte integer type for crc32_little() and crc32_big(). */
  76555. #ifndef NOBYFOUR
  76556. # ifdef STDC /* need ANSI C limits.h to determine sizes */
  76557. # include <limits.h>
  76558. # define BYFOUR
  76559. # if (UINT_MAX == 0xffffffffUL)
  76560. typedef unsigned int u4;
  76561. # else
  76562. # if (ULONG_MAX == 0xffffffffUL)
  76563. typedef unsigned long u4;
  76564. # else
  76565. # if (USHRT_MAX == 0xffffffffUL)
  76566. typedef unsigned short u4;
  76567. # else
  76568. # undef BYFOUR /* can't find a four-byte integer type! */
  76569. # endif
  76570. # endif
  76571. # endif
  76572. # endif /* STDC */
  76573. #endif /* !NOBYFOUR */
  76574. /* Definitions for doing the crc four data bytes at a time. */
  76575. #ifdef BYFOUR
  76576. # define REV(w) (((w)>>24)+(((w)>>8)&0xff00)+ \
  76577. (((w)&0xff00)<<8)+(((w)&0xff)<<24))
  76578. local unsigned long crc32_little OF((unsigned long,
  76579. const unsigned char FAR *, unsigned));
  76580. local unsigned long crc32_big OF((unsigned long,
  76581. const unsigned char FAR *, unsigned));
  76582. # define TBLS 8
  76583. #else
  76584. # define TBLS 1
  76585. #endif /* BYFOUR */
  76586. /* Local functions for crc concatenation */
  76587. local unsigned long gf2_matrix_times OF((unsigned long *mat,
  76588. unsigned long vec));
  76589. local void gf2_matrix_square OF((unsigned long *square, unsigned long *mat));
  76590. #ifdef DYNAMIC_CRC_TABLE
  76591. local volatile int crc_table_empty = 1;
  76592. local unsigned long FAR crc_table[TBLS][256];
  76593. local void make_crc_table OF((void));
  76594. #ifdef MAKECRCH
  76595. local void write_table OF((FILE *, const unsigned long FAR *));
  76596. #endif /* MAKECRCH */
  76597. /*
  76598. Generate tables for a byte-wise 32-bit CRC calculation on the polynomial:
  76599. 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.
  76600. Polynomials over GF(2) are represented in binary, one bit per coefficient,
  76601. with the lowest powers in the most significant bit. Then adding polynomials
  76602. is just exclusive-or, and multiplying a polynomial by x is a right shift by
  76603. one. If we call the above polynomial p, and represent a byte as the
  76604. polynomial q, also with the lowest power in the most significant bit (so the
  76605. byte 0xb1 is the polynomial x^7+x^3+x+1), then the CRC is (q*x^32) mod p,
  76606. where a mod b means the remainder after dividing a by b.
  76607. This calculation is done using the shift-register method of multiplying and
  76608. taking the remainder. The register is initialized to zero, and for each
  76609. incoming bit, x^32 is added mod p to the register if the bit is a one (where
  76610. x^32 mod p is p+x^32 = x^26+...+1), and the register is multiplied mod p by
  76611. x (which is shifting right by one and adding x^32 mod p if the bit shifted
  76612. out is a one). We start with the highest power (least significant bit) of
  76613. q and repeat for all eight bits of q.
  76614. The first table is simply the CRC of all possible eight bit values. This is
  76615. all the information needed to generate CRCs on data a byte at a time for all
  76616. combinations of CRC register values and incoming bytes. The remaining tables
  76617. allow for word-at-a-time CRC calculation for both big-endian and little-
  76618. endian machines, where a word is four bytes.
  76619. */
  76620. local void make_crc_table()
  76621. {
  76622. unsigned long c;
  76623. int n, k;
  76624. unsigned long poly; /* polynomial exclusive-or pattern */
  76625. /* terms of polynomial defining this crc (except x^32): */
  76626. static volatile int first = 1; /* flag to limit concurrent making */
  76627. static const unsigned char p[] = {0,1,2,4,5,7,8,10,11,12,16,22,23,26};
  76628. /* See if another task is already doing this (not thread-safe, but better
  76629. than nothing -- significantly reduces duration of vulnerability in
  76630. case the advice about DYNAMIC_CRC_TABLE is ignored) */
  76631. if (first) {
  76632. first = 0;
  76633. /* make exclusive-or pattern from polynomial (0xedb88320UL) */
  76634. poly = 0UL;
  76635. for (n = 0; n < sizeof(p)/sizeof(unsigned char); n++)
  76636. poly |= 1UL << (31 - p[n]);
  76637. /* generate a crc for every 8-bit value */
  76638. for (n = 0; n < 256; n++) {
  76639. c = (unsigned long)n;
  76640. for (k = 0; k < 8; k++)
  76641. c = c & 1 ? poly ^ (c >> 1) : c >> 1;
  76642. crc_table[0][n] = c;
  76643. }
  76644. #ifdef BYFOUR
  76645. /* generate crc for each value followed by one, two, and three zeros,
  76646. and then the byte reversal of those as well as the first table */
  76647. for (n = 0; n < 256; n++) {
  76648. c = crc_table[0][n];
  76649. crc_table[4][n] = REV(c);
  76650. for (k = 1; k < 4; k++) {
  76651. c = crc_table[0][c & 0xff] ^ (c >> 8);
  76652. crc_table[k][n] = c;
  76653. crc_table[k + 4][n] = REV(c);
  76654. }
  76655. }
  76656. #endif /* BYFOUR */
  76657. crc_table_empty = 0;
  76658. }
  76659. else { /* not first */
  76660. /* wait for the other guy to finish (not efficient, but rare) */
  76661. while (crc_table_empty)
  76662. ;
  76663. }
  76664. #ifdef MAKECRCH
  76665. /* write out CRC tables to crc32.h */
  76666. {
  76667. FILE *out;
  76668. out = fopen("crc32.h", "w");
  76669. if (out == NULL) return;
  76670. fprintf(out, "/* crc32.h -- tables for rapid CRC calculation\n");
  76671. fprintf(out, " * Generated automatically by crc32.c\n */\n\n");
  76672. fprintf(out, "local const unsigned long FAR ");
  76673. fprintf(out, "crc_table[TBLS][256] =\n{\n {\n");
  76674. write_table(out, crc_table[0]);
  76675. # ifdef BYFOUR
  76676. fprintf(out, "#ifdef BYFOUR\n");
  76677. for (k = 1; k < 8; k++) {
  76678. fprintf(out, " },\n {\n");
  76679. write_table(out, crc_table[k]);
  76680. }
  76681. fprintf(out, "#endif\n");
  76682. # endif /* BYFOUR */
  76683. fprintf(out, " }\n};\n");
  76684. fclose(out);
  76685. }
  76686. #endif /* MAKECRCH */
  76687. }
  76688. #ifdef MAKECRCH
  76689. local void write_table(out, table)
  76690. FILE *out;
  76691. const unsigned long FAR *table;
  76692. {
  76693. int n;
  76694. for (n = 0; n < 256; n++)
  76695. fprintf(out, "%s0x%08lxUL%s", n % 5 ? "" : " ", table[n],
  76696. n == 255 ? "\n" : (n % 5 == 4 ? ",\n" : ", "));
  76697. }
  76698. #endif /* MAKECRCH */
  76699. #else /* !DYNAMIC_CRC_TABLE */
  76700. /* ========================================================================
  76701. * Tables of CRC-32s of all single-byte values, made by make_crc_table().
  76702. */
  76703. /*** Start of inlined file: crc32.h ***/
  76704. local const unsigned long FAR crc_table[TBLS][256] =
  76705. {
  76706. {
  76707. 0x00000000UL, 0x77073096UL, 0xee0e612cUL, 0x990951baUL, 0x076dc419UL,
  76708. 0x706af48fUL, 0xe963a535UL, 0x9e6495a3UL, 0x0edb8832UL, 0x79dcb8a4UL,
  76709. 0xe0d5e91eUL, 0x97d2d988UL, 0x09b64c2bUL, 0x7eb17cbdUL, 0xe7b82d07UL,
  76710. 0x90bf1d91UL, 0x1db71064UL, 0x6ab020f2UL, 0xf3b97148UL, 0x84be41deUL,
  76711. 0x1adad47dUL, 0x6ddde4ebUL, 0xf4d4b551UL, 0x83d385c7UL, 0x136c9856UL,
  76712. 0x646ba8c0UL, 0xfd62f97aUL, 0x8a65c9ecUL, 0x14015c4fUL, 0x63066cd9UL,
  76713. 0xfa0f3d63UL, 0x8d080df5UL, 0x3b6e20c8UL, 0x4c69105eUL, 0xd56041e4UL,
  76714. 0xa2677172UL, 0x3c03e4d1UL, 0x4b04d447UL, 0xd20d85fdUL, 0xa50ab56bUL,
  76715. 0x35b5a8faUL, 0x42b2986cUL, 0xdbbbc9d6UL, 0xacbcf940UL, 0x32d86ce3UL,
  76716. 0x45df5c75UL, 0xdcd60dcfUL, 0xabd13d59UL, 0x26d930acUL, 0x51de003aUL,
  76717. 0xc8d75180UL, 0xbfd06116UL, 0x21b4f4b5UL, 0x56b3c423UL, 0xcfba9599UL,
  76718. 0xb8bda50fUL, 0x2802b89eUL, 0x5f058808UL, 0xc60cd9b2UL, 0xb10be924UL,
  76719. 0x2f6f7c87UL, 0x58684c11UL, 0xc1611dabUL, 0xb6662d3dUL, 0x76dc4190UL,
  76720. 0x01db7106UL, 0x98d220bcUL, 0xefd5102aUL, 0x71b18589UL, 0x06b6b51fUL,
  76721. 0x9fbfe4a5UL, 0xe8b8d433UL, 0x7807c9a2UL, 0x0f00f934UL, 0x9609a88eUL,
  76722. 0xe10e9818UL, 0x7f6a0dbbUL, 0x086d3d2dUL, 0x91646c97UL, 0xe6635c01UL,
  76723. 0x6b6b51f4UL, 0x1c6c6162UL, 0x856530d8UL, 0xf262004eUL, 0x6c0695edUL,
  76724. 0x1b01a57bUL, 0x8208f4c1UL, 0xf50fc457UL, 0x65b0d9c6UL, 0x12b7e950UL,
  76725. 0x8bbeb8eaUL, 0xfcb9887cUL, 0x62dd1ddfUL, 0x15da2d49UL, 0x8cd37cf3UL,
  76726. 0xfbd44c65UL, 0x4db26158UL, 0x3ab551ceUL, 0xa3bc0074UL, 0xd4bb30e2UL,
  76727. 0x4adfa541UL, 0x3dd895d7UL, 0xa4d1c46dUL, 0xd3d6f4fbUL, 0x4369e96aUL,
  76728. 0x346ed9fcUL, 0xad678846UL, 0xda60b8d0UL, 0x44042d73UL, 0x33031de5UL,
  76729. 0xaa0a4c5fUL, 0xdd0d7cc9UL, 0x5005713cUL, 0x270241aaUL, 0xbe0b1010UL,
  76730. 0xc90c2086UL, 0x5768b525UL, 0x206f85b3UL, 0xb966d409UL, 0xce61e49fUL,
  76731. 0x5edef90eUL, 0x29d9c998UL, 0xb0d09822UL, 0xc7d7a8b4UL, 0x59b33d17UL,
  76732. 0x2eb40d81UL, 0xb7bd5c3bUL, 0xc0ba6cadUL, 0xedb88320UL, 0x9abfb3b6UL,
  76733. 0x03b6e20cUL, 0x74b1d29aUL, 0xead54739UL, 0x9dd277afUL, 0x04db2615UL,
  76734. 0x73dc1683UL, 0xe3630b12UL, 0x94643b84UL, 0x0d6d6a3eUL, 0x7a6a5aa8UL,
  76735. 0xe40ecf0bUL, 0x9309ff9dUL, 0x0a00ae27UL, 0x7d079eb1UL, 0xf00f9344UL,
  76736. 0x8708a3d2UL, 0x1e01f268UL, 0x6906c2feUL, 0xf762575dUL, 0x806567cbUL,
  76737. 0x196c3671UL, 0x6e6b06e7UL, 0xfed41b76UL, 0x89d32be0UL, 0x10da7a5aUL,
  76738. 0x67dd4accUL, 0xf9b9df6fUL, 0x8ebeeff9UL, 0x17b7be43UL, 0x60b08ed5UL,
  76739. 0xd6d6a3e8UL, 0xa1d1937eUL, 0x38d8c2c4UL, 0x4fdff252UL, 0xd1bb67f1UL,
  76740. 0xa6bc5767UL, 0x3fb506ddUL, 0x48b2364bUL, 0xd80d2bdaUL, 0xaf0a1b4cUL,
  76741. 0x36034af6UL, 0x41047a60UL, 0xdf60efc3UL, 0xa867df55UL, 0x316e8eefUL,
  76742. 0x4669be79UL, 0xcb61b38cUL, 0xbc66831aUL, 0x256fd2a0UL, 0x5268e236UL,
  76743. 0xcc0c7795UL, 0xbb0b4703UL, 0x220216b9UL, 0x5505262fUL, 0xc5ba3bbeUL,
  76744. 0xb2bd0b28UL, 0x2bb45a92UL, 0x5cb36a04UL, 0xc2d7ffa7UL, 0xb5d0cf31UL,
  76745. 0x2cd99e8bUL, 0x5bdeae1dUL, 0x9b64c2b0UL, 0xec63f226UL, 0x756aa39cUL,
  76746. 0x026d930aUL, 0x9c0906a9UL, 0xeb0e363fUL, 0x72076785UL, 0x05005713UL,
  76747. 0x95bf4a82UL, 0xe2b87a14UL, 0x7bb12baeUL, 0x0cb61b38UL, 0x92d28e9bUL,
  76748. 0xe5d5be0dUL, 0x7cdcefb7UL, 0x0bdbdf21UL, 0x86d3d2d4UL, 0xf1d4e242UL,
  76749. 0x68ddb3f8UL, 0x1fda836eUL, 0x81be16cdUL, 0xf6b9265bUL, 0x6fb077e1UL,
  76750. 0x18b74777UL, 0x88085ae6UL, 0xff0f6a70UL, 0x66063bcaUL, 0x11010b5cUL,
  76751. 0x8f659effUL, 0xf862ae69UL, 0x616bffd3UL, 0x166ccf45UL, 0xa00ae278UL,
  76752. 0xd70dd2eeUL, 0x4e048354UL, 0x3903b3c2UL, 0xa7672661UL, 0xd06016f7UL,
  76753. 0x4969474dUL, 0x3e6e77dbUL, 0xaed16a4aUL, 0xd9d65adcUL, 0x40df0b66UL,
  76754. 0x37d83bf0UL, 0xa9bcae53UL, 0xdebb9ec5UL, 0x47b2cf7fUL, 0x30b5ffe9UL,
  76755. 0xbdbdf21cUL, 0xcabac28aUL, 0x53b39330UL, 0x24b4a3a6UL, 0xbad03605UL,
  76756. 0xcdd70693UL, 0x54de5729UL, 0x23d967bfUL, 0xb3667a2eUL, 0xc4614ab8UL,
  76757. 0x5d681b02UL, 0x2a6f2b94UL, 0xb40bbe37UL, 0xc30c8ea1UL, 0x5a05df1bUL,
  76758. 0x2d02ef8dUL
  76759. #ifdef BYFOUR
  76760. },
  76761. {
  76762. 0x00000000UL, 0x191b3141UL, 0x32366282UL, 0x2b2d53c3UL, 0x646cc504UL,
  76763. 0x7d77f445UL, 0x565aa786UL, 0x4f4196c7UL, 0xc8d98a08UL, 0xd1c2bb49UL,
  76764. 0xfaefe88aUL, 0xe3f4d9cbUL, 0xacb54f0cUL, 0xb5ae7e4dUL, 0x9e832d8eUL,
  76765. 0x87981ccfUL, 0x4ac21251UL, 0x53d92310UL, 0x78f470d3UL, 0x61ef4192UL,
  76766. 0x2eaed755UL, 0x37b5e614UL, 0x1c98b5d7UL, 0x05838496UL, 0x821b9859UL,
  76767. 0x9b00a918UL, 0xb02dfadbUL, 0xa936cb9aUL, 0xe6775d5dUL, 0xff6c6c1cUL,
  76768. 0xd4413fdfUL, 0xcd5a0e9eUL, 0x958424a2UL, 0x8c9f15e3UL, 0xa7b24620UL,
  76769. 0xbea97761UL, 0xf1e8e1a6UL, 0xe8f3d0e7UL, 0xc3de8324UL, 0xdac5b265UL,
  76770. 0x5d5daeaaUL, 0x44469febUL, 0x6f6bcc28UL, 0x7670fd69UL, 0x39316baeUL,
  76771. 0x202a5aefUL, 0x0b07092cUL, 0x121c386dUL, 0xdf4636f3UL, 0xc65d07b2UL,
  76772. 0xed705471UL, 0xf46b6530UL, 0xbb2af3f7UL, 0xa231c2b6UL, 0x891c9175UL,
  76773. 0x9007a034UL, 0x179fbcfbUL, 0x0e848dbaUL, 0x25a9de79UL, 0x3cb2ef38UL,
  76774. 0x73f379ffUL, 0x6ae848beUL, 0x41c51b7dUL, 0x58de2a3cUL, 0xf0794f05UL,
  76775. 0xe9627e44UL, 0xc24f2d87UL, 0xdb541cc6UL, 0x94158a01UL, 0x8d0ebb40UL,
  76776. 0xa623e883UL, 0xbf38d9c2UL, 0x38a0c50dUL, 0x21bbf44cUL, 0x0a96a78fUL,
  76777. 0x138d96ceUL, 0x5ccc0009UL, 0x45d73148UL, 0x6efa628bUL, 0x77e153caUL,
  76778. 0xbabb5d54UL, 0xa3a06c15UL, 0x888d3fd6UL, 0x91960e97UL, 0xded79850UL,
  76779. 0xc7cca911UL, 0xece1fad2UL, 0xf5facb93UL, 0x7262d75cUL, 0x6b79e61dUL,
  76780. 0x4054b5deUL, 0x594f849fUL, 0x160e1258UL, 0x0f152319UL, 0x243870daUL,
  76781. 0x3d23419bUL, 0x65fd6ba7UL, 0x7ce65ae6UL, 0x57cb0925UL, 0x4ed03864UL,
  76782. 0x0191aea3UL, 0x188a9fe2UL, 0x33a7cc21UL, 0x2abcfd60UL, 0xad24e1afUL,
  76783. 0xb43fd0eeUL, 0x9f12832dUL, 0x8609b26cUL, 0xc94824abUL, 0xd05315eaUL,
  76784. 0xfb7e4629UL, 0xe2657768UL, 0x2f3f79f6UL, 0x362448b7UL, 0x1d091b74UL,
  76785. 0x04122a35UL, 0x4b53bcf2UL, 0x52488db3UL, 0x7965de70UL, 0x607eef31UL,
  76786. 0xe7e6f3feUL, 0xfefdc2bfUL, 0xd5d0917cUL, 0xcccba03dUL, 0x838a36faUL,
  76787. 0x9a9107bbUL, 0xb1bc5478UL, 0xa8a76539UL, 0x3b83984bUL, 0x2298a90aUL,
  76788. 0x09b5fac9UL, 0x10aecb88UL, 0x5fef5d4fUL, 0x46f46c0eUL, 0x6dd93fcdUL,
  76789. 0x74c20e8cUL, 0xf35a1243UL, 0xea412302UL, 0xc16c70c1UL, 0xd8774180UL,
  76790. 0x9736d747UL, 0x8e2de606UL, 0xa500b5c5UL, 0xbc1b8484UL, 0x71418a1aUL,
  76791. 0x685abb5bUL, 0x4377e898UL, 0x5a6cd9d9UL, 0x152d4f1eUL, 0x0c367e5fUL,
  76792. 0x271b2d9cUL, 0x3e001cddUL, 0xb9980012UL, 0xa0833153UL, 0x8bae6290UL,
  76793. 0x92b553d1UL, 0xddf4c516UL, 0xc4eff457UL, 0xefc2a794UL, 0xf6d996d5UL,
  76794. 0xae07bce9UL, 0xb71c8da8UL, 0x9c31de6bUL, 0x852aef2aUL, 0xca6b79edUL,
  76795. 0xd37048acUL, 0xf85d1b6fUL, 0xe1462a2eUL, 0x66de36e1UL, 0x7fc507a0UL,
  76796. 0x54e85463UL, 0x4df36522UL, 0x02b2f3e5UL, 0x1ba9c2a4UL, 0x30849167UL,
  76797. 0x299fa026UL, 0xe4c5aeb8UL, 0xfdde9ff9UL, 0xd6f3cc3aUL, 0xcfe8fd7bUL,
  76798. 0x80a96bbcUL, 0x99b25afdUL, 0xb29f093eUL, 0xab84387fUL, 0x2c1c24b0UL,
  76799. 0x350715f1UL, 0x1e2a4632UL, 0x07317773UL, 0x4870e1b4UL, 0x516bd0f5UL,
  76800. 0x7a468336UL, 0x635db277UL, 0xcbfad74eUL, 0xd2e1e60fUL, 0xf9ccb5ccUL,
  76801. 0xe0d7848dUL, 0xaf96124aUL, 0xb68d230bUL, 0x9da070c8UL, 0x84bb4189UL,
  76802. 0x03235d46UL, 0x1a386c07UL, 0x31153fc4UL, 0x280e0e85UL, 0x674f9842UL,
  76803. 0x7e54a903UL, 0x5579fac0UL, 0x4c62cb81UL, 0x8138c51fUL, 0x9823f45eUL,
  76804. 0xb30ea79dUL, 0xaa1596dcUL, 0xe554001bUL, 0xfc4f315aUL, 0xd7626299UL,
  76805. 0xce7953d8UL, 0x49e14f17UL, 0x50fa7e56UL, 0x7bd72d95UL, 0x62cc1cd4UL,
  76806. 0x2d8d8a13UL, 0x3496bb52UL, 0x1fbbe891UL, 0x06a0d9d0UL, 0x5e7ef3ecUL,
  76807. 0x4765c2adUL, 0x6c48916eUL, 0x7553a02fUL, 0x3a1236e8UL, 0x230907a9UL,
  76808. 0x0824546aUL, 0x113f652bUL, 0x96a779e4UL, 0x8fbc48a5UL, 0xa4911b66UL,
  76809. 0xbd8a2a27UL, 0xf2cbbce0UL, 0xebd08da1UL, 0xc0fdde62UL, 0xd9e6ef23UL,
  76810. 0x14bce1bdUL, 0x0da7d0fcUL, 0x268a833fUL, 0x3f91b27eUL, 0x70d024b9UL,
  76811. 0x69cb15f8UL, 0x42e6463bUL, 0x5bfd777aUL, 0xdc656bb5UL, 0xc57e5af4UL,
  76812. 0xee530937UL, 0xf7483876UL, 0xb809aeb1UL, 0xa1129ff0UL, 0x8a3fcc33UL,
  76813. 0x9324fd72UL
  76814. },
  76815. {
  76816. 0x00000000UL, 0x01c26a37UL, 0x0384d46eUL, 0x0246be59UL, 0x0709a8dcUL,
  76817. 0x06cbc2ebUL, 0x048d7cb2UL, 0x054f1685UL, 0x0e1351b8UL, 0x0fd13b8fUL,
  76818. 0x0d9785d6UL, 0x0c55efe1UL, 0x091af964UL, 0x08d89353UL, 0x0a9e2d0aUL,
  76819. 0x0b5c473dUL, 0x1c26a370UL, 0x1de4c947UL, 0x1fa2771eUL, 0x1e601d29UL,
  76820. 0x1b2f0bacUL, 0x1aed619bUL, 0x18abdfc2UL, 0x1969b5f5UL, 0x1235f2c8UL,
  76821. 0x13f798ffUL, 0x11b126a6UL, 0x10734c91UL, 0x153c5a14UL, 0x14fe3023UL,
  76822. 0x16b88e7aUL, 0x177ae44dUL, 0x384d46e0UL, 0x398f2cd7UL, 0x3bc9928eUL,
  76823. 0x3a0bf8b9UL, 0x3f44ee3cUL, 0x3e86840bUL, 0x3cc03a52UL, 0x3d025065UL,
  76824. 0x365e1758UL, 0x379c7d6fUL, 0x35dac336UL, 0x3418a901UL, 0x3157bf84UL,
  76825. 0x3095d5b3UL, 0x32d36beaUL, 0x331101ddUL, 0x246be590UL, 0x25a98fa7UL,
  76826. 0x27ef31feUL, 0x262d5bc9UL, 0x23624d4cUL, 0x22a0277bUL, 0x20e69922UL,
  76827. 0x2124f315UL, 0x2a78b428UL, 0x2bbade1fUL, 0x29fc6046UL, 0x283e0a71UL,
  76828. 0x2d711cf4UL, 0x2cb376c3UL, 0x2ef5c89aUL, 0x2f37a2adUL, 0x709a8dc0UL,
  76829. 0x7158e7f7UL, 0x731e59aeUL, 0x72dc3399UL, 0x7793251cUL, 0x76514f2bUL,
  76830. 0x7417f172UL, 0x75d59b45UL, 0x7e89dc78UL, 0x7f4bb64fUL, 0x7d0d0816UL,
  76831. 0x7ccf6221UL, 0x798074a4UL, 0x78421e93UL, 0x7a04a0caUL, 0x7bc6cafdUL,
  76832. 0x6cbc2eb0UL, 0x6d7e4487UL, 0x6f38fadeUL, 0x6efa90e9UL, 0x6bb5866cUL,
  76833. 0x6a77ec5bUL, 0x68315202UL, 0x69f33835UL, 0x62af7f08UL, 0x636d153fUL,
  76834. 0x612bab66UL, 0x60e9c151UL, 0x65a6d7d4UL, 0x6464bde3UL, 0x662203baUL,
  76835. 0x67e0698dUL, 0x48d7cb20UL, 0x4915a117UL, 0x4b531f4eUL, 0x4a917579UL,
  76836. 0x4fde63fcUL, 0x4e1c09cbUL, 0x4c5ab792UL, 0x4d98dda5UL, 0x46c49a98UL,
  76837. 0x4706f0afUL, 0x45404ef6UL, 0x448224c1UL, 0x41cd3244UL, 0x400f5873UL,
  76838. 0x4249e62aUL, 0x438b8c1dUL, 0x54f16850UL, 0x55330267UL, 0x5775bc3eUL,
  76839. 0x56b7d609UL, 0x53f8c08cUL, 0x523aaabbUL, 0x507c14e2UL, 0x51be7ed5UL,
  76840. 0x5ae239e8UL, 0x5b2053dfUL, 0x5966ed86UL, 0x58a487b1UL, 0x5deb9134UL,
  76841. 0x5c29fb03UL, 0x5e6f455aUL, 0x5fad2f6dUL, 0xe1351b80UL, 0xe0f771b7UL,
  76842. 0xe2b1cfeeUL, 0xe373a5d9UL, 0xe63cb35cUL, 0xe7fed96bUL, 0xe5b86732UL,
  76843. 0xe47a0d05UL, 0xef264a38UL, 0xeee4200fUL, 0xeca29e56UL, 0xed60f461UL,
  76844. 0xe82fe2e4UL, 0xe9ed88d3UL, 0xebab368aUL, 0xea695cbdUL, 0xfd13b8f0UL,
  76845. 0xfcd1d2c7UL, 0xfe976c9eUL, 0xff5506a9UL, 0xfa1a102cUL, 0xfbd87a1bUL,
  76846. 0xf99ec442UL, 0xf85cae75UL, 0xf300e948UL, 0xf2c2837fUL, 0xf0843d26UL,
  76847. 0xf1465711UL, 0xf4094194UL, 0xf5cb2ba3UL, 0xf78d95faUL, 0xf64fffcdUL,
  76848. 0xd9785d60UL, 0xd8ba3757UL, 0xdafc890eUL, 0xdb3ee339UL, 0xde71f5bcUL,
  76849. 0xdfb39f8bUL, 0xddf521d2UL, 0xdc374be5UL, 0xd76b0cd8UL, 0xd6a966efUL,
  76850. 0xd4efd8b6UL, 0xd52db281UL, 0xd062a404UL, 0xd1a0ce33UL, 0xd3e6706aUL,
  76851. 0xd2241a5dUL, 0xc55efe10UL, 0xc49c9427UL, 0xc6da2a7eUL, 0xc7184049UL,
  76852. 0xc25756ccUL, 0xc3953cfbUL, 0xc1d382a2UL, 0xc011e895UL, 0xcb4dafa8UL,
  76853. 0xca8fc59fUL, 0xc8c97bc6UL, 0xc90b11f1UL, 0xcc440774UL, 0xcd866d43UL,
  76854. 0xcfc0d31aUL, 0xce02b92dUL, 0x91af9640UL, 0x906dfc77UL, 0x922b422eUL,
  76855. 0x93e92819UL, 0x96a63e9cUL, 0x976454abUL, 0x9522eaf2UL, 0x94e080c5UL,
  76856. 0x9fbcc7f8UL, 0x9e7eadcfUL, 0x9c381396UL, 0x9dfa79a1UL, 0x98b56f24UL,
  76857. 0x99770513UL, 0x9b31bb4aUL, 0x9af3d17dUL, 0x8d893530UL, 0x8c4b5f07UL,
  76858. 0x8e0de15eUL, 0x8fcf8b69UL, 0x8a809decUL, 0x8b42f7dbUL, 0x89044982UL,
  76859. 0x88c623b5UL, 0x839a6488UL, 0x82580ebfUL, 0x801eb0e6UL, 0x81dcdad1UL,
  76860. 0x8493cc54UL, 0x8551a663UL, 0x8717183aUL, 0x86d5720dUL, 0xa9e2d0a0UL,
  76861. 0xa820ba97UL, 0xaa6604ceUL, 0xaba46ef9UL, 0xaeeb787cUL, 0xaf29124bUL,
  76862. 0xad6fac12UL, 0xacadc625UL, 0xa7f18118UL, 0xa633eb2fUL, 0xa4755576UL,
  76863. 0xa5b73f41UL, 0xa0f829c4UL, 0xa13a43f3UL, 0xa37cfdaaUL, 0xa2be979dUL,
  76864. 0xb5c473d0UL, 0xb40619e7UL, 0xb640a7beUL, 0xb782cd89UL, 0xb2cddb0cUL,
  76865. 0xb30fb13bUL, 0xb1490f62UL, 0xb08b6555UL, 0xbbd72268UL, 0xba15485fUL,
  76866. 0xb853f606UL, 0xb9919c31UL, 0xbcde8ab4UL, 0xbd1ce083UL, 0xbf5a5edaUL,
  76867. 0xbe9834edUL
  76868. },
  76869. {
  76870. 0x00000000UL, 0xb8bc6765UL, 0xaa09c88bUL, 0x12b5afeeUL, 0x8f629757UL,
  76871. 0x37def032UL, 0x256b5fdcUL, 0x9dd738b9UL, 0xc5b428efUL, 0x7d084f8aUL,
  76872. 0x6fbde064UL, 0xd7018701UL, 0x4ad6bfb8UL, 0xf26ad8ddUL, 0xe0df7733UL,
  76873. 0x58631056UL, 0x5019579fUL, 0xe8a530faUL, 0xfa109f14UL, 0x42acf871UL,
  76874. 0xdf7bc0c8UL, 0x67c7a7adUL, 0x75720843UL, 0xcdce6f26UL, 0x95ad7f70UL,
  76875. 0x2d111815UL, 0x3fa4b7fbUL, 0x8718d09eUL, 0x1acfe827UL, 0xa2738f42UL,
  76876. 0xb0c620acUL, 0x087a47c9UL, 0xa032af3eUL, 0x188ec85bUL, 0x0a3b67b5UL,
  76877. 0xb28700d0UL, 0x2f503869UL, 0x97ec5f0cUL, 0x8559f0e2UL, 0x3de59787UL,
  76878. 0x658687d1UL, 0xdd3ae0b4UL, 0xcf8f4f5aUL, 0x7733283fUL, 0xeae41086UL,
  76879. 0x525877e3UL, 0x40edd80dUL, 0xf851bf68UL, 0xf02bf8a1UL, 0x48979fc4UL,
  76880. 0x5a22302aUL, 0xe29e574fUL, 0x7f496ff6UL, 0xc7f50893UL, 0xd540a77dUL,
  76881. 0x6dfcc018UL, 0x359fd04eUL, 0x8d23b72bUL, 0x9f9618c5UL, 0x272a7fa0UL,
  76882. 0xbafd4719UL, 0x0241207cUL, 0x10f48f92UL, 0xa848e8f7UL, 0x9b14583dUL,
  76883. 0x23a83f58UL, 0x311d90b6UL, 0x89a1f7d3UL, 0x1476cf6aUL, 0xaccaa80fUL,
  76884. 0xbe7f07e1UL, 0x06c36084UL, 0x5ea070d2UL, 0xe61c17b7UL, 0xf4a9b859UL,
  76885. 0x4c15df3cUL, 0xd1c2e785UL, 0x697e80e0UL, 0x7bcb2f0eUL, 0xc377486bUL,
  76886. 0xcb0d0fa2UL, 0x73b168c7UL, 0x6104c729UL, 0xd9b8a04cUL, 0x446f98f5UL,
  76887. 0xfcd3ff90UL, 0xee66507eUL, 0x56da371bUL, 0x0eb9274dUL, 0xb6054028UL,
  76888. 0xa4b0efc6UL, 0x1c0c88a3UL, 0x81dbb01aUL, 0x3967d77fUL, 0x2bd27891UL,
  76889. 0x936e1ff4UL, 0x3b26f703UL, 0x839a9066UL, 0x912f3f88UL, 0x299358edUL,
  76890. 0xb4446054UL, 0x0cf80731UL, 0x1e4da8dfUL, 0xa6f1cfbaUL, 0xfe92dfecUL,
  76891. 0x462eb889UL, 0x549b1767UL, 0xec277002UL, 0x71f048bbUL, 0xc94c2fdeUL,
  76892. 0xdbf98030UL, 0x6345e755UL, 0x6b3fa09cUL, 0xd383c7f9UL, 0xc1366817UL,
  76893. 0x798a0f72UL, 0xe45d37cbUL, 0x5ce150aeUL, 0x4e54ff40UL, 0xf6e89825UL,
  76894. 0xae8b8873UL, 0x1637ef16UL, 0x048240f8UL, 0xbc3e279dUL, 0x21e91f24UL,
  76895. 0x99557841UL, 0x8be0d7afUL, 0x335cb0caUL, 0xed59b63bUL, 0x55e5d15eUL,
  76896. 0x47507eb0UL, 0xffec19d5UL, 0x623b216cUL, 0xda874609UL, 0xc832e9e7UL,
  76897. 0x708e8e82UL, 0x28ed9ed4UL, 0x9051f9b1UL, 0x82e4565fUL, 0x3a58313aUL,
  76898. 0xa78f0983UL, 0x1f336ee6UL, 0x0d86c108UL, 0xb53aa66dUL, 0xbd40e1a4UL,
  76899. 0x05fc86c1UL, 0x1749292fUL, 0xaff54e4aUL, 0x322276f3UL, 0x8a9e1196UL,
  76900. 0x982bbe78UL, 0x2097d91dUL, 0x78f4c94bUL, 0xc048ae2eUL, 0xd2fd01c0UL,
  76901. 0x6a4166a5UL, 0xf7965e1cUL, 0x4f2a3979UL, 0x5d9f9697UL, 0xe523f1f2UL,
  76902. 0x4d6b1905UL, 0xf5d77e60UL, 0xe762d18eUL, 0x5fdeb6ebUL, 0xc2098e52UL,
  76903. 0x7ab5e937UL, 0x680046d9UL, 0xd0bc21bcUL, 0x88df31eaUL, 0x3063568fUL,
  76904. 0x22d6f961UL, 0x9a6a9e04UL, 0x07bda6bdUL, 0xbf01c1d8UL, 0xadb46e36UL,
  76905. 0x15080953UL, 0x1d724e9aUL, 0xa5ce29ffUL, 0xb77b8611UL, 0x0fc7e174UL,
  76906. 0x9210d9cdUL, 0x2aacbea8UL, 0x38191146UL, 0x80a57623UL, 0xd8c66675UL,
  76907. 0x607a0110UL, 0x72cfaefeUL, 0xca73c99bUL, 0x57a4f122UL, 0xef189647UL,
  76908. 0xfdad39a9UL, 0x45115eccUL, 0x764dee06UL, 0xcef18963UL, 0xdc44268dUL,
  76909. 0x64f841e8UL, 0xf92f7951UL, 0x41931e34UL, 0x5326b1daUL, 0xeb9ad6bfUL,
  76910. 0xb3f9c6e9UL, 0x0b45a18cUL, 0x19f00e62UL, 0xa14c6907UL, 0x3c9b51beUL,
  76911. 0x842736dbUL, 0x96929935UL, 0x2e2efe50UL, 0x2654b999UL, 0x9ee8defcUL,
  76912. 0x8c5d7112UL, 0x34e11677UL, 0xa9362eceUL, 0x118a49abUL, 0x033fe645UL,
  76913. 0xbb838120UL, 0xe3e09176UL, 0x5b5cf613UL, 0x49e959fdUL, 0xf1553e98UL,
  76914. 0x6c820621UL, 0xd43e6144UL, 0xc68bceaaUL, 0x7e37a9cfUL, 0xd67f4138UL,
  76915. 0x6ec3265dUL, 0x7c7689b3UL, 0xc4caeed6UL, 0x591dd66fUL, 0xe1a1b10aUL,
  76916. 0xf3141ee4UL, 0x4ba87981UL, 0x13cb69d7UL, 0xab770eb2UL, 0xb9c2a15cUL,
  76917. 0x017ec639UL, 0x9ca9fe80UL, 0x241599e5UL, 0x36a0360bUL, 0x8e1c516eUL,
  76918. 0x866616a7UL, 0x3eda71c2UL, 0x2c6fde2cUL, 0x94d3b949UL, 0x090481f0UL,
  76919. 0xb1b8e695UL, 0xa30d497bUL, 0x1bb12e1eUL, 0x43d23e48UL, 0xfb6e592dUL,
  76920. 0xe9dbf6c3UL, 0x516791a6UL, 0xccb0a91fUL, 0x740cce7aUL, 0x66b96194UL,
  76921. 0xde0506f1UL
  76922. },
  76923. {
  76924. 0x00000000UL, 0x96300777UL, 0x2c610eeeUL, 0xba510999UL, 0x19c46d07UL,
  76925. 0x8ff46a70UL, 0x35a563e9UL, 0xa395649eUL, 0x3288db0eUL, 0xa4b8dc79UL,
  76926. 0x1ee9d5e0UL, 0x88d9d297UL, 0x2b4cb609UL, 0xbd7cb17eUL, 0x072db8e7UL,
  76927. 0x911dbf90UL, 0x6410b71dUL, 0xf220b06aUL, 0x4871b9f3UL, 0xde41be84UL,
  76928. 0x7dd4da1aUL, 0xebe4dd6dUL, 0x51b5d4f4UL, 0xc785d383UL, 0x56986c13UL,
  76929. 0xc0a86b64UL, 0x7af962fdUL, 0xecc9658aUL, 0x4f5c0114UL, 0xd96c0663UL,
  76930. 0x633d0ffaUL, 0xf50d088dUL, 0xc8206e3bUL, 0x5e10694cUL, 0xe44160d5UL,
  76931. 0x727167a2UL, 0xd1e4033cUL, 0x47d4044bUL, 0xfd850dd2UL, 0x6bb50aa5UL,
  76932. 0xfaa8b535UL, 0x6c98b242UL, 0xd6c9bbdbUL, 0x40f9bcacUL, 0xe36cd832UL,
  76933. 0x755cdf45UL, 0xcf0dd6dcUL, 0x593dd1abUL, 0xac30d926UL, 0x3a00de51UL,
  76934. 0x8051d7c8UL, 0x1661d0bfUL, 0xb5f4b421UL, 0x23c4b356UL, 0x9995bacfUL,
  76935. 0x0fa5bdb8UL, 0x9eb80228UL, 0x0888055fUL, 0xb2d90cc6UL, 0x24e90bb1UL,
  76936. 0x877c6f2fUL, 0x114c6858UL, 0xab1d61c1UL, 0x3d2d66b6UL, 0x9041dc76UL,
  76937. 0x0671db01UL, 0xbc20d298UL, 0x2a10d5efUL, 0x8985b171UL, 0x1fb5b606UL,
  76938. 0xa5e4bf9fUL, 0x33d4b8e8UL, 0xa2c90778UL, 0x34f9000fUL, 0x8ea80996UL,
  76939. 0x18980ee1UL, 0xbb0d6a7fUL, 0x2d3d6d08UL, 0x976c6491UL, 0x015c63e6UL,
  76940. 0xf4516b6bUL, 0x62616c1cUL, 0xd8306585UL, 0x4e0062f2UL, 0xed95066cUL,
  76941. 0x7ba5011bUL, 0xc1f40882UL, 0x57c40ff5UL, 0xc6d9b065UL, 0x50e9b712UL,
  76942. 0xeab8be8bUL, 0x7c88b9fcUL, 0xdf1ddd62UL, 0x492dda15UL, 0xf37cd38cUL,
  76943. 0x654cd4fbUL, 0x5861b24dUL, 0xce51b53aUL, 0x7400bca3UL, 0xe230bbd4UL,
  76944. 0x41a5df4aUL, 0xd795d83dUL, 0x6dc4d1a4UL, 0xfbf4d6d3UL, 0x6ae96943UL,
  76945. 0xfcd96e34UL, 0x468867adUL, 0xd0b860daUL, 0x732d0444UL, 0xe51d0333UL,
  76946. 0x5f4c0aaaUL, 0xc97c0dddUL, 0x3c710550UL, 0xaa410227UL, 0x10100bbeUL,
  76947. 0x86200cc9UL, 0x25b56857UL, 0xb3856f20UL, 0x09d466b9UL, 0x9fe461ceUL,
  76948. 0x0ef9de5eUL, 0x98c9d929UL, 0x2298d0b0UL, 0xb4a8d7c7UL, 0x173db359UL,
  76949. 0x810db42eUL, 0x3b5cbdb7UL, 0xad6cbac0UL, 0x2083b8edUL, 0xb6b3bf9aUL,
  76950. 0x0ce2b603UL, 0x9ad2b174UL, 0x3947d5eaUL, 0xaf77d29dUL, 0x1526db04UL,
  76951. 0x8316dc73UL, 0x120b63e3UL, 0x843b6494UL, 0x3e6a6d0dUL, 0xa85a6a7aUL,
  76952. 0x0bcf0ee4UL, 0x9dff0993UL, 0x27ae000aUL, 0xb19e077dUL, 0x44930ff0UL,
  76953. 0xd2a30887UL, 0x68f2011eUL, 0xfec20669UL, 0x5d5762f7UL, 0xcb676580UL,
  76954. 0x71366c19UL, 0xe7066b6eUL, 0x761bd4feUL, 0xe02bd389UL, 0x5a7ada10UL,
  76955. 0xcc4add67UL, 0x6fdfb9f9UL, 0xf9efbe8eUL, 0x43beb717UL, 0xd58eb060UL,
  76956. 0xe8a3d6d6UL, 0x7e93d1a1UL, 0xc4c2d838UL, 0x52f2df4fUL, 0xf167bbd1UL,
  76957. 0x6757bca6UL, 0xdd06b53fUL, 0x4b36b248UL, 0xda2b0dd8UL, 0x4c1b0aafUL,
  76958. 0xf64a0336UL, 0x607a0441UL, 0xc3ef60dfUL, 0x55df67a8UL, 0xef8e6e31UL,
  76959. 0x79be6946UL, 0x8cb361cbUL, 0x1a8366bcUL, 0xa0d26f25UL, 0x36e26852UL,
  76960. 0x95770cccUL, 0x03470bbbUL, 0xb9160222UL, 0x2f260555UL, 0xbe3bbac5UL,
  76961. 0x280bbdb2UL, 0x925ab42bUL, 0x046ab35cUL, 0xa7ffd7c2UL, 0x31cfd0b5UL,
  76962. 0x8b9ed92cUL, 0x1daede5bUL, 0xb0c2649bUL, 0x26f263ecUL, 0x9ca36a75UL,
  76963. 0x0a936d02UL, 0xa906099cUL, 0x3f360eebUL, 0x85670772UL, 0x13570005UL,
  76964. 0x824abf95UL, 0x147ab8e2UL, 0xae2bb17bUL, 0x381bb60cUL, 0x9b8ed292UL,
  76965. 0x0dbed5e5UL, 0xb7efdc7cUL, 0x21dfdb0bUL, 0xd4d2d386UL, 0x42e2d4f1UL,
  76966. 0xf8b3dd68UL, 0x6e83da1fUL, 0xcd16be81UL, 0x5b26b9f6UL, 0xe177b06fUL,
  76967. 0x7747b718UL, 0xe65a0888UL, 0x706a0fffUL, 0xca3b0666UL, 0x5c0b0111UL,
  76968. 0xff9e658fUL, 0x69ae62f8UL, 0xd3ff6b61UL, 0x45cf6c16UL, 0x78e20aa0UL,
  76969. 0xeed20dd7UL, 0x5483044eUL, 0xc2b30339UL, 0x612667a7UL, 0xf71660d0UL,
  76970. 0x4d476949UL, 0xdb776e3eUL, 0x4a6ad1aeUL, 0xdc5ad6d9UL, 0x660bdf40UL,
  76971. 0xf03bd837UL, 0x53aebca9UL, 0xc59ebbdeUL, 0x7fcfb247UL, 0xe9ffb530UL,
  76972. 0x1cf2bdbdUL, 0x8ac2bacaUL, 0x3093b353UL, 0xa6a3b424UL, 0x0536d0baUL,
  76973. 0x9306d7cdUL, 0x2957de54UL, 0xbf67d923UL, 0x2e7a66b3UL, 0xb84a61c4UL,
  76974. 0x021b685dUL, 0x942b6f2aUL, 0x37be0bb4UL, 0xa18e0cc3UL, 0x1bdf055aUL,
  76975. 0x8def022dUL
  76976. },
  76977. {
  76978. 0x00000000UL, 0x41311b19UL, 0x82623632UL, 0xc3532d2bUL, 0x04c56c64UL,
  76979. 0x45f4777dUL, 0x86a75a56UL, 0xc796414fUL, 0x088ad9c8UL, 0x49bbc2d1UL,
  76980. 0x8ae8effaUL, 0xcbd9f4e3UL, 0x0c4fb5acUL, 0x4d7eaeb5UL, 0x8e2d839eUL,
  76981. 0xcf1c9887UL, 0x5112c24aUL, 0x1023d953UL, 0xd370f478UL, 0x9241ef61UL,
  76982. 0x55d7ae2eUL, 0x14e6b537UL, 0xd7b5981cUL, 0x96848305UL, 0x59981b82UL,
  76983. 0x18a9009bUL, 0xdbfa2db0UL, 0x9acb36a9UL, 0x5d5d77e6UL, 0x1c6c6cffUL,
  76984. 0xdf3f41d4UL, 0x9e0e5acdUL, 0xa2248495UL, 0xe3159f8cUL, 0x2046b2a7UL,
  76985. 0x6177a9beUL, 0xa6e1e8f1UL, 0xe7d0f3e8UL, 0x2483dec3UL, 0x65b2c5daUL,
  76986. 0xaaae5d5dUL, 0xeb9f4644UL, 0x28cc6b6fUL, 0x69fd7076UL, 0xae6b3139UL,
  76987. 0xef5a2a20UL, 0x2c09070bUL, 0x6d381c12UL, 0xf33646dfUL, 0xb2075dc6UL,
  76988. 0x715470edUL, 0x30656bf4UL, 0xf7f32abbUL, 0xb6c231a2UL, 0x75911c89UL,
  76989. 0x34a00790UL, 0xfbbc9f17UL, 0xba8d840eUL, 0x79dea925UL, 0x38efb23cUL,
  76990. 0xff79f373UL, 0xbe48e86aUL, 0x7d1bc541UL, 0x3c2ade58UL, 0x054f79f0UL,
  76991. 0x447e62e9UL, 0x872d4fc2UL, 0xc61c54dbUL, 0x018a1594UL, 0x40bb0e8dUL,
  76992. 0x83e823a6UL, 0xc2d938bfUL, 0x0dc5a038UL, 0x4cf4bb21UL, 0x8fa7960aUL,
  76993. 0xce968d13UL, 0x0900cc5cUL, 0x4831d745UL, 0x8b62fa6eUL, 0xca53e177UL,
  76994. 0x545dbbbaUL, 0x156ca0a3UL, 0xd63f8d88UL, 0x970e9691UL, 0x5098d7deUL,
  76995. 0x11a9ccc7UL, 0xd2fae1ecUL, 0x93cbfaf5UL, 0x5cd76272UL, 0x1de6796bUL,
  76996. 0xdeb55440UL, 0x9f844f59UL, 0x58120e16UL, 0x1923150fUL, 0xda703824UL,
  76997. 0x9b41233dUL, 0xa76bfd65UL, 0xe65ae67cUL, 0x2509cb57UL, 0x6438d04eUL,
  76998. 0xa3ae9101UL, 0xe29f8a18UL, 0x21cca733UL, 0x60fdbc2aUL, 0xafe124adUL,
  76999. 0xeed03fb4UL, 0x2d83129fUL, 0x6cb20986UL, 0xab2448c9UL, 0xea1553d0UL,
  77000. 0x29467efbUL, 0x687765e2UL, 0xf6793f2fUL, 0xb7482436UL, 0x741b091dUL,
  77001. 0x352a1204UL, 0xf2bc534bUL, 0xb38d4852UL, 0x70de6579UL, 0x31ef7e60UL,
  77002. 0xfef3e6e7UL, 0xbfc2fdfeUL, 0x7c91d0d5UL, 0x3da0cbccUL, 0xfa368a83UL,
  77003. 0xbb07919aUL, 0x7854bcb1UL, 0x3965a7a8UL, 0x4b98833bUL, 0x0aa99822UL,
  77004. 0xc9fab509UL, 0x88cbae10UL, 0x4f5def5fUL, 0x0e6cf446UL, 0xcd3fd96dUL,
  77005. 0x8c0ec274UL, 0x43125af3UL, 0x022341eaUL, 0xc1706cc1UL, 0x804177d8UL,
  77006. 0x47d73697UL, 0x06e62d8eUL, 0xc5b500a5UL, 0x84841bbcUL, 0x1a8a4171UL,
  77007. 0x5bbb5a68UL, 0x98e87743UL, 0xd9d96c5aUL, 0x1e4f2d15UL, 0x5f7e360cUL,
  77008. 0x9c2d1b27UL, 0xdd1c003eUL, 0x120098b9UL, 0x533183a0UL, 0x9062ae8bUL,
  77009. 0xd153b592UL, 0x16c5f4ddUL, 0x57f4efc4UL, 0x94a7c2efUL, 0xd596d9f6UL,
  77010. 0xe9bc07aeUL, 0xa88d1cb7UL, 0x6bde319cUL, 0x2aef2a85UL, 0xed796bcaUL,
  77011. 0xac4870d3UL, 0x6f1b5df8UL, 0x2e2a46e1UL, 0xe136de66UL, 0xa007c57fUL,
  77012. 0x6354e854UL, 0x2265f34dUL, 0xe5f3b202UL, 0xa4c2a91bUL, 0x67918430UL,
  77013. 0x26a09f29UL, 0xb8aec5e4UL, 0xf99fdefdUL, 0x3accf3d6UL, 0x7bfde8cfUL,
  77014. 0xbc6ba980UL, 0xfd5ab299UL, 0x3e099fb2UL, 0x7f3884abUL, 0xb0241c2cUL,
  77015. 0xf1150735UL, 0x32462a1eUL, 0x73773107UL, 0xb4e17048UL, 0xf5d06b51UL,
  77016. 0x3683467aUL, 0x77b25d63UL, 0x4ed7facbUL, 0x0fe6e1d2UL, 0xccb5ccf9UL,
  77017. 0x8d84d7e0UL, 0x4a1296afUL, 0x0b238db6UL, 0xc870a09dUL, 0x8941bb84UL,
  77018. 0x465d2303UL, 0x076c381aUL, 0xc43f1531UL, 0x850e0e28UL, 0x42984f67UL,
  77019. 0x03a9547eUL, 0xc0fa7955UL, 0x81cb624cUL, 0x1fc53881UL, 0x5ef42398UL,
  77020. 0x9da70eb3UL, 0xdc9615aaUL, 0x1b0054e5UL, 0x5a314ffcUL, 0x996262d7UL,
  77021. 0xd85379ceUL, 0x174fe149UL, 0x567efa50UL, 0x952dd77bUL, 0xd41ccc62UL,
  77022. 0x138a8d2dUL, 0x52bb9634UL, 0x91e8bb1fUL, 0xd0d9a006UL, 0xecf37e5eUL,
  77023. 0xadc26547UL, 0x6e91486cUL, 0x2fa05375UL, 0xe836123aUL, 0xa9070923UL,
  77024. 0x6a542408UL, 0x2b653f11UL, 0xe479a796UL, 0xa548bc8fUL, 0x661b91a4UL,
  77025. 0x272a8abdUL, 0xe0bccbf2UL, 0xa18dd0ebUL, 0x62defdc0UL, 0x23efe6d9UL,
  77026. 0xbde1bc14UL, 0xfcd0a70dUL, 0x3f838a26UL, 0x7eb2913fUL, 0xb924d070UL,
  77027. 0xf815cb69UL, 0x3b46e642UL, 0x7a77fd5bUL, 0xb56b65dcUL, 0xf45a7ec5UL,
  77028. 0x370953eeUL, 0x763848f7UL, 0xb1ae09b8UL, 0xf09f12a1UL, 0x33cc3f8aUL,
  77029. 0x72fd2493UL
  77030. },
  77031. {
  77032. 0x00000000UL, 0x376ac201UL, 0x6ed48403UL, 0x59be4602UL, 0xdca80907UL,
  77033. 0xebc2cb06UL, 0xb27c8d04UL, 0x85164f05UL, 0xb851130eUL, 0x8f3bd10fUL,
  77034. 0xd685970dUL, 0xe1ef550cUL, 0x64f91a09UL, 0x5393d808UL, 0x0a2d9e0aUL,
  77035. 0x3d475c0bUL, 0x70a3261cUL, 0x47c9e41dUL, 0x1e77a21fUL, 0x291d601eUL,
  77036. 0xac0b2f1bUL, 0x9b61ed1aUL, 0xc2dfab18UL, 0xf5b56919UL, 0xc8f23512UL,
  77037. 0xff98f713UL, 0xa626b111UL, 0x914c7310UL, 0x145a3c15UL, 0x2330fe14UL,
  77038. 0x7a8eb816UL, 0x4de47a17UL, 0xe0464d38UL, 0xd72c8f39UL, 0x8e92c93bUL,
  77039. 0xb9f80b3aUL, 0x3cee443fUL, 0x0b84863eUL, 0x523ac03cUL, 0x6550023dUL,
  77040. 0x58175e36UL, 0x6f7d9c37UL, 0x36c3da35UL, 0x01a91834UL, 0x84bf5731UL,
  77041. 0xb3d59530UL, 0xea6bd332UL, 0xdd011133UL, 0x90e56b24UL, 0xa78fa925UL,
  77042. 0xfe31ef27UL, 0xc95b2d26UL, 0x4c4d6223UL, 0x7b27a022UL, 0x2299e620UL,
  77043. 0x15f32421UL, 0x28b4782aUL, 0x1fdeba2bUL, 0x4660fc29UL, 0x710a3e28UL,
  77044. 0xf41c712dUL, 0xc376b32cUL, 0x9ac8f52eUL, 0xada2372fUL, 0xc08d9a70UL,
  77045. 0xf7e75871UL, 0xae591e73UL, 0x9933dc72UL, 0x1c259377UL, 0x2b4f5176UL,
  77046. 0x72f11774UL, 0x459bd575UL, 0x78dc897eUL, 0x4fb64b7fUL, 0x16080d7dUL,
  77047. 0x2162cf7cUL, 0xa4748079UL, 0x931e4278UL, 0xcaa0047aUL, 0xfdcac67bUL,
  77048. 0xb02ebc6cUL, 0x87447e6dUL, 0xdefa386fUL, 0xe990fa6eUL, 0x6c86b56bUL,
  77049. 0x5bec776aUL, 0x02523168UL, 0x3538f369UL, 0x087faf62UL, 0x3f156d63UL,
  77050. 0x66ab2b61UL, 0x51c1e960UL, 0xd4d7a665UL, 0xe3bd6464UL, 0xba032266UL,
  77051. 0x8d69e067UL, 0x20cbd748UL, 0x17a11549UL, 0x4e1f534bUL, 0x7975914aUL,
  77052. 0xfc63de4fUL, 0xcb091c4eUL, 0x92b75a4cUL, 0xa5dd984dUL, 0x989ac446UL,
  77053. 0xaff00647UL, 0xf64e4045UL, 0xc1248244UL, 0x4432cd41UL, 0x73580f40UL,
  77054. 0x2ae64942UL, 0x1d8c8b43UL, 0x5068f154UL, 0x67023355UL, 0x3ebc7557UL,
  77055. 0x09d6b756UL, 0x8cc0f853UL, 0xbbaa3a52UL, 0xe2147c50UL, 0xd57ebe51UL,
  77056. 0xe839e25aUL, 0xdf53205bUL, 0x86ed6659UL, 0xb187a458UL, 0x3491eb5dUL,
  77057. 0x03fb295cUL, 0x5a456f5eUL, 0x6d2fad5fUL, 0x801b35e1UL, 0xb771f7e0UL,
  77058. 0xeecfb1e2UL, 0xd9a573e3UL, 0x5cb33ce6UL, 0x6bd9fee7UL, 0x3267b8e5UL,
  77059. 0x050d7ae4UL, 0x384a26efUL, 0x0f20e4eeUL, 0x569ea2ecUL, 0x61f460edUL,
  77060. 0xe4e22fe8UL, 0xd388ede9UL, 0x8a36abebUL, 0xbd5c69eaUL, 0xf0b813fdUL,
  77061. 0xc7d2d1fcUL, 0x9e6c97feUL, 0xa90655ffUL, 0x2c101afaUL, 0x1b7ad8fbUL,
  77062. 0x42c49ef9UL, 0x75ae5cf8UL, 0x48e900f3UL, 0x7f83c2f2UL, 0x263d84f0UL,
  77063. 0x115746f1UL, 0x944109f4UL, 0xa32bcbf5UL, 0xfa958df7UL, 0xcdff4ff6UL,
  77064. 0x605d78d9UL, 0x5737bad8UL, 0x0e89fcdaUL, 0x39e33edbUL, 0xbcf571deUL,
  77065. 0x8b9fb3dfUL, 0xd221f5ddUL, 0xe54b37dcUL, 0xd80c6bd7UL, 0xef66a9d6UL,
  77066. 0xb6d8efd4UL, 0x81b22dd5UL, 0x04a462d0UL, 0x33cea0d1UL, 0x6a70e6d3UL,
  77067. 0x5d1a24d2UL, 0x10fe5ec5UL, 0x27949cc4UL, 0x7e2adac6UL, 0x494018c7UL,
  77068. 0xcc5657c2UL, 0xfb3c95c3UL, 0xa282d3c1UL, 0x95e811c0UL, 0xa8af4dcbUL,
  77069. 0x9fc58fcaUL, 0xc67bc9c8UL, 0xf1110bc9UL, 0x740744ccUL, 0x436d86cdUL,
  77070. 0x1ad3c0cfUL, 0x2db902ceUL, 0x4096af91UL, 0x77fc6d90UL, 0x2e422b92UL,
  77071. 0x1928e993UL, 0x9c3ea696UL, 0xab546497UL, 0xf2ea2295UL, 0xc580e094UL,
  77072. 0xf8c7bc9fUL, 0xcfad7e9eUL, 0x9613389cUL, 0xa179fa9dUL, 0x246fb598UL,
  77073. 0x13057799UL, 0x4abb319bUL, 0x7dd1f39aUL, 0x3035898dUL, 0x075f4b8cUL,
  77074. 0x5ee10d8eUL, 0x698bcf8fUL, 0xec9d808aUL, 0xdbf7428bUL, 0x82490489UL,
  77075. 0xb523c688UL, 0x88649a83UL, 0xbf0e5882UL, 0xe6b01e80UL, 0xd1dadc81UL,
  77076. 0x54cc9384UL, 0x63a65185UL, 0x3a181787UL, 0x0d72d586UL, 0xa0d0e2a9UL,
  77077. 0x97ba20a8UL, 0xce0466aaUL, 0xf96ea4abUL, 0x7c78ebaeUL, 0x4b1229afUL,
  77078. 0x12ac6fadUL, 0x25c6adacUL, 0x1881f1a7UL, 0x2feb33a6UL, 0x765575a4UL,
  77079. 0x413fb7a5UL, 0xc429f8a0UL, 0xf3433aa1UL, 0xaafd7ca3UL, 0x9d97bea2UL,
  77080. 0xd073c4b5UL, 0xe71906b4UL, 0xbea740b6UL, 0x89cd82b7UL, 0x0cdbcdb2UL,
  77081. 0x3bb10fb3UL, 0x620f49b1UL, 0x55658bb0UL, 0x6822d7bbUL, 0x5f4815baUL,
  77082. 0x06f653b8UL, 0x319c91b9UL, 0xb48adebcUL, 0x83e01cbdUL, 0xda5e5abfUL,
  77083. 0xed3498beUL
  77084. },
  77085. {
  77086. 0x00000000UL, 0x6567bcb8UL, 0x8bc809aaUL, 0xeeafb512UL, 0x5797628fUL,
  77087. 0x32f0de37UL, 0xdc5f6b25UL, 0xb938d79dUL, 0xef28b4c5UL, 0x8a4f087dUL,
  77088. 0x64e0bd6fUL, 0x018701d7UL, 0xb8bfd64aUL, 0xddd86af2UL, 0x3377dfe0UL,
  77089. 0x56106358UL, 0x9f571950UL, 0xfa30a5e8UL, 0x149f10faUL, 0x71f8ac42UL,
  77090. 0xc8c07bdfUL, 0xada7c767UL, 0x43087275UL, 0x266fcecdUL, 0x707fad95UL,
  77091. 0x1518112dUL, 0xfbb7a43fUL, 0x9ed01887UL, 0x27e8cf1aUL, 0x428f73a2UL,
  77092. 0xac20c6b0UL, 0xc9477a08UL, 0x3eaf32a0UL, 0x5bc88e18UL, 0xb5673b0aUL,
  77093. 0xd00087b2UL, 0x6938502fUL, 0x0c5fec97UL, 0xe2f05985UL, 0x8797e53dUL,
  77094. 0xd1878665UL, 0xb4e03addUL, 0x5a4f8fcfUL, 0x3f283377UL, 0x8610e4eaUL,
  77095. 0xe3775852UL, 0x0dd8ed40UL, 0x68bf51f8UL, 0xa1f82bf0UL, 0xc49f9748UL,
  77096. 0x2a30225aUL, 0x4f579ee2UL, 0xf66f497fUL, 0x9308f5c7UL, 0x7da740d5UL,
  77097. 0x18c0fc6dUL, 0x4ed09f35UL, 0x2bb7238dUL, 0xc518969fUL, 0xa07f2a27UL,
  77098. 0x1947fdbaUL, 0x7c204102UL, 0x928ff410UL, 0xf7e848a8UL, 0x3d58149bUL,
  77099. 0x583fa823UL, 0xb6901d31UL, 0xd3f7a189UL, 0x6acf7614UL, 0x0fa8caacUL,
  77100. 0xe1077fbeUL, 0x8460c306UL, 0xd270a05eUL, 0xb7171ce6UL, 0x59b8a9f4UL,
  77101. 0x3cdf154cUL, 0x85e7c2d1UL, 0xe0807e69UL, 0x0e2fcb7bUL, 0x6b4877c3UL,
  77102. 0xa20f0dcbUL, 0xc768b173UL, 0x29c70461UL, 0x4ca0b8d9UL, 0xf5986f44UL,
  77103. 0x90ffd3fcUL, 0x7e5066eeUL, 0x1b37da56UL, 0x4d27b90eUL, 0x284005b6UL,
  77104. 0xc6efb0a4UL, 0xa3880c1cUL, 0x1ab0db81UL, 0x7fd76739UL, 0x9178d22bUL,
  77105. 0xf41f6e93UL, 0x03f7263bUL, 0x66909a83UL, 0x883f2f91UL, 0xed589329UL,
  77106. 0x546044b4UL, 0x3107f80cUL, 0xdfa84d1eUL, 0xbacff1a6UL, 0xecdf92feUL,
  77107. 0x89b82e46UL, 0x67179b54UL, 0x027027ecUL, 0xbb48f071UL, 0xde2f4cc9UL,
  77108. 0x3080f9dbUL, 0x55e74563UL, 0x9ca03f6bUL, 0xf9c783d3UL, 0x176836c1UL,
  77109. 0x720f8a79UL, 0xcb375de4UL, 0xae50e15cUL, 0x40ff544eUL, 0x2598e8f6UL,
  77110. 0x73888baeUL, 0x16ef3716UL, 0xf8408204UL, 0x9d273ebcUL, 0x241fe921UL,
  77111. 0x41785599UL, 0xafd7e08bUL, 0xcab05c33UL, 0x3bb659edUL, 0x5ed1e555UL,
  77112. 0xb07e5047UL, 0xd519ecffUL, 0x6c213b62UL, 0x094687daUL, 0xe7e932c8UL,
  77113. 0x828e8e70UL, 0xd49eed28UL, 0xb1f95190UL, 0x5f56e482UL, 0x3a31583aUL,
  77114. 0x83098fa7UL, 0xe66e331fUL, 0x08c1860dUL, 0x6da63ab5UL, 0xa4e140bdUL,
  77115. 0xc186fc05UL, 0x2f294917UL, 0x4a4ef5afUL, 0xf3762232UL, 0x96119e8aUL,
  77116. 0x78be2b98UL, 0x1dd99720UL, 0x4bc9f478UL, 0x2eae48c0UL, 0xc001fdd2UL,
  77117. 0xa566416aUL, 0x1c5e96f7UL, 0x79392a4fUL, 0x97969f5dUL, 0xf2f123e5UL,
  77118. 0x05196b4dUL, 0x607ed7f5UL, 0x8ed162e7UL, 0xebb6de5fUL, 0x528e09c2UL,
  77119. 0x37e9b57aUL, 0xd9460068UL, 0xbc21bcd0UL, 0xea31df88UL, 0x8f566330UL,
  77120. 0x61f9d622UL, 0x049e6a9aUL, 0xbda6bd07UL, 0xd8c101bfUL, 0x366eb4adUL,
  77121. 0x53090815UL, 0x9a4e721dUL, 0xff29cea5UL, 0x11867bb7UL, 0x74e1c70fUL,
  77122. 0xcdd91092UL, 0xa8beac2aUL, 0x46111938UL, 0x2376a580UL, 0x7566c6d8UL,
  77123. 0x10017a60UL, 0xfeaecf72UL, 0x9bc973caUL, 0x22f1a457UL, 0x479618efUL,
  77124. 0xa939adfdUL, 0xcc5e1145UL, 0x06ee4d76UL, 0x6389f1ceUL, 0x8d2644dcUL,
  77125. 0xe841f864UL, 0x51792ff9UL, 0x341e9341UL, 0xdab12653UL, 0xbfd69aebUL,
  77126. 0xe9c6f9b3UL, 0x8ca1450bUL, 0x620ef019UL, 0x07694ca1UL, 0xbe519b3cUL,
  77127. 0xdb362784UL, 0x35999296UL, 0x50fe2e2eUL, 0x99b95426UL, 0xfcdee89eUL,
  77128. 0x12715d8cUL, 0x7716e134UL, 0xce2e36a9UL, 0xab498a11UL, 0x45e63f03UL,
  77129. 0x208183bbUL, 0x7691e0e3UL, 0x13f65c5bUL, 0xfd59e949UL, 0x983e55f1UL,
  77130. 0x2106826cUL, 0x44613ed4UL, 0xaace8bc6UL, 0xcfa9377eUL, 0x38417fd6UL,
  77131. 0x5d26c36eUL, 0xb389767cUL, 0xd6eecac4UL, 0x6fd61d59UL, 0x0ab1a1e1UL,
  77132. 0xe41e14f3UL, 0x8179a84bUL, 0xd769cb13UL, 0xb20e77abUL, 0x5ca1c2b9UL,
  77133. 0x39c67e01UL, 0x80fea99cUL, 0xe5991524UL, 0x0b36a036UL, 0x6e511c8eUL,
  77134. 0xa7166686UL, 0xc271da3eUL, 0x2cde6f2cUL, 0x49b9d394UL, 0xf0810409UL,
  77135. 0x95e6b8b1UL, 0x7b490da3UL, 0x1e2eb11bUL, 0x483ed243UL, 0x2d596efbUL,
  77136. 0xc3f6dbe9UL, 0xa6916751UL, 0x1fa9b0ccUL, 0x7ace0c74UL, 0x9461b966UL,
  77137. 0xf10605deUL
  77138. #endif
  77139. }
  77140. };
  77141. /*** End of inlined file: crc32.h ***/
  77142. #endif /* DYNAMIC_CRC_TABLE */
  77143. /* =========================================================================
  77144. * This function can be used by asm versions of crc32()
  77145. */
  77146. const unsigned long FAR * ZEXPORT get_crc_table()
  77147. {
  77148. #ifdef DYNAMIC_CRC_TABLE
  77149. if (crc_table_empty)
  77150. make_crc_table();
  77151. #endif /* DYNAMIC_CRC_TABLE */
  77152. return (const unsigned long FAR *)crc_table;
  77153. }
  77154. /* ========================================================================= */
  77155. #define DO1 crc = crc_table[0][((int)crc ^ (*buf++)) & 0xff] ^ (crc >> 8)
  77156. #define DO8 DO1; DO1; DO1; DO1; DO1; DO1; DO1; DO1
  77157. /* ========================================================================= */
  77158. unsigned long ZEXPORT crc32 (unsigned long crc, const unsigned char FAR *buf, unsigned len)
  77159. {
  77160. if (buf == Z_NULL) return 0UL;
  77161. #ifdef DYNAMIC_CRC_TABLE
  77162. if (crc_table_empty)
  77163. make_crc_table();
  77164. #endif /* DYNAMIC_CRC_TABLE */
  77165. #ifdef BYFOUR
  77166. if (sizeof(void *) == sizeof(ptrdiff_t)) {
  77167. u4 endian;
  77168. endian = 1;
  77169. if (*((unsigned char *)(&endian)))
  77170. return crc32_little(crc, buf, len);
  77171. else
  77172. return crc32_big(crc, buf, len);
  77173. }
  77174. #endif /* BYFOUR */
  77175. crc = crc ^ 0xffffffffUL;
  77176. while (len >= 8) {
  77177. DO8;
  77178. len -= 8;
  77179. }
  77180. if (len) do {
  77181. DO1;
  77182. } while (--len);
  77183. return crc ^ 0xffffffffUL;
  77184. }
  77185. #ifdef BYFOUR
  77186. /* ========================================================================= */
  77187. #define DOLIT4 c ^= *buf4++; \
  77188. c = crc_table[3][c & 0xff] ^ crc_table[2][(c >> 8) & 0xff] ^ \
  77189. crc_table[1][(c >> 16) & 0xff] ^ crc_table[0][c >> 24]
  77190. #define DOLIT32 DOLIT4; DOLIT4; DOLIT4; DOLIT4; DOLIT4; DOLIT4; DOLIT4; DOLIT4
  77191. /* ========================================================================= */
  77192. local unsigned long crc32_little(unsigned long crc, const unsigned char FAR *buf, unsigned len)
  77193. {
  77194. register u4 c;
  77195. register const u4 FAR *buf4;
  77196. c = (u4)crc;
  77197. c = ~c;
  77198. while (len && ((ptrdiff_t)buf & 3)) {
  77199. c = crc_table[0][(c ^ *buf++) & 0xff] ^ (c >> 8);
  77200. len--;
  77201. }
  77202. buf4 = (const u4 FAR *)(const void FAR *)buf;
  77203. while (len >= 32) {
  77204. DOLIT32;
  77205. len -= 32;
  77206. }
  77207. while (len >= 4) {
  77208. DOLIT4;
  77209. len -= 4;
  77210. }
  77211. buf = (const unsigned char FAR *)buf4;
  77212. if (len) do {
  77213. c = crc_table[0][(c ^ *buf++) & 0xff] ^ (c >> 8);
  77214. } while (--len);
  77215. c = ~c;
  77216. return (unsigned long)c;
  77217. }
  77218. /* ========================================================================= */
  77219. #define DOBIG4 c ^= *++buf4; \
  77220. c = crc_table[4][c & 0xff] ^ crc_table[5][(c >> 8) & 0xff] ^ \
  77221. crc_table[6][(c >> 16) & 0xff] ^ crc_table[7][c >> 24]
  77222. #define DOBIG32 DOBIG4; DOBIG4; DOBIG4; DOBIG4; DOBIG4; DOBIG4; DOBIG4; DOBIG4
  77223. /* ========================================================================= */
  77224. local unsigned long crc32_big (unsigned long crc, const unsigned char FAR *buf, unsigned len)
  77225. {
  77226. register u4 c;
  77227. register const u4 FAR *buf4;
  77228. c = REV((u4)crc);
  77229. c = ~c;
  77230. while (len && ((ptrdiff_t)buf & 3)) {
  77231. c = crc_table[4][(c >> 24) ^ *buf++] ^ (c << 8);
  77232. len--;
  77233. }
  77234. buf4 = (const u4 FAR *)(const void FAR *)buf;
  77235. buf4--;
  77236. while (len >= 32) {
  77237. DOBIG32;
  77238. len -= 32;
  77239. }
  77240. while (len >= 4) {
  77241. DOBIG4;
  77242. len -= 4;
  77243. }
  77244. buf4++;
  77245. buf = (const unsigned char FAR *)buf4;
  77246. if (len) do {
  77247. c = crc_table[4][(c >> 24) ^ *buf++] ^ (c << 8);
  77248. } while (--len);
  77249. c = ~c;
  77250. return (unsigned long)(REV(c));
  77251. }
  77252. #endif /* BYFOUR */
  77253. #define GF2_DIM 32 /* dimension of GF(2) vectors (length of CRC) */
  77254. /* ========================================================================= */
  77255. local unsigned long gf2_matrix_times (unsigned long *mat, unsigned long vec)
  77256. {
  77257. unsigned long sum;
  77258. sum = 0;
  77259. while (vec) {
  77260. if (vec & 1)
  77261. sum ^= *mat;
  77262. vec >>= 1;
  77263. mat++;
  77264. }
  77265. return sum;
  77266. }
  77267. /* ========================================================================= */
  77268. local void gf2_matrix_square (unsigned long *square, unsigned long *mat)
  77269. {
  77270. int n;
  77271. for (n = 0; n < GF2_DIM; n++)
  77272. square[n] = gf2_matrix_times(mat, mat[n]);
  77273. }
  77274. /* ========================================================================= */
  77275. uLong ZEXPORT crc32_combine (uLong crc1, uLong crc2, z_off_t len2)
  77276. {
  77277. int n;
  77278. unsigned long row;
  77279. unsigned long even[GF2_DIM]; /* even-power-of-two zeros operator */
  77280. unsigned long odd[GF2_DIM]; /* odd-power-of-two zeros operator */
  77281. /* degenerate case */
  77282. if (len2 == 0)
  77283. return crc1;
  77284. /* put operator for one zero bit in odd */
  77285. odd[0] = 0xedb88320L; /* CRC-32 polynomial */
  77286. row = 1;
  77287. for (n = 1; n < GF2_DIM; n++) {
  77288. odd[n] = row;
  77289. row <<= 1;
  77290. }
  77291. /* put operator for two zero bits in even */
  77292. gf2_matrix_square(even, odd);
  77293. /* put operator for four zero bits in odd */
  77294. gf2_matrix_square(odd, even);
  77295. /* apply len2 zeros to crc1 (first square will put the operator for one
  77296. zero byte, eight zero bits, in even) */
  77297. do {
  77298. /* apply zeros operator for this bit of len2 */
  77299. gf2_matrix_square(even, odd);
  77300. if (len2 & 1)
  77301. crc1 = gf2_matrix_times(even, crc1);
  77302. len2 >>= 1;
  77303. /* if no more bits set, then done */
  77304. if (len2 == 0)
  77305. break;
  77306. /* another iteration of the loop with odd and even swapped */
  77307. gf2_matrix_square(odd, even);
  77308. if (len2 & 1)
  77309. crc1 = gf2_matrix_times(odd, crc1);
  77310. len2 >>= 1;
  77311. /* if no more bits set, then done */
  77312. } while (len2 != 0);
  77313. /* return combined crc */
  77314. crc1 ^= crc2;
  77315. return crc1;
  77316. }
  77317. /*** End of inlined file: crc32.c ***/
  77318. /*** Start of inlined file: deflate.c ***/
  77319. /*
  77320. * ALGORITHM
  77321. *
  77322. * The "deflation" process depends on being able to identify portions
  77323. * of the input text which are identical to earlier input (within a
  77324. * sliding window trailing behind the input currently being processed).
  77325. *
  77326. * The most straightforward technique turns out to be the fastest for
  77327. * most input files: try all possible matches and select the longest.
  77328. * The key feature of this algorithm is that insertions into the string
  77329. * dictionary are very simple and thus fast, and deletions are avoided
  77330. * completely. Insertions are performed at each input character, whereas
  77331. * string matches are performed only when the previous match ends. So it
  77332. * is preferable to spend more time in matches to allow very fast string
  77333. * insertions and avoid deletions. The matching algorithm for small
  77334. * strings is inspired from that of Rabin & Karp. A brute force approach
  77335. * is used to find longer strings when a small match has been found.
  77336. * A similar algorithm is used in comic (by Jan-Mark Wams) and freeze
  77337. * (by Leonid Broukhis).
  77338. * A previous version of this file used a more sophisticated algorithm
  77339. * (by Fiala and Greene) which is guaranteed to run in linear amortized
  77340. * time, but has a larger average cost, uses more memory and is patented.
  77341. * However the F&G algorithm may be faster for some highly redundant
  77342. * files if the parameter max_chain_length (described below) is too large.
  77343. *
  77344. * ACKNOWLEDGEMENTS
  77345. *
  77346. * The idea of lazy evaluation of matches is due to Jan-Mark Wams, and
  77347. * I found it in 'freeze' written by Leonid Broukhis.
  77348. * Thanks to many people for bug reports and testing.
  77349. *
  77350. * REFERENCES
  77351. *
  77352. * Deutsch, L.P.,"DEFLATE Compressed Data Format Specification".
  77353. * Available in http://www.ietf.org/rfc/rfc1951.txt
  77354. *
  77355. * A description of the Rabin and Karp algorithm is given in the book
  77356. * "Algorithms" by R. Sedgewick, Addison-Wesley, p252.
  77357. *
  77358. * Fiala,E.R., and Greene,D.H.
  77359. * Data Compression with Finite Windows, Comm.ACM, 32,4 (1989) 490-595
  77360. *
  77361. */
  77362. /* @(#) $Id: deflate.c,v 1.1 2007/06/07 17:54:37 jules_rms Exp $ */
  77363. /*** Start of inlined file: deflate.h ***/
  77364. /* WARNING: this file should *not* be used by applications. It is
  77365. part of the implementation of the compression library and is
  77366. subject to change. Applications should only use zlib.h.
  77367. */
  77368. /* @(#) $Id: deflate.h,v 1.1 2007/06/07 17:54:37 jules_rms Exp $ */
  77369. #ifndef DEFLATE_H
  77370. #define DEFLATE_H
  77371. /* define NO_GZIP when compiling if you want to disable gzip header and
  77372. trailer creation by deflate(). NO_GZIP would be used to avoid linking in
  77373. the crc code when it is not needed. For shared libraries, gzip encoding
  77374. should be left enabled. */
  77375. #ifndef NO_GZIP
  77376. # define GZIP
  77377. #endif
  77378. #define NO_DUMMY_DECL
  77379. /* ===========================================================================
  77380. * Internal compression state.
  77381. */
  77382. #define LENGTH_CODES 29
  77383. /* number of length codes, not counting the special END_BLOCK code */
  77384. #define LITERALS 256
  77385. /* number of literal bytes 0..255 */
  77386. #define L_CODES (LITERALS+1+LENGTH_CODES)
  77387. /* number of Literal or Length codes, including the END_BLOCK code */
  77388. #define D_CODES 30
  77389. /* number of distance codes */
  77390. #define BL_CODES 19
  77391. /* number of codes used to transfer the bit lengths */
  77392. #define HEAP_SIZE (2*L_CODES+1)
  77393. /* maximum heap size */
  77394. #define MAX_BITS 15
  77395. /* All codes must not exceed MAX_BITS bits */
  77396. #define INIT_STATE 42
  77397. #define EXTRA_STATE 69
  77398. #define NAME_STATE 73
  77399. #define COMMENT_STATE 91
  77400. #define HCRC_STATE 103
  77401. #define BUSY_STATE 113
  77402. #define FINISH_STATE 666
  77403. /* Stream status */
  77404. /* Data structure describing a single value and its code string. */
  77405. typedef struct ct_data_s {
  77406. union {
  77407. ush freq; /* frequency count */
  77408. ush code; /* bit string */
  77409. } fc;
  77410. union {
  77411. ush dad; /* father node in Huffman tree */
  77412. ush len; /* length of bit string */
  77413. } dl;
  77414. } FAR ct_data;
  77415. #define Freq fc.freq
  77416. #define Code fc.code
  77417. #define Dad dl.dad
  77418. #define Len dl.len
  77419. typedef struct static_tree_desc_s static_tree_desc;
  77420. typedef struct tree_desc_s {
  77421. ct_data *dyn_tree; /* the dynamic tree */
  77422. int max_code; /* largest code with non zero frequency */
  77423. static_tree_desc *stat_desc; /* the corresponding static tree */
  77424. } FAR tree_desc;
  77425. typedef ush Pos;
  77426. typedef Pos FAR Posf;
  77427. typedef unsigned IPos;
  77428. /* A Pos is an index in the character window. We use short instead of int to
  77429. * save space in the various tables. IPos is used only for parameter passing.
  77430. */
  77431. typedef struct internal_state {
  77432. z_streamp strm; /* pointer back to this zlib stream */
  77433. int status; /* as the name implies */
  77434. Bytef *pending_buf; /* output still pending */
  77435. ulg pending_buf_size; /* size of pending_buf */
  77436. Bytef *pending_out; /* next pending byte to output to the stream */
  77437. uInt pending; /* nb of bytes in the pending buffer */
  77438. int wrap; /* bit 0 true for zlib, bit 1 true for gzip */
  77439. gz_headerp gzhead; /* gzip header information to write */
  77440. uInt gzindex; /* where in extra, name, or comment */
  77441. Byte method; /* STORED (for zip only) or DEFLATED */
  77442. int last_flush; /* value of flush param for previous deflate call */
  77443. /* used by deflate.c: */
  77444. uInt w_size; /* LZ77 window size (32K by default) */
  77445. uInt w_bits; /* log2(w_size) (8..16) */
  77446. uInt w_mask; /* w_size - 1 */
  77447. Bytef *window;
  77448. /* Sliding window. Input bytes are read into the second half of the window,
  77449. * and move to the first half later to keep a dictionary of at least wSize
  77450. * bytes. With this organization, matches are limited to a distance of
  77451. * wSize-MAX_MATCH bytes, but this ensures that IO is always
  77452. * performed with a length multiple of the block size. Also, it limits
  77453. * the window size to 64K, which is quite useful on MSDOS.
  77454. * To do: use the user input buffer as sliding window.
  77455. */
  77456. ulg window_size;
  77457. /* Actual size of window: 2*wSize, except when the user input buffer
  77458. * is directly used as sliding window.
  77459. */
  77460. Posf *prev;
  77461. /* Link to older string with same hash index. To limit the size of this
  77462. * array to 64K, this link is maintained only for the last 32K strings.
  77463. * An index in this array is thus a window index modulo 32K.
  77464. */
  77465. Posf *head; /* Heads of the hash chains or NIL. */
  77466. uInt ins_h; /* hash index of string to be inserted */
  77467. uInt hash_size; /* number of elements in hash table */
  77468. uInt hash_bits; /* log2(hash_size) */
  77469. uInt hash_mask; /* hash_size-1 */
  77470. uInt hash_shift;
  77471. /* Number of bits by which ins_h must be shifted at each input
  77472. * step. It must be such that after MIN_MATCH steps, the oldest
  77473. * byte no longer takes part in the hash key, that is:
  77474. * hash_shift * MIN_MATCH >= hash_bits
  77475. */
  77476. long block_start;
  77477. /* Window position at the beginning of the current output block. Gets
  77478. * negative when the window is moved backwards.
  77479. */
  77480. uInt match_length; /* length of best match */
  77481. IPos prev_match; /* previous match */
  77482. int match_available; /* set if previous match exists */
  77483. uInt strstart; /* start of string to insert */
  77484. uInt match_start; /* start of matching string */
  77485. uInt lookahead; /* number of valid bytes ahead in window */
  77486. uInt prev_length;
  77487. /* Length of the best match at previous step. Matches not greater than this
  77488. * are discarded. This is used in the lazy match evaluation.
  77489. */
  77490. uInt max_chain_length;
  77491. /* To speed up deflation, hash chains are never searched beyond this
  77492. * length. A higher limit improves compression ratio but degrades the
  77493. * speed.
  77494. */
  77495. uInt max_lazy_match;
  77496. /* Attempt to find a better match only when the current match is strictly
  77497. * smaller than this value. This mechanism is used only for compression
  77498. * levels >= 4.
  77499. */
  77500. # define max_insert_length max_lazy_match
  77501. /* Insert new strings in the hash table only if the match length is not
  77502. * greater than this length. This saves time but degrades compression.
  77503. * max_insert_length is used only for compression levels <= 3.
  77504. */
  77505. int level; /* compression level (1..9) */
  77506. int strategy; /* favor or force Huffman coding*/
  77507. uInt good_match;
  77508. /* Use a faster search when the previous match is longer than this */
  77509. int nice_match; /* Stop searching when current match exceeds this */
  77510. /* used by trees.c: */
  77511. /* Didn't use ct_data typedef below to supress compiler warning */
  77512. struct ct_data_s dyn_ltree[HEAP_SIZE]; /* literal and length tree */
  77513. struct ct_data_s dyn_dtree[2*D_CODES+1]; /* distance tree */
  77514. struct ct_data_s bl_tree[2*BL_CODES+1]; /* Huffman tree for bit lengths */
  77515. struct tree_desc_s l_desc; /* desc. for literal tree */
  77516. struct tree_desc_s d_desc; /* desc. for distance tree */
  77517. struct tree_desc_s bl_desc; /* desc. for bit length tree */
  77518. ush bl_count[MAX_BITS+1];
  77519. /* number of codes at each bit length for an optimal tree */
  77520. int heap[2*L_CODES+1]; /* heap used to build the Huffman trees */
  77521. int heap_len; /* number of elements in the heap */
  77522. int heap_max; /* element of largest frequency */
  77523. /* The sons of heap[n] are heap[2*n] and heap[2*n+1]. heap[0] is not used.
  77524. * The same heap array is used to build all trees.
  77525. */
  77526. uch depth[2*L_CODES+1];
  77527. /* Depth of each subtree used as tie breaker for trees of equal frequency
  77528. */
  77529. uchf *l_buf; /* buffer for literals or lengths */
  77530. uInt lit_bufsize;
  77531. /* Size of match buffer for literals/lengths. There are 4 reasons for
  77532. * limiting lit_bufsize to 64K:
  77533. * - frequencies can be kept in 16 bit counters
  77534. * - if compression is not successful for the first block, all input
  77535. * data is still in the window so we can still emit a stored block even
  77536. * when input comes from standard input. (This can also be done for
  77537. * all blocks if lit_bufsize is not greater than 32K.)
  77538. * - if compression is not successful for a file smaller than 64K, we can
  77539. * even emit a stored file instead of a stored block (saving 5 bytes).
  77540. * This is applicable only for zip (not gzip or zlib).
  77541. * - creating new Huffman trees less frequently may not provide fast
  77542. * adaptation to changes in the input data statistics. (Take for
  77543. * example a binary file with poorly compressible code followed by
  77544. * a highly compressible string table.) Smaller buffer sizes give
  77545. * fast adaptation but have of course the overhead of transmitting
  77546. * trees more frequently.
  77547. * - I can't count above 4
  77548. */
  77549. uInt last_lit; /* running index in l_buf */
  77550. ushf *d_buf;
  77551. /* Buffer for distances. To simplify the code, d_buf and l_buf have
  77552. * the same number of elements. To use different lengths, an extra flag
  77553. * array would be necessary.
  77554. */
  77555. ulg opt_len; /* bit length of current block with optimal trees */
  77556. ulg static_len; /* bit length of current block with static trees */
  77557. uInt matches; /* number of string matches in current block */
  77558. int last_eob_len; /* bit length of EOB code for last block */
  77559. #ifdef DEBUG
  77560. ulg compressed_len; /* total bit length of compressed file mod 2^32 */
  77561. ulg bits_sent; /* bit length of compressed data sent mod 2^32 */
  77562. #endif
  77563. ush bi_buf;
  77564. /* Output buffer. bits are inserted starting at the bottom (least
  77565. * significant bits).
  77566. */
  77567. int bi_valid;
  77568. /* Number of valid bits in bi_buf. All bits above the last valid bit
  77569. * are always zero.
  77570. */
  77571. } FAR deflate_state;
  77572. /* Output a byte on the stream.
  77573. * IN assertion: there is enough room in pending_buf.
  77574. */
  77575. #define put_byte(s, c) {s->pending_buf[s->pending++] = (c);}
  77576. #define MIN_LOOKAHEAD (MAX_MATCH+MIN_MATCH+1)
  77577. /* Minimum amount of lookahead, except at the end of the input file.
  77578. * See deflate.c for comments about the MIN_MATCH+1.
  77579. */
  77580. #define MAX_DIST(s) ((s)->w_size-MIN_LOOKAHEAD)
  77581. /* In order to simplify the code, particularly on 16 bit machines, match
  77582. * distances are limited to MAX_DIST instead of WSIZE.
  77583. */
  77584. /* in trees.c */
  77585. void _tr_init OF((deflate_state *s));
  77586. int _tr_tally OF((deflate_state *s, unsigned dist, unsigned lc));
  77587. void _tr_flush_block OF((deflate_state *s, charf *buf, ulg stored_len,
  77588. int eof));
  77589. void _tr_align OF((deflate_state *s));
  77590. void _tr_stored_block OF((deflate_state *s, charf *buf, ulg stored_len,
  77591. int eof));
  77592. #define d_code(dist) \
  77593. ((dist) < 256 ? _dist_code[dist] : _dist_code[256+((dist)>>7)])
  77594. /* Mapping from a distance to a distance code. dist is the distance - 1 and
  77595. * must not have side effects. _dist_code[256] and _dist_code[257] are never
  77596. * used.
  77597. */
  77598. #ifndef DEBUG
  77599. /* Inline versions of _tr_tally for speed: */
  77600. #if defined(GEN_TREES_H) || !defined(STDC)
  77601. extern uch _length_code[];
  77602. extern uch _dist_code[];
  77603. #else
  77604. extern const uch _length_code[];
  77605. extern const uch _dist_code[];
  77606. #endif
  77607. # define _tr_tally_lit(s, c, flush) \
  77608. { uch cc = (c); \
  77609. s->d_buf[s->last_lit] = 0; \
  77610. s->l_buf[s->last_lit++] = cc; \
  77611. s->dyn_ltree[cc].Freq++; \
  77612. flush = (s->last_lit == s->lit_bufsize-1); \
  77613. }
  77614. # define _tr_tally_dist(s, distance, length, flush) \
  77615. { uch len = (length); \
  77616. ush dist = (distance); \
  77617. s->d_buf[s->last_lit] = dist; \
  77618. s->l_buf[s->last_lit++] = len; \
  77619. dist--; \
  77620. s->dyn_ltree[_length_code[len]+LITERALS+1].Freq++; \
  77621. s->dyn_dtree[d_code(dist)].Freq++; \
  77622. flush = (s->last_lit == s->lit_bufsize-1); \
  77623. }
  77624. #else
  77625. # define _tr_tally_lit(s, c, flush) flush = _tr_tally(s, 0, c)
  77626. # define _tr_tally_dist(s, distance, length, flush) \
  77627. flush = _tr_tally(s, distance, length)
  77628. #endif
  77629. #endif /* DEFLATE_H */
  77630. /*** End of inlined file: deflate.h ***/
  77631. const char deflate_copyright[] =
  77632. " deflate 1.2.3 Copyright 1995-2005 Jean-loup Gailly ";
  77633. /*
  77634. If you use the zlib library in a product, an acknowledgment is welcome
  77635. in the documentation of your product. If for some reason you cannot
  77636. include such an acknowledgment, I would appreciate that you keep this
  77637. copyright string in the executable of your product.
  77638. */
  77639. /* ===========================================================================
  77640. * Function prototypes.
  77641. */
  77642. typedef enum {
  77643. need_more, /* block not completed, need more input or more output */
  77644. block_done, /* block flush performed */
  77645. finish_started, /* finish started, need only more output at next deflate */
  77646. finish_done /* finish done, accept no more input or output */
  77647. } block_state;
  77648. typedef block_state (*compress_func) OF((deflate_state *s, int flush));
  77649. /* Compression function. Returns the block state after the call. */
  77650. local void fill_window OF((deflate_state *s));
  77651. local block_state deflate_stored OF((deflate_state *s, int flush));
  77652. local block_state deflate_fast OF((deflate_state *s, int flush));
  77653. #ifndef FASTEST
  77654. local block_state deflate_slow OF((deflate_state *s, int flush));
  77655. #endif
  77656. local void lm_init OF((deflate_state *s));
  77657. local void putShortMSB OF((deflate_state *s, uInt b));
  77658. local void flush_pending OF((z_streamp strm));
  77659. local int read_buf OF((z_streamp strm, Bytef *buf, unsigned size));
  77660. #ifndef FASTEST
  77661. #ifdef ASMV
  77662. void match_init OF((void)); /* asm code initialization */
  77663. uInt longest_match OF((deflate_state *s, IPos cur_match));
  77664. #else
  77665. local uInt longest_match OF((deflate_state *s, IPos cur_match));
  77666. #endif
  77667. #endif
  77668. local uInt longest_match_fast OF((deflate_state *s, IPos cur_match));
  77669. #ifdef DEBUG
  77670. local void check_match OF((deflate_state *s, IPos start, IPos match,
  77671. int length));
  77672. #endif
  77673. /* ===========================================================================
  77674. * Local data
  77675. */
  77676. #define NIL 0
  77677. /* Tail of hash chains */
  77678. #ifndef TOO_FAR
  77679. # define TOO_FAR 4096
  77680. #endif
  77681. /* Matches of length 3 are discarded if their distance exceeds TOO_FAR */
  77682. #define MIN_LOOKAHEAD (MAX_MATCH+MIN_MATCH+1)
  77683. /* Minimum amount of lookahead, except at the end of the input file.
  77684. * See deflate.c for comments about the MIN_MATCH+1.
  77685. */
  77686. /* Values for max_lazy_match, good_match and max_chain_length, depending on
  77687. * the desired pack level (0..9). The values given below have been tuned to
  77688. * exclude worst case performance for pathological files. Better values may be
  77689. * found for specific files.
  77690. */
  77691. typedef struct config_s {
  77692. ush good_length; /* reduce lazy search above this match length */
  77693. ush max_lazy; /* do not perform lazy search above this match length */
  77694. ush nice_length; /* quit search above this match length */
  77695. ush max_chain;
  77696. compress_func func;
  77697. } config;
  77698. #ifdef FASTEST
  77699. local const config configuration_table[2] = {
  77700. /* good lazy nice chain */
  77701. /* 0 */ {0, 0, 0, 0, deflate_stored}, /* store only */
  77702. /* 1 */ {4, 4, 8, 4, deflate_fast}}; /* max speed, no lazy matches */
  77703. #else
  77704. local const config configuration_table[10] = {
  77705. /* good lazy nice chain */
  77706. /* 0 */ {0, 0, 0, 0, deflate_stored}, /* store only */
  77707. /* 1 */ {4, 4, 8, 4, deflate_fast}, /* max speed, no lazy matches */
  77708. /* 2 */ {4, 5, 16, 8, deflate_fast},
  77709. /* 3 */ {4, 6, 32, 32, deflate_fast},
  77710. /* 4 */ {4, 4, 16, 16, deflate_slow}, /* lazy matches */
  77711. /* 5 */ {8, 16, 32, 32, deflate_slow},
  77712. /* 6 */ {8, 16, 128, 128, deflate_slow},
  77713. /* 7 */ {8, 32, 128, 256, deflate_slow},
  77714. /* 8 */ {32, 128, 258, 1024, deflate_slow},
  77715. /* 9 */ {32, 258, 258, 4096, deflate_slow}}; /* max compression */
  77716. #endif
  77717. /* Note: the deflate() code requires max_lazy >= MIN_MATCH and max_chain >= 4
  77718. * For deflate_fast() (levels <= 3) good is ignored and lazy has a different
  77719. * meaning.
  77720. */
  77721. #define EQUAL 0
  77722. /* result of memcmp for equal strings */
  77723. #ifndef NO_DUMMY_DECL
  77724. struct static_tree_desc_s {int dummy;}; /* for buggy compilers */
  77725. #endif
  77726. /* ===========================================================================
  77727. * Update a hash value with the given input byte
  77728. * IN assertion: all calls to to UPDATE_HASH are made with consecutive
  77729. * input characters, so that a running hash key can be computed from the
  77730. * previous key instead of complete recalculation each time.
  77731. */
  77732. #define UPDATE_HASH(s,h,c) (h = (((h)<<s->hash_shift) ^ (c)) & s->hash_mask)
  77733. /* ===========================================================================
  77734. * Insert string str in the dictionary and set match_head to the previous head
  77735. * of the hash chain (the most recent string with same hash key). Return
  77736. * the previous length of the hash chain.
  77737. * If this file is compiled with -DFASTEST, the compression level is forced
  77738. * to 1, and no hash chains are maintained.
  77739. * IN assertion: all calls to to INSERT_STRING are made with consecutive
  77740. * input characters and the first MIN_MATCH bytes of str are valid
  77741. * (except for the last MIN_MATCH-1 bytes of the input file).
  77742. */
  77743. #ifdef FASTEST
  77744. #define INSERT_STRING(s, str, match_head) \
  77745. (UPDATE_HASH(s, s->ins_h, s->window[(str) + (MIN_MATCH-1)]), \
  77746. match_head = s->head[s->ins_h], \
  77747. s->head[s->ins_h] = (Pos)(str))
  77748. #else
  77749. #define INSERT_STRING(s, str, match_head) \
  77750. (UPDATE_HASH(s, s->ins_h, s->window[(str) + (MIN_MATCH-1)]), \
  77751. match_head = s->prev[(str) & s->w_mask] = s->head[s->ins_h], \
  77752. s->head[s->ins_h] = (Pos)(str))
  77753. #endif
  77754. /* ===========================================================================
  77755. * Initialize the hash table (avoiding 64K overflow for 16 bit systems).
  77756. * prev[] will be initialized on the fly.
  77757. */
  77758. #define CLEAR_HASH(s) \
  77759. s->head[s->hash_size-1] = NIL; \
  77760. zmemzero((Bytef *)s->head, (unsigned)(s->hash_size-1)*sizeof(*s->head));
  77761. /* ========================================================================= */
  77762. int ZEXPORT deflateInit_(z_streamp strm, int level, const char *version, int stream_size)
  77763. {
  77764. return deflateInit2_(strm, level, Z_DEFLATED, MAX_WBITS, DEF_MEM_LEVEL,
  77765. Z_DEFAULT_STRATEGY, version, stream_size);
  77766. /* To do: ignore strm->next_in if we use it as window */
  77767. }
  77768. /* ========================================================================= */
  77769. int ZEXPORT deflateInit2_ (z_streamp strm, int level, int method, int windowBits, int memLevel, int strategy, const char *version, int stream_size)
  77770. {
  77771. deflate_state *s;
  77772. int wrap = 1;
  77773. static const char my_version[] = ZLIB_VERSION;
  77774. ushf *overlay;
  77775. /* We overlay pending_buf and d_buf+l_buf. This works since the average
  77776. * output size for (length,distance) codes is <= 24 bits.
  77777. */
  77778. if (version == Z_NULL || version[0] != my_version[0] ||
  77779. stream_size != sizeof(z_stream)) {
  77780. return Z_VERSION_ERROR;
  77781. }
  77782. if (strm == Z_NULL) return Z_STREAM_ERROR;
  77783. strm->msg = Z_NULL;
  77784. if (strm->zalloc == (alloc_func)0) {
  77785. strm->zalloc = zcalloc;
  77786. strm->opaque = (voidpf)0;
  77787. }
  77788. if (strm->zfree == (free_func)0) strm->zfree = zcfree;
  77789. #ifdef FASTEST
  77790. if (level != 0) level = 1;
  77791. #else
  77792. if (level == Z_DEFAULT_COMPRESSION) level = 6;
  77793. #endif
  77794. if (windowBits < 0) { /* suppress zlib wrapper */
  77795. wrap = 0;
  77796. windowBits = -windowBits;
  77797. }
  77798. #ifdef GZIP
  77799. else if (windowBits > 15) {
  77800. wrap = 2; /* write gzip wrapper instead */
  77801. windowBits -= 16;
  77802. }
  77803. #endif
  77804. if (memLevel < 1 || memLevel > MAX_MEM_LEVEL || method != Z_DEFLATED ||
  77805. windowBits < 8 || windowBits > 15 || level < 0 || level > 9 ||
  77806. strategy < 0 || strategy > Z_FIXED) {
  77807. return Z_STREAM_ERROR;
  77808. }
  77809. if (windowBits == 8) windowBits = 9; /* until 256-byte window bug fixed */
  77810. s = (deflate_state *) ZALLOC(strm, 1, sizeof(deflate_state));
  77811. if (s == Z_NULL) return Z_MEM_ERROR;
  77812. strm->state = (struct internal_state FAR *)s;
  77813. s->strm = strm;
  77814. s->wrap = wrap;
  77815. s->gzhead = Z_NULL;
  77816. s->w_bits = windowBits;
  77817. s->w_size = 1 << s->w_bits;
  77818. s->w_mask = s->w_size - 1;
  77819. s->hash_bits = memLevel + 7;
  77820. s->hash_size = 1 << s->hash_bits;
  77821. s->hash_mask = s->hash_size - 1;
  77822. s->hash_shift = ((s->hash_bits+MIN_MATCH-1)/MIN_MATCH);
  77823. s->window = (Bytef *) ZALLOC(strm, s->w_size, 2*sizeof(Byte));
  77824. s->prev = (Posf *) ZALLOC(strm, s->w_size, sizeof(Pos));
  77825. s->head = (Posf *) ZALLOC(strm, s->hash_size, sizeof(Pos));
  77826. s->lit_bufsize = 1 << (memLevel + 6); /* 16K elements by default */
  77827. overlay = (ushf *) ZALLOC(strm, s->lit_bufsize, sizeof(ush)+2);
  77828. s->pending_buf = (uchf *) overlay;
  77829. s->pending_buf_size = (ulg)s->lit_bufsize * (sizeof(ush)+2L);
  77830. if (s->window == Z_NULL || s->prev == Z_NULL || s->head == Z_NULL ||
  77831. s->pending_buf == Z_NULL) {
  77832. s->status = FINISH_STATE;
  77833. strm->msg = (char*)ERR_MSG(Z_MEM_ERROR);
  77834. deflateEnd (strm);
  77835. return Z_MEM_ERROR;
  77836. }
  77837. s->d_buf = overlay + s->lit_bufsize/sizeof(ush);
  77838. s->l_buf = s->pending_buf + (1+sizeof(ush))*s->lit_bufsize;
  77839. s->level = level;
  77840. s->strategy = strategy;
  77841. s->method = (Byte)method;
  77842. return deflateReset(strm);
  77843. }
  77844. /* ========================================================================= */
  77845. int ZEXPORT deflateSetDictionary (z_streamp strm, const Bytef *dictionary, uInt dictLength)
  77846. {
  77847. deflate_state *s;
  77848. uInt length = dictLength;
  77849. uInt n;
  77850. IPos hash_head = 0;
  77851. if (strm == Z_NULL || strm->state == Z_NULL || dictionary == Z_NULL ||
  77852. strm->state->wrap == 2 ||
  77853. (strm->state->wrap == 1 && strm->state->status != INIT_STATE))
  77854. return Z_STREAM_ERROR;
  77855. s = strm->state;
  77856. if (s->wrap)
  77857. strm->adler = adler32(strm->adler, dictionary, dictLength);
  77858. if (length < MIN_MATCH) return Z_OK;
  77859. if (length > MAX_DIST(s)) {
  77860. length = MAX_DIST(s);
  77861. dictionary += dictLength - length; /* use the tail of the dictionary */
  77862. }
  77863. zmemcpy(s->window, dictionary, length);
  77864. s->strstart = length;
  77865. s->block_start = (long)length;
  77866. /* Insert all strings in the hash table (except for the last two bytes).
  77867. * s->lookahead stays null, so s->ins_h will be recomputed at the next
  77868. * call of fill_window.
  77869. */
  77870. s->ins_h = s->window[0];
  77871. UPDATE_HASH(s, s->ins_h, s->window[1]);
  77872. for (n = 0; n <= length - MIN_MATCH; n++) {
  77873. INSERT_STRING(s, n, hash_head);
  77874. }
  77875. if (hash_head) hash_head = 0; /* to make compiler happy */
  77876. return Z_OK;
  77877. }
  77878. /* ========================================================================= */
  77879. int ZEXPORT deflateReset (z_streamp strm)
  77880. {
  77881. deflate_state *s;
  77882. if (strm == Z_NULL || strm->state == Z_NULL ||
  77883. strm->zalloc == (alloc_func)0 || strm->zfree == (free_func)0) {
  77884. return Z_STREAM_ERROR;
  77885. }
  77886. strm->total_in = strm->total_out = 0;
  77887. strm->msg = Z_NULL; /* use zfree if we ever allocate msg dynamically */
  77888. strm->data_type = Z_UNKNOWN;
  77889. s = (deflate_state *)strm->state;
  77890. s->pending = 0;
  77891. s->pending_out = s->pending_buf;
  77892. if (s->wrap < 0) {
  77893. s->wrap = -s->wrap; /* was made negative by deflate(..., Z_FINISH); */
  77894. }
  77895. s->status = s->wrap ? INIT_STATE : BUSY_STATE;
  77896. strm->adler =
  77897. #ifdef GZIP
  77898. s->wrap == 2 ? crc32(0L, Z_NULL, 0) :
  77899. #endif
  77900. adler32(0L, Z_NULL, 0);
  77901. s->last_flush = Z_NO_FLUSH;
  77902. _tr_init(s);
  77903. lm_init(s);
  77904. return Z_OK;
  77905. }
  77906. /* ========================================================================= */
  77907. int ZEXPORT deflateSetHeader (z_streamp strm, gz_headerp head)
  77908. {
  77909. if (strm == Z_NULL || strm->state == Z_NULL) return Z_STREAM_ERROR;
  77910. if (strm->state->wrap != 2) return Z_STREAM_ERROR;
  77911. strm->state->gzhead = head;
  77912. return Z_OK;
  77913. }
  77914. /* ========================================================================= */
  77915. int ZEXPORT deflatePrime (z_streamp strm, int bits, int value)
  77916. {
  77917. if (strm == Z_NULL || strm->state == Z_NULL) return Z_STREAM_ERROR;
  77918. strm->state->bi_valid = bits;
  77919. strm->state->bi_buf = (ush)(value & ((1 << bits) - 1));
  77920. return Z_OK;
  77921. }
  77922. /* ========================================================================= */
  77923. int ZEXPORT deflateParams (z_streamp strm, int level, int strategy)
  77924. {
  77925. deflate_state *s;
  77926. compress_func func;
  77927. int err = Z_OK;
  77928. if (strm == Z_NULL || strm->state == Z_NULL) return Z_STREAM_ERROR;
  77929. s = strm->state;
  77930. #ifdef FASTEST
  77931. if (level != 0) level = 1;
  77932. #else
  77933. if (level == Z_DEFAULT_COMPRESSION) level = 6;
  77934. #endif
  77935. if (level < 0 || level > 9 || strategy < 0 || strategy > Z_FIXED) {
  77936. return Z_STREAM_ERROR;
  77937. }
  77938. func = configuration_table[s->level].func;
  77939. if (func != configuration_table[level].func && strm->total_in != 0) {
  77940. /* Flush the last buffer: */
  77941. err = deflate(strm, Z_PARTIAL_FLUSH);
  77942. }
  77943. if (s->level != level) {
  77944. s->level = level;
  77945. s->max_lazy_match = configuration_table[level].max_lazy;
  77946. s->good_match = configuration_table[level].good_length;
  77947. s->nice_match = configuration_table[level].nice_length;
  77948. s->max_chain_length = configuration_table[level].max_chain;
  77949. }
  77950. s->strategy = strategy;
  77951. return err;
  77952. }
  77953. /* ========================================================================= */
  77954. int ZEXPORT deflateTune (z_streamp strm, int good_length, int max_lazy, int nice_length, int max_chain)
  77955. {
  77956. deflate_state *s;
  77957. if (strm == Z_NULL || strm->state == Z_NULL) return Z_STREAM_ERROR;
  77958. s = strm->state;
  77959. s->good_match = good_length;
  77960. s->max_lazy_match = max_lazy;
  77961. s->nice_match = nice_length;
  77962. s->max_chain_length = max_chain;
  77963. return Z_OK;
  77964. }
  77965. /* =========================================================================
  77966. * For the default windowBits of 15 and memLevel of 8, this function returns
  77967. * a close to exact, as well as small, upper bound on the compressed size.
  77968. * They are coded as constants here for a reason--if the #define's are
  77969. * changed, then this function needs to be changed as well. The return
  77970. * value for 15 and 8 only works for those exact settings.
  77971. *
  77972. * For any setting other than those defaults for windowBits and memLevel,
  77973. * the value returned is a conservative worst case for the maximum expansion
  77974. * resulting from using fixed blocks instead of stored blocks, which deflate
  77975. * can emit on compressed data for some combinations of the parameters.
  77976. *
  77977. * This function could be more sophisticated to provide closer upper bounds
  77978. * for every combination of windowBits and memLevel, as well as wrap.
  77979. * But even the conservative upper bound of about 14% expansion does not
  77980. * seem onerous for output buffer allocation.
  77981. */
  77982. uLong ZEXPORT deflateBound (z_streamp strm, uLong sourceLen)
  77983. {
  77984. deflate_state *s;
  77985. uLong destLen;
  77986. /* conservative upper bound */
  77987. destLen = sourceLen +
  77988. ((sourceLen + 7) >> 3) + ((sourceLen + 63) >> 6) + 11;
  77989. /* if can't get parameters, return conservative bound */
  77990. if (strm == Z_NULL || strm->state == Z_NULL)
  77991. return destLen;
  77992. /* if not default parameters, return conservative bound */
  77993. s = strm->state;
  77994. if (s->w_bits != 15 || s->hash_bits != 8 + 7)
  77995. return destLen;
  77996. /* default settings: return tight bound for that case */
  77997. return compressBound(sourceLen);
  77998. }
  77999. /* =========================================================================
  78000. * Put a short in the pending buffer. The 16-bit value is put in MSB order.
  78001. * IN assertion: the stream state is correct and there is enough room in
  78002. * pending_buf.
  78003. */
  78004. local void putShortMSB (deflate_state *s, uInt b)
  78005. {
  78006. put_byte(s, (Byte)(b >> 8));
  78007. put_byte(s, (Byte)(b & 0xff));
  78008. }
  78009. /* =========================================================================
  78010. * Flush as much pending output as possible. All deflate() output goes
  78011. * through this function so some applications may wish to modify it
  78012. * to avoid allocating a large strm->next_out buffer and copying into it.
  78013. * (See also read_buf()).
  78014. */
  78015. local void flush_pending (z_streamp strm)
  78016. {
  78017. unsigned len = strm->state->pending;
  78018. if (len > strm->avail_out) len = strm->avail_out;
  78019. if (len == 0) return;
  78020. zmemcpy(strm->next_out, strm->state->pending_out, len);
  78021. strm->next_out += len;
  78022. strm->state->pending_out += len;
  78023. strm->total_out += len;
  78024. strm->avail_out -= len;
  78025. strm->state->pending -= len;
  78026. if (strm->state->pending == 0) {
  78027. strm->state->pending_out = strm->state->pending_buf;
  78028. }
  78029. }
  78030. /* ========================================================================= */
  78031. int ZEXPORT deflate (z_streamp strm, int flush)
  78032. {
  78033. int old_flush; /* value of flush param for previous deflate call */
  78034. deflate_state *s;
  78035. if (strm == Z_NULL || strm->state == Z_NULL ||
  78036. flush > Z_FINISH || flush < 0) {
  78037. return Z_STREAM_ERROR;
  78038. }
  78039. s = strm->state;
  78040. if (strm->next_out == Z_NULL ||
  78041. (strm->next_in == Z_NULL && strm->avail_in != 0) ||
  78042. (s->status == FINISH_STATE && flush != Z_FINISH)) {
  78043. ERR_RETURN(strm, Z_STREAM_ERROR);
  78044. }
  78045. if (strm->avail_out == 0) ERR_RETURN(strm, Z_BUF_ERROR);
  78046. s->strm = strm; /* just in case */
  78047. old_flush = s->last_flush;
  78048. s->last_flush = flush;
  78049. /* Write the header */
  78050. if (s->status == INIT_STATE) {
  78051. #ifdef GZIP
  78052. if (s->wrap == 2) {
  78053. strm->adler = crc32(0L, Z_NULL, 0);
  78054. put_byte(s, 31);
  78055. put_byte(s, 139);
  78056. put_byte(s, 8);
  78057. if (s->gzhead == NULL) {
  78058. put_byte(s, 0);
  78059. put_byte(s, 0);
  78060. put_byte(s, 0);
  78061. put_byte(s, 0);
  78062. put_byte(s, 0);
  78063. put_byte(s, s->level == 9 ? 2 :
  78064. (s->strategy >= Z_HUFFMAN_ONLY || s->level < 2 ?
  78065. 4 : 0));
  78066. put_byte(s, OS_CODE);
  78067. s->status = BUSY_STATE;
  78068. }
  78069. else {
  78070. put_byte(s, (s->gzhead->text ? 1 : 0) +
  78071. (s->gzhead->hcrc ? 2 : 0) +
  78072. (s->gzhead->extra == Z_NULL ? 0 : 4) +
  78073. (s->gzhead->name == Z_NULL ? 0 : 8) +
  78074. (s->gzhead->comment == Z_NULL ? 0 : 16)
  78075. );
  78076. put_byte(s, (Byte)(s->gzhead->time & 0xff));
  78077. put_byte(s, (Byte)((s->gzhead->time >> 8) & 0xff));
  78078. put_byte(s, (Byte)((s->gzhead->time >> 16) & 0xff));
  78079. put_byte(s, (Byte)((s->gzhead->time >> 24) & 0xff));
  78080. put_byte(s, s->level == 9 ? 2 :
  78081. (s->strategy >= Z_HUFFMAN_ONLY || s->level < 2 ?
  78082. 4 : 0));
  78083. put_byte(s, s->gzhead->os & 0xff);
  78084. if (s->gzhead->extra != NULL) {
  78085. put_byte(s, s->gzhead->extra_len & 0xff);
  78086. put_byte(s, (s->gzhead->extra_len >> 8) & 0xff);
  78087. }
  78088. if (s->gzhead->hcrc)
  78089. strm->adler = crc32(strm->adler, s->pending_buf,
  78090. s->pending);
  78091. s->gzindex = 0;
  78092. s->status = EXTRA_STATE;
  78093. }
  78094. }
  78095. else
  78096. #endif
  78097. {
  78098. uInt header = (Z_DEFLATED + ((s->w_bits-8)<<4)) << 8;
  78099. uInt level_flags;
  78100. if (s->strategy >= Z_HUFFMAN_ONLY || s->level < 2)
  78101. level_flags = 0;
  78102. else if (s->level < 6)
  78103. level_flags = 1;
  78104. else if (s->level == 6)
  78105. level_flags = 2;
  78106. else
  78107. level_flags = 3;
  78108. header |= (level_flags << 6);
  78109. if (s->strstart != 0) header |= PRESET_DICT;
  78110. header += 31 - (header % 31);
  78111. s->status = BUSY_STATE;
  78112. putShortMSB(s, header);
  78113. /* Save the adler32 of the preset dictionary: */
  78114. if (s->strstart != 0) {
  78115. putShortMSB(s, (uInt)(strm->adler >> 16));
  78116. putShortMSB(s, (uInt)(strm->adler & 0xffff));
  78117. }
  78118. strm->adler = adler32(0L, Z_NULL, 0);
  78119. }
  78120. }
  78121. #ifdef GZIP
  78122. if (s->status == EXTRA_STATE) {
  78123. if (s->gzhead->extra != NULL) {
  78124. uInt beg = s->pending; /* start of bytes to update crc */
  78125. while (s->gzindex < (s->gzhead->extra_len & 0xffff)) {
  78126. if (s->pending == s->pending_buf_size) {
  78127. if (s->gzhead->hcrc && s->pending > beg)
  78128. strm->adler = crc32(strm->adler, s->pending_buf + beg,
  78129. s->pending - beg);
  78130. flush_pending(strm);
  78131. beg = s->pending;
  78132. if (s->pending == s->pending_buf_size)
  78133. break;
  78134. }
  78135. put_byte(s, s->gzhead->extra[s->gzindex]);
  78136. s->gzindex++;
  78137. }
  78138. if (s->gzhead->hcrc && s->pending > beg)
  78139. strm->adler = crc32(strm->adler, s->pending_buf + beg,
  78140. s->pending - beg);
  78141. if (s->gzindex == s->gzhead->extra_len) {
  78142. s->gzindex = 0;
  78143. s->status = NAME_STATE;
  78144. }
  78145. }
  78146. else
  78147. s->status = NAME_STATE;
  78148. }
  78149. if (s->status == NAME_STATE) {
  78150. if (s->gzhead->name != NULL) {
  78151. uInt beg = s->pending; /* start of bytes to update crc */
  78152. int val;
  78153. do {
  78154. if (s->pending == s->pending_buf_size) {
  78155. if (s->gzhead->hcrc && s->pending > beg)
  78156. strm->adler = crc32(strm->adler, s->pending_buf + beg,
  78157. s->pending - beg);
  78158. flush_pending(strm);
  78159. beg = s->pending;
  78160. if (s->pending == s->pending_buf_size) {
  78161. val = 1;
  78162. break;
  78163. }
  78164. }
  78165. val = s->gzhead->name[s->gzindex++];
  78166. put_byte(s, val);
  78167. } while (val != 0);
  78168. if (s->gzhead->hcrc && s->pending > beg)
  78169. strm->adler = crc32(strm->adler, s->pending_buf + beg,
  78170. s->pending - beg);
  78171. if (val == 0) {
  78172. s->gzindex = 0;
  78173. s->status = COMMENT_STATE;
  78174. }
  78175. }
  78176. else
  78177. s->status = COMMENT_STATE;
  78178. }
  78179. if (s->status == COMMENT_STATE) {
  78180. if (s->gzhead->comment != NULL) {
  78181. uInt beg = s->pending; /* start of bytes to update crc */
  78182. int val;
  78183. do {
  78184. if (s->pending == s->pending_buf_size) {
  78185. if (s->gzhead->hcrc && s->pending > beg)
  78186. strm->adler = crc32(strm->adler, s->pending_buf + beg,
  78187. s->pending - beg);
  78188. flush_pending(strm);
  78189. beg = s->pending;
  78190. if (s->pending == s->pending_buf_size) {
  78191. val = 1;
  78192. break;
  78193. }
  78194. }
  78195. val = s->gzhead->comment[s->gzindex++];
  78196. put_byte(s, val);
  78197. } while (val != 0);
  78198. if (s->gzhead->hcrc && s->pending > beg)
  78199. strm->adler = crc32(strm->adler, s->pending_buf + beg,
  78200. s->pending - beg);
  78201. if (val == 0)
  78202. s->status = HCRC_STATE;
  78203. }
  78204. else
  78205. s->status = HCRC_STATE;
  78206. }
  78207. if (s->status == HCRC_STATE) {
  78208. if (s->gzhead->hcrc) {
  78209. if (s->pending + 2 > s->pending_buf_size)
  78210. flush_pending(strm);
  78211. if (s->pending + 2 <= s->pending_buf_size) {
  78212. put_byte(s, (Byte)(strm->adler & 0xff));
  78213. put_byte(s, (Byte)((strm->adler >> 8) & 0xff));
  78214. strm->adler = crc32(0L, Z_NULL, 0);
  78215. s->status = BUSY_STATE;
  78216. }
  78217. }
  78218. else
  78219. s->status = BUSY_STATE;
  78220. }
  78221. #endif
  78222. /* Flush as much pending output as possible */
  78223. if (s->pending != 0) {
  78224. flush_pending(strm);
  78225. if (strm->avail_out == 0) {
  78226. /* Since avail_out is 0, deflate will be called again with
  78227. * more output space, but possibly with both pending and
  78228. * avail_in equal to zero. There won't be anything to do,
  78229. * but this is not an error situation so make sure we
  78230. * return OK instead of BUF_ERROR at next call of deflate:
  78231. */
  78232. s->last_flush = -1;
  78233. return Z_OK;
  78234. }
  78235. /* Make sure there is something to do and avoid duplicate consecutive
  78236. * flushes. For repeated and useless calls with Z_FINISH, we keep
  78237. * returning Z_STREAM_END instead of Z_BUF_ERROR.
  78238. */
  78239. } else if (strm->avail_in == 0 && flush <= old_flush &&
  78240. flush != Z_FINISH) {
  78241. ERR_RETURN(strm, Z_BUF_ERROR);
  78242. }
  78243. /* User must not provide more input after the first FINISH: */
  78244. if (s->status == FINISH_STATE && strm->avail_in != 0) {
  78245. ERR_RETURN(strm, Z_BUF_ERROR);
  78246. }
  78247. /* Start a new block or continue the current one.
  78248. */
  78249. if (strm->avail_in != 0 || s->lookahead != 0 ||
  78250. (flush != Z_NO_FLUSH && s->status != FINISH_STATE)) {
  78251. block_state bstate;
  78252. bstate = (*(configuration_table[s->level].func))(s, flush);
  78253. if (bstate == finish_started || bstate == finish_done) {
  78254. s->status = FINISH_STATE;
  78255. }
  78256. if (bstate == need_more || bstate == finish_started) {
  78257. if (strm->avail_out == 0) {
  78258. s->last_flush = -1; /* avoid BUF_ERROR next call, see above */
  78259. }
  78260. return Z_OK;
  78261. /* If flush != Z_NO_FLUSH && avail_out == 0, the next call
  78262. * of deflate should use the same flush parameter to make sure
  78263. * that the flush is complete. So we don't have to output an
  78264. * empty block here, this will be done at next call. This also
  78265. * ensures that for a very small output buffer, we emit at most
  78266. * one empty block.
  78267. */
  78268. }
  78269. if (bstate == block_done) {
  78270. if (flush == Z_PARTIAL_FLUSH) {
  78271. _tr_align(s);
  78272. } else { /* FULL_FLUSH or SYNC_FLUSH */
  78273. _tr_stored_block(s, (char*)0, 0L, 0);
  78274. /* For a full flush, this empty block will be recognized
  78275. * as a special marker by inflate_sync().
  78276. */
  78277. if (flush == Z_FULL_FLUSH) {
  78278. CLEAR_HASH(s); /* forget history */
  78279. }
  78280. }
  78281. flush_pending(strm);
  78282. if (strm->avail_out == 0) {
  78283. s->last_flush = -1; /* avoid BUF_ERROR at next call, see above */
  78284. return Z_OK;
  78285. }
  78286. }
  78287. }
  78288. Assert(strm->avail_out > 0, "bug2");
  78289. if (flush != Z_FINISH) return Z_OK;
  78290. if (s->wrap <= 0) return Z_STREAM_END;
  78291. /* Write the trailer */
  78292. #ifdef GZIP
  78293. if (s->wrap == 2) {
  78294. put_byte(s, (Byte)(strm->adler & 0xff));
  78295. put_byte(s, (Byte)((strm->adler >> 8) & 0xff));
  78296. put_byte(s, (Byte)((strm->adler >> 16) & 0xff));
  78297. put_byte(s, (Byte)((strm->adler >> 24) & 0xff));
  78298. put_byte(s, (Byte)(strm->total_in & 0xff));
  78299. put_byte(s, (Byte)((strm->total_in >> 8) & 0xff));
  78300. put_byte(s, (Byte)((strm->total_in >> 16) & 0xff));
  78301. put_byte(s, (Byte)((strm->total_in >> 24) & 0xff));
  78302. }
  78303. else
  78304. #endif
  78305. {
  78306. putShortMSB(s, (uInt)(strm->adler >> 16));
  78307. putShortMSB(s, (uInt)(strm->adler & 0xffff));
  78308. }
  78309. flush_pending(strm);
  78310. /* If avail_out is zero, the application will call deflate again
  78311. * to flush the rest.
  78312. */
  78313. if (s->wrap > 0) s->wrap = -s->wrap; /* write the trailer only once! */
  78314. return s->pending != 0 ? Z_OK : Z_STREAM_END;
  78315. }
  78316. /* ========================================================================= */
  78317. int ZEXPORT deflateEnd (z_streamp strm)
  78318. {
  78319. int status;
  78320. if (strm == Z_NULL || strm->state == Z_NULL) return Z_STREAM_ERROR;
  78321. status = strm->state->status;
  78322. if (status != INIT_STATE &&
  78323. status != EXTRA_STATE &&
  78324. status != NAME_STATE &&
  78325. status != COMMENT_STATE &&
  78326. status != HCRC_STATE &&
  78327. status != BUSY_STATE &&
  78328. status != FINISH_STATE) {
  78329. return Z_STREAM_ERROR;
  78330. }
  78331. /* Deallocate in reverse order of allocations: */
  78332. TRY_FREE(strm, strm->state->pending_buf);
  78333. TRY_FREE(strm, strm->state->head);
  78334. TRY_FREE(strm, strm->state->prev);
  78335. TRY_FREE(strm, strm->state->window);
  78336. ZFREE(strm, strm->state);
  78337. strm->state = Z_NULL;
  78338. return status == BUSY_STATE ? Z_DATA_ERROR : Z_OK;
  78339. }
  78340. /* =========================================================================
  78341. * Copy the source state to the destination state.
  78342. * To simplify the source, this is not supported for 16-bit MSDOS (which
  78343. * doesn't have enough memory anyway to duplicate compression states).
  78344. */
  78345. int ZEXPORT deflateCopy (z_streamp dest, z_streamp source)
  78346. {
  78347. #ifdef MAXSEG_64K
  78348. return Z_STREAM_ERROR;
  78349. #else
  78350. deflate_state *ds;
  78351. deflate_state *ss;
  78352. ushf *overlay;
  78353. if (source == Z_NULL || dest == Z_NULL || source->state == Z_NULL) {
  78354. return Z_STREAM_ERROR;
  78355. }
  78356. ss = source->state;
  78357. zmemcpy(dest, source, sizeof(z_stream));
  78358. ds = (deflate_state *) ZALLOC(dest, 1, sizeof(deflate_state));
  78359. if (ds == Z_NULL) return Z_MEM_ERROR;
  78360. dest->state = (struct internal_state FAR *) ds;
  78361. zmemcpy(ds, ss, sizeof(deflate_state));
  78362. ds->strm = dest;
  78363. ds->window = (Bytef *) ZALLOC(dest, ds->w_size, 2*sizeof(Byte));
  78364. ds->prev = (Posf *) ZALLOC(dest, ds->w_size, sizeof(Pos));
  78365. ds->head = (Posf *) ZALLOC(dest, ds->hash_size, sizeof(Pos));
  78366. overlay = (ushf *) ZALLOC(dest, ds->lit_bufsize, sizeof(ush)+2);
  78367. ds->pending_buf = (uchf *) overlay;
  78368. if (ds->window == Z_NULL || ds->prev == Z_NULL || ds->head == Z_NULL ||
  78369. ds->pending_buf == Z_NULL) {
  78370. deflateEnd (dest);
  78371. return Z_MEM_ERROR;
  78372. }
  78373. /* following zmemcpy do not work for 16-bit MSDOS */
  78374. zmemcpy(ds->window, ss->window, ds->w_size * 2 * sizeof(Byte));
  78375. zmemcpy(ds->prev, ss->prev, ds->w_size * sizeof(Pos));
  78376. zmemcpy(ds->head, ss->head, ds->hash_size * sizeof(Pos));
  78377. zmemcpy(ds->pending_buf, ss->pending_buf, (uInt)ds->pending_buf_size);
  78378. ds->pending_out = ds->pending_buf + (ss->pending_out - ss->pending_buf);
  78379. ds->d_buf = overlay + ds->lit_bufsize/sizeof(ush);
  78380. ds->l_buf = ds->pending_buf + (1+sizeof(ush))*ds->lit_bufsize;
  78381. ds->l_desc.dyn_tree = ds->dyn_ltree;
  78382. ds->d_desc.dyn_tree = ds->dyn_dtree;
  78383. ds->bl_desc.dyn_tree = ds->bl_tree;
  78384. return Z_OK;
  78385. #endif /* MAXSEG_64K */
  78386. }
  78387. /* ===========================================================================
  78388. * Read a new buffer from the current input stream, update the adler32
  78389. * and total number of bytes read. All deflate() input goes through
  78390. * this function so some applications may wish to modify it to avoid
  78391. * allocating a large strm->next_in buffer and copying from it.
  78392. * (See also flush_pending()).
  78393. */
  78394. local int read_buf (z_streamp strm, Bytef *buf, unsigned size)
  78395. {
  78396. unsigned len = strm->avail_in;
  78397. if (len > size) len = size;
  78398. if (len == 0) return 0;
  78399. strm->avail_in -= len;
  78400. if (strm->state->wrap == 1) {
  78401. strm->adler = adler32(strm->adler, strm->next_in, len);
  78402. }
  78403. #ifdef GZIP
  78404. else if (strm->state->wrap == 2) {
  78405. strm->adler = crc32(strm->adler, strm->next_in, len);
  78406. }
  78407. #endif
  78408. zmemcpy(buf, strm->next_in, len);
  78409. strm->next_in += len;
  78410. strm->total_in += len;
  78411. return (int)len;
  78412. }
  78413. /* ===========================================================================
  78414. * Initialize the "longest match" routines for a new zlib stream
  78415. */
  78416. local void lm_init (deflate_state *s)
  78417. {
  78418. s->window_size = (ulg)2L*s->w_size;
  78419. CLEAR_HASH(s);
  78420. /* Set the default configuration parameters:
  78421. */
  78422. s->max_lazy_match = configuration_table[s->level].max_lazy;
  78423. s->good_match = configuration_table[s->level].good_length;
  78424. s->nice_match = configuration_table[s->level].nice_length;
  78425. s->max_chain_length = configuration_table[s->level].max_chain;
  78426. s->strstart = 0;
  78427. s->block_start = 0L;
  78428. s->lookahead = 0;
  78429. s->match_length = s->prev_length = MIN_MATCH-1;
  78430. s->match_available = 0;
  78431. s->ins_h = 0;
  78432. #ifndef FASTEST
  78433. #ifdef ASMV
  78434. match_init(); /* initialize the asm code */
  78435. #endif
  78436. #endif
  78437. }
  78438. #ifndef FASTEST
  78439. /* ===========================================================================
  78440. * Set match_start to the longest match starting at the given string and
  78441. * return its length. Matches shorter or equal to prev_length are discarded,
  78442. * in which case the result is equal to prev_length and match_start is
  78443. * garbage.
  78444. * IN assertions: cur_match is the head of the hash chain for the current
  78445. * string (strstart) and its distance is <= MAX_DIST, and prev_length >= 1
  78446. * OUT assertion: the match length is not greater than s->lookahead.
  78447. */
  78448. #ifndef ASMV
  78449. /* For 80x86 and 680x0, an optimized version will be provided in match.asm or
  78450. * match.S. The code will be functionally equivalent.
  78451. */
  78452. local uInt longest_match(deflate_state *s, IPos cur_match)
  78453. {
  78454. unsigned chain_length = s->max_chain_length;/* max hash chain length */
  78455. register Bytef *scan = s->window + s->strstart; /* current string */
  78456. register Bytef *match; /* matched string */
  78457. register int len; /* length of current match */
  78458. int best_len = s->prev_length; /* best match length so far */
  78459. int nice_match = s->nice_match; /* stop if match long enough */
  78460. IPos limit = s->strstart > (IPos)MAX_DIST(s) ?
  78461. s->strstart - (IPos)MAX_DIST(s) : NIL;
  78462. /* Stop when cur_match becomes <= limit. To simplify the code,
  78463. * we prevent matches with the string of window index 0.
  78464. */
  78465. Posf *prev = s->prev;
  78466. uInt wmask = s->w_mask;
  78467. #ifdef UNALIGNED_OK
  78468. /* Compare two bytes at a time. Note: this is not always beneficial.
  78469. * Try with and without -DUNALIGNED_OK to check.
  78470. */
  78471. register Bytef *strend = s->window + s->strstart + MAX_MATCH - 1;
  78472. register ush scan_start = *(ushf*)scan;
  78473. register ush scan_end = *(ushf*)(scan+best_len-1);
  78474. #else
  78475. register Bytef *strend = s->window + s->strstart + MAX_MATCH;
  78476. register Byte scan_end1 = scan[best_len-1];
  78477. register Byte scan_end = scan[best_len];
  78478. #endif
  78479. /* The code is optimized for HASH_BITS >= 8 and MAX_MATCH-2 multiple of 16.
  78480. * It is easy to get rid of this optimization if necessary.
  78481. */
  78482. Assert(s->hash_bits >= 8 && MAX_MATCH == 258, "Code too clever");
  78483. /* Do not waste too much time if we already have a good match: */
  78484. if (s->prev_length >= s->good_match) {
  78485. chain_length >>= 2;
  78486. }
  78487. /* Do not look for matches beyond the end of the input. This is necessary
  78488. * to make deflate deterministic.
  78489. */
  78490. if ((uInt)nice_match > s->lookahead) nice_match = s->lookahead;
  78491. Assert((ulg)s->strstart <= s->window_size-MIN_LOOKAHEAD, "need lookahead");
  78492. do {
  78493. Assert(cur_match < s->strstart, "no future");
  78494. match = s->window + cur_match;
  78495. /* Skip to next match if the match length cannot increase
  78496. * or if the match length is less than 2. Note that the checks below
  78497. * for insufficient lookahead only occur occasionally for performance
  78498. * reasons. Therefore uninitialized memory will be accessed, and
  78499. * conditional jumps will be made that depend on those values.
  78500. * However the length of the match is limited to the lookahead, so
  78501. * the output of deflate is not affected by the uninitialized values.
  78502. */
  78503. #if (defined(UNALIGNED_OK) && MAX_MATCH == 258)
  78504. /* This code assumes sizeof(unsigned short) == 2. Do not use
  78505. * UNALIGNED_OK if your compiler uses a different size.
  78506. */
  78507. if (*(ushf*)(match+best_len-1) != scan_end ||
  78508. *(ushf*)match != scan_start) continue;
  78509. /* It is not necessary to compare scan[2] and match[2] since they are
  78510. * always equal when the other bytes match, given that the hash keys
  78511. * are equal and that HASH_BITS >= 8. Compare 2 bytes at a time at
  78512. * strstart+3, +5, ... up to strstart+257. We check for insufficient
  78513. * lookahead only every 4th comparison; the 128th check will be made
  78514. * at strstart+257. If MAX_MATCH-2 is not a multiple of 8, it is
  78515. * necessary to put more guard bytes at the end of the window, or
  78516. * to check more often for insufficient lookahead.
  78517. */
  78518. Assert(scan[2] == match[2], "scan[2]?");
  78519. scan++, match++;
  78520. do {
  78521. } while (*(ushf*)(scan+=2) == *(ushf*)(match+=2) &&
  78522. *(ushf*)(scan+=2) == *(ushf*)(match+=2) &&
  78523. *(ushf*)(scan+=2) == *(ushf*)(match+=2) &&
  78524. *(ushf*)(scan+=2) == *(ushf*)(match+=2) &&
  78525. scan < strend);
  78526. /* The funny "do {}" generates better code on most compilers */
  78527. /* Here, scan <= window+strstart+257 */
  78528. Assert(scan <= s->window+(unsigned)(s->window_size-1), "wild scan");
  78529. if (*scan == *match) scan++;
  78530. len = (MAX_MATCH - 1) - (int)(strend-scan);
  78531. scan = strend - (MAX_MATCH-1);
  78532. #else /* UNALIGNED_OK */
  78533. if (match[best_len] != scan_end ||
  78534. match[best_len-1] != scan_end1 ||
  78535. *match != *scan ||
  78536. *++match != scan[1]) continue;
  78537. /* The check at best_len-1 can be removed because it will be made
  78538. * again later. (This heuristic is not always a win.)
  78539. * It is not necessary to compare scan[2] and match[2] since they
  78540. * are always equal when the other bytes match, given that
  78541. * the hash keys are equal and that HASH_BITS >= 8.
  78542. */
  78543. scan += 2, match++;
  78544. Assert(*scan == *match, "match[2]?");
  78545. /* We check for insufficient lookahead only every 8th comparison;
  78546. * the 256th check will be made at strstart+258.
  78547. */
  78548. do {
  78549. } while (*++scan == *++match && *++scan == *++match &&
  78550. *++scan == *++match && *++scan == *++match &&
  78551. *++scan == *++match && *++scan == *++match &&
  78552. *++scan == *++match && *++scan == *++match &&
  78553. scan < strend);
  78554. Assert(scan <= s->window+(unsigned)(s->window_size-1), "wild scan");
  78555. len = MAX_MATCH - (int)(strend - scan);
  78556. scan = strend - MAX_MATCH;
  78557. #endif /* UNALIGNED_OK */
  78558. if (len > best_len) {
  78559. s->match_start = cur_match;
  78560. best_len = len;
  78561. if (len >= nice_match) break;
  78562. #ifdef UNALIGNED_OK
  78563. scan_end = *(ushf*)(scan+best_len-1);
  78564. #else
  78565. scan_end1 = scan[best_len-1];
  78566. scan_end = scan[best_len];
  78567. #endif
  78568. }
  78569. } while ((cur_match = prev[cur_match & wmask]) > limit
  78570. && --chain_length != 0);
  78571. if ((uInt)best_len <= s->lookahead) return (uInt)best_len;
  78572. return s->lookahead;
  78573. }
  78574. #endif /* ASMV */
  78575. #endif /* FASTEST */
  78576. /* ---------------------------------------------------------------------------
  78577. * Optimized version for level == 1 or strategy == Z_RLE only
  78578. */
  78579. local uInt longest_match_fast (deflate_state *s, IPos cur_match)
  78580. {
  78581. register Bytef *scan = s->window + s->strstart; /* current string */
  78582. register Bytef *match; /* matched string */
  78583. register int len; /* length of current match */
  78584. register Bytef *strend = s->window + s->strstart + MAX_MATCH;
  78585. /* The code is optimized for HASH_BITS >= 8 and MAX_MATCH-2 multiple of 16.
  78586. * It is easy to get rid of this optimization if necessary.
  78587. */
  78588. Assert(s->hash_bits >= 8 && MAX_MATCH == 258, "Code too clever");
  78589. Assert((ulg)s->strstart <= s->window_size-MIN_LOOKAHEAD, "need lookahead");
  78590. Assert(cur_match < s->strstart, "no future");
  78591. match = s->window + cur_match;
  78592. /* Return failure if the match length is less than 2:
  78593. */
  78594. if (match[0] != scan[0] || match[1] != scan[1]) return MIN_MATCH-1;
  78595. /* The check at best_len-1 can be removed because it will be made
  78596. * again later. (This heuristic is not always a win.)
  78597. * It is not necessary to compare scan[2] and match[2] since they
  78598. * are always equal when the other bytes match, given that
  78599. * the hash keys are equal and that HASH_BITS >= 8.
  78600. */
  78601. scan += 2, match += 2;
  78602. Assert(*scan == *match, "match[2]?");
  78603. /* We check for insufficient lookahead only every 8th comparison;
  78604. * the 256th check will be made at strstart+258.
  78605. */
  78606. do {
  78607. } while (*++scan == *++match && *++scan == *++match &&
  78608. *++scan == *++match && *++scan == *++match &&
  78609. *++scan == *++match && *++scan == *++match &&
  78610. *++scan == *++match && *++scan == *++match &&
  78611. scan < strend);
  78612. Assert(scan <= s->window+(unsigned)(s->window_size-1), "wild scan");
  78613. len = MAX_MATCH - (int)(strend - scan);
  78614. if (len < MIN_MATCH) return MIN_MATCH - 1;
  78615. s->match_start = cur_match;
  78616. return (uInt)len <= s->lookahead ? (uInt)len : s->lookahead;
  78617. }
  78618. #ifdef DEBUG
  78619. /* ===========================================================================
  78620. * Check that the match at match_start is indeed a match.
  78621. */
  78622. local void check_match(deflate_state *s, IPos start, IPos match, int length)
  78623. {
  78624. /* check that the match is indeed a match */
  78625. if (zmemcmp(s->window + match,
  78626. s->window + start, length) != EQUAL) {
  78627. fprintf(stderr, " start %u, match %u, length %d\n",
  78628. start, match, length);
  78629. do {
  78630. fprintf(stderr, "%c%c", s->window[match++], s->window[start++]);
  78631. } while (--length != 0);
  78632. z_error("invalid match");
  78633. }
  78634. if (z_verbose > 1) {
  78635. fprintf(stderr,"\\[%d,%d]", start-match, length);
  78636. do { putc(s->window[start++], stderr); } while (--length != 0);
  78637. }
  78638. }
  78639. #else
  78640. # define check_match(s, start, match, length)
  78641. #endif /* DEBUG */
  78642. /* ===========================================================================
  78643. * Fill the window when the lookahead becomes insufficient.
  78644. * Updates strstart and lookahead.
  78645. *
  78646. * IN assertion: lookahead < MIN_LOOKAHEAD
  78647. * OUT assertions: strstart <= window_size-MIN_LOOKAHEAD
  78648. * At least one byte has been read, or avail_in == 0; reads are
  78649. * performed for at least two bytes (required for the zip translate_eol
  78650. * option -- not supported here).
  78651. */
  78652. local void fill_window (deflate_state *s)
  78653. {
  78654. register unsigned n, m;
  78655. register Posf *p;
  78656. unsigned more; /* Amount of free space at the end of the window. */
  78657. uInt wsize = s->w_size;
  78658. do {
  78659. more = (unsigned)(s->window_size -(ulg)s->lookahead -(ulg)s->strstart);
  78660. /* Deal with !@#$% 64K limit: */
  78661. if (sizeof(int) <= 2) {
  78662. if (more == 0 && s->strstart == 0 && s->lookahead == 0) {
  78663. more = wsize;
  78664. } else if (more == (unsigned)(-1)) {
  78665. /* Very unlikely, but possible on 16 bit machine if
  78666. * strstart == 0 && lookahead == 1 (input done a byte at time)
  78667. */
  78668. more--;
  78669. }
  78670. }
  78671. /* If the window is almost full and there is insufficient lookahead,
  78672. * move the upper half to the lower one to make room in the upper half.
  78673. */
  78674. if (s->strstart >= wsize+MAX_DIST(s)) {
  78675. zmemcpy(s->window, s->window+wsize, (unsigned)wsize);
  78676. s->match_start -= wsize;
  78677. s->strstart -= wsize; /* we now have strstart >= MAX_DIST */
  78678. s->block_start -= (long) wsize;
  78679. /* Slide the hash table (could be avoided with 32 bit values
  78680. at the expense of memory usage). We slide even when level == 0
  78681. to keep the hash table consistent if we switch back to level > 0
  78682. later. (Using level 0 permanently is not an optimal usage of
  78683. zlib, so we don't care about this pathological case.)
  78684. */
  78685. /* %%% avoid this when Z_RLE */
  78686. n = s->hash_size;
  78687. p = &s->head[n];
  78688. do {
  78689. m = *--p;
  78690. *p = (Pos)(m >= wsize ? m-wsize : NIL);
  78691. } while (--n);
  78692. n = wsize;
  78693. #ifndef FASTEST
  78694. p = &s->prev[n];
  78695. do {
  78696. m = *--p;
  78697. *p = (Pos)(m >= wsize ? m-wsize : NIL);
  78698. /* If n is not on any hash chain, prev[n] is garbage but
  78699. * its value will never be used.
  78700. */
  78701. } while (--n);
  78702. #endif
  78703. more += wsize;
  78704. }
  78705. if (s->strm->avail_in == 0) return;
  78706. /* If there was no sliding:
  78707. * strstart <= WSIZE+MAX_DIST-1 && lookahead <= MIN_LOOKAHEAD - 1 &&
  78708. * more == window_size - lookahead - strstart
  78709. * => more >= window_size - (MIN_LOOKAHEAD-1 + WSIZE + MAX_DIST-1)
  78710. * => more >= window_size - 2*WSIZE + 2
  78711. * In the BIG_MEM or MMAP case (not yet supported),
  78712. * window_size == input_size + MIN_LOOKAHEAD &&
  78713. * strstart + s->lookahead <= input_size => more >= MIN_LOOKAHEAD.
  78714. * Otherwise, window_size == 2*WSIZE so more >= 2.
  78715. * If there was sliding, more >= WSIZE. So in all cases, more >= 2.
  78716. */
  78717. Assert(more >= 2, "more < 2");
  78718. n = read_buf(s->strm, s->window + s->strstart + s->lookahead, more);
  78719. s->lookahead += n;
  78720. /* Initialize the hash value now that we have some input: */
  78721. if (s->lookahead >= MIN_MATCH) {
  78722. s->ins_h = s->window[s->strstart];
  78723. UPDATE_HASH(s, s->ins_h, s->window[s->strstart+1]);
  78724. #if MIN_MATCH != 3
  78725. Call UPDATE_HASH() MIN_MATCH-3 more times
  78726. #endif
  78727. }
  78728. /* If the whole input has less than MIN_MATCH bytes, ins_h is garbage,
  78729. * but this is not important since only literal bytes will be emitted.
  78730. */
  78731. } while (s->lookahead < MIN_LOOKAHEAD && s->strm->avail_in != 0);
  78732. }
  78733. /* ===========================================================================
  78734. * Flush the current block, with given end-of-file flag.
  78735. * IN assertion: strstart is set to the end of the current match.
  78736. */
  78737. #define FLUSH_BLOCK_ONLY(s, eof) { \
  78738. _tr_flush_block(s, (s->block_start >= 0L ? \
  78739. (charf *)&s->window[(unsigned)s->block_start] : \
  78740. (charf *)Z_NULL), \
  78741. (ulg)((long)s->strstart - s->block_start), \
  78742. (eof)); \
  78743. s->block_start = s->strstart; \
  78744. flush_pending(s->strm); \
  78745. Tracev((stderr,"[FLUSH]")); \
  78746. }
  78747. /* Same but force premature exit if necessary. */
  78748. #define FLUSH_BLOCK(s, eof) { \
  78749. FLUSH_BLOCK_ONLY(s, eof); \
  78750. if (s->strm->avail_out == 0) return (eof) ? finish_started : need_more; \
  78751. }
  78752. /* ===========================================================================
  78753. * Copy without compression as much as possible from the input stream, return
  78754. * the current block state.
  78755. * This function does not insert new strings in the dictionary since
  78756. * uncompressible data is probably not useful. This function is used
  78757. * only for the level=0 compression option.
  78758. * NOTE: this function should be optimized to avoid extra copying from
  78759. * window to pending_buf.
  78760. */
  78761. local block_state deflate_stored(deflate_state *s, int flush)
  78762. {
  78763. /* Stored blocks are limited to 0xffff bytes, pending_buf is limited
  78764. * to pending_buf_size, and each stored block has a 5 byte header:
  78765. */
  78766. ulg max_block_size = 0xffff;
  78767. ulg max_start;
  78768. if (max_block_size > s->pending_buf_size - 5) {
  78769. max_block_size = s->pending_buf_size - 5;
  78770. }
  78771. /* Copy as much as possible from input to output: */
  78772. for (;;) {
  78773. /* Fill the window as much as possible: */
  78774. if (s->lookahead <= 1) {
  78775. Assert(s->strstart < s->w_size+MAX_DIST(s) ||
  78776. s->block_start >= (long)s->w_size, "slide too late");
  78777. fill_window(s);
  78778. if (s->lookahead == 0 && flush == Z_NO_FLUSH) return need_more;
  78779. if (s->lookahead == 0) break; /* flush the current block */
  78780. }
  78781. Assert(s->block_start >= 0L, "block gone");
  78782. s->strstart += s->lookahead;
  78783. s->lookahead = 0;
  78784. /* Emit a stored block if pending_buf will be full: */
  78785. max_start = s->block_start + max_block_size;
  78786. if (s->strstart == 0 || (ulg)s->strstart >= max_start) {
  78787. /* strstart == 0 is possible when wraparound on 16-bit machine */
  78788. s->lookahead = (uInt)(s->strstart - max_start);
  78789. s->strstart = (uInt)max_start;
  78790. FLUSH_BLOCK(s, 0);
  78791. }
  78792. /* Flush if we may have to slide, otherwise block_start may become
  78793. * negative and the data will be gone:
  78794. */
  78795. if (s->strstart - (uInt)s->block_start >= MAX_DIST(s)) {
  78796. FLUSH_BLOCK(s, 0);
  78797. }
  78798. }
  78799. FLUSH_BLOCK(s, flush == Z_FINISH);
  78800. return flush == Z_FINISH ? finish_done : block_done;
  78801. }
  78802. /* ===========================================================================
  78803. * Compress as much as possible from the input stream, return the current
  78804. * block state.
  78805. * This function does not perform lazy evaluation of matches and inserts
  78806. * new strings in the dictionary only for unmatched strings or for short
  78807. * matches. It is used only for the fast compression options.
  78808. */
  78809. local block_state deflate_fast(deflate_state *s, int flush)
  78810. {
  78811. IPos hash_head = NIL; /* head of the hash chain */
  78812. int bflush; /* set if current block must be flushed */
  78813. for (;;) {
  78814. /* Make sure that we always have enough lookahead, except
  78815. * at the end of the input file. We need MAX_MATCH bytes
  78816. * for the next match, plus MIN_MATCH bytes to insert the
  78817. * string following the next match.
  78818. */
  78819. if (s->lookahead < MIN_LOOKAHEAD) {
  78820. fill_window(s);
  78821. if (s->lookahead < MIN_LOOKAHEAD && flush == Z_NO_FLUSH) {
  78822. return need_more;
  78823. }
  78824. if (s->lookahead == 0) break; /* flush the current block */
  78825. }
  78826. /* Insert the string window[strstart .. strstart+2] in the
  78827. * dictionary, and set hash_head to the head of the hash chain:
  78828. */
  78829. if (s->lookahead >= MIN_MATCH) {
  78830. INSERT_STRING(s, s->strstart, hash_head);
  78831. }
  78832. /* Find the longest match, discarding those <= prev_length.
  78833. * At this point we have always match_length < MIN_MATCH
  78834. */
  78835. if (hash_head != NIL && s->strstart - hash_head <= MAX_DIST(s)) {
  78836. /* To simplify the code, we prevent matches with the string
  78837. * of window index 0 (in particular we have to avoid a match
  78838. * of the string with itself at the start of the input file).
  78839. */
  78840. #ifdef FASTEST
  78841. if ((s->strategy != Z_HUFFMAN_ONLY && s->strategy != Z_RLE) ||
  78842. (s->strategy == Z_RLE && s->strstart - hash_head == 1)) {
  78843. s->match_length = longest_match_fast (s, hash_head);
  78844. }
  78845. #else
  78846. if (s->strategy != Z_HUFFMAN_ONLY && s->strategy != Z_RLE) {
  78847. s->match_length = longest_match (s, hash_head);
  78848. } else if (s->strategy == Z_RLE && s->strstart - hash_head == 1) {
  78849. s->match_length = longest_match_fast (s, hash_head);
  78850. }
  78851. #endif
  78852. /* longest_match() or longest_match_fast() sets match_start */
  78853. }
  78854. if (s->match_length >= MIN_MATCH) {
  78855. check_match(s, s->strstart, s->match_start, s->match_length);
  78856. _tr_tally_dist(s, s->strstart - s->match_start,
  78857. s->match_length - MIN_MATCH, bflush);
  78858. s->lookahead -= s->match_length;
  78859. /* Insert new strings in the hash table only if the match length
  78860. * is not too large. This saves time but degrades compression.
  78861. */
  78862. #ifndef FASTEST
  78863. if (s->match_length <= s->max_insert_length &&
  78864. s->lookahead >= MIN_MATCH) {
  78865. s->match_length--; /* string at strstart already in table */
  78866. do {
  78867. s->strstart++;
  78868. INSERT_STRING(s, s->strstart, hash_head);
  78869. /* strstart never exceeds WSIZE-MAX_MATCH, so there are
  78870. * always MIN_MATCH bytes ahead.
  78871. */
  78872. } while (--s->match_length != 0);
  78873. s->strstart++;
  78874. } else
  78875. #endif
  78876. {
  78877. s->strstart += s->match_length;
  78878. s->match_length = 0;
  78879. s->ins_h = s->window[s->strstart];
  78880. UPDATE_HASH(s, s->ins_h, s->window[s->strstart+1]);
  78881. #if MIN_MATCH != 3
  78882. Call UPDATE_HASH() MIN_MATCH-3 more times
  78883. #endif
  78884. /* If lookahead < MIN_MATCH, ins_h is garbage, but it does not
  78885. * matter since it will be recomputed at next deflate call.
  78886. */
  78887. }
  78888. } else {
  78889. /* No match, output a literal byte */
  78890. Tracevv((stderr,"%c", s->window[s->strstart]));
  78891. _tr_tally_lit (s, s->window[s->strstart], bflush);
  78892. s->lookahead--;
  78893. s->strstart++;
  78894. }
  78895. if (bflush) FLUSH_BLOCK(s, 0);
  78896. }
  78897. FLUSH_BLOCK(s, flush == Z_FINISH);
  78898. return flush == Z_FINISH ? finish_done : block_done;
  78899. }
  78900. #ifndef FASTEST
  78901. /* ===========================================================================
  78902. * Same as above, but achieves better compression. We use a lazy
  78903. * evaluation for matches: a match is finally adopted only if there is
  78904. * no better match at the next window position.
  78905. */
  78906. local block_state deflate_slow(deflate_state *s, int flush)
  78907. {
  78908. IPos hash_head = NIL; /* head of hash chain */
  78909. int bflush; /* set if current block must be flushed */
  78910. /* Process the input block. */
  78911. for (;;) {
  78912. /* Make sure that we always have enough lookahead, except
  78913. * at the end of the input file. We need MAX_MATCH bytes
  78914. * for the next match, plus MIN_MATCH bytes to insert the
  78915. * string following the next match.
  78916. */
  78917. if (s->lookahead < MIN_LOOKAHEAD) {
  78918. fill_window(s);
  78919. if (s->lookahead < MIN_LOOKAHEAD && flush == Z_NO_FLUSH) {
  78920. return need_more;
  78921. }
  78922. if (s->lookahead == 0) break; /* flush the current block */
  78923. }
  78924. /* Insert the string window[strstart .. strstart+2] in the
  78925. * dictionary, and set hash_head to the head of the hash chain:
  78926. */
  78927. if (s->lookahead >= MIN_MATCH) {
  78928. INSERT_STRING(s, s->strstart, hash_head);
  78929. }
  78930. /* Find the longest match, discarding those <= prev_length.
  78931. */
  78932. s->prev_length = s->match_length, s->prev_match = s->match_start;
  78933. s->match_length = MIN_MATCH-1;
  78934. if (hash_head != NIL && s->prev_length < s->max_lazy_match &&
  78935. s->strstart - hash_head <= MAX_DIST(s)) {
  78936. /* To simplify the code, we prevent matches with the string
  78937. * of window index 0 (in particular we have to avoid a match
  78938. * of the string with itself at the start of the input file).
  78939. */
  78940. if (s->strategy != Z_HUFFMAN_ONLY && s->strategy != Z_RLE) {
  78941. s->match_length = longest_match (s, hash_head);
  78942. } else if (s->strategy == Z_RLE && s->strstart - hash_head == 1) {
  78943. s->match_length = longest_match_fast (s, hash_head);
  78944. }
  78945. /* longest_match() or longest_match_fast() sets match_start */
  78946. if (s->match_length <= 5 && (s->strategy == Z_FILTERED
  78947. #if TOO_FAR <= 32767
  78948. || (s->match_length == MIN_MATCH &&
  78949. s->strstart - s->match_start > TOO_FAR)
  78950. #endif
  78951. )) {
  78952. /* If prev_match is also MIN_MATCH, match_start is garbage
  78953. * but we will ignore the current match anyway.
  78954. */
  78955. s->match_length = MIN_MATCH-1;
  78956. }
  78957. }
  78958. /* If there was a match at the previous step and the current
  78959. * match is not better, output the previous match:
  78960. */
  78961. if (s->prev_length >= MIN_MATCH && s->match_length <= s->prev_length) {
  78962. uInt max_insert = s->strstart + s->lookahead - MIN_MATCH;
  78963. /* Do not insert strings in hash table beyond this. */
  78964. check_match(s, s->strstart-1, s->prev_match, s->prev_length);
  78965. _tr_tally_dist(s, s->strstart -1 - s->prev_match,
  78966. s->prev_length - MIN_MATCH, bflush);
  78967. /* Insert in hash table all strings up to the end of the match.
  78968. * strstart-1 and strstart are already inserted. If there is not
  78969. * enough lookahead, the last two strings are not inserted in
  78970. * the hash table.
  78971. */
  78972. s->lookahead -= s->prev_length-1;
  78973. s->prev_length -= 2;
  78974. do {
  78975. if (++s->strstart <= max_insert) {
  78976. INSERT_STRING(s, s->strstart, hash_head);
  78977. }
  78978. } while (--s->prev_length != 0);
  78979. s->match_available = 0;
  78980. s->match_length = MIN_MATCH-1;
  78981. s->strstart++;
  78982. if (bflush) FLUSH_BLOCK(s, 0);
  78983. } else if (s->match_available) {
  78984. /* If there was no match at the previous position, output a
  78985. * single literal. If there was a match but the current match
  78986. * is longer, truncate the previous match to a single literal.
  78987. */
  78988. Tracevv((stderr,"%c", s->window[s->strstart-1]));
  78989. _tr_tally_lit(s, s->window[s->strstart-1], bflush);
  78990. if (bflush) {
  78991. FLUSH_BLOCK_ONLY(s, 0);
  78992. }
  78993. s->strstart++;
  78994. s->lookahead--;
  78995. if (s->strm->avail_out == 0) return need_more;
  78996. } else {
  78997. /* There is no previous match to compare with, wait for
  78998. * the next step to decide.
  78999. */
  79000. s->match_available = 1;
  79001. s->strstart++;
  79002. s->lookahead--;
  79003. }
  79004. }
  79005. Assert (flush != Z_NO_FLUSH, "no flush?");
  79006. if (s->match_available) {
  79007. Tracevv((stderr,"%c", s->window[s->strstart-1]));
  79008. _tr_tally_lit(s, s->window[s->strstart-1], bflush);
  79009. s->match_available = 0;
  79010. }
  79011. FLUSH_BLOCK(s, flush == Z_FINISH);
  79012. return flush == Z_FINISH ? finish_done : block_done;
  79013. }
  79014. #endif /* FASTEST */
  79015. #if 0
  79016. /* ===========================================================================
  79017. * For Z_RLE, simply look for runs of bytes, generate matches only of distance
  79018. * one. Do not maintain a hash table. (It will be regenerated if this run of
  79019. * deflate switches away from Z_RLE.)
  79020. */
  79021. local block_state deflate_rle(s, flush)
  79022. deflate_state *s;
  79023. int flush;
  79024. {
  79025. int bflush; /* set if current block must be flushed */
  79026. uInt run; /* length of run */
  79027. uInt max; /* maximum length of run */
  79028. uInt prev; /* byte at distance one to match */
  79029. Bytef *scan; /* scan for end of run */
  79030. for (;;) {
  79031. /* Make sure that we always have enough lookahead, except
  79032. * at the end of the input file. We need MAX_MATCH bytes
  79033. * for the longest encodable run.
  79034. */
  79035. if (s->lookahead < MAX_MATCH) {
  79036. fill_window(s);
  79037. if (s->lookahead < MAX_MATCH && flush == Z_NO_FLUSH) {
  79038. return need_more;
  79039. }
  79040. if (s->lookahead == 0) break; /* flush the current block */
  79041. }
  79042. /* See how many times the previous byte repeats */
  79043. run = 0;
  79044. if (s->strstart > 0) { /* if there is a previous byte, that is */
  79045. max = s->lookahead < MAX_MATCH ? s->lookahead : MAX_MATCH;
  79046. scan = s->window + s->strstart - 1;
  79047. prev = *scan++;
  79048. do {
  79049. if (*scan++ != prev)
  79050. break;
  79051. } while (++run < max);
  79052. }
  79053. /* Emit match if have run of MIN_MATCH or longer, else emit literal */
  79054. if (run >= MIN_MATCH) {
  79055. check_match(s, s->strstart, s->strstart - 1, run);
  79056. _tr_tally_dist(s, 1, run - MIN_MATCH, bflush);
  79057. s->lookahead -= run;
  79058. s->strstart += run;
  79059. } else {
  79060. /* No match, output a literal byte */
  79061. Tracevv((stderr,"%c", s->window[s->strstart]));
  79062. _tr_tally_lit (s, s->window[s->strstart], bflush);
  79063. s->lookahead--;
  79064. s->strstart++;
  79065. }
  79066. if (bflush) FLUSH_BLOCK(s, 0);
  79067. }
  79068. FLUSH_BLOCK(s, flush == Z_FINISH);
  79069. return flush == Z_FINISH ? finish_done : block_done;
  79070. }
  79071. #endif
  79072. /*** End of inlined file: deflate.c ***/
  79073. /*** Start of inlined file: inffast.c ***/
  79074. /*** Start of inlined file: inftrees.h ***/
  79075. /* WARNING: this file should *not* be used by applications. It is
  79076. part of the implementation of the compression library and is
  79077. subject to change. Applications should only use zlib.h.
  79078. */
  79079. #ifndef _INFTREES_H_
  79080. #define _INFTREES_H_
  79081. /* Structure for decoding tables. Each entry provides either the
  79082. information needed to do the operation requested by the code that
  79083. indexed that table entry, or it provides a pointer to another
  79084. table that indexes more bits of the code. op indicates whether
  79085. the entry is a pointer to another table, a literal, a length or
  79086. distance, an end-of-block, or an invalid code. For a table
  79087. pointer, the low four bits of op is the number of index bits of
  79088. that table. For a length or distance, the low four bits of op
  79089. is the number of extra bits to get after the code. bits is
  79090. the number of bits in this code or part of the code to drop off
  79091. of the bit buffer. val is the actual byte to output in the case
  79092. of a literal, the base length or distance, or the offset from
  79093. the current table to the next table. Each entry is four bytes. */
  79094. typedef struct {
  79095. unsigned char op; /* operation, extra bits, table bits */
  79096. unsigned char bits; /* bits in this part of the code */
  79097. unsigned short val; /* offset in table or code value */
  79098. } code;
  79099. /* op values as set by inflate_table():
  79100. 00000000 - literal
  79101. 0000tttt - table link, tttt != 0 is the number of table index bits
  79102. 0001eeee - length or distance, eeee is the number of extra bits
  79103. 01100000 - end of block
  79104. 01000000 - invalid code
  79105. */
  79106. /* Maximum size of dynamic tree. The maximum found in a long but non-
  79107. exhaustive search was 1444 code structures (852 for length/literals
  79108. and 592 for distances, the latter actually the result of an
  79109. exhaustive search). The true maximum is not known, but the value
  79110. below is more than safe. */
  79111. #define ENOUGH 2048
  79112. #define MAXD 592
  79113. /* Type of code to build for inftable() */
  79114. typedef enum {
  79115. CODES,
  79116. LENS,
  79117. DISTS
  79118. } codetype;
  79119. extern int inflate_table OF((codetype type, unsigned short FAR *lens,
  79120. unsigned codes, code FAR * FAR *table,
  79121. unsigned FAR *bits, unsigned short FAR *work));
  79122. #endif
  79123. /*** End of inlined file: inftrees.h ***/
  79124. /*** Start of inlined file: inflate.h ***/
  79125. /* WARNING: this file should *not* be used by applications. It is
  79126. part of the implementation of the compression library and is
  79127. subject to change. Applications should only use zlib.h.
  79128. */
  79129. #ifndef _INFLATE_H_
  79130. #define _INFLATE_H_
  79131. /* define NO_GZIP when compiling if you want to disable gzip header and
  79132. trailer decoding by inflate(). NO_GZIP would be used to avoid linking in
  79133. the crc code when it is not needed. For shared libraries, gzip decoding
  79134. should be left enabled. */
  79135. #ifndef NO_GZIP
  79136. # define GUNZIP
  79137. #endif
  79138. /* Possible inflate modes between inflate() calls */
  79139. typedef enum {
  79140. HEAD, /* i: waiting for magic header */
  79141. FLAGS, /* i: waiting for method and flags (gzip) */
  79142. TIME, /* i: waiting for modification time (gzip) */
  79143. OS, /* i: waiting for extra flags and operating system (gzip) */
  79144. EXLEN, /* i: waiting for extra length (gzip) */
  79145. EXTRA, /* i: waiting for extra bytes (gzip) */
  79146. NAME, /* i: waiting for end of file name (gzip) */
  79147. COMMENT, /* i: waiting for end of comment (gzip) */
  79148. HCRC, /* i: waiting for header crc (gzip) */
  79149. DICTID, /* i: waiting for dictionary check value */
  79150. DICT, /* waiting for inflateSetDictionary() call */
  79151. TYPE, /* i: waiting for type bits, including last-flag bit */
  79152. TYPEDO, /* i: same, but skip check to exit inflate on new block */
  79153. STORED, /* i: waiting for stored size (length and complement) */
  79154. COPY, /* i/o: waiting for input or output to copy stored block */
  79155. TABLE, /* i: waiting for dynamic block table lengths */
  79156. LENLENS, /* i: waiting for code length code lengths */
  79157. CODELENS, /* i: waiting for length/lit and distance code lengths */
  79158. LEN, /* i: waiting for length/lit code */
  79159. LENEXT, /* i: waiting for length extra bits */
  79160. DIST, /* i: waiting for distance code */
  79161. DISTEXT, /* i: waiting for distance extra bits */
  79162. MATCH, /* o: waiting for output space to copy string */
  79163. LIT, /* o: waiting for output space to write literal */
  79164. CHECK, /* i: waiting for 32-bit check value */
  79165. LENGTH, /* i: waiting for 32-bit length (gzip) */
  79166. DONE, /* finished check, done -- remain here until reset */
  79167. BAD, /* got a data error -- remain here until reset */
  79168. MEM, /* got an inflate() memory error -- remain here until reset */
  79169. SYNC /* looking for synchronization bytes to restart inflate() */
  79170. } inflate_mode;
  79171. /*
  79172. State transitions between above modes -
  79173. (most modes can go to the BAD or MEM mode -- not shown for clarity)
  79174. Process header:
  79175. HEAD -> (gzip) or (zlib)
  79176. (gzip) -> FLAGS -> TIME -> OS -> EXLEN -> EXTRA -> NAME
  79177. NAME -> COMMENT -> HCRC -> TYPE
  79178. (zlib) -> DICTID or TYPE
  79179. DICTID -> DICT -> TYPE
  79180. Read deflate blocks:
  79181. TYPE -> STORED or TABLE or LEN or CHECK
  79182. STORED -> COPY -> TYPE
  79183. TABLE -> LENLENS -> CODELENS -> LEN
  79184. Read deflate codes:
  79185. LEN -> LENEXT or LIT or TYPE
  79186. LENEXT -> DIST -> DISTEXT -> MATCH -> LEN
  79187. LIT -> LEN
  79188. Process trailer:
  79189. CHECK -> LENGTH -> DONE
  79190. */
  79191. /* state maintained between inflate() calls. Approximately 7K bytes. */
  79192. struct inflate_state {
  79193. inflate_mode mode; /* current inflate mode */
  79194. int last; /* true if processing last block */
  79195. int wrap; /* bit 0 true for zlib, bit 1 true for gzip */
  79196. int havedict; /* true if dictionary provided */
  79197. int flags; /* gzip header method and flags (0 if zlib) */
  79198. unsigned dmax; /* zlib header max distance (INFLATE_STRICT) */
  79199. unsigned long check; /* protected copy of check value */
  79200. unsigned long total; /* protected copy of output count */
  79201. gz_headerp head; /* where to save gzip header information */
  79202. /* sliding window */
  79203. unsigned wbits; /* log base 2 of requested window size */
  79204. unsigned wsize; /* window size or zero if not using window */
  79205. unsigned whave; /* valid bytes in the window */
  79206. unsigned write; /* window write index */
  79207. unsigned char FAR *window; /* allocated sliding window, if needed */
  79208. /* bit accumulator */
  79209. unsigned long hold; /* input bit accumulator */
  79210. unsigned bits; /* number of bits in "in" */
  79211. /* for string and stored block copying */
  79212. unsigned length; /* literal or length of data to copy */
  79213. unsigned offset; /* distance back to copy string from */
  79214. /* for table and code decoding */
  79215. unsigned extra; /* extra bits needed */
  79216. /* fixed and dynamic code tables */
  79217. code const FAR *lencode; /* starting table for length/literal codes */
  79218. code const FAR *distcode; /* starting table for distance codes */
  79219. unsigned lenbits; /* index bits for lencode */
  79220. unsigned distbits; /* index bits for distcode */
  79221. /* dynamic table building */
  79222. unsigned ncode; /* number of code length code lengths */
  79223. unsigned nlen; /* number of length code lengths */
  79224. unsigned ndist; /* number of distance code lengths */
  79225. unsigned have; /* number of code lengths in lens[] */
  79226. code FAR *next; /* next available space in codes[] */
  79227. unsigned short lens[320]; /* temporary storage for code lengths */
  79228. unsigned short work[288]; /* work area for code table building */
  79229. code codes[ENOUGH]; /* space for code tables */
  79230. };
  79231. #endif
  79232. /*** End of inlined file: inflate.h ***/
  79233. /*** Start of inlined file: inffast.h ***/
  79234. /* WARNING: this file should *not* be used by applications. It is
  79235. part of the implementation of the compression library and is
  79236. subject to change. Applications should only use zlib.h.
  79237. */
  79238. void inflate_fast OF((z_streamp strm, unsigned start));
  79239. /*** End of inlined file: inffast.h ***/
  79240. #ifndef ASMINF
  79241. /* Allow machine dependent optimization for post-increment or pre-increment.
  79242. Based on testing to date,
  79243. Pre-increment preferred for:
  79244. - PowerPC G3 (Adler)
  79245. - MIPS R5000 (Randers-Pehrson)
  79246. Post-increment preferred for:
  79247. - none
  79248. No measurable difference:
  79249. - Pentium III (Anderson)
  79250. - M68060 (Nikl)
  79251. */
  79252. #ifdef POSTINC
  79253. # define OFF 0
  79254. # define PUP(a) *(a)++
  79255. #else
  79256. # define OFF 1
  79257. # define PUP(a) *++(a)
  79258. #endif
  79259. /*
  79260. Decode literal, length, and distance codes and write out the resulting
  79261. literal and match bytes until either not enough input or output is
  79262. available, an end-of-block is encountered, or a data error is encountered.
  79263. When large enough input and output buffers are supplied to inflate(), for
  79264. example, a 16K input buffer and a 64K output buffer, more than 95% of the
  79265. inflate execution time is spent in this routine.
  79266. Entry assumptions:
  79267. state->mode == LEN
  79268. strm->avail_in >= 6
  79269. strm->avail_out >= 258
  79270. start >= strm->avail_out
  79271. state->bits < 8
  79272. On return, state->mode is one of:
  79273. LEN -- ran out of enough output space or enough available input
  79274. TYPE -- reached end of block code, inflate() to interpret next block
  79275. BAD -- error in block data
  79276. Notes:
  79277. - The maximum input bits used by a length/distance pair is 15 bits for the
  79278. length code, 5 bits for the length extra, 15 bits for the distance code,
  79279. and 13 bits for the distance extra. This totals 48 bits, or six bytes.
  79280. Therefore if strm->avail_in >= 6, then there is enough input to avoid
  79281. checking for available input while decoding.
  79282. - The maximum bytes that a single length/distance pair can output is 258
  79283. bytes, which is the maximum length that can be coded. inflate_fast()
  79284. requires strm->avail_out >= 258 for each loop to avoid checking for
  79285. output space.
  79286. */
  79287. void inflate_fast (z_streamp strm, unsigned start)
  79288. {
  79289. struct inflate_state FAR *state;
  79290. unsigned char FAR *in; /* local strm->next_in */
  79291. unsigned char FAR *last; /* while in < last, enough input available */
  79292. unsigned char FAR *out; /* local strm->next_out */
  79293. unsigned char FAR *beg; /* inflate()'s initial strm->next_out */
  79294. unsigned char FAR *end; /* while out < end, enough space available */
  79295. #ifdef INFLATE_STRICT
  79296. unsigned dmax; /* maximum distance from zlib header */
  79297. #endif
  79298. unsigned wsize; /* window size or zero if not using window */
  79299. unsigned whave; /* valid bytes in the window */
  79300. unsigned write; /* window write index */
  79301. unsigned char FAR *window; /* allocated sliding window, if wsize != 0 */
  79302. unsigned long hold; /* local strm->hold */
  79303. unsigned bits; /* local strm->bits */
  79304. code const FAR *lcode; /* local strm->lencode */
  79305. code const FAR *dcode; /* local strm->distcode */
  79306. unsigned lmask; /* mask for first level of length codes */
  79307. unsigned dmask; /* mask for first level of distance codes */
  79308. code thisx; /* retrieved table entry */
  79309. unsigned op; /* code bits, operation, extra bits, or */
  79310. /* window position, window bytes to copy */
  79311. unsigned len; /* match length, unused bytes */
  79312. unsigned dist; /* match distance */
  79313. unsigned char FAR *from; /* where to copy match from */
  79314. /* copy state to local variables */
  79315. state = (struct inflate_state FAR *)strm->state;
  79316. in = strm->next_in - OFF;
  79317. last = in + (strm->avail_in - 5);
  79318. out = strm->next_out - OFF;
  79319. beg = out - (start - strm->avail_out);
  79320. end = out + (strm->avail_out - 257);
  79321. #ifdef INFLATE_STRICT
  79322. dmax = state->dmax;
  79323. #endif
  79324. wsize = state->wsize;
  79325. whave = state->whave;
  79326. write = state->write;
  79327. window = state->window;
  79328. hold = state->hold;
  79329. bits = state->bits;
  79330. lcode = state->lencode;
  79331. dcode = state->distcode;
  79332. lmask = (1U << state->lenbits) - 1;
  79333. dmask = (1U << state->distbits) - 1;
  79334. /* decode literals and length/distances until end-of-block or not enough
  79335. input data or output space */
  79336. do {
  79337. if (bits < 15) {
  79338. hold += (unsigned long)(PUP(in)) << bits;
  79339. bits += 8;
  79340. hold += (unsigned long)(PUP(in)) << bits;
  79341. bits += 8;
  79342. }
  79343. thisx = lcode[hold & lmask];
  79344. dolen:
  79345. op = (unsigned)(thisx.bits);
  79346. hold >>= op;
  79347. bits -= op;
  79348. op = (unsigned)(thisx.op);
  79349. if (op == 0) { /* literal */
  79350. Tracevv((stderr, thisx.val >= 0x20 && thisx.val < 0x7f ?
  79351. "inflate: literal '%c'\n" :
  79352. "inflate: literal 0x%02x\n", thisx.val));
  79353. PUP(out) = (unsigned char)(thisx.val);
  79354. }
  79355. else if (op & 16) { /* length base */
  79356. len = (unsigned)(thisx.val);
  79357. op &= 15; /* number of extra bits */
  79358. if (op) {
  79359. if (bits < op) {
  79360. hold += (unsigned long)(PUP(in)) << bits;
  79361. bits += 8;
  79362. }
  79363. len += (unsigned)hold & ((1U << op) - 1);
  79364. hold >>= op;
  79365. bits -= op;
  79366. }
  79367. Tracevv((stderr, "inflate: length %u\n", len));
  79368. if (bits < 15) {
  79369. hold += (unsigned long)(PUP(in)) << bits;
  79370. bits += 8;
  79371. hold += (unsigned long)(PUP(in)) << bits;
  79372. bits += 8;
  79373. }
  79374. thisx = dcode[hold & dmask];
  79375. dodist:
  79376. op = (unsigned)(thisx.bits);
  79377. hold >>= op;
  79378. bits -= op;
  79379. op = (unsigned)(thisx.op);
  79380. if (op & 16) { /* distance base */
  79381. dist = (unsigned)(thisx.val);
  79382. op &= 15; /* number of extra bits */
  79383. if (bits < op) {
  79384. hold += (unsigned long)(PUP(in)) << bits;
  79385. bits += 8;
  79386. if (bits < op) {
  79387. hold += (unsigned long)(PUP(in)) << bits;
  79388. bits += 8;
  79389. }
  79390. }
  79391. dist += (unsigned)hold & ((1U << op) - 1);
  79392. #ifdef INFLATE_STRICT
  79393. if (dist > dmax) {
  79394. strm->msg = (char *)"invalid distance too far back";
  79395. state->mode = BAD;
  79396. break;
  79397. }
  79398. #endif
  79399. hold >>= op;
  79400. bits -= op;
  79401. Tracevv((stderr, "inflate: distance %u\n", dist));
  79402. op = (unsigned)(out - beg); /* max distance in output */
  79403. if (dist > op) { /* see if copy from window */
  79404. op = dist - op; /* distance back in window */
  79405. if (op > whave) {
  79406. strm->msg = (char *)"invalid distance too far back";
  79407. state->mode = BAD;
  79408. break;
  79409. }
  79410. from = window - OFF;
  79411. if (write == 0) { /* very common case */
  79412. from += wsize - op;
  79413. if (op < len) { /* some from window */
  79414. len -= op;
  79415. do {
  79416. PUP(out) = PUP(from);
  79417. } while (--op);
  79418. from = out - dist; /* rest from output */
  79419. }
  79420. }
  79421. else if (write < op) { /* wrap around window */
  79422. from += wsize + write - op;
  79423. op -= write;
  79424. if (op < len) { /* some from end of window */
  79425. len -= op;
  79426. do {
  79427. PUP(out) = PUP(from);
  79428. } while (--op);
  79429. from = window - OFF;
  79430. if (write < len) { /* some from start of window */
  79431. op = write;
  79432. len -= op;
  79433. do {
  79434. PUP(out) = PUP(from);
  79435. } while (--op);
  79436. from = out - dist; /* rest from output */
  79437. }
  79438. }
  79439. }
  79440. else { /* contiguous in window */
  79441. from += write - op;
  79442. if (op < len) { /* some from window */
  79443. len -= op;
  79444. do {
  79445. PUP(out) = PUP(from);
  79446. } while (--op);
  79447. from = out - dist; /* rest from output */
  79448. }
  79449. }
  79450. while (len > 2) {
  79451. PUP(out) = PUP(from);
  79452. PUP(out) = PUP(from);
  79453. PUP(out) = PUP(from);
  79454. len -= 3;
  79455. }
  79456. if (len) {
  79457. PUP(out) = PUP(from);
  79458. if (len > 1)
  79459. PUP(out) = PUP(from);
  79460. }
  79461. }
  79462. else {
  79463. from = out - dist; /* copy direct from output */
  79464. do { /* minimum length is three */
  79465. PUP(out) = PUP(from);
  79466. PUP(out) = PUP(from);
  79467. PUP(out) = PUP(from);
  79468. len -= 3;
  79469. } while (len > 2);
  79470. if (len) {
  79471. PUP(out) = PUP(from);
  79472. if (len > 1)
  79473. PUP(out) = PUP(from);
  79474. }
  79475. }
  79476. }
  79477. else if ((op & 64) == 0) { /* 2nd level distance code */
  79478. thisx = dcode[thisx.val + (hold & ((1U << op) - 1))];
  79479. goto dodist;
  79480. }
  79481. else {
  79482. strm->msg = (char *)"invalid distance code";
  79483. state->mode = BAD;
  79484. break;
  79485. }
  79486. }
  79487. else if ((op & 64) == 0) { /* 2nd level length code */
  79488. thisx = lcode[thisx.val + (hold & ((1U << op) - 1))];
  79489. goto dolen;
  79490. }
  79491. else if (op & 32) { /* end-of-block */
  79492. Tracevv((stderr, "inflate: end of block\n"));
  79493. state->mode = TYPE;
  79494. break;
  79495. }
  79496. else {
  79497. strm->msg = (char *)"invalid literal/length code";
  79498. state->mode = BAD;
  79499. break;
  79500. }
  79501. } while (in < last && out < end);
  79502. /* return unused bytes (on entry, bits < 8, so in won't go too far back) */
  79503. len = bits >> 3;
  79504. in -= len;
  79505. bits -= len << 3;
  79506. hold &= (1U << bits) - 1;
  79507. /* update state and return */
  79508. strm->next_in = in + OFF;
  79509. strm->next_out = out + OFF;
  79510. strm->avail_in = (unsigned)(in < last ? 5 + (last - in) : 5 - (in - last));
  79511. strm->avail_out = (unsigned)(out < end ?
  79512. 257 + (end - out) : 257 - (out - end));
  79513. state->hold = hold;
  79514. state->bits = bits;
  79515. return;
  79516. }
  79517. /*
  79518. inflate_fast() speedups that turned out slower (on a PowerPC G3 750CXe):
  79519. - Using bit fields for code structure
  79520. - Different op definition to avoid & for extra bits (do & for table bits)
  79521. - Three separate decoding do-loops for direct, window, and write == 0
  79522. - Special case for distance > 1 copies to do overlapped load and store copy
  79523. - Explicit branch predictions (based on measured branch probabilities)
  79524. - Deferring match copy and interspersed it with decoding subsequent codes
  79525. - Swapping literal/length else
  79526. - Swapping window/direct else
  79527. - Larger unrolled copy loops (three is about right)
  79528. - Moving len -= 3 statement into middle of loop
  79529. */
  79530. #endif /* !ASMINF */
  79531. /*** End of inlined file: inffast.c ***/
  79532. #undef PULLBYTE
  79533. #undef LOAD
  79534. #undef RESTORE
  79535. #undef INITBITS
  79536. #undef NEEDBITS
  79537. #undef DROPBITS
  79538. #undef BYTEBITS
  79539. /*** Start of inlined file: inflate.c ***/
  79540. /*
  79541. * Change history:
  79542. *
  79543. * 1.2.beta0 24 Nov 2002
  79544. * - First version -- complete rewrite of inflate to simplify code, avoid
  79545. * creation of window when not needed, minimize use of window when it is
  79546. * needed, make inffast.c even faster, implement gzip decoding, and to
  79547. * improve code readability and style over the previous zlib inflate code
  79548. *
  79549. * 1.2.beta1 25 Nov 2002
  79550. * - Use pointers for available input and output checking in inffast.c
  79551. * - Remove input and output counters in inffast.c
  79552. * - Change inffast.c entry and loop from avail_in >= 7 to >= 6
  79553. * - Remove unnecessary second byte pull from length extra in inffast.c
  79554. * - Unroll direct copy to three copies per loop in inffast.c
  79555. *
  79556. * 1.2.beta2 4 Dec 2002
  79557. * - Change external routine names to reduce potential conflicts
  79558. * - Correct filename to inffixed.h for fixed tables in inflate.c
  79559. * - Make hbuf[] unsigned char to match parameter type in inflate.c
  79560. * - Change strm->next_out[-state->offset] to *(strm->next_out - state->offset)
  79561. * to avoid negation problem on Alphas (64 bit) in inflate.c
  79562. *
  79563. * 1.2.beta3 22 Dec 2002
  79564. * - Add comments on state->bits assertion in inffast.c
  79565. * - Add comments on op field in inftrees.h
  79566. * - Fix bug in reuse of allocated window after inflateReset()
  79567. * - Remove bit fields--back to byte structure for speed
  79568. * - Remove distance extra == 0 check in inflate_fast()--only helps for lengths
  79569. * - Change post-increments to pre-increments in inflate_fast(), PPC biased?
  79570. * - Add compile time option, POSTINC, to use post-increments instead (Intel?)
  79571. * - Make MATCH copy in inflate() much faster for when inflate_fast() not used
  79572. * - Use local copies of stream next and avail values, as well as local bit
  79573. * buffer and bit count in inflate()--for speed when inflate_fast() not used
  79574. *
  79575. * 1.2.beta4 1 Jan 2003
  79576. * - Split ptr - 257 statements in inflate_table() to avoid compiler warnings
  79577. * - Move a comment on output buffer sizes from inffast.c to inflate.c
  79578. * - Add comments in inffast.c to introduce the inflate_fast() routine
  79579. * - Rearrange window copies in inflate_fast() for speed and simplification
  79580. * - Unroll last copy for window match in inflate_fast()
  79581. * - Use local copies of window variables in inflate_fast() for speed
  79582. * - Pull out common write == 0 case for speed in inflate_fast()
  79583. * - Make op and len in inflate_fast() unsigned for consistency
  79584. * - Add FAR to lcode and dcode declarations in inflate_fast()
  79585. * - Simplified bad distance check in inflate_fast()
  79586. * - Added inflateBackInit(), inflateBack(), and inflateBackEnd() in new
  79587. * source file infback.c to provide a call-back interface to inflate for
  79588. * programs like gzip and unzip -- uses window as output buffer to avoid
  79589. * window copying
  79590. *
  79591. * 1.2.beta5 1 Jan 2003
  79592. * - Improved inflateBack() interface to allow the caller to provide initial
  79593. * input in strm.
  79594. * - Fixed stored blocks bug in inflateBack()
  79595. *
  79596. * 1.2.beta6 4 Jan 2003
  79597. * - Added comments in inffast.c on effectiveness of POSTINC
  79598. * - Typecasting all around to reduce compiler warnings
  79599. * - Changed loops from while (1) or do {} while (1) to for (;;), again to
  79600. * make compilers happy
  79601. * - Changed type of window in inflateBackInit() to unsigned char *
  79602. *
  79603. * 1.2.beta7 27 Jan 2003
  79604. * - Changed many types to unsigned or unsigned short to avoid warnings
  79605. * - Added inflateCopy() function
  79606. *
  79607. * 1.2.0 9 Mar 2003
  79608. * - Changed inflateBack() interface to provide separate opaque descriptors
  79609. * for the in() and out() functions
  79610. * - Changed inflateBack() argument and in_func typedef to swap the length
  79611. * and buffer address return values for the input function
  79612. * - Check next_in and next_out for Z_NULL on entry to inflate()
  79613. *
  79614. * The history for versions after 1.2.0 are in ChangeLog in zlib distribution.
  79615. */
  79616. /*** Start of inlined file: inffast.h ***/
  79617. /* WARNING: this file should *not* be used by applications. It is
  79618. part of the implementation of the compression library and is
  79619. subject to change. Applications should only use zlib.h.
  79620. */
  79621. void inflate_fast OF((z_streamp strm, unsigned start));
  79622. /*** End of inlined file: inffast.h ***/
  79623. #ifdef MAKEFIXED
  79624. # ifndef BUILDFIXED
  79625. # define BUILDFIXED
  79626. # endif
  79627. #endif
  79628. /* function prototypes */
  79629. local void fixedtables OF((struct inflate_state FAR *state));
  79630. local int updatewindow OF((z_streamp strm, unsigned out));
  79631. #ifdef BUILDFIXED
  79632. void makefixed OF((void));
  79633. #endif
  79634. local unsigned syncsearch OF((unsigned FAR *have, unsigned char FAR *buf,
  79635. unsigned len));
  79636. int ZEXPORT inflateReset (z_streamp strm)
  79637. {
  79638. struct inflate_state FAR *state;
  79639. if (strm == Z_NULL || strm->state == Z_NULL) return Z_STREAM_ERROR;
  79640. state = (struct inflate_state FAR *)strm->state;
  79641. strm->total_in = strm->total_out = state->total = 0;
  79642. strm->msg = Z_NULL;
  79643. strm->adler = 1; /* to support ill-conceived Java test suite */
  79644. state->mode = HEAD;
  79645. state->last = 0;
  79646. state->havedict = 0;
  79647. state->dmax = 32768U;
  79648. state->head = Z_NULL;
  79649. state->wsize = 0;
  79650. state->whave = 0;
  79651. state->write = 0;
  79652. state->hold = 0;
  79653. state->bits = 0;
  79654. state->lencode = state->distcode = state->next = state->codes;
  79655. Tracev((stderr, "inflate: reset\n"));
  79656. return Z_OK;
  79657. }
  79658. int ZEXPORT inflatePrime (z_streamp strm, int bits, int value)
  79659. {
  79660. struct inflate_state FAR *state;
  79661. if (strm == Z_NULL || strm->state == Z_NULL) return Z_STREAM_ERROR;
  79662. state = (struct inflate_state FAR *)strm->state;
  79663. if (bits > 16 || state->bits + bits > 32) return Z_STREAM_ERROR;
  79664. value &= (1L << bits) - 1;
  79665. state->hold += value << state->bits;
  79666. state->bits += bits;
  79667. return Z_OK;
  79668. }
  79669. int ZEXPORT inflateInit2_(z_streamp strm, int windowBits, const char *version, int stream_size)
  79670. {
  79671. struct inflate_state FAR *state;
  79672. if (version == Z_NULL || version[0] != ZLIB_VERSION[0] ||
  79673. stream_size != (int)(sizeof(z_stream)))
  79674. return Z_VERSION_ERROR;
  79675. if (strm == Z_NULL) return Z_STREAM_ERROR;
  79676. strm->msg = Z_NULL; /* in case we return an error */
  79677. if (strm->zalloc == (alloc_func)0) {
  79678. strm->zalloc = zcalloc;
  79679. strm->opaque = (voidpf)0;
  79680. }
  79681. if (strm->zfree == (free_func)0) strm->zfree = zcfree;
  79682. state = (struct inflate_state FAR *)
  79683. ZALLOC(strm, 1, sizeof(struct inflate_state));
  79684. if (state == Z_NULL) return Z_MEM_ERROR;
  79685. Tracev((stderr, "inflate: allocated\n"));
  79686. strm->state = (struct internal_state FAR *)state;
  79687. if (windowBits < 0) {
  79688. state->wrap = 0;
  79689. windowBits = -windowBits;
  79690. }
  79691. else {
  79692. state->wrap = (windowBits >> 4) + 1;
  79693. #ifdef GUNZIP
  79694. if (windowBits < 48) windowBits &= 15;
  79695. #endif
  79696. }
  79697. if (windowBits < 8 || windowBits > 15) {
  79698. ZFREE(strm, state);
  79699. strm->state = Z_NULL;
  79700. return Z_STREAM_ERROR;
  79701. }
  79702. state->wbits = (unsigned)windowBits;
  79703. state->window = Z_NULL;
  79704. return inflateReset(strm);
  79705. }
  79706. int ZEXPORT inflateInit_ (z_streamp strm, const char *version, int stream_size)
  79707. {
  79708. return inflateInit2_(strm, DEF_WBITS, version, stream_size);
  79709. }
  79710. /*
  79711. Return state with length and distance decoding tables and index sizes set to
  79712. fixed code decoding. Normally this returns fixed tables from inffixed.h.
  79713. If BUILDFIXED is defined, then instead this routine builds the tables the
  79714. first time it's called, and returns those tables the first time and
  79715. thereafter. This reduces the size of the code by about 2K bytes, in
  79716. exchange for a little execution time. However, BUILDFIXED should not be
  79717. used for threaded applications, since the rewriting of the tables and virgin
  79718. may not be thread-safe.
  79719. */
  79720. local void fixedtables (struct inflate_state FAR *state)
  79721. {
  79722. #ifdef BUILDFIXED
  79723. static int virgin = 1;
  79724. static code *lenfix, *distfix;
  79725. static code fixed[544];
  79726. /* build fixed huffman tables if first call (may not be thread safe) */
  79727. if (virgin) {
  79728. unsigned sym, bits;
  79729. static code *next;
  79730. /* literal/length table */
  79731. sym = 0;
  79732. while (sym < 144) state->lens[sym++] = 8;
  79733. while (sym < 256) state->lens[sym++] = 9;
  79734. while (sym < 280) state->lens[sym++] = 7;
  79735. while (sym < 288) state->lens[sym++] = 8;
  79736. next = fixed;
  79737. lenfix = next;
  79738. bits = 9;
  79739. inflate_table(LENS, state->lens, 288, &(next), &(bits), state->work);
  79740. /* distance table */
  79741. sym = 0;
  79742. while (sym < 32) state->lens[sym++] = 5;
  79743. distfix = next;
  79744. bits = 5;
  79745. inflate_table(DISTS, state->lens, 32, &(next), &(bits), state->work);
  79746. /* do this just once */
  79747. virgin = 0;
  79748. }
  79749. #else /* !BUILDFIXED */
  79750. /*** Start of inlined file: inffixed.h ***/
  79751. /* WARNING: this file should *not* be used by applications. It
  79752. is part of the implementation of the compression library and
  79753. is subject to change. Applications should only use zlib.h.
  79754. */
  79755. static const code lenfix[512] = {
  79756. {96,7,0},{0,8,80},{0,8,16},{20,8,115},{18,7,31},{0,8,112},{0,8,48},
  79757. {0,9,192},{16,7,10},{0,8,96},{0,8,32},{0,9,160},{0,8,0},{0,8,128},
  79758. {0,8,64},{0,9,224},{16,7,6},{0,8,88},{0,8,24},{0,9,144},{19,7,59},
  79759. {0,8,120},{0,8,56},{0,9,208},{17,7,17},{0,8,104},{0,8,40},{0,9,176},
  79760. {0,8,8},{0,8,136},{0,8,72},{0,9,240},{16,7,4},{0,8,84},{0,8,20},
  79761. {21,8,227},{19,7,43},{0,8,116},{0,8,52},{0,9,200},{17,7,13},{0,8,100},
  79762. {0,8,36},{0,9,168},{0,8,4},{0,8,132},{0,8,68},{0,9,232},{16,7,8},
  79763. {0,8,92},{0,8,28},{0,9,152},{20,7,83},{0,8,124},{0,8,60},{0,9,216},
  79764. {18,7,23},{0,8,108},{0,8,44},{0,9,184},{0,8,12},{0,8,140},{0,8,76},
  79765. {0,9,248},{16,7,3},{0,8,82},{0,8,18},{21,8,163},{19,7,35},{0,8,114},
  79766. {0,8,50},{0,9,196},{17,7,11},{0,8,98},{0,8,34},{0,9,164},{0,8,2},
  79767. {0,8,130},{0,8,66},{0,9,228},{16,7,7},{0,8,90},{0,8,26},{0,9,148},
  79768. {20,7,67},{0,8,122},{0,8,58},{0,9,212},{18,7,19},{0,8,106},{0,8,42},
  79769. {0,9,180},{0,8,10},{0,8,138},{0,8,74},{0,9,244},{16,7,5},{0,8,86},
  79770. {0,8,22},{64,8,0},{19,7,51},{0,8,118},{0,8,54},{0,9,204},{17,7,15},
  79771. {0,8,102},{0,8,38},{0,9,172},{0,8,6},{0,8,134},{0,8,70},{0,9,236},
  79772. {16,7,9},{0,8,94},{0,8,30},{0,9,156},{20,7,99},{0,8,126},{0,8,62},
  79773. {0,9,220},{18,7,27},{0,8,110},{0,8,46},{0,9,188},{0,8,14},{0,8,142},
  79774. {0,8,78},{0,9,252},{96,7,0},{0,8,81},{0,8,17},{21,8,131},{18,7,31},
  79775. {0,8,113},{0,8,49},{0,9,194},{16,7,10},{0,8,97},{0,8,33},{0,9,162},
  79776. {0,8,1},{0,8,129},{0,8,65},{0,9,226},{16,7,6},{0,8,89},{0,8,25},
  79777. {0,9,146},{19,7,59},{0,8,121},{0,8,57},{0,9,210},{17,7,17},{0,8,105},
  79778. {0,8,41},{0,9,178},{0,8,9},{0,8,137},{0,8,73},{0,9,242},{16,7,4},
  79779. {0,8,85},{0,8,21},{16,8,258},{19,7,43},{0,8,117},{0,8,53},{0,9,202},
  79780. {17,7,13},{0,8,101},{0,8,37},{0,9,170},{0,8,5},{0,8,133},{0,8,69},
  79781. {0,9,234},{16,7,8},{0,8,93},{0,8,29},{0,9,154},{20,7,83},{0,8,125},
  79782. {0,8,61},{0,9,218},{18,7,23},{0,8,109},{0,8,45},{0,9,186},{0,8,13},
  79783. {0,8,141},{0,8,77},{0,9,250},{16,7,3},{0,8,83},{0,8,19},{21,8,195},
  79784. {19,7,35},{0,8,115},{0,8,51},{0,9,198},{17,7,11},{0,8,99},{0,8,35},
  79785. {0,9,166},{0,8,3},{0,8,131},{0,8,67},{0,9,230},{16,7,7},{0,8,91},
  79786. {0,8,27},{0,9,150},{20,7,67},{0,8,123},{0,8,59},{0,9,214},{18,7,19},
  79787. {0,8,107},{0,8,43},{0,9,182},{0,8,11},{0,8,139},{0,8,75},{0,9,246},
  79788. {16,7,5},{0,8,87},{0,8,23},{64,8,0},{19,7,51},{0,8,119},{0,8,55},
  79789. {0,9,206},{17,7,15},{0,8,103},{0,8,39},{0,9,174},{0,8,7},{0,8,135},
  79790. {0,8,71},{0,9,238},{16,7,9},{0,8,95},{0,8,31},{0,9,158},{20,7,99},
  79791. {0,8,127},{0,8,63},{0,9,222},{18,7,27},{0,8,111},{0,8,47},{0,9,190},
  79792. {0,8,15},{0,8,143},{0,8,79},{0,9,254},{96,7,0},{0,8,80},{0,8,16},
  79793. {20,8,115},{18,7,31},{0,8,112},{0,8,48},{0,9,193},{16,7,10},{0,8,96},
  79794. {0,8,32},{0,9,161},{0,8,0},{0,8,128},{0,8,64},{0,9,225},{16,7,6},
  79795. {0,8,88},{0,8,24},{0,9,145},{19,7,59},{0,8,120},{0,8,56},{0,9,209},
  79796. {17,7,17},{0,8,104},{0,8,40},{0,9,177},{0,8,8},{0,8,136},{0,8,72},
  79797. {0,9,241},{16,7,4},{0,8,84},{0,8,20},{21,8,227},{19,7,43},{0,8,116},
  79798. {0,8,52},{0,9,201},{17,7,13},{0,8,100},{0,8,36},{0,9,169},{0,8,4},
  79799. {0,8,132},{0,8,68},{0,9,233},{16,7,8},{0,8,92},{0,8,28},{0,9,153},
  79800. {20,7,83},{0,8,124},{0,8,60},{0,9,217},{18,7,23},{0,8,108},{0,8,44},
  79801. {0,9,185},{0,8,12},{0,8,140},{0,8,76},{0,9,249},{16,7,3},{0,8,82},
  79802. {0,8,18},{21,8,163},{19,7,35},{0,8,114},{0,8,50},{0,9,197},{17,7,11},
  79803. {0,8,98},{0,8,34},{0,9,165},{0,8,2},{0,8,130},{0,8,66},{0,9,229},
  79804. {16,7,7},{0,8,90},{0,8,26},{0,9,149},{20,7,67},{0,8,122},{0,8,58},
  79805. {0,9,213},{18,7,19},{0,8,106},{0,8,42},{0,9,181},{0,8,10},{0,8,138},
  79806. {0,8,74},{0,9,245},{16,7,5},{0,8,86},{0,8,22},{64,8,0},{19,7,51},
  79807. {0,8,118},{0,8,54},{0,9,205},{17,7,15},{0,8,102},{0,8,38},{0,9,173},
  79808. {0,8,6},{0,8,134},{0,8,70},{0,9,237},{16,7,9},{0,8,94},{0,8,30},
  79809. {0,9,157},{20,7,99},{0,8,126},{0,8,62},{0,9,221},{18,7,27},{0,8,110},
  79810. {0,8,46},{0,9,189},{0,8,14},{0,8,142},{0,8,78},{0,9,253},{96,7,0},
  79811. {0,8,81},{0,8,17},{21,8,131},{18,7,31},{0,8,113},{0,8,49},{0,9,195},
  79812. {16,7,10},{0,8,97},{0,8,33},{0,9,163},{0,8,1},{0,8,129},{0,8,65},
  79813. {0,9,227},{16,7,6},{0,8,89},{0,8,25},{0,9,147},{19,7,59},{0,8,121},
  79814. {0,8,57},{0,9,211},{17,7,17},{0,8,105},{0,8,41},{0,9,179},{0,8,9},
  79815. {0,8,137},{0,8,73},{0,9,243},{16,7,4},{0,8,85},{0,8,21},{16,8,258},
  79816. {19,7,43},{0,8,117},{0,8,53},{0,9,203},{17,7,13},{0,8,101},{0,8,37},
  79817. {0,9,171},{0,8,5},{0,8,133},{0,8,69},{0,9,235},{16,7,8},{0,8,93},
  79818. {0,8,29},{0,9,155},{20,7,83},{0,8,125},{0,8,61},{0,9,219},{18,7,23},
  79819. {0,8,109},{0,8,45},{0,9,187},{0,8,13},{0,8,141},{0,8,77},{0,9,251},
  79820. {16,7,3},{0,8,83},{0,8,19},{21,8,195},{19,7,35},{0,8,115},{0,8,51},
  79821. {0,9,199},{17,7,11},{0,8,99},{0,8,35},{0,9,167},{0,8,3},{0,8,131},
  79822. {0,8,67},{0,9,231},{16,7,7},{0,8,91},{0,8,27},{0,9,151},{20,7,67},
  79823. {0,8,123},{0,8,59},{0,9,215},{18,7,19},{0,8,107},{0,8,43},{0,9,183},
  79824. {0,8,11},{0,8,139},{0,8,75},{0,9,247},{16,7,5},{0,8,87},{0,8,23},
  79825. {64,8,0},{19,7,51},{0,8,119},{0,8,55},{0,9,207},{17,7,15},{0,8,103},
  79826. {0,8,39},{0,9,175},{0,8,7},{0,8,135},{0,8,71},{0,9,239},{16,7,9},
  79827. {0,8,95},{0,8,31},{0,9,159},{20,7,99},{0,8,127},{0,8,63},{0,9,223},
  79828. {18,7,27},{0,8,111},{0,8,47},{0,9,191},{0,8,15},{0,8,143},{0,8,79},
  79829. {0,9,255}
  79830. };
  79831. static const code distfix[32] = {
  79832. {16,5,1},{23,5,257},{19,5,17},{27,5,4097},{17,5,5},{25,5,1025},
  79833. {21,5,65},{29,5,16385},{16,5,3},{24,5,513},{20,5,33},{28,5,8193},
  79834. {18,5,9},{26,5,2049},{22,5,129},{64,5,0},{16,5,2},{23,5,385},
  79835. {19,5,25},{27,5,6145},{17,5,7},{25,5,1537},{21,5,97},{29,5,24577},
  79836. {16,5,4},{24,5,769},{20,5,49},{28,5,12289},{18,5,13},{26,5,3073},
  79837. {22,5,193},{64,5,0}
  79838. };
  79839. /*** End of inlined file: inffixed.h ***/
  79840. #endif /* BUILDFIXED */
  79841. state->lencode = lenfix;
  79842. state->lenbits = 9;
  79843. state->distcode = distfix;
  79844. state->distbits = 5;
  79845. }
  79846. #ifdef MAKEFIXED
  79847. #include <stdio.h>
  79848. /*
  79849. Write out the inffixed.h that is #include'd above. Defining MAKEFIXED also
  79850. defines BUILDFIXED, so the tables are built on the fly. makefixed() writes
  79851. those tables to stdout, which would be piped to inffixed.h. A small program
  79852. can simply call makefixed to do this:
  79853. void makefixed(void);
  79854. int main(void)
  79855. {
  79856. makefixed();
  79857. return 0;
  79858. }
  79859. Then that can be linked with zlib built with MAKEFIXED defined and run:
  79860. a.out > inffixed.h
  79861. */
  79862. void makefixed()
  79863. {
  79864. unsigned low, size;
  79865. struct inflate_state state;
  79866. fixedtables(&state);
  79867. puts(" /* inffixed.h -- table for decoding fixed codes");
  79868. puts(" * Generated automatically by makefixed().");
  79869. puts(" */");
  79870. puts("");
  79871. puts(" /* WARNING: this file should *not* be used by applications.");
  79872. puts(" It is part of the implementation of this library and is");
  79873. puts(" subject to change. Applications should only use zlib.h.");
  79874. puts(" */");
  79875. puts("");
  79876. size = 1U << 9;
  79877. printf(" static const code lenfix[%u] = {", size);
  79878. low = 0;
  79879. for (;;) {
  79880. if ((low % 7) == 0) printf("\n ");
  79881. printf("{%u,%u,%d}", state.lencode[low].op, state.lencode[low].bits,
  79882. state.lencode[low].val);
  79883. if (++low == size) break;
  79884. putchar(',');
  79885. }
  79886. puts("\n };");
  79887. size = 1U << 5;
  79888. printf("\n static const code distfix[%u] = {", size);
  79889. low = 0;
  79890. for (;;) {
  79891. if ((low % 6) == 0) printf("\n ");
  79892. printf("{%u,%u,%d}", state.distcode[low].op, state.distcode[low].bits,
  79893. state.distcode[low].val);
  79894. if (++low == size) break;
  79895. putchar(',');
  79896. }
  79897. puts("\n };");
  79898. }
  79899. #endif /* MAKEFIXED */
  79900. /*
  79901. Update the window with the last wsize (normally 32K) bytes written before
  79902. returning. If window does not exist yet, create it. This is only called
  79903. when a window is already in use, or when output has been written during this
  79904. inflate call, but the end of the deflate stream has not been reached yet.
  79905. It is also called to create a window for dictionary data when a dictionary
  79906. is loaded.
  79907. Providing output buffers larger than 32K to inflate() should provide a speed
  79908. advantage, since only the last 32K of output is copied to the sliding window
  79909. upon return from inflate(), and since all distances after the first 32K of
  79910. output will fall in the output data, making match copies simpler and faster.
  79911. The advantage may be dependent on the size of the processor's data caches.
  79912. */
  79913. local int updatewindow (z_streamp strm, unsigned out)
  79914. {
  79915. struct inflate_state FAR *state;
  79916. unsigned copy, dist;
  79917. state = (struct inflate_state FAR *)strm->state;
  79918. /* if it hasn't been done already, allocate space for the window */
  79919. if (state->window == Z_NULL) {
  79920. state->window = (unsigned char FAR *)
  79921. ZALLOC(strm, 1U << state->wbits,
  79922. sizeof(unsigned char));
  79923. if (state->window == Z_NULL) return 1;
  79924. }
  79925. /* if window not in use yet, initialize */
  79926. if (state->wsize == 0) {
  79927. state->wsize = 1U << state->wbits;
  79928. state->write = 0;
  79929. state->whave = 0;
  79930. }
  79931. /* copy state->wsize or less output bytes into the circular window */
  79932. copy = out - strm->avail_out;
  79933. if (copy >= state->wsize) {
  79934. zmemcpy(state->window, strm->next_out - state->wsize, state->wsize);
  79935. state->write = 0;
  79936. state->whave = state->wsize;
  79937. }
  79938. else {
  79939. dist = state->wsize - state->write;
  79940. if (dist > copy) dist = copy;
  79941. zmemcpy(state->window + state->write, strm->next_out - copy, dist);
  79942. copy -= dist;
  79943. if (copy) {
  79944. zmemcpy(state->window, strm->next_out - copy, copy);
  79945. state->write = copy;
  79946. state->whave = state->wsize;
  79947. }
  79948. else {
  79949. state->write += dist;
  79950. if (state->write == state->wsize) state->write = 0;
  79951. if (state->whave < state->wsize) state->whave += dist;
  79952. }
  79953. }
  79954. return 0;
  79955. }
  79956. /* Macros for inflate(): */
  79957. /* check function to use adler32() for zlib or crc32() for gzip */
  79958. #ifdef GUNZIP
  79959. # define UPDATE(check, buf, len) \
  79960. (state->flags ? crc32(check, buf, len) : adler32(check, buf, len))
  79961. #else
  79962. # define UPDATE(check, buf, len) adler32(check, buf, len)
  79963. #endif
  79964. /* check macros for header crc */
  79965. #ifdef GUNZIP
  79966. # define CRC2(check, word) \
  79967. do { \
  79968. hbuf[0] = (unsigned char)(word); \
  79969. hbuf[1] = (unsigned char)((word) >> 8); \
  79970. check = crc32(check, hbuf, 2); \
  79971. } while (0)
  79972. # define CRC4(check, word) \
  79973. do { \
  79974. hbuf[0] = (unsigned char)(word); \
  79975. hbuf[1] = (unsigned char)((word) >> 8); \
  79976. hbuf[2] = (unsigned char)((word) >> 16); \
  79977. hbuf[3] = (unsigned char)((word) >> 24); \
  79978. check = crc32(check, hbuf, 4); \
  79979. } while (0)
  79980. #endif
  79981. /* Load registers with state in inflate() for speed */
  79982. #define LOAD() \
  79983. do { \
  79984. put = strm->next_out; \
  79985. left = strm->avail_out; \
  79986. next = strm->next_in; \
  79987. have = strm->avail_in; \
  79988. hold = state->hold; \
  79989. bits = state->bits; \
  79990. } while (0)
  79991. /* Restore state from registers in inflate() */
  79992. #define RESTORE() \
  79993. do { \
  79994. strm->next_out = put; \
  79995. strm->avail_out = left; \
  79996. strm->next_in = next; \
  79997. strm->avail_in = have; \
  79998. state->hold = hold; \
  79999. state->bits = bits; \
  80000. } while (0)
  80001. /* Clear the input bit accumulator */
  80002. #define INITBITS() \
  80003. do { \
  80004. hold = 0; \
  80005. bits = 0; \
  80006. } while (0)
  80007. /* Get a byte of input into the bit accumulator, or return from inflate()
  80008. if there is no input available. */
  80009. #define PULLBYTE() \
  80010. do { \
  80011. if (have == 0) goto inf_leave; \
  80012. have--; \
  80013. hold += (unsigned long)(*next++) << bits; \
  80014. bits += 8; \
  80015. } while (0)
  80016. /* Assure that there are at least n bits in the bit accumulator. If there is
  80017. not enough available input to do that, then return from inflate(). */
  80018. #define NEEDBITS(n) \
  80019. do { \
  80020. while (bits < (unsigned)(n)) \
  80021. PULLBYTE(); \
  80022. } while (0)
  80023. /* Return the low n bits of the bit accumulator (n < 16) */
  80024. #define BITS(n) \
  80025. ((unsigned)hold & ((1U << (n)) - 1))
  80026. /* Remove n bits from the bit accumulator */
  80027. #define DROPBITS(n) \
  80028. do { \
  80029. hold >>= (n); \
  80030. bits -= (unsigned)(n); \
  80031. } while (0)
  80032. /* Remove zero to seven bits as needed to go to a byte boundary */
  80033. #define BYTEBITS() \
  80034. do { \
  80035. hold >>= bits & 7; \
  80036. bits -= bits & 7; \
  80037. } while (0)
  80038. /* Reverse the bytes in a 32-bit value */
  80039. #define REVERSE(q) \
  80040. ((((q) >> 24) & 0xff) + (((q) >> 8) & 0xff00) + \
  80041. (((q) & 0xff00) << 8) + (((q) & 0xff) << 24))
  80042. /*
  80043. inflate() uses a state machine to process as much input data and generate as
  80044. much output data as possible before returning. The state machine is
  80045. structured roughly as follows:
  80046. for (;;) switch (state) {
  80047. ...
  80048. case STATEn:
  80049. if (not enough input data or output space to make progress)
  80050. return;
  80051. ... make progress ...
  80052. state = STATEm;
  80053. break;
  80054. ...
  80055. }
  80056. so when inflate() is called again, the same case is attempted again, and
  80057. if the appropriate resources are provided, the machine proceeds to the
  80058. next state. The NEEDBITS() macro is usually the way the state evaluates
  80059. whether it can proceed or should return. NEEDBITS() does the return if
  80060. the requested bits are not available. The typical use of the BITS macros
  80061. is:
  80062. NEEDBITS(n);
  80063. ... do something with BITS(n) ...
  80064. DROPBITS(n);
  80065. where NEEDBITS(n) either returns from inflate() if there isn't enough
  80066. input left to load n bits into the accumulator, or it continues. BITS(n)
  80067. gives the low n bits in the accumulator. When done, DROPBITS(n) drops
  80068. the low n bits off the accumulator. INITBITS() clears the accumulator
  80069. and sets the number of available bits to zero. BYTEBITS() discards just
  80070. enough bits to put the accumulator on a byte boundary. After BYTEBITS()
  80071. and a NEEDBITS(8), then BITS(8) would return the next byte in the stream.
  80072. NEEDBITS(n) uses PULLBYTE() to get an available byte of input, or to return
  80073. if there is no input available. The decoding of variable length codes uses
  80074. PULLBYTE() directly in order to pull just enough bytes to decode the next
  80075. code, and no more.
  80076. Some states loop until they get enough input, making sure that enough
  80077. state information is maintained to continue the loop where it left off
  80078. if NEEDBITS() returns in the loop. For example, want, need, and keep
  80079. would all have to actually be part of the saved state in case NEEDBITS()
  80080. returns:
  80081. case STATEw:
  80082. while (want < need) {
  80083. NEEDBITS(n);
  80084. keep[want++] = BITS(n);
  80085. DROPBITS(n);
  80086. }
  80087. state = STATEx;
  80088. case STATEx:
  80089. As shown above, if the next state is also the next case, then the break
  80090. is omitted.
  80091. A state may also return if there is not enough output space available to
  80092. complete that state. Those states are copying stored data, writing a
  80093. literal byte, and copying a matching string.
  80094. When returning, a "goto inf_leave" is used to update the total counters,
  80095. update the check value, and determine whether any progress has been made
  80096. during that inflate() call in order to return the proper return code.
  80097. Progress is defined as a change in either strm->avail_in or strm->avail_out.
  80098. When there is a window, goto inf_leave will update the window with the last
  80099. output written. If a goto inf_leave occurs in the middle of decompression
  80100. and there is no window currently, goto inf_leave will create one and copy
  80101. output to the window for the next call of inflate().
  80102. In this implementation, the flush parameter of inflate() only affects the
  80103. return code (per zlib.h). inflate() always writes as much as possible to
  80104. strm->next_out, given the space available and the provided input--the effect
  80105. documented in zlib.h of Z_SYNC_FLUSH. Furthermore, inflate() always defers
  80106. the allocation of and copying into a sliding window until necessary, which
  80107. provides the effect documented in zlib.h for Z_FINISH when the entire input
  80108. stream available. So the only thing the flush parameter actually does is:
  80109. when flush is set to Z_FINISH, inflate() cannot return Z_OK. Instead it
  80110. will return Z_BUF_ERROR if it has not reached the end of the stream.
  80111. */
  80112. int ZEXPORT inflate (z_streamp strm, int flush)
  80113. {
  80114. struct inflate_state FAR *state;
  80115. unsigned char FAR *next; /* next input */
  80116. unsigned char FAR *put; /* next output */
  80117. unsigned have, left; /* available input and output */
  80118. unsigned long hold; /* bit buffer */
  80119. unsigned bits; /* bits in bit buffer */
  80120. unsigned in, out; /* save starting available input and output */
  80121. unsigned copy; /* number of stored or match bytes to copy */
  80122. unsigned char FAR *from; /* where to copy match bytes from */
  80123. code thisx; /* current decoding table entry */
  80124. code last; /* parent table entry */
  80125. unsigned len; /* length to copy for repeats, bits to drop */
  80126. int ret; /* return code */
  80127. #ifdef GUNZIP
  80128. unsigned char hbuf[4]; /* buffer for gzip header crc calculation */
  80129. #endif
  80130. static const unsigned short order[19] = /* permutation of code lengths */
  80131. {16, 17, 18, 0, 8, 7, 9, 6, 10, 5, 11, 4, 12, 3, 13, 2, 14, 1, 15};
  80132. if (strm == Z_NULL || strm->state == Z_NULL || strm->next_out == Z_NULL ||
  80133. (strm->next_in == Z_NULL && strm->avail_in != 0))
  80134. return Z_STREAM_ERROR;
  80135. state = (struct inflate_state FAR *)strm->state;
  80136. if (state->mode == TYPE) state->mode = TYPEDO; /* skip check */
  80137. LOAD();
  80138. in = have;
  80139. out = left;
  80140. ret = Z_OK;
  80141. for (;;)
  80142. switch (state->mode) {
  80143. case HEAD:
  80144. if (state->wrap == 0) {
  80145. state->mode = TYPEDO;
  80146. break;
  80147. }
  80148. NEEDBITS(16);
  80149. #ifdef GUNZIP
  80150. if ((state->wrap & 2) && hold == 0x8b1f) { /* gzip header */
  80151. state->check = crc32(0L, Z_NULL, 0);
  80152. CRC2(state->check, hold);
  80153. INITBITS();
  80154. state->mode = FLAGS;
  80155. break;
  80156. }
  80157. state->flags = 0; /* expect zlib header */
  80158. if (state->head != Z_NULL)
  80159. state->head->done = -1;
  80160. if (!(state->wrap & 1) || /* check if zlib header allowed */
  80161. #else
  80162. if (
  80163. #endif
  80164. ((BITS(8) << 8) + (hold >> 8)) % 31) {
  80165. strm->msg = (char *)"incorrect header check";
  80166. state->mode = BAD;
  80167. break;
  80168. }
  80169. if (BITS(4) != Z_DEFLATED) {
  80170. strm->msg = (char *)"unknown compression method";
  80171. state->mode = BAD;
  80172. break;
  80173. }
  80174. DROPBITS(4);
  80175. len = BITS(4) + 8;
  80176. if (len > state->wbits) {
  80177. strm->msg = (char *)"invalid window size";
  80178. state->mode = BAD;
  80179. break;
  80180. }
  80181. state->dmax = 1U << len;
  80182. Tracev((stderr, "inflate: zlib header ok\n"));
  80183. strm->adler = state->check = adler32(0L, Z_NULL, 0);
  80184. state->mode = hold & 0x200 ? DICTID : TYPE;
  80185. INITBITS();
  80186. break;
  80187. #ifdef GUNZIP
  80188. case FLAGS:
  80189. NEEDBITS(16);
  80190. state->flags = (int)(hold);
  80191. if ((state->flags & 0xff) != Z_DEFLATED) {
  80192. strm->msg = (char *)"unknown compression method";
  80193. state->mode = BAD;
  80194. break;
  80195. }
  80196. if (state->flags & 0xe000) {
  80197. strm->msg = (char *)"unknown header flags set";
  80198. state->mode = BAD;
  80199. break;
  80200. }
  80201. if (state->head != Z_NULL)
  80202. state->head->text = (int)((hold >> 8) & 1);
  80203. if (state->flags & 0x0200) CRC2(state->check, hold);
  80204. INITBITS();
  80205. state->mode = TIME;
  80206. case TIME:
  80207. NEEDBITS(32);
  80208. if (state->head != Z_NULL)
  80209. state->head->time = hold;
  80210. if (state->flags & 0x0200) CRC4(state->check, hold);
  80211. INITBITS();
  80212. state->mode = OS;
  80213. case OS:
  80214. NEEDBITS(16);
  80215. if (state->head != Z_NULL) {
  80216. state->head->xflags = (int)(hold & 0xff);
  80217. state->head->os = (int)(hold >> 8);
  80218. }
  80219. if (state->flags & 0x0200) CRC2(state->check, hold);
  80220. INITBITS();
  80221. state->mode = EXLEN;
  80222. case EXLEN:
  80223. if (state->flags & 0x0400) {
  80224. NEEDBITS(16);
  80225. state->length = (unsigned)(hold);
  80226. if (state->head != Z_NULL)
  80227. state->head->extra_len = (unsigned)hold;
  80228. if (state->flags & 0x0200) CRC2(state->check, hold);
  80229. INITBITS();
  80230. }
  80231. else if (state->head != Z_NULL)
  80232. state->head->extra = Z_NULL;
  80233. state->mode = EXTRA;
  80234. case EXTRA:
  80235. if (state->flags & 0x0400) {
  80236. copy = state->length;
  80237. if (copy > have) copy = have;
  80238. if (copy) {
  80239. if (state->head != Z_NULL &&
  80240. state->head->extra != Z_NULL) {
  80241. len = state->head->extra_len - state->length;
  80242. zmemcpy(state->head->extra + len, next,
  80243. len + copy > state->head->extra_max ?
  80244. state->head->extra_max - len : copy);
  80245. }
  80246. if (state->flags & 0x0200)
  80247. state->check = crc32(state->check, next, copy);
  80248. have -= copy;
  80249. next += copy;
  80250. state->length -= copy;
  80251. }
  80252. if (state->length) goto inf_leave;
  80253. }
  80254. state->length = 0;
  80255. state->mode = NAME;
  80256. case NAME:
  80257. if (state->flags & 0x0800) {
  80258. if (have == 0) goto inf_leave;
  80259. copy = 0;
  80260. do {
  80261. len = (unsigned)(next[copy++]);
  80262. if (state->head != Z_NULL &&
  80263. state->head->name != Z_NULL &&
  80264. state->length < state->head->name_max)
  80265. state->head->name[state->length++] = len;
  80266. } while (len && copy < have);
  80267. if (state->flags & 0x0200)
  80268. state->check = crc32(state->check, next, copy);
  80269. have -= copy;
  80270. next += copy;
  80271. if (len) goto inf_leave;
  80272. }
  80273. else if (state->head != Z_NULL)
  80274. state->head->name = Z_NULL;
  80275. state->length = 0;
  80276. state->mode = COMMENT;
  80277. case COMMENT:
  80278. if (state->flags & 0x1000) {
  80279. if (have == 0) goto inf_leave;
  80280. copy = 0;
  80281. do {
  80282. len = (unsigned)(next[copy++]);
  80283. if (state->head != Z_NULL &&
  80284. state->head->comment != Z_NULL &&
  80285. state->length < state->head->comm_max)
  80286. state->head->comment[state->length++] = len;
  80287. } while (len && copy < have);
  80288. if (state->flags & 0x0200)
  80289. state->check = crc32(state->check, next, copy);
  80290. have -= copy;
  80291. next += copy;
  80292. if (len) goto inf_leave;
  80293. }
  80294. else if (state->head != Z_NULL)
  80295. state->head->comment = Z_NULL;
  80296. state->mode = HCRC;
  80297. case HCRC:
  80298. if (state->flags & 0x0200) {
  80299. NEEDBITS(16);
  80300. if (hold != (state->check & 0xffff)) {
  80301. strm->msg = (char *)"header crc mismatch";
  80302. state->mode = BAD;
  80303. break;
  80304. }
  80305. INITBITS();
  80306. }
  80307. if (state->head != Z_NULL) {
  80308. state->head->hcrc = (int)((state->flags >> 9) & 1);
  80309. state->head->done = 1;
  80310. }
  80311. strm->adler = state->check = crc32(0L, Z_NULL, 0);
  80312. state->mode = TYPE;
  80313. break;
  80314. #endif
  80315. case DICTID:
  80316. NEEDBITS(32);
  80317. strm->adler = state->check = REVERSE(hold);
  80318. INITBITS();
  80319. state->mode = DICT;
  80320. case DICT:
  80321. if (state->havedict == 0) {
  80322. RESTORE();
  80323. return Z_NEED_DICT;
  80324. }
  80325. strm->adler = state->check = adler32(0L, Z_NULL, 0);
  80326. state->mode = TYPE;
  80327. case TYPE:
  80328. if (flush == Z_BLOCK) goto inf_leave;
  80329. case TYPEDO:
  80330. if (state->last) {
  80331. BYTEBITS();
  80332. state->mode = CHECK;
  80333. break;
  80334. }
  80335. NEEDBITS(3);
  80336. state->last = BITS(1);
  80337. DROPBITS(1);
  80338. switch (BITS(2)) {
  80339. case 0: /* stored block */
  80340. Tracev((stderr, "inflate: stored block%s\n",
  80341. state->last ? " (last)" : ""));
  80342. state->mode = STORED;
  80343. break;
  80344. case 1: /* fixed block */
  80345. fixedtables(state);
  80346. Tracev((stderr, "inflate: fixed codes block%s\n",
  80347. state->last ? " (last)" : ""));
  80348. state->mode = LEN; /* decode codes */
  80349. break;
  80350. case 2: /* dynamic block */
  80351. Tracev((stderr, "inflate: dynamic codes block%s\n",
  80352. state->last ? " (last)" : ""));
  80353. state->mode = TABLE;
  80354. break;
  80355. case 3:
  80356. strm->msg = (char *)"invalid block type";
  80357. state->mode = BAD;
  80358. }
  80359. DROPBITS(2);
  80360. break;
  80361. case STORED:
  80362. BYTEBITS(); /* go to byte boundary */
  80363. NEEDBITS(32);
  80364. if ((hold & 0xffff) != ((hold >> 16) ^ 0xffff)) {
  80365. strm->msg = (char *)"invalid stored block lengths";
  80366. state->mode = BAD;
  80367. break;
  80368. }
  80369. state->length = (unsigned)hold & 0xffff;
  80370. Tracev((stderr, "inflate: stored length %u\n",
  80371. state->length));
  80372. INITBITS();
  80373. state->mode = COPY;
  80374. case COPY:
  80375. copy = state->length;
  80376. if (copy) {
  80377. if (copy > have) copy = have;
  80378. if (copy > left) copy = left;
  80379. if (copy == 0) goto inf_leave;
  80380. zmemcpy(put, next, copy);
  80381. have -= copy;
  80382. next += copy;
  80383. left -= copy;
  80384. put += copy;
  80385. state->length -= copy;
  80386. break;
  80387. }
  80388. Tracev((stderr, "inflate: stored end\n"));
  80389. state->mode = TYPE;
  80390. break;
  80391. case TABLE:
  80392. NEEDBITS(14);
  80393. state->nlen = BITS(5) + 257;
  80394. DROPBITS(5);
  80395. state->ndist = BITS(5) + 1;
  80396. DROPBITS(5);
  80397. state->ncode = BITS(4) + 4;
  80398. DROPBITS(4);
  80399. #ifndef PKZIP_BUG_WORKAROUND
  80400. if (state->nlen > 286 || state->ndist > 30) {
  80401. strm->msg = (char *)"too many length or distance symbols";
  80402. state->mode = BAD;
  80403. break;
  80404. }
  80405. #endif
  80406. Tracev((stderr, "inflate: table sizes ok\n"));
  80407. state->have = 0;
  80408. state->mode = LENLENS;
  80409. case LENLENS:
  80410. while (state->have < state->ncode) {
  80411. NEEDBITS(3);
  80412. state->lens[order[state->have++]] = (unsigned short)BITS(3);
  80413. DROPBITS(3);
  80414. }
  80415. while (state->have < 19)
  80416. state->lens[order[state->have++]] = 0;
  80417. state->next = state->codes;
  80418. state->lencode = (code const FAR *)(state->next);
  80419. state->lenbits = 7;
  80420. ret = inflate_table(CODES, state->lens, 19, &(state->next),
  80421. &(state->lenbits), state->work);
  80422. if (ret) {
  80423. strm->msg = (char *)"invalid code lengths set";
  80424. state->mode = BAD;
  80425. break;
  80426. }
  80427. Tracev((stderr, "inflate: code lengths ok\n"));
  80428. state->have = 0;
  80429. state->mode = CODELENS;
  80430. case CODELENS:
  80431. while (state->have < state->nlen + state->ndist) {
  80432. for (;;) {
  80433. thisx = state->lencode[BITS(state->lenbits)];
  80434. if ((unsigned)(thisx.bits) <= bits) break;
  80435. PULLBYTE();
  80436. }
  80437. if (thisx.val < 16) {
  80438. NEEDBITS(thisx.bits);
  80439. DROPBITS(thisx.bits);
  80440. state->lens[state->have++] = thisx.val;
  80441. }
  80442. else {
  80443. if (thisx.val == 16) {
  80444. NEEDBITS(thisx.bits + 2);
  80445. DROPBITS(thisx.bits);
  80446. if (state->have == 0) {
  80447. strm->msg = (char *)"invalid bit length repeat";
  80448. state->mode = BAD;
  80449. break;
  80450. }
  80451. len = state->lens[state->have - 1];
  80452. copy = 3 + BITS(2);
  80453. DROPBITS(2);
  80454. }
  80455. else if (thisx.val == 17) {
  80456. NEEDBITS(thisx.bits + 3);
  80457. DROPBITS(thisx.bits);
  80458. len = 0;
  80459. copy = 3 + BITS(3);
  80460. DROPBITS(3);
  80461. }
  80462. else {
  80463. NEEDBITS(thisx.bits + 7);
  80464. DROPBITS(thisx.bits);
  80465. len = 0;
  80466. copy = 11 + BITS(7);
  80467. DROPBITS(7);
  80468. }
  80469. if (state->have + copy > state->nlen + state->ndist) {
  80470. strm->msg = (char *)"invalid bit length repeat";
  80471. state->mode = BAD;
  80472. break;
  80473. }
  80474. while (copy--)
  80475. state->lens[state->have++] = (unsigned short)len;
  80476. }
  80477. }
  80478. /* handle error breaks in while */
  80479. if (state->mode == BAD) break;
  80480. /* build code tables */
  80481. state->next = state->codes;
  80482. state->lencode = (code const FAR *)(state->next);
  80483. state->lenbits = 9;
  80484. ret = inflate_table(LENS, state->lens, state->nlen, &(state->next),
  80485. &(state->lenbits), state->work);
  80486. if (ret) {
  80487. strm->msg = (char *)"invalid literal/lengths set";
  80488. state->mode = BAD;
  80489. break;
  80490. }
  80491. state->distcode = (code const FAR *)(state->next);
  80492. state->distbits = 6;
  80493. ret = inflate_table(DISTS, state->lens + state->nlen, state->ndist,
  80494. &(state->next), &(state->distbits), state->work);
  80495. if (ret) {
  80496. strm->msg = (char *)"invalid distances set";
  80497. state->mode = BAD;
  80498. break;
  80499. }
  80500. Tracev((stderr, "inflate: codes ok\n"));
  80501. state->mode = LEN;
  80502. case LEN:
  80503. if (have >= 6 && left >= 258) {
  80504. RESTORE();
  80505. inflate_fast(strm, out);
  80506. LOAD();
  80507. break;
  80508. }
  80509. for (;;) {
  80510. thisx = state->lencode[BITS(state->lenbits)];
  80511. if ((unsigned)(thisx.bits) <= bits) break;
  80512. PULLBYTE();
  80513. }
  80514. if (thisx.op && (thisx.op & 0xf0) == 0) {
  80515. last = thisx;
  80516. for (;;) {
  80517. thisx = state->lencode[last.val +
  80518. (BITS(last.bits + last.op) >> last.bits)];
  80519. if ((unsigned)(last.bits + thisx.bits) <= bits) break;
  80520. PULLBYTE();
  80521. }
  80522. DROPBITS(last.bits);
  80523. }
  80524. DROPBITS(thisx.bits);
  80525. state->length = (unsigned)thisx.val;
  80526. if ((int)(thisx.op) == 0) {
  80527. Tracevv((stderr, thisx.val >= 0x20 && thisx.val < 0x7f ?
  80528. "inflate: literal '%c'\n" :
  80529. "inflate: literal 0x%02x\n", thisx.val));
  80530. state->mode = LIT;
  80531. break;
  80532. }
  80533. if (thisx.op & 32) {
  80534. Tracevv((stderr, "inflate: end of block\n"));
  80535. state->mode = TYPE;
  80536. break;
  80537. }
  80538. if (thisx.op & 64) {
  80539. strm->msg = (char *)"invalid literal/length code";
  80540. state->mode = BAD;
  80541. break;
  80542. }
  80543. state->extra = (unsigned)(thisx.op) & 15;
  80544. state->mode = LENEXT;
  80545. case LENEXT:
  80546. if (state->extra) {
  80547. NEEDBITS(state->extra);
  80548. state->length += BITS(state->extra);
  80549. DROPBITS(state->extra);
  80550. }
  80551. Tracevv((stderr, "inflate: length %u\n", state->length));
  80552. state->mode = DIST;
  80553. case DIST:
  80554. for (;;) {
  80555. thisx = state->distcode[BITS(state->distbits)];
  80556. if ((unsigned)(thisx.bits) <= bits) break;
  80557. PULLBYTE();
  80558. }
  80559. if ((thisx.op & 0xf0) == 0) {
  80560. last = thisx;
  80561. for (;;) {
  80562. thisx = state->distcode[last.val +
  80563. (BITS(last.bits + last.op) >> last.bits)];
  80564. if ((unsigned)(last.bits + thisx.bits) <= bits) break;
  80565. PULLBYTE();
  80566. }
  80567. DROPBITS(last.bits);
  80568. }
  80569. DROPBITS(thisx.bits);
  80570. if (thisx.op & 64) {
  80571. strm->msg = (char *)"invalid distance code";
  80572. state->mode = BAD;
  80573. break;
  80574. }
  80575. state->offset = (unsigned)thisx.val;
  80576. state->extra = (unsigned)(thisx.op) & 15;
  80577. state->mode = DISTEXT;
  80578. case DISTEXT:
  80579. if (state->extra) {
  80580. NEEDBITS(state->extra);
  80581. state->offset += BITS(state->extra);
  80582. DROPBITS(state->extra);
  80583. }
  80584. #ifdef INFLATE_STRICT
  80585. if (state->offset > state->dmax) {
  80586. strm->msg = (char *)"invalid distance too far back";
  80587. state->mode = BAD;
  80588. break;
  80589. }
  80590. #endif
  80591. if (state->offset > state->whave + out - left) {
  80592. strm->msg = (char *)"invalid distance too far back";
  80593. state->mode = BAD;
  80594. break;
  80595. }
  80596. Tracevv((stderr, "inflate: distance %u\n", state->offset));
  80597. state->mode = MATCH;
  80598. case MATCH:
  80599. if (left == 0) goto inf_leave;
  80600. copy = out - left;
  80601. if (state->offset > copy) { /* copy from window */
  80602. copy = state->offset - copy;
  80603. if (copy > state->write) {
  80604. copy -= state->write;
  80605. from = state->window + (state->wsize - copy);
  80606. }
  80607. else
  80608. from = state->window + (state->write - copy);
  80609. if (copy > state->length) copy = state->length;
  80610. }
  80611. else { /* copy from output */
  80612. from = put - state->offset;
  80613. copy = state->length;
  80614. }
  80615. if (copy > left) copy = left;
  80616. left -= copy;
  80617. state->length -= copy;
  80618. do {
  80619. *put++ = *from++;
  80620. } while (--copy);
  80621. if (state->length == 0) state->mode = LEN;
  80622. break;
  80623. case LIT:
  80624. if (left == 0) goto inf_leave;
  80625. *put++ = (unsigned char)(state->length);
  80626. left--;
  80627. state->mode = LEN;
  80628. break;
  80629. case CHECK:
  80630. if (state->wrap) {
  80631. NEEDBITS(32);
  80632. out -= left;
  80633. strm->total_out += out;
  80634. state->total += out;
  80635. if (out)
  80636. strm->adler = state->check =
  80637. UPDATE(state->check, put - out, out);
  80638. out = left;
  80639. if ((
  80640. #ifdef GUNZIP
  80641. state->flags ? hold :
  80642. #endif
  80643. REVERSE(hold)) != state->check) {
  80644. strm->msg = (char *)"incorrect data check";
  80645. state->mode = BAD;
  80646. break;
  80647. }
  80648. INITBITS();
  80649. Tracev((stderr, "inflate: check matches trailer\n"));
  80650. }
  80651. #ifdef GUNZIP
  80652. state->mode = LENGTH;
  80653. case LENGTH:
  80654. if (state->wrap && state->flags) {
  80655. NEEDBITS(32);
  80656. if (hold != (state->total & 0xffffffffUL)) {
  80657. strm->msg = (char *)"incorrect length check";
  80658. state->mode = BAD;
  80659. break;
  80660. }
  80661. INITBITS();
  80662. Tracev((stderr, "inflate: length matches trailer\n"));
  80663. }
  80664. #endif
  80665. state->mode = DONE;
  80666. case DONE:
  80667. ret = Z_STREAM_END;
  80668. goto inf_leave;
  80669. case BAD:
  80670. ret = Z_DATA_ERROR;
  80671. goto inf_leave;
  80672. case MEM:
  80673. return Z_MEM_ERROR;
  80674. case SYNC:
  80675. default:
  80676. return Z_STREAM_ERROR;
  80677. }
  80678. /*
  80679. Return from inflate(), updating the total counts and the check value.
  80680. If there was no progress during the inflate() call, return a buffer
  80681. error. Call updatewindow() to create and/or update the window state.
  80682. Note: a memory error from inflate() is non-recoverable.
  80683. */
  80684. inf_leave:
  80685. RESTORE();
  80686. if (state->wsize || (state->mode < CHECK && out != strm->avail_out))
  80687. if (updatewindow(strm, out)) {
  80688. state->mode = MEM;
  80689. return Z_MEM_ERROR;
  80690. }
  80691. in -= strm->avail_in;
  80692. out -= strm->avail_out;
  80693. strm->total_in += in;
  80694. strm->total_out += out;
  80695. state->total += out;
  80696. if (state->wrap && out)
  80697. strm->adler = state->check =
  80698. UPDATE(state->check, strm->next_out - out, out);
  80699. strm->data_type = state->bits + (state->last ? 64 : 0) +
  80700. (state->mode == TYPE ? 128 : 0);
  80701. if (((in == 0 && out == 0) || flush == Z_FINISH) && ret == Z_OK)
  80702. ret = Z_BUF_ERROR;
  80703. return ret;
  80704. }
  80705. int ZEXPORT inflateEnd (z_streamp strm)
  80706. {
  80707. struct inflate_state FAR *state;
  80708. if (strm == Z_NULL || strm->state == Z_NULL || strm->zfree == (free_func)0)
  80709. return Z_STREAM_ERROR;
  80710. state = (struct inflate_state FAR *)strm->state;
  80711. if (state->window != Z_NULL) ZFREE(strm, state->window);
  80712. ZFREE(strm, strm->state);
  80713. strm->state = Z_NULL;
  80714. Tracev((stderr, "inflate: end\n"));
  80715. return Z_OK;
  80716. }
  80717. int ZEXPORT inflateSetDictionary (z_streamp strm, const Bytef *dictionary, uInt dictLength)
  80718. {
  80719. struct inflate_state FAR *state;
  80720. unsigned long id_;
  80721. /* check state */
  80722. if (strm == Z_NULL || strm->state == Z_NULL) return Z_STREAM_ERROR;
  80723. state = (struct inflate_state FAR *)strm->state;
  80724. if (state->wrap != 0 && state->mode != DICT)
  80725. return Z_STREAM_ERROR;
  80726. /* check for correct dictionary id */
  80727. if (state->mode == DICT) {
  80728. id_ = adler32(0L, Z_NULL, 0);
  80729. id_ = adler32(id_, dictionary, dictLength);
  80730. if (id_ != state->check)
  80731. return Z_DATA_ERROR;
  80732. }
  80733. /* copy dictionary to window */
  80734. if (updatewindow(strm, strm->avail_out)) {
  80735. state->mode = MEM;
  80736. return Z_MEM_ERROR;
  80737. }
  80738. if (dictLength > state->wsize) {
  80739. zmemcpy(state->window, dictionary + dictLength - state->wsize,
  80740. state->wsize);
  80741. state->whave = state->wsize;
  80742. }
  80743. else {
  80744. zmemcpy(state->window + state->wsize - dictLength, dictionary,
  80745. dictLength);
  80746. state->whave = dictLength;
  80747. }
  80748. state->havedict = 1;
  80749. Tracev((stderr, "inflate: dictionary set\n"));
  80750. return Z_OK;
  80751. }
  80752. int ZEXPORT inflateGetHeader (z_streamp strm, gz_headerp head)
  80753. {
  80754. struct inflate_state FAR *state;
  80755. /* check state */
  80756. if (strm == Z_NULL || strm->state == Z_NULL) return Z_STREAM_ERROR;
  80757. state = (struct inflate_state FAR *)strm->state;
  80758. if ((state->wrap & 2) == 0) return Z_STREAM_ERROR;
  80759. /* save header structure */
  80760. state->head = head;
  80761. head->done = 0;
  80762. return Z_OK;
  80763. }
  80764. /*
  80765. Search buf[0..len-1] for the pattern: 0, 0, 0xff, 0xff. Return when found
  80766. or when out of input. When called, *have is the number of pattern bytes
  80767. found in order so far, in 0..3. On return *have is updated to the new
  80768. state. If on return *have equals four, then the pattern was found and the
  80769. return value is how many bytes were read including the last byte of the
  80770. pattern. If *have is less than four, then the pattern has not been found
  80771. yet and the return value is len. In the latter case, syncsearch() can be
  80772. called again with more data and the *have state. *have is initialized to
  80773. zero for the first call.
  80774. */
  80775. local unsigned syncsearch (unsigned FAR *have, unsigned char FAR *buf, unsigned len)
  80776. {
  80777. unsigned got;
  80778. unsigned next;
  80779. got = *have;
  80780. next = 0;
  80781. while (next < len && got < 4) {
  80782. if ((int)(buf[next]) == (got < 2 ? 0 : 0xff))
  80783. got++;
  80784. else if (buf[next])
  80785. got = 0;
  80786. else
  80787. got = 4 - got;
  80788. next++;
  80789. }
  80790. *have = got;
  80791. return next;
  80792. }
  80793. int ZEXPORT inflateSync (z_streamp strm)
  80794. {
  80795. unsigned len; /* number of bytes to look at or looked at */
  80796. unsigned long in, out; /* temporary to save total_in and total_out */
  80797. unsigned char buf[4]; /* to restore bit buffer to byte string */
  80798. struct inflate_state FAR *state;
  80799. /* check parameters */
  80800. if (strm == Z_NULL || strm->state == Z_NULL) return Z_STREAM_ERROR;
  80801. state = (struct inflate_state FAR *)strm->state;
  80802. if (strm->avail_in == 0 && state->bits < 8) return Z_BUF_ERROR;
  80803. /* if first time, start search in bit buffer */
  80804. if (state->mode != SYNC) {
  80805. state->mode = SYNC;
  80806. state->hold <<= state->bits & 7;
  80807. state->bits -= state->bits & 7;
  80808. len = 0;
  80809. while (state->bits >= 8) {
  80810. buf[len++] = (unsigned char)(state->hold);
  80811. state->hold >>= 8;
  80812. state->bits -= 8;
  80813. }
  80814. state->have = 0;
  80815. syncsearch(&(state->have), buf, len);
  80816. }
  80817. /* search available input */
  80818. len = syncsearch(&(state->have), strm->next_in, strm->avail_in);
  80819. strm->avail_in -= len;
  80820. strm->next_in += len;
  80821. strm->total_in += len;
  80822. /* return no joy or set up to restart inflate() on a new block */
  80823. if (state->have != 4) return Z_DATA_ERROR;
  80824. in = strm->total_in; out = strm->total_out;
  80825. inflateReset(strm);
  80826. strm->total_in = in; strm->total_out = out;
  80827. state->mode = TYPE;
  80828. return Z_OK;
  80829. }
  80830. /*
  80831. Returns true if inflate is currently at the end of a block generated by
  80832. Z_SYNC_FLUSH or Z_FULL_FLUSH. This function is used by one PPP
  80833. implementation to provide an additional safety check. PPP uses
  80834. Z_SYNC_FLUSH but removes the length bytes of the resulting empty stored
  80835. block. When decompressing, PPP checks that at the end of input packet,
  80836. inflate is waiting for these length bytes.
  80837. */
  80838. int ZEXPORT inflateSyncPoint (z_streamp strm)
  80839. {
  80840. struct inflate_state FAR *state;
  80841. if (strm == Z_NULL || strm->state == Z_NULL) return Z_STREAM_ERROR;
  80842. state = (struct inflate_state FAR *)strm->state;
  80843. return state->mode == STORED && state->bits == 0;
  80844. }
  80845. int ZEXPORT inflateCopy(z_streamp dest, z_streamp source)
  80846. {
  80847. struct inflate_state FAR *state;
  80848. struct inflate_state FAR *copy;
  80849. unsigned char FAR *window;
  80850. unsigned wsize;
  80851. /* check input */
  80852. if (dest == Z_NULL || source == Z_NULL || source->state == Z_NULL ||
  80853. source->zalloc == (alloc_func)0 || source->zfree == (free_func)0)
  80854. return Z_STREAM_ERROR;
  80855. state = (struct inflate_state FAR *)source->state;
  80856. /* allocate space */
  80857. copy = (struct inflate_state FAR *)
  80858. ZALLOC(source, 1, sizeof(struct inflate_state));
  80859. if (copy == Z_NULL) return Z_MEM_ERROR;
  80860. window = Z_NULL;
  80861. if (state->window != Z_NULL) {
  80862. window = (unsigned char FAR *)
  80863. ZALLOC(source, 1U << state->wbits, sizeof(unsigned char));
  80864. if (window == Z_NULL) {
  80865. ZFREE(source, copy);
  80866. return Z_MEM_ERROR;
  80867. }
  80868. }
  80869. /* copy state */
  80870. zmemcpy(dest, source, sizeof(z_stream));
  80871. zmemcpy(copy, state, sizeof(struct inflate_state));
  80872. if (state->lencode >= state->codes &&
  80873. state->lencode <= state->codes + ENOUGH - 1) {
  80874. copy->lencode = copy->codes + (state->lencode - state->codes);
  80875. copy->distcode = copy->codes + (state->distcode - state->codes);
  80876. }
  80877. copy->next = copy->codes + (state->next - state->codes);
  80878. if (window != Z_NULL) {
  80879. wsize = 1U << state->wbits;
  80880. zmemcpy(window, state->window, wsize);
  80881. }
  80882. copy->window = window;
  80883. dest->state = (struct internal_state FAR *)copy;
  80884. return Z_OK;
  80885. }
  80886. /*** End of inlined file: inflate.c ***/
  80887. /*** Start of inlined file: inftrees.c ***/
  80888. #define MAXBITS 15
  80889. const char inflate_copyright[] =
  80890. " inflate 1.2.3 Copyright 1995-2005 Mark Adler ";
  80891. /*
  80892. If you use the zlib library in a product, an acknowledgment is welcome
  80893. in the documentation of your product. If for some reason you cannot
  80894. include such an acknowledgment, I would appreciate that you keep this
  80895. copyright string in the executable of your product.
  80896. */
  80897. /*
  80898. Build a set of tables to decode the provided canonical Huffman code.
  80899. The code lengths are lens[0..codes-1]. The result starts at *table,
  80900. whose indices are 0..2^bits-1. work is a writable array of at least
  80901. lens shorts, which is used as a work area. type is the type of code
  80902. to be generated, CODES, LENS, or DISTS. On return, zero is success,
  80903. -1 is an invalid code, and +1 means that ENOUGH isn't enough. table
  80904. on return points to the next available entry's address. bits is the
  80905. requested root table index bits, and on return it is the actual root
  80906. table index bits. It will differ if the request is greater than the
  80907. longest code or if it is less than the shortest code.
  80908. */
  80909. int inflate_table (codetype type,
  80910. unsigned short FAR *lens,
  80911. unsigned codes,
  80912. code FAR * FAR *table,
  80913. unsigned FAR *bits,
  80914. unsigned short FAR *work)
  80915. {
  80916. unsigned len; /* a code's length in bits */
  80917. unsigned sym; /* index of code symbols */
  80918. unsigned min, max; /* minimum and maximum code lengths */
  80919. unsigned root; /* number of index bits for root table */
  80920. unsigned curr; /* number of index bits for current table */
  80921. unsigned drop; /* code bits to drop for sub-table */
  80922. int left; /* number of prefix codes available */
  80923. unsigned used; /* code entries in table used */
  80924. unsigned huff; /* Huffman code */
  80925. unsigned incr; /* for incrementing code, index */
  80926. unsigned fill; /* index for replicating entries */
  80927. unsigned low; /* low bits for current root entry */
  80928. unsigned mask; /* mask for low root bits */
  80929. code thisx; /* table entry for duplication */
  80930. code FAR *next; /* next available space in table */
  80931. const unsigned short FAR *base; /* base value table to use */
  80932. const unsigned short FAR *extra; /* extra bits table to use */
  80933. int end; /* use base and extra for symbol > end */
  80934. unsigned short count[MAXBITS+1]; /* number of codes of each length */
  80935. unsigned short offs[MAXBITS+1]; /* offsets in table for each length */
  80936. static const unsigned short lbase[31] = { /* Length codes 257..285 base */
  80937. 3, 4, 5, 6, 7, 8, 9, 10, 11, 13, 15, 17, 19, 23, 27, 31,
  80938. 35, 43, 51, 59, 67, 83, 99, 115, 131, 163, 195, 227, 258, 0, 0};
  80939. static const unsigned short lext[31] = { /* Length codes 257..285 extra */
  80940. 16, 16, 16, 16, 16, 16, 16, 16, 17, 17, 17, 17, 18, 18, 18, 18,
  80941. 19, 19, 19, 19, 20, 20, 20, 20, 21, 21, 21, 21, 16, 201, 196};
  80942. static const unsigned short dbase[32] = { /* Distance codes 0..29 base */
  80943. 1, 2, 3, 4, 5, 7, 9, 13, 17, 25, 33, 49, 65, 97, 129, 193,
  80944. 257, 385, 513, 769, 1025, 1537, 2049, 3073, 4097, 6145,
  80945. 8193, 12289, 16385, 24577, 0, 0};
  80946. static const unsigned short dext[32] = { /* Distance codes 0..29 extra */
  80947. 16, 16, 16, 16, 17, 17, 18, 18, 19, 19, 20, 20, 21, 21, 22, 22,
  80948. 23, 23, 24, 24, 25, 25, 26, 26, 27, 27,
  80949. 28, 28, 29, 29, 64, 64};
  80950. /*
  80951. Process a set of code lengths to create a canonical Huffman code. The
  80952. code lengths are lens[0..codes-1]. Each length corresponds to the
  80953. symbols 0..codes-1. The Huffman code is generated by first sorting the
  80954. symbols by length from short to long, and retaining the symbol order
  80955. for codes with equal lengths. Then the code starts with all zero bits
  80956. for the first code of the shortest length, and the codes are integer
  80957. increments for the same length, and zeros are appended as the length
  80958. increases. For the deflate format, these bits are stored backwards
  80959. from their more natural integer increment ordering, and so when the
  80960. decoding tables are built in the large loop below, the integer codes
  80961. are incremented backwards.
  80962. This routine assumes, but does not check, that all of the entries in
  80963. lens[] are in the range 0..MAXBITS. The caller must assure this.
  80964. 1..MAXBITS is interpreted as that code length. zero means that that
  80965. symbol does not occur in this code.
  80966. The codes are sorted by computing a count of codes for each length,
  80967. creating from that a table of starting indices for each length in the
  80968. sorted table, and then entering the symbols in order in the sorted
  80969. table. The sorted table is work[], with that space being provided by
  80970. the caller.
  80971. The length counts are used for other purposes as well, i.e. finding
  80972. the minimum and maximum length codes, determining if there are any
  80973. codes at all, checking for a valid set of lengths, and looking ahead
  80974. at length counts to determine sub-table sizes when building the
  80975. decoding tables.
  80976. */
  80977. /* accumulate lengths for codes (assumes lens[] all in 0..MAXBITS) */
  80978. for (len = 0; len <= MAXBITS; len++)
  80979. count[len] = 0;
  80980. for (sym = 0; sym < codes; sym++)
  80981. count[lens[sym]]++;
  80982. /* bound code lengths, force root to be within code lengths */
  80983. root = *bits;
  80984. for (max = MAXBITS; max >= 1; max--)
  80985. if (count[max] != 0) break;
  80986. if (root > max) root = max;
  80987. if (max == 0) { /* no symbols to code at all */
  80988. thisx.op = (unsigned char)64; /* invalid code marker */
  80989. thisx.bits = (unsigned char)1;
  80990. thisx.val = (unsigned short)0;
  80991. *(*table)++ = thisx; /* make a table to force an error */
  80992. *(*table)++ = thisx;
  80993. *bits = 1;
  80994. return 0; /* no symbols, but wait for decoding to report error */
  80995. }
  80996. for (min = 1; min <= MAXBITS; min++)
  80997. if (count[min] != 0) break;
  80998. if (root < min) root = min;
  80999. /* check for an over-subscribed or incomplete set of lengths */
  81000. left = 1;
  81001. for (len = 1; len <= MAXBITS; len++) {
  81002. left <<= 1;
  81003. left -= count[len];
  81004. if (left < 0) return -1; /* over-subscribed */
  81005. }
  81006. if (left > 0 && (type == CODES || max != 1))
  81007. return -1; /* incomplete set */
  81008. /* generate offsets into symbol table for each length for sorting */
  81009. offs[1] = 0;
  81010. for (len = 1; len < MAXBITS; len++)
  81011. offs[len + 1] = offs[len] + count[len];
  81012. /* sort symbols by length, by symbol order within each length */
  81013. for (sym = 0; sym < codes; sym++)
  81014. if (lens[sym] != 0) work[offs[lens[sym]]++] = (unsigned short)sym;
  81015. /*
  81016. Create and fill in decoding tables. In this loop, the table being
  81017. filled is at next and has curr index bits. The code being used is huff
  81018. with length len. That code is converted to an index by dropping drop
  81019. bits off of the bottom. For codes where len is less than drop + curr,
  81020. those top drop + curr - len bits are incremented through all values to
  81021. fill the table with replicated entries.
  81022. root is the number of index bits for the root table. When len exceeds
  81023. root, sub-tables are created pointed to by the root entry with an index
  81024. of the low root bits of huff. This is saved in low to check for when a
  81025. new sub-table should be started. drop is zero when the root table is
  81026. being filled, and drop is root when sub-tables are being filled.
  81027. When a new sub-table is needed, it is necessary to look ahead in the
  81028. code lengths to determine what size sub-table is needed. The length
  81029. counts are used for this, and so count[] is decremented as codes are
  81030. entered in the tables.
  81031. used keeps track of how many table entries have been allocated from the
  81032. provided *table space. It is checked when a LENS table is being made
  81033. against the space in *table, ENOUGH, minus the maximum space needed by
  81034. the worst case distance code, MAXD. This should never happen, but the
  81035. sufficiency of ENOUGH has not been proven exhaustively, hence the check.
  81036. This assumes that when type == LENS, bits == 9.
  81037. sym increments through all symbols, and the loop terminates when
  81038. all codes of length max, i.e. all codes, have been processed. This
  81039. routine permits incomplete codes, so another loop after this one fills
  81040. in the rest of the decoding tables with invalid code markers.
  81041. */
  81042. /* set up for code type */
  81043. switch (type) {
  81044. case CODES:
  81045. base = extra = work; /* dummy value--not used */
  81046. end = 19;
  81047. break;
  81048. case LENS:
  81049. base = lbase;
  81050. base -= 257;
  81051. extra = lext;
  81052. extra -= 257;
  81053. end = 256;
  81054. break;
  81055. default: /* DISTS */
  81056. base = dbase;
  81057. extra = dext;
  81058. end = -1;
  81059. }
  81060. /* initialize state for loop */
  81061. huff = 0; /* starting code */
  81062. sym = 0; /* starting code symbol */
  81063. len = min; /* starting code length */
  81064. next = *table; /* current table to fill in */
  81065. curr = root; /* current table index bits */
  81066. drop = 0; /* current bits to drop from code for index */
  81067. low = (unsigned)(-1); /* trigger new sub-table when len > root */
  81068. used = 1U << root; /* use root table entries */
  81069. mask = used - 1; /* mask for comparing low */
  81070. /* check available table space */
  81071. if (type == LENS && used >= ENOUGH - MAXD)
  81072. return 1;
  81073. /* process all codes and make table entries */
  81074. for (;;) {
  81075. /* create table entry */
  81076. thisx.bits = (unsigned char)(len - drop);
  81077. if ((int)(work[sym]) < end) {
  81078. thisx.op = (unsigned char)0;
  81079. thisx.val = work[sym];
  81080. }
  81081. else if ((int)(work[sym]) > end) {
  81082. thisx.op = (unsigned char)(extra[work[sym]]);
  81083. thisx.val = base[work[sym]];
  81084. }
  81085. else {
  81086. thisx.op = (unsigned char)(32 + 64); /* end of block */
  81087. thisx.val = 0;
  81088. }
  81089. /* replicate for those indices with low len bits equal to huff */
  81090. incr = 1U << (len - drop);
  81091. fill = 1U << curr;
  81092. min = fill; /* save offset to next table */
  81093. do {
  81094. fill -= incr;
  81095. next[(huff >> drop) + fill] = thisx;
  81096. } while (fill != 0);
  81097. /* backwards increment the len-bit code huff */
  81098. incr = 1U << (len - 1);
  81099. while (huff & incr)
  81100. incr >>= 1;
  81101. if (incr != 0) {
  81102. huff &= incr - 1;
  81103. huff += incr;
  81104. }
  81105. else
  81106. huff = 0;
  81107. /* go to next symbol, update count, len */
  81108. sym++;
  81109. if (--(count[len]) == 0) {
  81110. if (len == max) break;
  81111. len = lens[work[sym]];
  81112. }
  81113. /* create new sub-table if needed */
  81114. if (len > root && (huff & mask) != low) {
  81115. /* if first time, transition to sub-tables */
  81116. if (drop == 0)
  81117. drop = root;
  81118. /* increment past last table */
  81119. next += min; /* here min is 1 << curr */
  81120. /* determine length of next table */
  81121. curr = len - drop;
  81122. left = (int)(1 << curr);
  81123. while (curr + drop < max) {
  81124. left -= count[curr + drop];
  81125. if (left <= 0) break;
  81126. curr++;
  81127. left <<= 1;
  81128. }
  81129. /* check for enough space */
  81130. used += 1U << curr;
  81131. if (type == LENS && used >= ENOUGH - MAXD)
  81132. return 1;
  81133. /* point entry in root table to sub-table */
  81134. low = huff & mask;
  81135. (*table)[low].op = (unsigned char)curr;
  81136. (*table)[low].bits = (unsigned char)root;
  81137. (*table)[low].val = (unsigned short)(next - *table);
  81138. }
  81139. }
  81140. /*
  81141. Fill in rest of table for incomplete codes. This loop is similar to the
  81142. loop above in incrementing huff for table indices. It is assumed that
  81143. len is equal to curr + drop, so there is no loop needed to increment
  81144. through high index bits. When the current sub-table is filled, the loop
  81145. drops back to the root table to fill in any remaining entries there.
  81146. */
  81147. thisx.op = (unsigned char)64; /* invalid code marker */
  81148. thisx.bits = (unsigned char)(len - drop);
  81149. thisx.val = (unsigned short)0;
  81150. while (huff != 0) {
  81151. /* when done with sub-table, drop back to root table */
  81152. if (drop != 0 && (huff & mask) != low) {
  81153. drop = 0;
  81154. len = root;
  81155. next = *table;
  81156. thisx.bits = (unsigned char)len;
  81157. }
  81158. /* put invalid code marker in table */
  81159. next[huff >> drop] = thisx;
  81160. /* backwards increment the len-bit code huff */
  81161. incr = 1U << (len - 1);
  81162. while (huff & incr)
  81163. incr >>= 1;
  81164. if (incr != 0) {
  81165. huff &= incr - 1;
  81166. huff += incr;
  81167. }
  81168. else
  81169. huff = 0;
  81170. }
  81171. /* set return parameters */
  81172. *table += used;
  81173. *bits = root;
  81174. return 0;
  81175. }
  81176. /*** End of inlined file: inftrees.c ***/
  81177. /*** Start of inlined file: trees.c ***/
  81178. /*
  81179. * ALGORITHM
  81180. *
  81181. * The "deflation" process uses several Huffman trees. The more
  81182. * common source values are represented by shorter bit sequences.
  81183. *
  81184. * Each code tree is stored in a compressed form which is itself
  81185. * a Huffman encoding of the lengths of all the code strings (in
  81186. * ascending order by source values). The actual code strings are
  81187. * reconstructed from the lengths in the inflate process, as described
  81188. * in the deflate specification.
  81189. *
  81190. * REFERENCES
  81191. *
  81192. * Deutsch, L.P.,"'Deflate' Compressed Data Format Specification".
  81193. * Available in ftp.uu.net:/pub/archiving/zip/doc/deflate-1.1.doc
  81194. *
  81195. * Storer, James A.
  81196. * Data Compression: Methods and Theory, pp. 49-50.
  81197. * Computer Science Press, 1988. ISBN 0-7167-8156-5.
  81198. *
  81199. * Sedgewick, R.
  81200. * Algorithms, p290.
  81201. * Addison-Wesley, 1983. ISBN 0-201-06672-6.
  81202. */
  81203. /* @(#) $Id: trees.c,v 1.1 2007/06/07 17:54:37 jules_rms Exp $ */
  81204. /* #define GEN_TREES_H */
  81205. #ifdef DEBUG
  81206. # include <ctype.h>
  81207. #endif
  81208. /* ===========================================================================
  81209. * Constants
  81210. */
  81211. #define MAX_BL_BITS 7
  81212. /* Bit length codes must not exceed MAX_BL_BITS bits */
  81213. #define END_BLOCK 256
  81214. /* end of block literal code */
  81215. #define REP_3_6 16
  81216. /* repeat previous bit length 3-6 times (2 bits of repeat count) */
  81217. #define REPZ_3_10 17
  81218. /* repeat a zero length 3-10 times (3 bits of repeat count) */
  81219. #define REPZ_11_138 18
  81220. /* repeat a zero length 11-138 times (7 bits of repeat count) */
  81221. local const int extra_lbits[LENGTH_CODES] /* extra bits for each length code */
  81222. = {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};
  81223. local const int extra_dbits[D_CODES] /* extra bits for each distance code */
  81224. = {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};
  81225. local const int extra_blbits[BL_CODES]/* extra bits for each bit length code */
  81226. = {0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,2,3,7};
  81227. local const uch bl_order[BL_CODES]
  81228. = {16,17,18,0,8,7,9,6,10,5,11,4,12,3,13,2,14,1,15};
  81229. /* The lengths of the bit length codes are sent in order of decreasing
  81230. * probability, to avoid transmitting the lengths for unused bit length codes.
  81231. */
  81232. #define Buf_size (8 * 2*sizeof(char))
  81233. /* Number of bits used within bi_buf. (bi_buf might be implemented on
  81234. * more than 16 bits on some systems.)
  81235. */
  81236. /* ===========================================================================
  81237. * Local data. These are initialized only once.
  81238. */
  81239. #define DIST_CODE_LEN 512 /* see definition of array dist_code below */
  81240. #if defined(GEN_TREES_H) || !defined(STDC)
  81241. /* non ANSI compilers may not accept trees.h */
  81242. local ct_data static_ltree[L_CODES+2];
  81243. /* The static literal tree. Since the bit lengths are imposed, there is no
  81244. * need for the L_CODES extra codes used during heap construction. However
  81245. * The codes 286 and 287 are needed to build a canonical tree (see _tr_init
  81246. * below).
  81247. */
  81248. local ct_data static_dtree[D_CODES];
  81249. /* The static distance tree. (Actually a trivial tree since all codes use
  81250. * 5 bits.)
  81251. */
  81252. uch _dist_code[DIST_CODE_LEN];
  81253. /* Distance codes. The first 256 values correspond to the distances
  81254. * 3 .. 258, the last 256 values correspond to the top 8 bits of
  81255. * the 15 bit distances.
  81256. */
  81257. uch _length_code[MAX_MATCH-MIN_MATCH+1];
  81258. /* length code for each normalized match length (0 == MIN_MATCH) */
  81259. local int base_length[LENGTH_CODES];
  81260. /* First normalized length for each code (0 = MIN_MATCH) */
  81261. local int base_dist[D_CODES];
  81262. /* First normalized distance for each code (0 = distance of 1) */
  81263. #else
  81264. /*** Start of inlined file: trees.h ***/
  81265. local const ct_data static_ltree[L_CODES+2] = {
  81266. {{ 12},{ 8}}, {{140},{ 8}}, {{ 76},{ 8}}, {{204},{ 8}}, {{ 44},{ 8}},
  81267. {{172},{ 8}}, {{108},{ 8}}, {{236},{ 8}}, {{ 28},{ 8}}, {{156},{ 8}},
  81268. {{ 92},{ 8}}, {{220},{ 8}}, {{ 60},{ 8}}, {{188},{ 8}}, {{124},{ 8}},
  81269. {{252},{ 8}}, {{ 2},{ 8}}, {{130},{ 8}}, {{ 66},{ 8}}, {{194},{ 8}},
  81270. {{ 34},{ 8}}, {{162},{ 8}}, {{ 98},{ 8}}, {{226},{ 8}}, {{ 18},{ 8}},
  81271. {{146},{ 8}}, {{ 82},{ 8}}, {{210},{ 8}}, {{ 50},{ 8}}, {{178},{ 8}},
  81272. {{114},{ 8}}, {{242},{ 8}}, {{ 10},{ 8}}, {{138},{ 8}}, {{ 74},{ 8}},
  81273. {{202},{ 8}}, {{ 42},{ 8}}, {{170},{ 8}}, {{106},{ 8}}, {{234},{ 8}},
  81274. {{ 26},{ 8}}, {{154},{ 8}}, {{ 90},{ 8}}, {{218},{ 8}}, {{ 58},{ 8}},
  81275. {{186},{ 8}}, {{122},{ 8}}, {{250},{ 8}}, {{ 6},{ 8}}, {{134},{ 8}},
  81276. {{ 70},{ 8}}, {{198},{ 8}}, {{ 38},{ 8}}, {{166},{ 8}}, {{102},{ 8}},
  81277. {{230},{ 8}}, {{ 22},{ 8}}, {{150},{ 8}}, {{ 86},{ 8}}, {{214},{ 8}},
  81278. {{ 54},{ 8}}, {{182},{ 8}}, {{118},{ 8}}, {{246},{ 8}}, {{ 14},{ 8}},
  81279. {{142},{ 8}}, {{ 78},{ 8}}, {{206},{ 8}}, {{ 46},{ 8}}, {{174},{ 8}},
  81280. {{110},{ 8}}, {{238},{ 8}}, {{ 30},{ 8}}, {{158},{ 8}}, {{ 94},{ 8}},
  81281. {{222},{ 8}}, {{ 62},{ 8}}, {{190},{ 8}}, {{126},{ 8}}, {{254},{ 8}},
  81282. {{ 1},{ 8}}, {{129},{ 8}}, {{ 65},{ 8}}, {{193},{ 8}}, {{ 33},{ 8}},
  81283. {{161},{ 8}}, {{ 97},{ 8}}, {{225},{ 8}}, {{ 17},{ 8}}, {{145},{ 8}},
  81284. {{ 81},{ 8}}, {{209},{ 8}}, {{ 49},{ 8}}, {{177},{ 8}}, {{113},{ 8}},
  81285. {{241},{ 8}}, {{ 9},{ 8}}, {{137},{ 8}}, {{ 73},{ 8}}, {{201},{ 8}},
  81286. {{ 41},{ 8}}, {{169},{ 8}}, {{105},{ 8}}, {{233},{ 8}}, {{ 25},{ 8}},
  81287. {{153},{ 8}}, {{ 89},{ 8}}, {{217},{ 8}}, {{ 57},{ 8}}, {{185},{ 8}},
  81288. {{121},{ 8}}, {{249},{ 8}}, {{ 5},{ 8}}, {{133},{ 8}}, {{ 69},{ 8}},
  81289. {{197},{ 8}}, {{ 37},{ 8}}, {{165},{ 8}}, {{101},{ 8}}, {{229},{ 8}},
  81290. {{ 21},{ 8}}, {{149},{ 8}}, {{ 85},{ 8}}, {{213},{ 8}}, {{ 53},{ 8}},
  81291. {{181},{ 8}}, {{117},{ 8}}, {{245},{ 8}}, {{ 13},{ 8}}, {{141},{ 8}},
  81292. {{ 77},{ 8}}, {{205},{ 8}}, {{ 45},{ 8}}, {{173},{ 8}}, {{109},{ 8}},
  81293. {{237},{ 8}}, {{ 29},{ 8}}, {{157},{ 8}}, {{ 93},{ 8}}, {{221},{ 8}},
  81294. {{ 61},{ 8}}, {{189},{ 8}}, {{125},{ 8}}, {{253},{ 8}}, {{ 19},{ 9}},
  81295. {{275},{ 9}}, {{147},{ 9}}, {{403},{ 9}}, {{ 83},{ 9}}, {{339},{ 9}},
  81296. {{211},{ 9}}, {{467},{ 9}}, {{ 51},{ 9}}, {{307},{ 9}}, {{179},{ 9}},
  81297. {{435},{ 9}}, {{115},{ 9}}, {{371},{ 9}}, {{243},{ 9}}, {{499},{ 9}},
  81298. {{ 11},{ 9}}, {{267},{ 9}}, {{139},{ 9}}, {{395},{ 9}}, {{ 75},{ 9}},
  81299. {{331},{ 9}}, {{203},{ 9}}, {{459},{ 9}}, {{ 43},{ 9}}, {{299},{ 9}},
  81300. {{171},{ 9}}, {{427},{ 9}}, {{107},{ 9}}, {{363},{ 9}}, {{235},{ 9}},
  81301. {{491},{ 9}}, {{ 27},{ 9}}, {{283},{ 9}}, {{155},{ 9}}, {{411},{ 9}},
  81302. {{ 91},{ 9}}, {{347},{ 9}}, {{219},{ 9}}, {{475},{ 9}}, {{ 59},{ 9}},
  81303. {{315},{ 9}}, {{187},{ 9}}, {{443},{ 9}}, {{123},{ 9}}, {{379},{ 9}},
  81304. {{251},{ 9}}, {{507},{ 9}}, {{ 7},{ 9}}, {{263},{ 9}}, {{135},{ 9}},
  81305. {{391},{ 9}}, {{ 71},{ 9}}, {{327},{ 9}}, {{199},{ 9}}, {{455},{ 9}},
  81306. {{ 39},{ 9}}, {{295},{ 9}}, {{167},{ 9}}, {{423},{ 9}}, {{103},{ 9}},
  81307. {{359},{ 9}}, {{231},{ 9}}, {{487},{ 9}}, {{ 23},{ 9}}, {{279},{ 9}},
  81308. {{151},{ 9}}, {{407},{ 9}}, {{ 87},{ 9}}, {{343},{ 9}}, {{215},{ 9}},
  81309. {{471},{ 9}}, {{ 55},{ 9}}, {{311},{ 9}}, {{183},{ 9}}, {{439},{ 9}},
  81310. {{119},{ 9}}, {{375},{ 9}}, {{247},{ 9}}, {{503},{ 9}}, {{ 15},{ 9}},
  81311. {{271},{ 9}}, {{143},{ 9}}, {{399},{ 9}}, {{ 79},{ 9}}, {{335},{ 9}},
  81312. {{207},{ 9}}, {{463},{ 9}}, {{ 47},{ 9}}, {{303},{ 9}}, {{175},{ 9}},
  81313. {{431},{ 9}}, {{111},{ 9}}, {{367},{ 9}}, {{239},{ 9}}, {{495},{ 9}},
  81314. {{ 31},{ 9}}, {{287},{ 9}}, {{159},{ 9}}, {{415},{ 9}}, {{ 95},{ 9}},
  81315. {{351},{ 9}}, {{223},{ 9}}, {{479},{ 9}}, {{ 63},{ 9}}, {{319},{ 9}},
  81316. {{191},{ 9}}, {{447},{ 9}}, {{127},{ 9}}, {{383},{ 9}}, {{255},{ 9}},
  81317. {{511},{ 9}}, {{ 0},{ 7}}, {{ 64},{ 7}}, {{ 32},{ 7}}, {{ 96},{ 7}},
  81318. {{ 16},{ 7}}, {{ 80},{ 7}}, {{ 48},{ 7}}, {{112},{ 7}}, {{ 8},{ 7}},
  81319. {{ 72},{ 7}}, {{ 40},{ 7}}, {{104},{ 7}}, {{ 24},{ 7}}, {{ 88},{ 7}},
  81320. {{ 56},{ 7}}, {{120},{ 7}}, {{ 4},{ 7}}, {{ 68},{ 7}}, {{ 36},{ 7}},
  81321. {{100},{ 7}}, {{ 20},{ 7}}, {{ 84},{ 7}}, {{ 52},{ 7}}, {{116},{ 7}},
  81322. {{ 3},{ 8}}, {{131},{ 8}}, {{ 67},{ 8}}, {{195},{ 8}}, {{ 35},{ 8}},
  81323. {{163},{ 8}}, {{ 99},{ 8}}, {{227},{ 8}}
  81324. };
  81325. local const ct_data static_dtree[D_CODES] = {
  81326. {{ 0},{ 5}}, {{16},{ 5}}, {{ 8},{ 5}}, {{24},{ 5}}, {{ 4},{ 5}},
  81327. {{20},{ 5}}, {{12},{ 5}}, {{28},{ 5}}, {{ 2},{ 5}}, {{18},{ 5}},
  81328. {{10},{ 5}}, {{26},{ 5}}, {{ 6},{ 5}}, {{22},{ 5}}, {{14},{ 5}},
  81329. {{30},{ 5}}, {{ 1},{ 5}}, {{17},{ 5}}, {{ 9},{ 5}}, {{25},{ 5}},
  81330. {{ 5},{ 5}}, {{21},{ 5}}, {{13},{ 5}}, {{29},{ 5}}, {{ 3},{ 5}},
  81331. {{19},{ 5}}, {{11},{ 5}}, {{27},{ 5}}, {{ 7},{ 5}}, {{23},{ 5}}
  81332. };
  81333. const uch _dist_code[DIST_CODE_LEN] = {
  81334. 0, 1, 2, 3, 4, 4, 5, 5, 6, 6, 6, 6, 7, 7, 7, 7, 8, 8, 8, 8,
  81335. 8, 8, 8, 8, 9, 9, 9, 9, 9, 9, 9, 9, 10, 10, 10, 10, 10, 10, 10, 10,
  81336. 10, 10, 10, 10, 10, 10, 10, 10, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11,
  81337. 11, 11, 11, 11, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12,
  81338. 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 13, 13, 13, 13,
  81339. 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13,
  81340. 13, 13, 13, 13, 13, 13, 13, 13, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14,
  81341. 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14,
  81342. 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14,
  81343. 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 15, 15, 15, 15, 15, 15, 15, 15,
  81344. 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15,
  81345. 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15,
  81346. 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 0, 0, 16, 17,
  81347. 18, 18, 19, 19, 20, 20, 20, 20, 21, 21, 21, 21, 22, 22, 22, 22, 22, 22, 22, 22,
  81348. 23, 23, 23, 23, 23, 23, 23, 23, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24,
  81349. 24, 24, 24, 24, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25,
  81350. 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26,
  81351. 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 27, 27, 27, 27, 27, 27, 27, 27,
  81352. 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27,
  81353. 27, 27, 27, 27, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28,
  81354. 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28,
  81355. 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28,
  81356. 28, 28, 28, 28, 28, 28, 28, 28, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29,
  81357. 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29,
  81358. 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29,
  81359. 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29
  81360. };
  81361. const uch _length_code[MAX_MATCH-MIN_MATCH+1]= {
  81362. 0, 1, 2, 3, 4, 5, 6, 7, 8, 8, 9, 9, 10, 10, 11, 11, 12, 12, 12, 12,
  81363. 13, 13, 13, 13, 14, 14, 14, 14, 15, 15, 15, 15, 16, 16, 16, 16, 16, 16, 16, 16,
  81364. 17, 17, 17, 17, 17, 17, 17, 17, 18, 18, 18, 18, 18, 18, 18, 18, 19, 19, 19, 19,
  81365. 19, 19, 19, 19, 20, 20, 20, 20, 20, 20, 20, 20, 20, 20, 20, 20, 20, 20, 20, 20,
  81366. 21, 21, 21, 21, 21, 21, 21, 21, 21, 21, 21, 21, 21, 21, 21, 21, 22, 22, 22, 22,
  81367. 22, 22, 22, 22, 22, 22, 22, 22, 22, 22, 22, 22, 23, 23, 23, 23, 23, 23, 23, 23,
  81368. 23, 23, 23, 23, 23, 23, 23, 23, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24,
  81369. 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24,
  81370. 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25,
  81371. 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 26, 26, 26, 26, 26, 26, 26, 26,
  81372. 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26,
  81373. 26, 26, 26, 26, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27,
  81374. 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 28
  81375. };
  81376. local const int base_length[LENGTH_CODES] = {
  81377. 0, 1, 2, 3, 4, 5, 6, 7, 8, 10, 12, 14, 16, 20, 24, 28, 32, 40, 48, 56,
  81378. 64, 80, 96, 112, 128, 160, 192, 224, 0
  81379. };
  81380. local const int base_dist[D_CODES] = {
  81381. 0, 1, 2, 3, 4, 6, 8, 12, 16, 24,
  81382. 32, 48, 64, 96, 128, 192, 256, 384, 512, 768,
  81383. 1024, 1536, 2048, 3072, 4096, 6144, 8192, 12288, 16384, 24576
  81384. };
  81385. /*** End of inlined file: trees.h ***/
  81386. #endif /* GEN_TREES_H */
  81387. struct static_tree_desc_s {
  81388. const ct_data *static_tree; /* static tree or NULL */
  81389. const intf *extra_bits; /* extra bits for each code or NULL */
  81390. int extra_base; /* base index for extra_bits */
  81391. int elems; /* max number of elements in the tree */
  81392. int max_length; /* max bit length for the codes */
  81393. };
  81394. local static_tree_desc static_l_desc =
  81395. {static_ltree, extra_lbits, LITERALS+1, L_CODES, MAX_BITS};
  81396. local static_tree_desc static_d_desc =
  81397. {static_dtree, extra_dbits, 0, D_CODES, MAX_BITS};
  81398. local static_tree_desc static_bl_desc =
  81399. {(const ct_data *)0, extra_blbits, 0, BL_CODES, MAX_BL_BITS};
  81400. /* ===========================================================================
  81401. * Local (static) routines in this file.
  81402. */
  81403. local void tr_static_init OF((void));
  81404. local void init_block OF((deflate_state *s));
  81405. local void pqdownheap OF((deflate_state *s, ct_data *tree, int k));
  81406. local void gen_bitlen OF((deflate_state *s, tree_desc *desc));
  81407. local void gen_codes OF((ct_data *tree, int max_code, ushf *bl_count));
  81408. local void build_tree OF((deflate_state *s, tree_desc *desc));
  81409. local void scan_tree OF((deflate_state *s, ct_data *tree, int max_code));
  81410. local void send_tree OF((deflate_state *s, ct_data *tree, int max_code));
  81411. local int build_bl_tree OF((deflate_state *s));
  81412. local void send_all_trees OF((deflate_state *s, int lcodes, int dcodes,
  81413. int blcodes));
  81414. local void compress_block OF((deflate_state *s, ct_data *ltree,
  81415. ct_data *dtree));
  81416. local void set_data_type OF((deflate_state *s));
  81417. local unsigned bi_reverse OF((unsigned value, int length));
  81418. local void bi_windup OF((deflate_state *s));
  81419. local void bi_flush OF((deflate_state *s));
  81420. local void copy_block OF((deflate_state *s, charf *buf, unsigned len,
  81421. int header));
  81422. #ifdef GEN_TREES_H
  81423. local void gen_trees_header OF((void));
  81424. #endif
  81425. #ifndef DEBUG
  81426. # define send_code(s, c, tree) send_bits(s, tree[c].Code, tree[c].Len)
  81427. /* Send a code of the given tree. c and tree must not have side effects */
  81428. #else /* DEBUG */
  81429. # define send_code(s, c, tree) \
  81430. { if (z_verbose>2) fprintf(stderr,"\ncd %3d ",(c)); \
  81431. send_bits(s, tree[c].Code, tree[c].Len); }
  81432. #endif
  81433. /* ===========================================================================
  81434. * Output a short LSB first on the stream.
  81435. * IN assertion: there is enough room in pendingBuf.
  81436. */
  81437. #define put_short(s, w) { \
  81438. put_byte(s, (uch)((w) & 0xff)); \
  81439. put_byte(s, (uch)((ush)(w) >> 8)); \
  81440. }
  81441. /* ===========================================================================
  81442. * Send a value on a given number of bits.
  81443. * IN assertion: length <= 16 and value fits in length bits.
  81444. */
  81445. #ifdef DEBUG
  81446. local void send_bits OF((deflate_state *s, int value, int length));
  81447. local void send_bits (deflate_state *s, int value, int length)
  81448. {
  81449. Tracevv((stderr," l %2d v %4x ", length, value));
  81450. Assert(length > 0 && length <= 15, "invalid length");
  81451. s->bits_sent += (ulg)length;
  81452. /* If not enough room in bi_buf, use (valid) bits from bi_buf and
  81453. * (16 - bi_valid) bits from value, leaving (width - (16-bi_valid))
  81454. * unused bits in value.
  81455. */
  81456. if (s->bi_valid > (int)Buf_size - length) {
  81457. s->bi_buf |= (value << s->bi_valid);
  81458. put_short(s, s->bi_buf);
  81459. s->bi_buf = (ush)value >> (Buf_size - s->bi_valid);
  81460. s->bi_valid += length - Buf_size;
  81461. } else {
  81462. s->bi_buf |= value << s->bi_valid;
  81463. s->bi_valid += length;
  81464. }
  81465. }
  81466. #else /* !DEBUG */
  81467. #define send_bits(s, value, length) \
  81468. { int len = length;\
  81469. if (s->bi_valid > (int)Buf_size - len) {\
  81470. int val = value;\
  81471. s->bi_buf |= (val << s->bi_valid);\
  81472. put_short(s, s->bi_buf);\
  81473. s->bi_buf = (ush)val >> (Buf_size - s->bi_valid);\
  81474. s->bi_valid += len - Buf_size;\
  81475. } else {\
  81476. s->bi_buf |= (value) << s->bi_valid;\
  81477. s->bi_valid += len;\
  81478. }\
  81479. }
  81480. #endif /* DEBUG */
  81481. /* the arguments must not have side effects */
  81482. /* ===========================================================================
  81483. * Initialize the various 'constant' tables.
  81484. */
  81485. local void tr_static_init()
  81486. {
  81487. #if defined(GEN_TREES_H) || !defined(STDC)
  81488. static int static_init_done = 0;
  81489. int n; /* iterates over tree elements */
  81490. int bits; /* bit counter */
  81491. int length; /* length value */
  81492. int code; /* code value */
  81493. int dist; /* distance index */
  81494. ush bl_count[MAX_BITS+1];
  81495. /* number of codes at each bit length for an optimal tree */
  81496. if (static_init_done) return;
  81497. /* For some embedded targets, global variables are not initialized: */
  81498. static_l_desc.static_tree = static_ltree;
  81499. static_l_desc.extra_bits = extra_lbits;
  81500. static_d_desc.static_tree = static_dtree;
  81501. static_d_desc.extra_bits = extra_dbits;
  81502. static_bl_desc.extra_bits = extra_blbits;
  81503. /* Initialize the mapping length (0..255) -> length code (0..28) */
  81504. length = 0;
  81505. for (code = 0; code < LENGTH_CODES-1; code++) {
  81506. base_length[code] = length;
  81507. for (n = 0; n < (1<<extra_lbits[code]); n++) {
  81508. _length_code[length++] = (uch)code;
  81509. }
  81510. }
  81511. Assert (length == 256, "tr_static_init: length != 256");
  81512. /* Note that the length 255 (match length 258) can be represented
  81513. * in two different ways: code 284 + 5 bits or code 285, so we
  81514. * overwrite length_code[255] to use the best encoding:
  81515. */
  81516. _length_code[length-1] = (uch)code;
  81517. /* Initialize the mapping dist (0..32K) -> dist code (0..29) */
  81518. dist = 0;
  81519. for (code = 0 ; code < 16; code++) {
  81520. base_dist[code] = dist;
  81521. for (n = 0; n < (1<<extra_dbits[code]); n++) {
  81522. _dist_code[dist++] = (uch)code;
  81523. }
  81524. }
  81525. Assert (dist == 256, "tr_static_init: dist != 256");
  81526. dist >>= 7; /* from now on, all distances are divided by 128 */
  81527. for ( ; code < D_CODES; code++) {
  81528. base_dist[code] = dist << 7;
  81529. for (n = 0; n < (1<<(extra_dbits[code]-7)); n++) {
  81530. _dist_code[256 + dist++] = (uch)code;
  81531. }
  81532. }
  81533. Assert (dist == 256, "tr_static_init: 256+dist != 512");
  81534. /* Construct the codes of the static literal tree */
  81535. for (bits = 0; bits <= MAX_BITS; bits++) bl_count[bits] = 0;
  81536. n = 0;
  81537. while (n <= 143) static_ltree[n++].Len = 8, bl_count[8]++;
  81538. while (n <= 255) static_ltree[n++].Len = 9, bl_count[9]++;
  81539. while (n <= 279) static_ltree[n++].Len = 7, bl_count[7]++;
  81540. while (n <= 287) static_ltree[n++].Len = 8, bl_count[8]++;
  81541. /* Codes 286 and 287 do not exist, but we must include them in the
  81542. * tree construction to get a canonical Huffman tree (longest code
  81543. * all ones)
  81544. */
  81545. gen_codes((ct_data *)static_ltree, L_CODES+1, bl_count);
  81546. /* The static distance tree is trivial: */
  81547. for (n = 0; n < D_CODES; n++) {
  81548. static_dtree[n].Len = 5;
  81549. static_dtree[n].Code = bi_reverse((unsigned)n, 5);
  81550. }
  81551. static_init_done = 1;
  81552. # ifdef GEN_TREES_H
  81553. gen_trees_header();
  81554. # endif
  81555. #endif /* defined(GEN_TREES_H) || !defined(STDC) */
  81556. }
  81557. /* ===========================================================================
  81558. * Genererate the file trees.h describing the static trees.
  81559. */
  81560. #ifdef GEN_TREES_H
  81561. # ifndef DEBUG
  81562. # include <stdio.h>
  81563. # endif
  81564. # define SEPARATOR(i, last, width) \
  81565. ((i) == (last)? "\n};\n\n" : \
  81566. ((i) % (width) == (width)-1 ? ",\n" : ", "))
  81567. void gen_trees_header()
  81568. {
  81569. FILE *header = fopen("trees.h", "w");
  81570. int i;
  81571. Assert (header != NULL, "Can't open trees.h");
  81572. fprintf(header,
  81573. "/* header created automatically with -DGEN_TREES_H */\n\n");
  81574. fprintf(header, "local const ct_data static_ltree[L_CODES+2] = {\n");
  81575. for (i = 0; i < L_CODES+2; i++) {
  81576. fprintf(header, "{{%3u},{%3u}}%s", static_ltree[i].Code,
  81577. static_ltree[i].Len, SEPARATOR(i, L_CODES+1, 5));
  81578. }
  81579. fprintf(header, "local const ct_data static_dtree[D_CODES] = {\n");
  81580. for (i = 0; i < D_CODES; i++) {
  81581. fprintf(header, "{{%2u},{%2u}}%s", static_dtree[i].Code,
  81582. static_dtree[i].Len, SEPARATOR(i, D_CODES-1, 5));
  81583. }
  81584. fprintf(header, "const uch _dist_code[DIST_CODE_LEN] = {\n");
  81585. for (i = 0; i < DIST_CODE_LEN; i++) {
  81586. fprintf(header, "%2u%s", _dist_code[i],
  81587. SEPARATOR(i, DIST_CODE_LEN-1, 20));
  81588. }
  81589. fprintf(header, "const uch _length_code[MAX_MATCH-MIN_MATCH+1]= {\n");
  81590. for (i = 0; i < MAX_MATCH-MIN_MATCH+1; i++) {
  81591. fprintf(header, "%2u%s", _length_code[i],
  81592. SEPARATOR(i, MAX_MATCH-MIN_MATCH, 20));
  81593. }
  81594. fprintf(header, "local const int base_length[LENGTH_CODES] = {\n");
  81595. for (i = 0; i < LENGTH_CODES; i++) {
  81596. fprintf(header, "%1u%s", base_length[i],
  81597. SEPARATOR(i, LENGTH_CODES-1, 20));
  81598. }
  81599. fprintf(header, "local const int base_dist[D_CODES] = {\n");
  81600. for (i = 0; i < D_CODES; i++) {
  81601. fprintf(header, "%5u%s", base_dist[i],
  81602. SEPARATOR(i, D_CODES-1, 10));
  81603. }
  81604. fclose(header);
  81605. }
  81606. #endif /* GEN_TREES_H */
  81607. /* ===========================================================================
  81608. * Initialize the tree data structures for a new zlib stream.
  81609. */
  81610. void _tr_init(deflate_state *s)
  81611. {
  81612. tr_static_init();
  81613. s->l_desc.dyn_tree = s->dyn_ltree;
  81614. s->l_desc.stat_desc = &static_l_desc;
  81615. s->d_desc.dyn_tree = s->dyn_dtree;
  81616. s->d_desc.stat_desc = &static_d_desc;
  81617. s->bl_desc.dyn_tree = s->bl_tree;
  81618. s->bl_desc.stat_desc = &static_bl_desc;
  81619. s->bi_buf = 0;
  81620. s->bi_valid = 0;
  81621. s->last_eob_len = 8; /* enough lookahead for inflate */
  81622. #ifdef DEBUG
  81623. s->compressed_len = 0L;
  81624. s->bits_sent = 0L;
  81625. #endif
  81626. /* Initialize the first block of the first file: */
  81627. init_block(s);
  81628. }
  81629. /* ===========================================================================
  81630. * Initialize a new block.
  81631. */
  81632. local void init_block (deflate_state *s)
  81633. {
  81634. int n; /* iterates over tree elements */
  81635. /* Initialize the trees. */
  81636. for (n = 0; n < L_CODES; n++) s->dyn_ltree[n].Freq = 0;
  81637. for (n = 0; n < D_CODES; n++) s->dyn_dtree[n].Freq = 0;
  81638. for (n = 0; n < BL_CODES; n++) s->bl_tree[n].Freq = 0;
  81639. s->dyn_ltree[END_BLOCK].Freq = 1;
  81640. s->opt_len = s->static_len = 0L;
  81641. s->last_lit = s->matches = 0;
  81642. }
  81643. #define SMALLEST 1
  81644. /* Index within the heap array of least frequent node in the Huffman tree */
  81645. /* ===========================================================================
  81646. * Remove the smallest element from the heap and recreate the heap with
  81647. * one less element. Updates heap and heap_len.
  81648. */
  81649. #define pqremove(s, tree, top) \
  81650. {\
  81651. top = s->heap[SMALLEST]; \
  81652. s->heap[SMALLEST] = s->heap[s->heap_len--]; \
  81653. pqdownheap(s, tree, SMALLEST); \
  81654. }
  81655. /* ===========================================================================
  81656. * Compares to subtrees, using the tree depth as tie breaker when
  81657. * the subtrees have equal frequency. This minimizes the worst case length.
  81658. */
  81659. #define smaller(tree, n, m, depth) \
  81660. (tree[n].Freq < tree[m].Freq || \
  81661. (tree[n].Freq == tree[m].Freq && depth[n] <= depth[m]))
  81662. /* ===========================================================================
  81663. * Restore the heap property by moving down the tree starting at node k,
  81664. * exchanging a node with the smallest of its two sons if necessary, stopping
  81665. * when the heap property is re-established (each father smaller than its
  81666. * two sons).
  81667. */
  81668. local void pqdownheap (deflate_state *s,
  81669. ct_data *tree, /* the tree to restore */
  81670. int k) /* node to move down */
  81671. {
  81672. int v = s->heap[k];
  81673. int j = k << 1; /* left son of k */
  81674. while (j <= s->heap_len) {
  81675. /* Set j to the smallest of the two sons: */
  81676. if (j < s->heap_len &&
  81677. smaller(tree, s->heap[j+1], s->heap[j], s->depth)) {
  81678. j++;
  81679. }
  81680. /* Exit if v is smaller than both sons */
  81681. if (smaller(tree, v, s->heap[j], s->depth)) break;
  81682. /* Exchange v with the smallest son */
  81683. s->heap[k] = s->heap[j]; k = j;
  81684. /* And continue down the tree, setting j to the left son of k */
  81685. j <<= 1;
  81686. }
  81687. s->heap[k] = v;
  81688. }
  81689. /* ===========================================================================
  81690. * Compute the optimal bit lengths for a tree and update the total bit length
  81691. * for the current block.
  81692. * IN assertion: the fields freq and dad are set, heap[heap_max] and
  81693. * above are the tree nodes sorted by increasing frequency.
  81694. * OUT assertions: the field len is set to the optimal bit length, the
  81695. * array bl_count contains the frequencies for each bit length.
  81696. * The length opt_len is updated; static_len is also updated if stree is
  81697. * not null.
  81698. */
  81699. local void gen_bitlen (deflate_state *s, tree_desc *desc)
  81700. {
  81701. ct_data *tree = desc->dyn_tree;
  81702. int max_code = desc->max_code;
  81703. const ct_data *stree = desc->stat_desc->static_tree;
  81704. const intf *extra = desc->stat_desc->extra_bits;
  81705. int base = desc->stat_desc->extra_base;
  81706. int max_length = desc->stat_desc->max_length;
  81707. int h; /* heap index */
  81708. int n, m; /* iterate over the tree elements */
  81709. int bits; /* bit length */
  81710. int xbits; /* extra bits */
  81711. ush f; /* frequency */
  81712. int overflow = 0; /* number of elements with bit length too large */
  81713. for (bits = 0; bits <= MAX_BITS; bits++) s->bl_count[bits] = 0;
  81714. /* In a first pass, compute the optimal bit lengths (which may
  81715. * overflow in the case of the bit length tree).
  81716. */
  81717. tree[s->heap[s->heap_max]].Len = 0; /* root of the heap */
  81718. for (h = s->heap_max+1; h < HEAP_SIZE; h++) {
  81719. n = s->heap[h];
  81720. bits = tree[tree[n].Dad].Len + 1;
  81721. if (bits > max_length) bits = max_length, overflow++;
  81722. tree[n].Len = (ush)bits;
  81723. /* We overwrite tree[n].Dad which is no longer needed */
  81724. if (n > max_code) continue; /* not a leaf node */
  81725. s->bl_count[bits]++;
  81726. xbits = 0;
  81727. if (n >= base) xbits = extra[n-base];
  81728. f = tree[n].Freq;
  81729. s->opt_len += (ulg)f * (bits + xbits);
  81730. if (stree) s->static_len += (ulg)f * (stree[n].Len + xbits);
  81731. }
  81732. if (overflow == 0) return;
  81733. Trace((stderr,"\nbit length overflow\n"));
  81734. /* This happens for example on obj2 and pic of the Calgary corpus */
  81735. /* Find the first bit length which could increase: */
  81736. do {
  81737. bits = max_length-1;
  81738. while (s->bl_count[bits] == 0) bits--;
  81739. s->bl_count[bits]--; /* move one leaf down the tree */
  81740. s->bl_count[bits+1] += 2; /* move one overflow item as its brother */
  81741. s->bl_count[max_length]--;
  81742. /* The brother of the overflow item also moves one step up,
  81743. * but this does not affect bl_count[max_length]
  81744. */
  81745. overflow -= 2;
  81746. } while (overflow > 0);
  81747. /* Now recompute all bit lengths, scanning in increasing frequency.
  81748. * h is still equal to HEAP_SIZE. (It is simpler to reconstruct all
  81749. * lengths instead of fixing only the wrong ones. This idea is taken
  81750. * from 'ar' written by Haruhiko Okumura.)
  81751. */
  81752. for (bits = max_length; bits != 0; bits--) {
  81753. n = s->bl_count[bits];
  81754. while (n != 0) {
  81755. m = s->heap[--h];
  81756. if (m > max_code) continue;
  81757. if ((unsigned) tree[m].Len != (unsigned) bits) {
  81758. Trace((stderr,"code %d bits %d->%d\n", m, tree[m].Len, bits));
  81759. s->opt_len += ((long)bits - (long)tree[m].Len)
  81760. *(long)tree[m].Freq;
  81761. tree[m].Len = (ush)bits;
  81762. }
  81763. n--;
  81764. }
  81765. }
  81766. }
  81767. /* ===========================================================================
  81768. * Generate the codes for a given tree and bit counts (which need not be
  81769. * optimal).
  81770. * IN assertion: the array bl_count contains the bit length statistics for
  81771. * the given tree and the field len is set for all tree elements.
  81772. * OUT assertion: the field code is set for all tree elements of non
  81773. * zero code length.
  81774. */
  81775. local void gen_codes (ct_data *tree, /* the tree to decorate */
  81776. int max_code, /* largest code with non zero frequency */
  81777. ushf *bl_count) /* number of codes at each bit length */
  81778. {
  81779. ush next_code[MAX_BITS+1]; /* next code value for each bit length */
  81780. ush code = 0; /* running code value */
  81781. int bits; /* bit index */
  81782. int n; /* code index */
  81783. /* The distribution counts are first used to generate the code values
  81784. * without bit reversal.
  81785. */
  81786. for (bits = 1; bits <= MAX_BITS; bits++) {
  81787. next_code[bits] = code = (code + bl_count[bits-1]) << 1;
  81788. }
  81789. /* Check that the bit counts in bl_count are consistent. The last code
  81790. * must be all ones.
  81791. */
  81792. Assert (code + bl_count[MAX_BITS]-1 == (1<<MAX_BITS)-1,
  81793. "inconsistent bit counts");
  81794. Tracev((stderr,"\ngen_codes: max_code %d ", max_code));
  81795. for (n = 0; n <= max_code; n++) {
  81796. int len = tree[n].Len;
  81797. if (len == 0) continue;
  81798. /* Now reverse the bits */
  81799. tree[n].Code = bi_reverse(next_code[len]++, len);
  81800. Tracecv(tree != static_ltree, (stderr,"\nn %3d %c l %2d c %4x (%x) ",
  81801. n, (isgraph(n) ? n : ' '), len, tree[n].Code, next_code[len]-1));
  81802. }
  81803. }
  81804. /* ===========================================================================
  81805. * Construct one Huffman tree and assigns the code bit strings and lengths.
  81806. * Update the total bit length for the current block.
  81807. * IN assertion: the field freq is set for all tree elements.
  81808. * OUT assertions: the fields len and code are set to the optimal bit length
  81809. * and corresponding code. The length opt_len is updated; static_len is
  81810. * also updated if stree is not null. The field max_code is set.
  81811. */
  81812. local void build_tree (deflate_state *s,
  81813. tree_desc *desc) /* the tree descriptor */
  81814. {
  81815. ct_data *tree = desc->dyn_tree;
  81816. const ct_data *stree = desc->stat_desc->static_tree;
  81817. int elems = desc->stat_desc->elems;
  81818. int n, m; /* iterate over heap elements */
  81819. int max_code = -1; /* largest code with non zero frequency */
  81820. int node; /* new node being created */
  81821. /* Construct the initial heap, with least frequent element in
  81822. * heap[SMALLEST]. The sons of heap[n] are heap[2*n] and heap[2*n+1].
  81823. * heap[0] is not used.
  81824. */
  81825. s->heap_len = 0, s->heap_max = HEAP_SIZE;
  81826. for (n = 0; n < elems; n++) {
  81827. if (tree[n].Freq != 0) {
  81828. s->heap[++(s->heap_len)] = max_code = n;
  81829. s->depth[n] = 0;
  81830. } else {
  81831. tree[n].Len = 0;
  81832. }
  81833. }
  81834. /* The pkzip format requires that at least one distance code exists,
  81835. * and that at least one bit should be sent even if there is only one
  81836. * possible code. So to avoid special checks later on we force at least
  81837. * two codes of non zero frequency.
  81838. */
  81839. while (s->heap_len < 2) {
  81840. node = s->heap[++(s->heap_len)] = (max_code < 2 ? ++max_code : 0);
  81841. tree[node].Freq = 1;
  81842. s->depth[node] = 0;
  81843. s->opt_len--; if (stree) s->static_len -= stree[node].Len;
  81844. /* node is 0 or 1 so it does not have extra bits */
  81845. }
  81846. desc->max_code = max_code;
  81847. /* The elements heap[heap_len/2+1 .. heap_len] are leaves of the tree,
  81848. * establish sub-heaps of increasing lengths:
  81849. */
  81850. for (n = s->heap_len/2; n >= 1; n--) pqdownheap(s, tree, n);
  81851. /* Construct the Huffman tree by repeatedly combining the least two
  81852. * frequent nodes.
  81853. */
  81854. node = elems; /* next internal node of the tree */
  81855. do {
  81856. pqremove(s, tree, n); /* n = node of least frequency */
  81857. m = s->heap[SMALLEST]; /* m = node of next least frequency */
  81858. s->heap[--(s->heap_max)] = n; /* keep the nodes sorted by frequency */
  81859. s->heap[--(s->heap_max)] = m;
  81860. /* Create a new node father of n and m */
  81861. tree[node].Freq = tree[n].Freq + tree[m].Freq;
  81862. s->depth[node] = (uch)((s->depth[n] >= s->depth[m] ?
  81863. s->depth[n] : s->depth[m]) + 1);
  81864. tree[n].Dad = tree[m].Dad = (ush)node;
  81865. #ifdef DUMP_BL_TREE
  81866. if (tree == s->bl_tree) {
  81867. fprintf(stderr,"\nnode %d(%d), sons %d(%d) %d(%d)",
  81868. node, tree[node].Freq, n, tree[n].Freq, m, tree[m].Freq);
  81869. }
  81870. #endif
  81871. /* and insert the new node in the heap */
  81872. s->heap[SMALLEST] = node++;
  81873. pqdownheap(s, tree, SMALLEST);
  81874. } while (s->heap_len >= 2);
  81875. s->heap[--(s->heap_max)] = s->heap[SMALLEST];
  81876. /* At this point, the fields freq and dad are set. We can now
  81877. * generate the bit lengths.
  81878. */
  81879. gen_bitlen(s, (tree_desc *)desc);
  81880. /* The field len is now set, we can generate the bit codes */
  81881. gen_codes ((ct_data *)tree, max_code, s->bl_count);
  81882. }
  81883. /* ===========================================================================
  81884. * Scan a literal or distance tree to determine the frequencies of the codes
  81885. * in the bit length tree.
  81886. */
  81887. local void scan_tree (deflate_state *s,
  81888. ct_data *tree, /* the tree to be scanned */
  81889. int max_code) /* and its largest code of non zero frequency */
  81890. {
  81891. int n; /* iterates over all tree elements */
  81892. int prevlen = -1; /* last emitted length */
  81893. int curlen; /* length of current code */
  81894. int nextlen = tree[0].Len; /* length of next code */
  81895. int count = 0; /* repeat count of the current code */
  81896. int max_count = 7; /* max repeat count */
  81897. int min_count = 4; /* min repeat count */
  81898. if (nextlen == 0) max_count = 138, min_count = 3;
  81899. tree[max_code+1].Len = (ush)0xffff; /* guard */
  81900. for (n = 0; n <= max_code; n++) {
  81901. curlen = nextlen; nextlen = tree[n+1].Len;
  81902. if (++count < max_count && curlen == nextlen) {
  81903. continue;
  81904. } else if (count < min_count) {
  81905. s->bl_tree[curlen].Freq += count;
  81906. } else if (curlen != 0) {
  81907. if (curlen != prevlen) s->bl_tree[curlen].Freq++;
  81908. s->bl_tree[REP_3_6].Freq++;
  81909. } else if (count <= 10) {
  81910. s->bl_tree[REPZ_3_10].Freq++;
  81911. } else {
  81912. s->bl_tree[REPZ_11_138].Freq++;
  81913. }
  81914. count = 0; prevlen = curlen;
  81915. if (nextlen == 0) {
  81916. max_count = 138, min_count = 3;
  81917. } else if (curlen == nextlen) {
  81918. max_count = 6, min_count = 3;
  81919. } else {
  81920. max_count = 7, min_count = 4;
  81921. }
  81922. }
  81923. }
  81924. /* ===========================================================================
  81925. * Send a literal or distance tree in compressed form, using the codes in
  81926. * bl_tree.
  81927. */
  81928. local void send_tree (deflate_state *s,
  81929. ct_data *tree, /* the tree to be scanned */
  81930. int max_code) /* and its largest code of non zero frequency */
  81931. {
  81932. int n; /* iterates over all tree elements */
  81933. int prevlen = -1; /* last emitted length */
  81934. int curlen; /* length of current code */
  81935. int nextlen = tree[0].Len; /* length of next code */
  81936. int count = 0; /* repeat count of the current code */
  81937. int max_count = 7; /* max repeat count */
  81938. int min_count = 4; /* min repeat count */
  81939. /* tree[max_code+1].Len = -1; */ /* guard already set */
  81940. if (nextlen == 0) max_count = 138, min_count = 3;
  81941. for (n = 0; n <= max_code; n++) {
  81942. curlen = nextlen; nextlen = tree[n+1].Len;
  81943. if (++count < max_count && curlen == nextlen) {
  81944. continue;
  81945. } else if (count < min_count) {
  81946. do { send_code(s, curlen, s->bl_tree); } while (--count != 0);
  81947. } else if (curlen != 0) {
  81948. if (curlen != prevlen) {
  81949. send_code(s, curlen, s->bl_tree); count--;
  81950. }
  81951. Assert(count >= 3 && count <= 6, " 3_6?");
  81952. send_code(s, REP_3_6, s->bl_tree); send_bits(s, count-3, 2);
  81953. } else if (count <= 10) {
  81954. send_code(s, REPZ_3_10, s->bl_tree); send_bits(s, count-3, 3);
  81955. } else {
  81956. send_code(s, REPZ_11_138, s->bl_tree); send_bits(s, count-11, 7);
  81957. }
  81958. count = 0; prevlen = curlen;
  81959. if (nextlen == 0) {
  81960. max_count = 138, min_count = 3;
  81961. } else if (curlen == nextlen) {
  81962. max_count = 6, min_count = 3;
  81963. } else {
  81964. max_count = 7, min_count = 4;
  81965. }
  81966. }
  81967. }
  81968. /* ===========================================================================
  81969. * Construct the Huffman tree for the bit lengths and return the index in
  81970. * bl_order of the last bit length code to send.
  81971. */
  81972. local int build_bl_tree (deflate_state *s)
  81973. {
  81974. int max_blindex; /* index of last bit length code of non zero freq */
  81975. /* Determine the bit length frequencies for literal and distance trees */
  81976. scan_tree(s, (ct_data *)s->dyn_ltree, s->l_desc.max_code);
  81977. scan_tree(s, (ct_data *)s->dyn_dtree, s->d_desc.max_code);
  81978. /* Build the bit length tree: */
  81979. build_tree(s, (tree_desc *)(&(s->bl_desc)));
  81980. /* opt_len now includes the length of the tree representations, except
  81981. * the lengths of the bit lengths codes and the 5+5+4 bits for the counts.
  81982. */
  81983. /* Determine the number of bit length codes to send. The pkzip format
  81984. * requires that at least 4 bit length codes be sent. (appnote.txt says
  81985. * 3 but the actual value used is 4.)
  81986. */
  81987. for (max_blindex = BL_CODES-1; max_blindex >= 3; max_blindex--) {
  81988. if (s->bl_tree[bl_order[max_blindex]].Len != 0) break;
  81989. }
  81990. /* Update opt_len to include the bit length tree and counts */
  81991. s->opt_len += 3*(max_blindex+1) + 5+5+4;
  81992. Tracev((stderr, "\ndyn trees: dyn %ld, stat %ld",
  81993. s->opt_len, s->static_len));
  81994. return max_blindex;
  81995. }
  81996. /* ===========================================================================
  81997. * Send the header for a block using dynamic Huffman trees: the counts, the
  81998. * lengths of the bit length codes, the literal tree and the distance tree.
  81999. * IN assertion: lcodes >= 257, dcodes >= 1, blcodes >= 4.
  82000. */
  82001. local void send_all_trees (deflate_state *s,
  82002. int lcodes, int dcodes, int blcodes) /* number of codes for each tree */
  82003. {
  82004. int rank; /* index in bl_order */
  82005. Assert (lcodes >= 257 && dcodes >= 1 && blcodes >= 4, "not enough codes");
  82006. Assert (lcodes <= L_CODES && dcodes <= D_CODES && blcodes <= BL_CODES,
  82007. "too many codes");
  82008. Tracev((stderr, "\nbl counts: "));
  82009. send_bits(s, lcodes-257, 5); /* not +255 as stated in appnote.txt */
  82010. send_bits(s, dcodes-1, 5);
  82011. send_bits(s, blcodes-4, 4); /* not -3 as stated in appnote.txt */
  82012. for (rank = 0; rank < blcodes; rank++) {
  82013. Tracev((stderr, "\nbl code %2d ", bl_order[rank]));
  82014. send_bits(s, s->bl_tree[bl_order[rank]].Len, 3);
  82015. }
  82016. Tracev((stderr, "\nbl tree: sent %ld", s->bits_sent));
  82017. send_tree(s, (ct_data *)s->dyn_ltree, lcodes-1); /* literal tree */
  82018. Tracev((stderr, "\nlit tree: sent %ld", s->bits_sent));
  82019. send_tree(s, (ct_data *)s->dyn_dtree, dcodes-1); /* distance tree */
  82020. Tracev((stderr, "\ndist tree: sent %ld", s->bits_sent));
  82021. }
  82022. /* ===========================================================================
  82023. * Send a stored block
  82024. */
  82025. void _tr_stored_block (deflate_state *s, charf *buf, ulg stored_len, int eof)
  82026. {
  82027. send_bits(s, (STORED_BLOCK<<1)+eof, 3); /* send block type */
  82028. #ifdef DEBUG
  82029. s->compressed_len = (s->compressed_len + 3 + 7) & (ulg)~7L;
  82030. s->compressed_len += (stored_len + 4) << 3;
  82031. #endif
  82032. copy_block(s, buf, (unsigned)stored_len, 1); /* with header */
  82033. }
  82034. /* ===========================================================================
  82035. * Send one empty static block to give enough lookahead for inflate.
  82036. * This takes 10 bits, of which 7 may remain in the bit buffer.
  82037. * The current inflate code requires 9 bits of lookahead. If the
  82038. * last two codes for the previous block (real code plus EOB) were coded
  82039. * on 5 bits or less, inflate may have only 5+3 bits of lookahead to decode
  82040. * the last real code. In this case we send two empty static blocks instead
  82041. * of one. (There are no problems if the previous block is stored or fixed.)
  82042. * To simplify the code, we assume the worst case of last real code encoded
  82043. * on one bit only.
  82044. */
  82045. void _tr_align (deflate_state *s)
  82046. {
  82047. send_bits(s, STATIC_TREES<<1, 3);
  82048. send_code(s, END_BLOCK, static_ltree);
  82049. #ifdef DEBUG
  82050. s->compressed_len += 10L; /* 3 for block type, 7 for EOB */
  82051. #endif
  82052. bi_flush(s);
  82053. /* Of the 10 bits for the empty block, we have already sent
  82054. * (10 - bi_valid) bits. The lookahead for the last real code (before
  82055. * the EOB of the previous block) was thus at least one plus the length
  82056. * of the EOB plus what we have just sent of the empty static block.
  82057. */
  82058. if (1 + s->last_eob_len + 10 - s->bi_valid < 9) {
  82059. send_bits(s, STATIC_TREES<<1, 3);
  82060. send_code(s, END_BLOCK, static_ltree);
  82061. #ifdef DEBUG
  82062. s->compressed_len += 10L;
  82063. #endif
  82064. bi_flush(s);
  82065. }
  82066. s->last_eob_len = 7;
  82067. }
  82068. /* ===========================================================================
  82069. * Determine the best encoding for the current block: dynamic trees, static
  82070. * trees or store, and output the encoded block to the zip file.
  82071. */
  82072. void _tr_flush_block (deflate_state *s,
  82073. charf *buf, /* input block, or NULL if too old */
  82074. ulg stored_len, /* length of input block */
  82075. int eof) /* true if this is the last block for a file */
  82076. {
  82077. ulg opt_lenb, static_lenb; /* opt_len and static_len in bytes */
  82078. int max_blindex = 0; /* index of last bit length code of non zero freq */
  82079. /* Build the Huffman trees unless a stored block is forced */
  82080. if (s->level > 0) {
  82081. /* Check if the file is binary or text */
  82082. if (stored_len > 0 && s->strm->data_type == Z_UNKNOWN)
  82083. set_data_type(s);
  82084. /* Construct the literal and distance trees */
  82085. build_tree(s, (tree_desc *)(&(s->l_desc)));
  82086. Tracev((stderr, "\nlit data: dyn %ld, stat %ld", s->opt_len,
  82087. s->static_len));
  82088. build_tree(s, (tree_desc *)(&(s->d_desc)));
  82089. Tracev((stderr, "\ndist data: dyn %ld, stat %ld", s->opt_len,
  82090. s->static_len));
  82091. /* At this point, opt_len and static_len are the total bit lengths of
  82092. * the compressed block data, excluding the tree representations.
  82093. */
  82094. /* Build the bit length tree for the above two trees, and get the index
  82095. * in bl_order of the last bit length code to send.
  82096. */
  82097. max_blindex = build_bl_tree(s);
  82098. /* Determine the best encoding. Compute the block lengths in bytes. */
  82099. opt_lenb = (s->opt_len+3+7)>>3;
  82100. static_lenb = (s->static_len+3+7)>>3;
  82101. Tracev((stderr, "\nopt %lu(%lu) stat %lu(%lu) stored %lu lit %u ",
  82102. opt_lenb, s->opt_len, static_lenb, s->static_len, stored_len,
  82103. s->last_lit));
  82104. if (static_lenb <= opt_lenb) opt_lenb = static_lenb;
  82105. } else {
  82106. Assert(buf != (char*)0, "lost buf");
  82107. opt_lenb = static_lenb = stored_len + 5; /* force a stored block */
  82108. }
  82109. #ifdef FORCE_STORED
  82110. if (buf != (char*)0) { /* force stored block */
  82111. #else
  82112. if (stored_len+4 <= opt_lenb && buf != (char*)0) {
  82113. /* 4: two words for the lengths */
  82114. #endif
  82115. /* The test buf != NULL is only necessary if LIT_BUFSIZE > WSIZE.
  82116. * Otherwise we can't have processed more than WSIZE input bytes since
  82117. * the last block flush, because compression would have been
  82118. * successful. If LIT_BUFSIZE <= WSIZE, it is never too late to
  82119. * transform a block into a stored block.
  82120. */
  82121. _tr_stored_block(s, buf, stored_len, eof);
  82122. #ifdef FORCE_STATIC
  82123. } else if (static_lenb >= 0) { /* force static trees */
  82124. #else
  82125. } else if (s->strategy == Z_FIXED || static_lenb == opt_lenb) {
  82126. #endif
  82127. send_bits(s, (STATIC_TREES<<1)+eof, 3);
  82128. compress_block(s, (ct_data *)static_ltree, (ct_data *)static_dtree);
  82129. #ifdef DEBUG
  82130. s->compressed_len += 3 + s->static_len;
  82131. #endif
  82132. } else {
  82133. send_bits(s, (DYN_TREES<<1)+eof, 3);
  82134. send_all_trees(s, s->l_desc.max_code+1, s->d_desc.max_code+1,
  82135. max_blindex+1);
  82136. compress_block(s, (ct_data *)s->dyn_ltree, (ct_data *)s->dyn_dtree);
  82137. #ifdef DEBUG
  82138. s->compressed_len += 3 + s->opt_len;
  82139. #endif
  82140. }
  82141. Assert (s->compressed_len == s->bits_sent, "bad compressed size");
  82142. /* The above check is made mod 2^32, for files larger than 512 MB
  82143. * and uLong implemented on 32 bits.
  82144. */
  82145. init_block(s);
  82146. if (eof) {
  82147. bi_windup(s);
  82148. #ifdef DEBUG
  82149. s->compressed_len += 7; /* align on byte boundary */
  82150. #endif
  82151. }
  82152. Tracev((stderr,"\ncomprlen %lu(%lu) ", s->compressed_len>>3,
  82153. s->compressed_len-7*eof));
  82154. }
  82155. /* ===========================================================================
  82156. * Save the match info and tally the frequency counts. Return true if
  82157. * the current block must be flushed.
  82158. */
  82159. int _tr_tally (deflate_state *s,
  82160. unsigned dist, /* distance of matched string */
  82161. unsigned lc) /* match length-MIN_MATCH or unmatched char (if dist==0) */
  82162. {
  82163. s->d_buf[s->last_lit] = (ush)dist;
  82164. s->l_buf[s->last_lit++] = (uch)lc;
  82165. if (dist == 0) {
  82166. /* lc is the unmatched char */
  82167. s->dyn_ltree[lc].Freq++;
  82168. } else {
  82169. s->matches++;
  82170. /* Here, lc is the match length - MIN_MATCH */
  82171. dist--; /* dist = match distance - 1 */
  82172. Assert((ush)dist < (ush)MAX_DIST(s) &&
  82173. (ush)lc <= (ush)(MAX_MATCH-MIN_MATCH) &&
  82174. (ush)d_code(dist) < (ush)D_CODES, "_tr_tally: bad match");
  82175. s->dyn_ltree[_length_code[lc]+LITERALS+1].Freq++;
  82176. s->dyn_dtree[d_code(dist)].Freq++;
  82177. }
  82178. #ifdef TRUNCATE_BLOCK
  82179. /* Try to guess if it is profitable to stop the current block here */
  82180. if ((s->last_lit & 0x1fff) == 0 && s->level > 2) {
  82181. /* Compute an upper bound for the compressed length */
  82182. ulg out_length = (ulg)s->last_lit*8L;
  82183. ulg in_length = (ulg)((long)s->strstart - s->block_start);
  82184. int dcode;
  82185. for (dcode = 0; dcode < D_CODES; dcode++) {
  82186. out_length += (ulg)s->dyn_dtree[dcode].Freq *
  82187. (5L+extra_dbits[dcode]);
  82188. }
  82189. out_length >>= 3;
  82190. Tracev((stderr,"\nlast_lit %u, in %ld, out ~%ld(%ld%%) ",
  82191. s->last_lit, in_length, out_length,
  82192. 100L - out_length*100L/in_length));
  82193. if (s->matches < s->last_lit/2 && out_length < in_length/2) return 1;
  82194. }
  82195. #endif
  82196. return (s->last_lit == s->lit_bufsize-1);
  82197. /* We avoid equality with lit_bufsize because of wraparound at 64K
  82198. * on 16 bit machines and because stored blocks are restricted to
  82199. * 64K-1 bytes.
  82200. */
  82201. }
  82202. /* ===========================================================================
  82203. * Send the block data compressed using the given Huffman trees
  82204. */
  82205. local void compress_block (deflate_state *s,
  82206. ct_data *ltree, /* literal tree */
  82207. ct_data *dtree) /* distance tree */
  82208. {
  82209. unsigned dist; /* distance of matched string */
  82210. int lc; /* match length or unmatched char (if dist == 0) */
  82211. unsigned lx = 0; /* running index in l_buf */
  82212. unsigned code; /* the code to send */
  82213. int extra; /* number of extra bits to send */
  82214. if (s->last_lit != 0) do {
  82215. dist = s->d_buf[lx];
  82216. lc = s->l_buf[lx++];
  82217. if (dist == 0) {
  82218. send_code(s, lc, ltree); /* send a literal byte */
  82219. Tracecv(isgraph(lc), (stderr," '%c' ", lc));
  82220. } else {
  82221. /* Here, lc is the match length - MIN_MATCH */
  82222. code = _length_code[lc];
  82223. send_code(s, code+LITERALS+1, ltree); /* send the length code */
  82224. extra = extra_lbits[code];
  82225. if (extra != 0) {
  82226. lc -= base_length[code];
  82227. send_bits(s, lc, extra); /* send the extra length bits */
  82228. }
  82229. dist--; /* dist is now the match distance - 1 */
  82230. code = d_code(dist);
  82231. Assert (code < D_CODES, "bad d_code");
  82232. send_code(s, code, dtree); /* send the distance code */
  82233. extra = extra_dbits[code];
  82234. if (extra != 0) {
  82235. dist -= base_dist[code];
  82236. send_bits(s, dist, extra); /* send the extra distance bits */
  82237. }
  82238. } /* literal or match pair ? */
  82239. /* Check that the overlay between pending_buf and d_buf+l_buf is ok: */
  82240. Assert((uInt)(s->pending) < s->lit_bufsize + 2*lx,
  82241. "pendingBuf overflow");
  82242. } while (lx < s->last_lit);
  82243. send_code(s, END_BLOCK, ltree);
  82244. s->last_eob_len = ltree[END_BLOCK].Len;
  82245. }
  82246. /* ===========================================================================
  82247. * Set the data type to BINARY or TEXT, using a crude approximation:
  82248. * set it to Z_TEXT if all symbols are either printable characters (33 to 255)
  82249. * or white spaces (9 to 13, or 32); or set it to Z_BINARY otherwise.
  82250. * IN assertion: the fields Freq of dyn_ltree are set.
  82251. */
  82252. local void set_data_type (deflate_state *s)
  82253. {
  82254. int n;
  82255. for (n = 0; n < 9; n++)
  82256. if (s->dyn_ltree[n].Freq != 0)
  82257. break;
  82258. if (n == 9)
  82259. for (n = 14; n < 32; n++)
  82260. if (s->dyn_ltree[n].Freq != 0)
  82261. break;
  82262. s->strm->data_type = (n == 32) ? Z_TEXT : Z_BINARY;
  82263. }
  82264. /* ===========================================================================
  82265. * Reverse the first len bits of a code, using straightforward code (a faster
  82266. * method would use a table)
  82267. * IN assertion: 1 <= len <= 15
  82268. */
  82269. local unsigned bi_reverse (unsigned code, int len)
  82270. {
  82271. register unsigned res = 0;
  82272. do {
  82273. res |= code & 1;
  82274. code >>= 1, res <<= 1;
  82275. } while (--len > 0);
  82276. return res >> 1;
  82277. }
  82278. /* ===========================================================================
  82279. * Flush the bit buffer, keeping at most 7 bits in it.
  82280. */
  82281. local void bi_flush (deflate_state *s)
  82282. {
  82283. if (s->bi_valid == 16) {
  82284. put_short(s, s->bi_buf);
  82285. s->bi_buf = 0;
  82286. s->bi_valid = 0;
  82287. } else if (s->bi_valid >= 8) {
  82288. put_byte(s, (Byte)s->bi_buf);
  82289. s->bi_buf >>= 8;
  82290. s->bi_valid -= 8;
  82291. }
  82292. }
  82293. /* ===========================================================================
  82294. * Flush the bit buffer and align the output on a byte boundary
  82295. */
  82296. local void bi_windup (deflate_state *s)
  82297. {
  82298. if (s->bi_valid > 8) {
  82299. put_short(s, s->bi_buf);
  82300. } else if (s->bi_valid > 0) {
  82301. put_byte(s, (Byte)s->bi_buf);
  82302. }
  82303. s->bi_buf = 0;
  82304. s->bi_valid = 0;
  82305. #ifdef DEBUG
  82306. s->bits_sent = (s->bits_sent+7) & ~7;
  82307. #endif
  82308. }
  82309. /* ===========================================================================
  82310. * Copy a stored block, storing first the length and its
  82311. * one's complement if requested.
  82312. */
  82313. local void copy_block(deflate_state *s,
  82314. charf *buf, /* the input data */
  82315. unsigned len, /* its length */
  82316. int header) /* true if block header must be written */
  82317. {
  82318. bi_windup(s); /* align on byte boundary */
  82319. s->last_eob_len = 8; /* enough lookahead for inflate */
  82320. if (header) {
  82321. put_short(s, (ush)len);
  82322. put_short(s, (ush)~len);
  82323. #ifdef DEBUG
  82324. s->bits_sent += 2*16;
  82325. #endif
  82326. }
  82327. #ifdef DEBUG
  82328. s->bits_sent += (ulg)len<<3;
  82329. #endif
  82330. while (len--) {
  82331. put_byte(s, *buf++);
  82332. }
  82333. }
  82334. /*** End of inlined file: trees.c ***/
  82335. /*** Start of inlined file: zutil.c ***/
  82336. /* @(#) $Id: zutil.c,v 1.1 2007/06/07 17:54:37 jules_rms Exp $ */
  82337. #ifndef NO_DUMMY_DECL
  82338. struct internal_state {int dummy;}; /* for buggy compilers */
  82339. #endif
  82340. const char * const z_errmsg[10] = {
  82341. "need dictionary", /* Z_NEED_DICT 2 */
  82342. "stream end", /* Z_STREAM_END 1 */
  82343. "", /* Z_OK 0 */
  82344. "file error", /* Z_ERRNO (-1) */
  82345. "stream error", /* Z_STREAM_ERROR (-2) */
  82346. "data error", /* Z_DATA_ERROR (-3) */
  82347. "insufficient memory", /* Z_MEM_ERROR (-4) */
  82348. "buffer error", /* Z_BUF_ERROR (-5) */
  82349. "incompatible version",/* Z_VERSION_ERROR (-6) */
  82350. ""};
  82351. /*const char * ZEXPORT zlibVersion()
  82352. {
  82353. return ZLIB_VERSION;
  82354. }
  82355. uLong ZEXPORT zlibCompileFlags()
  82356. {
  82357. uLong flags;
  82358. flags = 0;
  82359. switch (sizeof(uInt)) {
  82360. case 2: break;
  82361. case 4: flags += 1; break;
  82362. case 8: flags += 2; break;
  82363. default: flags += 3;
  82364. }
  82365. switch (sizeof(uLong)) {
  82366. case 2: break;
  82367. case 4: flags += 1 << 2; break;
  82368. case 8: flags += 2 << 2; break;
  82369. default: flags += 3 << 2;
  82370. }
  82371. switch (sizeof(voidpf)) {
  82372. case 2: break;
  82373. case 4: flags += 1 << 4; break;
  82374. case 8: flags += 2 << 4; break;
  82375. default: flags += 3 << 4;
  82376. }
  82377. switch (sizeof(z_off_t)) {
  82378. case 2: break;
  82379. case 4: flags += 1 << 6; break;
  82380. case 8: flags += 2 << 6; break;
  82381. default: flags += 3 << 6;
  82382. }
  82383. #ifdef DEBUG
  82384. flags += 1 << 8;
  82385. #endif
  82386. #if defined(ASMV) || defined(ASMINF)
  82387. flags += 1 << 9;
  82388. #endif
  82389. #ifdef ZLIB_WINAPI
  82390. flags += 1 << 10;
  82391. #endif
  82392. #ifdef BUILDFIXED
  82393. flags += 1 << 12;
  82394. #endif
  82395. #ifdef DYNAMIC_CRC_TABLE
  82396. flags += 1 << 13;
  82397. #endif
  82398. #ifdef NO_GZCOMPRESS
  82399. flags += 1L << 16;
  82400. #endif
  82401. #ifdef NO_GZIP
  82402. flags += 1L << 17;
  82403. #endif
  82404. #ifdef PKZIP_BUG_WORKAROUND
  82405. flags += 1L << 20;
  82406. #endif
  82407. #ifdef FASTEST
  82408. flags += 1L << 21;
  82409. #endif
  82410. #ifdef STDC
  82411. # ifdef NO_vsnprintf
  82412. flags += 1L << 25;
  82413. # ifdef HAS_vsprintf_void
  82414. flags += 1L << 26;
  82415. # endif
  82416. # else
  82417. # ifdef HAS_vsnprintf_void
  82418. flags += 1L << 26;
  82419. # endif
  82420. # endif
  82421. #else
  82422. flags += 1L << 24;
  82423. # ifdef NO_snprintf
  82424. flags += 1L << 25;
  82425. # ifdef HAS_sprintf_void
  82426. flags += 1L << 26;
  82427. # endif
  82428. # else
  82429. # ifdef HAS_snprintf_void
  82430. flags += 1L << 26;
  82431. # endif
  82432. # endif
  82433. #endif
  82434. return flags;
  82435. }*/
  82436. #ifdef DEBUG
  82437. # ifndef verbose
  82438. # define verbose 0
  82439. # endif
  82440. int z_verbose = verbose;
  82441. void z_error (const char *m)
  82442. {
  82443. fprintf(stderr, "%s\n", m);
  82444. exit(1);
  82445. }
  82446. #endif
  82447. /* exported to allow conversion of error code to string for compress() and
  82448. * uncompress()
  82449. */
  82450. const char * ZEXPORT zError(int err)
  82451. {
  82452. return ERR_MSG(err);
  82453. }
  82454. #if defined(_WIN32_WCE)
  82455. /* The Microsoft C Run-Time Library for Windows CE doesn't have
  82456. * errno. We define it as a global variable to simplify porting.
  82457. * Its value is always 0 and should not be used.
  82458. */
  82459. int errno = 0;
  82460. #endif
  82461. #ifndef HAVE_MEMCPY
  82462. void zmemcpy(dest, source, len)
  82463. Bytef* dest;
  82464. const Bytef* source;
  82465. uInt len;
  82466. {
  82467. if (len == 0) return;
  82468. do {
  82469. *dest++ = *source++; /* ??? to be unrolled */
  82470. } while (--len != 0);
  82471. }
  82472. int zmemcmp(s1, s2, len)
  82473. const Bytef* s1;
  82474. const Bytef* s2;
  82475. uInt len;
  82476. {
  82477. uInt j;
  82478. for (j = 0; j < len; j++) {
  82479. if (s1[j] != s2[j]) return 2*(s1[j] > s2[j])-1;
  82480. }
  82481. return 0;
  82482. }
  82483. void zmemzero(dest, len)
  82484. Bytef* dest;
  82485. uInt len;
  82486. {
  82487. if (len == 0) return;
  82488. do {
  82489. *dest++ = 0; /* ??? to be unrolled */
  82490. } while (--len != 0);
  82491. }
  82492. #endif
  82493. #ifdef SYS16BIT
  82494. #ifdef __TURBOC__
  82495. /* Turbo C in 16-bit mode */
  82496. # define MY_ZCALLOC
  82497. /* Turbo C malloc() does not allow dynamic allocation of 64K bytes
  82498. * and farmalloc(64K) returns a pointer with an offset of 8, so we
  82499. * must fix the pointer. Warning: the pointer must be put back to its
  82500. * original form in order to free it, use zcfree().
  82501. */
  82502. #define MAX_PTR 10
  82503. /* 10*64K = 640K */
  82504. local int next_ptr = 0;
  82505. typedef struct ptr_table_s {
  82506. voidpf org_ptr;
  82507. voidpf new_ptr;
  82508. } ptr_table;
  82509. local ptr_table table[MAX_PTR];
  82510. /* This table is used to remember the original form of pointers
  82511. * to large buffers (64K). Such pointers are normalized with a zero offset.
  82512. * Since MSDOS is not a preemptive multitasking OS, this table is not
  82513. * protected from concurrent access. This hack doesn't work anyway on
  82514. * a protected system like OS/2. Use Microsoft C instead.
  82515. */
  82516. voidpf zcalloc (voidpf opaque, unsigned items, unsigned size)
  82517. {
  82518. voidpf buf = opaque; /* just to make some compilers happy */
  82519. ulg bsize = (ulg)items*size;
  82520. /* If we allocate less than 65520 bytes, we assume that farmalloc
  82521. * will return a usable pointer which doesn't have to be normalized.
  82522. */
  82523. if (bsize < 65520L) {
  82524. buf = farmalloc(bsize);
  82525. if (*(ush*)&buf != 0) return buf;
  82526. } else {
  82527. buf = farmalloc(bsize + 16L);
  82528. }
  82529. if (buf == NULL || next_ptr >= MAX_PTR) return NULL;
  82530. table[next_ptr].org_ptr = buf;
  82531. /* Normalize the pointer to seg:0 */
  82532. *((ush*)&buf+1) += ((ush)((uch*)buf-0) + 15) >> 4;
  82533. *(ush*)&buf = 0;
  82534. table[next_ptr++].new_ptr = buf;
  82535. return buf;
  82536. }
  82537. void zcfree (voidpf opaque, voidpf ptr)
  82538. {
  82539. int n;
  82540. if (*(ush*)&ptr != 0) { /* object < 64K */
  82541. farfree(ptr);
  82542. return;
  82543. }
  82544. /* Find the original pointer */
  82545. for (n = 0; n < next_ptr; n++) {
  82546. if (ptr != table[n].new_ptr) continue;
  82547. farfree(table[n].org_ptr);
  82548. while (++n < next_ptr) {
  82549. table[n-1] = table[n];
  82550. }
  82551. next_ptr--;
  82552. return;
  82553. }
  82554. ptr = opaque; /* just to make some compilers happy */
  82555. Assert(0, "zcfree: ptr not found");
  82556. }
  82557. #endif /* __TURBOC__ */
  82558. #ifdef M_I86
  82559. /* Microsoft C in 16-bit mode */
  82560. # define MY_ZCALLOC
  82561. #if (!defined(_MSC_VER) || (_MSC_VER <= 600))
  82562. # define _halloc halloc
  82563. # define _hfree hfree
  82564. #endif
  82565. voidpf zcalloc (voidpf opaque, unsigned items, unsigned size)
  82566. {
  82567. if (opaque) opaque = 0; /* to make compiler happy */
  82568. return _halloc((long)items, size);
  82569. }
  82570. void zcfree (voidpf opaque, voidpf ptr)
  82571. {
  82572. if (opaque) opaque = 0; /* to make compiler happy */
  82573. _hfree(ptr);
  82574. }
  82575. #endif /* M_I86 */
  82576. #endif /* SYS16BIT */
  82577. #ifndef MY_ZCALLOC /* Any system without a special alloc function */
  82578. #ifndef STDC
  82579. extern voidp malloc OF((uInt size));
  82580. extern voidp calloc OF((uInt items, uInt size));
  82581. extern void free OF((voidpf ptr));
  82582. #endif
  82583. voidpf zcalloc (voidpf opaque, unsigned items, unsigned size)
  82584. {
  82585. if (opaque) items += size - size; /* make compiler happy */
  82586. return sizeof(uInt) > 2 ? (voidpf)malloc(items * size) :
  82587. (voidpf)calloc(items, size);
  82588. }
  82589. void zcfree (voidpf opaque, voidpf ptr)
  82590. {
  82591. free(ptr);
  82592. if (opaque) return; /* make compiler happy */
  82593. }
  82594. #endif /* MY_ZCALLOC */
  82595. /*** End of inlined file: zutil.c ***/
  82596. #undef Byte
  82597. }
  82598. #else
  82599. #include <zlib.h>
  82600. #endif
  82601. }
  82602. #if JUCE_MSVC
  82603. #pragma warning (pop)
  82604. #endif
  82605. BEGIN_JUCE_NAMESPACE
  82606. // internal helper object that holds the zlib structures so they don't have to be
  82607. // included publicly.
  82608. class GZIPDecompressHelper
  82609. {
  82610. public:
  82611. GZIPDecompressHelper (const bool noWrap)
  82612. : finished (true),
  82613. needsDictionary (false),
  82614. error (true),
  82615. streamIsValid (false),
  82616. data (0),
  82617. dataSize (0)
  82618. {
  82619. using namespace zlibNamespace;
  82620. zerostruct (stream);
  82621. streamIsValid = (inflateInit2 (&stream, noWrap ? -MAX_WBITS : MAX_WBITS) == Z_OK);
  82622. finished = error = ! streamIsValid;
  82623. }
  82624. ~GZIPDecompressHelper()
  82625. {
  82626. using namespace zlibNamespace;
  82627. if (streamIsValid)
  82628. inflateEnd (&stream);
  82629. }
  82630. bool needsInput() const throw() { return dataSize <= 0; }
  82631. void setInput (uint8* const data_, const int size) throw()
  82632. {
  82633. data = data_;
  82634. dataSize = size;
  82635. }
  82636. int doNextBlock (uint8* const dest, const int destSize)
  82637. {
  82638. using namespace zlibNamespace;
  82639. if (streamIsValid && data != 0 && ! finished)
  82640. {
  82641. stream.next_in = data;
  82642. stream.next_out = dest;
  82643. stream.avail_in = dataSize;
  82644. stream.avail_out = destSize;
  82645. switch (inflate (&stream, Z_PARTIAL_FLUSH))
  82646. {
  82647. case Z_STREAM_END:
  82648. finished = true;
  82649. // deliberate fall-through
  82650. case Z_OK:
  82651. data += dataSize - stream.avail_in;
  82652. dataSize = stream.avail_in;
  82653. return destSize - stream.avail_out;
  82654. case Z_NEED_DICT:
  82655. needsDictionary = true;
  82656. data += dataSize - stream.avail_in;
  82657. dataSize = stream.avail_in;
  82658. break;
  82659. case Z_DATA_ERROR:
  82660. case Z_MEM_ERROR:
  82661. error = true;
  82662. default:
  82663. break;
  82664. }
  82665. }
  82666. return 0;
  82667. }
  82668. bool finished, needsDictionary, error, streamIsValid;
  82669. private:
  82670. zlibNamespace::z_stream stream;
  82671. uint8* data;
  82672. int dataSize;
  82673. GZIPDecompressHelper (const GZIPDecompressHelper&);
  82674. GZIPDecompressHelper& operator= (const GZIPDecompressHelper&);
  82675. };
  82676. const int gzipDecompBufferSize = 32768;
  82677. GZIPDecompressorInputStream::GZIPDecompressorInputStream (InputStream* const sourceStream_,
  82678. const bool deleteSourceWhenDestroyed,
  82679. const bool noWrap_,
  82680. const int64 uncompressedStreamLength_)
  82681. : sourceStream (sourceStream_),
  82682. streamToDelete (deleteSourceWhenDestroyed ? sourceStream_ : 0),
  82683. uncompressedStreamLength (uncompressedStreamLength_),
  82684. noWrap (noWrap_),
  82685. isEof (false),
  82686. activeBufferSize (0),
  82687. originalSourcePos (sourceStream_->getPosition()),
  82688. currentPos (0),
  82689. buffer (gzipDecompBufferSize),
  82690. helper (new GZIPDecompressHelper (noWrap_))
  82691. {
  82692. }
  82693. GZIPDecompressorInputStream::~GZIPDecompressorInputStream()
  82694. {
  82695. }
  82696. int64 GZIPDecompressorInputStream::getTotalLength()
  82697. {
  82698. return uncompressedStreamLength;
  82699. }
  82700. int GZIPDecompressorInputStream::read (void* destBuffer, int howMany)
  82701. {
  82702. if ((howMany > 0) && ! isEof)
  82703. {
  82704. jassert (destBuffer != 0);
  82705. if (destBuffer != 0)
  82706. {
  82707. int numRead = 0;
  82708. uint8* d = static_cast <uint8*> (destBuffer);
  82709. while (! helper->error)
  82710. {
  82711. const int n = helper->doNextBlock (d, howMany);
  82712. currentPos += n;
  82713. if (n == 0)
  82714. {
  82715. if (helper->finished || helper->needsDictionary)
  82716. {
  82717. isEof = true;
  82718. return numRead;
  82719. }
  82720. if (helper->needsInput())
  82721. {
  82722. activeBufferSize = sourceStream->read (buffer, gzipDecompBufferSize);
  82723. if (activeBufferSize > 0)
  82724. {
  82725. helper->setInput (buffer, activeBufferSize);
  82726. }
  82727. else
  82728. {
  82729. isEof = true;
  82730. return numRead;
  82731. }
  82732. }
  82733. }
  82734. else
  82735. {
  82736. numRead += n;
  82737. howMany -= n;
  82738. d += n;
  82739. if (howMany <= 0)
  82740. return numRead;
  82741. }
  82742. }
  82743. }
  82744. }
  82745. return 0;
  82746. }
  82747. bool GZIPDecompressorInputStream::isExhausted()
  82748. {
  82749. return helper->error || isEof;
  82750. }
  82751. int64 GZIPDecompressorInputStream::getPosition()
  82752. {
  82753. return currentPos;
  82754. }
  82755. bool GZIPDecompressorInputStream::setPosition (int64 newPos)
  82756. {
  82757. if (newPos < currentPos)
  82758. {
  82759. // to go backwards, reset the stream and start again..
  82760. isEof = false;
  82761. activeBufferSize = 0;
  82762. currentPos = 0;
  82763. helper = new GZIPDecompressHelper (noWrap);
  82764. sourceStream->setPosition (originalSourcePos);
  82765. }
  82766. skipNextBytes (newPos - currentPos);
  82767. return true;
  82768. }
  82769. END_JUCE_NAMESPACE
  82770. /*** End of inlined file: juce_GZIPDecompressorInputStream.cpp ***/
  82771. #endif
  82772. #if JUCE_BUILD_NATIVE && ! JUCE_ONLY_BUILD_CORE_LIBRARY
  82773. /*** Start of inlined file: juce_FlacAudioFormat.cpp ***/
  82774. #if JUCE_USE_FLAC
  82775. #if JUCE_WINDOWS
  82776. #include <windows.h>
  82777. #endif
  82778. #ifdef _MSC_VER
  82779. #pragma warning (disable : 4505)
  82780. #pragma warning (push)
  82781. #endif
  82782. namespace FlacNamespace
  82783. {
  82784. #if JUCE_INCLUDE_FLAC_CODE
  82785. #define FLAC__NO_DLL 1
  82786. #if ! defined (SIZE_MAX)
  82787. #define SIZE_MAX 0xffffffff
  82788. #endif
  82789. #define __STDC_LIMIT_MACROS 1
  82790. /*** Start of inlined file: all.h ***/
  82791. #ifndef FLAC__ALL_H
  82792. #define FLAC__ALL_H
  82793. /*** Start of inlined file: export.h ***/
  82794. #ifndef FLAC__EXPORT_H
  82795. #define FLAC__EXPORT_H
  82796. /** \file include/FLAC/export.h
  82797. *
  82798. * \brief
  82799. * This module contains #defines and symbols for exporting function
  82800. * calls, and providing version information and compiled-in features.
  82801. *
  82802. * See the \link flac_export export \endlink module.
  82803. */
  82804. /** \defgroup flac_export FLAC/export.h: export symbols
  82805. * \ingroup flac
  82806. *
  82807. * \brief
  82808. * This module contains #defines and symbols for exporting function
  82809. * calls, and providing version information and compiled-in features.
  82810. *
  82811. * If you are compiling with MSVC and will link to the static library
  82812. * (libFLAC.lib) you should define FLAC__NO_DLL in your project to
  82813. * make sure the symbols are exported properly.
  82814. *
  82815. * \{
  82816. */
  82817. #if defined(FLAC__NO_DLL) || !defined(_MSC_VER)
  82818. #define FLAC_API
  82819. #else
  82820. #ifdef FLAC_API_EXPORTS
  82821. #define FLAC_API _declspec(dllexport)
  82822. #else
  82823. #define FLAC_API _declspec(dllimport)
  82824. #endif
  82825. #endif
  82826. /** These #defines will mirror the libtool-based library version number, see
  82827. * http://www.gnu.org/software/libtool/manual.html#Libtool-versioning
  82828. */
  82829. #define FLAC_API_VERSION_CURRENT 10
  82830. #define FLAC_API_VERSION_REVISION 0 /**< see above */
  82831. #define FLAC_API_VERSION_AGE 2 /**< see above */
  82832. #ifdef __cplusplus
  82833. extern "C" {
  82834. #endif
  82835. /** \c 1 if the library has been compiled with support for Ogg FLAC, else \c 0. */
  82836. extern FLAC_API int FLAC_API_SUPPORTS_OGG_FLAC;
  82837. #ifdef __cplusplus
  82838. }
  82839. #endif
  82840. /* \} */
  82841. #endif
  82842. /*** End of inlined file: export.h ***/
  82843. /*** Start of inlined file: assert.h ***/
  82844. #ifndef FLAC__ASSERT_H
  82845. #define FLAC__ASSERT_H
  82846. /* we need this since some compilers (like MSVC) leave assert()s on release code (and we don't want to use their ASSERT) */
  82847. #ifdef DEBUG
  82848. #include <assert.h>
  82849. #define FLAC__ASSERT(x) assert(x)
  82850. #define FLAC__ASSERT_DECLARATION(x) x
  82851. #else
  82852. #define FLAC__ASSERT(x)
  82853. #define FLAC__ASSERT_DECLARATION(x)
  82854. #endif
  82855. #endif
  82856. /*** End of inlined file: assert.h ***/
  82857. /*** Start of inlined file: callback.h ***/
  82858. #ifndef FLAC__CALLBACK_H
  82859. #define FLAC__CALLBACK_H
  82860. /*** Start of inlined file: ordinals.h ***/
  82861. #ifndef FLAC__ORDINALS_H
  82862. #define FLAC__ORDINALS_H
  82863. #if !(defined(_MSC_VER) || defined(__BORLANDC__) || defined(__EMX__))
  82864. #include <inttypes.h>
  82865. #endif
  82866. typedef signed char FLAC__int8;
  82867. typedef unsigned char FLAC__uint8;
  82868. #if defined(_MSC_VER) || defined(__BORLANDC__)
  82869. typedef __int16 FLAC__int16;
  82870. typedef __int32 FLAC__int32;
  82871. typedef __int64 FLAC__int64;
  82872. typedef unsigned __int16 FLAC__uint16;
  82873. typedef unsigned __int32 FLAC__uint32;
  82874. typedef unsigned __int64 FLAC__uint64;
  82875. #elif defined(__EMX__)
  82876. typedef short FLAC__int16;
  82877. typedef long FLAC__int32;
  82878. typedef long long FLAC__int64;
  82879. typedef unsigned short FLAC__uint16;
  82880. typedef unsigned long FLAC__uint32;
  82881. typedef unsigned long long FLAC__uint64;
  82882. #else
  82883. typedef int16_t FLAC__int16;
  82884. typedef int32_t FLAC__int32;
  82885. typedef int64_t FLAC__int64;
  82886. typedef uint16_t FLAC__uint16;
  82887. typedef uint32_t FLAC__uint32;
  82888. typedef uint64_t FLAC__uint64;
  82889. #endif
  82890. typedef int FLAC__bool;
  82891. typedef FLAC__uint8 FLAC__byte;
  82892. #ifdef true
  82893. #undef true
  82894. #endif
  82895. #ifdef false
  82896. #undef false
  82897. #endif
  82898. #ifndef __cplusplus
  82899. #define true 1
  82900. #define false 0
  82901. #endif
  82902. #endif
  82903. /*** End of inlined file: ordinals.h ***/
  82904. #include <stdlib.h> /* for size_t */
  82905. /** \file include/FLAC/callback.h
  82906. *
  82907. * \brief
  82908. * This module defines the structures for describing I/O callbacks
  82909. * to the other FLAC interfaces.
  82910. *
  82911. * See the detailed documentation for callbacks in the
  82912. * \link flac_callbacks callbacks \endlink module.
  82913. */
  82914. /** \defgroup flac_callbacks FLAC/callback.h: I/O callback structures
  82915. * \ingroup flac
  82916. *
  82917. * \brief
  82918. * This module defines the structures for describing I/O callbacks
  82919. * to the other FLAC interfaces.
  82920. *
  82921. * The purpose of the I/O callback functions is to create a common way
  82922. * for the metadata interfaces to handle I/O.
  82923. *
  82924. * Originally the metadata interfaces required filenames as the way of
  82925. * specifying FLAC files to operate on. This is problematic in some
  82926. * environments so there is an additional option to specify a set of
  82927. * callbacks for doing I/O on the FLAC file, instead of the filename.
  82928. *
  82929. * In addition to the callbacks, a FLAC__IOHandle type is defined as an
  82930. * opaque structure for a data source.
  82931. *
  82932. * The callback function prototypes are similar (but not identical) to the
  82933. * stdio functions fread, fwrite, fseek, ftell, feof, and fclose. If you use
  82934. * stdio streams to implement the callbacks, you can pass fread, fwrite, and
  82935. * fclose anywhere a FLAC__IOCallback_Read, FLAC__IOCallback_Write, or
  82936. * FLAC__IOCallback_Close is required, and a FILE* anywhere a FLAC__IOHandle
  82937. * is required. \warning You generally CANNOT directly use fseek or ftell
  82938. * for FLAC__IOCallback_Seek or FLAC__IOCallback_Tell since on most systems
  82939. * these use 32-bit offsets and FLAC requires 64-bit offsets to deal with
  82940. * large files. You will have to find an equivalent function (e.g. ftello),
  82941. * or write a wrapper. The same is true for feof() since this is usually
  82942. * implemented as a macro, not as a function whose address can be taken.
  82943. *
  82944. * \{
  82945. */
  82946. #ifdef __cplusplus
  82947. extern "C" {
  82948. #endif
  82949. /** This is the opaque handle type used by the callbacks. Typically
  82950. * this is a \c FILE* or address of a file descriptor.
  82951. */
  82952. typedef void* FLAC__IOHandle;
  82953. /** Signature for the read callback.
  82954. * The signature and semantics match POSIX fread() implementations
  82955. * and can generally be used interchangeably.
  82956. *
  82957. * \param ptr The address of the read buffer.
  82958. * \param size The size of the records to be read.
  82959. * \param nmemb The number of records to be read.
  82960. * \param handle The handle to the data source.
  82961. * \retval size_t
  82962. * The number of records read.
  82963. */
  82964. typedef size_t (*FLAC__IOCallback_Read) (void *ptr, size_t size, size_t nmemb, FLAC__IOHandle handle);
  82965. /** Signature for the write callback.
  82966. * The signature and semantics match POSIX fwrite() implementations
  82967. * and can generally be used interchangeably.
  82968. *
  82969. * \param ptr The address of the write buffer.
  82970. * \param size The size of the records to be written.
  82971. * \param nmemb The number of records to be written.
  82972. * \param handle The handle to the data source.
  82973. * \retval size_t
  82974. * The number of records written.
  82975. */
  82976. typedef size_t (*FLAC__IOCallback_Write) (const void *ptr, size_t size, size_t nmemb, FLAC__IOHandle handle);
  82977. /** Signature for the seek callback.
  82978. * The signature and semantics mostly match POSIX fseek() WITH ONE IMPORTANT
  82979. * EXCEPTION: the offset is a 64-bit type whereas fseek() is generally 'long'
  82980. * and 32-bits wide.
  82981. *
  82982. * \param handle The handle to the data source.
  82983. * \param offset The new position, relative to \a whence
  82984. * \param whence \c SEEK_SET, \c SEEK_CUR, or \c SEEK_END
  82985. * \retval int
  82986. * \c 0 on success, \c -1 on error.
  82987. */
  82988. typedef int (*FLAC__IOCallback_Seek) (FLAC__IOHandle handle, FLAC__int64 offset, int whence);
  82989. /** Signature for the tell callback.
  82990. * The signature and semantics mostly match POSIX ftell() WITH ONE IMPORTANT
  82991. * EXCEPTION: the offset is a 64-bit type whereas ftell() is generally 'long'
  82992. * and 32-bits wide.
  82993. *
  82994. * \param handle The handle to the data source.
  82995. * \retval FLAC__int64
  82996. * The current position on success, \c -1 on error.
  82997. */
  82998. typedef FLAC__int64 (*FLAC__IOCallback_Tell) (FLAC__IOHandle handle);
  82999. /** Signature for the EOF callback.
  83000. * The signature and semantics mostly match POSIX feof() but WATCHOUT:
  83001. * on many systems, feof() is a macro, so in this case a wrapper function
  83002. * must be provided instead.
  83003. *
  83004. * \param handle The handle to the data source.
  83005. * \retval int
  83006. * \c 0 if not at end of file, nonzero if at end of file.
  83007. */
  83008. typedef int (*FLAC__IOCallback_Eof) (FLAC__IOHandle handle);
  83009. /** Signature for the close callback.
  83010. * The signature and semantics match POSIX fclose() implementations
  83011. * and can generally be used interchangeably.
  83012. *
  83013. * \param handle The handle to the data source.
  83014. * \retval int
  83015. * \c 0 on success, \c EOF on error.
  83016. */
  83017. typedef int (*FLAC__IOCallback_Close) (FLAC__IOHandle handle);
  83018. /** A structure for holding a set of callbacks.
  83019. * Each FLAC interface that requires a FLAC__IOCallbacks structure will
  83020. * describe which of the callbacks are required. The ones that are not
  83021. * required may be set to NULL.
  83022. *
  83023. * If the seek requirement for an interface is optional, you can signify that
  83024. * a data sorce is not seekable by setting the \a seek field to \c NULL.
  83025. */
  83026. typedef struct {
  83027. FLAC__IOCallback_Read read;
  83028. FLAC__IOCallback_Write write;
  83029. FLAC__IOCallback_Seek seek;
  83030. FLAC__IOCallback_Tell tell;
  83031. FLAC__IOCallback_Eof eof;
  83032. FLAC__IOCallback_Close close;
  83033. } FLAC__IOCallbacks;
  83034. /* \} */
  83035. #ifdef __cplusplus
  83036. }
  83037. #endif
  83038. #endif
  83039. /*** End of inlined file: callback.h ***/
  83040. /*** Start of inlined file: format.h ***/
  83041. #ifndef FLAC__FORMAT_H
  83042. #define FLAC__FORMAT_H
  83043. #ifdef __cplusplus
  83044. extern "C" {
  83045. #endif
  83046. /** \file include/FLAC/format.h
  83047. *
  83048. * \brief
  83049. * This module contains structure definitions for the representation
  83050. * of FLAC format components in memory. These are the basic
  83051. * structures used by the rest of the interfaces.
  83052. *
  83053. * See the detailed documentation in the
  83054. * \link flac_format format \endlink module.
  83055. */
  83056. /** \defgroup flac_format FLAC/format.h: format components
  83057. * \ingroup flac
  83058. *
  83059. * \brief
  83060. * This module contains structure definitions for the representation
  83061. * of FLAC format components in memory. These are the basic
  83062. * structures used by the rest of the interfaces.
  83063. *
  83064. * First, you should be familiar with the
  83065. * <A HREF="../format.html">FLAC format</A>. Many of the values here
  83066. * follow directly from the specification. As a user of libFLAC, the
  83067. * interesting parts really are the structures that describe the frame
  83068. * header and metadata blocks.
  83069. *
  83070. * The format structures here are very primitive, designed to store
  83071. * information in an efficient way. Reading information from the
  83072. * structures is easy but creating or modifying them directly is
  83073. * more complex. For the most part, as a user of a library, editing
  83074. * is not necessary; however, for metadata blocks it is, so there are
  83075. * convenience functions provided in the \link flac_metadata metadata
  83076. * module \endlink to simplify the manipulation of metadata blocks.
  83077. *
  83078. * \note
  83079. * It's not the best convention, but symbols ending in _LEN are in bits
  83080. * and _LENGTH are in bytes. _LENGTH symbols are \#defines instead of
  83081. * global variables because they are usually used when declaring byte
  83082. * arrays and some compilers require compile-time knowledge of array
  83083. * sizes when declared on the stack.
  83084. *
  83085. * \{
  83086. */
  83087. /*
  83088. Most of the values described in this file are defined by the FLAC
  83089. format specification. There is nothing to tune here.
  83090. */
  83091. /** The largest legal metadata type code. */
  83092. #define FLAC__MAX_METADATA_TYPE_CODE (126u)
  83093. /** The minimum block size, in samples, permitted by the format. */
  83094. #define FLAC__MIN_BLOCK_SIZE (16u)
  83095. /** The maximum block size, in samples, permitted by the format. */
  83096. #define FLAC__MAX_BLOCK_SIZE (65535u)
  83097. /** The maximum block size, in samples, permitted by the FLAC subset for
  83098. * sample rates up to 48kHz. */
  83099. #define FLAC__SUBSET_MAX_BLOCK_SIZE_48000HZ (4608u)
  83100. /** The maximum number of channels permitted by the format. */
  83101. #define FLAC__MAX_CHANNELS (8u)
  83102. /** The minimum sample resolution permitted by the format. */
  83103. #define FLAC__MIN_BITS_PER_SAMPLE (4u)
  83104. /** The maximum sample resolution permitted by the format. */
  83105. #define FLAC__MAX_BITS_PER_SAMPLE (32u)
  83106. /** The maximum sample resolution permitted by libFLAC.
  83107. *
  83108. * \warning
  83109. * FLAC__MAX_BITS_PER_SAMPLE is the limit of the FLAC format. However,
  83110. * the reference encoder/decoder is currently limited to 24 bits because
  83111. * of prevalent 32-bit math, so make sure and use this value when
  83112. * appropriate.
  83113. */
  83114. #define FLAC__REFERENCE_CODEC_MAX_BITS_PER_SAMPLE (24u)
  83115. /** The maximum sample rate permitted by the format. The value is
  83116. * ((2 ^ 16) - 1) * 10; see <A HREF="../format.html">FLAC format</A>
  83117. * as to why.
  83118. */
  83119. #define FLAC__MAX_SAMPLE_RATE (655350u)
  83120. /** The maximum LPC order permitted by the format. */
  83121. #define FLAC__MAX_LPC_ORDER (32u)
  83122. /** The maximum LPC order permitted by the FLAC subset for sample rates
  83123. * up to 48kHz. */
  83124. #define FLAC__SUBSET_MAX_LPC_ORDER_48000HZ (12u)
  83125. /** The minimum quantized linear predictor coefficient precision
  83126. * permitted by the format.
  83127. */
  83128. #define FLAC__MIN_QLP_COEFF_PRECISION (5u)
  83129. /** The maximum quantized linear predictor coefficient precision
  83130. * permitted by the format.
  83131. */
  83132. #define FLAC__MAX_QLP_COEFF_PRECISION (15u)
  83133. /** The maximum order of the fixed predictors permitted by the format. */
  83134. #define FLAC__MAX_FIXED_ORDER (4u)
  83135. /** The maximum Rice partition order permitted by the format. */
  83136. #define FLAC__MAX_RICE_PARTITION_ORDER (15u)
  83137. /** The maximum Rice partition order permitted by the FLAC Subset. */
  83138. #define FLAC__SUBSET_MAX_RICE_PARTITION_ORDER (8u)
  83139. /** The version string of the release, stamped onto the libraries and binaries.
  83140. *
  83141. * \note
  83142. * This does not correspond to the shared library version number, which
  83143. * is used to determine binary compatibility.
  83144. */
  83145. extern FLAC_API const char *FLAC__VERSION_STRING;
  83146. /** The vendor string inserted by the encoder into the VORBIS_COMMENT block.
  83147. * This is a NUL-terminated ASCII string; when inserted into the
  83148. * VORBIS_COMMENT the trailing null is stripped.
  83149. */
  83150. extern FLAC_API const char *FLAC__VENDOR_STRING;
  83151. /** The byte string representation of the beginning of a FLAC stream. */
  83152. extern FLAC_API const FLAC__byte FLAC__STREAM_SYNC_STRING[4]; /* = "fLaC" */
  83153. /** The 32-bit integer big-endian representation of the beginning of
  83154. * a FLAC stream.
  83155. */
  83156. extern FLAC_API const unsigned FLAC__STREAM_SYNC; /* = 0x664C6143 */
  83157. /** The length of the FLAC signature in bits. */
  83158. extern FLAC_API const unsigned FLAC__STREAM_SYNC_LEN; /* = 32 bits */
  83159. /** The length of the FLAC signature in bytes. */
  83160. #define FLAC__STREAM_SYNC_LENGTH (4u)
  83161. /*****************************************************************************
  83162. *
  83163. * Subframe structures
  83164. *
  83165. *****************************************************************************/
  83166. /*****************************************************************************/
  83167. /** An enumeration of the available entropy coding methods. */
  83168. typedef enum {
  83169. FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE = 0,
  83170. /**< Residual is coded by partitioning into contexts, each with it's own
  83171. * 4-bit Rice parameter. */
  83172. FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE2 = 1
  83173. /**< Residual is coded by partitioning into contexts, each with it's own
  83174. * 5-bit Rice parameter. */
  83175. } FLAC__EntropyCodingMethodType;
  83176. /** Maps a FLAC__EntropyCodingMethodType to a C string.
  83177. *
  83178. * Using a FLAC__EntropyCodingMethodType as the index to this array will
  83179. * give the string equivalent. The contents should not be modified.
  83180. */
  83181. extern FLAC_API const char * const FLAC__EntropyCodingMethodTypeString[];
  83182. /** Contents of a Rice partitioned residual
  83183. */
  83184. typedef struct {
  83185. unsigned *parameters;
  83186. /**< The Rice parameters for each context. */
  83187. unsigned *raw_bits;
  83188. /**< Widths for escape-coded partitions. Will be non-zero for escaped
  83189. * partitions and zero for unescaped partitions.
  83190. */
  83191. unsigned capacity_by_order;
  83192. /**< The capacity of the \a parameters and \a raw_bits arrays
  83193. * specified as an order, i.e. the number of array elements
  83194. * allocated is 2 ^ \a capacity_by_order.
  83195. */
  83196. } FLAC__EntropyCodingMethod_PartitionedRiceContents;
  83197. /** Header for a Rice partitioned residual. (c.f. <A HREF="../format.html#partitioned_rice">format specification</A>)
  83198. */
  83199. typedef struct {
  83200. unsigned order;
  83201. /**< The partition order, i.e. # of contexts = 2 ^ \a order. */
  83202. const FLAC__EntropyCodingMethod_PartitionedRiceContents *contents;
  83203. /**< The context's Rice parameters and/or raw bits. */
  83204. } FLAC__EntropyCodingMethod_PartitionedRice;
  83205. extern FLAC_API const unsigned FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE_ORDER_LEN; /**< == 4 (bits) */
  83206. extern FLAC_API const unsigned FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE_PARAMETER_LEN; /**< == 4 (bits) */
  83207. extern FLAC_API const unsigned FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE2_PARAMETER_LEN; /**< == 5 (bits) */
  83208. extern FLAC_API const unsigned FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE_RAW_LEN; /**< == 5 (bits) */
  83209. extern FLAC_API const unsigned FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE_ESCAPE_PARAMETER;
  83210. /**< == (1<<FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE_PARAMETER_LEN)-1 */
  83211. extern FLAC_API const unsigned FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE2_ESCAPE_PARAMETER;
  83212. /**< == (1<<FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE2_PARAMETER_LEN)-1 */
  83213. /** Header for the entropy coding method. (c.f. <A HREF="../format.html#residual">format specification</A>)
  83214. */
  83215. typedef struct {
  83216. FLAC__EntropyCodingMethodType type;
  83217. union {
  83218. FLAC__EntropyCodingMethod_PartitionedRice partitioned_rice;
  83219. } data;
  83220. } FLAC__EntropyCodingMethod;
  83221. extern FLAC_API const unsigned FLAC__ENTROPY_CODING_METHOD_TYPE_LEN; /**< == 2 (bits) */
  83222. /*****************************************************************************/
  83223. /** An enumeration of the available subframe types. */
  83224. typedef enum {
  83225. FLAC__SUBFRAME_TYPE_CONSTANT = 0, /**< constant signal */
  83226. FLAC__SUBFRAME_TYPE_VERBATIM = 1, /**< uncompressed signal */
  83227. FLAC__SUBFRAME_TYPE_FIXED = 2, /**< fixed polynomial prediction */
  83228. FLAC__SUBFRAME_TYPE_LPC = 3 /**< linear prediction */
  83229. } FLAC__SubframeType;
  83230. /** Maps a FLAC__SubframeType to a C string.
  83231. *
  83232. * Using a FLAC__SubframeType as the index to this array will
  83233. * give the string equivalent. The contents should not be modified.
  83234. */
  83235. extern FLAC_API const char * const FLAC__SubframeTypeString[];
  83236. /** CONSTANT subframe. (c.f. <A HREF="../format.html#subframe_constant">format specification</A>)
  83237. */
  83238. typedef struct {
  83239. FLAC__int32 value; /**< The constant signal value. */
  83240. } FLAC__Subframe_Constant;
  83241. /** VERBATIM subframe. (c.f. <A HREF="../format.html#subframe_verbatim">format specification</A>)
  83242. */
  83243. typedef struct {
  83244. const FLAC__int32 *data; /**< A pointer to verbatim signal. */
  83245. } FLAC__Subframe_Verbatim;
  83246. /** FIXED subframe. (c.f. <A HREF="../format.html#subframe_fixed">format specification</A>)
  83247. */
  83248. typedef struct {
  83249. FLAC__EntropyCodingMethod entropy_coding_method;
  83250. /**< The residual coding method. */
  83251. unsigned order;
  83252. /**< The polynomial order. */
  83253. FLAC__int32 warmup[FLAC__MAX_FIXED_ORDER];
  83254. /**< Warmup samples to prime the predictor, length == order. */
  83255. const FLAC__int32 *residual;
  83256. /**< The residual signal, length == (blocksize minus order) samples. */
  83257. } FLAC__Subframe_Fixed;
  83258. /** LPC subframe. (c.f. <A HREF="../format.html#subframe_lpc">format specification</A>)
  83259. */
  83260. typedef struct {
  83261. FLAC__EntropyCodingMethod entropy_coding_method;
  83262. /**< The residual coding method. */
  83263. unsigned order;
  83264. /**< The FIR order. */
  83265. unsigned qlp_coeff_precision;
  83266. /**< Quantized FIR filter coefficient precision in bits. */
  83267. int quantization_level;
  83268. /**< The qlp coeff shift needed. */
  83269. FLAC__int32 qlp_coeff[FLAC__MAX_LPC_ORDER];
  83270. /**< FIR filter coefficients. */
  83271. FLAC__int32 warmup[FLAC__MAX_LPC_ORDER];
  83272. /**< Warmup samples to prime the predictor, length == order. */
  83273. const FLAC__int32 *residual;
  83274. /**< The residual signal, length == (blocksize minus order) samples. */
  83275. } FLAC__Subframe_LPC;
  83276. extern FLAC_API const unsigned FLAC__SUBFRAME_LPC_QLP_COEFF_PRECISION_LEN; /**< == 4 (bits) */
  83277. extern FLAC_API const unsigned FLAC__SUBFRAME_LPC_QLP_SHIFT_LEN; /**< == 5 (bits) */
  83278. /** FLAC subframe structure. (c.f. <A HREF="../format.html#subframe">format specification</A>)
  83279. */
  83280. typedef struct {
  83281. FLAC__SubframeType type;
  83282. union {
  83283. FLAC__Subframe_Constant constant;
  83284. FLAC__Subframe_Fixed fixed;
  83285. FLAC__Subframe_LPC lpc;
  83286. FLAC__Subframe_Verbatim verbatim;
  83287. } data;
  83288. unsigned wasted_bits;
  83289. } FLAC__Subframe;
  83290. /** == 1 (bit)
  83291. *
  83292. * This used to be a zero-padding bit (hence the name
  83293. * FLAC__SUBFRAME_ZERO_PAD_LEN) but is now a reserved bit. It still has a
  83294. * mandatory value of \c 0 but in the future may take on the value \c 0 or \c 1
  83295. * to mean something else.
  83296. */
  83297. extern FLAC_API const unsigned FLAC__SUBFRAME_ZERO_PAD_LEN;
  83298. extern FLAC_API const unsigned FLAC__SUBFRAME_TYPE_LEN; /**< == 6 (bits) */
  83299. extern FLAC_API const unsigned FLAC__SUBFRAME_WASTED_BITS_FLAG_LEN; /**< == 1 (bit) */
  83300. extern FLAC_API const unsigned FLAC__SUBFRAME_TYPE_CONSTANT_BYTE_ALIGNED_MASK; /**< = 0x00 */
  83301. extern FLAC_API const unsigned FLAC__SUBFRAME_TYPE_VERBATIM_BYTE_ALIGNED_MASK; /**< = 0x02 */
  83302. extern FLAC_API const unsigned FLAC__SUBFRAME_TYPE_FIXED_BYTE_ALIGNED_MASK; /**< = 0x10 */
  83303. extern FLAC_API const unsigned FLAC__SUBFRAME_TYPE_LPC_BYTE_ALIGNED_MASK; /**< = 0x40 */
  83304. /*****************************************************************************/
  83305. /*****************************************************************************
  83306. *
  83307. * Frame structures
  83308. *
  83309. *****************************************************************************/
  83310. /** An enumeration of the available channel assignments. */
  83311. typedef enum {
  83312. FLAC__CHANNEL_ASSIGNMENT_INDEPENDENT = 0, /**< independent channels */
  83313. FLAC__CHANNEL_ASSIGNMENT_LEFT_SIDE = 1, /**< left+side stereo */
  83314. FLAC__CHANNEL_ASSIGNMENT_RIGHT_SIDE = 2, /**< right+side stereo */
  83315. FLAC__CHANNEL_ASSIGNMENT_MID_SIDE = 3 /**< mid+side stereo */
  83316. } FLAC__ChannelAssignment;
  83317. /** Maps a FLAC__ChannelAssignment to a C string.
  83318. *
  83319. * Using a FLAC__ChannelAssignment as the index to this array will
  83320. * give the string equivalent. The contents should not be modified.
  83321. */
  83322. extern FLAC_API const char * const FLAC__ChannelAssignmentString[];
  83323. /** An enumeration of the possible frame numbering methods. */
  83324. typedef enum {
  83325. FLAC__FRAME_NUMBER_TYPE_FRAME_NUMBER, /**< number contains the frame number */
  83326. FLAC__FRAME_NUMBER_TYPE_SAMPLE_NUMBER /**< number contains the sample number of first sample in frame */
  83327. } FLAC__FrameNumberType;
  83328. /** Maps a FLAC__FrameNumberType to a C string.
  83329. *
  83330. * Using a FLAC__FrameNumberType as the index to this array will
  83331. * give the string equivalent. The contents should not be modified.
  83332. */
  83333. extern FLAC_API const char * const FLAC__FrameNumberTypeString[];
  83334. /** FLAC frame header structure. (c.f. <A HREF="../format.html#frame_header">format specification</A>)
  83335. */
  83336. typedef struct {
  83337. unsigned blocksize;
  83338. /**< The number of samples per subframe. */
  83339. unsigned sample_rate;
  83340. /**< The sample rate in Hz. */
  83341. unsigned channels;
  83342. /**< The number of channels (== number of subframes). */
  83343. FLAC__ChannelAssignment channel_assignment;
  83344. /**< The channel assignment for the frame. */
  83345. unsigned bits_per_sample;
  83346. /**< The sample resolution. */
  83347. FLAC__FrameNumberType number_type;
  83348. /**< The numbering scheme used for the frame. As a convenience, the
  83349. * decoder will always convert a frame number to a sample number because
  83350. * the rules are complex. */
  83351. union {
  83352. FLAC__uint32 frame_number;
  83353. FLAC__uint64 sample_number;
  83354. } number;
  83355. /**< The frame number or sample number of first sample in frame;
  83356. * use the \a number_type value to determine which to use. */
  83357. FLAC__uint8 crc;
  83358. /**< CRC-8 (polynomial = x^8 + x^2 + x^1 + x^0, initialized with 0)
  83359. * of the raw frame header bytes, meaning everything before the CRC byte
  83360. * including the sync code.
  83361. */
  83362. } FLAC__FrameHeader;
  83363. extern FLAC_API const unsigned FLAC__FRAME_HEADER_SYNC; /**< == 0x3ffe; the frame header sync code */
  83364. extern FLAC_API const unsigned FLAC__FRAME_HEADER_SYNC_LEN; /**< == 14 (bits) */
  83365. extern FLAC_API const unsigned FLAC__FRAME_HEADER_RESERVED_LEN; /**< == 1 (bits) */
  83366. extern FLAC_API const unsigned FLAC__FRAME_HEADER_BLOCKING_STRATEGY_LEN; /**< == 1 (bits) */
  83367. extern FLAC_API const unsigned FLAC__FRAME_HEADER_BLOCK_SIZE_LEN; /**< == 4 (bits) */
  83368. extern FLAC_API const unsigned FLAC__FRAME_HEADER_SAMPLE_RATE_LEN; /**< == 4 (bits) */
  83369. extern FLAC_API const unsigned FLAC__FRAME_HEADER_CHANNEL_ASSIGNMENT_LEN; /**< == 4 (bits) */
  83370. extern FLAC_API const unsigned FLAC__FRAME_HEADER_BITS_PER_SAMPLE_LEN; /**< == 3 (bits) */
  83371. extern FLAC_API const unsigned FLAC__FRAME_HEADER_ZERO_PAD_LEN; /**< == 1 (bit) */
  83372. extern FLAC_API const unsigned FLAC__FRAME_HEADER_CRC_LEN; /**< == 8 (bits) */
  83373. /** FLAC frame footer structure. (c.f. <A HREF="../format.html#frame_footer">format specification</A>)
  83374. */
  83375. typedef struct {
  83376. FLAC__uint16 crc;
  83377. /**< CRC-16 (polynomial = x^16 + x^15 + x^2 + x^0, initialized with
  83378. * 0) of the bytes before the crc, back to and including the frame header
  83379. * sync code.
  83380. */
  83381. } FLAC__FrameFooter;
  83382. extern FLAC_API const unsigned FLAC__FRAME_FOOTER_CRC_LEN; /**< == 16 (bits) */
  83383. /** FLAC frame structure. (c.f. <A HREF="../format.html#frame">format specification</A>)
  83384. */
  83385. typedef struct {
  83386. FLAC__FrameHeader header;
  83387. FLAC__Subframe subframes[FLAC__MAX_CHANNELS];
  83388. FLAC__FrameFooter footer;
  83389. } FLAC__Frame;
  83390. /*****************************************************************************/
  83391. /*****************************************************************************
  83392. *
  83393. * Meta-data structures
  83394. *
  83395. *****************************************************************************/
  83396. /** An enumeration of the available metadata block types. */
  83397. typedef enum {
  83398. FLAC__METADATA_TYPE_STREAMINFO = 0,
  83399. /**< <A HREF="../format.html#metadata_block_streaminfo">STREAMINFO</A> block */
  83400. FLAC__METADATA_TYPE_PADDING = 1,
  83401. /**< <A HREF="../format.html#metadata_block_padding">PADDING</A> block */
  83402. FLAC__METADATA_TYPE_APPLICATION = 2,
  83403. /**< <A HREF="../format.html#metadata_block_application">APPLICATION</A> block */
  83404. FLAC__METADATA_TYPE_SEEKTABLE = 3,
  83405. /**< <A HREF="../format.html#metadata_block_seektable">SEEKTABLE</A> block */
  83406. FLAC__METADATA_TYPE_VORBIS_COMMENT = 4,
  83407. /**< <A HREF="../format.html#metadata_block_vorbis_comment">VORBISCOMMENT</A> block (a.k.a. FLAC tags) */
  83408. FLAC__METADATA_TYPE_CUESHEET = 5,
  83409. /**< <A HREF="../format.html#metadata_block_cuesheet">CUESHEET</A> block */
  83410. FLAC__METADATA_TYPE_PICTURE = 6,
  83411. /**< <A HREF="../format.html#metadata_block_picture">PICTURE</A> block */
  83412. FLAC__METADATA_TYPE_UNDEFINED = 7
  83413. /**< marker to denote beginning of undefined type range; this number will increase as new metadata types are added */
  83414. } FLAC__MetadataType;
  83415. /** Maps a FLAC__MetadataType to a C string.
  83416. *
  83417. * Using a FLAC__MetadataType as the index to this array will
  83418. * give the string equivalent. The contents should not be modified.
  83419. */
  83420. extern FLAC_API const char * const FLAC__MetadataTypeString[];
  83421. /** FLAC STREAMINFO structure. (c.f. <A HREF="../format.html#metadata_block_streaminfo">format specification</A>)
  83422. */
  83423. typedef struct {
  83424. unsigned min_blocksize, max_blocksize;
  83425. unsigned min_framesize, max_framesize;
  83426. unsigned sample_rate;
  83427. unsigned channels;
  83428. unsigned bits_per_sample;
  83429. FLAC__uint64 total_samples;
  83430. FLAC__byte md5sum[16];
  83431. } FLAC__StreamMetadata_StreamInfo;
  83432. extern FLAC_API const unsigned FLAC__STREAM_METADATA_STREAMINFO_MIN_BLOCK_SIZE_LEN; /**< == 16 (bits) */
  83433. extern FLAC_API const unsigned FLAC__STREAM_METADATA_STREAMINFO_MAX_BLOCK_SIZE_LEN; /**< == 16 (bits) */
  83434. extern FLAC_API const unsigned FLAC__STREAM_METADATA_STREAMINFO_MIN_FRAME_SIZE_LEN; /**< == 24 (bits) */
  83435. extern FLAC_API const unsigned FLAC__STREAM_METADATA_STREAMINFO_MAX_FRAME_SIZE_LEN; /**< == 24 (bits) */
  83436. extern FLAC_API const unsigned FLAC__STREAM_METADATA_STREAMINFO_SAMPLE_RATE_LEN; /**< == 20 (bits) */
  83437. extern FLAC_API const unsigned FLAC__STREAM_METADATA_STREAMINFO_CHANNELS_LEN; /**< == 3 (bits) */
  83438. extern FLAC_API const unsigned FLAC__STREAM_METADATA_STREAMINFO_BITS_PER_SAMPLE_LEN; /**< == 5 (bits) */
  83439. extern FLAC_API const unsigned FLAC__STREAM_METADATA_STREAMINFO_TOTAL_SAMPLES_LEN; /**< == 36 (bits) */
  83440. extern FLAC_API const unsigned FLAC__STREAM_METADATA_STREAMINFO_MD5SUM_LEN; /**< == 128 (bits) */
  83441. /** The total stream length of the STREAMINFO block in bytes. */
  83442. #define FLAC__STREAM_METADATA_STREAMINFO_LENGTH (34u)
  83443. /** FLAC PADDING structure. (c.f. <A HREF="../format.html#metadata_block_padding">format specification</A>)
  83444. */
  83445. typedef struct {
  83446. int dummy;
  83447. /**< Conceptually this is an empty struct since we don't store the
  83448. * padding bytes. Empty structs are not allowed by some C compilers,
  83449. * hence the dummy.
  83450. */
  83451. } FLAC__StreamMetadata_Padding;
  83452. /** FLAC APPLICATION structure. (c.f. <A HREF="../format.html#metadata_block_application">format specification</A>)
  83453. */
  83454. typedef struct {
  83455. FLAC__byte id[4];
  83456. FLAC__byte *data;
  83457. } FLAC__StreamMetadata_Application;
  83458. extern FLAC_API const unsigned FLAC__STREAM_METADATA_APPLICATION_ID_LEN; /**< == 32 (bits) */
  83459. /** SeekPoint structure used in SEEKTABLE blocks. (c.f. <A HREF="../format.html#seekpoint">format specification</A>)
  83460. */
  83461. typedef struct {
  83462. FLAC__uint64 sample_number;
  83463. /**< The sample number of the target frame. */
  83464. FLAC__uint64 stream_offset;
  83465. /**< The offset, in bytes, of the target frame with respect to
  83466. * beginning of the first frame. */
  83467. unsigned frame_samples;
  83468. /**< The number of samples in the target frame. */
  83469. } FLAC__StreamMetadata_SeekPoint;
  83470. extern FLAC_API const unsigned FLAC__STREAM_METADATA_SEEKPOINT_SAMPLE_NUMBER_LEN; /**< == 64 (bits) */
  83471. extern FLAC_API const unsigned FLAC__STREAM_METADATA_SEEKPOINT_STREAM_OFFSET_LEN; /**< == 64 (bits) */
  83472. extern FLAC_API const unsigned FLAC__STREAM_METADATA_SEEKPOINT_FRAME_SAMPLES_LEN; /**< == 16 (bits) */
  83473. /** The total stream length of a seek point in bytes. */
  83474. #define FLAC__STREAM_METADATA_SEEKPOINT_LENGTH (18u)
  83475. /** The value used in the \a sample_number field of
  83476. * FLAC__StreamMetadataSeekPoint used to indicate a placeholder
  83477. * point (== 0xffffffffffffffff).
  83478. */
  83479. extern FLAC_API const FLAC__uint64 FLAC__STREAM_METADATA_SEEKPOINT_PLACEHOLDER;
  83480. /** FLAC SEEKTABLE structure. (c.f. <A HREF="../format.html#metadata_block_seektable">format specification</A>)
  83481. *
  83482. * \note From the format specification:
  83483. * - The seek points must be sorted by ascending sample number.
  83484. * - Each seek point's sample number must be the first sample of the
  83485. * target frame.
  83486. * - Each seek point's sample number must be unique within the table.
  83487. * - Existence of a SEEKTABLE block implies a correct setting of
  83488. * total_samples in the stream_info block.
  83489. * - Behavior is undefined when more than one SEEKTABLE block is
  83490. * present in a stream.
  83491. */
  83492. typedef struct {
  83493. unsigned num_points;
  83494. FLAC__StreamMetadata_SeekPoint *points;
  83495. } FLAC__StreamMetadata_SeekTable;
  83496. /** Vorbis comment entry structure used in VORBIS_COMMENT blocks. (c.f. <A HREF="../format.html#metadata_block_vorbis_comment">format specification</A>)
  83497. *
  83498. * For convenience, the APIs maintain a trailing NUL character at the end of
  83499. * \a entry which is not counted toward \a length, i.e.
  83500. * \code strlen(entry) == length \endcode
  83501. */
  83502. typedef struct {
  83503. FLAC__uint32 length;
  83504. FLAC__byte *entry;
  83505. } FLAC__StreamMetadata_VorbisComment_Entry;
  83506. extern FLAC_API const unsigned FLAC__STREAM_METADATA_VORBIS_COMMENT_ENTRY_LENGTH_LEN; /**< == 32 (bits) */
  83507. /** FLAC VORBIS_COMMENT structure. (c.f. <A HREF="../format.html#metadata_block_vorbis_comment">format specification</A>)
  83508. */
  83509. typedef struct {
  83510. FLAC__StreamMetadata_VorbisComment_Entry vendor_string;
  83511. FLAC__uint32 num_comments;
  83512. FLAC__StreamMetadata_VorbisComment_Entry *comments;
  83513. } FLAC__StreamMetadata_VorbisComment;
  83514. extern FLAC_API const unsigned FLAC__STREAM_METADATA_VORBIS_COMMENT_NUM_COMMENTS_LEN; /**< == 32 (bits) */
  83515. /** FLAC CUESHEET track index structure. (See the
  83516. * <A HREF="../format.html#cuesheet_track_index">format specification</A> for
  83517. * the full description of each field.)
  83518. */
  83519. typedef struct {
  83520. FLAC__uint64 offset;
  83521. /**< Offset in samples, relative to the track offset, of the index
  83522. * point.
  83523. */
  83524. FLAC__byte number;
  83525. /**< The index point number. */
  83526. } FLAC__StreamMetadata_CueSheet_Index;
  83527. extern FLAC_API const unsigned FLAC__STREAM_METADATA_CUESHEET_INDEX_OFFSET_LEN; /**< == 64 (bits) */
  83528. extern FLAC_API const unsigned FLAC__STREAM_METADATA_CUESHEET_INDEX_NUMBER_LEN; /**< == 8 (bits) */
  83529. extern FLAC_API const unsigned FLAC__STREAM_METADATA_CUESHEET_INDEX_RESERVED_LEN; /**< == 3*8 (bits) */
  83530. /** FLAC CUESHEET track structure. (See the
  83531. * <A HREF="../format.html#cuesheet_track">format specification</A> for
  83532. * the full description of each field.)
  83533. */
  83534. typedef struct {
  83535. FLAC__uint64 offset;
  83536. /**< Track offset in samples, relative to the beginning of the FLAC audio stream. */
  83537. FLAC__byte number;
  83538. /**< The track number. */
  83539. char isrc[13];
  83540. /**< Track ISRC. This is a 12-digit alphanumeric code plus a trailing \c NUL byte */
  83541. unsigned type:1;
  83542. /**< The track type: 0 for audio, 1 for non-audio. */
  83543. unsigned pre_emphasis:1;
  83544. /**< The pre-emphasis flag: 0 for no pre-emphasis, 1 for pre-emphasis. */
  83545. FLAC__byte num_indices;
  83546. /**< The number of track index points. */
  83547. FLAC__StreamMetadata_CueSheet_Index *indices;
  83548. /**< NULL if num_indices == 0, else pointer to array of index points. */
  83549. } FLAC__StreamMetadata_CueSheet_Track;
  83550. extern FLAC_API const unsigned FLAC__STREAM_METADATA_CUESHEET_TRACK_OFFSET_LEN; /**< == 64 (bits) */
  83551. extern FLAC_API const unsigned FLAC__STREAM_METADATA_CUESHEET_TRACK_NUMBER_LEN; /**< == 8 (bits) */
  83552. extern FLAC_API const unsigned FLAC__STREAM_METADATA_CUESHEET_TRACK_ISRC_LEN; /**< == 12*8 (bits) */
  83553. extern FLAC_API const unsigned FLAC__STREAM_METADATA_CUESHEET_TRACK_TYPE_LEN; /**< == 1 (bit) */
  83554. extern FLAC_API const unsigned FLAC__STREAM_METADATA_CUESHEET_TRACK_PRE_EMPHASIS_LEN; /**< == 1 (bit) */
  83555. extern FLAC_API const unsigned FLAC__STREAM_METADATA_CUESHEET_TRACK_RESERVED_LEN; /**< == 6+13*8 (bits) */
  83556. extern FLAC_API const unsigned FLAC__STREAM_METADATA_CUESHEET_TRACK_NUM_INDICES_LEN; /**< == 8 (bits) */
  83557. /** FLAC CUESHEET structure. (See the
  83558. * <A HREF="../format.html#metadata_block_cuesheet">format specification</A>
  83559. * for the full description of each field.)
  83560. */
  83561. typedef struct {
  83562. char media_catalog_number[129];
  83563. /**< Media catalog number, in ASCII printable characters 0x20-0x7e. In
  83564. * general, the media catalog number may be 0 to 128 bytes long; any
  83565. * unused characters should be right-padded with NUL characters.
  83566. */
  83567. FLAC__uint64 lead_in;
  83568. /**< The number of lead-in samples. */
  83569. FLAC__bool is_cd;
  83570. /**< \c true if CUESHEET corresponds to a Compact Disc, else \c false. */
  83571. unsigned num_tracks;
  83572. /**< The number of tracks. */
  83573. FLAC__StreamMetadata_CueSheet_Track *tracks;
  83574. /**< NULL if num_tracks == 0, else pointer to array of tracks. */
  83575. } FLAC__StreamMetadata_CueSheet;
  83576. extern FLAC_API const unsigned FLAC__STREAM_METADATA_CUESHEET_MEDIA_CATALOG_NUMBER_LEN; /**< == 128*8 (bits) */
  83577. extern FLAC_API const unsigned FLAC__STREAM_METADATA_CUESHEET_LEAD_IN_LEN; /**< == 64 (bits) */
  83578. extern FLAC_API const unsigned FLAC__STREAM_METADATA_CUESHEET_IS_CD_LEN; /**< == 1 (bit) */
  83579. extern FLAC_API const unsigned FLAC__STREAM_METADATA_CUESHEET_RESERVED_LEN; /**< == 7+258*8 (bits) */
  83580. extern FLAC_API const unsigned FLAC__STREAM_METADATA_CUESHEET_NUM_TRACKS_LEN; /**< == 8 (bits) */
  83581. /** An enumeration of the PICTURE types (see FLAC__StreamMetadataPicture and id3 v2.4 APIC tag). */
  83582. typedef enum {
  83583. FLAC__STREAM_METADATA_PICTURE_TYPE_OTHER = 0, /**< Other */
  83584. FLAC__STREAM_METADATA_PICTURE_TYPE_FILE_ICON_STANDARD = 1, /**< 32x32 pixels 'file icon' (PNG only) */
  83585. FLAC__STREAM_METADATA_PICTURE_TYPE_FILE_ICON = 2, /**< Other file icon */
  83586. FLAC__STREAM_METADATA_PICTURE_TYPE_FRONT_COVER = 3, /**< Cover (front) */
  83587. FLAC__STREAM_METADATA_PICTURE_TYPE_BACK_COVER = 4, /**< Cover (back) */
  83588. FLAC__STREAM_METADATA_PICTURE_TYPE_LEAFLET_PAGE = 5, /**< Leaflet page */
  83589. FLAC__STREAM_METADATA_PICTURE_TYPE_MEDIA = 6, /**< Media (e.g. label side of CD) */
  83590. FLAC__STREAM_METADATA_PICTURE_TYPE_LEAD_ARTIST = 7, /**< Lead artist/lead performer/soloist */
  83591. FLAC__STREAM_METADATA_PICTURE_TYPE_ARTIST = 8, /**< Artist/performer */
  83592. FLAC__STREAM_METADATA_PICTURE_TYPE_CONDUCTOR = 9, /**< Conductor */
  83593. FLAC__STREAM_METADATA_PICTURE_TYPE_BAND = 10, /**< Band/Orchestra */
  83594. FLAC__STREAM_METADATA_PICTURE_TYPE_COMPOSER = 11, /**< Composer */
  83595. FLAC__STREAM_METADATA_PICTURE_TYPE_LYRICIST = 12, /**< Lyricist/text writer */
  83596. FLAC__STREAM_METADATA_PICTURE_TYPE_RECORDING_LOCATION = 13, /**< Recording Location */
  83597. FLAC__STREAM_METADATA_PICTURE_TYPE_DURING_RECORDING = 14, /**< During recording */
  83598. FLAC__STREAM_METADATA_PICTURE_TYPE_DURING_PERFORMANCE = 15, /**< During performance */
  83599. FLAC__STREAM_METADATA_PICTURE_TYPE_VIDEO_SCREEN_CAPTURE = 16, /**< Movie/video screen capture */
  83600. FLAC__STREAM_METADATA_PICTURE_TYPE_FISH = 17, /**< A bright coloured fish */
  83601. FLAC__STREAM_METADATA_PICTURE_TYPE_ILLUSTRATION = 18, /**< Illustration */
  83602. FLAC__STREAM_METADATA_PICTURE_TYPE_BAND_LOGOTYPE = 19, /**< Band/artist logotype */
  83603. FLAC__STREAM_METADATA_PICTURE_TYPE_PUBLISHER_LOGOTYPE = 20, /**< Publisher/Studio logotype */
  83604. FLAC__STREAM_METADATA_PICTURE_TYPE_UNDEFINED
  83605. } FLAC__StreamMetadata_Picture_Type;
  83606. /** Maps a FLAC__StreamMetadata_Picture_Type to a C string.
  83607. *
  83608. * Using a FLAC__StreamMetadata_Picture_Type as the index to this array
  83609. * will give the string equivalent. The contents should not be
  83610. * modified.
  83611. */
  83612. extern FLAC_API const char * const FLAC__StreamMetadata_Picture_TypeString[];
  83613. /** FLAC PICTURE structure. (See the
  83614. * <A HREF="../format.html#metadata_block_picture">format specification</A>
  83615. * for the full description of each field.)
  83616. */
  83617. typedef struct {
  83618. FLAC__StreamMetadata_Picture_Type type;
  83619. /**< The kind of picture stored. */
  83620. char *mime_type;
  83621. /**< Picture data's MIME type, in ASCII printable characters
  83622. * 0x20-0x7e, NUL terminated. For best compatibility with players,
  83623. * use picture data of MIME type \c image/jpeg or \c image/png. A
  83624. * MIME type of '-->' is also allowed, in which case the picture
  83625. * data should be a complete URL. In file storage, the MIME type is
  83626. * stored as a 32-bit length followed by the ASCII string with no NUL
  83627. * terminator, but is converted to a plain C string in this structure
  83628. * for convenience.
  83629. */
  83630. FLAC__byte *description;
  83631. /**< Picture's description in UTF-8, NUL terminated. In file storage,
  83632. * the description is stored as a 32-bit length followed by the UTF-8
  83633. * string with no NUL terminator, but is converted to a plain C string
  83634. * in this structure for convenience.
  83635. */
  83636. FLAC__uint32 width;
  83637. /**< Picture's width in pixels. */
  83638. FLAC__uint32 height;
  83639. /**< Picture's height in pixels. */
  83640. FLAC__uint32 depth;
  83641. /**< Picture's color depth in bits-per-pixel. */
  83642. FLAC__uint32 colors;
  83643. /**< For indexed palettes (like GIF), picture's number of colors (the
  83644. * number of palette entries), or \c 0 for non-indexed (i.e. 2^depth).
  83645. */
  83646. FLAC__uint32 data_length;
  83647. /**< Length of binary picture data in bytes. */
  83648. FLAC__byte *data;
  83649. /**< Binary picture data. */
  83650. } FLAC__StreamMetadata_Picture;
  83651. extern FLAC_API const unsigned FLAC__STREAM_METADATA_PICTURE_TYPE_LEN; /**< == 32 (bits) */
  83652. extern FLAC_API const unsigned FLAC__STREAM_METADATA_PICTURE_MIME_TYPE_LENGTH_LEN; /**< == 32 (bits) */
  83653. extern FLAC_API const unsigned FLAC__STREAM_METADATA_PICTURE_DESCRIPTION_LENGTH_LEN; /**< == 32 (bits) */
  83654. extern FLAC_API const unsigned FLAC__STREAM_METADATA_PICTURE_WIDTH_LEN; /**< == 32 (bits) */
  83655. extern FLAC_API const unsigned FLAC__STREAM_METADATA_PICTURE_HEIGHT_LEN; /**< == 32 (bits) */
  83656. extern FLAC_API const unsigned FLAC__STREAM_METADATA_PICTURE_DEPTH_LEN; /**< == 32 (bits) */
  83657. extern FLAC_API const unsigned FLAC__STREAM_METADATA_PICTURE_COLORS_LEN; /**< == 32 (bits) */
  83658. extern FLAC_API const unsigned FLAC__STREAM_METADATA_PICTURE_DATA_LENGTH_LEN; /**< == 32 (bits) */
  83659. /** Structure that is used when a metadata block of unknown type is loaded.
  83660. * The contents are opaque. The structure is used only internally to
  83661. * correctly handle unknown metadata.
  83662. */
  83663. typedef struct {
  83664. FLAC__byte *data;
  83665. } FLAC__StreamMetadata_Unknown;
  83666. /** FLAC metadata block structure. (c.f. <A HREF="../format.html#metadata_block">format specification</A>)
  83667. */
  83668. typedef struct {
  83669. FLAC__MetadataType type;
  83670. /**< The type of the metadata block; used determine which member of the
  83671. * \a data union to dereference. If type >= FLAC__METADATA_TYPE_UNDEFINED
  83672. * then \a data.unknown must be used. */
  83673. FLAC__bool is_last;
  83674. /**< \c true if this metadata block is the last, else \a false */
  83675. unsigned length;
  83676. /**< Length, in bytes, of the block data as it appears in the stream. */
  83677. union {
  83678. FLAC__StreamMetadata_StreamInfo stream_info;
  83679. FLAC__StreamMetadata_Padding padding;
  83680. FLAC__StreamMetadata_Application application;
  83681. FLAC__StreamMetadata_SeekTable seek_table;
  83682. FLAC__StreamMetadata_VorbisComment vorbis_comment;
  83683. FLAC__StreamMetadata_CueSheet cue_sheet;
  83684. FLAC__StreamMetadata_Picture picture;
  83685. FLAC__StreamMetadata_Unknown unknown;
  83686. } data;
  83687. /**< Polymorphic block data; use the \a type value to determine which
  83688. * to use. */
  83689. } FLAC__StreamMetadata;
  83690. extern FLAC_API const unsigned FLAC__STREAM_METADATA_IS_LAST_LEN; /**< == 1 (bit) */
  83691. extern FLAC_API const unsigned FLAC__STREAM_METADATA_TYPE_LEN; /**< == 7 (bits) */
  83692. extern FLAC_API const unsigned FLAC__STREAM_METADATA_LENGTH_LEN; /**< == 24 (bits) */
  83693. /** The total stream length of a metadata block header in bytes. */
  83694. #define FLAC__STREAM_METADATA_HEADER_LENGTH (4u)
  83695. /*****************************************************************************/
  83696. /*****************************************************************************
  83697. *
  83698. * Utility functions
  83699. *
  83700. *****************************************************************************/
  83701. /** Tests that a sample rate is valid for FLAC.
  83702. *
  83703. * \param sample_rate The sample rate to test for compliance.
  83704. * \retval FLAC__bool
  83705. * \c true if the given sample rate conforms to the specification, else
  83706. * \c false.
  83707. */
  83708. FLAC_API FLAC__bool FLAC__format_sample_rate_is_valid(unsigned sample_rate);
  83709. /** Tests that a sample rate is valid for the FLAC subset. The subset rules
  83710. * for valid sample rates are slightly more complex since the rate has to
  83711. * be expressible completely in the frame header.
  83712. *
  83713. * \param sample_rate The sample rate to test for compliance.
  83714. * \retval FLAC__bool
  83715. * \c true if the given sample rate conforms to the specification for the
  83716. * subset, else \c false.
  83717. */
  83718. FLAC_API FLAC__bool FLAC__format_sample_rate_is_subset(unsigned sample_rate);
  83719. /** Check a Vorbis comment entry name to see if it conforms to the Vorbis
  83720. * comment specification.
  83721. *
  83722. * Vorbis comment names must be composed only of characters from
  83723. * [0x20-0x3C,0x3E-0x7D].
  83724. *
  83725. * \param name A NUL-terminated string to be checked.
  83726. * \assert
  83727. * \code name != NULL \endcode
  83728. * \retval FLAC__bool
  83729. * \c false if entry name is illegal, else \c true.
  83730. */
  83731. FLAC_API FLAC__bool FLAC__format_vorbiscomment_entry_name_is_legal(const char *name);
  83732. /** Check a Vorbis comment entry value to see if it conforms to the Vorbis
  83733. * comment specification.
  83734. *
  83735. * Vorbis comment values must be valid UTF-8 sequences.
  83736. *
  83737. * \param value A string to be checked.
  83738. * \param length A the length of \a value in bytes. May be
  83739. * \c (unsigned)(-1) to indicate that \a value is a plain
  83740. * UTF-8 NUL-terminated string.
  83741. * \assert
  83742. * \code value != NULL \endcode
  83743. * \retval FLAC__bool
  83744. * \c false if entry name is illegal, else \c true.
  83745. */
  83746. FLAC_API FLAC__bool FLAC__format_vorbiscomment_entry_value_is_legal(const FLAC__byte *value, unsigned length);
  83747. /** Check a Vorbis comment entry to see if it conforms to the Vorbis
  83748. * comment specification.
  83749. *
  83750. * Vorbis comment entries must be of the form 'name=value', and 'name' and
  83751. * 'value' must be legal according to
  83752. * FLAC__format_vorbiscomment_entry_name_is_legal() and
  83753. * FLAC__format_vorbiscomment_entry_value_is_legal() respectively.
  83754. *
  83755. * \param entry An entry to be checked.
  83756. * \param length The length of \a entry in bytes.
  83757. * \assert
  83758. * \code value != NULL \endcode
  83759. * \retval FLAC__bool
  83760. * \c false if entry name is illegal, else \c true.
  83761. */
  83762. FLAC_API FLAC__bool FLAC__format_vorbiscomment_entry_is_legal(const FLAC__byte *entry, unsigned length);
  83763. /** Check a seek table to see if it conforms to the FLAC specification.
  83764. * See the format specification for limits on the contents of the
  83765. * seek table.
  83766. *
  83767. * \param seek_table A pointer to a seek table to be checked.
  83768. * \assert
  83769. * \code seek_table != NULL \endcode
  83770. * \retval FLAC__bool
  83771. * \c false if seek table is illegal, else \c true.
  83772. */
  83773. FLAC_API FLAC__bool FLAC__format_seektable_is_legal(const FLAC__StreamMetadata_SeekTable *seek_table);
  83774. /** Sort a seek table's seek points according to the format specification.
  83775. * This includes a "unique-ification" step to remove duplicates, i.e.
  83776. * seek points with identical \a sample_number values. Duplicate seek
  83777. * points are converted into placeholder points and sorted to the end of
  83778. * the table.
  83779. *
  83780. * \param seek_table A pointer to a seek table to be sorted.
  83781. * \assert
  83782. * \code seek_table != NULL \endcode
  83783. * \retval unsigned
  83784. * The number of duplicate seek points converted into placeholders.
  83785. */
  83786. FLAC_API unsigned FLAC__format_seektable_sort(FLAC__StreamMetadata_SeekTable *seek_table);
  83787. /** Check a cue sheet to see if it conforms to the FLAC specification.
  83788. * See the format specification for limits on the contents of the
  83789. * cue sheet.
  83790. *
  83791. * \param cue_sheet A pointer to an existing cue sheet to be checked.
  83792. * \param check_cd_da_subset If \c true, check CUESHEET against more
  83793. * stringent requirements for a CD-DA (audio) disc.
  83794. * \param violation Address of a pointer to a string. If there is a
  83795. * violation, a pointer to a string explanation of the
  83796. * violation will be returned here. \a violation may be
  83797. * \c NULL if you don't need the returned string. Do not
  83798. * free the returned string; it will always point to static
  83799. * data.
  83800. * \assert
  83801. * \code cue_sheet != NULL \endcode
  83802. * \retval FLAC__bool
  83803. * \c false if cue sheet is illegal, else \c true.
  83804. */
  83805. FLAC_API FLAC__bool FLAC__format_cuesheet_is_legal(const FLAC__StreamMetadata_CueSheet *cue_sheet, FLAC__bool check_cd_da_subset, const char **violation);
  83806. /** Check picture data to see if it conforms to the FLAC specification.
  83807. * See the format specification for limits on the contents of the
  83808. * PICTURE block.
  83809. *
  83810. * \param picture A pointer to existing picture data to be checked.
  83811. * \param violation Address of a pointer to a string. If there is a
  83812. * violation, a pointer to a string explanation of the
  83813. * violation will be returned here. \a violation may be
  83814. * \c NULL if you don't need the returned string. Do not
  83815. * free the returned string; it will always point to static
  83816. * data.
  83817. * \assert
  83818. * \code picture != NULL \endcode
  83819. * \retval FLAC__bool
  83820. * \c false if picture data is illegal, else \c true.
  83821. */
  83822. FLAC_API FLAC__bool FLAC__format_picture_is_legal(const FLAC__StreamMetadata_Picture *picture, const char **violation);
  83823. /* \} */
  83824. #ifdef __cplusplus
  83825. }
  83826. #endif
  83827. #endif
  83828. /*** End of inlined file: format.h ***/
  83829. /*** Start of inlined file: metadata.h ***/
  83830. #ifndef FLAC__METADATA_H
  83831. #define FLAC__METADATA_H
  83832. #include <sys/types.h> /* for off_t */
  83833. /* --------------------------------------------------------------------
  83834. (For an example of how all these routines are used, see the source
  83835. code for the unit tests in src/test_libFLAC/metadata_*.c, or
  83836. metaflac in src/metaflac/)
  83837. ------------------------------------------------------------------*/
  83838. /** \file include/FLAC/metadata.h
  83839. *
  83840. * \brief
  83841. * This module provides functions for creating and manipulating FLAC
  83842. * metadata blocks in memory, and three progressively more powerful
  83843. * interfaces for traversing and editing metadata in FLAC files.
  83844. *
  83845. * See the detailed documentation for each interface in the
  83846. * \link flac_metadata metadata \endlink module.
  83847. */
  83848. /** \defgroup flac_metadata FLAC/metadata.h: metadata interfaces
  83849. * \ingroup flac
  83850. *
  83851. * \brief
  83852. * This module provides functions for creating and manipulating FLAC
  83853. * metadata blocks in memory, and three progressively more powerful
  83854. * interfaces for traversing and editing metadata in native FLAC files.
  83855. * Note that currently only the Chain interface (level 2) supports Ogg
  83856. * FLAC files, and it is read-only i.e. no writing back changed
  83857. * metadata to file.
  83858. *
  83859. * There are three metadata interfaces of increasing complexity:
  83860. *
  83861. * Level 0:
  83862. * Read-only access to the STREAMINFO, VORBIS_COMMENT, CUESHEET, and
  83863. * PICTURE blocks.
  83864. *
  83865. * Level 1:
  83866. * Read-write access to all metadata blocks. This level is write-
  83867. * efficient in most cases (more on this below), and uses less memory
  83868. * than level 2.
  83869. *
  83870. * Level 2:
  83871. * Read-write access to all metadata blocks. This level is write-
  83872. * efficient in all cases, but uses more memory since all metadata for
  83873. * the whole file is read into memory and manipulated before writing
  83874. * out again.
  83875. *
  83876. * What do we mean by efficient? Since FLAC metadata appears at the
  83877. * beginning of the file, when writing metadata back to a FLAC file
  83878. * it is possible to grow or shrink the metadata such that the entire
  83879. * file must be rewritten. However, if the size remains the same during
  83880. * changes or PADDING blocks are utilized, only the metadata needs to be
  83881. * overwritten, which is much faster.
  83882. *
  83883. * Efficient means the whole file is rewritten at most one time, and only
  83884. * when necessary. Level 1 is not efficient only in the case that you
  83885. * cause more than one metadata block to grow or shrink beyond what can
  83886. * be accomodated by padding. In this case you should probably use level
  83887. * 2, which allows you to edit all the metadata for a file in memory and
  83888. * write it out all at once.
  83889. *
  83890. * All levels know how to skip over and not disturb an ID3v2 tag at the
  83891. * front of the file.
  83892. *
  83893. * All levels access files via their filenames. In addition, level 2
  83894. * has additional alternative read and write functions that take an I/O
  83895. * handle and callbacks, for situations where access by filename is not
  83896. * possible.
  83897. *
  83898. * In addition to the three interfaces, this module defines functions for
  83899. * creating and manipulating various metadata objects in memory. As we see
  83900. * from the Format module, FLAC metadata blocks in memory are very primitive
  83901. * structures for storing information in an efficient way. Reading
  83902. * information from the structures is easy but creating or modifying them
  83903. * directly is more complex. The metadata object routines here facilitate
  83904. * this by taking care of the consistency and memory management drudgery.
  83905. *
  83906. * Unless you will be using the level 1 or 2 interfaces to modify existing
  83907. * metadata however, you will not probably not need these.
  83908. *
  83909. * From a dependency standpoint, none of the encoders or decoders require
  83910. * the metadata module. This is so that embedded users can strip out the
  83911. * metadata module from libFLAC to reduce the size and complexity.
  83912. */
  83913. #ifdef __cplusplus
  83914. extern "C" {
  83915. #endif
  83916. /** \defgroup flac_metadata_level0 FLAC/metadata.h: metadata level 0 interface
  83917. * \ingroup flac_metadata
  83918. *
  83919. * \brief
  83920. * The level 0 interface consists of individual routines to read the
  83921. * STREAMINFO, VORBIS_COMMENT, CUESHEET, and PICTURE blocks, requiring
  83922. * only a filename.
  83923. *
  83924. * They try to skip any ID3v2 tag at the head of the file.
  83925. *
  83926. * \{
  83927. */
  83928. /** Read the STREAMINFO metadata block of the given FLAC file. This function
  83929. * will try to skip any ID3v2 tag at the head of the file.
  83930. *
  83931. * \param filename The path to the FLAC file to read.
  83932. * \param streaminfo A pointer to space for the STREAMINFO block. Since
  83933. * FLAC__StreamMetadata is a simple structure with no
  83934. * memory allocation involved, you pass the address of
  83935. * an existing structure. It need not be initialized.
  83936. * \assert
  83937. * \code filename != NULL \endcode
  83938. * \code streaminfo != NULL \endcode
  83939. * \retval FLAC__bool
  83940. * \c true if a valid STREAMINFO block was read from \a filename. Returns
  83941. * \c false if there was a memory allocation error, a file decoder error,
  83942. * or the file contained no STREAMINFO block. (A memory allocation error
  83943. * is possible because this function must set up a file decoder.)
  83944. */
  83945. FLAC_API FLAC__bool FLAC__metadata_get_streaminfo(const char *filename, FLAC__StreamMetadata *streaminfo);
  83946. /** Read the VORBIS_COMMENT metadata block of the given FLAC file. This
  83947. * function will try to skip any ID3v2 tag at the head of the file.
  83948. *
  83949. * \param filename The path to the FLAC file to read.
  83950. * \param tags The address where the returned pointer will be
  83951. * stored. The \a tags object must be deleted by
  83952. * the caller using FLAC__metadata_object_delete().
  83953. * \assert
  83954. * \code filename != NULL \endcode
  83955. * \code tags != NULL \endcode
  83956. * \retval FLAC__bool
  83957. * \c true if a valid VORBIS_COMMENT block was read from \a filename,
  83958. * and \a *tags will be set to the address of the metadata structure.
  83959. * Returns \c false if there was a memory allocation error, a file
  83960. * decoder error, or the file contained no VORBIS_COMMENT block, and
  83961. * \a *tags will be set to \c NULL.
  83962. */
  83963. FLAC_API FLAC__bool FLAC__metadata_get_tags(const char *filename, FLAC__StreamMetadata **tags);
  83964. /** Read the CUESHEET metadata block of the given FLAC file. This
  83965. * function will try to skip any ID3v2 tag at the head of the file.
  83966. *
  83967. * \param filename The path to the FLAC file to read.
  83968. * \param cuesheet The address where the returned pointer will be
  83969. * stored. The \a cuesheet object must be deleted by
  83970. * the caller using FLAC__metadata_object_delete().
  83971. * \assert
  83972. * \code filename != NULL \endcode
  83973. * \code cuesheet != NULL \endcode
  83974. * \retval FLAC__bool
  83975. * \c true if a valid CUESHEET block was read from \a filename,
  83976. * and \a *cuesheet will be set to the address of the metadata
  83977. * structure. Returns \c false if there was a memory allocation
  83978. * error, a file decoder error, or the file contained no CUESHEET
  83979. * block, and \a *cuesheet will be set to \c NULL.
  83980. */
  83981. FLAC_API FLAC__bool FLAC__metadata_get_cuesheet(const char *filename, FLAC__StreamMetadata **cuesheet);
  83982. /** Read a PICTURE metadata block of the given FLAC file. This
  83983. * function will try to skip any ID3v2 tag at the head of the file.
  83984. * Since there can be more than one PICTURE block in a file, this
  83985. * function takes a number of parameters that act as constraints to
  83986. * the search. The PICTURE block with the largest area matching all
  83987. * the constraints will be returned, or \a *picture will be set to
  83988. * \c NULL if there was no such block.
  83989. *
  83990. * \param filename The path to the FLAC file to read.
  83991. * \param picture The address where the returned pointer will be
  83992. * stored. The \a picture object must be deleted by
  83993. * the caller using FLAC__metadata_object_delete().
  83994. * \param type The desired picture type. Use \c -1 to mean
  83995. * "any type".
  83996. * \param mime_type The desired MIME type, e.g. "image/jpeg". The
  83997. * string will be matched exactly. Use \c NULL to
  83998. * mean "any MIME type".
  83999. * \param description The desired description. The string will be
  84000. * matched exactly. Use \c NULL to mean "any
  84001. * description".
  84002. * \param max_width The maximum width in pixels desired. Use
  84003. * \c (unsigned)(-1) to mean "any width".
  84004. * \param max_height The maximum height in pixels desired. Use
  84005. * \c (unsigned)(-1) to mean "any height".
  84006. * \param max_depth The maximum color depth in bits-per-pixel desired.
  84007. * Use \c (unsigned)(-1) to mean "any depth".
  84008. * \param max_colors The maximum number of colors desired. Use
  84009. * \c (unsigned)(-1) to mean "any number of colors".
  84010. * \assert
  84011. * \code filename != NULL \endcode
  84012. * \code picture != NULL \endcode
  84013. * \retval FLAC__bool
  84014. * \c true if a valid PICTURE block was read from \a filename,
  84015. * and \a *picture will be set to the address of the metadata
  84016. * structure. Returns \c false if there was a memory allocation
  84017. * error, a file decoder error, or the file contained no PICTURE
  84018. * block, and \a *picture will be set to \c NULL.
  84019. */
  84020. 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);
  84021. /* \} */
  84022. /** \defgroup flac_metadata_level1 FLAC/metadata.h: metadata level 1 interface
  84023. * \ingroup flac_metadata
  84024. *
  84025. * \brief
  84026. * The level 1 interface provides read-write access to FLAC file metadata and
  84027. * operates directly on the FLAC file.
  84028. *
  84029. * The general usage of this interface is:
  84030. *
  84031. * - Create an iterator using FLAC__metadata_simple_iterator_new()
  84032. * - Attach it to a file using FLAC__metadata_simple_iterator_init() and check
  84033. * the exit code. Call FLAC__metadata_simple_iterator_is_writable() to
  84034. * see if the file is writable, or only read access is allowed.
  84035. * - Use FLAC__metadata_simple_iterator_next() and
  84036. * FLAC__metadata_simple_iterator_prev() to traverse the blocks.
  84037. * This is does not read the actual blocks themselves.
  84038. * FLAC__metadata_simple_iterator_next() is relatively fast.
  84039. * FLAC__metadata_simple_iterator_prev() is slower since it needs to search
  84040. * forward from the front of the file.
  84041. * - Use FLAC__metadata_simple_iterator_get_block_type() or
  84042. * FLAC__metadata_simple_iterator_get_block() to access the actual data at
  84043. * the current iterator position. The returned object is yours to modify
  84044. * and free.
  84045. * - Use FLAC__metadata_simple_iterator_set_block() to write a modified block
  84046. * back. You must have write permission to the original file. Make sure to
  84047. * read the whole comment to FLAC__metadata_simple_iterator_set_block()
  84048. * below.
  84049. * - Use FLAC__metadata_simple_iterator_insert_block_after() to add new blocks.
  84050. * Use the object creation functions from
  84051. * \link flac_metadata_object here \endlink to generate new objects.
  84052. * - Use FLAC__metadata_simple_iterator_delete_block() to remove the block
  84053. * currently referred to by the iterator, or replace it with padding.
  84054. * - Destroy the iterator with FLAC__metadata_simple_iterator_delete() when
  84055. * finished.
  84056. *
  84057. * \note
  84058. * The FLAC file remains open the whole time between
  84059. * FLAC__metadata_simple_iterator_init() and
  84060. * FLAC__metadata_simple_iterator_delete(), so make sure you are not altering
  84061. * the file during this time.
  84062. *
  84063. * \note
  84064. * Do not modify the \a is_last, \a length, or \a type fields of returned
  84065. * FLAC__StreamMetadata objects. These are managed automatically.
  84066. *
  84067. * \note
  84068. * If any of the modification functions
  84069. * (FLAC__metadata_simple_iterator_set_block(),
  84070. * FLAC__metadata_simple_iterator_delete_block(),
  84071. * FLAC__metadata_simple_iterator_insert_block_after(), etc.) return \c false,
  84072. * you should delete the iterator as it may no longer be valid.
  84073. *
  84074. * \{
  84075. */
  84076. struct FLAC__Metadata_SimpleIterator;
  84077. /** The opaque structure definition for the level 1 iterator type.
  84078. * See the
  84079. * \link flac_metadata_level1 metadata level 1 module \endlink
  84080. * for a detailed description.
  84081. */
  84082. typedef struct FLAC__Metadata_SimpleIterator FLAC__Metadata_SimpleIterator;
  84083. /** Status type for FLAC__Metadata_SimpleIterator.
  84084. *
  84085. * The iterator's current status can be obtained by calling FLAC__metadata_simple_iterator_status().
  84086. */
  84087. typedef enum {
  84088. FLAC__METADATA_SIMPLE_ITERATOR_STATUS_OK = 0,
  84089. /**< The iterator is in the normal OK state */
  84090. FLAC__METADATA_SIMPLE_ITERATOR_STATUS_ILLEGAL_INPUT,
  84091. /**< The data passed into a function violated the function's usage criteria */
  84092. FLAC__METADATA_SIMPLE_ITERATOR_STATUS_ERROR_OPENING_FILE,
  84093. /**< The iterator could not open the target file */
  84094. FLAC__METADATA_SIMPLE_ITERATOR_STATUS_NOT_A_FLAC_FILE,
  84095. /**< The iterator could not find the FLAC signature at the start of the file */
  84096. FLAC__METADATA_SIMPLE_ITERATOR_STATUS_NOT_WRITABLE,
  84097. /**< The iterator tried to write to a file that was not writable */
  84098. FLAC__METADATA_SIMPLE_ITERATOR_STATUS_BAD_METADATA,
  84099. /**< The iterator encountered input that does not conform to the FLAC metadata specification */
  84100. FLAC__METADATA_SIMPLE_ITERATOR_STATUS_READ_ERROR,
  84101. /**< The iterator encountered an error while reading the FLAC file */
  84102. FLAC__METADATA_SIMPLE_ITERATOR_STATUS_SEEK_ERROR,
  84103. /**< The iterator encountered an error while seeking in the FLAC file */
  84104. FLAC__METADATA_SIMPLE_ITERATOR_STATUS_WRITE_ERROR,
  84105. /**< The iterator encountered an error while writing the FLAC file */
  84106. FLAC__METADATA_SIMPLE_ITERATOR_STATUS_RENAME_ERROR,
  84107. /**< The iterator encountered an error renaming the FLAC file */
  84108. FLAC__METADATA_SIMPLE_ITERATOR_STATUS_UNLINK_ERROR,
  84109. /**< The iterator encountered an error removing the temporary file */
  84110. FLAC__METADATA_SIMPLE_ITERATOR_STATUS_MEMORY_ALLOCATION_ERROR,
  84111. /**< Memory allocation failed */
  84112. FLAC__METADATA_SIMPLE_ITERATOR_STATUS_INTERNAL_ERROR
  84113. /**< The caller violated an assertion or an unexpected error occurred */
  84114. } FLAC__Metadata_SimpleIteratorStatus;
  84115. /** Maps a FLAC__Metadata_SimpleIteratorStatus to a C string.
  84116. *
  84117. * Using a FLAC__Metadata_SimpleIteratorStatus as the index to this array
  84118. * will give the string equivalent. The contents should not be modified.
  84119. */
  84120. extern FLAC_API const char * const FLAC__Metadata_SimpleIteratorStatusString[];
  84121. /** Create a new iterator instance.
  84122. *
  84123. * \retval FLAC__Metadata_SimpleIterator*
  84124. * \c NULL if there was an error allocating memory, else the new instance.
  84125. */
  84126. FLAC_API FLAC__Metadata_SimpleIterator *FLAC__metadata_simple_iterator_new(void);
  84127. /** Free an iterator instance. Deletes the object pointed to by \a iterator.
  84128. *
  84129. * \param iterator A pointer to an existing iterator.
  84130. * \assert
  84131. * \code iterator != NULL \endcode
  84132. */
  84133. FLAC_API void FLAC__metadata_simple_iterator_delete(FLAC__Metadata_SimpleIterator *iterator);
  84134. /** Get the current status of the iterator. Call this after a function
  84135. * returns \c false to get the reason for the error. Also resets the status
  84136. * to FLAC__METADATA_SIMPLE_ITERATOR_STATUS_OK.
  84137. *
  84138. * \param iterator A pointer to an existing iterator.
  84139. * \assert
  84140. * \code iterator != NULL \endcode
  84141. * \retval FLAC__Metadata_SimpleIteratorStatus
  84142. * The current status of the iterator.
  84143. */
  84144. FLAC_API FLAC__Metadata_SimpleIteratorStatus FLAC__metadata_simple_iterator_status(FLAC__Metadata_SimpleIterator *iterator);
  84145. /** Initialize the iterator to point to the first metadata block in the
  84146. * given FLAC file.
  84147. *
  84148. * \param iterator A pointer to an existing iterator.
  84149. * \param filename The path to the FLAC file.
  84150. * \param read_only If \c true, the FLAC file will be opened
  84151. * in read-only mode; if \c false, the FLAC
  84152. * file will be opened for edit even if no
  84153. * edits are performed.
  84154. * \param preserve_file_stats If \c true, the owner and modification
  84155. * time will be preserved even if the FLAC
  84156. * file is written to.
  84157. * \assert
  84158. * \code iterator != NULL \endcode
  84159. * \code filename != NULL \endcode
  84160. * \retval FLAC__bool
  84161. * \c false if a memory allocation error occurs, the file can't be
  84162. * opened, or another error occurs, else \c true.
  84163. */
  84164. 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);
  84165. /** Returns \c true if the FLAC file is writable. If \c false, calls to
  84166. * FLAC__metadata_simple_iterator_set_block() and
  84167. * FLAC__metadata_simple_iterator_insert_block_after() will fail.
  84168. *
  84169. * \param iterator A pointer to an existing iterator.
  84170. * \assert
  84171. * \code iterator != NULL \endcode
  84172. * \retval FLAC__bool
  84173. * See above.
  84174. */
  84175. FLAC_API FLAC__bool FLAC__metadata_simple_iterator_is_writable(const FLAC__Metadata_SimpleIterator *iterator);
  84176. /** Moves the iterator forward one metadata block, returning \c false if
  84177. * already at the end.
  84178. *
  84179. * \param iterator A pointer to an existing initialized iterator.
  84180. * \assert
  84181. * \code iterator != NULL \endcode
  84182. * \a iterator has been successfully initialized with
  84183. * FLAC__metadata_simple_iterator_init()
  84184. * \retval FLAC__bool
  84185. * \c false if already at the last metadata block of the chain, else
  84186. * \c true.
  84187. */
  84188. FLAC_API FLAC__bool FLAC__metadata_simple_iterator_next(FLAC__Metadata_SimpleIterator *iterator);
  84189. /** Moves the iterator backward one metadata block, returning \c false if
  84190. * already at the beginning.
  84191. *
  84192. * \param iterator A pointer to an existing initialized iterator.
  84193. * \assert
  84194. * \code iterator != NULL \endcode
  84195. * \a iterator has been successfully initialized with
  84196. * FLAC__metadata_simple_iterator_init()
  84197. * \retval FLAC__bool
  84198. * \c false if already at the first metadata block of the chain, else
  84199. * \c true.
  84200. */
  84201. FLAC_API FLAC__bool FLAC__metadata_simple_iterator_prev(FLAC__Metadata_SimpleIterator *iterator);
  84202. /** Returns a flag telling if the current metadata block is the last.
  84203. *
  84204. * \param iterator A pointer to an existing initialized iterator.
  84205. * \assert
  84206. * \code iterator != NULL \endcode
  84207. * \a iterator has been successfully initialized with
  84208. * FLAC__metadata_simple_iterator_init()
  84209. * \retval FLAC__bool
  84210. * \c true if the current metadata block is the last in the file,
  84211. * else \c false.
  84212. */
  84213. FLAC_API FLAC__bool FLAC__metadata_simple_iterator_is_last(const FLAC__Metadata_SimpleIterator *iterator);
  84214. /** Get the offset of the metadata block at the current position. This
  84215. * avoids reading the actual block data which can save time for large
  84216. * blocks.
  84217. *
  84218. * \param iterator A pointer to an existing initialized iterator.
  84219. * \assert
  84220. * \code iterator != NULL \endcode
  84221. * \a iterator has been successfully initialized with
  84222. * FLAC__metadata_simple_iterator_init()
  84223. * \retval off_t
  84224. * The offset of the metadata block at the current iterator position.
  84225. * This is the byte offset relative to the beginning of the file of
  84226. * the current metadata block's header.
  84227. */
  84228. FLAC_API off_t FLAC__metadata_simple_iterator_get_block_offset(const FLAC__Metadata_SimpleIterator *iterator);
  84229. /** Get the type of the metadata block at the current position. This
  84230. * avoids reading the actual block data which can save time for large
  84231. * blocks.
  84232. *
  84233. * \param iterator A pointer to an existing initialized iterator.
  84234. * \assert
  84235. * \code iterator != NULL \endcode
  84236. * \a iterator has been successfully initialized with
  84237. * FLAC__metadata_simple_iterator_init()
  84238. * \retval FLAC__MetadataType
  84239. * The type of the metadata block at the current iterator position.
  84240. */
  84241. FLAC_API FLAC__MetadataType FLAC__metadata_simple_iterator_get_block_type(const FLAC__Metadata_SimpleIterator *iterator);
  84242. /** Get the length of the metadata block at the current position. This
  84243. * avoids reading the actual block data which can save time for large
  84244. * blocks.
  84245. *
  84246. * \param iterator A pointer to an existing initialized iterator.
  84247. * \assert
  84248. * \code iterator != NULL \endcode
  84249. * \a iterator has been successfully initialized with
  84250. * FLAC__metadata_simple_iterator_init()
  84251. * \retval unsigned
  84252. * The length of the metadata block at the current iterator position.
  84253. * The is same length as that in the
  84254. * <a href="http://flac.sourceforge.net/format.html#metadata_block_header">metadata block header</a>,
  84255. * i.e. the length of the metadata body that follows the header.
  84256. */
  84257. FLAC_API unsigned FLAC__metadata_simple_iterator_get_block_length(const FLAC__Metadata_SimpleIterator *iterator);
  84258. /** Get the application ID of the \c APPLICATION block at the current
  84259. * position. This avoids reading the actual block data which can save
  84260. * time for large blocks.
  84261. *
  84262. * \param iterator A pointer to an existing initialized iterator.
  84263. * \param id A pointer to a buffer of at least \c 4 bytes where
  84264. * the ID will be stored.
  84265. * \assert
  84266. * \code iterator != NULL \endcode
  84267. * \code id != NULL \endcode
  84268. * \a iterator has been successfully initialized with
  84269. * FLAC__metadata_simple_iterator_init()
  84270. * \retval FLAC__bool
  84271. * \c true if the ID was successfully read, else \c false, in which
  84272. * case you should check FLAC__metadata_simple_iterator_status() to
  84273. * find out why. If the status is
  84274. * \c FLAC__METADATA_SIMPLE_ITERATOR_STATUS_ILLEGAL_INPUT, then the
  84275. * current metadata block is not an \c APPLICATION block. Otherwise
  84276. * if the status is
  84277. * \c FLAC__METADATA_SIMPLE_ITERATOR_STATUS_READ_ERROR or
  84278. * \c FLAC__METADATA_SIMPLE_ITERATOR_STATUS_SEEK_ERROR, an I/O error
  84279. * occurred and the iterator can no longer be used.
  84280. */
  84281. FLAC_API FLAC__bool FLAC__metadata_simple_iterator_get_application_id(FLAC__Metadata_SimpleIterator *iterator, FLAC__byte *id);
  84282. /** Get the metadata block at the current position. You can modify the
  84283. * block but must use FLAC__metadata_simple_iterator_set_block() to
  84284. * write it back to the FLAC file.
  84285. *
  84286. * You must call FLAC__metadata_object_delete() on the returned object
  84287. * when you are finished with it.
  84288. *
  84289. * \param iterator A pointer to an existing initialized iterator.
  84290. * \assert
  84291. * \code iterator != NULL \endcode
  84292. * \a iterator has been successfully initialized with
  84293. * FLAC__metadata_simple_iterator_init()
  84294. * \retval FLAC__StreamMetadata*
  84295. * The current metadata block, or \c NULL if there was a memory
  84296. * allocation error.
  84297. */
  84298. FLAC_API FLAC__StreamMetadata *FLAC__metadata_simple_iterator_get_block(FLAC__Metadata_SimpleIterator *iterator);
  84299. /** Write a block back to the FLAC file. This function tries to be
  84300. * as efficient as possible; how the block is actually written is
  84301. * shown by the following:
  84302. *
  84303. * Existing block is a STREAMINFO block and the new block is a
  84304. * STREAMINFO block: the new block is written in place. Make sure
  84305. * you know what you're doing when changing the values of a
  84306. * STREAMINFO block.
  84307. *
  84308. * Existing block is a STREAMINFO block and the new block is a
  84309. * not a STREAMINFO block: this is an error since the first block
  84310. * must be a STREAMINFO block. Returns \c false without altering the
  84311. * file.
  84312. *
  84313. * Existing block is not a STREAMINFO block and the new block is a
  84314. * STREAMINFO block: this is an error since there may be only one
  84315. * STREAMINFO block. Returns \c false without altering the file.
  84316. *
  84317. * Existing block and new block are the same length: the existing
  84318. * block will be replaced by the new block, written in place.
  84319. *
  84320. * Existing block is longer than new block: if use_padding is \c true,
  84321. * the existing block will be overwritten in place with the new
  84322. * block followed by a PADDING block, if possible, to make the total
  84323. * size the same as the existing block. Remember that a padding
  84324. * block requires at least four bytes so if the difference in size
  84325. * between the new block and existing block is less than that, the
  84326. * entire file will have to be rewritten, using the new block's
  84327. * exact size. If use_padding is \c false, the entire file will be
  84328. * rewritten, replacing the existing block by the new block.
  84329. *
  84330. * Existing block is shorter than new block: if use_padding is \c true,
  84331. * the function will try and expand the new block into the following
  84332. * PADDING block, if it exists and doing so won't shrink the PADDING
  84333. * block to less than 4 bytes. If there is no following PADDING
  84334. * block, or it will shrink to less than 4 bytes, or use_padding is
  84335. * \c false, the entire file is rewritten, replacing the existing block
  84336. * with the new block. Note that in this case any following PADDING
  84337. * block is preserved as is.
  84338. *
  84339. * After writing the block, the iterator will remain in the same
  84340. * place, i.e. pointing to the new block.
  84341. *
  84342. * \param iterator A pointer to an existing initialized iterator.
  84343. * \param block The block to set.
  84344. * \param use_padding See above.
  84345. * \assert
  84346. * \code iterator != NULL \endcode
  84347. * \a iterator has been successfully initialized with
  84348. * FLAC__metadata_simple_iterator_init()
  84349. * \code block != NULL \endcode
  84350. * \retval FLAC__bool
  84351. * \c true if successful, else \c false.
  84352. */
  84353. FLAC_API FLAC__bool FLAC__metadata_simple_iterator_set_block(FLAC__Metadata_SimpleIterator *iterator, FLAC__StreamMetadata *block, FLAC__bool use_padding);
  84354. /** This is similar to FLAC__metadata_simple_iterator_set_block()
  84355. * except that instead of writing over an existing block, it appends
  84356. * a block after the existing block. \a use_padding is again used to
  84357. * tell the function to try an expand into following padding in an
  84358. * attempt to avoid rewriting the entire file.
  84359. *
  84360. * This function will fail and return \c false if given a STREAMINFO
  84361. * block.
  84362. *
  84363. * After writing the block, the iterator will be pointing to the
  84364. * new block.
  84365. *
  84366. * \param iterator A pointer to an existing initialized iterator.
  84367. * \param block The block to set.
  84368. * \param use_padding See above.
  84369. * \assert
  84370. * \code iterator != NULL \endcode
  84371. * \a iterator has been successfully initialized with
  84372. * FLAC__metadata_simple_iterator_init()
  84373. * \code block != NULL \endcode
  84374. * \retval FLAC__bool
  84375. * \c true if successful, else \c false.
  84376. */
  84377. FLAC_API FLAC__bool FLAC__metadata_simple_iterator_insert_block_after(FLAC__Metadata_SimpleIterator *iterator, FLAC__StreamMetadata *block, FLAC__bool use_padding);
  84378. /** Deletes the block at the current position. This will cause the
  84379. * entire FLAC file to be rewritten, unless \a use_padding is \c true,
  84380. * in which case the block will be replaced by an equal-sized PADDING
  84381. * block. The iterator will be left pointing to the block before the
  84382. * one just deleted.
  84383. *
  84384. * You may not delete the STREAMINFO block.
  84385. *
  84386. * \param iterator A pointer to an existing initialized iterator.
  84387. * \param use_padding See above.
  84388. * \assert
  84389. * \code iterator != NULL \endcode
  84390. * \a iterator has been successfully initialized with
  84391. * FLAC__metadata_simple_iterator_init()
  84392. * \retval FLAC__bool
  84393. * \c true if successful, else \c false.
  84394. */
  84395. FLAC_API FLAC__bool FLAC__metadata_simple_iterator_delete_block(FLAC__Metadata_SimpleIterator *iterator, FLAC__bool use_padding);
  84396. /* \} */
  84397. /** \defgroup flac_metadata_level2 FLAC/metadata.h: metadata level 2 interface
  84398. * \ingroup flac_metadata
  84399. *
  84400. * \brief
  84401. * The level 2 interface provides read-write access to FLAC file metadata;
  84402. * all metadata is read into memory, operated on in memory, and then written
  84403. * to file, which is more efficient than level 1 when editing multiple blocks.
  84404. *
  84405. * Currently Ogg FLAC is supported for read only, via
  84406. * FLAC__metadata_chain_read_ogg() but a subsequent
  84407. * FLAC__metadata_chain_write() will fail.
  84408. *
  84409. * The general usage of this interface is:
  84410. *
  84411. * - Create a new chain using FLAC__metadata_chain_new(). A chain is a
  84412. * linked list of FLAC metadata blocks.
  84413. * - Read all metadata into the the chain from a FLAC file using
  84414. * FLAC__metadata_chain_read() or FLAC__metadata_chain_read_ogg() and
  84415. * check the status.
  84416. * - Optionally, consolidate the padding using
  84417. * FLAC__metadata_chain_merge_padding() or
  84418. * FLAC__metadata_chain_sort_padding().
  84419. * - Create a new iterator using FLAC__metadata_iterator_new()
  84420. * - Initialize the iterator to point to the first element in the chain
  84421. * using FLAC__metadata_iterator_init()
  84422. * - Traverse the chain using FLAC__metadata_iterator_next and
  84423. * FLAC__metadata_iterator_prev().
  84424. * - Get a block for reading or modification using
  84425. * FLAC__metadata_iterator_get_block(). The pointer to the object
  84426. * inside the chain is returned, so the block is yours to modify.
  84427. * Changes will be reflected in the FLAC file when you write the
  84428. * chain. You can also add and delete blocks (see functions below).
  84429. * - When done, write out the chain using FLAC__metadata_chain_write().
  84430. * Make sure to read the whole comment to the function below.
  84431. * - Delete the chain using FLAC__metadata_chain_delete().
  84432. *
  84433. * \note
  84434. * Even though the FLAC file is not open while the chain is being
  84435. * manipulated, you must not alter the file externally during
  84436. * this time. The chain assumes the FLAC file will not change
  84437. * between the time of FLAC__metadata_chain_read()/FLAC__metadata_chain_read_ogg()
  84438. * and FLAC__metadata_chain_write().
  84439. *
  84440. * \note
  84441. * Do not modify the is_last, length, or type fields of returned
  84442. * FLAC__StreamMetadata objects. These are managed automatically.
  84443. *
  84444. * \note
  84445. * The metadata objects returned by FLAC__metadata_iterator_get_block()
  84446. * are owned by the chain; do not FLAC__metadata_object_delete() them.
  84447. * In the same way, blocks passed to FLAC__metadata_iterator_set_block()
  84448. * become owned by the chain and they will be deleted when the chain is
  84449. * deleted.
  84450. *
  84451. * \{
  84452. */
  84453. struct FLAC__Metadata_Chain;
  84454. /** The opaque structure definition for the level 2 chain type.
  84455. */
  84456. typedef struct FLAC__Metadata_Chain FLAC__Metadata_Chain;
  84457. struct FLAC__Metadata_Iterator;
  84458. /** The opaque structure definition for the level 2 iterator type.
  84459. */
  84460. typedef struct FLAC__Metadata_Iterator FLAC__Metadata_Iterator;
  84461. typedef enum {
  84462. FLAC__METADATA_CHAIN_STATUS_OK = 0,
  84463. /**< The chain is in the normal OK state */
  84464. FLAC__METADATA_CHAIN_STATUS_ILLEGAL_INPUT,
  84465. /**< The data passed into a function violated the function's usage criteria */
  84466. FLAC__METADATA_CHAIN_STATUS_ERROR_OPENING_FILE,
  84467. /**< The chain could not open the target file */
  84468. FLAC__METADATA_CHAIN_STATUS_NOT_A_FLAC_FILE,
  84469. /**< The chain could not find the FLAC signature at the start of the file */
  84470. FLAC__METADATA_CHAIN_STATUS_NOT_WRITABLE,
  84471. /**< The chain tried to write to a file that was not writable */
  84472. FLAC__METADATA_CHAIN_STATUS_BAD_METADATA,
  84473. /**< The chain encountered input that does not conform to the FLAC metadata specification */
  84474. FLAC__METADATA_CHAIN_STATUS_READ_ERROR,
  84475. /**< The chain encountered an error while reading the FLAC file */
  84476. FLAC__METADATA_CHAIN_STATUS_SEEK_ERROR,
  84477. /**< The chain encountered an error while seeking in the FLAC file */
  84478. FLAC__METADATA_CHAIN_STATUS_WRITE_ERROR,
  84479. /**< The chain encountered an error while writing the FLAC file */
  84480. FLAC__METADATA_CHAIN_STATUS_RENAME_ERROR,
  84481. /**< The chain encountered an error renaming the FLAC file */
  84482. FLAC__METADATA_CHAIN_STATUS_UNLINK_ERROR,
  84483. /**< The chain encountered an error removing the temporary file */
  84484. FLAC__METADATA_CHAIN_STATUS_MEMORY_ALLOCATION_ERROR,
  84485. /**< Memory allocation failed */
  84486. FLAC__METADATA_CHAIN_STATUS_INTERNAL_ERROR,
  84487. /**< The caller violated an assertion or an unexpected error occurred */
  84488. FLAC__METADATA_CHAIN_STATUS_INVALID_CALLBACKS,
  84489. /**< One or more of the required callbacks was NULL */
  84490. FLAC__METADATA_CHAIN_STATUS_READ_WRITE_MISMATCH,
  84491. /**< FLAC__metadata_chain_write() was called on a chain read by
  84492. * FLAC__metadata_chain_read_with_callbacks()/FLAC__metadata_chain_read_ogg_with_callbacks(),
  84493. * or
  84494. * FLAC__metadata_chain_write_with_callbacks()/FLAC__metadata_chain_write_with_callbacks_and_tempfile()
  84495. * was called on a chain read by
  84496. * FLAC__metadata_chain_read()/FLAC__metadata_chain_read_ogg().
  84497. * Matching read/write methods must always be used. */
  84498. FLAC__METADATA_CHAIN_STATUS_WRONG_WRITE_CALL
  84499. /**< FLAC__metadata_chain_write_with_callbacks() was called when the
  84500. * chain write requires a tempfile; use
  84501. * FLAC__metadata_chain_write_with_callbacks_and_tempfile() instead.
  84502. * Or, FLAC__metadata_chain_write_with_callbacks_and_tempfile() was
  84503. * called when the chain write does not require a tempfile; use
  84504. * FLAC__metadata_chain_write_with_callbacks() instead.
  84505. * Always check FLAC__metadata_chain_check_if_tempfile_needed()
  84506. * before writing via callbacks. */
  84507. } FLAC__Metadata_ChainStatus;
  84508. /** Maps a FLAC__Metadata_ChainStatus to a C string.
  84509. *
  84510. * Using a FLAC__Metadata_ChainStatus as the index to this array
  84511. * will give the string equivalent. The contents should not be modified.
  84512. */
  84513. extern FLAC_API const char * const FLAC__Metadata_ChainStatusString[];
  84514. /*********** FLAC__Metadata_Chain ***********/
  84515. /** Create a new chain instance.
  84516. *
  84517. * \retval FLAC__Metadata_Chain*
  84518. * \c NULL if there was an error allocating memory, else the new instance.
  84519. */
  84520. FLAC_API FLAC__Metadata_Chain *FLAC__metadata_chain_new(void);
  84521. /** Free a chain instance. Deletes the object pointed to by \a chain.
  84522. *
  84523. * \param chain A pointer to an existing chain.
  84524. * \assert
  84525. * \code chain != NULL \endcode
  84526. */
  84527. FLAC_API void FLAC__metadata_chain_delete(FLAC__Metadata_Chain *chain);
  84528. /** Get the current status of the chain. Call this after a function
  84529. * returns \c false to get the reason for the error. Also resets the
  84530. * status to FLAC__METADATA_CHAIN_STATUS_OK.
  84531. *
  84532. * \param chain A pointer to an existing chain.
  84533. * \assert
  84534. * \code chain != NULL \endcode
  84535. * \retval FLAC__Metadata_ChainStatus
  84536. * The current status of the chain.
  84537. */
  84538. FLAC_API FLAC__Metadata_ChainStatus FLAC__metadata_chain_status(FLAC__Metadata_Chain *chain);
  84539. /** Read all metadata from a FLAC file into the chain.
  84540. *
  84541. * \param chain A pointer to an existing chain.
  84542. * \param filename The path to the FLAC file to read.
  84543. * \assert
  84544. * \code chain != NULL \endcode
  84545. * \code filename != NULL \endcode
  84546. * \retval FLAC__bool
  84547. * \c true if a valid list of metadata blocks was read from
  84548. * \a filename, else \c false. On failure, check the status with
  84549. * FLAC__metadata_chain_status().
  84550. */
  84551. FLAC_API FLAC__bool FLAC__metadata_chain_read(FLAC__Metadata_Chain *chain, const char *filename);
  84552. /** Read all metadata from an Ogg FLAC file into the chain.
  84553. *
  84554. * \note Ogg FLAC metadata data writing is not supported yet and
  84555. * FLAC__metadata_chain_write() will fail.
  84556. *
  84557. * \param chain A pointer to an existing chain.
  84558. * \param filename The path to the Ogg FLAC file to read.
  84559. * \assert
  84560. * \code chain != NULL \endcode
  84561. * \code filename != NULL \endcode
  84562. * \retval FLAC__bool
  84563. * \c true if a valid list of metadata blocks was read from
  84564. * \a filename, else \c false. On failure, check the status with
  84565. * FLAC__metadata_chain_status().
  84566. */
  84567. FLAC_API FLAC__bool FLAC__metadata_chain_read_ogg(FLAC__Metadata_Chain *chain, const char *filename);
  84568. /** Read all metadata from a FLAC stream into the chain via I/O callbacks.
  84569. *
  84570. * The \a handle need only be open for reading, but must be seekable.
  84571. * The equivalent minimum stdio fopen() file mode is \c "r" (or \c "rb"
  84572. * for Windows).
  84573. *
  84574. * \param chain A pointer to an existing chain.
  84575. * \param handle The I/O handle of the FLAC stream to read. The
  84576. * handle will NOT be closed after the metadata is read;
  84577. * that is the duty of the caller.
  84578. * \param callbacks
  84579. * A set of callbacks to use for I/O. The mandatory
  84580. * callbacks are \a read, \a seek, and \a tell.
  84581. * \assert
  84582. * \code chain != NULL \endcode
  84583. * \retval FLAC__bool
  84584. * \c true if a valid list of metadata blocks was read from
  84585. * \a handle, else \c false. On failure, check the status with
  84586. * FLAC__metadata_chain_status().
  84587. */
  84588. FLAC_API FLAC__bool FLAC__metadata_chain_read_with_callbacks(FLAC__Metadata_Chain *chain, FLAC__IOHandle handle, FLAC__IOCallbacks callbacks);
  84589. /** Read all metadata from an Ogg FLAC stream into the chain via I/O callbacks.
  84590. *
  84591. * The \a handle need only be open for reading, but must be seekable.
  84592. * The equivalent minimum stdio fopen() file mode is \c "r" (or \c "rb"
  84593. * for Windows).
  84594. *
  84595. * \note Ogg FLAC metadata data writing is not supported yet and
  84596. * FLAC__metadata_chain_write() will fail.
  84597. *
  84598. * \param chain A pointer to an existing chain.
  84599. * \param handle The I/O handle of the Ogg FLAC stream to read. The
  84600. * handle will NOT be closed after the metadata is read;
  84601. * that is the duty of the caller.
  84602. * \param callbacks
  84603. * A set of callbacks to use for I/O. The mandatory
  84604. * callbacks are \a read, \a seek, and \a tell.
  84605. * \assert
  84606. * \code chain != NULL \endcode
  84607. * \retval FLAC__bool
  84608. * \c true if a valid list of metadata blocks was read from
  84609. * \a handle, else \c false. On failure, check the status with
  84610. * FLAC__metadata_chain_status().
  84611. */
  84612. FLAC_API FLAC__bool FLAC__metadata_chain_read_ogg_with_callbacks(FLAC__Metadata_Chain *chain, FLAC__IOHandle handle, FLAC__IOCallbacks callbacks);
  84613. /** Checks if writing the given chain would require the use of a
  84614. * temporary file, or if it could be written in place.
  84615. *
  84616. * Under certain conditions, padding can be utilized so that writing
  84617. * edited metadata back to the FLAC file does not require rewriting the
  84618. * entire file. If rewriting is required, then a temporary workfile is
  84619. * required. When writing metadata using callbacks, you must check
  84620. * this function to know whether to call
  84621. * FLAC__metadata_chain_write_with_callbacks() or
  84622. * FLAC__metadata_chain_write_with_callbacks_and_tempfile(). When
  84623. * writing with FLAC__metadata_chain_write(), the temporary file is
  84624. * handled internally.
  84625. *
  84626. * \param chain A pointer to an existing chain.
  84627. * \param use_padding
  84628. * Whether or not padding will be allowed to be used
  84629. * during the write. The value of \a use_padding given
  84630. * here must match the value later passed to
  84631. * FLAC__metadata_chain_write_with_callbacks() or
  84632. * FLAC__metadata_chain_write_with_callbacks_with_tempfile().
  84633. * \assert
  84634. * \code chain != NULL \endcode
  84635. * \retval FLAC__bool
  84636. * \c true if writing the current chain would require a tempfile, or
  84637. * \c false if metadata can be written in place.
  84638. */
  84639. FLAC_API FLAC__bool FLAC__metadata_chain_check_if_tempfile_needed(FLAC__Metadata_Chain *chain, FLAC__bool use_padding);
  84640. /** Write all metadata out to the FLAC file. This function tries to be as
  84641. * efficient as possible; how the metadata is actually written is shown by
  84642. * the following:
  84643. *
  84644. * If the current chain is the same size as the existing metadata, the new
  84645. * data is written in place.
  84646. *
  84647. * If the current chain is longer than the existing metadata, and
  84648. * \a use_padding is \c true, and the last block is a PADDING block of
  84649. * sufficient length, the function will truncate the final padding block
  84650. * so that the overall size of the metadata is the same as the existing
  84651. * metadata, and then just rewrite the metadata. Otherwise, if not all of
  84652. * the above conditions are met, the entire FLAC file must be rewritten.
  84653. * If you want to use padding this way it is a good idea to call
  84654. * FLAC__metadata_chain_sort_padding() first so that you have the maximum
  84655. * amount of padding to work with, unless you need to preserve ordering
  84656. * of the PADDING blocks for some reason.
  84657. *
  84658. * If the current chain is shorter than the existing metadata, and
  84659. * \a use_padding is \c true, and the final block is a PADDING block, the padding
  84660. * is extended to make the overall size the same as the existing data. If
  84661. * \a use_padding is \c true and the last block is not a PADDING block, a new
  84662. * PADDING block is added to the end of the new data to make it the same
  84663. * size as the existing data (if possible, see the note to
  84664. * FLAC__metadata_simple_iterator_set_block() about the four byte limit)
  84665. * and the new data is written in place. If none of the above apply or
  84666. * \a use_padding is \c false, the entire FLAC file is rewritten.
  84667. *
  84668. * If \a preserve_file_stats is \c true, the owner and modification time will
  84669. * be preserved even if the FLAC file is written.
  84670. *
  84671. * For this write function to be used, the chain must have been read with
  84672. * FLAC__metadata_chain_read()/FLAC__metadata_chain_read_ogg(), not
  84673. * FLAC__metadata_chain_read_with_callbacks()/FLAC__metadata_chain_read_ogg_with_callbacks().
  84674. *
  84675. * \param chain A pointer to an existing chain.
  84676. * \param use_padding See above.
  84677. * \param preserve_file_stats See above.
  84678. * \assert
  84679. * \code chain != NULL \endcode
  84680. * \retval FLAC__bool
  84681. * \c true if the write succeeded, else \c false. On failure,
  84682. * check the status with FLAC__metadata_chain_status().
  84683. */
  84684. FLAC_API FLAC__bool FLAC__metadata_chain_write(FLAC__Metadata_Chain *chain, FLAC__bool use_padding, FLAC__bool preserve_file_stats);
  84685. /** Write all metadata out to a FLAC stream via callbacks.
  84686. *
  84687. * (See FLAC__metadata_chain_write() for the details on how padding is
  84688. * used to write metadata in place if possible.)
  84689. *
  84690. * The \a handle must be open for updating and be seekable. The
  84691. * equivalent minimum stdio fopen() file mode is \c "r+" (or \c "r+b"
  84692. * for Windows).
  84693. *
  84694. * For this write function to be used, the chain must have been read with
  84695. * FLAC__metadata_chain_read_with_callbacks()/FLAC__metadata_chain_read_ogg_with_callbacks(),
  84696. * not FLAC__metadata_chain_read()/FLAC__metadata_chain_read_ogg().
  84697. * Also, FLAC__metadata_chain_check_if_tempfile_needed() must have returned
  84698. * \c false.
  84699. *
  84700. * \param chain A pointer to an existing chain.
  84701. * \param use_padding See FLAC__metadata_chain_write()
  84702. * \param handle The I/O handle of the FLAC stream to write. The
  84703. * handle will NOT be closed after the metadata is
  84704. * written; that is the duty of the caller.
  84705. * \param callbacks A set of callbacks to use for I/O. The mandatory
  84706. * callbacks are \a write and \a seek.
  84707. * \assert
  84708. * \code chain != NULL \endcode
  84709. * \retval FLAC__bool
  84710. * \c true if the write succeeded, else \c false. On failure,
  84711. * check the status with FLAC__metadata_chain_status().
  84712. */
  84713. FLAC_API FLAC__bool FLAC__metadata_chain_write_with_callbacks(FLAC__Metadata_Chain *chain, FLAC__bool use_padding, FLAC__IOHandle handle, FLAC__IOCallbacks callbacks);
  84714. /** Write all metadata out to a FLAC stream via callbacks.
  84715. *
  84716. * (See FLAC__metadata_chain_write() for the details on how padding is
  84717. * used to write metadata in place if possible.)
  84718. *
  84719. * This version of the write-with-callbacks function must be used when
  84720. * FLAC__metadata_chain_check_if_tempfile_needed() returns true. In
  84721. * this function, you must supply an I/O handle corresponding to the
  84722. * FLAC file to edit, and a temporary handle to which the new FLAC
  84723. * file will be written. It is the caller's job to move this temporary
  84724. * FLAC file on top of the original FLAC file to complete the metadata
  84725. * edit.
  84726. *
  84727. * The \a handle must be open for reading and be seekable. The
  84728. * equivalent minimum stdio fopen() file mode is \c "r" (or \c "rb"
  84729. * for Windows).
  84730. *
  84731. * The \a temp_handle must be open for writing. The
  84732. * equivalent minimum stdio fopen() file mode is \c "w" (or \c "wb"
  84733. * for Windows). It should be an empty stream, or at least positioned
  84734. * at the start-of-file (in which case it is the caller's duty to
  84735. * truncate it on return).
  84736. *
  84737. * For this write function to be used, the chain must have been read with
  84738. * FLAC__metadata_chain_read_with_callbacks()/FLAC__metadata_chain_read_ogg_with_callbacks(),
  84739. * not FLAC__metadata_chain_read()/FLAC__metadata_chain_read_ogg().
  84740. * Also, FLAC__metadata_chain_check_if_tempfile_needed() must have returned
  84741. * \c true.
  84742. *
  84743. * \param chain A pointer to an existing chain.
  84744. * \param use_padding See FLAC__metadata_chain_write()
  84745. * \param handle The I/O handle of the original FLAC stream to read.
  84746. * The handle will NOT be closed after the metadata is
  84747. * written; that is the duty of the caller.
  84748. * \param callbacks A set of callbacks to use for I/O on \a handle.
  84749. * The mandatory callbacks are \a read, \a seek, and
  84750. * \a eof.
  84751. * \param temp_handle The I/O handle of the FLAC stream to write. The
  84752. * handle will NOT be closed after the metadata is
  84753. * written; that is the duty of the caller.
  84754. * \param temp_callbacks
  84755. * A set of callbacks to use for I/O on temp_handle.
  84756. * The only mandatory callback is \a write.
  84757. * \assert
  84758. * \code chain != NULL \endcode
  84759. * \retval FLAC__bool
  84760. * \c true if the write succeeded, else \c false. On failure,
  84761. * check the status with FLAC__metadata_chain_status().
  84762. */
  84763. 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);
  84764. /** Merge adjacent PADDING blocks into a single block.
  84765. *
  84766. * \note This function does not write to the FLAC file, it only
  84767. * modifies the chain.
  84768. *
  84769. * \warning Any iterator on the current chain will become invalid after this
  84770. * call. You should delete the iterator and get a new one.
  84771. *
  84772. * \param chain A pointer to an existing chain.
  84773. * \assert
  84774. * \code chain != NULL \endcode
  84775. */
  84776. FLAC_API void FLAC__metadata_chain_merge_padding(FLAC__Metadata_Chain *chain);
  84777. /** This function will move all PADDING blocks to the end on the metadata,
  84778. * then merge them into a single block.
  84779. *
  84780. * \note This function does not write to the FLAC file, it only
  84781. * modifies the chain.
  84782. *
  84783. * \warning Any iterator on the current chain will become invalid after this
  84784. * call. You should delete the iterator and get a new one.
  84785. *
  84786. * \param chain A pointer to an existing chain.
  84787. * \assert
  84788. * \code chain != NULL \endcode
  84789. */
  84790. FLAC_API void FLAC__metadata_chain_sort_padding(FLAC__Metadata_Chain *chain);
  84791. /*********** FLAC__Metadata_Iterator ***********/
  84792. /** Create a new iterator instance.
  84793. *
  84794. * \retval FLAC__Metadata_Iterator*
  84795. * \c NULL if there was an error allocating memory, else the new instance.
  84796. */
  84797. FLAC_API FLAC__Metadata_Iterator *FLAC__metadata_iterator_new(void);
  84798. /** Free an iterator instance. Deletes the object pointed to by \a iterator.
  84799. *
  84800. * \param iterator A pointer to an existing iterator.
  84801. * \assert
  84802. * \code iterator != NULL \endcode
  84803. */
  84804. FLAC_API void FLAC__metadata_iterator_delete(FLAC__Metadata_Iterator *iterator);
  84805. /** Initialize the iterator to point to the first metadata block in the
  84806. * given chain.
  84807. *
  84808. * \param iterator A pointer to an existing iterator.
  84809. * \param chain A pointer to an existing and initialized (read) chain.
  84810. * \assert
  84811. * \code iterator != NULL \endcode
  84812. * \code chain != NULL \endcode
  84813. */
  84814. FLAC_API void FLAC__metadata_iterator_init(FLAC__Metadata_Iterator *iterator, FLAC__Metadata_Chain *chain);
  84815. /** Moves the iterator forward one metadata block, returning \c false if
  84816. * already at the end.
  84817. *
  84818. * \param iterator A pointer to an existing initialized iterator.
  84819. * \assert
  84820. * \code iterator != NULL \endcode
  84821. * \a iterator has been successfully initialized with
  84822. * FLAC__metadata_iterator_init()
  84823. * \retval FLAC__bool
  84824. * \c false if already at the last metadata block of the chain, else
  84825. * \c true.
  84826. */
  84827. FLAC_API FLAC__bool FLAC__metadata_iterator_next(FLAC__Metadata_Iterator *iterator);
  84828. /** Moves the iterator backward one metadata block, returning \c false if
  84829. * already at the beginning.
  84830. *
  84831. * \param iterator A pointer to an existing initialized iterator.
  84832. * \assert
  84833. * \code iterator != NULL \endcode
  84834. * \a iterator has been successfully initialized with
  84835. * FLAC__metadata_iterator_init()
  84836. * \retval FLAC__bool
  84837. * \c false if already at the first metadata block of the chain, else
  84838. * \c true.
  84839. */
  84840. FLAC_API FLAC__bool FLAC__metadata_iterator_prev(FLAC__Metadata_Iterator *iterator);
  84841. /** Get the type of the metadata block at the current position.
  84842. *
  84843. * \param iterator A pointer to an existing initialized iterator.
  84844. * \assert
  84845. * \code iterator != NULL \endcode
  84846. * \a iterator has been successfully initialized with
  84847. * FLAC__metadata_iterator_init()
  84848. * \retval FLAC__MetadataType
  84849. * The type of the metadata block at the current iterator position.
  84850. */
  84851. FLAC_API FLAC__MetadataType FLAC__metadata_iterator_get_block_type(const FLAC__Metadata_Iterator *iterator);
  84852. /** Get the metadata block at the current position. You can modify
  84853. * the block in place but must write the chain before the changes
  84854. * are reflected to the FLAC file. You do not need to call
  84855. * FLAC__metadata_iterator_set_block() to reflect the changes;
  84856. * the pointer returned by FLAC__metadata_iterator_get_block()
  84857. * points directly into the chain.
  84858. *
  84859. * \warning
  84860. * Do not call FLAC__metadata_object_delete() on the returned object;
  84861. * to delete a block use FLAC__metadata_iterator_delete_block().
  84862. *
  84863. * \param iterator A pointer to an existing initialized iterator.
  84864. * \assert
  84865. * \code iterator != NULL \endcode
  84866. * \a iterator has been successfully initialized with
  84867. * FLAC__metadata_iterator_init()
  84868. * \retval FLAC__StreamMetadata*
  84869. * The current metadata block.
  84870. */
  84871. FLAC_API FLAC__StreamMetadata *FLAC__metadata_iterator_get_block(FLAC__Metadata_Iterator *iterator);
  84872. /** Set the metadata block at the current position, replacing the existing
  84873. * block. The new block passed in becomes owned by the chain and it will be
  84874. * deleted when the chain is deleted.
  84875. *
  84876. * \param iterator A pointer to an existing initialized iterator.
  84877. * \param block A pointer to a metadata block.
  84878. * \assert
  84879. * \code iterator != NULL \endcode
  84880. * \a iterator has been successfully initialized with
  84881. * FLAC__metadata_iterator_init()
  84882. * \code block != NULL \endcode
  84883. * \retval FLAC__bool
  84884. * \c false if the conditions in the above description are not met, or
  84885. * a memory allocation error occurs, otherwise \c true.
  84886. */
  84887. FLAC_API FLAC__bool FLAC__metadata_iterator_set_block(FLAC__Metadata_Iterator *iterator, FLAC__StreamMetadata *block);
  84888. /** Removes the current block from the chain. If \a replace_with_padding is
  84889. * \c true, the block will instead be replaced with a padding block of equal
  84890. * size. You can not delete the STREAMINFO block. The iterator will be
  84891. * left pointing to the block before the one just "deleted", even if
  84892. * \a replace_with_padding is \c true.
  84893. *
  84894. * \param iterator A pointer to an existing initialized iterator.
  84895. * \param replace_with_padding See above.
  84896. * \assert
  84897. * \code iterator != NULL \endcode
  84898. * \a iterator has been successfully initialized with
  84899. * FLAC__metadata_iterator_init()
  84900. * \retval FLAC__bool
  84901. * \c false if the conditions in the above description are not met,
  84902. * otherwise \c true.
  84903. */
  84904. FLAC_API FLAC__bool FLAC__metadata_iterator_delete_block(FLAC__Metadata_Iterator *iterator, FLAC__bool replace_with_padding);
  84905. /** Insert a new block before the current block. You cannot insert a block
  84906. * before the first STREAMINFO block. You cannot insert a STREAMINFO block
  84907. * as there can be only one, the one that already exists at the head when you
  84908. * read in a chain. The chain takes ownership of the new block and it will be
  84909. * deleted when the chain is deleted. The iterator will be left pointing to
  84910. * the new block.
  84911. *
  84912. * \param iterator A pointer to an existing initialized iterator.
  84913. * \param block A pointer to a metadata block to insert.
  84914. * \assert
  84915. * \code iterator != NULL \endcode
  84916. * \a iterator has been successfully initialized with
  84917. * FLAC__metadata_iterator_init()
  84918. * \retval FLAC__bool
  84919. * \c false if the conditions in the above description are not met, or
  84920. * a memory allocation error occurs, otherwise \c true.
  84921. */
  84922. FLAC_API FLAC__bool FLAC__metadata_iterator_insert_block_before(FLAC__Metadata_Iterator *iterator, FLAC__StreamMetadata *block);
  84923. /** Insert a new block after the current block. You cannot insert a STREAMINFO
  84924. * block as there can be only one, the one that already exists at the head when
  84925. * you read in a chain. The chain takes ownership of the new block and it will
  84926. * be deleted when the chain is deleted. The iterator will be left pointing to
  84927. * the new block.
  84928. *
  84929. * \param iterator A pointer to an existing initialized iterator.
  84930. * \param block A pointer to a metadata block to insert.
  84931. * \assert
  84932. * \code iterator != NULL \endcode
  84933. * \a iterator has been successfully initialized with
  84934. * FLAC__metadata_iterator_init()
  84935. * \retval FLAC__bool
  84936. * \c false if the conditions in the above description are not met, or
  84937. * a memory allocation error occurs, otherwise \c true.
  84938. */
  84939. FLAC_API FLAC__bool FLAC__metadata_iterator_insert_block_after(FLAC__Metadata_Iterator *iterator, FLAC__StreamMetadata *block);
  84940. /* \} */
  84941. /** \defgroup flac_metadata_object FLAC/metadata.h: metadata object methods
  84942. * \ingroup flac_metadata
  84943. *
  84944. * \brief
  84945. * This module contains methods for manipulating FLAC metadata objects.
  84946. *
  84947. * Since many are variable length we have to be careful about the memory
  84948. * management. We decree that all pointers to data in the object are
  84949. * owned by the object and memory-managed by the object.
  84950. *
  84951. * Use the FLAC__metadata_object_new() and FLAC__metadata_object_delete()
  84952. * functions to create all instances. When using the
  84953. * FLAC__metadata_object_set_*() functions to set pointers to data, set
  84954. * \a copy to \c true to have the function make it's own copy of the data, or
  84955. * to \c false to give the object ownership of your data. In the latter case
  84956. * your pointer must be freeable by free() and will be free()d when the object
  84957. * is FLAC__metadata_object_delete()d. It is legal to pass a null pointer as
  84958. * the data pointer to a FLAC__metadata_object_set_*() function as long as
  84959. * the length argument is 0 and the \a copy argument is \c false.
  84960. *
  84961. * The FLAC__metadata_object_new() and FLAC__metadata_object_clone() function
  84962. * will return \c NULL in the case of a memory allocation error, otherwise a new
  84963. * object. The FLAC__metadata_object_set_*() functions return \c false in the
  84964. * case of a memory allocation error.
  84965. *
  84966. * We don't have the convenience of C++ here, so note that the library relies
  84967. * on you to keep the types straight. In other words, if you pass, for
  84968. * example, a FLAC__StreamMetadata* that represents a STREAMINFO block to
  84969. * FLAC__metadata_object_application_set_data(), you will get an assertion
  84970. * failure.
  84971. *
  84972. * For convenience the FLAC__metadata_object_vorbiscomment_*() functions
  84973. * maintain a trailing NUL on each Vorbis comment entry. This is not counted
  84974. * toward the length or stored in the stream, but it can make working with plain
  84975. * comments (those that don't contain embedded-NULs in the value) easier.
  84976. * Entries passed into these functions have trailing NULs added if missing, and
  84977. * returned entries are guaranteed to have a trailing NUL.
  84978. *
  84979. * The FLAC__metadata_object_vorbiscomment_*() functions that take a Vorbis
  84980. * comment entry/name/value will first validate that it complies with the Vorbis
  84981. * comment specification and return false if it does not.
  84982. *
  84983. * There is no need to recalculate the length field on metadata blocks you
  84984. * have modified. They will be calculated automatically before they are
  84985. * written back to a file.
  84986. *
  84987. * \{
  84988. */
  84989. /** Create a new metadata object instance of the given type.
  84990. *
  84991. * The object will be "empty"; i.e. values and data pointers will be \c 0,
  84992. * with the exception of FLAC__METADATA_TYPE_VORBIS_COMMENT, which will have
  84993. * the vendor string set (but zero comments).
  84994. *
  84995. * Do not pass in a value greater than or equal to
  84996. * \a FLAC__METADATA_TYPE_UNDEFINED unless you really know what you're
  84997. * doing.
  84998. *
  84999. * \param type Type of object to create
  85000. * \retval FLAC__StreamMetadata*
  85001. * \c NULL if there was an error allocating memory or the type code is
  85002. * greater than FLAC__MAX_METADATA_TYPE_CODE, else the new instance.
  85003. */
  85004. FLAC_API FLAC__StreamMetadata *FLAC__metadata_object_new(FLAC__MetadataType type);
  85005. /** Create a copy of an existing metadata object.
  85006. *
  85007. * The copy is a "deep" copy, i.e. dynamically allocated data within the
  85008. * object is also copied. The caller takes ownership of the new block and
  85009. * is responsible for freeing it with FLAC__metadata_object_delete().
  85010. *
  85011. * \param object Pointer to object to copy.
  85012. * \assert
  85013. * \code object != NULL \endcode
  85014. * \retval FLAC__StreamMetadata*
  85015. * \c NULL if there was an error allocating memory, else the new instance.
  85016. */
  85017. FLAC_API FLAC__StreamMetadata *FLAC__metadata_object_clone(const FLAC__StreamMetadata *object);
  85018. /** Free a metadata object. Deletes the object pointed to by \a object.
  85019. *
  85020. * The delete is a "deep" delete, i.e. dynamically allocated data within the
  85021. * object is also deleted.
  85022. *
  85023. * \param object A pointer to an existing object.
  85024. * \assert
  85025. * \code object != NULL \endcode
  85026. */
  85027. FLAC_API void FLAC__metadata_object_delete(FLAC__StreamMetadata *object);
  85028. /** Compares two metadata objects.
  85029. *
  85030. * The compare is "deep", i.e. dynamically allocated data within the
  85031. * object is also compared.
  85032. *
  85033. * \param block1 A pointer to an existing object.
  85034. * \param block2 A pointer to an existing object.
  85035. * \assert
  85036. * \code block1 != NULL \endcode
  85037. * \code block2 != NULL \endcode
  85038. * \retval FLAC__bool
  85039. * \c true if objects are identical, else \c false.
  85040. */
  85041. FLAC_API FLAC__bool FLAC__metadata_object_is_equal(const FLAC__StreamMetadata *block1, const FLAC__StreamMetadata *block2);
  85042. /** Sets the application data of an APPLICATION block.
  85043. *
  85044. * If \a copy is \c true, a copy of the data is stored; otherwise, the object
  85045. * takes ownership of the pointer. The existing data will be freed if this
  85046. * function is successful, otherwise the original data will remain if \a copy
  85047. * is \c true and malloc() fails.
  85048. *
  85049. * \note It is safe to pass a const pointer to \a data if \a copy is \c true.
  85050. *
  85051. * \param object A pointer to an existing APPLICATION object.
  85052. * \param data A pointer to the data to set.
  85053. * \param length The length of \a data in bytes.
  85054. * \param copy See above.
  85055. * \assert
  85056. * \code object != NULL \endcode
  85057. * \code object->type == FLAC__METADATA_TYPE_APPLICATION \endcode
  85058. * \code (data != NULL && length > 0) ||
  85059. * (data == NULL && length == 0 && copy == false) \endcode
  85060. * \retval FLAC__bool
  85061. * \c false if \a copy is \c true and malloc() fails, else \c true.
  85062. */
  85063. FLAC_API FLAC__bool FLAC__metadata_object_application_set_data(FLAC__StreamMetadata *object, FLAC__byte *data, unsigned length, FLAC__bool copy);
  85064. /** Resize the seekpoint array.
  85065. *
  85066. * If the size shrinks, elements will truncated; if it grows, new placeholder
  85067. * points will be added to the end.
  85068. *
  85069. * \param object A pointer to an existing SEEKTABLE object.
  85070. * \param new_num_points The desired length of the array; may be \c 0.
  85071. * \assert
  85072. * \code object != NULL \endcode
  85073. * \code object->type == FLAC__METADATA_TYPE_SEEKTABLE \endcode
  85074. * \code (object->data.seek_table.points == NULL && object->data.seek_table.num_points == 0) ||
  85075. * (object->data.seek_table.points != NULL && object->data.seek_table.num_points > 0) \endcode
  85076. * \retval FLAC__bool
  85077. * \c false if memory allocation error, else \c true.
  85078. */
  85079. FLAC_API FLAC__bool FLAC__metadata_object_seektable_resize_points(FLAC__StreamMetadata *object, unsigned new_num_points);
  85080. /** Set a seekpoint in a seektable.
  85081. *
  85082. * \param object A pointer to an existing SEEKTABLE object.
  85083. * \param point_num Index into seekpoint array to set.
  85084. * \param point The point to set.
  85085. * \assert
  85086. * \code object != NULL \endcode
  85087. * \code object->type == FLAC__METADATA_TYPE_SEEKTABLE \endcode
  85088. * \code object->data.seek_table.num_points > point_num \endcode
  85089. */
  85090. FLAC_API void FLAC__metadata_object_seektable_set_point(FLAC__StreamMetadata *object, unsigned point_num, FLAC__StreamMetadata_SeekPoint point);
  85091. /** Insert a seekpoint into a seektable.
  85092. *
  85093. * \param object A pointer to an existing SEEKTABLE object.
  85094. * \param point_num Index into seekpoint array to set.
  85095. * \param point The point to set.
  85096. * \assert
  85097. * \code object != NULL \endcode
  85098. * \code object->type == FLAC__METADATA_TYPE_SEEKTABLE \endcode
  85099. * \code object->data.seek_table.num_points >= point_num \endcode
  85100. * \retval FLAC__bool
  85101. * \c false if memory allocation error, else \c true.
  85102. */
  85103. FLAC_API FLAC__bool FLAC__metadata_object_seektable_insert_point(FLAC__StreamMetadata *object, unsigned point_num, FLAC__StreamMetadata_SeekPoint point);
  85104. /** Delete a seekpoint from a seektable.
  85105. *
  85106. * \param object A pointer to an existing SEEKTABLE object.
  85107. * \param point_num Index into seekpoint array to set.
  85108. * \assert
  85109. * \code object != NULL \endcode
  85110. * \code object->type == FLAC__METADATA_TYPE_SEEKTABLE \endcode
  85111. * \code object->data.seek_table.num_points > point_num \endcode
  85112. * \retval FLAC__bool
  85113. * \c false if memory allocation error, else \c true.
  85114. */
  85115. FLAC_API FLAC__bool FLAC__metadata_object_seektable_delete_point(FLAC__StreamMetadata *object, unsigned point_num);
  85116. /** Check a seektable to see if it conforms to the FLAC specification.
  85117. * See the format specification for limits on the contents of the
  85118. * seektable.
  85119. *
  85120. * \param object A pointer to an existing SEEKTABLE object.
  85121. * \assert
  85122. * \code object != NULL \endcode
  85123. * \code object->type == FLAC__METADATA_TYPE_SEEKTABLE \endcode
  85124. * \retval FLAC__bool
  85125. * \c false if seek table is illegal, else \c true.
  85126. */
  85127. FLAC_API FLAC__bool FLAC__metadata_object_seektable_is_legal(const FLAC__StreamMetadata *object);
  85128. /** Append a number of placeholder points to the end of a seek table.
  85129. *
  85130. * \note
  85131. * As with the other ..._seektable_template_... functions, you should
  85132. * call FLAC__metadata_object_seektable_template_sort() when finished
  85133. * to make the seek table legal.
  85134. *
  85135. * \param object A pointer to an existing SEEKTABLE object.
  85136. * \param num The number of placeholder points to append.
  85137. * \assert
  85138. * \code object != NULL \endcode
  85139. * \code object->type == FLAC__METADATA_TYPE_SEEKTABLE \endcode
  85140. * \retval FLAC__bool
  85141. * \c false if memory allocation fails, else \c true.
  85142. */
  85143. FLAC_API FLAC__bool FLAC__metadata_object_seektable_template_append_placeholders(FLAC__StreamMetadata *object, unsigned num);
  85144. /** Append a specific seek point template to the end of a seek table.
  85145. *
  85146. * \note
  85147. * As with the other ..._seektable_template_... functions, you should
  85148. * call FLAC__metadata_object_seektable_template_sort() when finished
  85149. * to make the seek table legal.
  85150. *
  85151. * \param object A pointer to an existing SEEKTABLE object.
  85152. * \param sample_number The sample number of the seek point template.
  85153. * \assert
  85154. * \code object != NULL \endcode
  85155. * \code object->type == FLAC__METADATA_TYPE_SEEKTABLE \endcode
  85156. * \retval FLAC__bool
  85157. * \c false if memory allocation fails, else \c true.
  85158. */
  85159. FLAC_API FLAC__bool FLAC__metadata_object_seektable_template_append_point(FLAC__StreamMetadata *object, FLAC__uint64 sample_number);
  85160. /** Append specific seek point templates to the end of a seek table.
  85161. *
  85162. * \note
  85163. * As with the other ..._seektable_template_... functions, you should
  85164. * call FLAC__metadata_object_seektable_template_sort() when finished
  85165. * to make the seek table legal.
  85166. *
  85167. * \param object A pointer to an existing SEEKTABLE object.
  85168. * \param sample_numbers An array of sample numbers for the seek points.
  85169. * \param num The number of seek point templates to append.
  85170. * \assert
  85171. * \code object != NULL \endcode
  85172. * \code object->type == FLAC__METADATA_TYPE_SEEKTABLE \endcode
  85173. * \retval FLAC__bool
  85174. * \c false if memory allocation fails, else \c true.
  85175. */
  85176. FLAC_API FLAC__bool FLAC__metadata_object_seektable_template_append_points(FLAC__StreamMetadata *object, FLAC__uint64 sample_numbers[], unsigned num);
  85177. /** Append a set of evenly-spaced seek point templates to the end of a
  85178. * seek table.
  85179. *
  85180. * \note
  85181. * As with the other ..._seektable_template_... functions, you should
  85182. * call FLAC__metadata_object_seektable_template_sort() when finished
  85183. * to make the seek table legal.
  85184. *
  85185. * \param object A pointer to an existing SEEKTABLE object.
  85186. * \param num The number of placeholder points to append.
  85187. * \param total_samples The total number of samples to be encoded;
  85188. * the seekpoints will be spaced approximately
  85189. * \a total_samples / \a num samples apart.
  85190. * \assert
  85191. * \code object != NULL \endcode
  85192. * \code object->type == FLAC__METADATA_TYPE_SEEKTABLE \endcode
  85193. * \code total_samples > 0 \endcode
  85194. * \retval FLAC__bool
  85195. * \c false if memory allocation fails, else \c true.
  85196. */
  85197. FLAC_API FLAC__bool FLAC__metadata_object_seektable_template_append_spaced_points(FLAC__StreamMetadata *object, unsigned num, FLAC__uint64 total_samples);
  85198. /** Append a set of evenly-spaced seek point templates to the end of a
  85199. * seek table.
  85200. *
  85201. * \note
  85202. * As with the other ..._seektable_template_... functions, you should
  85203. * call FLAC__metadata_object_seektable_template_sort() when finished
  85204. * to make the seek table legal.
  85205. *
  85206. * \param object A pointer to an existing SEEKTABLE object.
  85207. * \param samples The number of samples apart to space the placeholder
  85208. * points. The first point will be at sample \c 0, the
  85209. * second at sample \a samples, then 2*\a samples, and
  85210. * so on. As long as \a samples and \a total_samples
  85211. * are greater than \c 0, there will always be at least
  85212. * one seekpoint at sample \c 0.
  85213. * \param total_samples The total number of samples to be encoded;
  85214. * the seekpoints will be spaced
  85215. * \a samples samples apart.
  85216. * \assert
  85217. * \code object != NULL \endcode
  85218. * \code object->type == FLAC__METADATA_TYPE_SEEKTABLE \endcode
  85219. * \code samples > 0 \endcode
  85220. * \code total_samples > 0 \endcode
  85221. * \retval FLAC__bool
  85222. * \c false if memory allocation fails, else \c true.
  85223. */
  85224. FLAC_API FLAC__bool FLAC__metadata_object_seektable_template_append_spaced_points_by_samples(FLAC__StreamMetadata *object, unsigned samples, FLAC__uint64 total_samples);
  85225. /** Sort a seek table's seek points according to the format specification,
  85226. * removing duplicates.
  85227. *
  85228. * \param object A pointer to a seek table to be sorted.
  85229. * \param compact If \c false, behaves like FLAC__format_seektable_sort().
  85230. * If \c true, duplicates are deleted and the seek table is
  85231. * shrunk appropriately; the number of placeholder points
  85232. * present in the seek table will be the same after the call
  85233. * as before.
  85234. * \assert
  85235. * \code object != NULL \endcode
  85236. * \code object->type == FLAC__METADATA_TYPE_SEEKTABLE \endcode
  85237. * \retval FLAC__bool
  85238. * \c false if realloc() fails, else \c true.
  85239. */
  85240. FLAC_API FLAC__bool FLAC__metadata_object_seektable_template_sort(FLAC__StreamMetadata *object, FLAC__bool compact);
  85241. /** Sets the vendor string in a VORBIS_COMMENT block.
  85242. *
  85243. * For convenience, a trailing NUL is added to the entry if it doesn't have
  85244. * one already.
  85245. *
  85246. * If \a copy is \c true, a copy of the entry is stored; otherwise, the object
  85247. * takes ownership of the \c entry.entry pointer.
  85248. *
  85249. * \note If this function returns \c false, the caller still owns the
  85250. * pointer.
  85251. *
  85252. * \param object A pointer to an existing VORBIS_COMMENT object.
  85253. * \param entry The entry to set the vendor string to.
  85254. * \param copy See above.
  85255. * \assert
  85256. * \code object != NULL \endcode
  85257. * \code object->type == FLAC__METADATA_TYPE_VORBIS_COMMENT \endcode
  85258. * \code (entry.entry != NULL && entry.length > 0) ||
  85259. * (entry.entry == NULL && entry.length == 0) \endcode
  85260. * \retval FLAC__bool
  85261. * \c false if memory allocation fails or \a entry does not comply with the
  85262. * Vorbis comment specification, else \c true.
  85263. */
  85264. FLAC_API FLAC__bool FLAC__metadata_object_vorbiscomment_set_vendor_string(FLAC__StreamMetadata *object, FLAC__StreamMetadata_VorbisComment_Entry entry, FLAC__bool copy);
  85265. /** Resize the comment array.
  85266. *
  85267. * If the size shrinks, elements will truncated; if it grows, new empty
  85268. * fields will be added to the end.
  85269. *
  85270. * \param object A pointer to an existing VORBIS_COMMENT object.
  85271. * \param new_num_comments The desired length of the array; may be \c 0.
  85272. * \assert
  85273. * \code object != NULL \endcode
  85274. * \code object->type == FLAC__METADATA_TYPE_VORBIS_COMMENT \endcode
  85275. * \code (object->data.vorbis_comment.comments == NULL && object->data.vorbis_comment.num_comments == 0) ||
  85276. * (object->data.vorbis_comment.comments != NULL && object->data.vorbis_comment.num_comments > 0) \endcode
  85277. * \retval FLAC__bool
  85278. * \c false if memory allocation fails, else \c true.
  85279. */
  85280. FLAC_API FLAC__bool FLAC__metadata_object_vorbiscomment_resize_comments(FLAC__StreamMetadata *object, unsigned new_num_comments);
  85281. /** Sets a comment in a VORBIS_COMMENT block.
  85282. *
  85283. * For convenience, a trailing NUL is added to the entry if it doesn't have
  85284. * one already.
  85285. *
  85286. * If \a copy is \c true, a copy of the entry is stored; otherwise, the object
  85287. * takes ownership of the \c entry.entry pointer.
  85288. *
  85289. * \note If this function returns \c false, the caller still owns the
  85290. * pointer.
  85291. *
  85292. * \param object A pointer to an existing VORBIS_COMMENT object.
  85293. * \param comment_num Index into comment array to set.
  85294. * \param entry The entry to set the comment to.
  85295. * \param copy See above.
  85296. * \assert
  85297. * \code object != NULL \endcode
  85298. * \code object->type == FLAC__METADATA_TYPE_VORBIS_COMMENT \endcode
  85299. * \code comment_num < object->data.vorbis_comment.num_comments \endcode
  85300. * \code (entry.entry != NULL && entry.length > 0) ||
  85301. * (entry.entry == NULL && entry.length == 0) \endcode
  85302. * \retval FLAC__bool
  85303. * \c false if memory allocation fails or \a entry does not comply with the
  85304. * Vorbis comment specification, else \c true.
  85305. */
  85306. FLAC_API FLAC__bool FLAC__metadata_object_vorbiscomment_set_comment(FLAC__StreamMetadata *object, unsigned comment_num, FLAC__StreamMetadata_VorbisComment_Entry entry, FLAC__bool copy);
  85307. /** Insert a comment in a VORBIS_COMMENT block at the given index.
  85308. *
  85309. * For convenience, a trailing NUL is added to the entry if it doesn't have
  85310. * one already.
  85311. *
  85312. * If \a copy is \c true, a copy of the entry is stored; otherwise, the object
  85313. * takes ownership of the \c entry.entry pointer.
  85314. *
  85315. * \note If this function returns \c false, the caller still owns the
  85316. * pointer.
  85317. *
  85318. * \param object A pointer to an existing VORBIS_COMMENT object.
  85319. * \param comment_num The index at which to insert the comment. The comments
  85320. * at and after \a comment_num move right one position.
  85321. * To append a comment to the end, set \a comment_num to
  85322. * \c object->data.vorbis_comment.num_comments .
  85323. * \param entry The comment to insert.
  85324. * \param copy See above.
  85325. * \assert
  85326. * \code object != NULL \endcode
  85327. * \code object->type == FLAC__METADATA_TYPE_VORBIS_COMMENT \endcode
  85328. * \code object->data.vorbis_comment.num_comments >= comment_num \endcode
  85329. * \code (entry.entry != NULL && entry.length > 0) ||
  85330. * (entry.entry == NULL && entry.length == 0 && copy == false) \endcode
  85331. * \retval FLAC__bool
  85332. * \c false if memory allocation fails or \a entry does not comply with the
  85333. * Vorbis comment specification, else \c true.
  85334. */
  85335. FLAC_API FLAC__bool FLAC__metadata_object_vorbiscomment_insert_comment(FLAC__StreamMetadata *object, unsigned comment_num, FLAC__StreamMetadata_VorbisComment_Entry entry, FLAC__bool copy);
  85336. /** Appends a comment to a VORBIS_COMMENT block.
  85337. *
  85338. * For convenience, a trailing NUL is added to the entry if it doesn't have
  85339. * one already.
  85340. *
  85341. * If \a copy is \c true, a copy of the entry is stored; otherwise, the object
  85342. * takes ownership of the \c entry.entry pointer.
  85343. *
  85344. * \note If this function returns \c false, the caller still owns the
  85345. * pointer.
  85346. *
  85347. * \param object A pointer to an existing VORBIS_COMMENT object.
  85348. * \param entry The comment to insert.
  85349. * \param copy See above.
  85350. * \assert
  85351. * \code object != NULL \endcode
  85352. * \code object->type == FLAC__METADATA_TYPE_VORBIS_COMMENT \endcode
  85353. * \code (entry.entry != NULL && entry.length > 0) ||
  85354. * (entry.entry == NULL && entry.length == 0 && copy == false) \endcode
  85355. * \retval FLAC__bool
  85356. * \c false if memory allocation fails or \a entry does not comply with the
  85357. * Vorbis comment specification, else \c true.
  85358. */
  85359. FLAC_API FLAC__bool FLAC__metadata_object_vorbiscomment_append_comment(FLAC__StreamMetadata *object, FLAC__StreamMetadata_VorbisComment_Entry entry, FLAC__bool copy);
  85360. /** Replaces comments in a VORBIS_COMMENT block with a new one.
  85361. *
  85362. * For convenience, a trailing NUL is added to the entry if it doesn't have
  85363. * one already.
  85364. *
  85365. * Depending on the the value of \a all, either all or just the first comment
  85366. * whose field name(s) match the given entry's name will be replaced by the
  85367. * given entry. If no comments match, \a entry will simply be appended.
  85368. *
  85369. * If \a copy is \c true, a copy of the entry is stored; otherwise, the object
  85370. * takes ownership of the \c entry.entry pointer.
  85371. *
  85372. * \note If this function returns \c false, the caller still owns the
  85373. * pointer.
  85374. *
  85375. * \param object A pointer to an existing VORBIS_COMMENT object.
  85376. * \param entry The comment to insert.
  85377. * \param all If \c true, all comments whose field name matches
  85378. * \a entry's field name will be removed, and \a entry will
  85379. * be inserted at the position of the first matching
  85380. * comment. If \c false, only the first comment whose
  85381. * field name matches \a entry's field name will be
  85382. * replaced with \a entry.
  85383. * \param copy See above.
  85384. * \assert
  85385. * \code object != NULL \endcode
  85386. * \code object->type == FLAC__METADATA_TYPE_VORBIS_COMMENT \endcode
  85387. * \code (entry.entry != NULL && entry.length > 0) ||
  85388. * (entry.entry == NULL && entry.length == 0 && copy == false) \endcode
  85389. * \retval FLAC__bool
  85390. * \c false if memory allocation fails or \a entry does not comply with the
  85391. * Vorbis comment specification, else \c true.
  85392. */
  85393. FLAC_API FLAC__bool FLAC__metadata_object_vorbiscomment_replace_comment(FLAC__StreamMetadata *object, FLAC__StreamMetadata_VorbisComment_Entry entry, FLAC__bool all, FLAC__bool copy);
  85394. /** Delete a comment in a VORBIS_COMMENT block at the given index.
  85395. *
  85396. * \param object A pointer to an existing VORBIS_COMMENT object.
  85397. * \param comment_num The index of the comment to delete.
  85398. * \assert
  85399. * \code object != NULL \endcode
  85400. * \code object->type == FLAC__METADATA_TYPE_VORBIS_COMMENT \endcode
  85401. * \code object->data.vorbis_comment.num_comments > comment_num \endcode
  85402. * \retval FLAC__bool
  85403. * \c false if realloc() fails, else \c true.
  85404. */
  85405. FLAC_API FLAC__bool FLAC__metadata_object_vorbiscomment_delete_comment(FLAC__StreamMetadata *object, unsigned comment_num);
  85406. /** Creates a Vorbis comment entry from NUL-terminated name and value strings.
  85407. *
  85408. * On return, the filled-in \a entry->entry pointer will point to malloc()ed
  85409. * memory and shall be owned by the caller. For convenience the entry will
  85410. * have a terminating NUL.
  85411. *
  85412. * \param entry A pointer to a Vorbis comment entry. The entry's
  85413. * \c entry pointer should not point to allocated
  85414. * memory as it will be overwritten.
  85415. * \param field_name The field name in ASCII, \c NUL terminated.
  85416. * \param field_value The field value in UTF-8, \c NUL terminated.
  85417. * \assert
  85418. * \code entry != NULL \endcode
  85419. * \code field_name != NULL \endcode
  85420. * \code field_value != NULL \endcode
  85421. * \retval FLAC__bool
  85422. * \c false if malloc() fails, or if \a field_name or \a field_value does
  85423. * not comply with the Vorbis comment specification, else \c true.
  85424. */
  85425. 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);
  85426. /** Splits a Vorbis comment entry into NUL-terminated name and value strings.
  85427. *
  85428. * The returned pointers to name and value will be allocated by malloc()
  85429. * and shall be owned by the caller.
  85430. *
  85431. * \param entry An existing Vorbis comment entry.
  85432. * \param field_name The address of where the returned pointer to the
  85433. * field name will be stored.
  85434. * \param field_value The address of where the returned pointer to the
  85435. * field value will be stored.
  85436. * \assert
  85437. * \code (entry.entry != NULL && entry.length > 0) \endcode
  85438. * \code memchr(entry.entry, '=', entry.length) != NULL \endcode
  85439. * \code field_name != NULL \endcode
  85440. * \code field_value != NULL \endcode
  85441. * \retval FLAC__bool
  85442. * \c false if memory allocation fails or \a entry does not comply with the
  85443. * Vorbis comment specification, else \c true.
  85444. */
  85445. 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);
  85446. /** Check if the given Vorbis comment entry's field name matches the given
  85447. * field name.
  85448. *
  85449. * \param entry An existing Vorbis comment entry.
  85450. * \param field_name The field name to check.
  85451. * \param field_name_length The length of \a field_name, not including the
  85452. * terminating \c NUL.
  85453. * \assert
  85454. * \code (entry.entry != NULL && entry.length > 0) \endcode
  85455. * \retval FLAC__bool
  85456. * \c true if the field names match, else \c false
  85457. */
  85458. FLAC_API FLAC__bool FLAC__metadata_object_vorbiscomment_entry_matches(const FLAC__StreamMetadata_VorbisComment_Entry entry, const char *field_name, unsigned field_name_length);
  85459. /** Find a Vorbis comment with the given field name.
  85460. *
  85461. * The search begins at entry number \a offset; use an offset of 0 to
  85462. * search from the beginning of the comment array.
  85463. *
  85464. * \param object A pointer to an existing VORBIS_COMMENT object.
  85465. * \param offset The offset into the comment array from where to start
  85466. * the search.
  85467. * \param field_name The field name of the comment to find.
  85468. * \assert
  85469. * \code object != NULL \endcode
  85470. * \code object->type == FLAC__METADATA_TYPE_VORBIS_COMMENT \endcode
  85471. * \code field_name != NULL \endcode
  85472. * \retval int
  85473. * The offset in the comment array of the first comment whose field
  85474. * name matches \a field_name, or \c -1 if no match was found.
  85475. */
  85476. FLAC_API int FLAC__metadata_object_vorbiscomment_find_entry_from(const FLAC__StreamMetadata *object, unsigned offset, const char *field_name);
  85477. /** Remove first Vorbis comment matching the given field name.
  85478. *
  85479. * \param object A pointer to an existing VORBIS_COMMENT object.
  85480. * \param field_name The field name of comment to delete.
  85481. * \assert
  85482. * \code object != NULL \endcode
  85483. * \code object->type == FLAC__METADATA_TYPE_VORBIS_COMMENT \endcode
  85484. * \retval int
  85485. * \c -1 for memory allocation error, \c 0 for no matching entries,
  85486. * \c 1 for one matching entry deleted.
  85487. */
  85488. FLAC_API int FLAC__metadata_object_vorbiscomment_remove_entry_matching(FLAC__StreamMetadata *object, const char *field_name);
  85489. /** Remove all Vorbis comments matching the given field name.
  85490. *
  85491. * \param object A pointer to an existing VORBIS_COMMENT object.
  85492. * \param field_name The field name of comments to delete.
  85493. * \assert
  85494. * \code object != NULL \endcode
  85495. * \code object->type == FLAC__METADATA_TYPE_VORBIS_COMMENT \endcode
  85496. * \retval int
  85497. * \c -1 for memory allocation error, \c 0 for no matching entries,
  85498. * else the number of matching entries deleted.
  85499. */
  85500. FLAC_API int FLAC__metadata_object_vorbiscomment_remove_entries_matching(FLAC__StreamMetadata *object, const char *field_name);
  85501. /** Create a new CUESHEET track instance.
  85502. *
  85503. * The object will be "empty"; i.e. values and data pointers will be \c 0.
  85504. *
  85505. * \retval FLAC__StreamMetadata_CueSheet_Track*
  85506. * \c NULL if there was an error allocating memory, else the new instance.
  85507. */
  85508. FLAC_API FLAC__StreamMetadata_CueSheet_Track *FLAC__metadata_object_cuesheet_track_new(void);
  85509. /** Create a copy of an existing CUESHEET track object.
  85510. *
  85511. * The copy is a "deep" copy, i.e. dynamically allocated data within the
  85512. * object is also copied. The caller takes ownership of the new object and
  85513. * is responsible for freeing it with
  85514. * FLAC__metadata_object_cuesheet_track_delete().
  85515. *
  85516. * \param object Pointer to object to copy.
  85517. * \assert
  85518. * \code object != NULL \endcode
  85519. * \retval FLAC__StreamMetadata_CueSheet_Track*
  85520. * \c NULL if there was an error allocating memory, else the new instance.
  85521. */
  85522. FLAC_API FLAC__StreamMetadata_CueSheet_Track *FLAC__metadata_object_cuesheet_track_clone(const FLAC__StreamMetadata_CueSheet_Track *object);
  85523. /** Delete a CUESHEET track object
  85524. *
  85525. * \param object A pointer to an existing CUESHEET track object.
  85526. * \assert
  85527. * \code object != NULL \endcode
  85528. */
  85529. FLAC_API void FLAC__metadata_object_cuesheet_track_delete(FLAC__StreamMetadata_CueSheet_Track *object);
  85530. /** Resize a track's index point array.
  85531. *
  85532. * If the size shrinks, elements will truncated; if it grows, new blank
  85533. * indices will be added to the end.
  85534. *
  85535. * \param object A pointer to an existing CUESHEET object.
  85536. * \param track_num The index of the track to modify. NOTE: this is not
  85537. * necessarily the same as the track's \a number field.
  85538. * \param new_num_indices The desired length of the array; may be \c 0.
  85539. * \assert
  85540. * \code object != NULL \endcode
  85541. * \code object->type == FLAC__METADATA_TYPE_CUESHEET \endcode
  85542. * \code object->data.cue_sheet.num_tracks > track_num \endcode
  85543. * \code (object->data.cue_sheet.tracks[track_num].indices == NULL && object->data.cue_sheet.tracks[track_num].num_indices == 0) ||
  85544. * (object->data.cue_sheet.tracks[track_num].indices != NULL && object->data.cue_sheet.tracks[track_num].num_indices > 0) \endcode
  85545. * \retval FLAC__bool
  85546. * \c false if memory allocation error, else \c true.
  85547. */
  85548. FLAC_API FLAC__bool FLAC__metadata_object_cuesheet_track_resize_indices(FLAC__StreamMetadata *object, unsigned track_num, unsigned new_num_indices);
  85549. /** Insert an index point in a CUESHEET track at the given index.
  85550. *
  85551. * \param object A pointer to an existing CUESHEET object.
  85552. * \param track_num The index of the track to modify. NOTE: this is not
  85553. * necessarily the same as the track's \a number field.
  85554. * \param index_num The index into the track's index array at which to
  85555. * insert the index point. NOTE: this is not necessarily
  85556. * the same as the index point's \a number field. The
  85557. * indices at and after \a index_num move right one
  85558. * position. To append an index point to the end, set
  85559. * \a index_num to
  85560. * \c object->data.cue_sheet.tracks[track_num].num_indices .
  85561. * \param index The index point to insert.
  85562. * \assert
  85563. * \code object != NULL \endcode
  85564. * \code object->type == FLAC__METADATA_TYPE_CUESHEET \endcode
  85565. * \code object->data.cue_sheet.num_tracks > track_num \endcode
  85566. * \code object->data.cue_sheet.tracks[track_num].num_indices >= index_num \endcode
  85567. * \retval FLAC__bool
  85568. * \c false if realloc() fails, else \c true.
  85569. */
  85570. 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);
  85571. /** Insert a blank index point in a CUESHEET track at the given index.
  85572. *
  85573. * A blank index point is one in which all field values are zero.
  85574. *
  85575. * \param object A pointer to an existing CUESHEET object.
  85576. * \param track_num The index of the track to modify. NOTE: this is not
  85577. * necessarily the same as the track's \a number field.
  85578. * \param index_num The index into the track's index array at which to
  85579. * insert the index point. NOTE: this is not necessarily
  85580. * the same as the index point's \a number field. The
  85581. * indices at and after \a index_num move right one
  85582. * position. To append an index point to the end, set
  85583. * \a index_num to
  85584. * \c object->data.cue_sheet.tracks[track_num].num_indices .
  85585. * \assert
  85586. * \code object != NULL \endcode
  85587. * \code object->type == FLAC__METADATA_TYPE_CUESHEET \endcode
  85588. * \code object->data.cue_sheet.num_tracks > track_num \endcode
  85589. * \code object->data.cue_sheet.tracks[track_num].num_indices >= index_num \endcode
  85590. * \retval FLAC__bool
  85591. * \c false if realloc() fails, else \c true.
  85592. */
  85593. FLAC_API FLAC__bool FLAC__metadata_object_cuesheet_track_insert_blank_index(FLAC__StreamMetadata *object, unsigned track_num, unsigned index_num);
  85594. /** Delete an index point in a CUESHEET track at the given index.
  85595. *
  85596. * \param object A pointer to an existing CUESHEET object.
  85597. * \param track_num The index into the track array of the track to
  85598. * modify. NOTE: this is not necessarily the same
  85599. * as the track's \a number field.
  85600. * \param index_num The index into the track's index array of the index
  85601. * to delete. NOTE: this is not necessarily the same
  85602. * as the index's \a number field.
  85603. * \assert
  85604. * \code object != NULL \endcode
  85605. * \code object->type == FLAC__METADATA_TYPE_CUESHEET \endcode
  85606. * \code object->data.cue_sheet.num_tracks > track_num \endcode
  85607. * \code object->data.cue_sheet.tracks[track_num].num_indices > index_num \endcode
  85608. * \retval FLAC__bool
  85609. * \c false if realloc() fails, else \c true.
  85610. */
  85611. FLAC_API FLAC__bool FLAC__metadata_object_cuesheet_track_delete_index(FLAC__StreamMetadata *object, unsigned track_num, unsigned index_num);
  85612. /** Resize the track array.
  85613. *
  85614. * If the size shrinks, elements will truncated; if it grows, new blank
  85615. * tracks will be added to the end.
  85616. *
  85617. * \param object A pointer to an existing CUESHEET object.
  85618. * \param new_num_tracks The desired length of the array; may be \c 0.
  85619. * \assert
  85620. * \code object != NULL \endcode
  85621. * \code object->type == FLAC__METADATA_TYPE_CUESHEET \endcode
  85622. * \code (object->data.cue_sheet.tracks == NULL && object->data.cue_sheet.num_tracks == 0) ||
  85623. * (object->data.cue_sheet.tracks != NULL && object->data.cue_sheet.num_tracks > 0) \endcode
  85624. * \retval FLAC__bool
  85625. * \c false if memory allocation error, else \c true.
  85626. */
  85627. FLAC_API FLAC__bool FLAC__metadata_object_cuesheet_resize_tracks(FLAC__StreamMetadata *object, unsigned new_num_tracks);
  85628. /** Sets a track in a CUESHEET block.
  85629. *
  85630. * If \a copy is \c true, a copy of the track is stored; otherwise, the object
  85631. * takes ownership of the \a track pointer.
  85632. *
  85633. * \param object A pointer to an existing CUESHEET object.
  85634. * \param track_num Index into track array to set. NOTE: this is not
  85635. * necessarily the same as the track's \a number field.
  85636. * \param track The track to set the track to. You may safely pass in
  85637. * a const pointer if \a copy is \c true.
  85638. * \param copy See above.
  85639. * \assert
  85640. * \code object != NULL \endcode
  85641. * \code object->type == FLAC__METADATA_TYPE_CUESHEET \endcode
  85642. * \code track_num < object->data.cue_sheet.num_tracks \endcode
  85643. * \code (track->indices != NULL && track->num_indices > 0) ||
  85644. * (track->indices == NULL && track->num_indices == 0)
  85645. * \retval FLAC__bool
  85646. * \c false if \a copy is \c true and malloc() fails, else \c true.
  85647. */
  85648. FLAC_API FLAC__bool FLAC__metadata_object_cuesheet_set_track(FLAC__StreamMetadata *object, unsigned track_num, FLAC__StreamMetadata_CueSheet_Track *track, FLAC__bool copy);
  85649. /** Insert a track in a CUESHEET block at the given index.
  85650. *
  85651. * If \a copy is \c true, a copy of the track is stored; otherwise, the object
  85652. * takes ownership of the \a track pointer.
  85653. *
  85654. * \param object A pointer to an existing CUESHEET object.
  85655. * \param track_num The index at which to insert the track. NOTE: this
  85656. * is not necessarily the same as the track's \a number
  85657. * field. The tracks at and after \a track_num move right
  85658. * one position. To append a track to the end, set
  85659. * \a track_num to \c object->data.cue_sheet.num_tracks .
  85660. * \param track The track to insert. You may safely pass in a const
  85661. * pointer if \a copy is \c true.
  85662. * \param copy See above.
  85663. * \assert
  85664. * \code object != NULL \endcode
  85665. * \code object->type == FLAC__METADATA_TYPE_CUESHEET \endcode
  85666. * \code object->data.cue_sheet.num_tracks >= track_num \endcode
  85667. * \retval FLAC__bool
  85668. * \c false if \a copy is \c true and malloc() fails, else \c true.
  85669. */
  85670. FLAC_API FLAC__bool FLAC__metadata_object_cuesheet_insert_track(FLAC__StreamMetadata *object, unsigned track_num, FLAC__StreamMetadata_CueSheet_Track *track, FLAC__bool copy);
  85671. /** Insert a blank track in a CUESHEET block at the given index.
  85672. *
  85673. * A blank track is one in which all field values are zero.
  85674. *
  85675. * \param object A pointer to an existing CUESHEET object.
  85676. * \param track_num The index at which to insert the track. NOTE: this
  85677. * is not necessarily the same as the track's \a number
  85678. * field. The tracks at and after \a track_num move right
  85679. * one position. To append a track to the end, set
  85680. * \a track_num to \c object->data.cue_sheet.num_tracks .
  85681. * \assert
  85682. * \code object != NULL \endcode
  85683. * \code object->type == FLAC__METADATA_TYPE_CUESHEET \endcode
  85684. * \code object->data.cue_sheet.num_tracks >= track_num \endcode
  85685. * \retval FLAC__bool
  85686. * \c false if \a copy is \c true and malloc() fails, else \c true.
  85687. */
  85688. FLAC_API FLAC__bool FLAC__metadata_object_cuesheet_insert_blank_track(FLAC__StreamMetadata *object, unsigned track_num);
  85689. /** Delete a track in a CUESHEET block at the given index.
  85690. *
  85691. * \param object A pointer to an existing CUESHEET object.
  85692. * \param track_num The index into the track array of the track to
  85693. * delete. NOTE: this is not necessarily the same
  85694. * as the track's \a number field.
  85695. * \assert
  85696. * \code object != NULL \endcode
  85697. * \code object->type == FLAC__METADATA_TYPE_CUESHEET \endcode
  85698. * \code object->data.cue_sheet.num_tracks > track_num \endcode
  85699. * \retval FLAC__bool
  85700. * \c false if realloc() fails, else \c true.
  85701. */
  85702. FLAC_API FLAC__bool FLAC__metadata_object_cuesheet_delete_track(FLAC__StreamMetadata *object, unsigned track_num);
  85703. /** Check a cue sheet to see if it conforms to the FLAC specification.
  85704. * See the format specification for limits on the contents of the
  85705. * cue sheet.
  85706. *
  85707. * \param object A pointer to an existing CUESHEET object.
  85708. * \param check_cd_da_subset If \c true, check CUESHEET against more
  85709. * stringent requirements for a CD-DA (audio) disc.
  85710. * \param violation Address of a pointer to a string. If there is a
  85711. * violation, a pointer to a string explanation of the
  85712. * violation will be returned here. \a violation may be
  85713. * \c NULL if you don't need the returned string. Do not
  85714. * free the returned string; it will always point to static
  85715. * data.
  85716. * \assert
  85717. * \code object != NULL \endcode
  85718. * \code object->type == FLAC__METADATA_TYPE_CUESHEET \endcode
  85719. * \retval FLAC__bool
  85720. * \c false if cue sheet is illegal, else \c true.
  85721. */
  85722. FLAC_API FLAC__bool FLAC__metadata_object_cuesheet_is_legal(const FLAC__StreamMetadata *object, FLAC__bool check_cd_da_subset, const char **violation);
  85723. /** Calculate and return the CDDB/freedb ID for a cue sheet. The function
  85724. * assumes the cue sheet corresponds to a CD; the result is undefined
  85725. * if the cuesheet's is_cd bit is not set.
  85726. *
  85727. * \param object A pointer to an existing CUESHEET object.
  85728. * \assert
  85729. * \code object != NULL \endcode
  85730. * \code object->type == FLAC__METADATA_TYPE_CUESHEET \endcode
  85731. * \retval FLAC__uint32
  85732. * The unsigned integer representation of the CDDB/freedb ID
  85733. */
  85734. FLAC_API FLAC__uint32 FLAC__metadata_object_cuesheet_calculate_cddb_id(const FLAC__StreamMetadata *object);
  85735. /** Sets the MIME type of a PICTURE block.
  85736. *
  85737. * If \a copy is \c true, a copy of the string is stored; otherwise, the object
  85738. * takes ownership of the pointer. The existing string will be freed if this
  85739. * function is successful, otherwise the original string will remain if \a copy
  85740. * is \c true and malloc() fails.
  85741. *
  85742. * \note It is safe to pass a const pointer to \a mime_type if \a copy is \c true.
  85743. *
  85744. * \param object A pointer to an existing PICTURE object.
  85745. * \param mime_type A pointer to the MIME type string. The string must be
  85746. * ASCII characters 0x20-0x7e, NUL-terminated. No validation
  85747. * is done.
  85748. * \param copy See above.
  85749. * \assert
  85750. * \code object != NULL \endcode
  85751. * \code object->type == FLAC__METADATA_TYPE_PICTURE \endcode
  85752. * \code (mime_type != NULL) \endcode
  85753. * \retval FLAC__bool
  85754. * \c false if \a copy is \c true and malloc() fails, else \c true.
  85755. */
  85756. FLAC_API FLAC__bool FLAC__metadata_object_picture_set_mime_type(FLAC__StreamMetadata *object, char *mime_type, FLAC__bool copy);
  85757. /** Sets the description of a PICTURE block.
  85758. *
  85759. * If \a copy is \c true, a copy of the string is stored; otherwise, the object
  85760. * takes ownership of the pointer. The existing string will be freed if this
  85761. * function is successful, otherwise the original string will remain if \a copy
  85762. * is \c true and malloc() fails.
  85763. *
  85764. * \note It is safe to pass a const pointer to \a description if \a copy is \c true.
  85765. *
  85766. * \param object A pointer to an existing PICTURE object.
  85767. * \param description A pointer to the description string. The string must be
  85768. * valid UTF-8, NUL-terminated. No validation is done.
  85769. * \param copy See above.
  85770. * \assert
  85771. * \code object != NULL \endcode
  85772. * \code object->type == FLAC__METADATA_TYPE_PICTURE \endcode
  85773. * \code (description != NULL) \endcode
  85774. * \retval FLAC__bool
  85775. * \c false if \a copy is \c true and malloc() fails, else \c true.
  85776. */
  85777. FLAC_API FLAC__bool FLAC__metadata_object_picture_set_description(FLAC__StreamMetadata *object, FLAC__byte *description, FLAC__bool copy);
  85778. /** Sets the picture data of a PICTURE block.
  85779. *
  85780. * If \a copy is \c true, a copy of the data is stored; otherwise, the object
  85781. * takes ownership of the pointer. Also sets the \a data_length field of the
  85782. * metadata object to what is passed in as the \a length parameter. The
  85783. * existing data will be freed if this function is successful, otherwise the
  85784. * original data and data_length will remain if \a copy is \c true and
  85785. * malloc() fails.
  85786. *
  85787. * \note It is safe to pass a const pointer to \a data if \a copy is \c true.
  85788. *
  85789. * \param object A pointer to an existing PICTURE object.
  85790. * \param data A pointer to the data to set.
  85791. * \param length The length of \a data in bytes.
  85792. * \param copy See above.
  85793. * \assert
  85794. * \code object != NULL \endcode
  85795. * \code object->type == FLAC__METADATA_TYPE_PICTURE \endcode
  85796. * \code (data != NULL && length > 0) ||
  85797. * (data == NULL && length == 0 && copy == false) \endcode
  85798. * \retval FLAC__bool
  85799. * \c false if \a copy is \c true and malloc() fails, else \c true.
  85800. */
  85801. FLAC_API FLAC__bool FLAC__metadata_object_picture_set_data(FLAC__StreamMetadata *object, FLAC__byte *data, FLAC__uint32 length, FLAC__bool copy);
  85802. /** Check a PICTURE block to see if it conforms to the FLAC specification.
  85803. * See the format specification for limits on the contents of the
  85804. * PICTURE block.
  85805. *
  85806. * \param object A pointer to existing PICTURE block to be checked.
  85807. * \param violation Address of a pointer to a string. If there is a
  85808. * violation, a pointer to a string explanation of the
  85809. * violation will be returned here. \a violation may be
  85810. * \c NULL if you don't need the returned string. Do not
  85811. * free the returned string; it will always point to static
  85812. * data.
  85813. * \assert
  85814. * \code object != NULL \endcode
  85815. * \code object->type == FLAC__METADATA_TYPE_PICTURE \endcode
  85816. * \retval FLAC__bool
  85817. * \c false if PICTURE block is illegal, else \c true.
  85818. */
  85819. FLAC_API FLAC__bool FLAC__metadata_object_picture_is_legal(const FLAC__StreamMetadata *object, const char **violation);
  85820. /* \} */
  85821. #ifdef __cplusplus
  85822. }
  85823. #endif
  85824. #endif
  85825. /*** End of inlined file: metadata.h ***/
  85826. /*** Start of inlined file: stream_decoder.h ***/
  85827. #ifndef FLAC__STREAM_DECODER_H
  85828. #define FLAC__STREAM_DECODER_H
  85829. #include <stdio.h> /* for FILE */
  85830. #ifdef __cplusplus
  85831. extern "C" {
  85832. #endif
  85833. /** \file include/FLAC/stream_decoder.h
  85834. *
  85835. * \brief
  85836. * This module contains the functions which implement the stream
  85837. * decoder.
  85838. *
  85839. * See the detailed documentation in the
  85840. * \link flac_stream_decoder stream decoder \endlink module.
  85841. */
  85842. /** \defgroup flac_decoder FLAC/ \*_decoder.h: decoder interfaces
  85843. * \ingroup flac
  85844. *
  85845. * \brief
  85846. * This module describes the decoder layers provided by libFLAC.
  85847. *
  85848. * The stream decoder can be used to decode complete streams either from
  85849. * the client via callbacks, or directly from a file, depending on how
  85850. * it is initialized. When decoding via callbacks, the client provides
  85851. * callbacks for reading FLAC data and writing decoded samples, and
  85852. * handling metadata and errors. If the client also supplies seek-related
  85853. * callback, the decoder function for sample-accurate seeking within the
  85854. * FLAC input is also available. When decoding from a file, the client
  85855. * needs only supply a filename or open \c FILE* and write/metadata/error
  85856. * callbacks; the rest of the callbacks are supplied internally. For more
  85857. * info see the \link flac_stream_decoder stream decoder \endlink module.
  85858. */
  85859. /** \defgroup flac_stream_decoder FLAC/stream_decoder.h: stream decoder interface
  85860. * \ingroup flac_decoder
  85861. *
  85862. * \brief
  85863. * This module contains the functions which implement the stream
  85864. * decoder.
  85865. *
  85866. * The stream decoder can decode native FLAC, and optionally Ogg FLAC
  85867. * (check FLAC_API_SUPPORTS_OGG_FLAC) streams and files.
  85868. *
  85869. * The basic usage of this decoder is as follows:
  85870. * - The program creates an instance of a decoder using
  85871. * FLAC__stream_decoder_new().
  85872. * - The program overrides the default settings using
  85873. * FLAC__stream_decoder_set_*() functions.
  85874. * - The program initializes the instance to validate the settings and
  85875. * prepare for decoding using
  85876. * - FLAC__stream_decoder_init_stream() or FLAC__stream_decoder_init_FILE()
  85877. * or FLAC__stream_decoder_init_file() for native FLAC,
  85878. * - FLAC__stream_decoder_init_ogg_stream() or FLAC__stream_decoder_init_ogg_FILE()
  85879. * or FLAC__stream_decoder_init_ogg_file() for Ogg FLAC
  85880. * - The program calls the FLAC__stream_decoder_process_*() functions
  85881. * to decode data, which subsequently calls the callbacks.
  85882. * - The program finishes the decoding with FLAC__stream_decoder_finish(),
  85883. * which flushes the input and output and resets the decoder to the
  85884. * uninitialized state.
  85885. * - The instance may be used again or deleted with
  85886. * FLAC__stream_decoder_delete().
  85887. *
  85888. * In more detail, the program will create a new instance by calling
  85889. * FLAC__stream_decoder_new(), then call FLAC__stream_decoder_set_*()
  85890. * functions to override the default decoder options, and call
  85891. * one of the FLAC__stream_decoder_init_*() functions.
  85892. *
  85893. * There are three initialization functions for native FLAC, one for
  85894. * setting up the decoder to decode FLAC data from the client via
  85895. * callbacks, and two for decoding directly from a FLAC file.
  85896. *
  85897. * For decoding via callbacks, use FLAC__stream_decoder_init_stream().
  85898. * You must also supply several callbacks for handling I/O. Some (like
  85899. * seeking) are optional, depending on the capabilities of the input.
  85900. *
  85901. * For decoding directly from a file, use FLAC__stream_decoder_init_FILE()
  85902. * or FLAC__stream_decoder_init_file(). Then you must only supply an open
  85903. * \c FILE* or filename and fewer callbacks; the decoder will handle
  85904. * the other callbacks internally.
  85905. *
  85906. * There are three similarly-named init functions for decoding from Ogg
  85907. * FLAC streams. Check \c FLAC_API_SUPPORTS_OGG_FLAC to find out if the
  85908. * library has been built with Ogg support.
  85909. *
  85910. * Once the decoder is initialized, your program will call one of several
  85911. * functions to start the decoding process:
  85912. *
  85913. * - FLAC__stream_decoder_process_single() - Tells the decoder to process at
  85914. * most one metadata block or audio frame and return, calling either the
  85915. * metadata callback or write callback, respectively, once. If the decoder
  85916. * loses sync it will return with only the error callback being called.
  85917. * - FLAC__stream_decoder_process_until_end_of_metadata() - Tells the decoder
  85918. * to process the stream from the current location and stop upon reaching
  85919. * the first audio frame. The client will get one metadata, write, or error
  85920. * callback per metadata block, audio frame, or sync error, respectively.
  85921. * - FLAC__stream_decoder_process_until_end_of_stream() - Tells the decoder
  85922. * to process the stream from the current location until the read callback
  85923. * returns FLAC__STREAM_DECODER_READ_STATUS_END_OF_STREAM or
  85924. * FLAC__STREAM_DECODER_READ_STATUS_ABORT. The client will get one metadata,
  85925. * write, or error callback per metadata block, audio frame, or sync error,
  85926. * respectively.
  85927. *
  85928. * When the decoder has finished decoding (normally or through an abort),
  85929. * the instance is finished by calling FLAC__stream_decoder_finish(), which
  85930. * ensures the decoder is in the correct state and frees memory. Then the
  85931. * instance may be deleted with FLAC__stream_decoder_delete() or initialized
  85932. * again to decode another stream.
  85933. *
  85934. * Seeking is exposed through the FLAC__stream_decoder_seek_absolute() method.
  85935. * At any point after the stream decoder has been initialized, the client can
  85936. * call this function to seek to an exact sample within the stream.
  85937. * Subsequently, the first time the write callback is called it will be
  85938. * passed a (possibly partial) block starting at that sample.
  85939. *
  85940. * If the client cannot seek via the callback interface provided, but still
  85941. * has another way of seeking, it can flush the decoder using
  85942. * FLAC__stream_decoder_flush() and start feeding data from the new position
  85943. * through the read callback.
  85944. *
  85945. * The stream decoder also provides MD5 signature checking. If this is
  85946. * turned on before initialization, FLAC__stream_decoder_finish() will
  85947. * report when the decoded MD5 signature does not match the one stored
  85948. * in the STREAMINFO block. MD5 checking is automatically turned off
  85949. * (until the next FLAC__stream_decoder_reset()) if there is no signature
  85950. * in the STREAMINFO block or when a seek is attempted.
  85951. *
  85952. * The FLAC__stream_decoder_set_metadata_*() functions deserve special
  85953. * attention. By default, the decoder only calls the metadata_callback for
  85954. * the STREAMINFO block. These functions allow you to tell the decoder
  85955. * explicitly which blocks to parse and return via the metadata_callback
  85956. * and/or which to skip. Use a FLAC__stream_decoder_set_metadata_respond_all(),
  85957. * FLAC__stream_decoder_set_metadata_ignore() ... or FLAC__stream_decoder_set_metadata_ignore_all(),
  85958. * FLAC__stream_decoder_set_metadata_respond() ... sequence to exactly specify
  85959. * which blocks to return. Remember that metadata blocks can potentially
  85960. * be big (for example, cover art) so filtering out the ones you don't
  85961. * use can reduce the memory requirements of the decoder. Also note the
  85962. * special forms FLAC__stream_decoder_set_metadata_respond_application(id)
  85963. * and FLAC__stream_decoder_set_metadata_ignore_application(id) for
  85964. * filtering APPLICATION blocks based on the application ID.
  85965. *
  85966. * STREAMINFO and SEEKTABLE blocks are always parsed and used internally, but
  85967. * they still can legally be filtered from the metadata_callback.
  85968. *
  85969. * \note
  85970. * The "set" functions may only be called when the decoder is in the
  85971. * state FLAC__STREAM_DECODER_UNINITIALIZED, i.e. after
  85972. * FLAC__stream_decoder_new() or FLAC__stream_decoder_finish(), but
  85973. * before FLAC__stream_decoder_init_*(). If this is the case they will
  85974. * return \c true, otherwise \c false.
  85975. *
  85976. * \note
  85977. * FLAC__stream_decoder_finish() resets all settings to the constructor
  85978. * defaults, including the callbacks.
  85979. *
  85980. * \{
  85981. */
  85982. /** State values for a FLAC__StreamDecoder
  85983. *
  85984. * The decoder's state can be obtained by calling FLAC__stream_decoder_get_state().
  85985. */
  85986. typedef enum {
  85987. FLAC__STREAM_DECODER_SEARCH_FOR_METADATA = 0,
  85988. /**< The decoder is ready to search for metadata. */
  85989. FLAC__STREAM_DECODER_READ_METADATA,
  85990. /**< The decoder is ready to or is in the process of reading metadata. */
  85991. FLAC__STREAM_DECODER_SEARCH_FOR_FRAME_SYNC,
  85992. /**< The decoder is ready to or is in the process of searching for the
  85993. * frame sync code.
  85994. */
  85995. FLAC__STREAM_DECODER_READ_FRAME,
  85996. /**< The decoder is ready to or is in the process of reading a frame. */
  85997. FLAC__STREAM_DECODER_END_OF_STREAM,
  85998. /**< The decoder has reached the end of the stream. */
  85999. FLAC__STREAM_DECODER_OGG_ERROR,
  86000. /**< An error occurred in the underlying Ogg layer. */
  86001. FLAC__STREAM_DECODER_SEEK_ERROR,
  86002. /**< An error occurred while seeking. The decoder must be flushed
  86003. * with FLAC__stream_decoder_flush() or reset with
  86004. * FLAC__stream_decoder_reset() before decoding can continue.
  86005. */
  86006. FLAC__STREAM_DECODER_ABORTED,
  86007. /**< The decoder was aborted by the read callback. */
  86008. FLAC__STREAM_DECODER_MEMORY_ALLOCATION_ERROR,
  86009. /**< An error occurred allocating memory. The decoder is in an invalid
  86010. * state and can no longer be used.
  86011. */
  86012. FLAC__STREAM_DECODER_UNINITIALIZED
  86013. /**< The decoder is in the uninitialized state; one of the
  86014. * FLAC__stream_decoder_init_*() functions must be called before samples
  86015. * can be processed.
  86016. */
  86017. } FLAC__StreamDecoderState;
  86018. /** Maps a FLAC__StreamDecoderState to a C string.
  86019. *
  86020. * Using a FLAC__StreamDecoderState as the index to this array
  86021. * will give the string equivalent. The contents should not be modified.
  86022. */
  86023. extern FLAC_API const char * const FLAC__StreamDecoderStateString[];
  86024. /** Possible return values for the FLAC__stream_decoder_init_*() functions.
  86025. */
  86026. typedef enum {
  86027. FLAC__STREAM_DECODER_INIT_STATUS_OK = 0,
  86028. /**< Initialization was successful. */
  86029. FLAC__STREAM_DECODER_INIT_STATUS_UNSUPPORTED_CONTAINER,
  86030. /**< The library was not compiled with support for the given container
  86031. * format.
  86032. */
  86033. FLAC__STREAM_DECODER_INIT_STATUS_INVALID_CALLBACKS,
  86034. /**< A required callback was not supplied. */
  86035. FLAC__STREAM_DECODER_INIT_STATUS_MEMORY_ALLOCATION_ERROR,
  86036. /**< An error occurred allocating memory. */
  86037. FLAC__STREAM_DECODER_INIT_STATUS_ERROR_OPENING_FILE,
  86038. /**< fopen() failed in FLAC__stream_decoder_init_file() or
  86039. * FLAC__stream_decoder_init_ogg_file(). */
  86040. FLAC__STREAM_DECODER_INIT_STATUS_ALREADY_INITIALIZED
  86041. /**< FLAC__stream_decoder_init_*() was called when the decoder was
  86042. * already initialized, usually because
  86043. * FLAC__stream_decoder_finish() was not called.
  86044. */
  86045. } FLAC__StreamDecoderInitStatus;
  86046. /** Maps a FLAC__StreamDecoderInitStatus to a C string.
  86047. *
  86048. * Using a FLAC__StreamDecoderInitStatus as the index to this array
  86049. * will give the string equivalent. The contents should not be modified.
  86050. */
  86051. extern FLAC_API const char * const FLAC__StreamDecoderInitStatusString[];
  86052. /** Return values for the FLAC__StreamDecoder read callback.
  86053. */
  86054. typedef enum {
  86055. FLAC__STREAM_DECODER_READ_STATUS_CONTINUE,
  86056. /**< The read was OK and decoding can continue. */
  86057. FLAC__STREAM_DECODER_READ_STATUS_END_OF_STREAM,
  86058. /**< The read was attempted while at the end of the stream. Note that
  86059. * the client must only return this value when the read callback was
  86060. * called when already at the end of the stream. Otherwise, if the read
  86061. * itself moves to the end of the stream, the client should still return
  86062. * the data and \c FLAC__STREAM_DECODER_READ_STATUS_CONTINUE, and then on
  86063. * the next read callback it should return
  86064. * \c FLAC__STREAM_DECODER_READ_STATUS_END_OF_STREAM with a byte count
  86065. * of \c 0.
  86066. */
  86067. FLAC__STREAM_DECODER_READ_STATUS_ABORT
  86068. /**< An unrecoverable error occurred. The decoder will return from the process call. */
  86069. } FLAC__StreamDecoderReadStatus;
  86070. /** Maps a FLAC__StreamDecoderReadStatus to a C string.
  86071. *
  86072. * Using a FLAC__StreamDecoderReadStatus as the index to this array
  86073. * will give the string equivalent. The contents should not be modified.
  86074. */
  86075. extern FLAC_API const char * const FLAC__StreamDecoderReadStatusString[];
  86076. /** Return values for the FLAC__StreamDecoder seek callback.
  86077. */
  86078. typedef enum {
  86079. FLAC__STREAM_DECODER_SEEK_STATUS_OK,
  86080. /**< The seek was OK and decoding can continue. */
  86081. FLAC__STREAM_DECODER_SEEK_STATUS_ERROR,
  86082. /**< An unrecoverable error occurred. The decoder will return from the process call. */
  86083. FLAC__STREAM_DECODER_SEEK_STATUS_UNSUPPORTED
  86084. /**< Client does not support seeking. */
  86085. } FLAC__StreamDecoderSeekStatus;
  86086. /** Maps a FLAC__StreamDecoderSeekStatus to a C string.
  86087. *
  86088. * Using a FLAC__StreamDecoderSeekStatus as the index to this array
  86089. * will give the string equivalent. The contents should not be modified.
  86090. */
  86091. extern FLAC_API const char * const FLAC__StreamDecoderSeekStatusString[];
  86092. /** Return values for the FLAC__StreamDecoder tell callback.
  86093. */
  86094. typedef enum {
  86095. FLAC__STREAM_DECODER_TELL_STATUS_OK,
  86096. /**< The tell was OK and decoding can continue. */
  86097. FLAC__STREAM_DECODER_TELL_STATUS_ERROR,
  86098. /**< An unrecoverable error occurred. The decoder will return from the process call. */
  86099. FLAC__STREAM_DECODER_TELL_STATUS_UNSUPPORTED
  86100. /**< Client does not support telling the position. */
  86101. } FLAC__StreamDecoderTellStatus;
  86102. /** Maps a FLAC__StreamDecoderTellStatus to a C string.
  86103. *
  86104. * Using a FLAC__StreamDecoderTellStatus as the index to this array
  86105. * will give the string equivalent. The contents should not be modified.
  86106. */
  86107. extern FLAC_API const char * const FLAC__StreamDecoderTellStatusString[];
  86108. /** Return values for the FLAC__StreamDecoder length callback.
  86109. */
  86110. typedef enum {
  86111. FLAC__STREAM_DECODER_LENGTH_STATUS_OK,
  86112. /**< The length call was OK and decoding can continue. */
  86113. FLAC__STREAM_DECODER_LENGTH_STATUS_ERROR,
  86114. /**< An unrecoverable error occurred. The decoder will return from the process call. */
  86115. FLAC__STREAM_DECODER_LENGTH_STATUS_UNSUPPORTED
  86116. /**< Client does not support reporting the length. */
  86117. } FLAC__StreamDecoderLengthStatus;
  86118. /** Maps a FLAC__StreamDecoderLengthStatus to a C string.
  86119. *
  86120. * Using a FLAC__StreamDecoderLengthStatus as the index to this array
  86121. * will give the string equivalent. The contents should not be modified.
  86122. */
  86123. extern FLAC_API const char * const FLAC__StreamDecoderLengthStatusString[];
  86124. /** Return values for the FLAC__StreamDecoder write callback.
  86125. */
  86126. typedef enum {
  86127. FLAC__STREAM_DECODER_WRITE_STATUS_CONTINUE,
  86128. /**< The write was OK and decoding can continue. */
  86129. FLAC__STREAM_DECODER_WRITE_STATUS_ABORT
  86130. /**< An unrecoverable error occurred. The decoder will return from the process call. */
  86131. } FLAC__StreamDecoderWriteStatus;
  86132. /** Maps a FLAC__StreamDecoderWriteStatus to a C string.
  86133. *
  86134. * Using a FLAC__StreamDecoderWriteStatus as the index to this array
  86135. * will give the string equivalent. The contents should not be modified.
  86136. */
  86137. extern FLAC_API const char * const FLAC__StreamDecoderWriteStatusString[];
  86138. /** Possible values passed back to the FLAC__StreamDecoder error callback.
  86139. * \c FLAC__STREAM_DECODER_ERROR_STATUS_LOST_SYNC is the generic catch-
  86140. * all. The rest could be caused by bad sync (false synchronization on
  86141. * data that is not the start of a frame) or corrupted data. The error
  86142. * itself is the decoder's best guess at what happened assuming a correct
  86143. * sync. For example \c FLAC__STREAM_DECODER_ERROR_STATUS_BAD_HEADER
  86144. * could be caused by a correct sync on the start of a frame, but some
  86145. * data in the frame header was corrupted. Or it could be the result of
  86146. * syncing on a point the stream that looked like the starting of a frame
  86147. * but was not. \c FLAC__STREAM_DECODER_ERROR_STATUS_UNPARSEABLE_STREAM
  86148. * could be because the decoder encountered a valid frame made by a future
  86149. * version of the encoder which it cannot parse, or because of a false
  86150. * sync making it appear as though an encountered frame was generated by
  86151. * a future encoder.
  86152. */
  86153. typedef enum {
  86154. FLAC__STREAM_DECODER_ERROR_STATUS_LOST_SYNC,
  86155. /**< An error in the stream caused the decoder to lose synchronization. */
  86156. FLAC__STREAM_DECODER_ERROR_STATUS_BAD_HEADER,
  86157. /**< The decoder encountered a corrupted frame header. */
  86158. FLAC__STREAM_DECODER_ERROR_STATUS_FRAME_CRC_MISMATCH,
  86159. /**< The frame's data did not match the CRC in the footer. */
  86160. FLAC__STREAM_DECODER_ERROR_STATUS_UNPARSEABLE_STREAM
  86161. /**< The decoder encountered reserved fields in use in the stream. */
  86162. } FLAC__StreamDecoderErrorStatus;
  86163. /** Maps a FLAC__StreamDecoderErrorStatus to a C string.
  86164. *
  86165. * Using a FLAC__StreamDecoderErrorStatus as the index to this array
  86166. * will give the string equivalent. The contents should not be modified.
  86167. */
  86168. extern FLAC_API const char * const FLAC__StreamDecoderErrorStatusString[];
  86169. /***********************************************************************
  86170. *
  86171. * class FLAC__StreamDecoder
  86172. *
  86173. ***********************************************************************/
  86174. struct FLAC__StreamDecoderProtected;
  86175. struct FLAC__StreamDecoderPrivate;
  86176. /** The opaque structure definition for the stream decoder type.
  86177. * See the \link flac_stream_decoder stream decoder module \endlink
  86178. * for a detailed description.
  86179. */
  86180. typedef struct {
  86181. struct FLAC__StreamDecoderProtected *protected_; /* avoid the C++ keyword 'protected' */
  86182. struct FLAC__StreamDecoderPrivate *private_; /* avoid the C++ keyword 'private' */
  86183. } FLAC__StreamDecoder;
  86184. /** Signature for the read callback.
  86185. *
  86186. * A function pointer matching this signature must be passed to
  86187. * FLAC__stream_decoder_init*_stream(). The supplied function will be
  86188. * called when the decoder needs more input data. The address of the
  86189. * buffer to be filled is supplied, along with the number of bytes the
  86190. * buffer can hold. The callback may choose to supply less data and
  86191. * modify the byte count but must be careful not to overflow the buffer.
  86192. * The callback then returns a status code chosen from
  86193. * FLAC__StreamDecoderReadStatus.
  86194. *
  86195. * Here is an example of a read callback for stdio streams:
  86196. * \code
  86197. * FLAC__StreamDecoderReadStatus read_cb(const FLAC__StreamDecoder *decoder, FLAC__byte buffer[], size_t *bytes, void *client_data)
  86198. * {
  86199. * FILE *file = ((MyClientData*)client_data)->file;
  86200. * if(*bytes > 0) {
  86201. * *bytes = fread(buffer, sizeof(FLAC__byte), *bytes, file);
  86202. * if(ferror(file))
  86203. * return FLAC__STREAM_DECODER_READ_STATUS_ABORT;
  86204. * else if(*bytes == 0)
  86205. * return FLAC__STREAM_DECODER_READ_STATUS_END_OF_STREAM;
  86206. * else
  86207. * return FLAC__STREAM_DECODER_READ_STATUS_CONTINUE;
  86208. * }
  86209. * else
  86210. * return FLAC__STREAM_DECODER_READ_STATUS_ABORT;
  86211. * }
  86212. * \endcode
  86213. *
  86214. * \note In general, FLAC__StreamDecoder functions which change the
  86215. * state should not be called on the \a decoder while in the callback.
  86216. *
  86217. * \param decoder The decoder instance calling the callback.
  86218. * \param buffer A pointer to a location for the callee to store
  86219. * data to be decoded.
  86220. * \param bytes A pointer to the size of the buffer. On entry
  86221. * to the callback, it contains the maximum number
  86222. * of bytes that may be stored in \a buffer. The
  86223. * callee must set it to the actual number of bytes
  86224. * stored (0 in case of error or end-of-stream) before
  86225. * returning.
  86226. * \param client_data The callee's client data set through
  86227. * FLAC__stream_decoder_init_*().
  86228. * \retval FLAC__StreamDecoderReadStatus
  86229. * The callee's return status. Note that the callback should return
  86230. * \c FLAC__STREAM_DECODER_READ_STATUS_END_OF_STREAM if and only if
  86231. * zero bytes were read and there is no more data to be read.
  86232. */
  86233. typedef FLAC__StreamDecoderReadStatus (*FLAC__StreamDecoderReadCallback)(const FLAC__StreamDecoder *decoder, FLAC__byte buffer[], size_t *bytes, void *client_data);
  86234. /** Signature for the seek callback.
  86235. *
  86236. * A function pointer matching this signature may be passed to
  86237. * FLAC__stream_decoder_init*_stream(). The supplied function will be
  86238. * called when the decoder needs to seek the input stream. The decoder
  86239. * will pass the absolute byte offset to seek to, 0 meaning the
  86240. * beginning of the stream.
  86241. *
  86242. * Here is an example of a seek callback for stdio streams:
  86243. * \code
  86244. * FLAC__StreamDecoderSeekStatus seek_cb(const FLAC__StreamDecoder *decoder, FLAC__uint64 absolute_byte_offset, void *client_data)
  86245. * {
  86246. * FILE *file = ((MyClientData*)client_data)->file;
  86247. * if(file == stdin)
  86248. * return FLAC__STREAM_DECODER_SEEK_STATUS_UNSUPPORTED;
  86249. * else if(fseeko(file, (off_t)absolute_byte_offset, SEEK_SET) < 0)
  86250. * return FLAC__STREAM_DECODER_SEEK_STATUS_ERROR;
  86251. * else
  86252. * return FLAC__STREAM_DECODER_SEEK_STATUS_OK;
  86253. * }
  86254. * \endcode
  86255. *
  86256. * \note In general, FLAC__StreamDecoder functions which change the
  86257. * state should not be called on the \a decoder while in the callback.
  86258. *
  86259. * \param decoder The decoder instance calling the callback.
  86260. * \param absolute_byte_offset The offset from the beginning of the stream
  86261. * to seek to.
  86262. * \param client_data The callee's client data set through
  86263. * FLAC__stream_decoder_init_*().
  86264. * \retval FLAC__StreamDecoderSeekStatus
  86265. * The callee's return status.
  86266. */
  86267. typedef FLAC__StreamDecoderSeekStatus (*FLAC__StreamDecoderSeekCallback)(const FLAC__StreamDecoder *decoder, FLAC__uint64 absolute_byte_offset, void *client_data);
  86268. /** Signature for the tell callback.
  86269. *
  86270. * A function pointer matching this signature may be passed to
  86271. * FLAC__stream_decoder_init*_stream(). The supplied function will be
  86272. * called when the decoder wants to know the current position of the
  86273. * stream. The callback should return the byte offset from the
  86274. * beginning of the stream.
  86275. *
  86276. * Here is an example of a tell callback for stdio streams:
  86277. * \code
  86278. * FLAC__StreamDecoderTellStatus tell_cb(const FLAC__StreamDecoder *decoder, FLAC__uint64 *absolute_byte_offset, void *client_data)
  86279. * {
  86280. * FILE *file = ((MyClientData*)client_data)->file;
  86281. * off_t pos;
  86282. * if(file == stdin)
  86283. * return FLAC__STREAM_DECODER_TELL_STATUS_UNSUPPORTED;
  86284. * else if((pos = ftello(file)) < 0)
  86285. * return FLAC__STREAM_DECODER_TELL_STATUS_ERROR;
  86286. * else {
  86287. * *absolute_byte_offset = (FLAC__uint64)pos;
  86288. * return FLAC__STREAM_DECODER_TELL_STATUS_OK;
  86289. * }
  86290. * }
  86291. * \endcode
  86292. *
  86293. * \note In general, FLAC__StreamDecoder functions which change the
  86294. * state should not be called on the \a decoder while in the callback.
  86295. *
  86296. * \param decoder The decoder instance calling the callback.
  86297. * \param absolute_byte_offset A pointer to storage for the current offset
  86298. * from the beginning of the stream.
  86299. * \param client_data The callee's client data set through
  86300. * FLAC__stream_decoder_init_*().
  86301. * \retval FLAC__StreamDecoderTellStatus
  86302. * The callee's return status.
  86303. */
  86304. typedef FLAC__StreamDecoderTellStatus (*FLAC__StreamDecoderTellCallback)(const FLAC__StreamDecoder *decoder, FLAC__uint64 *absolute_byte_offset, void *client_data);
  86305. /** Signature for the length callback.
  86306. *
  86307. * A function pointer matching this signature may be passed to
  86308. * FLAC__stream_decoder_init*_stream(). The supplied function will be
  86309. * called when the decoder wants to know the total length of the stream
  86310. * in bytes.
  86311. *
  86312. * Here is an example of a length callback for stdio streams:
  86313. * \code
  86314. * FLAC__StreamDecoderLengthStatus length_cb(const FLAC__StreamDecoder *decoder, FLAC__uint64 *stream_length, void *client_data)
  86315. * {
  86316. * FILE *file = ((MyClientData*)client_data)->file;
  86317. * struct stat filestats;
  86318. *
  86319. * if(file == stdin)
  86320. * return FLAC__STREAM_DECODER_LENGTH_STATUS_UNSUPPORTED;
  86321. * else if(fstat(fileno(file), &filestats) != 0)
  86322. * return FLAC__STREAM_DECODER_LENGTH_STATUS_ERROR;
  86323. * else {
  86324. * *stream_length = (FLAC__uint64)filestats.st_size;
  86325. * return FLAC__STREAM_DECODER_LENGTH_STATUS_OK;
  86326. * }
  86327. * }
  86328. * \endcode
  86329. *
  86330. * \note In general, FLAC__StreamDecoder functions which change the
  86331. * state should not be called on the \a decoder while in the callback.
  86332. *
  86333. * \param decoder The decoder instance calling the callback.
  86334. * \param stream_length A pointer to storage for the length of the stream
  86335. * in bytes.
  86336. * \param client_data The callee's client data set through
  86337. * FLAC__stream_decoder_init_*().
  86338. * \retval FLAC__StreamDecoderLengthStatus
  86339. * The callee's return status.
  86340. */
  86341. typedef FLAC__StreamDecoderLengthStatus (*FLAC__StreamDecoderLengthCallback)(const FLAC__StreamDecoder *decoder, FLAC__uint64 *stream_length, void *client_data);
  86342. /** Signature for the EOF callback.
  86343. *
  86344. * A function pointer matching this signature may be passed to
  86345. * FLAC__stream_decoder_init*_stream(). The supplied function will be
  86346. * called when the decoder needs to know if the end of the stream has
  86347. * been reached.
  86348. *
  86349. * Here is an example of a EOF callback for stdio streams:
  86350. * FLAC__bool eof_cb(const FLAC__StreamDecoder *decoder, void *client_data)
  86351. * \code
  86352. * {
  86353. * FILE *file = ((MyClientData*)client_data)->file;
  86354. * return feof(file)? true : false;
  86355. * }
  86356. * \endcode
  86357. *
  86358. * \note In general, FLAC__StreamDecoder functions which change the
  86359. * state should not be called on the \a decoder while in the callback.
  86360. *
  86361. * \param decoder The decoder instance calling the callback.
  86362. * \param client_data The callee's client data set through
  86363. * FLAC__stream_decoder_init_*().
  86364. * \retval FLAC__bool
  86365. * \c true if the currently at the end of the stream, else \c false.
  86366. */
  86367. typedef FLAC__bool (*FLAC__StreamDecoderEofCallback)(const FLAC__StreamDecoder *decoder, void *client_data);
  86368. /** Signature for the write callback.
  86369. *
  86370. * A function pointer matching this signature must be passed to one of
  86371. * the FLAC__stream_decoder_init_*() functions.
  86372. * The supplied function will be called when the decoder has decoded a
  86373. * single audio frame. The decoder will pass the frame metadata as well
  86374. * as an array of pointers (one for each channel) pointing to the
  86375. * decoded audio.
  86376. *
  86377. * \note In general, FLAC__StreamDecoder functions which change the
  86378. * state should not be called on the \a decoder while in the callback.
  86379. *
  86380. * \param decoder The decoder instance calling the callback.
  86381. * \param frame The description of the decoded frame. See
  86382. * FLAC__Frame.
  86383. * \param buffer An array of pointers to decoded channels of data.
  86384. * Each pointer will point to an array of signed
  86385. * samples of length \a frame->header.blocksize.
  86386. * Channels will be ordered according to the FLAC
  86387. * specification; see the documentation for the
  86388. * <A HREF="../format.html#frame_header">frame header</A>.
  86389. * \param client_data The callee's client data set through
  86390. * FLAC__stream_decoder_init_*().
  86391. * \retval FLAC__StreamDecoderWriteStatus
  86392. * The callee's return status.
  86393. */
  86394. typedef FLAC__StreamDecoderWriteStatus (*FLAC__StreamDecoderWriteCallback)(const FLAC__StreamDecoder *decoder, const FLAC__Frame *frame, const FLAC__int32 * const buffer[], void *client_data);
  86395. /** Signature for the metadata callback.
  86396. *
  86397. * A function pointer matching this signature must be passed to one of
  86398. * the FLAC__stream_decoder_init_*() functions.
  86399. * The supplied function will be called when the decoder has decoded a
  86400. * metadata block. In a valid FLAC file there will always be one
  86401. * \c STREAMINFO block, followed by zero or more other metadata blocks.
  86402. * These will be supplied by the decoder in the same order as they
  86403. * appear in the stream and always before the first audio frame (i.e.
  86404. * write callback). The metadata block that is passed in must not be
  86405. * modified, and it doesn't live beyond the callback, so you should make
  86406. * a copy of it with FLAC__metadata_object_clone() if you will need it
  86407. * elsewhere. Since metadata blocks can potentially be large, by
  86408. * default the decoder only calls the metadata callback for the
  86409. * \c STREAMINFO block; you can instruct the decoder to pass or filter
  86410. * other blocks with FLAC__stream_decoder_set_metadata_*() calls.
  86411. *
  86412. * \note In general, FLAC__StreamDecoder functions which change the
  86413. * state should not be called on the \a decoder while in the callback.
  86414. *
  86415. * \param decoder The decoder instance calling the callback.
  86416. * \param metadata The decoded metadata block.
  86417. * \param client_data The callee's client data set through
  86418. * FLAC__stream_decoder_init_*().
  86419. */
  86420. typedef void (*FLAC__StreamDecoderMetadataCallback)(const FLAC__StreamDecoder *decoder, const FLAC__StreamMetadata *metadata, void *client_data);
  86421. /** Signature for the error callback.
  86422. *
  86423. * A function pointer matching this signature must be passed to one of
  86424. * the FLAC__stream_decoder_init_*() functions.
  86425. * The supplied function will be called whenever an error occurs during
  86426. * decoding.
  86427. *
  86428. * \note In general, FLAC__StreamDecoder functions which change the
  86429. * state should not be called on the \a decoder while in the callback.
  86430. *
  86431. * \param decoder The decoder instance calling the callback.
  86432. * \param status The error encountered by the decoder.
  86433. * \param client_data The callee's client data set through
  86434. * FLAC__stream_decoder_init_*().
  86435. */
  86436. typedef void (*FLAC__StreamDecoderErrorCallback)(const FLAC__StreamDecoder *decoder, FLAC__StreamDecoderErrorStatus status, void *client_data);
  86437. /***********************************************************************
  86438. *
  86439. * Class constructor/destructor
  86440. *
  86441. ***********************************************************************/
  86442. /** Create a new stream decoder instance. The instance is created with
  86443. * default settings; see the individual FLAC__stream_decoder_set_*()
  86444. * functions for each setting's default.
  86445. *
  86446. * \retval FLAC__StreamDecoder*
  86447. * \c NULL if there was an error allocating memory, else the new instance.
  86448. */
  86449. FLAC_API FLAC__StreamDecoder *FLAC__stream_decoder_new(void);
  86450. /** Free a decoder instance. Deletes the object pointed to by \a decoder.
  86451. *
  86452. * \param decoder A pointer to an existing decoder.
  86453. * \assert
  86454. * \code decoder != NULL \endcode
  86455. */
  86456. FLAC_API void FLAC__stream_decoder_delete(FLAC__StreamDecoder *decoder);
  86457. /***********************************************************************
  86458. *
  86459. * Public class method prototypes
  86460. *
  86461. ***********************************************************************/
  86462. /** Set the serial number for the FLAC stream within the Ogg container.
  86463. * The default behavior is to use the serial number of the first Ogg
  86464. * page. Setting a serial number here will explicitly specify which
  86465. * stream is to be decoded.
  86466. *
  86467. * \note
  86468. * This does not need to be set for native FLAC decoding.
  86469. *
  86470. * \default \c use serial number of first page
  86471. * \param decoder A decoder instance to set.
  86472. * \param serial_number See above.
  86473. * \assert
  86474. * \code decoder != NULL \endcode
  86475. * \retval FLAC__bool
  86476. * \c false if the decoder is already initialized, else \c true.
  86477. */
  86478. FLAC_API FLAC__bool FLAC__stream_decoder_set_ogg_serial_number(FLAC__StreamDecoder *decoder, long serial_number);
  86479. /** Set the "MD5 signature checking" flag. If \c true, the decoder will
  86480. * compute the MD5 signature of the unencoded audio data while decoding
  86481. * and compare it to the signature from the STREAMINFO block, if it
  86482. * exists, during FLAC__stream_decoder_finish().
  86483. *
  86484. * MD5 signature checking will be turned off (until the next
  86485. * FLAC__stream_decoder_reset()) if there is no signature in the
  86486. * STREAMINFO block or when a seek is attempted.
  86487. *
  86488. * Clients that do not use the MD5 check should leave this off to speed
  86489. * up decoding.
  86490. *
  86491. * \default \c false
  86492. * \param decoder A decoder instance to set.
  86493. * \param value Flag value (see above).
  86494. * \assert
  86495. * \code decoder != NULL \endcode
  86496. * \retval FLAC__bool
  86497. * \c false if the decoder is already initialized, else \c true.
  86498. */
  86499. FLAC_API FLAC__bool FLAC__stream_decoder_set_md5_checking(FLAC__StreamDecoder *decoder, FLAC__bool value);
  86500. /** Direct the decoder to pass on all metadata blocks of type \a type.
  86501. *
  86502. * \default By default, only the \c STREAMINFO block is returned via the
  86503. * metadata callback.
  86504. * \param decoder A decoder instance to set.
  86505. * \param type See above.
  86506. * \assert
  86507. * \code decoder != NULL \endcode
  86508. * \a type is valid
  86509. * \retval FLAC__bool
  86510. * \c false if the decoder is already initialized, else \c true.
  86511. */
  86512. FLAC_API FLAC__bool FLAC__stream_decoder_set_metadata_respond(FLAC__StreamDecoder *decoder, FLAC__MetadataType type);
  86513. /** Direct the decoder to pass on all APPLICATION metadata blocks of the
  86514. * given \a id.
  86515. *
  86516. * \default By default, only the \c STREAMINFO block is returned via the
  86517. * metadata callback.
  86518. * \param decoder A decoder instance to set.
  86519. * \param id See above.
  86520. * \assert
  86521. * \code decoder != NULL \endcode
  86522. * \code id != NULL \endcode
  86523. * \retval FLAC__bool
  86524. * \c false if the decoder is already initialized, else \c true.
  86525. */
  86526. FLAC_API FLAC__bool FLAC__stream_decoder_set_metadata_respond_application(FLAC__StreamDecoder *decoder, const FLAC__byte id[4]);
  86527. /** Direct the decoder to pass on all metadata blocks of any type.
  86528. *
  86529. * \default By default, only the \c STREAMINFO block is returned via the
  86530. * metadata callback.
  86531. * \param decoder A decoder instance to set.
  86532. * \assert
  86533. * \code decoder != NULL \endcode
  86534. * \retval FLAC__bool
  86535. * \c false if the decoder is already initialized, else \c true.
  86536. */
  86537. FLAC_API FLAC__bool FLAC__stream_decoder_set_metadata_respond_all(FLAC__StreamDecoder *decoder);
  86538. /** Direct the decoder to filter out all metadata blocks of type \a type.
  86539. *
  86540. * \default By default, only the \c STREAMINFO block is returned via the
  86541. * metadata callback.
  86542. * \param decoder A decoder instance to set.
  86543. * \param type See above.
  86544. * \assert
  86545. * \code decoder != NULL \endcode
  86546. * \a type is valid
  86547. * \retval FLAC__bool
  86548. * \c false if the decoder is already initialized, else \c true.
  86549. */
  86550. FLAC_API FLAC__bool FLAC__stream_decoder_set_metadata_ignore(FLAC__StreamDecoder *decoder, FLAC__MetadataType type);
  86551. /** Direct the decoder to filter out all APPLICATION metadata blocks of
  86552. * the given \a id.
  86553. *
  86554. * \default By default, only the \c STREAMINFO block is returned via the
  86555. * metadata callback.
  86556. * \param decoder A decoder instance to set.
  86557. * \param id See above.
  86558. * \assert
  86559. * \code decoder != NULL \endcode
  86560. * \code id != NULL \endcode
  86561. * \retval FLAC__bool
  86562. * \c false if the decoder is already initialized, else \c true.
  86563. */
  86564. FLAC_API FLAC__bool FLAC__stream_decoder_set_metadata_ignore_application(FLAC__StreamDecoder *decoder, const FLAC__byte id[4]);
  86565. /** Direct the decoder to filter out all metadata blocks of any type.
  86566. *
  86567. * \default By default, only the \c STREAMINFO block is returned via the
  86568. * metadata callback.
  86569. * \param decoder A decoder instance to set.
  86570. * \assert
  86571. * \code decoder != NULL \endcode
  86572. * \retval FLAC__bool
  86573. * \c false if the decoder is already initialized, else \c true.
  86574. */
  86575. FLAC_API FLAC__bool FLAC__stream_decoder_set_metadata_ignore_all(FLAC__StreamDecoder *decoder);
  86576. /** Get the current decoder state.
  86577. *
  86578. * \param decoder A decoder instance to query.
  86579. * \assert
  86580. * \code decoder != NULL \endcode
  86581. * \retval FLAC__StreamDecoderState
  86582. * The current decoder state.
  86583. */
  86584. FLAC_API FLAC__StreamDecoderState FLAC__stream_decoder_get_state(const FLAC__StreamDecoder *decoder);
  86585. /** Get the current decoder state as a C string.
  86586. *
  86587. * \param decoder A decoder instance to query.
  86588. * \assert
  86589. * \code decoder != NULL \endcode
  86590. * \retval const char *
  86591. * The decoder state as a C string. Do not modify the contents.
  86592. */
  86593. FLAC_API const char *FLAC__stream_decoder_get_resolved_state_string(const FLAC__StreamDecoder *decoder);
  86594. /** Get the "MD5 signature checking" flag.
  86595. * This is the value of the setting, not whether or not the decoder is
  86596. * currently checking the MD5 (remember, it can be turned off automatically
  86597. * by a seek). When the decoder is reset the flag will be restored to the
  86598. * value returned by this function.
  86599. *
  86600. * \param decoder A decoder instance to query.
  86601. * \assert
  86602. * \code decoder != NULL \endcode
  86603. * \retval FLAC__bool
  86604. * See above.
  86605. */
  86606. FLAC_API FLAC__bool FLAC__stream_decoder_get_md5_checking(const FLAC__StreamDecoder *decoder);
  86607. /** Get the total number of samples in the stream being decoded.
  86608. * Will only be valid after decoding has started and will contain the
  86609. * value from the \c STREAMINFO block. A value of \c 0 means "unknown".
  86610. *
  86611. * \param decoder A decoder instance to query.
  86612. * \assert
  86613. * \code decoder != NULL \endcode
  86614. * \retval unsigned
  86615. * See above.
  86616. */
  86617. FLAC_API FLAC__uint64 FLAC__stream_decoder_get_total_samples(const FLAC__StreamDecoder *decoder);
  86618. /** Get the current number of channels in the stream being decoded.
  86619. * Will only be valid after decoding has started and will contain the
  86620. * value from the most recently decoded frame header.
  86621. *
  86622. * \param decoder A decoder instance to query.
  86623. * \assert
  86624. * \code decoder != NULL \endcode
  86625. * \retval unsigned
  86626. * See above.
  86627. */
  86628. FLAC_API unsigned FLAC__stream_decoder_get_channels(const FLAC__StreamDecoder *decoder);
  86629. /** Get the current channel assignment in the stream being decoded.
  86630. * Will only be valid after decoding has started and will contain the
  86631. * value from the most recently decoded frame header.
  86632. *
  86633. * \param decoder A decoder instance to query.
  86634. * \assert
  86635. * \code decoder != NULL \endcode
  86636. * \retval FLAC__ChannelAssignment
  86637. * See above.
  86638. */
  86639. FLAC_API FLAC__ChannelAssignment FLAC__stream_decoder_get_channel_assignment(const FLAC__StreamDecoder *decoder);
  86640. /** Get the current sample resolution in the stream being decoded.
  86641. * Will only be valid after decoding has started and will contain the
  86642. * value from the most recently decoded frame header.
  86643. *
  86644. * \param decoder A decoder instance to query.
  86645. * \assert
  86646. * \code decoder != NULL \endcode
  86647. * \retval unsigned
  86648. * See above.
  86649. */
  86650. FLAC_API unsigned FLAC__stream_decoder_get_bits_per_sample(const FLAC__StreamDecoder *decoder);
  86651. /** Get the current sample rate in Hz of the stream being decoded.
  86652. * Will only be valid after decoding has started and will contain the
  86653. * value from the most recently decoded frame header.
  86654. *
  86655. * \param decoder A decoder instance to query.
  86656. * \assert
  86657. * \code decoder != NULL \endcode
  86658. * \retval unsigned
  86659. * See above.
  86660. */
  86661. FLAC_API unsigned FLAC__stream_decoder_get_sample_rate(const FLAC__StreamDecoder *decoder);
  86662. /** Get the current blocksize of the stream being decoded.
  86663. * Will only be valid after decoding has started and will contain the
  86664. * value from the most recently decoded frame header.
  86665. *
  86666. * \param decoder A decoder instance to query.
  86667. * \assert
  86668. * \code decoder != NULL \endcode
  86669. * \retval unsigned
  86670. * See above.
  86671. */
  86672. FLAC_API unsigned FLAC__stream_decoder_get_blocksize(const FLAC__StreamDecoder *decoder);
  86673. /** Returns the decoder's current read position within the stream.
  86674. * The position is the byte offset from the start of the stream.
  86675. * Bytes before this position have been fully decoded. Note that
  86676. * there may still be undecoded bytes in the decoder's read FIFO.
  86677. * The returned position is correct even after a seek.
  86678. *
  86679. * \warning This function currently only works for native FLAC,
  86680. * not Ogg FLAC streams.
  86681. *
  86682. * \param decoder A decoder instance to query.
  86683. * \param position Address at which to return the desired position.
  86684. * \assert
  86685. * \code decoder != NULL \endcode
  86686. * \code position != NULL \endcode
  86687. * \retval FLAC__bool
  86688. * \c true if successful, \c false if the stream is not native FLAC,
  86689. * or there was an error from the 'tell' callback or it returned
  86690. * \c FLAC__STREAM_DECODER_TELL_STATUS_UNSUPPORTED.
  86691. */
  86692. FLAC_API FLAC__bool FLAC__stream_decoder_get_decode_position(const FLAC__StreamDecoder *decoder, FLAC__uint64 *position);
  86693. /** Initialize the decoder instance to decode native FLAC streams.
  86694. *
  86695. * This flavor of initialization sets up the decoder to decode from a
  86696. * native FLAC stream. I/O is performed via callbacks to the client.
  86697. * For decoding from a plain file via filename or open FILE*,
  86698. * FLAC__stream_decoder_init_file() and FLAC__stream_decoder_init_FILE()
  86699. * provide a simpler interface.
  86700. *
  86701. * This function should be called after FLAC__stream_decoder_new() and
  86702. * FLAC__stream_decoder_set_*() but before any of the
  86703. * FLAC__stream_decoder_process_*() functions. Will set and return the
  86704. * decoder state, which will be FLAC__STREAM_DECODER_SEARCH_FOR_METADATA
  86705. * if initialization succeeded.
  86706. *
  86707. * \param decoder An uninitialized decoder instance.
  86708. * \param read_callback See FLAC__StreamDecoderReadCallback. This
  86709. * pointer must not be \c NULL.
  86710. * \param seek_callback See FLAC__StreamDecoderSeekCallback. This
  86711. * pointer may be \c NULL if seeking is not
  86712. * supported. If \a seek_callback is not \c NULL then a
  86713. * \a tell_callback, \a length_callback, and \a eof_callback must also be supplied.
  86714. * Alternatively, a dummy seek callback that just
  86715. * returns \c FLAC__STREAM_DECODER_SEEK_STATUS_UNSUPPORTED
  86716. * may also be supplied, all though this is slightly
  86717. * less efficient for the decoder.
  86718. * \param tell_callback See FLAC__StreamDecoderTellCallback. This
  86719. * pointer may be \c NULL if not supported by the client. If
  86720. * \a seek_callback is not \c NULL then a
  86721. * \a tell_callback must also be supplied.
  86722. * Alternatively, a dummy tell callback that just
  86723. * returns \c FLAC__STREAM_DECODER_TELL_STATUS_UNSUPPORTED
  86724. * may also be supplied, all though this is slightly
  86725. * less efficient for the decoder.
  86726. * \param length_callback See FLAC__StreamDecoderLengthCallback. This
  86727. * pointer may be \c NULL if not supported by the client. If
  86728. * \a seek_callback is not \c NULL then a
  86729. * \a length_callback must also be supplied.
  86730. * Alternatively, a dummy length callback that just
  86731. * returns \c FLAC__STREAM_DECODER_LENGTH_STATUS_UNSUPPORTED
  86732. * may also be supplied, all though this is slightly
  86733. * less efficient for the decoder.
  86734. * \param eof_callback See FLAC__StreamDecoderEofCallback. This
  86735. * pointer may be \c NULL if not supported by the client. If
  86736. * \a seek_callback is not \c NULL then a
  86737. * \a eof_callback must also be supplied.
  86738. * Alternatively, a dummy length callback that just
  86739. * returns \c false
  86740. * may also be supplied, all though this is slightly
  86741. * less efficient for the decoder.
  86742. * \param write_callback See FLAC__StreamDecoderWriteCallback. This
  86743. * pointer must not be \c NULL.
  86744. * \param metadata_callback See FLAC__StreamDecoderMetadataCallback. This
  86745. * pointer may be \c NULL if the callback is not
  86746. * desired.
  86747. * \param error_callback See FLAC__StreamDecoderErrorCallback. This
  86748. * pointer must not be \c NULL.
  86749. * \param client_data This value will be supplied to callbacks in their
  86750. * \a client_data argument.
  86751. * \assert
  86752. * \code decoder != NULL \endcode
  86753. * \retval FLAC__StreamDecoderInitStatus
  86754. * \c FLAC__STREAM_DECODER_INIT_STATUS_OK if initialization was successful;
  86755. * see FLAC__StreamDecoderInitStatus for the meanings of other return values.
  86756. */
  86757. FLAC_API FLAC__StreamDecoderInitStatus FLAC__stream_decoder_init_stream(
  86758. FLAC__StreamDecoder *decoder,
  86759. FLAC__StreamDecoderReadCallback read_callback,
  86760. FLAC__StreamDecoderSeekCallback seek_callback,
  86761. FLAC__StreamDecoderTellCallback tell_callback,
  86762. FLAC__StreamDecoderLengthCallback length_callback,
  86763. FLAC__StreamDecoderEofCallback eof_callback,
  86764. FLAC__StreamDecoderWriteCallback write_callback,
  86765. FLAC__StreamDecoderMetadataCallback metadata_callback,
  86766. FLAC__StreamDecoderErrorCallback error_callback,
  86767. void *client_data
  86768. );
  86769. /** Initialize the decoder instance to decode Ogg FLAC streams.
  86770. *
  86771. * This flavor of initialization sets up the decoder to decode from a
  86772. * FLAC stream in an Ogg container. I/O is performed via callbacks to the
  86773. * client. For decoding from a plain file via filename or open FILE*,
  86774. * FLAC__stream_decoder_init_ogg_file() and FLAC__stream_decoder_init_ogg_FILE()
  86775. * provide a simpler interface.
  86776. *
  86777. * This function should be called after FLAC__stream_decoder_new() and
  86778. * FLAC__stream_decoder_set_*() but before any of the
  86779. * FLAC__stream_decoder_process_*() functions. Will set and return the
  86780. * decoder state, which will be FLAC__STREAM_DECODER_SEARCH_FOR_METADATA
  86781. * if initialization succeeded.
  86782. *
  86783. * \note Support for Ogg FLAC in the library is optional. If this
  86784. * library has been built without support for Ogg FLAC, this function
  86785. * will return \c FLAC__STREAM_DECODER_INIT_STATUS_UNSUPPORTED_CONTAINER.
  86786. *
  86787. * \param decoder An uninitialized decoder instance.
  86788. * \param read_callback See FLAC__StreamDecoderReadCallback. This
  86789. * pointer must not be \c NULL.
  86790. * \param seek_callback See FLAC__StreamDecoderSeekCallback. This
  86791. * pointer may be \c NULL if seeking is not
  86792. * supported. If \a seek_callback is not \c NULL then a
  86793. * \a tell_callback, \a length_callback, and \a eof_callback must also be supplied.
  86794. * Alternatively, a dummy seek callback that just
  86795. * returns \c FLAC__STREAM_DECODER_SEEK_STATUS_UNSUPPORTED
  86796. * may also be supplied, all though this is slightly
  86797. * less efficient for the decoder.
  86798. * \param tell_callback See FLAC__StreamDecoderTellCallback. This
  86799. * pointer may be \c NULL if not supported by the client. If
  86800. * \a seek_callback is not \c NULL then a
  86801. * \a tell_callback must also be supplied.
  86802. * Alternatively, a dummy tell callback that just
  86803. * returns \c FLAC__STREAM_DECODER_TELL_STATUS_UNSUPPORTED
  86804. * may also be supplied, all though this is slightly
  86805. * less efficient for the decoder.
  86806. * \param length_callback See FLAC__StreamDecoderLengthCallback. This
  86807. * pointer may be \c NULL if not supported by the client. If
  86808. * \a seek_callback is not \c NULL then a
  86809. * \a length_callback must also be supplied.
  86810. * Alternatively, a dummy length callback that just
  86811. * returns \c FLAC__STREAM_DECODER_LENGTH_STATUS_UNSUPPORTED
  86812. * may also be supplied, all though this is slightly
  86813. * less efficient for the decoder.
  86814. * \param eof_callback See FLAC__StreamDecoderEofCallback. This
  86815. * pointer may be \c NULL if not supported by the client. If
  86816. * \a seek_callback is not \c NULL then a
  86817. * \a eof_callback must also be supplied.
  86818. * Alternatively, a dummy length callback that just
  86819. * returns \c false
  86820. * may also be supplied, all though this is slightly
  86821. * less efficient for the decoder.
  86822. * \param write_callback See FLAC__StreamDecoderWriteCallback. This
  86823. * pointer must not be \c NULL.
  86824. * \param metadata_callback See FLAC__StreamDecoderMetadataCallback. This
  86825. * pointer may be \c NULL if the callback is not
  86826. * desired.
  86827. * \param error_callback See FLAC__StreamDecoderErrorCallback. This
  86828. * pointer must not be \c NULL.
  86829. * \param client_data This value will be supplied to callbacks in their
  86830. * \a client_data argument.
  86831. * \assert
  86832. * \code decoder != NULL \endcode
  86833. * \retval FLAC__StreamDecoderInitStatus
  86834. * \c FLAC__STREAM_DECODER_INIT_STATUS_OK if initialization was successful;
  86835. * see FLAC__StreamDecoderInitStatus for the meanings of other return values.
  86836. */
  86837. FLAC_API FLAC__StreamDecoderInitStatus FLAC__stream_decoder_init_ogg_stream(
  86838. FLAC__StreamDecoder *decoder,
  86839. FLAC__StreamDecoderReadCallback read_callback,
  86840. FLAC__StreamDecoderSeekCallback seek_callback,
  86841. FLAC__StreamDecoderTellCallback tell_callback,
  86842. FLAC__StreamDecoderLengthCallback length_callback,
  86843. FLAC__StreamDecoderEofCallback eof_callback,
  86844. FLAC__StreamDecoderWriteCallback write_callback,
  86845. FLAC__StreamDecoderMetadataCallback metadata_callback,
  86846. FLAC__StreamDecoderErrorCallback error_callback,
  86847. void *client_data
  86848. );
  86849. /** Initialize the decoder instance to decode native FLAC files.
  86850. *
  86851. * This flavor of initialization sets up the decoder to decode from a
  86852. * plain native FLAC file. For non-stdio streams, you must use
  86853. * FLAC__stream_decoder_init_stream() and provide callbacks for the I/O.
  86854. *
  86855. * This function should be called after FLAC__stream_decoder_new() and
  86856. * FLAC__stream_decoder_set_*() but before any of the
  86857. * FLAC__stream_decoder_process_*() functions. Will set and return the
  86858. * decoder state, which will be FLAC__STREAM_DECODER_SEARCH_FOR_METADATA
  86859. * if initialization succeeded.
  86860. *
  86861. * \param decoder An uninitialized decoder instance.
  86862. * \param file An open FLAC file. The file should have been
  86863. * opened with mode \c "rb" and rewound. The file
  86864. * becomes owned by the decoder and should not be
  86865. * manipulated by the client while decoding.
  86866. * Unless \a file is \c stdin, it will be closed
  86867. * when FLAC__stream_decoder_finish() is called.
  86868. * Note however that seeking will not work when
  86869. * decoding from \c stdout since it is not seekable.
  86870. * \param write_callback See FLAC__StreamDecoderWriteCallback. This
  86871. * pointer must not be \c NULL.
  86872. * \param metadata_callback See FLAC__StreamDecoderMetadataCallback. This
  86873. * pointer may be \c NULL if the callback is not
  86874. * desired.
  86875. * \param error_callback See FLAC__StreamDecoderErrorCallback. This
  86876. * pointer must not be \c NULL.
  86877. * \param client_data This value will be supplied to callbacks in their
  86878. * \a client_data argument.
  86879. * \assert
  86880. * \code decoder != NULL \endcode
  86881. * \code file != NULL \endcode
  86882. * \retval FLAC__StreamDecoderInitStatus
  86883. * \c FLAC__STREAM_DECODER_INIT_STATUS_OK if initialization was successful;
  86884. * see FLAC__StreamDecoderInitStatus for the meanings of other return values.
  86885. */
  86886. FLAC_API FLAC__StreamDecoderInitStatus FLAC__stream_decoder_init_FILE(
  86887. FLAC__StreamDecoder *decoder,
  86888. FILE *file,
  86889. FLAC__StreamDecoderWriteCallback write_callback,
  86890. FLAC__StreamDecoderMetadataCallback metadata_callback,
  86891. FLAC__StreamDecoderErrorCallback error_callback,
  86892. void *client_data
  86893. );
  86894. /** Initialize the decoder instance to decode Ogg FLAC files.
  86895. *
  86896. * This flavor of initialization sets up the decoder to decode from a
  86897. * plain Ogg FLAC file. For non-stdio streams, you must use
  86898. * FLAC__stream_decoder_init_ogg_stream() and provide callbacks for the I/O.
  86899. *
  86900. * This function should be called after FLAC__stream_decoder_new() and
  86901. * FLAC__stream_decoder_set_*() but before any of the
  86902. * FLAC__stream_decoder_process_*() functions. Will set and return the
  86903. * decoder state, which will be FLAC__STREAM_DECODER_SEARCH_FOR_METADATA
  86904. * if initialization succeeded.
  86905. *
  86906. * \note Support for Ogg FLAC in the library is optional. If this
  86907. * library has been built without support for Ogg FLAC, this function
  86908. * will return \c FLAC__STREAM_DECODER_INIT_STATUS_UNSUPPORTED_CONTAINER.
  86909. *
  86910. * \param decoder An uninitialized decoder instance.
  86911. * \param file An open FLAC file. The file should have been
  86912. * opened with mode \c "rb" and rewound. The file
  86913. * becomes owned by the decoder and should not be
  86914. * manipulated by the client while decoding.
  86915. * Unless \a file is \c stdin, it will be closed
  86916. * when FLAC__stream_decoder_finish() is called.
  86917. * Note however that seeking will not work when
  86918. * decoding from \c stdout since it is not seekable.
  86919. * \param write_callback See FLAC__StreamDecoderWriteCallback. This
  86920. * pointer must not be \c NULL.
  86921. * \param metadata_callback See FLAC__StreamDecoderMetadataCallback. This
  86922. * pointer may be \c NULL if the callback is not
  86923. * desired.
  86924. * \param error_callback See FLAC__StreamDecoderErrorCallback. This
  86925. * pointer must not be \c NULL.
  86926. * \param client_data This value will be supplied to callbacks in their
  86927. * \a client_data argument.
  86928. * \assert
  86929. * \code decoder != NULL \endcode
  86930. * \code file != NULL \endcode
  86931. * \retval FLAC__StreamDecoderInitStatus
  86932. * \c FLAC__STREAM_DECODER_INIT_STATUS_OK if initialization was successful;
  86933. * see FLAC__StreamDecoderInitStatus for the meanings of other return values.
  86934. */
  86935. FLAC_API FLAC__StreamDecoderInitStatus FLAC__stream_decoder_init_ogg_FILE(
  86936. FLAC__StreamDecoder *decoder,
  86937. FILE *file,
  86938. FLAC__StreamDecoderWriteCallback write_callback,
  86939. FLAC__StreamDecoderMetadataCallback metadata_callback,
  86940. FLAC__StreamDecoderErrorCallback error_callback,
  86941. void *client_data
  86942. );
  86943. /** Initialize the decoder instance to decode native FLAC files.
  86944. *
  86945. * This flavor of initialization sets up the decoder to decode from a plain
  86946. * native FLAC file. If POSIX fopen() semantics are not sufficient, (for
  86947. * example, with Unicode filenames on Windows), you must use
  86948. * FLAC__stream_decoder_init_FILE(), or FLAC__stream_decoder_init_stream()
  86949. * and provide callbacks for the I/O.
  86950. *
  86951. * This function should be called after FLAC__stream_decoder_new() and
  86952. * FLAC__stream_decoder_set_*() but before any of the
  86953. * FLAC__stream_decoder_process_*() functions. Will set and return the
  86954. * decoder state, which will be FLAC__STREAM_DECODER_SEARCH_FOR_METADATA
  86955. * if initialization succeeded.
  86956. *
  86957. * \param decoder An uninitialized decoder instance.
  86958. * \param filename The name of the file to decode from. The file will
  86959. * be opened with fopen(). Use \c NULL to decode from
  86960. * \c stdin. Note that \c stdin is not seekable.
  86961. * \param write_callback See FLAC__StreamDecoderWriteCallback. This
  86962. * pointer must not be \c NULL.
  86963. * \param metadata_callback See FLAC__StreamDecoderMetadataCallback. This
  86964. * pointer may be \c NULL if the callback is not
  86965. * desired.
  86966. * \param error_callback See FLAC__StreamDecoderErrorCallback. This
  86967. * pointer must not be \c NULL.
  86968. * \param client_data This value will be supplied to callbacks in their
  86969. * \a client_data argument.
  86970. * \assert
  86971. * \code decoder != NULL \endcode
  86972. * \retval FLAC__StreamDecoderInitStatus
  86973. * \c FLAC__STREAM_DECODER_INIT_STATUS_OK if initialization was successful;
  86974. * see FLAC__StreamDecoderInitStatus for the meanings of other return values.
  86975. */
  86976. FLAC_API FLAC__StreamDecoderInitStatus FLAC__stream_decoder_init_file(
  86977. FLAC__StreamDecoder *decoder,
  86978. const char *filename,
  86979. FLAC__StreamDecoderWriteCallback write_callback,
  86980. FLAC__StreamDecoderMetadataCallback metadata_callback,
  86981. FLAC__StreamDecoderErrorCallback error_callback,
  86982. void *client_data
  86983. );
  86984. /** Initialize the decoder instance to decode Ogg FLAC files.
  86985. *
  86986. * This flavor of initialization sets up the decoder to decode from a plain
  86987. * Ogg FLAC file. If POSIX fopen() semantics are not sufficient, (for
  86988. * example, with Unicode filenames on Windows), you must use
  86989. * FLAC__stream_decoder_init_ogg_FILE(), or FLAC__stream_decoder_init_ogg_stream()
  86990. * and provide callbacks for the I/O.
  86991. *
  86992. * This function should be called after FLAC__stream_decoder_new() and
  86993. * FLAC__stream_decoder_set_*() but before any of the
  86994. * FLAC__stream_decoder_process_*() functions. Will set and return the
  86995. * decoder state, which will be FLAC__STREAM_DECODER_SEARCH_FOR_METADATA
  86996. * if initialization succeeded.
  86997. *
  86998. * \note Support for Ogg FLAC in the library is optional. If this
  86999. * library has been built without support for Ogg FLAC, this function
  87000. * will return \c FLAC__STREAM_DECODER_INIT_STATUS_UNSUPPORTED_CONTAINER.
  87001. *
  87002. * \param decoder An uninitialized decoder instance.
  87003. * \param filename The name of the file to decode from. The file will
  87004. * be opened with fopen(). Use \c NULL to decode from
  87005. * \c stdin. Note that \c stdin is not seekable.
  87006. * \param write_callback See FLAC__StreamDecoderWriteCallback. This
  87007. * pointer must not be \c NULL.
  87008. * \param metadata_callback See FLAC__StreamDecoderMetadataCallback. This
  87009. * pointer may be \c NULL if the callback is not
  87010. * desired.
  87011. * \param error_callback See FLAC__StreamDecoderErrorCallback. This
  87012. * pointer must not be \c NULL.
  87013. * \param client_data This value will be supplied to callbacks in their
  87014. * \a client_data argument.
  87015. * \assert
  87016. * \code decoder != NULL \endcode
  87017. * \retval FLAC__StreamDecoderInitStatus
  87018. * \c FLAC__STREAM_DECODER_INIT_STATUS_OK if initialization was successful;
  87019. * see FLAC__StreamDecoderInitStatus for the meanings of other return values.
  87020. */
  87021. FLAC_API FLAC__StreamDecoderInitStatus FLAC__stream_decoder_init_ogg_file(
  87022. FLAC__StreamDecoder *decoder,
  87023. const char *filename,
  87024. FLAC__StreamDecoderWriteCallback write_callback,
  87025. FLAC__StreamDecoderMetadataCallback metadata_callback,
  87026. FLAC__StreamDecoderErrorCallback error_callback,
  87027. void *client_data
  87028. );
  87029. /** Finish the decoding process.
  87030. * Flushes the decoding buffer, releases resources, resets the decoder
  87031. * settings to their defaults, and returns the decoder state to
  87032. * FLAC__STREAM_DECODER_UNINITIALIZED.
  87033. *
  87034. * In the event of a prematurely-terminated decode, it is not strictly
  87035. * necessary to call this immediately before FLAC__stream_decoder_delete()
  87036. * but it is good practice to match every FLAC__stream_decoder_init_*()
  87037. * with a FLAC__stream_decoder_finish().
  87038. *
  87039. * \param decoder An uninitialized decoder instance.
  87040. * \assert
  87041. * \code decoder != NULL \endcode
  87042. * \retval FLAC__bool
  87043. * \c false if MD5 checking is on AND a STREAMINFO block was available
  87044. * AND the MD5 signature in the STREAMINFO block was non-zero AND the
  87045. * signature does not match the one computed by the decoder; else
  87046. * \c true.
  87047. */
  87048. FLAC_API FLAC__bool FLAC__stream_decoder_finish(FLAC__StreamDecoder *decoder);
  87049. /** Flush the stream input.
  87050. * The decoder's input buffer will be cleared and the state set to
  87051. * \c FLAC__STREAM_DECODER_SEARCH_FOR_FRAME_SYNC. This will also turn
  87052. * off MD5 checking.
  87053. *
  87054. * \param decoder A decoder instance.
  87055. * \assert
  87056. * \code decoder != NULL \endcode
  87057. * \retval FLAC__bool
  87058. * \c true if successful, else \c false if a memory allocation
  87059. * error occurs (in which case the state will be set to
  87060. * \c FLAC__STREAM_DECODER_MEMORY_ALLOCATION_ERROR).
  87061. */
  87062. FLAC_API FLAC__bool FLAC__stream_decoder_flush(FLAC__StreamDecoder *decoder);
  87063. /** Reset the decoding process.
  87064. * The decoder's input buffer will be cleared and the state set to
  87065. * \c FLAC__STREAM_DECODER_SEARCH_FOR_METADATA. This is similar to
  87066. * FLAC__stream_decoder_finish() except that the settings are
  87067. * preserved; there is no need to call FLAC__stream_decoder_init_*()
  87068. * before decoding again. MD5 checking will be restored to its original
  87069. * setting.
  87070. *
  87071. * If the decoder is seekable, or was initialized with
  87072. * FLAC__stream_decoder_init*_FILE() or FLAC__stream_decoder_init*_file(),
  87073. * the decoder will also attempt to seek to the beginning of the file.
  87074. * If this rewind fails, this function will return \c false. It follows
  87075. * that FLAC__stream_decoder_reset() cannot be used when decoding from
  87076. * \c stdin.
  87077. *
  87078. * If the decoder was initialized with FLAC__stream_encoder_init*_stream()
  87079. * and is not seekable (i.e. no seek callback was provided or the seek
  87080. * callback returns \c FLAC__STREAM_DECODER_SEEK_STATUS_UNSUPPORTED), it
  87081. * is the duty of the client to start feeding data from the beginning of
  87082. * the stream on the next FLAC__stream_decoder_process() or
  87083. * FLAC__stream_decoder_process_interleaved() call.
  87084. *
  87085. * \param decoder A decoder instance.
  87086. * \assert
  87087. * \code decoder != NULL \endcode
  87088. * \retval FLAC__bool
  87089. * \c true if successful, else \c false if a memory allocation occurs
  87090. * (in which case the state will be set to
  87091. * \c FLAC__STREAM_DECODER_MEMORY_ALLOCATION_ERROR) or a seek error
  87092. * occurs (the state will be unchanged).
  87093. */
  87094. FLAC_API FLAC__bool FLAC__stream_decoder_reset(FLAC__StreamDecoder *decoder);
  87095. /** Decode one metadata block or audio frame.
  87096. * This version instructs the decoder to decode a either a single metadata
  87097. * block or a single frame and stop, unless the callbacks return a fatal
  87098. * error or the read callback returns
  87099. * \c FLAC__STREAM_DECODER_READ_STATUS_END_OF_STREAM.
  87100. *
  87101. * As the decoder needs more input it will call the read callback.
  87102. * Depending on what was decoded, the metadata or write callback will be
  87103. * called with the decoded metadata block or audio frame.
  87104. *
  87105. * Unless there is a fatal read error or end of stream, this function
  87106. * will return once one whole frame is decoded. In other words, if the
  87107. * stream is not synchronized or points to a corrupt frame header, the
  87108. * decoder will continue to try and resync until it gets to a valid
  87109. * frame, then decode one frame, then return. If the decoder points to
  87110. * a frame whose frame CRC in the frame footer does not match the
  87111. * computed frame CRC, this function will issue a
  87112. * FLAC__STREAM_DECODER_ERROR_STATUS_FRAME_CRC_MISMATCH error to the
  87113. * error callback, and return, having decoded one complete, although
  87114. * corrupt, frame. (Such corrupted frames are sent as silence of the
  87115. * correct length to the write callback.)
  87116. *
  87117. * \param decoder An initialized decoder instance.
  87118. * \assert
  87119. * \code decoder != NULL \endcode
  87120. * \retval FLAC__bool
  87121. * \c false if any fatal read, write, or memory allocation error
  87122. * occurred (meaning decoding must stop), else \c true; for more
  87123. * information about the decoder, check the decoder state with
  87124. * FLAC__stream_decoder_get_state().
  87125. */
  87126. FLAC_API FLAC__bool FLAC__stream_decoder_process_single(FLAC__StreamDecoder *decoder);
  87127. /** Decode until the end of the metadata.
  87128. * This version instructs the decoder to decode from the current position
  87129. * and continue until all the metadata has been read, or until the
  87130. * callbacks return a fatal error or the read callback returns
  87131. * \c FLAC__STREAM_DECODER_READ_STATUS_END_OF_STREAM.
  87132. *
  87133. * As the decoder needs more input it will call the read callback.
  87134. * As each metadata block is decoded, the metadata callback will be called
  87135. * with the decoded metadata.
  87136. *
  87137. * \param decoder An initialized decoder instance.
  87138. * \assert
  87139. * \code decoder != NULL \endcode
  87140. * \retval FLAC__bool
  87141. * \c false if any fatal read, write, or memory allocation error
  87142. * occurred (meaning decoding must stop), else \c true; for more
  87143. * information about the decoder, check the decoder state with
  87144. * FLAC__stream_decoder_get_state().
  87145. */
  87146. FLAC_API FLAC__bool FLAC__stream_decoder_process_until_end_of_metadata(FLAC__StreamDecoder *decoder);
  87147. /** Decode until the end of the stream.
  87148. * This version instructs the decoder to decode from the current position
  87149. * and continue until the end of stream (the read callback returns
  87150. * \c FLAC__STREAM_DECODER_READ_STATUS_END_OF_STREAM), or until the
  87151. * callbacks return a fatal error.
  87152. *
  87153. * As the decoder needs more input it will call the read callback.
  87154. * As each metadata block and frame is decoded, the metadata or write
  87155. * callback will be called with the decoded metadata or frame.
  87156. *
  87157. * \param decoder An initialized decoder instance.
  87158. * \assert
  87159. * \code decoder != NULL \endcode
  87160. * \retval FLAC__bool
  87161. * \c false if any fatal read, write, or memory allocation error
  87162. * occurred (meaning decoding must stop), else \c true; for more
  87163. * information about the decoder, check the decoder state with
  87164. * FLAC__stream_decoder_get_state().
  87165. */
  87166. FLAC_API FLAC__bool FLAC__stream_decoder_process_until_end_of_stream(FLAC__StreamDecoder *decoder);
  87167. /** Skip one audio frame.
  87168. * This version instructs the decoder to 'skip' a single frame and stop,
  87169. * unless the callbacks return a fatal error or the read callback returns
  87170. * \c FLAC__STREAM_DECODER_READ_STATUS_END_OF_STREAM.
  87171. *
  87172. * The decoding flow is the same as what occurs when
  87173. * FLAC__stream_decoder_process_single() is called to process an audio
  87174. * frame, except that this function does not decode the parsed data into
  87175. * PCM or call the write callback. The integrity of the frame is still
  87176. * checked the same way as in the other process functions.
  87177. *
  87178. * This function will return once one whole frame is skipped, in the
  87179. * same way that FLAC__stream_decoder_process_single() will return once
  87180. * one whole frame is decoded.
  87181. *
  87182. * This function can be used in more quickly determining FLAC frame
  87183. * boundaries when decoding of the actual data is not needed, for
  87184. * example when an application is separating a FLAC stream into frames
  87185. * for editing or storing in a container. To do this, the application
  87186. * can use FLAC__stream_decoder_skip_single_frame() to quickly advance
  87187. * to the next frame, then use
  87188. * FLAC__stream_decoder_get_decode_position() to find the new frame
  87189. * boundary.
  87190. *
  87191. * This function should only be called when the stream has advanced
  87192. * past all the metadata, otherwise it will return \c false.
  87193. *
  87194. * \param decoder An initialized decoder instance not in a metadata
  87195. * state.
  87196. * \assert
  87197. * \code decoder != NULL \endcode
  87198. * \retval FLAC__bool
  87199. * \c false if any fatal read, write, or memory allocation error
  87200. * occurred (meaning decoding must stop), or if the decoder
  87201. * is in the FLAC__STREAM_DECODER_SEARCH_FOR_METADATA or
  87202. * FLAC__STREAM_DECODER_READ_METADATA state, else \c true; for more
  87203. * information about the decoder, check the decoder state with
  87204. * FLAC__stream_decoder_get_state().
  87205. */
  87206. FLAC_API FLAC__bool FLAC__stream_decoder_skip_single_frame(FLAC__StreamDecoder *decoder);
  87207. /** Flush the input and seek to an absolute sample.
  87208. * Decoding will resume at the given sample. Note that because of
  87209. * this, the next write callback may contain a partial block. The
  87210. * client must support seeking the input or this function will fail
  87211. * and return \c false. Furthermore, if the decoder state is
  87212. * \c FLAC__STREAM_DECODER_SEEK_ERROR, then the decoder must be flushed
  87213. * with FLAC__stream_decoder_flush() or reset with
  87214. * FLAC__stream_decoder_reset() before decoding can continue.
  87215. *
  87216. * \param decoder A decoder instance.
  87217. * \param sample The target sample number to seek to.
  87218. * \assert
  87219. * \code decoder != NULL \endcode
  87220. * \retval FLAC__bool
  87221. * \c true if successful, else \c false.
  87222. */
  87223. FLAC_API FLAC__bool FLAC__stream_decoder_seek_absolute(FLAC__StreamDecoder *decoder, FLAC__uint64 sample);
  87224. /* \} */
  87225. #ifdef __cplusplus
  87226. }
  87227. #endif
  87228. #endif
  87229. /*** End of inlined file: stream_decoder.h ***/
  87230. /*** Start of inlined file: stream_encoder.h ***/
  87231. #ifndef FLAC__STREAM_ENCODER_H
  87232. #define FLAC__STREAM_ENCODER_H
  87233. #include <stdio.h> /* for FILE */
  87234. #ifdef __cplusplus
  87235. extern "C" {
  87236. #endif
  87237. /** \file include/FLAC/stream_encoder.h
  87238. *
  87239. * \brief
  87240. * This module contains the functions which implement the stream
  87241. * encoder.
  87242. *
  87243. * See the detailed documentation in the
  87244. * \link flac_stream_encoder stream encoder \endlink module.
  87245. */
  87246. /** \defgroup flac_encoder FLAC/ \*_encoder.h: encoder interfaces
  87247. * \ingroup flac
  87248. *
  87249. * \brief
  87250. * This module describes the encoder layers provided by libFLAC.
  87251. *
  87252. * The stream encoder can be used to encode complete streams either to the
  87253. * client via callbacks, or directly to a file, depending on how it is
  87254. * initialized. When encoding via callbacks, the client provides a write
  87255. * callback which will be called whenever FLAC data is ready to be written.
  87256. * If the client also supplies a seek callback, the encoder will also
  87257. * automatically handle the writing back of metadata discovered while
  87258. * encoding, like stream info, seek points offsets, etc. When encoding to
  87259. * a file, the client needs only supply a filename or open \c FILE* and an
  87260. * optional progress callback for periodic notification of progress; the
  87261. * write and seek callbacks are supplied internally. For more info see the
  87262. * \link flac_stream_encoder stream encoder \endlink module.
  87263. */
  87264. /** \defgroup flac_stream_encoder FLAC/stream_encoder.h: stream encoder interface
  87265. * \ingroup flac_encoder
  87266. *
  87267. * \brief
  87268. * This module contains the functions which implement the stream
  87269. * encoder.
  87270. *
  87271. * The stream encoder can encode to native FLAC, and optionally Ogg FLAC
  87272. * (check FLAC_API_SUPPORTS_OGG_FLAC) streams and files.
  87273. *
  87274. * The basic usage of this encoder is as follows:
  87275. * - The program creates an instance of an encoder using
  87276. * FLAC__stream_encoder_new().
  87277. * - The program overrides the default settings using
  87278. * FLAC__stream_encoder_set_*() functions. At a minimum, the following
  87279. * functions should be called:
  87280. * - FLAC__stream_encoder_set_channels()
  87281. * - FLAC__stream_encoder_set_bits_per_sample()
  87282. * - FLAC__stream_encoder_set_sample_rate()
  87283. * - FLAC__stream_encoder_set_ogg_serial_number() (if encoding to Ogg FLAC)
  87284. * - FLAC__stream_encoder_set_total_samples_estimate() (if known)
  87285. * - If the application wants to control the compression level or set its own
  87286. * metadata, then the following should also be called:
  87287. * - FLAC__stream_encoder_set_compression_level()
  87288. * - FLAC__stream_encoder_set_verify()
  87289. * - FLAC__stream_encoder_set_metadata()
  87290. * - The rest of the set functions should only be called if the client needs
  87291. * exact control over how the audio is compressed; thorough understanding
  87292. * of the FLAC format is necessary to achieve good results.
  87293. * - The program initializes the instance to validate the settings and
  87294. * prepare for encoding using
  87295. * - FLAC__stream_encoder_init_stream() or FLAC__stream_encoder_init_FILE()
  87296. * or FLAC__stream_encoder_init_file() for native FLAC
  87297. * - FLAC__stream_encoder_init_ogg_stream() or FLAC__stream_encoder_init_ogg_FILE()
  87298. * or FLAC__stream_encoder_init_ogg_file() for Ogg FLAC
  87299. * - The program calls FLAC__stream_encoder_process() or
  87300. * FLAC__stream_encoder_process_interleaved() to encode data, which
  87301. * subsequently calls the callbacks when there is encoder data ready
  87302. * to be written.
  87303. * - The program finishes the encoding with FLAC__stream_encoder_finish(),
  87304. * which causes the encoder to encode any data still in its input pipe,
  87305. * update the metadata with the final encoding statistics if output
  87306. * seeking is possible, and finally reset the encoder to the
  87307. * uninitialized state.
  87308. * - The instance may be used again or deleted with
  87309. * FLAC__stream_encoder_delete().
  87310. *
  87311. * In more detail, the stream encoder functions similarly to the
  87312. * \link flac_stream_decoder stream decoder \endlink, but has fewer
  87313. * callbacks and more options. Typically the client will create a new
  87314. * instance by calling FLAC__stream_encoder_new(), then set the necessary
  87315. * parameters with FLAC__stream_encoder_set_*(), and initialize it by
  87316. * calling one of the FLAC__stream_encoder_init_*() functions.
  87317. *
  87318. * Unlike the decoders, the stream encoder has many options that can
  87319. * affect the speed and compression ratio. When setting these parameters
  87320. * you should have some basic knowledge of the format (see the
  87321. * <A HREF="../documentation.html#format">user-level documentation</A>
  87322. * or the <A HREF="../format.html">formal description</A>). The
  87323. * FLAC__stream_encoder_set_*() functions themselves do not validate the
  87324. * values as many are interdependent. The FLAC__stream_encoder_init_*()
  87325. * functions will do this, so make sure to pay attention to the state
  87326. * returned by FLAC__stream_encoder_init_*() to make sure that it is
  87327. * FLAC__STREAM_ENCODER_INIT_STATUS_OK. Any parameters that are not set
  87328. * before FLAC__stream_encoder_init_*() will take on the defaults from
  87329. * the constructor.
  87330. *
  87331. * There are three initialization functions for native FLAC, one for
  87332. * setting up the encoder to encode FLAC data to the client via
  87333. * callbacks, and two for encoding directly to a file.
  87334. *
  87335. * For encoding via callbacks, use FLAC__stream_encoder_init_stream().
  87336. * You must also supply a write callback which will be called anytime
  87337. * there is raw encoded data to write. If the client can seek the output
  87338. * it is best to also supply seek and tell callbacks, as this allows the
  87339. * encoder to go back after encoding is finished to write back
  87340. * information that was collected while encoding, like seek point offsets,
  87341. * frame sizes, etc.
  87342. *
  87343. * For encoding directly to a file, use FLAC__stream_encoder_init_FILE()
  87344. * or FLAC__stream_encoder_init_file(). Then you must only supply a
  87345. * filename or open \c FILE*; the encoder will handle all the callbacks
  87346. * internally. You may also supply a progress callback for periodic
  87347. * notification of the encoding progress.
  87348. *
  87349. * There are three similarly-named init functions for encoding to Ogg
  87350. * FLAC streams. Check \c FLAC_API_SUPPORTS_OGG_FLAC to find out if the
  87351. * library has been built with Ogg support.
  87352. *
  87353. * The call to FLAC__stream_encoder_init_*() currently will also immediately
  87354. * call the write callback several times, once with the \c fLaC signature,
  87355. * and once for each encoded metadata block. Note that for Ogg FLAC
  87356. * encoding you will usually get at least twice the number of callbacks than
  87357. * with native FLAC, one for the Ogg page header and one for the page body.
  87358. *
  87359. * After initializing the instance, the client may feed audio data to the
  87360. * encoder in one of two ways:
  87361. *
  87362. * - Channel separate, through FLAC__stream_encoder_process() - The client
  87363. * will pass an array of pointers to buffers, one for each channel, to
  87364. * the encoder, each of the same length. The samples need not be
  87365. * block-aligned, but each channel should have the same number of samples.
  87366. * - Channel interleaved, through
  87367. * FLAC__stream_encoder_process_interleaved() - The client will pass a single
  87368. * pointer to data that is channel-interleaved (i.e. channel0_sample0,
  87369. * channel1_sample0, ... , channelN_sample0, channel0_sample1, ...).
  87370. * Again, the samples need not be block-aligned but they must be
  87371. * sample-aligned, i.e. the first value should be channel0_sample0 and
  87372. * the last value channelN_sampleM.
  87373. *
  87374. * Note that for either process call, each sample in the buffers should be a
  87375. * signed integer, right-justified to the resolution set by
  87376. * FLAC__stream_encoder_set_bits_per_sample(). For example, if the resolution
  87377. * is 16 bits per sample, the samples should all be in the range [-32768,32767].
  87378. *
  87379. * When the client is finished encoding data, it calls
  87380. * FLAC__stream_encoder_finish(), which causes the encoder to encode any
  87381. * data still in its input pipe, and call the metadata callback with the
  87382. * final encoding statistics. Then the instance may be deleted with
  87383. * FLAC__stream_encoder_delete() or initialized again to encode another
  87384. * stream.
  87385. *
  87386. * For programs that write their own metadata, but that do not know the
  87387. * actual metadata until after encoding, it is advantageous to instruct
  87388. * the encoder to write a PADDING block of the correct size, so that
  87389. * instead of rewriting the whole stream after encoding, the program can
  87390. * just overwrite the PADDING block. If only the maximum size of the
  87391. * metadata is known, the program can write a slightly larger padding
  87392. * block, then split it after encoding.
  87393. *
  87394. * Make sure you understand how lengths are calculated. All FLAC metadata
  87395. * blocks have a 4 byte header which contains the type and length. This
  87396. * length does not include the 4 bytes of the header. See the format page
  87397. * for the specification of metadata blocks and their lengths.
  87398. *
  87399. * \note
  87400. * If you are writing the FLAC data to a file via callbacks, make sure it
  87401. * is open for update (e.g. mode "w+" for stdio streams). This is because
  87402. * after the first encoding pass, the encoder will try to seek back to the
  87403. * beginning of the stream, to the STREAMINFO block, to write some data
  87404. * there. (If using FLAC__stream_encoder_init*_file() or
  87405. * FLAC__stream_encoder_init*_FILE(), the file is managed internally.)
  87406. *
  87407. * \note
  87408. * The "set" functions may only be called when the encoder is in the
  87409. * state FLAC__STREAM_ENCODER_UNINITIALIZED, i.e. after
  87410. * FLAC__stream_encoder_new() or FLAC__stream_encoder_finish(), but
  87411. * before FLAC__stream_encoder_init_*(). If this is the case they will
  87412. * return \c true, otherwise \c false.
  87413. *
  87414. * \note
  87415. * FLAC__stream_encoder_finish() resets all settings to the constructor
  87416. * defaults.
  87417. *
  87418. * \{
  87419. */
  87420. /** State values for a FLAC__StreamEncoder.
  87421. *
  87422. * The encoder's state can be obtained by calling FLAC__stream_encoder_get_state().
  87423. *
  87424. * If the encoder gets into any other state besides \c FLAC__STREAM_ENCODER_OK
  87425. * or \c FLAC__STREAM_ENCODER_UNINITIALIZED, it becomes invalid for encoding and
  87426. * must be deleted with FLAC__stream_encoder_delete().
  87427. */
  87428. typedef enum {
  87429. FLAC__STREAM_ENCODER_OK = 0,
  87430. /**< The encoder is in the normal OK state and samples can be processed. */
  87431. FLAC__STREAM_ENCODER_UNINITIALIZED,
  87432. /**< The encoder is in the uninitialized state; one of the
  87433. * FLAC__stream_encoder_init_*() functions must be called before samples
  87434. * can be processed.
  87435. */
  87436. FLAC__STREAM_ENCODER_OGG_ERROR,
  87437. /**< An error occurred in the underlying Ogg layer. */
  87438. FLAC__STREAM_ENCODER_VERIFY_DECODER_ERROR,
  87439. /**< An error occurred in the underlying verify stream decoder;
  87440. * check FLAC__stream_encoder_get_verify_decoder_state().
  87441. */
  87442. FLAC__STREAM_ENCODER_VERIFY_MISMATCH_IN_AUDIO_DATA,
  87443. /**< The verify decoder detected a mismatch between the original
  87444. * audio signal and the decoded audio signal.
  87445. */
  87446. FLAC__STREAM_ENCODER_CLIENT_ERROR,
  87447. /**< One of the callbacks returned a fatal error. */
  87448. FLAC__STREAM_ENCODER_IO_ERROR,
  87449. /**< An I/O error occurred while opening/reading/writing a file.
  87450. * Check \c errno.
  87451. */
  87452. FLAC__STREAM_ENCODER_FRAMING_ERROR,
  87453. /**< An error occurred while writing the stream; usually, the
  87454. * write_callback returned an error.
  87455. */
  87456. FLAC__STREAM_ENCODER_MEMORY_ALLOCATION_ERROR
  87457. /**< Memory allocation failed. */
  87458. } FLAC__StreamEncoderState;
  87459. /** Maps a FLAC__StreamEncoderState to a C string.
  87460. *
  87461. * Using a FLAC__StreamEncoderState as the index to this array
  87462. * will give the string equivalent. The contents should not be modified.
  87463. */
  87464. extern FLAC_API const char * const FLAC__StreamEncoderStateString[];
  87465. /** Possible return values for the FLAC__stream_encoder_init_*() functions.
  87466. */
  87467. typedef enum {
  87468. FLAC__STREAM_ENCODER_INIT_STATUS_OK = 0,
  87469. /**< Initialization was successful. */
  87470. FLAC__STREAM_ENCODER_INIT_STATUS_ENCODER_ERROR,
  87471. /**< General failure to set up encoder; call FLAC__stream_encoder_get_state() for cause. */
  87472. FLAC__STREAM_ENCODER_INIT_STATUS_UNSUPPORTED_CONTAINER,
  87473. /**< The library was not compiled with support for the given container
  87474. * format.
  87475. */
  87476. FLAC__STREAM_ENCODER_INIT_STATUS_INVALID_CALLBACKS,
  87477. /**< A required callback was not supplied. */
  87478. FLAC__STREAM_ENCODER_INIT_STATUS_INVALID_NUMBER_OF_CHANNELS,
  87479. /**< The encoder has an invalid setting for number of channels. */
  87480. FLAC__STREAM_ENCODER_INIT_STATUS_INVALID_BITS_PER_SAMPLE,
  87481. /**< The encoder has an invalid setting for bits-per-sample.
  87482. * FLAC supports 4-32 bps but the reference encoder currently supports
  87483. * only up to 24 bps.
  87484. */
  87485. FLAC__STREAM_ENCODER_INIT_STATUS_INVALID_SAMPLE_RATE,
  87486. /**< The encoder has an invalid setting for the input sample rate. */
  87487. FLAC__STREAM_ENCODER_INIT_STATUS_INVALID_BLOCK_SIZE,
  87488. /**< The encoder has an invalid setting for the block size. */
  87489. FLAC__STREAM_ENCODER_INIT_STATUS_INVALID_MAX_LPC_ORDER,
  87490. /**< The encoder has an invalid setting for the maximum LPC order. */
  87491. FLAC__STREAM_ENCODER_INIT_STATUS_INVALID_QLP_COEFF_PRECISION,
  87492. /**< The encoder has an invalid setting for the precision of the quantized linear predictor coefficients. */
  87493. FLAC__STREAM_ENCODER_INIT_STATUS_BLOCK_SIZE_TOO_SMALL_FOR_LPC_ORDER,
  87494. /**< The specified block size is less than the maximum LPC order. */
  87495. FLAC__STREAM_ENCODER_INIT_STATUS_NOT_STREAMABLE,
  87496. /**< The encoder is bound to the <A HREF="../format.html#subset">Subset</A> but other settings violate it. */
  87497. FLAC__STREAM_ENCODER_INIT_STATUS_INVALID_METADATA,
  87498. /**< The metadata input to the encoder is invalid, in one of the following ways:
  87499. * - FLAC__stream_encoder_set_metadata() was called with a null pointer but a block count > 0
  87500. * - One of the metadata blocks contains an undefined type
  87501. * - It contains an illegal CUESHEET as checked by FLAC__format_cuesheet_is_legal()
  87502. * - It contains an illegal SEEKTABLE as checked by FLAC__format_seektable_is_legal()
  87503. * - It contains more than one SEEKTABLE block or more than one VORBIS_COMMENT block
  87504. */
  87505. FLAC__STREAM_ENCODER_INIT_STATUS_ALREADY_INITIALIZED
  87506. /**< FLAC__stream_encoder_init_*() was called when the encoder was
  87507. * already initialized, usually because
  87508. * FLAC__stream_encoder_finish() was not called.
  87509. */
  87510. } FLAC__StreamEncoderInitStatus;
  87511. /** Maps a FLAC__StreamEncoderInitStatus to a C string.
  87512. *
  87513. * Using a FLAC__StreamEncoderInitStatus as the index to this array
  87514. * will give the string equivalent. The contents should not be modified.
  87515. */
  87516. extern FLAC_API const char * const FLAC__StreamEncoderInitStatusString[];
  87517. /** Return values for the FLAC__StreamEncoder read callback.
  87518. */
  87519. typedef enum {
  87520. FLAC__STREAM_ENCODER_READ_STATUS_CONTINUE,
  87521. /**< The read was OK and decoding can continue. */
  87522. FLAC__STREAM_ENCODER_READ_STATUS_END_OF_STREAM,
  87523. /**< The read was attempted at the end of the stream. */
  87524. FLAC__STREAM_ENCODER_READ_STATUS_ABORT,
  87525. /**< An unrecoverable error occurred. */
  87526. FLAC__STREAM_ENCODER_READ_STATUS_UNSUPPORTED
  87527. /**< Client does not support reading back from the output. */
  87528. } FLAC__StreamEncoderReadStatus;
  87529. /** Maps a FLAC__StreamEncoderReadStatus to a C string.
  87530. *
  87531. * Using a FLAC__StreamEncoderReadStatus as the index to this array
  87532. * will give the string equivalent. The contents should not be modified.
  87533. */
  87534. extern FLAC_API const char * const FLAC__StreamEncoderReadStatusString[];
  87535. /** Return values for the FLAC__StreamEncoder write callback.
  87536. */
  87537. typedef enum {
  87538. FLAC__STREAM_ENCODER_WRITE_STATUS_OK = 0,
  87539. /**< The write was OK and encoding can continue. */
  87540. FLAC__STREAM_ENCODER_WRITE_STATUS_FATAL_ERROR
  87541. /**< An unrecoverable error occurred. The encoder will return from the process call. */
  87542. } FLAC__StreamEncoderWriteStatus;
  87543. /** Maps a FLAC__StreamEncoderWriteStatus to a C string.
  87544. *
  87545. * Using a FLAC__StreamEncoderWriteStatus as the index to this array
  87546. * will give the string equivalent. The contents should not be modified.
  87547. */
  87548. extern FLAC_API const char * const FLAC__StreamEncoderWriteStatusString[];
  87549. /** Return values for the FLAC__StreamEncoder seek callback.
  87550. */
  87551. typedef enum {
  87552. FLAC__STREAM_ENCODER_SEEK_STATUS_OK,
  87553. /**< The seek was OK and encoding can continue. */
  87554. FLAC__STREAM_ENCODER_SEEK_STATUS_ERROR,
  87555. /**< An unrecoverable error occurred. */
  87556. FLAC__STREAM_ENCODER_SEEK_STATUS_UNSUPPORTED
  87557. /**< Client does not support seeking. */
  87558. } FLAC__StreamEncoderSeekStatus;
  87559. /** Maps a FLAC__StreamEncoderSeekStatus to a C string.
  87560. *
  87561. * Using a FLAC__StreamEncoderSeekStatus as the index to this array
  87562. * will give the string equivalent. The contents should not be modified.
  87563. */
  87564. extern FLAC_API const char * const FLAC__StreamEncoderSeekStatusString[];
  87565. /** Return values for the FLAC__StreamEncoder tell callback.
  87566. */
  87567. typedef enum {
  87568. FLAC__STREAM_ENCODER_TELL_STATUS_OK,
  87569. /**< The tell was OK and encoding can continue. */
  87570. FLAC__STREAM_ENCODER_TELL_STATUS_ERROR,
  87571. /**< An unrecoverable error occurred. */
  87572. FLAC__STREAM_ENCODER_TELL_STATUS_UNSUPPORTED
  87573. /**< Client does not support seeking. */
  87574. } FLAC__StreamEncoderTellStatus;
  87575. /** Maps a FLAC__StreamEncoderTellStatus to a C string.
  87576. *
  87577. * Using a FLAC__StreamEncoderTellStatus as the index to this array
  87578. * will give the string equivalent. The contents should not be modified.
  87579. */
  87580. extern FLAC_API const char * const FLAC__StreamEncoderTellStatusString[];
  87581. /***********************************************************************
  87582. *
  87583. * class FLAC__StreamEncoder
  87584. *
  87585. ***********************************************************************/
  87586. struct FLAC__StreamEncoderProtected;
  87587. struct FLAC__StreamEncoderPrivate;
  87588. /** The opaque structure definition for the stream encoder type.
  87589. * See the \link flac_stream_encoder stream encoder module \endlink
  87590. * for a detailed description.
  87591. */
  87592. typedef struct {
  87593. struct FLAC__StreamEncoderProtected *protected_; /* avoid the C++ keyword 'protected' */
  87594. struct FLAC__StreamEncoderPrivate *private_; /* avoid the C++ keyword 'private' */
  87595. } FLAC__StreamEncoder;
  87596. /** Signature for the read callback.
  87597. *
  87598. * A function pointer matching this signature must be passed to
  87599. * FLAC__stream_encoder_init_ogg_stream() if seeking is supported.
  87600. * The supplied function will be called when the encoder needs to read back
  87601. * encoded data. This happens during the metadata callback, when the encoder
  87602. * has to read, modify, and rewrite the metadata (e.g. seekpoints) gathered
  87603. * while encoding. The address of the buffer to be filled is supplied, along
  87604. * with the number of bytes the buffer can hold. The callback may choose to
  87605. * supply less data and modify the byte count but must be careful not to
  87606. * overflow the buffer. The callback then returns a status code chosen from
  87607. * FLAC__StreamEncoderReadStatus.
  87608. *
  87609. * Here is an example of a read callback for stdio streams:
  87610. * \code
  87611. * FLAC__StreamEncoderReadStatus read_cb(const FLAC__StreamEncoder *encoder, FLAC__byte buffer[], size_t *bytes, void *client_data)
  87612. * {
  87613. * FILE *file = ((MyClientData*)client_data)->file;
  87614. * if(*bytes > 0) {
  87615. * *bytes = fread(buffer, sizeof(FLAC__byte), *bytes, file);
  87616. * if(ferror(file))
  87617. * return FLAC__STREAM_ENCODER_READ_STATUS_ABORT;
  87618. * else if(*bytes == 0)
  87619. * return FLAC__STREAM_ENCODER_READ_STATUS_END_OF_STREAM;
  87620. * else
  87621. * return FLAC__STREAM_ENCODER_READ_STATUS_CONTINUE;
  87622. * }
  87623. * else
  87624. * return FLAC__STREAM_ENCODER_READ_STATUS_ABORT;
  87625. * }
  87626. * \endcode
  87627. *
  87628. * \note In general, FLAC__StreamEncoder functions which change the
  87629. * state should not be called on the \a encoder while in the callback.
  87630. *
  87631. * \param encoder The encoder instance calling the callback.
  87632. * \param buffer A pointer to a location for the callee to store
  87633. * data to be encoded.
  87634. * \param bytes A pointer to the size of the buffer. On entry
  87635. * to the callback, it contains the maximum number
  87636. * of bytes that may be stored in \a buffer. The
  87637. * callee must set it to the actual number of bytes
  87638. * stored (0 in case of error or end-of-stream) before
  87639. * returning.
  87640. * \param client_data The callee's client data set through
  87641. * FLAC__stream_encoder_set_client_data().
  87642. * \retval FLAC__StreamEncoderReadStatus
  87643. * The callee's return status.
  87644. */
  87645. typedef FLAC__StreamEncoderReadStatus (*FLAC__StreamEncoderReadCallback)(const FLAC__StreamEncoder *encoder, FLAC__byte buffer[], size_t *bytes, void *client_data);
  87646. /** Signature for the write callback.
  87647. *
  87648. * A function pointer matching this signature must be passed to
  87649. * FLAC__stream_encoder_init*_stream(). The supplied function will be called
  87650. * by the encoder anytime there is raw encoded data ready to write. It may
  87651. * include metadata mixed with encoded audio frames and the data is not
  87652. * guaranteed to be aligned on frame or metadata block boundaries.
  87653. *
  87654. * The only duty of the callback is to write out the \a bytes worth of data
  87655. * in \a buffer to the current position in the output stream. The arguments
  87656. * \a samples and \a current_frame are purely informational. If \a samples
  87657. * is greater than \c 0, then \a current_frame will hold the current frame
  87658. * number that is being written; otherwise it indicates that the write
  87659. * callback is being called to write metadata.
  87660. *
  87661. * \note
  87662. * Unlike when writing to native FLAC, when writing to Ogg FLAC the
  87663. * write callback will be called twice when writing each audio
  87664. * frame; once for the page header, and once for the page body.
  87665. * When writing the page header, the \a samples argument to the
  87666. * write callback will be \c 0.
  87667. *
  87668. * \note In general, FLAC__StreamEncoder functions which change the
  87669. * state should not be called on the \a encoder while in the callback.
  87670. *
  87671. * \param encoder The encoder instance calling the callback.
  87672. * \param buffer An array of encoded data of length \a bytes.
  87673. * \param bytes The byte length of \a buffer.
  87674. * \param samples The number of samples encoded by \a buffer.
  87675. * \c 0 has a special meaning; see above.
  87676. * \param current_frame The number of the current frame being encoded.
  87677. * \param client_data The callee's client data set through
  87678. * FLAC__stream_encoder_init_*().
  87679. * \retval FLAC__StreamEncoderWriteStatus
  87680. * The callee's return status.
  87681. */
  87682. typedef FLAC__StreamEncoderWriteStatus (*FLAC__StreamEncoderWriteCallback)(const FLAC__StreamEncoder *encoder, const FLAC__byte buffer[], size_t bytes, unsigned samples, unsigned current_frame, void *client_data);
  87683. /** Signature for the seek callback.
  87684. *
  87685. * A function pointer matching this signature may be passed to
  87686. * FLAC__stream_encoder_init*_stream(). The supplied function will be called
  87687. * when the encoder needs to seek the output stream. The encoder will pass
  87688. * the absolute byte offset to seek to, 0 meaning the beginning of the stream.
  87689. *
  87690. * Here is an example of a seek callback for stdio streams:
  87691. * \code
  87692. * FLAC__StreamEncoderSeekStatus seek_cb(const FLAC__StreamEncoder *encoder, FLAC__uint64 absolute_byte_offset, void *client_data)
  87693. * {
  87694. * FILE *file = ((MyClientData*)client_data)->file;
  87695. * if(file == stdin)
  87696. * return FLAC__STREAM_ENCODER_SEEK_STATUS_UNSUPPORTED;
  87697. * else if(fseeko(file, (off_t)absolute_byte_offset, SEEK_SET) < 0)
  87698. * return FLAC__STREAM_ENCODER_SEEK_STATUS_ERROR;
  87699. * else
  87700. * return FLAC__STREAM_ENCODER_SEEK_STATUS_OK;
  87701. * }
  87702. * \endcode
  87703. *
  87704. * \note In general, FLAC__StreamEncoder functions which change the
  87705. * state should not be called on the \a encoder while in the callback.
  87706. *
  87707. * \param encoder The encoder instance calling the callback.
  87708. * \param absolute_byte_offset The offset from the beginning of the stream
  87709. * to seek to.
  87710. * \param client_data The callee's client data set through
  87711. * FLAC__stream_encoder_init_*().
  87712. * \retval FLAC__StreamEncoderSeekStatus
  87713. * The callee's return status.
  87714. */
  87715. typedef FLAC__StreamEncoderSeekStatus (*FLAC__StreamEncoderSeekCallback)(const FLAC__StreamEncoder *encoder, FLAC__uint64 absolute_byte_offset, void *client_data);
  87716. /** Signature for the tell callback.
  87717. *
  87718. * A function pointer matching this signature may be passed to
  87719. * FLAC__stream_encoder_init*_stream(). The supplied function will be called
  87720. * when the encoder needs to know the current position of the output stream.
  87721. *
  87722. * \warning
  87723. * The callback must return the true current byte offset of the output to
  87724. * which the encoder is writing. If you are buffering the output, make
  87725. * sure and take this into account. If you are writing directly to a
  87726. * FILE* from your write callback, ftell() is sufficient. If you are
  87727. * writing directly to a file descriptor from your write callback, you
  87728. * can use lseek(fd, SEEK_CUR, 0). The encoder may later seek back to
  87729. * these points to rewrite metadata after encoding.
  87730. *
  87731. * Here is an example of a tell callback for stdio streams:
  87732. * \code
  87733. * FLAC__StreamEncoderTellStatus tell_cb(const FLAC__StreamEncoder *encoder, FLAC__uint64 *absolute_byte_offset, void *client_data)
  87734. * {
  87735. * FILE *file = ((MyClientData*)client_data)->file;
  87736. * off_t pos;
  87737. * if(file == stdin)
  87738. * return FLAC__STREAM_ENCODER_TELL_STATUS_UNSUPPORTED;
  87739. * else if((pos = ftello(file)) < 0)
  87740. * return FLAC__STREAM_ENCODER_TELL_STATUS_ERROR;
  87741. * else {
  87742. * *absolute_byte_offset = (FLAC__uint64)pos;
  87743. * return FLAC__STREAM_ENCODER_TELL_STATUS_OK;
  87744. * }
  87745. * }
  87746. * \endcode
  87747. *
  87748. * \note In general, FLAC__StreamEncoder functions which change the
  87749. * state should not be called on the \a encoder while in the callback.
  87750. *
  87751. * \param encoder The encoder instance calling the callback.
  87752. * \param absolute_byte_offset The address at which to store the current
  87753. * position of the output.
  87754. * \param client_data The callee's client data set through
  87755. * FLAC__stream_encoder_init_*().
  87756. * \retval FLAC__StreamEncoderTellStatus
  87757. * The callee's return status.
  87758. */
  87759. typedef FLAC__StreamEncoderTellStatus (*FLAC__StreamEncoderTellCallback)(const FLAC__StreamEncoder *encoder, FLAC__uint64 *absolute_byte_offset, void *client_data);
  87760. /** Signature for the metadata callback.
  87761. *
  87762. * A function pointer matching this signature may be passed to
  87763. * FLAC__stream_encoder_init*_stream(). The supplied function will be called
  87764. * once at the end of encoding with the populated STREAMINFO structure. This
  87765. * is so the client can seek back to the beginning of the file and write the
  87766. * STREAMINFO block with the correct statistics after encoding (like
  87767. * minimum/maximum frame size and total samples).
  87768. *
  87769. * \note In general, FLAC__StreamEncoder functions which change the
  87770. * state should not be called on the \a encoder while in the callback.
  87771. *
  87772. * \param encoder The encoder instance calling the callback.
  87773. * \param metadata The final populated STREAMINFO block.
  87774. * \param client_data The callee's client data set through
  87775. * FLAC__stream_encoder_init_*().
  87776. */
  87777. typedef void (*FLAC__StreamEncoderMetadataCallback)(const FLAC__StreamEncoder *encoder, const FLAC__StreamMetadata *metadata, void *client_data);
  87778. /** Signature for the progress callback.
  87779. *
  87780. * A function pointer matching this signature may be passed to
  87781. * FLAC__stream_encoder_init*_file() or FLAC__stream_encoder_init*_FILE().
  87782. * The supplied function will be called when the encoder has finished
  87783. * writing a frame. The \c total_frames_estimate argument to the
  87784. * callback will be based on the value from
  87785. * FLAC__stream_encoder_set_total_samples_estimate().
  87786. *
  87787. * \note In general, FLAC__StreamEncoder functions which change the
  87788. * state should not be called on the \a encoder while in the callback.
  87789. *
  87790. * \param encoder The encoder instance calling the callback.
  87791. * \param bytes_written Bytes written so far.
  87792. * \param samples_written Samples written so far.
  87793. * \param frames_written Frames written so far.
  87794. * \param total_frames_estimate The estimate of the total number of
  87795. * frames to be written.
  87796. * \param client_data The callee's client data set through
  87797. * FLAC__stream_encoder_init_*().
  87798. */
  87799. 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);
  87800. /***********************************************************************
  87801. *
  87802. * Class constructor/destructor
  87803. *
  87804. ***********************************************************************/
  87805. /** Create a new stream encoder instance. The instance is created with
  87806. * default settings; see the individual FLAC__stream_encoder_set_*()
  87807. * functions for each setting's default.
  87808. *
  87809. * \retval FLAC__StreamEncoder*
  87810. * \c NULL if there was an error allocating memory, else the new instance.
  87811. */
  87812. FLAC_API FLAC__StreamEncoder *FLAC__stream_encoder_new(void);
  87813. /** Free an encoder instance. Deletes the object pointed to by \a encoder.
  87814. *
  87815. * \param encoder A pointer to an existing encoder.
  87816. * \assert
  87817. * \code encoder != NULL \endcode
  87818. */
  87819. FLAC_API void FLAC__stream_encoder_delete(FLAC__StreamEncoder *encoder);
  87820. /***********************************************************************
  87821. *
  87822. * Public class method prototypes
  87823. *
  87824. ***********************************************************************/
  87825. /** Set the serial number for the FLAC stream to use in the Ogg container.
  87826. *
  87827. * \note
  87828. * This does not need to be set for native FLAC encoding.
  87829. *
  87830. * \note
  87831. * It is recommended to set a serial number explicitly as the default of '0'
  87832. * may collide with other streams.
  87833. *
  87834. * \default \c 0
  87835. * \param encoder An encoder instance to set.
  87836. * \param serial_number See above.
  87837. * \assert
  87838. * \code encoder != NULL \endcode
  87839. * \retval FLAC__bool
  87840. * \c false if the encoder is already initialized, else \c true.
  87841. */
  87842. FLAC_API FLAC__bool FLAC__stream_encoder_set_ogg_serial_number(FLAC__StreamEncoder *encoder, long serial_number);
  87843. /** Set the "verify" flag. If \c true, the encoder will verify it's own
  87844. * encoded output by feeding it through an internal decoder and comparing
  87845. * the original signal against the decoded signal. If a mismatch occurs,
  87846. * the process call will return \c false. Note that this will slow the
  87847. * encoding process by the extra time required for decoding and comparison.
  87848. *
  87849. * \default \c false
  87850. * \param encoder An encoder instance to set.
  87851. * \param value Flag value (see above).
  87852. * \assert
  87853. * \code encoder != NULL \endcode
  87854. * \retval FLAC__bool
  87855. * \c false if the encoder is already initialized, else \c true.
  87856. */
  87857. FLAC_API FLAC__bool FLAC__stream_encoder_set_verify(FLAC__StreamEncoder *encoder, FLAC__bool value);
  87858. /** Set the <A HREF="../format.html#subset">Subset</A> flag. If \c true,
  87859. * the encoder will comply with the Subset and will check the
  87860. * settings during FLAC__stream_encoder_init_*() to see if all settings
  87861. * comply. If \c false, the settings may take advantage of the full
  87862. * range that the format allows.
  87863. *
  87864. * Make sure you know what it entails before setting this to \c false.
  87865. *
  87866. * \default \c true
  87867. * \param encoder An encoder instance to set.
  87868. * \param value Flag value (see above).
  87869. * \assert
  87870. * \code encoder != NULL \endcode
  87871. * \retval FLAC__bool
  87872. * \c false if the encoder is already initialized, else \c true.
  87873. */
  87874. FLAC_API FLAC__bool FLAC__stream_encoder_set_streamable_subset(FLAC__StreamEncoder *encoder, FLAC__bool value);
  87875. /** Set the number of channels to be encoded.
  87876. *
  87877. * \default \c 2
  87878. * \param encoder An encoder instance to set.
  87879. * \param value See above.
  87880. * \assert
  87881. * \code encoder != NULL \endcode
  87882. * \retval FLAC__bool
  87883. * \c false if the encoder is already initialized, else \c true.
  87884. */
  87885. FLAC_API FLAC__bool FLAC__stream_encoder_set_channels(FLAC__StreamEncoder *encoder, unsigned value);
  87886. /** Set the sample resolution of the input to be encoded.
  87887. *
  87888. * \warning
  87889. * Do not feed the encoder data that is wider than the value you
  87890. * set here or you will generate an invalid stream.
  87891. *
  87892. * \default \c 16
  87893. * \param encoder An encoder instance to set.
  87894. * \param value See above.
  87895. * \assert
  87896. * \code encoder != NULL \endcode
  87897. * \retval FLAC__bool
  87898. * \c false if the encoder is already initialized, else \c true.
  87899. */
  87900. FLAC_API FLAC__bool FLAC__stream_encoder_set_bits_per_sample(FLAC__StreamEncoder *encoder, unsigned value);
  87901. /** Set the sample rate (in Hz) of the input to be encoded.
  87902. *
  87903. * \default \c 44100
  87904. * \param encoder An encoder instance to set.
  87905. * \param value See above.
  87906. * \assert
  87907. * \code encoder != NULL \endcode
  87908. * \retval FLAC__bool
  87909. * \c false if the encoder is already initialized, else \c true.
  87910. */
  87911. FLAC_API FLAC__bool FLAC__stream_encoder_set_sample_rate(FLAC__StreamEncoder *encoder, unsigned value);
  87912. /** Set the compression level
  87913. *
  87914. * The compression level is roughly proportional to the amount of effort
  87915. * the encoder expends to compress the file. A higher level usually
  87916. * means more computation but higher compression. The default level is
  87917. * suitable for most applications.
  87918. *
  87919. * Currently the levels range from \c 0 (fastest, least compression) to
  87920. * \c 8 (slowest, most compression). A value larger than \c 8 will be
  87921. * treated as \c 8.
  87922. *
  87923. * This function automatically calls the following other \c _set_
  87924. * functions with appropriate values, so the client does not need to
  87925. * unless it specifically wants to override them:
  87926. * - FLAC__stream_encoder_set_do_mid_side_stereo()
  87927. * - FLAC__stream_encoder_set_loose_mid_side_stereo()
  87928. * - FLAC__stream_encoder_set_apodization()
  87929. * - FLAC__stream_encoder_set_max_lpc_order()
  87930. * - FLAC__stream_encoder_set_qlp_coeff_precision()
  87931. * - FLAC__stream_encoder_set_do_qlp_coeff_prec_search()
  87932. * - FLAC__stream_encoder_set_do_escape_coding()
  87933. * - FLAC__stream_encoder_set_do_exhaustive_model_search()
  87934. * - FLAC__stream_encoder_set_min_residual_partition_order()
  87935. * - FLAC__stream_encoder_set_max_residual_partition_order()
  87936. * - FLAC__stream_encoder_set_rice_parameter_search_dist()
  87937. *
  87938. * The actual values set for each level are:
  87939. * <table>
  87940. * <tr>
  87941. * <td><b>level</b><td>
  87942. * <td>do mid-side stereo<td>
  87943. * <td>loose mid-side stereo<td>
  87944. * <td>apodization<td>
  87945. * <td>max lpc order<td>
  87946. * <td>qlp coeff precision<td>
  87947. * <td>qlp coeff prec search<td>
  87948. * <td>escape coding<td>
  87949. * <td>exhaustive model search<td>
  87950. * <td>min residual partition order<td>
  87951. * <td>max residual partition order<td>
  87952. * <td>rice parameter search dist<td>
  87953. * </tr>
  87954. * <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>
  87955. * <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>
  87956. * <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>
  87957. * <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>
  87958. * <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>
  87959. * <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>
  87960. * <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>
  87961. * <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>
  87962. * <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>
  87963. * </table>
  87964. *
  87965. * \default \c 5
  87966. * \param encoder An encoder instance to set.
  87967. * \param value See above.
  87968. * \assert
  87969. * \code encoder != NULL \endcode
  87970. * \retval FLAC__bool
  87971. * \c false if the encoder is already initialized, else \c true.
  87972. */
  87973. FLAC_API FLAC__bool FLAC__stream_encoder_set_compression_level(FLAC__StreamEncoder *encoder, unsigned value);
  87974. /** Set the blocksize to use while encoding.
  87975. *
  87976. * The number of samples to use per frame. Use \c 0 to let the encoder
  87977. * estimate a blocksize; this is usually best.
  87978. *
  87979. * \default \c 0
  87980. * \param encoder An encoder instance to set.
  87981. * \param value See above.
  87982. * \assert
  87983. * \code encoder != NULL \endcode
  87984. * \retval FLAC__bool
  87985. * \c false if the encoder is already initialized, else \c true.
  87986. */
  87987. FLAC_API FLAC__bool FLAC__stream_encoder_set_blocksize(FLAC__StreamEncoder *encoder, unsigned value);
  87988. /** Set to \c true to enable mid-side encoding on stereo input. The
  87989. * number of channels must be 2 for this to have any effect. Set to
  87990. * \c false to use only independent channel coding.
  87991. *
  87992. * \default \c false
  87993. * \param encoder An encoder instance to set.
  87994. * \param value Flag value (see above).
  87995. * \assert
  87996. * \code encoder != NULL \endcode
  87997. * \retval FLAC__bool
  87998. * \c false if the encoder is already initialized, else \c true.
  87999. */
  88000. FLAC_API FLAC__bool FLAC__stream_encoder_set_do_mid_side_stereo(FLAC__StreamEncoder *encoder, FLAC__bool value);
  88001. /** Set to \c true to enable adaptive switching between mid-side and
  88002. * left-right encoding on stereo input. Set to \c false to use
  88003. * exhaustive searching. Setting this to \c true requires
  88004. * FLAC__stream_encoder_set_do_mid_side_stereo() to also be set to
  88005. * \c true in order to have any effect.
  88006. *
  88007. * \default \c false
  88008. * \param encoder An encoder instance to set.
  88009. * \param value Flag value (see above).
  88010. * \assert
  88011. * \code encoder != NULL \endcode
  88012. * \retval FLAC__bool
  88013. * \c false if the encoder is already initialized, else \c true.
  88014. */
  88015. FLAC_API FLAC__bool FLAC__stream_encoder_set_loose_mid_side_stereo(FLAC__StreamEncoder *encoder, FLAC__bool value);
  88016. /** Sets the apodization function(s) the encoder will use when windowing
  88017. * audio data for LPC analysis.
  88018. *
  88019. * The \a specification is a plain ASCII string which specifies exactly
  88020. * which functions to use. There may be more than one (up to 32),
  88021. * separated by \c ';' characters. Some functions take one or more
  88022. * comma-separated arguments in parentheses.
  88023. *
  88024. * The available functions are \c bartlett, \c bartlett_hann,
  88025. * \c blackman, \c blackman_harris_4term_92db, \c connes, \c flattop,
  88026. * \c gauss(STDDEV), \c hamming, \c hann, \c kaiser_bessel, \c nuttall,
  88027. * \c rectangle, \c triangle, \c tukey(P), \c welch.
  88028. *
  88029. * For \c gauss(STDDEV), STDDEV specifies the standard deviation
  88030. * (0<STDDEV<=0.5).
  88031. *
  88032. * For \c tukey(P), P specifies the fraction of the window that is
  88033. * tapered (0<=P<=1). P=0 corresponds to \c rectangle and P=1
  88034. * corresponds to \c hann.
  88035. *
  88036. * Example specifications are \c "blackman" or
  88037. * \c "hann;triangle;tukey(0.5);tukey(0.25);tukey(0.125)"
  88038. *
  88039. * Any function that is specified erroneously is silently dropped. Up
  88040. * to 32 functions are kept, the rest are dropped. If the specification
  88041. * is empty the encoder defaults to \c "tukey(0.5)".
  88042. *
  88043. * When more than one function is specified, then for every subframe the
  88044. * encoder will try each of them separately and choose the window that
  88045. * results in the smallest compressed subframe.
  88046. *
  88047. * Note that each function specified causes the encoder to occupy a
  88048. * floating point array in which to store the window.
  88049. *
  88050. * \default \c "tukey(0.5)"
  88051. * \param encoder An encoder instance to set.
  88052. * \param specification See above.
  88053. * \assert
  88054. * \code encoder != NULL \endcode
  88055. * \code specification != NULL \endcode
  88056. * \retval FLAC__bool
  88057. * \c false if the encoder is already initialized, else \c true.
  88058. */
  88059. FLAC_API FLAC__bool FLAC__stream_encoder_set_apodization(FLAC__StreamEncoder *encoder, const char *specification);
  88060. /** Set the maximum LPC order, or \c 0 to use only the fixed predictors.
  88061. *
  88062. * \default \c 0
  88063. * \param encoder An encoder instance to set.
  88064. * \param value See above.
  88065. * \assert
  88066. * \code encoder != NULL \endcode
  88067. * \retval FLAC__bool
  88068. * \c false if the encoder is already initialized, else \c true.
  88069. */
  88070. FLAC_API FLAC__bool FLAC__stream_encoder_set_max_lpc_order(FLAC__StreamEncoder *encoder, unsigned value);
  88071. /** Set the precision, in bits, of the quantized linear predictor
  88072. * coefficients, or \c 0 to let the encoder select it based on the
  88073. * blocksize.
  88074. *
  88075. * \note
  88076. * In the current implementation, qlp_coeff_precision + bits_per_sample must
  88077. * be less than 32.
  88078. *
  88079. * \default \c 0
  88080. * \param encoder An encoder instance to set.
  88081. * \param value See above.
  88082. * \assert
  88083. * \code encoder != NULL \endcode
  88084. * \retval FLAC__bool
  88085. * \c false if the encoder is already initialized, else \c true.
  88086. */
  88087. FLAC_API FLAC__bool FLAC__stream_encoder_set_qlp_coeff_precision(FLAC__StreamEncoder *encoder, unsigned value);
  88088. /** Set to \c false to use only the specified quantized linear predictor
  88089. * coefficient precision, or \c true to search neighboring precision
  88090. * values and use the best one.
  88091. *
  88092. * \default \c false
  88093. * \param encoder An encoder instance to set.
  88094. * \param value See above.
  88095. * \assert
  88096. * \code encoder != NULL \endcode
  88097. * \retval FLAC__bool
  88098. * \c false if the encoder is already initialized, else \c true.
  88099. */
  88100. FLAC_API FLAC__bool FLAC__stream_encoder_set_do_qlp_coeff_prec_search(FLAC__StreamEncoder *encoder, FLAC__bool value);
  88101. /** Deprecated. Setting this value has no effect.
  88102. *
  88103. * \default \c false
  88104. * \param encoder An encoder instance to set.
  88105. * \param value See above.
  88106. * \assert
  88107. * \code encoder != NULL \endcode
  88108. * \retval FLAC__bool
  88109. * \c false if the encoder is already initialized, else \c true.
  88110. */
  88111. FLAC_API FLAC__bool FLAC__stream_encoder_set_do_escape_coding(FLAC__StreamEncoder *encoder, FLAC__bool value);
  88112. /** Set to \c false to let the encoder estimate the best model order
  88113. * based on the residual signal energy, or \c true to force the
  88114. * encoder to evaluate all order models and select the best.
  88115. *
  88116. * \default \c false
  88117. * \param encoder An encoder instance to set.
  88118. * \param value See above.
  88119. * \assert
  88120. * \code encoder != NULL \endcode
  88121. * \retval FLAC__bool
  88122. * \c false if the encoder is already initialized, else \c true.
  88123. */
  88124. FLAC_API FLAC__bool FLAC__stream_encoder_set_do_exhaustive_model_search(FLAC__StreamEncoder *encoder, FLAC__bool value);
  88125. /** Set the minimum partition order to search when coding the residual.
  88126. * This is used in tandem with
  88127. * FLAC__stream_encoder_set_max_residual_partition_order().
  88128. *
  88129. * The partition order determines the context size in the residual.
  88130. * The context size will be approximately <tt>blocksize / (2 ^ order)</tt>.
  88131. *
  88132. * Set both min and max values to \c 0 to force a single context,
  88133. * whose Rice parameter is based on the residual signal variance.
  88134. * Otherwise, set a min and max order, and the encoder will search
  88135. * all orders, using the mean of each context for its Rice parameter,
  88136. * and use the best.
  88137. *
  88138. * \default \c 0
  88139. * \param encoder An encoder instance to set.
  88140. * \param value See above.
  88141. * \assert
  88142. * \code encoder != NULL \endcode
  88143. * \retval FLAC__bool
  88144. * \c false if the encoder is already initialized, else \c true.
  88145. */
  88146. FLAC_API FLAC__bool FLAC__stream_encoder_set_min_residual_partition_order(FLAC__StreamEncoder *encoder, unsigned value);
  88147. /** Set the maximum partition order to search when coding the residual.
  88148. * This is used in tandem with
  88149. * FLAC__stream_encoder_set_min_residual_partition_order().
  88150. *
  88151. * The partition order determines the context size in the residual.
  88152. * The context size will be approximately <tt>blocksize / (2 ^ order)</tt>.
  88153. *
  88154. * Set both min and max values to \c 0 to force a single context,
  88155. * whose Rice parameter is based on the residual signal variance.
  88156. * Otherwise, set a min and max order, and the encoder will search
  88157. * all orders, using the mean of each context for its Rice parameter,
  88158. * and use the best.
  88159. *
  88160. * \default \c 0
  88161. * \param encoder An encoder instance to set.
  88162. * \param value See above.
  88163. * \assert
  88164. * \code encoder != NULL \endcode
  88165. * \retval FLAC__bool
  88166. * \c false if the encoder is already initialized, else \c true.
  88167. */
  88168. FLAC_API FLAC__bool FLAC__stream_encoder_set_max_residual_partition_order(FLAC__StreamEncoder *encoder, unsigned value);
  88169. /** Deprecated. Setting this value has no effect.
  88170. *
  88171. * \default \c 0
  88172. * \param encoder An encoder instance to set.
  88173. * \param value See above.
  88174. * \assert
  88175. * \code encoder != NULL \endcode
  88176. * \retval FLAC__bool
  88177. * \c false if the encoder is already initialized, else \c true.
  88178. */
  88179. FLAC_API FLAC__bool FLAC__stream_encoder_set_rice_parameter_search_dist(FLAC__StreamEncoder *encoder, unsigned value);
  88180. /** Set an estimate of the total samples that will be encoded.
  88181. * This is merely an estimate and may be set to \c 0 if unknown.
  88182. * This value will be written to the STREAMINFO block before encoding,
  88183. * and can remove the need for the caller to rewrite the value later
  88184. * if the value is known before encoding.
  88185. *
  88186. * \default \c 0
  88187. * \param encoder An encoder instance to set.
  88188. * \param value See above.
  88189. * \assert
  88190. * \code encoder != NULL \endcode
  88191. * \retval FLAC__bool
  88192. * \c false if the encoder is already initialized, else \c true.
  88193. */
  88194. FLAC_API FLAC__bool FLAC__stream_encoder_set_total_samples_estimate(FLAC__StreamEncoder *encoder, FLAC__uint64 value);
  88195. /** Set the metadata blocks to be emitted to the stream before encoding.
  88196. * A value of \c NULL, \c 0 implies no metadata; otherwise, supply an
  88197. * array of pointers to metadata blocks. The array is non-const since
  88198. * the encoder may need to change the \a is_last flag inside them, and
  88199. * in some cases update seek point offsets. Otherwise, the encoder will
  88200. * not modify or free the blocks. It is up to the caller to free the
  88201. * metadata blocks after encoding finishes.
  88202. *
  88203. * \note
  88204. * The encoder stores only copies of the pointers in the \a metadata array;
  88205. * the metadata blocks themselves must survive at least until after
  88206. * FLAC__stream_encoder_finish() returns. Do not free the blocks until then.
  88207. *
  88208. * \note
  88209. * The STREAMINFO block is always written and no STREAMINFO block may
  88210. * occur in the supplied array.
  88211. *
  88212. * \note
  88213. * By default the encoder does not create a SEEKTABLE. If one is supplied
  88214. * in the \a metadata array, but the client has specified that it does not
  88215. * support seeking, then the SEEKTABLE will be written verbatim. However
  88216. * by itself this is not very useful as the client will not know the stream
  88217. * offsets for the seekpoints ahead of time. In order to get a proper
  88218. * seektable the client must support seeking. See next note.
  88219. *
  88220. * \note
  88221. * SEEKTABLE blocks are handled specially. Since you will not know
  88222. * the values for the seek point stream offsets, you should pass in
  88223. * a SEEKTABLE 'template', that is, a SEEKTABLE object with the
  88224. * required sample numbers (or placeholder points), with \c 0 for the
  88225. * \a frame_samples and \a stream_offset fields for each point. If the
  88226. * client has specified that it supports seeking by providing a seek
  88227. * callback to FLAC__stream_encoder_init_stream() or both seek AND read
  88228. * callback to FLAC__stream_encoder_init_ogg_stream() (or by using
  88229. * FLAC__stream_encoder_init*_file() or FLAC__stream_encoder_init*_FILE()),
  88230. * then while it is encoding the encoder will fill the stream offsets in
  88231. * for you and when encoding is finished, it will seek back and write the
  88232. * real values into the SEEKTABLE block in the stream. There are helper
  88233. * routines for manipulating seektable template blocks; see metadata.h:
  88234. * FLAC__metadata_object_seektable_template_*(). If the client does
  88235. * not support seeking, the SEEKTABLE will have inaccurate offsets which
  88236. * will slow down or remove the ability to seek in the FLAC stream.
  88237. *
  88238. * \note
  88239. * The encoder instance \b will modify the first \c SEEKTABLE block
  88240. * as it transforms the template to a valid seektable while encoding,
  88241. * but it is still up to the caller to free all metadata blocks after
  88242. * encoding.
  88243. *
  88244. * \note
  88245. * A VORBIS_COMMENT block may be supplied. The vendor string in it
  88246. * will be ignored. libFLAC will use it's own vendor string. libFLAC
  88247. * will not modify the passed-in VORBIS_COMMENT's vendor string, it
  88248. * will simply write it's own into the stream. If no VORBIS_COMMENT
  88249. * block is present in the \a metadata array, libFLAC will write an
  88250. * empty one, containing only the vendor string.
  88251. *
  88252. * \note The Ogg FLAC mapping requires that the VORBIS_COMMENT block be
  88253. * the second metadata block of the stream. The encoder already supplies
  88254. * the STREAMINFO block automatically. If \a metadata does not contain a
  88255. * VORBIS_COMMENT block, the encoder will supply that too. Otherwise, if
  88256. * \a metadata does contain a VORBIS_COMMENT block and it is not the
  88257. * first, the init function will reorder \a metadata by moving the
  88258. * VORBIS_COMMENT block to the front; the relative ordering of the other
  88259. * blocks will remain as they were.
  88260. *
  88261. * \note The Ogg FLAC mapping limits the number of metadata blocks per
  88262. * stream to \c 65535. If \a num_blocks exceeds this the function will
  88263. * return \c false.
  88264. *
  88265. * \default \c NULL, 0
  88266. * \param encoder An encoder instance to set.
  88267. * \param metadata See above.
  88268. * \param num_blocks See above.
  88269. * \assert
  88270. * \code encoder != NULL \endcode
  88271. * \retval FLAC__bool
  88272. * \c false if the encoder is already initialized, else \c true.
  88273. * \c false if the encoder is already initialized, or if
  88274. * \a num_blocks > 65535 if encoding to Ogg FLAC, else \c true.
  88275. */
  88276. FLAC_API FLAC__bool FLAC__stream_encoder_set_metadata(FLAC__StreamEncoder *encoder, FLAC__StreamMetadata **metadata, unsigned num_blocks);
  88277. /** Get the current encoder state.
  88278. *
  88279. * \param encoder An encoder instance to query.
  88280. * \assert
  88281. * \code encoder != NULL \endcode
  88282. * \retval FLAC__StreamEncoderState
  88283. * The current encoder state.
  88284. */
  88285. FLAC_API FLAC__StreamEncoderState FLAC__stream_encoder_get_state(const FLAC__StreamEncoder *encoder);
  88286. /** Get the state of the verify stream decoder.
  88287. * Useful when the stream encoder state is
  88288. * \c FLAC__STREAM_ENCODER_VERIFY_DECODER_ERROR.
  88289. *
  88290. * \param encoder An encoder instance to query.
  88291. * \assert
  88292. * \code encoder != NULL \endcode
  88293. * \retval FLAC__StreamDecoderState
  88294. * The verify stream decoder state.
  88295. */
  88296. FLAC_API FLAC__StreamDecoderState FLAC__stream_encoder_get_verify_decoder_state(const FLAC__StreamEncoder *encoder);
  88297. /** Get the current encoder state as a C string.
  88298. * This version automatically resolves
  88299. * \c FLAC__STREAM_ENCODER_VERIFY_DECODER_ERROR by getting the
  88300. * verify decoder's state.
  88301. *
  88302. * \param encoder A encoder instance to query.
  88303. * \assert
  88304. * \code encoder != NULL \endcode
  88305. * \retval const char *
  88306. * The encoder state as a C string. Do not modify the contents.
  88307. */
  88308. FLAC_API const char *FLAC__stream_encoder_get_resolved_state_string(const FLAC__StreamEncoder *encoder);
  88309. /** Get relevant values about the nature of a verify decoder error.
  88310. * Useful when the stream encoder state is
  88311. * \c FLAC__STREAM_ENCODER_VERIFY_DECODER_ERROR. The arguments should
  88312. * be addresses in which the stats will be returned, or NULL if value
  88313. * is not desired.
  88314. *
  88315. * \param encoder An encoder instance to query.
  88316. * \param absolute_sample The absolute sample number of the mismatch.
  88317. * \param frame_number The number of the frame in which the mismatch occurred.
  88318. * \param channel The channel in which the mismatch occurred.
  88319. * \param sample The number of the sample (relative to the frame) in
  88320. * which the mismatch occurred.
  88321. * \param expected The expected value for the sample in question.
  88322. * \param got The actual value returned by the decoder.
  88323. * \assert
  88324. * \code encoder != NULL \endcode
  88325. */
  88326. 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);
  88327. /** Get the "verify" flag.
  88328. *
  88329. * \param encoder An encoder instance to query.
  88330. * \assert
  88331. * \code encoder != NULL \endcode
  88332. * \retval FLAC__bool
  88333. * See FLAC__stream_encoder_set_verify().
  88334. */
  88335. FLAC_API FLAC__bool FLAC__stream_encoder_get_verify(const FLAC__StreamEncoder *encoder);
  88336. /** Get the <A HREF="../format.html#subset>Subset</A> flag.
  88337. *
  88338. * \param encoder An encoder instance to query.
  88339. * \assert
  88340. * \code encoder != NULL \endcode
  88341. * \retval FLAC__bool
  88342. * See FLAC__stream_encoder_set_streamable_subset().
  88343. */
  88344. FLAC_API FLAC__bool FLAC__stream_encoder_get_streamable_subset(const FLAC__StreamEncoder *encoder);
  88345. /** Get the number of input channels being processed.
  88346. *
  88347. * \param encoder An encoder instance to query.
  88348. * \assert
  88349. * \code encoder != NULL \endcode
  88350. * \retval unsigned
  88351. * See FLAC__stream_encoder_set_channels().
  88352. */
  88353. FLAC_API unsigned FLAC__stream_encoder_get_channels(const FLAC__StreamEncoder *encoder);
  88354. /** Get the input sample resolution setting.
  88355. *
  88356. * \param encoder An encoder instance to query.
  88357. * \assert
  88358. * \code encoder != NULL \endcode
  88359. * \retval unsigned
  88360. * See FLAC__stream_encoder_set_bits_per_sample().
  88361. */
  88362. FLAC_API unsigned FLAC__stream_encoder_get_bits_per_sample(const FLAC__StreamEncoder *encoder);
  88363. /** Get the input sample rate setting.
  88364. *
  88365. * \param encoder An encoder instance to query.
  88366. * \assert
  88367. * \code encoder != NULL \endcode
  88368. * \retval unsigned
  88369. * See FLAC__stream_encoder_set_sample_rate().
  88370. */
  88371. FLAC_API unsigned FLAC__stream_encoder_get_sample_rate(const FLAC__StreamEncoder *encoder);
  88372. /** Get the blocksize setting.
  88373. *
  88374. * \param encoder An encoder instance to query.
  88375. * \assert
  88376. * \code encoder != NULL \endcode
  88377. * \retval unsigned
  88378. * See FLAC__stream_encoder_set_blocksize().
  88379. */
  88380. FLAC_API unsigned FLAC__stream_encoder_get_blocksize(const FLAC__StreamEncoder *encoder);
  88381. /** Get the "mid/side stereo coding" flag.
  88382. *
  88383. * \param encoder An encoder instance to query.
  88384. * \assert
  88385. * \code encoder != NULL \endcode
  88386. * \retval FLAC__bool
  88387. * See FLAC__stream_encoder_get_do_mid_side_stereo().
  88388. */
  88389. FLAC_API FLAC__bool FLAC__stream_encoder_get_do_mid_side_stereo(const FLAC__StreamEncoder *encoder);
  88390. /** Get the "adaptive mid/side switching" flag.
  88391. *
  88392. * \param encoder An encoder instance to query.
  88393. * \assert
  88394. * \code encoder != NULL \endcode
  88395. * \retval FLAC__bool
  88396. * See FLAC__stream_encoder_set_loose_mid_side_stereo().
  88397. */
  88398. FLAC_API FLAC__bool FLAC__stream_encoder_get_loose_mid_side_stereo(const FLAC__StreamEncoder *encoder);
  88399. /** Get the maximum LPC order setting.
  88400. *
  88401. * \param encoder An encoder instance to query.
  88402. * \assert
  88403. * \code encoder != NULL \endcode
  88404. * \retval unsigned
  88405. * See FLAC__stream_encoder_set_max_lpc_order().
  88406. */
  88407. FLAC_API unsigned FLAC__stream_encoder_get_max_lpc_order(const FLAC__StreamEncoder *encoder);
  88408. /** Get the quantized linear predictor coefficient precision setting.
  88409. *
  88410. * \param encoder An encoder instance to query.
  88411. * \assert
  88412. * \code encoder != NULL \endcode
  88413. * \retval unsigned
  88414. * See FLAC__stream_encoder_set_qlp_coeff_precision().
  88415. */
  88416. FLAC_API unsigned FLAC__stream_encoder_get_qlp_coeff_precision(const FLAC__StreamEncoder *encoder);
  88417. /** Get the qlp coefficient precision search flag.
  88418. *
  88419. * \param encoder An encoder instance to query.
  88420. * \assert
  88421. * \code encoder != NULL \endcode
  88422. * \retval FLAC__bool
  88423. * See FLAC__stream_encoder_set_do_qlp_coeff_prec_search().
  88424. */
  88425. FLAC_API FLAC__bool FLAC__stream_encoder_get_do_qlp_coeff_prec_search(const FLAC__StreamEncoder *encoder);
  88426. /** Get the "escape coding" flag.
  88427. *
  88428. * \param encoder An encoder instance to query.
  88429. * \assert
  88430. * \code encoder != NULL \endcode
  88431. * \retval FLAC__bool
  88432. * See FLAC__stream_encoder_set_do_escape_coding().
  88433. */
  88434. FLAC_API FLAC__bool FLAC__stream_encoder_get_do_escape_coding(const FLAC__StreamEncoder *encoder);
  88435. /** Get the exhaustive model search flag.
  88436. *
  88437. * \param encoder An encoder instance to query.
  88438. * \assert
  88439. * \code encoder != NULL \endcode
  88440. * \retval FLAC__bool
  88441. * See FLAC__stream_encoder_set_do_exhaustive_model_search().
  88442. */
  88443. FLAC_API FLAC__bool FLAC__stream_encoder_get_do_exhaustive_model_search(const FLAC__StreamEncoder *encoder);
  88444. /** Get the minimum residual partition order setting.
  88445. *
  88446. * \param encoder An encoder instance to query.
  88447. * \assert
  88448. * \code encoder != NULL \endcode
  88449. * \retval unsigned
  88450. * See FLAC__stream_encoder_set_min_residual_partition_order().
  88451. */
  88452. FLAC_API unsigned FLAC__stream_encoder_get_min_residual_partition_order(const FLAC__StreamEncoder *encoder);
  88453. /** Get maximum residual partition order setting.
  88454. *
  88455. * \param encoder An encoder instance to query.
  88456. * \assert
  88457. * \code encoder != NULL \endcode
  88458. * \retval unsigned
  88459. * See FLAC__stream_encoder_set_max_residual_partition_order().
  88460. */
  88461. FLAC_API unsigned FLAC__stream_encoder_get_max_residual_partition_order(const FLAC__StreamEncoder *encoder);
  88462. /** Get the Rice parameter search distance setting.
  88463. *
  88464. * \param encoder An encoder instance to query.
  88465. * \assert
  88466. * \code encoder != NULL \endcode
  88467. * \retval unsigned
  88468. * See FLAC__stream_encoder_set_rice_parameter_search_dist().
  88469. */
  88470. FLAC_API unsigned FLAC__stream_encoder_get_rice_parameter_search_dist(const FLAC__StreamEncoder *encoder);
  88471. /** Get the previously set estimate of the total samples to be encoded.
  88472. * The encoder merely mimics back the value given to
  88473. * FLAC__stream_encoder_set_total_samples_estimate() since it has no
  88474. * other way of knowing how many samples the client will encode.
  88475. *
  88476. * \param encoder An encoder instance to set.
  88477. * \assert
  88478. * \code encoder != NULL \endcode
  88479. * \retval FLAC__uint64
  88480. * See FLAC__stream_encoder_get_total_samples_estimate().
  88481. */
  88482. FLAC_API FLAC__uint64 FLAC__stream_encoder_get_total_samples_estimate(const FLAC__StreamEncoder *encoder);
  88483. /** Initialize the encoder instance to encode native FLAC streams.
  88484. *
  88485. * This flavor of initialization sets up the encoder to encode to a
  88486. * native FLAC stream. I/O is performed via callbacks to the client.
  88487. * For encoding to a plain file via filename or open \c FILE*,
  88488. * FLAC__stream_encoder_init_file() and FLAC__stream_encoder_init_FILE()
  88489. * provide a simpler interface.
  88490. *
  88491. * This function should be called after FLAC__stream_encoder_new() and
  88492. * FLAC__stream_encoder_set_*() but before FLAC__stream_encoder_process()
  88493. * or FLAC__stream_encoder_process_interleaved().
  88494. * initialization succeeded.
  88495. *
  88496. * The call to FLAC__stream_encoder_init_stream() currently will also
  88497. * immediately call the write callback several times, once with the \c fLaC
  88498. * signature, and once for each encoded metadata block.
  88499. *
  88500. * \param encoder An uninitialized encoder instance.
  88501. * \param write_callback See FLAC__StreamEncoderWriteCallback. This
  88502. * pointer must not be \c NULL.
  88503. * \param seek_callback See FLAC__StreamEncoderSeekCallback. This
  88504. * pointer may be \c NULL if seeking is not
  88505. * supported. The encoder uses seeking to go back
  88506. * and write some some stream statistics to the
  88507. * STREAMINFO block; this is recommended but not
  88508. * necessary to create a valid FLAC stream. If
  88509. * \a seek_callback is not \c NULL then a
  88510. * \a tell_callback must also be supplied.
  88511. * Alternatively, a dummy seek callback that just
  88512. * returns \c FLAC__STREAM_ENCODER_SEEK_STATUS_UNSUPPORTED
  88513. * may also be supplied, all though this is slightly
  88514. * less efficient for the encoder.
  88515. * \param tell_callback See FLAC__StreamEncoderTellCallback. This
  88516. * pointer may be \c NULL if seeking is not
  88517. * supported. If \a seek_callback is \c NULL then
  88518. * this argument will be ignored. If
  88519. * \a seek_callback is not \c NULL then a
  88520. * \a tell_callback must also be supplied.
  88521. * Alternatively, a dummy tell callback that just
  88522. * returns \c FLAC__STREAM_ENCODER_TELL_STATUS_UNSUPPORTED
  88523. * may also be supplied, all though this is slightly
  88524. * less efficient for the encoder.
  88525. * \param metadata_callback See FLAC__StreamEncoderMetadataCallback. This
  88526. * pointer may be \c NULL if the callback is not
  88527. * desired. If the client provides a seek callback,
  88528. * this function is not necessary as the encoder
  88529. * will automatically seek back and update the
  88530. * STREAMINFO block. It may also be \c NULL if the
  88531. * client does not support seeking, since it will
  88532. * have no way of going back to update the
  88533. * STREAMINFO. However the client can still supply
  88534. * a callback if it would like to know the details
  88535. * from the STREAMINFO.
  88536. * \param client_data This value will be supplied to callbacks in their
  88537. * \a client_data argument.
  88538. * \assert
  88539. * \code encoder != NULL \endcode
  88540. * \retval FLAC__StreamEncoderInitStatus
  88541. * \c FLAC__STREAM_ENCODER_INIT_STATUS_OK if initialization was successful;
  88542. * see FLAC__StreamEncoderInitStatus for the meanings of other return values.
  88543. */
  88544. 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);
  88545. /** Initialize the encoder instance to encode Ogg FLAC streams.
  88546. *
  88547. * This flavor of initialization sets up the encoder to encode to a FLAC
  88548. * stream in an Ogg container. I/O is performed via callbacks to the
  88549. * client. For encoding to a plain file via filename or open \c FILE*,
  88550. * FLAC__stream_encoder_init_ogg_file() and FLAC__stream_encoder_init_ogg_FILE()
  88551. * provide a simpler interface.
  88552. *
  88553. * This function should be called after FLAC__stream_encoder_new() and
  88554. * FLAC__stream_encoder_set_*() but before FLAC__stream_encoder_process()
  88555. * or FLAC__stream_encoder_process_interleaved().
  88556. * initialization succeeded.
  88557. *
  88558. * The call to FLAC__stream_encoder_init_ogg_stream() currently will also
  88559. * immediately call the write callback several times to write the metadata
  88560. * packets.
  88561. *
  88562. * \param encoder An uninitialized encoder instance.
  88563. * \param read_callback See FLAC__StreamEncoderReadCallback. This
  88564. * pointer must not be \c NULL if \a seek_callback
  88565. * is non-NULL since they are both needed to be
  88566. * able to write data back to the Ogg FLAC stream
  88567. * in the post-encode phase.
  88568. * \param write_callback See FLAC__StreamEncoderWriteCallback. This
  88569. * pointer must not be \c NULL.
  88570. * \param seek_callback See FLAC__StreamEncoderSeekCallback. This
  88571. * pointer may be \c NULL if seeking is not
  88572. * supported. The encoder uses seeking to go back
  88573. * and write some some stream statistics to the
  88574. * STREAMINFO block; this is recommended but not
  88575. * necessary to create a valid FLAC stream. If
  88576. * \a seek_callback is not \c NULL then a
  88577. * \a tell_callback must also be supplied.
  88578. * Alternatively, a dummy seek callback that just
  88579. * returns \c FLAC__STREAM_ENCODER_SEEK_STATUS_UNSUPPORTED
  88580. * may also be supplied, all though this is slightly
  88581. * less efficient for the encoder.
  88582. * \param tell_callback See FLAC__StreamEncoderTellCallback. This
  88583. * pointer may be \c NULL if seeking is not
  88584. * supported. If \a seek_callback is \c NULL then
  88585. * this argument will be ignored. If
  88586. * \a seek_callback is not \c NULL then a
  88587. * \a tell_callback must also be supplied.
  88588. * Alternatively, a dummy tell callback that just
  88589. * returns \c FLAC__STREAM_ENCODER_TELL_STATUS_UNSUPPORTED
  88590. * may also be supplied, all though this is slightly
  88591. * less efficient for the encoder.
  88592. * \param metadata_callback See FLAC__StreamEncoderMetadataCallback. This
  88593. * pointer may be \c NULL if the callback is not
  88594. * desired. If the client provides a seek callback,
  88595. * this function is not necessary as the encoder
  88596. * will automatically seek back and update the
  88597. * STREAMINFO block. It may also be \c NULL if the
  88598. * client does not support seeking, since it will
  88599. * have no way of going back to update the
  88600. * STREAMINFO. However the client can still supply
  88601. * a callback if it would like to know the details
  88602. * from the STREAMINFO.
  88603. * \param client_data This value will be supplied to callbacks in their
  88604. * \a client_data argument.
  88605. * \assert
  88606. * \code encoder != NULL \endcode
  88607. * \retval FLAC__StreamEncoderInitStatus
  88608. * \c FLAC__STREAM_ENCODER_INIT_STATUS_OK if initialization was successful;
  88609. * see FLAC__StreamEncoderInitStatus for the meanings of other return values.
  88610. */
  88611. 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);
  88612. /** Initialize the encoder instance to encode native FLAC files.
  88613. *
  88614. * This flavor of initialization sets up the encoder to encode to a
  88615. * plain native FLAC file. For non-stdio streams, you must use
  88616. * FLAC__stream_encoder_init_stream() and provide callbacks for the I/O.
  88617. *
  88618. * This function should be called after FLAC__stream_encoder_new() and
  88619. * FLAC__stream_encoder_set_*() but before FLAC__stream_encoder_process()
  88620. * or FLAC__stream_encoder_process_interleaved().
  88621. * initialization succeeded.
  88622. *
  88623. * \param encoder An uninitialized encoder instance.
  88624. * \param file An open file. The file should have been opened
  88625. * with mode \c "w+b" and rewound. The file
  88626. * becomes owned by the encoder and should not be
  88627. * manipulated by the client while encoding.
  88628. * Unless \a file is \c stdout, it will be closed
  88629. * when FLAC__stream_encoder_finish() is called.
  88630. * Note however that a proper SEEKTABLE cannot be
  88631. * created when encoding to \c stdout since it is
  88632. * not seekable.
  88633. * \param progress_callback See FLAC__StreamEncoderProgressCallback. This
  88634. * pointer may be \c NULL if the callback is not
  88635. * desired.
  88636. * \param client_data This value will be supplied to callbacks in their
  88637. * \a client_data argument.
  88638. * \assert
  88639. * \code encoder != NULL \endcode
  88640. * \code file != NULL \endcode
  88641. * \retval FLAC__StreamEncoderInitStatus
  88642. * \c FLAC__STREAM_ENCODER_INIT_STATUS_OK if initialization was successful;
  88643. * see FLAC__StreamEncoderInitStatus for the meanings of other return values.
  88644. */
  88645. FLAC_API FLAC__StreamEncoderInitStatus FLAC__stream_encoder_init_FILE(FLAC__StreamEncoder *encoder, FILE *file, FLAC__StreamEncoderProgressCallback progress_callback, void *client_data);
  88646. /** Initialize the encoder instance to encode Ogg FLAC files.
  88647. *
  88648. * This flavor of initialization sets up the encoder to encode to a
  88649. * plain Ogg FLAC file. For non-stdio streams, you must use
  88650. * FLAC__stream_encoder_init_ogg_stream() and provide callbacks for the I/O.
  88651. *
  88652. * This function should be called after FLAC__stream_encoder_new() and
  88653. * FLAC__stream_encoder_set_*() but before FLAC__stream_encoder_process()
  88654. * or FLAC__stream_encoder_process_interleaved().
  88655. * initialization succeeded.
  88656. *
  88657. * \param encoder An uninitialized encoder instance.
  88658. * \param file An open file. The file should have been opened
  88659. * with mode \c "w+b" and rewound. The file
  88660. * becomes owned by the encoder and should not be
  88661. * manipulated by the client while encoding.
  88662. * Unless \a file is \c stdout, it will be closed
  88663. * when FLAC__stream_encoder_finish() is called.
  88664. * Note however that a proper SEEKTABLE cannot be
  88665. * created when encoding to \c stdout since it is
  88666. * not seekable.
  88667. * \param progress_callback See FLAC__StreamEncoderProgressCallback. This
  88668. * pointer may be \c NULL if the callback is not
  88669. * desired.
  88670. * \param client_data This value will be supplied to callbacks in their
  88671. * \a client_data argument.
  88672. * \assert
  88673. * \code encoder != NULL \endcode
  88674. * \code file != NULL \endcode
  88675. * \retval FLAC__StreamEncoderInitStatus
  88676. * \c FLAC__STREAM_ENCODER_INIT_STATUS_OK if initialization was successful;
  88677. * see FLAC__StreamEncoderInitStatus for the meanings of other return values.
  88678. */
  88679. FLAC_API FLAC__StreamEncoderInitStatus FLAC__stream_encoder_init_ogg_FILE(FLAC__StreamEncoder *encoder, FILE *file, FLAC__StreamEncoderProgressCallback progress_callback, void *client_data);
  88680. /** Initialize the encoder instance to encode native FLAC files.
  88681. *
  88682. * This flavor of initialization sets up the encoder to encode to a plain
  88683. * FLAC file. If POSIX fopen() semantics are not sufficient (for example,
  88684. * with Unicode filenames on Windows), you must use
  88685. * FLAC__stream_encoder_init_FILE(), or FLAC__stream_encoder_init_stream()
  88686. * and provide callbacks for the I/O.
  88687. *
  88688. * This function should be called after FLAC__stream_encoder_new() and
  88689. * FLAC__stream_encoder_set_*() but before FLAC__stream_encoder_process()
  88690. * or FLAC__stream_encoder_process_interleaved().
  88691. * initialization succeeded.
  88692. *
  88693. * \param encoder An uninitialized encoder instance.
  88694. * \param filename The name of the file to encode to. The file will
  88695. * be opened with fopen(). Use \c NULL to encode to
  88696. * \c stdout. Note however that a proper SEEKTABLE
  88697. * cannot be created when encoding to \c stdout since
  88698. * it is not seekable.
  88699. * \param progress_callback See FLAC__StreamEncoderProgressCallback. This
  88700. * pointer may be \c NULL if the callback is not
  88701. * desired.
  88702. * \param client_data This value will be supplied to callbacks in their
  88703. * \a client_data argument.
  88704. * \assert
  88705. * \code encoder != NULL \endcode
  88706. * \retval FLAC__StreamEncoderInitStatus
  88707. * \c FLAC__STREAM_ENCODER_INIT_STATUS_OK if initialization was successful;
  88708. * see FLAC__StreamEncoderInitStatus for the meanings of other return values.
  88709. */
  88710. FLAC_API FLAC__StreamEncoderInitStatus FLAC__stream_encoder_init_file(FLAC__StreamEncoder *encoder, const char *filename, FLAC__StreamEncoderProgressCallback progress_callback, void *client_data);
  88711. /** Initialize the encoder instance to encode Ogg FLAC files.
  88712. *
  88713. * This flavor of initialization sets up the encoder to encode to a plain
  88714. * Ogg FLAC file. If POSIX fopen() semantics are not sufficient (for example,
  88715. * with Unicode filenames on Windows), you must use
  88716. * FLAC__stream_encoder_init_ogg_FILE(), or FLAC__stream_encoder_init_ogg_stream()
  88717. * and provide callbacks for the I/O.
  88718. *
  88719. * This function should be called after FLAC__stream_encoder_new() and
  88720. * FLAC__stream_encoder_set_*() but before FLAC__stream_encoder_process()
  88721. * or FLAC__stream_encoder_process_interleaved().
  88722. * initialization succeeded.
  88723. *
  88724. * \param encoder An uninitialized encoder instance.
  88725. * \param filename The name of the file to encode to. The file will
  88726. * be opened with fopen(). Use \c NULL to encode to
  88727. * \c stdout. Note however that a proper SEEKTABLE
  88728. * cannot be created when encoding to \c stdout since
  88729. * it is not seekable.
  88730. * \param progress_callback See FLAC__StreamEncoderProgressCallback. This
  88731. * pointer may be \c NULL if the callback is not
  88732. * desired.
  88733. * \param client_data This value will be supplied to callbacks in their
  88734. * \a client_data argument.
  88735. * \assert
  88736. * \code encoder != NULL \endcode
  88737. * \retval FLAC__StreamEncoderInitStatus
  88738. * \c FLAC__STREAM_ENCODER_INIT_STATUS_OK if initialization was successful;
  88739. * see FLAC__StreamEncoderInitStatus for the meanings of other return values.
  88740. */
  88741. FLAC_API FLAC__StreamEncoderInitStatus FLAC__stream_encoder_init_ogg_file(FLAC__StreamEncoder *encoder, const char *filename, FLAC__StreamEncoderProgressCallback progress_callback, void *client_data);
  88742. /** Finish the encoding process.
  88743. * Flushes the encoding buffer, releases resources, resets the encoder
  88744. * settings to their defaults, and returns the encoder state to
  88745. * FLAC__STREAM_ENCODER_UNINITIALIZED. Note that this can generate
  88746. * one or more write callbacks before returning, and will generate
  88747. * a metadata callback.
  88748. *
  88749. * Note that in the course of processing the last frame, errors can
  88750. * occur, so the caller should be sure to check the return value to
  88751. * ensure the file was encoded properly.
  88752. *
  88753. * In the event of a prematurely-terminated encode, it is not strictly
  88754. * necessary to call this immediately before FLAC__stream_encoder_delete()
  88755. * but it is good practice to match every FLAC__stream_encoder_init_*()
  88756. * with a FLAC__stream_encoder_finish().
  88757. *
  88758. * \param encoder An uninitialized encoder instance.
  88759. * \assert
  88760. * \code encoder != NULL \endcode
  88761. * \retval FLAC__bool
  88762. * \c false if an error occurred processing the last frame; or if verify
  88763. * mode is set (see FLAC__stream_encoder_set_verify()), there was a
  88764. * verify mismatch; else \c true. If \c false, caller should check the
  88765. * state with FLAC__stream_encoder_get_state() for more information
  88766. * about the error.
  88767. */
  88768. FLAC_API FLAC__bool FLAC__stream_encoder_finish(FLAC__StreamEncoder *encoder);
  88769. /** Submit data for encoding.
  88770. * This version allows you to supply the input data via an array of
  88771. * pointers, each pointer pointing to an array of \a samples samples
  88772. * representing one channel. The samples need not be block-aligned,
  88773. * but each channel should have the same number of samples. Each sample
  88774. * should be a signed integer, right-justified to the resolution set by
  88775. * FLAC__stream_encoder_set_bits_per_sample(). For example, if the
  88776. * resolution is 16 bits per sample, the samples should all be in the
  88777. * range [-32768,32767].
  88778. *
  88779. * For applications where channel order is important, channels must
  88780. * follow the order as described in the
  88781. * <A HREF="../format.html#frame_header">frame header</A>.
  88782. *
  88783. * \param encoder An initialized encoder instance in the OK state.
  88784. * \param buffer An array of pointers to each channel's signal.
  88785. * \param samples The number of samples in one channel.
  88786. * \assert
  88787. * \code encoder != NULL \endcode
  88788. * \code FLAC__stream_encoder_get_state(encoder) == FLAC__STREAM_ENCODER_OK \endcode
  88789. * \retval FLAC__bool
  88790. * \c true if successful, else \c false; in this case, check the
  88791. * encoder state with FLAC__stream_encoder_get_state() to see what
  88792. * went wrong.
  88793. */
  88794. FLAC_API FLAC__bool FLAC__stream_encoder_process(FLAC__StreamEncoder *encoder, const FLAC__int32 * const buffer[], unsigned samples);
  88795. /** Submit data for encoding.
  88796. * This version allows you to supply the input data where the channels
  88797. * are interleaved into a single array (i.e. channel0_sample0,
  88798. * channel1_sample0, ... , channelN_sample0, channel0_sample1, ...).
  88799. * The samples need not be block-aligned but they must be
  88800. * sample-aligned, i.e. the first value should be channel0_sample0
  88801. * and the last value channelN_sampleM. Each sample should be a signed
  88802. * integer, right-justified to the resolution set by
  88803. * FLAC__stream_encoder_set_bits_per_sample(). For example, if the
  88804. * resolution is 16 bits per sample, the samples should all be in the
  88805. * range [-32768,32767].
  88806. *
  88807. * For applications where channel order is important, channels must
  88808. * follow the order as described in the
  88809. * <A HREF="../format.html#frame_header">frame header</A>.
  88810. *
  88811. * \param encoder An initialized encoder instance in the OK state.
  88812. * \param buffer An array of channel-interleaved data (see above).
  88813. * \param samples The number of samples in one channel, the same as for
  88814. * FLAC__stream_encoder_process(). For example, if
  88815. * encoding two channels, \c 1000 \a samples corresponds
  88816. * to a \a buffer of 2000 values.
  88817. * \assert
  88818. * \code encoder != NULL \endcode
  88819. * \code FLAC__stream_encoder_get_state(encoder) == FLAC__STREAM_ENCODER_OK \endcode
  88820. * \retval FLAC__bool
  88821. * \c true if successful, else \c false; in this case, check the
  88822. * encoder state with FLAC__stream_encoder_get_state() to see what
  88823. * went wrong.
  88824. */
  88825. FLAC_API FLAC__bool FLAC__stream_encoder_process_interleaved(FLAC__StreamEncoder *encoder, const FLAC__int32 buffer[], unsigned samples);
  88826. /* \} */
  88827. #ifdef __cplusplus
  88828. }
  88829. #endif
  88830. #endif
  88831. /*** End of inlined file: stream_encoder.h ***/
  88832. #ifdef _MSC_VER
  88833. /* OPT: an MSVC built-in would be better */
  88834. static _inline FLAC__uint32 local_swap32_(FLAC__uint32 x)
  88835. {
  88836. x = ((x<<8)&0xFF00FF00) | ((x>>8)&0x00FF00FF);
  88837. return (x>>16) | (x<<16);
  88838. }
  88839. #endif
  88840. #if defined(_MSC_VER) && defined(_X86_)
  88841. /* OPT: an MSVC built-in would be better */
  88842. static void local_swap32_block_(FLAC__uint32 *start, FLAC__uint32 len)
  88843. {
  88844. __asm {
  88845. mov edx, start
  88846. mov ecx, len
  88847. test ecx, ecx
  88848. loop1:
  88849. jz done1
  88850. mov eax, [edx]
  88851. bswap eax
  88852. mov [edx], eax
  88853. add edx, 4
  88854. dec ecx
  88855. jmp short loop1
  88856. done1:
  88857. }
  88858. }
  88859. #endif
  88860. /** \mainpage
  88861. *
  88862. * \section intro Introduction
  88863. *
  88864. * This is the documentation for the FLAC C and C++ APIs. It is
  88865. * highly interconnected; this introduction should give you a top
  88866. * level idea of the structure and how to find the information you
  88867. * need. As a prerequisite you should have at least a basic
  88868. * knowledge of the FLAC format, documented
  88869. * <A HREF="../format.html">here</A>.
  88870. *
  88871. * \section c_api FLAC C API
  88872. *
  88873. * The FLAC C API is the interface to libFLAC, a set of structures
  88874. * describing the components of FLAC streams, and functions for
  88875. * encoding and decoding streams, as well as manipulating FLAC
  88876. * metadata in files. The public include files will be installed
  88877. * in your include area (for example /usr/include/FLAC/...).
  88878. *
  88879. * By writing a little code and linking against libFLAC, it is
  88880. * relatively easy to add FLAC support to another program. The
  88881. * library is licensed under <A HREF="../license.html">Xiph's BSD license</A>.
  88882. * Complete source code of libFLAC as well as the command-line
  88883. * encoder and plugins is available and is a useful source of
  88884. * examples.
  88885. *
  88886. * Aside from encoders and decoders, libFLAC provides a powerful
  88887. * metadata interface for manipulating metadata in FLAC files. It
  88888. * allows the user to add, delete, and modify FLAC metadata blocks
  88889. * and it can automatically take advantage of PADDING blocks to avoid
  88890. * rewriting the entire FLAC file when changing the size of the
  88891. * metadata.
  88892. *
  88893. * libFLAC usually only requires the standard C library and C math
  88894. * library. In particular, threading is not used so there is no
  88895. * dependency on a thread library. However, libFLAC does not use
  88896. * global variables and should be thread-safe.
  88897. *
  88898. * libFLAC also supports encoding to and decoding from Ogg FLAC.
  88899. * However the metadata editing interfaces currently have limited
  88900. * read-only support for Ogg FLAC files.
  88901. *
  88902. * \section cpp_api FLAC C++ API
  88903. *
  88904. * The FLAC C++ API is a set of classes that encapsulate the
  88905. * structures and functions in libFLAC. They provide slightly more
  88906. * functionality with respect to metadata but are otherwise
  88907. * equivalent. For the most part, they share the same usage as
  88908. * their counterparts in libFLAC, and the FLAC C API documentation
  88909. * can be used as a supplement. The public include files
  88910. * for the C++ API will be installed in your include area (for
  88911. * example /usr/include/FLAC++/...).
  88912. *
  88913. * libFLAC++ is also licensed under
  88914. * <A HREF="../license.html">Xiph's BSD license</A>.
  88915. *
  88916. * \section getting_started Getting Started
  88917. *
  88918. * A good starting point for learning the API is to browse through
  88919. * the <A HREF="modules.html">modules</A>. Modules are logical
  88920. * groupings of related functions or classes, which correspond roughly
  88921. * to header files or sections of header files. Each module includes a
  88922. * detailed description of the general usage of its functions or
  88923. * classes.
  88924. *
  88925. * From there you can go on to look at the documentation of
  88926. * individual functions. You can see different views of the individual
  88927. * functions through the links in top bar across this page.
  88928. *
  88929. * If you prefer a more hands-on approach, you can jump right to some
  88930. * <A HREF="../documentation_example_code.html">example code</A>.
  88931. *
  88932. * \section porting_guide Porting Guide
  88933. *
  88934. * Starting with FLAC 1.1.3 a \link porting Porting Guide \endlink
  88935. * has been introduced which gives detailed instructions on how to
  88936. * port your code to newer versions of FLAC.
  88937. *
  88938. * \section embedded_developers Embedded Developers
  88939. *
  88940. * libFLAC has grown larger over time as more functionality has been
  88941. * included, but much of it may be unnecessary for a particular embedded
  88942. * implementation. Unused parts may be pruned by some simple editing of
  88943. * src/libFLAC/Makefile.am. In general, the decoders, encoders, and
  88944. * metadata interface are all independent from each other.
  88945. *
  88946. * It is easiest to just describe the dependencies:
  88947. *
  88948. * - All modules depend on the \link flac_format Format \endlink module.
  88949. * - The decoders and encoders depend on the bitbuffer.
  88950. * - The decoder is independent of the encoder. The encoder uses the
  88951. * decoder because of the verify feature, but this can be removed if
  88952. * not needed.
  88953. * - Parts of the metadata interface require the stream decoder (but not
  88954. * the encoder).
  88955. * - Ogg support is selectable through the compile time macro
  88956. * \c FLAC__HAS_OGG.
  88957. *
  88958. * For example, if your application only requires the stream decoder, no
  88959. * encoder, and no metadata interface, you can remove the stream encoder
  88960. * and the metadata interface, which will greatly reduce the size of the
  88961. * library.
  88962. *
  88963. * Also, there are several places in the libFLAC code with comments marked
  88964. * with "OPT:" where a #define can be changed to enable code that might be
  88965. * faster on a specific platform. Experimenting with these can yield faster
  88966. * binaries.
  88967. */
  88968. /** \defgroup porting Porting Guide for New Versions
  88969. *
  88970. * This module describes differences in the library interfaces from
  88971. * version to version. It assists in the porting of code that uses
  88972. * the libraries to newer versions of FLAC.
  88973. *
  88974. * One simple facility for making porting easier that has been added
  88975. * in FLAC 1.1.3 is a set of \c #defines in \c export.h of each
  88976. * library's includes (e.g. \c include/FLAC/export.h). The
  88977. * \c #defines mirror the libraries'
  88978. * <A HREF="http://www.gnu.org/software/libtool/manual.html#Libtool-versioning">libtool version numbers</A>,
  88979. * e.g. in libFLAC there are \c FLAC_API_VERSION_CURRENT,
  88980. * \c FLAC_API_VERSION_REVISION, and \c FLAC_API_VERSION_AGE.
  88981. * These can be used to support multiple versions of an API during the
  88982. * transition phase, e.g.
  88983. *
  88984. * \code
  88985. * #if !defined(FLAC_API_VERSION_CURRENT) || FLAC_API_VERSION_CURRENT <= 7
  88986. * legacy code
  88987. * #else
  88988. * new code
  88989. * #endif
  88990. * \endcode
  88991. *
  88992. * The the source will work for multiple versions and the legacy code can
  88993. * easily be removed when the transition is complete.
  88994. *
  88995. * Another available symbol is FLAC_API_SUPPORTS_OGG_FLAC (defined in
  88996. * include/FLAC/export.h), which can be used to determine whether or not
  88997. * the library has been compiled with support for Ogg FLAC. This is
  88998. * simpler than trying to call an Ogg init function and catching the
  88999. * error.
  89000. */
  89001. /** \defgroup porting_1_1_2_to_1_1_3 Porting from FLAC 1.1.2 to 1.1.3
  89002. * \ingroup porting
  89003. *
  89004. * \brief
  89005. * This module describes porting from FLAC 1.1.2 to FLAC 1.1.3.
  89006. *
  89007. * The main change between the APIs in 1.1.2 and 1.1.3 is that they have
  89008. * been simplified. First, libOggFLAC has been merged into libFLAC and
  89009. * libOggFLAC++ has been merged into libFLAC++. Second, both the three
  89010. * decoding layers and three encoding layers have been merged into a
  89011. * single stream decoder and stream encoder. That is, the functionality
  89012. * of FLAC__SeekableStreamDecoder and FLAC__FileDecoder has been merged
  89013. * into FLAC__StreamDecoder, and FLAC__SeekableStreamEncoder and
  89014. * FLAC__FileEncoder into FLAC__StreamEncoder. Only the
  89015. * FLAC__StreamDecoder and FLAC__StreamEncoder remain. What this means
  89016. * is there is now a single API that can be used to encode or decode
  89017. * streams to/from native FLAC or Ogg FLAC and the single API can work
  89018. * on both seekable and non-seekable streams.
  89019. *
  89020. * Instead of creating an encoder or decoder of a certain layer, now the
  89021. * client will always create a FLAC__StreamEncoder or
  89022. * FLAC__StreamDecoder. The old layers are now differentiated by the
  89023. * initialization function. For example, for the decoder,
  89024. * FLAC__stream_decoder_init() has been replaced by
  89025. * FLAC__stream_decoder_init_stream(). This init function takes
  89026. * callbacks for the I/O, and the seeking callbacks are optional. This
  89027. * allows the client to use the same object for seekable and
  89028. * non-seekable streams. For decoding a FLAC file directly, the client
  89029. * can use FLAC__stream_decoder_init_file() and pass just a filename
  89030. * and fewer callbacks; most of the other callbacks are supplied
  89031. * internally. For situations where fopen()ing by filename is not
  89032. * possible (e.g. Unicode filenames on Windows) the client can instead
  89033. * open the file itself and supply the FILE* to
  89034. * FLAC__stream_decoder_init_FILE(). The init functions now returns a
  89035. * FLAC__StreamDecoderInitStatus instead of FLAC__StreamDecoderState.
  89036. * Since the callbacks and client data are now passed to the init
  89037. * function, the FLAC__stream_decoder_set_*_callback() functions and
  89038. * FLAC__stream_decoder_set_client_data() are no longer needed. The
  89039. * rest of the calls to the decoder are the same as before.
  89040. *
  89041. * There are counterpart init functions for Ogg FLAC, e.g.
  89042. * FLAC__stream_decoder_init_ogg_stream(). All the rest of the calls
  89043. * and callbacks are the same as for native FLAC.
  89044. *
  89045. * As an example, in FLAC 1.1.2 a seekable stream decoder would have
  89046. * been set up like so:
  89047. *
  89048. * \code
  89049. * FLAC__SeekableStreamDecoder *decoder = FLAC__seekable_stream_decoder_new();
  89050. * if(decoder == NULL) do_something;
  89051. * FLAC__seekable_stream_decoder_set_md5_checking(decoder, true);
  89052. * [... other settings ...]
  89053. * FLAC__seekable_stream_decoder_set_read_callback(decoder, my_read_callback);
  89054. * FLAC__seekable_stream_decoder_set_seek_callback(decoder, my_seek_callback);
  89055. * FLAC__seekable_stream_decoder_set_tell_callback(decoder, my_tell_callback);
  89056. * FLAC__seekable_stream_decoder_set_length_callback(decoder, my_length_callback);
  89057. * FLAC__seekable_stream_decoder_set_eof_callback(decoder, my_eof_callback);
  89058. * FLAC__seekable_stream_decoder_set_write_callback(decoder, my_write_callback);
  89059. * FLAC__seekable_stream_decoder_set_metadata_callback(decoder, my_metadata_callback);
  89060. * FLAC__seekable_stream_decoder_set_error_callback(decoder, my_error_callback);
  89061. * FLAC__seekable_stream_decoder_set_client_data(decoder, my_client_data);
  89062. * if(FLAC__seekable_stream_decoder_init(decoder) != FLAC__SEEKABLE_STREAM_DECODER_OK) do_something;
  89063. * \endcode
  89064. *
  89065. * In FLAC 1.1.3 it is like this:
  89066. *
  89067. * \code
  89068. * FLAC__StreamDecoder *decoder = FLAC__stream_decoder_new();
  89069. * if(decoder == NULL) do_something;
  89070. * FLAC__stream_decoder_set_md5_checking(decoder, true);
  89071. * [... other settings ...]
  89072. * if(FLAC__stream_decoder_init_stream(
  89073. * decoder,
  89074. * my_read_callback,
  89075. * my_seek_callback, // or NULL
  89076. * my_tell_callback, // or NULL
  89077. * my_length_callback, // or NULL
  89078. * my_eof_callback, // or NULL
  89079. * my_write_callback,
  89080. * my_metadata_callback, // or NULL
  89081. * my_error_callback,
  89082. * my_client_data
  89083. * ) != FLAC__STREAM_DECODER_INIT_STATUS_OK) do_something;
  89084. * \endcode
  89085. *
  89086. * or you could do;
  89087. *
  89088. * \code
  89089. * [...]
  89090. * FILE *file = fopen("somefile.flac","rb");
  89091. * if(file == NULL) do_somthing;
  89092. * if(FLAC__stream_decoder_init_FILE(
  89093. * decoder,
  89094. * file,
  89095. * my_write_callback,
  89096. * my_metadata_callback, // or NULL
  89097. * my_error_callback,
  89098. * my_client_data
  89099. * ) != FLAC__STREAM_DECODER_INIT_STATUS_OK) do_something;
  89100. * \endcode
  89101. *
  89102. * or just:
  89103. *
  89104. * \code
  89105. * [...]
  89106. * if(FLAC__stream_decoder_init_file(
  89107. * decoder,
  89108. * "somefile.flac",
  89109. * my_write_callback,
  89110. * my_metadata_callback, // or NULL
  89111. * my_error_callback,
  89112. * my_client_data
  89113. * ) != FLAC__STREAM_DECODER_INIT_STATUS_OK) do_something;
  89114. * \endcode
  89115. *
  89116. * Another small change to the decoder is in how it handles unparseable
  89117. * streams. Before, when the decoder found an unparseable stream
  89118. * (reserved for when the decoder encounters a stream from a future
  89119. * encoder that it can't parse), it changed the state to
  89120. * \c FLAC__STREAM_DECODER_UNPARSEABLE_STREAM. Now the decoder instead
  89121. * drops sync and calls the error callback with a new error code
  89122. * \c FLAC__STREAM_DECODER_ERROR_STATUS_UNPARSEABLE_STREAM. This is
  89123. * more robust. If your error callback does not discriminate on the the
  89124. * error state, your code does not need to be changed.
  89125. *
  89126. * The encoder now has a new setting:
  89127. * FLAC__stream_encoder_set_apodization(). This is for setting the
  89128. * method used to window the data before LPC analysis. You only need to
  89129. * add a call to this function if the default is not suitable. There
  89130. * are also two new convenience functions that may be useful:
  89131. * FLAC__metadata_object_cuesheet_calculate_cddb_id() and
  89132. * FLAC__metadata_get_cuesheet().
  89133. *
  89134. * The \a bytes parameter to FLAC__StreamDecoderReadCallback,
  89135. * FLAC__StreamEncoderReadCallback, and FLAC__StreamEncoderWriteCallback
  89136. * is now \c size_t instead of \c unsigned.
  89137. */
  89138. /** \defgroup porting_1_1_3_to_1_1_4 Porting from FLAC 1.1.3 to 1.1.4
  89139. * \ingroup porting
  89140. *
  89141. * \brief
  89142. * This module describes porting from FLAC 1.1.3 to FLAC 1.1.4.
  89143. *
  89144. * There were no changes to any of the interfaces from 1.1.3 to 1.1.4.
  89145. * There was a slight change in the implementation of
  89146. * FLAC__stream_encoder_set_metadata(); the function now makes a copy
  89147. * of the \a metadata array of pointers so the client no longer needs
  89148. * to maintain it after the call. The objects themselves that are
  89149. * pointed to by the array are still not copied though and must be
  89150. * maintained until the call to FLAC__stream_encoder_finish().
  89151. */
  89152. /** \defgroup porting_1_1_4_to_1_2_0 Porting from FLAC 1.1.4 to 1.2.0
  89153. * \ingroup porting
  89154. *
  89155. * \brief
  89156. * This module describes porting from FLAC 1.1.4 to FLAC 1.2.0.
  89157. *
  89158. * There were only very minor changes to the interfaces from 1.1.4 to 1.2.0.
  89159. * In libFLAC, \c FLAC__format_sample_rate_is_subset() was added.
  89160. * In libFLAC++, \c FLAC::Decoder::Stream::get_decode_position() was added.
  89161. *
  89162. * Finally, value of the constant \c FLAC__FRAME_HEADER_RESERVED_LEN
  89163. * has changed to reflect the conversion of one of the reserved bits
  89164. * into active use. It used to be \c 2 and now is \c 1. However the
  89165. * FLAC frame header length has not changed, so to skip the proper
  89166. * number of bits, use \c FLAC__FRAME_HEADER_RESERVED_LEN +
  89167. * \c FLAC__FRAME_HEADER_BLOCKING_STRATEGY_LEN
  89168. */
  89169. /** \defgroup flac FLAC C API
  89170. *
  89171. * The FLAC C API is the interface to libFLAC, a set of structures
  89172. * describing the components of FLAC streams, and functions for
  89173. * encoding and decoding streams, as well as manipulating FLAC
  89174. * metadata in files.
  89175. *
  89176. * You should start with the format components as all other modules
  89177. * are dependent on it.
  89178. */
  89179. #endif
  89180. /*** End of inlined file: all.h ***/
  89181. /*** Start of inlined file: bitmath.c ***/
  89182. /*** Start of inlined file: juce_FlacHeader.h ***/
  89183. // This file is included at the start of each FLAC .c file, just to do a few housekeeping
  89184. // tasks..
  89185. #define VERSION "1.2.1"
  89186. #define FLAC__NO_DLL 1
  89187. #if JUCE_MSVC
  89188. #pragma warning (disable: 4267 4127 4244 4996 4100 4701 4702 4013 4133 4206 4312)
  89189. #endif
  89190. #if JUCE_MAC
  89191. #define FLAC__SYS_DARWIN 1
  89192. #endif
  89193. /*** End of inlined file: juce_FlacHeader.h ***/
  89194. #if JUCE_USE_FLAC
  89195. #if HAVE_CONFIG_H
  89196. # include <config.h>
  89197. #endif
  89198. /*** Start of inlined file: bitmath.h ***/
  89199. #ifndef FLAC__PRIVATE__BITMATH_H
  89200. #define FLAC__PRIVATE__BITMATH_H
  89201. unsigned FLAC__bitmath_ilog2(FLAC__uint32 v);
  89202. unsigned FLAC__bitmath_ilog2_wide(FLAC__uint64 v);
  89203. unsigned FLAC__bitmath_silog2(int v);
  89204. unsigned FLAC__bitmath_silog2_wide(FLAC__int64 v);
  89205. #endif
  89206. /*** End of inlined file: bitmath.h ***/
  89207. /* An example of what FLAC__bitmath_ilog2() computes:
  89208. *
  89209. * ilog2( 0) = assertion failure
  89210. * ilog2( 1) = 0
  89211. * ilog2( 2) = 1
  89212. * ilog2( 3) = 1
  89213. * ilog2( 4) = 2
  89214. * ilog2( 5) = 2
  89215. * ilog2( 6) = 2
  89216. * ilog2( 7) = 2
  89217. * ilog2( 8) = 3
  89218. * ilog2( 9) = 3
  89219. * ilog2(10) = 3
  89220. * ilog2(11) = 3
  89221. * ilog2(12) = 3
  89222. * ilog2(13) = 3
  89223. * ilog2(14) = 3
  89224. * ilog2(15) = 3
  89225. * ilog2(16) = 4
  89226. * ilog2(17) = 4
  89227. * ilog2(18) = 4
  89228. */
  89229. unsigned FLAC__bitmath_ilog2(FLAC__uint32 v)
  89230. {
  89231. unsigned l = 0;
  89232. FLAC__ASSERT(v > 0);
  89233. while(v >>= 1)
  89234. l++;
  89235. return l;
  89236. }
  89237. unsigned FLAC__bitmath_ilog2_wide(FLAC__uint64 v)
  89238. {
  89239. unsigned l = 0;
  89240. FLAC__ASSERT(v > 0);
  89241. while(v >>= 1)
  89242. l++;
  89243. return l;
  89244. }
  89245. /* An example of what FLAC__bitmath_silog2() computes:
  89246. *
  89247. * silog2(-10) = 5
  89248. * silog2(- 9) = 5
  89249. * silog2(- 8) = 4
  89250. * silog2(- 7) = 4
  89251. * silog2(- 6) = 4
  89252. * silog2(- 5) = 4
  89253. * silog2(- 4) = 3
  89254. * silog2(- 3) = 3
  89255. * silog2(- 2) = 2
  89256. * silog2(- 1) = 2
  89257. * silog2( 0) = 0
  89258. * silog2( 1) = 2
  89259. * silog2( 2) = 3
  89260. * silog2( 3) = 3
  89261. * silog2( 4) = 4
  89262. * silog2( 5) = 4
  89263. * silog2( 6) = 4
  89264. * silog2( 7) = 4
  89265. * silog2( 8) = 5
  89266. * silog2( 9) = 5
  89267. * silog2( 10) = 5
  89268. */
  89269. unsigned FLAC__bitmath_silog2(int v)
  89270. {
  89271. while(1) {
  89272. if(v == 0) {
  89273. return 0;
  89274. }
  89275. else if(v > 0) {
  89276. unsigned l = 0;
  89277. while(v) {
  89278. l++;
  89279. v >>= 1;
  89280. }
  89281. return l+1;
  89282. }
  89283. else if(v == -1) {
  89284. return 2;
  89285. }
  89286. else {
  89287. v++;
  89288. v = -v;
  89289. }
  89290. }
  89291. }
  89292. unsigned FLAC__bitmath_silog2_wide(FLAC__int64 v)
  89293. {
  89294. while(1) {
  89295. if(v == 0) {
  89296. return 0;
  89297. }
  89298. else if(v > 0) {
  89299. unsigned l = 0;
  89300. while(v) {
  89301. l++;
  89302. v >>= 1;
  89303. }
  89304. return l+1;
  89305. }
  89306. else if(v == -1) {
  89307. return 2;
  89308. }
  89309. else {
  89310. v++;
  89311. v = -v;
  89312. }
  89313. }
  89314. }
  89315. #endif
  89316. /*** End of inlined file: bitmath.c ***/
  89317. /*** Start of inlined file: bitreader.c ***/
  89318. /*** Start of inlined file: juce_FlacHeader.h ***/
  89319. // This file is included at the start of each FLAC .c file, just to do a few housekeeping
  89320. // tasks..
  89321. #define VERSION "1.2.1"
  89322. #define FLAC__NO_DLL 1
  89323. #if JUCE_MSVC
  89324. #pragma warning (disable: 4267 4127 4244 4996 4100 4701 4702 4013 4133 4206 4312)
  89325. #endif
  89326. #if JUCE_MAC
  89327. #define FLAC__SYS_DARWIN 1
  89328. #endif
  89329. /*** End of inlined file: juce_FlacHeader.h ***/
  89330. #if JUCE_USE_FLAC
  89331. #if HAVE_CONFIG_H
  89332. # include <config.h>
  89333. #endif
  89334. #include <stdlib.h> /* for malloc() */
  89335. #include <string.h> /* for memcpy(), memset() */
  89336. #ifdef _MSC_VER
  89337. #include <winsock.h> /* for ntohl() */
  89338. #elif defined FLAC__SYS_DARWIN
  89339. #include <machine/endian.h> /* for ntohl() */
  89340. #elif defined __MINGW32__
  89341. #include <winsock.h> /* for ntohl() */
  89342. #else
  89343. #include <netinet/in.h> /* for ntohl() */
  89344. #endif
  89345. /*** Start of inlined file: bitreader.h ***/
  89346. #ifndef FLAC__PRIVATE__BITREADER_H
  89347. #define FLAC__PRIVATE__BITREADER_H
  89348. #include <stdio.h> /* for FILE */
  89349. /*** Start of inlined file: cpu.h ***/
  89350. #ifndef FLAC__PRIVATE__CPU_H
  89351. #define FLAC__PRIVATE__CPU_H
  89352. #ifdef HAVE_CONFIG_H
  89353. #include <config.h>
  89354. #endif
  89355. typedef enum {
  89356. FLAC__CPUINFO_TYPE_IA32,
  89357. FLAC__CPUINFO_TYPE_PPC,
  89358. FLAC__CPUINFO_TYPE_UNKNOWN
  89359. } FLAC__CPUInfo_Type;
  89360. typedef struct {
  89361. FLAC__bool cpuid;
  89362. FLAC__bool bswap;
  89363. FLAC__bool cmov;
  89364. FLAC__bool mmx;
  89365. FLAC__bool fxsr;
  89366. FLAC__bool sse;
  89367. FLAC__bool sse2;
  89368. FLAC__bool sse3;
  89369. FLAC__bool ssse3;
  89370. FLAC__bool _3dnow;
  89371. FLAC__bool ext3dnow;
  89372. FLAC__bool extmmx;
  89373. } FLAC__CPUInfo_IA32;
  89374. typedef struct {
  89375. FLAC__bool altivec;
  89376. FLAC__bool ppc64;
  89377. } FLAC__CPUInfo_PPC;
  89378. typedef struct {
  89379. FLAC__bool use_asm;
  89380. FLAC__CPUInfo_Type type;
  89381. union {
  89382. FLAC__CPUInfo_IA32 ia32;
  89383. FLAC__CPUInfo_PPC ppc;
  89384. } data;
  89385. } FLAC__CPUInfo;
  89386. void FLAC__cpu_info(FLAC__CPUInfo *info);
  89387. #ifndef FLAC__NO_ASM
  89388. #ifdef FLAC__CPU_IA32
  89389. #ifdef FLAC__HAS_NASM
  89390. FLAC__uint32 FLAC__cpu_have_cpuid_asm_ia32(void);
  89391. void FLAC__cpu_info_asm_ia32(FLAC__uint32 *flags_edx, FLAC__uint32 *flags_ecx);
  89392. FLAC__uint32 FLAC__cpu_info_extended_amd_asm_ia32(void);
  89393. #endif
  89394. #endif
  89395. #endif
  89396. #endif
  89397. /*** End of inlined file: cpu.h ***/
  89398. /*
  89399. * opaque structure definition
  89400. */
  89401. struct FLAC__BitReader;
  89402. typedef struct FLAC__BitReader FLAC__BitReader;
  89403. typedef FLAC__bool (*FLAC__BitReaderReadCallback)(FLAC__byte buffer[], size_t *bytes, void *client_data);
  89404. /*
  89405. * construction, deletion, initialization, etc functions
  89406. */
  89407. FLAC__BitReader *FLAC__bitreader_new(void);
  89408. void FLAC__bitreader_delete(FLAC__BitReader *br);
  89409. FLAC__bool FLAC__bitreader_init(FLAC__BitReader *br, FLAC__CPUInfo cpu, FLAC__BitReaderReadCallback rcb, void *cd);
  89410. void FLAC__bitreader_free(FLAC__BitReader *br); /* does not 'free(br)' */
  89411. FLAC__bool FLAC__bitreader_clear(FLAC__BitReader *br);
  89412. void FLAC__bitreader_dump(const FLAC__BitReader *br, FILE *out);
  89413. /*
  89414. * CRC functions
  89415. */
  89416. void FLAC__bitreader_reset_read_crc16(FLAC__BitReader *br, FLAC__uint16 seed);
  89417. FLAC__uint16 FLAC__bitreader_get_read_crc16(FLAC__BitReader *br);
  89418. /*
  89419. * info functions
  89420. */
  89421. FLAC__bool FLAC__bitreader_is_consumed_byte_aligned(const FLAC__BitReader *br);
  89422. unsigned FLAC__bitreader_bits_left_for_byte_alignment(const FLAC__BitReader *br);
  89423. unsigned FLAC__bitreader_get_input_bits_unconsumed(const FLAC__BitReader *br);
  89424. /*
  89425. * read functions
  89426. */
  89427. FLAC__bool FLAC__bitreader_read_raw_uint32(FLAC__BitReader *br, FLAC__uint32 *val, unsigned bits);
  89428. FLAC__bool FLAC__bitreader_read_raw_int32(FLAC__BitReader *br, FLAC__int32 *val, unsigned bits);
  89429. FLAC__bool FLAC__bitreader_read_raw_uint64(FLAC__BitReader *br, FLAC__uint64 *val, unsigned bits);
  89430. FLAC__bool FLAC__bitreader_read_uint32_little_endian(FLAC__BitReader *br, FLAC__uint32 *val); /*only for bits=32*/
  89431. FLAC__bool FLAC__bitreader_skip_bits_no_crc(FLAC__BitReader *br, unsigned bits); /* WATCHOUT: does not CRC the skipped data! */ /*@@@@ add to unit tests */
  89432. FLAC__bool FLAC__bitreader_skip_byte_block_aligned_no_crc(FLAC__BitReader *br, unsigned nvals); /* WATCHOUT: does not CRC the read data! */
  89433. 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! */
  89434. FLAC__bool FLAC__bitreader_read_unary_unsigned(FLAC__BitReader *br, unsigned *val);
  89435. FLAC__bool FLAC__bitreader_read_rice_signed(FLAC__BitReader *br, int *val, unsigned parameter);
  89436. FLAC__bool FLAC__bitreader_read_rice_signed_block(FLAC__BitReader *br, int vals[], unsigned nvals, unsigned parameter);
  89437. #ifndef FLAC__NO_ASM
  89438. # ifdef FLAC__CPU_IA32
  89439. # ifdef FLAC__HAS_NASM
  89440. FLAC__bool FLAC__bitreader_read_rice_signed_block_asm_ia32_bswap(FLAC__BitReader *br, int vals[], unsigned nvals, unsigned parameter);
  89441. # endif
  89442. # endif
  89443. #endif
  89444. #if 0 /* UNUSED */
  89445. FLAC__bool FLAC__bitreader_read_golomb_signed(FLAC__BitReader *br, int *val, unsigned parameter);
  89446. FLAC__bool FLAC__bitreader_read_golomb_unsigned(FLAC__BitReader *br, unsigned *val, unsigned parameter);
  89447. #endif
  89448. FLAC__bool FLAC__bitreader_read_utf8_uint32(FLAC__BitReader *br, FLAC__uint32 *val, FLAC__byte *raw, unsigned *rawlen);
  89449. FLAC__bool FLAC__bitreader_read_utf8_uint64(FLAC__BitReader *br, FLAC__uint64 *val, FLAC__byte *raw, unsigned *rawlen);
  89450. FLAC__bool bitreader_read_from_client_(FLAC__BitReader *br);
  89451. #endif
  89452. /*** End of inlined file: bitreader.h ***/
  89453. /*** Start of inlined file: crc.h ***/
  89454. #ifndef FLAC__PRIVATE__CRC_H
  89455. #define FLAC__PRIVATE__CRC_H
  89456. /* 8 bit CRC generator, MSB shifted first
  89457. ** polynomial = x^8 + x^2 + x^1 + x^0
  89458. ** init = 0
  89459. */
  89460. extern FLAC__byte const FLAC__crc8_table[256];
  89461. #define FLAC__CRC8_UPDATE(data, crc) (crc) = FLAC__crc8_table[(crc) ^ (data)];
  89462. void FLAC__crc8_update(const FLAC__byte data, FLAC__uint8 *crc);
  89463. void FLAC__crc8_update_block(const FLAC__byte *data, unsigned len, FLAC__uint8 *crc);
  89464. FLAC__uint8 FLAC__crc8(const FLAC__byte *data, unsigned len);
  89465. /* 16 bit CRC generator, MSB shifted first
  89466. ** polynomial = x^16 + x^15 + x^2 + x^0
  89467. ** init = 0
  89468. */
  89469. extern unsigned FLAC__crc16_table[256];
  89470. #define FLAC__CRC16_UPDATE(data, crc) (((((crc)<<8) & 0xffff) ^ FLAC__crc16_table[((crc)>>8) ^ (data)]))
  89471. /* this alternate may be faster on some systems/compilers */
  89472. #if 0
  89473. #define FLAC__CRC16_UPDATE(data, crc) ((((crc)<<8) ^ FLAC__crc16_table[((crc)>>8) ^ (data)]) & 0xffff)
  89474. #endif
  89475. unsigned FLAC__crc16(const FLAC__byte *data, unsigned len);
  89476. #endif
  89477. /*** End of inlined file: crc.h ***/
  89478. /* Things should be fastest when this matches the machine word size */
  89479. /* WATCHOUT: if you change this you must also change the following #defines down to COUNT_ZERO_MSBS below to match */
  89480. /* WATCHOUT: there are a few places where the code will not work unless brword is >= 32 bits wide */
  89481. /* also, some sections currently only have fast versions for 4 or 8 bytes per word */
  89482. typedef FLAC__uint32 brword;
  89483. #define FLAC__BYTES_PER_WORD 4
  89484. #define FLAC__BITS_PER_WORD 32
  89485. #define FLAC__WORD_ALL_ONES ((FLAC__uint32)0xffffffff)
  89486. /* SWAP_BE_WORD_TO_HOST swaps bytes in a brword (which is always big-endian) if necessary to match host byte order */
  89487. #if WORDS_BIGENDIAN
  89488. #define SWAP_BE_WORD_TO_HOST(x) (x)
  89489. #else
  89490. #if defined (_MSC_VER) && defined (_X86_)
  89491. #define SWAP_BE_WORD_TO_HOST(x) local_swap32_(x)
  89492. #else
  89493. #define SWAP_BE_WORD_TO_HOST(x) ntohl(x)
  89494. #endif
  89495. #endif
  89496. /* counts the # of zero MSBs in a word */
  89497. #define COUNT_ZERO_MSBS(word) ( \
  89498. (word) <= 0xffff ? \
  89499. ( (word) <= 0xff? byte_to_unary_table[word] + 24 : byte_to_unary_table[(word) >> 8] + 16 ) : \
  89500. ( (word) <= 0xffffff? byte_to_unary_table[word >> 16] + 8 : byte_to_unary_table[(word) >> 24] ) \
  89501. )
  89502. /* this alternate might be slightly faster on some systems/compilers: */
  89503. #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])) )
  89504. /*
  89505. * This should be at least twice as large as the largest number of words
  89506. * required to represent any 'number' (in any encoding) you are going to
  89507. * read. With FLAC this is on the order of maybe a few hundred bits.
  89508. * If the buffer is smaller than that, the decoder won't be able to read
  89509. * in a whole number that is in a variable length encoding (e.g. Rice).
  89510. * But to be practical it should be at least 1K bytes.
  89511. *
  89512. * Increase this number to decrease the number of read callbacks, at the
  89513. * expense of using more memory. Or decrease for the reverse effect,
  89514. * keeping in mind the limit from the first paragraph. The optimal size
  89515. * also depends on the CPU cache size and other factors; some twiddling
  89516. * may be necessary to squeeze out the best performance.
  89517. */
  89518. static const unsigned FLAC__BITREADER_DEFAULT_CAPACITY = 65536u / FLAC__BITS_PER_WORD; /* in words */
  89519. static const unsigned char byte_to_unary_table[] = {
  89520. 8, 7, 6, 6, 5, 5, 5, 5, 4, 4, 4, 4, 4, 4, 4, 4,
  89521. 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3,
  89522. 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2,
  89523. 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2,
  89524. 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1,
  89525. 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1,
  89526. 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1,
  89527. 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1,
  89528. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  89529. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  89530. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  89531. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  89532. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  89533. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  89534. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  89535. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0
  89536. };
  89537. #ifdef min
  89538. #undef min
  89539. #endif
  89540. #define min(x,y) ((x)<(y)?(x):(y))
  89541. #ifdef max
  89542. #undef max
  89543. #endif
  89544. #define max(x,y) ((x)>(y)?(x):(y))
  89545. /* adjust for compilers that can't understand using LLU suffix for uint64_t literals */
  89546. #ifdef _MSC_VER
  89547. #define FLAC__U64L(x) x
  89548. #else
  89549. #define FLAC__U64L(x) x##LLU
  89550. #endif
  89551. #ifndef FLaC__INLINE
  89552. #define FLaC__INLINE
  89553. #endif
  89554. /* WATCHOUT: assembly routines rely on the order in which these fields are declared */
  89555. struct FLAC__BitReader {
  89556. /* any partially-consumed word at the head will stay right-justified as bits are consumed from the left */
  89557. /* any incomplete word at the tail will be left-justified, and bytes from the read callback are added on the right */
  89558. brword *buffer;
  89559. unsigned capacity; /* in words */
  89560. unsigned words; /* # of completed words in buffer */
  89561. unsigned bytes; /* # of bytes in incomplete word at buffer[words] */
  89562. unsigned consumed_words; /* #words ... */
  89563. unsigned consumed_bits; /* ... + (#bits of head word) already consumed from the front of buffer */
  89564. unsigned read_crc16; /* the running frame CRC */
  89565. unsigned crc16_align; /* the number of bits in the current consumed word that should not be CRC'd */
  89566. FLAC__BitReaderReadCallback read_callback;
  89567. void *client_data;
  89568. FLAC__CPUInfo cpu_info;
  89569. };
  89570. static FLaC__INLINE void crc16_update_word_(FLAC__BitReader *br, brword word)
  89571. {
  89572. register unsigned crc = br->read_crc16;
  89573. #if FLAC__BYTES_PER_WORD == 4
  89574. switch(br->crc16_align) {
  89575. case 0: crc = FLAC__CRC16_UPDATE((unsigned)(word >> 24), crc);
  89576. case 8: crc = FLAC__CRC16_UPDATE((unsigned)((word >> 16) & 0xff), crc);
  89577. case 16: crc = FLAC__CRC16_UPDATE((unsigned)((word >> 8) & 0xff), crc);
  89578. case 24: br->read_crc16 = FLAC__CRC16_UPDATE((unsigned)(word & 0xff), crc);
  89579. }
  89580. #elif FLAC__BYTES_PER_WORD == 8
  89581. switch(br->crc16_align) {
  89582. case 0: crc = FLAC__CRC16_UPDATE((unsigned)(word >> 56), crc);
  89583. case 8: crc = FLAC__CRC16_UPDATE((unsigned)((word >> 48) & 0xff), crc);
  89584. case 16: crc = FLAC__CRC16_UPDATE((unsigned)((word >> 40) & 0xff), crc);
  89585. case 24: crc = FLAC__CRC16_UPDATE((unsigned)((word >> 32) & 0xff), crc);
  89586. case 32: crc = FLAC__CRC16_UPDATE((unsigned)((word >> 24) & 0xff), crc);
  89587. case 40: crc = FLAC__CRC16_UPDATE((unsigned)((word >> 16) & 0xff), crc);
  89588. case 48: crc = FLAC__CRC16_UPDATE((unsigned)((word >> 8) & 0xff), crc);
  89589. case 56: br->read_crc16 = FLAC__CRC16_UPDATE((unsigned)(word & 0xff), crc);
  89590. }
  89591. #else
  89592. for( ; br->crc16_align < FLAC__BITS_PER_WORD; br->crc16_align += 8)
  89593. crc = FLAC__CRC16_UPDATE((unsigned)((word >> (FLAC__BITS_PER_WORD-8-br->crc16_align)) & 0xff), crc);
  89594. br->read_crc16 = crc;
  89595. #endif
  89596. br->crc16_align = 0;
  89597. }
  89598. /* would be static except it needs to be called by asm routines */
  89599. FLAC__bool bitreader_read_from_client_(FLAC__BitReader *br)
  89600. {
  89601. unsigned start, end;
  89602. size_t bytes;
  89603. FLAC__byte *target;
  89604. /* first shift the unconsumed buffer data toward the front as much as possible */
  89605. if(br->consumed_words > 0) {
  89606. start = br->consumed_words;
  89607. end = br->words + (br->bytes? 1:0);
  89608. memmove(br->buffer, br->buffer+start, FLAC__BYTES_PER_WORD * (end - start));
  89609. br->words -= start;
  89610. br->consumed_words = 0;
  89611. }
  89612. /*
  89613. * set the target for reading, taking into account word alignment and endianness
  89614. */
  89615. bytes = (br->capacity - br->words) * FLAC__BYTES_PER_WORD - br->bytes;
  89616. if(bytes == 0)
  89617. return false; /* no space left, buffer is too small; see note for FLAC__BITREADER_DEFAULT_CAPACITY */
  89618. target = ((FLAC__byte*)(br->buffer+br->words)) + br->bytes;
  89619. /* before reading, if the existing reader looks like this (say brword is 32 bits wide)
  89620. * bitstream : 11 22 33 44 55 br->words=1 br->bytes=1 (partial tail word is left-justified)
  89621. * buffer[BE]: 11 22 33 44 55 ?? ?? ?? (shown layed out as bytes sequentially in memory)
  89622. * buffer[LE]: 44 33 22 11 ?? ?? ?? 55 (?? being don't-care)
  89623. * ^^-------target, bytes=3
  89624. * on LE machines, have to byteswap the odd tail word so nothing is
  89625. * overwritten:
  89626. */
  89627. #if WORDS_BIGENDIAN
  89628. #else
  89629. if(br->bytes)
  89630. br->buffer[br->words] = SWAP_BE_WORD_TO_HOST(br->buffer[br->words]);
  89631. #endif
  89632. /* now it looks like:
  89633. * bitstream : 11 22 33 44 55 br->words=1 br->bytes=1
  89634. * buffer[BE]: 11 22 33 44 55 ?? ?? ??
  89635. * buffer[LE]: 44 33 22 11 55 ?? ?? ??
  89636. * ^^-------target, bytes=3
  89637. */
  89638. /* read in the data; note that the callback may return a smaller number of bytes */
  89639. if(!br->read_callback(target, &bytes, br->client_data))
  89640. return false;
  89641. /* after reading bytes 66 77 88 99 AA BB CC DD EE FF from the client:
  89642. * bitstream : 11 22 33 44 55 66 77 88 99 AA BB CC DD EE FF
  89643. * buffer[BE]: 11 22 33 44 55 66 77 88 99 AA BB CC DD EE FF ??
  89644. * buffer[LE]: 44 33 22 11 55 66 77 88 99 AA BB CC DD EE FF ??
  89645. * now have to byteswap on LE machines:
  89646. */
  89647. #if WORDS_BIGENDIAN
  89648. #else
  89649. end = (br->words*FLAC__BYTES_PER_WORD + br->bytes + bytes + (FLAC__BYTES_PER_WORD-1)) / FLAC__BYTES_PER_WORD;
  89650. # if defined(_MSC_VER) && defined (_X86_) && (FLAC__BYTES_PER_WORD == 4)
  89651. if(br->cpu_info.type == FLAC__CPUINFO_TYPE_IA32 && br->cpu_info.data.ia32.bswap) {
  89652. start = br->words;
  89653. local_swap32_block_(br->buffer + start, end - start);
  89654. }
  89655. else
  89656. # endif
  89657. for(start = br->words; start < end; start++)
  89658. br->buffer[start] = SWAP_BE_WORD_TO_HOST(br->buffer[start]);
  89659. #endif
  89660. /* now it looks like:
  89661. * bitstream : 11 22 33 44 55 66 77 88 99 AA BB CC DD EE FF
  89662. * buffer[BE]: 11 22 33 44 55 66 77 88 99 AA BB CC DD EE FF ??
  89663. * buffer[LE]: 44 33 22 11 88 77 66 55 CC BB AA 99 ?? FF EE DD
  89664. * finally we'll update the reader values:
  89665. */
  89666. end = br->words*FLAC__BYTES_PER_WORD + br->bytes + bytes;
  89667. br->words = end / FLAC__BYTES_PER_WORD;
  89668. br->bytes = end % FLAC__BYTES_PER_WORD;
  89669. return true;
  89670. }
  89671. /***********************************************************************
  89672. *
  89673. * Class constructor/destructor
  89674. *
  89675. ***********************************************************************/
  89676. FLAC__BitReader *FLAC__bitreader_new(void)
  89677. {
  89678. FLAC__BitReader *br = (FLAC__BitReader*)calloc(1, sizeof(FLAC__BitReader));
  89679. /* calloc() implies:
  89680. memset(br, 0, sizeof(FLAC__BitReader));
  89681. br->buffer = 0;
  89682. br->capacity = 0;
  89683. br->words = br->bytes = 0;
  89684. br->consumed_words = br->consumed_bits = 0;
  89685. br->read_callback = 0;
  89686. br->client_data = 0;
  89687. */
  89688. return br;
  89689. }
  89690. void FLAC__bitreader_delete(FLAC__BitReader *br)
  89691. {
  89692. FLAC__ASSERT(0 != br);
  89693. FLAC__bitreader_free(br);
  89694. free(br);
  89695. }
  89696. /***********************************************************************
  89697. *
  89698. * Public class methods
  89699. *
  89700. ***********************************************************************/
  89701. FLAC__bool FLAC__bitreader_init(FLAC__BitReader *br, FLAC__CPUInfo cpu, FLAC__BitReaderReadCallback rcb, void *cd)
  89702. {
  89703. FLAC__ASSERT(0 != br);
  89704. br->words = br->bytes = 0;
  89705. br->consumed_words = br->consumed_bits = 0;
  89706. br->capacity = FLAC__BITREADER_DEFAULT_CAPACITY;
  89707. br->buffer = (brword*)malloc(sizeof(brword) * br->capacity);
  89708. if(br->buffer == 0)
  89709. return false;
  89710. br->read_callback = rcb;
  89711. br->client_data = cd;
  89712. br->cpu_info = cpu;
  89713. return true;
  89714. }
  89715. void FLAC__bitreader_free(FLAC__BitReader *br)
  89716. {
  89717. FLAC__ASSERT(0 != br);
  89718. if(0 != br->buffer)
  89719. free(br->buffer);
  89720. br->buffer = 0;
  89721. br->capacity = 0;
  89722. br->words = br->bytes = 0;
  89723. br->consumed_words = br->consumed_bits = 0;
  89724. br->read_callback = 0;
  89725. br->client_data = 0;
  89726. }
  89727. FLAC__bool FLAC__bitreader_clear(FLAC__BitReader *br)
  89728. {
  89729. br->words = br->bytes = 0;
  89730. br->consumed_words = br->consumed_bits = 0;
  89731. return true;
  89732. }
  89733. void FLAC__bitreader_dump(const FLAC__BitReader *br, FILE *out)
  89734. {
  89735. unsigned i, j;
  89736. if(br == 0) {
  89737. fprintf(out, "bitreader is NULL\n");
  89738. }
  89739. else {
  89740. 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);
  89741. for(i = 0; i < br->words; i++) {
  89742. fprintf(out, "%08X: ", i);
  89743. for(j = 0; j < FLAC__BITS_PER_WORD; j++)
  89744. if(i < br->consumed_words || (i == br->consumed_words && j < br->consumed_bits))
  89745. fprintf(out, ".");
  89746. else
  89747. fprintf(out, "%01u", br->buffer[i] & (1 << (FLAC__BITS_PER_WORD-j-1)) ? 1:0);
  89748. fprintf(out, "\n");
  89749. }
  89750. if(br->bytes > 0) {
  89751. fprintf(out, "%08X: ", i);
  89752. for(j = 0; j < br->bytes*8; j++)
  89753. if(i < br->consumed_words || (i == br->consumed_words && j < br->consumed_bits))
  89754. fprintf(out, ".");
  89755. else
  89756. fprintf(out, "%01u", br->buffer[i] & (1 << (br->bytes*8-j-1)) ? 1:0);
  89757. fprintf(out, "\n");
  89758. }
  89759. }
  89760. }
  89761. void FLAC__bitreader_reset_read_crc16(FLAC__BitReader *br, FLAC__uint16 seed)
  89762. {
  89763. FLAC__ASSERT(0 != br);
  89764. FLAC__ASSERT(0 != br->buffer);
  89765. FLAC__ASSERT((br->consumed_bits & 7) == 0);
  89766. br->read_crc16 = (unsigned)seed;
  89767. br->crc16_align = br->consumed_bits;
  89768. }
  89769. FLAC__uint16 FLAC__bitreader_get_read_crc16(FLAC__BitReader *br)
  89770. {
  89771. FLAC__ASSERT(0 != br);
  89772. FLAC__ASSERT(0 != br->buffer);
  89773. FLAC__ASSERT((br->consumed_bits & 7) == 0);
  89774. FLAC__ASSERT(br->crc16_align <= br->consumed_bits);
  89775. /* CRC any tail bytes in a partially-consumed word */
  89776. if(br->consumed_bits) {
  89777. const brword tail = br->buffer[br->consumed_words];
  89778. for( ; br->crc16_align < br->consumed_bits; br->crc16_align += 8)
  89779. br->read_crc16 = FLAC__CRC16_UPDATE((unsigned)((tail >> (FLAC__BITS_PER_WORD-8-br->crc16_align)) & 0xff), br->read_crc16);
  89780. }
  89781. return br->read_crc16;
  89782. }
  89783. FLaC__INLINE FLAC__bool FLAC__bitreader_is_consumed_byte_aligned(const FLAC__BitReader *br)
  89784. {
  89785. return ((br->consumed_bits & 7) == 0);
  89786. }
  89787. FLaC__INLINE unsigned FLAC__bitreader_bits_left_for_byte_alignment(const FLAC__BitReader *br)
  89788. {
  89789. return 8 - (br->consumed_bits & 7);
  89790. }
  89791. FLaC__INLINE unsigned FLAC__bitreader_get_input_bits_unconsumed(const FLAC__BitReader *br)
  89792. {
  89793. return (br->words-br->consumed_words)*FLAC__BITS_PER_WORD + br->bytes*8 - br->consumed_bits;
  89794. }
  89795. FLaC__INLINE FLAC__bool FLAC__bitreader_read_raw_uint32(FLAC__BitReader *br, FLAC__uint32 *val, unsigned bits)
  89796. {
  89797. FLAC__ASSERT(0 != br);
  89798. FLAC__ASSERT(0 != br->buffer);
  89799. FLAC__ASSERT(bits <= 32);
  89800. FLAC__ASSERT((br->capacity*FLAC__BITS_PER_WORD) * 2 >= bits);
  89801. FLAC__ASSERT(br->consumed_words <= br->words);
  89802. /* WATCHOUT: code does not work with <32bit words; we can make things much faster with this assertion */
  89803. FLAC__ASSERT(FLAC__BITS_PER_WORD >= 32);
  89804. if(bits == 0) { /* OPT: investigate if this can ever happen, maybe change to assertion */
  89805. *val = 0;
  89806. return true;
  89807. }
  89808. while((br->words-br->consumed_words)*FLAC__BITS_PER_WORD + br->bytes*8 - br->consumed_bits < bits) {
  89809. if(!bitreader_read_from_client_(br))
  89810. return false;
  89811. }
  89812. if(br->consumed_words < br->words) { /* if we've not consumed up to a partial tail word... */
  89813. /* OPT: taking out the consumed_bits==0 "else" case below might make things faster if less code allows the compiler to inline this function */
  89814. if(br->consumed_bits) {
  89815. /* this also works when consumed_bits==0, it's just a little slower than necessary for that case */
  89816. const unsigned n = FLAC__BITS_PER_WORD - br->consumed_bits;
  89817. const brword word = br->buffer[br->consumed_words];
  89818. if(bits < n) {
  89819. *val = (word & (FLAC__WORD_ALL_ONES >> br->consumed_bits)) >> (n-bits);
  89820. br->consumed_bits += bits;
  89821. return true;
  89822. }
  89823. *val = word & (FLAC__WORD_ALL_ONES >> br->consumed_bits);
  89824. bits -= n;
  89825. crc16_update_word_(br, word);
  89826. br->consumed_words++;
  89827. br->consumed_bits = 0;
  89828. 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 */
  89829. *val <<= bits;
  89830. *val |= (br->buffer[br->consumed_words] >> (FLAC__BITS_PER_WORD-bits));
  89831. br->consumed_bits = bits;
  89832. }
  89833. return true;
  89834. }
  89835. else {
  89836. const brword word = br->buffer[br->consumed_words];
  89837. if(bits < FLAC__BITS_PER_WORD) {
  89838. *val = word >> (FLAC__BITS_PER_WORD-bits);
  89839. br->consumed_bits = bits;
  89840. return true;
  89841. }
  89842. /* at this point 'bits' must be == FLAC__BITS_PER_WORD; because of previous assertions, it can't be larger */
  89843. *val = word;
  89844. crc16_update_word_(br, word);
  89845. br->consumed_words++;
  89846. return true;
  89847. }
  89848. }
  89849. else {
  89850. /* in this case we're starting our read at a partial tail word;
  89851. * the reader has guaranteed that we have at least 'bits' bits
  89852. * available to read, which makes this case simpler.
  89853. */
  89854. /* OPT: taking out the consumed_bits==0 "else" case below might make things faster if less code allows the compiler to inline this function */
  89855. if(br->consumed_bits) {
  89856. /* this also works when consumed_bits==0, it's just a little slower than necessary for that case */
  89857. FLAC__ASSERT(br->consumed_bits + bits <= br->bytes*8);
  89858. *val = (br->buffer[br->consumed_words] & (FLAC__WORD_ALL_ONES >> br->consumed_bits)) >> (FLAC__BITS_PER_WORD-br->consumed_bits-bits);
  89859. br->consumed_bits += bits;
  89860. return true;
  89861. }
  89862. else {
  89863. *val = br->buffer[br->consumed_words] >> (FLAC__BITS_PER_WORD-bits);
  89864. br->consumed_bits += bits;
  89865. return true;
  89866. }
  89867. }
  89868. }
  89869. FLAC__bool FLAC__bitreader_read_raw_int32(FLAC__BitReader *br, FLAC__int32 *val, unsigned bits)
  89870. {
  89871. /* OPT: inline raw uint32 code here, or make into a macro if possible in the .h file */
  89872. if(!FLAC__bitreader_read_raw_uint32(br, (FLAC__uint32*)val, bits))
  89873. return false;
  89874. /* sign-extend: */
  89875. *val <<= (32-bits);
  89876. *val >>= (32-bits);
  89877. return true;
  89878. }
  89879. FLAC__bool FLAC__bitreader_read_raw_uint64(FLAC__BitReader *br, FLAC__uint64 *val, unsigned bits)
  89880. {
  89881. FLAC__uint32 hi, lo;
  89882. if(bits > 32) {
  89883. if(!FLAC__bitreader_read_raw_uint32(br, &hi, bits-32))
  89884. return false;
  89885. if(!FLAC__bitreader_read_raw_uint32(br, &lo, 32))
  89886. return false;
  89887. *val = hi;
  89888. *val <<= 32;
  89889. *val |= lo;
  89890. }
  89891. else {
  89892. if(!FLAC__bitreader_read_raw_uint32(br, &lo, bits))
  89893. return false;
  89894. *val = lo;
  89895. }
  89896. return true;
  89897. }
  89898. FLaC__INLINE FLAC__bool FLAC__bitreader_read_uint32_little_endian(FLAC__BitReader *br, FLAC__uint32 *val)
  89899. {
  89900. FLAC__uint32 x8, x32 = 0;
  89901. /* this doesn't need to be that fast as currently it is only used for vorbis comments */
  89902. if(!FLAC__bitreader_read_raw_uint32(br, &x32, 8))
  89903. return false;
  89904. if(!FLAC__bitreader_read_raw_uint32(br, &x8, 8))
  89905. return false;
  89906. x32 |= (x8 << 8);
  89907. if(!FLAC__bitreader_read_raw_uint32(br, &x8, 8))
  89908. return false;
  89909. x32 |= (x8 << 16);
  89910. if(!FLAC__bitreader_read_raw_uint32(br, &x8, 8))
  89911. return false;
  89912. x32 |= (x8 << 24);
  89913. *val = x32;
  89914. return true;
  89915. }
  89916. FLAC__bool FLAC__bitreader_skip_bits_no_crc(FLAC__BitReader *br, unsigned bits)
  89917. {
  89918. /*
  89919. * OPT: a faster implementation is possible but probably not that useful
  89920. * since this is only called a couple of times in the metadata readers.
  89921. */
  89922. FLAC__ASSERT(0 != br);
  89923. FLAC__ASSERT(0 != br->buffer);
  89924. if(bits > 0) {
  89925. const unsigned n = br->consumed_bits & 7;
  89926. unsigned m;
  89927. FLAC__uint32 x;
  89928. if(n != 0) {
  89929. m = min(8-n, bits);
  89930. if(!FLAC__bitreader_read_raw_uint32(br, &x, m))
  89931. return false;
  89932. bits -= m;
  89933. }
  89934. m = bits / 8;
  89935. if(m > 0) {
  89936. if(!FLAC__bitreader_skip_byte_block_aligned_no_crc(br, m))
  89937. return false;
  89938. bits %= 8;
  89939. }
  89940. if(bits > 0) {
  89941. if(!FLAC__bitreader_read_raw_uint32(br, &x, bits))
  89942. return false;
  89943. }
  89944. }
  89945. return true;
  89946. }
  89947. FLAC__bool FLAC__bitreader_skip_byte_block_aligned_no_crc(FLAC__BitReader *br, unsigned nvals)
  89948. {
  89949. FLAC__uint32 x;
  89950. FLAC__ASSERT(0 != br);
  89951. FLAC__ASSERT(0 != br->buffer);
  89952. FLAC__ASSERT(FLAC__bitreader_is_consumed_byte_aligned(br));
  89953. /* step 1: skip over partial head word to get word aligned */
  89954. while(nvals && br->consumed_bits) { /* i.e. run until we read 'nvals' bytes or we hit the end of the head word */
  89955. if(!FLAC__bitreader_read_raw_uint32(br, &x, 8))
  89956. return false;
  89957. nvals--;
  89958. }
  89959. if(0 == nvals)
  89960. return true;
  89961. /* step 2: skip whole words in chunks */
  89962. while(nvals >= FLAC__BYTES_PER_WORD) {
  89963. if(br->consumed_words < br->words) {
  89964. br->consumed_words++;
  89965. nvals -= FLAC__BYTES_PER_WORD;
  89966. }
  89967. else if(!bitreader_read_from_client_(br))
  89968. return false;
  89969. }
  89970. /* step 3: skip any remainder from partial tail bytes */
  89971. while(nvals) {
  89972. if(!FLAC__bitreader_read_raw_uint32(br, &x, 8))
  89973. return false;
  89974. nvals--;
  89975. }
  89976. return true;
  89977. }
  89978. FLAC__bool FLAC__bitreader_read_byte_block_aligned_no_crc(FLAC__BitReader *br, FLAC__byte *val, unsigned nvals)
  89979. {
  89980. FLAC__uint32 x;
  89981. FLAC__ASSERT(0 != br);
  89982. FLAC__ASSERT(0 != br->buffer);
  89983. FLAC__ASSERT(FLAC__bitreader_is_consumed_byte_aligned(br));
  89984. /* step 1: read from partial head word to get word aligned */
  89985. while(nvals && br->consumed_bits) { /* i.e. run until we read 'nvals' bytes or we hit the end of the head word */
  89986. if(!FLAC__bitreader_read_raw_uint32(br, &x, 8))
  89987. return false;
  89988. *val++ = (FLAC__byte)x;
  89989. nvals--;
  89990. }
  89991. if(0 == nvals)
  89992. return true;
  89993. /* step 2: read whole words in chunks */
  89994. while(nvals >= FLAC__BYTES_PER_WORD) {
  89995. if(br->consumed_words < br->words) {
  89996. const brword word = br->buffer[br->consumed_words++];
  89997. #if FLAC__BYTES_PER_WORD == 4
  89998. val[0] = (FLAC__byte)(word >> 24);
  89999. val[1] = (FLAC__byte)(word >> 16);
  90000. val[2] = (FLAC__byte)(word >> 8);
  90001. val[3] = (FLAC__byte)word;
  90002. #elif FLAC__BYTES_PER_WORD == 8
  90003. val[0] = (FLAC__byte)(word >> 56);
  90004. val[1] = (FLAC__byte)(word >> 48);
  90005. val[2] = (FLAC__byte)(word >> 40);
  90006. val[3] = (FLAC__byte)(word >> 32);
  90007. val[4] = (FLAC__byte)(word >> 24);
  90008. val[5] = (FLAC__byte)(word >> 16);
  90009. val[6] = (FLAC__byte)(word >> 8);
  90010. val[7] = (FLAC__byte)word;
  90011. #else
  90012. for(x = 0; x < FLAC__BYTES_PER_WORD; x++)
  90013. val[x] = (FLAC__byte)(word >> (8*(FLAC__BYTES_PER_WORD-x-1)));
  90014. #endif
  90015. val += FLAC__BYTES_PER_WORD;
  90016. nvals -= FLAC__BYTES_PER_WORD;
  90017. }
  90018. else if(!bitreader_read_from_client_(br))
  90019. return false;
  90020. }
  90021. /* step 3: read any remainder from partial tail bytes */
  90022. while(nvals) {
  90023. if(!FLAC__bitreader_read_raw_uint32(br, &x, 8))
  90024. return false;
  90025. *val++ = (FLAC__byte)x;
  90026. nvals--;
  90027. }
  90028. return true;
  90029. }
  90030. FLaC__INLINE FLAC__bool FLAC__bitreader_read_unary_unsigned(FLAC__BitReader *br, unsigned *val)
  90031. #if 0 /* slow but readable version */
  90032. {
  90033. unsigned bit;
  90034. FLAC__ASSERT(0 != br);
  90035. FLAC__ASSERT(0 != br->buffer);
  90036. *val = 0;
  90037. while(1) {
  90038. if(!FLAC__bitreader_read_bit(br, &bit))
  90039. return false;
  90040. if(bit)
  90041. break;
  90042. else
  90043. *val++;
  90044. }
  90045. return true;
  90046. }
  90047. #else
  90048. {
  90049. unsigned i;
  90050. FLAC__ASSERT(0 != br);
  90051. FLAC__ASSERT(0 != br->buffer);
  90052. *val = 0;
  90053. while(1) {
  90054. while(br->consumed_words < br->words) { /* if we've not consumed up to a partial tail word... */
  90055. brword b = br->buffer[br->consumed_words] << br->consumed_bits;
  90056. if(b) {
  90057. i = COUNT_ZERO_MSBS(b);
  90058. *val += i;
  90059. i++;
  90060. br->consumed_bits += i;
  90061. if(br->consumed_bits >= FLAC__BITS_PER_WORD) { /* faster way of testing if(br->consumed_bits == FLAC__BITS_PER_WORD) */
  90062. crc16_update_word_(br, br->buffer[br->consumed_words]);
  90063. br->consumed_words++;
  90064. br->consumed_bits = 0;
  90065. }
  90066. return true;
  90067. }
  90068. else {
  90069. *val += FLAC__BITS_PER_WORD - br->consumed_bits;
  90070. crc16_update_word_(br, br->buffer[br->consumed_words]);
  90071. br->consumed_words++;
  90072. br->consumed_bits = 0;
  90073. /* didn't find stop bit yet, have to keep going... */
  90074. }
  90075. }
  90076. /* at this point we've eaten up all the whole words; have to try
  90077. * reading through any tail bytes before calling the read callback.
  90078. * this is a repeat of the above logic adjusted for the fact we
  90079. * don't have a whole word. note though if the client is feeding
  90080. * us data a byte at a time (unlikely), br->consumed_bits may not
  90081. * be zero.
  90082. */
  90083. if(br->bytes) {
  90084. const unsigned end = br->bytes * 8;
  90085. brword b = (br->buffer[br->consumed_words] & (FLAC__WORD_ALL_ONES << (FLAC__BITS_PER_WORD-end))) << br->consumed_bits;
  90086. if(b) {
  90087. i = COUNT_ZERO_MSBS(b);
  90088. *val += i;
  90089. i++;
  90090. br->consumed_bits += i;
  90091. FLAC__ASSERT(br->consumed_bits < FLAC__BITS_PER_WORD);
  90092. return true;
  90093. }
  90094. else {
  90095. *val += end - br->consumed_bits;
  90096. br->consumed_bits += end;
  90097. FLAC__ASSERT(br->consumed_bits < FLAC__BITS_PER_WORD);
  90098. /* didn't find stop bit yet, have to keep going... */
  90099. }
  90100. }
  90101. if(!bitreader_read_from_client_(br))
  90102. return false;
  90103. }
  90104. }
  90105. #endif
  90106. FLAC__bool FLAC__bitreader_read_rice_signed(FLAC__BitReader *br, int *val, unsigned parameter)
  90107. {
  90108. FLAC__uint32 lsbs = 0, msbs = 0;
  90109. unsigned uval;
  90110. FLAC__ASSERT(0 != br);
  90111. FLAC__ASSERT(0 != br->buffer);
  90112. FLAC__ASSERT(parameter <= 31);
  90113. /* read the unary MSBs and end bit */
  90114. if(!FLAC__bitreader_read_unary_unsigned(br, (unsigned int*) &msbs))
  90115. return false;
  90116. /* read the binary LSBs */
  90117. if(!FLAC__bitreader_read_raw_uint32(br, &lsbs, parameter))
  90118. return false;
  90119. /* compose the value */
  90120. uval = (msbs << parameter) | lsbs;
  90121. if(uval & 1)
  90122. *val = -((int)(uval >> 1)) - 1;
  90123. else
  90124. *val = (int)(uval >> 1);
  90125. return true;
  90126. }
  90127. /* this is by far the most heavily used reader call. it ain't pretty but it's fast */
  90128. /* a lot of the logic is copied, then adapted, from FLAC__bitreader_read_unary_unsigned() and FLAC__bitreader_read_raw_uint32() */
  90129. FLAC__bool FLAC__bitreader_read_rice_signed_block(FLAC__BitReader *br, int vals[], unsigned nvals, unsigned parameter)
  90130. /* OPT: possibly faster version for use with MSVC */
  90131. #ifdef _MSC_VER
  90132. {
  90133. unsigned i;
  90134. unsigned uval = 0;
  90135. unsigned bits; /* the # of binary LSBs left to read to finish a rice codeword */
  90136. /* try and get br->consumed_words and br->consumed_bits into register;
  90137. * must remember to flush them back to *br before calling other
  90138. * bitwriter functions that use them, and before returning */
  90139. register unsigned cwords;
  90140. register unsigned cbits;
  90141. FLAC__ASSERT(0 != br);
  90142. FLAC__ASSERT(0 != br->buffer);
  90143. /* WATCHOUT: code does not work with <32bit words; we can make things much faster with this assertion */
  90144. FLAC__ASSERT(FLAC__BITS_PER_WORD >= 32);
  90145. FLAC__ASSERT(parameter < 32);
  90146. /* 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 */
  90147. if(nvals == 0)
  90148. return true;
  90149. cbits = br->consumed_bits;
  90150. cwords = br->consumed_words;
  90151. while(1) {
  90152. /* read unary part */
  90153. while(1) {
  90154. while(cwords < br->words) { /* if we've not consumed up to a partial tail word... */
  90155. brword b = br->buffer[cwords] << cbits;
  90156. if(b) {
  90157. #if 0 /* slower, probably due to bad register allocation... */ && defined FLAC__CPU_IA32 && !defined FLAC__NO_ASM && FLAC__BITS_PER_WORD == 32
  90158. __asm {
  90159. bsr eax, b
  90160. not eax
  90161. and eax, 31
  90162. mov i, eax
  90163. }
  90164. #else
  90165. i = COUNT_ZERO_MSBS(b);
  90166. #endif
  90167. uval += i;
  90168. bits = parameter;
  90169. i++;
  90170. cbits += i;
  90171. if(cbits == FLAC__BITS_PER_WORD) {
  90172. crc16_update_word_(br, br->buffer[cwords]);
  90173. cwords++;
  90174. cbits = 0;
  90175. }
  90176. goto break1;
  90177. }
  90178. else {
  90179. uval += FLAC__BITS_PER_WORD - cbits;
  90180. crc16_update_word_(br, br->buffer[cwords]);
  90181. cwords++;
  90182. cbits = 0;
  90183. /* didn't find stop bit yet, have to keep going... */
  90184. }
  90185. }
  90186. /* at this point we've eaten up all the whole words; have to try
  90187. * reading through any tail bytes before calling the read callback.
  90188. * this is a repeat of the above logic adjusted for the fact we
  90189. * don't have a whole word. note though if the client is feeding
  90190. * us data a byte at a time (unlikely), br->consumed_bits may not
  90191. * be zero.
  90192. */
  90193. if(br->bytes) {
  90194. const unsigned end = br->bytes * 8;
  90195. brword b = (br->buffer[cwords] & (FLAC__WORD_ALL_ONES << (FLAC__BITS_PER_WORD-end))) << cbits;
  90196. if(b) {
  90197. i = COUNT_ZERO_MSBS(b);
  90198. uval += i;
  90199. bits = parameter;
  90200. i++;
  90201. cbits += i;
  90202. FLAC__ASSERT(cbits < FLAC__BITS_PER_WORD);
  90203. goto break1;
  90204. }
  90205. else {
  90206. uval += end - cbits;
  90207. cbits += end;
  90208. FLAC__ASSERT(cbits < FLAC__BITS_PER_WORD);
  90209. /* didn't find stop bit yet, have to keep going... */
  90210. }
  90211. }
  90212. /* flush registers and read; bitreader_read_from_client_() does
  90213. * not touch br->consumed_bits at all but we still need to set
  90214. * it in case it fails and we have to return false.
  90215. */
  90216. br->consumed_bits = cbits;
  90217. br->consumed_words = cwords;
  90218. if(!bitreader_read_from_client_(br))
  90219. return false;
  90220. cwords = br->consumed_words;
  90221. }
  90222. break1:
  90223. /* read binary part */
  90224. FLAC__ASSERT(cwords <= br->words);
  90225. if(bits) {
  90226. while((br->words-cwords)*FLAC__BITS_PER_WORD + br->bytes*8 - cbits < bits) {
  90227. /* flush registers and read; bitreader_read_from_client_() does
  90228. * not touch br->consumed_bits at all but we still need to set
  90229. * it in case it fails and we have to return false.
  90230. */
  90231. br->consumed_bits = cbits;
  90232. br->consumed_words = cwords;
  90233. if(!bitreader_read_from_client_(br))
  90234. return false;
  90235. cwords = br->consumed_words;
  90236. }
  90237. if(cwords < br->words) { /* if we've not consumed up to a partial tail word... */
  90238. if(cbits) {
  90239. /* this also works when consumed_bits==0, it's just a little slower than necessary for that case */
  90240. const unsigned n = FLAC__BITS_PER_WORD - cbits;
  90241. const brword word = br->buffer[cwords];
  90242. if(bits < n) {
  90243. uval <<= bits;
  90244. uval |= (word & (FLAC__WORD_ALL_ONES >> cbits)) >> (n-bits);
  90245. cbits += bits;
  90246. goto break2;
  90247. }
  90248. uval <<= n;
  90249. uval |= word & (FLAC__WORD_ALL_ONES >> cbits);
  90250. bits -= n;
  90251. crc16_update_word_(br, word);
  90252. cwords++;
  90253. cbits = 0;
  90254. 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 */
  90255. uval <<= bits;
  90256. uval |= (br->buffer[cwords] >> (FLAC__BITS_PER_WORD-bits));
  90257. cbits = bits;
  90258. }
  90259. goto break2;
  90260. }
  90261. else {
  90262. FLAC__ASSERT(bits < FLAC__BITS_PER_WORD);
  90263. uval <<= bits;
  90264. uval |= br->buffer[cwords] >> (FLAC__BITS_PER_WORD-bits);
  90265. cbits = bits;
  90266. goto break2;
  90267. }
  90268. }
  90269. else {
  90270. /* in this case we're starting our read at a partial tail word;
  90271. * the reader has guaranteed that we have at least 'bits' bits
  90272. * available to read, which makes this case simpler.
  90273. */
  90274. uval <<= bits;
  90275. if(cbits) {
  90276. /* this also works when consumed_bits==0, it's just a little slower than necessary for that case */
  90277. FLAC__ASSERT(cbits + bits <= br->bytes*8);
  90278. uval |= (br->buffer[cwords] & (FLAC__WORD_ALL_ONES >> cbits)) >> (FLAC__BITS_PER_WORD-cbits-bits);
  90279. cbits += bits;
  90280. goto break2;
  90281. }
  90282. else {
  90283. uval |= br->buffer[cwords] >> (FLAC__BITS_PER_WORD-bits);
  90284. cbits += bits;
  90285. goto break2;
  90286. }
  90287. }
  90288. }
  90289. break2:
  90290. /* compose the value */
  90291. *vals = (int)(uval >> 1 ^ -(int)(uval & 1));
  90292. /* are we done? */
  90293. --nvals;
  90294. if(nvals == 0) {
  90295. br->consumed_bits = cbits;
  90296. br->consumed_words = cwords;
  90297. return true;
  90298. }
  90299. uval = 0;
  90300. ++vals;
  90301. }
  90302. }
  90303. #else
  90304. {
  90305. unsigned i;
  90306. unsigned uval = 0;
  90307. /* try and get br->consumed_words and br->consumed_bits into register;
  90308. * must remember to flush them back to *br before calling other
  90309. * bitwriter functions that use them, and before returning */
  90310. register unsigned cwords;
  90311. register unsigned cbits;
  90312. unsigned ucbits; /* keep track of the number of unconsumed bits in the buffer */
  90313. FLAC__ASSERT(0 != br);
  90314. FLAC__ASSERT(0 != br->buffer);
  90315. /* WATCHOUT: code does not work with <32bit words; we can make things much faster with this assertion */
  90316. FLAC__ASSERT(FLAC__BITS_PER_WORD >= 32);
  90317. FLAC__ASSERT(parameter < 32);
  90318. /* 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 */
  90319. if(nvals == 0)
  90320. return true;
  90321. cbits = br->consumed_bits;
  90322. cwords = br->consumed_words;
  90323. ucbits = (br->words-cwords)*FLAC__BITS_PER_WORD + br->bytes*8 - cbits;
  90324. while(1) {
  90325. /* read unary part */
  90326. while(1) {
  90327. while(cwords < br->words) { /* if we've not consumed up to a partial tail word... */
  90328. brword b = br->buffer[cwords] << cbits;
  90329. if(b) {
  90330. #if 0 /* is not discernably faster... */ && defined FLAC__CPU_IA32 && !defined FLAC__NO_ASM && FLAC__BITS_PER_WORD == 32 && defined __GNUC__
  90331. asm volatile (
  90332. "bsrl %1, %0;"
  90333. "notl %0;"
  90334. "andl $31, %0;"
  90335. : "=r"(i)
  90336. : "r"(b)
  90337. );
  90338. #else
  90339. i = COUNT_ZERO_MSBS(b);
  90340. #endif
  90341. uval += i;
  90342. cbits += i;
  90343. cbits++; /* skip over stop bit */
  90344. if(cbits >= FLAC__BITS_PER_WORD) { /* faster way of testing if(cbits == FLAC__BITS_PER_WORD) */
  90345. crc16_update_word_(br, br->buffer[cwords]);
  90346. cwords++;
  90347. cbits = 0;
  90348. }
  90349. goto break1;
  90350. }
  90351. else {
  90352. uval += FLAC__BITS_PER_WORD - cbits;
  90353. crc16_update_word_(br, br->buffer[cwords]);
  90354. cwords++;
  90355. cbits = 0;
  90356. /* didn't find stop bit yet, have to keep going... */
  90357. }
  90358. }
  90359. /* at this point we've eaten up all the whole words; have to try
  90360. * reading through any tail bytes before calling the read callback.
  90361. * this is a repeat of the above logic adjusted for the fact we
  90362. * don't have a whole word. note though if the client is feeding
  90363. * us data a byte at a time (unlikely), br->consumed_bits may not
  90364. * be zero.
  90365. */
  90366. if(br->bytes) {
  90367. const unsigned end = br->bytes * 8;
  90368. brword b = (br->buffer[cwords] & ~(FLAC__WORD_ALL_ONES >> end)) << cbits;
  90369. if(b) {
  90370. i = COUNT_ZERO_MSBS(b);
  90371. uval += i;
  90372. cbits += i;
  90373. cbits++; /* skip over stop bit */
  90374. FLAC__ASSERT(cbits < FLAC__BITS_PER_WORD);
  90375. goto break1;
  90376. }
  90377. else {
  90378. uval += end - cbits;
  90379. cbits += end;
  90380. FLAC__ASSERT(cbits < FLAC__BITS_PER_WORD);
  90381. /* didn't find stop bit yet, have to keep going... */
  90382. }
  90383. }
  90384. /* flush registers and read; bitreader_read_from_client_() does
  90385. * not touch br->consumed_bits at all but we still need to set
  90386. * it in case it fails and we have to return false.
  90387. */
  90388. br->consumed_bits = cbits;
  90389. br->consumed_words = cwords;
  90390. if(!bitreader_read_from_client_(br))
  90391. return false;
  90392. cwords = br->consumed_words;
  90393. ucbits = (br->words-cwords)*FLAC__BITS_PER_WORD + br->bytes*8 - cbits + uval;
  90394. /* + uval to offset our count by the # of unary bits already
  90395. * consumed before the read, because we will add these back
  90396. * in all at once at break1
  90397. */
  90398. }
  90399. break1:
  90400. ucbits -= uval;
  90401. ucbits--; /* account for stop bit */
  90402. /* read binary part */
  90403. FLAC__ASSERT(cwords <= br->words);
  90404. if(parameter) {
  90405. while(ucbits < parameter) {
  90406. /* flush registers and read; bitreader_read_from_client_() does
  90407. * not touch br->consumed_bits at all but we still need to set
  90408. * it in case it fails and we have to return false.
  90409. */
  90410. br->consumed_bits = cbits;
  90411. br->consumed_words = cwords;
  90412. if(!bitreader_read_from_client_(br))
  90413. return false;
  90414. cwords = br->consumed_words;
  90415. ucbits = (br->words-cwords)*FLAC__BITS_PER_WORD + br->bytes*8 - cbits;
  90416. }
  90417. if(cwords < br->words) { /* if we've not consumed up to a partial tail word... */
  90418. if(cbits) {
  90419. /* this also works when consumed_bits==0, it's just slower than necessary for that case */
  90420. const unsigned n = FLAC__BITS_PER_WORD - cbits;
  90421. const brword word = br->buffer[cwords];
  90422. if(parameter < n) {
  90423. uval <<= parameter;
  90424. uval |= (word & (FLAC__WORD_ALL_ONES >> cbits)) >> (n-parameter);
  90425. cbits += parameter;
  90426. }
  90427. else {
  90428. uval <<= n;
  90429. uval |= word & (FLAC__WORD_ALL_ONES >> cbits);
  90430. crc16_update_word_(br, word);
  90431. cwords++;
  90432. cbits = parameter - n;
  90433. 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 */
  90434. uval <<= cbits;
  90435. uval |= (br->buffer[cwords] >> (FLAC__BITS_PER_WORD-cbits));
  90436. }
  90437. }
  90438. }
  90439. else {
  90440. cbits = parameter;
  90441. uval <<= parameter;
  90442. uval |= br->buffer[cwords] >> (FLAC__BITS_PER_WORD-cbits);
  90443. }
  90444. }
  90445. else {
  90446. /* in this case we're starting our read at a partial tail word;
  90447. * the reader has guaranteed that we have at least 'parameter'
  90448. * bits available to read, which makes this case simpler.
  90449. */
  90450. uval <<= parameter;
  90451. if(cbits) {
  90452. /* this also works when consumed_bits==0, it's just a little slower than necessary for that case */
  90453. FLAC__ASSERT(cbits + parameter <= br->bytes*8);
  90454. uval |= (br->buffer[cwords] & (FLAC__WORD_ALL_ONES >> cbits)) >> (FLAC__BITS_PER_WORD-cbits-parameter);
  90455. cbits += parameter;
  90456. }
  90457. else {
  90458. cbits = parameter;
  90459. uval |= br->buffer[cwords] >> (FLAC__BITS_PER_WORD-cbits);
  90460. }
  90461. }
  90462. }
  90463. ucbits -= parameter;
  90464. /* compose the value */
  90465. *vals = (int)(uval >> 1 ^ -(int)(uval & 1));
  90466. /* are we done? */
  90467. --nvals;
  90468. if(nvals == 0) {
  90469. br->consumed_bits = cbits;
  90470. br->consumed_words = cwords;
  90471. return true;
  90472. }
  90473. uval = 0;
  90474. ++vals;
  90475. }
  90476. }
  90477. #endif
  90478. #if 0 /* UNUSED */
  90479. FLAC__bool FLAC__bitreader_read_golomb_signed(FLAC__BitReader *br, int *val, unsigned parameter)
  90480. {
  90481. FLAC__uint32 lsbs = 0, msbs = 0;
  90482. unsigned bit, uval, k;
  90483. FLAC__ASSERT(0 != br);
  90484. FLAC__ASSERT(0 != br->buffer);
  90485. k = FLAC__bitmath_ilog2(parameter);
  90486. /* read the unary MSBs and end bit */
  90487. if(!FLAC__bitreader_read_unary_unsigned(br, &msbs))
  90488. return false;
  90489. /* read the binary LSBs */
  90490. if(!FLAC__bitreader_read_raw_uint32(br, &lsbs, k))
  90491. return false;
  90492. if(parameter == 1u<<k) {
  90493. /* compose the value */
  90494. uval = (msbs << k) | lsbs;
  90495. }
  90496. else {
  90497. unsigned d = (1 << (k+1)) - parameter;
  90498. if(lsbs >= d) {
  90499. if(!FLAC__bitreader_read_bit(br, &bit))
  90500. return false;
  90501. lsbs <<= 1;
  90502. lsbs |= bit;
  90503. lsbs -= d;
  90504. }
  90505. /* compose the value */
  90506. uval = msbs * parameter + lsbs;
  90507. }
  90508. /* unfold unsigned to signed */
  90509. if(uval & 1)
  90510. *val = -((int)(uval >> 1)) - 1;
  90511. else
  90512. *val = (int)(uval >> 1);
  90513. return true;
  90514. }
  90515. FLAC__bool FLAC__bitreader_read_golomb_unsigned(FLAC__BitReader *br, unsigned *val, unsigned parameter)
  90516. {
  90517. FLAC__uint32 lsbs, msbs = 0;
  90518. unsigned bit, k;
  90519. FLAC__ASSERT(0 != br);
  90520. FLAC__ASSERT(0 != br->buffer);
  90521. k = FLAC__bitmath_ilog2(parameter);
  90522. /* read the unary MSBs and end bit */
  90523. if(!FLAC__bitreader_read_unary_unsigned(br, &msbs))
  90524. return false;
  90525. /* read the binary LSBs */
  90526. if(!FLAC__bitreader_read_raw_uint32(br, &lsbs, k))
  90527. return false;
  90528. if(parameter == 1u<<k) {
  90529. /* compose the value */
  90530. *val = (msbs << k) | lsbs;
  90531. }
  90532. else {
  90533. unsigned d = (1 << (k+1)) - parameter;
  90534. if(lsbs >= d) {
  90535. if(!FLAC__bitreader_read_bit(br, &bit))
  90536. return false;
  90537. lsbs <<= 1;
  90538. lsbs |= bit;
  90539. lsbs -= d;
  90540. }
  90541. /* compose the value */
  90542. *val = msbs * parameter + lsbs;
  90543. }
  90544. return true;
  90545. }
  90546. #endif /* UNUSED */
  90547. /* on return, if *val == 0xffffffff then the utf-8 sequence was invalid, but the return value will be true */
  90548. FLAC__bool FLAC__bitreader_read_utf8_uint32(FLAC__BitReader *br, FLAC__uint32 *val, FLAC__byte *raw, unsigned *rawlen)
  90549. {
  90550. FLAC__uint32 v = 0;
  90551. FLAC__uint32 x;
  90552. unsigned i;
  90553. if(!FLAC__bitreader_read_raw_uint32(br, &x, 8))
  90554. return false;
  90555. if(raw)
  90556. raw[(*rawlen)++] = (FLAC__byte)x;
  90557. if(!(x & 0x80)) { /* 0xxxxxxx */
  90558. v = x;
  90559. i = 0;
  90560. }
  90561. else if(x & 0xC0 && !(x & 0x20)) { /* 110xxxxx */
  90562. v = x & 0x1F;
  90563. i = 1;
  90564. }
  90565. else if(x & 0xE0 && !(x & 0x10)) { /* 1110xxxx */
  90566. v = x & 0x0F;
  90567. i = 2;
  90568. }
  90569. else if(x & 0xF0 && !(x & 0x08)) { /* 11110xxx */
  90570. v = x & 0x07;
  90571. i = 3;
  90572. }
  90573. else if(x & 0xF8 && !(x & 0x04)) { /* 111110xx */
  90574. v = x & 0x03;
  90575. i = 4;
  90576. }
  90577. else if(x & 0xFC && !(x & 0x02)) { /* 1111110x */
  90578. v = x & 0x01;
  90579. i = 5;
  90580. }
  90581. else {
  90582. *val = 0xffffffff;
  90583. return true;
  90584. }
  90585. for( ; i; i--) {
  90586. if(!FLAC__bitreader_read_raw_uint32(br, &x, 8))
  90587. return false;
  90588. if(raw)
  90589. raw[(*rawlen)++] = (FLAC__byte)x;
  90590. if(!(x & 0x80) || (x & 0x40)) { /* 10xxxxxx */
  90591. *val = 0xffffffff;
  90592. return true;
  90593. }
  90594. v <<= 6;
  90595. v |= (x & 0x3F);
  90596. }
  90597. *val = v;
  90598. return true;
  90599. }
  90600. /* on return, if *val == 0xffffffffffffffff then the utf-8 sequence was invalid, but the return value will be true */
  90601. FLAC__bool FLAC__bitreader_read_utf8_uint64(FLAC__BitReader *br, FLAC__uint64 *val, FLAC__byte *raw, unsigned *rawlen)
  90602. {
  90603. FLAC__uint64 v = 0;
  90604. FLAC__uint32 x;
  90605. unsigned i;
  90606. if(!FLAC__bitreader_read_raw_uint32(br, &x, 8))
  90607. return false;
  90608. if(raw)
  90609. raw[(*rawlen)++] = (FLAC__byte)x;
  90610. if(!(x & 0x80)) { /* 0xxxxxxx */
  90611. v = x;
  90612. i = 0;
  90613. }
  90614. else if(x & 0xC0 && !(x & 0x20)) { /* 110xxxxx */
  90615. v = x & 0x1F;
  90616. i = 1;
  90617. }
  90618. else if(x & 0xE0 && !(x & 0x10)) { /* 1110xxxx */
  90619. v = x & 0x0F;
  90620. i = 2;
  90621. }
  90622. else if(x & 0xF0 && !(x & 0x08)) { /* 11110xxx */
  90623. v = x & 0x07;
  90624. i = 3;
  90625. }
  90626. else if(x & 0xF8 && !(x & 0x04)) { /* 111110xx */
  90627. v = x & 0x03;
  90628. i = 4;
  90629. }
  90630. else if(x & 0xFC && !(x & 0x02)) { /* 1111110x */
  90631. v = x & 0x01;
  90632. i = 5;
  90633. }
  90634. else if(x & 0xFE && !(x & 0x01)) { /* 11111110 */
  90635. v = 0;
  90636. i = 6;
  90637. }
  90638. else {
  90639. *val = FLAC__U64L(0xffffffffffffffff);
  90640. return true;
  90641. }
  90642. for( ; i; i--) {
  90643. if(!FLAC__bitreader_read_raw_uint32(br, &x, 8))
  90644. return false;
  90645. if(raw)
  90646. raw[(*rawlen)++] = (FLAC__byte)x;
  90647. if(!(x & 0x80) || (x & 0x40)) { /* 10xxxxxx */
  90648. *val = FLAC__U64L(0xffffffffffffffff);
  90649. return true;
  90650. }
  90651. v <<= 6;
  90652. v |= (x & 0x3F);
  90653. }
  90654. *val = v;
  90655. return true;
  90656. }
  90657. #endif
  90658. /*** End of inlined file: bitreader.c ***/
  90659. /*** Start of inlined file: bitwriter.c ***/
  90660. /*** Start of inlined file: juce_FlacHeader.h ***/
  90661. // This file is included at the start of each FLAC .c file, just to do a few housekeeping
  90662. // tasks..
  90663. #define VERSION "1.2.1"
  90664. #define FLAC__NO_DLL 1
  90665. #if JUCE_MSVC
  90666. #pragma warning (disable: 4267 4127 4244 4996 4100 4701 4702 4013 4133 4206 4312)
  90667. #endif
  90668. #if JUCE_MAC
  90669. #define FLAC__SYS_DARWIN 1
  90670. #endif
  90671. /*** End of inlined file: juce_FlacHeader.h ***/
  90672. #if JUCE_USE_FLAC
  90673. #if HAVE_CONFIG_H
  90674. # include <config.h>
  90675. #endif
  90676. #include <stdlib.h> /* for malloc() */
  90677. #include <string.h> /* for memcpy(), memset() */
  90678. #ifdef _MSC_VER
  90679. #include <winsock.h> /* for ntohl() */
  90680. #elif defined FLAC__SYS_DARWIN
  90681. #include <machine/endian.h> /* for ntohl() */
  90682. #elif defined __MINGW32__
  90683. #include <winsock.h> /* for ntohl() */
  90684. #else
  90685. #include <netinet/in.h> /* for ntohl() */
  90686. #endif
  90687. #if 0 /* UNUSED */
  90688. #endif
  90689. /*** Start of inlined file: bitwriter.h ***/
  90690. #ifndef FLAC__PRIVATE__BITWRITER_H
  90691. #define FLAC__PRIVATE__BITWRITER_H
  90692. #include <stdio.h> /* for FILE */
  90693. /*
  90694. * opaque structure definition
  90695. */
  90696. struct FLAC__BitWriter;
  90697. typedef struct FLAC__BitWriter FLAC__BitWriter;
  90698. /*
  90699. * construction, deletion, initialization, etc functions
  90700. */
  90701. FLAC__BitWriter *FLAC__bitwriter_new(void);
  90702. void FLAC__bitwriter_delete(FLAC__BitWriter *bw);
  90703. FLAC__bool FLAC__bitwriter_init(FLAC__BitWriter *bw);
  90704. void FLAC__bitwriter_free(FLAC__BitWriter *bw); /* does not 'free(buffer)' */
  90705. void FLAC__bitwriter_clear(FLAC__BitWriter *bw);
  90706. void FLAC__bitwriter_dump(const FLAC__BitWriter *bw, FILE *out);
  90707. /*
  90708. * CRC functions
  90709. *
  90710. * non-const *bw because they have to cal FLAC__bitwriter_get_buffer()
  90711. */
  90712. FLAC__bool FLAC__bitwriter_get_write_crc16(FLAC__BitWriter *bw, FLAC__uint16 *crc);
  90713. FLAC__bool FLAC__bitwriter_get_write_crc8(FLAC__BitWriter *bw, FLAC__byte *crc);
  90714. /*
  90715. * info functions
  90716. */
  90717. FLAC__bool FLAC__bitwriter_is_byte_aligned(const FLAC__BitWriter *bw);
  90718. unsigned FLAC__bitwriter_get_input_bits_unconsumed(const FLAC__BitWriter *bw); /* can be called anytime, returns total # of bits unconsumed */
  90719. /*
  90720. * direct buffer access
  90721. *
  90722. * there may be no calls on the bitwriter between get and release.
  90723. * the bitwriter continues to own the returned buffer.
  90724. * before get, bitwriter MUST be byte aligned: check with FLAC__bitwriter_is_byte_aligned()
  90725. */
  90726. FLAC__bool FLAC__bitwriter_get_buffer(FLAC__BitWriter *bw, const FLAC__byte **buffer, size_t *bytes);
  90727. void FLAC__bitwriter_release_buffer(FLAC__BitWriter *bw);
  90728. /*
  90729. * write functions
  90730. */
  90731. FLAC__bool FLAC__bitwriter_write_zeroes(FLAC__BitWriter *bw, unsigned bits);
  90732. FLAC__bool FLAC__bitwriter_write_raw_uint32(FLAC__BitWriter *bw, FLAC__uint32 val, unsigned bits);
  90733. FLAC__bool FLAC__bitwriter_write_raw_int32(FLAC__BitWriter *bw, FLAC__int32 val, unsigned bits);
  90734. FLAC__bool FLAC__bitwriter_write_raw_uint64(FLAC__BitWriter *bw, FLAC__uint64 val, unsigned bits);
  90735. FLAC__bool FLAC__bitwriter_write_raw_uint32_little_endian(FLAC__BitWriter *bw, FLAC__uint32 val); /*only for bits=32*/
  90736. FLAC__bool FLAC__bitwriter_write_byte_block(FLAC__BitWriter *bw, const FLAC__byte vals[], unsigned nvals);
  90737. FLAC__bool FLAC__bitwriter_write_unary_unsigned(FLAC__BitWriter *bw, unsigned val);
  90738. unsigned FLAC__bitwriter_rice_bits(FLAC__int32 val, unsigned parameter);
  90739. #if 0 /* UNUSED */
  90740. unsigned FLAC__bitwriter_golomb_bits_signed(int val, unsigned parameter);
  90741. unsigned FLAC__bitwriter_golomb_bits_unsigned(unsigned val, unsigned parameter);
  90742. #endif
  90743. FLAC__bool FLAC__bitwriter_write_rice_signed(FLAC__BitWriter *bw, FLAC__int32 val, unsigned parameter);
  90744. FLAC__bool FLAC__bitwriter_write_rice_signed_block(FLAC__BitWriter *bw, const FLAC__int32 *vals, unsigned nvals, unsigned parameter);
  90745. #if 0 /* UNUSED */
  90746. FLAC__bool FLAC__bitwriter_write_golomb_signed(FLAC__BitWriter *bw, int val, unsigned parameter);
  90747. FLAC__bool FLAC__bitwriter_write_golomb_unsigned(FLAC__BitWriter *bw, unsigned val, unsigned parameter);
  90748. #endif
  90749. FLAC__bool FLAC__bitwriter_write_utf8_uint32(FLAC__BitWriter *bw, FLAC__uint32 val);
  90750. FLAC__bool FLAC__bitwriter_write_utf8_uint64(FLAC__BitWriter *bw, FLAC__uint64 val);
  90751. FLAC__bool FLAC__bitwriter_zero_pad_to_byte_boundary(FLAC__BitWriter *bw);
  90752. #endif
  90753. /*** End of inlined file: bitwriter.h ***/
  90754. /*** Start of inlined file: alloc.h ***/
  90755. #ifndef FLAC__SHARE__ALLOC_H
  90756. #define FLAC__SHARE__ALLOC_H
  90757. #if HAVE_CONFIG_H
  90758. # include <config.h>
  90759. #endif
  90760. /* WATCHOUT: for c++ you may have to #define __STDC_LIMIT_MACROS 1 real early
  90761. * before #including this file, otherwise SIZE_MAX might not be defined
  90762. */
  90763. #include <limits.h> /* for SIZE_MAX */
  90764. #if !defined _MSC_VER && !defined __MINGW32__ && !defined __EMX__
  90765. #include <stdint.h> /* for SIZE_MAX in case limits.h didn't get it */
  90766. #endif
  90767. #include <stdlib.h> /* for size_t, malloc(), etc */
  90768. #ifndef SIZE_MAX
  90769. # ifndef SIZE_T_MAX
  90770. # ifdef _MSC_VER
  90771. # define SIZE_T_MAX UINT_MAX
  90772. # else
  90773. # error
  90774. # endif
  90775. # endif
  90776. # define SIZE_MAX SIZE_T_MAX
  90777. #endif
  90778. #ifndef FLaC__INLINE
  90779. #define FLaC__INLINE
  90780. #endif
  90781. /* avoid malloc()ing 0 bytes, see:
  90782. * https://www.securecoding.cert.org/confluence/display/seccode/MEM04-A.+Do+not+make+assumptions+about+the+result+of+allocating+0+bytes?focusedCommentId=5407003
  90783. */
  90784. static FLaC__INLINE void *safe_malloc_(size_t size)
  90785. {
  90786. /* malloc(0) is undefined; FLAC src convention is to always allocate */
  90787. if(!size)
  90788. size++;
  90789. return malloc(size);
  90790. }
  90791. static FLaC__INLINE void *safe_calloc_(size_t nmemb, size_t size)
  90792. {
  90793. if(!nmemb || !size)
  90794. return malloc(1); /* malloc(0) is undefined; FLAC src convention is to always allocate */
  90795. return calloc(nmemb, size);
  90796. }
  90797. /*@@@@ there's probably a better way to prevent overflows when allocating untrusted sums but this works for now */
  90798. static FLaC__INLINE void *safe_malloc_add_2op_(size_t size1, size_t size2)
  90799. {
  90800. size2 += size1;
  90801. if(size2 < size1)
  90802. return 0;
  90803. return safe_malloc_(size2);
  90804. }
  90805. static FLaC__INLINE void *safe_malloc_add_3op_(size_t size1, size_t size2, size_t size3)
  90806. {
  90807. size2 += size1;
  90808. if(size2 < size1)
  90809. return 0;
  90810. size3 += size2;
  90811. if(size3 < size2)
  90812. return 0;
  90813. return safe_malloc_(size3);
  90814. }
  90815. static FLaC__INLINE void *safe_malloc_add_4op_(size_t size1, size_t size2, size_t size3, size_t size4)
  90816. {
  90817. size2 += size1;
  90818. if(size2 < size1)
  90819. return 0;
  90820. size3 += size2;
  90821. if(size3 < size2)
  90822. return 0;
  90823. size4 += size3;
  90824. if(size4 < size3)
  90825. return 0;
  90826. return safe_malloc_(size4);
  90827. }
  90828. static FLaC__INLINE void *safe_malloc_mul_2op_(size_t size1, size_t size2)
  90829. #if 0
  90830. needs support for cases where sizeof(size_t) != 4
  90831. {
  90832. /* could be faster #ifdef'ing off SIZEOF_SIZE_T */
  90833. if(sizeof(size_t) == 4) {
  90834. if ((double)size1 * (double)size2 < 4294967296.0)
  90835. return malloc(size1*size2);
  90836. }
  90837. return 0;
  90838. }
  90839. #else
  90840. /* better? */
  90841. {
  90842. if(!size1 || !size2)
  90843. return malloc(1); /* malloc(0) is undefined; FLAC src convention is to always allocate */
  90844. if(size1 > SIZE_MAX / size2)
  90845. return 0;
  90846. return malloc(size1*size2);
  90847. }
  90848. #endif
  90849. static FLaC__INLINE void *safe_malloc_mul_3op_(size_t size1, size_t size2, size_t size3)
  90850. {
  90851. if(!size1 || !size2 || !size3)
  90852. return malloc(1); /* malloc(0) is undefined; FLAC src convention is to always allocate */
  90853. if(size1 > SIZE_MAX / size2)
  90854. return 0;
  90855. size1 *= size2;
  90856. if(size1 > SIZE_MAX / size3)
  90857. return 0;
  90858. return malloc(size1*size3);
  90859. }
  90860. /* size1*size2 + size3 */
  90861. static FLaC__INLINE void *safe_malloc_mul2add_(size_t size1, size_t size2, size_t size3)
  90862. {
  90863. if(!size1 || !size2)
  90864. return safe_malloc_(size3);
  90865. if(size1 > SIZE_MAX / size2)
  90866. return 0;
  90867. return safe_malloc_add_2op_(size1*size2, size3);
  90868. }
  90869. /* size1 * (size2 + size3) */
  90870. static FLaC__INLINE void *safe_malloc_muladd2_(size_t size1, size_t size2, size_t size3)
  90871. {
  90872. if(!size1 || (!size2 && !size3))
  90873. return malloc(1); /* malloc(0) is undefined; FLAC src convention is to always allocate */
  90874. size2 += size3;
  90875. if(size2 < size3)
  90876. return 0;
  90877. return safe_malloc_mul_2op_(size1, size2);
  90878. }
  90879. static FLaC__INLINE void *safe_realloc_add_2op_(void *ptr, size_t size1, size_t size2)
  90880. {
  90881. size2 += size1;
  90882. if(size2 < size1)
  90883. return 0;
  90884. return realloc(ptr, size2);
  90885. }
  90886. static FLaC__INLINE void *safe_realloc_add_3op_(void *ptr, size_t size1, size_t size2, size_t size3)
  90887. {
  90888. size2 += size1;
  90889. if(size2 < size1)
  90890. return 0;
  90891. size3 += size2;
  90892. if(size3 < size2)
  90893. return 0;
  90894. return realloc(ptr, size3);
  90895. }
  90896. static FLaC__INLINE void *safe_realloc_add_4op_(void *ptr, size_t size1, size_t size2, size_t size3, size_t size4)
  90897. {
  90898. size2 += size1;
  90899. if(size2 < size1)
  90900. return 0;
  90901. size3 += size2;
  90902. if(size3 < size2)
  90903. return 0;
  90904. size4 += size3;
  90905. if(size4 < size3)
  90906. return 0;
  90907. return realloc(ptr, size4);
  90908. }
  90909. static FLaC__INLINE void *safe_realloc_mul_2op_(void *ptr, size_t size1, size_t size2)
  90910. {
  90911. if(!size1 || !size2)
  90912. return realloc(ptr, 0); /* preserve POSIX realloc(ptr, 0) semantics */
  90913. if(size1 > SIZE_MAX / size2)
  90914. return 0;
  90915. return realloc(ptr, size1*size2);
  90916. }
  90917. /* size1 * (size2 + size3) */
  90918. static FLaC__INLINE void *safe_realloc_muladd2_(void *ptr, size_t size1, size_t size2, size_t size3)
  90919. {
  90920. if(!size1 || (!size2 && !size3))
  90921. return realloc(ptr, 0); /* preserve POSIX realloc(ptr, 0) semantics */
  90922. size2 += size3;
  90923. if(size2 < size3)
  90924. return 0;
  90925. return safe_realloc_mul_2op_(ptr, size1, size2);
  90926. }
  90927. #endif
  90928. /*** End of inlined file: alloc.h ***/
  90929. /* Things should be fastest when this matches the machine word size */
  90930. /* WATCHOUT: if you change this you must also change the following #defines down to SWAP_BE_WORD_TO_HOST below to match */
  90931. /* WATCHOUT: there are a few places where the code will not work unless bwword is >= 32 bits wide */
  90932. typedef FLAC__uint32 bwword;
  90933. #define FLAC__BYTES_PER_WORD 4
  90934. #define FLAC__BITS_PER_WORD 32
  90935. #define FLAC__WORD_ALL_ONES ((FLAC__uint32)0xffffffff)
  90936. /* SWAP_BE_WORD_TO_HOST swaps bytes in a bwword (which is always big-endian) if necessary to match host byte order */
  90937. #if WORDS_BIGENDIAN
  90938. #define SWAP_BE_WORD_TO_HOST(x) (x)
  90939. #else
  90940. #ifdef _MSC_VER
  90941. #define SWAP_BE_WORD_TO_HOST(x) local_swap32_(x)
  90942. #else
  90943. #define SWAP_BE_WORD_TO_HOST(x) ntohl(x)
  90944. #endif
  90945. #endif
  90946. /*
  90947. * The default capacity here doesn't matter too much. The buffer always grows
  90948. * to hold whatever is written to it. Usually the encoder will stop adding at
  90949. * a frame or metadata block, then write that out and clear the buffer for the
  90950. * next one.
  90951. */
  90952. static const unsigned FLAC__BITWRITER_DEFAULT_CAPACITY = 32768u / sizeof(bwword); /* size in words */
  90953. /* When growing, increment 4K at a time */
  90954. static const unsigned FLAC__BITWRITER_DEFAULT_INCREMENT = 4096u / sizeof(bwword); /* size in words */
  90955. #define FLAC__WORDS_TO_BITS(words) ((words) * FLAC__BITS_PER_WORD)
  90956. #define FLAC__TOTAL_BITS(bw) (FLAC__WORDS_TO_BITS((bw)->words) + (bw)->bits)
  90957. #ifdef min
  90958. #undef min
  90959. #endif
  90960. #define min(x,y) ((x)<(y)?(x):(y))
  90961. /* adjust for compilers that can't understand using LLU suffix for uint64_t literals */
  90962. #ifdef _MSC_VER
  90963. #define FLAC__U64L(x) x
  90964. #else
  90965. #define FLAC__U64L(x) x##LLU
  90966. #endif
  90967. #ifndef FLaC__INLINE
  90968. #define FLaC__INLINE
  90969. #endif
  90970. struct FLAC__BitWriter {
  90971. bwword *buffer;
  90972. bwword accum; /* accumulator; bits are right-justified; when full, accum is appended to buffer */
  90973. unsigned capacity; /* capacity of buffer in words */
  90974. unsigned words; /* # of complete words in buffer */
  90975. unsigned bits; /* # of used bits in accum */
  90976. };
  90977. /* * WATCHOUT: The current implementation only grows the buffer. */
  90978. static FLAC__bool bitwriter_grow_(FLAC__BitWriter *bw, unsigned bits_to_add)
  90979. {
  90980. unsigned new_capacity;
  90981. bwword *new_buffer;
  90982. FLAC__ASSERT(0 != bw);
  90983. FLAC__ASSERT(0 != bw->buffer);
  90984. /* calculate total words needed to store 'bits_to_add' additional bits */
  90985. new_capacity = bw->words + ((bw->bits + bits_to_add + FLAC__BITS_PER_WORD - 1) / FLAC__BITS_PER_WORD);
  90986. /* it's possible (due to pessimism in the growth estimation that
  90987. * leads to this call) that we don't actually need to grow
  90988. */
  90989. if(bw->capacity >= new_capacity)
  90990. return true;
  90991. /* round up capacity increase to the nearest FLAC__BITWRITER_DEFAULT_INCREMENT */
  90992. if((new_capacity - bw->capacity) % FLAC__BITWRITER_DEFAULT_INCREMENT)
  90993. new_capacity += FLAC__BITWRITER_DEFAULT_INCREMENT - ((new_capacity - bw->capacity) % FLAC__BITWRITER_DEFAULT_INCREMENT);
  90994. /* make sure we got everything right */
  90995. FLAC__ASSERT(0 == (new_capacity - bw->capacity) % FLAC__BITWRITER_DEFAULT_INCREMENT);
  90996. FLAC__ASSERT(new_capacity > bw->capacity);
  90997. FLAC__ASSERT(new_capacity >= bw->words + ((bw->bits + bits_to_add + FLAC__BITS_PER_WORD - 1) / FLAC__BITS_PER_WORD));
  90998. new_buffer = (bwword*)safe_realloc_mul_2op_(bw->buffer, sizeof(bwword), /*times*/new_capacity);
  90999. if(new_buffer == 0)
  91000. return false;
  91001. bw->buffer = new_buffer;
  91002. bw->capacity = new_capacity;
  91003. return true;
  91004. }
  91005. /***********************************************************************
  91006. *
  91007. * Class constructor/destructor
  91008. *
  91009. ***********************************************************************/
  91010. FLAC__BitWriter *FLAC__bitwriter_new(void)
  91011. {
  91012. FLAC__BitWriter *bw = (FLAC__BitWriter*)calloc(1, sizeof(FLAC__BitWriter));
  91013. /* note that calloc() sets all members to 0 for us */
  91014. return bw;
  91015. }
  91016. void FLAC__bitwriter_delete(FLAC__BitWriter *bw)
  91017. {
  91018. FLAC__ASSERT(0 != bw);
  91019. FLAC__bitwriter_free(bw);
  91020. free(bw);
  91021. }
  91022. /***********************************************************************
  91023. *
  91024. * Public class methods
  91025. *
  91026. ***********************************************************************/
  91027. FLAC__bool FLAC__bitwriter_init(FLAC__BitWriter *bw)
  91028. {
  91029. FLAC__ASSERT(0 != bw);
  91030. bw->words = bw->bits = 0;
  91031. bw->capacity = FLAC__BITWRITER_DEFAULT_CAPACITY;
  91032. bw->buffer = (bwword*)malloc(sizeof(bwword) * bw->capacity);
  91033. if(bw->buffer == 0)
  91034. return false;
  91035. return true;
  91036. }
  91037. void FLAC__bitwriter_free(FLAC__BitWriter *bw)
  91038. {
  91039. FLAC__ASSERT(0 != bw);
  91040. if(0 != bw->buffer)
  91041. free(bw->buffer);
  91042. bw->buffer = 0;
  91043. bw->capacity = 0;
  91044. bw->words = bw->bits = 0;
  91045. }
  91046. void FLAC__bitwriter_clear(FLAC__BitWriter *bw)
  91047. {
  91048. bw->words = bw->bits = 0;
  91049. }
  91050. void FLAC__bitwriter_dump(const FLAC__BitWriter *bw, FILE *out)
  91051. {
  91052. unsigned i, j;
  91053. if(bw == 0) {
  91054. fprintf(out, "bitwriter is NULL\n");
  91055. }
  91056. else {
  91057. fprintf(out, "bitwriter: capacity=%u words=%u bits=%u total_bits=%u\n", bw->capacity, bw->words, bw->bits, FLAC__TOTAL_BITS(bw));
  91058. for(i = 0; i < bw->words; i++) {
  91059. fprintf(out, "%08X: ", i);
  91060. for(j = 0; j < FLAC__BITS_PER_WORD; j++)
  91061. fprintf(out, "%01u", bw->buffer[i] & (1 << (FLAC__BITS_PER_WORD-j-1)) ? 1:0);
  91062. fprintf(out, "\n");
  91063. }
  91064. if(bw->bits > 0) {
  91065. fprintf(out, "%08X: ", i);
  91066. for(j = 0; j < bw->bits; j++)
  91067. fprintf(out, "%01u", bw->accum & (1 << (bw->bits-j-1)) ? 1:0);
  91068. fprintf(out, "\n");
  91069. }
  91070. }
  91071. }
  91072. FLAC__bool FLAC__bitwriter_get_write_crc16(FLAC__BitWriter *bw, FLAC__uint16 *crc)
  91073. {
  91074. const FLAC__byte *buffer;
  91075. size_t bytes;
  91076. FLAC__ASSERT((bw->bits & 7) == 0); /* assert that we're byte-aligned */
  91077. if(!FLAC__bitwriter_get_buffer(bw, &buffer, &bytes))
  91078. return false;
  91079. *crc = (FLAC__uint16)FLAC__crc16(buffer, bytes);
  91080. FLAC__bitwriter_release_buffer(bw);
  91081. return true;
  91082. }
  91083. FLAC__bool FLAC__bitwriter_get_write_crc8(FLAC__BitWriter *bw, FLAC__byte *crc)
  91084. {
  91085. const FLAC__byte *buffer;
  91086. size_t bytes;
  91087. FLAC__ASSERT((bw->bits & 7) == 0); /* assert that we're byte-aligned */
  91088. if(!FLAC__bitwriter_get_buffer(bw, &buffer, &bytes))
  91089. return false;
  91090. *crc = FLAC__crc8(buffer, bytes);
  91091. FLAC__bitwriter_release_buffer(bw);
  91092. return true;
  91093. }
  91094. FLAC__bool FLAC__bitwriter_is_byte_aligned(const FLAC__BitWriter *bw)
  91095. {
  91096. return ((bw->bits & 7) == 0);
  91097. }
  91098. unsigned FLAC__bitwriter_get_input_bits_unconsumed(const FLAC__BitWriter *bw)
  91099. {
  91100. return FLAC__TOTAL_BITS(bw);
  91101. }
  91102. FLAC__bool FLAC__bitwriter_get_buffer(FLAC__BitWriter *bw, const FLAC__byte **buffer, size_t *bytes)
  91103. {
  91104. FLAC__ASSERT((bw->bits & 7) == 0);
  91105. /* double protection */
  91106. if(bw->bits & 7)
  91107. return false;
  91108. /* if we have bits in the accumulator we have to flush those to the buffer first */
  91109. if(bw->bits) {
  91110. FLAC__ASSERT(bw->words <= bw->capacity);
  91111. if(bw->words == bw->capacity && !bitwriter_grow_(bw, FLAC__BITS_PER_WORD))
  91112. return false;
  91113. /* append bits as complete word to buffer, but don't change bw->accum or bw->bits */
  91114. bw->buffer[bw->words] = SWAP_BE_WORD_TO_HOST(bw->accum << (FLAC__BITS_PER_WORD-bw->bits));
  91115. }
  91116. /* now we can just return what we have */
  91117. *buffer = (FLAC__byte*)bw->buffer;
  91118. *bytes = (FLAC__BYTES_PER_WORD * bw->words) + (bw->bits >> 3);
  91119. return true;
  91120. }
  91121. void FLAC__bitwriter_release_buffer(FLAC__BitWriter *bw)
  91122. {
  91123. /* nothing to do. in the future, strict checking of a 'writer-is-in-
  91124. * get-mode' flag could be added everywhere and then cleared here
  91125. */
  91126. (void)bw;
  91127. }
  91128. FLaC__INLINE FLAC__bool FLAC__bitwriter_write_zeroes(FLAC__BitWriter *bw, unsigned bits)
  91129. {
  91130. unsigned n;
  91131. FLAC__ASSERT(0 != bw);
  91132. FLAC__ASSERT(0 != bw->buffer);
  91133. if(bits == 0)
  91134. return true;
  91135. /* slightly pessimistic size check but faster than "<= bw->words + (bw->bits+bits+FLAC__BITS_PER_WORD-1)/FLAC__BITS_PER_WORD" */
  91136. if(bw->capacity <= bw->words + bits && !bitwriter_grow_(bw, bits))
  91137. return false;
  91138. /* first part gets to word alignment */
  91139. if(bw->bits) {
  91140. n = min(FLAC__BITS_PER_WORD - bw->bits, bits);
  91141. bw->accum <<= n;
  91142. bits -= n;
  91143. bw->bits += n;
  91144. if(bw->bits == FLAC__BITS_PER_WORD) {
  91145. bw->buffer[bw->words++] = SWAP_BE_WORD_TO_HOST(bw->accum);
  91146. bw->bits = 0;
  91147. }
  91148. else
  91149. return true;
  91150. }
  91151. /* do whole words */
  91152. while(bits >= FLAC__BITS_PER_WORD) {
  91153. bw->buffer[bw->words++] = 0;
  91154. bits -= FLAC__BITS_PER_WORD;
  91155. }
  91156. /* do any leftovers */
  91157. if(bits > 0) {
  91158. bw->accum = 0;
  91159. bw->bits = bits;
  91160. }
  91161. return true;
  91162. }
  91163. FLaC__INLINE FLAC__bool FLAC__bitwriter_write_raw_uint32(FLAC__BitWriter *bw, FLAC__uint32 val, unsigned bits)
  91164. {
  91165. register unsigned left;
  91166. /* WATCHOUT: code does not work with <32bit words; we can make things much faster with this assertion */
  91167. FLAC__ASSERT(FLAC__BITS_PER_WORD >= 32);
  91168. FLAC__ASSERT(0 != bw);
  91169. FLAC__ASSERT(0 != bw->buffer);
  91170. FLAC__ASSERT(bits <= 32);
  91171. if(bits == 0)
  91172. return true;
  91173. /* slightly pessimistic size check but faster than "<= bw->words + (bw->bits+bits+FLAC__BITS_PER_WORD-1)/FLAC__BITS_PER_WORD" */
  91174. if(bw->capacity <= bw->words + bits && !bitwriter_grow_(bw, bits))
  91175. return false;
  91176. left = FLAC__BITS_PER_WORD - bw->bits;
  91177. if(bits < left) {
  91178. bw->accum <<= bits;
  91179. bw->accum |= val;
  91180. bw->bits += bits;
  91181. }
  91182. 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 */
  91183. bw->accum <<= left;
  91184. bw->accum |= val >> (bw->bits = bits - left);
  91185. bw->buffer[bw->words++] = SWAP_BE_WORD_TO_HOST(bw->accum);
  91186. bw->accum = val;
  91187. }
  91188. else {
  91189. bw->accum = val;
  91190. bw->bits = 0;
  91191. bw->buffer[bw->words++] = SWAP_BE_WORD_TO_HOST(val);
  91192. }
  91193. return true;
  91194. }
  91195. FLaC__INLINE FLAC__bool FLAC__bitwriter_write_raw_int32(FLAC__BitWriter *bw, FLAC__int32 val, unsigned bits)
  91196. {
  91197. /* zero-out unused bits */
  91198. if(bits < 32)
  91199. val &= (~(0xffffffff << bits));
  91200. return FLAC__bitwriter_write_raw_uint32(bw, (FLAC__uint32)val, bits);
  91201. }
  91202. FLaC__INLINE FLAC__bool FLAC__bitwriter_write_raw_uint64(FLAC__BitWriter *bw, FLAC__uint64 val, unsigned bits)
  91203. {
  91204. /* this could be a little faster but it's not used for much */
  91205. if(bits > 32) {
  91206. return
  91207. FLAC__bitwriter_write_raw_uint32(bw, (FLAC__uint32)(val>>32), bits-32) &&
  91208. FLAC__bitwriter_write_raw_uint32(bw, (FLAC__uint32)val, 32);
  91209. }
  91210. else
  91211. return FLAC__bitwriter_write_raw_uint32(bw, (FLAC__uint32)val, bits);
  91212. }
  91213. FLaC__INLINE FLAC__bool FLAC__bitwriter_write_raw_uint32_little_endian(FLAC__BitWriter *bw, FLAC__uint32 val)
  91214. {
  91215. /* this doesn't need to be that fast as currently it is only used for vorbis comments */
  91216. if(!FLAC__bitwriter_write_raw_uint32(bw, val & 0xff, 8))
  91217. return false;
  91218. if(!FLAC__bitwriter_write_raw_uint32(bw, (val>>8) & 0xff, 8))
  91219. return false;
  91220. if(!FLAC__bitwriter_write_raw_uint32(bw, (val>>16) & 0xff, 8))
  91221. return false;
  91222. if(!FLAC__bitwriter_write_raw_uint32(bw, val>>24, 8))
  91223. return false;
  91224. return true;
  91225. }
  91226. FLaC__INLINE FLAC__bool FLAC__bitwriter_write_byte_block(FLAC__BitWriter *bw, const FLAC__byte vals[], unsigned nvals)
  91227. {
  91228. unsigned i;
  91229. /* this could be faster but currently we don't need it to be since it's only used for writing metadata */
  91230. for(i = 0; i < nvals; i++) {
  91231. if(!FLAC__bitwriter_write_raw_uint32(bw, (FLAC__uint32)(vals[i]), 8))
  91232. return false;
  91233. }
  91234. return true;
  91235. }
  91236. FLAC__bool FLAC__bitwriter_write_unary_unsigned(FLAC__BitWriter *bw, unsigned val)
  91237. {
  91238. if(val < 32)
  91239. return FLAC__bitwriter_write_raw_uint32(bw, 1, ++val);
  91240. else
  91241. return
  91242. FLAC__bitwriter_write_zeroes(bw, val) &&
  91243. FLAC__bitwriter_write_raw_uint32(bw, 1, 1);
  91244. }
  91245. unsigned FLAC__bitwriter_rice_bits(FLAC__int32 val, unsigned parameter)
  91246. {
  91247. FLAC__uint32 uval;
  91248. FLAC__ASSERT(parameter < sizeof(unsigned)*8);
  91249. /* fold signed to unsigned; actual formula is: negative(v)? -2v-1 : 2v */
  91250. uval = (val<<1) ^ (val>>31);
  91251. return 1 + parameter + (uval >> parameter);
  91252. }
  91253. #if 0 /* UNUSED */
  91254. unsigned FLAC__bitwriter_golomb_bits_signed(int val, unsigned parameter)
  91255. {
  91256. unsigned bits, msbs, uval;
  91257. unsigned k;
  91258. FLAC__ASSERT(parameter > 0);
  91259. /* fold signed to unsigned */
  91260. if(val < 0)
  91261. uval = (unsigned)(((-(++val)) << 1) + 1);
  91262. else
  91263. uval = (unsigned)(val << 1);
  91264. k = FLAC__bitmath_ilog2(parameter);
  91265. if(parameter == 1u<<k) {
  91266. FLAC__ASSERT(k <= 30);
  91267. msbs = uval >> k;
  91268. bits = 1 + k + msbs;
  91269. }
  91270. else {
  91271. unsigned q, r, d;
  91272. d = (1 << (k+1)) - parameter;
  91273. q = uval / parameter;
  91274. r = uval - (q * parameter);
  91275. bits = 1 + q + k;
  91276. if(r >= d)
  91277. bits++;
  91278. }
  91279. return bits;
  91280. }
  91281. unsigned FLAC__bitwriter_golomb_bits_unsigned(unsigned uval, unsigned parameter)
  91282. {
  91283. unsigned bits, msbs;
  91284. unsigned k;
  91285. FLAC__ASSERT(parameter > 0);
  91286. k = FLAC__bitmath_ilog2(parameter);
  91287. if(parameter == 1u<<k) {
  91288. FLAC__ASSERT(k <= 30);
  91289. msbs = uval >> k;
  91290. bits = 1 + k + msbs;
  91291. }
  91292. else {
  91293. unsigned q, r, d;
  91294. d = (1 << (k+1)) - parameter;
  91295. q = uval / parameter;
  91296. r = uval - (q * parameter);
  91297. bits = 1 + q + k;
  91298. if(r >= d)
  91299. bits++;
  91300. }
  91301. return bits;
  91302. }
  91303. #endif /* UNUSED */
  91304. FLAC__bool FLAC__bitwriter_write_rice_signed(FLAC__BitWriter *bw, FLAC__int32 val, unsigned parameter)
  91305. {
  91306. unsigned total_bits, interesting_bits, msbs;
  91307. FLAC__uint32 uval, pattern;
  91308. FLAC__ASSERT(0 != bw);
  91309. FLAC__ASSERT(0 != bw->buffer);
  91310. FLAC__ASSERT(parameter < 8*sizeof(uval));
  91311. /* fold signed to unsigned; actual formula is: negative(v)? -2v-1 : 2v */
  91312. uval = (val<<1) ^ (val>>31);
  91313. msbs = uval >> parameter;
  91314. interesting_bits = 1 + parameter;
  91315. total_bits = interesting_bits + msbs;
  91316. pattern = 1 << parameter; /* the unary end bit */
  91317. pattern |= (uval & ((1<<parameter)-1)); /* the binary LSBs */
  91318. if(total_bits <= 32)
  91319. return FLAC__bitwriter_write_raw_uint32(bw, pattern, total_bits);
  91320. else
  91321. return
  91322. FLAC__bitwriter_write_zeroes(bw, msbs) && /* write the unary MSBs */
  91323. FLAC__bitwriter_write_raw_uint32(bw, pattern, interesting_bits); /* write the unary end bit and binary LSBs */
  91324. }
  91325. FLAC__bool FLAC__bitwriter_write_rice_signed_block(FLAC__BitWriter *bw, const FLAC__int32 *vals, unsigned nvals, unsigned parameter)
  91326. {
  91327. const FLAC__uint32 mask1 = FLAC__WORD_ALL_ONES << parameter; /* we val|=mask1 to set the stop bit above it... */
  91328. const FLAC__uint32 mask2 = FLAC__WORD_ALL_ONES >> (31-parameter); /* ...then mask off the bits above the stop bit with val&=mask2*/
  91329. FLAC__uint32 uval;
  91330. unsigned left;
  91331. const unsigned lsbits = 1 + parameter;
  91332. unsigned msbits;
  91333. FLAC__ASSERT(0 != bw);
  91334. FLAC__ASSERT(0 != bw->buffer);
  91335. FLAC__ASSERT(parameter < 8*sizeof(bwword)-1);
  91336. /* WATCHOUT: code does not work with <32bit words; we can make things much faster with this assertion */
  91337. FLAC__ASSERT(FLAC__BITS_PER_WORD >= 32);
  91338. while(nvals) {
  91339. /* fold signed to unsigned; actual formula is: negative(v)? -2v-1 : 2v */
  91340. uval = (*vals<<1) ^ (*vals>>31);
  91341. msbits = uval >> parameter;
  91342. #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) */
  91343. if(bw->bits && bw->bits + msbits + lsbits <= FLAC__BITS_PER_WORD) { /* i.e. if the whole thing fits in the current bwword */
  91344. /* ^^^ if bw->bits is 0 then we may have filled the buffer and have no free bwword to work in */
  91345. bw->bits = bw->bits + msbits + lsbits;
  91346. uval |= mask1; /* set stop bit */
  91347. uval &= mask2; /* mask off unused top bits */
  91348. /* NOT: bw->accum <<= msbits + lsbits because msbits+lsbits could be 32, then the shift would be a NOP */
  91349. bw->accum <<= msbits;
  91350. bw->accum <<= lsbits;
  91351. bw->accum |= uval;
  91352. if(bw->bits == FLAC__BITS_PER_WORD) {
  91353. bw->buffer[bw->words++] = SWAP_BE_WORD_TO_HOST(bw->accum);
  91354. bw->bits = 0;
  91355. /* burying the capacity check down here means we have to grow the buffer a little if there are more vals to do */
  91356. if(bw->capacity <= bw->words && nvals > 1 && !bitwriter_grow_(bw, 1)) {
  91357. FLAC__ASSERT(bw->capacity == bw->words);
  91358. return false;
  91359. }
  91360. }
  91361. }
  91362. else {
  91363. #elif 1 /*@@@@@@ OPT: try this version with MSVC6 to see if better, not much difference for gcc-4 */
  91364. if(bw->bits && bw->bits + msbits + lsbits < FLAC__BITS_PER_WORD) { /* i.e. if the whole thing fits in the current bwword */
  91365. /* ^^^ if bw->bits is 0 then we may have filled the buffer and have no free bwword to work in */
  91366. bw->bits = bw->bits + msbits + lsbits;
  91367. uval |= mask1; /* set stop bit */
  91368. uval &= mask2; /* mask off unused top bits */
  91369. bw->accum <<= msbits + lsbits;
  91370. bw->accum |= uval;
  91371. }
  91372. else {
  91373. #endif
  91374. /* slightly pessimistic size check but faster than "<= bw->words + (bw->bits+msbits+lsbits+FLAC__BITS_PER_WORD-1)/FLAC__BITS_PER_WORD" */
  91375. /* OPT: pessimism may cause flurry of false calls to grow_ which eat up all savings before it */
  91376. if(bw->capacity <= bw->words + bw->bits + msbits + 1/*lsbits always fit in 1 bwword*/ && !bitwriter_grow_(bw, msbits+lsbits))
  91377. return false;
  91378. if(msbits) {
  91379. /* first part gets to word alignment */
  91380. if(bw->bits) {
  91381. left = FLAC__BITS_PER_WORD - bw->bits;
  91382. if(msbits < left) {
  91383. bw->accum <<= msbits;
  91384. bw->bits += msbits;
  91385. goto break1;
  91386. }
  91387. else {
  91388. bw->accum <<= left;
  91389. msbits -= left;
  91390. bw->buffer[bw->words++] = SWAP_BE_WORD_TO_HOST(bw->accum);
  91391. bw->bits = 0;
  91392. }
  91393. }
  91394. /* do whole words */
  91395. while(msbits >= FLAC__BITS_PER_WORD) {
  91396. bw->buffer[bw->words++] = 0;
  91397. msbits -= FLAC__BITS_PER_WORD;
  91398. }
  91399. /* do any leftovers */
  91400. if(msbits > 0) {
  91401. bw->accum = 0;
  91402. bw->bits = msbits;
  91403. }
  91404. }
  91405. break1:
  91406. uval |= mask1; /* set stop bit */
  91407. uval &= mask2; /* mask off unused top bits */
  91408. left = FLAC__BITS_PER_WORD - bw->bits;
  91409. if(lsbits < left) {
  91410. bw->accum <<= lsbits;
  91411. bw->accum |= uval;
  91412. bw->bits += lsbits;
  91413. }
  91414. else {
  91415. /* if bw->bits == 0, left==FLAC__BITS_PER_WORD which will always
  91416. * be > lsbits (because of previous assertions) so it would have
  91417. * triggered the (lsbits<left) case above.
  91418. */
  91419. FLAC__ASSERT(bw->bits);
  91420. FLAC__ASSERT(left < FLAC__BITS_PER_WORD);
  91421. bw->accum <<= left;
  91422. bw->accum |= uval >> (bw->bits = lsbits - left);
  91423. bw->buffer[bw->words++] = SWAP_BE_WORD_TO_HOST(bw->accum);
  91424. bw->accum = uval;
  91425. }
  91426. #if 1
  91427. }
  91428. #endif
  91429. vals++;
  91430. nvals--;
  91431. }
  91432. return true;
  91433. }
  91434. #if 0 /* UNUSED */
  91435. FLAC__bool FLAC__bitwriter_write_golomb_signed(FLAC__BitWriter *bw, int val, unsigned parameter)
  91436. {
  91437. unsigned total_bits, msbs, uval;
  91438. unsigned k;
  91439. FLAC__ASSERT(0 != bw);
  91440. FLAC__ASSERT(0 != bw->buffer);
  91441. FLAC__ASSERT(parameter > 0);
  91442. /* fold signed to unsigned */
  91443. if(val < 0)
  91444. uval = (unsigned)(((-(++val)) << 1) + 1);
  91445. else
  91446. uval = (unsigned)(val << 1);
  91447. k = FLAC__bitmath_ilog2(parameter);
  91448. if(parameter == 1u<<k) {
  91449. unsigned pattern;
  91450. FLAC__ASSERT(k <= 30);
  91451. msbs = uval >> k;
  91452. total_bits = 1 + k + msbs;
  91453. pattern = 1 << k; /* the unary end bit */
  91454. pattern |= (uval & ((1u<<k)-1)); /* the binary LSBs */
  91455. if(total_bits <= 32) {
  91456. if(!FLAC__bitwriter_write_raw_uint32(bw, pattern, total_bits))
  91457. return false;
  91458. }
  91459. else {
  91460. /* write the unary MSBs */
  91461. if(!FLAC__bitwriter_write_zeroes(bw, msbs))
  91462. return false;
  91463. /* write the unary end bit and binary LSBs */
  91464. if(!FLAC__bitwriter_write_raw_uint32(bw, pattern, k+1))
  91465. return false;
  91466. }
  91467. }
  91468. else {
  91469. unsigned q, r, d;
  91470. d = (1 << (k+1)) - parameter;
  91471. q = uval / parameter;
  91472. r = uval - (q * parameter);
  91473. /* write the unary MSBs */
  91474. if(!FLAC__bitwriter_write_zeroes(bw, q))
  91475. return false;
  91476. /* write the unary end bit */
  91477. if(!FLAC__bitwriter_write_raw_uint32(bw, 1, 1))
  91478. return false;
  91479. /* write the binary LSBs */
  91480. if(r >= d) {
  91481. if(!FLAC__bitwriter_write_raw_uint32(bw, r+d, k+1))
  91482. return false;
  91483. }
  91484. else {
  91485. if(!FLAC__bitwriter_write_raw_uint32(bw, r, k))
  91486. return false;
  91487. }
  91488. }
  91489. return true;
  91490. }
  91491. FLAC__bool FLAC__bitwriter_write_golomb_unsigned(FLAC__BitWriter *bw, unsigned uval, unsigned parameter)
  91492. {
  91493. unsigned total_bits, msbs;
  91494. unsigned k;
  91495. FLAC__ASSERT(0 != bw);
  91496. FLAC__ASSERT(0 != bw->buffer);
  91497. FLAC__ASSERT(parameter > 0);
  91498. k = FLAC__bitmath_ilog2(parameter);
  91499. if(parameter == 1u<<k) {
  91500. unsigned pattern;
  91501. FLAC__ASSERT(k <= 30);
  91502. msbs = uval >> k;
  91503. total_bits = 1 + k + msbs;
  91504. pattern = 1 << k; /* the unary end bit */
  91505. pattern |= (uval & ((1u<<k)-1)); /* the binary LSBs */
  91506. if(total_bits <= 32) {
  91507. if(!FLAC__bitwriter_write_raw_uint32(bw, pattern, total_bits))
  91508. return false;
  91509. }
  91510. else {
  91511. /* write the unary MSBs */
  91512. if(!FLAC__bitwriter_write_zeroes(bw, msbs))
  91513. return false;
  91514. /* write the unary end bit and binary LSBs */
  91515. if(!FLAC__bitwriter_write_raw_uint32(bw, pattern, k+1))
  91516. return false;
  91517. }
  91518. }
  91519. else {
  91520. unsigned q, r, d;
  91521. d = (1 << (k+1)) - parameter;
  91522. q = uval / parameter;
  91523. r = uval - (q * parameter);
  91524. /* write the unary MSBs */
  91525. if(!FLAC__bitwriter_write_zeroes(bw, q))
  91526. return false;
  91527. /* write the unary end bit */
  91528. if(!FLAC__bitwriter_write_raw_uint32(bw, 1, 1))
  91529. return false;
  91530. /* write the binary LSBs */
  91531. if(r >= d) {
  91532. if(!FLAC__bitwriter_write_raw_uint32(bw, r+d, k+1))
  91533. return false;
  91534. }
  91535. else {
  91536. if(!FLAC__bitwriter_write_raw_uint32(bw, r, k))
  91537. return false;
  91538. }
  91539. }
  91540. return true;
  91541. }
  91542. #endif /* UNUSED */
  91543. FLAC__bool FLAC__bitwriter_write_utf8_uint32(FLAC__BitWriter *bw, FLAC__uint32 val)
  91544. {
  91545. FLAC__bool ok = 1;
  91546. FLAC__ASSERT(0 != bw);
  91547. FLAC__ASSERT(0 != bw->buffer);
  91548. FLAC__ASSERT(!(val & 0x80000000)); /* this version only handles 31 bits */
  91549. if(val < 0x80) {
  91550. return FLAC__bitwriter_write_raw_uint32(bw, val, 8);
  91551. }
  91552. else if(val < 0x800) {
  91553. ok &= FLAC__bitwriter_write_raw_uint32(bw, 0xC0 | (val>>6), 8);
  91554. ok &= FLAC__bitwriter_write_raw_uint32(bw, 0x80 | (val&0x3F), 8);
  91555. }
  91556. else if(val < 0x10000) {
  91557. ok &= FLAC__bitwriter_write_raw_uint32(bw, 0xE0 | (val>>12), 8);
  91558. ok &= FLAC__bitwriter_write_raw_uint32(bw, 0x80 | ((val>>6)&0x3F), 8);
  91559. ok &= FLAC__bitwriter_write_raw_uint32(bw, 0x80 | (val&0x3F), 8);
  91560. }
  91561. else if(val < 0x200000) {
  91562. ok &= FLAC__bitwriter_write_raw_uint32(bw, 0xF0 | (val>>18), 8);
  91563. ok &= FLAC__bitwriter_write_raw_uint32(bw, 0x80 | ((val>>12)&0x3F), 8);
  91564. ok &= FLAC__bitwriter_write_raw_uint32(bw, 0x80 | ((val>>6)&0x3F), 8);
  91565. ok &= FLAC__bitwriter_write_raw_uint32(bw, 0x80 | (val&0x3F), 8);
  91566. }
  91567. else if(val < 0x4000000) {
  91568. ok &= FLAC__bitwriter_write_raw_uint32(bw, 0xF8 | (val>>24), 8);
  91569. ok &= FLAC__bitwriter_write_raw_uint32(bw, 0x80 | ((val>>18)&0x3F), 8);
  91570. ok &= FLAC__bitwriter_write_raw_uint32(bw, 0x80 | ((val>>12)&0x3F), 8);
  91571. ok &= FLAC__bitwriter_write_raw_uint32(bw, 0x80 | ((val>>6)&0x3F), 8);
  91572. ok &= FLAC__bitwriter_write_raw_uint32(bw, 0x80 | (val&0x3F), 8);
  91573. }
  91574. else {
  91575. ok &= FLAC__bitwriter_write_raw_uint32(bw, 0xFC | (val>>30), 8);
  91576. ok &= FLAC__bitwriter_write_raw_uint32(bw, 0x80 | ((val>>24)&0x3F), 8);
  91577. ok &= FLAC__bitwriter_write_raw_uint32(bw, 0x80 | ((val>>18)&0x3F), 8);
  91578. ok &= FLAC__bitwriter_write_raw_uint32(bw, 0x80 | ((val>>12)&0x3F), 8);
  91579. ok &= FLAC__bitwriter_write_raw_uint32(bw, 0x80 | ((val>>6)&0x3F), 8);
  91580. ok &= FLAC__bitwriter_write_raw_uint32(bw, 0x80 | (val&0x3F), 8);
  91581. }
  91582. return ok;
  91583. }
  91584. FLAC__bool FLAC__bitwriter_write_utf8_uint64(FLAC__BitWriter *bw, FLAC__uint64 val)
  91585. {
  91586. FLAC__bool ok = 1;
  91587. FLAC__ASSERT(0 != bw);
  91588. FLAC__ASSERT(0 != bw->buffer);
  91589. FLAC__ASSERT(!(val & FLAC__U64L(0xFFFFFFF000000000))); /* this version only handles 36 bits */
  91590. if(val < 0x80) {
  91591. return FLAC__bitwriter_write_raw_uint32(bw, (FLAC__uint32)val, 8);
  91592. }
  91593. else if(val < 0x800) {
  91594. ok &= FLAC__bitwriter_write_raw_uint32(bw, 0xC0 | (FLAC__uint32)(val>>6), 8);
  91595. ok &= FLAC__bitwriter_write_raw_uint32(bw, 0x80 | (FLAC__uint32)(val&0x3F), 8);
  91596. }
  91597. else if(val < 0x10000) {
  91598. ok &= FLAC__bitwriter_write_raw_uint32(bw, 0xE0 | (FLAC__uint32)(val>>12), 8);
  91599. ok &= FLAC__bitwriter_write_raw_uint32(bw, 0x80 | (FLAC__uint32)((val>>6)&0x3F), 8);
  91600. ok &= FLAC__bitwriter_write_raw_uint32(bw, 0x80 | (FLAC__uint32)(val&0x3F), 8);
  91601. }
  91602. else if(val < 0x200000) {
  91603. ok &= FLAC__bitwriter_write_raw_uint32(bw, 0xF0 | (FLAC__uint32)(val>>18), 8);
  91604. ok &= FLAC__bitwriter_write_raw_uint32(bw, 0x80 | (FLAC__uint32)((val>>12)&0x3F), 8);
  91605. ok &= FLAC__bitwriter_write_raw_uint32(bw, 0x80 | (FLAC__uint32)((val>>6)&0x3F), 8);
  91606. ok &= FLAC__bitwriter_write_raw_uint32(bw, 0x80 | (FLAC__uint32)(val&0x3F), 8);
  91607. }
  91608. else if(val < 0x4000000) {
  91609. ok &= FLAC__bitwriter_write_raw_uint32(bw, 0xF8 | (FLAC__uint32)(val>>24), 8);
  91610. ok &= FLAC__bitwriter_write_raw_uint32(bw, 0x80 | (FLAC__uint32)((val>>18)&0x3F), 8);
  91611. ok &= FLAC__bitwriter_write_raw_uint32(bw, 0x80 | (FLAC__uint32)((val>>12)&0x3F), 8);
  91612. ok &= FLAC__bitwriter_write_raw_uint32(bw, 0x80 | (FLAC__uint32)((val>>6)&0x3F), 8);
  91613. ok &= FLAC__bitwriter_write_raw_uint32(bw, 0x80 | (FLAC__uint32)(val&0x3F), 8);
  91614. }
  91615. else if(val < 0x80000000) {
  91616. ok &= FLAC__bitwriter_write_raw_uint32(bw, 0xFC | (FLAC__uint32)(val>>30), 8);
  91617. ok &= FLAC__bitwriter_write_raw_uint32(bw, 0x80 | (FLAC__uint32)((val>>24)&0x3F), 8);
  91618. ok &= FLAC__bitwriter_write_raw_uint32(bw, 0x80 | (FLAC__uint32)((val>>18)&0x3F), 8);
  91619. ok &= FLAC__bitwriter_write_raw_uint32(bw, 0x80 | (FLAC__uint32)((val>>12)&0x3F), 8);
  91620. ok &= FLAC__bitwriter_write_raw_uint32(bw, 0x80 | (FLAC__uint32)((val>>6)&0x3F), 8);
  91621. ok &= FLAC__bitwriter_write_raw_uint32(bw, 0x80 | (FLAC__uint32)(val&0x3F), 8);
  91622. }
  91623. else {
  91624. ok &= FLAC__bitwriter_write_raw_uint32(bw, 0xFE, 8);
  91625. ok &= FLAC__bitwriter_write_raw_uint32(bw, 0x80 | (FLAC__uint32)((val>>30)&0x3F), 8);
  91626. ok &= FLAC__bitwriter_write_raw_uint32(bw, 0x80 | (FLAC__uint32)((val>>24)&0x3F), 8);
  91627. ok &= FLAC__bitwriter_write_raw_uint32(bw, 0x80 | (FLAC__uint32)((val>>18)&0x3F), 8);
  91628. ok &= FLAC__bitwriter_write_raw_uint32(bw, 0x80 | (FLAC__uint32)((val>>12)&0x3F), 8);
  91629. ok &= FLAC__bitwriter_write_raw_uint32(bw, 0x80 | (FLAC__uint32)((val>>6)&0x3F), 8);
  91630. ok &= FLAC__bitwriter_write_raw_uint32(bw, 0x80 | (FLAC__uint32)(val&0x3F), 8);
  91631. }
  91632. return ok;
  91633. }
  91634. FLAC__bool FLAC__bitwriter_zero_pad_to_byte_boundary(FLAC__BitWriter *bw)
  91635. {
  91636. /* 0-pad to byte boundary */
  91637. if(bw->bits & 7u)
  91638. return FLAC__bitwriter_write_zeroes(bw, 8 - (bw->bits & 7u));
  91639. else
  91640. return true;
  91641. }
  91642. #endif
  91643. /*** End of inlined file: bitwriter.c ***/
  91644. /*** Start of inlined file: cpu.c ***/
  91645. /*** Start of inlined file: juce_FlacHeader.h ***/
  91646. // This file is included at the start of each FLAC .c file, just to do a few housekeeping
  91647. // tasks..
  91648. #define VERSION "1.2.1"
  91649. #define FLAC__NO_DLL 1
  91650. #if JUCE_MSVC
  91651. #pragma warning (disable: 4267 4127 4244 4996 4100 4701 4702 4013 4133 4206 4312)
  91652. #endif
  91653. #if JUCE_MAC
  91654. #define FLAC__SYS_DARWIN 1
  91655. #endif
  91656. /*** End of inlined file: juce_FlacHeader.h ***/
  91657. #if JUCE_USE_FLAC
  91658. #if HAVE_CONFIG_H
  91659. # include <config.h>
  91660. #endif
  91661. #include <stdlib.h>
  91662. #include <stdio.h>
  91663. #if defined FLAC__CPU_IA32
  91664. # include <signal.h>
  91665. #elif defined FLAC__CPU_PPC
  91666. # if !defined FLAC__NO_ASM
  91667. # if defined FLAC__SYS_DARWIN
  91668. # include <sys/sysctl.h>
  91669. # include <mach/mach.h>
  91670. # include <mach/mach_host.h>
  91671. # include <mach/host_info.h>
  91672. # include <mach/machine.h>
  91673. # ifndef CPU_SUBTYPE_POWERPC_970
  91674. # define CPU_SUBTYPE_POWERPC_970 ((cpu_subtype_t) 100)
  91675. # endif
  91676. # else /* FLAC__SYS_DARWIN */
  91677. # include <signal.h>
  91678. # include <setjmp.h>
  91679. static sigjmp_buf jmpbuf;
  91680. static volatile sig_atomic_t canjump = 0;
  91681. static void sigill_handler (int sig)
  91682. {
  91683. if (!canjump) {
  91684. signal (sig, SIG_DFL);
  91685. raise (sig);
  91686. }
  91687. canjump = 0;
  91688. siglongjmp (jmpbuf, 1);
  91689. }
  91690. # endif /* FLAC__SYS_DARWIN */
  91691. # endif /* FLAC__NO_ASM */
  91692. #endif /* FLAC__CPU_PPC */
  91693. #if defined (__NetBSD__) || defined(__OpenBSD__)
  91694. #include <sys/param.h>
  91695. #include <sys/sysctl.h>
  91696. #include <machine/cpu.h>
  91697. #endif
  91698. #if defined(__FreeBSD__) || defined(__FreeBSD_kernel__) || defined(__DragonFly__)
  91699. #include <sys/types.h>
  91700. #include <sys/sysctl.h>
  91701. #endif
  91702. #if defined(__APPLE__)
  91703. /* how to get sysctlbyname()? */
  91704. #endif
  91705. /* these are flags in EDX of CPUID AX=00000001 */
  91706. static const unsigned FLAC__CPUINFO_IA32_CPUID_CMOV = 0x00008000;
  91707. static const unsigned FLAC__CPUINFO_IA32_CPUID_MMX = 0x00800000;
  91708. static const unsigned FLAC__CPUINFO_IA32_CPUID_FXSR = 0x01000000;
  91709. static const unsigned FLAC__CPUINFO_IA32_CPUID_SSE = 0x02000000;
  91710. static const unsigned FLAC__CPUINFO_IA32_CPUID_SSE2 = 0x04000000;
  91711. /* these are flags in ECX of CPUID AX=00000001 */
  91712. static const unsigned FLAC__CPUINFO_IA32_CPUID_SSE3 = 0x00000001;
  91713. static const unsigned FLAC__CPUINFO_IA32_CPUID_SSSE3 = 0x00000200;
  91714. /* these are flags in EDX of CPUID AX=80000001 */
  91715. static const unsigned FLAC__CPUINFO_IA32_CPUID_EXTENDED_AMD_3DNOW = 0x80000000;
  91716. static const unsigned FLAC__CPUINFO_IA32_CPUID_EXTENDED_AMD_EXT3DNOW = 0x40000000;
  91717. static const unsigned FLAC__CPUINFO_IA32_CPUID_EXTENDED_AMD_EXTMMX = 0x00400000;
  91718. /*
  91719. * Extra stuff needed for detection of OS support for SSE on IA-32
  91720. */
  91721. #if defined(FLAC__CPU_IA32) && !defined FLAC__NO_ASM && defined FLAC__HAS_NASM && !defined FLAC__NO_SSE_OS && !defined FLAC__SSE_OS
  91722. # if defined(__linux__)
  91723. /*
  91724. * If the OS doesn't support SSE, we will get here with a SIGILL. We
  91725. * modify the return address to jump over the offending SSE instruction
  91726. * and also the operation following it that indicates the instruction
  91727. * executed successfully. In this way we use no global variables and
  91728. * stay thread-safe.
  91729. *
  91730. * 3 + 3 + 6:
  91731. * 3 bytes for "xorps xmm0,xmm0"
  91732. * 3 bytes for estimate of how long the follwing "inc var" instruction is
  91733. * 6 bytes extra in case our estimate is wrong
  91734. * 12 bytes puts us in the NOP "landing zone"
  91735. */
  91736. # undef USE_OBSOLETE_SIGCONTEXT_FLAVOR /* #define this to use the older signal handler method */
  91737. # ifdef USE_OBSOLETE_SIGCONTEXT_FLAVOR
  91738. static void sigill_handler_sse_os(int signal, struct sigcontext sc)
  91739. {
  91740. (void)signal;
  91741. sc.eip += 3 + 3 + 6;
  91742. }
  91743. # else
  91744. # include <sys/ucontext.h>
  91745. static void sigill_handler_sse_os(int signal, siginfo_t *si, void *uc)
  91746. {
  91747. (void)signal, (void)si;
  91748. ((ucontext_t*)uc)->uc_mcontext.gregs[14/*REG_EIP*/] += 3 + 3 + 6;
  91749. }
  91750. # endif
  91751. # elif defined(_MSC_VER)
  91752. # include <windows.h>
  91753. # undef USE_TRY_CATCH_FLAVOR /* #define this to use the try/catch method for catching illegal opcode exception */
  91754. # ifdef USE_TRY_CATCH_FLAVOR
  91755. # else
  91756. LONG CALLBACK sigill_handler_sse_os(EXCEPTION_POINTERS *ep)
  91757. {
  91758. if(ep->ExceptionRecord->ExceptionCode == EXCEPTION_ILLEGAL_INSTRUCTION) {
  91759. ep->ContextRecord->Eip += 3 + 3 + 6;
  91760. return EXCEPTION_CONTINUE_EXECUTION;
  91761. }
  91762. return EXCEPTION_CONTINUE_SEARCH;
  91763. }
  91764. # endif
  91765. # endif
  91766. #endif
  91767. void FLAC__cpu_info(FLAC__CPUInfo *info)
  91768. {
  91769. /*
  91770. * IA32-specific
  91771. */
  91772. #ifdef FLAC__CPU_IA32
  91773. info->type = FLAC__CPUINFO_TYPE_IA32;
  91774. #if !defined FLAC__NO_ASM && defined FLAC__HAS_NASM
  91775. info->use_asm = true; /* we assume a minimum of 80386 with FLAC__CPU_IA32 */
  91776. info->data.ia32.cpuid = FLAC__cpu_have_cpuid_asm_ia32()? true : false;
  91777. info->data.ia32.bswap = info->data.ia32.cpuid; /* CPUID => BSWAP since it came after */
  91778. info->data.ia32.cmov = false;
  91779. info->data.ia32.mmx = false;
  91780. info->data.ia32.fxsr = false;
  91781. info->data.ia32.sse = false;
  91782. info->data.ia32.sse2 = false;
  91783. info->data.ia32.sse3 = false;
  91784. info->data.ia32.ssse3 = false;
  91785. info->data.ia32._3dnow = false;
  91786. info->data.ia32.ext3dnow = false;
  91787. info->data.ia32.extmmx = false;
  91788. if(info->data.ia32.cpuid) {
  91789. /* http://www.sandpile.org/ia32/cpuid.htm */
  91790. FLAC__uint32 flags_edx, flags_ecx;
  91791. FLAC__cpu_info_asm_ia32(&flags_edx, &flags_ecx);
  91792. info->data.ia32.cmov = (flags_edx & FLAC__CPUINFO_IA32_CPUID_CMOV )? true : false;
  91793. info->data.ia32.mmx = (flags_edx & FLAC__CPUINFO_IA32_CPUID_MMX )? true : false;
  91794. info->data.ia32.fxsr = (flags_edx & FLAC__CPUINFO_IA32_CPUID_FXSR )? true : false;
  91795. info->data.ia32.sse = (flags_edx & FLAC__CPUINFO_IA32_CPUID_SSE )? true : false;
  91796. info->data.ia32.sse2 = (flags_edx & FLAC__CPUINFO_IA32_CPUID_SSE2 )? true : false;
  91797. info->data.ia32.sse3 = (flags_ecx & FLAC__CPUINFO_IA32_CPUID_SSE3 )? true : false;
  91798. info->data.ia32.ssse3 = (flags_ecx & FLAC__CPUINFO_IA32_CPUID_SSSE3)? true : false;
  91799. #ifdef FLAC__USE_3DNOW
  91800. flags_edx = FLAC__cpu_info_extended_amd_asm_ia32();
  91801. info->data.ia32._3dnow = (flags_edx & FLAC__CPUINFO_IA32_CPUID_EXTENDED_AMD_3DNOW )? true : false;
  91802. info->data.ia32.ext3dnow = (flags_edx & FLAC__CPUINFO_IA32_CPUID_EXTENDED_AMD_EXT3DNOW)? true : false;
  91803. info->data.ia32.extmmx = (flags_edx & FLAC__CPUINFO_IA32_CPUID_EXTENDED_AMD_EXTMMX )? true : false;
  91804. #else
  91805. info->data.ia32._3dnow = info->data.ia32.ext3dnow = info->data.ia32.extmmx = false;
  91806. #endif
  91807. #ifdef DEBUG
  91808. fprintf(stderr, "CPU info (IA-32):\n");
  91809. fprintf(stderr, " CPUID ...... %c\n", info->data.ia32.cpuid ? 'Y' : 'n');
  91810. fprintf(stderr, " BSWAP ...... %c\n", info->data.ia32.bswap ? 'Y' : 'n');
  91811. fprintf(stderr, " CMOV ....... %c\n", info->data.ia32.cmov ? 'Y' : 'n');
  91812. fprintf(stderr, " MMX ........ %c\n", info->data.ia32.mmx ? 'Y' : 'n');
  91813. fprintf(stderr, " FXSR ....... %c\n", info->data.ia32.fxsr ? 'Y' : 'n');
  91814. fprintf(stderr, " SSE ........ %c\n", info->data.ia32.sse ? 'Y' : 'n');
  91815. fprintf(stderr, " SSE2 ....... %c\n", info->data.ia32.sse2 ? 'Y' : 'n');
  91816. fprintf(stderr, " SSE3 ....... %c\n", info->data.ia32.sse3 ? 'Y' : 'n');
  91817. fprintf(stderr, " SSSE3 ...... %c\n", info->data.ia32.ssse3 ? 'Y' : 'n');
  91818. fprintf(stderr, " 3DNow! ..... %c\n", info->data.ia32._3dnow ? 'Y' : 'n');
  91819. fprintf(stderr, " 3DNow!-ext . %c\n", info->data.ia32.ext3dnow? 'Y' : 'n');
  91820. fprintf(stderr, " 3DNow!-MMX . %c\n", info->data.ia32.extmmx ? 'Y' : 'n');
  91821. #endif
  91822. /*
  91823. * now have to check for OS support of SSE/SSE2
  91824. */
  91825. if(info->data.ia32.fxsr || info->data.ia32.sse || info->data.ia32.sse2) {
  91826. #if defined FLAC__NO_SSE_OS
  91827. /* assume user knows better than us; turn it off */
  91828. info->data.ia32.fxsr = info->data.ia32.sse = info->data.ia32.sse2 = info->data.ia32.sse3 = info->data.ia32.ssse3 = false;
  91829. #elif defined FLAC__SSE_OS
  91830. /* assume user knows better than us; leave as detected above */
  91831. #elif defined(__FreeBSD__) || defined(__FreeBSD_kernel__) || defined(__DragonFly__) || defined(__APPLE__)
  91832. int sse = 0;
  91833. size_t len;
  91834. /* at least one of these must work: */
  91835. len = sizeof(sse); sse = sse || (sysctlbyname("hw.instruction_sse", &sse, &len, NULL, 0) == 0 && sse);
  91836. len = sizeof(sse); sse = sse || (sysctlbyname("hw.optional.sse" , &sse, &len, NULL, 0) == 0 && sse); /* __APPLE__ ? */
  91837. if(!sse)
  91838. info->data.ia32.fxsr = info->data.ia32.sse = info->data.ia32.sse2 = info->data.ia32.sse3 = info->data.ia32.ssse3 = false;
  91839. #elif defined(__NetBSD__) || defined (__OpenBSD__)
  91840. # if __NetBSD_Version__ >= 105250000 || (defined __OpenBSD__)
  91841. int val = 0, mib[2] = { CTL_MACHDEP, CPU_SSE };
  91842. size_t len = sizeof(val);
  91843. if(sysctl(mib, 2, &val, &len, NULL, 0) < 0 || !val)
  91844. info->data.ia32.fxsr = info->data.ia32.sse = info->data.ia32.sse2 = info->data.ia32.sse3 = info->data.ia32.ssse3 = false;
  91845. else { /* double-check SSE2 */
  91846. mib[1] = CPU_SSE2;
  91847. len = sizeof(val);
  91848. if(sysctl(mib, 2, &val, &len, NULL, 0) < 0 || !val)
  91849. info->data.ia32.sse2 = info->data.ia32.sse3 = info->data.ia32.ssse3 = false;
  91850. }
  91851. # else
  91852. info->data.ia32.fxsr = info->data.ia32.sse = info->data.ia32.sse2 = info->data.ia32.sse3 = info->data.ia32.ssse3 = false;
  91853. # endif
  91854. #elif defined(__linux__)
  91855. int sse = 0;
  91856. struct sigaction sigill_save;
  91857. #ifdef USE_OBSOLETE_SIGCONTEXT_FLAVOR
  91858. if(0 == sigaction(SIGILL, NULL, &sigill_save) && signal(SIGILL, (void (*)(int))sigill_handler_sse_os) != SIG_ERR)
  91859. #else
  91860. struct sigaction sigill_sse;
  91861. sigill_sse.sa_sigaction = sigill_handler_sse_os;
  91862. __sigemptyset(&sigill_sse.sa_mask);
  91863. 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 */
  91864. if(0 == sigaction(SIGILL, &sigill_sse, &sigill_save))
  91865. #endif
  91866. {
  91867. /* http://www.ibiblio.org/gferg/ldp/GCC-Inline-Assembly-HOWTO.html */
  91868. /* see sigill_handler_sse_os() for an explanation of the following: */
  91869. asm volatile (
  91870. "xorl %0,%0\n\t" /* for some reason, still need to do this to clear 'sse' var */
  91871. "xorps %%xmm0,%%xmm0\n\t" /* will cause SIGILL if unsupported by OS */
  91872. "incl %0\n\t" /* SIGILL handler will jump over this */
  91873. /* landing zone */
  91874. "nop\n\t" /* SIGILL jump lands here if "inc" is 9 bytes */
  91875. "nop\n\t"
  91876. "nop\n\t"
  91877. "nop\n\t"
  91878. "nop\n\t"
  91879. "nop\n\t"
  91880. "nop\n\t" /* SIGILL jump lands here if "inc" is 3 bytes (expected) */
  91881. "nop\n\t"
  91882. "nop" /* SIGILL jump lands here if "inc" is 1 byte */
  91883. : "=r"(sse)
  91884. : "r"(sse)
  91885. );
  91886. sigaction(SIGILL, &sigill_save, NULL);
  91887. }
  91888. if(!sse)
  91889. info->data.ia32.fxsr = info->data.ia32.sse = info->data.ia32.sse2 = info->data.ia32.sse3 = info->data.ia32.ssse3 = false;
  91890. #elif defined(_MSC_VER)
  91891. # ifdef USE_TRY_CATCH_FLAVOR
  91892. _try {
  91893. __asm {
  91894. # if _MSC_VER <= 1200
  91895. /* VC6 assembler doesn't know SSE, have to emit bytecode instead */
  91896. _emit 0x0F
  91897. _emit 0x57
  91898. _emit 0xC0
  91899. # else
  91900. xorps xmm0,xmm0
  91901. # endif
  91902. }
  91903. }
  91904. _except(EXCEPTION_EXECUTE_HANDLER) {
  91905. if (_exception_code() == STATUS_ILLEGAL_INSTRUCTION)
  91906. info->data.ia32.fxsr = info->data.ia32.sse = info->data.ia32.sse2 = info->data.ia32.sse3 = info->data.ia32.ssse3 = false;
  91907. }
  91908. # else
  91909. int sse = 0;
  91910. LPTOP_LEVEL_EXCEPTION_FILTER save = SetUnhandledExceptionFilter(sigill_handler_sse_os);
  91911. /* see GCC version above for explanation */
  91912. /* http://msdn2.microsoft.com/en-us/library/4ks26t93.aspx */
  91913. /* http://www.codeproject.com/cpp/gccasm.asp */
  91914. /* http://www.hick.org/~mmiller/msvc_inline_asm.html */
  91915. __asm {
  91916. # if _MSC_VER <= 1200
  91917. /* VC6 assembler doesn't know SSE, have to emit bytecode instead */
  91918. _emit 0x0F
  91919. _emit 0x57
  91920. _emit 0xC0
  91921. # else
  91922. xorps xmm0,xmm0
  91923. # endif
  91924. inc sse
  91925. nop
  91926. nop
  91927. nop
  91928. nop
  91929. nop
  91930. nop
  91931. nop
  91932. nop
  91933. nop
  91934. }
  91935. SetUnhandledExceptionFilter(save);
  91936. if(!sse)
  91937. info->data.ia32.fxsr = info->data.ia32.sse = info->data.ia32.sse2 = info->data.ia32.sse3 = info->data.ia32.ssse3 = false;
  91938. # endif
  91939. #else
  91940. /* no way to test, disable to be safe */
  91941. info->data.ia32.fxsr = info->data.ia32.sse = info->data.ia32.sse2 = info->data.ia32.sse3 = info->data.ia32.ssse3 = false;
  91942. #endif
  91943. #ifdef DEBUG
  91944. fprintf(stderr, " SSE OS sup . %c\n", info->data.ia32.sse ? 'Y' : 'n');
  91945. #endif
  91946. }
  91947. }
  91948. #else
  91949. info->use_asm = false;
  91950. #endif
  91951. /*
  91952. * PPC-specific
  91953. */
  91954. #elif defined FLAC__CPU_PPC
  91955. info->type = FLAC__CPUINFO_TYPE_PPC;
  91956. # if !defined FLAC__NO_ASM
  91957. info->use_asm = true;
  91958. # ifdef FLAC__USE_ALTIVEC
  91959. # if defined FLAC__SYS_DARWIN
  91960. {
  91961. int val = 0, mib[2] = { CTL_HW, HW_VECTORUNIT };
  91962. size_t len = sizeof(val);
  91963. info->data.ppc.altivec = !(sysctl(mib, 2, &val, &len, NULL, 0) || !val);
  91964. }
  91965. {
  91966. host_basic_info_data_t hostInfo;
  91967. mach_msg_type_number_t infoCount;
  91968. infoCount = HOST_BASIC_INFO_COUNT;
  91969. host_info(mach_host_self(), HOST_BASIC_INFO, (host_info_t)&hostInfo, &infoCount);
  91970. info->data.ppc.ppc64 = (hostInfo.cpu_type == CPU_TYPE_POWERPC) && (hostInfo.cpu_subtype == CPU_SUBTYPE_POWERPC_970);
  91971. }
  91972. # else /* FLAC__USE_ALTIVEC && !FLAC__SYS_DARWIN */
  91973. {
  91974. /* no Darwin, do it the brute-force way */
  91975. /* @@@@@@ this is not thread-safe; replace with SSE OS method above or remove */
  91976. info->data.ppc.altivec = 0;
  91977. info->data.ppc.ppc64 = 0;
  91978. signal (SIGILL, sigill_handler);
  91979. canjump = 0;
  91980. if (!sigsetjmp (jmpbuf, 1)) {
  91981. canjump = 1;
  91982. asm volatile (
  91983. "mtspr 256, %0\n\t"
  91984. "vand %%v0, %%v0, %%v0"
  91985. :
  91986. : "r" (-1)
  91987. );
  91988. info->data.ppc.altivec = 1;
  91989. }
  91990. canjump = 0;
  91991. if (!sigsetjmp (jmpbuf, 1)) {
  91992. int x = 0;
  91993. canjump = 1;
  91994. /* PPC64 hardware implements the cntlzd instruction */
  91995. asm volatile ("cntlzd %0, %1" : "=r" (x) : "r" (x) );
  91996. info->data.ppc.ppc64 = 1;
  91997. }
  91998. signal (SIGILL, SIG_DFL); /*@@@@@@ should save and restore old signal */
  91999. }
  92000. # endif
  92001. # else /* !FLAC__USE_ALTIVEC */
  92002. info->data.ppc.altivec = 0;
  92003. info->data.ppc.ppc64 = 0;
  92004. # endif
  92005. # else
  92006. info->use_asm = false;
  92007. # endif
  92008. /*
  92009. * unknown CPI
  92010. */
  92011. #else
  92012. info->type = FLAC__CPUINFO_TYPE_UNKNOWN;
  92013. info->use_asm = false;
  92014. #endif
  92015. }
  92016. #endif
  92017. /*** End of inlined file: cpu.c ***/
  92018. /*** Start of inlined file: crc.c ***/
  92019. /*** Start of inlined file: juce_FlacHeader.h ***/
  92020. // This file is included at the start of each FLAC .c file, just to do a few housekeeping
  92021. // tasks..
  92022. #define VERSION "1.2.1"
  92023. #define FLAC__NO_DLL 1
  92024. #if JUCE_MSVC
  92025. #pragma warning (disable: 4267 4127 4244 4996 4100 4701 4702 4013 4133 4206 4312)
  92026. #endif
  92027. #if JUCE_MAC
  92028. #define FLAC__SYS_DARWIN 1
  92029. #endif
  92030. /*** End of inlined file: juce_FlacHeader.h ***/
  92031. #if JUCE_USE_FLAC
  92032. #if HAVE_CONFIG_H
  92033. # include <config.h>
  92034. #endif
  92035. /* CRC-8, poly = x^8 + x^2 + x^1 + x^0, init = 0 */
  92036. FLAC__byte const FLAC__crc8_table[256] = {
  92037. 0x00, 0x07, 0x0E, 0x09, 0x1C, 0x1B, 0x12, 0x15,
  92038. 0x38, 0x3F, 0x36, 0x31, 0x24, 0x23, 0x2A, 0x2D,
  92039. 0x70, 0x77, 0x7E, 0x79, 0x6C, 0x6B, 0x62, 0x65,
  92040. 0x48, 0x4F, 0x46, 0x41, 0x54, 0x53, 0x5A, 0x5D,
  92041. 0xE0, 0xE7, 0xEE, 0xE9, 0xFC, 0xFB, 0xF2, 0xF5,
  92042. 0xD8, 0xDF, 0xD6, 0xD1, 0xC4, 0xC3, 0xCA, 0xCD,
  92043. 0x90, 0x97, 0x9E, 0x99, 0x8C, 0x8B, 0x82, 0x85,
  92044. 0xA8, 0xAF, 0xA6, 0xA1, 0xB4, 0xB3, 0xBA, 0xBD,
  92045. 0xC7, 0xC0, 0xC9, 0xCE, 0xDB, 0xDC, 0xD5, 0xD2,
  92046. 0xFF, 0xF8, 0xF1, 0xF6, 0xE3, 0xE4, 0xED, 0xEA,
  92047. 0xB7, 0xB0, 0xB9, 0xBE, 0xAB, 0xAC, 0xA5, 0xA2,
  92048. 0x8F, 0x88, 0x81, 0x86, 0x93, 0x94, 0x9D, 0x9A,
  92049. 0x27, 0x20, 0x29, 0x2E, 0x3B, 0x3C, 0x35, 0x32,
  92050. 0x1F, 0x18, 0x11, 0x16, 0x03, 0x04, 0x0D, 0x0A,
  92051. 0x57, 0x50, 0x59, 0x5E, 0x4B, 0x4C, 0x45, 0x42,
  92052. 0x6F, 0x68, 0x61, 0x66, 0x73, 0x74, 0x7D, 0x7A,
  92053. 0x89, 0x8E, 0x87, 0x80, 0x95, 0x92, 0x9B, 0x9C,
  92054. 0xB1, 0xB6, 0xBF, 0xB8, 0xAD, 0xAA, 0xA3, 0xA4,
  92055. 0xF9, 0xFE, 0xF7, 0xF0, 0xE5, 0xE2, 0xEB, 0xEC,
  92056. 0xC1, 0xC6, 0xCF, 0xC8, 0xDD, 0xDA, 0xD3, 0xD4,
  92057. 0x69, 0x6E, 0x67, 0x60, 0x75, 0x72, 0x7B, 0x7C,
  92058. 0x51, 0x56, 0x5F, 0x58, 0x4D, 0x4A, 0x43, 0x44,
  92059. 0x19, 0x1E, 0x17, 0x10, 0x05, 0x02, 0x0B, 0x0C,
  92060. 0x21, 0x26, 0x2F, 0x28, 0x3D, 0x3A, 0x33, 0x34,
  92061. 0x4E, 0x49, 0x40, 0x47, 0x52, 0x55, 0x5C, 0x5B,
  92062. 0x76, 0x71, 0x78, 0x7F, 0x6A, 0x6D, 0x64, 0x63,
  92063. 0x3E, 0x39, 0x30, 0x37, 0x22, 0x25, 0x2C, 0x2B,
  92064. 0x06, 0x01, 0x08, 0x0F, 0x1A, 0x1D, 0x14, 0x13,
  92065. 0xAE, 0xA9, 0xA0, 0xA7, 0xB2, 0xB5, 0xBC, 0xBB,
  92066. 0x96, 0x91, 0x98, 0x9F, 0x8A, 0x8D, 0x84, 0x83,
  92067. 0xDE, 0xD9, 0xD0, 0xD7, 0xC2, 0xC5, 0xCC, 0xCB,
  92068. 0xE6, 0xE1, 0xE8, 0xEF, 0xFA, 0xFD, 0xF4, 0xF3
  92069. };
  92070. /* CRC-16, poly = x^16 + x^15 + x^2 + x^0, init = 0 */
  92071. unsigned FLAC__crc16_table[256] = {
  92072. 0x0000, 0x8005, 0x800f, 0x000a, 0x801b, 0x001e, 0x0014, 0x8011,
  92073. 0x8033, 0x0036, 0x003c, 0x8039, 0x0028, 0x802d, 0x8027, 0x0022,
  92074. 0x8063, 0x0066, 0x006c, 0x8069, 0x0078, 0x807d, 0x8077, 0x0072,
  92075. 0x0050, 0x8055, 0x805f, 0x005a, 0x804b, 0x004e, 0x0044, 0x8041,
  92076. 0x80c3, 0x00c6, 0x00cc, 0x80c9, 0x00d8, 0x80dd, 0x80d7, 0x00d2,
  92077. 0x00f0, 0x80f5, 0x80ff, 0x00fa, 0x80eb, 0x00ee, 0x00e4, 0x80e1,
  92078. 0x00a0, 0x80a5, 0x80af, 0x00aa, 0x80bb, 0x00be, 0x00b4, 0x80b1,
  92079. 0x8093, 0x0096, 0x009c, 0x8099, 0x0088, 0x808d, 0x8087, 0x0082,
  92080. 0x8183, 0x0186, 0x018c, 0x8189, 0x0198, 0x819d, 0x8197, 0x0192,
  92081. 0x01b0, 0x81b5, 0x81bf, 0x01ba, 0x81ab, 0x01ae, 0x01a4, 0x81a1,
  92082. 0x01e0, 0x81e5, 0x81ef, 0x01ea, 0x81fb, 0x01fe, 0x01f4, 0x81f1,
  92083. 0x81d3, 0x01d6, 0x01dc, 0x81d9, 0x01c8, 0x81cd, 0x81c7, 0x01c2,
  92084. 0x0140, 0x8145, 0x814f, 0x014a, 0x815b, 0x015e, 0x0154, 0x8151,
  92085. 0x8173, 0x0176, 0x017c, 0x8179, 0x0168, 0x816d, 0x8167, 0x0162,
  92086. 0x8123, 0x0126, 0x012c, 0x8129, 0x0138, 0x813d, 0x8137, 0x0132,
  92087. 0x0110, 0x8115, 0x811f, 0x011a, 0x810b, 0x010e, 0x0104, 0x8101,
  92088. 0x8303, 0x0306, 0x030c, 0x8309, 0x0318, 0x831d, 0x8317, 0x0312,
  92089. 0x0330, 0x8335, 0x833f, 0x033a, 0x832b, 0x032e, 0x0324, 0x8321,
  92090. 0x0360, 0x8365, 0x836f, 0x036a, 0x837b, 0x037e, 0x0374, 0x8371,
  92091. 0x8353, 0x0356, 0x035c, 0x8359, 0x0348, 0x834d, 0x8347, 0x0342,
  92092. 0x03c0, 0x83c5, 0x83cf, 0x03ca, 0x83db, 0x03de, 0x03d4, 0x83d1,
  92093. 0x83f3, 0x03f6, 0x03fc, 0x83f9, 0x03e8, 0x83ed, 0x83e7, 0x03e2,
  92094. 0x83a3, 0x03a6, 0x03ac, 0x83a9, 0x03b8, 0x83bd, 0x83b7, 0x03b2,
  92095. 0x0390, 0x8395, 0x839f, 0x039a, 0x838b, 0x038e, 0x0384, 0x8381,
  92096. 0x0280, 0x8285, 0x828f, 0x028a, 0x829b, 0x029e, 0x0294, 0x8291,
  92097. 0x82b3, 0x02b6, 0x02bc, 0x82b9, 0x02a8, 0x82ad, 0x82a7, 0x02a2,
  92098. 0x82e3, 0x02e6, 0x02ec, 0x82e9, 0x02f8, 0x82fd, 0x82f7, 0x02f2,
  92099. 0x02d0, 0x82d5, 0x82df, 0x02da, 0x82cb, 0x02ce, 0x02c4, 0x82c1,
  92100. 0x8243, 0x0246, 0x024c, 0x8249, 0x0258, 0x825d, 0x8257, 0x0252,
  92101. 0x0270, 0x8275, 0x827f, 0x027a, 0x826b, 0x026e, 0x0264, 0x8261,
  92102. 0x0220, 0x8225, 0x822f, 0x022a, 0x823b, 0x023e, 0x0234, 0x8231,
  92103. 0x8213, 0x0216, 0x021c, 0x8219, 0x0208, 0x820d, 0x8207, 0x0202
  92104. };
  92105. void FLAC__crc8_update(const FLAC__byte data, FLAC__uint8 *crc)
  92106. {
  92107. *crc = FLAC__crc8_table[*crc ^ data];
  92108. }
  92109. void FLAC__crc8_update_block(const FLAC__byte *data, unsigned len, FLAC__uint8 *crc)
  92110. {
  92111. while(len--)
  92112. *crc = FLAC__crc8_table[*crc ^ *data++];
  92113. }
  92114. FLAC__uint8 FLAC__crc8(const FLAC__byte *data, unsigned len)
  92115. {
  92116. FLAC__uint8 crc = 0;
  92117. while(len--)
  92118. crc = FLAC__crc8_table[crc ^ *data++];
  92119. return crc;
  92120. }
  92121. unsigned FLAC__crc16(const FLAC__byte *data, unsigned len)
  92122. {
  92123. unsigned crc = 0;
  92124. while(len--)
  92125. crc = ((crc<<8) ^ FLAC__crc16_table[(crc>>8) ^ *data++]) & 0xffff;
  92126. return crc;
  92127. }
  92128. #endif
  92129. /*** End of inlined file: crc.c ***/
  92130. /*** Start of inlined file: fixed.c ***/
  92131. /*** Start of inlined file: juce_FlacHeader.h ***/
  92132. // This file is included at the start of each FLAC .c file, just to do a few housekeeping
  92133. // tasks..
  92134. #define VERSION "1.2.1"
  92135. #define FLAC__NO_DLL 1
  92136. #if JUCE_MSVC
  92137. #pragma warning (disable: 4267 4127 4244 4996 4100 4701 4702 4013 4133 4206 4312)
  92138. #endif
  92139. #if JUCE_MAC
  92140. #define FLAC__SYS_DARWIN 1
  92141. #endif
  92142. /*** End of inlined file: juce_FlacHeader.h ***/
  92143. #if JUCE_USE_FLAC
  92144. #if HAVE_CONFIG_H
  92145. # include <config.h>
  92146. #endif
  92147. #include <math.h>
  92148. #include <string.h>
  92149. /*** Start of inlined file: fixed.h ***/
  92150. #ifndef FLAC__PRIVATE__FIXED_H
  92151. #define FLAC__PRIVATE__FIXED_H
  92152. #ifdef HAVE_CONFIG_H
  92153. #include <config.h>
  92154. #endif
  92155. /*** Start of inlined file: float.h ***/
  92156. #ifndef FLAC__PRIVATE__FLOAT_H
  92157. #define FLAC__PRIVATE__FLOAT_H
  92158. #ifdef HAVE_CONFIG_H
  92159. #include <config.h>
  92160. #endif
  92161. /*
  92162. * These typedefs make it easier to ensure that integer versions of
  92163. * the library really only contain integer operations. All the code
  92164. * in libFLAC should use FLAC__float and FLAC__double in place of
  92165. * float and double, and be protected by checks of the macro
  92166. * FLAC__INTEGER_ONLY_LIBRARY.
  92167. *
  92168. * FLAC__real is the basic floating point type used in LPC analysis.
  92169. */
  92170. #ifndef FLAC__INTEGER_ONLY_LIBRARY
  92171. typedef double FLAC__double;
  92172. typedef float FLAC__float;
  92173. /*
  92174. * WATCHOUT: changing FLAC__real will change the signatures of many
  92175. * functions that have assembly language equivalents and break them.
  92176. */
  92177. typedef float FLAC__real;
  92178. #else
  92179. /*
  92180. * The convention for FLAC__fixedpoint is to use the upper 16 bits
  92181. * for the integer part and lower 16 bits for the fractional part.
  92182. */
  92183. typedef FLAC__int32 FLAC__fixedpoint;
  92184. extern const FLAC__fixedpoint FLAC__FP_ZERO;
  92185. extern const FLAC__fixedpoint FLAC__FP_ONE_HALF;
  92186. extern const FLAC__fixedpoint FLAC__FP_ONE;
  92187. extern const FLAC__fixedpoint FLAC__FP_LN2;
  92188. extern const FLAC__fixedpoint FLAC__FP_E;
  92189. #define FLAC__fixedpoint_trunc(x) ((x)>>16)
  92190. #define FLAC__fixedpoint_mul(x, y) ( (FLAC__fixedpoint) ( ((FLAC__int64)(x)*(FLAC__int64)(y)) >> 16 ) )
  92191. #define FLAC__fixedpoint_div(x, y) ( (FLAC__fixedpoint) ( ( ((FLAC__int64)(x)<<32) / (FLAC__int64)(y) ) >> 16 ) )
  92192. /*
  92193. * FLAC__fixedpoint_log2()
  92194. * --------------------------------------------------------------------
  92195. * Returns the base-2 logarithm of the fixed-point number 'x' using an
  92196. * algorithm by Knuth for x >= 1.0
  92197. *
  92198. * 'fracbits' is the number of fractional bits of 'x'. 'fracbits' must
  92199. * be < 32 and evenly divisible by 4 (0 is OK but not very precise).
  92200. *
  92201. * 'precision' roughly limits the number of iterations that are done;
  92202. * use (unsigned)(-1) for maximum precision.
  92203. *
  92204. * If 'x' is less than one -- that is, x < (1<<fracbits) -- then this
  92205. * function will punt and return 0.
  92206. *
  92207. * The return value will also have 'fracbits' fractional bits.
  92208. */
  92209. FLAC__uint32 FLAC__fixedpoint_log2(FLAC__uint32 x, unsigned fracbits, unsigned precision);
  92210. #endif
  92211. #endif
  92212. /*** End of inlined file: float.h ***/
  92213. /*** Start of inlined file: format.h ***/
  92214. #ifndef FLAC__PRIVATE__FORMAT_H
  92215. #define FLAC__PRIVATE__FORMAT_H
  92216. unsigned FLAC__format_get_max_rice_partition_order(unsigned blocksize, unsigned predictor_order);
  92217. unsigned FLAC__format_get_max_rice_partition_order_from_blocksize(unsigned blocksize);
  92218. unsigned FLAC__format_get_max_rice_partition_order_from_blocksize_limited_max_and_predictor_order(unsigned limit, unsigned blocksize, unsigned predictor_order);
  92219. void FLAC__format_entropy_coding_method_partitioned_rice_contents_init(FLAC__EntropyCodingMethod_PartitionedRiceContents *object);
  92220. void FLAC__format_entropy_coding_method_partitioned_rice_contents_clear(FLAC__EntropyCodingMethod_PartitionedRiceContents *object);
  92221. FLAC__bool FLAC__format_entropy_coding_method_partitioned_rice_contents_ensure_size(FLAC__EntropyCodingMethod_PartitionedRiceContents *object, unsigned max_partition_order);
  92222. #endif
  92223. /*** End of inlined file: format.h ***/
  92224. /*
  92225. * FLAC__fixed_compute_best_predictor()
  92226. * --------------------------------------------------------------------
  92227. * Compute the best fixed predictor and the expected bits-per-sample
  92228. * of the residual signal for each order. The _wide() version uses
  92229. * 64-bit integers which is statistically necessary when bits-per-
  92230. * sample + log2(blocksize) > 30
  92231. *
  92232. * IN data[0,data_len-1]
  92233. * IN data_len
  92234. * OUT residual_bits_per_sample[0,FLAC__MAX_FIXED_ORDER]
  92235. */
  92236. #ifndef FLAC__INTEGER_ONLY_LIBRARY
  92237. unsigned FLAC__fixed_compute_best_predictor(const FLAC__int32 data[], unsigned data_len, FLAC__float residual_bits_per_sample[FLAC__MAX_FIXED_ORDER+1]);
  92238. # ifndef FLAC__NO_ASM
  92239. # ifdef FLAC__CPU_IA32
  92240. # ifdef FLAC__HAS_NASM
  92241. 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]);
  92242. # endif
  92243. # endif
  92244. # endif
  92245. 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]);
  92246. #else
  92247. unsigned FLAC__fixed_compute_best_predictor(const FLAC__int32 data[], unsigned data_len, FLAC__fixedpoint residual_bits_per_sample[FLAC__MAX_FIXED_ORDER+1]);
  92248. 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]);
  92249. #endif
  92250. /*
  92251. * FLAC__fixed_compute_residual()
  92252. * --------------------------------------------------------------------
  92253. * Compute the residual signal obtained from sutracting the predicted
  92254. * signal from the original.
  92255. *
  92256. * IN data[-order,data_len-1] original signal (NOTE THE INDICES!)
  92257. * IN data_len length of original signal
  92258. * IN order <= FLAC__MAX_FIXED_ORDER fixed-predictor order
  92259. * OUT residual[0,data_len-1] residual signal
  92260. */
  92261. void FLAC__fixed_compute_residual(const FLAC__int32 data[], unsigned data_len, unsigned order, FLAC__int32 residual[]);
  92262. /*
  92263. * FLAC__fixed_restore_signal()
  92264. * --------------------------------------------------------------------
  92265. * Restore the original signal by summing the residual and the
  92266. * predictor.
  92267. *
  92268. * IN residual[0,data_len-1] residual signal
  92269. * IN data_len length of original signal
  92270. * IN order <= FLAC__MAX_FIXED_ORDER fixed-predictor order
  92271. * *** IMPORTANT: the caller must pass in the historical samples:
  92272. * IN data[-order,-1] previously-reconstructed historical samples
  92273. * OUT data[0,data_len-1] original signal
  92274. */
  92275. void FLAC__fixed_restore_signal(const FLAC__int32 residual[], unsigned data_len, unsigned order, FLAC__int32 data[]);
  92276. #endif
  92277. /*** End of inlined file: fixed.h ***/
  92278. #ifndef M_LN2
  92279. /* math.h in VC++ doesn't seem to have this (how Microsoft is that?) */
  92280. #define M_LN2 0.69314718055994530942
  92281. #endif
  92282. #ifdef min
  92283. #undef min
  92284. #endif
  92285. #define min(x,y) ((x) < (y)? (x) : (y))
  92286. #ifdef local_abs
  92287. #undef local_abs
  92288. #endif
  92289. #define local_abs(x) ((unsigned)((x)<0? -(x) : (x)))
  92290. #ifdef FLAC__INTEGER_ONLY_LIBRARY
  92291. /* rbps stands for residual bits per sample
  92292. *
  92293. * (ln(2) * err)
  92294. * rbps = log (-----------)
  92295. * 2 ( n )
  92296. */
  92297. static FLAC__fixedpoint local__compute_rbps_integerized(FLAC__uint32 err, FLAC__uint32 n)
  92298. {
  92299. FLAC__uint32 rbps;
  92300. unsigned bits; /* the number of bits required to represent a number */
  92301. int fracbits; /* the number of bits of rbps that comprise the fractional part */
  92302. FLAC__ASSERT(sizeof(rbps) == sizeof(FLAC__fixedpoint));
  92303. FLAC__ASSERT(err > 0);
  92304. FLAC__ASSERT(n > 0);
  92305. FLAC__ASSERT(n <= FLAC__MAX_BLOCK_SIZE);
  92306. if(err <= n)
  92307. return 0;
  92308. /*
  92309. * The above two things tell us 1) n fits in 16 bits; 2) err/n > 1.
  92310. * These allow us later to know we won't lose too much precision in the
  92311. * fixed-point division (err<<fracbits)/n.
  92312. */
  92313. fracbits = (8*sizeof(err)) - (FLAC__bitmath_ilog2(err)+1);
  92314. err <<= fracbits;
  92315. err /= n;
  92316. /* err now holds err/n with fracbits fractional bits */
  92317. /*
  92318. * Whittle err down to 16 bits max. 16 significant bits is enough for
  92319. * our purposes.
  92320. */
  92321. FLAC__ASSERT(err > 0);
  92322. bits = FLAC__bitmath_ilog2(err)+1;
  92323. if(bits > 16) {
  92324. err >>= (bits-16);
  92325. fracbits -= (bits-16);
  92326. }
  92327. rbps = (FLAC__uint32)err;
  92328. /* Multiply by fixed-point version of ln(2), with 16 fractional bits */
  92329. rbps *= FLAC__FP_LN2;
  92330. fracbits += 16;
  92331. FLAC__ASSERT(fracbits >= 0);
  92332. /* FLAC__fixedpoint_log2 requires fracbits%4 to be 0 */
  92333. {
  92334. const int f = fracbits & 3;
  92335. if(f) {
  92336. rbps >>= f;
  92337. fracbits -= f;
  92338. }
  92339. }
  92340. rbps = FLAC__fixedpoint_log2(rbps, fracbits, (unsigned)(-1));
  92341. if(rbps == 0)
  92342. return 0;
  92343. /*
  92344. * The return value must have 16 fractional bits. Since the whole part
  92345. * of the base-2 log of a 32 bit number must fit in 5 bits, and fracbits
  92346. * must be >= -3, these assertion allows us to be able to shift rbps
  92347. * left if necessary to get 16 fracbits without losing any bits of the
  92348. * whole part of rbps.
  92349. *
  92350. * There is a slight chance due to accumulated error that the whole part
  92351. * will require 6 bits, so we use 6 in the assertion. Really though as
  92352. * long as it fits in 13 bits (32 - (16 - (-3))) we are fine.
  92353. */
  92354. FLAC__ASSERT((int)FLAC__bitmath_ilog2(rbps)+1 <= fracbits + 6);
  92355. FLAC__ASSERT(fracbits >= -3);
  92356. /* now shift the decimal point into place */
  92357. if(fracbits < 16)
  92358. return rbps << (16-fracbits);
  92359. else if(fracbits > 16)
  92360. return rbps >> (fracbits-16);
  92361. else
  92362. return rbps;
  92363. }
  92364. static FLAC__fixedpoint local__compute_rbps_wide_integerized(FLAC__uint64 err, FLAC__uint32 n)
  92365. {
  92366. FLAC__uint32 rbps;
  92367. unsigned bits; /* the number of bits required to represent a number */
  92368. int fracbits; /* the number of bits of rbps that comprise the fractional part */
  92369. FLAC__ASSERT(sizeof(rbps) == sizeof(FLAC__fixedpoint));
  92370. FLAC__ASSERT(err > 0);
  92371. FLAC__ASSERT(n > 0);
  92372. FLAC__ASSERT(n <= FLAC__MAX_BLOCK_SIZE);
  92373. if(err <= n)
  92374. return 0;
  92375. /*
  92376. * The above two things tell us 1) n fits in 16 bits; 2) err/n > 1.
  92377. * These allow us later to know we won't lose too much precision in the
  92378. * fixed-point division (err<<fracbits)/n.
  92379. */
  92380. fracbits = (8*sizeof(err)) - (FLAC__bitmath_ilog2_wide(err)+1);
  92381. err <<= fracbits;
  92382. err /= n;
  92383. /* err now holds err/n with fracbits fractional bits */
  92384. /*
  92385. * Whittle err down to 16 bits max. 16 significant bits is enough for
  92386. * our purposes.
  92387. */
  92388. FLAC__ASSERT(err > 0);
  92389. bits = FLAC__bitmath_ilog2_wide(err)+1;
  92390. if(bits > 16) {
  92391. err >>= (bits-16);
  92392. fracbits -= (bits-16);
  92393. }
  92394. rbps = (FLAC__uint32)err;
  92395. /* Multiply by fixed-point version of ln(2), with 16 fractional bits */
  92396. rbps *= FLAC__FP_LN2;
  92397. fracbits += 16;
  92398. FLAC__ASSERT(fracbits >= 0);
  92399. /* FLAC__fixedpoint_log2 requires fracbits%4 to be 0 */
  92400. {
  92401. const int f = fracbits & 3;
  92402. if(f) {
  92403. rbps >>= f;
  92404. fracbits -= f;
  92405. }
  92406. }
  92407. rbps = FLAC__fixedpoint_log2(rbps, fracbits, (unsigned)(-1));
  92408. if(rbps == 0)
  92409. return 0;
  92410. /*
  92411. * The return value must have 16 fractional bits. Since the whole part
  92412. * of the base-2 log of a 32 bit number must fit in 5 bits, and fracbits
  92413. * must be >= -3, these assertion allows us to be able to shift rbps
  92414. * left if necessary to get 16 fracbits without losing any bits of the
  92415. * whole part of rbps.
  92416. *
  92417. * There is a slight chance due to accumulated error that the whole part
  92418. * will require 6 bits, so we use 6 in the assertion. Really though as
  92419. * long as it fits in 13 bits (32 - (16 - (-3))) we are fine.
  92420. */
  92421. FLAC__ASSERT((int)FLAC__bitmath_ilog2(rbps)+1 <= fracbits + 6);
  92422. FLAC__ASSERT(fracbits >= -3);
  92423. /* now shift the decimal point into place */
  92424. if(fracbits < 16)
  92425. return rbps << (16-fracbits);
  92426. else if(fracbits > 16)
  92427. return rbps >> (fracbits-16);
  92428. else
  92429. return rbps;
  92430. }
  92431. #endif
  92432. #ifndef FLAC__INTEGER_ONLY_LIBRARY
  92433. unsigned FLAC__fixed_compute_best_predictor(const FLAC__int32 data[], unsigned data_len, FLAC__float residual_bits_per_sample[FLAC__MAX_FIXED_ORDER+1])
  92434. #else
  92435. unsigned FLAC__fixed_compute_best_predictor(const FLAC__int32 data[], unsigned data_len, FLAC__fixedpoint residual_bits_per_sample[FLAC__MAX_FIXED_ORDER+1])
  92436. #endif
  92437. {
  92438. FLAC__int32 last_error_0 = data[-1];
  92439. FLAC__int32 last_error_1 = data[-1] - data[-2];
  92440. FLAC__int32 last_error_2 = last_error_1 - (data[-2] - data[-3]);
  92441. FLAC__int32 last_error_3 = last_error_2 - (data[-2] - 2*data[-3] + data[-4]);
  92442. FLAC__int32 error, save;
  92443. FLAC__uint32 total_error_0 = 0, total_error_1 = 0, total_error_2 = 0, total_error_3 = 0, total_error_4 = 0;
  92444. unsigned i, order;
  92445. for(i = 0; i < data_len; i++) {
  92446. error = data[i] ; total_error_0 += local_abs(error); save = error;
  92447. error -= last_error_0; total_error_1 += local_abs(error); last_error_0 = save; save = error;
  92448. error -= last_error_1; total_error_2 += local_abs(error); last_error_1 = save; save = error;
  92449. error -= last_error_2; total_error_3 += local_abs(error); last_error_2 = save; save = error;
  92450. error -= last_error_3; total_error_4 += local_abs(error); last_error_3 = save;
  92451. }
  92452. if(total_error_0 < min(min(min(total_error_1, total_error_2), total_error_3), total_error_4))
  92453. order = 0;
  92454. else if(total_error_1 < min(min(total_error_2, total_error_3), total_error_4))
  92455. order = 1;
  92456. else if(total_error_2 < min(total_error_3, total_error_4))
  92457. order = 2;
  92458. else if(total_error_3 < total_error_4)
  92459. order = 3;
  92460. else
  92461. order = 4;
  92462. /* Estimate the expected number of bits per residual signal sample. */
  92463. /* 'total_error*' is linearly related to the variance of the residual */
  92464. /* signal, so we use it directly to compute E(|x|) */
  92465. FLAC__ASSERT(data_len > 0 || total_error_0 == 0);
  92466. FLAC__ASSERT(data_len > 0 || total_error_1 == 0);
  92467. FLAC__ASSERT(data_len > 0 || total_error_2 == 0);
  92468. FLAC__ASSERT(data_len > 0 || total_error_3 == 0);
  92469. FLAC__ASSERT(data_len > 0 || total_error_4 == 0);
  92470. #ifndef FLAC__INTEGER_ONLY_LIBRARY
  92471. 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);
  92472. 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);
  92473. 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);
  92474. 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);
  92475. 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);
  92476. #else
  92477. residual_bits_per_sample[0] = (total_error_0 > 0) ? local__compute_rbps_integerized(total_error_0, data_len) : 0;
  92478. residual_bits_per_sample[1] = (total_error_1 > 0) ? local__compute_rbps_integerized(total_error_1, data_len) : 0;
  92479. residual_bits_per_sample[2] = (total_error_2 > 0) ? local__compute_rbps_integerized(total_error_2, data_len) : 0;
  92480. residual_bits_per_sample[3] = (total_error_3 > 0) ? local__compute_rbps_integerized(total_error_3, data_len) : 0;
  92481. residual_bits_per_sample[4] = (total_error_4 > 0) ? local__compute_rbps_integerized(total_error_4, data_len) : 0;
  92482. #endif
  92483. return order;
  92484. }
  92485. #ifndef FLAC__INTEGER_ONLY_LIBRARY
  92486. 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])
  92487. #else
  92488. 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])
  92489. #endif
  92490. {
  92491. FLAC__int32 last_error_0 = data[-1];
  92492. FLAC__int32 last_error_1 = data[-1] - data[-2];
  92493. FLAC__int32 last_error_2 = last_error_1 - (data[-2] - data[-3]);
  92494. FLAC__int32 last_error_3 = last_error_2 - (data[-2] - 2*data[-3] + data[-4]);
  92495. FLAC__int32 error, save;
  92496. /* total_error_* are 64-bits to avoid overflow when encoding
  92497. * erratic signals when the bits-per-sample and blocksize are
  92498. * large.
  92499. */
  92500. FLAC__uint64 total_error_0 = 0, total_error_1 = 0, total_error_2 = 0, total_error_3 = 0, total_error_4 = 0;
  92501. unsigned i, order;
  92502. for(i = 0; i < data_len; i++) {
  92503. error = data[i] ; total_error_0 += local_abs(error); save = error;
  92504. error -= last_error_0; total_error_1 += local_abs(error); last_error_0 = save; save = error;
  92505. error -= last_error_1; total_error_2 += local_abs(error); last_error_1 = save; save = error;
  92506. error -= last_error_2; total_error_3 += local_abs(error); last_error_2 = save; save = error;
  92507. error -= last_error_3; total_error_4 += local_abs(error); last_error_3 = save;
  92508. }
  92509. if(total_error_0 < min(min(min(total_error_1, total_error_2), total_error_3), total_error_4))
  92510. order = 0;
  92511. else if(total_error_1 < min(min(total_error_2, total_error_3), total_error_4))
  92512. order = 1;
  92513. else if(total_error_2 < min(total_error_3, total_error_4))
  92514. order = 2;
  92515. else if(total_error_3 < total_error_4)
  92516. order = 3;
  92517. else
  92518. order = 4;
  92519. /* Estimate the expected number of bits per residual signal sample. */
  92520. /* 'total_error*' is linearly related to the variance of the residual */
  92521. /* signal, so we use it directly to compute E(|x|) */
  92522. FLAC__ASSERT(data_len > 0 || total_error_0 == 0);
  92523. FLAC__ASSERT(data_len > 0 || total_error_1 == 0);
  92524. FLAC__ASSERT(data_len > 0 || total_error_2 == 0);
  92525. FLAC__ASSERT(data_len > 0 || total_error_3 == 0);
  92526. FLAC__ASSERT(data_len > 0 || total_error_4 == 0);
  92527. #ifndef FLAC__INTEGER_ONLY_LIBRARY
  92528. #if defined _MSC_VER || defined __MINGW32__
  92529. /* with MSVC you have to spoon feed it the casting */
  92530. 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);
  92531. 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);
  92532. 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);
  92533. 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);
  92534. 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);
  92535. #else
  92536. 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);
  92537. 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);
  92538. 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);
  92539. 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);
  92540. 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);
  92541. #endif
  92542. #else
  92543. residual_bits_per_sample[0] = (total_error_0 > 0) ? local__compute_rbps_wide_integerized(total_error_0, data_len) : 0;
  92544. residual_bits_per_sample[1] = (total_error_1 > 0) ? local__compute_rbps_wide_integerized(total_error_1, data_len) : 0;
  92545. residual_bits_per_sample[2] = (total_error_2 > 0) ? local__compute_rbps_wide_integerized(total_error_2, data_len) : 0;
  92546. residual_bits_per_sample[3] = (total_error_3 > 0) ? local__compute_rbps_wide_integerized(total_error_3, data_len) : 0;
  92547. residual_bits_per_sample[4] = (total_error_4 > 0) ? local__compute_rbps_wide_integerized(total_error_4, data_len) : 0;
  92548. #endif
  92549. return order;
  92550. }
  92551. void FLAC__fixed_compute_residual(const FLAC__int32 data[], unsigned data_len, unsigned order, FLAC__int32 residual[])
  92552. {
  92553. const int idata_len = (int)data_len;
  92554. int i;
  92555. switch(order) {
  92556. case 0:
  92557. FLAC__ASSERT(sizeof(residual[0]) == sizeof(data[0]));
  92558. memcpy(residual, data, sizeof(residual[0])*data_len);
  92559. break;
  92560. case 1:
  92561. for(i = 0; i < idata_len; i++)
  92562. residual[i] = data[i] - data[i-1];
  92563. break;
  92564. case 2:
  92565. for(i = 0; i < idata_len; i++)
  92566. #if 1 /* OPT: may be faster with some compilers on some systems */
  92567. residual[i] = data[i] - (data[i-1] << 1) + data[i-2];
  92568. #else
  92569. residual[i] = data[i] - 2*data[i-1] + data[i-2];
  92570. #endif
  92571. break;
  92572. case 3:
  92573. for(i = 0; i < idata_len; i++)
  92574. #if 1 /* OPT: may be faster with some compilers on some systems */
  92575. residual[i] = data[i] - (((data[i-1]-data[i-2])<<1) + (data[i-1]-data[i-2])) - data[i-3];
  92576. #else
  92577. residual[i] = data[i] - 3*data[i-1] + 3*data[i-2] - data[i-3];
  92578. #endif
  92579. break;
  92580. case 4:
  92581. for(i = 0; i < idata_len; i++)
  92582. #if 1 /* OPT: may be faster with some compilers on some systems */
  92583. residual[i] = data[i] - ((data[i-1]+data[i-3])<<2) + ((data[i-2]<<2) + (data[i-2]<<1)) + data[i-4];
  92584. #else
  92585. residual[i] = data[i] - 4*data[i-1] + 6*data[i-2] - 4*data[i-3] + data[i-4];
  92586. #endif
  92587. break;
  92588. default:
  92589. FLAC__ASSERT(0);
  92590. }
  92591. }
  92592. void FLAC__fixed_restore_signal(const FLAC__int32 residual[], unsigned data_len, unsigned order, FLAC__int32 data[])
  92593. {
  92594. int i, idata_len = (int)data_len;
  92595. switch(order) {
  92596. case 0:
  92597. FLAC__ASSERT(sizeof(residual[0]) == sizeof(data[0]));
  92598. memcpy(data, residual, sizeof(residual[0])*data_len);
  92599. break;
  92600. case 1:
  92601. for(i = 0; i < idata_len; i++)
  92602. data[i] = residual[i] + data[i-1];
  92603. break;
  92604. case 2:
  92605. for(i = 0; i < idata_len; i++)
  92606. #if 1 /* OPT: may be faster with some compilers on some systems */
  92607. data[i] = residual[i] + (data[i-1]<<1) - data[i-2];
  92608. #else
  92609. data[i] = residual[i] + 2*data[i-1] - data[i-2];
  92610. #endif
  92611. break;
  92612. case 3:
  92613. for(i = 0; i < idata_len; i++)
  92614. #if 1 /* OPT: may be faster with some compilers on some systems */
  92615. data[i] = residual[i] + (((data[i-1]-data[i-2])<<1) + (data[i-1]-data[i-2])) + data[i-3];
  92616. #else
  92617. data[i] = residual[i] + 3*data[i-1] - 3*data[i-2] + data[i-3];
  92618. #endif
  92619. break;
  92620. case 4:
  92621. for(i = 0; i < idata_len; i++)
  92622. #if 1 /* OPT: may be faster with some compilers on some systems */
  92623. data[i] = residual[i] + ((data[i-1]+data[i-3])<<2) - ((data[i-2]<<2) + (data[i-2]<<1)) - data[i-4];
  92624. #else
  92625. data[i] = residual[i] + 4*data[i-1] - 6*data[i-2] + 4*data[i-3] - data[i-4];
  92626. #endif
  92627. break;
  92628. default:
  92629. FLAC__ASSERT(0);
  92630. }
  92631. }
  92632. #endif
  92633. /*** End of inlined file: fixed.c ***/
  92634. /*** Start of inlined file: float.c ***/
  92635. /*** Start of inlined file: juce_FlacHeader.h ***/
  92636. // This file is included at the start of each FLAC .c file, just to do a few housekeeping
  92637. // tasks..
  92638. #define VERSION "1.2.1"
  92639. #define FLAC__NO_DLL 1
  92640. #if JUCE_MSVC
  92641. #pragma warning (disable: 4267 4127 4244 4996 4100 4701 4702 4013 4133 4206 4312)
  92642. #endif
  92643. #if JUCE_MAC
  92644. #define FLAC__SYS_DARWIN 1
  92645. #endif
  92646. /*** End of inlined file: juce_FlacHeader.h ***/
  92647. #if JUCE_USE_FLAC
  92648. #if HAVE_CONFIG_H
  92649. # include <config.h>
  92650. #endif
  92651. #ifdef FLAC__INTEGER_ONLY_LIBRARY
  92652. /* adjust for compilers that can't understand using LLU suffix for uint64_t literals */
  92653. #ifdef _MSC_VER
  92654. #define FLAC__U64L(x) x
  92655. #else
  92656. #define FLAC__U64L(x) x##LLU
  92657. #endif
  92658. const FLAC__fixedpoint FLAC__FP_ZERO = 0;
  92659. const FLAC__fixedpoint FLAC__FP_ONE_HALF = 0x00008000;
  92660. const FLAC__fixedpoint FLAC__FP_ONE = 0x00010000;
  92661. const FLAC__fixedpoint FLAC__FP_LN2 = 45426;
  92662. const FLAC__fixedpoint FLAC__FP_E = 178145;
  92663. /* Lookup tables for Knuth's logarithm algorithm */
  92664. #define LOG2_LOOKUP_PRECISION 16
  92665. static const FLAC__uint32 log2_lookup[][LOG2_LOOKUP_PRECISION] = {
  92666. {
  92667. /*
  92668. * 0 fraction bits
  92669. */
  92670. /* undefined */ 0x00000000,
  92671. /* lg(2/1) = */ 0x00000001,
  92672. /* lg(4/3) = */ 0x00000000,
  92673. /* lg(8/7) = */ 0x00000000,
  92674. /* lg(16/15) = */ 0x00000000,
  92675. /* lg(32/31) = */ 0x00000000,
  92676. /* lg(64/63) = */ 0x00000000,
  92677. /* lg(128/127) = */ 0x00000000,
  92678. /* lg(256/255) = */ 0x00000000,
  92679. /* lg(512/511) = */ 0x00000000,
  92680. /* lg(1024/1023) = */ 0x00000000,
  92681. /* lg(2048/2047) = */ 0x00000000,
  92682. /* lg(4096/4095) = */ 0x00000000,
  92683. /* lg(8192/8191) = */ 0x00000000,
  92684. /* lg(16384/16383) = */ 0x00000000,
  92685. /* lg(32768/32767) = */ 0x00000000
  92686. },
  92687. {
  92688. /*
  92689. * 4 fraction bits
  92690. */
  92691. /* undefined */ 0x00000000,
  92692. /* lg(2/1) = */ 0x00000010,
  92693. /* lg(4/3) = */ 0x00000007,
  92694. /* lg(8/7) = */ 0x00000003,
  92695. /* lg(16/15) = */ 0x00000001,
  92696. /* lg(32/31) = */ 0x00000001,
  92697. /* lg(64/63) = */ 0x00000000,
  92698. /* lg(128/127) = */ 0x00000000,
  92699. /* lg(256/255) = */ 0x00000000,
  92700. /* lg(512/511) = */ 0x00000000,
  92701. /* lg(1024/1023) = */ 0x00000000,
  92702. /* lg(2048/2047) = */ 0x00000000,
  92703. /* lg(4096/4095) = */ 0x00000000,
  92704. /* lg(8192/8191) = */ 0x00000000,
  92705. /* lg(16384/16383) = */ 0x00000000,
  92706. /* lg(32768/32767) = */ 0x00000000
  92707. },
  92708. {
  92709. /*
  92710. * 8 fraction bits
  92711. */
  92712. /* undefined */ 0x00000000,
  92713. /* lg(2/1) = */ 0x00000100,
  92714. /* lg(4/3) = */ 0x0000006a,
  92715. /* lg(8/7) = */ 0x00000031,
  92716. /* lg(16/15) = */ 0x00000018,
  92717. /* lg(32/31) = */ 0x0000000c,
  92718. /* lg(64/63) = */ 0x00000006,
  92719. /* lg(128/127) = */ 0x00000003,
  92720. /* lg(256/255) = */ 0x00000001,
  92721. /* lg(512/511) = */ 0x00000001,
  92722. /* lg(1024/1023) = */ 0x00000000,
  92723. /* lg(2048/2047) = */ 0x00000000,
  92724. /* lg(4096/4095) = */ 0x00000000,
  92725. /* lg(8192/8191) = */ 0x00000000,
  92726. /* lg(16384/16383) = */ 0x00000000,
  92727. /* lg(32768/32767) = */ 0x00000000
  92728. },
  92729. {
  92730. /*
  92731. * 12 fraction bits
  92732. */
  92733. /* undefined */ 0x00000000,
  92734. /* lg(2/1) = */ 0x00001000,
  92735. /* lg(4/3) = */ 0x000006a4,
  92736. /* lg(8/7) = */ 0x00000315,
  92737. /* lg(16/15) = */ 0x0000017d,
  92738. /* lg(32/31) = */ 0x000000bc,
  92739. /* lg(64/63) = */ 0x0000005d,
  92740. /* lg(128/127) = */ 0x0000002e,
  92741. /* lg(256/255) = */ 0x00000017,
  92742. /* lg(512/511) = */ 0x0000000c,
  92743. /* lg(1024/1023) = */ 0x00000006,
  92744. /* lg(2048/2047) = */ 0x00000003,
  92745. /* lg(4096/4095) = */ 0x00000001,
  92746. /* lg(8192/8191) = */ 0x00000001,
  92747. /* lg(16384/16383) = */ 0x00000000,
  92748. /* lg(32768/32767) = */ 0x00000000
  92749. },
  92750. {
  92751. /*
  92752. * 16 fraction bits
  92753. */
  92754. /* undefined */ 0x00000000,
  92755. /* lg(2/1) = */ 0x00010000,
  92756. /* lg(4/3) = */ 0x00006a40,
  92757. /* lg(8/7) = */ 0x00003151,
  92758. /* lg(16/15) = */ 0x000017d6,
  92759. /* lg(32/31) = */ 0x00000bba,
  92760. /* lg(64/63) = */ 0x000005d1,
  92761. /* lg(128/127) = */ 0x000002e6,
  92762. /* lg(256/255) = */ 0x00000172,
  92763. /* lg(512/511) = */ 0x000000b9,
  92764. /* lg(1024/1023) = */ 0x0000005c,
  92765. /* lg(2048/2047) = */ 0x0000002e,
  92766. /* lg(4096/4095) = */ 0x00000017,
  92767. /* lg(8192/8191) = */ 0x0000000c,
  92768. /* lg(16384/16383) = */ 0x00000006,
  92769. /* lg(32768/32767) = */ 0x00000003
  92770. },
  92771. {
  92772. /*
  92773. * 20 fraction bits
  92774. */
  92775. /* undefined */ 0x00000000,
  92776. /* lg(2/1) = */ 0x00100000,
  92777. /* lg(4/3) = */ 0x0006a3fe,
  92778. /* lg(8/7) = */ 0x00031513,
  92779. /* lg(16/15) = */ 0x00017d60,
  92780. /* lg(32/31) = */ 0x0000bb9d,
  92781. /* lg(64/63) = */ 0x00005d10,
  92782. /* lg(128/127) = */ 0x00002e59,
  92783. /* lg(256/255) = */ 0x00001721,
  92784. /* lg(512/511) = */ 0x00000b8e,
  92785. /* lg(1024/1023) = */ 0x000005c6,
  92786. /* lg(2048/2047) = */ 0x000002e3,
  92787. /* lg(4096/4095) = */ 0x00000171,
  92788. /* lg(8192/8191) = */ 0x000000b9,
  92789. /* lg(16384/16383) = */ 0x0000005c,
  92790. /* lg(32768/32767) = */ 0x0000002e
  92791. },
  92792. {
  92793. /*
  92794. * 24 fraction bits
  92795. */
  92796. /* undefined */ 0x00000000,
  92797. /* lg(2/1) = */ 0x01000000,
  92798. /* lg(4/3) = */ 0x006a3fe6,
  92799. /* lg(8/7) = */ 0x00315130,
  92800. /* lg(16/15) = */ 0x0017d605,
  92801. /* lg(32/31) = */ 0x000bb9ca,
  92802. /* lg(64/63) = */ 0x0005d0fc,
  92803. /* lg(128/127) = */ 0x0002e58f,
  92804. /* lg(256/255) = */ 0x0001720e,
  92805. /* lg(512/511) = */ 0x0000b8d8,
  92806. /* lg(1024/1023) = */ 0x00005c61,
  92807. /* lg(2048/2047) = */ 0x00002e2d,
  92808. /* lg(4096/4095) = */ 0x00001716,
  92809. /* lg(8192/8191) = */ 0x00000b8b,
  92810. /* lg(16384/16383) = */ 0x000005c5,
  92811. /* lg(32768/32767) = */ 0x000002e3
  92812. },
  92813. {
  92814. /*
  92815. * 28 fraction bits
  92816. */
  92817. /* undefined */ 0x00000000,
  92818. /* lg(2/1) = */ 0x10000000,
  92819. /* lg(4/3) = */ 0x06a3fe5c,
  92820. /* lg(8/7) = */ 0x03151301,
  92821. /* lg(16/15) = */ 0x017d6049,
  92822. /* lg(32/31) = */ 0x00bb9ca6,
  92823. /* lg(64/63) = */ 0x005d0fba,
  92824. /* lg(128/127) = */ 0x002e58f7,
  92825. /* lg(256/255) = */ 0x001720da,
  92826. /* lg(512/511) = */ 0x000b8d87,
  92827. /* lg(1024/1023) = */ 0x0005c60b,
  92828. /* lg(2048/2047) = */ 0x0002e2d7,
  92829. /* lg(4096/4095) = */ 0x00017160,
  92830. /* lg(8192/8191) = */ 0x0000b8ad,
  92831. /* lg(16384/16383) = */ 0x00005c56,
  92832. /* lg(32768/32767) = */ 0x00002e2b
  92833. }
  92834. };
  92835. #if 0
  92836. static const FLAC__uint64 log2_lookup_wide[] = {
  92837. {
  92838. /*
  92839. * 32 fraction bits
  92840. */
  92841. /* undefined */ 0x00000000,
  92842. /* lg(2/1) = */ FLAC__U64L(0x100000000),
  92843. /* lg(4/3) = */ FLAC__U64L(0x6a3fe5c6),
  92844. /* lg(8/7) = */ FLAC__U64L(0x31513015),
  92845. /* lg(16/15) = */ FLAC__U64L(0x17d60497),
  92846. /* lg(32/31) = */ FLAC__U64L(0x0bb9ca65),
  92847. /* lg(64/63) = */ FLAC__U64L(0x05d0fba2),
  92848. /* lg(128/127) = */ FLAC__U64L(0x02e58f74),
  92849. /* lg(256/255) = */ FLAC__U64L(0x01720d9c),
  92850. /* lg(512/511) = */ FLAC__U64L(0x00b8d875),
  92851. /* lg(1024/1023) = */ FLAC__U64L(0x005c60aa),
  92852. /* lg(2048/2047) = */ FLAC__U64L(0x002e2d72),
  92853. /* lg(4096/4095) = */ FLAC__U64L(0x00171600),
  92854. /* lg(8192/8191) = */ FLAC__U64L(0x000b8ad2),
  92855. /* lg(16384/16383) = */ FLAC__U64L(0x0005c55d),
  92856. /* lg(32768/32767) = */ FLAC__U64L(0x0002e2ac)
  92857. },
  92858. {
  92859. /*
  92860. * 48 fraction bits
  92861. */
  92862. /* undefined */ 0x00000000,
  92863. /* lg(2/1) = */ FLAC__U64L(0x1000000000000),
  92864. /* lg(4/3) = */ FLAC__U64L(0x6a3fe5c60429),
  92865. /* lg(8/7) = */ FLAC__U64L(0x315130157f7a),
  92866. /* lg(16/15) = */ FLAC__U64L(0x17d60496cfbb),
  92867. /* lg(32/31) = */ FLAC__U64L(0xbb9ca64ecac),
  92868. /* lg(64/63) = */ FLAC__U64L(0x5d0fba187cd),
  92869. /* lg(128/127) = */ FLAC__U64L(0x2e58f7441ee),
  92870. /* lg(256/255) = */ FLAC__U64L(0x1720d9c06a8),
  92871. /* lg(512/511) = */ FLAC__U64L(0xb8d8752173),
  92872. /* lg(1024/1023) = */ FLAC__U64L(0x5c60aa252e),
  92873. /* lg(2048/2047) = */ FLAC__U64L(0x2e2d71b0d8),
  92874. /* lg(4096/4095) = */ FLAC__U64L(0x1716001719),
  92875. /* lg(8192/8191) = */ FLAC__U64L(0xb8ad1de1b),
  92876. /* lg(16384/16383) = */ FLAC__U64L(0x5c55d640d),
  92877. /* lg(32768/32767) = */ FLAC__U64L(0x2e2abcf52)
  92878. }
  92879. };
  92880. #endif
  92881. FLAC__uint32 FLAC__fixedpoint_log2(FLAC__uint32 x, unsigned fracbits, unsigned precision)
  92882. {
  92883. const FLAC__uint32 ONE = (1u << fracbits);
  92884. const FLAC__uint32 *table = log2_lookup[fracbits >> 2];
  92885. FLAC__ASSERT(fracbits < 32);
  92886. FLAC__ASSERT((fracbits & 0x3) == 0);
  92887. if(x < ONE)
  92888. return 0;
  92889. if(precision > LOG2_LOOKUP_PRECISION)
  92890. precision = LOG2_LOOKUP_PRECISION;
  92891. /* Knuth's algorithm for computing logarithms, optimized for base-2 with lookup tables */
  92892. {
  92893. FLAC__uint32 y = 0;
  92894. FLAC__uint32 z = x >> 1, k = 1;
  92895. while (x > ONE && k < precision) {
  92896. if (x - z >= ONE) {
  92897. x -= z;
  92898. z = x >> k;
  92899. y += table[k];
  92900. }
  92901. else {
  92902. z >>= 1;
  92903. k++;
  92904. }
  92905. }
  92906. return y;
  92907. }
  92908. }
  92909. #endif /* defined FLAC__INTEGER_ONLY_LIBRARY */
  92910. #endif
  92911. /*** End of inlined file: float.c ***/
  92912. /*** Start of inlined file: format.c ***/
  92913. /*** Start of inlined file: juce_FlacHeader.h ***/
  92914. // This file is included at the start of each FLAC .c file, just to do a few housekeeping
  92915. // tasks..
  92916. #define VERSION "1.2.1"
  92917. #define FLAC__NO_DLL 1
  92918. #if JUCE_MSVC
  92919. #pragma warning (disable: 4267 4127 4244 4996 4100 4701 4702 4013 4133 4206 4312)
  92920. #endif
  92921. #if JUCE_MAC
  92922. #define FLAC__SYS_DARWIN 1
  92923. #endif
  92924. /*** End of inlined file: juce_FlacHeader.h ***/
  92925. #if JUCE_USE_FLAC
  92926. #if HAVE_CONFIG_H
  92927. # include <config.h>
  92928. #endif
  92929. #include <stdio.h>
  92930. #include <stdlib.h> /* for qsort() */
  92931. #include <string.h> /* for memset() */
  92932. #ifndef FLaC__INLINE
  92933. #define FLaC__INLINE
  92934. #endif
  92935. #ifdef min
  92936. #undef min
  92937. #endif
  92938. #define min(a,b) ((a)<(b)?(a):(b))
  92939. /* adjust for compilers that can't understand using LLU suffix for uint64_t literals */
  92940. #ifdef _MSC_VER
  92941. #define FLAC__U64L(x) x
  92942. #else
  92943. #define FLAC__U64L(x) x##LLU
  92944. #endif
  92945. /* VERSION should come from configure */
  92946. FLAC_API const char *FLAC__VERSION_STRING = VERSION
  92947. ;
  92948. #if defined _MSC_VER || defined __BORLANDC__ || defined __MINW32__
  92949. /* yet one more hack because of MSVC6: */
  92950. FLAC_API const char *FLAC__VENDOR_STRING = "reference libFLAC 1.2.1 20070917";
  92951. #else
  92952. FLAC_API const char *FLAC__VENDOR_STRING = "reference libFLAC " VERSION " 20070917";
  92953. #endif
  92954. FLAC_API const FLAC__byte FLAC__STREAM_SYNC_STRING[4] = { 'f','L','a','C' };
  92955. FLAC_API const unsigned FLAC__STREAM_SYNC = 0x664C6143;
  92956. FLAC_API const unsigned FLAC__STREAM_SYNC_LEN = 32; /* bits */
  92957. FLAC_API const unsigned FLAC__STREAM_METADATA_STREAMINFO_MIN_BLOCK_SIZE_LEN = 16; /* bits */
  92958. FLAC_API const unsigned FLAC__STREAM_METADATA_STREAMINFO_MAX_BLOCK_SIZE_LEN = 16; /* bits */
  92959. FLAC_API const unsigned FLAC__STREAM_METADATA_STREAMINFO_MIN_FRAME_SIZE_LEN = 24; /* bits */
  92960. FLAC_API const unsigned FLAC__STREAM_METADATA_STREAMINFO_MAX_FRAME_SIZE_LEN = 24; /* bits */
  92961. FLAC_API const unsigned FLAC__STREAM_METADATA_STREAMINFO_SAMPLE_RATE_LEN = 20; /* bits */
  92962. FLAC_API const unsigned FLAC__STREAM_METADATA_STREAMINFO_CHANNELS_LEN = 3; /* bits */
  92963. FLAC_API const unsigned FLAC__STREAM_METADATA_STREAMINFO_BITS_PER_SAMPLE_LEN = 5; /* bits */
  92964. FLAC_API const unsigned FLAC__STREAM_METADATA_STREAMINFO_TOTAL_SAMPLES_LEN = 36; /* bits */
  92965. FLAC_API const unsigned FLAC__STREAM_METADATA_STREAMINFO_MD5SUM_LEN = 128; /* bits */
  92966. FLAC_API const unsigned FLAC__STREAM_METADATA_APPLICATION_ID_LEN = 32; /* bits */
  92967. FLAC_API const unsigned FLAC__STREAM_METADATA_SEEKPOINT_SAMPLE_NUMBER_LEN = 64; /* bits */
  92968. FLAC_API const unsigned FLAC__STREAM_METADATA_SEEKPOINT_STREAM_OFFSET_LEN = 64; /* bits */
  92969. FLAC_API const unsigned FLAC__STREAM_METADATA_SEEKPOINT_FRAME_SAMPLES_LEN = 16; /* bits */
  92970. FLAC_API const FLAC__uint64 FLAC__STREAM_METADATA_SEEKPOINT_PLACEHOLDER = FLAC__U64L(0xffffffffffffffff);
  92971. FLAC_API const unsigned FLAC__STREAM_METADATA_VORBIS_COMMENT_ENTRY_LENGTH_LEN = 32; /* bits */
  92972. FLAC_API const unsigned FLAC__STREAM_METADATA_VORBIS_COMMENT_NUM_COMMENTS_LEN = 32; /* bits */
  92973. FLAC_API const unsigned FLAC__STREAM_METADATA_CUESHEET_INDEX_OFFSET_LEN = 64; /* bits */
  92974. FLAC_API const unsigned FLAC__STREAM_METADATA_CUESHEET_INDEX_NUMBER_LEN = 8; /* bits */
  92975. FLAC_API const unsigned FLAC__STREAM_METADATA_CUESHEET_INDEX_RESERVED_LEN = 3*8; /* bits */
  92976. FLAC_API const unsigned FLAC__STREAM_METADATA_CUESHEET_TRACK_OFFSET_LEN = 64; /* bits */
  92977. FLAC_API const unsigned FLAC__STREAM_METADATA_CUESHEET_TRACK_NUMBER_LEN = 8; /* bits */
  92978. FLAC_API const unsigned FLAC__STREAM_METADATA_CUESHEET_TRACK_ISRC_LEN = 12*8; /* bits */
  92979. FLAC_API const unsigned FLAC__STREAM_METADATA_CUESHEET_TRACK_TYPE_LEN = 1; /* bit */
  92980. FLAC_API const unsigned FLAC__STREAM_METADATA_CUESHEET_TRACK_PRE_EMPHASIS_LEN = 1; /* bit */
  92981. FLAC_API const unsigned FLAC__STREAM_METADATA_CUESHEET_TRACK_RESERVED_LEN = 6+13*8; /* bits */
  92982. FLAC_API const unsigned FLAC__STREAM_METADATA_CUESHEET_TRACK_NUM_INDICES_LEN = 8; /* bits */
  92983. FLAC_API const unsigned FLAC__STREAM_METADATA_CUESHEET_MEDIA_CATALOG_NUMBER_LEN = 128*8; /* bits */
  92984. FLAC_API const unsigned FLAC__STREAM_METADATA_CUESHEET_LEAD_IN_LEN = 64; /* bits */
  92985. FLAC_API const unsigned FLAC__STREAM_METADATA_CUESHEET_IS_CD_LEN = 1; /* bit */
  92986. FLAC_API const unsigned FLAC__STREAM_METADATA_CUESHEET_RESERVED_LEN = 7+258*8; /* bits */
  92987. FLAC_API const unsigned FLAC__STREAM_METADATA_CUESHEET_NUM_TRACKS_LEN = 8; /* bits */
  92988. FLAC_API const unsigned FLAC__STREAM_METADATA_PICTURE_TYPE_LEN = 32; /* bits */
  92989. FLAC_API const unsigned FLAC__STREAM_METADATA_PICTURE_MIME_TYPE_LENGTH_LEN = 32; /* bits */
  92990. FLAC_API const unsigned FLAC__STREAM_METADATA_PICTURE_DESCRIPTION_LENGTH_LEN = 32; /* bits */
  92991. FLAC_API const unsigned FLAC__STREAM_METADATA_PICTURE_WIDTH_LEN = 32; /* bits */
  92992. FLAC_API const unsigned FLAC__STREAM_METADATA_PICTURE_HEIGHT_LEN = 32; /* bits */
  92993. FLAC_API const unsigned FLAC__STREAM_METADATA_PICTURE_DEPTH_LEN = 32; /* bits */
  92994. FLAC_API const unsigned FLAC__STREAM_METADATA_PICTURE_COLORS_LEN = 32; /* bits */
  92995. FLAC_API const unsigned FLAC__STREAM_METADATA_PICTURE_DATA_LENGTH_LEN = 32; /* bits */
  92996. FLAC_API const unsigned FLAC__STREAM_METADATA_IS_LAST_LEN = 1; /* bits */
  92997. FLAC_API const unsigned FLAC__STREAM_METADATA_TYPE_LEN = 7; /* bits */
  92998. FLAC_API const unsigned FLAC__STREAM_METADATA_LENGTH_LEN = 24; /* bits */
  92999. FLAC_API const unsigned FLAC__FRAME_HEADER_SYNC = 0x3ffe;
  93000. FLAC_API const unsigned FLAC__FRAME_HEADER_SYNC_LEN = 14; /* bits */
  93001. FLAC_API const unsigned FLAC__FRAME_HEADER_RESERVED_LEN = 1; /* bits */
  93002. FLAC_API const unsigned FLAC__FRAME_HEADER_BLOCKING_STRATEGY_LEN = 1; /* bits */
  93003. FLAC_API const unsigned FLAC__FRAME_HEADER_BLOCK_SIZE_LEN = 4; /* bits */
  93004. FLAC_API const unsigned FLAC__FRAME_HEADER_SAMPLE_RATE_LEN = 4; /* bits */
  93005. FLAC_API const unsigned FLAC__FRAME_HEADER_CHANNEL_ASSIGNMENT_LEN = 4; /* bits */
  93006. FLAC_API const unsigned FLAC__FRAME_HEADER_BITS_PER_SAMPLE_LEN = 3; /* bits */
  93007. FLAC_API const unsigned FLAC__FRAME_HEADER_ZERO_PAD_LEN = 1; /* bits */
  93008. FLAC_API const unsigned FLAC__FRAME_HEADER_CRC_LEN = 8; /* bits */
  93009. FLAC_API const unsigned FLAC__FRAME_FOOTER_CRC_LEN = 16; /* bits */
  93010. FLAC_API const unsigned FLAC__ENTROPY_CODING_METHOD_TYPE_LEN = 2; /* bits */
  93011. FLAC_API const unsigned FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE_ORDER_LEN = 4; /* bits */
  93012. FLAC_API const unsigned FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE_PARAMETER_LEN = 4; /* bits */
  93013. FLAC_API const unsigned FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE2_PARAMETER_LEN = 5; /* bits */
  93014. FLAC_API const unsigned FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE_RAW_LEN = 5; /* bits */
  93015. FLAC_API const unsigned FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE_ESCAPE_PARAMETER = 15; /* == (1<<FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE_PARAMETER_LEN)-1 */
  93016. FLAC_API const unsigned FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE2_ESCAPE_PARAMETER = 31; /* == (1<<FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE2_PARAMETER_LEN)-1 */
  93017. FLAC_API const char * const FLAC__EntropyCodingMethodTypeString[] = {
  93018. "PARTITIONED_RICE",
  93019. "PARTITIONED_RICE2"
  93020. };
  93021. FLAC_API const unsigned FLAC__SUBFRAME_LPC_QLP_COEFF_PRECISION_LEN = 4; /* bits */
  93022. FLAC_API const unsigned FLAC__SUBFRAME_LPC_QLP_SHIFT_LEN = 5; /* bits */
  93023. FLAC_API const unsigned FLAC__SUBFRAME_ZERO_PAD_LEN = 1; /* bits */
  93024. FLAC_API const unsigned FLAC__SUBFRAME_TYPE_LEN = 6; /* bits */
  93025. FLAC_API const unsigned FLAC__SUBFRAME_WASTED_BITS_FLAG_LEN = 1; /* bits */
  93026. FLAC_API const unsigned FLAC__SUBFRAME_TYPE_CONSTANT_BYTE_ALIGNED_MASK = 0x00;
  93027. FLAC_API const unsigned FLAC__SUBFRAME_TYPE_VERBATIM_BYTE_ALIGNED_MASK = 0x02;
  93028. FLAC_API const unsigned FLAC__SUBFRAME_TYPE_FIXED_BYTE_ALIGNED_MASK = 0x10;
  93029. FLAC_API const unsigned FLAC__SUBFRAME_TYPE_LPC_BYTE_ALIGNED_MASK = 0x40;
  93030. FLAC_API const char * const FLAC__SubframeTypeString[] = {
  93031. "CONSTANT",
  93032. "VERBATIM",
  93033. "FIXED",
  93034. "LPC"
  93035. };
  93036. FLAC_API const char * const FLAC__ChannelAssignmentString[] = {
  93037. "INDEPENDENT",
  93038. "LEFT_SIDE",
  93039. "RIGHT_SIDE",
  93040. "MID_SIDE"
  93041. };
  93042. FLAC_API const char * const FLAC__FrameNumberTypeString[] = {
  93043. "FRAME_NUMBER_TYPE_FRAME_NUMBER",
  93044. "FRAME_NUMBER_TYPE_SAMPLE_NUMBER"
  93045. };
  93046. FLAC_API const char * const FLAC__MetadataTypeString[] = {
  93047. "STREAMINFO",
  93048. "PADDING",
  93049. "APPLICATION",
  93050. "SEEKTABLE",
  93051. "VORBIS_COMMENT",
  93052. "CUESHEET",
  93053. "PICTURE"
  93054. };
  93055. FLAC_API const char * const FLAC__StreamMetadata_Picture_TypeString[] = {
  93056. "Other",
  93057. "32x32 pixels 'file icon' (PNG only)",
  93058. "Other file icon",
  93059. "Cover (front)",
  93060. "Cover (back)",
  93061. "Leaflet page",
  93062. "Media (e.g. label side of CD)",
  93063. "Lead artist/lead performer/soloist",
  93064. "Artist/performer",
  93065. "Conductor",
  93066. "Band/Orchestra",
  93067. "Composer",
  93068. "Lyricist/text writer",
  93069. "Recording Location",
  93070. "During recording",
  93071. "During performance",
  93072. "Movie/video screen capture",
  93073. "A bright coloured fish",
  93074. "Illustration",
  93075. "Band/artist logotype",
  93076. "Publisher/Studio logotype"
  93077. };
  93078. FLAC_API FLAC__bool FLAC__format_sample_rate_is_valid(unsigned sample_rate)
  93079. {
  93080. if(sample_rate == 0 || sample_rate > FLAC__MAX_SAMPLE_RATE) {
  93081. return false;
  93082. }
  93083. else
  93084. return true;
  93085. }
  93086. FLAC_API FLAC__bool FLAC__format_sample_rate_is_subset(unsigned sample_rate)
  93087. {
  93088. if(
  93089. !FLAC__format_sample_rate_is_valid(sample_rate) ||
  93090. (
  93091. sample_rate >= (1u << 16) &&
  93092. !(sample_rate % 1000 == 0 || sample_rate % 10 == 0)
  93093. )
  93094. ) {
  93095. return false;
  93096. }
  93097. else
  93098. return true;
  93099. }
  93100. /* @@@@ add to unit tests; it is already indirectly tested by the metadata_object tests */
  93101. FLAC_API FLAC__bool FLAC__format_seektable_is_legal(const FLAC__StreamMetadata_SeekTable *seek_table)
  93102. {
  93103. unsigned i;
  93104. FLAC__uint64 prev_sample_number = 0;
  93105. FLAC__bool got_prev = false;
  93106. FLAC__ASSERT(0 != seek_table);
  93107. for(i = 0; i < seek_table->num_points; i++) {
  93108. if(got_prev) {
  93109. if(
  93110. seek_table->points[i].sample_number != FLAC__STREAM_METADATA_SEEKPOINT_PLACEHOLDER &&
  93111. seek_table->points[i].sample_number <= prev_sample_number
  93112. )
  93113. return false;
  93114. }
  93115. prev_sample_number = seek_table->points[i].sample_number;
  93116. got_prev = true;
  93117. }
  93118. return true;
  93119. }
  93120. /* used as the sort predicate for qsort() */
  93121. static int seekpoint_compare_(const FLAC__StreamMetadata_SeekPoint *l, const FLAC__StreamMetadata_SeekPoint *r)
  93122. {
  93123. /* we don't just 'return l->sample_number - r->sample_number' since the result (FLAC__int64) might overflow an 'int' */
  93124. if(l->sample_number == r->sample_number)
  93125. return 0;
  93126. else if(l->sample_number < r->sample_number)
  93127. return -1;
  93128. else
  93129. return 1;
  93130. }
  93131. /* @@@@ add to unit tests; it is already indirectly tested by the metadata_object tests */
  93132. FLAC_API unsigned FLAC__format_seektable_sort(FLAC__StreamMetadata_SeekTable *seek_table)
  93133. {
  93134. unsigned i, j;
  93135. FLAC__bool first;
  93136. FLAC__ASSERT(0 != seek_table);
  93137. /* sort the seekpoints */
  93138. qsort(seek_table->points, seek_table->num_points, sizeof(FLAC__StreamMetadata_SeekPoint), (int (*)(const void *, const void *))seekpoint_compare_);
  93139. /* uniquify the seekpoints */
  93140. first = true;
  93141. for(i = j = 0; i < seek_table->num_points; i++) {
  93142. if(seek_table->points[i].sample_number != FLAC__STREAM_METADATA_SEEKPOINT_PLACEHOLDER) {
  93143. if(!first) {
  93144. if(seek_table->points[i].sample_number == seek_table->points[j-1].sample_number)
  93145. continue;
  93146. }
  93147. }
  93148. first = false;
  93149. seek_table->points[j++] = seek_table->points[i];
  93150. }
  93151. for(i = j; i < seek_table->num_points; i++) {
  93152. seek_table->points[i].sample_number = FLAC__STREAM_METADATA_SEEKPOINT_PLACEHOLDER;
  93153. seek_table->points[i].stream_offset = 0;
  93154. seek_table->points[i].frame_samples = 0;
  93155. }
  93156. return j;
  93157. }
  93158. /*
  93159. * also disallows non-shortest-form encodings, c.f.
  93160. * http://www.unicode.org/versions/corrigendum1.html
  93161. * and a more clear explanation at the end of this section:
  93162. * http://www.cl.cam.ac.uk/~mgk25/unicode.html#utf-8
  93163. */
  93164. static FLaC__INLINE unsigned utf8len_(const FLAC__byte *utf8)
  93165. {
  93166. FLAC__ASSERT(0 != utf8);
  93167. if ((utf8[0] & 0x80) == 0) {
  93168. return 1;
  93169. }
  93170. else if ((utf8[0] & 0xE0) == 0xC0 && (utf8[1] & 0xC0) == 0x80) {
  93171. if ((utf8[0] & 0xFE) == 0xC0) /* overlong sequence check */
  93172. return 0;
  93173. return 2;
  93174. }
  93175. else if ((utf8[0] & 0xF0) == 0xE0 && (utf8[1] & 0xC0) == 0x80 && (utf8[2] & 0xC0) == 0x80) {
  93176. if (utf8[0] == 0xE0 && (utf8[1] & 0xE0) == 0x80) /* overlong sequence check */
  93177. return 0;
  93178. /* illegal surrogates check (U+D800...U+DFFF and U+FFFE...U+FFFF) */
  93179. if (utf8[0] == 0xED && (utf8[1] & 0xE0) == 0xA0) /* D800-DFFF */
  93180. return 0;
  93181. if (utf8[0] == 0xEF && utf8[1] == 0xBF && (utf8[2] & 0xFE) == 0xBE) /* FFFE-FFFF */
  93182. return 0;
  93183. return 3;
  93184. }
  93185. else if ((utf8[0] & 0xF8) == 0xF0 && (utf8[1] & 0xC0) == 0x80 && (utf8[2] & 0xC0) == 0x80 && (utf8[3] & 0xC0) == 0x80) {
  93186. if (utf8[0] == 0xF0 && (utf8[1] & 0xF0) == 0x80) /* overlong sequence check */
  93187. return 0;
  93188. return 4;
  93189. }
  93190. else if ((utf8[0] & 0xFC) == 0xF8 && (utf8[1] & 0xC0) == 0x80 && (utf8[2] & 0xC0) == 0x80 && (utf8[3] & 0xC0) == 0x80 && (utf8[4] & 0xC0) == 0x80) {
  93191. if (utf8[0] == 0xF8 && (utf8[1] & 0xF8) == 0x80) /* overlong sequence check */
  93192. return 0;
  93193. return 5;
  93194. }
  93195. 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) {
  93196. if (utf8[0] == 0xFC && (utf8[1] & 0xFC) == 0x80) /* overlong sequence check */
  93197. return 0;
  93198. return 6;
  93199. }
  93200. else {
  93201. return 0;
  93202. }
  93203. }
  93204. FLAC_API FLAC__bool FLAC__format_vorbiscomment_entry_name_is_legal(const char *name)
  93205. {
  93206. char c;
  93207. for(c = *name; c; c = *(++name))
  93208. if(c < 0x20 || c == 0x3d || c > 0x7d)
  93209. return false;
  93210. return true;
  93211. }
  93212. FLAC_API FLAC__bool FLAC__format_vorbiscomment_entry_value_is_legal(const FLAC__byte *value, unsigned length)
  93213. {
  93214. if(length == (unsigned)(-1)) {
  93215. while(*value) {
  93216. unsigned n = utf8len_(value);
  93217. if(n == 0)
  93218. return false;
  93219. value += n;
  93220. }
  93221. }
  93222. else {
  93223. const FLAC__byte *end = value + length;
  93224. while(value < end) {
  93225. unsigned n = utf8len_(value);
  93226. if(n == 0)
  93227. return false;
  93228. value += n;
  93229. }
  93230. if(value != end)
  93231. return false;
  93232. }
  93233. return true;
  93234. }
  93235. FLAC_API FLAC__bool FLAC__format_vorbiscomment_entry_is_legal(const FLAC__byte *entry, unsigned length)
  93236. {
  93237. const FLAC__byte *s, *end;
  93238. for(s = entry, end = s + length; s < end && *s != '='; s++) {
  93239. if(*s < 0x20 || *s > 0x7D)
  93240. return false;
  93241. }
  93242. if(s == end)
  93243. return false;
  93244. s++; /* skip '=' */
  93245. while(s < end) {
  93246. unsigned n = utf8len_(s);
  93247. if(n == 0)
  93248. return false;
  93249. s += n;
  93250. }
  93251. if(s != end)
  93252. return false;
  93253. return true;
  93254. }
  93255. /* @@@@ add to unit tests; it is already indirectly tested by the metadata_object tests */
  93256. FLAC_API FLAC__bool FLAC__format_cuesheet_is_legal(const FLAC__StreamMetadata_CueSheet *cue_sheet, FLAC__bool check_cd_da_subset, const char **violation)
  93257. {
  93258. unsigned i, j;
  93259. if(check_cd_da_subset) {
  93260. if(cue_sheet->lead_in < 2 * 44100) {
  93261. if(violation) *violation = "CD-DA cue sheet must have a lead-in length of at least 2 seconds";
  93262. return false;
  93263. }
  93264. if(cue_sheet->lead_in % 588 != 0) {
  93265. if(violation) *violation = "CD-DA cue sheet lead-in length must be evenly divisible by 588 samples";
  93266. return false;
  93267. }
  93268. }
  93269. if(cue_sheet->num_tracks == 0) {
  93270. if(violation) *violation = "cue sheet must have at least one track (the lead-out)";
  93271. return false;
  93272. }
  93273. if(check_cd_da_subset && cue_sheet->tracks[cue_sheet->num_tracks-1].number != 170) {
  93274. if(violation) *violation = "CD-DA cue sheet must have a lead-out track number 170 (0xAA)";
  93275. return false;
  93276. }
  93277. for(i = 0; i < cue_sheet->num_tracks; i++) {
  93278. if(cue_sheet->tracks[i].number == 0) {
  93279. if(violation) *violation = "cue sheet may not have a track number 0";
  93280. return false;
  93281. }
  93282. if(check_cd_da_subset) {
  93283. if(!((cue_sheet->tracks[i].number >= 1 && cue_sheet->tracks[i].number <= 99) || cue_sheet->tracks[i].number == 170)) {
  93284. if(violation) *violation = "CD-DA cue sheet track number must be 1-99 or 170";
  93285. return false;
  93286. }
  93287. }
  93288. if(check_cd_da_subset && cue_sheet->tracks[i].offset % 588 != 0) {
  93289. if(violation) {
  93290. if(i == cue_sheet->num_tracks-1) /* the lead-out track... */
  93291. *violation = "CD-DA cue sheet lead-out offset must be evenly divisible by 588 samples";
  93292. else
  93293. *violation = "CD-DA cue sheet track offset must be evenly divisible by 588 samples";
  93294. }
  93295. return false;
  93296. }
  93297. if(i < cue_sheet->num_tracks - 1) {
  93298. if(cue_sheet->tracks[i].num_indices == 0) {
  93299. if(violation) *violation = "cue sheet track must have at least one index point";
  93300. return false;
  93301. }
  93302. if(cue_sheet->tracks[i].indices[0].number > 1) {
  93303. if(violation) *violation = "cue sheet track's first index number must be 0 or 1";
  93304. return false;
  93305. }
  93306. }
  93307. for(j = 0; j < cue_sheet->tracks[i].num_indices; j++) {
  93308. if(check_cd_da_subset && cue_sheet->tracks[i].indices[j].offset % 588 != 0) {
  93309. if(violation) *violation = "CD-DA cue sheet track index offset must be evenly divisible by 588 samples";
  93310. return false;
  93311. }
  93312. if(j > 0) {
  93313. if(cue_sheet->tracks[i].indices[j].number != cue_sheet->tracks[i].indices[j-1].number + 1) {
  93314. if(violation) *violation = "cue sheet track index numbers must increase by 1";
  93315. return false;
  93316. }
  93317. }
  93318. }
  93319. }
  93320. return true;
  93321. }
  93322. /* @@@@ add to unit tests; it is already indirectly tested by the metadata_object tests */
  93323. FLAC_API FLAC__bool FLAC__format_picture_is_legal(const FLAC__StreamMetadata_Picture *picture, const char **violation)
  93324. {
  93325. char *p;
  93326. FLAC__byte *b;
  93327. for(p = picture->mime_type; *p; p++) {
  93328. if(*p < 0x20 || *p > 0x7e) {
  93329. if(violation) *violation = "MIME type string must contain only printable ASCII characters (0x20-0x7e)";
  93330. return false;
  93331. }
  93332. }
  93333. for(b = picture->description; *b; ) {
  93334. unsigned n = utf8len_(b);
  93335. if(n == 0) {
  93336. if(violation) *violation = "description string must be valid UTF-8";
  93337. return false;
  93338. }
  93339. b += n;
  93340. }
  93341. return true;
  93342. }
  93343. /*
  93344. * These routines are private to libFLAC
  93345. */
  93346. unsigned FLAC__format_get_max_rice_partition_order(unsigned blocksize, unsigned predictor_order)
  93347. {
  93348. return
  93349. FLAC__format_get_max_rice_partition_order_from_blocksize_limited_max_and_predictor_order(
  93350. FLAC__format_get_max_rice_partition_order_from_blocksize(blocksize),
  93351. blocksize,
  93352. predictor_order
  93353. );
  93354. }
  93355. unsigned FLAC__format_get_max_rice_partition_order_from_blocksize(unsigned blocksize)
  93356. {
  93357. unsigned max_rice_partition_order = 0;
  93358. while(!(blocksize & 1)) {
  93359. max_rice_partition_order++;
  93360. blocksize >>= 1;
  93361. }
  93362. return min(FLAC__MAX_RICE_PARTITION_ORDER, max_rice_partition_order);
  93363. }
  93364. unsigned FLAC__format_get_max_rice_partition_order_from_blocksize_limited_max_and_predictor_order(unsigned limit, unsigned blocksize, unsigned predictor_order)
  93365. {
  93366. unsigned max_rice_partition_order = limit;
  93367. while(max_rice_partition_order > 0 && (blocksize >> max_rice_partition_order) <= predictor_order)
  93368. max_rice_partition_order--;
  93369. FLAC__ASSERT(
  93370. (max_rice_partition_order == 0 && blocksize >= predictor_order) ||
  93371. (max_rice_partition_order > 0 && blocksize >> max_rice_partition_order > predictor_order)
  93372. );
  93373. return max_rice_partition_order;
  93374. }
  93375. void FLAC__format_entropy_coding_method_partitioned_rice_contents_init(FLAC__EntropyCodingMethod_PartitionedRiceContents *object)
  93376. {
  93377. FLAC__ASSERT(0 != object);
  93378. object->parameters = 0;
  93379. object->raw_bits = 0;
  93380. object->capacity_by_order = 0;
  93381. }
  93382. void FLAC__format_entropy_coding_method_partitioned_rice_contents_clear(FLAC__EntropyCodingMethod_PartitionedRiceContents *object)
  93383. {
  93384. FLAC__ASSERT(0 != object);
  93385. if(0 != object->parameters)
  93386. free(object->parameters);
  93387. if(0 != object->raw_bits)
  93388. free(object->raw_bits);
  93389. FLAC__format_entropy_coding_method_partitioned_rice_contents_init(object);
  93390. }
  93391. FLAC__bool FLAC__format_entropy_coding_method_partitioned_rice_contents_ensure_size(FLAC__EntropyCodingMethod_PartitionedRiceContents *object, unsigned max_partition_order)
  93392. {
  93393. FLAC__ASSERT(0 != object);
  93394. FLAC__ASSERT(object->capacity_by_order > 0 || (0 == object->parameters && 0 == object->raw_bits));
  93395. if(object->capacity_by_order < max_partition_order) {
  93396. if(0 == (object->parameters = (unsigned*)realloc(object->parameters, sizeof(unsigned)*(1 << max_partition_order))))
  93397. return false;
  93398. if(0 == (object->raw_bits = (unsigned*)realloc(object->raw_bits, sizeof(unsigned)*(1 << max_partition_order))))
  93399. return false;
  93400. memset(object->raw_bits, 0, sizeof(unsigned)*(1 << max_partition_order));
  93401. object->capacity_by_order = max_partition_order;
  93402. }
  93403. return true;
  93404. }
  93405. #endif
  93406. /*** End of inlined file: format.c ***/
  93407. /*** Start of inlined file: lpc_flac.c ***/
  93408. /*** Start of inlined file: juce_FlacHeader.h ***/
  93409. // This file is included at the start of each FLAC .c file, just to do a few housekeeping
  93410. // tasks..
  93411. #define VERSION "1.2.1"
  93412. #define FLAC__NO_DLL 1
  93413. #if JUCE_MSVC
  93414. #pragma warning (disable: 4267 4127 4244 4996 4100 4701 4702 4013 4133 4206 4312)
  93415. #endif
  93416. #if JUCE_MAC
  93417. #define FLAC__SYS_DARWIN 1
  93418. #endif
  93419. /*** End of inlined file: juce_FlacHeader.h ***/
  93420. #if JUCE_USE_FLAC
  93421. #if HAVE_CONFIG_H
  93422. # include <config.h>
  93423. #endif
  93424. #include <math.h>
  93425. /*** Start of inlined file: lpc.h ***/
  93426. #ifndef FLAC__PRIVATE__LPC_H
  93427. #define FLAC__PRIVATE__LPC_H
  93428. #ifdef HAVE_CONFIG_H
  93429. #include <config.h>
  93430. #endif
  93431. #ifndef FLAC__INTEGER_ONLY_LIBRARY
  93432. /*
  93433. * FLAC__lpc_window_data()
  93434. * --------------------------------------------------------------------
  93435. * Applies the given window to the data.
  93436. * OPT: asm implementation
  93437. *
  93438. * IN in[0,data_len-1]
  93439. * IN window[0,data_len-1]
  93440. * OUT out[0,lag-1]
  93441. * IN data_len
  93442. */
  93443. void FLAC__lpc_window_data(const FLAC__int32 in[], const FLAC__real window[], FLAC__real out[], unsigned data_len);
  93444. /*
  93445. * FLAC__lpc_compute_autocorrelation()
  93446. * --------------------------------------------------------------------
  93447. * Compute the autocorrelation for lags between 0 and lag-1.
  93448. * Assumes data[] outside of [0,data_len-1] == 0.
  93449. * Asserts that lag > 0.
  93450. *
  93451. * IN data[0,data_len-1]
  93452. * IN data_len
  93453. * IN 0 < lag <= data_len
  93454. * OUT autoc[0,lag-1]
  93455. */
  93456. void FLAC__lpc_compute_autocorrelation(const FLAC__real data[], unsigned data_len, unsigned lag, FLAC__real autoc[]);
  93457. #ifndef FLAC__NO_ASM
  93458. # ifdef FLAC__CPU_IA32
  93459. # ifdef FLAC__HAS_NASM
  93460. void FLAC__lpc_compute_autocorrelation_asm_ia32(const FLAC__real data[], unsigned data_len, unsigned lag, FLAC__real autoc[]);
  93461. void FLAC__lpc_compute_autocorrelation_asm_ia32_sse_lag_4(const FLAC__real data[], unsigned data_len, unsigned lag, FLAC__real autoc[]);
  93462. void FLAC__lpc_compute_autocorrelation_asm_ia32_sse_lag_8(const FLAC__real data[], unsigned data_len, unsigned lag, FLAC__real autoc[]);
  93463. void FLAC__lpc_compute_autocorrelation_asm_ia32_sse_lag_12(const FLAC__real data[], unsigned data_len, unsigned lag, FLAC__real autoc[]);
  93464. void FLAC__lpc_compute_autocorrelation_asm_ia32_3dnow(const FLAC__real data[], unsigned data_len, unsigned lag, FLAC__real autoc[]);
  93465. # endif
  93466. # endif
  93467. #endif
  93468. /*
  93469. * FLAC__lpc_compute_lp_coefficients()
  93470. * --------------------------------------------------------------------
  93471. * Computes LP coefficients for orders 1..max_order.
  93472. * Do not call if autoc[0] == 0.0. This means the signal is zero
  93473. * and there is no point in calculating a predictor.
  93474. *
  93475. * IN autoc[0,max_order] autocorrelation values
  93476. * IN 0 < max_order <= FLAC__MAX_LPC_ORDER max LP order to compute
  93477. * OUT lp_coeff[0,max_order-1][0,max_order-1] LP coefficients for each order
  93478. * *** IMPORTANT:
  93479. * *** lp_coeff[0,max_order-1][max_order,FLAC__MAX_LPC_ORDER-1] are untouched
  93480. * OUT error[0,max_order-1] error for each order (more
  93481. * specifically, the variance of
  93482. * the error signal times # of
  93483. * samples in the signal)
  93484. *
  93485. * Example: if max_order is 9, the LP coefficients for order 9 will be
  93486. * in lp_coeff[8][0,8], the LP coefficients for order 8 will be
  93487. * in lp_coeff[7][0,7], etc.
  93488. */
  93489. void FLAC__lpc_compute_lp_coefficients(const FLAC__real autoc[], unsigned *max_order, FLAC__real lp_coeff[][FLAC__MAX_LPC_ORDER], FLAC__double error[]);
  93490. /*
  93491. * FLAC__lpc_quantize_coefficients()
  93492. * --------------------------------------------------------------------
  93493. * Quantizes the LP coefficients. NOTE: precision + bits_per_sample
  93494. * must be less than 32 (sizeof(FLAC__int32)*8).
  93495. *
  93496. * IN lp_coeff[0,order-1] LP coefficients
  93497. * IN order LP order
  93498. * IN FLAC__MIN_QLP_COEFF_PRECISION < precision
  93499. * desired precision (in bits, including sign
  93500. * bit) of largest coefficient
  93501. * OUT qlp_coeff[0,order-1] quantized coefficients
  93502. * OUT shift # of bits to shift right to get approximated
  93503. * LP coefficients. NOTE: could be negative.
  93504. * RETURN 0 => quantization OK
  93505. * 1 => coefficients require too much shifting for *shift to
  93506. * fit in the LPC subframe header. 'shift' is unset.
  93507. * 2 => coefficients are all zero, which is bad. 'shift' is
  93508. * unset.
  93509. */
  93510. int FLAC__lpc_quantize_coefficients(const FLAC__real lp_coeff[], unsigned order, unsigned precision, FLAC__int32 qlp_coeff[], int *shift);
  93511. /*
  93512. * FLAC__lpc_compute_residual_from_qlp_coefficients()
  93513. * --------------------------------------------------------------------
  93514. * Compute the residual signal obtained from sutracting the predicted
  93515. * signal from the original.
  93516. *
  93517. * IN data[-order,data_len-1] original signal (NOTE THE INDICES!)
  93518. * IN data_len length of original signal
  93519. * IN qlp_coeff[0,order-1] quantized LP coefficients
  93520. * IN order > 0 LP order
  93521. * IN lp_quantization quantization of LP coefficients in bits
  93522. * OUT residual[0,data_len-1] residual signal
  93523. */
  93524. 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[]);
  93525. 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[]);
  93526. #ifndef FLAC__NO_ASM
  93527. # ifdef FLAC__CPU_IA32
  93528. # ifdef FLAC__HAS_NASM
  93529. 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[]);
  93530. 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[]);
  93531. # endif
  93532. # endif
  93533. #endif
  93534. #endif /* !defined FLAC__INTEGER_ONLY_LIBRARY */
  93535. /*
  93536. * FLAC__lpc_restore_signal()
  93537. * --------------------------------------------------------------------
  93538. * Restore the original signal by summing the residual and the
  93539. * predictor.
  93540. *
  93541. * IN residual[0,data_len-1] residual signal
  93542. * IN data_len length of original signal
  93543. * IN qlp_coeff[0,order-1] quantized LP coefficients
  93544. * IN order > 0 LP order
  93545. * IN lp_quantization quantization of LP coefficients in bits
  93546. * *** IMPORTANT: the caller must pass in the historical samples:
  93547. * IN data[-order,-1] previously-reconstructed historical samples
  93548. * OUT data[0,data_len-1] original signal
  93549. */
  93550. 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[]);
  93551. 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[]);
  93552. #ifndef FLAC__NO_ASM
  93553. # ifdef FLAC__CPU_IA32
  93554. # ifdef FLAC__HAS_NASM
  93555. 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[]);
  93556. 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[]);
  93557. # endif /* FLAC__HAS_NASM */
  93558. # elif defined FLAC__CPU_PPC
  93559. 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[]);
  93560. 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[]);
  93561. # endif/* FLAC__CPU_IA32 || FLAC__CPU_PPC */
  93562. #endif /* FLAC__NO_ASM */
  93563. #ifndef FLAC__INTEGER_ONLY_LIBRARY
  93564. /*
  93565. * FLAC__lpc_compute_expected_bits_per_residual_sample()
  93566. * --------------------------------------------------------------------
  93567. * Compute the expected number of bits per residual signal sample
  93568. * based on the LP error (which is related to the residual variance).
  93569. *
  93570. * IN lpc_error >= 0.0 error returned from calculating LP coefficients
  93571. * IN total_samples > 0 # of samples in residual signal
  93572. * RETURN expected bits per sample
  93573. */
  93574. FLAC__double FLAC__lpc_compute_expected_bits_per_residual_sample(FLAC__double lpc_error, unsigned total_samples);
  93575. FLAC__double FLAC__lpc_compute_expected_bits_per_residual_sample_with_error_scale(FLAC__double lpc_error, FLAC__double error_scale);
  93576. /*
  93577. * FLAC__lpc_compute_best_order()
  93578. * --------------------------------------------------------------------
  93579. * Compute the best order from the array of signal errors returned
  93580. * during coefficient computation.
  93581. *
  93582. * IN lpc_error[0,max_order-1] >= 0.0 error returned from calculating LP coefficients
  93583. * IN max_order > 0 max LP order
  93584. * IN total_samples > 0 # of samples in residual signal
  93585. * IN overhead_bits_per_order # of bits overhead for each increased LP order
  93586. * (includes warmup sample size and quantized LP coefficient)
  93587. * RETURN [1,max_order] best order
  93588. */
  93589. unsigned FLAC__lpc_compute_best_order(const FLAC__double lpc_error[], unsigned max_order, unsigned total_samples, unsigned overhead_bits_per_order);
  93590. #endif /* !defined FLAC__INTEGER_ONLY_LIBRARY */
  93591. #endif
  93592. /*** End of inlined file: lpc.h ***/
  93593. #if defined DEBUG || defined FLAC__OVERFLOW_DETECT || defined FLAC__OVERFLOW_DETECT_VERBOSE
  93594. #include <stdio.h>
  93595. #endif
  93596. #ifndef FLAC__INTEGER_ONLY_LIBRARY
  93597. #ifndef M_LN2
  93598. /* math.h in VC++ doesn't seem to have this (how Microsoft is that?) */
  93599. #define M_LN2 0.69314718055994530942
  93600. #endif
  93601. /* OPT: #undef'ing this may improve the speed on some architectures */
  93602. #define FLAC__LPC_UNROLLED_FILTER_LOOPS
  93603. void FLAC__lpc_window_data(const FLAC__int32 in[], const FLAC__real window[], FLAC__real out[], unsigned data_len)
  93604. {
  93605. unsigned i;
  93606. for(i = 0; i < data_len; i++)
  93607. out[i] = in[i] * window[i];
  93608. }
  93609. void FLAC__lpc_compute_autocorrelation(const FLAC__real data[], unsigned data_len, unsigned lag, FLAC__real autoc[])
  93610. {
  93611. /* a readable, but slower, version */
  93612. #if 0
  93613. FLAC__real d;
  93614. unsigned i;
  93615. FLAC__ASSERT(lag > 0);
  93616. FLAC__ASSERT(lag <= data_len);
  93617. /*
  93618. * Technically we should subtract the mean first like so:
  93619. * for(i = 0; i < data_len; i++)
  93620. * data[i] -= mean;
  93621. * but it appears not to make enough of a difference to matter, and
  93622. * most signals are already closely centered around zero
  93623. */
  93624. while(lag--) {
  93625. for(i = lag, d = 0.0; i < data_len; i++)
  93626. d += data[i] * data[i - lag];
  93627. autoc[lag] = d;
  93628. }
  93629. #endif
  93630. /*
  93631. * this version tends to run faster because of better data locality
  93632. * ('data_len' is usually much larger than 'lag')
  93633. */
  93634. FLAC__real d;
  93635. unsigned sample, coeff;
  93636. const unsigned limit = data_len - lag;
  93637. FLAC__ASSERT(lag > 0);
  93638. FLAC__ASSERT(lag <= data_len);
  93639. for(coeff = 0; coeff < lag; coeff++)
  93640. autoc[coeff] = 0.0;
  93641. for(sample = 0; sample <= limit; sample++) {
  93642. d = data[sample];
  93643. for(coeff = 0; coeff < lag; coeff++)
  93644. autoc[coeff] += d * data[sample+coeff];
  93645. }
  93646. for(; sample < data_len; sample++) {
  93647. d = data[sample];
  93648. for(coeff = 0; coeff < data_len - sample; coeff++)
  93649. autoc[coeff] += d * data[sample+coeff];
  93650. }
  93651. }
  93652. void FLAC__lpc_compute_lp_coefficients(const FLAC__real autoc[], unsigned *max_order, FLAC__real lp_coeff[][FLAC__MAX_LPC_ORDER], FLAC__double error[])
  93653. {
  93654. unsigned i, j;
  93655. FLAC__double r, err, ref[FLAC__MAX_LPC_ORDER], lpc[FLAC__MAX_LPC_ORDER];
  93656. FLAC__ASSERT(0 != max_order);
  93657. FLAC__ASSERT(0 < *max_order);
  93658. FLAC__ASSERT(*max_order <= FLAC__MAX_LPC_ORDER);
  93659. FLAC__ASSERT(autoc[0] != 0.0);
  93660. err = autoc[0];
  93661. for(i = 0; i < *max_order; i++) {
  93662. /* Sum up this iteration's reflection coefficient. */
  93663. r = -autoc[i+1];
  93664. for(j = 0; j < i; j++)
  93665. r -= lpc[j] * autoc[i-j];
  93666. ref[i] = (r/=err);
  93667. /* Update LPC coefficients and total error. */
  93668. lpc[i]=r;
  93669. for(j = 0; j < (i>>1); j++) {
  93670. FLAC__double tmp = lpc[j];
  93671. lpc[j] += r * lpc[i-1-j];
  93672. lpc[i-1-j] += r * tmp;
  93673. }
  93674. if(i & 1)
  93675. lpc[j] += lpc[j] * r;
  93676. err *= (1.0 - r * r);
  93677. /* save this order */
  93678. for(j = 0; j <= i; j++)
  93679. lp_coeff[i][j] = (FLAC__real)(-lpc[j]); /* negate FIR filter coeff to get predictor coeff */
  93680. error[i] = err;
  93681. /* see SF bug #1601812 http://sourceforge.net/tracker/index.php?func=detail&aid=1601812&group_id=13478&atid=113478 */
  93682. if(err == 0.0) {
  93683. *max_order = i+1;
  93684. return;
  93685. }
  93686. }
  93687. }
  93688. int FLAC__lpc_quantize_coefficients(const FLAC__real lp_coeff[], unsigned order, unsigned precision, FLAC__int32 qlp_coeff[], int *shift)
  93689. {
  93690. unsigned i;
  93691. FLAC__double cmax;
  93692. FLAC__int32 qmax, qmin;
  93693. FLAC__ASSERT(precision > 0);
  93694. FLAC__ASSERT(precision >= FLAC__MIN_QLP_COEFF_PRECISION);
  93695. /* drop one bit for the sign; from here on out we consider only |lp_coeff[i]| */
  93696. precision--;
  93697. qmax = 1 << precision;
  93698. qmin = -qmax;
  93699. qmax--;
  93700. /* calc cmax = max( |lp_coeff[i]| ) */
  93701. cmax = 0.0;
  93702. for(i = 0; i < order; i++) {
  93703. const FLAC__double d = fabs(lp_coeff[i]);
  93704. if(d > cmax)
  93705. cmax = d;
  93706. }
  93707. if(cmax <= 0.0) {
  93708. /* => coefficients are all 0, which means our constant-detect didn't work */
  93709. return 2;
  93710. }
  93711. else {
  93712. const int max_shiftlimit = (1 << (FLAC__SUBFRAME_LPC_QLP_SHIFT_LEN-1)) - 1;
  93713. const int min_shiftlimit = -max_shiftlimit - 1;
  93714. int log2cmax;
  93715. (void)frexp(cmax, &log2cmax);
  93716. log2cmax--;
  93717. *shift = (int)precision - log2cmax - 1;
  93718. if(*shift > max_shiftlimit)
  93719. *shift = max_shiftlimit;
  93720. else if(*shift < min_shiftlimit)
  93721. return 1;
  93722. }
  93723. if(*shift >= 0) {
  93724. FLAC__double error = 0.0;
  93725. FLAC__int32 q;
  93726. for(i = 0; i < order; i++) {
  93727. error += lp_coeff[i] * (1 << *shift);
  93728. #if 1 /* unfortunately lround() is C99 */
  93729. if(error >= 0.0)
  93730. q = (FLAC__int32)(error + 0.5);
  93731. else
  93732. q = (FLAC__int32)(error - 0.5);
  93733. #else
  93734. q = lround(error);
  93735. #endif
  93736. #ifdef FLAC__OVERFLOW_DETECT
  93737. if(q > qmax+1) /* we expect q==qmax+1 occasionally due to rounding */
  93738. 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]);
  93739. else if(q < qmin)
  93740. 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]);
  93741. #endif
  93742. if(q > qmax)
  93743. q = qmax;
  93744. else if(q < qmin)
  93745. q = qmin;
  93746. error -= q;
  93747. qlp_coeff[i] = q;
  93748. }
  93749. }
  93750. /* negative shift is very rare but due to design flaw, negative shift is
  93751. * a NOP in the decoder, so it must be handled specially by scaling down
  93752. * coeffs
  93753. */
  93754. else {
  93755. const int nshift = -(*shift);
  93756. FLAC__double error = 0.0;
  93757. FLAC__int32 q;
  93758. #ifdef DEBUG
  93759. fprintf(stderr,"FLAC__lpc_quantize_coefficients: negative shift=%d order=%u cmax=%f\n", *shift, order, cmax);
  93760. #endif
  93761. for(i = 0; i < order; i++) {
  93762. error += lp_coeff[i] / (1 << nshift);
  93763. #if 1 /* unfortunately lround() is C99 */
  93764. if(error >= 0.0)
  93765. q = (FLAC__int32)(error + 0.5);
  93766. else
  93767. q = (FLAC__int32)(error - 0.5);
  93768. #else
  93769. q = lround(error);
  93770. #endif
  93771. #ifdef FLAC__OVERFLOW_DETECT
  93772. if(q > qmax+1) /* we expect q==qmax+1 occasionally due to rounding */
  93773. 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]);
  93774. else if(q < qmin)
  93775. 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]);
  93776. #endif
  93777. if(q > qmax)
  93778. q = qmax;
  93779. else if(q < qmin)
  93780. q = qmin;
  93781. error -= q;
  93782. qlp_coeff[i] = q;
  93783. }
  93784. *shift = 0;
  93785. }
  93786. return 0;
  93787. }
  93788. 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[])
  93789. #if defined(FLAC__OVERFLOW_DETECT) || !defined(FLAC__LPC_UNROLLED_FILTER_LOOPS)
  93790. {
  93791. FLAC__int64 sumo;
  93792. unsigned i, j;
  93793. FLAC__int32 sum;
  93794. const FLAC__int32 *history;
  93795. #ifdef FLAC__OVERFLOW_DETECT_VERBOSE
  93796. fprintf(stderr,"FLAC__lpc_compute_residual_from_qlp_coefficients: data_len=%d, order=%u, lpq=%d",data_len,order,lp_quantization);
  93797. for(i=0;i<order;i++)
  93798. fprintf(stderr,", q[%u]=%d",i,qlp_coeff[i]);
  93799. fprintf(stderr,"\n");
  93800. #endif
  93801. FLAC__ASSERT(order > 0);
  93802. for(i = 0; i < data_len; i++) {
  93803. sumo = 0;
  93804. sum = 0;
  93805. history = data;
  93806. for(j = 0; j < order; j++) {
  93807. sum += qlp_coeff[j] * (*(--history));
  93808. sumo += (FLAC__int64)qlp_coeff[j] * (FLAC__int64)(*history);
  93809. #if defined _MSC_VER
  93810. if(sumo > 2147483647I64 || sumo < -2147483648I64)
  93811. 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);
  93812. #else
  93813. if(sumo > 2147483647ll || sumo < -2147483648ll)
  93814. 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);
  93815. #endif
  93816. }
  93817. *(residual++) = *(data++) - (sum >> lp_quantization);
  93818. }
  93819. /* Here's a slower but clearer version:
  93820. for(i = 0; i < data_len; i++) {
  93821. sum = 0;
  93822. for(j = 0; j < order; j++)
  93823. sum += qlp_coeff[j] * data[i-j-1];
  93824. residual[i] = data[i] - (sum >> lp_quantization);
  93825. }
  93826. */
  93827. }
  93828. #else /* fully unrolled version for normal use */
  93829. {
  93830. int i;
  93831. FLAC__int32 sum;
  93832. FLAC__ASSERT(order > 0);
  93833. FLAC__ASSERT(order <= 32);
  93834. /*
  93835. * We do unique versions up to 12th order since that's the subset limit.
  93836. * Also they are roughly ordered to match frequency of occurrence to
  93837. * minimize branching.
  93838. */
  93839. if(order <= 12) {
  93840. if(order > 8) {
  93841. if(order > 10) {
  93842. if(order == 12) {
  93843. for(i = 0; i < (int)data_len; i++) {
  93844. sum = 0;
  93845. sum += qlp_coeff[11] * data[i-12];
  93846. sum += qlp_coeff[10] * data[i-11];
  93847. sum += qlp_coeff[9] * data[i-10];
  93848. sum += qlp_coeff[8] * data[i-9];
  93849. sum += qlp_coeff[7] * data[i-8];
  93850. sum += qlp_coeff[6] * data[i-7];
  93851. sum += qlp_coeff[5] * data[i-6];
  93852. sum += qlp_coeff[4] * data[i-5];
  93853. sum += qlp_coeff[3] * data[i-4];
  93854. sum += qlp_coeff[2] * data[i-3];
  93855. sum += qlp_coeff[1] * data[i-2];
  93856. sum += qlp_coeff[0] * data[i-1];
  93857. residual[i] = data[i] - (sum >> lp_quantization);
  93858. }
  93859. }
  93860. else { /* order == 11 */
  93861. for(i = 0; i < (int)data_len; i++) {
  93862. sum = 0;
  93863. sum += qlp_coeff[10] * data[i-11];
  93864. sum += qlp_coeff[9] * data[i-10];
  93865. sum += qlp_coeff[8] * data[i-9];
  93866. sum += qlp_coeff[7] * data[i-8];
  93867. sum += qlp_coeff[6] * data[i-7];
  93868. sum += qlp_coeff[5] * data[i-6];
  93869. sum += qlp_coeff[4] * data[i-5];
  93870. sum += qlp_coeff[3] * data[i-4];
  93871. sum += qlp_coeff[2] * data[i-3];
  93872. sum += qlp_coeff[1] * data[i-2];
  93873. sum += qlp_coeff[0] * data[i-1];
  93874. residual[i] = data[i] - (sum >> lp_quantization);
  93875. }
  93876. }
  93877. }
  93878. else {
  93879. if(order == 10) {
  93880. for(i = 0; i < (int)data_len; i++) {
  93881. sum = 0;
  93882. sum += qlp_coeff[9] * data[i-10];
  93883. sum += qlp_coeff[8] * data[i-9];
  93884. sum += qlp_coeff[7] * data[i-8];
  93885. sum += qlp_coeff[6] * data[i-7];
  93886. sum += qlp_coeff[5] * data[i-6];
  93887. sum += qlp_coeff[4] * data[i-5];
  93888. sum += qlp_coeff[3] * data[i-4];
  93889. sum += qlp_coeff[2] * data[i-3];
  93890. sum += qlp_coeff[1] * data[i-2];
  93891. sum += qlp_coeff[0] * data[i-1];
  93892. residual[i] = data[i] - (sum >> lp_quantization);
  93893. }
  93894. }
  93895. else { /* order == 9 */
  93896. for(i = 0; i < (int)data_len; i++) {
  93897. sum = 0;
  93898. sum += qlp_coeff[8] * data[i-9];
  93899. sum += qlp_coeff[7] * data[i-8];
  93900. sum += qlp_coeff[6] * data[i-7];
  93901. sum += qlp_coeff[5] * data[i-6];
  93902. sum += qlp_coeff[4] * data[i-5];
  93903. sum += qlp_coeff[3] * data[i-4];
  93904. sum += qlp_coeff[2] * data[i-3];
  93905. sum += qlp_coeff[1] * data[i-2];
  93906. sum += qlp_coeff[0] * data[i-1];
  93907. residual[i] = data[i] - (sum >> lp_quantization);
  93908. }
  93909. }
  93910. }
  93911. }
  93912. else if(order > 4) {
  93913. if(order > 6) {
  93914. if(order == 8) {
  93915. for(i = 0; i < (int)data_len; i++) {
  93916. sum = 0;
  93917. sum += qlp_coeff[7] * data[i-8];
  93918. sum += qlp_coeff[6] * data[i-7];
  93919. sum += qlp_coeff[5] * data[i-6];
  93920. sum += qlp_coeff[4] * data[i-5];
  93921. sum += qlp_coeff[3] * data[i-4];
  93922. sum += qlp_coeff[2] * data[i-3];
  93923. sum += qlp_coeff[1] * data[i-2];
  93924. sum += qlp_coeff[0] * data[i-1];
  93925. residual[i] = data[i] - (sum >> lp_quantization);
  93926. }
  93927. }
  93928. else { /* order == 7 */
  93929. for(i = 0; i < (int)data_len; i++) {
  93930. sum = 0;
  93931. sum += qlp_coeff[6] * data[i-7];
  93932. sum += qlp_coeff[5] * data[i-6];
  93933. sum += qlp_coeff[4] * data[i-5];
  93934. sum += qlp_coeff[3] * data[i-4];
  93935. sum += qlp_coeff[2] * data[i-3];
  93936. sum += qlp_coeff[1] * data[i-2];
  93937. sum += qlp_coeff[0] * data[i-1];
  93938. residual[i] = data[i] - (sum >> lp_quantization);
  93939. }
  93940. }
  93941. }
  93942. else {
  93943. if(order == 6) {
  93944. for(i = 0; i < (int)data_len; i++) {
  93945. sum = 0;
  93946. sum += qlp_coeff[5] * data[i-6];
  93947. sum += qlp_coeff[4] * data[i-5];
  93948. sum += qlp_coeff[3] * data[i-4];
  93949. sum += qlp_coeff[2] * data[i-3];
  93950. sum += qlp_coeff[1] * data[i-2];
  93951. sum += qlp_coeff[0] * data[i-1];
  93952. residual[i] = data[i] - (sum >> lp_quantization);
  93953. }
  93954. }
  93955. else { /* order == 5 */
  93956. for(i = 0; i < (int)data_len; i++) {
  93957. sum = 0;
  93958. sum += qlp_coeff[4] * data[i-5];
  93959. sum += qlp_coeff[3] * data[i-4];
  93960. sum += qlp_coeff[2] * data[i-3];
  93961. sum += qlp_coeff[1] * data[i-2];
  93962. sum += qlp_coeff[0] * data[i-1];
  93963. residual[i] = data[i] - (sum >> lp_quantization);
  93964. }
  93965. }
  93966. }
  93967. }
  93968. else {
  93969. if(order > 2) {
  93970. if(order == 4) {
  93971. for(i = 0; i < (int)data_len; i++) {
  93972. sum = 0;
  93973. sum += qlp_coeff[3] * data[i-4];
  93974. sum += qlp_coeff[2] * data[i-3];
  93975. sum += qlp_coeff[1] * data[i-2];
  93976. sum += qlp_coeff[0] * data[i-1];
  93977. residual[i] = data[i] - (sum >> lp_quantization);
  93978. }
  93979. }
  93980. else { /* order == 3 */
  93981. for(i = 0; i < (int)data_len; i++) {
  93982. sum = 0;
  93983. sum += qlp_coeff[2] * data[i-3];
  93984. sum += qlp_coeff[1] * data[i-2];
  93985. sum += qlp_coeff[0] * data[i-1];
  93986. residual[i] = data[i] - (sum >> lp_quantization);
  93987. }
  93988. }
  93989. }
  93990. else {
  93991. if(order == 2) {
  93992. for(i = 0; i < (int)data_len; i++) {
  93993. sum = 0;
  93994. sum += qlp_coeff[1] * data[i-2];
  93995. sum += qlp_coeff[0] * data[i-1];
  93996. residual[i] = data[i] - (sum >> lp_quantization);
  93997. }
  93998. }
  93999. else { /* order == 1 */
  94000. for(i = 0; i < (int)data_len; i++)
  94001. residual[i] = data[i] - ((qlp_coeff[0] * data[i-1]) >> lp_quantization);
  94002. }
  94003. }
  94004. }
  94005. }
  94006. else { /* order > 12 */
  94007. for(i = 0; i < (int)data_len; i++) {
  94008. sum = 0;
  94009. switch(order) {
  94010. case 32: sum += qlp_coeff[31] * data[i-32];
  94011. case 31: sum += qlp_coeff[30] * data[i-31];
  94012. case 30: sum += qlp_coeff[29] * data[i-30];
  94013. case 29: sum += qlp_coeff[28] * data[i-29];
  94014. case 28: sum += qlp_coeff[27] * data[i-28];
  94015. case 27: sum += qlp_coeff[26] * data[i-27];
  94016. case 26: sum += qlp_coeff[25] * data[i-26];
  94017. case 25: sum += qlp_coeff[24] * data[i-25];
  94018. case 24: sum += qlp_coeff[23] * data[i-24];
  94019. case 23: sum += qlp_coeff[22] * data[i-23];
  94020. case 22: sum += qlp_coeff[21] * data[i-22];
  94021. case 21: sum += qlp_coeff[20] * data[i-21];
  94022. case 20: sum += qlp_coeff[19] * data[i-20];
  94023. case 19: sum += qlp_coeff[18] * data[i-19];
  94024. case 18: sum += qlp_coeff[17] * data[i-18];
  94025. case 17: sum += qlp_coeff[16] * data[i-17];
  94026. case 16: sum += qlp_coeff[15] * data[i-16];
  94027. case 15: sum += qlp_coeff[14] * data[i-15];
  94028. case 14: sum += qlp_coeff[13] * data[i-14];
  94029. case 13: sum += qlp_coeff[12] * data[i-13];
  94030. sum += qlp_coeff[11] * data[i-12];
  94031. sum += qlp_coeff[10] * data[i-11];
  94032. sum += qlp_coeff[ 9] * data[i-10];
  94033. sum += qlp_coeff[ 8] * data[i- 9];
  94034. sum += qlp_coeff[ 7] * data[i- 8];
  94035. sum += qlp_coeff[ 6] * data[i- 7];
  94036. sum += qlp_coeff[ 5] * data[i- 6];
  94037. sum += qlp_coeff[ 4] * data[i- 5];
  94038. sum += qlp_coeff[ 3] * data[i- 4];
  94039. sum += qlp_coeff[ 2] * data[i- 3];
  94040. sum += qlp_coeff[ 1] * data[i- 2];
  94041. sum += qlp_coeff[ 0] * data[i- 1];
  94042. }
  94043. residual[i] = data[i] - (sum >> lp_quantization);
  94044. }
  94045. }
  94046. }
  94047. #endif
  94048. 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[])
  94049. #if defined(FLAC__OVERFLOW_DETECT) || !defined(FLAC__LPC_UNROLLED_FILTER_LOOPS)
  94050. {
  94051. unsigned i, j;
  94052. FLAC__int64 sum;
  94053. const FLAC__int32 *history;
  94054. #ifdef FLAC__OVERFLOW_DETECT_VERBOSE
  94055. fprintf(stderr,"FLAC__lpc_compute_residual_from_qlp_coefficients_wide: data_len=%d, order=%u, lpq=%d",data_len,order,lp_quantization);
  94056. for(i=0;i<order;i++)
  94057. fprintf(stderr,", q[%u]=%d",i,qlp_coeff[i]);
  94058. fprintf(stderr,"\n");
  94059. #endif
  94060. FLAC__ASSERT(order > 0);
  94061. for(i = 0; i < data_len; i++) {
  94062. sum = 0;
  94063. history = data;
  94064. for(j = 0; j < order; j++)
  94065. sum += (FLAC__int64)qlp_coeff[j] * (FLAC__int64)(*(--history));
  94066. if(FLAC__bitmath_silog2_wide(sum >> lp_quantization) > 32) {
  94067. #if defined _MSC_VER
  94068. fprintf(stderr,"FLAC__lpc_compute_residual_from_qlp_coefficients_wide: OVERFLOW, i=%u, sum=%I64d\n", i, sum >> lp_quantization);
  94069. #else
  94070. fprintf(stderr,"FLAC__lpc_compute_residual_from_qlp_coefficients_wide: OVERFLOW, i=%u, sum=%lld\n", i, (long long)(sum >> lp_quantization));
  94071. #endif
  94072. break;
  94073. }
  94074. if(FLAC__bitmath_silog2_wide((FLAC__int64)(*data) - (sum >> lp_quantization)) > 32) {
  94075. #if defined _MSC_VER
  94076. 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));
  94077. #else
  94078. 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)));
  94079. #endif
  94080. break;
  94081. }
  94082. *(residual++) = *(data++) - (FLAC__int32)(sum >> lp_quantization);
  94083. }
  94084. }
  94085. #else /* fully unrolled version for normal use */
  94086. {
  94087. int i;
  94088. FLAC__int64 sum;
  94089. FLAC__ASSERT(order > 0);
  94090. FLAC__ASSERT(order <= 32);
  94091. /*
  94092. * We do unique versions up to 12th order since that's the subset limit.
  94093. * Also they are roughly ordered to match frequency of occurrence to
  94094. * minimize branching.
  94095. */
  94096. if(order <= 12) {
  94097. if(order > 8) {
  94098. if(order > 10) {
  94099. if(order == 12) {
  94100. for(i = 0; i < (int)data_len; i++) {
  94101. sum = 0;
  94102. sum += qlp_coeff[11] * (FLAC__int64)data[i-12];
  94103. sum += qlp_coeff[10] * (FLAC__int64)data[i-11];
  94104. sum += qlp_coeff[9] * (FLAC__int64)data[i-10];
  94105. sum += qlp_coeff[8] * (FLAC__int64)data[i-9];
  94106. sum += qlp_coeff[7] * (FLAC__int64)data[i-8];
  94107. sum += qlp_coeff[6] * (FLAC__int64)data[i-7];
  94108. sum += qlp_coeff[5] * (FLAC__int64)data[i-6];
  94109. sum += qlp_coeff[4] * (FLAC__int64)data[i-5];
  94110. sum += qlp_coeff[3] * (FLAC__int64)data[i-4];
  94111. sum += qlp_coeff[2] * (FLAC__int64)data[i-3];
  94112. sum += qlp_coeff[1] * (FLAC__int64)data[i-2];
  94113. sum += qlp_coeff[0] * (FLAC__int64)data[i-1];
  94114. residual[i] = data[i] - (FLAC__int32)(sum >> lp_quantization);
  94115. }
  94116. }
  94117. else { /* order == 11 */
  94118. for(i = 0; i < (int)data_len; i++) {
  94119. sum = 0;
  94120. sum += qlp_coeff[10] * (FLAC__int64)data[i-11];
  94121. sum += qlp_coeff[9] * (FLAC__int64)data[i-10];
  94122. sum += qlp_coeff[8] * (FLAC__int64)data[i-9];
  94123. sum += qlp_coeff[7] * (FLAC__int64)data[i-8];
  94124. sum += qlp_coeff[6] * (FLAC__int64)data[i-7];
  94125. sum += qlp_coeff[5] * (FLAC__int64)data[i-6];
  94126. sum += qlp_coeff[4] * (FLAC__int64)data[i-5];
  94127. sum += qlp_coeff[3] * (FLAC__int64)data[i-4];
  94128. sum += qlp_coeff[2] * (FLAC__int64)data[i-3];
  94129. sum += qlp_coeff[1] * (FLAC__int64)data[i-2];
  94130. sum += qlp_coeff[0] * (FLAC__int64)data[i-1];
  94131. residual[i] = data[i] - (FLAC__int32)(sum >> lp_quantization);
  94132. }
  94133. }
  94134. }
  94135. else {
  94136. if(order == 10) {
  94137. for(i = 0; i < (int)data_len; i++) {
  94138. sum = 0;
  94139. sum += qlp_coeff[9] * (FLAC__int64)data[i-10];
  94140. sum += qlp_coeff[8] * (FLAC__int64)data[i-9];
  94141. sum += qlp_coeff[7] * (FLAC__int64)data[i-8];
  94142. sum += qlp_coeff[6] * (FLAC__int64)data[i-7];
  94143. sum += qlp_coeff[5] * (FLAC__int64)data[i-6];
  94144. sum += qlp_coeff[4] * (FLAC__int64)data[i-5];
  94145. sum += qlp_coeff[3] * (FLAC__int64)data[i-4];
  94146. sum += qlp_coeff[2] * (FLAC__int64)data[i-3];
  94147. sum += qlp_coeff[1] * (FLAC__int64)data[i-2];
  94148. sum += qlp_coeff[0] * (FLAC__int64)data[i-1];
  94149. residual[i] = data[i] - (FLAC__int32)(sum >> lp_quantization);
  94150. }
  94151. }
  94152. else { /* order == 9 */
  94153. for(i = 0; i < (int)data_len; i++) {
  94154. sum = 0;
  94155. sum += qlp_coeff[8] * (FLAC__int64)data[i-9];
  94156. sum += qlp_coeff[7] * (FLAC__int64)data[i-8];
  94157. sum += qlp_coeff[6] * (FLAC__int64)data[i-7];
  94158. sum += qlp_coeff[5] * (FLAC__int64)data[i-6];
  94159. sum += qlp_coeff[4] * (FLAC__int64)data[i-5];
  94160. sum += qlp_coeff[3] * (FLAC__int64)data[i-4];
  94161. sum += qlp_coeff[2] * (FLAC__int64)data[i-3];
  94162. sum += qlp_coeff[1] * (FLAC__int64)data[i-2];
  94163. sum += qlp_coeff[0] * (FLAC__int64)data[i-1];
  94164. residual[i] = data[i] - (FLAC__int32)(sum >> lp_quantization);
  94165. }
  94166. }
  94167. }
  94168. }
  94169. else if(order > 4) {
  94170. if(order > 6) {
  94171. if(order == 8) {
  94172. for(i = 0; i < (int)data_len; i++) {
  94173. sum = 0;
  94174. sum += qlp_coeff[7] * (FLAC__int64)data[i-8];
  94175. sum += qlp_coeff[6] * (FLAC__int64)data[i-7];
  94176. sum += qlp_coeff[5] * (FLAC__int64)data[i-6];
  94177. sum += qlp_coeff[4] * (FLAC__int64)data[i-5];
  94178. sum += qlp_coeff[3] * (FLAC__int64)data[i-4];
  94179. sum += qlp_coeff[2] * (FLAC__int64)data[i-3];
  94180. sum += qlp_coeff[1] * (FLAC__int64)data[i-2];
  94181. sum += qlp_coeff[0] * (FLAC__int64)data[i-1];
  94182. residual[i] = data[i] - (FLAC__int32)(sum >> lp_quantization);
  94183. }
  94184. }
  94185. else { /* order == 7 */
  94186. for(i = 0; i < (int)data_len; i++) {
  94187. sum = 0;
  94188. sum += qlp_coeff[6] * (FLAC__int64)data[i-7];
  94189. sum += qlp_coeff[5] * (FLAC__int64)data[i-6];
  94190. sum += qlp_coeff[4] * (FLAC__int64)data[i-5];
  94191. sum += qlp_coeff[3] * (FLAC__int64)data[i-4];
  94192. sum += qlp_coeff[2] * (FLAC__int64)data[i-3];
  94193. sum += qlp_coeff[1] * (FLAC__int64)data[i-2];
  94194. sum += qlp_coeff[0] * (FLAC__int64)data[i-1];
  94195. residual[i] = data[i] - (FLAC__int32)(sum >> lp_quantization);
  94196. }
  94197. }
  94198. }
  94199. else {
  94200. if(order == 6) {
  94201. for(i = 0; i < (int)data_len; i++) {
  94202. sum = 0;
  94203. sum += qlp_coeff[5] * (FLAC__int64)data[i-6];
  94204. sum += qlp_coeff[4] * (FLAC__int64)data[i-5];
  94205. sum += qlp_coeff[3] * (FLAC__int64)data[i-4];
  94206. sum += qlp_coeff[2] * (FLAC__int64)data[i-3];
  94207. sum += qlp_coeff[1] * (FLAC__int64)data[i-2];
  94208. sum += qlp_coeff[0] * (FLAC__int64)data[i-1];
  94209. residual[i] = data[i] - (FLAC__int32)(sum >> lp_quantization);
  94210. }
  94211. }
  94212. else { /* order == 5 */
  94213. for(i = 0; i < (int)data_len; i++) {
  94214. sum = 0;
  94215. sum += qlp_coeff[4] * (FLAC__int64)data[i-5];
  94216. sum += qlp_coeff[3] * (FLAC__int64)data[i-4];
  94217. sum += qlp_coeff[2] * (FLAC__int64)data[i-3];
  94218. sum += qlp_coeff[1] * (FLAC__int64)data[i-2];
  94219. sum += qlp_coeff[0] * (FLAC__int64)data[i-1];
  94220. residual[i] = data[i] - (FLAC__int32)(sum >> lp_quantization);
  94221. }
  94222. }
  94223. }
  94224. }
  94225. else {
  94226. if(order > 2) {
  94227. if(order == 4) {
  94228. for(i = 0; i < (int)data_len; i++) {
  94229. sum = 0;
  94230. sum += qlp_coeff[3] * (FLAC__int64)data[i-4];
  94231. sum += qlp_coeff[2] * (FLAC__int64)data[i-3];
  94232. sum += qlp_coeff[1] * (FLAC__int64)data[i-2];
  94233. sum += qlp_coeff[0] * (FLAC__int64)data[i-1];
  94234. residual[i] = data[i] - (FLAC__int32)(sum >> lp_quantization);
  94235. }
  94236. }
  94237. else { /* order == 3 */
  94238. for(i = 0; i < (int)data_len; i++) {
  94239. sum = 0;
  94240. sum += qlp_coeff[2] * (FLAC__int64)data[i-3];
  94241. sum += qlp_coeff[1] * (FLAC__int64)data[i-2];
  94242. sum += qlp_coeff[0] * (FLAC__int64)data[i-1];
  94243. residual[i] = data[i] - (FLAC__int32)(sum >> lp_quantization);
  94244. }
  94245. }
  94246. }
  94247. else {
  94248. if(order == 2) {
  94249. for(i = 0; i < (int)data_len; i++) {
  94250. sum = 0;
  94251. sum += qlp_coeff[1] * (FLAC__int64)data[i-2];
  94252. sum += qlp_coeff[0] * (FLAC__int64)data[i-1];
  94253. residual[i] = data[i] - (FLAC__int32)(sum >> lp_quantization);
  94254. }
  94255. }
  94256. else { /* order == 1 */
  94257. for(i = 0; i < (int)data_len; i++)
  94258. residual[i] = data[i] - (FLAC__int32)((qlp_coeff[0] * (FLAC__int64)data[i-1]) >> lp_quantization);
  94259. }
  94260. }
  94261. }
  94262. }
  94263. else { /* order > 12 */
  94264. for(i = 0; i < (int)data_len; i++) {
  94265. sum = 0;
  94266. switch(order) {
  94267. case 32: sum += qlp_coeff[31] * (FLAC__int64)data[i-32];
  94268. case 31: sum += qlp_coeff[30] * (FLAC__int64)data[i-31];
  94269. case 30: sum += qlp_coeff[29] * (FLAC__int64)data[i-30];
  94270. case 29: sum += qlp_coeff[28] * (FLAC__int64)data[i-29];
  94271. case 28: sum += qlp_coeff[27] * (FLAC__int64)data[i-28];
  94272. case 27: sum += qlp_coeff[26] * (FLAC__int64)data[i-27];
  94273. case 26: sum += qlp_coeff[25] * (FLAC__int64)data[i-26];
  94274. case 25: sum += qlp_coeff[24] * (FLAC__int64)data[i-25];
  94275. case 24: sum += qlp_coeff[23] * (FLAC__int64)data[i-24];
  94276. case 23: sum += qlp_coeff[22] * (FLAC__int64)data[i-23];
  94277. case 22: sum += qlp_coeff[21] * (FLAC__int64)data[i-22];
  94278. case 21: sum += qlp_coeff[20] * (FLAC__int64)data[i-21];
  94279. case 20: sum += qlp_coeff[19] * (FLAC__int64)data[i-20];
  94280. case 19: sum += qlp_coeff[18] * (FLAC__int64)data[i-19];
  94281. case 18: sum += qlp_coeff[17] * (FLAC__int64)data[i-18];
  94282. case 17: sum += qlp_coeff[16] * (FLAC__int64)data[i-17];
  94283. case 16: sum += qlp_coeff[15] * (FLAC__int64)data[i-16];
  94284. case 15: sum += qlp_coeff[14] * (FLAC__int64)data[i-15];
  94285. case 14: sum += qlp_coeff[13] * (FLAC__int64)data[i-14];
  94286. case 13: sum += qlp_coeff[12] * (FLAC__int64)data[i-13];
  94287. sum += qlp_coeff[11] * (FLAC__int64)data[i-12];
  94288. sum += qlp_coeff[10] * (FLAC__int64)data[i-11];
  94289. sum += qlp_coeff[ 9] * (FLAC__int64)data[i-10];
  94290. sum += qlp_coeff[ 8] * (FLAC__int64)data[i- 9];
  94291. sum += qlp_coeff[ 7] * (FLAC__int64)data[i- 8];
  94292. sum += qlp_coeff[ 6] * (FLAC__int64)data[i- 7];
  94293. sum += qlp_coeff[ 5] * (FLAC__int64)data[i- 6];
  94294. sum += qlp_coeff[ 4] * (FLAC__int64)data[i- 5];
  94295. sum += qlp_coeff[ 3] * (FLAC__int64)data[i- 4];
  94296. sum += qlp_coeff[ 2] * (FLAC__int64)data[i- 3];
  94297. sum += qlp_coeff[ 1] * (FLAC__int64)data[i- 2];
  94298. sum += qlp_coeff[ 0] * (FLAC__int64)data[i- 1];
  94299. }
  94300. residual[i] = data[i] - (FLAC__int32)(sum >> lp_quantization);
  94301. }
  94302. }
  94303. }
  94304. #endif
  94305. #endif /* !defined FLAC__INTEGER_ONLY_LIBRARY */
  94306. 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[])
  94307. #if defined(FLAC__OVERFLOW_DETECT) || !defined(FLAC__LPC_UNROLLED_FILTER_LOOPS)
  94308. {
  94309. FLAC__int64 sumo;
  94310. unsigned i, j;
  94311. FLAC__int32 sum;
  94312. const FLAC__int32 *r = residual, *history;
  94313. #ifdef FLAC__OVERFLOW_DETECT_VERBOSE
  94314. fprintf(stderr,"FLAC__lpc_restore_signal: data_len=%d, order=%u, lpq=%d",data_len,order,lp_quantization);
  94315. for(i=0;i<order;i++)
  94316. fprintf(stderr,", q[%u]=%d",i,qlp_coeff[i]);
  94317. fprintf(stderr,"\n");
  94318. #endif
  94319. FLAC__ASSERT(order > 0);
  94320. for(i = 0; i < data_len; i++) {
  94321. sumo = 0;
  94322. sum = 0;
  94323. history = data;
  94324. for(j = 0; j < order; j++) {
  94325. sum += qlp_coeff[j] * (*(--history));
  94326. sumo += (FLAC__int64)qlp_coeff[j] * (FLAC__int64)(*history);
  94327. #if defined _MSC_VER
  94328. if(sumo > 2147483647I64 || sumo < -2147483648I64)
  94329. 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);
  94330. #else
  94331. if(sumo > 2147483647ll || sumo < -2147483648ll)
  94332. 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);
  94333. #endif
  94334. }
  94335. *(data++) = *(r++) + (sum >> lp_quantization);
  94336. }
  94337. /* Here's a slower but clearer version:
  94338. for(i = 0; i < data_len; i++) {
  94339. sum = 0;
  94340. for(j = 0; j < order; j++)
  94341. sum += qlp_coeff[j] * data[i-j-1];
  94342. data[i] = residual[i] + (sum >> lp_quantization);
  94343. }
  94344. */
  94345. }
  94346. #else /* fully unrolled version for normal use */
  94347. {
  94348. int i;
  94349. FLAC__int32 sum;
  94350. FLAC__ASSERT(order > 0);
  94351. FLAC__ASSERT(order <= 32);
  94352. /*
  94353. * We do unique versions up to 12th order since that's the subset limit.
  94354. * Also they are roughly ordered to match frequency of occurrence to
  94355. * minimize branching.
  94356. */
  94357. if(order <= 12) {
  94358. if(order > 8) {
  94359. if(order > 10) {
  94360. if(order == 12) {
  94361. for(i = 0; i < (int)data_len; i++) {
  94362. sum = 0;
  94363. sum += qlp_coeff[11] * data[i-12];
  94364. sum += qlp_coeff[10] * data[i-11];
  94365. sum += qlp_coeff[9] * data[i-10];
  94366. sum += qlp_coeff[8] * data[i-9];
  94367. sum += qlp_coeff[7] * data[i-8];
  94368. sum += qlp_coeff[6] * data[i-7];
  94369. sum += qlp_coeff[5] * data[i-6];
  94370. sum += qlp_coeff[4] * data[i-5];
  94371. sum += qlp_coeff[3] * data[i-4];
  94372. sum += qlp_coeff[2] * data[i-3];
  94373. sum += qlp_coeff[1] * data[i-2];
  94374. sum += qlp_coeff[0] * data[i-1];
  94375. data[i] = residual[i] + (sum >> lp_quantization);
  94376. }
  94377. }
  94378. else { /* order == 11 */
  94379. for(i = 0; i < (int)data_len; i++) {
  94380. sum = 0;
  94381. sum += qlp_coeff[10] * data[i-11];
  94382. sum += qlp_coeff[9] * data[i-10];
  94383. sum += qlp_coeff[8] * data[i-9];
  94384. sum += qlp_coeff[7] * data[i-8];
  94385. sum += qlp_coeff[6] * data[i-7];
  94386. sum += qlp_coeff[5] * data[i-6];
  94387. sum += qlp_coeff[4] * data[i-5];
  94388. sum += qlp_coeff[3] * data[i-4];
  94389. sum += qlp_coeff[2] * data[i-3];
  94390. sum += qlp_coeff[1] * data[i-2];
  94391. sum += qlp_coeff[0] * data[i-1];
  94392. data[i] = residual[i] + (sum >> lp_quantization);
  94393. }
  94394. }
  94395. }
  94396. else {
  94397. if(order == 10) {
  94398. for(i = 0; i < (int)data_len; i++) {
  94399. sum = 0;
  94400. sum += qlp_coeff[9] * data[i-10];
  94401. sum += qlp_coeff[8] * data[i-9];
  94402. sum += qlp_coeff[7] * data[i-8];
  94403. sum += qlp_coeff[6] * data[i-7];
  94404. sum += qlp_coeff[5] * data[i-6];
  94405. sum += qlp_coeff[4] * data[i-5];
  94406. sum += qlp_coeff[3] * data[i-4];
  94407. sum += qlp_coeff[2] * data[i-3];
  94408. sum += qlp_coeff[1] * data[i-2];
  94409. sum += qlp_coeff[0] * data[i-1];
  94410. data[i] = residual[i] + (sum >> lp_quantization);
  94411. }
  94412. }
  94413. else { /* order == 9 */
  94414. for(i = 0; i < (int)data_len; i++) {
  94415. sum = 0;
  94416. sum += qlp_coeff[8] * data[i-9];
  94417. sum += qlp_coeff[7] * data[i-8];
  94418. sum += qlp_coeff[6] * data[i-7];
  94419. sum += qlp_coeff[5] * data[i-6];
  94420. sum += qlp_coeff[4] * data[i-5];
  94421. sum += qlp_coeff[3] * data[i-4];
  94422. sum += qlp_coeff[2] * data[i-3];
  94423. sum += qlp_coeff[1] * data[i-2];
  94424. sum += qlp_coeff[0] * data[i-1];
  94425. data[i] = residual[i] + (sum >> lp_quantization);
  94426. }
  94427. }
  94428. }
  94429. }
  94430. else if(order > 4) {
  94431. if(order > 6) {
  94432. if(order == 8) {
  94433. for(i = 0; i < (int)data_len; i++) {
  94434. sum = 0;
  94435. sum += qlp_coeff[7] * data[i-8];
  94436. sum += qlp_coeff[6] * data[i-7];
  94437. sum += qlp_coeff[5] * data[i-6];
  94438. sum += qlp_coeff[4] * data[i-5];
  94439. sum += qlp_coeff[3] * data[i-4];
  94440. sum += qlp_coeff[2] * data[i-3];
  94441. sum += qlp_coeff[1] * data[i-2];
  94442. sum += qlp_coeff[0] * data[i-1];
  94443. data[i] = residual[i] + (sum >> lp_quantization);
  94444. }
  94445. }
  94446. else { /* order == 7 */
  94447. for(i = 0; i < (int)data_len; i++) {
  94448. sum = 0;
  94449. sum += qlp_coeff[6] * data[i-7];
  94450. sum += qlp_coeff[5] * data[i-6];
  94451. sum += qlp_coeff[4] * data[i-5];
  94452. sum += qlp_coeff[3] * data[i-4];
  94453. sum += qlp_coeff[2] * data[i-3];
  94454. sum += qlp_coeff[1] * data[i-2];
  94455. sum += qlp_coeff[0] * data[i-1];
  94456. data[i] = residual[i] + (sum >> lp_quantization);
  94457. }
  94458. }
  94459. }
  94460. else {
  94461. if(order == 6) {
  94462. for(i = 0; i < (int)data_len; i++) {
  94463. sum = 0;
  94464. sum += qlp_coeff[5] * data[i-6];
  94465. sum += qlp_coeff[4] * data[i-5];
  94466. sum += qlp_coeff[3] * data[i-4];
  94467. sum += qlp_coeff[2] * data[i-3];
  94468. sum += qlp_coeff[1] * data[i-2];
  94469. sum += qlp_coeff[0] * data[i-1];
  94470. data[i] = residual[i] + (sum >> lp_quantization);
  94471. }
  94472. }
  94473. else { /* order == 5 */
  94474. for(i = 0; i < (int)data_len; i++) {
  94475. sum = 0;
  94476. sum += qlp_coeff[4] * data[i-5];
  94477. sum += qlp_coeff[3] * data[i-4];
  94478. sum += qlp_coeff[2] * data[i-3];
  94479. sum += qlp_coeff[1] * data[i-2];
  94480. sum += qlp_coeff[0] * data[i-1];
  94481. data[i] = residual[i] + (sum >> lp_quantization);
  94482. }
  94483. }
  94484. }
  94485. }
  94486. else {
  94487. if(order > 2) {
  94488. if(order == 4) {
  94489. for(i = 0; i < (int)data_len; i++) {
  94490. sum = 0;
  94491. sum += qlp_coeff[3] * data[i-4];
  94492. sum += qlp_coeff[2] * data[i-3];
  94493. sum += qlp_coeff[1] * data[i-2];
  94494. sum += qlp_coeff[0] * data[i-1];
  94495. data[i] = residual[i] + (sum >> lp_quantization);
  94496. }
  94497. }
  94498. else { /* order == 3 */
  94499. for(i = 0; i < (int)data_len; i++) {
  94500. sum = 0;
  94501. sum += qlp_coeff[2] * data[i-3];
  94502. sum += qlp_coeff[1] * data[i-2];
  94503. sum += qlp_coeff[0] * data[i-1];
  94504. data[i] = residual[i] + (sum >> lp_quantization);
  94505. }
  94506. }
  94507. }
  94508. else {
  94509. if(order == 2) {
  94510. for(i = 0; i < (int)data_len; i++) {
  94511. sum = 0;
  94512. sum += qlp_coeff[1] * data[i-2];
  94513. sum += qlp_coeff[0] * data[i-1];
  94514. data[i] = residual[i] + (sum >> lp_quantization);
  94515. }
  94516. }
  94517. else { /* order == 1 */
  94518. for(i = 0; i < (int)data_len; i++)
  94519. data[i] = residual[i] + ((qlp_coeff[0] * data[i-1]) >> lp_quantization);
  94520. }
  94521. }
  94522. }
  94523. }
  94524. else { /* order > 12 */
  94525. for(i = 0; i < (int)data_len; i++) {
  94526. sum = 0;
  94527. switch(order) {
  94528. case 32: sum += qlp_coeff[31] * data[i-32];
  94529. case 31: sum += qlp_coeff[30] * data[i-31];
  94530. case 30: sum += qlp_coeff[29] * data[i-30];
  94531. case 29: sum += qlp_coeff[28] * data[i-29];
  94532. case 28: sum += qlp_coeff[27] * data[i-28];
  94533. case 27: sum += qlp_coeff[26] * data[i-27];
  94534. case 26: sum += qlp_coeff[25] * data[i-26];
  94535. case 25: sum += qlp_coeff[24] * data[i-25];
  94536. case 24: sum += qlp_coeff[23] * data[i-24];
  94537. case 23: sum += qlp_coeff[22] * data[i-23];
  94538. case 22: sum += qlp_coeff[21] * data[i-22];
  94539. case 21: sum += qlp_coeff[20] * data[i-21];
  94540. case 20: sum += qlp_coeff[19] * data[i-20];
  94541. case 19: sum += qlp_coeff[18] * data[i-19];
  94542. case 18: sum += qlp_coeff[17] * data[i-18];
  94543. case 17: sum += qlp_coeff[16] * data[i-17];
  94544. case 16: sum += qlp_coeff[15] * data[i-16];
  94545. case 15: sum += qlp_coeff[14] * data[i-15];
  94546. case 14: sum += qlp_coeff[13] * data[i-14];
  94547. case 13: sum += qlp_coeff[12] * data[i-13];
  94548. sum += qlp_coeff[11] * data[i-12];
  94549. sum += qlp_coeff[10] * data[i-11];
  94550. sum += qlp_coeff[ 9] * data[i-10];
  94551. sum += qlp_coeff[ 8] * data[i- 9];
  94552. sum += qlp_coeff[ 7] * data[i- 8];
  94553. sum += qlp_coeff[ 6] * data[i- 7];
  94554. sum += qlp_coeff[ 5] * data[i- 6];
  94555. sum += qlp_coeff[ 4] * data[i- 5];
  94556. sum += qlp_coeff[ 3] * data[i- 4];
  94557. sum += qlp_coeff[ 2] * data[i- 3];
  94558. sum += qlp_coeff[ 1] * data[i- 2];
  94559. sum += qlp_coeff[ 0] * data[i- 1];
  94560. }
  94561. data[i] = residual[i] + (sum >> lp_quantization);
  94562. }
  94563. }
  94564. }
  94565. #endif
  94566. 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[])
  94567. #if defined(FLAC__OVERFLOW_DETECT) || !defined(FLAC__LPC_UNROLLED_FILTER_LOOPS)
  94568. {
  94569. unsigned i, j;
  94570. FLAC__int64 sum;
  94571. const FLAC__int32 *r = residual, *history;
  94572. #ifdef FLAC__OVERFLOW_DETECT_VERBOSE
  94573. fprintf(stderr,"FLAC__lpc_restore_signal_wide: data_len=%d, order=%u, lpq=%d",data_len,order,lp_quantization);
  94574. for(i=0;i<order;i++)
  94575. fprintf(stderr,", q[%u]=%d",i,qlp_coeff[i]);
  94576. fprintf(stderr,"\n");
  94577. #endif
  94578. FLAC__ASSERT(order > 0);
  94579. for(i = 0; i < data_len; i++) {
  94580. sum = 0;
  94581. history = data;
  94582. for(j = 0; j < order; j++)
  94583. sum += (FLAC__int64)qlp_coeff[j] * (FLAC__int64)(*(--history));
  94584. if(FLAC__bitmath_silog2_wide(sum >> lp_quantization) > 32) {
  94585. #ifdef _MSC_VER
  94586. fprintf(stderr,"FLAC__lpc_restore_signal_wide: OVERFLOW, i=%u, sum=%I64d\n", i, sum >> lp_quantization);
  94587. #else
  94588. fprintf(stderr,"FLAC__lpc_restore_signal_wide: OVERFLOW, i=%u, sum=%lld\n", i, (long long)(sum >> lp_quantization));
  94589. #endif
  94590. break;
  94591. }
  94592. if(FLAC__bitmath_silog2_wide((FLAC__int64)(*r) + (sum >> lp_quantization)) > 32) {
  94593. #ifdef _MSC_VER
  94594. 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));
  94595. #else
  94596. 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)));
  94597. #endif
  94598. break;
  94599. }
  94600. *(data++) = *(r++) + (FLAC__int32)(sum >> lp_quantization);
  94601. }
  94602. }
  94603. #else /* fully unrolled version for normal use */
  94604. {
  94605. int i;
  94606. FLAC__int64 sum;
  94607. FLAC__ASSERT(order > 0);
  94608. FLAC__ASSERT(order <= 32);
  94609. /*
  94610. * We do unique versions up to 12th order since that's the subset limit.
  94611. * Also they are roughly ordered to match frequency of occurrence to
  94612. * minimize branching.
  94613. */
  94614. if(order <= 12) {
  94615. if(order > 8) {
  94616. if(order > 10) {
  94617. if(order == 12) {
  94618. for(i = 0; i < (int)data_len; i++) {
  94619. sum = 0;
  94620. sum += qlp_coeff[11] * (FLAC__int64)data[i-12];
  94621. sum += qlp_coeff[10] * (FLAC__int64)data[i-11];
  94622. sum += qlp_coeff[9] * (FLAC__int64)data[i-10];
  94623. sum += qlp_coeff[8] * (FLAC__int64)data[i-9];
  94624. sum += qlp_coeff[7] * (FLAC__int64)data[i-8];
  94625. sum += qlp_coeff[6] * (FLAC__int64)data[i-7];
  94626. sum += qlp_coeff[5] * (FLAC__int64)data[i-6];
  94627. sum += qlp_coeff[4] * (FLAC__int64)data[i-5];
  94628. sum += qlp_coeff[3] * (FLAC__int64)data[i-4];
  94629. sum += qlp_coeff[2] * (FLAC__int64)data[i-3];
  94630. sum += qlp_coeff[1] * (FLAC__int64)data[i-2];
  94631. sum += qlp_coeff[0] * (FLAC__int64)data[i-1];
  94632. data[i] = residual[i] + (FLAC__int32)(sum >> lp_quantization);
  94633. }
  94634. }
  94635. else { /* order == 11 */
  94636. for(i = 0; i < (int)data_len; i++) {
  94637. sum = 0;
  94638. sum += qlp_coeff[10] * (FLAC__int64)data[i-11];
  94639. sum += qlp_coeff[9] * (FLAC__int64)data[i-10];
  94640. sum += qlp_coeff[8] * (FLAC__int64)data[i-9];
  94641. sum += qlp_coeff[7] * (FLAC__int64)data[i-8];
  94642. sum += qlp_coeff[6] * (FLAC__int64)data[i-7];
  94643. sum += qlp_coeff[5] * (FLAC__int64)data[i-6];
  94644. sum += qlp_coeff[4] * (FLAC__int64)data[i-5];
  94645. sum += qlp_coeff[3] * (FLAC__int64)data[i-4];
  94646. sum += qlp_coeff[2] * (FLAC__int64)data[i-3];
  94647. sum += qlp_coeff[1] * (FLAC__int64)data[i-2];
  94648. sum += qlp_coeff[0] * (FLAC__int64)data[i-1];
  94649. data[i] = residual[i] + (FLAC__int32)(sum >> lp_quantization);
  94650. }
  94651. }
  94652. }
  94653. else {
  94654. if(order == 10) {
  94655. for(i = 0; i < (int)data_len; i++) {
  94656. sum = 0;
  94657. sum += qlp_coeff[9] * (FLAC__int64)data[i-10];
  94658. sum += qlp_coeff[8] * (FLAC__int64)data[i-9];
  94659. sum += qlp_coeff[7] * (FLAC__int64)data[i-8];
  94660. sum += qlp_coeff[6] * (FLAC__int64)data[i-7];
  94661. sum += qlp_coeff[5] * (FLAC__int64)data[i-6];
  94662. sum += qlp_coeff[4] * (FLAC__int64)data[i-5];
  94663. sum += qlp_coeff[3] * (FLAC__int64)data[i-4];
  94664. sum += qlp_coeff[2] * (FLAC__int64)data[i-3];
  94665. sum += qlp_coeff[1] * (FLAC__int64)data[i-2];
  94666. sum += qlp_coeff[0] * (FLAC__int64)data[i-1];
  94667. data[i] = residual[i] + (FLAC__int32)(sum >> lp_quantization);
  94668. }
  94669. }
  94670. else { /* order == 9 */
  94671. for(i = 0; i < (int)data_len; i++) {
  94672. sum = 0;
  94673. sum += qlp_coeff[8] * (FLAC__int64)data[i-9];
  94674. sum += qlp_coeff[7] * (FLAC__int64)data[i-8];
  94675. sum += qlp_coeff[6] * (FLAC__int64)data[i-7];
  94676. sum += qlp_coeff[5] * (FLAC__int64)data[i-6];
  94677. sum += qlp_coeff[4] * (FLAC__int64)data[i-5];
  94678. sum += qlp_coeff[3] * (FLAC__int64)data[i-4];
  94679. sum += qlp_coeff[2] * (FLAC__int64)data[i-3];
  94680. sum += qlp_coeff[1] * (FLAC__int64)data[i-2];
  94681. sum += qlp_coeff[0] * (FLAC__int64)data[i-1];
  94682. data[i] = residual[i] + (FLAC__int32)(sum >> lp_quantization);
  94683. }
  94684. }
  94685. }
  94686. }
  94687. else if(order > 4) {
  94688. if(order > 6) {
  94689. if(order == 8) {
  94690. for(i = 0; i < (int)data_len; i++) {
  94691. sum = 0;
  94692. sum += qlp_coeff[7] * (FLAC__int64)data[i-8];
  94693. sum += qlp_coeff[6] * (FLAC__int64)data[i-7];
  94694. sum += qlp_coeff[5] * (FLAC__int64)data[i-6];
  94695. sum += qlp_coeff[4] * (FLAC__int64)data[i-5];
  94696. sum += qlp_coeff[3] * (FLAC__int64)data[i-4];
  94697. sum += qlp_coeff[2] * (FLAC__int64)data[i-3];
  94698. sum += qlp_coeff[1] * (FLAC__int64)data[i-2];
  94699. sum += qlp_coeff[0] * (FLAC__int64)data[i-1];
  94700. data[i] = residual[i] + (FLAC__int32)(sum >> lp_quantization);
  94701. }
  94702. }
  94703. else { /* order == 7 */
  94704. for(i = 0; i < (int)data_len; i++) {
  94705. sum = 0;
  94706. sum += qlp_coeff[6] * (FLAC__int64)data[i-7];
  94707. sum += qlp_coeff[5] * (FLAC__int64)data[i-6];
  94708. sum += qlp_coeff[4] * (FLAC__int64)data[i-5];
  94709. sum += qlp_coeff[3] * (FLAC__int64)data[i-4];
  94710. sum += qlp_coeff[2] * (FLAC__int64)data[i-3];
  94711. sum += qlp_coeff[1] * (FLAC__int64)data[i-2];
  94712. sum += qlp_coeff[0] * (FLAC__int64)data[i-1];
  94713. data[i] = residual[i] + (FLAC__int32)(sum >> lp_quantization);
  94714. }
  94715. }
  94716. }
  94717. else {
  94718. if(order == 6) {
  94719. for(i = 0; i < (int)data_len; i++) {
  94720. sum = 0;
  94721. sum += qlp_coeff[5] * (FLAC__int64)data[i-6];
  94722. sum += qlp_coeff[4] * (FLAC__int64)data[i-5];
  94723. sum += qlp_coeff[3] * (FLAC__int64)data[i-4];
  94724. sum += qlp_coeff[2] * (FLAC__int64)data[i-3];
  94725. sum += qlp_coeff[1] * (FLAC__int64)data[i-2];
  94726. sum += qlp_coeff[0] * (FLAC__int64)data[i-1];
  94727. data[i] = residual[i] + (FLAC__int32)(sum >> lp_quantization);
  94728. }
  94729. }
  94730. else { /* order == 5 */
  94731. for(i = 0; i < (int)data_len; i++) {
  94732. sum = 0;
  94733. sum += qlp_coeff[4] * (FLAC__int64)data[i-5];
  94734. sum += qlp_coeff[3] * (FLAC__int64)data[i-4];
  94735. sum += qlp_coeff[2] * (FLAC__int64)data[i-3];
  94736. sum += qlp_coeff[1] * (FLAC__int64)data[i-2];
  94737. sum += qlp_coeff[0] * (FLAC__int64)data[i-1];
  94738. data[i] = residual[i] + (FLAC__int32)(sum >> lp_quantization);
  94739. }
  94740. }
  94741. }
  94742. }
  94743. else {
  94744. if(order > 2) {
  94745. if(order == 4) {
  94746. for(i = 0; i < (int)data_len; i++) {
  94747. sum = 0;
  94748. sum += qlp_coeff[3] * (FLAC__int64)data[i-4];
  94749. sum += qlp_coeff[2] * (FLAC__int64)data[i-3];
  94750. sum += qlp_coeff[1] * (FLAC__int64)data[i-2];
  94751. sum += qlp_coeff[0] * (FLAC__int64)data[i-1];
  94752. data[i] = residual[i] + (FLAC__int32)(sum >> lp_quantization);
  94753. }
  94754. }
  94755. else { /* order == 3 */
  94756. for(i = 0; i < (int)data_len; i++) {
  94757. sum = 0;
  94758. sum += qlp_coeff[2] * (FLAC__int64)data[i-3];
  94759. sum += qlp_coeff[1] * (FLAC__int64)data[i-2];
  94760. sum += qlp_coeff[0] * (FLAC__int64)data[i-1];
  94761. data[i] = residual[i] + (FLAC__int32)(sum >> lp_quantization);
  94762. }
  94763. }
  94764. }
  94765. else {
  94766. if(order == 2) {
  94767. for(i = 0; i < (int)data_len; i++) {
  94768. sum = 0;
  94769. sum += qlp_coeff[1] * (FLAC__int64)data[i-2];
  94770. sum += qlp_coeff[0] * (FLAC__int64)data[i-1];
  94771. data[i] = residual[i] + (FLAC__int32)(sum >> lp_quantization);
  94772. }
  94773. }
  94774. else { /* order == 1 */
  94775. for(i = 0; i < (int)data_len; i++)
  94776. data[i] = residual[i] + (FLAC__int32)((qlp_coeff[0] * (FLAC__int64)data[i-1]) >> lp_quantization);
  94777. }
  94778. }
  94779. }
  94780. }
  94781. else { /* order > 12 */
  94782. for(i = 0; i < (int)data_len; i++) {
  94783. sum = 0;
  94784. switch(order) {
  94785. case 32: sum += qlp_coeff[31] * (FLAC__int64)data[i-32];
  94786. case 31: sum += qlp_coeff[30] * (FLAC__int64)data[i-31];
  94787. case 30: sum += qlp_coeff[29] * (FLAC__int64)data[i-30];
  94788. case 29: sum += qlp_coeff[28] * (FLAC__int64)data[i-29];
  94789. case 28: sum += qlp_coeff[27] * (FLAC__int64)data[i-28];
  94790. case 27: sum += qlp_coeff[26] * (FLAC__int64)data[i-27];
  94791. case 26: sum += qlp_coeff[25] * (FLAC__int64)data[i-26];
  94792. case 25: sum += qlp_coeff[24] * (FLAC__int64)data[i-25];
  94793. case 24: sum += qlp_coeff[23] * (FLAC__int64)data[i-24];
  94794. case 23: sum += qlp_coeff[22] * (FLAC__int64)data[i-23];
  94795. case 22: sum += qlp_coeff[21] * (FLAC__int64)data[i-22];
  94796. case 21: sum += qlp_coeff[20] * (FLAC__int64)data[i-21];
  94797. case 20: sum += qlp_coeff[19] * (FLAC__int64)data[i-20];
  94798. case 19: sum += qlp_coeff[18] * (FLAC__int64)data[i-19];
  94799. case 18: sum += qlp_coeff[17] * (FLAC__int64)data[i-18];
  94800. case 17: sum += qlp_coeff[16] * (FLAC__int64)data[i-17];
  94801. case 16: sum += qlp_coeff[15] * (FLAC__int64)data[i-16];
  94802. case 15: sum += qlp_coeff[14] * (FLAC__int64)data[i-15];
  94803. case 14: sum += qlp_coeff[13] * (FLAC__int64)data[i-14];
  94804. case 13: sum += qlp_coeff[12] * (FLAC__int64)data[i-13];
  94805. sum += qlp_coeff[11] * (FLAC__int64)data[i-12];
  94806. sum += qlp_coeff[10] * (FLAC__int64)data[i-11];
  94807. sum += qlp_coeff[ 9] * (FLAC__int64)data[i-10];
  94808. sum += qlp_coeff[ 8] * (FLAC__int64)data[i- 9];
  94809. sum += qlp_coeff[ 7] * (FLAC__int64)data[i- 8];
  94810. sum += qlp_coeff[ 6] * (FLAC__int64)data[i- 7];
  94811. sum += qlp_coeff[ 5] * (FLAC__int64)data[i- 6];
  94812. sum += qlp_coeff[ 4] * (FLAC__int64)data[i- 5];
  94813. sum += qlp_coeff[ 3] * (FLAC__int64)data[i- 4];
  94814. sum += qlp_coeff[ 2] * (FLAC__int64)data[i- 3];
  94815. sum += qlp_coeff[ 1] * (FLAC__int64)data[i- 2];
  94816. sum += qlp_coeff[ 0] * (FLAC__int64)data[i- 1];
  94817. }
  94818. data[i] = residual[i] + (FLAC__int32)(sum >> lp_quantization);
  94819. }
  94820. }
  94821. }
  94822. #endif
  94823. #ifndef FLAC__INTEGER_ONLY_LIBRARY
  94824. FLAC__double FLAC__lpc_compute_expected_bits_per_residual_sample(FLAC__double lpc_error, unsigned total_samples)
  94825. {
  94826. FLAC__double error_scale;
  94827. FLAC__ASSERT(total_samples > 0);
  94828. error_scale = 0.5 * M_LN2 * M_LN2 / (FLAC__double)total_samples;
  94829. return FLAC__lpc_compute_expected_bits_per_residual_sample_with_error_scale(lpc_error, error_scale);
  94830. }
  94831. FLAC__double FLAC__lpc_compute_expected_bits_per_residual_sample_with_error_scale(FLAC__double lpc_error, FLAC__double error_scale)
  94832. {
  94833. if(lpc_error > 0.0) {
  94834. FLAC__double bps = (FLAC__double)0.5 * log(error_scale * lpc_error) / M_LN2;
  94835. if(bps >= 0.0)
  94836. return bps;
  94837. else
  94838. return 0.0;
  94839. }
  94840. else if(lpc_error < 0.0) { /* error should not be negative but can happen due to inadequate floating-point resolution */
  94841. return 1e32;
  94842. }
  94843. else {
  94844. return 0.0;
  94845. }
  94846. }
  94847. unsigned FLAC__lpc_compute_best_order(const FLAC__double lpc_error[], unsigned max_order, unsigned total_samples, unsigned overhead_bits_per_order)
  94848. {
  94849. 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 */
  94850. FLAC__double bits, best_bits, error_scale;
  94851. FLAC__ASSERT(max_order > 0);
  94852. FLAC__ASSERT(total_samples > 0);
  94853. error_scale = 0.5 * M_LN2 * M_LN2 / (FLAC__double)total_samples;
  94854. best_index = 0;
  94855. best_bits = (unsigned)(-1);
  94856. for(index = 0, order = 1; index < max_order; index++, order++) {
  94857. 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);
  94858. if(bits < best_bits) {
  94859. best_index = index;
  94860. best_bits = bits;
  94861. }
  94862. }
  94863. return best_index+1; /* +1 since index of lpc_error[] is order-1 */
  94864. }
  94865. #endif /* !defined FLAC__INTEGER_ONLY_LIBRARY */
  94866. #endif
  94867. /*** End of inlined file: lpc_flac.c ***/
  94868. /*** Start of inlined file: md5.c ***/
  94869. /*** Start of inlined file: juce_FlacHeader.h ***/
  94870. // This file is included at the start of each FLAC .c file, just to do a few housekeeping
  94871. // tasks..
  94872. #define VERSION "1.2.1"
  94873. #define FLAC__NO_DLL 1
  94874. #if JUCE_MSVC
  94875. #pragma warning (disable: 4267 4127 4244 4996 4100 4701 4702 4013 4133 4206 4312)
  94876. #endif
  94877. #if JUCE_MAC
  94878. #define FLAC__SYS_DARWIN 1
  94879. #endif
  94880. /*** End of inlined file: juce_FlacHeader.h ***/
  94881. #if JUCE_USE_FLAC
  94882. #if HAVE_CONFIG_H
  94883. # include <config.h>
  94884. #endif
  94885. #include <stdlib.h> /* for malloc() */
  94886. #include <string.h> /* for memcpy() */
  94887. /*** Start of inlined file: md5.h ***/
  94888. #ifndef FLAC__PRIVATE__MD5_H
  94889. #define FLAC__PRIVATE__MD5_H
  94890. /*
  94891. * This is the header file for the MD5 message-digest algorithm.
  94892. * The algorithm is due to Ron Rivest. This code was
  94893. * written by Colin Plumb in 1993, no copyright is claimed.
  94894. * This code is in the public domain; do with it what you wish.
  94895. *
  94896. * Equivalent code is available from RSA Data Security, Inc.
  94897. * This code has been tested against that, and is equivalent,
  94898. * except that you don't need to include two pages of legalese
  94899. * with every copy.
  94900. *
  94901. * To compute the message digest of a chunk of bytes, declare an
  94902. * MD5Context structure, pass it to MD5Init, call MD5Update as
  94903. * needed on buffers full of bytes, and then call MD5Final, which
  94904. * will fill a supplied 16-byte array with the digest.
  94905. *
  94906. * Changed so as no longer to depend on Colin Plumb's `usual.h'
  94907. * header definitions; now uses stuff from dpkg's config.h
  94908. * - Ian Jackson <ijackson@nyx.cs.du.edu>.
  94909. * Still in the public domain.
  94910. *
  94911. * Josh Coalson: made some changes to integrate with libFLAC.
  94912. * Still in the public domain, with no warranty.
  94913. */
  94914. typedef struct {
  94915. FLAC__uint32 in[16];
  94916. FLAC__uint32 buf[4];
  94917. FLAC__uint32 bytes[2];
  94918. FLAC__byte *internal_buf;
  94919. size_t capacity;
  94920. } FLAC__MD5Context;
  94921. void FLAC__MD5Init(FLAC__MD5Context *context);
  94922. void FLAC__MD5Final(FLAC__byte digest[16], FLAC__MD5Context *context);
  94923. FLAC__bool FLAC__MD5Accumulate(FLAC__MD5Context *ctx, const FLAC__int32 * const signal[], unsigned channels, unsigned samples, unsigned bytes_per_sample);
  94924. #endif
  94925. /*** End of inlined file: md5.h ***/
  94926. #ifndef FLaC__INLINE
  94927. #define FLaC__INLINE
  94928. #endif
  94929. /*
  94930. * This code implements the MD5 message-digest algorithm.
  94931. * The algorithm is due to Ron Rivest. This code was
  94932. * written by Colin Plumb in 1993, no copyright is claimed.
  94933. * This code is in the public domain; do with it what you wish.
  94934. *
  94935. * Equivalent code is available from RSA Data Security, Inc.
  94936. * This code has been tested against that, and is equivalent,
  94937. * except that you don't need to include two pages of legalese
  94938. * with every copy.
  94939. *
  94940. * To compute the message digest of a chunk of bytes, declare an
  94941. * MD5Context structure, pass it to MD5Init, call MD5Update as
  94942. * needed on buffers full of bytes, and then call MD5Final, which
  94943. * will fill a supplied 16-byte array with the digest.
  94944. *
  94945. * Changed so as no longer to depend on Colin Plumb's `usual.h' header
  94946. * definitions; now uses stuff from dpkg's config.h.
  94947. * - Ian Jackson <ijackson@nyx.cs.du.edu>.
  94948. * Still in the public domain.
  94949. *
  94950. * Josh Coalson: made some changes to integrate with libFLAC.
  94951. * Still in the public domain.
  94952. */
  94953. /* The four core functions - F1 is optimized somewhat */
  94954. /* #define F1(x, y, z) (x & y | ~x & z) */
  94955. #define F1(x, y, z) (z ^ (x & (y ^ z)))
  94956. #define F2(x, y, z) F1(z, x, y)
  94957. #define F3(x, y, z) (x ^ y ^ z)
  94958. #define F4(x, y, z) (y ^ (x | ~z))
  94959. /* This is the central step in the MD5 algorithm. */
  94960. #define MD5STEP(f,w,x,y,z,in,s) \
  94961. (w += f(x,y,z) + in, w = (w<<s | w>>(32-s)) + x)
  94962. /*
  94963. * The core of the MD5 algorithm, this alters an existing MD5 hash to
  94964. * reflect the addition of 16 longwords of new data. MD5Update blocks
  94965. * the data and converts bytes into longwords for this routine.
  94966. */
  94967. static void FLAC__MD5Transform(FLAC__uint32 buf[4], FLAC__uint32 const in[16])
  94968. {
  94969. register FLAC__uint32 a, b, c, d;
  94970. a = buf[0];
  94971. b = buf[1];
  94972. c = buf[2];
  94973. d = buf[3];
  94974. MD5STEP(F1, a, b, c, d, in[0] + 0xd76aa478, 7);
  94975. MD5STEP(F1, d, a, b, c, in[1] + 0xe8c7b756, 12);
  94976. MD5STEP(F1, c, d, a, b, in[2] + 0x242070db, 17);
  94977. MD5STEP(F1, b, c, d, a, in[3] + 0xc1bdceee, 22);
  94978. MD5STEP(F1, a, b, c, d, in[4] + 0xf57c0faf, 7);
  94979. MD5STEP(F1, d, a, b, c, in[5] + 0x4787c62a, 12);
  94980. MD5STEP(F1, c, d, a, b, in[6] + 0xa8304613, 17);
  94981. MD5STEP(F1, b, c, d, a, in[7] + 0xfd469501, 22);
  94982. MD5STEP(F1, a, b, c, d, in[8] + 0x698098d8, 7);
  94983. MD5STEP(F1, d, a, b, c, in[9] + 0x8b44f7af, 12);
  94984. MD5STEP(F1, c, d, a, b, in[10] + 0xffff5bb1, 17);
  94985. MD5STEP(F1, b, c, d, a, in[11] + 0x895cd7be, 22);
  94986. MD5STEP(F1, a, b, c, d, in[12] + 0x6b901122, 7);
  94987. MD5STEP(F1, d, a, b, c, in[13] + 0xfd987193, 12);
  94988. MD5STEP(F1, c, d, a, b, in[14] + 0xa679438e, 17);
  94989. MD5STEP(F1, b, c, d, a, in[15] + 0x49b40821, 22);
  94990. MD5STEP(F2, a, b, c, d, in[1] + 0xf61e2562, 5);
  94991. MD5STEP(F2, d, a, b, c, in[6] + 0xc040b340, 9);
  94992. MD5STEP(F2, c, d, a, b, in[11] + 0x265e5a51, 14);
  94993. MD5STEP(F2, b, c, d, a, in[0] + 0xe9b6c7aa, 20);
  94994. MD5STEP(F2, a, b, c, d, in[5] + 0xd62f105d, 5);
  94995. MD5STEP(F2, d, a, b, c, in[10] + 0x02441453, 9);
  94996. MD5STEP(F2, c, d, a, b, in[15] + 0xd8a1e681, 14);
  94997. MD5STEP(F2, b, c, d, a, in[4] + 0xe7d3fbc8, 20);
  94998. MD5STEP(F2, a, b, c, d, in[9] + 0x21e1cde6, 5);
  94999. MD5STEP(F2, d, a, b, c, in[14] + 0xc33707d6, 9);
  95000. MD5STEP(F2, c, d, a, b, in[3] + 0xf4d50d87, 14);
  95001. MD5STEP(F2, b, c, d, a, in[8] + 0x455a14ed, 20);
  95002. MD5STEP(F2, a, b, c, d, in[13] + 0xa9e3e905, 5);
  95003. MD5STEP(F2, d, a, b, c, in[2] + 0xfcefa3f8, 9);
  95004. MD5STEP(F2, c, d, a, b, in[7] + 0x676f02d9, 14);
  95005. MD5STEP(F2, b, c, d, a, in[12] + 0x8d2a4c8a, 20);
  95006. MD5STEP(F3, a, b, c, d, in[5] + 0xfffa3942, 4);
  95007. MD5STEP(F3, d, a, b, c, in[8] + 0x8771f681, 11);
  95008. MD5STEP(F3, c, d, a, b, in[11] + 0x6d9d6122, 16);
  95009. MD5STEP(F3, b, c, d, a, in[14] + 0xfde5380c, 23);
  95010. MD5STEP(F3, a, b, c, d, in[1] + 0xa4beea44, 4);
  95011. MD5STEP(F3, d, a, b, c, in[4] + 0x4bdecfa9, 11);
  95012. MD5STEP(F3, c, d, a, b, in[7] + 0xf6bb4b60, 16);
  95013. MD5STEP(F3, b, c, d, a, in[10] + 0xbebfbc70, 23);
  95014. MD5STEP(F3, a, b, c, d, in[13] + 0x289b7ec6, 4);
  95015. MD5STEP(F3, d, a, b, c, in[0] + 0xeaa127fa, 11);
  95016. MD5STEP(F3, c, d, a, b, in[3] + 0xd4ef3085, 16);
  95017. MD5STEP(F3, b, c, d, a, in[6] + 0x04881d05, 23);
  95018. MD5STEP(F3, a, b, c, d, in[9] + 0xd9d4d039, 4);
  95019. MD5STEP(F3, d, a, b, c, in[12] + 0xe6db99e5, 11);
  95020. MD5STEP(F3, c, d, a, b, in[15] + 0x1fa27cf8, 16);
  95021. MD5STEP(F3, b, c, d, a, in[2] + 0xc4ac5665, 23);
  95022. MD5STEP(F4, a, b, c, d, in[0] + 0xf4292244, 6);
  95023. MD5STEP(F4, d, a, b, c, in[7] + 0x432aff97, 10);
  95024. MD5STEP(F4, c, d, a, b, in[14] + 0xab9423a7, 15);
  95025. MD5STEP(F4, b, c, d, a, in[5] + 0xfc93a039, 21);
  95026. MD5STEP(F4, a, b, c, d, in[12] + 0x655b59c3, 6);
  95027. MD5STEP(F4, d, a, b, c, in[3] + 0x8f0ccc92, 10);
  95028. MD5STEP(F4, c, d, a, b, in[10] + 0xffeff47d, 15);
  95029. MD5STEP(F4, b, c, d, a, in[1] + 0x85845dd1, 21);
  95030. MD5STEP(F4, a, b, c, d, in[8] + 0x6fa87e4f, 6);
  95031. MD5STEP(F4, d, a, b, c, in[15] + 0xfe2ce6e0, 10);
  95032. MD5STEP(F4, c, d, a, b, in[6] + 0xa3014314, 15);
  95033. MD5STEP(F4, b, c, d, a, in[13] + 0x4e0811a1, 21);
  95034. MD5STEP(F4, a, b, c, d, in[4] + 0xf7537e82, 6);
  95035. MD5STEP(F4, d, a, b, c, in[11] + 0xbd3af235, 10);
  95036. MD5STEP(F4, c, d, a, b, in[2] + 0x2ad7d2bb, 15);
  95037. MD5STEP(F4, b, c, d, a, in[9] + 0xeb86d391, 21);
  95038. buf[0] += a;
  95039. buf[1] += b;
  95040. buf[2] += c;
  95041. buf[3] += d;
  95042. }
  95043. #if WORDS_BIGENDIAN
  95044. //@@@@@@ OPT: use bswap/intrinsics
  95045. static void byteSwap(FLAC__uint32 *buf, unsigned words)
  95046. {
  95047. register FLAC__uint32 x;
  95048. do {
  95049. x = *buf;
  95050. x = ((x << 8) & 0xff00ff00) | ((x >> 8) & 0x00ff00ff);
  95051. *buf++ = (x >> 16) | (x << 16);
  95052. } while (--words);
  95053. }
  95054. static void byteSwapX16(FLAC__uint32 *buf)
  95055. {
  95056. register FLAC__uint32 x;
  95057. x = *buf; x = ((x << 8) & 0xff00ff00) | ((x >> 8) & 0x00ff00ff); *buf++ = (x >> 16) | (x << 16);
  95058. x = *buf; x = ((x << 8) & 0xff00ff00) | ((x >> 8) & 0x00ff00ff); *buf++ = (x >> 16) | (x << 16);
  95059. x = *buf; x = ((x << 8) & 0xff00ff00) | ((x >> 8) & 0x00ff00ff); *buf++ = (x >> 16) | (x << 16);
  95060. x = *buf; x = ((x << 8) & 0xff00ff00) | ((x >> 8) & 0x00ff00ff); *buf++ = (x >> 16) | (x << 16);
  95061. x = *buf; x = ((x << 8) & 0xff00ff00) | ((x >> 8) & 0x00ff00ff); *buf++ = (x >> 16) | (x << 16);
  95062. x = *buf; x = ((x << 8) & 0xff00ff00) | ((x >> 8) & 0x00ff00ff); *buf++ = (x >> 16) | (x << 16);
  95063. x = *buf; x = ((x << 8) & 0xff00ff00) | ((x >> 8) & 0x00ff00ff); *buf++ = (x >> 16) | (x << 16);
  95064. x = *buf; x = ((x << 8) & 0xff00ff00) | ((x >> 8) & 0x00ff00ff); *buf++ = (x >> 16) | (x << 16);
  95065. x = *buf; x = ((x << 8) & 0xff00ff00) | ((x >> 8) & 0x00ff00ff); *buf++ = (x >> 16) | (x << 16);
  95066. x = *buf; x = ((x << 8) & 0xff00ff00) | ((x >> 8) & 0x00ff00ff); *buf++ = (x >> 16) | (x << 16);
  95067. x = *buf; x = ((x << 8) & 0xff00ff00) | ((x >> 8) & 0x00ff00ff); *buf++ = (x >> 16) | (x << 16);
  95068. x = *buf; x = ((x << 8) & 0xff00ff00) | ((x >> 8) & 0x00ff00ff); *buf++ = (x >> 16) | (x << 16);
  95069. x = *buf; x = ((x << 8) & 0xff00ff00) | ((x >> 8) & 0x00ff00ff); *buf++ = (x >> 16) | (x << 16);
  95070. x = *buf; x = ((x << 8) & 0xff00ff00) | ((x >> 8) & 0x00ff00ff); *buf++ = (x >> 16) | (x << 16);
  95071. x = *buf; x = ((x << 8) & 0xff00ff00) | ((x >> 8) & 0x00ff00ff); *buf++ = (x >> 16) | (x << 16);
  95072. x = *buf; x = ((x << 8) & 0xff00ff00) | ((x >> 8) & 0x00ff00ff); *buf = (x >> 16) | (x << 16);
  95073. }
  95074. #else
  95075. #define byteSwap(buf, words)
  95076. #define byteSwapX16(buf)
  95077. #endif
  95078. /*
  95079. * Update context to reflect the concatenation of another buffer full
  95080. * of bytes.
  95081. */
  95082. static void FLAC__MD5Update(FLAC__MD5Context *ctx, FLAC__byte const *buf, unsigned len)
  95083. {
  95084. FLAC__uint32 t;
  95085. /* Update byte count */
  95086. t = ctx->bytes[0];
  95087. if ((ctx->bytes[0] = t + len) < t)
  95088. ctx->bytes[1]++; /* Carry from low to high */
  95089. t = 64 - (t & 0x3f); /* Space available in ctx->in (at least 1) */
  95090. if (t > len) {
  95091. memcpy((FLAC__byte *)ctx->in + 64 - t, buf, len);
  95092. return;
  95093. }
  95094. /* First chunk is an odd size */
  95095. memcpy((FLAC__byte *)ctx->in + 64 - t, buf, t);
  95096. byteSwapX16(ctx->in);
  95097. FLAC__MD5Transform(ctx->buf, ctx->in);
  95098. buf += t;
  95099. len -= t;
  95100. /* Process data in 64-byte chunks */
  95101. while (len >= 64) {
  95102. memcpy(ctx->in, buf, 64);
  95103. byteSwapX16(ctx->in);
  95104. FLAC__MD5Transform(ctx->buf, ctx->in);
  95105. buf += 64;
  95106. len -= 64;
  95107. }
  95108. /* Handle any remaining bytes of data. */
  95109. memcpy(ctx->in, buf, len);
  95110. }
  95111. /*
  95112. * Start MD5 accumulation. Set bit count to 0 and buffer to mysterious
  95113. * initialization constants.
  95114. */
  95115. void FLAC__MD5Init(FLAC__MD5Context *ctx)
  95116. {
  95117. ctx->buf[0] = 0x67452301;
  95118. ctx->buf[1] = 0xefcdab89;
  95119. ctx->buf[2] = 0x98badcfe;
  95120. ctx->buf[3] = 0x10325476;
  95121. ctx->bytes[0] = 0;
  95122. ctx->bytes[1] = 0;
  95123. ctx->internal_buf = 0;
  95124. ctx->capacity = 0;
  95125. }
  95126. /*
  95127. * Final wrapup - pad to 64-byte boundary with the bit pattern
  95128. * 1 0* (64-bit count of bits processed, MSB-first)
  95129. */
  95130. void FLAC__MD5Final(FLAC__byte digest[16], FLAC__MD5Context *ctx)
  95131. {
  95132. int count = ctx->bytes[0] & 0x3f; /* Number of bytes in ctx->in */
  95133. FLAC__byte *p = (FLAC__byte *)ctx->in + count;
  95134. /* Set the first char of padding to 0x80. There is always room. */
  95135. *p++ = 0x80;
  95136. /* Bytes of padding needed to make 56 bytes (-8..55) */
  95137. count = 56 - 1 - count;
  95138. if (count < 0) { /* Padding forces an extra block */
  95139. memset(p, 0, count + 8);
  95140. byteSwapX16(ctx->in);
  95141. FLAC__MD5Transform(ctx->buf, ctx->in);
  95142. p = (FLAC__byte *)ctx->in;
  95143. count = 56;
  95144. }
  95145. memset(p, 0, count);
  95146. byteSwap(ctx->in, 14);
  95147. /* Append length in bits and transform */
  95148. ctx->in[14] = ctx->bytes[0] << 3;
  95149. ctx->in[15] = ctx->bytes[1] << 3 | ctx->bytes[0] >> 29;
  95150. FLAC__MD5Transform(ctx->buf, ctx->in);
  95151. byteSwap(ctx->buf, 4);
  95152. memcpy(digest, ctx->buf, 16);
  95153. memset(ctx, 0, sizeof(ctx)); /* In case it's sensitive */
  95154. if(0 != ctx->internal_buf) {
  95155. free(ctx->internal_buf);
  95156. ctx->internal_buf = 0;
  95157. ctx->capacity = 0;
  95158. }
  95159. }
  95160. /*
  95161. * Convert the incoming audio signal to a byte stream
  95162. */
  95163. static void format_input_(FLAC__byte *buf, const FLAC__int32 * const signal[], unsigned channels, unsigned samples, unsigned bytes_per_sample)
  95164. {
  95165. unsigned channel, sample;
  95166. register FLAC__int32 a_word;
  95167. register FLAC__byte *buf_ = buf;
  95168. #if WORDS_BIGENDIAN
  95169. #else
  95170. if(channels == 2 && bytes_per_sample == 2) {
  95171. FLAC__int16 *buf1_ = ((FLAC__int16*)buf_) + 1;
  95172. memcpy(buf_, signal[0], sizeof(FLAC__int32) * samples);
  95173. for(sample = 0; sample < samples; sample++, buf1_+=2)
  95174. *buf1_ = (FLAC__int16)signal[1][sample];
  95175. }
  95176. else if(channels == 1 && bytes_per_sample == 2) {
  95177. FLAC__int16 *buf1_ = (FLAC__int16*)buf_;
  95178. for(sample = 0; sample < samples; sample++)
  95179. *buf1_++ = (FLAC__int16)signal[0][sample];
  95180. }
  95181. else
  95182. #endif
  95183. if(bytes_per_sample == 2) {
  95184. if(channels == 2) {
  95185. for(sample = 0; sample < samples; sample++) {
  95186. a_word = signal[0][sample];
  95187. *buf_++ = (FLAC__byte)a_word; a_word >>= 8;
  95188. *buf_++ = (FLAC__byte)a_word;
  95189. a_word = signal[1][sample];
  95190. *buf_++ = (FLAC__byte)a_word; a_word >>= 8;
  95191. *buf_++ = (FLAC__byte)a_word;
  95192. }
  95193. }
  95194. else if(channels == 1) {
  95195. for(sample = 0; sample < samples; sample++) {
  95196. a_word = signal[0][sample];
  95197. *buf_++ = (FLAC__byte)a_word; a_word >>= 8;
  95198. *buf_++ = (FLAC__byte)a_word;
  95199. }
  95200. }
  95201. else {
  95202. for(sample = 0; sample < samples; sample++) {
  95203. for(channel = 0; channel < channels; channel++) {
  95204. a_word = signal[channel][sample];
  95205. *buf_++ = (FLAC__byte)a_word; a_word >>= 8;
  95206. *buf_++ = (FLAC__byte)a_word;
  95207. }
  95208. }
  95209. }
  95210. }
  95211. else if(bytes_per_sample == 3) {
  95212. if(channels == 2) {
  95213. for(sample = 0; sample < samples; sample++) {
  95214. a_word = signal[0][sample];
  95215. *buf_++ = (FLAC__byte)a_word; a_word >>= 8;
  95216. *buf_++ = (FLAC__byte)a_word; a_word >>= 8;
  95217. *buf_++ = (FLAC__byte)a_word;
  95218. a_word = signal[1][sample];
  95219. *buf_++ = (FLAC__byte)a_word; a_word >>= 8;
  95220. *buf_++ = (FLAC__byte)a_word; a_word >>= 8;
  95221. *buf_++ = (FLAC__byte)a_word;
  95222. }
  95223. }
  95224. else if(channels == 1) {
  95225. for(sample = 0; sample < samples; sample++) {
  95226. a_word = signal[0][sample];
  95227. *buf_++ = (FLAC__byte)a_word; a_word >>= 8;
  95228. *buf_++ = (FLAC__byte)a_word; a_word >>= 8;
  95229. *buf_++ = (FLAC__byte)a_word;
  95230. }
  95231. }
  95232. else {
  95233. for(sample = 0; sample < samples; sample++) {
  95234. for(channel = 0; channel < channels; channel++) {
  95235. a_word = signal[channel][sample];
  95236. *buf_++ = (FLAC__byte)a_word; a_word >>= 8;
  95237. *buf_++ = (FLAC__byte)a_word; a_word >>= 8;
  95238. *buf_++ = (FLAC__byte)a_word;
  95239. }
  95240. }
  95241. }
  95242. }
  95243. else if(bytes_per_sample == 1) {
  95244. if(channels == 2) {
  95245. for(sample = 0; sample < samples; sample++) {
  95246. a_word = signal[0][sample];
  95247. *buf_++ = (FLAC__byte)a_word;
  95248. a_word = signal[1][sample];
  95249. *buf_++ = (FLAC__byte)a_word;
  95250. }
  95251. }
  95252. else if(channels == 1) {
  95253. for(sample = 0; sample < samples; sample++) {
  95254. a_word = signal[0][sample];
  95255. *buf_++ = (FLAC__byte)a_word;
  95256. }
  95257. }
  95258. else {
  95259. for(sample = 0; sample < samples; sample++) {
  95260. for(channel = 0; channel < channels; channel++) {
  95261. a_word = signal[channel][sample];
  95262. *buf_++ = (FLAC__byte)a_word;
  95263. }
  95264. }
  95265. }
  95266. }
  95267. else { /* bytes_per_sample == 4, maybe optimize more later */
  95268. for(sample = 0; sample < samples; sample++) {
  95269. for(channel = 0; channel < channels; channel++) {
  95270. a_word = signal[channel][sample];
  95271. *buf_++ = (FLAC__byte)a_word; a_word >>= 8;
  95272. *buf_++ = (FLAC__byte)a_word; a_word >>= 8;
  95273. *buf_++ = (FLAC__byte)a_word; a_word >>= 8;
  95274. *buf_++ = (FLAC__byte)a_word;
  95275. }
  95276. }
  95277. }
  95278. }
  95279. /*
  95280. * Convert the incoming audio signal to a byte stream and FLAC__MD5Update it.
  95281. */
  95282. FLAC__bool FLAC__MD5Accumulate(FLAC__MD5Context *ctx, const FLAC__int32 * const signal[], unsigned channels, unsigned samples, unsigned bytes_per_sample)
  95283. {
  95284. const size_t bytes_needed = (size_t)channels * (size_t)samples * (size_t)bytes_per_sample;
  95285. /* overflow check */
  95286. if((size_t)channels > SIZE_MAX / (size_t)bytes_per_sample)
  95287. return false;
  95288. if((size_t)channels * (size_t)bytes_per_sample > SIZE_MAX / (size_t)samples)
  95289. return false;
  95290. if(ctx->capacity < bytes_needed) {
  95291. FLAC__byte *tmp = (FLAC__byte*)realloc(ctx->internal_buf, bytes_needed);
  95292. if(0 == tmp) {
  95293. free(ctx->internal_buf);
  95294. if(0 == (ctx->internal_buf = (FLAC__byte*)safe_malloc_(bytes_needed)))
  95295. return false;
  95296. }
  95297. ctx->internal_buf = tmp;
  95298. ctx->capacity = bytes_needed;
  95299. }
  95300. format_input_(ctx->internal_buf, signal, channels, samples, bytes_per_sample);
  95301. FLAC__MD5Update(ctx, ctx->internal_buf, bytes_needed);
  95302. return true;
  95303. }
  95304. #endif
  95305. /*** End of inlined file: md5.c ***/
  95306. /*** Start of inlined file: memory.c ***/
  95307. /*** Start of inlined file: juce_FlacHeader.h ***/
  95308. // This file is included at the start of each FLAC .c file, just to do a few housekeeping
  95309. // tasks..
  95310. #define VERSION "1.2.1"
  95311. #define FLAC__NO_DLL 1
  95312. #if JUCE_MSVC
  95313. #pragma warning (disable: 4267 4127 4244 4996 4100 4701 4702 4013 4133 4206 4312)
  95314. #endif
  95315. #if JUCE_MAC
  95316. #define FLAC__SYS_DARWIN 1
  95317. #endif
  95318. /*** End of inlined file: juce_FlacHeader.h ***/
  95319. #if JUCE_USE_FLAC
  95320. #if HAVE_CONFIG_H
  95321. # include <config.h>
  95322. #endif
  95323. /*** Start of inlined file: memory.h ***/
  95324. #ifndef FLAC__PRIVATE__MEMORY_H
  95325. #define FLAC__PRIVATE__MEMORY_H
  95326. #ifdef HAVE_CONFIG_H
  95327. #include <config.h>
  95328. #endif
  95329. #include <stdlib.h> /* for size_t */
  95330. /* Returns the unaligned address returned by malloc.
  95331. * Use free() on this address to deallocate.
  95332. */
  95333. void *FLAC__memory_alloc_aligned(size_t bytes, void **aligned_address);
  95334. FLAC__bool FLAC__memory_alloc_aligned_int32_array(unsigned elements, FLAC__int32 **unaligned_pointer, FLAC__int32 **aligned_pointer);
  95335. FLAC__bool FLAC__memory_alloc_aligned_uint32_array(unsigned elements, FLAC__uint32 **unaligned_pointer, FLAC__uint32 **aligned_pointer);
  95336. FLAC__bool FLAC__memory_alloc_aligned_uint64_array(unsigned elements, FLAC__uint64 **unaligned_pointer, FLAC__uint64 **aligned_pointer);
  95337. FLAC__bool FLAC__memory_alloc_aligned_unsigned_array(unsigned elements, unsigned **unaligned_pointer, unsigned **aligned_pointer);
  95338. #ifndef FLAC__INTEGER_ONLY_LIBRARY
  95339. FLAC__bool FLAC__memory_alloc_aligned_real_array(unsigned elements, FLAC__real **unaligned_pointer, FLAC__real **aligned_pointer);
  95340. #endif
  95341. #endif
  95342. /*** End of inlined file: memory.h ***/
  95343. void *FLAC__memory_alloc_aligned(size_t bytes, void **aligned_address)
  95344. {
  95345. void *x;
  95346. FLAC__ASSERT(0 != aligned_address);
  95347. #ifdef FLAC__ALIGN_MALLOC_DATA
  95348. /* align on 32-byte (256-bit) boundary */
  95349. x = safe_malloc_add_2op_(bytes, /*+*/31);
  95350. #ifdef SIZEOF_VOIDP
  95351. #if SIZEOF_VOIDP == 4
  95352. /* could do *aligned_address = x + ((unsigned) (32 - (((unsigned)x) & 31))) & 31; */
  95353. *aligned_address = (void*)(((unsigned)x + 31) & -32);
  95354. #elif SIZEOF_VOIDP == 8
  95355. *aligned_address = (void*)(((FLAC__uint64)x + 31) & (FLAC__uint64)(-((FLAC__int64)32)));
  95356. #else
  95357. # error Unsupported sizeof(void*)
  95358. #endif
  95359. #else
  95360. /* there's got to be a better way to do this right for all archs */
  95361. if(sizeof(void*) == sizeof(unsigned))
  95362. *aligned_address = (void*)(((unsigned)x + 31) & -32);
  95363. else if(sizeof(void*) == sizeof(FLAC__uint64))
  95364. *aligned_address = (void*)(((FLAC__uint64)x + 31) & (FLAC__uint64)(-((FLAC__int64)32)));
  95365. else
  95366. return 0;
  95367. #endif
  95368. #else
  95369. x = safe_malloc_(bytes);
  95370. *aligned_address = x;
  95371. #endif
  95372. return x;
  95373. }
  95374. FLAC__bool FLAC__memory_alloc_aligned_int32_array(unsigned elements, FLAC__int32 **unaligned_pointer, FLAC__int32 **aligned_pointer)
  95375. {
  95376. FLAC__int32 *pu; /* unaligned pointer */
  95377. union { /* union needed to comply with C99 pointer aliasing rules */
  95378. FLAC__int32 *pa; /* aligned pointer */
  95379. void *pv; /* aligned pointer alias */
  95380. } u;
  95381. FLAC__ASSERT(elements > 0);
  95382. FLAC__ASSERT(0 != unaligned_pointer);
  95383. FLAC__ASSERT(0 != aligned_pointer);
  95384. FLAC__ASSERT(unaligned_pointer != aligned_pointer);
  95385. pu = (FLAC__int32*)FLAC__memory_alloc_aligned(sizeof(*pu) * (size_t)elements, &u.pv);
  95386. if(0 == pu) {
  95387. return false;
  95388. }
  95389. else {
  95390. if(*unaligned_pointer != 0)
  95391. free(*unaligned_pointer);
  95392. *unaligned_pointer = pu;
  95393. *aligned_pointer = u.pa;
  95394. return true;
  95395. }
  95396. }
  95397. FLAC__bool FLAC__memory_alloc_aligned_uint32_array(unsigned elements, FLAC__uint32 **unaligned_pointer, FLAC__uint32 **aligned_pointer)
  95398. {
  95399. FLAC__uint32 *pu; /* unaligned pointer */
  95400. union { /* union needed to comply with C99 pointer aliasing rules */
  95401. FLAC__uint32 *pa; /* aligned pointer */
  95402. void *pv; /* aligned pointer alias */
  95403. } u;
  95404. FLAC__ASSERT(elements > 0);
  95405. FLAC__ASSERT(0 != unaligned_pointer);
  95406. FLAC__ASSERT(0 != aligned_pointer);
  95407. FLAC__ASSERT(unaligned_pointer != aligned_pointer);
  95408. pu = (FLAC__uint32*)FLAC__memory_alloc_aligned(sizeof(*pu) * elements, &u.pv);
  95409. if(0 == pu) {
  95410. return false;
  95411. }
  95412. else {
  95413. if(*unaligned_pointer != 0)
  95414. free(*unaligned_pointer);
  95415. *unaligned_pointer = pu;
  95416. *aligned_pointer = u.pa;
  95417. return true;
  95418. }
  95419. }
  95420. FLAC__bool FLAC__memory_alloc_aligned_uint64_array(unsigned elements, FLAC__uint64 **unaligned_pointer, FLAC__uint64 **aligned_pointer)
  95421. {
  95422. FLAC__uint64 *pu; /* unaligned pointer */
  95423. union { /* union needed to comply with C99 pointer aliasing rules */
  95424. FLAC__uint64 *pa; /* aligned pointer */
  95425. void *pv; /* aligned pointer alias */
  95426. } u;
  95427. FLAC__ASSERT(elements > 0);
  95428. FLAC__ASSERT(0 != unaligned_pointer);
  95429. FLAC__ASSERT(0 != aligned_pointer);
  95430. FLAC__ASSERT(unaligned_pointer != aligned_pointer);
  95431. pu = (FLAC__uint64*)FLAC__memory_alloc_aligned(sizeof(*pu) * elements, &u.pv);
  95432. if(0 == pu) {
  95433. return false;
  95434. }
  95435. else {
  95436. if(*unaligned_pointer != 0)
  95437. free(*unaligned_pointer);
  95438. *unaligned_pointer = pu;
  95439. *aligned_pointer = u.pa;
  95440. return true;
  95441. }
  95442. }
  95443. FLAC__bool FLAC__memory_alloc_aligned_unsigned_array(unsigned elements, unsigned **unaligned_pointer, unsigned **aligned_pointer)
  95444. {
  95445. unsigned *pu; /* unaligned pointer */
  95446. union { /* union needed to comply with C99 pointer aliasing rules */
  95447. unsigned *pa; /* aligned pointer */
  95448. void *pv; /* aligned pointer alias */
  95449. } u;
  95450. FLAC__ASSERT(elements > 0);
  95451. FLAC__ASSERT(0 != unaligned_pointer);
  95452. FLAC__ASSERT(0 != aligned_pointer);
  95453. FLAC__ASSERT(unaligned_pointer != aligned_pointer);
  95454. pu = (unsigned*)FLAC__memory_alloc_aligned(sizeof(*pu) * elements, &u.pv);
  95455. if(0 == pu) {
  95456. return false;
  95457. }
  95458. else {
  95459. if(*unaligned_pointer != 0)
  95460. free(*unaligned_pointer);
  95461. *unaligned_pointer = pu;
  95462. *aligned_pointer = u.pa;
  95463. return true;
  95464. }
  95465. }
  95466. #ifndef FLAC__INTEGER_ONLY_LIBRARY
  95467. FLAC__bool FLAC__memory_alloc_aligned_real_array(unsigned elements, FLAC__real **unaligned_pointer, FLAC__real **aligned_pointer)
  95468. {
  95469. FLAC__real *pu; /* unaligned pointer */
  95470. union { /* union needed to comply with C99 pointer aliasing rules */
  95471. FLAC__real *pa; /* aligned pointer */
  95472. void *pv; /* aligned pointer alias */
  95473. } u;
  95474. FLAC__ASSERT(elements > 0);
  95475. FLAC__ASSERT(0 != unaligned_pointer);
  95476. FLAC__ASSERT(0 != aligned_pointer);
  95477. FLAC__ASSERT(unaligned_pointer != aligned_pointer);
  95478. pu = (FLAC__real*)FLAC__memory_alloc_aligned(sizeof(*pu) * elements, &u.pv);
  95479. if(0 == pu) {
  95480. return false;
  95481. }
  95482. else {
  95483. if(*unaligned_pointer != 0)
  95484. free(*unaligned_pointer);
  95485. *unaligned_pointer = pu;
  95486. *aligned_pointer = u.pa;
  95487. return true;
  95488. }
  95489. }
  95490. #endif
  95491. #endif
  95492. /*** End of inlined file: memory.c ***/
  95493. /*** Start of inlined file: stream_decoder.c ***/
  95494. /*** Start of inlined file: juce_FlacHeader.h ***/
  95495. // This file is included at the start of each FLAC .c file, just to do a few housekeeping
  95496. // tasks..
  95497. #define VERSION "1.2.1"
  95498. #define FLAC__NO_DLL 1
  95499. #if JUCE_MSVC
  95500. #pragma warning (disable: 4267 4127 4244 4996 4100 4701 4702 4013 4133 4206 4312)
  95501. #endif
  95502. #if JUCE_MAC
  95503. #define FLAC__SYS_DARWIN 1
  95504. #endif
  95505. /*** End of inlined file: juce_FlacHeader.h ***/
  95506. #if JUCE_USE_FLAC
  95507. #if HAVE_CONFIG_H
  95508. # include <config.h>
  95509. #endif
  95510. #if defined _MSC_VER || defined __MINGW32__
  95511. #include <io.h> /* for _setmode() */
  95512. #include <fcntl.h> /* for _O_BINARY */
  95513. #endif
  95514. #if defined __CYGWIN__ || defined __EMX__
  95515. #include <io.h> /* for setmode(), O_BINARY */
  95516. #include <fcntl.h> /* for _O_BINARY */
  95517. #endif
  95518. #include <stdio.h>
  95519. #include <stdlib.h> /* for malloc() */
  95520. #include <string.h> /* for memset/memcpy() */
  95521. #include <sys/stat.h> /* for stat() */
  95522. #include <sys/types.h> /* for off_t */
  95523. #if defined _MSC_VER || defined __BORLANDC__ || defined __MINGW32__
  95524. #if _MSC_VER <= 1600 || defined __BORLANDC__ /* @@@ [2G limit] */
  95525. #define fseeko fseek
  95526. #define ftello ftell
  95527. #endif
  95528. #endif
  95529. /*** Start of inlined file: stream_decoder.h ***/
  95530. #ifndef FLAC__PROTECTED__STREAM_DECODER_H
  95531. #define FLAC__PROTECTED__STREAM_DECODER_H
  95532. #if FLAC__HAS_OGG
  95533. #include "include/private/ogg_decoder_aspect.h"
  95534. #endif
  95535. typedef struct FLAC__StreamDecoderProtected {
  95536. FLAC__StreamDecoderState state;
  95537. unsigned channels;
  95538. FLAC__ChannelAssignment channel_assignment;
  95539. unsigned bits_per_sample;
  95540. unsigned sample_rate; /* in Hz */
  95541. unsigned blocksize; /* in samples (per channel) */
  95542. FLAC__bool md5_checking; /* if true, generate MD5 signature of decoded data and compare against signature in the STREAMINFO metadata block */
  95543. #if FLAC__HAS_OGG
  95544. FLAC__OggDecoderAspect ogg_decoder_aspect;
  95545. #endif
  95546. } FLAC__StreamDecoderProtected;
  95547. /*
  95548. * return the number of input bytes consumed
  95549. */
  95550. unsigned FLAC__stream_decoder_get_input_bytes_unconsumed(const FLAC__StreamDecoder *decoder);
  95551. #endif
  95552. /*** End of inlined file: stream_decoder.h ***/
  95553. #ifdef max
  95554. #undef max
  95555. #endif
  95556. #define max(a,b) ((a)>(b)?(a):(b))
  95557. /* adjust for compilers that can't understand using LLU suffix for uint64_t literals */
  95558. #ifdef _MSC_VER
  95559. #define FLAC__U64L(x) x
  95560. #else
  95561. #define FLAC__U64L(x) x##LLU
  95562. #endif
  95563. /* technically this should be in an "export.c" but this is convenient enough */
  95564. FLAC_API int FLAC_API_SUPPORTS_OGG_FLAC =
  95565. #if FLAC__HAS_OGG
  95566. 1
  95567. #else
  95568. 0
  95569. #endif
  95570. ;
  95571. /***********************************************************************
  95572. *
  95573. * Private static data
  95574. *
  95575. ***********************************************************************/
  95576. static FLAC__byte ID3V2_TAG_[3] = { 'I', 'D', '3' };
  95577. /***********************************************************************
  95578. *
  95579. * Private class method prototypes
  95580. *
  95581. ***********************************************************************/
  95582. static void set_defaults_dec(FLAC__StreamDecoder *decoder);
  95583. static FILE *get_binary_stdin_(void);
  95584. static FLAC__bool allocate_output_(FLAC__StreamDecoder *decoder, unsigned size, unsigned channels);
  95585. static FLAC__bool has_id_filtered_(FLAC__StreamDecoder *decoder, FLAC__byte *id);
  95586. static FLAC__bool find_metadata_(FLAC__StreamDecoder *decoder);
  95587. static FLAC__bool read_metadata_(FLAC__StreamDecoder *decoder);
  95588. static FLAC__bool read_metadata_streaminfo_(FLAC__StreamDecoder *decoder, FLAC__bool is_last, unsigned length);
  95589. static FLAC__bool read_metadata_seektable_(FLAC__StreamDecoder *decoder, FLAC__bool is_last, unsigned length);
  95590. static FLAC__bool read_metadata_vorbiscomment_(FLAC__StreamDecoder *decoder, FLAC__StreamMetadata_VorbisComment *obj);
  95591. static FLAC__bool read_metadata_cuesheet_(FLAC__StreamDecoder *decoder, FLAC__StreamMetadata_CueSheet *obj);
  95592. static FLAC__bool read_metadata_picture_(FLAC__StreamDecoder *decoder, FLAC__StreamMetadata_Picture *obj);
  95593. static FLAC__bool skip_id3v2_tag_(FLAC__StreamDecoder *decoder);
  95594. static FLAC__bool frame_sync_(FLAC__StreamDecoder *decoder);
  95595. static FLAC__bool read_frame_(FLAC__StreamDecoder *decoder, FLAC__bool *got_a_frame, FLAC__bool do_full_decode);
  95596. static FLAC__bool read_frame_header_(FLAC__StreamDecoder *decoder);
  95597. static FLAC__bool read_subframe_(FLAC__StreamDecoder *decoder, unsigned channel, unsigned bps, FLAC__bool do_full_decode);
  95598. static FLAC__bool read_subframe_constant_(FLAC__StreamDecoder *decoder, unsigned channel, unsigned bps, FLAC__bool do_full_decode);
  95599. static FLAC__bool read_subframe_fixed_(FLAC__StreamDecoder *decoder, unsigned channel, unsigned bps, const unsigned order, FLAC__bool do_full_decode);
  95600. static FLAC__bool read_subframe_lpc_(FLAC__StreamDecoder *decoder, unsigned channel, unsigned bps, const unsigned order, FLAC__bool do_full_decode);
  95601. static FLAC__bool read_subframe_verbatim_(FLAC__StreamDecoder *decoder, unsigned channel, unsigned bps, FLAC__bool do_full_decode);
  95602. 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);
  95603. static FLAC__bool read_zero_padding_(FLAC__StreamDecoder *decoder);
  95604. static FLAC__bool read_callback_(FLAC__byte buffer[], size_t *bytes, void *client_data);
  95605. #if FLAC__HAS_OGG
  95606. static FLAC__StreamDecoderReadStatus read_callback_ogg_aspect_(const FLAC__StreamDecoder *decoder, FLAC__byte buffer[], size_t *bytes);
  95607. static FLAC__OggDecoderAspectReadStatus read_callback_proxy_(const void *void_decoder, FLAC__byte buffer[], size_t *bytes, void *client_data);
  95608. #endif
  95609. static FLAC__StreamDecoderWriteStatus write_audio_frame_to_client_(FLAC__StreamDecoder *decoder, const FLAC__Frame *frame, const FLAC__int32 * const buffer[]);
  95610. static void send_error_to_client_(const FLAC__StreamDecoder *decoder, FLAC__StreamDecoderErrorStatus status);
  95611. static FLAC__bool seek_to_absolute_sample_(FLAC__StreamDecoder *decoder, FLAC__uint64 stream_length, FLAC__uint64 target_sample);
  95612. #if FLAC__HAS_OGG
  95613. static FLAC__bool seek_to_absolute_sample_ogg_(FLAC__StreamDecoder *decoder, FLAC__uint64 stream_length, FLAC__uint64 target_sample);
  95614. #endif
  95615. static FLAC__StreamDecoderReadStatus file_read_callback_dec (const FLAC__StreamDecoder *decoder, FLAC__byte buffer[], size_t *bytes, void *client_data);
  95616. static FLAC__StreamDecoderSeekStatus file_seek_callback_dec (const FLAC__StreamDecoder *decoder, FLAC__uint64 absolute_byte_offset, void *client_data);
  95617. static FLAC__StreamDecoderTellStatus file_tell_callback_dec (const FLAC__StreamDecoder *decoder, FLAC__uint64 *absolute_byte_offset, void *client_data);
  95618. static FLAC__StreamDecoderLengthStatus file_length_callback_(const FLAC__StreamDecoder *decoder, FLAC__uint64 *stream_length, void *client_data);
  95619. static FLAC__bool file_eof_callback_(const FLAC__StreamDecoder *decoder, void *client_data);
  95620. /***********************************************************************
  95621. *
  95622. * Private class data
  95623. *
  95624. ***********************************************************************/
  95625. typedef struct FLAC__StreamDecoderPrivate {
  95626. #if FLAC__HAS_OGG
  95627. FLAC__bool is_ogg;
  95628. #endif
  95629. FLAC__StreamDecoderReadCallback read_callback;
  95630. FLAC__StreamDecoderSeekCallback seek_callback;
  95631. FLAC__StreamDecoderTellCallback tell_callback;
  95632. FLAC__StreamDecoderLengthCallback length_callback;
  95633. FLAC__StreamDecoderEofCallback eof_callback;
  95634. FLAC__StreamDecoderWriteCallback write_callback;
  95635. FLAC__StreamDecoderMetadataCallback metadata_callback;
  95636. FLAC__StreamDecoderErrorCallback error_callback;
  95637. /* generic 32-bit datapath: */
  95638. 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[]);
  95639. /* generic 64-bit datapath: */
  95640. 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[]);
  95641. /* for use when the signal is <= 16 bits-per-sample, or <= 15 bits-per-sample on a side channel (which requires 1 extra bit): */
  95642. 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[]);
  95643. /* 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: */
  95644. 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[]);
  95645. FLAC__bool (*local_bitreader_read_rice_signed_block)(FLAC__BitReader *br, int* vals, unsigned nvals, unsigned parameter);
  95646. void *client_data;
  95647. FILE *file; /* only used if FLAC__stream_decoder_init_file()/FLAC__stream_decoder_init_file() called, else NULL */
  95648. FLAC__BitReader *input;
  95649. FLAC__int32 *output[FLAC__MAX_CHANNELS];
  95650. FLAC__int32 *residual[FLAC__MAX_CHANNELS]; /* WATCHOUT: these are the aligned pointers; the real pointers that should be free()'d are residual_unaligned[] below */
  95651. FLAC__EntropyCodingMethod_PartitionedRiceContents partitioned_rice_contents[FLAC__MAX_CHANNELS];
  95652. unsigned output_capacity, output_channels;
  95653. FLAC__uint32 fixed_block_size, next_fixed_block_size;
  95654. FLAC__uint64 samples_decoded;
  95655. FLAC__bool has_stream_info, has_seek_table;
  95656. FLAC__StreamMetadata stream_info;
  95657. FLAC__StreamMetadata seek_table;
  95658. FLAC__bool metadata_filter[128]; /* MAGIC number 128 == total number of metadata block types == 1 << 7 */
  95659. FLAC__byte *metadata_filter_ids;
  95660. size_t metadata_filter_ids_count, metadata_filter_ids_capacity; /* units for both are IDs, not bytes */
  95661. FLAC__Frame frame;
  95662. FLAC__bool cached; /* true if there is a byte in lookahead */
  95663. FLAC__CPUInfo cpuinfo;
  95664. FLAC__byte header_warmup[2]; /* contains the sync code and reserved bits */
  95665. FLAC__byte lookahead; /* temp storage when we need to look ahead one byte in the stream */
  95666. /* unaligned (original) pointers to allocated data */
  95667. FLAC__int32 *residual_unaligned[FLAC__MAX_CHANNELS];
  95668. 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 */
  95669. FLAC__bool internal_reset_hack; /* used only during init() so we can call reset to set up the decoder without rewinding the input */
  95670. FLAC__bool is_seeking;
  95671. FLAC__MD5Context md5context;
  95672. FLAC__byte computed_md5sum[16]; /* this is the sum we computed from the decoded data */
  95673. /* (the rest of these are only used for seeking) */
  95674. FLAC__Frame last_frame; /* holds the info of the last frame we seeked to */
  95675. FLAC__uint64 first_frame_offset; /* hint to the seek routine of where in the stream the first audio frame starts */
  95676. FLAC__uint64 target_sample;
  95677. unsigned unparseable_frame_count; /* used to tell whether we're decoding a future version of FLAC or just got a bad sync */
  95678. #if FLAC__HAS_OGG
  95679. FLAC__bool got_a_frame; /* hack needed in Ogg FLAC seek routine to check when process_single() actually writes a frame */
  95680. #endif
  95681. } FLAC__StreamDecoderPrivate;
  95682. /***********************************************************************
  95683. *
  95684. * Public static class data
  95685. *
  95686. ***********************************************************************/
  95687. FLAC_API const char * const FLAC__StreamDecoderStateString[] = {
  95688. "FLAC__STREAM_DECODER_SEARCH_FOR_METADATA",
  95689. "FLAC__STREAM_DECODER_READ_METADATA",
  95690. "FLAC__STREAM_DECODER_SEARCH_FOR_FRAME_SYNC",
  95691. "FLAC__STREAM_DECODER_READ_FRAME",
  95692. "FLAC__STREAM_DECODER_END_OF_STREAM",
  95693. "FLAC__STREAM_DECODER_OGG_ERROR",
  95694. "FLAC__STREAM_DECODER_SEEK_ERROR",
  95695. "FLAC__STREAM_DECODER_ABORTED",
  95696. "FLAC__STREAM_DECODER_MEMORY_ALLOCATION_ERROR",
  95697. "FLAC__STREAM_DECODER_UNINITIALIZED"
  95698. };
  95699. FLAC_API const char * const FLAC__StreamDecoderInitStatusString[] = {
  95700. "FLAC__STREAM_DECODER_INIT_STATUS_OK",
  95701. "FLAC__STREAM_DECODER_INIT_STATUS_UNSUPPORTED_CONTAINER",
  95702. "FLAC__STREAM_DECODER_INIT_STATUS_INVALID_CALLBACKS",
  95703. "FLAC__STREAM_DECODER_INIT_STATUS_MEMORY_ALLOCATION_ERROR",
  95704. "FLAC__STREAM_DECODER_INIT_STATUS_ERROR_OPENING_FILE",
  95705. "FLAC__STREAM_DECODER_INIT_STATUS_ALREADY_INITIALIZED"
  95706. };
  95707. FLAC_API const char * const FLAC__StreamDecoderReadStatusString[] = {
  95708. "FLAC__STREAM_DECODER_READ_STATUS_CONTINUE",
  95709. "FLAC__STREAM_DECODER_READ_STATUS_END_OF_STREAM",
  95710. "FLAC__STREAM_DECODER_READ_STATUS_ABORT"
  95711. };
  95712. FLAC_API const char * const FLAC__StreamDecoderSeekStatusString[] = {
  95713. "FLAC__STREAM_DECODER_SEEK_STATUS_OK",
  95714. "FLAC__STREAM_DECODER_SEEK_STATUS_ERROR",
  95715. "FLAC__STREAM_DECODER_SEEK_STATUS_UNSUPPORTED"
  95716. };
  95717. FLAC_API const char * const FLAC__StreamDecoderTellStatusString[] = {
  95718. "FLAC__STREAM_DECODER_TELL_STATUS_OK",
  95719. "FLAC__STREAM_DECODER_TELL_STATUS_ERROR",
  95720. "FLAC__STREAM_DECODER_TELL_STATUS_UNSUPPORTED"
  95721. };
  95722. FLAC_API const char * const FLAC__StreamDecoderLengthStatusString[] = {
  95723. "FLAC__STREAM_DECODER_LENGTH_STATUS_OK",
  95724. "FLAC__STREAM_DECODER_LENGTH_STATUS_ERROR",
  95725. "FLAC__STREAM_DECODER_LENGTH_STATUS_UNSUPPORTED"
  95726. };
  95727. FLAC_API const char * const FLAC__StreamDecoderWriteStatusString[] = {
  95728. "FLAC__STREAM_DECODER_WRITE_STATUS_CONTINUE",
  95729. "FLAC__STREAM_DECODER_WRITE_STATUS_ABORT"
  95730. };
  95731. FLAC_API const char * const FLAC__StreamDecoderErrorStatusString[] = {
  95732. "FLAC__STREAM_DECODER_ERROR_STATUS_LOST_SYNC",
  95733. "FLAC__STREAM_DECODER_ERROR_STATUS_BAD_HEADER",
  95734. "FLAC__STREAM_DECODER_ERROR_STATUS_FRAME_CRC_MISMATCH",
  95735. "FLAC__STREAM_DECODER_ERROR_STATUS_UNPARSEABLE_STREAM"
  95736. };
  95737. /***********************************************************************
  95738. *
  95739. * Class constructor/destructor
  95740. *
  95741. ***********************************************************************/
  95742. FLAC_API FLAC__StreamDecoder *FLAC__stream_decoder_new(void)
  95743. {
  95744. FLAC__StreamDecoder *decoder;
  95745. unsigned i;
  95746. FLAC__ASSERT(sizeof(int) >= 4); /* we want to die right away if this is not true */
  95747. decoder = (FLAC__StreamDecoder*)calloc(1, sizeof(FLAC__StreamDecoder));
  95748. if(decoder == 0) {
  95749. return 0;
  95750. }
  95751. decoder->protected_ = (FLAC__StreamDecoderProtected*)calloc(1, sizeof(FLAC__StreamDecoderProtected));
  95752. if(decoder->protected_ == 0) {
  95753. free(decoder);
  95754. return 0;
  95755. }
  95756. decoder->private_ = (FLAC__StreamDecoderPrivate*)calloc(1, sizeof(FLAC__StreamDecoderPrivate));
  95757. if(decoder->private_ == 0) {
  95758. free(decoder->protected_);
  95759. free(decoder);
  95760. return 0;
  95761. }
  95762. decoder->private_->input = FLAC__bitreader_new();
  95763. if(decoder->private_->input == 0) {
  95764. free(decoder->private_);
  95765. free(decoder->protected_);
  95766. free(decoder);
  95767. return 0;
  95768. }
  95769. decoder->private_->metadata_filter_ids_capacity = 16;
  95770. if(0 == (decoder->private_->metadata_filter_ids = (FLAC__byte*)malloc((FLAC__STREAM_METADATA_APPLICATION_ID_LEN/8) * decoder->private_->metadata_filter_ids_capacity))) {
  95771. FLAC__bitreader_delete(decoder->private_->input);
  95772. free(decoder->private_);
  95773. free(decoder->protected_);
  95774. free(decoder);
  95775. return 0;
  95776. }
  95777. for(i = 0; i < FLAC__MAX_CHANNELS; i++) {
  95778. decoder->private_->output[i] = 0;
  95779. decoder->private_->residual_unaligned[i] = decoder->private_->residual[i] = 0;
  95780. }
  95781. decoder->private_->output_capacity = 0;
  95782. decoder->private_->output_channels = 0;
  95783. decoder->private_->has_seek_table = false;
  95784. for(i = 0; i < FLAC__MAX_CHANNELS; i++)
  95785. FLAC__format_entropy_coding_method_partitioned_rice_contents_init(&decoder->private_->partitioned_rice_contents[i]);
  95786. decoder->private_->file = 0;
  95787. set_defaults_dec(decoder);
  95788. decoder->protected_->state = FLAC__STREAM_DECODER_UNINITIALIZED;
  95789. return decoder;
  95790. }
  95791. FLAC_API void FLAC__stream_decoder_delete(FLAC__StreamDecoder *decoder)
  95792. {
  95793. unsigned i;
  95794. FLAC__ASSERT(0 != decoder);
  95795. FLAC__ASSERT(0 != decoder->protected_);
  95796. FLAC__ASSERT(0 != decoder->private_);
  95797. FLAC__ASSERT(0 != decoder->private_->input);
  95798. (void)FLAC__stream_decoder_finish(decoder);
  95799. if(0 != decoder->private_->metadata_filter_ids)
  95800. free(decoder->private_->metadata_filter_ids);
  95801. FLAC__bitreader_delete(decoder->private_->input);
  95802. for(i = 0; i < FLAC__MAX_CHANNELS; i++)
  95803. FLAC__format_entropy_coding_method_partitioned_rice_contents_clear(&decoder->private_->partitioned_rice_contents[i]);
  95804. free(decoder->private_);
  95805. free(decoder->protected_);
  95806. free(decoder);
  95807. }
  95808. /***********************************************************************
  95809. *
  95810. * Public class methods
  95811. *
  95812. ***********************************************************************/
  95813. static FLAC__StreamDecoderInitStatus init_stream_internal_dec(
  95814. FLAC__StreamDecoder *decoder,
  95815. FLAC__StreamDecoderReadCallback read_callback,
  95816. FLAC__StreamDecoderSeekCallback seek_callback,
  95817. FLAC__StreamDecoderTellCallback tell_callback,
  95818. FLAC__StreamDecoderLengthCallback length_callback,
  95819. FLAC__StreamDecoderEofCallback eof_callback,
  95820. FLAC__StreamDecoderWriteCallback write_callback,
  95821. FLAC__StreamDecoderMetadataCallback metadata_callback,
  95822. FLAC__StreamDecoderErrorCallback error_callback,
  95823. void *client_data,
  95824. FLAC__bool is_ogg
  95825. )
  95826. {
  95827. FLAC__ASSERT(0 != decoder);
  95828. if(decoder->protected_->state != FLAC__STREAM_DECODER_UNINITIALIZED)
  95829. return FLAC__STREAM_DECODER_INIT_STATUS_ALREADY_INITIALIZED;
  95830. #if !FLAC__HAS_OGG
  95831. if(is_ogg)
  95832. return FLAC__STREAM_DECODER_INIT_STATUS_UNSUPPORTED_CONTAINER;
  95833. #endif
  95834. if(
  95835. 0 == read_callback ||
  95836. 0 == write_callback ||
  95837. 0 == error_callback ||
  95838. (seek_callback && (0 == tell_callback || 0 == length_callback || 0 == eof_callback))
  95839. )
  95840. return FLAC__STREAM_DECODER_INIT_STATUS_INVALID_CALLBACKS;
  95841. #if FLAC__HAS_OGG
  95842. decoder->private_->is_ogg = is_ogg;
  95843. if(is_ogg && !FLAC__ogg_decoder_aspect_init(&decoder->protected_->ogg_decoder_aspect))
  95844. return decoder->protected_->state = FLAC__STREAM_DECODER_OGG_ERROR;
  95845. #endif
  95846. /*
  95847. * get the CPU info and set the function pointers
  95848. */
  95849. FLAC__cpu_info(&decoder->private_->cpuinfo);
  95850. /* first default to the non-asm routines */
  95851. decoder->private_->local_lpc_restore_signal = FLAC__lpc_restore_signal;
  95852. decoder->private_->local_lpc_restore_signal_64bit = FLAC__lpc_restore_signal_wide;
  95853. decoder->private_->local_lpc_restore_signal_16bit = FLAC__lpc_restore_signal;
  95854. decoder->private_->local_lpc_restore_signal_16bit_order8 = FLAC__lpc_restore_signal;
  95855. decoder->private_->local_bitreader_read_rice_signed_block = FLAC__bitreader_read_rice_signed_block;
  95856. /* now override with asm where appropriate */
  95857. #ifndef FLAC__NO_ASM
  95858. if(decoder->private_->cpuinfo.use_asm) {
  95859. #ifdef FLAC__CPU_IA32
  95860. FLAC__ASSERT(decoder->private_->cpuinfo.type == FLAC__CPUINFO_TYPE_IA32);
  95861. #ifdef FLAC__HAS_NASM
  95862. #if 1 /*@@@@@@ OPT: not clearly faster, needs more testing */
  95863. if(decoder->private_->cpuinfo.data.ia32.bswap)
  95864. decoder->private_->local_bitreader_read_rice_signed_block = FLAC__bitreader_read_rice_signed_block_asm_ia32_bswap;
  95865. #endif
  95866. if(decoder->private_->cpuinfo.data.ia32.mmx) {
  95867. decoder->private_->local_lpc_restore_signal = FLAC__lpc_restore_signal_asm_ia32;
  95868. decoder->private_->local_lpc_restore_signal_16bit = FLAC__lpc_restore_signal_asm_ia32_mmx;
  95869. decoder->private_->local_lpc_restore_signal_16bit_order8 = FLAC__lpc_restore_signal_asm_ia32_mmx;
  95870. }
  95871. else {
  95872. decoder->private_->local_lpc_restore_signal = FLAC__lpc_restore_signal_asm_ia32;
  95873. decoder->private_->local_lpc_restore_signal_16bit = FLAC__lpc_restore_signal_asm_ia32;
  95874. decoder->private_->local_lpc_restore_signal_16bit_order8 = FLAC__lpc_restore_signal_asm_ia32;
  95875. }
  95876. #endif
  95877. #elif defined FLAC__CPU_PPC
  95878. FLAC__ASSERT(decoder->private_->cpuinfo.type == FLAC__CPUINFO_TYPE_PPC);
  95879. if(decoder->private_->cpuinfo.data.ppc.altivec) {
  95880. decoder->private_->local_lpc_restore_signal_16bit = FLAC__lpc_restore_signal_asm_ppc_altivec_16;
  95881. decoder->private_->local_lpc_restore_signal_16bit_order8 = FLAC__lpc_restore_signal_asm_ppc_altivec_16_order8;
  95882. }
  95883. #endif
  95884. }
  95885. #endif
  95886. /* from here on, errors are fatal */
  95887. if(!FLAC__bitreader_init(decoder->private_->input, decoder->private_->cpuinfo, read_callback_, decoder)) {
  95888. decoder->protected_->state = FLAC__STREAM_DECODER_MEMORY_ALLOCATION_ERROR;
  95889. return FLAC__STREAM_DECODER_INIT_STATUS_MEMORY_ALLOCATION_ERROR;
  95890. }
  95891. decoder->private_->read_callback = read_callback;
  95892. decoder->private_->seek_callback = seek_callback;
  95893. decoder->private_->tell_callback = tell_callback;
  95894. decoder->private_->length_callback = length_callback;
  95895. decoder->private_->eof_callback = eof_callback;
  95896. decoder->private_->write_callback = write_callback;
  95897. decoder->private_->metadata_callback = metadata_callback;
  95898. decoder->private_->error_callback = error_callback;
  95899. decoder->private_->client_data = client_data;
  95900. decoder->private_->fixed_block_size = decoder->private_->next_fixed_block_size = 0;
  95901. decoder->private_->samples_decoded = 0;
  95902. decoder->private_->has_stream_info = false;
  95903. decoder->private_->cached = false;
  95904. decoder->private_->do_md5_checking = decoder->protected_->md5_checking;
  95905. decoder->private_->is_seeking = false;
  95906. decoder->private_->internal_reset_hack = true; /* so the following reset does not try to rewind the input */
  95907. if(!FLAC__stream_decoder_reset(decoder)) {
  95908. /* above call sets the state for us */
  95909. return FLAC__STREAM_DECODER_INIT_STATUS_MEMORY_ALLOCATION_ERROR;
  95910. }
  95911. return FLAC__STREAM_DECODER_INIT_STATUS_OK;
  95912. }
  95913. FLAC_API FLAC__StreamDecoderInitStatus FLAC__stream_decoder_init_stream(
  95914. FLAC__StreamDecoder *decoder,
  95915. FLAC__StreamDecoderReadCallback read_callback,
  95916. FLAC__StreamDecoderSeekCallback seek_callback,
  95917. FLAC__StreamDecoderTellCallback tell_callback,
  95918. FLAC__StreamDecoderLengthCallback length_callback,
  95919. FLAC__StreamDecoderEofCallback eof_callback,
  95920. FLAC__StreamDecoderWriteCallback write_callback,
  95921. FLAC__StreamDecoderMetadataCallback metadata_callback,
  95922. FLAC__StreamDecoderErrorCallback error_callback,
  95923. void *client_data
  95924. )
  95925. {
  95926. return init_stream_internal_dec(
  95927. decoder,
  95928. read_callback,
  95929. seek_callback,
  95930. tell_callback,
  95931. length_callback,
  95932. eof_callback,
  95933. write_callback,
  95934. metadata_callback,
  95935. error_callback,
  95936. client_data,
  95937. /*is_ogg=*/false
  95938. );
  95939. }
  95940. FLAC_API FLAC__StreamDecoderInitStatus FLAC__stream_decoder_init_ogg_stream(
  95941. FLAC__StreamDecoder *decoder,
  95942. FLAC__StreamDecoderReadCallback read_callback,
  95943. FLAC__StreamDecoderSeekCallback seek_callback,
  95944. FLAC__StreamDecoderTellCallback tell_callback,
  95945. FLAC__StreamDecoderLengthCallback length_callback,
  95946. FLAC__StreamDecoderEofCallback eof_callback,
  95947. FLAC__StreamDecoderWriteCallback write_callback,
  95948. FLAC__StreamDecoderMetadataCallback metadata_callback,
  95949. FLAC__StreamDecoderErrorCallback error_callback,
  95950. void *client_data
  95951. )
  95952. {
  95953. return init_stream_internal_dec(
  95954. decoder,
  95955. read_callback,
  95956. seek_callback,
  95957. tell_callback,
  95958. length_callback,
  95959. eof_callback,
  95960. write_callback,
  95961. metadata_callback,
  95962. error_callback,
  95963. client_data,
  95964. /*is_ogg=*/true
  95965. );
  95966. }
  95967. static FLAC__StreamDecoderInitStatus init_FILE_internal_(
  95968. FLAC__StreamDecoder *decoder,
  95969. FILE *file,
  95970. FLAC__StreamDecoderWriteCallback write_callback,
  95971. FLAC__StreamDecoderMetadataCallback metadata_callback,
  95972. FLAC__StreamDecoderErrorCallback error_callback,
  95973. void *client_data,
  95974. FLAC__bool is_ogg
  95975. )
  95976. {
  95977. FLAC__ASSERT(0 != decoder);
  95978. FLAC__ASSERT(0 != file);
  95979. if(decoder->protected_->state != FLAC__STREAM_DECODER_UNINITIALIZED)
  95980. return (FLAC__StreamDecoderInitStatus) (decoder->protected_->state = (FLAC__StreamDecoderState) FLAC__STREAM_DECODER_INIT_STATUS_ALREADY_INITIALIZED);
  95981. if(0 == write_callback || 0 == error_callback)
  95982. return (FLAC__StreamDecoderInitStatus) (decoder->protected_->state = (FLAC__StreamDecoderState) FLAC__STREAM_DECODER_INIT_STATUS_INVALID_CALLBACKS);
  95983. /*
  95984. * To make sure that our file does not go unclosed after an error, we
  95985. * must assign the FILE pointer before any further error can occur in
  95986. * this routine.
  95987. */
  95988. if(file == stdin)
  95989. file = get_binary_stdin_(); /* just to be safe */
  95990. decoder->private_->file = file;
  95991. return init_stream_internal_dec(
  95992. decoder,
  95993. file_read_callback_dec,
  95994. decoder->private_->file == stdin? 0: file_seek_callback_dec,
  95995. decoder->private_->file == stdin? 0: file_tell_callback_dec,
  95996. decoder->private_->file == stdin? 0: file_length_callback_,
  95997. file_eof_callback_,
  95998. write_callback,
  95999. metadata_callback,
  96000. error_callback,
  96001. client_data,
  96002. is_ogg
  96003. );
  96004. }
  96005. FLAC_API FLAC__StreamDecoderInitStatus FLAC__stream_decoder_init_FILE(
  96006. FLAC__StreamDecoder *decoder,
  96007. FILE *file,
  96008. FLAC__StreamDecoderWriteCallback write_callback,
  96009. FLAC__StreamDecoderMetadataCallback metadata_callback,
  96010. FLAC__StreamDecoderErrorCallback error_callback,
  96011. void *client_data
  96012. )
  96013. {
  96014. return init_FILE_internal_(decoder, file, write_callback, metadata_callback, error_callback, client_data, /*is_ogg=*/false);
  96015. }
  96016. FLAC_API FLAC__StreamDecoderInitStatus FLAC__stream_decoder_init_ogg_FILE(
  96017. FLAC__StreamDecoder *decoder,
  96018. FILE *file,
  96019. FLAC__StreamDecoderWriteCallback write_callback,
  96020. FLAC__StreamDecoderMetadataCallback metadata_callback,
  96021. FLAC__StreamDecoderErrorCallback error_callback,
  96022. void *client_data
  96023. )
  96024. {
  96025. return init_FILE_internal_(decoder, file, write_callback, metadata_callback, error_callback, client_data, /*is_ogg=*/true);
  96026. }
  96027. static FLAC__StreamDecoderInitStatus init_file_internal_(
  96028. FLAC__StreamDecoder *decoder,
  96029. const char *filename,
  96030. FLAC__StreamDecoderWriteCallback write_callback,
  96031. FLAC__StreamDecoderMetadataCallback metadata_callback,
  96032. FLAC__StreamDecoderErrorCallback error_callback,
  96033. void *client_data,
  96034. FLAC__bool is_ogg
  96035. )
  96036. {
  96037. FILE *file;
  96038. FLAC__ASSERT(0 != decoder);
  96039. /*
  96040. * To make sure that our file does not go unclosed after an error, we
  96041. * have to do the same entrance checks here that are later performed
  96042. * in FLAC__stream_decoder_init_FILE() before the FILE* is assigned.
  96043. */
  96044. if(decoder->protected_->state != FLAC__STREAM_DECODER_UNINITIALIZED)
  96045. return (FLAC__StreamDecoderInitStatus) (decoder->protected_->state = (FLAC__StreamDecoderState) FLAC__STREAM_DECODER_INIT_STATUS_ALREADY_INITIALIZED);
  96046. if(0 == write_callback || 0 == error_callback)
  96047. return (FLAC__StreamDecoderInitStatus) (decoder->protected_->state = (FLAC__StreamDecoderState) FLAC__STREAM_DECODER_INIT_STATUS_INVALID_CALLBACKS);
  96048. file = filename? fopen(filename, "rb") : stdin;
  96049. if(0 == file)
  96050. return FLAC__STREAM_DECODER_INIT_STATUS_ERROR_OPENING_FILE;
  96051. return init_FILE_internal_(decoder, file, write_callback, metadata_callback, error_callback, client_data, is_ogg);
  96052. }
  96053. FLAC_API FLAC__StreamDecoderInitStatus FLAC__stream_decoder_init_file(
  96054. FLAC__StreamDecoder *decoder,
  96055. const char *filename,
  96056. FLAC__StreamDecoderWriteCallback write_callback,
  96057. FLAC__StreamDecoderMetadataCallback metadata_callback,
  96058. FLAC__StreamDecoderErrorCallback error_callback,
  96059. void *client_data
  96060. )
  96061. {
  96062. return init_file_internal_(decoder, filename, write_callback, metadata_callback, error_callback, client_data, /*is_ogg=*/false);
  96063. }
  96064. FLAC_API FLAC__StreamDecoderInitStatus FLAC__stream_decoder_init_ogg_file(
  96065. FLAC__StreamDecoder *decoder,
  96066. const char *filename,
  96067. FLAC__StreamDecoderWriteCallback write_callback,
  96068. FLAC__StreamDecoderMetadataCallback metadata_callback,
  96069. FLAC__StreamDecoderErrorCallback error_callback,
  96070. void *client_data
  96071. )
  96072. {
  96073. return init_file_internal_(decoder, filename, write_callback, metadata_callback, error_callback, client_data, /*is_ogg=*/true);
  96074. }
  96075. FLAC_API FLAC__bool FLAC__stream_decoder_finish(FLAC__StreamDecoder *decoder)
  96076. {
  96077. FLAC__bool md5_failed = false;
  96078. unsigned i;
  96079. FLAC__ASSERT(0 != decoder);
  96080. FLAC__ASSERT(0 != decoder->private_);
  96081. FLAC__ASSERT(0 != decoder->protected_);
  96082. if(decoder->protected_->state == FLAC__STREAM_DECODER_UNINITIALIZED)
  96083. return true;
  96084. /* see the comment in FLAC__seekable_stream_decoder_reset() as to why we
  96085. * always call FLAC__MD5Final()
  96086. */
  96087. FLAC__MD5Final(decoder->private_->computed_md5sum, &decoder->private_->md5context);
  96088. if(decoder->private_->has_seek_table && 0 != decoder->private_->seek_table.data.seek_table.points) {
  96089. free(decoder->private_->seek_table.data.seek_table.points);
  96090. decoder->private_->seek_table.data.seek_table.points = 0;
  96091. decoder->private_->has_seek_table = false;
  96092. }
  96093. FLAC__bitreader_free(decoder->private_->input);
  96094. for(i = 0; i < FLAC__MAX_CHANNELS; i++) {
  96095. /* WATCHOUT:
  96096. * FLAC__lpc_restore_signal_asm_ia32_mmx() requires that the
  96097. * output arrays have a buffer of up to 3 zeroes in front
  96098. * (at negative indices) for alignment purposes; we use 4
  96099. * to keep the data well-aligned.
  96100. */
  96101. if(0 != decoder->private_->output[i]) {
  96102. free(decoder->private_->output[i]-4);
  96103. decoder->private_->output[i] = 0;
  96104. }
  96105. if(0 != decoder->private_->residual_unaligned[i]) {
  96106. free(decoder->private_->residual_unaligned[i]);
  96107. decoder->private_->residual_unaligned[i] = decoder->private_->residual[i] = 0;
  96108. }
  96109. }
  96110. decoder->private_->output_capacity = 0;
  96111. decoder->private_->output_channels = 0;
  96112. #if FLAC__HAS_OGG
  96113. if(decoder->private_->is_ogg)
  96114. FLAC__ogg_decoder_aspect_finish(&decoder->protected_->ogg_decoder_aspect);
  96115. #endif
  96116. if(0 != decoder->private_->file) {
  96117. if(decoder->private_->file != stdin)
  96118. fclose(decoder->private_->file);
  96119. decoder->private_->file = 0;
  96120. }
  96121. if(decoder->private_->do_md5_checking) {
  96122. if(memcmp(decoder->private_->stream_info.data.stream_info.md5sum, decoder->private_->computed_md5sum, 16))
  96123. md5_failed = true;
  96124. }
  96125. decoder->private_->is_seeking = false;
  96126. set_defaults_dec(decoder);
  96127. decoder->protected_->state = FLAC__STREAM_DECODER_UNINITIALIZED;
  96128. return !md5_failed;
  96129. }
  96130. FLAC_API FLAC__bool FLAC__stream_decoder_set_ogg_serial_number(FLAC__StreamDecoder *decoder, long value)
  96131. {
  96132. FLAC__ASSERT(0 != decoder);
  96133. FLAC__ASSERT(0 != decoder->private_);
  96134. FLAC__ASSERT(0 != decoder->protected_);
  96135. if(decoder->protected_->state != FLAC__STREAM_DECODER_UNINITIALIZED)
  96136. return false;
  96137. #if FLAC__HAS_OGG
  96138. /* can't check decoder->private_->is_ogg since that's not set until init time */
  96139. FLAC__ogg_decoder_aspect_set_serial_number(&decoder->protected_->ogg_decoder_aspect, value);
  96140. return true;
  96141. #else
  96142. (void)value;
  96143. return false;
  96144. #endif
  96145. }
  96146. FLAC_API FLAC__bool FLAC__stream_decoder_set_md5_checking(FLAC__StreamDecoder *decoder, FLAC__bool value)
  96147. {
  96148. FLAC__ASSERT(0 != decoder);
  96149. FLAC__ASSERT(0 != decoder->protected_);
  96150. if(decoder->protected_->state != FLAC__STREAM_DECODER_UNINITIALIZED)
  96151. return false;
  96152. decoder->protected_->md5_checking = value;
  96153. return true;
  96154. }
  96155. FLAC_API FLAC__bool FLAC__stream_decoder_set_metadata_respond(FLAC__StreamDecoder *decoder, FLAC__MetadataType type)
  96156. {
  96157. FLAC__ASSERT(0 != decoder);
  96158. FLAC__ASSERT(0 != decoder->private_);
  96159. FLAC__ASSERT(0 != decoder->protected_);
  96160. FLAC__ASSERT((unsigned)type <= FLAC__MAX_METADATA_TYPE_CODE);
  96161. /* double protection */
  96162. if((unsigned)type > FLAC__MAX_METADATA_TYPE_CODE)
  96163. return false;
  96164. if(decoder->protected_->state != FLAC__STREAM_DECODER_UNINITIALIZED)
  96165. return false;
  96166. decoder->private_->metadata_filter[type] = true;
  96167. if(type == FLAC__METADATA_TYPE_APPLICATION)
  96168. decoder->private_->metadata_filter_ids_count = 0;
  96169. return true;
  96170. }
  96171. FLAC_API FLAC__bool FLAC__stream_decoder_set_metadata_respond_application(FLAC__StreamDecoder *decoder, const FLAC__byte id[4])
  96172. {
  96173. FLAC__ASSERT(0 != decoder);
  96174. FLAC__ASSERT(0 != decoder->private_);
  96175. FLAC__ASSERT(0 != decoder->protected_);
  96176. FLAC__ASSERT(0 != id);
  96177. if(decoder->protected_->state != FLAC__STREAM_DECODER_UNINITIALIZED)
  96178. return false;
  96179. if(decoder->private_->metadata_filter[FLAC__METADATA_TYPE_APPLICATION])
  96180. return true;
  96181. FLAC__ASSERT(0 != decoder->private_->metadata_filter_ids);
  96182. if(decoder->private_->metadata_filter_ids_count == decoder->private_->metadata_filter_ids_capacity) {
  96183. 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))) {
  96184. decoder->protected_->state = FLAC__STREAM_DECODER_MEMORY_ALLOCATION_ERROR;
  96185. return false;
  96186. }
  96187. decoder->private_->metadata_filter_ids_capacity *= 2;
  96188. }
  96189. 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));
  96190. decoder->private_->metadata_filter_ids_count++;
  96191. return true;
  96192. }
  96193. FLAC_API FLAC__bool FLAC__stream_decoder_set_metadata_respond_all(FLAC__StreamDecoder *decoder)
  96194. {
  96195. unsigned i;
  96196. FLAC__ASSERT(0 != decoder);
  96197. FLAC__ASSERT(0 != decoder->private_);
  96198. FLAC__ASSERT(0 != decoder->protected_);
  96199. if(decoder->protected_->state != FLAC__STREAM_DECODER_UNINITIALIZED)
  96200. return false;
  96201. for(i = 0; i < sizeof(decoder->private_->metadata_filter) / sizeof(decoder->private_->metadata_filter[0]); i++)
  96202. decoder->private_->metadata_filter[i] = true;
  96203. decoder->private_->metadata_filter_ids_count = 0;
  96204. return true;
  96205. }
  96206. FLAC_API FLAC__bool FLAC__stream_decoder_set_metadata_ignore(FLAC__StreamDecoder *decoder, FLAC__MetadataType type)
  96207. {
  96208. FLAC__ASSERT(0 != decoder);
  96209. FLAC__ASSERT(0 != decoder->private_);
  96210. FLAC__ASSERT(0 != decoder->protected_);
  96211. FLAC__ASSERT((unsigned)type <= FLAC__MAX_METADATA_TYPE_CODE);
  96212. /* double protection */
  96213. if((unsigned)type > FLAC__MAX_METADATA_TYPE_CODE)
  96214. return false;
  96215. if(decoder->protected_->state != FLAC__STREAM_DECODER_UNINITIALIZED)
  96216. return false;
  96217. decoder->private_->metadata_filter[type] = false;
  96218. if(type == FLAC__METADATA_TYPE_APPLICATION)
  96219. decoder->private_->metadata_filter_ids_count = 0;
  96220. return true;
  96221. }
  96222. FLAC_API FLAC__bool FLAC__stream_decoder_set_metadata_ignore_application(FLAC__StreamDecoder *decoder, const FLAC__byte id[4])
  96223. {
  96224. FLAC__ASSERT(0 != decoder);
  96225. FLAC__ASSERT(0 != decoder->private_);
  96226. FLAC__ASSERT(0 != decoder->protected_);
  96227. FLAC__ASSERT(0 != id);
  96228. if(decoder->protected_->state != FLAC__STREAM_DECODER_UNINITIALIZED)
  96229. return false;
  96230. if(!decoder->private_->metadata_filter[FLAC__METADATA_TYPE_APPLICATION])
  96231. return true;
  96232. FLAC__ASSERT(0 != decoder->private_->metadata_filter_ids);
  96233. if(decoder->private_->metadata_filter_ids_count == decoder->private_->metadata_filter_ids_capacity) {
  96234. 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))) {
  96235. decoder->protected_->state = FLAC__STREAM_DECODER_MEMORY_ALLOCATION_ERROR;
  96236. return false;
  96237. }
  96238. decoder->private_->metadata_filter_ids_capacity *= 2;
  96239. }
  96240. 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));
  96241. decoder->private_->metadata_filter_ids_count++;
  96242. return true;
  96243. }
  96244. FLAC_API FLAC__bool FLAC__stream_decoder_set_metadata_ignore_all(FLAC__StreamDecoder *decoder)
  96245. {
  96246. FLAC__ASSERT(0 != decoder);
  96247. FLAC__ASSERT(0 != decoder->private_);
  96248. FLAC__ASSERT(0 != decoder->protected_);
  96249. if(decoder->protected_->state != FLAC__STREAM_DECODER_UNINITIALIZED)
  96250. return false;
  96251. memset(decoder->private_->metadata_filter, 0, sizeof(decoder->private_->metadata_filter));
  96252. decoder->private_->metadata_filter_ids_count = 0;
  96253. return true;
  96254. }
  96255. FLAC_API FLAC__StreamDecoderState FLAC__stream_decoder_get_state(const FLAC__StreamDecoder *decoder)
  96256. {
  96257. FLAC__ASSERT(0 != decoder);
  96258. FLAC__ASSERT(0 != decoder->protected_);
  96259. return decoder->protected_->state;
  96260. }
  96261. FLAC_API const char *FLAC__stream_decoder_get_resolved_state_string(const FLAC__StreamDecoder *decoder)
  96262. {
  96263. return FLAC__StreamDecoderStateString[decoder->protected_->state];
  96264. }
  96265. FLAC_API FLAC__bool FLAC__stream_decoder_get_md5_checking(const FLAC__StreamDecoder *decoder)
  96266. {
  96267. FLAC__ASSERT(0 != decoder);
  96268. FLAC__ASSERT(0 != decoder->protected_);
  96269. return decoder->protected_->md5_checking;
  96270. }
  96271. FLAC_API FLAC__uint64 FLAC__stream_decoder_get_total_samples(const FLAC__StreamDecoder *decoder)
  96272. {
  96273. FLAC__ASSERT(0 != decoder);
  96274. FLAC__ASSERT(0 != decoder->protected_);
  96275. return decoder->private_->has_stream_info? decoder->private_->stream_info.data.stream_info.total_samples : 0;
  96276. }
  96277. FLAC_API unsigned FLAC__stream_decoder_get_channels(const FLAC__StreamDecoder *decoder)
  96278. {
  96279. FLAC__ASSERT(0 != decoder);
  96280. FLAC__ASSERT(0 != decoder->protected_);
  96281. return decoder->protected_->channels;
  96282. }
  96283. FLAC_API FLAC__ChannelAssignment FLAC__stream_decoder_get_channel_assignment(const FLAC__StreamDecoder *decoder)
  96284. {
  96285. FLAC__ASSERT(0 != decoder);
  96286. FLAC__ASSERT(0 != decoder->protected_);
  96287. return decoder->protected_->channel_assignment;
  96288. }
  96289. FLAC_API unsigned FLAC__stream_decoder_get_bits_per_sample(const FLAC__StreamDecoder *decoder)
  96290. {
  96291. FLAC__ASSERT(0 != decoder);
  96292. FLAC__ASSERT(0 != decoder->protected_);
  96293. return decoder->protected_->bits_per_sample;
  96294. }
  96295. FLAC_API unsigned FLAC__stream_decoder_get_sample_rate(const FLAC__StreamDecoder *decoder)
  96296. {
  96297. FLAC__ASSERT(0 != decoder);
  96298. FLAC__ASSERT(0 != decoder->protected_);
  96299. return decoder->protected_->sample_rate;
  96300. }
  96301. FLAC_API unsigned FLAC__stream_decoder_get_blocksize(const FLAC__StreamDecoder *decoder)
  96302. {
  96303. FLAC__ASSERT(0 != decoder);
  96304. FLAC__ASSERT(0 != decoder->protected_);
  96305. return decoder->protected_->blocksize;
  96306. }
  96307. FLAC_API FLAC__bool FLAC__stream_decoder_get_decode_position(const FLAC__StreamDecoder *decoder, FLAC__uint64 *position)
  96308. {
  96309. FLAC__ASSERT(0 != decoder);
  96310. FLAC__ASSERT(0 != decoder->private_);
  96311. FLAC__ASSERT(0 != position);
  96312. #if FLAC__HAS_OGG
  96313. if(decoder->private_->is_ogg)
  96314. return false;
  96315. #endif
  96316. if(0 == decoder->private_->tell_callback)
  96317. return false;
  96318. if(decoder->private_->tell_callback(decoder, position, decoder->private_->client_data) != FLAC__STREAM_DECODER_TELL_STATUS_OK)
  96319. return false;
  96320. /* should never happen since all FLAC frames and metadata blocks are byte aligned, but check just in case */
  96321. if(!FLAC__bitreader_is_consumed_byte_aligned(decoder->private_->input))
  96322. return false;
  96323. FLAC__ASSERT(*position >= FLAC__stream_decoder_get_input_bytes_unconsumed(decoder));
  96324. *position -= FLAC__stream_decoder_get_input_bytes_unconsumed(decoder);
  96325. return true;
  96326. }
  96327. FLAC_API FLAC__bool FLAC__stream_decoder_flush(FLAC__StreamDecoder *decoder)
  96328. {
  96329. FLAC__ASSERT(0 != decoder);
  96330. FLAC__ASSERT(0 != decoder->private_);
  96331. FLAC__ASSERT(0 != decoder->protected_);
  96332. decoder->private_->samples_decoded = 0;
  96333. decoder->private_->do_md5_checking = false;
  96334. #if FLAC__HAS_OGG
  96335. if(decoder->private_->is_ogg)
  96336. FLAC__ogg_decoder_aspect_flush(&decoder->protected_->ogg_decoder_aspect);
  96337. #endif
  96338. if(!FLAC__bitreader_clear(decoder->private_->input)) {
  96339. decoder->protected_->state = FLAC__STREAM_DECODER_MEMORY_ALLOCATION_ERROR;
  96340. return false;
  96341. }
  96342. decoder->protected_->state = FLAC__STREAM_DECODER_SEARCH_FOR_FRAME_SYNC;
  96343. return true;
  96344. }
  96345. FLAC_API FLAC__bool FLAC__stream_decoder_reset(FLAC__StreamDecoder *decoder)
  96346. {
  96347. FLAC__ASSERT(0 != decoder);
  96348. FLAC__ASSERT(0 != decoder->private_);
  96349. FLAC__ASSERT(0 != decoder->protected_);
  96350. if(!FLAC__stream_decoder_flush(decoder)) {
  96351. /* above call sets the state for us */
  96352. return false;
  96353. }
  96354. #if FLAC__HAS_OGG
  96355. /*@@@ could go in !internal_reset_hack block below */
  96356. if(decoder->private_->is_ogg)
  96357. FLAC__ogg_decoder_aspect_reset(&decoder->protected_->ogg_decoder_aspect);
  96358. #endif
  96359. /* Rewind if necessary. If FLAC__stream_decoder_init() is calling us,
  96360. * (internal_reset_hack) don't try to rewind since we are already at
  96361. * the beginning of the stream and don't want to fail if the input is
  96362. * not seekable.
  96363. */
  96364. if(!decoder->private_->internal_reset_hack) {
  96365. if(decoder->private_->file == stdin)
  96366. return false; /* can't rewind stdin, reset fails */
  96367. if(decoder->private_->seek_callback && decoder->private_->seek_callback(decoder, 0, decoder->private_->client_data) == FLAC__STREAM_DECODER_SEEK_STATUS_ERROR)
  96368. return false; /* seekable and seek fails, reset fails */
  96369. }
  96370. else
  96371. decoder->private_->internal_reset_hack = false;
  96372. decoder->protected_->state = FLAC__STREAM_DECODER_SEARCH_FOR_METADATA;
  96373. decoder->private_->has_stream_info = false;
  96374. if(decoder->private_->has_seek_table && 0 != decoder->private_->seek_table.data.seek_table.points) {
  96375. free(decoder->private_->seek_table.data.seek_table.points);
  96376. decoder->private_->seek_table.data.seek_table.points = 0;
  96377. decoder->private_->has_seek_table = false;
  96378. }
  96379. decoder->private_->do_md5_checking = decoder->protected_->md5_checking;
  96380. /*
  96381. * This goes in reset() and not flush() because according to the spec, a
  96382. * fixed-blocksize stream must stay that way through the whole stream.
  96383. */
  96384. decoder->private_->fixed_block_size = decoder->private_->next_fixed_block_size = 0;
  96385. /* We initialize the FLAC__MD5Context even though we may never use it. This
  96386. * is because md5 checking may be turned on to start and then turned off if
  96387. * a seek occurs. So we init the context here and finalize it in
  96388. * FLAC__stream_decoder_finish() to make sure things are always cleaned up
  96389. * properly.
  96390. */
  96391. FLAC__MD5Init(&decoder->private_->md5context);
  96392. decoder->private_->first_frame_offset = 0;
  96393. decoder->private_->unparseable_frame_count = 0;
  96394. return true;
  96395. }
  96396. FLAC_API FLAC__bool FLAC__stream_decoder_process_single(FLAC__StreamDecoder *decoder)
  96397. {
  96398. FLAC__bool got_a_frame;
  96399. FLAC__ASSERT(0 != decoder);
  96400. FLAC__ASSERT(0 != decoder->protected_);
  96401. while(1) {
  96402. switch(decoder->protected_->state) {
  96403. case FLAC__STREAM_DECODER_SEARCH_FOR_METADATA:
  96404. if(!find_metadata_(decoder))
  96405. return false; /* above function sets the status for us */
  96406. break;
  96407. case FLAC__STREAM_DECODER_READ_METADATA:
  96408. if(!read_metadata_(decoder))
  96409. return false; /* above function sets the status for us */
  96410. else
  96411. return true;
  96412. case FLAC__STREAM_DECODER_SEARCH_FOR_FRAME_SYNC:
  96413. if(!frame_sync_(decoder))
  96414. return true; /* above function sets the status for us */
  96415. break;
  96416. case FLAC__STREAM_DECODER_READ_FRAME:
  96417. if(!read_frame_(decoder, &got_a_frame, /*do_full_decode=*/true))
  96418. return false; /* above function sets the status for us */
  96419. if(got_a_frame)
  96420. return true; /* above function sets the status for us */
  96421. break;
  96422. case FLAC__STREAM_DECODER_END_OF_STREAM:
  96423. case FLAC__STREAM_DECODER_ABORTED:
  96424. return true;
  96425. default:
  96426. FLAC__ASSERT(0);
  96427. return false;
  96428. }
  96429. }
  96430. }
  96431. FLAC_API FLAC__bool FLAC__stream_decoder_process_until_end_of_metadata(FLAC__StreamDecoder *decoder)
  96432. {
  96433. FLAC__ASSERT(0 != decoder);
  96434. FLAC__ASSERT(0 != decoder->protected_);
  96435. while(1) {
  96436. switch(decoder->protected_->state) {
  96437. case FLAC__STREAM_DECODER_SEARCH_FOR_METADATA:
  96438. if(!find_metadata_(decoder))
  96439. return false; /* above function sets the status for us */
  96440. break;
  96441. case FLAC__STREAM_DECODER_READ_METADATA:
  96442. if(!read_metadata_(decoder))
  96443. return false; /* above function sets the status for us */
  96444. break;
  96445. case FLAC__STREAM_DECODER_SEARCH_FOR_FRAME_SYNC:
  96446. case FLAC__STREAM_DECODER_READ_FRAME:
  96447. case FLAC__STREAM_DECODER_END_OF_STREAM:
  96448. case FLAC__STREAM_DECODER_ABORTED:
  96449. return true;
  96450. default:
  96451. FLAC__ASSERT(0);
  96452. return false;
  96453. }
  96454. }
  96455. }
  96456. FLAC_API FLAC__bool FLAC__stream_decoder_process_until_end_of_stream(FLAC__StreamDecoder *decoder)
  96457. {
  96458. FLAC__bool dummy;
  96459. FLAC__ASSERT(0 != decoder);
  96460. FLAC__ASSERT(0 != decoder->protected_);
  96461. while(1) {
  96462. switch(decoder->protected_->state) {
  96463. case FLAC__STREAM_DECODER_SEARCH_FOR_METADATA:
  96464. if(!find_metadata_(decoder))
  96465. return false; /* above function sets the status for us */
  96466. break;
  96467. case FLAC__STREAM_DECODER_READ_METADATA:
  96468. if(!read_metadata_(decoder))
  96469. return false; /* above function sets the status for us */
  96470. break;
  96471. case FLAC__STREAM_DECODER_SEARCH_FOR_FRAME_SYNC:
  96472. if(!frame_sync_(decoder))
  96473. return true; /* above function sets the status for us */
  96474. break;
  96475. case FLAC__STREAM_DECODER_READ_FRAME:
  96476. if(!read_frame_(decoder, &dummy, /*do_full_decode=*/true))
  96477. return false; /* above function sets the status for us */
  96478. break;
  96479. case FLAC__STREAM_DECODER_END_OF_STREAM:
  96480. case FLAC__STREAM_DECODER_ABORTED:
  96481. return true;
  96482. default:
  96483. FLAC__ASSERT(0);
  96484. return false;
  96485. }
  96486. }
  96487. }
  96488. FLAC_API FLAC__bool FLAC__stream_decoder_skip_single_frame(FLAC__StreamDecoder *decoder)
  96489. {
  96490. FLAC__bool got_a_frame;
  96491. FLAC__ASSERT(0 != decoder);
  96492. FLAC__ASSERT(0 != decoder->protected_);
  96493. while(1) {
  96494. switch(decoder->protected_->state) {
  96495. case FLAC__STREAM_DECODER_SEARCH_FOR_METADATA:
  96496. case FLAC__STREAM_DECODER_READ_METADATA:
  96497. return false; /* above function sets the status for us */
  96498. case FLAC__STREAM_DECODER_SEARCH_FOR_FRAME_SYNC:
  96499. if(!frame_sync_(decoder))
  96500. return true; /* above function sets the status for us */
  96501. break;
  96502. case FLAC__STREAM_DECODER_READ_FRAME:
  96503. if(!read_frame_(decoder, &got_a_frame, /*do_full_decode=*/false))
  96504. return false; /* above function sets the status for us */
  96505. if(got_a_frame)
  96506. return true; /* above function sets the status for us */
  96507. break;
  96508. case FLAC__STREAM_DECODER_END_OF_STREAM:
  96509. case FLAC__STREAM_DECODER_ABORTED:
  96510. return true;
  96511. default:
  96512. FLAC__ASSERT(0);
  96513. return false;
  96514. }
  96515. }
  96516. }
  96517. FLAC_API FLAC__bool FLAC__stream_decoder_seek_absolute(FLAC__StreamDecoder *decoder, FLAC__uint64 sample)
  96518. {
  96519. FLAC__uint64 length;
  96520. FLAC__ASSERT(0 != decoder);
  96521. if(
  96522. decoder->protected_->state != FLAC__STREAM_DECODER_SEARCH_FOR_METADATA &&
  96523. decoder->protected_->state != FLAC__STREAM_DECODER_READ_METADATA &&
  96524. decoder->protected_->state != FLAC__STREAM_DECODER_SEARCH_FOR_FRAME_SYNC &&
  96525. decoder->protected_->state != FLAC__STREAM_DECODER_READ_FRAME &&
  96526. decoder->protected_->state != FLAC__STREAM_DECODER_END_OF_STREAM
  96527. )
  96528. return false;
  96529. if(0 == decoder->private_->seek_callback)
  96530. return false;
  96531. FLAC__ASSERT(decoder->private_->seek_callback);
  96532. FLAC__ASSERT(decoder->private_->tell_callback);
  96533. FLAC__ASSERT(decoder->private_->length_callback);
  96534. FLAC__ASSERT(decoder->private_->eof_callback);
  96535. if(FLAC__stream_decoder_get_total_samples(decoder) > 0 && sample >= FLAC__stream_decoder_get_total_samples(decoder))
  96536. return false;
  96537. decoder->private_->is_seeking = true;
  96538. /* turn off md5 checking if a seek is attempted */
  96539. decoder->private_->do_md5_checking = false;
  96540. /* 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) */
  96541. if(decoder->private_->length_callback(decoder, &length, decoder->private_->client_data) != FLAC__STREAM_DECODER_LENGTH_STATUS_OK) {
  96542. decoder->private_->is_seeking = false;
  96543. return false;
  96544. }
  96545. /* if we haven't finished processing the metadata yet, do that so we have the STREAMINFO, SEEK_TABLE, and first_frame_offset */
  96546. if(
  96547. decoder->protected_->state == FLAC__STREAM_DECODER_SEARCH_FOR_METADATA ||
  96548. decoder->protected_->state == FLAC__STREAM_DECODER_READ_METADATA
  96549. ) {
  96550. if(!FLAC__stream_decoder_process_until_end_of_metadata(decoder)) {
  96551. /* above call sets the state for us */
  96552. decoder->private_->is_seeking = false;
  96553. return false;
  96554. }
  96555. /* check this again in case we didn't know total_samples the first time */
  96556. if(FLAC__stream_decoder_get_total_samples(decoder) > 0 && sample >= FLAC__stream_decoder_get_total_samples(decoder)) {
  96557. decoder->private_->is_seeking = false;
  96558. return false;
  96559. }
  96560. }
  96561. {
  96562. const FLAC__bool ok =
  96563. #if FLAC__HAS_OGG
  96564. decoder->private_->is_ogg?
  96565. seek_to_absolute_sample_ogg_(decoder, length, sample) :
  96566. #endif
  96567. seek_to_absolute_sample_(decoder, length, sample)
  96568. ;
  96569. decoder->private_->is_seeking = false;
  96570. return ok;
  96571. }
  96572. }
  96573. /***********************************************************************
  96574. *
  96575. * Protected class methods
  96576. *
  96577. ***********************************************************************/
  96578. unsigned FLAC__stream_decoder_get_input_bytes_unconsumed(const FLAC__StreamDecoder *decoder)
  96579. {
  96580. FLAC__ASSERT(0 != decoder);
  96581. FLAC__ASSERT(FLAC__bitreader_is_consumed_byte_aligned(decoder->private_->input));
  96582. FLAC__ASSERT(!(FLAC__bitreader_get_input_bits_unconsumed(decoder->private_->input) & 7));
  96583. return FLAC__bitreader_get_input_bits_unconsumed(decoder->private_->input) / 8;
  96584. }
  96585. /***********************************************************************
  96586. *
  96587. * Private class methods
  96588. *
  96589. ***********************************************************************/
  96590. void set_defaults_dec(FLAC__StreamDecoder *decoder)
  96591. {
  96592. #if FLAC__HAS_OGG
  96593. decoder->private_->is_ogg = false;
  96594. #endif
  96595. decoder->private_->read_callback = 0;
  96596. decoder->private_->seek_callback = 0;
  96597. decoder->private_->tell_callback = 0;
  96598. decoder->private_->length_callback = 0;
  96599. decoder->private_->eof_callback = 0;
  96600. decoder->private_->write_callback = 0;
  96601. decoder->private_->metadata_callback = 0;
  96602. decoder->private_->error_callback = 0;
  96603. decoder->private_->client_data = 0;
  96604. memset(decoder->private_->metadata_filter, 0, sizeof(decoder->private_->metadata_filter));
  96605. decoder->private_->metadata_filter[FLAC__METADATA_TYPE_STREAMINFO] = true;
  96606. decoder->private_->metadata_filter_ids_count = 0;
  96607. decoder->protected_->md5_checking = false;
  96608. #if FLAC__HAS_OGG
  96609. FLAC__ogg_decoder_aspect_set_defaults(&decoder->protected_->ogg_decoder_aspect);
  96610. #endif
  96611. }
  96612. /*
  96613. * This will forcibly set stdin to binary mode (for OSes that require it)
  96614. */
  96615. FILE *get_binary_stdin_(void)
  96616. {
  96617. /* if something breaks here it is probably due to the presence or
  96618. * absence of an underscore before the identifiers 'setmode',
  96619. * 'fileno', and/or 'O_BINARY'; check your system header files.
  96620. */
  96621. #if defined _MSC_VER || defined __MINGW32__
  96622. _setmode(_fileno(stdin), _O_BINARY);
  96623. #elif defined __CYGWIN__
  96624. /* almost certainly not needed for any modern Cygwin, but let's be safe... */
  96625. setmode(_fileno(stdin), _O_BINARY);
  96626. #elif defined __EMX__
  96627. setmode(fileno(stdin), O_BINARY);
  96628. #endif
  96629. return stdin;
  96630. }
  96631. FLAC__bool allocate_output_(FLAC__StreamDecoder *decoder, unsigned size, unsigned channels)
  96632. {
  96633. unsigned i;
  96634. FLAC__int32 *tmp;
  96635. if(size <= decoder->private_->output_capacity && channels <= decoder->private_->output_channels)
  96636. return true;
  96637. /* simply using realloc() is not practical because the number of channels may change mid-stream */
  96638. for(i = 0; i < FLAC__MAX_CHANNELS; i++) {
  96639. if(0 != decoder->private_->output[i]) {
  96640. free(decoder->private_->output[i]-4);
  96641. decoder->private_->output[i] = 0;
  96642. }
  96643. if(0 != decoder->private_->residual_unaligned[i]) {
  96644. free(decoder->private_->residual_unaligned[i]);
  96645. decoder->private_->residual_unaligned[i] = decoder->private_->residual[i] = 0;
  96646. }
  96647. }
  96648. for(i = 0; i < channels; i++) {
  96649. /* WATCHOUT:
  96650. * FLAC__lpc_restore_signal_asm_ia32_mmx() requires that the
  96651. * output arrays have a buffer of up to 3 zeroes in front
  96652. * (at negative indices) for alignment purposes; we use 4
  96653. * to keep the data well-aligned.
  96654. */
  96655. tmp = (FLAC__int32*)safe_malloc_muladd2_(sizeof(FLAC__int32), /*times (*/size, /*+*/4/*)*/);
  96656. if(tmp == 0) {
  96657. decoder->protected_->state = FLAC__STREAM_DECODER_MEMORY_ALLOCATION_ERROR;
  96658. return false;
  96659. }
  96660. memset(tmp, 0, sizeof(FLAC__int32)*4);
  96661. decoder->private_->output[i] = tmp + 4;
  96662. /* WATCHOUT:
  96663. * minimum of quadword alignment for PPC vector optimizations is REQUIRED:
  96664. */
  96665. if(!FLAC__memory_alloc_aligned_int32_array(size, &decoder->private_->residual_unaligned[i], &decoder->private_->residual[i])) {
  96666. decoder->protected_->state = FLAC__STREAM_DECODER_MEMORY_ALLOCATION_ERROR;
  96667. return false;
  96668. }
  96669. }
  96670. decoder->private_->output_capacity = size;
  96671. decoder->private_->output_channels = channels;
  96672. return true;
  96673. }
  96674. FLAC__bool has_id_filtered_(FLAC__StreamDecoder *decoder, FLAC__byte *id)
  96675. {
  96676. size_t i;
  96677. FLAC__ASSERT(0 != decoder);
  96678. FLAC__ASSERT(0 != decoder->private_);
  96679. for(i = 0; i < decoder->private_->metadata_filter_ids_count; i++)
  96680. if(0 == memcmp(decoder->private_->metadata_filter_ids + i * (FLAC__STREAM_METADATA_APPLICATION_ID_LEN/8), id, (FLAC__STREAM_METADATA_APPLICATION_ID_LEN/8)))
  96681. return true;
  96682. return false;
  96683. }
  96684. FLAC__bool find_metadata_(FLAC__StreamDecoder *decoder)
  96685. {
  96686. FLAC__uint32 x;
  96687. unsigned i, id_;
  96688. FLAC__bool first = true;
  96689. FLAC__ASSERT(FLAC__bitreader_is_consumed_byte_aligned(decoder->private_->input));
  96690. for(i = id_ = 0; i < 4; ) {
  96691. if(decoder->private_->cached) {
  96692. x = (FLAC__uint32)decoder->private_->lookahead;
  96693. decoder->private_->cached = false;
  96694. }
  96695. else {
  96696. if(!FLAC__bitreader_read_raw_uint32(decoder->private_->input, &x, 8))
  96697. return false; /* read_callback_ sets the state for us */
  96698. }
  96699. if(x == FLAC__STREAM_SYNC_STRING[i]) {
  96700. first = true;
  96701. i++;
  96702. id_ = 0;
  96703. continue;
  96704. }
  96705. if(x == ID3V2_TAG_[id_]) {
  96706. id_++;
  96707. i = 0;
  96708. if(id_ == 3) {
  96709. if(!skip_id3v2_tag_(decoder))
  96710. return false; /* skip_id3v2_tag_ sets the state for us */
  96711. }
  96712. continue;
  96713. }
  96714. id_ = 0;
  96715. if(x == 0xff) { /* MAGIC NUMBER for the first 8 frame sync bits */
  96716. decoder->private_->header_warmup[0] = (FLAC__byte)x;
  96717. if(!FLAC__bitreader_read_raw_uint32(decoder->private_->input, &x, 8))
  96718. return false; /* read_callback_ sets the state for us */
  96719. /* 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 */
  96720. /* else we have to check if the second byte is the end of a sync code */
  96721. if(x == 0xff) { /* MAGIC NUMBER for the first 8 frame sync bits */
  96722. decoder->private_->lookahead = (FLAC__byte)x;
  96723. decoder->private_->cached = true;
  96724. }
  96725. else if(x >> 2 == 0x3e) { /* MAGIC NUMBER for the last 6 sync bits */
  96726. decoder->private_->header_warmup[1] = (FLAC__byte)x;
  96727. decoder->protected_->state = FLAC__STREAM_DECODER_READ_FRAME;
  96728. return true;
  96729. }
  96730. }
  96731. i = 0;
  96732. if(first) {
  96733. send_error_to_client_(decoder, FLAC__STREAM_DECODER_ERROR_STATUS_LOST_SYNC);
  96734. first = false;
  96735. }
  96736. }
  96737. decoder->protected_->state = FLAC__STREAM_DECODER_READ_METADATA;
  96738. return true;
  96739. }
  96740. FLAC__bool read_metadata_(FLAC__StreamDecoder *decoder)
  96741. {
  96742. FLAC__bool is_last;
  96743. FLAC__uint32 i, x, type, length;
  96744. FLAC__ASSERT(FLAC__bitreader_is_consumed_byte_aligned(decoder->private_->input));
  96745. if(!FLAC__bitreader_read_raw_uint32(decoder->private_->input, &x, FLAC__STREAM_METADATA_IS_LAST_LEN))
  96746. return false; /* read_callback_ sets the state for us */
  96747. is_last = x? true : false;
  96748. if(!FLAC__bitreader_read_raw_uint32(decoder->private_->input, &type, FLAC__STREAM_METADATA_TYPE_LEN))
  96749. return false; /* read_callback_ sets the state for us */
  96750. if(!FLAC__bitreader_read_raw_uint32(decoder->private_->input, &length, FLAC__STREAM_METADATA_LENGTH_LEN))
  96751. return false; /* read_callback_ sets the state for us */
  96752. if(type == FLAC__METADATA_TYPE_STREAMINFO) {
  96753. if(!read_metadata_streaminfo_(decoder, is_last, length))
  96754. return false;
  96755. decoder->private_->has_stream_info = true;
  96756. 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))
  96757. decoder->private_->do_md5_checking = false;
  96758. if(!decoder->private_->is_seeking && decoder->private_->metadata_filter[FLAC__METADATA_TYPE_STREAMINFO] && decoder->private_->metadata_callback)
  96759. decoder->private_->metadata_callback(decoder, &decoder->private_->stream_info, decoder->private_->client_data);
  96760. }
  96761. else if(type == FLAC__METADATA_TYPE_SEEKTABLE) {
  96762. if(!read_metadata_seektable_(decoder, is_last, length))
  96763. return false;
  96764. decoder->private_->has_seek_table = true;
  96765. if(!decoder->private_->is_seeking && decoder->private_->metadata_filter[FLAC__METADATA_TYPE_SEEKTABLE] && decoder->private_->metadata_callback)
  96766. decoder->private_->metadata_callback(decoder, &decoder->private_->seek_table, decoder->private_->client_data);
  96767. }
  96768. else {
  96769. FLAC__bool skip_it = !decoder->private_->metadata_filter[type];
  96770. unsigned real_length = length;
  96771. FLAC__StreamMetadata block;
  96772. block.is_last = is_last;
  96773. block.type = (FLAC__MetadataType)type;
  96774. block.length = length;
  96775. if(type == FLAC__METADATA_TYPE_APPLICATION) {
  96776. if(!FLAC__bitreader_read_byte_block_aligned_no_crc(decoder->private_->input, block.data.application.id, FLAC__STREAM_METADATA_APPLICATION_ID_LEN/8))
  96777. return false; /* read_callback_ sets the state for us */
  96778. if(real_length < FLAC__STREAM_METADATA_APPLICATION_ID_LEN/8) { /* underflow check */
  96779. decoder->protected_->state = FLAC__STREAM_DECODER_MEMORY_ALLOCATION_ERROR;/*@@@@@@ maybe wrong error? need to resync?*/
  96780. return false;
  96781. }
  96782. real_length -= FLAC__STREAM_METADATA_APPLICATION_ID_LEN/8;
  96783. if(decoder->private_->metadata_filter_ids_count > 0 && has_id_filtered_(decoder, block.data.application.id))
  96784. skip_it = !skip_it;
  96785. }
  96786. if(skip_it) {
  96787. if(!FLAC__bitreader_skip_byte_block_aligned_no_crc(decoder->private_->input, real_length))
  96788. return false; /* read_callback_ sets the state for us */
  96789. }
  96790. else {
  96791. switch(type) {
  96792. case FLAC__METADATA_TYPE_PADDING:
  96793. /* skip the padding bytes */
  96794. if(!FLAC__bitreader_skip_byte_block_aligned_no_crc(decoder->private_->input, real_length))
  96795. return false; /* read_callback_ sets the state for us */
  96796. break;
  96797. case FLAC__METADATA_TYPE_APPLICATION:
  96798. /* remember, we read the ID already */
  96799. if(real_length > 0) {
  96800. if(0 == (block.data.application.data = (FLAC__byte*)malloc(real_length))) {
  96801. decoder->protected_->state = FLAC__STREAM_DECODER_MEMORY_ALLOCATION_ERROR;
  96802. return false;
  96803. }
  96804. if(!FLAC__bitreader_read_byte_block_aligned_no_crc(decoder->private_->input, block.data.application.data, real_length))
  96805. return false; /* read_callback_ sets the state for us */
  96806. }
  96807. else
  96808. block.data.application.data = 0;
  96809. break;
  96810. case FLAC__METADATA_TYPE_VORBIS_COMMENT:
  96811. if(!read_metadata_vorbiscomment_(decoder, &block.data.vorbis_comment))
  96812. return false;
  96813. break;
  96814. case FLAC__METADATA_TYPE_CUESHEET:
  96815. if(!read_metadata_cuesheet_(decoder, &block.data.cue_sheet))
  96816. return false;
  96817. break;
  96818. case FLAC__METADATA_TYPE_PICTURE:
  96819. if(!read_metadata_picture_(decoder, &block.data.picture))
  96820. return false;
  96821. break;
  96822. case FLAC__METADATA_TYPE_STREAMINFO:
  96823. case FLAC__METADATA_TYPE_SEEKTABLE:
  96824. FLAC__ASSERT(0);
  96825. break;
  96826. default:
  96827. if(real_length > 0) {
  96828. if(0 == (block.data.unknown.data = (FLAC__byte*)malloc(real_length))) {
  96829. decoder->protected_->state = FLAC__STREAM_DECODER_MEMORY_ALLOCATION_ERROR;
  96830. return false;
  96831. }
  96832. if(!FLAC__bitreader_read_byte_block_aligned_no_crc(decoder->private_->input, block.data.unknown.data, real_length))
  96833. return false; /* read_callback_ sets the state for us */
  96834. }
  96835. else
  96836. block.data.unknown.data = 0;
  96837. break;
  96838. }
  96839. if(!decoder->private_->is_seeking && decoder->private_->metadata_callback)
  96840. decoder->private_->metadata_callback(decoder, &block, decoder->private_->client_data);
  96841. /* now we have to free any malloc()ed data in the block */
  96842. switch(type) {
  96843. case FLAC__METADATA_TYPE_PADDING:
  96844. break;
  96845. case FLAC__METADATA_TYPE_APPLICATION:
  96846. if(0 != block.data.application.data)
  96847. free(block.data.application.data);
  96848. break;
  96849. case FLAC__METADATA_TYPE_VORBIS_COMMENT:
  96850. if(0 != block.data.vorbis_comment.vendor_string.entry)
  96851. free(block.data.vorbis_comment.vendor_string.entry);
  96852. if(block.data.vorbis_comment.num_comments > 0)
  96853. for(i = 0; i < block.data.vorbis_comment.num_comments; i++)
  96854. if(0 != block.data.vorbis_comment.comments[i].entry)
  96855. free(block.data.vorbis_comment.comments[i].entry);
  96856. if(0 != block.data.vorbis_comment.comments)
  96857. free(block.data.vorbis_comment.comments);
  96858. break;
  96859. case FLAC__METADATA_TYPE_CUESHEET:
  96860. if(block.data.cue_sheet.num_tracks > 0)
  96861. for(i = 0; i < block.data.cue_sheet.num_tracks; i++)
  96862. if(0 != block.data.cue_sheet.tracks[i].indices)
  96863. free(block.data.cue_sheet.tracks[i].indices);
  96864. if(0 != block.data.cue_sheet.tracks)
  96865. free(block.data.cue_sheet.tracks);
  96866. break;
  96867. case FLAC__METADATA_TYPE_PICTURE:
  96868. if(0 != block.data.picture.mime_type)
  96869. free(block.data.picture.mime_type);
  96870. if(0 != block.data.picture.description)
  96871. free(block.data.picture.description);
  96872. if(0 != block.data.picture.data)
  96873. free(block.data.picture.data);
  96874. break;
  96875. case FLAC__METADATA_TYPE_STREAMINFO:
  96876. case FLAC__METADATA_TYPE_SEEKTABLE:
  96877. FLAC__ASSERT(0);
  96878. default:
  96879. if(0 != block.data.unknown.data)
  96880. free(block.data.unknown.data);
  96881. break;
  96882. }
  96883. }
  96884. }
  96885. if(is_last) {
  96886. /* if this fails, it's OK, it's just a hint for the seek routine */
  96887. if(!FLAC__stream_decoder_get_decode_position(decoder, &decoder->private_->first_frame_offset))
  96888. decoder->private_->first_frame_offset = 0;
  96889. decoder->protected_->state = FLAC__STREAM_DECODER_SEARCH_FOR_FRAME_SYNC;
  96890. }
  96891. return true;
  96892. }
  96893. FLAC__bool read_metadata_streaminfo_(FLAC__StreamDecoder *decoder, FLAC__bool is_last, unsigned length)
  96894. {
  96895. FLAC__uint32 x;
  96896. unsigned bits, used_bits = 0;
  96897. FLAC__ASSERT(FLAC__bitreader_is_consumed_byte_aligned(decoder->private_->input));
  96898. decoder->private_->stream_info.type = FLAC__METADATA_TYPE_STREAMINFO;
  96899. decoder->private_->stream_info.is_last = is_last;
  96900. decoder->private_->stream_info.length = length;
  96901. bits = FLAC__STREAM_METADATA_STREAMINFO_MIN_BLOCK_SIZE_LEN;
  96902. if(!FLAC__bitreader_read_raw_uint32(decoder->private_->input, &x, bits))
  96903. return false; /* read_callback_ sets the state for us */
  96904. decoder->private_->stream_info.data.stream_info.min_blocksize = x;
  96905. used_bits += bits;
  96906. bits = FLAC__STREAM_METADATA_STREAMINFO_MAX_BLOCK_SIZE_LEN;
  96907. if(!FLAC__bitreader_read_raw_uint32(decoder->private_->input, &x, FLAC__STREAM_METADATA_STREAMINFO_MAX_BLOCK_SIZE_LEN))
  96908. return false; /* read_callback_ sets the state for us */
  96909. decoder->private_->stream_info.data.stream_info.max_blocksize = x;
  96910. used_bits += bits;
  96911. bits = FLAC__STREAM_METADATA_STREAMINFO_MIN_FRAME_SIZE_LEN;
  96912. if(!FLAC__bitreader_read_raw_uint32(decoder->private_->input, &x, FLAC__STREAM_METADATA_STREAMINFO_MIN_FRAME_SIZE_LEN))
  96913. return false; /* read_callback_ sets the state for us */
  96914. decoder->private_->stream_info.data.stream_info.min_framesize = x;
  96915. used_bits += bits;
  96916. bits = FLAC__STREAM_METADATA_STREAMINFO_MAX_FRAME_SIZE_LEN;
  96917. if(!FLAC__bitreader_read_raw_uint32(decoder->private_->input, &x, FLAC__STREAM_METADATA_STREAMINFO_MAX_FRAME_SIZE_LEN))
  96918. return false; /* read_callback_ sets the state for us */
  96919. decoder->private_->stream_info.data.stream_info.max_framesize = x;
  96920. used_bits += bits;
  96921. bits = FLAC__STREAM_METADATA_STREAMINFO_SAMPLE_RATE_LEN;
  96922. if(!FLAC__bitreader_read_raw_uint32(decoder->private_->input, &x, FLAC__STREAM_METADATA_STREAMINFO_SAMPLE_RATE_LEN))
  96923. return false; /* read_callback_ sets the state for us */
  96924. decoder->private_->stream_info.data.stream_info.sample_rate = x;
  96925. used_bits += bits;
  96926. bits = FLAC__STREAM_METADATA_STREAMINFO_CHANNELS_LEN;
  96927. if(!FLAC__bitreader_read_raw_uint32(decoder->private_->input, &x, FLAC__STREAM_METADATA_STREAMINFO_CHANNELS_LEN))
  96928. return false; /* read_callback_ sets the state for us */
  96929. decoder->private_->stream_info.data.stream_info.channels = x+1;
  96930. used_bits += bits;
  96931. bits = FLAC__STREAM_METADATA_STREAMINFO_BITS_PER_SAMPLE_LEN;
  96932. if(!FLAC__bitreader_read_raw_uint32(decoder->private_->input, &x, FLAC__STREAM_METADATA_STREAMINFO_BITS_PER_SAMPLE_LEN))
  96933. return false; /* read_callback_ sets the state for us */
  96934. decoder->private_->stream_info.data.stream_info.bits_per_sample = x+1;
  96935. used_bits += bits;
  96936. bits = FLAC__STREAM_METADATA_STREAMINFO_TOTAL_SAMPLES_LEN;
  96937. 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))
  96938. return false; /* read_callback_ sets the state for us */
  96939. used_bits += bits;
  96940. if(!FLAC__bitreader_read_byte_block_aligned_no_crc(decoder->private_->input, decoder->private_->stream_info.data.stream_info.md5sum, 16))
  96941. return false; /* read_callback_ sets the state for us */
  96942. used_bits += 16*8;
  96943. /* skip the rest of the block */
  96944. FLAC__ASSERT(used_bits % 8 == 0);
  96945. length -= (used_bits / 8);
  96946. if(!FLAC__bitreader_skip_byte_block_aligned_no_crc(decoder->private_->input, length))
  96947. return false; /* read_callback_ sets the state for us */
  96948. return true;
  96949. }
  96950. FLAC__bool read_metadata_seektable_(FLAC__StreamDecoder *decoder, FLAC__bool is_last, unsigned length)
  96951. {
  96952. FLAC__uint32 i, x;
  96953. FLAC__uint64 xx;
  96954. FLAC__ASSERT(FLAC__bitreader_is_consumed_byte_aligned(decoder->private_->input));
  96955. decoder->private_->seek_table.type = FLAC__METADATA_TYPE_SEEKTABLE;
  96956. decoder->private_->seek_table.is_last = is_last;
  96957. decoder->private_->seek_table.length = length;
  96958. decoder->private_->seek_table.data.seek_table.num_points = length / FLAC__STREAM_METADATA_SEEKPOINT_LENGTH;
  96959. /* use realloc since we may pass through here several times (e.g. after seeking) */
  96960. 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)))) {
  96961. decoder->protected_->state = FLAC__STREAM_DECODER_MEMORY_ALLOCATION_ERROR;
  96962. return false;
  96963. }
  96964. for(i = 0; i < decoder->private_->seek_table.data.seek_table.num_points; i++) {
  96965. if(!FLAC__bitreader_read_raw_uint64(decoder->private_->input, &xx, FLAC__STREAM_METADATA_SEEKPOINT_SAMPLE_NUMBER_LEN))
  96966. return false; /* read_callback_ sets the state for us */
  96967. decoder->private_->seek_table.data.seek_table.points[i].sample_number = xx;
  96968. if(!FLAC__bitreader_read_raw_uint64(decoder->private_->input, &xx, FLAC__STREAM_METADATA_SEEKPOINT_STREAM_OFFSET_LEN))
  96969. return false; /* read_callback_ sets the state for us */
  96970. decoder->private_->seek_table.data.seek_table.points[i].stream_offset = xx;
  96971. if(!FLAC__bitreader_read_raw_uint32(decoder->private_->input, &x, FLAC__STREAM_METADATA_SEEKPOINT_FRAME_SAMPLES_LEN))
  96972. return false; /* read_callback_ sets the state for us */
  96973. decoder->private_->seek_table.data.seek_table.points[i].frame_samples = x;
  96974. }
  96975. length -= (decoder->private_->seek_table.data.seek_table.num_points * FLAC__STREAM_METADATA_SEEKPOINT_LENGTH);
  96976. /* if there is a partial point left, skip over it */
  96977. if(length > 0) {
  96978. /*@@@ do a send_error_to_client_() here? there's an argument for either way */
  96979. if(!FLAC__bitreader_skip_byte_block_aligned_no_crc(decoder->private_->input, length))
  96980. return false; /* read_callback_ sets the state for us */
  96981. }
  96982. return true;
  96983. }
  96984. FLAC__bool read_metadata_vorbiscomment_(FLAC__StreamDecoder *decoder, FLAC__StreamMetadata_VorbisComment *obj)
  96985. {
  96986. FLAC__uint32 i;
  96987. FLAC__ASSERT(FLAC__bitreader_is_consumed_byte_aligned(decoder->private_->input));
  96988. /* read vendor string */
  96989. FLAC__ASSERT(FLAC__STREAM_METADATA_VORBIS_COMMENT_ENTRY_LENGTH_LEN == 32);
  96990. if(!FLAC__bitreader_read_uint32_little_endian(decoder->private_->input, &obj->vendor_string.length))
  96991. return false; /* read_callback_ sets the state for us */
  96992. if(obj->vendor_string.length > 0) {
  96993. if(0 == (obj->vendor_string.entry = (FLAC__byte*)safe_malloc_add_2op_(obj->vendor_string.length, /*+*/1))) {
  96994. decoder->protected_->state = FLAC__STREAM_DECODER_MEMORY_ALLOCATION_ERROR;
  96995. return false;
  96996. }
  96997. if(!FLAC__bitreader_read_byte_block_aligned_no_crc(decoder->private_->input, obj->vendor_string.entry, obj->vendor_string.length))
  96998. return false; /* read_callback_ sets the state for us */
  96999. obj->vendor_string.entry[obj->vendor_string.length] = '\0';
  97000. }
  97001. else
  97002. obj->vendor_string.entry = 0;
  97003. /* read num comments */
  97004. FLAC__ASSERT(FLAC__STREAM_METADATA_VORBIS_COMMENT_NUM_COMMENTS_LEN == 32);
  97005. if(!FLAC__bitreader_read_uint32_little_endian(decoder->private_->input, &obj->num_comments))
  97006. return false; /* read_callback_ sets the state for us */
  97007. /* read comments */
  97008. if(obj->num_comments > 0) {
  97009. if(0 == (obj->comments = (FLAC__StreamMetadata_VorbisComment_Entry*)safe_malloc_mul_2op_(obj->num_comments, /*times*/sizeof(FLAC__StreamMetadata_VorbisComment_Entry)))) {
  97010. decoder->protected_->state = FLAC__STREAM_DECODER_MEMORY_ALLOCATION_ERROR;
  97011. return false;
  97012. }
  97013. for(i = 0; i < obj->num_comments; i++) {
  97014. FLAC__ASSERT(FLAC__STREAM_METADATA_VORBIS_COMMENT_ENTRY_LENGTH_LEN == 32);
  97015. if(!FLAC__bitreader_read_uint32_little_endian(decoder->private_->input, &obj->comments[i].length))
  97016. return false; /* read_callback_ sets the state for us */
  97017. if(obj->comments[i].length > 0) {
  97018. if(0 == (obj->comments[i].entry = (FLAC__byte*)safe_malloc_add_2op_(obj->comments[i].length, /*+*/1))) {
  97019. decoder->protected_->state = FLAC__STREAM_DECODER_MEMORY_ALLOCATION_ERROR;
  97020. return false;
  97021. }
  97022. if(!FLAC__bitreader_read_byte_block_aligned_no_crc(decoder->private_->input, obj->comments[i].entry, obj->comments[i].length))
  97023. return false; /* read_callback_ sets the state for us */
  97024. obj->comments[i].entry[obj->comments[i].length] = '\0';
  97025. }
  97026. else
  97027. obj->comments[i].entry = 0;
  97028. }
  97029. }
  97030. else {
  97031. obj->comments = 0;
  97032. }
  97033. return true;
  97034. }
  97035. FLAC__bool read_metadata_cuesheet_(FLAC__StreamDecoder *decoder, FLAC__StreamMetadata_CueSheet *obj)
  97036. {
  97037. FLAC__uint32 i, j, x;
  97038. FLAC__ASSERT(FLAC__bitreader_is_consumed_byte_aligned(decoder->private_->input));
  97039. memset(obj, 0, sizeof(FLAC__StreamMetadata_CueSheet));
  97040. FLAC__ASSERT(FLAC__STREAM_METADATA_CUESHEET_MEDIA_CATALOG_NUMBER_LEN % 8 == 0);
  97041. 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))
  97042. return false; /* read_callback_ sets the state for us */
  97043. if(!FLAC__bitreader_read_raw_uint64(decoder->private_->input, &obj->lead_in, FLAC__STREAM_METADATA_CUESHEET_LEAD_IN_LEN))
  97044. return false; /* read_callback_ sets the state for us */
  97045. if(!FLAC__bitreader_read_raw_uint32(decoder->private_->input, &x, FLAC__STREAM_METADATA_CUESHEET_IS_CD_LEN))
  97046. return false; /* read_callback_ sets the state for us */
  97047. obj->is_cd = x? true : false;
  97048. if(!FLAC__bitreader_skip_bits_no_crc(decoder->private_->input, FLAC__STREAM_METADATA_CUESHEET_RESERVED_LEN))
  97049. return false; /* read_callback_ sets the state for us */
  97050. if(!FLAC__bitreader_read_raw_uint32(decoder->private_->input, &x, FLAC__STREAM_METADATA_CUESHEET_NUM_TRACKS_LEN))
  97051. return false; /* read_callback_ sets the state for us */
  97052. obj->num_tracks = x;
  97053. if(obj->num_tracks > 0) {
  97054. if(0 == (obj->tracks = (FLAC__StreamMetadata_CueSheet_Track*)safe_calloc_(obj->num_tracks, sizeof(FLAC__StreamMetadata_CueSheet_Track)))) {
  97055. decoder->protected_->state = FLAC__STREAM_DECODER_MEMORY_ALLOCATION_ERROR;
  97056. return false;
  97057. }
  97058. for(i = 0; i < obj->num_tracks; i++) {
  97059. FLAC__StreamMetadata_CueSheet_Track *track = &obj->tracks[i];
  97060. if(!FLAC__bitreader_read_raw_uint64(decoder->private_->input, &track->offset, FLAC__STREAM_METADATA_CUESHEET_TRACK_OFFSET_LEN))
  97061. return false; /* read_callback_ sets the state for us */
  97062. if(!FLAC__bitreader_read_raw_uint32(decoder->private_->input, &x, FLAC__STREAM_METADATA_CUESHEET_TRACK_NUMBER_LEN))
  97063. return false; /* read_callback_ sets the state for us */
  97064. track->number = (FLAC__byte)x;
  97065. FLAC__ASSERT(FLAC__STREAM_METADATA_CUESHEET_TRACK_ISRC_LEN % 8 == 0);
  97066. if(!FLAC__bitreader_read_byte_block_aligned_no_crc(decoder->private_->input, (FLAC__byte*)track->isrc, FLAC__STREAM_METADATA_CUESHEET_TRACK_ISRC_LEN/8))
  97067. return false; /* read_callback_ sets the state for us */
  97068. if(!FLAC__bitreader_read_raw_uint32(decoder->private_->input, &x, FLAC__STREAM_METADATA_CUESHEET_TRACK_TYPE_LEN))
  97069. return false; /* read_callback_ sets the state for us */
  97070. track->type = x;
  97071. if(!FLAC__bitreader_read_raw_uint32(decoder->private_->input, &x, FLAC__STREAM_METADATA_CUESHEET_TRACK_PRE_EMPHASIS_LEN))
  97072. return false; /* read_callback_ sets the state for us */
  97073. track->pre_emphasis = x;
  97074. if(!FLAC__bitreader_skip_bits_no_crc(decoder->private_->input, FLAC__STREAM_METADATA_CUESHEET_TRACK_RESERVED_LEN))
  97075. return false; /* read_callback_ sets the state for us */
  97076. if(!FLAC__bitreader_read_raw_uint32(decoder->private_->input, &x, FLAC__STREAM_METADATA_CUESHEET_TRACK_NUM_INDICES_LEN))
  97077. return false; /* read_callback_ sets the state for us */
  97078. track->num_indices = (FLAC__byte)x;
  97079. if(track->num_indices > 0) {
  97080. if(0 == (track->indices = (FLAC__StreamMetadata_CueSheet_Index*)safe_calloc_(track->num_indices, sizeof(FLAC__StreamMetadata_CueSheet_Index)))) {
  97081. decoder->protected_->state = FLAC__STREAM_DECODER_MEMORY_ALLOCATION_ERROR;
  97082. return false;
  97083. }
  97084. for(j = 0; j < track->num_indices; j++) {
  97085. FLAC__StreamMetadata_CueSheet_Index *index = &track->indices[j];
  97086. if(!FLAC__bitreader_read_raw_uint64(decoder->private_->input, &index->offset, FLAC__STREAM_METADATA_CUESHEET_INDEX_OFFSET_LEN))
  97087. return false; /* read_callback_ sets the state for us */
  97088. if(!FLAC__bitreader_read_raw_uint32(decoder->private_->input, &x, FLAC__STREAM_METADATA_CUESHEET_INDEX_NUMBER_LEN))
  97089. return false; /* read_callback_ sets the state for us */
  97090. index->number = (FLAC__byte)x;
  97091. if(!FLAC__bitreader_skip_bits_no_crc(decoder->private_->input, FLAC__STREAM_METADATA_CUESHEET_INDEX_RESERVED_LEN))
  97092. return false; /* read_callback_ sets the state for us */
  97093. }
  97094. }
  97095. }
  97096. }
  97097. return true;
  97098. }
  97099. FLAC__bool read_metadata_picture_(FLAC__StreamDecoder *decoder, FLAC__StreamMetadata_Picture *obj)
  97100. {
  97101. FLAC__uint32 x;
  97102. FLAC__ASSERT(FLAC__bitreader_is_consumed_byte_aligned(decoder->private_->input));
  97103. /* read type */
  97104. if(!FLAC__bitreader_read_raw_uint32(decoder->private_->input, &x, FLAC__STREAM_METADATA_PICTURE_TYPE_LEN))
  97105. return false; /* read_callback_ sets the state for us */
  97106. obj->type = (FLAC__StreamMetadata_Picture_Type) x;
  97107. /* read MIME type */
  97108. if(!FLAC__bitreader_read_raw_uint32(decoder->private_->input, &x, FLAC__STREAM_METADATA_PICTURE_MIME_TYPE_LENGTH_LEN))
  97109. return false; /* read_callback_ sets the state for us */
  97110. if(0 == (obj->mime_type = (char*)safe_malloc_add_2op_(x, /*+*/1))) {
  97111. decoder->protected_->state = FLAC__STREAM_DECODER_MEMORY_ALLOCATION_ERROR;
  97112. return false;
  97113. }
  97114. if(x > 0) {
  97115. if(!FLAC__bitreader_read_byte_block_aligned_no_crc(decoder->private_->input, (FLAC__byte*)obj->mime_type, x))
  97116. return false; /* read_callback_ sets the state for us */
  97117. }
  97118. obj->mime_type[x] = '\0';
  97119. /* read description */
  97120. if(!FLAC__bitreader_read_raw_uint32(decoder->private_->input, &x, FLAC__STREAM_METADATA_PICTURE_DESCRIPTION_LENGTH_LEN))
  97121. return false; /* read_callback_ sets the state for us */
  97122. if(0 == (obj->description = (FLAC__byte*)safe_malloc_add_2op_(x, /*+*/1))) {
  97123. decoder->protected_->state = FLAC__STREAM_DECODER_MEMORY_ALLOCATION_ERROR;
  97124. return false;
  97125. }
  97126. if(x > 0) {
  97127. if(!FLAC__bitreader_read_byte_block_aligned_no_crc(decoder->private_->input, obj->description, x))
  97128. return false; /* read_callback_ sets the state for us */
  97129. }
  97130. obj->description[x] = '\0';
  97131. /* read width */
  97132. if(!FLAC__bitreader_read_raw_uint32(decoder->private_->input, &obj->width, FLAC__STREAM_METADATA_PICTURE_WIDTH_LEN))
  97133. return false; /* read_callback_ sets the state for us */
  97134. /* read height */
  97135. if(!FLAC__bitreader_read_raw_uint32(decoder->private_->input, &obj->height, FLAC__STREAM_METADATA_PICTURE_HEIGHT_LEN))
  97136. return false; /* read_callback_ sets the state for us */
  97137. /* read depth */
  97138. if(!FLAC__bitreader_read_raw_uint32(decoder->private_->input, &obj->depth, FLAC__STREAM_METADATA_PICTURE_DEPTH_LEN))
  97139. return false; /* read_callback_ sets the state for us */
  97140. /* read colors */
  97141. if(!FLAC__bitreader_read_raw_uint32(decoder->private_->input, &obj->colors, FLAC__STREAM_METADATA_PICTURE_COLORS_LEN))
  97142. return false; /* read_callback_ sets the state for us */
  97143. /* read data */
  97144. if(!FLAC__bitreader_read_raw_uint32(decoder->private_->input, &(obj->data_length), FLAC__STREAM_METADATA_PICTURE_DATA_LENGTH_LEN))
  97145. return false; /* read_callback_ sets the state for us */
  97146. if(0 == (obj->data = (FLAC__byte*)safe_malloc_(obj->data_length))) {
  97147. decoder->protected_->state = FLAC__STREAM_DECODER_MEMORY_ALLOCATION_ERROR;
  97148. return false;
  97149. }
  97150. if(obj->data_length > 0) {
  97151. if(!FLAC__bitreader_read_byte_block_aligned_no_crc(decoder->private_->input, obj->data, obj->data_length))
  97152. return false; /* read_callback_ sets the state for us */
  97153. }
  97154. return true;
  97155. }
  97156. FLAC__bool skip_id3v2_tag_(FLAC__StreamDecoder *decoder)
  97157. {
  97158. FLAC__uint32 x;
  97159. unsigned i, skip;
  97160. /* skip the version and flags bytes */
  97161. if(!FLAC__bitreader_read_raw_uint32(decoder->private_->input, &x, 24))
  97162. return false; /* read_callback_ sets the state for us */
  97163. /* get the size (in bytes) to skip */
  97164. skip = 0;
  97165. for(i = 0; i < 4; i++) {
  97166. if(!FLAC__bitreader_read_raw_uint32(decoder->private_->input, &x, 8))
  97167. return false; /* read_callback_ sets the state for us */
  97168. skip <<= 7;
  97169. skip |= (x & 0x7f);
  97170. }
  97171. /* skip the rest of the tag */
  97172. if(!FLAC__bitreader_skip_byte_block_aligned_no_crc(decoder->private_->input, skip))
  97173. return false; /* read_callback_ sets the state for us */
  97174. return true;
  97175. }
  97176. FLAC__bool frame_sync_(FLAC__StreamDecoder *decoder)
  97177. {
  97178. FLAC__uint32 x;
  97179. FLAC__bool first = true;
  97180. /* If we know the total number of samples in the stream, stop if we've read that many. */
  97181. /* This will stop us, for example, from wasting time trying to sync on an ID3V1 tag. */
  97182. if(FLAC__stream_decoder_get_total_samples(decoder) > 0) {
  97183. if(decoder->private_->samples_decoded >= FLAC__stream_decoder_get_total_samples(decoder)) {
  97184. decoder->protected_->state = FLAC__STREAM_DECODER_END_OF_STREAM;
  97185. return true;
  97186. }
  97187. }
  97188. /* make sure we're byte aligned */
  97189. if(!FLAC__bitreader_is_consumed_byte_aligned(decoder->private_->input)) {
  97190. if(!FLAC__bitreader_read_raw_uint32(decoder->private_->input, &x, FLAC__bitreader_bits_left_for_byte_alignment(decoder->private_->input)))
  97191. return false; /* read_callback_ sets the state for us */
  97192. }
  97193. while(1) {
  97194. if(decoder->private_->cached) {
  97195. x = (FLAC__uint32)decoder->private_->lookahead;
  97196. decoder->private_->cached = false;
  97197. }
  97198. else {
  97199. if(!FLAC__bitreader_read_raw_uint32(decoder->private_->input, &x, 8))
  97200. return false; /* read_callback_ sets the state for us */
  97201. }
  97202. if(x == 0xff) { /* MAGIC NUMBER for the first 8 frame sync bits */
  97203. decoder->private_->header_warmup[0] = (FLAC__byte)x;
  97204. if(!FLAC__bitreader_read_raw_uint32(decoder->private_->input, &x, 8))
  97205. return false; /* read_callback_ sets the state for us */
  97206. /* 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 */
  97207. /* else we have to check if the second byte is the end of a sync code */
  97208. if(x == 0xff) { /* MAGIC NUMBER for the first 8 frame sync bits */
  97209. decoder->private_->lookahead = (FLAC__byte)x;
  97210. decoder->private_->cached = true;
  97211. }
  97212. else if(x >> 2 == 0x3e) { /* MAGIC NUMBER for the last 6 sync bits */
  97213. decoder->private_->header_warmup[1] = (FLAC__byte)x;
  97214. decoder->protected_->state = FLAC__STREAM_DECODER_READ_FRAME;
  97215. return true;
  97216. }
  97217. }
  97218. if(first) {
  97219. send_error_to_client_(decoder, FLAC__STREAM_DECODER_ERROR_STATUS_LOST_SYNC);
  97220. first = false;
  97221. }
  97222. }
  97223. return true;
  97224. }
  97225. FLAC__bool read_frame_(FLAC__StreamDecoder *decoder, FLAC__bool *got_a_frame, FLAC__bool do_full_decode)
  97226. {
  97227. unsigned channel;
  97228. unsigned i;
  97229. FLAC__int32 mid, side;
  97230. unsigned frame_crc; /* the one we calculate from the input stream */
  97231. FLAC__uint32 x;
  97232. *got_a_frame = false;
  97233. /* init the CRC */
  97234. frame_crc = 0;
  97235. frame_crc = FLAC__CRC16_UPDATE(decoder->private_->header_warmup[0], frame_crc);
  97236. frame_crc = FLAC__CRC16_UPDATE(decoder->private_->header_warmup[1], frame_crc);
  97237. FLAC__bitreader_reset_read_crc16(decoder->private_->input, (FLAC__uint16)frame_crc);
  97238. if(!read_frame_header_(decoder))
  97239. return false;
  97240. if(decoder->protected_->state == FLAC__STREAM_DECODER_SEARCH_FOR_FRAME_SYNC) /* means we didn't sync on a valid header */
  97241. return true;
  97242. if(!allocate_output_(decoder, decoder->private_->frame.header.blocksize, decoder->private_->frame.header.channels))
  97243. return false;
  97244. for(channel = 0; channel < decoder->private_->frame.header.channels; channel++) {
  97245. /*
  97246. * first figure the correct bits-per-sample of the subframe
  97247. */
  97248. unsigned bps = decoder->private_->frame.header.bits_per_sample;
  97249. switch(decoder->private_->frame.header.channel_assignment) {
  97250. case FLAC__CHANNEL_ASSIGNMENT_INDEPENDENT:
  97251. /* no adjustment needed */
  97252. break;
  97253. case FLAC__CHANNEL_ASSIGNMENT_LEFT_SIDE:
  97254. FLAC__ASSERT(decoder->private_->frame.header.channels == 2);
  97255. if(channel == 1)
  97256. bps++;
  97257. break;
  97258. case FLAC__CHANNEL_ASSIGNMENT_RIGHT_SIDE:
  97259. FLAC__ASSERT(decoder->private_->frame.header.channels == 2);
  97260. if(channel == 0)
  97261. bps++;
  97262. break;
  97263. case FLAC__CHANNEL_ASSIGNMENT_MID_SIDE:
  97264. FLAC__ASSERT(decoder->private_->frame.header.channels == 2);
  97265. if(channel == 1)
  97266. bps++;
  97267. break;
  97268. default:
  97269. FLAC__ASSERT(0);
  97270. }
  97271. /*
  97272. * now read it
  97273. */
  97274. if(!read_subframe_(decoder, channel, bps, do_full_decode))
  97275. return false;
  97276. if(decoder->protected_->state == FLAC__STREAM_DECODER_SEARCH_FOR_FRAME_SYNC) /* means bad sync or got corruption */
  97277. return true;
  97278. }
  97279. if(!read_zero_padding_(decoder))
  97280. return false;
  97281. 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) */
  97282. return true;
  97283. /*
  97284. * Read the frame CRC-16 from the footer and check
  97285. */
  97286. frame_crc = FLAC__bitreader_get_read_crc16(decoder->private_->input);
  97287. if(!FLAC__bitreader_read_raw_uint32(decoder->private_->input, &x, FLAC__FRAME_FOOTER_CRC_LEN))
  97288. return false; /* read_callback_ sets the state for us */
  97289. if(frame_crc == x) {
  97290. if(do_full_decode) {
  97291. /* Undo any special channel coding */
  97292. switch(decoder->private_->frame.header.channel_assignment) {
  97293. case FLAC__CHANNEL_ASSIGNMENT_INDEPENDENT:
  97294. /* do nothing */
  97295. break;
  97296. case FLAC__CHANNEL_ASSIGNMENT_LEFT_SIDE:
  97297. FLAC__ASSERT(decoder->private_->frame.header.channels == 2);
  97298. for(i = 0; i < decoder->private_->frame.header.blocksize; i++)
  97299. decoder->private_->output[1][i] = decoder->private_->output[0][i] - decoder->private_->output[1][i];
  97300. break;
  97301. case FLAC__CHANNEL_ASSIGNMENT_RIGHT_SIDE:
  97302. FLAC__ASSERT(decoder->private_->frame.header.channels == 2);
  97303. for(i = 0; i < decoder->private_->frame.header.blocksize; i++)
  97304. decoder->private_->output[0][i] += decoder->private_->output[1][i];
  97305. break;
  97306. case FLAC__CHANNEL_ASSIGNMENT_MID_SIDE:
  97307. FLAC__ASSERT(decoder->private_->frame.header.channels == 2);
  97308. for(i = 0; i < decoder->private_->frame.header.blocksize; i++) {
  97309. #if 1
  97310. mid = decoder->private_->output[0][i];
  97311. side = decoder->private_->output[1][i];
  97312. mid <<= 1;
  97313. mid |= (side & 1); /* i.e. if 'side' is odd... */
  97314. decoder->private_->output[0][i] = (mid + side) >> 1;
  97315. decoder->private_->output[1][i] = (mid - side) >> 1;
  97316. #else
  97317. /* OPT: without 'side' temp variable */
  97318. mid = (decoder->private_->output[0][i] << 1) | (decoder->private_->output[1][i] & 1); /* i.e. if 'side' is odd... */
  97319. decoder->private_->output[0][i] = (mid + decoder->private_->output[1][i]) >> 1;
  97320. decoder->private_->output[1][i] = (mid - decoder->private_->output[1][i]) >> 1;
  97321. #endif
  97322. }
  97323. break;
  97324. default:
  97325. FLAC__ASSERT(0);
  97326. break;
  97327. }
  97328. }
  97329. }
  97330. else {
  97331. /* Bad frame, emit error and zero the output signal */
  97332. send_error_to_client_(decoder, FLAC__STREAM_DECODER_ERROR_STATUS_FRAME_CRC_MISMATCH);
  97333. if(do_full_decode) {
  97334. for(channel = 0; channel < decoder->private_->frame.header.channels; channel++) {
  97335. memset(decoder->private_->output[channel], 0, sizeof(FLAC__int32) * decoder->private_->frame.header.blocksize);
  97336. }
  97337. }
  97338. }
  97339. *got_a_frame = true;
  97340. /* we wait to update fixed_block_size until here, when we're sure we've got a proper frame and hence a correct blocksize */
  97341. if(decoder->private_->next_fixed_block_size)
  97342. decoder->private_->fixed_block_size = decoder->private_->next_fixed_block_size;
  97343. /* put the latest values into the public section of the decoder instance */
  97344. decoder->protected_->channels = decoder->private_->frame.header.channels;
  97345. decoder->protected_->channel_assignment = decoder->private_->frame.header.channel_assignment;
  97346. decoder->protected_->bits_per_sample = decoder->private_->frame.header.bits_per_sample;
  97347. decoder->protected_->sample_rate = decoder->private_->frame.header.sample_rate;
  97348. decoder->protected_->blocksize = decoder->private_->frame.header.blocksize;
  97349. FLAC__ASSERT(decoder->private_->frame.header.number_type == FLAC__FRAME_NUMBER_TYPE_SAMPLE_NUMBER);
  97350. decoder->private_->samples_decoded = decoder->private_->frame.header.number.sample_number + decoder->private_->frame.header.blocksize;
  97351. /* write it */
  97352. if(do_full_decode) {
  97353. if(write_audio_frame_to_client_(decoder, &decoder->private_->frame, (const FLAC__int32 * const *)decoder->private_->output) != FLAC__STREAM_DECODER_WRITE_STATUS_CONTINUE)
  97354. return false;
  97355. }
  97356. decoder->protected_->state = FLAC__STREAM_DECODER_SEARCH_FOR_FRAME_SYNC;
  97357. return true;
  97358. }
  97359. FLAC__bool read_frame_header_(FLAC__StreamDecoder *decoder)
  97360. {
  97361. FLAC__uint32 x;
  97362. FLAC__uint64 xx;
  97363. unsigned i, blocksize_hint = 0, sample_rate_hint = 0;
  97364. FLAC__byte crc8, raw_header[16]; /* MAGIC NUMBER based on the maximum frame header size, including CRC */
  97365. unsigned raw_header_len;
  97366. FLAC__bool is_unparseable = false;
  97367. FLAC__ASSERT(FLAC__bitreader_is_consumed_byte_aligned(decoder->private_->input));
  97368. /* init the raw header with the saved bits from synchronization */
  97369. raw_header[0] = decoder->private_->header_warmup[0];
  97370. raw_header[1] = decoder->private_->header_warmup[1];
  97371. raw_header_len = 2;
  97372. /* check to make sure that reserved bit is 0 */
  97373. if(raw_header[1] & 0x02) /* MAGIC NUMBER */
  97374. is_unparseable = true;
  97375. /*
  97376. * Note that along the way as we read the header, we look for a sync
  97377. * code inside. If we find one it would indicate that our original
  97378. * sync was bad since there cannot be a sync code in a valid header.
  97379. *
  97380. * Three kinds of things can go wrong when reading the frame header:
  97381. * 1) We may have sync'ed incorrectly and not landed on a frame header.
  97382. * If we don't find a sync code, it can end up looking like we read
  97383. * a valid but unparseable header, until getting to the frame header
  97384. * CRC. Even then we could get a false positive on the CRC.
  97385. * 2) We may have sync'ed correctly but on an unparseable frame (from a
  97386. * future encoder).
  97387. * 3) We may be on a damaged frame which appears valid but unparseable.
  97388. *
  97389. * For all these reasons, we try and read a complete frame header as
  97390. * long as it seems valid, even if unparseable, up until the frame
  97391. * header CRC.
  97392. */
  97393. /*
  97394. * read in the raw header as bytes so we can CRC it, and parse it on the way
  97395. */
  97396. for(i = 0; i < 2; i++) {
  97397. if(!FLAC__bitreader_read_raw_uint32(decoder->private_->input, &x, 8))
  97398. return false; /* read_callback_ sets the state for us */
  97399. if(x == 0xff) { /* MAGIC NUMBER for the first 8 frame sync bits */
  97400. /* if we get here it means our original sync was erroneous since the sync code cannot appear in the header */
  97401. decoder->private_->lookahead = (FLAC__byte)x;
  97402. decoder->private_->cached = true;
  97403. send_error_to_client_(decoder, FLAC__STREAM_DECODER_ERROR_STATUS_BAD_HEADER);
  97404. decoder->protected_->state = FLAC__STREAM_DECODER_SEARCH_FOR_FRAME_SYNC;
  97405. return true;
  97406. }
  97407. raw_header[raw_header_len++] = (FLAC__byte)x;
  97408. }
  97409. switch(x = raw_header[2] >> 4) {
  97410. case 0:
  97411. is_unparseable = true;
  97412. break;
  97413. case 1:
  97414. decoder->private_->frame.header.blocksize = 192;
  97415. break;
  97416. case 2:
  97417. case 3:
  97418. case 4:
  97419. case 5:
  97420. decoder->private_->frame.header.blocksize = 576 << (x-2);
  97421. break;
  97422. case 6:
  97423. case 7:
  97424. blocksize_hint = x;
  97425. break;
  97426. case 8:
  97427. case 9:
  97428. case 10:
  97429. case 11:
  97430. case 12:
  97431. case 13:
  97432. case 14:
  97433. case 15:
  97434. decoder->private_->frame.header.blocksize = 256 << (x-8);
  97435. break;
  97436. default:
  97437. FLAC__ASSERT(0);
  97438. break;
  97439. }
  97440. switch(x = raw_header[2] & 0x0f) {
  97441. case 0:
  97442. if(decoder->private_->has_stream_info)
  97443. decoder->private_->frame.header.sample_rate = decoder->private_->stream_info.data.stream_info.sample_rate;
  97444. else
  97445. is_unparseable = true;
  97446. break;
  97447. case 1:
  97448. decoder->private_->frame.header.sample_rate = 88200;
  97449. break;
  97450. case 2:
  97451. decoder->private_->frame.header.sample_rate = 176400;
  97452. break;
  97453. case 3:
  97454. decoder->private_->frame.header.sample_rate = 192000;
  97455. break;
  97456. case 4:
  97457. decoder->private_->frame.header.sample_rate = 8000;
  97458. break;
  97459. case 5:
  97460. decoder->private_->frame.header.sample_rate = 16000;
  97461. break;
  97462. case 6:
  97463. decoder->private_->frame.header.sample_rate = 22050;
  97464. break;
  97465. case 7:
  97466. decoder->private_->frame.header.sample_rate = 24000;
  97467. break;
  97468. case 8:
  97469. decoder->private_->frame.header.sample_rate = 32000;
  97470. break;
  97471. case 9:
  97472. decoder->private_->frame.header.sample_rate = 44100;
  97473. break;
  97474. case 10:
  97475. decoder->private_->frame.header.sample_rate = 48000;
  97476. break;
  97477. case 11:
  97478. decoder->private_->frame.header.sample_rate = 96000;
  97479. break;
  97480. case 12:
  97481. case 13:
  97482. case 14:
  97483. sample_rate_hint = x;
  97484. break;
  97485. case 15:
  97486. send_error_to_client_(decoder, FLAC__STREAM_DECODER_ERROR_STATUS_BAD_HEADER);
  97487. decoder->protected_->state = FLAC__STREAM_DECODER_SEARCH_FOR_FRAME_SYNC;
  97488. return true;
  97489. default:
  97490. FLAC__ASSERT(0);
  97491. }
  97492. x = (unsigned)(raw_header[3] >> 4);
  97493. if(x & 8) {
  97494. decoder->private_->frame.header.channels = 2;
  97495. switch(x & 7) {
  97496. case 0:
  97497. decoder->private_->frame.header.channel_assignment = FLAC__CHANNEL_ASSIGNMENT_LEFT_SIDE;
  97498. break;
  97499. case 1:
  97500. decoder->private_->frame.header.channel_assignment = FLAC__CHANNEL_ASSIGNMENT_RIGHT_SIDE;
  97501. break;
  97502. case 2:
  97503. decoder->private_->frame.header.channel_assignment = FLAC__CHANNEL_ASSIGNMENT_MID_SIDE;
  97504. break;
  97505. default:
  97506. is_unparseable = true;
  97507. break;
  97508. }
  97509. }
  97510. else {
  97511. decoder->private_->frame.header.channels = (unsigned)x + 1;
  97512. decoder->private_->frame.header.channel_assignment = FLAC__CHANNEL_ASSIGNMENT_INDEPENDENT;
  97513. }
  97514. switch(x = (unsigned)(raw_header[3] & 0x0e) >> 1) {
  97515. case 0:
  97516. if(decoder->private_->has_stream_info)
  97517. decoder->private_->frame.header.bits_per_sample = decoder->private_->stream_info.data.stream_info.bits_per_sample;
  97518. else
  97519. is_unparseable = true;
  97520. break;
  97521. case 1:
  97522. decoder->private_->frame.header.bits_per_sample = 8;
  97523. break;
  97524. case 2:
  97525. decoder->private_->frame.header.bits_per_sample = 12;
  97526. break;
  97527. case 4:
  97528. decoder->private_->frame.header.bits_per_sample = 16;
  97529. break;
  97530. case 5:
  97531. decoder->private_->frame.header.bits_per_sample = 20;
  97532. break;
  97533. case 6:
  97534. decoder->private_->frame.header.bits_per_sample = 24;
  97535. break;
  97536. case 3:
  97537. case 7:
  97538. is_unparseable = true;
  97539. break;
  97540. default:
  97541. FLAC__ASSERT(0);
  97542. break;
  97543. }
  97544. /* check to make sure that reserved bit is 0 */
  97545. if(raw_header[3] & 0x01) /* MAGIC NUMBER */
  97546. is_unparseable = true;
  97547. /* read the frame's starting sample number (or frame number as the case may be) */
  97548. if(
  97549. raw_header[1] & 0x01 ||
  97550. /*@@@ 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 */
  97551. (decoder->private_->has_stream_info && decoder->private_->stream_info.data.stream_info.min_blocksize != decoder->private_->stream_info.data.stream_info.max_blocksize)
  97552. ) { /* variable blocksize */
  97553. if(!FLAC__bitreader_read_utf8_uint64(decoder->private_->input, &xx, raw_header, &raw_header_len))
  97554. return false; /* read_callback_ sets the state for us */
  97555. if(xx == FLAC__U64L(0xffffffffffffffff)) { /* i.e. non-UTF8 code... */
  97556. decoder->private_->lookahead = raw_header[raw_header_len-1]; /* back up as much as we can */
  97557. decoder->private_->cached = true;
  97558. send_error_to_client_(decoder, FLAC__STREAM_DECODER_ERROR_STATUS_BAD_HEADER);
  97559. decoder->protected_->state = FLAC__STREAM_DECODER_SEARCH_FOR_FRAME_SYNC;
  97560. return true;
  97561. }
  97562. decoder->private_->frame.header.number_type = FLAC__FRAME_NUMBER_TYPE_SAMPLE_NUMBER;
  97563. decoder->private_->frame.header.number.sample_number = xx;
  97564. }
  97565. else { /* fixed blocksize */
  97566. if(!FLAC__bitreader_read_utf8_uint32(decoder->private_->input, &x, raw_header, &raw_header_len))
  97567. return false; /* read_callback_ sets the state for us */
  97568. if(x == 0xffffffff) { /* i.e. non-UTF8 code... */
  97569. decoder->private_->lookahead = raw_header[raw_header_len-1]; /* back up as much as we can */
  97570. decoder->private_->cached = true;
  97571. send_error_to_client_(decoder, FLAC__STREAM_DECODER_ERROR_STATUS_BAD_HEADER);
  97572. decoder->protected_->state = FLAC__STREAM_DECODER_SEARCH_FOR_FRAME_SYNC;
  97573. return true;
  97574. }
  97575. decoder->private_->frame.header.number_type = FLAC__FRAME_NUMBER_TYPE_FRAME_NUMBER;
  97576. decoder->private_->frame.header.number.frame_number = x;
  97577. }
  97578. if(blocksize_hint) {
  97579. if(!FLAC__bitreader_read_raw_uint32(decoder->private_->input, &x, 8))
  97580. return false; /* read_callback_ sets the state for us */
  97581. raw_header[raw_header_len++] = (FLAC__byte)x;
  97582. if(blocksize_hint == 7) {
  97583. FLAC__uint32 _x;
  97584. if(!FLAC__bitreader_read_raw_uint32(decoder->private_->input, &_x, 8))
  97585. return false; /* read_callback_ sets the state for us */
  97586. raw_header[raw_header_len++] = (FLAC__byte)_x;
  97587. x = (x << 8) | _x;
  97588. }
  97589. decoder->private_->frame.header.blocksize = x+1;
  97590. }
  97591. if(sample_rate_hint) {
  97592. if(!FLAC__bitreader_read_raw_uint32(decoder->private_->input, &x, 8))
  97593. return false; /* read_callback_ sets the state for us */
  97594. raw_header[raw_header_len++] = (FLAC__byte)x;
  97595. if(sample_rate_hint != 12) {
  97596. FLAC__uint32 _x;
  97597. if(!FLAC__bitreader_read_raw_uint32(decoder->private_->input, &_x, 8))
  97598. return false; /* read_callback_ sets the state for us */
  97599. raw_header[raw_header_len++] = (FLAC__byte)_x;
  97600. x = (x << 8) | _x;
  97601. }
  97602. if(sample_rate_hint == 12)
  97603. decoder->private_->frame.header.sample_rate = x*1000;
  97604. else if(sample_rate_hint == 13)
  97605. decoder->private_->frame.header.sample_rate = x;
  97606. else
  97607. decoder->private_->frame.header.sample_rate = x*10;
  97608. }
  97609. /* read the CRC-8 byte */
  97610. if(!FLAC__bitreader_read_raw_uint32(decoder->private_->input, &x, 8))
  97611. return false; /* read_callback_ sets the state for us */
  97612. crc8 = (FLAC__byte)x;
  97613. if(FLAC__crc8(raw_header, raw_header_len) != crc8) {
  97614. send_error_to_client_(decoder, FLAC__STREAM_DECODER_ERROR_STATUS_BAD_HEADER);
  97615. decoder->protected_->state = FLAC__STREAM_DECODER_SEARCH_FOR_FRAME_SYNC;
  97616. return true;
  97617. }
  97618. /* calculate the sample number from the frame number if needed */
  97619. decoder->private_->next_fixed_block_size = 0;
  97620. if(decoder->private_->frame.header.number_type == FLAC__FRAME_NUMBER_TYPE_FRAME_NUMBER) {
  97621. x = decoder->private_->frame.header.number.frame_number;
  97622. decoder->private_->frame.header.number_type = FLAC__FRAME_NUMBER_TYPE_SAMPLE_NUMBER;
  97623. if(decoder->private_->fixed_block_size)
  97624. decoder->private_->frame.header.number.sample_number = (FLAC__uint64)decoder->private_->fixed_block_size * (FLAC__uint64)x;
  97625. else if(decoder->private_->has_stream_info) {
  97626. if(decoder->private_->stream_info.data.stream_info.min_blocksize == decoder->private_->stream_info.data.stream_info.max_blocksize) {
  97627. decoder->private_->frame.header.number.sample_number = (FLAC__uint64)decoder->private_->stream_info.data.stream_info.min_blocksize * (FLAC__uint64)x;
  97628. decoder->private_->next_fixed_block_size = decoder->private_->stream_info.data.stream_info.max_blocksize;
  97629. }
  97630. else
  97631. is_unparseable = true;
  97632. }
  97633. else if(x == 0) {
  97634. decoder->private_->frame.header.number.sample_number = 0;
  97635. decoder->private_->next_fixed_block_size = decoder->private_->frame.header.blocksize;
  97636. }
  97637. else {
  97638. /* can only get here if the stream has invalid frame numbering and no STREAMINFO, so assume it's not the last (possibly short) frame */
  97639. decoder->private_->frame.header.number.sample_number = (FLAC__uint64)decoder->private_->frame.header.blocksize * (FLAC__uint64)x;
  97640. }
  97641. }
  97642. if(is_unparseable) {
  97643. send_error_to_client_(decoder, FLAC__STREAM_DECODER_ERROR_STATUS_UNPARSEABLE_STREAM);
  97644. decoder->protected_->state = FLAC__STREAM_DECODER_SEARCH_FOR_FRAME_SYNC;
  97645. return true;
  97646. }
  97647. return true;
  97648. }
  97649. FLAC__bool read_subframe_(FLAC__StreamDecoder *decoder, unsigned channel, unsigned bps, FLAC__bool do_full_decode)
  97650. {
  97651. FLAC__uint32 x;
  97652. FLAC__bool wasted_bits;
  97653. unsigned i;
  97654. if(!FLAC__bitreader_read_raw_uint32(decoder->private_->input, &x, 8)) /* MAGIC NUMBER */
  97655. return false; /* read_callback_ sets the state for us */
  97656. wasted_bits = (x & 1);
  97657. x &= 0xfe;
  97658. if(wasted_bits) {
  97659. unsigned u;
  97660. if(!FLAC__bitreader_read_unary_unsigned(decoder->private_->input, &u))
  97661. return false; /* read_callback_ sets the state for us */
  97662. decoder->private_->frame.subframes[channel].wasted_bits = u+1;
  97663. bps -= decoder->private_->frame.subframes[channel].wasted_bits;
  97664. }
  97665. else
  97666. decoder->private_->frame.subframes[channel].wasted_bits = 0;
  97667. /*
  97668. * Lots of magic numbers here
  97669. */
  97670. if(x & 0x80) {
  97671. send_error_to_client_(decoder, FLAC__STREAM_DECODER_ERROR_STATUS_LOST_SYNC);
  97672. decoder->protected_->state = FLAC__STREAM_DECODER_SEARCH_FOR_FRAME_SYNC;
  97673. return true;
  97674. }
  97675. else if(x == 0) {
  97676. if(!read_subframe_constant_(decoder, channel, bps, do_full_decode))
  97677. return false;
  97678. }
  97679. else if(x == 2) {
  97680. if(!read_subframe_verbatim_(decoder, channel, bps, do_full_decode))
  97681. return false;
  97682. }
  97683. else if(x < 16) {
  97684. send_error_to_client_(decoder, FLAC__STREAM_DECODER_ERROR_STATUS_UNPARSEABLE_STREAM);
  97685. decoder->protected_->state = FLAC__STREAM_DECODER_SEARCH_FOR_FRAME_SYNC;
  97686. return true;
  97687. }
  97688. else if(x <= 24) {
  97689. if(!read_subframe_fixed_(decoder, channel, bps, (x>>1)&7, do_full_decode))
  97690. return false;
  97691. if(decoder->protected_->state == FLAC__STREAM_DECODER_SEARCH_FOR_FRAME_SYNC) /* means bad sync or got corruption */
  97692. return true;
  97693. }
  97694. else if(x < 64) {
  97695. send_error_to_client_(decoder, FLAC__STREAM_DECODER_ERROR_STATUS_UNPARSEABLE_STREAM);
  97696. decoder->protected_->state = FLAC__STREAM_DECODER_SEARCH_FOR_FRAME_SYNC;
  97697. return true;
  97698. }
  97699. else {
  97700. if(!read_subframe_lpc_(decoder, channel, bps, ((x>>1)&31)+1, do_full_decode))
  97701. return false;
  97702. if(decoder->protected_->state == FLAC__STREAM_DECODER_SEARCH_FOR_FRAME_SYNC) /* means bad sync or got corruption */
  97703. return true;
  97704. }
  97705. if(wasted_bits && do_full_decode) {
  97706. x = decoder->private_->frame.subframes[channel].wasted_bits;
  97707. for(i = 0; i < decoder->private_->frame.header.blocksize; i++)
  97708. decoder->private_->output[channel][i] <<= x;
  97709. }
  97710. return true;
  97711. }
  97712. FLAC__bool read_subframe_constant_(FLAC__StreamDecoder *decoder, unsigned channel, unsigned bps, FLAC__bool do_full_decode)
  97713. {
  97714. FLAC__Subframe_Constant *subframe = &decoder->private_->frame.subframes[channel].data.constant;
  97715. FLAC__int32 x;
  97716. unsigned i;
  97717. FLAC__int32 *output = decoder->private_->output[channel];
  97718. decoder->private_->frame.subframes[channel].type = FLAC__SUBFRAME_TYPE_CONSTANT;
  97719. if(!FLAC__bitreader_read_raw_int32(decoder->private_->input, &x, bps))
  97720. return false; /* read_callback_ sets the state for us */
  97721. subframe->value = x;
  97722. /* decode the subframe */
  97723. if(do_full_decode) {
  97724. for(i = 0; i < decoder->private_->frame.header.blocksize; i++)
  97725. output[i] = x;
  97726. }
  97727. return true;
  97728. }
  97729. FLAC__bool read_subframe_fixed_(FLAC__StreamDecoder *decoder, unsigned channel, unsigned bps, const unsigned order, FLAC__bool do_full_decode)
  97730. {
  97731. FLAC__Subframe_Fixed *subframe = &decoder->private_->frame.subframes[channel].data.fixed;
  97732. FLAC__int32 i32;
  97733. FLAC__uint32 u32;
  97734. unsigned u;
  97735. decoder->private_->frame.subframes[channel].type = FLAC__SUBFRAME_TYPE_FIXED;
  97736. subframe->residual = decoder->private_->residual[channel];
  97737. subframe->order = order;
  97738. /* read warm-up samples */
  97739. for(u = 0; u < order; u++) {
  97740. if(!FLAC__bitreader_read_raw_int32(decoder->private_->input, &i32, bps))
  97741. return false; /* read_callback_ sets the state for us */
  97742. subframe->warmup[u] = i32;
  97743. }
  97744. /* read entropy coding method info */
  97745. if(!FLAC__bitreader_read_raw_uint32(decoder->private_->input, &u32, FLAC__ENTROPY_CODING_METHOD_TYPE_LEN))
  97746. return false; /* read_callback_ sets the state for us */
  97747. subframe->entropy_coding_method.type = (FLAC__EntropyCodingMethodType)u32;
  97748. switch(subframe->entropy_coding_method.type) {
  97749. case FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE:
  97750. case FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE2:
  97751. if(!FLAC__bitreader_read_raw_uint32(decoder->private_->input, &u32, FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE_ORDER_LEN))
  97752. return false; /* read_callback_ sets the state for us */
  97753. subframe->entropy_coding_method.data.partitioned_rice.order = u32;
  97754. subframe->entropy_coding_method.data.partitioned_rice.contents = &decoder->private_->partitioned_rice_contents[channel];
  97755. break;
  97756. default:
  97757. send_error_to_client_(decoder, FLAC__STREAM_DECODER_ERROR_STATUS_UNPARSEABLE_STREAM);
  97758. decoder->protected_->state = FLAC__STREAM_DECODER_SEARCH_FOR_FRAME_SYNC;
  97759. return true;
  97760. }
  97761. /* read residual */
  97762. switch(subframe->entropy_coding_method.type) {
  97763. case FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE:
  97764. case FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE2:
  97765. 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))
  97766. return false;
  97767. break;
  97768. default:
  97769. FLAC__ASSERT(0);
  97770. }
  97771. /* decode the subframe */
  97772. if(do_full_decode) {
  97773. memcpy(decoder->private_->output[channel], subframe->warmup, sizeof(FLAC__int32) * order);
  97774. FLAC__fixed_restore_signal(decoder->private_->residual[channel], decoder->private_->frame.header.blocksize-order, order, decoder->private_->output[channel]+order);
  97775. }
  97776. return true;
  97777. }
  97778. FLAC__bool read_subframe_lpc_(FLAC__StreamDecoder *decoder, unsigned channel, unsigned bps, const unsigned order, FLAC__bool do_full_decode)
  97779. {
  97780. FLAC__Subframe_LPC *subframe = &decoder->private_->frame.subframes[channel].data.lpc;
  97781. FLAC__int32 i32;
  97782. FLAC__uint32 u32;
  97783. unsigned u;
  97784. decoder->private_->frame.subframes[channel].type = FLAC__SUBFRAME_TYPE_LPC;
  97785. subframe->residual = decoder->private_->residual[channel];
  97786. subframe->order = order;
  97787. /* read warm-up samples */
  97788. for(u = 0; u < order; u++) {
  97789. if(!FLAC__bitreader_read_raw_int32(decoder->private_->input, &i32, bps))
  97790. return false; /* read_callback_ sets the state for us */
  97791. subframe->warmup[u] = i32;
  97792. }
  97793. /* read qlp coeff precision */
  97794. if(!FLAC__bitreader_read_raw_uint32(decoder->private_->input, &u32, FLAC__SUBFRAME_LPC_QLP_COEFF_PRECISION_LEN))
  97795. return false; /* read_callback_ sets the state for us */
  97796. if(u32 == (1u << FLAC__SUBFRAME_LPC_QLP_COEFF_PRECISION_LEN) - 1) {
  97797. send_error_to_client_(decoder, FLAC__STREAM_DECODER_ERROR_STATUS_LOST_SYNC);
  97798. decoder->protected_->state = FLAC__STREAM_DECODER_SEARCH_FOR_FRAME_SYNC;
  97799. return true;
  97800. }
  97801. subframe->qlp_coeff_precision = u32+1;
  97802. /* read qlp shift */
  97803. if(!FLAC__bitreader_read_raw_int32(decoder->private_->input, &i32, FLAC__SUBFRAME_LPC_QLP_SHIFT_LEN))
  97804. return false; /* read_callback_ sets the state for us */
  97805. subframe->quantization_level = i32;
  97806. /* read quantized lp coefficiencts */
  97807. for(u = 0; u < order; u++) {
  97808. if(!FLAC__bitreader_read_raw_int32(decoder->private_->input, &i32, subframe->qlp_coeff_precision))
  97809. return false; /* read_callback_ sets the state for us */
  97810. subframe->qlp_coeff[u] = i32;
  97811. }
  97812. /* read entropy coding method info */
  97813. if(!FLAC__bitreader_read_raw_uint32(decoder->private_->input, &u32, FLAC__ENTROPY_CODING_METHOD_TYPE_LEN))
  97814. return false; /* read_callback_ sets the state for us */
  97815. subframe->entropy_coding_method.type = (FLAC__EntropyCodingMethodType)u32;
  97816. switch(subframe->entropy_coding_method.type) {
  97817. case FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE:
  97818. case FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE2:
  97819. if(!FLAC__bitreader_read_raw_uint32(decoder->private_->input, &u32, FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE_ORDER_LEN))
  97820. return false; /* read_callback_ sets the state for us */
  97821. subframe->entropy_coding_method.data.partitioned_rice.order = u32;
  97822. subframe->entropy_coding_method.data.partitioned_rice.contents = &decoder->private_->partitioned_rice_contents[channel];
  97823. break;
  97824. default:
  97825. send_error_to_client_(decoder, FLAC__STREAM_DECODER_ERROR_STATUS_UNPARSEABLE_STREAM);
  97826. decoder->protected_->state = FLAC__STREAM_DECODER_SEARCH_FOR_FRAME_SYNC;
  97827. return true;
  97828. }
  97829. /* read residual */
  97830. switch(subframe->entropy_coding_method.type) {
  97831. case FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE:
  97832. case FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE2:
  97833. 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))
  97834. return false;
  97835. break;
  97836. default:
  97837. FLAC__ASSERT(0);
  97838. }
  97839. /* decode the subframe */
  97840. if(do_full_decode) {
  97841. memcpy(decoder->private_->output[channel], subframe->warmup, sizeof(FLAC__int32) * order);
  97842. /*@@@@@@ technically not pessimistic enough, should be more like
  97843. if( (FLAC__uint64)order * ((((FLAC__uint64)1)<<bps)-1) * ((1<<subframe->qlp_coeff_precision)-1) < (((FLAC__uint64)-1) << 32) )
  97844. */
  97845. if(bps + subframe->qlp_coeff_precision + FLAC__bitmath_ilog2(order) <= 32)
  97846. if(bps <= 16 && subframe->qlp_coeff_precision <= 16) {
  97847. if(order <= 8)
  97848. 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);
  97849. else
  97850. 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);
  97851. }
  97852. else
  97853. 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);
  97854. else
  97855. 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);
  97856. }
  97857. return true;
  97858. }
  97859. FLAC__bool read_subframe_verbatim_(FLAC__StreamDecoder *decoder, unsigned channel, unsigned bps, FLAC__bool do_full_decode)
  97860. {
  97861. FLAC__Subframe_Verbatim *subframe = &decoder->private_->frame.subframes[channel].data.verbatim;
  97862. FLAC__int32 x, *residual = decoder->private_->residual[channel];
  97863. unsigned i;
  97864. decoder->private_->frame.subframes[channel].type = FLAC__SUBFRAME_TYPE_VERBATIM;
  97865. subframe->data = residual;
  97866. for(i = 0; i < decoder->private_->frame.header.blocksize; i++) {
  97867. if(!FLAC__bitreader_read_raw_int32(decoder->private_->input, &x, bps))
  97868. return false; /* read_callback_ sets the state for us */
  97869. residual[i] = x;
  97870. }
  97871. /* decode the subframe */
  97872. if(do_full_decode)
  97873. memcpy(decoder->private_->output[channel], subframe->data, sizeof(FLAC__int32) * decoder->private_->frame.header.blocksize);
  97874. return true;
  97875. }
  97876. 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)
  97877. {
  97878. FLAC__uint32 rice_parameter;
  97879. int i;
  97880. unsigned partition, sample, u;
  97881. const unsigned partitions = 1u << partition_order;
  97882. const unsigned partition_samples = partition_order > 0? decoder->private_->frame.header.blocksize >> partition_order : decoder->private_->frame.header.blocksize - predictor_order;
  97883. const unsigned plen = is_extended? FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE2_PARAMETER_LEN : FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE_PARAMETER_LEN;
  97884. const unsigned pesc = is_extended? FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE2_ESCAPE_PARAMETER : FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE_ESCAPE_PARAMETER;
  97885. /* sanity checks */
  97886. if(partition_order == 0) {
  97887. if(decoder->private_->frame.header.blocksize < predictor_order) {
  97888. send_error_to_client_(decoder, FLAC__STREAM_DECODER_ERROR_STATUS_LOST_SYNC);
  97889. decoder->protected_->state = FLAC__STREAM_DECODER_SEARCH_FOR_FRAME_SYNC;
  97890. return true;
  97891. }
  97892. }
  97893. else {
  97894. if(partition_samples < predictor_order) {
  97895. send_error_to_client_(decoder, FLAC__STREAM_DECODER_ERROR_STATUS_LOST_SYNC);
  97896. decoder->protected_->state = FLAC__STREAM_DECODER_SEARCH_FOR_FRAME_SYNC;
  97897. return true;
  97898. }
  97899. }
  97900. if(!FLAC__format_entropy_coding_method_partitioned_rice_contents_ensure_size(partitioned_rice_contents, max(6, partition_order))) {
  97901. decoder->protected_->state = FLAC__STREAM_DECODER_MEMORY_ALLOCATION_ERROR;
  97902. return false;
  97903. }
  97904. sample = 0;
  97905. for(partition = 0; partition < partitions; partition++) {
  97906. if(!FLAC__bitreader_read_raw_uint32(decoder->private_->input, &rice_parameter, plen))
  97907. return false; /* read_callback_ sets the state for us */
  97908. partitioned_rice_contents->parameters[partition] = rice_parameter;
  97909. if(rice_parameter < pesc) {
  97910. partitioned_rice_contents->raw_bits[partition] = 0;
  97911. u = (partition_order == 0 || partition > 0)? partition_samples : partition_samples - predictor_order;
  97912. if(!decoder->private_->local_bitreader_read_rice_signed_block(decoder->private_->input, (int*) residual + sample, u, rice_parameter))
  97913. return false; /* read_callback_ sets the state for us */
  97914. sample += u;
  97915. }
  97916. else {
  97917. if(!FLAC__bitreader_read_raw_uint32(decoder->private_->input, &rice_parameter, FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE_RAW_LEN))
  97918. return false; /* read_callback_ sets the state for us */
  97919. partitioned_rice_contents->raw_bits[partition] = rice_parameter;
  97920. for(u = (partition_order == 0 || partition > 0)? 0 : predictor_order; u < partition_samples; u++, sample++) {
  97921. if(!FLAC__bitreader_read_raw_int32(decoder->private_->input, (FLAC__int32*) &i, rice_parameter))
  97922. return false; /* read_callback_ sets the state for us */
  97923. residual[sample] = i;
  97924. }
  97925. }
  97926. }
  97927. return true;
  97928. }
  97929. FLAC__bool read_zero_padding_(FLAC__StreamDecoder *decoder)
  97930. {
  97931. if(!FLAC__bitreader_is_consumed_byte_aligned(decoder->private_->input)) {
  97932. FLAC__uint32 zero = 0;
  97933. if(!FLAC__bitreader_read_raw_uint32(decoder->private_->input, &zero, FLAC__bitreader_bits_left_for_byte_alignment(decoder->private_->input)))
  97934. return false; /* read_callback_ sets the state for us */
  97935. if(zero != 0) {
  97936. send_error_to_client_(decoder, FLAC__STREAM_DECODER_ERROR_STATUS_LOST_SYNC);
  97937. decoder->protected_->state = FLAC__STREAM_DECODER_SEARCH_FOR_FRAME_SYNC;
  97938. }
  97939. }
  97940. return true;
  97941. }
  97942. FLAC__bool read_callback_(FLAC__byte buffer[], size_t *bytes, void *client_data)
  97943. {
  97944. FLAC__StreamDecoder *decoder = (FLAC__StreamDecoder *)client_data;
  97945. if(
  97946. #if FLAC__HAS_OGG
  97947. /* see [1] HACK NOTE below for why we don't call the eof_callback when decoding Ogg FLAC */
  97948. !decoder->private_->is_ogg &&
  97949. #endif
  97950. decoder->private_->eof_callback && decoder->private_->eof_callback(decoder, decoder->private_->client_data)
  97951. ) {
  97952. *bytes = 0;
  97953. decoder->protected_->state = FLAC__STREAM_DECODER_END_OF_STREAM;
  97954. return false;
  97955. }
  97956. else if(*bytes > 0) {
  97957. /* While seeking, it is possible for our seek to land in the
  97958. * middle of audio data that looks exactly like a frame header
  97959. * from a future version of an encoder. When that happens, our
  97960. * error callback will get an
  97961. * FLAC__STREAM_DECODER_UNPARSEABLE_STREAM and increment its
  97962. * unparseable_frame_count. But there is a remote possibility
  97963. * that it is properly synced at such a "future-codec frame",
  97964. * so to make sure, we wait to see many "unparseable" errors in
  97965. * a row before bailing out.
  97966. */
  97967. if(decoder->private_->is_seeking && decoder->private_->unparseable_frame_count > 20) {
  97968. decoder->protected_->state = FLAC__STREAM_DECODER_ABORTED;
  97969. return false;
  97970. }
  97971. else {
  97972. const FLAC__StreamDecoderReadStatus status =
  97973. #if FLAC__HAS_OGG
  97974. decoder->private_->is_ogg?
  97975. read_callback_ogg_aspect_(decoder, buffer, bytes) :
  97976. #endif
  97977. decoder->private_->read_callback(decoder, buffer, bytes, decoder->private_->client_data)
  97978. ;
  97979. if(status == FLAC__STREAM_DECODER_READ_STATUS_ABORT) {
  97980. decoder->protected_->state = FLAC__STREAM_DECODER_ABORTED;
  97981. return false;
  97982. }
  97983. else if(*bytes == 0) {
  97984. if(
  97985. status == FLAC__STREAM_DECODER_READ_STATUS_END_OF_STREAM ||
  97986. (
  97987. #if FLAC__HAS_OGG
  97988. /* see [1] HACK NOTE below for why we don't call the eof_callback when decoding Ogg FLAC */
  97989. !decoder->private_->is_ogg &&
  97990. #endif
  97991. decoder->private_->eof_callback && decoder->private_->eof_callback(decoder, decoder->private_->client_data)
  97992. )
  97993. ) {
  97994. decoder->protected_->state = FLAC__STREAM_DECODER_END_OF_STREAM;
  97995. return false;
  97996. }
  97997. else
  97998. return true;
  97999. }
  98000. else
  98001. return true;
  98002. }
  98003. }
  98004. else {
  98005. /* abort to avoid a deadlock */
  98006. decoder->protected_->state = FLAC__STREAM_DECODER_ABORTED;
  98007. return false;
  98008. }
  98009. /* [1] @@@ HACK NOTE: The end-of-stream checking has to be hacked around
  98010. * for Ogg FLAC. This is because the ogg decoder aspect can lose sync
  98011. * and at the same time hit the end of the stream (for example, seeking
  98012. * to a point that is after the beginning of the last Ogg page). There
  98013. * is no way to report an Ogg sync loss through the callbacks (see note
  98014. * in read_callback_ogg_aspect_()) so it returns CONTINUE with *bytes==0.
  98015. * So to keep the decoder from stopping at this point we gate the call
  98016. * to the eof_callback and let the Ogg decoder aspect set the
  98017. * end-of-stream state when it is needed.
  98018. */
  98019. }
  98020. #if FLAC__HAS_OGG
  98021. FLAC__StreamDecoderReadStatus read_callback_ogg_aspect_(const FLAC__StreamDecoder *decoder, FLAC__byte buffer[], size_t *bytes)
  98022. {
  98023. switch(FLAC__ogg_decoder_aspect_read_callback_wrapper(&decoder->protected_->ogg_decoder_aspect, buffer, bytes, read_callback_proxy_, decoder, decoder->private_->client_data)) {
  98024. case FLAC__OGG_DECODER_ASPECT_READ_STATUS_OK:
  98025. return FLAC__STREAM_DECODER_READ_STATUS_CONTINUE;
  98026. /* we don't really have a way to handle lost sync via read
  98027. * callback so we'll let it pass and let the underlying
  98028. * FLAC decoder catch the error
  98029. */
  98030. case FLAC__OGG_DECODER_ASPECT_READ_STATUS_LOST_SYNC:
  98031. return FLAC__STREAM_DECODER_READ_STATUS_CONTINUE;
  98032. case FLAC__OGG_DECODER_ASPECT_READ_STATUS_END_OF_STREAM:
  98033. return FLAC__STREAM_DECODER_READ_STATUS_END_OF_STREAM;
  98034. case FLAC__OGG_DECODER_ASPECT_READ_STATUS_NOT_FLAC:
  98035. case FLAC__OGG_DECODER_ASPECT_READ_STATUS_UNSUPPORTED_MAPPING_VERSION:
  98036. case FLAC__OGG_DECODER_ASPECT_READ_STATUS_ABORT:
  98037. case FLAC__OGG_DECODER_ASPECT_READ_STATUS_ERROR:
  98038. case FLAC__OGG_DECODER_ASPECT_READ_STATUS_MEMORY_ALLOCATION_ERROR:
  98039. return FLAC__STREAM_DECODER_READ_STATUS_ABORT;
  98040. default:
  98041. FLAC__ASSERT(0);
  98042. /* double protection */
  98043. return FLAC__STREAM_DECODER_READ_STATUS_ABORT;
  98044. }
  98045. }
  98046. FLAC__OggDecoderAspectReadStatus read_callback_proxy_(const void *void_decoder, FLAC__byte buffer[], size_t *bytes, void *client_data)
  98047. {
  98048. FLAC__StreamDecoder *decoder = (FLAC__StreamDecoder*)void_decoder;
  98049. switch(decoder->private_->read_callback(decoder, buffer, bytes, client_data)) {
  98050. case FLAC__STREAM_DECODER_READ_STATUS_CONTINUE:
  98051. return FLAC__OGG_DECODER_ASPECT_READ_STATUS_OK;
  98052. case FLAC__STREAM_DECODER_READ_STATUS_END_OF_STREAM:
  98053. return FLAC__OGG_DECODER_ASPECT_READ_STATUS_END_OF_STREAM;
  98054. case FLAC__STREAM_DECODER_READ_STATUS_ABORT:
  98055. return FLAC__OGG_DECODER_ASPECT_READ_STATUS_ABORT;
  98056. default:
  98057. /* double protection: */
  98058. FLAC__ASSERT(0);
  98059. return FLAC__OGG_DECODER_ASPECT_READ_STATUS_ABORT;
  98060. }
  98061. }
  98062. #endif
  98063. FLAC__StreamDecoderWriteStatus write_audio_frame_to_client_(FLAC__StreamDecoder *decoder, const FLAC__Frame *frame, const FLAC__int32 * const buffer[])
  98064. {
  98065. if(decoder->private_->is_seeking) {
  98066. FLAC__uint64 this_frame_sample = frame->header.number.sample_number;
  98067. FLAC__uint64 next_frame_sample = this_frame_sample + (FLAC__uint64)frame->header.blocksize;
  98068. FLAC__uint64 target_sample = decoder->private_->target_sample;
  98069. FLAC__ASSERT(frame->header.number_type == FLAC__FRAME_NUMBER_TYPE_SAMPLE_NUMBER);
  98070. #if FLAC__HAS_OGG
  98071. decoder->private_->got_a_frame = true;
  98072. #endif
  98073. decoder->private_->last_frame = *frame; /* save the frame */
  98074. if(this_frame_sample <= target_sample && target_sample < next_frame_sample) { /* we hit our target frame */
  98075. unsigned delta = (unsigned)(target_sample - this_frame_sample);
  98076. /* kick out of seek mode */
  98077. decoder->private_->is_seeking = false;
  98078. /* shift out the samples before target_sample */
  98079. if(delta > 0) {
  98080. unsigned channel;
  98081. const FLAC__int32 *newbuffer[FLAC__MAX_CHANNELS];
  98082. for(channel = 0; channel < frame->header.channels; channel++)
  98083. newbuffer[channel] = buffer[channel] + delta;
  98084. decoder->private_->last_frame.header.blocksize -= delta;
  98085. decoder->private_->last_frame.header.number.sample_number += (FLAC__uint64)delta;
  98086. /* write the relevant samples */
  98087. return decoder->private_->write_callback(decoder, &decoder->private_->last_frame, newbuffer, decoder->private_->client_data);
  98088. }
  98089. else {
  98090. /* write the relevant samples */
  98091. return decoder->private_->write_callback(decoder, frame, buffer, decoder->private_->client_data);
  98092. }
  98093. }
  98094. return FLAC__STREAM_DECODER_WRITE_STATUS_CONTINUE;
  98095. }
  98096. /*
  98097. * If we never got STREAMINFO, turn off MD5 checking to save
  98098. * cycles since we don't have a sum to compare to anyway
  98099. */
  98100. if(!decoder->private_->has_stream_info)
  98101. decoder->private_->do_md5_checking = false;
  98102. if(decoder->private_->do_md5_checking) {
  98103. if(!FLAC__MD5Accumulate(&decoder->private_->md5context, buffer, frame->header.channels, frame->header.blocksize, (frame->header.bits_per_sample+7) / 8))
  98104. return FLAC__STREAM_DECODER_WRITE_STATUS_ABORT;
  98105. }
  98106. return decoder->private_->write_callback(decoder, frame, buffer, decoder->private_->client_data);
  98107. }
  98108. void send_error_to_client_(const FLAC__StreamDecoder *decoder, FLAC__StreamDecoderErrorStatus status)
  98109. {
  98110. if(!decoder->private_->is_seeking)
  98111. decoder->private_->error_callback(decoder, status, decoder->private_->client_data);
  98112. else if(status == FLAC__STREAM_DECODER_ERROR_STATUS_UNPARSEABLE_STREAM)
  98113. decoder->private_->unparseable_frame_count++;
  98114. }
  98115. FLAC__bool seek_to_absolute_sample_(FLAC__StreamDecoder *decoder, FLAC__uint64 stream_length, FLAC__uint64 target_sample)
  98116. {
  98117. FLAC__uint64 first_frame_offset = decoder->private_->first_frame_offset, lower_bound, upper_bound, lower_bound_sample, upper_bound_sample, this_frame_sample;
  98118. FLAC__int64 pos = -1;
  98119. int i;
  98120. unsigned approx_bytes_per_frame;
  98121. FLAC__bool first_seek = true;
  98122. const FLAC__uint64 total_samples = FLAC__stream_decoder_get_total_samples(decoder);
  98123. const unsigned min_blocksize = decoder->private_->stream_info.data.stream_info.min_blocksize;
  98124. const unsigned max_blocksize = decoder->private_->stream_info.data.stream_info.max_blocksize;
  98125. const unsigned max_framesize = decoder->private_->stream_info.data.stream_info.max_framesize;
  98126. const unsigned min_framesize = decoder->private_->stream_info.data.stream_info.min_framesize;
  98127. /* take these from the current frame in case they've changed mid-stream */
  98128. unsigned channels = FLAC__stream_decoder_get_channels(decoder);
  98129. unsigned bps = FLAC__stream_decoder_get_bits_per_sample(decoder);
  98130. const FLAC__StreamMetadata_SeekTable *seek_table = decoder->private_->has_seek_table? &decoder->private_->seek_table.data.seek_table : 0;
  98131. /* use values from stream info if we didn't decode a frame */
  98132. if(channels == 0)
  98133. channels = decoder->private_->stream_info.data.stream_info.channels;
  98134. if(bps == 0)
  98135. bps = decoder->private_->stream_info.data.stream_info.bits_per_sample;
  98136. /* we are just guessing here */
  98137. if(max_framesize > 0)
  98138. approx_bytes_per_frame = (max_framesize + min_framesize) / 2 + 1;
  98139. /*
  98140. * Check if it's a known fixed-blocksize stream. Note that though
  98141. * the spec doesn't allow zeroes in the STREAMINFO block, we may
  98142. * never get a STREAMINFO block when decoding so the value of
  98143. * min_blocksize might be zero.
  98144. */
  98145. else if(min_blocksize == max_blocksize && min_blocksize > 0) {
  98146. /* note there are no () around 'bps/8' to keep precision up since it's an integer calulation */
  98147. approx_bytes_per_frame = min_blocksize * channels * bps/8 + 64;
  98148. }
  98149. else
  98150. approx_bytes_per_frame = 4096 * channels * bps/8 + 64;
  98151. /*
  98152. * First, we set an upper and lower bound on where in the
  98153. * stream we will search. For now we assume the worst case
  98154. * scenario, which is our best guess at the beginning of
  98155. * the first frame and end of the stream.
  98156. */
  98157. lower_bound = first_frame_offset;
  98158. lower_bound_sample = 0;
  98159. upper_bound = stream_length;
  98160. upper_bound_sample = total_samples > 0 ? total_samples : target_sample /*estimate it*/;
  98161. /*
  98162. * Now we refine the bounds if we have a seektable with
  98163. * suitable points. Note that according to the spec they
  98164. * must be ordered by ascending sample number.
  98165. *
  98166. * Note: to protect against invalid seek tables we will ignore points
  98167. * that have frame_samples==0 or sample_number>=total_samples
  98168. */
  98169. if(seek_table) {
  98170. FLAC__uint64 new_lower_bound = lower_bound;
  98171. FLAC__uint64 new_upper_bound = upper_bound;
  98172. FLAC__uint64 new_lower_bound_sample = lower_bound_sample;
  98173. FLAC__uint64 new_upper_bound_sample = upper_bound_sample;
  98174. /* find the closest seek point <= target_sample, if it exists */
  98175. for(i = (int)seek_table->num_points - 1; i >= 0; i--) {
  98176. if(
  98177. seek_table->points[i].sample_number != FLAC__STREAM_METADATA_SEEKPOINT_PLACEHOLDER &&
  98178. seek_table->points[i].frame_samples > 0 && /* defense against bad seekpoints */
  98179. (total_samples <= 0 || seek_table->points[i].sample_number < total_samples) && /* defense against bad seekpoints */
  98180. seek_table->points[i].sample_number <= target_sample
  98181. )
  98182. break;
  98183. }
  98184. if(i >= 0) { /* i.e. we found a suitable seek point... */
  98185. new_lower_bound = first_frame_offset + seek_table->points[i].stream_offset;
  98186. new_lower_bound_sample = seek_table->points[i].sample_number;
  98187. }
  98188. /* find the closest seek point > target_sample, if it exists */
  98189. for(i = 0; i < (int)seek_table->num_points; i++) {
  98190. if(
  98191. seek_table->points[i].sample_number != FLAC__STREAM_METADATA_SEEKPOINT_PLACEHOLDER &&
  98192. seek_table->points[i].frame_samples > 0 && /* defense against bad seekpoints */
  98193. (total_samples <= 0 || seek_table->points[i].sample_number < total_samples) && /* defense against bad seekpoints */
  98194. seek_table->points[i].sample_number > target_sample
  98195. )
  98196. break;
  98197. }
  98198. if(i < (int)seek_table->num_points) { /* i.e. we found a suitable seek point... */
  98199. new_upper_bound = first_frame_offset + seek_table->points[i].stream_offset;
  98200. new_upper_bound_sample = seek_table->points[i].sample_number;
  98201. }
  98202. /* final protection against unsorted seek tables; keep original values if bogus */
  98203. if(new_upper_bound >= new_lower_bound) {
  98204. lower_bound = new_lower_bound;
  98205. upper_bound = new_upper_bound;
  98206. lower_bound_sample = new_lower_bound_sample;
  98207. upper_bound_sample = new_upper_bound_sample;
  98208. }
  98209. }
  98210. FLAC__ASSERT(upper_bound_sample >= lower_bound_sample);
  98211. /* there are 2 insidious ways that the following equality occurs, which
  98212. * we need to fix:
  98213. * 1) total_samples is 0 (unknown) and target_sample is 0
  98214. * 2) total_samples is 0 (unknown) and target_sample happens to be
  98215. * exactly equal to the last seek point in the seek table; this
  98216. * means there is no seek point above it, and upper_bound_samples
  98217. * remains equal to the estimate (of target_samples) we made above
  98218. * in either case it does not hurt to move upper_bound_sample up by 1
  98219. */
  98220. if(upper_bound_sample == lower_bound_sample)
  98221. upper_bound_sample++;
  98222. decoder->private_->target_sample = target_sample;
  98223. while(1) {
  98224. /* check if the bounds are still ok */
  98225. if (lower_bound_sample >= upper_bound_sample || lower_bound > upper_bound) {
  98226. decoder->protected_->state = FLAC__STREAM_DECODER_SEEK_ERROR;
  98227. return false;
  98228. }
  98229. #ifndef FLAC__INTEGER_ONLY_LIBRARY
  98230. #if defined _MSC_VER || defined __MINGW32__
  98231. /* with VC++ you have to spoon feed it the casting */
  98232. 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;
  98233. #else
  98234. 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;
  98235. #endif
  98236. #else
  98237. /* a little less accurate: */
  98238. if(upper_bound - lower_bound < 0xffffffff)
  98239. 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;
  98240. else /* @@@ WATCHOUT, ~2TB limit */
  98241. 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;
  98242. #endif
  98243. if(pos >= (FLAC__int64)upper_bound)
  98244. pos = (FLAC__int64)upper_bound - 1;
  98245. if(pos < (FLAC__int64)lower_bound)
  98246. pos = (FLAC__int64)lower_bound;
  98247. if(decoder->private_->seek_callback(decoder, (FLAC__uint64)pos, decoder->private_->client_data) != FLAC__STREAM_DECODER_SEEK_STATUS_OK) {
  98248. decoder->protected_->state = FLAC__STREAM_DECODER_SEEK_ERROR;
  98249. return false;
  98250. }
  98251. if(!FLAC__stream_decoder_flush(decoder)) {
  98252. /* above call sets the state for us */
  98253. return false;
  98254. }
  98255. /* Now we need to get a frame. First we need to reset our
  98256. * unparseable_frame_count; if we get too many unparseable
  98257. * frames in a row, the read callback will return
  98258. * FLAC__STREAM_DECODER_READ_STATUS_ABORT, causing
  98259. * FLAC__stream_decoder_process_single() to return false.
  98260. */
  98261. decoder->private_->unparseable_frame_count = 0;
  98262. if(!FLAC__stream_decoder_process_single(decoder)) {
  98263. decoder->protected_->state = FLAC__STREAM_DECODER_SEEK_ERROR;
  98264. return false;
  98265. }
  98266. /* our write callback will change the state when it gets to the target frame */
  98267. /* 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 */
  98268. #if 0
  98269. /*@@@@@@ used to be the following; not clear if the check for end of stream is needed anymore */
  98270. if(decoder->protected_->state != FLAC__SEEKABLE_STREAM_DECODER_SEEKING && decoder->protected_->state != FLAC__STREAM_DECODER_END_OF_STREAM)
  98271. break;
  98272. #endif
  98273. if(!decoder->private_->is_seeking)
  98274. break;
  98275. FLAC__ASSERT(decoder->private_->last_frame.header.number_type == FLAC__FRAME_NUMBER_TYPE_SAMPLE_NUMBER);
  98276. this_frame_sample = decoder->private_->last_frame.header.number.sample_number;
  98277. if (0 == decoder->private_->samples_decoded || (this_frame_sample + decoder->private_->last_frame.header.blocksize >= upper_bound_sample && !first_seek)) {
  98278. if (pos == (FLAC__int64)lower_bound) {
  98279. /* can't move back any more than the first frame, something is fatally wrong */
  98280. decoder->protected_->state = FLAC__STREAM_DECODER_SEEK_ERROR;
  98281. return false;
  98282. }
  98283. /* our last move backwards wasn't big enough, try again */
  98284. approx_bytes_per_frame = approx_bytes_per_frame? approx_bytes_per_frame * 2 : 16;
  98285. continue;
  98286. }
  98287. /* allow one seek over upper bound, so we can get a correct upper_bound_sample for streams with unknown total_samples */
  98288. first_seek = false;
  98289. /* make sure we are not seeking in corrupted stream */
  98290. if (this_frame_sample < lower_bound_sample) {
  98291. decoder->protected_->state = FLAC__STREAM_DECODER_SEEK_ERROR;
  98292. return false;
  98293. }
  98294. /* we need to narrow the search */
  98295. if(target_sample < this_frame_sample) {
  98296. upper_bound_sample = this_frame_sample + decoder->private_->last_frame.header.blocksize;
  98297. /*@@@@@@ what will decode position be if at end of stream? */
  98298. if(!FLAC__stream_decoder_get_decode_position(decoder, &upper_bound)) {
  98299. decoder->protected_->state = FLAC__STREAM_DECODER_SEEK_ERROR;
  98300. return false;
  98301. }
  98302. approx_bytes_per_frame = (unsigned)(2 * (upper_bound - pos) / 3 + 16);
  98303. }
  98304. else { /* target_sample >= this_frame_sample + this frame's blocksize */
  98305. lower_bound_sample = this_frame_sample + decoder->private_->last_frame.header.blocksize;
  98306. if(!FLAC__stream_decoder_get_decode_position(decoder, &lower_bound)) {
  98307. decoder->protected_->state = FLAC__STREAM_DECODER_SEEK_ERROR;
  98308. return false;
  98309. }
  98310. approx_bytes_per_frame = (unsigned)(2 * (lower_bound - pos) / 3 + 16);
  98311. }
  98312. }
  98313. return true;
  98314. }
  98315. #if FLAC__HAS_OGG
  98316. FLAC__bool seek_to_absolute_sample_ogg_(FLAC__StreamDecoder *decoder, FLAC__uint64 stream_length, FLAC__uint64 target_sample)
  98317. {
  98318. FLAC__uint64 left_pos = 0, right_pos = stream_length;
  98319. FLAC__uint64 left_sample = 0, right_sample = FLAC__stream_decoder_get_total_samples(decoder);
  98320. FLAC__uint64 this_frame_sample = (FLAC__uint64)0 - 1;
  98321. FLAC__uint64 pos = 0; /* only initialized to avoid compiler warning */
  98322. FLAC__bool did_a_seek;
  98323. unsigned iteration = 0;
  98324. /* In the first iterations, we will calculate the target byte position
  98325. * by the distance from the target sample to left_sample and
  98326. * right_sample (let's call it "proportional search"). After that, we
  98327. * will switch to binary search.
  98328. */
  98329. unsigned BINARY_SEARCH_AFTER_ITERATION = 2;
  98330. /* We will switch to a linear search once our current sample is less
  98331. * than this number of samples ahead of the target sample
  98332. */
  98333. static const FLAC__uint64 LINEAR_SEARCH_WITHIN_SAMPLES = FLAC__MAX_BLOCK_SIZE * 2;
  98334. /* If the total number of samples is unknown, use a large value, and
  98335. * force binary search immediately.
  98336. */
  98337. if(right_sample == 0) {
  98338. right_sample = (FLAC__uint64)(-1);
  98339. BINARY_SEARCH_AFTER_ITERATION = 0;
  98340. }
  98341. decoder->private_->target_sample = target_sample;
  98342. for( ; ; iteration++) {
  98343. if (iteration == 0 || this_frame_sample > target_sample || target_sample - this_frame_sample > LINEAR_SEARCH_WITHIN_SAMPLES) {
  98344. if (iteration >= BINARY_SEARCH_AFTER_ITERATION) {
  98345. pos = (right_pos + left_pos) / 2;
  98346. }
  98347. else {
  98348. #ifndef FLAC__INTEGER_ONLY_LIBRARY
  98349. #if defined _MSC_VER || defined __MINGW32__
  98350. /* with MSVC you have to spoon feed it the casting */
  98351. 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));
  98352. #else
  98353. pos = (FLAC__uint64)((FLAC__double)(target_sample - left_sample) / (FLAC__double)(right_sample - left_sample) * (FLAC__double)(right_pos - left_pos));
  98354. #endif
  98355. #else
  98356. /* a little less accurate: */
  98357. if ((target_sample-left_sample <= 0xffffffff) && (right_pos-left_pos <= 0xffffffff))
  98358. pos = (FLAC__int64)(((target_sample-left_sample) * (right_pos-left_pos)) / (right_sample-left_sample));
  98359. else /* @@@ WATCHOUT, ~2TB limit */
  98360. pos = (FLAC__int64)((((target_sample-left_sample)>>8) * ((right_pos-left_pos)>>8)) / ((right_sample-left_sample)>>16));
  98361. #endif
  98362. /* @@@ TODO: might want to limit pos to some distance
  98363. * before EOF, to make sure we land before the last frame,
  98364. * thereby getting a this_frame_sample and so having a better
  98365. * estimate.
  98366. */
  98367. }
  98368. /* physical seek */
  98369. if(decoder->private_->seek_callback((FLAC__StreamDecoder*)decoder, (FLAC__uint64)pos, decoder->private_->client_data) != FLAC__STREAM_DECODER_SEEK_STATUS_OK) {
  98370. decoder->protected_->state = FLAC__STREAM_DECODER_SEEK_ERROR;
  98371. return false;
  98372. }
  98373. if(!FLAC__stream_decoder_flush(decoder)) {
  98374. /* above call sets the state for us */
  98375. return false;
  98376. }
  98377. did_a_seek = true;
  98378. }
  98379. else
  98380. did_a_seek = false;
  98381. decoder->private_->got_a_frame = false;
  98382. if(!FLAC__stream_decoder_process_single(decoder)) {
  98383. decoder->protected_->state = FLAC__STREAM_DECODER_SEEK_ERROR;
  98384. return false;
  98385. }
  98386. if(!decoder->private_->got_a_frame) {
  98387. if(did_a_seek) {
  98388. /* this can happen if we seek to a point after the last frame; we drop
  98389. * to binary search right away in this case to avoid any wasted
  98390. * iterations of proportional search.
  98391. */
  98392. right_pos = pos;
  98393. BINARY_SEARCH_AFTER_ITERATION = 0;
  98394. }
  98395. else {
  98396. /* this can probably only happen if total_samples is unknown and the
  98397. * target_sample is past the end of the stream
  98398. */
  98399. decoder->protected_->state = FLAC__STREAM_DECODER_SEEK_ERROR;
  98400. return false;
  98401. }
  98402. }
  98403. /* our write callback will change the state when it gets to the target frame */
  98404. else if(!decoder->private_->is_seeking) {
  98405. break;
  98406. }
  98407. else {
  98408. this_frame_sample = decoder->private_->last_frame.header.number.sample_number;
  98409. FLAC__ASSERT(decoder->private_->last_frame.header.number_type == FLAC__FRAME_NUMBER_TYPE_SAMPLE_NUMBER);
  98410. if (did_a_seek) {
  98411. if (this_frame_sample <= target_sample) {
  98412. /* The 'equal' case should not happen, since
  98413. * FLAC__stream_decoder_process_single()
  98414. * should recognize that it has hit the
  98415. * target sample and we would exit through
  98416. * the 'break' above.
  98417. */
  98418. FLAC__ASSERT(this_frame_sample != target_sample);
  98419. left_sample = this_frame_sample;
  98420. /* sanity check to avoid infinite loop */
  98421. if (left_pos == pos) {
  98422. decoder->protected_->state = FLAC__STREAM_DECODER_SEEK_ERROR;
  98423. return false;
  98424. }
  98425. left_pos = pos;
  98426. }
  98427. else if(this_frame_sample > target_sample) {
  98428. right_sample = this_frame_sample;
  98429. /* sanity check to avoid infinite loop */
  98430. if (right_pos == pos) {
  98431. decoder->protected_->state = FLAC__STREAM_DECODER_SEEK_ERROR;
  98432. return false;
  98433. }
  98434. right_pos = pos;
  98435. }
  98436. }
  98437. }
  98438. }
  98439. return true;
  98440. }
  98441. #endif
  98442. FLAC__StreamDecoderReadStatus file_read_callback_dec(const FLAC__StreamDecoder *decoder, FLAC__byte buffer[], size_t *bytes, void *client_data)
  98443. {
  98444. (void)client_data;
  98445. if(*bytes > 0) {
  98446. *bytes = fread(buffer, sizeof(FLAC__byte), *bytes, decoder->private_->file);
  98447. if(ferror(decoder->private_->file))
  98448. return FLAC__STREAM_DECODER_READ_STATUS_ABORT;
  98449. else if(*bytes == 0)
  98450. return FLAC__STREAM_DECODER_READ_STATUS_END_OF_STREAM;
  98451. else
  98452. return FLAC__STREAM_DECODER_READ_STATUS_CONTINUE;
  98453. }
  98454. else
  98455. return FLAC__STREAM_DECODER_READ_STATUS_ABORT; /* abort to avoid a deadlock */
  98456. }
  98457. FLAC__StreamDecoderSeekStatus file_seek_callback_dec(const FLAC__StreamDecoder *decoder, FLAC__uint64 absolute_byte_offset, void *client_data)
  98458. {
  98459. (void)client_data;
  98460. if(decoder->private_->file == stdin)
  98461. return FLAC__STREAM_DECODER_SEEK_STATUS_UNSUPPORTED;
  98462. else if(fseeko(decoder->private_->file, (off_t)absolute_byte_offset, SEEK_SET) < 0)
  98463. return FLAC__STREAM_DECODER_SEEK_STATUS_ERROR;
  98464. else
  98465. return FLAC__STREAM_DECODER_SEEK_STATUS_OK;
  98466. }
  98467. FLAC__StreamDecoderTellStatus file_tell_callback_dec(const FLAC__StreamDecoder *decoder, FLAC__uint64 *absolute_byte_offset, void *client_data)
  98468. {
  98469. off_t pos;
  98470. (void)client_data;
  98471. if(decoder->private_->file == stdin)
  98472. return FLAC__STREAM_DECODER_TELL_STATUS_UNSUPPORTED;
  98473. else if((pos = ftello(decoder->private_->file)) < 0)
  98474. return FLAC__STREAM_DECODER_TELL_STATUS_ERROR;
  98475. else {
  98476. *absolute_byte_offset = (FLAC__uint64)pos;
  98477. return FLAC__STREAM_DECODER_TELL_STATUS_OK;
  98478. }
  98479. }
  98480. FLAC__StreamDecoderLengthStatus file_length_callback_(const FLAC__StreamDecoder *decoder, FLAC__uint64 *stream_length, void *client_data)
  98481. {
  98482. struct stat filestats;
  98483. (void)client_data;
  98484. if(decoder->private_->file == stdin)
  98485. return FLAC__STREAM_DECODER_LENGTH_STATUS_UNSUPPORTED;
  98486. else if(fstat(fileno(decoder->private_->file), &filestats) != 0)
  98487. return FLAC__STREAM_DECODER_LENGTH_STATUS_ERROR;
  98488. else {
  98489. *stream_length = (FLAC__uint64)filestats.st_size;
  98490. return FLAC__STREAM_DECODER_LENGTH_STATUS_OK;
  98491. }
  98492. }
  98493. FLAC__bool file_eof_callback_(const FLAC__StreamDecoder *decoder, void *client_data)
  98494. {
  98495. (void)client_data;
  98496. return feof(decoder->private_->file)? true : false;
  98497. }
  98498. #endif
  98499. /*** End of inlined file: stream_decoder.c ***/
  98500. /*** Start of inlined file: stream_encoder.c ***/
  98501. /*** Start of inlined file: juce_FlacHeader.h ***/
  98502. // This file is included at the start of each FLAC .c file, just to do a few housekeeping
  98503. // tasks..
  98504. #define VERSION "1.2.1"
  98505. #define FLAC__NO_DLL 1
  98506. #if JUCE_MSVC
  98507. #pragma warning (disable: 4267 4127 4244 4996 4100 4701 4702 4013 4133 4206 4312)
  98508. #endif
  98509. #if JUCE_MAC
  98510. #define FLAC__SYS_DARWIN 1
  98511. #endif
  98512. /*** End of inlined file: juce_FlacHeader.h ***/
  98513. #if JUCE_USE_FLAC
  98514. #if HAVE_CONFIG_H
  98515. # include <config.h>
  98516. #endif
  98517. #if defined _MSC_VER || defined __MINGW32__
  98518. #include <io.h> /* for _setmode() */
  98519. #include <fcntl.h> /* for _O_BINARY */
  98520. #endif
  98521. #if defined __CYGWIN__ || defined __EMX__
  98522. #include <io.h> /* for setmode(), O_BINARY */
  98523. #include <fcntl.h> /* for _O_BINARY */
  98524. #endif
  98525. #include <limits.h>
  98526. #include <stdio.h>
  98527. #include <stdlib.h> /* for malloc() */
  98528. #include <string.h> /* for memcpy() */
  98529. #include <sys/types.h> /* for off_t */
  98530. #if defined _MSC_VER || defined __BORLANDC__ || defined __MINGW32__
  98531. #if _MSC_VER <= 1600 || defined __BORLANDC__ /* @@@ [2G limit] */
  98532. #define fseeko fseek
  98533. #define ftello ftell
  98534. #endif
  98535. #endif
  98536. /*** Start of inlined file: stream_encoder.h ***/
  98537. #ifndef FLAC__PROTECTED__STREAM_ENCODER_H
  98538. #define FLAC__PROTECTED__STREAM_ENCODER_H
  98539. #if FLAC__HAS_OGG
  98540. #include "private/ogg_encoder_aspect.h"
  98541. #endif
  98542. #ifndef FLAC__INTEGER_ONLY_LIBRARY
  98543. #define FLAC__MAX_APODIZATION_FUNCTIONS 32
  98544. typedef enum {
  98545. FLAC__APODIZATION_BARTLETT,
  98546. FLAC__APODIZATION_BARTLETT_HANN,
  98547. FLAC__APODIZATION_BLACKMAN,
  98548. FLAC__APODIZATION_BLACKMAN_HARRIS_4TERM_92DB_SIDELOBE,
  98549. FLAC__APODIZATION_CONNES,
  98550. FLAC__APODIZATION_FLATTOP,
  98551. FLAC__APODIZATION_GAUSS,
  98552. FLAC__APODIZATION_HAMMING,
  98553. FLAC__APODIZATION_HANN,
  98554. FLAC__APODIZATION_KAISER_BESSEL,
  98555. FLAC__APODIZATION_NUTTALL,
  98556. FLAC__APODIZATION_RECTANGLE,
  98557. FLAC__APODIZATION_TRIANGLE,
  98558. FLAC__APODIZATION_TUKEY,
  98559. FLAC__APODIZATION_WELCH
  98560. } FLAC__ApodizationFunction;
  98561. typedef struct {
  98562. FLAC__ApodizationFunction type;
  98563. union {
  98564. struct {
  98565. FLAC__real stddev;
  98566. } gauss;
  98567. struct {
  98568. FLAC__real p;
  98569. } tukey;
  98570. } parameters;
  98571. } FLAC__ApodizationSpecification;
  98572. #endif // #ifndef FLAC__INTEGER_ONLY_LIBRARY
  98573. typedef struct FLAC__StreamEncoderProtected {
  98574. FLAC__StreamEncoderState state;
  98575. FLAC__bool verify;
  98576. FLAC__bool streamable_subset;
  98577. FLAC__bool do_md5;
  98578. FLAC__bool do_mid_side_stereo;
  98579. FLAC__bool loose_mid_side_stereo;
  98580. unsigned channels;
  98581. unsigned bits_per_sample;
  98582. unsigned sample_rate;
  98583. unsigned blocksize;
  98584. #ifndef FLAC__INTEGER_ONLY_LIBRARY
  98585. unsigned num_apodizations;
  98586. FLAC__ApodizationSpecification apodizations[FLAC__MAX_APODIZATION_FUNCTIONS];
  98587. #endif
  98588. unsigned max_lpc_order;
  98589. unsigned qlp_coeff_precision;
  98590. FLAC__bool do_qlp_coeff_prec_search;
  98591. FLAC__bool do_exhaustive_model_search;
  98592. FLAC__bool do_escape_coding;
  98593. unsigned min_residual_partition_order;
  98594. unsigned max_residual_partition_order;
  98595. unsigned rice_parameter_search_dist;
  98596. FLAC__uint64 total_samples_estimate;
  98597. FLAC__StreamMetadata **metadata;
  98598. unsigned num_metadata_blocks;
  98599. FLAC__uint64 streaminfo_offset, seektable_offset, audio_offset;
  98600. #if FLAC__HAS_OGG
  98601. FLAC__OggEncoderAspect ogg_encoder_aspect;
  98602. #endif
  98603. } FLAC__StreamEncoderProtected;
  98604. #endif
  98605. /*** End of inlined file: stream_encoder.h ***/
  98606. #if FLAC__HAS_OGG
  98607. #include "include/private/ogg_helper.h"
  98608. #include "include/private/ogg_mapping.h"
  98609. #endif
  98610. /*** Start of inlined file: stream_encoder_framing.h ***/
  98611. #ifndef FLAC__PRIVATE__STREAM_ENCODER_FRAMING_H
  98612. #define FLAC__PRIVATE__STREAM_ENCODER_FRAMING_H
  98613. FLAC__bool FLAC__add_metadata_block(const FLAC__StreamMetadata *metadata, FLAC__BitWriter *bw);
  98614. FLAC__bool FLAC__frame_add_header(const FLAC__FrameHeader *header, FLAC__BitWriter *bw);
  98615. FLAC__bool FLAC__subframe_add_constant(const FLAC__Subframe_Constant *subframe, unsigned subframe_bps, unsigned wasted_bits, FLAC__BitWriter *bw);
  98616. FLAC__bool FLAC__subframe_add_fixed(const FLAC__Subframe_Fixed *subframe, unsigned residual_samples, unsigned subframe_bps, unsigned wasted_bits, FLAC__BitWriter *bw);
  98617. FLAC__bool FLAC__subframe_add_lpc(const FLAC__Subframe_LPC *subframe, unsigned residual_samples, unsigned subframe_bps, unsigned wasted_bits, FLAC__BitWriter *bw);
  98618. FLAC__bool FLAC__subframe_add_verbatim(const FLAC__Subframe_Verbatim *subframe, unsigned samples, unsigned subframe_bps, unsigned wasted_bits, FLAC__BitWriter *bw);
  98619. #endif
  98620. /*** End of inlined file: stream_encoder_framing.h ***/
  98621. /*** Start of inlined file: window.h ***/
  98622. #ifndef FLAC__PRIVATE__WINDOW_H
  98623. #define FLAC__PRIVATE__WINDOW_H
  98624. #ifdef HAVE_CONFIG_H
  98625. #include <config.h>
  98626. #endif
  98627. #ifndef FLAC__INTEGER_ONLY_LIBRARY
  98628. /*
  98629. * FLAC__window_*()
  98630. * --------------------------------------------------------------------
  98631. * Calculates window coefficients according to different apodization
  98632. * functions.
  98633. *
  98634. * OUT window[0,L-1]
  98635. * IN L (number of points in window)
  98636. */
  98637. void FLAC__window_bartlett(FLAC__real *window, const FLAC__int32 L);
  98638. void FLAC__window_bartlett_hann(FLAC__real *window, const FLAC__int32 L);
  98639. void FLAC__window_blackman(FLAC__real *window, const FLAC__int32 L);
  98640. void FLAC__window_blackman_harris_4term_92db_sidelobe(FLAC__real *window, const FLAC__int32 L);
  98641. void FLAC__window_connes(FLAC__real *window, const FLAC__int32 L);
  98642. void FLAC__window_flattop(FLAC__real *window, const FLAC__int32 L);
  98643. void FLAC__window_gauss(FLAC__real *window, const FLAC__int32 L, const FLAC__real stddev); /* 0.0 < stddev <= 0.5 */
  98644. void FLAC__window_hamming(FLAC__real *window, const FLAC__int32 L);
  98645. void FLAC__window_hann(FLAC__real *window, const FLAC__int32 L);
  98646. void FLAC__window_kaiser_bessel(FLAC__real *window, const FLAC__int32 L);
  98647. void FLAC__window_nuttall(FLAC__real *window, const FLAC__int32 L);
  98648. void FLAC__window_rectangle(FLAC__real *window, const FLAC__int32 L);
  98649. void FLAC__window_triangle(FLAC__real *window, const FLAC__int32 L);
  98650. void FLAC__window_tukey(FLAC__real *window, const FLAC__int32 L, const FLAC__real p);
  98651. void FLAC__window_welch(FLAC__real *window, const FLAC__int32 L);
  98652. #endif /* !defined FLAC__INTEGER_ONLY_LIBRARY */
  98653. #endif
  98654. /*** End of inlined file: window.h ***/
  98655. #ifndef FLaC__INLINE
  98656. #define FLaC__INLINE
  98657. #endif
  98658. #ifdef min
  98659. #undef min
  98660. #endif
  98661. #define min(x,y) ((x)<(y)?(x):(y))
  98662. #ifdef max
  98663. #undef max
  98664. #endif
  98665. #define max(x,y) ((x)>(y)?(x):(y))
  98666. /* Exact Rice codeword length calculation is off by default. The simple
  98667. * (and fast) estimation (of how many bits a residual value will be
  98668. * encoded with) in this encoder is very good, almost always yielding
  98669. * compression within 0.1% of exact calculation.
  98670. */
  98671. #undef EXACT_RICE_BITS_CALCULATION
  98672. /* Rice parameter searching is off by default. The simple (and fast)
  98673. * parameter estimation in this encoder is very good, almost always
  98674. * yielding compression within 0.1% of the optimal parameters.
  98675. */
  98676. #undef ENABLE_RICE_PARAMETER_SEARCH
  98677. typedef struct {
  98678. FLAC__int32 *data[FLAC__MAX_CHANNELS];
  98679. unsigned size; /* of each data[] in samples */
  98680. unsigned tail;
  98681. } verify_input_fifo;
  98682. typedef struct {
  98683. const FLAC__byte *data;
  98684. unsigned capacity;
  98685. unsigned bytes;
  98686. } verify_output;
  98687. typedef enum {
  98688. ENCODER_IN_MAGIC = 0,
  98689. ENCODER_IN_METADATA = 1,
  98690. ENCODER_IN_AUDIO = 2
  98691. } EncoderStateHint;
  98692. static struct CompressionLevels {
  98693. FLAC__bool do_mid_side_stereo;
  98694. FLAC__bool loose_mid_side_stereo;
  98695. unsigned max_lpc_order;
  98696. unsigned qlp_coeff_precision;
  98697. FLAC__bool do_qlp_coeff_prec_search;
  98698. FLAC__bool do_escape_coding;
  98699. FLAC__bool do_exhaustive_model_search;
  98700. unsigned min_residual_partition_order;
  98701. unsigned max_residual_partition_order;
  98702. unsigned rice_parameter_search_dist;
  98703. } compression_levels_[] = {
  98704. { false, false, 0, 0, false, false, false, 0, 3, 0 },
  98705. { true , true , 0, 0, false, false, false, 0, 3, 0 },
  98706. { true , false, 0, 0, false, false, false, 0, 3, 0 },
  98707. { false, false, 6, 0, false, false, false, 0, 4, 0 },
  98708. { true , true , 8, 0, false, false, false, 0, 4, 0 },
  98709. { true , false, 8, 0, false, false, false, 0, 5, 0 },
  98710. { true , false, 8, 0, false, false, false, 0, 6, 0 },
  98711. { true , false, 8, 0, false, false, true , 0, 6, 0 },
  98712. { true , false, 12, 0, false, false, true , 0, 6, 0 }
  98713. };
  98714. /***********************************************************************
  98715. *
  98716. * Private class method prototypes
  98717. *
  98718. ***********************************************************************/
  98719. static void set_defaults_enc(FLAC__StreamEncoder *encoder);
  98720. static void free_(FLAC__StreamEncoder *encoder);
  98721. static FLAC__bool resize_buffers_(FLAC__StreamEncoder *encoder, unsigned new_blocksize);
  98722. static FLAC__bool write_bitbuffer_(FLAC__StreamEncoder *encoder, unsigned samples, FLAC__bool is_last_block);
  98723. static FLAC__StreamEncoderWriteStatus write_frame_(FLAC__StreamEncoder *encoder, const FLAC__byte buffer[], size_t bytes, unsigned samples, FLAC__bool is_last_block);
  98724. static void update_metadata_(const FLAC__StreamEncoder *encoder);
  98725. #if FLAC__HAS_OGG
  98726. static void update_ogg_metadata_(FLAC__StreamEncoder *encoder);
  98727. #endif
  98728. static FLAC__bool process_frame_(FLAC__StreamEncoder *encoder, FLAC__bool is_fractional_block, FLAC__bool is_last_block);
  98729. static FLAC__bool process_subframes_(FLAC__StreamEncoder *encoder, FLAC__bool is_fractional_block);
  98730. static FLAC__bool process_subframe_(
  98731. FLAC__StreamEncoder *encoder,
  98732. unsigned min_partition_order,
  98733. unsigned max_partition_order,
  98734. const FLAC__FrameHeader *frame_header,
  98735. unsigned subframe_bps,
  98736. const FLAC__int32 integer_signal[],
  98737. FLAC__Subframe *subframe[2],
  98738. FLAC__EntropyCodingMethod_PartitionedRiceContents *partitioned_rice_contents[2],
  98739. FLAC__int32 *residual[2],
  98740. unsigned *best_subframe,
  98741. unsigned *best_bits
  98742. );
  98743. static FLAC__bool add_subframe_(
  98744. FLAC__StreamEncoder *encoder,
  98745. unsigned blocksize,
  98746. unsigned subframe_bps,
  98747. const FLAC__Subframe *subframe,
  98748. FLAC__BitWriter *frame
  98749. );
  98750. static unsigned evaluate_constant_subframe_(
  98751. FLAC__StreamEncoder *encoder,
  98752. const FLAC__int32 signal,
  98753. unsigned blocksize,
  98754. unsigned subframe_bps,
  98755. FLAC__Subframe *subframe
  98756. );
  98757. static unsigned evaluate_fixed_subframe_(
  98758. FLAC__StreamEncoder *encoder,
  98759. const FLAC__int32 signal[],
  98760. FLAC__int32 residual[],
  98761. FLAC__uint64 abs_residual_partition_sums[],
  98762. unsigned raw_bits_per_partition[],
  98763. unsigned blocksize,
  98764. unsigned subframe_bps,
  98765. unsigned order,
  98766. unsigned rice_parameter,
  98767. unsigned rice_parameter_limit,
  98768. unsigned min_partition_order,
  98769. unsigned max_partition_order,
  98770. FLAC__bool do_escape_coding,
  98771. unsigned rice_parameter_search_dist,
  98772. FLAC__Subframe *subframe,
  98773. FLAC__EntropyCodingMethod_PartitionedRiceContents *partitioned_rice_contents
  98774. );
  98775. #ifndef FLAC__INTEGER_ONLY_LIBRARY
  98776. static unsigned evaluate_lpc_subframe_(
  98777. FLAC__StreamEncoder *encoder,
  98778. const FLAC__int32 signal[],
  98779. FLAC__int32 residual[],
  98780. FLAC__uint64 abs_residual_partition_sums[],
  98781. unsigned raw_bits_per_partition[],
  98782. const FLAC__real lp_coeff[],
  98783. unsigned blocksize,
  98784. unsigned subframe_bps,
  98785. unsigned order,
  98786. unsigned qlp_coeff_precision,
  98787. unsigned rice_parameter,
  98788. unsigned rice_parameter_limit,
  98789. unsigned min_partition_order,
  98790. unsigned max_partition_order,
  98791. FLAC__bool do_escape_coding,
  98792. unsigned rice_parameter_search_dist,
  98793. FLAC__Subframe *subframe,
  98794. FLAC__EntropyCodingMethod_PartitionedRiceContents *partitioned_rice_contents
  98795. );
  98796. #endif
  98797. static unsigned evaluate_verbatim_subframe_(
  98798. FLAC__StreamEncoder *encoder,
  98799. const FLAC__int32 signal[],
  98800. unsigned blocksize,
  98801. unsigned subframe_bps,
  98802. FLAC__Subframe *subframe
  98803. );
  98804. static unsigned find_best_partition_order_(
  98805. struct FLAC__StreamEncoderPrivate *private_,
  98806. const FLAC__int32 residual[],
  98807. FLAC__uint64 abs_residual_partition_sums[],
  98808. unsigned raw_bits_per_partition[],
  98809. unsigned residual_samples,
  98810. unsigned predictor_order,
  98811. unsigned rice_parameter,
  98812. unsigned rice_parameter_limit,
  98813. unsigned min_partition_order,
  98814. unsigned max_partition_order,
  98815. unsigned bps,
  98816. FLAC__bool do_escape_coding,
  98817. unsigned rice_parameter_search_dist,
  98818. FLAC__EntropyCodingMethod *best_ecm
  98819. );
  98820. static void precompute_partition_info_sums_(
  98821. const FLAC__int32 residual[],
  98822. FLAC__uint64 abs_residual_partition_sums[],
  98823. unsigned residual_samples,
  98824. unsigned predictor_order,
  98825. unsigned min_partition_order,
  98826. unsigned max_partition_order,
  98827. unsigned bps
  98828. );
  98829. static void precompute_partition_info_escapes_(
  98830. const FLAC__int32 residual[],
  98831. unsigned raw_bits_per_partition[],
  98832. unsigned residual_samples,
  98833. unsigned predictor_order,
  98834. unsigned min_partition_order,
  98835. unsigned max_partition_order
  98836. );
  98837. static FLAC__bool set_partitioned_rice_(
  98838. #ifdef EXACT_RICE_BITS_CALCULATION
  98839. const FLAC__int32 residual[],
  98840. #endif
  98841. const FLAC__uint64 abs_residual_partition_sums[],
  98842. const unsigned raw_bits_per_partition[],
  98843. const unsigned residual_samples,
  98844. const unsigned predictor_order,
  98845. const unsigned suggested_rice_parameter,
  98846. const unsigned rice_parameter_limit,
  98847. const unsigned rice_parameter_search_dist,
  98848. const unsigned partition_order,
  98849. const FLAC__bool search_for_escapes,
  98850. FLAC__EntropyCodingMethod_PartitionedRiceContents *partitioned_rice_contents,
  98851. unsigned *bits
  98852. );
  98853. static unsigned get_wasted_bits_(FLAC__int32 signal[], unsigned samples);
  98854. /* verify-related routines: */
  98855. static void append_to_verify_fifo_(
  98856. verify_input_fifo *fifo,
  98857. const FLAC__int32 * const input[],
  98858. unsigned input_offset,
  98859. unsigned channels,
  98860. unsigned wide_samples
  98861. );
  98862. static void append_to_verify_fifo_interleaved_(
  98863. verify_input_fifo *fifo,
  98864. const FLAC__int32 input[],
  98865. unsigned input_offset,
  98866. unsigned channels,
  98867. unsigned wide_samples
  98868. );
  98869. static FLAC__StreamDecoderReadStatus verify_read_callback_(const FLAC__StreamDecoder *decoder, FLAC__byte buffer[], size_t *bytes, void *client_data);
  98870. static FLAC__StreamDecoderWriteStatus verify_write_callback_(const FLAC__StreamDecoder *decoder, const FLAC__Frame *frame, const FLAC__int32 * const buffer[], void *client_data);
  98871. static void verify_metadata_callback_(const FLAC__StreamDecoder *decoder, const FLAC__StreamMetadata *metadata, void *client_data);
  98872. static void verify_error_callback_(const FLAC__StreamDecoder *decoder, FLAC__StreamDecoderErrorStatus status, void *client_data);
  98873. static FLAC__StreamEncoderReadStatus file_read_callback_enc(const FLAC__StreamEncoder *encoder, FLAC__byte buffer[], size_t *bytes, void *client_data);
  98874. static FLAC__StreamEncoderSeekStatus file_seek_callback_enc(const FLAC__StreamEncoder *encoder, FLAC__uint64 absolute_byte_offset, void *client_data);
  98875. static FLAC__StreamEncoderTellStatus file_tell_callback_enc(const FLAC__StreamEncoder *encoder, FLAC__uint64 *absolute_byte_offset, void *client_data);
  98876. 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);
  98877. static FILE *get_binary_stdout_(void);
  98878. /***********************************************************************
  98879. *
  98880. * Private class data
  98881. *
  98882. ***********************************************************************/
  98883. typedef struct FLAC__StreamEncoderPrivate {
  98884. unsigned input_capacity; /* current size (in samples) of the signal and residual buffers */
  98885. FLAC__int32 *integer_signal[FLAC__MAX_CHANNELS]; /* the integer version of the input signal */
  98886. FLAC__int32 *integer_signal_mid_side[2]; /* the integer version of the mid-side input signal (stereo only) */
  98887. #ifndef FLAC__INTEGER_ONLY_LIBRARY
  98888. FLAC__real *real_signal[FLAC__MAX_CHANNELS]; /* (@@@ currently unused) the floating-point version of the input signal */
  98889. FLAC__real *real_signal_mid_side[2]; /* (@@@ currently unused) the floating-point version of the mid-side input signal (stereo only) */
  98890. FLAC__real *window[FLAC__MAX_APODIZATION_FUNCTIONS]; /* the pre-computed floating-point window for each apodization function */
  98891. FLAC__real *windowed_signal; /* the integer_signal[] * current window[] */
  98892. #endif
  98893. unsigned subframe_bps[FLAC__MAX_CHANNELS]; /* the effective bits per sample of the input signal (stream bps - wasted bits) */
  98894. unsigned subframe_bps_mid_side[2]; /* the effective bits per sample of the mid-side input signal (stream bps - wasted bits + 0/1) */
  98895. FLAC__int32 *residual_workspace[FLAC__MAX_CHANNELS][2]; /* each channel has a candidate and best workspace where the subframe residual signals will be stored */
  98896. FLAC__int32 *residual_workspace_mid_side[2][2];
  98897. FLAC__Subframe subframe_workspace[FLAC__MAX_CHANNELS][2];
  98898. FLAC__Subframe subframe_workspace_mid_side[2][2];
  98899. FLAC__Subframe *subframe_workspace_ptr[FLAC__MAX_CHANNELS][2];
  98900. FLAC__Subframe *subframe_workspace_ptr_mid_side[2][2];
  98901. FLAC__EntropyCodingMethod_PartitionedRiceContents partitioned_rice_contents_workspace[FLAC__MAX_CHANNELS][2];
  98902. FLAC__EntropyCodingMethod_PartitionedRiceContents partitioned_rice_contents_workspace_mid_side[FLAC__MAX_CHANNELS][2];
  98903. FLAC__EntropyCodingMethod_PartitionedRiceContents *partitioned_rice_contents_workspace_ptr[FLAC__MAX_CHANNELS][2];
  98904. FLAC__EntropyCodingMethod_PartitionedRiceContents *partitioned_rice_contents_workspace_ptr_mid_side[FLAC__MAX_CHANNELS][2];
  98905. unsigned best_subframe[FLAC__MAX_CHANNELS]; /* index (0 or 1) into 2nd dimension of the above workspaces */
  98906. unsigned best_subframe_mid_side[2];
  98907. unsigned best_subframe_bits[FLAC__MAX_CHANNELS]; /* size in bits of the best subframe for each channel */
  98908. unsigned best_subframe_bits_mid_side[2];
  98909. FLAC__uint64 *abs_residual_partition_sums; /* workspace where the sum of abs(candidate residual) for each partition is stored */
  98910. unsigned *raw_bits_per_partition; /* workspace where the sum of silog2(candidate residual) for each partition is stored */
  98911. FLAC__BitWriter *frame; /* the current frame being worked on */
  98912. unsigned loose_mid_side_stereo_frames; /* rounded number of frames the encoder will use before trying both independent and mid/side frames again */
  98913. unsigned loose_mid_side_stereo_frame_count; /* number of frames using the current channel assignment */
  98914. FLAC__ChannelAssignment last_channel_assignment;
  98915. FLAC__StreamMetadata streaminfo; /* scratchpad for STREAMINFO as it is built */
  98916. FLAC__StreamMetadata_SeekTable *seek_table; /* pointer into encoder->protected_->metadata_ where the seek table is */
  98917. unsigned current_sample_number;
  98918. unsigned current_frame_number;
  98919. FLAC__MD5Context md5context;
  98920. FLAC__CPUInfo cpuinfo;
  98921. #ifndef FLAC__INTEGER_ONLY_LIBRARY
  98922. unsigned (*local_fixed_compute_best_predictor)(const FLAC__int32 data[], unsigned data_len, FLAC__float residual_bits_per_sample[FLAC__MAX_FIXED_ORDER+1]);
  98923. #else
  98924. unsigned (*local_fixed_compute_best_predictor)(const FLAC__int32 data[], unsigned data_len, FLAC__fixedpoint residual_bits_per_sample[FLAC__MAX_FIXED_ORDER+1]);
  98925. #endif
  98926. #ifndef FLAC__INTEGER_ONLY_LIBRARY
  98927. void (*local_lpc_compute_autocorrelation)(const FLAC__real data[], unsigned data_len, unsigned lag, FLAC__real autoc[]);
  98928. 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[]);
  98929. 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[]);
  98930. 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[]);
  98931. #endif
  98932. FLAC__bool use_wide_by_block; /* use slow 64-bit versions of some functions because of the block size */
  98933. FLAC__bool use_wide_by_partition; /* use slow 64-bit versions of some functions because of the min partition order and blocksize */
  98934. FLAC__bool use_wide_by_order; /* use slow 64-bit versions of some functions because of the lpc order */
  98935. FLAC__bool disable_constant_subframes;
  98936. FLAC__bool disable_fixed_subframes;
  98937. FLAC__bool disable_verbatim_subframes;
  98938. #if FLAC__HAS_OGG
  98939. FLAC__bool is_ogg;
  98940. #endif
  98941. FLAC__StreamEncoderReadCallback read_callback; /* currently only needed for Ogg FLAC */
  98942. FLAC__StreamEncoderSeekCallback seek_callback;
  98943. FLAC__StreamEncoderTellCallback tell_callback;
  98944. FLAC__StreamEncoderWriteCallback write_callback;
  98945. FLAC__StreamEncoderMetadataCallback metadata_callback;
  98946. FLAC__StreamEncoderProgressCallback progress_callback;
  98947. void *client_data;
  98948. unsigned first_seekpoint_to_check;
  98949. FILE *file; /* only used when encoding to a file */
  98950. FLAC__uint64 bytes_written;
  98951. FLAC__uint64 samples_written;
  98952. unsigned frames_written;
  98953. unsigned total_frames_estimate;
  98954. /* unaligned (original) pointers to allocated data */
  98955. FLAC__int32 *integer_signal_unaligned[FLAC__MAX_CHANNELS];
  98956. FLAC__int32 *integer_signal_mid_side_unaligned[2];
  98957. #ifndef FLAC__INTEGER_ONLY_LIBRARY
  98958. FLAC__real *real_signal_unaligned[FLAC__MAX_CHANNELS]; /* (@@@ currently unused) */
  98959. FLAC__real *real_signal_mid_side_unaligned[2]; /* (@@@ currently unused) */
  98960. FLAC__real *window_unaligned[FLAC__MAX_APODIZATION_FUNCTIONS];
  98961. FLAC__real *windowed_signal_unaligned;
  98962. #endif
  98963. FLAC__int32 *residual_workspace_unaligned[FLAC__MAX_CHANNELS][2];
  98964. FLAC__int32 *residual_workspace_mid_side_unaligned[2][2];
  98965. FLAC__uint64 *abs_residual_partition_sums_unaligned;
  98966. unsigned *raw_bits_per_partition_unaligned;
  98967. /*
  98968. * These fields have been moved here from private function local
  98969. * declarations merely to save stack space during encoding.
  98970. */
  98971. #ifndef FLAC__INTEGER_ONLY_LIBRARY
  98972. FLAC__real lp_coeff[FLAC__MAX_LPC_ORDER][FLAC__MAX_LPC_ORDER]; /* from process_subframe_() */
  98973. #endif
  98974. FLAC__EntropyCodingMethod_PartitionedRiceContents partitioned_rice_contents_extra[2]; /* from find_best_partition_order_() */
  98975. /*
  98976. * The data for the verify section
  98977. */
  98978. struct {
  98979. FLAC__StreamDecoder *decoder;
  98980. EncoderStateHint state_hint;
  98981. FLAC__bool needs_magic_hack;
  98982. verify_input_fifo input_fifo;
  98983. verify_output output;
  98984. struct {
  98985. FLAC__uint64 absolute_sample;
  98986. unsigned frame_number;
  98987. unsigned channel;
  98988. unsigned sample;
  98989. FLAC__int32 expected;
  98990. FLAC__int32 got;
  98991. } error_stats;
  98992. } verify;
  98993. FLAC__bool is_being_deleted; /* if true, call to ..._finish() from ..._delete() will not call the callbacks */
  98994. } FLAC__StreamEncoderPrivate;
  98995. /***********************************************************************
  98996. *
  98997. * Public static class data
  98998. *
  98999. ***********************************************************************/
  99000. FLAC_API const char * const FLAC__StreamEncoderStateString[] = {
  99001. "FLAC__STREAM_ENCODER_OK",
  99002. "FLAC__STREAM_ENCODER_UNINITIALIZED",
  99003. "FLAC__STREAM_ENCODER_OGG_ERROR",
  99004. "FLAC__STREAM_ENCODER_VERIFY_DECODER_ERROR",
  99005. "FLAC__STREAM_ENCODER_VERIFY_MISMATCH_IN_AUDIO_DATA",
  99006. "FLAC__STREAM_ENCODER_CLIENT_ERROR",
  99007. "FLAC__STREAM_ENCODER_IO_ERROR",
  99008. "FLAC__STREAM_ENCODER_FRAMING_ERROR",
  99009. "FLAC__STREAM_ENCODER_MEMORY_ALLOCATION_ERROR"
  99010. };
  99011. FLAC_API const char * const FLAC__StreamEncoderInitStatusString[] = {
  99012. "FLAC__STREAM_ENCODER_INIT_STATUS_OK",
  99013. "FLAC__STREAM_ENCODER_INIT_STATUS_ENCODER_ERROR",
  99014. "FLAC__STREAM_ENCODER_INIT_STATUS_UNSUPPORTED_CONTAINER",
  99015. "FLAC__STREAM_ENCODER_INIT_STATUS_INVALID_CALLBACKS",
  99016. "FLAC__STREAM_ENCODER_INIT_STATUS_INVALID_NUMBER_OF_CHANNELS",
  99017. "FLAC__STREAM_ENCODER_INIT_STATUS_INVALID_BITS_PER_SAMPLE",
  99018. "FLAC__STREAM_ENCODER_INIT_STATUS_INVALID_SAMPLE_RATE",
  99019. "FLAC__STREAM_ENCODER_INIT_STATUS_INVALID_BLOCK_SIZE",
  99020. "FLAC__STREAM_ENCODER_INIT_STATUS_INVALID_MAX_LPC_ORDER",
  99021. "FLAC__STREAM_ENCODER_INIT_STATUS_INVALID_QLP_COEFF_PRECISION",
  99022. "FLAC__STREAM_ENCODER_INIT_STATUS_BLOCK_SIZE_TOO_SMALL_FOR_LPC_ORDER",
  99023. "FLAC__STREAM_ENCODER_INIT_STATUS_NOT_STREAMABLE",
  99024. "FLAC__STREAM_ENCODER_INIT_STATUS_INVALID_METADATA",
  99025. "FLAC__STREAM_ENCODER_INIT_STATUS_ALREADY_INITIALIZED"
  99026. };
  99027. FLAC_API const char * const FLAC__treamEncoderReadStatusString[] = {
  99028. "FLAC__STREAM_ENCODER_READ_STATUS_CONTINUE",
  99029. "FLAC__STREAM_ENCODER_READ_STATUS_END_OF_STREAM",
  99030. "FLAC__STREAM_ENCODER_READ_STATUS_ABORT",
  99031. "FLAC__STREAM_ENCODER_READ_STATUS_UNSUPPORTED"
  99032. };
  99033. FLAC_API const char * const FLAC__StreamEncoderWriteStatusString[] = {
  99034. "FLAC__STREAM_ENCODER_WRITE_STATUS_OK",
  99035. "FLAC__STREAM_ENCODER_WRITE_STATUS_FATAL_ERROR"
  99036. };
  99037. FLAC_API const char * const FLAC__StreamEncoderSeekStatusString[] = {
  99038. "FLAC__STREAM_ENCODER_SEEK_STATUS_OK",
  99039. "FLAC__STREAM_ENCODER_SEEK_STATUS_ERROR",
  99040. "FLAC__STREAM_ENCODER_SEEK_STATUS_UNSUPPORTED"
  99041. };
  99042. FLAC_API const char * const FLAC__StreamEncoderTellStatusString[] = {
  99043. "FLAC__STREAM_ENCODER_TELL_STATUS_OK",
  99044. "FLAC__STREAM_ENCODER_TELL_STATUS_ERROR",
  99045. "FLAC__STREAM_ENCODER_TELL_STATUS_UNSUPPORTED"
  99046. };
  99047. /* Number of samples that will be overread to watch for end of stream. By
  99048. * 'overread', we mean that the FLAC__stream_encoder_process*() calls will
  99049. * always try to read blocksize+1 samples before encoding a block, so that
  99050. * even if the stream has a total sample count that is an integral multiple
  99051. * of the blocksize, we will still notice when we are encoding the last
  99052. * block. This is needed, for example, to correctly set the end-of-stream
  99053. * marker in Ogg FLAC.
  99054. *
  99055. * WATCHOUT: some parts of the code assert that OVERREAD_ == 1 and there's
  99056. * not really any reason to change it.
  99057. */
  99058. static const unsigned OVERREAD_ = 1;
  99059. /***********************************************************************
  99060. *
  99061. * Class constructor/destructor
  99062. *
  99063. */
  99064. FLAC_API FLAC__StreamEncoder *FLAC__stream_encoder_new(void)
  99065. {
  99066. FLAC__StreamEncoder *encoder;
  99067. unsigned i;
  99068. FLAC__ASSERT(sizeof(int) >= 4); /* we want to die right away if this is not true */
  99069. encoder = (FLAC__StreamEncoder*)calloc(1, sizeof(FLAC__StreamEncoder));
  99070. if(encoder == 0) {
  99071. return 0;
  99072. }
  99073. encoder->protected_ = (FLAC__StreamEncoderProtected*)calloc(1, sizeof(FLAC__StreamEncoderProtected));
  99074. if(encoder->protected_ == 0) {
  99075. free(encoder);
  99076. return 0;
  99077. }
  99078. encoder->private_ = (FLAC__StreamEncoderPrivate*)calloc(1, sizeof(FLAC__StreamEncoderPrivate));
  99079. if(encoder->private_ == 0) {
  99080. free(encoder->protected_);
  99081. free(encoder);
  99082. return 0;
  99083. }
  99084. encoder->private_->frame = FLAC__bitwriter_new();
  99085. if(encoder->private_->frame == 0) {
  99086. free(encoder->private_);
  99087. free(encoder->protected_);
  99088. free(encoder);
  99089. return 0;
  99090. }
  99091. encoder->private_->file = 0;
  99092. set_defaults_enc(encoder);
  99093. encoder->private_->is_being_deleted = false;
  99094. for(i = 0; i < FLAC__MAX_CHANNELS; i++) {
  99095. encoder->private_->subframe_workspace_ptr[i][0] = &encoder->private_->subframe_workspace[i][0];
  99096. encoder->private_->subframe_workspace_ptr[i][1] = &encoder->private_->subframe_workspace[i][1];
  99097. }
  99098. for(i = 0; i < 2; i++) {
  99099. encoder->private_->subframe_workspace_ptr_mid_side[i][0] = &encoder->private_->subframe_workspace_mid_side[i][0];
  99100. encoder->private_->subframe_workspace_ptr_mid_side[i][1] = &encoder->private_->subframe_workspace_mid_side[i][1];
  99101. }
  99102. for(i = 0; i < FLAC__MAX_CHANNELS; i++) {
  99103. encoder->private_->partitioned_rice_contents_workspace_ptr[i][0] = &encoder->private_->partitioned_rice_contents_workspace[i][0];
  99104. encoder->private_->partitioned_rice_contents_workspace_ptr[i][1] = &encoder->private_->partitioned_rice_contents_workspace[i][1];
  99105. }
  99106. for(i = 0; i < 2; i++) {
  99107. encoder->private_->partitioned_rice_contents_workspace_ptr_mid_side[i][0] = &encoder->private_->partitioned_rice_contents_workspace_mid_side[i][0];
  99108. encoder->private_->partitioned_rice_contents_workspace_ptr_mid_side[i][1] = &encoder->private_->partitioned_rice_contents_workspace_mid_side[i][1];
  99109. }
  99110. for(i = 0; i < FLAC__MAX_CHANNELS; i++) {
  99111. FLAC__format_entropy_coding_method_partitioned_rice_contents_init(&encoder->private_->partitioned_rice_contents_workspace[i][0]);
  99112. FLAC__format_entropy_coding_method_partitioned_rice_contents_init(&encoder->private_->partitioned_rice_contents_workspace[i][1]);
  99113. }
  99114. for(i = 0; i < 2; i++) {
  99115. FLAC__format_entropy_coding_method_partitioned_rice_contents_init(&encoder->private_->partitioned_rice_contents_workspace_mid_side[i][0]);
  99116. FLAC__format_entropy_coding_method_partitioned_rice_contents_init(&encoder->private_->partitioned_rice_contents_workspace_mid_side[i][1]);
  99117. }
  99118. for(i = 0; i < 2; i++)
  99119. FLAC__format_entropy_coding_method_partitioned_rice_contents_init(&encoder->private_->partitioned_rice_contents_extra[i]);
  99120. encoder->protected_->state = FLAC__STREAM_ENCODER_UNINITIALIZED;
  99121. return encoder;
  99122. }
  99123. FLAC_API void FLAC__stream_encoder_delete(FLAC__StreamEncoder *encoder)
  99124. {
  99125. unsigned i;
  99126. FLAC__ASSERT(0 != encoder);
  99127. FLAC__ASSERT(0 != encoder->protected_);
  99128. FLAC__ASSERT(0 != encoder->private_);
  99129. FLAC__ASSERT(0 != encoder->private_->frame);
  99130. encoder->private_->is_being_deleted = true;
  99131. (void)FLAC__stream_encoder_finish(encoder);
  99132. if(0 != encoder->private_->verify.decoder)
  99133. FLAC__stream_decoder_delete(encoder->private_->verify.decoder);
  99134. for(i = 0; i < FLAC__MAX_CHANNELS; i++) {
  99135. FLAC__format_entropy_coding_method_partitioned_rice_contents_clear(&encoder->private_->partitioned_rice_contents_workspace[i][0]);
  99136. FLAC__format_entropy_coding_method_partitioned_rice_contents_clear(&encoder->private_->partitioned_rice_contents_workspace[i][1]);
  99137. }
  99138. for(i = 0; i < 2; i++) {
  99139. FLAC__format_entropy_coding_method_partitioned_rice_contents_clear(&encoder->private_->partitioned_rice_contents_workspace_mid_side[i][0]);
  99140. FLAC__format_entropy_coding_method_partitioned_rice_contents_clear(&encoder->private_->partitioned_rice_contents_workspace_mid_side[i][1]);
  99141. }
  99142. for(i = 0; i < 2; i++)
  99143. FLAC__format_entropy_coding_method_partitioned_rice_contents_clear(&encoder->private_->partitioned_rice_contents_extra[i]);
  99144. FLAC__bitwriter_delete(encoder->private_->frame);
  99145. free(encoder->private_);
  99146. free(encoder->protected_);
  99147. free(encoder);
  99148. }
  99149. /***********************************************************************
  99150. *
  99151. * Public class methods
  99152. *
  99153. ***********************************************************************/
  99154. static FLAC__StreamEncoderInitStatus init_stream_internal_enc(
  99155. FLAC__StreamEncoder *encoder,
  99156. FLAC__StreamEncoderReadCallback read_callback,
  99157. FLAC__StreamEncoderWriteCallback write_callback,
  99158. FLAC__StreamEncoderSeekCallback seek_callback,
  99159. FLAC__StreamEncoderTellCallback tell_callback,
  99160. FLAC__StreamEncoderMetadataCallback metadata_callback,
  99161. void *client_data,
  99162. FLAC__bool is_ogg
  99163. )
  99164. {
  99165. unsigned i;
  99166. FLAC__bool metadata_has_seektable, metadata_has_vorbis_comment, metadata_picture_has_type1, metadata_picture_has_type2;
  99167. FLAC__ASSERT(0 != encoder);
  99168. if(encoder->protected_->state != FLAC__STREAM_ENCODER_UNINITIALIZED)
  99169. return FLAC__STREAM_ENCODER_INIT_STATUS_ALREADY_INITIALIZED;
  99170. #if !FLAC__HAS_OGG
  99171. if(is_ogg)
  99172. return FLAC__STREAM_ENCODER_INIT_STATUS_UNSUPPORTED_CONTAINER;
  99173. #endif
  99174. if(0 == write_callback || (seek_callback && 0 == tell_callback))
  99175. return FLAC__STREAM_ENCODER_INIT_STATUS_INVALID_CALLBACKS;
  99176. if(encoder->protected_->channels == 0 || encoder->protected_->channels > FLAC__MAX_CHANNELS)
  99177. return FLAC__STREAM_ENCODER_INIT_STATUS_INVALID_NUMBER_OF_CHANNELS;
  99178. if(encoder->protected_->channels != 2) {
  99179. encoder->protected_->do_mid_side_stereo = false;
  99180. encoder->protected_->loose_mid_side_stereo = false;
  99181. }
  99182. else if(!encoder->protected_->do_mid_side_stereo)
  99183. encoder->protected_->loose_mid_side_stereo = false;
  99184. if(encoder->protected_->bits_per_sample >= 32)
  99185. encoder->protected_->do_mid_side_stereo = false; /* since we currenty do 32-bit math, the side channel would have 33 bps and overflow */
  99186. if(encoder->protected_->bits_per_sample < FLAC__MIN_BITS_PER_SAMPLE || encoder->protected_->bits_per_sample > FLAC__REFERENCE_CODEC_MAX_BITS_PER_SAMPLE)
  99187. return FLAC__STREAM_ENCODER_INIT_STATUS_INVALID_BITS_PER_SAMPLE;
  99188. if(!FLAC__format_sample_rate_is_valid(encoder->protected_->sample_rate))
  99189. return FLAC__STREAM_ENCODER_INIT_STATUS_INVALID_SAMPLE_RATE;
  99190. if(encoder->protected_->blocksize == 0) {
  99191. if(encoder->protected_->max_lpc_order == 0)
  99192. encoder->protected_->blocksize = 1152;
  99193. else
  99194. encoder->protected_->blocksize = 4096;
  99195. }
  99196. if(encoder->protected_->blocksize < FLAC__MIN_BLOCK_SIZE || encoder->protected_->blocksize > FLAC__MAX_BLOCK_SIZE)
  99197. return FLAC__STREAM_ENCODER_INIT_STATUS_INVALID_BLOCK_SIZE;
  99198. if(encoder->protected_->max_lpc_order > FLAC__MAX_LPC_ORDER)
  99199. return FLAC__STREAM_ENCODER_INIT_STATUS_INVALID_MAX_LPC_ORDER;
  99200. if(encoder->protected_->blocksize < encoder->protected_->max_lpc_order)
  99201. return FLAC__STREAM_ENCODER_INIT_STATUS_BLOCK_SIZE_TOO_SMALL_FOR_LPC_ORDER;
  99202. if(encoder->protected_->qlp_coeff_precision == 0) {
  99203. if(encoder->protected_->bits_per_sample < 16) {
  99204. /* @@@ need some data about how to set this here w.r.t. blocksize and sample rate */
  99205. /* @@@ until then we'll make a guess */
  99206. encoder->protected_->qlp_coeff_precision = max(FLAC__MIN_QLP_COEFF_PRECISION, 2 + encoder->protected_->bits_per_sample / 2);
  99207. }
  99208. else if(encoder->protected_->bits_per_sample == 16) {
  99209. if(encoder->protected_->blocksize <= 192)
  99210. encoder->protected_->qlp_coeff_precision = 7;
  99211. else if(encoder->protected_->blocksize <= 384)
  99212. encoder->protected_->qlp_coeff_precision = 8;
  99213. else if(encoder->protected_->blocksize <= 576)
  99214. encoder->protected_->qlp_coeff_precision = 9;
  99215. else if(encoder->protected_->blocksize <= 1152)
  99216. encoder->protected_->qlp_coeff_precision = 10;
  99217. else if(encoder->protected_->blocksize <= 2304)
  99218. encoder->protected_->qlp_coeff_precision = 11;
  99219. else if(encoder->protected_->blocksize <= 4608)
  99220. encoder->protected_->qlp_coeff_precision = 12;
  99221. else
  99222. encoder->protected_->qlp_coeff_precision = 13;
  99223. }
  99224. else {
  99225. if(encoder->protected_->blocksize <= 384)
  99226. encoder->protected_->qlp_coeff_precision = FLAC__MAX_QLP_COEFF_PRECISION-2;
  99227. else if(encoder->protected_->blocksize <= 1152)
  99228. encoder->protected_->qlp_coeff_precision = FLAC__MAX_QLP_COEFF_PRECISION-1;
  99229. else
  99230. encoder->protected_->qlp_coeff_precision = FLAC__MAX_QLP_COEFF_PRECISION;
  99231. }
  99232. FLAC__ASSERT(encoder->protected_->qlp_coeff_precision <= FLAC__MAX_QLP_COEFF_PRECISION);
  99233. }
  99234. else if(encoder->protected_->qlp_coeff_precision < FLAC__MIN_QLP_COEFF_PRECISION || encoder->protected_->qlp_coeff_precision > FLAC__MAX_QLP_COEFF_PRECISION)
  99235. return FLAC__STREAM_ENCODER_INIT_STATUS_INVALID_QLP_COEFF_PRECISION;
  99236. if(encoder->protected_->streamable_subset) {
  99237. if(
  99238. encoder->protected_->blocksize != 192 &&
  99239. encoder->protected_->blocksize != 576 &&
  99240. encoder->protected_->blocksize != 1152 &&
  99241. encoder->protected_->blocksize != 2304 &&
  99242. encoder->protected_->blocksize != 4608 &&
  99243. encoder->protected_->blocksize != 256 &&
  99244. encoder->protected_->blocksize != 512 &&
  99245. encoder->protected_->blocksize != 1024 &&
  99246. encoder->protected_->blocksize != 2048 &&
  99247. encoder->protected_->blocksize != 4096 &&
  99248. encoder->protected_->blocksize != 8192 &&
  99249. encoder->protected_->blocksize != 16384
  99250. )
  99251. return FLAC__STREAM_ENCODER_INIT_STATUS_NOT_STREAMABLE;
  99252. if(!FLAC__format_sample_rate_is_subset(encoder->protected_->sample_rate))
  99253. return FLAC__STREAM_ENCODER_INIT_STATUS_NOT_STREAMABLE;
  99254. if(
  99255. encoder->protected_->bits_per_sample != 8 &&
  99256. encoder->protected_->bits_per_sample != 12 &&
  99257. encoder->protected_->bits_per_sample != 16 &&
  99258. encoder->protected_->bits_per_sample != 20 &&
  99259. encoder->protected_->bits_per_sample != 24
  99260. )
  99261. return FLAC__STREAM_ENCODER_INIT_STATUS_NOT_STREAMABLE;
  99262. if(encoder->protected_->max_residual_partition_order > FLAC__SUBSET_MAX_RICE_PARTITION_ORDER)
  99263. return FLAC__STREAM_ENCODER_INIT_STATUS_NOT_STREAMABLE;
  99264. if(
  99265. encoder->protected_->sample_rate <= 48000 &&
  99266. (
  99267. encoder->protected_->blocksize > FLAC__SUBSET_MAX_BLOCK_SIZE_48000HZ ||
  99268. encoder->protected_->max_lpc_order > FLAC__SUBSET_MAX_LPC_ORDER_48000HZ
  99269. )
  99270. ) {
  99271. return FLAC__STREAM_ENCODER_INIT_STATUS_NOT_STREAMABLE;
  99272. }
  99273. }
  99274. if(encoder->protected_->max_residual_partition_order >= (1u << FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE_ORDER_LEN))
  99275. encoder->protected_->max_residual_partition_order = (1u << FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE_ORDER_LEN) - 1;
  99276. if(encoder->protected_->min_residual_partition_order >= encoder->protected_->max_residual_partition_order)
  99277. encoder->protected_->min_residual_partition_order = encoder->protected_->max_residual_partition_order;
  99278. #if FLAC__HAS_OGG
  99279. /* reorder metadata if necessary to ensure that any VORBIS_COMMENT is the first, according to the mapping spec */
  99280. if(is_ogg && 0 != encoder->protected_->metadata && encoder->protected_->num_metadata_blocks > 1) {
  99281. unsigned i;
  99282. for(i = 1; i < encoder->protected_->num_metadata_blocks; i++) {
  99283. if(0 != encoder->protected_->metadata[i] && encoder->protected_->metadata[i]->type == FLAC__METADATA_TYPE_VORBIS_COMMENT) {
  99284. FLAC__StreamMetadata *vc = encoder->protected_->metadata[i];
  99285. for( ; i > 0; i--)
  99286. encoder->protected_->metadata[i] = encoder->protected_->metadata[i-1];
  99287. encoder->protected_->metadata[0] = vc;
  99288. break;
  99289. }
  99290. }
  99291. }
  99292. #endif
  99293. /* keep track of any SEEKTABLE block */
  99294. if(0 != encoder->protected_->metadata && encoder->protected_->num_metadata_blocks > 0) {
  99295. unsigned i;
  99296. for(i = 0; i < encoder->protected_->num_metadata_blocks; i++) {
  99297. if(0 != encoder->protected_->metadata[i] && encoder->protected_->metadata[i]->type == FLAC__METADATA_TYPE_SEEKTABLE) {
  99298. encoder->private_->seek_table = &encoder->protected_->metadata[i]->data.seek_table;
  99299. break; /* take only the first one */
  99300. }
  99301. }
  99302. }
  99303. /* validate metadata */
  99304. if(0 == encoder->protected_->metadata && encoder->protected_->num_metadata_blocks > 0)
  99305. return FLAC__STREAM_ENCODER_INIT_STATUS_INVALID_METADATA;
  99306. metadata_has_seektable = false;
  99307. metadata_has_vorbis_comment = false;
  99308. metadata_picture_has_type1 = false;
  99309. metadata_picture_has_type2 = false;
  99310. for(i = 0; i < encoder->protected_->num_metadata_blocks; i++) {
  99311. const FLAC__StreamMetadata *m = encoder->protected_->metadata[i];
  99312. if(m->type == FLAC__METADATA_TYPE_STREAMINFO)
  99313. return FLAC__STREAM_ENCODER_INIT_STATUS_INVALID_METADATA;
  99314. else if(m->type == FLAC__METADATA_TYPE_SEEKTABLE) {
  99315. if(metadata_has_seektable) /* only one is allowed */
  99316. return FLAC__STREAM_ENCODER_INIT_STATUS_INVALID_METADATA;
  99317. metadata_has_seektable = true;
  99318. if(!FLAC__format_seektable_is_legal(&m->data.seek_table))
  99319. return FLAC__STREAM_ENCODER_INIT_STATUS_INVALID_METADATA;
  99320. }
  99321. else if(m->type == FLAC__METADATA_TYPE_VORBIS_COMMENT) {
  99322. if(metadata_has_vorbis_comment) /* only one is allowed */
  99323. return FLAC__STREAM_ENCODER_INIT_STATUS_INVALID_METADATA;
  99324. metadata_has_vorbis_comment = true;
  99325. }
  99326. else if(m->type == FLAC__METADATA_TYPE_CUESHEET) {
  99327. if(!FLAC__format_cuesheet_is_legal(&m->data.cue_sheet, m->data.cue_sheet.is_cd, /*violation=*/0))
  99328. return FLAC__STREAM_ENCODER_INIT_STATUS_INVALID_METADATA;
  99329. }
  99330. else if(m->type == FLAC__METADATA_TYPE_PICTURE) {
  99331. if(!FLAC__format_picture_is_legal(&m->data.picture, /*violation=*/0))
  99332. return FLAC__STREAM_ENCODER_INIT_STATUS_INVALID_METADATA;
  99333. if(m->data.picture.type == FLAC__STREAM_METADATA_PICTURE_TYPE_FILE_ICON_STANDARD) {
  99334. if(metadata_picture_has_type1) /* there should only be 1 per stream */
  99335. return FLAC__STREAM_ENCODER_INIT_STATUS_INVALID_METADATA;
  99336. metadata_picture_has_type1 = true;
  99337. /* standard icon must be 32x32 pixel PNG */
  99338. if(
  99339. m->data.picture.type == FLAC__STREAM_METADATA_PICTURE_TYPE_FILE_ICON_STANDARD &&
  99340. (
  99341. (strcmp(m->data.picture.mime_type, "image/png") && strcmp(m->data.picture.mime_type, "-->")) ||
  99342. m->data.picture.width != 32 ||
  99343. m->data.picture.height != 32
  99344. )
  99345. )
  99346. return FLAC__STREAM_ENCODER_INIT_STATUS_INVALID_METADATA;
  99347. }
  99348. else if(m->data.picture.type == FLAC__STREAM_METADATA_PICTURE_TYPE_FILE_ICON) {
  99349. if(metadata_picture_has_type2) /* there should only be 1 per stream */
  99350. return FLAC__STREAM_ENCODER_INIT_STATUS_INVALID_METADATA;
  99351. metadata_picture_has_type2 = true;
  99352. }
  99353. }
  99354. }
  99355. encoder->private_->input_capacity = 0;
  99356. for(i = 0; i < encoder->protected_->channels; i++) {
  99357. encoder->private_->integer_signal_unaligned[i] = encoder->private_->integer_signal[i] = 0;
  99358. #ifndef FLAC__INTEGER_ONLY_LIBRARY
  99359. encoder->private_->real_signal_unaligned[i] = encoder->private_->real_signal[i] = 0;
  99360. #endif
  99361. }
  99362. for(i = 0; i < 2; i++) {
  99363. encoder->private_->integer_signal_mid_side_unaligned[i] = encoder->private_->integer_signal_mid_side[i] = 0;
  99364. #ifndef FLAC__INTEGER_ONLY_LIBRARY
  99365. encoder->private_->real_signal_mid_side_unaligned[i] = encoder->private_->real_signal_mid_side[i] = 0;
  99366. #endif
  99367. }
  99368. #ifndef FLAC__INTEGER_ONLY_LIBRARY
  99369. for(i = 0; i < encoder->protected_->num_apodizations; i++)
  99370. encoder->private_->window_unaligned[i] = encoder->private_->window[i] = 0;
  99371. encoder->private_->windowed_signal_unaligned = encoder->private_->windowed_signal = 0;
  99372. #endif
  99373. for(i = 0; i < encoder->protected_->channels; i++) {
  99374. encoder->private_->residual_workspace_unaligned[i][0] = encoder->private_->residual_workspace[i][0] = 0;
  99375. encoder->private_->residual_workspace_unaligned[i][1] = encoder->private_->residual_workspace[i][1] = 0;
  99376. encoder->private_->best_subframe[i] = 0;
  99377. }
  99378. for(i = 0; i < 2; i++) {
  99379. encoder->private_->residual_workspace_mid_side_unaligned[i][0] = encoder->private_->residual_workspace_mid_side[i][0] = 0;
  99380. encoder->private_->residual_workspace_mid_side_unaligned[i][1] = encoder->private_->residual_workspace_mid_side[i][1] = 0;
  99381. encoder->private_->best_subframe_mid_side[i] = 0;
  99382. }
  99383. encoder->private_->abs_residual_partition_sums_unaligned = encoder->private_->abs_residual_partition_sums = 0;
  99384. encoder->private_->raw_bits_per_partition_unaligned = encoder->private_->raw_bits_per_partition = 0;
  99385. #ifndef FLAC__INTEGER_ONLY_LIBRARY
  99386. encoder->private_->loose_mid_side_stereo_frames = (unsigned)((FLAC__double)encoder->protected_->sample_rate * 0.4 / (FLAC__double)encoder->protected_->blocksize + 0.5);
  99387. #else
  99388. /* 26214 is the approximate fixed-point equivalent to 0.4 (0.4 * 2^16) */
  99389. /* sample rate can be up to 655350 Hz, and thus use 20 bits, so we do the multiply&divide by hand */
  99390. FLAC__ASSERT(FLAC__MAX_SAMPLE_RATE <= 655350);
  99391. FLAC__ASSERT(FLAC__MAX_BLOCK_SIZE <= 65535);
  99392. FLAC__ASSERT(encoder->protected_->sample_rate <= 655350);
  99393. FLAC__ASSERT(encoder->protected_->blocksize <= 65535);
  99394. 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);
  99395. #endif
  99396. if(encoder->private_->loose_mid_side_stereo_frames == 0)
  99397. encoder->private_->loose_mid_side_stereo_frames = 1;
  99398. encoder->private_->loose_mid_side_stereo_frame_count = 0;
  99399. encoder->private_->current_sample_number = 0;
  99400. encoder->private_->current_frame_number = 0;
  99401. encoder->private_->use_wide_by_block = (encoder->protected_->bits_per_sample + FLAC__bitmath_ilog2(encoder->protected_->blocksize)+1 > 30);
  99402. 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? */
  99403. encoder->private_->use_wide_by_partition = (false); /*@@@ need to set this */
  99404. /*
  99405. * get the CPU info and set the function pointers
  99406. */
  99407. FLAC__cpu_info(&encoder->private_->cpuinfo);
  99408. /* first default to the non-asm routines */
  99409. #ifndef FLAC__INTEGER_ONLY_LIBRARY
  99410. encoder->private_->local_lpc_compute_autocorrelation = FLAC__lpc_compute_autocorrelation;
  99411. #endif
  99412. encoder->private_->local_fixed_compute_best_predictor = FLAC__fixed_compute_best_predictor;
  99413. #ifndef FLAC__INTEGER_ONLY_LIBRARY
  99414. encoder->private_->local_lpc_compute_residual_from_qlp_coefficients = FLAC__lpc_compute_residual_from_qlp_coefficients;
  99415. encoder->private_->local_lpc_compute_residual_from_qlp_coefficients_64bit = FLAC__lpc_compute_residual_from_qlp_coefficients_wide;
  99416. encoder->private_->local_lpc_compute_residual_from_qlp_coefficients_16bit = FLAC__lpc_compute_residual_from_qlp_coefficients;
  99417. #endif
  99418. /* now override with asm where appropriate */
  99419. #ifndef FLAC__INTEGER_ONLY_LIBRARY
  99420. # ifndef FLAC__NO_ASM
  99421. if(encoder->private_->cpuinfo.use_asm) {
  99422. # ifdef FLAC__CPU_IA32
  99423. FLAC__ASSERT(encoder->private_->cpuinfo.type == FLAC__CPUINFO_TYPE_IA32);
  99424. # ifdef FLAC__HAS_NASM
  99425. if(encoder->private_->cpuinfo.data.ia32.sse) {
  99426. if(encoder->protected_->max_lpc_order < 4)
  99427. encoder->private_->local_lpc_compute_autocorrelation = FLAC__lpc_compute_autocorrelation_asm_ia32_sse_lag_4;
  99428. else if(encoder->protected_->max_lpc_order < 8)
  99429. encoder->private_->local_lpc_compute_autocorrelation = FLAC__lpc_compute_autocorrelation_asm_ia32_sse_lag_8;
  99430. else if(encoder->protected_->max_lpc_order < 12)
  99431. encoder->private_->local_lpc_compute_autocorrelation = FLAC__lpc_compute_autocorrelation_asm_ia32_sse_lag_12;
  99432. else
  99433. encoder->private_->local_lpc_compute_autocorrelation = FLAC__lpc_compute_autocorrelation_asm_ia32;
  99434. }
  99435. else if(encoder->private_->cpuinfo.data.ia32._3dnow)
  99436. encoder->private_->local_lpc_compute_autocorrelation = FLAC__lpc_compute_autocorrelation_asm_ia32_3dnow;
  99437. else
  99438. encoder->private_->local_lpc_compute_autocorrelation = FLAC__lpc_compute_autocorrelation_asm_ia32;
  99439. if(encoder->private_->cpuinfo.data.ia32.mmx) {
  99440. encoder->private_->local_lpc_compute_residual_from_qlp_coefficients = FLAC__lpc_compute_residual_from_qlp_coefficients_asm_ia32;
  99441. encoder->private_->local_lpc_compute_residual_from_qlp_coefficients_16bit = FLAC__lpc_compute_residual_from_qlp_coefficients_asm_ia32_mmx;
  99442. }
  99443. else {
  99444. encoder->private_->local_lpc_compute_residual_from_qlp_coefficients = FLAC__lpc_compute_residual_from_qlp_coefficients_asm_ia32;
  99445. encoder->private_->local_lpc_compute_residual_from_qlp_coefficients_16bit = FLAC__lpc_compute_residual_from_qlp_coefficients_asm_ia32;
  99446. }
  99447. if(encoder->private_->cpuinfo.data.ia32.mmx && encoder->private_->cpuinfo.data.ia32.cmov)
  99448. encoder->private_->local_fixed_compute_best_predictor = FLAC__fixed_compute_best_predictor_asm_ia32_mmx_cmov;
  99449. # endif /* FLAC__HAS_NASM */
  99450. # endif /* FLAC__CPU_IA32 */
  99451. }
  99452. # endif /* !FLAC__NO_ASM */
  99453. #endif /* !FLAC__INTEGER_ONLY_LIBRARY */
  99454. /* finally override based on wide-ness if necessary */
  99455. if(encoder->private_->use_wide_by_block) {
  99456. encoder->private_->local_fixed_compute_best_predictor = FLAC__fixed_compute_best_predictor_wide;
  99457. }
  99458. /* set state to OK; from here on, errors are fatal and we'll override the state then */
  99459. encoder->protected_->state = FLAC__STREAM_ENCODER_OK;
  99460. #if FLAC__HAS_OGG
  99461. encoder->private_->is_ogg = is_ogg;
  99462. if(is_ogg && !FLAC__ogg_encoder_aspect_init(&encoder->protected_->ogg_encoder_aspect)) {
  99463. encoder->protected_->state = FLAC__STREAM_ENCODER_OGG_ERROR;
  99464. return FLAC__STREAM_ENCODER_INIT_STATUS_ENCODER_ERROR;
  99465. }
  99466. #endif
  99467. encoder->private_->read_callback = read_callback;
  99468. encoder->private_->write_callback = write_callback;
  99469. encoder->private_->seek_callback = seek_callback;
  99470. encoder->private_->tell_callback = tell_callback;
  99471. encoder->private_->metadata_callback = metadata_callback;
  99472. encoder->private_->client_data = client_data;
  99473. if(!resize_buffers_(encoder, encoder->protected_->blocksize)) {
  99474. /* the above function sets the state for us in case of an error */
  99475. return FLAC__STREAM_ENCODER_INIT_STATUS_ENCODER_ERROR;
  99476. }
  99477. if(!FLAC__bitwriter_init(encoder->private_->frame)) {
  99478. encoder->protected_->state = FLAC__STREAM_ENCODER_MEMORY_ALLOCATION_ERROR;
  99479. return FLAC__STREAM_ENCODER_INIT_STATUS_ENCODER_ERROR;
  99480. }
  99481. /*
  99482. * Set up the verify stuff if necessary
  99483. */
  99484. if(encoder->protected_->verify) {
  99485. /*
  99486. * First, set up the fifo which will hold the
  99487. * original signal to compare against
  99488. */
  99489. encoder->private_->verify.input_fifo.size = encoder->protected_->blocksize+OVERREAD_;
  99490. for(i = 0; i < encoder->protected_->channels; i++) {
  99491. 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))) {
  99492. encoder->protected_->state = FLAC__STREAM_ENCODER_MEMORY_ALLOCATION_ERROR;
  99493. return FLAC__STREAM_ENCODER_INIT_STATUS_ENCODER_ERROR;
  99494. }
  99495. }
  99496. encoder->private_->verify.input_fifo.tail = 0;
  99497. /*
  99498. * Now set up a stream decoder for verification
  99499. */
  99500. encoder->private_->verify.decoder = FLAC__stream_decoder_new();
  99501. if(0 == encoder->private_->verify.decoder) {
  99502. encoder->protected_->state = FLAC__STREAM_ENCODER_VERIFY_DECODER_ERROR;
  99503. return FLAC__STREAM_ENCODER_INIT_STATUS_ENCODER_ERROR;
  99504. }
  99505. 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) {
  99506. encoder->protected_->state = FLAC__STREAM_ENCODER_VERIFY_DECODER_ERROR;
  99507. return FLAC__STREAM_ENCODER_INIT_STATUS_ENCODER_ERROR;
  99508. }
  99509. }
  99510. encoder->private_->verify.error_stats.absolute_sample = 0;
  99511. encoder->private_->verify.error_stats.frame_number = 0;
  99512. encoder->private_->verify.error_stats.channel = 0;
  99513. encoder->private_->verify.error_stats.sample = 0;
  99514. encoder->private_->verify.error_stats.expected = 0;
  99515. encoder->private_->verify.error_stats.got = 0;
  99516. /*
  99517. * These must be done before we write any metadata, because that
  99518. * calls the write_callback, which uses these values.
  99519. */
  99520. encoder->private_->first_seekpoint_to_check = 0;
  99521. encoder->private_->samples_written = 0;
  99522. encoder->protected_->streaminfo_offset = 0;
  99523. encoder->protected_->seektable_offset = 0;
  99524. encoder->protected_->audio_offset = 0;
  99525. /*
  99526. * write the stream header
  99527. */
  99528. if(encoder->protected_->verify)
  99529. encoder->private_->verify.state_hint = ENCODER_IN_MAGIC;
  99530. if(!FLAC__bitwriter_write_raw_uint32(encoder->private_->frame, FLAC__STREAM_SYNC, FLAC__STREAM_SYNC_LEN)) {
  99531. encoder->protected_->state = FLAC__STREAM_ENCODER_FRAMING_ERROR;
  99532. return FLAC__STREAM_ENCODER_INIT_STATUS_ENCODER_ERROR;
  99533. }
  99534. if(!write_bitbuffer_(encoder, 0, /*is_last_block=*/false)) {
  99535. /* the above function sets the state for us in case of an error */
  99536. return FLAC__STREAM_ENCODER_INIT_STATUS_ENCODER_ERROR;
  99537. }
  99538. /*
  99539. * write the STREAMINFO metadata block
  99540. */
  99541. if(encoder->protected_->verify)
  99542. encoder->private_->verify.state_hint = ENCODER_IN_METADATA;
  99543. encoder->private_->streaminfo.type = FLAC__METADATA_TYPE_STREAMINFO;
  99544. encoder->private_->streaminfo.is_last = false; /* we will have at a minimum a VORBIS_COMMENT afterwards */
  99545. encoder->private_->streaminfo.length = FLAC__STREAM_METADATA_STREAMINFO_LENGTH;
  99546. encoder->private_->streaminfo.data.stream_info.min_blocksize = encoder->protected_->blocksize; /* this encoder uses the same blocksize for the whole stream */
  99547. encoder->private_->streaminfo.data.stream_info.max_blocksize = encoder->protected_->blocksize;
  99548. encoder->private_->streaminfo.data.stream_info.min_framesize = 0; /* we don't know this yet; have to fill it in later */
  99549. encoder->private_->streaminfo.data.stream_info.max_framesize = 0; /* we don't know this yet; have to fill it in later */
  99550. encoder->private_->streaminfo.data.stream_info.sample_rate = encoder->protected_->sample_rate;
  99551. encoder->private_->streaminfo.data.stream_info.channels = encoder->protected_->channels;
  99552. encoder->private_->streaminfo.data.stream_info.bits_per_sample = encoder->protected_->bits_per_sample;
  99553. encoder->private_->streaminfo.data.stream_info.total_samples = encoder->protected_->total_samples_estimate; /* we will replace this later with the real total */
  99554. memset(encoder->private_->streaminfo.data.stream_info.md5sum, 0, 16); /* we don't know this yet; have to fill it in later */
  99555. if(encoder->protected_->do_md5)
  99556. FLAC__MD5Init(&encoder->private_->md5context);
  99557. if(!FLAC__add_metadata_block(&encoder->private_->streaminfo, encoder->private_->frame)) {
  99558. encoder->protected_->state = FLAC__STREAM_ENCODER_FRAMING_ERROR;
  99559. return FLAC__STREAM_ENCODER_INIT_STATUS_ENCODER_ERROR;
  99560. }
  99561. if(!write_bitbuffer_(encoder, 0, /*is_last_block=*/false)) {
  99562. /* the above function sets the state for us in case of an error */
  99563. return FLAC__STREAM_ENCODER_INIT_STATUS_ENCODER_ERROR;
  99564. }
  99565. /*
  99566. * Now that the STREAMINFO block is written, we can init this to an
  99567. * absurdly-high value...
  99568. */
  99569. encoder->private_->streaminfo.data.stream_info.min_framesize = (1u << FLAC__STREAM_METADATA_STREAMINFO_MIN_FRAME_SIZE_LEN) - 1;
  99570. /* ... and clear this to 0 */
  99571. encoder->private_->streaminfo.data.stream_info.total_samples = 0;
  99572. /*
  99573. * Check to see if the supplied metadata contains a VORBIS_COMMENT;
  99574. * if not, we will write an empty one (FLAC__add_metadata_block()
  99575. * automatically supplies the vendor string).
  99576. *
  99577. * WATCHOUT: the Ogg FLAC mapping requires us to write this block after
  99578. * the STREAMINFO. (In the case that metadata_has_vorbis_comment is
  99579. * true it will have already insured that the metadata list is properly
  99580. * ordered.)
  99581. */
  99582. if(!metadata_has_vorbis_comment) {
  99583. FLAC__StreamMetadata vorbis_comment;
  99584. vorbis_comment.type = FLAC__METADATA_TYPE_VORBIS_COMMENT;
  99585. vorbis_comment.is_last = (encoder->protected_->num_metadata_blocks == 0);
  99586. vorbis_comment.length = 4 + 4; /* MAGIC NUMBER */
  99587. vorbis_comment.data.vorbis_comment.vendor_string.length = 0;
  99588. vorbis_comment.data.vorbis_comment.vendor_string.entry = 0;
  99589. vorbis_comment.data.vorbis_comment.num_comments = 0;
  99590. vorbis_comment.data.vorbis_comment.comments = 0;
  99591. if(!FLAC__add_metadata_block(&vorbis_comment, encoder->private_->frame)) {
  99592. encoder->protected_->state = FLAC__STREAM_ENCODER_FRAMING_ERROR;
  99593. return FLAC__STREAM_ENCODER_INIT_STATUS_ENCODER_ERROR;
  99594. }
  99595. if(!write_bitbuffer_(encoder, 0, /*is_last_block=*/false)) {
  99596. /* the above function sets the state for us in case of an error */
  99597. return FLAC__STREAM_ENCODER_INIT_STATUS_ENCODER_ERROR;
  99598. }
  99599. }
  99600. /*
  99601. * write the user's metadata blocks
  99602. */
  99603. for(i = 0; i < encoder->protected_->num_metadata_blocks; i++) {
  99604. encoder->protected_->metadata[i]->is_last = (i == encoder->protected_->num_metadata_blocks - 1);
  99605. if(!FLAC__add_metadata_block(encoder->protected_->metadata[i], encoder->private_->frame)) {
  99606. encoder->protected_->state = FLAC__STREAM_ENCODER_FRAMING_ERROR;
  99607. return FLAC__STREAM_ENCODER_INIT_STATUS_ENCODER_ERROR;
  99608. }
  99609. if(!write_bitbuffer_(encoder, 0, /*is_last_block=*/false)) {
  99610. /* the above function sets the state for us in case of an error */
  99611. return FLAC__STREAM_ENCODER_INIT_STATUS_ENCODER_ERROR;
  99612. }
  99613. }
  99614. /* now that all the metadata is written, we save the stream offset */
  99615. 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 */
  99616. encoder->protected_->state = FLAC__STREAM_ENCODER_CLIENT_ERROR;
  99617. return FLAC__STREAM_ENCODER_INIT_STATUS_ENCODER_ERROR;
  99618. }
  99619. if(encoder->protected_->verify)
  99620. encoder->private_->verify.state_hint = ENCODER_IN_AUDIO;
  99621. return FLAC__STREAM_ENCODER_INIT_STATUS_OK;
  99622. }
  99623. FLAC_API FLAC__StreamEncoderInitStatus FLAC__stream_encoder_init_stream(
  99624. FLAC__StreamEncoder *encoder,
  99625. FLAC__StreamEncoderWriteCallback write_callback,
  99626. FLAC__StreamEncoderSeekCallback seek_callback,
  99627. FLAC__StreamEncoderTellCallback tell_callback,
  99628. FLAC__StreamEncoderMetadataCallback metadata_callback,
  99629. void *client_data
  99630. )
  99631. {
  99632. return init_stream_internal_enc(
  99633. encoder,
  99634. /*read_callback=*/0,
  99635. write_callback,
  99636. seek_callback,
  99637. tell_callback,
  99638. metadata_callback,
  99639. client_data,
  99640. /*is_ogg=*/false
  99641. );
  99642. }
  99643. FLAC_API FLAC__StreamEncoderInitStatus FLAC__stream_encoder_init_ogg_stream(
  99644. FLAC__StreamEncoder *encoder,
  99645. FLAC__StreamEncoderReadCallback read_callback,
  99646. FLAC__StreamEncoderWriteCallback write_callback,
  99647. FLAC__StreamEncoderSeekCallback seek_callback,
  99648. FLAC__StreamEncoderTellCallback tell_callback,
  99649. FLAC__StreamEncoderMetadataCallback metadata_callback,
  99650. void *client_data
  99651. )
  99652. {
  99653. return init_stream_internal_enc(
  99654. encoder,
  99655. read_callback,
  99656. write_callback,
  99657. seek_callback,
  99658. tell_callback,
  99659. metadata_callback,
  99660. client_data,
  99661. /*is_ogg=*/true
  99662. );
  99663. }
  99664. static FLAC__StreamEncoderInitStatus init_FILE_internal_enc(
  99665. FLAC__StreamEncoder *encoder,
  99666. FILE *file,
  99667. FLAC__StreamEncoderProgressCallback progress_callback,
  99668. void *client_data,
  99669. FLAC__bool is_ogg
  99670. )
  99671. {
  99672. FLAC__StreamEncoderInitStatus init_status;
  99673. FLAC__ASSERT(0 != encoder);
  99674. FLAC__ASSERT(0 != file);
  99675. if(encoder->protected_->state != FLAC__STREAM_ENCODER_UNINITIALIZED)
  99676. return FLAC__STREAM_ENCODER_INIT_STATUS_ALREADY_INITIALIZED;
  99677. /* double protection */
  99678. if(file == 0) {
  99679. encoder->protected_->state = FLAC__STREAM_ENCODER_IO_ERROR;
  99680. return FLAC__STREAM_ENCODER_INIT_STATUS_ENCODER_ERROR;
  99681. }
  99682. /*
  99683. * To make sure that our file does not go unclosed after an error, we
  99684. * must assign the FILE pointer before any further error can occur in
  99685. * this routine.
  99686. */
  99687. if(file == stdout)
  99688. file = get_binary_stdout_(); /* just to be safe */
  99689. encoder->private_->file = file;
  99690. encoder->private_->progress_callback = progress_callback;
  99691. encoder->private_->bytes_written = 0;
  99692. encoder->private_->samples_written = 0;
  99693. encoder->private_->frames_written = 0;
  99694. init_status = init_stream_internal_enc(
  99695. encoder,
  99696. encoder->private_->file == stdout? 0 : is_ogg? file_read_callback_enc : 0,
  99697. file_write_callback_,
  99698. encoder->private_->file == stdout? 0 : file_seek_callback_enc,
  99699. encoder->private_->file == stdout? 0 : file_tell_callback_enc,
  99700. /*metadata_callback=*/0,
  99701. client_data,
  99702. is_ogg
  99703. );
  99704. if(init_status != FLAC__STREAM_ENCODER_INIT_STATUS_OK) {
  99705. /* the above function sets the state for us in case of an error */
  99706. return init_status;
  99707. }
  99708. {
  99709. unsigned blocksize = FLAC__stream_encoder_get_blocksize(encoder);
  99710. FLAC__ASSERT(blocksize != 0);
  99711. encoder->private_->total_frames_estimate = (unsigned)((FLAC__stream_encoder_get_total_samples_estimate(encoder) + blocksize - 1) / blocksize);
  99712. }
  99713. return init_status;
  99714. }
  99715. FLAC_API FLAC__StreamEncoderInitStatus FLAC__stream_encoder_init_FILE(
  99716. FLAC__StreamEncoder *encoder,
  99717. FILE *file,
  99718. FLAC__StreamEncoderProgressCallback progress_callback,
  99719. void *client_data
  99720. )
  99721. {
  99722. return init_FILE_internal_enc(encoder, file, progress_callback, client_data, /*is_ogg=*/false);
  99723. }
  99724. FLAC_API FLAC__StreamEncoderInitStatus FLAC__stream_encoder_init_ogg_FILE(
  99725. FLAC__StreamEncoder *encoder,
  99726. FILE *file,
  99727. FLAC__StreamEncoderProgressCallback progress_callback,
  99728. void *client_data
  99729. )
  99730. {
  99731. return init_FILE_internal_enc(encoder, file, progress_callback, client_data, /*is_ogg=*/true);
  99732. }
  99733. static FLAC__StreamEncoderInitStatus init_file_internal_enc(
  99734. FLAC__StreamEncoder *encoder,
  99735. const char *filename,
  99736. FLAC__StreamEncoderProgressCallback progress_callback,
  99737. void *client_data,
  99738. FLAC__bool is_ogg
  99739. )
  99740. {
  99741. FILE *file;
  99742. FLAC__ASSERT(0 != encoder);
  99743. /*
  99744. * To make sure that our file does not go unclosed after an error, we
  99745. * have to do the same entrance checks here that are later performed
  99746. * in FLAC__stream_encoder_init_FILE() before the FILE* is assigned.
  99747. */
  99748. if(encoder->protected_->state != FLAC__STREAM_ENCODER_UNINITIALIZED)
  99749. return FLAC__STREAM_ENCODER_INIT_STATUS_ALREADY_INITIALIZED;
  99750. file = filename? fopen(filename, "w+b") : stdout;
  99751. if(file == 0) {
  99752. encoder->protected_->state = FLAC__STREAM_ENCODER_IO_ERROR;
  99753. return FLAC__STREAM_ENCODER_INIT_STATUS_ENCODER_ERROR;
  99754. }
  99755. return init_FILE_internal_enc(encoder, file, progress_callback, client_data, is_ogg);
  99756. }
  99757. FLAC_API FLAC__StreamEncoderInitStatus FLAC__stream_encoder_init_file(
  99758. FLAC__StreamEncoder *encoder,
  99759. const char *filename,
  99760. FLAC__StreamEncoderProgressCallback progress_callback,
  99761. void *client_data
  99762. )
  99763. {
  99764. return init_file_internal_enc(encoder, filename, progress_callback, client_data, /*is_ogg=*/false);
  99765. }
  99766. FLAC_API FLAC__StreamEncoderInitStatus FLAC__stream_encoder_init_ogg_file(
  99767. FLAC__StreamEncoder *encoder,
  99768. const char *filename,
  99769. FLAC__StreamEncoderProgressCallback progress_callback,
  99770. void *client_data
  99771. )
  99772. {
  99773. return init_file_internal_enc(encoder, filename, progress_callback, client_data, /*is_ogg=*/true);
  99774. }
  99775. FLAC_API FLAC__bool FLAC__stream_encoder_finish(FLAC__StreamEncoder *encoder)
  99776. {
  99777. FLAC__bool error = false;
  99778. FLAC__ASSERT(0 != encoder);
  99779. FLAC__ASSERT(0 != encoder->private_);
  99780. FLAC__ASSERT(0 != encoder->protected_);
  99781. if(encoder->protected_->state == FLAC__STREAM_ENCODER_UNINITIALIZED)
  99782. return true;
  99783. if(encoder->protected_->state == FLAC__STREAM_ENCODER_OK && !encoder->private_->is_being_deleted) {
  99784. if(encoder->private_->current_sample_number != 0) {
  99785. const FLAC__bool is_fractional_block = encoder->protected_->blocksize != encoder->private_->current_sample_number;
  99786. encoder->protected_->blocksize = encoder->private_->current_sample_number;
  99787. if(!process_frame_(encoder, is_fractional_block, /*is_last_block=*/true))
  99788. error = true;
  99789. }
  99790. }
  99791. if(encoder->protected_->do_md5)
  99792. FLAC__MD5Final(encoder->private_->streaminfo.data.stream_info.md5sum, &encoder->private_->md5context);
  99793. if(!encoder->private_->is_being_deleted) {
  99794. if(encoder->protected_->state == FLAC__STREAM_ENCODER_OK) {
  99795. if(encoder->private_->seek_callback) {
  99796. #if FLAC__HAS_OGG
  99797. if(encoder->private_->is_ogg)
  99798. update_ogg_metadata_(encoder);
  99799. else
  99800. #endif
  99801. update_metadata_(encoder);
  99802. /* check if an error occurred while updating metadata */
  99803. if(encoder->protected_->state != FLAC__STREAM_ENCODER_OK)
  99804. error = true;
  99805. }
  99806. if(encoder->private_->metadata_callback)
  99807. encoder->private_->metadata_callback(encoder, &encoder->private_->streaminfo, encoder->private_->client_data);
  99808. }
  99809. if(encoder->protected_->verify && 0 != encoder->private_->verify.decoder && !FLAC__stream_decoder_finish(encoder->private_->verify.decoder)) {
  99810. if(!error)
  99811. encoder->protected_->state = FLAC__STREAM_ENCODER_VERIFY_MISMATCH_IN_AUDIO_DATA;
  99812. error = true;
  99813. }
  99814. }
  99815. if(0 != encoder->private_->file) {
  99816. if(encoder->private_->file != stdout)
  99817. fclose(encoder->private_->file);
  99818. encoder->private_->file = 0;
  99819. }
  99820. #if FLAC__HAS_OGG
  99821. if(encoder->private_->is_ogg)
  99822. FLAC__ogg_encoder_aspect_finish(&encoder->protected_->ogg_encoder_aspect);
  99823. #endif
  99824. free_(encoder);
  99825. set_defaults_enc(encoder);
  99826. if(!error)
  99827. encoder->protected_->state = FLAC__STREAM_ENCODER_UNINITIALIZED;
  99828. return !error;
  99829. }
  99830. FLAC_API FLAC__bool FLAC__stream_encoder_set_ogg_serial_number(FLAC__StreamEncoder *encoder, long value)
  99831. {
  99832. FLAC__ASSERT(0 != encoder);
  99833. FLAC__ASSERT(0 != encoder->private_);
  99834. FLAC__ASSERT(0 != encoder->protected_);
  99835. if(encoder->protected_->state != FLAC__STREAM_ENCODER_UNINITIALIZED)
  99836. return false;
  99837. #if FLAC__HAS_OGG
  99838. /* can't check encoder->private_->is_ogg since that's not set until init time */
  99839. FLAC__ogg_encoder_aspect_set_serial_number(&encoder->protected_->ogg_encoder_aspect, value);
  99840. return true;
  99841. #else
  99842. (void)value;
  99843. return false;
  99844. #endif
  99845. }
  99846. FLAC_API FLAC__bool FLAC__stream_encoder_set_verify(FLAC__StreamEncoder *encoder, FLAC__bool value)
  99847. {
  99848. FLAC__ASSERT(0 != encoder);
  99849. FLAC__ASSERT(0 != encoder->private_);
  99850. FLAC__ASSERT(0 != encoder->protected_);
  99851. if(encoder->protected_->state != FLAC__STREAM_ENCODER_UNINITIALIZED)
  99852. return false;
  99853. #ifndef FLAC__MANDATORY_VERIFY_WHILE_ENCODING
  99854. encoder->protected_->verify = value;
  99855. #endif
  99856. return true;
  99857. }
  99858. FLAC_API FLAC__bool FLAC__stream_encoder_set_streamable_subset(FLAC__StreamEncoder *encoder, FLAC__bool value)
  99859. {
  99860. FLAC__ASSERT(0 != encoder);
  99861. FLAC__ASSERT(0 != encoder->private_);
  99862. FLAC__ASSERT(0 != encoder->protected_);
  99863. if(encoder->protected_->state != FLAC__STREAM_ENCODER_UNINITIALIZED)
  99864. return false;
  99865. encoder->protected_->streamable_subset = value;
  99866. return true;
  99867. }
  99868. FLAC_API FLAC__bool FLAC__stream_encoder_set_do_md5(FLAC__StreamEncoder *encoder, FLAC__bool value)
  99869. {
  99870. FLAC__ASSERT(0 != encoder);
  99871. FLAC__ASSERT(0 != encoder->private_);
  99872. FLAC__ASSERT(0 != encoder->protected_);
  99873. if(encoder->protected_->state != FLAC__STREAM_ENCODER_UNINITIALIZED)
  99874. return false;
  99875. encoder->protected_->do_md5 = value;
  99876. return true;
  99877. }
  99878. FLAC_API FLAC__bool FLAC__stream_encoder_set_channels(FLAC__StreamEncoder *encoder, unsigned value)
  99879. {
  99880. FLAC__ASSERT(0 != encoder);
  99881. FLAC__ASSERT(0 != encoder->private_);
  99882. FLAC__ASSERT(0 != encoder->protected_);
  99883. if(encoder->protected_->state != FLAC__STREAM_ENCODER_UNINITIALIZED)
  99884. return false;
  99885. encoder->protected_->channels = value;
  99886. return true;
  99887. }
  99888. FLAC_API FLAC__bool FLAC__stream_encoder_set_bits_per_sample(FLAC__StreamEncoder *encoder, unsigned value)
  99889. {
  99890. FLAC__ASSERT(0 != encoder);
  99891. FLAC__ASSERT(0 != encoder->private_);
  99892. FLAC__ASSERT(0 != encoder->protected_);
  99893. if(encoder->protected_->state != FLAC__STREAM_ENCODER_UNINITIALIZED)
  99894. return false;
  99895. encoder->protected_->bits_per_sample = value;
  99896. return true;
  99897. }
  99898. FLAC_API FLAC__bool FLAC__stream_encoder_set_sample_rate(FLAC__StreamEncoder *encoder, unsigned value)
  99899. {
  99900. FLAC__ASSERT(0 != encoder);
  99901. FLAC__ASSERT(0 != encoder->private_);
  99902. FLAC__ASSERT(0 != encoder->protected_);
  99903. if(encoder->protected_->state != FLAC__STREAM_ENCODER_UNINITIALIZED)
  99904. return false;
  99905. encoder->protected_->sample_rate = value;
  99906. return true;
  99907. }
  99908. FLAC_API FLAC__bool FLAC__stream_encoder_set_compression_level(FLAC__StreamEncoder *encoder, unsigned value)
  99909. {
  99910. FLAC__bool ok = true;
  99911. FLAC__ASSERT(0 != encoder);
  99912. FLAC__ASSERT(0 != encoder->private_);
  99913. FLAC__ASSERT(0 != encoder->protected_);
  99914. if(encoder->protected_->state != FLAC__STREAM_ENCODER_UNINITIALIZED)
  99915. return false;
  99916. if(value >= sizeof(compression_levels_)/sizeof(compression_levels_[0]))
  99917. value = sizeof(compression_levels_)/sizeof(compression_levels_[0]) - 1;
  99918. ok &= FLAC__stream_encoder_set_do_mid_side_stereo (encoder, compression_levels_[value].do_mid_side_stereo);
  99919. ok &= FLAC__stream_encoder_set_loose_mid_side_stereo (encoder, compression_levels_[value].loose_mid_side_stereo);
  99920. #ifndef FLAC__INTEGER_ONLY_LIBRARY
  99921. #if 0
  99922. /* was: */
  99923. ok &= FLAC__stream_encoder_set_apodization (encoder, compression_levels_[value].apodization);
  99924. /* but it's too hard to specify the string in a locale-specific way */
  99925. #else
  99926. encoder->protected_->num_apodizations = 1;
  99927. encoder->protected_->apodizations[0].type = FLAC__APODIZATION_TUKEY;
  99928. encoder->protected_->apodizations[0].parameters.tukey.p = 0.5;
  99929. #endif
  99930. #endif
  99931. ok &= FLAC__stream_encoder_set_max_lpc_order (encoder, compression_levels_[value].max_lpc_order);
  99932. ok &= FLAC__stream_encoder_set_qlp_coeff_precision (encoder, compression_levels_[value].qlp_coeff_precision);
  99933. ok &= FLAC__stream_encoder_set_do_qlp_coeff_prec_search (encoder, compression_levels_[value].do_qlp_coeff_prec_search);
  99934. ok &= FLAC__stream_encoder_set_do_escape_coding (encoder, compression_levels_[value].do_escape_coding);
  99935. ok &= FLAC__stream_encoder_set_do_exhaustive_model_search (encoder, compression_levels_[value].do_exhaustive_model_search);
  99936. ok &= FLAC__stream_encoder_set_min_residual_partition_order(encoder, compression_levels_[value].min_residual_partition_order);
  99937. ok &= FLAC__stream_encoder_set_max_residual_partition_order(encoder, compression_levels_[value].max_residual_partition_order);
  99938. ok &= FLAC__stream_encoder_set_rice_parameter_search_dist (encoder, compression_levels_[value].rice_parameter_search_dist);
  99939. return ok;
  99940. }
  99941. FLAC_API FLAC__bool FLAC__stream_encoder_set_blocksize(FLAC__StreamEncoder *encoder, unsigned value)
  99942. {
  99943. FLAC__ASSERT(0 != encoder);
  99944. FLAC__ASSERT(0 != encoder->private_);
  99945. FLAC__ASSERT(0 != encoder->protected_);
  99946. if(encoder->protected_->state != FLAC__STREAM_ENCODER_UNINITIALIZED)
  99947. return false;
  99948. encoder->protected_->blocksize = value;
  99949. return true;
  99950. }
  99951. FLAC_API FLAC__bool FLAC__stream_encoder_set_do_mid_side_stereo(FLAC__StreamEncoder *encoder, FLAC__bool value)
  99952. {
  99953. FLAC__ASSERT(0 != encoder);
  99954. FLAC__ASSERT(0 != encoder->private_);
  99955. FLAC__ASSERT(0 != encoder->protected_);
  99956. if(encoder->protected_->state != FLAC__STREAM_ENCODER_UNINITIALIZED)
  99957. return false;
  99958. encoder->protected_->do_mid_side_stereo = value;
  99959. return true;
  99960. }
  99961. FLAC_API FLAC__bool FLAC__stream_encoder_set_loose_mid_side_stereo(FLAC__StreamEncoder *encoder, FLAC__bool value)
  99962. {
  99963. FLAC__ASSERT(0 != encoder);
  99964. FLAC__ASSERT(0 != encoder->private_);
  99965. FLAC__ASSERT(0 != encoder->protected_);
  99966. if(encoder->protected_->state != FLAC__STREAM_ENCODER_UNINITIALIZED)
  99967. return false;
  99968. encoder->protected_->loose_mid_side_stereo = value;
  99969. return true;
  99970. }
  99971. /*@@@@add to tests*/
  99972. FLAC_API FLAC__bool FLAC__stream_encoder_set_apodization(FLAC__StreamEncoder *encoder, const char *specification)
  99973. {
  99974. FLAC__ASSERT(0 != encoder);
  99975. FLAC__ASSERT(0 != encoder->private_);
  99976. FLAC__ASSERT(0 != encoder->protected_);
  99977. FLAC__ASSERT(0 != specification);
  99978. if(encoder->protected_->state != FLAC__STREAM_ENCODER_UNINITIALIZED)
  99979. return false;
  99980. #ifdef FLAC__INTEGER_ONLY_LIBRARY
  99981. (void)specification; /* silently ignore since we haven't integerized; will always use a rectangular window */
  99982. #else
  99983. encoder->protected_->num_apodizations = 0;
  99984. while(1) {
  99985. const char *s = strchr(specification, ';');
  99986. const size_t n = s? (size_t)(s - specification) : strlen(specification);
  99987. if (n==8 && 0 == strncmp("bartlett" , specification, n))
  99988. encoder->protected_->apodizations[encoder->protected_->num_apodizations++].type = FLAC__APODIZATION_BARTLETT;
  99989. else if(n==13 && 0 == strncmp("bartlett_hann", specification, n))
  99990. encoder->protected_->apodizations[encoder->protected_->num_apodizations++].type = FLAC__APODIZATION_BARTLETT_HANN;
  99991. else if(n==8 && 0 == strncmp("blackman" , specification, n))
  99992. encoder->protected_->apodizations[encoder->protected_->num_apodizations++].type = FLAC__APODIZATION_BLACKMAN;
  99993. else if(n==26 && 0 == strncmp("blackman_harris_4term_92db", specification, n))
  99994. encoder->protected_->apodizations[encoder->protected_->num_apodizations++].type = FLAC__APODIZATION_BLACKMAN_HARRIS_4TERM_92DB_SIDELOBE;
  99995. else if(n==6 && 0 == strncmp("connes" , specification, n))
  99996. encoder->protected_->apodizations[encoder->protected_->num_apodizations++].type = FLAC__APODIZATION_CONNES;
  99997. else if(n==7 && 0 == strncmp("flattop" , specification, n))
  99998. encoder->protected_->apodizations[encoder->protected_->num_apodizations++].type = FLAC__APODIZATION_FLATTOP;
  99999. else if(n>7 && 0 == strncmp("gauss(" , specification, 6)) {
  100000. FLAC__real stddev = (FLAC__real)strtod(specification+6, 0);
  100001. if (stddev > 0.0 && stddev <= 0.5) {
  100002. encoder->protected_->apodizations[encoder->protected_->num_apodizations].parameters.gauss.stddev = stddev;
  100003. encoder->protected_->apodizations[encoder->protected_->num_apodizations++].type = FLAC__APODIZATION_GAUSS;
  100004. }
  100005. }
  100006. else if(n==7 && 0 == strncmp("hamming" , specification, n))
  100007. encoder->protected_->apodizations[encoder->protected_->num_apodizations++].type = FLAC__APODIZATION_HAMMING;
  100008. else if(n==4 && 0 == strncmp("hann" , specification, n))
  100009. encoder->protected_->apodizations[encoder->protected_->num_apodizations++].type = FLAC__APODIZATION_HANN;
  100010. else if(n==13 && 0 == strncmp("kaiser_bessel", specification, n))
  100011. encoder->protected_->apodizations[encoder->protected_->num_apodizations++].type = FLAC__APODIZATION_KAISER_BESSEL;
  100012. else if(n==7 && 0 == strncmp("nuttall" , specification, n))
  100013. encoder->protected_->apodizations[encoder->protected_->num_apodizations++].type = FLAC__APODIZATION_NUTTALL;
  100014. else if(n==9 && 0 == strncmp("rectangle" , specification, n))
  100015. encoder->protected_->apodizations[encoder->protected_->num_apodizations++].type = FLAC__APODIZATION_RECTANGLE;
  100016. else if(n==8 && 0 == strncmp("triangle" , specification, n))
  100017. encoder->protected_->apodizations[encoder->protected_->num_apodizations++].type = FLAC__APODIZATION_TRIANGLE;
  100018. else if(n>7 && 0 == strncmp("tukey(" , specification, 6)) {
  100019. FLAC__real p = (FLAC__real)strtod(specification+6, 0);
  100020. if (p >= 0.0 && p <= 1.0) {
  100021. encoder->protected_->apodizations[encoder->protected_->num_apodizations].parameters.tukey.p = p;
  100022. encoder->protected_->apodizations[encoder->protected_->num_apodizations++].type = FLAC__APODIZATION_TUKEY;
  100023. }
  100024. }
  100025. else if(n==5 && 0 == strncmp("welch" , specification, n))
  100026. encoder->protected_->apodizations[encoder->protected_->num_apodizations++].type = FLAC__APODIZATION_WELCH;
  100027. if (encoder->protected_->num_apodizations == 32)
  100028. break;
  100029. if (s)
  100030. specification = s+1;
  100031. else
  100032. break;
  100033. }
  100034. if(encoder->protected_->num_apodizations == 0) {
  100035. encoder->protected_->num_apodizations = 1;
  100036. encoder->protected_->apodizations[0].type = FLAC__APODIZATION_TUKEY;
  100037. encoder->protected_->apodizations[0].parameters.tukey.p = 0.5;
  100038. }
  100039. #endif
  100040. return true;
  100041. }
  100042. FLAC_API FLAC__bool FLAC__stream_encoder_set_max_lpc_order(FLAC__StreamEncoder *encoder, unsigned value)
  100043. {
  100044. FLAC__ASSERT(0 != encoder);
  100045. FLAC__ASSERT(0 != encoder->private_);
  100046. FLAC__ASSERT(0 != encoder->protected_);
  100047. if(encoder->protected_->state != FLAC__STREAM_ENCODER_UNINITIALIZED)
  100048. return false;
  100049. encoder->protected_->max_lpc_order = value;
  100050. return true;
  100051. }
  100052. FLAC_API FLAC__bool FLAC__stream_encoder_set_qlp_coeff_precision(FLAC__StreamEncoder *encoder, unsigned value)
  100053. {
  100054. FLAC__ASSERT(0 != encoder);
  100055. FLAC__ASSERT(0 != encoder->private_);
  100056. FLAC__ASSERT(0 != encoder->protected_);
  100057. if(encoder->protected_->state != FLAC__STREAM_ENCODER_UNINITIALIZED)
  100058. return false;
  100059. encoder->protected_->qlp_coeff_precision = value;
  100060. return true;
  100061. }
  100062. FLAC_API FLAC__bool FLAC__stream_encoder_set_do_qlp_coeff_prec_search(FLAC__StreamEncoder *encoder, FLAC__bool value)
  100063. {
  100064. FLAC__ASSERT(0 != encoder);
  100065. FLAC__ASSERT(0 != encoder->private_);
  100066. FLAC__ASSERT(0 != encoder->protected_);
  100067. if(encoder->protected_->state != FLAC__STREAM_ENCODER_UNINITIALIZED)
  100068. return false;
  100069. encoder->protected_->do_qlp_coeff_prec_search = value;
  100070. return true;
  100071. }
  100072. FLAC_API FLAC__bool FLAC__stream_encoder_set_do_escape_coding(FLAC__StreamEncoder *encoder, FLAC__bool value)
  100073. {
  100074. FLAC__ASSERT(0 != encoder);
  100075. FLAC__ASSERT(0 != encoder->private_);
  100076. FLAC__ASSERT(0 != encoder->protected_);
  100077. if(encoder->protected_->state != FLAC__STREAM_ENCODER_UNINITIALIZED)
  100078. return false;
  100079. #if 0
  100080. /*@@@ deprecated: */
  100081. encoder->protected_->do_escape_coding = value;
  100082. #else
  100083. (void)value;
  100084. #endif
  100085. return true;
  100086. }
  100087. FLAC_API FLAC__bool FLAC__stream_encoder_set_do_exhaustive_model_search(FLAC__StreamEncoder *encoder, FLAC__bool value)
  100088. {
  100089. FLAC__ASSERT(0 != encoder);
  100090. FLAC__ASSERT(0 != encoder->private_);
  100091. FLAC__ASSERT(0 != encoder->protected_);
  100092. if(encoder->protected_->state != FLAC__STREAM_ENCODER_UNINITIALIZED)
  100093. return false;
  100094. encoder->protected_->do_exhaustive_model_search = value;
  100095. return true;
  100096. }
  100097. FLAC_API FLAC__bool FLAC__stream_encoder_set_min_residual_partition_order(FLAC__StreamEncoder *encoder, unsigned value)
  100098. {
  100099. FLAC__ASSERT(0 != encoder);
  100100. FLAC__ASSERT(0 != encoder->private_);
  100101. FLAC__ASSERT(0 != encoder->protected_);
  100102. if(encoder->protected_->state != FLAC__STREAM_ENCODER_UNINITIALIZED)
  100103. return false;
  100104. encoder->protected_->min_residual_partition_order = value;
  100105. return true;
  100106. }
  100107. FLAC_API FLAC__bool FLAC__stream_encoder_set_max_residual_partition_order(FLAC__StreamEncoder *encoder, unsigned value)
  100108. {
  100109. FLAC__ASSERT(0 != encoder);
  100110. FLAC__ASSERT(0 != encoder->private_);
  100111. FLAC__ASSERT(0 != encoder->protected_);
  100112. if(encoder->protected_->state != FLAC__STREAM_ENCODER_UNINITIALIZED)
  100113. return false;
  100114. encoder->protected_->max_residual_partition_order = value;
  100115. return true;
  100116. }
  100117. FLAC_API FLAC__bool FLAC__stream_encoder_set_rice_parameter_search_dist(FLAC__StreamEncoder *encoder, unsigned value)
  100118. {
  100119. FLAC__ASSERT(0 != encoder);
  100120. FLAC__ASSERT(0 != encoder->private_);
  100121. FLAC__ASSERT(0 != encoder->protected_);
  100122. if(encoder->protected_->state != FLAC__STREAM_ENCODER_UNINITIALIZED)
  100123. return false;
  100124. #if 0
  100125. /*@@@ deprecated: */
  100126. encoder->protected_->rice_parameter_search_dist = value;
  100127. #else
  100128. (void)value;
  100129. #endif
  100130. return true;
  100131. }
  100132. FLAC_API FLAC__bool FLAC__stream_encoder_set_total_samples_estimate(FLAC__StreamEncoder *encoder, FLAC__uint64 value)
  100133. {
  100134. FLAC__ASSERT(0 != encoder);
  100135. FLAC__ASSERT(0 != encoder->private_);
  100136. FLAC__ASSERT(0 != encoder->protected_);
  100137. if(encoder->protected_->state != FLAC__STREAM_ENCODER_UNINITIALIZED)
  100138. return false;
  100139. encoder->protected_->total_samples_estimate = value;
  100140. return true;
  100141. }
  100142. FLAC_API FLAC__bool FLAC__stream_encoder_set_metadata(FLAC__StreamEncoder *encoder, FLAC__StreamMetadata **metadata, unsigned num_blocks)
  100143. {
  100144. FLAC__ASSERT(0 != encoder);
  100145. FLAC__ASSERT(0 != encoder->private_);
  100146. FLAC__ASSERT(0 != encoder->protected_);
  100147. if(encoder->protected_->state != FLAC__STREAM_ENCODER_UNINITIALIZED)
  100148. return false;
  100149. if(0 == metadata)
  100150. num_blocks = 0;
  100151. if(0 == num_blocks)
  100152. metadata = 0;
  100153. /* realloc() does not do exactly what we want so... */
  100154. if(encoder->protected_->metadata) {
  100155. free(encoder->protected_->metadata);
  100156. encoder->protected_->metadata = 0;
  100157. encoder->protected_->num_metadata_blocks = 0;
  100158. }
  100159. if(num_blocks) {
  100160. FLAC__StreamMetadata **m;
  100161. if(0 == (m = (FLAC__StreamMetadata**)safe_malloc_mul_2op_(sizeof(m[0]), /*times*/num_blocks)))
  100162. return false;
  100163. memcpy(m, metadata, sizeof(m[0]) * num_blocks);
  100164. encoder->protected_->metadata = m;
  100165. encoder->protected_->num_metadata_blocks = num_blocks;
  100166. }
  100167. #if FLAC__HAS_OGG
  100168. if(!FLAC__ogg_encoder_aspect_set_num_metadata(&encoder->protected_->ogg_encoder_aspect, num_blocks))
  100169. return false;
  100170. #endif
  100171. return true;
  100172. }
  100173. /*
  100174. * These three functions are not static, but not publically exposed in
  100175. * include/FLAC/ either. They are used by the test suite.
  100176. */
  100177. FLAC_API FLAC__bool FLAC__stream_encoder_disable_constant_subframes(FLAC__StreamEncoder *encoder, FLAC__bool value)
  100178. {
  100179. FLAC__ASSERT(0 != encoder);
  100180. FLAC__ASSERT(0 != encoder->private_);
  100181. FLAC__ASSERT(0 != encoder->protected_);
  100182. if(encoder->protected_->state != FLAC__STREAM_ENCODER_UNINITIALIZED)
  100183. return false;
  100184. encoder->private_->disable_constant_subframes = value;
  100185. return true;
  100186. }
  100187. FLAC_API FLAC__bool FLAC__stream_encoder_disable_fixed_subframes(FLAC__StreamEncoder *encoder, FLAC__bool value)
  100188. {
  100189. FLAC__ASSERT(0 != encoder);
  100190. FLAC__ASSERT(0 != encoder->private_);
  100191. FLAC__ASSERT(0 != encoder->protected_);
  100192. if(encoder->protected_->state != FLAC__STREAM_ENCODER_UNINITIALIZED)
  100193. return false;
  100194. encoder->private_->disable_fixed_subframes = value;
  100195. return true;
  100196. }
  100197. FLAC_API FLAC__bool FLAC__stream_encoder_disable_verbatim_subframes(FLAC__StreamEncoder *encoder, FLAC__bool value)
  100198. {
  100199. FLAC__ASSERT(0 != encoder);
  100200. FLAC__ASSERT(0 != encoder->private_);
  100201. FLAC__ASSERT(0 != encoder->protected_);
  100202. if(encoder->protected_->state != FLAC__STREAM_ENCODER_UNINITIALIZED)
  100203. return false;
  100204. encoder->private_->disable_verbatim_subframes = value;
  100205. return true;
  100206. }
  100207. FLAC_API FLAC__StreamEncoderState FLAC__stream_encoder_get_state(const FLAC__StreamEncoder *encoder)
  100208. {
  100209. FLAC__ASSERT(0 != encoder);
  100210. FLAC__ASSERT(0 != encoder->private_);
  100211. FLAC__ASSERT(0 != encoder->protected_);
  100212. return encoder->protected_->state;
  100213. }
  100214. FLAC_API FLAC__StreamDecoderState FLAC__stream_encoder_get_verify_decoder_state(const FLAC__StreamEncoder *encoder)
  100215. {
  100216. FLAC__ASSERT(0 != encoder);
  100217. FLAC__ASSERT(0 != encoder->private_);
  100218. FLAC__ASSERT(0 != encoder->protected_);
  100219. if(encoder->protected_->verify)
  100220. return FLAC__stream_decoder_get_state(encoder->private_->verify.decoder);
  100221. else
  100222. return FLAC__STREAM_DECODER_UNINITIALIZED;
  100223. }
  100224. FLAC_API const char *FLAC__stream_encoder_get_resolved_state_string(const FLAC__StreamEncoder *encoder)
  100225. {
  100226. FLAC__ASSERT(0 != encoder);
  100227. FLAC__ASSERT(0 != encoder->private_);
  100228. FLAC__ASSERT(0 != encoder->protected_);
  100229. if(encoder->protected_->state != FLAC__STREAM_ENCODER_VERIFY_DECODER_ERROR)
  100230. return FLAC__StreamEncoderStateString[encoder->protected_->state];
  100231. else
  100232. return FLAC__stream_decoder_get_resolved_state_string(encoder->private_->verify.decoder);
  100233. }
  100234. 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)
  100235. {
  100236. FLAC__ASSERT(0 != encoder);
  100237. FLAC__ASSERT(0 != encoder->private_);
  100238. FLAC__ASSERT(0 != encoder->protected_);
  100239. if(0 != absolute_sample)
  100240. *absolute_sample = encoder->private_->verify.error_stats.absolute_sample;
  100241. if(0 != frame_number)
  100242. *frame_number = encoder->private_->verify.error_stats.frame_number;
  100243. if(0 != channel)
  100244. *channel = encoder->private_->verify.error_stats.channel;
  100245. if(0 != sample)
  100246. *sample = encoder->private_->verify.error_stats.sample;
  100247. if(0 != expected)
  100248. *expected = encoder->private_->verify.error_stats.expected;
  100249. if(0 != got)
  100250. *got = encoder->private_->verify.error_stats.got;
  100251. }
  100252. FLAC_API FLAC__bool FLAC__stream_encoder_get_verify(const FLAC__StreamEncoder *encoder)
  100253. {
  100254. FLAC__ASSERT(0 != encoder);
  100255. FLAC__ASSERT(0 != encoder->private_);
  100256. FLAC__ASSERT(0 != encoder->protected_);
  100257. return encoder->protected_->verify;
  100258. }
  100259. FLAC_API FLAC__bool FLAC__stream_encoder_get_streamable_subset(const FLAC__StreamEncoder *encoder)
  100260. {
  100261. FLAC__ASSERT(0 != encoder);
  100262. FLAC__ASSERT(0 != encoder->private_);
  100263. FLAC__ASSERT(0 != encoder->protected_);
  100264. return encoder->protected_->streamable_subset;
  100265. }
  100266. FLAC_API FLAC__bool FLAC__stream_encoder_get_do_md5(const FLAC__StreamEncoder *encoder)
  100267. {
  100268. FLAC__ASSERT(0 != encoder);
  100269. FLAC__ASSERT(0 != encoder->private_);
  100270. FLAC__ASSERT(0 != encoder->protected_);
  100271. return encoder->protected_->do_md5;
  100272. }
  100273. FLAC_API unsigned FLAC__stream_encoder_get_channels(const FLAC__StreamEncoder *encoder)
  100274. {
  100275. FLAC__ASSERT(0 != encoder);
  100276. FLAC__ASSERT(0 != encoder->private_);
  100277. FLAC__ASSERT(0 != encoder->protected_);
  100278. return encoder->protected_->channels;
  100279. }
  100280. FLAC_API unsigned FLAC__stream_encoder_get_bits_per_sample(const FLAC__StreamEncoder *encoder)
  100281. {
  100282. FLAC__ASSERT(0 != encoder);
  100283. FLAC__ASSERT(0 != encoder->private_);
  100284. FLAC__ASSERT(0 != encoder->protected_);
  100285. return encoder->protected_->bits_per_sample;
  100286. }
  100287. FLAC_API unsigned FLAC__stream_encoder_get_sample_rate(const FLAC__StreamEncoder *encoder)
  100288. {
  100289. FLAC__ASSERT(0 != encoder);
  100290. FLAC__ASSERT(0 != encoder->private_);
  100291. FLAC__ASSERT(0 != encoder->protected_);
  100292. return encoder->protected_->sample_rate;
  100293. }
  100294. FLAC_API unsigned FLAC__stream_encoder_get_blocksize(const FLAC__StreamEncoder *encoder)
  100295. {
  100296. FLAC__ASSERT(0 != encoder);
  100297. FLAC__ASSERT(0 != encoder->private_);
  100298. FLAC__ASSERT(0 != encoder->protected_);
  100299. return encoder->protected_->blocksize;
  100300. }
  100301. FLAC_API FLAC__bool FLAC__stream_encoder_get_do_mid_side_stereo(const FLAC__StreamEncoder *encoder)
  100302. {
  100303. FLAC__ASSERT(0 != encoder);
  100304. FLAC__ASSERT(0 != encoder->private_);
  100305. FLAC__ASSERT(0 != encoder->protected_);
  100306. return encoder->protected_->do_mid_side_stereo;
  100307. }
  100308. FLAC_API FLAC__bool FLAC__stream_encoder_get_loose_mid_side_stereo(const FLAC__StreamEncoder *encoder)
  100309. {
  100310. FLAC__ASSERT(0 != encoder);
  100311. FLAC__ASSERT(0 != encoder->private_);
  100312. FLAC__ASSERT(0 != encoder->protected_);
  100313. return encoder->protected_->loose_mid_side_stereo;
  100314. }
  100315. FLAC_API unsigned FLAC__stream_encoder_get_max_lpc_order(const FLAC__StreamEncoder *encoder)
  100316. {
  100317. FLAC__ASSERT(0 != encoder);
  100318. FLAC__ASSERT(0 != encoder->private_);
  100319. FLAC__ASSERT(0 != encoder->protected_);
  100320. return encoder->protected_->max_lpc_order;
  100321. }
  100322. FLAC_API unsigned FLAC__stream_encoder_get_qlp_coeff_precision(const FLAC__StreamEncoder *encoder)
  100323. {
  100324. FLAC__ASSERT(0 != encoder);
  100325. FLAC__ASSERT(0 != encoder->private_);
  100326. FLAC__ASSERT(0 != encoder->protected_);
  100327. return encoder->protected_->qlp_coeff_precision;
  100328. }
  100329. FLAC_API FLAC__bool FLAC__stream_encoder_get_do_qlp_coeff_prec_search(const FLAC__StreamEncoder *encoder)
  100330. {
  100331. FLAC__ASSERT(0 != encoder);
  100332. FLAC__ASSERT(0 != encoder->private_);
  100333. FLAC__ASSERT(0 != encoder->protected_);
  100334. return encoder->protected_->do_qlp_coeff_prec_search;
  100335. }
  100336. FLAC_API FLAC__bool FLAC__stream_encoder_get_do_escape_coding(const FLAC__StreamEncoder *encoder)
  100337. {
  100338. FLAC__ASSERT(0 != encoder);
  100339. FLAC__ASSERT(0 != encoder->private_);
  100340. FLAC__ASSERT(0 != encoder->protected_);
  100341. return encoder->protected_->do_escape_coding;
  100342. }
  100343. FLAC_API FLAC__bool FLAC__stream_encoder_get_do_exhaustive_model_search(const FLAC__StreamEncoder *encoder)
  100344. {
  100345. FLAC__ASSERT(0 != encoder);
  100346. FLAC__ASSERT(0 != encoder->private_);
  100347. FLAC__ASSERT(0 != encoder->protected_);
  100348. return encoder->protected_->do_exhaustive_model_search;
  100349. }
  100350. FLAC_API unsigned FLAC__stream_encoder_get_min_residual_partition_order(const FLAC__StreamEncoder *encoder)
  100351. {
  100352. FLAC__ASSERT(0 != encoder);
  100353. FLAC__ASSERT(0 != encoder->private_);
  100354. FLAC__ASSERT(0 != encoder->protected_);
  100355. return encoder->protected_->min_residual_partition_order;
  100356. }
  100357. FLAC_API unsigned FLAC__stream_encoder_get_max_residual_partition_order(const FLAC__StreamEncoder *encoder)
  100358. {
  100359. FLAC__ASSERT(0 != encoder);
  100360. FLAC__ASSERT(0 != encoder->private_);
  100361. FLAC__ASSERT(0 != encoder->protected_);
  100362. return encoder->protected_->max_residual_partition_order;
  100363. }
  100364. FLAC_API unsigned FLAC__stream_encoder_get_rice_parameter_search_dist(const FLAC__StreamEncoder *encoder)
  100365. {
  100366. FLAC__ASSERT(0 != encoder);
  100367. FLAC__ASSERT(0 != encoder->private_);
  100368. FLAC__ASSERT(0 != encoder->protected_);
  100369. return encoder->protected_->rice_parameter_search_dist;
  100370. }
  100371. FLAC_API FLAC__uint64 FLAC__stream_encoder_get_total_samples_estimate(const FLAC__StreamEncoder *encoder)
  100372. {
  100373. FLAC__ASSERT(0 != encoder);
  100374. FLAC__ASSERT(0 != encoder->private_);
  100375. FLAC__ASSERT(0 != encoder->protected_);
  100376. return encoder->protected_->total_samples_estimate;
  100377. }
  100378. FLAC_API FLAC__bool FLAC__stream_encoder_process(FLAC__StreamEncoder *encoder, const FLAC__int32 * const buffer[], unsigned samples)
  100379. {
  100380. unsigned i, j = 0, channel;
  100381. const unsigned channels = encoder->protected_->channels, blocksize = encoder->protected_->blocksize;
  100382. FLAC__ASSERT(0 != encoder);
  100383. FLAC__ASSERT(0 != encoder->private_);
  100384. FLAC__ASSERT(0 != encoder->protected_);
  100385. FLAC__ASSERT(encoder->protected_->state == FLAC__STREAM_ENCODER_OK);
  100386. do {
  100387. const unsigned n = min(blocksize+OVERREAD_-encoder->private_->current_sample_number, samples-j);
  100388. if(encoder->protected_->verify)
  100389. append_to_verify_fifo_(&encoder->private_->verify.input_fifo, buffer, j, channels, n);
  100390. for(channel = 0; channel < channels; channel++)
  100391. memcpy(&encoder->private_->integer_signal[channel][encoder->private_->current_sample_number], &buffer[channel][j], sizeof(buffer[channel][0]) * n);
  100392. if(encoder->protected_->do_mid_side_stereo) {
  100393. FLAC__ASSERT(channels == 2);
  100394. /* "i <= blocksize" to overread 1 sample; see comment in OVERREAD_ decl */
  100395. for(i = encoder->private_->current_sample_number; i <= blocksize && j < samples; i++, j++) {
  100396. encoder->private_->integer_signal_mid_side[1][i] = buffer[0][j] - buffer[1][j];
  100397. 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' ! */
  100398. }
  100399. }
  100400. else
  100401. j += n;
  100402. encoder->private_->current_sample_number += n;
  100403. /* we only process if we have a full block + 1 extra sample; final block is always handled by FLAC__stream_encoder_finish() */
  100404. if(encoder->private_->current_sample_number > blocksize) {
  100405. FLAC__ASSERT(encoder->private_->current_sample_number == blocksize+OVERREAD_);
  100406. FLAC__ASSERT(OVERREAD_ == 1); /* assert we only overread 1 sample which simplifies the rest of the code below */
  100407. if(!process_frame_(encoder, /*is_fractional_block=*/false, /*is_last_block=*/false))
  100408. return false;
  100409. /* move unprocessed overread samples to beginnings of arrays */
  100410. for(channel = 0; channel < channels; channel++)
  100411. encoder->private_->integer_signal[channel][0] = encoder->private_->integer_signal[channel][blocksize];
  100412. if(encoder->protected_->do_mid_side_stereo) {
  100413. encoder->private_->integer_signal_mid_side[0][0] = encoder->private_->integer_signal_mid_side[0][blocksize];
  100414. encoder->private_->integer_signal_mid_side[1][0] = encoder->private_->integer_signal_mid_side[1][blocksize];
  100415. }
  100416. encoder->private_->current_sample_number = 1;
  100417. }
  100418. } while(j < samples);
  100419. return true;
  100420. }
  100421. FLAC_API FLAC__bool FLAC__stream_encoder_process_interleaved(FLAC__StreamEncoder *encoder, const FLAC__int32 buffer[], unsigned samples)
  100422. {
  100423. unsigned i, j, k, channel;
  100424. FLAC__int32 x, mid, side;
  100425. const unsigned channels = encoder->protected_->channels, blocksize = encoder->protected_->blocksize;
  100426. FLAC__ASSERT(0 != encoder);
  100427. FLAC__ASSERT(0 != encoder->private_);
  100428. FLAC__ASSERT(0 != encoder->protected_);
  100429. FLAC__ASSERT(encoder->protected_->state == FLAC__STREAM_ENCODER_OK);
  100430. j = k = 0;
  100431. /*
  100432. * we have several flavors of the same basic loop, optimized for
  100433. * different conditions:
  100434. */
  100435. if(encoder->protected_->do_mid_side_stereo && channels == 2) {
  100436. /*
  100437. * stereo coding: unroll channel loop
  100438. */
  100439. do {
  100440. if(encoder->protected_->verify)
  100441. append_to_verify_fifo_interleaved_(&encoder->private_->verify.input_fifo, buffer, j, channels, min(blocksize+OVERREAD_-encoder->private_->current_sample_number, samples-j));
  100442. /* "i <= blocksize" to overread 1 sample; see comment in OVERREAD_ decl */
  100443. for(i = encoder->private_->current_sample_number; i <= blocksize && j < samples; i++, j++) {
  100444. encoder->private_->integer_signal[0][i] = mid = side = buffer[k++];
  100445. x = buffer[k++];
  100446. encoder->private_->integer_signal[1][i] = x;
  100447. mid += x;
  100448. side -= x;
  100449. mid >>= 1; /* NOTE: not the same as 'mid = (left + right) / 2' ! */
  100450. encoder->private_->integer_signal_mid_side[1][i] = side;
  100451. encoder->private_->integer_signal_mid_side[0][i] = mid;
  100452. }
  100453. encoder->private_->current_sample_number = i;
  100454. /* we only process if we have a full block + 1 extra sample; final block is always handled by FLAC__stream_encoder_finish() */
  100455. if(i > blocksize) {
  100456. if(!process_frame_(encoder, /*is_fractional_block=*/false, /*is_last_block=*/false))
  100457. return false;
  100458. /* move unprocessed overread samples to beginnings of arrays */
  100459. FLAC__ASSERT(i == blocksize+OVERREAD_);
  100460. FLAC__ASSERT(OVERREAD_ == 1); /* assert we only overread 1 sample which simplifies the rest of the code below */
  100461. encoder->private_->integer_signal[0][0] = encoder->private_->integer_signal[0][blocksize];
  100462. encoder->private_->integer_signal[1][0] = encoder->private_->integer_signal[1][blocksize];
  100463. encoder->private_->integer_signal_mid_side[0][0] = encoder->private_->integer_signal_mid_side[0][blocksize];
  100464. encoder->private_->integer_signal_mid_side[1][0] = encoder->private_->integer_signal_mid_side[1][blocksize];
  100465. encoder->private_->current_sample_number = 1;
  100466. }
  100467. } while(j < samples);
  100468. }
  100469. else {
  100470. /*
  100471. * independent channel coding: buffer each channel in inner loop
  100472. */
  100473. do {
  100474. if(encoder->protected_->verify)
  100475. append_to_verify_fifo_interleaved_(&encoder->private_->verify.input_fifo, buffer, j, channels, min(blocksize+OVERREAD_-encoder->private_->current_sample_number, samples-j));
  100476. /* "i <= blocksize" to overread 1 sample; see comment in OVERREAD_ decl */
  100477. for(i = encoder->private_->current_sample_number; i <= blocksize && j < samples; i++, j++) {
  100478. for(channel = 0; channel < channels; channel++)
  100479. encoder->private_->integer_signal[channel][i] = buffer[k++];
  100480. }
  100481. encoder->private_->current_sample_number = i;
  100482. /* we only process if we have a full block + 1 extra sample; final block is always handled by FLAC__stream_encoder_finish() */
  100483. if(i > blocksize) {
  100484. if(!process_frame_(encoder, /*is_fractional_block=*/false, /*is_last_block=*/false))
  100485. return false;
  100486. /* move unprocessed overread samples to beginnings of arrays */
  100487. FLAC__ASSERT(i == blocksize+OVERREAD_);
  100488. FLAC__ASSERT(OVERREAD_ == 1); /* assert we only overread 1 sample which simplifies the rest of the code below */
  100489. for(channel = 0; channel < channels; channel++)
  100490. encoder->private_->integer_signal[channel][0] = encoder->private_->integer_signal[channel][blocksize];
  100491. encoder->private_->current_sample_number = 1;
  100492. }
  100493. } while(j < samples);
  100494. }
  100495. return true;
  100496. }
  100497. /***********************************************************************
  100498. *
  100499. * Private class methods
  100500. *
  100501. ***********************************************************************/
  100502. void set_defaults_enc(FLAC__StreamEncoder *encoder)
  100503. {
  100504. FLAC__ASSERT(0 != encoder);
  100505. #ifdef FLAC__MANDATORY_VERIFY_WHILE_ENCODING
  100506. encoder->protected_->verify = true;
  100507. #else
  100508. encoder->protected_->verify = false;
  100509. #endif
  100510. encoder->protected_->streamable_subset = true;
  100511. encoder->protected_->do_md5 = true;
  100512. encoder->protected_->do_mid_side_stereo = false;
  100513. encoder->protected_->loose_mid_side_stereo = false;
  100514. encoder->protected_->channels = 2;
  100515. encoder->protected_->bits_per_sample = 16;
  100516. encoder->protected_->sample_rate = 44100;
  100517. encoder->protected_->blocksize = 0;
  100518. #ifndef FLAC__INTEGER_ONLY_LIBRARY
  100519. encoder->protected_->num_apodizations = 1;
  100520. encoder->protected_->apodizations[0].type = FLAC__APODIZATION_TUKEY;
  100521. encoder->protected_->apodizations[0].parameters.tukey.p = 0.5;
  100522. #endif
  100523. encoder->protected_->max_lpc_order = 0;
  100524. encoder->protected_->qlp_coeff_precision = 0;
  100525. encoder->protected_->do_qlp_coeff_prec_search = false;
  100526. encoder->protected_->do_exhaustive_model_search = false;
  100527. encoder->protected_->do_escape_coding = false;
  100528. encoder->protected_->min_residual_partition_order = 0;
  100529. encoder->protected_->max_residual_partition_order = 0;
  100530. encoder->protected_->rice_parameter_search_dist = 0;
  100531. encoder->protected_->total_samples_estimate = 0;
  100532. encoder->protected_->metadata = 0;
  100533. encoder->protected_->num_metadata_blocks = 0;
  100534. encoder->private_->seek_table = 0;
  100535. encoder->private_->disable_constant_subframes = false;
  100536. encoder->private_->disable_fixed_subframes = false;
  100537. encoder->private_->disable_verbatim_subframes = false;
  100538. #if FLAC__HAS_OGG
  100539. encoder->private_->is_ogg = false;
  100540. #endif
  100541. encoder->private_->read_callback = 0;
  100542. encoder->private_->write_callback = 0;
  100543. encoder->private_->seek_callback = 0;
  100544. encoder->private_->tell_callback = 0;
  100545. encoder->private_->metadata_callback = 0;
  100546. encoder->private_->progress_callback = 0;
  100547. encoder->private_->client_data = 0;
  100548. #if FLAC__HAS_OGG
  100549. FLAC__ogg_encoder_aspect_set_defaults(&encoder->protected_->ogg_encoder_aspect);
  100550. #endif
  100551. }
  100552. void free_(FLAC__StreamEncoder *encoder)
  100553. {
  100554. unsigned i, channel;
  100555. FLAC__ASSERT(0 != encoder);
  100556. if(encoder->protected_->metadata) {
  100557. free(encoder->protected_->metadata);
  100558. encoder->protected_->metadata = 0;
  100559. encoder->protected_->num_metadata_blocks = 0;
  100560. }
  100561. for(i = 0; i < encoder->protected_->channels; i++) {
  100562. if(0 != encoder->private_->integer_signal_unaligned[i]) {
  100563. free(encoder->private_->integer_signal_unaligned[i]);
  100564. encoder->private_->integer_signal_unaligned[i] = 0;
  100565. }
  100566. #ifndef FLAC__INTEGER_ONLY_LIBRARY
  100567. if(0 != encoder->private_->real_signal_unaligned[i]) {
  100568. free(encoder->private_->real_signal_unaligned[i]);
  100569. encoder->private_->real_signal_unaligned[i] = 0;
  100570. }
  100571. #endif
  100572. }
  100573. for(i = 0; i < 2; i++) {
  100574. if(0 != encoder->private_->integer_signal_mid_side_unaligned[i]) {
  100575. free(encoder->private_->integer_signal_mid_side_unaligned[i]);
  100576. encoder->private_->integer_signal_mid_side_unaligned[i] = 0;
  100577. }
  100578. #ifndef FLAC__INTEGER_ONLY_LIBRARY
  100579. if(0 != encoder->private_->real_signal_mid_side_unaligned[i]) {
  100580. free(encoder->private_->real_signal_mid_side_unaligned[i]);
  100581. encoder->private_->real_signal_mid_side_unaligned[i] = 0;
  100582. }
  100583. #endif
  100584. }
  100585. #ifndef FLAC__INTEGER_ONLY_LIBRARY
  100586. for(i = 0; i < encoder->protected_->num_apodizations; i++) {
  100587. if(0 != encoder->private_->window_unaligned[i]) {
  100588. free(encoder->private_->window_unaligned[i]);
  100589. encoder->private_->window_unaligned[i] = 0;
  100590. }
  100591. }
  100592. if(0 != encoder->private_->windowed_signal_unaligned) {
  100593. free(encoder->private_->windowed_signal_unaligned);
  100594. encoder->private_->windowed_signal_unaligned = 0;
  100595. }
  100596. #endif
  100597. for(channel = 0; channel < encoder->protected_->channels; channel++) {
  100598. for(i = 0; i < 2; i++) {
  100599. if(0 != encoder->private_->residual_workspace_unaligned[channel][i]) {
  100600. free(encoder->private_->residual_workspace_unaligned[channel][i]);
  100601. encoder->private_->residual_workspace_unaligned[channel][i] = 0;
  100602. }
  100603. }
  100604. }
  100605. for(channel = 0; channel < 2; channel++) {
  100606. for(i = 0; i < 2; i++) {
  100607. if(0 != encoder->private_->residual_workspace_mid_side_unaligned[channel][i]) {
  100608. free(encoder->private_->residual_workspace_mid_side_unaligned[channel][i]);
  100609. encoder->private_->residual_workspace_mid_side_unaligned[channel][i] = 0;
  100610. }
  100611. }
  100612. }
  100613. if(0 != encoder->private_->abs_residual_partition_sums_unaligned) {
  100614. free(encoder->private_->abs_residual_partition_sums_unaligned);
  100615. encoder->private_->abs_residual_partition_sums_unaligned = 0;
  100616. }
  100617. if(0 != encoder->private_->raw_bits_per_partition_unaligned) {
  100618. free(encoder->private_->raw_bits_per_partition_unaligned);
  100619. encoder->private_->raw_bits_per_partition_unaligned = 0;
  100620. }
  100621. if(encoder->protected_->verify) {
  100622. for(i = 0; i < encoder->protected_->channels; i++) {
  100623. if(0 != encoder->private_->verify.input_fifo.data[i]) {
  100624. free(encoder->private_->verify.input_fifo.data[i]);
  100625. encoder->private_->verify.input_fifo.data[i] = 0;
  100626. }
  100627. }
  100628. }
  100629. FLAC__bitwriter_free(encoder->private_->frame);
  100630. }
  100631. FLAC__bool resize_buffers_(FLAC__StreamEncoder *encoder, unsigned new_blocksize)
  100632. {
  100633. FLAC__bool ok;
  100634. unsigned i, channel;
  100635. FLAC__ASSERT(new_blocksize > 0);
  100636. FLAC__ASSERT(encoder->protected_->state == FLAC__STREAM_ENCODER_OK);
  100637. FLAC__ASSERT(encoder->private_->current_sample_number == 0);
  100638. /* To avoid excessive malloc'ing, we only grow the buffer; no shrinking. */
  100639. if(new_blocksize <= encoder->private_->input_capacity)
  100640. return true;
  100641. ok = true;
  100642. /* WATCHOUT: FLAC__lpc_compute_residual_from_qlp_coefficients_asm_ia32_mmx()
  100643. * requires that the input arrays (in our case the integer signals)
  100644. * have a buffer of up to 3 zeroes in front (at negative indices) for
  100645. * alignment purposes; we use 4 in front to keep the data well-aligned.
  100646. */
  100647. for(i = 0; ok && i < encoder->protected_->channels; i++) {
  100648. ok = ok && FLAC__memory_alloc_aligned_int32_array(new_blocksize+4+OVERREAD_, &encoder->private_->integer_signal_unaligned[i], &encoder->private_->integer_signal[i]);
  100649. memset(encoder->private_->integer_signal[i], 0, sizeof(FLAC__int32)*4);
  100650. encoder->private_->integer_signal[i] += 4;
  100651. #ifndef FLAC__INTEGER_ONLY_LIBRARY
  100652. #if 0 /* @@@ currently unused */
  100653. if(encoder->protected_->max_lpc_order > 0)
  100654. ok = ok && FLAC__memory_alloc_aligned_real_array(new_blocksize+OVERREAD_, &encoder->private_->real_signal_unaligned[i], &encoder->private_->real_signal[i]);
  100655. #endif
  100656. #endif
  100657. }
  100658. for(i = 0; ok && i < 2; i++) {
  100659. 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]);
  100660. memset(encoder->private_->integer_signal_mid_side[i], 0, sizeof(FLAC__int32)*4);
  100661. encoder->private_->integer_signal_mid_side[i] += 4;
  100662. #ifndef FLAC__INTEGER_ONLY_LIBRARY
  100663. #if 0 /* @@@ currently unused */
  100664. if(encoder->protected_->max_lpc_order > 0)
  100665. 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]);
  100666. #endif
  100667. #endif
  100668. }
  100669. #ifndef FLAC__INTEGER_ONLY_LIBRARY
  100670. if(ok && encoder->protected_->max_lpc_order > 0) {
  100671. for(i = 0; ok && i < encoder->protected_->num_apodizations; i++)
  100672. ok = ok && FLAC__memory_alloc_aligned_real_array(new_blocksize, &encoder->private_->window_unaligned[i], &encoder->private_->window[i]);
  100673. ok = ok && FLAC__memory_alloc_aligned_real_array(new_blocksize, &encoder->private_->windowed_signal_unaligned, &encoder->private_->windowed_signal);
  100674. }
  100675. #endif
  100676. for(channel = 0; ok && channel < encoder->protected_->channels; channel++) {
  100677. for(i = 0; ok && i < 2; i++) {
  100678. ok = ok && FLAC__memory_alloc_aligned_int32_array(new_blocksize, &encoder->private_->residual_workspace_unaligned[channel][i], &encoder->private_->residual_workspace[channel][i]);
  100679. }
  100680. }
  100681. for(channel = 0; ok && channel < 2; channel++) {
  100682. for(i = 0; ok && i < 2; i++) {
  100683. 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]);
  100684. }
  100685. }
  100686. /* the *2 is an approximation to the series 1 + 1/2 + 1/4 + ... that sums tree occupies in a flat array */
  100687. /*@@@ 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) */
  100688. ok = ok && FLAC__memory_alloc_aligned_uint64_array(new_blocksize * 2, &encoder->private_->abs_residual_partition_sums_unaligned, &encoder->private_->abs_residual_partition_sums);
  100689. if(encoder->protected_->do_escape_coding)
  100690. ok = ok && FLAC__memory_alloc_aligned_unsigned_array(new_blocksize * 2, &encoder->private_->raw_bits_per_partition_unaligned, &encoder->private_->raw_bits_per_partition);
  100691. /* now adjust the windows if the blocksize has changed */
  100692. #ifndef FLAC__INTEGER_ONLY_LIBRARY
  100693. if(ok && new_blocksize != encoder->private_->input_capacity && encoder->protected_->max_lpc_order > 0) {
  100694. for(i = 0; ok && i < encoder->protected_->num_apodizations; i++) {
  100695. switch(encoder->protected_->apodizations[i].type) {
  100696. case FLAC__APODIZATION_BARTLETT:
  100697. FLAC__window_bartlett(encoder->private_->window[i], new_blocksize);
  100698. break;
  100699. case FLAC__APODIZATION_BARTLETT_HANN:
  100700. FLAC__window_bartlett_hann(encoder->private_->window[i], new_blocksize);
  100701. break;
  100702. case FLAC__APODIZATION_BLACKMAN:
  100703. FLAC__window_blackman(encoder->private_->window[i], new_blocksize);
  100704. break;
  100705. case FLAC__APODIZATION_BLACKMAN_HARRIS_4TERM_92DB_SIDELOBE:
  100706. FLAC__window_blackman_harris_4term_92db_sidelobe(encoder->private_->window[i], new_blocksize);
  100707. break;
  100708. case FLAC__APODIZATION_CONNES:
  100709. FLAC__window_connes(encoder->private_->window[i], new_blocksize);
  100710. break;
  100711. case FLAC__APODIZATION_FLATTOP:
  100712. FLAC__window_flattop(encoder->private_->window[i], new_blocksize);
  100713. break;
  100714. case FLAC__APODIZATION_GAUSS:
  100715. FLAC__window_gauss(encoder->private_->window[i], new_blocksize, encoder->protected_->apodizations[i].parameters.gauss.stddev);
  100716. break;
  100717. case FLAC__APODIZATION_HAMMING:
  100718. FLAC__window_hamming(encoder->private_->window[i], new_blocksize);
  100719. break;
  100720. case FLAC__APODIZATION_HANN:
  100721. FLAC__window_hann(encoder->private_->window[i], new_blocksize);
  100722. break;
  100723. case FLAC__APODIZATION_KAISER_BESSEL:
  100724. FLAC__window_kaiser_bessel(encoder->private_->window[i], new_blocksize);
  100725. break;
  100726. case FLAC__APODIZATION_NUTTALL:
  100727. FLAC__window_nuttall(encoder->private_->window[i], new_blocksize);
  100728. break;
  100729. case FLAC__APODIZATION_RECTANGLE:
  100730. FLAC__window_rectangle(encoder->private_->window[i], new_blocksize);
  100731. break;
  100732. case FLAC__APODIZATION_TRIANGLE:
  100733. FLAC__window_triangle(encoder->private_->window[i], new_blocksize);
  100734. break;
  100735. case FLAC__APODIZATION_TUKEY:
  100736. FLAC__window_tukey(encoder->private_->window[i], new_blocksize, encoder->protected_->apodizations[i].parameters.tukey.p);
  100737. break;
  100738. case FLAC__APODIZATION_WELCH:
  100739. FLAC__window_welch(encoder->private_->window[i], new_blocksize);
  100740. break;
  100741. default:
  100742. FLAC__ASSERT(0);
  100743. /* double protection */
  100744. FLAC__window_hann(encoder->private_->window[i], new_blocksize);
  100745. break;
  100746. }
  100747. }
  100748. }
  100749. #endif
  100750. if(ok)
  100751. encoder->private_->input_capacity = new_blocksize;
  100752. else
  100753. encoder->protected_->state = FLAC__STREAM_ENCODER_MEMORY_ALLOCATION_ERROR;
  100754. return ok;
  100755. }
  100756. FLAC__bool write_bitbuffer_(FLAC__StreamEncoder *encoder, unsigned samples, FLAC__bool is_last_block)
  100757. {
  100758. const FLAC__byte *buffer;
  100759. size_t bytes;
  100760. FLAC__ASSERT(FLAC__bitwriter_is_byte_aligned(encoder->private_->frame));
  100761. if(!FLAC__bitwriter_get_buffer(encoder->private_->frame, &buffer, &bytes)) {
  100762. encoder->protected_->state = FLAC__STREAM_ENCODER_MEMORY_ALLOCATION_ERROR;
  100763. return false;
  100764. }
  100765. if(encoder->protected_->verify) {
  100766. encoder->private_->verify.output.data = buffer;
  100767. encoder->private_->verify.output.bytes = bytes;
  100768. if(encoder->private_->verify.state_hint == ENCODER_IN_MAGIC) {
  100769. encoder->private_->verify.needs_magic_hack = true;
  100770. }
  100771. else {
  100772. if(!FLAC__stream_decoder_process_single(encoder->private_->verify.decoder)) {
  100773. FLAC__bitwriter_release_buffer(encoder->private_->frame);
  100774. FLAC__bitwriter_clear(encoder->private_->frame);
  100775. if(encoder->protected_->state != FLAC__STREAM_ENCODER_VERIFY_MISMATCH_IN_AUDIO_DATA)
  100776. encoder->protected_->state = FLAC__STREAM_ENCODER_VERIFY_DECODER_ERROR;
  100777. return false;
  100778. }
  100779. }
  100780. }
  100781. if(write_frame_(encoder, buffer, bytes, samples, is_last_block) != FLAC__STREAM_ENCODER_WRITE_STATUS_OK) {
  100782. FLAC__bitwriter_release_buffer(encoder->private_->frame);
  100783. FLAC__bitwriter_clear(encoder->private_->frame);
  100784. encoder->protected_->state = FLAC__STREAM_ENCODER_CLIENT_ERROR;
  100785. return false;
  100786. }
  100787. FLAC__bitwriter_release_buffer(encoder->private_->frame);
  100788. FLAC__bitwriter_clear(encoder->private_->frame);
  100789. if(samples > 0) {
  100790. encoder->private_->streaminfo.data.stream_info.min_framesize = min(bytes, encoder->private_->streaminfo.data.stream_info.min_framesize);
  100791. encoder->private_->streaminfo.data.stream_info.max_framesize = max(bytes, encoder->private_->streaminfo.data.stream_info.max_framesize);
  100792. }
  100793. return true;
  100794. }
  100795. FLAC__StreamEncoderWriteStatus write_frame_(FLAC__StreamEncoder *encoder, const FLAC__byte buffer[], size_t bytes, unsigned samples, FLAC__bool is_last_block)
  100796. {
  100797. FLAC__StreamEncoderWriteStatus status;
  100798. FLAC__uint64 output_position = 0;
  100799. /* FLAC__STREAM_ENCODER_TELL_STATUS_UNSUPPORTED just means we didn't get the offset; no error */
  100800. if(encoder->private_->tell_callback && encoder->private_->tell_callback(encoder, &output_position, encoder->private_->client_data) == FLAC__STREAM_ENCODER_TELL_STATUS_ERROR) {
  100801. encoder->protected_->state = FLAC__STREAM_ENCODER_CLIENT_ERROR;
  100802. return FLAC__STREAM_ENCODER_WRITE_STATUS_FATAL_ERROR;
  100803. }
  100804. /*
  100805. * Watch for the STREAMINFO block and first SEEKTABLE block to go by and store their offsets.
  100806. */
  100807. if(samples == 0) {
  100808. FLAC__MetadataType type = (FLAC__MetadataType) (buffer[0] & 0x7f);
  100809. if(type == FLAC__METADATA_TYPE_STREAMINFO)
  100810. encoder->protected_->streaminfo_offset = output_position;
  100811. else if(type == FLAC__METADATA_TYPE_SEEKTABLE && encoder->protected_->seektable_offset == 0)
  100812. encoder->protected_->seektable_offset = output_position;
  100813. }
  100814. /*
  100815. * Mark the current seek point if hit (if audio_offset == 0 that
  100816. * means we're still writing metadata and haven't hit the first
  100817. * frame yet)
  100818. */
  100819. if(0 != encoder->private_->seek_table && encoder->protected_->audio_offset > 0 && encoder->private_->seek_table->num_points > 0) {
  100820. const unsigned blocksize = FLAC__stream_encoder_get_blocksize(encoder);
  100821. const FLAC__uint64 frame_first_sample = encoder->private_->samples_written;
  100822. const FLAC__uint64 frame_last_sample = frame_first_sample + (FLAC__uint64)blocksize - 1;
  100823. FLAC__uint64 test_sample;
  100824. unsigned i;
  100825. for(i = encoder->private_->first_seekpoint_to_check; i < encoder->private_->seek_table->num_points; i++) {
  100826. test_sample = encoder->private_->seek_table->points[i].sample_number;
  100827. if(test_sample > frame_last_sample) {
  100828. break;
  100829. }
  100830. else if(test_sample >= frame_first_sample) {
  100831. encoder->private_->seek_table->points[i].sample_number = frame_first_sample;
  100832. encoder->private_->seek_table->points[i].stream_offset = output_position - encoder->protected_->audio_offset;
  100833. encoder->private_->seek_table->points[i].frame_samples = blocksize;
  100834. encoder->private_->first_seekpoint_to_check++;
  100835. /* DO NOT: "break;" and here's why:
  100836. * The seektable template may contain more than one target
  100837. * sample for any given frame; we will keep looping, generating
  100838. * duplicate seekpoints for them, and we'll clean it up later,
  100839. * just before writing the seektable back to the metadata.
  100840. */
  100841. }
  100842. else {
  100843. encoder->private_->first_seekpoint_to_check++;
  100844. }
  100845. }
  100846. }
  100847. #if FLAC__HAS_OGG
  100848. if(encoder->private_->is_ogg) {
  100849. status = FLAC__ogg_encoder_aspect_write_callback_wrapper(
  100850. &encoder->protected_->ogg_encoder_aspect,
  100851. buffer,
  100852. bytes,
  100853. samples,
  100854. encoder->private_->current_frame_number,
  100855. is_last_block,
  100856. (FLAC__OggEncoderAspectWriteCallbackProxy)encoder->private_->write_callback,
  100857. encoder,
  100858. encoder->private_->client_data
  100859. );
  100860. }
  100861. else
  100862. #endif
  100863. status = encoder->private_->write_callback(encoder, buffer, bytes, samples, encoder->private_->current_frame_number, encoder->private_->client_data);
  100864. if(status == FLAC__STREAM_ENCODER_WRITE_STATUS_OK) {
  100865. encoder->private_->bytes_written += bytes;
  100866. encoder->private_->samples_written += samples;
  100867. /* we keep a high watermark on the number of frames written because
  100868. * when the encoder goes back to write metadata, 'current_frame'
  100869. * will drop back to 0.
  100870. */
  100871. encoder->private_->frames_written = max(encoder->private_->frames_written, encoder->private_->current_frame_number+1);
  100872. }
  100873. else
  100874. encoder->protected_->state = FLAC__STREAM_ENCODER_CLIENT_ERROR;
  100875. return status;
  100876. }
  100877. /* Gets called when the encoding process has finished so that we can update the STREAMINFO and SEEKTABLE blocks. */
  100878. void update_metadata_(const FLAC__StreamEncoder *encoder)
  100879. {
  100880. FLAC__byte b[max(6, FLAC__STREAM_METADATA_SEEKPOINT_LENGTH)];
  100881. const FLAC__StreamMetadata *metadata = &encoder->private_->streaminfo;
  100882. const FLAC__uint64 samples = metadata->data.stream_info.total_samples;
  100883. const unsigned min_framesize = metadata->data.stream_info.min_framesize;
  100884. const unsigned max_framesize = metadata->data.stream_info.max_framesize;
  100885. const unsigned bps = metadata->data.stream_info.bits_per_sample;
  100886. FLAC__StreamEncoderSeekStatus seek_status;
  100887. FLAC__ASSERT(metadata->type == FLAC__METADATA_TYPE_STREAMINFO);
  100888. /* All this is based on intimate knowledge of the stream header
  100889. * layout, but a change to the header format that would break this
  100890. * would also break all streams encoded in the previous format.
  100891. */
  100892. /*
  100893. * Write MD5 signature
  100894. */
  100895. {
  100896. const unsigned md5_offset =
  100897. FLAC__STREAM_METADATA_HEADER_LENGTH +
  100898. (
  100899. FLAC__STREAM_METADATA_STREAMINFO_MIN_BLOCK_SIZE_LEN +
  100900. FLAC__STREAM_METADATA_STREAMINFO_MAX_BLOCK_SIZE_LEN +
  100901. FLAC__STREAM_METADATA_STREAMINFO_MIN_FRAME_SIZE_LEN +
  100902. FLAC__STREAM_METADATA_STREAMINFO_MAX_FRAME_SIZE_LEN +
  100903. FLAC__STREAM_METADATA_STREAMINFO_SAMPLE_RATE_LEN +
  100904. FLAC__STREAM_METADATA_STREAMINFO_CHANNELS_LEN +
  100905. FLAC__STREAM_METADATA_STREAMINFO_BITS_PER_SAMPLE_LEN +
  100906. FLAC__STREAM_METADATA_STREAMINFO_TOTAL_SAMPLES_LEN
  100907. ) / 8;
  100908. if((seek_status = encoder->private_->seek_callback(encoder, encoder->protected_->streaminfo_offset + md5_offset, encoder->private_->client_data)) != FLAC__STREAM_ENCODER_SEEK_STATUS_OK) {
  100909. if(seek_status == FLAC__STREAM_ENCODER_SEEK_STATUS_ERROR)
  100910. encoder->protected_->state = FLAC__STREAM_ENCODER_CLIENT_ERROR;
  100911. return;
  100912. }
  100913. if(encoder->private_->write_callback(encoder, metadata->data.stream_info.md5sum, 16, 0, 0, encoder->private_->client_data) != FLAC__STREAM_ENCODER_WRITE_STATUS_OK) {
  100914. encoder->protected_->state = FLAC__STREAM_ENCODER_CLIENT_ERROR;
  100915. return;
  100916. }
  100917. }
  100918. /*
  100919. * Write total samples
  100920. */
  100921. {
  100922. const unsigned total_samples_byte_offset =
  100923. FLAC__STREAM_METADATA_HEADER_LENGTH +
  100924. (
  100925. FLAC__STREAM_METADATA_STREAMINFO_MIN_BLOCK_SIZE_LEN +
  100926. FLAC__STREAM_METADATA_STREAMINFO_MAX_BLOCK_SIZE_LEN +
  100927. FLAC__STREAM_METADATA_STREAMINFO_MIN_FRAME_SIZE_LEN +
  100928. FLAC__STREAM_METADATA_STREAMINFO_MAX_FRAME_SIZE_LEN +
  100929. FLAC__STREAM_METADATA_STREAMINFO_SAMPLE_RATE_LEN +
  100930. FLAC__STREAM_METADATA_STREAMINFO_CHANNELS_LEN +
  100931. FLAC__STREAM_METADATA_STREAMINFO_BITS_PER_SAMPLE_LEN
  100932. - 4
  100933. ) / 8;
  100934. b[0] = ((FLAC__byte)(bps-1) << 4) | (FLAC__byte)((samples >> 32) & 0x0F);
  100935. b[1] = (FLAC__byte)((samples >> 24) & 0xFF);
  100936. b[2] = (FLAC__byte)((samples >> 16) & 0xFF);
  100937. b[3] = (FLAC__byte)((samples >> 8) & 0xFF);
  100938. b[4] = (FLAC__byte)(samples & 0xFF);
  100939. 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) {
  100940. if(seek_status == FLAC__STREAM_ENCODER_SEEK_STATUS_ERROR)
  100941. encoder->protected_->state = FLAC__STREAM_ENCODER_CLIENT_ERROR;
  100942. return;
  100943. }
  100944. if(encoder->private_->write_callback(encoder, b, 5, 0, 0, encoder->private_->client_data) != FLAC__STREAM_ENCODER_WRITE_STATUS_OK) {
  100945. encoder->protected_->state = FLAC__STREAM_ENCODER_CLIENT_ERROR;
  100946. return;
  100947. }
  100948. }
  100949. /*
  100950. * Write min/max framesize
  100951. */
  100952. {
  100953. const unsigned min_framesize_offset =
  100954. FLAC__STREAM_METADATA_HEADER_LENGTH +
  100955. (
  100956. FLAC__STREAM_METADATA_STREAMINFO_MIN_BLOCK_SIZE_LEN +
  100957. FLAC__STREAM_METADATA_STREAMINFO_MAX_BLOCK_SIZE_LEN
  100958. ) / 8;
  100959. b[0] = (FLAC__byte)((min_framesize >> 16) & 0xFF);
  100960. b[1] = (FLAC__byte)((min_framesize >> 8) & 0xFF);
  100961. b[2] = (FLAC__byte)(min_framesize & 0xFF);
  100962. b[3] = (FLAC__byte)((max_framesize >> 16) & 0xFF);
  100963. b[4] = (FLAC__byte)((max_framesize >> 8) & 0xFF);
  100964. b[5] = (FLAC__byte)(max_framesize & 0xFF);
  100965. 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) {
  100966. if(seek_status == FLAC__STREAM_ENCODER_SEEK_STATUS_ERROR)
  100967. encoder->protected_->state = FLAC__STREAM_ENCODER_CLIENT_ERROR;
  100968. return;
  100969. }
  100970. if(encoder->private_->write_callback(encoder, b, 6, 0, 0, encoder->private_->client_data) != FLAC__STREAM_ENCODER_WRITE_STATUS_OK) {
  100971. encoder->protected_->state = FLAC__STREAM_ENCODER_CLIENT_ERROR;
  100972. return;
  100973. }
  100974. }
  100975. /*
  100976. * Write seektable
  100977. */
  100978. if(0 != encoder->private_->seek_table && encoder->private_->seek_table->num_points > 0 && encoder->protected_->seektable_offset > 0) {
  100979. unsigned i;
  100980. FLAC__format_seektable_sort(encoder->private_->seek_table);
  100981. FLAC__ASSERT(FLAC__format_seektable_is_legal(encoder->private_->seek_table));
  100982. 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) {
  100983. if(seek_status == FLAC__STREAM_ENCODER_SEEK_STATUS_ERROR)
  100984. encoder->protected_->state = FLAC__STREAM_ENCODER_CLIENT_ERROR;
  100985. return;
  100986. }
  100987. for(i = 0; i < encoder->private_->seek_table->num_points; i++) {
  100988. FLAC__uint64 xx;
  100989. unsigned x;
  100990. xx = encoder->private_->seek_table->points[i].sample_number;
  100991. b[7] = (FLAC__byte)xx; xx >>= 8;
  100992. b[6] = (FLAC__byte)xx; xx >>= 8;
  100993. b[5] = (FLAC__byte)xx; xx >>= 8;
  100994. b[4] = (FLAC__byte)xx; xx >>= 8;
  100995. b[3] = (FLAC__byte)xx; xx >>= 8;
  100996. b[2] = (FLAC__byte)xx; xx >>= 8;
  100997. b[1] = (FLAC__byte)xx; xx >>= 8;
  100998. b[0] = (FLAC__byte)xx; xx >>= 8;
  100999. xx = encoder->private_->seek_table->points[i].stream_offset;
  101000. b[15] = (FLAC__byte)xx; xx >>= 8;
  101001. b[14] = (FLAC__byte)xx; xx >>= 8;
  101002. b[13] = (FLAC__byte)xx; xx >>= 8;
  101003. b[12] = (FLAC__byte)xx; xx >>= 8;
  101004. b[11] = (FLAC__byte)xx; xx >>= 8;
  101005. b[10] = (FLAC__byte)xx; xx >>= 8;
  101006. b[9] = (FLAC__byte)xx; xx >>= 8;
  101007. b[8] = (FLAC__byte)xx; xx >>= 8;
  101008. x = encoder->private_->seek_table->points[i].frame_samples;
  101009. b[17] = (FLAC__byte)x; x >>= 8;
  101010. b[16] = (FLAC__byte)x; x >>= 8;
  101011. if(encoder->private_->write_callback(encoder, b, 18, 0, 0, encoder->private_->client_data) != FLAC__STREAM_ENCODER_WRITE_STATUS_OK) {
  101012. encoder->protected_->state = FLAC__STREAM_ENCODER_CLIENT_ERROR;
  101013. return;
  101014. }
  101015. }
  101016. }
  101017. }
  101018. #if FLAC__HAS_OGG
  101019. /* Gets called when the encoding process has finished so that we can update the STREAMINFO and SEEKTABLE blocks. */
  101020. void update_ogg_metadata_(FLAC__StreamEncoder *encoder)
  101021. {
  101022. /* the # of bytes in the 1st packet that precede the STREAMINFO */
  101023. static const unsigned FIRST_OGG_PACKET_STREAMINFO_PREFIX_LENGTH =
  101024. FLAC__OGG_MAPPING_PACKET_TYPE_LENGTH +
  101025. FLAC__OGG_MAPPING_MAGIC_LENGTH +
  101026. FLAC__OGG_MAPPING_VERSION_MAJOR_LENGTH +
  101027. FLAC__OGG_MAPPING_VERSION_MINOR_LENGTH +
  101028. FLAC__OGG_MAPPING_NUM_HEADERS_LENGTH +
  101029. FLAC__STREAM_SYNC_LENGTH
  101030. ;
  101031. FLAC__byte b[max(6, FLAC__STREAM_METADATA_SEEKPOINT_LENGTH)];
  101032. const FLAC__StreamMetadata *metadata = &encoder->private_->streaminfo;
  101033. const FLAC__uint64 samples = metadata->data.stream_info.total_samples;
  101034. const unsigned min_framesize = metadata->data.stream_info.min_framesize;
  101035. const unsigned max_framesize = metadata->data.stream_info.max_framesize;
  101036. ogg_page page;
  101037. FLAC__ASSERT(metadata->type == FLAC__METADATA_TYPE_STREAMINFO);
  101038. FLAC__ASSERT(0 != encoder->private_->seek_callback);
  101039. /* Pre-check that client supports seeking, since we don't want the
  101040. * ogg_helper code to ever have to deal with this condition.
  101041. */
  101042. if(encoder->private_->seek_callback(encoder, 0, encoder->private_->client_data) == FLAC__STREAM_ENCODER_SEEK_STATUS_UNSUPPORTED)
  101043. return;
  101044. /* All this is based on intimate knowledge of the stream header
  101045. * layout, but a change to the header format that would break this
  101046. * would also break all streams encoded in the previous format.
  101047. */
  101048. /**
  101049. ** Write STREAMINFO stats
  101050. **/
  101051. simple_ogg_page__init(&page);
  101052. if(!simple_ogg_page__get_at(encoder, encoder->protected_->streaminfo_offset, &page, encoder->private_->seek_callback, encoder->private_->read_callback, encoder->private_->client_data)) {
  101053. simple_ogg_page__clear(&page);
  101054. return; /* state already set */
  101055. }
  101056. /*
  101057. * Write MD5 signature
  101058. */
  101059. {
  101060. const unsigned md5_offset =
  101061. FIRST_OGG_PACKET_STREAMINFO_PREFIX_LENGTH +
  101062. FLAC__STREAM_METADATA_HEADER_LENGTH +
  101063. (
  101064. FLAC__STREAM_METADATA_STREAMINFO_MIN_BLOCK_SIZE_LEN +
  101065. FLAC__STREAM_METADATA_STREAMINFO_MAX_BLOCK_SIZE_LEN +
  101066. FLAC__STREAM_METADATA_STREAMINFO_MIN_FRAME_SIZE_LEN +
  101067. FLAC__STREAM_METADATA_STREAMINFO_MAX_FRAME_SIZE_LEN +
  101068. FLAC__STREAM_METADATA_STREAMINFO_SAMPLE_RATE_LEN +
  101069. FLAC__STREAM_METADATA_STREAMINFO_CHANNELS_LEN +
  101070. FLAC__STREAM_METADATA_STREAMINFO_BITS_PER_SAMPLE_LEN +
  101071. FLAC__STREAM_METADATA_STREAMINFO_TOTAL_SAMPLES_LEN
  101072. ) / 8;
  101073. if(md5_offset + 16 > (unsigned)page.body_len) {
  101074. encoder->protected_->state = FLAC__STREAM_ENCODER_OGG_ERROR;
  101075. simple_ogg_page__clear(&page);
  101076. return;
  101077. }
  101078. memcpy(page.body + md5_offset, metadata->data.stream_info.md5sum, 16);
  101079. }
  101080. /*
  101081. * Write total samples
  101082. */
  101083. {
  101084. const unsigned total_samples_byte_offset =
  101085. FIRST_OGG_PACKET_STREAMINFO_PREFIX_LENGTH +
  101086. FLAC__STREAM_METADATA_HEADER_LENGTH +
  101087. (
  101088. FLAC__STREAM_METADATA_STREAMINFO_MIN_BLOCK_SIZE_LEN +
  101089. FLAC__STREAM_METADATA_STREAMINFO_MAX_BLOCK_SIZE_LEN +
  101090. FLAC__STREAM_METADATA_STREAMINFO_MIN_FRAME_SIZE_LEN +
  101091. FLAC__STREAM_METADATA_STREAMINFO_MAX_FRAME_SIZE_LEN +
  101092. FLAC__STREAM_METADATA_STREAMINFO_SAMPLE_RATE_LEN +
  101093. FLAC__STREAM_METADATA_STREAMINFO_CHANNELS_LEN +
  101094. FLAC__STREAM_METADATA_STREAMINFO_BITS_PER_SAMPLE_LEN
  101095. - 4
  101096. ) / 8;
  101097. if(total_samples_byte_offset + 5 > (unsigned)page.body_len) {
  101098. encoder->protected_->state = FLAC__STREAM_ENCODER_OGG_ERROR;
  101099. simple_ogg_page__clear(&page);
  101100. return;
  101101. }
  101102. b[0] = (FLAC__byte)page.body[total_samples_byte_offset] & 0xF0;
  101103. b[0] |= (FLAC__byte)((samples >> 32) & 0x0F);
  101104. b[1] = (FLAC__byte)((samples >> 24) & 0xFF);
  101105. b[2] = (FLAC__byte)((samples >> 16) & 0xFF);
  101106. b[3] = (FLAC__byte)((samples >> 8) & 0xFF);
  101107. b[4] = (FLAC__byte)(samples & 0xFF);
  101108. memcpy(page.body + total_samples_byte_offset, b, 5);
  101109. }
  101110. /*
  101111. * Write min/max framesize
  101112. */
  101113. {
  101114. const unsigned min_framesize_offset =
  101115. FIRST_OGG_PACKET_STREAMINFO_PREFIX_LENGTH +
  101116. FLAC__STREAM_METADATA_HEADER_LENGTH +
  101117. (
  101118. FLAC__STREAM_METADATA_STREAMINFO_MIN_BLOCK_SIZE_LEN +
  101119. FLAC__STREAM_METADATA_STREAMINFO_MAX_BLOCK_SIZE_LEN
  101120. ) / 8;
  101121. if(min_framesize_offset + 6 > (unsigned)page.body_len) {
  101122. encoder->protected_->state = FLAC__STREAM_ENCODER_OGG_ERROR;
  101123. simple_ogg_page__clear(&page);
  101124. return;
  101125. }
  101126. b[0] = (FLAC__byte)((min_framesize >> 16) & 0xFF);
  101127. b[1] = (FLAC__byte)((min_framesize >> 8) & 0xFF);
  101128. b[2] = (FLAC__byte)(min_framesize & 0xFF);
  101129. b[3] = (FLAC__byte)((max_framesize >> 16) & 0xFF);
  101130. b[4] = (FLAC__byte)((max_framesize >> 8) & 0xFF);
  101131. b[5] = (FLAC__byte)(max_framesize & 0xFF);
  101132. memcpy(page.body + min_framesize_offset, b, 6);
  101133. }
  101134. if(!simple_ogg_page__set_at(encoder, encoder->protected_->streaminfo_offset, &page, encoder->private_->seek_callback, encoder->private_->write_callback, encoder->private_->client_data)) {
  101135. simple_ogg_page__clear(&page);
  101136. return; /* state already set */
  101137. }
  101138. simple_ogg_page__clear(&page);
  101139. /*
  101140. * Write seektable
  101141. */
  101142. if(0 != encoder->private_->seek_table && encoder->private_->seek_table->num_points > 0 && encoder->protected_->seektable_offset > 0) {
  101143. unsigned i;
  101144. FLAC__byte *p;
  101145. FLAC__format_seektable_sort(encoder->private_->seek_table);
  101146. FLAC__ASSERT(FLAC__format_seektable_is_legal(encoder->private_->seek_table));
  101147. simple_ogg_page__init(&page);
  101148. if(!simple_ogg_page__get_at(encoder, encoder->protected_->seektable_offset, &page, encoder->private_->seek_callback, encoder->private_->read_callback, encoder->private_->client_data)) {
  101149. simple_ogg_page__clear(&page);
  101150. return; /* state already set */
  101151. }
  101152. if((FLAC__STREAM_METADATA_HEADER_LENGTH + 18*encoder->private_->seek_table->num_points) != (unsigned)page.body_len) {
  101153. encoder->protected_->state = FLAC__STREAM_ENCODER_OGG_ERROR;
  101154. simple_ogg_page__clear(&page);
  101155. return;
  101156. }
  101157. for(i = 0, p = page.body + FLAC__STREAM_METADATA_HEADER_LENGTH; i < encoder->private_->seek_table->num_points; i++, p += 18) {
  101158. FLAC__uint64 xx;
  101159. unsigned x;
  101160. xx = encoder->private_->seek_table->points[i].sample_number;
  101161. b[7] = (FLAC__byte)xx; xx >>= 8;
  101162. b[6] = (FLAC__byte)xx; xx >>= 8;
  101163. b[5] = (FLAC__byte)xx; xx >>= 8;
  101164. b[4] = (FLAC__byte)xx; xx >>= 8;
  101165. b[3] = (FLAC__byte)xx; xx >>= 8;
  101166. b[2] = (FLAC__byte)xx; xx >>= 8;
  101167. b[1] = (FLAC__byte)xx; xx >>= 8;
  101168. b[0] = (FLAC__byte)xx; xx >>= 8;
  101169. xx = encoder->private_->seek_table->points[i].stream_offset;
  101170. b[15] = (FLAC__byte)xx; xx >>= 8;
  101171. b[14] = (FLAC__byte)xx; xx >>= 8;
  101172. b[13] = (FLAC__byte)xx; xx >>= 8;
  101173. b[12] = (FLAC__byte)xx; xx >>= 8;
  101174. b[11] = (FLAC__byte)xx; xx >>= 8;
  101175. b[10] = (FLAC__byte)xx; xx >>= 8;
  101176. b[9] = (FLAC__byte)xx; xx >>= 8;
  101177. b[8] = (FLAC__byte)xx; xx >>= 8;
  101178. x = encoder->private_->seek_table->points[i].frame_samples;
  101179. b[17] = (FLAC__byte)x; x >>= 8;
  101180. b[16] = (FLAC__byte)x; x >>= 8;
  101181. memcpy(p, b, 18);
  101182. }
  101183. if(!simple_ogg_page__set_at(encoder, encoder->protected_->seektable_offset, &page, encoder->private_->seek_callback, encoder->private_->write_callback, encoder->private_->client_data)) {
  101184. simple_ogg_page__clear(&page);
  101185. return; /* state already set */
  101186. }
  101187. simple_ogg_page__clear(&page);
  101188. }
  101189. }
  101190. #endif
  101191. FLAC__bool process_frame_(FLAC__StreamEncoder *encoder, FLAC__bool is_fractional_block, FLAC__bool is_last_block)
  101192. {
  101193. FLAC__uint16 crc;
  101194. FLAC__ASSERT(encoder->protected_->state == FLAC__STREAM_ENCODER_OK);
  101195. /*
  101196. * Accumulate raw signal to the MD5 signature
  101197. */
  101198. 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)) {
  101199. encoder->protected_->state = FLAC__STREAM_ENCODER_MEMORY_ALLOCATION_ERROR;
  101200. return false;
  101201. }
  101202. /*
  101203. * Process the frame header and subframes into the frame bitbuffer
  101204. */
  101205. if(!process_subframes_(encoder, is_fractional_block)) {
  101206. /* the above function sets the state for us in case of an error */
  101207. return false;
  101208. }
  101209. /*
  101210. * Zero-pad the frame to a byte_boundary
  101211. */
  101212. if(!FLAC__bitwriter_zero_pad_to_byte_boundary(encoder->private_->frame)) {
  101213. encoder->protected_->state = FLAC__STREAM_ENCODER_MEMORY_ALLOCATION_ERROR;
  101214. return false;
  101215. }
  101216. /*
  101217. * CRC-16 the whole thing
  101218. */
  101219. FLAC__ASSERT(FLAC__bitwriter_is_byte_aligned(encoder->private_->frame));
  101220. if(
  101221. !FLAC__bitwriter_get_write_crc16(encoder->private_->frame, &crc) ||
  101222. !FLAC__bitwriter_write_raw_uint32(encoder->private_->frame, crc, FLAC__FRAME_FOOTER_CRC_LEN)
  101223. ) {
  101224. encoder->protected_->state = FLAC__STREAM_ENCODER_MEMORY_ALLOCATION_ERROR;
  101225. return false;
  101226. }
  101227. /*
  101228. * Write it
  101229. */
  101230. if(!write_bitbuffer_(encoder, encoder->protected_->blocksize, is_last_block)) {
  101231. /* the above function sets the state for us in case of an error */
  101232. return false;
  101233. }
  101234. /*
  101235. * Get ready for the next frame
  101236. */
  101237. encoder->private_->current_sample_number = 0;
  101238. encoder->private_->current_frame_number++;
  101239. encoder->private_->streaminfo.data.stream_info.total_samples += (FLAC__uint64)encoder->protected_->blocksize;
  101240. return true;
  101241. }
  101242. FLAC__bool process_subframes_(FLAC__StreamEncoder *encoder, FLAC__bool is_fractional_block)
  101243. {
  101244. FLAC__FrameHeader frame_header;
  101245. unsigned channel, min_partition_order = encoder->protected_->min_residual_partition_order, max_partition_order;
  101246. FLAC__bool do_independent, do_mid_side;
  101247. /*
  101248. * Calculate the min,max Rice partition orders
  101249. */
  101250. if(is_fractional_block) {
  101251. max_partition_order = 0;
  101252. }
  101253. else {
  101254. max_partition_order = FLAC__format_get_max_rice_partition_order_from_blocksize(encoder->protected_->blocksize);
  101255. max_partition_order = min(max_partition_order, encoder->protected_->max_residual_partition_order);
  101256. }
  101257. min_partition_order = min(min_partition_order, max_partition_order);
  101258. /*
  101259. * Setup the frame
  101260. */
  101261. frame_header.blocksize = encoder->protected_->blocksize;
  101262. frame_header.sample_rate = encoder->protected_->sample_rate;
  101263. frame_header.channels = encoder->protected_->channels;
  101264. frame_header.channel_assignment = FLAC__CHANNEL_ASSIGNMENT_INDEPENDENT; /* the default unless the encoder determines otherwise */
  101265. frame_header.bits_per_sample = encoder->protected_->bits_per_sample;
  101266. frame_header.number_type = FLAC__FRAME_NUMBER_TYPE_FRAME_NUMBER;
  101267. frame_header.number.frame_number = encoder->private_->current_frame_number;
  101268. /*
  101269. * Figure out what channel assignments to try
  101270. */
  101271. if(encoder->protected_->do_mid_side_stereo) {
  101272. if(encoder->protected_->loose_mid_side_stereo) {
  101273. if(encoder->private_->loose_mid_side_stereo_frame_count == 0) {
  101274. do_independent = true;
  101275. do_mid_side = true;
  101276. }
  101277. else {
  101278. do_independent = (encoder->private_->last_channel_assignment == FLAC__CHANNEL_ASSIGNMENT_INDEPENDENT);
  101279. do_mid_side = !do_independent;
  101280. }
  101281. }
  101282. else {
  101283. do_independent = true;
  101284. do_mid_side = true;
  101285. }
  101286. }
  101287. else {
  101288. do_independent = true;
  101289. do_mid_side = false;
  101290. }
  101291. FLAC__ASSERT(do_independent || do_mid_side);
  101292. /*
  101293. * Check for wasted bits; set effective bps for each subframe
  101294. */
  101295. if(do_independent) {
  101296. for(channel = 0; channel < encoder->protected_->channels; channel++) {
  101297. const unsigned w = get_wasted_bits_(encoder->private_->integer_signal[channel], encoder->protected_->blocksize);
  101298. encoder->private_->subframe_workspace[channel][0].wasted_bits = encoder->private_->subframe_workspace[channel][1].wasted_bits = w;
  101299. encoder->private_->subframe_bps[channel] = encoder->protected_->bits_per_sample - w;
  101300. }
  101301. }
  101302. if(do_mid_side) {
  101303. FLAC__ASSERT(encoder->protected_->channels == 2);
  101304. for(channel = 0; channel < 2; channel++) {
  101305. const unsigned w = get_wasted_bits_(encoder->private_->integer_signal_mid_side[channel], encoder->protected_->blocksize);
  101306. encoder->private_->subframe_workspace_mid_side[channel][0].wasted_bits = encoder->private_->subframe_workspace_mid_side[channel][1].wasted_bits = w;
  101307. encoder->private_->subframe_bps_mid_side[channel] = encoder->protected_->bits_per_sample - w + (channel==0? 0:1);
  101308. }
  101309. }
  101310. /*
  101311. * First do a normal encoding pass of each independent channel
  101312. */
  101313. if(do_independent) {
  101314. for(channel = 0; channel < encoder->protected_->channels; channel++) {
  101315. if(!
  101316. process_subframe_(
  101317. encoder,
  101318. min_partition_order,
  101319. max_partition_order,
  101320. &frame_header,
  101321. encoder->private_->subframe_bps[channel],
  101322. encoder->private_->integer_signal[channel],
  101323. encoder->private_->subframe_workspace_ptr[channel],
  101324. encoder->private_->partitioned_rice_contents_workspace_ptr[channel],
  101325. encoder->private_->residual_workspace[channel],
  101326. encoder->private_->best_subframe+channel,
  101327. encoder->private_->best_subframe_bits+channel
  101328. )
  101329. )
  101330. return false;
  101331. }
  101332. }
  101333. /*
  101334. * Now do mid and side channels if requested
  101335. */
  101336. if(do_mid_side) {
  101337. FLAC__ASSERT(encoder->protected_->channels == 2);
  101338. for(channel = 0; channel < 2; channel++) {
  101339. if(!
  101340. process_subframe_(
  101341. encoder,
  101342. min_partition_order,
  101343. max_partition_order,
  101344. &frame_header,
  101345. encoder->private_->subframe_bps_mid_side[channel],
  101346. encoder->private_->integer_signal_mid_side[channel],
  101347. encoder->private_->subframe_workspace_ptr_mid_side[channel],
  101348. encoder->private_->partitioned_rice_contents_workspace_ptr_mid_side[channel],
  101349. encoder->private_->residual_workspace_mid_side[channel],
  101350. encoder->private_->best_subframe_mid_side+channel,
  101351. encoder->private_->best_subframe_bits_mid_side+channel
  101352. )
  101353. )
  101354. return false;
  101355. }
  101356. }
  101357. /*
  101358. * Compose the frame bitbuffer
  101359. */
  101360. if(do_mid_side) {
  101361. unsigned left_bps = 0, right_bps = 0; /* initialized only to prevent superfluous compiler warning */
  101362. FLAC__Subframe *left_subframe = 0, *right_subframe = 0; /* initialized only to prevent superfluous compiler warning */
  101363. FLAC__ChannelAssignment channel_assignment;
  101364. FLAC__ASSERT(encoder->protected_->channels == 2);
  101365. if(encoder->protected_->loose_mid_side_stereo && encoder->private_->loose_mid_side_stereo_frame_count > 0) {
  101366. channel_assignment = (encoder->private_->last_channel_assignment == FLAC__CHANNEL_ASSIGNMENT_INDEPENDENT? FLAC__CHANNEL_ASSIGNMENT_INDEPENDENT : FLAC__CHANNEL_ASSIGNMENT_MID_SIDE);
  101367. }
  101368. else {
  101369. unsigned bits[4]; /* WATCHOUT - indexed by FLAC__ChannelAssignment */
  101370. unsigned min_bits;
  101371. int ca;
  101372. FLAC__ASSERT(FLAC__CHANNEL_ASSIGNMENT_INDEPENDENT == 0);
  101373. FLAC__ASSERT(FLAC__CHANNEL_ASSIGNMENT_LEFT_SIDE == 1);
  101374. FLAC__ASSERT(FLAC__CHANNEL_ASSIGNMENT_RIGHT_SIDE == 2);
  101375. FLAC__ASSERT(FLAC__CHANNEL_ASSIGNMENT_MID_SIDE == 3);
  101376. FLAC__ASSERT(do_independent && do_mid_side);
  101377. /* We have to figure out which channel assignent results in the smallest frame */
  101378. bits[FLAC__CHANNEL_ASSIGNMENT_INDEPENDENT] = encoder->private_->best_subframe_bits [0] + encoder->private_->best_subframe_bits [1];
  101379. bits[FLAC__CHANNEL_ASSIGNMENT_LEFT_SIDE ] = encoder->private_->best_subframe_bits [0] + encoder->private_->best_subframe_bits_mid_side[1];
  101380. bits[FLAC__CHANNEL_ASSIGNMENT_RIGHT_SIDE ] = encoder->private_->best_subframe_bits [1] + encoder->private_->best_subframe_bits_mid_side[1];
  101381. bits[FLAC__CHANNEL_ASSIGNMENT_MID_SIDE ] = encoder->private_->best_subframe_bits_mid_side[0] + encoder->private_->best_subframe_bits_mid_side[1];
  101382. channel_assignment = FLAC__CHANNEL_ASSIGNMENT_INDEPENDENT;
  101383. min_bits = bits[channel_assignment];
  101384. for(ca = 1; ca <= 3; ca++) {
  101385. if(bits[ca] < min_bits) {
  101386. min_bits = bits[ca];
  101387. channel_assignment = (FLAC__ChannelAssignment)ca;
  101388. }
  101389. }
  101390. }
  101391. frame_header.channel_assignment = channel_assignment;
  101392. if(!FLAC__frame_add_header(&frame_header, encoder->private_->frame)) {
  101393. encoder->protected_->state = FLAC__STREAM_ENCODER_FRAMING_ERROR;
  101394. return false;
  101395. }
  101396. switch(channel_assignment) {
  101397. case FLAC__CHANNEL_ASSIGNMENT_INDEPENDENT:
  101398. left_subframe = &encoder->private_->subframe_workspace [0][encoder->private_->best_subframe [0]];
  101399. right_subframe = &encoder->private_->subframe_workspace [1][encoder->private_->best_subframe [1]];
  101400. break;
  101401. case FLAC__CHANNEL_ASSIGNMENT_LEFT_SIDE:
  101402. left_subframe = &encoder->private_->subframe_workspace [0][encoder->private_->best_subframe [0]];
  101403. right_subframe = &encoder->private_->subframe_workspace_mid_side[1][encoder->private_->best_subframe_mid_side[1]];
  101404. break;
  101405. case FLAC__CHANNEL_ASSIGNMENT_RIGHT_SIDE:
  101406. left_subframe = &encoder->private_->subframe_workspace_mid_side[1][encoder->private_->best_subframe_mid_side[1]];
  101407. right_subframe = &encoder->private_->subframe_workspace [1][encoder->private_->best_subframe [1]];
  101408. break;
  101409. case FLAC__CHANNEL_ASSIGNMENT_MID_SIDE:
  101410. left_subframe = &encoder->private_->subframe_workspace_mid_side[0][encoder->private_->best_subframe_mid_side[0]];
  101411. right_subframe = &encoder->private_->subframe_workspace_mid_side[1][encoder->private_->best_subframe_mid_side[1]];
  101412. break;
  101413. default:
  101414. FLAC__ASSERT(0);
  101415. }
  101416. switch(channel_assignment) {
  101417. case FLAC__CHANNEL_ASSIGNMENT_INDEPENDENT:
  101418. left_bps = encoder->private_->subframe_bps [0];
  101419. right_bps = encoder->private_->subframe_bps [1];
  101420. break;
  101421. case FLAC__CHANNEL_ASSIGNMENT_LEFT_SIDE:
  101422. left_bps = encoder->private_->subframe_bps [0];
  101423. right_bps = encoder->private_->subframe_bps_mid_side[1];
  101424. break;
  101425. case FLAC__CHANNEL_ASSIGNMENT_RIGHT_SIDE:
  101426. left_bps = encoder->private_->subframe_bps_mid_side[1];
  101427. right_bps = encoder->private_->subframe_bps [1];
  101428. break;
  101429. case FLAC__CHANNEL_ASSIGNMENT_MID_SIDE:
  101430. left_bps = encoder->private_->subframe_bps_mid_side[0];
  101431. right_bps = encoder->private_->subframe_bps_mid_side[1];
  101432. break;
  101433. default:
  101434. FLAC__ASSERT(0);
  101435. }
  101436. /* note that encoder_add_subframe_ sets the state for us in case of an error */
  101437. if(!add_subframe_(encoder, frame_header.blocksize, left_bps , left_subframe , encoder->private_->frame))
  101438. return false;
  101439. if(!add_subframe_(encoder, frame_header.blocksize, right_bps, right_subframe, encoder->private_->frame))
  101440. return false;
  101441. }
  101442. else {
  101443. if(!FLAC__frame_add_header(&frame_header, encoder->private_->frame)) {
  101444. encoder->protected_->state = FLAC__STREAM_ENCODER_FRAMING_ERROR;
  101445. return false;
  101446. }
  101447. for(channel = 0; channel < encoder->protected_->channels; channel++) {
  101448. 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)) {
  101449. /* the above function sets the state for us in case of an error */
  101450. return false;
  101451. }
  101452. }
  101453. }
  101454. if(encoder->protected_->loose_mid_side_stereo) {
  101455. encoder->private_->loose_mid_side_stereo_frame_count++;
  101456. if(encoder->private_->loose_mid_side_stereo_frame_count >= encoder->private_->loose_mid_side_stereo_frames)
  101457. encoder->private_->loose_mid_side_stereo_frame_count = 0;
  101458. }
  101459. encoder->private_->last_channel_assignment = frame_header.channel_assignment;
  101460. return true;
  101461. }
  101462. FLAC__bool process_subframe_(
  101463. FLAC__StreamEncoder *encoder,
  101464. unsigned min_partition_order,
  101465. unsigned max_partition_order,
  101466. const FLAC__FrameHeader *frame_header,
  101467. unsigned subframe_bps,
  101468. const FLAC__int32 integer_signal[],
  101469. FLAC__Subframe *subframe[2],
  101470. FLAC__EntropyCodingMethod_PartitionedRiceContents *partitioned_rice_contents[2],
  101471. FLAC__int32 *residual[2],
  101472. unsigned *best_subframe,
  101473. unsigned *best_bits
  101474. )
  101475. {
  101476. #ifndef FLAC__INTEGER_ONLY_LIBRARY
  101477. FLAC__float fixed_residual_bits_per_sample[FLAC__MAX_FIXED_ORDER+1];
  101478. #else
  101479. FLAC__fixedpoint fixed_residual_bits_per_sample[FLAC__MAX_FIXED_ORDER+1];
  101480. #endif
  101481. #ifndef FLAC__INTEGER_ONLY_LIBRARY
  101482. FLAC__double lpc_residual_bits_per_sample;
  101483. 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 */
  101484. FLAC__double lpc_error[FLAC__MAX_LPC_ORDER];
  101485. unsigned min_lpc_order, max_lpc_order, lpc_order;
  101486. unsigned min_qlp_coeff_precision, max_qlp_coeff_precision, qlp_coeff_precision;
  101487. #endif
  101488. unsigned min_fixed_order, max_fixed_order, guess_fixed_order, fixed_order;
  101489. unsigned rice_parameter;
  101490. unsigned _candidate_bits, _best_bits;
  101491. unsigned _best_subframe;
  101492. /* only use RICE2 partitions if stream bps > 16 */
  101493. 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;
  101494. FLAC__ASSERT(frame_header->blocksize > 0);
  101495. /* verbatim subframe is the baseline against which we measure other compressed subframes */
  101496. _best_subframe = 0;
  101497. if(encoder->private_->disable_verbatim_subframes && frame_header->blocksize >= FLAC__MAX_FIXED_ORDER)
  101498. _best_bits = UINT_MAX;
  101499. else
  101500. _best_bits = evaluate_verbatim_subframe_(encoder, integer_signal, frame_header->blocksize, subframe_bps, subframe[_best_subframe]);
  101501. if(frame_header->blocksize >= FLAC__MAX_FIXED_ORDER) {
  101502. unsigned signal_is_constant = false;
  101503. 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);
  101504. /* check for constant subframe */
  101505. if(
  101506. !encoder->private_->disable_constant_subframes &&
  101507. #ifndef FLAC__INTEGER_ONLY_LIBRARY
  101508. fixed_residual_bits_per_sample[1] == 0.0
  101509. #else
  101510. fixed_residual_bits_per_sample[1] == FLAC__FP_ZERO
  101511. #endif
  101512. ) {
  101513. /* the above means it's possible all samples are the same value; now double-check it: */
  101514. unsigned i;
  101515. signal_is_constant = true;
  101516. for(i = 1; i < frame_header->blocksize; i++) {
  101517. if(integer_signal[0] != integer_signal[i]) {
  101518. signal_is_constant = false;
  101519. break;
  101520. }
  101521. }
  101522. }
  101523. if(signal_is_constant) {
  101524. _candidate_bits = evaluate_constant_subframe_(encoder, integer_signal[0], frame_header->blocksize, subframe_bps, subframe[!_best_subframe]);
  101525. if(_candidate_bits < _best_bits) {
  101526. _best_subframe = !_best_subframe;
  101527. _best_bits = _candidate_bits;
  101528. }
  101529. }
  101530. else {
  101531. if(!encoder->private_->disable_fixed_subframes || (encoder->protected_->max_lpc_order == 0 && _best_bits == UINT_MAX)) {
  101532. /* encode fixed */
  101533. if(encoder->protected_->do_exhaustive_model_search) {
  101534. min_fixed_order = 0;
  101535. max_fixed_order = FLAC__MAX_FIXED_ORDER;
  101536. }
  101537. else {
  101538. min_fixed_order = max_fixed_order = guess_fixed_order;
  101539. }
  101540. if(max_fixed_order >= frame_header->blocksize)
  101541. max_fixed_order = frame_header->blocksize - 1;
  101542. for(fixed_order = min_fixed_order; fixed_order <= max_fixed_order; fixed_order++) {
  101543. #ifndef FLAC__INTEGER_ONLY_LIBRARY
  101544. if(fixed_residual_bits_per_sample[fixed_order] >= (FLAC__float)subframe_bps)
  101545. continue; /* don't even try */
  101546. 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 */
  101547. #else
  101548. if(FLAC__fixedpoint_trunc(fixed_residual_bits_per_sample[fixed_order]) >= (int)subframe_bps)
  101549. continue; /* don't even try */
  101550. 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 */
  101551. #endif
  101552. rice_parameter++; /* to account for the signed->unsigned conversion during rice coding */
  101553. if(rice_parameter >= rice_parameter_limit) {
  101554. #ifdef DEBUG_VERBOSE
  101555. fprintf(stderr, "clipping rice_parameter (%u -> %u) @0\n", rice_parameter, rice_parameter_limit - 1);
  101556. #endif
  101557. rice_parameter = rice_parameter_limit - 1;
  101558. }
  101559. _candidate_bits =
  101560. evaluate_fixed_subframe_(
  101561. encoder,
  101562. integer_signal,
  101563. residual[!_best_subframe],
  101564. encoder->private_->abs_residual_partition_sums,
  101565. encoder->private_->raw_bits_per_partition,
  101566. frame_header->blocksize,
  101567. subframe_bps,
  101568. fixed_order,
  101569. rice_parameter,
  101570. rice_parameter_limit,
  101571. min_partition_order,
  101572. max_partition_order,
  101573. encoder->protected_->do_escape_coding,
  101574. encoder->protected_->rice_parameter_search_dist,
  101575. subframe[!_best_subframe],
  101576. partitioned_rice_contents[!_best_subframe]
  101577. );
  101578. if(_candidate_bits < _best_bits) {
  101579. _best_subframe = !_best_subframe;
  101580. _best_bits = _candidate_bits;
  101581. }
  101582. }
  101583. }
  101584. #ifndef FLAC__INTEGER_ONLY_LIBRARY
  101585. /* encode lpc */
  101586. if(encoder->protected_->max_lpc_order > 0) {
  101587. if(encoder->protected_->max_lpc_order >= frame_header->blocksize)
  101588. max_lpc_order = frame_header->blocksize-1;
  101589. else
  101590. max_lpc_order = encoder->protected_->max_lpc_order;
  101591. if(max_lpc_order > 0) {
  101592. unsigned a;
  101593. for (a = 0; a < encoder->protected_->num_apodizations; a++) {
  101594. FLAC__lpc_window_data(integer_signal, encoder->private_->window[a], encoder->private_->windowed_signal, frame_header->blocksize);
  101595. encoder->private_->local_lpc_compute_autocorrelation(encoder->private_->windowed_signal, frame_header->blocksize, max_lpc_order+1, autoc);
  101596. /* if autoc[0] == 0.0, the signal is constant and we usually won't get here, but it can happen */
  101597. if(autoc[0] != 0.0) {
  101598. FLAC__lpc_compute_lp_coefficients(autoc, &max_lpc_order, encoder->private_->lp_coeff, lpc_error);
  101599. if(encoder->protected_->do_exhaustive_model_search) {
  101600. min_lpc_order = 1;
  101601. }
  101602. else {
  101603. const unsigned guess_lpc_order =
  101604. FLAC__lpc_compute_best_order(
  101605. lpc_error,
  101606. max_lpc_order,
  101607. frame_header->blocksize,
  101608. subframe_bps + (
  101609. encoder->protected_->do_qlp_coeff_prec_search?
  101610. FLAC__MIN_QLP_COEFF_PRECISION : /* have to guess; use the min possible size to avoid accidentally favoring lower orders */
  101611. encoder->protected_->qlp_coeff_precision
  101612. )
  101613. );
  101614. min_lpc_order = max_lpc_order = guess_lpc_order;
  101615. }
  101616. if(max_lpc_order >= frame_header->blocksize)
  101617. max_lpc_order = frame_header->blocksize - 1;
  101618. for(lpc_order = min_lpc_order; lpc_order <= max_lpc_order; lpc_order++) {
  101619. lpc_residual_bits_per_sample = FLAC__lpc_compute_expected_bits_per_residual_sample(lpc_error[lpc_order-1], frame_header->blocksize-lpc_order);
  101620. if(lpc_residual_bits_per_sample >= (FLAC__double)subframe_bps)
  101621. continue; /* don't even try */
  101622. rice_parameter = (lpc_residual_bits_per_sample > 0.0)? (unsigned)(lpc_residual_bits_per_sample+0.5) : 0; /* 0.5 is for rounding */
  101623. rice_parameter++; /* to account for the signed->unsigned conversion during rice coding */
  101624. if(rice_parameter >= rice_parameter_limit) {
  101625. #ifdef DEBUG_VERBOSE
  101626. fprintf(stderr, "clipping rice_parameter (%u -> %u) @1\n", rice_parameter, rice_parameter_limit - 1);
  101627. #endif
  101628. rice_parameter = rice_parameter_limit - 1;
  101629. }
  101630. if(encoder->protected_->do_qlp_coeff_prec_search) {
  101631. min_qlp_coeff_precision = FLAC__MIN_QLP_COEFF_PRECISION;
  101632. /* try to ensure a 32-bit datapath throughout for 16bps(+1bps for side channel) or less */
  101633. if(subframe_bps <= 17) {
  101634. max_qlp_coeff_precision = min(32 - subframe_bps - lpc_order, FLAC__MAX_QLP_COEFF_PRECISION);
  101635. max_qlp_coeff_precision = max(max_qlp_coeff_precision, min_qlp_coeff_precision);
  101636. }
  101637. else
  101638. max_qlp_coeff_precision = FLAC__MAX_QLP_COEFF_PRECISION;
  101639. }
  101640. else {
  101641. min_qlp_coeff_precision = max_qlp_coeff_precision = encoder->protected_->qlp_coeff_precision;
  101642. }
  101643. for(qlp_coeff_precision = min_qlp_coeff_precision; qlp_coeff_precision <= max_qlp_coeff_precision; qlp_coeff_precision++) {
  101644. _candidate_bits =
  101645. evaluate_lpc_subframe_(
  101646. encoder,
  101647. integer_signal,
  101648. residual[!_best_subframe],
  101649. encoder->private_->abs_residual_partition_sums,
  101650. encoder->private_->raw_bits_per_partition,
  101651. encoder->private_->lp_coeff[lpc_order-1],
  101652. frame_header->blocksize,
  101653. subframe_bps,
  101654. lpc_order,
  101655. qlp_coeff_precision,
  101656. rice_parameter,
  101657. rice_parameter_limit,
  101658. min_partition_order,
  101659. max_partition_order,
  101660. encoder->protected_->do_escape_coding,
  101661. encoder->protected_->rice_parameter_search_dist,
  101662. subframe[!_best_subframe],
  101663. partitioned_rice_contents[!_best_subframe]
  101664. );
  101665. if(_candidate_bits > 0) { /* if == 0, there was a problem quantizing the lpcoeffs */
  101666. if(_candidate_bits < _best_bits) {
  101667. _best_subframe = !_best_subframe;
  101668. _best_bits = _candidate_bits;
  101669. }
  101670. }
  101671. }
  101672. }
  101673. }
  101674. }
  101675. }
  101676. }
  101677. #endif /* !defined FLAC__INTEGER_ONLY_LIBRARY */
  101678. }
  101679. }
  101680. /* under rare circumstances this can happen when all but lpc subframe types are disabled: */
  101681. if(_best_bits == UINT_MAX) {
  101682. FLAC__ASSERT(_best_subframe == 0);
  101683. _best_bits = evaluate_verbatim_subframe_(encoder, integer_signal, frame_header->blocksize, subframe_bps, subframe[_best_subframe]);
  101684. }
  101685. *best_subframe = _best_subframe;
  101686. *best_bits = _best_bits;
  101687. return true;
  101688. }
  101689. FLAC__bool add_subframe_(
  101690. FLAC__StreamEncoder *encoder,
  101691. unsigned blocksize,
  101692. unsigned subframe_bps,
  101693. const FLAC__Subframe *subframe,
  101694. FLAC__BitWriter *frame
  101695. )
  101696. {
  101697. switch(subframe->type) {
  101698. case FLAC__SUBFRAME_TYPE_CONSTANT:
  101699. if(!FLAC__subframe_add_constant(&(subframe->data.constant), subframe_bps, subframe->wasted_bits, frame)) {
  101700. encoder->protected_->state = FLAC__STREAM_ENCODER_FRAMING_ERROR;
  101701. return false;
  101702. }
  101703. break;
  101704. case FLAC__SUBFRAME_TYPE_FIXED:
  101705. if(!FLAC__subframe_add_fixed(&(subframe->data.fixed), blocksize - subframe->data.fixed.order, subframe_bps, subframe->wasted_bits, frame)) {
  101706. encoder->protected_->state = FLAC__STREAM_ENCODER_FRAMING_ERROR;
  101707. return false;
  101708. }
  101709. break;
  101710. case FLAC__SUBFRAME_TYPE_LPC:
  101711. if(!FLAC__subframe_add_lpc(&(subframe->data.lpc), blocksize - subframe->data.lpc.order, subframe_bps, subframe->wasted_bits, frame)) {
  101712. encoder->protected_->state = FLAC__STREAM_ENCODER_FRAMING_ERROR;
  101713. return false;
  101714. }
  101715. break;
  101716. case FLAC__SUBFRAME_TYPE_VERBATIM:
  101717. if(!FLAC__subframe_add_verbatim(&(subframe->data.verbatim), blocksize, subframe_bps, subframe->wasted_bits, frame)) {
  101718. encoder->protected_->state = FLAC__STREAM_ENCODER_FRAMING_ERROR;
  101719. return false;
  101720. }
  101721. break;
  101722. default:
  101723. FLAC__ASSERT(0);
  101724. }
  101725. return true;
  101726. }
  101727. #define SPOTCHECK_ESTIMATE 0
  101728. #if SPOTCHECK_ESTIMATE
  101729. static void spotcheck_subframe_estimate_(
  101730. FLAC__StreamEncoder *encoder,
  101731. unsigned blocksize,
  101732. unsigned subframe_bps,
  101733. const FLAC__Subframe *subframe,
  101734. unsigned estimate
  101735. )
  101736. {
  101737. FLAC__bool ret;
  101738. FLAC__BitWriter *frame = FLAC__bitwriter_new();
  101739. if(frame == 0) {
  101740. fprintf(stderr, "EST: can't allocate frame\n");
  101741. return;
  101742. }
  101743. if(!FLAC__bitwriter_init(frame)) {
  101744. fprintf(stderr, "EST: can't init frame\n");
  101745. return;
  101746. }
  101747. ret = add_subframe_(encoder, blocksize, subframe_bps, subframe, frame);
  101748. FLAC__ASSERT(ret);
  101749. {
  101750. const unsigned actual = FLAC__bitwriter_get_input_bits_unconsumed(frame);
  101751. if(estimate != actual)
  101752. 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);
  101753. }
  101754. FLAC__bitwriter_delete(frame);
  101755. }
  101756. #endif
  101757. unsigned evaluate_constant_subframe_(
  101758. FLAC__StreamEncoder *encoder,
  101759. const FLAC__int32 signal,
  101760. unsigned blocksize,
  101761. unsigned subframe_bps,
  101762. FLAC__Subframe *subframe
  101763. )
  101764. {
  101765. unsigned estimate;
  101766. subframe->type = FLAC__SUBFRAME_TYPE_CONSTANT;
  101767. subframe->data.constant.value = signal;
  101768. estimate = FLAC__SUBFRAME_ZERO_PAD_LEN + FLAC__SUBFRAME_TYPE_LEN + FLAC__SUBFRAME_WASTED_BITS_FLAG_LEN + subframe->wasted_bits + subframe_bps;
  101769. #if SPOTCHECK_ESTIMATE
  101770. spotcheck_subframe_estimate_(encoder, blocksize, subframe_bps, subframe, estimate);
  101771. #else
  101772. (void)encoder, (void)blocksize;
  101773. #endif
  101774. return estimate;
  101775. }
  101776. unsigned evaluate_fixed_subframe_(
  101777. FLAC__StreamEncoder *encoder,
  101778. const FLAC__int32 signal[],
  101779. FLAC__int32 residual[],
  101780. FLAC__uint64 abs_residual_partition_sums[],
  101781. unsigned raw_bits_per_partition[],
  101782. unsigned blocksize,
  101783. unsigned subframe_bps,
  101784. unsigned order,
  101785. unsigned rice_parameter,
  101786. unsigned rice_parameter_limit,
  101787. unsigned min_partition_order,
  101788. unsigned max_partition_order,
  101789. FLAC__bool do_escape_coding,
  101790. unsigned rice_parameter_search_dist,
  101791. FLAC__Subframe *subframe,
  101792. FLAC__EntropyCodingMethod_PartitionedRiceContents *partitioned_rice_contents
  101793. )
  101794. {
  101795. unsigned i, residual_bits, estimate;
  101796. const unsigned residual_samples = blocksize - order;
  101797. FLAC__fixed_compute_residual(signal+order, residual_samples, order, residual);
  101798. subframe->type = FLAC__SUBFRAME_TYPE_FIXED;
  101799. subframe->data.fixed.entropy_coding_method.type = FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE;
  101800. subframe->data.fixed.entropy_coding_method.data.partitioned_rice.contents = partitioned_rice_contents;
  101801. subframe->data.fixed.residual = residual;
  101802. residual_bits =
  101803. find_best_partition_order_(
  101804. encoder->private_,
  101805. residual,
  101806. abs_residual_partition_sums,
  101807. raw_bits_per_partition,
  101808. residual_samples,
  101809. order,
  101810. rice_parameter,
  101811. rice_parameter_limit,
  101812. min_partition_order,
  101813. max_partition_order,
  101814. subframe_bps,
  101815. do_escape_coding,
  101816. rice_parameter_search_dist,
  101817. &subframe->data.fixed.entropy_coding_method
  101818. );
  101819. subframe->data.fixed.order = order;
  101820. for(i = 0; i < order; i++)
  101821. subframe->data.fixed.warmup[i] = signal[i];
  101822. estimate = FLAC__SUBFRAME_ZERO_PAD_LEN + FLAC__SUBFRAME_TYPE_LEN + FLAC__SUBFRAME_WASTED_BITS_FLAG_LEN + subframe->wasted_bits + (order * subframe_bps) + residual_bits;
  101823. #if SPOTCHECK_ESTIMATE
  101824. spotcheck_subframe_estimate_(encoder, blocksize, subframe_bps, subframe, estimate);
  101825. #endif
  101826. return estimate;
  101827. }
  101828. #ifndef FLAC__INTEGER_ONLY_LIBRARY
  101829. unsigned evaluate_lpc_subframe_(
  101830. FLAC__StreamEncoder *encoder,
  101831. const FLAC__int32 signal[],
  101832. FLAC__int32 residual[],
  101833. FLAC__uint64 abs_residual_partition_sums[],
  101834. unsigned raw_bits_per_partition[],
  101835. const FLAC__real lp_coeff[],
  101836. unsigned blocksize,
  101837. unsigned subframe_bps,
  101838. unsigned order,
  101839. unsigned qlp_coeff_precision,
  101840. unsigned rice_parameter,
  101841. unsigned rice_parameter_limit,
  101842. unsigned min_partition_order,
  101843. unsigned max_partition_order,
  101844. FLAC__bool do_escape_coding,
  101845. unsigned rice_parameter_search_dist,
  101846. FLAC__Subframe *subframe,
  101847. FLAC__EntropyCodingMethod_PartitionedRiceContents *partitioned_rice_contents
  101848. )
  101849. {
  101850. FLAC__int32 qlp_coeff[FLAC__MAX_LPC_ORDER];
  101851. unsigned i, residual_bits, estimate;
  101852. int quantization, ret;
  101853. const unsigned residual_samples = blocksize - order;
  101854. /* try to keep qlp coeff precision such that only 32-bit math is required for decode of <=16bps streams */
  101855. if(subframe_bps <= 16) {
  101856. FLAC__ASSERT(order > 0);
  101857. FLAC__ASSERT(order <= FLAC__MAX_LPC_ORDER);
  101858. qlp_coeff_precision = min(qlp_coeff_precision, 32 - subframe_bps - FLAC__bitmath_ilog2(order));
  101859. }
  101860. ret = FLAC__lpc_quantize_coefficients(lp_coeff, order, qlp_coeff_precision, qlp_coeff, &quantization);
  101861. if(ret != 0)
  101862. return 0; /* this is a hack to indicate to the caller that we can't do lp at this order on this subframe */
  101863. if(subframe_bps + qlp_coeff_precision + FLAC__bitmath_ilog2(order) <= 32)
  101864. if(subframe_bps <= 16 && qlp_coeff_precision <= 16)
  101865. encoder->private_->local_lpc_compute_residual_from_qlp_coefficients_16bit(signal+order, residual_samples, qlp_coeff, order, quantization, residual);
  101866. else
  101867. encoder->private_->local_lpc_compute_residual_from_qlp_coefficients(signal+order, residual_samples, qlp_coeff, order, quantization, residual);
  101868. else
  101869. encoder->private_->local_lpc_compute_residual_from_qlp_coefficients_64bit(signal+order, residual_samples, qlp_coeff, order, quantization, residual);
  101870. subframe->type = FLAC__SUBFRAME_TYPE_LPC;
  101871. subframe->data.lpc.entropy_coding_method.type = FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE;
  101872. subframe->data.lpc.entropy_coding_method.data.partitioned_rice.contents = partitioned_rice_contents;
  101873. subframe->data.lpc.residual = residual;
  101874. residual_bits =
  101875. find_best_partition_order_(
  101876. encoder->private_,
  101877. residual,
  101878. abs_residual_partition_sums,
  101879. raw_bits_per_partition,
  101880. residual_samples,
  101881. order,
  101882. rice_parameter,
  101883. rice_parameter_limit,
  101884. min_partition_order,
  101885. max_partition_order,
  101886. subframe_bps,
  101887. do_escape_coding,
  101888. rice_parameter_search_dist,
  101889. &subframe->data.lpc.entropy_coding_method
  101890. );
  101891. subframe->data.lpc.order = order;
  101892. subframe->data.lpc.qlp_coeff_precision = qlp_coeff_precision;
  101893. subframe->data.lpc.quantization_level = quantization;
  101894. memcpy(subframe->data.lpc.qlp_coeff, qlp_coeff, sizeof(FLAC__int32)*FLAC__MAX_LPC_ORDER);
  101895. for(i = 0; i < order; i++)
  101896. subframe->data.lpc.warmup[i] = signal[i];
  101897. 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;
  101898. #if SPOTCHECK_ESTIMATE
  101899. spotcheck_subframe_estimate_(encoder, blocksize, subframe_bps, subframe, estimate);
  101900. #endif
  101901. return estimate;
  101902. }
  101903. #endif
  101904. unsigned evaluate_verbatim_subframe_(
  101905. FLAC__StreamEncoder *encoder,
  101906. const FLAC__int32 signal[],
  101907. unsigned blocksize,
  101908. unsigned subframe_bps,
  101909. FLAC__Subframe *subframe
  101910. )
  101911. {
  101912. unsigned estimate;
  101913. subframe->type = FLAC__SUBFRAME_TYPE_VERBATIM;
  101914. subframe->data.verbatim.data = signal;
  101915. estimate = FLAC__SUBFRAME_ZERO_PAD_LEN + FLAC__SUBFRAME_TYPE_LEN + FLAC__SUBFRAME_WASTED_BITS_FLAG_LEN + subframe->wasted_bits + (blocksize * subframe_bps);
  101916. #if SPOTCHECK_ESTIMATE
  101917. spotcheck_subframe_estimate_(encoder, blocksize, subframe_bps, subframe, estimate);
  101918. #else
  101919. (void)encoder;
  101920. #endif
  101921. return estimate;
  101922. }
  101923. unsigned find_best_partition_order_(
  101924. FLAC__StreamEncoderPrivate *private_,
  101925. const FLAC__int32 residual[],
  101926. FLAC__uint64 abs_residual_partition_sums[],
  101927. unsigned raw_bits_per_partition[],
  101928. unsigned residual_samples,
  101929. unsigned predictor_order,
  101930. unsigned rice_parameter,
  101931. unsigned rice_parameter_limit,
  101932. unsigned min_partition_order,
  101933. unsigned max_partition_order,
  101934. unsigned bps,
  101935. FLAC__bool do_escape_coding,
  101936. unsigned rice_parameter_search_dist,
  101937. FLAC__EntropyCodingMethod *best_ecm
  101938. )
  101939. {
  101940. unsigned residual_bits, best_residual_bits = 0;
  101941. unsigned best_parameters_index = 0;
  101942. unsigned best_partition_order = 0;
  101943. const unsigned blocksize = residual_samples + predictor_order;
  101944. max_partition_order = FLAC__format_get_max_rice_partition_order_from_blocksize_limited_max_and_predictor_order(max_partition_order, blocksize, predictor_order);
  101945. min_partition_order = min(min_partition_order, max_partition_order);
  101946. precompute_partition_info_sums_(residual, abs_residual_partition_sums, residual_samples, predictor_order, min_partition_order, max_partition_order, bps);
  101947. if(do_escape_coding)
  101948. precompute_partition_info_escapes_(residual, raw_bits_per_partition, residual_samples, predictor_order, min_partition_order, max_partition_order);
  101949. {
  101950. int partition_order;
  101951. unsigned sum;
  101952. for(partition_order = (int)max_partition_order, sum = 0; partition_order >= (int)min_partition_order; partition_order--) {
  101953. if(!
  101954. set_partitioned_rice_(
  101955. #ifdef EXACT_RICE_BITS_CALCULATION
  101956. residual,
  101957. #endif
  101958. abs_residual_partition_sums+sum,
  101959. raw_bits_per_partition+sum,
  101960. residual_samples,
  101961. predictor_order,
  101962. rice_parameter,
  101963. rice_parameter_limit,
  101964. rice_parameter_search_dist,
  101965. (unsigned)partition_order,
  101966. do_escape_coding,
  101967. &private_->partitioned_rice_contents_extra[!best_parameters_index],
  101968. &residual_bits
  101969. )
  101970. )
  101971. {
  101972. FLAC__ASSERT(best_residual_bits != 0);
  101973. break;
  101974. }
  101975. sum += 1u << partition_order;
  101976. if(best_residual_bits == 0 || residual_bits < best_residual_bits) {
  101977. best_residual_bits = residual_bits;
  101978. best_parameters_index = !best_parameters_index;
  101979. best_partition_order = partition_order;
  101980. }
  101981. }
  101982. }
  101983. best_ecm->data.partitioned_rice.order = best_partition_order;
  101984. {
  101985. /*
  101986. * We are allowed to de-const the pointer based on our special
  101987. * knowledge; it is const to the outside world.
  101988. */
  101989. FLAC__EntropyCodingMethod_PartitionedRiceContents* prc = (FLAC__EntropyCodingMethod_PartitionedRiceContents*)best_ecm->data.partitioned_rice.contents;
  101990. unsigned partition;
  101991. /* save best parameters and raw_bits */
  101992. FLAC__format_entropy_coding_method_partitioned_rice_contents_ensure_size(prc, max(6, best_partition_order));
  101993. memcpy(prc->parameters, private_->partitioned_rice_contents_extra[best_parameters_index].parameters, sizeof(unsigned)*(1<<(best_partition_order)));
  101994. if(do_escape_coding)
  101995. memcpy(prc->raw_bits, private_->partitioned_rice_contents_extra[best_parameters_index].raw_bits, sizeof(unsigned)*(1<<(best_partition_order)));
  101996. /*
  101997. * Now need to check if the type should be changed to
  101998. * FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE2 based on the
  101999. * size of the rice parameters.
  102000. */
  102001. for(partition = 0; partition < (1u<<best_partition_order); partition++) {
  102002. if(prc->parameters[partition] >= FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE_ESCAPE_PARAMETER) {
  102003. best_ecm->type = FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE2;
  102004. break;
  102005. }
  102006. }
  102007. }
  102008. return best_residual_bits;
  102009. }
  102010. #if defined(FLAC__CPU_IA32) && !defined FLAC__NO_ASM && defined FLAC__HAS_NASM
  102011. extern void precompute_partition_info_sums_32bit_asm_ia32_(
  102012. const FLAC__int32 residual[],
  102013. FLAC__uint64 abs_residual_partition_sums[],
  102014. unsigned blocksize,
  102015. unsigned predictor_order,
  102016. unsigned min_partition_order,
  102017. unsigned max_partition_order
  102018. );
  102019. #endif
  102020. void precompute_partition_info_sums_(
  102021. const FLAC__int32 residual[],
  102022. FLAC__uint64 abs_residual_partition_sums[],
  102023. unsigned residual_samples,
  102024. unsigned predictor_order,
  102025. unsigned min_partition_order,
  102026. unsigned max_partition_order,
  102027. unsigned bps
  102028. )
  102029. {
  102030. const unsigned default_partition_samples = (residual_samples + predictor_order) >> max_partition_order;
  102031. unsigned partitions = 1u << max_partition_order;
  102032. FLAC__ASSERT(default_partition_samples > predictor_order);
  102033. #if defined(FLAC__CPU_IA32) && !defined FLAC__NO_ASM && defined FLAC__HAS_NASM
  102034. /* slightly pessimistic but still catches all common cases */
  102035. /* WATCHOUT: "+ bps" is an assumption that the average residual magnitude will not be more than "bps" bits */
  102036. if(FLAC__bitmath_ilog2(default_partition_samples) + bps < 32) {
  102037. precompute_partition_info_sums_32bit_asm_ia32_(residual, abs_residual_partition_sums, residual_samples + predictor_order, predictor_order, min_partition_order, max_partition_order);
  102038. return;
  102039. }
  102040. #endif
  102041. /* first do max_partition_order */
  102042. {
  102043. unsigned partition, residual_sample, end = (unsigned)(-(int)predictor_order);
  102044. /* slightly pessimistic but still catches all common cases */
  102045. /* WATCHOUT: "+ bps" is an assumption that the average residual magnitude will not be more than "bps" bits */
  102046. if(FLAC__bitmath_ilog2(default_partition_samples) + bps < 32) {
  102047. FLAC__uint32 abs_residual_partition_sum;
  102048. for(partition = residual_sample = 0; partition < partitions; partition++) {
  102049. end += default_partition_samples;
  102050. abs_residual_partition_sum = 0;
  102051. for( ; residual_sample < end; residual_sample++)
  102052. abs_residual_partition_sum += abs(residual[residual_sample]); /* abs(INT_MIN) is undefined, but if the residual is INT_MIN we have bigger problems */
  102053. abs_residual_partition_sums[partition] = abs_residual_partition_sum;
  102054. }
  102055. }
  102056. else { /* have to pessimistically use 64 bits for accumulator */
  102057. FLAC__uint64 abs_residual_partition_sum;
  102058. for(partition = residual_sample = 0; partition < partitions; partition++) {
  102059. end += default_partition_samples;
  102060. abs_residual_partition_sum = 0;
  102061. for( ; residual_sample < end; residual_sample++)
  102062. abs_residual_partition_sum += abs(residual[residual_sample]); /* abs(INT_MIN) is undefined, but if the residual is INT_MIN we have bigger problems */
  102063. abs_residual_partition_sums[partition] = abs_residual_partition_sum;
  102064. }
  102065. }
  102066. }
  102067. /* now merge partitions for lower orders */
  102068. {
  102069. unsigned from_partition = 0, to_partition = partitions;
  102070. int partition_order;
  102071. for(partition_order = (int)max_partition_order - 1; partition_order >= (int)min_partition_order; partition_order--) {
  102072. unsigned i;
  102073. partitions >>= 1;
  102074. for(i = 0; i < partitions; i++) {
  102075. abs_residual_partition_sums[to_partition++] =
  102076. abs_residual_partition_sums[from_partition ] +
  102077. abs_residual_partition_sums[from_partition+1];
  102078. from_partition += 2;
  102079. }
  102080. }
  102081. }
  102082. }
  102083. void precompute_partition_info_escapes_(
  102084. const FLAC__int32 residual[],
  102085. unsigned raw_bits_per_partition[],
  102086. unsigned residual_samples,
  102087. unsigned predictor_order,
  102088. unsigned min_partition_order,
  102089. unsigned max_partition_order
  102090. )
  102091. {
  102092. int partition_order;
  102093. unsigned from_partition, to_partition = 0;
  102094. const unsigned blocksize = residual_samples + predictor_order;
  102095. /* first do max_partition_order */
  102096. for(partition_order = (int)max_partition_order; partition_order >= 0; partition_order--) {
  102097. FLAC__int32 r;
  102098. FLAC__uint32 rmax;
  102099. unsigned partition, partition_sample, partition_samples, residual_sample;
  102100. const unsigned partitions = 1u << partition_order;
  102101. const unsigned default_partition_samples = blocksize >> partition_order;
  102102. FLAC__ASSERT(default_partition_samples > predictor_order);
  102103. for(partition = residual_sample = 0; partition < partitions; partition++) {
  102104. partition_samples = default_partition_samples;
  102105. if(partition == 0)
  102106. partition_samples -= predictor_order;
  102107. rmax = 0;
  102108. for(partition_sample = 0; partition_sample < partition_samples; partition_sample++) {
  102109. r = residual[residual_sample++];
  102110. /* OPT: maybe faster: rmax |= r ^ (r>>31) */
  102111. if(r < 0)
  102112. rmax |= ~r;
  102113. else
  102114. rmax |= r;
  102115. }
  102116. /* now we know all residual values are in the range [-rmax-1,rmax] */
  102117. raw_bits_per_partition[partition] = rmax? FLAC__bitmath_ilog2(rmax) + 2 : 1;
  102118. }
  102119. to_partition = partitions;
  102120. break; /*@@@ yuck, should remove the 'for' loop instead */
  102121. }
  102122. /* now merge partitions for lower orders */
  102123. for(from_partition = 0, --partition_order; partition_order >= (int)min_partition_order; partition_order--) {
  102124. unsigned m;
  102125. unsigned i;
  102126. const unsigned partitions = 1u << partition_order;
  102127. for(i = 0; i < partitions; i++) {
  102128. m = raw_bits_per_partition[from_partition];
  102129. from_partition++;
  102130. raw_bits_per_partition[to_partition] = max(m, raw_bits_per_partition[from_partition]);
  102131. from_partition++;
  102132. to_partition++;
  102133. }
  102134. }
  102135. }
  102136. #ifdef EXACT_RICE_BITS_CALCULATION
  102137. static FLaC__INLINE unsigned count_rice_bits_in_partition_(
  102138. const unsigned rice_parameter,
  102139. const unsigned partition_samples,
  102140. const FLAC__int32 *residual
  102141. )
  102142. {
  102143. unsigned i, partition_bits =
  102144. 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 */
  102145. (1+rice_parameter) * partition_samples /* 1 for unary stop bit + rice_parameter for the binary portion */
  102146. ;
  102147. for(i = 0; i < partition_samples; i++)
  102148. partition_bits += ( (FLAC__uint32)((residual[i]<<1)^(residual[i]>>31)) >> rice_parameter );
  102149. return partition_bits;
  102150. }
  102151. #else
  102152. static FLaC__INLINE unsigned count_rice_bits_in_partition_(
  102153. const unsigned rice_parameter,
  102154. const unsigned partition_samples,
  102155. const FLAC__uint64 abs_residual_partition_sum
  102156. )
  102157. {
  102158. return
  102159. 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 */
  102160. (1+rice_parameter) * partition_samples + /* 1 for unary stop bit + rice_parameter for the binary portion */
  102161. (
  102162. rice_parameter?
  102163. (unsigned)(abs_residual_partition_sum >> (rice_parameter-1)) /* rice_parameter-1 because the real coder sign-folds instead of using a sign bit */
  102164. : (unsigned)(abs_residual_partition_sum << 1) /* can't shift by negative number, so reverse */
  102165. )
  102166. - (partition_samples >> 1)
  102167. /* -(partition_samples>>1) to subtract out extra contributions to the abs_residual_partition_sum.
  102168. * The actual number of bits used is closer to the sum(for all i in the partition) of abs(residual[i])>>(rice_parameter-1)
  102169. * By using the abs_residual_partition sum, we also add in bits in the LSBs that would normally be shifted out.
  102170. * So the subtraction term tries to guess how many extra bits were contributed.
  102171. * If the LSBs are randomly distributed, this should average to 0.5 extra bits per sample.
  102172. */
  102173. ;
  102174. }
  102175. #endif
  102176. FLAC__bool set_partitioned_rice_(
  102177. #ifdef EXACT_RICE_BITS_CALCULATION
  102178. const FLAC__int32 residual[],
  102179. #endif
  102180. const FLAC__uint64 abs_residual_partition_sums[],
  102181. const unsigned raw_bits_per_partition[],
  102182. const unsigned residual_samples,
  102183. const unsigned predictor_order,
  102184. const unsigned suggested_rice_parameter,
  102185. const unsigned rice_parameter_limit,
  102186. const unsigned rice_parameter_search_dist,
  102187. const unsigned partition_order,
  102188. const FLAC__bool search_for_escapes,
  102189. FLAC__EntropyCodingMethod_PartitionedRiceContents *partitioned_rice_contents,
  102190. unsigned *bits
  102191. )
  102192. {
  102193. unsigned rice_parameter, partition_bits;
  102194. unsigned best_partition_bits, best_rice_parameter = 0;
  102195. unsigned bits_ = FLAC__ENTROPY_CODING_METHOD_TYPE_LEN + FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE_ORDER_LEN;
  102196. unsigned *parameters, *raw_bits;
  102197. #ifdef ENABLE_RICE_PARAMETER_SEARCH
  102198. unsigned min_rice_parameter, max_rice_parameter;
  102199. #else
  102200. (void)rice_parameter_search_dist;
  102201. #endif
  102202. FLAC__ASSERT(suggested_rice_parameter < FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE2_ESCAPE_PARAMETER);
  102203. FLAC__ASSERT(rice_parameter_limit <= FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE2_ESCAPE_PARAMETER);
  102204. FLAC__format_entropy_coding_method_partitioned_rice_contents_ensure_size(partitioned_rice_contents, max(6, partition_order));
  102205. parameters = partitioned_rice_contents->parameters;
  102206. raw_bits = partitioned_rice_contents->raw_bits;
  102207. if(partition_order == 0) {
  102208. best_partition_bits = (unsigned)(-1);
  102209. #ifdef ENABLE_RICE_PARAMETER_SEARCH
  102210. if(rice_parameter_search_dist) {
  102211. if(suggested_rice_parameter < rice_parameter_search_dist)
  102212. min_rice_parameter = 0;
  102213. else
  102214. min_rice_parameter = suggested_rice_parameter - rice_parameter_search_dist;
  102215. max_rice_parameter = suggested_rice_parameter + rice_parameter_search_dist;
  102216. if(max_rice_parameter >= rice_parameter_limit) {
  102217. #ifdef DEBUG_VERBOSE
  102218. fprintf(stderr, "clipping rice_parameter (%u -> %u) @5\n", max_rice_parameter, rice_parameter_limit - 1);
  102219. #endif
  102220. max_rice_parameter = rice_parameter_limit - 1;
  102221. }
  102222. }
  102223. else
  102224. min_rice_parameter = max_rice_parameter = suggested_rice_parameter;
  102225. for(rice_parameter = min_rice_parameter; rice_parameter <= max_rice_parameter; rice_parameter++) {
  102226. #else
  102227. rice_parameter = suggested_rice_parameter;
  102228. #endif
  102229. #ifdef EXACT_RICE_BITS_CALCULATION
  102230. partition_bits = count_rice_bits_in_partition_(rice_parameter, residual_samples, residual);
  102231. #else
  102232. partition_bits = count_rice_bits_in_partition_(rice_parameter, residual_samples, abs_residual_partition_sums[0]);
  102233. #endif
  102234. if(partition_bits < best_partition_bits) {
  102235. best_rice_parameter = rice_parameter;
  102236. best_partition_bits = partition_bits;
  102237. }
  102238. #ifdef ENABLE_RICE_PARAMETER_SEARCH
  102239. }
  102240. #endif
  102241. if(search_for_escapes) {
  102242. 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;
  102243. if(partition_bits <= best_partition_bits) {
  102244. raw_bits[0] = raw_bits_per_partition[0];
  102245. best_rice_parameter = 0; /* will be converted to appropriate escape parameter later */
  102246. best_partition_bits = partition_bits;
  102247. }
  102248. else
  102249. raw_bits[0] = 0;
  102250. }
  102251. parameters[0] = best_rice_parameter;
  102252. bits_ += best_partition_bits;
  102253. }
  102254. else {
  102255. unsigned partition, residual_sample;
  102256. unsigned partition_samples;
  102257. FLAC__uint64 mean, k;
  102258. const unsigned partitions = 1u << partition_order;
  102259. for(partition = residual_sample = 0; partition < partitions; partition++) {
  102260. partition_samples = (residual_samples+predictor_order) >> partition_order;
  102261. if(partition == 0) {
  102262. if(partition_samples <= predictor_order)
  102263. return false;
  102264. else
  102265. partition_samples -= predictor_order;
  102266. }
  102267. mean = abs_residual_partition_sums[partition];
  102268. /* we are basically calculating the size in bits of the
  102269. * average residual magnitude in the partition:
  102270. * rice_parameter = floor(log2(mean/partition_samples))
  102271. * 'mean' is not a good name for the variable, it is
  102272. * actually the sum of magnitudes of all residual values
  102273. * in the partition, so the actual mean is
  102274. * mean/partition_samples
  102275. */
  102276. for(rice_parameter = 0, k = partition_samples; k < mean; rice_parameter++, k <<= 1)
  102277. ;
  102278. if(rice_parameter >= rice_parameter_limit) {
  102279. #ifdef DEBUG_VERBOSE
  102280. fprintf(stderr, "clipping rice_parameter (%u -> %u) @6\n", rice_parameter, rice_parameter_limit - 1);
  102281. #endif
  102282. rice_parameter = rice_parameter_limit - 1;
  102283. }
  102284. best_partition_bits = (unsigned)(-1);
  102285. #ifdef ENABLE_RICE_PARAMETER_SEARCH
  102286. if(rice_parameter_search_dist) {
  102287. if(rice_parameter < rice_parameter_search_dist)
  102288. min_rice_parameter = 0;
  102289. else
  102290. min_rice_parameter = rice_parameter - rice_parameter_search_dist;
  102291. max_rice_parameter = rice_parameter + rice_parameter_search_dist;
  102292. if(max_rice_parameter >= rice_parameter_limit) {
  102293. #ifdef DEBUG_VERBOSE
  102294. fprintf(stderr, "clipping rice_parameter (%u -> %u) @7\n", max_rice_parameter, rice_parameter_limit - 1);
  102295. #endif
  102296. max_rice_parameter = rice_parameter_limit - 1;
  102297. }
  102298. }
  102299. else
  102300. min_rice_parameter = max_rice_parameter = rice_parameter;
  102301. for(rice_parameter = min_rice_parameter; rice_parameter <= max_rice_parameter; rice_parameter++) {
  102302. #endif
  102303. #ifdef EXACT_RICE_BITS_CALCULATION
  102304. partition_bits = count_rice_bits_in_partition_(rice_parameter, partition_samples, residual+residual_sample);
  102305. #else
  102306. partition_bits = count_rice_bits_in_partition_(rice_parameter, partition_samples, abs_residual_partition_sums[partition]);
  102307. #endif
  102308. if(partition_bits < best_partition_bits) {
  102309. best_rice_parameter = rice_parameter;
  102310. best_partition_bits = partition_bits;
  102311. }
  102312. #ifdef ENABLE_RICE_PARAMETER_SEARCH
  102313. }
  102314. #endif
  102315. if(search_for_escapes) {
  102316. 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;
  102317. if(partition_bits <= best_partition_bits) {
  102318. raw_bits[partition] = raw_bits_per_partition[partition];
  102319. best_rice_parameter = 0; /* will be converted to appropriate escape parameter later */
  102320. best_partition_bits = partition_bits;
  102321. }
  102322. else
  102323. raw_bits[partition] = 0;
  102324. }
  102325. parameters[partition] = best_rice_parameter;
  102326. bits_ += best_partition_bits;
  102327. residual_sample += partition_samples;
  102328. }
  102329. }
  102330. *bits = bits_;
  102331. return true;
  102332. }
  102333. unsigned get_wasted_bits_(FLAC__int32 signal[], unsigned samples)
  102334. {
  102335. unsigned i, shift;
  102336. FLAC__int32 x = 0;
  102337. for(i = 0; i < samples && !(x&1); i++)
  102338. x |= signal[i];
  102339. if(x == 0) {
  102340. shift = 0;
  102341. }
  102342. else {
  102343. for(shift = 0; !(x&1); shift++)
  102344. x >>= 1;
  102345. }
  102346. if(shift > 0) {
  102347. for(i = 0; i < samples; i++)
  102348. signal[i] >>= shift;
  102349. }
  102350. return shift;
  102351. }
  102352. void append_to_verify_fifo_(verify_input_fifo *fifo, const FLAC__int32 * const input[], unsigned input_offset, unsigned channels, unsigned wide_samples)
  102353. {
  102354. unsigned channel;
  102355. for(channel = 0; channel < channels; channel++)
  102356. memcpy(&fifo->data[channel][fifo->tail], &input[channel][input_offset], sizeof(FLAC__int32) * wide_samples);
  102357. fifo->tail += wide_samples;
  102358. FLAC__ASSERT(fifo->tail <= fifo->size);
  102359. }
  102360. void append_to_verify_fifo_interleaved_(verify_input_fifo *fifo, const FLAC__int32 input[], unsigned input_offset, unsigned channels, unsigned wide_samples)
  102361. {
  102362. unsigned channel;
  102363. unsigned sample, wide_sample;
  102364. unsigned tail = fifo->tail;
  102365. sample = input_offset * channels;
  102366. for(wide_sample = 0; wide_sample < wide_samples; wide_sample++) {
  102367. for(channel = 0; channel < channels; channel++)
  102368. fifo->data[channel][tail] = input[sample++];
  102369. tail++;
  102370. }
  102371. fifo->tail = tail;
  102372. FLAC__ASSERT(fifo->tail <= fifo->size);
  102373. }
  102374. FLAC__StreamDecoderReadStatus verify_read_callback_(const FLAC__StreamDecoder *decoder, FLAC__byte buffer[], size_t *bytes, void *client_data)
  102375. {
  102376. FLAC__StreamEncoder *encoder = (FLAC__StreamEncoder*)client_data;
  102377. const size_t encoded_bytes = encoder->private_->verify.output.bytes;
  102378. (void)decoder;
  102379. if(encoder->private_->verify.needs_magic_hack) {
  102380. FLAC__ASSERT(*bytes >= FLAC__STREAM_SYNC_LENGTH);
  102381. *bytes = FLAC__STREAM_SYNC_LENGTH;
  102382. memcpy(buffer, FLAC__STREAM_SYNC_STRING, *bytes);
  102383. encoder->private_->verify.needs_magic_hack = false;
  102384. }
  102385. else {
  102386. if(encoded_bytes == 0) {
  102387. /*
  102388. * If we get here, a FIFO underflow has occurred,
  102389. * which means there is a bug somewhere.
  102390. */
  102391. FLAC__ASSERT(0);
  102392. return FLAC__STREAM_DECODER_READ_STATUS_ABORT;
  102393. }
  102394. else if(encoded_bytes < *bytes)
  102395. *bytes = encoded_bytes;
  102396. memcpy(buffer, encoder->private_->verify.output.data, *bytes);
  102397. encoder->private_->verify.output.data += *bytes;
  102398. encoder->private_->verify.output.bytes -= *bytes;
  102399. }
  102400. return FLAC__STREAM_DECODER_READ_STATUS_CONTINUE;
  102401. }
  102402. FLAC__StreamDecoderWriteStatus verify_write_callback_(const FLAC__StreamDecoder *decoder, const FLAC__Frame *frame, const FLAC__int32 * const buffer[], void *client_data)
  102403. {
  102404. FLAC__StreamEncoder *encoder = (FLAC__StreamEncoder *)client_data;
  102405. unsigned channel;
  102406. const unsigned channels = frame->header.channels;
  102407. const unsigned blocksize = frame->header.blocksize;
  102408. const unsigned bytes_per_block = sizeof(FLAC__int32) * blocksize;
  102409. (void)decoder;
  102410. for(channel = 0; channel < channels; channel++) {
  102411. if(0 != memcmp(buffer[channel], encoder->private_->verify.input_fifo.data[channel], bytes_per_block)) {
  102412. unsigned i, sample = 0;
  102413. FLAC__int32 expect = 0, got = 0;
  102414. for(i = 0; i < blocksize; i++) {
  102415. if(buffer[channel][i] != encoder->private_->verify.input_fifo.data[channel][i]) {
  102416. sample = i;
  102417. expect = (FLAC__int32)encoder->private_->verify.input_fifo.data[channel][i];
  102418. got = (FLAC__int32)buffer[channel][i];
  102419. break;
  102420. }
  102421. }
  102422. FLAC__ASSERT(i < blocksize);
  102423. FLAC__ASSERT(frame->header.number_type == FLAC__FRAME_NUMBER_TYPE_SAMPLE_NUMBER);
  102424. encoder->private_->verify.error_stats.absolute_sample = frame->header.number.sample_number + sample;
  102425. encoder->private_->verify.error_stats.frame_number = (unsigned)(frame->header.number.sample_number / blocksize);
  102426. encoder->private_->verify.error_stats.channel = channel;
  102427. encoder->private_->verify.error_stats.sample = sample;
  102428. encoder->private_->verify.error_stats.expected = expect;
  102429. encoder->private_->verify.error_stats.got = got;
  102430. encoder->protected_->state = FLAC__STREAM_ENCODER_VERIFY_MISMATCH_IN_AUDIO_DATA;
  102431. return FLAC__STREAM_DECODER_WRITE_STATUS_ABORT;
  102432. }
  102433. }
  102434. /* dequeue the frame from the fifo */
  102435. encoder->private_->verify.input_fifo.tail -= blocksize;
  102436. FLAC__ASSERT(encoder->private_->verify.input_fifo.tail <= OVERREAD_);
  102437. for(channel = 0; channel < channels; channel++)
  102438. 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]));
  102439. return FLAC__STREAM_DECODER_WRITE_STATUS_CONTINUE;
  102440. }
  102441. void verify_metadata_callback_(const FLAC__StreamDecoder *decoder, const FLAC__StreamMetadata *metadata, void *client_data)
  102442. {
  102443. (void)decoder, (void)metadata, (void)client_data;
  102444. }
  102445. void verify_error_callback_(const FLAC__StreamDecoder *decoder, FLAC__StreamDecoderErrorStatus status, void *client_data)
  102446. {
  102447. FLAC__StreamEncoder *encoder = (FLAC__StreamEncoder*)client_data;
  102448. (void)decoder, (void)status;
  102449. encoder->protected_->state = FLAC__STREAM_ENCODER_VERIFY_DECODER_ERROR;
  102450. }
  102451. FLAC__StreamEncoderReadStatus file_read_callback_enc(const FLAC__StreamEncoder *encoder, FLAC__byte buffer[], size_t *bytes, void *client_data)
  102452. {
  102453. (void)client_data;
  102454. *bytes = fread(buffer, 1, *bytes, encoder->private_->file);
  102455. if (*bytes == 0) {
  102456. if (feof(encoder->private_->file))
  102457. return FLAC__STREAM_ENCODER_READ_STATUS_END_OF_STREAM;
  102458. else if (ferror(encoder->private_->file))
  102459. return FLAC__STREAM_ENCODER_READ_STATUS_ABORT;
  102460. }
  102461. return FLAC__STREAM_ENCODER_READ_STATUS_CONTINUE;
  102462. }
  102463. FLAC__StreamEncoderSeekStatus file_seek_callback_enc(const FLAC__StreamEncoder *encoder, FLAC__uint64 absolute_byte_offset, void *client_data)
  102464. {
  102465. (void)client_data;
  102466. if(fseeko(encoder->private_->file, (off_t)absolute_byte_offset, SEEK_SET) < 0)
  102467. return FLAC__STREAM_ENCODER_SEEK_STATUS_ERROR;
  102468. else
  102469. return FLAC__STREAM_ENCODER_SEEK_STATUS_OK;
  102470. }
  102471. FLAC__StreamEncoderTellStatus file_tell_callback_enc(const FLAC__StreamEncoder *encoder, FLAC__uint64 *absolute_byte_offset, void *client_data)
  102472. {
  102473. off_t offset;
  102474. (void)client_data;
  102475. offset = ftello(encoder->private_->file);
  102476. if(offset < 0) {
  102477. return FLAC__STREAM_ENCODER_TELL_STATUS_ERROR;
  102478. }
  102479. else {
  102480. *absolute_byte_offset = (FLAC__uint64)offset;
  102481. return FLAC__STREAM_ENCODER_TELL_STATUS_OK;
  102482. }
  102483. }
  102484. #ifdef FLAC__VALGRIND_TESTING
  102485. static size_t local__fwrite(const void *ptr, size_t size, size_t nmemb, FILE *stream)
  102486. {
  102487. size_t ret = fwrite(ptr, size, nmemb, stream);
  102488. if(!ferror(stream))
  102489. fflush(stream);
  102490. return ret;
  102491. }
  102492. #else
  102493. #define local__fwrite fwrite
  102494. #endif
  102495. FLAC__StreamEncoderWriteStatus file_write_callback_(const FLAC__StreamEncoder *encoder, const FLAC__byte buffer[], size_t bytes, unsigned samples, unsigned current_frame, void *client_data)
  102496. {
  102497. (void)client_data, (void)current_frame;
  102498. if(local__fwrite(buffer, sizeof(FLAC__byte), bytes, encoder->private_->file) == bytes) {
  102499. FLAC__bool call_it = 0 != encoder->private_->progress_callback && (
  102500. #if FLAC__HAS_OGG
  102501. /* We would like to be able to use 'samples > 0' in the
  102502. * clause here but currently because of the nature of our
  102503. * Ogg writing implementation, 'samples' is always 0 (see
  102504. * ogg_encoder_aspect.c). The downside is extra progress
  102505. * callbacks.
  102506. */
  102507. encoder->private_->is_ogg? true :
  102508. #endif
  102509. samples > 0
  102510. );
  102511. if(call_it) {
  102512. /* NOTE: We have to add +bytes, +samples, and +1 to the stats
  102513. * because at this point in the callback chain, the stats
  102514. * have not been updated. Only after we return and control
  102515. * gets back to write_frame_() are the stats updated
  102516. */
  102517. 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);
  102518. }
  102519. return FLAC__STREAM_ENCODER_WRITE_STATUS_OK;
  102520. }
  102521. else
  102522. return FLAC__STREAM_ENCODER_WRITE_STATUS_FATAL_ERROR;
  102523. }
  102524. /*
  102525. * This will forcibly set stdout to binary mode (for OSes that require it)
  102526. */
  102527. FILE *get_binary_stdout_(void)
  102528. {
  102529. /* if something breaks here it is probably due to the presence or
  102530. * absence of an underscore before the identifiers 'setmode',
  102531. * 'fileno', and/or 'O_BINARY'; check your system header files.
  102532. */
  102533. #if defined _MSC_VER || defined __MINGW32__
  102534. _setmode(_fileno(stdout), _O_BINARY);
  102535. #elif defined __CYGWIN__
  102536. /* almost certainly not needed for any modern Cygwin, but let's be safe... */
  102537. setmode(_fileno(stdout), _O_BINARY);
  102538. #elif defined __EMX__
  102539. setmode(fileno(stdout), O_BINARY);
  102540. #endif
  102541. return stdout;
  102542. }
  102543. #endif
  102544. /*** End of inlined file: stream_encoder.c ***/
  102545. /*** Start of inlined file: stream_encoder_framing.c ***/
  102546. /*** Start of inlined file: juce_FlacHeader.h ***/
  102547. // This file is included at the start of each FLAC .c file, just to do a few housekeeping
  102548. // tasks..
  102549. #define VERSION "1.2.1"
  102550. #define FLAC__NO_DLL 1
  102551. #if JUCE_MSVC
  102552. #pragma warning (disable: 4267 4127 4244 4996 4100 4701 4702 4013 4133 4206 4312)
  102553. #endif
  102554. #if JUCE_MAC
  102555. #define FLAC__SYS_DARWIN 1
  102556. #endif
  102557. /*** End of inlined file: juce_FlacHeader.h ***/
  102558. #if JUCE_USE_FLAC
  102559. #if HAVE_CONFIG_H
  102560. # include <config.h>
  102561. #endif
  102562. #include <stdio.h>
  102563. #include <string.h> /* for strlen() */
  102564. #ifdef max
  102565. #undef max
  102566. #endif
  102567. #define max(x,y) ((x)>(y)?(x):(y))
  102568. static FLAC__bool add_entropy_coding_method_(FLAC__BitWriter *bw, const FLAC__EntropyCodingMethod *method);
  102569. 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);
  102570. FLAC__bool FLAC__add_metadata_block(const FLAC__StreamMetadata *metadata, FLAC__BitWriter *bw)
  102571. {
  102572. unsigned i, j;
  102573. const unsigned vendor_string_length = (unsigned)strlen(FLAC__VENDOR_STRING);
  102574. if(!FLAC__bitwriter_write_raw_uint32(bw, metadata->is_last, FLAC__STREAM_METADATA_IS_LAST_LEN))
  102575. return false;
  102576. if(!FLAC__bitwriter_write_raw_uint32(bw, metadata->type, FLAC__STREAM_METADATA_TYPE_LEN))
  102577. return false;
  102578. /*
  102579. * First, for VORBIS_COMMENTs, adjust the length to reflect our vendor string
  102580. */
  102581. i = metadata->length;
  102582. if(metadata->type == FLAC__METADATA_TYPE_VORBIS_COMMENT) {
  102583. FLAC__ASSERT(metadata->data.vorbis_comment.vendor_string.length == 0 || 0 != metadata->data.vorbis_comment.vendor_string.entry);
  102584. i -= metadata->data.vorbis_comment.vendor_string.length;
  102585. i += vendor_string_length;
  102586. }
  102587. FLAC__ASSERT(i < (1u << FLAC__STREAM_METADATA_LENGTH_LEN));
  102588. if(!FLAC__bitwriter_write_raw_uint32(bw, i, FLAC__STREAM_METADATA_LENGTH_LEN))
  102589. return false;
  102590. switch(metadata->type) {
  102591. case FLAC__METADATA_TYPE_STREAMINFO:
  102592. FLAC__ASSERT(metadata->data.stream_info.min_blocksize < (1u << FLAC__STREAM_METADATA_STREAMINFO_MIN_BLOCK_SIZE_LEN));
  102593. if(!FLAC__bitwriter_write_raw_uint32(bw, metadata->data.stream_info.min_blocksize, FLAC__STREAM_METADATA_STREAMINFO_MIN_BLOCK_SIZE_LEN))
  102594. return false;
  102595. FLAC__ASSERT(metadata->data.stream_info.max_blocksize < (1u << FLAC__STREAM_METADATA_STREAMINFO_MAX_BLOCK_SIZE_LEN));
  102596. if(!FLAC__bitwriter_write_raw_uint32(bw, metadata->data.stream_info.max_blocksize, FLAC__STREAM_METADATA_STREAMINFO_MAX_BLOCK_SIZE_LEN))
  102597. return false;
  102598. FLAC__ASSERT(metadata->data.stream_info.min_framesize < (1u << FLAC__STREAM_METADATA_STREAMINFO_MIN_FRAME_SIZE_LEN));
  102599. if(!FLAC__bitwriter_write_raw_uint32(bw, metadata->data.stream_info.min_framesize, FLAC__STREAM_METADATA_STREAMINFO_MIN_FRAME_SIZE_LEN))
  102600. return false;
  102601. FLAC__ASSERT(metadata->data.stream_info.max_framesize < (1u << FLAC__STREAM_METADATA_STREAMINFO_MAX_FRAME_SIZE_LEN));
  102602. if(!FLAC__bitwriter_write_raw_uint32(bw, metadata->data.stream_info.max_framesize, FLAC__STREAM_METADATA_STREAMINFO_MAX_FRAME_SIZE_LEN))
  102603. return false;
  102604. FLAC__ASSERT(FLAC__format_sample_rate_is_valid(metadata->data.stream_info.sample_rate));
  102605. if(!FLAC__bitwriter_write_raw_uint32(bw, metadata->data.stream_info.sample_rate, FLAC__STREAM_METADATA_STREAMINFO_SAMPLE_RATE_LEN))
  102606. return false;
  102607. FLAC__ASSERT(metadata->data.stream_info.channels > 0);
  102608. FLAC__ASSERT(metadata->data.stream_info.channels <= (1u << FLAC__STREAM_METADATA_STREAMINFO_CHANNELS_LEN));
  102609. if(!FLAC__bitwriter_write_raw_uint32(bw, metadata->data.stream_info.channels-1, FLAC__STREAM_METADATA_STREAMINFO_CHANNELS_LEN))
  102610. return false;
  102611. FLAC__ASSERT(metadata->data.stream_info.bits_per_sample > 0);
  102612. FLAC__ASSERT(metadata->data.stream_info.bits_per_sample <= (1u << FLAC__STREAM_METADATA_STREAMINFO_BITS_PER_SAMPLE_LEN));
  102613. if(!FLAC__bitwriter_write_raw_uint32(bw, metadata->data.stream_info.bits_per_sample-1, FLAC__STREAM_METADATA_STREAMINFO_BITS_PER_SAMPLE_LEN))
  102614. return false;
  102615. if(!FLAC__bitwriter_write_raw_uint64(bw, metadata->data.stream_info.total_samples, FLAC__STREAM_METADATA_STREAMINFO_TOTAL_SAMPLES_LEN))
  102616. return false;
  102617. if(!FLAC__bitwriter_write_byte_block(bw, metadata->data.stream_info.md5sum, 16))
  102618. return false;
  102619. break;
  102620. case FLAC__METADATA_TYPE_PADDING:
  102621. if(!FLAC__bitwriter_write_zeroes(bw, metadata->length * 8))
  102622. return false;
  102623. break;
  102624. case FLAC__METADATA_TYPE_APPLICATION:
  102625. if(!FLAC__bitwriter_write_byte_block(bw, metadata->data.application.id, FLAC__STREAM_METADATA_APPLICATION_ID_LEN / 8))
  102626. return false;
  102627. if(!FLAC__bitwriter_write_byte_block(bw, metadata->data.application.data, metadata->length - (FLAC__STREAM_METADATA_APPLICATION_ID_LEN / 8)))
  102628. return false;
  102629. break;
  102630. case FLAC__METADATA_TYPE_SEEKTABLE:
  102631. for(i = 0; i < metadata->data.seek_table.num_points; i++) {
  102632. if(!FLAC__bitwriter_write_raw_uint64(bw, metadata->data.seek_table.points[i].sample_number, FLAC__STREAM_METADATA_SEEKPOINT_SAMPLE_NUMBER_LEN))
  102633. return false;
  102634. if(!FLAC__bitwriter_write_raw_uint64(bw, metadata->data.seek_table.points[i].stream_offset, FLAC__STREAM_METADATA_SEEKPOINT_STREAM_OFFSET_LEN))
  102635. return false;
  102636. if(!FLAC__bitwriter_write_raw_uint32(bw, metadata->data.seek_table.points[i].frame_samples, FLAC__STREAM_METADATA_SEEKPOINT_FRAME_SAMPLES_LEN))
  102637. return false;
  102638. }
  102639. break;
  102640. case FLAC__METADATA_TYPE_VORBIS_COMMENT:
  102641. if(!FLAC__bitwriter_write_raw_uint32_little_endian(bw, vendor_string_length))
  102642. return false;
  102643. if(!FLAC__bitwriter_write_byte_block(bw, (const FLAC__byte*)FLAC__VENDOR_STRING, vendor_string_length))
  102644. return false;
  102645. if(!FLAC__bitwriter_write_raw_uint32_little_endian(bw, metadata->data.vorbis_comment.num_comments))
  102646. return false;
  102647. for(i = 0; i < metadata->data.vorbis_comment.num_comments; i++) {
  102648. if(!FLAC__bitwriter_write_raw_uint32_little_endian(bw, metadata->data.vorbis_comment.comments[i].length))
  102649. return false;
  102650. if(!FLAC__bitwriter_write_byte_block(bw, metadata->data.vorbis_comment.comments[i].entry, metadata->data.vorbis_comment.comments[i].length))
  102651. return false;
  102652. }
  102653. break;
  102654. case FLAC__METADATA_TYPE_CUESHEET:
  102655. FLAC__ASSERT(FLAC__STREAM_METADATA_CUESHEET_MEDIA_CATALOG_NUMBER_LEN % 8 == 0);
  102656. 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))
  102657. return false;
  102658. if(!FLAC__bitwriter_write_raw_uint64(bw, metadata->data.cue_sheet.lead_in, FLAC__STREAM_METADATA_CUESHEET_LEAD_IN_LEN))
  102659. return false;
  102660. if(!FLAC__bitwriter_write_raw_uint32(bw, metadata->data.cue_sheet.is_cd? 1 : 0, FLAC__STREAM_METADATA_CUESHEET_IS_CD_LEN))
  102661. return false;
  102662. if(!FLAC__bitwriter_write_zeroes(bw, FLAC__STREAM_METADATA_CUESHEET_RESERVED_LEN))
  102663. return false;
  102664. if(!FLAC__bitwriter_write_raw_uint32(bw, metadata->data.cue_sheet.num_tracks, FLAC__STREAM_METADATA_CUESHEET_NUM_TRACKS_LEN))
  102665. return false;
  102666. for(i = 0; i < metadata->data.cue_sheet.num_tracks; i++) {
  102667. const FLAC__StreamMetadata_CueSheet_Track *track = metadata->data.cue_sheet.tracks + i;
  102668. if(!FLAC__bitwriter_write_raw_uint64(bw, track->offset, FLAC__STREAM_METADATA_CUESHEET_TRACK_OFFSET_LEN))
  102669. return false;
  102670. if(!FLAC__bitwriter_write_raw_uint32(bw, track->number, FLAC__STREAM_METADATA_CUESHEET_TRACK_NUMBER_LEN))
  102671. return false;
  102672. FLAC__ASSERT(FLAC__STREAM_METADATA_CUESHEET_TRACK_ISRC_LEN % 8 == 0);
  102673. if(!FLAC__bitwriter_write_byte_block(bw, (const FLAC__byte*)track->isrc, FLAC__STREAM_METADATA_CUESHEET_TRACK_ISRC_LEN/8))
  102674. return false;
  102675. if(!FLAC__bitwriter_write_raw_uint32(bw, track->type, FLAC__STREAM_METADATA_CUESHEET_TRACK_TYPE_LEN))
  102676. return false;
  102677. if(!FLAC__bitwriter_write_raw_uint32(bw, track->pre_emphasis, FLAC__STREAM_METADATA_CUESHEET_TRACK_PRE_EMPHASIS_LEN))
  102678. return false;
  102679. if(!FLAC__bitwriter_write_zeroes(bw, FLAC__STREAM_METADATA_CUESHEET_TRACK_RESERVED_LEN))
  102680. return false;
  102681. if(!FLAC__bitwriter_write_raw_uint32(bw, track->num_indices, FLAC__STREAM_METADATA_CUESHEET_TRACK_NUM_INDICES_LEN))
  102682. return false;
  102683. for(j = 0; j < track->num_indices; j++) {
  102684. const FLAC__StreamMetadata_CueSheet_Index *index = track->indices + j;
  102685. if(!FLAC__bitwriter_write_raw_uint64(bw, index->offset, FLAC__STREAM_METADATA_CUESHEET_INDEX_OFFSET_LEN))
  102686. return false;
  102687. if(!FLAC__bitwriter_write_raw_uint32(bw, index->number, FLAC__STREAM_METADATA_CUESHEET_INDEX_NUMBER_LEN))
  102688. return false;
  102689. if(!FLAC__bitwriter_write_zeroes(bw, FLAC__STREAM_METADATA_CUESHEET_INDEX_RESERVED_LEN))
  102690. return false;
  102691. }
  102692. }
  102693. break;
  102694. case FLAC__METADATA_TYPE_PICTURE:
  102695. {
  102696. size_t len;
  102697. if(!FLAC__bitwriter_write_raw_uint32(bw, metadata->data.picture.type, FLAC__STREAM_METADATA_PICTURE_TYPE_LEN))
  102698. return false;
  102699. len = strlen(metadata->data.picture.mime_type);
  102700. if(!FLAC__bitwriter_write_raw_uint32(bw, len, FLAC__STREAM_METADATA_PICTURE_MIME_TYPE_LENGTH_LEN))
  102701. return false;
  102702. if(!FLAC__bitwriter_write_byte_block(bw, (const FLAC__byte*)metadata->data.picture.mime_type, len))
  102703. return false;
  102704. len = strlen((const char *)metadata->data.picture.description);
  102705. if(!FLAC__bitwriter_write_raw_uint32(bw, len, FLAC__STREAM_METADATA_PICTURE_DESCRIPTION_LENGTH_LEN))
  102706. return false;
  102707. if(!FLAC__bitwriter_write_byte_block(bw, metadata->data.picture.description, len))
  102708. return false;
  102709. if(!FLAC__bitwriter_write_raw_uint32(bw, metadata->data.picture.width, FLAC__STREAM_METADATA_PICTURE_WIDTH_LEN))
  102710. return false;
  102711. if(!FLAC__bitwriter_write_raw_uint32(bw, metadata->data.picture.height, FLAC__STREAM_METADATA_PICTURE_HEIGHT_LEN))
  102712. return false;
  102713. if(!FLAC__bitwriter_write_raw_uint32(bw, metadata->data.picture.depth, FLAC__STREAM_METADATA_PICTURE_DEPTH_LEN))
  102714. return false;
  102715. if(!FLAC__bitwriter_write_raw_uint32(bw, metadata->data.picture.colors, FLAC__STREAM_METADATA_PICTURE_COLORS_LEN))
  102716. return false;
  102717. if(!FLAC__bitwriter_write_raw_uint32(bw, metadata->data.picture.data_length, FLAC__STREAM_METADATA_PICTURE_DATA_LENGTH_LEN))
  102718. return false;
  102719. if(!FLAC__bitwriter_write_byte_block(bw, metadata->data.picture.data, metadata->data.picture.data_length))
  102720. return false;
  102721. }
  102722. break;
  102723. default:
  102724. if(!FLAC__bitwriter_write_byte_block(bw, metadata->data.unknown.data, metadata->length))
  102725. return false;
  102726. break;
  102727. }
  102728. FLAC__ASSERT(FLAC__bitwriter_is_byte_aligned(bw));
  102729. return true;
  102730. }
  102731. FLAC__bool FLAC__frame_add_header(const FLAC__FrameHeader *header, FLAC__BitWriter *bw)
  102732. {
  102733. unsigned u, blocksize_hint, sample_rate_hint;
  102734. FLAC__byte crc;
  102735. FLAC__ASSERT(FLAC__bitwriter_is_byte_aligned(bw));
  102736. if(!FLAC__bitwriter_write_raw_uint32(bw, FLAC__FRAME_HEADER_SYNC, FLAC__FRAME_HEADER_SYNC_LEN))
  102737. return false;
  102738. if(!FLAC__bitwriter_write_raw_uint32(bw, 0, FLAC__FRAME_HEADER_RESERVED_LEN))
  102739. return false;
  102740. if(!FLAC__bitwriter_write_raw_uint32(bw, (header->number_type == FLAC__FRAME_NUMBER_TYPE_FRAME_NUMBER)? 0 : 1, FLAC__FRAME_HEADER_BLOCKING_STRATEGY_LEN))
  102741. return false;
  102742. FLAC__ASSERT(header->blocksize > 0 && header->blocksize <= FLAC__MAX_BLOCK_SIZE);
  102743. /* when this assertion holds true, any legal blocksize can be expressed in the frame header */
  102744. FLAC__ASSERT(FLAC__MAX_BLOCK_SIZE <= 65535u);
  102745. blocksize_hint = 0;
  102746. switch(header->blocksize) {
  102747. case 192: u = 1; break;
  102748. case 576: u = 2; break;
  102749. case 1152: u = 3; break;
  102750. case 2304: u = 4; break;
  102751. case 4608: u = 5; break;
  102752. case 256: u = 8; break;
  102753. case 512: u = 9; break;
  102754. case 1024: u = 10; break;
  102755. case 2048: u = 11; break;
  102756. case 4096: u = 12; break;
  102757. case 8192: u = 13; break;
  102758. case 16384: u = 14; break;
  102759. case 32768: u = 15; break;
  102760. default:
  102761. if(header->blocksize <= 0x100)
  102762. blocksize_hint = u = 6;
  102763. else
  102764. blocksize_hint = u = 7;
  102765. break;
  102766. }
  102767. if(!FLAC__bitwriter_write_raw_uint32(bw, u, FLAC__FRAME_HEADER_BLOCK_SIZE_LEN))
  102768. return false;
  102769. FLAC__ASSERT(FLAC__format_sample_rate_is_valid(header->sample_rate));
  102770. sample_rate_hint = 0;
  102771. switch(header->sample_rate) {
  102772. case 88200: u = 1; break;
  102773. case 176400: u = 2; break;
  102774. case 192000: u = 3; break;
  102775. case 8000: u = 4; break;
  102776. case 16000: u = 5; break;
  102777. case 22050: u = 6; break;
  102778. case 24000: u = 7; break;
  102779. case 32000: u = 8; break;
  102780. case 44100: u = 9; break;
  102781. case 48000: u = 10; break;
  102782. case 96000: u = 11; break;
  102783. default:
  102784. if(header->sample_rate <= 255000 && header->sample_rate % 1000 == 0)
  102785. sample_rate_hint = u = 12;
  102786. else if(header->sample_rate % 10 == 0)
  102787. sample_rate_hint = u = 14;
  102788. else if(header->sample_rate <= 0xffff)
  102789. sample_rate_hint = u = 13;
  102790. else
  102791. u = 0;
  102792. break;
  102793. }
  102794. if(!FLAC__bitwriter_write_raw_uint32(bw, u, FLAC__FRAME_HEADER_SAMPLE_RATE_LEN))
  102795. return false;
  102796. FLAC__ASSERT(header->channels > 0 && header->channels <= (1u << FLAC__STREAM_METADATA_STREAMINFO_CHANNELS_LEN) && header->channels <= FLAC__MAX_CHANNELS);
  102797. switch(header->channel_assignment) {
  102798. case FLAC__CHANNEL_ASSIGNMENT_INDEPENDENT:
  102799. u = header->channels - 1;
  102800. break;
  102801. case FLAC__CHANNEL_ASSIGNMENT_LEFT_SIDE:
  102802. FLAC__ASSERT(header->channels == 2);
  102803. u = 8;
  102804. break;
  102805. case FLAC__CHANNEL_ASSIGNMENT_RIGHT_SIDE:
  102806. FLAC__ASSERT(header->channels == 2);
  102807. u = 9;
  102808. break;
  102809. case FLAC__CHANNEL_ASSIGNMENT_MID_SIDE:
  102810. FLAC__ASSERT(header->channels == 2);
  102811. u = 10;
  102812. break;
  102813. default:
  102814. FLAC__ASSERT(0);
  102815. }
  102816. if(!FLAC__bitwriter_write_raw_uint32(bw, u, FLAC__FRAME_HEADER_CHANNEL_ASSIGNMENT_LEN))
  102817. return false;
  102818. FLAC__ASSERT(header->bits_per_sample > 0 && header->bits_per_sample <= (1u << FLAC__STREAM_METADATA_STREAMINFO_BITS_PER_SAMPLE_LEN));
  102819. switch(header->bits_per_sample) {
  102820. case 8 : u = 1; break;
  102821. case 12: u = 2; break;
  102822. case 16: u = 4; break;
  102823. case 20: u = 5; break;
  102824. case 24: u = 6; break;
  102825. default: u = 0; break;
  102826. }
  102827. if(!FLAC__bitwriter_write_raw_uint32(bw, u, FLAC__FRAME_HEADER_BITS_PER_SAMPLE_LEN))
  102828. return false;
  102829. if(!FLAC__bitwriter_write_raw_uint32(bw, 0, FLAC__FRAME_HEADER_ZERO_PAD_LEN))
  102830. return false;
  102831. if(header->number_type == FLAC__FRAME_NUMBER_TYPE_FRAME_NUMBER) {
  102832. if(!FLAC__bitwriter_write_utf8_uint32(bw, header->number.frame_number))
  102833. return false;
  102834. }
  102835. else {
  102836. if(!FLAC__bitwriter_write_utf8_uint64(bw, header->number.sample_number))
  102837. return false;
  102838. }
  102839. if(blocksize_hint)
  102840. if(!FLAC__bitwriter_write_raw_uint32(bw, header->blocksize-1, (blocksize_hint==6)? 8:16))
  102841. return false;
  102842. switch(sample_rate_hint) {
  102843. case 12:
  102844. if(!FLAC__bitwriter_write_raw_uint32(bw, header->sample_rate / 1000, 8))
  102845. return false;
  102846. break;
  102847. case 13:
  102848. if(!FLAC__bitwriter_write_raw_uint32(bw, header->sample_rate, 16))
  102849. return false;
  102850. break;
  102851. case 14:
  102852. if(!FLAC__bitwriter_write_raw_uint32(bw, header->sample_rate / 10, 16))
  102853. return false;
  102854. break;
  102855. }
  102856. /* write the CRC */
  102857. if(!FLAC__bitwriter_get_write_crc8(bw, &crc))
  102858. return false;
  102859. if(!FLAC__bitwriter_write_raw_uint32(bw, crc, FLAC__FRAME_HEADER_CRC_LEN))
  102860. return false;
  102861. return true;
  102862. }
  102863. FLAC__bool FLAC__subframe_add_constant(const FLAC__Subframe_Constant *subframe, unsigned subframe_bps, unsigned wasted_bits, FLAC__BitWriter *bw)
  102864. {
  102865. FLAC__bool ok;
  102866. ok =
  102867. 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) &&
  102868. (wasted_bits? FLAC__bitwriter_write_unary_unsigned(bw, wasted_bits-1) : true) &&
  102869. FLAC__bitwriter_write_raw_int32(bw, subframe->value, subframe_bps)
  102870. ;
  102871. return ok;
  102872. }
  102873. FLAC__bool FLAC__subframe_add_fixed(const FLAC__Subframe_Fixed *subframe, unsigned residual_samples, unsigned subframe_bps, unsigned wasted_bits, FLAC__BitWriter *bw)
  102874. {
  102875. unsigned i;
  102876. 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))
  102877. return false;
  102878. if(wasted_bits)
  102879. if(!FLAC__bitwriter_write_unary_unsigned(bw, wasted_bits-1))
  102880. return false;
  102881. for(i = 0; i < subframe->order; i++)
  102882. if(!FLAC__bitwriter_write_raw_int32(bw, subframe->warmup[i], subframe_bps))
  102883. return false;
  102884. if(!add_entropy_coding_method_(bw, &subframe->entropy_coding_method))
  102885. return false;
  102886. switch(subframe->entropy_coding_method.type) {
  102887. case FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE:
  102888. case FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE2:
  102889. if(!add_residual_partitioned_rice_(
  102890. bw,
  102891. subframe->residual,
  102892. residual_samples,
  102893. subframe->order,
  102894. subframe->entropy_coding_method.data.partitioned_rice.contents->parameters,
  102895. subframe->entropy_coding_method.data.partitioned_rice.contents->raw_bits,
  102896. subframe->entropy_coding_method.data.partitioned_rice.order,
  102897. /*is_extended=*/subframe->entropy_coding_method.type == FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE2
  102898. ))
  102899. return false;
  102900. break;
  102901. default:
  102902. FLAC__ASSERT(0);
  102903. }
  102904. return true;
  102905. }
  102906. FLAC__bool FLAC__subframe_add_lpc(const FLAC__Subframe_LPC *subframe, unsigned residual_samples, unsigned subframe_bps, unsigned wasted_bits, FLAC__BitWriter *bw)
  102907. {
  102908. unsigned i;
  102909. 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))
  102910. return false;
  102911. if(wasted_bits)
  102912. if(!FLAC__bitwriter_write_unary_unsigned(bw, wasted_bits-1))
  102913. return false;
  102914. for(i = 0; i < subframe->order; i++)
  102915. if(!FLAC__bitwriter_write_raw_int32(bw, subframe->warmup[i], subframe_bps))
  102916. return false;
  102917. if(!FLAC__bitwriter_write_raw_uint32(bw, subframe->qlp_coeff_precision-1, FLAC__SUBFRAME_LPC_QLP_COEFF_PRECISION_LEN))
  102918. return false;
  102919. if(!FLAC__bitwriter_write_raw_int32(bw, subframe->quantization_level, FLAC__SUBFRAME_LPC_QLP_SHIFT_LEN))
  102920. return false;
  102921. for(i = 0; i < subframe->order; i++)
  102922. if(!FLAC__bitwriter_write_raw_int32(bw, subframe->qlp_coeff[i], subframe->qlp_coeff_precision))
  102923. return false;
  102924. if(!add_entropy_coding_method_(bw, &subframe->entropy_coding_method))
  102925. return false;
  102926. switch(subframe->entropy_coding_method.type) {
  102927. case FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE:
  102928. case FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE2:
  102929. if(!add_residual_partitioned_rice_(
  102930. bw,
  102931. subframe->residual,
  102932. residual_samples,
  102933. subframe->order,
  102934. subframe->entropy_coding_method.data.partitioned_rice.contents->parameters,
  102935. subframe->entropy_coding_method.data.partitioned_rice.contents->raw_bits,
  102936. subframe->entropy_coding_method.data.partitioned_rice.order,
  102937. /*is_extended=*/subframe->entropy_coding_method.type == FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE2
  102938. ))
  102939. return false;
  102940. break;
  102941. default:
  102942. FLAC__ASSERT(0);
  102943. }
  102944. return true;
  102945. }
  102946. FLAC__bool FLAC__subframe_add_verbatim(const FLAC__Subframe_Verbatim *subframe, unsigned samples, unsigned subframe_bps, unsigned wasted_bits, FLAC__BitWriter *bw)
  102947. {
  102948. unsigned i;
  102949. const FLAC__int32 *signal = subframe->data;
  102950. 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))
  102951. return false;
  102952. if(wasted_bits)
  102953. if(!FLAC__bitwriter_write_unary_unsigned(bw, wasted_bits-1))
  102954. return false;
  102955. for(i = 0; i < samples; i++)
  102956. if(!FLAC__bitwriter_write_raw_int32(bw, signal[i], subframe_bps))
  102957. return false;
  102958. return true;
  102959. }
  102960. FLAC__bool add_entropy_coding_method_(FLAC__BitWriter *bw, const FLAC__EntropyCodingMethod *method)
  102961. {
  102962. if(!FLAC__bitwriter_write_raw_uint32(bw, method->type, FLAC__ENTROPY_CODING_METHOD_TYPE_LEN))
  102963. return false;
  102964. switch(method->type) {
  102965. case FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE:
  102966. case FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE2:
  102967. if(!FLAC__bitwriter_write_raw_uint32(bw, method->data.partitioned_rice.order, FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE_ORDER_LEN))
  102968. return false;
  102969. break;
  102970. default:
  102971. FLAC__ASSERT(0);
  102972. }
  102973. return true;
  102974. }
  102975. 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)
  102976. {
  102977. const unsigned plen = is_extended? FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE2_PARAMETER_LEN : FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE_PARAMETER_LEN;
  102978. const unsigned pesc = is_extended? FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE2_ESCAPE_PARAMETER : FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE_ESCAPE_PARAMETER;
  102979. if(partition_order == 0) {
  102980. unsigned i;
  102981. if(raw_bits[0] == 0) {
  102982. if(!FLAC__bitwriter_write_raw_uint32(bw, rice_parameters[0], plen))
  102983. return false;
  102984. if(!FLAC__bitwriter_write_rice_signed_block(bw, residual, residual_samples, rice_parameters[0]))
  102985. return false;
  102986. }
  102987. else {
  102988. FLAC__ASSERT(rice_parameters[0] == 0);
  102989. if(!FLAC__bitwriter_write_raw_uint32(bw, pesc, plen))
  102990. return false;
  102991. if(!FLAC__bitwriter_write_raw_uint32(bw, raw_bits[0], FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE_RAW_LEN))
  102992. return false;
  102993. for(i = 0; i < residual_samples; i++) {
  102994. if(!FLAC__bitwriter_write_raw_int32(bw, residual[i], raw_bits[0]))
  102995. return false;
  102996. }
  102997. }
  102998. return true;
  102999. }
  103000. else {
  103001. unsigned i, j, k = 0, k_last = 0;
  103002. unsigned partition_samples;
  103003. const unsigned default_partition_samples = (residual_samples+predictor_order) >> partition_order;
  103004. for(i = 0; i < (1u<<partition_order); i++) {
  103005. partition_samples = default_partition_samples;
  103006. if(i == 0)
  103007. partition_samples -= predictor_order;
  103008. k += partition_samples;
  103009. if(raw_bits[i] == 0) {
  103010. if(!FLAC__bitwriter_write_raw_uint32(bw, rice_parameters[i], plen))
  103011. return false;
  103012. if(!FLAC__bitwriter_write_rice_signed_block(bw, residual+k_last, k-k_last, rice_parameters[i]))
  103013. return false;
  103014. }
  103015. else {
  103016. if(!FLAC__bitwriter_write_raw_uint32(bw, pesc, plen))
  103017. return false;
  103018. if(!FLAC__bitwriter_write_raw_uint32(bw, raw_bits[i], FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE_RAW_LEN))
  103019. return false;
  103020. for(j = k_last; j < k; j++) {
  103021. if(!FLAC__bitwriter_write_raw_int32(bw, residual[j], raw_bits[i]))
  103022. return false;
  103023. }
  103024. }
  103025. k_last = k;
  103026. }
  103027. return true;
  103028. }
  103029. }
  103030. #endif
  103031. /*** End of inlined file: stream_encoder_framing.c ***/
  103032. /*** Start of inlined file: window_flac.c ***/
  103033. /*** Start of inlined file: juce_FlacHeader.h ***/
  103034. // This file is included at the start of each FLAC .c file, just to do a few housekeeping
  103035. // tasks..
  103036. #define VERSION "1.2.1"
  103037. #define FLAC__NO_DLL 1
  103038. #if JUCE_MSVC
  103039. #pragma warning (disable: 4267 4127 4244 4996 4100 4701 4702 4013 4133 4206 4312)
  103040. #endif
  103041. #if JUCE_MAC
  103042. #define FLAC__SYS_DARWIN 1
  103043. #endif
  103044. /*** End of inlined file: juce_FlacHeader.h ***/
  103045. #if JUCE_USE_FLAC
  103046. #if HAVE_CONFIG_H
  103047. # include <config.h>
  103048. #endif
  103049. #include <math.h>
  103050. #ifndef FLAC__INTEGER_ONLY_LIBRARY
  103051. #ifndef M_PI
  103052. /* math.h in VC++ doesn't seem to have this (how Microsoft is that?) */
  103053. #define M_PI 3.14159265358979323846
  103054. #endif
  103055. void FLAC__window_bartlett(FLAC__real *window, const FLAC__int32 L)
  103056. {
  103057. const FLAC__int32 N = L - 1;
  103058. FLAC__int32 n;
  103059. if (L & 1) {
  103060. for (n = 0; n <= N/2; n++)
  103061. window[n] = 2.0f * n / (float)N;
  103062. for (; n <= N; n++)
  103063. window[n] = 2.0f - 2.0f * n / (float)N;
  103064. }
  103065. else {
  103066. for (n = 0; n <= L/2-1; n++)
  103067. window[n] = 2.0f * n / (float)N;
  103068. for (; n <= N; n++)
  103069. window[n] = 2.0f - 2.0f * (N-n) / (float)N;
  103070. }
  103071. }
  103072. void FLAC__window_bartlett_hann(FLAC__real *window, const FLAC__int32 L)
  103073. {
  103074. const FLAC__int32 N = L - 1;
  103075. FLAC__int32 n;
  103076. for (n = 0; n < L; n++)
  103077. 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)));
  103078. }
  103079. void FLAC__window_blackman(FLAC__real *window, const FLAC__int32 L)
  103080. {
  103081. const FLAC__int32 N = L - 1;
  103082. FLAC__int32 n;
  103083. for (n = 0; n < L; n++)
  103084. window[n] = (FLAC__real)(0.42f - 0.5f * cos(2.0f * M_PI * n / N) + 0.08f * cos(4.0f * M_PI * n / N));
  103085. }
  103086. /* 4-term -92dB side-lobe */
  103087. void FLAC__window_blackman_harris_4term_92db_sidelobe(FLAC__real *window, const FLAC__int32 L)
  103088. {
  103089. const FLAC__int32 N = L - 1;
  103090. FLAC__int32 n;
  103091. for (n = 0; n <= N; n++)
  103092. 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));
  103093. }
  103094. void FLAC__window_connes(FLAC__real *window, const FLAC__int32 L)
  103095. {
  103096. const FLAC__int32 N = L - 1;
  103097. const double N2 = (double)N / 2.;
  103098. FLAC__int32 n;
  103099. for (n = 0; n <= N; n++) {
  103100. double k = ((double)n - N2) / N2;
  103101. k = 1.0f - k * k;
  103102. window[n] = (FLAC__real)(k * k);
  103103. }
  103104. }
  103105. void FLAC__window_flattop(FLAC__real *window, const FLAC__int32 L)
  103106. {
  103107. const FLAC__int32 N = L - 1;
  103108. FLAC__int32 n;
  103109. for (n = 0; n < L; n++)
  103110. 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));
  103111. }
  103112. void FLAC__window_gauss(FLAC__real *window, const FLAC__int32 L, const FLAC__real stddev)
  103113. {
  103114. const FLAC__int32 N = L - 1;
  103115. const double N2 = (double)N / 2.;
  103116. FLAC__int32 n;
  103117. for (n = 0; n <= N; n++) {
  103118. const double k = ((double)n - N2) / (stddev * N2);
  103119. window[n] = (FLAC__real)exp(-0.5f * k * k);
  103120. }
  103121. }
  103122. void FLAC__window_hamming(FLAC__real *window, const FLAC__int32 L)
  103123. {
  103124. const FLAC__int32 N = L - 1;
  103125. FLAC__int32 n;
  103126. for (n = 0; n < L; n++)
  103127. window[n] = (FLAC__real)(0.54f - 0.46f * cos(2.0f * M_PI * n / N));
  103128. }
  103129. void FLAC__window_hann(FLAC__real *window, const FLAC__int32 L)
  103130. {
  103131. const FLAC__int32 N = L - 1;
  103132. FLAC__int32 n;
  103133. for (n = 0; n < L; n++)
  103134. window[n] = (FLAC__real)(0.5f - 0.5f * cos(2.0f * M_PI * n / N));
  103135. }
  103136. void FLAC__window_kaiser_bessel(FLAC__real *window, const FLAC__int32 L)
  103137. {
  103138. const FLAC__int32 N = L - 1;
  103139. FLAC__int32 n;
  103140. for (n = 0; n < L; n++)
  103141. 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));
  103142. }
  103143. void FLAC__window_nuttall(FLAC__real *window, const FLAC__int32 L)
  103144. {
  103145. const FLAC__int32 N = L - 1;
  103146. FLAC__int32 n;
  103147. for (n = 0; n < L; n++)
  103148. 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));
  103149. }
  103150. void FLAC__window_rectangle(FLAC__real *window, const FLAC__int32 L)
  103151. {
  103152. FLAC__int32 n;
  103153. for (n = 0; n < L; n++)
  103154. window[n] = 1.0f;
  103155. }
  103156. void FLAC__window_triangle(FLAC__real *window, const FLAC__int32 L)
  103157. {
  103158. FLAC__int32 n;
  103159. if (L & 1) {
  103160. for (n = 1; n <= L+1/2; n++)
  103161. window[n-1] = 2.0f * n / ((float)L + 1.0f);
  103162. for (; n <= L; n++)
  103163. window[n-1] = - (float)(2 * (L - n + 1)) / ((float)L + 1.0f);
  103164. }
  103165. else {
  103166. for (n = 1; n <= L/2; n++)
  103167. window[n-1] = 2.0f * n / (float)L;
  103168. for (; n <= L; n++)
  103169. window[n-1] = ((float)(2 * (L - n)) + 1.0f) / (float)L;
  103170. }
  103171. }
  103172. void FLAC__window_tukey(FLAC__real *window, const FLAC__int32 L, const FLAC__real p)
  103173. {
  103174. if (p <= 0.0)
  103175. FLAC__window_rectangle(window, L);
  103176. else if (p >= 1.0)
  103177. FLAC__window_hann(window, L);
  103178. else {
  103179. const FLAC__int32 Np = (FLAC__int32)(p / 2.0f * L) - 1;
  103180. FLAC__int32 n;
  103181. /* start with rectangle... */
  103182. FLAC__window_rectangle(window, L);
  103183. /* ...replace ends with hann */
  103184. if (Np > 0) {
  103185. for (n = 0; n <= Np; n++) {
  103186. window[n] = (FLAC__real)(0.5f - 0.5f * cos(M_PI * n / Np));
  103187. window[L-Np-1+n] = (FLAC__real)(0.5f - 0.5f * cos(M_PI * (n+Np) / Np));
  103188. }
  103189. }
  103190. }
  103191. }
  103192. void FLAC__window_welch(FLAC__real *window, const FLAC__int32 L)
  103193. {
  103194. const FLAC__int32 N = L - 1;
  103195. const double N2 = (double)N / 2.;
  103196. FLAC__int32 n;
  103197. for (n = 0; n <= N; n++) {
  103198. const double k = ((double)n - N2) / N2;
  103199. window[n] = (FLAC__real)(1.0f - k * k);
  103200. }
  103201. }
  103202. #endif /* !defined FLAC__INTEGER_ONLY_LIBRARY */
  103203. #endif
  103204. /*** End of inlined file: window_flac.c ***/
  103205. #else
  103206. #include <FLAC/all.h>
  103207. #endif
  103208. }
  103209. #undef max
  103210. #undef min
  103211. #ifdef _MSC_VER
  103212. #pragma warning (pop)
  103213. #endif
  103214. BEGIN_JUCE_NAMESPACE
  103215. static const char* const flacFormatName = "FLAC file";
  103216. static const juce_wchar* const flacExtensions[] = { T(".flac"), 0 };
  103217. class FlacReader : public AudioFormatReader
  103218. {
  103219. public:
  103220. FlacReader (InputStream* const in)
  103221. : AudioFormatReader (in, TRANS (flacFormatName)),
  103222. reservoir (2, 0),
  103223. reservoirStart (0),
  103224. samplesInReservoir (0),
  103225. scanningForLength (false)
  103226. {
  103227. using namespace FlacNamespace;
  103228. lengthInSamples = 0;
  103229. decoder = FLAC__stream_decoder_new();
  103230. ok = FLAC__stream_decoder_init_stream (decoder,
  103231. readCallback_, seekCallback_, tellCallback_, lengthCallback_,
  103232. eofCallback_, writeCallback_, metadataCallback_, errorCallback_,
  103233. this) == FLAC__STREAM_DECODER_INIT_STATUS_OK;
  103234. if (ok)
  103235. {
  103236. FLAC__stream_decoder_process_until_end_of_metadata (decoder);
  103237. if (lengthInSamples == 0 && sampleRate > 0)
  103238. {
  103239. // the length hasn't been stored in the metadata, so we'll need to
  103240. // work it out the length the hard way, by scanning the whole file..
  103241. scanningForLength = true;
  103242. FLAC__stream_decoder_process_until_end_of_stream (decoder);
  103243. scanningForLength = false;
  103244. const int64 tempLength = lengthInSamples;
  103245. FLAC__stream_decoder_reset (decoder);
  103246. FLAC__stream_decoder_process_until_end_of_metadata (decoder);
  103247. lengthInSamples = tempLength;
  103248. }
  103249. }
  103250. }
  103251. ~FlacReader()
  103252. {
  103253. FlacNamespace::FLAC__stream_decoder_delete (decoder);
  103254. }
  103255. void useMetadata (const FlacNamespace::FLAC__StreamMetadata_StreamInfo& info)
  103256. {
  103257. sampleRate = info.sample_rate;
  103258. bitsPerSample = info.bits_per_sample;
  103259. lengthInSamples = (unsigned int) info.total_samples;
  103260. numChannels = info.channels;
  103261. reservoir.setSize (numChannels, 2 * info.max_blocksize, false, false, true);
  103262. }
  103263. // returns the number of samples read
  103264. bool readSamples (int** destSamples, int numDestChannels, int startOffsetInDestBuffer,
  103265. int64 startSampleInFile, int numSamples)
  103266. {
  103267. using namespace FlacNamespace;
  103268. if (! ok)
  103269. return false;
  103270. while (numSamples > 0)
  103271. {
  103272. if (startSampleInFile >= reservoirStart
  103273. && startSampleInFile < reservoirStart + samplesInReservoir)
  103274. {
  103275. const int num = (int) jmin ((int64) numSamples,
  103276. reservoirStart + samplesInReservoir - startSampleInFile);
  103277. jassert (num > 0);
  103278. for (int i = jmin (numDestChannels, reservoir.getNumChannels()); --i >= 0;)
  103279. if (destSamples[i] != 0)
  103280. memcpy (destSamples[i] + startOffsetInDestBuffer,
  103281. reservoir.getSampleData (i, (int) (startSampleInFile - reservoirStart)),
  103282. sizeof (int) * num);
  103283. startOffsetInDestBuffer += num;
  103284. startSampleInFile += num;
  103285. numSamples -= num;
  103286. }
  103287. else
  103288. {
  103289. if (startSampleInFile >= (int) lengthInSamples)
  103290. {
  103291. samplesInReservoir = 0;
  103292. }
  103293. else if (startSampleInFile < reservoirStart
  103294. || startSampleInFile > reservoirStart + jmax (samplesInReservoir, 511))
  103295. {
  103296. // had some problems with flac crashing if the read pos is aligned more
  103297. // accurately than this. Probably fixed in newer versions of the library, though.
  103298. reservoirStart = (int) (startSampleInFile & ~511);
  103299. samplesInReservoir = 0;
  103300. FLAC__stream_decoder_seek_absolute (decoder, (FLAC__uint64) reservoirStart);
  103301. }
  103302. else
  103303. {
  103304. reservoirStart += samplesInReservoir;
  103305. samplesInReservoir = 0;
  103306. FLAC__stream_decoder_process_single (decoder);
  103307. }
  103308. if (samplesInReservoir == 0)
  103309. break;
  103310. }
  103311. }
  103312. if (numSamples > 0)
  103313. {
  103314. for (int i = numDestChannels; --i >= 0;)
  103315. if (destSamples[i] != 0)
  103316. zeromem (destSamples[i] + startOffsetInDestBuffer,
  103317. sizeof (int) * numSamples);
  103318. }
  103319. return true;
  103320. }
  103321. void useSamples (const FlacNamespace::FLAC__int32* const buffer[], int numSamples)
  103322. {
  103323. if (scanningForLength)
  103324. {
  103325. lengthInSamples += numSamples;
  103326. }
  103327. else
  103328. {
  103329. if (numSamples > reservoir.getNumSamples())
  103330. reservoir.setSize (numChannels, numSamples, false, false, true);
  103331. const int bitsToShift = 32 - bitsPerSample;
  103332. for (int i = 0; i < (int) numChannels; ++i)
  103333. {
  103334. const FlacNamespace::FLAC__int32* src = buffer[i];
  103335. int n = i;
  103336. while (src == 0 && n > 0)
  103337. src = buffer [--n];
  103338. if (src != 0)
  103339. {
  103340. int* dest = (int*) reservoir.getSampleData(i);
  103341. for (int j = 0; j < numSamples; ++j)
  103342. dest[j] = src[j] << bitsToShift;
  103343. }
  103344. }
  103345. samplesInReservoir = numSamples;
  103346. }
  103347. }
  103348. static FlacNamespace::FLAC__StreamDecoderReadStatus readCallback_ (const FlacNamespace::FLAC__StreamDecoder*, FlacNamespace::FLAC__byte buffer[], size_t* bytes, void* client_data)
  103349. {
  103350. using namespace FlacNamespace;
  103351. *bytes = (size_t) static_cast <const FlacReader*> (client_data)->input->read (buffer, (int) *bytes);
  103352. return FLAC__STREAM_DECODER_READ_STATUS_CONTINUE;
  103353. }
  103354. static FlacNamespace::FLAC__StreamDecoderSeekStatus seekCallback_ (const FlacNamespace::FLAC__StreamDecoder*, FlacNamespace::FLAC__uint64 absolute_byte_offset, void* client_data)
  103355. {
  103356. using namespace FlacNamespace;
  103357. static_cast <const FlacReader*> (client_data)->input->setPosition ((int) absolute_byte_offset);
  103358. return FLAC__STREAM_DECODER_SEEK_STATUS_OK;
  103359. }
  103360. static FlacNamespace::FLAC__StreamDecoderTellStatus tellCallback_ (const FlacNamespace::FLAC__StreamDecoder*, FlacNamespace::FLAC__uint64* absolute_byte_offset, void* client_data)
  103361. {
  103362. using namespace FlacNamespace;
  103363. *absolute_byte_offset = static_cast <const FlacReader*> (client_data)->input->getPosition();
  103364. return FLAC__STREAM_DECODER_TELL_STATUS_OK;
  103365. }
  103366. static FlacNamespace::FLAC__StreamDecoderLengthStatus lengthCallback_ (const FlacNamespace::FLAC__StreamDecoder*, FlacNamespace::FLAC__uint64* stream_length, void* client_data)
  103367. {
  103368. using namespace FlacNamespace;
  103369. *stream_length = static_cast <const FlacReader*> (client_data)->input->getTotalLength();
  103370. return FLAC__STREAM_DECODER_LENGTH_STATUS_OK;
  103371. }
  103372. static FlacNamespace::FLAC__bool eofCallback_ (const FlacNamespace::FLAC__StreamDecoder*, void* client_data)
  103373. {
  103374. return static_cast <const FlacReader*> (client_data)->input->isExhausted();
  103375. }
  103376. static FlacNamespace::FLAC__StreamDecoderWriteStatus writeCallback_ (const FlacNamespace::FLAC__StreamDecoder*,
  103377. const FlacNamespace::FLAC__Frame* frame,
  103378. const FlacNamespace::FLAC__int32* const buffer[],
  103379. void* client_data)
  103380. {
  103381. using namespace FlacNamespace;
  103382. static_cast <FlacReader*> (client_data)->useSamples (buffer, frame->header.blocksize);
  103383. return FLAC__STREAM_DECODER_WRITE_STATUS_CONTINUE;
  103384. }
  103385. static void metadataCallback_ (const FlacNamespace::FLAC__StreamDecoder*,
  103386. const FlacNamespace::FLAC__StreamMetadata* metadata,
  103387. void* client_data)
  103388. {
  103389. static_cast <FlacReader*> (client_data)->useMetadata (metadata->data.stream_info);
  103390. }
  103391. static void errorCallback_ (const FlacNamespace::FLAC__StreamDecoder*, FlacNamespace::FLAC__StreamDecoderErrorStatus, void*)
  103392. {
  103393. }
  103394. juce_UseDebuggingNewOperator
  103395. private:
  103396. FlacNamespace::FLAC__StreamDecoder* decoder;
  103397. AudioSampleBuffer reservoir;
  103398. int reservoirStart, samplesInReservoir;
  103399. bool ok, scanningForLength;
  103400. FlacReader (const FlacReader&);
  103401. FlacReader& operator= (const FlacReader&);
  103402. };
  103403. class FlacWriter : public AudioFormatWriter
  103404. {
  103405. public:
  103406. FlacWriter (OutputStream* const out,
  103407. const double sampleRate_,
  103408. const int numChannels_,
  103409. const int bitsPerSample_)
  103410. : AudioFormatWriter (out, TRANS (flacFormatName),
  103411. sampleRate_,
  103412. numChannels_,
  103413. bitsPerSample_)
  103414. {
  103415. using namespace FlacNamespace;
  103416. encoder = FLAC__stream_encoder_new();
  103417. FLAC__stream_encoder_set_do_mid_side_stereo (encoder, numChannels == 2);
  103418. FLAC__stream_encoder_set_loose_mid_side_stereo (encoder, numChannels == 2);
  103419. FLAC__stream_encoder_set_channels (encoder, numChannels);
  103420. FLAC__stream_encoder_set_bits_per_sample (encoder, jmin ((unsigned int) 24, bitsPerSample));
  103421. FLAC__stream_encoder_set_sample_rate (encoder, (unsigned int) sampleRate);
  103422. FLAC__stream_encoder_set_blocksize (encoder, 2048);
  103423. FLAC__stream_encoder_set_do_escape_coding (encoder, true);
  103424. ok = FLAC__stream_encoder_init_stream (encoder,
  103425. encodeWriteCallback, encodeSeekCallback,
  103426. encodeTellCallback, encodeMetadataCallback,
  103427. this) == FLAC__STREAM_ENCODER_INIT_STATUS_OK;
  103428. }
  103429. ~FlacWriter()
  103430. {
  103431. if (ok)
  103432. {
  103433. FlacNamespace::FLAC__stream_encoder_finish (encoder);
  103434. output->flush();
  103435. }
  103436. else
  103437. {
  103438. output = 0; // to stop the base class deleting this, as it needs to be returned
  103439. // to the caller of createWriter()
  103440. }
  103441. FlacNamespace::FLAC__stream_encoder_delete (encoder);
  103442. }
  103443. bool write (const int** samplesToWrite, int numSamples)
  103444. {
  103445. using namespace FlacNamespace;
  103446. if (! ok)
  103447. return false;
  103448. int* buf[3];
  103449. const int bitsToShift = 32 - bitsPerSample;
  103450. if (bitsToShift > 0)
  103451. {
  103452. const int numChannelsToWrite = (samplesToWrite[1] == 0) ? 1 : 2;
  103453. temp.setSize (sizeof (int) * numSamples * numChannelsToWrite);
  103454. buf[0] = (int*) temp.getData();
  103455. buf[1] = buf[0] + numSamples;
  103456. buf[2] = 0;
  103457. for (int i = numChannelsToWrite; --i >= 0;)
  103458. {
  103459. if (samplesToWrite[i] != 0)
  103460. {
  103461. for (int j = 0; j < numSamples; ++j)
  103462. buf [i][j] = (samplesToWrite [i][j] >> bitsToShift);
  103463. }
  103464. }
  103465. samplesToWrite = (const int**) buf;
  103466. }
  103467. return FLAC__stream_encoder_process (encoder,
  103468. (const FLAC__int32**) samplesToWrite,
  103469. numSamples) != 0;
  103470. }
  103471. bool writeData (const void* const data, const int size) const
  103472. {
  103473. return output->write (data, size);
  103474. }
  103475. static void packUint32 (FlacNamespace::FLAC__uint32 val, FlacNamespace::FLAC__byte* b, const int bytes)
  103476. {
  103477. using namespace FlacNamespace;
  103478. b += bytes;
  103479. for (int i = 0; i < bytes; ++i)
  103480. {
  103481. *(--b) = (FLAC__byte) (val & 0xff);
  103482. val >>= 8;
  103483. }
  103484. }
  103485. void writeMetaData (const FlacNamespace::FLAC__StreamMetadata* metadata)
  103486. {
  103487. using namespace FlacNamespace;
  103488. const FLAC__StreamMetadata_StreamInfo& info = metadata->data.stream_info;
  103489. unsigned char buffer [FLAC__STREAM_METADATA_STREAMINFO_LENGTH];
  103490. const unsigned int channelsMinus1 = info.channels - 1;
  103491. const unsigned int bitsMinus1 = info.bits_per_sample - 1;
  103492. packUint32 (info.min_blocksize, buffer, 2);
  103493. packUint32 (info.max_blocksize, buffer + 2, 2);
  103494. packUint32 (info.min_framesize, buffer + 4, 3);
  103495. packUint32 (info.max_framesize, buffer + 7, 3);
  103496. buffer[10] = (uint8) ((info.sample_rate >> 12) & 0xff);
  103497. buffer[11] = (uint8) ((info.sample_rate >> 4) & 0xff);
  103498. buffer[12] = (uint8) (((info.sample_rate & 0x0f) << 4) | (channelsMinus1 << 1) | (bitsMinus1 >> 4));
  103499. buffer[13] = (FLAC__byte) (((bitsMinus1 & 0x0f) << 4) | (unsigned int) ((info.total_samples >> 32) & 0x0f));
  103500. packUint32 ((FLAC__uint32) info.total_samples, buffer + 14, 4);
  103501. memcpy (buffer + 18, info.md5sum, 16);
  103502. const bool seekOk = output->setPosition (4);
  103503. (void) seekOk;
  103504. // if this fails, you've given it an output stream that can't seek! It needs
  103505. // to be able to seek back to write the header
  103506. jassert (seekOk);
  103507. output->writeIntBigEndian (FLAC__STREAM_METADATA_STREAMINFO_LENGTH);
  103508. output->write (buffer, FLAC__STREAM_METADATA_STREAMINFO_LENGTH);
  103509. }
  103510. static FlacNamespace::FLAC__StreamEncoderWriteStatus encodeWriteCallback (const FlacNamespace::FLAC__StreamEncoder*,
  103511. const FlacNamespace::FLAC__byte buffer[],
  103512. size_t bytes,
  103513. unsigned int /*samples*/,
  103514. unsigned int /*current_frame*/,
  103515. void* client_data)
  103516. {
  103517. using namespace FlacNamespace;
  103518. return static_cast <FlacWriter*> (client_data)->writeData (buffer, (int) bytes)
  103519. ? FLAC__STREAM_ENCODER_WRITE_STATUS_OK
  103520. : FLAC__STREAM_ENCODER_WRITE_STATUS_FATAL_ERROR;
  103521. }
  103522. static FlacNamespace::FLAC__StreamEncoderSeekStatus encodeSeekCallback (const FlacNamespace::FLAC__StreamEncoder*, FlacNamespace::FLAC__uint64, void*)
  103523. {
  103524. using namespace FlacNamespace;
  103525. return FLAC__STREAM_ENCODER_SEEK_STATUS_UNSUPPORTED;
  103526. }
  103527. static FlacNamespace::FLAC__StreamEncoderTellStatus encodeTellCallback (const FlacNamespace::FLAC__StreamEncoder*, FlacNamespace::FLAC__uint64* absolute_byte_offset, void* client_data)
  103528. {
  103529. using namespace FlacNamespace;
  103530. if (client_data == 0)
  103531. return FLAC__STREAM_ENCODER_TELL_STATUS_UNSUPPORTED;
  103532. *absolute_byte_offset = (FLAC__uint64) static_cast <FlacWriter*> (client_data)->output->getPosition();
  103533. return FLAC__STREAM_ENCODER_TELL_STATUS_OK;
  103534. }
  103535. static void encodeMetadataCallback (const FlacNamespace::FLAC__StreamEncoder*, const FlacNamespace::FLAC__StreamMetadata* metadata, void* client_data)
  103536. {
  103537. static_cast <FlacWriter*> (client_data)->writeMetaData (metadata);
  103538. }
  103539. juce_UseDebuggingNewOperator
  103540. bool ok;
  103541. private:
  103542. FlacNamespace::FLAC__StreamEncoder* encoder;
  103543. MemoryBlock temp;
  103544. FlacWriter (const FlacWriter&);
  103545. FlacWriter& operator= (const FlacWriter&);
  103546. };
  103547. FlacAudioFormat::FlacAudioFormat()
  103548. : AudioFormat (TRANS (flacFormatName), (const juce_wchar**) flacExtensions)
  103549. {
  103550. }
  103551. FlacAudioFormat::~FlacAudioFormat()
  103552. {
  103553. }
  103554. const Array <int> FlacAudioFormat::getPossibleSampleRates()
  103555. {
  103556. const int rates[] = { 22050, 32000, 44100, 48000, 88200, 96000, 0 };
  103557. return Array <int> (rates);
  103558. }
  103559. const Array <int> FlacAudioFormat::getPossibleBitDepths()
  103560. {
  103561. const int depths[] = { 16, 24, 0 };
  103562. return Array <int> (depths);
  103563. }
  103564. bool FlacAudioFormat::canDoStereo()
  103565. {
  103566. return true;
  103567. }
  103568. bool FlacAudioFormat::canDoMono()
  103569. {
  103570. return true;
  103571. }
  103572. bool FlacAudioFormat::isCompressed()
  103573. {
  103574. return true;
  103575. }
  103576. AudioFormatReader* FlacAudioFormat::createReaderFor (InputStream* in,
  103577. const bool deleteStreamIfOpeningFails)
  103578. {
  103579. ScopedPointer<FlacReader> r (new FlacReader (in));
  103580. if (r->sampleRate != 0)
  103581. return r.release();
  103582. if (! deleteStreamIfOpeningFails)
  103583. r->input = 0;
  103584. return 0;
  103585. }
  103586. AudioFormatWriter* FlacAudioFormat::createWriterFor (OutputStream* out,
  103587. double sampleRate,
  103588. unsigned int numberOfChannels,
  103589. int bitsPerSample,
  103590. const StringPairArray& /*metadataValues*/,
  103591. int /*qualityOptionIndex*/)
  103592. {
  103593. if (getPossibleBitDepths().contains (bitsPerSample))
  103594. {
  103595. ScopedPointer<FlacWriter> w (new FlacWriter (out, sampleRate, numberOfChannels, bitsPerSample));
  103596. if (w->ok)
  103597. return w.release();
  103598. }
  103599. return 0;
  103600. }
  103601. END_JUCE_NAMESPACE
  103602. #endif
  103603. /*** End of inlined file: juce_FlacAudioFormat.cpp ***/
  103604. /*** Start of inlined file: juce_OggVorbisAudioFormat.cpp ***/
  103605. #if JUCE_USE_OGGVORBIS
  103606. #if JUCE_MAC
  103607. #define __MACOSX__ 1
  103608. #endif
  103609. namespace OggVorbisNamespace
  103610. {
  103611. #if JUCE_INCLUDE_OGGVORBIS_CODE
  103612. /*** Start of inlined file: vorbisenc.h ***/
  103613. #ifndef _OV_ENC_H_
  103614. #define _OV_ENC_H_
  103615. #ifdef __cplusplus
  103616. extern "C"
  103617. {
  103618. #endif /* __cplusplus */
  103619. /*** Start of inlined file: codec.h ***/
  103620. #ifndef _vorbis_codec_h_
  103621. #define _vorbis_codec_h_
  103622. #ifdef __cplusplus
  103623. extern "C"
  103624. {
  103625. #endif /* __cplusplus */
  103626. /*** Start of inlined file: ogg.h ***/
  103627. #ifndef _OGG_H
  103628. #define _OGG_H
  103629. #ifdef __cplusplus
  103630. extern "C" {
  103631. #endif
  103632. /*** Start of inlined file: os_types.h ***/
  103633. #ifndef _OS_TYPES_H
  103634. #define _OS_TYPES_H
  103635. /* make it easy on the folks that want to compile the libs with a
  103636. different malloc than stdlib */
  103637. #define _ogg_malloc malloc
  103638. #define _ogg_calloc calloc
  103639. #define _ogg_realloc realloc
  103640. #define _ogg_free free
  103641. #if defined(_WIN32)
  103642. # if defined(__CYGWIN__)
  103643. # include <_G_config.h>
  103644. typedef _G_int64_t ogg_int64_t;
  103645. typedef _G_int32_t ogg_int32_t;
  103646. typedef _G_uint32_t ogg_uint32_t;
  103647. typedef _G_int16_t ogg_int16_t;
  103648. typedef _G_uint16_t ogg_uint16_t;
  103649. # elif defined(__MINGW32__)
  103650. typedef short ogg_int16_t;
  103651. typedef unsigned short ogg_uint16_t;
  103652. typedef int ogg_int32_t;
  103653. typedef unsigned int ogg_uint32_t;
  103654. typedef long long ogg_int64_t;
  103655. typedef unsigned long long ogg_uint64_t;
  103656. # elif defined(__MWERKS__)
  103657. typedef long long ogg_int64_t;
  103658. typedef int ogg_int32_t;
  103659. typedef unsigned int ogg_uint32_t;
  103660. typedef short ogg_int16_t;
  103661. typedef unsigned short ogg_uint16_t;
  103662. # else
  103663. /* MSVC/Borland */
  103664. typedef __int64 ogg_int64_t;
  103665. typedef __int32 ogg_int32_t;
  103666. typedef unsigned __int32 ogg_uint32_t;
  103667. typedef __int16 ogg_int16_t;
  103668. typedef unsigned __int16 ogg_uint16_t;
  103669. # endif
  103670. #elif defined(__MACOS__)
  103671. # include <sys/types.h>
  103672. typedef SInt16 ogg_int16_t;
  103673. typedef UInt16 ogg_uint16_t;
  103674. typedef SInt32 ogg_int32_t;
  103675. typedef UInt32 ogg_uint32_t;
  103676. typedef SInt64 ogg_int64_t;
  103677. #elif defined(__MACOSX__) /* MacOS X Framework build */
  103678. # include <sys/types.h>
  103679. typedef int16_t ogg_int16_t;
  103680. typedef u_int16_t ogg_uint16_t;
  103681. typedef int32_t ogg_int32_t;
  103682. typedef u_int32_t ogg_uint32_t;
  103683. typedef int64_t ogg_int64_t;
  103684. #elif defined(__BEOS__)
  103685. /* Be */
  103686. # include <inttypes.h>
  103687. typedef int16_t ogg_int16_t;
  103688. typedef u_int16_t ogg_uint16_t;
  103689. typedef int32_t ogg_int32_t;
  103690. typedef u_int32_t ogg_uint32_t;
  103691. typedef int64_t ogg_int64_t;
  103692. #elif defined (__EMX__)
  103693. /* OS/2 GCC */
  103694. typedef short ogg_int16_t;
  103695. typedef unsigned short ogg_uint16_t;
  103696. typedef int ogg_int32_t;
  103697. typedef unsigned int ogg_uint32_t;
  103698. typedef long long ogg_int64_t;
  103699. #elif defined (DJGPP)
  103700. /* DJGPP */
  103701. typedef short ogg_int16_t;
  103702. typedef int ogg_int32_t;
  103703. typedef unsigned int ogg_uint32_t;
  103704. typedef long long ogg_int64_t;
  103705. #elif defined(R5900)
  103706. /* PS2 EE */
  103707. typedef long ogg_int64_t;
  103708. typedef int ogg_int32_t;
  103709. typedef unsigned ogg_uint32_t;
  103710. typedef short ogg_int16_t;
  103711. #elif defined(__SYMBIAN32__)
  103712. /* Symbian GCC */
  103713. typedef signed short ogg_int16_t;
  103714. typedef unsigned short ogg_uint16_t;
  103715. typedef signed int ogg_int32_t;
  103716. typedef unsigned int ogg_uint32_t;
  103717. typedef long long int ogg_int64_t;
  103718. #else
  103719. # include <sys/types.h>
  103720. /*** Start of inlined file: config_types.h ***/
  103721. #ifndef __CONFIG_TYPES_H__
  103722. #define __CONFIG_TYPES_H__
  103723. typedef int16_t ogg_int16_t;
  103724. typedef unsigned short ogg_uint16_t;
  103725. typedef int32_t ogg_int32_t;
  103726. typedef unsigned int ogg_uint32_t;
  103727. typedef int64_t ogg_int64_t;
  103728. #endif
  103729. /*** End of inlined file: config_types.h ***/
  103730. #endif
  103731. #endif /* _OS_TYPES_H */
  103732. /*** End of inlined file: os_types.h ***/
  103733. typedef struct {
  103734. long endbyte;
  103735. int endbit;
  103736. unsigned char *buffer;
  103737. unsigned char *ptr;
  103738. long storage;
  103739. } oggpack_buffer;
  103740. /* ogg_page is used to encapsulate the data in one Ogg bitstream page *****/
  103741. typedef struct {
  103742. unsigned char *header;
  103743. long header_len;
  103744. unsigned char *body;
  103745. long body_len;
  103746. } ogg_page;
  103747. ogg_uint32_t ogg_bitreverse(ogg_uint32_t x){
  103748. x= ((x>>16)&0x0000ffffUL) | ((x<<16)&0xffff0000UL);
  103749. x= ((x>> 8)&0x00ff00ffUL) | ((x<< 8)&0xff00ff00UL);
  103750. x= ((x>> 4)&0x0f0f0f0fUL) | ((x<< 4)&0xf0f0f0f0UL);
  103751. x= ((x>> 2)&0x33333333UL) | ((x<< 2)&0xccccccccUL);
  103752. return((x>> 1)&0x55555555UL) | ((x<< 1)&0xaaaaaaaaUL);
  103753. }
  103754. /* ogg_stream_state contains the current encode/decode state of a logical
  103755. Ogg bitstream **********************************************************/
  103756. typedef struct {
  103757. unsigned char *body_data; /* bytes from packet bodies */
  103758. long body_storage; /* storage elements allocated */
  103759. long body_fill; /* elements stored; fill mark */
  103760. long body_returned; /* elements of fill returned */
  103761. int *lacing_vals; /* The values that will go to the segment table */
  103762. ogg_int64_t *granule_vals; /* granulepos values for headers. Not compact
  103763. this way, but it is simple coupled to the
  103764. lacing fifo */
  103765. long lacing_storage;
  103766. long lacing_fill;
  103767. long lacing_packet;
  103768. long lacing_returned;
  103769. unsigned char header[282]; /* working space for header encode */
  103770. int header_fill;
  103771. int e_o_s; /* set when we have buffered the last packet in the
  103772. logical bitstream */
  103773. int b_o_s; /* set after we've written the initial page
  103774. of a logical bitstream */
  103775. long serialno;
  103776. long pageno;
  103777. ogg_int64_t packetno; /* sequence number for decode; the framing
  103778. knows where there's a hole in the data,
  103779. but we need coupling so that the codec
  103780. (which is in a seperate abstraction
  103781. layer) also knows about the gap */
  103782. ogg_int64_t granulepos;
  103783. } ogg_stream_state;
  103784. /* ogg_packet is used to encapsulate the data and metadata belonging
  103785. to a single raw Ogg/Vorbis packet *************************************/
  103786. typedef struct {
  103787. unsigned char *packet;
  103788. long bytes;
  103789. long b_o_s;
  103790. long e_o_s;
  103791. ogg_int64_t granulepos;
  103792. ogg_int64_t packetno; /* sequence number for decode; the framing
  103793. knows where there's a hole in the data,
  103794. but we need coupling so that the codec
  103795. (which is in a seperate abstraction
  103796. layer) also knows about the gap */
  103797. } ogg_packet;
  103798. typedef struct {
  103799. unsigned char *data;
  103800. int storage;
  103801. int fill;
  103802. int returned;
  103803. int unsynced;
  103804. int headerbytes;
  103805. int bodybytes;
  103806. } ogg_sync_state;
  103807. /* Ogg BITSTREAM PRIMITIVES: bitstream ************************/
  103808. extern void oggpack_writeinit(oggpack_buffer *b);
  103809. extern void oggpack_writetrunc(oggpack_buffer *b,long bits);
  103810. extern void oggpack_writealign(oggpack_buffer *b);
  103811. extern void oggpack_writecopy(oggpack_buffer *b,void *source,long bits);
  103812. extern void oggpack_reset(oggpack_buffer *b);
  103813. extern void oggpack_writeclear(oggpack_buffer *b);
  103814. extern void oggpack_readinit(oggpack_buffer *b,unsigned char *buf,int bytes);
  103815. extern void oggpack_write(oggpack_buffer *b,unsigned long value,int bits);
  103816. extern long oggpack_look(oggpack_buffer *b,int bits);
  103817. extern long oggpack_look1(oggpack_buffer *b);
  103818. extern void oggpack_adv(oggpack_buffer *b,int bits);
  103819. extern void oggpack_adv1(oggpack_buffer *b);
  103820. extern long oggpack_read(oggpack_buffer *b,int bits);
  103821. extern long oggpack_read1(oggpack_buffer *b);
  103822. extern long oggpack_bytes(oggpack_buffer *b);
  103823. extern long oggpack_bits(oggpack_buffer *b);
  103824. extern unsigned char *oggpack_get_buffer(oggpack_buffer *b);
  103825. extern void oggpackB_writeinit(oggpack_buffer *b);
  103826. extern void oggpackB_writetrunc(oggpack_buffer *b,long bits);
  103827. extern void oggpackB_writealign(oggpack_buffer *b);
  103828. extern void oggpackB_writecopy(oggpack_buffer *b,void *source,long bits);
  103829. extern void oggpackB_reset(oggpack_buffer *b);
  103830. extern void oggpackB_writeclear(oggpack_buffer *b);
  103831. extern void oggpackB_readinit(oggpack_buffer *b,unsigned char *buf,int bytes);
  103832. extern void oggpackB_write(oggpack_buffer *b,unsigned long value,int bits);
  103833. extern long oggpackB_look(oggpack_buffer *b,int bits);
  103834. extern long oggpackB_look1(oggpack_buffer *b);
  103835. extern void oggpackB_adv(oggpack_buffer *b,int bits);
  103836. extern void oggpackB_adv1(oggpack_buffer *b);
  103837. extern long oggpackB_read(oggpack_buffer *b,int bits);
  103838. extern long oggpackB_read1(oggpack_buffer *b);
  103839. extern long oggpackB_bytes(oggpack_buffer *b);
  103840. extern long oggpackB_bits(oggpack_buffer *b);
  103841. extern unsigned char *oggpackB_get_buffer(oggpack_buffer *b);
  103842. /* Ogg BITSTREAM PRIMITIVES: encoding **************************/
  103843. extern int ogg_stream_packetin(ogg_stream_state *os, ogg_packet *op);
  103844. extern int ogg_stream_pageout(ogg_stream_state *os, ogg_page *og);
  103845. extern int ogg_stream_flush(ogg_stream_state *os, ogg_page *og);
  103846. /* Ogg BITSTREAM PRIMITIVES: decoding **************************/
  103847. extern int ogg_sync_init(ogg_sync_state *oy);
  103848. extern int ogg_sync_clear(ogg_sync_state *oy);
  103849. extern int ogg_sync_reset(ogg_sync_state *oy);
  103850. extern int ogg_sync_destroy(ogg_sync_state *oy);
  103851. extern char *ogg_sync_buffer(ogg_sync_state *oy, long size);
  103852. extern int ogg_sync_wrote(ogg_sync_state *oy, long bytes);
  103853. extern long ogg_sync_pageseek(ogg_sync_state *oy,ogg_page *og);
  103854. extern int ogg_sync_pageout(ogg_sync_state *oy, ogg_page *og);
  103855. extern int ogg_stream_pagein(ogg_stream_state *os, ogg_page *og);
  103856. extern int ogg_stream_packetout(ogg_stream_state *os,ogg_packet *op);
  103857. extern int ogg_stream_packetpeek(ogg_stream_state *os,ogg_packet *op);
  103858. /* Ogg BITSTREAM PRIMITIVES: general ***************************/
  103859. extern int ogg_stream_init(ogg_stream_state *os,int serialno);
  103860. extern int ogg_stream_clear(ogg_stream_state *os);
  103861. extern int ogg_stream_reset(ogg_stream_state *os);
  103862. extern int ogg_stream_reset_serialno(ogg_stream_state *os,int serialno);
  103863. extern int ogg_stream_destroy(ogg_stream_state *os);
  103864. extern int ogg_stream_eos(ogg_stream_state *os);
  103865. extern void ogg_page_checksum_set(ogg_page *og);
  103866. extern int ogg_page_version(ogg_page *og);
  103867. extern int ogg_page_continued(ogg_page *og);
  103868. extern int ogg_page_bos(ogg_page *og);
  103869. extern int ogg_page_eos(ogg_page *og);
  103870. extern ogg_int64_t ogg_page_granulepos(ogg_page *og);
  103871. extern int ogg_page_serialno(ogg_page *og);
  103872. extern long ogg_page_pageno(ogg_page *og);
  103873. extern int ogg_page_packets(ogg_page *og);
  103874. extern void ogg_packet_clear(ogg_packet *op);
  103875. #ifdef __cplusplus
  103876. }
  103877. #endif
  103878. #endif /* _OGG_H */
  103879. /*** End of inlined file: ogg.h ***/
  103880. typedef struct vorbis_info{
  103881. int version;
  103882. int channels;
  103883. long rate;
  103884. /* The below bitrate declarations are *hints*.
  103885. Combinations of the three values carry the following implications:
  103886. all three set to the same value:
  103887. implies a fixed rate bitstream
  103888. only nominal set:
  103889. implies a VBR stream that averages the nominal bitrate. No hard
  103890. upper/lower limit
  103891. upper and or lower set:
  103892. implies a VBR bitstream that obeys the bitrate limits. nominal
  103893. may also be set to give a nominal rate.
  103894. none set:
  103895. the coder does not care to speculate.
  103896. */
  103897. long bitrate_upper;
  103898. long bitrate_nominal;
  103899. long bitrate_lower;
  103900. long bitrate_window;
  103901. void *codec_setup;
  103902. } vorbis_info;
  103903. /* vorbis_dsp_state buffers the current vorbis audio
  103904. analysis/synthesis state. The DSP state belongs to a specific
  103905. logical bitstream ****************************************************/
  103906. typedef struct vorbis_dsp_state{
  103907. int analysisp;
  103908. vorbis_info *vi;
  103909. float **pcm;
  103910. float **pcmret;
  103911. int pcm_storage;
  103912. int pcm_current;
  103913. int pcm_returned;
  103914. int preextrapolate;
  103915. int eofflag;
  103916. long lW;
  103917. long W;
  103918. long nW;
  103919. long centerW;
  103920. ogg_int64_t granulepos;
  103921. ogg_int64_t sequence;
  103922. ogg_int64_t glue_bits;
  103923. ogg_int64_t time_bits;
  103924. ogg_int64_t floor_bits;
  103925. ogg_int64_t res_bits;
  103926. void *backend_state;
  103927. } vorbis_dsp_state;
  103928. typedef struct vorbis_block{
  103929. /* necessary stream state for linking to the framing abstraction */
  103930. float **pcm; /* this is a pointer into local storage */
  103931. oggpack_buffer opb;
  103932. long lW;
  103933. long W;
  103934. long nW;
  103935. int pcmend;
  103936. int mode;
  103937. int eofflag;
  103938. ogg_int64_t granulepos;
  103939. ogg_int64_t sequence;
  103940. vorbis_dsp_state *vd; /* For read-only access of configuration */
  103941. /* local storage to avoid remallocing; it's up to the mapping to
  103942. structure it */
  103943. void *localstore;
  103944. long localtop;
  103945. long localalloc;
  103946. long totaluse;
  103947. struct alloc_chain *reap;
  103948. /* bitmetrics for the frame */
  103949. long glue_bits;
  103950. long time_bits;
  103951. long floor_bits;
  103952. long res_bits;
  103953. void *internal;
  103954. } vorbis_block;
  103955. /* vorbis_block is a single block of data to be processed as part of
  103956. the analysis/synthesis stream; it belongs to a specific logical
  103957. bitstream, but is independant from other vorbis_blocks belonging to
  103958. that logical bitstream. *************************************************/
  103959. struct alloc_chain{
  103960. void *ptr;
  103961. struct alloc_chain *next;
  103962. };
  103963. /* vorbis_info contains all the setup information specific to the
  103964. specific compression/decompression mode in progress (eg,
  103965. psychoacoustic settings, channel setup, options, codebook
  103966. etc). vorbis_info and substructures are in backends.h.
  103967. *********************************************************************/
  103968. /* the comments are not part of vorbis_info so that vorbis_info can be
  103969. static storage */
  103970. typedef struct vorbis_comment{
  103971. /* unlimited user comment fields. libvorbis writes 'libvorbis'
  103972. whatever vendor is set to in encode */
  103973. char **user_comments;
  103974. int *comment_lengths;
  103975. int comments;
  103976. char *vendor;
  103977. } vorbis_comment;
  103978. /* libvorbis encodes in two abstraction layers; first we perform DSP
  103979. and produce a packet (see docs/analysis.txt). The packet is then
  103980. coded into a framed OggSquish bitstream by the second layer (see
  103981. docs/framing.txt). Decode is the reverse process; we sync/frame
  103982. the bitstream and extract individual packets, then decode the
  103983. packet back into PCM audio.
  103984. The extra framing/packetizing is used in streaming formats, such as
  103985. files. Over the net (such as with UDP), the framing and
  103986. packetization aren't necessary as they're provided by the transport
  103987. and the streaming layer is not used */
  103988. /* Vorbis PRIMITIVES: general ***************************************/
  103989. extern void vorbis_info_init(vorbis_info *vi);
  103990. extern void vorbis_info_clear(vorbis_info *vi);
  103991. extern int vorbis_info_blocksize(vorbis_info *vi,int zo);
  103992. extern void vorbis_comment_init(vorbis_comment *vc);
  103993. extern void vorbis_comment_add(vorbis_comment *vc, char *comment);
  103994. extern void vorbis_comment_add_tag(vorbis_comment *vc,
  103995. const char *tag, char *contents);
  103996. extern char *vorbis_comment_query(vorbis_comment *vc, char *tag, int count);
  103997. extern int vorbis_comment_query_count(vorbis_comment *vc, char *tag);
  103998. extern void vorbis_comment_clear(vorbis_comment *vc);
  103999. extern int vorbis_block_init(vorbis_dsp_state *v, vorbis_block *vb);
  104000. extern int vorbis_block_clear(vorbis_block *vb);
  104001. extern void vorbis_dsp_clear(vorbis_dsp_state *v);
  104002. extern double vorbis_granule_time(vorbis_dsp_state *v,
  104003. ogg_int64_t granulepos);
  104004. /* Vorbis PRIMITIVES: analysis/DSP layer ****************************/
  104005. extern int vorbis_analysis_init(vorbis_dsp_state *v,vorbis_info *vi);
  104006. extern int vorbis_commentheader_out(vorbis_comment *vc, ogg_packet *op);
  104007. extern int vorbis_analysis_headerout(vorbis_dsp_state *v,
  104008. vorbis_comment *vc,
  104009. ogg_packet *op,
  104010. ogg_packet *op_comm,
  104011. ogg_packet *op_code);
  104012. extern float **vorbis_analysis_buffer(vorbis_dsp_state *v,int vals);
  104013. extern int vorbis_analysis_wrote(vorbis_dsp_state *v,int vals);
  104014. extern int vorbis_analysis_blockout(vorbis_dsp_state *v,vorbis_block *vb);
  104015. extern int vorbis_analysis(vorbis_block *vb,ogg_packet *op);
  104016. extern int vorbis_bitrate_addblock(vorbis_block *vb);
  104017. extern int vorbis_bitrate_flushpacket(vorbis_dsp_state *vd,
  104018. ogg_packet *op);
  104019. /* Vorbis PRIMITIVES: synthesis layer *******************************/
  104020. extern int vorbis_synthesis_headerin(vorbis_info *vi,vorbis_comment *vc,
  104021. ogg_packet *op);
  104022. extern int vorbis_synthesis_init(vorbis_dsp_state *v,vorbis_info *vi);
  104023. extern int vorbis_synthesis_restart(vorbis_dsp_state *v);
  104024. extern int vorbis_synthesis(vorbis_block *vb,ogg_packet *op);
  104025. extern int vorbis_synthesis_trackonly(vorbis_block *vb,ogg_packet *op);
  104026. extern int vorbis_synthesis_blockin(vorbis_dsp_state *v,vorbis_block *vb);
  104027. extern int vorbis_synthesis_pcmout(vorbis_dsp_state *v,float ***pcm);
  104028. extern int vorbis_synthesis_lapout(vorbis_dsp_state *v,float ***pcm);
  104029. extern int vorbis_synthesis_read(vorbis_dsp_state *v,int samples);
  104030. extern long vorbis_packet_blocksize(vorbis_info *vi,ogg_packet *op);
  104031. extern int vorbis_synthesis_halfrate(vorbis_info *v,int flag);
  104032. extern int vorbis_synthesis_halfrate_p(vorbis_info *v);
  104033. /* Vorbis ERRORS and return codes ***********************************/
  104034. #define OV_FALSE -1
  104035. #define OV_EOF -2
  104036. #define OV_HOLE -3
  104037. #define OV_EREAD -128
  104038. #define OV_EFAULT -129
  104039. #define OV_EIMPL -130
  104040. #define OV_EINVAL -131
  104041. #define OV_ENOTVORBIS -132
  104042. #define OV_EBADHEADER -133
  104043. #define OV_EVERSION -134
  104044. #define OV_ENOTAUDIO -135
  104045. #define OV_EBADPACKET -136
  104046. #define OV_EBADLINK -137
  104047. #define OV_ENOSEEK -138
  104048. #ifdef __cplusplus
  104049. }
  104050. #endif /* __cplusplus */
  104051. #endif
  104052. /*** End of inlined file: codec.h ***/
  104053. extern int vorbis_encode_init(vorbis_info *vi,
  104054. long channels,
  104055. long rate,
  104056. long max_bitrate,
  104057. long nominal_bitrate,
  104058. long min_bitrate);
  104059. extern int vorbis_encode_setup_managed(vorbis_info *vi,
  104060. long channels,
  104061. long rate,
  104062. long max_bitrate,
  104063. long nominal_bitrate,
  104064. long min_bitrate);
  104065. extern int vorbis_encode_setup_vbr(vorbis_info *vi,
  104066. long channels,
  104067. long rate,
  104068. float quality /* quality level from 0. (lo) to 1. (hi) */
  104069. );
  104070. extern int vorbis_encode_init_vbr(vorbis_info *vi,
  104071. long channels,
  104072. long rate,
  104073. float base_quality /* quality level from 0. (lo) to 1. (hi) */
  104074. );
  104075. extern int vorbis_encode_setup_init(vorbis_info *vi);
  104076. extern int vorbis_encode_ctl(vorbis_info *vi,int number,void *arg);
  104077. /* deprecated rate management supported only for compatability */
  104078. #define OV_ECTL_RATEMANAGE_GET 0x10
  104079. #define OV_ECTL_RATEMANAGE_SET 0x11
  104080. #define OV_ECTL_RATEMANAGE_AVG 0x12
  104081. #define OV_ECTL_RATEMANAGE_HARD 0x13
  104082. struct ovectl_ratemanage_arg {
  104083. int management_active;
  104084. long bitrate_hard_min;
  104085. long bitrate_hard_max;
  104086. double bitrate_hard_window;
  104087. long bitrate_av_lo;
  104088. long bitrate_av_hi;
  104089. double bitrate_av_window;
  104090. double bitrate_av_window_center;
  104091. };
  104092. /* new rate setup */
  104093. #define OV_ECTL_RATEMANAGE2_GET 0x14
  104094. #define OV_ECTL_RATEMANAGE2_SET 0x15
  104095. struct ovectl_ratemanage2_arg {
  104096. int management_active;
  104097. long bitrate_limit_min_kbps;
  104098. long bitrate_limit_max_kbps;
  104099. long bitrate_limit_reservoir_bits;
  104100. double bitrate_limit_reservoir_bias;
  104101. long bitrate_average_kbps;
  104102. double bitrate_average_damping;
  104103. };
  104104. #define OV_ECTL_LOWPASS_GET 0x20
  104105. #define OV_ECTL_LOWPASS_SET 0x21
  104106. #define OV_ECTL_IBLOCK_GET 0x30
  104107. #define OV_ECTL_IBLOCK_SET 0x31
  104108. #ifdef __cplusplus
  104109. }
  104110. #endif /* __cplusplus */
  104111. #endif
  104112. /*** End of inlined file: vorbisenc.h ***/
  104113. /*** Start of inlined file: vorbisfile.h ***/
  104114. #ifndef _OV_FILE_H_
  104115. #define _OV_FILE_H_
  104116. #ifdef __cplusplus
  104117. extern "C"
  104118. {
  104119. #endif /* __cplusplus */
  104120. #include <stdio.h>
  104121. /* The function prototypes for the callbacks are basically the same as for
  104122. * the stdio functions fread, fseek, fclose, ftell.
  104123. * The one difference is that the FILE * arguments have been replaced with
  104124. * a void * - this is to be used as a pointer to whatever internal data these
  104125. * functions might need. In the stdio case, it's just a FILE * cast to a void *
  104126. *
  104127. * If you use other functions, check the docs for these functions and return
  104128. * the right values. For seek_func(), you *MUST* return -1 if the stream is
  104129. * unseekable
  104130. */
  104131. typedef struct {
  104132. size_t (*read_func) (void *ptr, size_t size, size_t nmemb, void *datasource);
  104133. int (*seek_func) (void *datasource, ogg_int64_t offset, int whence);
  104134. int (*close_func) (void *datasource);
  104135. long (*tell_func) (void *datasource);
  104136. } ov_callbacks;
  104137. #define NOTOPEN 0
  104138. #define PARTOPEN 1
  104139. #define OPENED 2
  104140. #define STREAMSET 3
  104141. #define INITSET 4
  104142. typedef struct OggVorbis_File {
  104143. void *datasource; /* Pointer to a FILE *, etc. */
  104144. int seekable;
  104145. ogg_int64_t offset;
  104146. ogg_int64_t end;
  104147. ogg_sync_state oy;
  104148. /* If the FILE handle isn't seekable (eg, a pipe), only the current
  104149. stream appears */
  104150. int links;
  104151. ogg_int64_t *offsets;
  104152. ogg_int64_t *dataoffsets;
  104153. long *serialnos;
  104154. ogg_int64_t *pcmlengths; /* overloaded to maintain binary
  104155. compatability; x2 size, stores both
  104156. beginning and end values */
  104157. vorbis_info *vi;
  104158. vorbis_comment *vc;
  104159. /* Decoding working state local storage */
  104160. ogg_int64_t pcm_offset;
  104161. int ready_state;
  104162. long current_serialno;
  104163. int current_link;
  104164. double bittrack;
  104165. double samptrack;
  104166. ogg_stream_state os; /* take physical pages, weld into a logical
  104167. stream of packets */
  104168. vorbis_dsp_state vd; /* central working state for the packet->PCM decoder */
  104169. vorbis_block vb; /* local working space for packet->PCM decode */
  104170. ov_callbacks callbacks;
  104171. } OggVorbis_File;
  104172. extern int ov_clear(OggVorbis_File *vf);
  104173. extern int ov_open(FILE *f,OggVorbis_File *vf,char *initial,long ibytes);
  104174. extern int ov_open_callbacks(void *datasource, OggVorbis_File *vf,
  104175. char *initial, long ibytes, ov_callbacks callbacks);
  104176. extern int ov_test(FILE *f,OggVorbis_File *vf,char *initial,long ibytes);
  104177. extern int ov_test_callbacks(void *datasource, OggVorbis_File *vf,
  104178. char *initial, long ibytes, ov_callbacks callbacks);
  104179. extern int ov_test_open(OggVorbis_File *vf);
  104180. extern long ov_bitrate(OggVorbis_File *vf,int i);
  104181. extern long ov_bitrate_instant(OggVorbis_File *vf);
  104182. extern long ov_streams(OggVorbis_File *vf);
  104183. extern long ov_seekable(OggVorbis_File *vf);
  104184. extern long ov_serialnumber(OggVorbis_File *vf,int i);
  104185. extern ogg_int64_t ov_raw_total(OggVorbis_File *vf,int i);
  104186. extern ogg_int64_t ov_pcm_total(OggVorbis_File *vf,int i);
  104187. extern double ov_time_total(OggVorbis_File *vf,int i);
  104188. extern int ov_raw_seek(OggVorbis_File *vf,ogg_int64_t pos);
  104189. extern int ov_pcm_seek(OggVorbis_File *vf,ogg_int64_t pos);
  104190. extern int ov_pcm_seek_page(OggVorbis_File *vf,ogg_int64_t pos);
  104191. extern int ov_time_seek(OggVorbis_File *vf,double pos);
  104192. extern int ov_time_seek_page(OggVorbis_File *vf,double pos);
  104193. extern int ov_raw_seek_lap(OggVorbis_File *vf,ogg_int64_t pos);
  104194. extern int ov_pcm_seek_lap(OggVorbis_File *vf,ogg_int64_t pos);
  104195. extern int ov_pcm_seek_page_lap(OggVorbis_File *vf,ogg_int64_t pos);
  104196. extern int ov_time_seek_lap(OggVorbis_File *vf,double pos);
  104197. extern int ov_time_seek_page_lap(OggVorbis_File *vf,double pos);
  104198. extern ogg_int64_t ov_raw_tell(OggVorbis_File *vf);
  104199. extern ogg_int64_t ov_pcm_tell(OggVorbis_File *vf);
  104200. extern double ov_time_tell(OggVorbis_File *vf);
  104201. extern vorbis_info *ov_info(OggVorbis_File *vf,int link);
  104202. extern vorbis_comment *ov_comment(OggVorbis_File *vf,int link);
  104203. extern long ov_read_float(OggVorbis_File *vf,float ***pcm_channels,int samples,
  104204. int *bitstream);
  104205. extern long ov_read(OggVorbis_File *vf,char *buffer,int length,
  104206. int bigendianp,int word,int sgned,int *bitstream);
  104207. extern int ov_crosslap(OggVorbis_File *vf1,OggVorbis_File *vf2);
  104208. extern int ov_halfrate(OggVorbis_File *vf,int flag);
  104209. extern int ov_halfrate_p(OggVorbis_File *vf);
  104210. #ifdef __cplusplus
  104211. }
  104212. #endif /* __cplusplus */
  104213. #endif
  104214. /*** End of inlined file: vorbisfile.h ***/
  104215. /*** Start of inlined file: bitwise.c ***/
  104216. /* We're 'LSb' endian; if we write a word but read individual bits,
  104217. then we'll read the lsb first */
  104218. /*** Start of inlined file: juce_OggVorbisHeader.h ***/
  104219. // This file is included at the start of each Ogg-Vorbis .c file, just to do a few housekeeping
  104220. // tasks..
  104221. #if JUCE_MSVC
  104222. #pragma warning (disable: 4267 4127 4244 4996 4100 4701 4702 4013 4133 4206 4305 4189 4706)
  104223. #endif
  104224. /*** End of inlined file: juce_OggVorbisHeader.h ***/
  104225. #if JUCE_USE_OGGVORBIS
  104226. #include <string.h>
  104227. #include <stdlib.h>
  104228. #define BUFFER_INCREMENT 256
  104229. static const unsigned long mask[]=
  104230. {0x00000000,0x00000001,0x00000003,0x00000007,0x0000000f,
  104231. 0x0000001f,0x0000003f,0x0000007f,0x000000ff,0x000001ff,
  104232. 0x000003ff,0x000007ff,0x00000fff,0x00001fff,0x00003fff,
  104233. 0x00007fff,0x0000ffff,0x0001ffff,0x0003ffff,0x0007ffff,
  104234. 0x000fffff,0x001fffff,0x003fffff,0x007fffff,0x00ffffff,
  104235. 0x01ffffff,0x03ffffff,0x07ffffff,0x0fffffff,0x1fffffff,
  104236. 0x3fffffff,0x7fffffff,0xffffffff };
  104237. static const unsigned int mask8B[]=
  104238. {0x00,0x80,0xc0,0xe0,0xf0,0xf8,0xfc,0xfe,0xff};
  104239. void oggpack_writeinit(oggpack_buffer *b){
  104240. memset(b,0,sizeof(*b));
  104241. b->ptr=b->buffer=(unsigned char*) _ogg_malloc(BUFFER_INCREMENT);
  104242. b->buffer[0]='\0';
  104243. b->storage=BUFFER_INCREMENT;
  104244. }
  104245. void oggpackB_writeinit(oggpack_buffer *b){
  104246. oggpack_writeinit(b);
  104247. }
  104248. void oggpack_writetrunc(oggpack_buffer *b,long bits){
  104249. long bytes=bits>>3;
  104250. bits-=bytes*8;
  104251. b->ptr=b->buffer+bytes;
  104252. b->endbit=bits;
  104253. b->endbyte=bytes;
  104254. *b->ptr&=mask[bits];
  104255. }
  104256. void oggpackB_writetrunc(oggpack_buffer *b,long bits){
  104257. long bytes=bits>>3;
  104258. bits-=bytes*8;
  104259. b->ptr=b->buffer+bytes;
  104260. b->endbit=bits;
  104261. b->endbyte=bytes;
  104262. *b->ptr&=mask8B[bits];
  104263. }
  104264. /* Takes only up to 32 bits. */
  104265. void oggpack_write(oggpack_buffer *b,unsigned long value,int bits){
  104266. if(b->endbyte+4>=b->storage){
  104267. b->buffer=(unsigned char*) _ogg_realloc(b->buffer,b->storage+BUFFER_INCREMENT);
  104268. b->storage+=BUFFER_INCREMENT;
  104269. b->ptr=b->buffer+b->endbyte;
  104270. }
  104271. value&=mask[bits];
  104272. bits+=b->endbit;
  104273. b->ptr[0]|=value<<b->endbit;
  104274. if(bits>=8){
  104275. b->ptr[1]=(unsigned char)(value>>(8-b->endbit));
  104276. if(bits>=16){
  104277. b->ptr[2]=(unsigned char)(value>>(16-b->endbit));
  104278. if(bits>=24){
  104279. b->ptr[3]=(unsigned char)(value>>(24-b->endbit));
  104280. if(bits>=32){
  104281. if(b->endbit)
  104282. b->ptr[4]=(unsigned char)(value>>(32-b->endbit));
  104283. else
  104284. b->ptr[4]=0;
  104285. }
  104286. }
  104287. }
  104288. }
  104289. b->endbyte+=bits/8;
  104290. b->ptr+=bits/8;
  104291. b->endbit=bits&7;
  104292. }
  104293. /* Takes only up to 32 bits. */
  104294. void oggpackB_write(oggpack_buffer *b,unsigned long value,int bits){
  104295. if(b->endbyte+4>=b->storage){
  104296. b->buffer=(unsigned char*) _ogg_realloc(b->buffer,b->storage+BUFFER_INCREMENT);
  104297. b->storage+=BUFFER_INCREMENT;
  104298. b->ptr=b->buffer+b->endbyte;
  104299. }
  104300. value=(value&mask[bits])<<(32-bits);
  104301. bits+=b->endbit;
  104302. b->ptr[0]|=value>>(24+b->endbit);
  104303. if(bits>=8){
  104304. b->ptr[1]=(unsigned char)(value>>(16+b->endbit));
  104305. if(bits>=16){
  104306. b->ptr[2]=(unsigned char)(value>>(8+b->endbit));
  104307. if(bits>=24){
  104308. b->ptr[3]=(unsigned char)(value>>(b->endbit));
  104309. if(bits>=32){
  104310. if(b->endbit)
  104311. b->ptr[4]=(unsigned char)(value<<(8-b->endbit));
  104312. else
  104313. b->ptr[4]=0;
  104314. }
  104315. }
  104316. }
  104317. }
  104318. b->endbyte+=bits/8;
  104319. b->ptr+=bits/8;
  104320. b->endbit=bits&7;
  104321. }
  104322. void oggpack_writealign(oggpack_buffer *b){
  104323. int bits=8-b->endbit;
  104324. if(bits<8)
  104325. oggpack_write(b,0,bits);
  104326. }
  104327. void oggpackB_writealign(oggpack_buffer *b){
  104328. int bits=8-b->endbit;
  104329. if(bits<8)
  104330. oggpackB_write(b,0,bits);
  104331. }
  104332. static void oggpack_writecopy_helper(oggpack_buffer *b,
  104333. void *source,
  104334. long bits,
  104335. void (*w)(oggpack_buffer *,
  104336. unsigned long,
  104337. int),
  104338. int msb){
  104339. unsigned char *ptr=(unsigned char *)source;
  104340. long bytes=bits/8;
  104341. bits-=bytes*8;
  104342. if(b->endbit){
  104343. int i;
  104344. /* unaligned copy. Do it the hard way. */
  104345. for(i=0;i<bytes;i++)
  104346. w(b,(unsigned long)(ptr[i]),8);
  104347. }else{
  104348. /* aligned block copy */
  104349. if(b->endbyte+bytes+1>=b->storage){
  104350. b->storage=b->endbyte+bytes+BUFFER_INCREMENT;
  104351. b->buffer=(unsigned char*) _ogg_realloc(b->buffer,b->storage);
  104352. b->ptr=b->buffer+b->endbyte;
  104353. }
  104354. memmove(b->ptr,source,bytes);
  104355. b->ptr+=bytes;
  104356. b->endbyte+=bytes;
  104357. *b->ptr=0;
  104358. }
  104359. if(bits){
  104360. if(msb)
  104361. w(b,(unsigned long)(ptr[bytes]>>(8-bits)),bits);
  104362. else
  104363. w(b,(unsigned long)(ptr[bytes]),bits);
  104364. }
  104365. }
  104366. void oggpack_writecopy(oggpack_buffer *b,void *source,long bits){
  104367. oggpack_writecopy_helper(b,source,bits,oggpack_write,0);
  104368. }
  104369. void oggpackB_writecopy(oggpack_buffer *b,void *source,long bits){
  104370. oggpack_writecopy_helper(b,source,bits,oggpackB_write,1);
  104371. }
  104372. void oggpack_reset(oggpack_buffer *b){
  104373. b->ptr=b->buffer;
  104374. b->buffer[0]=0;
  104375. b->endbit=b->endbyte=0;
  104376. }
  104377. void oggpackB_reset(oggpack_buffer *b){
  104378. oggpack_reset(b);
  104379. }
  104380. void oggpack_writeclear(oggpack_buffer *b){
  104381. _ogg_free(b->buffer);
  104382. memset(b,0,sizeof(*b));
  104383. }
  104384. void oggpackB_writeclear(oggpack_buffer *b){
  104385. oggpack_writeclear(b);
  104386. }
  104387. void oggpack_readinit(oggpack_buffer *b,unsigned char *buf,int bytes){
  104388. memset(b,0,sizeof(*b));
  104389. b->buffer=b->ptr=buf;
  104390. b->storage=bytes;
  104391. }
  104392. void oggpackB_readinit(oggpack_buffer *b,unsigned char *buf,int bytes){
  104393. oggpack_readinit(b,buf,bytes);
  104394. }
  104395. /* Read in bits without advancing the bitptr; bits <= 32 */
  104396. long oggpack_look(oggpack_buffer *b,int bits){
  104397. unsigned long ret;
  104398. unsigned long m=mask[bits];
  104399. bits+=b->endbit;
  104400. if(b->endbyte+4>=b->storage){
  104401. /* not the main path */
  104402. if(b->endbyte*8+bits>b->storage*8)return(-1);
  104403. }
  104404. ret=b->ptr[0]>>b->endbit;
  104405. if(bits>8){
  104406. ret|=b->ptr[1]<<(8-b->endbit);
  104407. if(bits>16){
  104408. ret|=b->ptr[2]<<(16-b->endbit);
  104409. if(bits>24){
  104410. ret|=b->ptr[3]<<(24-b->endbit);
  104411. if(bits>32 && b->endbit)
  104412. ret|=b->ptr[4]<<(32-b->endbit);
  104413. }
  104414. }
  104415. }
  104416. return(m&ret);
  104417. }
  104418. /* Read in bits without advancing the bitptr; bits <= 32 */
  104419. long oggpackB_look(oggpack_buffer *b,int bits){
  104420. unsigned long ret;
  104421. int m=32-bits;
  104422. bits+=b->endbit;
  104423. if(b->endbyte+4>=b->storage){
  104424. /* not the main path */
  104425. if(b->endbyte*8+bits>b->storage*8)return(-1);
  104426. }
  104427. ret=b->ptr[0]<<(24+b->endbit);
  104428. if(bits>8){
  104429. ret|=b->ptr[1]<<(16+b->endbit);
  104430. if(bits>16){
  104431. ret|=b->ptr[2]<<(8+b->endbit);
  104432. if(bits>24){
  104433. ret|=b->ptr[3]<<(b->endbit);
  104434. if(bits>32 && b->endbit)
  104435. ret|=b->ptr[4]>>(8-b->endbit);
  104436. }
  104437. }
  104438. }
  104439. return ((ret&0xffffffff)>>(m>>1))>>((m+1)>>1);
  104440. }
  104441. long oggpack_look1(oggpack_buffer *b){
  104442. if(b->endbyte>=b->storage)return(-1);
  104443. return((b->ptr[0]>>b->endbit)&1);
  104444. }
  104445. long oggpackB_look1(oggpack_buffer *b){
  104446. if(b->endbyte>=b->storage)return(-1);
  104447. return((b->ptr[0]>>(7-b->endbit))&1);
  104448. }
  104449. void oggpack_adv(oggpack_buffer *b,int bits){
  104450. bits+=b->endbit;
  104451. b->ptr+=bits/8;
  104452. b->endbyte+=bits/8;
  104453. b->endbit=bits&7;
  104454. }
  104455. void oggpackB_adv(oggpack_buffer *b,int bits){
  104456. oggpack_adv(b,bits);
  104457. }
  104458. void oggpack_adv1(oggpack_buffer *b){
  104459. if(++(b->endbit)>7){
  104460. b->endbit=0;
  104461. b->ptr++;
  104462. b->endbyte++;
  104463. }
  104464. }
  104465. void oggpackB_adv1(oggpack_buffer *b){
  104466. oggpack_adv1(b);
  104467. }
  104468. /* bits <= 32 */
  104469. long oggpack_read(oggpack_buffer *b,int bits){
  104470. long ret;
  104471. unsigned long m=mask[bits];
  104472. bits+=b->endbit;
  104473. if(b->endbyte+4>=b->storage){
  104474. /* not the main path */
  104475. ret=-1L;
  104476. if(b->endbyte*8+bits>b->storage*8)goto overflow;
  104477. }
  104478. ret=b->ptr[0]>>b->endbit;
  104479. if(bits>8){
  104480. ret|=b->ptr[1]<<(8-b->endbit);
  104481. if(bits>16){
  104482. ret|=b->ptr[2]<<(16-b->endbit);
  104483. if(bits>24){
  104484. ret|=b->ptr[3]<<(24-b->endbit);
  104485. if(bits>32 && b->endbit){
  104486. ret|=b->ptr[4]<<(32-b->endbit);
  104487. }
  104488. }
  104489. }
  104490. }
  104491. ret&=m;
  104492. overflow:
  104493. b->ptr+=bits/8;
  104494. b->endbyte+=bits/8;
  104495. b->endbit=bits&7;
  104496. return(ret);
  104497. }
  104498. /* bits <= 32 */
  104499. long oggpackB_read(oggpack_buffer *b,int bits){
  104500. long ret;
  104501. long m=32-bits;
  104502. bits+=b->endbit;
  104503. if(b->endbyte+4>=b->storage){
  104504. /* not the main path */
  104505. ret=-1L;
  104506. if(b->endbyte*8+bits>b->storage*8)goto overflow;
  104507. }
  104508. ret=b->ptr[0]<<(24+b->endbit);
  104509. if(bits>8){
  104510. ret|=b->ptr[1]<<(16+b->endbit);
  104511. if(bits>16){
  104512. ret|=b->ptr[2]<<(8+b->endbit);
  104513. if(bits>24){
  104514. ret|=b->ptr[3]<<(b->endbit);
  104515. if(bits>32 && b->endbit)
  104516. ret|=b->ptr[4]>>(8-b->endbit);
  104517. }
  104518. }
  104519. }
  104520. ret=((ret&0xffffffffUL)>>(m>>1))>>((m+1)>>1);
  104521. overflow:
  104522. b->ptr+=bits/8;
  104523. b->endbyte+=bits/8;
  104524. b->endbit=bits&7;
  104525. return(ret);
  104526. }
  104527. long oggpack_read1(oggpack_buffer *b){
  104528. long ret;
  104529. if(b->endbyte>=b->storage){
  104530. /* not the main path */
  104531. ret=-1L;
  104532. goto overflow;
  104533. }
  104534. ret=(b->ptr[0]>>b->endbit)&1;
  104535. overflow:
  104536. b->endbit++;
  104537. if(b->endbit>7){
  104538. b->endbit=0;
  104539. b->ptr++;
  104540. b->endbyte++;
  104541. }
  104542. return(ret);
  104543. }
  104544. long oggpackB_read1(oggpack_buffer *b){
  104545. long ret;
  104546. if(b->endbyte>=b->storage){
  104547. /* not the main path */
  104548. ret=-1L;
  104549. goto overflow;
  104550. }
  104551. ret=(b->ptr[0]>>(7-b->endbit))&1;
  104552. overflow:
  104553. b->endbit++;
  104554. if(b->endbit>7){
  104555. b->endbit=0;
  104556. b->ptr++;
  104557. b->endbyte++;
  104558. }
  104559. return(ret);
  104560. }
  104561. long oggpack_bytes(oggpack_buffer *b){
  104562. return(b->endbyte+(b->endbit+7)/8);
  104563. }
  104564. long oggpack_bits(oggpack_buffer *b){
  104565. return(b->endbyte*8+b->endbit);
  104566. }
  104567. long oggpackB_bytes(oggpack_buffer *b){
  104568. return oggpack_bytes(b);
  104569. }
  104570. long oggpackB_bits(oggpack_buffer *b){
  104571. return oggpack_bits(b);
  104572. }
  104573. unsigned char *oggpack_get_buffer(oggpack_buffer *b){
  104574. return(b->buffer);
  104575. }
  104576. unsigned char *oggpackB_get_buffer(oggpack_buffer *b){
  104577. return oggpack_get_buffer(b);
  104578. }
  104579. /* Self test of the bitwise routines; everything else is based on
  104580. them, so they damned well better be solid. */
  104581. #ifdef _V_SELFTEST
  104582. #include <stdio.h>
  104583. static int ilog(unsigned int v){
  104584. int ret=0;
  104585. while(v){
  104586. ret++;
  104587. v>>=1;
  104588. }
  104589. return(ret);
  104590. }
  104591. oggpack_buffer o;
  104592. oggpack_buffer r;
  104593. void report(char *in){
  104594. fprintf(stderr,"%s",in);
  104595. exit(1);
  104596. }
  104597. void cliptest(unsigned long *b,int vals,int bits,int *comp,int compsize){
  104598. long bytes,i;
  104599. unsigned char *buffer;
  104600. oggpack_reset(&o);
  104601. for(i=0;i<vals;i++)
  104602. oggpack_write(&o,b[i],bits?bits:ilog(b[i]));
  104603. buffer=oggpack_get_buffer(&o);
  104604. bytes=oggpack_bytes(&o);
  104605. if(bytes!=compsize)report("wrong number of bytes!\n");
  104606. for(i=0;i<bytes;i++)if(buffer[i]!=comp[i]){
  104607. for(i=0;i<bytes;i++)fprintf(stderr,"%x %x\n",(int)buffer[i],(int)comp[i]);
  104608. report("wrote incorrect value!\n");
  104609. }
  104610. oggpack_readinit(&r,buffer,bytes);
  104611. for(i=0;i<vals;i++){
  104612. int tbit=bits?bits:ilog(b[i]);
  104613. if(oggpack_look(&r,tbit)==-1)
  104614. report("out of data!\n");
  104615. if(oggpack_look(&r,tbit)!=(b[i]&mask[tbit]))
  104616. report("looked at incorrect value!\n");
  104617. if(tbit==1)
  104618. if(oggpack_look1(&r)!=(b[i]&mask[tbit]))
  104619. report("looked at single bit incorrect value!\n");
  104620. if(tbit==1){
  104621. if(oggpack_read1(&r)!=(b[i]&mask[tbit]))
  104622. report("read incorrect single bit value!\n");
  104623. }else{
  104624. if(oggpack_read(&r,tbit)!=(b[i]&mask[tbit]))
  104625. report("read incorrect value!\n");
  104626. }
  104627. }
  104628. if(oggpack_bytes(&r)!=bytes)report("leftover bytes after read!\n");
  104629. }
  104630. void cliptestB(unsigned long *b,int vals,int bits,int *comp,int compsize){
  104631. long bytes,i;
  104632. unsigned char *buffer;
  104633. oggpackB_reset(&o);
  104634. for(i=0;i<vals;i++)
  104635. oggpackB_write(&o,b[i],bits?bits:ilog(b[i]));
  104636. buffer=oggpackB_get_buffer(&o);
  104637. bytes=oggpackB_bytes(&o);
  104638. if(bytes!=compsize)report("wrong number of bytes!\n");
  104639. for(i=0;i<bytes;i++)if(buffer[i]!=comp[i]){
  104640. for(i=0;i<bytes;i++)fprintf(stderr,"%x %x\n",(int)buffer[i],(int)comp[i]);
  104641. report("wrote incorrect value!\n");
  104642. }
  104643. oggpackB_readinit(&r,buffer,bytes);
  104644. for(i=0;i<vals;i++){
  104645. int tbit=bits?bits:ilog(b[i]);
  104646. if(oggpackB_look(&r,tbit)==-1)
  104647. report("out of data!\n");
  104648. if(oggpackB_look(&r,tbit)!=(b[i]&mask[tbit]))
  104649. report("looked at incorrect value!\n");
  104650. if(tbit==1)
  104651. if(oggpackB_look1(&r)!=(b[i]&mask[tbit]))
  104652. report("looked at single bit incorrect value!\n");
  104653. if(tbit==1){
  104654. if(oggpackB_read1(&r)!=(b[i]&mask[tbit]))
  104655. report("read incorrect single bit value!\n");
  104656. }else{
  104657. if(oggpackB_read(&r,tbit)!=(b[i]&mask[tbit]))
  104658. report("read incorrect value!\n");
  104659. }
  104660. }
  104661. if(oggpackB_bytes(&r)!=bytes)report("leftover bytes after read!\n");
  104662. }
  104663. int main(void){
  104664. unsigned char *buffer;
  104665. long bytes,i;
  104666. static unsigned long testbuffer1[]=
  104667. {18,12,103948,4325,543,76,432,52,3,65,4,56,32,42,34,21,1,23,32,546,456,7,
  104668. 567,56,8,8,55,3,52,342,341,4,265,7,67,86,2199,21,7,1,5,1,4};
  104669. int test1size=43;
  104670. static unsigned long testbuffer2[]=
  104671. {216531625L,1237861823,56732452,131,3212421,12325343,34547562,12313212,
  104672. 1233432,534,5,346435231,14436467,7869299,76326614,167548585,
  104673. 85525151,0,12321,1,349528352};
  104674. int test2size=21;
  104675. static unsigned long testbuffer3[]=
  104676. {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,
  104677. 0,1,30,1,1,1,0,0,1,0,0,0,12,0,11,0,1,0,0,1};
  104678. int test3size=56;
  104679. static unsigned long large[]=
  104680. {2136531625L,2137861823,56732452,131,3212421,12325343,34547562,12313212,
  104681. 1233432,534,5,2146435231,14436467,7869299,76326614,167548585,
  104682. 85525151,0,12321,1,2146528352};
  104683. int onesize=33;
  104684. static int one[33]={146,25,44,151,195,15,153,176,233,131,196,65,85,172,47,40,
  104685. 34,242,223,136,35,222,211,86,171,50,225,135,214,75,172,
  104686. 223,4};
  104687. static int oneB[33]={150,101,131,33,203,15,204,216,105,193,156,65,84,85,222,
  104688. 8,139,145,227,126,34,55,244,171,85,100,39,195,173,18,
  104689. 245,251,128};
  104690. int twosize=6;
  104691. static int two[6]={61,255,255,251,231,29};
  104692. static int twoB[6]={247,63,255,253,249,120};
  104693. int threesize=54;
  104694. static int three[54]={169,2,232,252,91,132,156,36,89,13,123,176,144,32,254,
  104695. 142,224,85,59,121,144,79,124,23,67,90,90,216,79,23,83,
  104696. 58,135,196,61,55,129,183,54,101,100,170,37,127,126,10,
  104697. 100,52,4,14,18,86,77,1};
  104698. static int threeB[54]={206,128,42,153,57,8,183,251,13,89,36,30,32,144,183,
  104699. 130,59,240,121,59,85,223,19,228,180,134,33,107,74,98,
  104700. 233,253,196,135,63,2,110,114,50,155,90,127,37,170,104,
  104701. 200,20,254,4,58,106,176,144,0};
  104702. int foursize=38;
  104703. static int four[38]={18,6,163,252,97,194,104,131,32,1,7,82,137,42,129,11,72,
  104704. 132,60,220,112,8,196,109,64,179,86,9,137,195,208,122,169,
  104705. 28,2,133,0,1};
  104706. static int fourB[38]={36,48,102,83,243,24,52,7,4,35,132,10,145,21,2,93,2,41,
  104707. 1,219,184,16,33,184,54,149,170,132,18,30,29,98,229,67,
  104708. 129,10,4,32};
  104709. int fivesize=45;
  104710. static int five[45]={169,2,126,139,144,172,30,4,80,72,240,59,130,218,73,62,
  104711. 241,24,210,44,4,20,0,248,116,49,135,100,110,130,181,169,
  104712. 84,75,159,2,1,0,132,192,8,0,0,18,22};
  104713. static int fiveB[45]={1,84,145,111,245,100,128,8,56,36,40,71,126,78,213,226,
  104714. 124,105,12,0,133,128,0,162,233,242,67,152,77,205,77,
  104715. 172,150,169,129,79,128,0,6,4,32,0,27,9,0};
  104716. int sixsize=7;
  104717. static int six[7]={17,177,170,242,169,19,148};
  104718. static int sixB[7]={136,141,85,79,149,200,41};
  104719. /* Test read/write together */
  104720. /* Later we test against pregenerated bitstreams */
  104721. oggpack_writeinit(&o);
  104722. fprintf(stderr,"\nSmall preclipped packing (LSb): ");
  104723. cliptest(testbuffer1,test1size,0,one,onesize);
  104724. fprintf(stderr,"ok.");
  104725. fprintf(stderr,"\nNull bit call (LSb): ");
  104726. cliptest(testbuffer3,test3size,0,two,twosize);
  104727. fprintf(stderr,"ok.");
  104728. fprintf(stderr,"\nLarge preclipped packing (LSb): ");
  104729. cliptest(testbuffer2,test2size,0,three,threesize);
  104730. fprintf(stderr,"ok.");
  104731. fprintf(stderr,"\n32 bit preclipped packing (LSb): ");
  104732. oggpack_reset(&o);
  104733. for(i=0;i<test2size;i++)
  104734. oggpack_write(&o,large[i],32);
  104735. buffer=oggpack_get_buffer(&o);
  104736. bytes=oggpack_bytes(&o);
  104737. oggpack_readinit(&r,buffer,bytes);
  104738. for(i=0;i<test2size;i++){
  104739. if(oggpack_look(&r,32)==-1)report("out of data. failed!");
  104740. if(oggpack_look(&r,32)!=large[i]){
  104741. fprintf(stderr,"%ld != %ld (%lx!=%lx):",oggpack_look(&r,32),large[i],
  104742. oggpack_look(&r,32),large[i]);
  104743. report("read incorrect value!\n");
  104744. }
  104745. oggpack_adv(&r,32);
  104746. }
  104747. if(oggpack_bytes(&r)!=bytes)report("leftover bytes after read!\n");
  104748. fprintf(stderr,"ok.");
  104749. fprintf(stderr,"\nSmall unclipped packing (LSb): ");
  104750. cliptest(testbuffer1,test1size,7,four,foursize);
  104751. fprintf(stderr,"ok.");
  104752. fprintf(stderr,"\nLarge unclipped packing (LSb): ");
  104753. cliptest(testbuffer2,test2size,17,five,fivesize);
  104754. fprintf(stderr,"ok.");
  104755. fprintf(stderr,"\nSingle bit unclipped packing (LSb): ");
  104756. cliptest(testbuffer3,test3size,1,six,sixsize);
  104757. fprintf(stderr,"ok.");
  104758. fprintf(stderr,"\nTesting read past end (LSb): ");
  104759. oggpack_readinit(&r,"\0\0\0\0\0\0\0\0",8);
  104760. for(i=0;i<64;i++){
  104761. if(oggpack_read(&r,1)!=0){
  104762. fprintf(stderr,"failed; got -1 prematurely.\n");
  104763. exit(1);
  104764. }
  104765. }
  104766. if(oggpack_look(&r,1)!=-1 ||
  104767. oggpack_read(&r,1)!=-1){
  104768. fprintf(stderr,"failed; read past end without -1.\n");
  104769. exit(1);
  104770. }
  104771. oggpack_readinit(&r,"\0\0\0\0\0\0\0\0",8);
  104772. if(oggpack_read(&r,30)!=0 || oggpack_read(&r,16)!=0){
  104773. fprintf(stderr,"failed 2; got -1 prematurely.\n");
  104774. exit(1);
  104775. }
  104776. if(oggpack_look(&r,18)!=0 ||
  104777. oggpack_look(&r,18)!=0){
  104778. fprintf(stderr,"failed 3; got -1 prematurely.\n");
  104779. exit(1);
  104780. }
  104781. if(oggpack_look(&r,19)!=-1 ||
  104782. oggpack_look(&r,19)!=-1){
  104783. fprintf(stderr,"failed; read past end without -1.\n");
  104784. exit(1);
  104785. }
  104786. if(oggpack_look(&r,32)!=-1 ||
  104787. oggpack_look(&r,32)!=-1){
  104788. fprintf(stderr,"failed; read past end without -1.\n");
  104789. exit(1);
  104790. }
  104791. oggpack_writeclear(&o);
  104792. fprintf(stderr,"ok.\n");
  104793. /********** lazy, cut-n-paste retest with MSb packing ***********/
  104794. /* Test read/write together */
  104795. /* Later we test against pregenerated bitstreams */
  104796. oggpackB_writeinit(&o);
  104797. fprintf(stderr,"\nSmall preclipped packing (MSb): ");
  104798. cliptestB(testbuffer1,test1size,0,oneB,onesize);
  104799. fprintf(stderr,"ok.");
  104800. fprintf(stderr,"\nNull bit call (MSb): ");
  104801. cliptestB(testbuffer3,test3size,0,twoB,twosize);
  104802. fprintf(stderr,"ok.");
  104803. fprintf(stderr,"\nLarge preclipped packing (MSb): ");
  104804. cliptestB(testbuffer2,test2size,0,threeB,threesize);
  104805. fprintf(stderr,"ok.");
  104806. fprintf(stderr,"\n32 bit preclipped packing (MSb): ");
  104807. oggpackB_reset(&o);
  104808. for(i=0;i<test2size;i++)
  104809. oggpackB_write(&o,large[i],32);
  104810. buffer=oggpackB_get_buffer(&o);
  104811. bytes=oggpackB_bytes(&o);
  104812. oggpackB_readinit(&r,buffer,bytes);
  104813. for(i=0;i<test2size;i++){
  104814. if(oggpackB_look(&r,32)==-1)report("out of data. failed!");
  104815. if(oggpackB_look(&r,32)!=large[i]){
  104816. fprintf(stderr,"%ld != %ld (%lx!=%lx):",oggpackB_look(&r,32),large[i],
  104817. oggpackB_look(&r,32),large[i]);
  104818. report("read incorrect value!\n");
  104819. }
  104820. oggpackB_adv(&r,32);
  104821. }
  104822. if(oggpackB_bytes(&r)!=bytes)report("leftover bytes after read!\n");
  104823. fprintf(stderr,"ok.");
  104824. fprintf(stderr,"\nSmall unclipped packing (MSb): ");
  104825. cliptestB(testbuffer1,test1size,7,fourB,foursize);
  104826. fprintf(stderr,"ok.");
  104827. fprintf(stderr,"\nLarge unclipped packing (MSb): ");
  104828. cliptestB(testbuffer2,test2size,17,fiveB,fivesize);
  104829. fprintf(stderr,"ok.");
  104830. fprintf(stderr,"\nSingle bit unclipped packing (MSb): ");
  104831. cliptestB(testbuffer3,test3size,1,sixB,sixsize);
  104832. fprintf(stderr,"ok.");
  104833. fprintf(stderr,"\nTesting read past end (MSb): ");
  104834. oggpackB_readinit(&r,"\0\0\0\0\0\0\0\0",8);
  104835. for(i=0;i<64;i++){
  104836. if(oggpackB_read(&r,1)!=0){
  104837. fprintf(stderr,"failed; got -1 prematurely.\n");
  104838. exit(1);
  104839. }
  104840. }
  104841. if(oggpackB_look(&r,1)!=-1 ||
  104842. oggpackB_read(&r,1)!=-1){
  104843. fprintf(stderr,"failed; read past end without -1.\n");
  104844. exit(1);
  104845. }
  104846. oggpackB_readinit(&r,"\0\0\0\0\0\0\0\0",8);
  104847. if(oggpackB_read(&r,30)!=0 || oggpackB_read(&r,16)!=0){
  104848. fprintf(stderr,"failed 2; got -1 prematurely.\n");
  104849. exit(1);
  104850. }
  104851. if(oggpackB_look(&r,18)!=0 ||
  104852. oggpackB_look(&r,18)!=0){
  104853. fprintf(stderr,"failed 3; got -1 prematurely.\n");
  104854. exit(1);
  104855. }
  104856. if(oggpackB_look(&r,19)!=-1 ||
  104857. oggpackB_look(&r,19)!=-1){
  104858. fprintf(stderr,"failed; read past end without -1.\n");
  104859. exit(1);
  104860. }
  104861. if(oggpackB_look(&r,32)!=-1 ||
  104862. oggpackB_look(&r,32)!=-1){
  104863. fprintf(stderr,"failed; read past end without -1.\n");
  104864. exit(1);
  104865. }
  104866. oggpackB_writeclear(&o);
  104867. fprintf(stderr,"ok.\n\n");
  104868. return(0);
  104869. }
  104870. #endif /* _V_SELFTEST */
  104871. #undef BUFFER_INCREMENT
  104872. #endif
  104873. /*** End of inlined file: bitwise.c ***/
  104874. /*** Start of inlined file: framing.c ***/
  104875. /*** Start of inlined file: juce_OggVorbisHeader.h ***/
  104876. // This file is included at the start of each Ogg-Vorbis .c file, just to do a few housekeeping
  104877. // tasks..
  104878. #if JUCE_MSVC
  104879. #pragma warning (disable: 4267 4127 4244 4996 4100 4701 4702 4013 4133 4206 4305 4189 4706)
  104880. #endif
  104881. /*** End of inlined file: juce_OggVorbisHeader.h ***/
  104882. #if JUCE_USE_OGGVORBIS
  104883. #include <stdlib.h>
  104884. #include <string.h>
  104885. /* A complete description of Ogg framing exists in docs/framing.html */
  104886. int ogg_page_version(ogg_page *og){
  104887. return((int)(og->header[4]));
  104888. }
  104889. int ogg_page_continued(ogg_page *og){
  104890. return((int)(og->header[5]&0x01));
  104891. }
  104892. int ogg_page_bos(ogg_page *og){
  104893. return((int)(og->header[5]&0x02));
  104894. }
  104895. int ogg_page_eos(ogg_page *og){
  104896. return((int)(og->header[5]&0x04));
  104897. }
  104898. ogg_int64_t ogg_page_granulepos(ogg_page *og){
  104899. unsigned char *page=og->header;
  104900. ogg_int64_t granulepos=page[13]&(0xff);
  104901. granulepos= (granulepos<<8)|(page[12]&0xff);
  104902. granulepos= (granulepos<<8)|(page[11]&0xff);
  104903. granulepos= (granulepos<<8)|(page[10]&0xff);
  104904. granulepos= (granulepos<<8)|(page[9]&0xff);
  104905. granulepos= (granulepos<<8)|(page[8]&0xff);
  104906. granulepos= (granulepos<<8)|(page[7]&0xff);
  104907. granulepos= (granulepos<<8)|(page[6]&0xff);
  104908. return(granulepos);
  104909. }
  104910. int ogg_page_serialno(ogg_page *og){
  104911. return(og->header[14] |
  104912. (og->header[15]<<8) |
  104913. (og->header[16]<<16) |
  104914. (og->header[17]<<24));
  104915. }
  104916. long ogg_page_pageno(ogg_page *og){
  104917. return(og->header[18] |
  104918. (og->header[19]<<8) |
  104919. (og->header[20]<<16) |
  104920. (og->header[21]<<24));
  104921. }
  104922. /* returns the number of packets that are completed on this page (if
  104923. the leading packet is begun on a previous page, but ends on this
  104924. page, it's counted */
  104925. /* NOTE:
  104926. If a page consists of a packet begun on a previous page, and a new
  104927. packet begun (but not completed) on this page, the return will be:
  104928. ogg_page_packets(page) ==1,
  104929. ogg_page_continued(page) !=0
  104930. If a page happens to be a single packet that was begun on a
  104931. previous page, and spans to the next page (in the case of a three or
  104932. more page packet), the return will be:
  104933. ogg_page_packets(page) ==0,
  104934. ogg_page_continued(page) !=0
  104935. */
  104936. int ogg_page_packets(ogg_page *og){
  104937. int i,n=og->header[26],count=0;
  104938. for(i=0;i<n;i++)
  104939. if(og->header[27+i]<255)count++;
  104940. return(count);
  104941. }
  104942. #if 0
  104943. /* helper to initialize lookup for direct-table CRC (illustrative; we
  104944. use the static init below) */
  104945. static ogg_uint32_t _ogg_crc_entry(unsigned long index){
  104946. int i;
  104947. unsigned long r;
  104948. r = index << 24;
  104949. for (i=0; i<8; i++)
  104950. if (r & 0x80000000UL)
  104951. r = (r << 1) ^ 0x04c11db7; /* The same as the ethernet generator
  104952. polynomial, although we use an
  104953. unreflected alg and an init/final
  104954. of 0, not 0xffffffff */
  104955. else
  104956. r<<=1;
  104957. return (r & 0xffffffffUL);
  104958. }
  104959. #endif
  104960. static const ogg_uint32_t crc_lookup[256]={
  104961. 0x00000000,0x04c11db7,0x09823b6e,0x0d4326d9,
  104962. 0x130476dc,0x17c56b6b,0x1a864db2,0x1e475005,
  104963. 0x2608edb8,0x22c9f00f,0x2f8ad6d6,0x2b4bcb61,
  104964. 0x350c9b64,0x31cd86d3,0x3c8ea00a,0x384fbdbd,
  104965. 0x4c11db70,0x48d0c6c7,0x4593e01e,0x4152fda9,
  104966. 0x5f15adac,0x5bd4b01b,0x569796c2,0x52568b75,
  104967. 0x6a1936c8,0x6ed82b7f,0x639b0da6,0x675a1011,
  104968. 0x791d4014,0x7ddc5da3,0x709f7b7a,0x745e66cd,
  104969. 0x9823b6e0,0x9ce2ab57,0x91a18d8e,0x95609039,
  104970. 0x8b27c03c,0x8fe6dd8b,0x82a5fb52,0x8664e6e5,
  104971. 0xbe2b5b58,0xbaea46ef,0xb7a96036,0xb3687d81,
  104972. 0xad2f2d84,0xa9ee3033,0xa4ad16ea,0xa06c0b5d,
  104973. 0xd4326d90,0xd0f37027,0xddb056fe,0xd9714b49,
  104974. 0xc7361b4c,0xc3f706fb,0xceb42022,0xca753d95,
  104975. 0xf23a8028,0xf6fb9d9f,0xfbb8bb46,0xff79a6f1,
  104976. 0xe13ef6f4,0xe5ffeb43,0xe8bccd9a,0xec7dd02d,
  104977. 0x34867077,0x30476dc0,0x3d044b19,0x39c556ae,
  104978. 0x278206ab,0x23431b1c,0x2e003dc5,0x2ac12072,
  104979. 0x128e9dcf,0x164f8078,0x1b0ca6a1,0x1fcdbb16,
  104980. 0x018aeb13,0x054bf6a4,0x0808d07d,0x0cc9cdca,
  104981. 0x7897ab07,0x7c56b6b0,0x71159069,0x75d48dde,
  104982. 0x6b93dddb,0x6f52c06c,0x6211e6b5,0x66d0fb02,
  104983. 0x5e9f46bf,0x5a5e5b08,0x571d7dd1,0x53dc6066,
  104984. 0x4d9b3063,0x495a2dd4,0x44190b0d,0x40d816ba,
  104985. 0xaca5c697,0xa864db20,0xa527fdf9,0xa1e6e04e,
  104986. 0xbfa1b04b,0xbb60adfc,0xb6238b25,0xb2e29692,
  104987. 0x8aad2b2f,0x8e6c3698,0x832f1041,0x87ee0df6,
  104988. 0x99a95df3,0x9d684044,0x902b669d,0x94ea7b2a,
  104989. 0xe0b41de7,0xe4750050,0xe9362689,0xedf73b3e,
  104990. 0xf3b06b3b,0xf771768c,0xfa325055,0xfef34de2,
  104991. 0xc6bcf05f,0xc27dede8,0xcf3ecb31,0xcbffd686,
  104992. 0xd5b88683,0xd1799b34,0xdc3abded,0xd8fba05a,
  104993. 0x690ce0ee,0x6dcdfd59,0x608edb80,0x644fc637,
  104994. 0x7a089632,0x7ec98b85,0x738aad5c,0x774bb0eb,
  104995. 0x4f040d56,0x4bc510e1,0x46863638,0x42472b8f,
  104996. 0x5c007b8a,0x58c1663d,0x558240e4,0x51435d53,
  104997. 0x251d3b9e,0x21dc2629,0x2c9f00f0,0x285e1d47,
  104998. 0x36194d42,0x32d850f5,0x3f9b762c,0x3b5a6b9b,
  104999. 0x0315d626,0x07d4cb91,0x0a97ed48,0x0e56f0ff,
  105000. 0x1011a0fa,0x14d0bd4d,0x19939b94,0x1d528623,
  105001. 0xf12f560e,0xf5ee4bb9,0xf8ad6d60,0xfc6c70d7,
  105002. 0xe22b20d2,0xe6ea3d65,0xeba91bbc,0xef68060b,
  105003. 0xd727bbb6,0xd3e6a601,0xdea580d8,0xda649d6f,
  105004. 0xc423cd6a,0xc0e2d0dd,0xcda1f604,0xc960ebb3,
  105005. 0xbd3e8d7e,0xb9ff90c9,0xb4bcb610,0xb07daba7,
  105006. 0xae3afba2,0xaafbe615,0xa7b8c0cc,0xa379dd7b,
  105007. 0x9b3660c6,0x9ff77d71,0x92b45ba8,0x9675461f,
  105008. 0x8832161a,0x8cf30bad,0x81b02d74,0x857130c3,
  105009. 0x5d8a9099,0x594b8d2e,0x5408abf7,0x50c9b640,
  105010. 0x4e8ee645,0x4a4ffbf2,0x470cdd2b,0x43cdc09c,
  105011. 0x7b827d21,0x7f436096,0x7200464f,0x76c15bf8,
  105012. 0x68860bfd,0x6c47164a,0x61043093,0x65c52d24,
  105013. 0x119b4be9,0x155a565e,0x18197087,0x1cd86d30,
  105014. 0x029f3d35,0x065e2082,0x0b1d065b,0x0fdc1bec,
  105015. 0x3793a651,0x3352bbe6,0x3e119d3f,0x3ad08088,
  105016. 0x2497d08d,0x2056cd3a,0x2d15ebe3,0x29d4f654,
  105017. 0xc5a92679,0xc1683bce,0xcc2b1d17,0xc8ea00a0,
  105018. 0xd6ad50a5,0xd26c4d12,0xdf2f6bcb,0xdbee767c,
  105019. 0xe3a1cbc1,0xe760d676,0xea23f0af,0xeee2ed18,
  105020. 0xf0a5bd1d,0xf464a0aa,0xf9278673,0xfde69bc4,
  105021. 0x89b8fd09,0x8d79e0be,0x803ac667,0x84fbdbd0,
  105022. 0x9abc8bd5,0x9e7d9662,0x933eb0bb,0x97ffad0c,
  105023. 0xafb010b1,0xab710d06,0xa6322bdf,0xa2f33668,
  105024. 0xbcb4666d,0xb8757bda,0xb5365d03,0xb1f740b4};
  105025. /* init the encode/decode logical stream state */
  105026. int ogg_stream_init(ogg_stream_state *os,int serialno){
  105027. if(os){
  105028. memset(os,0,sizeof(*os));
  105029. os->body_storage=16*1024;
  105030. os->body_data=(unsigned char*) _ogg_malloc(os->body_storage*sizeof(*os->body_data));
  105031. os->lacing_storage=1024;
  105032. os->lacing_vals=(int*) _ogg_malloc(os->lacing_storage*sizeof(*os->lacing_vals));
  105033. os->granule_vals=(ogg_int64_t*) _ogg_malloc(os->lacing_storage*sizeof(*os->granule_vals));
  105034. os->serialno=serialno;
  105035. return(0);
  105036. }
  105037. return(-1);
  105038. }
  105039. /* _clear does not free os, only the non-flat storage within */
  105040. int ogg_stream_clear(ogg_stream_state *os){
  105041. if(os){
  105042. if(os->body_data)_ogg_free(os->body_data);
  105043. if(os->lacing_vals)_ogg_free(os->lacing_vals);
  105044. if(os->granule_vals)_ogg_free(os->granule_vals);
  105045. memset(os,0,sizeof(*os));
  105046. }
  105047. return(0);
  105048. }
  105049. int ogg_stream_destroy(ogg_stream_state *os){
  105050. if(os){
  105051. ogg_stream_clear(os);
  105052. _ogg_free(os);
  105053. }
  105054. return(0);
  105055. }
  105056. /* Helpers for ogg_stream_encode; this keeps the structure and
  105057. what's happening fairly clear */
  105058. static void _os_body_expand(ogg_stream_state *os,int needed){
  105059. if(os->body_storage<=os->body_fill+needed){
  105060. os->body_storage+=(needed+1024);
  105061. os->body_data=(unsigned char*) _ogg_realloc(os->body_data,os->body_storage*sizeof(*os->body_data));
  105062. }
  105063. }
  105064. static void _os_lacing_expand(ogg_stream_state *os,int needed){
  105065. if(os->lacing_storage<=os->lacing_fill+needed){
  105066. os->lacing_storage+=(needed+32);
  105067. os->lacing_vals=(int*)_ogg_realloc(os->lacing_vals,os->lacing_storage*sizeof(*os->lacing_vals));
  105068. os->granule_vals=(ogg_int64_t*)_ogg_realloc(os->granule_vals,os->lacing_storage*sizeof(*os->granule_vals));
  105069. }
  105070. }
  105071. /* checksum the page */
  105072. /* Direct table CRC; note that this will be faster in the future if we
  105073. perform the checksum silmultaneously with other copies */
  105074. void ogg_page_checksum_set(ogg_page *og){
  105075. if(og){
  105076. ogg_uint32_t crc_reg=0;
  105077. int i;
  105078. /* safety; needed for API behavior, but not framing code */
  105079. og->header[22]=0;
  105080. og->header[23]=0;
  105081. og->header[24]=0;
  105082. og->header[25]=0;
  105083. for(i=0;i<og->header_len;i++)
  105084. crc_reg=(crc_reg<<8)^crc_lookup[((crc_reg >> 24)&0xff)^og->header[i]];
  105085. for(i=0;i<og->body_len;i++)
  105086. crc_reg=(crc_reg<<8)^crc_lookup[((crc_reg >> 24)&0xff)^og->body[i]];
  105087. og->header[22]=(unsigned char)(crc_reg&0xff);
  105088. og->header[23]=(unsigned char)((crc_reg>>8)&0xff);
  105089. og->header[24]=(unsigned char)((crc_reg>>16)&0xff);
  105090. og->header[25]=(unsigned char)((crc_reg>>24)&0xff);
  105091. }
  105092. }
  105093. /* submit data to the internal buffer of the framing engine */
  105094. int ogg_stream_packetin(ogg_stream_state *os,ogg_packet *op){
  105095. int lacing_vals=op->bytes/255+1,i;
  105096. if(os->body_returned){
  105097. /* advance packet data according to the body_returned pointer. We
  105098. had to keep it around to return a pointer into the buffer last
  105099. call */
  105100. os->body_fill-=os->body_returned;
  105101. if(os->body_fill)
  105102. memmove(os->body_data,os->body_data+os->body_returned,
  105103. os->body_fill);
  105104. os->body_returned=0;
  105105. }
  105106. /* make sure we have the buffer storage */
  105107. _os_body_expand(os,op->bytes);
  105108. _os_lacing_expand(os,lacing_vals);
  105109. /* Copy in the submitted packet. Yes, the copy is a waste; this is
  105110. the liability of overly clean abstraction for the time being. It
  105111. will actually be fairly easy to eliminate the extra copy in the
  105112. future */
  105113. memcpy(os->body_data+os->body_fill,op->packet,op->bytes);
  105114. os->body_fill+=op->bytes;
  105115. /* Store lacing vals for this packet */
  105116. for(i=0;i<lacing_vals-1;i++){
  105117. os->lacing_vals[os->lacing_fill+i]=255;
  105118. os->granule_vals[os->lacing_fill+i]=os->granulepos;
  105119. }
  105120. os->lacing_vals[os->lacing_fill+i]=(op->bytes)%255;
  105121. os->granulepos=os->granule_vals[os->lacing_fill+i]=op->granulepos;
  105122. /* flag the first segment as the beginning of the packet */
  105123. os->lacing_vals[os->lacing_fill]|= 0x100;
  105124. os->lacing_fill+=lacing_vals;
  105125. /* for the sake of completeness */
  105126. os->packetno++;
  105127. if(op->e_o_s)os->e_o_s=1;
  105128. return(0);
  105129. }
  105130. /* This will flush remaining packets into a page (returning nonzero),
  105131. even if there is not enough data to trigger a flush normally
  105132. (undersized page). If there are no packets or partial packets to
  105133. flush, ogg_stream_flush returns 0. Note that ogg_stream_flush will
  105134. try to flush a normal sized page like ogg_stream_pageout; a call to
  105135. ogg_stream_flush does not guarantee that all packets have flushed.
  105136. Only a return value of 0 from ogg_stream_flush indicates all packet
  105137. data is flushed into pages.
  105138. since ogg_stream_flush will flush the last page in a stream even if
  105139. it's undersized, you almost certainly want to use ogg_stream_pageout
  105140. (and *not* ogg_stream_flush) unless you specifically need to flush
  105141. an page regardless of size in the middle of a stream. */
  105142. int ogg_stream_flush(ogg_stream_state *os,ogg_page *og){
  105143. int i;
  105144. int vals=0;
  105145. int maxvals=(os->lacing_fill>255?255:os->lacing_fill);
  105146. int bytes=0;
  105147. long acc=0;
  105148. ogg_int64_t granule_pos=-1;
  105149. if(maxvals==0)return(0);
  105150. /* construct a page */
  105151. /* decide how many segments to include */
  105152. /* If this is the initial header case, the first page must only include
  105153. the initial header packet */
  105154. if(os->b_o_s==0){ /* 'initial header page' case */
  105155. granule_pos=0;
  105156. for(vals=0;vals<maxvals;vals++){
  105157. if((os->lacing_vals[vals]&0x0ff)<255){
  105158. vals++;
  105159. break;
  105160. }
  105161. }
  105162. }else{
  105163. for(vals=0;vals<maxvals;vals++){
  105164. if(acc>4096)break;
  105165. acc+=os->lacing_vals[vals]&0x0ff;
  105166. if((os->lacing_vals[vals]&0xff)<255)
  105167. granule_pos=os->granule_vals[vals];
  105168. }
  105169. }
  105170. /* construct the header in temp storage */
  105171. memcpy(os->header,"OggS",4);
  105172. /* stream structure version */
  105173. os->header[4]=0x00;
  105174. /* continued packet flag? */
  105175. os->header[5]=0x00;
  105176. if((os->lacing_vals[0]&0x100)==0)os->header[5]|=0x01;
  105177. /* first page flag? */
  105178. if(os->b_o_s==0)os->header[5]|=0x02;
  105179. /* last page flag? */
  105180. if(os->e_o_s && os->lacing_fill==vals)os->header[5]|=0x04;
  105181. os->b_o_s=1;
  105182. /* 64 bits of PCM position */
  105183. for(i=6;i<14;i++){
  105184. os->header[i]=(unsigned char)(granule_pos&0xff);
  105185. granule_pos>>=8;
  105186. }
  105187. /* 32 bits of stream serial number */
  105188. {
  105189. long serialno=os->serialno;
  105190. for(i=14;i<18;i++){
  105191. os->header[i]=(unsigned char)(serialno&0xff);
  105192. serialno>>=8;
  105193. }
  105194. }
  105195. /* 32 bits of page counter (we have both counter and page header
  105196. because this val can roll over) */
  105197. if(os->pageno==-1)os->pageno=0; /* because someone called
  105198. stream_reset; this would be a
  105199. strange thing to do in an
  105200. encode stream, but it has
  105201. plausible uses */
  105202. {
  105203. long pageno=os->pageno++;
  105204. for(i=18;i<22;i++){
  105205. os->header[i]=(unsigned char)(pageno&0xff);
  105206. pageno>>=8;
  105207. }
  105208. }
  105209. /* zero for computation; filled in later */
  105210. os->header[22]=0;
  105211. os->header[23]=0;
  105212. os->header[24]=0;
  105213. os->header[25]=0;
  105214. /* segment table */
  105215. os->header[26]=(unsigned char)(vals&0xff);
  105216. for(i=0;i<vals;i++)
  105217. bytes+=os->header[i+27]=(unsigned char)(os->lacing_vals[i]&0xff);
  105218. /* set pointers in the ogg_page struct */
  105219. og->header=os->header;
  105220. og->header_len=os->header_fill=vals+27;
  105221. og->body=os->body_data+os->body_returned;
  105222. og->body_len=bytes;
  105223. /* advance the lacing data and set the body_returned pointer */
  105224. os->lacing_fill-=vals;
  105225. memmove(os->lacing_vals,os->lacing_vals+vals,os->lacing_fill*sizeof(*os->lacing_vals));
  105226. memmove(os->granule_vals,os->granule_vals+vals,os->lacing_fill*sizeof(*os->granule_vals));
  105227. os->body_returned+=bytes;
  105228. /* calculate the checksum */
  105229. ogg_page_checksum_set(og);
  105230. /* done */
  105231. return(1);
  105232. }
  105233. /* This constructs pages from buffered packet segments. The pointers
  105234. returned are to static buffers; do not free. The returned buffers are
  105235. good only until the next call (using the same ogg_stream_state) */
  105236. int ogg_stream_pageout(ogg_stream_state *os, ogg_page *og){
  105237. if((os->e_o_s&&os->lacing_fill) || /* 'were done, now flush' case */
  105238. os->body_fill-os->body_returned > 4096 ||/* 'page nominal size' case */
  105239. os->lacing_fill>=255 || /* 'segment table full' case */
  105240. (os->lacing_fill&&!os->b_o_s)){ /* 'initial header page' case */
  105241. return(ogg_stream_flush(os,og));
  105242. }
  105243. /* not enough data to construct a page and not end of stream */
  105244. return(0);
  105245. }
  105246. int ogg_stream_eos(ogg_stream_state *os){
  105247. return os->e_o_s;
  105248. }
  105249. /* DECODING PRIMITIVES: packet streaming layer **********************/
  105250. /* This has two layers to place more of the multi-serialno and paging
  105251. control in the application's hands. First, we expose a data buffer
  105252. using ogg_sync_buffer(). The app either copies into the
  105253. buffer, or passes it directly to read(), etc. We then call
  105254. ogg_sync_wrote() to tell how many bytes we just added.
  105255. Pages are returned (pointers into the buffer in ogg_sync_state)
  105256. by ogg_sync_pageout(). The page is then submitted to
  105257. ogg_stream_pagein() along with the appropriate
  105258. ogg_stream_state* (ie, matching serialno). We then get raw
  105259. packets out calling ogg_stream_packetout() with a
  105260. ogg_stream_state. */
  105261. /* initialize the struct to a known state */
  105262. int ogg_sync_init(ogg_sync_state *oy){
  105263. if(oy){
  105264. memset(oy,0,sizeof(*oy));
  105265. }
  105266. return(0);
  105267. }
  105268. /* clear non-flat storage within */
  105269. int ogg_sync_clear(ogg_sync_state *oy){
  105270. if(oy){
  105271. if(oy->data)_ogg_free(oy->data);
  105272. ogg_sync_init(oy);
  105273. }
  105274. return(0);
  105275. }
  105276. int ogg_sync_destroy(ogg_sync_state *oy){
  105277. if(oy){
  105278. ogg_sync_clear(oy);
  105279. _ogg_free(oy);
  105280. }
  105281. return(0);
  105282. }
  105283. char *ogg_sync_buffer(ogg_sync_state *oy, long size){
  105284. /* first, clear out any space that has been previously returned */
  105285. if(oy->returned){
  105286. oy->fill-=oy->returned;
  105287. if(oy->fill>0)
  105288. memmove(oy->data,oy->data+oy->returned,oy->fill);
  105289. oy->returned=0;
  105290. }
  105291. if(size>oy->storage-oy->fill){
  105292. /* We need to extend the internal buffer */
  105293. long newsize=size+oy->fill+4096; /* an extra page to be nice */
  105294. if(oy->data)
  105295. oy->data=(unsigned char*) _ogg_realloc(oy->data,newsize);
  105296. else
  105297. oy->data=(unsigned char*) _ogg_malloc(newsize);
  105298. oy->storage=newsize;
  105299. }
  105300. /* expose a segment at least as large as requested at the fill mark */
  105301. return((char *)oy->data+oy->fill);
  105302. }
  105303. int ogg_sync_wrote(ogg_sync_state *oy, long bytes){
  105304. if(oy->fill+bytes>oy->storage)return(-1);
  105305. oy->fill+=bytes;
  105306. return(0);
  105307. }
  105308. /* sync the stream. This is meant to be useful for finding page
  105309. boundaries.
  105310. return values for this:
  105311. -n) skipped n bytes
  105312. 0) page not ready; more data (no bytes skipped)
  105313. n) page synced at current location; page length n bytes
  105314. */
  105315. long ogg_sync_pageseek(ogg_sync_state *oy,ogg_page *og){
  105316. unsigned char *page=oy->data+oy->returned;
  105317. unsigned char *next;
  105318. long bytes=oy->fill-oy->returned;
  105319. if(oy->headerbytes==0){
  105320. int headerbytes,i;
  105321. if(bytes<27)return(0); /* not enough for a header */
  105322. /* verify capture pattern */
  105323. if(memcmp(page,"OggS",4))goto sync_fail;
  105324. headerbytes=page[26]+27;
  105325. if(bytes<headerbytes)return(0); /* not enough for header + seg table */
  105326. /* count up body length in the segment table */
  105327. for(i=0;i<page[26];i++)
  105328. oy->bodybytes+=page[27+i];
  105329. oy->headerbytes=headerbytes;
  105330. }
  105331. if(oy->bodybytes+oy->headerbytes>bytes)return(0);
  105332. /* The whole test page is buffered. Verify the checksum */
  105333. {
  105334. /* Grab the checksum bytes, set the header field to zero */
  105335. char chksum[4];
  105336. ogg_page log;
  105337. memcpy(chksum,page+22,4);
  105338. memset(page+22,0,4);
  105339. /* set up a temp page struct and recompute the checksum */
  105340. log.header=page;
  105341. log.header_len=oy->headerbytes;
  105342. log.body=page+oy->headerbytes;
  105343. log.body_len=oy->bodybytes;
  105344. ogg_page_checksum_set(&log);
  105345. /* Compare */
  105346. if(memcmp(chksum,page+22,4)){
  105347. /* D'oh. Mismatch! Corrupt page (or miscapture and not a page
  105348. at all) */
  105349. /* replace the computed checksum with the one actually read in */
  105350. memcpy(page+22,chksum,4);
  105351. /* Bad checksum. Lose sync */
  105352. goto sync_fail;
  105353. }
  105354. }
  105355. /* yes, have a whole page all ready to go */
  105356. {
  105357. unsigned char *page=oy->data+oy->returned;
  105358. long bytes;
  105359. if(og){
  105360. og->header=page;
  105361. og->header_len=oy->headerbytes;
  105362. og->body=page+oy->headerbytes;
  105363. og->body_len=oy->bodybytes;
  105364. }
  105365. oy->unsynced=0;
  105366. oy->returned+=(bytes=oy->headerbytes+oy->bodybytes);
  105367. oy->headerbytes=0;
  105368. oy->bodybytes=0;
  105369. return(bytes);
  105370. }
  105371. sync_fail:
  105372. oy->headerbytes=0;
  105373. oy->bodybytes=0;
  105374. /* search for possible capture */
  105375. next=(unsigned char*)memchr(page+1,'O',bytes-1);
  105376. if(!next)
  105377. next=oy->data+oy->fill;
  105378. oy->returned=next-oy->data;
  105379. return(-(next-page));
  105380. }
  105381. /* sync the stream and get a page. Keep trying until we find a page.
  105382. Supress 'sync errors' after reporting the first.
  105383. return values:
  105384. -1) recapture (hole in data)
  105385. 0) need more data
  105386. 1) page returned
  105387. Returns pointers into buffered data; invalidated by next call to
  105388. _stream, _clear, _init, or _buffer */
  105389. int ogg_sync_pageout(ogg_sync_state *oy, ogg_page *og){
  105390. /* all we need to do is verify a page at the head of the stream
  105391. buffer. If it doesn't verify, we look for the next potential
  105392. frame */
  105393. for(;;){
  105394. long ret=ogg_sync_pageseek(oy,og);
  105395. if(ret>0){
  105396. /* have a page */
  105397. return(1);
  105398. }
  105399. if(ret==0){
  105400. /* need more data */
  105401. return(0);
  105402. }
  105403. /* head did not start a synced page... skipped some bytes */
  105404. if(!oy->unsynced){
  105405. oy->unsynced=1;
  105406. return(-1);
  105407. }
  105408. /* loop. keep looking */
  105409. }
  105410. }
  105411. /* add the incoming page to the stream state; we decompose the page
  105412. into packet segments here as well. */
  105413. int ogg_stream_pagein(ogg_stream_state *os, ogg_page *og){
  105414. unsigned char *header=og->header;
  105415. unsigned char *body=og->body;
  105416. long bodysize=og->body_len;
  105417. int segptr=0;
  105418. int version=ogg_page_version(og);
  105419. int continued=ogg_page_continued(og);
  105420. int bos=ogg_page_bos(og);
  105421. int eos=ogg_page_eos(og);
  105422. ogg_int64_t granulepos=ogg_page_granulepos(og);
  105423. int serialno=ogg_page_serialno(og);
  105424. long pageno=ogg_page_pageno(og);
  105425. int segments=header[26];
  105426. /* clean up 'returned data' */
  105427. {
  105428. long lr=os->lacing_returned;
  105429. long br=os->body_returned;
  105430. /* body data */
  105431. if(br){
  105432. os->body_fill-=br;
  105433. if(os->body_fill)
  105434. memmove(os->body_data,os->body_data+br,os->body_fill);
  105435. os->body_returned=0;
  105436. }
  105437. if(lr){
  105438. /* segment table */
  105439. if(os->lacing_fill-lr){
  105440. memmove(os->lacing_vals,os->lacing_vals+lr,
  105441. (os->lacing_fill-lr)*sizeof(*os->lacing_vals));
  105442. memmove(os->granule_vals,os->granule_vals+lr,
  105443. (os->lacing_fill-lr)*sizeof(*os->granule_vals));
  105444. }
  105445. os->lacing_fill-=lr;
  105446. os->lacing_packet-=lr;
  105447. os->lacing_returned=0;
  105448. }
  105449. }
  105450. /* check the serial number */
  105451. if(serialno!=os->serialno)return(-1);
  105452. if(version>0)return(-1);
  105453. _os_lacing_expand(os,segments+1);
  105454. /* are we in sequence? */
  105455. if(pageno!=os->pageno){
  105456. int i;
  105457. /* unroll previous partial packet (if any) */
  105458. for(i=os->lacing_packet;i<os->lacing_fill;i++)
  105459. os->body_fill-=os->lacing_vals[i]&0xff;
  105460. os->lacing_fill=os->lacing_packet;
  105461. /* make a note of dropped data in segment table */
  105462. if(os->pageno!=-1){
  105463. os->lacing_vals[os->lacing_fill++]=0x400;
  105464. os->lacing_packet++;
  105465. }
  105466. }
  105467. /* are we a 'continued packet' page? If so, we may need to skip
  105468. some segments */
  105469. if(continued){
  105470. if(os->lacing_fill<1 ||
  105471. os->lacing_vals[os->lacing_fill-1]==0x400){
  105472. bos=0;
  105473. for(;segptr<segments;segptr++){
  105474. int val=header[27+segptr];
  105475. body+=val;
  105476. bodysize-=val;
  105477. if(val<255){
  105478. segptr++;
  105479. break;
  105480. }
  105481. }
  105482. }
  105483. }
  105484. if(bodysize){
  105485. _os_body_expand(os,bodysize);
  105486. memcpy(os->body_data+os->body_fill,body,bodysize);
  105487. os->body_fill+=bodysize;
  105488. }
  105489. {
  105490. int saved=-1;
  105491. while(segptr<segments){
  105492. int val=header[27+segptr];
  105493. os->lacing_vals[os->lacing_fill]=val;
  105494. os->granule_vals[os->lacing_fill]=-1;
  105495. if(bos){
  105496. os->lacing_vals[os->lacing_fill]|=0x100;
  105497. bos=0;
  105498. }
  105499. if(val<255)saved=os->lacing_fill;
  105500. os->lacing_fill++;
  105501. segptr++;
  105502. if(val<255)os->lacing_packet=os->lacing_fill;
  105503. }
  105504. /* set the granulepos on the last granuleval of the last full packet */
  105505. if(saved!=-1){
  105506. os->granule_vals[saved]=granulepos;
  105507. }
  105508. }
  105509. if(eos){
  105510. os->e_o_s=1;
  105511. if(os->lacing_fill>0)
  105512. os->lacing_vals[os->lacing_fill-1]|=0x200;
  105513. }
  105514. os->pageno=pageno+1;
  105515. return(0);
  105516. }
  105517. /* clear things to an initial state. Good to call, eg, before seeking */
  105518. int ogg_sync_reset(ogg_sync_state *oy){
  105519. oy->fill=0;
  105520. oy->returned=0;
  105521. oy->unsynced=0;
  105522. oy->headerbytes=0;
  105523. oy->bodybytes=0;
  105524. return(0);
  105525. }
  105526. int ogg_stream_reset(ogg_stream_state *os){
  105527. os->body_fill=0;
  105528. os->body_returned=0;
  105529. os->lacing_fill=0;
  105530. os->lacing_packet=0;
  105531. os->lacing_returned=0;
  105532. os->header_fill=0;
  105533. os->e_o_s=0;
  105534. os->b_o_s=0;
  105535. os->pageno=-1;
  105536. os->packetno=0;
  105537. os->granulepos=0;
  105538. return(0);
  105539. }
  105540. int ogg_stream_reset_serialno(ogg_stream_state *os,int serialno){
  105541. ogg_stream_reset(os);
  105542. os->serialno=serialno;
  105543. return(0);
  105544. }
  105545. static int _packetout(ogg_stream_state *os,ogg_packet *op,int adv){
  105546. /* The last part of decode. We have the stream broken into packet
  105547. segments. Now we need to group them into packets (or return the
  105548. out of sync markers) */
  105549. int ptr=os->lacing_returned;
  105550. if(os->lacing_packet<=ptr)return(0);
  105551. if(os->lacing_vals[ptr]&0x400){
  105552. /* we need to tell the codec there's a gap; it might need to
  105553. handle previous packet dependencies. */
  105554. os->lacing_returned++;
  105555. os->packetno++;
  105556. return(-1);
  105557. }
  105558. if(!op && !adv)return(1); /* just using peek as an inexpensive way
  105559. to ask if there's a whole packet
  105560. waiting */
  105561. /* Gather the whole packet. We'll have no holes or a partial packet */
  105562. {
  105563. int size=os->lacing_vals[ptr]&0xff;
  105564. int bytes=size;
  105565. int eos=os->lacing_vals[ptr]&0x200; /* last packet of the stream? */
  105566. int bos=os->lacing_vals[ptr]&0x100; /* first packet of the stream? */
  105567. while(size==255){
  105568. int val=os->lacing_vals[++ptr];
  105569. size=val&0xff;
  105570. if(val&0x200)eos=0x200;
  105571. bytes+=size;
  105572. }
  105573. if(op){
  105574. op->e_o_s=eos;
  105575. op->b_o_s=bos;
  105576. op->packet=os->body_data+os->body_returned;
  105577. op->packetno=os->packetno;
  105578. op->granulepos=os->granule_vals[ptr];
  105579. op->bytes=bytes;
  105580. }
  105581. if(adv){
  105582. os->body_returned+=bytes;
  105583. os->lacing_returned=ptr+1;
  105584. os->packetno++;
  105585. }
  105586. }
  105587. return(1);
  105588. }
  105589. int ogg_stream_packetout(ogg_stream_state *os,ogg_packet *op){
  105590. return _packetout(os,op,1);
  105591. }
  105592. int ogg_stream_packetpeek(ogg_stream_state *os,ogg_packet *op){
  105593. return _packetout(os,op,0);
  105594. }
  105595. void ogg_packet_clear(ogg_packet *op) {
  105596. _ogg_free(op->packet);
  105597. memset(op, 0, sizeof(*op));
  105598. }
  105599. #ifdef _V_SELFTEST
  105600. #include <stdio.h>
  105601. ogg_stream_state os_en, os_de;
  105602. ogg_sync_state oy;
  105603. void checkpacket(ogg_packet *op,int len, int no, int pos){
  105604. long j;
  105605. static int sequence=0;
  105606. static int lastno=0;
  105607. if(op->bytes!=len){
  105608. fprintf(stderr,"incorrect packet length!\n");
  105609. exit(1);
  105610. }
  105611. if(op->granulepos!=pos){
  105612. fprintf(stderr,"incorrect packet position!\n");
  105613. exit(1);
  105614. }
  105615. /* packet number just follows sequence/gap; adjust the input number
  105616. for that */
  105617. if(no==0){
  105618. sequence=0;
  105619. }else{
  105620. sequence++;
  105621. if(no>lastno+1)
  105622. sequence++;
  105623. }
  105624. lastno=no;
  105625. if(op->packetno!=sequence){
  105626. fprintf(stderr,"incorrect packet sequence %ld != %d\n",
  105627. (long)(op->packetno),sequence);
  105628. exit(1);
  105629. }
  105630. /* Test data */
  105631. for(j=0;j<op->bytes;j++)
  105632. if(op->packet[j]!=((j+no)&0xff)){
  105633. fprintf(stderr,"body data mismatch (1) at pos %ld: %x!=%lx!\n\n",
  105634. j,op->packet[j],(j+no)&0xff);
  105635. exit(1);
  105636. }
  105637. }
  105638. void check_page(unsigned char *data,const int *header,ogg_page *og){
  105639. long j;
  105640. /* Test data */
  105641. for(j=0;j<og->body_len;j++)
  105642. if(og->body[j]!=data[j]){
  105643. fprintf(stderr,"body data mismatch (2) at pos %ld: %x!=%x!\n\n",
  105644. j,data[j],og->body[j]);
  105645. exit(1);
  105646. }
  105647. /* Test header */
  105648. for(j=0;j<og->header_len;j++){
  105649. if(og->header[j]!=header[j]){
  105650. fprintf(stderr,"header content mismatch at pos %ld:\n",j);
  105651. for(j=0;j<header[26]+27;j++)
  105652. fprintf(stderr," (%ld)%02x:%02x",j,header[j],og->header[j]);
  105653. fprintf(stderr,"\n");
  105654. exit(1);
  105655. }
  105656. }
  105657. if(og->header_len!=header[26]+27){
  105658. fprintf(stderr,"header length incorrect! (%ld!=%d)\n",
  105659. og->header_len,header[26]+27);
  105660. exit(1);
  105661. }
  105662. }
  105663. void print_header(ogg_page *og){
  105664. int j;
  105665. fprintf(stderr,"\nHEADER:\n");
  105666. fprintf(stderr," capture: %c %c %c %c version: %d flags: %x\n",
  105667. og->header[0],og->header[1],og->header[2],og->header[3],
  105668. (int)og->header[4],(int)og->header[5]);
  105669. fprintf(stderr," granulepos: %d serialno: %d pageno: %ld\n",
  105670. (og->header[9]<<24)|(og->header[8]<<16)|
  105671. (og->header[7]<<8)|og->header[6],
  105672. (og->header[17]<<24)|(og->header[16]<<16)|
  105673. (og->header[15]<<8)|og->header[14],
  105674. ((long)(og->header[21])<<24)|(og->header[20]<<16)|
  105675. (og->header[19]<<8)|og->header[18]);
  105676. fprintf(stderr," checksum: %02x:%02x:%02x:%02x\n segments: %d (",
  105677. (int)og->header[22],(int)og->header[23],
  105678. (int)og->header[24],(int)og->header[25],
  105679. (int)og->header[26]);
  105680. for(j=27;j<og->header_len;j++)
  105681. fprintf(stderr,"%d ",(int)og->header[j]);
  105682. fprintf(stderr,")\n\n");
  105683. }
  105684. void copy_page(ogg_page *og){
  105685. unsigned char *temp=_ogg_malloc(og->header_len);
  105686. memcpy(temp,og->header,og->header_len);
  105687. og->header=temp;
  105688. temp=_ogg_malloc(og->body_len);
  105689. memcpy(temp,og->body,og->body_len);
  105690. og->body=temp;
  105691. }
  105692. void free_page(ogg_page *og){
  105693. _ogg_free (og->header);
  105694. _ogg_free (og->body);
  105695. }
  105696. void error(void){
  105697. fprintf(stderr,"error!\n");
  105698. exit(1);
  105699. }
  105700. /* 17 only */
  105701. const int head1_0[] = {0x4f,0x67,0x67,0x53,0,0x06,
  105702. 0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,
  105703. 0x01,0x02,0x03,0x04,0,0,0,0,
  105704. 0x15,0xed,0xec,0x91,
  105705. 1,
  105706. 17};
  105707. /* 17, 254, 255, 256, 500, 510, 600 byte, pad */
  105708. const int head1_1[] = {0x4f,0x67,0x67,0x53,0,0x02,
  105709. 0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,
  105710. 0x01,0x02,0x03,0x04,0,0,0,0,
  105711. 0x59,0x10,0x6c,0x2c,
  105712. 1,
  105713. 17};
  105714. const int head2_1[] = {0x4f,0x67,0x67,0x53,0,0x04,
  105715. 0x07,0x18,0x00,0x00,0x00,0x00,0x00,0x00,
  105716. 0x01,0x02,0x03,0x04,1,0,0,0,
  105717. 0x89,0x33,0x85,0xce,
  105718. 13,
  105719. 254,255,0,255,1,255,245,255,255,0,
  105720. 255,255,90};
  105721. /* nil packets; beginning,middle,end */
  105722. const int head1_2[] = {0x4f,0x67,0x67,0x53,0,0x02,
  105723. 0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,
  105724. 0x01,0x02,0x03,0x04,0,0,0,0,
  105725. 0xff,0x7b,0x23,0x17,
  105726. 1,
  105727. 0};
  105728. const int head2_2[] = {0x4f,0x67,0x67,0x53,0,0x04,
  105729. 0x07,0x28,0x00,0x00,0x00,0x00,0x00,0x00,
  105730. 0x01,0x02,0x03,0x04,1,0,0,0,
  105731. 0x5c,0x3f,0x66,0xcb,
  105732. 17,
  105733. 17,254,255,0,0,255,1,0,255,245,255,255,0,
  105734. 255,255,90,0};
  105735. /* large initial packet */
  105736. const int head1_3[] = {0x4f,0x67,0x67,0x53,0,0x02,
  105737. 0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,
  105738. 0x01,0x02,0x03,0x04,0,0,0,0,
  105739. 0x01,0x27,0x31,0xaa,
  105740. 18,
  105741. 255,255,255,255,255,255,255,255,
  105742. 255,255,255,255,255,255,255,255,255,10};
  105743. const int head2_3[] = {0x4f,0x67,0x67,0x53,0,0x04,
  105744. 0x07,0x08,0x00,0x00,0x00,0x00,0x00,0x00,
  105745. 0x01,0x02,0x03,0x04,1,0,0,0,
  105746. 0x7f,0x4e,0x8a,0xd2,
  105747. 4,
  105748. 255,4,255,0};
  105749. /* continuing packet test */
  105750. const int head1_4[] = {0x4f,0x67,0x67,0x53,0,0x02,
  105751. 0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,
  105752. 0x01,0x02,0x03,0x04,0,0,0,0,
  105753. 0xff,0x7b,0x23,0x17,
  105754. 1,
  105755. 0};
  105756. const int head2_4[] = {0x4f,0x67,0x67,0x53,0,0x00,
  105757. 0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,
  105758. 0x01,0x02,0x03,0x04,1,0,0,0,
  105759. 0x54,0x05,0x51,0xc8,
  105760. 17,
  105761. 255,255,255,255,255,255,255,255,
  105762. 255,255,255,255,255,255,255,255,255};
  105763. const int head3_4[] = {0x4f,0x67,0x67,0x53,0,0x05,
  105764. 0x07,0x0c,0x00,0x00,0x00,0x00,0x00,0x00,
  105765. 0x01,0x02,0x03,0x04,2,0,0,0,
  105766. 0xc8,0xc3,0xcb,0xed,
  105767. 5,
  105768. 10,255,4,255,0};
  105769. /* page with the 255 segment limit */
  105770. const int head1_5[] = {0x4f,0x67,0x67,0x53,0,0x02,
  105771. 0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,
  105772. 0x01,0x02,0x03,0x04,0,0,0,0,
  105773. 0xff,0x7b,0x23,0x17,
  105774. 1,
  105775. 0};
  105776. const int head2_5[] = {0x4f,0x67,0x67,0x53,0,0x00,
  105777. 0x07,0xfc,0x03,0x00,0x00,0x00,0x00,0x00,
  105778. 0x01,0x02,0x03,0x04,1,0,0,0,
  105779. 0xed,0x2a,0x2e,0xa7,
  105780. 255,
  105781. 10,10,10,10,10,10,10,10,
  105782. 10,10,10,10,10,10,10,10,
  105783. 10,10,10,10,10,10,10,10,
  105784. 10,10,10,10,10,10,10,10,
  105785. 10,10,10,10,10,10,10,10,
  105786. 10,10,10,10,10,10,10,10,
  105787. 10,10,10,10,10,10,10,10,
  105788. 10,10,10,10,10,10,10,10,
  105789. 10,10,10,10,10,10,10,10,
  105790. 10,10,10,10,10,10,10,10,
  105791. 10,10,10,10,10,10,10,10,
  105792. 10,10,10,10,10,10,10,10,
  105793. 10,10,10,10,10,10,10,10,
  105794. 10,10,10,10,10,10,10,10,
  105795. 10,10,10,10,10,10,10,10,
  105796. 10,10,10,10,10,10,10,10,
  105797. 10,10,10,10,10,10,10,10,
  105798. 10,10,10,10,10,10,10,10,
  105799. 10,10,10,10,10,10,10,10,
  105800. 10,10,10,10,10,10,10,10,
  105801. 10,10,10,10,10,10,10,10,
  105802. 10,10,10,10,10,10,10,10,
  105803. 10,10,10,10,10,10,10,10,
  105804. 10,10,10,10,10,10,10,10,
  105805. 10,10,10,10,10,10,10,10,
  105806. 10,10,10,10,10,10,10,10,
  105807. 10,10,10,10,10,10,10,10,
  105808. 10,10,10,10,10,10,10,10,
  105809. 10,10,10,10,10,10,10,10,
  105810. 10,10,10,10,10,10,10,10,
  105811. 10,10,10,10,10,10,10,10,
  105812. 10,10,10,10,10,10,10};
  105813. const int head3_5[] = {0x4f,0x67,0x67,0x53,0,0x04,
  105814. 0x07,0x00,0x04,0x00,0x00,0x00,0x00,0x00,
  105815. 0x01,0x02,0x03,0x04,2,0,0,0,
  105816. 0x6c,0x3b,0x82,0x3d,
  105817. 1,
  105818. 50};
  105819. /* packet that overspans over an entire page */
  105820. const int head1_6[] = {0x4f,0x67,0x67,0x53,0,0x02,
  105821. 0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,
  105822. 0x01,0x02,0x03,0x04,0,0,0,0,
  105823. 0xff,0x7b,0x23,0x17,
  105824. 1,
  105825. 0};
  105826. const int head2_6[] = {0x4f,0x67,0x67,0x53,0,0x00,
  105827. 0x07,0x04,0x00,0x00,0x00,0x00,0x00,0x00,
  105828. 0x01,0x02,0x03,0x04,1,0,0,0,
  105829. 0x3c,0xd9,0x4d,0x3f,
  105830. 17,
  105831. 100,255,255,255,255,255,255,255,255,
  105832. 255,255,255,255,255,255,255,255};
  105833. const int head3_6[] = {0x4f,0x67,0x67,0x53,0,0x01,
  105834. 0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,
  105835. 0x01,0x02,0x03,0x04,2,0,0,0,
  105836. 0x01,0xd2,0xe5,0xe5,
  105837. 17,
  105838. 255,255,255,255,255,255,255,255,
  105839. 255,255,255,255,255,255,255,255,255};
  105840. const int head4_6[] = {0x4f,0x67,0x67,0x53,0,0x05,
  105841. 0x07,0x10,0x00,0x00,0x00,0x00,0x00,0x00,
  105842. 0x01,0x02,0x03,0x04,3,0,0,0,
  105843. 0xef,0xdd,0x88,0xde,
  105844. 7,
  105845. 255,255,75,255,4,255,0};
  105846. /* packet that overspans over an entire page */
  105847. const int head1_7[] = {0x4f,0x67,0x67,0x53,0,0x02,
  105848. 0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,
  105849. 0x01,0x02,0x03,0x04,0,0,0,0,
  105850. 0xff,0x7b,0x23,0x17,
  105851. 1,
  105852. 0};
  105853. const int head2_7[] = {0x4f,0x67,0x67,0x53,0,0x00,
  105854. 0x07,0x04,0x00,0x00,0x00,0x00,0x00,0x00,
  105855. 0x01,0x02,0x03,0x04,1,0,0,0,
  105856. 0x3c,0xd9,0x4d,0x3f,
  105857. 17,
  105858. 100,255,255,255,255,255,255,255,255,
  105859. 255,255,255,255,255,255,255,255};
  105860. const int head3_7[] = {0x4f,0x67,0x67,0x53,0,0x05,
  105861. 0x07,0x08,0x00,0x00,0x00,0x00,0x00,0x00,
  105862. 0x01,0x02,0x03,0x04,2,0,0,0,
  105863. 0xd4,0xe0,0x60,0xe5,
  105864. 1,0};
  105865. void test_pack(const int *pl, const int **headers, int byteskip,
  105866. int pageskip, int packetskip){
  105867. unsigned char *data=_ogg_malloc(1024*1024); /* for scripted test cases only */
  105868. long inptr=0;
  105869. long outptr=0;
  105870. long deptr=0;
  105871. long depacket=0;
  105872. long granule_pos=7,pageno=0;
  105873. int i,j,packets,pageout=pageskip;
  105874. int eosflag=0;
  105875. int bosflag=0;
  105876. int byteskipcount=0;
  105877. ogg_stream_reset(&os_en);
  105878. ogg_stream_reset(&os_de);
  105879. ogg_sync_reset(&oy);
  105880. for(packets=0;packets<packetskip;packets++)
  105881. depacket+=pl[packets];
  105882. for(packets=0;;packets++)if(pl[packets]==-1)break;
  105883. for(i=0;i<packets;i++){
  105884. /* construct a test packet */
  105885. ogg_packet op;
  105886. int len=pl[i];
  105887. op.packet=data+inptr;
  105888. op.bytes=len;
  105889. op.e_o_s=(pl[i+1]<0?1:0);
  105890. op.granulepos=granule_pos;
  105891. granule_pos+=1024;
  105892. for(j=0;j<len;j++)data[inptr++]=i+j;
  105893. /* submit the test packet */
  105894. ogg_stream_packetin(&os_en,&op);
  105895. /* retrieve any finished pages */
  105896. {
  105897. ogg_page og;
  105898. while(ogg_stream_pageout(&os_en,&og)){
  105899. /* We have a page. Check it carefully */
  105900. fprintf(stderr,"%ld, ",pageno);
  105901. if(headers[pageno]==NULL){
  105902. fprintf(stderr,"coded too many pages!\n");
  105903. exit(1);
  105904. }
  105905. check_page(data+outptr,headers[pageno],&og);
  105906. outptr+=og.body_len;
  105907. pageno++;
  105908. if(pageskip){
  105909. bosflag=1;
  105910. pageskip--;
  105911. deptr+=og.body_len;
  105912. }
  105913. /* have a complete page; submit it to sync/decode */
  105914. {
  105915. ogg_page og_de;
  105916. ogg_packet op_de,op_de2;
  105917. char *buf=ogg_sync_buffer(&oy,og.header_len+og.body_len);
  105918. char *next=buf;
  105919. byteskipcount+=og.header_len;
  105920. if(byteskipcount>byteskip){
  105921. memcpy(next,og.header,byteskipcount-byteskip);
  105922. next+=byteskipcount-byteskip;
  105923. byteskipcount=byteskip;
  105924. }
  105925. byteskipcount+=og.body_len;
  105926. if(byteskipcount>byteskip){
  105927. memcpy(next,og.body,byteskipcount-byteskip);
  105928. next+=byteskipcount-byteskip;
  105929. byteskipcount=byteskip;
  105930. }
  105931. ogg_sync_wrote(&oy,next-buf);
  105932. while(1){
  105933. int ret=ogg_sync_pageout(&oy,&og_de);
  105934. if(ret==0)break;
  105935. if(ret<0)continue;
  105936. /* got a page. Happy happy. Verify that it's good. */
  105937. fprintf(stderr,"(%ld), ",pageout);
  105938. check_page(data+deptr,headers[pageout],&og_de);
  105939. deptr+=og_de.body_len;
  105940. pageout++;
  105941. /* submit it to deconstitution */
  105942. ogg_stream_pagein(&os_de,&og_de);
  105943. /* packets out? */
  105944. while(ogg_stream_packetpeek(&os_de,&op_de2)>0){
  105945. ogg_stream_packetpeek(&os_de,NULL);
  105946. ogg_stream_packetout(&os_de,&op_de); /* just catching them all */
  105947. /* verify peek and out match */
  105948. if(memcmp(&op_de,&op_de2,sizeof(op_de))){
  105949. fprintf(stderr,"packetout != packetpeek! pos=%ld\n",
  105950. depacket);
  105951. exit(1);
  105952. }
  105953. /* verify the packet! */
  105954. /* check data */
  105955. if(memcmp(data+depacket,op_de.packet,op_de.bytes)){
  105956. fprintf(stderr,"packet data mismatch in decode! pos=%ld\n",
  105957. depacket);
  105958. exit(1);
  105959. }
  105960. /* check bos flag */
  105961. if(bosflag==0 && op_de.b_o_s==0){
  105962. fprintf(stderr,"b_o_s flag not set on packet!\n");
  105963. exit(1);
  105964. }
  105965. if(bosflag && op_de.b_o_s){
  105966. fprintf(stderr,"b_o_s flag incorrectly set on packet!\n");
  105967. exit(1);
  105968. }
  105969. bosflag=1;
  105970. depacket+=op_de.bytes;
  105971. /* check eos flag */
  105972. if(eosflag){
  105973. fprintf(stderr,"Multiple decoded packets with eos flag!\n");
  105974. exit(1);
  105975. }
  105976. if(op_de.e_o_s)eosflag=1;
  105977. /* check granulepos flag */
  105978. if(op_de.granulepos!=-1){
  105979. fprintf(stderr," granule:%ld ",(long)op_de.granulepos);
  105980. }
  105981. }
  105982. }
  105983. }
  105984. }
  105985. }
  105986. }
  105987. _ogg_free(data);
  105988. if(headers[pageno]!=NULL){
  105989. fprintf(stderr,"did not write last page!\n");
  105990. exit(1);
  105991. }
  105992. if(headers[pageout]!=NULL){
  105993. fprintf(stderr,"did not decode last page!\n");
  105994. exit(1);
  105995. }
  105996. if(inptr!=outptr){
  105997. fprintf(stderr,"encoded page data incomplete!\n");
  105998. exit(1);
  105999. }
  106000. if(inptr!=deptr){
  106001. fprintf(stderr,"decoded page data incomplete!\n");
  106002. exit(1);
  106003. }
  106004. if(inptr!=depacket){
  106005. fprintf(stderr,"decoded packet data incomplete!\n");
  106006. exit(1);
  106007. }
  106008. if(!eosflag){
  106009. fprintf(stderr,"Never got a packet with EOS set!\n");
  106010. exit(1);
  106011. }
  106012. fprintf(stderr,"ok.\n");
  106013. }
  106014. int main(void){
  106015. ogg_stream_init(&os_en,0x04030201);
  106016. ogg_stream_init(&os_de,0x04030201);
  106017. ogg_sync_init(&oy);
  106018. /* Exercise each code path in the framing code. Also verify that
  106019. the checksums are working. */
  106020. {
  106021. /* 17 only */
  106022. const int packets[]={17, -1};
  106023. const int *headret[]={head1_0,NULL};
  106024. fprintf(stderr,"testing single page encoding... ");
  106025. test_pack(packets,headret,0,0,0);
  106026. }
  106027. {
  106028. /* 17, 254, 255, 256, 500, 510, 600 byte, pad */
  106029. const int packets[]={17, 254, 255, 256, 500, 510, 600, -1};
  106030. const int *headret[]={head1_1,head2_1,NULL};
  106031. fprintf(stderr,"testing basic page encoding... ");
  106032. test_pack(packets,headret,0,0,0);
  106033. }
  106034. {
  106035. /* nil packets; beginning,middle,end */
  106036. const int packets[]={0,17, 254, 255, 0, 256, 0, 500, 510, 600, 0, -1};
  106037. const int *headret[]={head1_2,head2_2,NULL};
  106038. fprintf(stderr,"testing basic nil packets... ");
  106039. test_pack(packets,headret,0,0,0);
  106040. }
  106041. {
  106042. /* large initial packet */
  106043. const int packets[]={4345,259,255,-1};
  106044. const int *headret[]={head1_3,head2_3,NULL};
  106045. fprintf(stderr,"testing initial-packet lacing > 4k... ");
  106046. test_pack(packets,headret,0,0,0);
  106047. }
  106048. {
  106049. /* continuing packet test */
  106050. const int packets[]={0,4345,259,255,-1};
  106051. const int *headret[]={head1_4,head2_4,head3_4,NULL};
  106052. fprintf(stderr,"testing single packet page span... ");
  106053. test_pack(packets,headret,0,0,0);
  106054. }
  106055. /* page with the 255 segment limit */
  106056. {
  106057. const int packets[]={0,10,10,10,10,10,10,10,10,
  106058. 10,10,10,10,10,10,10,10,
  106059. 10,10,10,10,10,10,10,10,
  106060. 10,10,10,10,10,10,10,10,
  106061. 10,10,10,10,10,10,10,10,
  106062. 10,10,10,10,10,10,10,10,
  106063. 10,10,10,10,10,10,10,10,
  106064. 10,10,10,10,10,10,10,10,
  106065. 10,10,10,10,10,10,10,10,
  106066. 10,10,10,10,10,10,10,10,
  106067. 10,10,10,10,10,10,10,10,
  106068. 10,10,10,10,10,10,10,10,
  106069. 10,10,10,10,10,10,10,10,
  106070. 10,10,10,10,10,10,10,10,
  106071. 10,10,10,10,10,10,10,10,
  106072. 10,10,10,10,10,10,10,10,
  106073. 10,10,10,10,10,10,10,10,
  106074. 10,10,10,10,10,10,10,10,
  106075. 10,10,10,10,10,10,10,10,
  106076. 10,10,10,10,10,10,10,10,
  106077. 10,10,10,10,10,10,10,10,
  106078. 10,10,10,10,10,10,10,10,
  106079. 10,10,10,10,10,10,10,10,
  106080. 10,10,10,10,10,10,10,10,
  106081. 10,10,10,10,10,10,10,10,
  106082. 10,10,10,10,10,10,10,10,
  106083. 10,10,10,10,10,10,10,10,
  106084. 10,10,10,10,10,10,10,10,
  106085. 10,10,10,10,10,10,10,10,
  106086. 10,10,10,10,10,10,10,10,
  106087. 10,10,10,10,10,10,10,10,
  106088. 10,10,10,10,10,10,10,50,-1};
  106089. const int *headret[]={head1_5,head2_5,head3_5,NULL};
  106090. fprintf(stderr,"testing max packet segments... ");
  106091. test_pack(packets,headret,0,0,0);
  106092. }
  106093. {
  106094. /* packet that overspans over an entire page */
  106095. const int packets[]={0,100,9000,259,255,-1};
  106096. const int *headret[]={head1_6,head2_6,head3_6,head4_6,NULL};
  106097. fprintf(stderr,"testing very large packets... ");
  106098. test_pack(packets,headret,0,0,0);
  106099. }
  106100. {
  106101. /* test for the libogg 1.1.1 resync in large continuation bug
  106102. found by Josh Coalson) */
  106103. const int packets[]={0,100,9000,259,255,-1};
  106104. const int *headret[]={head1_6,head2_6,head3_6,head4_6,NULL};
  106105. fprintf(stderr,"testing continuation resync in very large packets... ");
  106106. test_pack(packets,headret,100,2,3);
  106107. }
  106108. {
  106109. /* term only page. why not? */
  106110. const int packets[]={0,100,4080,-1};
  106111. const int *headret[]={head1_7,head2_7,head3_7,NULL};
  106112. fprintf(stderr,"testing zero data page (1 nil packet)... ");
  106113. test_pack(packets,headret,0,0,0);
  106114. }
  106115. {
  106116. /* build a bunch of pages for testing */
  106117. unsigned char *data=_ogg_malloc(1024*1024);
  106118. int pl[]={0,100,4079,2956,2057,76,34,912,0,234,1000,1000,1000,300,-1};
  106119. int inptr=0,i,j;
  106120. ogg_page og[5];
  106121. ogg_stream_reset(&os_en);
  106122. for(i=0;pl[i]!=-1;i++){
  106123. ogg_packet op;
  106124. int len=pl[i];
  106125. op.packet=data+inptr;
  106126. op.bytes=len;
  106127. op.e_o_s=(pl[i+1]<0?1:0);
  106128. op.granulepos=(i+1)*1000;
  106129. for(j=0;j<len;j++)data[inptr++]=i+j;
  106130. ogg_stream_packetin(&os_en,&op);
  106131. }
  106132. _ogg_free(data);
  106133. /* retrieve finished pages */
  106134. for(i=0;i<5;i++){
  106135. if(ogg_stream_pageout(&os_en,&og[i])==0){
  106136. fprintf(stderr,"Too few pages output building sync tests!\n");
  106137. exit(1);
  106138. }
  106139. copy_page(&og[i]);
  106140. }
  106141. /* Test lost pages on pagein/packetout: no rollback */
  106142. {
  106143. ogg_page temp;
  106144. ogg_packet test;
  106145. fprintf(stderr,"Testing loss of pages... ");
  106146. ogg_sync_reset(&oy);
  106147. ogg_stream_reset(&os_de);
  106148. for(i=0;i<5;i++){
  106149. memcpy(ogg_sync_buffer(&oy,og[i].header_len),og[i].header,
  106150. og[i].header_len);
  106151. ogg_sync_wrote(&oy,og[i].header_len);
  106152. memcpy(ogg_sync_buffer(&oy,og[i].body_len),og[i].body,og[i].body_len);
  106153. ogg_sync_wrote(&oy,og[i].body_len);
  106154. }
  106155. ogg_sync_pageout(&oy,&temp);
  106156. ogg_stream_pagein(&os_de,&temp);
  106157. ogg_sync_pageout(&oy,&temp);
  106158. ogg_stream_pagein(&os_de,&temp);
  106159. ogg_sync_pageout(&oy,&temp);
  106160. /* skip */
  106161. ogg_sync_pageout(&oy,&temp);
  106162. ogg_stream_pagein(&os_de,&temp);
  106163. /* do we get the expected results/packets? */
  106164. if(ogg_stream_packetout(&os_de,&test)!=1)error();
  106165. checkpacket(&test,0,0,0);
  106166. if(ogg_stream_packetout(&os_de,&test)!=1)error();
  106167. checkpacket(&test,100,1,-1);
  106168. if(ogg_stream_packetout(&os_de,&test)!=1)error();
  106169. checkpacket(&test,4079,2,3000);
  106170. if(ogg_stream_packetout(&os_de,&test)!=-1){
  106171. fprintf(stderr,"Error: loss of page did not return error\n");
  106172. exit(1);
  106173. }
  106174. if(ogg_stream_packetout(&os_de,&test)!=1)error();
  106175. checkpacket(&test,76,5,-1);
  106176. if(ogg_stream_packetout(&os_de,&test)!=1)error();
  106177. checkpacket(&test,34,6,-1);
  106178. fprintf(stderr,"ok.\n");
  106179. }
  106180. /* Test lost pages on pagein/packetout: rollback with continuation */
  106181. {
  106182. ogg_page temp;
  106183. ogg_packet test;
  106184. fprintf(stderr,"Testing loss of pages (rollback required)... ");
  106185. ogg_sync_reset(&oy);
  106186. ogg_stream_reset(&os_de);
  106187. for(i=0;i<5;i++){
  106188. memcpy(ogg_sync_buffer(&oy,og[i].header_len),og[i].header,
  106189. og[i].header_len);
  106190. ogg_sync_wrote(&oy,og[i].header_len);
  106191. memcpy(ogg_sync_buffer(&oy,og[i].body_len),og[i].body,og[i].body_len);
  106192. ogg_sync_wrote(&oy,og[i].body_len);
  106193. }
  106194. ogg_sync_pageout(&oy,&temp);
  106195. ogg_stream_pagein(&os_de,&temp);
  106196. ogg_sync_pageout(&oy,&temp);
  106197. ogg_stream_pagein(&os_de,&temp);
  106198. ogg_sync_pageout(&oy,&temp);
  106199. ogg_stream_pagein(&os_de,&temp);
  106200. ogg_sync_pageout(&oy,&temp);
  106201. /* skip */
  106202. ogg_sync_pageout(&oy,&temp);
  106203. ogg_stream_pagein(&os_de,&temp);
  106204. /* do we get the expected results/packets? */
  106205. if(ogg_stream_packetout(&os_de,&test)!=1)error();
  106206. checkpacket(&test,0,0,0);
  106207. if(ogg_stream_packetout(&os_de,&test)!=1)error();
  106208. checkpacket(&test,100,1,-1);
  106209. if(ogg_stream_packetout(&os_de,&test)!=1)error();
  106210. checkpacket(&test,4079,2,3000);
  106211. if(ogg_stream_packetout(&os_de,&test)!=1)error();
  106212. checkpacket(&test,2956,3,4000);
  106213. if(ogg_stream_packetout(&os_de,&test)!=-1){
  106214. fprintf(stderr,"Error: loss of page did not return error\n");
  106215. exit(1);
  106216. }
  106217. if(ogg_stream_packetout(&os_de,&test)!=1)error();
  106218. checkpacket(&test,300,13,14000);
  106219. fprintf(stderr,"ok.\n");
  106220. }
  106221. /* the rest only test sync */
  106222. {
  106223. ogg_page og_de;
  106224. /* Test fractional page inputs: incomplete capture */
  106225. fprintf(stderr,"Testing sync on partial inputs... ");
  106226. ogg_sync_reset(&oy);
  106227. memcpy(ogg_sync_buffer(&oy,og[1].header_len),og[1].header,
  106228. 3);
  106229. ogg_sync_wrote(&oy,3);
  106230. if(ogg_sync_pageout(&oy,&og_de)>0)error();
  106231. /* Test fractional page inputs: incomplete fixed header */
  106232. memcpy(ogg_sync_buffer(&oy,og[1].header_len),og[1].header+3,
  106233. 20);
  106234. ogg_sync_wrote(&oy,20);
  106235. if(ogg_sync_pageout(&oy,&og_de)>0)error();
  106236. /* Test fractional page inputs: incomplete header */
  106237. memcpy(ogg_sync_buffer(&oy,og[1].header_len),og[1].header+23,
  106238. 5);
  106239. ogg_sync_wrote(&oy,5);
  106240. if(ogg_sync_pageout(&oy,&og_de)>0)error();
  106241. /* Test fractional page inputs: incomplete body */
  106242. memcpy(ogg_sync_buffer(&oy,og[1].header_len),og[1].header+28,
  106243. og[1].header_len-28);
  106244. ogg_sync_wrote(&oy,og[1].header_len-28);
  106245. if(ogg_sync_pageout(&oy,&og_de)>0)error();
  106246. memcpy(ogg_sync_buffer(&oy,og[1].body_len),og[1].body,1000);
  106247. ogg_sync_wrote(&oy,1000);
  106248. if(ogg_sync_pageout(&oy,&og_de)>0)error();
  106249. memcpy(ogg_sync_buffer(&oy,og[1].body_len),og[1].body+1000,
  106250. og[1].body_len-1000);
  106251. ogg_sync_wrote(&oy,og[1].body_len-1000);
  106252. if(ogg_sync_pageout(&oy,&og_de)<=0)error();
  106253. fprintf(stderr,"ok.\n");
  106254. }
  106255. /* Test fractional page inputs: page + incomplete capture */
  106256. {
  106257. ogg_page og_de;
  106258. fprintf(stderr,"Testing sync on 1+partial inputs... ");
  106259. ogg_sync_reset(&oy);
  106260. memcpy(ogg_sync_buffer(&oy,og[1].header_len),og[1].header,
  106261. og[1].header_len);
  106262. ogg_sync_wrote(&oy,og[1].header_len);
  106263. memcpy(ogg_sync_buffer(&oy,og[1].body_len),og[1].body,
  106264. og[1].body_len);
  106265. ogg_sync_wrote(&oy,og[1].body_len);
  106266. memcpy(ogg_sync_buffer(&oy,og[1].header_len),og[1].header,
  106267. 20);
  106268. ogg_sync_wrote(&oy,20);
  106269. if(ogg_sync_pageout(&oy,&og_de)<=0)error();
  106270. if(ogg_sync_pageout(&oy,&og_de)>0)error();
  106271. memcpy(ogg_sync_buffer(&oy,og[1].header_len),og[1].header+20,
  106272. og[1].header_len-20);
  106273. ogg_sync_wrote(&oy,og[1].header_len-20);
  106274. memcpy(ogg_sync_buffer(&oy,og[1].body_len),og[1].body,
  106275. og[1].body_len);
  106276. ogg_sync_wrote(&oy,og[1].body_len);
  106277. if(ogg_sync_pageout(&oy,&og_de)<=0)error();
  106278. fprintf(stderr,"ok.\n");
  106279. }
  106280. /* Test recapture: garbage + page */
  106281. {
  106282. ogg_page og_de;
  106283. fprintf(stderr,"Testing search for capture... ");
  106284. ogg_sync_reset(&oy);
  106285. /* 'garbage' */
  106286. memcpy(ogg_sync_buffer(&oy,og[1].body_len),og[1].body,
  106287. og[1].body_len);
  106288. ogg_sync_wrote(&oy,og[1].body_len);
  106289. memcpy(ogg_sync_buffer(&oy,og[1].header_len),og[1].header,
  106290. og[1].header_len);
  106291. ogg_sync_wrote(&oy,og[1].header_len);
  106292. memcpy(ogg_sync_buffer(&oy,og[1].body_len),og[1].body,
  106293. og[1].body_len);
  106294. ogg_sync_wrote(&oy,og[1].body_len);
  106295. memcpy(ogg_sync_buffer(&oy,og[2].header_len),og[2].header,
  106296. 20);
  106297. ogg_sync_wrote(&oy,20);
  106298. if(ogg_sync_pageout(&oy,&og_de)>0)error();
  106299. if(ogg_sync_pageout(&oy,&og_de)<=0)error();
  106300. if(ogg_sync_pageout(&oy,&og_de)>0)error();
  106301. memcpy(ogg_sync_buffer(&oy,og[2].header_len),og[2].header+20,
  106302. og[2].header_len-20);
  106303. ogg_sync_wrote(&oy,og[2].header_len-20);
  106304. memcpy(ogg_sync_buffer(&oy,og[2].body_len),og[2].body,
  106305. og[2].body_len);
  106306. ogg_sync_wrote(&oy,og[2].body_len);
  106307. if(ogg_sync_pageout(&oy,&og_de)<=0)error();
  106308. fprintf(stderr,"ok.\n");
  106309. }
  106310. /* Test recapture: page + garbage + page */
  106311. {
  106312. ogg_page og_de;
  106313. fprintf(stderr,"Testing recapture... ");
  106314. ogg_sync_reset(&oy);
  106315. memcpy(ogg_sync_buffer(&oy,og[1].header_len),og[1].header,
  106316. og[1].header_len);
  106317. ogg_sync_wrote(&oy,og[1].header_len);
  106318. memcpy(ogg_sync_buffer(&oy,og[1].body_len),og[1].body,
  106319. og[1].body_len);
  106320. ogg_sync_wrote(&oy,og[1].body_len);
  106321. memcpy(ogg_sync_buffer(&oy,og[2].header_len),og[2].header,
  106322. og[2].header_len);
  106323. ogg_sync_wrote(&oy,og[2].header_len);
  106324. memcpy(ogg_sync_buffer(&oy,og[2].header_len),og[2].header,
  106325. og[2].header_len);
  106326. ogg_sync_wrote(&oy,og[2].header_len);
  106327. if(ogg_sync_pageout(&oy,&og_de)<=0)error();
  106328. memcpy(ogg_sync_buffer(&oy,og[2].body_len),og[2].body,
  106329. og[2].body_len-5);
  106330. ogg_sync_wrote(&oy,og[2].body_len-5);
  106331. memcpy(ogg_sync_buffer(&oy,og[3].header_len),og[3].header,
  106332. og[3].header_len);
  106333. ogg_sync_wrote(&oy,og[3].header_len);
  106334. memcpy(ogg_sync_buffer(&oy,og[3].body_len),og[3].body,
  106335. og[3].body_len);
  106336. ogg_sync_wrote(&oy,og[3].body_len);
  106337. if(ogg_sync_pageout(&oy,&og_de)>0)error();
  106338. if(ogg_sync_pageout(&oy,&og_de)<=0)error();
  106339. fprintf(stderr,"ok.\n");
  106340. }
  106341. /* Free page data that was previously copied */
  106342. {
  106343. for(i=0;i<5;i++){
  106344. free_page(&og[i]);
  106345. }
  106346. }
  106347. }
  106348. return(0);
  106349. }
  106350. #endif
  106351. #endif
  106352. /*** End of inlined file: framing.c ***/
  106353. /*** Start of inlined file: analysis.c ***/
  106354. /*** Start of inlined file: juce_OggVorbisHeader.h ***/
  106355. // This file is included at the start of each Ogg-Vorbis .c file, just to do a few housekeeping
  106356. // tasks..
  106357. #if JUCE_MSVC
  106358. #pragma warning (disable: 4267 4127 4244 4996 4100 4701 4702 4013 4133 4206 4305 4189 4706)
  106359. #endif
  106360. /*** End of inlined file: juce_OggVorbisHeader.h ***/
  106361. #if JUCE_USE_OGGVORBIS
  106362. #include <stdio.h>
  106363. #include <string.h>
  106364. #include <math.h>
  106365. /*** Start of inlined file: codec_internal.h ***/
  106366. #ifndef _V_CODECI_H_
  106367. #define _V_CODECI_H_
  106368. /*** Start of inlined file: envelope.h ***/
  106369. #ifndef _V_ENVELOPE_
  106370. #define _V_ENVELOPE_
  106371. /*** Start of inlined file: mdct.h ***/
  106372. #ifndef _OGG_mdct_H_
  106373. #define _OGG_mdct_H_
  106374. /*#define MDCT_INTEGERIZED <- be warned there could be some hurt left here*/
  106375. #ifdef MDCT_INTEGERIZED
  106376. #define DATA_TYPE int
  106377. #define REG_TYPE register int
  106378. #define TRIGBITS 14
  106379. #define cPI3_8 6270
  106380. #define cPI2_8 11585
  106381. #define cPI1_8 15137
  106382. #define FLOAT_CONV(x) ((int)((x)*(1<<TRIGBITS)+.5))
  106383. #define MULT_NORM(x) ((x)>>TRIGBITS)
  106384. #define HALVE(x) ((x)>>1)
  106385. #else
  106386. #define DATA_TYPE float
  106387. #define REG_TYPE float
  106388. #define cPI3_8 .38268343236508977175F
  106389. #define cPI2_8 .70710678118654752441F
  106390. #define cPI1_8 .92387953251128675613F
  106391. #define FLOAT_CONV(x) (x)
  106392. #define MULT_NORM(x) (x)
  106393. #define HALVE(x) ((x)*.5f)
  106394. #endif
  106395. typedef struct {
  106396. int n;
  106397. int log2n;
  106398. DATA_TYPE *trig;
  106399. int *bitrev;
  106400. DATA_TYPE scale;
  106401. } mdct_lookup;
  106402. extern void mdct_init(mdct_lookup *lookup,int n);
  106403. extern void mdct_clear(mdct_lookup *l);
  106404. extern void mdct_forward(mdct_lookup *init, DATA_TYPE *in, DATA_TYPE *out);
  106405. extern void mdct_backward(mdct_lookup *init, DATA_TYPE *in, DATA_TYPE *out);
  106406. #endif
  106407. /*** End of inlined file: mdct.h ***/
  106408. #define VE_PRE 16
  106409. #define VE_WIN 4
  106410. #define VE_POST 2
  106411. #define VE_AMP (VE_PRE+VE_POST-1)
  106412. #define VE_BANDS 7
  106413. #define VE_NEARDC 15
  106414. #define VE_MINSTRETCH 2 /* a bit less than short block */
  106415. #define VE_MAXSTRETCH 12 /* one-third full block */
  106416. typedef struct {
  106417. float ampbuf[VE_AMP];
  106418. int ampptr;
  106419. float nearDC[VE_NEARDC];
  106420. float nearDC_acc;
  106421. float nearDC_partialacc;
  106422. int nearptr;
  106423. } envelope_filter_state;
  106424. typedef struct {
  106425. int begin;
  106426. int end;
  106427. float *window;
  106428. float total;
  106429. } envelope_band;
  106430. typedef struct {
  106431. int ch;
  106432. int winlength;
  106433. int searchstep;
  106434. float minenergy;
  106435. mdct_lookup mdct;
  106436. float *mdct_win;
  106437. envelope_band band[VE_BANDS];
  106438. envelope_filter_state *filter;
  106439. int stretch;
  106440. int *mark;
  106441. long storage;
  106442. long current;
  106443. long curmark;
  106444. long cursor;
  106445. } envelope_lookup;
  106446. extern void _ve_envelope_init(envelope_lookup *e,vorbis_info *vi);
  106447. extern void _ve_envelope_clear(envelope_lookup *e);
  106448. extern long _ve_envelope_search(vorbis_dsp_state *v);
  106449. extern void _ve_envelope_shift(envelope_lookup *e,long shift);
  106450. extern int _ve_envelope_mark(vorbis_dsp_state *v);
  106451. #endif
  106452. /*** End of inlined file: envelope.h ***/
  106453. /*** Start of inlined file: codebook.h ***/
  106454. #ifndef _V_CODEBOOK_H_
  106455. #define _V_CODEBOOK_H_
  106456. /* This structure encapsulates huffman and VQ style encoding books; it
  106457. doesn't do anything specific to either.
  106458. valuelist/quantlist are nonNULL (and q_* significant) only if
  106459. there's entry->value mapping to be done.
  106460. If encode-side mapping must be done (and thus the entry needs to be
  106461. hunted), the auxiliary encode pointer will point to a decision
  106462. tree. This is true of both VQ and huffman, but is mostly useful
  106463. with VQ.
  106464. */
  106465. typedef struct static_codebook{
  106466. long dim; /* codebook dimensions (elements per vector) */
  106467. long entries; /* codebook entries */
  106468. long *lengthlist; /* codeword lengths in bits */
  106469. /* mapping ***************************************************************/
  106470. int maptype; /* 0=none
  106471. 1=implicitly populated values from map column
  106472. 2=listed arbitrary values */
  106473. /* The below does a linear, single monotonic sequence mapping. */
  106474. long q_min; /* packed 32 bit float; quant value 0 maps to minval */
  106475. long q_delta; /* packed 32 bit float; val 1 - val 0 == delta */
  106476. int q_quant; /* bits: 0 < quant <= 16 */
  106477. int q_sequencep; /* bitflag */
  106478. long *quantlist; /* map == 1: (int)(entries^(1/dim)) element column map
  106479. map == 2: list of dim*entries quantized entry vals
  106480. */
  106481. /* encode helpers ********************************************************/
  106482. struct encode_aux_nearestmatch *nearest_tree;
  106483. struct encode_aux_threshmatch *thresh_tree;
  106484. struct encode_aux_pigeonhole *pigeon_tree;
  106485. int allocedp;
  106486. } static_codebook;
  106487. /* this structures an arbitrary trained book to quickly find the
  106488. nearest cell match */
  106489. typedef struct encode_aux_nearestmatch{
  106490. /* pre-calculated partitioning tree */
  106491. long *ptr0;
  106492. long *ptr1;
  106493. long *p; /* decision points (each is an entry) */
  106494. long *q; /* decision points (each is an entry) */
  106495. long aux; /* number of tree entries */
  106496. long alloc;
  106497. } encode_aux_nearestmatch;
  106498. /* assumes a maptype of 1; encode side only, so that's OK */
  106499. typedef struct encode_aux_threshmatch{
  106500. float *quantthresh;
  106501. long *quantmap;
  106502. int quantvals;
  106503. int threshvals;
  106504. } encode_aux_threshmatch;
  106505. typedef struct encode_aux_pigeonhole{
  106506. float min;
  106507. float del;
  106508. int mapentries;
  106509. int quantvals;
  106510. long *pigeonmap;
  106511. long fittotal;
  106512. long *fitlist;
  106513. long *fitmap;
  106514. long *fitlength;
  106515. } encode_aux_pigeonhole;
  106516. typedef struct codebook{
  106517. long dim; /* codebook dimensions (elements per vector) */
  106518. long entries; /* codebook entries */
  106519. long used_entries; /* populated codebook entries */
  106520. const static_codebook *c;
  106521. /* for encode, the below are entry-ordered, fully populated */
  106522. /* for decode, the below are ordered by bitreversed codeword and only
  106523. used entries are populated */
  106524. float *valuelist; /* list of dim*entries actual entry values */
  106525. ogg_uint32_t *codelist; /* list of bitstream codewords for each entry */
  106526. int *dec_index; /* only used if sparseness collapsed */
  106527. char *dec_codelengths;
  106528. ogg_uint32_t *dec_firsttable;
  106529. int dec_firsttablen;
  106530. int dec_maxlength;
  106531. } codebook;
  106532. extern void vorbis_staticbook_clear(static_codebook *b);
  106533. extern void vorbis_staticbook_destroy(static_codebook *b);
  106534. extern int vorbis_book_init_encode(codebook *dest,const static_codebook *source);
  106535. extern int vorbis_book_init_decode(codebook *dest,const static_codebook *source);
  106536. extern void vorbis_book_clear(codebook *b);
  106537. extern float *_book_unquantize(const static_codebook *b,int n,int *map);
  106538. extern float *_book_logdist(const static_codebook *b,float *vals);
  106539. extern float _float32_unpack(long val);
  106540. extern long _float32_pack(float val);
  106541. extern int _best(codebook *book, float *a, int step);
  106542. extern int _ilog(unsigned int v);
  106543. extern long _book_maptype1_quantvals(const static_codebook *b);
  106544. extern int vorbis_book_besterror(codebook *book,float *a,int step,int addmul);
  106545. extern long vorbis_book_codeword(codebook *book,int entry);
  106546. extern long vorbis_book_codelen(codebook *book,int entry);
  106547. extern int vorbis_staticbook_pack(const static_codebook *c,oggpack_buffer *b);
  106548. extern int vorbis_staticbook_unpack(oggpack_buffer *b,static_codebook *c);
  106549. extern int vorbis_book_encode(codebook *book, int a, oggpack_buffer *b);
  106550. extern int vorbis_book_errorv(codebook *book, float *a);
  106551. extern int vorbis_book_encodev(codebook *book, int best,float *a,
  106552. oggpack_buffer *b);
  106553. extern long vorbis_book_decode(codebook *book, oggpack_buffer *b);
  106554. extern long vorbis_book_decodevs_add(codebook *book, float *a,
  106555. oggpack_buffer *b,int n);
  106556. extern long vorbis_book_decodev_set(codebook *book, float *a,
  106557. oggpack_buffer *b,int n);
  106558. extern long vorbis_book_decodev_add(codebook *book, float *a,
  106559. oggpack_buffer *b,int n);
  106560. extern long vorbis_book_decodevv_add(codebook *book, float **a,
  106561. long off,int ch,
  106562. oggpack_buffer *b,int n);
  106563. #endif
  106564. /*** End of inlined file: codebook.h ***/
  106565. #define BLOCKTYPE_IMPULSE 0
  106566. #define BLOCKTYPE_PADDING 1
  106567. #define BLOCKTYPE_TRANSITION 0
  106568. #define BLOCKTYPE_LONG 1
  106569. #define PACKETBLOBS 15
  106570. typedef struct vorbis_block_internal{
  106571. float **pcmdelay; /* this is a pointer into local storage */
  106572. float ampmax;
  106573. int blocktype;
  106574. oggpack_buffer *packetblob[PACKETBLOBS]; /* initialized, must be freed;
  106575. blob [PACKETBLOBS/2] points to
  106576. the oggpack_buffer in the
  106577. main vorbis_block */
  106578. } vorbis_block_internal;
  106579. typedef void vorbis_look_floor;
  106580. typedef void vorbis_look_residue;
  106581. typedef void vorbis_look_transform;
  106582. /* mode ************************************************************/
  106583. typedef struct {
  106584. int blockflag;
  106585. int windowtype;
  106586. int transformtype;
  106587. int mapping;
  106588. } vorbis_info_mode;
  106589. typedef void vorbis_info_floor;
  106590. typedef void vorbis_info_residue;
  106591. typedef void vorbis_info_mapping;
  106592. /*** Start of inlined file: psy.h ***/
  106593. #ifndef _V_PSY_H_
  106594. #define _V_PSY_H_
  106595. /*** Start of inlined file: smallft.h ***/
  106596. #ifndef _V_SMFT_H_
  106597. #define _V_SMFT_H_
  106598. typedef struct {
  106599. int n;
  106600. float *trigcache;
  106601. int *splitcache;
  106602. } drft_lookup;
  106603. extern void drft_forward(drft_lookup *l,float *data);
  106604. extern void drft_backward(drft_lookup *l,float *data);
  106605. extern void drft_init(drft_lookup *l,int n);
  106606. extern void drft_clear(drft_lookup *l);
  106607. #endif
  106608. /*** End of inlined file: smallft.h ***/
  106609. /*** Start of inlined file: backends.h ***/
  106610. /* this is exposed up here because we need it for static modes.
  106611. Lookups for each backend aren't exposed because there's no reason
  106612. to do so */
  106613. #ifndef _vorbis_backend_h_
  106614. #define _vorbis_backend_h_
  106615. /* this would all be simpler/shorter with templates, but.... */
  106616. /* Floor backend generic *****************************************/
  106617. typedef struct{
  106618. void (*pack) (vorbis_info_floor *,oggpack_buffer *);
  106619. vorbis_info_floor *(*unpack)(vorbis_info *,oggpack_buffer *);
  106620. vorbis_look_floor *(*look) (vorbis_dsp_state *,vorbis_info_floor *);
  106621. void (*free_info) (vorbis_info_floor *);
  106622. void (*free_look) (vorbis_look_floor *);
  106623. void *(*inverse1) (struct vorbis_block *,vorbis_look_floor *);
  106624. int (*inverse2) (struct vorbis_block *,vorbis_look_floor *,
  106625. void *buffer,float *);
  106626. } vorbis_func_floor;
  106627. typedef struct{
  106628. int order;
  106629. long rate;
  106630. long barkmap;
  106631. int ampbits;
  106632. int ampdB;
  106633. int numbooks; /* <= 16 */
  106634. int books[16];
  106635. float lessthan; /* encode-only config setting hacks for libvorbis */
  106636. float greaterthan; /* encode-only config setting hacks for libvorbis */
  106637. } vorbis_info_floor0;
  106638. #define VIF_POSIT 63
  106639. #define VIF_CLASS 16
  106640. #define VIF_PARTS 31
  106641. typedef struct{
  106642. int partitions; /* 0 to 31 */
  106643. int partitionclass[VIF_PARTS]; /* 0 to 15 */
  106644. int class_dim[VIF_CLASS]; /* 1 to 8 */
  106645. int class_subs[VIF_CLASS]; /* 0,1,2,3 (bits: 1<<n poss) */
  106646. int class_book[VIF_CLASS]; /* subs ^ dim entries */
  106647. int class_subbook[VIF_CLASS][8]; /* [VIF_CLASS][subs] */
  106648. int mult; /* 1 2 3 or 4 */
  106649. int postlist[VIF_POSIT+2]; /* first two implicit */
  106650. /* encode side analysis parameters */
  106651. float maxover;
  106652. float maxunder;
  106653. float maxerr;
  106654. float twofitweight;
  106655. float twofitatten;
  106656. int n;
  106657. } vorbis_info_floor1;
  106658. /* Residue backend generic *****************************************/
  106659. typedef struct{
  106660. void (*pack) (vorbis_info_residue *,oggpack_buffer *);
  106661. vorbis_info_residue *(*unpack)(vorbis_info *,oggpack_buffer *);
  106662. vorbis_look_residue *(*look) (vorbis_dsp_state *,
  106663. vorbis_info_residue *);
  106664. void (*free_info) (vorbis_info_residue *);
  106665. void (*free_look) (vorbis_look_residue *);
  106666. long **(*classx) (struct vorbis_block *,vorbis_look_residue *,
  106667. float **,int *,int);
  106668. int (*forward) (oggpack_buffer *,struct vorbis_block *,
  106669. vorbis_look_residue *,
  106670. float **,float **,int *,int,long **);
  106671. int (*inverse) (struct vorbis_block *,vorbis_look_residue *,
  106672. float **,int *,int);
  106673. } vorbis_func_residue;
  106674. typedef struct vorbis_info_residue0{
  106675. /* block-partitioned VQ coded straight residue */
  106676. long begin;
  106677. long end;
  106678. /* first stage (lossless partitioning) */
  106679. int grouping; /* group n vectors per partition */
  106680. int partitions; /* possible codebooks for a partition */
  106681. int groupbook; /* huffbook for partitioning */
  106682. int secondstages[64]; /* expanded out to pointers in lookup */
  106683. int booklist[256]; /* list of second stage books */
  106684. float classmetric1[64];
  106685. float classmetric2[64];
  106686. } vorbis_info_residue0;
  106687. /* Mapping backend generic *****************************************/
  106688. typedef struct{
  106689. void (*pack) (vorbis_info *,vorbis_info_mapping *,
  106690. oggpack_buffer *);
  106691. vorbis_info_mapping *(*unpack)(vorbis_info *,oggpack_buffer *);
  106692. void (*free_info) (vorbis_info_mapping *);
  106693. int (*forward) (struct vorbis_block *vb);
  106694. int (*inverse) (struct vorbis_block *vb,vorbis_info_mapping *);
  106695. } vorbis_func_mapping;
  106696. typedef struct vorbis_info_mapping0{
  106697. int submaps; /* <= 16 */
  106698. int chmuxlist[256]; /* up to 256 channels in a Vorbis stream */
  106699. int floorsubmap[16]; /* [mux] submap to floors */
  106700. int residuesubmap[16]; /* [mux] submap to residue */
  106701. int coupling_steps;
  106702. int coupling_mag[256];
  106703. int coupling_ang[256];
  106704. } vorbis_info_mapping0;
  106705. #endif
  106706. /*** End of inlined file: backends.h ***/
  106707. #ifndef EHMER_MAX
  106708. #define EHMER_MAX 56
  106709. #endif
  106710. /* psychoacoustic setup ********************************************/
  106711. #define P_BANDS 17 /* 62Hz to 16kHz */
  106712. #define P_LEVELS 8 /* 30dB to 100dB */
  106713. #define P_LEVEL_0 30. /* 30 dB */
  106714. #define P_NOISECURVES 3
  106715. #define NOISE_COMPAND_LEVELS 40
  106716. typedef struct vorbis_info_psy{
  106717. int blockflag;
  106718. float ath_adjatt;
  106719. float ath_maxatt;
  106720. float tone_masteratt[P_NOISECURVES];
  106721. float tone_centerboost;
  106722. float tone_decay;
  106723. float tone_abs_limit;
  106724. float toneatt[P_BANDS];
  106725. int noisemaskp;
  106726. float noisemaxsupp;
  106727. float noisewindowlo;
  106728. float noisewindowhi;
  106729. int noisewindowlomin;
  106730. int noisewindowhimin;
  106731. int noisewindowfixed;
  106732. float noiseoff[P_NOISECURVES][P_BANDS];
  106733. float noisecompand[NOISE_COMPAND_LEVELS];
  106734. float max_curve_dB;
  106735. int normal_channel_p;
  106736. int normal_point_p;
  106737. int normal_start;
  106738. int normal_partition;
  106739. double normal_thresh;
  106740. } vorbis_info_psy;
  106741. typedef struct{
  106742. int eighth_octave_lines;
  106743. /* for block long/short tuning; encode only */
  106744. float preecho_thresh[VE_BANDS];
  106745. float postecho_thresh[VE_BANDS];
  106746. float stretch_penalty;
  106747. float preecho_minenergy;
  106748. float ampmax_att_per_sec;
  106749. /* channel coupling config */
  106750. int coupling_pkHz[PACKETBLOBS];
  106751. int coupling_pointlimit[2][PACKETBLOBS];
  106752. int coupling_prepointamp[PACKETBLOBS];
  106753. int coupling_postpointamp[PACKETBLOBS];
  106754. int sliding_lowpass[2][PACKETBLOBS];
  106755. } vorbis_info_psy_global;
  106756. typedef struct {
  106757. float ampmax;
  106758. int channels;
  106759. vorbis_info_psy_global *gi;
  106760. int coupling_pointlimit[2][P_NOISECURVES];
  106761. } vorbis_look_psy_global;
  106762. typedef struct {
  106763. int n;
  106764. struct vorbis_info_psy *vi;
  106765. float ***tonecurves;
  106766. float **noiseoffset;
  106767. float *ath;
  106768. long *octave; /* in n.ocshift format */
  106769. long *bark;
  106770. long firstoc;
  106771. long shiftoc;
  106772. int eighth_octave_lines; /* power of two, please */
  106773. int total_octave_lines;
  106774. long rate; /* cache it */
  106775. float m_val; /* Masking compensation value */
  106776. } vorbis_look_psy;
  106777. extern void _vp_psy_init(vorbis_look_psy *p,vorbis_info_psy *vi,
  106778. vorbis_info_psy_global *gi,int n,long rate);
  106779. extern void _vp_psy_clear(vorbis_look_psy *p);
  106780. extern void *_vi_psy_dup(void *source);
  106781. extern void _vi_psy_free(vorbis_info_psy *i);
  106782. extern vorbis_info_psy *_vi_psy_copy(vorbis_info_psy *i);
  106783. extern void _vp_remove_floor(vorbis_look_psy *p,
  106784. float *mdct,
  106785. int *icodedflr,
  106786. float *residue,
  106787. int sliding_lowpass);
  106788. extern void _vp_noisemask(vorbis_look_psy *p,
  106789. float *logmdct,
  106790. float *logmask);
  106791. extern void _vp_tonemask(vorbis_look_psy *p,
  106792. float *logfft,
  106793. float *logmask,
  106794. float global_specmax,
  106795. float local_specmax);
  106796. extern void _vp_offset_and_mix(vorbis_look_psy *p,
  106797. float *noise,
  106798. float *tone,
  106799. int offset_select,
  106800. float *logmask,
  106801. float *mdct,
  106802. float *logmdct);
  106803. extern float _vp_ampmax_decay(float amp,vorbis_dsp_state *vd);
  106804. extern float **_vp_quantize_couple_memo(vorbis_block *vb,
  106805. vorbis_info_psy_global *g,
  106806. vorbis_look_psy *p,
  106807. vorbis_info_mapping0 *vi,
  106808. float **mdct);
  106809. extern void _vp_couple(int blobno,
  106810. vorbis_info_psy_global *g,
  106811. vorbis_look_psy *p,
  106812. vorbis_info_mapping0 *vi,
  106813. float **res,
  106814. float **mag_memo,
  106815. int **mag_sort,
  106816. int **ifloor,
  106817. int *nonzero,
  106818. int sliding_lowpass);
  106819. extern void _vp_noise_normalize(vorbis_look_psy *p,
  106820. float *in,float *out,int *sortedindex);
  106821. extern void _vp_noise_normalize_sort(vorbis_look_psy *p,
  106822. float *magnitudes,int *sortedindex);
  106823. extern int **_vp_quantize_couple_sort(vorbis_block *vb,
  106824. vorbis_look_psy *p,
  106825. vorbis_info_mapping0 *vi,
  106826. float **mags);
  106827. extern void hf_reduction(vorbis_info_psy_global *g,
  106828. vorbis_look_psy *p,
  106829. vorbis_info_mapping0 *vi,
  106830. float **mdct);
  106831. #endif
  106832. /*** End of inlined file: psy.h ***/
  106833. /*** Start of inlined file: bitrate.h ***/
  106834. #ifndef _V_BITRATE_H_
  106835. #define _V_BITRATE_H_
  106836. /*** Start of inlined file: os.h ***/
  106837. #ifndef _OS_H
  106838. #define _OS_H
  106839. /********************************************************************
  106840. * *
  106841. * THIS FILE IS PART OF THE OggVorbis SOFTWARE CODEC SOURCE CODE. *
  106842. * USE, DISTRIBUTION AND REPRODUCTION OF THIS LIBRARY SOURCE IS *
  106843. * GOVERNED BY A BSD-STYLE SOURCE LICENSE INCLUDED WITH THIS SOURCE *
  106844. * IN 'COPYING'. PLEASE READ THESE TERMS BEFORE DISTRIBUTING. *
  106845. * *
  106846. * THE OggVorbis SOURCE CODE IS (C) COPYRIGHT 1994-2002 *
  106847. * by the XIPHOPHORUS Company http://www.xiph.org/ *
  106848. * *
  106849. ********************************************************************
  106850. function: #ifdef jail to whip a few platforms into the UNIX ideal.
  106851. last mod: $Id: os.h,v 1.1 2007/06/07 17:49:18 jules_rms Exp $
  106852. ********************************************************************/
  106853. #ifdef HAVE_CONFIG_H
  106854. #include "config.h"
  106855. #endif
  106856. #include <math.h>
  106857. /*** Start of inlined file: misc.h ***/
  106858. #ifndef _V_RANDOM_H_
  106859. #define _V_RANDOM_H_
  106860. extern int analysis_noisy;
  106861. extern void *_vorbis_block_alloc(vorbis_block *vb,long bytes);
  106862. extern void _vorbis_block_ripcord(vorbis_block *vb);
  106863. extern void _analysis_output(char *base,int i,float *v,int n,int bark,int dB,
  106864. ogg_int64_t off);
  106865. #ifdef DEBUG_MALLOC
  106866. #define _VDBG_GRAPHFILE "malloc.m"
  106867. extern void *_VDBG_malloc(void *ptr,long bytes,char *file,long line);
  106868. extern void _VDBG_free(void *ptr,char *file,long line);
  106869. #ifndef MISC_C
  106870. #undef _ogg_malloc
  106871. #undef _ogg_calloc
  106872. #undef _ogg_realloc
  106873. #undef _ogg_free
  106874. #define _ogg_malloc(x) _VDBG_malloc(NULL,(x),__FILE__,__LINE__)
  106875. #define _ogg_calloc(x,y) _VDBG_malloc(NULL,(x)*(y),__FILE__,__LINE__)
  106876. #define _ogg_realloc(x,y) _VDBG_malloc((x),(y),__FILE__,__LINE__)
  106877. #define _ogg_free(x) _VDBG_free((x),__FILE__,__LINE__)
  106878. #endif
  106879. #endif
  106880. #endif
  106881. /*** End of inlined file: misc.h ***/
  106882. #ifndef _V_IFDEFJAIL_H_
  106883. # define _V_IFDEFJAIL_H_
  106884. # ifdef __GNUC__
  106885. # define STIN static __inline__
  106886. # elif _WIN32
  106887. # define STIN static __inline
  106888. # else
  106889. # define STIN static
  106890. # endif
  106891. #ifdef DJGPP
  106892. # define rint(x) (floor((x)+0.5f))
  106893. #endif
  106894. #ifndef M_PI
  106895. # define M_PI (3.1415926536f)
  106896. #endif
  106897. #if defined(_WIN32) && !defined(__SYMBIAN32__)
  106898. # include <malloc.h>
  106899. # define rint(x) (floor((x)+0.5f))
  106900. # define NO_FLOAT_MATH_LIB
  106901. # define FAST_HYPOT(a, b) sqrt((a)*(a) + (b)*(b))
  106902. #endif
  106903. #if defined(__SYMBIAN32__) && defined(__WINS__)
  106904. void *_alloca(size_t size);
  106905. # define alloca _alloca
  106906. #endif
  106907. #ifndef FAST_HYPOT
  106908. # define FAST_HYPOT hypot
  106909. #endif
  106910. #endif
  106911. #ifdef HAVE_ALLOCA_H
  106912. # include <alloca.h>
  106913. #endif
  106914. #ifdef USE_MEMORY_H
  106915. # include <memory.h>
  106916. #endif
  106917. #ifndef min
  106918. # define min(x,y) ((x)>(y)?(y):(x))
  106919. #endif
  106920. #ifndef max
  106921. # define max(x,y) ((x)<(y)?(y):(x))
  106922. #endif
  106923. #if defined(__i386__) && defined(__GNUC__) && !defined(__BEOS__)
  106924. # define VORBIS_FPU_CONTROL
  106925. /* both GCC and MSVC are kinda stupid about rounding/casting to int.
  106926. Because of encapsulation constraints (GCC can't see inside the asm
  106927. block and so we end up doing stupid things like a store/load that
  106928. is collectively a noop), we do it this way */
  106929. /* we must set up the fpu before this works!! */
  106930. typedef ogg_int16_t vorbis_fpu_control;
  106931. static inline void vorbis_fpu_setround(vorbis_fpu_control *fpu){
  106932. ogg_int16_t ret;
  106933. ogg_int16_t temp;
  106934. __asm__ __volatile__("fnstcw %0\n\t"
  106935. "movw %0,%%dx\n\t"
  106936. "orw $62463,%%dx\n\t"
  106937. "movw %%dx,%1\n\t"
  106938. "fldcw %1\n\t":"=m"(ret):"m"(temp): "dx");
  106939. *fpu=ret;
  106940. }
  106941. static inline void vorbis_fpu_restore(vorbis_fpu_control fpu){
  106942. __asm__ __volatile__("fldcw %0":: "m"(fpu));
  106943. }
  106944. /* assumes the FPU is in round mode! */
  106945. static inline int vorbis_ftoi(double f){ /* yes, double! Otherwise,
  106946. we get extra fst/fld to
  106947. truncate precision */
  106948. int i;
  106949. __asm__("fistl %0": "=m"(i) : "t"(f));
  106950. return(i);
  106951. }
  106952. #endif
  106953. #if defined(_WIN32) && defined(_X86_) && !defined(__GNUC__) && !defined(__BORLANDC__)
  106954. # define VORBIS_FPU_CONTROL
  106955. typedef ogg_int16_t vorbis_fpu_control;
  106956. static __inline int vorbis_ftoi(double f){
  106957. int i;
  106958. __asm{
  106959. fld f
  106960. fistp i
  106961. }
  106962. return i;
  106963. }
  106964. static __inline void vorbis_fpu_setround(vorbis_fpu_control *fpu){
  106965. }
  106966. static __inline void vorbis_fpu_restore(vorbis_fpu_control fpu){
  106967. }
  106968. #endif
  106969. #ifndef VORBIS_FPU_CONTROL
  106970. typedef int vorbis_fpu_control;
  106971. static int vorbis_ftoi(double f){
  106972. return (int)(f+.5);
  106973. }
  106974. /* We don't have special code for this compiler/arch, so do it the slow way */
  106975. # define vorbis_fpu_setround(vorbis_fpu_control) {}
  106976. # define vorbis_fpu_restore(vorbis_fpu_control) {}
  106977. #endif
  106978. #endif /* _OS_H */
  106979. /*** End of inlined file: os.h ***/
  106980. /* encode side bitrate tracking */
  106981. typedef struct bitrate_manager_state {
  106982. int managed;
  106983. long avg_reservoir;
  106984. long minmax_reservoir;
  106985. long avg_bitsper;
  106986. long min_bitsper;
  106987. long max_bitsper;
  106988. long short_per_long;
  106989. double avgfloat;
  106990. vorbis_block *vb;
  106991. int choice;
  106992. } bitrate_manager_state;
  106993. typedef struct bitrate_manager_info{
  106994. long avg_rate;
  106995. long min_rate;
  106996. long max_rate;
  106997. long reservoir_bits;
  106998. double reservoir_bias;
  106999. double slew_damp;
  107000. } bitrate_manager_info;
  107001. extern void vorbis_bitrate_init(vorbis_info *vi,bitrate_manager_state *bs);
  107002. extern void vorbis_bitrate_clear(bitrate_manager_state *bs);
  107003. extern int vorbis_bitrate_managed(vorbis_block *vb);
  107004. extern int vorbis_bitrate_addblock(vorbis_block *vb);
  107005. extern int vorbis_bitrate_flushpacket(vorbis_dsp_state *vd, ogg_packet *op);
  107006. #endif
  107007. /*** End of inlined file: bitrate.h ***/
  107008. static int ilog(unsigned int v){
  107009. int ret=0;
  107010. while(v){
  107011. ret++;
  107012. v>>=1;
  107013. }
  107014. return(ret);
  107015. }
  107016. static int ilog2(unsigned int v){
  107017. int ret=0;
  107018. if(v)--v;
  107019. while(v){
  107020. ret++;
  107021. v>>=1;
  107022. }
  107023. return(ret);
  107024. }
  107025. typedef struct private_state {
  107026. /* local lookup storage */
  107027. envelope_lookup *ve; /* envelope lookup */
  107028. int window[2];
  107029. vorbis_look_transform **transform[2]; /* block, type */
  107030. drft_lookup fft_look[2];
  107031. int modebits;
  107032. vorbis_look_floor **flr;
  107033. vorbis_look_residue **residue;
  107034. vorbis_look_psy *psy;
  107035. vorbis_look_psy_global *psy_g_look;
  107036. /* local storage, only used on the encoding side. This way the
  107037. application does not need to worry about freeing some packets'
  107038. memory and not others'; packet storage is always tracked.
  107039. Cleared next call to a _dsp_ function */
  107040. unsigned char *header;
  107041. unsigned char *header1;
  107042. unsigned char *header2;
  107043. bitrate_manager_state bms;
  107044. ogg_int64_t sample_count;
  107045. } private_state;
  107046. /* codec_setup_info contains all the setup information specific to the
  107047. specific compression/decompression mode in progress (eg,
  107048. psychoacoustic settings, channel setup, options, codebook
  107049. etc).
  107050. *********************************************************************/
  107051. /*** Start of inlined file: highlevel.h ***/
  107052. typedef struct highlevel_byblocktype {
  107053. double tone_mask_setting;
  107054. double tone_peaklimit_setting;
  107055. double noise_bias_setting;
  107056. double noise_compand_setting;
  107057. } highlevel_byblocktype;
  107058. typedef struct highlevel_encode_setup {
  107059. void *setup;
  107060. int set_in_stone;
  107061. double base_setting;
  107062. double long_setting;
  107063. double short_setting;
  107064. double impulse_noisetune;
  107065. int managed;
  107066. long bitrate_min;
  107067. long bitrate_av;
  107068. double bitrate_av_damp;
  107069. long bitrate_max;
  107070. long bitrate_reservoir;
  107071. double bitrate_reservoir_bias;
  107072. int impulse_block_p;
  107073. int noise_normalize_p;
  107074. double stereo_point_setting;
  107075. double lowpass_kHz;
  107076. double ath_floating_dB;
  107077. double ath_absolute_dB;
  107078. double amplitude_track_dBpersec;
  107079. double trigger_setting;
  107080. highlevel_byblocktype block[4]; /* padding, impulse, transition, long */
  107081. } highlevel_encode_setup;
  107082. /*** End of inlined file: highlevel.h ***/
  107083. typedef struct codec_setup_info {
  107084. /* Vorbis supports only short and long blocks, but allows the
  107085. encoder to choose the sizes */
  107086. long blocksizes[2];
  107087. /* modes are the primary means of supporting on-the-fly different
  107088. blocksizes, different channel mappings (LR or M/A),
  107089. different residue backends, etc. Each mode consists of a
  107090. blocksize flag and a mapping (along with the mapping setup */
  107091. int modes;
  107092. int maps;
  107093. int floors;
  107094. int residues;
  107095. int books;
  107096. int psys; /* encode only */
  107097. vorbis_info_mode *mode_param[64];
  107098. int map_type[64];
  107099. vorbis_info_mapping *map_param[64];
  107100. int floor_type[64];
  107101. vorbis_info_floor *floor_param[64];
  107102. int residue_type[64];
  107103. vorbis_info_residue *residue_param[64];
  107104. static_codebook *book_param[256];
  107105. codebook *fullbooks;
  107106. vorbis_info_psy *psy_param[4]; /* encode only */
  107107. vorbis_info_psy_global psy_g_param;
  107108. bitrate_manager_info bi;
  107109. highlevel_encode_setup hi; /* used only by vorbisenc.c. It's a
  107110. highly redundant structure, but
  107111. improves clarity of program flow. */
  107112. int halfrate_flag; /* painless downsample for decode */
  107113. } codec_setup_info;
  107114. extern vorbis_look_psy_global *_vp_global_look(vorbis_info *vi);
  107115. extern void _vp_global_free(vorbis_look_psy_global *look);
  107116. #endif
  107117. /*** End of inlined file: codec_internal.h ***/
  107118. /*** Start of inlined file: registry.h ***/
  107119. #ifndef _V_REG_H_
  107120. #define _V_REG_H_
  107121. #define VI_TRANSFORMB 1
  107122. #define VI_WINDOWB 1
  107123. #define VI_TIMEB 1
  107124. #define VI_FLOORB 2
  107125. #define VI_RESB 3
  107126. #define VI_MAPB 1
  107127. extern vorbis_func_floor *_floor_P[];
  107128. extern vorbis_func_residue *_residue_P[];
  107129. extern vorbis_func_mapping *_mapping_P[];
  107130. #endif
  107131. /*** End of inlined file: registry.h ***/
  107132. /*** Start of inlined file: scales.h ***/
  107133. #ifndef _V_SCALES_H_
  107134. #define _V_SCALES_H_
  107135. #include <math.h>
  107136. /* 20log10(x) */
  107137. #define VORBIS_IEEE_FLOAT32 1
  107138. #ifdef VORBIS_IEEE_FLOAT32
  107139. static float unitnorm(float x){
  107140. union {
  107141. ogg_uint32_t i;
  107142. float f;
  107143. } ix;
  107144. ix.f = x;
  107145. ix.i = (ix.i & 0x80000000U) | (0x3f800000U);
  107146. return ix.f;
  107147. }
  107148. /* Segher was off (too high) by ~ .3 decibel. Center the conversion correctly. */
  107149. static float todB(const float *x){
  107150. union {
  107151. ogg_uint32_t i;
  107152. float f;
  107153. } ix;
  107154. ix.f = *x;
  107155. ix.i = ix.i&0x7fffffff;
  107156. return (float)(ix.i * 7.17711438e-7f -764.6161886f);
  107157. }
  107158. #define todB_nn(x) todB(x)
  107159. #else
  107160. static float unitnorm(float x){
  107161. if(x<0)return(-1.f);
  107162. return(1.f);
  107163. }
  107164. #define todB(x) (*(x)==0?-400.f:log(*(x)**(x))*4.34294480f)
  107165. #define todB_nn(x) (*(x)==0.f?-400.f:log(*(x))*8.6858896f)
  107166. #endif
  107167. #define fromdB(x) (exp((x)*.11512925f))
  107168. /* The bark scale equations are approximations, since the original
  107169. table was somewhat hand rolled. The below are chosen to have the
  107170. best possible fit to the rolled tables, thus their somewhat odd
  107171. appearance (these are more accurate and over a longer range than
  107172. the oft-quoted bark equations found in the texts I have). The
  107173. approximations are valid from 0 - 30kHz (nyquist) or so.
  107174. all f in Hz, z in Bark */
  107175. #define toBARK(n) (13.1f*atan(.00074f*(n))+2.24f*atan((n)*(n)*1.85e-8f)+1e-4f*(n))
  107176. #define fromBARK(z) (102.f*(z)-2.f*pow(z,2.f)+.4f*pow(z,3.f)+pow(1.46f,z)-1.f)
  107177. #define toMEL(n) (log(1.f+(n)*.001f)*1442.695f)
  107178. #define fromMEL(m) (1000.f*exp((m)/1442.695f)-1000.f)
  107179. /* Frequency to octave. We arbitrarily declare 63.5 Hz to be octave
  107180. 0.0 */
  107181. #define toOC(n) (log(n)*1.442695f-5.965784f)
  107182. #define fromOC(o) (exp(((o)+5.965784f)*.693147f))
  107183. #endif
  107184. /*** End of inlined file: scales.h ***/
  107185. int analysis_noisy=1;
  107186. /* decides between modes, dispatches to the appropriate mapping. */
  107187. int vorbis_analysis(vorbis_block *vb, ogg_packet *op){
  107188. int ret,i;
  107189. vorbis_block_internal *vbi=(vorbis_block_internal *)vb->internal;
  107190. vb->glue_bits=0;
  107191. vb->time_bits=0;
  107192. vb->floor_bits=0;
  107193. vb->res_bits=0;
  107194. /* first things first. Make sure encode is ready */
  107195. for(i=0;i<PACKETBLOBS;i++)
  107196. oggpack_reset(vbi->packetblob[i]);
  107197. /* we only have one mapping type (0), and we let the mapping code
  107198. itself figure out what soft mode to use. This allows easier
  107199. bitrate management */
  107200. if((ret=_mapping_P[0]->forward(vb)))
  107201. return(ret);
  107202. if(op){
  107203. if(vorbis_bitrate_managed(vb))
  107204. /* The app is using a bitmanaged mode... but not using the
  107205. bitrate management interface. */
  107206. return(OV_EINVAL);
  107207. op->packet=oggpack_get_buffer(&vb->opb);
  107208. op->bytes=oggpack_bytes(&vb->opb);
  107209. op->b_o_s=0;
  107210. op->e_o_s=vb->eofflag;
  107211. op->granulepos=vb->granulepos;
  107212. op->packetno=vb->sequence; /* for sake of completeness */
  107213. }
  107214. return(0);
  107215. }
  107216. /* there was no great place to put this.... */
  107217. void _analysis_output_always(const char *base,int i,float *v,int n,int bark,int dB,ogg_int64_t off){
  107218. int j;
  107219. FILE *of;
  107220. char buffer[80];
  107221. /* if(i==5870){*/
  107222. sprintf(buffer,"%s_%d.m",base,i);
  107223. of=fopen(buffer,"w");
  107224. if(!of)perror("failed to open data dump file");
  107225. for(j=0;j<n;j++){
  107226. if(bark){
  107227. float b=toBARK((4000.f*j/n)+.25);
  107228. fprintf(of,"%f ",b);
  107229. }else
  107230. if(off!=0)
  107231. fprintf(of,"%f ",(double)(j+off)/8000.);
  107232. else
  107233. fprintf(of,"%f ",(double)j);
  107234. if(dB){
  107235. float val;
  107236. if(v[j]==0.)
  107237. val=-140.;
  107238. else
  107239. val=todB(v+j);
  107240. fprintf(of,"%f\n",val);
  107241. }else{
  107242. fprintf(of,"%f\n",v[j]);
  107243. }
  107244. }
  107245. fclose(of);
  107246. /* } */
  107247. }
  107248. void _analysis_output(char *base,int i,float *v,int n,int bark,int dB,
  107249. ogg_int64_t off){
  107250. if(analysis_noisy)_analysis_output_always(base,i,v,n,bark,dB,off);
  107251. }
  107252. #endif
  107253. /*** End of inlined file: analysis.c ***/
  107254. /*** Start of inlined file: bitrate.c ***/
  107255. /*** Start of inlined file: juce_OggVorbisHeader.h ***/
  107256. // This file is included at the start of each Ogg-Vorbis .c file, just to do a few housekeeping
  107257. // tasks..
  107258. #if JUCE_MSVC
  107259. #pragma warning (disable: 4267 4127 4244 4996 4100 4701 4702 4013 4133 4206 4305 4189 4706)
  107260. #endif
  107261. /*** End of inlined file: juce_OggVorbisHeader.h ***/
  107262. #if JUCE_USE_OGGVORBIS
  107263. #include <stdlib.h>
  107264. #include <string.h>
  107265. #include <math.h>
  107266. /* compute bitrate tracking setup */
  107267. void vorbis_bitrate_init(vorbis_info *vi,bitrate_manager_state *bm){
  107268. codec_setup_info *ci=(codec_setup_info *)vi->codec_setup;
  107269. bitrate_manager_info *bi=&ci->bi;
  107270. memset(bm,0,sizeof(*bm));
  107271. if(bi && (bi->reservoir_bits>0)){
  107272. long ratesamples=vi->rate;
  107273. int halfsamples=ci->blocksizes[0]>>1;
  107274. bm->short_per_long=ci->blocksizes[1]/ci->blocksizes[0];
  107275. bm->managed=1;
  107276. bm->avg_bitsper= rint(1.*bi->avg_rate*halfsamples/ratesamples);
  107277. bm->min_bitsper= rint(1.*bi->min_rate*halfsamples/ratesamples);
  107278. bm->max_bitsper= rint(1.*bi->max_rate*halfsamples/ratesamples);
  107279. bm->avgfloat=PACKETBLOBS/2;
  107280. /* not a necessary fix, but one that leads to a more balanced
  107281. typical initialization */
  107282. {
  107283. long desired_fill=bi->reservoir_bits*bi->reservoir_bias;
  107284. bm->minmax_reservoir=desired_fill;
  107285. bm->avg_reservoir=desired_fill;
  107286. }
  107287. }
  107288. }
  107289. void vorbis_bitrate_clear(bitrate_manager_state *bm){
  107290. memset(bm,0,sizeof(*bm));
  107291. return;
  107292. }
  107293. int vorbis_bitrate_managed(vorbis_block *vb){
  107294. vorbis_dsp_state *vd=vb->vd;
  107295. private_state *b=(private_state*)vd->backend_state;
  107296. bitrate_manager_state *bm=&b->bms;
  107297. if(bm && bm->managed)return(1);
  107298. return(0);
  107299. }
  107300. /* finish taking in the block we just processed */
  107301. int vorbis_bitrate_addblock(vorbis_block *vb){
  107302. vorbis_block_internal *vbi=(vorbis_block_internal*)vb->internal;
  107303. vorbis_dsp_state *vd=vb->vd;
  107304. private_state *b=(private_state*)vd->backend_state;
  107305. bitrate_manager_state *bm=&b->bms;
  107306. vorbis_info *vi=vd->vi;
  107307. codec_setup_info *ci=(codec_setup_info*)vi->codec_setup;
  107308. bitrate_manager_info *bi=&ci->bi;
  107309. int choice=rint(bm->avgfloat);
  107310. long this_bits=oggpack_bytes(vbi->packetblob[choice])*8;
  107311. long min_target_bits=(vb->W?bm->min_bitsper*bm->short_per_long:bm->min_bitsper);
  107312. long max_target_bits=(vb->W?bm->max_bitsper*bm->short_per_long:bm->max_bitsper);
  107313. int samples=ci->blocksizes[vb->W]>>1;
  107314. long desired_fill=bi->reservoir_bits*bi->reservoir_bias;
  107315. if(!bm->managed){
  107316. /* not a bitrate managed stream, but for API simplicity, we'll
  107317. buffer the packet to keep the code path clean */
  107318. if(bm->vb)return(-1); /* one has been submitted without
  107319. being claimed */
  107320. bm->vb=vb;
  107321. return(0);
  107322. }
  107323. bm->vb=vb;
  107324. /* look ahead for avg floater */
  107325. if(bm->avg_bitsper>0){
  107326. double slew=0.;
  107327. long avg_target_bits=(vb->W?bm->avg_bitsper*bm->short_per_long:bm->avg_bitsper);
  107328. double slewlimit= 15./bi->slew_damp;
  107329. /* choosing a new floater:
  107330. if we're over target, we slew down
  107331. if we're under target, we slew up
  107332. choose slew as follows: look through packetblobs of this frame
  107333. and set slew as the first in the appropriate direction that
  107334. gives us the slew we want. This may mean no slew if delta is
  107335. already favorable.
  107336. Then limit slew to slew max */
  107337. if(bm->avg_reservoir+(this_bits-avg_target_bits)>desired_fill){
  107338. while(choice>0 && this_bits>avg_target_bits &&
  107339. bm->avg_reservoir+(this_bits-avg_target_bits)>desired_fill){
  107340. choice--;
  107341. this_bits=oggpack_bytes(vbi->packetblob[choice])*8;
  107342. }
  107343. }else if(bm->avg_reservoir+(this_bits-avg_target_bits)<desired_fill){
  107344. while(choice+1<PACKETBLOBS && this_bits<avg_target_bits &&
  107345. bm->avg_reservoir+(this_bits-avg_target_bits)<desired_fill){
  107346. choice++;
  107347. this_bits=oggpack_bytes(vbi->packetblob[choice])*8;
  107348. }
  107349. }
  107350. slew=rint(choice-bm->avgfloat)/samples*vi->rate;
  107351. if(slew<-slewlimit)slew=-slewlimit;
  107352. if(slew>slewlimit)slew=slewlimit;
  107353. choice=rint(bm->avgfloat+= slew/vi->rate*samples);
  107354. this_bits=oggpack_bytes(vbi->packetblob[choice])*8;
  107355. }
  107356. /* enforce min(if used) on the current floater (if used) */
  107357. if(bm->min_bitsper>0){
  107358. /* do we need to force the bitrate up? */
  107359. if(this_bits<min_target_bits){
  107360. while(bm->minmax_reservoir-(min_target_bits-this_bits)<0){
  107361. choice++;
  107362. if(choice>=PACKETBLOBS)break;
  107363. this_bits=oggpack_bytes(vbi->packetblob[choice])*8;
  107364. }
  107365. }
  107366. }
  107367. /* enforce max (if used) on the current floater (if used) */
  107368. if(bm->max_bitsper>0){
  107369. /* do we need to force the bitrate down? */
  107370. if(this_bits>max_target_bits){
  107371. while(bm->minmax_reservoir+(this_bits-max_target_bits)>bi->reservoir_bits){
  107372. choice--;
  107373. if(choice<0)break;
  107374. this_bits=oggpack_bytes(vbi->packetblob[choice])*8;
  107375. }
  107376. }
  107377. }
  107378. /* Choice of packetblobs now made based on floater, and min/max
  107379. requirements. Now boundary check extreme choices */
  107380. if(choice<0){
  107381. /* choosing a smaller packetblob is insufficient to trim bitrate.
  107382. frame will need to be truncated */
  107383. long maxsize=(max_target_bits+(bi->reservoir_bits-bm->minmax_reservoir))/8;
  107384. bm->choice=choice=0;
  107385. if(oggpack_bytes(vbi->packetblob[choice])>maxsize){
  107386. oggpack_writetrunc(vbi->packetblob[choice],maxsize*8);
  107387. this_bits=oggpack_bytes(vbi->packetblob[choice])*8;
  107388. }
  107389. }else{
  107390. long minsize=(min_target_bits-bm->minmax_reservoir+7)/8;
  107391. if(choice>=PACKETBLOBS)
  107392. choice=PACKETBLOBS-1;
  107393. bm->choice=choice;
  107394. /* prop up bitrate according to demand. pad this frame out with zeroes */
  107395. minsize-=oggpack_bytes(vbi->packetblob[choice]);
  107396. while(minsize-->0)oggpack_write(vbi->packetblob[choice],0,8);
  107397. this_bits=oggpack_bytes(vbi->packetblob[choice])*8;
  107398. }
  107399. /* now we have the final packet and the final packet size. Update statistics */
  107400. /* min and max reservoir */
  107401. if(bm->min_bitsper>0 || bm->max_bitsper>0){
  107402. if(max_target_bits>0 && this_bits>max_target_bits){
  107403. bm->minmax_reservoir+=(this_bits-max_target_bits);
  107404. }else if(min_target_bits>0 && this_bits<min_target_bits){
  107405. bm->minmax_reservoir+=(this_bits-min_target_bits);
  107406. }else{
  107407. /* inbetween; we want to take reservoir toward but not past desired_fill */
  107408. if(bm->minmax_reservoir>desired_fill){
  107409. if(max_target_bits>0){ /* logical bulletproofing against initialization state */
  107410. bm->minmax_reservoir+=(this_bits-max_target_bits);
  107411. if(bm->minmax_reservoir<desired_fill)bm->minmax_reservoir=desired_fill;
  107412. }else{
  107413. bm->minmax_reservoir=desired_fill;
  107414. }
  107415. }else{
  107416. if(min_target_bits>0){ /* logical bulletproofing against initialization state */
  107417. bm->minmax_reservoir+=(this_bits-min_target_bits);
  107418. if(bm->minmax_reservoir>desired_fill)bm->minmax_reservoir=desired_fill;
  107419. }else{
  107420. bm->minmax_reservoir=desired_fill;
  107421. }
  107422. }
  107423. }
  107424. }
  107425. /* avg reservoir */
  107426. if(bm->avg_bitsper>0){
  107427. long avg_target_bits=(vb->W?bm->avg_bitsper*bm->short_per_long:bm->avg_bitsper);
  107428. bm->avg_reservoir+=this_bits-avg_target_bits;
  107429. }
  107430. return(0);
  107431. }
  107432. int vorbis_bitrate_flushpacket(vorbis_dsp_state *vd,ogg_packet *op){
  107433. private_state *b=(private_state*)vd->backend_state;
  107434. bitrate_manager_state *bm=&b->bms;
  107435. vorbis_block *vb=bm->vb;
  107436. int choice=PACKETBLOBS/2;
  107437. if(!vb)return 0;
  107438. if(op){
  107439. vorbis_block_internal *vbi=(vorbis_block_internal*)vb->internal;
  107440. if(vorbis_bitrate_managed(vb))
  107441. choice=bm->choice;
  107442. op->packet=oggpack_get_buffer(vbi->packetblob[choice]);
  107443. op->bytes=oggpack_bytes(vbi->packetblob[choice]);
  107444. op->b_o_s=0;
  107445. op->e_o_s=vb->eofflag;
  107446. op->granulepos=vb->granulepos;
  107447. op->packetno=vb->sequence; /* for sake of completeness */
  107448. }
  107449. bm->vb=0;
  107450. return(1);
  107451. }
  107452. #endif
  107453. /*** End of inlined file: bitrate.c ***/
  107454. /*** Start of inlined file: block.c ***/
  107455. /*** Start of inlined file: juce_OggVorbisHeader.h ***/
  107456. // This file is included at the start of each Ogg-Vorbis .c file, just to do a few housekeeping
  107457. // tasks..
  107458. #if JUCE_MSVC
  107459. #pragma warning (disable: 4267 4127 4244 4996 4100 4701 4702 4013 4133 4206 4305 4189 4706)
  107460. #endif
  107461. /*** End of inlined file: juce_OggVorbisHeader.h ***/
  107462. #if JUCE_USE_OGGVORBIS
  107463. #include <stdio.h>
  107464. #include <stdlib.h>
  107465. #include <string.h>
  107466. /*** Start of inlined file: window.h ***/
  107467. #ifndef _V_WINDOW_
  107468. #define _V_WINDOW_
  107469. extern float *_vorbis_window_get(int n);
  107470. extern void _vorbis_apply_window(float *d,int *winno,long *blocksizes,
  107471. int lW,int W,int nW);
  107472. #endif
  107473. /*** End of inlined file: window.h ***/
  107474. /*** Start of inlined file: lpc.h ***/
  107475. #ifndef _V_LPC_H_
  107476. #define _V_LPC_H_
  107477. /* simple linear scale LPC code */
  107478. extern float vorbis_lpc_from_data(float *data,float *lpc,int n,int m);
  107479. extern void vorbis_lpc_predict(float *coeff,float *prime,int m,
  107480. float *data,long n);
  107481. #endif
  107482. /*** End of inlined file: lpc.h ***/
  107483. /* pcm accumulator examples (not exhaustive):
  107484. <-------------- lW ---------------->
  107485. <--------------- W ---------------->
  107486. : .....|..... _______________ |
  107487. : .''' | '''_--- | |\ |
  107488. :.....''' |_____--- '''......| | \_______|
  107489. :.................|__________________|_______|__|______|
  107490. |<------ Sl ------>| > Sr < |endW
  107491. |beginSl |endSl | |endSr
  107492. |beginW |endlW |beginSr
  107493. |< lW >|
  107494. <--------------- W ---------------->
  107495. | | .. ______________ |
  107496. | | ' `/ | ---_ |
  107497. |___.'___/`. | ---_____|
  107498. |_______|__|_______|_________________|
  107499. | >|Sl|< |<------ Sr ----->|endW
  107500. | | |endSl |beginSr |endSr
  107501. |beginW | |endlW
  107502. mult[0] |beginSl mult[n]
  107503. <-------------- lW ----------------->
  107504. |<--W-->|
  107505. : .............. ___ | |
  107506. : .''' |`/ \ | |
  107507. :.....''' |/`....\|...|
  107508. :.........................|___|___|___|
  107509. |Sl |Sr |endW
  107510. | | |endSr
  107511. | |beginSr
  107512. | |endSl
  107513. |beginSl
  107514. |beginW
  107515. */
  107516. /* block abstraction setup *********************************************/
  107517. #ifndef WORD_ALIGN
  107518. #define WORD_ALIGN 8
  107519. #endif
  107520. int vorbis_block_init(vorbis_dsp_state *v, vorbis_block *vb){
  107521. int i;
  107522. memset(vb,0,sizeof(*vb));
  107523. vb->vd=v;
  107524. vb->localalloc=0;
  107525. vb->localstore=NULL;
  107526. if(v->analysisp){
  107527. vorbis_block_internal *vbi=(vorbis_block_internal*)
  107528. (vb->internal=(vorbis_block_internal*)_ogg_calloc(1,sizeof(vorbis_block_internal)));
  107529. vbi->ampmax=-9999;
  107530. for(i=0;i<PACKETBLOBS;i++){
  107531. if(i==PACKETBLOBS/2){
  107532. vbi->packetblob[i]=&vb->opb;
  107533. }else{
  107534. vbi->packetblob[i]=
  107535. (oggpack_buffer*) _ogg_calloc(1,sizeof(oggpack_buffer));
  107536. }
  107537. oggpack_writeinit(vbi->packetblob[i]);
  107538. }
  107539. }
  107540. return(0);
  107541. }
  107542. void *_vorbis_block_alloc(vorbis_block *vb,long bytes){
  107543. bytes=(bytes+(WORD_ALIGN-1)) & ~(WORD_ALIGN-1);
  107544. if(bytes+vb->localtop>vb->localalloc){
  107545. /* can't just _ogg_realloc... there are outstanding pointers */
  107546. if(vb->localstore){
  107547. struct alloc_chain *link=(struct alloc_chain*)_ogg_malloc(sizeof(*link));
  107548. vb->totaluse+=vb->localtop;
  107549. link->next=vb->reap;
  107550. link->ptr=vb->localstore;
  107551. vb->reap=link;
  107552. }
  107553. /* highly conservative */
  107554. vb->localalloc=bytes;
  107555. vb->localstore=_ogg_malloc(vb->localalloc);
  107556. vb->localtop=0;
  107557. }
  107558. {
  107559. void *ret=(void *)(((char *)vb->localstore)+vb->localtop);
  107560. vb->localtop+=bytes;
  107561. return ret;
  107562. }
  107563. }
  107564. /* reap the chain, pull the ripcord */
  107565. void _vorbis_block_ripcord(vorbis_block *vb){
  107566. /* reap the chain */
  107567. struct alloc_chain *reap=vb->reap;
  107568. while(reap){
  107569. struct alloc_chain *next=reap->next;
  107570. _ogg_free(reap->ptr);
  107571. memset(reap,0,sizeof(*reap));
  107572. _ogg_free(reap);
  107573. reap=next;
  107574. }
  107575. /* consolidate storage */
  107576. if(vb->totaluse){
  107577. vb->localstore=_ogg_realloc(vb->localstore,vb->totaluse+vb->localalloc);
  107578. vb->localalloc+=vb->totaluse;
  107579. vb->totaluse=0;
  107580. }
  107581. /* pull the ripcord */
  107582. vb->localtop=0;
  107583. vb->reap=NULL;
  107584. }
  107585. int vorbis_block_clear(vorbis_block *vb){
  107586. int i;
  107587. vorbis_block_internal *vbi=(vorbis_block_internal*)vb->internal;
  107588. _vorbis_block_ripcord(vb);
  107589. if(vb->localstore)_ogg_free(vb->localstore);
  107590. if(vbi){
  107591. for(i=0;i<PACKETBLOBS;i++){
  107592. oggpack_writeclear(vbi->packetblob[i]);
  107593. if(i!=PACKETBLOBS/2)_ogg_free(vbi->packetblob[i]);
  107594. }
  107595. _ogg_free(vbi);
  107596. }
  107597. memset(vb,0,sizeof(*vb));
  107598. return(0);
  107599. }
  107600. /* Analysis side code, but directly related to blocking. Thus it's
  107601. here and not in analysis.c (which is for analysis transforms only).
  107602. The init is here because some of it is shared */
  107603. static int _vds_shared_init(vorbis_dsp_state *v,vorbis_info *vi,int encp){
  107604. int i;
  107605. codec_setup_info *ci=(codec_setup_info*)vi->codec_setup;
  107606. private_state *b=NULL;
  107607. int hs;
  107608. if(ci==NULL) return 1;
  107609. hs=ci->halfrate_flag;
  107610. memset(v,0,sizeof(*v));
  107611. b=(private_state*) (v->backend_state=(private_state*)_ogg_calloc(1,sizeof(*b)));
  107612. v->vi=vi;
  107613. b->modebits=ilog2(ci->modes);
  107614. b->transform[0]=(vorbis_look_transform**)_ogg_calloc(VI_TRANSFORMB,sizeof(*b->transform[0]));
  107615. b->transform[1]=(vorbis_look_transform**)_ogg_calloc(VI_TRANSFORMB,sizeof(*b->transform[1]));
  107616. /* MDCT is tranform 0 */
  107617. b->transform[0][0]=_ogg_calloc(1,sizeof(mdct_lookup));
  107618. b->transform[1][0]=_ogg_calloc(1,sizeof(mdct_lookup));
  107619. mdct_init((mdct_lookup*)b->transform[0][0],ci->blocksizes[0]>>hs);
  107620. mdct_init((mdct_lookup*)b->transform[1][0],ci->blocksizes[1]>>hs);
  107621. /* Vorbis I uses only window type 0 */
  107622. b->window[0]=ilog2(ci->blocksizes[0])-6;
  107623. b->window[1]=ilog2(ci->blocksizes[1])-6;
  107624. if(encp){ /* encode/decode differ here */
  107625. /* analysis always needs an fft */
  107626. drft_init(&b->fft_look[0],ci->blocksizes[0]);
  107627. drft_init(&b->fft_look[1],ci->blocksizes[1]);
  107628. /* finish the codebooks */
  107629. if(!ci->fullbooks){
  107630. ci->fullbooks=(codebook*) _ogg_calloc(ci->books,sizeof(*ci->fullbooks));
  107631. for(i=0;i<ci->books;i++)
  107632. vorbis_book_init_encode(ci->fullbooks+i,ci->book_param[i]);
  107633. }
  107634. b->psy=(vorbis_look_psy*)_ogg_calloc(ci->psys,sizeof(*b->psy));
  107635. for(i=0;i<ci->psys;i++){
  107636. _vp_psy_init(b->psy+i,
  107637. ci->psy_param[i],
  107638. &ci->psy_g_param,
  107639. ci->blocksizes[ci->psy_param[i]->blockflag]/2,
  107640. vi->rate);
  107641. }
  107642. v->analysisp=1;
  107643. }else{
  107644. /* finish the codebooks */
  107645. if(!ci->fullbooks){
  107646. ci->fullbooks=(codebook*) _ogg_calloc(ci->books,sizeof(*ci->fullbooks));
  107647. for(i=0;i<ci->books;i++){
  107648. vorbis_book_init_decode(ci->fullbooks+i,ci->book_param[i]);
  107649. /* decode codebooks are now standalone after init */
  107650. vorbis_staticbook_destroy(ci->book_param[i]);
  107651. ci->book_param[i]=NULL;
  107652. }
  107653. }
  107654. }
  107655. /* initialize the storage vectors. blocksize[1] is small for encode,
  107656. but the correct size for decode */
  107657. v->pcm_storage=ci->blocksizes[1];
  107658. v->pcm=(float**)_ogg_malloc(vi->channels*sizeof(*v->pcm));
  107659. v->pcmret=(float**)_ogg_malloc(vi->channels*sizeof(*v->pcmret));
  107660. {
  107661. int i;
  107662. for(i=0;i<vi->channels;i++)
  107663. v->pcm[i]=(float*)_ogg_calloc(v->pcm_storage,sizeof(*v->pcm[i]));
  107664. }
  107665. /* all 1 (large block) or 0 (small block) */
  107666. /* explicitly set for the sake of clarity */
  107667. v->lW=0; /* previous window size */
  107668. v->W=0; /* current window size */
  107669. /* all vector indexes */
  107670. v->centerW=ci->blocksizes[1]/2;
  107671. v->pcm_current=v->centerW;
  107672. /* initialize all the backend lookups */
  107673. b->flr=(vorbis_look_floor**)_ogg_calloc(ci->floors,sizeof(*b->flr));
  107674. b->residue=(vorbis_look_residue**)_ogg_calloc(ci->residues,sizeof(*b->residue));
  107675. for(i=0;i<ci->floors;i++)
  107676. b->flr[i]=_floor_P[ci->floor_type[i]]->
  107677. look(v,ci->floor_param[i]);
  107678. for(i=0;i<ci->residues;i++)
  107679. b->residue[i]=_residue_P[ci->residue_type[i]]->
  107680. look(v,ci->residue_param[i]);
  107681. return 0;
  107682. }
  107683. /* arbitrary settings and spec-mandated numbers get filled in here */
  107684. int vorbis_analysis_init(vorbis_dsp_state *v,vorbis_info *vi){
  107685. private_state *b=NULL;
  107686. if(_vds_shared_init(v,vi,1))return 1;
  107687. b=(private_state*)v->backend_state;
  107688. b->psy_g_look=_vp_global_look(vi);
  107689. /* Initialize the envelope state storage */
  107690. b->ve=(envelope_lookup*)_ogg_calloc(1,sizeof(*b->ve));
  107691. _ve_envelope_init(b->ve,vi);
  107692. vorbis_bitrate_init(vi,&b->bms);
  107693. /* compressed audio packets start after the headers
  107694. with sequence number 3 */
  107695. v->sequence=3;
  107696. return(0);
  107697. }
  107698. void vorbis_dsp_clear(vorbis_dsp_state *v){
  107699. int i;
  107700. if(v){
  107701. vorbis_info *vi=v->vi;
  107702. codec_setup_info *ci=(codec_setup_info*)(vi?vi->codec_setup:NULL);
  107703. private_state *b=(private_state*)v->backend_state;
  107704. if(b){
  107705. if(b->ve){
  107706. _ve_envelope_clear(b->ve);
  107707. _ogg_free(b->ve);
  107708. }
  107709. if(b->transform[0]){
  107710. mdct_clear((mdct_lookup*) b->transform[0][0]);
  107711. _ogg_free(b->transform[0][0]);
  107712. _ogg_free(b->transform[0]);
  107713. }
  107714. if(b->transform[1]){
  107715. mdct_clear((mdct_lookup*) b->transform[1][0]);
  107716. _ogg_free(b->transform[1][0]);
  107717. _ogg_free(b->transform[1]);
  107718. }
  107719. if(b->flr){
  107720. for(i=0;i<ci->floors;i++)
  107721. _floor_P[ci->floor_type[i]]->
  107722. free_look(b->flr[i]);
  107723. _ogg_free(b->flr);
  107724. }
  107725. if(b->residue){
  107726. for(i=0;i<ci->residues;i++)
  107727. _residue_P[ci->residue_type[i]]->
  107728. free_look(b->residue[i]);
  107729. _ogg_free(b->residue);
  107730. }
  107731. if(b->psy){
  107732. for(i=0;i<ci->psys;i++)
  107733. _vp_psy_clear(b->psy+i);
  107734. _ogg_free(b->psy);
  107735. }
  107736. if(b->psy_g_look)_vp_global_free(b->psy_g_look);
  107737. vorbis_bitrate_clear(&b->bms);
  107738. drft_clear(&b->fft_look[0]);
  107739. drft_clear(&b->fft_look[1]);
  107740. }
  107741. if(v->pcm){
  107742. for(i=0;i<vi->channels;i++)
  107743. if(v->pcm[i])_ogg_free(v->pcm[i]);
  107744. _ogg_free(v->pcm);
  107745. if(v->pcmret)_ogg_free(v->pcmret);
  107746. }
  107747. if(b){
  107748. /* free header, header1, header2 */
  107749. if(b->header)_ogg_free(b->header);
  107750. if(b->header1)_ogg_free(b->header1);
  107751. if(b->header2)_ogg_free(b->header2);
  107752. _ogg_free(b);
  107753. }
  107754. memset(v,0,sizeof(*v));
  107755. }
  107756. }
  107757. float **vorbis_analysis_buffer(vorbis_dsp_state *v, int vals){
  107758. int i;
  107759. vorbis_info *vi=v->vi;
  107760. private_state *b=(private_state*)v->backend_state;
  107761. /* free header, header1, header2 */
  107762. if(b->header)_ogg_free(b->header);b->header=NULL;
  107763. if(b->header1)_ogg_free(b->header1);b->header1=NULL;
  107764. if(b->header2)_ogg_free(b->header2);b->header2=NULL;
  107765. /* Do we have enough storage space for the requested buffer? If not,
  107766. expand the PCM (and envelope) storage */
  107767. if(v->pcm_current+vals>=v->pcm_storage){
  107768. v->pcm_storage=v->pcm_current+vals*2;
  107769. for(i=0;i<vi->channels;i++){
  107770. v->pcm[i]=(float*)_ogg_realloc(v->pcm[i],v->pcm_storage*sizeof(*v->pcm[i]));
  107771. }
  107772. }
  107773. for(i=0;i<vi->channels;i++)
  107774. v->pcmret[i]=v->pcm[i]+v->pcm_current;
  107775. return(v->pcmret);
  107776. }
  107777. static void _preextrapolate_helper(vorbis_dsp_state *v){
  107778. int i;
  107779. int order=32;
  107780. float *lpc=(float*)alloca(order*sizeof(*lpc));
  107781. float *work=(float*)alloca(v->pcm_current*sizeof(*work));
  107782. long j;
  107783. v->preextrapolate=1;
  107784. if(v->pcm_current-v->centerW>order*2){ /* safety */
  107785. for(i=0;i<v->vi->channels;i++){
  107786. /* need to run the extrapolation in reverse! */
  107787. for(j=0;j<v->pcm_current;j++)
  107788. work[j]=v->pcm[i][v->pcm_current-j-1];
  107789. /* prime as above */
  107790. vorbis_lpc_from_data(work,lpc,v->pcm_current-v->centerW,order);
  107791. /* run the predictor filter */
  107792. vorbis_lpc_predict(lpc,work+v->pcm_current-v->centerW-order,
  107793. order,
  107794. work+v->pcm_current-v->centerW,
  107795. v->centerW);
  107796. for(j=0;j<v->pcm_current;j++)
  107797. v->pcm[i][v->pcm_current-j-1]=work[j];
  107798. }
  107799. }
  107800. }
  107801. /* call with val<=0 to set eof */
  107802. int vorbis_analysis_wrote(vorbis_dsp_state *v, int vals){
  107803. vorbis_info *vi=v->vi;
  107804. codec_setup_info *ci=(codec_setup_info*)vi->codec_setup;
  107805. if(vals<=0){
  107806. int order=32;
  107807. int i;
  107808. float *lpc=(float*) alloca(order*sizeof(*lpc));
  107809. /* if it wasn't done earlier (very short sample) */
  107810. if(!v->preextrapolate)
  107811. _preextrapolate_helper(v);
  107812. /* We're encoding the end of the stream. Just make sure we have
  107813. [at least] a few full blocks of zeroes at the end. */
  107814. /* actually, we don't want zeroes; that could drop a large
  107815. amplitude off a cliff, creating spread spectrum noise that will
  107816. suck to encode. Extrapolate for the sake of cleanliness. */
  107817. vorbis_analysis_buffer(v,ci->blocksizes[1]*3);
  107818. v->eofflag=v->pcm_current;
  107819. v->pcm_current+=ci->blocksizes[1]*3;
  107820. for(i=0;i<vi->channels;i++){
  107821. if(v->eofflag>order*2){
  107822. /* extrapolate with LPC to fill in */
  107823. long n;
  107824. /* make a predictor filter */
  107825. n=v->eofflag;
  107826. if(n>ci->blocksizes[1])n=ci->blocksizes[1];
  107827. vorbis_lpc_from_data(v->pcm[i]+v->eofflag-n,lpc,n,order);
  107828. /* run the predictor filter */
  107829. vorbis_lpc_predict(lpc,v->pcm[i]+v->eofflag-order,order,
  107830. v->pcm[i]+v->eofflag,v->pcm_current-v->eofflag);
  107831. }else{
  107832. /* not enough data to extrapolate (unlikely to happen due to
  107833. guarding the overlap, but bulletproof in case that
  107834. assumtion goes away). zeroes will do. */
  107835. memset(v->pcm[i]+v->eofflag,0,
  107836. (v->pcm_current-v->eofflag)*sizeof(*v->pcm[i]));
  107837. }
  107838. }
  107839. }else{
  107840. if(v->pcm_current+vals>v->pcm_storage)
  107841. return(OV_EINVAL);
  107842. v->pcm_current+=vals;
  107843. /* we may want to reverse extrapolate the beginning of a stream
  107844. too... in case we're beginning on a cliff! */
  107845. /* clumsy, but simple. It only runs once, so simple is good. */
  107846. if(!v->preextrapolate && v->pcm_current-v->centerW>ci->blocksizes[1])
  107847. _preextrapolate_helper(v);
  107848. }
  107849. return(0);
  107850. }
  107851. /* do the deltas, envelope shaping, pre-echo and determine the size of
  107852. the next block on which to continue analysis */
  107853. int vorbis_analysis_blockout(vorbis_dsp_state *v,vorbis_block *vb){
  107854. int i;
  107855. vorbis_info *vi=v->vi;
  107856. codec_setup_info *ci=(codec_setup_info*)vi->codec_setup;
  107857. private_state *b=(private_state*)v->backend_state;
  107858. vorbis_look_psy_global *g=b->psy_g_look;
  107859. long beginW=v->centerW-ci->blocksizes[v->W]/2,centerNext;
  107860. vorbis_block_internal *vbi=(vorbis_block_internal *)vb->internal;
  107861. /* check to see if we're started... */
  107862. if(!v->preextrapolate)return(0);
  107863. /* check to see if we're done... */
  107864. if(v->eofflag==-1)return(0);
  107865. /* By our invariant, we have lW, W and centerW set. Search for
  107866. the next boundary so we can determine nW (the next window size)
  107867. which lets us compute the shape of the current block's window */
  107868. /* we do an envelope search even on a single blocksize; we may still
  107869. be throwing more bits at impulses, and envelope search handles
  107870. marking impulses too. */
  107871. {
  107872. long bp=_ve_envelope_search(v);
  107873. if(bp==-1){
  107874. if(v->eofflag==0)return(0); /* not enough data currently to search for a
  107875. full long block */
  107876. v->nW=0;
  107877. }else{
  107878. if(ci->blocksizes[0]==ci->blocksizes[1])
  107879. v->nW=0;
  107880. else
  107881. v->nW=bp;
  107882. }
  107883. }
  107884. centerNext=v->centerW+ci->blocksizes[v->W]/4+ci->blocksizes[v->nW]/4;
  107885. {
  107886. /* center of next block + next block maximum right side. */
  107887. long blockbound=centerNext+ci->blocksizes[v->nW]/2;
  107888. if(v->pcm_current<blockbound)return(0); /* not enough data yet;
  107889. although this check is
  107890. less strict that the
  107891. _ve_envelope_search,
  107892. the search is not run
  107893. if we only use one
  107894. block size */
  107895. }
  107896. /* fill in the block. Note that for a short window, lW and nW are *short*
  107897. regardless of actual settings in the stream */
  107898. _vorbis_block_ripcord(vb);
  107899. vb->lW=v->lW;
  107900. vb->W=v->W;
  107901. vb->nW=v->nW;
  107902. if(v->W){
  107903. if(!v->lW || !v->nW){
  107904. vbi->blocktype=BLOCKTYPE_TRANSITION;
  107905. /*fprintf(stderr,"-");*/
  107906. }else{
  107907. vbi->blocktype=BLOCKTYPE_LONG;
  107908. /*fprintf(stderr,"_");*/
  107909. }
  107910. }else{
  107911. if(_ve_envelope_mark(v)){
  107912. vbi->blocktype=BLOCKTYPE_IMPULSE;
  107913. /*fprintf(stderr,"|");*/
  107914. }else{
  107915. vbi->blocktype=BLOCKTYPE_PADDING;
  107916. /*fprintf(stderr,".");*/
  107917. }
  107918. }
  107919. vb->vd=v;
  107920. vb->sequence=v->sequence++;
  107921. vb->granulepos=v->granulepos;
  107922. vb->pcmend=ci->blocksizes[v->W];
  107923. /* copy the vectors; this uses the local storage in vb */
  107924. /* this tracks 'strongest peak' for later psychoacoustics */
  107925. /* moved to the global psy state; clean this mess up */
  107926. if(vbi->ampmax>g->ampmax)g->ampmax=vbi->ampmax;
  107927. g->ampmax=_vp_ampmax_decay(g->ampmax,v);
  107928. vbi->ampmax=g->ampmax;
  107929. vb->pcm=(float**)_vorbis_block_alloc(vb,sizeof(*vb->pcm)*vi->channels);
  107930. vbi->pcmdelay=(float**)_vorbis_block_alloc(vb,sizeof(*vbi->pcmdelay)*vi->channels);
  107931. for(i=0;i<vi->channels;i++){
  107932. vbi->pcmdelay[i]=
  107933. (float*) _vorbis_block_alloc(vb,(vb->pcmend+beginW)*sizeof(*vbi->pcmdelay[i]));
  107934. memcpy(vbi->pcmdelay[i],v->pcm[i],(vb->pcmend+beginW)*sizeof(*vbi->pcmdelay[i]));
  107935. vb->pcm[i]=vbi->pcmdelay[i]+beginW;
  107936. /* before we added the delay
  107937. vb->pcm[i]=_vorbis_block_alloc(vb,vb->pcmend*sizeof(*vb->pcm[i]));
  107938. memcpy(vb->pcm[i],v->pcm[i]+beginW,ci->blocksizes[v->W]*sizeof(*vb->pcm[i]));
  107939. */
  107940. }
  107941. /* handle eof detection: eof==0 means that we've not yet received EOF
  107942. eof>0 marks the last 'real' sample in pcm[]
  107943. eof<0 'no more to do'; doesn't get here */
  107944. if(v->eofflag){
  107945. if(v->centerW>=v->eofflag){
  107946. v->eofflag=-1;
  107947. vb->eofflag=1;
  107948. return(1);
  107949. }
  107950. }
  107951. /* advance storage vectors and clean up */
  107952. {
  107953. int new_centerNext=ci->blocksizes[1]/2;
  107954. int movementW=centerNext-new_centerNext;
  107955. if(movementW>0){
  107956. _ve_envelope_shift(b->ve,movementW);
  107957. v->pcm_current-=movementW;
  107958. for(i=0;i<vi->channels;i++)
  107959. memmove(v->pcm[i],v->pcm[i]+movementW,
  107960. v->pcm_current*sizeof(*v->pcm[i]));
  107961. v->lW=v->W;
  107962. v->W=v->nW;
  107963. v->centerW=new_centerNext;
  107964. if(v->eofflag){
  107965. v->eofflag-=movementW;
  107966. if(v->eofflag<=0)v->eofflag=-1;
  107967. /* do not add padding to end of stream! */
  107968. if(v->centerW>=v->eofflag){
  107969. v->granulepos+=movementW-(v->centerW-v->eofflag);
  107970. }else{
  107971. v->granulepos+=movementW;
  107972. }
  107973. }else{
  107974. v->granulepos+=movementW;
  107975. }
  107976. }
  107977. }
  107978. /* done */
  107979. return(1);
  107980. }
  107981. int vorbis_synthesis_restart(vorbis_dsp_state *v){
  107982. vorbis_info *vi=v->vi;
  107983. codec_setup_info *ci;
  107984. int hs;
  107985. if(!v->backend_state)return -1;
  107986. if(!vi)return -1;
  107987. ci=(codec_setup_info*) vi->codec_setup;
  107988. if(!ci)return -1;
  107989. hs=ci->halfrate_flag;
  107990. v->centerW=ci->blocksizes[1]>>(hs+1);
  107991. v->pcm_current=v->centerW>>hs;
  107992. v->pcm_returned=-1;
  107993. v->granulepos=-1;
  107994. v->sequence=-1;
  107995. v->eofflag=0;
  107996. ((private_state *)(v->backend_state))->sample_count=-1;
  107997. return(0);
  107998. }
  107999. int vorbis_synthesis_init(vorbis_dsp_state *v,vorbis_info *vi){
  108000. if(_vds_shared_init(v,vi,0)) return 1;
  108001. vorbis_synthesis_restart(v);
  108002. return 0;
  108003. }
  108004. /* Unlike in analysis, the window is only partially applied for each
  108005. block. The time domain envelope is not yet handled at the point of
  108006. calling (as it relies on the previous block). */
  108007. int vorbis_synthesis_blockin(vorbis_dsp_state *v,vorbis_block *vb){
  108008. vorbis_info *vi=v->vi;
  108009. codec_setup_info *ci=(codec_setup_info*)vi->codec_setup;
  108010. private_state *b=(private_state*)v->backend_state;
  108011. int hs=ci->halfrate_flag;
  108012. int i,j;
  108013. if(!vb)return(OV_EINVAL);
  108014. if(v->pcm_current>v->pcm_returned && v->pcm_returned!=-1)return(OV_EINVAL);
  108015. v->lW=v->W;
  108016. v->W=vb->W;
  108017. v->nW=-1;
  108018. if((v->sequence==-1)||
  108019. (v->sequence+1 != vb->sequence)){
  108020. v->granulepos=-1; /* out of sequence; lose count */
  108021. b->sample_count=-1;
  108022. }
  108023. v->sequence=vb->sequence;
  108024. if(vb->pcm){ /* no pcm to process if vorbis_synthesis_trackonly
  108025. was called on block */
  108026. int n=ci->blocksizes[v->W]>>(hs+1);
  108027. int n0=ci->blocksizes[0]>>(hs+1);
  108028. int n1=ci->blocksizes[1]>>(hs+1);
  108029. int thisCenter;
  108030. int prevCenter;
  108031. v->glue_bits+=vb->glue_bits;
  108032. v->time_bits+=vb->time_bits;
  108033. v->floor_bits+=vb->floor_bits;
  108034. v->res_bits+=vb->res_bits;
  108035. if(v->centerW){
  108036. thisCenter=n1;
  108037. prevCenter=0;
  108038. }else{
  108039. thisCenter=0;
  108040. prevCenter=n1;
  108041. }
  108042. /* v->pcm is now used like a two-stage double buffer. We don't want
  108043. to have to constantly shift *or* adjust memory usage. Don't
  108044. accept a new block until the old is shifted out */
  108045. for(j=0;j<vi->channels;j++){
  108046. /* the overlap/add section */
  108047. if(v->lW){
  108048. if(v->W){
  108049. /* large/large */
  108050. float *w=_vorbis_window_get(b->window[1]-hs);
  108051. float *pcm=v->pcm[j]+prevCenter;
  108052. float *p=vb->pcm[j];
  108053. for(i=0;i<n1;i++)
  108054. pcm[i]=pcm[i]*w[n1-i-1] + p[i]*w[i];
  108055. }else{
  108056. /* large/small */
  108057. float *w=_vorbis_window_get(b->window[0]-hs);
  108058. float *pcm=v->pcm[j]+prevCenter+n1/2-n0/2;
  108059. float *p=vb->pcm[j];
  108060. for(i=0;i<n0;i++)
  108061. pcm[i]=pcm[i]*w[n0-i-1] +p[i]*w[i];
  108062. }
  108063. }else{
  108064. if(v->W){
  108065. /* small/large */
  108066. float *w=_vorbis_window_get(b->window[0]-hs);
  108067. float *pcm=v->pcm[j]+prevCenter;
  108068. float *p=vb->pcm[j]+n1/2-n0/2;
  108069. for(i=0;i<n0;i++)
  108070. pcm[i]=pcm[i]*w[n0-i-1] +p[i]*w[i];
  108071. for(;i<n1/2+n0/2;i++)
  108072. pcm[i]=p[i];
  108073. }else{
  108074. /* small/small */
  108075. float *w=_vorbis_window_get(b->window[0]-hs);
  108076. float *pcm=v->pcm[j]+prevCenter;
  108077. float *p=vb->pcm[j];
  108078. for(i=0;i<n0;i++)
  108079. pcm[i]=pcm[i]*w[n0-i-1] +p[i]*w[i];
  108080. }
  108081. }
  108082. /* the copy section */
  108083. {
  108084. float *pcm=v->pcm[j]+thisCenter;
  108085. float *p=vb->pcm[j]+n;
  108086. for(i=0;i<n;i++)
  108087. pcm[i]=p[i];
  108088. }
  108089. }
  108090. if(v->centerW)
  108091. v->centerW=0;
  108092. else
  108093. v->centerW=n1;
  108094. /* deal with initial packet state; we do this using the explicit
  108095. pcm_returned==-1 flag otherwise we're sensitive to first block
  108096. being short or long */
  108097. if(v->pcm_returned==-1){
  108098. v->pcm_returned=thisCenter;
  108099. v->pcm_current=thisCenter;
  108100. }else{
  108101. v->pcm_returned=prevCenter;
  108102. v->pcm_current=prevCenter+
  108103. ((ci->blocksizes[v->lW]/4+
  108104. ci->blocksizes[v->W]/4)>>hs);
  108105. }
  108106. }
  108107. /* track the frame number... This is for convenience, but also
  108108. making sure our last packet doesn't end with added padding. If
  108109. the last packet is partial, the number of samples we'll have to
  108110. return will be past the vb->granulepos.
  108111. This is not foolproof! It will be confused if we begin
  108112. decoding at the last page after a seek or hole. In that case,
  108113. we don't have a starting point to judge where the last frame
  108114. is. For this reason, vorbisfile will always try to make sure
  108115. it reads the last two marked pages in proper sequence */
  108116. if(b->sample_count==-1){
  108117. b->sample_count=0;
  108118. }else{
  108119. b->sample_count+=ci->blocksizes[v->lW]/4+ci->blocksizes[v->W]/4;
  108120. }
  108121. if(v->granulepos==-1){
  108122. if(vb->granulepos!=-1){ /* only set if we have a position to set to */
  108123. v->granulepos=vb->granulepos;
  108124. /* is this a short page? */
  108125. if(b->sample_count>v->granulepos){
  108126. /* corner case; if this is both the first and last audio page,
  108127. then spec says the end is cut, not beginning */
  108128. if(vb->eofflag){
  108129. /* trim the end */
  108130. /* no preceeding granulepos; assume we started at zero (we'd
  108131. have to in a short single-page stream) */
  108132. /* granulepos could be -1 due to a seek, but that would result
  108133. in a long count, not short count */
  108134. v->pcm_current-=(b->sample_count-v->granulepos)>>hs;
  108135. }else{
  108136. /* trim the beginning */
  108137. v->pcm_returned+=(b->sample_count-v->granulepos)>>hs;
  108138. if(v->pcm_returned>v->pcm_current)
  108139. v->pcm_returned=v->pcm_current;
  108140. }
  108141. }
  108142. }
  108143. }else{
  108144. v->granulepos+=ci->blocksizes[v->lW]/4+ci->blocksizes[v->W]/4;
  108145. if(vb->granulepos!=-1 && v->granulepos!=vb->granulepos){
  108146. if(v->granulepos>vb->granulepos){
  108147. long extra=v->granulepos-vb->granulepos;
  108148. if(extra)
  108149. if(vb->eofflag){
  108150. /* partial last frame. Strip the extra samples off */
  108151. v->pcm_current-=extra>>hs;
  108152. } /* else {Shouldn't happen *unless* the bitstream is out of
  108153. spec. Either way, believe the bitstream } */
  108154. } /* else {Shouldn't happen *unless* the bitstream is out of
  108155. spec. Either way, believe the bitstream } */
  108156. v->granulepos=vb->granulepos;
  108157. }
  108158. }
  108159. /* Update, cleanup */
  108160. if(vb->eofflag)v->eofflag=1;
  108161. return(0);
  108162. }
  108163. /* pcm==NULL indicates we just want the pending samples, no more */
  108164. int vorbis_synthesis_pcmout(vorbis_dsp_state *v,float ***pcm){
  108165. vorbis_info *vi=v->vi;
  108166. if(v->pcm_returned>-1 && v->pcm_returned<v->pcm_current){
  108167. if(pcm){
  108168. int i;
  108169. for(i=0;i<vi->channels;i++)
  108170. v->pcmret[i]=v->pcm[i]+v->pcm_returned;
  108171. *pcm=v->pcmret;
  108172. }
  108173. return(v->pcm_current-v->pcm_returned);
  108174. }
  108175. return(0);
  108176. }
  108177. int vorbis_synthesis_read(vorbis_dsp_state *v,int n){
  108178. if(n && v->pcm_returned+n>v->pcm_current)return(OV_EINVAL);
  108179. v->pcm_returned+=n;
  108180. return(0);
  108181. }
  108182. /* intended for use with a specific vorbisfile feature; we want access
  108183. to the [usually synthetic/postextrapolated] buffer and lapping at
  108184. the end of a decode cycle, specifically, a half-short-block worth.
  108185. This funtion works like pcmout above, except it will also expose
  108186. this implicit buffer data not normally decoded. */
  108187. int vorbis_synthesis_lapout(vorbis_dsp_state *v,float ***pcm){
  108188. vorbis_info *vi=v->vi;
  108189. codec_setup_info *ci=(codec_setup_info *)vi->codec_setup;
  108190. int hs=ci->halfrate_flag;
  108191. int n=ci->blocksizes[v->W]>>(hs+1);
  108192. int n0=ci->blocksizes[0]>>(hs+1);
  108193. int n1=ci->blocksizes[1]>>(hs+1);
  108194. int i,j;
  108195. if(v->pcm_returned<0)return 0;
  108196. /* our returned data ends at pcm_returned; because the synthesis pcm
  108197. buffer is a two-fragment ring, that means our data block may be
  108198. fragmented by buffering, wrapping or a short block not filling
  108199. out a buffer. To simplify things, we unfragment if it's at all
  108200. possibly needed. Otherwise, we'd need to call lapout more than
  108201. once as well as hold additional dsp state. Opt for
  108202. simplicity. */
  108203. /* centerW was advanced by blockin; it would be the center of the
  108204. *next* block */
  108205. if(v->centerW==n1){
  108206. /* the data buffer wraps; swap the halves */
  108207. /* slow, sure, small */
  108208. for(j=0;j<vi->channels;j++){
  108209. float *p=v->pcm[j];
  108210. for(i=0;i<n1;i++){
  108211. float temp=p[i];
  108212. p[i]=p[i+n1];
  108213. p[i+n1]=temp;
  108214. }
  108215. }
  108216. v->pcm_current-=n1;
  108217. v->pcm_returned-=n1;
  108218. v->centerW=0;
  108219. }
  108220. /* solidify buffer into contiguous space */
  108221. if((v->lW^v->W)==1){
  108222. /* long/short or short/long */
  108223. for(j=0;j<vi->channels;j++){
  108224. float *s=v->pcm[j];
  108225. float *d=v->pcm[j]+(n1-n0)/2;
  108226. for(i=(n1+n0)/2-1;i>=0;--i)
  108227. d[i]=s[i];
  108228. }
  108229. v->pcm_returned+=(n1-n0)/2;
  108230. v->pcm_current+=(n1-n0)/2;
  108231. }else{
  108232. if(v->lW==0){
  108233. /* short/short */
  108234. for(j=0;j<vi->channels;j++){
  108235. float *s=v->pcm[j];
  108236. float *d=v->pcm[j]+n1-n0;
  108237. for(i=n0-1;i>=0;--i)
  108238. d[i]=s[i];
  108239. }
  108240. v->pcm_returned+=n1-n0;
  108241. v->pcm_current+=n1-n0;
  108242. }
  108243. }
  108244. if(pcm){
  108245. int i;
  108246. for(i=0;i<vi->channels;i++)
  108247. v->pcmret[i]=v->pcm[i]+v->pcm_returned;
  108248. *pcm=v->pcmret;
  108249. }
  108250. return(n1+n-v->pcm_returned);
  108251. }
  108252. float *vorbis_window(vorbis_dsp_state *v,int W){
  108253. vorbis_info *vi=v->vi;
  108254. codec_setup_info *ci=(codec_setup_info*) vi->codec_setup;
  108255. int hs=ci->halfrate_flag;
  108256. private_state *b=(private_state*)v->backend_state;
  108257. if(b->window[W]-1<0)return NULL;
  108258. return _vorbis_window_get(b->window[W]-hs);
  108259. }
  108260. #endif
  108261. /*** End of inlined file: block.c ***/
  108262. /*** Start of inlined file: codebook.c ***/
  108263. /*** Start of inlined file: juce_OggVorbisHeader.h ***/
  108264. // This file is included at the start of each Ogg-Vorbis .c file, just to do a few housekeeping
  108265. // tasks..
  108266. #if JUCE_MSVC
  108267. #pragma warning (disable: 4267 4127 4244 4996 4100 4701 4702 4013 4133 4206 4305 4189 4706)
  108268. #endif
  108269. /*** End of inlined file: juce_OggVorbisHeader.h ***/
  108270. #if JUCE_USE_OGGVORBIS
  108271. #include <stdlib.h>
  108272. #include <string.h>
  108273. #include <math.h>
  108274. /* packs the given codebook into the bitstream **************************/
  108275. int vorbis_staticbook_pack(const static_codebook *c,oggpack_buffer *opb){
  108276. long i,j;
  108277. int ordered=0;
  108278. /* first the basic parameters */
  108279. oggpack_write(opb,0x564342,24);
  108280. oggpack_write(opb,c->dim,16);
  108281. oggpack_write(opb,c->entries,24);
  108282. /* pack the codewords. There are two packings; length ordered and
  108283. length random. Decide between the two now. */
  108284. for(i=1;i<c->entries;i++)
  108285. if(c->lengthlist[i-1]==0 || c->lengthlist[i]<c->lengthlist[i-1])break;
  108286. if(i==c->entries)ordered=1;
  108287. if(ordered){
  108288. /* length ordered. We only need to say how many codewords of
  108289. each length. The actual codewords are generated
  108290. deterministically */
  108291. long count=0;
  108292. oggpack_write(opb,1,1); /* ordered */
  108293. oggpack_write(opb,c->lengthlist[0]-1,5); /* 1 to 32 */
  108294. for(i=1;i<c->entries;i++){
  108295. long thisx=c->lengthlist[i];
  108296. long last=c->lengthlist[i-1];
  108297. if(thisx>last){
  108298. for(j=last;j<thisx;j++){
  108299. oggpack_write(opb,i-count,_ilog(c->entries-count));
  108300. count=i;
  108301. }
  108302. }
  108303. }
  108304. oggpack_write(opb,i-count,_ilog(c->entries-count));
  108305. }else{
  108306. /* length random. Again, we don't code the codeword itself, just
  108307. the length. This time, though, we have to encode each length */
  108308. oggpack_write(opb,0,1); /* unordered */
  108309. /* algortihmic mapping has use for 'unused entries', which we tag
  108310. here. The algorithmic mapping happens as usual, but the unused
  108311. entry has no codeword. */
  108312. for(i=0;i<c->entries;i++)
  108313. if(c->lengthlist[i]==0)break;
  108314. if(i==c->entries){
  108315. oggpack_write(opb,0,1); /* no unused entries */
  108316. for(i=0;i<c->entries;i++)
  108317. oggpack_write(opb,c->lengthlist[i]-1,5);
  108318. }else{
  108319. oggpack_write(opb,1,1); /* we have unused entries; thus we tag */
  108320. for(i=0;i<c->entries;i++){
  108321. if(c->lengthlist[i]==0){
  108322. oggpack_write(opb,0,1);
  108323. }else{
  108324. oggpack_write(opb,1,1);
  108325. oggpack_write(opb,c->lengthlist[i]-1,5);
  108326. }
  108327. }
  108328. }
  108329. }
  108330. /* is the entry number the desired return value, or do we have a
  108331. mapping? If we have a mapping, what type? */
  108332. oggpack_write(opb,c->maptype,4);
  108333. switch(c->maptype){
  108334. case 0:
  108335. /* no mapping */
  108336. break;
  108337. case 1:case 2:
  108338. /* implicitly populated value mapping */
  108339. /* explicitly populated value mapping */
  108340. if(!c->quantlist){
  108341. /* no quantlist? error */
  108342. return(-1);
  108343. }
  108344. /* values that define the dequantization */
  108345. oggpack_write(opb,c->q_min,32);
  108346. oggpack_write(opb,c->q_delta,32);
  108347. oggpack_write(opb,c->q_quant-1,4);
  108348. oggpack_write(opb,c->q_sequencep,1);
  108349. {
  108350. int quantvals;
  108351. switch(c->maptype){
  108352. case 1:
  108353. /* a single column of (c->entries/c->dim) quantized values for
  108354. building a full value list algorithmically (square lattice) */
  108355. quantvals=_book_maptype1_quantvals(c);
  108356. break;
  108357. case 2:
  108358. /* every value (c->entries*c->dim total) specified explicitly */
  108359. quantvals=c->entries*c->dim;
  108360. break;
  108361. default: /* NOT_REACHABLE */
  108362. quantvals=-1;
  108363. }
  108364. /* quantized values */
  108365. for(i=0;i<quantvals;i++)
  108366. oggpack_write(opb,labs(c->quantlist[i]),c->q_quant);
  108367. }
  108368. break;
  108369. default:
  108370. /* error case; we don't have any other map types now */
  108371. return(-1);
  108372. }
  108373. return(0);
  108374. }
  108375. /* unpacks a codebook from the packet buffer into the codebook struct,
  108376. readies the codebook auxiliary structures for decode *************/
  108377. int vorbis_staticbook_unpack(oggpack_buffer *opb,static_codebook *s){
  108378. long i,j;
  108379. memset(s,0,sizeof(*s));
  108380. s->allocedp=1;
  108381. /* make sure alignment is correct */
  108382. if(oggpack_read(opb,24)!=0x564342)goto _eofout;
  108383. /* first the basic parameters */
  108384. s->dim=oggpack_read(opb,16);
  108385. s->entries=oggpack_read(opb,24);
  108386. if(s->entries==-1)goto _eofout;
  108387. /* codeword ordering.... length ordered or unordered? */
  108388. switch((int)oggpack_read(opb,1)){
  108389. case 0:
  108390. /* unordered */
  108391. s->lengthlist=(long*)_ogg_malloc(sizeof(*s->lengthlist)*s->entries);
  108392. /* allocated but unused entries? */
  108393. if(oggpack_read(opb,1)){
  108394. /* yes, unused entries */
  108395. for(i=0;i<s->entries;i++){
  108396. if(oggpack_read(opb,1)){
  108397. long num=oggpack_read(opb,5);
  108398. if(num==-1)goto _eofout;
  108399. s->lengthlist[i]=num+1;
  108400. }else
  108401. s->lengthlist[i]=0;
  108402. }
  108403. }else{
  108404. /* all entries used; no tagging */
  108405. for(i=0;i<s->entries;i++){
  108406. long num=oggpack_read(opb,5);
  108407. if(num==-1)goto _eofout;
  108408. s->lengthlist[i]=num+1;
  108409. }
  108410. }
  108411. break;
  108412. case 1:
  108413. /* ordered */
  108414. {
  108415. long length=oggpack_read(opb,5)+1;
  108416. s->lengthlist=(long*)_ogg_malloc(sizeof(*s->lengthlist)*s->entries);
  108417. for(i=0;i<s->entries;){
  108418. long num=oggpack_read(opb,_ilog(s->entries-i));
  108419. if(num==-1)goto _eofout;
  108420. for(j=0;j<num && i<s->entries;j++,i++)
  108421. s->lengthlist[i]=length;
  108422. length++;
  108423. }
  108424. }
  108425. break;
  108426. default:
  108427. /* EOF */
  108428. return(-1);
  108429. }
  108430. /* Do we have a mapping to unpack? */
  108431. switch((s->maptype=oggpack_read(opb,4))){
  108432. case 0:
  108433. /* no mapping */
  108434. break;
  108435. case 1: case 2:
  108436. /* implicitly populated value mapping */
  108437. /* explicitly populated value mapping */
  108438. s->q_min=oggpack_read(opb,32);
  108439. s->q_delta=oggpack_read(opb,32);
  108440. s->q_quant=oggpack_read(opb,4)+1;
  108441. s->q_sequencep=oggpack_read(opb,1);
  108442. {
  108443. int quantvals=0;
  108444. switch(s->maptype){
  108445. case 1:
  108446. quantvals=_book_maptype1_quantvals(s);
  108447. break;
  108448. case 2:
  108449. quantvals=s->entries*s->dim;
  108450. break;
  108451. }
  108452. /* quantized values */
  108453. s->quantlist=(long*)_ogg_malloc(sizeof(*s->quantlist)*quantvals);
  108454. for(i=0;i<quantvals;i++)
  108455. s->quantlist[i]=oggpack_read(opb,s->q_quant);
  108456. if(quantvals&&s->quantlist[quantvals-1]==-1)goto _eofout;
  108457. }
  108458. break;
  108459. default:
  108460. goto _errout;
  108461. }
  108462. /* all set */
  108463. return(0);
  108464. _errout:
  108465. _eofout:
  108466. vorbis_staticbook_clear(s);
  108467. return(-1);
  108468. }
  108469. /* returns the number of bits ************************************************/
  108470. int vorbis_book_encode(codebook *book, int a, oggpack_buffer *b){
  108471. oggpack_write(b,book->codelist[a],book->c->lengthlist[a]);
  108472. return(book->c->lengthlist[a]);
  108473. }
  108474. /* One the encode side, our vector writers are each designed for a
  108475. specific purpose, and the encoder is not flexible without modification:
  108476. The LSP vector coder uses a single stage nearest-match with no
  108477. interleave, so no step and no error return. This is specced by floor0
  108478. and doesn't change.
  108479. Residue0 encoding interleaves, uses multiple stages, and each stage
  108480. peels of a specific amount of resolution from a lattice (thus we want
  108481. to match by threshold, not nearest match). Residue doesn't *have* to
  108482. be encoded that way, but to change it, one will need to add more
  108483. infrastructure on the encode side (decode side is specced and simpler) */
  108484. /* floor0 LSP (single stage, non interleaved, nearest match) */
  108485. /* returns entry number and *modifies a* to the quantization value *****/
  108486. int vorbis_book_errorv(codebook *book,float *a){
  108487. int dim=book->dim,k;
  108488. int best=_best(book,a,1);
  108489. for(k=0;k<dim;k++)
  108490. a[k]=(book->valuelist+best*dim)[k];
  108491. return(best);
  108492. }
  108493. /* returns the number of bits and *modifies a* to the quantization value *****/
  108494. int vorbis_book_encodev(codebook *book,int best,float *a,oggpack_buffer *b){
  108495. int k,dim=book->dim;
  108496. for(k=0;k<dim;k++)
  108497. a[k]=(book->valuelist+best*dim)[k];
  108498. return(vorbis_book_encode(book,best,b));
  108499. }
  108500. /* the 'eliminate the decode tree' optimization actually requires the
  108501. codewords to be MSb first, not LSb. This is an annoying inelegancy
  108502. (and one of the first places where carefully thought out design
  108503. turned out to be wrong; Vorbis II and future Ogg codecs should go
  108504. to an MSb bitpacker), but not actually the huge hit it appears to
  108505. be. The first-stage decode table catches most words so that
  108506. bitreverse is not in the main execution path. */
  108507. STIN long decode_packed_entry_number(codebook *book, oggpack_buffer *b){
  108508. int read=book->dec_maxlength;
  108509. long lo,hi;
  108510. long lok = oggpack_look(b,book->dec_firsttablen);
  108511. if (lok >= 0) {
  108512. long entry = book->dec_firsttable[lok];
  108513. if(entry&0x80000000UL){
  108514. lo=(entry>>15)&0x7fff;
  108515. hi=book->used_entries-(entry&0x7fff);
  108516. }else{
  108517. oggpack_adv(b, book->dec_codelengths[entry-1]);
  108518. return(entry-1);
  108519. }
  108520. }else{
  108521. lo=0;
  108522. hi=book->used_entries;
  108523. }
  108524. lok = oggpack_look(b, read);
  108525. while(lok<0 && read>1)
  108526. lok = oggpack_look(b, --read);
  108527. if(lok<0)return -1;
  108528. /* bisect search for the codeword in the ordered list */
  108529. {
  108530. ogg_uint32_t testword=ogg_bitreverse((ogg_uint32_t)lok);
  108531. while(hi-lo>1){
  108532. long p=(hi-lo)>>1;
  108533. long test=book->codelist[lo+p]>testword;
  108534. lo+=p&(test-1);
  108535. hi-=p&(-test);
  108536. }
  108537. if(book->dec_codelengths[lo]<=read){
  108538. oggpack_adv(b, book->dec_codelengths[lo]);
  108539. return(lo);
  108540. }
  108541. }
  108542. oggpack_adv(b, read);
  108543. return(-1);
  108544. }
  108545. /* Decode side is specced and easier, because we don't need to find
  108546. matches using different criteria; we simply read and map. There are
  108547. two things we need to do 'depending':
  108548. We may need to support interleave. We don't really, but it's
  108549. convenient to do it here rather than rebuild the vector later.
  108550. Cascades may be additive or multiplicitive; this is not inherent in
  108551. the codebook, but set in the code using the codebook. Like
  108552. interleaving, it's easiest to do it here.
  108553. addmul==0 -> declarative (set the value)
  108554. addmul==1 -> additive
  108555. addmul==2 -> multiplicitive */
  108556. /* returns the [original, not compacted] entry number or -1 on eof *********/
  108557. long vorbis_book_decode(codebook *book, oggpack_buffer *b){
  108558. long packed_entry=decode_packed_entry_number(book,b);
  108559. if(packed_entry>=0)
  108560. return(book->dec_index[packed_entry]);
  108561. /* if there's no dec_index, the codebook unpacking isn't collapsed */
  108562. return(packed_entry);
  108563. }
  108564. /* returns 0 on OK or -1 on eof *************************************/
  108565. long vorbis_book_decodevs_add(codebook *book,float *a,oggpack_buffer *b,int n){
  108566. int step=n/book->dim;
  108567. long *entry = (long*)alloca(sizeof(*entry)*step);
  108568. float **t = (float**)alloca(sizeof(*t)*step);
  108569. int i,j,o;
  108570. for (i = 0; i < step; i++) {
  108571. entry[i]=decode_packed_entry_number(book,b);
  108572. if(entry[i]==-1)return(-1);
  108573. t[i] = book->valuelist+entry[i]*book->dim;
  108574. }
  108575. for(i=0,o=0;i<book->dim;i++,o+=step)
  108576. for (j=0;j<step;j++)
  108577. a[o+j]+=t[j][i];
  108578. return(0);
  108579. }
  108580. long vorbis_book_decodev_add(codebook *book,float *a,oggpack_buffer *b,int n){
  108581. int i,j,entry;
  108582. float *t;
  108583. if(book->dim>8){
  108584. for(i=0;i<n;){
  108585. entry = decode_packed_entry_number(book,b);
  108586. if(entry==-1)return(-1);
  108587. t = book->valuelist+entry*book->dim;
  108588. for (j=0;j<book->dim;)
  108589. a[i++]+=t[j++];
  108590. }
  108591. }else{
  108592. for(i=0;i<n;){
  108593. entry = decode_packed_entry_number(book,b);
  108594. if(entry==-1)return(-1);
  108595. t = book->valuelist+entry*book->dim;
  108596. j=0;
  108597. switch((int)book->dim){
  108598. case 8:
  108599. a[i++]+=t[j++];
  108600. case 7:
  108601. a[i++]+=t[j++];
  108602. case 6:
  108603. a[i++]+=t[j++];
  108604. case 5:
  108605. a[i++]+=t[j++];
  108606. case 4:
  108607. a[i++]+=t[j++];
  108608. case 3:
  108609. a[i++]+=t[j++];
  108610. case 2:
  108611. a[i++]+=t[j++];
  108612. case 1:
  108613. a[i++]+=t[j++];
  108614. case 0:
  108615. break;
  108616. }
  108617. }
  108618. }
  108619. return(0);
  108620. }
  108621. long vorbis_book_decodev_set(codebook *book,float *a,oggpack_buffer *b,int n){
  108622. int i,j,entry;
  108623. float *t;
  108624. for(i=0;i<n;){
  108625. entry = decode_packed_entry_number(book,b);
  108626. if(entry==-1)return(-1);
  108627. t = book->valuelist+entry*book->dim;
  108628. for (j=0;j<book->dim;)
  108629. a[i++]=t[j++];
  108630. }
  108631. return(0);
  108632. }
  108633. long vorbis_book_decodevv_add(codebook *book,float **a,long offset,int ch,
  108634. oggpack_buffer *b,int n){
  108635. long i,j,entry;
  108636. int chptr=0;
  108637. for(i=offset/ch;i<(offset+n)/ch;){
  108638. entry = decode_packed_entry_number(book,b);
  108639. if(entry==-1)return(-1);
  108640. {
  108641. const float *t = book->valuelist+entry*book->dim;
  108642. for (j=0;j<book->dim;j++){
  108643. a[chptr++][i]+=t[j];
  108644. if(chptr==ch){
  108645. chptr=0;
  108646. i++;
  108647. }
  108648. }
  108649. }
  108650. }
  108651. return(0);
  108652. }
  108653. #ifdef _V_SELFTEST
  108654. /* Simple enough; pack a few candidate codebooks, unpack them. Code a
  108655. number of vectors through (keeping track of the quantized values),
  108656. and decode using the unpacked book. quantized version of in should
  108657. exactly equal out */
  108658. #include <stdio.h>
  108659. #include "vorbis/book/lsp20_0.vqh"
  108660. #include "vorbis/book/res0a_13.vqh"
  108661. #define TESTSIZE 40
  108662. float test1[TESTSIZE]={
  108663. 0.105939f,
  108664. 0.215373f,
  108665. 0.429117f,
  108666. 0.587974f,
  108667. 0.181173f,
  108668. 0.296583f,
  108669. 0.515707f,
  108670. 0.715261f,
  108671. 0.162327f,
  108672. 0.263834f,
  108673. 0.342876f,
  108674. 0.406025f,
  108675. 0.103571f,
  108676. 0.223561f,
  108677. 0.368513f,
  108678. 0.540313f,
  108679. 0.136672f,
  108680. 0.395882f,
  108681. 0.587183f,
  108682. 0.652476f,
  108683. 0.114338f,
  108684. 0.417300f,
  108685. 0.525486f,
  108686. 0.698679f,
  108687. 0.147492f,
  108688. 0.324481f,
  108689. 0.643089f,
  108690. 0.757582f,
  108691. 0.139556f,
  108692. 0.215795f,
  108693. 0.324559f,
  108694. 0.399387f,
  108695. 0.120236f,
  108696. 0.267420f,
  108697. 0.446940f,
  108698. 0.608760f,
  108699. 0.115587f,
  108700. 0.287234f,
  108701. 0.571081f,
  108702. 0.708603f,
  108703. };
  108704. float test3[TESTSIZE]={
  108705. 0,1,-2,3,4,-5,6,7,8,9,
  108706. 8,-2,7,-1,4,6,8,3,1,-9,
  108707. 10,11,12,13,14,15,26,17,18,19,
  108708. 30,-25,-30,-1,-5,-32,4,3,-2,0};
  108709. static_codebook *testlist[]={&_vq_book_lsp20_0,
  108710. &_vq_book_res0a_13,NULL};
  108711. float *testvec[]={test1,test3};
  108712. int main(){
  108713. oggpack_buffer write;
  108714. oggpack_buffer read;
  108715. long ptr=0,i;
  108716. oggpack_writeinit(&write);
  108717. fprintf(stderr,"Testing codebook abstraction...:\n");
  108718. while(testlist[ptr]){
  108719. codebook c;
  108720. static_codebook s;
  108721. float *qv=alloca(sizeof(*qv)*TESTSIZE);
  108722. float *iv=alloca(sizeof(*iv)*TESTSIZE);
  108723. memcpy(qv,testvec[ptr],sizeof(*qv)*TESTSIZE);
  108724. memset(iv,0,sizeof(*iv)*TESTSIZE);
  108725. fprintf(stderr,"\tpacking/coding %ld... ",ptr);
  108726. /* pack the codebook, write the testvector */
  108727. oggpack_reset(&write);
  108728. vorbis_book_init_encode(&c,testlist[ptr]); /* get it into memory
  108729. we can write */
  108730. vorbis_staticbook_pack(testlist[ptr],&write);
  108731. fprintf(stderr,"Codebook size %ld bytes... ",oggpack_bytes(&write));
  108732. for(i=0;i<TESTSIZE;i+=c.dim){
  108733. int best=_best(&c,qv+i,1);
  108734. vorbis_book_encodev(&c,best,qv+i,&write);
  108735. }
  108736. vorbis_book_clear(&c);
  108737. fprintf(stderr,"OK.\n");
  108738. fprintf(stderr,"\tunpacking/decoding %ld... ",ptr);
  108739. /* transfer the write data to a read buffer and unpack/read */
  108740. oggpack_readinit(&read,oggpack_get_buffer(&write),oggpack_bytes(&write));
  108741. if(vorbis_staticbook_unpack(&read,&s)){
  108742. fprintf(stderr,"Error unpacking codebook.\n");
  108743. exit(1);
  108744. }
  108745. if(vorbis_book_init_decode(&c,&s)){
  108746. fprintf(stderr,"Error initializing codebook.\n");
  108747. exit(1);
  108748. }
  108749. for(i=0;i<TESTSIZE;i+=c.dim)
  108750. if(vorbis_book_decodev_set(&c,iv+i,&read,c.dim)==-1){
  108751. fprintf(stderr,"Error reading codebook test data (EOP).\n");
  108752. exit(1);
  108753. }
  108754. for(i=0;i<TESTSIZE;i++)
  108755. if(fabs(qv[i]-iv[i])>.000001){
  108756. fprintf(stderr,"read (%g) != written (%g) at position (%ld)\n",
  108757. iv[i],qv[i],i);
  108758. exit(1);
  108759. }
  108760. fprintf(stderr,"OK\n");
  108761. ptr++;
  108762. }
  108763. /* The above is the trivial stuff; now try unquantizing a log scale codebook */
  108764. exit(0);
  108765. }
  108766. #endif
  108767. #endif
  108768. /*** End of inlined file: codebook.c ***/
  108769. /*** Start of inlined file: envelope.c ***/
  108770. /*** Start of inlined file: juce_OggVorbisHeader.h ***/
  108771. // This file is included at the start of each Ogg-Vorbis .c file, just to do a few housekeeping
  108772. // tasks..
  108773. #if JUCE_MSVC
  108774. #pragma warning (disable: 4267 4127 4244 4996 4100 4701 4702 4013 4133 4206 4305 4189 4706)
  108775. #endif
  108776. /*** End of inlined file: juce_OggVorbisHeader.h ***/
  108777. #if JUCE_USE_OGGVORBIS
  108778. #include <stdlib.h>
  108779. #include <string.h>
  108780. #include <stdio.h>
  108781. #include <math.h>
  108782. void _ve_envelope_init(envelope_lookup *e,vorbis_info *vi){
  108783. codec_setup_info *ci=(codec_setup_info*)vi->codec_setup;
  108784. vorbis_info_psy_global *gi=&ci->psy_g_param;
  108785. int ch=vi->channels;
  108786. int i,j;
  108787. int n=e->winlength=128;
  108788. e->searchstep=64; /* not random */
  108789. e->minenergy=gi->preecho_minenergy;
  108790. e->ch=ch;
  108791. e->storage=128;
  108792. e->cursor=ci->blocksizes[1]/2;
  108793. e->mdct_win=(float*)_ogg_calloc(n,sizeof(*e->mdct_win));
  108794. mdct_init(&e->mdct,n);
  108795. for(i=0;i<n;i++){
  108796. e->mdct_win[i]=sin(i/(n-1.)*M_PI);
  108797. e->mdct_win[i]*=e->mdct_win[i];
  108798. }
  108799. /* magic follows */
  108800. e->band[0].begin=2; e->band[0].end=4;
  108801. e->band[1].begin=4; e->band[1].end=5;
  108802. e->band[2].begin=6; e->band[2].end=6;
  108803. e->band[3].begin=9; e->band[3].end=8;
  108804. e->band[4].begin=13; e->band[4].end=8;
  108805. e->band[5].begin=17; e->band[5].end=8;
  108806. e->band[6].begin=22; e->band[6].end=8;
  108807. for(j=0;j<VE_BANDS;j++){
  108808. n=e->band[j].end;
  108809. e->band[j].window=(float*)_ogg_malloc(n*sizeof(*e->band[0].window));
  108810. for(i=0;i<n;i++){
  108811. e->band[j].window[i]=sin((i+.5)/n*M_PI);
  108812. e->band[j].total+=e->band[j].window[i];
  108813. }
  108814. e->band[j].total=1./e->band[j].total;
  108815. }
  108816. e->filter=(envelope_filter_state*)_ogg_calloc(VE_BANDS*ch,sizeof(*e->filter));
  108817. e->mark=(int*)_ogg_calloc(e->storage,sizeof(*e->mark));
  108818. }
  108819. void _ve_envelope_clear(envelope_lookup *e){
  108820. int i;
  108821. mdct_clear(&e->mdct);
  108822. for(i=0;i<VE_BANDS;i++)
  108823. _ogg_free(e->band[i].window);
  108824. _ogg_free(e->mdct_win);
  108825. _ogg_free(e->filter);
  108826. _ogg_free(e->mark);
  108827. memset(e,0,sizeof(*e));
  108828. }
  108829. /* fairly straight threshhold-by-band based until we find something
  108830. that works better and isn't patented. */
  108831. static int _ve_amp(envelope_lookup *ve,
  108832. vorbis_info_psy_global *gi,
  108833. float *data,
  108834. envelope_band *bands,
  108835. envelope_filter_state *filters,
  108836. long pos){
  108837. long n=ve->winlength;
  108838. int ret=0;
  108839. long i,j;
  108840. float decay;
  108841. /* we want to have a 'minimum bar' for energy, else we're just
  108842. basing blocks on quantization noise that outweighs the signal
  108843. itself (for low power signals) */
  108844. float minV=ve->minenergy;
  108845. float *vec=(float*) alloca(n*sizeof(*vec));
  108846. /* stretch is used to gradually lengthen the number of windows
  108847. considered prevoius-to-potential-trigger */
  108848. int stretch=max(VE_MINSTRETCH,ve->stretch/2);
  108849. float penalty=gi->stretch_penalty-(ve->stretch/2-VE_MINSTRETCH);
  108850. if(penalty<0.f)penalty=0.f;
  108851. if(penalty>gi->stretch_penalty)penalty=gi->stretch_penalty;
  108852. /*_analysis_output_always("lpcm",seq2,data,n,0,0,
  108853. totalshift+pos*ve->searchstep);*/
  108854. /* window and transform */
  108855. for(i=0;i<n;i++)
  108856. vec[i]=data[i]*ve->mdct_win[i];
  108857. mdct_forward(&ve->mdct,vec,vec);
  108858. /*_analysis_output_always("mdct",seq2,vec,n/2,0,1,0); */
  108859. /* near-DC spreading function; this has nothing to do with
  108860. psychoacoustics, just sidelobe leakage and window size */
  108861. {
  108862. float temp=vec[0]*vec[0]+.7*vec[1]*vec[1]+.2*vec[2]*vec[2];
  108863. int ptr=filters->nearptr;
  108864. /* the accumulation is regularly refreshed from scratch to avoid
  108865. floating point creep */
  108866. if(ptr==0){
  108867. decay=filters->nearDC_acc=filters->nearDC_partialacc+temp;
  108868. filters->nearDC_partialacc=temp;
  108869. }else{
  108870. decay=filters->nearDC_acc+=temp;
  108871. filters->nearDC_partialacc+=temp;
  108872. }
  108873. filters->nearDC_acc-=filters->nearDC[ptr];
  108874. filters->nearDC[ptr]=temp;
  108875. decay*=(1./(VE_NEARDC+1));
  108876. filters->nearptr++;
  108877. if(filters->nearptr>=VE_NEARDC)filters->nearptr=0;
  108878. decay=todB(&decay)*.5-15.f;
  108879. }
  108880. /* perform spreading and limiting, also smooth the spectrum. yes,
  108881. the MDCT results in all real coefficients, but it still *behaves*
  108882. like real/imaginary pairs */
  108883. for(i=0;i<n/2;i+=2){
  108884. float val=vec[i]*vec[i]+vec[i+1]*vec[i+1];
  108885. val=todB(&val)*.5f;
  108886. if(val<decay)val=decay;
  108887. if(val<minV)val=minV;
  108888. vec[i>>1]=val;
  108889. decay-=8.;
  108890. }
  108891. /*_analysis_output_always("spread",seq2++,vec,n/4,0,0,0);*/
  108892. /* perform preecho/postecho triggering by band */
  108893. for(j=0;j<VE_BANDS;j++){
  108894. float acc=0.;
  108895. float valmax,valmin;
  108896. /* accumulate amplitude */
  108897. for(i=0;i<bands[j].end;i++)
  108898. acc+=vec[i+bands[j].begin]*bands[j].window[i];
  108899. acc*=bands[j].total;
  108900. /* convert amplitude to delta */
  108901. {
  108902. int p,thisx=filters[j].ampptr;
  108903. float postmax,postmin,premax=-99999.f,premin=99999.f;
  108904. p=thisx;
  108905. p--;
  108906. if(p<0)p+=VE_AMP;
  108907. postmax=max(acc,filters[j].ampbuf[p]);
  108908. postmin=min(acc,filters[j].ampbuf[p]);
  108909. for(i=0;i<stretch;i++){
  108910. p--;
  108911. if(p<0)p+=VE_AMP;
  108912. premax=max(premax,filters[j].ampbuf[p]);
  108913. premin=min(premin,filters[j].ampbuf[p]);
  108914. }
  108915. valmin=postmin-premin;
  108916. valmax=postmax-premax;
  108917. /*filters[j].markers[pos]=valmax;*/
  108918. filters[j].ampbuf[thisx]=acc;
  108919. filters[j].ampptr++;
  108920. if(filters[j].ampptr>=VE_AMP)filters[j].ampptr=0;
  108921. }
  108922. /* look at min/max, decide trigger */
  108923. if(valmax>gi->preecho_thresh[j]+penalty){
  108924. ret|=1;
  108925. ret|=4;
  108926. }
  108927. if(valmin<gi->postecho_thresh[j]-penalty)ret|=2;
  108928. }
  108929. return(ret);
  108930. }
  108931. #if 0
  108932. static int seq=0;
  108933. static ogg_int64_t totalshift=-1024;
  108934. #endif
  108935. long _ve_envelope_search(vorbis_dsp_state *v){
  108936. vorbis_info *vi=v->vi;
  108937. codec_setup_info *ci=(codec_setup_info *)vi->codec_setup;
  108938. vorbis_info_psy_global *gi=&ci->psy_g_param;
  108939. envelope_lookup *ve=((private_state *)(v->backend_state))->ve;
  108940. long i,j;
  108941. int first=ve->current/ve->searchstep;
  108942. int last=v->pcm_current/ve->searchstep-VE_WIN;
  108943. if(first<0)first=0;
  108944. /* make sure we have enough storage to match the PCM */
  108945. if(last+VE_WIN+VE_POST>ve->storage){
  108946. ve->storage=last+VE_WIN+VE_POST; /* be sure */
  108947. ve->mark=(int*)_ogg_realloc(ve->mark,ve->storage*sizeof(*ve->mark));
  108948. }
  108949. for(j=first;j<last;j++){
  108950. int ret=0;
  108951. ve->stretch++;
  108952. if(ve->stretch>VE_MAXSTRETCH*2)
  108953. ve->stretch=VE_MAXSTRETCH*2;
  108954. for(i=0;i<ve->ch;i++){
  108955. float *pcm=v->pcm[i]+ve->searchstep*(j);
  108956. ret|=_ve_amp(ve,gi,pcm,ve->band,ve->filter+i*VE_BANDS,j);
  108957. }
  108958. ve->mark[j+VE_POST]=0;
  108959. if(ret&1){
  108960. ve->mark[j]=1;
  108961. ve->mark[j+1]=1;
  108962. }
  108963. if(ret&2){
  108964. ve->mark[j]=1;
  108965. if(j>0)ve->mark[j-1]=1;
  108966. }
  108967. if(ret&4)ve->stretch=-1;
  108968. }
  108969. ve->current=last*ve->searchstep;
  108970. {
  108971. long centerW=v->centerW;
  108972. long testW=
  108973. centerW+
  108974. ci->blocksizes[v->W]/4+
  108975. ci->blocksizes[1]/2+
  108976. ci->blocksizes[0]/4;
  108977. j=ve->cursor;
  108978. while(j<ve->current-(ve->searchstep)){/* account for postecho
  108979. working back one window */
  108980. if(j>=testW)return(1);
  108981. ve->cursor=j;
  108982. if(ve->mark[j/ve->searchstep]){
  108983. if(j>centerW){
  108984. #if 0
  108985. if(j>ve->curmark){
  108986. float *marker=alloca(v->pcm_current*sizeof(*marker));
  108987. int l,m;
  108988. memset(marker,0,sizeof(*marker)*v->pcm_current);
  108989. fprintf(stderr,"mark! seq=%d, cursor:%fs time:%fs\n",
  108990. seq,
  108991. (totalshift+ve->cursor)/44100.,
  108992. (totalshift+j)/44100.);
  108993. _analysis_output_always("pcmL",seq,v->pcm[0],v->pcm_current,0,0,totalshift);
  108994. _analysis_output_always("pcmR",seq,v->pcm[1],v->pcm_current,0,0,totalshift);
  108995. _analysis_output_always("markL",seq,v->pcm[0],j,0,0,totalshift);
  108996. _analysis_output_always("markR",seq,v->pcm[1],j,0,0,totalshift);
  108997. for(m=0;m<VE_BANDS;m++){
  108998. char buf[80];
  108999. sprintf(buf,"delL%d",m);
  109000. for(l=0;l<last;l++)marker[l*ve->searchstep]=ve->filter[m].markers[l]*.1;
  109001. _analysis_output_always(buf,seq,marker,v->pcm_current,0,0,totalshift);
  109002. }
  109003. for(m=0;m<VE_BANDS;m++){
  109004. char buf[80];
  109005. sprintf(buf,"delR%d",m);
  109006. for(l=0;l<last;l++)marker[l*ve->searchstep]=ve->filter[m+VE_BANDS].markers[l]*.1;
  109007. _analysis_output_always(buf,seq,marker,v->pcm_current,0,0,totalshift);
  109008. }
  109009. for(l=0;l<last;l++)marker[l*ve->searchstep]=ve->mark[l]*.4;
  109010. _analysis_output_always("mark",seq,marker,v->pcm_current,0,0,totalshift);
  109011. seq++;
  109012. }
  109013. #endif
  109014. ve->curmark=j;
  109015. if(j>=testW)return(1);
  109016. return(0);
  109017. }
  109018. }
  109019. j+=ve->searchstep;
  109020. }
  109021. }
  109022. return(-1);
  109023. }
  109024. int _ve_envelope_mark(vorbis_dsp_state *v){
  109025. envelope_lookup *ve=((private_state *)(v->backend_state))->ve;
  109026. vorbis_info *vi=v->vi;
  109027. codec_setup_info *ci=(codec_setup_info*)vi->codec_setup;
  109028. long centerW=v->centerW;
  109029. long beginW=centerW-ci->blocksizes[v->W]/4;
  109030. long endW=centerW+ci->blocksizes[v->W]/4;
  109031. if(v->W){
  109032. beginW-=ci->blocksizes[v->lW]/4;
  109033. endW+=ci->blocksizes[v->nW]/4;
  109034. }else{
  109035. beginW-=ci->blocksizes[0]/4;
  109036. endW+=ci->blocksizes[0]/4;
  109037. }
  109038. if(ve->curmark>=beginW && ve->curmark<endW)return(1);
  109039. {
  109040. long first=beginW/ve->searchstep;
  109041. long last=endW/ve->searchstep;
  109042. long i;
  109043. for(i=first;i<last;i++)
  109044. if(ve->mark[i])return(1);
  109045. }
  109046. return(0);
  109047. }
  109048. void _ve_envelope_shift(envelope_lookup *e,long shift){
  109049. int smallsize=e->current/e->searchstep+VE_POST; /* adjust for placing marks
  109050. ahead of ve->current */
  109051. int smallshift=shift/e->searchstep;
  109052. memmove(e->mark,e->mark+smallshift,(smallsize-smallshift)*sizeof(*e->mark));
  109053. #if 0
  109054. for(i=0;i<VE_BANDS*e->ch;i++)
  109055. memmove(e->filter[i].markers,
  109056. e->filter[i].markers+smallshift,
  109057. (1024-smallshift)*sizeof(*(*e->filter).markers));
  109058. totalshift+=shift;
  109059. #endif
  109060. e->current-=shift;
  109061. if(e->curmark>=0)
  109062. e->curmark-=shift;
  109063. e->cursor-=shift;
  109064. }
  109065. #endif
  109066. /*** End of inlined file: envelope.c ***/
  109067. /*** Start of inlined file: floor0.c ***/
  109068. /*** Start of inlined file: juce_OggVorbisHeader.h ***/
  109069. // This file is included at the start of each Ogg-Vorbis .c file, just to do a few housekeeping
  109070. // tasks..
  109071. #if JUCE_MSVC
  109072. #pragma warning (disable: 4267 4127 4244 4996 4100 4701 4702 4013 4133 4206 4305 4189 4706)
  109073. #endif
  109074. /*** End of inlined file: juce_OggVorbisHeader.h ***/
  109075. #if JUCE_USE_OGGVORBIS
  109076. #include <stdlib.h>
  109077. #include <string.h>
  109078. #include <math.h>
  109079. /*** Start of inlined file: lsp.h ***/
  109080. #ifndef _V_LSP_H_
  109081. #define _V_LSP_H_
  109082. extern int vorbis_lpc_to_lsp(float *lpc,float *lsp,int m);
  109083. extern void vorbis_lsp_to_curve(float *curve,int *map,int n,int ln,
  109084. float *lsp,int m,
  109085. float amp,float ampoffset);
  109086. #endif
  109087. /*** End of inlined file: lsp.h ***/
  109088. #include <stdio.h>
  109089. typedef struct {
  109090. int ln;
  109091. int m;
  109092. int **linearmap;
  109093. int n[2];
  109094. vorbis_info_floor0 *vi;
  109095. long bits;
  109096. long frames;
  109097. } vorbis_look_floor0;
  109098. /***********************************************/
  109099. static void floor0_free_info(vorbis_info_floor *i){
  109100. vorbis_info_floor0 *info=(vorbis_info_floor0 *)i;
  109101. if(info){
  109102. memset(info,0,sizeof(*info));
  109103. _ogg_free(info);
  109104. }
  109105. }
  109106. static void floor0_free_look(vorbis_look_floor *i){
  109107. vorbis_look_floor0 *look=(vorbis_look_floor0 *)i;
  109108. if(look){
  109109. if(look->linearmap){
  109110. if(look->linearmap[0])_ogg_free(look->linearmap[0]);
  109111. if(look->linearmap[1])_ogg_free(look->linearmap[1]);
  109112. _ogg_free(look->linearmap);
  109113. }
  109114. memset(look,0,sizeof(*look));
  109115. _ogg_free(look);
  109116. }
  109117. }
  109118. static vorbis_info_floor *floor0_unpack (vorbis_info *vi,oggpack_buffer *opb){
  109119. codec_setup_info *ci=(codec_setup_info*)vi->codec_setup;
  109120. int j;
  109121. vorbis_info_floor0 *info=(vorbis_info_floor0*)_ogg_malloc(sizeof(*info));
  109122. info->order=oggpack_read(opb,8);
  109123. info->rate=oggpack_read(opb,16);
  109124. info->barkmap=oggpack_read(opb,16);
  109125. info->ampbits=oggpack_read(opb,6);
  109126. info->ampdB=oggpack_read(opb,8);
  109127. info->numbooks=oggpack_read(opb,4)+1;
  109128. if(info->order<1)goto err_out;
  109129. if(info->rate<1)goto err_out;
  109130. if(info->barkmap<1)goto err_out;
  109131. if(info->numbooks<1)goto err_out;
  109132. for(j=0;j<info->numbooks;j++){
  109133. info->books[j]=oggpack_read(opb,8);
  109134. if(info->books[j]<0 || info->books[j]>=ci->books)goto err_out;
  109135. }
  109136. return(info);
  109137. err_out:
  109138. floor0_free_info(info);
  109139. return(NULL);
  109140. }
  109141. /* initialize Bark scale and normalization lookups. We could do this
  109142. with static tables, but Vorbis allows a number of possible
  109143. combinations, so it's best to do it computationally.
  109144. The below is authoritative in terms of defining scale mapping.
  109145. Note that the scale depends on the sampling rate as well as the
  109146. linear block and mapping sizes */
  109147. static void floor0_map_lazy_init(vorbis_block *vb,
  109148. vorbis_info_floor *infoX,
  109149. vorbis_look_floor0 *look){
  109150. if(!look->linearmap[vb->W]){
  109151. vorbis_dsp_state *vd=vb->vd;
  109152. vorbis_info *vi=vd->vi;
  109153. codec_setup_info *ci=(codec_setup_info*)vi->codec_setup;
  109154. vorbis_info_floor0 *info=(vorbis_info_floor0 *)infoX;
  109155. int W=vb->W;
  109156. int n=ci->blocksizes[W]/2,j;
  109157. /* we choose a scaling constant so that:
  109158. floor(bark(rate/2-1)*C)=mapped-1
  109159. floor(bark(rate/2)*C)=mapped */
  109160. float scale=look->ln/toBARK(info->rate/2.f);
  109161. /* the mapping from a linear scale to a smaller bark scale is
  109162. straightforward. We do *not* make sure that the linear mapping
  109163. does not skip bark-scale bins; the decoder simply skips them and
  109164. the encoder may do what it wishes in filling them. They're
  109165. necessary in some mapping combinations to keep the scale spacing
  109166. accurate */
  109167. look->linearmap[W]=(int*)_ogg_malloc((n+1)*sizeof(**look->linearmap));
  109168. for(j=0;j<n;j++){
  109169. int val=floor( toBARK((info->rate/2.f)/n*j)
  109170. *scale); /* bark numbers represent band edges */
  109171. if(val>=look->ln)val=look->ln-1; /* guard against the approximation */
  109172. look->linearmap[W][j]=val;
  109173. }
  109174. look->linearmap[W][j]=-1;
  109175. look->n[W]=n;
  109176. }
  109177. }
  109178. static vorbis_look_floor *floor0_look(vorbis_dsp_state *vd,
  109179. vorbis_info_floor *i){
  109180. vorbis_info_floor0 *info=(vorbis_info_floor0*)i;
  109181. vorbis_look_floor0 *look=(vorbis_look_floor0*)_ogg_calloc(1,sizeof(*look));
  109182. look->m=info->order;
  109183. look->ln=info->barkmap;
  109184. look->vi=info;
  109185. look->linearmap=(int**)_ogg_calloc(2,sizeof(*look->linearmap));
  109186. return look;
  109187. }
  109188. static void *floor0_inverse1(vorbis_block *vb,vorbis_look_floor *i){
  109189. vorbis_look_floor0 *look=(vorbis_look_floor0 *)i;
  109190. vorbis_info_floor0 *info=look->vi;
  109191. int j,k;
  109192. int ampraw=oggpack_read(&vb->opb,info->ampbits);
  109193. if(ampraw>0){ /* also handles the -1 out of data case */
  109194. long maxval=(1<<info->ampbits)-1;
  109195. float amp=(float)ampraw/maxval*info->ampdB;
  109196. int booknum=oggpack_read(&vb->opb,_ilog(info->numbooks));
  109197. if(booknum!=-1 && booknum<info->numbooks){ /* be paranoid */
  109198. codec_setup_info *ci=(codec_setup_info *)vb->vd->vi->codec_setup;
  109199. codebook *b=ci->fullbooks+info->books[booknum];
  109200. float last=0.f;
  109201. /* the additional b->dim is a guard against any possible stack
  109202. smash; b->dim is provably more than we can overflow the
  109203. vector */
  109204. float *lsp=(float*)_vorbis_block_alloc(vb,sizeof(*lsp)*(look->m+b->dim+1));
  109205. for(j=0;j<look->m;j+=b->dim)
  109206. if(vorbis_book_decodev_set(b,lsp+j,&vb->opb,b->dim)==-1)goto eop;
  109207. for(j=0;j<look->m;){
  109208. for(k=0;k<b->dim;k++,j++)lsp[j]+=last;
  109209. last=lsp[j-1];
  109210. }
  109211. lsp[look->m]=amp;
  109212. return(lsp);
  109213. }
  109214. }
  109215. eop:
  109216. return(NULL);
  109217. }
  109218. static int floor0_inverse2(vorbis_block *vb,vorbis_look_floor *i,
  109219. void *memo,float *out){
  109220. vorbis_look_floor0 *look=(vorbis_look_floor0 *)i;
  109221. vorbis_info_floor0 *info=look->vi;
  109222. floor0_map_lazy_init(vb,info,look);
  109223. if(memo){
  109224. float *lsp=(float *)memo;
  109225. float amp=lsp[look->m];
  109226. /* take the coefficients back to a spectral envelope curve */
  109227. vorbis_lsp_to_curve(out,
  109228. look->linearmap[vb->W],
  109229. look->n[vb->W],
  109230. look->ln,
  109231. lsp,look->m,amp,(float)info->ampdB);
  109232. return(1);
  109233. }
  109234. memset(out,0,sizeof(*out)*look->n[vb->W]);
  109235. return(0);
  109236. }
  109237. /* export hooks */
  109238. vorbis_func_floor floor0_exportbundle={
  109239. NULL,&floor0_unpack,&floor0_look,&floor0_free_info,
  109240. &floor0_free_look,&floor0_inverse1,&floor0_inverse2
  109241. };
  109242. #endif
  109243. /*** End of inlined file: floor0.c ***/
  109244. /*** Start of inlined file: floor1.c ***/
  109245. /*** Start of inlined file: juce_OggVorbisHeader.h ***/
  109246. // This file is included at the start of each Ogg-Vorbis .c file, just to do a few housekeeping
  109247. // tasks..
  109248. #if JUCE_MSVC
  109249. #pragma warning (disable: 4267 4127 4244 4996 4100 4701 4702 4013 4133 4206 4305 4189 4706)
  109250. #endif
  109251. /*** End of inlined file: juce_OggVorbisHeader.h ***/
  109252. #if JUCE_USE_OGGVORBIS
  109253. #include <stdlib.h>
  109254. #include <string.h>
  109255. #include <math.h>
  109256. #include <stdio.h>
  109257. #define floor1_rangedB 140 /* floor 1 fixed at -140dB to 0dB range */
  109258. typedef struct {
  109259. int sorted_index[VIF_POSIT+2];
  109260. int forward_index[VIF_POSIT+2];
  109261. int reverse_index[VIF_POSIT+2];
  109262. int hineighbor[VIF_POSIT];
  109263. int loneighbor[VIF_POSIT];
  109264. int posts;
  109265. int n;
  109266. int quant_q;
  109267. vorbis_info_floor1 *vi;
  109268. long phrasebits;
  109269. long postbits;
  109270. long frames;
  109271. } vorbis_look_floor1;
  109272. typedef struct lsfit_acc{
  109273. long x0;
  109274. long x1;
  109275. long xa;
  109276. long ya;
  109277. long x2a;
  109278. long y2a;
  109279. long xya;
  109280. long an;
  109281. } lsfit_acc;
  109282. /***********************************************/
  109283. static void floor1_free_info(vorbis_info_floor *i){
  109284. vorbis_info_floor1 *info=(vorbis_info_floor1 *)i;
  109285. if(info){
  109286. memset(info,0,sizeof(*info));
  109287. _ogg_free(info);
  109288. }
  109289. }
  109290. static void floor1_free_look(vorbis_look_floor *i){
  109291. vorbis_look_floor1 *look=(vorbis_look_floor1 *)i;
  109292. if(look){
  109293. /*fprintf(stderr,"floor 1 bit usage %f:%f (%f total)\n",
  109294. (float)look->phrasebits/look->frames,
  109295. (float)look->postbits/look->frames,
  109296. (float)(look->postbits+look->phrasebits)/look->frames);*/
  109297. memset(look,0,sizeof(*look));
  109298. _ogg_free(look);
  109299. }
  109300. }
  109301. static void floor1_pack (vorbis_info_floor *i,oggpack_buffer *opb){
  109302. vorbis_info_floor1 *info=(vorbis_info_floor1 *)i;
  109303. int j,k;
  109304. int count=0;
  109305. int rangebits;
  109306. int maxposit=info->postlist[1];
  109307. int maxclass=-1;
  109308. /* save out partitions */
  109309. oggpack_write(opb,info->partitions,5); /* only 0 to 31 legal */
  109310. for(j=0;j<info->partitions;j++){
  109311. oggpack_write(opb,info->partitionclass[j],4); /* only 0 to 15 legal */
  109312. if(maxclass<info->partitionclass[j])maxclass=info->partitionclass[j];
  109313. }
  109314. /* save out partition classes */
  109315. for(j=0;j<maxclass+1;j++){
  109316. oggpack_write(opb,info->class_dim[j]-1,3); /* 1 to 8 */
  109317. oggpack_write(opb,info->class_subs[j],2); /* 0 to 3 */
  109318. if(info->class_subs[j])oggpack_write(opb,info->class_book[j],8);
  109319. for(k=0;k<(1<<info->class_subs[j]);k++)
  109320. oggpack_write(opb,info->class_subbook[j][k]+1,8);
  109321. }
  109322. /* save out the post list */
  109323. oggpack_write(opb,info->mult-1,2); /* only 1,2,3,4 legal now */
  109324. oggpack_write(opb,ilog2(maxposit),4);
  109325. rangebits=ilog2(maxposit);
  109326. for(j=0,k=0;j<info->partitions;j++){
  109327. count+=info->class_dim[info->partitionclass[j]];
  109328. for(;k<count;k++)
  109329. oggpack_write(opb,info->postlist[k+2],rangebits);
  109330. }
  109331. }
  109332. static vorbis_info_floor *floor1_unpack (vorbis_info *vi,oggpack_buffer *opb){
  109333. codec_setup_info *ci=(codec_setup_info*)vi->codec_setup;
  109334. int j,k,count=0,maxclass=-1,rangebits;
  109335. vorbis_info_floor1 *info=(vorbis_info_floor1*)_ogg_calloc(1,sizeof(*info));
  109336. /* read partitions */
  109337. info->partitions=oggpack_read(opb,5); /* only 0 to 31 legal */
  109338. for(j=0;j<info->partitions;j++){
  109339. info->partitionclass[j]=oggpack_read(opb,4); /* only 0 to 15 legal */
  109340. if(maxclass<info->partitionclass[j])maxclass=info->partitionclass[j];
  109341. }
  109342. /* read partition classes */
  109343. for(j=0;j<maxclass+1;j++){
  109344. info->class_dim[j]=oggpack_read(opb,3)+1; /* 1 to 8 */
  109345. info->class_subs[j]=oggpack_read(opb,2); /* 0,1,2,3 bits */
  109346. if(info->class_subs[j]<0)
  109347. goto err_out;
  109348. if(info->class_subs[j])info->class_book[j]=oggpack_read(opb,8);
  109349. if(info->class_book[j]<0 || info->class_book[j]>=ci->books)
  109350. goto err_out;
  109351. for(k=0;k<(1<<info->class_subs[j]);k++){
  109352. info->class_subbook[j][k]=oggpack_read(opb,8)-1;
  109353. if(info->class_subbook[j][k]<-1 || info->class_subbook[j][k]>=ci->books)
  109354. goto err_out;
  109355. }
  109356. }
  109357. /* read the post list */
  109358. info->mult=oggpack_read(opb,2)+1; /* only 1,2,3,4 legal now */
  109359. rangebits=oggpack_read(opb,4);
  109360. for(j=0,k=0;j<info->partitions;j++){
  109361. count+=info->class_dim[info->partitionclass[j]];
  109362. for(;k<count;k++){
  109363. int t=info->postlist[k+2]=oggpack_read(opb,rangebits);
  109364. if(t<0 || t>=(1<<rangebits))
  109365. goto err_out;
  109366. }
  109367. }
  109368. info->postlist[0]=0;
  109369. info->postlist[1]=1<<rangebits;
  109370. return(info);
  109371. err_out:
  109372. floor1_free_info(info);
  109373. return(NULL);
  109374. }
  109375. static int icomp(const void *a,const void *b){
  109376. return(**(int **)a-**(int **)b);
  109377. }
  109378. static vorbis_look_floor *floor1_look(vorbis_dsp_state *vd,
  109379. vorbis_info_floor *in){
  109380. int *sortpointer[VIF_POSIT+2];
  109381. vorbis_info_floor1 *info=(vorbis_info_floor1*)in;
  109382. vorbis_look_floor1 *look=(vorbis_look_floor1*)_ogg_calloc(1,sizeof(*look));
  109383. int i,j,n=0;
  109384. look->vi=info;
  109385. look->n=info->postlist[1];
  109386. /* we drop each position value in-between already decoded values,
  109387. and use linear interpolation to predict each new value past the
  109388. edges. The positions are read in the order of the position
  109389. list... we precompute the bounding positions in the lookup. Of
  109390. course, the neighbors can change (if a position is declined), but
  109391. this is an initial mapping */
  109392. for(i=0;i<info->partitions;i++)n+=info->class_dim[info->partitionclass[i]];
  109393. n+=2;
  109394. look->posts=n;
  109395. /* also store a sorted position index */
  109396. for(i=0;i<n;i++)sortpointer[i]=info->postlist+i;
  109397. qsort(sortpointer,n,sizeof(*sortpointer),icomp);
  109398. /* points from sort order back to range number */
  109399. for(i=0;i<n;i++)look->forward_index[i]=sortpointer[i]-info->postlist;
  109400. /* points from range order to sorted position */
  109401. for(i=0;i<n;i++)look->reverse_index[look->forward_index[i]]=i;
  109402. /* we actually need the post values too */
  109403. for(i=0;i<n;i++)look->sorted_index[i]=info->postlist[look->forward_index[i]];
  109404. /* quantize values to multiplier spec */
  109405. switch(info->mult){
  109406. case 1: /* 1024 -> 256 */
  109407. look->quant_q=256;
  109408. break;
  109409. case 2: /* 1024 -> 128 */
  109410. look->quant_q=128;
  109411. break;
  109412. case 3: /* 1024 -> 86 */
  109413. look->quant_q=86;
  109414. break;
  109415. case 4: /* 1024 -> 64 */
  109416. look->quant_q=64;
  109417. break;
  109418. }
  109419. /* discover our neighbors for decode where we don't use fit flags
  109420. (that would push the neighbors outward) */
  109421. for(i=0;i<n-2;i++){
  109422. int lo=0;
  109423. int hi=1;
  109424. int lx=0;
  109425. int hx=look->n;
  109426. int currentx=info->postlist[i+2];
  109427. for(j=0;j<i+2;j++){
  109428. int x=info->postlist[j];
  109429. if(x>lx && x<currentx){
  109430. lo=j;
  109431. lx=x;
  109432. }
  109433. if(x<hx && x>currentx){
  109434. hi=j;
  109435. hx=x;
  109436. }
  109437. }
  109438. look->loneighbor[i]=lo;
  109439. look->hineighbor[i]=hi;
  109440. }
  109441. return(look);
  109442. }
  109443. static int render_point(int x0,int x1,int y0,int y1,int x){
  109444. y0&=0x7fff; /* mask off flag */
  109445. y1&=0x7fff;
  109446. {
  109447. int dy=y1-y0;
  109448. int adx=x1-x0;
  109449. int ady=abs(dy);
  109450. int err=ady*(x-x0);
  109451. int off=err/adx;
  109452. if(dy<0)return(y0-off);
  109453. return(y0+off);
  109454. }
  109455. }
  109456. static int vorbis_dBquant(const float *x){
  109457. int i= *x*7.3142857f+1023.5f;
  109458. if(i>1023)return(1023);
  109459. if(i<0)return(0);
  109460. return i;
  109461. }
  109462. static float FLOOR1_fromdB_LOOKUP[256]={
  109463. 1.0649863e-07F, 1.1341951e-07F, 1.2079015e-07F, 1.2863978e-07F,
  109464. 1.3699951e-07F, 1.4590251e-07F, 1.5538408e-07F, 1.6548181e-07F,
  109465. 1.7623575e-07F, 1.8768855e-07F, 1.9988561e-07F, 2.128753e-07F,
  109466. 2.2670913e-07F, 2.4144197e-07F, 2.5713223e-07F, 2.7384213e-07F,
  109467. 2.9163793e-07F, 3.1059021e-07F, 3.3077411e-07F, 3.5226968e-07F,
  109468. 3.7516214e-07F, 3.9954229e-07F, 4.2550680e-07F, 4.5315863e-07F,
  109469. 4.8260743e-07F, 5.1396998e-07F, 5.4737065e-07F, 5.8294187e-07F,
  109470. 6.2082472e-07F, 6.6116941e-07F, 7.0413592e-07F, 7.4989464e-07F,
  109471. 7.9862701e-07F, 8.5052630e-07F, 9.0579828e-07F, 9.6466216e-07F,
  109472. 1.0273513e-06F, 1.0941144e-06F, 1.1652161e-06F, 1.2409384e-06F,
  109473. 1.3215816e-06F, 1.4074654e-06F, 1.4989305e-06F, 1.5963394e-06F,
  109474. 1.7000785e-06F, 1.8105592e-06F, 1.9282195e-06F, 2.0535261e-06F,
  109475. 2.1869758e-06F, 2.3290978e-06F, 2.4804557e-06F, 2.6416497e-06F,
  109476. 2.8133190e-06F, 2.9961443e-06F, 3.1908506e-06F, 3.3982101e-06F,
  109477. 3.6190449e-06F, 3.8542308e-06F, 4.1047004e-06F, 4.3714470e-06F,
  109478. 4.6555282e-06F, 4.9580707e-06F, 5.2802740e-06F, 5.6234160e-06F,
  109479. 5.9888572e-06F, 6.3780469e-06F, 6.7925283e-06F, 7.2339451e-06F,
  109480. 7.7040476e-06F, 8.2047000e-06F, 8.7378876e-06F, 9.3057248e-06F,
  109481. 9.9104632e-06F, 1.0554501e-05F, 1.1240392e-05F, 1.1970856e-05F,
  109482. 1.2748789e-05F, 1.3577278e-05F, 1.4459606e-05F, 1.5399272e-05F,
  109483. 1.6400004e-05F, 1.7465768e-05F, 1.8600792e-05F, 1.9809576e-05F,
  109484. 2.1096914e-05F, 2.2467911e-05F, 2.3928002e-05F, 2.5482978e-05F,
  109485. 2.7139006e-05F, 2.8902651e-05F, 3.0780908e-05F, 3.2781225e-05F,
  109486. 3.4911534e-05F, 3.7180282e-05F, 3.9596466e-05F, 4.2169667e-05F,
  109487. 4.4910090e-05F, 4.7828601e-05F, 5.0936773e-05F, 5.4246931e-05F,
  109488. 5.7772202e-05F, 6.1526565e-05F, 6.5524908e-05F, 6.9783085e-05F,
  109489. 7.4317983e-05F, 7.9147585e-05F, 8.4291040e-05F, 8.9768747e-05F,
  109490. 9.5602426e-05F, 0.00010181521F, 0.00010843174F, 0.00011547824F,
  109491. 0.00012298267F, 0.00013097477F, 0.00013948625F, 0.00014855085F,
  109492. 0.00015820453F, 0.00016848555F, 0.00017943469F, 0.00019109536F,
  109493. 0.00020351382F, 0.00021673929F, 0.00023082423F, 0.00024582449F,
  109494. 0.00026179955F, 0.00027881276F, 0.00029693158F, 0.00031622787F,
  109495. 0.00033677814F, 0.00035866388F, 0.00038197188F, 0.00040679456F,
  109496. 0.00043323036F, 0.00046138411F, 0.00049136745F, 0.00052329927F,
  109497. 0.00055730621F, 0.00059352311F, 0.00063209358F, 0.00067317058F,
  109498. 0.00071691700F, 0.00076350630F, 0.00081312324F, 0.00086596457F,
  109499. 0.00092223983F, 0.00098217216F, 0.0010459992F, 0.0011139742F,
  109500. 0.0011863665F, 0.0012634633F, 0.0013455702F, 0.0014330129F,
  109501. 0.0015261382F, 0.0016253153F, 0.0017309374F, 0.0018434235F,
  109502. 0.0019632195F, 0.0020908006F, 0.0022266726F, 0.0023713743F,
  109503. 0.0025254795F, 0.0026895994F, 0.0028643847F, 0.0030505286F,
  109504. 0.0032487691F, 0.0034598925F, 0.0036847358F, 0.0039241906F,
  109505. 0.0041792066F, 0.0044507950F, 0.0047400328F, 0.0050480668F,
  109506. 0.0053761186F, 0.0057254891F, 0.0060975636F, 0.0064938176F,
  109507. 0.0069158225F, 0.0073652516F, 0.0078438871F, 0.0083536271F,
  109508. 0.0088964928F, 0.009474637F, 0.010090352F, 0.010746080F,
  109509. 0.011444421F, 0.012188144F, 0.012980198F, 0.013823725F,
  109510. 0.014722068F, 0.015678791F, 0.016697687F, 0.017782797F,
  109511. 0.018938423F, 0.020169149F, 0.021479854F, 0.022875735F,
  109512. 0.024362330F, 0.025945531F, 0.027631618F, 0.029427276F,
  109513. 0.031339626F, 0.033376252F, 0.035545228F, 0.037855157F,
  109514. 0.040315199F, 0.042935108F, 0.045725273F, 0.048696758F,
  109515. 0.051861348F, 0.055231591F, 0.058820850F, 0.062643361F,
  109516. 0.066714279F, 0.071049749F, 0.075666962F, 0.080584227F,
  109517. 0.085821044F, 0.091398179F, 0.097337747F, 0.10366330F,
  109518. 0.11039993F, 0.11757434F, 0.12521498F, 0.13335215F,
  109519. 0.14201813F, 0.15124727F, 0.16107617F, 0.17154380F,
  109520. 0.18269168F, 0.19456402F, 0.20720788F, 0.22067342F,
  109521. 0.23501402F, 0.25028656F, 0.26655159F, 0.28387361F,
  109522. 0.30232132F, 0.32196786F, 0.34289114F, 0.36517414F,
  109523. 0.38890521F, 0.41417847F, 0.44109412F, 0.46975890F,
  109524. 0.50028648F, 0.53279791F, 0.56742212F, 0.60429640F,
  109525. 0.64356699F, 0.68538959F, 0.72993007F, 0.77736504F,
  109526. 0.82788260F, 0.88168307F, 0.9389798F, 1.F,
  109527. };
  109528. static void render_line(int x0,int x1,int y0,int y1,float *d){
  109529. int dy=y1-y0;
  109530. int adx=x1-x0;
  109531. int ady=abs(dy);
  109532. int base=dy/adx;
  109533. int sy=(dy<0?base-1:base+1);
  109534. int x=x0;
  109535. int y=y0;
  109536. int err=0;
  109537. ady-=abs(base*adx);
  109538. d[x]*=FLOOR1_fromdB_LOOKUP[y];
  109539. while(++x<x1){
  109540. err=err+ady;
  109541. if(err>=adx){
  109542. err-=adx;
  109543. y+=sy;
  109544. }else{
  109545. y+=base;
  109546. }
  109547. d[x]*=FLOOR1_fromdB_LOOKUP[y];
  109548. }
  109549. }
  109550. static void render_line0(int x0,int x1,int y0,int y1,int *d){
  109551. int dy=y1-y0;
  109552. int adx=x1-x0;
  109553. int ady=abs(dy);
  109554. int base=dy/adx;
  109555. int sy=(dy<0?base-1:base+1);
  109556. int x=x0;
  109557. int y=y0;
  109558. int err=0;
  109559. ady-=abs(base*adx);
  109560. d[x]=y;
  109561. while(++x<x1){
  109562. err=err+ady;
  109563. if(err>=adx){
  109564. err-=adx;
  109565. y+=sy;
  109566. }else{
  109567. y+=base;
  109568. }
  109569. d[x]=y;
  109570. }
  109571. }
  109572. /* the floor has already been filtered to only include relevant sections */
  109573. static int accumulate_fit(const float *flr,const float *mdct,
  109574. int x0, int x1,lsfit_acc *a,
  109575. int n,vorbis_info_floor1 *info){
  109576. long i;
  109577. 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;
  109578. memset(a,0,sizeof(*a));
  109579. a->x0=x0;
  109580. a->x1=x1;
  109581. if(x1>=n)x1=n-1;
  109582. for(i=x0;i<=x1;i++){
  109583. int quantized=vorbis_dBquant(flr+i);
  109584. if(quantized){
  109585. if(mdct[i]+info->twofitatten>=flr[i]){
  109586. xa += i;
  109587. ya += quantized;
  109588. x2a += i*i;
  109589. y2a += quantized*quantized;
  109590. xya += i*quantized;
  109591. na++;
  109592. }else{
  109593. xb += i;
  109594. yb += quantized;
  109595. x2b += i*i;
  109596. y2b += quantized*quantized;
  109597. xyb += i*quantized;
  109598. nb++;
  109599. }
  109600. }
  109601. }
  109602. xb+=xa;
  109603. yb+=ya;
  109604. x2b+=x2a;
  109605. y2b+=y2a;
  109606. xyb+=xya;
  109607. nb+=na;
  109608. /* weight toward the actually used frequencies if we meet the threshhold */
  109609. {
  109610. int weight=nb*info->twofitweight/(na+1);
  109611. a->xa=xa*weight+xb;
  109612. a->ya=ya*weight+yb;
  109613. a->x2a=x2a*weight+x2b;
  109614. a->y2a=y2a*weight+y2b;
  109615. a->xya=xya*weight+xyb;
  109616. a->an=na*weight+nb;
  109617. }
  109618. return(na);
  109619. }
  109620. static void fit_line(lsfit_acc *a,int fits,int *y0,int *y1){
  109621. long x=0,y=0,x2=0,y2=0,xy=0,an=0,i;
  109622. long x0=a[0].x0;
  109623. long x1=a[fits-1].x1;
  109624. for(i=0;i<fits;i++){
  109625. x+=a[i].xa;
  109626. y+=a[i].ya;
  109627. x2+=a[i].x2a;
  109628. y2+=a[i].y2a;
  109629. xy+=a[i].xya;
  109630. an+=a[i].an;
  109631. }
  109632. if(*y0>=0){
  109633. x+= x0;
  109634. y+= *y0;
  109635. x2+= x0 * x0;
  109636. y2+= *y0 * *y0;
  109637. xy+= *y0 * x0;
  109638. an++;
  109639. }
  109640. if(*y1>=0){
  109641. x+= x1;
  109642. y+= *y1;
  109643. x2+= x1 * x1;
  109644. y2+= *y1 * *y1;
  109645. xy+= *y1 * x1;
  109646. an++;
  109647. }
  109648. if(an){
  109649. /* need 64 bit multiplies, which C doesn't give portably as int */
  109650. double fx=x;
  109651. double fy=y;
  109652. double fx2=x2;
  109653. double fxy=xy;
  109654. double denom=1./(an*fx2-fx*fx);
  109655. double a=(fy*fx2-fxy*fx)*denom;
  109656. double b=(an*fxy-fx*fy)*denom;
  109657. *y0=rint(a+b*x0);
  109658. *y1=rint(a+b*x1);
  109659. /* limit to our range! */
  109660. if(*y0>1023)*y0=1023;
  109661. if(*y1>1023)*y1=1023;
  109662. if(*y0<0)*y0=0;
  109663. if(*y1<0)*y1=0;
  109664. }else{
  109665. *y0=0;
  109666. *y1=0;
  109667. }
  109668. }
  109669. /*static void fit_line_point(lsfit_acc *a,int fits,int *y0,int *y1){
  109670. long y=0;
  109671. int i;
  109672. for(i=0;i<fits && y==0;i++)
  109673. y+=a[i].ya;
  109674. *y0=*y1=y;
  109675. }*/
  109676. static int inspect_error(int x0,int x1,int y0,int y1,const float *mask,
  109677. const float *mdct,
  109678. vorbis_info_floor1 *info){
  109679. int dy=y1-y0;
  109680. int adx=x1-x0;
  109681. int ady=abs(dy);
  109682. int base=dy/adx;
  109683. int sy=(dy<0?base-1:base+1);
  109684. int x=x0;
  109685. int y=y0;
  109686. int err=0;
  109687. int val=vorbis_dBquant(mask+x);
  109688. int mse=0;
  109689. int n=0;
  109690. ady-=abs(base*adx);
  109691. mse=(y-val);
  109692. mse*=mse;
  109693. n++;
  109694. if(mdct[x]+info->twofitatten>=mask[x]){
  109695. if(y+info->maxover<val)return(1);
  109696. if(y-info->maxunder>val)return(1);
  109697. }
  109698. while(++x<x1){
  109699. err=err+ady;
  109700. if(err>=adx){
  109701. err-=adx;
  109702. y+=sy;
  109703. }else{
  109704. y+=base;
  109705. }
  109706. val=vorbis_dBquant(mask+x);
  109707. mse+=((y-val)*(y-val));
  109708. n++;
  109709. if(mdct[x]+info->twofitatten>=mask[x]){
  109710. if(val){
  109711. if(y+info->maxover<val)return(1);
  109712. if(y-info->maxunder>val)return(1);
  109713. }
  109714. }
  109715. }
  109716. if(info->maxover*info->maxover/n>info->maxerr)return(0);
  109717. if(info->maxunder*info->maxunder/n>info->maxerr)return(0);
  109718. if(mse/n>info->maxerr)return(1);
  109719. return(0);
  109720. }
  109721. static int post_Y(int *A,int *B,int pos){
  109722. if(A[pos]<0)
  109723. return B[pos];
  109724. if(B[pos]<0)
  109725. return A[pos];
  109726. return (A[pos]+B[pos])>>1;
  109727. }
  109728. int *floor1_fit(vorbis_block *vb,void *look_,
  109729. const float *logmdct, /* in */
  109730. const float *logmask){
  109731. long i,j;
  109732. vorbis_look_floor1 *look = (vorbis_look_floor1*) look_;
  109733. vorbis_info_floor1 *info=look->vi;
  109734. long n=look->n;
  109735. long posts=look->posts;
  109736. long nonzero=0;
  109737. lsfit_acc fits[VIF_POSIT+1];
  109738. int fit_valueA[VIF_POSIT+2]; /* index by range list position */
  109739. int fit_valueB[VIF_POSIT+2]; /* index by range list position */
  109740. int loneighbor[VIF_POSIT+2]; /* sorted index of range list position (+2) */
  109741. int hineighbor[VIF_POSIT+2];
  109742. int *output=NULL;
  109743. int memo[VIF_POSIT+2];
  109744. for(i=0;i<posts;i++)fit_valueA[i]=-200; /* mark all unused */
  109745. for(i=0;i<posts;i++)fit_valueB[i]=-200; /* mark all unused */
  109746. for(i=0;i<posts;i++)loneighbor[i]=0; /* 0 for the implicit 0 post */
  109747. for(i=0;i<posts;i++)hineighbor[i]=1; /* 1 for the implicit post at n */
  109748. for(i=0;i<posts;i++)memo[i]=-1; /* no neighbor yet */
  109749. /* quantize the relevant floor points and collect them into line fit
  109750. structures (one per minimal division) at the same time */
  109751. if(posts==0){
  109752. nonzero+=accumulate_fit(logmask,logmdct,0,n,fits,n,info);
  109753. }else{
  109754. for(i=0;i<posts-1;i++)
  109755. nonzero+=accumulate_fit(logmask,logmdct,look->sorted_index[i],
  109756. look->sorted_index[i+1],fits+i,
  109757. n,info);
  109758. }
  109759. if(nonzero){
  109760. /* start by fitting the implicit base case.... */
  109761. int y0=-200;
  109762. int y1=-200;
  109763. fit_line(fits,posts-1,&y0,&y1);
  109764. fit_valueA[0]=y0;
  109765. fit_valueB[0]=y0;
  109766. fit_valueB[1]=y1;
  109767. fit_valueA[1]=y1;
  109768. /* Non degenerate case */
  109769. /* start progressive splitting. This is a greedy, non-optimal
  109770. algorithm, but simple and close enough to the best
  109771. answer. */
  109772. for(i=2;i<posts;i++){
  109773. int sortpos=look->reverse_index[i];
  109774. int ln=loneighbor[sortpos];
  109775. int hn=hineighbor[sortpos];
  109776. /* eliminate repeat searches of a particular range with a memo */
  109777. if(memo[ln]!=hn){
  109778. /* haven't performed this error search yet */
  109779. int lsortpos=look->reverse_index[ln];
  109780. int hsortpos=look->reverse_index[hn];
  109781. memo[ln]=hn;
  109782. {
  109783. /* A note: we want to bound/minimize *local*, not global, error */
  109784. int lx=info->postlist[ln];
  109785. int hx=info->postlist[hn];
  109786. int ly=post_Y(fit_valueA,fit_valueB,ln);
  109787. int hy=post_Y(fit_valueA,fit_valueB,hn);
  109788. if(ly==-1 || hy==-1){
  109789. exit(1);
  109790. }
  109791. if(inspect_error(lx,hx,ly,hy,logmask,logmdct,info)){
  109792. /* outside error bounds/begin search area. Split it. */
  109793. int ly0=-200;
  109794. int ly1=-200;
  109795. int hy0=-200;
  109796. int hy1=-200;
  109797. fit_line(fits+lsortpos,sortpos-lsortpos,&ly0,&ly1);
  109798. fit_line(fits+sortpos,hsortpos-sortpos,&hy0,&hy1);
  109799. /* store new edge values */
  109800. fit_valueB[ln]=ly0;
  109801. if(ln==0)fit_valueA[ln]=ly0;
  109802. fit_valueA[i]=ly1;
  109803. fit_valueB[i]=hy0;
  109804. fit_valueA[hn]=hy1;
  109805. if(hn==1)fit_valueB[hn]=hy1;
  109806. if(ly1>=0 || hy0>=0){
  109807. /* store new neighbor values */
  109808. for(j=sortpos-1;j>=0;j--)
  109809. if(hineighbor[j]==hn)
  109810. hineighbor[j]=i;
  109811. else
  109812. break;
  109813. for(j=sortpos+1;j<posts;j++)
  109814. if(loneighbor[j]==ln)
  109815. loneighbor[j]=i;
  109816. else
  109817. break;
  109818. }
  109819. }else{
  109820. fit_valueA[i]=-200;
  109821. fit_valueB[i]=-200;
  109822. }
  109823. }
  109824. }
  109825. }
  109826. output=(int*)_vorbis_block_alloc(vb,sizeof(*output)*posts);
  109827. output[0]=post_Y(fit_valueA,fit_valueB,0);
  109828. output[1]=post_Y(fit_valueA,fit_valueB,1);
  109829. /* fill in posts marked as not using a fit; we will zero
  109830. back out to 'unused' when encoding them so long as curve
  109831. interpolation doesn't force them into use */
  109832. for(i=2;i<posts;i++){
  109833. int ln=look->loneighbor[i-2];
  109834. int hn=look->hineighbor[i-2];
  109835. int x0=info->postlist[ln];
  109836. int x1=info->postlist[hn];
  109837. int y0=output[ln];
  109838. int y1=output[hn];
  109839. int predicted=render_point(x0,x1,y0,y1,info->postlist[i]);
  109840. int vx=post_Y(fit_valueA,fit_valueB,i);
  109841. if(vx>=0 && predicted!=vx){
  109842. output[i]=vx;
  109843. }else{
  109844. output[i]= predicted|0x8000;
  109845. }
  109846. }
  109847. }
  109848. return(output);
  109849. }
  109850. int *floor1_interpolate_fit(vorbis_block *vb,void *look_,
  109851. int *A,int *B,
  109852. int del){
  109853. long i;
  109854. vorbis_look_floor1* look = (vorbis_look_floor1*) look_;
  109855. long posts=look->posts;
  109856. int *output=NULL;
  109857. if(A && B){
  109858. output=(int*)_vorbis_block_alloc(vb,sizeof(*output)*posts);
  109859. for(i=0;i<posts;i++){
  109860. output[i]=((65536-del)*(A[i]&0x7fff)+del*(B[i]&0x7fff)+32768)>>16;
  109861. if(A[i]&0x8000 && B[i]&0x8000)output[i]|=0x8000;
  109862. }
  109863. }
  109864. return(output);
  109865. }
  109866. int floor1_encode(oggpack_buffer *opb,vorbis_block *vb,
  109867. void*look_,
  109868. int *post,int *ilogmask){
  109869. long i,j;
  109870. vorbis_look_floor1 *look = (vorbis_look_floor1 *) look_;
  109871. vorbis_info_floor1 *info=look->vi;
  109872. long posts=look->posts;
  109873. codec_setup_info *ci=(codec_setup_info*)vb->vd->vi->codec_setup;
  109874. int out[VIF_POSIT+2];
  109875. static_codebook **sbooks=ci->book_param;
  109876. codebook *books=ci->fullbooks;
  109877. static long seq=0;
  109878. /* quantize values to multiplier spec */
  109879. if(post){
  109880. for(i=0;i<posts;i++){
  109881. int val=post[i]&0x7fff;
  109882. switch(info->mult){
  109883. case 1: /* 1024 -> 256 */
  109884. val>>=2;
  109885. break;
  109886. case 2: /* 1024 -> 128 */
  109887. val>>=3;
  109888. break;
  109889. case 3: /* 1024 -> 86 */
  109890. val/=12;
  109891. break;
  109892. case 4: /* 1024 -> 64 */
  109893. val>>=4;
  109894. break;
  109895. }
  109896. post[i]=val | (post[i]&0x8000);
  109897. }
  109898. out[0]=post[0];
  109899. out[1]=post[1];
  109900. /* find prediction values for each post and subtract them */
  109901. for(i=2;i<posts;i++){
  109902. int ln=look->loneighbor[i-2];
  109903. int hn=look->hineighbor[i-2];
  109904. int x0=info->postlist[ln];
  109905. int x1=info->postlist[hn];
  109906. int y0=post[ln];
  109907. int y1=post[hn];
  109908. int predicted=render_point(x0,x1,y0,y1,info->postlist[i]);
  109909. if((post[i]&0x8000) || (predicted==post[i])){
  109910. post[i]=predicted|0x8000; /* in case there was roundoff jitter
  109911. in interpolation */
  109912. out[i]=0;
  109913. }else{
  109914. int headroom=(look->quant_q-predicted<predicted?
  109915. look->quant_q-predicted:predicted);
  109916. int val=post[i]-predicted;
  109917. /* at this point the 'deviation' value is in the range +/- max
  109918. range, but the real, unique range can always be mapped to
  109919. only [0-maxrange). So we want to wrap the deviation into
  109920. this limited range, but do it in the way that least screws
  109921. an essentially gaussian probability distribution. */
  109922. if(val<0)
  109923. if(val<-headroom)
  109924. val=headroom-val-1;
  109925. else
  109926. val=-1-(val<<1);
  109927. else
  109928. if(val>=headroom)
  109929. val= val+headroom;
  109930. else
  109931. val<<=1;
  109932. out[i]=val;
  109933. post[ln]&=0x7fff;
  109934. post[hn]&=0x7fff;
  109935. }
  109936. }
  109937. /* we have everything we need. pack it out */
  109938. /* mark nontrivial floor */
  109939. oggpack_write(opb,1,1);
  109940. /* beginning/end post */
  109941. look->frames++;
  109942. look->postbits+=ilog(look->quant_q-1)*2;
  109943. oggpack_write(opb,out[0],ilog(look->quant_q-1));
  109944. oggpack_write(opb,out[1],ilog(look->quant_q-1));
  109945. /* partition by partition */
  109946. for(i=0,j=2;i<info->partitions;i++){
  109947. int classx=info->partitionclass[i];
  109948. int cdim=info->class_dim[classx];
  109949. int csubbits=info->class_subs[classx];
  109950. int csub=1<<csubbits;
  109951. int bookas[8]={0,0,0,0,0,0,0,0};
  109952. int cval=0;
  109953. int cshift=0;
  109954. int k,l;
  109955. /* generate the partition's first stage cascade value */
  109956. if(csubbits){
  109957. int maxval[8];
  109958. for(k=0;k<csub;k++){
  109959. int booknum=info->class_subbook[classx][k];
  109960. if(booknum<0){
  109961. maxval[k]=1;
  109962. }else{
  109963. maxval[k]=sbooks[info->class_subbook[classx][k]]->entries;
  109964. }
  109965. }
  109966. for(k=0;k<cdim;k++){
  109967. for(l=0;l<csub;l++){
  109968. int val=out[j+k];
  109969. if(val<maxval[l]){
  109970. bookas[k]=l;
  109971. break;
  109972. }
  109973. }
  109974. cval|= bookas[k]<<cshift;
  109975. cshift+=csubbits;
  109976. }
  109977. /* write it */
  109978. look->phrasebits+=
  109979. vorbis_book_encode(books+info->class_book[classx],cval,opb);
  109980. #ifdef TRAIN_FLOOR1
  109981. {
  109982. FILE *of;
  109983. char buffer[80];
  109984. sprintf(buffer,"line_%dx%ld_class%d.vqd",
  109985. vb->pcmend/2,posts-2,class);
  109986. of=fopen(buffer,"a");
  109987. fprintf(of,"%d\n",cval);
  109988. fclose(of);
  109989. }
  109990. #endif
  109991. }
  109992. /* write post values */
  109993. for(k=0;k<cdim;k++){
  109994. int book=info->class_subbook[classx][bookas[k]];
  109995. if(book>=0){
  109996. /* hack to allow training with 'bad' books */
  109997. if(out[j+k]<(books+book)->entries)
  109998. look->postbits+=vorbis_book_encode(books+book,
  109999. out[j+k],opb);
  110000. /*else
  110001. fprintf(stderr,"+!");*/
  110002. #ifdef TRAIN_FLOOR1
  110003. {
  110004. FILE *of;
  110005. char buffer[80];
  110006. sprintf(buffer,"line_%dx%ld_%dsub%d.vqd",
  110007. vb->pcmend/2,posts-2,class,bookas[k]);
  110008. of=fopen(buffer,"a");
  110009. fprintf(of,"%d\n",out[j+k]);
  110010. fclose(of);
  110011. }
  110012. #endif
  110013. }
  110014. }
  110015. j+=cdim;
  110016. }
  110017. {
  110018. /* generate quantized floor equivalent to what we'd unpack in decode */
  110019. /* render the lines */
  110020. int hx=0;
  110021. int lx=0;
  110022. int ly=post[0]*info->mult;
  110023. for(j=1;j<look->posts;j++){
  110024. int current=look->forward_index[j];
  110025. int hy=post[current]&0x7fff;
  110026. if(hy==post[current]){
  110027. hy*=info->mult;
  110028. hx=info->postlist[current];
  110029. render_line0(lx,hx,ly,hy,ilogmask);
  110030. lx=hx;
  110031. ly=hy;
  110032. }
  110033. }
  110034. for(j=hx;j<vb->pcmend/2;j++)ilogmask[j]=ly; /* be certain */
  110035. seq++;
  110036. return(1);
  110037. }
  110038. }else{
  110039. oggpack_write(opb,0,1);
  110040. memset(ilogmask,0,vb->pcmend/2*sizeof(*ilogmask));
  110041. seq++;
  110042. return(0);
  110043. }
  110044. }
  110045. static void *floor1_inverse1(vorbis_block *vb,vorbis_look_floor *in){
  110046. vorbis_look_floor1 *look=(vorbis_look_floor1 *)in;
  110047. vorbis_info_floor1 *info=look->vi;
  110048. codec_setup_info *ci=(codec_setup_info*)vb->vd->vi->codec_setup;
  110049. int i,j,k;
  110050. codebook *books=ci->fullbooks;
  110051. /* unpack wrapped/predicted values from stream */
  110052. if(oggpack_read(&vb->opb,1)==1){
  110053. int *fit_value=(int*)_vorbis_block_alloc(vb,(look->posts)*sizeof(*fit_value));
  110054. fit_value[0]=oggpack_read(&vb->opb,ilog(look->quant_q-1));
  110055. fit_value[1]=oggpack_read(&vb->opb,ilog(look->quant_q-1));
  110056. /* partition by partition */
  110057. for(i=0,j=2;i<info->partitions;i++){
  110058. int classx=info->partitionclass[i];
  110059. int cdim=info->class_dim[classx];
  110060. int csubbits=info->class_subs[classx];
  110061. int csub=1<<csubbits;
  110062. int cval=0;
  110063. /* decode the partition's first stage cascade value */
  110064. if(csubbits){
  110065. cval=vorbis_book_decode(books+info->class_book[classx],&vb->opb);
  110066. if(cval==-1)goto eop;
  110067. }
  110068. for(k=0;k<cdim;k++){
  110069. int book=info->class_subbook[classx][cval&(csub-1)];
  110070. cval>>=csubbits;
  110071. if(book>=0){
  110072. if((fit_value[j+k]=vorbis_book_decode(books+book,&vb->opb))==-1)
  110073. goto eop;
  110074. }else{
  110075. fit_value[j+k]=0;
  110076. }
  110077. }
  110078. j+=cdim;
  110079. }
  110080. /* unwrap positive values and reconsitute via linear interpolation */
  110081. for(i=2;i<look->posts;i++){
  110082. int predicted=render_point(info->postlist[look->loneighbor[i-2]],
  110083. info->postlist[look->hineighbor[i-2]],
  110084. fit_value[look->loneighbor[i-2]],
  110085. fit_value[look->hineighbor[i-2]],
  110086. info->postlist[i]);
  110087. int hiroom=look->quant_q-predicted;
  110088. int loroom=predicted;
  110089. int room=(hiroom<loroom?hiroom:loroom)<<1;
  110090. int val=fit_value[i];
  110091. if(val){
  110092. if(val>=room){
  110093. if(hiroom>loroom){
  110094. val = val-loroom;
  110095. }else{
  110096. val = -1-(val-hiroom);
  110097. }
  110098. }else{
  110099. if(val&1){
  110100. val= -((val+1)>>1);
  110101. }else{
  110102. val>>=1;
  110103. }
  110104. }
  110105. fit_value[i]=val+predicted;
  110106. fit_value[look->loneighbor[i-2]]&=0x7fff;
  110107. fit_value[look->hineighbor[i-2]]&=0x7fff;
  110108. }else{
  110109. fit_value[i]=predicted|0x8000;
  110110. }
  110111. }
  110112. return(fit_value);
  110113. }
  110114. eop:
  110115. return(NULL);
  110116. }
  110117. static int floor1_inverse2(vorbis_block *vb,vorbis_look_floor *in,void *memo,
  110118. float *out){
  110119. vorbis_look_floor1 *look=(vorbis_look_floor1 *)in;
  110120. vorbis_info_floor1 *info=look->vi;
  110121. codec_setup_info *ci=(codec_setup_info*)vb->vd->vi->codec_setup;
  110122. int n=ci->blocksizes[vb->W]/2;
  110123. int j;
  110124. if(memo){
  110125. /* render the lines */
  110126. int *fit_value=(int *)memo;
  110127. int hx=0;
  110128. int lx=0;
  110129. int ly=fit_value[0]*info->mult;
  110130. for(j=1;j<look->posts;j++){
  110131. int current=look->forward_index[j];
  110132. int hy=fit_value[current]&0x7fff;
  110133. if(hy==fit_value[current]){
  110134. hy*=info->mult;
  110135. hx=info->postlist[current];
  110136. render_line(lx,hx,ly,hy,out);
  110137. lx=hx;
  110138. ly=hy;
  110139. }
  110140. }
  110141. for(j=hx;j<n;j++)out[j]*=FLOOR1_fromdB_LOOKUP[ly]; /* be certain */
  110142. return(1);
  110143. }
  110144. memset(out,0,sizeof(*out)*n);
  110145. return(0);
  110146. }
  110147. /* export hooks */
  110148. vorbis_func_floor floor1_exportbundle={
  110149. &floor1_pack,&floor1_unpack,&floor1_look,&floor1_free_info,
  110150. &floor1_free_look,&floor1_inverse1,&floor1_inverse2
  110151. };
  110152. #endif
  110153. /*** End of inlined file: floor1.c ***/
  110154. /*** Start of inlined file: info.c ***/
  110155. /*** Start of inlined file: juce_OggVorbisHeader.h ***/
  110156. // This file is included at the start of each Ogg-Vorbis .c file, just to do a few housekeeping
  110157. // tasks..
  110158. #if JUCE_MSVC
  110159. #pragma warning (disable: 4267 4127 4244 4996 4100 4701 4702 4013 4133 4206 4305 4189 4706)
  110160. #endif
  110161. /*** End of inlined file: juce_OggVorbisHeader.h ***/
  110162. #if JUCE_USE_OGGVORBIS
  110163. /* general handling of the header and the vorbis_info structure (and
  110164. substructures) */
  110165. #include <stdlib.h>
  110166. #include <string.h>
  110167. #include <ctype.h>
  110168. static void _v_writestring(oggpack_buffer *o, const char *s, int bytes){
  110169. while(bytes--){
  110170. oggpack_write(o,*s++,8);
  110171. }
  110172. }
  110173. static void _v_readstring(oggpack_buffer *o,char *buf,int bytes){
  110174. while(bytes--){
  110175. *buf++=oggpack_read(o,8);
  110176. }
  110177. }
  110178. void vorbis_comment_init(vorbis_comment *vc){
  110179. memset(vc,0,sizeof(*vc));
  110180. }
  110181. void vorbis_comment_add(vorbis_comment *vc,char *comment){
  110182. vc->user_comments=(char**)_ogg_realloc(vc->user_comments,
  110183. (vc->comments+2)*sizeof(*vc->user_comments));
  110184. vc->comment_lengths=(int*)_ogg_realloc(vc->comment_lengths,
  110185. (vc->comments+2)*sizeof(*vc->comment_lengths));
  110186. vc->comment_lengths[vc->comments]=strlen(comment);
  110187. vc->user_comments[vc->comments]=(char*)_ogg_malloc(vc->comment_lengths[vc->comments]+1);
  110188. strcpy(vc->user_comments[vc->comments], comment);
  110189. vc->comments++;
  110190. vc->user_comments[vc->comments]=NULL;
  110191. }
  110192. void vorbis_comment_add_tag(vorbis_comment *vc, const char *tag, char *contents){
  110193. char *comment=(char*)alloca(strlen(tag)+strlen(contents)+2); /* +2 for = and \0 */
  110194. strcpy(comment, tag);
  110195. strcat(comment, "=");
  110196. strcat(comment, contents);
  110197. vorbis_comment_add(vc, comment);
  110198. }
  110199. /* This is more or less the same as strncasecmp - but that doesn't exist
  110200. * everywhere, and this is a fairly trivial function, so we include it */
  110201. static int tagcompare(const char *s1, const char *s2, int n){
  110202. int c=0;
  110203. while(c < n){
  110204. if(toupper(s1[c]) != toupper(s2[c]))
  110205. return !0;
  110206. c++;
  110207. }
  110208. return 0;
  110209. }
  110210. char *vorbis_comment_query(vorbis_comment *vc, char *tag, int count){
  110211. long i;
  110212. int found = 0;
  110213. int taglen = strlen(tag)+1; /* +1 for the = we append */
  110214. char *fulltag = (char*)alloca(taglen+ 1);
  110215. strcpy(fulltag, tag);
  110216. strcat(fulltag, "=");
  110217. for(i=0;i<vc->comments;i++){
  110218. if(!tagcompare(vc->user_comments[i], fulltag, taglen)){
  110219. if(count == found)
  110220. /* We return a pointer to the data, not a copy */
  110221. return vc->user_comments[i] + taglen;
  110222. else
  110223. found++;
  110224. }
  110225. }
  110226. return NULL; /* didn't find anything */
  110227. }
  110228. int vorbis_comment_query_count(vorbis_comment *vc, char *tag){
  110229. int i,count=0;
  110230. int taglen = strlen(tag)+1; /* +1 for the = we append */
  110231. char *fulltag = (char*)alloca(taglen+1);
  110232. strcpy(fulltag,tag);
  110233. strcat(fulltag, "=");
  110234. for(i=0;i<vc->comments;i++){
  110235. if(!tagcompare(vc->user_comments[i], fulltag, taglen))
  110236. count++;
  110237. }
  110238. return count;
  110239. }
  110240. void vorbis_comment_clear(vorbis_comment *vc){
  110241. if(vc){
  110242. long i;
  110243. for(i=0;i<vc->comments;i++)
  110244. if(vc->user_comments[i])_ogg_free(vc->user_comments[i]);
  110245. if(vc->user_comments)_ogg_free(vc->user_comments);
  110246. if(vc->comment_lengths)_ogg_free(vc->comment_lengths);
  110247. if(vc->vendor)_ogg_free(vc->vendor);
  110248. }
  110249. memset(vc,0,sizeof(*vc));
  110250. }
  110251. /* blocksize 0 is guaranteed to be short, 1 is guarantted to be long.
  110252. They may be equal, but short will never ge greater than long */
  110253. int vorbis_info_blocksize(vorbis_info *vi,int zo){
  110254. codec_setup_info *ci = (codec_setup_info*)vi->codec_setup;
  110255. return ci ? ci->blocksizes[zo] : -1;
  110256. }
  110257. /* used by synthesis, which has a full, alloced vi */
  110258. void vorbis_info_init(vorbis_info *vi){
  110259. memset(vi,0,sizeof(*vi));
  110260. vi->codec_setup=_ogg_calloc(1,sizeof(codec_setup_info));
  110261. }
  110262. void vorbis_info_clear(vorbis_info *vi){
  110263. codec_setup_info *ci=(codec_setup_info*)vi->codec_setup;
  110264. int i;
  110265. if(ci){
  110266. for(i=0;i<ci->modes;i++)
  110267. if(ci->mode_param[i])_ogg_free(ci->mode_param[i]);
  110268. for(i=0;i<ci->maps;i++) /* unpack does the range checking */
  110269. _mapping_P[ci->map_type[i]]->free_info(ci->map_param[i]);
  110270. for(i=0;i<ci->floors;i++) /* unpack does the range checking */
  110271. _floor_P[ci->floor_type[i]]->free_info(ci->floor_param[i]);
  110272. for(i=0;i<ci->residues;i++) /* unpack does the range checking */
  110273. _residue_P[ci->residue_type[i]]->free_info(ci->residue_param[i]);
  110274. for(i=0;i<ci->books;i++){
  110275. if(ci->book_param[i]){
  110276. /* knows if the book was not alloced */
  110277. vorbis_staticbook_destroy(ci->book_param[i]);
  110278. }
  110279. if(ci->fullbooks)
  110280. vorbis_book_clear(ci->fullbooks+i);
  110281. }
  110282. if(ci->fullbooks)
  110283. _ogg_free(ci->fullbooks);
  110284. for(i=0;i<ci->psys;i++)
  110285. _vi_psy_free(ci->psy_param[i]);
  110286. _ogg_free(ci);
  110287. }
  110288. memset(vi,0,sizeof(*vi));
  110289. }
  110290. /* Header packing/unpacking ********************************************/
  110291. static int _vorbis_unpack_info(vorbis_info *vi,oggpack_buffer *opb){
  110292. codec_setup_info *ci=(codec_setup_info*)vi->codec_setup;
  110293. if(!ci)return(OV_EFAULT);
  110294. vi->version=oggpack_read(opb,32);
  110295. if(vi->version!=0)return(OV_EVERSION);
  110296. vi->channels=oggpack_read(opb,8);
  110297. vi->rate=oggpack_read(opb,32);
  110298. vi->bitrate_upper=oggpack_read(opb,32);
  110299. vi->bitrate_nominal=oggpack_read(opb,32);
  110300. vi->bitrate_lower=oggpack_read(opb,32);
  110301. ci->blocksizes[0]=1<<oggpack_read(opb,4);
  110302. ci->blocksizes[1]=1<<oggpack_read(opb,4);
  110303. if(vi->rate<1)goto err_out;
  110304. if(vi->channels<1)goto err_out;
  110305. if(ci->blocksizes[0]<8)goto err_out;
  110306. if(ci->blocksizes[1]<ci->blocksizes[0])goto err_out;
  110307. if(oggpack_read(opb,1)!=1)goto err_out; /* EOP check */
  110308. return(0);
  110309. err_out:
  110310. vorbis_info_clear(vi);
  110311. return(OV_EBADHEADER);
  110312. }
  110313. static int _vorbis_unpack_comment(vorbis_comment *vc,oggpack_buffer *opb){
  110314. int i;
  110315. int vendorlen=oggpack_read(opb,32);
  110316. if(vendorlen<0)goto err_out;
  110317. vc->vendor=(char*)_ogg_calloc(vendorlen+1,1);
  110318. _v_readstring(opb,vc->vendor,vendorlen);
  110319. vc->comments=oggpack_read(opb,32);
  110320. if(vc->comments<0)goto err_out;
  110321. vc->user_comments=(char**)_ogg_calloc(vc->comments+1,sizeof(*vc->user_comments));
  110322. vc->comment_lengths=(int*)_ogg_calloc(vc->comments+1, sizeof(*vc->comment_lengths));
  110323. for(i=0;i<vc->comments;i++){
  110324. int len=oggpack_read(opb,32);
  110325. if(len<0)goto err_out;
  110326. vc->comment_lengths[i]=len;
  110327. vc->user_comments[i]=(char*)_ogg_calloc(len+1,1);
  110328. _v_readstring(opb,vc->user_comments[i],len);
  110329. }
  110330. if(oggpack_read(opb,1)!=1)goto err_out; /* EOP check */
  110331. return(0);
  110332. err_out:
  110333. vorbis_comment_clear(vc);
  110334. return(OV_EBADHEADER);
  110335. }
  110336. /* all of the real encoding details are here. The modes, books,
  110337. everything */
  110338. static int _vorbis_unpack_books(vorbis_info *vi,oggpack_buffer *opb){
  110339. codec_setup_info *ci=(codec_setup_info*)vi->codec_setup;
  110340. int i;
  110341. if(!ci)return(OV_EFAULT);
  110342. /* codebooks */
  110343. ci->books=oggpack_read(opb,8)+1;
  110344. /*ci->book_param=_ogg_calloc(ci->books,sizeof(*ci->book_param));*/
  110345. for(i=0;i<ci->books;i++){
  110346. ci->book_param[i]=(static_codebook*)_ogg_calloc(1,sizeof(*ci->book_param[i]));
  110347. if(vorbis_staticbook_unpack(opb,ci->book_param[i]))goto err_out;
  110348. }
  110349. /* time backend settings; hooks are unused */
  110350. {
  110351. int times=oggpack_read(opb,6)+1;
  110352. for(i=0;i<times;i++){
  110353. int test=oggpack_read(opb,16);
  110354. if(test<0 || test>=VI_TIMEB)goto err_out;
  110355. }
  110356. }
  110357. /* floor backend settings */
  110358. ci->floors=oggpack_read(opb,6)+1;
  110359. /*ci->floor_type=_ogg_malloc(ci->floors*sizeof(*ci->floor_type));*/
  110360. /*ci->floor_param=_ogg_calloc(ci->floors,sizeof(void *));*/
  110361. for(i=0;i<ci->floors;i++){
  110362. ci->floor_type[i]=oggpack_read(opb,16);
  110363. if(ci->floor_type[i]<0 || ci->floor_type[i]>=VI_FLOORB)goto err_out;
  110364. ci->floor_param[i]=_floor_P[ci->floor_type[i]]->unpack(vi,opb);
  110365. if(!ci->floor_param[i])goto err_out;
  110366. }
  110367. /* residue backend settings */
  110368. ci->residues=oggpack_read(opb,6)+1;
  110369. /*ci->residue_type=_ogg_malloc(ci->residues*sizeof(*ci->residue_type));*/
  110370. /*ci->residue_param=_ogg_calloc(ci->residues,sizeof(void *));*/
  110371. for(i=0;i<ci->residues;i++){
  110372. ci->residue_type[i]=oggpack_read(opb,16);
  110373. if(ci->residue_type[i]<0 || ci->residue_type[i]>=VI_RESB)goto err_out;
  110374. ci->residue_param[i]=_residue_P[ci->residue_type[i]]->unpack(vi,opb);
  110375. if(!ci->residue_param[i])goto err_out;
  110376. }
  110377. /* map backend settings */
  110378. ci->maps=oggpack_read(opb,6)+1;
  110379. /*ci->map_type=_ogg_malloc(ci->maps*sizeof(*ci->map_type));*/
  110380. /*ci->map_param=_ogg_calloc(ci->maps,sizeof(void *));*/
  110381. for(i=0;i<ci->maps;i++){
  110382. ci->map_type[i]=oggpack_read(opb,16);
  110383. if(ci->map_type[i]<0 || ci->map_type[i]>=VI_MAPB)goto err_out;
  110384. ci->map_param[i]=_mapping_P[ci->map_type[i]]->unpack(vi,opb);
  110385. if(!ci->map_param[i])goto err_out;
  110386. }
  110387. /* mode settings */
  110388. ci->modes=oggpack_read(opb,6)+1;
  110389. /*vi->mode_param=_ogg_calloc(vi->modes,sizeof(void *));*/
  110390. for(i=0;i<ci->modes;i++){
  110391. ci->mode_param[i]=(vorbis_info_mode*)_ogg_calloc(1,sizeof(*ci->mode_param[i]));
  110392. ci->mode_param[i]->blockflag=oggpack_read(opb,1);
  110393. ci->mode_param[i]->windowtype=oggpack_read(opb,16);
  110394. ci->mode_param[i]->transformtype=oggpack_read(opb,16);
  110395. ci->mode_param[i]->mapping=oggpack_read(opb,8);
  110396. if(ci->mode_param[i]->windowtype>=VI_WINDOWB)goto err_out;
  110397. if(ci->mode_param[i]->transformtype>=VI_WINDOWB)goto err_out;
  110398. if(ci->mode_param[i]->mapping>=ci->maps)goto err_out;
  110399. }
  110400. if(oggpack_read(opb,1)!=1)goto err_out; /* top level EOP check */
  110401. return(0);
  110402. err_out:
  110403. vorbis_info_clear(vi);
  110404. return(OV_EBADHEADER);
  110405. }
  110406. /* The Vorbis header is in three packets; the initial small packet in
  110407. the first page that identifies basic parameters, a second packet
  110408. with bitstream comments and a third packet that holds the
  110409. codebook. */
  110410. int vorbis_synthesis_headerin(vorbis_info *vi,vorbis_comment *vc,ogg_packet *op){
  110411. oggpack_buffer opb;
  110412. if(op){
  110413. oggpack_readinit(&opb,op->packet,op->bytes);
  110414. /* Which of the three types of header is this? */
  110415. /* Also verify header-ness, vorbis */
  110416. {
  110417. char buffer[6];
  110418. int packtype=oggpack_read(&opb,8);
  110419. memset(buffer,0,6);
  110420. _v_readstring(&opb,buffer,6);
  110421. if(memcmp(buffer,"vorbis",6)){
  110422. /* not a vorbis header */
  110423. return(OV_ENOTVORBIS);
  110424. }
  110425. switch(packtype){
  110426. case 0x01: /* least significant *bit* is read first */
  110427. if(!op->b_o_s){
  110428. /* Not the initial packet */
  110429. return(OV_EBADHEADER);
  110430. }
  110431. if(vi->rate!=0){
  110432. /* previously initialized info header */
  110433. return(OV_EBADHEADER);
  110434. }
  110435. return(_vorbis_unpack_info(vi,&opb));
  110436. case 0x03: /* least significant *bit* is read first */
  110437. if(vi->rate==0){
  110438. /* um... we didn't get the initial header */
  110439. return(OV_EBADHEADER);
  110440. }
  110441. return(_vorbis_unpack_comment(vc,&opb));
  110442. case 0x05: /* least significant *bit* is read first */
  110443. if(vi->rate==0 || vc->vendor==NULL){
  110444. /* um... we didn;t get the initial header or comments yet */
  110445. return(OV_EBADHEADER);
  110446. }
  110447. return(_vorbis_unpack_books(vi,&opb));
  110448. default:
  110449. /* Not a valid vorbis header type */
  110450. return(OV_EBADHEADER);
  110451. break;
  110452. }
  110453. }
  110454. }
  110455. return(OV_EBADHEADER);
  110456. }
  110457. /* pack side **********************************************************/
  110458. static int _vorbis_pack_info(oggpack_buffer *opb,vorbis_info *vi){
  110459. codec_setup_info *ci=(codec_setup_info*)vi->codec_setup;
  110460. if(!ci)return(OV_EFAULT);
  110461. /* preamble */
  110462. oggpack_write(opb,0x01,8);
  110463. _v_writestring(opb,"vorbis", 6);
  110464. /* basic information about the stream */
  110465. oggpack_write(opb,0x00,32);
  110466. oggpack_write(opb,vi->channels,8);
  110467. oggpack_write(opb,vi->rate,32);
  110468. oggpack_write(opb,vi->bitrate_upper,32);
  110469. oggpack_write(opb,vi->bitrate_nominal,32);
  110470. oggpack_write(opb,vi->bitrate_lower,32);
  110471. oggpack_write(opb,ilog2(ci->blocksizes[0]),4);
  110472. oggpack_write(opb,ilog2(ci->blocksizes[1]),4);
  110473. oggpack_write(opb,1,1);
  110474. return(0);
  110475. }
  110476. static int _vorbis_pack_comment(oggpack_buffer *opb,vorbis_comment *vc){
  110477. char temp[]="Xiph.Org libVorbis I 20050304";
  110478. int bytes = strlen(temp);
  110479. /* preamble */
  110480. oggpack_write(opb,0x03,8);
  110481. _v_writestring(opb,"vorbis", 6);
  110482. /* vendor */
  110483. oggpack_write(opb,bytes,32);
  110484. _v_writestring(opb,temp, bytes);
  110485. /* comments */
  110486. oggpack_write(opb,vc->comments,32);
  110487. if(vc->comments){
  110488. int i;
  110489. for(i=0;i<vc->comments;i++){
  110490. if(vc->user_comments[i]){
  110491. oggpack_write(opb,vc->comment_lengths[i],32);
  110492. _v_writestring(opb,vc->user_comments[i], vc->comment_lengths[i]);
  110493. }else{
  110494. oggpack_write(opb,0,32);
  110495. }
  110496. }
  110497. }
  110498. oggpack_write(opb,1,1);
  110499. return(0);
  110500. }
  110501. static int _vorbis_pack_books(oggpack_buffer *opb,vorbis_info *vi){
  110502. codec_setup_info *ci=(codec_setup_info*)vi->codec_setup;
  110503. int i;
  110504. if(!ci)return(OV_EFAULT);
  110505. oggpack_write(opb,0x05,8);
  110506. _v_writestring(opb,"vorbis", 6);
  110507. /* books */
  110508. oggpack_write(opb,ci->books-1,8);
  110509. for(i=0;i<ci->books;i++)
  110510. if(vorbis_staticbook_pack(ci->book_param[i],opb))goto err_out;
  110511. /* times; hook placeholders */
  110512. oggpack_write(opb,0,6);
  110513. oggpack_write(opb,0,16);
  110514. /* floors */
  110515. oggpack_write(opb,ci->floors-1,6);
  110516. for(i=0;i<ci->floors;i++){
  110517. oggpack_write(opb,ci->floor_type[i],16);
  110518. if(_floor_P[ci->floor_type[i]]->pack)
  110519. _floor_P[ci->floor_type[i]]->pack(ci->floor_param[i],opb);
  110520. else
  110521. goto err_out;
  110522. }
  110523. /* residues */
  110524. oggpack_write(opb,ci->residues-1,6);
  110525. for(i=0;i<ci->residues;i++){
  110526. oggpack_write(opb,ci->residue_type[i],16);
  110527. _residue_P[ci->residue_type[i]]->pack(ci->residue_param[i],opb);
  110528. }
  110529. /* maps */
  110530. oggpack_write(opb,ci->maps-1,6);
  110531. for(i=0;i<ci->maps;i++){
  110532. oggpack_write(opb,ci->map_type[i],16);
  110533. _mapping_P[ci->map_type[i]]->pack(vi,ci->map_param[i],opb);
  110534. }
  110535. /* modes */
  110536. oggpack_write(opb,ci->modes-1,6);
  110537. for(i=0;i<ci->modes;i++){
  110538. oggpack_write(opb,ci->mode_param[i]->blockflag,1);
  110539. oggpack_write(opb,ci->mode_param[i]->windowtype,16);
  110540. oggpack_write(opb,ci->mode_param[i]->transformtype,16);
  110541. oggpack_write(opb,ci->mode_param[i]->mapping,8);
  110542. }
  110543. oggpack_write(opb,1,1);
  110544. return(0);
  110545. err_out:
  110546. return(-1);
  110547. }
  110548. int vorbis_commentheader_out(vorbis_comment *vc,
  110549. ogg_packet *op){
  110550. oggpack_buffer opb;
  110551. oggpack_writeinit(&opb);
  110552. if(_vorbis_pack_comment(&opb,vc)) return OV_EIMPL;
  110553. op->packet = (unsigned char*) _ogg_malloc(oggpack_bytes(&opb));
  110554. memcpy(op->packet, opb.buffer, oggpack_bytes(&opb));
  110555. op->bytes=oggpack_bytes(&opb);
  110556. op->b_o_s=0;
  110557. op->e_o_s=0;
  110558. op->granulepos=0;
  110559. op->packetno=1;
  110560. return 0;
  110561. }
  110562. int vorbis_analysis_headerout(vorbis_dsp_state *v,
  110563. vorbis_comment *vc,
  110564. ogg_packet *op,
  110565. ogg_packet *op_comm,
  110566. ogg_packet *op_code){
  110567. int ret=OV_EIMPL;
  110568. vorbis_info *vi=v->vi;
  110569. oggpack_buffer opb;
  110570. private_state *b=(private_state*)v->backend_state;
  110571. if(!b){
  110572. ret=OV_EFAULT;
  110573. goto err_out;
  110574. }
  110575. /* first header packet **********************************************/
  110576. oggpack_writeinit(&opb);
  110577. if(_vorbis_pack_info(&opb,vi))goto err_out;
  110578. /* build the packet */
  110579. if(b->header)_ogg_free(b->header);
  110580. b->header=(unsigned char*) _ogg_malloc(oggpack_bytes(&opb));
  110581. memcpy(b->header,opb.buffer,oggpack_bytes(&opb));
  110582. op->packet=b->header;
  110583. op->bytes=oggpack_bytes(&opb);
  110584. op->b_o_s=1;
  110585. op->e_o_s=0;
  110586. op->granulepos=0;
  110587. op->packetno=0;
  110588. /* second header packet (comments) **********************************/
  110589. oggpack_reset(&opb);
  110590. if(_vorbis_pack_comment(&opb,vc))goto err_out;
  110591. if(b->header1)_ogg_free(b->header1);
  110592. b->header1=(unsigned char*) _ogg_malloc(oggpack_bytes(&opb));
  110593. memcpy(b->header1,opb.buffer,oggpack_bytes(&opb));
  110594. op_comm->packet=b->header1;
  110595. op_comm->bytes=oggpack_bytes(&opb);
  110596. op_comm->b_o_s=0;
  110597. op_comm->e_o_s=0;
  110598. op_comm->granulepos=0;
  110599. op_comm->packetno=1;
  110600. /* third header packet (modes/codebooks) ****************************/
  110601. oggpack_reset(&opb);
  110602. if(_vorbis_pack_books(&opb,vi))goto err_out;
  110603. if(b->header2)_ogg_free(b->header2);
  110604. b->header2=(unsigned char*) _ogg_malloc(oggpack_bytes(&opb));
  110605. memcpy(b->header2,opb.buffer,oggpack_bytes(&opb));
  110606. op_code->packet=b->header2;
  110607. op_code->bytes=oggpack_bytes(&opb);
  110608. op_code->b_o_s=0;
  110609. op_code->e_o_s=0;
  110610. op_code->granulepos=0;
  110611. op_code->packetno=2;
  110612. oggpack_writeclear(&opb);
  110613. return(0);
  110614. err_out:
  110615. oggpack_writeclear(&opb);
  110616. memset(op,0,sizeof(*op));
  110617. memset(op_comm,0,sizeof(*op_comm));
  110618. memset(op_code,0,sizeof(*op_code));
  110619. if(b->header)_ogg_free(b->header);
  110620. if(b->header1)_ogg_free(b->header1);
  110621. if(b->header2)_ogg_free(b->header2);
  110622. b->header=NULL;
  110623. b->header1=NULL;
  110624. b->header2=NULL;
  110625. return(ret);
  110626. }
  110627. double vorbis_granule_time(vorbis_dsp_state *v,ogg_int64_t granulepos){
  110628. if(granulepos>=0)
  110629. return((double)granulepos/v->vi->rate);
  110630. return(-1);
  110631. }
  110632. #endif
  110633. /*** End of inlined file: info.c ***/
  110634. /*** Start of inlined file: lpc.c ***/
  110635. /* Some of these routines (autocorrelator, LPC coefficient estimator)
  110636. are derived from code written by Jutta Degener and Carsten Bormann;
  110637. thus we include their copyright below. The entirety of this file
  110638. is freely redistributable on the condition that both of these
  110639. copyright notices are preserved without modification. */
  110640. /* Preserved Copyright: *********************************************/
  110641. /* Copyright 1992, 1993, 1994 by Jutta Degener and Carsten Bormann,
  110642. Technische Universita"t Berlin
  110643. Any use of this software is permitted provided that this notice is not
  110644. removed and that neither the authors nor the Technische Universita"t
  110645. Berlin are deemed to have made any representations as to the
  110646. suitability of this software for any purpose nor are held responsible
  110647. for any defects of this software. THERE IS ABSOLUTELY NO WARRANTY FOR
  110648. THIS SOFTWARE.
  110649. As a matter of courtesy, the authors request to be informed about uses
  110650. this software has found, about bugs in this software, and about any
  110651. improvements that may be of general interest.
  110652. Berlin, 28.11.1994
  110653. Jutta Degener
  110654. Carsten Bormann
  110655. *********************************************************************/
  110656. /*** Start of inlined file: juce_OggVorbisHeader.h ***/
  110657. // This file is included at the start of each Ogg-Vorbis .c file, just to do a few housekeeping
  110658. // tasks..
  110659. #if JUCE_MSVC
  110660. #pragma warning (disable: 4267 4127 4244 4996 4100 4701 4702 4013 4133 4206 4305 4189 4706)
  110661. #endif
  110662. /*** End of inlined file: juce_OggVorbisHeader.h ***/
  110663. #if JUCE_USE_OGGVORBIS
  110664. #include <stdlib.h>
  110665. #include <string.h>
  110666. #include <math.h>
  110667. /* Autocorrelation LPC coeff generation algorithm invented by
  110668. N. Levinson in 1947, modified by J. Durbin in 1959. */
  110669. /* Input : n elements of time doamin data
  110670. Output: m lpc coefficients, excitation energy */
  110671. float vorbis_lpc_from_data(float *data,float *lpci,int n,int m){
  110672. double *aut=(double*)alloca(sizeof(*aut)*(m+1));
  110673. double *lpc=(double*)alloca(sizeof(*lpc)*(m));
  110674. double error;
  110675. int i,j;
  110676. /* autocorrelation, p+1 lag coefficients */
  110677. j=m+1;
  110678. while(j--){
  110679. double d=0; /* double needed for accumulator depth */
  110680. for(i=j;i<n;i++)d+=(double)data[i]*data[i-j];
  110681. aut[j]=d;
  110682. }
  110683. /* Generate lpc coefficients from autocorr values */
  110684. error=aut[0];
  110685. for(i=0;i<m;i++){
  110686. double r= -aut[i+1];
  110687. if(error==0){
  110688. memset(lpci,0,m*sizeof(*lpci));
  110689. return 0;
  110690. }
  110691. /* Sum up this iteration's reflection coefficient; note that in
  110692. Vorbis we don't save it. If anyone wants to recycle this code
  110693. and needs reflection coefficients, save the results of 'r' from
  110694. each iteration. */
  110695. for(j=0;j<i;j++)r-=lpc[j]*aut[i-j];
  110696. r/=error;
  110697. /* Update LPC coefficients and total error */
  110698. lpc[i]=r;
  110699. for(j=0;j<i/2;j++){
  110700. double tmp=lpc[j];
  110701. lpc[j]+=r*lpc[i-1-j];
  110702. lpc[i-1-j]+=r*tmp;
  110703. }
  110704. if(i%2)lpc[j]+=lpc[j]*r;
  110705. error*=1.f-r*r;
  110706. }
  110707. for(j=0;j<m;j++)lpci[j]=(float)lpc[j];
  110708. /* we need the error value to know how big an impulse to hit the
  110709. filter with later */
  110710. return error;
  110711. }
  110712. void vorbis_lpc_predict(float *coeff,float *prime,int m,
  110713. float *data,long n){
  110714. /* in: coeff[0...m-1] LPC coefficients
  110715. prime[0...m-1] initial values (allocated size of n+m-1)
  110716. out: data[0...n-1] data samples */
  110717. long i,j,o,p;
  110718. float y;
  110719. float *work=(float*)alloca(sizeof(*work)*(m+n));
  110720. if(!prime)
  110721. for(i=0;i<m;i++)
  110722. work[i]=0.f;
  110723. else
  110724. for(i=0;i<m;i++)
  110725. work[i]=prime[i];
  110726. for(i=0;i<n;i++){
  110727. y=0;
  110728. o=i;
  110729. p=m;
  110730. for(j=0;j<m;j++)
  110731. y-=work[o++]*coeff[--p];
  110732. data[i]=work[o]=y;
  110733. }
  110734. }
  110735. #endif
  110736. /*** End of inlined file: lpc.c ***/
  110737. /*** Start of inlined file: lsp.c ***/
  110738. /* Note that the lpc-lsp conversion finds the roots of polynomial with
  110739. an iterative root polisher (CACM algorithm 283). It *is* possible
  110740. to confuse this algorithm into not converging; that should only
  110741. happen with absurdly closely spaced roots (very sharp peaks in the
  110742. LPC f response) which in turn should be impossible in our use of
  110743. the code. If this *does* happen anyway, it's a bug in the floor
  110744. finder; find the cause of the confusion (probably a single bin
  110745. spike or accidental near-float-limit resolution problems) and
  110746. correct it. */
  110747. /*** Start of inlined file: juce_OggVorbisHeader.h ***/
  110748. // This file is included at the start of each Ogg-Vorbis .c file, just to do a few housekeeping
  110749. // tasks..
  110750. #if JUCE_MSVC
  110751. #pragma warning (disable: 4267 4127 4244 4996 4100 4701 4702 4013 4133 4206 4305 4189 4706)
  110752. #endif
  110753. /*** End of inlined file: juce_OggVorbisHeader.h ***/
  110754. #if JUCE_USE_OGGVORBIS
  110755. #include <math.h>
  110756. #include <string.h>
  110757. #include <stdlib.h>
  110758. /*** Start of inlined file: lookup.h ***/
  110759. #ifndef _V_LOOKUP_H_
  110760. #ifdef FLOAT_LOOKUP
  110761. extern float vorbis_coslook(float a);
  110762. extern float vorbis_invsqlook(float a);
  110763. extern float vorbis_invsq2explook(int a);
  110764. extern float vorbis_fromdBlook(float a);
  110765. #endif
  110766. #ifdef INT_LOOKUP
  110767. extern long vorbis_invsqlook_i(long a,long e);
  110768. extern long vorbis_coslook_i(long a);
  110769. extern float vorbis_fromdBlook_i(long a);
  110770. #endif
  110771. #endif
  110772. /*** End of inlined file: lookup.h ***/
  110773. /* three possible LSP to f curve functions; the exact computation
  110774. (float), a lookup based float implementation, and an integer
  110775. implementation. The float lookup is likely the optimal choice on
  110776. any machine with an FPU. The integer implementation is *not* fixed
  110777. point (due to the need for a large dynamic range and thus a
  110778. seperately tracked exponent) and thus much more complex than the
  110779. relatively simple float implementations. It's mostly for future
  110780. work on a fully fixed point implementation for processors like the
  110781. ARM family. */
  110782. /* undefine both for the 'old' but more precise implementation */
  110783. #define FLOAT_LOOKUP
  110784. #undef INT_LOOKUP
  110785. #ifdef FLOAT_LOOKUP
  110786. /*** Start of inlined file: lookup.c ***/
  110787. /*** Start of inlined file: juce_OggVorbisHeader.h ***/
  110788. // This file is included at the start of each Ogg-Vorbis .c file, just to do a few housekeeping
  110789. // tasks..
  110790. #if JUCE_MSVC
  110791. #pragma warning (disable: 4267 4127 4244 4996 4100 4701 4702 4013 4133 4206 4305 4189 4706)
  110792. #endif
  110793. /*** End of inlined file: juce_OggVorbisHeader.h ***/
  110794. #if JUCE_USE_OGGVORBIS
  110795. #include <math.h>
  110796. /*** Start of inlined file: lookup.h ***/
  110797. #ifndef _V_LOOKUP_H_
  110798. #ifdef FLOAT_LOOKUP
  110799. extern float vorbis_coslook(float a);
  110800. extern float vorbis_invsqlook(float a);
  110801. extern float vorbis_invsq2explook(int a);
  110802. extern float vorbis_fromdBlook(float a);
  110803. #endif
  110804. #ifdef INT_LOOKUP
  110805. extern long vorbis_invsqlook_i(long a,long e);
  110806. extern long vorbis_coslook_i(long a);
  110807. extern float vorbis_fromdBlook_i(long a);
  110808. #endif
  110809. #endif
  110810. /*** End of inlined file: lookup.h ***/
  110811. /*** Start of inlined file: lookup_data.h ***/
  110812. #ifndef _V_LOOKUP_DATA_H_
  110813. #ifdef FLOAT_LOOKUP
  110814. #define COS_LOOKUP_SZ 128
  110815. static float COS_LOOKUP[COS_LOOKUP_SZ+1]={
  110816. +1.0000000000000f,+0.9996988186962f,+0.9987954562052f,+0.9972904566787f,
  110817. +0.9951847266722f,+0.9924795345987f,+0.9891765099648f,+0.9852776423889f,
  110818. +0.9807852804032f,+0.9757021300385f,+0.9700312531945f,+0.9637760657954f,
  110819. +0.9569403357322f,+0.9495281805930f,+0.9415440651830f,+0.9329927988347f,
  110820. +0.9238795325113f,+0.9142097557035f,+0.9039892931234f,+0.8932243011955f,
  110821. +0.8819212643484f,+0.8700869911087f,+0.8577286100003f,+0.8448535652497f,
  110822. +0.8314696123025f,+0.8175848131516f,+0.8032075314806f,+0.7883464276266f,
  110823. +0.7730104533627f,+0.7572088465065f,+0.7409511253550f,+0.7242470829515f,
  110824. +0.7071067811865f,+0.6895405447371f,+0.6715589548470f,+0.6531728429538f,
  110825. +0.6343932841636f,+0.6152315905806f,+0.5956993044924f,+0.5758081914178f,
  110826. +0.5555702330196f,+0.5349976198871f,+0.5141027441932f,+0.4928981922298f,
  110827. +0.4713967368260f,+0.4496113296546f,+0.4275550934303f,+0.4052413140050f,
  110828. +0.3826834323651f,+0.3598950365350f,+0.3368898533922f,+0.3136817403989f,
  110829. +0.2902846772545f,+0.2667127574749f,+0.2429801799033f,+0.2191012401569f,
  110830. +0.1950903220161f,+0.1709618887603f,+0.1467304744554f,+0.1224106751992f,
  110831. +0.0980171403296f,+0.0735645635997f,+0.0490676743274f,+0.0245412285229f,
  110832. +0.0000000000000f,-0.0245412285229f,-0.0490676743274f,-0.0735645635997f,
  110833. -0.0980171403296f,-0.1224106751992f,-0.1467304744554f,-0.1709618887603f,
  110834. -0.1950903220161f,-0.2191012401569f,-0.2429801799033f,-0.2667127574749f,
  110835. -0.2902846772545f,-0.3136817403989f,-0.3368898533922f,-0.3598950365350f,
  110836. -0.3826834323651f,-0.4052413140050f,-0.4275550934303f,-0.4496113296546f,
  110837. -0.4713967368260f,-0.4928981922298f,-0.5141027441932f,-0.5349976198871f,
  110838. -0.5555702330196f,-0.5758081914178f,-0.5956993044924f,-0.6152315905806f,
  110839. -0.6343932841636f,-0.6531728429538f,-0.6715589548470f,-0.6895405447371f,
  110840. -0.7071067811865f,-0.7242470829515f,-0.7409511253550f,-0.7572088465065f,
  110841. -0.7730104533627f,-0.7883464276266f,-0.8032075314806f,-0.8175848131516f,
  110842. -0.8314696123025f,-0.8448535652497f,-0.8577286100003f,-0.8700869911087f,
  110843. -0.8819212643484f,-0.8932243011955f,-0.9039892931234f,-0.9142097557035f,
  110844. -0.9238795325113f,-0.9329927988347f,-0.9415440651830f,-0.9495281805930f,
  110845. -0.9569403357322f,-0.9637760657954f,-0.9700312531945f,-0.9757021300385f,
  110846. -0.9807852804032f,-0.9852776423889f,-0.9891765099648f,-0.9924795345987f,
  110847. -0.9951847266722f,-0.9972904566787f,-0.9987954562052f,-0.9996988186962f,
  110848. -1.0000000000000f,
  110849. };
  110850. #define INVSQ_LOOKUP_SZ 32
  110851. static float INVSQ_LOOKUP[INVSQ_LOOKUP_SZ+1]={
  110852. 1.414213562373f,1.392621247646f,1.371988681140f,1.352246807566f,
  110853. 1.333333333333f,1.315191898443f,1.297771369046f,1.281025230441f,
  110854. 1.264911064067f,1.249390095109f,1.234426799697f,1.219988562661f,
  110855. 1.206045378311f,1.192569588000f,1.179535649239f,1.166919931983f,
  110856. 1.154700538379f,1.142857142857f,1.131370849898f,1.120224067222f,
  110857. 1.109400392450f,1.098884511590f,1.088662107904f,1.078719779941f,
  110858. 1.069044967650f,1.059625885652f,1.050451462878f,1.041511287847f,
  110859. 1.032795558989f,1.024295039463f,1.016001016002f,1.007905261358f,
  110860. 1.000000000000f,
  110861. };
  110862. #define INVSQ2EXP_LOOKUP_MIN (-32)
  110863. #define INVSQ2EXP_LOOKUP_MAX 32
  110864. static float INVSQ2EXP_LOOKUP[INVSQ2EXP_LOOKUP_MAX-\
  110865. INVSQ2EXP_LOOKUP_MIN+1]={
  110866. 65536.f, 46340.95001f, 32768.f, 23170.47501f,
  110867. 16384.f, 11585.2375f, 8192.f, 5792.618751f,
  110868. 4096.f, 2896.309376f, 2048.f, 1448.154688f,
  110869. 1024.f, 724.0773439f, 512.f, 362.038672f,
  110870. 256.f, 181.019336f, 128.f, 90.50966799f,
  110871. 64.f, 45.254834f, 32.f, 22.627417f,
  110872. 16.f, 11.3137085f, 8.f, 5.656854249f,
  110873. 4.f, 2.828427125f, 2.f, 1.414213562f,
  110874. 1.f, 0.7071067812f, 0.5f, 0.3535533906f,
  110875. 0.25f, 0.1767766953f, 0.125f, 0.08838834765f,
  110876. 0.0625f, 0.04419417382f, 0.03125f, 0.02209708691f,
  110877. 0.015625f, 0.01104854346f, 0.0078125f, 0.005524271728f,
  110878. 0.00390625f, 0.002762135864f, 0.001953125f, 0.001381067932f,
  110879. 0.0009765625f, 0.000690533966f, 0.00048828125f, 0.000345266983f,
  110880. 0.000244140625f,0.0001726334915f,0.0001220703125f,8.631674575e-05f,
  110881. 6.103515625e-05f,4.315837288e-05f,3.051757812e-05f,2.157918644e-05f,
  110882. 1.525878906e-05f,
  110883. };
  110884. #endif
  110885. #define FROMdB_LOOKUP_SZ 35
  110886. #define FROMdB2_LOOKUP_SZ 32
  110887. #define FROMdB_SHIFT 5
  110888. #define FROMdB2_SHIFT 3
  110889. #define FROMdB2_MASK 31
  110890. static float FROMdB_LOOKUP[FROMdB_LOOKUP_SZ]={
  110891. 1.f, 0.6309573445f, 0.3981071706f, 0.2511886432f,
  110892. 0.1584893192f, 0.1f, 0.06309573445f, 0.03981071706f,
  110893. 0.02511886432f, 0.01584893192f, 0.01f, 0.006309573445f,
  110894. 0.003981071706f, 0.002511886432f, 0.001584893192f, 0.001f,
  110895. 0.0006309573445f,0.0003981071706f,0.0002511886432f,0.0001584893192f,
  110896. 0.0001f,6.309573445e-05f,3.981071706e-05f,2.511886432e-05f,
  110897. 1.584893192e-05f, 1e-05f,6.309573445e-06f,3.981071706e-06f,
  110898. 2.511886432e-06f,1.584893192e-06f, 1e-06f,6.309573445e-07f,
  110899. 3.981071706e-07f,2.511886432e-07f,1.584893192e-07f,
  110900. };
  110901. static float FROMdB2_LOOKUP[FROMdB2_LOOKUP_SZ]={
  110902. 0.9928302478f, 0.9786445908f, 0.9646616199f, 0.9508784391f,
  110903. 0.9372921937f, 0.92390007f, 0.9106992942f, 0.8976871324f,
  110904. 0.8848608897f, 0.8722179097f, 0.8597555737f, 0.8474713009f,
  110905. 0.835362547f, 0.8234268041f, 0.8116616003f, 0.8000644989f,
  110906. 0.7886330981f, 0.7773650302f, 0.7662579617f, 0.755309592f,
  110907. 0.7445176537f, 0.7338799116f, 0.7233941627f, 0.7130582353f,
  110908. 0.7028699885f, 0.6928273125f, 0.6829281272f, 0.6731703824f,
  110909. 0.6635520573f, 0.6540711597f, 0.6447257262f, 0.6355138211f,
  110910. };
  110911. #ifdef INT_LOOKUP
  110912. #define INVSQ_LOOKUP_I_SHIFT 10
  110913. #define INVSQ_LOOKUP_I_MASK 1023
  110914. static long INVSQ_LOOKUP_I[64+1]={
  110915. 92682l, 91966l, 91267l, 90583l,
  110916. 89915l, 89261l, 88621l, 87995l,
  110917. 87381l, 86781l, 86192l, 85616l,
  110918. 85051l, 84497l, 83953l, 83420l,
  110919. 82897l, 82384l, 81880l, 81385l,
  110920. 80899l, 80422l, 79953l, 79492l,
  110921. 79039l, 78594l, 78156l, 77726l,
  110922. 77302l, 76885l, 76475l, 76072l,
  110923. 75674l, 75283l, 74898l, 74519l,
  110924. 74146l, 73778l, 73415l, 73058l,
  110925. 72706l, 72359l, 72016l, 71679l,
  110926. 71347l, 71019l, 70695l, 70376l,
  110927. 70061l, 69750l, 69444l, 69141l,
  110928. 68842l, 68548l, 68256l, 67969l,
  110929. 67685l, 67405l, 67128l, 66855l,
  110930. 66585l, 66318l, 66054l, 65794l,
  110931. 65536l,
  110932. };
  110933. #define COS_LOOKUP_I_SHIFT 9
  110934. #define COS_LOOKUP_I_MASK 511
  110935. #define COS_LOOKUP_I_SZ 128
  110936. static long COS_LOOKUP_I[COS_LOOKUP_I_SZ+1]={
  110937. 16384l, 16379l, 16364l, 16340l,
  110938. 16305l, 16261l, 16207l, 16143l,
  110939. 16069l, 15986l, 15893l, 15791l,
  110940. 15679l, 15557l, 15426l, 15286l,
  110941. 15137l, 14978l, 14811l, 14635l,
  110942. 14449l, 14256l, 14053l, 13842l,
  110943. 13623l, 13395l, 13160l, 12916l,
  110944. 12665l, 12406l, 12140l, 11866l,
  110945. 11585l, 11297l, 11003l, 10702l,
  110946. 10394l, 10080l, 9760l, 9434l,
  110947. 9102l, 8765l, 8423l, 8076l,
  110948. 7723l, 7366l, 7005l, 6639l,
  110949. 6270l, 5897l, 5520l, 5139l,
  110950. 4756l, 4370l, 3981l, 3590l,
  110951. 3196l, 2801l, 2404l, 2006l,
  110952. 1606l, 1205l, 804l, 402l,
  110953. 0l, -401l, -803l, -1204l,
  110954. -1605l, -2005l, -2403l, -2800l,
  110955. -3195l, -3589l, -3980l, -4369l,
  110956. -4755l, -5138l, -5519l, -5896l,
  110957. -6269l, -6638l, -7004l, -7365l,
  110958. -7722l, -8075l, -8422l, -8764l,
  110959. -9101l, -9433l, -9759l, -10079l,
  110960. -10393l, -10701l, -11002l, -11296l,
  110961. -11584l, -11865l, -12139l, -12405l,
  110962. -12664l, -12915l, -13159l, -13394l,
  110963. -13622l, -13841l, -14052l, -14255l,
  110964. -14448l, -14634l, -14810l, -14977l,
  110965. -15136l, -15285l, -15425l, -15556l,
  110966. -15678l, -15790l, -15892l, -15985l,
  110967. -16068l, -16142l, -16206l, -16260l,
  110968. -16304l, -16339l, -16363l, -16378l,
  110969. -16383l,
  110970. };
  110971. #endif
  110972. #endif
  110973. /*** End of inlined file: lookup_data.h ***/
  110974. #ifdef FLOAT_LOOKUP
  110975. /* interpolated lookup based cos function, domain 0 to PI only */
  110976. float vorbis_coslook(float a){
  110977. double d=a*(.31830989*(float)COS_LOOKUP_SZ);
  110978. int i=vorbis_ftoi(d-.5);
  110979. return COS_LOOKUP[i]+ (d-i)*(COS_LOOKUP[i+1]-COS_LOOKUP[i]);
  110980. }
  110981. /* interpolated 1./sqrt(p) where .5 <= p < 1. */
  110982. float vorbis_invsqlook(float a){
  110983. double d=a*(2.f*(float)INVSQ_LOOKUP_SZ)-(float)INVSQ_LOOKUP_SZ;
  110984. int i=vorbis_ftoi(d-.5f);
  110985. return INVSQ_LOOKUP[i]+ (d-i)*(INVSQ_LOOKUP[i+1]-INVSQ_LOOKUP[i]);
  110986. }
  110987. /* interpolated 1./sqrt(p) where .5 <= p < 1. */
  110988. float vorbis_invsq2explook(int a){
  110989. return INVSQ2EXP_LOOKUP[a-INVSQ2EXP_LOOKUP_MIN];
  110990. }
  110991. #include <stdio.h>
  110992. /* interpolated lookup based fromdB function, domain -140dB to 0dB only */
  110993. float vorbis_fromdBlook(float a){
  110994. int i=vorbis_ftoi(a*((float)(-(1<<FROMdB2_SHIFT)))-.5f);
  110995. return (i<0)?1.f:
  110996. ((i>=(FROMdB_LOOKUP_SZ<<FROMdB_SHIFT))?0.f:
  110997. FROMdB_LOOKUP[i>>FROMdB_SHIFT]*FROMdB2_LOOKUP[i&FROMdB2_MASK]);
  110998. }
  110999. #endif
  111000. #ifdef INT_LOOKUP
  111001. /* interpolated 1./sqrt(p) where .5 <= a < 1. (.100000... to .111111...) in
  111002. 16.16 format
  111003. returns in m.8 format */
  111004. long vorbis_invsqlook_i(long a,long e){
  111005. long i=(a&0x7fff)>>(INVSQ_LOOKUP_I_SHIFT-1);
  111006. long d=(a&INVSQ_LOOKUP_I_MASK)<<(16-INVSQ_LOOKUP_I_SHIFT); /* 0.16 */
  111007. long val=INVSQ_LOOKUP_I[i]- /* 1.16 */
  111008. (((INVSQ_LOOKUP_I[i]-INVSQ_LOOKUP_I[i+1])* /* 0.16 */
  111009. d)>>16); /* result 1.16 */
  111010. e+=32;
  111011. if(e&1)val=(val*5792)>>13; /* multiply val by 1/sqrt(2) */
  111012. e=(e>>1)-8;
  111013. return(val>>e);
  111014. }
  111015. /* interpolated lookup based fromdB function, domain -140dB to 0dB only */
  111016. /* a is in n.12 format */
  111017. float vorbis_fromdBlook_i(long a){
  111018. int i=(-a)>>(12-FROMdB2_SHIFT);
  111019. return (i<0)?1.f:
  111020. ((i>=(FROMdB_LOOKUP_SZ<<FROMdB_SHIFT))?0.f:
  111021. FROMdB_LOOKUP[i>>FROMdB_SHIFT]*FROMdB2_LOOKUP[i&FROMdB2_MASK]);
  111022. }
  111023. /* interpolated lookup based cos function, domain 0 to PI only */
  111024. /* a is in 0.16 format, where 0==0, 2^^16-1==PI, return 0.14 */
  111025. long vorbis_coslook_i(long a){
  111026. int i=a>>COS_LOOKUP_I_SHIFT;
  111027. int d=a&COS_LOOKUP_I_MASK;
  111028. return COS_LOOKUP_I[i]- ((d*(COS_LOOKUP_I[i]-COS_LOOKUP_I[i+1]))>>
  111029. COS_LOOKUP_I_SHIFT);
  111030. }
  111031. #endif
  111032. #endif
  111033. /*** End of inlined file: lookup.c ***/
  111034. /* catch this in the build system; we #include for
  111035. compilers (like gcc) that can't inline across
  111036. modules */
  111037. /* side effect: changes *lsp to cosines of lsp */
  111038. void vorbis_lsp_to_curve(float *curve,int *map,int n,int ln,float *lsp,int m,
  111039. float amp,float ampoffset){
  111040. int i;
  111041. float wdel=M_PI/ln;
  111042. vorbis_fpu_control fpu;
  111043. (void) fpu; // to avoid an unused variable warning
  111044. vorbis_fpu_setround(&fpu);
  111045. for(i=0;i<m;i++)lsp[i]=vorbis_coslook(lsp[i]);
  111046. i=0;
  111047. while(i<n){
  111048. int k=map[i];
  111049. int qexp;
  111050. float p=.7071067812f;
  111051. float q=.7071067812f;
  111052. float w=vorbis_coslook(wdel*k);
  111053. float *ftmp=lsp;
  111054. int c=m>>1;
  111055. do{
  111056. q*=ftmp[0]-w;
  111057. p*=ftmp[1]-w;
  111058. ftmp+=2;
  111059. }while(--c);
  111060. if(m&1){
  111061. /* odd order filter; slightly assymetric */
  111062. /* the last coefficient */
  111063. q*=ftmp[0]-w;
  111064. q*=q;
  111065. p*=p*(1.f-w*w);
  111066. }else{
  111067. /* even order filter; still symmetric */
  111068. q*=q*(1.f+w);
  111069. p*=p*(1.f-w);
  111070. }
  111071. q=frexp(p+q,&qexp);
  111072. q=vorbis_fromdBlook(amp*
  111073. vorbis_invsqlook(q)*
  111074. vorbis_invsq2explook(qexp+m)-
  111075. ampoffset);
  111076. do{
  111077. curve[i++]*=q;
  111078. }while(map[i]==k);
  111079. }
  111080. vorbis_fpu_restore(fpu);
  111081. }
  111082. #else
  111083. #ifdef INT_LOOKUP
  111084. /*** Start of inlined file: lookup.c ***/
  111085. /*** Start of inlined file: juce_OggVorbisHeader.h ***/
  111086. // This file is included at the start of each Ogg-Vorbis .c file, just to do a few housekeeping
  111087. // tasks..
  111088. #if JUCE_MSVC
  111089. #pragma warning (disable: 4267 4127 4244 4996 4100 4701 4702 4013 4133 4206 4305 4189 4706)
  111090. #endif
  111091. /*** End of inlined file: juce_OggVorbisHeader.h ***/
  111092. #if JUCE_USE_OGGVORBIS
  111093. #include <math.h>
  111094. /*** Start of inlined file: lookup.h ***/
  111095. #ifndef _V_LOOKUP_H_
  111096. #ifdef FLOAT_LOOKUP
  111097. extern float vorbis_coslook(float a);
  111098. extern float vorbis_invsqlook(float a);
  111099. extern float vorbis_invsq2explook(int a);
  111100. extern float vorbis_fromdBlook(float a);
  111101. #endif
  111102. #ifdef INT_LOOKUP
  111103. extern long vorbis_invsqlook_i(long a,long e);
  111104. extern long vorbis_coslook_i(long a);
  111105. extern float vorbis_fromdBlook_i(long a);
  111106. #endif
  111107. #endif
  111108. /*** End of inlined file: lookup.h ***/
  111109. /*** Start of inlined file: lookup_data.h ***/
  111110. #ifndef _V_LOOKUP_DATA_H_
  111111. #ifdef FLOAT_LOOKUP
  111112. #define COS_LOOKUP_SZ 128
  111113. static float COS_LOOKUP[COS_LOOKUP_SZ+1]={
  111114. +1.0000000000000f,+0.9996988186962f,+0.9987954562052f,+0.9972904566787f,
  111115. +0.9951847266722f,+0.9924795345987f,+0.9891765099648f,+0.9852776423889f,
  111116. +0.9807852804032f,+0.9757021300385f,+0.9700312531945f,+0.9637760657954f,
  111117. +0.9569403357322f,+0.9495281805930f,+0.9415440651830f,+0.9329927988347f,
  111118. +0.9238795325113f,+0.9142097557035f,+0.9039892931234f,+0.8932243011955f,
  111119. +0.8819212643484f,+0.8700869911087f,+0.8577286100003f,+0.8448535652497f,
  111120. +0.8314696123025f,+0.8175848131516f,+0.8032075314806f,+0.7883464276266f,
  111121. +0.7730104533627f,+0.7572088465065f,+0.7409511253550f,+0.7242470829515f,
  111122. +0.7071067811865f,+0.6895405447371f,+0.6715589548470f,+0.6531728429538f,
  111123. +0.6343932841636f,+0.6152315905806f,+0.5956993044924f,+0.5758081914178f,
  111124. +0.5555702330196f,+0.5349976198871f,+0.5141027441932f,+0.4928981922298f,
  111125. +0.4713967368260f,+0.4496113296546f,+0.4275550934303f,+0.4052413140050f,
  111126. +0.3826834323651f,+0.3598950365350f,+0.3368898533922f,+0.3136817403989f,
  111127. +0.2902846772545f,+0.2667127574749f,+0.2429801799033f,+0.2191012401569f,
  111128. +0.1950903220161f,+0.1709618887603f,+0.1467304744554f,+0.1224106751992f,
  111129. +0.0980171403296f,+0.0735645635997f,+0.0490676743274f,+0.0245412285229f,
  111130. +0.0000000000000f,-0.0245412285229f,-0.0490676743274f,-0.0735645635997f,
  111131. -0.0980171403296f,-0.1224106751992f,-0.1467304744554f,-0.1709618887603f,
  111132. -0.1950903220161f,-0.2191012401569f,-0.2429801799033f,-0.2667127574749f,
  111133. -0.2902846772545f,-0.3136817403989f,-0.3368898533922f,-0.3598950365350f,
  111134. -0.3826834323651f,-0.4052413140050f,-0.4275550934303f,-0.4496113296546f,
  111135. -0.4713967368260f,-0.4928981922298f,-0.5141027441932f,-0.5349976198871f,
  111136. -0.5555702330196f,-0.5758081914178f,-0.5956993044924f,-0.6152315905806f,
  111137. -0.6343932841636f,-0.6531728429538f,-0.6715589548470f,-0.6895405447371f,
  111138. -0.7071067811865f,-0.7242470829515f,-0.7409511253550f,-0.7572088465065f,
  111139. -0.7730104533627f,-0.7883464276266f,-0.8032075314806f,-0.8175848131516f,
  111140. -0.8314696123025f,-0.8448535652497f,-0.8577286100003f,-0.8700869911087f,
  111141. -0.8819212643484f,-0.8932243011955f,-0.9039892931234f,-0.9142097557035f,
  111142. -0.9238795325113f,-0.9329927988347f,-0.9415440651830f,-0.9495281805930f,
  111143. -0.9569403357322f,-0.9637760657954f,-0.9700312531945f,-0.9757021300385f,
  111144. -0.9807852804032f,-0.9852776423889f,-0.9891765099648f,-0.9924795345987f,
  111145. -0.9951847266722f,-0.9972904566787f,-0.9987954562052f,-0.9996988186962f,
  111146. -1.0000000000000f,
  111147. };
  111148. #define INVSQ_LOOKUP_SZ 32
  111149. static float INVSQ_LOOKUP[INVSQ_LOOKUP_SZ+1]={
  111150. 1.414213562373f,1.392621247646f,1.371988681140f,1.352246807566f,
  111151. 1.333333333333f,1.315191898443f,1.297771369046f,1.281025230441f,
  111152. 1.264911064067f,1.249390095109f,1.234426799697f,1.219988562661f,
  111153. 1.206045378311f,1.192569588000f,1.179535649239f,1.166919931983f,
  111154. 1.154700538379f,1.142857142857f,1.131370849898f,1.120224067222f,
  111155. 1.109400392450f,1.098884511590f,1.088662107904f,1.078719779941f,
  111156. 1.069044967650f,1.059625885652f,1.050451462878f,1.041511287847f,
  111157. 1.032795558989f,1.024295039463f,1.016001016002f,1.007905261358f,
  111158. 1.000000000000f,
  111159. };
  111160. #define INVSQ2EXP_LOOKUP_MIN (-32)
  111161. #define INVSQ2EXP_LOOKUP_MAX 32
  111162. static float INVSQ2EXP_LOOKUP[INVSQ2EXP_LOOKUP_MAX-\
  111163. INVSQ2EXP_LOOKUP_MIN+1]={
  111164. 65536.f, 46340.95001f, 32768.f, 23170.47501f,
  111165. 16384.f, 11585.2375f, 8192.f, 5792.618751f,
  111166. 4096.f, 2896.309376f, 2048.f, 1448.154688f,
  111167. 1024.f, 724.0773439f, 512.f, 362.038672f,
  111168. 256.f, 181.019336f, 128.f, 90.50966799f,
  111169. 64.f, 45.254834f, 32.f, 22.627417f,
  111170. 16.f, 11.3137085f, 8.f, 5.656854249f,
  111171. 4.f, 2.828427125f, 2.f, 1.414213562f,
  111172. 1.f, 0.7071067812f, 0.5f, 0.3535533906f,
  111173. 0.25f, 0.1767766953f, 0.125f, 0.08838834765f,
  111174. 0.0625f, 0.04419417382f, 0.03125f, 0.02209708691f,
  111175. 0.015625f, 0.01104854346f, 0.0078125f, 0.005524271728f,
  111176. 0.00390625f, 0.002762135864f, 0.001953125f, 0.001381067932f,
  111177. 0.0009765625f, 0.000690533966f, 0.00048828125f, 0.000345266983f,
  111178. 0.000244140625f,0.0001726334915f,0.0001220703125f,8.631674575e-05f,
  111179. 6.103515625e-05f,4.315837288e-05f,3.051757812e-05f,2.157918644e-05f,
  111180. 1.525878906e-05f,
  111181. };
  111182. #endif
  111183. #define FROMdB_LOOKUP_SZ 35
  111184. #define FROMdB2_LOOKUP_SZ 32
  111185. #define FROMdB_SHIFT 5
  111186. #define FROMdB2_SHIFT 3
  111187. #define FROMdB2_MASK 31
  111188. static float FROMdB_LOOKUP[FROMdB_LOOKUP_SZ]={
  111189. 1.f, 0.6309573445f, 0.3981071706f, 0.2511886432f,
  111190. 0.1584893192f, 0.1f, 0.06309573445f, 0.03981071706f,
  111191. 0.02511886432f, 0.01584893192f, 0.01f, 0.006309573445f,
  111192. 0.003981071706f, 0.002511886432f, 0.001584893192f, 0.001f,
  111193. 0.0006309573445f,0.0003981071706f,0.0002511886432f,0.0001584893192f,
  111194. 0.0001f,6.309573445e-05f,3.981071706e-05f,2.511886432e-05f,
  111195. 1.584893192e-05f, 1e-05f,6.309573445e-06f,3.981071706e-06f,
  111196. 2.511886432e-06f,1.584893192e-06f, 1e-06f,6.309573445e-07f,
  111197. 3.981071706e-07f,2.511886432e-07f,1.584893192e-07f,
  111198. };
  111199. static float FROMdB2_LOOKUP[FROMdB2_LOOKUP_SZ]={
  111200. 0.9928302478f, 0.9786445908f, 0.9646616199f, 0.9508784391f,
  111201. 0.9372921937f, 0.92390007f, 0.9106992942f, 0.8976871324f,
  111202. 0.8848608897f, 0.8722179097f, 0.8597555737f, 0.8474713009f,
  111203. 0.835362547f, 0.8234268041f, 0.8116616003f, 0.8000644989f,
  111204. 0.7886330981f, 0.7773650302f, 0.7662579617f, 0.755309592f,
  111205. 0.7445176537f, 0.7338799116f, 0.7233941627f, 0.7130582353f,
  111206. 0.7028699885f, 0.6928273125f, 0.6829281272f, 0.6731703824f,
  111207. 0.6635520573f, 0.6540711597f, 0.6447257262f, 0.6355138211f,
  111208. };
  111209. #ifdef INT_LOOKUP
  111210. #define INVSQ_LOOKUP_I_SHIFT 10
  111211. #define INVSQ_LOOKUP_I_MASK 1023
  111212. static long INVSQ_LOOKUP_I[64+1]={
  111213. 92682l, 91966l, 91267l, 90583l,
  111214. 89915l, 89261l, 88621l, 87995l,
  111215. 87381l, 86781l, 86192l, 85616l,
  111216. 85051l, 84497l, 83953l, 83420l,
  111217. 82897l, 82384l, 81880l, 81385l,
  111218. 80899l, 80422l, 79953l, 79492l,
  111219. 79039l, 78594l, 78156l, 77726l,
  111220. 77302l, 76885l, 76475l, 76072l,
  111221. 75674l, 75283l, 74898l, 74519l,
  111222. 74146l, 73778l, 73415l, 73058l,
  111223. 72706l, 72359l, 72016l, 71679l,
  111224. 71347l, 71019l, 70695l, 70376l,
  111225. 70061l, 69750l, 69444l, 69141l,
  111226. 68842l, 68548l, 68256l, 67969l,
  111227. 67685l, 67405l, 67128l, 66855l,
  111228. 66585l, 66318l, 66054l, 65794l,
  111229. 65536l,
  111230. };
  111231. #define COS_LOOKUP_I_SHIFT 9
  111232. #define COS_LOOKUP_I_MASK 511
  111233. #define COS_LOOKUP_I_SZ 128
  111234. static long COS_LOOKUP_I[COS_LOOKUP_I_SZ+1]={
  111235. 16384l, 16379l, 16364l, 16340l,
  111236. 16305l, 16261l, 16207l, 16143l,
  111237. 16069l, 15986l, 15893l, 15791l,
  111238. 15679l, 15557l, 15426l, 15286l,
  111239. 15137l, 14978l, 14811l, 14635l,
  111240. 14449l, 14256l, 14053l, 13842l,
  111241. 13623l, 13395l, 13160l, 12916l,
  111242. 12665l, 12406l, 12140l, 11866l,
  111243. 11585l, 11297l, 11003l, 10702l,
  111244. 10394l, 10080l, 9760l, 9434l,
  111245. 9102l, 8765l, 8423l, 8076l,
  111246. 7723l, 7366l, 7005l, 6639l,
  111247. 6270l, 5897l, 5520l, 5139l,
  111248. 4756l, 4370l, 3981l, 3590l,
  111249. 3196l, 2801l, 2404l, 2006l,
  111250. 1606l, 1205l, 804l, 402l,
  111251. 0l, -401l, -803l, -1204l,
  111252. -1605l, -2005l, -2403l, -2800l,
  111253. -3195l, -3589l, -3980l, -4369l,
  111254. -4755l, -5138l, -5519l, -5896l,
  111255. -6269l, -6638l, -7004l, -7365l,
  111256. -7722l, -8075l, -8422l, -8764l,
  111257. -9101l, -9433l, -9759l, -10079l,
  111258. -10393l, -10701l, -11002l, -11296l,
  111259. -11584l, -11865l, -12139l, -12405l,
  111260. -12664l, -12915l, -13159l, -13394l,
  111261. -13622l, -13841l, -14052l, -14255l,
  111262. -14448l, -14634l, -14810l, -14977l,
  111263. -15136l, -15285l, -15425l, -15556l,
  111264. -15678l, -15790l, -15892l, -15985l,
  111265. -16068l, -16142l, -16206l, -16260l,
  111266. -16304l, -16339l, -16363l, -16378l,
  111267. -16383l,
  111268. };
  111269. #endif
  111270. #endif
  111271. /*** End of inlined file: lookup_data.h ***/
  111272. #ifdef FLOAT_LOOKUP
  111273. /* interpolated lookup based cos function, domain 0 to PI only */
  111274. float vorbis_coslook(float a){
  111275. double d=a*(.31830989*(float)COS_LOOKUP_SZ);
  111276. int i=vorbis_ftoi(d-.5);
  111277. return COS_LOOKUP[i]+ (d-i)*(COS_LOOKUP[i+1]-COS_LOOKUP[i]);
  111278. }
  111279. /* interpolated 1./sqrt(p) where .5 <= p < 1. */
  111280. float vorbis_invsqlook(float a){
  111281. double d=a*(2.f*(float)INVSQ_LOOKUP_SZ)-(float)INVSQ_LOOKUP_SZ;
  111282. int i=vorbis_ftoi(d-.5f);
  111283. return INVSQ_LOOKUP[i]+ (d-i)*(INVSQ_LOOKUP[i+1]-INVSQ_LOOKUP[i]);
  111284. }
  111285. /* interpolated 1./sqrt(p) where .5 <= p < 1. */
  111286. float vorbis_invsq2explook(int a){
  111287. return INVSQ2EXP_LOOKUP[a-INVSQ2EXP_LOOKUP_MIN];
  111288. }
  111289. #include <stdio.h>
  111290. /* interpolated lookup based fromdB function, domain -140dB to 0dB only */
  111291. float vorbis_fromdBlook(float a){
  111292. int i=vorbis_ftoi(a*((float)(-(1<<FROMdB2_SHIFT)))-.5f);
  111293. return (i<0)?1.f:
  111294. ((i>=(FROMdB_LOOKUP_SZ<<FROMdB_SHIFT))?0.f:
  111295. FROMdB_LOOKUP[i>>FROMdB_SHIFT]*FROMdB2_LOOKUP[i&FROMdB2_MASK]);
  111296. }
  111297. #endif
  111298. #ifdef INT_LOOKUP
  111299. /* interpolated 1./sqrt(p) where .5 <= a < 1. (.100000... to .111111...) in
  111300. 16.16 format
  111301. returns in m.8 format */
  111302. long vorbis_invsqlook_i(long a,long e){
  111303. long i=(a&0x7fff)>>(INVSQ_LOOKUP_I_SHIFT-1);
  111304. long d=(a&INVSQ_LOOKUP_I_MASK)<<(16-INVSQ_LOOKUP_I_SHIFT); /* 0.16 */
  111305. long val=INVSQ_LOOKUP_I[i]- /* 1.16 */
  111306. (((INVSQ_LOOKUP_I[i]-INVSQ_LOOKUP_I[i+1])* /* 0.16 */
  111307. d)>>16); /* result 1.16 */
  111308. e+=32;
  111309. if(e&1)val=(val*5792)>>13; /* multiply val by 1/sqrt(2) */
  111310. e=(e>>1)-8;
  111311. return(val>>e);
  111312. }
  111313. /* interpolated lookup based fromdB function, domain -140dB to 0dB only */
  111314. /* a is in n.12 format */
  111315. float vorbis_fromdBlook_i(long a){
  111316. int i=(-a)>>(12-FROMdB2_SHIFT);
  111317. return (i<0)?1.f:
  111318. ((i>=(FROMdB_LOOKUP_SZ<<FROMdB_SHIFT))?0.f:
  111319. FROMdB_LOOKUP[i>>FROMdB_SHIFT]*FROMdB2_LOOKUP[i&FROMdB2_MASK]);
  111320. }
  111321. /* interpolated lookup based cos function, domain 0 to PI only */
  111322. /* a is in 0.16 format, where 0==0, 2^^16-1==PI, return 0.14 */
  111323. long vorbis_coslook_i(long a){
  111324. int i=a>>COS_LOOKUP_I_SHIFT;
  111325. int d=a&COS_LOOKUP_I_MASK;
  111326. return COS_LOOKUP_I[i]- ((d*(COS_LOOKUP_I[i]-COS_LOOKUP_I[i+1]))>>
  111327. COS_LOOKUP_I_SHIFT);
  111328. }
  111329. #endif
  111330. #endif
  111331. /*** End of inlined file: lookup.c ***/
  111332. /* catch this in the build system; we #include for
  111333. compilers (like gcc) that can't inline across
  111334. modules */
  111335. static int MLOOP_1[64]={
  111336. 0,10,11,11, 12,12,12,12, 13,13,13,13, 13,13,13,13,
  111337. 14,14,14,14, 14,14,14,14, 14,14,14,14, 14,14,14,14,
  111338. 15,15,15,15, 15,15,15,15, 15,15,15,15, 15,15,15,15,
  111339. 15,15,15,15, 15,15,15,15, 15,15,15,15, 15,15,15,15,
  111340. };
  111341. static int MLOOP_2[64]={
  111342. 0,4,5,5, 6,6,6,6, 7,7,7,7, 7,7,7,7,
  111343. 8,8,8,8, 8,8,8,8, 8,8,8,8, 8,8,8,8,
  111344. 9,9,9,9, 9,9,9,9, 9,9,9,9, 9,9,9,9,
  111345. 9,9,9,9, 9,9,9,9, 9,9,9,9, 9,9,9,9,
  111346. };
  111347. static int MLOOP_3[8]={0,1,2,2,3,3,3,3};
  111348. /* side effect: changes *lsp to cosines of lsp */
  111349. void vorbis_lsp_to_curve(float *curve,int *map,int n,int ln,float *lsp,int m,
  111350. float amp,float ampoffset){
  111351. /* 0 <= m < 256 */
  111352. /* set up for using all int later */
  111353. int i;
  111354. int ampoffseti=rint(ampoffset*4096.f);
  111355. int ampi=rint(amp*16.f);
  111356. long *ilsp=alloca(m*sizeof(*ilsp));
  111357. for(i=0;i<m;i++)ilsp[i]=vorbis_coslook_i(lsp[i]/M_PI*65536.f+.5f);
  111358. i=0;
  111359. while(i<n){
  111360. int j,k=map[i];
  111361. unsigned long pi=46341; /* 2**-.5 in 0.16 */
  111362. unsigned long qi=46341;
  111363. int qexp=0,shift;
  111364. long wi=vorbis_coslook_i(k*65536/ln);
  111365. qi*=labs(ilsp[0]-wi);
  111366. pi*=labs(ilsp[1]-wi);
  111367. for(j=3;j<m;j+=2){
  111368. if(!(shift=MLOOP_1[(pi|qi)>>25]))
  111369. if(!(shift=MLOOP_2[(pi|qi)>>19]))
  111370. shift=MLOOP_3[(pi|qi)>>16];
  111371. qi=(qi>>shift)*labs(ilsp[j-1]-wi);
  111372. pi=(pi>>shift)*labs(ilsp[j]-wi);
  111373. qexp+=shift;
  111374. }
  111375. if(!(shift=MLOOP_1[(pi|qi)>>25]))
  111376. if(!(shift=MLOOP_2[(pi|qi)>>19]))
  111377. shift=MLOOP_3[(pi|qi)>>16];
  111378. /* pi,qi normalized collectively, both tracked using qexp */
  111379. if(m&1){
  111380. /* odd order filter; slightly assymetric */
  111381. /* the last coefficient */
  111382. qi=(qi>>shift)*labs(ilsp[j-1]-wi);
  111383. pi=(pi>>shift)<<14;
  111384. qexp+=shift;
  111385. if(!(shift=MLOOP_1[(pi|qi)>>25]))
  111386. if(!(shift=MLOOP_2[(pi|qi)>>19]))
  111387. shift=MLOOP_3[(pi|qi)>>16];
  111388. pi>>=shift;
  111389. qi>>=shift;
  111390. qexp+=shift-14*((m+1)>>1);
  111391. pi=((pi*pi)>>16);
  111392. qi=((qi*qi)>>16);
  111393. qexp=qexp*2+m;
  111394. pi*=(1<<14)-((wi*wi)>>14);
  111395. qi+=pi>>14;
  111396. }else{
  111397. /* even order filter; still symmetric */
  111398. /* p*=p(1-w), q*=q(1+w), let normalization drift because it isn't
  111399. worth tracking step by step */
  111400. pi>>=shift;
  111401. qi>>=shift;
  111402. qexp+=shift-7*m;
  111403. pi=((pi*pi)>>16);
  111404. qi=((qi*qi)>>16);
  111405. qexp=qexp*2+m;
  111406. pi*=(1<<14)-wi;
  111407. qi*=(1<<14)+wi;
  111408. qi=(qi+pi)>>14;
  111409. }
  111410. /* we've let the normalization drift because it wasn't important;
  111411. however, for the lookup, things must be normalized again. We
  111412. need at most one right shift or a number of left shifts */
  111413. if(qi&0xffff0000){ /* checks for 1.xxxxxxxxxxxxxxxx */
  111414. qi>>=1; qexp++;
  111415. }else
  111416. while(qi && !(qi&0x8000)){ /* checks for 0.0xxxxxxxxxxxxxxx or less*/
  111417. qi<<=1; qexp--;
  111418. }
  111419. amp=vorbis_fromdBlook_i(ampi* /* n.4 */
  111420. vorbis_invsqlook_i(qi,qexp)-
  111421. /* m.8, m+n<=8 */
  111422. ampoffseti); /* 8.12[0] */
  111423. curve[i]*=amp;
  111424. while(map[++i]==k)curve[i]*=amp;
  111425. }
  111426. }
  111427. #else
  111428. /* old, nonoptimized but simple version for any poor sap who needs to
  111429. figure out what the hell this code does, or wants the other
  111430. fraction of a dB precision */
  111431. /* side effect: changes *lsp to cosines of lsp */
  111432. void vorbis_lsp_to_curve(float *curve,int *map,int n,int ln,float *lsp,int m,
  111433. float amp,float ampoffset){
  111434. int i;
  111435. float wdel=M_PI/ln;
  111436. for(i=0;i<m;i++)lsp[i]=2.f*cos(lsp[i]);
  111437. i=0;
  111438. while(i<n){
  111439. int j,k=map[i];
  111440. float p=.5f;
  111441. float q=.5f;
  111442. float w=2.f*cos(wdel*k);
  111443. for(j=1;j<m;j+=2){
  111444. q *= w-lsp[j-1];
  111445. p *= w-lsp[j];
  111446. }
  111447. if(j==m){
  111448. /* odd order filter; slightly assymetric */
  111449. /* the last coefficient */
  111450. q*=w-lsp[j-1];
  111451. p*=p*(4.f-w*w);
  111452. q*=q;
  111453. }else{
  111454. /* even order filter; still symmetric */
  111455. p*=p*(2.f-w);
  111456. q*=q*(2.f+w);
  111457. }
  111458. q=fromdB(amp/sqrt(p+q)-ampoffset);
  111459. curve[i]*=q;
  111460. while(map[++i]==k)curve[i]*=q;
  111461. }
  111462. }
  111463. #endif
  111464. #endif
  111465. static void cheby(float *g, int ord) {
  111466. int i, j;
  111467. g[0] *= .5f;
  111468. for(i=2; i<= ord; i++) {
  111469. for(j=ord; j >= i; j--) {
  111470. g[j-2] -= g[j];
  111471. g[j] += g[j];
  111472. }
  111473. }
  111474. }
  111475. static int comp(const void *a,const void *b){
  111476. return (*(float *)a<*(float *)b)-(*(float *)a>*(float *)b);
  111477. }
  111478. /* Newton-Raphson-Maehly actually functioned as a decent root finder,
  111479. but there are root sets for which it gets into limit cycles
  111480. (exacerbated by zero suppression) and fails. We can't afford to
  111481. fail, even if the failure is 1 in 100,000,000, so we now use
  111482. Laguerre and later polish with Newton-Raphson (which can then
  111483. afford to fail) */
  111484. #define EPSILON 10e-7
  111485. static int Laguerre_With_Deflation(float *a,int ord,float *r){
  111486. int i,m;
  111487. double lastdelta=0.f;
  111488. double *defl=(double*)alloca(sizeof(*defl)*(ord+1));
  111489. for(i=0;i<=ord;i++)defl[i]=a[i];
  111490. for(m=ord;m>0;m--){
  111491. double newx=0.f,delta;
  111492. /* iterate a root */
  111493. while(1){
  111494. double p=defl[m],pp=0.f,ppp=0.f,denom;
  111495. /* eval the polynomial and its first two derivatives */
  111496. for(i=m;i>0;i--){
  111497. ppp = newx*ppp + pp;
  111498. pp = newx*pp + p;
  111499. p = newx*p + defl[i-1];
  111500. }
  111501. /* Laguerre's method */
  111502. denom=(m-1) * ((m-1)*pp*pp - m*p*ppp);
  111503. if(denom<0)
  111504. return(-1); /* complex root! The LPC generator handed us a bad filter */
  111505. if(pp>0){
  111506. denom = pp + sqrt(denom);
  111507. if(denom<EPSILON)denom=EPSILON;
  111508. }else{
  111509. denom = pp - sqrt(denom);
  111510. if(denom>-(EPSILON))denom=-(EPSILON);
  111511. }
  111512. delta = m*p/denom;
  111513. newx -= delta;
  111514. if(delta<0.f)delta*=-1;
  111515. if(fabs(delta/newx)<10e-12)break;
  111516. lastdelta=delta;
  111517. }
  111518. r[m-1]=newx;
  111519. /* forward deflation */
  111520. for(i=m;i>0;i--)
  111521. defl[i-1]+=newx*defl[i];
  111522. defl++;
  111523. }
  111524. return(0);
  111525. }
  111526. /* for spit-and-polish only */
  111527. static int Newton_Raphson(float *a,int ord,float *r){
  111528. int i, k, count=0;
  111529. double error=1.f;
  111530. double *root=(double*)alloca(ord*sizeof(*root));
  111531. for(i=0; i<ord;i++) root[i] = r[i];
  111532. while(error>1e-20){
  111533. error=0;
  111534. for(i=0; i<ord; i++) { /* Update each point. */
  111535. double pp=0.,delta;
  111536. double rooti=root[i];
  111537. double p=a[ord];
  111538. for(k=ord-1; k>= 0; k--) {
  111539. pp= pp* rooti + p;
  111540. p = p * rooti + a[k];
  111541. }
  111542. delta = p/pp;
  111543. root[i] -= delta;
  111544. error+= delta*delta;
  111545. }
  111546. if(count>40)return(-1);
  111547. count++;
  111548. }
  111549. /* Replaced the original bubble sort with a real sort. With your
  111550. help, we can eliminate the bubble sort in our lifetime. --Monty */
  111551. for(i=0; i<ord;i++) r[i] = root[i];
  111552. return(0);
  111553. }
  111554. /* Convert lpc coefficients to lsp coefficients */
  111555. int vorbis_lpc_to_lsp(float *lpc,float *lsp,int m){
  111556. int order2=(m+1)>>1;
  111557. int g1_order,g2_order;
  111558. float *g1=(float*)alloca(sizeof(*g1)*(order2+1));
  111559. float *g2=(float*)alloca(sizeof(*g2)*(order2+1));
  111560. float *g1r=(float*)alloca(sizeof(*g1r)*(order2+1));
  111561. float *g2r=(float*)alloca(sizeof(*g2r)*(order2+1));
  111562. int i;
  111563. /* even and odd are slightly different base cases */
  111564. g1_order=(m+1)>>1;
  111565. g2_order=(m) >>1;
  111566. /* Compute the lengths of the x polynomials. */
  111567. /* Compute the first half of K & R F1 & F2 polynomials. */
  111568. /* Compute half of the symmetric and antisymmetric polynomials. */
  111569. /* Remove the roots at +1 and -1. */
  111570. g1[g1_order] = 1.f;
  111571. for(i=1;i<=g1_order;i++) g1[g1_order-i] = lpc[i-1]+lpc[m-i];
  111572. g2[g2_order] = 1.f;
  111573. for(i=1;i<=g2_order;i++) g2[g2_order-i] = lpc[i-1]-lpc[m-i];
  111574. if(g1_order>g2_order){
  111575. for(i=2; i<=g2_order;i++) g2[g2_order-i] += g2[g2_order-i+2];
  111576. }else{
  111577. for(i=1; i<=g1_order;i++) g1[g1_order-i] -= g1[g1_order-i+1];
  111578. for(i=1; i<=g2_order;i++) g2[g2_order-i] += g2[g2_order-i+1];
  111579. }
  111580. /* Convert into polynomials in cos(alpha) */
  111581. cheby(g1,g1_order);
  111582. cheby(g2,g2_order);
  111583. /* Find the roots of the 2 even polynomials.*/
  111584. if(Laguerre_With_Deflation(g1,g1_order,g1r) ||
  111585. Laguerre_With_Deflation(g2,g2_order,g2r))
  111586. return(-1);
  111587. Newton_Raphson(g1,g1_order,g1r); /* if it fails, it leaves g1r alone */
  111588. Newton_Raphson(g2,g2_order,g2r); /* if it fails, it leaves g2r alone */
  111589. qsort(g1r,g1_order,sizeof(*g1r),comp);
  111590. qsort(g2r,g2_order,sizeof(*g2r),comp);
  111591. for(i=0;i<g1_order;i++)
  111592. lsp[i*2] = acos(g1r[i]);
  111593. for(i=0;i<g2_order;i++)
  111594. lsp[i*2+1] = acos(g2r[i]);
  111595. return(0);
  111596. }
  111597. #endif
  111598. /*** End of inlined file: lsp.c ***/
  111599. /*** Start of inlined file: mapping0.c ***/
  111600. /*** Start of inlined file: juce_OggVorbisHeader.h ***/
  111601. // This file is included at the start of each Ogg-Vorbis .c file, just to do a few housekeeping
  111602. // tasks..
  111603. #if JUCE_MSVC
  111604. #pragma warning (disable: 4267 4127 4244 4996 4100 4701 4702 4013 4133 4206 4305 4189 4706)
  111605. #endif
  111606. /*** End of inlined file: juce_OggVorbisHeader.h ***/
  111607. #if JUCE_USE_OGGVORBIS
  111608. #include <stdlib.h>
  111609. #include <stdio.h>
  111610. #include <string.h>
  111611. #include <math.h>
  111612. /* simplistic, wasteful way of doing this (unique lookup for each
  111613. mode/submapping); there should be a central repository for
  111614. identical lookups. That will require minor work, so I'm putting it
  111615. off as low priority.
  111616. Why a lookup for each backend in a given mode? Because the
  111617. blocksize is set by the mode, and low backend lookups may require
  111618. parameters from other areas of the mode/mapping */
  111619. static void mapping0_free_info(vorbis_info_mapping *i){
  111620. vorbis_info_mapping0 *info=(vorbis_info_mapping0 *)i;
  111621. if(info){
  111622. memset(info,0,sizeof(*info));
  111623. _ogg_free(info);
  111624. }
  111625. }
  111626. static int ilog3(unsigned int v){
  111627. int ret=0;
  111628. if(v)--v;
  111629. while(v){
  111630. ret++;
  111631. v>>=1;
  111632. }
  111633. return(ret);
  111634. }
  111635. static void mapping0_pack(vorbis_info *vi,vorbis_info_mapping *vm,
  111636. oggpack_buffer *opb){
  111637. int i;
  111638. vorbis_info_mapping0 *info=(vorbis_info_mapping0 *)vm;
  111639. /* another 'we meant to do it this way' hack... up to beta 4, we
  111640. packed 4 binary zeros here to signify one submapping in use. We
  111641. now redefine that to mean four bitflags that indicate use of
  111642. deeper features; bit0:submappings, bit1:coupling,
  111643. bit2,3:reserved. This is backward compatable with all actual uses
  111644. of the beta code. */
  111645. if(info->submaps>1){
  111646. oggpack_write(opb,1,1);
  111647. oggpack_write(opb,info->submaps-1,4);
  111648. }else
  111649. oggpack_write(opb,0,1);
  111650. if(info->coupling_steps>0){
  111651. oggpack_write(opb,1,1);
  111652. oggpack_write(opb,info->coupling_steps-1,8);
  111653. for(i=0;i<info->coupling_steps;i++){
  111654. oggpack_write(opb,info->coupling_mag[i],ilog3(vi->channels));
  111655. oggpack_write(opb,info->coupling_ang[i],ilog3(vi->channels));
  111656. }
  111657. }else
  111658. oggpack_write(opb,0,1);
  111659. oggpack_write(opb,0,2); /* 2,3:reserved */
  111660. /* we don't write the channel submappings if we only have one... */
  111661. if(info->submaps>1){
  111662. for(i=0;i<vi->channels;i++)
  111663. oggpack_write(opb,info->chmuxlist[i],4);
  111664. }
  111665. for(i=0;i<info->submaps;i++){
  111666. oggpack_write(opb,0,8); /* time submap unused */
  111667. oggpack_write(opb,info->floorsubmap[i],8);
  111668. oggpack_write(opb,info->residuesubmap[i],8);
  111669. }
  111670. }
  111671. /* also responsible for range checking */
  111672. static vorbis_info_mapping *mapping0_unpack(vorbis_info *vi,oggpack_buffer *opb){
  111673. int i;
  111674. vorbis_info_mapping0 *info=(vorbis_info_mapping0*)_ogg_calloc(1,sizeof(*info));
  111675. codec_setup_info *ci=(codec_setup_info*)vi->codec_setup;
  111676. memset(info,0,sizeof(*info));
  111677. if(oggpack_read(opb,1))
  111678. info->submaps=oggpack_read(opb,4)+1;
  111679. else
  111680. info->submaps=1;
  111681. if(oggpack_read(opb,1)){
  111682. info->coupling_steps=oggpack_read(opb,8)+1;
  111683. for(i=0;i<info->coupling_steps;i++){
  111684. int testM=info->coupling_mag[i]=oggpack_read(opb,ilog3(vi->channels));
  111685. int testA=info->coupling_ang[i]=oggpack_read(opb,ilog3(vi->channels));
  111686. if(testM<0 ||
  111687. testA<0 ||
  111688. testM==testA ||
  111689. testM>=vi->channels ||
  111690. testA>=vi->channels) goto err_out;
  111691. }
  111692. }
  111693. if(oggpack_read(opb,2)>0)goto err_out; /* 2,3:reserved */
  111694. if(info->submaps>1){
  111695. for(i=0;i<vi->channels;i++){
  111696. info->chmuxlist[i]=oggpack_read(opb,4);
  111697. if(info->chmuxlist[i]>=info->submaps)goto err_out;
  111698. }
  111699. }
  111700. for(i=0;i<info->submaps;i++){
  111701. oggpack_read(opb,8); /* time submap unused */
  111702. info->floorsubmap[i]=oggpack_read(opb,8);
  111703. if(info->floorsubmap[i]>=ci->floors)goto err_out;
  111704. info->residuesubmap[i]=oggpack_read(opb,8);
  111705. if(info->residuesubmap[i]>=ci->residues)goto err_out;
  111706. }
  111707. return info;
  111708. err_out:
  111709. mapping0_free_info(info);
  111710. return(NULL);
  111711. }
  111712. #if 0
  111713. static long seq=0;
  111714. static ogg_int64_t total=0;
  111715. static float FLOOR1_fromdB_LOOKUP[256]={
  111716. 1.0649863e-07F, 1.1341951e-07F, 1.2079015e-07F, 1.2863978e-07F,
  111717. 1.3699951e-07F, 1.4590251e-07F, 1.5538408e-07F, 1.6548181e-07F,
  111718. 1.7623575e-07F, 1.8768855e-07F, 1.9988561e-07F, 2.128753e-07F,
  111719. 2.2670913e-07F, 2.4144197e-07F, 2.5713223e-07F, 2.7384213e-07F,
  111720. 2.9163793e-07F, 3.1059021e-07F, 3.3077411e-07F, 3.5226968e-07F,
  111721. 3.7516214e-07F, 3.9954229e-07F, 4.2550680e-07F, 4.5315863e-07F,
  111722. 4.8260743e-07F, 5.1396998e-07F, 5.4737065e-07F, 5.8294187e-07F,
  111723. 6.2082472e-07F, 6.6116941e-07F, 7.0413592e-07F, 7.4989464e-07F,
  111724. 7.9862701e-07F, 8.5052630e-07F, 9.0579828e-07F, 9.6466216e-07F,
  111725. 1.0273513e-06F, 1.0941144e-06F, 1.1652161e-06F, 1.2409384e-06F,
  111726. 1.3215816e-06F, 1.4074654e-06F, 1.4989305e-06F, 1.5963394e-06F,
  111727. 1.7000785e-06F, 1.8105592e-06F, 1.9282195e-06F, 2.0535261e-06F,
  111728. 2.1869758e-06F, 2.3290978e-06F, 2.4804557e-06F, 2.6416497e-06F,
  111729. 2.8133190e-06F, 2.9961443e-06F, 3.1908506e-06F, 3.3982101e-06F,
  111730. 3.6190449e-06F, 3.8542308e-06F, 4.1047004e-06F, 4.3714470e-06F,
  111731. 4.6555282e-06F, 4.9580707e-06F, 5.2802740e-06F, 5.6234160e-06F,
  111732. 5.9888572e-06F, 6.3780469e-06F, 6.7925283e-06F, 7.2339451e-06F,
  111733. 7.7040476e-06F, 8.2047000e-06F, 8.7378876e-06F, 9.3057248e-06F,
  111734. 9.9104632e-06F, 1.0554501e-05F, 1.1240392e-05F, 1.1970856e-05F,
  111735. 1.2748789e-05F, 1.3577278e-05F, 1.4459606e-05F, 1.5399272e-05F,
  111736. 1.6400004e-05F, 1.7465768e-05F, 1.8600792e-05F, 1.9809576e-05F,
  111737. 2.1096914e-05F, 2.2467911e-05F, 2.3928002e-05F, 2.5482978e-05F,
  111738. 2.7139006e-05F, 2.8902651e-05F, 3.0780908e-05F, 3.2781225e-05F,
  111739. 3.4911534e-05F, 3.7180282e-05F, 3.9596466e-05F, 4.2169667e-05F,
  111740. 4.4910090e-05F, 4.7828601e-05F, 5.0936773e-05F, 5.4246931e-05F,
  111741. 5.7772202e-05F, 6.1526565e-05F, 6.5524908e-05F, 6.9783085e-05F,
  111742. 7.4317983e-05F, 7.9147585e-05F, 8.4291040e-05F, 8.9768747e-05F,
  111743. 9.5602426e-05F, 0.00010181521F, 0.00010843174F, 0.00011547824F,
  111744. 0.00012298267F, 0.00013097477F, 0.00013948625F, 0.00014855085F,
  111745. 0.00015820453F, 0.00016848555F, 0.00017943469F, 0.00019109536F,
  111746. 0.00020351382F, 0.00021673929F, 0.00023082423F, 0.00024582449F,
  111747. 0.00026179955F, 0.00027881276F, 0.00029693158F, 0.00031622787F,
  111748. 0.00033677814F, 0.00035866388F, 0.00038197188F, 0.00040679456F,
  111749. 0.00043323036F, 0.00046138411F, 0.00049136745F, 0.00052329927F,
  111750. 0.00055730621F, 0.00059352311F, 0.00063209358F, 0.00067317058F,
  111751. 0.00071691700F, 0.00076350630F, 0.00081312324F, 0.00086596457F,
  111752. 0.00092223983F, 0.00098217216F, 0.0010459992F, 0.0011139742F,
  111753. 0.0011863665F, 0.0012634633F, 0.0013455702F, 0.0014330129F,
  111754. 0.0015261382F, 0.0016253153F, 0.0017309374F, 0.0018434235F,
  111755. 0.0019632195F, 0.0020908006F, 0.0022266726F, 0.0023713743F,
  111756. 0.0025254795F, 0.0026895994F, 0.0028643847F, 0.0030505286F,
  111757. 0.0032487691F, 0.0034598925F, 0.0036847358F, 0.0039241906F,
  111758. 0.0041792066F, 0.0044507950F, 0.0047400328F, 0.0050480668F,
  111759. 0.0053761186F, 0.0057254891F, 0.0060975636F, 0.0064938176F,
  111760. 0.0069158225F, 0.0073652516F, 0.0078438871F, 0.0083536271F,
  111761. 0.0088964928F, 0.009474637F, 0.010090352F, 0.010746080F,
  111762. 0.011444421F, 0.012188144F, 0.012980198F, 0.013823725F,
  111763. 0.014722068F, 0.015678791F, 0.016697687F, 0.017782797F,
  111764. 0.018938423F, 0.020169149F, 0.021479854F, 0.022875735F,
  111765. 0.024362330F, 0.025945531F, 0.027631618F, 0.029427276F,
  111766. 0.031339626F, 0.033376252F, 0.035545228F, 0.037855157F,
  111767. 0.040315199F, 0.042935108F, 0.045725273F, 0.048696758F,
  111768. 0.051861348F, 0.055231591F, 0.058820850F, 0.062643361F,
  111769. 0.066714279F, 0.071049749F, 0.075666962F, 0.080584227F,
  111770. 0.085821044F, 0.091398179F, 0.097337747F, 0.10366330F,
  111771. 0.11039993F, 0.11757434F, 0.12521498F, 0.13335215F,
  111772. 0.14201813F, 0.15124727F, 0.16107617F, 0.17154380F,
  111773. 0.18269168F, 0.19456402F, 0.20720788F, 0.22067342F,
  111774. 0.23501402F, 0.25028656F, 0.26655159F, 0.28387361F,
  111775. 0.30232132F, 0.32196786F, 0.34289114F, 0.36517414F,
  111776. 0.38890521F, 0.41417847F, 0.44109412F, 0.46975890F,
  111777. 0.50028648F, 0.53279791F, 0.56742212F, 0.60429640F,
  111778. 0.64356699F, 0.68538959F, 0.72993007F, 0.77736504F,
  111779. 0.82788260F, 0.88168307F, 0.9389798F, 1.F,
  111780. };
  111781. #endif
  111782. extern int *floor1_fit(vorbis_block *vb,void *look,
  111783. const float *logmdct, /* in */
  111784. const float *logmask);
  111785. extern int *floor1_interpolate_fit(vorbis_block *vb,void *look,
  111786. int *A,int *B,
  111787. int del);
  111788. extern int floor1_encode(oggpack_buffer *opb,vorbis_block *vb,
  111789. void*look,
  111790. int *post,int *ilogmask);
  111791. static int mapping0_forward(vorbis_block *vb){
  111792. vorbis_dsp_state *vd=vb->vd;
  111793. vorbis_info *vi=vd->vi;
  111794. codec_setup_info *ci=(codec_setup_info*)vi->codec_setup;
  111795. private_state *b=(private_state*)vb->vd->backend_state;
  111796. vorbis_block_internal *vbi=(vorbis_block_internal *)vb->internal;
  111797. int n=vb->pcmend;
  111798. int i,j,k;
  111799. int *nonzero = (int*) alloca(sizeof(*nonzero)*vi->channels);
  111800. float **gmdct = (float**) _vorbis_block_alloc(vb,vi->channels*sizeof(*gmdct));
  111801. int **ilogmaskch= (int**) _vorbis_block_alloc(vb,vi->channels*sizeof(*ilogmaskch));
  111802. int ***floor_posts = (int***) _vorbis_block_alloc(vb,vi->channels*sizeof(*floor_posts));
  111803. float global_ampmax=vbi->ampmax;
  111804. float *local_ampmax=(float*)alloca(sizeof(*local_ampmax)*vi->channels);
  111805. int blocktype=vbi->blocktype;
  111806. int modenumber=vb->W;
  111807. vorbis_info_mapping0 *info=(vorbis_info_mapping0*)ci->map_param[modenumber];
  111808. vorbis_look_psy *psy_look=
  111809. b->psy+blocktype+(vb->W?2:0);
  111810. vb->mode=modenumber;
  111811. for(i=0;i<vi->channels;i++){
  111812. float scale=4.f/n;
  111813. float scale_dB;
  111814. float *pcm =vb->pcm[i];
  111815. float *logfft =pcm;
  111816. gmdct[i]=(float*)_vorbis_block_alloc(vb,n/2*sizeof(**gmdct));
  111817. scale_dB=todB(&scale) + .345; /* + .345 is a hack; the original
  111818. todB estimation used on IEEE 754
  111819. compliant machines had a bug that
  111820. returned dB values about a third
  111821. of a decibel too high. The bug
  111822. was harmless because tunings
  111823. implicitly took that into
  111824. account. However, fixing the bug
  111825. in the estimator requires
  111826. changing all the tunings as well.
  111827. For now, it's easier to sync
  111828. things back up here, and
  111829. recalibrate the tunings in the
  111830. next major model upgrade. */
  111831. #if 0
  111832. if(vi->channels==2)
  111833. if(i==0)
  111834. _analysis_output("pcmL",seq,pcm,n,0,0,total-n/2);
  111835. else
  111836. _analysis_output("pcmR",seq,pcm,n,0,0,total-n/2);
  111837. #endif
  111838. /* window the PCM data */
  111839. _vorbis_apply_window(pcm,b->window,ci->blocksizes,vb->lW,vb->W,vb->nW);
  111840. #if 0
  111841. if(vi->channels==2)
  111842. if(i==0)
  111843. _analysis_output("windowedL",seq,pcm,n,0,0,total-n/2);
  111844. else
  111845. _analysis_output("windowedR",seq,pcm,n,0,0,total-n/2);
  111846. #endif
  111847. /* transform the PCM data */
  111848. /* only MDCT right now.... */
  111849. mdct_forward((mdct_lookup*) b->transform[vb->W][0],pcm,gmdct[i]);
  111850. /* FFT yields more accurate tonal estimation (not phase sensitive) */
  111851. drft_forward(&b->fft_look[vb->W],pcm);
  111852. logfft[0]=scale_dB+todB(pcm) + .345; /* + .345 is a hack; the
  111853. original todB estimation used on
  111854. IEEE 754 compliant machines had a
  111855. bug that returned dB values about
  111856. a third of a decibel too high.
  111857. The bug was harmless because
  111858. tunings implicitly took that into
  111859. account. However, fixing the bug
  111860. in the estimator requires
  111861. changing all the tunings as well.
  111862. For now, it's easier to sync
  111863. things back up here, and
  111864. recalibrate the tunings in the
  111865. next major model upgrade. */
  111866. local_ampmax[i]=logfft[0];
  111867. for(j=1;j<n-1;j+=2){
  111868. float temp=pcm[j]*pcm[j]+pcm[j+1]*pcm[j+1];
  111869. temp=logfft[(j+1)>>1]=scale_dB+.5f*todB(&temp) + .345; /* +
  111870. .345 is a hack; the original todB
  111871. estimation used on IEEE 754
  111872. compliant machines had a bug that
  111873. returned dB values about a third
  111874. of a decibel too high. The bug
  111875. was harmless because tunings
  111876. implicitly took that into
  111877. account. However, fixing the bug
  111878. in the estimator requires
  111879. changing all the tunings as well.
  111880. For now, it's easier to sync
  111881. things back up here, and
  111882. recalibrate the tunings in the
  111883. next major model upgrade. */
  111884. if(temp>local_ampmax[i])local_ampmax[i]=temp;
  111885. }
  111886. if(local_ampmax[i]>0.f)local_ampmax[i]=0.f;
  111887. if(local_ampmax[i]>global_ampmax)global_ampmax=local_ampmax[i];
  111888. #if 0
  111889. if(vi->channels==2){
  111890. if(i==0){
  111891. _analysis_output("fftL",seq,logfft,n/2,1,0,0);
  111892. }else{
  111893. _analysis_output("fftR",seq,logfft,n/2,1,0,0);
  111894. }
  111895. }
  111896. #endif
  111897. }
  111898. {
  111899. float *noise = (float*) _vorbis_block_alloc(vb,n/2*sizeof(*noise));
  111900. float *tone = (float*) _vorbis_block_alloc(vb,n/2*sizeof(*tone));
  111901. for(i=0;i<vi->channels;i++){
  111902. /* the encoder setup assumes that all the modes used by any
  111903. specific bitrate tweaking use the same floor */
  111904. int submap=info->chmuxlist[i];
  111905. /* the following makes things clearer to *me* anyway */
  111906. float *mdct =gmdct[i];
  111907. float *logfft =vb->pcm[i];
  111908. float *logmdct =logfft+n/2;
  111909. float *logmask =logfft;
  111910. vb->mode=modenumber;
  111911. floor_posts[i]=(int**) _vorbis_block_alloc(vb,PACKETBLOBS*sizeof(**floor_posts));
  111912. memset(floor_posts[i],0,sizeof(**floor_posts)*PACKETBLOBS);
  111913. for(j=0;j<n/2;j++)
  111914. logmdct[j]=todB(mdct+j) + .345; /* + .345 is a hack; the original
  111915. todB estimation used on IEEE 754
  111916. compliant machines had a bug that
  111917. returned dB values about a third
  111918. of a decibel too high. The bug
  111919. was harmless because tunings
  111920. implicitly took that into
  111921. account. However, fixing the bug
  111922. in the estimator requires
  111923. changing all the tunings as well.
  111924. For now, it's easier to sync
  111925. things back up here, and
  111926. recalibrate the tunings in the
  111927. next major model upgrade. */
  111928. #if 0
  111929. if(vi->channels==2){
  111930. if(i==0)
  111931. _analysis_output("mdctL",seq,logmdct,n/2,1,0,0);
  111932. else
  111933. _analysis_output("mdctR",seq,logmdct,n/2,1,0,0);
  111934. }else{
  111935. _analysis_output("mdct",seq,logmdct,n/2,1,0,0);
  111936. }
  111937. #endif
  111938. /* first step; noise masking. Not only does 'noise masking'
  111939. give us curves from which we can decide how much resolution
  111940. to give noise parts of the spectrum, it also implicitly hands
  111941. us a tonality estimate (the larger the value in the
  111942. 'noise_depth' vector, the more tonal that area is) */
  111943. _vp_noisemask(psy_look,
  111944. logmdct,
  111945. noise); /* noise does not have by-frequency offset
  111946. bias applied yet */
  111947. #if 0
  111948. if(vi->channels==2){
  111949. if(i==0)
  111950. _analysis_output("noiseL",seq,noise,n/2,1,0,0);
  111951. else
  111952. _analysis_output("noiseR",seq,noise,n/2,1,0,0);
  111953. }
  111954. #endif
  111955. /* second step: 'all the other crap'; all the stuff that isn't
  111956. computed/fit for bitrate management goes in the second psy
  111957. vector. This includes tone masking, peak limiting and ATH */
  111958. _vp_tonemask(psy_look,
  111959. logfft,
  111960. tone,
  111961. global_ampmax,
  111962. local_ampmax[i]);
  111963. #if 0
  111964. if(vi->channels==2){
  111965. if(i==0)
  111966. _analysis_output("toneL",seq,tone,n/2,1,0,0);
  111967. else
  111968. _analysis_output("toneR",seq,tone,n/2,1,0,0);
  111969. }
  111970. #endif
  111971. /* third step; we offset the noise vectors, overlay tone
  111972. masking. We then do a floor1-specific line fit. If we're
  111973. performing bitrate management, the line fit is performed
  111974. multiple times for up/down tweakage on demand. */
  111975. #if 0
  111976. {
  111977. float aotuv[psy_look->n];
  111978. #endif
  111979. _vp_offset_and_mix(psy_look,
  111980. noise,
  111981. tone,
  111982. 1,
  111983. logmask,
  111984. mdct,
  111985. logmdct);
  111986. #if 0
  111987. if(vi->channels==2){
  111988. if(i==0)
  111989. _analysis_output("aotuvM1_L",seq,aotuv,psy_look->n,1,1,0);
  111990. else
  111991. _analysis_output("aotuvM1_R",seq,aotuv,psy_look->n,1,1,0);
  111992. }
  111993. }
  111994. #endif
  111995. #if 0
  111996. if(vi->channels==2){
  111997. if(i==0)
  111998. _analysis_output("mask1L",seq,logmask,n/2,1,0,0);
  111999. else
  112000. _analysis_output("mask1R",seq,logmask,n/2,1,0,0);
  112001. }
  112002. #endif
  112003. /* this algorithm is hardwired to floor 1 for now; abort out if
  112004. we're *not* floor1. This won't happen unless someone has
  112005. broken the encode setup lib. Guard it anyway. */
  112006. if(ci->floor_type[info->floorsubmap[submap]]!=1)return(-1);
  112007. floor_posts[i][PACKETBLOBS/2]=
  112008. floor1_fit(vb,b->flr[info->floorsubmap[submap]],
  112009. logmdct,
  112010. logmask);
  112011. /* are we managing bitrate? If so, perform two more fits for
  112012. later rate tweaking (fits represent hi/lo) */
  112013. if(vorbis_bitrate_managed(vb) && floor_posts[i][PACKETBLOBS/2]){
  112014. /* higher rate by way of lower noise curve */
  112015. _vp_offset_and_mix(psy_look,
  112016. noise,
  112017. tone,
  112018. 2,
  112019. logmask,
  112020. mdct,
  112021. logmdct);
  112022. #if 0
  112023. if(vi->channels==2){
  112024. if(i==0)
  112025. _analysis_output("mask2L",seq,logmask,n/2,1,0,0);
  112026. else
  112027. _analysis_output("mask2R",seq,logmask,n/2,1,0,0);
  112028. }
  112029. #endif
  112030. floor_posts[i][PACKETBLOBS-1]=
  112031. floor1_fit(vb,b->flr[info->floorsubmap[submap]],
  112032. logmdct,
  112033. logmask);
  112034. /* lower rate by way of higher noise curve */
  112035. _vp_offset_and_mix(psy_look,
  112036. noise,
  112037. tone,
  112038. 0,
  112039. logmask,
  112040. mdct,
  112041. logmdct);
  112042. #if 0
  112043. if(vi->channels==2)
  112044. if(i==0)
  112045. _analysis_output("mask0L",seq,logmask,n/2,1,0,0);
  112046. else
  112047. _analysis_output("mask0R",seq,logmask,n/2,1,0,0);
  112048. #endif
  112049. floor_posts[i][0]=
  112050. floor1_fit(vb,b->flr[info->floorsubmap[submap]],
  112051. logmdct,
  112052. logmask);
  112053. /* we also interpolate a range of intermediate curves for
  112054. intermediate rates */
  112055. for(k=1;k<PACKETBLOBS/2;k++)
  112056. floor_posts[i][k]=
  112057. floor1_interpolate_fit(vb,b->flr[info->floorsubmap[submap]],
  112058. floor_posts[i][0],
  112059. floor_posts[i][PACKETBLOBS/2],
  112060. k*65536/(PACKETBLOBS/2));
  112061. for(k=PACKETBLOBS/2+1;k<PACKETBLOBS-1;k++)
  112062. floor_posts[i][k]=
  112063. floor1_interpolate_fit(vb,b->flr[info->floorsubmap[submap]],
  112064. floor_posts[i][PACKETBLOBS/2],
  112065. floor_posts[i][PACKETBLOBS-1],
  112066. (k-PACKETBLOBS/2)*65536/(PACKETBLOBS/2));
  112067. }
  112068. }
  112069. }
  112070. vbi->ampmax=global_ampmax;
  112071. /*
  112072. the next phases are performed once for vbr-only and PACKETBLOB
  112073. times for bitrate managed modes.
  112074. 1) encode actual mode being used
  112075. 2) encode the floor for each channel, compute coded mask curve/res
  112076. 3) normalize and couple.
  112077. 4) encode residue
  112078. 5) save packet bytes to the packetblob vector
  112079. */
  112080. /* iterate over the many masking curve fits we've created */
  112081. {
  112082. float **res_bundle=(float**) alloca(sizeof(*res_bundle)*vi->channels);
  112083. float **couple_bundle=(float**) alloca(sizeof(*couple_bundle)*vi->channels);
  112084. int *zerobundle=(int*) alloca(sizeof(*zerobundle)*vi->channels);
  112085. int **sortindex=(int**) alloca(sizeof(*sortindex)*vi->channels);
  112086. float **mag_memo;
  112087. int **mag_sort;
  112088. if(info->coupling_steps){
  112089. mag_memo=_vp_quantize_couple_memo(vb,
  112090. &ci->psy_g_param,
  112091. psy_look,
  112092. info,
  112093. gmdct);
  112094. mag_sort=_vp_quantize_couple_sort(vb,
  112095. psy_look,
  112096. info,
  112097. mag_memo);
  112098. hf_reduction(&ci->psy_g_param,
  112099. psy_look,
  112100. info,
  112101. mag_memo);
  112102. }
  112103. memset(sortindex,0,sizeof(*sortindex)*vi->channels);
  112104. if(psy_look->vi->normal_channel_p){
  112105. for(i=0;i<vi->channels;i++){
  112106. float *mdct =gmdct[i];
  112107. sortindex[i]=(int*) alloca(sizeof(**sortindex)*n/2);
  112108. _vp_noise_normalize_sort(psy_look,mdct,sortindex[i]);
  112109. }
  112110. }
  112111. for(k=(vorbis_bitrate_managed(vb)?0:PACKETBLOBS/2);
  112112. k<=(vorbis_bitrate_managed(vb)?PACKETBLOBS-1:PACKETBLOBS/2);
  112113. k++){
  112114. oggpack_buffer *opb=vbi->packetblob[k];
  112115. /* start out our new packet blob with packet type and mode */
  112116. /* Encode the packet type */
  112117. oggpack_write(opb,0,1);
  112118. /* Encode the modenumber */
  112119. /* Encode frame mode, pre,post windowsize, then dispatch */
  112120. oggpack_write(opb,modenumber,b->modebits);
  112121. if(vb->W){
  112122. oggpack_write(opb,vb->lW,1);
  112123. oggpack_write(opb,vb->nW,1);
  112124. }
  112125. /* encode floor, compute masking curve, sep out residue */
  112126. for(i=0;i<vi->channels;i++){
  112127. int submap=info->chmuxlist[i];
  112128. float *mdct =gmdct[i];
  112129. float *res =vb->pcm[i];
  112130. int *ilogmask=ilogmaskch[i]=
  112131. (int*) _vorbis_block_alloc(vb,n/2*sizeof(**gmdct));
  112132. nonzero[i]=floor1_encode(opb,vb,b->flr[info->floorsubmap[submap]],
  112133. floor_posts[i][k],
  112134. ilogmask);
  112135. #if 0
  112136. {
  112137. char buf[80];
  112138. sprintf(buf,"maskI%c%d",i?'R':'L',k);
  112139. float work[n/2];
  112140. for(j=0;j<n/2;j++)
  112141. work[j]=FLOOR1_fromdB_LOOKUP[ilogmask[j]];
  112142. _analysis_output(buf,seq,work,n/2,1,1,0);
  112143. }
  112144. #endif
  112145. _vp_remove_floor(psy_look,
  112146. mdct,
  112147. ilogmask,
  112148. res,
  112149. ci->psy_g_param.sliding_lowpass[vb->W][k]);
  112150. _vp_noise_normalize(psy_look,res,res+n/2,sortindex[i]);
  112151. #if 0
  112152. {
  112153. char buf[80];
  112154. float work[n/2];
  112155. for(j=0;j<n/2;j++)
  112156. work[j]=FLOOR1_fromdB_LOOKUP[ilogmask[j]]*(res+n/2)[j];
  112157. sprintf(buf,"resI%c%d",i?'R':'L',k);
  112158. _analysis_output(buf,seq,work,n/2,1,1,0);
  112159. }
  112160. #endif
  112161. }
  112162. /* our iteration is now based on masking curve, not prequant and
  112163. coupling. Only one prequant/coupling step */
  112164. /* quantize/couple */
  112165. /* incomplete implementation that assumes the tree is all depth
  112166. one, or no tree at all */
  112167. if(info->coupling_steps){
  112168. _vp_couple(k,
  112169. &ci->psy_g_param,
  112170. psy_look,
  112171. info,
  112172. vb->pcm,
  112173. mag_memo,
  112174. mag_sort,
  112175. ilogmaskch,
  112176. nonzero,
  112177. ci->psy_g_param.sliding_lowpass[vb->W][k]);
  112178. }
  112179. /* classify and encode by submap */
  112180. for(i=0;i<info->submaps;i++){
  112181. int ch_in_bundle=0;
  112182. long **classifications;
  112183. int resnum=info->residuesubmap[i];
  112184. for(j=0;j<vi->channels;j++){
  112185. if(info->chmuxlist[j]==i){
  112186. zerobundle[ch_in_bundle]=0;
  112187. if(nonzero[j])zerobundle[ch_in_bundle]=1;
  112188. res_bundle[ch_in_bundle]=vb->pcm[j];
  112189. couple_bundle[ch_in_bundle++]=vb->pcm[j]+n/2;
  112190. }
  112191. }
  112192. classifications=_residue_P[ci->residue_type[resnum]]->
  112193. classx(vb,b->residue[resnum],couple_bundle,zerobundle,ch_in_bundle);
  112194. _residue_P[ci->residue_type[resnum]]->
  112195. forward(opb,vb,b->residue[resnum],
  112196. couple_bundle,NULL,zerobundle,ch_in_bundle,classifications);
  112197. }
  112198. /* ok, done encoding. Next protopacket. */
  112199. }
  112200. }
  112201. #if 0
  112202. seq++;
  112203. total+=ci->blocksizes[vb->W]/4+ci->blocksizes[vb->nW]/4;
  112204. #endif
  112205. return(0);
  112206. }
  112207. static int mapping0_inverse(vorbis_block *vb,vorbis_info_mapping *l){
  112208. vorbis_dsp_state *vd=vb->vd;
  112209. vorbis_info *vi=vd->vi;
  112210. codec_setup_info *ci=(codec_setup_info*) vi->codec_setup;
  112211. private_state *b=(private_state*)vd->backend_state;
  112212. vorbis_info_mapping0 *info=(vorbis_info_mapping0 *)l;
  112213. int i,j;
  112214. long n=vb->pcmend=ci->blocksizes[vb->W];
  112215. float **pcmbundle=(float**) alloca(sizeof(*pcmbundle)*vi->channels);
  112216. int *zerobundle=(int*) alloca(sizeof(*zerobundle)*vi->channels);
  112217. int *nonzero =(int*) alloca(sizeof(*nonzero)*vi->channels);
  112218. void **floormemo=(void**) alloca(sizeof(*floormemo)*vi->channels);
  112219. /* recover the spectral envelope; store it in the PCM vector for now */
  112220. for(i=0;i<vi->channels;i++){
  112221. int submap=info->chmuxlist[i];
  112222. floormemo[i]=_floor_P[ci->floor_type[info->floorsubmap[submap]]]->
  112223. inverse1(vb,b->flr[info->floorsubmap[submap]]);
  112224. if(floormemo[i])
  112225. nonzero[i]=1;
  112226. else
  112227. nonzero[i]=0;
  112228. memset(vb->pcm[i],0,sizeof(*vb->pcm[i])*n/2);
  112229. }
  112230. /* channel coupling can 'dirty' the nonzero listing */
  112231. for(i=0;i<info->coupling_steps;i++){
  112232. if(nonzero[info->coupling_mag[i]] ||
  112233. nonzero[info->coupling_ang[i]]){
  112234. nonzero[info->coupling_mag[i]]=1;
  112235. nonzero[info->coupling_ang[i]]=1;
  112236. }
  112237. }
  112238. /* recover the residue into our working vectors */
  112239. for(i=0;i<info->submaps;i++){
  112240. int ch_in_bundle=0;
  112241. for(j=0;j<vi->channels;j++){
  112242. if(info->chmuxlist[j]==i){
  112243. if(nonzero[j])
  112244. zerobundle[ch_in_bundle]=1;
  112245. else
  112246. zerobundle[ch_in_bundle]=0;
  112247. pcmbundle[ch_in_bundle++]=vb->pcm[j];
  112248. }
  112249. }
  112250. _residue_P[ci->residue_type[info->residuesubmap[i]]]->
  112251. inverse(vb,b->residue[info->residuesubmap[i]],
  112252. pcmbundle,zerobundle,ch_in_bundle);
  112253. }
  112254. /* channel coupling */
  112255. for(i=info->coupling_steps-1;i>=0;i--){
  112256. float *pcmM=vb->pcm[info->coupling_mag[i]];
  112257. float *pcmA=vb->pcm[info->coupling_ang[i]];
  112258. for(j=0;j<n/2;j++){
  112259. float mag=pcmM[j];
  112260. float ang=pcmA[j];
  112261. if(mag>0)
  112262. if(ang>0){
  112263. pcmM[j]=mag;
  112264. pcmA[j]=mag-ang;
  112265. }else{
  112266. pcmA[j]=mag;
  112267. pcmM[j]=mag+ang;
  112268. }
  112269. else
  112270. if(ang>0){
  112271. pcmM[j]=mag;
  112272. pcmA[j]=mag+ang;
  112273. }else{
  112274. pcmA[j]=mag;
  112275. pcmM[j]=mag-ang;
  112276. }
  112277. }
  112278. }
  112279. /* compute and apply spectral envelope */
  112280. for(i=0;i<vi->channels;i++){
  112281. float *pcm=vb->pcm[i];
  112282. int submap=info->chmuxlist[i];
  112283. _floor_P[ci->floor_type[info->floorsubmap[submap]]]->
  112284. inverse2(vb,b->flr[info->floorsubmap[submap]],
  112285. floormemo[i],pcm);
  112286. }
  112287. /* transform the PCM data; takes PCM vector, vb; modifies PCM vector */
  112288. /* only MDCT right now.... */
  112289. for(i=0;i<vi->channels;i++){
  112290. float *pcm=vb->pcm[i];
  112291. mdct_backward((mdct_lookup*) b->transform[vb->W][0],pcm,pcm);
  112292. }
  112293. /* all done! */
  112294. return(0);
  112295. }
  112296. /* export hooks */
  112297. vorbis_func_mapping mapping0_exportbundle={
  112298. &mapping0_pack,
  112299. &mapping0_unpack,
  112300. &mapping0_free_info,
  112301. &mapping0_forward,
  112302. &mapping0_inverse
  112303. };
  112304. #endif
  112305. /*** End of inlined file: mapping0.c ***/
  112306. /*** Start of inlined file: mdct.c ***/
  112307. /* this can also be run as an integer transform by uncommenting a
  112308. define in mdct.h; the integerization is a first pass and although
  112309. it's likely stable for Vorbis, the dynamic range is constrained and
  112310. roundoff isn't done (so it's noisy). Consider it functional, but
  112311. only a starting point. There's no point on a machine with an FPU */
  112312. /*** Start of inlined file: juce_OggVorbisHeader.h ***/
  112313. // This file is included at the start of each Ogg-Vorbis .c file, just to do a few housekeeping
  112314. // tasks..
  112315. #if JUCE_MSVC
  112316. #pragma warning (disable: 4267 4127 4244 4996 4100 4701 4702 4013 4133 4206 4305 4189 4706)
  112317. #endif
  112318. /*** End of inlined file: juce_OggVorbisHeader.h ***/
  112319. #if JUCE_USE_OGGVORBIS
  112320. #include <stdio.h>
  112321. #include <stdlib.h>
  112322. #include <string.h>
  112323. #include <math.h>
  112324. /* build lookups for trig functions; also pre-figure scaling and
  112325. some window function algebra. */
  112326. void mdct_init(mdct_lookup *lookup,int n){
  112327. int *bitrev=(int*) _ogg_malloc(sizeof(*bitrev)*(n/4));
  112328. DATA_TYPE *T=(DATA_TYPE*) _ogg_malloc(sizeof(*T)*(n+n/4));
  112329. int i;
  112330. int n2=n>>1;
  112331. int log2n=lookup->log2n=rint(log((float)n)/log(2.f));
  112332. lookup->n=n;
  112333. lookup->trig=T;
  112334. lookup->bitrev=bitrev;
  112335. /* trig lookups... */
  112336. for(i=0;i<n/4;i++){
  112337. T[i*2]=FLOAT_CONV(cos((M_PI/n)*(4*i)));
  112338. T[i*2+1]=FLOAT_CONV(-sin((M_PI/n)*(4*i)));
  112339. T[n2+i*2]=FLOAT_CONV(cos((M_PI/(2*n))*(2*i+1)));
  112340. T[n2+i*2+1]=FLOAT_CONV(sin((M_PI/(2*n))*(2*i+1)));
  112341. }
  112342. for(i=0;i<n/8;i++){
  112343. T[n+i*2]=FLOAT_CONV(cos((M_PI/n)*(4*i+2))*.5);
  112344. T[n+i*2+1]=FLOAT_CONV(-sin((M_PI/n)*(4*i+2))*.5);
  112345. }
  112346. /* bitreverse lookup... */
  112347. {
  112348. int mask=(1<<(log2n-1))-1,i,j;
  112349. int msb=1<<(log2n-2);
  112350. for(i=0;i<n/8;i++){
  112351. int acc=0;
  112352. for(j=0;msb>>j;j++)
  112353. if((msb>>j)&i)acc|=1<<j;
  112354. bitrev[i*2]=((~acc)&mask)-1;
  112355. bitrev[i*2+1]=acc;
  112356. }
  112357. }
  112358. lookup->scale=FLOAT_CONV(4.f/n);
  112359. }
  112360. /* 8 point butterfly (in place, 4 register) */
  112361. STIN void mdct_butterfly_8(DATA_TYPE *x){
  112362. REG_TYPE r0 = x[6] + x[2];
  112363. REG_TYPE r1 = x[6] - x[2];
  112364. REG_TYPE r2 = x[4] + x[0];
  112365. REG_TYPE r3 = x[4] - x[0];
  112366. x[6] = r0 + r2;
  112367. x[4] = r0 - r2;
  112368. r0 = x[5] - x[1];
  112369. r2 = x[7] - x[3];
  112370. x[0] = r1 + r0;
  112371. x[2] = r1 - r0;
  112372. r0 = x[5] + x[1];
  112373. r1 = x[7] + x[3];
  112374. x[3] = r2 + r3;
  112375. x[1] = r2 - r3;
  112376. x[7] = r1 + r0;
  112377. x[5] = r1 - r0;
  112378. }
  112379. /* 16 point butterfly (in place, 4 register) */
  112380. STIN void mdct_butterfly_16(DATA_TYPE *x){
  112381. REG_TYPE r0 = x[1] - x[9];
  112382. REG_TYPE r1 = x[0] - x[8];
  112383. x[8] += x[0];
  112384. x[9] += x[1];
  112385. x[0] = MULT_NORM((r0 + r1) * cPI2_8);
  112386. x[1] = MULT_NORM((r0 - r1) * cPI2_8);
  112387. r0 = x[3] - x[11];
  112388. r1 = x[10] - x[2];
  112389. x[10] += x[2];
  112390. x[11] += x[3];
  112391. x[2] = r0;
  112392. x[3] = r1;
  112393. r0 = x[12] - x[4];
  112394. r1 = x[13] - x[5];
  112395. x[12] += x[4];
  112396. x[13] += x[5];
  112397. x[4] = MULT_NORM((r0 - r1) * cPI2_8);
  112398. x[5] = MULT_NORM((r0 + r1) * cPI2_8);
  112399. r0 = x[14] - x[6];
  112400. r1 = x[15] - x[7];
  112401. x[14] += x[6];
  112402. x[15] += x[7];
  112403. x[6] = r0;
  112404. x[7] = r1;
  112405. mdct_butterfly_8(x);
  112406. mdct_butterfly_8(x+8);
  112407. }
  112408. /* 32 point butterfly (in place, 4 register) */
  112409. STIN void mdct_butterfly_32(DATA_TYPE *x){
  112410. REG_TYPE r0 = x[30] - x[14];
  112411. REG_TYPE r1 = x[31] - x[15];
  112412. x[30] += x[14];
  112413. x[31] += x[15];
  112414. x[14] = r0;
  112415. x[15] = r1;
  112416. r0 = x[28] - x[12];
  112417. r1 = x[29] - x[13];
  112418. x[28] += x[12];
  112419. x[29] += x[13];
  112420. x[12] = MULT_NORM( r0 * cPI1_8 - r1 * cPI3_8 );
  112421. x[13] = MULT_NORM( r0 * cPI3_8 + r1 * cPI1_8 );
  112422. r0 = x[26] - x[10];
  112423. r1 = x[27] - x[11];
  112424. x[26] += x[10];
  112425. x[27] += x[11];
  112426. x[10] = MULT_NORM(( r0 - r1 ) * cPI2_8);
  112427. x[11] = MULT_NORM(( r0 + r1 ) * cPI2_8);
  112428. r0 = x[24] - x[8];
  112429. r1 = x[25] - x[9];
  112430. x[24] += x[8];
  112431. x[25] += x[9];
  112432. x[8] = MULT_NORM( r0 * cPI3_8 - r1 * cPI1_8 );
  112433. x[9] = MULT_NORM( r1 * cPI3_8 + r0 * cPI1_8 );
  112434. r0 = x[22] - x[6];
  112435. r1 = x[7] - x[23];
  112436. x[22] += x[6];
  112437. x[23] += x[7];
  112438. x[6] = r1;
  112439. x[7] = r0;
  112440. r0 = x[4] - x[20];
  112441. r1 = x[5] - x[21];
  112442. x[20] += x[4];
  112443. x[21] += x[5];
  112444. x[4] = MULT_NORM( r1 * cPI1_8 + r0 * cPI3_8 );
  112445. x[5] = MULT_NORM( r1 * cPI3_8 - r0 * cPI1_8 );
  112446. r0 = x[2] - x[18];
  112447. r1 = x[3] - x[19];
  112448. x[18] += x[2];
  112449. x[19] += x[3];
  112450. x[2] = MULT_NORM(( r1 + r0 ) * cPI2_8);
  112451. x[3] = MULT_NORM(( r1 - r0 ) * cPI2_8);
  112452. r0 = x[0] - x[16];
  112453. r1 = x[1] - x[17];
  112454. x[16] += x[0];
  112455. x[17] += x[1];
  112456. x[0] = MULT_NORM( r1 * cPI3_8 + r0 * cPI1_8 );
  112457. x[1] = MULT_NORM( r1 * cPI1_8 - r0 * cPI3_8 );
  112458. mdct_butterfly_16(x);
  112459. mdct_butterfly_16(x+16);
  112460. }
  112461. /* N point first stage butterfly (in place, 2 register) */
  112462. STIN void mdct_butterfly_first(DATA_TYPE *T,
  112463. DATA_TYPE *x,
  112464. int points){
  112465. DATA_TYPE *x1 = x + points - 8;
  112466. DATA_TYPE *x2 = x + (points>>1) - 8;
  112467. REG_TYPE r0;
  112468. REG_TYPE r1;
  112469. do{
  112470. r0 = x1[6] - x2[6];
  112471. r1 = x1[7] - x2[7];
  112472. x1[6] += x2[6];
  112473. x1[7] += x2[7];
  112474. x2[6] = MULT_NORM(r1 * T[1] + r0 * T[0]);
  112475. x2[7] = MULT_NORM(r1 * T[0] - r0 * T[1]);
  112476. r0 = x1[4] - x2[4];
  112477. r1 = x1[5] - x2[5];
  112478. x1[4] += x2[4];
  112479. x1[5] += x2[5];
  112480. x2[4] = MULT_NORM(r1 * T[5] + r0 * T[4]);
  112481. x2[5] = MULT_NORM(r1 * T[4] - r0 * T[5]);
  112482. r0 = x1[2] - x2[2];
  112483. r1 = x1[3] - x2[3];
  112484. x1[2] += x2[2];
  112485. x1[3] += x2[3];
  112486. x2[2] = MULT_NORM(r1 * T[9] + r0 * T[8]);
  112487. x2[3] = MULT_NORM(r1 * T[8] - r0 * T[9]);
  112488. r0 = x1[0] - x2[0];
  112489. r1 = x1[1] - x2[1];
  112490. x1[0] += x2[0];
  112491. x1[1] += x2[1];
  112492. x2[0] = MULT_NORM(r1 * T[13] + r0 * T[12]);
  112493. x2[1] = MULT_NORM(r1 * T[12] - r0 * T[13]);
  112494. x1-=8;
  112495. x2-=8;
  112496. T+=16;
  112497. }while(x2>=x);
  112498. }
  112499. /* N/stage point generic N stage butterfly (in place, 2 register) */
  112500. STIN void mdct_butterfly_generic(DATA_TYPE *T,
  112501. DATA_TYPE *x,
  112502. int points,
  112503. int trigint){
  112504. DATA_TYPE *x1 = x + points - 8;
  112505. DATA_TYPE *x2 = x + (points>>1) - 8;
  112506. REG_TYPE r0;
  112507. REG_TYPE r1;
  112508. do{
  112509. r0 = x1[6] - x2[6];
  112510. r1 = x1[7] - x2[7];
  112511. x1[6] += x2[6];
  112512. x1[7] += x2[7];
  112513. x2[6] = MULT_NORM(r1 * T[1] + r0 * T[0]);
  112514. x2[7] = MULT_NORM(r1 * T[0] - r0 * T[1]);
  112515. T+=trigint;
  112516. r0 = x1[4] - x2[4];
  112517. r1 = x1[5] - x2[5];
  112518. x1[4] += x2[4];
  112519. x1[5] += x2[5];
  112520. x2[4] = MULT_NORM(r1 * T[1] + r0 * T[0]);
  112521. x2[5] = MULT_NORM(r1 * T[0] - r0 * T[1]);
  112522. T+=trigint;
  112523. r0 = x1[2] - x2[2];
  112524. r1 = x1[3] - x2[3];
  112525. x1[2] += x2[2];
  112526. x1[3] += x2[3];
  112527. x2[2] = MULT_NORM(r1 * T[1] + r0 * T[0]);
  112528. x2[3] = MULT_NORM(r1 * T[0] - r0 * T[1]);
  112529. T+=trigint;
  112530. r0 = x1[0] - x2[0];
  112531. r1 = x1[1] - x2[1];
  112532. x1[0] += x2[0];
  112533. x1[1] += x2[1];
  112534. x2[0] = MULT_NORM(r1 * T[1] + r0 * T[0]);
  112535. x2[1] = MULT_NORM(r1 * T[0] - r0 * T[1]);
  112536. T+=trigint;
  112537. x1-=8;
  112538. x2-=8;
  112539. }while(x2>=x);
  112540. }
  112541. STIN void mdct_butterflies(mdct_lookup *init,
  112542. DATA_TYPE *x,
  112543. int points){
  112544. DATA_TYPE *T=init->trig;
  112545. int stages=init->log2n-5;
  112546. int i,j;
  112547. if(--stages>0){
  112548. mdct_butterfly_first(T,x,points);
  112549. }
  112550. for(i=1;--stages>0;i++){
  112551. for(j=0;j<(1<<i);j++)
  112552. mdct_butterfly_generic(T,x+(points>>i)*j,points>>i,4<<i);
  112553. }
  112554. for(j=0;j<points;j+=32)
  112555. mdct_butterfly_32(x+j);
  112556. }
  112557. void mdct_clear(mdct_lookup *l){
  112558. if(l){
  112559. if(l->trig)_ogg_free(l->trig);
  112560. if(l->bitrev)_ogg_free(l->bitrev);
  112561. memset(l,0,sizeof(*l));
  112562. }
  112563. }
  112564. STIN void mdct_bitreverse(mdct_lookup *init,
  112565. DATA_TYPE *x){
  112566. int n = init->n;
  112567. int *bit = init->bitrev;
  112568. DATA_TYPE *w0 = x;
  112569. DATA_TYPE *w1 = x = w0+(n>>1);
  112570. DATA_TYPE *T = init->trig+n;
  112571. do{
  112572. DATA_TYPE *x0 = x+bit[0];
  112573. DATA_TYPE *x1 = x+bit[1];
  112574. REG_TYPE r0 = x0[1] - x1[1];
  112575. REG_TYPE r1 = x0[0] + x1[0];
  112576. REG_TYPE r2 = MULT_NORM(r1 * T[0] + r0 * T[1]);
  112577. REG_TYPE r3 = MULT_NORM(r1 * T[1] - r0 * T[0]);
  112578. w1 -= 4;
  112579. r0 = HALVE(x0[1] + x1[1]);
  112580. r1 = HALVE(x0[0] - x1[0]);
  112581. w0[0] = r0 + r2;
  112582. w1[2] = r0 - r2;
  112583. w0[1] = r1 + r3;
  112584. w1[3] = r3 - r1;
  112585. x0 = x+bit[2];
  112586. x1 = x+bit[3];
  112587. r0 = x0[1] - x1[1];
  112588. r1 = x0[0] + x1[0];
  112589. r2 = MULT_NORM(r1 * T[2] + r0 * T[3]);
  112590. r3 = MULT_NORM(r1 * T[3] - r0 * T[2]);
  112591. r0 = HALVE(x0[1] + x1[1]);
  112592. r1 = HALVE(x0[0] - x1[0]);
  112593. w0[2] = r0 + r2;
  112594. w1[0] = r0 - r2;
  112595. w0[3] = r1 + r3;
  112596. w1[1] = r3 - r1;
  112597. T += 4;
  112598. bit += 4;
  112599. w0 += 4;
  112600. }while(w0<w1);
  112601. }
  112602. void mdct_backward(mdct_lookup *init, DATA_TYPE *in, DATA_TYPE *out){
  112603. int n=init->n;
  112604. int n2=n>>1;
  112605. int n4=n>>2;
  112606. /* rotate */
  112607. DATA_TYPE *iX = in+n2-7;
  112608. DATA_TYPE *oX = out+n2+n4;
  112609. DATA_TYPE *T = init->trig+n4;
  112610. do{
  112611. oX -= 4;
  112612. oX[0] = MULT_NORM(-iX[2] * T[3] - iX[0] * T[2]);
  112613. oX[1] = MULT_NORM (iX[0] * T[3] - iX[2] * T[2]);
  112614. oX[2] = MULT_NORM(-iX[6] * T[1] - iX[4] * T[0]);
  112615. oX[3] = MULT_NORM (iX[4] * T[1] - iX[6] * T[0]);
  112616. iX -= 8;
  112617. T += 4;
  112618. }while(iX>=in);
  112619. iX = in+n2-8;
  112620. oX = out+n2+n4;
  112621. T = init->trig+n4;
  112622. do{
  112623. T -= 4;
  112624. oX[0] = MULT_NORM (iX[4] * T[3] + iX[6] * T[2]);
  112625. oX[1] = MULT_NORM (iX[4] * T[2] - iX[6] * T[3]);
  112626. oX[2] = MULT_NORM (iX[0] * T[1] + iX[2] * T[0]);
  112627. oX[3] = MULT_NORM (iX[0] * T[0] - iX[2] * T[1]);
  112628. iX -= 8;
  112629. oX += 4;
  112630. }while(iX>=in);
  112631. mdct_butterflies(init,out+n2,n2);
  112632. mdct_bitreverse(init,out);
  112633. /* roatate + window */
  112634. {
  112635. DATA_TYPE *oX1=out+n2+n4;
  112636. DATA_TYPE *oX2=out+n2+n4;
  112637. DATA_TYPE *iX =out;
  112638. T =init->trig+n2;
  112639. do{
  112640. oX1-=4;
  112641. oX1[3] = MULT_NORM (iX[0] * T[1] - iX[1] * T[0]);
  112642. oX2[0] = -MULT_NORM (iX[0] * T[0] + iX[1] * T[1]);
  112643. oX1[2] = MULT_NORM (iX[2] * T[3] - iX[3] * T[2]);
  112644. oX2[1] = -MULT_NORM (iX[2] * T[2] + iX[3] * T[3]);
  112645. oX1[1] = MULT_NORM (iX[4] * T[5] - iX[5] * T[4]);
  112646. oX2[2] = -MULT_NORM (iX[4] * T[4] + iX[5] * T[5]);
  112647. oX1[0] = MULT_NORM (iX[6] * T[7] - iX[7] * T[6]);
  112648. oX2[3] = -MULT_NORM (iX[6] * T[6] + iX[7] * T[7]);
  112649. oX2+=4;
  112650. iX += 8;
  112651. T += 8;
  112652. }while(iX<oX1);
  112653. iX=out+n2+n4;
  112654. oX1=out+n4;
  112655. oX2=oX1;
  112656. do{
  112657. oX1-=4;
  112658. iX-=4;
  112659. oX2[0] = -(oX1[3] = iX[3]);
  112660. oX2[1] = -(oX1[2] = iX[2]);
  112661. oX2[2] = -(oX1[1] = iX[1]);
  112662. oX2[3] = -(oX1[0] = iX[0]);
  112663. oX2+=4;
  112664. }while(oX2<iX);
  112665. iX=out+n2+n4;
  112666. oX1=out+n2+n4;
  112667. oX2=out+n2;
  112668. do{
  112669. oX1-=4;
  112670. oX1[0]= iX[3];
  112671. oX1[1]= iX[2];
  112672. oX1[2]= iX[1];
  112673. oX1[3]= iX[0];
  112674. iX+=4;
  112675. }while(oX1>oX2);
  112676. }
  112677. }
  112678. void mdct_forward(mdct_lookup *init, DATA_TYPE *in, DATA_TYPE *out){
  112679. int n=init->n;
  112680. int n2=n>>1;
  112681. int n4=n>>2;
  112682. int n8=n>>3;
  112683. DATA_TYPE *w=(DATA_TYPE*) alloca(n*sizeof(*w)); /* forward needs working space */
  112684. DATA_TYPE *w2=w+n2;
  112685. /* rotate */
  112686. /* window + rotate + step 1 */
  112687. REG_TYPE r0;
  112688. REG_TYPE r1;
  112689. DATA_TYPE *x0=in+n2+n4;
  112690. DATA_TYPE *x1=x0+1;
  112691. DATA_TYPE *T=init->trig+n2;
  112692. int i=0;
  112693. for(i=0;i<n8;i+=2){
  112694. x0 -=4;
  112695. T-=2;
  112696. r0= x0[2] + x1[0];
  112697. r1= x0[0] + x1[2];
  112698. w2[i]= MULT_NORM(r1*T[1] + r0*T[0]);
  112699. w2[i+1]= MULT_NORM(r1*T[0] - r0*T[1]);
  112700. x1 +=4;
  112701. }
  112702. x1=in+1;
  112703. for(;i<n2-n8;i+=2){
  112704. T-=2;
  112705. x0 -=4;
  112706. r0= x0[2] - x1[0];
  112707. r1= x0[0] - x1[2];
  112708. w2[i]= MULT_NORM(r1*T[1] + r0*T[0]);
  112709. w2[i+1]= MULT_NORM(r1*T[0] - r0*T[1]);
  112710. x1 +=4;
  112711. }
  112712. x0=in+n;
  112713. for(;i<n2;i+=2){
  112714. T-=2;
  112715. x0 -=4;
  112716. r0= -x0[2] - x1[0];
  112717. r1= -x0[0] - x1[2];
  112718. w2[i]= MULT_NORM(r1*T[1] + r0*T[0]);
  112719. w2[i+1]= MULT_NORM(r1*T[0] - r0*T[1]);
  112720. x1 +=4;
  112721. }
  112722. mdct_butterflies(init,w+n2,n2);
  112723. mdct_bitreverse(init,w);
  112724. /* roatate + window */
  112725. T=init->trig+n2;
  112726. x0=out+n2;
  112727. for(i=0;i<n4;i++){
  112728. x0--;
  112729. out[i] =MULT_NORM((w[0]*T[0]+w[1]*T[1])*init->scale);
  112730. x0[0] =MULT_NORM((w[0]*T[1]-w[1]*T[0])*init->scale);
  112731. w+=2;
  112732. T+=2;
  112733. }
  112734. }
  112735. #endif
  112736. /*** End of inlined file: mdct.c ***/
  112737. /*** Start of inlined file: psy.c ***/
  112738. /*** Start of inlined file: juce_OggVorbisHeader.h ***/
  112739. // This file is included at the start of each Ogg-Vorbis .c file, just to do a few housekeeping
  112740. // tasks..
  112741. #if JUCE_MSVC
  112742. #pragma warning (disable: 4267 4127 4244 4996 4100 4701 4702 4013 4133 4206 4305 4189 4706)
  112743. #endif
  112744. /*** End of inlined file: juce_OggVorbisHeader.h ***/
  112745. #if JUCE_USE_OGGVORBIS
  112746. #include <stdlib.h>
  112747. #include <math.h>
  112748. #include <string.h>
  112749. /*** Start of inlined file: masking.h ***/
  112750. #ifndef _V_MASKING_H_
  112751. #define _V_MASKING_H_
  112752. /* more detailed ATH; the bass if flat to save stressing the floor
  112753. overly for only a bin or two of savings. */
  112754. #define MAX_ATH 88
  112755. static float ATH[]={
  112756. /*15*/ -51, -52, -53, -54, -55, -56, -57, -58,
  112757. /*31*/ -59, -60, -61, -62, -63, -64, -65, -66,
  112758. /*63*/ -67, -68, -69, -70, -71, -72, -73, -74,
  112759. /*125*/ -75, -76, -77, -78, -80, -81, -82, -83,
  112760. /*250*/ -84, -85, -86, -87, -88, -88, -89, -89,
  112761. /*500*/ -90, -91, -91, -92, -93, -94, -95, -96,
  112762. /*1k*/ -96, -97, -98, -98, -99, -99,-100,-100,
  112763. /*2k*/ -101,-102,-103,-104,-106,-107,-107,-107,
  112764. /*4k*/ -107,-105,-103,-102,-101, -99, -98, -96,
  112765. /*8k*/ -95, -95, -96, -97, -96, -95, -93, -90,
  112766. /*16k*/ -80, -70, -50, -40, -30, -30, -30, -30
  112767. };
  112768. /* The tone masking curves from Ehmer's and Fielder's papers have been
  112769. replaced by an empirically collected data set. The previously
  112770. published values were, far too often, simply on crack. */
  112771. #define EHMER_OFFSET 16
  112772. #define EHMER_MAX 56
  112773. /* masking tones from -50 to 0dB, 62.5 through 16kHz at half octaves
  112774. test tones from -2 octaves to +5 octaves sampled at eighth octaves */
  112775. /* (Vorbis 0dB, the loudest possible tone, is assumed to be ~100dB SPL
  112776. for collection of these curves) */
  112777. static float tonemasks[P_BANDS][6][EHMER_MAX]={
  112778. /* 62.5 Hz */
  112779. {{ -60, -60, -60, -60, -60, -60, -60, -60,
  112780. -60, -60, -60, -60, -62, -62, -65, -73,
  112781. -69, -68, -68, -67, -70, -70, -72, -74,
  112782. -75, -79, -79, -80, -83, -88, -93, -100,
  112783. -110, -999, -999, -999, -999, -999, -999, -999,
  112784. -999, -999, -999, -999, -999, -999, -999, -999,
  112785. -999, -999, -999, -999, -999, -999, -999, -999},
  112786. { -48, -48, -48, -48, -48, -48, -48, -48,
  112787. -48, -48, -48, -48, -48, -53, -61, -66,
  112788. -66, -68, -67, -70, -76, -76, -72, -73,
  112789. -75, -76, -78, -79, -83, -88, -93, -100,
  112790. -110, -999, -999, -999, -999, -999, -999, -999,
  112791. -999, -999, -999, -999, -999, -999, -999, -999,
  112792. -999, -999, -999, -999, -999, -999, -999, -999},
  112793. { -37, -37, -37, -37, -37, -37, -37, -37,
  112794. -38, -40, -42, -46, -48, -53, -55, -62,
  112795. -65, -58, -56, -56, -61, -60, -65, -67,
  112796. -69, -71, -77, -77, -78, -80, -82, -84,
  112797. -88, -93, -98, -106, -112, -999, -999, -999,
  112798. -999, -999, -999, -999, -999, -999, -999, -999,
  112799. -999, -999, -999, -999, -999, -999, -999, -999},
  112800. { -25, -25, -25, -25, -25, -25, -25, -25,
  112801. -25, -26, -27, -29, -32, -38, -48, -52,
  112802. -52, -50, -48, -48, -51, -52, -54, -60,
  112803. -67, -67, -66, -68, -69, -73, -73, -76,
  112804. -80, -81, -81, -85, -85, -86, -88, -93,
  112805. -100, -110, -999, -999, -999, -999, -999, -999,
  112806. -999, -999, -999, -999, -999, -999, -999, -999},
  112807. { -16, -16, -16, -16, -16, -16, -16, -16,
  112808. -17, -19, -20, -22, -26, -28, -31, -40,
  112809. -47, -39, -39, -40, -42, -43, -47, -51,
  112810. -57, -52, -55, -55, -60, -58, -62, -63,
  112811. -70, -67, -69, -72, -73, -77, -80, -82,
  112812. -83, -87, -90, -94, -98, -104, -115, -999,
  112813. -999, -999, -999, -999, -999, -999, -999, -999},
  112814. { -8, -8, -8, -8, -8, -8, -8, -8,
  112815. -8, -8, -10, -11, -15, -19, -25, -30,
  112816. -34, -31, -30, -31, -29, -32, -35, -42,
  112817. -48, -42, -44, -46, -50, -50, -51, -52,
  112818. -59, -54, -55, -55, -58, -62, -63, -66,
  112819. -72, -73, -76, -75, -78, -80, -80, -81,
  112820. -84, -88, -90, -94, -98, -101, -106, -110}},
  112821. /* 88Hz */
  112822. {{ -66, -66, -66, -66, -66, -66, -66, -66,
  112823. -66, -66, -66, -66, -66, -67, -67, -67,
  112824. -76, -72, -71, -74, -76, -76, -75, -78,
  112825. -79, -79, -81, -83, -86, -89, -93, -97,
  112826. -100, -105, -110, -999, -999, -999, -999, -999,
  112827. -999, -999, -999, -999, -999, -999, -999, -999,
  112828. -999, -999, -999, -999, -999, -999, -999, -999},
  112829. { -47, -47, -47, -47, -47, -47, -47, -47,
  112830. -47, -47, -47, -48, -51, -55, -59, -66,
  112831. -66, -66, -67, -66, -68, -69, -70, -74,
  112832. -79, -77, -77, -78, -80, -81, -82, -84,
  112833. -86, -88, -91, -95, -100, -108, -116, -999,
  112834. -999, -999, -999, -999, -999, -999, -999, -999,
  112835. -999, -999, -999, -999, -999, -999, -999, -999},
  112836. { -36, -36, -36, -36, -36, -36, -36, -36,
  112837. -36, -37, -37, -41, -44, -48, -51, -58,
  112838. -62, -60, -57, -59, -59, -60, -63, -65,
  112839. -72, -71, -70, -72, -74, -77, -76, -78,
  112840. -81, -81, -80, -83, -86, -91, -96, -100,
  112841. -105, -110, -999, -999, -999, -999, -999, -999,
  112842. -999, -999, -999, -999, -999, -999, -999, -999},
  112843. { -28, -28, -28, -28, -28, -28, -28, -28,
  112844. -28, -30, -32, -32, -33, -35, -41, -49,
  112845. -50, -49, -47, -48, -48, -52, -51, -57,
  112846. -65, -61, -59, -61, -64, -69, -70, -74,
  112847. -77, -77, -78, -81, -84, -85, -87, -90,
  112848. -92, -96, -100, -107, -112, -999, -999, -999,
  112849. -999, -999, -999, -999, -999, -999, -999, -999},
  112850. { -19, -19, -19, -19, -19, -19, -19, -19,
  112851. -20, -21, -23, -27, -30, -35, -36, -41,
  112852. -46, -44, -42, -40, -41, -41, -43, -48,
  112853. -55, -53, -52, -53, -56, -59, -58, -60,
  112854. -67, -66, -69, -71, -72, -75, -79, -81,
  112855. -84, -87, -90, -93, -97, -101, -107, -114,
  112856. -999, -999, -999, -999, -999, -999, -999, -999},
  112857. { -9, -9, -9, -9, -9, -9, -9, -9,
  112858. -11, -12, -12, -15, -16, -20, -23, -30,
  112859. -37, -34, -33, -34, -31, -32, -32, -38,
  112860. -47, -44, -41, -40, -47, -49, -46, -46,
  112861. -58, -50, -50, -54, -58, -62, -64, -67,
  112862. -67, -70, -72, -76, -79, -83, -87, -91,
  112863. -96, -100, -104, -110, -999, -999, -999, -999}},
  112864. /* 125 Hz */
  112865. {{ -62, -62, -62, -62, -62, -62, -62, -62,
  112866. -62, -62, -63, -64, -66, -67, -66, -68,
  112867. -75, -72, -76, -75, -76, -78, -79, -82,
  112868. -84, -85, -90, -94, -101, -110, -999, -999,
  112869. -999, -999, -999, -999, -999, -999, -999, -999,
  112870. -999, -999, -999, -999, -999, -999, -999, -999,
  112871. -999, -999, -999, -999, -999, -999, -999, -999},
  112872. { -59, -59, -59, -59, -59, -59, -59, -59,
  112873. -59, -59, -59, -60, -60, -61, -63, -66,
  112874. -71, -68, -70, -70, -71, -72, -72, -75,
  112875. -81, -78, -79, -82, -83, -86, -90, -97,
  112876. -103, -113, -999, -999, -999, -999, -999, -999,
  112877. -999, -999, -999, -999, -999, -999, -999, -999,
  112878. -999, -999, -999, -999, -999, -999, -999, -999},
  112879. { -53, -53, -53, -53, -53, -53, -53, -53,
  112880. -53, -54, -55, -57, -56, -57, -55, -61,
  112881. -65, -60, -60, -62, -63, -63, -66, -68,
  112882. -74, -73, -75, -75, -78, -80, -80, -82,
  112883. -85, -90, -96, -101, -108, -999, -999, -999,
  112884. -999, -999, -999, -999, -999, -999, -999, -999,
  112885. -999, -999, -999, -999, -999, -999, -999, -999},
  112886. { -46, -46, -46, -46, -46, -46, -46, -46,
  112887. -46, -46, -47, -47, -47, -47, -48, -51,
  112888. -57, -51, -49, -50, -51, -53, -54, -59,
  112889. -66, -60, -62, -67, -67, -70, -72, -75,
  112890. -76, -78, -81, -85, -88, -94, -97, -104,
  112891. -112, -999, -999, -999, -999, -999, -999, -999,
  112892. -999, -999, -999, -999, -999, -999, -999, -999},
  112893. { -36, -36, -36, -36, -36, -36, -36, -36,
  112894. -39, -41, -42, -42, -39, -38, -41, -43,
  112895. -52, -44, -40, -39, -37, -37, -40, -47,
  112896. -54, -50, -48, -50, -55, -61, -59, -62,
  112897. -66, -66, -66, -69, -69, -73, -74, -74,
  112898. -75, -77, -79, -82, -87, -91, -95, -100,
  112899. -108, -115, -999, -999, -999, -999, -999, -999},
  112900. { -28, -26, -24, -22, -20, -20, -23, -29,
  112901. -30, -31, -28, -27, -28, -28, -28, -35,
  112902. -40, -33, -32, -29, -30, -30, -30, -37,
  112903. -45, -41, -37, -38, -45, -47, -47, -48,
  112904. -53, -49, -48, -50, -49, -49, -51, -52,
  112905. -58, -56, -57, -56, -60, -61, -62, -70,
  112906. -72, -74, -78, -83, -88, -93, -100, -106}},
  112907. /* 177 Hz */
  112908. {{-999, -999, -999, -999, -999, -999, -999, -999,
  112909. -999, -110, -105, -100, -95, -91, -87, -83,
  112910. -80, -78, -76, -78, -78, -81, -83, -85,
  112911. -86, -85, -86, -87, -90, -97, -107, -999,
  112912. -999, -999, -999, -999, -999, -999, -999, -999,
  112913. -999, -999, -999, -999, -999, -999, -999, -999,
  112914. -999, -999, -999, -999, -999, -999, -999, -999},
  112915. {-999, -999, -999, -110, -105, -100, -95, -90,
  112916. -85, -81, -77, -73, -70, -67, -67, -68,
  112917. -75, -73, -70, -69, -70, -72, -75, -79,
  112918. -84, -83, -84, -86, -88, -89, -89, -93,
  112919. -98, -105, -112, -999, -999, -999, -999, -999,
  112920. -999, -999, -999, -999, -999, -999, -999, -999,
  112921. -999, -999, -999, -999, -999, -999, -999, -999},
  112922. {-105, -100, -95, -90, -85, -80, -76, -71,
  112923. -68, -68, -65, -63, -63, -62, -62, -64,
  112924. -65, -64, -61, -62, -63, -64, -66, -68,
  112925. -73, -73, -74, -75, -76, -81, -83, -85,
  112926. -88, -89, -92, -95, -100, -108, -999, -999,
  112927. -999, -999, -999, -999, -999, -999, -999, -999,
  112928. -999, -999, -999, -999, -999, -999, -999, -999},
  112929. { -80, -75, -71, -68, -65, -63, -62, -61,
  112930. -61, -61, -61, -59, -56, -57, -53, -50,
  112931. -58, -52, -50, -50, -52, -53, -54, -58,
  112932. -67, -63, -67, -68, -72, -75, -78, -80,
  112933. -81, -81, -82, -85, -89, -90, -93, -97,
  112934. -101, -107, -114, -999, -999, -999, -999, -999,
  112935. -999, -999, -999, -999, -999, -999, -999, -999},
  112936. { -65, -61, -59, -57, -56, -55, -55, -56,
  112937. -56, -57, -55, -53, -52, -47, -44, -44,
  112938. -50, -44, -41, -39, -39, -42, -40, -46,
  112939. -51, -49, -50, -53, -54, -63, -60, -61,
  112940. -62, -66, -66, -66, -70, -73, -74, -75,
  112941. -76, -75, -79, -85, -89, -91, -96, -102,
  112942. -110, -999, -999, -999, -999, -999, -999, -999},
  112943. { -52, -50, -49, -49, -48, -48, -48, -49,
  112944. -50, -50, -49, -46, -43, -39, -35, -33,
  112945. -38, -36, -32, -29, -32, -32, -32, -35,
  112946. -44, -39, -38, -38, -46, -50, -45, -46,
  112947. -53, -50, -50, -50, -54, -54, -53, -53,
  112948. -56, -57, -59, -66, -70, -72, -74, -79,
  112949. -83, -85, -90, -97, -114, -999, -999, -999}},
  112950. /* 250 Hz */
  112951. {{-999, -999, -999, -999, -999, -999, -110, -105,
  112952. -100, -95, -90, -86, -80, -75, -75, -79,
  112953. -80, -79, -80, -81, -82, -88, -95, -103,
  112954. -110, -999, -999, -999, -999, -999, -999, -999,
  112955. -999, -999, -999, -999, -999, -999, -999, -999,
  112956. -999, -999, -999, -999, -999, -999, -999, -999,
  112957. -999, -999, -999, -999, -999, -999, -999, -999},
  112958. {-999, -999, -999, -999, -108, -103, -98, -93,
  112959. -88, -83, -79, -78, -75, -71, -67, -68,
  112960. -73, -73, -72, -73, -75, -77, -80, -82,
  112961. -88, -93, -100, -107, -114, -999, -999, -999,
  112962. -999, -999, -999, -999, -999, -999, -999, -999,
  112963. -999, -999, -999, -999, -999, -999, -999, -999,
  112964. -999, -999, -999, -999, -999, -999, -999, -999},
  112965. {-999, -999, -999, -110, -105, -101, -96, -90,
  112966. -86, -81, -77, -73, -69, -66, -61, -62,
  112967. -66, -64, -62, -65, -66, -70, -72, -76,
  112968. -81, -80, -84, -90, -95, -102, -110, -999,
  112969. -999, -999, -999, -999, -999, -999, -999, -999,
  112970. -999, -999, -999, -999, -999, -999, -999, -999,
  112971. -999, -999, -999, -999, -999, -999, -999, -999},
  112972. {-999, -999, -999, -107, -103, -97, -92, -88,
  112973. -83, -79, -74, -70, -66, -59, -53, -58,
  112974. -62, -55, -54, -54, -54, -58, -61, -62,
  112975. -72, -70, -72, -75, -78, -80, -81, -80,
  112976. -83, -83, -88, -93, -100, -107, -115, -999,
  112977. -999, -999, -999, -999, -999, -999, -999, -999,
  112978. -999, -999, -999, -999, -999, -999, -999, -999},
  112979. {-999, -999, -999, -105, -100, -95, -90, -85,
  112980. -80, -75, -70, -66, -62, -56, -48, -44,
  112981. -48, -46, -46, -43, -46, -48, -48, -51,
  112982. -58, -58, -59, -60, -62, -62, -61, -61,
  112983. -65, -64, -65, -68, -70, -74, -75, -78,
  112984. -81, -86, -95, -110, -999, -999, -999, -999,
  112985. -999, -999, -999, -999, -999, -999, -999, -999},
  112986. {-999, -999, -105, -100, -95, -90, -85, -80,
  112987. -75, -70, -65, -61, -55, -49, -39, -33,
  112988. -40, -35, -32, -38, -40, -33, -35, -37,
  112989. -46, -41, -45, -44, -46, -42, -45, -46,
  112990. -52, -50, -50, -50, -54, -54, -55, -57,
  112991. -62, -64, -66, -68, -70, -76, -81, -90,
  112992. -100, -110, -999, -999, -999, -999, -999, -999}},
  112993. /* 354 hz */
  112994. {{-999, -999, -999, -999, -999, -999, -999, -999,
  112995. -105, -98, -90, -85, -82, -83, -80, -78,
  112996. -84, -79, -80, -83, -87, -89, -91, -93,
  112997. -99, -106, -117, -999, -999, -999, -999, -999,
  112998. -999, -999, -999, -999, -999, -999, -999, -999,
  112999. -999, -999, -999, -999, -999, -999, -999, -999,
  113000. -999, -999, -999, -999, -999, -999, -999, -999},
  113001. {-999, -999, -999, -999, -999, -999, -999, -999,
  113002. -105, -98, -90, -85, -80, -75, -70, -68,
  113003. -74, -72, -74, -77, -80, -82, -85, -87,
  113004. -92, -89, -91, -95, -100, -106, -112, -999,
  113005. -999, -999, -999, -999, -999, -999, -999, -999,
  113006. -999, -999, -999, -999, -999, -999, -999, -999,
  113007. -999, -999, -999, -999, -999, -999, -999, -999},
  113008. {-999, -999, -999, -999, -999, -999, -999, -999,
  113009. -105, -98, -90, -83, -75, -71, -63, -64,
  113010. -67, -62, -64, -67, -70, -73, -77, -81,
  113011. -84, -83, -85, -89, -90, -93, -98, -104,
  113012. -109, -114, -999, -999, -999, -999, -999, -999,
  113013. -999, -999, -999, -999, -999, -999, -999, -999,
  113014. -999, -999, -999, -999, -999, -999, -999, -999},
  113015. {-999, -999, -999, -999, -999, -999, -999, -999,
  113016. -103, -96, -88, -81, -75, -68, -58, -54,
  113017. -56, -54, -56, -56, -58, -60, -63, -66,
  113018. -74, -69, -72, -72, -75, -74, -77, -81,
  113019. -81, -82, -84, -87, -93, -96, -99, -104,
  113020. -110, -999, -999, -999, -999, -999, -999, -999,
  113021. -999, -999, -999, -999, -999, -999, -999, -999},
  113022. {-999, -999, -999, -999, -999, -108, -102, -96,
  113023. -91, -85, -80, -74, -68, -60, -51, -46,
  113024. -48, -46, -43, -45, -47, -47, -49, -48,
  113025. -56, -53, -55, -58, -57, -63, -58, -60,
  113026. -66, -64, -67, -70, -70, -74, -77, -84,
  113027. -86, -89, -91, -93, -94, -101, -109, -118,
  113028. -999, -999, -999, -999, -999, -999, -999, -999},
  113029. {-999, -999, -999, -108, -103, -98, -93, -88,
  113030. -83, -78, -73, -68, -60, -53, -44, -35,
  113031. -38, -38, -34, -34, -36, -40, -41, -44,
  113032. -51, -45, -46, -47, -46, -54, -50, -49,
  113033. -50, -50, -50, -51, -54, -57, -58, -60,
  113034. -66, -66, -66, -64, -65, -68, -77, -82,
  113035. -87, -95, -110, -999, -999, -999, -999, -999}},
  113036. /* 500 Hz */
  113037. {{-999, -999, -999, -999, -999, -999, -999, -999,
  113038. -107, -102, -97, -92, -87, -83, -78, -75,
  113039. -82, -79, -83, -85, -89, -92, -95, -98,
  113040. -101, -105, -109, -113, -999, -999, -999, -999,
  113041. -999, -999, -999, -999, -999, -999, -999, -999,
  113042. -999, -999, -999, -999, -999, -999, -999, -999,
  113043. -999, -999, -999, -999, -999, -999, -999, -999},
  113044. {-999, -999, -999, -999, -999, -999, -999, -106,
  113045. -100, -95, -90, -86, -81, -78, -74, -69,
  113046. -74, -74, -76, -79, -83, -84, -86, -89,
  113047. -92, -97, -93, -100, -103, -107, -110, -999,
  113048. -999, -999, -999, -999, -999, -999, -999, -999,
  113049. -999, -999, -999, -999, -999, -999, -999, -999,
  113050. -999, -999, -999, -999, -999, -999, -999, -999},
  113051. {-999, -999, -999, -999, -999, -999, -106, -100,
  113052. -95, -90, -87, -83, -80, -75, -69, -60,
  113053. -66, -66, -68, -70, -74, -78, -79, -81,
  113054. -81, -83, -84, -87, -93, -96, -99, -103,
  113055. -107, -110, -999, -999, -999, -999, -999, -999,
  113056. -999, -999, -999, -999, -999, -999, -999, -999,
  113057. -999, -999, -999, -999, -999, -999, -999, -999},
  113058. {-999, -999, -999, -999, -999, -108, -103, -98,
  113059. -93, -89, -85, -82, -78, -71, -62, -55,
  113060. -58, -58, -54, -54, -55, -59, -61, -62,
  113061. -70, -66, -66, -67, -70, -72, -75, -78,
  113062. -84, -84, -84, -88, -91, -90, -95, -98,
  113063. -102, -103, -106, -110, -999, -999, -999, -999,
  113064. -999, -999, -999, -999, -999, -999, -999, -999},
  113065. {-999, -999, -999, -999, -108, -103, -98, -94,
  113066. -90, -87, -82, -79, -73, -67, -58, -47,
  113067. -50, -45, -41, -45, -48, -44, -44, -49,
  113068. -54, -51, -48, -47, -49, -50, -51, -57,
  113069. -58, -60, -63, -69, -70, -69, -71, -74,
  113070. -78, -82, -90, -95, -101, -105, -110, -999,
  113071. -999, -999, -999, -999, -999, -999, -999, -999},
  113072. {-999, -999, -999, -105, -101, -97, -93, -90,
  113073. -85, -80, -77, -72, -65, -56, -48, -37,
  113074. -40, -36, -34, -40, -50, -47, -38, -41,
  113075. -47, -38, -35, -39, -38, -43, -40, -45,
  113076. -50, -45, -44, -47, -50, -55, -48, -48,
  113077. -52, -66, -70, -76, -82, -90, -97, -105,
  113078. -110, -999, -999, -999, -999, -999, -999, -999}},
  113079. /* 707 Hz */
  113080. {{-999, -999, -999, -999, -999, -999, -999, -999,
  113081. -999, -108, -103, -98, -93, -86, -79, -76,
  113082. -83, -81, -85, -87, -89, -93, -98, -102,
  113083. -107, -112, -999, -999, -999, -999, -999, -999,
  113084. -999, -999, -999, -999, -999, -999, -999, -999,
  113085. -999, -999, -999, -999, -999, -999, -999, -999,
  113086. -999, -999, -999, -999, -999, -999, -999, -999},
  113087. {-999, -999, -999, -999, -999, -999, -999, -999,
  113088. -999, -108, -103, -98, -93, -86, -79, -71,
  113089. -77, -74, -77, -79, -81, -84, -85, -90,
  113090. -92, -93, -92, -98, -101, -108, -112, -999,
  113091. -999, -999, -999, -999, -999, -999, -999, -999,
  113092. -999, -999, -999, -999, -999, -999, -999, -999,
  113093. -999, -999, -999, -999, -999, -999, -999, -999},
  113094. {-999, -999, -999, -999, -999, -999, -999, -999,
  113095. -108, -103, -98, -93, -87, -78, -68, -65,
  113096. -66, -62, -65, -67, -70, -73, -75, -78,
  113097. -82, -82, -83, -84, -91, -93, -98, -102,
  113098. -106, -110, -999, -999, -999, -999, -999, -999,
  113099. -999, -999, -999, -999, -999, -999, -999, -999,
  113100. -999, -999, -999, -999, -999, -999, -999, -999},
  113101. {-999, -999, -999, -999, -999, -999, -999, -999,
  113102. -105, -100, -95, -90, -82, -74, -62, -57,
  113103. -58, -56, -51, -52, -52, -54, -54, -58,
  113104. -66, -59, -60, -63, -66, -69, -73, -79,
  113105. -83, -84, -80, -81, -81, -82, -88, -92,
  113106. -98, -105, -113, -999, -999, -999, -999, -999,
  113107. -999, -999, -999, -999, -999, -999, -999, -999},
  113108. {-999, -999, -999, -999, -999, -999, -999, -107,
  113109. -102, -97, -92, -84, -79, -69, -57, -47,
  113110. -52, -47, -44, -45, -50, -52, -42, -42,
  113111. -53, -43, -43, -48, -51, -56, -55, -52,
  113112. -57, -59, -61, -62, -67, -71, -78, -83,
  113113. -86, -94, -98, -103, -110, -999, -999, -999,
  113114. -999, -999, -999, -999, -999, -999, -999, -999},
  113115. {-999, -999, -999, -999, -999, -999, -105, -100,
  113116. -95, -90, -84, -78, -70, -61, -51, -41,
  113117. -40, -38, -40, -46, -52, -51, -41, -40,
  113118. -46, -40, -38, -38, -41, -46, -41, -46,
  113119. -47, -43, -43, -45, -41, -45, -56, -67,
  113120. -68, -83, -87, -90, -95, -102, -107, -113,
  113121. -999, -999, -999, -999, -999, -999, -999, -999}},
  113122. /* 1000 Hz */
  113123. {{-999, -999, -999, -999, -999, -999, -999, -999,
  113124. -999, -109, -105, -101, -96, -91, -84, -77,
  113125. -82, -82, -85, -89, -94, -100, -106, -110,
  113126. -999, -999, -999, -999, -999, -999, -999, -999,
  113127. -999, -999, -999, -999, -999, -999, -999, -999,
  113128. -999, -999, -999, -999, -999, -999, -999, -999,
  113129. -999, -999, -999, -999, -999, -999, -999, -999},
  113130. {-999, -999, -999, -999, -999, -999, -999, -999,
  113131. -999, -106, -103, -98, -92, -85, -80, -71,
  113132. -75, -72, -76, -80, -84, -86, -89, -93,
  113133. -100, -107, -113, -999, -999, -999, -999, -999,
  113134. -999, -999, -999, -999, -999, -999, -999, -999,
  113135. -999, -999, -999, -999, -999, -999, -999, -999,
  113136. -999, -999, -999, -999, -999, -999, -999, -999},
  113137. {-999, -999, -999, -999, -999, -999, -999, -107,
  113138. -104, -101, -97, -92, -88, -84, -80, -64,
  113139. -66, -63, -64, -66, -69, -73, -77, -83,
  113140. -83, -86, -91, -98, -104, -111, -999, -999,
  113141. -999, -999, -999, -999, -999, -999, -999, -999,
  113142. -999, -999, -999, -999, -999, -999, -999, -999,
  113143. -999, -999, -999, -999, -999, -999, -999, -999},
  113144. {-999, -999, -999, -999, -999, -999, -999, -107,
  113145. -104, -101, -97, -92, -90, -84, -74, -57,
  113146. -58, -52, -55, -54, -50, -52, -50, -52,
  113147. -63, -62, -69, -76, -77, -78, -78, -79,
  113148. -82, -88, -94, -100, -106, -111, -999, -999,
  113149. -999, -999, -999, -999, -999, -999, -999, -999,
  113150. -999, -999, -999, -999, -999, -999, -999, -999},
  113151. {-999, -999, -999, -999, -999, -999, -106, -102,
  113152. -98, -95, -90, -85, -83, -78, -70, -50,
  113153. -50, -41, -44, -49, -47, -50, -50, -44,
  113154. -55, -46, -47, -48, -48, -54, -49, -49,
  113155. -58, -62, -71, -81, -87, -92, -97, -102,
  113156. -108, -114, -999, -999, -999, -999, -999, -999,
  113157. -999, -999, -999, -999, -999, -999, -999, -999},
  113158. {-999, -999, -999, -999, -999, -999, -106, -102,
  113159. -98, -95, -90, -85, -83, -78, -70, -45,
  113160. -43, -41, -47, -50, -51, -50, -49, -45,
  113161. -47, -41, -44, -41, -39, -43, -38, -37,
  113162. -40, -41, -44, -50, -58, -65, -73, -79,
  113163. -85, -92, -97, -101, -105, -109, -113, -999,
  113164. -999, -999, -999, -999, -999, -999, -999, -999}},
  113165. /* 1414 Hz */
  113166. {{-999, -999, -999, -999, -999, -999, -999, -999,
  113167. -999, -999, -999, -107, -100, -95, -87, -81,
  113168. -85, -83, -88, -93, -100, -107, -114, -999,
  113169. -999, -999, -999, -999, -999, -999, -999, -999,
  113170. -999, -999, -999, -999, -999, -999, -999, -999,
  113171. -999, -999, -999, -999, -999, -999, -999, -999,
  113172. -999, -999, -999, -999, -999, -999, -999, -999},
  113173. {-999, -999, -999, -999, -999, -999, -999, -999,
  113174. -999, -999, -107, -101, -95, -88, -83, -76,
  113175. -73, -72, -79, -84, -90, -95, -100, -105,
  113176. -110, -115, -999, -999, -999, -999, -999, -999,
  113177. -999, -999, -999, -999, -999, -999, -999, -999,
  113178. -999, -999, -999, -999, -999, -999, -999, -999,
  113179. -999, -999, -999, -999, -999, -999, -999, -999},
  113180. {-999, -999, -999, -999, -999, -999, -999, -999,
  113181. -999, -999, -104, -98, -92, -87, -81, -70,
  113182. -65, -62, -67, -71, -74, -80, -85, -91,
  113183. -95, -99, -103, -108, -111, -114, -999, -999,
  113184. -999, -999, -999, -999, -999, -999, -999, -999,
  113185. -999, -999, -999, -999, -999, -999, -999, -999,
  113186. -999, -999, -999, -999, -999, -999, -999, -999},
  113187. {-999, -999, -999, -999, -999, -999, -999, -999,
  113188. -999, -999, -103, -97, -90, -85, -76, -60,
  113189. -56, -54, -60, -62, -61, -56, -63, -65,
  113190. -73, -74, -77, -75, -78, -81, -86, -87,
  113191. -88, -91, -94, -98, -103, -110, -999, -999,
  113192. -999, -999, -999, -999, -999, -999, -999, -999,
  113193. -999, -999, -999, -999, -999, -999, -999, -999},
  113194. {-999, -999, -999, -999, -999, -999, -999, -105,
  113195. -100, -97, -92, -86, -81, -79, -70, -57,
  113196. -51, -47, -51, -58, -60, -56, -53, -50,
  113197. -58, -52, -50, -50, -53, -55, -64, -69,
  113198. -71, -85, -82, -78, -81, -85, -95, -102,
  113199. -112, -999, -999, -999, -999, -999, -999, -999,
  113200. -999, -999, -999, -999, -999, -999, -999, -999},
  113201. {-999, -999, -999, -999, -999, -999, -999, -105,
  113202. -100, -97, -92, -85, -83, -79, -72, -49,
  113203. -40, -43, -43, -54, -56, -51, -50, -40,
  113204. -43, -38, -36, -35, -37, -38, -37, -44,
  113205. -54, -60, -57, -60, -70, -75, -84, -92,
  113206. -103, -112, -999, -999, -999, -999, -999, -999,
  113207. -999, -999, -999, -999, -999, -999, -999, -999}},
  113208. /* 2000 Hz */
  113209. {{-999, -999, -999, -999, -999, -999, -999, -999,
  113210. -999, -999, -999, -110, -102, -95, -89, -82,
  113211. -83, -84, -90, -92, -99, -107, -113, -999,
  113212. -999, -999, -999, -999, -999, -999, -999, -999,
  113213. -999, -999, -999, -999, -999, -999, -999, -999,
  113214. -999, -999, -999, -999, -999, -999, -999, -999,
  113215. -999, -999, -999, -999, -999, -999, -999, -999},
  113216. {-999, -999, -999, -999, -999, -999, -999, -999,
  113217. -999, -999, -107, -101, -95, -89, -83, -72,
  113218. -74, -78, -85, -88, -88, -90, -92, -98,
  113219. -105, -111, -999, -999, -999, -999, -999, -999,
  113220. -999, -999, -999, -999, -999, -999, -999, -999,
  113221. -999, -999, -999, -999, -999, -999, -999, -999,
  113222. -999, -999, -999, -999, -999, -999, -999, -999},
  113223. {-999, -999, -999, -999, -999, -999, -999, -999,
  113224. -999, -109, -103, -97, -93, -87, -81, -70,
  113225. -70, -67, -75, -73, -76, -79, -81, -83,
  113226. -88, -89, -97, -103, -110, -999, -999, -999,
  113227. -999, -999, -999, -999, -999, -999, -999, -999,
  113228. -999, -999, -999, -999, -999, -999, -999, -999,
  113229. -999, -999, -999, -999, -999, -999, -999, -999},
  113230. {-999, -999, -999, -999, -999, -999, -999, -999,
  113231. -999, -107, -100, -94, -88, -83, -75, -63,
  113232. -59, -59, -63, -66, -60, -62, -67, -67,
  113233. -77, -76, -81, -88, -86, -92, -96, -102,
  113234. -109, -116, -999, -999, -999, -999, -999, -999,
  113235. -999, -999, -999, -999, -999, -999, -999, -999,
  113236. -999, -999, -999, -999, -999, -999, -999, -999},
  113237. {-999, -999, -999, -999, -999, -999, -999, -999,
  113238. -999, -105, -98, -92, -86, -81, -73, -56,
  113239. -52, -47, -55, -60, -58, -52, -51, -45,
  113240. -49, -50, -53, -54, -61, -71, -70, -69,
  113241. -78, -79, -87, -90, -96, -104, -112, -999,
  113242. -999, -999, -999, -999, -999, -999, -999, -999,
  113243. -999, -999, -999, -999, -999, -999, -999, -999},
  113244. {-999, -999, -999, -999, -999, -999, -999, -999,
  113245. -999, -103, -96, -90, -86, -78, -70, -51,
  113246. -42, -47, -48, -55, -54, -54, -53, -42,
  113247. -35, -28, -33, -38, -37, -44, -47, -49,
  113248. -54, -63, -68, -78, -82, -89, -94, -99,
  113249. -104, -109, -114, -999, -999, -999, -999, -999,
  113250. -999, -999, -999, -999, -999, -999, -999, -999}},
  113251. /* 2828 Hz */
  113252. {{-999, -999, -999, -999, -999, -999, -999, -999,
  113253. -999, -999, -999, -999, -110, -100, -90, -79,
  113254. -85, -81, -82, -82, -89, -94, -99, -103,
  113255. -109, -115, -999, -999, -999, -999, -999, -999,
  113256. -999, -999, -999, -999, -999, -999, -999, -999,
  113257. -999, -999, -999, -999, -999, -999, -999, -999,
  113258. -999, -999, -999, -999, -999, -999, -999, -999},
  113259. {-999, -999, -999, -999, -999, -999, -999, -999,
  113260. -999, -999, -999, -999, -105, -97, -85, -72,
  113261. -74, -70, -70, -70, -76, -85, -91, -93,
  113262. -97, -103, -109, -115, -999, -999, -999, -999,
  113263. -999, -999, -999, -999, -999, -999, -999, -999,
  113264. -999, -999, -999, -999, -999, -999, -999, -999,
  113265. -999, -999, -999, -999, -999, -999, -999, -999},
  113266. {-999, -999, -999, -999, -999, -999, -999, -999,
  113267. -999, -999, -999, -999, -112, -93, -81, -68,
  113268. -62, -60, -60, -57, -63, -70, -77, -82,
  113269. -90, -93, -98, -104, -109, -113, -999, -999,
  113270. -999, -999, -999, -999, -999, -999, -999, -999,
  113271. -999, -999, -999, -999, -999, -999, -999, -999,
  113272. -999, -999, -999, -999, -999, -999, -999, -999},
  113273. {-999, -999, -999, -999, -999, -999, -999, -999,
  113274. -999, -999, -999, -113, -100, -93, -84, -63,
  113275. -58, -48, -53, -54, -52, -52, -57, -64,
  113276. -66, -76, -83, -81, -85, -85, -90, -95,
  113277. -98, -101, -103, -106, -108, -111, -999, -999,
  113278. -999, -999, -999, -999, -999, -999, -999, -999,
  113279. -999, -999, -999, -999, -999, -999, -999, -999},
  113280. {-999, -999, -999, -999, -999, -999, -999, -999,
  113281. -999, -999, -999, -105, -95, -86, -74, -53,
  113282. -50, -38, -43, -49, -43, -42, -39, -39,
  113283. -46, -52, -57, -56, -72, -69, -74, -81,
  113284. -87, -92, -94, -97, -99, -102, -105, -108,
  113285. -999, -999, -999, -999, -999, -999, -999, -999,
  113286. -999, -999, -999, -999, -999, -999, -999, -999},
  113287. {-999, -999, -999, -999, -999, -999, -999, -999,
  113288. -999, -999, -108, -99, -90, -76, -66, -45,
  113289. -43, -41, -44, -47, -43, -47, -40, -30,
  113290. -31, -31, -39, -33, -40, -41, -43, -53,
  113291. -59, -70, -73, -77, -79, -82, -84, -87,
  113292. -999, -999, -999, -999, -999, -999, -999, -999,
  113293. -999, -999, -999, -999, -999, -999, -999, -999}},
  113294. /* 4000 Hz */
  113295. {{-999, -999, -999, -999, -999, -999, -999, -999,
  113296. -999, -999, -999, -999, -999, -110, -91, -76,
  113297. -75, -85, -93, -98, -104, -110, -999, -999,
  113298. -999, -999, -999, -999, -999, -999, -999, -999,
  113299. -999, -999, -999, -999, -999, -999, -999, -999,
  113300. -999, -999, -999, -999, -999, -999, -999, -999,
  113301. -999, -999, -999, -999, -999, -999, -999, -999},
  113302. {-999, -999, -999, -999, -999, -999, -999, -999,
  113303. -999, -999, -999, -999, -999, -110, -91, -70,
  113304. -70, -75, -86, -89, -94, -98, -101, -106,
  113305. -110, -999, -999, -999, -999, -999, -999, -999,
  113306. -999, -999, -999, -999, -999, -999, -999, -999,
  113307. -999, -999, -999, -999, -999, -999, -999, -999,
  113308. -999, -999, -999, -999, -999, -999, -999, -999},
  113309. {-999, -999, -999, -999, -999, -999, -999, -999,
  113310. -999, -999, -999, -999, -110, -95, -80, -60,
  113311. -65, -64, -74, -83, -88, -91, -95, -99,
  113312. -103, -107, -110, -999, -999, -999, -999, -999,
  113313. -999, -999, -999, -999, -999, -999, -999, -999,
  113314. -999, -999, -999, -999, -999, -999, -999, -999,
  113315. -999, -999, -999, -999, -999, -999, -999, -999},
  113316. {-999, -999, -999, -999, -999, -999, -999, -999,
  113317. -999, -999, -999, -999, -110, -95, -80, -58,
  113318. -55, -49, -66, -68, -71, -78, -78, -80,
  113319. -88, -85, -89, -97, -100, -105, -110, -999,
  113320. -999, -999, -999, -999, -999, -999, -999, -999,
  113321. -999, -999, -999, -999, -999, -999, -999, -999,
  113322. -999, -999, -999, -999, -999, -999, -999, -999},
  113323. {-999, -999, -999, -999, -999, -999, -999, -999,
  113324. -999, -999, -999, -999, -110, -95, -80, -53,
  113325. -52, -41, -59, -59, -49, -58, -56, -63,
  113326. -86, -79, -90, -93, -98, -103, -107, -112,
  113327. -999, -999, -999, -999, -999, -999, -999, -999,
  113328. -999, -999, -999, -999, -999, -999, -999, -999,
  113329. -999, -999, -999, -999, -999, -999, -999, -999},
  113330. {-999, -999, -999, -999, -999, -999, -999, -999,
  113331. -999, -999, -999, -110, -97, -91, -73, -45,
  113332. -40, -33, -53, -61, -49, -54, -50, -50,
  113333. -60, -52, -67, -74, -81, -92, -96, -100,
  113334. -105, -110, -999, -999, -999, -999, -999, -999,
  113335. -999, -999, -999, -999, -999, -999, -999, -999,
  113336. -999, -999, -999, -999, -999, -999, -999, -999}},
  113337. /* 5657 Hz */
  113338. {{-999, -999, -999, -999, -999, -999, -999, -999,
  113339. -999, -999, -999, -113, -106, -99, -92, -77,
  113340. -80, -88, -97, -106, -115, -999, -999, -999,
  113341. -999, -999, -999, -999, -999, -999, -999, -999,
  113342. -999, -999, -999, -999, -999, -999, -999, -999,
  113343. -999, -999, -999, -999, -999, -999, -999, -999,
  113344. -999, -999, -999, -999, -999, -999, -999, -999},
  113345. {-999, -999, -999, -999, -999, -999, -999, -999,
  113346. -999, -999, -116, -109, -102, -95, -89, -74,
  113347. -72, -88, -87, -95, -102, -109, -116, -999,
  113348. -999, -999, -999, -999, -999, -999, -999, -999,
  113349. -999, -999, -999, -999, -999, -999, -999, -999,
  113350. -999, -999, -999, -999, -999, -999, -999, -999,
  113351. -999, -999, -999, -999, -999, -999, -999, -999},
  113352. {-999, -999, -999, -999, -999, -999, -999, -999,
  113353. -999, -999, -116, -109, -102, -95, -89, -75,
  113354. -66, -74, -77, -78, -86, -87, -90, -96,
  113355. -105, -115, -999, -999, -999, -999, -999, -999,
  113356. -999, -999, -999, -999, -999, -999, -999, -999,
  113357. -999, -999, -999, -999, -999, -999, -999, -999,
  113358. -999, -999, -999, -999, -999, -999, -999, -999},
  113359. {-999, -999, -999, -999, -999, -999, -999, -999,
  113360. -999, -999, -115, -108, -101, -94, -88, -66,
  113361. -56, -61, -70, -65, -78, -72, -83, -84,
  113362. -93, -98, -105, -110, -999, -999, -999, -999,
  113363. -999, -999, -999, -999, -999, -999, -999, -999,
  113364. -999, -999, -999, -999, -999, -999, -999, -999,
  113365. -999, -999, -999, -999, -999, -999, -999, -999},
  113366. {-999, -999, -999, -999, -999, -999, -999, -999,
  113367. -999, -999, -110, -105, -95, -89, -82, -57,
  113368. -52, -52, -59, -56, -59, -58, -69, -67,
  113369. -88, -82, -82, -89, -94, -100, -108, -999,
  113370. -999, -999, -999, -999, -999, -999, -999, -999,
  113371. -999, -999, -999, -999, -999, -999, -999, -999,
  113372. -999, -999, -999, -999, -999, -999, -999, -999},
  113373. {-999, -999, -999, -999, -999, -999, -999, -999,
  113374. -999, -110, -101, -96, -90, -83, -77, -54,
  113375. -43, -38, -50, -48, -52, -48, -42, -42,
  113376. -51, -52, -53, -59, -65, -71, -78, -85,
  113377. -95, -999, -999, -999, -999, -999, -999, -999,
  113378. -999, -999, -999, -999, -999, -999, -999, -999,
  113379. -999, -999, -999, -999, -999, -999, -999, -999}},
  113380. /* 8000 Hz */
  113381. {{-999, -999, -999, -999, -999, -999, -999, -999,
  113382. -999, -999, -999, -999, -120, -105, -86, -68,
  113383. -78, -79, -90, -100, -110, -999, -999, -999,
  113384. -999, -999, -999, -999, -999, -999, -999, -999,
  113385. -999, -999, -999, -999, -999, -999, -999, -999,
  113386. -999, -999, -999, -999, -999, -999, -999, -999,
  113387. -999, -999, -999, -999, -999, -999, -999, -999},
  113388. {-999, -999, -999, -999, -999, -999, -999, -999,
  113389. -999, -999, -999, -999, -120, -105, -86, -66,
  113390. -73, -77, -88, -96, -105, -115, -999, -999,
  113391. -999, -999, -999, -999, -999, -999, -999, -999,
  113392. -999, -999, -999, -999, -999, -999, -999, -999,
  113393. -999, -999, -999, -999, -999, -999, -999, -999,
  113394. -999, -999, -999, -999, -999, -999, -999, -999},
  113395. {-999, -999, -999, -999, -999, -999, -999, -999,
  113396. -999, -999, -999, -120, -105, -92, -80, -61,
  113397. -64, -68, -80, -87, -92, -100, -110, -999,
  113398. -999, -999, -999, -999, -999, -999, -999, -999,
  113399. -999, -999, -999, -999, -999, -999, -999, -999,
  113400. -999, -999, -999, -999, -999, -999, -999, -999,
  113401. -999, -999, -999, -999, -999, -999, -999, -999},
  113402. {-999, -999, -999, -999, -999, -999, -999, -999,
  113403. -999, -999, -999, -120, -104, -91, -79, -52,
  113404. -60, -54, -64, -69, -77, -80, -82, -84,
  113405. -85, -87, -88, -90, -999, -999, -999, -999,
  113406. -999, -999, -999, -999, -999, -999, -999, -999,
  113407. -999, -999, -999, -999, -999, -999, -999, -999,
  113408. -999, -999, -999, -999, -999, -999, -999, -999},
  113409. {-999, -999, -999, -999, -999, -999, -999, -999,
  113410. -999, -999, -999, -118, -100, -87, -77, -49,
  113411. -50, -44, -58, -61, -61, -67, -65, -62,
  113412. -62, -62, -65, -68, -999, -999, -999, -999,
  113413. -999, -999, -999, -999, -999, -999, -999, -999,
  113414. -999, -999, -999, -999, -999, -999, -999, -999,
  113415. -999, -999, -999, -999, -999, -999, -999, -999},
  113416. {-999, -999, -999, -999, -999, -999, -999, -999,
  113417. -999, -999, -999, -115, -98, -84, -62, -49,
  113418. -44, -38, -46, -49, -49, -46, -39, -37,
  113419. -39, -40, -42, -43, -999, -999, -999, -999,
  113420. -999, -999, -999, -999, -999, -999, -999, -999,
  113421. -999, -999, -999, -999, -999, -999, -999, -999,
  113422. -999, -999, -999, -999, -999, -999, -999, -999}},
  113423. /* 11314 Hz */
  113424. {{-999, -999, -999, -999, -999, -999, -999, -999,
  113425. -999, -999, -999, -999, -999, -110, -88, -74,
  113426. -77, -82, -82, -85, -90, -94, -99, -104,
  113427. -999, -999, -999, -999, -999, -999, -999, -999,
  113428. -999, -999, -999, -999, -999, -999, -999, -999,
  113429. -999, -999, -999, -999, -999, -999, -999, -999,
  113430. -999, -999, -999, -999, -999, -999, -999, -999},
  113431. {-999, -999, -999, -999, -999, -999, -999, -999,
  113432. -999, -999, -999, -999, -999, -110, -88, -66,
  113433. -70, -81, -80, -81, -84, -88, -91, -93,
  113434. -999, -999, -999, -999, -999, -999, -999, -999,
  113435. -999, -999, -999, -999, -999, -999, -999, -999,
  113436. -999, -999, -999, -999, -999, -999, -999, -999,
  113437. -999, -999, -999, -999, -999, -999, -999, -999},
  113438. {-999, -999, -999, -999, -999, -999, -999, -999,
  113439. -999, -999, -999, -999, -999, -110, -88, -61,
  113440. -63, -70, -71, -74, -77, -80, -83, -85,
  113441. -999, -999, -999, -999, -999, -999, -999, -999,
  113442. -999, -999, -999, -999, -999, -999, -999, -999,
  113443. -999, -999, -999, -999, -999, -999, -999, -999,
  113444. -999, -999, -999, -999, -999, -999, -999, -999},
  113445. {-999, -999, -999, -999, -999, -999, -999, -999,
  113446. -999, -999, -999, -999, -999, -110, -86, -62,
  113447. -63, -62, -62, -58, -52, -50, -50, -52,
  113448. -54, -999, -999, -999, -999, -999, -999, -999,
  113449. -999, -999, -999, -999, -999, -999, -999, -999,
  113450. -999, -999, -999, -999, -999, -999, -999, -999,
  113451. -999, -999, -999, -999, -999, -999, -999, -999},
  113452. {-999, -999, -999, -999, -999, -999, -999, -999,
  113453. -999, -999, -999, -999, -118, -108, -84, -53,
  113454. -50, -50, -50, -55, -47, -45, -40, -40,
  113455. -40, -999, -999, -999, -999, -999, -999, -999,
  113456. -999, -999, -999, -999, -999, -999, -999, -999,
  113457. -999, -999, -999, -999, -999, -999, -999, -999,
  113458. -999, -999, -999, -999, -999, -999, -999, -999},
  113459. {-999, -999, -999, -999, -999, -999, -999, -999,
  113460. -999, -999, -999, -999, -118, -100, -73, -43,
  113461. -37, -42, -43, -53, -38, -37, -35, -35,
  113462. -38, -999, -999, -999, -999, -999, -999, -999,
  113463. -999, -999, -999, -999, -999, -999, -999, -999,
  113464. -999, -999, -999, -999, -999, -999, -999, -999,
  113465. -999, -999, -999, -999, -999, -999, -999, -999}},
  113466. /* 16000 Hz */
  113467. {{-999, -999, -999, -999, -999, -999, -999, -999,
  113468. -999, -999, -999, -110, -100, -91, -84, -74,
  113469. -80, -80, -80, -80, -80, -999, -999, -999,
  113470. -999, -999, -999, -999, -999, -999, -999, -999,
  113471. -999, -999, -999, -999, -999, -999, -999, -999,
  113472. -999, -999, -999, -999, -999, -999, -999, -999,
  113473. -999, -999, -999, -999, -999, -999, -999, -999},
  113474. {-999, -999, -999, -999, -999, -999, -999, -999,
  113475. -999, -999, -999, -110, -100, -91, -84, -74,
  113476. -68, -68, -68, -68, -68, -999, -999, -999,
  113477. -999, -999, -999, -999, -999, -999, -999, -999,
  113478. -999, -999, -999, -999, -999, -999, -999, -999,
  113479. -999, -999, -999, -999, -999, -999, -999, -999,
  113480. -999, -999, -999, -999, -999, -999, -999, -999},
  113481. {-999, -999, -999, -999, -999, -999, -999, -999,
  113482. -999, -999, -999, -110, -100, -86, -78, -70,
  113483. -60, -45, -30, -21, -999, -999, -999, -999,
  113484. -999, -999, -999, -999, -999, -999, -999, -999,
  113485. -999, -999, -999, -999, -999, -999, -999, -999,
  113486. -999, -999, -999, -999, -999, -999, -999, -999,
  113487. -999, -999, -999, -999, -999, -999, -999, -999},
  113488. {-999, -999, -999, -999, -999, -999, -999, -999,
  113489. -999, -999, -999, -110, -100, -87, -78, -67,
  113490. -48, -38, -29, -21, -999, -999, -999, -999,
  113491. -999, -999, -999, -999, -999, -999, -999, -999,
  113492. -999, -999, -999, -999, -999, -999, -999, -999,
  113493. -999, -999, -999, -999, -999, -999, -999, -999,
  113494. -999, -999, -999, -999, -999, -999, -999, -999},
  113495. {-999, -999, -999, -999, -999, -999, -999, -999,
  113496. -999, -999, -999, -110, -100, -86, -69, -56,
  113497. -45, -35, -33, -29, -999, -999, -999, -999,
  113498. -999, -999, -999, -999, -999, -999, -999, -999,
  113499. -999, -999, -999, -999, -999, -999, -999, -999,
  113500. -999, -999, -999, -999, -999, -999, -999, -999,
  113501. -999, -999, -999, -999, -999, -999, -999, -999},
  113502. {-999, -999, -999, -999, -999, -999, -999, -999,
  113503. -999, -999, -999, -110, -100, -83, -71, -48,
  113504. -27, -38, -37, -34, -999, -999, -999, -999,
  113505. -999, -999, -999, -999, -999, -999, -999, -999,
  113506. -999, -999, -999, -999, -999, -999, -999, -999,
  113507. -999, -999, -999, -999, -999, -999, -999, -999,
  113508. -999, -999, -999, -999, -999, -999, -999, -999}}
  113509. };
  113510. #endif
  113511. /*** End of inlined file: masking.h ***/
  113512. #define NEGINF -9999.f
  113513. static double stereo_threshholds[]={0.0, .5, 1.0, 1.5, 2.5, 4.5, 8.5, 16.5, 9e10};
  113514. static double stereo_threshholds_limited[]={0.0, .5, 1.0, 1.5, 2.0, 2.5, 4.5, 8.5, 9e10};
  113515. vorbis_look_psy_global *_vp_global_look(vorbis_info *vi){
  113516. codec_setup_info *ci=(codec_setup_info*)vi->codec_setup;
  113517. vorbis_info_psy_global *gi=&ci->psy_g_param;
  113518. vorbis_look_psy_global *look=(vorbis_look_psy_global*)_ogg_calloc(1,sizeof(*look));
  113519. look->channels=vi->channels;
  113520. look->ampmax=-9999.;
  113521. look->gi=gi;
  113522. return(look);
  113523. }
  113524. void _vp_global_free(vorbis_look_psy_global *look){
  113525. if(look){
  113526. memset(look,0,sizeof(*look));
  113527. _ogg_free(look);
  113528. }
  113529. }
  113530. void _vi_gpsy_free(vorbis_info_psy_global *i){
  113531. if(i){
  113532. memset(i,0,sizeof(*i));
  113533. _ogg_free(i);
  113534. }
  113535. }
  113536. void _vi_psy_free(vorbis_info_psy *i){
  113537. if(i){
  113538. memset(i,0,sizeof(*i));
  113539. _ogg_free(i);
  113540. }
  113541. }
  113542. static void min_curve(float *c,
  113543. float *c2){
  113544. int i;
  113545. for(i=0;i<EHMER_MAX;i++)if(c2[i]<c[i])c[i]=c2[i];
  113546. }
  113547. static void max_curve(float *c,
  113548. float *c2){
  113549. int i;
  113550. for(i=0;i<EHMER_MAX;i++)if(c2[i]>c[i])c[i]=c2[i];
  113551. }
  113552. static void attenuate_curve(float *c,float att){
  113553. int i;
  113554. for(i=0;i<EHMER_MAX;i++)
  113555. c[i]+=att;
  113556. }
  113557. static float ***setup_tone_curves(float curveatt_dB[P_BANDS],float binHz,int n,
  113558. float center_boost, float center_decay_rate){
  113559. int i,j,k,m;
  113560. float ath[EHMER_MAX];
  113561. float workc[P_BANDS][P_LEVELS][EHMER_MAX];
  113562. float athc[P_LEVELS][EHMER_MAX];
  113563. float *brute_buffer=(float*) alloca(n*sizeof(*brute_buffer));
  113564. float ***ret=(float***) _ogg_malloc(sizeof(*ret)*P_BANDS);
  113565. memset(workc,0,sizeof(workc));
  113566. for(i=0;i<P_BANDS;i++){
  113567. /* we add back in the ATH to avoid low level curves falling off to
  113568. -infinity and unnecessarily cutting off high level curves in the
  113569. curve limiting (last step). */
  113570. /* A half-band's settings must be valid over the whole band, and
  113571. it's better to mask too little than too much */
  113572. int ath_offset=i*4;
  113573. for(j=0;j<EHMER_MAX;j++){
  113574. float min=999.;
  113575. for(k=0;k<4;k++)
  113576. if(j+k+ath_offset<MAX_ATH){
  113577. if(min>ATH[j+k+ath_offset])min=ATH[j+k+ath_offset];
  113578. }else{
  113579. if(min>ATH[MAX_ATH-1])min=ATH[MAX_ATH-1];
  113580. }
  113581. ath[j]=min;
  113582. }
  113583. /* copy curves into working space, replicate the 50dB curve to 30
  113584. and 40, replicate the 100dB curve to 110 */
  113585. for(j=0;j<6;j++)
  113586. memcpy(workc[i][j+2],tonemasks[i][j],EHMER_MAX*sizeof(*tonemasks[i][j]));
  113587. memcpy(workc[i][0],tonemasks[i][0],EHMER_MAX*sizeof(*tonemasks[i][0]));
  113588. memcpy(workc[i][1],tonemasks[i][0],EHMER_MAX*sizeof(*tonemasks[i][0]));
  113589. /* apply centered curve boost/decay */
  113590. for(j=0;j<P_LEVELS;j++){
  113591. for(k=0;k<EHMER_MAX;k++){
  113592. float adj=center_boost+abs(EHMER_OFFSET-k)*center_decay_rate;
  113593. if(adj<0. && center_boost>0)adj=0.;
  113594. if(adj>0. && center_boost<0)adj=0.;
  113595. workc[i][j][k]+=adj;
  113596. }
  113597. }
  113598. /* normalize curves so the driving amplitude is 0dB */
  113599. /* make temp curves with the ATH overlayed */
  113600. for(j=0;j<P_LEVELS;j++){
  113601. attenuate_curve(workc[i][j],curveatt_dB[i]+100.-(j<2?2:j)*10.-P_LEVEL_0);
  113602. memcpy(athc[j],ath,EHMER_MAX*sizeof(**athc));
  113603. attenuate_curve(athc[j],+100.-j*10.f-P_LEVEL_0);
  113604. max_curve(athc[j],workc[i][j]);
  113605. }
  113606. /* Now limit the louder curves.
  113607. the idea is this: We don't know what the playback attenuation
  113608. will be; 0dB SL moves every time the user twiddles the volume
  113609. knob. So that means we have to use a single 'most pessimal' curve
  113610. for all masking amplitudes, right? Wrong. The *loudest* sound
  113611. can be in (we assume) a range of ...+100dB] SL. However, sounds
  113612. 20dB down will be in a range ...+80], 40dB down is from ...+60],
  113613. etc... */
  113614. for(j=1;j<P_LEVELS;j++){
  113615. min_curve(athc[j],athc[j-1]);
  113616. min_curve(workc[i][j],athc[j]);
  113617. }
  113618. }
  113619. for(i=0;i<P_BANDS;i++){
  113620. int hi_curve,lo_curve,bin;
  113621. ret[i]=(float**)_ogg_malloc(sizeof(**ret)*P_LEVELS);
  113622. /* low frequency curves are measured with greater resolution than
  113623. the MDCT/FFT will actually give us; we want the curve applied
  113624. to the tone data to be pessimistic and thus apply the minimum
  113625. masking possible for a given bin. That means that a single bin
  113626. could span more than one octave and that the curve will be a
  113627. composite of multiple octaves. It also may mean that a single
  113628. bin may span > an eighth of an octave and that the eighth
  113629. octave values may also be composited. */
  113630. /* which octave curves will we be compositing? */
  113631. bin=floor(fromOC(i*.5)/binHz);
  113632. lo_curve= ceil(toOC(bin*binHz+1)*2);
  113633. hi_curve= floor(toOC((bin+1)*binHz)*2);
  113634. if(lo_curve>i)lo_curve=i;
  113635. if(lo_curve<0)lo_curve=0;
  113636. if(hi_curve>=P_BANDS)hi_curve=P_BANDS-1;
  113637. for(m=0;m<P_LEVELS;m++){
  113638. ret[i][m]=(float*)_ogg_malloc(sizeof(***ret)*(EHMER_MAX+2));
  113639. for(j=0;j<n;j++)brute_buffer[j]=999.;
  113640. /* render the curve into bins, then pull values back into curve.
  113641. The point is that any inherent subsampling aliasing results in
  113642. a safe minimum */
  113643. for(k=lo_curve;k<=hi_curve;k++){
  113644. int l=0;
  113645. for(j=0;j<EHMER_MAX;j++){
  113646. int lo_bin= fromOC(j*.125+k*.5-2.0625)/binHz;
  113647. int hi_bin= fromOC(j*.125+k*.5-1.9375)/binHz+1;
  113648. if(lo_bin<0)lo_bin=0;
  113649. if(lo_bin>n)lo_bin=n;
  113650. if(lo_bin<l)l=lo_bin;
  113651. if(hi_bin<0)hi_bin=0;
  113652. if(hi_bin>n)hi_bin=n;
  113653. for(;l<hi_bin && l<n;l++)
  113654. if(brute_buffer[l]>workc[k][m][j])
  113655. brute_buffer[l]=workc[k][m][j];
  113656. }
  113657. for(;l<n;l++)
  113658. if(brute_buffer[l]>workc[k][m][EHMER_MAX-1])
  113659. brute_buffer[l]=workc[k][m][EHMER_MAX-1];
  113660. }
  113661. /* be equally paranoid about being valid up to next half ocatve */
  113662. if(i+1<P_BANDS){
  113663. int l=0;
  113664. k=i+1;
  113665. for(j=0;j<EHMER_MAX;j++){
  113666. int lo_bin= fromOC(j*.125+i*.5-2.0625)/binHz;
  113667. int hi_bin= fromOC(j*.125+i*.5-1.9375)/binHz+1;
  113668. if(lo_bin<0)lo_bin=0;
  113669. if(lo_bin>n)lo_bin=n;
  113670. if(lo_bin<l)l=lo_bin;
  113671. if(hi_bin<0)hi_bin=0;
  113672. if(hi_bin>n)hi_bin=n;
  113673. for(;l<hi_bin && l<n;l++)
  113674. if(brute_buffer[l]>workc[k][m][j])
  113675. brute_buffer[l]=workc[k][m][j];
  113676. }
  113677. for(;l<n;l++)
  113678. if(brute_buffer[l]>workc[k][m][EHMER_MAX-1])
  113679. brute_buffer[l]=workc[k][m][EHMER_MAX-1];
  113680. }
  113681. for(j=0;j<EHMER_MAX;j++){
  113682. int bin=fromOC(j*.125+i*.5-2.)/binHz;
  113683. if(bin<0){
  113684. ret[i][m][j+2]=-999.;
  113685. }else{
  113686. if(bin>=n){
  113687. ret[i][m][j+2]=-999.;
  113688. }else{
  113689. ret[i][m][j+2]=brute_buffer[bin];
  113690. }
  113691. }
  113692. }
  113693. /* add fenceposts */
  113694. for(j=0;j<EHMER_OFFSET;j++)
  113695. if(ret[i][m][j+2]>-200.f)break;
  113696. ret[i][m][0]=j;
  113697. for(j=EHMER_MAX-1;j>EHMER_OFFSET+1;j--)
  113698. if(ret[i][m][j+2]>-200.f)
  113699. break;
  113700. ret[i][m][1]=j;
  113701. }
  113702. }
  113703. return(ret);
  113704. }
  113705. void _vp_psy_init(vorbis_look_psy *p,vorbis_info_psy *vi,
  113706. vorbis_info_psy_global *gi,int n,long rate){
  113707. long i,j,lo=-99,hi=1;
  113708. long maxoc;
  113709. memset(p,0,sizeof(*p));
  113710. p->eighth_octave_lines=gi->eighth_octave_lines;
  113711. p->shiftoc=rint(log(gi->eighth_octave_lines*8.f)/log(2.f))-1;
  113712. p->firstoc=toOC(.25f*rate*.5/n)*(1<<(p->shiftoc+1))-gi->eighth_octave_lines;
  113713. maxoc=toOC((n+.25f)*rate*.5/n)*(1<<(p->shiftoc+1))+.5f;
  113714. p->total_octave_lines=maxoc-p->firstoc+1;
  113715. p->ath=(float*)_ogg_malloc(n*sizeof(*p->ath));
  113716. p->octave=(long*)_ogg_malloc(n*sizeof(*p->octave));
  113717. p->bark=(long*)_ogg_malloc(n*sizeof(*p->bark));
  113718. p->vi=vi;
  113719. p->n=n;
  113720. p->rate=rate;
  113721. /* AoTuV HF weighting */
  113722. p->m_val = 1.;
  113723. if(rate < 26000) p->m_val = 0;
  113724. else if(rate < 38000) p->m_val = .94; /* 32kHz */
  113725. else if(rate > 46000) p->m_val = 1.275; /* 48kHz */
  113726. /* set up the lookups for a given blocksize and sample rate */
  113727. for(i=0,j=0;i<MAX_ATH-1;i++){
  113728. int endpos=rint(fromOC((i+1)*.125-2.)*2*n/rate);
  113729. float base=ATH[i];
  113730. if(j<endpos){
  113731. float delta=(ATH[i+1]-base)/(endpos-j);
  113732. for(;j<endpos && j<n;j++){
  113733. p->ath[j]=base+100.;
  113734. base+=delta;
  113735. }
  113736. }
  113737. }
  113738. for(i=0;i<n;i++){
  113739. float bark=toBARK(rate/(2*n)*i);
  113740. for(;lo+vi->noisewindowlomin<i &&
  113741. toBARK(rate/(2*n)*lo)<(bark-vi->noisewindowlo);lo++);
  113742. for(;hi<=n && (hi<i+vi->noisewindowhimin ||
  113743. toBARK(rate/(2*n)*hi)<(bark+vi->noisewindowhi));hi++);
  113744. p->bark[i]=((lo-1)<<16)+(hi-1);
  113745. }
  113746. for(i=0;i<n;i++)
  113747. p->octave[i]=toOC((i+.25f)*.5*rate/n)*(1<<(p->shiftoc+1))+.5f;
  113748. p->tonecurves=setup_tone_curves(vi->toneatt,rate*.5/n,n,
  113749. vi->tone_centerboost,vi->tone_decay);
  113750. /* set up rolling noise median */
  113751. p->noiseoffset=(float**)_ogg_malloc(P_NOISECURVES*sizeof(*p->noiseoffset));
  113752. for(i=0;i<P_NOISECURVES;i++)
  113753. p->noiseoffset[i]=(float*)_ogg_malloc(n*sizeof(**p->noiseoffset));
  113754. for(i=0;i<n;i++){
  113755. float halfoc=toOC((i+.5)*rate/(2.*n))*2.;
  113756. int inthalfoc;
  113757. float del;
  113758. if(halfoc<0)halfoc=0;
  113759. if(halfoc>=P_BANDS-1)halfoc=P_BANDS-1;
  113760. inthalfoc=(int)halfoc;
  113761. del=halfoc-inthalfoc;
  113762. for(j=0;j<P_NOISECURVES;j++)
  113763. p->noiseoffset[j][i]=
  113764. p->vi->noiseoff[j][inthalfoc]*(1.-del) +
  113765. p->vi->noiseoff[j][inthalfoc+1]*del;
  113766. }
  113767. #if 0
  113768. {
  113769. static int ls=0;
  113770. _analysis_output_always("noiseoff0",ls,p->noiseoffset[0],n,1,0,0);
  113771. _analysis_output_always("noiseoff1",ls,p->noiseoffset[1],n,1,0,0);
  113772. _analysis_output_always("noiseoff2",ls++,p->noiseoffset[2],n,1,0,0);
  113773. }
  113774. #endif
  113775. }
  113776. void _vp_psy_clear(vorbis_look_psy *p){
  113777. int i,j;
  113778. if(p){
  113779. if(p->ath)_ogg_free(p->ath);
  113780. if(p->octave)_ogg_free(p->octave);
  113781. if(p->bark)_ogg_free(p->bark);
  113782. if(p->tonecurves){
  113783. for(i=0;i<P_BANDS;i++){
  113784. for(j=0;j<P_LEVELS;j++){
  113785. _ogg_free(p->tonecurves[i][j]);
  113786. }
  113787. _ogg_free(p->tonecurves[i]);
  113788. }
  113789. _ogg_free(p->tonecurves);
  113790. }
  113791. if(p->noiseoffset){
  113792. for(i=0;i<P_NOISECURVES;i++){
  113793. _ogg_free(p->noiseoffset[i]);
  113794. }
  113795. _ogg_free(p->noiseoffset);
  113796. }
  113797. memset(p,0,sizeof(*p));
  113798. }
  113799. }
  113800. /* octave/(8*eighth_octave_lines) x scale and dB y scale */
  113801. static void seed_curve(float *seed,
  113802. const float **curves,
  113803. float amp,
  113804. int oc, int n,
  113805. int linesper,float dBoffset){
  113806. int i,post1;
  113807. int seedptr;
  113808. const float *posts,*curve;
  113809. int choice=(int)((amp+dBoffset-P_LEVEL_0)*.1f);
  113810. choice=max(choice,0);
  113811. choice=min(choice,P_LEVELS-1);
  113812. posts=curves[choice];
  113813. curve=posts+2;
  113814. post1=(int)posts[1];
  113815. seedptr=oc+(posts[0]-EHMER_OFFSET)*linesper-(linesper>>1);
  113816. for(i=posts[0];i<post1;i++){
  113817. if(seedptr>0){
  113818. float lin=amp+curve[i];
  113819. if(seed[seedptr]<lin)seed[seedptr]=lin;
  113820. }
  113821. seedptr+=linesper;
  113822. if(seedptr>=n)break;
  113823. }
  113824. }
  113825. static void seed_loop(vorbis_look_psy *p,
  113826. const float ***curves,
  113827. const float *f,
  113828. const float *flr,
  113829. float *seed,
  113830. float specmax){
  113831. vorbis_info_psy *vi=p->vi;
  113832. long n=p->n,i;
  113833. float dBoffset=vi->max_curve_dB-specmax;
  113834. /* prime the working vector with peak values */
  113835. for(i=0;i<n;i++){
  113836. float max=f[i];
  113837. long oc=p->octave[i];
  113838. while(i+1<n && p->octave[i+1]==oc){
  113839. i++;
  113840. if(f[i]>max)max=f[i];
  113841. }
  113842. if(max+6.f>flr[i]){
  113843. oc=oc>>p->shiftoc;
  113844. if(oc>=P_BANDS)oc=P_BANDS-1;
  113845. if(oc<0)oc=0;
  113846. seed_curve(seed,
  113847. curves[oc],
  113848. max,
  113849. p->octave[i]-p->firstoc,
  113850. p->total_octave_lines,
  113851. p->eighth_octave_lines,
  113852. dBoffset);
  113853. }
  113854. }
  113855. }
  113856. static void seed_chase(float *seeds, int linesper, long n){
  113857. long *posstack=(long*)alloca(n*sizeof(*posstack));
  113858. float *ampstack=(float*)alloca(n*sizeof(*ampstack));
  113859. long stack=0;
  113860. long pos=0;
  113861. long i;
  113862. for(i=0;i<n;i++){
  113863. if(stack<2){
  113864. posstack[stack]=i;
  113865. ampstack[stack++]=seeds[i];
  113866. }else{
  113867. while(1){
  113868. if(seeds[i]<ampstack[stack-1]){
  113869. posstack[stack]=i;
  113870. ampstack[stack++]=seeds[i];
  113871. break;
  113872. }else{
  113873. if(i<posstack[stack-1]+linesper){
  113874. if(stack>1 && ampstack[stack-1]<=ampstack[stack-2] &&
  113875. i<posstack[stack-2]+linesper){
  113876. /* we completely overlap, making stack-1 irrelevant. pop it */
  113877. stack--;
  113878. continue;
  113879. }
  113880. }
  113881. posstack[stack]=i;
  113882. ampstack[stack++]=seeds[i];
  113883. break;
  113884. }
  113885. }
  113886. }
  113887. }
  113888. /* the stack now contains only the positions that are relevant. Scan
  113889. 'em straight through */
  113890. for(i=0;i<stack;i++){
  113891. long endpos;
  113892. if(i<stack-1 && ampstack[i+1]>ampstack[i]){
  113893. endpos=posstack[i+1];
  113894. }else{
  113895. endpos=posstack[i]+linesper+1; /* +1 is important, else bin 0 is
  113896. discarded in short frames */
  113897. }
  113898. if(endpos>n)endpos=n;
  113899. for(;pos<endpos;pos++)
  113900. seeds[pos]=ampstack[i];
  113901. }
  113902. /* there. Linear time. I now remember this was on a problem set I
  113903. had in Grad Skool... I didn't solve it at the time ;-) */
  113904. }
  113905. /* bleaugh, this is more complicated than it needs to be */
  113906. #include<stdio.h>
  113907. static void max_seeds(vorbis_look_psy *p,
  113908. float *seed,
  113909. float *flr){
  113910. long n=p->total_octave_lines;
  113911. int linesper=p->eighth_octave_lines;
  113912. long linpos=0;
  113913. long pos;
  113914. seed_chase(seed,linesper,n); /* for masking */
  113915. pos=p->octave[0]-p->firstoc-(linesper>>1);
  113916. while(linpos+1<p->n){
  113917. float minV=seed[pos];
  113918. long end=((p->octave[linpos]+p->octave[linpos+1])>>1)-p->firstoc;
  113919. if(minV>p->vi->tone_abs_limit)minV=p->vi->tone_abs_limit;
  113920. while(pos+1<=end){
  113921. pos++;
  113922. if((seed[pos]>NEGINF && seed[pos]<minV) || minV==NEGINF)
  113923. minV=seed[pos];
  113924. }
  113925. end=pos+p->firstoc;
  113926. for(;linpos<p->n && p->octave[linpos]<=end;linpos++)
  113927. if(flr[linpos]<minV)flr[linpos]=minV;
  113928. }
  113929. {
  113930. float minV=seed[p->total_octave_lines-1];
  113931. for(;linpos<p->n;linpos++)
  113932. if(flr[linpos]<minV)flr[linpos]=minV;
  113933. }
  113934. }
  113935. static void bark_noise_hybridmp(int n,const long *b,
  113936. const float *f,
  113937. float *noise,
  113938. const float offset,
  113939. const int fixed){
  113940. float *N=(float*) alloca(n*sizeof(*N));
  113941. float *X=(float*) alloca(n*sizeof(*N));
  113942. float *XX=(float*) alloca(n*sizeof(*N));
  113943. float *Y=(float*) alloca(n*sizeof(*N));
  113944. float *XY=(float*) alloca(n*sizeof(*N));
  113945. float tN, tX, tXX, tY, tXY;
  113946. int i;
  113947. int lo, hi;
  113948. float R, A, B, D;
  113949. float w, x, y;
  113950. tN = tX = tXX = tY = tXY = 0.f;
  113951. y = f[0] + offset;
  113952. if (y < 1.f) y = 1.f;
  113953. w = y * y * .5;
  113954. tN += w;
  113955. tX += w;
  113956. tY += w * y;
  113957. N[0] = tN;
  113958. X[0] = tX;
  113959. XX[0] = tXX;
  113960. Y[0] = tY;
  113961. XY[0] = tXY;
  113962. for (i = 1, x = 1.f; i < n; i++, x += 1.f) {
  113963. y = f[i] + offset;
  113964. if (y < 1.f) y = 1.f;
  113965. w = y * y;
  113966. tN += w;
  113967. tX += w * x;
  113968. tXX += w * x * x;
  113969. tY += w * y;
  113970. tXY += w * x * y;
  113971. N[i] = tN;
  113972. X[i] = tX;
  113973. XX[i] = tXX;
  113974. Y[i] = tY;
  113975. XY[i] = tXY;
  113976. }
  113977. for (i = 0, x = 0.f;; i++, x += 1.f) {
  113978. lo = b[i] >> 16;
  113979. if( lo>=0 ) break;
  113980. hi = b[i] & 0xffff;
  113981. tN = N[hi] + N[-lo];
  113982. tX = X[hi] - X[-lo];
  113983. tXX = XX[hi] + XX[-lo];
  113984. tY = Y[hi] + Y[-lo];
  113985. tXY = XY[hi] - XY[-lo];
  113986. A = tY * tXX - tX * tXY;
  113987. B = tN * tXY - tX * tY;
  113988. D = tN * tXX - tX * tX;
  113989. R = (A + x * B) / D;
  113990. if (R < 0.f)
  113991. R = 0.f;
  113992. noise[i] = R - offset;
  113993. }
  113994. for ( ;; i++, x += 1.f) {
  113995. lo = b[i] >> 16;
  113996. hi = b[i] & 0xffff;
  113997. if(hi>=n)break;
  113998. tN = N[hi] - N[lo];
  113999. tX = X[hi] - X[lo];
  114000. tXX = XX[hi] - XX[lo];
  114001. tY = Y[hi] - Y[lo];
  114002. tXY = XY[hi] - XY[lo];
  114003. A = tY * tXX - tX * tXY;
  114004. B = tN * tXY - tX * tY;
  114005. D = tN * tXX - tX * tX;
  114006. R = (A + x * B) / D;
  114007. if (R < 0.f) R = 0.f;
  114008. noise[i] = R - offset;
  114009. }
  114010. for ( ; i < n; i++, x += 1.f) {
  114011. R = (A + x * B) / D;
  114012. if (R < 0.f) R = 0.f;
  114013. noise[i] = R - offset;
  114014. }
  114015. if (fixed <= 0) return;
  114016. for (i = 0, x = 0.f;; i++, x += 1.f) {
  114017. hi = i + fixed / 2;
  114018. lo = hi - fixed;
  114019. if(lo>=0)break;
  114020. tN = N[hi] + N[-lo];
  114021. tX = X[hi] - X[-lo];
  114022. tXX = XX[hi] + XX[-lo];
  114023. tY = Y[hi] + Y[-lo];
  114024. tXY = XY[hi] - XY[-lo];
  114025. A = tY * tXX - tX * tXY;
  114026. B = tN * tXY - tX * tY;
  114027. D = tN * tXX - tX * tX;
  114028. R = (A + x * B) / D;
  114029. if (R - offset < noise[i]) noise[i] = R - offset;
  114030. }
  114031. for ( ;; i++, x += 1.f) {
  114032. hi = i + fixed / 2;
  114033. lo = hi - fixed;
  114034. if(hi>=n)break;
  114035. tN = N[hi] - N[lo];
  114036. tX = X[hi] - X[lo];
  114037. tXX = XX[hi] - XX[lo];
  114038. tY = Y[hi] - Y[lo];
  114039. tXY = XY[hi] - XY[lo];
  114040. A = tY * tXX - tX * tXY;
  114041. B = tN * tXY - tX * tY;
  114042. D = tN * tXX - tX * tX;
  114043. R = (A + x * B) / D;
  114044. if (R - offset < noise[i]) noise[i] = R - offset;
  114045. }
  114046. for ( ; i < n; i++, x += 1.f) {
  114047. R = (A + x * B) / D;
  114048. if (R - offset < noise[i]) noise[i] = R - offset;
  114049. }
  114050. }
  114051. static float FLOOR1_fromdB_INV_LOOKUP[256]={
  114052. 0.F, 8.81683e+06F, 8.27882e+06F, 7.77365e+06F,
  114053. 7.29930e+06F, 6.85389e+06F, 6.43567e+06F, 6.04296e+06F,
  114054. 5.67422e+06F, 5.32798e+06F, 5.00286e+06F, 4.69759e+06F,
  114055. 4.41094e+06F, 4.14178e+06F, 3.88905e+06F, 3.65174e+06F,
  114056. 3.42891e+06F, 3.21968e+06F, 3.02321e+06F, 2.83873e+06F,
  114057. 2.66551e+06F, 2.50286e+06F, 2.35014e+06F, 2.20673e+06F,
  114058. 2.07208e+06F, 1.94564e+06F, 1.82692e+06F, 1.71544e+06F,
  114059. 1.61076e+06F, 1.51247e+06F, 1.42018e+06F, 1.33352e+06F,
  114060. 1.25215e+06F, 1.17574e+06F, 1.10400e+06F, 1.03663e+06F,
  114061. 973377.F, 913981.F, 858210.F, 805842.F,
  114062. 756669.F, 710497.F, 667142.F, 626433.F,
  114063. 588208.F, 552316.F, 518613.F, 486967.F,
  114064. 457252.F, 429351.F, 403152.F, 378551.F,
  114065. 355452.F, 333762.F, 313396.F, 294273.F,
  114066. 276316.F, 259455.F, 243623.F, 228757.F,
  114067. 214798.F, 201691.F, 189384.F, 177828.F,
  114068. 166977.F, 156788.F, 147221.F, 138237.F,
  114069. 129802.F, 121881.F, 114444.F, 107461.F,
  114070. 100903.F, 94746.3F, 88964.9F, 83536.2F,
  114071. 78438.8F, 73652.5F, 69158.2F, 64938.1F,
  114072. 60975.6F, 57254.9F, 53761.2F, 50480.6F,
  114073. 47400.3F, 44507.9F, 41792.0F, 39241.9F,
  114074. 36847.3F, 34598.9F, 32487.7F, 30505.3F,
  114075. 28643.8F, 26896.0F, 25254.8F, 23713.7F,
  114076. 22266.7F, 20908.0F, 19632.2F, 18434.2F,
  114077. 17309.4F, 16253.1F, 15261.4F, 14330.1F,
  114078. 13455.7F, 12634.6F, 11863.7F, 11139.7F,
  114079. 10460.0F, 9821.72F, 9222.39F, 8659.64F,
  114080. 8131.23F, 7635.06F, 7169.17F, 6731.70F,
  114081. 6320.93F, 5935.23F, 5573.06F, 5232.99F,
  114082. 4913.67F, 4613.84F, 4332.30F, 4067.94F,
  114083. 3819.72F, 3586.64F, 3367.78F, 3162.28F,
  114084. 2969.31F, 2788.13F, 2617.99F, 2458.24F,
  114085. 2308.24F, 2167.39F, 2035.14F, 1910.95F,
  114086. 1794.35F, 1684.85F, 1582.04F, 1485.51F,
  114087. 1394.86F, 1309.75F, 1229.83F, 1154.78F,
  114088. 1084.32F, 1018.15F, 956.024F, 897.687F,
  114089. 842.910F, 791.475F, 743.179F, 697.830F,
  114090. 655.249F, 615.265F, 577.722F, 542.469F,
  114091. 509.367F, 478.286F, 449.101F, 421.696F,
  114092. 395.964F, 371.803F, 349.115F, 327.812F,
  114093. 307.809F, 289.026F, 271.390F, 254.830F,
  114094. 239.280F, 224.679F, 210.969F, 198.096F,
  114095. 186.008F, 174.658F, 164.000F, 153.993F,
  114096. 144.596F, 135.773F, 127.488F, 119.708F,
  114097. 112.404F, 105.545F, 99.1046F, 93.0572F,
  114098. 87.3788F, 82.0469F, 77.0404F, 72.3394F,
  114099. 67.9252F, 63.7804F, 59.8885F, 56.2341F,
  114100. 52.8027F, 49.5807F, 46.5553F, 43.7144F,
  114101. 41.0470F, 38.5423F, 36.1904F, 33.9821F,
  114102. 31.9085F, 29.9614F, 28.1332F, 26.4165F,
  114103. 24.8045F, 23.2910F, 21.8697F, 20.5352F,
  114104. 19.2822F, 18.1056F, 17.0008F, 15.9634F,
  114105. 14.9893F, 14.0746F, 13.2158F, 12.4094F,
  114106. 11.6522F, 10.9411F, 10.2735F, 9.64662F,
  114107. 9.05798F, 8.50526F, 7.98626F, 7.49894F,
  114108. 7.04135F, 6.61169F, 6.20824F, 5.82941F,
  114109. 5.47370F, 5.13970F, 4.82607F, 4.53158F,
  114110. 4.25507F, 3.99542F, 3.75162F, 3.52269F,
  114111. 3.30774F, 3.10590F, 2.91638F, 2.73842F,
  114112. 2.57132F, 2.41442F, 2.26709F, 2.12875F,
  114113. 1.99885F, 1.87688F, 1.76236F, 1.65482F,
  114114. 1.55384F, 1.45902F, 1.36999F, 1.28640F,
  114115. 1.20790F, 1.13419F, 1.06499F, 1.F
  114116. };
  114117. void _vp_remove_floor(vorbis_look_psy *p,
  114118. float *mdct,
  114119. int *codedflr,
  114120. float *residue,
  114121. int sliding_lowpass){
  114122. int i,n=p->n;
  114123. if(sliding_lowpass>n)sliding_lowpass=n;
  114124. for(i=0;i<sliding_lowpass;i++){
  114125. residue[i]=
  114126. mdct[i]*FLOOR1_fromdB_INV_LOOKUP[codedflr[i]];
  114127. }
  114128. for(;i<n;i++)
  114129. residue[i]=0.;
  114130. }
  114131. void _vp_noisemask(vorbis_look_psy *p,
  114132. float *logmdct,
  114133. float *logmask){
  114134. int i,n=p->n;
  114135. float *work=(float*) alloca(n*sizeof(*work));
  114136. bark_noise_hybridmp(n,p->bark,logmdct,logmask,
  114137. 140.,-1);
  114138. for(i=0;i<n;i++)work[i]=logmdct[i]-logmask[i];
  114139. bark_noise_hybridmp(n,p->bark,work,logmask,0.,
  114140. p->vi->noisewindowfixed);
  114141. for(i=0;i<n;i++)work[i]=logmdct[i]-work[i];
  114142. #if 0
  114143. {
  114144. static int seq=0;
  114145. float work2[n];
  114146. for(i=0;i<n;i++){
  114147. work2[i]=logmask[i]+work[i];
  114148. }
  114149. if(seq&1)
  114150. _analysis_output("median2R",seq/2,work,n,1,0,0);
  114151. else
  114152. _analysis_output("median2L",seq/2,work,n,1,0,0);
  114153. if(seq&1)
  114154. _analysis_output("envelope2R",seq/2,work2,n,1,0,0);
  114155. else
  114156. _analysis_output("envelope2L",seq/2,work2,n,1,0,0);
  114157. seq++;
  114158. }
  114159. #endif
  114160. for(i=0;i<n;i++){
  114161. int dB=logmask[i]+.5;
  114162. if(dB>=NOISE_COMPAND_LEVELS)dB=NOISE_COMPAND_LEVELS-1;
  114163. if(dB<0)dB=0;
  114164. logmask[i]= work[i]+p->vi->noisecompand[dB];
  114165. }
  114166. }
  114167. void _vp_tonemask(vorbis_look_psy *p,
  114168. float *logfft,
  114169. float *logmask,
  114170. float global_specmax,
  114171. float local_specmax){
  114172. int i,n=p->n;
  114173. float *seed=(float*) alloca(sizeof(*seed)*p->total_octave_lines);
  114174. float att=local_specmax+p->vi->ath_adjatt;
  114175. for(i=0;i<p->total_octave_lines;i++)seed[i]=NEGINF;
  114176. /* set the ATH (floating below localmax, not global max by a
  114177. specified att) */
  114178. if(att<p->vi->ath_maxatt)att=p->vi->ath_maxatt;
  114179. for(i=0;i<n;i++)
  114180. logmask[i]=p->ath[i]+att;
  114181. /* tone masking */
  114182. seed_loop(p,(const float ***)p->tonecurves,logfft,logmask,seed,global_specmax);
  114183. max_seeds(p,seed,logmask);
  114184. }
  114185. void _vp_offset_and_mix(vorbis_look_psy *p,
  114186. float *noise,
  114187. float *tone,
  114188. int offset_select,
  114189. float *logmask,
  114190. float *mdct,
  114191. float *logmdct){
  114192. int i,n=p->n;
  114193. float de, coeffi, cx;/* AoTuV */
  114194. float toneatt=p->vi->tone_masteratt[offset_select];
  114195. cx = p->m_val;
  114196. for(i=0;i<n;i++){
  114197. float val= noise[i]+p->noiseoffset[offset_select][i];
  114198. if(val>p->vi->noisemaxsupp)val=p->vi->noisemaxsupp;
  114199. logmask[i]=max(val,tone[i]+toneatt);
  114200. /* AoTuV */
  114201. /** @ M1 **
  114202. The following codes improve a noise problem.
  114203. A fundamental idea uses the value of masking and carries out
  114204. the relative compensation of the MDCT.
  114205. However, this code is not perfect and all noise problems cannot be solved.
  114206. by Aoyumi @ 2004/04/18
  114207. */
  114208. if(offset_select == 1) {
  114209. coeffi = -17.2; /* coeffi is a -17.2dB threshold */
  114210. val = val - logmdct[i]; /* val == mdct line value relative to floor in dB */
  114211. if(val > coeffi){
  114212. /* mdct value is > -17.2 dB below floor */
  114213. de = 1.0-((val-coeffi)*0.005*cx);
  114214. /* pro-rated attenuation:
  114215. -0.00 dB boost if mdct value is -17.2dB (relative to floor)
  114216. -0.77 dB boost if mdct value is 0dB (relative to floor)
  114217. -1.64 dB boost if mdct value is +17.2dB (relative to floor)
  114218. etc... */
  114219. if(de < 0) de = 0.0001;
  114220. }else
  114221. /* mdct value is <= -17.2 dB below floor */
  114222. de = 1.0-((val-coeffi)*0.0003*cx);
  114223. /* pro-rated attenuation:
  114224. +0.00 dB atten if mdct value is -17.2dB (relative to floor)
  114225. +0.45 dB atten if mdct value is -34.4dB (relative to floor)
  114226. etc... */
  114227. mdct[i] *= de;
  114228. }
  114229. }
  114230. }
  114231. float _vp_ampmax_decay(float amp,vorbis_dsp_state *vd){
  114232. vorbis_info *vi=vd->vi;
  114233. codec_setup_info *ci=(codec_setup_info*)vi->codec_setup;
  114234. vorbis_info_psy_global *gi=&ci->psy_g_param;
  114235. int n=ci->blocksizes[vd->W]/2;
  114236. float secs=(float)n/vi->rate;
  114237. amp+=secs*gi->ampmax_att_per_sec;
  114238. if(amp<-9999)amp=-9999;
  114239. return(amp);
  114240. }
  114241. static void couple_lossless(float A, float B,
  114242. float *qA, float *qB){
  114243. int test1=fabs(*qA)>fabs(*qB);
  114244. test1-= fabs(*qA)<fabs(*qB);
  114245. if(!test1)test1=((fabs(A)>fabs(B))<<1)-1;
  114246. if(test1==1){
  114247. *qB=(*qA>0.f?*qA-*qB:*qB-*qA);
  114248. }else{
  114249. float temp=*qB;
  114250. *qB=(*qB>0.f?*qA-*qB:*qB-*qA);
  114251. *qA=temp;
  114252. }
  114253. if(*qB>fabs(*qA)*1.9999f){
  114254. *qB= -fabs(*qA)*2.f;
  114255. *qA= -*qA;
  114256. }
  114257. }
  114258. static float hypot_lookup[32]={
  114259. -0.009935, -0.011245, -0.012726, -0.014397,
  114260. -0.016282, -0.018407, -0.020800, -0.023494,
  114261. -0.026522, -0.029923, -0.033737, -0.038010,
  114262. -0.042787, -0.048121, -0.054064, -0.060671,
  114263. -0.068000, -0.076109, -0.085054, -0.094892,
  114264. -0.105675, -0.117451, -0.130260, -0.144134,
  114265. -0.159093, -0.175146, -0.192286, -0.210490,
  114266. -0.229718, -0.249913, -0.271001, -0.292893};
  114267. static void precomputed_couple_point(float premag,
  114268. int floorA,int floorB,
  114269. float *mag, float *ang){
  114270. int test=(floorA>floorB)-1;
  114271. int offset=31-abs(floorA-floorB);
  114272. float floormag=hypot_lookup[((offset<0)-1)&offset]+1.f;
  114273. floormag*=FLOOR1_fromdB_INV_LOOKUP[(floorB&test)|(floorA&(~test))];
  114274. *mag=premag*floormag;
  114275. *ang=0.f;
  114276. }
  114277. /* just like below, this is currently set up to only do
  114278. single-step-depth coupling. Otherwise, we'd have to do more
  114279. copying (which will be inevitable later) */
  114280. /* doing the real circular magnitude calculation is audibly superior
  114281. to (A+B)/sqrt(2) */
  114282. static float dipole_hypot(float a, float b){
  114283. if(a>0.){
  114284. if(b>0.)return sqrt(a*a+b*b);
  114285. if(a>-b)return sqrt(a*a-b*b);
  114286. return -sqrt(b*b-a*a);
  114287. }
  114288. if(b<0.)return -sqrt(a*a+b*b);
  114289. if(-a>b)return -sqrt(a*a-b*b);
  114290. return sqrt(b*b-a*a);
  114291. }
  114292. static float round_hypot(float a, float b){
  114293. if(a>0.){
  114294. if(b>0.)return sqrt(a*a+b*b);
  114295. if(a>-b)return sqrt(a*a+b*b);
  114296. return -sqrt(b*b+a*a);
  114297. }
  114298. if(b<0.)return -sqrt(a*a+b*b);
  114299. if(-a>b)return -sqrt(a*a+b*b);
  114300. return sqrt(b*b+a*a);
  114301. }
  114302. /* revert to round hypot for now */
  114303. float **_vp_quantize_couple_memo(vorbis_block *vb,
  114304. vorbis_info_psy_global *g,
  114305. vorbis_look_psy *p,
  114306. vorbis_info_mapping0 *vi,
  114307. float **mdct){
  114308. int i,j,n=p->n;
  114309. float **ret=(float**) _vorbis_block_alloc(vb,vi->coupling_steps*sizeof(*ret));
  114310. int limit=g->coupling_pointlimit[p->vi->blockflag][PACKETBLOBS/2];
  114311. for(i=0;i<vi->coupling_steps;i++){
  114312. float *mdctM=mdct[vi->coupling_mag[i]];
  114313. float *mdctA=mdct[vi->coupling_ang[i]];
  114314. ret[i]=(float*) _vorbis_block_alloc(vb,n*sizeof(**ret));
  114315. for(j=0;j<limit;j++)
  114316. ret[i][j]=dipole_hypot(mdctM[j],mdctA[j]);
  114317. for(;j<n;j++)
  114318. ret[i][j]=round_hypot(mdctM[j],mdctA[j]);
  114319. }
  114320. return(ret);
  114321. }
  114322. /* this is for per-channel noise normalization */
  114323. static int apsort(const void *a, const void *b){
  114324. float f1=fabs(**(float**)a);
  114325. float f2=fabs(**(float**)b);
  114326. return (f1<f2)-(f1>f2);
  114327. }
  114328. int **_vp_quantize_couple_sort(vorbis_block *vb,
  114329. vorbis_look_psy *p,
  114330. vorbis_info_mapping0 *vi,
  114331. float **mags){
  114332. if(p->vi->normal_point_p){
  114333. int i,j,k,n=p->n;
  114334. int **ret=(int**) _vorbis_block_alloc(vb,vi->coupling_steps*sizeof(*ret));
  114335. int partition=p->vi->normal_partition;
  114336. float **work=(float**) alloca(sizeof(*work)*partition);
  114337. for(i=0;i<vi->coupling_steps;i++){
  114338. ret[i]=(int*) _vorbis_block_alloc(vb,n*sizeof(**ret));
  114339. for(j=0;j<n;j+=partition){
  114340. for(k=0;k<partition;k++)work[k]=mags[i]+k+j;
  114341. qsort(work,partition,sizeof(*work),apsort);
  114342. for(k=0;k<partition;k++)ret[i][k+j]=work[k]-mags[i];
  114343. }
  114344. }
  114345. return(ret);
  114346. }
  114347. return(NULL);
  114348. }
  114349. void _vp_noise_normalize_sort(vorbis_look_psy *p,
  114350. float *magnitudes,int *sortedindex){
  114351. int i,j,n=p->n;
  114352. vorbis_info_psy *vi=p->vi;
  114353. int partition=vi->normal_partition;
  114354. float **work=(float**) alloca(sizeof(*work)*partition);
  114355. int start=vi->normal_start;
  114356. for(j=start;j<n;j+=partition){
  114357. if(j+partition>n)partition=n-j;
  114358. for(i=0;i<partition;i++)work[i]=magnitudes+i+j;
  114359. qsort(work,partition,sizeof(*work),apsort);
  114360. for(i=0;i<partition;i++){
  114361. sortedindex[i+j-start]=work[i]-magnitudes;
  114362. }
  114363. }
  114364. }
  114365. void _vp_noise_normalize(vorbis_look_psy *p,
  114366. float *in,float *out,int *sortedindex){
  114367. int flag=0,i,j=0,n=p->n;
  114368. vorbis_info_psy *vi=p->vi;
  114369. int partition=vi->normal_partition;
  114370. int start=vi->normal_start;
  114371. if(start>n)start=n;
  114372. if(vi->normal_channel_p){
  114373. for(;j<start;j++)
  114374. out[j]=rint(in[j]);
  114375. for(;j+partition<=n;j+=partition){
  114376. float acc=0.;
  114377. int k;
  114378. for(i=j;i<j+partition;i++)
  114379. acc+=in[i]*in[i];
  114380. for(i=0;i<partition;i++){
  114381. k=sortedindex[i+j-start];
  114382. if(in[k]*in[k]>=.25f){
  114383. out[k]=rint(in[k]);
  114384. acc-=in[k]*in[k];
  114385. flag=1;
  114386. }else{
  114387. if(acc<vi->normal_thresh)break;
  114388. out[k]=unitnorm(in[k]);
  114389. acc-=1.;
  114390. }
  114391. }
  114392. for(;i<partition;i++){
  114393. k=sortedindex[i+j-start];
  114394. out[k]=0.;
  114395. }
  114396. }
  114397. }
  114398. for(;j<n;j++)
  114399. out[j]=rint(in[j]);
  114400. }
  114401. void _vp_couple(int blobno,
  114402. vorbis_info_psy_global *g,
  114403. vorbis_look_psy *p,
  114404. vorbis_info_mapping0 *vi,
  114405. float **res,
  114406. float **mag_memo,
  114407. int **mag_sort,
  114408. int **ifloor,
  114409. int *nonzero,
  114410. int sliding_lowpass){
  114411. int i,j,k,n=p->n;
  114412. /* perform any requested channel coupling */
  114413. /* point stereo can only be used in a first stage (in this encoder)
  114414. because of the dependency on floor lookups */
  114415. for(i=0;i<vi->coupling_steps;i++){
  114416. /* once we're doing multistage coupling in which a channel goes
  114417. through more than one coupling step, the floor vector
  114418. magnitudes will also have to be recalculated an propogated
  114419. along with PCM. Right now, we're not (that will wait until 5.1
  114420. most likely), so the code isn't here yet. The memory management
  114421. here is all assuming single depth couplings anyway. */
  114422. /* make sure coupling a zero and a nonzero channel results in two
  114423. nonzero channels. */
  114424. if(nonzero[vi->coupling_mag[i]] ||
  114425. nonzero[vi->coupling_ang[i]]){
  114426. float *rM=res[vi->coupling_mag[i]];
  114427. float *rA=res[vi->coupling_ang[i]];
  114428. float *qM=rM+n;
  114429. float *qA=rA+n;
  114430. int *floorM=ifloor[vi->coupling_mag[i]];
  114431. int *floorA=ifloor[vi->coupling_ang[i]];
  114432. float prepoint=stereo_threshholds[g->coupling_prepointamp[blobno]];
  114433. float postpoint=stereo_threshholds[g->coupling_postpointamp[blobno]];
  114434. int partition=(p->vi->normal_point_p?p->vi->normal_partition:p->n);
  114435. int limit=g->coupling_pointlimit[p->vi->blockflag][blobno];
  114436. int pointlimit=limit;
  114437. nonzero[vi->coupling_mag[i]]=1;
  114438. nonzero[vi->coupling_ang[i]]=1;
  114439. /* The threshold of a stereo is changed with the size of n */
  114440. if(n > 1000)
  114441. postpoint=stereo_threshholds_limited[g->coupling_postpointamp[blobno]];
  114442. for(j=0;j<p->n;j+=partition){
  114443. float acc=0.f;
  114444. for(k=0;k<partition;k++){
  114445. int l=k+j;
  114446. if(l<sliding_lowpass){
  114447. if((l>=limit && fabs(rM[l])<postpoint && fabs(rA[l])<postpoint) ||
  114448. (fabs(rM[l])<prepoint && fabs(rA[l])<prepoint)){
  114449. precomputed_couple_point(mag_memo[i][l],
  114450. floorM[l],floorA[l],
  114451. qM+l,qA+l);
  114452. if(rint(qM[l])==0.f)acc+=qM[l]*qM[l];
  114453. }else{
  114454. couple_lossless(rM[l],rA[l],qM+l,qA+l);
  114455. }
  114456. }else{
  114457. qM[l]=0.;
  114458. qA[l]=0.;
  114459. }
  114460. }
  114461. if(p->vi->normal_point_p){
  114462. for(k=0;k<partition && acc>=p->vi->normal_thresh;k++){
  114463. int l=mag_sort[i][j+k];
  114464. if(l<sliding_lowpass && l>=pointlimit && rint(qM[l])==0.f){
  114465. qM[l]=unitnorm(qM[l]);
  114466. acc-=1.f;
  114467. }
  114468. }
  114469. }
  114470. }
  114471. }
  114472. }
  114473. }
  114474. /* AoTuV */
  114475. /** @ M2 **
  114476. The boost problem by the combination of noise normalization and point stereo is eased.
  114477. However, this is a temporary patch.
  114478. by Aoyumi @ 2004/04/18
  114479. */
  114480. void hf_reduction(vorbis_info_psy_global *g,
  114481. vorbis_look_psy *p,
  114482. vorbis_info_mapping0 *vi,
  114483. float **mdct){
  114484. int i,j,n=p->n, de=0.3*p->m_val;
  114485. int limit=g->coupling_pointlimit[p->vi->blockflag][PACKETBLOBS/2];
  114486. for(i=0; i<vi->coupling_steps; i++){
  114487. /* for(j=start; j<limit; j++){} // ???*/
  114488. for(j=limit; j<n; j++)
  114489. mdct[i][j] *= (1.0 - de*((float)(j-limit) / (float)(n-limit)));
  114490. }
  114491. }
  114492. #endif
  114493. /*** End of inlined file: psy.c ***/
  114494. /*** Start of inlined file: registry.c ***/
  114495. /*** Start of inlined file: juce_OggVorbisHeader.h ***/
  114496. // This file is included at the start of each Ogg-Vorbis .c file, just to do a few housekeeping
  114497. // tasks..
  114498. #if JUCE_MSVC
  114499. #pragma warning (disable: 4267 4127 4244 4996 4100 4701 4702 4013 4133 4206 4305 4189 4706)
  114500. #endif
  114501. /*** End of inlined file: juce_OggVorbisHeader.h ***/
  114502. #if JUCE_USE_OGGVORBIS
  114503. /* seems like major overkill now; the backend numbers will grow into
  114504. the infrastructure soon enough */
  114505. extern vorbis_func_floor floor0_exportbundle;
  114506. extern vorbis_func_floor floor1_exportbundle;
  114507. extern vorbis_func_residue residue0_exportbundle;
  114508. extern vorbis_func_residue residue1_exportbundle;
  114509. extern vorbis_func_residue residue2_exportbundle;
  114510. extern vorbis_func_mapping mapping0_exportbundle;
  114511. vorbis_func_floor *_floor_P[]={
  114512. &floor0_exportbundle,
  114513. &floor1_exportbundle,
  114514. };
  114515. vorbis_func_residue *_residue_P[]={
  114516. &residue0_exportbundle,
  114517. &residue1_exportbundle,
  114518. &residue2_exportbundle,
  114519. };
  114520. vorbis_func_mapping *_mapping_P[]={
  114521. &mapping0_exportbundle,
  114522. };
  114523. #endif
  114524. /*** End of inlined file: registry.c ***/
  114525. /*** Start of inlined file: res0.c ***/
  114526. /* Slow, slow, slow, simpleminded and did I mention it was slow? The
  114527. encode/decode loops are coded for clarity and performance is not
  114528. yet even a nagging little idea lurking in the shadows. Oh and BTW,
  114529. it's slow. */
  114530. /*** Start of inlined file: juce_OggVorbisHeader.h ***/
  114531. // This file is included at the start of each Ogg-Vorbis .c file, just to do a few housekeeping
  114532. // tasks..
  114533. #if JUCE_MSVC
  114534. #pragma warning (disable: 4267 4127 4244 4996 4100 4701 4702 4013 4133 4206 4305 4189 4706)
  114535. #endif
  114536. /*** End of inlined file: juce_OggVorbisHeader.h ***/
  114537. #if JUCE_USE_OGGVORBIS
  114538. #include <stdlib.h>
  114539. #include <string.h>
  114540. #include <math.h>
  114541. #if defined(TRAIN_RES) || defined (TRAIN_RESAUX)
  114542. #include <stdio.h>
  114543. #endif
  114544. typedef struct {
  114545. vorbis_info_residue0 *info;
  114546. int parts;
  114547. int stages;
  114548. codebook *fullbooks;
  114549. codebook *phrasebook;
  114550. codebook ***partbooks;
  114551. int partvals;
  114552. int **decodemap;
  114553. long postbits;
  114554. long phrasebits;
  114555. long frames;
  114556. #if defined(TRAIN_RES) || defined(TRAIN_RESAUX)
  114557. int train_seq;
  114558. long *training_data[8][64];
  114559. float training_max[8][64];
  114560. float training_min[8][64];
  114561. float tmin;
  114562. float tmax;
  114563. #endif
  114564. } vorbis_look_residue0;
  114565. void res0_free_info(vorbis_info_residue *i){
  114566. vorbis_info_residue0 *info=(vorbis_info_residue0 *)i;
  114567. if(info){
  114568. memset(info,0,sizeof(*info));
  114569. _ogg_free(info);
  114570. }
  114571. }
  114572. void res0_free_look(vorbis_look_residue *i){
  114573. int j;
  114574. if(i){
  114575. vorbis_look_residue0 *look=(vorbis_look_residue0 *)i;
  114576. #ifdef TRAIN_RES
  114577. {
  114578. int j,k,l;
  114579. for(j=0;j<look->parts;j++){
  114580. /*fprintf(stderr,"partition %d: ",j);*/
  114581. for(k=0;k<8;k++)
  114582. if(look->training_data[k][j]){
  114583. char buffer[80];
  114584. FILE *of;
  114585. codebook *statebook=look->partbooks[j][k];
  114586. /* long and short into the same bucket by current convention */
  114587. sprintf(buffer,"res_part%d_pass%d.vqd",j,k);
  114588. of=fopen(buffer,"a");
  114589. for(l=0;l<statebook->entries;l++)
  114590. fprintf(of,"%d:%ld\n",l,look->training_data[k][j][l]);
  114591. fclose(of);
  114592. /*fprintf(stderr,"%d(%.2f|%.2f) ",k,
  114593. look->training_min[k][j],look->training_max[k][j]);*/
  114594. _ogg_free(look->training_data[k][j]);
  114595. look->training_data[k][j]=NULL;
  114596. }
  114597. /*fprintf(stderr,"\n");*/
  114598. }
  114599. }
  114600. fprintf(stderr,"min/max residue: %g::%g\n",look->tmin,look->tmax);
  114601. /*fprintf(stderr,"residue bit usage %f:%f (%f total)\n",
  114602. (float)look->phrasebits/look->frames,
  114603. (float)look->postbits/look->frames,
  114604. (float)(look->postbits+look->phrasebits)/look->frames);*/
  114605. #endif
  114606. /*vorbis_info_residue0 *info=look->info;
  114607. fprintf(stderr,
  114608. "%ld frames encoded in %ld phrasebits and %ld residue bits "
  114609. "(%g/frame) \n",look->frames,look->phrasebits,
  114610. look->resbitsflat,
  114611. (look->phrasebits+look->resbitsflat)/(float)look->frames);
  114612. for(j=0;j<look->parts;j++){
  114613. long acc=0;
  114614. fprintf(stderr,"\t[%d] == ",j);
  114615. for(k=0;k<look->stages;k++)
  114616. if((info->secondstages[j]>>k)&1){
  114617. fprintf(stderr,"%ld,",look->resbits[j][k]);
  114618. acc+=look->resbits[j][k];
  114619. }
  114620. fprintf(stderr,":: (%ld vals) %1.2fbits/sample\n",look->resvals[j],
  114621. acc?(float)acc/(look->resvals[j]*info->grouping):0);
  114622. }
  114623. fprintf(stderr,"\n");*/
  114624. for(j=0;j<look->parts;j++)
  114625. if(look->partbooks[j])_ogg_free(look->partbooks[j]);
  114626. _ogg_free(look->partbooks);
  114627. for(j=0;j<look->partvals;j++)
  114628. _ogg_free(look->decodemap[j]);
  114629. _ogg_free(look->decodemap);
  114630. memset(look,0,sizeof(*look));
  114631. _ogg_free(look);
  114632. }
  114633. }
  114634. static int icount(unsigned int v){
  114635. int ret=0;
  114636. while(v){
  114637. ret+=v&1;
  114638. v>>=1;
  114639. }
  114640. return(ret);
  114641. }
  114642. void res0_pack(vorbis_info_residue *vr,oggpack_buffer *opb){
  114643. vorbis_info_residue0 *info=(vorbis_info_residue0 *)vr;
  114644. int j,acc=0;
  114645. oggpack_write(opb,info->begin,24);
  114646. oggpack_write(opb,info->end,24);
  114647. oggpack_write(opb,info->grouping-1,24); /* residue vectors to group and
  114648. code with a partitioned book */
  114649. oggpack_write(opb,info->partitions-1,6); /* possible partition choices */
  114650. oggpack_write(opb,info->groupbook,8); /* group huffman book */
  114651. /* secondstages is a bitmask; as encoding progresses pass by pass, a
  114652. bitmask of one indicates this partition class has bits to write
  114653. this pass */
  114654. for(j=0;j<info->partitions;j++){
  114655. if(ilog(info->secondstages[j])>3){
  114656. /* yes, this is a minor hack due to not thinking ahead */
  114657. oggpack_write(opb,info->secondstages[j],3);
  114658. oggpack_write(opb,1,1);
  114659. oggpack_write(opb,info->secondstages[j]>>3,5);
  114660. }else
  114661. oggpack_write(opb,info->secondstages[j],4); /* trailing zero */
  114662. acc+=icount(info->secondstages[j]);
  114663. }
  114664. for(j=0;j<acc;j++)
  114665. oggpack_write(opb,info->booklist[j],8);
  114666. }
  114667. /* vorbis_info is for range checking */
  114668. vorbis_info_residue *res0_unpack(vorbis_info *vi,oggpack_buffer *opb){
  114669. int j,acc=0;
  114670. vorbis_info_residue0 *info=(vorbis_info_residue0*) _ogg_calloc(1,sizeof(*info));
  114671. codec_setup_info *ci=(codec_setup_info*) vi->codec_setup;
  114672. info->begin=oggpack_read(opb,24);
  114673. info->end=oggpack_read(opb,24);
  114674. info->grouping=oggpack_read(opb,24)+1;
  114675. info->partitions=oggpack_read(opb,6)+1;
  114676. info->groupbook=oggpack_read(opb,8);
  114677. for(j=0;j<info->partitions;j++){
  114678. int cascade=oggpack_read(opb,3);
  114679. if(oggpack_read(opb,1))
  114680. cascade|=(oggpack_read(opb,5)<<3);
  114681. info->secondstages[j]=cascade;
  114682. acc+=icount(cascade);
  114683. }
  114684. for(j=0;j<acc;j++)
  114685. info->booklist[j]=oggpack_read(opb,8);
  114686. if(info->groupbook>=ci->books)goto errout;
  114687. for(j=0;j<acc;j++)
  114688. if(info->booklist[j]>=ci->books)goto errout;
  114689. return(info);
  114690. errout:
  114691. res0_free_info(info);
  114692. return(NULL);
  114693. }
  114694. vorbis_look_residue *res0_look(vorbis_dsp_state *vd,
  114695. vorbis_info_residue *vr){
  114696. vorbis_info_residue0 *info=(vorbis_info_residue0 *)vr;
  114697. vorbis_look_residue0 *look=(vorbis_look_residue0 *)_ogg_calloc(1,sizeof(*look));
  114698. codec_setup_info *ci=(codec_setup_info*)vd->vi->codec_setup;
  114699. int j,k,acc=0;
  114700. int dim;
  114701. int maxstage=0;
  114702. look->info=info;
  114703. look->parts=info->partitions;
  114704. look->fullbooks=ci->fullbooks;
  114705. look->phrasebook=ci->fullbooks+info->groupbook;
  114706. dim=look->phrasebook->dim;
  114707. look->partbooks=(codebook***)_ogg_calloc(look->parts,sizeof(*look->partbooks));
  114708. for(j=0;j<look->parts;j++){
  114709. int stages=ilog(info->secondstages[j]);
  114710. if(stages){
  114711. if(stages>maxstage)maxstage=stages;
  114712. look->partbooks[j]=(codebook**) _ogg_calloc(stages,sizeof(*look->partbooks[j]));
  114713. for(k=0;k<stages;k++)
  114714. if(info->secondstages[j]&(1<<k)){
  114715. look->partbooks[j][k]=ci->fullbooks+info->booklist[acc++];
  114716. #ifdef TRAIN_RES
  114717. look->training_data[k][j]=_ogg_calloc(look->partbooks[j][k]->entries,
  114718. sizeof(***look->training_data));
  114719. #endif
  114720. }
  114721. }
  114722. }
  114723. look->partvals=rint(pow((float)look->parts,(float)dim));
  114724. look->stages=maxstage;
  114725. look->decodemap=(int**)_ogg_malloc(look->partvals*sizeof(*look->decodemap));
  114726. for(j=0;j<look->partvals;j++){
  114727. long val=j;
  114728. long mult=look->partvals/look->parts;
  114729. look->decodemap[j]=(int*)_ogg_malloc(dim*sizeof(*look->decodemap[j]));
  114730. for(k=0;k<dim;k++){
  114731. long deco=val/mult;
  114732. val-=deco*mult;
  114733. mult/=look->parts;
  114734. look->decodemap[j][k]=deco;
  114735. }
  114736. }
  114737. #if defined(TRAIN_RES) || defined (TRAIN_RESAUX)
  114738. {
  114739. static int train_seq=0;
  114740. look->train_seq=train_seq++;
  114741. }
  114742. #endif
  114743. return(look);
  114744. }
  114745. /* break an abstraction and copy some code for performance purposes */
  114746. static int local_book_besterror(codebook *book,float *a){
  114747. int dim=book->dim,i,k,o;
  114748. int best=0;
  114749. encode_aux_threshmatch *tt=book->c->thresh_tree;
  114750. /* find the quant val of each scalar */
  114751. for(k=0,o=dim;k<dim;++k){
  114752. float val=a[--o];
  114753. i=tt->threshvals>>1;
  114754. if(val<tt->quantthresh[i]){
  114755. if(val<tt->quantthresh[i-1]){
  114756. for(--i;i>0;--i)
  114757. if(val>=tt->quantthresh[i-1])
  114758. break;
  114759. }
  114760. }else{
  114761. for(++i;i<tt->threshvals-1;++i)
  114762. if(val<tt->quantthresh[i])break;
  114763. }
  114764. best=(best*tt->quantvals)+tt->quantmap[i];
  114765. }
  114766. /* regular lattices are easy :-) */
  114767. if(book->c->lengthlist[best]<=0){
  114768. const static_codebook *c=book->c;
  114769. int i,j;
  114770. float bestf=0.f;
  114771. float *e=book->valuelist;
  114772. best=-1;
  114773. for(i=0;i<book->entries;i++){
  114774. if(c->lengthlist[i]>0){
  114775. float thisx=0.f;
  114776. for(j=0;j<dim;j++){
  114777. float val=(e[j]-a[j]);
  114778. thisx+=val*val;
  114779. }
  114780. if(best==-1 || thisx<bestf){
  114781. bestf=thisx;
  114782. best=i;
  114783. }
  114784. }
  114785. e+=dim;
  114786. }
  114787. }
  114788. {
  114789. float *ptr=book->valuelist+best*dim;
  114790. for(i=0;i<dim;i++)
  114791. *a++ -= *ptr++;
  114792. }
  114793. return(best);
  114794. }
  114795. static int _encodepart(oggpack_buffer *opb,float *vec, int n,
  114796. codebook *book,long *acc){
  114797. int i,bits=0;
  114798. int dim=book->dim;
  114799. int step=n/dim;
  114800. for(i=0;i<step;i++){
  114801. int entry=local_book_besterror(book,vec+i*dim);
  114802. #ifdef TRAIN_RES
  114803. acc[entry]++;
  114804. #endif
  114805. bits+=vorbis_book_encode(book,entry,opb);
  114806. }
  114807. return(bits);
  114808. }
  114809. static long **_01class(vorbis_block *vb,vorbis_look_residue *vl,
  114810. float **in,int ch){
  114811. long i,j,k;
  114812. vorbis_look_residue0 *look=(vorbis_look_residue0 *)vl;
  114813. vorbis_info_residue0 *info=look->info;
  114814. /* move all this setup out later */
  114815. int samples_per_partition=info->grouping;
  114816. int possible_partitions=info->partitions;
  114817. int n=info->end-info->begin;
  114818. int partvals=n/samples_per_partition;
  114819. long **partword=(long**)_vorbis_block_alloc(vb,ch*sizeof(*partword));
  114820. float scale=100./samples_per_partition;
  114821. /* we find the partition type for each partition of each
  114822. channel. We'll go back and do the interleaved encoding in a
  114823. bit. For now, clarity */
  114824. for(i=0;i<ch;i++){
  114825. partword[i]=(long*)_vorbis_block_alloc(vb,n/samples_per_partition*sizeof(*partword[i]));
  114826. memset(partword[i],0,n/samples_per_partition*sizeof(*partword[i]));
  114827. }
  114828. for(i=0;i<partvals;i++){
  114829. int offset=i*samples_per_partition+info->begin;
  114830. for(j=0;j<ch;j++){
  114831. float max=0.;
  114832. float ent=0.;
  114833. for(k=0;k<samples_per_partition;k++){
  114834. if(fabs(in[j][offset+k])>max)max=fabs(in[j][offset+k]);
  114835. ent+=fabs(rint(in[j][offset+k]));
  114836. }
  114837. ent*=scale;
  114838. for(k=0;k<possible_partitions-1;k++)
  114839. if(max<=info->classmetric1[k] &&
  114840. (info->classmetric2[k]<0 || (int)ent<info->classmetric2[k]))
  114841. break;
  114842. partword[j][i]=k;
  114843. }
  114844. }
  114845. #ifdef TRAIN_RESAUX
  114846. {
  114847. FILE *of;
  114848. char buffer[80];
  114849. for(i=0;i<ch;i++){
  114850. sprintf(buffer,"resaux_%d.vqd",look->train_seq);
  114851. of=fopen(buffer,"a");
  114852. for(j=0;j<partvals;j++)
  114853. fprintf(of,"%ld, ",partword[i][j]);
  114854. fprintf(of,"\n");
  114855. fclose(of);
  114856. }
  114857. }
  114858. #endif
  114859. look->frames++;
  114860. return(partword);
  114861. }
  114862. /* designed for stereo or other modes where the partition size is an
  114863. integer multiple of the number of channels encoded in the current
  114864. submap */
  114865. static long **_2class(vorbis_block *vb,vorbis_look_residue *vl,float **in,
  114866. int ch){
  114867. long i,j,k,l;
  114868. vorbis_look_residue0 *look=(vorbis_look_residue0 *)vl;
  114869. vorbis_info_residue0 *info=look->info;
  114870. /* move all this setup out later */
  114871. int samples_per_partition=info->grouping;
  114872. int possible_partitions=info->partitions;
  114873. int n=info->end-info->begin;
  114874. int partvals=n/samples_per_partition;
  114875. long **partword=(long**)_vorbis_block_alloc(vb,sizeof(*partword));
  114876. #if defined(TRAIN_RES) || defined (TRAIN_RESAUX)
  114877. FILE *of;
  114878. char buffer[80];
  114879. #endif
  114880. partword[0]=(long*)_vorbis_block_alloc(vb,n*ch/samples_per_partition*sizeof(*partword[0]));
  114881. memset(partword[0],0,n*ch/samples_per_partition*sizeof(*partword[0]));
  114882. for(i=0,l=info->begin/ch;i<partvals;i++){
  114883. float magmax=0.f;
  114884. float angmax=0.f;
  114885. for(j=0;j<samples_per_partition;j+=ch){
  114886. if(fabs(in[0][l])>magmax)magmax=fabs(in[0][l]);
  114887. for(k=1;k<ch;k++)
  114888. if(fabs(in[k][l])>angmax)angmax=fabs(in[k][l]);
  114889. l++;
  114890. }
  114891. for(j=0;j<possible_partitions-1;j++)
  114892. if(magmax<=info->classmetric1[j] &&
  114893. angmax<=info->classmetric2[j])
  114894. break;
  114895. partword[0][i]=j;
  114896. }
  114897. #ifdef TRAIN_RESAUX
  114898. sprintf(buffer,"resaux_%d.vqd",look->train_seq);
  114899. of=fopen(buffer,"a");
  114900. for(i=0;i<partvals;i++)
  114901. fprintf(of,"%ld, ",partword[0][i]);
  114902. fprintf(of,"\n");
  114903. fclose(of);
  114904. #endif
  114905. look->frames++;
  114906. return(partword);
  114907. }
  114908. static int _01forward(oggpack_buffer *opb,
  114909. vorbis_block *vb,vorbis_look_residue *vl,
  114910. float **in,int ch,
  114911. long **partword,
  114912. int (*encode)(oggpack_buffer *,float *,int,
  114913. codebook *,long *)){
  114914. long i,j,k,s;
  114915. vorbis_look_residue0 *look=(vorbis_look_residue0 *)vl;
  114916. vorbis_info_residue0 *info=look->info;
  114917. /* move all this setup out later */
  114918. int samples_per_partition=info->grouping;
  114919. int possible_partitions=info->partitions;
  114920. int partitions_per_word=look->phrasebook->dim;
  114921. int n=info->end-info->begin;
  114922. int partvals=n/samples_per_partition;
  114923. long resbits[128];
  114924. long resvals[128];
  114925. #ifdef TRAIN_RES
  114926. for(i=0;i<ch;i++)
  114927. for(j=info->begin;j<info->end;j++){
  114928. if(in[i][j]>look->tmax)look->tmax=in[i][j];
  114929. if(in[i][j]<look->tmin)look->tmin=in[i][j];
  114930. }
  114931. #endif
  114932. memset(resbits,0,sizeof(resbits));
  114933. memset(resvals,0,sizeof(resvals));
  114934. /* we code the partition words for each channel, then the residual
  114935. words for a partition per channel until we've written all the
  114936. residual words for that partition word. Then write the next
  114937. partition channel words... */
  114938. for(s=0;s<look->stages;s++){
  114939. for(i=0;i<partvals;){
  114940. /* first we encode a partition codeword for each channel */
  114941. if(s==0){
  114942. for(j=0;j<ch;j++){
  114943. long val=partword[j][i];
  114944. for(k=1;k<partitions_per_word;k++){
  114945. val*=possible_partitions;
  114946. if(i+k<partvals)
  114947. val+=partword[j][i+k];
  114948. }
  114949. /* training hack */
  114950. if(val<look->phrasebook->entries)
  114951. look->phrasebits+=vorbis_book_encode(look->phrasebook,val,opb);
  114952. #if 0 /*def TRAIN_RES*/
  114953. else
  114954. fprintf(stderr,"!");
  114955. #endif
  114956. }
  114957. }
  114958. /* now we encode interleaved residual values for the partitions */
  114959. for(k=0;k<partitions_per_word && i<partvals;k++,i++){
  114960. long offset=i*samples_per_partition+info->begin;
  114961. for(j=0;j<ch;j++){
  114962. if(s==0)resvals[partword[j][i]]+=samples_per_partition;
  114963. if(info->secondstages[partword[j][i]]&(1<<s)){
  114964. codebook *statebook=look->partbooks[partword[j][i]][s];
  114965. if(statebook){
  114966. int ret;
  114967. long *accumulator=NULL;
  114968. #ifdef TRAIN_RES
  114969. accumulator=look->training_data[s][partword[j][i]];
  114970. {
  114971. int l;
  114972. float *samples=in[j]+offset;
  114973. for(l=0;l<samples_per_partition;l++){
  114974. if(samples[l]<look->training_min[s][partword[j][i]])
  114975. look->training_min[s][partword[j][i]]=samples[l];
  114976. if(samples[l]>look->training_max[s][partword[j][i]])
  114977. look->training_max[s][partword[j][i]]=samples[l];
  114978. }
  114979. }
  114980. #endif
  114981. ret=encode(opb,in[j]+offset,samples_per_partition,
  114982. statebook,accumulator);
  114983. look->postbits+=ret;
  114984. resbits[partword[j][i]]+=ret;
  114985. }
  114986. }
  114987. }
  114988. }
  114989. }
  114990. }
  114991. /*{
  114992. long total=0;
  114993. long totalbits=0;
  114994. fprintf(stderr,"%d :: ",vb->mode);
  114995. for(k=0;k<possible_partitions;k++){
  114996. fprintf(stderr,"%ld/%1.2g, ",resvals[k],(float)resbits[k]/resvals[k]);
  114997. total+=resvals[k];
  114998. totalbits+=resbits[k];
  114999. }
  115000. fprintf(stderr,":: %ld:%1.2g\n",total,(double)totalbits/total);
  115001. }*/
  115002. return(0);
  115003. }
  115004. /* a truncated packet here just means 'stop working'; it's not an error */
  115005. static int _01inverse(vorbis_block *vb,vorbis_look_residue *vl,
  115006. float **in,int ch,
  115007. long (*decodepart)(codebook *, float *,
  115008. oggpack_buffer *,int)){
  115009. long i,j,k,l,s;
  115010. vorbis_look_residue0 *look=(vorbis_look_residue0 *)vl;
  115011. vorbis_info_residue0 *info=look->info;
  115012. /* move all this setup out later */
  115013. int samples_per_partition=info->grouping;
  115014. int partitions_per_word=look->phrasebook->dim;
  115015. int n=info->end-info->begin;
  115016. int partvals=n/samples_per_partition;
  115017. int partwords=(partvals+partitions_per_word-1)/partitions_per_word;
  115018. int ***partword=(int***)alloca(ch*sizeof(*partword));
  115019. for(j=0;j<ch;j++)
  115020. partword[j]=(int**)_vorbis_block_alloc(vb,partwords*sizeof(*partword[j]));
  115021. for(s=0;s<look->stages;s++){
  115022. /* each loop decodes on partition codeword containing
  115023. partitions_pre_word partitions */
  115024. for(i=0,l=0;i<partvals;l++){
  115025. if(s==0){
  115026. /* fetch the partition word for each channel */
  115027. for(j=0;j<ch;j++){
  115028. int temp=vorbis_book_decode(look->phrasebook,&vb->opb);
  115029. if(temp==-1)goto eopbreak;
  115030. partword[j][l]=look->decodemap[temp];
  115031. if(partword[j][l]==NULL)goto errout;
  115032. }
  115033. }
  115034. /* now we decode residual values for the partitions */
  115035. for(k=0;k<partitions_per_word && i<partvals;k++,i++)
  115036. for(j=0;j<ch;j++){
  115037. long offset=info->begin+i*samples_per_partition;
  115038. if(info->secondstages[partword[j][l][k]]&(1<<s)){
  115039. codebook *stagebook=look->partbooks[partword[j][l][k]][s];
  115040. if(stagebook){
  115041. if(decodepart(stagebook,in[j]+offset,&vb->opb,
  115042. samples_per_partition)==-1)goto eopbreak;
  115043. }
  115044. }
  115045. }
  115046. }
  115047. }
  115048. errout:
  115049. eopbreak:
  115050. return(0);
  115051. }
  115052. #if 0
  115053. /* residue 0 and 1 are just slight variants of one another. 0 is
  115054. interleaved, 1 is not */
  115055. long **res0_class(vorbis_block *vb,vorbis_look_residue *vl,
  115056. float **in,int *nonzero,int ch){
  115057. /* we encode only the nonzero parts of a bundle */
  115058. int i,used=0;
  115059. for(i=0;i<ch;i++)
  115060. if(nonzero[i])
  115061. in[used++]=in[i];
  115062. if(used)
  115063. /*return(_01class(vb,vl,in,used,_interleaved_testhack));*/
  115064. return(_01class(vb,vl,in,used));
  115065. else
  115066. return(0);
  115067. }
  115068. int res0_forward(vorbis_block *vb,vorbis_look_residue *vl,
  115069. float **in,float **out,int *nonzero,int ch,
  115070. long **partword){
  115071. /* we encode only the nonzero parts of a bundle */
  115072. int i,j,used=0,n=vb->pcmend/2;
  115073. for(i=0;i<ch;i++)
  115074. if(nonzero[i]){
  115075. if(out)
  115076. for(j=0;j<n;j++)
  115077. out[i][j]+=in[i][j];
  115078. in[used++]=in[i];
  115079. }
  115080. if(used){
  115081. int ret=_01forward(vb,vl,in,used,partword,
  115082. _interleaved_encodepart);
  115083. if(out){
  115084. used=0;
  115085. for(i=0;i<ch;i++)
  115086. if(nonzero[i]){
  115087. for(j=0;j<n;j++)
  115088. out[i][j]-=in[used][j];
  115089. used++;
  115090. }
  115091. }
  115092. return(ret);
  115093. }else{
  115094. return(0);
  115095. }
  115096. }
  115097. #endif
  115098. int res0_inverse(vorbis_block *vb,vorbis_look_residue *vl,
  115099. float **in,int *nonzero,int ch){
  115100. int i,used=0;
  115101. for(i=0;i<ch;i++)
  115102. if(nonzero[i])
  115103. in[used++]=in[i];
  115104. if(used)
  115105. return(_01inverse(vb,vl,in,used,vorbis_book_decodevs_add));
  115106. else
  115107. return(0);
  115108. }
  115109. int res1_forward(oggpack_buffer *opb,vorbis_block *vb,vorbis_look_residue *vl,
  115110. float **in,float **out,int *nonzero,int ch,
  115111. long **partword){
  115112. int i,j,used=0,n=vb->pcmend/2;
  115113. for(i=0;i<ch;i++)
  115114. if(nonzero[i]){
  115115. if(out)
  115116. for(j=0;j<n;j++)
  115117. out[i][j]+=in[i][j];
  115118. in[used++]=in[i];
  115119. }
  115120. if(used){
  115121. int ret=_01forward(opb,vb,vl,in,used,partword,_encodepart);
  115122. if(out){
  115123. used=0;
  115124. for(i=0;i<ch;i++)
  115125. if(nonzero[i]){
  115126. for(j=0;j<n;j++)
  115127. out[i][j]-=in[used][j];
  115128. used++;
  115129. }
  115130. }
  115131. return(ret);
  115132. }else{
  115133. return(0);
  115134. }
  115135. }
  115136. long **res1_class(vorbis_block *vb,vorbis_look_residue *vl,
  115137. float **in,int *nonzero,int ch){
  115138. int i,used=0;
  115139. for(i=0;i<ch;i++)
  115140. if(nonzero[i])
  115141. in[used++]=in[i];
  115142. if(used)
  115143. return(_01class(vb,vl,in,used));
  115144. else
  115145. return(0);
  115146. }
  115147. int res1_inverse(vorbis_block *vb,vorbis_look_residue *vl,
  115148. float **in,int *nonzero,int ch){
  115149. int i,used=0;
  115150. for(i=0;i<ch;i++)
  115151. if(nonzero[i])
  115152. in[used++]=in[i];
  115153. if(used)
  115154. return(_01inverse(vb,vl,in,used,vorbis_book_decodev_add));
  115155. else
  115156. return(0);
  115157. }
  115158. long **res2_class(vorbis_block *vb,vorbis_look_residue *vl,
  115159. float **in,int *nonzero,int ch){
  115160. int i,used=0;
  115161. for(i=0;i<ch;i++)
  115162. if(nonzero[i])used++;
  115163. if(used)
  115164. return(_2class(vb,vl,in,ch));
  115165. else
  115166. return(0);
  115167. }
  115168. /* res2 is slightly more different; all the channels are interleaved
  115169. into a single vector and encoded. */
  115170. int res2_forward(oggpack_buffer *opb,
  115171. vorbis_block *vb,vorbis_look_residue *vl,
  115172. float **in,float **out,int *nonzero,int ch,
  115173. long **partword){
  115174. long i,j,k,n=vb->pcmend/2,used=0;
  115175. /* don't duplicate the code; use a working vector hack for now and
  115176. reshape ourselves into a single channel res1 */
  115177. /* ugly; reallocs for each coupling pass :-( */
  115178. float *work=(float*)_vorbis_block_alloc(vb,ch*n*sizeof(*work));
  115179. for(i=0;i<ch;i++){
  115180. float *pcm=in[i];
  115181. if(nonzero[i])used++;
  115182. for(j=0,k=i;j<n;j++,k+=ch)
  115183. work[k]=pcm[j];
  115184. }
  115185. if(used){
  115186. int ret=_01forward(opb,vb,vl,&work,1,partword,_encodepart);
  115187. /* update the sofar vector */
  115188. if(out){
  115189. for(i=0;i<ch;i++){
  115190. float *pcm=in[i];
  115191. float *sofar=out[i];
  115192. for(j=0,k=i;j<n;j++,k+=ch)
  115193. sofar[j]+=pcm[j]-work[k];
  115194. }
  115195. }
  115196. return(ret);
  115197. }else{
  115198. return(0);
  115199. }
  115200. }
  115201. /* duplicate code here as speed is somewhat more important */
  115202. int res2_inverse(vorbis_block *vb,vorbis_look_residue *vl,
  115203. float **in,int *nonzero,int ch){
  115204. long i,k,l,s;
  115205. vorbis_look_residue0 *look=(vorbis_look_residue0 *)vl;
  115206. vorbis_info_residue0 *info=look->info;
  115207. /* move all this setup out later */
  115208. int samples_per_partition=info->grouping;
  115209. int partitions_per_word=look->phrasebook->dim;
  115210. int n=info->end-info->begin;
  115211. int partvals=n/samples_per_partition;
  115212. int partwords=(partvals+partitions_per_word-1)/partitions_per_word;
  115213. int **partword=(int**)_vorbis_block_alloc(vb,partwords*sizeof(*partword));
  115214. for(i=0;i<ch;i++)if(nonzero[i])break;
  115215. if(i==ch)return(0); /* no nonzero vectors */
  115216. for(s=0;s<look->stages;s++){
  115217. for(i=0,l=0;i<partvals;l++){
  115218. if(s==0){
  115219. /* fetch the partition word */
  115220. int temp=vorbis_book_decode(look->phrasebook,&vb->opb);
  115221. if(temp==-1)goto eopbreak;
  115222. partword[l]=look->decodemap[temp];
  115223. if(partword[l]==NULL)goto errout;
  115224. }
  115225. /* now we decode residual values for the partitions */
  115226. for(k=0;k<partitions_per_word && i<partvals;k++,i++)
  115227. if(info->secondstages[partword[l][k]]&(1<<s)){
  115228. codebook *stagebook=look->partbooks[partword[l][k]][s];
  115229. if(stagebook){
  115230. if(vorbis_book_decodevv_add(stagebook,in,
  115231. i*samples_per_partition+info->begin,ch,
  115232. &vb->opb,samples_per_partition)==-1)
  115233. goto eopbreak;
  115234. }
  115235. }
  115236. }
  115237. }
  115238. errout:
  115239. eopbreak:
  115240. return(0);
  115241. }
  115242. vorbis_func_residue residue0_exportbundle={
  115243. NULL,
  115244. &res0_unpack,
  115245. &res0_look,
  115246. &res0_free_info,
  115247. &res0_free_look,
  115248. NULL,
  115249. NULL,
  115250. &res0_inverse
  115251. };
  115252. vorbis_func_residue residue1_exportbundle={
  115253. &res0_pack,
  115254. &res0_unpack,
  115255. &res0_look,
  115256. &res0_free_info,
  115257. &res0_free_look,
  115258. &res1_class,
  115259. &res1_forward,
  115260. &res1_inverse
  115261. };
  115262. vorbis_func_residue residue2_exportbundle={
  115263. &res0_pack,
  115264. &res0_unpack,
  115265. &res0_look,
  115266. &res0_free_info,
  115267. &res0_free_look,
  115268. &res2_class,
  115269. &res2_forward,
  115270. &res2_inverse
  115271. };
  115272. #endif
  115273. /*** End of inlined file: res0.c ***/
  115274. /*** Start of inlined file: sharedbook.c ***/
  115275. /*** Start of inlined file: juce_OggVorbisHeader.h ***/
  115276. // This file is included at the start of each Ogg-Vorbis .c file, just to do a few housekeeping
  115277. // tasks..
  115278. #if JUCE_MSVC
  115279. #pragma warning (disable: 4267 4127 4244 4996 4100 4701 4702 4013 4133 4206 4305 4189 4706)
  115280. #endif
  115281. /*** End of inlined file: juce_OggVorbisHeader.h ***/
  115282. #if JUCE_USE_OGGVORBIS
  115283. #include <stdlib.h>
  115284. #include <math.h>
  115285. #include <string.h>
  115286. /**** pack/unpack helpers ******************************************/
  115287. int _ilog(unsigned int v){
  115288. int ret=0;
  115289. while(v){
  115290. ret++;
  115291. v>>=1;
  115292. }
  115293. return(ret);
  115294. }
  115295. /* 32 bit float (not IEEE; nonnormalized mantissa +
  115296. biased exponent) : neeeeeee eeemmmmm mmmmmmmm mmmmmmmm
  115297. Why not IEEE? It's just not that important here. */
  115298. #define VQ_FEXP 10
  115299. #define VQ_FMAN 21
  115300. #define VQ_FEXP_BIAS 768 /* bias toward values smaller than 1. */
  115301. /* doesn't currently guard under/overflow */
  115302. long _float32_pack(float val){
  115303. int sign=0;
  115304. long exp;
  115305. long mant;
  115306. if(val<0){
  115307. sign=0x80000000;
  115308. val= -val;
  115309. }
  115310. exp= floor(log(val)/log(2.f));
  115311. mant=rint(ldexp(val,(VQ_FMAN-1)-exp));
  115312. exp=(exp+VQ_FEXP_BIAS)<<VQ_FMAN;
  115313. return(sign|exp|mant);
  115314. }
  115315. float _float32_unpack(long val){
  115316. double mant=val&0x1fffff;
  115317. int sign=val&0x80000000;
  115318. long exp =(val&0x7fe00000L)>>VQ_FMAN;
  115319. if(sign)mant= -mant;
  115320. return(ldexp(mant,exp-(VQ_FMAN-1)-VQ_FEXP_BIAS));
  115321. }
  115322. /* given a list of word lengths, generate a list of codewords. Works
  115323. for length ordered or unordered, always assigns the lowest valued
  115324. codewords first. Extended to handle unused entries (length 0) */
  115325. ogg_uint32_t *_make_words(long *l,long n,long sparsecount){
  115326. long i,j,count=0;
  115327. ogg_uint32_t marker[33];
  115328. ogg_uint32_t *r=(ogg_uint32_t*)_ogg_malloc((sparsecount?sparsecount:n)*sizeof(*r));
  115329. memset(marker,0,sizeof(marker));
  115330. for(i=0;i<n;i++){
  115331. long length=l[i];
  115332. if(length>0){
  115333. ogg_uint32_t entry=marker[length];
  115334. /* when we claim a node for an entry, we also claim the nodes
  115335. below it (pruning off the imagined tree that may have dangled
  115336. from it) as well as blocking the use of any nodes directly
  115337. above for leaves */
  115338. /* update ourself */
  115339. if(length<32 && (entry>>length)){
  115340. /* error condition; the lengths must specify an overpopulated tree */
  115341. _ogg_free(r);
  115342. return(NULL);
  115343. }
  115344. r[count++]=entry;
  115345. /* Look to see if the next shorter marker points to the node
  115346. above. if so, update it and repeat. */
  115347. {
  115348. for(j=length;j>0;j--){
  115349. if(marker[j]&1){
  115350. /* have to jump branches */
  115351. if(j==1)
  115352. marker[1]++;
  115353. else
  115354. marker[j]=marker[j-1]<<1;
  115355. break; /* invariant says next upper marker would already
  115356. have been moved if it was on the same path */
  115357. }
  115358. marker[j]++;
  115359. }
  115360. }
  115361. /* prune the tree; the implicit invariant says all the longer
  115362. markers were dangling from our just-taken node. Dangle them
  115363. from our *new* node. */
  115364. for(j=length+1;j<33;j++)
  115365. if((marker[j]>>1) == entry){
  115366. entry=marker[j];
  115367. marker[j]=marker[j-1]<<1;
  115368. }else
  115369. break;
  115370. }else
  115371. if(sparsecount==0)count++;
  115372. }
  115373. /* bitreverse the words because our bitwise packer/unpacker is LSb
  115374. endian */
  115375. for(i=0,count=0;i<n;i++){
  115376. ogg_uint32_t temp=0;
  115377. for(j=0;j<l[i];j++){
  115378. temp<<=1;
  115379. temp|=(r[count]>>j)&1;
  115380. }
  115381. if(sparsecount){
  115382. if(l[i])
  115383. r[count++]=temp;
  115384. }else
  115385. r[count++]=temp;
  115386. }
  115387. return(r);
  115388. }
  115389. /* there might be a straightforward one-line way to do the below
  115390. that's portable and totally safe against roundoff, but I haven't
  115391. thought of it. Therefore, we opt on the side of caution */
  115392. long _book_maptype1_quantvals(const static_codebook *b){
  115393. long vals=floor(pow((float)b->entries,1.f/b->dim));
  115394. /* the above *should* be reliable, but we'll not assume that FP is
  115395. ever reliable when bitstream sync is at stake; verify via integer
  115396. means that vals really is the greatest value of dim for which
  115397. vals^b->bim <= b->entries */
  115398. /* treat the above as an initial guess */
  115399. while(1){
  115400. long acc=1;
  115401. long acc1=1;
  115402. int i;
  115403. for(i=0;i<b->dim;i++){
  115404. acc*=vals;
  115405. acc1*=vals+1;
  115406. }
  115407. if(acc<=b->entries && acc1>b->entries){
  115408. return(vals);
  115409. }else{
  115410. if(acc>b->entries){
  115411. vals--;
  115412. }else{
  115413. vals++;
  115414. }
  115415. }
  115416. }
  115417. }
  115418. /* unpack the quantized list of values for encode/decode ***********/
  115419. /* we need to deal with two map types: in map type 1, the values are
  115420. generated algorithmically (each column of the vector counts through
  115421. the values in the quant vector). in map type 2, all the values came
  115422. in in an explicit list. Both value lists must be unpacked */
  115423. float *_book_unquantize(const static_codebook *b,int n,int *sparsemap){
  115424. long j,k,count=0;
  115425. if(b->maptype==1 || b->maptype==2){
  115426. int quantvals;
  115427. float mindel=_float32_unpack(b->q_min);
  115428. float delta=_float32_unpack(b->q_delta);
  115429. float *r=(float*)_ogg_calloc(n*b->dim,sizeof(*r));
  115430. /* maptype 1 and 2 both use a quantized value vector, but
  115431. different sizes */
  115432. switch(b->maptype){
  115433. case 1:
  115434. /* most of the time, entries%dimensions == 0, but we need to be
  115435. well defined. We define that the possible vales at each
  115436. scalar is values == entries/dim. If entries%dim != 0, we'll
  115437. have 'too few' values (values*dim<entries), which means that
  115438. we'll have 'left over' entries; left over entries use zeroed
  115439. values (and are wasted). So don't generate codebooks like
  115440. that */
  115441. quantvals=_book_maptype1_quantvals(b);
  115442. for(j=0;j<b->entries;j++){
  115443. if((sparsemap && b->lengthlist[j]) || !sparsemap){
  115444. float last=0.f;
  115445. int indexdiv=1;
  115446. for(k=0;k<b->dim;k++){
  115447. int index= (j/indexdiv)%quantvals;
  115448. float val=b->quantlist[index];
  115449. val=fabs(val)*delta+mindel+last;
  115450. if(b->q_sequencep)last=val;
  115451. if(sparsemap)
  115452. r[sparsemap[count]*b->dim+k]=val;
  115453. else
  115454. r[count*b->dim+k]=val;
  115455. indexdiv*=quantvals;
  115456. }
  115457. count++;
  115458. }
  115459. }
  115460. break;
  115461. case 2:
  115462. for(j=0;j<b->entries;j++){
  115463. if((sparsemap && b->lengthlist[j]) || !sparsemap){
  115464. float last=0.f;
  115465. for(k=0;k<b->dim;k++){
  115466. float val=b->quantlist[j*b->dim+k];
  115467. val=fabs(val)*delta+mindel+last;
  115468. if(b->q_sequencep)last=val;
  115469. if(sparsemap)
  115470. r[sparsemap[count]*b->dim+k]=val;
  115471. else
  115472. r[count*b->dim+k]=val;
  115473. }
  115474. count++;
  115475. }
  115476. }
  115477. break;
  115478. }
  115479. return(r);
  115480. }
  115481. return(NULL);
  115482. }
  115483. void vorbis_staticbook_clear(static_codebook *b){
  115484. if(b->allocedp){
  115485. if(b->quantlist)_ogg_free(b->quantlist);
  115486. if(b->lengthlist)_ogg_free(b->lengthlist);
  115487. if(b->nearest_tree){
  115488. _ogg_free(b->nearest_tree->ptr0);
  115489. _ogg_free(b->nearest_tree->ptr1);
  115490. _ogg_free(b->nearest_tree->p);
  115491. _ogg_free(b->nearest_tree->q);
  115492. memset(b->nearest_tree,0,sizeof(*b->nearest_tree));
  115493. _ogg_free(b->nearest_tree);
  115494. }
  115495. if(b->thresh_tree){
  115496. _ogg_free(b->thresh_tree->quantthresh);
  115497. _ogg_free(b->thresh_tree->quantmap);
  115498. memset(b->thresh_tree,0,sizeof(*b->thresh_tree));
  115499. _ogg_free(b->thresh_tree);
  115500. }
  115501. memset(b,0,sizeof(*b));
  115502. }
  115503. }
  115504. void vorbis_staticbook_destroy(static_codebook *b){
  115505. if(b->allocedp){
  115506. vorbis_staticbook_clear(b);
  115507. _ogg_free(b);
  115508. }
  115509. }
  115510. void vorbis_book_clear(codebook *b){
  115511. /* static book is not cleared; we're likely called on the lookup and
  115512. the static codebook belongs to the info struct */
  115513. if(b->valuelist)_ogg_free(b->valuelist);
  115514. if(b->codelist)_ogg_free(b->codelist);
  115515. if(b->dec_index)_ogg_free(b->dec_index);
  115516. if(b->dec_codelengths)_ogg_free(b->dec_codelengths);
  115517. if(b->dec_firsttable)_ogg_free(b->dec_firsttable);
  115518. memset(b,0,sizeof(*b));
  115519. }
  115520. int vorbis_book_init_encode(codebook *c,const static_codebook *s){
  115521. memset(c,0,sizeof(*c));
  115522. c->c=s;
  115523. c->entries=s->entries;
  115524. c->used_entries=s->entries;
  115525. c->dim=s->dim;
  115526. c->codelist=_make_words(s->lengthlist,s->entries,0);
  115527. c->valuelist=_book_unquantize(s,s->entries,NULL);
  115528. return(0);
  115529. }
  115530. static int sort32a(const void *a,const void *b){
  115531. return ( **(ogg_uint32_t **)a>**(ogg_uint32_t **)b)-
  115532. ( **(ogg_uint32_t **)a<**(ogg_uint32_t **)b);
  115533. }
  115534. /* decode codebook arrangement is more heavily optimized than encode */
  115535. int vorbis_book_init_decode(codebook *c,const static_codebook *s){
  115536. int i,j,n=0,tabn;
  115537. int *sortindex;
  115538. memset(c,0,sizeof(*c));
  115539. /* count actually used entries */
  115540. for(i=0;i<s->entries;i++)
  115541. if(s->lengthlist[i]>0)
  115542. n++;
  115543. c->entries=s->entries;
  115544. c->used_entries=n;
  115545. c->dim=s->dim;
  115546. /* two different remappings go on here.
  115547. First, we collapse the likely sparse codebook down only to
  115548. actually represented values/words. This collapsing needs to be
  115549. indexed as map-valueless books are used to encode original entry
  115550. positions as integers.
  115551. Second, we reorder all vectors, including the entry index above,
  115552. by sorted bitreversed codeword to allow treeless decode. */
  115553. {
  115554. /* perform sort */
  115555. ogg_uint32_t *codes=_make_words(s->lengthlist,s->entries,c->used_entries);
  115556. ogg_uint32_t **codep=(ogg_uint32_t**)alloca(sizeof(*codep)*n);
  115557. if(codes==NULL)goto err_out;
  115558. for(i=0;i<n;i++){
  115559. codes[i]=ogg_bitreverse(codes[i]);
  115560. codep[i]=codes+i;
  115561. }
  115562. qsort(codep,n,sizeof(*codep),sort32a);
  115563. sortindex=(int*)alloca(n*sizeof(*sortindex));
  115564. c->codelist=(ogg_uint32_t*)_ogg_malloc(n*sizeof(*c->codelist));
  115565. /* the index is a reverse index */
  115566. for(i=0;i<n;i++){
  115567. int position=codep[i]-codes;
  115568. sortindex[position]=i;
  115569. }
  115570. for(i=0;i<n;i++)
  115571. c->codelist[sortindex[i]]=codes[i];
  115572. _ogg_free(codes);
  115573. }
  115574. c->valuelist=_book_unquantize(s,n,sortindex);
  115575. c->dec_index=(int*)_ogg_malloc(n*sizeof(*c->dec_index));
  115576. for(n=0,i=0;i<s->entries;i++)
  115577. if(s->lengthlist[i]>0)
  115578. c->dec_index[sortindex[n++]]=i;
  115579. c->dec_codelengths=(char*)_ogg_malloc(n*sizeof(*c->dec_codelengths));
  115580. for(n=0,i=0;i<s->entries;i++)
  115581. if(s->lengthlist[i]>0)
  115582. c->dec_codelengths[sortindex[n++]]=s->lengthlist[i];
  115583. c->dec_firsttablen=_ilog(c->used_entries)-4; /* this is magic */
  115584. if(c->dec_firsttablen<5)c->dec_firsttablen=5;
  115585. if(c->dec_firsttablen>8)c->dec_firsttablen=8;
  115586. tabn=1<<c->dec_firsttablen;
  115587. c->dec_firsttable=(ogg_uint32_t*)_ogg_calloc(tabn,sizeof(*c->dec_firsttable));
  115588. c->dec_maxlength=0;
  115589. for(i=0;i<n;i++){
  115590. if(c->dec_maxlength<c->dec_codelengths[i])
  115591. c->dec_maxlength=c->dec_codelengths[i];
  115592. if(c->dec_codelengths[i]<=c->dec_firsttablen){
  115593. ogg_uint32_t orig=ogg_bitreverse(c->codelist[i]);
  115594. for(j=0;j<(1<<(c->dec_firsttablen-c->dec_codelengths[i]));j++)
  115595. c->dec_firsttable[orig|(j<<c->dec_codelengths[i])]=i+1;
  115596. }
  115597. }
  115598. /* now fill in 'unused' entries in the firsttable with hi/lo search
  115599. hints for the non-direct-hits */
  115600. {
  115601. ogg_uint32_t mask=0xfffffffeUL<<(31-c->dec_firsttablen);
  115602. long lo=0,hi=0;
  115603. for(i=0;i<tabn;i++){
  115604. ogg_uint32_t word=i<<(32-c->dec_firsttablen);
  115605. if(c->dec_firsttable[ogg_bitreverse(word)]==0){
  115606. while((lo+1)<n && c->codelist[lo+1]<=word)lo++;
  115607. while( hi<n && word>=(c->codelist[hi]&mask))hi++;
  115608. /* we only actually have 15 bits per hint to play with here.
  115609. In order to overflow gracefully (nothing breaks, efficiency
  115610. just drops), encode as the difference from the extremes. */
  115611. {
  115612. unsigned long loval=lo;
  115613. unsigned long hival=n-hi;
  115614. if(loval>0x7fff)loval=0x7fff;
  115615. if(hival>0x7fff)hival=0x7fff;
  115616. c->dec_firsttable[ogg_bitreverse(word)]=
  115617. 0x80000000UL | (loval<<15) | hival;
  115618. }
  115619. }
  115620. }
  115621. }
  115622. return(0);
  115623. err_out:
  115624. vorbis_book_clear(c);
  115625. return(-1);
  115626. }
  115627. static float _dist(int el,float *ref, float *b,int step){
  115628. int i;
  115629. float acc=0.f;
  115630. for(i=0;i<el;i++){
  115631. float val=(ref[i]-b[i*step]);
  115632. acc+=val*val;
  115633. }
  115634. return(acc);
  115635. }
  115636. int _best(codebook *book, float *a, int step){
  115637. encode_aux_threshmatch *tt=book->c->thresh_tree;
  115638. #if 0
  115639. encode_aux_nearestmatch *nt=book->c->nearest_tree;
  115640. encode_aux_pigeonhole *pt=book->c->pigeon_tree;
  115641. #endif
  115642. int dim=book->dim;
  115643. int k,o;
  115644. /*int savebest=-1;
  115645. float saverr;*/
  115646. /* do we have a threshhold encode hint? */
  115647. if(tt){
  115648. int index=0,i;
  115649. /* find the quant val of each scalar */
  115650. for(k=0,o=step*(dim-1);k<dim;k++,o-=step){
  115651. i=tt->threshvals>>1;
  115652. if(a[o]<tt->quantthresh[i]){
  115653. for(;i>0;i--)
  115654. if(a[o]>=tt->quantthresh[i-1])
  115655. break;
  115656. }else{
  115657. for(i++;i<tt->threshvals-1;i++)
  115658. if(a[o]<tt->quantthresh[i])break;
  115659. }
  115660. index=(index*tt->quantvals)+tt->quantmap[i];
  115661. }
  115662. /* regular lattices are easy :-) */
  115663. if(book->c->lengthlist[index]>0) /* is this unused? If so, we'll
  115664. use a decision tree after all
  115665. and fall through*/
  115666. return(index);
  115667. }
  115668. #if 0
  115669. /* do we have a pigeonhole encode hint? */
  115670. if(pt){
  115671. const static_codebook *c=book->c;
  115672. int i,besti=-1;
  115673. float best=0.f;
  115674. int entry=0;
  115675. /* dealing with sequentialness is a pain in the ass */
  115676. if(c->q_sequencep){
  115677. int pv;
  115678. long mul=1;
  115679. float qlast=0;
  115680. for(k=0,o=0;k<dim;k++,o+=step){
  115681. pv=(int)((a[o]-qlast-pt->min)/pt->del);
  115682. if(pv<0 || pv>=pt->mapentries)break;
  115683. entry+=pt->pigeonmap[pv]*mul;
  115684. mul*=pt->quantvals;
  115685. qlast+=pv*pt->del+pt->min;
  115686. }
  115687. }else{
  115688. for(k=0,o=step*(dim-1);k<dim;k++,o-=step){
  115689. int pv=(int)((a[o]-pt->min)/pt->del);
  115690. if(pv<0 || pv>=pt->mapentries)break;
  115691. entry=entry*pt->quantvals+pt->pigeonmap[pv];
  115692. }
  115693. }
  115694. /* must be within the pigeonholable range; if we quant outside (or
  115695. in an entry that we define no list for), brute force it */
  115696. if(k==dim && pt->fitlength[entry]){
  115697. /* search the abbreviated list */
  115698. long *list=pt->fitlist+pt->fitmap[entry];
  115699. for(i=0;i<pt->fitlength[entry];i++){
  115700. float this=_dist(dim,book->valuelist+list[i]*dim,a,step);
  115701. if(besti==-1 || this<best){
  115702. best=this;
  115703. besti=list[i];
  115704. }
  115705. }
  115706. return(besti);
  115707. }
  115708. }
  115709. if(nt){
  115710. /* optimized using the decision tree */
  115711. while(1){
  115712. float c=0.f;
  115713. float *p=book->valuelist+nt->p[ptr];
  115714. float *q=book->valuelist+nt->q[ptr];
  115715. for(k=0,o=0;k<dim;k++,o+=step)
  115716. c+=(p[k]-q[k])*(a[o]-(p[k]+q[k])*.5);
  115717. if(c>0.f) /* in A */
  115718. ptr= -nt->ptr0[ptr];
  115719. else /* in B */
  115720. ptr= -nt->ptr1[ptr];
  115721. if(ptr<=0)break;
  115722. }
  115723. return(-ptr);
  115724. }
  115725. #endif
  115726. /* brute force it! */
  115727. {
  115728. const static_codebook *c=book->c;
  115729. int i,besti=-1;
  115730. float best=0.f;
  115731. float *e=book->valuelist;
  115732. for(i=0;i<book->entries;i++){
  115733. if(c->lengthlist[i]>0){
  115734. float thisx=_dist(dim,e,a,step);
  115735. if(besti==-1 || thisx<best){
  115736. best=thisx;
  115737. besti=i;
  115738. }
  115739. }
  115740. e+=dim;
  115741. }
  115742. /*if(savebest!=-1 && savebest!=besti){
  115743. fprintf(stderr,"brute force/pigeonhole disagreement:\n"
  115744. "original:");
  115745. for(i=0;i<dim*step;i+=step)fprintf(stderr,"%g,",a[i]);
  115746. fprintf(stderr,"\n"
  115747. "pigeonhole (entry %d, err %g):",savebest,saverr);
  115748. for(i=0;i<dim;i++)fprintf(stderr,"%g,",
  115749. (book->valuelist+savebest*dim)[i]);
  115750. fprintf(stderr,"\n"
  115751. "bruteforce (entry %d, err %g):",besti,best);
  115752. for(i=0;i<dim;i++)fprintf(stderr,"%g,",
  115753. (book->valuelist+besti*dim)[i]);
  115754. fprintf(stderr,"\n");
  115755. }*/
  115756. return(besti);
  115757. }
  115758. }
  115759. long vorbis_book_codeword(codebook *book,int entry){
  115760. if(book->c) /* only use with encode; decode optimizations are
  115761. allowed to break this */
  115762. return book->codelist[entry];
  115763. return -1;
  115764. }
  115765. long vorbis_book_codelen(codebook *book,int entry){
  115766. if(book->c) /* only use with encode; decode optimizations are
  115767. allowed to break this */
  115768. return book->c->lengthlist[entry];
  115769. return -1;
  115770. }
  115771. #ifdef _V_SELFTEST
  115772. /* Unit tests of the dequantizer; this stuff will be OK
  115773. cross-platform, I simply want to be sure that special mapping cases
  115774. actually work properly; a bug could go unnoticed for a while */
  115775. #include <stdio.h>
  115776. /* cases:
  115777. no mapping
  115778. full, explicit mapping
  115779. algorithmic mapping
  115780. nonsequential
  115781. sequential
  115782. */
  115783. static long full_quantlist1[]={0,1,2,3, 4,5,6,7, 8,3,6,1};
  115784. static long partial_quantlist1[]={0,7,2};
  115785. /* no mapping */
  115786. static_codebook test1={
  115787. 4,16,
  115788. NULL,
  115789. 0,
  115790. 0,0,0,0,
  115791. NULL,
  115792. NULL,NULL
  115793. };
  115794. static float *test1_result=NULL;
  115795. /* linear, full mapping, nonsequential */
  115796. static_codebook test2={
  115797. 4,3,
  115798. NULL,
  115799. 2,
  115800. -533200896,1611661312,4,0,
  115801. full_quantlist1,
  115802. NULL,NULL
  115803. };
  115804. static float test2_result[]={-3,-2,-1,0, 1,2,3,4, 5,0,3,-2};
  115805. /* linear, full mapping, sequential */
  115806. static_codebook test3={
  115807. 4,3,
  115808. NULL,
  115809. 2,
  115810. -533200896,1611661312,4,1,
  115811. full_quantlist1,
  115812. NULL,NULL
  115813. };
  115814. static float test3_result[]={-3,-5,-6,-6, 1,3,6,10, 5,5,8,6};
  115815. /* linear, algorithmic mapping, nonsequential */
  115816. static_codebook test4={
  115817. 3,27,
  115818. NULL,
  115819. 1,
  115820. -533200896,1611661312,4,0,
  115821. partial_quantlist1,
  115822. NULL,NULL
  115823. };
  115824. static float test4_result[]={-3,-3,-3, 4,-3,-3, -1,-3,-3,
  115825. -3, 4,-3, 4, 4,-3, -1, 4,-3,
  115826. -3,-1,-3, 4,-1,-3, -1,-1,-3,
  115827. -3,-3, 4, 4,-3, 4, -1,-3, 4,
  115828. -3, 4, 4, 4, 4, 4, -1, 4, 4,
  115829. -3,-1, 4, 4,-1, 4, -1,-1, 4,
  115830. -3,-3,-1, 4,-3,-1, -1,-3,-1,
  115831. -3, 4,-1, 4, 4,-1, -1, 4,-1,
  115832. -3,-1,-1, 4,-1,-1, -1,-1,-1};
  115833. /* linear, algorithmic mapping, sequential */
  115834. static_codebook test5={
  115835. 3,27,
  115836. NULL,
  115837. 1,
  115838. -533200896,1611661312,4,1,
  115839. partial_quantlist1,
  115840. NULL,NULL
  115841. };
  115842. static float test5_result[]={-3,-6,-9, 4, 1,-2, -1,-4,-7,
  115843. -3, 1,-2, 4, 8, 5, -1, 3, 0,
  115844. -3,-4,-7, 4, 3, 0, -1,-2,-5,
  115845. -3,-6,-2, 4, 1, 5, -1,-4, 0,
  115846. -3, 1, 5, 4, 8,12, -1, 3, 7,
  115847. -3,-4, 0, 4, 3, 7, -1,-2, 2,
  115848. -3,-6,-7, 4, 1, 0, -1,-4,-5,
  115849. -3, 1, 0, 4, 8, 7, -1, 3, 2,
  115850. -3,-4,-5, 4, 3, 2, -1,-2,-3};
  115851. void run_test(static_codebook *b,float *comp){
  115852. float *out=_book_unquantize(b,b->entries,NULL);
  115853. int i;
  115854. if(comp){
  115855. if(!out){
  115856. fprintf(stderr,"_book_unquantize incorrectly returned NULL\n");
  115857. exit(1);
  115858. }
  115859. for(i=0;i<b->entries*b->dim;i++)
  115860. if(fabs(out[i]-comp[i])>.0001){
  115861. fprintf(stderr,"disagreement in unquantized and reference data:\n"
  115862. "position %d, %g != %g\n",i,out[i],comp[i]);
  115863. exit(1);
  115864. }
  115865. }else{
  115866. if(out){
  115867. fprintf(stderr,"_book_unquantize returned a value array: \n"
  115868. " correct result should have been NULL\n");
  115869. exit(1);
  115870. }
  115871. }
  115872. }
  115873. int main(){
  115874. /* run the nine dequant tests, and compare to the hand-rolled results */
  115875. fprintf(stderr,"Dequant test 1... ");
  115876. run_test(&test1,test1_result);
  115877. fprintf(stderr,"OK\nDequant test 2... ");
  115878. run_test(&test2,test2_result);
  115879. fprintf(stderr,"OK\nDequant test 3... ");
  115880. run_test(&test3,test3_result);
  115881. fprintf(stderr,"OK\nDequant test 4... ");
  115882. run_test(&test4,test4_result);
  115883. fprintf(stderr,"OK\nDequant test 5... ");
  115884. run_test(&test5,test5_result);
  115885. fprintf(stderr,"OK\n\n");
  115886. return(0);
  115887. }
  115888. #endif
  115889. #endif
  115890. /*** End of inlined file: sharedbook.c ***/
  115891. /*** Start of inlined file: smallft.c ***/
  115892. /* FFT implementation from OggSquish, minus cosine transforms,
  115893. * minus all but radix 2/4 case. In Vorbis we only need this
  115894. * cut-down version.
  115895. *
  115896. * To do more than just power-of-two sized vectors, see the full
  115897. * version I wrote for NetLib.
  115898. *
  115899. * Note that the packing is a little strange; rather than the FFT r/i
  115900. * packing following R_0, I_n, R_1, I_1, R_2, I_2 ... R_n-1, I_n-1,
  115901. * it follows R_0, R_1, I_1, R_2, I_2 ... R_n-1, I_n-1, I_n like the
  115902. * FORTRAN version
  115903. */
  115904. /*** Start of inlined file: juce_OggVorbisHeader.h ***/
  115905. // This file is included at the start of each Ogg-Vorbis .c file, just to do a few housekeeping
  115906. // tasks..
  115907. #if JUCE_MSVC
  115908. #pragma warning (disable: 4267 4127 4244 4996 4100 4701 4702 4013 4133 4206 4305 4189 4706)
  115909. #endif
  115910. /*** End of inlined file: juce_OggVorbisHeader.h ***/
  115911. #if JUCE_USE_OGGVORBIS
  115912. #include <stdlib.h>
  115913. #include <string.h>
  115914. #include <math.h>
  115915. static void drfti1(int n, float *wa, int *ifac){
  115916. static int ntryh[4] = { 4,2,3,5 };
  115917. static float tpi = 6.28318530717958648f;
  115918. float arg,argh,argld,fi;
  115919. int ntry=0,i,j=-1;
  115920. int k1, l1, l2, ib;
  115921. int ld, ii, ip, is, nq, nr;
  115922. int ido, ipm, nfm1;
  115923. int nl=n;
  115924. int nf=0;
  115925. L101:
  115926. j++;
  115927. if (j < 4)
  115928. ntry=ntryh[j];
  115929. else
  115930. ntry+=2;
  115931. L104:
  115932. nq=nl/ntry;
  115933. nr=nl-ntry*nq;
  115934. if (nr!=0) goto L101;
  115935. nf++;
  115936. ifac[nf+1]=ntry;
  115937. nl=nq;
  115938. if(ntry!=2)goto L107;
  115939. if(nf==1)goto L107;
  115940. for (i=1;i<nf;i++){
  115941. ib=nf-i+1;
  115942. ifac[ib+1]=ifac[ib];
  115943. }
  115944. ifac[2] = 2;
  115945. L107:
  115946. if(nl!=1)goto L104;
  115947. ifac[0]=n;
  115948. ifac[1]=nf;
  115949. argh=tpi/n;
  115950. is=0;
  115951. nfm1=nf-1;
  115952. l1=1;
  115953. if(nfm1==0)return;
  115954. for (k1=0;k1<nfm1;k1++){
  115955. ip=ifac[k1+2];
  115956. ld=0;
  115957. l2=l1*ip;
  115958. ido=n/l2;
  115959. ipm=ip-1;
  115960. for (j=0;j<ipm;j++){
  115961. ld+=l1;
  115962. i=is;
  115963. argld=(float)ld*argh;
  115964. fi=0.f;
  115965. for (ii=2;ii<ido;ii+=2){
  115966. fi+=1.f;
  115967. arg=fi*argld;
  115968. wa[i++]=cos(arg);
  115969. wa[i++]=sin(arg);
  115970. }
  115971. is+=ido;
  115972. }
  115973. l1=l2;
  115974. }
  115975. }
  115976. static void fdrffti(int n, float *wsave, int *ifac){
  115977. if (n == 1) return;
  115978. drfti1(n, wsave+n, ifac);
  115979. }
  115980. static void dradf2(int ido,int l1,float *cc,float *ch,float *wa1){
  115981. int i,k;
  115982. float ti2,tr2;
  115983. int t0,t1,t2,t3,t4,t5,t6;
  115984. t1=0;
  115985. t0=(t2=l1*ido);
  115986. t3=ido<<1;
  115987. for(k=0;k<l1;k++){
  115988. ch[t1<<1]=cc[t1]+cc[t2];
  115989. ch[(t1<<1)+t3-1]=cc[t1]-cc[t2];
  115990. t1+=ido;
  115991. t2+=ido;
  115992. }
  115993. if(ido<2)return;
  115994. if(ido==2)goto L105;
  115995. t1=0;
  115996. t2=t0;
  115997. for(k=0;k<l1;k++){
  115998. t3=t2;
  115999. t4=(t1<<1)+(ido<<1);
  116000. t5=t1;
  116001. t6=t1+t1;
  116002. for(i=2;i<ido;i+=2){
  116003. t3+=2;
  116004. t4-=2;
  116005. t5+=2;
  116006. t6+=2;
  116007. tr2=wa1[i-2]*cc[t3-1]+wa1[i-1]*cc[t3];
  116008. ti2=wa1[i-2]*cc[t3]-wa1[i-1]*cc[t3-1];
  116009. ch[t6]=cc[t5]+ti2;
  116010. ch[t4]=ti2-cc[t5];
  116011. ch[t6-1]=cc[t5-1]+tr2;
  116012. ch[t4-1]=cc[t5-1]-tr2;
  116013. }
  116014. t1+=ido;
  116015. t2+=ido;
  116016. }
  116017. if(ido%2==1)return;
  116018. L105:
  116019. t3=(t2=(t1=ido)-1);
  116020. t2+=t0;
  116021. for(k=0;k<l1;k++){
  116022. ch[t1]=-cc[t2];
  116023. ch[t1-1]=cc[t3];
  116024. t1+=ido<<1;
  116025. t2+=ido;
  116026. t3+=ido;
  116027. }
  116028. }
  116029. static void dradf4(int ido,int l1,float *cc,float *ch,float *wa1,
  116030. float *wa2,float *wa3){
  116031. static float hsqt2 = .70710678118654752f;
  116032. int i,k,t0,t1,t2,t3,t4,t5,t6;
  116033. float ci2,ci3,ci4,cr2,cr3,cr4,ti1,ti2,ti3,ti4,tr1,tr2,tr3,tr4;
  116034. t0=l1*ido;
  116035. t1=t0;
  116036. t4=t1<<1;
  116037. t2=t1+(t1<<1);
  116038. t3=0;
  116039. for(k=0;k<l1;k++){
  116040. tr1=cc[t1]+cc[t2];
  116041. tr2=cc[t3]+cc[t4];
  116042. ch[t5=t3<<2]=tr1+tr2;
  116043. ch[(ido<<2)+t5-1]=tr2-tr1;
  116044. ch[(t5+=(ido<<1))-1]=cc[t3]-cc[t4];
  116045. ch[t5]=cc[t2]-cc[t1];
  116046. t1+=ido;
  116047. t2+=ido;
  116048. t3+=ido;
  116049. t4+=ido;
  116050. }
  116051. if(ido<2)return;
  116052. if(ido==2)goto L105;
  116053. t1=0;
  116054. for(k=0;k<l1;k++){
  116055. t2=t1;
  116056. t4=t1<<2;
  116057. t5=(t6=ido<<1)+t4;
  116058. for(i=2;i<ido;i+=2){
  116059. t3=(t2+=2);
  116060. t4+=2;
  116061. t5-=2;
  116062. t3+=t0;
  116063. cr2=wa1[i-2]*cc[t3-1]+wa1[i-1]*cc[t3];
  116064. ci2=wa1[i-2]*cc[t3]-wa1[i-1]*cc[t3-1];
  116065. t3+=t0;
  116066. cr3=wa2[i-2]*cc[t3-1]+wa2[i-1]*cc[t3];
  116067. ci3=wa2[i-2]*cc[t3]-wa2[i-1]*cc[t3-1];
  116068. t3+=t0;
  116069. cr4=wa3[i-2]*cc[t3-1]+wa3[i-1]*cc[t3];
  116070. ci4=wa3[i-2]*cc[t3]-wa3[i-1]*cc[t3-1];
  116071. tr1=cr2+cr4;
  116072. tr4=cr4-cr2;
  116073. ti1=ci2+ci4;
  116074. ti4=ci2-ci4;
  116075. ti2=cc[t2]+ci3;
  116076. ti3=cc[t2]-ci3;
  116077. tr2=cc[t2-1]+cr3;
  116078. tr3=cc[t2-1]-cr3;
  116079. ch[t4-1]=tr1+tr2;
  116080. ch[t4]=ti1+ti2;
  116081. ch[t5-1]=tr3-ti4;
  116082. ch[t5]=tr4-ti3;
  116083. ch[t4+t6-1]=ti4+tr3;
  116084. ch[t4+t6]=tr4+ti3;
  116085. ch[t5+t6-1]=tr2-tr1;
  116086. ch[t5+t6]=ti1-ti2;
  116087. }
  116088. t1+=ido;
  116089. }
  116090. if(ido&1)return;
  116091. L105:
  116092. t2=(t1=t0+ido-1)+(t0<<1);
  116093. t3=ido<<2;
  116094. t4=ido;
  116095. t5=ido<<1;
  116096. t6=ido;
  116097. for(k=0;k<l1;k++){
  116098. ti1=-hsqt2*(cc[t1]+cc[t2]);
  116099. tr1=hsqt2*(cc[t1]-cc[t2]);
  116100. ch[t4-1]=tr1+cc[t6-1];
  116101. ch[t4+t5-1]=cc[t6-1]-tr1;
  116102. ch[t4]=ti1-cc[t1+t0];
  116103. ch[t4+t5]=ti1+cc[t1+t0];
  116104. t1+=ido;
  116105. t2+=ido;
  116106. t4+=t3;
  116107. t6+=ido;
  116108. }
  116109. }
  116110. static void dradfg(int ido,int ip,int l1,int idl1,float *cc,float *c1,
  116111. float *c2,float *ch,float *ch2,float *wa){
  116112. static float tpi=6.283185307179586f;
  116113. int idij,ipph,i,j,k,l,ic,ik,is;
  116114. int t0,t1,t2,t3,t4,t5,t6,t7,t8,t9,t10;
  116115. float dc2,ai1,ai2,ar1,ar2,ds2;
  116116. int nbd;
  116117. float dcp,arg,dsp,ar1h,ar2h;
  116118. int idp2,ipp2;
  116119. arg=tpi/(float)ip;
  116120. dcp=cos(arg);
  116121. dsp=sin(arg);
  116122. ipph=(ip+1)>>1;
  116123. ipp2=ip;
  116124. idp2=ido;
  116125. nbd=(ido-1)>>1;
  116126. t0=l1*ido;
  116127. t10=ip*ido;
  116128. if(ido==1)goto L119;
  116129. for(ik=0;ik<idl1;ik++)ch2[ik]=c2[ik];
  116130. t1=0;
  116131. for(j=1;j<ip;j++){
  116132. t1+=t0;
  116133. t2=t1;
  116134. for(k=0;k<l1;k++){
  116135. ch[t2]=c1[t2];
  116136. t2+=ido;
  116137. }
  116138. }
  116139. is=-ido;
  116140. t1=0;
  116141. if(nbd>l1){
  116142. for(j=1;j<ip;j++){
  116143. t1+=t0;
  116144. is+=ido;
  116145. t2= -ido+t1;
  116146. for(k=0;k<l1;k++){
  116147. idij=is-1;
  116148. t2+=ido;
  116149. t3=t2;
  116150. for(i=2;i<ido;i+=2){
  116151. idij+=2;
  116152. t3+=2;
  116153. ch[t3-1]=wa[idij-1]*c1[t3-1]+wa[idij]*c1[t3];
  116154. ch[t3]=wa[idij-1]*c1[t3]-wa[idij]*c1[t3-1];
  116155. }
  116156. }
  116157. }
  116158. }else{
  116159. for(j=1;j<ip;j++){
  116160. is+=ido;
  116161. idij=is-1;
  116162. t1+=t0;
  116163. t2=t1;
  116164. for(i=2;i<ido;i+=2){
  116165. idij+=2;
  116166. t2+=2;
  116167. t3=t2;
  116168. for(k=0;k<l1;k++){
  116169. ch[t3-1]=wa[idij-1]*c1[t3-1]+wa[idij]*c1[t3];
  116170. ch[t3]=wa[idij-1]*c1[t3]-wa[idij]*c1[t3-1];
  116171. t3+=ido;
  116172. }
  116173. }
  116174. }
  116175. }
  116176. t1=0;
  116177. t2=ipp2*t0;
  116178. if(nbd<l1){
  116179. for(j=1;j<ipph;j++){
  116180. t1+=t0;
  116181. t2-=t0;
  116182. t3=t1;
  116183. t4=t2;
  116184. for(i=2;i<ido;i+=2){
  116185. t3+=2;
  116186. t4+=2;
  116187. t5=t3-ido;
  116188. t6=t4-ido;
  116189. for(k=0;k<l1;k++){
  116190. t5+=ido;
  116191. t6+=ido;
  116192. c1[t5-1]=ch[t5-1]+ch[t6-1];
  116193. c1[t6-1]=ch[t5]-ch[t6];
  116194. c1[t5]=ch[t5]+ch[t6];
  116195. c1[t6]=ch[t6-1]-ch[t5-1];
  116196. }
  116197. }
  116198. }
  116199. }else{
  116200. for(j=1;j<ipph;j++){
  116201. t1+=t0;
  116202. t2-=t0;
  116203. t3=t1;
  116204. t4=t2;
  116205. for(k=0;k<l1;k++){
  116206. t5=t3;
  116207. t6=t4;
  116208. for(i=2;i<ido;i+=2){
  116209. t5+=2;
  116210. t6+=2;
  116211. c1[t5-1]=ch[t5-1]+ch[t6-1];
  116212. c1[t6-1]=ch[t5]-ch[t6];
  116213. c1[t5]=ch[t5]+ch[t6];
  116214. c1[t6]=ch[t6-1]-ch[t5-1];
  116215. }
  116216. t3+=ido;
  116217. t4+=ido;
  116218. }
  116219. }
  116220. }
  116221. L119:
  116222. for(ik=0;ik<idl1;ik++)c2[ik]=ch2[ik];
  116223. t1=0;
  116224. t2=ipp2*idl1;
  116225. for(j=1;j<ipph;j++){
  116226. t1+=t0;
  116227. t2-=t0;
  116228. t3=t1-ido;
  116229. t4=t2-ido;
  116230. for(k=0;k<l1;k++){
  116231. t3+=ido;
  116232. t4+=ido;
  116233. c1[t3]=ch[t3]+ch[t4];
  116234. c1[t4]=ch[t4]-ch[t3];
  116235. }
  116236. }
  116237. ar1=1.f;
  116238. ai1=0.f;
  116239. t1=0;
  116240. t2=ipp2*idl1;
  116241. t3=(ip-1)*idl1;
  116242. for(l=1;l<ipph;l++){
  116243. t1+=idl1;
  116244. t2-=idl1;
  116245. ar1h=dcp*ar1-dsp*ai1;
  116246. ai1=dcp*ai1+dsp*ar1;
  116247. ar1=ar1h;
  116248. t4=t1;
  116249. t5=t2;
  116250. t6=t3;
  116251. t7=idl1;
  116252. for(ik=0;ik<idl1;ik++){
  116253. ch2[t4++]=c2[ik]+ar1*c2[t7++];
  116254. ch2[t5++]=ai1*c2[t6++];
  116255. }
  116256. dc2=ar1;
  116257. ds2=ai1;
  116258. ar2=ar1;
  116259. ai2=ai1;
  116260. t4=idl1;
  116261. t5=(ipp2-1)*idl1;
  116262. for(j=2;j<ipph;j++){
  116263. t4+=idl1;
  116264. t5-=idl1;
  116265. ar2h=dc2*ar2-ds2*ai2;
  116266. ai2=dc2*ai2+ds2*ar2;
  116267. ar2=ar2h;
  116268. t6=t1;
  116269. t7=t2;
  116270. t8=t4;
  116271. t9=t5;
  116272. for(ik=0;ik<idl1;ik++){
  116273. ch2[t6++]+=ar2*c2[t8++];
  116274. ch2[t7++]+=ai2*c2[t9++];
  116275. }
  116276. }
  116277. }
  116278. t1=0;
  116279. for(j=1;j<ipph;j++){
  116280. t1+=idl1;
  116281. t2=t1;
  116282. for(ik=0;ik<idl1;ik++)ch2[ik]+=c2[t2++];
  116283. }
  116284. if(ido<l1)goto L132;
  116285. t1=0;
  116286. t2=0;
  116287. for(k=0;k<l1;k++){
  116288. t3=t1;
  116289. t4=t2;
  116290. for(i=0;i<ido;i++)cc[t4++]=ch[t3++];
  116291. t1+=ido;
  116292. t2+=t10;
  116293. }
  116294. goto L135;
  116295. L132:
  116296. for(i=0;i<ido;i++){
  116297. t1=i;
  116298. t2=i;
  116299. for(k=0;k<l1;k++){
  116300. cc[t2]=ch[t1];
  116301. t1+=ido;
  116302. t2+=t10;
  116303. }
  116304. }
  116305. L135:
  116306. t1=0;
  116307. t2=ido<<1;
  116308. t3=0;
  116309. t4=ipp2*t0;
  116310. for(j=1;j<ipph;j++){
  116311. t1+=t2;
  116312. t3+=t0;
  116313. t4-=t0;
  116314. t5=t1;
  116315. t6=t3;
  116316. t7=t4;
  116317. for(k=0;k<l1;k++){
  116318. cc[t5-1]=ch[t6];
  116319. cc[t5]=ch[t7];
  116320. t5+=t10;
  116321. t6+=ido;
  116322. t7+=ido;
  116323. }
  116324. }
  116325. if(ido==1)return;
  116326. if(nbd<l1)goto L141;
  116327. t1=-ido;
  116328. t3=0;
  116329. t4=0;
  116330. t5=ipp2*t0;
  116331. for(j=1;j<ipph;j++){
  116332. t1+=t2;
  116333. t3+=t2;
  116334. t4+=t0;
  116335. t5-=t0;
  116336. t6=t1;
  116337. t7=t3;
  116338. t8=t4;
  116339. t9=t5;
  116340. for(k=0;k<l1;k++){
  116341. for(i=2;i<ido;i+=2){
  116342. ic=idp2-i;
  116343. cc[i+t7-1]=ch[i+t8-1]+ch[i+t9-1];
  116344. cc[ic+t6-1]=ch[i+t8-1]-ch[i+t9-1];
  116345. cc[i+t7]=ch[i+t8]+ch[i+t9];
  116346. cc[ic+t6]=ch[i+t9]-ch[i+t8];
  116347. }
  116348. t6+=t10;
  116349. t7+=t10;
  116350. t8+=ido;
  116351. t9+=ido;
  116352. }
  116353. }
  116354. return;
  116355. L141:
  116356. t1=-ido;
  116357. t3=0;
  116358. t4=0;
  116359. t5=ipp2*t0;
  116360. for(j=1;j<ipph;j++){
  116361. t1+=t2;
  116362. t3+=t2;
  116363. t4+=t0;
  116364. t5-=t0;
  116365. for(i=2;i<ido;i+=2){
  116366. t6=idp2+t1-i;
  116367. t7=i+t3;
  116368. t8=i+t4;
  116369. t9=i+t5;
  116370. for(k=0;k<l1;k++){
  116371. cc[t7-1]=ch[t8-1]+ch[t9-1];
  116372. cc[t6-1]=ch[t8-1]-ch[t9-1];
  116373. cc[t7]=ch[t8]+ch[t9];
  116374. cc[t6]=ch[t9]-ch[t8];
  116375. t6+=t10;
  116376. t7+=t10;
  116377. t8+=ido;
  116378. t9+=ido;
  116379. }
  116380. }
  116381. }
  116382. }
  116383. static void drftf1(int n,float *c,float *ch,float *wa,int *ifac){
  116384. int i,k1,l1,l2;
  116385. int na,kh,nf;
  116386. int ip,iw,ido,idl1,ix2,ix3;
  116387. nf=ifac[1];
  116388. na=1;
  116389. l2=n;
  116390. iw=n;
  116391. for(k1=0;k1<nf;k1++){
  116392. kh=nf-k1;
  116393. ip=ifac[kh+1];
  116394. l1=l2/ip;
  116395. ido=n/l2;
  116396. idl1=ido*l1;
  116397. iw-=(ip-1)*ido;
  116398. na=1-na;
  116399. if(ip!=4)goto L102;
  116400. ix2=iw+ido;
  116401. ix3=ix2+ido;
  116402. if(na!=0)
  116403. dradf4(ido,l1,ch,c,wa+iw-1,wa+ix2-1,wa+ix3-1);
  116404. else
  116405. dradf4(ido,l1,c,ch,wa+iw-1,wa+ix2-1,wa+ix3-1);
  116406. goto L110;
  116407. L102:
  116408. if(ip!=2)goto L104;
  116409. if(na!=0)goto L103;
  116410. dradf2(ido,l1,c,ch,wa+iw-1);
  116411. goto L110;
  116412. L103:
  116413. dradf2(ido,l1,ch,c,wa+iw-1);
  116414. goto L110;
  116415. L104:
  116416. if(ido==1)na=1-na;
  116417. if(na!=0)goto L109;
  116418. dradfg(ido,ip,l1,idl1,c,c,c,ch,ch,wa+iw-1);
  116419. na=1;
  116420. goto L110;
  116421. L109:
  116422. dradfg(ido,ip,l1,idl1,ch,ch,ch,c,c,wa+iw-1);
  116423. na=0;
  116424. L110:
  116425. l2=l1;
  116426. }
  116427. if(na==1)return;
  116428. for(i=0;i<n;i++)c[i]=ch[i];
  116429. }
  116430. static void dradb2(int ido,int l1,float *cc,float *ch,float *wa1){
  116431. int i,k,t0,t1,t2,t3,t4,t5,t6;
  116432. float ti2,tr2;
  116433. t0=l1*ido;
  116434. t1=0;
  116435. t2=0;
  116436. t3=(ido<<1)-1;
  116437. for(k=0;k<l1;k++){
  116438. ch[t1]=cc[t2]+cc[t3+t2];
  116439. ch[t1+t0]=cc[t2]-cc[t3+t2];
  116440. t2=(t1+=ido)<<1;
  116441. }
  116442. if(ido<2)return;
  116443. if(ido==2)goto L105;
  116444. t1=0;
  116445. t2=0;
  116446. for(k=0;k<l1;k++){
  116447. t3=t1;
  116448. t5=(t4=t2)+(ido<<1);
  116449. t6=t0+t1;
  116450. for(i=2;i<ido;i+=2){
  116451. t3+=2;
  116452. t4+=2;
  116453. t5-=2;
  116454. t6+=2;
  116455. ch[t3-1]=cc[t4-1]+cc[t5-1];
  116456. tr2=cc[t4-1]-cc[t5-1];
  116457. ch[t3]=cc[t4]-cc[t5];
  116458. ti2=cc[t4]+cc[t5];
  116459. ch[t6-1]=wa1[i-2]*tr2-wa1[i-1]*ti2;
  116460. ch[t6]=wa1[i-2]*ti2+wa1[i-1]*tr2;
  116461. }
  116462. t2=(t1+=ido)<<1;
  116463. }
  116464. if(ido%2==1)return;
  116465. L105:
  116466. t1=ido-1;
  116467. t2=ido-1;
  116468. for(k=0;k<l1;k++){
  116469. ch[t1]=cc[t2]+cc[t2];
  116470. ch[t1+t0]=-(cc[t2+1]+cc[t2+1]);
  116471. t1+=ido;
  116472. t2+=ido<<1;
  116473. }
  116474. }
  116475. static void dradb3(int ido,int l1,float *cc,float *ch,float *wa1,
  116476. float *wa2){
  116477. static float taur = -.5f;
  116478. static float taui = .8660254037844386f;
  116479. int i,k,t0,t1,t2,t3,t4,t5,t6,t7,t8,t9,t10;
  116480. float ci2,ci3,di2,di3,cr2,cr3,dr2,dr3,ti2,tr2;
  116481. t0=l1*ido;
  116482. t1=0;
  116483. t2=t0<<1;
  116484. t3=ido<<1;
  116485. t4=ido+(ido<<1);
  116486. t5=0;
  116487. for(k=0;k<l1;k++){
  116488. tr2=cc[t3-1]+cc[t3-1];
  116489. cr2=cc[t5]+(taur*tr2);
  116490. ch[t1]=cc[t5]+tr2;
  116491. ci3=taui*(cc[t3]+cc[t3]);
  116492. ch[t1+t0]=cr2-ci3;
  116493. ch[t1+t2]=cr2+ci3;
  116494. t1+=ido;
  116495. t3+=t4;
  116496. t5+=t4;
  116497. }
  116498. if(ido==1)return;
  116499. t1=0;
  116500. t3=ido<<1;
  116501. for(k=0;k<l1;k++){
  116502. t7=t1+(t1<<1);
  116503. t6=(t5=t7+t3);
  116504. t8=t1;
  116505. t10=(t9=t1+t0)+t0;
  116506. for(i=2;i<ido;i+=2){
  116507. t5+=2;
  116508. t6-=2;
  116509. t7+=2;
  116510. t8+=2;
  116511. t9+=2;
  116512. t10+=2;
  116513. tr2=cc[t5-1]+cc[t6-1];
  116514. cr2=cc[t7-1]+(taur*tr2);
  116515. ch[t8-1]=cc[t7-1]+tr2;
  116516. ti2=cc[t5]-cc[t6];
  116517. ci2=cc[t7]+(taur*ti2);
  116518. ch[t8]=cc[t7]+ti2;
  116519. cr3=taui*(cc[t5-1]-cc[t6-1]);
  116520. ci3=taui*(cc[t5]+cc[t6]);
  116521. dr2=cr2-ci3;
  116522. dr3=cr2+ci3;
  116523. di2=ci2+cr3;
  116524. di3=ci2-cr3;
  116525. ch[t9-1]=wa1[i-2]*dr2-wa1[i-1]*di2;
  116526. ch[t9]=wa1[i-2]*di2+wa1[i-1]*dr2;
  116527. ch[t10-1]=wa2[i-2]*dr3-wa2[i-1]*di3;
  116528. ch[t10]=wa2[i-2]*di3+wa2[i-1]*dr3;
  116529. }
  116530. t1+=ido;
  116531. }
  116532. }
  116533. static void dradb4(int ido,int l1,float *cc,float *ch,float *wa1,
  116534. float *wa2,float *wa3){
  116535. static float sqrt2=1.414213562373095f;
  116536. int i,k,t0,t1,t2,t3,t4,t5,t6,t7,t8;
  116537. float ci2,ci3,ci4,cr2,cr3,cr4,ti1,ti2,ti3,ti4,tr1,tr2,tr3,tr4;
  116538. t0=l1*ido;
  116539. t1=0;
  116540. t2=ido<<2;
  116541. t3=0;
  116542. t6=ido<<1;
  116543. for(k=0;k<l1;k++){
  116544. t4=t3+t6;
  116545. t5=t1;
  116546. tr3=cc[t4-1]+cc[t4-1];
  116547. tr4=cc[t4]+cc[t4];
  116548. tr1=cc[t3]-cc[(t4+=t6)-1];
  116549. tr2=cc[t3]+cc[t4-1];
  116550. ch[t5]=tr2+tr3;
  116551. ch[t5+=t0]=tr1-tr4;
  116552. ch[t5+=t0]=tr2-tr3;
  116553. ch[t5+=t0]=tr1+tr4;
  116554. t1+=ido;
  116555. t3+=t2;
  116556. }
  116557. if(ido<2)return;
  116558. if(ido==2)goto L105;
  116559. t1=0;
  116560. for(k=0;k<l1;k++){
  116561. t5=(t4=(t3=(t2=t1<<2)+t6))+t6;
  116562. t7=t1;
  116563. for(i=2;i<ido;i+=2){
  116564. t2+=2;
  116565. t3+=2;
  116566. t4-=2;
  116567. t5-=2;
  116568. t7+=2;
  116569. ti1=cc[t2]+cc[t5];
  116570. ti2=cc[t2]-cc[t5];
  116571. ti3=cc[t3]-cc[t4];
  116572. tr4=cc[t3]+cc[t4];
  116573. tr1=cc[t2-1]-cc[t5-1];
  116574. tr2=cc[t2-1]+cc[t5-1];
  116575. ti4=cc[t3-1]-cc[t4-1];
  116576. tr3=cc[t3-1]+cc[t4-1];
  116577. ch[t7-1]=tr2+tr3;
  116578. cr3=tr2-tr3;
  116579. ch[t7]=ti2+ti3;
  116580. ci3=ti2-ti3;
  116581. cr2=tr1-tr4;
  116582. cr4=tr1+tr4;
  116583. ci2=ti1+ti4;
  116584. ci4=ti1-ti4;
  116585. ch[(t8=t7+t0)-1]=wa1[i-2]*cr2-wa1[i-1]*ci2;
  116586. ch[t8]=wa1[i-2]*ci2+wa1[i-1]*cr2;
  116587. ch[(t8+=t0)-1]=wa2[i-2]*cr3-wa2[i-1]*ci3;
  116588. ch[t8]=wa2[i-2]*ci3+wa2[i-1]*cr3;
  116589. ch[(t8+=t0)-1]=wa3[i-2]*cr4-wa3[i-1]*ci4;
  116590. ch[t8]=wa3[i-2]*ci4+wa3[i-1]*cr4;
  116591. }
  116592. t1+=ido;
  116593. }
  116594. if(ido%2 == 1)return;
  116595. L105:
  116596. t1=ido;
  116597. t2=ido<<2;
  116598. t3=ido-1;
  116599. t4=ido+(ido<<1);
  116600. for(k=0;k<l1;k++){
  116601. t5=t3;
  116602. ti1=cc[t1]+cc[t4];
  116603. ti2=cc[t4]-cc[t1];
  116604. tr1=cc[t1-1]-cc[t4-1];
  116605. tr2=cc[t1-1]+cc[t4-1];
  116606. ch[t5]=tr2+tr2;
  116607. ch[t5+=t0]=sqrt2*(tr1-ti1);
  116608. ch[t5+=t0]=ti2+ti2;
  116609. ch[t5+=t0]=-sqrt2*(tr1+ti1);
  116610. t3+=ido;
  116611. t1+=t2;
  116612. t4+=t2;
  116613. }
  116614. }
  116615. static void dradbg(int ido,int ip,int l1,int idl1,float *cc,float *c1,
  116616. float *c2,float *ch,float *ch2,float *wa){
  116617. static float tpi=6.283185307179586f;
  116618. int idij,ipph,i,j,k,l,ik,is,t0,t1,t2,t3,t4,t5,t6,t7,t8,t9,t10,
  116619. t11,t12;
  116620. float dc2,ai1,ai2,ar1,ar2,ds2;
  116621. int nbd;
  116622. float dcp,arg,dsp,ar1h,ar2h;
  116623. int ipp2;
  116624. t10=ip*ido;
  116625. t0=l1*ido;
  116626. arg=tpi/(float)ip;
  116627. dcp=cos(arg);
  116628. dsp=sin(arg);
  116629. nbd=(ido-1)>>1;
  116630. ipp2=ip;
  116631. ipph=(ip+1)>>1;
  116632. if(ido<l1)goto L103;
  116633. t1=0;
  116634. t2=0;
  116635. for(k=0;k<l1;k++){
  116636. t3=t1;
  116637. t4=t2;
  116638. for(i=0;i<ido;i++){
  116639. ch[t3]=cc[t4];
  116640. t3++;
  116641. t4++;
  116642. }
  116643. t1+=ido;
  116644. t2+=t10;
  116645. }
  116646. goto L106;
  116647. L103:
  116648. t1=0;
  116649. for(i=0;i<ido;i++){
  116650. t2=t1;
  116651. t3=t1;
  116652. for(k=0;k<l1;k++){
  116653. ch[t2]=cc[t3];
  116654. t2+=ido;
  116655. t3+=t10;
  116656. }
  116657. t1++;
  116658. }
  116659. L106:
  116660. t1=0;
  116661. t2=ipp2*t0;
  116662. t7=(t5=ido<<1);
  116663. for(j=1;j<ipph;j++){
  116664. t1+=t0;
  116665. t2-=t0;
  116666. t3=t1;
  116667. t4=t2;
  116668. t6=t5;
  116669. for(k=0;k<l1;k++){
  116670. ch[t3]=cc[t6-1]+cc[t6-1];
  116671. ch[t4]=cc[t6]+cc[t6];
  116672. t3+=ido;
  116673. t4+=ido;
  116674. t6+=t10;
  116675. }
  116676. t5+=t7;
  116677. }
  116678. if (ido == 1)goto L116;
  116679. if(nbd<l1)goto L112;
  116680. t1=0;
  116681. t2=ipp2*t0;
  116682. t7=0;
  116683. for(j=1;j<ipph;j++){
  116684. t1+=t0;
  116685. t2-=t0;
  116686. t3=t1;
  116687. t4=t2;
  116688. t7+=(ido<<1);
  116689. t8=t7;
  116690. for(k=0;k<l1;k++){
  116691. t5=t3;
  116692. t6=t4;
  116693. t9=t8;
  116694. t11=t8;
  116695. for(i=2;i<ido;i+=2){
  116696. t5+=2;
  116697. t6+=2;
  116698. t9+=2;
  116699. t11-=2;
  116700. ch[t5-1]=cc[t9-1]+cc[t11-1];
  116701. ch[t6-1]=cc[t9-1]-cc[t11-1];
  116702. ch[t5]=cc[t9]-cc[t11];
  116703. ch[t6]=cc[t9]+cc[t11];
  116704. }
  116705. t3+=ido;
  116706. t4+=ido;
  116707. t8+=t10;
  116708. }
  116709. }
  116710. goto L116;
  116711. L112:
  116712. t1=0;
  116713. t2=ipp2*t0;
  116714. t7=0;
  116715. for(j=1;j<ipph;j++){
  116716. t1+=t0;
  116717. t2-=t0;
  116718. t3=t1;
  116719. t4=t2;
  116720. t7+=(ido<<1);
  116721. t8=t7;
  116722. t9=t7;
  116723. for(i=2;i<ido;i+=2){
  116724. t3+=2;
  116725. t4+=2;
  116726. t8+=2;
  116727. t9-=2;
  116728. t5=t3;
  116729. t6=t4;
  116730. t11=t8;
  116731. t12=t9;
  116732. for(k=0;k<l1;k++){
  116733. ch[t5-1]=cc[t11-1]+cc[t12-1];
  116734. ch[t6-1]=cc[t11-1]-cc[t12-1];
  116735. ch[t5]=cc[t11]-cc[t12];
  116736. ch[t6]=cc[t11]+cc[t12];
  116737. t5+=ido;
  116738. t6+=ido;
  116739. t11+=t10;
  116740. t12+=t10;
  116741. }
  116742. }
  116743. }
  116744. L116:
  116745. ar1=1.f;
  116746. ai1=0.f;
  116747. t1=0;
  116748. t9=(t2=ipp2*idl1);
  116749. t3=(ip-1)*idl1;
  116750. for(l=1;l<ipph;l++){
  116751. t1+=idl1;
  116752. t2-=idl1;
  116753. ar1h=dcp*ar1-dsp*ai1;
  116754. ai1=dcp*ai1+dsp*ar1;
  116755. ar1=ar1h;
  116756. t4=t1;
  116757. t5=t2;
  116758. t6=0;
  116759. t7=idl1;
  116760. t8=t3;
  116761. for(ik=0;ik<idl1;ik++){
  116762. c2[t4++]=ch2[t6++]+ar1*ch2[t7++];
  116763. c2[t5++]=ai1*ch2[t8++];
  116764. }
  116765. dc2=ar1;
  116766. ds2=ai1;
  116767. ar2=ar1;
  116768. ai2=ai1;
  116769. t6=idl1;
  116770. t7=t9-idl1;
  116771. for(j=2;j<ipph;j++){
  116772. t6+=idl1;
  116773. t7-=idl1;
  116774. ar2h=dc2*ar2-ds2*ai2;
  116775. ai2=dc2*ai2+ds2*ar2;
  116776. ar2=ar2h;
  116777. t4=t1;
  116778. t5=t2;
  116779. t11=t6;
  116780. t12=t7;
  116781. for(ik=0;ik<idl1;ik++){
  116782. c2[t4++]+=ar2*ch2[t11++];
  116783. c2[t5++]+=ai2*ch2[t12++];
  116784. }
  116785. }
  116786. }
  116787. t1=0;
  116788. for(j=1;j<ipph;j++){
  116789. t1+=idl1;
  116790. t2=t1;
  116791. for(ik=0;ik<idl1;ik++)ch2[ik]+=ch2[t2++];
  116792. }
  116793. t1=0;
  116794. t2=ipp2*t0;
  116795. for(j=1;j<ipph;j++){
  116796. t1+=t0;
  116797. t2-=t0;
  116798. t3=t1;
  116799. t4=t2;
  116800. for(k=0;k<l1;k++){
  116801. ch[t3]=c1[t3]-c1[t4];
  116802. ch[t4]=c1[t3]+c1[t4];
  116803. t3+=ido;
  116804. t4+=ido;
  116805. }
  116806. }
  116807. if(ido==1)goto L132;
  116808. if(nbd<l1)goto L128;
  116809. t1=0;
  116810. t2=ipp2*t0;
  116811. for(j=1;j<ipph;j++){
  116812. t1+=t0;
  116813. t2-=t0;
  116814. t3=t1;
  116815. t4=t2;
  116816. for(k=0;k<l1;k++){
  116817. t5=t3;
  116818. t6=t4;
  116819. for(i=2;i<ido;i+=2){
  116820. t5+=2;
  116821. t6+=2;
  116822. ch[t5-1]=c1[t5-1]-c1[t6];
  116823. ch[t6-1]=c1[t5-1]+c1[t6];
  116824. ch[t5]=c1[t5]+c1[t6-1];
  116825. ch[t6]=c1[t5]-c1[t6-1];
  116826. }
  116827. t3+=ido;
  116828. t4+=ido;
  116829. }
  116830. }
  116831. goto L132;
  116832. L128:
  116833. t1=0;
  116834. t2=ipp2*t0;
  116835. for(j=1;j<ipph;j++){
  116836. t1+=t0;
  116837. t2-=t0;
  116838. t3=t1;
  116839. t4=t2;
  116840. for(i=2;i<ido;i+=2){
  116841. t3+=2;
  116842. t4+=2;
  116843. t5=t3;
  116844. t6=t4;
  116845. for(k=0;k<l1;k++){
  116846. ch[t5-1]=c1[t5-1]-c1[t6];
  116847. ch[t6-1]=c1[t5-1]+c1[t6];
  116848. ch[t5]=c1[t5]+c1[t6-1];
  116849. ch[t6]=c1[t5]-c1[t6-1];
  116850. t5+=ido;
  116851. t6+=ido;
  116852. }
  116853. }
  116854. }
  116855. L132:
  116856. if(ido==1)return;
  116857. for(ik=0;ik<idl1;ik++)c2[ik]=ch2[ik];
  116858. t1=0;
  116859. for(j=1;j<ip;j++){
  116860. t2=(t1+=t0);
  116861. for(k=0;k<l1;k++){
  116862. c1[t2]=ch[t2];
  116863. t2+=ido;
  116864. }
  116865. }
  116866. if(nbd>l1)goto L139;
  116867. is= -ido-1;
  116868. t1=0;
  116869. for(j=1;j<ip;j++){
  116870. is+=ido;
  116871. t1+=t0;
  116872. idij=is;
  116873. t2=t1;
  116874. for(i=2;i<ido;i+=2){
  116875. t2+=2;
  116876. idij+=2;
  116877. t3=t2;
  116878. for(k=0;k<l1;k++){
  116879. c1[t3-1]=wa[idij-1]*ch[t3-1]-wa[idij]*ch[t3];
  116880. c1[t3]=wa[idij-1]*ch[t3]+wa[idij]*ch[t3-1];
  116881. t3+=ido;
  116882. }
  116883. }
  116884. }
  116885. return;
  116886. L139:
  116887. is= -ido-1;
  116888. t1=0;
  116889. for(j=1;j<ip;j++){
  116890. is+=ido;
  116891. t1+=t0;
  116892. t2=t1;
  116893. for(k=0;k<l1;k++){
  116894. idij=is;
  116895. t3=t2;
  116896. for(i=2;i<ido;i+=2){
  116897. idij+=2;
  116898. t3+=2;
  116899. c1[t3-1]=wa[idij-1]*ch[t3-1]-wa[idij]*ch[t3];
  116900. c1[t3]=wa[idij-1]*ch[t3]+wa[idij]*ch[t3-1];
  116901. }
  116902. t2+=ido;
  116903. }
  116904. }
  116905. }
  116906. static void drftb1(int n, float *c, float *ch, float *wa, int *ifac){
  116907. int i,k1,l1,l2;
  116908. int na;
  116909. int nf,ip,iw,ix2,ix3,ido,idl1;
  116910. nf=ifac[1];
  116911. na=0;
  116912. l1=1;
  116913. iw=1;
  116914. for(k1=0;k1<nf;k1++){
  116915. ip=ifac[k1 + 2];
  116916. l2=ip*l1;
  116917. ido=n/l2;
  116918. idl1=ido*l1;
  116919. if(ip!=4)goto L103;
  116920. ix2=iw+ido;
  116921. ix3=ix2+ido;
  116922. if(na!=0)
  116923. dradb4(ido,l1,ch,c,wa+iw-1,wa+ix2-1,wa+ix3-1);
  116924. else
  116925. dradb4(ido,l1,c,ch,wa+iw-1,wa+ix2-1,wa+ix3-1);
  116926. na=1-na;
  116927. goto L115;
  116928. L103:
  116929. if(ip!=2)goto L106;
  116930. if(na!=0)
  116931. dradb2(ido,l1,ch,c,wa+iw-1);
  116932. else
  116933. dradb2(ido,l1,c,ch,wa+iw-1);
  116934. na=1-na;
  116935. goto L115;
  116936. L106:
  116937. if(ip!=3)goto L109;
  116938. ix2=iw+ido;
  116939. if(na!=0)
  116940. dradb3(ido,l1,ch,c,wa+iw-1,wa+ix2-1);
  116941. else
  116942. dradb3(ido,l1,c,ch,wa+iw-1,wa+ix2-1);
  116943. na=1-na;
  116944. goto L115;
  116945. L109:
  116946. /* The radix five case can be translated later..... */
  116947. /* if(ip!=5)goto L112;
  116948. ix2=iw+ido;
  116949. ix3=ix2+ido;
  116950. ix4=ix3+ido;
  116951. if(na!=0)
  116952. dradb5(ido,l1,ch,c,wa+iw-1,wa+ix2-1,wa+ix3-1,wa+ix4-1);
  116953. else
  116954. dradb5(ido,l1,c,ch,wa+iw-1,wa+ix2-1,wa+ix3-1,wa+ix4-1);
  116955. na=1-na;
  116956. goto L115;
  116957. L112:*/
  116958. if(na!=0)
  116959. dradbg(ido,ip,l1,idl1,ch,ch,ch,c,c,wa+iw-1);
  116960. else
  116961. dradbg(ido,ip,l1,idl1,c,c,c,ch,ch,wa+iw-1);
  116962. if(ido==1)na=1-na;
  116963. L115:
  116964. l1=l2;
  116965. iw+=(ip-1)*ido;
  116966. }
  116967. if(na==0)return;
  116968. for(i=0;i<n;i++)c[i]=ch[i];
  116969. }
  116970. void drft_forward(drft_lookup *l,float *data){
  116971. if(l->n==1)return;
  116972. drftf1(l->n,data,l->trigcache,l->trigcache+l->n,l->splitcache);
  116973. }
  116974. void drft_backward(drft_lookup *l,float *data){
  116975. if (l->n==1)return;
  116976. drftb1(l->n,data,l->trigcache,l->trigcache+l->n,l->splitcache);
  116977. }
  116978. void drft_init(drft_lookup *l,int n){
  116979. l->n=n;
  116980. l->trigcache=(float*)_ogg_calloc(3*n,sizeof(*l->trigcache));
  116981. l->splitcache=(int*)_ogg_calloc(32,sizeof(*l->splitcache));
  116982. fdrffti(n, l->trigcache, l->splitcache);
  116983. }
  116984. void drft_clear(drft_lookup *l){
  116985. if(l){
  116986. if(l->trigcache)_ogg_free(l->trigcache);
  116987. if(l->splitcache)_ogg_free(l->splitcache);
  116988. memset(l,0,sizeof(*l));
  116989. }
  116990. }
  116991. #endif
  116992. /*** End of inlined file: smallft.c ***/
  116993. /*** Start of inlined file: synthesis.c ***/
  116994. /*** Start of inlined file: juce_OggVorbisHeader.h ***/
  116995. // This file is included at the start of each Ogg-Vorbis .c file, just to do a few housekeeping
  116996. // tasks..
  116997. #if JUCE_MSVC
  116998. #pragma warning (disable: 4267 4127 4244 4996 4100 4701 4702 4013 4133 4206 4305 4189 4706)
  116999. #endif
  117000. /*** End of inlined file: juce_OggVorbisHeader.h ***/
  117001. #if JUCE_USE_OGGVORBIS
  117002. #include <stdio.h>
  117003. int vorbis_synthesis(vorbis_block *vb,ogg_packet *op){
  117004. vorbis_dsp_state *vd=vb->vd;
  117005. private_state *b=(private_state*)vd->backend_state;
  117006. vorbis_info *vi=vd->vi;
  117007. codec_setup_info *ci=(codec_setup_info*) vi->codec_setup;
  117008. oggpack_buffer *opb=&vb->opb;
  117009. int type,mode,i;
  117010. /* first things first. Make sure decode is ready */
  117011. _vorbis_block_ripcord(vb);
  117012. oggpack_readinit(opb,op->packet,op->bytes);
  117013. /* Check the packet type */
  117014. if(oggpack_read(opb,1)!=0){
  117015. /* Oops. This is not an audio data packet */
  117016. return(OV_ENOTAUDIO);
  117017. }
  117018. /* read our mode and pre/post windowsize */
  117019. mode=oggpack_read(opb,b->modebits);
  117020. if(mode==-1)return(OV_EBADPACKET);
  117021. vb->mode=mode;
  117022. vb->W=ci->mode_param[mode]->blockflag;
  117023. if(vb->W){
  117024. /* this doesn;t get mapped through mode selection as it's used
  117025. only for window selection */
  117026. vb->lW=oggpack_read(opb,1);
  117027. vb->nW=oggpack_read(opb,1);
  117028. if(vb->nW==-1) return(OV_EBADPACKET);
  117029. }else{
  117030. vb->lW=0;
  117031. vb->nW=0;
  117032. }
  117033. /* more setup */
  117034. vb->granulepos=op->granulepos;
  117035. vb->sequence=op->packetno;
  117036. vb->eofflag=op->e_o_s;
  117037. /* alloc pcm passback storage */
  117038. vb->pcmend=ci->blocksizes[vb->W];
  117039. vb->pcm=(float**)_vorbis_block_alloc(vb,sizeof(*vb->pcm)*vi->channels);
  117040. for(i=0;i<vi->channels;i++)
  117041. vb->pcm[i]=(float*)_vorbis_block_alloc(vb,vb->pcmend*sizeof(*vb->pcm[i]));
  117042. /* unpack_header enforces range checking */
  117043. type=ci->map_type[ci->mode_param[mode]->mapping];
  117044. return(_mapping_P[type]->inverse(vb,ci->map_param[ci->mode_param[mode]->
  117045. mapping]));
  117046. }
  117047. /* used to track pcm position without actually performing decode.
  117048. Useful for sequential 'fast forward' */
  117049. int vorbis_synthesis_trackonly(vorbis_block *vb,ogg_packet *op){
  117050. vorbis_dsp_state *vd=vb->vd;
  117051. private_state *b=(private_state*)vd->backend_state;
  117052. vorbis_info *vi=vd->vi;
  117053. codec_setup_info *ci=(codec_setup_info*)vi->codec_setup;
  117054. oggpack_buffer *opb=&vb->opb;
  117055. int mode;
  117056. /* first things first. Make sure decode is ready */
  117057. _vorbis_block_ripcord(vb);
  117058. oggpack_readinit(opb,op->packet,op->bytes);
  117059. /* Check the packet type */
  117060. if(oggpack_read(opb,1)!=0){
  117061. /* Oops. This is not an audio data packet */
  117062. return(OV_ENOTAUDIO);
  117063. }
  117064. /* read our mode and pre/post windowsize */
  117065. mode=oggpack_read(opb,b->modebits);
  117066. if(mode==-1)return(OV_EBADPACKET);
  117067. vb->mode=mode;
  117068. vb->W=ci->mode_param[mode]->blockflag;
  117069. if(vb->W){
  117070. vb->lW=oggpack_read(opb,1);
  117071. vb->nW=oggpack_read(opb,1);
  117072. if(vb->nW==-1) return(OV_EBADPACKET);
  117073. }else{
  117074. vb->lW=0;
  117075. vb->nW=0;
  117076. }
  117077. /* more setup */
  117078. vb->granulepos=op->granulepos;
  117079. vb->sequence=op->packetno;
  117080. vb->eofflag=op->e_o_s;
  117081. /* no pcm */
  117082. vb->pcmend=0;
  117083. vb->pcm=NULL;
  117084. return(0);
  117085. }
  117086. long vorbis_packet_blocksize(vorbis_info *vi,ogg_packet *op){
  117087. codec_setup_info *ci=(codec_setup_info*)vi->codec_setup;
  117088. oggpack_buffer opb;
  117089. int mode;
  117090. oggpack_readinit(&opb,op->packet,op->bytes);
  117091. /* Check the packet type */
  117092. if(oggpack_read(&opb,1)!=0){
  117093. /* Oops. This is not an audio data packet */
  117094. return(OV_ENOTAUDIO);
  117095. }
  117096. {
  117097. int modebits=0;
  117098. int v=ci->modes;
  117099. while(v>1){
  117100. modebits++;
  117101. v>>=1;
  117102. }
  117103. /* read our mode and pre/post windowsize */
  117104. mode=oggpack_read(&opb,modebits);
  117105. }
  117106. if(mode==-1)return(OV_EBADPACKET);
  117107. return(ci->blocksizes[ci->mode_param[mode]->blockflag]);
  117108. }
  117109. int vorbis_synthesis_halfrate(vorbis_info *vi,int flag){
  117110. /* set / clear half-sample-rate mode */
  117111. codec_setup_info *ci=(codec_setup_info*)vi->codec_setup;
  117112. /* right now, our MDCT can't handle < 64 sample windows. */
  117113. if(ci->blocksizes[0]<=64 && flag)return -1;
  117114. ci->halfrate_flag=(flag?1:0);
  117115. return 0;
  117116. }
  117117. int vorbis_synthesis_halfrate_p(vorbis_info *vi){
  117118. codec_setup_info *ci=(codec_setup_info*)vi->codec_setup;
  117119. return ci->halfrate_flag;
  117120. }
  117121. #endif
  117122. /*** End of inlined file: synthesis.c ***/
  117123. /*** Start of inlined file: vorbisenc.c ***/
  117124. /*** Start of inlined file: juce_OggVorbisHeader.h ***/
  117125. // This file is included at the start of each Ogg-Vorbis .c file, just to do a few housekeeping
  117126. // tasks..
  117127. #if JUCE_MSVC
  117128. #pragma warning (disable: 4267 4127 4244 4996 4100 4701 4702 4013 4133 4206 4305 4189 4706)
  117129. #endif
  117130. /*** End of inlined file: juce_OggVorbisHeader.h ***/
  117131. #if JUCE_USE_OGGVORBIS
  117132. #include <stdlib.h>
  117133. #include <string.h>
  117134. #include <math.h>
  117135. /* careful with this; it's using static array sizing to make managing
  117136. all the modes a little less annoying. If we use a residue backend
  117137. with > 12 partition types, or a different division of iteration,
  117138. this needs to be updated. */
  117139. typedef struct {
  117140. static_codebook *books[12][3];
  117141. } static_bookblock;
  117142. typedef struct {
  117143. int res_type;
  117144. int limit_type; /* 0 lowpass limited, 1 point stereo limited */
  117145. vorbis_info_residue0 *res;
  117146. static_codebook *book_aux;
  117147. static_codebook *book_aux_managed;
  117148. static_bookblock *books_base;
  117149. static_bookblock *books_base_managed;
  117150. } vorbis_residue_template;
  117151. typedef struct {
  117152. vorbis_info_mapping0 *map;
  117153. vorbis_residue_template *res;
  117154. } vorbis_mapping_template;
  117155. typedef struct vp_adjblock{
  117156. int block[P_BANDS];
  117157. } vp_adjblock;
  117158. typedef struct {
  117159. int data[NOISE_COMPAND_LEVELS];
  117160. } compandblock;
  117161. /* high level configuration information for setting things up
  117162. step-by-step with the detailed vorbis_encode_ctl interface.
  117163. There's a fair amount of redundancy such that interactive setup
  117164. does not directly deal with any vorbis_info or codec_setup_info
  117165. initialization; it's all stored (until full init) in this highlevel
  117166. setup, then flushed out to the real codec setup structs later. */
  117167. typedef struct {
  117168. int att[P_NOISECURVES];
  117169. float boost;
  117170. float decay;
  117171. } att3;
  117172. typedef struct { int data[P_NOISECURVES]; } adj3;
  117173. typedef struct {
  117174. int pre[PACKETBLOBS];
  117175. int post[PACKETBLOBS];
  117176. float kHz[PACKETBLOBS];
  117177. float lowpasskHz[PACKETBLOBS];
  117178. } adj_stereo;
  117179. typedef struct {
  117180. int lo;
  117181. int hi;
  117182. int fixed;
  117183. } noiseguard;
  117184. typedef struct {
  117185. int data[P_NOISECURVES][17];
  117186. } noise3;
  117187. typedef struct {
  117188. int mappings;
  117189. double *rate_mapping;
  117190. double *quality_mapping;
  117191. int coupling_restriction;
  117192. long samplerate_min_restriction;
  117193. long samplerate_max_restriction;
  117194. int *blocksize_short;
  117195. int *blocksize_long;
  117196. att3 *psy_tone_masteratt;
  117197. int *psy_tone_0dB;
  117198. int *psy_tone_dBsuppress;
  117199. vp_adjblock *psy_tone_adj_impulse;
  117200. vp_adjblock *psy_tone_adj_long;
  117201. vp_adjblock *psy_tone_adj_other;
  117202. noiseguard *psy_noiseguards;
  117203. noise3 *psy_noise_bias_impulse;
  117204. noise3 *psy_noise_bias_padding;
  117205. noise3 *psy_noise_bias_trans;
  117206. noise3 *psy_noise_bias_long;
  117207. int *psy_noise_dBsuppress;
  117208. compandblock *psy_noise_compand;
  117209. double *psy_noise_compand_short_mapping;
  117210. double *psy_noise_compand_long_mapping;
  117211. int *psy_noise_normal_start[2];
  117212. int *psy_noise_normal_partition[2];
  117213. double *psy_noise_normal_thresh;
  117214. int *psy_ath_float;
  117215. int *psy_ath_abs;
  117216. double *psy_lowpass;
  117217. vorbis_info_psy_global *global_params;
  117218. double *global_mapping;
  117219. adj_stereo *stereo_modes;
  117220. static_codebook ***floor_books;
  117221. vorbis_info_floor1 *floor_params;
  117222. int *floor_short_mapping;
  117223. int *floor_long_mapping;
  117224. vorbis_mapping_template *maps;
  117225. } ve_setup_data_template;
  117226. /* a few static coder conventions */
  117227. static vorbis_info_mode _mode_template[2]={
  117228. {0,0,0,0},
  117229. {1,0,0,1}
  117230. };
  117231. static vorbis_info_mapping0 _map_nominal[2]={
  117232. {1, {0,0}, {0}, {0}, 1,{0},{1}},
  117233. {1, {0,0}, {1}, {1}, 1,{0},{1}}
  117234. };
  117235. /*** Start of inlined file: setup_44.h ***/
  117236. /*** Start of inlined file: floor_all.h ***/
  117237. /*** Start of inlined file: floor_books.h ***/
  117238. static long _huff_lengthlist_line_256x7_0sub1[] = {
  117239. 0, 2, 3, 3, 3, 3, 4, 3, 4,
  117240. };
  117241. static static_codebook _huff_book_line_256x7_0sub1 = {
  117242. 1, 9,
  117243. _huff_lengthlist_line_256x7_0sub1,
  117244. 0, 0, 0, 0, 0,
  117245. NULL,
  117246. NULL,
  117247. NULL,
  117248. NULL,
  117249. 0
  117250. };
  117251. static long _huff_lengthlist_line_256x7_0sub2[] = {
  117252. 0, 0, 0, 0, 0, 0, 0, 0, 0, 3, 4, 3, 4, 3, 5, 3,
  117253. 6, 3, 6, 4, 6, 4, 7, 5, 7,
  117254. };
  117255. static static_codebook _huff_book_line_256x7_0sub2 = {
  117256. 1, 25,
  117257. _huff_lengthlist_line_256x7_0sub2,
  117258. 0, 0, 0, 0, 0,
  117259. NULL,
  117260. NULL,
  117261. NULL,
  117262. NULL,
  117263. 0
  117264. };
  117265. static long _huff_lengthlist_line_256x7_0sub3[] = {
  117266. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  117267. 0, 0, 0, 0, 0, 0, 0, 0, 0, 3, 5, 2, 5, 3, 5, 3,
  117268. 6, 3, 6, 4, 7, 6, 7, 8, 7, 9, 8, 9, 9, 9,10, 9,
  117269. 11,13,11,13,10,10,13,13,13,13,13,13,12,12,12,12,
  117270. };
  117271. static static_codebook _huff_book_line_256x7_0sub3 = {
  117272. 1, 64,
  117273. _huff_lengthlist_line_256x7_0sub3,
  117274. 0, 0, 0, 0, 0,
  117275. NULL,
  117276. NULL,
  117277. NULL,
  117278. NULL,
  117279. 0
  117280. };
  117281. static long _huff_lengthlist_line_256x7_1sub1[] = {
  117282. 0, 3, 3, 3, 3, 2, 4, 3, 4,
  117283. };
  117284. static static_codebook _huff_book_line_256x7_1sub1 = {
  117285. 1, 9,
  117286. _huff_lengthlist_line_256x7_1sub1,
  117287. 0, 0, 0, 0, 0,
  117288. NULL,
  117289. NULL,
  117290. NULL,
  117291. NULL,
  117292. 0
  117293. };
  117294. static long _huff_lengthlist_line_256x7_1sub2[] = {
  117295. 0, 0, 0, 0, 0, 0, 0, 0, 0, 2, 3, 3, 4, 3, 4, 4,
  117296. 5, 4, 6, 5, 6, 7, 6, 8, 8,
  117297. };
  117298. static static_codebook _huff_book_line_256x7_1sub2 = {
  117299. 1, 25,
  117300. _huff_lengthlist_line_256x7_1sub2,
  117301. 0, 0, 0, 0, 0,
  117302. NULL,
  117303. NULL,
  117304. NULL,
  117305. NULL,
  117306. 0
  117307. };
  117308. static long _huff_lengthlist_line_256x7_1sub3[] = {
  117309. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  117310. 0, 0, 0, 0, 0, 0, 0, 0, 0, 3, 2, 4, 3, 6, 3, 7,
  117311. 3, 8, 5, 8, 6, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8,
  117312. 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 7,
  117313. };
  117314. static static_codebook _huff_book_line_256x7_1sub3 = {
  117315. 1, 64,
  117316. _huff_lengthlist_line_256x7_1sub3,
  117317. 0, 0, 0, 0, 0,
  117318. NULL,
  117319. NULL,
  117320. NULL,
  117321. NULL,
  117322. 0
  117323. };
  117324. static long _huff_lengthlist_line_256x7_class0[] = {
  117325. 7, 5, 5, 9, 9, 6, 6, 9,12, 8, 7, 8,11, 8, 9,15,
  117326. 6, 3, 3, 7, 7, 4, 3, 6, 9, 6, 5, 6, 8, 6, 8,15,
  117327. 8, 5, 5, 9, 8, 5, 4, 6,10, 7, 5, 5,11, 8, 7,15,
  117328. 14,15,13,13,13,13, 8,11,15,10, 7, 6,11, 9,10,15,
  117329. };
  117330. static static_codebook _huff_book_line_256x7_class0 = {
  117331. 1, 64,
  117332. _huff_lengthlist_line_256x7_class0,
  117333. 0, 0, 0, 0, 0,
  117334. NULL,
  117335. NULL,
  117336. NULL,
  117337. NULL,
  117338. 0
  117339. };
  117340. static long _huff_lengthlist_line_256x7_class1[] = {
  117341. 5, 6, 8,15, 6, 9,10,15,10,11,12,15,15,15,15,15,
  117342. 4, 6, 7,15, 6, 7, 8,15, 9, 8, 9,15,15,15,15,15,
  117343. 6, 8, 9,15, 7, 7, 8,15,10, 9,10,15,15,15,15,15,
  117344. 15,13,15,15,15,10,11,15,15,13,13,15,15,15,15,15,
  117345. 4, 6, 7,15, 6, 8, 9,15,10,10,12,15,15,15,15,15,
  117346. 2, 5, 6,15, 5, 6, 7,15, 8, 6, 7,15,15,15,15,15,
  117347. 5, 6, 8,15, 5, 6, 7,15, 9, 6, 7,15,15,15,15,15,
  117348. 14,12,13,15,12,10,11,15,15,15,15,15,15,15,15,15,
  117349. 7, 8, 9,15, 9,10,10,15,15,14,14,15,15,15,15,15,
  117350. 5, 6, 7,15, 7, 8, 9,15,12, 9,10,15,15,15,15,15,
  117351. 7, 7, 9,15, 7, 7, 8,15,12, 8, 9,15,15,15,15,15,
  117352. 13,13,14,15,12,11,12,15,15,15,15,15,15,15,15,15,
  117353. 15,15,15,15,15,15,15,15,15,15,15,15,15,15,15,15,
  117354. 13,13,13,15,15,15,15,15,15,15,15,15,15,15,15,15,
  117355. 15,12,13,15,15,12,13,15,15,14,15,15,15,15,15,15,
  117356. 15,15,15,15,15,15,13,15,15,15,15,15,15,15,15,15,
  117357. };
  117358. static static_codebook _huff_book_line_256x7_class1 = {
  117359. 1, 256,
  117360. _huff_lengthlist_line_256x7_class1,
  117361. 0, 0, 0, 0, 0,
  117362. NULL,
  117363. NULL,
  117364. NULL,
  117365. NULL,
  117366. 0
  117367. };
  117368. static long _huff_lengthlist_line_512x17_0sub0[] = {
  117369. 4, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5,
  117370. 5, 6, 5, 6, 6, 6, 6, 5, 6, 6, 7, 6, 7, 6, 7, 6,
  117371. 7, 6, 8, 7, 8, 7, 8, 7, 8, 7, 8, 7, 9, 7, 9, 7,
  117372. 9, 7, 9, 8, 9, 8,10, 8,10, 8,10, 7,10, 6,10, 8,
  117373. 10, 8,11, 7,10, 7,11, 8,11,11,12,12,11,11,12,11,
  117374. 13,11,13,11,13,12,15,12,13,13,14,14,14,14,14,15,
  117375. 15,15,16,14,17,19,19,18,18,18,18,18,18,18,18,18,
  117376. 18,18,18,18,18,18,18,18,18,18,18,18,18,18,18,18,
  117377. };
  117378. static static_codebook _huff_book_line_512x17_0sub0 = {
  117379. 1, 128,
  117380. _huff_lengthlist_line_512x17_0sub0,
  117381. 0, 0, 0, 0, 0,
  117382. NULL,
  117383. NULL,
  117384. NULL,
  117385. NULL,
  117386. 0
  117387. };
  117388. static long _huff_lengthlist_line_512x17_1sub0[] = {
  117389. 2, 4, 5, 4, 5, 4, 5, 4, 5, 5, 5, 5, 5, 5, 6, 5,
  117390. 6, 5, 6, 6, 7, 6, 7, 6, 8, 7, 8, 7, 8, 7, 8, 7,
  117391. };
  117392. static static_codebook _huff_book_line_512x17_1sub0 = {
  117393. 1, 32,
  117394. _huff_lengthlist_line_512x17_1sub0,
  117395. 0, 0, 0, 0, 0,
  117396. NULL,
  117397. NULL,
  117398. NULL,
  117399. NULL,
  117400. 0
  117401. };
  117402. static long _huff_lengthlist_line_512x17_1sub1[] = {
  117403. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  117404. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  117405. 4, 3, 5, 3, 5, 4, 5, 4, 5, 4, 5, 5, 5, 5, 6, 5,
  117406. 6, 5, 7, 5, 8, 6, 8, 6, 8, 6, 8, 6, 8, 7, 9, 7,
  117407. 9, 7,11, 9,11,11,12,11,14,12,14,16,14,16,13,16,
  117408. 14,16,12,15,13,16,14,16,13,14,12,15,13,15,13,13,
  117409. 13,15,12,14,14,15,13,15,12,15,15,15,15,15,15,15,
  117410. 15,15,15,15,15,15,15,15,15,15,15,15,15,15,15,15,
  117411. };
  117412. static static_codebook _huff_book_line_512x17_1sub1 = {
  117413. 1, 128,
  117414. _huff_lengthlist_line_512x17_1sub1,
  117415. 0, 0, 0, 0, 0,
  117416. NULL,
  117417. NULL,
  117418. NULL,
  117419. NULL,
  117420. 0
  117421. };
  117422. static long _huff_lengthlist_line_512x17_2sub1[] = {
  117423. 0, 4, 5, 4, 4, 4, 5, 4, 4, 4, 5, 4, 5, 4, 5, 3,
  117424. 5, 3,
  117425. };
  117426. static static_codebook _huff_book_line_512x17_2sub1 = {
  117427. 1, 18,
  117428. _huff_lengthlist_line_512x17_2sub1,
  117429. 0, 0, 0, 0, 0,
  117430. NULL,
  117431. NULL,
  117432. NULL,
  117433. NULL,
  117434. 0
  117435. };
  117436. static long _huff_lengthlist_line_512x17_2sub2[] = {
  117437. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  117438. 0, 0, 4, 3, 4, 3, 4, 4, 5, 4, 5, 4, 6, 4, 6, 5,
  117439. 6, 5, 7, 5, 7, 6, 8, 6, 8, 6, 8, 7, 8, 7, 9, 7,
  117440. 9, 8,
  117441. };
  117442. static static_codebook _huff_book_line_512x17_2sub2 = {
  117443. 1, 50,
  117444. _huff_lengthlist_line_512x17_2sub2,
  117445. 0, 0, 0, 0, 0,
  117446. NULL,
  117447. NULL,
  117448. NULL,
  117449. NULL,
  117450. 0
  117451. };
  117452. static long _huff_lengthlist_line_512x17_2sub3[] = {
  117453. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  117454. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  117455. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  117456. 0, 0, 3, 3, 3, 3, 4, 3, 4, 4, 5, 5, 6, 6, 7, 7,
  117457. 7, 8, 8,11, 8, 9, 9, 9,10,11,11,11, 9,10,10,11,
  117458. 11,11,11,10,10,10,10,10,10,10,10,10,10,10,10,10,
  117459. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  117460. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  117461. };
  117462. static static_codebook _huff_book_line_512x17_2sub3 = {
  117463. 1, 128,
  117464. _huff_lengthlist_line_512x17_2sub3,
  117465. 0, 0, 0, 0, 0,
  117466. NULL,
  117467. NULL,
  117468. NULL,
  117469. NULL,
  117470. 0
  117471. };
  117472. static long _huff_lengthlist_line_512x17_3sub1[] = {
  117473. 0, 4, 4, 4, 4, 4, 4, 3, 4, 4, 4, 4, 4, 5, 4, 5,
  117474. 5, 5,
  117475. };
  117476. static static_codebook _huff_book_line_512x17_3sub1 = {
  117477. 1, 18,
  117478. _huff_lengthlist_line_512x17_3sub1,
  117479. 0, 0, 0, 0, 0,
  117480. NULL,
  117481. NULL,
  117482. NULL,
  117483. NULL,
  117484. 0
  117485. };
  117486. static long _huff_lengthlist_line_512x17_3sub2[] = {
  117487. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  117488. 0, 0, 2, 3, 3, 4, 3, 5, 4, 6, 4, 6, 5, 7, 6, 7,
  117489. 6, 8, 6, 8, 7, 9, 8,10, 8,12, 9,13,10,15,10,15,
  117490. 11,14,
  117491. };
  117492. static static_codebook _huff_book_line_512x17_3sub2 = {
  117493. 1, 50,
  117494. _huff_lengthlist_line_512x17_3sub2,
  117495. 0, 0, 0, 0, 0,
  117496. NULL,
  117497. NULL,
  117498. NULL,
  117499. NULL,
  117500. 0
  117501. };
  117502. static long _huff_lengthlist_line_512x17_3sub3[] = {
  117503. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  117504. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  117505. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  117506. 0, 0, 4, 8, 4, 8, 4, 8, 4, 8, 5, 8, 5, 8, 6, 8,
  117507. 4, 8, 4, 8, 5, 8, 5, 7, 7, 7, 7, 7, 7, 7, 7, 7,
  117508. 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7,
  117509. 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7,
  117510. 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7,
  117511. };
  117512. static static_codebook _huff_book_line_512x17_3sub3 = {
  117513. 1, 128,
  117514. _huff_lengthlist_line_512x17_3sub3,
  117515. 0, 0, 0, 0, 0,
  117516. NULL,
  117517. NULL,
  117518. NULL,
  117519. NULL,
  117520. 0
  117521. };
  117522. static long _huff_lengthlist_line_512x17_class1[] = {
  117523. 1, 2, 3, 6, 5, 4, 7, 7,
  117524. };
  117525. static static_codebook _huff_book_line_512x17_class1 = {
  117526. 1, 8,
  117527. _huff_lengthlist_line_512x17_class1,
  117528. 0, 0, 0, 0, 0,
  117529. NULL,
  117530. NULL,
  117531. NULL,
  117532. NULL,
  117533. 0
  117534. };
  117535. static long _huff_lengthlist_line_512x17_class2[] = {
  117536. 3, 3, 3,14, 5, 4, 4,11, 8, 6, 6,10,17,12,11,17,
  117537. 6, 5, 5,15, 5, 3, 4,11, 8, 5, 5, 8,16, 9,10,14,
  117538. 10, 8, 9,17, 8, 6, 6,13,10, 7, 7,10,16,11,13,14,
  117539. 17,17,17,17,17,16,16,16,16,15,16,16,16,16,16,16,
  117540. };
  117541. static static_codebook _huff_book_line_512x17_class2 = {
  117542. 1, 64,
  117543. _huff_lengthlist_line_512x17_class2,
  117544. 0, 0, 0, 0, 0,
  117545. NULL,
  117546. NULL,
  117547. NULL,
  117548. NULL,
  117549. 0
  117550. };
  117551. static long _huff_lengthlist_line_512x17_class3[] = {
  117552. 2, 4, 6,17, 4, 5, 7,17, 8, 7,10,17,17,17,17,17,
  117553. 3, 4, 6,15, 3, 3, 6,15, 7, 6, 9,17,17,17,17,17,
  117554. 6, 8,10,17, 6, 6, 8,16, 9, 8,10,17,17,15,16,17,
  117555. 17,17,17,17,12,15,15,16,12,15,15,16,16,16,16,16,
  117556. };
  117557. static static_codebook _huff_book_line_512x17_class3 = {
  117558. 1, 64,
  117559. _huff_lengthlist_line_512x17_class3,
  117560. 0, 0, 0, 0, 0,
  117561. NULL,
  117562. NULL,
  117563. NULL,
  117564. NULL,
  117565. 0
  117566. };
  117567. static long _huff_lengthlist_line_128x4_class0[] = {
  117568. 7, 7, 7,11, 6, 6, 7,11, 7, 6, 6,10,12,10,10,13,
  117569. 7, 7, 8,11, 7, 7, 7,11, 7, 6, 7,10,11,10,10,13,
  117570. 10,10, 9,12, 9, 9, 9,11, 8, 8, 8,11,13,11,10,14,
  117571. 15,15,14,15,15,14,13,14,15,12,12,17,17,17,17,17,
  117572. 7, 7, 6, 9, 6, 6, 6, 9, 7, 6, 6, 8,11,11,10,12,
  117573. 7, 7, 7, 9, 7, 6, 6, 9, 7, 6, 6, 9,13,10,10,11,
  117574. 10, 9, 8,10, 9, 8, 8,10, 8, 8, 7, 9,13,12,10,11,
  117575. 17,14,14,13,15,14,12,13,17,13,12,15,17,17,14,17,
  117576. 7, 6, 6, 7, 6, 6, 5, 7, 6, 6, 6, 6,11, 9, 9, 9,
  117577. 7, 7, 6, 7, 7, 6, 6, 7, 6, 6, 6, 6,10, 9, 8, 9,
  117578. 10, 9, 8, 8, 9, 8, 7, 8, 8, 7, 6, 8,11,10, 9,10,
  117579. 17,17,12,15,15,15,12,14,14,14,10,12,15,13,12,13,
  117580. 11,10, 8,10,11,10, 8, 8,10, 9, 7, 7,10, 9, 9,11,
  117581. 11,11, 9,10,11,10, 8, 9,10, 8, 6, 8,10, 9, 9,11,
  117582. 14,13,10,12,12,11,10,10, 8, 7, 8,10,10,11,11,12,
  117583. 17,17,15,17,17,17,17,17,17,13,12,17,17,17,14,17,
  117584. };
  117585. static static_codebook _huff_book_line_128x4_class0 = {
  117586. 1, 256,
  117587. _huff_lengthlist_line_128x4_class0,
  117588. 0, 0, 0, 0, 0,
  117589. NULL,
  117590. NULL,
  117591. NULL,
  117592. NULL,
  117593. 0
  117594. };
  117595. static long _huff_lengthlist_line_128x4_0sub0[] = {
  117596. 2, 2, 2, 2,
  117597. };
  117598. static static_codebook _huff_book_line_128x4_0sub0 = {
  117599. 1, 4,
  117600. _huff_lengthlist_line_128x4_0sub0,
  117601. 0, 0, 0, 0, 0,
  117602. NULL,
  117603. NULL,
  117604. NULL,
  117605. NULL,
  117606. 0
  117607. };
  117608. static long _huff_lengthlist_line_128x4_0sub1[] = {
  117609. 0, 0, 0, 0, 3, 2, 3, 2, 3, 3,
  117610. };
  117611. static static_codebook _huff_book_line_128x4_0sub1 = {
  117612. 1, 10,
  117613. _huff_lengthlist_line_128x4_0sub1,
  117614. 0, 0, 0, 0, 0,
  117615. NULL,
  117616. NULL,
  117617. NULL,
  117618. NULL,
  117619. 0
  117620. };
  117621. static long _huff_lengthlist_line_128x4_0sub2[] = {
  117622. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 3, 3, 4, 3, 4, 3,
  117623. 4, 4, 5, 4, 5, 4, 6, 5, 6,
  117624. };
  117625. static static_codebook _huff_book_line_128x4_0sub2 = {
  117626. 1, 25,
  117627. _huff_lengthlist_line_128x4_0sub2,
  117628. 0, 0, 0, 0, 0,
  117629. NULL,
  117630. NULL,
  117631. NULL,
  117632. NULL,
  117633. 0
  117634. };
  117635. static long _huff_lengthlist_line_128x4_0sub3[] = {
  117636. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  117637. 0, 0, 0, 0, 0, 0, 0, 0, 0, 2, 4, 3, 5, 3, 5, 3,
  117638. 5, 4, 6, 5, 6, 5, 7, 6, 6, 7, 7, 9, 9,11,11,16,
  117639. 11,14,10,11,11,13,16,15,15,15,15,15,15,15,15,15,
  117640. };
  117641. static static_codebook _huff_book_line_128x4_0sub3 = {
  117642. 1, 64,
  117643. _huff_lengthlist_line_128x4_0sub3,
  117644. 0, 0, 0, 0, 0,
  117645. NULL,
  117646. NULL,
  117647. NULL,
  117648. NULL,
  117649. 0
  117650. };
  117651. static long _huff_lengthlist_line_256x4_class0[] = {
  117652. 6, 7, 7,12, 6, 6, 7,12, 7, 6, 6,10,15,12,11,13,
  117653. 7, 7, 8,13, 7, 7, 8,12, 7, 7, 7,11,12,12,11,13,
  117654. 10, 9, 9,11, 9, 9, 9,10,10, 8, 8,12,14,12,12,14,
  117655. 11,11,12,14,11,12,11,15,15,12,13,15,15,15,15,15,
  117656. 6, 6, 7,10, 6, 6, 6,11, 7, 6, 6, 9,14,12,11,13,
  117657. 7, 7, 7,10, 6, 6, 7, 9, 7, 7, 6,10,13,12,10,12,
  117658. 9, 9, 9,11, 9, 9, 8, 9, 9, 8, 8,10,13,12,10,12,
  117659. 12,12,11,13,12,12,11,12,15,13,12,15,15,15,14,14,
  117660. 6, 6, 6, 8, 6, 6, 5, 6, 7, 7, 6, 5,11,10, 9, 8,
  117661. 7, 6, 6, 7, 6, 6, 5, 6, 7, 7, 6, 6,11,10, 9, 8,
  117662. 8, 8, 8, 9, 8, 8, 7, 8, 8, 8, 6, 7,11,10, 9, 9,
  117663. 14,11,10,14,14,11,10,15,13,11, 9,11,15,12,12,11,
  117664. 11, 9, 8, 8,10, 9, 8, 9,11,10, 9, 8,12,11,12,11,
  117665. 13,10, 8, 9,11,10, 8, 9,10, 9, 8, 9,10, 8,12,12,
  117666. 15,11,10,10,13,11,10,10, 8, 8, 7,12,10, 9,11,12,
  117667. 15,12,11,15,13,11,11,15,12,14,11,13,15,15,13,13,
  117668. };
  117669. static static_codebook _huff_book_line_256x4_class0 = {
  117670. 1, 256,
  117671. _huff_lengthlist_line_256x4_class0,
  117672. 0, 0, 0, 0, 0,
  117673. NULL,
  117674. NULL,
  117675. NULL,
  117676. NULL,
  117677. 0
  117678. };
  117679. static long _huff_lengthlist_line_256x4_0sub0[] = {
  117680. 2, 2, 2, 2,
  117681. };
  117682. static static_codebook _huff_book_line_256x4_0sub0 = {
  117683. 1, 4,
  117684. _huff_lengthlist_line_256x4_0sub0,
  117685. 0, 0, 0, 0, 0,
  117686. NULL,
  117687. NULL,
  117688. NULL,
  117689. NULL,
  117690. 0
  117691. };
  117692. static long _huff_lengthlist_line_256x4_0sub1[] = {
  117693. 0, 0, 0, 0, 2, 2, 3, 3, 3, 3,
  117694. };
  117695. static static_codebook _huff_book_line_256x4_0sub1 = {
  117696. 1, 10,
  117697. _huff_lengthlist_line_256x4_0sub1,
  117698. 0, 0, 0, 0, 0,
  117699. NULL,
  117700. NULL,
  117701. NULL,
  117702. NULL,
  117703. 0
  117704. };
  117705. static long _huff_lengthlist_line_256x4_0sub2[] = {
  117706. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 4, 3, 4, 3, 4, 3,
  117707. 5, 3, 5, 4, 5, 4, 6, 4, 6,
  117708. };
  117709. static static_codebook _huff_book_line_256x4_0sub2 = {
  117710. 1, 25,
  117711. _huff_lengthlist_line_256x4_0sub2,
  117712. 0, 0, 0, 0, 0,
  117713. NULL,
  117714. NULL,
  117715. NULL,
  117716. NULL,
  117717. 0
  117718. };
  117719. static long _huff_lengthlist_line_256x4_0sub3[] = {
  117720. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  117721. 0, 0, 0, 0, 0, 0, 0, 0, 0, 2, 4, 3, 5, 3, 5, 3,
  117722. 6, 4, 7, 4, 7, 5, 7, 6, 7, 6, 7, 8,10,13,13,13,
  117723. 13,13,13,13,13,13,13,13,13,13,13,12,12,12,12,12,
  117724. };
  117725. static static_codebook _huff_book_line_256x4_0sub3 = {
  117726. 1, 64,
  117727. _huff_lengthlist_line_256x4_0sub3,
  117728. 0, 0, 0, 0, 0,
  117729. NULL,
  117730. NULL,
  117731. NULL,
  117732. NULL,
  117733. 0
  117734. };
  117735. static long _huff_lengthlist_line_128x7_class0[] = {
  117736. 10, 7, 8,13, 9, 6, 7,11,10, 8, 8,12,17,17,17,17,
  117737. 7, 5, 5, 9, 6, 4, 4, 8, 8, 5, 5, 8,16,14,13,16,
  117738. 7, 5, 5, 7, 6, 3, 3, 5, 8, 5, 4, 7,14,12,12,15,
  117739. 10, 7, 8, 9, 7, 5, 5, 6, 9, 6, 5, 5,15,12, 9,10,
  117740. };
  117741. static static_codebook _huff_book_line_128x7_class0 = {
  117742. 1, 64,
  117743. _huff_lengthlist_line_128x7_class0,
  117744. 0, 0, 0, 0, 0,
  117745. NULL,
  117746. NULL,
  117747. NULL,
  117748. NULL,
  117749. 0
  117750. };
  117751. static long _huff_lengthlist_line_128x7_class1[] = {
  117752. 8,13,17,17, 8,11,17,17,11,13,17,17,17,17,17,17,
  117753. 6,10,16,17, 6,10,15,17, 8,10,16,17,17,17,17,17,
  117754. 9,13,15,17, 8,11,17,17,10,12,17,17,17,17,17,17,
  117755. 17,17,17,17,17,17,17,17,17,17,17,17,17,17,17,17,
  117756. 6,11,15,17, 7,10,15,17, 8,10,17,17,17,15,17,17,
  117757. 4, 8,13,17, 4, 7,13,17, 6, 8,15,17,16,15,17,17,
  117758. 6,11,15,17, 6, 9,13,17, 8,10,17,17,15,17,17,17,
  117759. 16,17,17,17,12,14,15,17,13,14,15,17,17,17,17,17,
  117760. 5,10,14,17, 5, 9,14,17, 7, 9,15,17,15,15,17,17,
  117761. 3, 7,12,17, 3, 6,11,17, 5, 7,13,17,12,12,17,17,
  117762. 5, 9,14,17, 3, 7,11,17, 5, 8,13,17,13,11,16,17,
  117763. 12,17,17,17, 9,14,15,17,10,11,14,17,16,14,17,17,
  117764. 8,12,17,17, 8,12,17,17,10,12,17,17,17,17,17,17,
  117765. 5,10,17,17, 5, 9,15,17, 7, 9,17,17,13,13,17,17,
  117766. 7,11,17,17, 6,10,15,17, 7, 9,15,17,12,11,17,17,
  117767. 12,15,17,17,11,14,17,17,11,10,15,17,17,16,17,17,
  117768. };
  117769. static static_codebook _huff_book_line_128x7_class1 = {
  117770. 1, 256,
  117771. _huff_lengthlist_line_128x7_class1,
  117772. 0, 0, 0, 0, 0,
  117773. NULL,
  117774. NULL,
  117775. NULL,
  117776. NULL,
  117777. 0
  117778. };
  117779. static long _huff_lengthlist_line_128x7_0sub1[] = {
  117780. 0, 3, 3, 3, 3, 3, 3, 3, 3,
  117781. };
  117782. static static_codebook _huff_book_line_128x7_0sub1 = {
  117783. 1, 9,
  117784. _huff_lengthlist_line_128x7_0sub1,
  117785. 0, 0, 0, 0, 0,
  117786. NULL,
  117787. NULL,
  117788. NULL,
  117789. NULL,
  117790. 0
  117791. };
  117792. static long _huff_lengthlist_line_128x7_0sub2[] = {
  117793. 0, 0, 0, 0, 0, 0, 0, 0, 0, 3, 3, 3, 4, 4, 4, 4,
  117794. 5, 4, 5, 4, 5, 4, 6, 4, 6,
  117795. };
  117796. static static_codebook _huff_book_line_128x7_0sub2 = {
  117797. 1, 25,
  117798. _huff_lengthlist_line_128x7_0sub2,
  117799. 0, 0, 0, 0, 0,
  117800. NULL,
  117801. NULL,
  117802. NULL,
  117803. NULL,
  117804. 0
  117805. };
  117806. static long _huff_lengthlist_line_128x7_0sub3[] = {
  117807. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  117808. 0, 0, 0, 0, 0, 0, 0, 0, 0, 3, 5, 3, 5, 3, 5, 4,
  117809. 5, 4, 5, 5, 5, 5, 6, 5, 6, 5, 6, 5, 6, 5, 6, 5,
  117810. 7, 8, 9,11,13,13,13,13,13,13,13,13,13,13,13,13,
  117811. };
  117812. static static_codebook _huff_book_line_128x7_0sub3 = {
  117813. 1, 64,
  117814. _huff_lengthlist_line_128x7_0sub3,
  117815. 0, 0, 0, 0, 0,
  117816. NULL,
  117817. NULL,
  117818. NULL,
  117819. NULL,
  117820. 0
  117821. };
  117822. static long _huff_lengthlist_line_128x7_1sub1[] = {
  117823. 0, 3, 3, 2, 3, 3, 4, 3, 4,
  117824. };
  117825. static static_codebook _huff_book_line_128x7_1sub1 = {
  117826. 1, 9,
  117827. _huff_lengthlist_line_128x7_1sub1,
  117828. 0, 0, 0, 0, 0,
  117829. NULL,
  117830. NULL,
  117831. NULL,
  117832. NULL,
  117833. 0
  117834. };
  117835. static long _huff_lengthlist_line_128x7_1sub2[] = {
  117836. 0, 0, 0, 0, 0, 0, 0, 0, 0, 3, 4, 3, 6, 3, 6, 3,
  117837. 6, 3, 7, 3, 8, 4, 9, 4, 9,
  117838. };
  117839. static static_codebook _huff_book_line_128x7_1sub2 = {
  117840. 1, 25,
  117841. _huff_lengthlist_line_128x7_1sub2,
  117842. 0, 0, 0, 0, 0,
  117843. NULL,
  117844. NULL,
  117845. NULL,
  117846. NULL,
  117847. 0
  117848. };
  117849. static long _huff_lengthlist_line_128x7_1sub3[] = {
  117850. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  117851. 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 7, 2, 7, 3, 8, 4,
  117852. 9, 5, 9, 8,10,11,11,12,14,14,14,14,14,14,14,14,
  117853. 14,14,14,14,14,14,14,14,14,14,14,14,13,13,13,13,
  117854. };
  117855. static static_codebook _huff_book_line_128x7_1sub3 = {
  117856. 1, 64,
  117857. _huff_lengthlist_line_128x7_1sub3,
  117858. 0, 0, 0, 0, 0,
  117859. NULL,
  117860. NULL,
  117861. NULL,
  117862. NULL,
  117863. 0
  117864. };
  117865. static long _huff_lengthlist_line_128x11_class1[] = {
  117866. 1, 6, 3, 7, 2, 4, 5, 7,
  117867. };
  117868. static static_codebook _huff_book_line_128x11_class1 = {
  117869. 1, 8,
  117870. _huff_lengthlist_line_128x11_class1,
  117871. 0, 0, 0, 0, 0,
  117872. NULL,
  117873. NULL,
  117874. NULL,
  117875. NULL,
  117876. 0
  117877. };
  117878. static long _huff_lengthlist_line_128x11_class2[] = {
  117879. 1, 6,12,16, 4,12,15,16, 9,15,16,16,16,16,16,16,
  117880. 2, 5,11,16, 5,11,13,16, 9,13,16,16,16,16,16,16,
  117881. 4, 8,12,16, 5, 9,12,16, 9,13,15,16,16,16,16,16,
  117882. 15,16,16,16,11,14,13,16,12,15,16,16,16,16,16,15,
  117883. };
  117884. static static_codebook _huff_book_line_128x11_class2 = {
  117885. 1, 64,
  117886. _huff_lengthlist_line_128x11_class2,
  117887. 0, 0, 0, 0, 0,
  117888. NULL,
  117889. NULL,
  117890. NULL,
  117891. NULL,
  117892. 0
  117893. };
  117894. static long _huff_lengthlist_line_128x11_class3[] = {
  117895. 7, 6, 9,17, 7, 6, 8,17,12, 9,11,16,16,16,16,16,
  117896. 5, 4, 7,16, 5, 3, 6,14, 9, 6, 8,15,16,16,16,16,
  117897. 5, 4, 6,13, 3, 2, 4,11, 7, 4, 6,13,16,11,10,14,
  117898. 12,12,12,16, 9, 7,10,15,12, 9,11,16,16,15,15,16,
  117899. };
  117900. static static_codebook _huff_book_line_128x11_class3 = {
  117901. 1, 64,
  117902. _huff_lengthlist_line_128x11_class3,
  117903. 0, 0, 0, 0, 0,
  117904. NULL,
  117905. NULL,
  117906. NULL,
  117907. NULL,
  117908. 0
  117909. };
  117910. static long _huff_lengthlist_line_128x11_0sub0[] = {
  117911. 5, 5, 5, 5, 5, 5, 6, 5, 6, 5, 6, 5, 6, 5, 6, 5,
  117912. 6, 5, 6, 5, 6, 5, 6, 5, 6, 5, 6, 6, 6, 6, 7, 6,
  117913. 7, 6, 7, 6, 7, 6, 7, 6, 7, 6, 8, 6, 8, 6, 8, 7,
  117914. 8, 7, 8, 7, 8, 7, 9, 7, 9, 8, 9, 8, 9, 8,10, 8,
  117915. 10, 9,10, 9,10, 9,11, 9,11, 9,10,10,11,10,11,10,
  117916. 11,11,11,11,11,11,12,13,14,14,14,15,15,16,16,16,
  117917. 17,15,16,15,16,16,17,17,16,17,17,17,17,17,17,17,
  117918. 17,17,17,17,17,17,17,17,17,17,17,17,17,17,17,17,
  117919. };
  117920. static static_codebook _huff_book_line_128x11_0sub0 = {
  117921. 1, 128,
  117922. _huff_lengthlist_line_128x11_0sub0,
  117923. 0, 0, 0, 0, 0,
  117924. NULL,
  117925. NULL,
  117926. NULL,
  117927. NULL,
  117928. 0
  117929. };
  117930. static long _huff_lengthlist_line_128x11_1sub0[] = {
  117931. 2, 5, 5, 5, 5, 5, 5, 4, 5, 5, 5, 5, 5, 5, 5, 5,
  117932. 6, 5, 6, 5, 6, 5, 7, 6, 7, 6, 7, 6, 8, 6, 8, 6,
  117933. };
  117934. static static_codebook _huff_book_line_128x11_1sub0 = {
  117935. 1, 32,
  117936. _huff_lengthlist_line_128x11_1sub0,
  117937. 0, 0, 0, 0, 0,
  117938. NULL,
  117939. NULL,
  117940. NULL,
  117941. NULL,
  117942. 0
  117943. };
  117944. static long _huff_lengthlist_line_128x11_1sub1[] = {
  117945. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  117946. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  117947. 5, 3, 5, 3, 6, 4, 6, 4, 7, 4, 7, 4, 7, 4, 8, 4,
  117948. 8, 4, 9, 5, 9, 5, 9, 5, 9, 6,10, 6,10, 6,11, 7,
  117949. 10, 7,10, 8,11, 9,11, 9,11,10,11,11,12,11,11,12,
  117950. 15,15,12,14,11,14,12,14,11,14,13,14,12,14,11,14,
  117951. 11,14,12,14,11,14,11,14,13,13,14,14,14,14,14,14,
  117952. 14,14,14,14,14,14,14,14,14,14,14,14,14,14,14,14,
  117953. };
  117954. static static_codebook _huff_book_line_128x11_1sub1 = {
  117955. 1, 128,
  117956. _huff_lengthlist_line_128x11_1sub1,
  117957. 0, 0, 0, 0, 0,
  117958. NULL,
  117959. NULL,
  117960. NULL,
  117961. NULL,
  117962. 0
  117963. };
  117964. static long _huff_lengthlist_line_128x11_2sub1[] = {
  117965. 0, 4, 5, 4, 5, 4, 5, 3, 5, 3, 5, 3, 5, 4, 4, 4,
  117966. 5, 5,
  117967. };
  117968. static static_codebook _huff_book_line_128x11_2sub1 = {
  117969. 1, 18,
  117970. _huff_lengthlist_line_128x11_2sub1,
  117971. 0, 0, 0, 0, 0,
  117972. NULL,
  117973. NULL,
  117974. NULL,
  117975. NULL,
  117976. 0
  117977. };
  117978. static long _huff_lengthlist_line_128x11_2sub2[] = {
  117979. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  117980. 0, 0, 3, 3, 3, 4, 4, 4, 4, 5, 4, 5, 4, 6, 5, 7,
  117981. 5, 7, 6, 8, 6, 8, 6, 9, 7, 9, 7,10, 7, 9, 8,11,
  117982. 8,11,
  117983. };
  117984. static static_codebook _huff_book_line_128x11_2sub2 = {
  117985. 1, 50,
  117986. _huff_lengthlist_line_128x11_2sub2,
  117987. 0, 0, 0, 0, 0,
  117988. NULL,
  117989. NULL,
  117990. NULL,
  117991. NULL,
  117992. 0
  117993. };
  117994. static long _huff_lengthlist_line_128x11_2sub3[] = {
  117995. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  117996. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  117997. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  117998. 0, 0, 4, 8, 3, 8, 4, 8, 4, 8, 6, 8, 5, 8, 4, 8,
  117999. 4, 8, 6, 8, 7, 8, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7,
  118000. 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7,
  118001. 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7,
  118002. 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7,
  118003. };
  118004. static static_codebook _huff_book_line_128x11_2sub3 = {
  118005. 1, 128,
  118006. _huff_lengthlist_line_128x11_2sub3,
  118007. 0, 0, 0, 0, 0,
  118008. NULL,
  118009. NULL,
  118010. NULL,
  118011. NULL,
  118012. 0
  118013. };
  118014. static long _huff_lengthlist_line_128x11_3sub1[] = {
  118015. 0, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 5, 4,
  118016. 5, 4,
  118017. };
  118018. static static_codebook _huff_book_line_128x11_3sub1 = {
  118019. 1, 18,
  118020. _huff_lengthlist_line_128x11_3sub1,
  118021. 0, 0, 0, 0, 0,
  118022. NULL,
  118023. NULL,
  118024. NULL,
  118025. NULL,
  118026. 0
  118027. };
  118028. static long _huff_lengthlist_line_128x11_3sub2[] = {
  118029. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  118030. 0, 0, 5, 3, 5, 4, 6, 4, 6, 4, 7, 4, 7, 4, 8, 4,
  118031. 8, 4, 9, 4, 9, 4,10, 4,10, 5,10, 5,11, 5,12, 6,
  118032. 12, 6,
  118033. };
  118034. static static_codebook _huff_book_line_128x11_3sub2 = {
  118035. 1, 50,
  118036. _huff_lengthlist_line_128x11_3sub2,
  118037. 0, 0, 0, 0, 0,
  118038. NULL,
  118039. NULL,
  118040. NULL,
  118041. NULL,
  118042. 0
  118043. };
  118044. static long _huff_lengthlist_line_128x11_3sub3[] = {
  118045. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  118046. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  118047. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  118048. 0, 0, 7, 1, 6, 3, 7, 3, 8, 4, 8, 5, 8, 8, 8, 9,
  118049. 7, 8, 8, 7, 7, 7, 8, 9,10, 9, 9,10,10,10,10,10,
  118050. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  118051. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  118052. 10,10,10,10,10,10,10,10,10,10,10,10,10,10, 9, 9,
  118053. };
  118054. static static_codebook _huff_book_line_128x11_3sub3 = {
  118055. 1, 128,
  118056. _huff_lengthlist_line_128x11_3sub3,
  118057. 0, 0, 0, 0, 0,
  118058. NULL,
  118059. NULL,
  118060. NULL,
  118061. NULL,
  118062. 0
  118063. };
  118064. static long _huff_lengthlist_line_128x17_class1[] = {
  118065. 1, 3, 4, 7, 2, 5, 6, 7,
  118066. };
  118067. static static_codebook _huff_book_line_128x17_class1 = {
  118068. 1, 8,
  118069. _huff_lengthlist_line_128x17_class1,
  118070. 0, 0, 0, 0, 0,
  118071. NULL,
  118072. NULL,
  118073. NULL,
  118074. NULL,
  118075. 0
  118076. };
  118077. static long _huff_lengthlist_line_128x17_class2[] = {
  118078. 1, 4,10,19, 3, 8,13,19, 7,12,19,19,19,19,19,19,
  118079. 2, 6,11,19, 8,13,19,19, 9,11,19,19,19,19,19,19,
  118080. 6, 7,13,19, 9,13,19,19,10,13,18,18,18,18,18,18,
  118081. 18,18,18,18,18,18,18,18,18,18,18,18,18,18,18,18,
  118082. };
  118083. static static_codebook _huff_book_line_128x17_class2 = {
  118084. 1, 64,
  118085. _huff_lengthlist_line_128x17_class2,
  118086. 0, 0, 0, 0, 0,
  118087. NULL,
  118088. NULL,
  118089. NULL,
  118090. NULL,
  118091. 0
  118092. };
  118093. static long _huff_lengthlist_line_128x17_class3[] = {
  118094. 3, 6,10,17, 4, 8,11,20, 8,10,11,20,20,20,20,20,
  118095. 2, 4, 8,18, 4, 6, 8,17, 7, 8,10,20,20,17,20,20,
  118096. 3, 5, 8,17, 3, 4, 6,17, 8, 8,10,17,17,12,16,20,
  118097. 13,13,15,20,10,10,12,20,15,14,15,20,20,20,19,19,
  118098. };
  118099. static static_codebook _huff_book_line_128x17_class3 = {
  118100. 1, 64,
  118101. _huff_lengthlist_line_128x17_class3,
  118102. 0, 0, 0, 0, 0,
  118103. NULL,
  118104. NULL,
  118105. NULL,
  118106. NULL,
  118107. 0
  118108. };
  118109. static long _huff_lengthlist_line_128x17_0sub0[] = {
  118110. 5, 5, 6, 5, 6, 5, 6, 5, 6, 5, 6, 5, 6, 5, 6, 5,
  118111. 7, 5, 7, 5, 7, 5, 7, 5, 7, 5, 7, 5, 8, 5, 8, 5,
  118112. 8, 5, 8, 5, 8, 6, 8, 6, 8, 6, 9, 6, 9, 6, 9, 6,
  118113. 9, 6, 9, 7, 9, 7, 9, 7, 9, 7,10, 7,10, 8,10, 8,
  118114. 10, 8,10, 8,10, 8,11, 8,11, 8,11, 8,11, 8,11, 9,
  118115. 12, 9,12, 9,12, 9,12, 9,12,10,12,10,13,11,13,11,
  118116. 14,12,14,13,15,14,16,14,17,15,18,16,20,20,20,20,
  118117. 20,20,20,20,20,20,20,20,20,20,20,20,20,20,20,20,
  118118. };
  118119. static static_codebook _huff_book_line_128x17_0sub0 = {
  118120. 1, 128,
  118121. _huff_lengthlist_line_128x17_0sub0,
  118122. 0, 0, 0, 0, 0,
  118123. NULL,
  118124. NULL,
  118125. NULL,
  118126. NULL,
  118127. 0
  118128. };
  118129. static long _huff_lengthlist_line_128x17_1sub0[] = {
  118130. 2, 5, 5, 4, 5, 4, 5, 4, 5, 5, 5, 5, 5, 5, 6, 5,
  118131. 6, 5, 6, 5, 7, 6, 7, 6, 7, 6, 8, 6, 9, 7, 9, 7,
  118132. };
  118133. static static_codebook _huff_book_line_128x17_1sub0 = {
  118134. 1, 32,
  118135. _huff_lengthlist_line_128x17_1sub0,
  118136. 0, 0, 0, 0, 0,
  118137. NULL,
  118138. NULL,
  118139. NULL,
  118140. NULL,
  118141. 0
  118142. };
  118143. static long _huff_lengthlist_line_128x17_1sub1[] = {
  118144. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  118145. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  118146. 4, 3, 5, 3, 5, 3, 6, 3, 6, 4, 6, 4, 7, 4, 7, 5,
  118147. 8, 5, 8, 6, 9, 7, 9, 7, 9, 8,10, 9,10, 9,11,10,
  118148. 11,11,11,11,11,11,12,12,12,13,12,13,12,14,12,15,
  118149. 12,14,12,16,13,17,13,17,14,17,14,16,13,17,14,17,
  118150. 14,17,15,17,15,15,16,17,17,17,17,17,17,17,17,17,
  118151. 17,17,17,17,17,17,16,16,16,16,16,16,16,16,16,16,
  118152. };
  118153. static static_codebook _huff_book_line_128x17_1sub1 = {
  118154. 1, 128,
  118155. _huff_lengthlist_line_128x17_1sub1,
  118156. 0, 0, 0, 0, 0,
  118157. NULL,
  118158. NULL,
  118159. NULL,
  118160. NULL,
  118161. 0
  118162. };
  118163. static long _huff_lengthlist_line_128x17_2sub1[] = {
  118164. 0, 4, 5, 4, 6, 4, 8, 3, 9, 3, 9, 2, 9, 3, 8, 4,
  118165. 9, 4,
  118166. };
  118167. static static_codebook _huff_book_line_128x17_2sub1 = {
  118168. 1, 18,
  118169. _huff_lengthlist_line_128x17_2sub1,
  118170. 0, 0, 0, 0, 0,
  118171. NULL,
  118172. NULL,
  118173. NULL,
  118174. NULL,
  118175. 0
  118176. };
  118177. static long _huff_lengthlist_line_128x17_2sub2[] = {
  118178. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  118179. 0, 0, 5, 1, 5, 3, 5, 3, 5, 4, 7, 5,10, 7,10, 7,
  118180. 12,10,14,10,14, 9,14,11,14,14,14,13,13,13,13,13,
  118181. 13,13,
  118182. };
  118183. static static_codebook _huff_book_line_128x17_2sub2 = {
  118184. 1, 50,
  118185. _huff_lengthlist_line_128x17_2sub2,
  118186. 0, 0, 0, 0, 0,
  118187. NULL,
  118188. NULL,
  118189. NULL,
  118190. NULL,
  118191. 0
  118192. };
  118193. static long _huff_lengthlist_line_128x17_2sub3[] = {
  118194. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  118195. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  118196. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  118197. 0, 0, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7,
  118198. 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 6, 6,
  118199. 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6,
  118200. 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6,
  118201. 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6,
  118202. };
  118203. static static_codebook _huff_book_line_128x17_2sub3 = {
  118204. 1, 128,
  118205. _huff_lengthlist_line_128x17_2sub3,
  118206. 0, 0, 0, 0, 0,
  118207. NULL,
  118208. NULL,
  118209. NULL,
  118210. NULL,
  118211. 0
  118212. };
  118213. static long _huff_lengthlist_line_128x17_3sub1[] = {
  118214. 0, 4, 4, 4, 4, 4, 4, 4, 5, 3, 5, 3, 5, 4, 6, 4,
  118215. 6, 4,
  118216. };
  118217. static static_codebook _huff_book_line_128x17_3sub1 = {
  118218. 1, 18,
  118219. _huff_lengthlist_line_128x17_3sub1,
  118220. 0, 0, 0, 0, 0,
  118221. NULL,
  118222. NULL,
  118223. NULL,
  118224. NULL,
  118225. 0
  118226. };
  118227. static long _huff_lengthlist_line_128x17_3sub2[] = {
  118228. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  118229. 0, 0, 5, 3, 6, 3, 6, 4, 7, 4, 7, 4, 7, 4, 8, 4,
  118230. 8, 4, 8, 4, 8, 4, 9, 4, 9, 5,10, 5,10, 7,10, 8,
  118231. 10, 8,
  118232. };
  118233. static static_codebook _huff_book_line_128x17_3sub2 = {
  118234. 1, 50,
  118235. _huff_lengthlist_line_128x17_3sub2,
  118236. 0, 0, 0, 0, 0,
  118237. NULL,
  118238. NULL,
  118239. NULL,
  118240. NULL,
  118241. 0
  118242. };
  118243. static long _huff_lengthlist_line_128x17_3sub3[] = {
  118244. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  118245. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  118246. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  118247. 0, 0, 3, 2, 4, 3, 4, 4, 4, 5, 4, 7, 5, 8, 5,11,
  118248. 6,10, 6,12, 7,12, 7,12, 8,12, 8,12,10,12,12,12,
  118249. 12,12,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  118250. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  118251. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  118252. };
  118253. static static_codebook _huff_book_line_128x17_3sub3 = {
  118254. 1, 128,
  118255. _huff_lengthlist_line_128x17_3sub3,
  118256. 0, 0, 0, 0, 0,
  118257. NULL,
  118258. NULL,
  118259. NULL,
  118260. NULL,
  118261. 0
  118262. };
  118263. static long _huff_lengthlist_line_1024x27_class1[] = {
  118264. 2,10, 8,14, 7,12,11,14, 1, 5, 3, 7, 4, 9, 7,13,
  118265. };
  118266. static static_codebook _huff_book_line_1024x27_class1 = {
  118267. 1, 16,
  118268. _huff_lengthlist_line_1024x27_class1,
  118269. 0, 0, 0, 0, 0,
  118270. NULL,
  118271. NULL,
  118272. NULL,
  118273. NULL,
  118274. 0
  118275. };
  118276. static long _huff_lengthlist_line_1024x27_class2[] = {
  118277. 1, 4, 2, 6, 3, 7, 5, 7,
  118278. };
  118279. static static_codebook _huff_book_line_1024x27_class2 = {
  118280. 1, 8,
  118281. _huff_lengthlist_line_1024x27_class2,
  118282. 0, 0, 0, 0, 0,
  118283. NULL,
  118284. NULL,
  118285. NULL,
  118286. NULL,
  118287. 0
  118288. };
  118289. static long _huff_lengthlist_line_1024x27_class3[] = {
  118290. 1, 5, 7,21, 5, 8, 9,21,10, 9,12,20,20,16,20,20,
  118291. 4, 8, 9,20, 6, 8, 9,20,11,11,13,20,20,15,17,20,
  118292. 9,11,14,20, 8,10,15,20,11,13,15,20,20,20,20,20,
  118293. 20,20,20,20,13,20,20,20,18,18,20,20,20,20,20,20,
  118294. 3, 6, 8,20, 6, 7, 9,20,10, 9,12,20,20,20,20,20,
  118295. 5, 7, 9,20, 6, 6, 9,20,10, 9,12,20,20,20,20,20,
  118296. 8,10,13,20, 8, 9,12,20,11,10,12,20,20,20,20,20,
  118297. 18,20,20,20,15,17,18,20,18,17,18,20,20,20,20,20,
  118298. 7,10,12,20, 8, 9,11,20,14,13,14,20,20,20,20,20,
  118299. 6, 9,12,20, 7, 8,11,20,12,11,13,20,20,20,20,20,
  118300. 9,11,15,20, 8,10,14,20,12,11,14,20,20,20,20,20,
  118301. 20,20,20,20,20,20,20,20,20,20,20,20,20,20,20,20,
  118302. 11,16,18,20,15,15,17,20,20,17,20,20,20,20,20,20,
  118303. 9,14,16,20,12,12,15,20,17,15,18,20,20,20,20,20,
  118304. 16,19,18,20,15,16,20,20,17,17,20,20,20,20,20,20,
  118305. 20,20,20,20,20,20,20,20,20,20,20,20,20,20,20,20,
  118306. };
  118307. static static_codebook _huff_book_line_1024x27_class3 = {
  118308. 1, 256,
  118309. _huff_lengthlist_line_1024x27_class3,
  118310. 0, 0, 0, 0, 0,
  118311. NULL,
  118312. NULL,
  118313. NULL,
  118314. NULL,
  118315. 0
  118316. };
  118317. static long _huff_lengthlist_line_1024x27_class4[] = {
  118318. 2, 3, 7,13, 4, 4, 7,15, 8, 6, 9,17,21,16,15,21,
  118319. 2, 5, 7,11, 5, 5, 7,14, 9, 7,10,16,17,15,16,21,
  118320. 4, 7,10,17, 7, 7, 9,15,11, 9,11,16,21,18,15,21,
  118321. 18,21,21,21,15,17,17,19,21,19,18,20,21,21,21,20,
  118322. };
  118323. static static_codebook _huff_book_line_1024x27_class4 = {
  118324. 1, 64,
  118325. _huff_lengthlist_line_1024x27_class4,
  118326. 0, 0, 0, 0, 0,
  118327. NULL,
  118328. NULL,
  118329. NULL,
  118330. NULL,
  118331. 0
  118332. };
  118333. static long _huff_lengthlist_line_1024x27_0sub0[] = {
  118334. 5, 5, 5, 5, 6, 5, 6, 5, 6, 5, 6, 5, 6, 5, 6, 5,
  118335. 6, 5, 6, 5, 6, 5, 6, 5, 7, 5, 7, 5, 7, 5, 7, 5,
  118336. 8, 6, 8, 6, 8, 6, 9, 6, 9, 6,10, 6,10, 6,11, 6,
  118337. 11, 7,11, 7,12, 7,12, 7,12, 7,12, 7,12, 7,12, 7,
  118338. 12, 7,12, 8,13, 8,12, 8,12, 8,13, 8,13, 9,13, 9,
  118339. 13, 9,13, 9,12,10,12,10,13,10,14,11,14,12,14,13,
  118340. 14,13,14,14,15,16,15,15,15,14,15,17,21,22,22,21,
  118341. 22,22,22,22,22,22,21,21,21,21,21,21,21,21,21,21,
  118342. };
  118343. static static_codebook _huff_book_line_1024x27_0sub0 = {
  118344. 1, 128,
  118345. _huff_lengthlist_line_1024x27_0sub0,
  118346. 0, 0, 0, 0, 0,
  118347. NULL,
  118348. NULL,
  118349. NULL,
  118350. NULL,
  118351. 0
  118352. };
  118353. static long _huff_lengthlist_line_1024x27_1sub0[] = {
  118354. 2, 5, 5, 4, 5, 4, 5, 4, 5, 4, 6, 5, 6, 5, 6, 5,
  118355. 6, 5, 7, 5, 7, 6, 8, 6, 8, 6, 8, 6, 9, 6, 9, 6,
  118356. };
  118357. static static_codebook _huff_book_line_1024x27_1sub0 = {
  118358. 1, 32,
  118359. _huff_lengthlist_line_1024x27_1sub0,
  118360. 0, 0, 0, 0, 0,
  118361. NULL,
  118362. NULL,
  118363. NULL,
  118364. NULL,
  118365. 0
  118366. };
  118367. static long _huff_lengthlist_line_1024x27_1sub1[] = {
  118368. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  118369. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  118370. 8, 5, 8, 4, 9, 4, 9, 4, 9, 4, 9, 4, 9, 4, 9, 4,
  118371. 9, 4, 9, 4, 9, 4, 8, 4, 8, 4, 9, 5, 9, 5, 9, 5,
  118372. 9, 5, 9, 6,10, 6,10, 7,10, 8,11, 9,11,11,12,13,
  118373. 12,14,13,15,13,15,14,16,14,17,15,17,15,15,16,16,
  118374. 15,16,16,16,15,18,16,15,17,17,19,19,19,19,19,19,
  118375. 19,19,19,19,19,19,19,19,19,19,19,19,19,19,19,19,
  118376. };
  118377. static static_codebook _huff_book_line_1024x27_1sub1 = {
  118378. 1, 128,
  118379. _huff_lengthlist_line_1024x27_1sub1,
  118380. 0, 0, 0, 0, 0,
  118381. NULL,
  118382. NULL,
  118383. NULL,
  118384. NULL,
  118385. 0
  118386. };
  118387. static long _huff_lengthlist_line_1024x27_2sub0[] = {
  118388. 1, 5, 5, 5, 5, 5, 5, 5, 6, 5, 6, 5, 6, 5, 6, 5,
  118389. 6, 6, 7, 7, 7, 7, 8, 7, 8, 8, 9, 8,10, 9,10, 9,
  118390. };
  118391. static static_codebook _huff_book_line_1024x27_2sub0 = {
  118392. 1, 32,
  118393. _huff_lengthlist_line_1024x27_2sub0,
  118394. 0, 0, 0, 0, 0,
  118395. NULL,
  118396. NULL,
  118397. NULL,
  118398. NULL,
  118399. 0
  118400. };
  118401. static long _huff_lengthlist_line_1024x27_2sub1[] = {
  118402. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  118403. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  118404. 4, 3, 4, 3, 4, 4, 5, 4, 5, 4, 5, 5, 6, 5, 6, 5,
  118405. 7, 5, 7, 6, 7, 6, 8, 7, 8, 7, 8, 7, 9, 8, 9, 9,
  118406. 9, 9,10,10,10,11, 9,12, 9,12, 9,15,10,14, 9,13,
  118407. 10,13,10,12,10,12,10,13,10,12,11,13,11,14,12,13,
  118408. 13,14,14,13,14,15,14,16,13,13,14,16,16,16,16,16,
  118409. 16,16,16,16,16,16,16,16,16,16,16,16,16,16,15,15,
  118410. };
  118411. static static_codebook _huff_book_line_1024x27_2sub1 = {
  118412. 1, 128,
  118413. _huff_lengthlist_line_1024x27_2sub1,
  118414. 0, 0, 0, 0, 0,
  118415. NULL,
  118416. NULL,
  118417. NULL,
  118418. NULL,
  118419. 0
  118420. };
  118421. static long _huff_lengthlist_line_1024x27_3sub1[] = {
  118422. 0, 4, 5, 4, 5, 3, 5, 3, 5, 3, 5, 4, 4, 4, 4, 5,
  118423. 5, 5,
  118424. };
  118425. static static_codebook _huff_book_line_1024x27_3sub1 = {
  118426. 1, 18,
  118427. _huff_lengthlist_line_1024x27_3sub1,
  118428. 0, 0, 0, 0, 0,
  118429. NULL,
  118430. NULL,
  118431. NULL,
  118432. NULL,
  118433. 0
  118434. };
  118435. static long _huff_lengthlist_line_1024x27_3sub2[] = {
  118436. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  118437. 0, 0, 3, 3, 4, 3, 4, 4, 4, 4, 5, 5, 5, 5, 5, 6,
  118438. 5, 7, 5, 8, 6, 8, 6, 9, 7,10, 7,10, 8,10, 8,11,
  118439. 9,11,
  118440. };
  118441. static static_codebook _huff_book_line_1024x27_3sub2 = {
  118442. 1, 50,
  118443. _huff_lengthlist_line_1024x27_3sub2,
  118444. 0, 0, 0, 0, 0,
  118445. NULL,
  118446. NULL,
  118447. NULL,
  118448. NULL,
  118449. 0
  118450. };
  118451. static long _huff_lengthlist_line_1024x27_3sub3[] = {
  118452. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  118453. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  118454. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  118455. 0, 0, 3, 7, 3, 8, 3,10, 3, 8, 3, 9, 3, 8, 4, 9,
  118456. 4, 9, 5, 9, 6,10, 6, 9, 7,11, 7,12, 9,13,10,13,
  118457. 12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,
  118458. 12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,
  118459. 12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,
  118460. };
  118461. static static_codebook _huff_book_line_1024x27_3sub3 = {
  118462. 1, 128,
  118463. _huff_lengthlist_line_1024x27_3sub3,
  118464. 0, 0, 0, 0, 0,
  118465. NULL,
  118466. NULL,
  118467. NULL,
  118468. NULL,
  118469. 0
  118470. };
  118471. static long _huff_lengthlist_line_1024x27_4sub1[] = {
  118472. 0, 4, 5, 4, 5, 4, 5, 4, 5, 3, 5, 3, 5, 3, 5, 4,
  118473. 5, 4,
  118474. };
  118475. static static_codebook _huff_book_line_1024x27_4sub1 = {
  118476. 1, 18,
  118477. _huff_lengthlist_line_1024x27_4sub1,
  118478. 0, 0, 0, 0, 0,
  118479. NULL,
  118480. NULL,
  118481. NULL,
  118482. NULL,
  118483. 0
  118484. };
  118485. static long _huff_lengthlist_line_1024x27_4sub2[] = {
  118486. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  118487. 0, 0, 4, 2, 4, 2, 5, 3, 5, 4, 6, 6, 6, 7, 7, 8,
  118488. 7, 8, 7, 8, 7, 9, 8, 9, 8, 9, 8,10, 8,11, 9,12,
  118489. 9,12,
  118490. };
  118491. static static_codebook _huff_book_line_1024x27_4sub2 = {
  118492. 1, 50,
  118493. _huff_lengthlist_line_1024x27_4sub2,
  118494. 0, 0, 0, 0, 0,
  118495. NULL,
  118496. NULL,
  118497. NULL,
  118498. NULL,
  118499. 0
  118500. };
  118501. static long _huff_lengthlist_line_1024x27_4sub3[] = {
  118502. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  118503. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  118504. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  118505. 0, 0, 2, 5, 2, 6, 3, 6, 4, 7, 4, 7, 5, 9, 5,11,
  118506. 6,11, 6,11, 7,11, 6,11, 6,11, 9,11, 8,11,11,11,
  118507. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  118508. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  118509. 11,11,11,11,11,11,11,11,11,11,10,10,10,10,10,10,
  118510. };
  118511. static static_codebook _huff_book_line_1024x27_4sub3 = {
  118512. 1, 128,
  118513. _huff_lengthlist_line_1024x27_4sub3,
  118514. 0, 0, 0, 0, 0,
  118515. NULL,
  118516. NULL,
  118517. NULL,
  118518. NULL,
  118519. 0
  118520. };
  118521. static long _huff_lengthlist_line_2048x27_class1[] = {
  118522. 2, 6, 8, 9, 7,11,13,13, 1, 3, 5, 5, 6, 6,12,10,
  118523. };
  118524. static static_codebook _huff_book_line_2048x27_class1 = {
  118525. 1, 16,
  118526. _huff_lengthlist_line_2048x27_class1,
  118527. 0, 0, 0, 0, 0,
  118528. NULL,
  118529. NULL,
  118530. NULL,
  118531. NULL,
  118532. 0
  118533. };
  118534. static long _huff_lengthlist_line_2048x27_class2[] = {
  118535. 1, 2, 3, 6, 4, 7, 5, 7,
  118536. };
  118537. static static_codebook _huff_book_line_2048x27_class2 = {
  118538. 1, 8,
  118539. _huff_lengthlist_line_2048x27_class2,
  118540. 0, 0, 0, 0, 0,
  118541. NULL,
  118542. NULL,
  118543. NULL,
  118544. NULL,
  118545. 0
  118546. };
  118547. static long _huff_lengthlist_line_2048x27_class3[] = {
  118548. 3, 3, 6,16, 5, 5, 7,16, 9, 8,11,16,16,16,16,16,
  118549. 5, 5, 8,16, 5, 5, 7,16, 8, 7, 9,16,16,16,16,16,
  118550. 9, 9,12,16, 6, 8,11,16, 9,10,11,16,16,16,16,16,
  118551. 16,16,16,16,13,16,16,16,15,16,16,16,16,16,16,16,
  118552. 5, 4, 7,16, 6, 5, 8,16, 9, 8,10,16,16,16,16,16,
  118553. 5, 5, 7,15, 5, 4, 6,15, 7, 6, 8,16,16,16,16,16,
  118554. 9, 9,11,15, 7, 7, 9,16, 8, 8, 9,16,16,16,16,16,
  118555. 16,16,16,16,15,15,15,16,15,15,14,16,16,16,16,16,
  118556. 8, 8,11,16, 8, 9,10,16,11,10,14,16,16,16,16,16,
  118557. 6, 8,10,16, 6, 7,10,16, 8, 8,11,16,14,16,16,16,
  118558. 10,11,14,16, 9, 9,11,16,10,10,11,16,16,16,16,16,
  118559. 16,16,16,16,16,16,16,16,16,16,16,16,16,16,16,16,
  118560. 16,16,16,16,15,16,16,16,16,16,16,16,16,16,16,16,
  118561. 12,16,15,16,12,14,16,16,16,16,16,16,16,16,16,16,
  118562. 16,16,16,16,16,16,16,16,16,16,16,16,16,16,16,16,
  118563. 16,16,16,16,16,16,16,16,16,16,16,16,16,16,16,16,
  118564. };
  118565. static static_codebook _huff_book_line_2048x27_class3 = {
  118566. 1, 256,
  118567. _huff_lengthlist_line_2048x27_class3,
  118568. 0, 0, 0, 0, 0,
  118569. NULL,
  118570. NULL,
  118571. NULL,
  118572. NULL,
  118573. 0
  118574. };
  118575. static long _huff_lengthlist_line_2048x27_class4[] = {
  118576. 2, 4, 7,13, 4, 5, 7,15, 8, 7,10,16,16,14,16,16,
  118577. 2, 4, 7,16, 3, 4, 7,14, 8, 8,10,16,16,16,15,16,
  118578. 6, 8,11,16, 7, 7, 9,16,11, 9,13,16,16,16,15,16,
  118579. 16,16,16,16,14,16,16,16,16,16,16,16,16,16,16,16,
  118580. };
  118581. static static_codebook _huff_book_line_2048x27_class4 = {
  118582. 1, 64,
  118583. _huff_lengthlist_line_2048x27_class4,
  118584. 0, 0, 0, 0, 0,
  118585. NULL,
  118586. NULL,
  118587. NULL,
  118588. NULL,
  118589. 0
  118590. };
  118591. static long _huff_lengthlist_line_2048x27_0sub0[] = {
  118592. 5, 5, 5, 5, 5, 5, 6, 5, 6, 5, 6, 5, 6, 5, 6, 5,
  118593. 6, 5, 7, 5, 7, 5, 7, 5, 8, 5, 8, 5, 8, 5, 9, 5,
  118594. 9, 6,10, 6,10, 6,11, 6,11, 6,11, 6,11, 6,11, 6,
  118595. 11, 6,11, 6,12, 7,11, 7,11, 7,11, 7,11, 7,10, 7,
  118596. 11, 7,11, 7,12, 7,11, 8,11, 8,11, 8,11, 8,13, 8,
  118597. 12, 9,11, 9,11, 9,11,10,12,10,12, 9,12,10,12,11,
  118598. 14,12,16,12,12,11,14,16,17,17,17,17,17,17,17,17,
  118599. 17,17,17,17,17,17,17,17,17,17,17,17,16,16,16,16,
  118600. };
  118601. static static_codebook _huff_book_line_2048x27_0sub0 = {
  118602. 1, 128,
  118603. _huff_lengthlist_line_2048x27_0sub0,
  118604. 0, 0, 0, 0, 0,
  118605. NULL,
  118606. NULL,
  118607. NULL,
  118608. NULL,
  118609. 0
  118610. };
  118611. static long _huff_lengthlist_line_2048x27_1sub0[] = {
  118612. 4, 4, 4, 4, 4, 4, 4, 4, 5, 5, 5, 5, 5, 5, 5, 5,
  118613. 5, 5, 6, 6, 6, 6, 6, 6, 7, 6, 7, 6, 7, 6, 7, 6,
  118614. };
  118615. static static_codebook _huff_book_line_2048x27_1sub0 = {
  118616. 1, 32,
  118617. _huff_lengthlist_line_2048x27_1sub0,
  118618. 0, 0, 0, 0, 0,
  118619. NULL,
  118620. NULL,
  118621. NULL,
  118622. NULL,
  118623. 0
  118624. };
  118625. static long _huff_lengthlist_line_2048x27_1sub1[] = {
  118626. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  118627. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  118628. 6, 5, 7, 5, 7, 4, 7, 4, 8, 4, 8, 4, 8, 4, 8, 3,
  118629. 8, 4, 9, 4, 9, 4, 9, 4, 9, 4, 9, 5, 9, 5, 9, 6,
  118630. 9, 7, 9, 8, 9, 9, 9,10, 9,11, 9,14, 9,15,10,15,
  118631. 10,15,10,15,10,15,11,15,10,14,12,14,11,14,13,14,
  118632. 13,15,15,15,12,15,15,15,13,15,13,15,13,15,15,15,
  118633. 15,15,15,15,15,15,15,15,15,15,15,15,15,15,15,14,
  118634. };
  118635. static static_codebook _huff_book_line_2048x27_1sub1 = {
  118636. 1, 128,
  118637. _huff_lengthlist_line_2048x27_1sub1,
  118638. 0, 0, 0, 0, 0,
  118639. NULL,
  118640. NULL,
  118641. NULL,
  118642. NULL,
  118643. 0
  118644. };
  118645. static long _huff_lengthlist_line_2048x27_2sub0[] = {
  118646. 2, 4, 5, 4, 5, 4, 5, 4, 5, 5, 5, 5, 5, 5, 6, 5,
  118647. 6, 5, 6, 6, 6, 6, 7, 7, 7, 7, 7, 7, 8, 8, 8, 8,
  118648. };
  118649. static static_codebook _huff_book_line_2048x27_2sub0 = {
  118650. 1, 32,
  118651. _huff_lengthlist_line_2048x27_2sub0,
  118652. 0, 0, 0, 0, 0,
  118653. NULL,
  118654. NULL,
  118655. NULL,
  118656. NULL,
  118657. 0
  118658. };
  118659. static long _huff_lengthlist_line_2048x27_2sub1[] = {
  118660. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  118661. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  118662. 3, 4, 3, 4, 3, 4, 4, 5, 4, 5, 5, 5, 6, 6, 6, 7,
  118663. 6, 8, 6, 8, 6, 9, 7,10, 7,10, 7,10, 7,12, 7,12,
  118664. 7,12, 9,12,11,12,10,12,10,12,11,12,12,12,10,12,
  118665. 10,12,10,12, 9,12,11,12,12,12,12,12,11,12,11,12,
  118666. 12,12,12,12,12,12,12,12,10,10,12,12,12,12,12,10,
  118667. 12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,
  118668. };
  118669. static static_codebook _huff_book_line_2048x27_2sub1 = {
  118670. 1, 128,
  118671. _huff_lengthlist_line_2048x27_2sub1,
  118672. 0, 0, 0, 0, 0,
  118673. NULL,
  118674. NULL,
  118675. NULL,
  118676. NULL,
  118677. 0
  118678. };
  118679. static long _huff_lengthlist_line_2048x27_3sub1[] = {
  118680. 0, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4,
  118681. 5, 5,
  118682. };
  118683. static static_codebook _huff_book_line_2048x27_3sub1 = {
  118684. 1, 18,
  118685. _huff_lengthlist_line_2048x27_3sub1,
  118686. 0, 0, 0, 0, 0,
  118687. NULL,
  118688. NULL,
  118689. NULL,
  118690. NULL,
  118691. 0
  118692. };
  118693. static long _huff_lengthlist_line_2048x27_3sub2[] = {
  118694. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  118695. 0, 0, 3, 3, 3, 4, 4, 4, 4, 4, 4, 5, 5, 5, 5, 6,
  118696. 6, 7, 6, 7, 6, 8, 6, 9, 7, 9, 7, 9, 9,11, 9,12,
  118697. 10,12,
  118698. };
  118699. static static_codebook _huff_book_line_2048x27_3sub2 = {
  118700. 1, 50,
  118701. _huff_lengthlist_line_2048x27_3sub2,
  118702. 0, 0, 0, 0, 0,
  118703. NULL,
  118704. NULL,
  118705. NULL,
  118706. NULL,
  118707. 0
  118708. };
  118709. static long _huff_lengthlist_line_2048x27_3sub3[] = {
  118710. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  118711. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  118712. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  118713. 0, 0, 3, 6, 3, 7, 3, 7, 5, 7, 7, 7, 7, 7, 6, 7,
  118714. 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7,
  118715. 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7,
  118716. 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7,
  118717. 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7,
  118718. };
  118719. static static_codebook _huff_book_line_2048x27_3sub3 = {
  118720. 1, 128,
  118721. _huff_lengthlist_line_2048x27_3sub3,
  118722. 0, 0, 0, 0, 0,
  118723. NULL,
  118724. NULL,
  118725. NULL,
  118726. NULL,
  118727. 0
  118728. };
  118729. static long _huff_lengthlist_line_2048x27_4sub1[] = {
  118730. 0, 3, 4, 4, 4, 4, 4, 4, 4, 4, 5, 4, 5, 4, 5, 4,
  118731. 4, 5,
  118732. };
  118733. static static_codebook _huff_book_line_2048x27_4sub1 = {
  118734. 1, 18,
  118735. _huff_lengthlist_line_2048x27_4sub1,
  118736. 0, 0, 0, 0, 0,
  118737. NULL,
  118738. NULL,
  118739. NULL,
  118740. NULL,
  118741. 0
  118742. };
  118743. static long _huff_lengthlist_line_2048x27_4sub2[] = {
  118744. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  118745. 0, 0, 3, 2, 4, 3, 4, 4, 4, 5, 5, 6, 5, 6, 5, 7,
  118746. 6, 6, 6, 7, 7, 7, 8, 9, 9, 9,12,10,11,10,10,12,
  118747. 10,10,
  118748. };
  118749. static static_codebook _huff_book_line_2048x27_4sub2 = {
  118750. 1, 50,
  118751. _huff_lengthlist_line_2048x27_4sub2,
  118752. 0, 0, 0, 0, 0,
  118753. NULL,
  118754. NULL,
  118755. NULL,
  118756. NULL,
  118757. 0
  118758. };
  118759. static long _huff_lengthlist_line_2048x27_4sub3[] = {
  118760. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  118761. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  118762. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  118763. 0, 0, 3, 6, 5, 7, 5, 7, 7, 7, 7, 7, 5, 7, 5, 7,
  118764. 5, 7, 5, 7, 7, 7, 7, 7, 4, 7, 7, 7, 7, 7, 7, 7,
  118765. 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7,
  118766. 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7,
  118767. 7, 7, 7, 7, 7, 7, 7, 6, 6, 6, 6, 6, 6, 6, 6, 6,
  118768. };
  118769. static static_codebook _huff_book_line_2048x27_4sub3 = {
  118770. 1, 128,
  118771. _huff_lengthlist_line_2048x27_4sub3,
  118772. 0, 0, 0, 0, 0,
  118773. NULL,
  118774. NULL,
  118775. NULL,
  118776. NULL,
  118777. 0
  118778. };
  118779. static long _huff_lengthlist_line_256x4low_class0[] = {
  118780. 4, 5, 6,11, 5, 5, 6,10, 7, 7, 6, 6,14,13, 9, 9,
  118781. 6, 6, 6,10, 6, 6, 6, 9, 8, 7, 7, 9,14,12, 8,11,
  118782. 8, 7, 7,11, 8, 8, 7,11, 9, 9, 7, 9,13,11, 9,13,
  118783. 19,19,18,19,15,16,16,19,11,11,10,13,10,10, 9,15,
  118784. 5, 5, 6,13, 6, 6, 6,11, 8, 7, 6, 7,14,11,10,11,
  118785. 6, 6, 6,12, 7, 6, 6,11, 8, 7, 7,11,13,11, 9,11,
  118786. 9, 7, 6,12, 8, 7, 6,12, 9, 8, 8,11,13,10, 7,13,
  118787. 19,19,17,19,17,14,14,19,12,10, 8,12,13,10, 9,16,
  118788. 7, 8, 7,12, 7, 7, 7,11, 8, 7, 7, 8,12,12,11,11,
  118789. 8, 8, 7,12, 8, 7, 6,11, 8, 7, 7,10,10,11,10,11,
  118790. 9, 8, 8,13, 9, 8, 7,12,10, 9, 7,11, 9, 8, 7,11,
  118791. 18,18,15,18,18,16,17,18,15,11,10,18,11, 9, 9,18,
  118792. 16,16,13,16,12,11,10,16,12,11, 9, 6,15,12,11,13,
  118793. 16,16,14,14,13,11,12,16,12, 9, 9,13,13,10,10,12,
  118794. 17,18,17,17,14,15,14,16,14,12,14,15,12,10,11,12,
  118795. 18,18,18,18,18,18,18,18,18,12,13,18,16,11, 9,18,
  118796. };
  118797. static static_codebook _huff_book_line_256x4low_class0 = {
  118798. 1, 256,
  118799. _huff_lengthlist_line_256x4low_class0,
  118800. 0, 0, 0, 0, 0,
  118801. NULL,
  118802. NULL,
  118803. NULL,
  118804. NULL,
  118805. 0
  118806. };
  118807. static long _huff_lengthlist_line_256x4low_0sub0[] = {
  118808. 1, 3, 2, 3,
  118809. };
  118810. static static_codebook _huff_book_line_256x4low_0sub0 = {
  118811. 1, 4,
  118812. _huff_lengthlist_line_256x4low_0sub0,
  118813. 0, 0, 0, 0, 0,
  118814. NULL,
  118815. NULL,
  118816. NULL,
  118817. NULL,
  118818. 0
  118819. };
  118820. static long _huff_lengthlist_line_256x4low_0sub1[] = {
  118821. 0, 0, 0, 0, 2, 3, 2, 3, 3, 3,
  118822. };
  118823. static static_codebook _huff_book_line_256x4low_0sub1 = {
  118824. 1, 10,
  118825. _huff_lengthlist_line_256x4low_0sub1,
  118826. 0, 0, 0, 0, 0,
  118827. NULL,
  118828. NULL,
  118829. NULL,
  118830. NULL,
  118831. 0
  118832. };
  118833. static long _huff_lengthlist_line_256x4low_0sub2[] = {
  118834. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 3, 3, 3, 4, 3, 4,
  118835. 4, 4, 4, 4, 5, 5, 5, 6, 6,
  118836. };
  118837. static static_codebook _huff_book_line_256x4low_0sub2 = {
  118838. 1, 25,
  118839. _huff_lengthlist_line_256x4low_0sub2,
  118840. 0, 0, 0, 0, 0,
  118841. NULL,
  118842. NULL,
  118843. NULL,
  118844. NULL,
  118845. 0
  118846. };
  118847. static long _huff_lengthlist_line_256x4low_0sub3[] = {
  118848. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  118849. 0, 0, 0, 0, 0, 0, 0, 0, 0, 3, 4, 2, 4, 3, 5, 4,
  118850. 5, 5, 5, 5, 6, 6, 6, 6, 6, 6, 6, 7, 7, 8, 6, 9,
  118851. 7,12,11,16,13,16,12,15,13,15,12,14,12,15,15,15,
  118852. };
  118853. static static_codebook _huff_book_line_256x4low_0sub3 = {
  118854. 1, 64,
  118855. _huff_lengthlist_line_256x4low_0sub3,
  118856. 0, 0, 0, 0, 0,
  118857. NULL,
  118858. NULL,
  118859. NULL,
  118860. NULL,
  118861. 0
  118862. };
  118863. /*** End of inlined file: floor_books.h ***/
  118864. static static_codebook *_floor_128x4_books[]={
  118865. &_huff_book_line_128x4_class0,
  118866. &_huff_book_line_128x4_0sub0,
  118867. &_huff_book_line_128x4_0sub1,
  118868. &_huff_book_line_128x4_0sub2,
  118869. &_huff_book_line_128x4_0sub3,
  118870. };
  118871. static static_codebook *_floor_256x4_books[]={
  118872. &_huff_book_line_256x4_class0,
  118873. &_huff_book_line_256x4_0sub0,
  118874. &_huff_book_line_256x4_0sub1,
  118875. &_huff_book_line_256x4_0sub2,
  118876. &_huff_book_line_256x4_0sub3,
  118877. };
  118878. static static_codebook *_floor_128x7_books[]={
  118879. &_huff_book_line_128x7_class0,
  118880. &_huff_book_line_128x7_class1,
  118881. &_huff_book_line_128x7_0sub1,
  118882. &_huff_book_line_128x7_0sub2,
  118883. &_huff_book_line_128x7_0sub3,
  118884. &_huff_book_line_128x7_1sub1,
  118885. &_huff_book_line_128x7_1sub2,
  118886. &_huff_book_line_128x7_1sub3,
  118887. };
  118888. static static_codebook *_floor_256x7_books[]={
  118889. &_huff_book_line_256x7_class0,
  118890. &_huff_book_line_256x7_class1,
  118891. &_huff_book_line_256x7_0sub1,
  118892. &_huff_book_line_256x7_0sub2,
  118893. &_huff_book_line_256x7_0sub3,
  118894. &_huff_book_line_256x7_1sub1,
  118895. &_huff_book_line_256x7_1sub2,
  118896. &_huff_book_line_256x7_1sub3,
  118897. };
  118898. static static_codebook *_floor_128x11_books[]={
  118899. &_huff_book_line_128x11_class1,
  118900. &_huff_book_line_128x11_class2,
  118901. &_huff_book_line_128x11_class3,
  118902. &_huff_book_line_128x11_0sub0,
  118903. &_huff_book_line_128x11_1sub0,
  118904. &_huff_book_line_128x11_1sub1,
  118905. &_huff_book_line_128x11_2sub1,
  118906. &_huff_book_line_128x11_2sub2,
  118907. &_huff_book_line_128x11_2sub3,
  118908. &_huff_book_line_128x11_3sub1,
  118909. &_huff_book_line_128x11_3sub2,
  118910. &_huff_book_line_128x11_3sub3,
  118911. };
  118912. static static_codebook *_floor_128x17_books[]={
  118913. &_huff_book_line_128x17_class1,
  118914. &_huff_book_line_128x17_class2,
  118915. &_huff_book_line_128x17_class3,
  118916. &_huff_book_line_128x17_0sub0,
  118917. &_huff_book_line_128x17_1sub0,
  118918. &_huff_book_line_128x17_1sub1,
  118919. &_huff_book_line_128x17_2sub1,
  118920. &_huff_book_line_128x17_2sub2,
  118921. &_huff_book_line_128x17_2sub3,
  118922. &_huff_book_line_128x17_3sub1,
  118923. &_huff_book_line_128x17_3sub2,
  118924. &_huff_book_line_128x17_3sub3,
  118925. };
  118926. static static_codebook *_floor_256x4low_books[]={
  118927. &_huff_book_line_256x4low_class0,
  118928. &_huff_book_line_256x4low_0sub0,
  118929. &_huff_book_line_256x4low_0sub1,
  118930. &_huff_book_line_256x4low_0sub2,
  118931. &_huff_book_line_256x4low_0sub3,
  118932. };
  118933. static static_codebook *_floor_1024x27_books[]={
  118934. &_huff_book_line_1024x27_class1,
  118935. &_huff_book_line_1024x27_class2,
  118936. &_huff_book_line_1024x27_class3,
  118937. &_huff_book_line_1024x27_class4,
  118938. &_huff_book_line_1024x27_0sub0,
  118939. &_huff_book_line_1024x27_1sub0,
  118940. &_huff_book_line_1024x27_1sub1,
  118941. &_huff_book_line_1024x27_2sub0,
  118942. &_huff_book_line_1024x27_2sub1,
  118943. &_huff_book_line_1024x27_3sub1,
  118944. &_huff_book_line_1024x27_3sub2,
  118945. &_huff_book_line_1024x27_3sub3,
  118946. &_huff_book_line_1024x27_4sub1,
  118947. &_huff_book_line_1024x27_4sub2,
  118948. &_huff_book_line_1024x27_4sub3,
  118949. };
  118950. static static_codebook *_floor_2048x27_books[]={
  118951. &_huff_book_line_2048x27_class1,
  118952. &_huff_book_line_2048x27_class2,
  118953. &_huff_book_line_2048x27_class3,
  118954. &_huff_book_line_2048x27_class4,
  118955. &_huff_book_line_2048x27_0sub0,
  118956. &_huff_book_line_2048x27_1sub0,
  118957. &_huff_book_line_2048x27_1sub1,
  118958. &_huff_book_line_2048x27_2sub0,
  118959. &_huff_book_line_2048x27_2sub1,
  118960. &_huff_book_line_2048x27_3sub1,
  118961. &_huff_book_line_2048x27_3sub2,
  118962. &_huff_book_line_2048x27_3sub3,
  118963. &_huff_book_line_2048x27_4sub1,
  118964. &_huff_book_line_2048x27_4sub2,
  118965. &_huff_book_line_2048x27_4sub3,
  118966. };
  118967. static static_codebook *_floor_512x17_books[]={
  118968. &_huff_book_line_512x17_class1,
  118969. &_huff_book_line_512x17_class2,
  118970. &_huff_book_line_512x17_class3,
  118971. &_huff_book_line_512x17_0sub0,
  118972. &_huff_book_line_512x17_1sub0,
  118973. &_huff_book_line_512x17_1sub1,
  118974. &_huff_book_line_512x17_2sub1,
  118975. &_huff_book_line_512x17_2sub2,
  118976. &_huff_book_line_512x17_2sub3,
  118977. &_huff_book_line_512x17_3sub1,
  118978. &_huff_book_line_512x17_3sub2,
  118979. &_huff_book_line_512x17_3sub3,
  118980. };
  118981. static static_codebook **_floor_books[10]={
  118982. _floor_128x4_books,
  118983. _floor_256x4_books,
  118984. _floor_128x7_books,
  118985. _floor_256x7_books,
  118986. _floor_128x11_books,
  118987. _floor_128x17_books,
  118988. _floor_256x4low_books,
  118989. _floor_1024x27_books,
  118990. _floor_2048x27_books,
  118991. _floor_512x17_books,
  118992. };
  118993. static vorbis_info_floor1 _floor[10]={
  118994. /* 128 x 4 */
  118995. {
  118996. 1,{0},{4},{2},{0},
  118997. {{1,2,3,4}},
  118998. 4,{0,128, 33,8,16,70},
  118999. 60,30,500, 1.,18., -1
  119000. },
  119001. /* 256 x 4 */
  119002. {
  119003. 1,{0},{4},{2},{0},
  119004. {{1,2,3,4}},
  119005. 4,{0,256, 66,16,32,140},
  119006. 60,30,500, 1.,18., -1
  119007. },
  119008. /* 128 x 7 */
  119009. {
  119010. 2,{0,1},{3,4},{2,2},{0,1},
  119011. {{-1,2,3,4},{-1,5,6,7}},
  119012. 4,{0,128, 14,4,58, 2,8,28,90},
  119013. 60,30,500, 1.,18., -1
  119014. },
  119015. /* 256 x 7 */
  119016. {
  119017. 2,{0,1},{3,4},{2,2},{0,1},
  119018. {{-1,2,3,4},{-1,5,6,7}},
  119019. 4,{0,256, 28,8,116, 4,16,56,180},
  119020. 60,30,500, 1.,18., -1
  119021. },
  119022. /* 128 x 11 */
  119023. {
  119024. 4,{0,1,2,3},{2,3,3,3},{0,1,2,2},{-1,0,1,2},
  119025. {{3},{4,5},{-1,6,7,8},{-1,9,10,11}},
  119026. 2,{0,128, 8,33, 4,16,70, 2,6,12, 23,46,90},
  119027. 60,30,500, 1,18., -1
  119028. },
  119029. /* 128 x 17 */
  119030. {
  119031. 6,{0,1,1,2,3,3},{2,3,3,3},{0,1,2,2},{-1,0,1,2},
  119032. {{3},{4,5},{-1,6,7,8},{-1,9,10,11}},
  119033. 2,{0,128, 12,46, 4,8,16, 23,33,70, 2,6,10, 14,19,28, 39,58,90},
  119034. 60,30,500, 1,18., -1
  119035. },
  119036. /* 256 x 4 (low bitrate version) */
  119037. {
  119038. 1,{0},{4},{2},{0},
  119039. {{1,2,3,4}},
  119040. 4,{0,256, 66,16,32,140},
  119041. 60,30,500, 1.,18., -1
  119042. },
  119043. /* 1024 x 27 */
  119044. {
  119045. 8,{0,1,2,2,3,3,4,4},{3,4,3,4,3},{0,1,1,2,2},{-1,0,1,2,3},
  119046. {{4},{5,6},{7,8},{-1,9,10,11},{-1,12,13,14}},
  119047. 2,{0,1024, 93,23,372, 6,46,186,750, 14,33,65, 130,260,556,
  119048. 3,10,18,28, 39,55,79,111, 158,220,312, 464,650,850},
  119049. 60,30,500, 3,18., -1 /* lowpass */
  119050. },
  119051. /* 2048 x 27 */
  119052. {
  119053. 8,{0,1,2,2,3,3,4,4},{3,4,3,4,3},{0,1,1,2,2},{-1,0,1,2,3},
  119054. {{4},{5,6},{7,8},{-1,9,10,11},{-1,12,13,14}},
  119055. 2,{0,2048, 186,46,744, 12,92,372,1500, 28,66,130, 260,520,1112,
  119056. 6,20,36,56, 78,110,158,222, 316,440,624, 928,1300,1700},
  119057. 60,30,500, 3,18., -1 /* lowpass */
  119058. },
  119059. /* 512 x 17 */
  119060. {
  119061. 6,{0,1,1,2,3,3},{2,3,3,3},{0,1,2,2},{-1,0,1,2},
  119062. {{3},{4,5},{-1,6,7,8},{-1,9,10,11}},
  119063. 2,{0,512, 46,186, 16,33,65, 93,130,278,
  119064. 7,23,39, 55,79,110, 156,232,360},
  119065. 60,30,500, 1,18., -1 /* lowpass! */
  119066. },
  119067. };
  119068. /*** End of inlined file: floor_all.h ***/
  119069. /*** Start of inlined file: residue_44.h ***/
  119070. /*** Start of inlined file: res_books_stereo.h ***/
  119071. static long _vq_quantlist__16c0_s_p1_0[] = {
  119072. 1,
  119073. 0,
  119074. 2,
  119075. };
  119076. static long _vq_lengthlist__16c0_s_p1_0[] = {
  119077. 1, 4, 4, 0, 0, 0, 0, 0, 0, 5, 7, 7, 0, 0, 0, 0,
  119078. 0, 0, 5, 7, 7, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119079. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119080. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119081. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119082. 0, 5, 8, 8, 0, 0, 0, 0, 0, 0, 8, 9,10, 0, 0, 0,
  119083. 0, 0, 0, 7, 9,10, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119084. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119085. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119086. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119087. 0, 0, 5, 8, 8, 0, 0, 0, 0, 0, 0, 7, 9, 9, 0, 0,
  119088. 0, 0, 0, 0, 7, 9, 9, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119089. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119090. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119091. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119092. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119093. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119094. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119095. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119096. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119097. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119098. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119099. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119100. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119101. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119102. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119103. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119104. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119105. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119106. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119107. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119108. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119109. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119110. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119111. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119112. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119113. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119114. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119115. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119116. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119117. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119118. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119119. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119120. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119121. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119122. 0, 0, 0, 0, 0, 0, 0, 0, 0, 5, 8, 8, 0, 0, 0, 0,
  119123. 0, 0, 8,10,10, 0, 0, 0, 0, 0, 0, 8,10,10, 0, 0,
  119124. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119125. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119126. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119127. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 7,10,10, 0, 0, 0,
  119128. 0, 0, 0, 9, 9,12, 0, 0, 0, 0, 0, 0,10,12,11, 0,
  119129. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119130. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119131. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119132. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 7,10,10, 0, 0,
  119133. 0, 0, 0, 0, 9,12,10, 0, 0, 0, 0, 0, 0,10,11,12,
  119134. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119135. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119136. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119137. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119138. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119139. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119140. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119141. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119142. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119143. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119144. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119145. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119146. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119147. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119148. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119149. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119150. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119151. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119152. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119153. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119154. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119155. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119156. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119157. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119158. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119159. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119160. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119161. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119162. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119163. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119164. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119165. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119166. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119167. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119168. 0, 0, 5, 8, 8, 0, 0, 0, 0, 0, 0, 8,10,10, 0, 0,
  119169. 0, 0, 0, 0, 8,10,10, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119170. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119171. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119172. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119173. 0, 0, 0, 7,10,10, 0, 0, 0, 0, 0, 0,10,12,11, 0,
  119174. 0, 0, 0, 0, 0, 9,10,12, 0, 0, 0, 0, 0, 0, 0, 0,
  119175. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119176. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119177. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119178. 0, 0, 0, 0, 7,10,10, 0, 0, 0, 0, 0, 0,10,11,12,
  119179. 0, 0, 0, 0, 0, 0, 9,12, 9, 0, 0, 0, 0, 0, 0, 0,
  119180. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119181. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119182. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119183. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119184. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119185. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119186. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119187. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119188. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119189. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119190. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119191. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119192. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119193. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119194. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119195. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119196. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119197. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119198. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119199. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119200. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119201. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119202. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119203. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119204. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119205. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119206. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119207. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119208. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119209. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119210. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119211. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119212. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119213. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119214. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119215. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119216. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119217. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119218. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119219. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119220. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119221. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119222. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119223. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119224. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119225. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119226. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119227. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119228. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119229. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119230. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119231. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119232. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119233. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119234. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119235. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119236. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119237. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119238. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119239. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119240. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119241. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119242. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119243. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119244. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119245. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119246. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119247. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119248. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119249. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119250. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119251. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119252. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119253. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119254. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119255. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119256. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119257. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119258. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119259. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119260. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119261. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119262. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119263. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119264. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119265. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119266. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119267. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119268. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119269. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119270. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119271. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119272. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119273. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119274. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119275. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119276. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119277. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119278. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119279. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119280. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119281. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119282. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119283. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119284. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119285. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119286. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119287. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119288. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119289. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119290. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119291. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119292. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119293. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119294. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119295. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119296. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119297. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119298. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119299. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119300. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119301. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119302. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119303. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119304. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119305. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119306. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119307. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119308. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119309. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119310. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119311. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119312. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119313. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119314. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119315. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119316. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119317. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119318. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119319. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119320. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119321. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119322. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119323. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119324. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119325. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119326. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119327. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119328. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119329. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119330. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119331. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119332. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119333. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119334. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119335. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119336. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119337. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119338. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119339. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119340. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119341. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119342. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119343. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119344. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119345. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119346. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119347. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119348. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119349. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119350. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119351. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119352. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119353. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119354. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119355. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119356. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119357. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119358. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119359. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119360. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119361. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119362. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119363. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119364. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119365. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119366. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119367. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119368. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119369. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119370. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119371. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119372. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119373. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119374. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119375. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119376. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119377. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119378. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119379. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119380. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119381. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119382. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119383. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119384. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119385. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119386. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119387. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119388. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119389. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119390. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119391. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119392. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119393. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119394. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119395. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119396. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119397. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119398. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119399. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119400. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119401. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119402. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119403. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119404. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119405. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119406. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119407. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119408. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119409. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119410. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119411. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119412. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119413. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119414. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119415. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119416. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119417. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119418. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119419. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119420. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119421. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119422. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119423. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119424. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119425. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119426. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119427. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119428. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119429. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119430. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119431. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119432. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119433. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119434. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119435. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119436. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119437. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119438. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119439. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119440. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119441. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119442. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119443. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119444. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119445. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119446. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119447. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119448. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119449. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119450. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119451. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119452. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119453. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119454. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119455. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119456. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119457. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119458. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119459. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119460. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119461. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119462. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119463. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119464. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119465. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119466. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119467. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119468. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119469. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119470. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119471. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119472. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119473. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119474. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119475. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119476. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119477. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119478. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119479. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119480. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119481. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119482. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119483. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119484. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119485. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119486. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119487. 0,
  119488. };
  119489. static float _vq_quantthresh__16c0_s_p1_0[] = {
  119490. -0.5, 0.5,
  119491. };
  119492. static long _vq_quantmap__16c0_s_p1_0[] = {
  119493. 1, 0, 2,
  119494. };
  119495. static encode_aux_threshmatch _vq_auxt__16c0_s_p1_0 = {
  119496. _vq_quantthresh__16c0_s_p1_0,
  119497. _vq_quantmap__16c0_s_p1_0,
  119498. 3,
  119499. 3
  119500. };
  119501. static static_codebook _16c0_s_p1_0 = {
  119502. 8, 6561,
  119503. _vq_lengthlist__16c0_s_p1_0,
  119504. 1, -535822336, 1611661312, 2, 0,
  119505. _vq_quantlist__16c0_s_p1_0,
  119506. NULL,
  119507. &_vq_auxt__16c0_s_p1_0,
  119508. NULL,
  119509. 0
  119510. };
  119511. static long _vq_quantlist__16c0_s_p2_0[] = {
  119512. 2,
  119513. 1,
  119514. 3,
  119515. 0,
  119516. 4,
  119517. };
  119518. static long _vq_lengthlist__16c0_s_p2_0[] = {
  119519. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119520. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119521. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119522. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119523. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119524. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119525. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119526. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119527. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119528. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119529. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119530. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119531. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119532. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119533. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119534. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119535. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119536. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119537. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119538. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119539. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119540. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119541. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119542. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119543. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119544. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119545. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119546. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119547. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119548. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119549. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119550. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119551. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119552. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119553. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119554. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119555. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119556. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119557. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119558. 0,
  119559. };
  119560. static float _vq_quantthresh__16c0_s_p2_0[] = {
  119561. -1.5, -0.5, 0.5, 1.5,
  119562. };
  119563. static long _vq_quantmap__16c0_s_p2_0[] = {
  119564. 3, 1, 0, 2, 4,
  119565. };
  119566. static encode_aux_threshmatch _vq_auxt__16c0_s_p2_0 = {
  119567. _vq_quantthresh__16c0_s_p2_0,
  119568. _vq_quantmap__16c0_s_p2_0,
  119569. 5,
  119570. 5
  119571. };
  119572. static static_codebook _16c0_s_p2_0 = {
  119573. 4, 625,
  119574. _vq_lengthlist__16c0_s_p2_0,
  119575. 1, -533725184, 1611661312, 3, 0,
  119576. _vq_quantlist__16c0_s_p2_0,
  119577. NULL,
  119578. &_vq_auxt__16c0_s_p2_0,
  119579. NULL,
  119580. 0
  119581. };
  119582. static long _vq_quantlist__16c0_s_p3_0[] = {
  119583. 2,
  119584. 1,
  119585. 3,
  119586. 0,
  119587. 4,
  119588. };
  119589. static long _vq_lengthlist__16c0_s_p3_0[] = {
  119590. 1, 4, 4, 6, 6, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119591. 0, 0, 0, 0, 0, 0, 0, 0, 0, 4, 6, 6, 7, 6, 0, 0,
  119592. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119593. 0, 0, 4, 6, 6, 6, 6, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119594. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 6, 6, 6, 9, 9,
  119595. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119596. 0, 0, 0, 0, 6, 6, 6, 9, 9, 0, 0, 0, 0, 0, 0, 0,
  119597. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119598. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119599. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119600. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119601. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119602. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119603. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119604. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119605. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119606. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119607. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119608. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119609. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119610. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119611. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119612. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119613. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119614. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119615. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119616. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119617. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119618. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119619. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119620. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119621. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119622. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119623. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119624. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119625. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119626. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119627. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119628. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119629. 0,
  119630. };
  119631. static float _vq_quantthresh__16c0_s_p3_0[] = {
  119632. -1.5, -0.5, 0.5, 1.5,
  119633. };
  119634. static long _vq_quantmap__16c0_s_p3_0[] = {
  119635. 3, 1, 0, 2, 4,
  119636. };
  119637. static encode_aux_threshmatch _vq_auxt__16c0_s_p3_0 = {
  119638. _vq_quantthresh__16c0_s_p3_0,
  119639. _vq_quantmap__16c0_s_p3_0,
  119640. 5,
  119641. 5
  119642. };
  119643. static static_codebook _16c0_s_p3_0 = {
  119644. 4, 625,
  119645. _vq_lengthlist__16c0_s_p3_0,
  119646. 1, -533725184, 1611661312, 3, 0,
  119647. _vq_quantlist__16c0_s_p3_0,
  119648. NULL,
  119649. &_vq_auxt__16c0_s_p3_0,
  119650. NULL,
  119651. 0
  119652. };
  119653. static long _vq_quantlist__16c0_s_p4_0[] = {
  119654. 4,
  119655. 3,
  119656. 5,
  119657. 2,
  119658. 6,
  119659. 1,
  119660. 7,
  119661. 0,
  119662. 8,
  119663. };
  119664. static long _vq_lengthlist__16c0_s_p4_0[] = {
  119665. 1, 3, 2, 7, 8, 0, 0, 0, 0, 0, 0, 0, 6, 6, 0, 0,
  119666. 0, 0, 0, 0, 0, 6, 6, 0, 0, 0, 0, 0, 0, 0, 7, 7,
  119667. 0, 0, 0, 0, 0, 0, 0, 7, 7, 0, 0, 0, 0, 0, 0, 0,
  119668. 8, 8, 0, 0, 0, 0, 0, 0, 0, 8, 8, 0, 0, 0, 0, 0,
  119669. 0, 0, 9, 9, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119670. 0,
  119671. };
  119672. static float _vq_quantthresh__16c0_s_p4_0[] = {
  119673. -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5, 3.5,
  119674. };
  119675. static long _vq_quantmap__16c0_s_p4_0[] = {
  119676. 7, 5, 3, 1, 0, 2, 4, 6,
  119677. 8,
  119678. };
  119679. static encode_aux_threshmatch _vq_auxt__16c0_s_p4_0 = {
  119680. _vq_quantthresh__16c0_s_p4_0,
  119681. _vq_quantmap__16c0_s_p4_0,
  119682. 9,
  119683. 9
  119684. };
  119685. static static_codebook _16c0_s_p4_0 = {
  119686. 2, 81,
  119687. _vq_lengthlist__16c0_s_p4_0,
  119688. 1, -531628032, 1611661312, 4, 0,
  119689. _vq_quantlist__16c0_s_p4_0,
  119690. NULL,
  119691. &_vq_auxt__16c0_s_p4_0,
  119692. NULL,
  119693. 0
  119694. };
  119695. static long _vq_quantlist__16c0_s_p5_0[] = {
  119696. 4,
  119697. 3,
  119698. 5,
  119699. 2,
  119700. 6,
  119701. 1,
  119702. 7,
  119703. 0,
  119704. 8,
  119705. };
  119706. static long _vq_lengthlist__16c0_s_p5_0[] = {
  119707. 1, 3, 3, 6, 6, 6, 6, 8, 8, 0, 0, 0, 7, 7, 7, 7,
  119708. 8, 8, 0, 0, 0, 7, 7, 7, 7, 8, 8, 0, 0, 0, 7, 7,
  119709. 8, 8, 9, 9, 0, 0, 0, 7, 7, 8, 8, 9, 9, 0, 0, 0,
  119710. 8, 9, 8, 8,10,10, 0, 0, 0, 8, 8, 8, 8,10,10, 0,
  119711. 0, 0,10,10, 9, 9,10,10, 0, 0, 0, 0, 0, 9, 9,10,
  119712. 10,
  119713. };
  119714. static float _vq_quantthresh__16c0_s_p5_0[] = {
  119715. -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5, 3.5,
  119716. };
  119717. static long _vq_quantmap__16c0_s_p5_0[] = {
  119718. 7, 5, 3, 1, 0, 2, 4, 6,
  119719. 8,
  119720. };
  119721. static encode_aux_threshmatch _vq_auxt__16c0_s_p5_0 = {
  119722. _vq_quantthresh__16c0_s_p5_0,
  119723. _vq_quantmap__16c0_s_p5_0,
  119724. 9,
  119725. 9
  119726. };
  119727. static static_codebook _16c0_s_p5_0 = {
  119728. 2, 81,
  119729. _vq_lengthlist__16c0_s_p5_0,
  119730. 1, -531628032, 1611661312, 4, 0,
  119731. _vq_quantlist__16c0_s_p5_0,
  119732. NULL,
  119733. &_vq_auxt__16c0_s_p5_0,
  119734. NULL,
  119735. 0
  119736. };
  119737. static long _vq_quantlist__16c0_s_p6_0[] = {
  119738. 8,
  119739. 7,
  119740. 9,
  119741. 6,
  119742. 10,
  119743. 5,
  119744. 11,
  119745. 4,
  119746. 12,
  119747. 3,
  119748. 13,
  119749. 2,
  119750. 14,
  119751. 1,
  119752. 15,
  119753. 0,
  119754. 16,
  119755. };
  119756. static long _vq_lengthlist__16c0_s_p6_0[] = {
  119757. 1, 3, 4, 6, 6, 7, 7, 8, 8, 8, 8, 9, 9,10,10,11,
  119758. 11, 0, 0, 0, 7, 7, 8, 8, 9, 9, 9, 9,10,10,10,11,
  119759. 11,11, 0, 0, 0, 6, 6, 8, 8, 9, 9, 9, 9,10,10,11,
  119760. 11,11,11, 0, 0, 0, 7, 7, 8, 8, 9, 9, 9, 9,10,10,
  119761. 11,11,12,12, 0, 0, 0, 7, 7, 8, 8, 9, 9, 9, 9,10,
  119762. 10,11,11,12,12, 0, 0, 0, 8, 8, 9, 9,10,10,10,10,
  119763. 11,11,12,12,12,12, 0, 0, 0, 8, 8, 9, 9,10,10,10,
  119764. 10,11,11,12,12,12,13, 0, 0, 0, 9, 9, 9, 9,10,10,
  119765. 10,10,11,11,12,12,13,13, 0, 0, 0, 0, 0,10,10,10,
  119766. 10,10,10,11,11,12,12,13,13, 0, 0, 0, 0, 0, 9, 9,
  119767. 10,10,11,11,12,12,13,13,13,13, 0, 0, 0, 0, 0, 9,
  119768. 9,10,10,11,11,12,12,13,13,13,14, 0, 0, 0, 0, 0,
  119769. 10,10,10,11,11,11,12,12,13,13,13,14, 0, 0, 0, 0,
  119770. 0, 0, 0,10,10,11,11,12,12,13,13,14,14, 0, 0, 0,
  119771. 0, 0, 0, 0,11,11,12,12,13,13,13,13,14,14, 0, 0,
  119772. 0, 0, 0, 0, 0,11,11,12,12,12,13,13,14,15,14, 0,
  119773. 0, 0, 0, 0, 0, 0,12,12,12,12,13,13,13,14,14,15,
  119774. 0, 0, 0, 0, 0, 0, 0, 0, 0,12,12,13,13,14,13,14,
  119775. 14,
  119776. };
  119777. static float _vq_quantthresh__16c0_s_p6_0[] = {
  119778. -7.5, -6.5, -5.5, -4.5, -3.5, -2.5, -1.5, -0.5,
  119779. 0.5, 1.5, 2.5, 3.5, 4.5, 5.5, 6.5, 7.5,
  119780. };
  119781. static long _vq_quantmap__16c0_s_p6_0[] = {
  119782. 15, 13, 11, 9, 7, 5, 3, 1,
  119783. 0, 2, 4, 6, 8, 10, 12, 14,
  119784. 16,
  119785. };
  119786. static encode_aux_threshmatch _vq_auxt__16c0_s_p6_0 = {
  119787. _vq_quantthresh__16c0_s_p6_0,
  119788. _vq_quantmap__16c0_s_p6_0,
  119789. 17,
  119790. 17
  119791. };
  119792. static static_codebook _16c0_s_p6_0 = {
  119793. 2, 289,
  119794. _vq_lengthlist__16c0_s_p6_0,
  119795. 1, -529530880, 1611661312, 5, 0,
  119796. _vq_quantlist__16c0_s_p6_0,
  119797. NULL,
  119798. &_vq_auxt__16c0_s_p6_0,
  119799. NULL,
  119800. 0
  119801. };
  119802. static long _vq_quantlist__16c0_s_p7_0[] = {
  119803. 1,
  119804. 0,
  119805. 2,
  119806. };
  119807. static long _vq_lengthlist__16c0_s_p7_0[] = {
  119808. 1, 4, 4, 6, 6, 6, 7, 6, 6, 4, 7, 7,11,10,10,11,
  119809. 11,10, 4, 7, 7,10,10,10,11,10,10, 6,10,10,11,11,
  119810. 11,11,11,10, 6, 9, 9,11,12,12,11, 9, 9, 6, 9,10,
  119811. 11,12,12,11, 9,10, 7,11,11,11,11,11,12,13,12, 6,
  119812. 9,10,11,10,10,12,13,13, 6,10, 9,11,10,10,11,12,
  119813. 13,
  119814. };
  119815. static float _vq_quantthresh__16c0_s_p7_0[] = {
  119816. -5.5, 5.5,
  119817. };
  119818. static long _vq_quantmap__16c0_s_p7_0[] = {
  119819. 1, 0, 2,
  119820. };
  119821. static encode_aux_threshmatch _vq_auxt__16c0_s_p7_0 = {
  119822. _vq_quantthresh__16c0_s_p7_0,
  119823. _vq_quantmap__16c0_s_p7_0,
  119824. 3,
  119825. 3
  119826. };
  119827. static static_codebook _16c0_s_p7_0 = {
  119828. 4, 81,
  119829. _vq_lengthlist__16c0_s_p7_0,
  119830. 1, -529137664, 1618345984, 2, 0,
  119831. _vq_quantlist__16c0_s_p7_0,
  119832. NULL,
  119833. &_vq_auxt__16c0_s_p7_0,
  119834. NULL,
  119835. 0
  119836. };
  119837. static long _vq_quantlist__16c0_s_p7_1[] = {
  119838. 5,
  119839. 4,
  119840. 6,
  119841. 3,
  119842. 7,
  119843. 2,
  119844. 8,
  119845. 1,
  119846. 9,
  119847. 0,
  119848. 10,
  119849. };
  119850. static long _vq_lengthlist__16c0_s_p7_1[] = {
  119851. 1, 3, 4, 6, 6, 7, 7, 8, 8, 8, 8,10,10,10, 7, 7,
  119852. 8, 8, 8, 9, 9, 9,10,10,10, 6, 7, 8, 8, 8, 8, 9,
  119853. 8,10,10,10, 7, 7, 8, 8, 9, 9, 9, 9,10,10,10, 7,
  119854. 7, 8, 8, 9, 9, 8, 9,10,10,10, 8, 8, 9, 9, 9, 9,
  119855. 9, 9,11,11,11, 8, 8, 9, 9, 9, 9, 9,10,10,11,11,
  119856. 9, 9, 9, 9, 9, 9, 9,10,11,11,11,10,11, 9, 9, 9,
  119857. 9,10, 9,11,11,11,10,11,10,10, 9, 9,10,10,11,11,
  119858. 11,11,11, 9, 9, 9, 9,10,10,
  119859. };
  119860. static float _vq_quantthresh__16c0_s_p7_1[] = {
  119861. -4.5, -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5,
  119862. 3.5, 4.5,
  119863. };
  119864. static long _vq_quantmap__16c0_s_p7_1[] = {
  119865. 9, 7, 5, 3, 1, 0, 2, 4,
  119866. 6, 8, 10,
  119867. };
  119868. static encode_aux_threshmatch _vq_auxt__16c0_s_p7_1 = {
  119869. _vq_quantthresh__16c0_s_p7_1,
  119870. _vq_quantmap__16c0_s_p7_1,
  119871. 11,
  119872. 11
  119873. };
  119874. static static_codebook _16c0_s_p7_1 = {
  119875. 2, 121,
  119876. _vq_lengthlist__16c0_s_p7_1,
  119877. 1, -531365888, 1611661312, 4, 0,
  119878. _vq_quantlist__16c0_s_p7_1,
  119879. NULL,
  119880. &_vq_auxt__16c0_s_p7_1,
  119881. NULL,
  119882. 0
  119883. };
  119884. static long _vq_quantlist__16c0_s_p8_0[] = {
  119885. 6,
  119886. 5,
  119887. 7,
  119888. 4,
  119889. 8,
  119890. 3,
  119891. 9,
  119892. 2,
  119893. 10,
  119894. 1,
  119895. 11,
  119896. 0,
  119897. 12,
  119898. };
  119899. static long _vq_lengthlist__16c0_s_p8_0[] = {
  119900. 1, 4, 4, 7, 7, 7, 7, 7, 6, 8, 8,10,10, 6, 5, 6,
  119901. 8, 8, 8, 8, 8, 8, 8, 9,10,10, 7, 6, 6, 8, 8, 8,
  119902. 8, 8, 8, 8, 8,10,10, 0, 8, 8, 8, 8, 9, 8, 9, 9,
  119903. 9,10,10,10, 0, 9, 8, 8, 8, 9, 9, 8, 8, 9, 9,10,
  119904. 10, 0,12,11, 8, 8, 9, 9, 9, 9,10,10,11,10, 0,12,
  119905. 13, 8, 8, 9,10, 9, 9,11,11,11,12, 0, 0, 0, 8, 8,
  119906. 8, 8,10, 9,12,13,12,14, 0, 0, 0, 8, 8, 8, 9,10,
  119907. 10,12,12,13,14, 0, 0, 0,13,13, 9, 9,11,11, 0, 0,
  119908. 14, 0, 0, 0, 0,14,14,10,10,12,11,12,14,14,14, 0,
  119909. 0, 0, 0, 0,11,11,13,13,14,13,14,14, 0, 0, 0, 0,
  119910. 0,12,13,13,12,13,14,14,14,
  119911. };
  119912. static float _vq_quantthresh__16c0_s_p8_0[] = {
  119913. -27.5, -22.5, -17.5, -12.5, -7.5, -2.5, 2.5, 7.5,
  119914. 12.5, 17.5, 22.5, 27.5,
  119915. };
  119916. static long _vq_quantmap__16c0_s_p8_0[] = {
  119917. 11, 9, 7, 5, 3, 1, 0, 2,
  119918. 4, 6, 8, 10, 12,
  119919. };
  119920. static encode_aux_threshmatch _vq_auxt__16c0_s_p8_0 = {
  119921. _vq_quantthresh__16c0_s_p8_0,
  119922. _vq_quantmap__16c0_s_p8_0,
  119923. 13,
  119924. 13
  119925. };
  119926. static static_codebook _16c0_s_p8_0 = {
  119927. 2, 169,
  119928. _vq_lengthlist__16c0_s_p8_0,
  119929. 1, -526516224, 1616117760, 4, 0,
  119930. _vq_quantlist__16c0_s_p8_0,
  119931. NULL,
  119932. &_vq_auxt__16c0_s_p8_0,
  119933. NULL,
  119934. 0
  119935. };
  119936. static long _vq_quantlist__16c0_s_p8_1[] = {
  119937. 2,
  119938. 1,
  119939. 3,
  119940. 0,
  119941. 4,
  119942. };
  119943. static long _vq_lengthlist__16c0_s_p8_1[] = {
  119944. 1, 4, 3, 5, 5, 7, 7, 7, 6, 6, 7, 7, 7, 5, 5, 7,
  119945. 7, 7, 6, 6, 7, 7, 7, 6, 6,
  119946. };
  119947. static float _vq_quantthresh__16c0_s_p8_1[] = {
  119948. -1.5, -0.5, 0.5, 1.5,
  119949. };
  119950. static long _vq_quantmap__16c0_s_p8_1[] = {
  119951. 3, 1, 0, 2, 4,
  119952. };
  119953. static encode_aux_threshmatch _vq_auxt__16c0_s_p8_1 = {
  119954. _vq_quantthresh__16c0_s_p8_1,
  119955. _vq_quantmap__16c0_s_p8_1,
  119956. 5,
  119957. 5
  119958. };
  119959. static static_codebook _16c0_s_p8_1 = {
  119960. 2, 25,
  119961. _vq_lengthlist__16c0_s_p8_1,
  119962. 1, -533725184, 1611661312, 3, 0,
  119963. _vq_quantlist__16c0_s_p8_1,
  119964. NULL,
  119965. &_vq_auxt__16c0_s_p8_1,
  119966. NULL,
  119967. 0
  119968. };
  119969. static long _vq_quantlist__16c0_s_p9_0[] = {
  119970. 1,
  119971. 0,
  119972. 2,
  119973. };
  119974. static long _vq_lengthlist__16c0_s_p9_0[] = {
  119975. 1, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8,
  119976. 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8,
  119977. 8, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7,
  119978. 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7,
  119979. 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7,
  119980. 7,
  119981. };
  119982. static float _vq_quantthresh__16c0_s_p9_0[] = {
  119983. -157.5, 157.5,
  119984. };
  119985. static long _vq_quantmap__16c0_s_p9_0[] = {
  119986. 1, 0, 2,
  119987. };
  119988. static encode_aux_threshmatch _vq_auxt__16c0_s_p9_0 = {
  119989. _vq_quantthresh__16c0_s_p9_0,
  119990. _vq_quantmap__16c0_s_p9_0,
  119991. 3,
  119992. 3
  119993. };
  119994. static static_codebook _16c0_s_p9_0 = {
  119995. 4, 81,
  119996. _vq_lengthlist__16c0_s_p9_0,
  119997. 1, -518803456, 1628680192, 2, 0,
  119998. _vq_quantlist__16c0_s_p9_0,
  119999. NULL,
  120000. &_vq_auxt__16c0_s_p9_0,
  120001. NULL,
  120002. 0
  120003. };
  120004. static long _vq_quantlist__16c0_s_p9_1[] = {
  120005. 7,
  120006. 6,
  120007. 8,
  120008. 5,
  120009. 9,
  120010. 4,
  120011. 10,
  120012. 3,
  120013. 11,
  120014. 2,
  120015. 12,
  120016. 1,
  120017. 13,
  120018. 0,
  120019. 14,
  120020. };
  120021. static long _vq_lengthlist__16c0_s_p9_1[] = {
  120022. 1, 5, 5, 5, 5, 9,11,11,10,10,10,10,10,10,10, 7,
  120023. 6, 6, 6, 6,10,10,10,10,10,10,10,10,10,10, 7, 6,
  120024. 6, 6, 6,10, 9,10,10,10,10,10,10,10,10,10, 7, 7,
  120025. 8, 9,10,10,10,10,10,10,10,10,10,10,10, 8, 7,10,
  120026. 10,10, 9,10,10,10,10,10,10,10,10,10,10,10,10,10,
  120027. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  120028. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  120029. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  120030. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  120031. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  120032. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  120033. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  120034. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  120035. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  120036. 10,
  120037. };
  120038. static float _vq_quantthresh__16c0_s_p9_1[] = {
  120039. -136.5, -115.5, -94.5, -73.5, -52.5, -31.5, -10.5, 10.5,
  120040. 31.5, 52.5, 73.5, 94.5, 115.5, 136.5,
  120041. };
  120042. static long _vq_quantmap__16c0_s_p9_1[] = {
  120043. 13, 11, 9, 7, 5, 3, 1, 0,
  120044. 2, 4, 6, 8, 10, 12, 14,
  120045. };
  120046. static encode_aux_threshmatch _vq_auxt__16c0_s_p9_1 = {
  120047. _vq_quantthresh__16c0_s_p9_1,
  120048. _vq_quantmap__16c0_s_p9_1,
  120049. 15,
  120050. 15
  120051. };
  120052. static static_codebook _16c0_s_p9_1 = {
  120053. 2, 225,
  120054. _vq_lengthlist__16c0_s_p9_1,
  120055. 1, -520986624, 1620377600, 4, 0,
  120056. _vq_quantlist__16c0_s_p9_1,
  120057. NULL,
  120058. &_vq_auxt__16c0_s_p9_1,
  120059. NULL,
  120060. 0
  120061. };
  120062. static long _vq_quantlist__16c0_s_p9_2[] = {
  120063. 10,
  120064. 9,
  120065. 11,
  120066. 8,
  120067. 12,
  120068. 7,
  120069. 13,
  120070. 6,
  120071. 14,
  120072. 5,
  120073. 15,
  120074. 4,
  120075. 16,
  120076. 3,
  120077. 17,
  120078. 2,
  120079. 18,
  120080. 1,
  120081. 19,
  120082. 0,
  120083. 20,
  120084. };
  120085. static long _vq_lengthlist__16c0_s_p9_2[] = {
  120086. 1, 5, 5, 7, 8, 8, 7, 9, 9, 9,12,12,11,12,12,10,
  120087. 10,11,12,12,12,11,12,12, 8, 9, 8, 7, 9,10,10,11,
  120088. 11,10,11,12,10,12,10,12,12,12,11,12,11, 9, 8, 8,
  120089. 9,10, 9, 8, 9,10,12,12,11,11,12,11,10,11,12,11,
  120090. 12,12, 8, 9, 9, 9,10,11,12,11,12,11,11,11,11,12,
  120091. 12,11,11,12,12,11,11, 9, 9, 8, 9, 9,11, 9, 9,10,
  120092. 9,11,11,11,11,12,11,11,10,12,12,12, 9,12,11,10,
  120093. 11,11,11,11,12,12,12,11,11,11,12,10,12,12,12,10,
  120094. 10, 9,10, 9,10,10, 9, 9, 9,10,10,12,10,11,11, 9,
  120095. 11,11,10,11,11,11,10,10,10, 9, 9,10,10, 9, 9,10,
  120096. 11,11,10,11,10,11,10,11,11,10,11,11,11,10, 9,10,
  120097. 10, 9,10, 9, 9,11, 9, 9,11,10,10,11,11,10,10,11,
  120098. 10,11, 8, 9,11,11,10, 9,10,11,11,10,11,11,10,10,
  120099. 10,11,10, 9,10,10,11, 9,10,10, 9,11,10,10,10,10,
  120100. 11,10,11,11, 9,11,10,11,10,10,11,11,10,10,10, 9,
  120101. 10,10,11,11,11, 9,10,10,10,10,10,11,10,10,10, 9,
  120102. 10,10,11,10,10,10,10,10, 9,10,11,10,10,10,10,11,
  120103. 11,11,10,10,10,10,10,11,10,11,10,11,10,10,10, 9,
  120104. 11,11,10,10,10,11,11,10,10,10,10,10,10,10,10,11,
  120105. 11, 9,10,10,10,11,10,11,10,10,10,11, 9,10,11,10,
  120106. 11,10,10, 9,10,10,10,11,10,11,10,10,10,10,10,11,
  120107. 11,10,11,11,10,10,11,11,10, 9, 9,10,10,10,10,10,
  120108. 9,11, 9,10,10,10,11,11,10,10,10,10,11,11,11,10,
  120109. 9, 9,10,10,11,10,10,10,10,10,11,11,11,10,10,10,
  120110. 11,11,11, 9,10,10,10,10, 9,10, 9,10,11,10,11,10,
  120111. 10,11,11,10,11,11,11,11,11,10,11,10,10,10, 9,11,
  120112. 11,10,11,11,11,11,11,11,11,11,11,10,11,10,10,10,
  120113. 10,11,10,10,11, 9,10,10,10,
  120114. };
  120115. static float _vq_quantthresh__16c0_s_p9_2[] = {
  120116. -9.5, -8.5, -7.5, -6.5, -5.5, -4.5, -3.5, -2.5,
  120117. -1.5, -0.5, 0.5, 1.5, 2.5, 3.5, 4.5, 5.5,
  120118. 6.5, 7.5, 8.5, 9.5,
  120119. };
  120120. static long _vq_quantmap__16c0_s_p9_2[] = {
  120121. 19, 17, 15, 13, 11, 9, 7, 5,
  120122. 3, 1, 0, 2, 4, 6, 8, 10,
  120123. 12, 14, 16, 18, 20,
  120124. };
  120125. static encode_aux_threshmatch _vq_auxt__16c0_s_p9_2 = {
  120126. _vq_quantthresh__16c0_s_p9_2,
  120127. _vq_quantmap__16c0_s_p9_2,
  120128. 21,
  120129. 21
  120130. };
  120131. static static_codebook _16c0_s_p9_2 = {
  120132. 2, 441,
  120133. _vq_lengthlist__16c0_s_p9_2,
  120134. 1, -529268736, 1611661312, 5, 0,
  120135. _vq_quantlist__16c0_s_p9_2,
  120136. NULL,
  120137. &_vq_auxt__16c0_s_p9_2,
  120138. NULL,
  120139. 0
  120140. };
  120141. static long _huff_lengthlist__16c0_s_single[] = {
  120142. 3, 4,19, 7, 9, 7, 8,11, 9,12, 4, 1,19, 6, 7, 7,
  120143. 8,10,11,13,18,18,18,18,18,18,18,18,18,18, 8, 6,
  120144. 18, 8, 9, 9,11,12,14,18, 9, 6,18, 9, 7, 8, 9,11,
  120145. 12,18, 7, 6,18, 8, 7, 7, 7, 9,11,17, 8, 8,18, 9,
  120146. 7, 6, 6, 8,11,17,10,10,18,12, 9, 8, 7, 9,12,18,
  120147. 13,15,18,15,13,11,10,11,15,18,14,18,18,18,18,18,
  120148. 16,16,18,18,
  120149. };
  120150. static static_codebook _huff_book__16c0_s_single = {
  120151. 2, 100,
  120152. _huff_lengthlist__16c0_s_single,
  120153. 0, 0, 0, 0, 0,
  120154. NULL,
  120155. NULL,
  120156. NULL,
  120157. NULL,
  120158. 0
  120159. };
  120160. static long _huff_lengthlist__16c1_s_long[] = {
  120161. 2, 5,20, 7,10, 7, 8,10,11,11, 4, 2,20, 5, 8, 6,
  120162. 7, 9,10,10,20,20,20,20,19,19,19,19,19,19, 7, 5,
  120163. 19, 6,10, 7, 9,11,13,17,11, 8,19,10, 7, 7, 8,10,
  120164. 11,15, 7, 5,19, 7, 7, 5, 6, 9,11,16, 7, 6,19, 8,
  120165. 7, 6, 6, 7, 9,13, 9, 9,19,11, 9, 8, 6, 7, 8,13,
  120166. 12,14,19,16,13,10, 9, 8, 9,13,14,17,19,18,18,17,
  120167. 12,11,11,13,
  120168. };
  120169. static static_codebook _huff_book__16c1_s_long = {
  120170. 2, 100,
  120171. _huff_lengthlist__16c1_s_long,
  120172. 0, 0, 0, 0, 0,
  120173. NULL,
  120174. NULL,
  120175. NULL,
  120176. NULL,
  120177. 0
  120178. };
  120179. static long _vq_quantlist__16c1_s_p1_0[] = {
  120180. 1,
  120181. 0,
  120182. 2,
  120183. };
  120184. static long _vq_lengthlist__16c1_s_p1_0[] = {
  120185. 1, 5, 5, 0, 0, 0, 0, 0, 0, 5, 7, 7, 0, 0, 0, 0,
  120186. 0, 0, 5, 7, 7, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120187. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120188. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120189. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120190. 0, 5, 8, 7, 0, 0, 0, 0, 0, 0, 7, 9, 9, 0, 0, 0,
  120191. 0, 0, 0, 7, 8, 9, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120192. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120193. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120194. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120195. 0, 0, 5, 7, 8, 0, 0, 0, 0, 0, 0, 7, 9, 8, 0, 0,
  120196. 0, 0, 0, 0, 7, 9, 9, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120197. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120198. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120199. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120200. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120201. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120202. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120203. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120204. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120205. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120206. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120207. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120208. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120209. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120210. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120211. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120212. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120213. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120214. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120215. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120216. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120217. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120218. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120219. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120220. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120221. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120222. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120223. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120224. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120225. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120226. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120227. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120228. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120229. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120230. 0, 0, 0, 0, 0, 0, 0, 0, 0, 5, 8, 7, 0, 0, 0, 0,
  120231. 0, 0, 8, 9, 9, 0, 0, 0, 0, 0, 0, 7, 9, 9, 0, 0,
  120232. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120233. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120234. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120235. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 7, 9, 9, 0, 0, 0,
  120236. 0, 0, 0, 9, 9,11, 0, 0, 0, 0, 0, 0, 9,11,10, 0,
  120237. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120238. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120239. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120240. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 7, 9, 9, 0, 0,
  120241. 0, 0, 0, 0, 8,11, 9, 0, 0, 0, 0, 0, 0, 9,10,11,
  120242. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120243. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120244. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120245. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120246. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120247. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120248. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120249. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120250. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120251. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120252. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120253. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120254. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120255. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120256. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120257. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120258. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120259. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120260. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120261. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120262. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120263. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120264. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120265. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120266. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120267. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120268. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120269. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120270. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120271. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120272. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120273. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120274. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120275. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120276. 0, 0, 5, 7, 8, 0, 0, 0, 0, 0, 0, 7, 9, 9, 0, 0,
  120277. 0, 0, 0, 0, 8, 9, 9, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120278. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120279. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120280. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120281. 0, 0, 0, 7, 9, 9, 0, 0, 0, 0, 0, 0, 9,11,10, 0,
  120282. 0, 0, 0, 0, 0, 8, 9,11, 0, 0, 0, 0, 0, 0, 0, 0,
  120283. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120284. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120285. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120286. 0, 0, 0, 0, 7, 9, 9, 0, 0, 0, 0, 0, 0, 9,10,11,
  120287. 0, 0, 0, 0, 0, 0, 9,11, 9, 0, 0, 0, 0, 0, 0, 0,
  120288. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120289. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120290. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120291. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120292. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120293. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120294. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120295. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120296. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120297. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120298. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120299. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120300. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120301. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120302. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120303. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120304. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120305. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120306. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120307. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120308. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120309. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120310. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120311. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120312. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120313. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120314. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120315. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120316. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120317. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120318. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120319. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120320. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120321. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120322. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120323. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120324. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120325. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120326. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120327. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120328. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120329. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120330. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120331. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120332. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120333. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120334. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120335. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120336. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120337. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120338. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120339. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120340. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120341. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120342. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120343. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120344. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120345. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120346. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120347. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120348. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120349. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120350. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120351. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120352. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120353. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120354. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120355. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120356. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120357. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120358. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120359. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120360. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120361. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120362. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120363. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120364. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120365. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120366. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120367. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120368. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120369. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120370. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120371. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120372. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  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. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120376. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120377. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120378. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120379. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120380. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120381. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120382. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120383. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120384. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120385. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120386. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120387. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120388. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120389. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120390. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120391. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120392. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120393. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120394. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120395. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120396. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120397. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120398. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120399. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120400. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120401. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120402. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120403. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120404. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120405. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120406. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120407. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120408. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120409. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120410. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120411. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120412. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120413. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120414. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120415. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120416. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120417. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120418. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120419. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120420. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120421. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120422. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  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, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120427. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120428. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120429. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120430. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120431. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120432. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120433. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120434. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120435. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120436. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120437. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120438. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120439. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120440. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120441. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120442. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120443. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120444. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120445. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120446. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120447. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120448. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120449. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120450. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120451. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120452. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120453. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120454. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120455. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120456. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120457. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120458. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120459. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120460. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120461. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120462. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120463. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120464. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120465. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120466. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120467. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120468. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120469. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120470. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120471. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120472. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  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, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120477. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120478. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120479. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120480. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120481. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120482. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120483. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120484. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120485. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120486. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120487. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120488. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120489. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120490. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120491. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120492. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120493. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120494. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120495. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120496. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120497. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120498. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120499. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120500. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120501. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120502. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120503. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120504. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120505. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120506. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120507. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120508. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120509. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120510. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120511. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120512. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120513. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120514. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120515. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120516. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120517. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120518. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120519. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120520. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120521. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120522. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120523. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120524. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120525. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120526. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120527. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120528. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120529. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120530. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120531. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120532. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120533. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120534. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120535. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120536. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120537. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120538. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120539. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120540. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120541. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120542. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120543. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120544. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120545. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120546. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120547. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120548. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120549. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120550. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120551. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120552. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120553. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120554. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120555. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120556. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120557. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120558. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120559. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120560. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120561. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120562. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120563. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120564. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120565. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120566. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120567. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120568. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120569. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120570. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120571. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120572. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120573. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120574. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120575. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120576. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120577. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120578. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120579. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120580. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120581. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120582. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120583. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120584. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120585. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120586. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120587. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120588. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120589. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120590. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120591. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120592. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120593. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120594. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120595. 0,
  120596. };
  120597. static float _vq_quantthresh__16c1_s_p1_0[] = {
  120598. -0.5, 0.5,
  120599. };
  120600. static long _vq_quantmap__16c1_s_p1_0[] = {
  120601. 1, 0, 2,
  120602. };
  120603. static encode_aux_threshmatch _vq_auxt__16c1_s_p1_0 = {
  120604. _vq_quantthresh__16c1_s_p1_0,
  120605. _vq_quantmap__16c1_s_p1_0,
  120606. 3,
  120607. 3
  120608. };
  120609. static static_codebook _16c1_s_p1_0 = {
  120610. 8, 6561,
  120611. _vq_lengthlist__16c1_s_p1_0,
  120612. 1, -535822336, 1611661312, 2, 0,
  120613. _vq_quantlist__16c1_s_p1_0,
  120614. NULL,
  120615. &_vq_auxt__16c1_s_p1_0,
  120616. NULL,
  120617. 0
  120618. };
  120619. static long _vq_quantlist__16c1_s_p2_0[] = {
  120620. 2,
  120621. 1,
  120622. 3,
  120623. 0,
  120624. 4,
  120625. };
  120626. static long _vq_lengthlist__16c1_s_p2_0[] = {
  120627. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120628. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120629. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120630. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120631. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120632. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120633. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120634. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120635. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120636. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120637. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120638. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120639. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120640. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120641. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120642. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120643. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120644. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120645. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120646. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120647. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120648. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120649. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120650. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120651. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120652. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120653. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120654. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120655. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120656. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120657. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120658. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120659. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120660. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120661. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120662. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120663. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120664. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120665. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120666. 0,
  120667. };
  120668. static float _vq_quantthresh__16c1_s_p2_0[] = {
  120669. -1.5, -0.5, 0.5, 1.5,
  120670. };
  120671. static long _vq_quantmap__16c1_s_p2_0[] = {
  120672. 3, 1, 0, 2, 4,
  120673. };
  120674. static encode_aux_threshmatch _vq_auxt__16c1_s_p2_0 = {
  120675. _vq_quantthresh__16c1_s_p2_0,
  120676. _vq_quantmap__16c1_s_p2_0,
  120677. 5,
  120678. 5
  120679. };
  120680. static static_codebook _16c1_s_p2_0 = {
  120681. 4, 625,
  120682. _vq_lengthlist__16c1_s_p2_0,
  120683. 1, -533725184, 1611661312, 3, 0,
  120684. _vq_quantlist__16c1_s_p2_0,
  120685. NULL,
  120686. &_vq_auxt__16c1_s_p2_0,
  120687. NULL,
  120688. 0
  120689. };
  120690. static long _vq_quantlist__16c1_s_p3_0[] = {
  120691. 2,
  120692. 1,
  120693. 3,
  120694. 0,
  120695. 4,
  120696. };
  120697. static long _vq_lengthlist__16c1_s_p3_0[] = {
  120698. 1, 4, 4, 6, 6, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120699. 0, 0, 0, 0, 0, 0, 0, 0, 0, 4, 5, 5, 7, 7, 0, 0,
  120700. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120701. 0, 0, 4, 5, 5, 7, 7, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120702. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 7, 7, 7, 9, 9,
  120703. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120704. 0, 0, 0, 0, 6, 7, 7, 9, 9, 0, 0, 0, 0, 0, 0, 0,
  120705. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120706. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120707. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120708. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120709. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120710. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120711. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120712. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120713. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120714. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120715. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120716. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120717. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120718. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120719. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120720. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120721. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120722. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120723. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120724. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120725. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120726. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120727. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120728. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120729. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120730. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120731. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120732. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120733. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120734. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120735. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120736. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120737. 0,
  120738. };
  120739. static float _vq_quantthresh__16c1_s_p3_0[] = {
  120740. -1.5, -0.5, 0.5, 1.5,
  120741. };
  120742. static long _vq_quantmap__16c1_s_p3_0[] = {
  120743. 3, 1, 0, 2, 4,
  120744. };
  120745. static encode_aux_threshmatch _vq_auxt__16c1_s_p3_0 = {
  120746. _vq_quantthresh__16c1_s_p3_0,
  120747. _vq_quantmap__16c1_s_p3_0,
  120748. 5,
  120749. 5
  120750. };
  120751. static static_codebook _16c1_s_p3_0 = {
  120752. 4, 625,
  120753. _vq_lengthlist__16c1_s_p3_0,
  120754. 1, -533725184, 1611661312, 3, 0,
  120755. _vq_quantlist__16c1_s_p3_0,
  120756. NULL,
  120757. &_vq_auxt__16c1_s_p3_0,
  120758. NULL,
  120759. 0
  120760. };
  120761. static long _vq_quantlist__16c1_s_p4_0[] = {
  120762. 4,
  120763. 3,
  120764. 5,
  120765. 2,
  120766. 6,
  120767. 1,
  120768. 7,
  120769. 0,
  120770. 8,
  120771. };
  120772. static long _vq_lengthlist__16c1_s_p4_0[] = {
  120773. 1, 2, 3, 7, 7, 0, 0, 0, 0, 0, 0, 0, 6, 6, 0, 0,
  120774. 0, 0, 0, 0, 0, 6, 6, 0, 0, 0, 0, 0, 0, 0, 7, 7,
  120775. 0, 0, 0, 0, 0, 0, 0, 7, 7, 0, 0, 0, 0, 0, 0, 0,
  120776. 8, 8, 0, 0, 0, 0, 0, 0, 0, 8, 9, 0, 0, 0, 0, 0,
  120777. 0, 0,10,10, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120778. 0,
  120779. };
  120780. static float _vq_quantthresh__16c1_s_p4_0[] = {
  120781. -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5, 3.5,
  120782. };
  120783. static long _vq_quantmap__16c1_s_p4_0[] = {
  120784. 7, 5, 3, 1, 0, 2, 4, 6,
  120785. 8,
  120786. };
  120787. static encode_aux_threshmatch _vq_auxt__16c1_s_p4_0 = {
  120788. _vq_quantthresh__16c1_s_p4_0,
  120789. _vq_quantmap__16c1_s_p4_0,
  120790. 9,
  120791. 9
  120792. };
  120793. static static_codebook _16c1_s_p4_0 = {
  120794. 2, 81,
  120795. _vq_lengthlist__16c1_s_p4_0,
  120796. 1, -531628032, 1611661312, 4, 0,
  120797. _vq_quantlist__16c1_s_p4_0,
  120798. NULL,
  120799. &_vq_auxt__16c1_s_p4_0,
  120800. NULL,
  120801. 0
  120802. };
  120803. static long _vq_quantlist__16c1_s_p5_0[] = {
  120804. 4,
  120805. 3,
  120806. 5,
  120807. 2,
  120808. 6,
  120809. 1,
  120810. 7,
  120811. 0,
  120812. 8,
  120813. };
  120814. static long _vq_lengthlist__16c1_s_p5_0[] = {
  120815. 1, 3, 3, 5, 5, 6, 6, 8, 8, 0, 0, 0, 7, 7, 7, 7,
  120816. 9, 9, 0, 0, 0, 7, 7, 7, 7, 9, 9, 0, 0, 0, 8, 8,
  120817. 8, 8, 9, 9, 0, 0, 0, 8, 8, 8, 8,10,10, 0, 0, 0,
  120818. 9, 9, 8, 8,10,10, 0, 0, 0, 9, 9, 8, 8,10,10, 0,
  120819. 0, 0,10,10, 9, 9,10,10, 0, 0, 0, 0, 0, 9, 9,10,
  120820. 10,
  120821. };
  120822. static float _vq_quantthresh__16c1_s_p5_0[] = {
  120823. -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5, 3.5,
  120824. };
  120825. static long _vq_quantmap__16c1_s_p5_0[] = {
  120826. 7, 5, 3, 1, 0, 2, 4, 6,
  120827. 8,
  120828. };
  120829. static encode_aux_threshmatch _vq_auxt__16c1_s_p5_0 = {
  120830. _vq_quantthresh__16c1_s_p5_0,
  120831. _vq_quantmap__16c1_s_p5_0,
  120832. 9,
  120833. 9
  120834. };
  120835. static static_codebook _16c1_s_p5_0 = {
  120836. 2, 81,
  120837. _vq_lengthlist__16c1_s_p5_0,
  120838. 1, -531628032, 1611661312, 4, 0,
  120839. _vq_quantlist__16c1_s_p5_0,
  120840. NULL,
  120841. &_vq_auxt__16c1_s_p5_0,
  120842. NULL,
  120843. 0
  120844. };
  120845. static long _vq_quantlist__16c1_s_p6_0[] = {
  120846. 8,
  120847. 7,
  120848. 9,
  120849. 6,
  120850. 10,
  120851. 5,
  120852. 11,
  120853. 4,
  120854. 12,
  120855. 3,
  120856. 13,
  120857. 2,
  120858. 14,
  120859. 1,
  120860. 15,
  120861. 0,
  120862. 16,
  120863. };
  120864. static long _vq_lengthlist__16c1_s_p6_0[] = {
  120865. 1, 3, 3, 6, 6, 8, 8, 9, 9, 9, 9,10,10,11,11,12,
  120866. 12, 0, 0, 0, 7, 7, 8, 8, 9, 9, 9, 9,10,10,11,11,
  120867. 12,12, 0, 0, 0, 7, 7, 8, 8, 9, 9, 9, 9,10,10,11,
  120868. 11,12,12, 0, 0, 0, 8, 8, 8, 9,10, 9,10,10,10,10,
  120869. 11,11,12,12, 0, 0, 0, 8, 8, 9, 9,10,10,10,10,11,
  120870. 11,11,12,12,12, 0, 0, 0, 8, 8, 9, 9,10,10,10,10,
  120871. 11,11,12,12,12,12, 0, 0, 0, 8, 8, 9, 9,10,10,10,
  120872. 10,11,11,12,12,13,13, 0, 0, 0, 9, 9, 9, 9,10,10,
  120873. 10,10,11,11,12,12,13,13, 0, 0, 0, 0, 0, 9, 9,10,
  120874. 10,10,10,11,11,12,12,13,13, 0, 0, 0, 0, 0, 9, 9,
  120875. 10,10,11,11,12,12,12,12,13,13, 0, 0, 0, 0, 0, 9,
  120876. 9,10,10,11,11,12,12,12,12,13,13, 0, 0, 0, 0, 0,
  120877. 10,10,11,10,11,11,12,12,13,13,13,13, 0, 0, 0, 0,
  120878. 0, 0, 0,10,10,11,11,12,12,13,13,13,13, 0, 0, 0,
  120879. 0, 0, 0, 0,11,11,12,12,12,12,13,13,14,14, 0, 0,
  120880. 0, 0, 0, 0, 0,11,11,12,12,12,12,13,13,14,14, 0,
  120881. 0, 0, 0, 0, 0, 0,12,12,12,12,13,13,13,13,14,14,
  120882. 0, 0, 0, 0, 0, 0, 0, 0, 0,12,12,13,13,13,13,14,
  120883. 14,
  120884. };
  120885. static float _vq_quantthresh__16c1_s_p6_0[] = {
  120886. -7.5, -6.5, -5.5, -4.5, -3.5, -2.5, -1.5, -0.5,
  120887. 0.5, 1.5, 2.5, 3.5, 4.5, 5.5, 6.5, 7.5,
  120888. };
  120889. static long _vq_quantmap__16c1_s_p6_0[] = {
  120890. 15, 13, 11, 9, 7, 5, 3, 1,
  120891. 0, 2, 4, 6, 8, 10, 12, 14,
  120892. 16,
  120893. };
  120894. static encode_aux_threshmatch _vq_auxt__16c1_s_p6_0 = {
  120895. _vq_quantthresh__16c1_s_p6_0,
  120896. _vq_quantmap__16c1_s_p6_0,
  120897. 17,
  120898. 17
  120899. };
  120900. static static_codebook _16c1_s_p6_0 = {
  120901. 2, 289,
  120902. _vq_lengthlist__16c1_s_p6_0,
  120903. 1, -529530880, 1611661312, 5, 0,
  120904. _vq_quantlist__16c1_s_p6_0,
  120905. NULL,
  120906. &_vq_auxt__16c1_s_p6_0,
  120907. NULL,
  120908. 0
  120909. };
  120910. static long _vq_quantlist__16c1_s_p7_0[] = {
  120911. 1,
  120912. 0,
  120913. 2,
  120914. };
  120915. static long _vq_lengthlist__16c1_s_p7_0[] = {
  120916. 1, 4, 4, 6, 6, 6, 7, 6, 6, 4, 7, 7,10, 9,10,10,
  120917. 10, 9, 4, 7, 7,10,10,10,11,10,10, 6,10,10,11,11,
  120918. 11,11,10,10, 6,10, 9,11,11,11,11,10,10, 6,10,10,
  120919. 11,11,11,11,10,10, 7,11,11,11,11,11,12,12,11, 6,
  120920. 10,10,11,10,10,11,11,11, 6,10,10,10,11,10,11,11,
  120921. 11,
  120922. };
  120923. static float _vq_quantthresh__16c1_s_p7_0[] = {
  120924. -5.5, 5.5,
  120925. };
  120926. static long _vq_quantmap__16c1_s_p7_0[] = {
  120927. 1, 0, 2,
  120928. };
  120929. static encode_aux_threshmatch _vq_auxt__16c1_s_p7_0 = {
  120930. _vq_quantthresh__16c1_s_p7_0,
  120931. _vq_quantmap__16c1_s_p7_0,
  120932. 3,
  120933. 3
  120934. };
  120935. static static_codebook _16c1_s_p7_0 = {
  120936. 4, 81,
  120937. _vq_lengthlist__16c1_s_p7_0,
  120938. 1, -529137664, 1618345984, 2, 0,
  120939. _vq_quantlist__16c1_s_p7_0,
  120940. NULL,
  120941. &_vq_auxt__16c1_s_p7_0,
  120942. NULL,
  120943. 0
  120944. };
  120945. static long _vq_quantlist__16c1_s_p7_1[] = {
  120946. 5,
  120947. 4,
  120948. 6,
  120949. 3,
  120950. 7,
  120951. 2,
  120952. 8,
  120953. 1,
  120954. 9,
  120955. 0,
  120956. 10,
  120957. };
  120958. static long _vq_lengthlist__16c1_s_p7_1[] = {
  120959. 2, 3, 3, 5, 6, 7, 7, 7, 7, 8, 8,10,10,10, 6, 6,
  120960. 7, 7, 8, 8, 8, 8,10,10,10, 6, 6, 7, 7, 8, 8, 8,
  120961. 8,10,10,10, 7, 7, 7, 7, 8, 8, 8, 8,10,10,10, 7,
  120962. 7, 7, 7, 8, 8, 8, 8,10,10,10, 7, 7, 8, 8, 8, 8,
  120963. 8, 8,10,10,10, 7, 7, 8, 8, 8, 8, 8, 8,10,10,10,
  120964. 8, 8, 8, 8, 8, 8, 9, 9,10,10,10,10,10, 8, 8, 8,
  120965. 8, 9, 9,10,10,10,10,10, 9, 9, 8, 8, 9, 9,10,10,
  120966. 10,10,10, 8, 8, 8, 8, 9, 9,
  120967. };
  120968. static float _vq_quantthresh__16c1_s_p7_1[] = {
  120969. -4.5, -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5,
  120970. 3.5, 4.5,
  120971. };
  120972. static long _vq_quantmap__16c1_s_p7_1[] = {
  120973. 9, 7, 5, 3, 1, 0, 2, 4,
  120974. 6, 8, 10,
  120975. };
  120976. static encode_aux_threshmatch _vq_auxt__16c1_s_p7_1 = {
  120977. _vq_quantthresh__16c1_s_p7_1,
  120978. _vq_quantmap__16c1_s_p7_1,
  120979. 11,
  120980. 11
  120981. };
  120982. static static_codebook _16c1_s_p7_1 = {
  120983. 2, 121,
  120984. _vq_lengthlist__16c1_s_p7_1,
  120985. 1, -531365888, 1611661312, 4, 0,
  120986. _vq_quantlist__16c1_s_p7_1,
  120987. NULL,
  120988. &_vq_auxt__16c1_s_p7_1,
  120989. NULL,
  120990. 0
  120991. };
  120992. static long _vq_quantlist__16c1_s_p8_0[] = {
  120993. 6,
  120994. 5,
  120995. 7,
  120996. 4,
  120997. 8,
  120998. 3,
  120999. 9,
  121000. 2,
  121001. 10,
  121002. 1,
  121003. 11,
  121004. 0,
  121005. 12,
  121006. };
  121007. static long _vq_lengthlist__16c1_s_p8_0[] = {
  121008. 1, 4, 4, 6, 6, 7, 7, 7, 7, 8, 8, 9, 9, 6, 5, 5,
  121009. 7, 8, 8, 9, 8, 8, 9, 9,10,11, 6, 5, 5, 8, 8, 9,
  121010. 9, 8, 8, 9,10,10,11, 0, 8, 8, 8, 9, 9, 9, 9, 9,
  121011. 10,10,11,11, 0, 9, 9, 9, 8, 9, 9, 9, 9,10,10,11,
  121012. 11, 0,13,13, 9, 9,10,10,10,10,11,11,12,12, 0,14,
  121013. 13, 9, 9,10,10,10,10,11,11,12,12, 0, 0, 0,10,10,
  121014. 9, 9,11,11,12,12,13,12, 0, 0, 0,10,10, 9, 9,10,
  121015. 10,12,12,13,13, 0, 0, 0,13,14,11,10,11,11,12,12,
  121016. 13,14, 0, 0, 0,14,14,10,10,11,11,12,12,13,13, 0,
  121017. 0, 0, 0, 0,12,12,12,12,13,13,14,15, 0, 0, 0, 0,
  121018. 0,12,12,12,12,13,13,14,15,
  121019. };
  121020. static float _vq_quantthresh__16c1_s_p8_0[] = {
  121021. -27.5, -22.5, -17.5, -12.5, -7.5, -2.5, 2.5, 7.5,
  121022. 12.5, 17.5, 22.5, 27.5,
  121023. };
  121024. static long _vq_quantmap__16c1_s_p8_0[] = {
  121025. 11, 9, 7, 5, 3, 1, 0, 2,
  121026. 4, 6, 8, 10, 12,
  121027. };
  121028. static encode_aux_threshmatch _vq_auxt__16c1_s_p8_0 = {
  121029. _vq_quantthresh__16c1_s_p8_0,
  121030. _vq_quantmap__16c1_s_p8_0,
  121031. 13,
  121032. 13
  121033. };
  121034. static static_codebook _16c1_s_p8_0 = {
  121035. 2, 169,
  121036. _vq_lengthlist__16c1_s_p8_0,
  121037. 1, -526516224, 1616117760, 4, 0,
  121038. _vq_quantlist__16c1_s_p8_0,
  121039. NULL,
  121040. &_vq_auxt__16c1_s_p8_0,
  121041. NULL,
  121042. 0
  121043. };
  121044. static long _vq_quantlist__16c1_s_p8_1[] = {
  121045. 2,
  121046. 1,
  121047. 3,
  121048. 0,
  121049. 4,
  121050. };
  121051. static long _vq_lengthlist__16c1_s_p8_1[] = {
  121052. 2, 3, 3, 5, 5, 6, 6, 6, 5, 5, 6, 6, 6, 5, 5, 6,
  121053. 6, 6, 5, 5, 6, 6, 6, 5, 5,
  121054. };
  121055. static float _vq_quantthresh__16c1_s_p8_1[] = {
  121056. -1.5, -0.5, 0.5, 1.5,
  121057. };
  121058. static long _vq_quantmap__16c1_s_p8_1[] = {
  121059. 3, 1, 0, 2, 4,
  121060. };
  121061. static encode_aux_threshmatch _vq_auxt__16c1_s_p8_1 = {
  121062. _vq_quantthresh__16c1_s_p8_1,
  121063. _vq_quantmap__16c1_s_p8_1,
  121064. 5,
  121065. 5
  121066. };
  121067. static static_codebook _16c1_s_p8_1 = {
  121068. 2, 25,
  121069. _vq_lengthlist__16c1_s_p8_1,
  121070. 1, -533725184, 1611661312, 3, 0,
  121071. _vq_quantlist__16c1_s_p8_1,
  121072. NULL,
  121073. &_vq_auxt__16c1_s_p8_1,
  121074. NULL,
  121075. 0
  121076. };
  121077. static long _vq_quantlist__16c1_s_p9_0[] = {
  121078. 6,
  121079. 5,
  121080. 7,
  121081. 4,
  121082. 8,
  121083. 3,
  121084. 9,
  121085. 2,
  121086. 10,
  121087. 1,
  121088. 11,
  121089. 0,
  121090. 12,
  121091. };
  121092. static long _vq_lengthlist__16c1_s_p9_0[] = {
  121093. 1, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,
  121094. 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,
  121095. 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,
  121096. 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,
  121097. 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,
  121098. 9, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8,
  121099. 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8,
  121100. 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8,
  121101. 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8,
  121102. 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8,
  121103. 8, 8, 8, 8, 8, 8, 8, 8, 8,
  121104. };
  121105. static float _vq_quantthresh__16c1_s_p9_0[] = {
  121106. -1732.5, -1417.5, -1102.5, -787.5, -472.5, -157.5, 157.5, 472.5,
  121107. 787.5, 1102.5, 1417.5, 1732.5,
  121108. };
  121109. static long _vq_quantmap__16c1_s_p9_0[] = {
  121110. 11, 9, 7, 5, 3, 1, 0, 2,
  121111. 4, 6, 8, 10, 12,
  121112. };
  121113. static encode_aux_threshmatch _vq_auxt__16c1_s_p9_0 = {
  121114. _vq_quantthresh__16c1_s_p9_0,
  121115. _vq_quantmap__16c1_s_p9_0,
  121116. 13,
  121117. 13
  121118. };
  121119. static static_codebook _16c1_s_p9_0 = {
  121120. 2, 169,
  121121. _vq_lengthlist__16c1_s_p9_0,
  121122. 1, -513964032, 1628680192, 4, 0,
  121123. _vq_quantlist__16c1_s_p9_0,
  121124. NULL,
  121125. &_vq_auxt__16c1_s_p9_0,
  121126. NULL,
  121127. 0
  121128. };
  121129. static long _vq_quantlist__16c1_s_p9_1[] = {
  121130. 7,
  121131. 6,
  121132. 8,
  121133. 5,
  121134. 9,
  121135. 4,
  121136. 10,
  121137. 3,
  121138. 11,
  121139. 2,
  121140. 12,
  121141. 1,
  121142. 13,
  121143. 0,
  121144. 14,
  121145. };
  121146. static long _vq_lengthlist__16c1_s_p9_1[] = {
  121147. 1, 4, 4, 4, 4, 8, 8,12,13,14,14,14,14,14,14, 6,
  121148. 6, 6, 6, 6,10, 9,14,14,14,14,14,14,14,14, 7, 6,
  121149. 5, 6, 6,10, 9,12,13,13,13,13,13,13,13,13, 7, 7,
  121150. 9, 9,11,11,12,13,13,13,13,13,13,13,13, 7, 7, 8,
  121151. 8,11,12,13,13,13,13,13,13,13,13,13,12,12,10,10,
  121152. 13,12,13,13,13,13,13,13,13,13,13,12,12,10,10,13,
  121153. 13,13,13,13,13,13,13,13,13,13,13,13,13,12,13,12,
  121154. 13,13,13,13,13,13,13,13,13,13,13,13,12,13,13,13,
  121155. 13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,
  121156. 13,13,13,13,13,13,13,13,13,13,13,13,12,13,13,13,
  121157. 13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,
  121158. 13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,
  121159. 13,13,13,13,13,13,13,13,13,12,13,13,13,13,13,13,
  121160. 13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,
  121161. 13,
  121162. };
  121163. static float _vq_quantthresh__16c1_s_p9_1[] = {
  121164. -136.5, -115.5, -94.5, -73.5, -52.5, -31.5, -10.5, 10.5,
  121165. 31.5, 52.5, 73.5, 94.5, 115.5, 136.5,
  121166. };
  121167. static long _vq_quantmap__16c1_s_p9_1[] = {
  121168. 13, 11, 9, 7, 5, 3, 1, 0,
  121169. 2, 4, 6, 8, 10, 12, 14,
  121170. };
  121171. static encode_aux_threshmatch _vq_auxt__16c1_s_p9_1 = {
  121172. _vq_quantthresh__16c1_s_p9_1,
  121173. _vq_quantmap__16c1_s_p9_1,
  121174. 15,
  121175. 15
  121176. };
  121177. static static_codebook _16c1_s_p9_1 = {
  121178. 2, 225,
  121179. _vq_lengthlist__16c1_s_p9_1,
  121180. 1, -520986624, 1620377600, 4, 0,
  121181. _vq_quantlist__16c1_s_p9_1,
  121182. NULL,
  121183. &_vq_auxt__16c1_s_p9_1,
  121184. NULL,
  121185. 0
  121186. };
  121187. static long _vq_quantlist__16c1_s_p9_2[] = {
  121188. 10,
  121189. 9,
  121190. 11,
  121191. 8,
  121192. 12,
  121193. 7,
  121194. 13,
  121195. 6,
  121196. 14,
  121197. 5,
  121198. 15,
  121199. 4,
  121200. 16,
  121201. 3,
  121202. 17,
  121203. 2,
  121204. 18,
  121205. 1,
  121206. 19,
  121207. 0,
  121208. 20,
  121209. };
  121210. static long _vq_lengthlist__16c1_s_p9_2[] = {
  121211. 1, 4, 4, 6, 6, 7, 7, 8, 7, 8, 8, 9, 9, 9, 9,10,
  121212. 10,10, 9,10,10,11,12,12, 8, 8, 8, 8, 9, 9, 9, 9,
  121213. 10,10,10,10,10,11,11,10,12,11,11,13,11, 7, 7, 8,
  121214. 8, 8, 8, 9, 9, 9,10,10,10,10, 9,10,10,11,11,12,
  121215. 11,11, 8, 8, 8, 8, 9, 9,10,10,10,10,11,11,11,11,
  121216. 11,11,11,12,11,12,12, 8, 8, 9, 9, 9, 9, 9,10,10,
  121217. 10,10,10,10,11,11,11,11,11,11,12,11, 9, 9, 9, 9,
  121218. 10,10,10,10,11,10,11,11,11,11,11,11,12,12,12,12,
  121219. 11, 9, 9, 9, 9,10,10,10,10,11,11,11,11,11,11,11,
  121220. 11,11,12,12,12,13, 9,10,10, 9,11,10,10,10,10,11,
  121221. 11,11,11,11,10,11,12,11,12,12,11,12,11,10, 9,10,
  121222. 10,11,10,11,11,11,11,11,11,11,11,11,12,12,11,12,
  121223. 12,12,10,10,10,11,10,11,11,11,11,11,11,11,11,11,
  121224. 11,11,12,13,12,12,11, 9,10,10,11,11,10,11,11,11,
  121225. 12,11,11,11,11,11,12,12,13,13,12,13,10,10,12,10,
  121226. 11,11,11,11,11,11,11,11,11,12,12,11,13,12,12,12,
  121227. 12,13,12,11,11,11,11,11,11,12,11,12,11,11,11,11,
  121228. 12,12,13,12,11,12,12,11,11,11,11,11,12,11,11,11,
  121229. 11,12,11,11,12,11,12,13,13,12,12,12,12,11,11,11,
  121230. 11,11,12,11,11,12,11,12,11,11,11,11,13,12,12,12,
  121231. 12,13,11,11,11,12,12,11,11,11,12,11,12,12,12,11,
  121232. 12,13,12,11,11,12,12,11,12,11,11,11,12,12,11,12,
  121233. 11,11,11,12,12,12,12,13,12,13,12,12,12,12,11,11,
  121234. 12,11,11,11,11,11,11,12,12,12,13,12,11,13,13,12,
  121235. 12,11,12,10,11,11,11,11,12,11,12,12,11,12,12,13,
  121236. 12,12,13,12,12,12,12,12,11,12,12,12,11,12,11,11,
  121237. 11,12,13,12,13,13,13,13,13,12,13,13,12,12,13,11,
  121238. 11,11,11,11,12,11,11,12,11,
  121239. };
  121240. static float _vq_quantthresh__16c1_s_p9_2[] = {
  121241. -9.5, -8.5, -7.5, -6.5, -5.5, -4.5, -3.5, -2.5,
  121242. -1.5, -0.5, 0.5, 1.5, 2.5, 3.5, 4.5, 5.5,
  121243. 6.5, 7.5, 8.5, 9.5,
  121244. };
  121245. static long _vq_quantmap__16c1_s_p9_2[] = {
  121246. 19, 17, 15, 13, 11, 9, 7, 5,
  121247. 3, 1, 0, 2, 4, 6, 8, 10,
  121248. 12, 14, 16, 18, 20,
  121249. };
  121250. static encode_aux_threshmatch _vq_auxt__16c1_s_p9_2 = {
  121251. _vq_quantthresh__16c1_s_p9_2,
  121252. _vq_quantmap__16c1_s_p9_2,
  121253. 21,
  121254. 21
  121255. };
  121256. static static_codebook _16c1_s_p9_2 = {
  121257. 2, 441,
  121258. _vq_lengthlist__16c1_s_p9_2,
  121259. 1, -529268736, 1611661312, 5, 0,
  121260. _vq_quantlist__16c1_s_p9_2,
  121261. NULL,
  121262. &_vq_auxt__16c1_s_p9_2,
  121263. NULL,
  121264. 0
  121265. };
  121266. static long _huff_lengthlist__16c1_s_short[] = {
  121267. 5, 6,17, 8,12, 9,10,10,12,13, 5, 2,17, 4, 9, 5,
  121268. 7, 8,11,13,16,16,16,16,16,16,16,16,16,16, 6, 4,
  121269. 16, 5,10, 5, 7,10,14,16,13, 9,16,11, 8, 7, 8, 9,
  121270. 13,16, 7, 4,16, 5, 7, 4, 6, 8,11,13, 8, 6,16, 7,
  121271. 8, 5, 5, 7, 9,13, 9, 8,16, 9, 8, 6, 6, 7, 9,13,
  121272. 11,11,16,10,10, 7, 7, 7, 9,13,13,13,16,13,13, 9,
  121273. 9, 9,10,13,
  121274. };
  121275. static static_codebook _huff_book__16c1_s_short = {
  121276. 2, 100,
  121277. _huff_lengthlist__16c1_s_short,
  121278. 0, 0, 0, 0, 0,
  121279. NULL,
  121280. NULL,
  121281. NULL,
  121282. NULL,
  121283. 0
  121284. };
  121285. static long _huff_lengthlist__16c2_s_long[] = {
  121286. 4, 7, 9, 9, 9, 8, 9,10,15,19, 5, 4, 5, 6, 7, 7,
  121287. 8, 9,14,16, 6, 5, 4, 5, 6, 7, 8,10,12,19, 7, 6,
  121288. 5, 4, 5, 6, 7, 9,11,18, 8, 7, 6, 5, 5, 5, 7, 9,
  121289. 10,17, 8, 7, 7, 5, 5, 5, 6, 7,12,18, 8, 8, 8, 7,
  121290. 7, 5, 5, 7,12,18, 8, 9,10, 9, 9, 7, 6, 7,12,17,
  121291. 14,18,16,16,15,12,11,10,12,18,15,17,18,18,18,15,
  121292. 14,14,16,18,
  121293. };
  121294. static static_codebook _huff_book__16c2_s_long = {
  121295. 2, 100,
  121296. _huff_lengthlist__16c2_s_long,
  121297. 0, 0, 0, 0, 0,
  121298. NULL,
  121299. NULL,
  121300. NULL,
  121301. NULL,
  121302. 0
  121303. };
  121304. static long _vq_quantlist__16c2_s_p1_0[] = {
  121305. 1,
  121306. 0,
  121307. 2,
  121308. };
  121309. static long _vq_lengthlist__16c2_s_p1_0[] = {
  121310. 1, 3, 3, 0, 0, 0, 0, 0, 0, 4, 5, 5, 0, 0, 0, 0,
  121311. 0, 0, 4, 5, 5, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121312. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121313. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121314. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121315. 0,
  121316. };
  121317. static float _vq_quantthresh__16c2_s_p1_0[] = {
  121318. -0.5, 0.5,
  121319. };
  121320. static long _vq_quantmap__16c2_s_p1_0[] = {
  121321. 1, 0, 2,
  121322. };
  121323. static encode_aux_threshmatch _vq_auxt__16c2_s_p1_0 = {
  121324. _vq_quantthresh__16c2_s_p1_0,
  121325. _vq_quantmap__16c2_s_p1_0,
  121326. 3,
  121327. 3
  121328. };
  121329. static static_codebook _16c2_s_p1_0 = {
  121330. 4, 81,
  121331. _vq_lengthlist__16c2_s_p1_0,
  121332. 1, -535822336, 1611661312, 2, 0,
  121333. _vq_quantlist__16c2_s_p1_0,
  121334. NULL,
  121335. &_vq_auxt__16c2_s_p1_0,
  121336. NULL,
  121337. 0
  121338. };
  121339. static long _vq_quantlist__16c2_s_p2_0[] = {
  121340. 2,
  121341. 1,
  121342. 3,
  121343. 0,
  121344. 4,
  121345. };
  121346. static long _vq_lengthlist__16c2_s_p2_0[] = {
  121347. 2, 4, 3, 7, 7, 0, 0, 0, 7, 8, 0, 0, 0, 8, 8, 0,
  121348. 0, 0, 8, 8, 0, 0, 0, 8, 8, 4, 5, 4, 8, 8, 0, 0,
  121349. 0, 8, 8, 0, 0, 0, 8, 8, 0, 0, 0, 9, 9, 0, 0, 0,
  121350. 9, 9, 4, 4, 5, 8, 8, 0, 0, 0, 8, 8, 0, 0, 0, 8,
  121351. 8, 0, 0, 0, 9, 9, 0, 0, 0, 9, 9, 7, 8, 8,10,10,
  121352. 0, 0, 0,12,11, 0, 0, 0,11,11, 0, 0, 0,14,13, 0,
  121353. 0, 0,14,13, 7, 8, 8, 9,10, 0, 0, 0,11,12, 0, 0,
  121354. 0,11,11, 0, 0, 0,14,14, 0, 0, 0,13,14, 0, 0, 0,
  121355. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121356. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121357. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121358. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121359. 0, 0, 0, 0, 0, 0, 0, 0, 8, 8, 8,11,11, 0, 0, 0,
  121360. 11,11, 0, 0, 0,12,11, 0, 0, 0,12,12, 0, 0, 0,13,
  121361. 13, 8, 8, 8,11,11, 0, 0, 0,11,11, 0, 0, 0,11,12,
  121362. 0, 0, 0,12,13, 0, 0, 0,13,13, 0, 0, 0, 0, 0, 0,
  121363. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121364. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121365. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121366. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121367. 0, 0, 0, 0, 0, 8, 8, 8,12,11, 0, 0, 0,12,11, 0,
  121368. 0, 0,11,11, 0, 0, 0,13,13, 0, 0, 0,13,12, 8, 8,
  121369. 8,11,12, 0, 0, 0,11,12, 0, 0, 0,11,11, 0, 0, 0,
  121370. 13,13, 0, 0, 0,12,13, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121371. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121372. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121373. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121374. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121375. 0, 0, 8, 9, 9,14,13, 0, 0, 0,13,12, 0, 0, 0,13,
  121376. 13, 0, 0, 0,13,12, 0, 0, 0,13,13, 8, 9, 9,13,14,
  121377. 0, 0, 0,12,13, 0, 0, 0,13,13, 0, 0, 0,12,13, 0,
  121378. 0, 0,13,13, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121379. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121380. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121381. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121382. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 8,
  121383. 9, 9,14,13, 0, 0, 0,13,13, 0, 0, 0,13,12, 0, 0,
  121384. 0,13,13, 0, 0, 0,13,12, 8, 9, 9,14,14, 0, 0, 0,
  121385. 13,13, 0, 0, 0,12,13, 0, 0, 0,13,13, 0, 0, 0,12,
  121386. 13,
  121387. };
  121388. static float _vq_quantthresh__16c2_s_p2_0[] = {
  121389. -1.5, -0.5, 0.5, 1.5,
  121390. };
  121391. static long _vq_quantmap__16c2_s_p2_0[] = {
  121392. 3, 1, 0, 2, 4,
  121393. };
  121394. static encode_aux_threshmatch _vq_auxt__16c2_s_p2_0 = {
  121395. _vq_quantthresh__16c2_s_p2_0,
  121396. _vq_quantmap__16c2_s_p2_0,
  121397. 5,
  121398. 5
  121399. };
  121400. static static_codebook _16c2_s_p2_0 = {
  121401. 4, 625,
  121402. _vq_lengthlist__16c2_s_p2_0,
  121403. 1, -533725184, 1611661312, 3, 0,
  121404. _vq_quantlist__16c2_s_p2_0,
  121405. NULL,
  121406. &_vq_auxt__16c2_s_p2_0,
  121407. NULL,
  121408. 0
  121409. };
  121410. static long _vq_quantlist__16c2_s_p3_0[] = {
  121411. 4,
  121412. 3,
  121413. 5,
  121414. 2,
  121415. 6,
  121416. 1,
  121417. 7,
  121418. 0,
  121419. 8,
  121420. };
  121421. static long _vq_lengthlist__16c2_s_p3_0[] = {
  121422. 1, 3, 3, 6, 6, 7, 7, 8, 8, 0, 0, 0, 6, 6, 7, 7,
  121423. 9, 9, 0, 0, 0, 6, 6, 7, 7, 9, 9, 0, 0, 0, 7, 7,
  121424. 8, 8,10,10, 0, 0, 0, 7, 7, 8, 8,10,10, 0, 0, 0,
  121425. 7, 7, 9, 9,10,10, 0, 0, 0, 7, 7, 9, 9,10,10, 0,
  121426. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121427. 0,
  121428. };
  121429. static float _vq_quantthresh__16c2_s_p3_0[] = {
  121430. -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5, 3.5,
  121431. };
  121432. static long _vq_quantmap__16c2_s_p3_0[] = {
  121433. 7, 5, 3, 1, 0, 2, 4, 6,
  121434. 8,
  121435. };
  121436. static encode_aux_threshmatch _vq_auxt__16c2_s_p3_0 = {
  121437. _vq_quantthresh__16c2_s_p3_0,
  121438. _vq_quantmap__16c2_s_p3_0,
  121439. 9,
  121440. 9
  121441. };
  121442. static static_codebook _16c2_s_p3_0 = {
  121443. 2, 81,
  121444. _vq_lengthlist__16c2_s_p3_0,
  121445. 1, -531628032, 1611661312, 4, 0,
  121446. _vq_quantlist__16c2_s_p3_0,
  121447. NULL,
  121448. &_vq_auxt__16c2_s_p3_0,
  121449. NULL,
  121450. 0
  121451. };
  121452. static long _vq_quantlist__16c2_s_p4_0[] = {
  121453. 8,
  121454. 7,
  121455. 9,
  121456. 6,
  121457. 10,
  121458. 5,
  121459. 11,
  121460. 4,
  121461. 12,
  121462. 3,
  121463. 13,
  121464. 2,
  121465. 14,
  121466. 1,
  121467. 15,
  121468. 0,
  121469. 16,
  121470. };
  121471. static long _vq_lengthlist__16c2_s_p4_0[] = {
  121472. 2, 3, 3, 5, 5, 6, 6, 7, 7, 7, 7, 8, 8, 9, 9,10,
  121473. 10, 0, 0, 0, 6, 6, 7, 7, 8, 8, 8, 8, 9, 9,10,10,
  121474. 11,11, 0, 0, 0, 6, 6, 7, 7, 8, 8, 8, 8, 9, 9,10,
  121475. 10,10,11, 0, 0, 0, 6, 6, 8, 8, 8, 8, 9, 9,10,10,
  121476. 10,11,11,11, 0, 0, 0, 6, 6, 8, 8, 9, 9, 9, 9,10,
  121477. 10,11,11,11,11, 0, 0, 0, 7, 7, 8, 8, 9, 9, 9, 9,
  121478. 10,10,11,11,12,12, 0, 0, 0, 7, 7, 8, 8, 9, 9, 9,
  121479. 9,10,10,11,11,12,12, 0, 0, 0, 7, 7, 8, 8, 9, 9,
  121480. 10,10,11,11,12,12,12,12, 0, 0, 0, 0, 0, 8, 8, 9,
  121481. 9,10,10,11,11,12,12,12,12, 0, 0, 0, 0, 0, 0, 0,
  121482. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121483. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121484. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121485. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121486. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121487. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121488. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121489. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121490. 0,
  121491. };
  121492. static float _vq_quantthresh__16c2_s_p4_0[] = {
  121493. -7.5, -6.5, -5.5, -4.5, -3.5, -2.5, -1.5, -0.5,
  121494. 0.5, 1.5, 2.5, 3.5, 4.5, 5.5, 6.5, 7.5,
  121495. };
  121496. static long _vq_quantmap__16c2_s_p4_0[] = {
  121497. 15, 13, 11, 9, 7, 5, 3, 1,
  121498. 0, 2, 4, 6, 8, 10, 12, 14,
  121499. 16,
  121500. };
  121501. static encode_aux_threshmatch _vq_auxt__16c2_s_p4_0 = {
  121502. _vq_quantthresh__16c2_s_p4_0,
  121503. _vq_quantmap__16c2_s_p4_0,
  121504. 17,
  121505. 17
  121506. };
  121507. static static_codebook _16c2_s_p4_0 = {
  121508. 2, 289,
  121509. _vq_lengthlist__16c2_s_p4_0,
  121510. 1, -529530880, 1611661312, 5, 0,
  121511. _vq_quantlist__16c2_s_p4_0,
  121512. NULL,
  121513. &_vq_auxt__16c2_s_p4_0,
  121514. NULL,
  121515. 0
  121516. };
  121517. static long _vq_quantlist__16c2_s_p5_0[] = {
  121518. 1,
  121519. 0,
  121520. 2,
  121521. };
  121522. static long _vq_lengthlist__16c2_s_p5_0[] = {
  121523. 1, 4, 4, 5, 7, 7, 6, 7, 7, 4, 6, 6,10,10,10,10,
  121524. 10,10, 4, 7, 6,10,10,10,10,10,10, 5, 9, 9, 9,12,
  121525. 11,10,11,12, 7,10,10,12,12,12,12,12,12, 7,10,10,
  121526. 11,12,12,12,12,13, 6,10,10,10,12,12,10,12,12, 7,
  121527. 10,10,11,13,12,12,12,12, 7,10,10,11,12,12,12,12,
  121528. 12,
  121529. };
  121530. static float _vq_quantthresh__16c2_s_p5_0[] = {
  121531. -5.5, 5.5,
  121532. };
  121533. static long _vq_quantmap__16c2_s_p5_0[] = {
  121534. 1, 0, 2,
  121535. };
  121536. static encode_aux_threshmatch _vq_auxt__16c2_s_p5_0 = {
  121537. _vq_quantthresh__16c2_s_p5_0,
  121538. _vq_quantmap__16c2_s_p5_0,
  121539. 3,
  121540. 3
  121541. };
  121542. static static_codebook _16c2_s_p5_0 = {
  121543. 4, 81,
  121544. _vq_lengthlist__16c2_s_p5_0,
  121545. 1, -529137664, 1618345984, 2, 0,
  121546. _vq_quantlist__16c2_s_p5_0,
  121547. NULL,
  121548. &_vq_auxt__16c2_s_p5_0,
  121549. NULL,
  121550. 0
  121551. };
  121552. static long _vq_quantlist__16c2_s_p5_1[] = {
  121553. 5,
  121554. 4,
  121555. 6,
  121556. 3,
  121557. 7,
  121558. 2,
  121559. 8,
  121560. 1,
  121561. 9,
  121562. 0,
  121563. 10,
  121564. };
  121565. static long _vq_lengthlist__16c2_s_p5_1[] = {
  121566. 2, 3, 3, 6, 6, 7, 7, 7, 7, 8, 8,11,11,11, 6, 6,
  121567. 7, 7, 8, 8, 8, 8,11,11,11, 6, 6, 7, 7, 8, 8, 8,
  121568. 8,11,11,11, 6, 6, 8, 8, 8, 8, 9, 9,11,11,11, 6,
  121569. 6, 8, 8, 8, 8, 9, 9,11,11,11, 7, 7, 8, 8, 8, 8,
  121570. 8, 8,11,11,11, 7, 7, 8, 8, 8, 8, 8, 9,11,11,11,
  121571. 8, 8, 8, 8, 8, 8, 8, 8,11,11,11,11,11, 8, 8, 8,
  121572. 8, 8, 8,11,11,11,11,11, 8, 8, 8, 8, 8, 8,11,11,
  121573. 11,11,11, 7, 7, 8, 8, 8, 8,
  121574. };
  121575. static float _vq_quantthresh__16c2_s_p5_1[] = {
  121576. -4.5, -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5,
  121577. 3.5, 4.5,
  121578. };
  121579. static long _vq_quantmap__16c2_s_p5_1[] = {
  121580. 9, 7, 5, 3, 1, 0, 2, 4,
  121581. 6, 8, 10,
  121582. };
  121583. static encode_aux_threshmatch _vq_auxt__16c2_s_p5_1 = {
  121584. _vq_quantthresh__16c2_s_p5_1,
  121585. _vq_quantmap__16c2_s_p5_1,
  121586. 11,
  121587. 11
  121588. };
  121589. static static_codebook _16c2_s_p5_1 = {
  121590. 2, 121,
  121591. _vq_lengthlist__16c2_s_p5_1,
  121592. 1, -531365888, 1611661312, 4, 0,
  121593. _vq_quantlist__16c2_s_p5_1,
  121594. NULL,
  121595. &_vq_auxt__16c2_s_p5_1,
  121596. NULL,
  121597. 0
  121598. };
  121599. static long _vq_quantlist__16c2_s_p6_0[] = {
  121600. 6,
  121601. 5,
  121602. 7,
  121603. 4,
  121604. 8,
  121605. 3,
  121606. 9,
  121607. 2,
  121608. 10,
  121609. 1,
  121610. 11,
  121611. 0,
  121612. 12,
  121613. };
  121614. static long _vq_lengthlist__16c2_s_p6_0[] = {
  121615. 1, 4, 4, 7, 6, 8, 8, 9, 9,10,10,11,11, 5, 5, 5,
  121616. 7, 7, 9, 9, 9, 9,11,11,12,12, 6, 5, 5, 7, 7, 9,
  121617. 9,10,10,11,11,12,12, 0, 6, 6, 7, 7, 9, 9,10,10,
  121618. 11,11,12,12, 0, 7, 7, 7, 7, 9, 9,10,10,11,12,12,
  121619. 12, 0,11,11, 8, 8,10,10,11,11,12,12,13,13, 0,11,
  121620. 12, 8, 8,10,10,11,11,12,12,13,13, 0, 0, 0, 0, 0,
  121621. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121622. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121623. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121624. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121625. 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121626. };
  121627. static float _vq_quantthresh__16c2_s_p6_0[] = {
  121628. -27.5, -22.5, -17.5, -12.5, -7.5, -2.5, 2.5, 7.5,
  121629. 12.5, 17.5, 22.5, 27.5,
  121630. };
  121631. static long _vq_quantmap__16c2_s_p6_0[] = {
  121632. 11, 9, 7, 5, 3, 1, 0, 2,
  121633. 4, 6, 8, 10, 12,
  121634. };
  121635. static encode_aux_threshmatch _vq_auxt__16c2_s_p6_0 = {
  121636. _vq_quantthresh__16c2_s_p6_0,
  121637. _vq_quantmap__16c2_s_p6_0,
  121638. 13,
  121639. 13
  121640. };
  121641. static static_codebook _16c2_s_p6_0 = {
  121642. 2, 169,
  121643. _vq_lengthlist__16c2_s_p6_0,
  121644. 1, -526516224, 1616117760, 4, 0,
  121645. _vq_quantlist__16c2_s_p6_0,
  121646. NULL,
  121647. &_vq_auxt__16c2_s_p6_0,
  121648. NULL,
  121649. 0
  121650. };
  121651. static long _vq_quantlist__16c2_s_p6_1[] = {
  121652. 2,
  121653. 1,
  121654. 3,
  121655. 0,
  121656. 4,
  121657. };
  121658. static long _vq_lengthlist__16c2_s_p6_1[] = {
  121659. 2, 3, 3, 5, 5, 6, 6, 6, 5, 5, 6, 6, 6, 5, 5, 6,
  121660. 6, 6, 5, 5, 6, 6, 6, 5, 5,
  121661. };
  121662. static float _vq_quantthresh__16c2_s_p6_1[] = {
  121663. -1.5, -0.5, 0.5, 1.5,
  121664. };
  121665. static long _vq_quantmap__16c2_s_p6_1[] = {
  121666. 3, 1, 0, 2, 4,
  121667. };
  121668. static encode_aux_threshmatch _vq_auxt__16c2_s_p6_1 = {
  121669. _vq_quantthresh__16c2_s_p6_1,
  121670. _vq_quantmap__16c2_s_p6_1,
  121671. 5,
  121672. 5
  121673. };
  121674. static static_codebook _16c2_s_p6_1 = {
  121675. 2, 25,
  121676. _vq_lengthlist__16c2_s_p6_1,
  121677. 1, -533725184, 1611661312, 3, 0,
  121678. _vq_quantlist__16c2_s_p6_1,
  121679. NULL,
  121680. &_vq_auxt__16c2_s_p6_1,
  121681. NULL,
  121682. 0
  121683. };
  121684. static long _vq_quantlist__16c2_s_p7_0[] = {
  121685. 6,
  121686. 5,
  121687. 7,
  121688. 4,
  121689. 8,
  121690. 3,
  121691. 9,
  121692. 2,
  121693. 10,
  121694. 1,
  121695. 11,
  121696. 0,
  121697. 12,
  121698. };
  121699. static long _vq_lengthlist__16c2_s_p7_0[] = {
  121700. 1, 4, 4, 7, 7, 8, 8, 9, 9,10,10,11,11, 5, 5, 5,
  121701. 8, 8, 9, 9,10,10,11,11,12,12, 6, 5, 5, 8, 8, 9,
  121702. 9,10,10,11,11,12,13,18, 6, 6, 7, 7, 9, 9,10,10,
  121703. 12,12,13,13,18, 6, 6, 7, 7, 9, 9,10,10,12,12,13,
  121704. 13,18,11,10, 8, 8,10,10,11,11,12,12,13,13,18,11,
  121705. 11, 8, 8,10,10,11,11,12,13,13,13,18,18,18,10,11,
  121706. 11,11,12,12,13,13,14,14,18,18,18,11,11,11,11,12,
  121707. 12,13,13,14,14,18,18,18,14,14,12,12,12,12,14,14,
  121708. 15,14,18,18,18,15,15,11,12,12,12,13,13,15,15,18,
  121709. 18,18,18,18,13,13,13,13,13,14,17,16,18,18,18,18,
  121710. 18,13,14,13,13,14,13,15,14,
  121711. };
  121712. static float _vq_quantthresh__16c2_s_p7_0[] = {
  121713. -60.5, -49.5, -38.5, -27.5, -16.5, -5.5, 5.5, 16.5,
  121714. 27.5, 38.5, 49.5, 60.5,
  121715. };
  121716. static long _vq_quantmap__16c2_s_p7_0[] = {
  121717. 11, 9, 7, 5, 3, 1, 0, 2,
  121718. 4, 6, 8, 10, 12,
  121719. };
  121720. static encode_aux_threshmatch _vq_auxt__16c2_s_p7_0 = {
  121721. _vq_quantthresh__16c2_s_p7_0,
  121722. _vq_quantmap__16c2_s_p7_0,
  121723. 13,
  121724. 13
  121725. };
  121726. static static_codebook _16c2_s_p7_0 = {
  121727. 2, 169,
  121728. _vq_lengthlist__16c2_s_p7_0,
  121729. 1, -523206656, 1618345984, 4, 0,
  121730. _vq_quantlist__16c2_s_p7_0,
  121731. NULL,
  121732. &_vq_auxt__16c2_s_p7_0,
  121733. NULL,
  121734. 0
  121735. };
  121736. static long _vq_quantlist__16c2_s_p7_1[] = {
  121737. 5,
  121738. 4,
  121739. 6,
  121740. 3,
  121741. 7,
  121742. 2,
  121743. 8,
  121744. 1,
  121745. 9,
  121746. 0,
  121747. 10,
  121748. };
  121749. static long _vq_lengthlist__16c2_s_p7_1[] = {
  121750. 2, 4, 4, 6, 6, 7, 7, 7, 7, 7, 7, 9, 9, 9, 6, 6,
  121751. 7, 7, 8, 8, 8, 8, 9, 9, 9, 6, 6, 7, 7, 8, 8, 8,
  121752. 8, 9, 9, 9, 7, 7, 7, 7, 8, 8, 8, 8, 9, 9, 9, 7,
  121753. 7, 7, 7, 8, 8, 8, 8, 9, 9, 9, 7, 7, 7, 7, 8, 8,
  121754. 8, 8, 9, 9, 9, 7, 7, 7, 7, 7, 7, 8, 8, 9, 9, 9,
  121755. 7, 7, 8, 8, 7, 7, 8, 8, 9, 9, 9, 9, 9, 7, 7, 7,
  121756. 7, 8, 8, 9, 9, 9, 9, 9, 8, 8, 7, 7, 8, 8, 9, 9,
  121757. 9, 9, 9, 7, 7, 7, 7, 8, 8,
  121758. };
  121759. static float _vq_quantthresh__16c2_s_p7_1[] = {
  121760. -4.5, -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5,
  121761. 3.5, 4.5,
  121762. };
  121763. static long _vq_quantmap__16c2_s_p7_1[] = {
  121764. 9, 7, 5, 3, 1, 0, 2, 4,
  121765. 6, 8, 10,
  121766. };
  121767. static encode_aux_threshmatch _vq_auxt__16c2_s_p7_1 = {
  121768. _vq_quantthresh__16c2_s_p7_1,
  121769. _vq_quantmap__16c2_s_p7_1,
  121770. 11,
  121771. 11
  121772. };
  121773. static static_codebook _16c2_s_p7_1 = {
  121774. 2, 121,
  121775. _vq_lengthlist__16c2_s_p7_1,
  121776. 1, -531365888, 1611661312, 4, 0,
  121777. _vq_quantlist__16c2_s_p7_1,
  121778. NULL,
  121779. &_vq_auxt__16c2_s_p7_1,
  121780. NULL,
  121781. 0
  121782. };
  121783. static long _vq_quantlist__16c2_s_p8_0[] = {
  121784. 7,
  121785. 6,
  121786. 8,
  121787. 5,
  121788. 9,
  121789. 4,
  121790. 10,
  121791. 3,
  121792. 11,
  121793. 2,
  121794. 12,
  121795. 1,
  121796. 13,
  121797. 0,
  121798. 14,
  121799. };
  121800. static long _vq_lengthlist__16c2_s_p8_0[] = {
  121801. 1, 4, 4, 7, 6, 7, 7, 6, 6, 8, 8, 9, 9,10,10, 6,
  121802. 6, 6, 8, 8, 9, 8, 8, 8, 9, 9,11,10,11,11, 7, 6,
  121803. 6, 8, 8, 9, 8, 7, 7, 9, 9,10,10,12,11,14, 8, 8,
  121804. 8, 9, 9, 9, 9, 9,10, 9,10,10,11,13,14, 8, 8, 8,
  121805. 8, 9, 9, 8, 8, 9, 9,10,10,11,12,14,13,11, 9, 9,
  121806. 9, 9, 9, 9, 9,10,11,10,13,12,14,11,13, 8, 9, 9,
  121807. 9, 9, 9,10,10,11,10,13,12,14,14,14, 8, 9, 9, 9,
  121808. 11,11,11,11,11,12,13,13,14,14,14, 9, 8, 9, 9,10,
  121809. 10,12,10,11,12,12,14,14,14,14,11,12,10,10,12,12,
  121810. 12,12,13,14,12,12,14,14,14,12,12, 9,10,11,11,12,
  121811. 14,12,14,14,14,14,14,14,14,14,11,11,12,11,12,14,
  121812. 14,14,14,14,14,14,14,14,14,12,11,11,11,11,14,14,
  121813. 14,14,14,14,14,14,14,14,14,14,13,12,14,14,14,14,
  121814. 14,14,14,14,14,14,14,14,14,12,12,12,13,14,14,13,
  121815. 13,
  121816. };
  121817. static float _vq_quantthresh__16c2_s_p8_0[] = {
  121818. -136.5, -115.5, -94.5, -73.5, -52.5, -31.5, -10.5, 10.5,
  121819. 31.5, 52.5, 73.5, 94.5, 115.5, 136.5,
  121820. };
  121821. static long _vq_quantmap__16c2_s_p8_0[] = {
  121822. 13, 11, 9, 7, 5, 3, 1, 0,
  121823. 2, 4, 6, 8, 10, 12, 14,
  121824. };
  121825. static encode_aux_threshmatch _vq_auxt__16c2_s_p8_0 = {
  121826. _vq_quantthresh__16c2_s_p8_0,
  121827. _vq_quantmap__16c2_s_p8_0,
  121828. 15,
  121829. 15
  121830. };
  121831. static static_codebook _16c2_s_p8_0 = {
  121832. 2, 225,
  121833. _vq_lengthlist__16c2_s_p8_0,
  121834. 1, -520986624, 1620377600, 4, 0,
  121835. _vq_quantlist__16c2_s_p8_0,
  121836. NULL,
  121837. &_vq_auxt__16c2_s_p8_0,
  121838. NULL,
  121839. 0
  121840. };
  121841. static long _vq_quantlist__16c2_s_p8_1[] = {
  121842. 10,
  121843. 9,
  121844. 11,
  121845. 8,
  121846. 12,
  121847. 7,
  121848. 13,
  121849. 6,
  121850. 14,
  121851. 5,
  121852. 15,
  121853. 4,
  121854. 16,
  121855. 3,
  121856. 17,
  121857. 2,
  121858. 18,
  121859. 1,
  121860. 19,
  121861. 0,
  121862. 20,
  121863. };
  121864. static long _vq_lengthlist__16c2_s_p8_1[] = {
  121865. 2, 4, 4, 6, 6, 7, 7, 7, 7, 8, 7, 8, 8, 8, 8, 8,
  121866. 8, 8, 8, 8, 8,11,12,11, 7, 7, 8, 8, 8, 8, 9, 9,
  121867. 9, 9, 9, 9, 9, 9, 9,10, 9, 9,11,11,10, 7, 7, 8,
  121868. 8, 8, 8, 9, 8, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,11,
  121869. 11,11, 8, 7, 8, 8, 9, 9, 9, 9, 9, 9,10,10, 9,10,
  121870. 10, 9,10,10,11,11,12, 8, 8, 8, 8, 9, 9, 9, 9, 9,
  121871. 9, 9, 9,10, 9,10,10,10,10,11,11,11, 8, 8, 9, 9,
  121872. 9, 9, 9, 9, 9,10,10,10,10,10,10,10,10,10,11,11,
  121873. 11, 8, 8, 9, 8, 9, 9, 9, 9,10, 9, 9, 9,10,10,10,
  121874. 10, 9,10,11,11,11, 9, 9, 9, 9,10, 9, 9, 9,10,10,
  121875. 9,10, 9,10,10,10,10,10,11,12,11,11,11, 9, 9, 9,
  121876. 9, 9,10,10, 9,10,10,10,10,10,10,10,10,12,11,13,
  121877. 13,11, 9, 9, 9, 9,10,10, 9,10,10,10,10,11,10,10,
  121878. 10,10,11,12,11,12,11, 9, 9, 9,10,10, 9,10,10,10,
  121879. 10,10,10,10,10,10,10,11,11,11,12,11, 9,10,10,10,
  121880. 10,10,10,10,10,10,10,10,10,10,10,10,11,12,12,12,
  121881. 11,11,11,10, 9,10,10,10,10,10,10,10,10,11,10,10,
  121882. 10,11,11,11,11,11,11,11,10,10,10,11,10,10,10,10,
  121883. 10,10,10,10,10,10,11,11,11,11,12,12,11,10,10,10,
  121884. 10,10,10,10,10,11,10,10,10,11,10,12,11,11,12,11,
  121885. 11,11,10,10,10,10,10,11,10,10,10,10,10,11,10,10,
  121886. 11,11,11,12,11,12,11,11,12,10,10,10,10,10,10,10,
  121887. 11,10,10,11,10,12,11,11,11,12,11,11,11,11,10,10,
  121888. 10,10,10,10,10,11,11,11,10,11,12,11,11,11,12,11,
  121889. 12,11,12,10,11,10,10,10,10,11,10,10,10,10,10,10,
  121890. 12,11,11,11,11,11,12,12,10,10,10,10,10,11,10,10,
  121891. 11,10,11,11,11,11,11,11,11,11,11,11,11,11,12,11,
  121892. 10,11,10,10,10,10,10,10,10,
  121893. };
  121894. static float _vq_quantthresh__16c2_s_p8_1[] = {
  121895. -9.5, -8.5, -7.5, -6.5, -5.5, -4.5, -3.5, -2.5,
  121896. -1.5, -0.5, 0.5, 1.5, 2.5, 3.5, 4.5, 5.5,
  121897. 6.5, 7.5, 8.5, 9.5,
  121898. };
  121899. static long _vq_quantmap__16c2_s_p8_1[] = {
  121900. 19, 17, 15, 13, 11, 9, 7, 5,
  121901. 3, 1, 0, 2, 4, 6, 8, 10,
  121902. 12, 14, 16, 18, 20,
  121903. };
  121904. static encode_aux_threshmatch _vq_auxt__16c2_s_p8_1 = {
  121905. _vq_quantthresh__16c2_s_p8_1,
  121906. _vq_quantmap__16c2_s_p8_1,
  121907. 21,
  121908. 21
  121909. };
  121910. static static_codebook _16c2_s_p8_1 = {
  121911. 2, 441,
  121912. _vq_lengthlist__16c2_s_p8_1,
  121913. 1, -529268736, 1611661312, 5, 0,
  121914. _vq_quantlist__16c2_s_p8_1,
  121915. NULL,
  121916. &_vq_auxt__16c2_s_p8_1,
  121917. NULL,
  121918. 0
  121919. };
  121920. static long _vq_quantlist__16c2_s_p9_0[] = {
  121921. 6,
  121922. 5,
  121923. 7,
  121924. 4,
  121925. 8,
  121926. 3,
  121927. 9,
  121928. 2,
  121929. 10,
  121930. 1,
  121931. 11,
  121932. 0,
  121933. 12,
  121934. };
  121935. static long _vq_lengthlist__16c2_s_p9_0[] = {
  121936. 1, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,
  121937. 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,
  121938. 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,
  121939. 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,
  121940. 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,
  121941. 9, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8,
  121942. 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8,
  121943. 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8,
  121944. 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8,
  121945. 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8,
  121946. 8, 8, 8, 8, 8, 8, 8, 8, 8,
  121947. };
  121948. static float _vq_quantthresh__16c2_s_p9_0[] = {
  121949. -5120.5, -4189.5, -3258.5, -2327.5, -1396.5, -465.5, 465.5, 1396.5,
  121950. 2327.5, 3258.5, 4189.5, 5120.5,
  121951. };
  121952. static long _vq_quantmap__16c2_s_p9_0[] = {
  121953. 11, 9, 7, 5, 3, 1, 0, 2,
  121954. 4, 6, 8, 10, 12,
  121955. };
  121956. static encode_aux_threshmatch _vq_auxt__16c2_s_p9_0 = {
  121957. _vq_quantthresh__16c2_s_p9_0,
  121958. _vq_quantmap__16c2_s_p9_0,
  121959. 13,
  121960. 13
  121961. };
  121962. static static_codebook _16c2_s_p9_0 = {
  121963. 2, 169,
  121964. _vq_lengthlist__16c2_s_p9_0,
  121965. 1, -510275072, 1631393792, 4, 0,
  121966. _vq_quantlist__16c2_s_p9_0,
  121967. NULL,
  121968. &_vq_auxt__16c2_s_p9_0,
  121969. NULL,
  121970. 0
  121971. };
  121972. static long _vq_quantlist__16c2_s_p9_1[] = {
  121973. 8,
  121974. 7,
  121975. 9,
  121976. 6,
  121977. 10,
  121978. 5,
  121979. 11,
  121980. 4,
  121981. 12,
  121982. 3,
  121983. 13,
  121984. 2,
  121985. 14,
  121986. 1,
  121987. 15,
  121988. 0,
  121989. 16,
  121990. };
  121991. static long _vq_lengthlist__16c2_s_p9_1[] = {
  121992. 1, 5, 5, 9, 8, 7, 7, 7, 6,10,11,11,11,11,11,11,
  121993. 11, 8, 7, 6, 8, 8,10, 9,10,10,10, 9,11,10,10,10,
  121994. 10,10, 8, 6, 6, 8, 8, 9, 8, 9, 8, 9,10,10,10,10,
  121995. 10,10,10,10, 8,10, 9, 9, 9, 9,10,10,10,10,10,10,
  121996. 10,10,10,10,10, 8, 9, 9, 9,10,10, 9,10,10,10,10,
  121997. 10,10,10,10,10,10,10,10, 9, 8, 9, 9,10,10,10,10,
  121998. 10,10,10,10,10,10,10,10, 9, 8, 8, 9, 9,10,10,10,
  121999. 10,10,10,10,10,10,10,10,10,10, 9,10, 9, 9,10,10,
  122000. 10,10,10,10,10,10,10,10,10,10,10, 9, 8, 9, 9,10,
  122001. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10, 9,
  122002. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  122003. 8,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  122004. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  122005. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  122006. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  122007. 10,10,10,10, 9,10, 9,10,10,10,10,10,10,10,10,10,
  122008. 10,10,10,10,10,10,10,10,10, 9,10,10,10,10,10,10,
  122009. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  122010. 10,
  122011. };
  122012. static float _vq_quantthresh__16c2_s_p9_1[] = {
  122013. -367.5, -318.5, -269.5, -220.5, -171.5, -122.5, -73.5, -24.5,
  122014. 24.5, 73.5, 122.5, 171.5, 220.5, 269.5, 318.5, 367.5,
  122015. };
  122016. static long _vq_quantmap__16c2_s_p9_1[] = {
  122017. 15, 13, 11, 9, 7, 5, 3, 1,
  122018. 0, 2, 4, 6, 8, 10, 12, 14,
  122019. 16,
  122020. };
  122021. static encode_aux_threshmatch _vq_auxt__16c2_s_p9_1 = {
  122022. _vq_quantthresh__16c2_s_p9_1,
  122023. _vq_quantmap__16c2_s_p9_1,
  122024. 17,
  122025. 17
  122026. };
  122027. static static_codebook _16c2_s_p9_1 = {
  122028. 2, 289,
  122029. _vq_lengthlist__16c2_s_p9_1,
  122030. 1, -518488064, 1622704128, 5, 0,
  122031. _vq_quantlist__16c2_s_p9_1,
  122032. NULL,
  122033. &_vq_auxt__16c2_s_p9_1,
  122034. NULL,
  122035. 0
  122036. };
  122037. static long _vq_quantlist__16c2_s_p9_2[] = {
  122038. 13,
  122039. 12,
  122040. 14,
  122041. 11,
  122042. 15,
  122043. 10,
  122044. 16,
  122045. 9,
  122046. 17,
  122047. 8,
  122048. 18,
  122049. 7,
  122050. 19,
  122051. 6,
  122052. 20,
  122053. 5,
  122054. 21,
  122055. 4,
  122056. 22,
  122057. 3,
  122058. 23,
  122059. 2,
  122060. 24,
  122061. 1,
  122062. 25,
  122063. 0,
  122064. 26,
  122065. };
  122066. static long _vq_lengthlist__16c2_s_p9_2[] = {
  122067. 1, 4, 4, 5, 5, 6, 6, 6, 6, 6, 7, 7, 7, 7, 7, 7,
  122068. 7, 7, 7, 7, 8, 7, 8, 7, 7, 4, 4,
  122069. };
  122070. static float _vq_quantthresh__16c2_s_p9_2[] = {
  122071. -12.5, -11.5, -10.5, -9.5, -8.5, -7.5, -6.5, -5.5,
  122072. -4.5, -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5,
  122073. 3.5, 4.5, 5.5, 6.5, 7.5, 8.5, 9.5, 10.5,
  122074. 11.5, 12.5,
  122075. };
  122076. static long _vq_quantmap__16c2_s_p9_2[] = {
  122077. 25, 23, 21, 19, 17, 15, 13, 11,
  122078. 9, 7, 5, 3, 1, 0, 2, 4,
  122079. 6, 8, 10, 12, 14, 16, 18, 20,
  122080. 22, 24, 26,
  122081. };
  122082. static encode_aux_threshmatch _vq_auxt__16c2_s_p9_2 = {
  122083. _vq_quantthresh__16c2_s_p9_2,
  122084. _vq_quantmap__16c2_s_p9_2,
  122085. 27,
  122086. 27
  122087. };
  122088. static static_codebook _16c2_s_p9_2 = {
  122089. 1, 27,
  122090. _vq_lengthlist__16c2_s_p9_2,
  122091. 1, -528875520, 1611661312, 5, 0,
  122092. _vq_quantlist__16c2_s_p9_2,
  122093. NULL,
  122094. &_vq_auxt__16c2_s_p9_2,
  122095. NULL,
  122096. 0
  122097. };
  122098. static long _huff_lengthlist__16c2_s_short[] = {
  122099. 7,10,11,11,11,14,15,15,17,14, 8, 6, 7, 7, 8, 9,
  122100. 11,11,14,17, 9, 6, 6, 6, 7, 7,10,11,15,16, 9, 6,
  122101. 6, 4, 4, 5, 8, 9,12,16,10, 6, 6, 4, 4, 4, 6, 9,
  122102. 13,16,10, 7, 6, 5, 4, 3, 5, 7,13,16,11, 9, 8, 7,
  122103. 6, 5, 5, 6,12,15,10,10,10, 9, 7, 6, 6, 7,11,15,
  122104. 13,13,13,13,11,10,10, 9,12,16,16,16,16,14,16,15,
  122105. 15,12,14,14,
  122106. };
  122107. static static_codebook _huff_book__16c2_s_short = {
  122108. 2, 100,
  122109. _huff_lengthlist__16c2_s_short,
  122110. 0, 0, 0, 0, 0,
  122111. NULL,
  122112. NULL,
  122113. NULL,
  122114. NULL,
  122115. 0
  122116. };
  122117. static long _vq_quantlist__8c0_s_p1_0[] = {
  122118. 1,
  122119. 0,
  122120. 2,
  122121. };
  122122. static long _vq_lengthlist__8c0_s_p1_0[] = {
  122123. 1, 5, 4, 0, 0, 0, 0, 0, 0, 5, 7, 7, 0, 0, 0, 0,
  122124. 0, 0, 5, 7, 7, 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, 5, 8, 8, 0, 0, 0, 0, 0, 0, 7, 8, 9, 0, 0, 0,
  122129. 0, 0, 0, 7, 8, 9, 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, 5, 8, 8, 0, 0, 0, 0, 0, 0, 7, 9, 9, 0, 0,
  122134. 0, 0, 0, 0, 7, 9, 8, 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, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122139. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122140. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122141. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122142. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122143. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122144. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122145. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122146. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122147. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122148. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122149. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122150. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122151. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122152. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122153. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122154. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122155. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122156. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122157. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122158. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122159. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122160. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122161. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122162. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122163. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122164. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122165. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122166. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122167. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122168. 0, 0, 0, 0, 0, 0, 0, 0, 0, 5, 8, 8, 0, 0, 0, 0,
  122169. 0, 0, 8,10,10, 0, 0, 0, 0, 0, 0, 8, 9, 9, 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, 7,10, 9, 0, 0, 0,
  122174. 0, 0, 0, 8, 9,11, 0, 0, 0, 0, 0, 0, 9,11,11, 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, 7, 9,10, 0, 0,
  122179. 0, 0, 0, 0, 9,11,10, 0, 0, 0, 0, 0, 0, 9,11,11,
  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, 5, 8, 8, 0, 0, 0, 0, 0, 0, 8, 9, 9, 0, 0,
  122215. 0, 0, 0, 0, 8, 9,10, 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, 7, 9, 9, 0, 0, 0, 0, 0, 0, 9,11,11, 0,
  122220. 0, 0, 0, 0, 0, 9,10,11, 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, 7, 9,10, 0, 0, 0, 0, 0, 0, 9,11,11,
  122225. 0, 0, 0, 0, 0, 0, 8,11, 9, 0, 0, 0, 0, 0, 0, 0,
  122226. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122227. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122228. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122229. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122230. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122231. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122232. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122233. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122234. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122235. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122236. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122237. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122238. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122239. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122240. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122241. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122242. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122243. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122244. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122245. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122246. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122247. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122248. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122249. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122250. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122251. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122252. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122253. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122254. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122255. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122256. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122257. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122258. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122259. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122260. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122261. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122262. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122263. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122264. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122265. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122266. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122267. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122268. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122269. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122270. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122271. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122272. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122273. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122274. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122275. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122276. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122277. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122278. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122279. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122280. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122281. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122282. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122283. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122284. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122285. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122286. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122287. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122288. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122289. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122290. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122291. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122292. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122293. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122294. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122295. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122296. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122297. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122298. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122299. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122300. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122301. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122302. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122303. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122304. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122305. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122306. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122307. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122308. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122309. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122310. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122311. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122312. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122313. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122314. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122315. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122316. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122317. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122318. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122319. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122320. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122321. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122322. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122323. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122324. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122325. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122326. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122327. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122328. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122329. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122330. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122331. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122332. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122333. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122334. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122335. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122336. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122337. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122338. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122339. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122340. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122341. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122342. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122343. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122344. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122345. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122346. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122347. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122348. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122349. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122350. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122351. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122352. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122353. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122354. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122355. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122356. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122357. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122358. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122359. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122360. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122361. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122362. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122363. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122364. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122365. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122366. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122367. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122368. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122369. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122370. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122371. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122372. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122373. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122374. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122375. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122376. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122377. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122378. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122379. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122380. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122381. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122382. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122383. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122384. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122385. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122386. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122387. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122388. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122389. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122390. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122391. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122392. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122393. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122394. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122395. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122396. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122397. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122398. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122399. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122400. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122401. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122402. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122403. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122404. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122405. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122406. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122407. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122408. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122409. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122410. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122411. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122412. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122413. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122414. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122415. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122416. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122417. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122418. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122419. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122420. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122421. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122422. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122423. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122424. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122425. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122426. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122427. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122428. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122429. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122430. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122431. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122432. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122433. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122434. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122435. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122436. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122437. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122438. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122439. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122440. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122441. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122442. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122443. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122444. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122445. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122446. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122447. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122448. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122449. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122450. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122451. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122452. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122453. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122454. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122455. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122456. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122457. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122458. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122459. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122460. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122461. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122462. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122463. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122464. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122465. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122466. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122467. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122468. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122469. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122470. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122471. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122472. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122473. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122474. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122475. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122476. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122477. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122478. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122479. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122480. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122481. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122482. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122483. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122484. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122485. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122486. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122487. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122488. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 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, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122529. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122530. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122531. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122532. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122533. 0,
  122534. };
  122535. static float _vq_quantthresh__8c0_s_p1_0[] = {
  122536. -0.5, 0.5,
  122537. };
  122538. static long _vq_quantmap__8c0_s_p1_0[] = {
  122539. 1, 0, 2,
  122540. };
  122541. static encode_aux_threshmatch _vq_auxt__8c0_s_p1_0 = {
  122542. _vq_quantthresh__8c0_s_p1_0,
  122543. _vq_quantmap__8c0_s_p1_0,
  122544. 3,
  122545. 3
  122546. };
  122547. static static_codebook _8c0_s_p1_0 = {
  122548. 8, 6561,
  122549. _vq_lengthlist__8c0_s_p1_0,
  122550. 1, -535822336, 1611661312, 2, 0,
  122551. _vq_quantlist__8c0_s_p1_0,
  122552. NULL,
  122553. &_vq_auxt__8c0_s_p1_0,
  122554. NULL,
  122555. 0
  122556. };
  122557. static long _vq_quantlist__8c0_s_p2_0[] = {
  122558. 2,
  122559. 1,
  122560. 3,
  122561. 0,
  122562. 4,
  122563. };
  122564. static long _vq_lengthlist__8c0_s_p2_0[] = {
  122565. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122566. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122567. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122568. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122569. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122570. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122571. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122572. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122573. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122574. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122575. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122576. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122577. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122578. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122579. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122580. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122581. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122582. 0, 0, 0, 0, 0, 0, 0, 0, 0, 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, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122600. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122601. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122602. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122603. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122604. 0,
  122605. };
  122606. static float _vq_quantthresh__8c0_s_p2_0[] = {
  122607. -1.5, -0.5, 0.5, 1.5,
  122608. };
  122609. static long _vq_quantmap__8c0_s_p2_0[] = {
  122610. 3, 1, 0, 2, 4,
  122611. };
  122612. static encode_aux_threshmatch _vq_auxt__8c0_s_p2_0 = {
  122613. _vq_quantthresh__8c0_s_p2_0,
  122614. _vq_quantmap__8c0_s_p2_0,
  122615. 5,
  122616. 5
  122617. };
  122618. static static_codebook _8c0_s_p2_0 = {
  122619. 4, 625,
  122620. _vq_lengthlist__8c0_s_p2_0,
  122621. 1, -533725184, 1611661312, 3, 0,
  122622. _vq_quantlist__8c0_s_p2_0,
  122623. NULL,
  122624. &_vq_auxt__8c0_s_p2_0,
  122625. NULL,
  122626. 0
  122627. };
  122628. static long _vq_quantlist__8c0_s_p3_0[] = {
  122629. 2,
  122630. 1,
  122631. 3,
  122632. 0,
  122633. 4,
  122634. };
  122635. static long _vq_lengthlist__8c0_s_p3_0[] = {
  122636. 1, 4, 4, 6, 6, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122637. 0, 0, 0, 0, 0, 0, 0, 0, 0, 4, 5, 6, 7, 7, 0, 0,
  122638. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122639. 0, 0, 4, 5, 5, 7, 7, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122640. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 6, 7, 7, 8, 8,
  122641. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122642. 0, 0, 0, 0, 6, 7, 7, 8, 8, 0, 0, 0, 0, 0, 0, 0,
  122643. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122644. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122645. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122646. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122647. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122648. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122649. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122650. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122651. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122652. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122653. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122654. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122655. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122656. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122657. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122658. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122659. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122660. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122661. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122662. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122663. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122664. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122665. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122666. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122667. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122668. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122669. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122670. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122671. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122672. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122673. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122674. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122675. 0,
  122676. };
  122677. static float _vq_quantthresh__8c0_s_p3_0[] = {
  122678. -1.5, -0.5, 0.5, 1.5,
  122679. };
  122680. static long _vq_quantmap__8c0_s_p3_0[] = {
  122681. 3, 1, 0, 2, 4,
  122682. };
  122683. static encode_aux_threshmatch _vq_auxt__8c0_s_p3_0 = {
  122684. _vq_quantthresh__8c0_s_p3_0,
  122685. _vq_quantmap__8c0_s_p3_0,
  122686. 5,
  122687. 5
  122688. };
  122689. static static_codebook _8c0_s_p3_0 = {
  122690. 4, 625,
  122691. _vq_lengthlist__8c0_s_p3_0,
  122692. 1, -533725184, 1611661312, 3, 0,
  122693. _vq_quantlist__8c0_s_p3_0,
  122694. NULL,
  122695. &_vq_auxt__8c0_s_p3_0,
  122696. NULL,
  122697. 0
  122698. };
  122699. static long _vq_quantlist__8c0_s_p4_0[] = {
  122700. 4,
  122701. 3,
  122702. 5,
  122703. 2,
  122704. 6,
  122705. 1,
  122706. 7,
  122707. 0,
  122708. 8,
  122709. };
  122710. static long _vq_lengthlist__8c0_s_p4_0[] = {
  122711. 1, 2, 3, 7, 7, 0, 0, 0, 0, 0, 0, 0, 6, 6, 0, 0,
  122712. 0, 0, 0, 0, 0, 6, 6, 0, 0, 0, 0, 0, 0, 0, 7, 7,
  122713. 0, 0, 0, 0, 0, 0, 0, 7, 7, 0, 0, 0, 0, 0, 0, 0,
  122714. 8, 8, 0, 0, 0, 0, 0, 0, 0, 9, 8, 0, 0, 0, 0, 0,
  122715. 0, 0,10,10, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122716. 0,
  122717. };
  122718. static float _vq_quantthresh__8c0_s_p4_0[] = {
  122719. -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5, 3.5,
  122720. };
  122721. static long _vq_quantmap__8c0_s_p4_0[] = {
  122722. 7, 5, 3, 1, 0, 2, 4, 6,
  122723. 8,
  122724. };
  122725. static encode_aux_threshmatch _vq_auxt__8c0_s_p4_0 = {
  122726. _vq_quantthresh__8c0_s_p4_0,
  122727. _vq_quantmap__8c0_s_p4_0,
  122728. 9,
  122729. 9
  122730. };
  122731. static static_codebook _8c0_s_p4_0 = {
  122732. 2, 81,
  122733. _vq_lengthlist__8c0_s_p4_0,
  122734. 1, -531628032, 1611661312, 4, 0,
  122735. _vq_quantlist__8c0_s_p4_0,
  122736. NULL,
  122737. &_vq_auxt__8c0_s_p4_0,
  122738. NULL,
  122739. 0
  122740. };
  122741. static long _vq_quantlist__8c0_s_p5_0[] = {
  122742. 4,
  122743. 3,
  122744. 5,
  122745. 2,
  122746. 6,
  122747. 1,
  122748. 7,
  122749. 0,
  122750. 8,
  122751. };
  122752. static long _vq_lengthlist__8c0_s_p5_0[] = {
  122753. 1, 3, 3, 5, 5, 7, 6, 8, 8, 0, 0, 0, 7, 7, 7, 7,
  122754. 8, 8, 0, 0, 0, 7, 7, 7, 7, 8, 9, 0, 0, 0, 8, 8,
  122755. 8, 8, 9, 9, 0, 0, 0, 8, 8, 8, 8, 9, 9, 0, 0, 0,
  122756. 9, 9, 8, 8,10,10, 0, 0, 0, 9, 9, 8, 8,10,10, 0,
  122757. 0, 0,10,10, 9, 9,10,10, 0, 0, 0, 0, 0, 9, 9,10,
  122758. 10,
  122759. };
  122760. static float _vq_quantthresh__8c0_s_p5_0[] = {
  122761. -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5, 3.5,
  122762. };
  122763. static long _vq_quantmap__8c0_s_p5_0[] = {
  122764. 7, 5, 3, 1, 0, 2, 4, 6,
  122765. 8,
  122766. };
  122767. static encode_aux_threshmatch _vq_auxt__8c0_s_p5_0 = {
  122768. _vq_quantthresh__8c0_s_p5_0,
  122769. _vq_quantmap__8c0_s_p5_0,
  122770. 9,
  122771. 9
  122772. };
  122773. static static_codebook _8c0_s_p5_0 = {
  122774. 2, 81,
  122775. _vq_lengthlist__8c0_s_p5_0,
  122776. 1, -531628032, 1611661312, 4, 0,
  122777. _vq_quantlist__8c0_s_p5_0,
  122778. NULL,
  122779. &_vq_auxt__8c0_s_p5_0,
  122780. NULL,
  122781. 0
  122782. };
  122783. static long _vq_quantlist__8c0_s_p6_0[] = {
  122784. 8,
  122785. 7,
  122786. 9,
  122787. 6,
  122788. 10,
  122789. 5,
  122790. 11,
  122791. 4,
  122792. 12,
  122793. 3,
  122794. 13,
  122795. 2,
  122796. 14,
  122797. 1,
  122798. 15,
  122799. 0,
  122800. 16,
  122801. };
  122802. static long _vq_lengthlist__8c0_s_p6_0[] = {
  122803. 1, 3, 3, 6, 6, 8, 8, 9, 9, 8, 8,10, 9,10,10,11,
  122804. 11, 0, 0, 0, 7, 7, 8, 8, 9, 9, 9, 9,10,10,11,11,
  122805. 11,12, 0, 0, 0, 7, 7, 8, 8, 9, 9, 9, 9,10,10,11,
  122806. 11,12,11, 0, 0, 0, 8, 8, 9, 9,10,10, 9, 9,10,10,
  122807. 11,11,12,12, 0, 0, 0, 8, 8, 9, 9,10,10, 9, 9,11,
  122808. 10,11,11,12,12, 0, 0, 0, 9, 9, 9, 9,10,10,10,10,
  122809. 11,11,11,12,12,12, 0, 0, 0, 9, 9, 9, 9,10,10,10,
  122810. 10,11,11,12,12,13,13, 0, 0, 0,10,10,10,10,11,11,
  122811. 10,10,11,11,12,12,13,13, 0, 0, 0, 0, 0,10, 9,10,
  122812. 11,10,10,11,11,12,12,13,13, 0, 0, 0, 0, 0, 9, 9,
  122813. 10, 9,10,11,12,12,13,13,14,13, 0, 0, 0, 0, 0, 9,
  122814. 9, 9,10,10,10,11,11,13,12,13,13, 0, 0, 0, 0, 0,
  122815. 10,10,10,10,11,11,12,12,13,13,14,14, 0, 0, 0, 0,
  122816. 0, 0, 0,10,10,11,11,12,12,13,13,13,14, 0, 0, 0,
  122817. 0, 0, 0, 0,11,11,11,11,12,12,13,14,14,14, 0, 0,
  122818. 0, 0, 0, 0, 0,11,11,11,11,12,12,13,13,14,13, 0,
  122819. 0, 0, 0, 0, 0, 0,11,11,12,12,13,13,14,14,14,14,
  122820. 0, 0, 0, 0, 0, 0, 0, 0, 0,12,12,12,12,13,13,14,
  122821. 14,
  122822. };
  122823. static float _vq_quantthresh__8c0_s_p6_0[] = {
  122824. -7.5, -6.5, -5.5, -4.5, -3.5, -2.5, -1.5, -0.5,
  122825. 0.5, 1.5, 2.5, 3.5, 4.5, 5.5, 6.5, 7.5,
  122826. };
  122827. static long _vq_quantmap__8c0_s_p6_0[] = {
  122828. 15, 13, 11, 9, 7, 5, 3, 1,
  122829. 0, 2, 4, 6, 8, 10, 12, 14,
  122830. 16,
  122831. };
  122832. static encode_aux_threshmatch _vq_auxt__8c0_s_p6_0 = {
  122833. _vq_quantthresh__8c0_s_p6_0,
  122834. _vq_quantmap__8c0_s_p6_0,
  122835. 17,
  122836. 17
  122837. };
  122838. static static_codebook _8c0_s_p6_0 = {
  122839. 2, 289,
  122840. _vq_lengthlist__8c0_s_p6_0,
  122841. 1, -529530880, 1611661312, 5, 0,
  122842. _vq_quantlist__8c0_s_p6_0,
  122843. NULL,
  122844. &_vq_auxt__8c0_s_p6_0,
  122845. NULL,
  122846. 0
  122847. };
  122848. static long _vq_quantlist__8c0_s_p7_0[] = {
  122849. 1,
  122850. 0,
  122851. 2,
  122852. };
  122853. static long _vq_lengthlist__8c0_s_p7_0[] = {
  122854. 1, 4, 4, 7, 6, 6, 7, 6, 6, 4, 7, 7,11, 9,10,12,
  122855. 9,10, 4, 7, 7,10,10,10,11, 9, 9, 6,11,10,11,11,
  122856. 12,11,11,11, 6,10,10,11,11,12,11,10,10, 6, 9,10,
  122857. 11,11,11,11,10,10, 7,10,11,12,11,11,12,11,12, 6,
  122858. 9, 9,10, 9, 9,11,10,10, 6, 9, 9,10,10,10,11,10,
  122859. 10,
  122860. };
  122861. static float _vq_quantthresh__8c0_s_p7_0[] = {
  122862. -5.5, 5.5,
  122863. };
  122864. static long _vq_quantmap__8c0_s_p7_0[] = {
  122865. 1, 0, 2,
  122866. };
  122867. static encode_aux_threshmatch _vq_auxt__8c0_s_p7_0 = {
  122868. _vq_quantthresh__8c0_s_p7_0,
  122869. _vq_quantmap__8c0_s_p7_0,
  122870. 3,
  122871. 3
  122872. };
  122873. static static_codebook _8c0_s_p7_0 = {
  122874. 4, 81,
  122875. _vq_lengthlist__8c0_s_p7_0,
  122876. 1, -529137664, 1618345984, 2, 0,
  122877. _vq_quantlist__8c0_s_p7_0,
  122878. NULL,
  122879. &_vq_auxt__8c0_s_p7_0,
  122880. NULL,
  122881. 0
  122882. };
  122883. static long _vq_quantlist__8c0_s_p7_1[] = {
  122884. 5,
  122885. 4,
  122886. 6,
  122887. 3,
  122888. 7,
  122889. 2,
  122890. 8,
  122891. 1,
  122892. 9,
  122893. 0,
  122894. 10,
  122895. };
  122896. static long _vq_lengthlist__8c0_s_p7_1[] = {
  122897. 1, 3, 3, 6, 6, 8, 8, 9, 9, 9, 9,10,10,10, 7, 7,
  122898. 8, 8, 9, 9, 9, 9,10,10, 9, 7, 7, 8, 8, 9, 9, 9,
  122899. 9,10,10,10, 8, 8, 9, 9, 9, 9, 9, 9,10,10,10, 8,
  122900. 8, 9, 9, 9, 9, 8, 9,10,10,10, 8, 8, 9, 9, 9,10,
  122901. 10,10,10,10,10, 9, 9, 9, 9, 9, 9,10,10,11,10,11,
  122902. 9, 9, 9, 9,10,10,10,10,11,11,11,10,10, 9, 9,10,
  122903. 10,10, 9,11,10,10,10,10,10,10, 9, 9,10,10,11,11,
  122904. 10,10,10, 9, 9, 9,10,10,10,
  122905. };
  122906. static float _vq_quantthresh__8c0_s_p7_1[] = {
  122907. -4.5, -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5,
  122908. 3.5, 4.5,
  122909. };
  122910. static long _vq_quantmap__8c0_s_p7_1[] = {
  122911. 9, 7, 5, 3, 1, 0, 2, 4,
  122912. 6, 8, 10,
  122913. };
  122914. static encode_aux_threshmatch _vq_auxt__8c0_s_p7_1 = {
  122915. _vq_quantthresh__8c0_s_p7_1,
  122916. _vq_quantmap__8c0_s_p7_1,
  122917. 11,
  122918. 11
  122919. };
  122920. static static_codebook _8c0_s_p7_1 = {
  122921. 2, 121,
  122922. _vq_lengthlist__8c0_s_p7_1,
  122923. 1, -531365888, 1611661312, 4, 0,
  122924. _vq_quantlist__8c0_s_p7_1,
  122925. NULL,
  122926. &_vq_auxt__8c0_s_p7_1,
  122927. NULL,
  122928. 0
  122929. };
  122930. static long _vq_quantlist__8c0_s_p8_0[] = {
  122931. 6,
  122932. 5,
  122933. 7,
  122934. 4,
  122935. 8,
  122936. 3,
  122937. 9,
  122938. 2,
  122939. 10,
  122940. 1,
  122941. 11,
  122942. 0,
  122943. 12,
  122944. };
  122945. static long _vq_lengthlist__8c0_s_p8_0[] = {
  122946. 1, 4, 4, 7, 6, 7, 7, 7, 7, 8, 8, 9, 9, 7, 6, 6,
  122947. 7, 7, 8, 8, 7, 7, 8, 9,10,10, 7, 6, 6, 7, 7, 8,
  122948. 7, 7, 7, 9, 9,10,12, 0, 8, 8, 8, 8, 8, 9, 8, 8,
  122949. 9, 9,10,10, 0, 8, 8, 8, 8, 8, 9, 8, 9, 9, 9,11,
  122950. 10, 0, 0,13, 9, 8, 9, 9, 9, 9,10,10,11,11, 0,13,
  122951. 0, 9, 9, 9, 9, 9, 9,11,10,11,11, 0, 0, 0, 8, 9,
  122952. 10, 9,10,10,13,11,12,12, 0, 0, 0, 8, 9, 9, 9,10,
  122953. 10,13,12,12,13, 0, 0, 0,12, 0,10,10,12,11,10,11,
  122954. 12,12, 0, 0, 0,13,13,10,10,10,11,12, 0,13, 0, 0,
  122955. 0, 0, 0, 0,13,11, 0,12,12,12,13,12, 0, 0, 0, 0,
  122956. 0, 0,13,13,11,13,13,11,12,
  122957. };
  122958. static float _vq_quantthresh__8c0_s_p8_0[] = {
  122959. -27.5, -22.5, -17.5, -12.5, -7.5, -2.5, 2.5, 7.5,
  122960. 12.5, 17.5, 22.5, 27.5,
  122961. };
  122962. static long _vq_quantmap__8c0_s_p8_0[] = {
  122963. 11, 9, 7, 5, 3, 1, 0, 2,
  122964. 4, 6, 8, 10, 12,
  122965. };
  122966. static encode_aux_threshmatch _vq_auxt__8c0_s_p8_0 = {
  122967. _vq_quantthresh__8c0_s_p8_0,
  122968. _vq_quantmap__8c0_s_p8_0,
  122969. 13,
  122970. 13
  122971. };
  122972. static static_codebook _8c0_s_p8_0 = {
  122973. 2, 169,
  122974. _vq_lengthlist__8c0_s_p8_0,
  122975. 1, -526516224, 1616117760, 4, 0,
  122976. _vq_quantlist__8c0_s_p8_0,
  122977. NULL,
  122978. &_vq_auxt__8c0_s_p8_0,
  122979. NULL,
  122980. 0
  122981. };
  122982. static long _vq_quantlist__8c0_s_p8_1[] = {
  122983. 2,
  122984. 1,
  122985. 3,
  122986. 0,
  122987. 4,
  122988. };
  122989. static long _vq_lengthlist__8c0_s_p8_1[] = {
  122990. 1, 3, 4, 5, 5, 7, 6, 6, 6, 5, 7, 7, 7, 6, 6, 7,
  122991. 7, 7, 6, 6, 7, 7, 7, 6, 6,
  122992. };
  122993. static float _vq_quantthresh__8c0_s_p8_1[] = {
  122994. -1.5, -0.5, 0.5, 1.5,
  122995. };
  122996. static long _vq_quantmap__8c0_s_p8_1[] = {
  122997. 3, 1, 0, 2, 4,
  122998. };
  122999. static encode_aux_threshmatch _vq_auxt__8c0_s_p8_1 = {
  123000. _vq_quantthresh__8c0_s_p8_1,
  123001. _vq_quantmap__8c0_s_p8_1,
  123002. 5,
  123003. 5
  123004. };
  123005. static static_codebook _8c0_s_p8_1 = {
  123006. 2, 25,
  123007. _vq_lengthlist__8c0_s_p8_1,
  123008. 1, -533725184, 1611661312, 3, 0,
  123009. _vq_quantlist__8c0_s_p8_1,
  123010. NULL,
  123011. &_vq_auxt__8c0_s_p8_1,
  123012. NULL,
  123013. 0
  123014. };
  123015. static long _vq_quantlist__8c0_s_p9_0[] = {
  123016. 1,
  123017. 0,
  123018. 2,
  123019. };
  123020. static long _vq_lengthlist__8c0_s_p9_0[] = {
  123021. 1, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8,
  123022. 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8,
  123023. 8, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7,
  123024. 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7,
  123025. 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7,
  123026. 7,
  123027. };
  123028. static float _vq_quantthresh__8c0_s_p9_0[] = {
  123029. -157.5, 157.5,
  123030. };
  123031. static long _vq_quantmap__8c0_s_p9_0[] = {
  123032. 1, 0, 2,
  123033. };
  123034. static encode_aux_threshmatch _vq_auxt__8c0_s_p9_0 = {
  123035. _vq_quantthresh__8c0_s_p9_0,
  123036. _vq_quantmap__8c0_s_p9_0,
  123037. 3,
  123038. 3
  123039. };
  123040. static static_codebook _8c0_s_p9_0 = {
  123041. 4, 81,
  123042. _vq_lengthlist__8c0_s_p9_0,
  123043. 1, -518803456, 1628680192, 2, 0,
  123044. _vq_quantlist__8c0_s_p9_0,
  123045. NULL,
  123046. &_vq_auxt__8c0_s_p9_0,
  123047. NULL,
  123048. 0
  123049. };
  123050. static long _vq_quantlist__8c0_s_p9_1[] = {
  123051. 7,
  123052. 6,
  123053. 8,
  123054. 5,
  123055. 9,
  123056. 4,
  123057. 10,
  123058. 3,
  123059. 11,
  123060. 2,
  123061. 12,
  123062. 1,
  123063. 13,
  123064. 0,
  123065. 14,
  123066. };
  123067. static long _vq_lengthlist__8c0_s_p9_1[] = {
  123068. 1, 4, 4, 5, 5,10, 8,11,11,11,11,11,11,11,11, 6,
  123069. 6, 6, 7, 6,11,10,11,11,11,11,11,11,11,11, 7, 5,
  123070. 6, 6, 6, 8, 7,11,11,11,11,11,11,11,11,11, 7, 8,
  123071. 8, 8, 9, 9,11,11,11,11,11,11,11,11,11, 9, 8, 7,
  123072. 8, 9,11,11,11,11,11,11,11,11,11,11,11,10,11,11,
  123073. 11,11,11,11,11,11,11,11,11,11,11,11,11,10,11,11,
  123074. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  123075. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  123076. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  123077. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  123078. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  123079. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  123080. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  123081. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  123082. 11,
  123083. };
  123084. static float _vq_quantthresh__8c0_s_p9_1[] = {
  123085. -136.5, -115.5, -94.5, -73.5, -52.5, -31.5, -10.5, 10.5,
  123086. 31.5, 52.5, 73.5, 94.5, 115.5, 136.5,
  123087. };
  123088. static long _vq_quantmap__8c0_s_p9_1[] = {
  123089. 13, 11, 9, 7, 5, 3, 1, 0,
  123090. 2, 4, 6, 8, 10, 12, 14,
  123091. };
  123092. static encode_aux_threshmatch _vq_auxt__8c0_s_p9_1 = {
  123093. _vq_quantthresh__8c0_s_p9_1,
  123094. _vq_quantmap__8c0_s_p9_1,
  123095. 15,
  123096. 15
  123097. };
  123098. static static_codebook _8c0_s_p9_1 = {
  123099. 2, 225,
  123100. _vq_lengthlist__8c0_s_p9_1,
  123101. 1, -520986624, 1620377600, 4, 0,
  123102. _vq_quantlist__8c0_s_p9_1,
  123103. NULL,
  123104. &_vq_auxt__8c0_s_p9_1,
  123105. NULL,
  123106. 0
  123107. };
  123108. static long _vq_quantlist__8c0_s_p9_2[] = {
  123109. 10,
  123110. 9,
  123111. 11,
  123112. 8,
  123113. 12,
  123114. 7,
  123115. 13,
  123116. 6,
  123117. 14,
  123118. 5,
  123119. 15,
  123120. 4,
  123121. 16,
  123122. 3,
  123123. 17,
  123124. 2,
  123125. 18,
  123126. 1,
  123127. 19,
  123128. 0,
  123129. 20,
  123130. };
  123131. static long _vq_lengthlist__8c0_s_p9_2[] = {
  123132. 1, 5, 5, 7, 7, 8, 7, 8, 8,10,10, 9, 9,10,10,10,
  123133. 11,11,10,12,11,12,12,12, 9, 8, 8, 8, 8, 8, 9,10,
  123134. 10,10,10,11,11,11,10,11,11,12,12,11,12, 8, 8, 7,
  123135. 7, 8, 9,10,10,10, 9,10,10, 9,10,10,11,11,11,11,
  123136. 11,11, 9, 9, 9, 9, 8, 9,10,10,11,10,10,11,11,12,
  123137. 10,10,12,12,11,11,10, 9, 9,10, 8, 9,10,10,10, 9,
  123138. 10,10,11,11,10,11,10,10,10,12,12,12, 9,10, 9,10,
  123139. 9, 9,10,10,11,11,11,11,10,10,10,11,12,11,12,11,
  123140. 12,10,11,10,11, 9,10, 9,10, 9,10,10, 9,10,10,11,
  123141. 10,11,11,11,11,12,11, 9,10,10,10,10,11,11,11,11,
  123142. 11,10,11,11,11,11,10,12,10,12,12,11,12,10,10,11,
  123143. 10, 9,11,10,11, 9,10,11,10,10,10,11,11,11,11,12,
  123144. 12,10, 9, 9,11,10, 9,12,11,10,12,12,11,11,11,11,
  123145. 10,11,11,12,11,10,12, 9,11,10,11,10,10,11,10,11,
  123146. 9,10,10,10,11,12,11,11,12,11,10,10,11,11, 9,10,
  123147. 10,12,10,11,10,10,10, 9,10,10,10,10, 9,10,10,11,
  123148. 11,11,11,12,11,10,10,10,10,11,11,10,11,11, 9,11,
  123149. 10,12,10,12,11,10,11,10,10,10,11,10,10,11,11,10,
  123150. 11,10,10,10,10,11,11,12,10,10,10,11,10,11,12,11,
  123151. 10,11,10,10,11,11,10,12,10, 9,10,10,11,11,11,10,
  123152. 12,10,10,11,11,11,10,10,11,10,10,10,11,10,11,10,
  123153. 12,11,11,10,10,10,12,10,10,11, 9,10,11,11,11,10,
  123154. 10,11,10,10, 9,11,11,12,12,11,12,11,11,11,11,11,
  123155. 11, 9,10,11,10,12,10,10,10,10,11,10,10,11,10,10,
  123156. 12,10,10,10,10,10, 9,12,10,10,10,10,12, 9,11,10,
  123157. 10,11,10,12,12,10,12,12,12,10,10,10,10, 9,10,11,
  123158. 10,10,12,10,10,12,11,10,11,10,10,12,11,10,12,10,
  123159. 10,11, 9,11,10, 9,10, 9,10,
  123160. };
  123161. static float _vq_quantthresh__8c0_s_p9_2[] = {
  123162. -9.5, -8.5, -7.5, -6.5, -5.5, -4.5, -3.5, -2.5,
  123163. -1.5, -0.5, 0.5, 1.5, 2.5, 3.5, 4.5, 5.5,
  123164. 6.5, 7.5, 8.5, 9.5,
  123165. };
  123166. static long _vq_quantmap__8c0_s_p9_2[] = {
  123167. 19, 17, 15, 13, 11, 9, 7, 5,
  123168. 3, 1, 0, 2, 4, 6, 8, 10,
  123169. 12, 14, 16, 18, 20,
  123170. };
  123171. static encode_aux_threshmatch _vq_auxt__8c0_s_p9_2 = {
  123172. _vq_quantthresh__8c0_s_p9_2,
  123173. _vq_quantmap__8c0_s_p9_2,
  123174. 21,
  123175. 21
  123176. };
  123177. static static_codebook _8c0_s_p9_2 = {
  123178. 2, 441,
  123179. _vq_lengthlist__8c0_s_p9_2,
  123180. 1, -529268736, 1611661312, 5, 0,
  123181. _vq_quantlist__8c0_s_p9_2,
  123182. NULL,
  123183. &_vq_auxt__8c0_s_p9_2,
  123184. NULL,
  123185. 0
  123186. };
  123187. static long _huff_lengthlist__8c0_s_single[] = {
  123188. 4, 5,18, 7,10, 6, 7, 8, 9,10, 5, 2,18, 5, 7, 5,
  123189. 6, 7, 8,11,17,17,17,17,17,17,17,17,17,17, 7, 4,
  123190. 17, 6, 9, 6, 8,10,12,15,11, 7,17, 9, 6, 6, 7, 9,
  123191. 11,15, 6, 4,17, 6, 6, 4, 5, 8,11,16, 6, 6,17, 8,
  123192. 6, 5, 6, 9,13,16, 8, 9,17,11, 9, 8, 8,11,13,17,
  123193. 9,12,17,15,14,13,12,13,14,17,12,15,17,17,17,17,
  123194. 17,16,17,17,
  123195. };
  123196. static static_codebook _huff_book__8c0_s_single = {
  123197. 2, 100,
  123198. _huff_lengthlist__8c0_s_single,
  123199. 0, 0, 0, 0, 0,
  123200. NULL,
  123201. NULL,
  123202. NULL,
  123203. NULL,
  123204. 0
  123205. };
  123206. static long _vq_quantlist__8c1_s_p1_0[] = {
  123207. 1,
  123208. 0,
  123209. 2,
  123210. };
  123211. static long _vq_lengthlist__8c1_s_p1_0[] = {
  123212. 1, 5, 5, 0, 0, 0, 0, 0, 0, 5, 7, 7, 0, 0, 0, 0,
  123213. 0, 0, 5, 7, 7, 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, 5, 8, 7, 0, 0, 0, 0, 0, 0, 7, 8, 9, 0, 0, 0,
  123218. 0, 0, 0, 7, 8, 9, 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, 5, 7, 8, 0, 0, 0, 0, 0, 0, 7, 9, 8, 0, 0,
  123223. 0, 0, 0, 0, 7, 9, 8, 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, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123247. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123248. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123249. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123250. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123251. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123252. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123253. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123254. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123255. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123256. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123257. 0, 0, 0, 0, 0, 0, 0, 0, 0, 5, 8, 8, 0, 0, 0, 0,
  123258. 0, 0, 8, 9, 9, 0, 0, 0, 0, 0, 0, 8, 9, 9, 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, 7, 9, 9, 0, 0, 0,
  123263. 0, 0, 0, 8, 8,10, 0, 0, 0, 0, 0, 0, 9,10,10, 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, 7, 9, 9, 0, 0,
  123268. 0, 0, 0, 0, 8,10, 9, 0, 0, 0, 0, 0, 0, 9,10,10,
  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, 5, 8, 8, 0, 0, 0, 0, 0, 0, 8, 9, 9, 0, 0,
  123304. 0, 0, 0, 0, 8, 9, 9, 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, 7, 9, 9, 0, 0, 0, 0, 0, 0, 9,10,10, 0,
  123309. 0, 0, 0, 0, 0, 8, 9,10, 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, 7, 9, 9, 0, 0, 0, 0, 0, 0, 9,10,10,
  123314. 0, 0, 0, 0, 0, 0, 8,10, 8, 0, 0, 0, 0, 0, 0, 0,
  123315. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123316. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123317. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123318. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123319. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123320. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123321. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123322. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123323. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123324. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123325. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123326. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123327. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123328. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123329. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123330. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123331. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123332. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123333. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123334. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123335. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123336. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123337. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123338. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123339. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123340. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123341. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123342. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123343. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123344. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123345. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123346. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123347. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123348. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123349. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123350. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123351. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123352. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123353. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123354. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123355. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123356. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123357. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123358. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123359. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123360. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123361. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123362. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123363. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123364. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123365. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123366. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123367. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123368. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123369. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123370. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123371. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123372. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123373. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123374. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123375. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123376. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123377. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123378. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123379. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123380. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123381. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123382. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123383. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123384. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123385. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123386. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123387. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123388. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123389. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123390. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123391. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123392. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123393. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123394. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123395. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123396. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123397. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123398. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123399. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123400. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123401. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123402. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123403. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123404. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123405. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123406. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123407. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123408. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123409. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123410. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123411. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123412. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123413. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123414. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123415. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123416. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123417. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123418. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123419. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123420. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123421. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123422. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123423. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123424. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123425. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123426. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123427. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123428. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123429. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123430. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123431. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123432. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123433. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123434. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123435. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123436. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123437. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123438. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123439. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123440. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123441. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123442. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123443. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123444. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123445. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123446. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123447. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123448. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123449. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123450. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123451. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123452. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123453. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123454. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123455. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123456. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123457. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123458. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123459. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123460. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123461. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123462. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123463. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123464. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123465. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123466. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123467. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123468. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123469. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123470. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123471. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123472. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123473. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123474. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123475. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123476. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123477. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123478. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123479. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123480. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123481. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123482. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123483. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123484. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123485. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123486. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123487. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123488. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123489. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123490. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123491. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123492. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123493. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123494. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123495. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123496. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123497. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123498. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123499. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123500. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123501. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123502. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123503. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123504. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123505. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123506. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123507. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123508. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123509. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123510. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123511. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123512. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123513. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123514. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123515. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123516. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123517. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123518. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123519. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123520. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123521. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123522. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123523. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123524. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123525. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123526. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123527. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123528. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123529. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123530. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123531. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123532. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123533. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123534. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123535. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123536. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123537. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123538. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123539. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123540. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123541. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123542. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123543. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123544. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123545. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123546. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123547. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123548. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123549. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123550. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123551. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123552. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123553. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123554. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123555. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123556. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123557. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123558. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123559. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123560. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123561. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123562. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123563. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123564. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123565. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123566. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123567. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123568. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123569. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123570. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123571. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123572. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123573. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123574. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123575. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123576. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123577. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123578. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123579. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123580. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123581. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123582. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123583. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123584. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123585. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123586. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123587. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123588. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123589. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123590. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123591. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123592. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123593. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123594. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123595. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123596. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 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,
  123623. };
  123624. static float _vq_quantthresh__8c1_s_p1_0[] = {
  123625. -0.5, 0.5,
  123626. };
  123627. static long _vq_quantmap__8c1_s_p1_0[] = {
  123628. 1, 0, 2,
  123629. };
  123630. static encode_aux_threshmatch _vq_auxt__8c1_s_p1_0 = {
  123631. _vq_quantthresh__8c1_s_p1_0,
  123632. _vq_quantmap__8c1_s_p1_0,
  123633. 3,
  123634. 3
  123635. };
  123636. static static_codebook _8c1_s_p1_0 = {
  123637. 8, 6561,
  123638. _vq_lengthlist__8c1_s_p1_0,
  123639. 1, -535822336, 1611661312, 2, 0,
  123640. _vq_quantlist__8c1_s_p1_0,
  123641. NULL,
  123642. &_vq_auxt__8c1_s_p1_0,
  123643. NULL,
  123644. 0
  123645. };
  123646. static long _vq_quantlist__8c1_s_p2_0[] = {
  123647. 2,
  123648. 1,
  123649. 3,
  123650. 0,
  123651. 4,
  123652. };
  123653. static long _vq_lengthlist__8c1_s_p2_0[] = {
  123654. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123655. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123656. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123657. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123658. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123659. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123660. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123661. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123662. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123663. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123664. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123665. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123666. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123667. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123668. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123669. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123670. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123671. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123672. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123673. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123674. 0, 0, 0, 0, 0, 0, 0, 0, 0, 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,
  123694. };
  123695. static float _vq_quantthresh__8c1_s_p2_0[] = {
  123696. -1.5, -0.5, 0.5, 1.5,
  123697. };
  123698. static long _vq_quantmap__8c1_s_p2_0[] = {
  123699. 3, 1, 0, 2, 4,
  123700. };
  123701. static encode_aux_threshmatch _vq_auxt__8c1_s_p2_0 = {
  123702. _vq_quantthresh__8c1_s_p2_0,
  123703. _vq_quantmap__8c1_s_p2_0,
  123704. 5,
  123705. 5
  123706. };
  123707. static static_codebook _8c1_s_p2_0 = {
  123708. 4, 625,
  123709. _vq_lengthlist__8c1_s_p2_0,
  123710. 1, -533725184, 1611661312, 3, 0,
  123711. _vq_quantlist__8c1_s_p2_0,
  123712. NULL,
  123713. &_vq_auxt__8c1_s_p2_0,
  123714. NULL,
  123715. 0
  123716. };
  123717. static long _vq_quantlist__8c1_s_p3_0[] = {
  123718. 2,
  123719. 1,
  123720. 3,
  123721. 0,
  123722. 4,
  123723. };
  123724. static long _vq_lengthlist__8c1_s_p3_0[] = {
  123725. 2, 4, 4, 5, 5, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123726. 0, 0, 0, 0, 0, 0, 0, 0, 0, 4, 4, 4, 6, 6, 0, 0,
  123727. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123728. 0, 0, 4, 4, 4, 6, 6, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123729. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 6, 6, 6, 7, 7,
  123730. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123731. 0, 0, 0, 0, 6, 6, 6, 7, 7, 0, 0, 0, 0, 0, 0, 0,
  123732. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123733. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123734. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123735. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123736. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123737. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123738. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123739. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123740. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123741. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123742. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123743. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123744. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123745. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123746. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123747. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123748. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123749. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123750. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123751. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123752. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123753. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123754. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123755. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123756. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123757. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123758. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123759. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123760. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123761. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123762. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123763. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123764. 0,
  123765. };
  123766. static float _vq_quantthresh__8c1_s_p3_0[] = {
  123767. -1.5, -0.5, 0.5, 1.5,
  123768. };
  123769. static long _vq_quantmap__8c1_s_p3_0[] = {
  123770. 3, 1, 0, 2, 4,
  123771. };
  123772. static encode_aux_threshmatch _vq_auxt__8c1_s_p3_0 = {
  123773. _vq_quantthresh__8c1_s_p3_0,
  123774. _vq_quantmap__8c1_s_p3_0,
  123775. 5,
  123776. 5
  123777. };
  123778. static static_codebook _8c1_s_p3_0 = {
  123779. 4, 625,
  123780. _vq_lengthlist__8c1_s_p3_0,
  123781. 1, -533725184, 1611661312, 3, 0,
  123782. _vq_quantlist__8c1_s_p3_0,
  123783. NULL,
  123784. &_vq_auxt__8c1_s_p3_0,
  123785. NULL,
  123786. 0
  123787. };
  123788. static long _vq_quantlist__8c1_s_p4_0[] = {
  123789. 4,
  123790. 3,
  123791. 5,
  123792. 2,
  123793. 6,
  123794. 1,
  123795. 7,
  123796. 0,
  123797. 8,
  123798. };
  123799. static long _vq_lengthlist__8c1_s_p4_0[] = {
  123800. 1, 2, 3, 7, 7, 0, 0, 0, 0, 0, 0, 0, 6, 6, 0, 0,
  123801. 0, 0, 0, 0, 0, 6, 6, 0, 0, 0, 0, 0, 0, 0, 7, 7,
  123802. 0, 0, 0, 0, 0, 0, 0, 7, 7, 0, 0, 0, 0, 0, 0, 0,
  123803. 8, 8, 0, 0, 0, 0, 0, 0, 0, 9, 8, 0, 0, 0, 0, 0,
  123804. 0, 0,10,10, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123805. 0,
  123806. };
  123807. static float _vq_quantthresh__8c1_s_p4_0[] = {
  123808. -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5, 3.5,
  123809. };
  123810. static long _vq_quantmap__8c1_s_p4_0[] = {
  123811. 7, 5, 3, 1, 0, 2, 4, 6,
  123812. 8,
  123813. };
  123814. static encode_aux_threshmatch _vq_auxt__8c1_s_p4_0 = {
  123815. _vq_quantthresh__8c1_s_p4_0,
  123816. _vq_quantmap__8c1_s_p4_0,
  123817. 9,
  123818. 9
  123819. };
  123820. static static_codebook _8c1_s_p4_0 = {
  123821. 2, 81,
  123822. _vq_lengthlist__8c1_s_p4_0,
  123823. 1, -531628032, 1611661312, 4, 0,
  123824. _vq_quantlist__8c1_s_p4_0,
  123825. NULL,
  123826. &_vq_auxt__8c1_s_p4_0,
  123827. NULL,
  123828. 0
  123829. };
  123830. static long _vq_quantlist__8c1_s_p5_0[] = {
  123831. 4,
  123832. 3,
  123833. 5,
  123834. 2,
  123835. 6,
  123836. 1,
  123837. 7,
  123838. 0,
  123839. 8,
  123840. };
  123841. static long _vq_lengthlist__8c1_s_p5_0[] = {
  123842. 1, 3, 3, 4, 5, 6, 6, 8, 8, 0, 0, 0, 8, 8, 7, 7,
  123843. 9, 9, 0, 0, 0, 8, 8, 7, 7, 9, 9, 0, 0, 0, 9,10,
  123844. 8, 8, 9, 9, 0, 0, 0,10,10, 8, 8, 9, 9, 0, 0, 0,
  123845. 11,10, 8, 8,10,10, 0, 0, 0,11,11, 8, 8,10,10, 0,
  123846. 0, 0,12,12, 9, 9,10,10, 0, 0, 0, 0, 0, 9, 9,10,
  123847. 10,
  123848. };
  123849. static float _vq_quantthresh__8c1_s_p5_0[] = {
  123850. -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5, 3.5,
  123851. };
  123852. static long _vq_quantmap__8c1_s_p5_0[] = {
  123853. 7, 5, 3, 1, 0, 2, 4, 6,
  123854. 8,
  123855. };
  123856. static encode_aux_threshmatch _vq_auxt__8c1_s_p5_0 = {
  123857. _vq_quantthresh__8c1_s_p5_0,
  123858. _vq_quantmap__8c1_s_p5_0,
  123859. 9,
  123860. 9
  123861. };
  123862. static static_codebook _8c1_s_p5_0 = {
  123863. 2, 81,
  123864. _vq_lengthlist__8c1_s_p5_0,
  123865. 1, -531628032, 1611661312, 4, 0,
  123866. _vq_quantlist__8c1_s_p5_0,
  123867. NULL,
  123868. &_vq_auxt__8c1_s_p5_0,
  123869. NULL,
  123870. 0
  123871. };
  123872. static long _vq_quantlist__8c1_s_p6_0[] = {
  123873. 8,
  123874. 7,
  123875. 9,
  123876. 6,
  123877. 10,
  123878. 5,
  123879. 11,
  123880. 4,
  123881. 12,
  123882. 3,
  123883. 13,
  123884. 2,
  123885. 14,
  123886. 1,
  123887. 15,
  123888. 0,
  123889. 16,
  123890. };
  123891. static long _vq_lengthlist__8c1_s_p6_0[] = {
  123892. 1, 3, 3, 5, 5, 8, 8, 8, 8, 9, 9,10,10,11,11,11,
  123893. 11, 0, 0, 0, 8, 8, 8, 8, 9, 9, 9, 9,10,10,11,11,
  123894. 12,12, 0, 0, 0, 8, 8, 8, 8, 9, 9, 9, 9,10,10,11,
  123895. 11,12,12, 0, 0, 0, 9, 9, 8, 8,10,10,10,10,11,11,
  123896. 12,12,12,12, 0, 0, 0, 9, 9, 8, 8,10,10,10,10,11,
  123897. 11,12,12,12,12, 0, 0, 0,10,10, 9, 9,10,10,10,10,
  123898. 11,11,12,12,13,13, 0, 0, 0,10,10, 9, 9,10,10,10,
  123899. 10,11,11,12,12,13,13, 0, 0, 0,11,11, 9, 9,10,10,
  123900. 10,10,11,11,12,12,13,13, 0, 0, 0, 0, 0, 9, 9,10,
  123901. 10,10,10,11,11,12,12,13,13, 0, 0, 0, 0, 0, 9, 9,
  123902. 10,10,11,11,12,12,12,12,13,13, 0, 0, 0, 0, 0, 9,
  123903. 9,10,10,11,11,12,11,12,12,13,13, 0, 0, 0, 0, 0,
  123904. 10,10,11,11,11,11,12,12,13,12,13,13, 0, 0, 0, 0,
  123905. 0, 0, 0,11,10,11,11,12,12,13,13,13,13, 0, 0, 0,
  123906. 0, 0, 0, 0,11,11,12,12,12,12,13,13,13,14, 0, 0,
  123907. 0, 0, 0, 0, 0,11,11,12,12,12,12,13,13,14,13, 0,
  123908. 0, 0, 0, 0, 0, 0,12,12,12,12,13,13,13,13,14,14,
  123909. 0, 0, 0, 0, 0, 0, 0, 0, 0,12,12,13,13,13,13,14,
  123910. 14,
  123911. };
  123912. static float _vq_quantthresh__8c1_s_p6_0[] = {
  123913. -7.5, -6.5, -5.5, -4.5, -3.5, -2.5, -1.5, -0.5,
  123914. 0.5, 1.5, 2.5, 3.5, 4.5, 5.5, 6.5, 7.5,
  123915. };
  123916. static long _vq_quantmap__8c1_s_p6_0[] = {
  123917. 15, 13, 11, 9, 7, 5, 3, 1,
  123918. 0, 2, 4, 6, 8, 10, 12, 14,
  123919. 16,
  123920. };
  123921. static encode_aux_threshmatch _vq_auxt__8c1_s_p6_0 = {
  123922. _vq_quantthresh__8c1_s_p6_0,
  123923. _vq_quantmap__8c1_s_p6_0,
  123924. 17,
  123925. 17
  123926. };
  123927. static static_codebook _8c1_s_p6_0 = {
  123928. 2, 289,
  123929. _vq_lengthlist__8c1_s_p6_0,
  123930. 1, -529530880, 1611661312, 5, 0,
  123931. _vq_quantlist__8c1_s_p6_0,
  123932. NULL,
  123933. &_vq_auxt__8c1_s_p6_0,
  123934. NULL,
  123935. 0
  123936. };
  123937. static long _vq_quantlist__8c1_s_p7_0[] = {
  123938. 1,
  123939. 0,
  123940. 2,
  123941. };
  123942. static long _vq_lengthlist__8c1_s_p7_0[] = {
  123943. 1, 4, 4, 6, 6, 6, 7, 6, 6, 4, 7, 7,10, 9, 9,10,
  123944. 9, 9, 5, 7, 7,10, 9, 9,10, 9, 9, 6,10,10,10,10,
  123945. 10,11,10,10, 6, 9, 9,10, 9,10,11,10,10, 6, 9, 9,
  123946. 10, 9, 9,11, 9,10, 7,10,10,11,11,11,11,10,10, 6,
  123947. 9, 9,10,10,10,11, 9, 9, 6, 9, 9,10,10,10,10, 9,
  123948. 9,
  123949. };
  123950. static float _vq_quantthresh__8c1_s_p7_0[] = {
  123951. -5.5, 5.5,
  123952. };
  123953. static long _vq_quantmap__8c1_s_p7_0[] = {
  123954. 1, 0, 2,
  123955. };
  123956. static encode_aux_threshmatch _vq_auxt__8c1_s_p7_0 = {
  123957. _vq_quantthresh__8c1_s_p7_0,
  123958. _vq_quantmap__8c1_s_p7_0,
  123959. 3,
  123960. 3
  123961. };
  123962. static static_codebook _8c1_s_p7_0 = {
  123963. 4, 81,
  123964. _vq_lengthlist__8c1_s_p7_0,
  123965. 1, -529137664, 1618345984, 2, 0,
  123966. _vq_quantlist__8c1_s_p7_0,
  123967. NULL,
  123968. &_vq_auxt__8c1_s_p7_0,
  123969. NULL,
  123970. 0
  123971. };
  123972. static long _vq_quantlist__8c1_s_p7_1[] = {
  123973. 5,
  123974. 4,
  123975. 6,
  123976. 3,
  123977. 7,
  123978. 2,
  123979. 8,
  123980. 1,
  123981. 9,
  123982. 0,
  123983. 10,
  123984. };
  123985. static long _vq_lengthlist__8c1_s_p7_1[] = {
  123986. 2, 3, 3, 5, 5, 7, 7, 7, 7, 7, 7,10,10, 9, 7, 7,
  123987. 7, 7, 8, 8, 8, 8, 9, 9, 9, 7, 7, 7, 7, 8, 8, 8,
  123988. 8,10,10,10, 7, 7, 7, 7, 8, 8, 8, 8,10,10,10, 7,
  123989. 7, 7, 7, 8, 8, 8, 8,10,10,10, 8, 8, 8, 8, 8, 8,
  123990. 8, 8,10,10,10, 8, 8, 8, 8, 8, 8, 8, 8,10,10,10,
  123991. 8, 8, 8, 8, 8, 8, 8, 8,10,10,10,10,10, 8, 8, 8,
  123992. 8, 8, 8,10,10,10,10,10, 8, 8, 8, 8, 8, 8,10,10,
  123993. 10,10,10, 8, 8, 8, 8, 8, 8,
  123994. };
  123995. static float _vq_quantthresh__8c1_s_p7_1[] = {
  123996. -4.5, -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5,
  123997. 3.5, 4.5,
  123998. };
  123999. static long _vq_quantmap__8c1_s_p7_1[] = {
  124000. 9, 7, 5, 3, 1, 0, 2, 4,
  124001. 6, 8, 10,
  124002. };
  124003. static encode_aux_threshmatch _vq_auxt__8c1_s_p7_1 = {
  124004. _vq_quantthresh__8c1_s_p7_1,
  124005. _vq_quantmap__8c1_s_p7_1,
  124006. 11,
  124007. 11
  124008. };
  124009. static static_codebook _8c1_s_p7_1 = {
  124010. 2, 121,
  124011. _vq_lengthlist__8c1_s_p7_1,
  124012. 1, -531365888, 1611661312, 4, 0,
  124013. _vq_quantlist__8c1_s_p7_1,
  124014. NULL,
  124015. &_vq_auxt__8c1_s_p7_1,
  124016. NULL,
  124017. 0
  124018. };
  124019. static long _vq_quantlist__8c1_s_p8_0[] = {
  124020. 6,
  124021. 5,
  124022. 7,
  124023. 4,
  124024. 8,
  124025. 3,
  124026. 9,
  124027. 2,
  124028. 10,
  124029. 1,
  124030. 11,
  124031. 0,
  124032. 12,
  124033. };
  124034. static long _vq_lengthlist__8c1_s_p8_0[] = {
  124035. 1, 4, 4, 6, 6, 8, 8, 8, 8, 9, 9,10,10, 7, 5, 5,
  124036. 7, 7, 8, 8, 8, 8, 9,10,11,11, 7, 5, 5, 7, 7, 8,
  124037. 8, 9, 9,10,10,11,11, 0, 8, 8, 8, 8, 9, 9, 9, 9,
  124038. 9,10,11,11, 0, 8, 8, 8, 8, 9, 9, 9, 9,10,10,11,
  124039. 11, 0,12,12, 9, 9, 9, 9,10, 9,10,11,11,11, 0,13,
  124040. 12, 9, 8, 9, 9,10,10,11,11,12,11, 0, 0, 0, 9, 9,
  124041. 9, 9,10,10,11,11,12,12, 0, 0, 0,10,10, 9, 9,10,
  124042. 10,11,11,12,12, 0, 0, 0,13,13,10,10,11,11,12,11,
  124043. 13,12, 0, 0, 0,14,14,10,10,11,10,11,11,12,12, 0,
  124044. 0, 0, 0, 0,12,12,11,11,12,12,13,13, 0, 0, 0, 0,
  124045. 0,12,12,11,10,12,11,13,12,
  124046. };
  124047. static float _vq_quantthresh__8c1_s_p8_0[] = {
  124048. -27.5, -22.5, -17.5, -12.5, -7.5, -2.5, 2.5, 7.5,
  124049. 12.5, 17.5, 22.5, 27.5,
  124050. };
  124051. static long _vq_quantmap__8c1_s_p8_0[] = {
  124052. 11, 9, 7, 5, 3, 1, 0, 2,
  124053. 4, 6, 8, 10, 12,
  124054. };
  124055. static encode_aux_threshmatch _vq_auxt__8c1_s_p8_0 = {
  124056. _vq_quantthresh__8c1_s_p8_0,
  124057. _vq_quantmap__8c1_s_p8_0,
  124058. 13,
  124059. 13
  124060. };
  124061. static static_codebook _8c1_s_p8_0 = {
  124062. 2, 169,
  124063. _vq_lengthlist__8c1_s_p8_0,
  124064. 1, -526516224, 1616117760, 4, 0,
  124065. _vq_quantlist__8c1_s_p8_0,
  124066. NULL,
  124067. &_vq_auxt__8c1_s_p8_0,
  124068. NULL,
  124069. 0
  124070. };
  124071. static long _vq_quantlist__8c1_s_p8_1[] = {
  124072. 2,
  124073. 1,
  124074. 3,
  124075. 0,
  124076. 4,
  124077. };
  124078. static long _vq_lengthlist__8c1_s_p8_1[] = {
  124079. 2, 3, 3, 5, 5, 6, 6, 6, 5, 5, 6, 6, 6, 5, 5, 6,
  124080. 6, 6, 5, 5, 6, 6, 6, 5, 5,
  124081. };
  124082. static float _vq_quantthresh__8c1_s_p8_1[] = {
  124083. -1.5, -0.5, 0.5, 1.5,
  124084. };
  124085. static long _vq_quantmap__8c1_s_p8_1[] = {
  124086. 3, 1, 0, 2, 4,
  124087. };
  124088. static encode_aux_threshmatch _vq_auxt__8c1_s_p8_1 = {
  124089. _vq_quantthresh__8c1_s_p8_1,
  124090. _vq_quantmap__8c1_s_p8_1,
  124091. 5,
  124092. 5
  124093. };
  124094. static static_codebook _8c1_s_p8_1 = {
  124095. 2, 25,
  124096. _vq_lengthlist__8c1_s_p8_1,
  124097. 1, -533725184, 1611661312, 3, 0,
  124098. _vq_quantlist__8c1_s_p8_1,
  124099. NULL,
  124100. &_vq_auxt__8c1_s_p8_1,
  124101. NULL,
  124102. 0
  124103. };
  124104. static long _vq_quantlist__8c1_s_p9_0[] = {
  124105. 6,
  124106. 5,
  124107. 7,
  124108. 4,
  124109. 8,
  124110. 3,
  124111. 9,
  124112. 2,
  124113. 10,
  124114. 1,
  124115. 11,
  124116. 0,
  124117. 12,
  124118. };
  124119. static long _vq_lengthlist__8c1_s_p9_0[] = {
  124120. 1, 3, 3,10,10,10,10,10,10,10,10,10,10, 5, 6, 6,
  124121. 10,10,10,10,10,10,10,10,10,10, 6, 7, 8,10,10,10,
  124122. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  124123. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  124124. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  124125. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  124126. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  124127. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  124128. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  124129. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  124130. 10,10,10,10,10, 9, 9, 9, 9,
  124131. };
  124132. static float _vq_quantthresh__8c1_s_p9_0[] = {
  124133. -1732.5, -1417.5, -1102.5, -787.5, -472.5, -157.5, 157.5, 472.5,
  124134. 787.5, 1102.5, 1417.5, 1732.5,
  124135. };
  124136. static long _vq_quantmap__8c1_s_p9_0[] = {
  124137. 11, 9, 7, 5, 3, 1, 0, 2,
  124138. 4, 6, 8, 10, 12,
  124139. };
  124140. static encode_aux_threshmatch _vq_auxt__8c1_s_p9_0 = {
  124141. _vq_quantthresh__8c1_s_p9_0,
  124142. _vq_quantmap__8c1_s_p9_0,
  124143. 13,
  124144. 13
  124145. };
  124146. static static_codebook _8c1_s_p9_0 = {
  124147. 2, 169,
  124148. _vq_lengthlist__8c1_s_p9_0,
  124149. 1, -513964032, 1628680192, 4, 0,
  124150. _vq_quantlist__8c1_s_p9_0,
  124151. NULL,
  124152. &_vq_auxt__8c1_s_p9_0,
  124153. NULL,
  124154. 0
  124155. };
  124156. static long _vq_quantlist__8c1_s_p9_1[] = {
  124157. 7,
  124158. 6,
  124159. 8,
  124160. 5,
  124161. 9,
  124162. 4,
  124163. 10,
  124164. 3,
  124165. 11,
  124166. 2,
  124167. 12,
  124168. 1,
  124169. 13,
  124170. 0,
  124171. 14,
  124172. };
  124173. static long _vq_lengthlist__8c1_s_p9_1[] = {
  124174. 1, 4, 4, 5, 5, 7, 7, 9, 9,11,11,12,12,13,13, 6,
  124175. 5, 5, 6, 6, 9, 9,10,10,12,12,12,13,15,14, 6, 5,
  124176. 5, 7, 7, 9, 9,10,10,12,12,12,13,14,13,17, 7, 7,
  124177. 8, 8,10,10,11,11,12,13,13,13,13,13,17, 7, 7, 8,
  124178. 8,10,10,11,11,13,13,13,13,14,14,17,11,11, 9, 9,
  124179. 11,11,12,12,12,13,13,14,15,13,17,12,12, 9, 9,11,
  124180. 11,12,12,13,13,13,13,14,16,17,17,17,11,12,12,12,
  124181. 13,13,13,14,15,14,15,15,17,17,17,12,12,11,11,13,
  124182. 13,14,14,15,14,15,15,17,17,17,15,15,13,13,14,14,
  124183. 15,14,15,15,16,15,17,17,17,15,15,13,13,13,14,14,
  124184. 15,15,15,15,16,17,17,17,17,16,14,15,14,14,15,14,
  124185. 14,15,15,15,17,17,17,17,17,14,14,16,14,15,15,15,
  124186. 15,15,15,17,17,17,17,17,17,16,16,15,17,15,15,14,
  124187. 17,15,17,16,17,17,17,17,16,15,14,15,15,15,15,15,
  124188. 15,
  124189. };
  124190. static float _vq_quantthresh__8c1_s_p9_1[] = {
  124191. -136.5, -115.5, -94.5, -73.5, -52.5, -31.5, -10.5, 10.5,
  124192. 31.5, 52.5, 73.5, 94.5, 115.5, 136.5,
  124193. };
  124194. static long _vq_quantmap__8c1_s_p9_1[] = {
  124195. 13, 11, 9, 7, 5, 3, 1, 0,
  124196. 2, 4, 6, 8, 10, 12, 14,
  124197. };
  124198. static encode_aux_threshmatch _vq_auxt__8c1_s_p9_1 = {
  124199. _vq_quantthresh__8c1_s_p9_1,
  124200. _vq_quantmap__8c1_s_p9_1,
  124201. 15,
  124202. 15
  124203. };
  124204. static static_codebook _8c1_s_p9_1 = {
  124205. 2, 225,
  124206. _vq_lengthlist__8c1_s_p9_1,
  124207. 1, -520986624, 1620377600, 4, 0,
  124208. _vq_quantlist__8c1_s_p9_1,
  124209. NULL,
  124210. &_vq_auxt__8c1_s_p9_1,
  124211. NULL,
  124212. 0
  124213. };
  124214. static long _vq_quantlist__8c1_s_p9_2[] = {
  124215. 10,
  124216. 9,
  124217. 11,
  124218. 8,
  124219. 12,
  124220. 7,
  124221. 13,
  124222. 6,
  124223. 14,
  124224. 5,
  124225. 15,
  124226. 4,
  124227. 16,
  124228. 3,
  124229. 17,
  124230. 2,
  124231. 18,
  124232. 1,
  124233. 19,
  124234. 0,
  124235. 20,
  124236. };
  124237. static long _vq_lengthlist__8c1_s_p9_2[] = {
  124238. 2, 4, 4, 6, 6, 7, 7, 8, 8, 8, 8, 9, 8, 9, 9, 9,
  124239. 9, 9, 9, 9, 9,11,11,12, 7, 7, 7, 7, 8, 8, 9, 9,
  124240. 9, 9,10,10,10,10,10,10,10,10,11,11,11, 7, 7, 7,
  124241. 7, 8, 8, 9, 8, 9, 9, 9, 9, 9, 9,10,10,10,10,11,
  124242. 11,12, 8, 8, 8, 8, 8, 8, 9, 9, 9, 9,10,10,10,10,
  124243. 10,10,10,10,11,11,11, 7, 7, 8, 8, 8, 8, 9, 9, 9,
  124244. 9,10,10,10,10,10,10,10,10,11,11,11, 8, 8, 8, 8,
  124245. 9, 9, 9, 9, 9, 9,10,10,10,10,10,10,10,10,11,11,
  124246. 11, 8, 8, 8, 8, 9, 9, 9, 9, 9, 9,10,10,10,10,10,
  124247. 10,10,10,11,12,11, 9, 9, 8, 9, 9, 9, 9, 9,10,10,
  124248. 10,10,10,10,10,10,10,10,11,11,11,11,11, 8, 8, 9,
  124249. 9, 9, 9,10,10,10,10,10,10,10,10,10,10,11,12,11,
  124250. 12,11, 9, 9, 9, 9, 9,10,10,10,10,10,10,10,10,10,
  124251. 10,10,11,11,11,11,11, 9, 9, 9, 9,10,10,10,10,10,
  124252. 10,10,10,10,10,10,10,12,11,12,11,11, 9, 9, 9,10,
  124253. 10,10,10,10,10,10,10,10,10,10,10,10,12,11,11,11,
  124254. 11,11,11,10,10,10,10,10,10,10,10,10,10,10,10,10,
  124255. 11,11,11,12,11,11,12,11,10,10,10,10,10,10,10,10,
  124256. 10,10,10,10,11,10,11,11,11,11,11,11,11,10,10,10,
  124257. 10,10,10,10,10,10,10,10,10,10,10,11,11,12,11,12,
  124258. 11,11,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  124259. 11,11,12,11,12,11,11,11,11,10,10,10,10,10,10,10,
  124260. 10,10,10,10,10,11,11,12,11,11,12,11,11,12,10,10,
  124261. 11,10,10,10,10,10,10,10,10,10,11,11,11,11,11,11,
  124262. 11,11,11,10,10,10,10,10,10,10,10,10,10,10,10,12,
  124263. 12,11,12,11,11,12,12,12,11,11,10,10,10,10,10,10,
  124264. 10,10,10,11,12,12,11,12,12,11,12,11,11,11,11,10,
  124265. 10,10,10,10,10,10,10,10,10,
  124266. };
  124267. static float _vq_quantthresh__8c1_s_p9_2[] = {
  124268. -9.5, -8.5, -7.5, -6.5, -5.5, -4.5, -3.5, -2.5,
  124269. -1.5, -0.5, 0.5, 1.5, 2.5, 3.5, 4.5, 5.5,
  124270. 6.5, 7.5, 8.5, 9.5,
  124271. };
  124272. static long _vq_quantmap__8c1_s_p9_2[] = {
  124273. 19, 17, 15, 13, 11, 9, 7, 5,
  124274. 3, 1, 0, 2, 4, 6, 8, 10,
  124275. 12, 14, 16, 18, 20,
  124276. };
  124277. static encode_aux_threshmatch _vq_auxt__8c1_s_p9_2 = {
  124278. _vq_quantthresh__8c1_s_p9_2,
  124279. _vq_quantmap__8c1_s_p9_2,
  124280. 21,
  124281. 21
  124282. };
  124283. static static_codebook _8c1_s_p9_2 = {
  124284. 2, 441,
  124285. _vq_lengthlist__8c1_s_p9_2,
  124286. 1, -529268736, 1611661312, 5, 0,
  124287. _vq_quantlist__8c1_s_p9_2,
  124288. NULL,
  124289. &_vq_auxt__8c1_s_p9_2,
  124290. NULL,
  124291. 0
  124292. };
  124293. static long _huff_lengthlist__8c1_s_single[] = {
  124294. 4, 6,18, 8,11, 8, 8, 9, 9,10, 4, 4,18, 5, 9, 5,
  124295. 6, 7, 8,10,18,18,18,18,17,17,17,17,17,17, 7, 5,
  124296. 17, 6,11, 6, 7, 8, 9,12,12, 9,17,12, 8, 8, 9,10,
  124297. 10,13, 7, 5,17, 6, 8, 4, 5, 6, 8,10, 6, 5,17, 6,
  124298. 8, 5, 4, 5, 7, 9, 7, 7,17, 8, 9, 6, 5, 5, 6, 8,
  124299. 8, 8,17, 9,11, 8, 6, 6, 6, 7, 9,10,17,12,12,10,
  124300. 9, 7, 7, 8,
  124301. };
  124302. static static_codebook _huff_book__8c1_s_single = {
  124303. 2, 100,
  124304. _huff_lengthlist__8c1_s_single,
  124305. 0, 0, 0, 0, 0,
  124306. NULL,
  124307. NULL,
  124308. NULL,
  124309. NULL,
  124310. 0
  124311. };
  124312. static long _huff_lengthlist__44c2_s_long[] = {
  124313. 6, 6,12,10,10,10, 9,10,12,12, 6, 1,10, 5, 6, 6,
  124314. 7, 9,11,14,12, 9, 8,11, 7, 8, 9,11,13,15,10, 5,
  124315. 12, 7, 8, 7, 9,12,14,15,10, 6, 7, 8, 5, 6, 7, 9,
  124316. 12,14, 9, 6, 8, 7, 6, 6, 7, 9,12,12, 9, 7, 9, 9,
  124317. 7, 6, 6, 7,10,10,10, 9,10,11, 8, 7, 6, 6, 8,10,
  124318. 12,11,13,13,11,10, 8, 8, 8,10,11,13,15,15,14,13,
  124319. 10, 8, 8, 9,
  124320. };
  124321. static static_codebook _huff_book__44c2_s_long = {
  124322. 2, 100,
  124323. _huff_lengthlist__44c2_s_long,
  124324. 0, 0, 0, 0, 0,
  124325. NULL,
  124326. NULL,
  124327. NULL,
  124328. NULL,
  124329. 0
  124330. };
  124331. static long _vq_quantlist__44c2_s_p1_0[] = {
  124332. 1,
  124333. 0,
  124334. 2,
  124335. };
  124336. static long _vq_lengthlist__44c2_s_p1_0[] = {
  124337. 2, 4, 4, 0, 0, 0, 0, 0, 0, 5, 6, 6, 0, 0, 0, 0,
  124338. 0, 0, 5, 6, 7, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124339. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124340. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124341. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124342. 0, 5, 7, 7, 0, 0, 0, 0, 0, 0, 7, 8, 8, 0, 0, 0,
  124343. 0, 0, 0, 6, 8, 8, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124344. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124345. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124346. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124347. 0, 0, 5, 7, 7, 0, 0, 0, 0, 0, 0, 6, 8, 7, 0, 0,
  124348. 0, 0, 0, 0, 7, 8, 8, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124349. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124350. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124351. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124352. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124353. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124354. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124355. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124356. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124357. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124358. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124359. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124360. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124361. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124362. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124363. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124364. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124365. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124366. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124367. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124368. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124369. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124370. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124371. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124372. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124373. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124374. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124375. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124376. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124377. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124378. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124379. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124380. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124381. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124382. 0, 0, 0, 0, 0, 0, 0, 0, 0, 5, 7, 7, 0, 0, 0, 0,
  124383. 0, 0, 7, 8, 8, 0, 0, 0, 0, 0, 0, 7, 8, 8, 0, 0,
  124384. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124385. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124386. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124387. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 7, 8, 8, 0, 0, 0,
  124388. 0, 0, 0, 8, 9, 9, 0, 0, 0, 0, 0, 0, 8, 9, 9, 0,
  124389. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124390. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124391. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124392. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 6, 8, 8, 0, 0,
  124393. 0, 0, 0, 0, 8, 9, 8, 0, 0, 0, 0, 0, 0, 8, 9, 9,
  124394. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124395. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124396. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124397. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124398. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124399. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124400. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124401. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124402. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124403. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124404. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124405. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124406. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124407. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124408. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124409. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124410. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124411. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124412. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124413. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124414. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124415. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124416. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124417. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124418. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124419. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124420. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124421. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124422. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124423. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124424. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124425. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124426. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124427. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124428. 0, 0, 4, 7, 7, 0, 0, 0, 0, 0, 0, 7, 8, 8, 0, 0,
  124429. 0, 0, 0, 0, 7, 8, 8, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124430. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124431. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124432. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124433. 0, 0, 0, 6, 8, 8, 0, 0, 0, 0, 0, 0, 8, 9, 9, 0,
  124434. 0, 0, 0, 0, 0, 8, 8, 9, 0, 0, 0, 0, 0, 0, 0, 0,
  124435. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124436. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124437. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124438. 0, 0, 0, 0, 7, 8, 8, 0, 0, 0, 0, 0, 0, 8, 9, 9,
  124439. 0, 0, 0, 0, 0, 0, 8, 9, 9, 0, 0, 0, 0, 0, 0, 0,
  124440. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124441. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124442. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124443. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124444. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124445. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124446. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124447. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124448. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124449. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124450. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124451. 0, 0, 0, 0, 0, 0, 0, 0, 0, 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, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124461. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124462. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124463. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124464. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124465. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124466. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124467. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124468. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124469. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124470. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124471. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124472. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124473. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124474. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124475. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124476. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124477. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124478. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124479. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124480. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124481. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124482. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124483. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124484. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124485. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124486. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124487. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124488. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124489. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124490. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124491. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124492. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124493. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124494. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124495. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124496. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124497. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124498. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124499. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124500. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124501. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124502. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124503. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124504. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124505. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124506. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124507. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124508. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124509. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124510. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124511. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124512. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124513. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124514. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124515. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124516. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124517. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124518. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124519. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124520. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124521. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124522. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124523. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124524. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124525. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124526. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124527. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124528. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124529. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124530. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124531. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124532. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124533. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124534. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124535. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124536. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124537. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124538. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124539. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124540. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124541. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124542. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124543. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124544. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124545. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124546. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124547. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124548. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124549. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124550. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124551. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124552. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124553. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124554. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124555. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124556. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124557. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124558. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124559. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124560. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124561. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124562. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124563. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124564. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124565. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124566. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124567. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124568. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124569. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124570. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124571. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124572. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124573. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124574. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124575. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124576. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124577. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124578. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124579. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124580. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124581. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124582. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124583. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124584. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124585. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124586. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124587. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124588. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124589. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124590. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124591. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124592. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124593. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124594. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124595. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124596. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124597. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124598. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124599. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124600. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124601. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124602. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124603. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124604. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124605. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124606. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124607. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124608. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124609. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124610. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124611. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124612. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124613. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124614. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124615. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124616. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124617. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124618. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124619. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124620. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124621. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124622. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124623. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124624. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124625. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124626. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124627. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124628. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124629. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124630. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124631. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124632. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124633. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124634. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124635. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124636. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124637. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124638. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124639. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124640. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124641. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124642. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124643. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124644. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124645. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124646. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124647. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124648. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124649. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124650. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124651. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124652. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124653. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124654. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124655. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124656. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124657. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124658. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124659. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124660. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124661. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124662. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124663. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124664. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124665. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124666. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124667. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124668. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124669. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124670. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124671. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124672. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124673. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124674. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124675. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124676. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124677. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124678. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124679. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124680. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124681. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124682. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124683. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124684. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124685. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124686. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124687. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124688. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124689. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124690. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124691. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124692. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124693. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124694. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124695. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124696. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124697. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124698. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124699. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124700. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124701. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124702. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124703. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124704. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124705. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124706. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124707. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124708. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124709. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124710. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124711. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124712. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124713. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124714. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124715. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124716. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124717. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124718. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124719. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124720. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124721. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124722. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124723. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124724. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124725. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124726. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124727. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124728. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124729. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124730. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124731. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124732. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124733. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124734. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124735. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124736. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124737. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124738. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124739. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124740. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124741. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124742. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124743. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124744. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124745. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124746. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124747. 0,
  124748. };
  124749. static float _vq_quantthresh__44c2_s_p1_0[] = {
  124750. -0.5, 0.5,
  124751. };
  124752. static long _vq_quantmap__44c2_s_p1_0[] = {
  124753. 1, 0, 2,
  124754. };
  124755. static encode_aux_threshmatch _vq_auxt__44c2_s_p1_0 = {
  124756. _vq_quantthresh__44c2_s_p1_0,
  124757. _vq_quantmap__44c2_s_p1_0,
  124758. 3,
  124759. 3
  124760. };
  124761. static static_codebook _44c2_s_p1_0 = {
  124762. 8, 6561,
  124763. _vq_lengthlist__44c2_s_p1_0,
  124764. 1, -535822336, 1611661312, 2, 0,
  124765. _vq_quantlist__44c2_s_p1_0,
  124766. NULL,
  124767. &_vq_auxt__44c2_s_p1_0,
  124768. NULL,
  124769. 0
  124770. };
  124771. static long _vq_quantlist__44c2_s_p2_0[] = {
  124772. 2,
  124773. 1,
  124774. 3,
  124775. 0,
  124776. 4,
  124777. };
  124778. static long _vq_lengthlist__44c2_s_p2_0[] = {
  124779. 1, 4, 4, 0, 0, 0, 7, 7, 0, 0, 0, 7, 7, 0, 0, 0,
  124780. 8, 8, 0, 0, 0, 0, 0, 0, 0, 4, 6, 6, 0, 0, 0, 8,
  124781. 8, 0, 0, 0, 8, 8, 0, 0, 0, 9, 9, 0, 0, 0, 0, 0,
  124782. 0, 0, 4, 6, 6, 0, 0, 0, 8, 8, 0, 0, 0, 8, 8, 0,
  124783. 0, 0, 9, 9, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124784. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124785. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124786. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124787. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124788. 0, 0, 0, 0, 0, 0, 7, 8, 8, 0, 0, 0,11,11, 0, 0,
  124789. 0,11,11, 0, 0, 0,12,11, 0, 0, 0, 0, 0, 0, 0, 7,
  124790. 8, 8, 0, 0, 0,10,11, 0, 0, 0,11,11, 0, 0, 0,11,
  124791. 12, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124792. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124793. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124794. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124795. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124796. 0, 0, 0, 6, 8, 8, 0, 0, 0,11,11, 0, 0, 0,11,11,
  124797. 0, 0, 0,12,12, 0, 0, 0, 0, 0, 0, 0, 6, 8, 8, 0,
  124798. 0, 0,10,11, 0, 0, 0,10,11, 0, 0, 0,11,11, 0, 0,
  124799. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124800. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124801. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124802. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124803. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124804. 8, 9, 9, 0, 0, 0,11,12, 0, 0, 0,11,12, 0, 0, 0,
  124805. 12,11, 0, 0, 0, 0, 0, 0, 0, 8,10, 9, 0, 0, 0,12,
  124806. 11, 0, 0, 0,12,11, 0, 0, 0,11,12, 0, 0, 0, 0, 0,
  124807. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124808. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124809. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124810. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124811. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124812. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124813. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124814. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124815. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124816. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124817. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124818. 0,
  124819. };
  124820. static float _vq_quantthresh__44c2_s_p2_0[] = {
  124821. -1.5, -0.5, 0.5, 1.5,
  124822. };
  124823. static long _vq_quantmap__44c2_s_p2_0[] = {
  124824. 3, 1, 0, 2, 4,
  124825. };
  124826. static encode_aux_threshmatch _vq_auxt__44c2_s_p2_0 = {
  124827. _vq_quantthresh__44c2_s_p2_0,
  124828. _vq_quantmap__44c2_s_p2_0,
  124829. 5,
  124830. 5
  124831. };
  124832. static static_codebook _44c2_s_p2_0 = {
  124833. 4, 625,
  124834. _vq_lengthlist__44c2_s_p2_0,
  124835. 1, -533725184, 1611661312, 3, 0,
  124836. _vq_quantlist__44c2_s_p2_0,
  124837. NULL,
  124838. &_vq_auxt__44c2_s_p2_0,
  124839. NULL,
  124840. 0
  124841. };
  124842. static long _vq_quantlist__44c2_s_p3_0[] = {
  124843. 2,
  124844. 1,
  124845. 3,
  124846. 0,
  124847. 4,
  124848. };
  124849. static long _vq_lengthlist__44c2_s_p3_0[] = {
  124850. 2, 4, 3, 6, 6, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124851. 0, 0, 0, 0, 0, 0, 0, 0, 0, 4, 4, 4, 6, 6, 0, 0,
  124852. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124853. 0, 0, 4, 4, 4, 6, 6, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124854. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 6, 6, 6, 9, 9,
  124855. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124856. 0, 0, 0, 0, 6, 6, 7, 9, 9, 0, 0, 0, 0, 0, 0, 0,
  124857. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124858. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124859. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124860. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124861. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124862. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124863. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124864. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124865. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124866. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124867. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124868. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124869. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124870. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124871. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124872. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124873. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124874. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124875. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124876. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124877. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124878. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124879. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124880. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124881. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124882. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124883. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124884. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124885. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124886. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124887. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124888. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124889. 0,
  124890. };
  124891. static float _vq_quantthresh__44c2_s_p3_0[] = {
  124892. -1.5, -0.5, 0.5, 1.5,
  124893. };
  124894. static long _vq_quantmap__44c2_s_p3_0[] = {
  124895. 3, 1, 0, 2, 4,
  124896. };
  124897. static encode_aux_threshmatch _vq_auxt__44c2_s_p3_0 = {
  124898. _vq_quantthresh__44c2_s_p3_0,
  124899. _vq_quantmap__44c2_s_p3_0,
  124900. 5,
  124901. 5
  124902. };
  124903. static static_codebook _44c2_s_p3_0 = {
  124904. 4, 625,
  124905. _vq_lengthlist__44c2_s_p3_0,
  124906. 1, -533725184, 1611661312, 3, 0,
  124907. _vq_quantlist__44c2_s_p3_0,
  124908. NULL,
  124909. &_vq_auxt__44c2_s_p3_0,
  124910. NULL,
  124911. 0
  124912. };
  124913. static long _vq_quantlist__44c2_s_p4_0[] = {
  124914. 4,
  124915. 3,
  124916. 5,
  124917. 2,
  124918. 6,
  124919. 1,
  124920. 7,
  124921. 0,
  124922. 8,
  124923. };
  124924. static long _vq_lengthlist__44c2_s_p4_0[] = {
  124925. 1, 3, 3, 6, 6, 0, 0, 0, 0, 0, 6, 6, 6, 6, 0, 0,
  124926. 0, 0, 0, 6, 6, 6, 6, 0, 0, 0, 0, 0, 7, 7, 6, 6,
  124927. 0, 0, 0, 0, 0, 0, 0, 6, 7, 0, 0, 0, 0, 0, 0, 0,
  124928. 7, 8, 0, 0, 0, 0, 0, 0, 0, 8, 8, 0, 0, 0, 0, 0,
  124929. 0, 0, 9, 9, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124930. 0,
  124931. };
  124932. static float _vq_quantthresh__44c2_s_p4_0[] = {
  124933. -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5, 3.5,
  124934. };
  124935. static long _vq_quantmap__44c2_s_p4_0[] = {
  124936. 7, 5, 3, 1, 0, 2, 4, 6,
  124937. 8,
  124938. };
  124939. static encode_aux_threshmatch _vq_auxt__44c2_s_p4_0 = {
  124940. _vq_quantthresh__44c2_s_p4_0,
  124941. _vq_quantmap__44c2_s_p4_0,
  124942. 9,
  124943. 9
  124944. };
  124945. static static_codebook _44c2_s_p4_0 = {
  124946. 2, 81,
  124947. _vq_lengthlist__44c2_s_p4_0,
  124948. 1, -531628032, 1611661312, 4, 0,
  124949. _vq_quantlist__44c2_s_p4_0,
  124950. NULL,
  124951. &_vq_auxt__44c2_s_p4_0,
  124952. NULL,
  124953. 0
  124954. };
  124955. static long _vq_quantlist__44c2_s_p5_0[] = {
  124956. 4,
  124957. 3,
  124958. 5,
  124959. 2,
  124960. 6,
  124961. 1,
  124962. 7,
  124963. 0,
  124964. 8,
  124965. };
  124966. static long _vq_lengthlist__44c2_s_p5_0[] = {
  124967. 1, 3, 3, 6, 6, 7, 7, 9, 9, 0, 7, 7, 7, 7, 7, 7,
  124968. 9, 9, 0, 7, 7, 7, 7, 7, 7, 9, 9, 0, 8, 8, 7, 7,
  124969. 8, 8,10,10, 0, 0, 0, 7, 7, 8, 8,10,10, 0, 0, 0,
  124970. 9, 9, 8, 8,10,10, 0, 0, 0, 9, 9, 8, 8,10,10, 0,
  124971. 0, 0,10,10, 9, 9,11,11, 0, 0, 0, 0, 0, 9, 9,11,
  124972. 11,
  124973. };
  124974. static float _vq_quantthresh__44c2_s_p5_0[] = {
  124975. -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5, 3.5,
  124976. };
  124977. static long _vq_quantmap__44c2_s_p5_0[] = {
  124978. 7, 5, 3, 1, 0, 2, 4, 6,
  124979. 8,
  124980. };
  124981. static encode_aux_threshmatch _vq_auxt__44c2_s_p5_0 = {
  124982. _vq_quantthresh__44c2_s_p5_0,
  124983. _vq_quantmap__44c2_s_p5_0,
  124984. 9,
  124985. 9
  124986. };
  124987. static static_codebook _44c2_s_p5_0 = {
  124988. 2, 81,
  124989. _vq_lengthlist__44c2_s_p5_0,
  124990. 1, -531628032, 1611661312, 4, 0,
  124991. _vq_quantlist__44c2_s_p5_0,
  124992. NULL,
  124993. &_vq_auxt__44c2_s_p5_0,
  124994. NULL,
  124995. 0
  124996. };
  124997. static long _vq_quantlist__44c2_s_p6_0[] = {
  124998. 8,
  124999. 7,
  125000. 9,
  125001. 6,
  125002. 10,
  125003. 5,
  125004. 11,
  125005. 4,
  125006. 12,
  125007. 3,
  125008. 13,
  125009. 2,
  125010. 14,
  125011. 1,
  125012. 15,
  125013. 0,
  125014. 16,
  125015. };
  125016. static long _vq_lengthlist__44c2_s_p6_0[] = {
  125017. 1, 4, 3, 6, 6, 8, 8, 9, 9, 9, 9, 9, 9,10,10,11,
  125018. 11, 0, 7, 7, 7, 7, 8, 8, 9, 9, 9, 9,10,10,11,11,
  125019. 12,11, 0, 7, 7, 7, 7, 8, 8, 9, 9, 9, 9,10,10,11,
  125020. 11,11,12, 0, 8, 8, 7, 7, 9, 9,10,10, 9, 9,10,10,
  125021. 11,11,12,12, 0, 0, 0, 7, 7, 9, 9,10,10,10, 9,10,
  125022. 10,11,11,12,12, 0, 0, 0, 8, 8, 9, 9,10,10,10,10,
  125023. 11,11,11,11,12,12, 0, 0, 0, 8, 8, 9, 9,10,10,10,
  125024. 10,11,11,12,12,12,12, 0, 0, 0, 9, 9, 9, 9,10,10,
  125025. 10,10,11,11,12,12,12,12, 0, 0, 0, 0, 0, 9, 9,10,
  125026. 10,10,10,11,11,12,12,13,13, 0, 0, 0, 0, 0, 9, 9,
  125027. 10,10,11,11,11,11,12,12,13,13, 0, 0, 0, 0, 0, 9,
  125028. 9,10,10,11,11,11,11,12,12,13,13, 0, 0, 0, 0, 0,
  125029. 10,10,10,10,11,11,12,12,13,12,13,13, 0, 0, 0, 0,
  125030. 0, 0, 0,10,10,11,11,12,12,13,13,13,13, 0, 0, 0,
  125031. 0, 0, 0, 0,11,11,12,12,12,12,13,13,13,14, 0, 0,
  125032. 0, 0, 0, 0, 0,11,11,12,12,12,12,13,13,13,14, 0,
  125033. 0, 0, 0, 0, 0, 0,12,12,12,12,13,13,13,13,14,14,
  125034. 0, 0, 0, 0, 0, 0, 0, 0, 0,12,12,13,13,13,13,14,
  125035. 14,
  125036. };
  125037. static float _vq_quantthresh__44c2_s_p6_0[] = {
  125038. -7.5, -6.5, -5.5, -4.5, -3.5, -2.5, -1.5, -0.5,
  125039. 0.5, 1.5, 2.5, 3.5, 4.5, 5.5, 6.5, 7.5,
  125040. };
  125041. static long _vq_quantmap__44c2_s_p6_0[] = {
  125042. 15, 13, 11, 9, 7, 5, 3, 1,
  125043. 0, 2, 4, 6, 8, 10, 12, 14,
  125044. 16,
  125045. };
  125046. static encode_aux_threshmatch _vq_auxt__44c2_s_p6_0 = {
  125047. _vq_quantthresh__44c2_s_p6_0,
  125048. _vq_quantmap__44c2_s_p6_0,
  125049. 17,
  125050. 17
  125051. };
  125052. static static_codebook _44c2_s_p6_0 = {
  125053. 2, 289,
  125054. _vq_lengthlist__44c2_s_p6_0,
  125055. 1, -529530880, 1611661312, 5, 0,
  125056. _vq_quantlist__44c2_s_p6_0,
  125057. NULL,
  125058. &_vq_auxt__44c2_s_p6_0,
  125059. NULL,
  125060. 0
  125061. };
  125062. static long _vq_quantlist__44c2_s_p7_0[] = {
  125063. 1,
  125064. 0,
  125065. 2,
  125066. };
  125067. static long _vq_lengthlist__44c2_s_p7_0[] = {
  125068. 1, 4, 4, 7, 6, 6, 7, 6, 6, 4, 7, 7,10, 9, 9,11,
  125069. 9, 9, 4, 7, 7,10, 9, 9,10, 9, 9, 7,10,10,11,10,
  125070. 11,11,10,11, 6, 9, 9,11,10,10,11,10,10, 6, 9, 9,
  125071. 11,10,11,11,10,10, 7,11,10,11,11,11,12,11,11, 6,
  125072. 9, 9,11,10,10,11,11,10, 6, 9, 9,11,10,10,12,10,
  125073. 11,
  125074. };
  125075. static float _vq_quantthresh__44c2_s_p7_0[] = {
  125076. -5.5, 5.5,
  125077. };
  125078. static long _vq_quantmap__44c2_s_p7_0[] = {
  125079. 1, 0, 2,
  125080. };
  125081. static encode_aux_threshmatch _vq_auxt__44c2_s_p7_0 = {
  125082. _vq_quantthresh__44c2_s_p7_0,
  125083. _vq_quantmap__44c2_s_p7_0,
  125084. 3,
  125085. 3
  125086. };
  125087. static static_codebook _44c2_s_p7_0 = {
  125088. 4, 81,
  125089. _vq_lengthlist__44c2_s_p7_0,
  125090. 1, -529137664, 1618345984, 2, 0,
  125091. _vq_quantlist__44c2_s_p7_0,
  125092. NULL,
  125093. &_vq_auxt__44c2_s_p7_0,
  125094. NULL,
  125095. 0
  125096. };
  125097. static long _vq_quantlist__44c2_s_p7_1[] = {
  125098. 5,
  125099. 4,
  125100. 6,
  125101. 3,
  125102. 7,
  125103. 2,
  125104. 8,
  125105. 1,
  125106. 9,
  125107. 0,
  125108. 10,
  125109. };
  125110. static long _vq_lengthlist__44c2_s_p7_1[] = {
  125111. 2, 3, 4, 6, 6, 7, 7, 7, 7, 7, 7, 9, 7, 7, 6, 6,
  125112. 7, 7, 8, 8, 8, 8, 9, 6, 6, 6, 6, 7, 7, 8, 8, 8,
  125113. 8,10, 7, 7, 7, 7, 7, 7, 8, 8, 8, 8,10,10,10, 7,
  125114. 7, 7, 7, 8, 8, 8, 8,10,10,10, 7, 7, 8, 8, 8, 8,
  125115. 8, 8,10,10,10, 7, 8, 8, 8, 8, 8, 8, 8,10,10,10,
  125116. 8, 8, 8, 8, 8, 8, 8, 8,10,10,10,10,10, 8, 8, 8,
  125117. 8, 8, 8,10,10,10,10,10, 9, 9, 8, 8, 8, 8,10,10,
  125118. 10,10,10, 8, 8, 8, 8, 8, 8,
  125119. };
  125120. static float _vq_quantthresh__44c2_s_p7_1[] = {
  125121. -4.5, -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5,
  125122. 3.5, 4.5,
  125123. };
  125124. static long _vq_quantmap__44c2_s_p7_1[] = {
  125125. 9, 7, 5, 3, 1, 0, 2, 4,
  125126. 6, 8, 10,
  125127. };
  125128. static encode_aux_threshmatch _vq_auxt__44c2_s_p7_1 = {
  125129. _vq_quantthresh__44c2_s_p7_1,
  125130. _vq_quantmap__44c2_s_p7_1,
  125131. 11,
  125132. 11
  125133. };
  125134. static static_codebook _44c2_s_p7_1 = {
  125135. 2, 121,
  125136. _vq_lengthlist__44c2_s_p7_1,
  125137. 1, -531365888, 1611661312, 4, 0,
  125138. _vq_quantlist__44c2_s_p7_1,
  125139. NULL,
  125140. &_vq_auxt__44c2_s_p7_1,
  125141. NULL,
  125142. 0
  125143. };
  125144. static long _vq_quantlist__44c2_s_p8_0[] = {
  125145. 6,
  125146. 5,
  125147. 7,
  125148. 4,
  125149. 8,
  125150. 3,
  125151. 9,
  125152. 2,
  125153. 10,
  125154. 1,
  125155. 11,
  125156. 0,
  125157. 12,
  125158. };
  125159. static long _vq_lengthlist__44c2_s_p8_0[] = {
  125160. 1, 4, 4, 6, 6, 7, 7, 7, 7, 8, 8, 9, 9, 6, 5, 5,
  125161. 7, 7, 8, 8, 8, 8, 9, 9,10,10, 7, 6, 5, 7, 7, 8,
  125162. 8, 8, 8, 9, 9,10,10, 0, 8, 8, 8, 8, 9, 9, 9, 9,
  125163. 10,10,11,11, 0, 8, 8, 8, 8, 9, 9, 9, 9,10,10,11,
  125164. 11, 0,12,12, 9, 9,10,10,10,10,11,11,11,11, 0,13,
  125165. 13, 9, 9,10,10,10,10,11,11,12,12, 0, 0, 0,10,10,
  125166. 10,10,11,11,12,12,12,13, 0, 0, 0,10,10,10,10,11,
  125167. 11,12,12,12,12, 0, 0, 0,14,14,10,11,11,11,12,12,
  125168. 13,13, 0, 0, 0,14,14,11,10,11,11,13,12,13,13, 0,
  125169. 0, 0, 0, 0,12,12,11,12,13,12,14,14, 0, 0, 0, 0,
  125170. 0,12,12,12,12,13,12,14,14,
  125171. };
  125172. static float _vq_quantthresh__44c2_s_p8_0[] = {
  125173. -27.5, -22.5, -17.5, -12.5, -7.5, -2.5, 2.5, 7.5,
  125174. 12.5, 17.5, 22.5, 27.5,
  125175. };
  125176. static long _vq_quantmap__44c2_s_p8_0[] = {
  125177. 11, 9, 7, 5, 3, 1, 0, 2,
  125178. 4, 6, 8, 10, 12,
  125179. };
  125180. static encode_aux_threshmatch _vq_auxt__44c2_s_p8_0 = {
  125181. _vq_quantthresh__44c2_s_p8_0,
  125182. _vq_quantmap__44c2_s_p8_0,
  125183. 13,
  125184. 13
  125185. };
  125186. static static_codebook _44c2_s_p8_0 = {
  125187. 2, 169,
  125188. _vq_lengthlist__44c2_s_p8_0,
  125189. 1, -526516224, 1616117760, 4, 0,
  125190. _vq_quantlist__44c2_s_p8_0,
  125191. NULL,
  125192. &_vq_auxt__44c2_s_p8_0,
  125193. NULL,
  125194. 0
  125195. };
  125196. static long _vq_quantlist__44c2_s_p8_1[] = {
  125197. 2,
  125198. 1,
  125199. 3,
  125200. 0,
  125201. 4,
  125202. };
  125203. static long _vq_lengthlist__44c2_s_p8_1[] = {
  125204. 2, 4, 4, 5, 4, 6, 5, 5, 5, 5, 6, 5, 5, 5, 5, 6,
  125205. 5, 5, 5, 5, 6, 6, 6, 5, 5,
  125206. };
  125207. static float _vq_quantthresh__44c2_s_p8_1[] = {
  125208. -1.5, -0.5, 0.5, 1.5,
  125209. };
  125210. static long _vq_quantmap__44c2_s_p8_1[] = {
  125211. 3, 1, 0, 2, 4,
  125212. };
  125213. static encode_aux_threshmatch _vq_auxt__44c2_s_p8_1 = {
  125214. _vq_quantthresh__44c2_s_p8_1,
  125215. _vq_quantmap__44c2_s_p8_1,
  125216. 5,
  125217. 5
  125218. };
  125219. static static_codebook _44c2_s_p8_1 = {
  125220. 2, 25,
  125221. _vq_lengthlist__44c2_s_p8_1,
  125222. 1, -533725184, 1611661312, 3, 0,
  125223. _vq_quantlist__44c2_s_p8_1,
  125224. NULL,
  125225. &_vq_auxt__44c2_s_p8_1,
  125226. NULL,
  125227. 0
  125228. };
  125229. static long _vq_quantlist__44c2_s_p9_0[] = {
  125230. 6,
  125231. 5,
  125232. 7,
  125233. 4,
  125234. 8,
  125235. 3,
  125236. 9,
  125237. 2,
  125238. 10,
  125239. 1,
  125240. 11,
  125241. 0,
  125242. 12,
  125243. };
  125244. static long _vq_lengthlist__44c2_s_p9_0[] = {
  125245. 1, 5, 4,12,12,12,12,12,12,12,12,12,12, 4, 9, 8,
  125246. 11,11,11,11,11,11,11,11,11,11, 2, 8, 7,11,11,11,
  125247. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  125248. 11,11,11,11,11,11,10,11,11,11,11,11,11,11,11,11,
  125249. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  125250. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  125251. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  125252. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  125253. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  125254. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  125255. 11,11,11,11,11,11,11,11,11,
  125256. };
  125257. static float _vq_quantthresh__44c2_s_p9_0[] = {
  125258. -1215.5, -994.5, -773.5, -552.5, -331.5, -110.5, 110.5, 331.5,
  125259. 552.5, 773.5, 994.5, 1215.5,
  125260. };
  125261. static long _vq_quantmap__44c2_s_p9_0[] = {
  125262. 11, 9, 7, 5, 3, 1, 0, 2,
  125263. 4, 6, 8, 10, 12,
  125264. };
  125265. static encode_aux_threshmatch _vq_auxt__44c2_s_p9_0 = {
  125266. _vq_quantthresh__44c2_s_p9_0,
  125267. _vq_quantmap__44c2_s_p9_0,
  125268. 13,
  125269. 13
  125270. };
  125271. static static_codebook _44c2_s_p9_0 = {
  125272. 2, 169,
  125273. _vq_lengthlist__44c2_s_p9_0,
  125274. 1, -514541568, 1627103232, 4, 0,
  125275. _vq_quantlist__44c2_s_p9_0,
  125276. NULL,
  125277. &_vq_auxt__44c2_s_p9_0,
  125278. NULL,
  125279. 0
  125280. };
  125281. static long _vq_quantlist__44c2_s_p9_1[] = {
  125282. 6,
  125283. 5,
  125284. 7,
  125285. 4,
  125286. 8,
  125287. 3,
  125288. 9,
  125289. 2,
  125290. 10,
  125291. 1,
  125292. 11,
  125293. 0,
  125294. 12,
  125295. };
  125296. static long _vq_lengthlist__44c2_s_p9_1[] = {
  125297. 1, 4, 4, 6, 6, 7, 6, 8, 8,10, 9,10,10, 6, 5, 5,
  125298. 7, 7, 8, 7,10, 9,11,11,12,13, 6, 5, 5, 7, 7, 8,
  125299. 8,10,10,11,11,13,13,18, 8, 8, 8, 8, 9, 9,10,10,
  125300. 12,12,12,13,18, 8, 8, 8, 8, 9, 9,10,10,12,12,13,
  125301. 13,18,11,11, 8, 8,10,10,11,11,12,11,13,12,18,11,
  125302. 11, 9, 7,10,10,11,11,11,12,12,13,17,17,17,10,10,
  125303. 11,11,12,12,12,10,12,12,17,17,17,11,10,11,10,13,
  125304. 12,11,12,12,12,17,17,17,15,14,11,11,12,11,13,10,
  125305. 13,12,17,17,17,14,14,12,10,11,11,13,13,13,13,17,
  125306. 17,16,17,16,13,13,12,10,13,10,14,13,17,16,17,16,
  125307. 17,13,12,12,10,13,11,14,14,
  125308. };
  125309. static float _vq_quantthresh__44c2_s_p9_1[] = {
  125310. -93.5, -76.5, -59.5, -42.5, -25.5, -8.5, 8.5, 25.5,
  125311. 42.5, 59.5, 76.5, 93.5,
  125312. };
  125313. static long _vq_quantmap__44c2_s_p9_1[] = {
  125314. 11, 9, 7, 5, 3, 1, 0, 2,
  125315. 4, 6, 8, 10, 12,
  125316. };
  125317. static encode_aux_threshmatch _vq_auxt__44c2_s_p9_1 = {
  125318. _vq_quantthresh__44c2_s_p9_1,
  125319. _vq_quantmap__44c2_s_p9_1,
  125320. 13,
  125321. 13
  125322. };
  125323. static static_codebook _44c2_s_p9_1 = {
  125324. 2, 169,
  125325. _vq_lengthlist__44c2_s_p9_1,
  125326. 1, -522616832, 1620115456, 4, 0,
  125327. _vq_quantlist__44c2_s_p9_1,
  125328. NULL,
  125329. &_vq_auxt__44c2_s_p9_1,
  125330. NULL,
  125331. 0
  125332. };
  125333. static long _vq_quantlist__44c2_s_p9_2[] = {
  125334. 8,
  125335. 7,
  125336. 9,
  125337. 6,
  125338. 10,
  125339. 5,
  125340. 11,
  125341. 4,
  125342. 12,
  125343. 3,
  125344. 13,
  125345. 2,
  125346. 14,
  125347. 1,
  125348. 15,
  125349. 0,
  125350. 16,
  125351. };
  125352. static long _vq_lengthlist__44c2_s_p9_2[] = {
  125353. 2, 4, 4, 6, 6, 7, 7, 7, 7, 7, 7, 8, 8, 8, 8, 8,
  125354. 8,10, 7, 7, 7, 7, 7, 7, 8, 8, 8, 8, 9, 9, 9, 9,
  125355. 9, 9,10, 7, 7, 7, 7, 8, 8, 8, 8, 8, 8, 9, 9, 9,
  125356. 9, 9, 9,10, 8, 8, 8, 8, 8, 8, 8, 8, 9, 9, 9, 9,
  125357. 9, 9, 9, 9,10,10,10, 8, 7, 8, 8, 8, 8, 9, 9, 9,
  125358. 9, 9, 9, 9, 9,10,11,11, 8, 8, 8, 8, 9, 9, 9, 9,
  125359. 9, 9,10, 9, 9, 9,10,11,10, 8, 8, 8, 8, 9, 9, 9,
  125360. 9, 9, 9, 9,10,10,10,10,11,10, 8, 8, 9, 9, 9, 9,
  125361. 9, 9,10, 9, 9,10, 9,10,11,10,11,11,11, 8, 8, 9,
  125362. 9, 9, 9, 9, 9, 9, 9,10,10,11,11,11,11,11, 9, 9,
  125363. 9, 9, 9, 9,10, 9, 9, 9,10,10,11,11,11,11,11, 9,
  125364. 9, 9, 9, 9, 9, 9, 9, 9,10, 9,10,11,11,11,11,11,
  125365. 9, 9, 9, 9,10,10, 9, 9, 9,10,10,10,11,11,11,11,
  125366. 11,11,11, 9, 9, 9,10, 9, 9,10,10,10,10,11,11,10,
  125367. 11,11,11,11,10, 9,10,10, 9, 9, 9, 9,10,10,11,10,
  125368. 11,11,11,11,11, 9, 9, 9, 9,10, 9,10,10,10,10,11,
  125369. 10,11,11,11,11,11,10,10, 9, 9,10, 9,10,10,10,10,
  125370. 10,10,10,11,11,11,11,11,11, 9, 9,10, 9,10, 9,10,
  125371. 10,
  125372. };
  125373. static float _vq_quantthresh__44c2_s_p9_2[] = {
  125374. -7.5, -6.5, -5.5, -4.5, -3.5, -2.5, -1.5, -0.5,
  125375. 0.5, 1.5, 2.5, 3.5, 4.5, 5.5, 6.5, 7.5,
  125376. };
  125377. static long _vq_quantmap__44c2_s_p9_2[] = {
  125378. 15, 13, 11, 9, 7, 5, 3, 1,
  125379. 0, 2, 4, 6, 8, 10, 12, 14,
  125380. 16,
  125381. };
  125382. static encode_aux_threshmatch _vq_auxt__44c2_s_p9_2 = {
  125383. _vq_quantthresh__44c2_s_p9_2,
  125384. _vq_quantmap__44c2_s_p9_2,
  125385. 17,
  125386. 17
  125387. };
  125388. static static_codebook _44c2_s_p9_2 = {
  125389. 2, 289,
  125390. _vq_lengthlist__44c2_s_p9_2,
  125391. 1, -529530880, 1611661312, 5, 0,
  125392. _vq_quantlist__44c2_s_p9_2,
  125393. NULL,
  125394. &_vq_auxt__44c2_s_p9_2,
  125395. NULL,
  125396. 0
  125397. };
  125398. static long _huff_lengthlist__44c2_s_short[] = {
  125399. 11, 9,13,12,12,11,12,12,13,15, 8, 2,11, 4, 8, 5,
  125400. 7,10,12,15,13, 7,10, 9, 8, 8,10,13,17,17,11, 4,
  125401. 12, 5, 9, 5, 8,11,14,16,12, 6, 8, 7, 6, 6, 8,11,
  125402. 13,16,11, 4, 9, 5, 6, 4, 6,10,13,16,11, 6,11, 7,
  125403. 7, 6, 7,10,13,15,13, 9,12, 9, 8, 6, 8,10,12,14,
  125404. 14,10,10, 8, 6, 5, 6, 9,11,13,15,11,11, 9, 6, 5,
  125405. 6, 8, 9,12,
  125406. };
  125407. static static_codebook _huff_book__44c2_s_short = {
  125408. 2, 100,
  125409. _huff_lengthlist__44c2_s_short,
  125410. 0, 0, 0, 0, 0,
  125411. NULL,
  125412. NULL,
  125413. NULL,
  125414. NULL,
  125415. 0
  125416. };
  125417. static long _huff_lengthlist__44c3_s_long[] = {
  125418. 5, 6,11,11,11,11,10,10,12,11, 5, 2,11, 5, 6, 6,
  125419. 7, 9,11,13,13,10, 7,11, 6, 7, 8, 9,10,12,11, 5,
  125420. 11, 6, 8, 7, 9,11,14,15,11, 6, 6, 8, 4, 5, 7, 8,
  125421. 10,13,10, 5, 7, 7, 5, 5, 6, 8,10,11,10, 7, 7, 8,
  125422. 6, 5, 5, 7, 9, 9,11, 8, 8,11, 8, 7, 6, 6, 7, 9,
  125423. 12,11,10,13, 9, 9, 7, 7, 7, 9,11,13,12,15,12,11,
  125424. 9, 8, 8, 8,
  125425. };
  125426. static static_codebook _huff_book__44c3_s_long = {
  125427. 2, 100,
  125428. _huff_lengthlist__44c3_s_long,
  125429. 0, 0, 0, 0, 0,
  125430. NULL,
  125431. NULL,
  125432. NULL,
  125433. NULL,
  125434. 0
  125435. };
  125436. static long _vq_quantlist__44c3_s_p1_0[] = {
  125437. 1,
  125438. 0,
  125439. 2,
  125440. };
  125441. static long _vq_lengthlist__44c3_s_p1_0[] = {
  125442. 2, 4, 4, 0, 0, 0, 0, 0, 0, 5, 6, 6, 0, 0, 0, 0,
  125443. 0, 0, 5, 6, 6, 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, 5, 7, 7, 0, 0, 0, 0, 0, 0, 7, 8, 8, 0, 0, 0,
  125448. 0, 0, 0, 6, 7, 8, 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, 5, 7, 7, 0, 0, 0, 0, 0, 0, 6, 8, 7, 0, 0,
  125453. 0, 0, 0, 0, 7, 8, 8, 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, 5, 7, 7, 0, 0, 0, 0,
  125488. 0, 0, 7, 8, 8, 0, 0, 0, 0, 0, 0, 7, 8, 8, 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, 7, 8, 8, 0, 0, 0,
  125493. 0, 0, 0, 8, 8, 9, 0, 0, 0, 0, 0, 0, 8, 9, 9, 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, 6, 8, 8, 0, 0,
  125498. 0, 0, 0, 0, 7, 9, 8, 0, 0, 0, 0, 0, 0, 8, 9, 9,
  125499. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125500. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125501. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125502. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125503. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125504. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125505. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125506. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125507. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125508. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125509. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125510. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125511. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125512. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125513. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125514. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125515. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125516. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125517. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125518. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125519. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125520. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125521. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125522. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125523. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125524. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125525. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125526. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125527. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125528. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125529. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125530. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125531. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125532. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125533. 0, 0, 5, 7, 7, 0, 0, 0, 0, 0, 0, 7, 8, 8, 0, 0,
  125534. 0, 0, 0, 0, 7, 8, 8, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125535. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125536. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125537. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125538. 0, 0, 0, 6, 8, 8, 0, 0, 0, 0, 0, 0, 8, 9, 9, 0,
  125539. 0, 0, 0, 0, 0, 7, 8, 9, 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, 6, 8, 8, 0, 0, 0, 0, 0, 0, 8, 9, 9,
  125544. 0, 0, 0, 0, 0, 0, 8, 9, 8, 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, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125575. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125576. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125577. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125578. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125579. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125580. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125581. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125582. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125583. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125584. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125585. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125586. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125587. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125588. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125589. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125590. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125591. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125592. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125593. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125594. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125595. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125596. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125597. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125598. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125599. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125600. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125601. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125602. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125603. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125604. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125605. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125606. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125607. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125608. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125609. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125610. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125611. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125612. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125613. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125614. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 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, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125646. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125647. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125648. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125649. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125650. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125651. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125652. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125653. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125654. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125655. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125656. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125657. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125658. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125659. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125660. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125661. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125662. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125663. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125664. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125665. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125666. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125667. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125668. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125669. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125670. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125671. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125672. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125673. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125674. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125675. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125676. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125677. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125678. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125679. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125680. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125681. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125682. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125683. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125684. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125685. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125686. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125687. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125688. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125689. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125690. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125691. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125692. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125693. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125694. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125695. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125696. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125697. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125698. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125699. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125700. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125701. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125702. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125703. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125704. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125705. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125706. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125707. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125708. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125709. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125710. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125711. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125712. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125713. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125714. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125715. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125716. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125717. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125718. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125719. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125720. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125721. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125722. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125723. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125724. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125725. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125726. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125727. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125728. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125729. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125730. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125731. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125732. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125733. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125734. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125735. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125736. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125737. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125738. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125739. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125740. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125741. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125742. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125743. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125744. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125745. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125746. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125747. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125748. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125749. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125750. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125751. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125752. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125753. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125754. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125755. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125756. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125757. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125758. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125759. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125760. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125761. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125762. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125763. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125764. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125765. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125766. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125767. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125768. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125769. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125770. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125771. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125772. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125773. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125774. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125775. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125776. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125777. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125778. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125779. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125780. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125781. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125782. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125783. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125784. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125785. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125786. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125787. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125788. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125789. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125790. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125791. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125792. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125793. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125794. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125795. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125796. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125797. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125798. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125799. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125800. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125801. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125802. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125803. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125804. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125805. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125806. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125807. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125808. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125809. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125810. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125811. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125812. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125813. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125814. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125815. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125816. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125817. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125818. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125819. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125820. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125821. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125822. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125823. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125824. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125825. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125826. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125827. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125828. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125829. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125830. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125831. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125832. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125833. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125834. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125835. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125836. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125837. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125838. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125839. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125840. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125841. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125842. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125843. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125844. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125845. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125846. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125847. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125848. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125849. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125850. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125851. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125852. 0,
  125853. };
  125854. static float _vq_quantthresh__44c3_s_p1_0[] = {
  125855. -0.5, 0.5,
  125856. };
  125857. static long _vq_quantmap__44c3_s_p1_0[] = {
  125858. 1, 0, 2,
  125859. };
  125860. static encode_aux_threshmatch _vq_auxt__44c3_s_p1_0 = {
  125861. _vq_quantthresh__44c3_s_p1_0,
  125862. _vq_quantmap__44c3_s_p1_0,
  125863. 3,
  125864. 3
  125865. };
  125866. static static_codebook _44c3_s_p1_0 = {
  125867. 8, 6561,
  125868. _vq_lengthlist__44c3_s_p1_0,
  125869. 1, -535822336, 1611661312, 2, 0,
  125870. _vq_quantlist__44c3_s_p1_0,
  125871. NULL,
  125872. &_vq_auxt__44c3_s_p1_0,
  125873. NULL,
  125874. 0
  125875. };
  125876. static long _vq_quantlist__44c3_s_p2_0[] = {
  125877. 2,
  125878. 1,
  125879. 3,
  125880. 0,
  125881. 4,
  125882. };
  125883. static long _vq_lengthlist__44c3_s_p2_0[] = {
  125884. 2, 5, 5, 0, 0, 0, 5, 5, 0, 0, 0, 5, 5, 0, 0, 0,
  125885. 7, 8, 0, 0, 0, 0, 0, 0, 0, 5, 6, 6, 0, 0, 0, 7,
  125886. 7, 0, 0, 0, 7, 7, 0, 0, 0,10,10, 0, 0, 0, 0, 0,
  125887. 0, 0, 5, 6, 6, 0, 0, 0, 7, 7, 0, 0, 0, 7, 7, 0,
  125888. 0, 0,10,10, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125889. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125890. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125891. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125892. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125893. 0, 0, 0, 0, 0, 0, 5, 7, 7, 0, 0, 0, 7, 7, 0, 0,
  125894. 0, 7, 7, 0, 0, 0, 9, 9, 0, 0, 0, 0, 0, 0, 0, 5,
  125895. 7, 7, 0, 0, 0, 7, 7, 0, 0, 0, 7, 7, 0, 0, 0, 9,
  125896. 9, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125897. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125898. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125899. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125900. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125901. 0, 0, 0, 5, 7, 7, 0, 0, 0, 7, 7, 0, 0, 0, 7, 7,
  125902. 0, 0, 0, 9, 9, 0, 0, 0, 0, 0, 0, 0, 5, 7, 7, 0,
  125903. 0, 0, 7, 7, 0, 0, 0, 7, 7, 0, 0, 0, 9, 9, 0, 0,
  125904. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125905. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125906. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125907. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125908. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125909. 8,10,10, 0, 0, 0, 9, 9, 0, 0, 0, 9, 9, 0, 0, 0,
  125910. 10,10, 0, 0, 0, 0, 0, 0, 0, 8,10,10, 0, 0, 0, 9,
  125911. 9, 0, 0, 0, 9, 9, 0, 0, 0,10,10, 0, 0, 0, 0, 0,
  125912. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125913. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125914. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125915. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125916. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125917. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125918. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125919. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125920. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125921. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125922. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125923. 0,
  125924. };
  125925. static float _vq_quantthresh__44c3_s_p2_0[] = {
  125926. -1.5, -0.5, 0.5, 1.5,
  125927. };
  125928. static long _vq_quantmap__44c3_s_p2_0[] = {
  125929. 3, 1, 0, 2, 4,
  125930. };
  125931. static encode_aux_threshmatch _vq_auxt__44c3_s_p2_0 = {
  125932. _vq_quantthresh__44c3_s_p2_0,
  125933. _vq_quantmap__44c3_s_p2_0,
  125934. 5,
  125935. 5
  125936. };
  125937. static static_codebook _44c3_s_p2_0 = {
  125938. 4, 625,
  125939. _vq_lengthlist__44c3_s_p2_0,
  125940. 1, -533725184, 1611661312, 3, 0,
  125941. _vq_quantlist__44c3_s_p2_0,
  125942. NULL,
  125943. &_vq_auxt__44c3_s_p2_0,
  125944. NULL,
  125945. 0
  125946. };
  125947. static long _vq_quantlist__44c3_s_p3_0[] = {
  125948. 2,
  125949. 1,
  125950. 3,
  125951. 0,
  125952. 4,
  125953. };
  125954. static long _vq_lengthlist__44c3_s_p3_0[] = {
  125955. 2, 4, 3, 6, 6, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125956. 0, 0, 0, 0, 0, 0, 0, 0, 0, 4, 4, 4, 6, 6, 0, 0,
  125957. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125958. 0, 0, 4, 4, 4, 6, 6, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125959. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 6, 6, 6, 9, 9,
  125960. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125961. 0, 0, 0, 0, 6, 6, 7, 9, 9, 0, 0, 0, 0, 0, 0, 0,
  125962. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125963. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125964. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125965. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125966. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125967. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125968. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125969. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125970. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125971. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125972. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125973. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125974. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125975. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125976. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125977. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125978. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125979. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125980. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125981. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125982. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125983. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125984. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125985. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125986. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125987. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125988. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125989. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125990. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125991. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125992. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125993. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125994. 0,
  125995. };
  125996. static float _vq_quantthresh__44c3_s_p3_0[] = {
  125997. -1.5, -0.5, 0.5, 1.5,
  125998. };
  125999. static long _vq_quantmap__44c3_s_p3_0[] = {
  126000. 3, 1, 0, 2, 4,
  126001. };
  126002. static encode_aux_threshmatch _vq_auxt__44c3_s_p3_0 = {
  126003. _vq_quantthresh__44c3_s_p3_0,
  126004. _vq_quantmap__44c3_s_p3_0,
  126005. 5,
  126006. 5
  126007. };
  126008. static static_codebook _44c3_s_p3_0 = {
  126009. 4, 625,
  126010. _vq_lengthlist__44c3_s_p3_0,
  126011. 1, -533725184, 1611661312, 3, 0,
  126012. _vq_quantlist__44c3_s_p3_0,
  126013. NULL,
  126014. &_vq_auxt__44c3_s_p3_0,
  126015. NULL,
  126016. 0
  126017. };
  126018. static long _vq_quantlist__44c3_s_p4_0[] = {
  126019. 4,
  126020. 3,
  126021. 5,
  126022. 2,
  126023. 6,
  126024. 1,
  126025. 7,
  126026. 0,
  126027. 8,
  126028. };
  126029. static long _vq_lengthlist__44c3_s_p4_0[] = {
  126030. 2, 3, 3, 6, 6, 0, 0, 0, 0, 0, 4, 4, 6, 6, 0, 0,
  126031. 0, 0, 0, 4, 4, 6, 6, 0, 0, 0, 0, 0, 5, 5, 6, 6,
  126032. 0, 0, 0, 0, 0, 0, 0, 6, 6, 0, 0, 0, 0, 0, 0, 0,
  126033. 7, 8, 0, 0, 0, 0, 0, 0, 0, 7, 7, 0, 0, 0, 0, 0,
  126034. 0, 0, 9, 9, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126035. 0,
  126036. };
  126037. static float _vq_quantthresh__44c3_s_p4_0[] = {
  126038. -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5, 3.5,
  126039. };
  126040. static long _vq_quantmap__44c3_s_p4_0[] = {
  126041. 7, 5, 3, 1, 0, 2, 4, 6,
  126042. 8,
  126043. };
  126044. static encode_aux_threshmatch _vq_auxt__44c3_s_p4_0 = {
  126045. _vq_quantthresh__44c3_s_p4_0,
  126046. _vq_quantmap__44c3_s_p4_0,
  126047. 9,
  126048. 9
  126049. };
  126050. static static_codebook _44c3_s_p4_0 = {
  126051. 2, 81,
  126052. _vq_lengthlist__44c3_s_p4_0,
  126053. 1, -531628032, 1611661312, 4, 0,
  126054. _vq_quantlist__44c3_s_p4_0,
  126055. NULL,
  126056. &_vq_auxt__44c3_s_p4_0,
  126057. NULL,
  126058. 0
  126059. };
  126060. static long _vq_quantlist__44c3_s_p5_0[] = {
  126061. 4,
  126062. 3,
  126063. 5,
  126064. 2,
  126065. 6,
  126066. 1,
  126067. 7,
  126068. 0,
  126069. 8,
  126070. };
  126071. static long _vq_lengthlist__44c3_s_p5_0[] = {
  126072. 1, 3, 4, 6, 6, 7, 7, 9, 9, 0, 5, 5, 7, 7, 7, 8,
  126073. 9, 9, 0, 5, 5, 7, 7, 8, 8, 9, 9, 0, 7, 7, 8, 8,
  126074. 8, 8,10,10, 0, 0, 0, 8, 8, 8, 8,10,10, 0, 0, 0,
  126075. 9, 9, 9, 9,10,10, 0, 0, 0, 9, 9, 9, 9,10,10, 0,
  126076. 0, 0,10,10,10,10,11,11, 0, 0, 0, 0, 0,10,10,11,
  126077. 11,
  126078. };
  126079. static float _vq_quantthresh__44c3_s_p5_0[] = {
  126080. -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5, 3.5,
  126081. };
  126082. static long _vq_quantmap__44c3_s_p5_0[] = {
  126083. 7, 5, 3, 1, 0, 2, 4, 6,
  126084. 8,
  126085. };
  126086. static encode_aux_threshmatch _vq_auxt__44c3_s_p5_0 = {
  126087. _vq_quantthresh__44c3_s_p5_0,
  126088. _vq_quantmap__44c3_s_p5_0,
  126089. 9,
  126090. 9
  126091. };
  126092. static static_codebook _44c3_s_p5_0 = {
  126093. 2, 81,
  126094. _vq_lengthlist__44c3_s_p5_0,
  126095. 1, -531628032, 1611661312, 4, 0,
  126096. _vq_quantlist__44c3_s_p5_0,
  126097. NULL,
  126098. &_vq_auxt__44c3_s_p5_0,
  126099. NULL,
  126100. 0
  126101. };
  126102. static long _vq_quantlist__44c3_s_p6_0[] = {
  126103. 8,
  126104. 7,
  126105. 9,
  126106. 6,
  126107. 10,
  126108. 5,
  126109. 11,
  126110. 4,
  126111. 12,
  126112. 3,
  126113. 13,
  126114. 2,
  126115. 14,
  126116. 1,
  126117. 15,
  126118. 0,
  126119. 16,
  126120. };
  126121. static long _vq_lengthlist__44c3_s_p6_0[] = {
  126122. 2, 3, 3, 6, 6, 7, 7, 8, 8, 8, 8, 9, 9,10,10,11,
  126123. 10, 0, 5, 5, 7, 7, 8, 8, 9, 9, 9, 9,10,10,10,10,
  126124. 11,11, 0, 5, 5, 7, 7, 8, 8, 9, 9, 9, 9,10,10,10,
  126125. 10,11,11, 0, 6, 6, 7, 7, 8, 8, 9, 9, 9, 9,10,10,
  126126. 11,11,11,11, 0, 0, 0, 7, 7, 8, 8, 9, 9, 9, 9,10,
  126127. 10,11,11,11,12, 0, 0, 0, 8, 8, 8, 8, 9, 9, 9, 9,
  126128. 10,10,11,11,12,12, 0, 0, 0, 8, 8, 8, 8, 9, 9, 9,
  126129. 9,10,10,11,11,12,12, 0, 0, 0, 9, 9, 9, 9,10,10,
  126130. 10,10,11,10,11,11,12,12, 0, 0, 0, 0, 0, 9, 9,10,
  126131. 10,10,10,11,11,11,11,12,12, 0, 0, 0, 0, 0, 9, 8,
  126132. 9, 9,10,10,11,11,12,12,12,12, 0, 0, 0, 0, 0, 8,
  126133. 8, 9, 9,10,10,11,11,12,11,12,12, 0, 0, 0, 0, 0,
  126134. 9,10,10,10,11,11,11,11,12,12,13,13, 0, 0, 0, 0,
  126135. 0, 0, 0,10,10,10,10,11,11,12,12,13,13, 0, 0, 0,
  126136. 0, 0, 0, 0,11,11,11,11,12,12,12,12,13,13, 0, 0,
  126137. 0, 0, 0, 0, 0,11,11,11,11,12,12,12,12,13,13, 0,
  126138. 0, 0, 0, 0, 0, 0,11,11,12,12,12,12,13,13,13,13,
  126139. 0, 0, 0, 0, 0, 0, 0, 0, 0,12,12,12,12,13,13,13,
  126140. 13,
  126141. };
  126142. static float _vq_quantthresh__44c3_s_p6_0[] = {
  126143. -7.5, -6.5, -5.5, -4.5, -3.5, -2.5, -1.5, -0.5,
  126144. 0.5, 1.5, 2.5, 3.5, 4.5, 5.5, 6.5, 7.5,
  126145. };
  126146. static long _vq_quantmap__44c3_s_p6_0[] = {
  126147. 15, 13, 11, 9, 7, 5, 3, 1,
  126148. 0, 2, 4, 6, 8, 10, 12, 14,
  126149. 16,
  126150. };
  126151. static encode_aux_threshmatch _vq_auxt__44c3_s_p6_0 = {
  126152. _vq_quantthresh__44c3_s_p6_0,
  126153. _vq_quantmap__44c3_s_p6_0,
  126154. 17,
  126155. 17
  126156. };
  126157. static static_codebook _44c3_s_p6_0 = {
  126158. 2, 289,
  126159. _vq_lengthlist__44c3_s_p6_0,
  126160. 1, -529530880, 1611661312, 5, 0,
  126161. _vq_quantlist__44c3_s_p6_0,
  126162. NULL,
  126163. &_vq_auxt__44c3_s_p6_0,
  126164. NULL,
  126165. 0
  126166. };
  126167. static long _vq_quantlist__44c3_s_p7_0[] = {
  126168. 1,
  126169. 0,
  126170. 2,
  126171. };
  126172. static long _vq_lengthlist__44c3_s_p7_0[] = {
  126173. 1, 4, 4, 7, 6, 6, 7, 6, 6, 4, 7, 7,10, 9, 9,11,
  126174. 9, 9, 4, 7, 7,10, 9, 9,11, 9, 9, 7,10,10,11,11,
  126175. 10,12,11,11, 6, 9, 9,11,10,10,11,10,10, 6, 9, 9,
  126176. 11,10,10,11,10,10, 7,11,11,11,11,11,12,11,11, 6,
  126177. 9, 9,11,10,10,11,10,10, 6, 9, 9,11,10,10,11,10,
  126178. 10,
  126179. };
  126180. static float _vq_quantthresh__44c3_s_p7_0[] = {
  126181. -5.5, 5.5,
  126182. };
  126183. static long _vq_quantmap__44c3_s_p7_0[] = {
  126184. 1, 0, 2,
  126185. };
  126186. static encode_aux_threshmatch _vq_auxt__44c3_s_p7_0 = {
  126187. _vq_quantthresh__44c3_s_p7_0,
  126188. _vq_quantmap__44c3_s_p7_0,
  126189. 3,
  126190. 3
  126191. };
  126192. static static_codebook _44c3_s_p7_0 = {
  126193. 4, 81,
  126194. _vq_lengthlist__44c3_s_p7_0,
  126195. 1, -529137664, 1618345984, 2, 0,
  126196. _vq_quantlist__44c3_s_p7_0,
  126197. NULL,
  126198. &_vq_auxt__44c3_s_p7_0,
  126199. NULL,
  126200. 0
  126201. };
  126202. static long _vq_quantlist__44c3_s_p7_1[] = {
  126203. 5,
  126204. 4,
  126205. 6,
  126206. 3,
  126207. 7,
  126208. 2,
  126209. 8,
  126210. 1,
  126211. 9,
  126212. 0,
  126213. 10,
  126214. };
  126215. static long _vq_lengthlist__44c3_s_p7_1[] = {
  126216. 2, 4, 4, 6, 6, 7, 7, 7, 7, 8, 8,10, 5, 5, 6, 6,
  126217. 7, 7, 8, 8, 8, 8,10, 5, 5, 6, 6, 7, 7, 8, 8, 8,
  126218. 8,10, 6, 6, 7, 7, 8, 8, 8, 8, 8, 8,10,10,10, 7,
  126219. 7, 8, 7, 8, 8, 8, 8,10,10,10, 8, 8, 8, 8, 8, 8,
  126220. 8, 8,10,10,10, 7, 8, 8, 8, 8, 8, 8, 8,10,10,10,
  126221. 8, 8, 8, 8, 8, 8, 8, 8,10,10,10,10,10, 8, 8, 8,
  126222. 8, 8, 8,10,10,10,10,10, 9, 9, 8, 8, 9, 8,10,10,
  126223. 10,10,10, 8, 8, 8, 8, 8, 8,
  126224. };
  126225. static float _vq_quantthresh__44c3_s_p7_1[] = {
  126226. -4.5, -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5,
  126227. 3.5, 4.5,
  126228. };
  126229. static long _vq_quantmap__44c3_s_p7_1[] = {
  126230. 9, 7, 5, 3, 1, 0, 2, 4,
  126231. 6, 8, 10,
  126232. };
  126233. static encode_aux_threshmatch _vq_auxt__44c3_s_p7_1 = {
  126234. _vq_quantthresh__44c3_s_p7_1,
  126235. _vq_quantmap__44c3_s_p7_1,
  126236. 11,
  126237. 11
  126238. };
  126239. static static_codebook _44c3_s_p7_1 = {
  126240. 2, 121,
  126241. _vq_lengthlist__44c3_s_p7_1,
  126242. 1, -531365888, 1611661312, 4, 0,
  126243. _vq_quantlist__44c3_s_p7_1,
  126244. NULL,
  126245. &_vq_auxt__44c3_s_p7_1,
  126246. NULL,
  126247. 0
  126248. };
  126249. static long _vq_quantlist__44c3_s_p8_0[] = {
  126250. 6,
  126251. 5,
  126252. 7,
  126253. 4,
  126254. 8,
  126255. 3,
  126256. 9,
  126257. 2,
  126258. 10,
  126259. 1,
  126260. 11,
  126261. 0,
  126262. 12,
  126263. };
  126264. static long _vq_lengthlist__44c3_s_p8_0[] = {
  126265. 1, 4, 4, 6, 6, 7, 7, 8, 8, 9, 9,10,10, 6, 5, 5,
  126266. 7, 7, 8, 8, 8, 8, 9, 9,10,10, 7, 5, 5, 7, 7, 8,
  126267. 8, 8, 8, 9, 9,11,10, 0, 8, 8, 8, 8, 9, 9, 9, 9,
  126268. 10,10,11,11, 0, 8, 8, 8, 8, 9, 9, 9, 9,10,10,11,
  126269. 11, 0,12,12, 9, 9,10,10,10,10,11,11,11,12, 0,13,
  126270. 13, 9, 9,10,10,10,10,11,11,12,12, 0, 0, 0,10,10,
  126271. 10,10,11,11,12,12,12,12, 0, 0, 0,10,10,10,10,11,
  126272. 11,12,12,12,12, 0, 0, 0,14,14,11,11,11,11,12,12,
  126273. 13,13, 0, 0, 0,14,14,11,11,11,11,12,12,13,13, 0,
  126274. 0, 0, 0, 0,12,12,12,12,13,13,14,13, 0, 0, 0, 0,
  126275. 0,13,13,12,12,13,12,14,13,
  126276. };
  126277. static float _vq_quantthresh__44c3_s_p8_0[] = {
  126278. -27.5, -22.5, -17.5, -12.5, -7.5, -2.5, 2.5, 7.5,
  126279. 12.5, 17.5, 22.5, 27.5,
  126280. };
  126281. static long _vq_quantmap__44c3_s_p8_0[] = {
  126282. 11, 9, 7, 5, 3, 1, 0, 2,
  126283. 4, 6, 8, 10, 12,
  126284. };
  126285. static encode_aux_threshmatch _vq_auxt__44c3_s_p8_0 = {
  126286. _vq_quantthresh__44c3_s_p8_0,
  126287. _vq_quantmap__44c3_s_p8_0,
  126288. 13,
  126289. 13
  126290. };
  126291. static static_codebook _44c3_s_p8_0 = {
  126292. 2, 169,
  126293. _vq_lengthlist__44c3_s_p8_0,
  126294. 1, -526516224, 1616117760, 4, 0,
  126295. _vq_quantlist__44c3_s_p8_0,
  126296. NULL,
  126297. &_vq_auxt__44c3_s_p8_0,
  126298. NULL,
  126299. 0
  126300. };
  126301. static long _vq_quantlist__44c3_s_p8_1[] = {
  126302. 2,
  126303. 1,
  126304. 3,
  126305. 0,
  126306. 4,
  126307. };
  126308. static long _vq_lengthlist__44c3_s_p8_1[] = {
  126309. 2, 4, 4, 5, 5, 6, 5, 5, 5, 5, 6, 4, 5, 5, 5, 6,
  126310. 5, 5, 5, 5, 6, 6, 6, 5, 5,
  126311. };
  126312. static float _vq_quantthresh__44c3_s_p8_1[] = {
  126313. -1.5, -0.5, 0.5, 1.5,
  126314. };
  126315. static long _vq_quantmap__44c3_s_p8_1[] = {
  126316. 3, 1, 0, 2, 4,
  126317. };
  126318. static encode_aux_threshmatch _vq_auxt__44c3_s_p8_1 = {
  126319. _vq_quantthresh__44c3_s_p8_1,
  126320. _vq_quantmap__44c3_s_p8_1,
  126321. 5,
  126322. 5
  126323. };
  126324. static static_codebook _44c3_s_p8_1 = {
  126325. 2, 25,
  126326. _vq_lengthlist__44c3_s_p8_1,
  126327. 1, -533725184, 1611661312, 3, 0,
  126328. _vq_quantlist__44c3_s_p8_1,
  126329. NULL,
  126330. &_vq_auxt__44c3_s_p8_1,
  126331. NULL,
  126332. 0
  126333. };
  126334. static long _vq_quantlist__44c3_s_p9_0[] = {
  126335. 6,
  126336. 5,
  126337. 7,
  126338. 4,
  126339. 8,
  126340. 3,
  126341. 9,
  126342. 2,
  126343. 10,
  126344. 1,
  126345. 11,
  126346. 0,
  126347. 12,
  126348. };
  126349. static long _vq_lengthlist__44c3_s_p9_0[] = {
  126350. 1, 4, 4,12,12,12,12,12,12,12,12,12,12, 4, 9, 8,
  126351. 12,12,12,12,12,12,12,12,12,12, 2, 9, 7,12,12,12,
  126352. 12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,
  126353. 12,12,12,12,12,12,11,12,12,12,12,12,12,12,12,12,
  126354. 12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,
  126355. 12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,
  126356. 12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,
  126357. 12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,
  126358. 12,12,12,12,12,12,12,12,12,12,11,11,11,11,11,11,
  126359. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  126360. 11,11,11,11,11,11,11,11,11,
  126361. };
  126362. static float _vq_quantthresh__44c3_s_p9_0[] = {
  126363. -1402.5, -1147.5, -892.5, -637.5, -382.5, -127.5, 127.5, 382.5,
  126364. 637.5, 892.5, 1147.5, 1402.5,
  126365. };
  126366. static long _vq_quantmap__44c3_s_p9_0[] = {
  126367. 11, 9, 7, 5, 3, 1, 0, 2,
  126368. 4, 6, 8, 10, 12,
  126369. };
  126370. static encode_aux_threshmatch _vq_auxt__44c3_s_p9_0 = {
  126371. _vq_quantthresh__44c3_s_p9_0,
  126372. _vq_quantmap__44c3_s_p9_0,
  126373. 13,
  126374. 13
  126375. };
  126376. static static_codebook _44c3_s_p9_0 = {
  126377. 2, 169,
  126378. _vq_lengthlist__44c3_s_p9_0,
  126379. 1, -514332672, 1627381760, 4, 0,
  126380. _vq_quantlist__44c3_s_p9_0,
  126381. NULL,
  126382. &_vq_auxt__44c3_s_p9_0,
  126383. NULL,
  126384. 0
  126385. };
  126386. static long _vq_quantlist__44c3_s_p9_1[] = {
  126387. 7,
  126388. 6,
  126389. 8,
  126390. 5,
  126391. 9,
  126392. 4,
  126393. 10,
  126394. 3,
  126395. 11,
  126396. 2,
  126397. 12,
  126398. 1,
  126399. 13,
  126400. 0,
  126401. 14,
  126402. };
  126403. static long _vq_lengthlist__44c3_s_p9_1[] = {
  126404. 1, 4, 4, 6, 6, 7, 7, 8, 7, 9, 9,10,10,10,10, 6,
  126405. 5, 5, 7, 7, 8, 8,10, 8,11,10,12,12,13,13, 6, 5,
  126406. 5, 7, 7, 8, 8,10, 9,11,11,12,12,13,12,18, 8, 8,
  126407. 8, 8, 9, 9,10, 9,11,10,12,12,13,13,18, 8, 8, 8,
  126408. 8, 9, 9,10,10,11,11,13,12,14,13,18,11,11, 9, 9,
  126409. 10,10,11,11,11,12,13,12,13,14,18,11,11, 9, 8,11,
  126410. 10,11,11,11,11,12,12,14,13,18,18,18,10,11,10,11,
  126411. 12,12,12,12,13,12,14,13,18,18,18,10,11,11, 9,12,
  126412. 11,12,12,12,13,13,13,18,18,17,14,14,11,11,12,12,
  126413. 13,12,14,12,14,13,18,18,18,14,14,11,10,12, 9,12,
  126414. 13,13,13,13,13,18,18,17,16,18,13,13,12,12,13,11,
  126415. 14,12,14,14,17,18,18,17,18,13,12,13,10,12,11,14,
  126416. 14,14,14,17,18,18,18,18,15,16,12,12,13,10,14,12,
  126417. 14,15,18,18,18,16,17,16,14,12,11,13,10,13,13,14,
  126418. 15,
  126419. };
  126420. static float _vq_quantthresh__44c3_s_p9_1[] = {
  126421. -110.5, -93.5, -76.5, -59.5, -42.5, -25.5, -8.5, 8.5,
  126422. 25.5, 42.5, 59.5, 76.5, 93.5, 110.5,
  126423. };
  126424. static long _vq_quantmap__44c3_s_p9_1[] = {
  126425. 13, 11, 9, 7, 5, 3, 1, 0,
  126426. 2, 4, 6, 8, 10, 12, 14,
  126427. };
  126428. static encode_aux_threshmatch _vq_auxt__44c3_s_p9_1 = {
  126429. _vq_quantthresh__44c3_s_p9_1,
  126430. _vq_quantmap__44c3_s_p9_1,
  126431. 15,
  126432. 15
  126433. };
  126434. static static_codebook _44c3_s_p9_1 = {
  126435. 2, 225,
  126436. _vq_lengthlist__44c3_s_p9_1,
  126437. 1, -522338304, 1620115456, 4, 0,
  126438. _vq_quantlist__44c3_s_p9_1,
  126439. NULL,
  126440. &_vq_auxt__44c3_s_p9_1,
  126441. NULL,
  126442. 0
  126443. };
  126444. static long _vq_quantlist__44c3_s_p9_2[] = {
  126445. 8,
  126446. 7,
  126447. 9,
  126448. 6,
  126449. 10,
  126450. 5,
  126451. 11,
  126452. 4,
  126453. 12,
  126454. 3,
  126455. 13,
  126456. 2,
  126457. 14,
  126458. 1,
  126459. 15,
  126460. 0,
  126461. 16,
  126462. };
  126463. static long _vq_lengthlist__44c3_s_p9_2[] = {
  126464. 2, 5, 5, 6, 6, 7, 7, 7, 7, 7, 7, 8, 8, 8, 8, 8,
  126465. 8,10, 6, 6, 7, 7, 8, 7, 8, 8, 8, 8, 8, 9, 9, 9,
  126466. 9, 9,10, 6, 6, 7, 7, 7, 7, 8, 8, 8, 8, 9, 9, 9,
  126467. 9, 9, 9,10, 7, 7, 7, 7, 8, 8, 8, 8, 9, 9, 9, 9,
  126468. 9, 9, 9, 9,10,10,10, 7, 7, 8, 8, 8, 9, 9, 9, 9,
  126469. 9, 9, 9, 9, 9,11,11,11, 8, 8, 8, 8, 9, 9, 9, 9,
  126470. 9, 9, 9, 9, 9, 9,10,10,10, 8, 8, 8, 8, 9, 9, 9,
  126471. 9, 9, 9, 9, 9, 9, 9,10,10,10, 8, 9, 9, 9, 9, 9,
  126472. 9, 9, 9, 9, 9, 9,10, 9,10,10,10,11,11, 9, 9, 9,
  126473. 9, 9, 9, 9, 9, 9, 9, 9, 9,11,10,11,11,11, 9, 9,
  126474. 9, 9, 9, 9,10,10, 9, 9,10, 9,11,10,11,11,11, 9,
  126475. 9, 9, 9, 9, 9, 9, 9,10,10,10, 9,11,11,11,11,11,
  126476. 9, 9, 9, 9,10,10, 9, 9, 9, 9,10, 9,11,11,11,11,
  126477. 11,11,11, 9, 9, 9, 9, 9, 9,10,10,10,10,11,11,11,
  126478. 11,11,11,11,10, 9,10,10, 9,10, 9, 9,10, 9,11,10,
  126479. 10,11,11,11,11, 9,10, 9, 9, 9, 9,10,10,10,10,11,
  126480. 11,11,11,11,11,10,10,10, 9, 9,10, 9,10, 9,10,10,
  126481. 10,10,11,11,11,11,11,11,11, 9, 9, 9, 9, 9,10,10,
  126482. 10,
  126483. };
  126484. static float _vq_quantthresh__44c3_s_p9_2[] = {
  126485. -7.5, -6.5, -5.5, -4.5, -3.5, -2.5, -1.5, -0.5,
  126486. 0.5, 1.5, 2.5, 3.5, 4.5, 5.5, 6.5, 7.5,
  126487. };
  126488. static long _vq_quantmap__44c3_s_p9_2[] = {
  126489. 15, 13, 11, 9, 7, 5, 3, 1,
  126490. 0, 2, 4, 6, 8, 10, 12, 14,
  126491. 16,
  126492. };
  126493. static encode_aux_threshmatch _vq_auxt__44c3_s_p9_2 = {
  126494. _vq_quantthresh__44c3_s_p9_2,
  126495. _vq_quantmap__44c3_s_p9_2,
  126496. 17,
  126497. 17
  126498. };
  126499. static static_codebook _44c3_s_p9_2 = {
  126500. 2, 289,
  126501. _vq_lengthlist__44c3_s_p9_2,
  126502. 1, -529530880, 1611661312, 5, 0,
  126503. _vq_quantlist__44c3_s_p9_2,
  126504. NULL,
  126505. &_vq_auxt__44c3_s_p9_2,
  126506. NULL,
  126507. 0
  126508. };
  126509. static long _huff_lengthlist__44c3_s_short[] = {
  126510. 10, 9,13,11,14,10,12,13,13,14, 7, 2,12, 5,10, 5,
  126511. 7,10,12,14,12, 6, 9, 8, 7, 7, 9,11,13,16,10, 4,
  126512. 12, 5,10, 6, 8,12,14,16,12, 6, 8, 7, 6, 5, 7,11,
  126513. 12,16,10, 4, 8, 5, 6, 4, 6, 9,13,16,10, 6,10, 7,
  126514. 7, 6, 7, 9,13,15,12, 9,11, 9, 8, 6, 7,10,12,14,
  126515. 14,11,10, 9, 6, 5, 6, 9,11,13,15,13,11,10, 6, 5,
  126516. 6, 8, 9,11,
  126517. };
  126518. static static_codebook _huff_book__44c3_s_short = {
  126519. 2, 100,
  126520. _huff_lengthlist__44c3_s_short,
  126521. 0, 0, 0, 0, 0,
  126522. NULL,
  126523. NULL,
  126524. NULL,
  126525. NULL,
  126526. 0
  126527. };
  126528. static long _huff_lengthlist__44c4_s_long[] = {
  126529. 4, 7,11,11,11,11,10,11,12,11, 5, 2,11, 5, 6, 6,
  126530. 7, 9,11,12,11, 9, 6,10, 6, 7, 8, 9,10,11,11, 5,
  126531. 11, 7, 8, 8, 9,11,13,14,11, 6, 5, 8, 4, 5, 7, 8,
  126532. 10,11,10, 6, 7, 7, 5, 5, 6, 8, 9,11,10, 7, 8, 9,
  126533. 6, 6, 6, 7, 8, 9,11, 9, 9,11, 7, 7, 6, 6, 7, 9,
  126534. 12,12,10,13, 9, 8, 7, 7, 7, 8,11,13,11,14,11,10,
  126535. 9, 8, 7, 7,
  126536. };
  126537. static static_codebook _huff_book__44c4_s_long = {
  126538. 2, 100,
  126539. _huff_lengthlist__44c4_s_long,
  126540. 0, 0, 0, 0, 0,
  126541. NULL,
  126542. NULL,
  126543. NULL,
  126544. NULL,
  126545. 0
  126546. };
  126547. static long _vq_quantlist__44c4_s_p1_0[] = {
  126548. 1,
  126549. 0,
  126550. 2,
  126551. };
  126552. static long _vq_lengthlist__44c4_s_p1_0[] = {
  126553. 2, 4, 4, 0, 0, 0, 0, 0, 0, 5, 6, 6, 0, 0, 0, 0,
  126554. 0, 0, 5, 6, 7, 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, 5, 7, 7, 0, 0, 0, 0, 0, 0, 7, 8, 8, 0, 0, 0,
  126559. 0, 0, 0, 6, 8, 8, 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, 5, 7, 7, 0, 0, 0, 0, 0, 0, 6, 8, 7, 0, 0,
  126564. 0, 0, 0, 0, 7, 8, 8, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126565. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126566. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126567. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126568. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126569. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126570. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126571. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126572. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126573. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126574. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126575. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126576. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126577. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126578. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126579. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126580. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126581. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126582. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126583. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126584. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126585. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126586. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126587. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126588. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126589. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126590. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126591. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126592. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126593. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126594. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126595. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126596. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126597. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126598. 0, 0, 0, 0, 0, 0, 0, 0, 0, 5, 7, 7, 0, 0, 0, 0,
  126599. 0, 0, 7, 8, 8, 0, 0, 0, 0, 0, 0, 7, 8, 8, 0, 0,
  126600. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126601. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126602. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126603. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 7, 8, 8, 0, 0, 0,
  126604. 0, 0, 0, 8, 9, 9, 0, 0, 0, 0, 0, 0, 8, 9, 9, 0,
  126605. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126606. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126607. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126608. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 6, 8, 8, 0, 0,
  126609. 0, 0, 0, 0, 8, 9, 8, 0, 0, 0, 0, 0, 0, 8, 9, 9,
  126610. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126611. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126612. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126613. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126614. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126615. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126616. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126617. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126618. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126619. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126620. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126621. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126622. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126623. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126624. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126625. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126626. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126627. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126628. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126629. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126630. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126631. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126632. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126633. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126634. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126635. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126636. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126637. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126638. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126639. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126640. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126641. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126642. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126643. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126644. 0, 0, 4, 7, 7, 0, 0, 0, 0, 0, 0, 7, 8, 8, 0, 0,
  126645. 0, 0, 0, 0, 7, 8, 8, 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, 6, 8, 8, 0, 0, 0, 0, 0, 0, 8, 9, 9, 0,
  126650. 0, 0, 0, 0, 0, 8, 8, 9, 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, 7, 8, 8, 0, 0, 0, 0, 0, 0, 8, 9, 9,
  126655. 0, 0, 0, 0, 0, 0, 8, 9, 9, 0, 0, 0, 0, 0, 0, 0,
  126656. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126657. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126658. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126659. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126660. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126661. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126662. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126663. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126664. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126665. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126666. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126667. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126668. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126669. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126670. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126671. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126672. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126673. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126674. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126675. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126676. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126677. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126678. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126679. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126680. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126681. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126682. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126683. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126684. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126685. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126686. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126687. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126688. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126689. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126690. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126691. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126692. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126693. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126694. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126695. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126696. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126697. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126698. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126699. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126700. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126701. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126702. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126703. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126704. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126705. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126706. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126707. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126708. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126709. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126710. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126711. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126712. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126713. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126714. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126715. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126716. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126717. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126718. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126719. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126720. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126721. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126722. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126723. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126724. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126725. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126726. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126727. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126728. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126729. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126730. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126731. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126732. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126733. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126734. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126735. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126736. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126737. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126738. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126739. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126740. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126741. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126742. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126743. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126744. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126745. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126746. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126747. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126748. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126749. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126750. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126751. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126752. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126753. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126754. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126755. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126756. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126757. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126758. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126759. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126760. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126761. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126762. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126763. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126764. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126765. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126766. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126767. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126768. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126769. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126770. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126771. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126772. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126773. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126774. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126775. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126776. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126777. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126778. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126779. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126780. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126781. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126782. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126783. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126784. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126785. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126786. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126787. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126788. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126789. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126790. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126791. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126792. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126793. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126794. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126795. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126796. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126797. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126798. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126799. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126800. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126801. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126802. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126803. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126804. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126805. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126806. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126807. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126808. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126809. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126810. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126811. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126812. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126813. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126814. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126815. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126816. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126817. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126818. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126819. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126820. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126821. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126822. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126823. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126824. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126825. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126826. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126827. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126828. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126829. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126830. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126831. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126832. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126833. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126834. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126835. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126836. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126837. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126838. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126839. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126840. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126841. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126842. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126843. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126844. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126845. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126846. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126847. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126848. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126849. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126850. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126851. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126852. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126853. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126854. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126855. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126856. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126857. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126858. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126859. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126860. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126861. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126862. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126863. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126864. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126865. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126866. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126867. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126868. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126869. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126870. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126871. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126872. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126873. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126874. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126875. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126876. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126877. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126878. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126879. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126880. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126881. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126882. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126883. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126884. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126885. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126886. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126887. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126888. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126889. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126890. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126891. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126892. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126893. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126894. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126895. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126896. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126897. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126898. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126899. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126900. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126901. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126902. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126903. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126904. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126905. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126906. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126907. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126908. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126909. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126910. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126911. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126912. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126913. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126914. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126915. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126916. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126917. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126918. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126919. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126920. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126921. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126922. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126923. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126924. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126925. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126926. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126927. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126928. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126929. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126930. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126931. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126932. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126933. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126934. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126935. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126936. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126937. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126938. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126939. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126940. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126941. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126942. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126943. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126944. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126945. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126946. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126947. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126948. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126949. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126950. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126951. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126952. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126953. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126954. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126955. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126956. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126957. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126958. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126959. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126960. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126961. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126962. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126963. 0,
  126964. };
  126965. static float _vq_quantthresh__44c4_s_p1_0[] = {
  126966. -0.5, 0.5,
  126967. };
  126968. static long _vq_quantmap__44c4_s_p1_0[] = {
  126969. 1, 0, 2,
  126970. };
  126971. static encode_aux_threshmatch _vq_auxt__44c4_s_p1_0 = {
  126972. _vq_quantthresh__44c4_s_p1_0,
  126973. _vq_quantmap__44c4_s_p1_0,
  126974. 3,
  126975. 3
  126976. };
  126977. static static_codebook _44c4_s_p1_0 = {
  126978. 8, 6561,
  126979. _vq_lengthlist__44c4_s_p1_0,
  126980. 1, -535822336, 1611661312, 2, 0,
  126981. _vq_quantlist__44c4_s_p1_0,
  126982. NULL,
  126983. &_vq_auxt__44c4_s_p1_0,
  126984. NULL,
  126985. 0
  126986. };
  126987. static long _vq_quantlist__44c4_s_p2_0[] = {
  126988. 2,
  126989. 1,
  126990. 3,
  126991. 0,
  126992. 4,
  126993. };
  126994. static long _vq_lengthlist__44c4_s_p2_0[] = {
  126995. 2, 5, 5, 0, 0, 0, 5, 5, 0, 0, 0, 5, 5, 0, 0, 0,
  126996. 7, 7, 0, 0, 0, 0, 0, 0, 0, 5, 6, 6, 0, 0, 0, 7,
  126997. 7, 0, 0, 0, 7, 7, 0, 0, 0,10,10, 0, 0, 0, 0, 0,
  126998. 0, 0, 5, 6, 6, 0, 0, 0, 7, 7, 0, 0, 0, 7, 7, 0,
  126999. 0, 0,10,10, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127000. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127001. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127002. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127003. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127004. 0, 0, 0, 0, 0, 0, 5, 8, 7, 0, 0, 0, 7, 7, 0, 0,
  127005. 0, 7, 7, 0, 0, 0, 9, 9, 0, 0, 0, 0, 0, 0, 0, 5,
  127006. 7, 8, 0, 0, 0, 7, 7, 0, 0, 0, 7, 7, 0, 0, 0, 9,
  127007. 9, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127008. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127009. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127010. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127011. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127012. 0, 0, 0, 5, 7, 7, 0, 0, 0, 7, 7, 0, 0, 0, 7, 7,
  127013. 0, 0, 0, 9, 9, 0, 0, 0, 0, 0, 0, 0, 5, 7, 7, 0,
  127014. 0, 0, 7, 7, 0, 0, 0, 7, 7, 0, 0, 0, 9, 9, 0, 0,
  127015. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127016. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127017. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127018. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127019. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127020. 7,10,10, 0, 0, 0, 9, 9, 0, 0, 0, 9, 9, 0, 0, 0,
  127021. 10,10, 0, 0, 0, 0, 0, 0, 0, 8,10,10, 0, 0, 0, 9,
  127022. 9, 0, 0, 0, 9, 9, 0, 0, 0,10,10, 0, 0, 0, 0, 0,
  127023. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127024. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127025. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127026. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127027. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127028. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127029. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127030. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127031. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127032. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127033. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127034. 0,
  127035. };
  127036. static float _vq_quantthresh__44c4_s_p2_0[] = {
  127037. -1.5, -0.5, 0.5, 1.5,
  127038. };
  127039. static long _vq_quantmap__44c4_s_p2_0[] = {
  127040. 3, 1, 0, 2, 4,
  127041. };
  127042. static encode_aux_threshmatch _vq_auxt__44c4_s_p2_0 = {
  127043. _vq_quantthresh__44c4_s_p2_0,
  127044. _vq_quantmap__44c4_s_p2_0,
  127045. 5,
  127046. 5
  127047. };
  127048. static static_codebook _44c4_s_p2_0 = {
  127049. 4, 625,
  127050. _vq_lengthlist__44c4_s_p2_0,
  127051. 1, -533725184, 1611661312, 3, 0,
  127052. _vq_quantlist__44c4_s_p2_0,
  127053. NULL,
  127054. &_vq_auxt__44c4_s_p2_0,
  127055. NULL,
  127056. 0
  127057. };
  127058. static long _vq_quantlist__44c4_s_p3_0[] = {
  127059. 2,
  127060. 1,
  127061. 3,
  127062. 0,
  127063. 4,
  127064. };
  127065. static long _vq_lengthlist__44c4_s_p3_0[] = {
  127066. 2, 3, 3, 6, 6, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127067. 0, 0, 0, 0, 0, 0, 0, 0, 0, 4, 5, 4, 6, 6, 0, 0,
  127068. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127069. 0, 0, 4, 4, 5, 6, 6, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127070. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 6, 6, 6, 9, 9,
  127071. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127072. 0, 0, 0, 0, 6, 6, 7, 9, 9, 0, 0, 0, 0, 0, 0, 0,
  127073. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127074. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127075. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127076. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127077. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127078. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127079. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127080. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127081. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127082. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127083. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127084. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127085. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127086. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127087. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127088. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127089. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127090. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127091. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127092. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127093. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127094. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127095. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127096. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127097. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127098. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127099. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127100. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127101. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127102. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127103. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127104. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127105. 0,
  127106. };
  127107. static float _vq_quantthresh__44c4_s_p3_0[] = {
  127108. -1.5, -0.5, 0.5, 1.5,
  127109. };
  127110. static long _vq_quantmap__44c4_s_p3_0[] = {
  127111. 3, 1, 0, 2, 4,
  127112. };
  127113. static encode_aux_threshmatch _vq_auxt__44c4_s_p3_0 = {
  127114. _vq_quantthresh__44c4_s_p3_0,
  127115. _vq_quantmap__44c4_s_p3_0,
  127116. 5,
  127117. 5
  127118. };
  127119. static static_codebook _44c4_s_p3_0 = {
  127120. 4, 625,
  127121. _vq_lengthlist__44c4_s_p3_0,
  127122. 1, -533725184, 1611661312, 3, 0,
  127123. _vq_quantlist__44c4_s_p3_0,
  127124. NULL,
  127125. &_vq_auxt__44c4_s_p3_0,
  127126. NULL,
  127127. 0
  127128. };
  127129. static long _vq_quantlist__44c4_s_p4_0[] = {
  127130. 4,
  127131. 3,
  127132. 5,
  127133. 2,
  127134. 6,
  127135. 1,
  127136. 7,
  127137. 0,
  127138. 8,
  127139. };
  127140. static long _vq_lengthlist__44c4_s_p4_0[] = {
  127141. 2, 3, 3, 6, 6, 0, 0, 0, 0, 0, 4, 4, 6, 6, 0, 0,
  127142. 0, 0, 0, 4, 4, 6, 6, 0, 0, 0, 0, 0, 5, 5, 6, 6,
  127143. 0, 0, 0, 0, 0, 0, 0, 6, 6, 0, 0, 0, 0, 0, 0, 0,
  127144. 7, 8, 0, 0, 0, 0, 0, 0, 0, 7, 7, 0, 0, 0, 0, 0,
  127145. 0, 0, 9, 9, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127146. 0,
  127147. };
  127148. static float _vq_quantthresh__44c4_s_p4_0[] = {
  127149. -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5, 3.5,
  127150. };
  127151. static long _vq_quantmap__44c4_s_p4_0[] = {
  127152. 7, 5, 3, 1, 0, 2, 4, 6,
  127153. 8,
  127154. };
  127155. static encode_aux_threshmatch _vq_auxt__44c4_s_p4_0 = {
  127156. _vq_quantthresh__44c4_s_p4_0,
  127157. _vq_quantmap__44c4_s_p4_0,
  127158. 9,
  127159. 9
  127160. };
  127161. static static_codebook _44c4_s_p4_0 = {
  127162. 2, 81,
  127163. _vq_lengthlist__44c4_s_p4_0,
  127164. 1, -531628032, 1611661312, 4, 0,
  127165. _vq_quantlist__44c4_s_p4_0,
  127166. NULL,
  127167. &_vq_auxt__44c4_s_p4_0,
  127168. NULL,
  127169. 0
  127170. };
  127171. static long _vq_quantlist__44c4_s_p5_0[] = {
  127172. 4,
  127173. 3,
  127174. 5,
  127175. 2,
  127176. 6,
  127177. 1,
  127178. 7,
  127179. 0,
  127180. 8,
  127181. };
  127182. static long _vq_lengthlist__44c4_s_p5_0[] = {
  127183. 2, 3, 3, 6, 6, 7, 7, 9, 9, 0, 4, 4, 6, 6, 7, 7,
  127184. 9, 9, 0, 4, 5, 6, 6, 7, 7, 9, 9, 0, 6, 6, 7, 7,
  127185. 8, 8,10,10, 0, 0, 0, 7, 7, 8, 8,10, 9, 0, 0, 0,
  127186. 9, 8, 8, 8,10,10, 0, 0, 0, 8, 8, 8, 8,10,10, 0,
  127187. 0, 0,10,10, 9, 9,11,11, 0, 0, 0, 0, 0, 9, 9,10,
  127188. 10,
  127189. };
  127190. static float _vq_quantthresh__44c4_s_p5_0[] = {
  127191. -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5, 3.5,
  127192. };
  127193. static long _vq_quantmap__44c4_s_p5_0[] = {
  127194. 7, 5, 3, 1, 0, 2, 4, 6,
  127195. 8,
  127196. };
  127197. static encode_aux_threshmatch _vq_auxt__44c4_s_p5_0 = {
  127198. _vq_quantthresh__44c4_s_p5_0,
  127199. _vq_quantmap__44c4_s_p5_0,
  127200. 9,
  127201. 9
  127202. };
  127203. static static_codebook _44c4_s_p5_0 = {
  127204. 2, 81,
  127205. _vq_lengthlist__44c4_s_p5_0,
  127206. 1, -531628032, 1611661312, 4, 0,
  127207. _vq_quantlist__44c4_s_p5_0,
  127208. NULL,
  127209. &_vq_auxt__44c4_s_p5_0,
  127210. NULL,
  127211. 0
  127212. };
  127213. static long _vq_quantlist__44c4_s_p6_0[] = {
  127214. 8,
  127215. 7,
  127216. 9,
  127217. 6,
  127218. 10,
  127219. 5,
  127220. 11,
  127221. 4,
  127222. 12,
  127223. 3,
  127224. 13,
  127225. 2,
  127226. 14,
  127227. 1,
  127228. 15,
  127229. 0,
  127230. 16,
  127231. };
  127232. static long _vq_lengthlist__44c4_s_p6_0[] = {
  127233. 2, 4, 4, 6, 6, 8, 8, 9, 9, 8, 8, 9, 9,10,10,11,
  127234. 11, 0, 4, 4, 6, 6, 8, 8, 9, 9, 9, 9,10,10,11,11,
  127235. 11,11, 0, 4, 4, 7, 6, 8, 8, 9, 9, 9, 9,10,10,11,
  127236. 11,11,11, 0, 6, 6, 7, 7, 8, 8, 9, 9, 9, 9,10,10,
  127237. 11,11,11,12, 0, 0, 0, 7, 7, 8, 8, 9, 9, 9, 9,10,
  127238. 10,11,11,12,12, 0, 0, 0, 8, 8, 8, 8, 9, 9, 9, 9,
  127239. 10,10,11,11,12,12, 0, 0, 0, 8, 8, 8, 8, 9, 9, 9,
  127240. 9,10,10,11,11,12,12, 0, 0, 0, 9, 9, 9, 9,10,10,
  127241. 10,10,11,11,11,11,12,12, 0, 0, 0, 0, 0, 9, 9,10,
  127242. 10,10,10,11,11,11,11,12,12, 0, 0, 0, 0, 0, 9, 9,
  127243. 9,10,10,10,11,11,11,11,12,12, 0, 0, 0, 0, 0, 9,
  127244. 9, 9, 9,10,10,11,11,11,12,12,12, 0, 0, 0, 0, 0,
  127245. 10,10,10,10,11,11,11,11,12,12,13,12, 0, 0, 0, 0,
  127246. 0, 0, 0,10,10,11,11,11,11,12,12,12,12, 0, 0, 0,
  127247. 0, 0, 0, 0,11,11,11,11,12,12,12,12,13,13, 0, 0,
  127248. 0, 0, 0, 0, 0,11,11,11,11,12,12,12,12,13,13, 0,
  127249. 0, 0, 0, 0, 0, 0,12,12,12,12,12,12,13,13,13,13,
  127250. 0, 0, 0, 0, 0, 0, 0, 0, 0,12,12,12,12,12,13,13,
  127251. 13,
  127252. };
  127253. static float _vq_quantthresh__44c4_s_p6_0[] = {
  127254. -7.5, -6.5, -5.5, -4.5, -3.5, -2.5, -1.5, -0.5,
  127255. 0.5, 1.5, 2.5, 3.5, 4.5, 5.5, 6.5, 7.5,
  127256. };
  127257. static long _vq_quantmap__44c4_s_p6_0[] = {
  127258. 15, 13, 11, 9, 7, 5, 3, 1,
  127259. 0, 2, 4, 6, 8, 10, 12, 14,
  127260. 16,
  127261. };
  127262. static encode_aux_threshmatch _vq_auxt__44c4_s_p6_0 = {
  127263. _vq_quantthresh__44c4_s_p6_0,
  127264. _vq_quantmap__44c4_s_p6_0,
  127265. 17,
  127266. 17
  127267. };
  127268. static static_codebook _44c4_s_p6_0 = {
  127269. 2, 289,
  127270. _vq_lengthlist__44c4_s_p6_0,
  127271. 1, -529530880, 1611661312, 5, 0,
  127272. _vq_quantlist__44c4_s_p6_0,
  127273. NULL,
  127274. &_vq_auxt__44c4_s_p6_0,
  127275. NULL,
  127276. 0
  127277. };
  127278. static long _vq_quantlist__44c4_s_p7_0[] = {
  127279. 1,
  127280. 0,
  127281. 2,
  127282. };
  127283. static long _vq_lengthlist__44c4_s_p7_0[] = {
  127284. 1, 4, 4, 7, 6, 6, 7, 6, 6, 4, 7, 7,10, 9, 9,11,
  127285. 9, 9, 4, 7, 7,10, 9, 9,11, 9, 9, 7,10,10,11,11,
  127286. 10,11,11,11, 6, 9, 9,11,10,10,11,10,10, 6, 9, 9,
  127287. 11,10,10,11,10,10, 7,11,11,12,11,11,12,11,11, 6,
  127288. 9, 9,11,10,10,11,10,10, 6, 9, 9,11,10,10,11,10,
  127289. 10,
  127290. };
  127291. static float _vq_quantthresh__44c4_s_p7_0[] = {
  127292. -5.5, 5.5,
  127293. };
  127294. static long _vq_quantmap__44c4_s_p7_0[] = {
  127295. 1, 0, 2,
  127296. };
  127297. static encode_aux_threshmatch _vq_auxt__44c4_s_p7_0 = {
  127298. _vq_quantthresh__44c4_s_p7_0,
  127299. _vq_quantmap__44c4_s_p7_0,
  127300. 3,
  127301. 3
  127302. };
  127303. static static_codebook _44c4_s_p7_0 = {
  127304. 4, 81,
  127305. _vq_lengthlist__44c4_s_p7_0,
  127306. 1, -529137664, 1618345984, 2, 0,
  127307. _vq_quantlist__44c4_s_p7_0,
  127308. NULL,
  127309. &_vq_auxt__44c4_s_p7_0,
  127310. NULL,
  127311. 0
  127312. };
  127313. static long _vq_quantlist__44c4_s_p7_1[] = {
  127314. 5,
  127315. 4,
  127316. 6,
  127317. 3,
  127318. 7,
  127319. 2,
  127320. 8,
  127321. 1,
  127322. 9,
  127323. 0,
  127324. 10,
  127325. };
  127326. static long _vq_lengthlist__44c4_s_p7_1[] = {
  127327. 2, 4, 4, 6, 6, 7, 7, 7, 7, 8, 8,10, 5, 5, 6, 6,
  127328. 7, 7, 8, 8, 8, 8,10, 5, 5, 6, 6, 7, 7, 8, 8, 8,
  127329. 8,10, 6, 6, 7, 7, 8, 8, 8, 8, 8, 8,10,10,10, 7,
  127330. 7, 8, 8, 8, 8, 8, 8,10,10,10, 8, 7, 8, 8, 8, 8,
  127331. 8, 8,10,10,10, 7, 7, 8, 8, 8, 8, 8, 8,10,10,10,
  127332. 8, 8, 8, 8, 8, 8, 8, 8,10,10,10,10,10, 8, 8, 8,
  127333. 8, 8, 8,10,10,10,10,10, 9, 9, 8, 8, 9, 8,10,10,
  127334. 10,10,10, 8, 8, 8, 8, 9, 9,
  127335. };
  127336. static float _vq_quantthresh__44c4_s_p7_1[] = {
  127337. -4.5, -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5,
  127338. 3.5, 4.5,
  127339. };
  127340. static long _vq_quantmap__44c4_s_p7_1[] = {
  127341. 9, 7, 5, 3, 1, 0, 2, 4,
  127342. 6, 8, 10,
  127343. };
  127344. static encode_aux_threshmatch _vq_auxt__44c4_s_p7_1 = {
  127345. _vq_quantthresh__44c4_s_p7_1,
  127346. _vq_quantmap__44c4_s_p7_1,
  127347. 11,
  127348. 11
  127349. };
  127350. static static_codebook _44c4_s_p7_1 = {
  127351. 2, 121,
  127352. _vq_lengthlist__44c4_s_p7_1,
  127353. 1, -531365888, 1611661312, 4, 0,
  127354. _vq_quantlist__44c4_s_p7_1,
  127355. NULL,
  127356. &_vq_auxt__44c4_s_p7_1,
  127357. NULL,
  127358. 0
  127359. };
  127360. static long _vq_quantlist__44c4_s_p8_0[] = {
  127361. 6,
  127362. 5,
  127363. 7,
  127364. 4,
  127365. 8,
  127366. 3,
  127367. 9,
  127368. 2,
  127369. 10,
  127370. 1,
  127371. 11,
  127372. 0,
  127373. 12,
  127374. };
  127375. static long _vq_lengthlist__44c4_s_p8_0[] = {
  127376. 1, 4, 4, 6, 6, 7, 7, 8, 8, 9, 9,10,10, 6, 5, 5,
  127377. 7, 7, 8, 8, 8, 8, 9,10,11,11, 7, 5, 5, 7, 7, 8,
  127378. 8, 9, 9,10,10,11,11, 0, 8, 8, 8, 8, 9, 9, 9, 9,
  127379. 10,10,11,11, 0, 8, 8, 8, 8, 9, 9, 9, 9,10,10,11,
  127380. 11, 0,12,12, 9, 9, 9, 9,10,10,10,10,11,11, 0,13,
  127381. 13, 9, 9,10, 9,10,10,11,11,11,12, 0, 0, 0,10,10,
  127382. 10,10,10,10,11,11,12,12, 0, 0, 0,10,10,10,10,10,
  127383. 10,11,11,12,12, 0, 0, 0,14,14,11,11,11,11,12,12,
  127384. 12,12, 0, 0, 0,14,14,11,11,11,11,12,12,12,13, 0,
  127385. 0, 0, 0, 0,12,12,12,12,12,12,13,13, 0, 0, 0, 0,
  127386. 0,13,12,12,12,12,12,13,13,
  127387. };
  127388. static float _vq_quantthresh__44c4_s_p8_0[] = {
  127389. -27.5, -22.5, -17.5, -12.5, -7.5, -2.5, 2.5, 7.5,
  127390. 12.5, 17.5, 22.5, 27.5,
  127391. };
  127392. static long _vq_quantmap__44c4_s_p8_0[] = {
  127393. 11, 9, 7, 5, 3, 1, 0, 2,
  127394. 4, 6, 8, 10, 12,
  127395. };
  127396. static encode_aux_threshmatch _vq_auxt__44c4_s_p8_0 = {
  127397. _vq_quantthresh__44c4_s_p8_0,
  127398. _vq_quantmap__44c4_s_p8_0,
  127399. 13,
  127400. 13
  127401. };
  127402. static static_codebook _44c4_s_p8_0 = {
  127403. 2, 169,
  127404. _vq_lengthlist__44c4_s_p8_0,
  127405. 1, -526516224, 1616117760, 4, 0,
  127406. _vq_quantlist__44c4_s_p8_0,
  127407. NULL,
  127408. &_vq_auxt__44c4_s_p8_0,
  127409. NULL,
  127410. 0
  127411. };
  127412. static long _vq_quantlist__44c4_s_p8_1[] = {
  127413. 2,
  127414. 1,
  127415. 3,
  127416. 0,
  127417. 4,
  127418. };
  127419. static long _vq_lengthlist__44c4_s_p8_1[] = {
  127420. 2, 4, 4, 5, 5, 6, 5, 5, 5, 5, 6, 5, 4, 5, 5, 6,
  127421. 5, 5, 5, 5, 6, 6, 6, 5, 5,
  127422. };
  127423. static float _vq_quantthresh__44c4_s_p8_1[] = {
  127424. -1.5, -0.5, 0.5, 1.5,
  127425. };
  127426. static long _vq_quantmap__44c4_s_p8_1[] = {
  127427. 3, 1, 0, 2, 4,
  127428. };
  127429. static encode_aux_threshmatch _vq_auxt__44c4_s_p8_1 = {
  127430. _vq_quantthresh__44c4_s_p8_1,
  127431. _vq_quantmap__44c4_s_p8_1,
  127432. 5,
  127433. 5
  127434. };
  127435. static static_codebook _44c4_s_p8_1 = {
  127436. 2, 25,
  127437. _vq_lengthlist__44c4_s_p8_1,
  127438. 1, -533725184, 1611661312, 3, 0,
  127439. _vq_quantlist__44c4_s_p8_1,
  127440. NULL,
  127441. &_vq_auxt__44c4_s_p8_1,
  127442. NULL,
  127443. 0
  127444. };
  127445. static long _vq_quantlist__44c4_s_p9_0[] = {
  127446. 6,
  127447. 5,
  127448. 7,
  127449. 4,
  127450. 8,
  127451. 3,
  127452. 9,
  127453. 2,
  127454. 10,
  127455. 1,
  127456. 11,
  127457. 0,
  127458. 12,
  127459. };
  127460. static long _vq_lengthlist__44c4_s_p9_0[] = {
  127461. 1, 3, 3,12,12,12,12,12,12,12,12,12,12, 4, 7, 7,
  127462. 12,12,12,12,12,12,12,12,12,12, 3, 8, 8,12,12,12,
  127463. 12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,
  127464. 12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,
  127465. 12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,
  127466. 12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,
  127467. 12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,
  127468. 12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,
  127469. 12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,
  127470. 12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,
  127471. 12,12,12,12,12,12,12,12,12,
  127472. };
  127473. static float _vq_quantthresh__44c4_s_p9_0[] = {
  127474. -1732.5, -1417.5, -1102.5, -787.5, -472.5, -157.5, 157.5, 472.5,
  127475. 787.5, 1102.5, 1417.5, 1732.5,
  127476. };
  127477. static long _vq_quantmap__44c4_s_p9_0[] = {
  127478. 11, 9, 7, 5, 3, 1, 0, 2,
  127479. 4, 6, 8, 10, 12,
  127480. };
  127481. static encode_aux_threshmatch _vq_auxt__44c4_s_p9_0 = {
  127482. _vq_quantthresh__44c4_s_p9_0,
  127483. _vq_quantmap__44c4_s_p9_0,
  127484. 13,
  127485. 13
  127486. };
  127487. static static_codebook _44c4_s_p9_0 = {
  127488. 2, 169,
  127489. _vq_lengthlist__44c4_s_p9_0,
  127490. 1, -513964032, 1628680192, 4, 0,
  127491. _vq_quantlist__44c4_s_p9_0,
  127492. NULL,
  127493. &_vq_auxt__44c4_s_p9_0,
  127494. NULL,
  127495. 0
  127496. };
  127497. static long _vq_quantlist__44c4_s_p9_1[] = {
  127498. 7,
  127499. 6,
  127500. 8,
  127501. 5,
  127502. 9,
  127503. 4,
  127504. 10,
  127505. 3,
  127506. 11,
  127507. 2,
  127508. 12,
  127509. 1,
  127510. 13,
  127511. 0,
  127512. 14,
  127513. };
  127514. static long _vq_lengthlist__44c4_s_p9_1[] = {
  127515. 1, 4, 4, 5, 5, 7, 7, 9, 8,10, 9,10,10,10,10, 6,
  127516. 5, 5, 7, 7, 9, 8,10, 9,11,10,12,12,13,13, 6, 5,
  127517. 5, 7, 7, 9, 9,10,10,11,11,12,12,12,13,19, 8, 8,
  127518. 8, 8, 9, 9,10,10,12,11,12,12,13,13,19, 8, 8, 8,
  127519. 8, 9, 9,11,11,12,12,13,13,13,13,19,12,12, 9, 9,
  127520. 11,11,11,11,12,11,13,12,13,13,18,12,12, 9, 9,11,
  127521. 10,11,11,12,12,12,13,13,14,19,18,18,11,11,11,11,
  127522. 12,12,13,12,13,13,14,14,16,18,18,11,11,11,10,12,
  127523. 11,13,13,13,13,13,14,17,18,18,14,15,11,12,12,13,
  127524. 13,13,13,14,14,14,18,18,18,15,15,12,10,13,10,13,
  127525. 13,13,13,13,14,18,17,18,17,18,12,13,12,13,13,13,
  127526. 14,14,16,14,18,17,18,18,17,13,12,13,10,12,12,14,
  127527. 14,14,14,17,18,18,18,18,14,15,12,12,13,12,14,14,
  127528. 15,15,18,18,18,17,18,15,14,12,11,12,12,14,14,14,
  127529. 15,
  127530. };
  127531. static float _vq_quantthresh__44c4_s_p9_1[] = {
  127532. -136.5, -115.5, -94.5, -73.5, -52.5, -31.5, -10.5, 10.5,
  127533. 31.5, 52.5, 73.5, 94.5, 115.5, 136.5,
  127534. };
  127535. static long _vq_quantmap__44c4_s_p9_1[] = {
  127536. 13, 11, 9, 7, 5, 3, 1, 0,
  127537. 2, 4, 6, 8, 10, 12, 14,
  127538. };
  127539. static encode_aux_threshmatch _vq_auxt__44c4_s_p9_1 = {
  127540. _vq_quantthresh__44c4_s_p9_1,
  127541. _vq_quantmap__44c4_s_p9_1,
  127542. 15,
  127543. 15
  127544. };
  127545. static static_codebook _44c4_s_p9_1 = {
  127546. 2, 225,
  127547. _vq_lengthlist__44c4_s_p9_1,
  127548. 1, -520986624, 1620377600, 4, 0,
  127549. _vq_quantlist__44c4_s_p9_1,
  127550. NULL,
  127551. &_vq_auxt__44c4_s_p9_1,
  127552. NULL,
  127553. 0
  127554. };
  127555. static long _vq_quantlist__44c4_s_p9_2[] = {
  127556. 10,
  127557. 9,
  127558. 11,
  127559. 8,
  127560. 12,
  127561. 7,
  127562. 13,
  127563. 6,
  127564. 14,
  127565. 5,
  127566. 15,
  127567. 4,
  127568. 16,
  127569. 3,
  127570. 17,
  127571. 2,
  127572. 18,
  127573. 1,
  127574. 19,
  127575. 0,
  127576. 20,
  127577. };
  127578. static long _vq_lengthlist__44c4_s_p9_2[] = {
  127579. 2, 5, 5, 6, 6, 7, 7, 7, 7, 8, 8, 8, 8, 8, 8, 8,
  127580. 8, 9, 9, 9, 9,11, 6, 6, 7, 7, 8, 8, 8, 8, 9, 9,
  127581. 9, 9, 9, 9, 9, 9,10,10,10,10,11, 6, 6, 7, 7, 8,
  127582. 8, 8, 8, 9, 9, 9, 9, 9, 9,10, 9,10,10,10,10,11,
  127583. 7, 7, 7, 7, 8, 8, 9, 9, 9, 9, 9, 9, 9,10,10,10,
  127584. 10,10,10,10,12,11,11, 7, 7, 8, 8, 9, 9, 9, 9, 9,
  127585. 9,10,10,10,10,10,10,10,10,12,11,12, 8, 8, 8, 8,
  127586. 9, 9, 9, 9, 9,10,10,10,10,10,10,10,10,10,11,11,
  127587. 11, 8, 8, 8, 8, 9, 9, 9, 9,10,10,10,10,10,10,10,
  127588. 10,10,10,11,11,12, 9, 9, 9, 9, 9, 9,10, 9,10,10,
  127589. 10,10,10,10,10,10,10,10,11,11,11,11,11, 9, 9, 9,
  127590. 9,10,10,10,10,10,10,10,10,10,10,10,10,11,12,11,
  127591. 11,11, 9, 9, 9,10,10,10,10,10,10,10,10,10,10,10,
  127592. 10,10,11,11,11,11,11, 9, 9, 9, 9,10,10,10,10,10,
  127593. 10,10,10,10,10,10,10,11,11,11,12,12,10,10,10,10,
  127594. 10,10,10,10,10,10,10,10,10,10,10,10,11,12,11,12,
  127595. 11,11,11, 9,10,10,10,10,10,10,10,10,10,10,10,10,
  127596. 10,11,12,11,11,11,11,11,10,10,10,10,10,10,10,10,
  127597. 10,10,10,10,10,10,11,11,11,12,11,11,11,10,10,10,
  127598. 10,10,10,10,10,10,10,10,10,10,10,12,11,11,12,11,
  127599. 11,11,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  127600. 11,11,11,11,11,11,11,11,11,10,10,10,10,10,10,10,
  127601. 10,10,10,10,10,11,11,11,11,12,12,11,11,11,11,11,
  127602. 11,11,10,10,10,10,10,10,10,10,12,12,12,11,11,11,
  127603. 12,11,11,11,10,10,10,10,10,10,10,10,10,10,10,12,
  127604. 11,12,12,12,12,12,11,12,11,11,10,10,10,10,10,10,
  127605. 10,10,10,10,12,12,12,12,11,11,11,11,11,11,11,10,
  127606. 10,10,10,10,10,10,10,10,10,
  127607. };
  127608. static float _vq_quantthresh__44c4_s_p9_2[] = {
  127609. -9.5, -8.5, -7.5, -6.5, -5.5, -4.5, -3.5, -2.5,
  127610. -1.5, -0.5, 0.5, 1.5, 2.5, 3.5, 4.5, 5.5,
  127611. 6.5, 7.5, 8.5, 9.5,
  127612. };
  127613. static long _vq_quantmap__44c4_s_p9_2[] = {
  127614. 19, 17, 15, 13, 11, 9, 7, 5,
  127615. 3, 1, 0, 2, 4, 6, 8, 10,
  127616. 12, 14, 16, 18, 20,
  127617. };
  127618. static encode_aux_threshmatch _vq_auxt__44c4_s_p9_2 = {
  127619. _vq_quantthresh__44c4_s_p9_2,
  127620. _vq_quantmap__44c4_s_p9_2,
  127621. 21,
  127622. 21
  127623. };
  127624. static static_codebook _44c4_s_p9_2 = {
  127625. 2, 441,
  127626. _vq_lengthlist__44c4_s_p9_2,
  127627. 1, -529268736, 1611661312, 5, 0,
  127628. _vq_quantlist__44c4_s_p9_2,
  127629. NULL,
  127630. &_vq_auxt__44c4_s_p9_2,
  127631. NULL,
  127632. 0
  127633. };
  127634. static long _huff_lengthlist__44c4_s_short[] = {
  127635. 4, 7,14,10,15,10,12,15,16,15, 4, 2,11, 5,10, 6,
  127636. 8,11,14,14,14,10, 7,11, 6, 8,10,11,13,15, 9, 4,
  127637. 11, 5, 9, 6, 9,12,14,15,14, 9, 6, 9, 4, 5, 7,10,
  127638. 12,13, 9, 5, 7, 6, 5, 5, 7,10,13,13,10, 8, 9, 8,
  127639. 7, 6, 8,10,14,14,13,11,10,10, 7, 7, 8,11,14,15,
  127640. 13,12, 9, 9, 6, 5, 7,10,14,17,15,13,11,10, 6, 6,
  127641. 7, 9,12,17,
  127642. };
  127643. static static_codebook _huff_book__44c4_s_short = {
  127644. 2, 100,
  127645. _huff_lengthlist__44c4_s_short,
  127646. 0, 0, 0, 0, 0,
  127647. NULL,
  127648. NULL,
  127649. NULL,
  127650. NULL,
  127651. 0
  127652. };
  127653. static long _huff_lengthlist__44c5_s_long[] = {
  127654. 3, 8, 9,13,10,12,12,12,12,12, 6, 4, 6, 8, 6, 8,
  127655. 10,10,11,12, 8, 5, 4,10, 4, 7, 8, 9,10,11,13, 8,
  127656. 10, 8, 9, 9,11,12,13,14,10, 6, 4, 9, 3, 5, 6, 8,
  127657. 10,11,11, 8, 6, 9, 5, 5, 6, 7, 9,11,12, 9, 7,11,
  127658. 6, 6, 6, 7, 8,10,12,11, 9,12, 7, 7, 6, 6, 7, 9,
  127659. 13,12,10,13, 9, 8, 7, 7, 7, 8,11,15,11,15,11,10,
  127660. 9, 8, 7, 7,
  127661. };
  127662. static static_codebook _huff_book__44c5_s_long = {
  127663. 2, 100,
  127664. _huff_lengthlist__44c5_s_long,
  127665. 0, 0, 0, 0, 0,
  127666. NULL,
  127667. NULL,
  127668. NULL,
  127669. NULL,
  127670. 0
  127671. };
  127672. static long _vq_quantlist__44c5_s_p1_0[] = {
  127673. 1,
  127674. 0,
  127675. 2,
  127676. };
  127677. static long _vq_lengthlist__44c5_s_p1_0[] = {
  127678. 2, 4, 4, 0, 0, 0, 0, 0, 0, 4, 7, 7, 0, 0, 0, 0,
  127679. 0, 0, 4, 6, 7, 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, 5, 7, 7, 0, 0, 0, 0, 0, 0, 7, 9, 9, 0, 0, 0,
  127684. 0, 0, 0, 7, 8, 9, 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, 4, 7, 7, 0, 0, 0, 0, 0, 0, 7, 9, 8, 0, 0,
  127689. 0, 0, 0, 0, 7, 9, 9, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127690. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127691. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127692. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127693. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127694. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127695. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127696. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127697. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127698. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127699. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127700. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127701. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127702. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127703. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127704. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127705. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127706. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127707. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127708. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127709. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127710. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127711. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127712. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127713. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127714. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127715. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127716. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127717. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127718. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127719. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127720. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127721. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127722. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127723. 0, 0, 0, 0, 0, 0, 0, 0, 0, 4, 7, 7, 0, 0, 0, 0,
  127724. 0, 0, 7, 9, 9, 0, 0, 0, 0, 0, 0, 7, 9, 9, 0, 0,
  127725. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127726. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127727. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127728. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 7, 9, 9, 0, 0, 0,
  127729. 0, 0, 0, 9,10,11, 0, 0, 0, 0, 0, 0, 9,10,10, 0,
  127730. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127731. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127732. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127733. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 7, 9, 9, 0, 0,
  127734. 0, 0, 0, 0, 8,10, 9, 0, 0, 0, 0, 0, 0, 9,10,11,
  127735. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127736. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127737. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127738. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127739. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127740. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127741. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127742. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127743. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127744. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127745. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127746. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127747. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127748. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127749. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127750. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127751. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127752. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127753. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127754. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127755. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127756. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127757. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127758. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127759. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127760. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127761. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127762. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127763. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127764. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127765. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127766. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127767. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127768. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127769. 0, 0, 4, 7, 7, 0, 0, 0, 0, 0, 0, 7, 9, 9, 0, 0,
  127770. 0, 0, 0, 0, 7, 9, 9, 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. 0, 0, 0, 7, 9, 9, 0, 0, 0, 0, 0, 0, 9,11,10, 0,
  127775. 0, 0, 0, 0, 0, 8, 9,10, 0, 0, 0, 0, 0, 0, 0, 0,
  127776. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 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, 7, 9, 9, 0, 0, 0, 0, 0, 0, 9,10,10,
  127780. 0, 0, 0, 0, 0, 0, 9,11,10, 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, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127789. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127790. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127791. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127792. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127793. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127794. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127795. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127796. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127797. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127798. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127799. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127800. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127801. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127802. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127803. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127804. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127805. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127806. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127807. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127808. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127809. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127810. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127811. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127812. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127813. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127814. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127815. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127816. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127817. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127818. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127819. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127820. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127821. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127822. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127823. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127824. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127825. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127826. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127827. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127828. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127829. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127830. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127831. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127832. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127833. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127834. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127835. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127836. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127837. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127838. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127839. 0, 0, 0, 0, 0, 0, 0, 0, 0, 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, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127860. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127861. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127862. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127863. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127864. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127865. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127866. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127867. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127868. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127869. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127870. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127871. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127872. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127873. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127874. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127875. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127876. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127877. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127878. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127879. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127880. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127881. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127882. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127883. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127884. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127885. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127886. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127887. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127888. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127889. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127890. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127891. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127892. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127893. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127894. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127895. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127896. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127897. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127898. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127899. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127900. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127901. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127902. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127903. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127904. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127905. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127906. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127907. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127908. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127909. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127910. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127911. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127912. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127913. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127914. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127915. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127916. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127917. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127918. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127919. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127920. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127921. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127922. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127923. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127924. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127925. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127926. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127927. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127928. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127929. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127930. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127931. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127932. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127933. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127934. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127935. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127936. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127937. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127938. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127939. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127940. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127941. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127942. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127943. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127944. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127945. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127946. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127947. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127948. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127949. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127950. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127951. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127952. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127953. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127954. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127955. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127956. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127957. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127958. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127959. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127960. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127961. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127962. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127963. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127964. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127965. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127966. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127967. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127968. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127969. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127970. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127971. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127972. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127973. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127974. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127975. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127976. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127977. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127978. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127979. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127980. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127981. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127982. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127983. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127984. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127985. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127986. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127987. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127988. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127989. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127990. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127991. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127992. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127993. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127994. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127995. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127996. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127997. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127998. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127999. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128000. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128001. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128002. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128003. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128004. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128005. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128006. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128007. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128008. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128009. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128010. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128011. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128012. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128013. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128014. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128015. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128016. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128017. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128018. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128019. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128020. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128021. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128022. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128023. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128024. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128025. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128026. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128027. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128028. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128029. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128030. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128031. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128032. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128033. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128034. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128035. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128036. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128037. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128038. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128039. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128040. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128041. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128042. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128043. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128044. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128045. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128046. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128047. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128048. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128049. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128050. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128051. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128052. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128053. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128054. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128055. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128056. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128057. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128058. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128059. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128060. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128061. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128062. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128063. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128064. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128065. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128066. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128067. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128068. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128069. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128070. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128071. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128072. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128073. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128074. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128075. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128076. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128077. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128078. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128079. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128080. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128081. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128082. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128083. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128084. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128085. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128086. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128087. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128088. 0,
  128089. };
  128090. static float _vq_quantthresh__44c5_s_p1_0[] = {
  128091. -0.5, 0.5,
  128092. };
  128093. static long _vq_quantmap__44c5_s_p1_0[] = {
  128094. 1, 0, 2,
  128095. };
  128096. static encode_aux_threshmatch _vq_auxt__44c5_s_p1_0 = {
  128097. _vq_quantthresh__44c5_s_p1_0,
  128098. _vq_quantmap__44c5_s_p1_0,
  128099. 3,
  128100. 3
  128101. };
  128102. static static_codebook _44c5_s_p1_0 = {
  128103. 8, 6561,
  128104. _vq_lengthlist__44c5_s_p1_0,
  128105. 1, -535822336, 1611661312, 2, 0,
  128106. _vq_quantlist__44c5_s_p1_0,
  128107. NULL,
  128108. &_vq_auxt__44c5_s_p1_0,
  128109. NULL,
  128110. 0
  128111. };
  128112. static long _vq_quantlist__44c5_s_p2_0[] = {
  128113. 2,
  128114. 1,
  128115. 3,
  128116. 0,
  128117. 4,
  128118. };
  128119. static long _vq_lengthlist__44c5_s_p2_0[] = {
  128120. 2, 4, 4, 0, 0, 0, 5, 5, 0, 0, 0, 5, 5, 0, 0, 0,
  128121. 8, 7, 0, 0, 0, 0, 0, 0, 0, 4, 6, 6, 0, 0, 0, 8,
  128122. 8, 0, 0, 0, 8, 7, 0, 0, 0,10,10, 0, 0, 0, 0, 0,
  128123. 0, 0, 4, 6, 6, 0, 0, 0, 8, 8, 0, 0, 0, 7, 8, 0,
  128124. 0, 0,10,10, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128125. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128126. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128127. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128128. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128129. 0, 0, 0, 0, 0, 0, 5, 8, 7, 0, 0, 0, 8, 8, 0, 0,
  128130. 0, 8, 8, 0, 0, 0,10,10, 0, 0, 0, 0, 0, 0, 0, 5,
  128131. 7, 8, 0, 0, 0, 8, 8, 0, 0, 0, 8, 8, 0, 0, 0,10,
  128132. 10, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128133. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128134. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128135. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128136. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128137. 0, 0, 0, 5, 8, 8, 0, 0, 0, 8, 8, 0, 0, 0, 8, 8,
  128138. 0, 0, 0,10,10, 0, 0, 0, 0, 0, 0, 0, 5, 8, 8, 0,
  128139. 0, 0, 8, 8, 0, 0, 0, 8, 8, 0, 0, 0,10,10, 0, 0,
  128140. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128141. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128142. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128143. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128144. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128145. 8,10,10, 0, 0, 0,10,10, 0, 0, 0, 9,10, 0, 0, 0,
  128146. 11,10, 0, 0, 0, 0, 0, 0, 0, 8,10,10, 0, 0, 0,10,
  128147. 10, 0, 0, 0,10,10, 0, 0, 0,10,11, 0, 0, 0, 0, 0,
  128148. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128149. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128150. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128151. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128152. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128153. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128154. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128155. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128156. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128157. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128158. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128159. 0,
  128160. };
  128161. static float _vq_quantthresh__44c5_s_p2_0[] = {
  128162. -1.5, -0.5, 0.5, 1.5,
  128163. };
  128164. static long _vq_quantmap__44c5_s_p2_0[] = {
  128165. 3, 1, 0, 2, 4,
  128166. };
  128167. static encode_aux_threshmatch _vq_auxt__44c5_s_p2_0 = {
  128168. _vq_quantthresh__44c5_s_p2_0,
  128169. _vq_quantmap__44c5_s_p2_0,
  128170. 5,
  128171. 5
  128172. };
  128173. static static_codebook _44c5_s_p2_0 = {
  128174. 4, 625,
  128175. _vq_lengthlist__44c5_s_p2_0,
  128176. 1, -533725184, 1611661312, 3, 0,
  128177. _vq_quantlist__44c5_s_p2_0,
  128178. NULL,
  128179. &_vq_auxt__44c5_s_p2_0,
  128180. NULL,
  128181. 0
  128182. };
  128183. static long _vq_quantlist__44c5_s_p3_0[] = {
  128184. 2,
  128185. 1,
  128186. 3,
  128187. 0,
  128188. 4,
  128189. };
  128190. static long _vq_lengthlist__44c5_s_p3_0[] = {
  128191. 2, 4, 3, 5, 5, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128192. 0, 0, 0, 0, 0, 0, 0, 0, 0, 4, 5, 5, 6, 6, 0, 0,
  128193. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128194. 0, 0, 3, 5, 5, 6, 6, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128195. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 6, 6, 6, 8, 8,
  128196. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128197. 0, 0, 0, 0, 5, 6, 6, 8, 8, 0, 0, 0, 0, 0, 0, 0,
  128198. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128199. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128200. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128201. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128202. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128203. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128204. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128205. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128206. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128207. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128208. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128209. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128210. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128211. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128212. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128213. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128214. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128215. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128216. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128217. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128218. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128219. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128220. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128221. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128222. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128223. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128224. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128225. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128226. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128227. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128228. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128229. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128230. 0,
  128231. };
  128232. static float _vq_quantthresh__44c5_s_p3_0[] = {
  128233. -1.5, -0.5, 0.5, 1.5,
  128234. };
  128235. static long _vq_quantmap__44c5_s_p3_0[] = {
  128236. 3, 1, 0, 2, 4,
  128237. };
  128238. static encode_aux_threshmatch _vq_auxt__44c5_s_p3_0 = {
  128239. _vq_quantthresh__44c5_s_p3_0,
  128240. _vq_quantmap__44c5_s_p3_0,
  128241. 5,
  128242. 5
  128243. };
  128244. static static_codebook _44c5_s_p3_0 = {
  128245. 4, 625,
  128246. _vq_lengthlist__44c5_s_p3_0,
  128247. 1, -533725184, 1611661312, 3, 0,
  128248. _vq_quantlist__44c5_s_p3_0,
  128249. NULL,
  128250. &_vq_auxt__44c5_s_p3_0,
  128251. NULL,
  128252. 0
  128253. };
  128254. static long _vq_quantlist__44c5_s_p4_0[] = {
  128255. 4,
  128256. 3,
  128257. 5,
  128258. 2,
  128259. 6,
  128260. 1,
  128261. 7,
  128262. 0,
  128263. 8,
  128264. };
  128265. static long _vq_lengthlist__44c5_s_p4_0[] = {
  128266. 2, 3, 3, 6, 6, 0, 0, 0, 0, 0, 4, 4, 6, 6, 0, 0,
  128267. 0, 0, 0, 4, 4, 6, 6, 0, 0, 0, 0, 0, 5, 5, 6, 6,
  128268. 0, 0, 0, 0, 0, 0, 0, 6, 6, 0, 0, 0, 0, 0, 0, 0,
  128269. 7, 7, 0, 0, 0, 0, 0, 0, 0, 8, 7, 0, 0, 0, 0, 0,
  128270. 0, 0, 9, 9, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128271. 0,
  128272. };
  128273. static float _vq_quantthresh__44c5_s_p4_0[] = {
  128274. -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5, 3.5,
  128275. };
  128276. static long _vq_quantmap__44c5_s_p4_0[] = {
  128277. 7, 5, 3, 1, 0, 2, 4, 6,
  128278. 8,
  128279. };
  128280. static encode_aux_threshmatch _vq_auxt__44c5_s_p4_0 = {
  128281. _vq_quantthresh__44c5_s_p4_0,
  128282. _vq_quantmap__44c5_s_p4_0,
  128283. 9,
  128284. 9
  128285. };
  128286. static static_codebook _44c5_s_p4_0 = {
  128287. 2, 81,
  128288. _vq_lengthlist__44c5_s_p4_0,
  128289. 1, -531628032, 1611661312, 4, 0,
  128290. _vq_quantlist__44c5_s_p4_0,
  128291. NULL,
  128292. &_vq_auxt__44c5_s_p4_0,
  128293. NULL,
  128294. 0
  128295. };
  128296. static long _vq_quantlist__44c5_s_p5_0[] = {
  128297. 4,
  128298. 3,
  128299. 5,
  128300. 2,
  128301. 6,
  128302. 1,
  128303. 7,
  128304. 0,
  128305. 8,
  128306. };
  128307. static long _vq_lengthlist__44c5_s_p5_0[] = {
  128308. 2, 4, 3, 6, 6, 7, 7, 9, 9, 0, 4, 4, 6, 6, 7, 7,
  128309. 9, 9, 0, 4, 4, 6, 6, 7, 7, 9, 9, 0, 6, 6, 7, 7,
  128310. 7, 7, 9, 9, 0, 0, 0, 7, 6, 7, 7, 9, 9, 0, 0, 0,
  128311. 8, 8, 8, 8,10,10, 0, 0, 0, 8, 8, 8, 8,10,10, 0,
  128312. 0, 0, 9, 9, 9, 9,10,10, 0, 0, 0, 0, 0, 9, 9,10,
  128313. 10,
  128314. };
  128315. static float _vq_quantthresh__44c5_s_p5_0[] = {
  128316. -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5, 3.5,
  128317. };
  128318. static long _vq_quantmap__44c5_s_p5_0[] = {
  128319. 7, 5, 3, 1, 0, 2, 4, 6,
  128320. 8,
  128321. };
  128322. static encode_aux_threshmatch _vq_auxt__44c5_s_p5_0 = {
  128323. _vq_quantthresh__44c5_s_p5_0,
  128324. _vq_quantmap__44c5_s_p5_0,
  128325. 9,
  128326. 9
  128327. };
  128328. static static_codebook _44c5_s_p5_0 = {
  128329. 2, 81,
  128330. _vq_lengthlist__44c5_s_p5_0,
  128331. 1, -531628032, 1611661312, 4, 0,
  128332. _vq_quantlist__44c5_s_p5_0,
  128333. NULL,
  128334. &_vq_auxt__44c5_s_p5_0,
  128335. NULL,
  128336. 0
  128337. };
  128338. static long _vq_quantlist__44c5_s_p6_0[] = {
  128339. 8,
  128340. 7,
  128341. 9,
  128342. 6,
  128343. 10,
  128344. 5,
  128345. 11,
  128346. 4,
  128347. 12,
  128348. 3,
  128349. 13,
  128350. 2,
  128351. 14,
  128352. 1,
  128353. 15,
  128354. 0,
  128355. 16,
  128356. };
  128357. static long _vq_lengthlist__44c5_s_p6_0[] = {
  128358. 2, 4, 4, 6, 6, 8, 8, 9, 9, 9, 9,10,10,10,10,11,
  128359. 11, 0, 4, 4, 6, 6, 8, 8, 9, 9, 9, 9,10,10,11,11,
  128360. 12,12, 0, 4, 4, 6, 6, 8, 8, 9, 9, 9, 9,10,10,11,
  128361. 11,12,12, 0, 6, 6, 7, 7, 8, 8, 9, 9, 9, 9,10,10,
  128362. 11,11,12,12, 0, 0, 0, 7, 7, 8, 8, 9, 9, 9, 9,10,
  128363. 10,11,11,12,12, 0, 0, 0, 7, 7, 9, 9,10,10,10,10,
  128364. 11,11,11,11,12,12, 0, 0, 0, 7, 7, 8, 9,10,10,10,
  128365. 10,11,11,11,11,12,12, 0, 0, 0, 8, 8, 9, 9,10,10,
  128366. 10,10,11,11,12,12,12,12, 0, 0, 0, 0, 0, 9, 9,10,
  128367. 10,10,10,11,11,12,12,12,12, 0, 0, 0, 0, 0, 9, 9,
  128368. 10,10,10,10,11,11,12,12,12,12, 0, 0, 0, 0, 0, 9,
  128369. 9, 9,10,10,10,11,11,12,12,12,12, 0, 0, 0, 0, 0,
  128370. 10,10,10,10,11,11,11,12,12,12,13,13, 0, 0, 0, 0,
  128371. 0, 0, 0,10,10,11,11,11,11,12,12,13,13, 0, 0, 0,
  128372. 0, 0, 0, 0,11,11,11,11,12,12,12,13,13,13, 0, 0,
  128373. 0, 0, 0, 0, 0,11,11,11,11,12,12,12,12,13,13, 0,
  128374. 0, 0, 0, 0, 0, 0,12,12,12,12,13,12,13,13,13,13,
  128375. 0, 0, 0, 0, 0, 0, 0, 0, 0,12,12,12,12,13,13,13,
  128376. 13,
  128377. };
  128378. static float _vq_quantthresh__44c5_s_p6_0[] = {
  128379. -7.5, -6.5, -5.5, -4.5, -3.5, -2.5, -1.5, -0.5,
  128380. 0.5, 1.5, 2.5, 3.5, 4.5, 5.5, 6.5, 7.5,
  128381. };
  128382. static long _vq_quantmap__44c5_s_p6_0[] = {
  128383. 15, 13, 11, 9, 7, 5, 3, 1,
  128384. 0, 2, 4, 6, 8, 10, 12, 14,
  128385. 16,
  128386. };
  128387. static encode_aux_threshmatch _vq_auxt__44c5_s_p6_0 = {
  128388. _vq_quantthresh__44c5_s_p6_0,
  128389. _vq_quantmap__44c5_s_p6_0,
  128390. 17,
  128391. 17
  128392. };
  128393. static static_codebook _44c5_s_p6_0 = {
  128394. 2, 289,
  128395. _vq_lengthlist__44c5_s_p6_0,
  128396. 1, -529530880, 1611661312, 5, 0,
  128397. _vq_quantlist__44c5_s_p6_0,
  128398. NULL,
  128399. &_vq_auxt__44c5_s_p6_0,
  128400. NULL,
  128401. 0
  128402. };
  128403. static long _vq_quantlist__44c5_s_p7_0[] = {
  128404. 1,
  128405. 0,
  128406. 2,
  128407. };
  128408. static long _vq_lengthlist__44c5_s_p7_0[] = {
  128409. 1, 4, 4, 7, 6, 6, 7, 6, 6, 4, 7, 7,10, 9, 9,11,
  128410. 9, 9, 4, 7, 7,10, 9, 9,11, 9, 9, 7,10,10,11,11,
  128411. 10,11,11,11, 6, 9, 9,11,10,10,11,10,10, 6, 9, 9,
  128412. 11,10,10,11,10,10, 7,11,11,12,11,11,12,11,11, 6,
  128413. 9, 9,11,10,10,11,10,10, 6, 9, 9,11,10,10,11,10,
  128414. 10,
  128415. };
  128416. static float _vq_quantthresh__44c5_s_p7_0[] = {
  128417. -5.5, 5.5,
  128418. };
  128419. static long _vq_quantmap__44c5_s_p7_0[] = {
  128420. 1, 0, 2,
  128421. };
  128422. static encode_aux_threshmatch _vq_auxt__44c5_s_p7_0 = {
  128423. _vq_quantthresh__44c5_s_p7_0,
  128424. _vq_quantmap__44c5_s_p7_0,
  128425. 3,
  128426. 3
  128427. };
  128428. static static_codebook _44c5_s_p7_0 = {
  128429. 4, 81,
  128430. _vq_lengthlist__44c5_s_p7_0,
  128431. 1, -529137664, 1618345984, 2, 0,
  128432. _vq_quantlist__44c5_s_p7_0,
  128433. NULL,
  128434. &_vq_auxt__44c5_s_p7_0,
  128435. NULL,
  128436. 0
  128437. };
  128438. static long _vq_quantlist__44c5_s_p7_1[] = {
  128439. 5,
  128440. 4,
  128441. 6,
  128442. 3,
  128443. 7,
  128444. 2,
  128445. 8,
  128446. 1,
  128447. 9,
  128448. 0,
  128449. 10,
  128450. };
  128451. static long _vq_lengthlist__44c5_s_p7_1[] = {
  128452. 2, 4, 4, 6, 6, 7, 7, 8, 8, 8, 8,10, 5, 5, 6, 6,
  128453. 7, 7, 8, 8, 8, 8,10, 5, 5, 6, 6, 7, 7, 8, 8, 8,
  128454. 8,10, 6, 6, 7, 7, 8, 8, 8, 8, 8, 8,10,10,10, 7,
  128455. 7, 8, 8, 8, 8, 8, 8,10,10,10, 7, 7, 8, 8, 8, 8,
  128456. 8, 8,10,10,10, 7, 7, 8, 8, 8, 8, 8, 8,10,10,10,
  128457. 8, 8, 8, 8, 8, 8, 8, 9,10,10,10,10,10, 8, 8, 8,
  128458. 8, 8, 8,10,10,10,10,10, 9, 9, 8, 8, 8, 8,10,10,
  128459. 10,10,10, 8, 8, 8, 8, 8, 8,
  128460. };
  128461. static float _vq_quantthresh__44c5_s_p7_1[] = {
  128462. -4.5, -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5,
  128463. 3.5, 4.5,
  128464. };
  128465. static long _vq_quantmap__44c5_s_p7_1[] = {
  128466. 9, 7, 5, 3, 1, 0, 2, 4,
  128467. 6, 8, 10,
  128468. };
  128469. static encode_aux_threshmatch _vq_auxt__44c5_s_p7_1 = {
  128470. _vq_quantthresh__44c5_s_p7_1,
  128471. _vq_quantmap__44c5_s_p7_1,
  128472. 11,
  128473. 11
  128474. };
  128475. static static_codebook _44c5_s_p7_1 = {
  128476. 2, 121,
  128477. _vq_lengthlist__44c5_s_p7_1,
  128478. 1, -531365888, 1611661312, 4, 0,
  128479. _vq_quantlist__44c5_s_p7_1,
  128480. NULL,
  128481. &_vq_auxt__44c5_s_p7_1,
  128482. NULL,
  128483. 0
  128484. };
  128485. static long _vq_quantlist__44c5_s_p8_0[] = {
  128486. 6,
  128487. 5,
  128488. 7,
  128489. 4,
  128490. 8,
  128491. 3,
  128492. 9,
  128493. 2,
  128494. 10,
  128495. 1,
  128496. 11,
  128497. 0,
  128498. 12,
  128499. };
  128500. static long _vq_lengthlist__44c5_s_p8_0[] = {
  128501. 1, 4, 4, 6, 6, 7, 7, 8, 8, 9, 9,10,10, 6, 5, 5,
  128502. 7, 7, 8, 8, 8, 9,10,10,10,10, 7, 5, 5, 7, 7, 8,
  128503. 8, 9, 9,10,10,10,10, 0, 8, 8, 8, 8, 9, 9, 9, 9,
  128504. 10,10,11,11, 0, 8, 8, 8, 8, 9, 9, 9, 9,10,10,11,
  128505. 11, 0,12,12, 9, 9, 9,10,10,10,10,10,11,11, 0,13,
  128506. 13, 9, 9, 9, 9,10,10,11,11,11,11, 0, 0, 0,10,10,
  128507. 10,10,10,10,11,11,11,11, 0, 0, 0,10,10,10,10,10,
  128508. 10,11,11,12,12, 0, 0, 0,14,14,11,11,11,11,12,12,
  128509. 12,12, 0, 0, 0,14,14,11,11,11,11,12,12,12,12, 0,
  128510. 0, 0, 0, 0,12,12,12,12,12,12,13,13, 0, 0, 0, 0,
  128511. 0,12,12,12,12,12,12,13,13,
  128512. };
  128513. static float _vq_quantthresh__44c5_s_p8_0[] = {
  128514. -27.5, -22.5, -17.5, -12.5, -7.5, -2.5, 2.5, 7.5,
  128515. 12.5, 17.5, 22.5, 27.5,
  128516. };
  128517. static long _vq_quantmap__44c5_s_p8_0[] = {
  128518. 11, 9, 7, 5, 3, 1, 0, 2,
  128519. 4, 6, 8, 10, 12,
  128520. };
  128521. static encode_aux_threshmatch _vq_auxt__44c5_s_p8_0 = {
  128522. _vq_quantthresh__44c5_s_p8_0,
  128523. _vq_quantmap__44c5_s_p8_0,
  128524. 13,
  128525. 13
  128526. };
  128527. static static_codebook _44c5_s_p8_0 = {
  128528. 2, 169,
  128529. _vq_lengthlist__44c5_s_p8_0,
  128530. 1, -526516224, 1616117760, 4, 0,
  128531. _vq_quantlist__44c5_s_p8_0,
  128532. NULL,
  128533. &_vq_auxt__44c5_s_p8_0,
  128534. NULL,
  128535. 0
  128536. };
  128537. static long _vq_quantlist__44c5_s_p8_1[] = {
  128538. 2,
  128539. 1,
  128540. 3,
  128541. 0,
  128542. 4,
  128543. };
  128544. static long _vq_lengthlist__44c5_s_p8_1[] = {
  128545. 2, 4, 4, 5, 5, 6, 5, 5, 5, 5, 6, 4, 5, 5, 5, 6,
  128546. 5, 5, 5, 5, 6, 6, 6, 5, 5,
  128547. };
  128548. static float _vq_quantthresh__44c5_s_p8_1[] = {
  128549. -1.5, -0.5, 0.5, 1.5,
  128550. };
  128551. static long _vq_quantmap__44c5_s_p8_1[] = {
  128552. 3, 1, 0, 2, 4,
  128553. };
  128554. static encode_aux_threshmatch _vq_auxt__44c5_s_p8_1 = {
  128555. _vq_quantthresh__44c5_s_p8_1,
  128556. _vq_quantmap__44c5_s_p8_1,
  128557. 5,
  128558. 5
  128559. };
  128560. static static_codebook _44c5_s_p8_1 = {
  128561. 2, 25,
  128562. _vq_lengthlist__44c5_s_p8_1,
  128563. 1, -533725184, 1611661312, 3, 0,
  128564. _vq_quantlist__44c5_s_p8_1,
  128565. NULL,
  128566. &_vq_auxt__44c5_s_p8_1,
  128567. NULL,
  128568. 0
  128569. };
  128570. static long _vq_quantlist__44c5_s_p9_0[] = {
  128571. 7,
  128572. 6,
  128573. 8,
  128574. 5,
  128575. 9,
  128576. 4,
  128577. 10,
  128578. 3,
  128579. 11,
  128580. 2,
  128581. 12,
  128582. 1,
  128583. 13,
  128584. 0,
  128585. 14,
  128586. };
  128587. static long _vq_lengthlist__44c5_s_p9_0[] = {
  128588. 1, 3, 3,13,13,13,13,13,13,13,13,13,13,13,13, 4,
  128589. 7, 7,13,13,13,13,13,13,13,13,13,13,13,13, 3, 8,
  128590. 6,13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,
  128591. 13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,
  128592. 13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,
  128593. 13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,
  128594. 13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,
  128595. 13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,
  128596. 13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,
  128597. 13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,
  128598. 13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,
  128599. 13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,
  128600. 13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,
  128601. 13,13,13,13,13,13,13,13,13,12,12,12,12,12,12,12,
  128602. 12,
  128603. };
  128604. static float _vq_quantthresh__44c5_s_p9_0[] = {
  128605. -2320.5, -1963.5, -1606.5, -1249.5, -892.5, -535.5, -178.5, 178.5,
  128606. 535.5, 892.5, 1249.5, 1606.5, 1963.5, 2320.5,
  128607. };
  128608. static long _vq_quantmap__44c5_s_p9_0[] = {
  128609. 13, 11, 9, 7, 5, 3, 1, 0,
  128610. 2, 4, 6, 8, 10, 12, 14,
  128611. };
  128612. static encode_aux_threshmatch _vq_auxt__44c5_s_p9_0 = {
  128613. _vq_quantthresh__44c5_s_p9_0,
  128614. _vq_quantmap__44c5_s_p9_0,
  128615. 15,
  128616. 15
  128617. };
  128618. static static_codebook _44c5_s_p9_0 = {
  128619. 2, 225,
  128620. _vq_lengthlist__44c5_s_p9_0,
  128621. 1, -512522752, 1628852224, 4, 0,
  128622. _vq_quantlist__44c5_s_p9_0,
  128623. NULL,
  128624. &_vq_auxt__44c5_s_p9_0,
  128625. NULL,
  128626. 0
  128627. };
  128628. static long _vq_quantlist__44c5_s_p9_1[] = {
  128629. 8,
  128630. 7,
  128631. 9,
  128632. 6,
  128633. 10,
  128634. 5,
  128635. 11,
  128636. 4,
  128637. 12,
  128638. 3,
  128639. 13,
  128640. 2,
  128641. 14,
  128642. 1,
  128643. 15,
  128644. 0,
  128645. 16,
  128646. };
  128647. static long _vq_lengthlist__44c5_s_p9_1[] = {
  128648. 1, 4, 4, 5, 5, 7, 7, 9, 8,10, 9,10,10,11,10,11,
  128649. 11, 6, 5, 5, 7, 7, 8, 9,10,10,11,10,12,11,12,11,
  128650. 13,12, 6, 5, 5, 7, 7, 9, 9,10,10,11,11,12,12,13,
  128651. 12,13,13,18, 8, 8, 8, 8, 9, 9,10,11,11,11,12,11,
  128652. 13,11,13,12,18, 8, 8, 8, 8,10,10,11,11,12,12,13,
  128653. 13,13,13,13,14,18,12,12, 9, 9,11,11,11,11,12,12,
  128654. 13,12,13,12,13,13,20,13,12, 9, 9,11,11,11,11,12,
  128655. 12,13,13,13,14,14,13,20,18,19,11,12,11,11,12,12,
  128656. 13,13,13,13,13,13,14,13,18,19,19,12,11,11,11,12,
  128657. 12,13,12,13,13,13,14,14,13,18,17,19,14,15,12,12,
  128658. 12,13,13,13,14,14,14,14,14,14,19,19,19,16,15,12,
  128659. 11,13,12,14,14,14,13,13,14,14,14,19,18,19,18,19,
  128660. 13,13,13,13,14,14,14,13,14,14,14,14,18,17,19,19,
  128661. 19,13,13,13,11,13,11,13,14,14,14,14,14,19,17,17,
  128662. 18,18,16,16,13,13,13,13,14,13,15,15,14,14,19,19,
  128663. 17,17,18,16,16,13,11,14,10,13,12,14,14,14,14,19,
  128664. 19,19,19,19,18,17,13,14,13,11,14,13,14,14,15,15,
  128665. 19,19,19,17,19,18,18,14,13,12,11,14,11,15,15,15,
  128666. 15,
  128667. };
  128668. static float _vq_quantthresh__44c5_s_p9_1[] = {
  128669. -157.5, -136.5, -115.5, -94.5, -73.5, -52.5, -31.5, -10.5,
  128670. 10.5, 31.5, 52.5, 73.5, 94.5, 115.5, 136.5, 157.5,
  128671. };
  128672. static long _vq_quantmap__44c5_s_p9_1[] = {
  128673. 15, 13, 11, 9, 7, 5, 3, 1,
  128674. 0, 2, 4, 6, 8, 10, 12, 14,
  128675. 16,
  128676. };
  128677. static encode_aux_threshmatch _vq_auxt__44c5_s_p9_1 = {
  128678. _vq_quantthresh__44c5_s_p9_1,
  128679. _vq_quantmap__44c5_s_p9_1,
  128680. 17,
  128681. 17
  128682. };
  128683. static static_codebook _44c5_s_p9_1 = {
  128684. 2, 289,
  128685. _vq_lengthlist__44c5_s_p9_1,
  128686. 1, -520814592, 1620377600, 5, 0,
  128687. _vq_quantlist__44c5_s_p9_1,
  128688. NULL,
  128689. &_vq_auxt__44c5_s_p9_1,
  128690. NULL,
  128691. 0
  128692. };
  128693. static long _vq_quantlist__44c5_s_p9_2[] = {
  128694. 10,
  128695. 9,
  128696. 11,
  128697. 8,
  128698. 12,
  128699. 7,
  128700. 13,
  128701. 6,
  128702. 14,
  128703. 5,
  128704. 15,
  128705. 4,
  128706. 16,
  128707. 3,
  128708. 17,
  128709. 2,
  128710. 18,
  128711. 1,
  128712. 19,
  128713. 0,
  128714. 20,
  128715. };
  128716. static long _vq_lengthlist__44c5_s_p9_2[] = {
  128717. 3, 5, 5, 6, 6, 7, 7, 7, 7, 8, 8, 8, 8, 8, 8, 8,
  128718. 8, 8, 8, 8, 9,11, 5, 6, 7, 7, 8, 7, 8, 8, 8, 8,
  128719. 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,11, 5, 5, 7, 7, 7,
  128720. 7, 8, 8, 8, 8, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,11,
  128721. 7, 7, 7, 7, 8, 8, 8, 8, 9, 9, 9, 9, 9, 9, 9, 9,
  128722. 9,10, 9,10,11,11,11, 7, 7, 8, 8, 8, 8, 9, 9, 9,
  128723. 9, 9, 9,10,10,10,10,10,10,11,11,11, 8, 8, 8, 8,
  128724. 9, 9, 9, 9, 9, 9, 9,10,10,10,10,10,10,10,11,11,
  128725. 11, 8, 8, 8, 8, 9, 9, 9, 9, 9, 9,10,10,10,10,10,
  128726. 10,10,10,11,11,11, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,
  128727. 10,10,10,10,10,10,10,10,11,11,11,11,11, 9, 9, 9,
  128728. 9, 9, 9,10, 9,10,10,10,10,10,10,10,10,11,11,11,
  128729. 11,11, 9, 9, 9, 9, 9, 9,10,10,10,10,10,10,10,10,
  128730. 10,10,11,11,11,11,11, 9, 9, 9, 9, 9, 9,10,10,10,
  128731. 10,10,10,10,10,10,10,11,11,11,11,11, 9, 9,10, 9,
  128732. 10,10,10,10,10,10,10,10,10,10,10,10,11,11,11,11,
  128733. 11,11,11, 9, 9,10,10,10,10,10,10,10,10,10,10,10,
  128734. 10,11,11,11,11,11,11,11,10,10,10,10,10,10,10,10,
  128735. 10,10,10,10,10,10,11,11,11,11,11,11,11,10,10,10,
  128736. 10,10,10,10,10,10,10,10,10,10,10,11,11,11,11,11,
  128737. 11,11,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  128738. 11,11,11,11,11,11,11,11,11,10,10,10,10,10,10,10,
  128739. 10,10,10,10,10,11,11,11,11,11,11,11,11,11,10,10,
  128740. 10,10,10,10,10,10,10,10,10,10,11,11,11,11,11,11,
  128741. 11,11,11,10,10,10,10,10,10,10,10,10,10,10,10,11,
  128742. 11,11,11,11,11,11,11,11,10,10,10,10,10,10,10,10,
  128743. 10,10,10,10,11,11,11,11,11,11,11,11,11,11,11,10,
  128744. 10,10,10,10,10,10,10,10,10,
  128745. };
  128746. static float _vq_quantthresh__44c5_s_p9_2[] = {
  128747. -9.5, -8.5, -7.5, -6.5, -5.5, -4.5, -3.5, -2.5,
  128748. -1.5, -0.5, 0.5, 1.5, 2.5, 3.5, 4.5, 5.5,
  128749. 6.5, 7.5, 8.5, 9.5,
  128750. };
  128751. static long _vq_quantmap__44c5_s_p9_2[] = {
  128752. 19, 17, 15, 13, 11, 9, 7, 5,
  128753. 3, 1, 0, 2, 4, 6, 8, 10,
  128754. 12, 14, 16, 18, 20,
  128755. };
  128756. static encode_aux_threshmatch _vq_auxt__44c5_s_p9_2 = {
  128757. _vq_quantthresh__44c5_s_p9_2,
  128758. _vq_quantmap__44c5_s_p9_2,
  128759. 21,
  128760. 21
  128761. };
  128762. static static_codebook _44c5_s_p9_2 = {
  128763. 2, 441,
  128764. _vq_lengthlist__44c5_s_p9_2,
  128765. 1, -529268736, 1611661312, 5, 0,
  128766. _vq_quantlist__44c5_s_p9_2,
  128767. NULL,
  128768. &_vq_auxt__44c5_s_p9_2,
  128769. NULL,
  128770. 0
  128771. };
  128772. static long _huff_lengthlist__44c5_s_short[] = {
  128773. 5, 8,10,14,11,11,12,16,15,17, 5, 5, 7, 9, 7, 8,
  128774. 10,13,17,17, 7, 5, 5,10, 5, 7, 8,11,13,15,10, 8,
  128775. 10, 8, 8, 8,11,15,18,18, 8, 5, 5, 8, 3, 4, 6,10,
  128776. 14,16, 9, 7, 6, 7, 4, 3, 5, 9,14,18,10, 9, 8,10,
  128777. 6, 5, 6, 9,14,18,12,12,11,12, 8, 7, 8,11,14,18,
  128778. 14,13,12,10, 7, 5, 6, 9,14,18,14,14,13,10, 6, 5,
  128779. 6, 8,11,16,
  128780. };
  128781. static static_codebook _huff_book__44c5_s_short = {
  128782. 2, 100,
  128783. _huff_lengthlist__44c5_s_short,
  128784. 0, 0, 0, 0, 0,
  128785. NULL,
  128786. NULL,
  128787. NULL,
  128788. NULL,
  128789. 0
  128790. };
  128791. static long _huff_lengthlist__44c6_s_long[] = {
  128792. 3, 8,11,13,14,14,13,13,16,14, 6, 3, 4, 7, 9, 9,
  128793. 10,11,14,13,10, 4, 3, 5, 7, 7, 9,10,13,15,12, 7,
  128794. 4, 4, 6, 6, 8,10,13,15,12, 8, 6, 6, 6, 6, 8,10,
  128795. 13,14,11, 9, 7, 6, 6, 6, 7, 8,12,11,13,10, 9, 8,
  128796. 7, 6, 6, 7,11,11,13,11,10, 9, 9, 7, 7, 6,10,11,
  128797. 13,13,13,13,13,11, 9, 8,10,12,12,15,15,16,15,12,
  128798. 11,10,10,12,
  128799. };
  128800. static static_codebook _huff_book__44c6_s_long = {
  128801. 2, 100,
  128802. _huff_lengthlist__44c6_s_long,
  128803. 0, 0, 0, 0, 0,
  128804. NULL,
  128805. NULL,
  128806. NULL,
  128807. NULL,
  128808. 0
  128809. };
  128810. static long _vq_quantlist__44c6_s_p1_0[] = {
  128811. 1,
  128812. 0,
  128813. 2,
  128814. };
  128815. static long _vq_lengthlist__44c6_s_p1_0[] = {
  128816. 1, 5, 5, 0, 5, 5, 0, 5, 5, 5, 8, 7, 0, 9, 9, 0,
  128817. 9, 8, 5, 7, 8, 0, 9, 9, 0, 8, 9, 0, 0, 0, 0, 0,
  128818. 0, 0, 0, 0, 5, 9, 8, 0, 8, 8, 0, 8, 8, 5, 8, 9,
  128819. 0, 8, 8, 0, 8, 8, 0, 0, 0, 0, 0, 0, 0, 0, 0, 5,
  128820. 9, 9, 0, 8, 8, 0, 8, 8, 5, 9, 9, 0, 8, 8, 0, 8,
  128821. 8,
  128822. };
  128823. static float _vq_quantthresh__44c6_s_p1_0[] = {
  128824. -0.5, 0.5,
  128825. };
  128826. static long _vq_quantmap__44c6_s_p1_0[] = {
  128827. 1, 0, 2,
  128828. };
  128829. static encode_aux_threshmatch _vq_auxt__44c6_s_p1_0 = {
  128830. _vq_quantthresh__44c6_s_p1_0,
  128831. _vq_quantmap__44c6_s_p1_0,
  128832. 3,
  128833. 3
  128834. };
  128835. static static_codebook _44c6_s_p1_0 = {
  128836. 4, 81,
  128837. _vq_lengthlist__44c6_s_p1_0,
  128838. 1, -535822336, 1611661312, 2, 0,
  128839. _vq_quantlist__44c6_s_p1_0,
  128840. NULL,
  128841. &_vq_auxt__44c6_s_p1_0,
  128842. NULL,
  128843. 0
  128844. };
  128845. static long _vq_quantlist__44c6_s_p2_0[] = {
  128846. 2,
  128847. 1,
  128848. 3,
  128849. 0,
  128850. 4,
  128851. };
  128852. static long _vq_lengthlist__44c6_s_p2_0[] = {
  128853. 3, 5, 5, 8, 8, 0, 5, 5, 8, 8, 0, 5, 5, 8, 8, 0,
  128854. 7, 7, 9, 9, 0, 0, 0, 9, 9, 5, 7, 7, 9, 9, 0, 8,
  128855. 8,10,10, 0, 8, 7,10, 9, 0,10,10,11,11, 0, 0, 0,
  128856. 11,11, 5, 7, 7, 9, 9, 0, 8, 8,10,10, 0, 7, 8, 9,
  128857. 10, 0,10,10,11,11, 0, 0, 0,11,11, 8, 9, 9,11,11,
  128858. 0,11,11,12,12, 0,11,10,12,12, 0,13,14,14,14, 0,
  128859. 0, 0,14,13, 8, 9, 9,11,11, 0,11,11,12,12, 0,10,
  128860. 11,12,12, 0,14,13,14,14, 0, 0, 0,13,14, 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, 5, 8, 7,11,10, 0, 7, 7,10,10,
  128863. 0, 7, 7,10,10, 0, 9, 9,11,10, 0, 0, 0,11,11, 5,
  128864. 7, 8,10,11, 0, 7, 7,10,10, 0, 7, 7,10,10, 0, 9,
  128865. 9,10,11, 0, 0, 0,11,11, 8,10, 9,12,12, 0,10,10,
  128866. 12,12, 0,10,10,12,12, 0,12,12,13,13, 0, 0, 0,13,
  128867. 13, 8, 9,10,12,12, 0,10,10,11,12, 0,10,10,12,12,
  128868. 0,12,12,13,13, 0, 0, 0,13,13, 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, 5, 8, 8,11,11, 0, 7, 7,10,10, 0, 7, 7,
  128871. 10,10, 0, 9, 9,10,11, 0, 0, 0,11,10, 5, 8, 8,11,
  128872. 11, 0, 7, 7,10,10, 0, 7, 7,10,10, 0, 9, 9,11,11,
  128873. 0, 0, 0,10,11, 8,10,10,12,12, 0,10,10,12,12, 0,
  128874. 10,10,12,12, 0,12,13,13,13, 0, 0, 0,14,13, 8,10,
  128875. 10,12,12, 0,10,10,12,12, 0,10,10,12,12, 0,13,12,
  128876. 13,13, 0, 0, 0,13,13, 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. 7,10,10,14,13, 0, 9, 9,13,12, 0, 9, 9,12,12, 0,
  128879. 10,10,12,12, 0, 0, 0,12,12, 7,10,10,13,14, 0, 9,
  128880. 9,12,13, 0, 9, 9,12,12, 0,10,10,12,12, 0, 0, 0,
  128881. 12,12, 9,11,11,14,13, 0,11,10,14,13, 0,11,11,13,
  128882. 13, 0,12,12,13,13, 0, 0, 0,13,13, 9,11,11,13,14,
  128883. 0,10,11,13,14, 0,11,11,13,13, 0,12,12,13,13, 0,
  128884. 0, 0,13,13, 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, 9,
  128889. 11,11,14,14, 0,11,11,13,13, 0,11,10,13,13, 0,12,
  128890. 12,13,13, 0, 0, 0,13,13, 9,11,11,14,14, 0,11,11,
  128891. 13,13, 0,10,11,13,13, 0,12,12,14,13, 0, 0, 0,13,
  128892. 13,
  128893. };
  128894. static float _vq_quantthresh__44c6_s_p2_0[] = {
  128895. -1.5, -0.5, 0.5, 1.5,
  128896. };
  128897. static long _vq_quantmap__44c6_s_p2_0[] = {
  128898. 3, 1, 0, 2, 4,
  128899. };
  128900. static encode_aux_threshmatch _vq_auxt__44c6_s_p2_0 = {
  128901. _vq_quantthresh__44c6_s_p2_0,
  128902. _vq_quantmap__44c6_s_p2_0,
  128903. 5,
  128904. 5
  128905. };
  128906. static static_codebook _44c6_s_p2_0 = {
  128907. 4, 625,
  128908. _vq_lengthlist__44c6_s_p2_0,
  128909. 1, -533725184, 1611661312, 3, 0,
  128910. _vq_quantlist__44c6_s_p2_0,
  128911. NULL,
  128912. &_vq_auxt__44c6_s_p2_0,
  128913. NULL,
  128914. 0
  128915. };
  128916. static long _vq_quantlist__44c6_s_p3_0[] = {
  128917. 4,
  128918. 3,
  128919. 5,
  128920. 2,
  128921. 6,
  128922. 1,
  128923. 7,
  128924. 0,
  128925. 8,
  128926. };
  128927. static long _vq_lengthlist__44c6_s_p3_0[] = {
  128928. 2, 3, 4, 6, 6, 7, 7, 9, 9, 0, 4, 4, 6, 6, 7, 7,
  128929. 9,10, 0, 4, 4, 6, 6, 7, 7,10, 9, 0, 5, 5, 7, 7,
  128930. 8, 8,10,10, 0, 0, 0, 7, 6, 8, 8,10,10, 0, 0, 0,
  128931. 7, 7, 9, 9,11,11, 0, 0, 0, 7, 7, 9, 9,11,11, 0,
  128932. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128933. 0,
  128934. };
  128935. static float _vq_quantthresh__44c6_s_p3_0[] = {
  128936. -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5, 3.5,
  128937. };
  128938. static long _vq_quantmap__44c6_s_p3_0[] = {
  128939. 7, 5, 3, 1, 0, 2, 4, 6,
  128940. 8,
  128941. };
  128942. static encode_aux_threshmatch _vq_auxt__44c6_s_p3_0 = {
  128943. _vq_quantthresh__44c6_s_p3_0,
  128944. _vq_quantmap__44c6_s_p3_0,
  128945. 9,
  128946. 9
  128947. };
  128948. static static_codebook _44c6_s_p3_0 = {
  128949. 2, 81,
  128950. _vq_lengthlist__44c6_s_p3_0,
  128951. 1, -531628032, 1611661312, 4, 0,
  128952. _vq_quantlist__44c6_s_p3_0,
  128953. NULL,
  128954. &_vq_auxt__44c6_s_p3_0,
  128955. NULL,
  128956. 0
  128957. };
  128958. static long _vq_quantlist__44c6_s_p4_0[] = {
  128959. 8,
  128960. 7,
  128961. 9,
  128962. 6,
  128963. 10,
  128964. 5,
  128965. 11,
  128966. 4,
  128967. 12,
  128968. 3,
  128969. 13,
  128970. 2,
  128971. 14,
  128972. 1,
  128973. 15,
  128974. 0,
  128975. 16,
  128976. };
  128977. static long _vq_lengthlist__44c6_s_p4_0[] = {
  128978. 2, 4, 4, 6, 6, 7, 7, 8, 8, 8, 8, 9, 9, 9,10,10,
  128979. 10, 0, 4, 4, 6, 6, 8, 8, 9, 9, 9, 9,10,10,10,10,
  128980. 11,11, 0, 4, 4, 6, 6, 8, 8, 9, 9, 9, 9,10,10,10,
  128981. 10,11,11, 0, 6, 6, 7, 7, 8, 8, 9, 9, 9, 9,10,10,
  128982. 11,11,11,11, 0, 0, 0, 7, 7, 8, 8, 9, 9, 9, 9,10,
  128983. 10,11,11,11,11, 0, 0, 0, 7, 7, 9, 9,10,10,10,10,
  128984. 11,11,11,11,12,12, 0, 0, 0, 7, 7, 9, 9,10,10,10,
  128985. 10,11,11,11,11,12,12, 0, 0, 0, 7, 7, 8, 8, 9, 9,
  128986. 10,10,11,11,12,12,12,12, 0, 0, 0, 0, 0, 8, 8, 9,
  128987. 9,10,10,11,11,12,12,12,12, 0, 0, 0, 0, 0, 0, 0,
  128988. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128989. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128990. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128991. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128992. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128993. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128994. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128995. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128996. 0,
  128997. };
  128998. static float _vq_quantthresh__44c6_s_p4_0[] = {
  128999. -7.5, -6.5, -5.5, -4.5, -3.5, -2.5, -1.5, -0.5,
  129000. 0.5, 1.5, 2.5, 3.5, 4.5, 5.5, 6.5, 7.5,
  129001. };
  129002. static long _vq_quantmap__44c6_s_p4_0[] = {
  129003. 15, 13, 11, 9, 7, 5, 3, 1,
  129004. 0, 2, 4, 6, 8, 10, 12, 14,
  129005. 16,
  129006. };
  129007. static encode_aux_threshmatch _vq_auxt__44c6_s_p4_0 = {
  129008. _vq_quantthresh__44c6_s_p4_0,
  129009. _vq_quantmap__44c6_s_p4_0,
  129010. 17,
  129011. 17
  129012. };
  129013. static static_codebook _44c6_s_p4_0 = {
  129014. 2, 289,
  129015. _vq_lengthlist__44c6_s_p4_0,
  129016. 1, -529530880, 1611661312, 5, 0,
  129017. _vq_quantlist__44c6_s_p4_0,
  129018. NULL,
  129019. &_vq_auxt__44c6_s_p4_0,
  129020. NULL,
  129021. 0
  129022. };
  129023. static long _vq_quantlist__44c6_s_p5_0[] = {
  129024. 1,
  129025. 0,
  129026. 2,
  129027. };
  129028. static long _vq_lengthlist__44c6_s_p5_0[] = {
  129029. 1, 4, 4, 5, 7, 7, 6, 7, 7, 4, 6, 6, 9, 9,10,10,
  129030. 10, 9, 4, 6, 6, 9,10, 9,10, 9,10, 6, 9, 9,10,12,
  129031. 11,10,11,11, 7,10, 9,11,12,12,12,12,12, 7,10,10,
  129032. 11,12,12,12,12,12, 6,10,10,10,12,12,11,12,12, 7,
  129033. 9,10,11,12,12,12,12,12, 7,10, 9,12,12,12,12,12,
  129034. 12,
  129035. };
  129036. static float _vq_quantthresh__44c6_s_p5_0[] = {
  129037. -5.5, 5.5,
  129038. };
  129039. static long _vq_quantmap__44c6_s_p5_0[] = {
  129040. 1, 0, 2,
  129041. };
  129042. static encode_aux_threshmatch _vq_auxt__44c6_s_p5_0 = {
  129043. _vq_quantthresh__44c6_s_p5_0,
  129044. _vq_quantmap__44c6_s_p5_0,
  129045. 3,
  129046. 3
  129047. };
  129048. static static_codebook _44c6_s_p5_0 = {
  129049. 4, 81,
  129050. _vq_lengthlist__44c6_s_p5_0,
  129051. 1, -529137664, 1618345984, 2, 0,
  129052. _vq_quantlist__44c6_s_p5_0,
  129053. NULL,
  129054. &_vq_auxt__44c6_s_p5_0,
  129055. NULL,
  129056. 0
  129057. };
  129058. static long _vq_quantlist__44c6_s_p5_1[] = {
  129059. 5,
  129060. 4,
  129061. 6,
  129062. 3,
  129063. 7,
  129064. 2,
  129065. 8,
  129066. 1,
  129067. 9,
  129068. 0,
  129069. 10,
  129070. };
  129071. static long _vq_lengthlist__44c6_s_p5_1[] = {
  129072. 3, 5, 4, 6, 6, 7, 7, 8, 8, 8, 8,11, 4, 4, 6, 6,
  129073. 7, 7, 8, 8, 8, 8,11, 4, 4, 6, 6, 7, 7, 8, 8, 8,
  129074. 8,11, 6, 6, 6, 6, 8, 8, 8, 8, 9, 9,11,11,11, 6,
  129075. 6, 7, 8, 8, 8, 8, 9,11,11,11, 7, 7, 8, 8, 8, 8,
  129076. 8, 8,11,11,11, 7, 7, 8, 8, 8, 8, 8, 8,11,11,11,
  129077. 8, 8, 8, 8, 8, 8, 8, 8,11,11,11,10,10, 8, 8, 8,
  129078. 8, 8, 8,11,11,11,10,10, 8, 8, 8, 8, 8, 8,11,11,
  129079. 11,10,10, 7, 7, 8, 8, 8, 8,
  129080. };
  129081. static float _vq_quantthresh__44c6_s_p5_1[] = {
  129082. -4.5, -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5,
  129083. 3.5, 4.5,
  129084. };
  129085. static long _vq_quantmap__44c6_s_p5_1[] = {
  129086. 9, 7, 5, 3, 1, 0, 2, 4,
  129087. 6, 8, 10,
  129088. };
  129089. static encode_aux_threshmatch _vq_auxt__44c6_s_p5_1 = {
  129090. _vq_quantthresh__44c6_s_p5_1,
  129091. _vq_quantmap__44c6_s_p5_1,
  129092. 11,
  129093. 11
  129094. };
  129095. static static_codebook _44c6_s_p5_1 = {
  129096. 2, 121,
  129097. _vq_lengthlist__44c6_s_p5_1,
  129098. 1, -531365888, 1611661312, 4, 0,
  129099. _vq_quantlist__44c6_s_p5_1,
  129100. NULL,
  129101. &_vq_auxt__44c6_s_p5_1,
  129102. NULL,
  129103. 0
  129104. };
  129105. static long _vq_quantlist__44c6_s_p6_0[] = {
  129106. 6,
  129107. 5,
  129108. 7,
  129109. 4,
  129110. 8,
  129111. 3,
  129112. 9,
  129113. 2,
  129114. 10,
  129115. 1,
  129116. 11,
  129117. 0,
  129118. 12,
  129119. };
  129120. static long _vq_lengthlist__44c6_s_p6_0[] = {
  129121. 1, 4, 4, 6, 6, 8, 8, 8, 8,10, 9,10,10, 6, 5, 5,
  129122. 7, 7, 9, 9, 9, 9,10,10,11,11, 6, 5, 5, 7, 7, 9,
  129123. 9,10, 9,11,10,11,11, 0, 6, 6, 7, 7, 9, 9,10,10,
  129124. 11,11,12,12, 0, 7, 7, 7, 7, 9, 9,10,10,11,11,12,
  129125. 12, 0,11,11, 8, 8,10,10,11,11,12,12,12,12, 0,11,
  129126. 12, 9, 8,10,10,11,11,12,12,13,13, 0, 0, 0, 0, 0,
  129127. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129128. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129129. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129130. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129131. 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129132. };
  129133. static float _vq_quantthresh__44c6_s_p6_0[] = {
  129134. -27.5, -22.5, -17.5, -12.5, -7.5, -2.5, 2.5, 7.5,
  129135. 12.5, 17.5, 22.5, 27.5,
  129136. };
  129137. static long _vq_quantmap__44c6_s_p6_0[] = {
  129138. 11, 9, 7, 5, 3, 1, 0, 2,
  129139. 4, 6, 8, 10, 12,
  129140. };
  129141. static encode_aux_threshmatch _vq_auxt__44c6_s_p6_0 = {
  129142. _vq_quantthresh__44c6_s_p6_0,
  129143. _vq_quantmap__44c6_s_p6_0,
  129144. 13,
  129145. 13
  129146. };
  129147. static static_codebook _44c6_s_p6_0 = {
  129148. 2, 169,
  129149. _vq_lengthlist__44c6_s_p6_0,
  129150. 1, -526516224, 1616117760, 4, 0,
  129151. _vq_quantlist__44c6_s_p6_0,
  129152. NULL,
  129153. &_vq_auxt__44c6_s_p6_0,
  129154. NULL,
  129155. 0
  129156. };
  129157. static long _vq_quantlist__44c6_s_p6_1[] = {
  129158. 2,
  129159. 1,
  129160. 3,
  129161. 0,
  129162. 4,
  129163. };
  129164. static long _vq_lengthlist__44c6_s_p6_1[] = {
  129165. 3, 4, 4, 5, 5, 5, 4, 4, 5, 5, 5, 4, 4, 5, 5, 6,
  129166. 5, 5, 5, 5, 6, 6, 6, 5, 5,
  129167. };
  129168. static float _vq_quantthresh__44c6_s_p6_1[] = {
  129169. -1.5, -0.5, 0.5, 1.5,
  129170. };
  129171. static long _vq_quantmap__44c6_s_p6_1[] = {
  129172. 3, 1, 0, 2, 4,
  129173. };
  129174. static encode_aux_threshmatch _vq_auxt__44c6_s_p6_1 = {
  129175. _vq_quantthresh__44c6_s_p6_1,
  129176. _vq_quantmap__44c6_s_p6_1,
  129177. 5,
  129178. 5
  129179. };
  129180. static static_codebook _44c6_s_p6_1 = {
  129181. 2, 25,
  129182. _vq_lengthlist__44c6_s_p6_1,
  129183. 1, -533725184, 1611661312, 3, 0,
  129184. _vq_quantlist__44c6_s_p6_1,
  129185. NULL,
  129186. &_vq_auxt__44c6_s_p6_1,
  129187. NULL,
  129188. 0
  129189. };
  129190. static long _vq_quantlist__44c6_s_p7_0[] = {
  129191. 6,
  129192. 5,
  129193. 7,
  129194. 4,
  129195. 8,
  129196. 3,
  129197. 9,
  129198. 2,
  129199. 10,
  129200. 1,
  129201. 11,
  129202. 0,
  129203. 12,
  129204. };
  129205. static long _vq_lengthlist__44c6_s_p7_0[] = {
  129206. 1, 4, 4, 6, 6, 8, 8, 8, 8,10,10,11,10, 6, 5, 5,
  129207. 7, 7, 8, 8, 9, 9,10,10,12,11, 6, 5, 5, 7, 7, 8,
  129208. 8, 9, 9,10,10,12,11,21, 7, 7, 7, 7, 9, 9,10,10,
  129209. 11,11,12,12,21, 7, 7, 7, 7, 9, 9,10,10,11,11,12,
  129210. 12,21,12,12, 9, 9,10,10,11,11,11,11,12,12,21,12,
  129211. 12, 9, 9,10,10,11,11,12,12,12,12,21,21,21,11,11,
  129212. 10,10,11,12,12,12,13,13,21,21,21,11,11,10,10,12,
  129213. 12,12,12,13,13,21,21,21,15,15,11,11,12,12,13,13,
  129214. 13,13,21,21,21,15,16,11,11,12,12,13,13,14,14,21,
  129215. 21,21,21,20,13,13,13,13,13,13,14,14,20,20,20,20,
  129216. 20,13,13,13,13,13,13,14,14,
  129217. };
  129218. static float _vq_quantthresh__44c6_s_p7_0[] = {
  129219. -60.5, -49.5, -38.5, -27.5, -16.5, -5.5, 5.5, 16.5,
  129220. 27.5, 38.5, 49.5, 60.5,
  129221. };
  129222. static long _vq_quantmap__44c6_s_p7_0[] = {
  129223. 11, 9, 7, 5, 3, 1, 0, 2,
  129224. 4, 6, 8, 10, 12,
  129225. };
  129226. static encode_aux_threshmatch _vq_auxt__44c6_s_p7_0 = {
  129227. _vq_quantthresh__44c6_s_p7_0,
  129228. _vq_quantmap__44c6_s_p7_0,
  129229. 13,
  129230. 13
  129231. };
  129232. static static_codebook _44c6_s_p7_0 = {
  129233. 2, 169,
  129234. _vq_lengthlist__44c6_s_p7_0,
  129235. 1, -523206656, 1618345984, 4, 0,
  129236. _vq_quantlist__44c6_s_p7_0,
  129237. NULL,
  129238. &_vq_auxt__44c6_s_p7_0,
  129239. NULL,
  129240. 0
  129241. };
  129242. static long _vq_quantlist__44c6_s_p7_1[] = {
  129243. 5,
  129244. 4,
  129245. 6,
  129246. 3,
  129247. 7,
  129248. 2,
  129249. 8,
  129250. 1,
  129251. 9,
  129252. 0,
  129253. 10,
  129254. };
  129255. static long _vq_lengthlist__44c6_s_p7_1[] = {
  129256. 3, 5, 5, 6, 6, 7, 7, 7, 7, 7, 7, 9, 5, 5, 6, 6,
  129257. 7, 7, 7, 7, 8, 7, 8, 5, 5, 6, 6, 7, 7, 7, 7, 7,
  129258. 7, 9, 6, 6, 7, 7, 7, 7, 8, 7, 7, 8, 9, 9, 9, 7,
  129259. 7, 7, 7, 7, 7, 7, 8, 9, 9, 9, 7, 7, 7, 7, 8, 8,
  129260. 8, 8, 9, 9, 9, 7, 7, 7, 7, 7, 7, 8, 8, 9, 9, 9,
  129261. 8, 8, 8, 8, 7, 7, 8, 8, 9, 9, 9, 9, 8, 8, 8, 7,
  129262. 7, 8, 8, 9, 9, 9, 8, 8, 8, 8, 7, 7, 8, 8, 9, 9,
  129263. 9, 8, 8, 7, 7, 7, 7, 8, 8,
  129264. };
  129265. static float _vq_quantthresh__44c6_s_p7_1[] = {
  129266. -4.5, -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5,
  129267. 3.5, 4.5,
  129268. };
  129269. static long _vq_quantmap__44c6_s_p7_1[] = {
  129270. 9, 7, 5, 3, 1, 0, 2, 4,
  129271. 6, 8, 10,
  129272. };
  129273. static encode_aux_threshmatch _vq_auxt__44c6_s_p7_1 = {
  129274. _vq_quantthresh__44c6_s_p7_1,
  129275. _vq_quantmap__44c6_s_p7_1,
  129276. 11,
  129277. 11
  129278. };
  129279. static static_codebook _44c6_s_p7_1 = {
  129280. 2, 121,
  129281. _vq_lengthlist__44c6_s_p7_1,
  129282. 1, -531365888, 1611661312, 4, 0,
  129283. _vq_quantlist__44c6_s_p7_1,
  129284. NULL,
  129285. &_vq_auxt__44c6_s_p7_1,
  129286. NULL,
  129287. 0
  129288. };
  129289. static long _vq_quantlist__44c6_s_p8_0[] = {
  129290. 7,
  129291. 6,
  129292. 8,
  129293. 5,
  129294. 9,
  129295. 4,
  129296. 10,
  129297. 3,
  129298. 11,
  129299. 2,
  129300. 12,
  129301. 1,
  129302. 13,
  129303. 0,
  129304. 14,
  129305. };
  129306. static long _vq_lengthlist__44c6_s_p8_0[] = {
  129307. 1, 4, 4, 7, 7, 8, 8, 7, 7, 8, 7, 9, 8,10, 9, 6,
  129308. 5, 5, 8, 8, 9, 9, 8, 8, 9, 9,11,10,11,10, 6, 5,
  129309. 5, 8, 8, 9, 9, 8, 8, 9, 9,10,10,11,11,18, 8, 8,
  129310. 9, 8,10,10, 9, 9,10,10,10,10,11,10,18, 8, 8, 9,
  129311. 9,10,10, 9, 9,10,10,11,11,12,12,18,12,13, 9,10,
  129312. 10,10, 9,10,10,10,11,11,12,11,18,13,13, 9, 9,10,
  129313. 10,10,10,10,10,11,11,12,12,18,18,18,10,10, 9, 9,
  129314. 11,11,11,11,11,12,12,12,18,18,18,10, 9,10, 9,11,
  129315. 10,11,11,11,11,13,12,18,18,18,14,13,10,10,11,11,
  129316. 12,12,12,12,12,12,18,18,18,14,13,10,10,11,10,12,
  129317. 12,12,12,12,12,18,18,18,18,18,12,12,11,11,12,12,
  129318. 13,13,13,14,18,18,18,18,18,12,12,11,11,12,11,13,
  129319. 13,14,13,18,18,18,18,18,16,16,11,12,12,13,13,13,
  129320. 14,13,18,18,18,18,18,16,15,12,11,12,11,13,11,15,
  129321. 14,
  129322. };
  129323. static float _vq_quantthresh__44c6_s_p8_0[] = {
  129324. -136.5, -115.5, -94.5, -73.5, -52.5, -31.5, -10.5, 10.5,
  129325. 31.5, 52.5, 73.5, 94.5, 115.5, 136.5,
  129326. };
  129327. static long _vq_quantmap__44c6_s_p8_0[] = {
  129328. 13, 11, 9, 7, 5, 3, 1, 0,
  129329. 2, 4, 6, 8, 10, 12, 14,
  129330. };
  129331. static encode_aux_threshmatch _vq_auxt__44c6_s_p8_0 = {
  129332. _vq_quantthresh__44c6_s_p8_0,
  129333. _vq_quantmap__44c6_s_p8_0,
  129334. 15,
  129335. 15
  129336. };
  129337. static static_codebook _44c6_s_p8_0 = {
  129338. 2, 225,
  129339. _vq_lengthlist__44c6_s_p8_0,
  129340. 1, -520986624, 1620377600, 4, 0,
  129341. _vq_quantlist__44c6_s_p8_0,
  129342. NULL,
  129343. &_vq_auxt__44c6_s_p8_0,
  129344. NULL,
  129345. 0
  129346. };
  129347. static long _vq_quantlist__44c6_s_p8_1[] = {
  129348. 10,
  129349. 9,
  129350. 11,
  129351. 8,
  129352. 12,
  129353. 7,
  129354. 13,
  129355. 6,
  129356. 14,
  129357. 5,
  129358. 15,
  129359. 4,
  129360. 16,
  129361. 3,
  129362. 17,
  129363. 2,
  129364. 18,
  129365. 1,
  129366. 19,
  129367. 0,
  129368. 20,
  129369. };
  129370. static long _vq_lengthlist__44c6_s_p8_1[] = {
  129371. 3, 5, 5, 6, 6, 7, 7, 7, 7, 8, 7, 8, 8, 8, 8, 8,
  129372. 8, 8, 8, 8, 8,10, 6, 6, 7, 7, 8, 8, 8, 8, 8, 8,
  129373. 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,10, 6, 6, 7, 7, 8,
  129374. 8, 8, 8, 8, 8, 9, 8, 9, 9, 9, 9, 9, 9, 9, 9,10,
  129375. 7, 7, 8, 8, 8, 8, 8, 9, 9, 9, 9, 9, 9, 9, 9, 9,
  129376. 9, 9, 9, 9,10,11,11, 8, 7, 8, 8, 8, 9, 9, 9, 9,
  129377. 9, 9, 9, 9, 9, 9, 9, 9, 9,11,11,11, 8, 8, 8, 8,
  129378. 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,11,11,
  129379. 11, 8, 8, 8, 8, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,
  129380. 9, 9, 9,11,11,11, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,
  129381. 9, 9, 9, 9, 9, 9, 9, 9,11,11,11,11,11, 9, 9, 9,
  129382. 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,10,10, 9,11,11,11,
  129383. 11,11, 9, 9, 9, 9, 9, 9,10, 9, 9,10, 9,10, 9, 9,
  129384. 10, 9,11,11,11,11,11, 9, 9, 9, 9, 9, 9, 9,10,10,
  129385. 10,10, 9,10,10, 9,10,11,11,11,11,11, 9, 9, 9, 9,
  129386. 10,10,10, 9,10,10,10,10, 9,10,10, 9,11,11,11,11,
  129387. 11,11,11, 9, 9, 9, 9,10,10,10,10, 9,10,10,10,10,
  129388. 10,11,11,11,11,11,11,11,10, 9,10,10,10,10,10,10,
  129389. 10, 9,10, 9,10,10,11,11,11,11,11,11,11,10, 9,10,
  129390. 9,10,10, 9,10,10,10,10,10,10,10,11,11,11,11,11,
  129391. 11,11,10,10,10,10,10,10,10, 9,10,10,10,10,10, 9,
  129392. 11,11,11,11,11,11,11,11,11,10,10,10,10,10,10,10,
  129393. 10,10,10,10,10,11,11,11,11,11,11,11,11,11,10,10,
  129394. 10,10,10,10,10,10,10,10,10,10,11,11,11,11,11,11,
  129395. 11,11,11,10,10,10,10,10,10,10,10,10, 9,10,10,11,
  129396. 11,11,11,11,11,11,11,11,10,10,10, 9,10,10,10,10,
  129397. 10,10,10,10,10,11,11,11,11,11,11,11,11,10,11, 9,
  129398. 10,10,10,10,10,10,10,10,10,
  129399. };
  129400. static float _vq_quantthresh__44c6_s_p8_1[] = {
  129401. -9.5, -8.5, -7.5, -6.5, -5.5, -4.5, -3.5, -2.5,
  129402. -1.5, -0.5, 0.5, 1.5, 2.5, 3.5, 4.5, 5.5,
  129403. 6.5, 7.5, 8.5, 9.5,
  129404. };
  129405. static long _vq_quantmap__44c6_s_p8_1[] = {
  129406. 19, 17, 15, 13, 11, 9, 7, 5,
  129407. 3, 1, 0, 2, 4, 6, 8, 10,
  129408. 12, 14, 16, 18, 20,
  129409. };
  129410. static encode_aux_threshmatch _vq_auxt__44c6_s_p8_1 = {
  129411. _vq_quantthresh__44c6_s_p8_1,
  129412. _vq_quantmap__44c6_s_p8_1,
  129413. 21,
  129414. 21
  129415. };
  129416. static static_codebook _44c6_s_p8_1 = {
  129417. 2, 441,
  129418. _vq_lengthlist__44c6_s_p8_1,
  129419. 1, -529268736, 1611661312, 5, 0,
  129420. _vq_quantlist__44c6_s_p8_1,
  129421. NULL,
  129422. &_vq_auxt__44c6_s_p8_1,
  129423. NULL,
  129424. 0
  129425. };
  129426. static long _vq_quantlist__44c6_s_p9_0[] = {
  129427. 6,
  129428. 5,
  129429. 7,
  129430. 4,
  129431. 8,
  129432. 3,
  129433. 9,
  129434. 2,
  129435. 10,
  129436. 1,
  129437. 11,
  129438. 0,
  129439. 12,
  129440. };
  129441. static long _vq_lengthlist__44c6_s_p9_0[] = {
  129442. 1, 3, 3,11,11,11,11,11,11,11,11,11,11, 4, 7, 7,
  129443. 11,11,11,11,11,11,11,11,11,11, 5, 8, 9,11,11,11,
  129444. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  129445. 11,11,11,11,11,10,10,10,10,10,10,10,10,10,10,10,
  129446. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  129447. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  129448. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  129449. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  129450. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  129451. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  129452. 10,10,10,10,10,10,10,10,10,
  129453. };
  129454. static float _vq_quantthresh__44c6_s_p9_0[] = {
  129455. -3503.5, -2866.5, -2229.5, -1592.5, -955.5, -318.5, 318.5, 955.5,
  129456. 1592.5, 2229.5, 2866.5, 3503.5,
  129457. };
  129458. static long _vq_quantmap__44c6_s_p9_0[] = {
  129459. 11, 9, 7, 5, 3, 1, 0, 2,
  129460. 4, 6, 8, 10, 12,
  129461. };
  129462. static encode_aux_threshmatch _vq_auxt__44c6_s_p9_0 = {
  129463. _vq_quantthresh__44c6_s_p9_0,
  129464. _vq_quantmap__44c6_s_p9_0,
  129465. 13,
  129466. 13
  129467. };
  129468. static static_codebook _44c6_s_p9_0 = {
  129469. 2, 169,
  129470. _vq_lengthlist__44c6_s_p9_0,
  129471. 1, -511845376, 1630791680, 4, 0,
  129472. _vq_quantlist__44c6_s_p9_0,
  129473. NULL,
  129474. &_vq_auxt__44c6_s_p9_0,
  129475. NULL,
  129476. 0
  129477. };
  129478. static long _vq_quantlist__44c6_s_p9_1[] = {
  129479. 6,
  129480. 5,
  129481. 7,
  129482. 4,
  129483. 8,
  129484. 3,
  129485. 9,
  129486. 2,
  129487. 10,
  129488. 1,
  129489. 11,
  129490. 0,
  129491. 12,
  129492. };
  129493. static long _vq_lengthlist__44c6_s_p9_1[] = {
  129494. 1, 4, 4, 7, 7, 7, 7, 7, 6, 8, 8, 8, 8, 6, 6, 6,
  129495. 8, 8, 8, 8, 8, 7, 9, 8,10,10, 5, 6, 6, 8, 8, 9,
  129496. 9, 8, 8,10,10,10,10,16, 9, 9, 9, 9, 9, 9, 9, 8,
  129497. 10, 9,11,11,16, 8, 9, 9, 9, 9, 9, 9, 9,10,10,11,
  129498. 11,16,13,13, 9, 9,10, 9, 9,10,11,11,11,12,16,13,
  129499. 14, 9, 8,10, 8, 9, 9,10,10,12,11,16,14,16, 9, 9,
  129500. 9, 9,11,11,12,11,12,11,16,16,16, 9, 7, 9, 6,11,
  129501. 11,11,10,11,11,16,16,16,11,12, 9,10,11,11,12,11,
  129502. 13,13,16,16,16,12,11,10, 7,12,10,12,12,12,12,16,
  129503. 16,15,16,16,10,11,10,11,13,13,14,12,16,16,16,15,
  129504. 15,12,10,11,11,13,11,12,13,
  129505. };
  129506. static float _vq_quantthresh__44c6_s_p9_1[] = {
  129507. -269.5, -220.5, -171.5, -122.5, -73.5, -24.5, 24.5, 73.5,
  129508. 122.5, 171.5, 220.5, 269.5,
  129509. };
  129510. static long _vq_quantmap__44c6_s_p9_1[] = {
  129511. 11, 9, 7, 5, 3, 1, 0, 2,
  129512. 4, 6, 8, 10, 12,
  129513. };
  129514. static encode_aux_threshmatch _vq_auxt__44c6_s_p9_1 = {
  129515. _vq_quantthresh__44c6_s_p9_1,
  129516. _vq_quantmap__44c6_s_p9_1,
  129517. 13,
  129518. 13
  129519. };
  129520. static static_codebook _44c6_s_p9_1 = {
  129521. 2, 169,
  129522. _vq_lengthlist__44c6_s_p9_1,
  129523. 1, -518889472, 1622704128, 4, 0,
  129524. _vq_quantlist__44c6_s_p9_1,
  129525. NULL,
  129526. &_vq_auxt__44c6_s_p9_1,
  129527. NULL,
  129528. 0
  129529. };
  129530. static long _vq_quantlist__44c6_s_p9_2[] = {
  129531. 24,
  129532. 23,
  129533. 25,
  129534. 22,
  129535. 26,
  129536. 21,
  129537. 27,
  129538. 20,
  129539. 28,
  129540. 19,
  129541. 29,
  129542. 18,
  129543. 30,
  129544. 17,
  129545. 31,
  129546. 16,
  129547. 32,
  129548. 15,
  129549. 33,
  129550. 14,
  129551. 34,
  129552. 13,
  129553. 35,
  129554. 12,
  129555. 36,
  129556. 11,
  129557. 37,
  129558. 10,
  129559. 38,
  129560. 9,
  129561. 39,
  129562. 8,
  129563. 40,
  129564. 7,
  129565. 41,
  129566. 6,
  129567. 42,
  129568. 5,
  129569. 43,
  129570. 4,
  129571. 44,
  129572. 3,
  129573. 45,
  129574. 2,
  129575. 46,
  129576. 1,
  129577. 47,
  129578. 0,
  129579. 48,
  129580. };
  129581. static long _vq_lengthlist__44c6_s_p9_2[] = {
  129582. 2, 4, 3, 4, 5, 5, 5, 6, 6, 6, 6, 6, 6, 6, 6, 6,
  129583. 6, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7,
  129584. 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7,
  129585. 7,
  129586. };
  129587. static float _vq_quantthresh__44c6_s_p9_2[] = {
  129588. -23.5, -22.5, -21.5, -20.5, -19.5, -18.5, -17.5, -16.5,
  129589. -15.5, -14.5, -13.5, -12.5, -11.5, -10.5, -9.5, -8.5,
  129590. -7.5, -6.5, -5.5, -4.5, -3.5, -2.5, -1.5, -0.5,
  129591. 0.5, 1.5, 2.5, 3.5, 4.5, 5.5, 6.5, 7.5,
  129592. 8.5, 9.5, 10.5, 11.5, 12.5, 13.5, 14.5, 15.5,
  129593. 16.5, 17.5, 18.5, 19.5, 20.5, 21.5, 22.5, 23.5,
  129594. };
  129595. static long _vq_quantmap__44c6_s_p9_2[] = {
  129596. 47, 45, 43, 41, 39, 37, 35, 33,
  129597. 31, 29, 27, 25, 23, 21, 19, 17,
  129598. 15, 13, 11, 9, 7, 5, 3, 1,
  129599. 0, 2, 4, 6, 8, 10, 12, 14,
  129600. 16, 18, 20, 22, 24, 26, 28, 30,
  129601. 32, 34, 36, 38, 40, 42, 44, 46,
  129602. 48,
  129603. };
  129604. static encode_aux_threshmatch _vq_auxt__44c6_s_p9_2 = {
  129605. _vq_quantthresh__44c6_s_p9_2,
  129606. _vq_quantmap__44c6_s_p9_2,
  129607. 49,
  129608. 49
  129609. };
  129610. static static_codebook _44c6_s_p9_2 = {
  129611. 1, 49,
  129612. _vq_lengthlist__44c6_s_p9_2,
  129613. 1, -526909440, 1611661312, 6, 0,
  129614. _vq_quantlist__44c6_s_p9_2,
  129615. NULL,
  129616. &_vq_auxt__44c6_s_p9_2,
  129617. NULL,
  129618. 0
  129619. };
  129620. static long _huff_lengthlist__44c6_s_short[] = {
  129621. 3, 9,11,11,13,14,19,17,17,19, 5, 4, 5, 8,10,10,
  129622. 13,16,18,19, 7, 4, 4, 5, 8, 9,12,14,17,19, 8, 6,
  129623. 5, 5, 7, 7,10,13,16,18,10, 8, 7, 6, 5, 5, 8,11,
  129624. 17,19,11, 9, 7, 7, 5, 4, 5, 8,17,19,13,11, 8, 7,
  129625. 7, 5, 5, 7,16,18,14,13, 8, 6, 6, 5, 5, 7,16,18,
  129626. 18,16,10, 8, 8, 7, 7, 9,16,18,18,18,12,10,10, 9,
  129627. 9,10,17,18,
  129628. };
  129629. static static_codebook _huff_book__44c6_s_short = {
  129630. 2, 100,
  129631. _huff_lengthlist__44c6_s_short,
  129632. 0, 0, 0, 0, 0,
  129633. NULL,
  129634. NULL,
  129635. NULL,
  129636. NULL,
  129637. 0
  129638. };
  129639. static long _huff_lengthlist__44c7_s_long[] = {
  129640. 3, 8,11,13,15,14,14,13,15,14, 6, 4, 5, 7, 9,10,
  129641. 11,11,14,13,10, 4, 3, 5, 7, 8, 9,10,13,13,12, 7,
  129642. 4, 4, 5, 6, 8, 9,12,14,13, 9, 6, 5, 5, 6, 8, 9,
  129643. 12,14,12, 9, 7, 6, 5, 5, 6, 8,11,11,12,11, 9, 8,
  129644. 7, 6, 6, 7,10,11,13,11,10, 9, 8, 7, 6, 6, 9,11,
  129645. 13,13,12,12,12,10, 9, 8, 9,11,12,14,15,15,14,12,
  129646. 11,10,10,12,
  129647. };
  129648. static static_codebook _huff_book__44c7_s_long = {
  129649. 2, 100,
  129650. _huff_lengthlist__44c7_s_long,
  129651. 0, 0, 0, 0, 0,
  129652. NULL,
  129653. NULL,
  129654. NULL,
  129655. NULL,
  129656. 0
  129657. };
  129658. static long _vq_quantlist__44c7_s_p1_0[] = {
  129659. 1,
  129660. 0,
  129661. 2,
  129662. };
  129663. static long _vq_lengthlist__44c7_s_p1_0[] = {
  129664. 1, 5, 5, 0, 5, 5, 0, 5, 5, 5, 8, 7, 0, 9, 9, 0,
  129665. 9, 8, 5, 7, 8, 0, 9, 9, 0, 8, 9, 0, 0, 0, 0, 0,
  129666. 0, 0, 0, 0, 5, 9, 9, 0, 8, 8, 0, 8, 8, 5, 8, 9,
  129667. 0, 8, 8, 0, 8, 8, 0, 0, 0, 0, 0, 0, 0, 0, 0, 5,
  129668. 9, 9, 0, 8, 8, 0, 8, 8, 5, 8, 9, 0, 8, 8, 0, 8,
  129669. 8,
  129670. };
  129671. static float _vq_quantthresh__44c7_s_p1_0[] = {
  129672. -0.5, 0.5,
  129673. };
  129674. static long _vq_quantmap__44c7_s_p1_0[] = {
  129675. 1, 0, 2,
  129676. };
  129677. static encode_aux_threshmatch _vq_auxt__44c7_s_p1_0 = {
  129678. _vq_quantthresh__44c7_s_p1_0,
  129679. _vq_quantmap__44c7_s_p1_0,
  129680. 3,
  129681. 3
  129682. };
  129683. static static_codebook _44c7_s_p1_0 = {
  129684. 4, 81,
  129685. _vq_lengthlist__44c7_s_p1_0,
  129686. 1, -535822336, 1611661312, 2, 0,
  129687. _vq_quantlist__44c7_s_p1_0,
  129688. NULL,
  129689. &_vq_auxt__44c7_s_p1_0,
  129690. NULL,
  129691. 0
  129692. };
  129693. static long _vq_quantlist__44c7_s_p2_0[] = {
  129694. 2,
  129695. 1,
  129696. 3,
  129697. 0,
  129698. 4,
  129699. };
  129700. static long _vq_lengthlist__44c7_s_p2_0[] = {
  129701. 3, 5, 5, 8, 8, 0, 5, 5, 8, 8, 0, 5, 5, 8, 8, 0,
  129702. 7, 7, 9, 9, 0, 0, 0, 9, 9, 5, 7, 7, 9, 9, 0, 8,
  129703. 8,10,10, 0, 8, 7,10, 9, 0,10,10,11,11, 0, 0, 0,
  129704. 11,11, 5, 7, 7, 9, 9, 0, 8, 8,10,10, 0, 7, 8, 9,
  129705. 10, 0,10,10,11,11, 0, 0, 0,11,11, 8, 9, 9,11,10,
  129706. 0,11,11,12,12, 0,11,10,12,12, 0,13,14,14,14, 0,
  129707. 0, 0,14,13, 8, 9, 9,10,11, 0,11,11,12,12, 0,10,
  129708. 11,12,12, 0,13,13,14,14, 0, 0, 0,13,14, 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, 5, 8, 7,11,10, 0, 7, 7,10,10,
  129711. 0, 7, 7,10,10, 0, 9, 9,11,10, 0, 0, 0,11,11, 5,
  129712. 7, 8,10,11, 0, 7, 7,10,10, 0, 7, 7,10,10, 0, 9,
  129713. 9,10,11, 0, 0, 0,11,11, 8,10, 9,12,12, 0,10,10,
  129714. 12,12, 0,10,10,12,12, 0,12,12,13,13, 0, 0, 0,13,
  129715. 13, 8, 9,10,12,12, 0,10,10,12,12, 0,10,10,11,12,
  129716. 0,12,12,13,13, 0, 0, 0,13,13, 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, 5, 8, 8,11,11, 0, 7, 7,10,10, 0, 7, 7,
  129719. 10,10, 0, 9, 9,10,11, 0, 0, 0,11,10, 5, 8, 8,10,
  129720. 11, 0, 7, 7,10,10, 0, 7, 7,10,10, 0, 9, 9,11,10,
  129721. 0, 0, 0,10,11, 9,10,10,12,12, 0,10,10,12,12, 0,
  129722. 10,10,12,12, 0,12,13,13,13, 0, 0, 0,13,12, 9,10,
  129723. 10,12,12, 0,10,10,12,12, 0,10,10,12,12, 0,13,12,
  129724. 13,13, 0, 0, 0,12,13, 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. 7,10,10,14,13, 0, 9, 9,12,12, 0, 9, 9,12,12, 0,
  129727. 10,10,12,12, 0, 0, 0,12,12, 7,10,10,13,14, 0, 9,
  129728. 9,12,13, 0, 9, 9,12,12, 0,10,10,12,12, 0, 0, 0,
  129729. 12,12, 9,11,11,14,13, 0,11,10,13,12, 0,11,11,13,
  129730. 13, 0,12,12,13,13, 0, 0, 0,13,13, 9,11,11,13,14,
  129731. 0,10,11,12,13, 0,11,11,13,13, 0,12,12,13,13, 0,
  129732. 0, 0,13,13, 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, 9,
  129737. 11,11,14,14, 0,10,11,13,13, 0,11,10,13,13, 0,12,
  129738. 12,13,13, 0, 0, 0,13,12, 9,11,11,14,14, 0,11,10,
  129739. 13,13, 0,10,11,13,13, 0,12,12,14,13, 0, 0, 0,13,
  129740. 13,
  129741. };
  129742. static float _vq_quantthresh__44c7_s_p2_0[] = {
  129743. -1.5, -0.5, 0.5, 1.5,
  129744. };
  129745. static long _vq_quantmap__44c7_s_p2_0[] = {
  129746. 3, 1, 0, 2, 4,
  129747. };
  129748. static encode_aux_threshmatch _vq_auxt__44c7_s_p2_0 = {
  129749. _vq_quantthresh__44c7_s_p2_0,
  129750. _vq_quantmap__44c7_s_p2_0,
  129751. 5,
  129752. 5
  129753. };
  129754. static static_codebook _44c7_s_p2_0 = {
  129755. 4, 625,
  129756. _vq_lengthlist__44c7_s_p2_0,
  129757. 1, -533725184, 1611661312, 3, 0,
  129758. _vq_quantlist__44c7_s_p2_0,
  129759. NULL,
  129760. &_vq_auxt__44c7_s_p2_0,
  129761. NULL,
  129762. 0
  129763. };
  129764. static long _vq_quantlist__44c7_s_p3_0[] = {
  129765. 4,
  129766. 3,
  129767. 5,
  129768. 2,
  129769. 6,
  129770. 1,
  129771. 7,
  129772. 0,
  129773. 8,
  129774. };
  129775. static long _vq_lengthlist__44c7_s_p3_0[] = {
  129776. 2, 4, 4, 5, 5, 7, 7, 9, 9, 0, 4, 4, 6, 6, 7, 7,
  129777. 9, 9, 0, 4, 4, 6, 6, 7, 7, 9, 9, 0, 5, 5, 6, 6,
  129778. 8, 8,10,10, 0, 0, 0, 6, 6, 8, 8,10,10, 0, 0, 0,
  129779. 7, 7, 9, 9,10,10, 0, 0, 0, 7, 7, 8, 8,10,10, 0,
  129780. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129781. 0,
  129782. };
  129783. static float _vq_quantthresh__44c7_s_p3_0[] = {
  129784. -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5, 3.5,
  129785. };
  129786. static long _vq_quantmap__44c7_s_p3_0[] = {
  129787. 7, 5, 3, 1, 0, 2, 4, 6,
  129788. 8,
  129789. };
  129790. static encode_aux_threshmatch _vq_auxt__44c7_s_p3_0 = {
  129791. _vq_quantthresh__44c7_s_p3_0,
  129792. _vq_quantmap__44c7_s_p3_0,
  129793. 9,
  129794. 9
  129795. };
  129796. static static_codebook _44c7_s_p3_0 = {
  129797. 2, 81,
  129798. _vq_lengthlist__44c7_s_p3_0,
  129799. 1, -531628032, 1611661312, 4, 0,
  129800. _vq_quantlist__44c7_s_p3_0,
  129801. NULL,
  129802. &_vq_auxt__44c7_s_p3_0,
  129803. NULL,
  129804. 0
  129805. };
  129806. static long _vq_quantlist__44c7_s_p4_0[] = {
  129807. 8,
  129808. 7,
  129809. 9,
  129810. 6,
  129811. 10,
  129812. 5,
  129813. 11,
  129814. 4,
  129815. 12,
  129816. 3,
  129817. 13,
  129818. 2,
  129819. 14,
  129820. 1,
  129821. 15,
  129822. 0,
  129823. 16,
  129824. };
  129825. static long _vq_lengthlist__44c7_s_p4_0[] = {
  129826. 3, 4, 4, 5, 5, 7, 7, 8, 8, 8, 8, 9, 9,10,10,11,
  129827. 11, 0, 4, 4, 6, 6, 7, 7, 8, 8, 9, 9,10,10,11,11,
  129828. 12,12, 0, 4, 4, 6, 6, 7, 7, 8, 8, 9, 9,10,10,11,
  129829. 11,12,12, 0, 5, 5, 6, 6, 8, 8, 9, 9, 9, 9,10,10,
  129830. 11,12,12,12, 0, 0, 0, 6, 6, 8, 7, 9, 9, 9, 9,10,
  129831. 10,11,11,12,12, 0, 0, 0, 7, 7, 8, 8, 9, 9,10,10,
  129832. 11,11,12,12,13,12, 0, 0, 0, 7, 7, 8, 8, 9, 9,10,
  129833. 10,11,11,12,12,12,13, 0, 0, 0, 7, 7, 8, 8, 9, 9,
  129834. 10,10,11,11,12,12,13,13, 0, 0, 0, 0, 0, 8, 8, 9,
  129835. 9,10,10,11,11,12,12,13,13, 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,
  129845. };
  129846. static float _vq_quantthresh__44c7_s_p4_0[] = {
  129847. -7.5, -6.5, -5.5, -4.5, -3.5, -2.5, -1.5, -0.5,
  129848. 0.5, 1.5, 2.5, 3.5, 4.5, 5.5, 6.5, 7.5,
  129849. };
  129850. static long _vq_quantmap__44c7_s_p4_0[] = {
  129851. 15, 13, 11, 9, 7, 5, 3, 1,
  129852. 0, 2, 4, 6, 8, 10, 12, 14,
  129853. 16,
  129854. };
  129855. static encode_aux_threshmatch _vq_auxt__44c7_s_p4_0 = {
  129856. _vq_quantthresh__44c7_s_p4_0,
  129857. _vq_quantmap__44c7_s_p4_0,
  129858. 17,
  129859. 17
  129860. };
  129861. static static_codebook _44c7_s_p4_0 = {
  129862. 2, 289,
  129863. _vq_lengthlist__44c7_s_p4_0,
  129864. 1, -529530880, 1611661312, 5, 0,
  129865. _vq_quantlist__44c7_s_p4_0,
  129866. NULL,
  129867. &_vq_auxt__44c7_s_p4_0,
  129868. NULL,
  129869. 0
  129870. };
  129871. static long _vq_quantlist__44c7_s_p5_0[] = {
  129872. 1,
  129873. 0,
  129874. 2,
  129875. };
  129876. static long _vq_lengthlist__44c7_s_p5_0[] = {
  129877. 1, 4, 4, 5, 7, 7, 6, 7, 7, 4, 6, 7,10,10,10,10,
  129878. 10, 9, 4, 6, 6,10,10,10,10, 9,10, 5,10,10, 9,11,
  129879. 12,10,11,12, 7,10,10,11,12,12,12,12,12, 7,10,10,
  129880. 11,12,12,12,12,12, 6,10,10,10,12,12,11,12,12, 7,
  129881. 10,10,12,12,12,12,11,12, 7,10,10,11,12,12,12,12,
  129882. 12,
  129883. };
  129884. static float _vq_quantthresh__44c7_s_p5_0[] = {
  129885. -5.5, 5.5,
  129886. };
  129887. static long _vq_quantmap__44c7_s_p5_0[] = {
  129888. 1, 0, 2,
  129889. };
  129890. static encode_aux_threshmatch _vq_auxt__44c7_s_p5_0 = {
  129891. _vq_quantthresh__44c7_s_p5_0,
  129892. _vq_quantmap__44c7_s_p5_0,
  129893. 3,
  129894. 3
  129895. };
  129896. static static_codebook _44c7_s_p5_0 = {
  129897. 4, 81,
  129898. _vq_lengthlist__44c7_s_p5_0,
  129899. 1, -529137664, 1618345984, 2, 0,
  129900. _vq_quantlist__44c7_s_p5_0,
  129901. NULL,
  129902. &_vq_auxt__44c7_s_p5_0,
  129903. NULL,
  129904. 0
  129905. };
  129906. static long _vq_quantlist__44c7_s_p5_1[] = {
  129907. 5,
  129908. 4,
  129909. 6,
  129910. 3,
  129911. 7,
  129912. 2,
  129913. 8,
  129914. 1,
  129915. 9,
  129916. 0,
  129917. 10,
  129918. };
  129919. static long _vq_lengthlist__44c7_s_p5_1[] = {
  129920. 3, 5, 5, 6, 6, 7, 7, 8, 8, 8, 8,11, 4, 4, 6, 6,
  129921. 7, 7, 8, 8, 9, 9,11, 4, 4, 6, 6, 7, 7, 8, 8, 9,
  129922. 9,12, 5, 5, 6, 6, 7, 7, 9, 9, 9, 9,12,12,12, 6,
  129923. 6, 7, 7, 9, 9, 9, 9,11,11,11, 7, 7, 7, 7, 8, 8,
  129924. 9, 9,11,11,11, 7, 7, 7, 7, 8, 8, 9, 9,11,11,11,
  129925. 7, 7, 8, 8, 8, 8, 9, 9,11,11,11,11,11, 8, 8, 8,
  129926. 8, 8, 9,11,11,11,11,11, 8, 8, 8, 8, 8, 8,11,11,
  129927. 11,11,11, 7, 7, 8, 8, 8, 8,
  129928. };
  129929. static float _vq_quantthresh__44c7_s_p5_1[] = {
  129930. -4.5, -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5,
  129931. 3.5, 4.5,
  129932. };
  129933. static long _vq_quantmap__44c7_s_p5_1[] = {
  129934. 9, 7, 5, 3, 1, 0, 2, 4,
  129935. 6, 8, 10,
  129936. };
  129937. static encode_aux_threshmatch _vq_auxt__44c7_s_p5_1 = {
  129938. _vq_quantthresh__44c7_s_p5_1,
  129939. _vq_quantmap__44c7_s_p5_1,
  129940. 11,
  129941. 11
  129942. };
  129943. static static_codebook _44c7_s_p5_1 = {
  129944. 2, 121,
  129945. _vq_lengthlist__44c7_s_p5_1,
  129946. 1, -531365888, 1611661312, 4, 0,
  129947. _vq_quantlist__44c7_s_p5_1,
  129948. NULL,
  129949. &_vq_auxt__44c7_s_p5_1,
  129950. NULL,
  129951. 0
  129952. };
  129953. static long _vq_quantlist__44c7_s_p6_0[] = {
  129954. 6,
  129955. 5,
  129956. 7,
  129957. 4,
  129958. 8,
  129959. 3,
  129960. 9,
  129961. 2,
  129962. 10,
  129963. 1,
  129964. 11,
  129965. 0,
  129966. 12,
  129967. };
  129968. static long _vq_lengthlist__44c7_s_p6_0[] = {
  129969. 1, 4, 4, 6, 6, 7, 7, 8, 7, 9, 8,10,10, 6, 5, 5,
  129970. 7, 7, 8, 8, 9, 9, 9,10,11,11, 7, 5, 5, 7, 7, 8,
  129971. 8, 9, 9,10,10,11,11, 0, 7, 7, 7, 7, 9, 8, 9, 9,
  129972. 10,10,11,11, 0, 8, 8, 7, 7, 8, 9, 9, 9,10,10,11,
  129973. 11, 0,11,11, 9, 9,10,10,11,10,11,11,12,12, 0,12,
  129974. 12, 9, 9,10,10,11,11,11,11,12,12, 0, 0, 0, 0, 0,
  129975. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129976. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129977. 0, 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,
  129980. };
  129981. static float _vq_quantthresh__44c7_s_p6_0[] = {
  129982. -27.5, -22.5, -17.5, -12.5, -7.5, -2.5, 2.5, 7.5,
  129983. 12.5, 17.5, 22.5, 27.5,
  129984. };
  129985. static long _vq_quantmap__44c7_s_p6_0[] = {
  129986. 11, 9, 7, 5, 3, 1, 0, 2,
  129987. 4, 6, 8, 10, 12,
  129988. };
  129989. static encode_aux_threshmatch _vq_auxt__44c7_s_p6_0 = {
  129990. _vq_quantthresh__44c7_s_p6_0,
  129991. _vq_quantmap__44c7_s_p6_0,
  129992. 13,
  129993. 13
  129994. };
  129995. static static_codebook _44c7_s_p6_0 = {
  129996. 2, 169,
  129997. _vq_lengthlist__44c7_s_p6_0,
  129998. 1, -526516224, 1616117760, 4, 0,
  129999. _vq_quantlist__44c7_s_p6_0,
  130000. NULL,
  130001. &_vq_auxt__44c7_s_p6_0,
  130002. NULL,
  130003. 0
  130004. };
  130005. static long _vq_quantlist__44c7_s_p6_1[] = {
  130006. 2,
  130007. 1,
  130008. 3,
  130009. 0,
  130010. 4,
  130011. };
  130012. static long _vq_lengthlist__44c7_s_p6_1[] = {
  130013. 3, 4, 4, 5, 5, 5, 4, 4, 5, 5, 5, 4, 4, 5, 5, 6,
  130014. 5, 5, 5, 5, 6, 6, 6, 5, 5,
  130015. };
  130016. static float _vq_quantthresh__44c7_s_p6_1[] = {
  130017. -1.5, -0.5, 0.5, 1.5,
  130018. };
  130019. static long _vq_quantmap__44c7_s_p6_1[] = {
  130020. 3, 1, 0, 2, 4,
  130021. };
  130022. static encode_aux_threshmatch _vq_auxt__44c7_s_p6_1 = {
  130023. _vq_quantthresh__44c7_s_p6_1,
  130024. _vq_quantmap__44c7_s_p6_1,
  130025. 5,
  130026. 5
  130027. };
  130028. static static_codebook _44c7_s_p6_1 = {
  130029. 2, 25,
  130030. _vq_lengthlist__44c7_s_p6_1,
  130031. 1, -533725184, 1611661312, 3, 0,
  130032. _vq_quantlist__44c7_s_p6_1,
  130033. NULL,
  130034. &_vq_auxt__44c7_s_p6_1,
  130035. NULL,
  130036. 0
  130037. };
  130038. static long _vq_quantlist__44c7_s_p7_0[] = {
  130039. 6,
  130040. 5,
  130041. 7,
  130042. 4,
  130043. 8,
  130044. 3,
  130045. 9,
  130046. 2,
  130047. 10,
  130048. 1,
  130049. 11,
  130050. 0,
  130051. 12,
  130052. };
  130053. static long _vq_lengthlist__44c7_s_p7_0[] = {
  130054. 1, 4, 4, 6, 6, 7, 8, 9, 9,10,10,12,11, 6, 5, 5,
  130055. 7, 7, 8, 8, 9,10,11,11,12,12, 7, 5, 5, 7, 7, 8,
  130056. 8,10,10,11,11,12,12,20, 7, 7, 7, 7, 8, 9,10,10,
  130057. 11,11,12,13,20, 7, 7, 7, 7, 9, 9,10,10,11,12,13,
  130058. 13,20,11,11, 8, 8, 9, 9,11,11,12,12,13,13,20,11,
  130059. 11, 8, 8, 9, 9,11,11,12,12,13,13,20,20,20,10,10,
  130060. 10,10,12,12,13,13,13,13,20,20,20,10,10,10,10,12,
  130061. 12,13,13,13,14,20,20,20,14,14,11,11,12,12,13,13,
  130062. 14,14,20,20,20,14,14,11,11,12,12,13,13,14,14,20,
  130063. 20,20,20,19,13,13,13,13,14,14,15,14,19,19,19,19,
  130064. 19,13,13,13,13,14,14,15,15,
  130065. };
  130066. static float _vq_quantthresh__44c7_s_p7_0[] = {
  130067. -60.5, -49.5, -38.5, -27.5, -16.5, -5.5, 5.5, 16.5,
  130068. 27.5, 38.5, 49.5, 60.5,
  130069. };
  130070. static long _vq_quantmap__44c7_s_p7_0[] = {
  130071. 11, 9, 7, 5, 3, 1, 0, 2,
  130072. 4, 6, 8, 10, 12,
  130073. };
  130074. static encode_aux_threshmatch _vq_auxt__44c7_s_p7_0 = {
  130075. _vq_quantthresh__44c7_s_p7_0,
  130076. _vq_quantmap__44c7_s_p7_0,
  130077. 13,
  130078. 13
  130079. };
  130080. static static_codebook _44c7_s_p7_0 = {
  130081. 2, 169,
  130082. _vq_lengthlist__44c7_s_p7_0,
  130083. 1, -523206656, 1618345984, 4, 0,
  130084. _vq_quantlist__44c7_s_p7_0,
  130085. NULL,
  130086. &_vq_auxt__44c7_s_p7_0,
  130087. NULL,
  130088. 0
  130089. };
  130090. static long _vq_quantlist__44c7_s_p7_1[] = {
  130091. 5,
  130092. 4,
  130093. 6,
  130094. 3,
  130095. 7,
  130096. 2,
  130097. 8,
  130098. 1,
  130099. 9,
  130100. 0,
  130101. 10,
  130102. };
  130103. static long _vq_lengthlist__44c7_s_p7_1[] = {
  130104. 4, 5, 5, 6, 6, 7, 7, 7, 7, 7, 7, 8, 6, 6, 7, 7,
  130105. 7, 7, 7, 7, 7, 7, 8, 6, 6, 6, 7, 7, 7, 7, 7, 7,
  130106. 7, 8, 6, 6, 7, 7, 7, 7, 7, 7, 7, 7, 8, 8, 8, 7,
  130107. 7, 7, 7, 7, 7, 7, 7, 8, 8, 8, 7, 7, 7, 7, 7, 7,
  130108. 7, 7, 8, 8, 8, 7, 7, 7, 7, 7, 7, 7, 7, 8, 8, 8,
  130109. 7, 7, 7, 7, 7, 7, 7, 7, 8, 8, 8, 8, 8, 7, 7, 7,
  130110. 7, 7, 7, 8, 8, 8, 8, 8, 7, 7, 7, 7, 7, 7, 8, 8,
  130111. 8, 8, 8, 7, 7, 7, 7, 7, 7,
  130112. };
  130113. static float _vq_quantthresh__44c7_s_p7_1[] = {
  130114. -4.5, -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5,
  130115. 3.5, 4.5,
  130116. };
  130117. static long _vq_quantmap__44c7_s_p7_1[] = {
  130118. 9, 7, 5, 3, 1, 0, 2, 4,
  130119. 6, 8, 10,
  130120. };
  130121. static encode_aux_threshmatch _vq_auxt__44c7_s_p7_1 = {
  130122. _vq_quantthresh__44c7_s_p7_1,
  130123. _vq_quantmap__44c7_s_p7_1,
  130124. 11,
  130125. 11
  130126. };
  130127. static static_codebook _44c7_s_p7_1 = {
  130128. 2, 121,
  130129. _vq_lengthlist__44c7_s_p7_1,
  130130. 1, -531365888, 1611661312, 4, 0,
  130131. _vq_quantlist__44c7_s_p7_1,
  130132. NULL,
  130133. &_vq_auxt__44c7_s_p7_1,
  130134. NULL,
  130135. 0
  130136. };
  130137. static long _vq_quantlist__44c7_s_p8_0[] = {
  130138. 7,
  130139. 6,
  130140. 8,
  130141. 5,
  130142. 9,
  130143. 4,
  130144. 10,
  130145. 3,
  130146. 11,
  130147. 2,
  130148. 12,
  130149. 1,
  130150. 13,
  130151. 0,
  130152. 14,
  130153. };
  130154. static long _vq_lengthlist__44c7_s_p8_0[] = {
  130155. 1, 4, 4, 7, 7, 8, 8, 8, 7, 9, 8, 9, 9,10,10, 6,
  130156. 5, 5, 7, 7, 9, 9, 8, 8,10, 9,11,10,12,11, 6, 5,
  130157. 5, 8, 7, 9, 9, 8, 8,10,10,11,11,12,11,19, 8, 8,
  130158. 8, 8,10,10, 9, 9,10,10,11,11,12,11,19, 8, 8, 8,
  130159. 8,10,10, 9, 9,10,10,11,11,12,12,19,12,12, 9, 9,
  130160. 10,10, 9,10,10,10,11,11,12,12,19,12,12, 9, 9,10,
  130161. 10,10,10,10,10,12,12,12,12,19,19,19, 9, 9, 9, 9,
  130162. 11,10,11,11,12,11,13,13,19,19,19, 9, 9, 9, 9,11,
  130163. 10,11,11,11,12,13,13,19,19,19,13,13,10,10,11,11,
  130164. 12,12,12,12,13,12,19,19,19,14,13,10,10,11,11,12,
  130165. 12,12,13,13,13,19,19,19,19,19,12,12,12,11,12,13,
  130166. 14,13,13,13,19,19,19,19,19,12,12,12,11,12,12,13,
  130167. 14,13,14,19,19,19,19,19,16,16,12,13,12,13,13,14,
  130168. 15,14,19,18,18,18,18,16,15,12,11,12,11,14,12,14,
  130169. 14,
  130170. };
  130171. static float _vq_quantthresh__44c7_s_p8_0[] = {
  130172. -136.5, -115.5, -94.5, -73.5, -52.5, -31.5, -10.5, 10.5,
  130173. 31.5, 52.5, 73.5, 94.5, 115.5, 136.5,
  130174. };
  130175. static long _vq_quantmap__44c7_s_p8_0[] = {
  130176. 13, 11, 9, 7, 5, 3, 1, 0,
  130177. 2, 4, 6, 8, 10, 12, 14,
  130178. };
  130179. static encode_aux_threshmatch _vq_auxt__44c7_s_p8_0 = {
  130180. _vq_quantthresh__44c7_s_p8_0,
  130181. _vq_quantmap__44c7_s_p8_0,
  130182. 15,
  130183. 15
  130184. };
  130185. static static_codebook _44c7_s_p8_0 = {
  130186. 2, 225,
  130187. _vq_lengthlist__44c7_s_p8_0,
  130188. 1, -520986624, 1620377600, 4, 0,
  130189. _vq_quantlist__44c7_s_p8_0,
  130190. NULL,
  130191. &_vq_auxt__44c7_s_p8_0,
  130192. NULL,
  130193. 0
  130194. };
  130195. static long _vq_quantlist__44c7_s_p8_1[] = {
  130196. 10,
  130197. 9,
  130198. 11,
  130199. 8,
  130200. 12,
  130201. 7,
  130202. 13,
  130203. 6,
  130204. 14,
  130205. 5,
  130206. 15,
  130207. 4,
  130208. 16,
  130209. 3,
  130210. 17,
  130211. 2,
  130212. 18,
  130213. 1,
  130214. 19,
  130215. 0,
  130216. 20,
  130217. };
  130218. static long _vq_lengthlist__44c7_s_p8_1[] = {
  130219. 3, 5, 5, 7, 6, 7, 7, 8, 8, 8, 8, 8, 8, 8, 8, 8,
  130220. 8, 8, 8, 8, 8,10, 6, 6, 7, 7, 8, 8, 8, 8, 9, 9,
  130221. 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,10, 6, 6, 7, 7, 8,
  130222. 8, 8, 8, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,10,
  130223. 7, 7, 8, 8, 8, 8, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,
  130224. 9, 9, 9, 9,10,10,10, 8, 8, 8, 8, 9, 9, 9, 9, 9,
  130225. 9, 9, 9, 9, 9, 9, 9, 9, 9,10,10,10, 8, 8, 8, 9,
  130226. 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,10,10,
  130227. 10, 8, 8, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,
  130228. 9, 9, 9,10,10,10, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,
  130229. 9, 9, 9, 9, 9, 9, 9, 9,10,11,10,10,10, 9, 9, 9,
  130230. 9, 9, 9, 9, 9, 9, 9,10, 9, 9,10, 9, 9,10,11,10,
  130231. 11,10, 9, 9, 9, 9, 9, 9, 9,10,10,10, 9,10, 9, 9,
  130232. 9, 9,11,10,11,10,10, 9, 9, 9, 9, 9, 9,10, 9, 9,
  130233. 10, 9, 9,10, 9, 9,10,11,10,10,11,10, 9, 9, 9, 9,
  130234. 9,10,10, 9,10,10,10,10, 9,10,10,10,10,10,10,11,
  130235. 11,11,10, 9, 9, 9,10,10,10,10,10,10,10,10,10,10,
  130236. 10,10,10,11,11,10,10,10,10,10,10,10,10,10,10,10,
  130237. 10, 9,10,10, 9,10,11,11,10,11,10,11,10, 9,10,10,
  130238. 9,10,10,10,10,10,10,10,10,10,10,11,11,11,11,10,
  130239. 11,11,10,10,10,10,10,10, 9,10, 9,10,10, 9,10, 9,
  130240. 10,10,10,11,10,11,10,11,11,10,10,10,10,10,10, 9,
  130241. 10,10,10,10,10,10,10,11,10,10,10,10,10,10,10,10,
  130242. 10,10,10,10,10,10,10,10,10,10,10,10,10,11,10,11,
  130243. 11,10,10,10,10, 9, 9,10,10, 9, 9,10, 9,10,10,10,
  130244. 10,11,11,10,10,10,10,10,10,10, 9, 9,10,10,10, 9,
  130245. 9,10,10,10,10,10,11,10,11,10,10,10,10,10,10, 9,
  130246. 10,10,10,10,10,10,10,10,10,
  130247. };
  130248. static float _vq_quantthresh__44c7_s_p8_1[] = {
  130249. -9.5, -8.5, -7.5, -6.5, -5.5, -4.5, -3.5, -2.5,
  130250. -1.5, -0.5, 0.5, 1.5, 2.5, 3.5, 4.5, 5.5,
  130251. 6.5, 7.5, 8.5, 9.5,
  130252. };
  130253. static long _vq_quantmap__44c7_s_p8_1[] = {
  130254. 19, 17, 15, 13, 11, 9, 7, 5,
  130255. 3, 1, 0, 2, 4, 6, 8, 10,
  130256. 12, 14, 16, 18, 20,
  130257. };
  130258. static encode_aux_threshmatch _vq_auxt__44c7_s_p8_1 = {
  130259. _vq_quantthresh__44c7_s_p8_1,
  130260. _vq_quantmap__44c7_s_p8_1,
  130261. 21,
  130262. 21
  130263. };
  130264. static static_codebook _44c7_s_p8_1 = {
  130265. 2, 441,
  130266. _vq_lengthlist__44c7_s_p8_1,
  130267. 1, -529268736, 1611661312, 5, 0,
  130268. _vq_quantlist__44c7_s_p8_1,
  130269. NULL,
  130270. &_vq_auxt__44c7_s_p8_1,
  130271. NULL,
  130272. 0
  130273. };
  130274. static long _vq_quantlist__44c7_s_p9_0[] = {
  130275. 6,
  130276. 5,
  130277. 7,
  130278. 4,
  130279. 8,
  130280. 3,
  130281. 9,
  130282. 2,
  130283. 10,
  130284. 1,
  130285. 11,
  130286. 0,
  130287. 12,
  130288. };
  130289. static long _vq_lengthlist__44c7_s_p9_0[] = {
  130290. 1, 3, 3,11,11,11,11,11,11,11,11,11,11, 4, 6, 6,
  130291. 11,11,11,11,11,11,11,11,11,11, 4, 7, 7,11,11,11,
  130292. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  130293. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  130294. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  130295. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  130296. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  130297. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  130298. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  130299. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  130300. 11,11,11,11,11,11,11,11,11,
  130301. };
  130302. static float _vq_quantthresh__44c7_s_p9_0[] = {
  130303. -3503.5, -2866.5, -2229.5, -1592.5, -955.5, -318.5, 318.5, 955.5,
  130304. 1592.5, 2229.5, 2866.5, 3503.5,
  130305. };
  130306. static long _vq_quantmap__44c7_s_p9_0[] = {
  130307. 11, 9, 7, 5, 3, 1, 0, 2,
  130308. 4, 6, 8, 10, 12,
  130309. };
  130310. static encode_aux_threshmatch _vq_auxt__44c7_s_p9_0 = {
  130311. _vq_quantthresh__44c7_s_p9_0,
  130312. _vq_quantmap__44c7_s_p9_0,
  130313. 13,
  130314. 13
  130315. };
  130316. static static_codebook _44c7_s_p9_0 = {
  130317. 2, 169,
  130318. _vq_lengthlist__44c7_s_p9_0,
  130319. 1, -511845376, 1630791680, 4, 0,
  130320. _vq_quantlist__44c7_s_p9_0,
  130321. NULL,
  130322. &_vq_auxt__44c7_s_p9_0,
  130323. NULL,
  130324. 0
  130325. };
  130326. static long _vq_quantlist__44c7_s_p9_1[] = {
  130327. 6,
  130328. 5,
  130329. 7,
  130330. 4,
  130331. 8,
  130332. 3,
  130333. 9,
  130334. 2,
  130335. 10,
  130336. 1,
  130337. 11,
  130338. 0,
  130339. 12,
  130340. };
  130341. static long _vq_lengthlist__44c7_s_p9_1[] = {
  130342. 1, 4, 4, 7, 7, 7, 7, 7, 6, 8, 8, 8, 8, 6, 6, 6,
  130343. 8, 8, 9, 8, 8, 7, 9, 8,11,10, 5, 6, 6, 8, 8, 9,
  130344. 8, 8, 8,10, 9,11,11,16, 8, 8, 9, 8, 9, 9, 9, 8,
  130345. 10, 9,11,10,16, 8, 8, 9, 9,10,10, 9, 9,10,10,11,
  130346. 11,16,13,13, 9, 9,10,10, 9,10,11,11,12,11,16,13,
  130347. 13, 9, 8,10, 9,10,10,10,10,11,11,16,14,16, 8, 9,
  130348. 9, 9,11,10,11,11,12,11,16,16,16, 9, 7,10, 7,11,
  130349. 10,11,11,12,11,16,16,16,12,12, 9,10,11,11,12,11,
  130350. 12,12,16,16,16,12,10,10, 7,11, 8,12,11,12,12,16,
  130351. 16,15,16,16,11,12,10,10,12,11,12,12,16,16,16,15,
  130352. 15,11,11,10,10,12,12,12,12,
  130353. };
  130354. static float _vq_quantthresh__44c7_s_p9_1[] = {
  130355. -269.5, -220.5, -171.5, -122.5, -73.5, -24.5, 24.5, 73.5,
  130356. 122.5, 171.5, 220.5, 269.5,
  130357. };
  130358. static long _vq_quantmap__44c7_s_p9_1[] = {
  130359. 11, 9, 7, 5, 3, 1, 0, 2,
  130360. 4, 6, 8, 10, 12,
  130361. };
  130362. static encode_aux_threshmatch _vq_auxt__44c7_s_p9_1 = {
  130363. _vq_quantthresh__44c7_s_p9_1,
  130364. _vq_quantmap__44c7_s_p9_1,
  130365. 13,
  130366. 13
  130367. };
  130368. static static_codebook _44c7_s_p9_1 = {
  130369. 2, 169,
  130370. _vq_lengthlist__44c7_s_p9_1,
  130371. 1, -518889472, 1622704128, 4, 0,
  130372. _vq_quantlist__44c7_s_p9_1,
  130373. NULL,
  130374. &_vq_auxt__44c7_s_p9_1,
  130375. NULL,
  130376. 0
  130377. };
  130378. static long _vq_quantlist__44c7_s_p9_2[] = {
  130379. 24,
  130380. 23,
  130381. 25,
  130382. 22,
  130383. 26,
  130384. 21,
  130385. 27,
  130386. 20,
  130387. 28,
  130388. 19,
  130389. 29,
  130390. 18,
  130391. 30,
  130392. 17,
  130393. 31,
  130394. 16,
  130395. 32,
  130396. 15,
  130397. 33,
  130398. 14,
  130399. 34,
  130400. 13,
  130401. 35,
  130402. 12,
  130403. 36,
  130404. 11,
  130405. 37,
  130406. 10,
  130407. 38,
  130408. 9,
  130409. 39,
  130410. 8,
  130411. 40,
  130412. 7,
  130413. 41,
  130414. 6,
  130415. 42,
  130416. 5,
  130417. 43,
  130418. 4,
  130419. 44,
  130420. 3,
  130421. 45,
  130422. 2,
  130423. 46,
  130424. 1,
  130425. 47,
  130426. 0,
  130427. 48,
  130428. };
  130429. static long _vq_lengthlist__44c7_s_p9_2[] = {
  130430. 2, 4, 3, 4, 5, 5, 5, 6, 6, 6, 6, 6, 6, 6, 6, 6,
  130431. 6, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7,
  130432. 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7,
  130433. 7,
  130434. };
  130435. static float _vq_quantthresh__44c7_s_p9_2[] = {
  130436. -23.5, -22.5, -21.5, -20.5, -19.5, -18.5, -17.5, -16.5,
  130437. -15.5, -14.5, -13.5, -12.5, -11.5, -10.5, -9.5, -8.5,
  130438. -7.5, -6.5, -5.5, -4.5, -3.5, -2.5, -1.5, -0.5,
  130439. 0.5, 1.5, 2.5, 3.5, 4.5, 5.5, 6.5, 7.5,
  130440. 8.5, 9.5, 10.5, 11.5, 12.5, 13.5, 14.5, 15.5,
  130441. 16.5, 17.5, 18.5, 19.5, 20.5, 21.5, 22.5, 23.5,
  130442. };
  130443. static long _vq_quantmap__44c7_s_p9_2[] = {
  130444. 47, 45, 43, 41, 39, 37, 35, 33,
  130445. 31, 29, 27, 25, 23, 21, 19, 17,
  130446. 15, 13, 11, 9, 7, 5, 3, 1,
  130447. 0, 2, 4, 6, 8, 10, 12, 14,
  130448. 16, 18, 20, 22, 24, 26, 28, 30,
  130449. 32, 34, 36, 38, 40, 42, 44, 46,
  130450. 48,
  130451. };
  130452. static encode_aux_threshmatch _vq_auxt__44c7_s_p9_2 = {
  130453. _vq_quantthresh__44c7_s_p9_2,
  130454. _vq_quantmap__44c7_s_p9_2,
  130455. 49,
  130456. 49
  130457. };
  130458. static static_codebook _44c7_s_p9_2 = {
  130459. 1, 49,
  130460. _vq_lengthlist__44c7_s_p9_2,
  130461. 1, -526909440, 1611661312, 6, 0,
  130462. _vq_quantlist__44c7_s_p9_2,
  130463. NULL,
  130464. &_vq_auxt__44c7_s_p9_2,
  130465. NULL,
  130466. 0
  130467. };
  130468. static long _huff_lengthlist__44c7_s_short[] = {
  130469. 4,11,12,14,15,15,17,17,18,18, 5, 6, 6, 8, 9,10,
  130470. 13,17,18,19, 7, 5, 4, 6, 8, 9,11,15,19,19, 8, 6,
  130471. 5, 5, 6, 7,11,14,16,17, 9, 7, 7, 6, 7, 7,10,13,
  130472. 15,19,10, 8, 7, 6, 7, 6, 7, 9,14,16,12,10, 9, 7,
  130473. 7, 6, 4, 5,10,15,14,13,11, 7, 6, 6, 4, 2, 7,13,
  130474. 16,16,15, 9, 8, 8, 8, 6, 9,13,19,19,17,12,11,10,
  130475. 10, 9,11,14,
  130476. };
  130477. static static_codebook _huff_book__44c7_s_short = {
  130478. 2, 100,
  130479. _huff_lengthlist__44c7_s_short,
  130480. 0, 0, 0, 0, 0,
  130481. NULL,
  130482. NULL,
  130483. NULL,
  130484. NULL,
  130485. 0
  130486. };
  130487. static long _huff_lengthlist__44c8_s_long[] = {
  130488. 3, 8,12,13,14,14,14,13,14,14, 6, 4, 5, 8,10,10,
  130489. 11,11,14,13, 9, 5, 4, 5, 7, 8, 9,10,13,13,12, 7,
  130490. 5, 4, 5, 6, 8, 9,12,13,13, 9, 6, 5, 5, 5, 7, 9,
  130491. 11,14,12,10, 7, 6, 5, 4, 6, 7,10,11,12,11, 9, 8,
  130492. 7, 5, 5, 6,10,10,13,12,10, 9, 8, 6, 6, 5, 8,10,
  130493. 14,13,12,12,11,10, 9, 7, 8,10,12,13,14,14,13,12,
  130494. 11, 9, 9,10,
  130495. };
  130496. static static_codebook _huff_book__44c8_s_long = {
  130497. 2, 100,
  130498. _huff_lengthlist__44c8_s_long,
  130499. 0, 0, 0, 0, 0,
  130500. NULL,
  130501. NULL,
  130502. NULL,
  130503. NULL,
  130504. 0
  130505. };
  130506. static long _vq_quantlist__44c8_s_p1_0[] = {
  130507. 1,
  130508. 0,
  130509. 2,
  130510. };
  130511. static long _vq_lengthlist__44c8_s_p1_0[] = {
  130512. 1, 5, 5, 0, 5, 5, 0, 5, 5, 5, 7, 7, 0, 9, 8, 0,
  130513. 9, 8, 6, 7, 7, 0, 8, 9, 0, 8, 9, 0, 0, 0, 0, 0,
  130514. 0, 0, 0, 0, 5, 9, 8, 0, 8, 8, 0, 8, 8, 5, 8, 9,
  130515. 0, 8, 8, 0, 8, 8, 0, 0, 0, 0, 0, 0, 0, 0, 0, 5,
  130516. 9, 8, 0, 8, 8, 0, 8, 8, 5, 8, 9, 0, 8, 8, 0, 8,
  130517. 8,
  130518. };
  130519. static float _vq_quantthresh__44c8_s_p1_0[] = {
  130520. -0.5, 0.5,
  130521. };
  130522. static long _vq_quantmap__44c8_s_p1_0[] = {
  130523. 1, 0, 2,
  130524. };
  130525. static encode_aux_threshmatch _vq_auxt__44c8_s_p1_0 = {
  130526. _vq_quantthresh__44c8_s_p1_0,
  130527. _vq_quantmap__44c8_s_p1_0,
  130528. 3,
  130529. 3
  130530. };
  130531. static static_codebook _44c8_s_p1_0 = {
  130532. 4, 81,
  130533. _vq_lengthlist__44c8_s_p1_0,
  130534. 1, -535822336, 1611661312, 2, 0,
  130535. _vq_quantlist__44c8_s_p1_0,
  130536. NULL,
  130537. &_vq_auxt__44c8_s_p1_0,
  130538. NULL,
  130539. 0
  130540. };
  130541. static long _vq_quantlist__44c8_s_p2_0[] = {
  130542. 2,
  130543. 1,
  130544. 3,
  130545. 0,
  130546. 4,
  130547. };
  130548. static long _vq_lengthlist__44c8_s_p2_0[] = {
  130549. 3, 5, 5, 8, 8, 0, 5, 5, 8, 8, 0, 5, 5, 8, 8, 0,
  130550. 7, 7, 9, 9, 0, 0, 0, 9, 9, 5, 7, 7, 9, 9, 0, 8,
  130551. 7,10, 9, 0, 8, 7,10, 9, 0,10,10,11,11, 0, 0, 0,
  130552. 11,11, 5, 7, 7, 9, 9, 0, 7, 8, 9,10, 0, 7, 8, 9,
  130553. 10, 0,10,10,11,11, 0, 0, 0,11,11, 8, 9, 9,11,10,
  130554. 0,11,10,12,11, 0,11,10,12,12, 0,13,13,14,14, 0,
  130555. 0, 0,14,13, 8, 9, 9,10,11, 0,10,11,12,12, 0,10,
  130556. 11,12,12, 0,13,13,14,14, 0, 0, 0,13,14, 0, 0, 0,
  130557. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130558. 0, 0, 0, 0, 0, 0, 5, 8, 7,11,10, 0, 7, 7,10,10,
  130559. 0, 7, 7,10,10, 0, 9, 9,10,10, 0, 0, 0,11,10, 5,
  130560. 7, 8,10,11, 0, 7, 7,10,10, 0, 7, 7,10,10, 0, 9,
  130561. 9,10,10, 0, 0, 0,10,10, 8,10, 9,12,12, 0,10,10,
  130562. 12,11, 0,10,10,12,12, 0,12,12,13,12, 0, 0, 0,13,
  130563. 12, 8, 9,10,12,12, 0,10,10,11,12, 0,10,10,11,12,
  130564. 0,12,12,13,13, 0, 0, 0,12,13, 0, 0, 0, 0, 0, 0,
  130565. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130566. 0, 0, 0, 6, 8, 7,11,10, 0, 7, 7,10,10, 0, 7, 7,
  130567. 10,10, 0, 9, 9,10,11, 0, 0, 0,10,10, 6, 7, 8,10,
  130568. 11, 0, 7, 7,10,10, 0, 7, 7,10,10, 0, 9, 9,10,10,
  130569. 0, 0, 0,10,10, 9,10, 9,12,12, 0,10,10,12,12, 0,
  130570. 10,10,12,11, 0,12,12,13,13, 0, 0, 0,13,12, 8, 9,
  130571. 10,12,12, 0,10,10,12,12, 0,10,10,11,12, 0,12,12,
  130572. 13,13, 0, 0, 0,12,13, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130573. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130574. 7,10,10,13,13, 0, 9, 9,12,12, 0, 9, 9,12,12, 0,
  130575. 10,10,12,12, 0, 0, 0,12,12, 7,10,10,13,13, 0, 9,
  130576. 9,12,12, 0, 9, 9,12,12, 0,10,10,12,12, 0, 0, 0,
  130577. 12,12, 9,11,11,14,13, 0,10,10,13,12, 0,11,10,13,
  130578. 12, 0,12,12,13,12, 0, 0, 0,13,13, 9,11,11,13,14,
  130579. 0,10,11,12,13, 0,10,11,13,13, 0,12,12,12,13, 0,
  130580. 0, 0,13,13, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130581. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130582. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130583. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130584. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 9,
  130585. 11,11,14,14, 0,10,11,13,13, 0,11,10,13,13, 0,11,
  130586. 12,13,13, 0, 0, 0,13,12, 9,11,11,14,14, 0,11,10,
  130587. 13,13, 0,10,11,13,13, 0,12,12,13,13, 0, 0, 0,12,
  130588. 13,
  130589. };
  130590. static float _vq_quantthresh__44c8_s_p2_0[] = {
  130591. -1.5, -0.5, 0.5, 1.5,
  130592. };
  130593. static long _vq_quantmap__44c8_s_p2_0[] = {
  130594. 3, 1, 0, 2, 4,
  130595. };
  130596. static encode_aux_threshmatch _vq_auxt__44c8_s_p2_0 = {
  130597. _vq_quantthresh__44c8_s_p2_0,
  130598. _vq_quantmap__44c8_s_p2_0,
  130599. 5,
  130600. 5
  130601. };
  130602. static static_codebook _44c8_s_p2_0 = {
  130603. 4, 625,
  130604. _vq_lengthlist__44c8_s_p2_0,
  130605. 1, -533725184, 1611661312, 3, 0,
  130606. _vq_quantlist__44c8_s_p2_0,
  130607. NULL,
  130608. &_vq_auxt__44c8_s_p2_0,
  130609. NULL,
  130610. 0
  130611. };
  130612. static long _vq_quantlist__44c8_s_p3_0[] = {
  130613. 4,
  130614. 3,
  130615. 5,
  130616. 2,
  130617. 6,
  130618. 1,
  130619. 7,
  130620. 0,
  130621. 8,
  130622. };
  130623. static long _vq_lengthlist__44c8_s_p3_0[] = {
  130624. 2, 4, 4, 5, 5, 7, 7, 9, 9, 0, 4, 4, 6, 6, 7, 7,
  130625. 9, 9, 0, 4, 4, 6, 6, 7, 7, 9, 9, 0, 5, 5, 6, 6,
  130626. 8, 8,10,10, 0, 0, 0, 6, 6, 8, 8,10,10, 0, 0, 0,
  130627. 7, 7, 9, 9,10,10, 0, 0, 0, 7, 7, 8, 8,10,10, 0,
  130628. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130629. 0,
  130630. };
  130631. static float _vq_quantthresh__44c8_s_p3_0[] = {
  130632. -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5, 3.5,
  130633. };
  130634. static long _vq_quantmap__44c8_s_p3_0[] = {
  130635. 7, 5, 3, 1, 0, 2, 4, 6,
  130636. 8,
  130637. };
  130638. static encode_aux_threshmatch _vq_auxt__44c8_s_p3_0 = {
  130639. _vq_quantthresh__44c8_s_p3_0,
  130640. _vq_quantmap__44c8_s_p3_0,
  130641. 9,
  130642. 9
  130643. };
  130644. static static_codebook _44c8_s_p3_0 = {
  130645. 2, 81,
  130646. _vq_lengthlist__44c8_s_p3_0,
  130647. 1, -531628032, 1611661312, 4, 0,
  130648. _vq_quantlist__44c8_s_p3_0,
  130649. NULL,
  130650. &_vq_auxt__44c8_s_p3_0,
  130651. NULL,
  130652. 0
  130653. };
  130654. static long _vq_quantlist__44c8_s_p4_0[] = {
  130655. 8,
  130656. 7,
  130657. 9,
  130658. 6,
  130659. 10,
  130660. 5,
  130661. 11,
  130662. 4,
  130663. 12,
  130664. 3,
  130665. 13,
  130666. 2,
  130667. 14,
  130668. 1,
  130669. 15,
  130670. 0,
  130671. 16,
  130672. };
  130673. static long _vq_lengthlist__44c8_s_p4_0[] = {
  130674. 3, 4, 4, 5, 5, 7, 7, 8, 8, 8, 8, 9, 9,10,10,11,
  130675. 11, 0, 4, 4, 6, 6, 7, 7, 8, 8, 9, 8,10,10,11,11,
  130676. 11,11, 0, 4, 4, 6, 6, 7, 7, 8, 8, 9, 9,10,10,11,
  130677. 11,11,11, 0, 6, 5, 6, 6, 7, 7, 9, 9, 9, 9,10,10,
  130678. 11,11,12,12, 0, 0, 0, 6, 6, 7, 7, 9, 9, 9, 9,10,
  130679. 10,11,11,12,12, 0, 0, 0, 7, 7, 8, 8, 9, 9,10,10,
  130680. 11,11,11,12,12,12, 0, 0, 0, 7, 7, 8, 8, 9, 9,10,
  130681. 10,11,11,11,12,12,12, 0, 0, 0, 7, 7, 8, 8, 9, 9,
  130682. 10,10,11,11,12,12,13,13, 0, 0, 0, 0, 0, 8, 8, 9,
  130683. 9,10,10,11,11,12,12,13,13, 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,
  130693. };
  130694. static float _vq_quantthresh__44c8_s_p4_0[] = {
  130695. -7.5, -6.5, -5.5, -4.5, -3.5, -2.5, -1.5, -0.5,
  130696. 0.5, 1.5, 2.5, 3.5, 4.5, 5.5, 6.5, 7.5,
  130697. };
  130698. static long _vq_quantmap__44c8_s_p4_0[] = {
  130699. 15, 13, 11, 9, 7, 5, 3, 1,
  130700. 0, 2, 4, 6, 8, 10, 12, 14,
  130701. 16,
  130702. };
  130703. static encode_aux_threshmatch _vq_auxt__44c8_s_p4_0 = {
  130704. _vq_quantthresh__44c8_s_p4_0,
  130705. _vq_quantmap__44c8_s_p4_0,
  130706. 17,
  130707. 17
  130708. };
  130709. static static_codebook _44c8_s_p4_0 = {
  130710. 2, 289,
  130711. _vq_lengthlist__44c8_s_p4_0,
  130712. 1, -529530880, 1611661312, 5, 0,
  130713. _vq_quantlist__44c8_s_p4_0,
  130714. NULL,
  130715. &_vq_auxt__44c8_s_p4_0,
  130716. NULL,
  130717. 0
  130718. };
  130719. static long _vq_quantlist__44c8_s_p5_0[] = {
  130720. 1,
  130721. 0,
  130722. 2,
  130723. };
  130724. static long _vq_lengthlist__44c8_s_p5_0[] = {
  130725. 1, 4, 4, 5, 7, 7, 6, 7, 7, 4, 7, 6,10,10,10,10,
  130726. 10,10, 4, 6, 6,10,10,10,10, 9,10, 5,10,10, 9,11,
  130727. 11,10,11,11, 7,10,10,11,12,12,12,12,12, 7,10,10,
  130728. 11,12,12,12,12,12, 6,10,10,10,12,12,10,12,12, 7,
  130729. 10,10,11,12,12,12,12,12, 7,10,10,11,12,12,12,12,
  130730. 12,
  130731. };
  130732. static float _vq_quantthresh__44c8_s_p5_0[] = {
  130733. -5.5, 5.5,
  130734. };
  130735. static long _vq_quantmap__44c8_s_p5_0[] = {
  130736. 1, 0, 2,
  130737. };
  130738. static encode_aux_threshmatch _vq_auxt__44c8_s_p5_0 = {
  130739. _vq_quantthresh__44c8_s_p5_0,
  130740. _vq_quantmap__44c8_s_p5_0,
  130741. 3,
  130742. 3
  130743. };
  130744. static static_codebook _44c8_s_p5_0 = {
  130745. 4, 81,
  130746. _vq_lengthlist__44c8_s_p5_0,
  130747. 1, -529137664, 1618345984, 2, 0,
  130748. _vq_quantlist__44c8_s_p5_0,
  130749. NULL,
  130750. &_vq_auxt__44c8_s_p5_0,
  130751. NULL,
  130752. 0
  130753. };
  130754. static long _vq_quantlist__44c8_s_p5_1[] = {
  130755. 5,
  130756. 4,
  130757. 6,
  130758. 3,
  130759. 7,
  130760. 2,
  130761. 8,
  130762. 1,
  130763. 9,
  130764. 0,
  130765. 10,
  130766. };
  130767. static long _vq_lengthlist__44c8_s_p5_1[] = {
  130768. 3, 5, 5, 6, 6, 7, 7, 8, 8, 8, 8,11, 4, 5, 6, 6,
  130769. 7, 7, 8, 8, 8, 8,11, 5, 5, 6, 6, 7, 7, 8, 8, 8,
  130770. 9,12, 5, 5, 6, 6, 7, 7, 8, 8, 9, 9,12,12,12, 6,
  130771. 6, 7, 7, 8, 8, 9, 9,11,11,11, 6, 6, 7, 7, 8, 8,
  130772. 8, 8,11,11,11, 6, 6, 7, 7, 8, 8, 8, 8,11,11,11,
  130773. 7, 7, 7, 8, 8, 8, 8, 8,11,11,11,11,11, 7, 7, 8,
  130774. 8, 8, 8,11,11,11,11,11, 7, 7, 7, 7, 8, 8,11,11,
  130775. 11,11,11, 7, 7, 7, 7, 8, 8,
  130776. };
  130777. static float _vq_quantthresh__44c8_s_p5_1[] = {
  130778. -4.5, -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5,
  130779. 3.5, 4.5,
  130780. };
  130781. static long _vq_quantmap__44c8_s_p5_1[] = {
  130782. 9, 7, 5, 3, 1, 0, 2, 4,
  130783. 6, 8, 10,
  130784. };
  130785. static encode_aux_threshmatch _vq_auxt__44c8_s_p5_1 = {
  130786. _vq_quantthresh__44c8_s_p5_1,
  130787. _vq_quantmap__44c8_s_p5_1,
  130788. 11,
  130789. 11
  130790. };
  130791. static static_codebook _44c8_s_p5_1 = {
  130792. 2, 121,
  130793. _vq_lengthlist__44c8_s_p5_1,
  130794. 1, -531365888, 1611661312, 4, 0,
  130795. _vq_quantlist__44c8_s_p5_1,
  130796. NULL,
  130797. &_vq_auxt__44c8_s_p5_1,
  130798. NULL,
  130799. 0
  130800. };
  130801. static long _vq_quantlist__44c8_s_p6_0[] = {
  130802. 6,
  130803. 5,
  130804. 7,
  130805. 4,
  130806. 8,
  130807. 3,
  130808. 9,
  130809. 2,
  130810. 10,
  130811. 1,
  130812. 11,
  130813. 0,
  130814. 12,
  130815. };
  130816. static long _vq_lengthlist__44c8_s_p6_0[] = {
  130817. 1, 4, 4, 6, 6, 7, 7, 8, 8, 9, 9,10,10, 6, 5, 5,
  130818. 7, 7, 8, 8, 9, 9,10,10,11,11, 6, 5, 5, 7, 7, 8,
  130819. 8, 9, 9,10,10,11,11, 0, 7, 7, 7, 7, 9, 9,10,10,
  130820. 10,10,11,11, 0, 7, 7, 7, 7, 9, 9,10,10,10,10,11,
  130821. 11, 0,11,11, 9, 9,10,10,11,11,11,11,12,12, 0,12,
  130822. 12, 9, 9,10,10,11,11,12,12,12,12, 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,
  130828. };
  130829. static float _vq_quantthresh__44c8_s_p6_0[] = {
  130830. -27.5, -22.5, -17.5, -12.5, -7.5, -2.5, 2.5, 7.5,
  130831. 12.5, 17.5, 22.5, 27.5,
  130832. };
  130833. static long _vq_quantmap__44c8_s_p6_0[] = {
  130834. 11, 9, 7, 5, 3, 1, 0, 2,
  130835. 4, 6, 8, 10, 12,
  130836. };
  130837. static encode_aux_threshmatch _vq_auxt__44c8_s_p6_0 = {
  130838. _vq_quantthresh__44c8_s_p6_0,
  130839. _vq_quantmap__44c8_s_p6_0,
  130840. 13,
  130841. 13
  130842. };
  130843. static static_codebook _44c8_s_p6_0 = {
  130844. 2, 169,
  130845. _vq_lengthlist__44c8_s_p6_0,
  130846. 1, -526516224, 1616117760, 4, 0,
  130847. _vq_quantlist__44c8_s_p6_0,
  130848. NULL,
  130849. &_vq_auxt__44c8_s_p6_0,
  130850. NULL,
  130851. 0
  130852. };
  130853. static long _vq_quantlist__44c8_s_p6_1[] = {
  130854. 2,
  130855. 1,
  130856. 3,
  130857. 0,
  130858. 4,
  130859. };
  130860. static long _vq_lengthlist__44c8_s_p6_1[] = {
  130861. 3, 4, 4, 5, 5, 5, 4, 4, 5, 5, 5, 4, 4, 5, 5, 6,
  130862. 5, 5, 5, 5, 6, 6, 6, 5, 5,
  130863. };
  130864. static float _vq_quantthresh__44c8_s_p6_1[] = {
  130865. -1.5, -0.5, 0.5, 1.5,
  130866. };
  130867. static long _vq_quantmap__44c8_s_p6_1[] = {
  130868. 3, 1, 0, 2, 4,
  130869. };
  130870. static encode_aux_threshmatch _vq_auxt__44c8_s_p6_1 = {
  130871. _vq_quantthresh__44c8_s_p6_1,
  130872. _vq_quantmap__44c8_s_p6_1,
  130873. 5,
  130874. 5
  130875. };
  130876. static static_codebook _44c8_s_p6_1 = {
  130877. 2, 25,
  130878. _vq_lengthlist__44c8_s_p6_1,
  130879. 1, -533725184, 1611661312, 3, 0,
  130880. _vq_quantlist__44c8_s_p6_1,
  130881. NULL,
  130882. &_vq_auxt__44c8_s_p6_1,
  130883. NULL,
  130884. 0
  130885. };
  130886. static long _vq_quantlist__44c8_s_p7_0[] = {
  130887. 6,
  130888. 5,
  130889. 7,
  130890. 4,
  130891. 8,
  130892. 3,
  130893. 9,
  130894. 2,
  130895. 10,
  130896. 1,
  130897. 11,
  130898. 0,
  130899. 12,
  130900. };
  130901. static long _vq_lengthlist__44c8_s_p7_0[] = {
  130902. 1, 4, 4, 6, 6, 8, 7, 9, 9,10,10,12,12, 6, 5, 5,
  130903. 7, 7, 8, 8,10,10,11,11,12,12, 7, 5, 5, 7, 7, 8,
  130904. 8,10,10,11,11,12,12,21, 7, 7, 7, 7, 8, 9,10,10,
  130905. 11,11,12,12,21, 7, 7, 7, 7, 9, 9,10,10,12,12,13,
  130906. 13,21,11,11, 8, 8, 9, 9,11,11,12,12,13,13,21,11,
  130907. 11, 8, 8, 9, 9,11,11,12,12,13,13,21,21,21,10,10,
  130908. 10,10,11,11,12,13,13,13,21,21,21,10,10,10,10,11,
  130909. 11,13,13,14,13,21,21,21,13,13,11,11,12,12,13,13,
  130910. 14,14,21,21,21,14,14,11,11,12,12,13,13,14,14,21,
  130911. 21,21,21,20,13,13,13,12,14,14,16,15,20,20,20,20,
  130912. 20,13,13,13,13,14,13,15,15,
  130913. };
  130914. static float _vq_quantthresh__44c8_s_p7_0[] = {
  130915. -60.5, -49.5, -38.5, -27.5, -16.5, -5.5, 5.5, 16.5,
  130916. 27.5, 38.5, 49.5, 60.5,
  130917. };
  130918. static long _vq_quantmap__44c8_s_p7_0[] = {
  130919. 11, 9, 7, 5, 3, 1, 0, 2,
  130920. 4, 6, 8, 10, 12,
  130921. };
  130922. static encode_aux_threshmatch _vq_auxt__44c8_s_p7_0 = {
  130923. _vq_quantthresh__44c8_s_p7_0,
  130924. _vq_quantmap__44c8_s_p7_0,
  130925. 13,
  130926. 13
  130927. };
  130928. static static_codebook _44c8_s_p7_0 = {
  130929. 2, 169,
  130930. _vq_lengthlist__44c8_s_p7_0,
  130931. 1, -523206656, 1618345984, 4, 0,
  130932. _vq_quantlist__44c8_s_p7_0,
  130933. NULL,
  130934. &_vq_auxt__44c8_s_p7_0,
  130935. NULL,
  130936. 0
  130937. };
  130938. static long _vq_quantlist__44c8_s_p7_1[] = {
  130939. 5,
  130940. 4,
  130941. 6,
  130942. 3,
  130943. 7,
  130944. 2,
  130945. 8,
  130946. 1,
  130947. 9,
  130948. 0,
  130949. 10,
  130950. };
  130951. static long _vq_lengthlist__44c8_s_p7_1[] = {
  130952. 4, 5, 6, 6, 6, 7, 7, 7, 7, 7, 7, 8, 6, 6, 6, 7,
  130953. 7, 7, 7, 7, 7, 7, 8, 6, 6, 6, 6, 7, 7, 7, 7, 7,
  130954. 7, 8, 6, 6, 7, 7, 7, 7, 7, 7, 7, 7, 8, 8, 8, 7,
  130955. 7, 7, 7, 7, 7, 7, 7, 8, 8, 8, 7, 7, 7, 7, 7, 7,
  130956. 7, 7, 8, 8, 8, 7, 7, 7, 7, 7, 7, 7, 7, 8, 8, 8,
  130957. 7, 7, 7, 7, 7, 7, 7, 7, 8, 8, 8, 8, 8, 7, 7, 7,
  130958. 7, 7, 7, 8, 8, 8, 8, 8, 7, 7, 7, 7, 7, 7, 8, 8,
  130959. 8, 8, 8, 7, 7, 7, 7, 7, 7,
  130960. };
  130961. static float _vq_quantthresh__44c8_s_p7_1[] = {
  130962. -4.5, -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5,
  130963. 3.5, 4.5,
  130964. };
  130965. static long _vq_quantmap__44c8_s_p7_1[] = {
  130966. 9, 7, 5, 3, 1, 0, 2, 4,
  130967. 6, 8, 10,
  130968. };
  130969. static encode_aux_threshmatch _vq_auxt__44c8_s_p7_1 = {
  130970. _vq_quantthresh__44c8_s_p7_1,
  130971. _vq_quantmap__44c8_s_p7_1,
  130972. 11,
  130973. 11
  130974. };
  130975. static static_codebook _44c8_s_p7_1 = {
  130976. 2, 121,
  130977. _vq_lengthlist__44c8_s_p7_1,
  130978. 1, -531365888, 1611661312, 4, 0,
  130979. _vq_quantlist__44c8_s_p7_1,
  130980. NULL,
  130981. &_vq_auxt__44c8_s_p7_1,
  130982. NULL,
  130983. 0
  130984. };
  130985. static long _vq_quantlist__44c8_s_p8_0[] = {
  130986. 7,
  130987. 6,
  130988. 8,
  130989. 5,
  130990. 9,
  130991. 4,
  130992. 10,
  130993. 3,
  130994. 11,
  130995. 2,
  130996. 12,
  130997. 1,
  130998. 13,
  130999. 0,
  131000. 14,
  131001. };
  131002. static long _vq_lengthlist__44c8_s_p8_0[] = {
  131003. 1, 4, 4, 7, 6, 8, 8, 8, 7, 9, 8,10,10,11,10, 6,
  131004. 5, 5, 7, 7, 9, 9, 8, 8,10,10,11,11,12,11, 6, 5,
  131005. 5, 7, 7, 9, 9, 9, 9,10,10,11,11,12,12,20, 8, 8,
  131006. 8, 8, 9, 9, 9, 9,10,10,11,11,12,12,20, 8, 8, 8,
  131007. 8,10, 9, 9, 9,10,10,11,11,12,12,20,12,12, 9, 9,
  131008. 10,10,10,10,10,11,12,12,12,12,20,12,12, 9, 9,10,
  131009. 10,10,10,11,11,12,12,13,13,20,20,20, 9, 9, 9, 9,
  131010. 11,10,11,11,12,12,12,13,20,19,19, 9, 9, 9, 9,11,
  131011. 11,11,12,12,12,13,13,19,19,19,13,13,10,10,11,11,
  131012. 12,12,13,13,13,13,19,19,19,14,13,11,10,11,11,12,
  131013. 12,12,13,13,13,19,19,19,19,19,12,12,12,12,13,13,
  131014. 13,13,14,13,19,19,19,19,19,12,12,12,11,12,12,13,
  131015. 14,14,14,19,19,19,19,19,16,15,13,12,13,13,13,14,
  131016. 14,14,19,19,19,19,19,17,17,13,12,13,11,14,13,15,
  131017. 15,
  131018. };
  131019. static float _vq_quantthresh__44c8_s_p8_0[] = {
  131020. -136.5, -115.5, -94.5, -73.5, -52.5, -31.5, -10.5, 10.5,
  131021. 31.5, 52.5, 73.5, 94.5, 115.5, 136.5,
  131022. };
  131023. static long _vq_quantmap__44c8_s_p8_0[] = {
  131024. 13, 11, 9, 7, 5, 3, 1, 0,
  131025. 2, 4, 6, 8, 10, 12, 14,
  131026. };
  131027. static encode_aux_threshmatch _vq_auxt__44c8_s_p8_0 = {
  131028. _vq_quantthresh__44c8_s_p8_0,
  131029. _vq_quantmap__44c8_s_p8_0,
  131030. 15,
  131031. 15
  131032. };
  131033. static static_codebook _44c8_s_p8_0 = {
  131034. 2, 225,
  131035. _vq_lengthlist__44c8_s_p8_0,
  131036. 1, -520986624, 1620377600, 4, 0,
  131037. _vq_quantlist__44c8_s_p8_0,
  131038. NULL,
  131039. &_vq_auxt__44c8_s_p8_0,
  131040. NULL,
  131041. 0
  131042. };
  131043. static long _vq_quantlist__44c8_s_p8_1[] = {
  131044. 10,
  131045. 9,
  131046. 11,
  131047. 8,
  131048. 12,
  131049. 7,
  131050. 13,
  131051. 6,
  131052. 14,
  131053. 5,
  131054. 15,
  131055. 4,
  131056. 16,
  131057. 3,
  131058. 17,
  131059. 2,
  131060. 18,
  131061. 1,
  131062. 19,
  131063. 0,
  131064. 20,
  131065. };
  131066. static long _vq_lengthlist__44c8_s_p8_1[] = {
  131067. 4, 5, 5, 7, 7, 7, 7, 8, 8, 8, 8, 8, 8, 8, 8, 8,
  131068. 8, 8, 8, 8, 8,10, 6, 6, 7, 7, 8, 8, 8, 8, 9, 9,
  131069. 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,10, 6, 6, 7, 7, 8,
  131070. 8, 8, 8, 8, 8, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,10,
  131071. 7, 7, 8, 8, 8, 8, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,
  131072. 9, 9, 9, 9,10,10,10, 8, 8, 8, 8, 9, 9, 9, 9, 9,
  131073. 9, 9, 9, 9, 9, 9, 9, 9, 9,10,10,10, 8, 8, 8, 9,
  131074. 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,10,10,
  131075. 10, 8, 8, 8, 8, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,
  131076. 9, 9, 9,10,10,10, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,
  131077. 9, 9, 9, 9, 9, 9, 9, 9,10,10,10,10,10, 9, 9, 9,
  131078. 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,10,10,10,
  131079. 10,10, 9, 9, 9, 9, 9, 9, 9, 9,10, 9, 9, 9, 9, 9,
  131080. 9, 9,10,10,10,10,10, 9, 9, 9, 9, 9, 9, 9, 9, 9,
  131081. 9, 9, 9, 9, 9, 9, 9,10,10,10,10,10, 9, 9, 9, 9,
  131082. 9, 9, 9, 9,10,10,10, 9, 9, 9, 9, 9,10,10,10,10,
  131083. 10,10,10, 9, 9, 9, 9, 9,10,10,10, 9, 9, 9, 9, 9,
  131084. 9,10,10,10,10,10,10,10, 9,10,10, 9,10,10,10,10,
  131085. 9,10, 9,10,10, 9,10,10,10,10,10,10,10, 9,10,10,
  131086. 10,10,10,10, 9, 9,10,10, 9,10,10,10,10,10,10,10,
  131087. 10,10,10,10,10,10,10,10, 9, 9, 9,10, 9, 9, 9, 9,
  131088. 10,10,10,10,10,10,10,10,10,10,10,10,10,10, 9, 9,
  131089. 10, 9,10, 9,10,10,10,10,10,10,10,10,10,10,10,10,
  131090. 10,10,10,10, 9, 9,10, 9, 9, 9,10,10,10,10,10,10,
  131091. 10,10,10,10,10, 9, 9, 9, 9, 9, 9,10, 9, 9,10,10,
  131092. 10,10,10,10,10,10,10,10,10,10,10,10,10, 9,10, 9,
  131093. 9,10, 9, 9,10,10,10,10,10,10,10,10,10,10,10,10,
  131094. 10, 9, 9,10,10, 9,10, 9, 9,
  131095. };
  131096. static float _vq_quantthresh__44c8_s_p8_1[] = {
  131097. -9.5, -8.5, -7.5, -6.5, -5.5, -4.5, -3.5, -2.5,
  131098. -1.5, -0.5, 0.5, 1.5, 2.5, 3.5, 4.5, 5.5,
  131099. 6.5, 7.5, 8.5, 9.5,
  131100. };
  131101. static long _vq_quantmap__44c8_s_p8_1[] = {
  131102. 19, 17, 15, 13, 11, 9, 7, 5,
  131103. 3, 1, 0, 2, 4, 6, 8, 10,
  131104. 12, 14, 16, 18, 20,
  131105. };
  131106. static encode_aux_threshmatch _vq_auxt__44c8_s_p8_1 = {
  131107. _vq_quantthresh__44c8_s_p8_1,
  131108. _vq_quantmap__44c8_s_p8_1,
  131109. 21,
  131110. 21
  131111. };
  131112. static static_codebook _44c8_s_p8_1 = {
  131113. 2, 441,
  131114. _vq_lengthlist__44c8_s_p8_1,
  131115. 1, -529268736, 1611661312, 5, 0,
  131116. _vq_quantlist__44c8_s_p8_1,
  131117. NULL,
  131118. &_vq_auxt__44c8_s_p8_1,
  131119. NULL,
  131120. 0
  131121. };
  131122. static long _vq_quantlist__44c8_s_p9_0[] = {
  131123. 8,
  131124. 7,
  131125. 9,
  131126. 6,
  131127. 10,
  131128. 5,
  131129. 11,
  131130. 4,
  131131. 12,
  131132. 3,
  131133. 13,
  131134. 2,
  131135. 14,
  131136. 1,
  131137. 15,
  131138. 0,
  131139. 16,
  131140. };
  131141. static long _vq_lengthlist__44c8_s_p9_0[] = {
  131142. 1, 4, 3,11,11,11,11,11,11,11,11,11,11,11,11,11,
  131143. 11, 4, 7, 7,11,11,11,11,11,11,11,11,11,11,11,11,
  131144. 11,11, 4, 8,11,11,11,11,11,11,11,11,11,11,11,11,
  131145. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  131146. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  131147. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  131148. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  131149. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  131150. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  131151. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  131152. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  131153. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  131154. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  131155. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  131156. 11,11,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  131157. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  131158. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  131159. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  131160. 10,
  131161. };
  131162. static float _vq_quantthresh__44c8_s_p9_0[] = {
  131163. -6982.5, -6051.5, -5120.5, -4189.5, -3258.5, -2327.5, -1396.5, -465.5,
  131164. 465.5, 1396.5, 2327.5, 3258.5, 4189.5, 5120.5, 6051.5, 6982.5,
  131165. };
  131166. static long _vq_quantmap__44c8_s_p9_0[] = {
  131167. 15, 13, 11, 9, 7, 5, 3, 1,
  131168. 0, 2, 4, 6, 8, 10, 12, 14,
  131169. 16,
  131170. };
  131171. static encode_aux_threshmatch _vq_auxt__44c8_s_p9_0 = {
  131172. _vq_quantthresh__44c8_s_p9_0,
  131173. _vq_quantmap__44c8_s_p9_0,
  131174. 17,
  131175. 17
  131176. };
  131177. static static_codebook _44c8_s_p9_0 = {
  131178. 2, 289,
  131179. _vq_lengthlist__44c8_s_p9_0,
  131180. 1, -509798400, 1631393792, 5, 0,
  131181. _vq_quantlist__44c8_s_p9_0,
  131182. NULL,
  131183. &_vq_auxt__44c8_s_p9_0,
  131184. NULL,
  131185. 0
  131186. };
  131187. static long _vq_quantlist__44c8_s_p9_1[] = {
  131188. 9,
  131189. 8,
  131190. 10,
  131191. 7,
  131192. 11,
  131193. 6,
  131194. 12,
  131195. 5,
  131196. 13,
  131197. 4,
  131198. 14,
  131199. 3,
  131200. 15,
  131201. 2,
  131202. 16,
  131203. 1,
  131204. 17,
  131205. 0,
  131206. 18,
  131207. };
  131208. static long _vq_lengthlist__44c8_s_p9_1[] = {
  131209. 1, 4, 4, 7, 6, 7, 7, 7, 7, 8, 8, 9, 9,10,10,10,
  131210. 10,11,11, 6, 6, 6, 8, 8, 9, 8, 8, 7,10, 8,11,10,
  131211. 12,11,12,12,13,13, 5, 5, 6, 8, 8, 9, 9, 8, 8,10,
  131212. 9,11,11,12,12,13,13,13,13,17, 8, 8, 9, 9, 9, 9,
  131213. 9, 9,10, 9,12,10,12,12,13,12,13,13,17, 9, 8, 9,
  131214. 9, 9, 9, 9, 9,10,10,12,12,12,12,13,13,13,13,17,
  131215. 13,13, 9, 9,10,10,10,10,11,11,12,11,13,12,13,13,
  131216. 14,15,17,13,13, 9, 8,10, 9,10,10,11,11,12,12,14,
  131217. 13,15,13,14,15,17,17,17, 9,10, 9,10,11,11,12,12,
  131218. 12,12,13,13,14,14,15,15,17,17,17, 9, 8, 9, 8,11,
  131219. 11,12,12,12,12,14,13,14,14,14,15,17,17,17,12,14,
  131220. 9,10,11,11,12,12,14,13,13,14,15,13,15,15,17,17,
  131221. 17,13,11,10, 8,11, 9,13,12,13,13,13,13,13,14,14,
  131222. 14,17,17,17,17,17,11,12,11,11,13,13,14,13,15,14,
  131223. 13,15,16,15,17,17,17,17,17,11,11,12, 8,13,12,14,
  131224. 13,17,14,15,14,15,14,17,17,17,17,17,15,15,12,12,
  131225. 12,12,13,14,14,14,15,14,17,14,17,17,17,17,17,16,
  131226. 17,12,12,13,12,13,13,14,14,14,14,14,14,17,17,17,
  131227. 17,17,17,17,14,14,13,12,13,13,15,15,14,13,15,17,
  131228. 17,17,17,17,17,17,17,13,14,13,13,13,13,14,15,15,
  131229. 15,14,15,17,17,17,17,17,17,17,16,15,13,14,13,13,
  131230. 14,14,15,14,14,16,17,17,17,17,17,17,17,16,16,13,
  131231. 14,13,13,14,14,15,14,15,14,
  131232. };
  131233. static float _vq_quantthresh__44c8_s_p9_1[] = {
  131234. -416.5, -367.5, -318.5, -269.5, -220.5, -171.5, -122.5, -73.5,
  131235. -24.5, 24.5, 73.5, 122.5, 171.5, 220.5, 269.5, 318.5,
  131236. 367.5, 416.5,
  131237. };
  131238. static long _vq_quantmap__44c8_s_p9_1[] = {
  131239. 17, 15, 13, 11, 9, 7, 5, 3,
  131240. 1, 0, 2, 4, 6, 8, 10, 12,
  131241. 14, 16, 18,
  131242. };
  131243. static encode_aux_threshmatch _vq_auxt__44c8_s_p9_1 = {
  131244. _vq_quantthresh__44c8_s_p9_1,
  131245. _vq_quantmap__44c8_s_p9_1,
  131246. 19,
  131247. 19
  131248. };
  131249. static static_codebook _44c8_s_p9_1 = {
  131250. 2, 361,
  131251. _vq_lengthlist__44c8_s_p9_1,
  131252. 1, -518287360, 1622704128, 5, 0,
  131253. _vq_quantlist__44c8_s_p9_1,
  131254. NULL,
  131255. &_vq_auxt__44c8_s_p9_1,
  131256. NULL,
  131257. 0
  131258. };
  131259. static long _vq_quantlist__44c8_s_p9_2[] = {
  131260. 24,
  131261. 23,
  131262. 25,
  131263. 22,
  131264. 26,
  131265. 21,
  131266. 27,
  131267. 20,
  131268. 28,
  131269. 19,
  131270. 29,
  131271. 18,
  131272. 30,
  131273. 17,
  131274. 31,
  131275. 16,
  131276. 32,
  131277. 15,
  131278. 33,
  131279. 14,
  131280. 34,
  131281. 13,
  131282. 35,
  131283. 12,
  131284. 36,
  131285. 11,
  131286. 37,
  131287. 10,
  131288. 38,
  131289. 9,
  131290. 39,
  131291. 8,
  131292. 40,
  131293. 7,
  131294. 41,
  131295. 6,
  131296. 42,
  131297. 5,
  131298. 43,
  131299. 4,
  131300. 44,
  131301. 3,
  131302. 45,
  131303. 2,
  131304. 46,
  131305. 1,
  131306. 47,
  131307. 0,
  131308. 48,
  131309. };
  131310. static long _vq_lengthlist__44c8_s_p9_2[] = {
  131311. 2, 4, 4, 4, 5, 5, 5, 5, 6, 6, 6, 6, 6, 6, 6, 6,
  131312. 6, 6, 6, 6, 6, 6, 6, 7, 7, 7, 7, 7, 7, 7, 7, 7,
  131313. 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7,
  131314. 7,
  131315. };
  131316. static float _vq_quantthresh__44c8_s_p9_2[] = {
  131317. -23.5, -22.5, -21.5, -20.5, -19.5, -18.5, -17.5, -16.5,
  131318. -15.5, -14.5, -13.5, -12.5, -11.5, -10.5, -9.5, -8.5,
  131319. -7.5, -6.5, -5.5, -4.5, -3.5, -2.5, -1.5, -0.5,
  131320. 0.5, 1.5, 2.5, 3.5, 4.5, 5.5, 6.5, 7.5,
  131321. 8.5, 9.5, 10.5, 11.5, 12.5, 13.5, 14.5, 15.5,
  131322. 16.5, 17.5, 18.5, 19.5, 20.5, 21.5, 22.5, 23.5,
  131323. };
  131324. static long _vq_quantmap__44c8_s_p9_2[] = {
  131325. 47, 45, 43, 41, 39, 37, 35, 33,
  131326. 31, 29, 27, 25, 23, 21, 19, 17,
  131327. 15, 13, 11, 9, 7, 5, 3, 1,
  131328. 0, 2, 4, 6, 8, 10, 12, 14,
  131329. 16, 18, 20, 22, 24, 26, 28, 30,
  131330. 32, 34, 36, 38, 40, 42, 44, 46,
  131331. 48,
  131332. };
  131333. static encode_aux_threshmatch _vq_auxt__44c8_s_p9_2 = {
  131334. _vq_quantthresh__44c8_s_p9_2,
  131335. _vq_quantmap__44c8_s_p9_2,
  131336. 49,
  131337. 49
  131338. };
  131339. static static_codebook _44c8_s_p9_2 = {
  131340. 1, 49,
  131341. _vq_lengthlist__44c8_s_p9_2,
  131342. 1, -526909440, 1611661312, 6, 0,
  131343. _vq_quantlist__44c8_s_p9_2,
  131344. NULL,
  131345. &_vq_auxt__44c8_s_p9_2,
  131346. NULL,
  131347. 0
  131348. };
  131349. static long _huff_lengthlist__44c8_s_short[] = {
  131350. 4,11,13,14,15,15,18,17,19,17, 5, 6, 8, 9,10,10,
  131351. 12,15,19,19, 6, 6, 6, 6, 8, 8,11,14,18,19, 8, 6,
  131352. 5, 4, 6, 7,10,13,16,17, 9, 7, 6, 5, 6, 7, 9,12,
  131353. 15,19,10, 8, 7, 6, 6, 6, 7, 9,13,15,12,10, 9, 8,
  131354. 7, 6, 4, 5,10,15,13,13,11, 8, 6, 6, 4, 2, 7,12,
  131355. 17,15,16,10, 8, 8, 7, 6, 9,12,19,18,17,13,11,10,
  131356. 10, 9,11,14,
  131357. };
  131358. static static_codebook _huff_book__44c8_s_short = {
  131359. 2, 100,
  131360. _huff_lengthlist__44c8_s_short,
  131361. 0, 0, 0, 0, 0,
  131362. NULL,
  131363. NULL,
  131364. NULL,
  131365. NULL,
  131366. 0
  131367. };
  131368. static long _huff_lengthlist__44c9_s_long[] = {
  131369. 3, 8,12,14,15,15,15,13,15,15, 6, 5, 8,10,12,12,
  131370. 13,12,14,13,10, 6, 5, 6, 8, 9,11,11,13,13,13, 8,
  131371. 5, 4, 5, 6, 8,10,11,13,14,10, 7, 5, 4, 5, 7, 9,
  131372. 11,12,13,11, 8, 6, 5, 4, 5, 7, 9,11,12,11,10, 8,
  131373. 7, 5, 4, 5, 9,10,13,13,11,10, 8, 6, 5, 4, 7, 9,
  131374. 15,14,13,12,10, 9, 8, 7, 8, 9,12,12,14,13,12,11,
  131375. 10, 9, 8, 9,
  131376. };
  131377. static static_codebook _huff_book__44c9_s_long = {
  131378. 2, 100,
  131379. _huff_lengthlist__44c9_s_long,
  131380. 0, 0, 0, 0, 0,
  131381. NULL,
  131382. NULL,
  131383. NULL,
  131384. NULL,
  131385. 0
  131386. };
  131387. static long _vq_quantlist__44c9_s_p1_0[] = {
  131388. 1,
  131389. 0,
  131390. 2,
  131391. };
  131392. static long _vq_lengthlist__44c9_s_p1_0[] = {
  131393. 1, 5, 5, 0, 5, 5, 0, 5, 5, 6, 8, 8, 0, 9, 8, 0,
  131394. 9, 8, 6, 8, 8, 0, 8, 9, 0, 8, 9, 0, 0, 0, 0, 0,
  131395. 0, 0, 0, 0, 5, 8, 8, 0, 7, 7, 0, 8, 8, 5, 8, 8,
  131396. 0, 7, 8, 0, 8, 8, 0, 0, 0, 0, 0, 0, 0, 0, 0, 5,
  131397. 9, 8, 0, 8, 8, 0, 7, 7, 5, 8, 9, 0, 8, 8, 0, 7,
  131398. 7,
  131399. };
  131400. static float _vq_quantthresh__44c9_s_p1_0[] = {
  131401. -0.5, 0.5,
  131402. };
  131403. static long _vq_quantmap__44c9_s_p1_0[] = {
  131404. 1, 0, 2,
  131405. };
  131406. static encode_aux_threshmatch _vq_auxt__44c9_s_p1_0 = {
  131407. _vq_quantthresh__44c9_s_p1_0,
  131408. _vq_quantmap__44c9_s_p1_0,
  131409. 3,
  131410. 3
  131411. };
  131412. static static_codebook _44c9_s_p1_0 = {
  131413. 4, 81,
  131414. _vq_lengthlist__44c9_s_p1_0,
  131415. 1, -535822336, 1611661312, 2, 0,
  131416. _vq_quantlist__44c9_s_p1_0,
  131417. NULL,
  131418. &_vq_auxt__44c9_s_p1_0,
  131419. NULL,
  131420. 0
  131421. };
  131422. static long _vq_quantlist__44c9_s_p2_0[] = {
  131423. 2,
  131424. 1,
  131425. 3,
  131426. 0,
  131427. 4,
  131428. };
  131429. static long _vq_lengthlist__44c9_s_p2_0[] = {
  131430. 3, 5, 5, 8, 8, 0, 5, 5, 8, 8, 0, 5, 5, 8, 8, 0,
  131431. 7, 7, 9, 9, 0, 0, 0, 9, 9, 6, 7, 7, 9, 8, 0, 8,
  131432. 8, 9, 9, 0, 8, 7, 9, 9, 0, 9,10,10,10, 0, 0, 0,
  131433. 11,10, 6, 7, 7, 8, 9, 0, 8, 8, 9, 9, 0, 7, 8, 9,
  131434. 9, 0,10, 9,11,10, 0, 0, 0,10,10, 8, 9, 8,10,10,
  131435. 0,10,10,12,11, 0,10,10,11,11, 0,12,13,13,13, 0,
  131436. 0, 0,13,12, 8, 8, 9,10,10, 0,10,10,11,12, 0,10,
  131437. 10,11,11, 0,13,12,13,13, 0, 0, 0,13,13, 0, 0, 0,
  131438. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131439. 0, 0, 0, 0, 0, 0, 6, 8, 7,10,10, 0, 7, 7,10, 9,
  131440. 0, 7, 7,10,10, 0, 9, 9,10,10, 0, 0, 0,10,10, 6,
  131441. 7, 8,10,10, 0, 7, 7, 9,10, 0, 7, 7,10,10, 0, 9,
  131442. 9,10,10, 0, 0, 0,10,10, 8, 9, 9,11,11, 0,10,10,
  131443. 11,11, 0,10,10,11,11, 0,12,12,12,12, 0, 0, 0,12,
  131444. 12, 8, 9,10,11,11, 0, 9,10,11,11, 0,10,10,11,11,
  131445. 0,12,12,12,12, 0, 0, 0,12,12, 0, 0, 0, 0, 0, 0,
  131446. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131447. 0, 0, 0, 5, 8, 7,10,10, 0, 7, 7,10,10, 0, 7, 7,
  131448. 10, 9, 0, 9, 9,10,10, 0, 0, 0,10,10, 6, 7, 8,10,
  131449. 10, 0, 7, 7,10,10, 0, 7, 7, 9,10, 0, 9, 9,10,10,
  131450. 0, 0, 0,10,10, 8,10, 9,12,11, 0,10,10,12,11, 0,
  131451. 10, 9,11,11, 0,11,12,12,12, 0, 0, 0,12,12, 8, 9,
  131452. 10,11,12, 0,10,10,11,11, 0, 9,10,11,11, 0,12,11,
  131453. 12,12, 0, 0, 0,12,12, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131454. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131455. 7,10, 9,12,12, 0, 9, 9,12,11, 0, 9, 9,11,11, 0,
  131456. 10,10,12,11, 0, 0, 0,11,12, 7, 9,10,12,12, 0, 9,
  131457. 9,11,12, 0, 9, 9,11,11, 0,10,10,11,12, 0, 0, 0,
  131458. 11,11, 9,11,10,13,12, 0,10,10,12,12, 0,10,10,12,
  131459. 12, 0,11,11,12,12, 0, 0, 0,13,12, 9,10,11,12,13,
  131460. 0,10,10,12,12, 0,10,10,12,12, 0,11,12,12,12, 0,
  131461. 0, 0,12,13, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131462. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131463. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131464. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131465. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 9,
  131466. 11,10,13,13, 0,10,10,12,12, 0,10,10,12,12, 0,11,
  131467. 12,12,12, 0, 0, 0,12,12, 9,10,11,13,13, 0,10,10,
  131468. 12,12, 0,10,10,12,12, 0,12,11,13,12, 0, 0, 0,12,
  131469. 12,
  131470. };
  131471. static float _vq_quantthresh__44c9_s_p2_0[] = {
  131472. -1.5, -0.5, 0.5, 1.5,
  131473. };
  131474. static long _vq_quantmap__44c9_s_p2_0[] = {
  131475. 3, 1, 0, 2, 4,
  131476. };
  131477. static encode_aux_threshmatch _vq_auxt__44c9_s_p2_0 = {
  131478. _vq_quantthresh__44c9_s_p2_0,
  131479. _vq_quantmap__44c9_s_p2_0,
  131480. 5,
  131481. 5
  131482. };
  131483. static static_codebook _44c9_s_p2_0 = {
  131484. 4, 625,
  131485. _vq_lengthlist__44c9_s_p2_0,
  131486. 1, -533725184, 1611661312, 3, 0,
  131487. _vq_quantlist__44c9_s_p2_0,
  131488. NULL,
  131489. &_vq_auxt__44c9_s_p2_0,
  131490. NULL,
  131491. 0
  131492. };
  131493. static long _vq_quantlist__44c9_s_p3_0[] = {
  131494. 4,
  131495. 3,
  131496. 5,
  131497. 2,
  131498. 6,
  131499. 1,
  131500. 7,
  131501. 0,
  131502. 8,
  131503. };
  131504. static long _vq_lengthlist__44c9_s_p3_0[] = {
  131505. 3, 4, 4, 5, 5, 6, 6, 8, 8, 0, 4, 4, 5, 5, 6, 7,
  131506. 8, 8, 0, 4, 4, 5, 5, 7, 7, 8, 8, 0, 5, 5, 6, 6,
  131507. 7, 7, 9, 9, 0, 0, 0, 6, 6, 7, 7, 9, 9, 0, 0, 0,
  131508. 7, 7, 8, 8, 9, 9, 0, 0, 0, 7, 7, 8, 8, 9, 9, 0,
  131509. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131510. 0,
  131511. };
  131512. static float _vq_quantthresh__44c9_s_p3_0[] = {
  131513. -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5, 3.5,
  131514. };
  131515. static long _vq_quantmap__44c9_s_p3_0[] = {
  131516. 7, 5, 3, 1, 0, 2, 4, 6,
  131517. 8,
  131518. };
  131519. static encode_aux_threshmatch _vq_auxt__44c9_s_p3_0 = {
  131520. _vq_quantthresh__44c9_s_p3_0,
  131521. _vq_quantmap__44c9_s_p3_0,
  131522. 9,
  131523. 9
  131524. };
  131525. static static_codebook _44c9_s_p3_0 = {
  131526. 2, 81,
  131527. _vq_lengthlist__44c9_s_p3_0,
  131528. 1, -531628032, 1611661312, 4, 0,
  131529. _vq_quantlist__44c9_s_p3_0,
  131530. NULL,
  131531. &_vq_auxt__44c9_s_p3_0,
  131532. NULL,
  131533. 0
  131534. };
  131535. static long _vq_quantlist__44c9_s_p4_0[] = {
  131536. 8,
  131537. 7,
  131538. 9,
  131539. 6,
  131540. 10,
  131541. 5,
  131542. 11,
  131543. 4,
  131544. 12,
  131545. 3,
  131546. 13,
  131547. 2,
  131548. 14,
  131549. 1,
  131550. 15,
  131551. 0,
  131552. 16,
  131553. };
  131554. static long _vq_lengthlist__44c9_s_p4_0[] = {
  131555. 3, 4, 4, 5, 5, 6, 6, 7, 7, 8, 8, 9, 9,10,10,10,
  131556. 10, 0, 5, 4, 5, 5, 7, 7, 8, 8, 8, 8, 9, 9,10,10,
  131557. 11,11, 0, 5, 5, 6, 6, 7, 7, 8, 8, 8, 8, 9, 9,10,
  131558. 10,11,11, 0, 6, 5, 6, 6, 7, 7, 8, 8, 9, 9,10,10,
  131559. 11,11,11,12, 0, 0, 0, 6, 6, 7, 7, 8, 8, 9, 9,10,
  131560. 10,11,11,12,12, 0, 0, 0, 7, 7, 7, 7, 9, 9, 9, 9,
  131561. 10,10,11,11,12,12, 0, 0, 0, 7, 7, 7, 8, 9, 9, 9,
  131562. 9,10,10,11,11,12,12, 0, 0, 0, 7, 7, 8, 8, 9, 9,
  131563. 10,10,11,11,12,12,13,13, 0, 0, 0, 0, 0, 8, 8, 9,
  131564. 9,10,10,11,11,12,12,12,12, 0, 0, 0, 0, 0, 0, 0,
  131565. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131566. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131567. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131568. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131569. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131570. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131571. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131572. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131573. 0,
  131574. };
  131575. static float _vq_quantthresh__44c9_s_p4_0[] = {
  131576. -7.5, -6.5, -5.5, -4.5, -3.5, -2.5, -1.5, -0.5,
  131577. 0.5, 1.5, 2.5, 3.5, 4.5, 5.5, 6.5, 7.5,
  131578. };
  131579. static long _vq_quantmap__44c9_s_p4_0[] = {
  131580. 15, 13, 11, 9, 7, 5, 3, 1,
  131581. 0, 2, 4, 6, 8, 10, 12, 14,
  131582. 16,
  131583. };
  131584. static encode_aux_threshmatch _vq_auxt__44c9_s_p4_0 = {
  131585. _vq_quantthresh__44c9_s_p4_0,
  131586. _vq_quantmap__44c9_s_p4_0,
  131587. 17,
  131588. 17
  131589. };
  131590. static static_codebook _44c9_s_p4_0 = {
  131591. 2, 289,
  131592. _vq_lengthlist__44c9_s_p4_0,
  131593. 1, -529530880, 1611661312, 5, 0,
  131594. _vq_quantlist__44c9_s_p4_0,
  131595. NULL,
  131596. &_vq_auxt__44c9_s_p4_0,
  131597. NULL,
  131598. 0
  131599. };
  131600. static long _vq_quantlist__44c9_s_p5_0[] = {
  131601. 1,
  131602. 0,
  131603. 2,
  131604. };
  131605. static long _vq_lengthlist__44c9_s_p5_0[] = {
  131606. 1, 4, 4, 5, 7, 7, 6, 7, 7, 4, 7, 6, 9,10,10,10,
  131607. 10, 9, 4, 6, 7, 9,10,10,10, 9,10, 5, 9, 9, 9,11,
  131608. 11,10,11,11, 7,10, 9,11,12,11,12,12,12, 7, 9,10,
  131609. 11,11,12,12,12,12, 6,10,10,10,12,12,10,12,11, 7,
  131610. 10,10,11,12,12,11,12,12, 7,10,10,11,12,12,12,12,
  131611. 12,
  131612. };
  131613. static float _vq_quantthresh__44c9_s_p5_0[] = {
  131614. -5.5, 5.5,
  131615. };
  131616. static long _vq_quantmap__44c9_s_p5_0[] = {
  131617. 1, 0, 2,
  131618. };
  131619. static encode_aux_threshmatch _vq_auxt__44c9_s_p5_0 = {
  131620. _vq_quantthresh__44c9_s_p5_0,
  131621. _vq_quantmap__44c9_s_p5_0,
  131622. 3,
  131623. 3
  131624. };
  131625. static static_codebook _44c9_s_p5_0 = {
  131626. 4, 81,
  131627. _vq_lengthlist__44c9_s_p5_0,
  131628. 1, -529137664, 1618345984, 2, 0,
  131629. _vq_quantlist__44c9_s_p5_0,
  131630. NULL,
  131631. &_vq_auxt__44c9_s_p5_0,
  131632. NULL,
  131633. 0
  131634. };
  131635. static long _vq_quantlist__44c9_s_p5_1[] = {
  131636. 5,
  131637. 4,
  131638. 6,
  131639. 3,
  131640. 7,
  131641. 2,
  131642. 8,
  131643. 1,
  131644. 9,
  131645. 0,
  131646. 10,
  131647. };
  131648. static long _vq_lengthlist__44c9_s_p5_1[] = {
  131649. 4, 5, 5, 6, 6, 7, 7, 7, 7, 7, 7,11, 5, 5, 6, 6,
  131650. 7, 7, 7, 7, 8, 8,11, 5, 5, 6, 6, 7, 7, 7, 7, 8,
  131651. 8,11, 5, 5, 6, 6, 7, 7, 8, 8, 8, 8,11,11,11, 6,
  131652. 6, 7, 7, 7, 8, 8, 8,11,11,11, 6, 6, 7, 7, 7, 8,
  131653. 8, 8,11,11,11, 6, 6, 7, 7, 7, 7, 8, 8,11,11,11,
  131654. 7, 7, 7, 7, 7, 7, 8, 8,11,11,11,10,10, 7, 7, 7,
  131655. 7, 8, 8,11,11,11,11,11, 7, 7, 7, 7, 7, 7,11,11,
  131656. 11,11,11, 7, 7, 7, 7, 7, 7,
  131657. };
  131658. static float _vq_quantthresh__44c9_s_p5_1[] = {
  131659. -4.5, -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5,
  131660. 3.5, 4.5,
  131661. };
  131662. static long _vq_quantmap__44c9_s_p5_1[] = {
  131663. 9, 7, 5, 3, 1, 0, 2, 4,
  131664. 6, 8, 10,
  131665. };
  131666. static encode_aux_threshmatch _vq_auxt__44c9_s_p5_1 = {
  131667. _vq_quantthresh__44c9_s_p5_1,
  131668. _vq_quantmap__44c9_s_p5_1,
  131669. 11,
  131670. 11
  131671. };
  131672. static static_codebook _44c9_s_p5_1 = {
  131673. 2, 121,
  131674. _vq_lengthlist__44c9_s_p5_1,
  131675. 1, -531365888, 1611661312, 4, 0,
  131676. _vq_quantlist__44c9_s_p5_1,
  131677. NULL,
  131678. &_vq_auxt__44c9_s_p5_1,
  131679. NULL,
  131680. 0
  131681. };
  131682. static long _vq_quantlist__44c9_s_p6_0[] = {
  131683. 6,
  131684. 5,
  131685. 7,
  131686. 4,
  131687. 8,
  131688. 3,
  131689. 9,
  131690. 2,
  131691. 10,
  131692. 1,
  131693. 11,
  131694. 0,
  131695. 12,
  131696. };
  131697. static long _vq_lengthlist__44c9_s_p6_0[] = {
  131698. 2, 4, 4, 6, 6, 7, 7, 7, 7, 8, 8, 9, 9, 5, 4, 4,
  131699. 6, 6, 8, 8, 9, 9, 9, 9,10,10, 6, 4, 4, 6, 6, 8,
  131700. 8, 9, 9, 9, 9,10,10, 0, 6, 6, 7, 7, 8, 8, 9, 9,
  131701. 10,10,11,11, 0, 6, 6, 7, 7, 8, 8, 9, 9,10,10,11,
  131702. 11, 0,10,10, 8, 8, 9, 9,10,10,11,11,12,12, 0,11,
  131703. 11, 8, 8, 9, 9,10,10,11,11,12,12, 0, 0, 0, 0, 0,
  131704. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131705. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131706. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131707. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131708. 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131709. };
  131710. static float _vq_quantthresh__44c9_s_p6_0[] = {
  131711. -27.5, -22.5, -17.5, -12.5, -7.5, -2.5, 2.5, 7.5,
  131712. 12.5, 17.5, 22.5, 27.5,
  131713. };
  131714. static long _vq_quantmap__44c9_s_p6_0[] = {
  131715. 11, 9, 7, 5, 3, 1, 0, 2,
  131716. 4, 6, 8, 10, 12,
  131717. };
  131718. static encode_aux_threshmatch _vq_auxt__44c9_s_p6_0 = {
  131719. _vq_quantthresh__44c9_s_p6_0,
  131720. _vq_quantmap__44c9_s_p6_0,
  131721. 13,
  131722. 13
  131723. };
  131724. static static_codebook _44c9_s_p6_0 = {
  131725. 2, 169,
  131726. _vq_lengthlist__44c9_s_p6_0,
  131727. 1, -526516224, 1616117760, 4, 0,
  131728. _vq_quantlist__44c9_s_p6_0,
  131729. NULL,
  131730. &_vq_auxt__44c9_s_p6_0,
  131731. NULL,
  131732. 0
  131733. };
  131734. static long _vq_quantlist__44c9_s_p6_1[] = {
  131735. 2,
  131736. 1,
  131737. 3,
  131738. 0,
  131739. 4,
  131740. };
  131741. static long _vq_lengthlist__44c9_s_p6_1[] = {
  131742. 4, 4, 4, 5, 5, 5, 4, 4, 5, 5, 5, 4, 4, 5, 5, 5,
  131743. 5, 5, 5, 5, 5, 5, 5, 5, 5,
  131744. };
  131745. static float _vq_quantthresh__44c9_s_p6_1[] = {
  131746. -1.5, -0.5, 0.5, 1.5,
  131747. };
  131748. static long _vq_quantmap__44c9_s_p6_1[] = {
  131749. 3, 1, 0, 2, 4,
  131750. };
  131751. static encode_aux_threshmatch _vq_auxt__44c9_s_p6_1 = {
  131752. _vq_quantthresh__44c9_s_p6_1,
  131753. _vq_quantmap__44c9_s_p6_1,
  131754. 5,
  131755. 5
  131756. };
  131757. static static_codebook _44c9_s_p6_1 = {
  131758. 2, 25,
  131759. _vq_lengthlist__44c9_s_p6_1,
  131760. 1, -533725184, 1611661312, 3, 0,
  131761. _vq_quantlist__44c9_s_p6_1,
  131762. NULL,
  131763. &_vq_auxt__44c9_s_p6_1,
  131764. NULL,
  131765. 0
  131766. };
  131767. static long _vq_quantlist__44c9_s_p7_0[] = {
  131768. 6,
  131769. 5,
  131770. 7,
  131771. 4,
  131772. 8,
  131773. 3,
  131774. 9,
  131775. 2,
  131776. 10,
  131777. 1,
  131778. 11,
  131779. 0,
  131780. 12,
  131781. };
  131782. static long _vq_lengthlist__44c9_s_p7_0[] = {
  131783. 2, 4, 4, 6, 6, 7, 7, 8, 8,10,10,11,11, 6, 4, 4,
  131784. 6, 6, 8, 8, 9, 9,10,10,12,12, 6, 4, 5, 6, 6, 8,
  131785. 8, 9, 9,10,10,12,12,20, 6, 6, 6, 6, 8, 8, 9,10,
  131786. 11,11,12,12,20, 6, 6, 6, 6, 8, 8,10,10,11,11,12,
  131787. 12,20,10,10, 7, 7, 9, 9,10,10,11,11,12,12,20,11,
  131788. 11, 7, 7, 9, 9,10,10,11,11,12,12,20,20,20, 9, 9,
  131789. 9, 9,11,11,12,12,13,13,20,20,20, 9, 9, 9, 9,11,
  131790. 11,12,12,13,13,20,20,20,13,13,10,10,11,11,12,13,
  131791. 13,13,20,20,20,13,13,10,10,11,11,12,13,13,13,20,
  131792. 20,20,20,19,12,12,12,12,13,13,14,15,19,19,19,19,
  131793. 19,12,12,12,12,13,13,14,14,
  131794. };
  131795. static float _vq_quantthresh__44c9_s_p7_0[] = {
  131796. -60.5, -49.5, -38.5, -27.5, -16.5, -5.5, 5.5, 16.5,
  131797. 27.5, 38.5, 49.5, 60.5,
  131798. };
  131799. static long _vq_quantmap__44c9_s_p7_0[] = {
  131800. 11, 9, 7, 5, 3, 1, 0, 2,
  131801. 4, 6, 8, 10, 12,
  131802. };
  131803. static encode_aux_threshmatch _vq_auxt__44c9_s_p7_0 = {
  131804. _vq_quantthresh__44c9_s_p7_0,
  131805. _vq_quantmap__44c9_s_p7_0,
  131806. 13,
  131807. 13
  131808. };
  131809. static static_codebook _44c9_s_p7_0 = {
  131810. 2, 169,
  131811. _vq_lengthlist__44c9_s_p7_0,
  131812. 1, -523206656, 1618345984, 4, 0,
  131813. _vq_quantlist__44c9_s_p7_0,
  131814. NULL,
  131815. &_vq_auxt__44c9_s_p7_0,
  131816. NULL,
  131817. 0
  131818. };
  131819. static long _vq_quantlist__44c9_s_p7_1[] = {
  131820. 5,
  131821. 4,
  131822. 6,
  131823. 3,
  131824. 7,
  131825. 2,
  131826. 8,
  131827. 1,
  131828. 9,
  131829. 0,
  131830. 10,
  131831. };
  131832. static long _vq_lengthlist__44c9_s_p7_1[] = {
  131833. 5, 6, 6, 6, 6, 7, 7, 7, 7, 7, 7, 7, 6, 6, 6, 6,
  131834. 7, 7, 7, 7, 7, 7, 7, 6, 6, 6, 6, 7, 7, 7, 7, 7,
  131835. 7, 8, 6, 6, 6, 6, 7, 7, 7, 7, 7, 7, 8, 8, 8, 6,
  131836. 6, 7, 7, 7, 7, 7, 7, 8, 8, 8, 7, 7, 7, 7, 7, 7,
  131837. 7, 7, 8, 8, 8, 7, 7, 7, 7, 7, 7, 7, 7, 8, 8, 8,
  131838. 7, 7, 7, 7, 7, 7, 7, 7, 8, 8, 8, 8, 8, 7, 7, 7,
  131839. 7, 7, 7, 8, 8, 8, 8, 8, 7, 7, 7, 7, 7, 7, 8, 8,
  131840. 8, 8, 8, 7, 7, 7, 7, 7, 7,
  131841. };
  131842. static float _vq_quantthresh__44c9_s_p7_1[] = {
  131843. -4.5, -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5,
  131844. 3.5, 4.5,
  131845. };
  131846. static long _vq_quantmap__44c9_s_p7_1[] = {
  131847. 9, 7, 5, 3, 1, 0, 2, 4,
  131848. 6, 8, 10,
  131849. };
  131850. static encode_aux_threshmatch _vq_auxt__44c9_s_p7_1 = {
  131851. _vq_quantthresh__44c9_s_p7_1,
  131852. _vq_quantmap__44c9_s_p7_1,
  131853. 11,
  131854. 11
  131855. };
  131856. static static_codebook _44c9_s_p7_1 = {
  131857. 2, 121,
  131858. _vq_lengthlist__44c9_s_p7_1,
  131859. 1, -531365888, 1611661312, 4, 0,
  131860. _vq_quantlist__44c9_s_p7_1,
  131861. NULL,
  131862. &_vq_auxt__44c9_s_p7_1,
  131863. NULL,
  131864. 0
  131865. };
  131866. static long _vq_quantlist__44c9_s_p8_0[] = {
  131867. 7,
  131868. 6,
  131869. 8,
  131870. 5,
  131871. 9,
  131872. 4,
  131873. 10,
  131874. 3,
  131875. 11,
  131876. 2,
  131877. 12,
  131878. 1,
  131879. 13,
  131880. 0,
  131881. 14,
  131882. };
  131883. static long _vq_lengthlist__44c9_s_p8_0[] = {
  131884. 1, 4, 4, 7, 6, 8, 8, 8, 8, 9, 9,10,10,11,10, 6,
  131885. 5, 5, 7, 7, 9, 9, 8, 9,10,10,11,11,12,12, 6, 5,
  131886. 5, 7, 7, 9, 9, 9, 9,10,10,11,11,12,12,21, 7, 8,
  131887. 8, 8, 9, 9, 9, 9,10,10,11,11,12,12,21, 8, 8, 8,
  131888. 8, 9, 9, 9, 9,10,10,11,11,12,12,21,11,12, 9, 9,
  131889. 10,10,10,10,10,11,11,12,12,12,21,12,12, 9, 8,10,
  131890. 10,10,10,11,11,12,12,13,13,21,21,21, 9, 9, 9, 9,
  131891. 11,11,11,11,12,12,12,13,21,20,20, 9, 9, 9, 9,10,
  131892. 11,11,11,12,12,13,13,20,20,20,13,13,10,10,11,11,
  131893. 12,12,13,13,13,13,20,20,20,13,13,10,10,11,11,12,
  131894. 12,13,13,13,13,20,20,20,20,20,12,12,12,12,12,12,
  131895. 13,13,14,14,20,20,20,20,20,12,12,12,11,13,12,13,
  131896. 13,14,14,20,20,20,20,20,15,16,13,12,13,13,14,13,
  131897. 14,14,20,20,20,20,20,16,15,12,12,13,12,14,13,14,
  131898. 14,
  131899. };
  131900. static float _vq_quantthresh__44c9_s_p8_0[] = {
  131901. -136.5, -115.5, -94.5, -73.5, -52.5, -31.5, -10.5, 10.5,
  131902. 31.5, 52.5, 73.5, 94.5, 115.5, 136.5,
  131903. };
  131904. static long _vq_quantmap__44c9_s_p8_0[] = {
  131905. 13, 11, 9, 7, 5, 3, 1, 0,
  131906. 2, 4, 6, 8, 10, 12, 14,
  131907. };
  131908. static encode_aux_threshmatch _vq_auxt__44c9_s_p8_0 = {
  131909. _vq_quantthresh__44c9_s_p8_0,
  131910. _vq_quantmap__44c9_s_p8_0,
  131911. 15,
  131912. 15
  131913. };
  131914. static static_codebook _44c9_s_p8_0 = {
  131915. 2, 225,
  131916. _vq_lengthlist__44c9_s_p8_0,
  131917. 1, -520986624, 1620377600, 4, 0,
  131918. _vq_quantlist__44c9_s_p8_0,
  131919. NULL,
  131920. &_vq_auxt__44c9_s_p8_0,
  131921. NULL,
  131922. 0
  131923. };
  131924. static long _vq_quantlist__44c9_s_p8_1[] = {
  131925. 10,
  131926. 9,
  131927. 11,
  131928. 8,
  131929. 12,
  131930. 7,
  131931. 13,
  131932. 6,
  131933. 14,
  131934. 5,
  131935. 15,
  131936. 4,
  131937. 16,
  131938. 3,
  131939. 17,
  131940. 2,
  131941. 18,
  131942. 1,
  131943. 19,
  131944. 0,
  131945. 20,
  131946. };
  131947. static long _vq_lengthlist__44c9_s_p8_1[] = {
  131948. 4, 6, 6, 7, 7, 7, 7, 8, 8, 8, 8, 8, 8, 8, 8, 8,
  131949. 8, 8, 8, 8, 8,10, 6, 6, 7, 7, 8, 8, 8, 8, 9, 9,
  131950. 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,10, 6, 6, 7, 7, 8,
  131951. 8, 8, 8, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,10,
  131952. 7, 7, 8, 8, 8, 8, 8, 9, 9, 9, 9, 9, 9, 9, 9, 9,
  131953. 9, 9, 9, 9,10,10,10, 8, 8, 8, 8, 9, 9, 9, 9, 9,
  131954. 9, 9, 9, 9, 9, 9, 9, 9, 9,10,10,10, 8, 8, 8, 8,
  131955. 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,10,10,
  131956. 10, 8, 8, 8, 8, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,
  131957. 9, 9, 9,10,10,10, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,
  131958. 9, 9, 9, 9, 9, 9, 9, 9,10,10,10,10,10, 9, 9, 9,
  131959. 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,10,10,10,
  131960. 10,10, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,
  131961. 9, 9,10,10,10,10,10, 9, 9, 9, 9, 9, 9, 9, 9, 9,
  131962. 9, 9, 9, 9, 9, 9, 9,10,10,10,10,10, 9, 9, 9, 9,
  131963. 9, 9, 9, 9, 9, 9, 9, 9,10, 9, 9, 9,10,10,10,10,
  131964. 10,10,10, 9, 9, 9, 9, 9, 9,10, 9, 9, 9, 9, 9, 9,
  131965. 9,10,10,10,10,10,10,10, 9, 9, 9,10,10,10,10,10,
  131966. 9, 9, 9, 9, 9, 9,10,10,10,10,10,10,10, 9, 9,10,
  131967. 9,10, 9, 9, 9, 9, 9, 9, 9, 9,10,10,10,10,10,10,
  131968. 10,10,10,10, 9, 9,10,10, 9, 9, 9, 9, 9, 9, 9, 9,
  131969. 10,10,10,10,10,10,10,10,10,10,10,10,10, 9, 9, 9,
  131970. 9, 9, 9, 9, 9,10,10,10,10,10,10,10,10,10,10,10,
  131971. 10,10, 9, 9,10, 9, 9, 9, 9, 9,10,10,10,10,10,10,
  131972. 10,10,10,10,10, 9, 9,10,10, 9, 9,10, 9, 9, 9,10,
  131973. 10,10,10,10,10,10,10,10,10,10, 9, 9,10, 9, 9, 9,
  131974. 9, 9, 9, 9,10,10,10,10,10,10,10,10,10,10,10, 9,
  131975. 9, 9, 9,10, 9, 9, 9, 9, 9,
  131976. };
  131977. static float _vq_quantthresh__44c9_s_p8_1[] = {
  131978. -9.5, -8.5, -7.5, -6.5, -5.5, -4.5, -3.5, -2.5,
  131979. -1.5, -0.5, 0.5, 1.5, 2.5, 3.5, 4.5, 5.5,
  131980. 6.5, 7.5, 8.5, 9.5,
  131981. };
  131982. static long _vq_quantmap__44c9_s_p8_1[] = {
  131983. 19, 17, 15, 13, 11, 9, 7, 5,
  131984. 3, 1, 0, 2, 4, 6, 8, 10,
  131985. 12, 14, 16, 18, 20,
  131986. };
  131987. static encode_aux_threshmatch _vq_auxt__44c9_s_p8_1 = {
  131988. _vq_quantthresh__44c9_s_p8_1,
  131989. _vq_quantmap__44c9_s_p8_1,
  131990. 21,
  131991. 21
  131992. };
  131993. static static_codebook _44c9_s_p8_1 = {
  131994. 2, 441,
  131995. _vq_lengthlist__44c9_s_p8_1,
  131996. 1, -529268736, 1611661312, 5, 0,
  131997. _vq_quantlist__44c9_s_p8_1,
  131998. NULL,
  131999. &_vq_auxt__44c9_s_p8_1,
  132000. NULL,
  132001. 0
  132002. };
  132003. static long _vq_quantlist__44c9_s_p9_0[] = {
  132004. 9,
  132005. 8,
  132006. 10,
  132007. 7,
  132008. 11,
  132009. 6,
  132010. 12,
  132011. 5,
  132012. 13,
  132013. 4,
  132014. 14,
  132015. 3,
  132016. 15,
  132017. 2,
  132018. 16,
  132019. 1,
  132020. 17,
  132021. 0,
  132022. 18,
  132023. };
  132024. static long _vq_lengthlist__44c9_s_p9_0[] = {
  132025. 1, 4, 3,12,12,12,12,12,12,12,12,12,12,12,12,12,
  132026. 12,12,12, 4, 5, 6,12,12,12,12,12,12,12,12,12,12,
  132027. 12,12,12,12,12,12, 4, 6, 6,12,12,12,12,12,12,12,
  132028. 12,12,12,12,12,12,12,12,12,12,12,11,12,12,12,12,
  132029. 12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,
  132030. 12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,
  132031. 12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,
  132032. 12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,
  132033. 12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,
  132034. 12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,
  132035. 12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,
  132036. 12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,
  132037. 12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,
  132038. 12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,
  132039. 12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,
  132040. 12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,
  132041. 12,12,12,12,12,12,12,12,12,12,11,11,11,11,11,11,
  132042. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  132043. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  132044. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  132045. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  132046. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  132047. 11,11,11,11,11,11,11,11,11,
  132048. };
  132049. static float _vq_quantthresh__44c9_s_p9_0[] = {
  132050. -7913.5, -6982.5, -6051.5, -5120.5, -4189.5, -3258.5, -2327.5, -1396.5,
  132051. -465.5, 465.5, 1396.5, 2327.5, 3258.5, 4189.5, 5120.5, 6051.5,
  132052. 6982.5, 7913.5,
  132053. };
  132054. static long _vq_quantmap__44c9_s_p9_0[] = {
  132055. 17, 15, 13, 11, 9, 7, 5, 3,
  132056. 1, 0, 2, 4, 6, 8, 10, 12,
  132057. 14, 16, 18,
  132058. };
  132059. static encode_aux_threshmatch _vq_auxt__44c9_s_p9_0 = {
  132060. _vq_quantthresh__44c9_s_p9_0,
  132061. _vq_quantmap__44c9_s_p9_0,
  132062. 19,
  132063. 19
  132064. };
  132065. static static_codebook _44c9_s_p9_0 = {
  132066. 2, 361,
  132067. _vq_lengthlist__44c9_s_p9_0,
  132068. 1, -508535424, 1631393792, 5, 0,
  132069. _vq_quantlist__44c9_s_p9_0,
  132070. NULL,
  132071. &_vq_auxt__44c9_s_p9_0,
  132072. NULL,
  132073. 0
  132074. };
  132075. static long _vq_quantlist__44c9_s_p9_1[] = {
  132076. 9,
  132077. 8,
  132078. 10,
  132079. 7,
  132080. 11,
  132081. 6,
  132082. 12,
  132083. 5,
  132084. 13,
  132085. 4,
  132086. 14,
  132087. 3,
  132088. 15,
  132089. 2,
  132090. 16,
  132091. 1,
  132092. 17,
  132093. 0,
  132094. 18,
  132095. };
  132096. static long _vq_lengthlist__44c9_s_p9_1[] = {
  132097. 1, 4, 4, 7, 7, 7, 7, 8, 7, 9, 8, 9, 9,10,10,11,
  132098. 11,11,11, 6, 5, 5, 8, 8, 9, 9, 9, 8,10, 9,11,10,
  132099. 12,12,13,12,13,13, 5, 5, 5, 8, 8, 9, 9, 9, 9,10,
  132100. 10,11,11,12,12,13,12,13,13,17, 8, 8, 9, 9, 9, 9,
  132101. 9, 9,10,10,12,11,13,12,13,13,13,13,18, 8, 8, 9,
  132102. 9, 9, 9, 9, 9,11,11,12,12,13,13,13,13,13,13,17,
  132103. 13,12, 9, 9,10,10,10,10,11,11,12,12,12,13,13,13,
  132104. 14,14,18,13,12, 9, 9,10,10,10,10,11,11,12,12,13,
  132105. 13,13,14,14,14,17,18,18,10,10,10,10,11,11,11,12,
  132106. 12,12,14,13,14,13,13,14,18,18,18,10, 9,10, 9,11,
  132107. 11,12,12,12,12,13,13,15,14,14,14,18,18,16,13,14,
  132108. 10,11,11,11,12,13,13,13,13,14,13,13,14,14,18,18,
  132109. 18,14,12,11, 9,11,10,13,12,13,13,13,14,14,14,13,
  132110. 14,18,18,17,18,18,11,12,12,12,13,13,14,13,14,14,
  132111. 13,14,14,14,18,18,18,18,17,12,10,12, 9,13,11,13,
  132112. 14,14,14,14,14,15,14,18,18,17,17,18,14,15,12,13,
  132113. 13,13,14,13,14,14,15,14,15,14,18,17,18,18,18,15,
  132114. 15,12,10,14,10,14,14,13,13,14,14,14,14,18,16,18,
  132115. 18,18,18,17,14,14,13,14,14,13,13,14,14,14,15,15,
  132116. 18,18,18,18,17,17,17,14,14,14,12,14,13,14,14,15,
  132117. 14,15,14,18,18,18,18,18,18,18,17,16,13,13,13,14,
  132118. 14,14,14,15,16,15,18,18,18,18,18,18,18,17,17,13,
  132119. 13,13,13,14,13,14,15,15,15,
  132120. };
  132121. static float _vq_quantthresh__44c9_s_p9_1[] = {
  132122. -416.5, -367.5, -318.5, -269.5, -220.5, -171.5, -122.5, -73.5,
  132123. -24.5, 24.5, 73.5, 122.5, 171.5, 220.5, 269.5, 318.5,
  132124. 367.5, 416.5,
  132125. };
  132126. static long _vq_quantmap__44c9_s_p9_1[] = {
  132127. 17, 15, 13, 11, 9, 7, 5, 3,
  132128. 1, 0, 2, 4, 6, 8, 10, 12,
  132129. 14, 16, 18,
  132130. };
  132131. static encode_aux_threshmatch _vq_auxt__44c9_s_p9_1 = {
  132132. _vq_quantthresh__44c9_s_p9_1,
  132133. _vq_quantmap__44c9_s_p9_1,
  132134. 19,
  132135. 19
  132136. };
  132137. static static_codebook _44c9_s_p9_1 = {
  132138. 2, 361,
  132139. _vq_lengthlist__44c9_s_p9_1,
  132140. 1, -518287360, 1622704128, 5, 0,
  132141. _vq_quantlist__44c9_s_p9_1,
  132142. NULL,
  132143. &_vq_auxt__44c9_s_p9_1,
  132144. NULL,
  132145. 0
  132146. };
  132147. static long _vq_quantlist__44c9_s_p9_2[] = {
  132148. 24,
  132149. 23,
  132150. 25,
  132151. 22,
  132152. 26,
  132153. 21,
  132154. 27,
  132155. 20,
  132156. 28,
  132157. 19,
  132158. 29,
  132159. 18,
  132160. 30,
  132161. 17,
  132162. 31,
  132163. 16,
  132164. 32,
  132165. 15,
  132166. 33,
  132167. 14,
  132168. 34,
  132169. 13,
  132170. 35,
  132171. 12,
  132172. 36,
  132173. 11,
  132174. 37,
  132175. 10,
  132176. 38,
  132177. 9,
  132178. 39,
  132179. 8,
  132180. 40,
  132181. 7,
  132182. 41,
  132183. 6,
  132184. 42,
  132185. 5,
  132186. 43,
  132187. 4,
  132188. 44,
  132189. 3,
  132190. 45,
  132191. 2,
  132192. 46,
  132193. 1,
  132194. 47,
  132195. 0,
  132196. 48,
  132197. };
  132198. static long _vq_lengthlist__44c9_s_p9_2[] = {
  132199. 2, 4, 4, 5, 5, 5, 5, 5, 6, 6, 6, 6, 6, 6, 6, 6,
  132200. 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 7, 7, 7, 7, 7,
  132201. 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7,
  132202. 7,
  132203. };
  132204. static float _vq_quantthresh__44c9_s_p9_2[] = {
  132205. -23.5, -22.5, -21.5, -20.5, -19.5, -18.5, -17.5, -16.5,
  132206. -15.5, -14.5, -13.5, -12.5, -11.5, -10.5, -9.5, -8.5,
  132207. -7.5, -6.5, -5.5, -4.5, -3.5, -2.5, -1.5, -0.5,
  132208. 0.5, 1.5, 2.5, 3.5, 4.5, 5.5, 6.5, 7.5,
  132209. 8.5, 9.5, 10.5, 11.5, 12.5, 13.5, 14.5, 15.5,
  132210. 16.5, 17.5, 18.5, 19.5, 20.5, 21.5, 22.5, 23.5,
  132211. };
  132212. static long _vq_quantmap__44c9_s_p9_2[] = {
  132213. 47, 45, 43, 41, 39, 37, 35, 33,
  132214. 31, 29, 27, 25, 23, 21, 19, 17,
  132215. 15, 13, 11, 9, 7, 5, 3, 1,
  132216. 0, 2, 4, 6, 8, 10, 12, 14,
  132217. 16, 18, 20, 22, 24, 26, 28, 30,
  132218. 32, 34, 36, 38, 40, 42, 44, 46,
  132219. 48,
  132220. };
  132221. static encode_aux_threshmatch _vq_auxt__44c9_s_p9_2 = {
  132222. _vq_quantthresh__44c9_s_p9_2,
  132223. _vq_quantmap__44c9_s_p9_2,
  132224. 49,
  132225. 49
  132226. };
  132227. static static_codebook _44c9_s_p9_2 = {
  132228. 1, 49,
  132229. _vq_lengthlist__44c9_s_p9_2,
  132230. 1, -526909440, 1611661312, 6, 0,
  132231. _vq_quantlist__44c9_s_p9_2,
  132232. NULL,
  132233. &_vq_auxt__44c9_s_p9_2,
  132234. NULL,
  132235. 0
  132236. };
  132237. static long _huff_lengthlist__44c9_s_short[] = {
  132238. 5,13,18,16,17,17,19,18,19,19, 5, 7,10,11,12,12,
  132239. 13,16,17,18, 6, 6, 7, 7, 9, 9,10,14,17,19, 8, 7,
  132240. 6, 5, 6, 7, 9,12,19,17, 8, 7, 7, 6, 5, 6, 8,11,
  132241. 15,19, 9, 8, 7, 6, 5, 5, 6, 8,13,15,11,10, 8, 8,
  132242. 7, 5, 4, 4,10,14,12,13,11, 9, 7, 6, 4, 2, 6,12,
  132243. 18,16,16,13, 8, 7, 7, 5, 8,13,16,17,18,15,11, 9,
  132244. 9, 8,10,13,
  132245. };
  132246. static static_codebook _huff_book__44c9_s_short = {
  132247. 2, 100,
  132248. _huff_lengthlist__44c9_s_short,
  132249. 0, 0, 0, 0, 0,
  132250. NULL,
  132251. NULL,
  132252. NULL,
  132253. NULL,
  132254. 0
  132255. };
  132256. static long _huff_lengthlist__44c0_s_long[] = {
  132257. 5, 4, 8, 9, 8, 9,10,12,15, 4, 1, 5, 5, 6, 8,11,
  132258. 12,12, 8, 5, 8, 9, 9,11,13,12,12, 9, 5, 8, 5, 7,
  132259. 9,12,13,13, 8, 6, 8, 7, 7, 9,11,11,11, 9, 7, 9,
  132260. 7, 7, 7, 7,10,12,10,10,11, 9, 8, 7, 7, 9,11,11,
  132261. 12,13,12,11, 9, 8, 9,11,13,16,16,15,15,12,10,11,
  132262. 12,
  132263. };
  132264. static static_codebook _huff_book__44c0_s_long = {
  132265. 2, 81,
  132266. _huff_lengthlist__44c0_s_long,
  132267. 0, 0, 0, 0, 0,
  132268. NULL,
  132269. NULL,
  132270. NULL,
  132271. NULL,
  132272. 0
  132273. };
  132274. static long _vq_quantlist__44c0_s_p1_0[] = {
  132275. 1,
  132276. 0,
  132277. 2,
  132278. };
  132279. static long _vq_lengthlist__44c0_s_p1_0[] = {
  132280. 1, 5, 5, 0, 0, 0, 0, 0, 0, 5, 7, 7, 0, 0, 0, 0,
  132281. 0, 0, 5, 7, 7, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132282. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132283. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132284. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132285. 0, 5, 8, 7, 0, 0, 0, 0, 0, 0, 7, 9, 9, 0, 0, 0,
  132286. 0, 0, 0, 7, 9, 9, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132287. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132288. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132289. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132290. 0, 0, 5, 7, 7, 0, 0, 0, 0, 0, 0, 7, 9, 9, 0, 0,
  132291. 0, 0, 0, 0, 7, 9, 9, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132292. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132293. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132294. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132295. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132296. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132297. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132298. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132299. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132300. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132301. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132302. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132303. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132304. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132305. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132306. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132307. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132308. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132309. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132310. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132311. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132312. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132313. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132314. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132315. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132316. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132317. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132318. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132319. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132320. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132321. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132322. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132323. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132324. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132325. 0, 0, 0, 0, 0, 0, 0, 0, 0, 5, 7, 7, 0, 0, 0, 0,
  132326. 0, 0, 8,10, 9, 0, 0, 0, 0, 0, 0, 7, 9, 9, 0, 0,
  132327. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132328. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132329. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132330. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 7, 9, 9, 0, 0, 0,
  132331. 0, 0, 0, 9,10,11, 0, 0, 0, 0, 0, 0, 9,11,10, 0,
  132332. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132333. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132334. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132335. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 7, 9, 9, 0, 0,
  132336. 0, 0, 0, 0, 9,11, 9, 0, 0, 0, 0, 0, 0, 9,10,11,
  132337. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132338. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132339. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132340. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132341. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132342. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132343. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132344. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132345. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132346. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132347. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132348. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132349. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132350. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132351. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132352. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132353. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132354. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132355. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132356. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132357. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132358. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132359. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132360. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132361. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132362. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132363. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132364. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132365. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132366. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132367. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132368. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132369. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132370. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132371. 0, 0, 5, 7, 7, 0, 0, 0, 0, 0, 0, 7, 9, 9, 0, 0,
  132372. 0, 0, 0, 0, 8, 9, 9, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132373. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132374. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132375. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132376. 0, 0, 0, 7, 9, 9, 0, 0, 0, 0, 0, 0, 9,11,10, 0,
  132377. 0, 0, 0, 0, 0, 9, 9,11, 0, 0, 0, 0, 0, 0, 0, 0,
  132378. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132379. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132380. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132381. 0, 0, 0, 0, 7, 9,10, 0, 0, 0, 0, 0, 0, 9,10,11,
  132382. 0, 0, 0, 0, 0, 0, 9,11,10, 0, 0, 0, 0, 0, 0, 0,
  132383. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132384. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132385. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132386. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132387. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132388. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132389. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132390. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132391. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132392. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132393. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132394. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132395. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132396. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132397. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132398. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132399. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132400. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132401. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132402. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132403. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132404. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132405. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132406. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132407. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132408. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132409. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132410. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132411. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132412. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132413. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132414. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132415. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132416. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132417. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132418. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132419. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132420. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132421. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132422. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132423. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132424. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132425. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132426. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132427. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132428. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132429. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132430. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132431. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132432. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132433. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132434. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132435. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132436. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132437. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132438. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132439. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132440. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132441. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132442. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132443. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132444. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132445. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132446. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132447. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132448. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132449. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132450. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132451. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132452. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132453. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132454. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132455. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132456. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132457. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132458. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132459. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132460. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132461. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132462. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132463. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132464. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132465. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132466. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132467. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132468. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132469. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132470. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132471. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132472. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132473. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132474. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132475. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132476. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132477. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132478. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132479. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132480. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132481. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132482. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132483. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132484. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132485. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132486. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132487. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132488. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132489. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132490. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132491. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132492. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132493. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132494. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132495. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132496. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132497. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132498. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132499. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132500. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132501. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132502. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132503. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132504. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132505. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132506. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132507. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132508. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132509. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132510. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132511. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132512. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132513. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132514. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132515. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132516. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132517. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132518. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132519. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132520. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132521. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132522. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132523. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132524. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132525. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132526. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132527. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132528. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132529. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132530. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132531. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132532. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132533. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132534. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132535. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132536. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132537. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132538. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132539. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132540. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132541. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132542. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132543. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132544. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132545. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132546. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132547. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132548. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132549. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132550. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132551. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132552. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132553. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132554. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132555. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132556. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132557. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132558. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132559. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132560. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132561. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132562. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132563. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132564. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132565. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132566. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132567. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132568. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132569. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132570. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132571. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132572. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132573. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132574. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132575. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132576. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132577. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132578. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132579. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132580. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132581. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132582. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132583. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132584. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132585. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132586. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132587. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132588. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132589. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132590. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132591. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132592. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132593. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132594. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132595. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132596. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132597. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132598. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132599. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132600. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132601. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132602. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132603. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132604. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132605. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132606. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132607. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132608. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132609. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132610. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132611. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132612. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132613. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132614. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132615. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132616. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132617. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132618. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132619. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132620. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132621. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132622. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132623. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132624. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132625. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132626. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132627. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132628. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132629. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132630. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132631. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132632. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132633. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132634. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132635. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132636. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132637. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132638. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132639. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132640. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132641. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132642. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132643. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132644. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132645. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132646. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132647. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132648. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132649. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132650. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132651. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132652. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132653. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132654. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132655. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132656. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132657. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132658. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132659. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132660. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132661. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132662. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132663. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132664. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132665. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132666. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132667. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132668. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132669. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132670. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132671. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132672. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132673. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132674. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132675. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132676. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132677. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132678. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 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, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132681. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132682. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132683. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132684. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132685. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132686. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 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, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132689. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132690. 0,
  132691. };
  132692. static float _vq_quantthresh__44c0_s_p1_0[] = {
  132693. -0.5, 0.5,
  132694. };
  132695. static long _vq_quantmap__44c0_s_p1_0[] = {
  132696. 1, 0, 2,
  132697. };
  132698. static encode_aux_threshmatch _vq_auxt__44c0_s_p1_0 = {
  132699. _vq_quantthresh__44c0_s_p1_0,
  132700. _vq_quantmap__44c0_s_p1_0,
  132701. 3,
  132702. 3
  132703. };
  132704. static static_codebook _44c0_s_p1_0 = {
  132705. 8, 6561,
  132706. _vq_lengthlist__44c0_s_p1_0,
  132707. 1, -535822336, 1611661312, 2, 0,
  132708. _vq_quantlist__44c0_s_p1_0,
  132709. NULL,
  132710. &_vq_auxt__44c0_s_p1_0,
  132711. NULL,
  132712. 0
  132713. };
  132714. static long _vq_quantlist__44c0_s_p2_0[] = {
  132715. 2,
  132716. 1,
  132717. 3,
  132718. 0,
  132719. 4,
  132720. };
  132721. static long _vq_lengthlist__44c0_s_p2_0[] = {
  132722. 1, 4, 4, 6, 6, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132723. 0, 0, 0, 0, 0, 0, 0, 0, 0, 4, 5, 5, 7, 6, 0, 0,
  132724. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132725. 0, 0, 4, 5, 6, 7, 7, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132726. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 6, 7, 7, 9, 9,
  132727. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132728. 0, 0, 0, 0, 6, 7, 7, 9, 9, 0, 0, 0, 0, 0, 0, 0,
  132729. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132730. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132731. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132732. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132733. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132734. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132735. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132736. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132737. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132738. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132739. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132740. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132741. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132742. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132743. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132744. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132745. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132746. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132747. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132748. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132749. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132750. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132751. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132752. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132753. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132754. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132755. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132756. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132757. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132758. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132759. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132760. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132761. 0,
  132762. };
  132763. static float _vq_quantthresh__44c0_s_p2_0[] = {
  132764. -1.5, -0.5, 0.5, 1.5,
  132765. };
  132766. static long _vq_quantmap__44c0_s_p2_0[] = {
  132767. 3, 1, 0, 2, 4,
  132768. };
  132769. static encode_aux_threshmatch _vq_auxt__44c0_s_p2_0 = {
  132770. _vq_quantthresh__44c0_s_p2_0,
  132771. _vq_quantmap__44c0_s_p2_0,
  132772. 5,
  132773. 5
  132774. };
  132775. static static_codebook _44c0_s_p2_0 = {
  132776. 4, 625,
  132777. _vq_lengthlist__44c0_s_p2_0,
  132778. 1, -533725184, 1611661312, 3, 0,
  132779. _vq_quantlist__44c0_s_p2_0,
  132780. NULL,
  132781. &_vq_auxt__44c0_s_p2_0,
  132782. NULL,
  132783. 0
  132784. };
  132785. static long _vq_quantlist__44c0_s_p3_0[] = {
  132786. 4,
  132787. 3,
  132788. 5,
  132789. 2,
  132790. 6,
  132791. 1,
  132792. 7,
  132793. 0,
  132794. 8,
  132795. };
  132796. static long _vq_lengthlist__44c0_s_p3_0[] = {
  132797. 1, 3, 2, 8, 7, 0, 0, 0, 0, 0, 0, 0, 6, 6, 0, 0,
  132798. 0, 0, 0, 0, 0, 6, 6, 0, 0, 0, 0, 0, 0, 0, 7, 7,
  132799. 0, 0, 0, 0, 0, 0, 0, 7, 7, 0, 0, 0, 0, 0, 0, 0,
  132800. 8, 8, 0, 0, 0, 0, 0, 0, 0, 8, 8, 0, 0, 0, 0, 0,
  132801. 0, 0, 9, 9, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132802. 0,
  132803. };
  132804. static float _vq_quantthresh__44c0_s_p3_0[] = {
  132805. -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5, 3.5,
  132806. };
  132807. static long _vq_quantmap__44c0_s_p3_0[] = {
  132808. 7, 5, 3, 1, 0, 2, 4, 6,
  132809. 8,
  132810. };
  132811. static encode_aux_threshmatch _vq_auxt__44c0_s_p3_0 = {
  132812. _vq_quantthresh__44c0_s_p3_0,
  132813. _vq_quantmap__44c0_s_p3_0,
  132814. 9,
  132815. 9
  132816. };
  132817. static static_codebook _44c0_s_p3_0 = {
  132818. 2, 81,
  132819. _vq_lengthlist__44c0_s_p3_0,
  132820. 1, -531628032, 1611661312, 4, 0,
  132821. _vq_quantlist__44c0_s_p3_0,
  132822. NULL,
  132823. &_vq_auxt__44c0_s_p3_0,
  132824. NULL,
  132825. 0
  132826. };
  132827. static long _vq_quantlist__44c0_s_p4_0[] = {
  132828. 4,
  132829. 3,
  132830. 5,
  132831. 2,
  132832. 6,
  132833. 1,
  132834. 7,
  132835. 0,
  132836. 8,
  132837. };
  132838. static long _vq_lengthlist__44c0_s_p4_0[] = {
  132839. 1, 3, 3, 6, 6, 6, 6, 8, 8, 0, 0, 0, 7, 7, 7, 7,
  132840. 9, 9, 0, 0, 0, 7, 7, 7, 7, 9, 9, 0, 0, 0, 7, 7,
  132841. 7, 8, 9, 9, 0, 0, 0, 7, 7, 7, 7, 9, 9, 0, 0, 0,
  132842. 9, 9, 8, 8,10,10, 0, 0, 0, 8, 9, 8, 8,10,10, 0,
  132843. 0, 0,10,10, 9, 9,10,10, 0, 0, 0, 0, 0, 9, 9,10,
  132844. 10,
  132845. };
  132846. static float _vq_quantthresh__44c0_s_p4_0[] = {
  132847. -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5, 3.5,
  132848. };
  132849. static long _vq_quantmap__44c0_s_p4_0[] = {
  132850. 7, 5, 3, 1, 0, 2, 4, 6,
  132851. 8,
  132852. };
  132853. static encode_aux_threshmatch _vq_auxt__44c0_s_p4_0 = {
  132854. _vq_quantthresh__44c0_s_p4_0,
  132855. _vq_quantmap__44c0_s_p4_0,
  132856. 9,
  132857. 9
  132858. };
  132859. static static_codebook _44c0_s_p4_0 = {
  132860. 2, 81,
  132861. _vq_lengthlist__44c0_s_p4_0,
  132862. 1, -531628032, 1611661312, 4, 0,
  132863. _vq_quantlist__44c0_s_p4_0,
  132864. NULL,
  132865. &_vq_auxt__44c0_s_p4_0,
  132866. NULL,
  132867. 0
  132868. };
  132869. static long _vq_quantlist__44c0_s_p5_0[] = {
  132870. 8,
  132871. 7,
  132872. 9,
  132873. 6,
  132874. 10,
  132875. 5,
  132876. 11,
  132877. 4,
  132878. 12,
  132879. 3,
  132880. 13,
  132881. 2,
  132882. 14,
  132883. 1,
  132884. 15,
  132885. 0,
  132886. 16,
  132887. };
  132888. static long _vq_lengthlist__44c0_s_p5_0[] = {
  132889. 1, 4, 3, 6, 6, 8, 7, 8, 8, 8, 8, 9, 9,10,10,11,
  132890. 11, 0, 0, 0, 7, 7, 8, 8, 9, 9, 9, 9, 9,10,10,10,
  132891. 11,11, 0, 0, 0, 7, 7, 8, 8, 9, 9, 9, 9,10,10,10,
  132892. 10,11,11, 0, 0, 0, 7, 7, 8, 8, 9, 9, 9, 9,10,10,
  132893. 11,11,11,11, 0, 0, 0, 7, 7, 8, 8, 9, 9, 9, 9,10,
  132894. 10,11,11,11,11, 0, 0, 0, 8, 8, 9, 9, 9, 9,10,10,
  132895. 10,10,11,11,12,12, 0, 0, 0, 8, 8, 9, 9, 9, 9,10,
  132896. 10,10,10,11,11,12,12, 0, 0, 0, 9, 9, 9, 9,10,10,
  132897. 10,10,11,11,11,12,12,12, 0, 0, 0, 0, 0, 9, 9,10,
  132898. 10,10,10,11,11,11,11,12,12, 0, 0, 0, 0, 0, 9, 9,
  132899. 10,10,10,10,11,11,12,12,13,13, 0, 0, 0, 0, 0, 9,
  132900. 9,10,10,10,10,11,11,12,12,13,13, 0, 0, 0, 0, 0,
  132901. 10,10,11,11,11,11,11,12,12,12,13,13, 0, 0, 0, 0,
  132902. 0, 0, 0,11,10,11,11,11,11,12,12,13,13, 0, 0, 0,
  132903. 0, 0, 0, 0,11,11,12,11,12,12,12,12,13,13, 0, 0,
  132904. 0, 0, 0, 0, 0,11,11,11,12,12,12,12,13,13,13, 0,
  132905. 0, 0, 0, 0, 0, 0,12,12,12,12,12,13,13,13,14,14,
  132906. 0, 0, 0, 0, 0, 0, 0, 0, 0,12,12,12,12,13,13,14,
  132907. 14,
  132908. };
  132909. static float _vq_quantthresh__44c0_s_p5_0[] = {
  132910. -7.5, -6.5, -5.5, -4.5, -3.5, -2.5, -1.5, -0.5,
  132911. 0.5, 1.5, 2.5, 3.5, 4.5, 5.5, 6.5, 7.5,
  132912. };
  132913. static long _vq_quantmap__44c0_s_p5_0[] = {
  132914. 15, 13, 11, 9, 7, 5, 3, 1,
  132915. 0, 2, 4, 6, 8, 10, 12, 14,
  132916. 16,
  132917. };
  132918. static encode_aux_threshmatch _vq_auxt__44c0_s_p5_0 = {
  132919. _vq_quantthresh__44c0_s_p5_0,
  132920. _vq_quantmap__44c0_s_p5_0,
  132921. 17,
  132922. 17
  132923. };
  132924. static static_codebook _44c0_s_p5_0 = {
  132925. 2, 289,
  132926. _vq_lengthlist__44c0_s_p5_0,
  132927. 1, -529530880, 1611661312, 5, 0,
  132928. _vq_quantlist__44c0_s_p5_0,
  132929. NULL,
  132930. &_vq_auxt__44c0_s_p5_0,
  132931. NULL,
  132932. 0
  132933. };
  132934. static long _vq_quantlist__44c0_s_p6_0[] = {
  132935. 1,
  132936. 0,
  132937. 2,
  132938. };
  132939. static long _vq_lengthlist__44c0_s_p6_0[] = {
  132940. 1, 4, 4, 7, 6, 6, 7, 6, 6, 4, 7, 7,10, 9, 9,10,
  132941. 9, 9, 4, 6, 7,10, 9, 9,11, 9, 9, 7,10,10,11,11,
  132942. 11,12,10,11, 6, 9, 9,11,10,11,11,10,10, 6, 9, 9,
  132943. 11,10,11,11,10,10, 7,11,10,12,11,11,11,11,11, 7,
  132944. 9, 9,10,10,10,11,11,10, 6, 9, 9,11,10,10,11,10,
  132945. 10,
  132946. };
  132947. static float _vq_quantthresh__44c0_s_p6_0[] = {
  132948. -5.5, 5.5,
  132949. };
  132950. static long _vq_quantmap__44c0_s_p6_0[] = {
  132951. 1, 0, 2,
  132952. };
  132953. static encode_aux_threshmatch _vq_auxt__44c0_s_p6_0 = {
  132954. _vq_quantthresh__44c0_s_p6_0,
  132955. _vq_quantmap__44c0_s_p6_0,
  132956. 3,
  132957. 3
  132958. };
  132959. static static_codebook _44c0_s_p6_0 = {
  132960. 4, 81,
  132961. _vq_lengthlist__44c0_s_p6_0,
  132962. 1, -529137664, 1618345984, 2, 0,
  132963. _vq_quantlist__44c0_s_p6_0,
  132964. NULL,
  132965. &_vq_auxt__44c0_s_p6_0,
  132966. NULL,
  132967. 0
  132968. };
  132969. static long _vq_quantlist__44c0_s_p6_1[] = {
  132970. 5,
  132971. 4,
  132972. 6,
  132973. 3,
  132974. 7,
  132975. 2,
  132976. 8,
  132977. 1,
  132978. 9,
  132979. 0,
  132980. 10,
  132981. };
  132982. static long _vq_lengthlist__44c0_s_p6_1[] = {
  132983. 2, 3, 3, 6, 6, 7, 7, 7, 7, 7, 8,10,10,10, 6, 6,
  132984. 7, 7, 8, 8, 8, 8,10,10,10, 6, 6, 7, 7, 8, 8, 8,
  132985. 8,10,10,10, 7, 7, 7, 7, 8, 8, 8, 8,10,10,10, 7,
  132986. 7, 7, 7, 8, 8, 8, 8,10,10,10, 8, 7, 8, 8, 8, 8,
  132987. 8, 8,10,10,10, 7, 7, 8, 8, 8, 8, 8, 8,10,10,10,
  132988. 8, 8, 8, 8, 8, 8, 8, 8,10,10,10,10,10, 8, 8, 8,
  132989. 8, 8, 8,10,10,10,10,10, 9, 9, 8, 8, 8, 8,10,10,
  132990. 10,10,10, 8, 8, 8, 8, 8, 8,
  132991. };
  132992. static float _vq_quantthresh__44c0_s_p6_1[] = {
  132993. -4.5, -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5,
  132994. 3.5, 4.5,
  132995. };
  132996. static long _vq_quantmap__44c0_s_p6_1[] = {
  132997. 9, 7, 5, 3, 1, 0, 2, 4,
  132998. 6, 8, 10,
  132999. };
  133000. static encode_aux_threshmatch _vq_auxt__44c0_s_p6_1 = {
  133001. _vq_quantthresh__44c0_s_p6_1,
  133002. _vq_quantmap__44c0_s_p6_1,
  133003. 11,
  133004. 11
  133005. };
  133006. static static_codebook _44c0_s_p6_1 = {
  133007. 2, 121,
  133008. _vq_lengthlist__44c0_s_p6_1,
  133009. 1, -531365888, 1611661312, 4, 0,
  133010. _vq_quantlist__44c0_s_p6_1,
  133011. NULL,
  133012. &_vq_auxt__44c0_s_p6_1,
  133013. NULL,
  133014. 0
  133015. };
  133016. static long _vq_quantlist__44c0_s_p7_0[] = {
  133017. 6,
  133018. 5,
  133019. 7,
  133020. 4,
  133021. 8,
  133022. 3,
  133023. 9,
  133024. 2,
  133025. 10,
  133026. 1,
  133027. 11,
  133028. 0,
  133029. 12,
  133030. };
  133031. static long _vq_lengthlist__44c0_s_p7_0[] = {
  133032. 1, 4, 4, 6, 6, 7, 7, 7, 7, 8, 8, 9, 9, 7, 5, 5,
  133033. 7, 7, 8, 8, 8, 8, 9, 9,10,10, 7, 5, 6, 7, 7, 8,
  133034. 8, 8, 8, 9, 9,10,10, 0, 8, 8, 8, 8, 9, 9, 9, 9,
  133035. 10,10,11,11, 0, 8, 8, 8, 8, 9, 9, 9, 9,10,10,11,
  133036. 11, 0,12,12, 9, 9,10,10,10,10,11,11,11,11, 0,13,
  133037. 13, 9, 9, 9, 9,10,10,11,11,11,12, 0, 0, 0,10,10,
  133038. 10,10,11,11,11,11,12,12, 0, 0, 0,10,10, 9, 9,11,
  133039. 11,11,12,12,12, 0, 0, 0,13,13,10,10,11,11,12,12,
  133040. 13,13, 0, 0, 0,14,14,10,10,11,11,12,12,13,13, 0,
  133041. 0, 0, 0, 0,11,11,11,11,13,12,13,13, 0, 0, 0, 0,
  133042. 0,12,12,11,11,12,12,13,13,
  133043. };
  133044. static float _vq_quantthresh__44c0_s_p7_0[] = {
  133045. -27.5, -22.5, -17.5, -12.5, -7.5, -2.5, 2.5, 7.5,
  133046. 12.5, 17.5, 22.5, 27.5,
  133047. };
  133048. static long _vq_quantmap__44c0_s_p7_0[] = {
  133049. 11, 9, 7, 5, 3, 1, 0, 2,
  133050. 4, 6, 8, 10, 12,
  133051. };
  133052. static encode_aux_threshmatch _vq_auxt__44c0_s_p7_0 = {
  133053. _vq_quantthresh__44c0_s_p7_0,
  133054. _vq_quantmap__44c0_s_p7_0,
  133055. 13,
  133056. 13
  133057. };
  133058. static static_codebook _44c0_s_p7_0 = {
  133059. 2, 169,
  133060. _vq_lengthlist__44c0_s_p7_0,
  133061. 1, -526516224, 1616117760, 4, 0,
  133062. _vq_quantlist__44c0_s_p7_0,
  133063. NULL,
  133064. &_vq_auxt__44c0_s_p7_0,
  133065. NULL,
  133066. 0
  133067. };
  133068. static long _vq_quantlist__44c0_s_p7_1[] = {
  133069. 2,
  133070. 1,
  133071. 3,
  133072. 0,
  133073. 4,
  133074. };
  133075. static long _vq_lengthlist__44c0_s_p7_1[] = {
  133076. 2, 3, 3, 5, 5, 6, 6, 6, 5, 5, 6, 6, 6, 5, 5, 6,
  133077. 6, 6, 5, 5, 6, 6, 6, 5, 5,
  133078. };
  133079. static float _vq_quantthresh__44c0_s_p7_1[] = {
  133080. -1.5, -0.5, 0.5, 1.5,
  133081. };
  133082. static long _vq_quantmap__44c0_s_p7_1[] = {
  133083. 3, 1, 0, 2, 4,
  133084. };
  133085. static encode_aux_threshmatch _vq_auxt__44c0_s_p7_1 = {
  133086. _vq_quantthresh__44c0_s_p7_1,
  133087. _vq_quantmap__44c0_s_p7_1,
  133088. 5,
  133089. 5
  133090. };
  133091. static static_codebook _44c0_s_p7_1 = {
  133092. 2, 25,
  133093. _vq_lengthlist__44c0_s_p7_1,
  133094. 1, -533725184, 1611661312, 3, 0,
  133095. _vq_quantlist__44c0_s_p7_1,
  133096. NULL,
  133097. &_vq_auxt__44c0_s_p7_1,
  133098. NULL,
  133099. 0
  133100. };
  133101. static long _vq_quantlist__44c0_s_p8_0[] = {
  133102. 2,
  133103. 1,
  133104. 3,
  133105. 0,
  133106. 4,
  133107. };
  133108. static long _vq_lengthlist__44c0_s_p8_0[] = {
  133109. 1, 5, 5,10,10, 6, 9, 8,10,10, 6,10, 9,10,10,10,
  133110. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  133111. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  133112. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  133113. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  133114. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  133115. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  133116. 10,10,10,10,10,10,10,10,10,10,10,10,10, 8,10,10,
  133117. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  133118. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  133119. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  133120. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  133121. 10,10,10,10,10,10,10,10,11,11,11,11,11,11,11,11,
  133122. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  133123. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  133124. 11,11,11,11,11,11,11,11,11,11,10,11,11,11,11,11,
  133125. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  133126. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  133127. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  133128. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  133129. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  133130. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  133131. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  133132. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  133133. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  133134. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  133135. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  133136. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  133137. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  133138. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  133139. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  133140. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  133141. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  133142. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  133143. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  133144. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  133145. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  133146. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  133147. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  133148. 11,
  133149. };
  133150. static float _vq_quantthresh__44c0_s_p8_0[] = {
  133151. -331.5, -110.5, 110.5, 331.5,
  133152. };
  133153. static long _vq_quantmap__44c0_s_p8_0[] = {
  133154. 3, 1, 0, 2, 4,
  133155. };
  133156. static encode_aux_threshmatch _vq_auxt__44c0_s_p8_0 = {
  133157. _vq_quantthresh__44c0_s_p8_0,
  133158. _vq_quantmap__44c0_s_p8_0,
  133159. 5,
  133160. 5
  133161. };
  133162. static static_codebook _44c0_s_p8_0 = {
  133163. 4, 625,
  133164. _vq_lengthlist__44c0_s_p8_0,
  133165. 1, -518283264, 1627103232, 3, 0,
  133166. _vq_quantlist__44c0_s_p8_0,
  133167. NULL,
  133168. &_vq_auxt__44c0_s_p8_0,
  133169. NULL,
  133170. 0
  133171. };
  133172. static long _vq_quantlist__44c0_s_p8_1[] = {
  133173. 6,
  133174. 5,
  133175. 7,
  133176. 4,
  133177. 8,
  133178. 3,
  133179. 9,
  133180. 2,
  133181. 10,
  133182. 1,
  133183. 11,
  133184. 0,
  133185. 12,
  133186. };
  133187. static long _vq_lengthlist__44c0_s_p8_1[] = {
  133188. 1, 4, 4, 6, 6, 7, 7, 9, 9,11,12,13,12, 6, 5, 5,
  133189. 7, 7, 8, 8,10, 9,12,12,12,12, 6, 5, 5, 7, 7, 8,
  133190. 8,10, 9,12,11,11,13,16, 7, 7, 8, 8, 9, 9,10,10,
  133191. 12,12,13,12,16, 7, 7, 8, 7, 9, 9,10,10,11,12,12,
  133192. 13,16,10,10, 8, 8,10,10,11,12,12,12,13,13,16,11,
  133193. 10, 8, 7,11,10,11,11,12,11,13,13,16,16,16,10,10,
  133194. 10,10,11,11,13,12,13,13,16,16,16,11, 9,11, 9,15,
  133195. 13,12,13,13,13,16,16,16,15,13,11,11,12,13,12,12,
  133196. 14,13,16,16,16,14,13,11,11,13,12,14,13,13,13,16,
  133197. 16,16,16,16,13,13,13,12,14,13,14,14,16,16,16,16,
  133198. 16,13,13,12,12,14,14,15,13,
  133199. };
  133200. static float _vq_quantthresh__44c0_s_p8_1[] = {
  133201. -93.5, -76.5, -59.5, -42.5, -25.5, -8.5, 8.5, 25.5,
  133202. 42.5, 59.5, 76.5, 93.5,
  133203. };
  133204. static long _vq_quantmap__44c0_s_p8_1[] = {
  133205. 11, 9, 7, 5, 3, 1, 0, 2,
  133206. 4, 6, 8, 10, 12,
  133207. };
  133208. static encode_aux_threshmatch _vq_auxt__44c0_s_p8_1 = {
  133209. _vq_quantthresh__44c0_s_p8_1,
  133210. _vq_quantmap__44c0_s_p8_1,
  133211. 13,
  133212. 13
  133213. };
  133214. static static_codebook _44c0_s_p8_1 = {
  133215. 2, 169,
  133216. _vq_lengthlist__44c0_s_p8_1,
  133217. 1, -522616832, 1620115456, 4, 0,
  133218. _vq_quantlist__44c0_s_p8_1,
  133219. NULL,
  133220. &_vq_auxt__44c0_s_p8_1,
  133221. NULL,
  133222. 0
  133223. };
  133224. static long _vq_quantlist__44c0_s_p8_2[] = {
  133225. 8,
  133226. 7,
  133227. 9,
  133228. 6,
  133229. 10,
  133230. 5,
  133231. 11,
  133232. 4,
  133233. 12,
  133234. 3,
  133235. 13,
  133236. 2,
  133237. 14,
  133238. 1,
  133239. 15,
  133240. 0,
  133241. 16,
  133242. };
  133243. static long _vq_lengthlist__44c0_s_p8_2[] = {
  133244. 2, 4, 4, 6, 6, 7, 7, 7, 7, 8, 8, 8, 8, 8, 8, 8,
  133245. 8,10,10,10, 7, 7, 7, 8, 8, 8, 9, 9, 9, 9, 9, 9,
  133246. 9, 9,10,10,10, 7, 7, 7, 7, 8, 8, 9, 9, 9, 9, 9,
  133247. 9, 9, 9,10,10,10, 7, 7, 8, 8, 8, 8, 9, 9, 9, 9,
  133248. 9,10, 9, 9,10,10,10, 7, 7, 8, 8, 9, 8, 9, 9, 9,
  133249. 9,10, 9, 9,10,10,10,10, 8, 8, 8, 8, 9, 8, 9, 9,
  133250. 9, 9, 9,10, 9,10,10,10,10, 7, 7, 8, 8, 9, 9, 9,
  133251. 9, 9, 9,10, 9,10,10,10,10,10, 8, 8, 8, 9, 9, 9,
  133252. 9, 9, 9, 9,10,10,10, 9,11,10,10,10,10, 8, 8, 9,
  133253. 9, 9, 9, 9,10, 9, 9, 9,10,10,10,10,11,11, 9, 9,
  133254. 9, 9, 9, 9, 9, 9,10, 9, 9,10,11,10,10,11,11, 9,
  133255. 9, 9, 9, 9, 9, 9, 9, 9, 9,10, 9,11,11,10,11,11,
  133256. 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,10, 9,11,10,10,11,
  133257. 11,11,11, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,10,10,10,
  133258. 11,11,11,11, 9,10, 9,10, 9, 9, 9, 9,10, 9,10,11,
  133259. 10,11,10,10,10,10,10, 9, 9, 9,10, 9, 9, 9,10,11,
  133260. 11,10,11,11,10,11,10,10,10, 9, 9, 9, 9,10, 9, 9,
  133261. 10,11,10,11,11,11,11,10,11,10,10, 9,10, 9, 9, 9,
  133262. 10,
  133263. };
  133264. static float _vq_quantthresh__44c0_s_p8_2[] = {
  133265. -7.5, -6.5, -5.5, -4.5, -3.5, -2.5, -1.5, -0.5,
  133266. 0.5, 1.5, 2.5, 3.5, 4.5, 5.5, 6.5, 7.5,
  133267. };
  133268. static long _vq_quantmap__44c0_s_p8_2[] = {
  133269. 15, 13, 11, 9, 7, 5, 3, 1,
  133270. 0, 2, 4, 6, 8, 10, 12, 14,
  133271. 16,
  133272. };
  133273. static encode_aux_threshmatch _vq_auxt__44c0_s_p8_2 = {
  133274. _vq_quantthresh__44c0_s_p8_2,
  133275. _vq_quantmap__44c0_s_p8_2,
  133276. 17,
  133277. 17
  133278. };
  133279. static static_codebook _44c0_s_p8_2 = {
  133280. 2, 289,
  133281. _vq_lengthlist__44c0_s_p8_2,
  133282. 1, -529530880, 1611661312, 5, 0,
  133283. _vq_quantlist__44c0_s_p8_2,
  133284. NULL,
  133285. &_vq_auxt__44c0_s_p8_2,
  133286. NULL,
  133287. 0
  133288. };
  133289. static long _huff_lengthlist__44c0_s_short[] = {
  133290. 9, 8,12,11,12,13,14,14,16, 6, 1, 5, 6, 6, 9,12,
  133291. 14,17, 9, 4, 5, 9, 7, 9,13,15,16, 8, 5, 8, 6, 8,
  133292. 10,13,17,17, 9, 6, 7, 7, 8, 9,13,15,17,11, 8, 9,
  133293. 9, 9,10,12,16,16,13, 7, 8, 7, 7, 9,12,14,15,13,
  133294. 6, 7, 5, 5, 7,10,13,13,14, 7, 8, 5, 6, 7, 9,10,
  133295. 12,
  133296. };
  133297. static static_codebook _huff_book__44c0_s_short = {
  133298. 2, 81,
  133299. _huff_lengthlist__44c0_s_short,
  133300. 0, 0, 0, 0, 0,
  133301. NULL,
  133302. NULL,
  133303. NULL,
  133304. NULL,
  133305. 0
  133306. };
  133307. static long _huff_lengthlist__44c0_sm_long[] = {
  133308. 5, 4, 9,10, 9,10,11,12,13, 4, 1, 5, 7, 7, 9,11,
  133309. 12,14, 8, 5, 7, 9, 8,10,13,13,13,10, 7, 9, 4, 6,
  133310. 7,10,12,14, 9, 6, 7, 6, 6, 7,10,12,12, 9, 8, 9,
  133311. 7, 6, 7, 8,11,12,11,11,11, 9, 8, 7, 8,10,12,12,
  133312. 13,14,12,11, 9, 9, 9,12,12,17,17,15,16,12,10,11,
  133313. 13,
  133314. };
  133315. static static_codebook _huff_book__44c0_sm_long = {
  133316. 2, 81,
  133317. _huff_lengthlist__44c0_sm_long,
  133318. 0, 0, 0, 0, 0,
  133319. NULL,
  133320. NULL,
  133321. NULL,
  133322. NULL,
  133323. 0
  133324. };
  133325. static long _vq_quantlist__44c0_sm_p1_0[] = {
  133326. 1,
  133327. 0,
  133328. 2,
  133329. };
  133330. static long _vq_lengthlist__44c0_sm_p1_0[] = {
  133331. 1, 5, 5, 0, 0, 0, 0, 0, 0, 5, 7, 7, 0, 0, 0, 0,
  133332. 0, 0, 5, 7, 7, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133333. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133334. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133335. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133336. 0, 5, 8, 7, 0, 0, 0, 0, 0, 0, 7, 9, 9, 0, 0, 0,
  133337. 0, 0, 0, 7, 8, 9, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133338. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133339. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133340. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133341. 0, 0, 5, 7, 7, 0, 0, 0, 0, 0, 0, 7, 9, 8, 0, 0,
  133342. 0, 0, 0, 0, 7, 9, 9, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133343. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133344. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133345. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133346. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133347. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133348. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133349. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133350. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133351. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133352. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133353. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133354. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133355. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133356. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133357. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133358. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133359. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133360. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133361. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133362. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133363. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133364. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133365. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133366. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133367. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133368. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133369. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133370. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133371. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133372. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133373. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133374. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133375. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133376. 0, 0, 0, 0, 0, 0, 0, 0, 0, 5, 8, 7, 0, 0, 0, 0,
  133377. 0, 0, 8, 9, 9, 0, 0, 0, 0, 0, 0, 8, 9, 9, 0, 0,
  133378. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133379. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133380. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133381. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 7, 9, 9, 0, 0, 0,
  133382. 0, 0, 0, 9,10,10, 0, 0, 0, 0, 0, 0, 9,10,10, 0,
  133383. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133384. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133385. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133386. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 7, 9, 9, 0, 0,
  133387. 0, 0, 0, 0, 8,10, 9, 0, 0, 0, 0, 0, 0, 9,10,10,
  133388. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133389. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133390. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133391. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133392. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133393. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133394. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133395. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133396. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133397. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133398. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133399. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133400. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133401. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133402. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133403. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133404. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133405. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133406. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133407. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133408. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133409. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133410. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133411. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133412. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133413. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133414. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133415. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133416. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133417. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133418. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133419. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133420. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133421. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133422. 0, 0, 5, 7, 8, 0, 0, 0, 0, 0, 0, 7, 9, 9, 0, 0,
  133423. 0, 0, 0, 0, 8, 9, 9, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133424. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133425. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133426. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133427. 0, 0, 0, 7, 9, 9, 0, 0, 0, 0, 0, 0, 9,10,10, 0,
  133428. 0, 0, 0, 0, 0, 9, 9,10, 0, 0, 0, 0, 0, 0, 0, 0,
  133429. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133430. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133431. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133432. 0, 0, 0, 0, 7, 9, 9, 0, 0, 0, 0, 0, 0, 9,10,10,
  133433. 0, 0, 0, 0, 0, 0, 9,10,10, 0, 0, 0, 0, 0, 0, 0,
  133434. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133435. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133436. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133437. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133438. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133439. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133440. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133441. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133442. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133443. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133444. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133445. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133446. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133447. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133448. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133449. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133450. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133451. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133452. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133453. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133454. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133455. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133456. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133457. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133458. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133459. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133460. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133461. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133462. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133463. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133464. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133465. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133466. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133467. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133468. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133469. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133470. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133471. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133472. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133473. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133474. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133475. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133476. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133477. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133478. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133479. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133480. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133481. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133482. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133483. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133484. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133485. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133486. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133487. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133488. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133489. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133490. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133491. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133492. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133493. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133494. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133495. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133496. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133497. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133498. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133499. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133500. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133501. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133502. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133503. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133504. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133505. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133506. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133507. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133508. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133509. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133510. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133511. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133512. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133513. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133514. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133515. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133516. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133517. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133518. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133519. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133520. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133521. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133522. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133523. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133524. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133525. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133526. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 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, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133529. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133530. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133531. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133532. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133533. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133534. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 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, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133537. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133538. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133539. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133540. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133541. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133542. 0, 0, 0, 0, 0, 0, 0, 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. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133545. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133546. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133547. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133548. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133549. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133550. 0, 0, 0, 0, 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, 0,
  133555. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133556. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133557. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133558. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133559. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133560. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133561. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133562. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133563. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133564. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133565. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133566. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133567. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133568. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133569. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133570. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133571. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133572. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133573. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133574. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133575. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133576. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133577. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133578. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133579. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133580. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133581. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133582. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133583. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133584. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133585. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133586. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133587. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133588. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133589. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133590. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133591. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133592. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133593. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133594. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133595. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133596. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133597. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133598. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133599. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133600. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133601. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133602. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133603. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133604. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133605. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133606. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133607. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133608. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133609. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133610. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133611. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133612. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133613. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133614. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133615. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133616. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133617. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133618. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133619. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133620. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133621. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133622. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133623. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133624. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133625. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133626. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133627. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133628. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133629. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133630. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133631. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133632. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133633. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133634. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133635. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133636. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133637. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133638. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133639. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133640. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133641. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133642. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133643. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133644. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133645. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133646. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133647. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133648. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133649. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133650. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133651. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133652. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133653. 0, 0, 0, 0, 0, 0, 0, 0, 0, 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, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133663. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133664. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133665. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133666. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133667. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133668. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133669. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133670. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133671. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133672. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133673. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133674. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133675. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133676. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133677. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133678. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133679. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133680. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133681. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133682. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133683. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133684. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133685. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133686. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133687. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133688. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133689. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133690. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133691. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133692. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133693. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133694. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133695. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133696. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133697. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133698. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133699. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133700. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133701. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133702. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133703. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133704. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133705. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133706. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133707. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133708. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133709. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133710. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133711. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133712. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133713. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133714. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133715. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133716. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133717. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133718. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133719. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133720. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133721. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133722. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133723. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133724. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133725. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133726. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133727. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133728. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133729. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133730. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133731. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133732. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133733. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133734. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133735. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133736. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133737. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133738. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133739. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133740. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133741. 0,
  133742. };
  133743. static float _vq_quantthresh__44c0_sm_p1_0[] = {
  133744. -0.5, 0.5,
  133745. };
  133746. static long _vq_quantmap__44c0_sm_p1_0[] = {
  133747. 1, 0, 2,
  133748. };
  133749. static encode_aux_threshmatch _vq_auxt__44c0_sm_p1_0 = {
  133750. _vq_quantthresh__44c0_sm_p1_0,
  133751. _vq_quantmap__44c0_sm_p1_0,
  133752. 3,
  133753. 3
  133754. };
  133755. static static_codebook _44c0_sm_p1_0 = {
  133756. 8, 6561,
  133757. _vq_lengthlist__44c0_sm_p1_0,
  133758. 1, -535822336, 1611661312, 2, 0,
  133759. _vq_quantlist__44c0_sm_p1_0,
  133760. NULL,
  133761. &_vq_auxt__44c0_sm_p1_0,
  133762. NULL,
  133763. 0
  133764. };
  133765. static long _vq_quantlist__44c0_sm_p2_0[] = {
  133766. 2,
  133767. 1,
  133768. 3,
  133769. 0,
  133770. 4,
  133771. };
  133772. static long _vq_lengthlist__44c0_sm_p2_0[] = {
  133773. 1, 4, 4, 6, 6, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133774. 0, 0, 0, 0, 0, 0, 0, 0, 0, 4, 5, 5, 7, 7, 0, 0,
  133775. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133776. 0, 0, 4, 5, 5, 7, 7, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133777. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 6, 7, 7, 9, 9,
  133778. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133779. 0, 0, 0, 0, 7, 7, 7, 9, 9, 0, 0, 0, 0, 0, 0, 0,
  133780. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133781. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133782. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133783. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133784. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133785. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133786. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133787. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133788. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133789. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133790. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133791. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133792. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 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, 0, 0, 0, 0, 0, 0, 0,
  133798. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133799. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133800. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133801. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133802. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133803. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133804. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133805. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133806. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133807. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133808. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133809. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133810. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133811. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133812. 0,
  133813. };
  133814. static float _vq_quantthresh__44c0_sm_p2_0[] = {
  133815. -1.5, -0.5, 0.5, 1.5,
  133816. };
  133817. static long _vq_quantmap__44c0_sm_p2_0[] = {
  133818. 3, 1, 0, 2, 4,
  133819. };
  133820. static encode_aux_threshmatch _vq_auxt__44c0_sm_p2_0 = {
  133821. _vq_quantthresh__44c0_sm_p2_0,
  133822. _vq_quantmap__44c0_sm_p2_0,
  133823. 5,
  133824. 5
  133825. };
  133826. static static_codebook _44c0_sm_p2_0 = {
  133827. 4, 625,
  133828. _vq_lengthlist__44c0_sm_p2_0,
  133829. 1, -533725184, 1611661312, 3, 0,
  133830. _vq_quantlist__44c0_sm_p2_0,
  133831. NULL,
  133832. &_vq_auxt__44c0_sm_p2_0,
  133833. NULL,
  133834. 0
  133835. };
  133836. static long _vq_quantlist__44c0_sm_p3_0[] = {
  133837. 4,
  133838. 3,
  133839. 5,
  133840. 2,
  133841. 6,
  133842. 1,
  133843. 7,
  133844. 0,
  133845. 8,
  133846. };
  133847. static long _vq_lengthlist__44c0_sm_p3_0[] = {
  133848. 1, 3, 3, 7, 7, 0, 0, 0, 0, 0, 5, 4, 7, 7, 0, 0,
  133849. 0, 0, 0, 5, 5, 7, 7, 0, 0, 0, 0, 0, 6, 7, 8, 8,
  133850. 0, 0, 0, 0, 0, 0, 0, 8, 8, 0, 0, 0, 0, 0, 0, 0,
  133851. 9,10, 0, 0, 0, 0, 0, 0, 0, 9, 9, 0, 0, 0, 0, 0,
  133852. 0, 0,11,11, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133853. 0,
  133854. };
  133855. static float _vq_quantthresh__44c0_sm_p3_0[] = {
  133856. -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5, 3.5,
  133857. };
  133858. static long _vq_quantmap__44c0_sm_p3_0[] = {
  133859. 7, 5, 3, 1, 0, 2, 4, 6,
  133860. 8,
  133861. };
  133862. static encode_aux_threshmatch _vq_auxt__44c0_sm_p3_0 = {
  133863. _vq_quantthresh__44c0_sm_p3_0,
  133864. _vq_quantmap__44c0_sm_p3_0,
  133865. 9,
  133866. 9
  133867. };
  133868. static static_codebook _44c0_sm_p3_0 = {
  133869. 2, 81,
  133870. _vq_lengthlist__44c0_sm_p3_0,
  133871. 1, -531628032, 1611661312, 4, 0,
  133872. _vq_quantlist__44c0_sm_p3_0,
  133873. NULL,
  133874. &_vq_auxt__44c0_sm_p3_0,
  133875. NULL,
  133876. 0
  133877. };
  133878. static long _vq_quantlist__44c0_sm_p4_0[] = {
  133879. 4,
  133880. 3,
  133881. 5,
  133882. 2,
  133883. 6,
  133884. 1,
  133885. 7,
  133886. 0,
  133887. 8,
  133888. };
  133889. static long _vq_lengthlist__44c0_sm_p4_0[] = {
  133890. 1, 4, 3, 6, 6, 7, 7, 9, 9, 0, 5, 5, 7, 7, 8, 7,
  133891. 9, 9, 0, 5, 5, 7, 7, 8, 8, 9, 9, 0, 7, 7, 8, 8,
  133892. 8, 8,10,10, 0, 0, 0, 8, 8, 8, 8,10,10, 0, 0, 0,
  133893. 9, 9, 9, 9,11,11, 0, 0, 0, 9, 9, 9, 9,11,11, 0,
  133894. 0, 0,10,10,10,10,11,11, 0, 0, 0, 0, 0, 9, 9,11,
  133895. 11,
  133896. };
  133897. static float _vq_quantthresh__44c0_sm_p4_0[] = {
  133898. -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5, 3.5,
  133899. };
  133900. static long _vq_quantmap__44c0_sm_p4_0[] = {
  133901. 7, 5, 3, 1, 0, 2, 4, 6,
  133902. 8,
  133903. };
  133904. static encode_aux_threshmatch _vq_auxt__44c0_sm_p4_0 = {
  133905. _vq_quantthresh__44c0_sm_p4_0,
  133906. _vq_quantmap__44c0_sm_p4_0,
  133907. 9,
  133908. 9
  133909. };
  133910. static static_codebook _44c0_sm_p4_0 = {
  133911. 2, 81,
  133912. _vq_lengthlist__44c0_sm_p4_0,
  133913. 1, -531628032, 1611661312, 4, 0,
  133914. _vq_quantlist__44c0_sm_p4_0,
  133915. NULL,
  133916. &_vq_auxt__44c0_sm_p4_0,
  133917. NULL,
  133918. 0
  133919. };
  133920. static long _vq_quantlist__44c0_sm_p5_0[] = {
  133921. 8,
  133922. 7,
  133923. 9,
  133924. 6,
  133925. 10,
  133926. 5,
  133927. 11,
  133928. 4,
  133929. 12,
  133930. 3,
  133931. 13,
  133932. 2,
  133933. 14,
  133934. 1,
  133935. 15,
  133936. 0,
  133937. 16,
  133938. };
  133939. static long _vq_lengthlist__44c0_sm_p5_0[] = {
  133940. 1, 4, 4, 6, 6, 8, 8, 8, 8, 8, 8, 9, 9,10,10,11,
  133941. 11, 0, 6, 6, 7, 7, 8, 8, 9, 9, 9, 9,10,10,10,11,
  133942. 11,11, 0, 5, 6, 7, 7, 8, 8, 9, 9, 9, 9,10,10,10,
  133943. 11,11,11, 0, 7, 7, 8, 8, 8, 8, 9, 9, 9, 9,10,10,
  133944. 11,11,12,12, 0, 0, 0, 8, 8, 8, 8, 9, 9, 9, 9,10,
  133945. 10,11,11,12,12, 0, 0, 0, 8, 8, 9, 9,10,10,10,10,
  133946. 11,11,11,11,12,12, 0, 0, 0, 8, 8, 9, 9,10,10,10,
  133947. 10,11,11,11,11,12,12, 0, 0, 0, 9, 9, 9, 9,10,10,
  133948. 10,10,11,11,12,12,12,13, 0, 0, 0, 0, 0, 9, 9,10,
  133949. 10,10,10,11,11,12,12,13,13, 0, 0, 0, 0, 0, 9, 9,
  133950. 10,10,11,11,11,11,12,12,13,13, 0, 0, 0, 0, 0, 9,
  133951. 9,10,10,11,10,11,11,12,12,13,13, 0, 0, 0, 0, 0,
  133952. 10,10,10,10,11,11,12,12,12,13,13,13, 0, 0, 0, 0,
  133953. 0, 0, 0,10,10,11,11,12,12,12,13,13,13, 0, 0, 0,
  133954. 0, 0, 0, 0,11,11,12,12,12,12,13,13,14,14, 0, 0,
  133955. 0, 0, 0, 0, 0,11,11,12,11,12,12,13,13,13,13, 0,
  133956. 0, 0, 0, 0, 0, 0,12,12,12,12,13,13,13,13,14,14,
  133957. 0, 0, 0, 0, 0, 0, 0, 0, 0,12,12,12,12,13,13,14,
  133958. 14,
  133959. };
  133960. static float _vq_quantthresh__44c0_sm_p5_0[] = {
  133961. -7.5, -6.5, -5.5, -4.5, -3.5, -2.5, -1.5, -0.5,
  133962. 0.5, 1.5, 2.5, 3.5, 4.5, 5.5, 6.5, 7.5,
  133963. };
  133964. static long _vq_quantmap__44c0_sm_p5_0[] = {
  133965. 15, 13, 11, 9, 7, 5, 3, 1,
  133966. 0, 2, 4, 6, 8, 10, 12, 14,
  133967. 16,
  133968. };
  133969. static encode_aux_threshmatch _vq_auxt__44c0_sm_p5_0 = {
  133970. _vq_quantthresh__44c0_sm_p5_0,
  133971. _vq_quantmap__44c0_sm_p5_0,
  133972. 17,
  133973. 17
  133974. };
  133975. static static_codebook _44c0_sm_p5_0 = {
  133976. 2, 289,
  133977. _vq_lengthlist__44c0_sm_p5_0,
  133978. 1, -529530880, 1611661312, 5, 0,
  133979. _vq_quantlist__44c0_sm_p5_0,
  133980. NULL,
  133981. &_vq_auxt__44c0_sm_p5_0,
  133982. NULL,
  133983. 0
  133984. };
  133985. static long _vq_quantlist__44c0_sm_p6_0[] = {
  133986. 1,
  133987. 0,
  133988. 2,
  133989. };
  133990. static long _vq_lengthlist__44c0_sm_p6_0[] = {
  133991. 1, 4, 4, 7, 6, 6, 7, 6, 6, 4, 7, 7,10, 9, 9,11,
  133992. 9, 9, 4, 7, 7,10, 9, 9,11, 9, 9, 7,10,10,10,11,
  133993. 11,11,10,10, 6, 9, 9,11,11,10,11,10,10, 6, 9, 9,
  133994. 11,10,11,11,10,10, 7,11,10,11,11,11,11,11,11, 6,
  133995. 9, 9,11,10,10,11,11,10, 6, 9, 9,11,10,10,11,10,
  133996. 11,
  133997. };
  133998. static float _vq_quantthresh__44c0_sm_p6_0[] = {
  133999. -5.5, 5.5,
  134000. };
  134001. static long _vq_quantmap__44c0_sm_p6_0[] = {
  134002. 1, 0, 2,
  134003. };
  134004. static encode_aux_threshmatch _vq_auxt__44c0_sm_p6_0 = {
  134005. _vq_quantthresh__44c0_sm_p6_0,
  134006. _vq_quantmap__44c0_sm_p6_0,
  134007. 3,
  134008. 3
  134009. };
  134010. static static_codebook _44c0_sm_p6_0 = {
  134011. 4, 81,
  134012. _vq_lengthlist__44c0_sm_p6_0,
  134013. 1, -529137664, 1618345984, 2, 0,
  134014. _vq_quantlist__44c0_sm_p6_0,
  134015. NULL,
  134016. &_vq_auxt__44c0_sm_p6_0,
  134017. NULL,
  134018. 0
  134019. };
  134020. static long _vq_quantlist__44c0_sm_p6_1[] = {
  134021. 5,
  134022. 4,
  134023. 6,
  134024. 3,
  134025. 7,
  134026. 2,
  134027. 8,
  134028. 1,
  134029. 9,
  134030. 0,
  134031. 10,
  134032. };
  134033. static long _vq_lengthlist__44c0_sm_p6_1[] = {
  134034. 2, 4, 4, 6, 6, 7, 7, 7, 7, 7, 8, 9, 5, 5, 6, 6,
  134035. 7, 7, 8, 8, 8, 8, 9, 5, 5, 6, 6, 7, 7, 8, 8, 8,
  134036. 8,10, 7, 7, 7, 7, 7, 7, 8, 8, 8, 8,10,10,10, 7,
  134037. 7, 7, 7, 8, 8, 8, 8,10,10,10, 8, 8, 8, 8, 8, 8,
  134038. 8, 8,10,10,10, 8, 8, 8, 8, 8, 8, 8, 8,10,10,10,
  134039. 8, 8, 8, 8, 8, 8, 8, 8,10,10,10,10,10, 8, 8, 8,
  134040. 8, 8, 8,10,10,10,10,10, 9, 9, 8, 8, 8, 8,10,10,
  134041. 10,10,10, 8, 8, 8, 8, 8, 8,
  134042. };
  134043. static float _vq_quantthresh__44c0_sm_p6_1[] = {
  134044. -4.5, -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5,
  134045. 3.5, 4.5,
  134046. };
  134047. static long _vq_quantmap__44c0_sm_p6_1[] = {
  134048. 9, 7, 5, 3, 1, 0, 2, 4,
  134049. 6, 8, 10,
  134050. };
  134051. static encode_aux_threshmatch _vq_auxt__44c0_sm_p6_1 = {
  134052. _vq_quantthresh__44c0_sm_p6_1,
  134053. _vq_quantmap__44c0_sm_p6_1,
  134054. 11,
  134055. 11
  134056. };
  134057. static static_codebook _44c0_sm_p6_1 = {
  134058. 2, 121,
  134059. _vq_lengthlist__44c0_sm_p6_1,
  134060. 1, -531365888, 1611661312, 4, 0,
  134061. _vq_quantlist__44c0_sm_p6_1,
  134062. NULL,
  134063. &_vq_auxt__44c0_sm_p6_1,
  134064. NULL,
  134065. 0
  134066. };
  134067. static long _vq_quantlist__44c0_sm_p7_0[] = {
  134068. 6,
  134069. 5,
  134070. 7,
  134071. 4,
  134072. 8,
  134073. 3,
  134074. 9,
  134075. 2,
  134076. 10,
  134077. 1,
  134078. 11,
  134079. 0,
  134080. 12,
  134081. };
  134082. static long _vq_lengthlist__44c0_sm_p7_0[] = {
  134083. 1, 4, 4, 6, 6, 7, 7, 7, 7, 8, 8, 9, 9, 7, 5, 5,
  134084. 7, 7, 8, 8, 8, 8, 9, 9,10,10, 7, 6, 5, 7, 7, 8,
  134085. 8, 8, 8, 9, 9,10,10, 0, 8, 8, 8, 8, 9, 9, 9, 9,
  134086. 10,10,11,11, 0, 8, 8, 8, 8, 9, 9, 9, 9,10,10,11,
  134087. 11, 0,12,12, 9, 9,10,10,10,10,11,11,11,11, 0,13,
  134088. 13, 9, 9, 9, 9,10,10,11,11,11,12, 0, 0, 0, 9,10,
  134089. 10,10,11,11,12,11,12,12, 0, 0, 0,10,10, 9, 9,11,
  134090. 11,12,12,12,12, 0, 0, 0,13,13,10,10,11,11,12,12,
  134091. 13,13, 0, 0, 0,14,14,10,10,11,11,12,12,13,13, 0,
  134092. 0, 0, 0, 0,11,12,11,11,13,12,13,13, 0, 0, 0, 0,
  134093. 0,12,12,11,11,13,12,14,14,
  134094. };
  134095. static float _vq_quantthresh__44c0_sm_p7_0[] = {
  134096. -27.5, -22.5, -17.5, -12.5, -7.5, -2.5, 2.5, 7.5,
  134097. 12.5, 17.5, 22.5, 27.5,
  134098. };
  134099. static long _vq_quantmap__44c0_sm_p7_0[] = {
  134100. 11, 9, 7, 5, 3, 1, 0, 2,
  134101. 4, 6, 8, 10, 12,
  134102. };
  134103. static encode_aux_threshmatch _vq_auxt__44c0_sm_p7_0 = {
  134104. _vq_quantthresh__44c0_sm_p7_0,
  134105. _vq_quantmap__44c0_sm_p7_0,
  134106. 13,
  134107. 13
  134108. };
  134109. static static_codebook _44c0_sm_p7_0 = {
  134110. 2, 169,
  134111. _vq_lengthlist__44c0_sm_p7_0,
  134112. 1, -526516224, 1616117760, 4, 0,
  134113. _vq_quantlist__44c0_sm_p7_0,
  134114. NULL,
  134115. &_vq_auxt__44c0_sm_p7_0,
  134116. NULL,
  134117. 0
  134118. };
  134119. static long _vq_quantlist__44c0_sm_p7_1[] = {
  134120. 2,
  134121. 1,
  134122. 3,
  134123. 0,
  134124. 4,
  134125. };
  134126. static long _vq_lengthlist__44c0_sm_p7_1[] = {
  134127. 2, 4, 4, 4, 4, 6, 5, 5, 5, 5, 6, 5, 5, 5, 5, 6,
  134128. 6, 6, 5, 5, 6, 6, 6, 5, 5,
  134129. };
  134130. static float _vq_quantthresh__44c0_sm_p7_1[] = {
  134131. -1.5, -0.5, 0.5, 1.5,
  134132. };
  134133. static long _vq_quantmap__44c0_sm_p7_1[] = {
  134134. 3, 1, 0, 2, 4,
  134135. };
  134136. static encode_aux_threshmatch _vq_auxt__44c0_sm_p7_1 = {
  134137. _vq_quantthresh__44c0_sm_p7_1,
  134138. _vq_quantmap__44c0_sm_p7_1,
  134139. 5,
  134140. 5
  134141. };
  134142. static static_codebook _44c0_sm_p7_1 = {
  134143. 2, 25,
  134144. _vq_lengthlist__44c0_sm_p7_1,
  134145. 1, -533725184, 1611661312, 3, 0,
  134146. _vq_quantlist__44c0_sm_p7_1,
  134147. NULL,
  134148. &_vq_auxt__44c0_sm_p7_1,
  134149. NULL,
  134150. 0
  134151. };
  134152. static long _vq_quantlist__44c0_sm_p8_0[] = {
  134153. 4,
  134154. 3,
  134155. 5,
  134156. 2,
  134157. 6,
  134158. 1,
  134159. 7,
  134160. 0,
  134161. 8,
  134162. };
  134163. static long _vq_lengthlist__44c0_sm_p8_0[] = {
  134164. 1, 3, 3,11,11,11,11,11,11, 3, 7, 6,11,11,11,11,
  134165. 11,11, 4, 8, 7,11,11,11,11,11,11,11,11,11,11,11,
  134166. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  134167. 11,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,
  134168. 12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,
  134169. 12,
  134170. };
  134171. static float _vq_quantthresh__44c0_sm_p8_0[] = {
  134172. -773.5, -552.5, -331.5, -110.5, 110.5, 331.5, 552.5, 773.5,
  134173. };
  134174. static long _vq_quantmap__44c0_sm_p8_0[] = {
  134175. 7, 5, 3, 1, 0, 2, 4, 6,
  134176. 8,
  134177. };
  134178. static encode_aux_threshmatch _vq_auxt__44c0_sm_p8_0 = {
  134179. _vq_quantthresh__44c0_sm_p8_0,
  134180. _vq_quantmap__44c0_sm_p8_0,
  134181. 9,
  134182. 9
  134183. };
  134184. static static_codebook _44c0_sm_p8_0 = {
  134185. 2, 81,
  134186. _vq_lengthlist__44c0_sm_p8_0,
  134187. 1, -516186112, 1627103232, 4, 0,
  134188. _vq_quantlist__44c0_sm_p8_0,
  134189. NULL,
  134190. &_vq_auxt__44c0_sm_p8_0,
  134191. NULL,
  134192. 0
  134193. };
  134194. static long _vq_quantlist__44c0_sm_p8_1[] = {
  134195. 6,
  134196. 5,
  134197. 7,
  134198. 4,
  134199. 8,
  134200. 3,
  134201. 9,
  134202. 2,
  134203. 10,
  134204. 1,
  134205. 11,
  134206. 0,
  134207. 12,
  134208. };
  134209. static long _vq_lengthlist__44c0_sm_p8_1[] = {
  134210. 1, 4, 4, 6, 6, 7, 7, 9, 9,10,11,12,12, 6, 5, 5,
  134211. 7, 7, 8, 8,10,10,12,11,12,12, 6, 5, 5, 7, 7, 8,
  134212. 8,10,10,12,11,12,12,17, 7, 7, 8, 8, 9, 9,10,10,
  134213. 12,12,13,13,18, 7, 7, 8, 7, 9, 9,10,10,12,12,12,
  134214. 13,19,10,10, 8, 8,10,10,11,11,12,12,13,14,19,11,
  134215. 10, 8, 7,10,10,11,11,12,12,13,12,19,19,19,10,10,
  134216. 10,10,11,11,12,12,13,13,19,19,19,11, 9,11, 9,14,
  134217. 12,13,12,13,13,19,20,18,13,14,11,11,12,12,13,13,
  134218. 14,13,20,20,20,15,13,11,10,13,11,13,13,14,13,20,
  134219. 20,20,20,20,13,14,12,12,13,13,13,13,20,20,20,20,
  134220. 20,13,13,12,12,16,13,15,13,
  134221. };
  134222. static float _vq_quantthresh__44c0_sm_p8_1[] = {
  134223. -93.5, -76.5, -59.5, -42.5, -25.5, -8.5, 8.5, 25.5,
  134224. 42.5, 59.5, 76.5, 93.5,
  134225. };
  134226. static long _vq_quantmap__44c0_sm_p8_1[] = {
  134227. 11, 9, 7, 5, 3, 1, 0, 2,
  134228. 4, 6, 8, 10, 12,
  134229. };
  134230. static encode_aux_threshmatch _vq_auxt__44c0_sm_p8_1 = {
  134231. _vq_quantthresh__44c0_sm_p8_1,
  134232. _vq_quantmap__44c0_sm_p8_1,
  134233. 13,
  134234. 13
  134235. };
  134236. static static_codebook _44c0_sm_p8_1 = {
  134237. 2, 169,
  134238. _vq_lengthlist__44c0_sm_p8_1,
  134239. 1, -522616832, 1620115456, 4, 0,
  134240. _vq_quantlist__44c0_sm_p8_1,
  134241. NULL,
  134242. &_vq_auxt__44c0_sm_p8_1,
  134243. NULL,
  134244. 0
  134245. };
  134246. static long _vq_quantlist__44c0_sm_p8_2[] = {
  134247. 8,
  134248. 7,
  134249. 9,
  134250. 6,
  134251. 10,
  134252. 5,
  134253. 11,
  134254. 4,
  134255. 12,
  134256. 3,
  134257. 13,
  134258. 2,
  134259. 14,
  134260. 1,
  134261. 15,
  134262. 0,
  134263. 16,
  134264. };
  134265. static long _vq_lengthlist__44c0_sm_p8_2[] = {
  134266. 2, 5, 5, 6, 6, 7, 7, 7, 7, 8, 8, 8, 8, 8, 8, 8,
  134267. 8,10, 6, 6, 7, 7, 7, 7, 8, 8, 9, 9, 9, 9, 9, 9,
  134268. 9, 9,10, 6, 6, 7, 7, 8, 7, 8, 8, 9, 9, 9, 9, 9,
  134269. 9, 9, 9,10, 7, 7, 7, 7, 8, 8, 8, 9, 9, 9, 9, 9,
  134270. 9, 9, 9, 9,10,10,10, 7, 7, 8, 8, 9, 8, 9, 9, 9,
  134271. 9,10, 9, 9,10,10,10,11, 8, 8, 8, 8, 9, 9, 9, 9,
  134272. 9, 9, 9,10, 9,10,10,10,10, 8, 8, 8, 8, 9, 9, 9,
  134273. 9, 9, 9, 9, 9,10,10,11,10,10, 8, 8, 9, 9, 9, 9,
  134274. 9, 9, 9, 9, 9, 9,10,10,10,10,10,11,11, 8, 8, 9,
  134275. 9, 9, 9, 9, 9, 9, 9, 9,10,11,11,11,11,11, 9, 9,
  134276. 9, 9, 9, 9, 9, 9,10, 9,10, 9,11,11,10,11,11, 9,
  134277. 9, 9, 9, 9, 9, 9, 9, 9, 9,10, 9,11,11,10,11,11,
  134278. 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,10, 9,11,10,11,11,
  134279. 11,11,11, 9, 9,10, 9, 9, 9, 9, 9, 9, 9,10,11,10,
  134280. 11,11,11,11,10,10,10,10, 9, 9, 9, 9, 9, 9,10,11,
  134281. 11,11,11,11,11, 9,10, 9, 9, 9, 9, 9, 9, 9, 9,11,
  134282. 11,10,11,11,11,10,10,10, 9, 9, 9, 9, 9, 9, 9, 9,
  134283. 10,11,10,11,11,11,11,11,11, 9, 9, 9, 9, 9, 9, 9,
  134284. 9,
  134285. };
  134286. static float _vq_quantthresh__44c0_sm_p8_2[] = {
  134287. -7.5, -6.5, -5.5, -4.5, -3.5, -2.5, -1.5, -0.5,
  134288. 0.5, 1.5, 2.5, 3.5, 4.5, 5.5, 6.5, 7.5,
  134289. };
  134290. static long _vq_quantmap__44c0_sm_p8_2[] = {
  134291. 15, 13, 11, 9, 7, 5, 3, 1,
  134292. 0, 2, 4, 6, 8, 10, 12, 14,
  134293. 16,
  134294. };
  134295. static encode_aux_threshmatch _vq_auxt__44c0_sm_p8_2 = {
  134296. _vq_quantthresh__44c0_sm_p8_2,
  134297. _vq_quantmap__44c0_sm_p8_2,
  134298. 17,
  134299. 17
  134300. };
  134301. static static_codebook _44c0_sm_p8_2 = {
  134302. 2, 289,
  134303. _vq_lengthlist__44c0_sm_p8_2,
  134304. 1, -529530880, 1611661312, 5, 0,
  134305. _vq_quantlist__44c0_sm_p8_2,
  134306. NULL,
  134307. &_vq_auxt__44c0_sm_p8_2,
  134308. NULL,
  134309. 0
  134310. };
  134311. static long _huff_lengthlist__44c0_sm_short[] = {
  134312. 6, 6,12,13,13,14,16,17,17, 4, 2, 5, 8, 7, 9,12,
  134313. 15,15, 9, 4, 5, 9, 7, 9,12,16,18,11, 6, 7, 4, 6,
  134314. 8,11,14,18,10, 5, 6, 5, 5, 7,10,14,17,10, 5, 7,
  134315. 7, 6, 7,10,13,16,11, 5, 7, 7, 7, 8,10,12,15,13,
  134316. 6, 7, 5, 5, 7, 9,12,13,16, 8, 9, 6, 6, 7, 9,10,
  134317. 12,
  134318. };
  134319. static static_codebook _huff_book__44c0_sm_short = {
  134320. 2, 81,
  134321. _huff_lengthlist__44c0_sm_short,
  134322. 0, 0, 0, 0, 0,
  134323. NULL,
  134324. NULL,
  134325. NULL,
  134326. NULL,
  134327. 0
  134328. };
  134329. static long _huff_lengthlist__44c1_s_long[] = {
  134330. 5, 5, 9,10, 9, 9,10,11,12, 5, 1, 5, 6, 6, 7,10,
  134331. 12,14, 9, 5, 6, 8, 8,10,12,14,14,10, 5, 8, 5, 6,
  134332. 8,11,13,14, 9, 5, 7, 6, 6, 8,10,12,11, 9, 7, 9,
  134333. 7, 6, 6, 7,10,10,10, 9,12, 9, 8, 7, 7,10,12,11,
  134334. 11,13,12,10, 9, 8, 9,11,11,14,15,15,13,11, 9, 9,
  134335. 11,
  134336. };
  134337. static static_codebook _huff_book__44c1_s_long = {
  134338. 2, 81,
  134339. _huff_lengthlist__44c1_s_long,
  134340. 0, 0, 0, 0, 0,
  134341. NULL,
  134342. NULL,
  134343. NULL,
  134344. NULL,
  134345. 0
  134346. };
  134347. static long _vq_quantlist__44c1_s_p1_0[] = {
  134348. 1,
  134349. 0,
  134350. 2,
  134351. };
  134352. static long _vq_lengthlist__44c1_s_p1_0[] = {
  134353. 2, 4, 4, 0, 0, 0, 0, 0, 0, 5, 7, 6, 0, 0, 0, 0,
  134354. 0, 0, 5, 6, 7, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134355. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134356. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134357. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134358. 0, 5, 7, 7, 0, 0, 0, 0, 0, 0, 7, 8, 8, 0, 0, 0,
  134359. 0, 0, 0, 7, 8, 8, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134360. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134361. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134362. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134363. 0, 0, 5, 7, 7, 0, 0, 0, 0, 0, 0, 7, 8, 8, 0, 0,
  134364. 0, 0, 0, 0, 7, 8, 8, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134365. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134366. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134367. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134368. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134369. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134370. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134371. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134372. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134373. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134374. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134375. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134376. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134377. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134378. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134379. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134380. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134381. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134382. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134383. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134384. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134385. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134386. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134387. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134388. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134389. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134390. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134391. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134392. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134393. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134394. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134395. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134396. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134397. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134398. 0, 0, 0, 0, 0, 0, 0, 0, 0, 4, 7, 7, 0, 0, 0, 0,
  134399. 0, 0, 7, 8, 8, 0, 0, 0, 0, 0, 0, 7, 8, 8, 0, 0,
  134400. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134401. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134402. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134403. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 7, 8, 8, 0, 0, 0,
  134404. 0, 0, 0, 8, 9,10, 0, 0, 0, 0, 0, 0, 8, 9, 9, 0,
  134405. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134406. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134407. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134408. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 6, 8, 8, 0, 0,
  134409. 0, 0, 0, 0, 8, 9, 8, 0, 0, 0, 0, 0, 0, 8, 9, 9,
  134410. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134411. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134412. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134413. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134414. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134415. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 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, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134418. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134419. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134420. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134421. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134422. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134423. 0, 0, 0, 0, 0, 0, 0, 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. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134426. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134427. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134428. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134429. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134430. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134431. 0, 0, 0, 0, 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, 0,
  134436. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134437. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134438. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134439. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134440. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134441. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134442. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134443. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134444. 0, 0, 4, 7, 7, 0, 0, 0, 0, 0, 0, 7, 8, 8, 0, 0,
  134445. 0, 0, 0, 0, 7, 8, 9, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134446. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134447. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134448. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134449. 0, 0, 0, 6, 8, 8, 0, 0, 0, 0, 0, 0, 8,10, 9, 0,
  134450. 0, 0, 0, 0, 0, 8, 8, 9, 0, 0, 0, 0, 0, 0, 0, 0,
  134451. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134452. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134453. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134454. 0, 0, 0, 0, 7, 8, 8, 0, 0, 0, 0, 0, 0, 8, 9, 9,
  134455. 0, 0, 0, 0, 0, 0, 8, 9, 9, 0, 0, 0, 0, 0, 0, 0,
  134456. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134457. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134458. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134459. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134460. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134461. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134462. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134463. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134464. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134465. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134466. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134467. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134468. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134469. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134470. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134471. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134472. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134473. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134474. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134475. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134476. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134477. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134478. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134479. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134480. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134481. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134482. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134483. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134484. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134485. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134486. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134487. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134488. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134489. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134490. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134491. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134492. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134493. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134494. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134495. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134496. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134497. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134498. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134499. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134500. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134501. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134502. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134503. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134504. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134505. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134506. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134507. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134508. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134509. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134510. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134511. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134512. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134513. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134514. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134515. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134516. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134517. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134518. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134519. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134520. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134521. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134522. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134523. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134524. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134525. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134526. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134527. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134528. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134529. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134530. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134531. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134532. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134533. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134534. 0, 0, 0, 0, 0, 0, 0, 0, 0, 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, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134544. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134545. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134546. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134547. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134548. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134549. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134550. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134551. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134552. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134553. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134554. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134555. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134556. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134557. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134558. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134559. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134560. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134561. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134562. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134563. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134564. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134565. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134566. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134567. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134568. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134569. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134570. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134571. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134572. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134573. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134574. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134575. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134576. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134577. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134578. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134579. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134580. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134581. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134582. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134583. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134584. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134585. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134586. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134587. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134588. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134589. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134590. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134591. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134592. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134593. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134594. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134595. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134596. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134597. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134598. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134599. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134600. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134601. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134602. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134603. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134604. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134605. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134606. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134607. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134608. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134609. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134610. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134611. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134612. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134613. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134614. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134615. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134616. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134617. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134618. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134619. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134620. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134621. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134622. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134623. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134624. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134625. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134626. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134627. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134628. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134629. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134630. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134631. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134632. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134633. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134634. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134635. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134636. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134637. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134638. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134639. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134640. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134641. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134642. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134643. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134644. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134645. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134646. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134647. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134648. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134649. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134650. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134651. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134652. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134653. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134654. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134655. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134656. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134657. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134658. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134659. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134660. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134661. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134662. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134663. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134664. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134665. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134666. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134667. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134668. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134669. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134670. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134671. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134672. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134673. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134674. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134675. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134676. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134677. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134678. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134679. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134680. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134681. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134682. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134683. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134684. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134685. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134686. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134687. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134688. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134689. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134690. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134691. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134692. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134693. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134694. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134695. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134696. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134697. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134698. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134699. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134700. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134701. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134702. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134703. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134704. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134705. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134706. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134707. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134708. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134709. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134710. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134711. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134712. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134713. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134714. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134715. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134716. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134717. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134718. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134719. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134720. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134721. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134722. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134723. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134724. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134725. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134726. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134727. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134728. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134729. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134730. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134731. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134732. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134733. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134734. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134735. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134736. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134737. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134738. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134739. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134740. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134741. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134742. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134743. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134744. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134745. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134746. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134747. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134748. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134749. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134750. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134751. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134752. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134753. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134754. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134755. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134756. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134757. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134758. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134759. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134760. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134761. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134762. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134763. 0,
  134764. };
  134765. static float _vq_quantthresh__44c1_s_p1_0[] = {
  134766. -0.5, 0.5,
  134767. };
  134768. static long _vq_quantmap__44c1_s_p1_0[] = {
  134769. 1, 0, 2,
  134770. };
  134771. static encode_aux_threshmatch _vq_auxt__44c1_s_p1_0 = {
  134772. _vq_quantthresh__44c1_s_p1_0,
  134773. _vq_quantmap__44c1_s_p1_0,
  134774. 3,
  134775. 3
  134776. };
  134777. static static_codebook _44c1_s_p1_0 = {
  134778. 8, 6561,
  134779. _vq_lengthlist__44c1_s_p1_0,
  134780. 1, -535822336, 1611661312, 2, 0,
  134781. _vq_quantlist__44c1_s_p1_0,
  134782. NULL,
  134783. &_vq_auxt__44c1_s_p1_0,
  134784. NULL,
  134785. 0
  134786. };
  134787. static long _vq_quantlist__44c1_s_p2_0[] = {
  134788. 2,
  134789. 1,
  134790. 3,
  134791. 0,
  134792. 4,
  134793. };
  134794. static long _vq_lengthlist__44c1_s_p2_0[] = {
  134795. 2, 3, 4, 6, 5, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134796. 0, 0, 0, 0, 0, 0, 0, 0, 0, 4, 4, 4, 6, 6, 0, 0,
  134797. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134798. 0, 0, 4, 4, 5, 6, 6, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134799. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 6, 6, 6, 8, 8,
  134800. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134801. 0, 0, 0, 0, 6, 6, 6, 8, 8, 0, 0, 0, 0, 0, 0, 0,
  134802. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134803. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134804. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134805. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134806. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134807. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134808. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134809. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134810. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134811. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134812. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134813. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134814. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134815. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134816. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134817. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134818. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134819. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134820. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134821. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134822. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134823. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134824. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134825. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134826. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134827. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134828. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134829. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134830. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134831. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134832. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134833. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134834. 0,
  134835. };
  134836. static float _vq_quantthresh__44c1_s_p2_0[] = {
  134837. -1.5, -0.5, 0.5, 1.5,
  134838. };
  134839. static long _vq_quantmap__44c1_s_p2_0[] = {
  134840. 3, 1, 0, 2, 4,
  134841. };
  134842. static encode_aux_threshmatch _vq_auxt__44c1_s_p2_0 = {
  134843. _vq_quantthresh__44c1_s_p2_0,
  134844. _vq_quantmap__44c1_s_p2_0,
  134845. 5,
  134846. 5
  134847. };
  134848. static static_codebook _44c1_s_p2_0 = {
  134849. 4, 625,
  134850. _vq_lengthlist__44c1_s_p2_0,
  134851. 1, -533725184, 1611661312, 3, 0,
  134852. _vq_quantlist__44c1_s_p2_0,
  134853. NULL,
  134854. &_vq_auxt__44c1_s_p2_0,
  134855. NULL,
  134856. 0
  134857. };
  134858. static long _vq_quantlist__44c1_s_p3_0[] = {
  134859. 4,
  134860. 3,
  134861. 5,
  134862. 2,
  134863. 6,
  134864. 1,
  134865. 7,
  134866. 0,
  134867. 8,
  134868. };
  134869. static long _vq_lengthlist__44c1_s_p3_0[] = {
  134870. 1, 3, 2, 7, 7, 0, 0, 0, 0, 0,13,13, 6, 6, 0, 0,
  134871. 0, 0, 0,12, 0, 6, 6, 0, 0, 0, 0, 0, 0, 0, 7, 7,
  134872. 0, 0, 0, 0, 0, 0, 0, 7, 7, 0, 0, 0, 0, 0, 0, 0,
  134873. 8, 9, 0, 0, 0, 0, 0, 0, 0, 8, 8, 0, 0, 0, 0, 0,
  134874. 0, 0,11,10, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134875. 0,
  134876. };
  134877. static float _vq_quantthresh__44c1_s_p3_0[] = {
  134878. -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5, 3.5,
  134879. };
  134880. static long _vq_quantmap__44c1_s_p3_0[] = {
  134881. 7, 5, 3, 1, 0, 2, 4, 6,
  134882. 8,
  134883. };
  134884. static encode_aux_threshmatch _vq_auxt__44c1_s_p3_0 = {
  134885. _vq_quantthresh__44c1_s_p3_0,
  134886. _vq_quantmap__44c1_s_p3_0,
  134887. 9,
  134888. 9
  134889. };
  134890. static static_codebook _44c1_s_p3_0 = {
  134891. 2, 81,
  134892. _vq_lengthlist__44c1_s_p3_0,
  134893. 1, -531628032, 1611661312, 4, 0,
  134894. _vq_quantlist__44c1_s_p3_0,
  134895. NULL,
  134896. &_vq_auxt__44c1_s_p3_0,
  134897. NULL,
  134898. 0
  134899. };
  134900. static long _vq_quantlist__44c1_s_p4_0[] = {
  134901. 4,
  134902. 3,
  134903. 5,
  134904. 2,
  134905. 6,
  134906. 1,
  134907. 7,
  134908. 0,
  134909. 8,
  134910. };
  134911. static long _vq_lengthlist__44c1_s_p4_0[] = {
  134912. 1, 3, 3, 6, 5, 6, 6, 8, 8, 0, 0, 0, 7, 7, 7, 7,
  134913. 9, 9, 0, 0, 0, 7, 7, 7, 7, 9, 9, 0, 0, 0, 7, 7,
  134914. 8, 8,10,10, 0, 0, 0, 7, 7, 8, 8,10,10, 0, 0, 0,
  134915. 9, 9, 8, 8,10,10, 0, 0, 0, 8, 8, 8, 8,10,10, 0,
  134916. 0, 0,10,10, 9, 9,11,11, 0, 0, 0, 0, 0, 9, 9,11,
  134917. 11,
  134918. };
  134919. static float _vq_quantthresh__44c1_s_p4_0[] = {
  134920. -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5, 3.5,
  134921. };
  134922. static long _vq_quantmap__44c1_s_p4_0[] = {
  134923. 7, 5, 3, 1, 0, 2, 4, 6,
  134924. 8,
  134925. };
  134926. static encode_aux_threshmatch _vq_auxt__44c1_s_p4_0 = {
  134927. _vq_quantthresh__44c1_s_p4_0,
  134928. _vq_quantmap__44c1_s_p4_0,
  134929. 9,
  134930. 9
  134931. };
  134932. static static_codebook _44c1_s_p4_0 = {
  134933. 2, 81,
  134934. _vq_lengthlist__44c1_s_p4_0,
  134935. 1, -531628032, 1611661312, 4, 0,
  134936. _vq_quantlist__44c1_s_p4_0,
  134937. NULL,
  134938. &_vq_auxt__44c1_s_p4_0,
  134939. NULL,
  134940. 0
  134941. };
  134942. static long _vq_quantlist__44c1_s_p5_0[] = {
  134943. 8,
  134944. 7,
  134945. 9,
  134946. 6,
  134947. 10,
  134948. 5,
  134949. 11,
  134950. 4,
  134951. 12,
  134952. 3,
  134953. 13,
  134954. 2,
  134955. 14,
  134956. 1,
  134957. 15,
  134958. 0,
  134959. 16,
  134960. };
  134961. static long _vq_lengthlist__44c1_s_p5_0[] = {
  134962. 1, 4, 3, 6, 6, 7, 7, 8, 8, 8, 8, 9, 9,10,10,11,
  134963. 11, 0, 0, 0, 7, 7, 8, 8, 9, 9, 9, 9,10,10,10,10,
  134964. 11,11, 0, 0, 0, 7, 7, 8, 8, 9, 9, 9, 9,10,10,10,
  134965. 10,11,11, 0, 0, 0, 7, 7, 8, 8, 9, 9, 9, 9,10,10,
  134966. 11,11,11,11, 0, 0, 0, 7, 7, 8, 8, 9, 9, 9, 9,10,
  134967. 10,11,11,12,11, 0, 0, 0, 8, 8, 9, 9, 9,10,10,10,
  134968. 10,10,11,11,12,12, 0, 0, 0, 8, 8, 9, 9,10, 9,10,
  134969. 10,10,10,11,11,12,12, 0, 0, 0, 9, 9, 9, 9,10,10,
  134970. 10,10,11,11,12,12,12,12, 0, 0, 0, 0, 0, 9, 9,10,
  134971. 10,10,10,11,11,12,12,12,12, 0, 0, 0, 0, 0, 9, 9,
  134972. 10,10,10,11,11,11,12,12,13,13, 0, 0, 0, 0, 0, 9,
  134973. 9,10,10,10,10,11,11,12,12,13,13, 0, 0, 0, 0, 0,
  134974. 10,10,10,10,11,11,12,12,12,12,13,13, 0, 0, 0, 0,
  134975. 0, 0, 0,10,10,11,11,12,12,12,12,13,13, 0, 0, 0,
  134976. 0, 0, 0, 0,11,11,12,12,12,12,13,13,13,13, 0, 0,
  134977. 0, 0, 0, 0, 0,11,11,11,11,12,12,13,13,13,13, 0,
  134978. 0, 0, 0, 0, 0, 0,12,12,12,12,12,12,13,13,14,14,
  134979. 0, 0, 0, 0, 0, 0, 0, 0, 0,12,12,12,12,13,13,14,
  134980. 14,
  134981. };
  134982. static float _vq_quantthresh__44c1_s_p5_0[] = {
  134983. -7.5, -6.5, -5.5, -4.5, -3.5, -2.5, -1.5, -0.5,
  134984. 0.5, 1.5, 2.5, 3.5, 4.5, 5.5, 6.5, 7.5,
  134985. };
  134986. static long _vq_quantmap__44c1_s_p5_0[] = {
  134987. 15, 13, 11, 9, 7, 5, 3, 1,
  134988. 0, 2, 4, 6, 8, 10, 12, 14,
  134989. 16,
  134990. };
  134991. static encode_aux_threshmatch _vq_auxt__44c1_s_p5_0 = {
  134992. _vq_quantthresh__44c1_s_p5_0,
  134993. _vq_quantmap__44c1_s_p5_0,
  134994. 17,
  134995. 17
  134996. };
  134997. static static_codebook _44c1_s_p5_0 = {
  134998. 2, 289,
  134999. _vq_lengthlist__44c1_s_p5_0,
  135000. 1, -529530880, 1611661312, 5, 0,
  135001. _vq_quantlist__44c1_s_p5_0,
  135002. NULL,
  135003. &_vq_auxt__44c1_s_p5_0,
  135004. NULL,
  135005. 0
  135006. };
  135007. static long _vq_quantlist__44c1_s_p6_0[] = {
  135008. 1,
  135009. 0,
  135010. 2,
  135011. };
  135012. static long _vq_lengthlist__44c1_s_p6_0[] = {
  135013. 1, 4, 4, 7, 6, 6, 7, 6, 6, 4, 7, 7,10, 9, 9,11,
  135014. 9, 9, 4, 7, 7,10, 9, 9,11, 9, 9, 6,10,10,11,11,
  135015. 11,11,10,10, 6, 9, 9,11,10,10,11,10,10, 6, 9, 9,
  135016. 11,10,11,11,10,10, 7,11,10,11,11,11,12,11,11, 7,
  135017. 9, 9,11,10,10,11,11,10, 6, 9, 9,10,10,10,12,10,
  135018. 11,
  135019. };
  135020. static float _vq_quantthresh__44c1_s_p6_0[] = {
  135021. -5.5, 5.5,
  135022. };
  135023. static long _vq_quantmap__44c1_s_p6_0[] = {
  135024. 1, 0, 2,
  135025. };
  135026. static encode_aux_threshmatch _vq_auxt__44c1_s_p6_0 = {
  135027. _vq_quantthresh__44c1_s_p6_0,
  135028. _vq_quantmap__44c1_s_p6_0,
  135029. 3,
  135030. 3
  135031. };
  135032. static static_codebook _44c1_s_p6_0 = {
  135033. 4, 81,
  135034. _vq_lengthlist__44c1_s_p6_0,
  135035. 1, -529137664, 1618345984, 2, 0,
  135036. _vq_quantlist__44c1_s_p6_0,
  135037. NULL,
  135038. &_vq_auxt__44c1_s_p6_0,
  135039. NULL,
  135040. 0
  135041. };
  135042. static long _vq_quantlist__44c1_s_p6_1[] = {
  135043. 5,
  135044. 4,
  135045. 6,
  135046. 3,
  135047. 7,
  135048. 2,
  135049. 8,
  135050. 1,
  135051. 9,
  135052. 0,
  135053. 10,
  135054. };
  135055. static long _vq_lengthlist__44c1_s_p6_1[] = {
  135056. 2, 3, 3, 6, 6, 7, 7, 7, 7, 8, 8,10,10,10, 6, 6,
  135057. 7, 7, 8, 8, 8, 8,10,10,10, 6, 6, 7, 7, 8, 8, 8,
  135058. 8,10,10,10, 7, 7, 7, 7, 8, 8, 8, 8,10,10,10, 7,
  135059. 7, 7, 7, 8, 8, 8, 8,10,10,10, 7, 7, 8, 8, 8, 8,
  135060. 8, 8,10,10,10, 7, 7, 8, 8, 8, 8, 8, 8,10,10,10,
  135061. 8, 8, 8, 8, 8, 8, 8, 8,10,10,10,10,10, 8, 8, 8,
  135062. 8, 8, 8,10,10,10,10,10, 9, 9, 8, 8, 8, 8,10,10,
  135063. 10,10,10, 8, 8, 8, 8, 8, 8,
  135064. };
  135065. static float _vq_quantthresh__44c1_s_p6_1[] = {
  135066. -4.5, -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5,
  135067. 3.5, 4.5,
  135068. };
  135069. static long _vq_quantmap__44c1_s_p6_1[] = {
  135070. 9, 7, 5, 3, 1, 0, 2, 4,
  135071. 6, 8, 10,
  135072. };
  135073. static encode_aux_threshmatch _vq_auxt__44c1_s_p6_1 = {
  135074. _vq_quantthresh__44c1_s_p6_1,
  135075. _vq_quantmap__44c1_s_p6_1,
  135076. 11,
  135077. 11
  135078. };
  135079. static static_codebook _44c1_s_p6_1 = {
  135080. 2, 121,
  135081. _vq_lengthlist__44c1_s_p6_1,
  135082. 1, -531365888, 1611661312, 4, 0,
  135083. _vq_quantlist__44c1_s_p6_1,
  135084. NULL,
  135085. &_vq_auxt__44c1_s_p6_1,
  135086. NULL,
  135087. 0
  135088. };
  135089. static long _vq_quantlist__44c1_s_p7_0[] = {
  135090. 6,
  135091. 5,
  135092. 7,
  135093. 4,
  135094. 8,
  135095. 3,
  135096. 9,
  135097. 2,
  135098. 10,
  135099. 1,
  135100. 11,
  135101. 0,
  135102. 12,
  135103. };
  135104. static long _vq_lengthlist__44c1_s_p7_0[] = {
  135105. 1, 4, 4, 6, 6, 7, 7, 7, 7, 8, 8,10, 9, 7, 5, 6,
  135106. 7, 7, 8, 8, 8, 8, 9, 9,10,10, 7, 5, 5, 7, 7, 8,
  135107. 8, 8, 8, 9, 9,10,10, 0, 8, 8, 8, 8, 9, 9, 9, 9,
  135108. 10,10,11,10, 0, 8, 8, 8, 8, 9, 9, 9, 9,10,10,11,
  135109. 11, 0,12,12, 9, 9, 9,10,10,10,11,11,11,11, 0,13,
  135110. 13, 9, 9, 9, 9,10,10,11,11,11,11, 0, 0, 0,10,10,
  135111. 10,10,11,11,12,11,12,12, 0, 0, 0,10,10,10, 9,11,
  135112. 11,12,11,13,12, 0, 0, 0,13,13,10,10,11,11,12,12,
  135113. 13,13, 0, 0, 0,14,14,10,10,11,11,12,12,13,13, 0,
  135114. 0, 0, 0, 0,11,12,11,11,12,12,14,13, 0, 0, 0, 0,
  135115. 0,12,11,11,11,13,10,14,13,
  135116. };
  135117. static float _vq_quantthresh__44c1_s_p7_0[] = {
  135118. -27.5, -22.5, -17.5, -12.5, -7.5, -2.5, 2.5, 7.5,
  135119. 12.5, 17.5, 22.5, 27.5,
  135120. };
  135121. static long _vq_quantmap__44c1_s_p7_0[] = {
  135122. 11, 9, 7, 5, 3, 1, 0, 2,
  135123. 4, 6, 8, 10, 12,
  135124. };
  135125. static encode_aux_threshmatch _vq_auxt__44c1_s_p7_0 = {
  135126. _vq_quantthresh__44c1_s_p7_0,
  135127. _vq_quantmap__44c1_s_p7_0,
  135128. 13,
  135129. 13
  135130. };
  135131. static static_codebook _44c1_s_p7_0 = {
  135132. 2, 169,
  135133. _vq_lengthlist__44c1_s_p7_0,
  135134. 1, -526516224, 1616117760, 4, 0,
  135135. _vq_quantlist__44c1_s_p7_0,
  135136. NULL,
  135137. &_vq_auxt__44c1_s_p7_0,
  135138. NULL,
  135139. 0
  135140. };
  135141. static long _vq_quantlist__44c1_s_p7_1[] = {
  135142. 2,
  135143. 1,
  135144. 3,
  135145. 0,
  135146. 4,
  135147. };
  135148. static long _vq_lengthlist__44c1_s_p7_1[] = {
  135149. 2, 3, 3, 5, 5, 6, 6, 6, 5, 5, 6, 6, 6, 5, 5, 6,
  135150. 6, 6, 5, 5, 6, 6, 6, 5, 5,
  135151. };
  135152. static float _vq_quantthresh__44c1_s_p7_1[] = {
  135153. -1.5, -0.5, 0.5, 1.5,
  135154. };
  135155. static long _vq_quantmap__44c1_s_p7_1[] = {
  135156. 3, 1, 0, 2, 4,
  135157. };
  135158. static encode_aux_threshmatch _vq_auxt__44c1_s_p7_1 = {
  135159. _vq_quantthresh__44c1_s_p7_1,
  135160. _vq_quantmap__44c1_s_p7_1,
  135161. 5,
  135162. 5
  135163. };
  135164. static static_codebook _44c1_s_p7_1 = {
  135165. 2, 25,
  135166. _vq_lengthlist__44c1_s_p7_1,
  135167. 1, -533725184, 1611661312, 3, 0,
  135168. _vq_quantlist__44c1_s_p7_1,
  135169. NULL,
  135170. &_vq_auxt__44c1_s_p7_1,
  135171. NULL,
  135172. 0
  135173. };
  135174. static long _vq_quantlist__44c1_s_p8_0[] = {
  135175. 6,
  135176. 5,
  135177. 7,
  135178. 4,
  135179. 8,
  135180. 3,
  135181. 9,
  135182. 2,
  135183. 10,
  135184. 1,
  135185. 11,
  135186. 0,
  135187. 12,
  135188. };
  135189. static long _vq_lengthlist__44c1_s_p8_0[] = {
  135190. 1, 4, 3,10,10,10,10,10,10,10,10,10,10, 4, 8, 6,
  135191. 10,10,10,10,10,10,10,10,10,10, 4, 8, 7,10,10,10,
  135192. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  135193. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  135194. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  135195. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  135196. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  135197. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  135198. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  135199. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  135200. 10,10,10,10,10,10,10,10,10,
  135201. };
  135202. static float _vq_quantthresh__44c1_s_p8_0[] = {
  135203. -1215.5, -994.5, -773.5, -552.5, -331.5, -110.5, 110.5, 331.5,
  135204. 552.5, 773.5, 994.5, 1215.5,
  135205. };
  135206. static long _vq_quantmap__44c1_s_p8_0[] = {
  135207. 11, 9, 7, 5, 3, 1, 0, 2,
  135208. 4, 6, 8, 10, 12,
  135209. };
  135210. static encode_aux_threshmatch _vq_auxt__44c1_s_p8_0 = {
  135211. _vq_quantthresh__44c1_s_p8_0,
  135212. _vq_quantmap__44c1_s_p8_0,
  135213. 13,
  135214. 13
  135215. };
  135216. static static_codebook _44c1_s_p8_0 = {
  135217. 2, 169,
  135218. _vq_lengthlist__44c1_s_p8_0,
  135219. 1, -514541568, 1627103232, 4, 0,
  135220. _vq_quantlist__44c1_s_p8_0,
  135221. NULL,
  135222. &_vq_auxt__44c1_s_p8_0,
  135223. NULL,
  135224. 0
  135225. };
  135226. static long _vq_quantlist__44c1_s_p8_1[] = {
  135227. 6,
  135228. 5,
  135229. 7,
  135230. 4,
  135231. 8,
  135232. 3,
  135233. 9,
  135234. 2,
  135235. 10,
  135236. 1,
  135237. 11,
  135238. 0,
  135239. 12,
  135240. };
  135241. static long _vq_lengthlist__44c1_s_p8_1[] = {
  135242. 1, 4, 4, 6, 5, 7, 7, 9, 9,10,10,12,12, 6, 5, 5,
  135243. 7, 7, 8, 8,10,10,12,11,12,12, 6, 5, 5, 7, 7, 8,
  135244. 8,10,10,11,11,12,12,15, 7, 7, 8, 8, 9, 9,11,11,
  135245. 12,12,13,12,15, 8, 8, 8, 7, 9, 9,10,10,12,12,13,
  135246. 13,16,11,10, 8, 8,10,10,11,11,12,12,13,13,16,11,
  135247. 11, 9, 8,11,10,11,11,12,12,13,12,16,16,16,10,11,
  135248. 10,11,12,12,12,12,13,13,16,16,16,11, 9,11, 9,14,
  135249. 12,12,12,13,13,16,16,16,12,14,11,12,12,12,13,13,
  135250. 14,13,16,16,16,15,13,12,10,13,10,13,14,13,13,16,
  135251. 16,16,16,16,13,14,12,13,13,12,13,13,16,16,16,16,
  135252. 16,13,12,12,11,14,12,15,13,
  135253. };
  135254. static float _vq_quantthresh__44c1_s_p8_1[] = {
  135255. -93.5, -76.5, -59.5, -42.5, -25.5, -8.5, 8.5, 25.5,
  135256. 42.5, 59.5, 76.5, 93.5,
  135257. };
  135258. static long _vq_quantmap__44c1_s_p8_1[] = {
  135259. 11, 9, 7, 5, 3, 1, 0, 2,
  135260. 4, 6, 8, 10, 12,
  135261. };
  135262. static encode_aux_threshmatch _vq_auxt__44c1_s_p8_1 = {
  135263. _vq_quantthresh__44c1_s_p8_1,
  135264. _vq_quantmap__44c1_s_p8_1,
  135265. 13,
  135266. 13
  135267. };
  135268. static static_codebook _44c1_s_p8_1 = {
  135269. 2, 169,
  135270. _vq_lengthlist__44c1_s_p8_1,
  135271. 1, -522616832, 1620115456, 4, 0,
  135272. _vq_quantlist__44c1_s_p8_1,
  135273. NULL,
  135274. &_vq_auxt__44c1_s_p8_1,
  135275. NULL,
  135276. 0
  135277. };
  135278. static long _vq_quantlist__44c1_s_p8_2[] = {
  135279. 8,
  135280. 7,
  135281. 9,
  135282. 6,
  135283. 10,
  135284. 5,
  135285. 11,
  135286. 4,
  135287. 12,
  135288. 3,
  135289. 13,
  135290. 2,
  135291. 14,
  135292. 1,
  135293. 15,
  135294. 0,
  135295. 16,
  135296. };
  135297. static long _vq_lengthlist__44c1_s_p8_2[] = {
  135298. 2, 4, 4, 6, 6, 6, 6, 7, 7, 8, 8, 8, 8, 8, 8, 8,
  135299. 8,10,10,10, 7, 7, 7, 7, 8, 8, 9, 9, 9, 9, 9, 9,
  135300. 9, 9,10,10,10, 7, 7, 8, 7, 8, 8, 9, 9, 9, 9, 9,
  135301. 9, 9, 9,10,10,10, 7, 7, 8, 8, 8, 9, 9, 9, 9, 9,
  135302. 9,10, 9, 9,10,10,10, 7, 7, 8, 8, 9, 8, 9, 9, 9,
  135303. 9,10, 9, 9,10,10,11,11, 8, 8, 8, 8, 9, 9, 9, 9,
  135304. 9, 9,10, 9, 9,10,10,10,10, 8, 8, 8, 8, 9, 9, 9,
  135305. 9, 9, 9, 9, 9,10,10,11,11,11, 8, 8, 9, 9, 9, 9,
  135306. 9, 9, 9, 9, 9, 9,10,10,10,10,11,11,11, 8, 8, 9,
  135307. 9, 9, 9,10, 9, 9, 9, 9, 9,11,11,11,11,11, 9, 9,
  135308. 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,11,10,10,11,11, 9,
  135309. 9, 9, 9, 9, 9, 9, 9, 9,10,10,10,10,11,10,11,11,
  135310. 9, 9, 9, 9, 9, 9, 9, 9, 9,10,10, 9,10,10,11,11,
  135311. 11,11,11, 9, 9, 9,10, 9, 9, 9, 9, 9, 9,10,11,11,
  135312. 11,11,11,11,10,10,10,10, 9, 9, 9, 9, 9, 9,10,11,
  135313. 11,11,11,11,11, 9,10, 9, 9, 9, 9,10, 9, 9, 9,11,
  135314. 11,11,11,11,11,11,10,10, 9, 9, 9, 9, 9, 9,10, 9,
  135315. 11,11,10,11,11,11,11,10,11, 9, 9, 9, 9, 9, 9, 9,
  135316. 9,
  135317. };
  135318. static float _vq_quantthresh__44c1_s_p8_2[] = {
  135319. -7.5, -6.5, -5.5, -4.5, -3.5, -2.5, -1.5, -0.5,
  135320. 0.5, 1.5, 2.5, 3.5, 4.5, 5.5, 6.5, 7.5,
  135321. };
  135322. static long _vq_quantmap__44c1_s_p8_2[] = {
  135323. 15, 13, 11, 9, 7, 5, 3, 1,
  135324. 0, 2, 4, 6, 8, 10, 12, 14,
  135325. 16,
  135326. };
  135327. static encode_aux_threshmatch _vq_auxt__44c1_s_p8_2 = {
  135328. _vq_quantthresh__44c1_s_p8_2,
  135329. _vq_quantmap__44c1_s_p8_2,
  135330. 17,
  135331. 17
  135332. };
  135333. static static_codebook _44c1_s_p8_2 = {
  135334. 2, 289,
  135335. _vq_lengthlist__44c1_s_p8_2,
  135336. 1, -529530880, 1611661312, 5, 0,
  135337. _vq_quantlist__44c1_s_p8_2,
  135338. NULL,
  135339. &_vq_auxt__44c1_s_p8_2,
  135340. NULL,
  135341. 0
  135342. };
  135343. static long _huff_lengthlist__44c1_s_short[] = {
  135344. 6, 8,13,12,13,14,15,16,16, 4, 2, 4, 7, 6, 8,11,
  135345. 13,15,10, 4, 4, 8, 6, 8,11,14,17,11, 5, 6, 5, 6,
  135346. 8,12,14,17,11, 5, 5, 6, 5, 7,10,13,16,12, 6, 7,
  135347. 8, 7, 8,10,13,15,13, 8, 8, 7, 7, 8,10,12,15,15,
  135348. 7, 7, 5, 5, 7, 9,12,14,15, 8, 8, 6, 6, 7, 8,10,
  135349. 11,
  135350. };
  135351. static static_codebook _huff_book__44c1_s_short = {
  135352. 2, 81,
  135353. _huff_lengthlist__44c1_s_short,
  135354. 0, 0, 0, 0, 0,
  135355. NULL,
  135356. NULL,
  135357. NULL,
  135358. NULL,
  135359. 0
  135360. };
  135361. static long _huff_lengthlist__44c1_sm_long[] = {
  135362. 5, 4, 8,10, 9, 9,10,11,12, 4, 2, 5, 6, 6, 8,10,
  135363. 11,13, 8, 4, 6, 8, 7, 9,12,12,14,10, 6, 8, 4, 5,
  135364. 6, 9,11,12, 9, 5, 6, 5, 5, 6, 9,11,11, 9, 7, 9,
  135365. 6, 5, 5, 7,10,10,10, 9,11, 8, 7, 6, 7, 9,11,11,
  135366. 12,13,10,10, 9, 8, 9,11,11,15,15,12,13,11, 9,10,
  135367. 11,
  135368. };
  135369. static static_codebook _huff_book__44c1_sm_long = {
  135370. 2, 81,
  135371. _huff_lengthlist__44c1_sm_long,
  135372. 0, 0, 0, 0, 0,
  135373. NULL,
  135374. NULL,
  135375. NULL,
  135376. NULL,
  135377. 0
  135378. };
  135379. static long _vq_quantlist__44c1_sm_p1_0[] = {
  135380. 1,
  135381. 0,
  135382. 2,
  135383. };
  135384. static long _vq_lengthlist__44c1_sm_p1_0[] = {
  135385. 1, 5, 5, 0, 0, 0, 0, 0, 0, 5, 7, 7, 0, 0, 0, 0,
  135386. 0, 0, 5, 7, 7, 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, 5, 8, 7, 0, 0, 0, 0, 0, 0, 7, 9, 9, 0, 0, 0,
  135391. 0, 0, 0, 7, 8, 9, 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, 5, 7, 7, 0, 0, 0, 0, 0, 0, 7, 9, 8, 0, 0,
  135396. 0, 0, 0, 0, 7, 9, 9, 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, 5, 8, 7, 0, 0, 0, 0,
  135431. 0, 0, 8, 9, 9, 0, 0, 0, 0, 0, 0, 8, 9, 9, 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, 7, 9, 9, 0, 0, 0,
  135436. 0, 0, 0, 9, 9,10, 0, 0, 0, 0, 0, 0, 9,10,10, 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, 7, 9, 9, 0, 0,
  135441. 0, 0, 0, 0, 8,10, 9, 0, 0, 0, 0, 0, 0, 9,10,10,
  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, 5, 7, 8, 0, 0, 0, 0, 0, 0, 8, 9, 9, 0, 0,
  135477. 0, 0, 0, 0, 8, 9, 9, 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, 7, 9, 9, 0, 0, 0, 0, 0, 0, 9,10,10, 0,
  135482. 0, 0, 0, 0, 0, 8, 9,10, 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, 7, 9, 9, 0, 0, 0, 0, 0, 0, 9,10,10,
  135487. 0, 0, 0, 0, 0, 0, 9,10, 9, 0, 0, 0, 0, 0, 0, 0,
  135488. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135489. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135490. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135491. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135492. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135493. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135494. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135495. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135496. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135497. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135498. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135499. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135500. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135501. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135502. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135503. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135504. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135505. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135506. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135507. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135508. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135509. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135510. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135511. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135512. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135513. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135514. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135515. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135516. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135517. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135518. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135519. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135520. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135521. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135522. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135523. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135524. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135525. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135526. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135527. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135528. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135529. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135530. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135531. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135532. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135533. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135534. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135535. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135536. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135537. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135538. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135539. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135540. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135541. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135542. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135543. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135544. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135545. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135546. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135547. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135548. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135549. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135550. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135551. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135552. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135553. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135554. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135555. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135556. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135557. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135558. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135559. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135560. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135561. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135562. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135563. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135564. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135565. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135566. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135567. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135568. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135569. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135570. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135571. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135572. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135573. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135574. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135575. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135576. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135577. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135578. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135579. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135580. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135581. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135582. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135583. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135584. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135585. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135586. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135587. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135588. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135589. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135590. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135591. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135592. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135593. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135594. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135595. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135596. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135597. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135598. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135599. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135600. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135601. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135602. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135603. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135604. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135605. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135606. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135607. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135608. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135609. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135610. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135611. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135612. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135613. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135614. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135615. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135616. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135617. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135618. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135619. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135620. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135621. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135622. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135623. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135624. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135625. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135626. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135627. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135628. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135629. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135630. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135631. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135632. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135633. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135634. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135635. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135636. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135637. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135638. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135639. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135640. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135641. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135642. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135643. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135644. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135645. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135646. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135647. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135648. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135649. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135650. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135651. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135652. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135653. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135654. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135655. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135656. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135657. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135658. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135659. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135660. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135661. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135662. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135663. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135664. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135665. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135666. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135667. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135668. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135669. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135670. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135671. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135672. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135673. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135674. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135675. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135676. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135677. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135678. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135679. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135680. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135681. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135682. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135683. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135684. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135685. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135686. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135687. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135688. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135689. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135690. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135691. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135692. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135693. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135694. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135695. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135696. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135697. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135698. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135699. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135700. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135701. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135702. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135703. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135704. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135705. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135706. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135707. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135708. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135709. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135710. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135711. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135712. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135713. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135714. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135715. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135716. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135717. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135718. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135719. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135720. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135721. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135722. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135723. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135724. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135725. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135726. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135727. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135728. 0, 0, 0, 0, 0, 0, 0, 0, 0, 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, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135732. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135733. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135734. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135735. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135736. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135737. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135738. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135739. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135740. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135741. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135742. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135743. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135744. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135745. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135746. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135747. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135748. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135749. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135750. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135751. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135752. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135753. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135754. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135755. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135756. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135757. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135758. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135759. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135760. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135761. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135762. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135763. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135764. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135765. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135766. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135767. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135768. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135769. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135770. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135771. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135772. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135773. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135774. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135775. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135776. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135777. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135778. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135779. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135780. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135781. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135782. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135783. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135784. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135785. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135786. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135787. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135788. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135789. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135790. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135791. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135792. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135793. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135794. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135795. 0,
  135796. };
  135797. static float _vq_quantthresh__44c1_sm_p1_0[] = {
  135798. -0.5, 0.5,
  135799. };
  135800. static long _vq_quantmap__44c1_sm_p1_0[] = {
  135801. 1, 0, 2,
  135802. };
  135803. static encode_aux_threshmatch _vq_auxt__44c1_sm_p1_0 = {
  135804. _vq_quantthresh__44c1_sm_p1_0,
  135805. _vq_quantmap__44c1_sm_p1_0,
  135806. 3,
  135807. 3
  135808. };
  135809. static static_codebook _44c1_sm_p1_0 = {
  135810. 8, 6561,
  135811. _vq_lengthlist__44c1_sm_p1_0,
  135812. 1, -535822336, 1611661312, 2, 0,
  135813. _vq_quantlist__44c1_sm_p1_0,
  135814. NULL,
  135815. &_vq_auxt__44c1_sm_p1_0,
  135816. NULL,
  135817. 0
  135818. };
  135819. static long _vq_quantlist__44c1_sm_p2_0[] = {
  135820. 2,
  135821. 1,
  135822. 3,
  135823. 0,
  135824. 4,
  135825. };
  135826. static long _vq_lengthlist__44c1_sm_p2_0[] = {
  135827. 2, 3, 4, 6, 6, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135828. 0, 0, 0, 0, 0, 0, 0, 0, 0, 4, 4, 4, 6, 6, 0, 0,
  135829. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135830. 0, 0, 4, 4, 4, 6, 6, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135831. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 6, 6, 6, 9, 9,
  135832. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135833. 0, 0, 0, 0, 6, 6, 7, 9, 9, 0, 0, 0, 0, 0, 0, 0,
  135834. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135835. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135836. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135837. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135838. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135839. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135840. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135841. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135842. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135843. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135844. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135845. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135846. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135847. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135848. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135849. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135850. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135851. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135852. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135853. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135854. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135855. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135856. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135857. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135858. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135859. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135860. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135861. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135862. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135863. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135864. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135865. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135866. 0,
  135867. };
  135868. static float _vq_quantthresh__44c1_sm_p2_0[] = {
  135869. -1.5, -0.5, 0.5, 1.5,
  135870. };
  135871. static long _vq_quantmap__44c1_sm_p2_0[] = {
  135872. 3, 1, 0, 2, 4,
  135873. };
  135874. static encode_aux_threshmatch _vq_auxt__44c1_sm_p2_0 = {
  135875. _vq_quantthresh__44c1_sm_p2_0,
  135876. _vq_quantmap__44c1_sm_p2_0,
  135877. 5,
  135878. 5
  135879. };
  135880. static static_codebook _44c1_sm_p2_0 = {
  135881. 4, 625,
  135882. _vq_lengthlist__44c1_sm_p2_0,
  135883. 1, -533725184, 1611661312, 3, 0,
  135884. _vq_quantlist__44c1_sm_p2_0,
  135885. NULL,
  135886. &_vq_auxt__44c1_sm_p2_0,
  135887. NULL,
  135888. 0
  135889. };
  135890. static long _vq_quantlist__44c1_sm_p3_0[] = {
  135891. 4,
  135892. 3,
  135893. 5,
  135894. 2,
  135895. 6,
  135896. 1,
  135897. 7,
  135898. 0,
  135899. 8,
  135900. };
  135901. static long _vq_lengthlist__44c1_sm_p3_0[] = {
  135902. 1, 3, 3, 7, 7, 0, 0, 0, 0, 0, 5, 5, 6, 6, 0, 0,
  135903. 0, 0, 0, 5, 5, 7, 7, 0, 0, 0, 0, 0, 7, 7, 7, 7,
  135904. 0, 0, 0, 0, 0, 0, 0, 7, 7, 0, 0, 0, 0, 0, 0, 0,
  135905. 8, 9, 0, 0, 0, 0, 0, 0, 0, 8, 8, 0, 0, 0, 0, 0,
  135906. 0, 0,10,10, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135907. 0,
  135908. };
  135909. static float _vq_quantthresh__44c1_sm_p3_0[] = {
  135910. -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5, 3.5,
  135911. };
  135912. static long _vq_quantmap__44c1_sm_p3_0[] = {
  135913. 7, 5, 3, 1, 0, 2, 4, 6,
  135914. 8,
  135915. };
  135916. static encode_aux_threshmatch _vq_auxt__44c1_sm_p3_0 = {
  135917. _vq_quantthresh__44c1_sm_p3_0,
  135918. _vq_quantmap__44c1_sm_p3_0,
  135919. 9,
  135920. 9
  135921. };
  135922. static static_codebook _44c1_sm_p3_0 = {
  135923. 2, 81,
  135924. _vq_lengthlist__44c1_sm_p3_0,
  135925. 1, -531628032, 1611661312, 4, 0,
  135926. _vq_quantlist__44c1_sm_p3_0,
  135927. NULL,
  135928. &_vq_auxt__44c1_sm_p3_0,
  135929. NULL,
  135930. 0
  135931. };
  135932. static long _vq_quantlist__44c1_sm_p4_0[] = {
  135933. 4,
  135934. 3,
  135935. 5,
  135936. 2,
  135937. 6,
  135938. 1,
  135939. 7,
  135940. 0,
  135941. 8,
  135942. };
  135943. static long _vq_lengthlist__44c1_sm_p4_0[] = {
  135944. 1, 3, 3, 6, 6, 7, 7, 9, 9, 0, 6, 6, 7, 7, 8, 8,
  135945. 9, 9, 0, 6, 6, 7, 7, 8, 8, 9, 9, 0, 7, 7, 8, 8,
  135946. 8, 8,10,10, 0, 0, 0, 8, 8, 8, 8,10,10, 0, 0, 0,
  135947. 8, 8, 9, 9,11,11, 0, 0, 0, 9, 9, 9, 9,11,11, 0,
  135948. 0, 0,10,10,10,10,11,11, 0, 0, 0, 0, 0, 9, 9,11,
  135949. 11,
  135950. };
  135951. static float _vq_quantthresh__44c1_sm_p4_0[] = {
  135952. -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5, 3.5,
  135953. };
  135954. static long _vq_quantmap__44c1_sm_p4_0[] = {
  135955. 7, 5, 3, 1, 0, 2, 4, 6,
  135956. 8,
  135957. };
  135958. static encode_aux_threshmatch _vq_auxt__44c1_sm_p4_0 = {
  135959. _vq_quantthresh__44c1_sm_p4_0,
  135960. _vq_quantmap__44c1_sm_p4_0,
  135961. 9,
  135962. 9
  135963. };
  135964. static static_codebook _44c1_sm_p4_0 = {
  135965. 2, 81,
  135966. _vq_lengthlist__44c1_sm_p4_0,
  135967. 1, -531628032, 1611661312, 4, 0,
  135968. _vq_quantlist__44c1_sm_p4_0,
  135969. NULL,
  135970. &_vq_auxt__44c1_sm_p4_0,
  135971. NULL,
  135972. 0
  135973. };
  135974. static long _vq_quantlist__44c1_sm_p5_0[] = {
  135975. 8,
  135976. 7,
  135977. 9,
  135978. 6,
  135979. 10,
  135980. 5,
  135981. 11,
  135982. 4,
  135983. 12,
  135984. 3,
  135985. 13,
  135986. 2,
  135987. 14,
  135988. 1,
  135989. 15,
  135990. 0,
  135991. 16,
  135992. };
  135993. static long _vq_lengthlist__44c1_sm_p5_0[] = {
  135994. 2, 3, 3, 6, 6, 7, 7, 8, 8, 8, 8, 9, 9,10,10,11,
  135995. 11, 0, 5, 5, 6, 6, 8, 8, 9, 9, 9, 9,10,10,10,10,
  135996. 11,11, 0, 5, 5, 6, 6, 8, 8, 9, 9, 9, 9,10,10,10,
  135997. 10,11,11, 0, 7, 7, 7, 7, 8, 8, 9, 9, 9, 9,10,10,
  135998. 11,11,12,12, 0, 0, 0, 7, 7, 8, 8, 9, 9, 9, 9,10,
  135999. 10,11,11,12,12, 0, 0, 0, 8, 8, 8, 8, 9, 9,10,10,
  136000. 10,11,11,11,12,12, 0, 0, 0, 8, 8, 8, 8, 9, 9,10,
  136001. 10,10,10,11,11,12,12, 0, 0, 0, 9, 9, 9, 9,10,10,
  136002. 10,10,11,11,12,12,12,12, 0, 0, 0, 0, 0, 9, 9,10,
  136003. 10,10,10,11,11,12,12,13,13, 0, 0, 0, 0, 0, 9, 9,
  136004. 9, 9,10,10,11,11,12,12,13,13, 0, 0, 0, 0, 0, 9,
  136005. 9, 9, 9,10,10,11,11,12,12,13,13, 0, 0, 0, 0, 0,
  136006. 9, 9,10,10,11,11,12,12,12,12,13,13, 0, 0, 0, 0,
  136007. 0, 0, 0,10,10,11,11,12,12,12,12,13,13, 0, 0, 0,
  136008. 0, 0, 0, 0,11,11,11,11,12,12,13,13,13,13, 0, 0,
  136009. 0, 0, 0, 0, 0,11,11,11,11,12,12,13,13,13,13, 0,
  136010. 0, 0, 0, 0, 0, 0,11,11,12,12,12,12,13,13,14,14,
  136011. 0, 0, 0, 0, 0, 0, 0, 0, 0,12,12,12,12,13,13,14,
  136012. 14,
  136013. };
  136014. static float _vq_quantthresh__44c1_sm_p5_0[] = {
  136015. -7.5, -6.5, -5.5, -4.5, -3.5, -2.5, -1.5, -0.5,
  136016. 0.5, 1.5, 2.5, 3.5, 4.5, 5.5, 6.5, 7.5,
  136017. };
  136018. static long _vq_quantmap__44c1_sm_p5_0[] = {
  136019. 15, 13, 11, 9, 7, 5, 3, 1,
  136020. 0, 2, 4, 6, 8, 10, 12, 14,
  136021. 16,
  136022. };
  136023. static encode_aux_threshmatch _vq_auxt__44c1_sm_p5_0 = {
  136024. _vq_quantthresh__44c1_sm_p5_0,
  136025. _vq_quantmap__44c1_sm_p5_0,
  136026. 17,
  136027. 17
  136028. };
  136029. static static_codebook _44c1_sm_p5_0 = {
  136030. 2, 289,
  136031. _vq_lengthlist__44c1_sm_p5_0,
  136032. 1, -529530880, 1611661312, 5, 0,
  136033. _vq_quantlist__44c1_sm_p5_0,
  136034. NULL,
  136035. &_vq_auxt__44c1_sm_p5_0,
  136036. NULL,
  136037. 0
  136038. };
  136039. static long _vq_quantlist__44c1_sm_p6_0[] = {
  136040. 1,
  136041. 0,
  136042. 2,
  136043. };
  136044. static long _vq_lengthlist__44c1_sm_p6_0[] = {
  136045. 1, 4, 4, 7, 6, 6, 7, 6, 6, 4, 7, 7,10, 9, 9,11,
  136046. 9, 9, 4, 7, 7,10, 9, 9,11, 9, 9, 7,10,10,10,11,
  136047. 11,11,10,10, 6, 9, 9,11,11,10,11,10,10, 6, 9, 9,
  136048. 11,10,11,11,10,10, 7,11,11,11,11,11,11,11,11, 6,
  136049. 9, 9,11,10,10,11,11,10, 6, 9, 9,10,10,10,11,10,
  136050. 11,
  136051. };
  136052. static float _vq_quantthresh__44c1_sm_p6_0[] = {
  136053. -5.5, 5.5,
  136054. };
  136055. static long _vq_quantmap__44c1_sm_p6_0[] = {
  136056. 1, 0, 2,
  136057. };
  136058. static encode_aux_threshmatch _vq_auxt__44c1_sm_p6_0 = {
  136059. _vq_quantthresh__44c1_sm_p6_0,
  136060. _vq_quantmap__44c1_sm_p6_0,
  136061. 3,
  136062. 3
  136063. };
  136064. static static_codebook _44c1_sm_p6_0 = {
  136065. 4, 81,
  136066. _vq_lengthlist__44c1_sm_p6_0,
  136067. 1, -529137664, 1618345984, 2, 0,
  136068. _vq_quantlist__44c1_sm_p6_0,
  136069. NULL,
  136070. &_vq_auxt__44c1_sm_p6_0,
  136071. NULL,
  136072. 0
  136073. };
  136074. static long _vq_quantlist__44c1_sm_p6_1[] = {
  136075. 5,
  136076. 4,
  136077. 6,
  136078. 3,
  136079. 7,
  136080. 2,
  136081. 8,
  136082. 1,
  136083. 9,
  136084. 0,
  136085. 10,
  136086. };
  136087. static long _vq_lengthlist__44c1_sm_p6_1[] = {
  136088. 2, 4, 4, 6, 6, 7, 7, 7, 7, 8, 8,10, 5, 5, 6, 6,
  136089. 7, 7, 8, 8, 8, 8,10, 5, 5, 6, 6, 7, 7, 8, 8, 8,
  136090. 8,10, 7, 7, 7, 7, 8, 8, 8, 8, 8, 8,10,10,10, 7,
  136091. 7, 7, 7, 8, 8, 8, 8,10,10,10, 7, 7, 8, 8, 8, 8,
  136092. 8, 8,10,10,10, 7, 7, 8, 8, 8, 8, 8, 8,10,10,10,
  136093. 8, 8, 8, 8, 8, 8, 9, 8,10,10,10,10,10, 8, 8, 8,
  136094. 8, 8, 8,10,10,10,10,10, 9, 9, 8, 8, 8, 8,10,10,
  136095. 10,10,10, 8, 8, 8, 8, 8, 8,
  136096. };
  136097. static float _vq_quantthresh__44c1_sm_p6_1[] = {
  136098. -4.5, -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5,
  136099. 3.5, 4.5,
  136100. };
  136101. static long _vq_quantmap__44c1_sm_p6_1[] = {
  136102. 9, 7, 5, 3, 1, 0, 2, 4,
  136103. 6, 8, 10,
  136104. };
  136105. static encode_aux_threshmatch _vq_auxt__44c1_sm_p6_1 = {
  136106. _vq_quantthresh__44c1_sm_p6_1,
  136107. _vq_quantmap__44c1_sm_p6_1,
  136108. 11,
  136109. 11
  136110. };
  136111. static static_codebook _44c1_sm_p6_1 = {
  136112. 2, 121,
  136113. _vq_lengthlist__44c1_sm_p6_1,
  136114. 1, -531365888, 1611661312, 4, 0,
  136115. _vq_quantlist__44c1_sm_p6_1,
  136116. NULL,
  136117. &_vq_auxt__44c1_sm_p6_1,
  136118. NULL,
  136119. 0
  136120. };
  136121. static long _vq_quantlist__44c1_sm_p7_0[] = {
  136122. 6,
  136123. 5,
  136124. 7,
  136125. 4,
  136126. 8,
  136127. 3,
  136128. 9,
  136129. 2,
  136130. 10,
  136131. 1,
  136132. 11,
  136133. 0,
  136134. 12,
  136135. };
  136136. static long _vq_lengthlist__44c1_sm_p7_0[] = {
  136137. 1, 4, 4, 6, 6, 7, 7, 7, 7, 8, 8, 9, 9, 7, 5, 5,
  136138. 7, 7, 8, 8, 8, 8, 9, 9,10,10, 7, 5, 6, 7, 7, 8,
  136139. 8, 8, 8, 9, 9,11,10, 0, 8, 8, 8, 8, 9, 9, 9, 9,
  136140. 10,10,11,11, 0, 8, 8, 8, 8, 9, 9, 9, 9,10,10,11,
  136141. 11, 0,12,12, 9, 9,10,10,10,10,11,11,11,11, 0,13,
  136142. 13, 9, 9, 9, 9,10,10,11,11,12,12, 0, 0, 0, 9,10,
  136143. 9,10,11,11,12,11,13,12, 0, 0, 0,10,10, 9, 9,11,
  136144. 11,12,12,13,12, 0, 0, 0,13,13,10,10,11,11,12,12,
  136145. 13,13, 0, 0, 0,14,14,10,10,11,11,12,12,13,13, 0,
  136146. 0, 0, 0, 0,11,12,11,11,12,13,14,13, 0, 0, 0, 0,
  136147. 0,12,12,11,11,13,12,14,13,
  136148. };
  136149. static float _vq_quantthresh__44c1_sm_p7_0[] = {
  136150. -27.5, -22.5, -17.5, -12.5, -7.5, -2.5, 2.5, 7.5,
  136151. 12.5, 17.5, 22.5, 27.5,
  136152. };
  136153. static long _vq_quantmap__44c1_sm_p7_0[] = {
  136154. 11, 9, 7, 5, 3, 1, 0, 2,
  136155. 4, 6, 8, 10, 12,
  136156. };
  136157. static encode_aux_threshmatch _vq_auxt__44c1_sm_p7_0 = {
  136158. _vq_quantthresh__44c1_sm_p7_0,
  136159. _vq_quantmap__44c1_sm_p7_0,
  136160. 13,
  136161. 13
  136162. };
  136163. static static_codebook _44c1_sm_p7_0 = {
  136164. 2, 169,
  136165. _vq_lengthlist__44c1_sm_p7_0,
  136166. 1, -526516224, 1616117760, 4, 0,
  136167. _vq_quantlist__44c1_sm_p7_0,
  136168. NULL,
  136169. &_vq_auxt__44c1_sm_p7_0,
  136170. NULL,
  136171. 0
  136172. };
  136173. static long _vq_quantlist__44c1_sm_p7_1[] = {
  136174. 2,
  136175. 1,
  136176. 3,
  136177. 0,
  136178. 4,
  136179. };
  136180. static long _vq_lengthlist__44c1_sm_p7_1[] = {
  136181. 2, 4, 4, 4, 5, 6, 5, 5, 5, 5, 6, 5, 5, 5, 5, 6,
  136182. 5, 5, 5, 5, 6, 6, 6, 5, 5,
  136183. };
  136184. static float _vq_quantthresh__44c1_sm_p7_1[] = {
  136185. -1.5, -0.5, 0.5, 1.5,
  136186. };
  136187. static long _vq_quantmap__44c1_sm_p7_1[] = {
  136188. 3, 1, 0, 2, 4,
  136189. };
  136190. static encode_aux_threshmatch _vq_auxt__44c1_sm_p7_1 = {
  136191. _vq_quantthresh__44c1_sm_p7_1,
  136192. _vq_quantmap__44c1_sm_p7_1,
  136193. 5,
  136194. 5
  136195. };
  136196. static static_codebook _44c1_sm_p7_1 = {
  136197. 2, 25,
  136198. _vq_lengthlist__44c1_sm_p7_1,
  136199. 1, -533725184, 1611661312, 3, 0,
  136200. _vq_quantlist__44c1_sm_p7_1,
  136201. NULL,
  136202. &_vq_auxt__44c1_sm_p7_1,
  136203. NULL,
  136204. 0
  136205. };
  136206. static long _vq_quantlist__44c1_sm_p8_0[] = {
  136207. 6,
  136208. 5,
  136209. 7,
  136210. 4,
  136211. 8,
  136212. 3,
  136213. 9,
  136214. 2,
  136215. 10,
  136216. 1,
  136217. 11,
  136218. 0,
  136219. 12,
  136220. };
  136221. static long _vq_lengthlist__44c1_sm_p8_0[] = {
  136222. 1, 3, 3,13,13,13,13,13,13,13,13,13,13, 3, 6, 6,
  136223. 13,13,13,13,13,13,13,13,13,13, 4, 8, 7,13,13,13,
  136224. 13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,
  136225. 13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,
  136226. 13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,
  136227. 13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,
  136228. 13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,
  136229. 13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,
  136230. 13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,
  136231. 13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,
  136232. 13,13,13,13,13,13,13,13,13,
  136233. };
  136234. static float _vq_quantthresh__44c1_sm_p8_0[] = {
  136235. -1215.5, -994.5, -773.5, -552.5, -331.5, -110.5, 110.5, 331.5,
  136236. 552.5, 773.5, 994.5, 1215.5,
  136237. };
  136238. static long _vq_quantmap__44c1_sm_p8_0[] = {
  136239. 11, 9, 7, 5, 3, 1, 0, 2,
  136240. 4, 6, 8, 10, 12,
  136241. };
  136242. static encode_aux_threshmatch _vq_auxt__44c1_sm_p8_0 = {
  136243. _vq_quantthresh__44c1_sm_p8_0,
  136244. _vq_quantmap__44c1_sm_p8_0,
  136245. 13,
  136246. 13
  136247. };
  136248. static static_codebook _44c1_sm_p8_0 = {
  136249. 2, 169,
  136250. _vq_lengthlist__44c1_sm_p8_0,
  136251. 1, -514541568, 1627103232, 4, 0,
  136252. _vq_quantlist__44c1_sm_p8_0,
  136253. NULL,
  136254. &_vq_auxt__44c1_sm_p8_0,
  136255. NULL,
  136256. 0
  136257. };
  136258. static long _vq_quantlist__44c1_sm_p8_1[] = {
  136259. 6,
  136260. 5,
  136261. 7,
  136262. 4,
  136263. 8,
  136264. 3,
  136265. 9,
  136266. 2,
  136267. 10,
  136268. 1,
  136269. 11,
  136270. 0,
  136271. 12,
  136272. };
  136273. static long _vq_lengthlist__44c1_sm_p8_1[] = {
  136274. 1, 4, 4, 6, 6, 7, 7, 9, 9,10,11,12,12, 6, 5, 5,
  136275. 7, 7, 8, 7,10,10,11,11,12,12, 6, 5, 5, 7, 7, 8,
  136276. 8,10,10,11,11,12,12,16, 7, 7, 8, 8, 9, 9,11,11,
  136277. 12,12,13,13,17, 7, 7, 8, 7, 9, 9,11,10,12,12,13,
  136278. 13,19,11,10, 8, 8,10,10,11,11,12,12,13,13,19,11,
  136279. 11, 9, 7,11,10,11,11,12,12,13,12,19,19,19,10,10,
  136280. 10,10,11,12,12,12,13,14,18,19,19,11, 9,11, 9,13,
  136281. 12,12,12,13,13,19,20,19,13,15,11,11,12,12,13,13,
  136282. 14,13,18,19,20,15,13,12,10,13,10,13,13,13,14,20,
  136283. 20,20,20,20,13,14,12,12,13,12,13,13,20,20,20,20,
  136284. 20,13,12,12,12,14,12,14,13,
  136285. };
  136286. static float _vq_quantthresh__44c1_sm_p8_1[] = {
  136287. -93.5, -76.5, -59.5, -42.5, -25.5, -8.5, 8.5, 25.5,
  136288. 42.5, 59.5, 76.5, 93.5,
  136289. };
  136290. static long _vq_quantmap__44c1_sm_p8_1[] = {
  136291. 11, 9, 7, 5, 3, 1, 0, 2,
  136292. 4, 6, 8, 10, 12,
  136293. };
  136294. static encode_aux_threshmatch _vq_auxt__44c1_sm_p8_1 = {
  136295. _vq_quantthresh__44c1_sm_p8_1,
  136296. _vq_quantmap__44c1_sm_p8_1,
  136297. 13,
  136298. 13
  136299. };
  136300. static static_codebook _44c1_sm_p8_1 = {
  136301. 2, 169,
  136302. _vq_lengthlist__44c1_sm_p8_1,
  136303. 1, -522616832, 1620115456, 4, 0,
  136304. _vq_quantlist__44c1_sm_p8_1,
  136305. NULL,
  136306. &_vq_auxt__44c1_sm_p8_1,
  136307. NULL,
  136308. 0
  136309. };
  136310. static long _vq_quantlist__44c1_sm_p8_2[] = {
  136311. 8,
  136312. 7,
  136313. 9,
  136314. 6,
  136315. 10,
  136316. 5,
  136317. 11,
  136318. 4,
  136319. 12,
  136320. 3,
  136321. 13,
  136322. 2,
  136323. 14,
  136324. 1,
  136325. 15,
  136326. 0,
  136327. 16,
  136328. };
  136329. static long _vq_lengthlist__44c1_sm_p8_2[] = {
  136330. 2, 5, 5, 6, 6, 7, 6, 7, 7, 8, 8, 8, 8, 8, 8, 8,
  136331. 8,10, 6, 6, 7, 7, 7, 7, 8, 8, 9, 9, 9, 9, 9, 9,
  136332. 9, 9,10, 6, 6, 7, 7, 8, 8, 8, 8, 9, 9, 9, 9, 9,
  136333. 9, 9, 9,10, 7, 7, 7, 7, 8, 8, 8, 9, 9, 9, 9, 9,
  136334. 9, 9, 9, 9,10,10,10, 7, 7, 8, 8, 9, 9, 9, 9, 9,
  136335. 9, 9, 9, 9, 9,10,11,11, 8, 8, 8, 8, 9, 9, 9, 9,
  136336. 9, 9,10,10, 9,10,10,10,10, 8, 8, 8, 8, 9, 9, 9,
  136337. 9, 9, 9, 9, 9,10,10,11,10,10, 8, 8, 9, 9, 9, 9,
  136338. 9, 9, 9, 9, 9, 9,10, 9,10,10,10,11,11, 8, 8, 9,
  136339. 9, 9, 9, 9, 9, 9, 9, 9, 9,11,11,11,11,11, 9, 9,
  136340. 9, 9, 9, 9, 9, 9,10, 9,10, 9,11,11,11,11,11, 9,
  136341. 8, 9, 9, 9, 9, 9, 9, 9,10,10, 9,11,11,10,11,11,
  136342. 9, 9, 9, 9, 9, 9, 9, 9, 9,10,10, 9,11,11,11,11,
  136343. 11,11,11, 9, 9,10, 9, 9, 9, 9,10, 9,10,10,11,10,
  136344. 11,11,11,11, 9,10,10,10, 9, 9, 9, 9, 9, 9,10,11,
  136345. 11,11,11,11,11, 9, 9, 9, 9, 9, 9, 9, 9,10, 9,11,
  136346. 11,10,11,11,11,11,10,10, 9, 9, 9, 9, 9, 9,10, 9,
  136347. 10,11,10,11,11,11,11,11,11, 9, 9,10, 9, 9, 9, 9,
  136348. 9,
  136349. };
  136350. static float _vq_quantthresh__44c1_sm_p8_2[] = {
  136351. -7.5, -6.5, -5.5, -4.5, -3.5, -2.5, -1.5, -0.5,
  136352. 0.5, 1.5, 2.5, 3.5, 4.5, 5.5, 6.5, 7.5,
  136353. };
  136354. static long _vq_quantmap__44c1_sm_p8_2[] = {
  136355. 15, 13, 11, 9, 7, 5, 3, 1,
  136356. 0, 2, 4, 6, 8, 10, 12, 14,
  136357. 16,
  136358. };
  136359. static encode_aux_threshmatch _vq_auxt__44c1_sm_p8_2 = {
  136360. _vq_quantthresh__44c1_sm_p8_2,
  136361. _vq_quantmap__44c1_sm_p8_2,
  136362. 17,
  136363. 17
  136364. };
  136365. static static_codebook _44c1_sm_p8_2 = {
  136366. 2, 289,
  136367. _vq_lengthlist__44c1_sm_p8_2,
  136368. 1, -529530880, 1611661312, 5, 0,
  136369. _vq_quantlist__44c1_sm_p8_2,
  136370. NULL,
  136371. &_vq_auxt__44c1_sm_p8_2,
  136372. NULL,
  136373. 0
  136374. };
  136375. static long _huff_lengthlist__44c1_sm_short[] = {
  136376. 4, 7,13,14,14,15,16,18,18, 4, 2, 5, 8, 7, 9,12,
  136377. 15,15,10, 4, 5,10, 6, 8,11,15,17,12, 5, 7, 5, 6,
  136378. 8,11,14,17,11, 5, 6, 6, 5, 6, 9,13,17,12, 6, 7,
  136379. 6, 5, 6, 8,12,14,14, 7, 8, 6, 6, 7, 9,11,14,14,
  136380. 8, 9, 6, 5, 6, 9,11,13,16,10,10, 7, 6, 7, 8,10,
  136381. 11,
  136382. };
  136383. static static_codebook _huff_book__44c1_sm_short = {
  136384. 2, 81,
  136385. _huff_lengthlist__44c1_sm_short,
  136386. 0, 0, 0, 0, 0,
  136387. NULL,
  136388. NULL,
  136389. NULL,
  136390. NULL,
  136391. 0
  136392. };
  136393. static long _huff_lengthlist__44cn1_s_long[] = {
  136394. 4, 4, 7, 8, 7, 8,10,12,17, 3, 1, 6, 6, 7, 8,10,
  136395. 12,15, 7, 6, 9, 9, 9,11,12,14,17, 8, 6, 9, 6, 7,
  136396. 9,11,13,17, 7, 6, 9, 7, 7, 8, 9,12,15, 8, 8,10,
  136397. 8, 7, 7, 7,10,14, 9,10,12,10, 8, 8, 8,10,14,11,
  136398. 13,15,13,12,11,11,12,16,17,18,18,19,20,18,16,16,
  136399. 20,
  136400. };
  136401. static static_codebook _huff_book__44cn1_s_long = {
  136402. 2, 81,
  136403. _huff_lengthlist__44cn1_s_long,
  136404. 0, 0, 0, 0, 0,
  136405. NULL,
  136406. NULL,
  136407. NULL,
  136408. NULL,
  136409. 0
  136410. };
  136411. static long _vq_quantlist__44cn1_s_p1_0[] = {
  136412. 1,
  136413. 0,
  136414. 2,
  136415. };
  136416. static long _vq_lengthlist__44cn1_s_p1_0[] = {
  136417. 1, 4, 4, 0, 0, 0, 0, 0, 0, 5, 7, 7, 0, 0, 0, 0,
  136418. 0, 0, 5, 7, 7, 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, 5, 8, 8, 0, 0, 0, 0, 0, 0, 8, 9, 9, 0, 0, 0,
  136423. 0, 0, 0, 7, 9,10, 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, 5, 8, 8, 0, 0, 0, 0, 0, 0, 7,10, 9, 0, 0,
  136428. 0, 0, 0, 0, 8,10, 9, 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, 5, 8, 8, 0, 0, 0, 0,
  136463. 0, 0, 8,10,10, 0, 0, 0, 0, 0, 0, 8, 9,10, 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, 7,10,10, 0, 0, 0,
  136468. 0, 0, 0, 9, 9,11, 0, 0, 0, 0, 0, 0,10,11,11, 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, 7,10,10, 0, 0,
  136473. 0, 0, 0, 0, 9,11, 9, 0, 0, 0, 0, 0, 0,10,11,11,
  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, 5, 8, 8, 0, 0, 0, 0, 0, 0, 8,10,10, 0, 0,
  136509. 0, 0, 0, 0, 8,10,10, 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, 7,10,10, 0, 0, 0, 0, 0, 0,10,11,11, 0,
  136514. 0, 0, 0, 0, 0, 9, 9,11, 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, 7,10,10, 0, 0, 0, 0, 0, 0,10,11,11,
  136519. 0, 0, 0, 0, 0, 0, 9,11, 9, 0, 0, 0, 0, 0, 0, 0,
  136520. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136521. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136522. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136523. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136524. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136525. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136526. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136527. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136528. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136529. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136530. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136531. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136532. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136533. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136534. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136535. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136536. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136537. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136538. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136539. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136540. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136541. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136542. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136543. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136544. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136545. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136546. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136547. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136548. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136549. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136550. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136551. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136552. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136553. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136554. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136555. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136556. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136557. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136558. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136559. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136560. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136561. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136562. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136563. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136564. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136565. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136566. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136567. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136568. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136569. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136570. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136571. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136572. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136573. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136574. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136575. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136576. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136577. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136578. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136579. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136580. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136581. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136582. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136583. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136584. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136585. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136586. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136587. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136588. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136589. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136590. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136591. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136592. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136593. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136594. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136595. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136596. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136597. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136598. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136599. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136600. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136601. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136602. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136603. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136604. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136605. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136606. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136607. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136608. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136609. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136610. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136611. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136612. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136613. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136614. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136615. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136616. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136617. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136618. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136619. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136620. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136621. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136622. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136623. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136624. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136625. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136626. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136627. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136628. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136629. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136630. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136631. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136632. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136633. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136634. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136635. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136636. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136637. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136638. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136639. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136640. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136641. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136642. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136643. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136644. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136645. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136646. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136647. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136648. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136649. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136650. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136651. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136652. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136653. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136654. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136655. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136656. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136657. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136658. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136659. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136660. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136661. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136662. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136663. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136664. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136665. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136666. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136667. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136668. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136669. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136670. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136671. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136672. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136673. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136674. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136675. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136676. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136677. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136678. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136679. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136680. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136681. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136682. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136683. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136684. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136685. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136686. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136687. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136688. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136689. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136690. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136691. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136692. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136693. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136694. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136695. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136696. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136697. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136698. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136699. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136700. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136701. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136702. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136703. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136704. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136705. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136706. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136707. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136708. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136709. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136710. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136711. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136712. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136713. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136714. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136715. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136716. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136717. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136718. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136719. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136720. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136721. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136722. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136723. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136724. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136725. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136726. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136727. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136728. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136729. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136730. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136731. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136732. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136733. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136734. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136735. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136736. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136737. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136738. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136739. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136740. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136741. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136742. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136743. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136744. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136745. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136746. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136747. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136748. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136749. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136750. 0, 0, 0, 0, 0, 0, 0, 0, 0, 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, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136783. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136784. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136785. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136786. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136787. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136788. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136789. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136790. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136791. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136792. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136793. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136794. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136795. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136796. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136797. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136798. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136799. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136800. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136801. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136802. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136803. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136804. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136805. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136806. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136807. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136808. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136809. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136810. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136811. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136812. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136813. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136814. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136815. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136816. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136817. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136818. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136819. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136820. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136821. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136822. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136823. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136824. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136825. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136826. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136827. 0,
  136828. };
  136829. static float _vq_quantthresh__44cn1_s_p1_0[] = {
  136830. -0.5, 0.5,
  136831. };
  136832. static long _vq_quantmap__44cn1_s_p1_0[] = {
  136833. 1, 0, 2,
  136834. };
  136835. static encode_aux_threshmatch _vq_auxt__44cn1_s_p1_0 = {
  136836. _vq_quantthresh__44cn1_s_p1_0,
  136837. _vq_quantmap__44cn1_s_p1_0,
  136838. 3,
  136839. 3
  136840. };
  136841. static static_codebook _44cn1_s_p1_0 = {
  136842. 8, 6561,
  136843. _vq_lengthlist__44cn1_s_p1_0,
  136844. 1, -535822336, 1611661312, 2, 0,
  136845. _vq_quantlist__44cn1_s_p1_0,
  136846. NULL,
  136847. &_vq_auxt__44cn1_s_p1_0,
  136848. NULL,
  136849. 0
  136850. };
  136851. static long _vq_quantlist__44cn1_s_p2_0[] = {
  136852. 2,
  136853. 1,
  136854. 3,
  136855. 0,
  136856. 4,
  136857. };
  136858. static long _vq_lengthlist__44cn1_s_p2_0[] = {
  136859. 1, 4, 4, 7, 6, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136860. 0, 0, 0, 0, 0, 0, 0, 0, 0, 4, 5, 5, 7, 7, 0, 0,
  136861. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136862. 0, 0, 4, 5, 5, 7, 7, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136863. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 6, 7, 7, 9, 9,
  136864. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136865. 0, 0, 0, 0, 6, 7, 7, 9, 9, 0, 0, 0, 0, 0, 0, 0,
  136866. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136867. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136868. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136869. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136870. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136871. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136872. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136873. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136874. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136875. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136876. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136877. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136878. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136879. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136880. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136881. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136882. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136883. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136884. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136885. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136886. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136887. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136888. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136889. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136890. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136891. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136892. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136893. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136894. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136895. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136896. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136897. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136898. 0,
  136899. };
  136900. static float _vq_quantthresh__44cn1_s_p2_0[] = {
  136901. -1.5, -0.5, 0.5, 1.5,
  136902. };
  136903. static long _vq_quantmap__44cn1_s_p2_0[] = {
  136904. 3, 1, 0, 2, 4,
  136905. };
  136906. static encode_aux_threshmatch _vq_auxt__44cn1_s_p2_0 = {
  136907. _vq_quantthresh__44cn1_s_p2_0,
  136908. _vq_quantmap__44cn1_s_p2_0,
  136909. 5,
  136910. 5
  136911. };
  136912. static static_codebook _44cn1_s_p2_0 = {
  136913. 4, 625,
  136914. _vq_lengthlist__44cn1_s_p2_0,
  136915. 1, -533725184, 1611661312, 3, 0,
  136916. _vq_quantlist__44cn1_s_p2_0,
  136917. NULL,
  136918. &_vq_auxt__44cn1_s_p2_0,
  136919. NULL,
  136920. 0
  136921. };
  136922. static long _vq_quantlist__44cn1_s_p3_0[] = {
  136923. 4,
  136924. 3,
  136925. 5,
  136926. 2,
  136927. 6,
  136928. 1,
  136929. 7,
  136930. 0,
  136931. 8,
  136932. };
  136933. static long _vq_lengthlist__44cn1_s_p3_0[] = {
  136934. 1, 2, 3, 7, 7, 0, 0, 0, 0, 0, 0, 0, 6, 6, 0, 0,
  136935. 0, 0, 0, 0, 0, 6, 6, 0, 0, 0, 0, 0, 0, 0, 7, 7,
  136936. 0, 0, 0, 0, 0, 0, 0, 7, 7, 0, 0, 0, 0, 0, 0, 0,
  136937. 9, 8, 0, 0, 0, 0, 0, 0, 0, 8, 8, 0, 0, 0, 0, 0,
  136938. 0, 0,10,10, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136939. 0,
  136940. };
  136941. static float _vq_quantthresh__44cn1_s_p3_0[] = {
  136942. -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5, 3.5,
  136943. };
  136944. static long _vq_quantmap__44cn1_s_p3_0[] = {
  136945. 7, 5, 3, 1, 0, 2, 4, 6,
  136946. 8,
  136947. };
  136948. static encode_aux_threshmatch _vq_auxt__44cn1_s_p3_0 = {
  136949. _vq_quantthresh__44cn1_s_p3_0,
  136950. _vq_quantmap__44cn1_s_p3_0,
  136951. 9,
  136952. 9
  136953. };
  136954. static static_codebook _44cn1_s_p3_0 = {
  136955. 2, 81,
  136956. _vq_lengthlist__44cn1_s_p3_0,
  136957. 1, -531628032, 1611661312, 4, 0,
  136958. _vq_quantlist__44cn1_s_p3_0,
  136959. NULL,
  136960. &_vq_auxt__44cn1_s_p3_0,
  136961. NULL,
  136962. 0
  136963. };
  136964. static long _vq_quantlist__44cn1_s_p4_0[] = {
  136965. 4,
  136966. 3,
  136967. 5,
  136968. 2,
  136969. 6,
  136970. 1,
  136971. 7,
  136972. 0,
  136973. 8,
  136974. };
  136975. static long _vq_lengthlist__44cn1_s_p4_0[] = {
  136976. 1, 3, 3, 6, 6, 6, 6, 8, 8, 0, 0, 0, 6, 6, 7, 7,
  136977. 9, 9, 0, 0, 0, 6, 6, 7, 7, 9, 9, 0, 0, 0, 7, 7,
  136978. 8, 8,10,10, 0, 0, 0, 7, 7, 8, 8,10,10, 0, 0, 0,
  136979. 9, 9, 9, 9,10,10, 0, 0, 0, 9, 9, 9, 9,10,10, 0,
  136980. 0, 0,10,10,10,10,11,11, 0, 0, 0, 0, 0,10,10,11,
  136981. 11,
  136982. };
  136983. static float _vq_quantthresh__44cn1_s_p4_0[] = {
  136984. -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5, 3.5,
  136985. };
  136986. static long _vq_quantmap__44cn1_s_p4_0[] = {
  136987. 7, 5, 3, 1, 0, 2, 4, 6,
  136988. 8,
  136989. };
  136990. static encode_aux_threshmatch _vq_auxt__44cn1_s_p4_0 = {
  136991. _vq_quantthresh__44cn1_s_p4_0,
  136992. _vq_quantmap__44cn1_s_p4_0,
  136993. 9,
  136994. 9
  136995. };
  136996. static static_codebook _44cn1_s_p4_0 = {
  136997. 2, 81,
  136998. _vq_lengthlist__44cn1_s_p4_0,
  136999. 1, -531628032, 1611661312, 4, 0,
  137000. _vq_quantlist__44cn1_s_p4_0,
  137001. NULL,
  137002. &_vq_auxt__44cn1_s_p4_0,
  137003. NULL,
  137004. 0
  137005. };
  137006. static long _vq_quantlist__44cn1_s_p5_0[] = {
  137007. 8,
  137008. 7,
  137009. 9,
  137010. 6,
  137011. 10,
  137012. 5,
  137013. 11,
  137014. 4,
  137015. 12,
  137016. 3,
  137017. 13,
  137018. 2,
  137019. 14,
  137020. 1,
  137021. 15,
  137022. 0,
  137023. 16,
  137024. };
  137025. static long _vq_lengthlist__44cn1_s_p5_0[] = {
  137026. 1, 4, 3, 6, 6, 7, 7, 8, 8, 8, 8, 9, 9,10,10,10,
  137027. 10, 0, 0, 0, 7, 7, 8, 8, 9, 9, 9, 9,10,10,10,10,
  137028. 11,11, 0, 0, 0, 7, 7, 8, 8, 9, 9, 9, 9,10,10,10,
  137029. 10,11,11, 0, 0, 0, 7, 7, 8, 8, 9, 9, 9, 9,10,10,
  137030. 11,11,11,12, 0, 0, 0, 7, 7, 8, 8, 9, 9, 9, 9,10,
  137031. 10,11,11,11,11, 0, 0, 0, 8, 8, 9, 9, 9, 9,10,10,
  137032. 10,10,11,11,12,12, 0, 0, 0, 8, 8, 9, 9, 9, 9,10,
  137033. 10,10,11,11,11,12,12, 0, 0, 0, 9, 9,10, 9,10,10,
  137034. 10,10,11,11,11,11,12,12, 0, 0, 0, 0, 0, 9, 9,10,
  137035. 10,10,10,11,11,12,12,12,12, 0, 0, 0, 0, 0, 9, 9,
  137036. 10,10,10,11,11,11,12,12,13,13, 0, 0, 0, 0, 0, 9,
  137037. 9,10,10,10,10,11,11,12,12,13,13, 0, 0, 0, 0, 0,
  137038. 10,10,11,10,11,11,11,12,13,12,13,13, 0, 0, 0, 0,
  137039. 0, 0, 0,11,10,11,11,12,12,12,12,13,13, 0, 0, 0,
  137040. 0, 0, 0, 0,11,11,12,12,12,12,13,13,13,14, 0, 0,
  137041. 0, 0, 0, 0, 0,11,11,12,12,12,12,13,13,13,14, 0,
  137042. 0, 0, 0, 0, 0, 0,12,12,12,13,13,13,13,13,14,14,
  137043. 0, 0, 0, 0, 0, 0, 0, 0, 0,12,12,13,12,13,13,14,
  137044. 14,
  137045. };
  137046. static float _vq_quantthresh__44cn1_s_p5_0[] = {
  137047. -7.5, -6.5, -5.5, -4.5, -3.5, -2.5, -1.5, -0.5,
  137048. 0.5, 1.5, 2.5, 3.5, 4.5, 5.5, 6.5, 7.5,
  137049. };
  137050. static long _vq_quantmap__44cn1_s_p5_0[] = {
  137051. 15, 13, 11, 9, 7, 5, 3, 1,
  137052. 0, 2, 4, 6, 8, 10, 12, 14,
  137053. 16,
  137054. };
  137055. static encode_aux_threshmatch _vq_auxt__44cn1_s_p5_0 = {
  137056. _vq_quantthresh__44cn1_s_p5_0,
  137057. _vq_quantmap__44cn1_s_p5_0,
  137058. 17,
  137059. 17
  137060. };
  137061. static static_codebook _44cn1_s_p5_0 = {
  137062. 2, 289,
  137063. _vq_lengthlist__44cn1_s_p5_0,
  137064. 1, -529530880, 1611661312, 5, 0,
  137065. _vq_quantlist__44cn1_s_p5_0,
  137066. NULL,
  137067. &_vq_auxt__44cn1_s_p5_0,
  137068. NULL,
  137069. 0
  137070. };
  137071. static long _vq_quantlist__44cn1_s_p6_0[] = {
  137072. 1,
  137073. 0,
  137074. 2,
  137075. };
  137076. static long _vq_lengthlist__44cn1_s_p6_0[] = {
  137077. 1, 4, 4, 7, 6, 6, 7, 6, 6, 4, 6, 6,10, 9, 9,11,
  137078. 9, 9, 4, 6, 6,10, 9, 9,10, 9, 9, 7,10,10,11,11,
  137079. 11,12,11,11, 7, 9, 9,11,11,10,11,10,10, 7, 9, 9,
  137080. 11,10,11,11,10,10, 7,10,10,11,11,11,12,11,11, 7,
  137081. 9, 9,11,10,10,11,10,10, 7, 9, 9,11,10,10,11,10,
  137082. 10,
  137083. };
  137084. static float _vq_quantthresh__44cn1_s_p6_0[] = {
  137085. -5.5, 5.5,
  137086. };
  137087. static long _vq_quantmap__44cn1_s_p6_0[] = {
  137088. 1, 0, 2,
  137089. };
  137090. static encode_aux_threshmatch _vq_auxt__44cn1_s_p6_0 = {
  137091. _vq_quantthresh__44cn1_s_p6_0,
  137092. _vq_quantmap__44cn1_s_p6_0,
  137093. 3,
  137094. 3
  137095. };
  137096. static static_codebook _44cn1_s_p6_0 = {
  137097. 4, 81,
  137098. _vq_lengthlist__44cn1_s_p6_0,
  137099. 1, -529137664, 1618345984, 2, 0,
  137100. _vq_quantlist__44cn1_s_p6_0,
  137101. NULL,
  137102. &_vq_auxt__44cn1_s_p6_0,
  137103. NULL,
  137104. 0
  137105. };
  137106. static long _vq_quantlist__44cn1_s_p6_1[] = {
  137107. 5,
  137108. 4,
  137109. 6,
  137110. 3,
  137111. 7,
  137112. 2,
  137113. 8,
  137114. 1,
  137115. 9,
  137116. 0,
  137117. 10,
  137118. };
  137119. static long _vq_lengthlist__44cn1_s_p6_1[] = {
  137120. 1, 4, 4, 6, 6, 7, 7, 8, 8, 8, 8,10,10,10, 7, 6,
  137121. 8, 8, 8, 8, 8, 8,10,10,10, 7, 6, 7, 7, 8, 8, 8,
  137122. 8,10,10,10, 7, 7, 8, 8, 8, 8, 8, 8,10,10,10, 7,
  137123. 7, 8, 8, 8, 8, 8, 8,10,10,10, 8, 8, 8, 8, 9, 9,
  137124. 9, 9,10,10,10, 8, 8, 8, 8, 9, 9, 9, 9,10,10,10,
  137125. 9, 9, 9, 9, 9, 9, 9, 9,10,10,10,10,10, 9, 9, 9,
  137126. 9, 9, 9,10,10,10,10,10, 9, 9, 9, 9, 9, 9,10,10,
  137127. 10,10,10, 9, 9, 9, 9, 9, 9,
  137128. };
  137129. static float _vq_quantthresh__44cn1_s_p6_1[] = {
  137130. -4.5, -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5,
  137131. 3.5, 4.5,
  137132. };
  137133. static long _vq_quantmap__44cn1_s_p6_1[] = {
  137134. 9, 7, 5, 3, 1, 0, 2, 4,
  137135. 6, 8, 10,
  137136. };
  137137. static encode_aux_threshmatch _vq_auxt__44cn1_s_p6_1 = {
  137138. _vq_quantthresh__44cn1_s_p6_1,
  137139. _vq_quantmap__44cn1_s_p6_1,
  137140. 11,
  137141. 11
  137142. };
  137143. static static_codebook _44cn1_s_p6_1 = {
  137144. 2, 121,
  137145. _vq_lengthlist__44cn1_s_p6_1,
  137146. 1, -531365888, 1611661312, 4, 0,
  137147. _vq_quantlist__44cn1_s_p6_1,
  137148. NULL,
  137149. &_vq_auxt__44cn1_s_p6_1,
  137150. NULL,
  137151. 0
  137152. };
  137153. static long _vq_quantlist__44cn1_s_p7_0[] = {
  137154. 6,
  137155. 5,
  137156. 7,
  137157. 4,
  137158. 8,
  137159. 3,
  137160. 9,
  137161. 2,
  137162. 10,
  137163. 1,
  137164. 11,
  137165. 0,
  137166. 12,
  137167. };
  137168. static long _vq_lengthlist__44cn1_s_p7_0[] = {
  137169. 1, 4, 4, 6, 6, 7, 7, 8, 8, 9, 9,10,10, 6, 5, 5,
  137170. 7, 7, 8, 8, 8, 8, 9, 9,11,11, 7, 5, 5, 7, 7, 8,
  137171. 8, 8, 8, 9,10,11,11, 0, 8, 8, 8, 8, 9, 9, 9, 9,
  137172. 10,10,11,11, 0, 8, 8, 8, 8, 9, 9, 9, 9,10,10,11,
  137173. 11, 0,12,12, 9, 9, 9,10,10,10,11,11,11,12, 0,13,
  137174. 13, 9, 9, 9, 9,10,10,11,11,11,12, 0, 0, 0,10,10,
  137175. 10,10,11,11,12,12,12,13, 0, 0, 0,10,10,10,10,11,
  137176. 11,12,12,13,12, 0, 0, 0,14,14,11,10,11,12,12,13,
  137177. 13,14, 0, 0, 0,15,15,11,11,12,11,12,12,14,13, 0,
  137178. 0, 0, 0, 0,12,12,12,12,13,13,14,14, 0, 0, 0, 0,
  137179. 0,13,13,12,12,13,13,13,14,
  137180. };
  137181. static float _vq_quantthresh__44cn1_s_p7_0[] = {
  137182. -27.5, -22.5, -17.5, -12.5, -7.5, -2.5, 2.5, 7.5,
  137183. 12.5, 17.5, 22.5, 27.5,
  137184. };
  137185. static long _vq_quantmap__44cn1_s_p7_0[] = {
  137186. 11, 9, 7, 5, 3, 1, 0, 2,
  137187. 4, 6, 8, 10, 12,
  137188. };
  137189. static encode_aux_threshmatch _vq_auxt__44cn1_s_p7_0 = {
  137190. _vq_quantthresh__44cn1_s_p7_0,
  137191. _vq_quantmap__44cn1_s_p7_0,
  137192. 13,
  137193. 13
  137194. };
  137195. static static_codebook _44cn1_s_p7_0 = {
  137196. 2, 169,
  137197. _vq_lengthlist__44cn1_s_p7_0,
  137198. 1, -526516224, 1616117760, 4, 0,
  137199. _vq_quantlist__44cn1_s_p7_0,
  137200. NULL,
  137201. &_vq_auxt__44cn1_s_p7_0,
  137202. NULL,
  137203. 0
  137204. };
  137205. static long _vq_quantlist__44cn1_s_p7_1[] = {
  137206. 2,
  137207. 1,
  137208. 3,
  137209. 0,
  137210. 4,
  137211. };
  137212. static long _vq_lengthlist__44cn1_s_p7_1[] = {
  137213. 2, 3, 3, 5, 5, 6, 6, 6, 5, 5, 6, 6, 6, 5, 5, 6,
  137214. 6, 6, 5, 5, 6, 6, 6, 5, 5,
  137215. };
  137216. static float _vq_quantthresh__44cn1_s_p7_1[] = {
  137217. -1.5, -0.5, 0.5, 1.5,
  137218. };
  137219. static long _vq_quantmap__44cn1_s_p7_1[] = {
  137220. 3, 1, 0, 2, 4,
  137221. };
  137222. static encode_aux_threshmatch _vq_auxt__44cn1_s_p7_1 = {
  137223. _vq_quantthresh__44cn1_s_p7_1,
  137224. _vq_quantmap__44cn1_s_p7_1,
  137225. 5,
  137226. 5
  137227. };
  137228. static static_codebook _44cn1_s_p7_1 = {
  137229. 2, 25,
  137230. _vq_lengthlist__44cn1_s_p7_1,
  137231. 1, -533725184, 1611661312, 3, 0,
  137232. _vq_quantlist__44cn1_s_p7_1,
  137233. NULL,
  137234. &_vq_auxt__44cn1_s_p7_1,
  137235. NULL,
  137236. 0
  137237. };
  137238. static long _vq_quantlist__44cn1_s_p8_0[] = {
  137239. 2,
  137240. 1,
  137241. 3,
  137242. 0,
  137243. 4,
  137244. };
  137245. static long _vq_lengthlist__44cn1_s_p8_0[] = {
  137246. 1, 7, 7,11,11, 8,11,11,11,11, 4,11, 3,11,11,11,
  137247. 11,11,11,11,11,11,11,11,11,11,11,10,11,11,11,11,
  137248. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  137249. 11,11,11,10,11,11,11,11,11,11,11,11,11,11,11,11,
  137250. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  137251. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  137252. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  137253. 11,11,11,11,11,11,11,11,11,11,11,11,11, 7,11,11,
  137254. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  137255. 11,11,11,11,11,11,10,11,11,11,11,11,11,11,11,11,
  137256. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,10,
  137257. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  137258. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  137259. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  137260. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  137261. 11,11,11,11,11,11,11,11,11,11, 8,11,11,11,11,11,
  137262. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  137263. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  137264. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  137265. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  137266. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  137267. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  137268. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  137269. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  137270. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  137271. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  137272. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  137273. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  137274. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  137275. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  137276. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  137277. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  137278. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  137279. 11,11,11,11,11,11,11,12,12,12,12,12,12,12,12,12,
  137280. 12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,
  137281. 12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,
  137282. 12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,
  137283. 12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,
  137284. 12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,
  137285. 12,
  137286. };
  137287. static float _vq_quantthresh__44cn1_s_p8_0[] = {
  137288. -331.5, -110.5, 110.5, 331.5,
  137289. };
  137290. static long _vq_quantmap__44cn1_s_p8_0[] = {
  137291. 3, 1, 0, 2, 4,
  137292. };
  137293. static encode_aux_threshmatch _vq_auxt__44cn1_s_p8_0 = {
  137294. _vq_quantthresh__44cn1_s_p8_0,
  137295. _vq_quantmap__44cn1_s_p8_0,
  137296. 5,
  137297. 5
  137298. };
  137299. static static_codebook _44cn1_s_p8_0 = {
  137300. 4, 625,
  137301. _vq_lengthlist__44cn1_s_p8_0,
  137302. 1, -518283264, 1627103232, 3, 0,
  137303. _vq_quantlist__44cn1_s_p8_0,
  137304. NULL,
  137305. &_vq_auxt__44cn1_s_p8_0,
  137306. NULL,
  137307. 0
  137308. };
  137309. static long _vq_quantlist__44cn1_s_p8_1[] = {
  137310. 6,
  137311. 5,
  137312. 7,
  137313. 4,
  137314. 8,
  137315. 3,
  137316. 9,
  137317. 2,
  137318. 10,
  137319. 1,
  137320. 11,
  137321. 0,
  137322. 12,
  137323. };
  137324. static long _vq_lengthlist__44cn1_s_p8_1[] = {
  137325. 1, 4, 4, 6, 6, 8, 8, 9,10,10,11,11,11, 6, 5, 5,
  137326. 7, 7, 8, 8, 9,10, 9,11,11,12, 5, 5, 5, 7, 7, 8,
  137327. 9,10,10,12,12,14,13,15, 7, 7, 8, 8, 9,10,11,11,
  137328. 10,12,10,11,15, 7, 8, 8, 8, 9, 9,11,11,13,12,12,
  137329. 13,15,10,10, 8, 8,10,10,12,12,11,14,10,10,15,11,
  137330. 11, 8, 8,10,10,12,13,13,14,15,13,15,15,15,10,10,
  137331. 10,10,12,12,13,12,13,10,15,15,15,10,10,11,10,13,
  137332. 11,13,13,15,13,15,15,15,13,13,10,11,11,11,12,10,
  137333. 14,11,15,15,14,14,13,10,10,12,11,13,13,14,14,15,
  137334. 15,15,15,15,11,11,11,11,12,11,15,12,15,15,15,15,
  137335. 15,12,12,11,11,14,12,13,14,
  137336. };
  137337. static float _vq_quantthresh__44cn1_s_p8_1[] = {
  137338. -93.5, -76.5, -59.5, -42.5, -25.5, -8.5, 8.5, 25.5,
  137339. 42.5, 59.5, 76.5, 93.5,
  137340. };
  137341. static long _vq_quantmap__44cn1_s_p8_1[] = {
  137342. 11, 9, 7, 5, 3, 1, 0, 2,
  137343. 4, 6, 8, 10, 12,
  137344. };
  137345. static encode_aux_threshmatch _vq_auxt__44cn1_s_p8_1 = {
  137346. _vq_quantthresh__44cn1_s_p8_1,
  137347. _vq_quantmap__44cn1_s_p8_1,
  137348. 13,
  137349. 13
  137350. };
  137351. static static_codebook _44cn1_s_p8_1 = {
  137352. 2, 169,
  137353. _vq_lengthlist__44cn1_s_p8_1,
  137354. 1, -522616832, 1620115456, 4, 0,
  137355. _vq_quantlist__44cn1_s_p8_1,
  137356. NULL,
  137357. &_vq_auxt__44cn1_s_p8_1,
  137358. NULL,
  137359. 0
  137360. };
  137361. static long _vq_quantlist__44cn1_s_p8_2[] = {
  137362. 8,
  137363. 7,
  137364. 9,
  137365. 6,
  137366. 10,
  137367. 5,
  137368. 11,
  137369. 4,
  137370. 12,
  137371. 3,
  137372. 13,
  137373. 2,
  137374. 14,
  137375. 1,
  137376. 15,
  137377. 0,
  137378. 16,
  137379. };
  137380. static long _vq_lengthlist__44cn1_s_p8_2[] = {
  137381. 3, 4, 3, 6, 6, 7, 7, 8, 8, 9, 9, 9, 9, 9, 9, 9,
  137382. 9,10,11,11, 6, 6, 7, 7, 8, 8, 9, 9, 9, 9, 9, 9,
  137383. 9, 9,10,10,10, 6, 6, 7, 7, 8, 8, 9, 9, 9, 9, 9,
  137384. 9, 9, 9,10,10,10, 7, 7, 7, 8, 8, 8, 9, 9, 9, 9,
  137385. 9, 9,10, 9,10,11,10, 7, 6, 7, 7, 8, 8, 9, 9, 9,
  137386. 9, 9, 9, 9,10,10,10,11, 7, 7, 8, 8, 8, 8, 9, 9,
  137387. 9, 9, 9, 9, 9, 9,10,10,10, 7, 7, 8, 8, 8, 8, 9,
  137388. 9, 9, 9, 9, 9, 9,10,11,11,11, 8, 8, 8, 8, 8, 8,
  137389. 9, 9, 9, 9, 9, 9, 9, 9,11,10,10,11,11, 8, 8, 8,
  137390. 9, 9, 9, 9, 9, 9,10, 9,10,10,10,10,11,11, 9, 9,
  137391. 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,11,11,10,11,11, 9,
  137392. 9, 9, 9, 9, 9, 9, 9, 9,10,10,10,10,11,10,11,11,
  137393. 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,11,10,10,11,
  137394. 11,11,11, 9, 9, 9, 9, 9, 9, 9, 9,10,10,10,11,11,
  137395. 10,11,11,11, 9,10,10, 9, 9, 9, 9, 9, 9, 9,10,11,
  137396. 11,11,11,11,11, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,11,
  137397. 11,11,11,11,11,11,10,10, 9, 9, 9, 9, 9, 9, 9, 9,
  137398. 11,11,11,10,11,11,11,11,11, 9, 9, 9,10, 9, 9, 9,
  137399. 9,
  137400. };
  137401. static float _vq_quantthresh__44cn1_s_p8_2[] = {
  137402. -7.5, -6.5, -5.5, -4.5, -3.5, -2.5, -1.5, -0.5,
  137403. 0.5, 1.5, 2.5, 3.5, 4.5, 5.5, 6.5, 7.5,
  137404. };
  137405. static long _vq_quantmap__44cn1_s_p8_2[] = {
  137406. 15, 13, 11, 9, 7, 5, 3, 1,
  137407. 0, 2, 4, 6, 8, 10, 12, 14,
  137408. 16,
  137409. };
  137410. static encode_aux_threshmatch _vq_auxt__44cn1_s_p8_2 = {
  137411. _vq_quantthresh__44cn1_s_p8_2,
  137412. _vq_quantmap__44cn1_s_p8_2,
  137413. 17,
  137414. 17
  137415. };
  137416. static static_codebook _44cn1_s_p8_2 = {
  137417. 2, 289,
  137418. _vq_lengthlist__44cn1_s_p8_2,
  137419. 1, -529530880, 1611661312, 5, 0,
  137420. _vq_quantlist__44cn1_s_p8_2,
  137421. NULL,
  137422. &_vq_auxt__44cn1_s_p8_2,
  137423. NULL,
  137424. 0
  137425. };
  137426. static long _huff_lengthlist__44cn1_s_short[] = {
  137427. 10, 9,12,15,12,13,16,14,16, 7, 1, 5,14, 7,10,13,
  137428. 16,16, 9, 4, 6,16, 8,11,16,16,16,14, 4, 7,16, 9,
  137429. 12,14,16,16,10, 5, 7,14, 9,12,14,15,15,13, 8, 9,
  137430. 14,10,12,13,14,15,13, 9, 9, 7, 6, 8,11,12,12,14,
  137431. 8, 8, 5, 4, 5, 8,11,12,16,10,10, 6, 5, 6, 8, 9,
  137432. 10,
  137433. };
  137434. static static_codebook _huff_book__44cn1_s_short = {
  137435. 2, 81,
  137436. _huff_lengthlist__44cn1_s_short,
  137437. 0, 0, 0, 0, 0,
  137438. NULL,
  137439. NULL,
  137440. NULL,
  137441. NULL,
  137442. 0
  137443. };
  137444. static long _huff_lengthlist__44cn1_sm_long[] = {
  137445. 3, 3, 8, 8, 8, 8,10,12,14, 3, 2, 6, 7, 7, 8,10,
  137446. 12,16, 7, 6, 7, 9, 8,10,12,14,16, 8, 6, 8, 4, 5,
  137447. 7, 9,11,13, 7, 6, 8, 5, 6, 7, 9,11,14, 8, 8,10,
  137448. 7, 7, 6, 8,10,13, 9,11,12, 9, 9, 7, 8,10,12,10,
  137449. 13,15,11,11,10, 9,10,13,13,16,17,14,15,14,13,14,
  137450. 17,
  137451. };
  137452. static static_codebook _huff_book__44cn1_sm_long = {
  137453. 2, 81,
  137454. _huff_lengthlist__44cn1_sm_long,
  137455. 0, 0, 0, 0, 0,
  137456. NULL,
  137457. NULL,
  137458. NULL,
  137459. NULL,
  137460. 0
  137461. };
  137462. static long _vq_quantlist__44cn1_sm_p1_0[] = {
  137463. 1,
  137464. 0,
  137465. 2,
  137466. };
  137467. static long _vq_lengthlist__44cn1_sm_p1_0[] = {
  137468. 1, 4, 5, 0, 0, 0, 0, 0, 0, 5, 7, 7, 0, 0, 0, 0,
  137469. 0, 0, 5, 7, 7, 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, 5, 8, 8, 0, 0, 0, 0, 0, 0, 8, 9, 9, 0, 0, 0,
  137474. 0, 0, 0, 7, 8, 9, 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, 5, 8, 8, 0, 0, 0, 0, 0, 0, 7, 9, 8, 0, 0,
  137479. 0, 0, 0, 0, 8, 9, 9, 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, 5, 8, 8, 0, 0, 0, 0,
  137514. 0, 0, 8,10, 9, 0, 0, 0, 0, 0, 0, 8, 9, 9, 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, 7,10, 9, 0, 0, 0,
  137519. 0, 0, 0, 9, 9,10, 0, 0, 0, 0, 0, 0, 9,10,10, 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, 7, 9, 9, 0, 0,
  137524. 0, 0, 0, 0, 8,10, 9, 0, 0, 0, 0, 0, 0, 9,10,10,
  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, 5, 8, 8, 0, 0, 0, 0, 0, 0, 8, 9, 9, 0, 0,
  137560. 0, 0, 0, 0, 8, 9,10, 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, 7, 9, 9, 0, 0, 0, 0, 0, 0, 9,10,10, 0,
  137565. 0, 0, 0, 0, 0, 8, 9,10, 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, 7, 9,10, 0, 0, 0, 0, 0, 0, 9,10,10,
  137570. 0, 0, 0, 0, 0, 0, 9,10, 9, 0, 0, 0, 0, 0, 0, 0,
  137571. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137572. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137573. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137574. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137575. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137576. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137577. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137578. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137579. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137580. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137581. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137582. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137583. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137584. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137585. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137586. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137587. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137588. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137589. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137590. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137591. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137592. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137593. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137594. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137595. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137596. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137597. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137598. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137599. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137600. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137601. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137602. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137603. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137604. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137605. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137606. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137607. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137608. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137609. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137610. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137611. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137612. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137613. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137614. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137615. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137616. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137617. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137618. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137619. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137620. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137621. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137622. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137623. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137624. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137625. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137626. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137627. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137628. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137629. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137630. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137631. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137632. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137633. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137634. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137635. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137636. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137637. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137638. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137639. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137640. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137641. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137642. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137643. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137644. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137645. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137646. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137647. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137648. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137649. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137650. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137651. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137652. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137653. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137654. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137655. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137656. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137657. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137658. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137659. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137660. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137661. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137662. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137663. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137664. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137665. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137666. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137667. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137668. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137669. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137670. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137671. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137672. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137673. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137674. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137675. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137676. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137677. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137678. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137679. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137680. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137681. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137682. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137683. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137684. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137685. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137686. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137687. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137688. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137689. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137690. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137691. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137692. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137693. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137694. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137695. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137696. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137697. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137698. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137699. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137700. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137701. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137702. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137703. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137704. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137705. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137706. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137707. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137708. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137709. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137710. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137711. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137712. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137713. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137714. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137715. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137716. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137717. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137718. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137719. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137720. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137721. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137722. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137723. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137724. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137725. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137726. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137727. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137728. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137729. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137730. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137731. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137732. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137733. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137734. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137735. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137736. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137737. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137738. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137739. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137740. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137741. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137742. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137743. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137744. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137745. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137746. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137747. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137748. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137749. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137750. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137751. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137752. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137753. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137754. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137755. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137756. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137757. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137758. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137759. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137760. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137761. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137762. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137763. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137764. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137765. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137766. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137767. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137768. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137769. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137770. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137771. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137772. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137773. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137774. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137775. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137776. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137777. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137778. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137779. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137780. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137781. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137782. 0, 0, 0, 0, 0, 0, 0, 0, 0, 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, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137805. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137806. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137807. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137808. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137809. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137810. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137811. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137812. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137813. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137814. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137815. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137816. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137817. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137818. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137819. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137820. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137821. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137822. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137823. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137824. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137825. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137826. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137827. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137828. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137829. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137830. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137831. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137832. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137833. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137834. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137835. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137836. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137837. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137838. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137839. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137840. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137841. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137842. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137843. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137844. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137845. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137846. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137847. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137848. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137849. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137850. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137851. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137852. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137853. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137854. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137855. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137856. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137857. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137858. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137859. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137860. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137861. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137862. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137863. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137864. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137865. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137866. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137867. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137868. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137869. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137870. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137871. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137872. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137873. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137874. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137875. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137876. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137877. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137878. 0,
  137879. };
  137880. static float _vq_quantthresh__44cn1_sm_p1_0[] = {
  137881. -0.5, 0.5,
  137882. };
  137883. static long _vq_quantmap__44cn1_sm_p1_0[] = {
  137884. 1, 0, 2,
  137885. };
  137886. static encode_aux_threshmatch _vq_auxt__44cn1_sm_p1_0 = {
  137887. _vq_quantthresh__44cn1_sm_p1_0,
  137888. _vq_quantmap__44cn1_sm_p1_0,
  137889. 3,
  137890. 3
  137891. };
  137892. static static_codebook _44cn1_sm_p1_0 = {
  137893. 8, 6561,
  137894. _vq_lengthlist__44cn1_sm_p1_0,
  137895. 1, -535822336, 1611661312, 2, 0,
  137896. _vq_quantlist__44cn1_sm_p1_0,
  137897. NULL,
  137898. &_vq_auxt__44cn1_sm_p1_0,
  137899. NULL,
  137900. 0
  137901. };
  137902. static long _vq_quantlist__44cn1_sm_p2_0[] = {
  137903. 2,
  137904. 1,
  137905. 3,
  137906. 0,
  137907. 4,
  137908. };
  137909. static long _vq_lengthlist__44cn1_sm_p2_0[] = {
  137910. 1, 4, 4, 6, 6, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137911. 0, 0, 0, 0, 0, 0, 0, 0, 0, 4, 5, 5, 7, 7, 0, 0,
  137912. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137913. 0, 0, 4, 5, 5, 7, 7, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137914. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 6, 7, 7, 9, 9,
  137915. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137916. 0, 0, 0, 0, 7, 7, 7, 9, 9, 0, 0, 0, 0, 0, 0, 0,
  137917. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137918. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137919. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137920. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137921. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137922. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137923. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137924. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137925. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137926. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137927. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137928. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137929. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137930. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137931. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137932. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137933. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137934. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137935. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137936. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137937. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137938. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137939. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137940. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137941. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137942. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137943. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137944. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137945. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137946. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137947. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137948. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137949. 0,
  137950. };
  137951. static float _vq_quantthresh__44cn1_sm_p2_0[] = {
  137952. -1.5, -0.5, 0.5, 1.5,
  137953. };
  137954. static long _vq_quantmap__44cn1_sm_p2_0[] = {
  137955. 3, 1, 0, 2, 4,
  137956. };
  137957. static encode_aux_threshmatch _vq_auxt__44cn1_sm_p2_0 = {
  137958. _vq_quantthresh__44cn1_sm_p2_0,
  137959. _vq_quantmap__44cn1_sm_p2_0,
  137960. 5,
  137961. 5
  137962. };
  137963. static static_codebook _44cn1_sm_p2_0 = {
  137964. 4, 625,
  137965. _vq_lengthlist__44cn1_sm_p2_0,
  137966. 1, -533725184, 1611661312, 3, 0,
  137967. _vq_quantlist__44cn1_sm_p2_0,
  137968. NULL,
  137969. &_vq_auxt__44cn1_sm_p2_0,
  137970. NULL,
  137971. 0
  137972. };
  137973. static long _vq_quantlist__44cn1_sm_p3_0[] = {
  137974. 4,
  137975. 3,
  137976. 5,
  137977. 2,
  137978. 6,
  137979. 1,
  137980. 7,
  137981. 0,
  137982. 8,
  137983. };
  137984. static long _vq_lengthlist__44cn1_sm_p3_0[] = {
  137985. 1, 3, 4, 7, 7, 0, 0, 0, 0, 0, 4, 4, 7, 7, 0, 0,
  137986. 0, 0, 0, 4, 5, 7, 7, 0, 0, 0, 0, 0, 6, 7, 8, 8,
  137987. 0, 0, 0, 0, 0, 0, 0, 8, 8, 0, 0, 0, 0, 0, 0, 0,
  137988. 9, 9, 0, 0, 0, 0, 0, 0, 0,10, 9, 0, 0, 0, 0, 0,
  137989. 0, 0,11,11, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137990. 0,
  137991. };
  137992. static float _vq_quantthresh__44cn1_sm_p3_0[] = {
  137993. -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5, 3.5,
  137994. };
  137995. static long _vq_quantmap__44cn1_sm_p3_0[] = {
  137996. 7, 5, 3, 1, 0, 2, 4, 6,
  137997. 8,
  137998. };
  137999. static encode_aux_threshmatch _vq_auxt__44cn1_sm_p3_0 = {
  138000. _vq_quantthresh__44cn1_sm_p3_0,
  138001. _vq_quantmap__44cn1_sm_p3_0,
  138002. 9,
  138003. 9
  138004. };
  138005. static static_codebook _44cn1_sm_p3_0 = {
  138006. 2, 81,
  138007. _vq_lengthlist__44cn1_sm_p3_0,
  138008. 1, -531628032, 1611661312, 4, 0,
  138009. _vq_quantlist__44cn1_sm_p3_0,
  138010. NULL,
  138011. &_vq_auxt__44cn1_sm_p3_0,
  138012. NULL,
  138013. 0
  138014. };
  138015. static long _vq_quantlist__44cn1_sm_p4_0[] = {
  138016. 4,
  138017. 3,
  138018. 5,
  138019. 2,
  138020. 6,
  138021. 1,
  138022. 7,
  138023. 0,
  138024. 8,
  138025. };
  138026. static long _vq_lengthlist__44cn1_sm_p4_0[] = {
  138027. 1, 4, 3, 6, 6, 7, 7, 9, 9, 0, 5, 5, 7, 7, 8, 7,
  138028. 9, 9, 0, 5, 5, 7, 7, 8, 8, 9, 9, 0, 7, 7, 8, 8,
  138029. 8, 8,10,10, 0, 0, 0, 8, 8, 8, 8,10,10, 0, 0, 0,
  138030. 9, 9, 9, 9,10,10, 0, 0, 0, 9, 9, 9, 9,10,10, 0,
  138031. 0, 0,10,10,10,10,11,11, 0, 0, 0, 0, 0,10,10,11,
  138032. 11,
  138033. };
  138034. static float _vq_quantthresh__44cn1_sm_p4_0[] = {
  138035. -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5, 3.5,
  138036. };
  138037. static long _vq_quantmap__44cn1_sm_p4_0[] = {
  138038. 7, 5, 3, 1, 0, 2, 4, 6,
  138039. 8,
  138040. };
  138041. static encode_aux_threshmatch _vq_auxt__44cn1_sm_p4_0 = {
  138042. _vq_quantthresh__44cn1_sm_p4_0,
  138043. _vq_quantmap__44cn1_sm_p4_0,
  138044. 9,
  138045. 9
  138046. };
  138047. static static_codebook _44cn1_sm_p4_0 = {
  138048. 2, 81,
  138049. _vq_lengthlist__44cn1_sm_p4_0,
  138050. 1, -531628032, 1611661312, 4, 0,
  138051. _vq_quantlist__44cn1_sm_p4_0,
  138052. NULL,
  138053. &_vq_auxt__44cn1_sm_p4_0,
  138054. NULL,
  138055. 0
  138056. };
  138057. static long _vq_quantlist__44cn1_sm_p5_0[] = {
  138058. 8,
  138059. 7,
  138060. 9,
  138061. 6,
  138062. 10,
  138063. 5,
  138064. 11,
  138065. 4,
  138066. 12,
  138067. 3,
  138068. 13,
  138069. 2,
  138070. 14,
  138071. 1,
  138072. 15,
  138073. 0,
  138074. 16,
  138075. };
  138076. static long _vq_lengthlist__44cn1_sm_p5_0[] = {
  138077. 1, 4, 4, 6, 6, 8, 8, 9, 9, 8, 8, 9, 9,10,10,11,
  138078. 11, 0, 6, 6, 7, 7, 8, 8, 9, 9, 9, 9,10,10,11,11,
  138079. 12,12, 0, 6, 5, 7, 7, 8, 8, 9, 9, 9, 9,10,10,11,
  138080. 11,12,12, 0, 7, 7, 7, 7, 8, 8, 9, 9, 9, 9,10,10,
  138081. 11,11,12,12, 0, 0, 0, 7, 7, 8, 8, 9, 9,10,10,11,
  138082. 11,11,11,12,12, 0, 0, 0, 8, 8, 9, 9,10,10,10,10,
  138083. 11,11,12,12,12,12, 0, 0, 0, 8, 8, 9, 9,10,10,10,
  138084. 10,11,11,12,12,12,12, 0, 0, 0, 9, 9, 9, 9,10,10,
  138085. 10,10,11,11,12,12,13,13, 0, 0, 0, 0, 0, 9, 9,10,
  138086. 10,10,10,11,11,12,12,13,13, 0, 0, 0, 0, 0, 9, 9,
  138087. 10,10,11,11,12,12,13,13,13,13, 0, 0, 0, 0, 0, 9,
  138088. 9,10,10,11,11,12,12,12,13,13,13, 0, 0, 0, 0, 0,
  138089. 10,10,11,11,11,11,12,12,13,13,14,14, 0, 0, 0, 0,
  138090. 0, 0, 0,11,11,11,11,12,12,13,13,14,14, 0, 0, 0,
  138091. 0, 0, 0, 0,11,11,12,12,13,13,13,13,14,14, 0, 0,
  138092. 0, 0, 0, 0, 0,11,11,12,12,13,13,13,13,14,14, 0,
  138093. 0, 0, 0, 0, 0, 0,12,12,12,13,13,13,14,14,14,14,
  138094. 0, 0, 0, 0, 0, 0, 0, 0, 0,12,12,13,13,14,14,14,
  138095. 14,
  138096. };
  138097. static float _vq_quantthresh__44cn1_sm_p5_0[] = {
  138098. -7.5, -6.5, -5.5, -4.5, -3.5, -2.5, -1.5, -0.5,
  138099. 0.5, 1.5, 2.5, 3.5, 4.5, 5.5, 6.5, 7.5,
  138100. };
  138101. static long _vq_quantmap__44cn1_sm_p5_0[] = {
  138102. 15, 13, 11, 9, 7, 5, 3, 1,
  138103. 0, 2, 4, 6, 8, 10, 12, 14,
  138104. 16,
  138105. };
  138106. static encode_aux_threshmatch _vq_auxt__44cn1_sm_p5_0 = {
  138107. _vq_quantthresh__44cn1_sm_p5_0,
  138108. _vq_quantmap__44cn1_sm_p5_0,
  138109. 17,
  138110. 17
  138111. };
  138112. static static_codebook _44cn1_sm_p5_0 = {
  138113. 2, 289,
  138114. _vq_lengthlist__44cn1_sm_p5_0,
  138115. 1, -529530880, 1611661312, 5, 0,
  138116. _vq_quantlist__44cn1_sm_p5_0,
  138117. NULL,
  138118. &_vq_auxt__44cn1_sm_p5_0,
  138119. NULL,
  138120. 0
  138121. };
  138122. static long _vq_quantlist__44cn1_sm_p6_0[] = {
  138123. 1,
  138124. 0,
  138125. 2,
  138126. };
  138127. static long _vq_lengthlist__44cn1_sm_p6_0[] = {
  138128. 1, 4, 4, 7, 6, 6, 7, 6, 6, 4, 7, 6,10, 9, 9,11,
  138129. 9, 9, 4, 6, 7,10, 9, 9,11, 9, 9, 7,10,10,10,11,
  138130. 11,11,11,10, 6, 9, 9,11,10,10,11,10,10, 6, 9, 9,
  138131. 11,10,11,11,10,10, 7,11,11,11,11,11,12,11,11, 7,
  138132. 9, 9,11,10,10,12,10,10, 7, 9, 9,11,10,10,11,10,
  138133. 10,
  138134. };
  138135. static float _vq_quantthresh__44cn1_sm_p6_0[] = {
  138136. -5.5, 5.5,
  138137. };
  138138. static long _vq_quantmap__44cn1_sm_p6_0[] = {
  138139. 1, 0, 2,
  138140. };
  138141. static encode_aux_threshmatch _vq_auxt__44cn1_sm_p6_0 = {
  138142. _vq_quantthresh__44cn1_sm_p6_0,
  138143. _vq_quantmap__44cn1_sm_p6_0,
  138144. 3,
  138145. 3
  138146. };
  138147. static static_codebook _44cn1_sm_p6_0 = {
  138148. 4, 81,
  138149. _vq_lengthlist__44cn1_sm_p6_0,
  138150. 1, -529137664, 1618345984, 2, 0,
  138151. _vq_quantlist__44cn1_sm_p6_0,
  138152. NULL,
  138153. &_vq_auxt__44cn1_sm_p6_0,
  138154. NULL,
  138155. 0
  138156. };
  138157. static long _vq_quantlist__44cn1_sm_p6_1[] = {
  138158. 5,
  138159. 4,
  138160. 6,
  138161. 3,
  138162. 7,
  138163. 2,
  138164. 8,
  138165. 1,
  138166. 9,
  138167. 0,
  138168. 10,
  138169. };
  138170. static long _vq_lengthlist__44cn1_sm_p6_1[] = {
  138171. 2, 4, 4, 5, 5, 7, 7, 7, 7, 8, 8,10, 5, 5, 6, 6,
  138172. 7, 7, 8, 8, 8, 8,10, 5, 5, 6, 6, 7, 7, 8, 8, 8,
  138173. 8,10, 7, 7, 7, 7, 8, 8, 8, 8, 8, 8,10,10,10, 7,
  138174. 7, 7, 7, 8, 8, 8, 8,10,10,10, 8, 8, 8, 8, 8, 8,
  138175. 8, 8,10,10,10, 8, 8, 8, 8, 8, 8, 8, 8,10,10,10,
  138176. 8, 8, 8, 8, 8, 8, 9, 9,10,10,10,10,10, 8, 8, 8,
  138177. 8, 9, 9,10,10,10,10,10, 9, 9, 9, 9, 8, 9,10,10,
  138178. 10,10,10, 8, 9, 8, 8, 9, 8,
  138179. };
  138180. static float _vq_quantthresh__44cn1_sm_p6_1[] = {
  138181. -4.5, -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5,
  138182. 3.5, 4.5,
  138183. };
  138184. static long _vq_quantmap__44cn1_sm_p6_1[] = {
  138185. 9, 7, 5, 3, 1, 0, 2, 4,
  138186. 6, 8, 10,
  138187. };
  138188. static encode_aux_threshmatch _vq_auxt__44cn1_sm_p6_1 = {
  138189. _vq_quantthresh__44cn1_sm_p6_1,
  138190. _vq_quantmap__44cn1_sm_p6_1,
  138191. 11,
  138192. 11
  138193. };
  138194. static static_codebook _44cn1_sm_p6_1 = {
  138195. 2, 121,
  138196. _vq_lengthlist__44cn1_sm_p6_1,
  138197. 1, -531365888, 1611661312, 4, 0,
  138198. _vq_quantlist__44cn1_sm_p6_1,
  138199. NULL,
  138200. &_vq_auxt__44cn1_sm_p6_1,
  138201. NULL,
  138202. 0
  138203. };
  138204. static long _vq_quantlist__44cn1_sm_p7_0[] = {
  138205. 6,
  138206. 5,
  138207. 7,
  138208. 4,
  138209. 8,
  138210. 3,
  138211. 9,
  138212. 2,
  138213. 10,
  138214. 1,
  138215. 11,
  138216. 0,
  138217. 12,
  138218. };
  138219. static long _vq_lengthlist__44cn1_sm_p7_0[] = {
  138220. 1, 4, 4, 6, 6, 7, 7, 7, 7, 9, 9,10,10, 7, 5, 5,
  138221. 7, 7, 8, 8, 8, 8,10, 9,11,10, 7, 5, 5, 7, 7, 8,
  138222. 8, 8, 8, 9,10,11,11, 0, 8, 8, 8, 8, 9, 9, 9, 9,
  138223. 10,10,11,11, 0, 8, 8, 8, 8, 9, 9, 9, 9,10,10,11,
  138224. 11, 0,12,12, 9, 9, 9,10,10,10,11,11,12,12, 0,13,
  138225. 13, 9, 9, 9, 9,10,10,11,11,12,12, 0, 0, 0,10,10,
  138226. 10,10,11,11,12,12,12,13, 0, 0, 0,10,10,10,10,11,
  138227. 11,12,12,12,12, 0, 0, 0,14,14,11,11,11,11,12,13,
  138228. 13,13, 0, 0, 0,14,14,11,10,11,11,12,12,13,13, 0,
  138229. 0, 0, 0, 0,12,12,12,12,13,13,13,14, 0, 0, 0, 0,
  138230. 0,13,12,12,12,13,13,13,14,
  138231. };
  138232. static float _vq_quantthresh__44cn1_sm_p7_0[] = {
  138233. -27.5, -22.5, -17.5, -12.5, -7.5, -2.5, 2.5, 7.5,
  138234. 12.5, 17.5, 22.5, 27.5,
  138235. };
  138236. static long _vq_quantmap__44cn1_sm_p7_0[] = {
  138237. 11, 9, 7, 5, 3, 1, 0, 2,
  138238. 4, 6, 8, 10, 12,
  138239. };
  138240. static encode_aux_threshmatch _vq_auxt__44cn1_sm_p7_0 = {
  138241. _vq_quantthresh__44cn1_sm_p7_0,
  138242. _vq_quantmap__44cn1_sm_p7_0,
  138243. 13,
  138244. 13
  138245. };
  138246. static static_codebook _44cn1_sm_p7_0 = {
  138247. 2, 169,
  138248. _vq_lengthlist__44cn1_sm_p7_0,
  138249. 1, -526516224, 1616117760, 4, 0,
  138250. _vq_quantlist__44cn1_sm_p7_0,
  138251. NULL,
  138252. &_vq_auxt__44cn1_sm_p7_0,
  138253. NULL,
  138254. 0
  138255. };
  138256. static long _vq_quantlist__44cn1_sm_p7_1[] = {
  138257. 2,
  138258. 1,
  138259. 3,
  138260. 0,
  138261. 4,
  138262. };
  138263. static long _vq_lengthlist__44cn1_sm_p7_1[] = {
  138264. 2, 4, 4, 4, 5, 6, 5, 5, 5, 5, 6, 5, 5, 5, 5, 6,
  138265. 5, 5, 5, 5, 6, 6, 6, 5, 5,
  138266. };
  138267. static float _vq_quantthresh__44cn1_sm_p7_1[] = {
  138268. -1.5, -0.5, 0.5, 1.5,
  138269. };
  138270. static long _vq_quantmap__44cn1_sm_p7_1[] = {
  138271. 3, 1, 0, 2, 4,
  138272. };
  138273. static encode_aux_threshmatch _vq_auxt__44cn1_sm_p7_1 = {
  138274. _vq_quantthresh__44cn1_sm_p7_1,
  138275. _vq_quantmap__44cn1_sm_p7_1,
  138276. 5,
  138277. 5
  138278. };
  138279. static static_codebook _44cn1_sm_p7_1 = {
  138280. 2, 25,
  138281. _vq_lengthlist__44cn1_sm_p7_1,
  138282. 1, -533725184, 1611661312, 3, 0,
  138283. _vq_quantlist__44cn1_sm_p7_1,
  138284. NULL,
  138285. &_vq_auxt__44cn1_sm_p7_1,
  138286. NULL,
  138287. 0
  138288. };
  138289. static long _vq_quantlist__44cn1_sm_p8_0[] = {
  138290. 4,
  138291. 3,
  138292. 5,
  138293. 2,
  138294. 6,
  138295. 1,
  138296. 7,
  138297. 0,
  138298. 8,
  138299. };
  138300. static long _vq_lengthlist__44cn1_sm_p8_0[] = {
  138301. 1, 4, 4,12,11,13,13,14,14, 4, 7, 7,11,13,14,14,
  138302. 14,14, 3, 8, 3,14,14,14,14,14,14,14,10,12,14,14,
  138303. 14,14,14,14,14,14, 5,14, 8,14,14,14,14,14,12,14,
  138304. 13,14,14,14,14,14,14,14,13,14,10,14,14,14,14,14,
  138305. 14,14,14,14,14,14,14,14,14,14,14,14,14,14,14,14,
  138306. 14,
  138307. };
  138308. static float _vq_quantthresh__44cn1_sm_p8_0[] = {
  138309. -773.5, -552.5, -331.5, -110.5, 110.5, 331.5, 552.5, 773.5,
  138310. };
  138311. static long _vq_quantmap__44cn1_sm_p8_0[] = {
  138312. 7, 5, 3, 1, 0, 2, 4, 6,
  138313. 8,
  138314. };
  138315. static encode_aux_threshmatch _vq_auxt__44cn1_sm_p8_0 = {
  138316. _vq_quantthresh__44cn1_sm_p8_0,
  138317. _vq_quantmap__44cn1_sm_p8_0,
  138318. 9,
  138319. 9
  138320. };
  138321. static static_codebook _44cn1_sm_p8_0 = {
  138322. 2, 81,
  138323. _vq_lengthlist__44cn1_sm_p8_0,
  138324. 1, -516186112, 1627103232, 4, 0,
  138325. _vq_quantlist__44cn1_sm_p8_0,
  138326. NULL,
  138327. &_vq_auxt__44cn1_sm_p8_0,
  138328. NULL,
  138329. 0
  138330. };
  138331. static long _vq_quantlist__44cn1_sm_p8_1[] = {
  138332. 6,
  138333. 5,
  138334. 7,
  138335. 4,
  138336. 8,
  138337. 3,
  138338. 9,
  138339. 2,
  138340. 10,
  138341. 1,
  138342. 11,
  138343. 0,
  138344. 12,
  138345. };
  138346. static long _vq_lengthlist__44cn1_sm_p8_1[] = {
  138347. 1, 4, 4, 6, 6, 8, 8, 9, 9,10,11,11,11, 6, 5, 5,
  138348. 7, 7, 8, 8,10,10,10,11,11,11, 6, 5, 5, 7, 7, 8,
  138349. 8,10,10,11,12,12,12,14, 7, 7, 7, 8, 9, 9,11,11,
  138350. 11,12,11,12,17, 7, 7, 8, 7, 9, 9,11,11,12,12,12,
  138351. 12,14,11,11, 8, 8,10,10,11,12,12,13,11,12,14,11,
  138352. 11, 8, 8,10,10,11,12,12,13,13,12,14,15,14,10,10,
  138353. 10,10,11,12,12,12,12,11,14,13,16,10,10,10, 9,12,
  138354. 11,12,12,13,14,14,15,14,14,13,10,10,11,11,12,11,
  138355. 13,11,14,12,15,13,14,11,10,12,10,12,12,13,13,13,
  138356. 13,14,15,15,12,12,11,11,12,11,13,12,14,14,14,14,
  138357. 17,12,12,11,10,13,11,13,13,
  138358. };
  138359. static float _vq_quantthresh__44cn1_sm_p8_1[] = {
  138360. -93.5, -76.5, -59.5, -42.5, -25.5, -8.5, 8.5, 25.5,
  138361. 42.5, 59.5, 76.5, 93.5,
  138362. };
  138363. static long _vq_quantmap__44cn1_sm_p8_1[] = {
  138364. 11, 9, 7, 5, 3, 1, 0, 2,
  138365. 4, 6, 8, 10, 12,
  138366. };
  138367. static encode_aux_threshmatch _vq_auxt__44cn1_sm_p8_1 = {
  138368. _vq_quantthresh__44cn1_sm_p8_1,
  138369. _vq_quantmap__44cn1_sm_p8_1,
  138370. 13,
  138371. 13
  138372. };
  138373. static static_codebook _44cn1_sm_p8_1 = {
  138374. 2, 169,
  138375. _vq_lengthlist__44cn1_sm_p8_1,
  138376. 1, -522616832, 1620115456, 4, 0,
  138377. _vq_quantlist__44cn1_sm_p8_1,
  138378. NULL,
  138379. &_vq_auxt__44cn1_sm_p8_1,
  138380. NULL,
  138381. 0
  138382. };
  138383. static long _vq_quantlist__44cn1_sm_p8_2[] = {
  138384. 8,
  138385. 7,
  138386. 9,
  138387. 6,
  138388. 10,
  138389. 5,
  138390. 11,
  138391. 4,
  138392. 12,
  138393. 3,
  138394. 13,
  138395. 2,
  138396. 14,
  138397. 1,
  138398. 15,
  138399. 0,
  138400. 16,
  138401. };
  138402. static long _vq_lengthlist__44cn1_sm_p8_2[] = {
  138403. 3, 4, 4, 6, 6, 7, 7, 8, 8, 8, 8, 9, 9, 9, 9, 9,
  138404. 9,10, 6, 6, 6, 6, 7, 7, 8, 8, 8, 9, 9, 9, 9, 9,
  138405. 9, 9,10, 6, 6, 6, 6, 7, 7, 8, 8, 8, 8, 9, 9, 9,
  138406. 9, 9, 9,10, 7, 7, 7, 7, 8, 8, 8, 8, 9, 9, 9, 9,
  138407. 9, 9, 9, 9,10,10,10, 7, 7, 7, 8, 8, 8, 9, 9, 9,
  138408. 9, 9, 9, 9, 9,10,10,10, 8, 8, 8, 8, 8, 8, 9, 9,
  138409. 9, 9, 9, 9, 9, 9,10,10,10, 8, 8, 8, 8, 8, 8, 9,
  138410. 9, 9, 9, 9, 9, 9, 9,11,10,11, 8, 8, 8, 8, 8, 8,
  138411. 9, 9, 9, 9, 9, 9, 9, 9,10,10,10,11,11, 8, 8, 8,
  138412. 8, 9, 9, 9, 9, 9, 9, 9, 9,11,10,11,11,11, 9, 9,
  138413. 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,10,11,10,11,11, 9,
  138414. 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,10,11,11,10,11,11,
  138415. 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,11,10,11,11,
  138416. 11,11,11, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,10,11,11,
  138417. 11,11,11,11, 9,10,10,10, 9, 9, 9, 9, 9, 9,11,10,
  138418. 11,11,11,11,11, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,11,
  138419. 11,11,11,11,11,11,10,10, 9, 9, 9, 9, 9, 9, 9, 9,
  138420. 10,11,11,11,11,11,11,11,11, 9, 9, 9, 9, 9, 9, 9,
  138421. 9,
  138422. };
  138423. static float _vq_quantthresh__44cn1_sm_p8_2[] = {
  138424. -7.5, -6.5, -5.5, -4.5, -3.5, -2.5, -1.5, -0.5,
  138425. 0.5, 1.5, 2.5, 3.5, 4.5, 5.5, 6.5, 7.5,
  138426. };
  138427. static long _vq_quantmap__44cn1_sm_p8_2[] = {
  138428. 15, 13, 11, 9, 7, 5, 3, 1,
  138429. 0, 2, 4, 6, 8, 10, 12, 14,
  138430. 16,
  138431. };
  138432. static encode_aux_threshmatch _vq_auxt__44cn1_sm_p8_2 = {
  138433. _vq_quantthresh__44cn1_sm_p8_2,
  138434. _vq_quantmap__44cn1_sm_p8_2,
  138435. 17,
  138436. 17
  138437. };
  138438. static static_codebook _44cn1_sm_p8_2 = {
  138439. 2, 289,
  138440. _vq_lengthlist__44cn1_sm_p8_2,
  138441. 1, -529530880, 1611661312, 5, 0,
  138442. _vq_quantlist__44cn1_sm_p8_2,
  138443. NULL,
  138444. &_vq_auxt__44cn1_sm_p8_2,
  138445. NULL,
  138446. 0
  138447. };
  138448. static long _huff_lengthlist__44cn1_sm_short[] = {
  138449. 5, 6,12,14,12,14,16,17,18, 4, 2, 5,11, 7,10,12,
  138450. 14,15, 9, 4, 5,11, 7,10,13,15,18,15, 6, 7, 5, 6,
  138451. 8,11,13,16,11, 5, 6, 5, 5, 6, 9,13,15,12, 5, 7,
  138452. 6, 5, 6, 9,12,14,12, 6, 7, 8, 6, 7, 9,12,13,14,
  138453. 8, 8, 7, 5, 5, 8,10,12,16, 9, 9, 8, 6, 6, 7, 9,
  138454. 9,
  138455. };
  138456. static static_codebook _huff_book__44cn1_sm_short = {
  138457. 2, 81,
  138458. _huff_lengthlist__44cn1_sm_short,
  138459. 0, 0, 0, 0, 0,
  138460. NULL,
  138461. NULL,
  138462. NULL,
  138463. NULL,
  138464. 0
  138465. };
  138466. /*** End of inlined file: res_books_stereo.h ***/
  138467. /***** residue backends *********************************************/
  138468. static vorbis_info_residue0 _residue_44_low={
  138469. 0,-1, -1, 9,-1,
  138470. /* 0 1 2 3 4 5 6 7 */
  138471. {0},
  138472. {-1},
  138473. { .5, 1.5, 2.5, 2.5, 4.5, 8.5, 16.5, 32.5},
  138474. { .5, .5, .5, 999., 4.5, 8.5, 16.5, 32.5},
  138475. };
  138476. static vorbis_info_residue0 _residue_44_mid={
  138477. 0,-1, -1, 10,-1,
  138478. /* 0 1 2 3 4 5 6 7 8 */
  138479. {0},
  138480. {-1},
  138481. { .5, 1.5, 1.5, 2.5, 2.5, 4.5, 8.5, 16.5, 32.5},
  138482. { .5, .5, 999., .5, 999., 4.5, 8.5, 16.5, 32.5},
  138483. };
  138484. static vorbis_info_residue0 _residue_44_high={
  138485. 0,-1, -1, 10,-1,
  138486. /* 0 1 2 3 4 5 6 7 8 */
  138487. {0},
  138488. {-1},
  138489. { .5, 1.5, 2.5, 4.5, 8.5, 16.5, 32.5, 71.5,157.5},
  138490. { .5, 1.5, 2.5, 3.5, 4.5, 8.5, 16.5, 71.5,157.5},
  138491. };
  138492. static static_bookblock _resbook_44s_n1={
  138493. {
  138494. {0},{0,0,&_44cn1_s_p1_0},{0,0,&_44cn1_s_p2_0},
  138495. {0,0,&_44cn1_s_p3_0},{0,0,&_44cn1_s_p4_0},{0,0,&_44cn1_s_p5_0},
  138496. {&_44cn1_s_p6_0,&_44cn1_s_p6_1},{&_44cn1_s_p7_0,&_44cn1_s_p7_1},
  138497. {&_44cn1_s_p8_0,&_44cn1_s_p8_1,&_44cn1_s_p8_2}
  138498. }
  138499. };
  138500. static static_bookblock _resbook_44sm_n1={
  138501. {
  138502. {0},{0,0,&_44cn1_sm_p1_0},{0,0,&_44cn1_sm_p2_0},
  138503. {0,0,&_44cn1_sm_p3_0},{0,0,&_44cn1_sm_p4_0},{0,0,&_44cn1_sm_p5_0},
  138504. {&_44cn1_sm_p6_0,&_44cn1_sm_p6_1},{&_44cn1_sm_p7_0,&_44cn1_sm_p7_1},
  138505. {&_44cn1_sm_p8_0,&_44cn1_sm_p8_1,&_44cn1_sm_p8_2}
  138506. }
  138507. };
  138508. static static_bookblock _resbook_44s_0={
  138509. {
  138510. {0},{0,0,&_44c0_s_p1_0},{0,0,&_44c0_s_p2_0},
  138511. {0,0,&_44c0_s_p3_0},{0,0,&_44c0_s_p4_0},{0,0,&_44c0_s_p5_0},
  138512. {&_44c0_s_p6_0,&_44c0_s_p6_1},{&_44c0_s_p7_0,&_44c0_s_p7_1},
  138513. {&_44c0_s_p8_0,&_44c0_s_p8_1,&_44c0_s_p8_2}
  138514. }
  138515. };
  138516. static static_bookblock _resbook_44sm_0={
  138517. {
  138518. {0},{0,0,&_44c0_sm_p1_0},{0,0,&_44c0_sm_p2_0},
  138519. {0,0,&_44c0_sm_p3_0},{0,0,&_44c0_sm_p4_0},{0,0,&_44c0_sm_p5_0},
  138520. {&_44c0_sm_p6_0,&_44c0_sm_p6_1},{&_44c0_sm_p7_0,&_44c0_sm_p7_1},
  138521. {&_44c0_sm_p8_0,&_44c0_sm_p8_1,&_44c0_sm_p8_2}
  138522. }
  138523. };
  138524. static static_bookblock _resbook_44s_1={
  138525. {
  138526. {0},{0,0,&_44c1_s_p1_0},{0,0,&_44c1_s_p2_0},
  138527. {0,0,&_44c1_s_p3_0},{0,0,&_44c1_s_p4_0},{0,0,&_44c1_s_p5_0},
  138528. {&_44c1_s_p6_0,&_44c1_s_p6_1},{&_44c1_s_p7_0,&_44c1_s_p7_1},
  138529. {&_44c1_s_p8_0,&_44c1_s_p8_1,&_44c1_s_p8_2}
  138530. }
  138531. };
  138532. static static_bookblock _resbook_44sm_1={
  138533. {
  138534. {0},{0,0,&_44c1_sm_p1_0},{0,0,&_44c1_sm_p2_0},
  138535. {0,0,&_44c1_sm_p3_0},{0,0,&_44c1_sm_p4_0},{0,0,&_44c1_sm_p5_0},
  138536. {&_44c1_sm_p6_0,&_44c1_sm_p6_1},{&_44c1_sm_p7_0,&_44c1_sm_p7_1},
  138537. {&_44c1_sm_p8_0,&_44c1_sm_p8_1,&_44c1_sm_p8_2}
  138538. }
  138539. };
  138540. static static_bookblock _resbook_44s_2={
  138541. {
  138542. {0},{0,0,&_44c2_s_p1_0},{0,0,&_44c2_s_p2_0},{0,0,&_44c2_s_p3_0},
  138543. {0,0,&_44c2_s_p4_0},{0,0,&_44c2_s_p5_0},{0,0,&_44c2_s_p6_0},
  138544. {&_44c2_s_p7_0,&_44c2_s_p7_1},{&_44c2_s_p8_0,&_44c2_s_p8_1},
  138545. {&_44c2_s_p9_0,&_44c2_s_p9_1,&_44c2_s_p9_2}
  138546. }
  138547. };
  138548. static static_bookblock _resbook_44s_3={
  138549. {
  138550. {0},{0,0,&_44c3_s_p1_0},{0,0,&_44c3_s_p2_0},{0,0,&_44c3_s_p3_0},
  138551. {0,0,&_44c3_s_p4_0},{0,0,&_44c3_s_p5_0},{0,0,&_44c3_s_p6_0},
  138552. {&_44c3_s_p7_0,&_44c3_s_p7_1},{&_44c3_s_p8_0,&_44c3_s_p8_1},
  138553. {&_44c3_s_p9_0,&_44c3_s_p9_1,&_44c3_s_p9_2}
  138554. }
  138555. };
  138556. static static_bookblock _resbook_44s_4={
  138557. {
  138558. {0},{0,0,&_44c4_s_p1_0},{0,0,&_44c4_s_p2_0},{0,0,&_44c4_s_p3_0},
  138559. {0,0,&_44c4_s_p4_0},{0,0,&_44c4_s_p5_0},{0,0,&_44c4_s_p6_0},
  138560. {&_44c4_s_p7_0,&_44c4_s_p7_1},{&_44c4_s_p8_0,&_44c4_s_p8_1},
  138561. {&_44c4_s_p9_0,&_44c4_s_p9_1,&_44c4_s_p9_2}
  138562. }
  138563. };
  138564. static static_bookblock _resbook_44s_5={
  138565. {
  138566. {0},{0,0,&_44c5_s_p1_0},{0,0,&_44c5_s_p2_0},{0,0,&_44c5_s_p3_0},
  138567. {0,0,&_44c5_s_p4_0},{0,0,&_44c5_s_p5_0},{0,0,&_44c5_s_p6_0},
  138568. {&_44c5_s_p7_0,&_44c5_s_p7_1},{&_44c5_s_p8_0,&_44c5_s_p8_1},
  138569. {&_44c5_s_p9_0,&_44c5_s_p9_1,&_44c5_s_p9_2}
  138570. }
  138571. };
  138572. static static_bookblock _resbook_44s_6={
  138573. {
  138574. {0},{0,0,&_44c6_s_p1_0},{0,0,&_44c6_s_p2_0},{0,0,&_44c6_s_p3_0},
  138575. {0,0,&_44c6_s_p4_0},
  138576. {&_44c6_s_p5_0,&_44c6_s_p5_1},
  138577. {&_44c6_s_p6_0,&_44c6_s_p6_1},
  138578. {&_44c6_s_p7_0,&_44c6_s_p7_1},
  138579. {&_44c6_s_p8_0,&_44c6_s_p8_1},
  138580. {&_44c6_s_p9_0,&_44c6_s_p9_1,&_44c6_s_p9_2}
  138581. }
  138582. };
  138583. static static_bookblock _resbook_44s_7={
  138584. {
  138585. {0},{0,0,&_44c7_s_p1_0},{0,0,&_44c7_s_p2_0},{0,0,&_44c7_s_p3_0},
  138586. {0,0,&_44c7_s_p4_0},
  138587. {&_44c7_s_p5_0,&_44c7_s_p5_1},
  138588. {&_44c7_s_p6_0,&_44c7_s_p6_1},
  138589. {&_44c7_s_p7_0,&_44c7_s_p7_1},
  138590. {&_44c7_s_p8_0,&_44c7_s_p8_1},
  138591. {&_44c7_s_p9_0,&_44c7_s_p9_1,&_44c7_s_p9_2}
  138592. }
  138593. };
  138594. static static_bookblock _resbook_44s_8={
  138595. {
  138596. {0},{0,0,&_44c8_s_p1_0},{0,0,&_44c8_s_p2_0},{0,0,&_44c8_s_p3_0},
  138597. {0,0,&_44c8_s_p4_0},
  138598. {&_44c8_s_p5_0,&_44c8_s_p5_1},
  138599. {&_44c8_s_p6_0,&_44c8_s_p6_1},
  138600. {&_44c8_s_p7_0,&_44c8_s_p7_1},
  138601. {&_44c8_s_p8_0,&_44c8_s_p8_1},
  138602. {&_44c8_s_p9_0,&_44c8_s_p9_1,&_44c8_s_p9_2}
  138603. }
  138604. };
  138605. static static_bookblock _resbook_44s_9={
  138606. {
  138607. {0},{0,0,&_44c9_s_p1_0},{0,0,&_44c9_s_p2_0},{0,0,&_44c9_s_p3_0},
  138608. {0,0,&_44c9_s_p4_0},
  138609. {&_44c9_s_p5_0,&_44c9_s_p5_1},
  138610. {&_44c9_s_p6_0,&_44c9_s_p6_1},
  138611. {&_44c9_s_p7_0,&_44c9_s_p7_1},
  138612. {&_44c9_s_p8_0,&_44c9_s_p8_1},
  138613. {&_44c9_s_p9_0,&_44c9_s_p9_1,&_44c9_s_p9_2}
  138614. }
  138615. };
  138616. static vorbis_residue_template _res_44s_n1[]={
  138617. {2,0, &_residue_44_low,
  138618. &_huff_book__44cn1_s_short,&_huff_book__44cn1_sm_short,
  138619. &_resbook_44s_n1,&_resbook_44sm_n1},
  138620. {2,0, &_residue_44_low,
  138621. &_huff_book__44cn1_s_long,&_huff_book__44cn1_sm_long,
  138622. &_resbook_44s_n1,&_resbook_44sm_n1}
  138623. };
  138624. static vorbis_residue_template _res_44s_0[]={
  138625. {2,0, &_residue_44_low,
  138626. &_huff_book__44c0_s_short,&_huff_book__44c0_sm_short,
  138627. &_resbook_44s_0,&_resbook_44sm_0},
  138628. {2,0, &_residue_44_low,
  138629. &_huff_book__44c0_s_long,&_huff_book__44c0_sm_long,
  138630. &_resbook_44s_0,&_resbook_44sm_0}
  138631. };
  138632. static vorbis_residue_template _res_44s_1[]={
  138633. {2,0, &_residue_44_low,
  138634. &_huff_book__44c1_s_short,&_huff_book__44c1_sm_short,
  138635. &_resbook_44s_1,&_resbook_44sm_1},
  138636. {2,0, &_residue_44_low,
  138637. &_huff_book__44c1_s_long,&_huff_book__44c1_sm_long,
  138638. &_resbook_44s_1,&_resbook_44sm_1}
  138639. };
  138640. static vorbis_residue_template _res_44s_2[]={
  138641. {2,0, &_residue_44_mid,
  138642. &_huff_book__44c2_s_short,&_huff_book__44c2_s_short,
  138643. &_resbook_44s_2,&_resbook_44s_2},
  138644. {2,0, &_residue_44_mid,
  138645. &_huff_book__44c2_s_long,&_huff_book__44c2_s_long,
  138646. &_resbook_44s_2,&_resbook_44s_2}
  138647. };
  138648. static vorbis_residue_template _res_44s_3[]={
  138649. {2,0, &_residue_44_mid,
  138650. &_huff_book__44c3_s_short,&_huff_book__44c3_s_short,
  138651. &_resbook_44s_3,&_resbook_44s_3},
  138652. {2,0, &_residue_44_mid,
  138653. &_huff_book__44c3_s_long,&_huff_book__44c3_s_long,
  138654. &_resbook_44s_3,&_resbook_44s_3}
  138655. };
  138656. static vorbis_residue_template _res_44s_4[]={
  138657. {2,0, &_residue_44_mid,
  138658. &_huff_book__44c4_s_short,&_huff_book__44c4_s_short,
  138659. &_resbook_44s_4,&_resbook_44s_4},
  138660. {2,0, &_residue_44_mid,
  138661. &_huff_book__44c4_s_long,&_huff_book__44c4_s_long,
  138662. &_resbook_44s_4,&_resbook_44s_4}
  138663. };
  138664. static vorbis_residue_template _res_44s_5[]={
  138665. {2,0, &_residue_44_mid,
  138666. &_huff_book__44c5_s_short,&_huff_book__44c5_s_short,
  138667. &_resbook_44s_5,&_resbook_44s_5},
  138668. {2,0, &_residue_44_mid,
  138669. &_huff_book__44c5_s_long,&_huff_book__44c5_s_long,
  138670. &_resbook_44s_5,&_resbook_44s_5}
  138671. };
  138672. static vorbis_residue_template _res_44s_6[]={
  138673. {2,0, &_residue_44_high,
  138674. &_huff_book__44c6_s_short,&_huff_book__44c6_s_short,
  138675. &_resbook_44s_6,&_resbook_44s_6},
  138676. {2,0, &_residue_44_high,
  138677. &_huff_book__44c6_s_long,&_huff_book__44c6_s_long,
  138678. &_resbook_44s_6,&_resbook_44s_6}
  138679. };
  138680. static vorbis_residue_template _res_44s_7[]={
  138681. {2,0, &_residue_44_high,
  138682. &_huff_book__44c7_s_short,&_huff_book__44c7_s_short,
  138683. &_resbook_44s_7,&_resbook_44s_7},
  138684. {2,0, &_residue_44_high,
  138685. &_huff_book__44c7_s_long,&_huff_book__44c7_s_long,
  138686. &_resbook_44s_7,&_resbook_44s_7}
  138687. };
  138688. static vorbis_residue_template _res_44s_8[]={
  138689. {2,0, &_residue_44_high,
  138690. &_huff_book__44c8_s_short,&_huff_book__44c8_s_short,
  138691. &_resbook_44s_8,&_resbook_44s_8},
  138692. {2,0, &_residue_44_high,
  138693. &_huff_book__44c8_s_long,&_huff_book__44c8_s_long,
  138694. &_resbook_44s_8,&_resbook_44s_8}
  138695. };
  138696. static vorbis_residue_template _res_44s_9[]={
  138697. {2,0, &_residue_44_high,
  138698. &_huff_book__44c9_s_short,&_huff_book__44c9_s_short,
  138699. &_resbook_44s_9,&_resbook_44s_9},
  138700. {2,0, &_residue_44_high,
  138701. &_huff_book__44c9_s_long,&_huff_book__44c9_s_long,
  138702. &_resbook_44s_9,&_resbook_44s_9}
  138703. };
  138704. static vorbis_mapping_template _mapres_template_44_stereo[]={
  138705. { _map_nominal, _res_44s_n1 }, /* -1 */
  138706. { _map_nominal, _res_44s_0 }, /* 0 */
  138707. { _map_nominal, _res_44s_1 }, /* 1 */
  138708. { _map_nominal, _res_44s_2 }, /* 2 */
  138709. { _map_nominal, _res_44s_3 }, /* 3 */
  138710. { _map_nominal, _res_44s_4 }, /* 4 */
  138711. { _map_nominal, _res_44s_5 }, /* 5 */
  138712. { _map_nominal, _res_44s_6 }, /* 6 */
  138713. { _map_nominal, _res_44s_7 }, /* 7 */
  138714. { _map_nominal, _res_44s_8 }, /* 8 */
  138715. { _map_nominal, _res_44s_9 }, /* 9 */
  138716. };
  138717. /*** End of inlined file: residue_44.h ***/
  138718. /*** Start of inlined file: psych_44.h ***/
  138719. /* preecho trigger settings *****************************************/
  138720. static vorbis_info_psy_global _psy_global_44[5]={
  138721. {8, /* lines per eighth octave */
  138722. {20.f,14.f,12.f,12.f,12.f,12.f,12.f},
  138723. {-60.f,-30.f,-40.f,-40.f,-40.f,-40.f,-40.f}, 2,-75.f,
  138724. -6.f,
  138725. {99.},{{99.},{99.}},{0},{0},{{0.},{0.}}
  138726. },
  138727. {8, /* lines per eighth octave */
  138728. {14.f,10.f,10.f,10.f,10.f,10.f,10.f},
  138729. {-40.f,-30.f,-25.f,-25.f,-25.f,-25.f,-25.f}, 2,-80.f,
  138730. -6.f,
  138731. {99.},{{99.},{99.}},{0},{0},{{0.},{0.}}
  138732. },
  138733. {8, /* lines per eighth octave */
  138734. {12.f,10.f,10.f,10.f,10.f,10.f,10.f},
  138735. {-20.f,-20.f,-15.f,-15.f,-15.f,-15.f,-15.f}, 0,-80.f,
  138736. -6.f,
  138737. {99.},{{99.},{99.}},{0},{0},{{0.},{0.}}
  138738. },
  138739. {8, /* lines per eighth octave */
  138740. {10.f,8.f,8.f,8.f,8.f,8.f,8.f},
  138741. {-20.f,-15.f,-12.f,-12.f,-12.f,-12.f,-12.f}, 0,-80.f,
  138742. -6.f,
  138743. {99.},{{99.},{99.}},{0},{0},{{0.},{0.}}
  138744. },
  138745. {8, /* lines per eighth octave */
  138746. {10.f,6.f,6.f,6.f,6.f,6.f,6.f},
  138747. {-15.f,-15.f,-12.f,-12.f,-12.f,-12.f,-12.f}, 0,-85.f,
  138748. -6.f,
  138749. {99.},{{99.},{99.}},{0},{0},{{0.},{0.}}
  138750. },
  138751. };
  138752. /* noise compander lookups * low, mid, high quality ****************/
  138753. static compandblock _psy_compand_44[6]={
  138754. /* sub-mode Z short */
  138755. {{
  138756. 0, 1, 2, 3, 4, 5, 6, 7, /* 7dB */
  138757. 8, 9,10,11,12,13,14, 15, /* 15dB */
  138758. 16,17,18,19,20,21,22, 23, /* 23dB */
  138759. 24,25,26,27,28,29,30, 31, /* 31dB */
  138760. 32,33,34,35,36,37,38, 39, /* 39dB */
  138761. }},
  138762. /* mode_Z nominal short */
  138763. {{
  138764. 0, 1, 2, 3, 4, 5, 6, 6, /* 7dB */
  138765. 7, 7, 7, 7, 6, 6, 6, 7, /* 15dB */
  138766. 7, 8, 9,10,11,12,13, 14, /* 23dB */
  138767. 15,16,17,17,17,18,18, 19, /* 31dB */
  138768. 19,19,20,21,22,23,24, 25, /* 39dB */
  138769. }},
  138770. /* mode A short */
  138771. {{
  138772. 0, 1, 2, 3, 4, 5, 5, 5, /* 7dB */
  138773. 6, 6, 6, 5, 4, 4, 4, 4, /* 15dB */
  138774. 4, 4, 5, 5, 5, 6, 6, 6, /* 23dB */
  138775. 7, 7, 7, 8, 8, 8, 9, 10, /* 31dB */
  138776. 11,12,13,14,15,16,17, 18, /* 39dB */
  138777. }},
  138778. /* sub-mode Z long */
  138779. {{
  138780. 0, 1, 2, 3, 4, 5, 6, 7, /* 7dB */
  138781. 8, 9,10,11,12,13,14, 15, /* 15dB */
  138782. 16,17,18,19,20,21,22, 23, /* 23dB */
  138783. 24,25,26,27,28,29,30, 31, /* 31dB */
  138784. 32,33,34,35,36,37,38, 39, /* 39dB */
  138785. }},
  138786. /* mode_Z nominal long */
  138787. {{
  138788. 0, 1, 2, 3, 4, 5, 6, 7, /* 7dB */
  138789. 8, 9,10,11,12,12,13, 13, /* 15dB */
  138790. 13,14,14,14,15,15,15, 15, /* 23dB */
  138791. 16,16,17,17,17,18,18, 19, /* 31dB */
  138792. 19,19,20,21,22,23,24, 25, /* 39dB */
  138793. }},
  138794. /* mode A long */
  138795. {{
  138796. 0, 1, 2, 3, 4, 5, 6, 7, /* 7dB */
  138797. 8, 8, 7, 6, 5, 4, 4, 4, /* 15dB */
  138798. 4, 4, 5, 5, 5, 6, 6, 6, /* 23dB */
  138799. 7, 7, 7, 8, 8, 8, 9, 10, /* 31dB */
  138800. 11,12,13,14,15,16,17, 18, /* 39dB */
  138801. }}
  138802. };
  138803. /* tonal masking curve level adjustments *************************/
  138804. static vp_adjblock _vp_tonemask_adj_longblock[12]={
  138805. /* 63 125 250 500 1 2 4 8 16 */
  138806. {{ -3, -8,-13,-15,-10,-10,-10,-10,-10,-10,-10, 0, 0, 0, 0, 0, 0}}, /* -1 */
  138807. /* {{-15,-15,-15,-15,-10, -8, -4, -2, 0, 0, 0, 10, 0, 0, 0, 0, 0}}, 0 */
  138808. {{ -4,-10,-14,-16,-15,-14,-13,-12,-12,-12,-11, -1, -1, -1, -1, -1, 0}}, /* 0 */
  138809. /* {{-15,-15,-15,-15,-15,-12,-10, -8, 0, 0, 0, 5, 0, 0, 0, 0, 0}}, 1 */
  138810. {{ -6,-12,-14,-16,-15,-15,-14,-13,-13,-12,-12, -2, -2, -1, -1, -1, 0}}, /* 1 */
  138811. /* {{-15,-15,-15,-15,-15,-12,-10, -8, 0, 0, 0, 0, 0, 0, 0, 0, 0}}, 2 */
  138812. {{-12,-13,-14,-16,-16,-16,-15,-14,-13,-12,-12, -6, -3, -1, -1, -1, 0}}, /* 2 */
  138813. /* {{-15,-15,-15,-15,-15,-12,-10, -8, 0, 0, 0, 0, 0, 0, 0, 0, 0}}, 3 */
  138814. {{-15,-15,-15,-16,-16,-16,-16,-14,-13,-13,-13,-10, -4, -2, -1, -1, 0}}, /* 3 */
  138815. /* {{-15,-15,-15,-15,-15,-12,-10, -8, 0, 0, 0, 0, 0, 0, 0, 0, 0}}, *//* 4 */
  138816. {{-16,-16,-16,-16,-16,-16,-16,-15,-14,-14,-13,-11, -7 -3, -1, -1 , 0}}, /* 4 */
  138817. /* {{-15,-15,-15,-15,-15,-12,-10, -8, 0, 0, 0, 0, 0, 0, 0, 0, 0}}, 5 */
  138818. {{-16,-16,-16,-16,-16,-16,-16,-15,-14,-14,-13,-11, -7 -3, -1, -1 , 0}}, /* 5 */
  138819. /* {{-15,-15,-15,-15,-15,-12,-10, -8, 0, 0, 0, 0, 0, 0, 0, 0, 0}}, 6 */
  138820. {{-16,-16,-16,-16,-16,-16,-16,-15,-14,-14,-14,-12, -8, -4, -2, -2, 0}}, /* 6 */
  138821. /* {{-15,-15,-15,-15,-15,-12,-10, -8, 0, 0, 0, 0, 0, 0, 0, 0, 0}}, 7 */
  138822. {{-16,-16,-16,-16,-16,-16,-16,-15,-14,-14,-14,-12, -9, -4, -2, -2, 0}}, /* 7 */
  138823. /* {{-15,-15,-15,-15,-15,-12,-10, -8, 0, 0, 0, 0, 0, 0, 0, 0, 0}}, 8 */
  138824. {{-16,-16,-16,-16,-16,-16,-16,-15,-14,-14,-14,-12, -9, -4, -2, -2, 0}}, /* 8 */
  138825. /* {{-15,-15,-15,-15,-15,-12,-10, -8, 0, 0, 0, 0, 0, 0, 0, 0, 0}}, 9 */
  138826. {{-16,-16,-16,-16,-16,-16,-16,-15,-14,-14,-14,-12, -9, -4, -2, -2, 0}}, /* 9 */
  138827. /* {{-15,-15,-15,-15,-15,-12,-10, -8, 0, 0, 0, 0, 0, 0, 0, 0, 0}}, 10 */
  138828. {{-16,-16,-16,-16,-16,-16,-16,-15,-14,-14,-14,-12, -9, -4, -2, -2, 0}}, /* 10 */
  138829. };
  138830. static vp_adjblock _vp_tonemask_adj_otherblock[12]={
  138831. /* 63 125 250 500 1 2 4 8 16 */
  138832. {{ -3, -8,-13,-15,-10,-10, -9, -9, -9, -9, -9, 1, 1, 1, 1, 1, 1}}, /* -1 */
  138833. /* {{-20,-20,-20,-20,-14,-12,-10, -8, -4, 0, 0, 10, 0, 0, 0, 0, 0}}, 0 */
  138834. {{ -4,-10,-14,-16,-14,-13,-12,-12,-11,-11,-10, 0, 0, 0, 0, 0, 0}}, /* 0 */
  138835. /* {{-20,-20,-20,-20,-20,-18,-16,-14,-10, 0, 0, 5, 0, 0, 0, 0, 0}}, 1 */
  138836. {{ -6,-12,-14,-16,-15,-15,-14,-13,-13,-12,-12, -2, -2, -1, 0, 0, 0}}, /* 1 */
  138837. /* {{-20,-20,-20,-20,-20,-18,-16,-14,-10, 0, 0, 0, 0, 0, 0, 0, 0}}, 2 */
  138838. {{-12,-13,-14,-16,-16,-16,-15,-14,-13,-12,-12, -5, -2, -1, 0, 0, 0}}, /* 2 */
  138839. /* {{-20,-20,-20,-20,-20,-18,-16,-14,-10, 0, 0, 0, 0, 0, 0, 0, 0}}, 3 */
  138840. {{-15,-15,-15,-16,-16,-16,-16,-14,-13,-13,-13,-10, -4, -2, 0, 0, 0}}, /* 3 */
  138841. /* {{-20,-20,-20,-20,-20,-18,-16,-14,-10, 0, 0, 0, 0, 0, 0, 0, 0}}, 4 */
  138842. {{-16,-16,-16,-16,-16,-16,-16,-15,-14,-14,-13,-11, -7 -3, -1, -1 , 0}}, /* 4 */
  138843. /* {{-20,-20,-20,-20,-20,-18,-16,-14,-10, 0, 0, 0, 0, 0, 0, 0, 0}}, 5 */
  138844. {{-16,-16,-16,-16,-16,-16,-16,-15,-14,-14,-13,-11, -7 -3, -1, -1 , 0}}, /* 5 */
  138845. /* {{-20,-20,-20,-20,-20,-18,-16,-14,-10, 0, 0, 0, 0, 0, 0, 0, 0}}, 6 */
  138846. {{-16,-16,-16,-16,-16,-16,-16,-15,-14,-14,-14,-12, -8, -4, -2, -2, 0}}, /* 6 */
  138847. /* {{-20,-20,-20,-20,-20,-18,-16,-14,-10, 0, 0, 0, 0, 0, 0, 0, 0}}, 7 */
  138848. {{-16,-16,-16,-16,-16,-16,-16,-15,-14,-14,-14,-12, -9, -4, -2, -2, 0}}, /* 7 */
  138849. /* {{-20,-20,-20,-20,-20,-18,-16,-14,-10, 0, 0, 0, 0, 0, 0, 0, 0}}, 8 */
  138850. {{-16,-16,-16,-16,-16,-16,-16,-15,-14,-14,-14,-12, -9, -4, -2, -2, 0}}, /* 8 */
  138851. /* {{-20,-20,-20,-20,-20,-18,-16,-14,-10, 0, 0, 0, 0, 0, 0, 0, 0}}, 9 */
  138852. {{-16,-16,-16,-16,-16,-16,-16,-15,-14,-14,-14,-12, -9, -4, -2, -2, 0}}, /* 9 */
  138853. /* {{-20,-20,-20,-20,-20,-18,-16,-14,-10, 0, 0, 0, 0, 0, 0, 0, 0}}, 10 */
  138854. {{-16,-16,-16,-16,-16,-16,-16,-15,-14,-14,-14,-12, -9, -4, -2, -2, 0}}, /* 10 */
  138855. };
  138856. /* noise bias (transition block) */
  138857. static noise3 _psy_noisebias_trans[12]={
  138858. /* 63 125 250 500 1k 2k 4k 8k 16k*/
  138859. /* -1 */
  138860. {{{-10,-10,-10,-10,-10, -4, 0, 0, 4, 8, 8, 8, 8, 10, 12, 14, 20},
  138861. {-30,-30,-30,-30,-26,-20,-16, -8, -6, -6, -2, 2, 2, 3, 6, 6, 15},
  138862. {-30,-30,-30,-30,-30,-24,-20,-14,-10, -6, -8, -8, -6, -6, -6, -4, -2}}},
  138863. /* 0
  138864. {{{-15,-15,-15,-15,-15,-12,-10, -8, 0, 2, 4, 4, 5, 5, 5, 8, 10},
  138865. {-30,-30,-30,-30,-26,-22,-20,-14, -8, -4, 0, 0, 0, 0, 2, 4, 10},
  138866. {-30,-30,-30,-30,-26,-22,-20,-14,-10, -6, -6, -6, -6, -4, -4, -4, -2}}},*/
  138867. {{{-15,-15,-15,-15,-15,-12, -6, -4, 0, 2, 4, 4, 5, 5, 5, 8, 10},
  138868. {-30,-30,-30,-30,-26,-22,-20,-14, -8, -4, 0, 0, 0, 0, 2, 3, 6},
  138869. {-30,-30,-30,-30,-26,-22,-20,-14,-10, -6, -6, -6, -6, -4, -4, -4, -2}}},
  138870. /* 1
  138871. {{{-15,-15,-15,-15,-15,-12,-10, -8, 0, 2, 4, 4, 5, 5, 5, 8, 10},
  138872. {-30,-30,-30,-30,-26,-22,-20,-14,-10, -4, -2, -2, -2, -2, 0, 2, 8},
  138873. {-30,-30,-30,-30,-26,-22,-20,-14,-10, -8, -8, -8, -8, -6, -6, -6, -4}}},*/
  138874. {{{-15,-15,-15,-15,-15,-12,-10, -8, 0, 2, 4, 4, 5, 5, 5, 8, 10},
  138875. {-30,-30,-30,-30,-26,-22,-20,-14,-10, -4, -2, -2, -2, -2, 0, 1, 4},
  138876. {-30,-30,-30,-30,-26,-22,-20,-14,-10, -8, -8, -8, -8, -6, -6, -6, -4}}},
  138877. /* 2
  138878. {{{-15,-15,-15,-15,-15,-12,-10, -8, 0, 2, 2, 2, 4, 4, 5, 6, 10},
  138879. {-30,-30,-30,-30,-26,-22,-20,-14,-10, -4, -2, -2, -2, -2, 0, 2, 6},
  138880. {-30,-30,-30,-30,-26,-22,-20,-14,-10,-10,-10,-10,-10, -8, -8, -8, -4}}}, */
  138881. {{{-15,-15,-15,-15,-15,-12,-10, -8, 0, 2, 2, 2, 4, 4, 5, 6, 10},
  138882. {-30,-30,-30,-30,-26,-22,-20,-14,-10, -4, -3, -3, -3, -2, -1, 0, 3},
  138883. {-30,-30,-30,-30,-26,-22,-20,-14,-10,-10,-10,-10,-10, -8, -8, -7, -4}}},
  138884. /* 3
  138885. {{{-15,-15,-15,-15,-15,-12,-10, -8, 0, 2, 2, 2, 4, 4, 4, 5, 8},
  138886. {-30,-30,-30,-30,-26,-22,-20,-14,-10, -4, -3, -3, -3, -3, -1, 1, 6},
  138887. {-30,-30,-30,-30,-26,-22,-20,-14,-10,-10,-10,-10,-10, -8, -8, -8, -4}}},*/
  138888. {{{-15,-15,-15,-15,-15,-12,-10, -8, 0, 2, 2, 2, 4, 4, 4, 5, 8},
  138889. {-30,-30,-30,-30,-26,-22,-20,-14,-10, -4, -3, -3, -3, -3, -2, 0, 2},
  138890. {-30,-30,-30,-30,-26,-22,-20,-14,-10,-10,-10,-10,-10, -8, -8, -8, -4}}},
  138891. /* 4
  138892. {{{-20,-20,-20,-20,-20,-18,-14, -8, -1, 1, 1, 1, 2, 3, 3, 4, 7},
  138893. {-30,-30,-30,-30,-26,-22,-20,-14,-10, -4, -3, -3, -3, -3, -1, 1, 5},
  138894. {-30,-30,-30,-30,-26,-22,-20,-14,-10,-10,-10,-10,-10, -8, -8, -8, -4}}},*/
  138895. {{{-20,-20,-20,-20,-20,-18,-14, -8, -1, 1, 1, 1, 2, 3, 3, 4, 7},
  138896. {-30,-30,-30,-30,-26,-22,-20,-14,-10, -4, -3, -3, -3, -3, -2, -1, 1},
  138897. {-30,-30,-30,-30,-26,-22,-20,-14,-10,-10,-10,-10,-10, -8, -8, -8, -4}}},
  138898. /* 5
  138899. {{{-24,-24,-24,-24,-20,-18,-14, -8, -1, 1, 1, 1, 2, 3, 3, 4, 7},
  138900. {-32,-32,-32,-32,-28,-24,-22,-16,-12, -6, -4, -4, -4, -4, -2, -1, 2},
  138901. {-34,-34,-34,-34,-30,-24,-24,-18,-14,-12,-12,-12,-12,-10,-10, -9, -5}}}, */
  138902. {{{-24,-24,-24,-24,-20,-18,-14, -8, -1, 1, 1, 1, 2, 3, 3, 4, 7},
  138903. {-32,-32,-32,-32,-28,-24,-22,-16,-12, -6, -4, -4, -4, -4, -3, -1, 0},
  138904. {-34,-34,-34,-34,-30,-24,-24,-18,-14,-12,-12,-12,-12,-10,-10, -9, -5}}},
  138905. /* 6
  138906. {{{-24,-24,-24,-24,-20,-18,-14, -8, -1, 1, 1, 1, 2, 3, 3, 4, 7},
  138907. {-32,-32,-32,-32,-28,-24,-24,-18,-14, -8, -6, -6, -6, -6, -4, -2, 1},
  138908. {-34,-34,-34,-34,-30,-26,-24,-18,-17,-15,-15,-15,-15,-13,-13,-12, -8}}},*/
  138909. {{{-24,-24,-24,-24,-20,-18,-14, -8, -1, 1, 1, 1, 2, 3, 3, 4, 7},
  138910. {-32,-32,-32,-32,-28,-24,-24,-18,-14, -8, -6, -6, -6, -6, -5, -2, 0},
  138911. {-34,-34,-34,-34,-30,-26,-26,-24,-22,-19,-19,-19,-19,-18,-17,-16,-12}}},
  138912. /* 7
  138913. {{{-24,-24,-24,-24,-20,-18,-14, -8, -1, 1, 1, 1, 2, 3, 3, 4, 7},
  138914. {-32,-32,-32,-32,-28,-24,-24,-18,-14,-12,-10, -8, -8, -8, -6, -4, 0},
  138915. {-34,-34,-34,-34,-30,-26,-26,-24,-22,-19,-19,-19,-19,-18,-17,-16,-12}}},*/
  138916. {{{-24,-24,-24,-24,-20,-18,-14, -8, -1, 1, 1, 1, 2, 3, 3, 4, 7},
  138917. {-32,-32,-32,-32,-28,-24,-24,-24,-18,-14,-12,-10,-10,-10, -8, -6, -2},
  138918. {-34,-34,-34,-34,-30,-26,-26,-26,-24,-24,-24,-24,-24,-24,-24,-20,-16}}},
  138919. /* 8
  138920. {{{-24,-24,-24,-24,-22,-20,-15,-10, -8, -2, 0, 0, 0, 1, 2, 3, 7},
  138921. {-36,-36,-36,-36,-30,-30,-30,-24,-18,-14,-12,-10,-10,-10, -8, -6, -2},
  138922. {-36,-36,-36,-36,-34,-30,-28,-26,-24,-24,-24,-24,-24,-24,-24,-20,-16}}},*/
  138923. {{{-24,-24,-24,-24,-22,-20,-15,-10, -8, -2, 0, 0, 0, 1, 2, 3, 7},
  138924. {-36,-36,-36,-36,-30,-30,-30,-24,-20,-16,-16,-16,-16,-14,-12,-10, -7},
  138925. {-36,-36,-36,-36,-34,-30,-28,-26,-24,-30,-30,-30,-30,-30,-30,-24,-20}}},
  138926. /* 9
  138927. {{{-28,-28,-28,-28,-28,-28,-28,-20,-14, -8, -4, -4, -4, -4, -4, -2, 2},
  138928. {-36,-36,-36,-36,-34,-32,-32,-28,-20,-16,-16,-16,-16,-14,-12,-10, -7},
  138929. {-40,-40,-40,-40,-40,-40,-40,-32,-30,-30,-30,-30,-30,-30,-30,-24,-20}}},*/
  138930. {{{-28,-28,-28,-28,-28,-28,-28,-20,-14, -8, -4, -4, -4, -4, -4, -2, 2},
  138931. {-38,-38,-38,-38,-36,-34,-34,-30,-24,-20,-20,-20,-20,-18,-16,-12,-10},
  138932. {-40,-40,-40,-40,-40,-40,-40,-38,-35,-35,-35,-35,-35,-35,-35,-35,-30}}},
  138933. /* 10 */
  138934. {{{-30,-30,-30,-30,-30,-30,-30,-28,-20,-14,-14,-14,-14,-14,-14,-12,-10},
  138935. {-40,-40,-40,-40,-40,-40,-40,-40,-35,-30,-30,-30,-30,-30,-30,-30,-20},
  138936. {-40,-40,-40,-40,-40,-40,-40,-40,-40,-40,-40,-40,-40,-40,-40,-40,-40}}},
  138937. };
  138938. /* noise bias (long block) */
  138939. static noise3 _psy_noisebias_long[12]={
  138940. /*63 125 250 500 1k 2k 4k 8k 16k*/
  138941. /* -1 */
  138942. {{{-10,-10,-10,-10,-10, -4, 0, 0, 0, 6, 6, 6, 6, 10, 10, 12, 20},
  138943. {-20,-20,-20,-20,-20,-20,-10, -2, 0, 0, 0, 0, 0, 2, 4, 6, 15},
  138944. {-20,-20,-20,-20,-20,-20,-20,-10, -6, -6, -6, -6, -6, -4, -4, -4, -2}}},
  138945. /* 0 */
  138946. /* {{{-10,-10,-10,-10,-10,-10, -8, 2, 2, 2, 4, 4, 5, 5, 5, 8, 10},
  138947. {-20,-20,-20,-20,-20,-20,-20,-14, -6, 0, 0, 0, 0, 0, 2, 4, 10},
  138948. {-20,-20,-20,-20,-20,-20,-20,-14, -8, -6, -6, -6, -6, -4, -4, -4, -2}}},*/
  138949. {{{-10,-10,-10,-10,-10,-10, -8, 2, 2, 2, 4, 4, 5, 5, 5, 8, 10},
  138950. {-20,-20,-20,-20,-20,-20,-20,-14, -6, 0, 0, 0, 0, 0, 2, 3, 6},
  138951. {-20,-20,-20,-20,-20,-20,-20,-14, -8, -6, -6, -6, -6, -4, -4, -4, -2}}},
  138952. /* 1 */
  138953. /* {{{-10,-10,-10,-10,-10,-10, -8, -4, 0, 2, 4, 4, 5, 5, 5, 8, 10},
  138954. {-20,-20,-20,-20,-20,-20,-20,-14,-10, -4, -2, -2, -2, -2, 0, 2, 8},
  138955. {-20,-20,-20,-20,-20,-20,-20,-14,-10, -8, -8, -8, -8, -6, -6, -6, -4}}},*/
  138956. {{{-10,-10,-10,-10,-10,-10, -8, -4, 0, 2, 4, 4, 5, 5, 5, 8, 10},
  138957. {-20,-20,-20,-20,-20,-20,-20,-14,-10, -4, -2, -2, -2, -2, 0, 1, 4},
  138958. {-20,-20,-20,-20,-20,-20,-20,-14,-10, -8, -8, -8, -8, -6, -6, -6, -4}}},
  138959. /* 2 */
  138960. /* {{{-10,-10,-10,-10,-10,-10,-10, -8, 0, 2, 2, 2, 4, 4, 5, 6, 10},
  138961. {-20,-20,-20,-20,-20,-20,-20,-14,-10, -4, -2, -2, -2, -2, 0, 2, 6},
  138962. {-20,-20,-20,-20,-20,-20,-20,-14,-10,-10,-10,-10,-10, -8, -8, -8, -4}}},*/
  138963. {{{-10,-10,-10,-10,-10,-10,-10, -8, 0, 2, 2, 2, 4, 4, 5, 6, 10},
  138964. {-20,-20,-20,-20,-20,-20,-20,-14,-10, -4, -3, -3, -3, -2, -1, 0, 3},
  138965. {-20,-20,-20,-20,-20,-20,-20,-14,-10,-10,-10,-10,-10, -8, -8, -8, -4}}},
  138966. /* 3 */
  138967. /* {{{-10,-10,-10,-10,-10,-10,-10, -8, 0, 2, 2, 2, 4, 4, 4, 5, 8},
  138968. {-20,-20,-20,-20,-20,-20,-20,-14,-10, -4, -3, -3, -3, -3, -1, 1, 6},
  138969. {-20,-20,-20,-20,-20,-20,-20,-14,-10,-10,-10,-10,-10, -8, -8, -8, -4}}},*/
  138970. {{{-10,-10,-10,-10,-10,-10,-10, -8, 0, 2, 2, 2, 4, 4, 4, 5, 8},
  138971. {-20,-20,-20,-20,-20,-20,-20,-14,-10, -4, -3, -3, -3, -3, -2, 0, 2},
  138972. {-20,-20,-20,-20,-20,-20,-20,-14,-10,-10,-10,-10,-10, -8, -8, -8, -5}}},
  138973. /* 4 */
  138974. /* {{{-15,-15,-15,-15,-15,-15,-15,-10, -4, 1, 1, 1, 2, 3, 3, 4, 7},
  138975. {-20,-20,-20,-20,-20,-20,-20,-14,-10, -4, -3, -3, -3, -3, -1, 1, 5},
  138976. {-20,-20,-20,-20,-20,-20,-20,-14,-10,-10,-10,-10,-10, -8, -8, -8, -4}}},*/
  138977. {{{-15,-15,-15,-15,-15,-15,-15,-10, -4, 1, 1, 1, 2, 3, 3, 4, 7},
  138978. {-20,-20,-20,-20,-20,-20,-20,-14,-10, -4, -3, -3, -3, -3, -2, -1, 1},
  138979. {-20,-20,-20,-20,-20,-20,-20,-14,-10,-10,-10,-10,-10, -8, -8, -8, -7}}},
  138980. /* 5 */
  138981. /* {{{-15,-15,-15,-15,-15,-15,-15,-10, -4, 1, 1, 1, 2, 3, 3, 4, 7},
  138982. {-22,-22,-22,-22,-22,-22,-22,-16,-12, -6, -4, -4, -4, -4, -2, -1, 2},
  138983. {-24,-24,-24,-24,-24,-24,-24,-18,-14,-12,-12,-12,-12,-10,-10, -9, -5}}},*/
  138984. {{{-15,-15,-15,-15,-15,-15,-15,-10, -4, 1, 1, 1, 2, 3, 3, 4, 7},
  138985. {-22,-22,-22,-22,-22,-22,-22,-16,-12, -6, -4, -4, -4, -4, -3, -1, 0},
  138986. {-24,-24,-24,-24,-24,-24,-24,-18,-14,-12,-12,-12,-12,-10,-10, -9, -8}}},
  138987. /* 6 */
  138988. /* {{{-15,-15,-15,-15,-15,-15,-15,-10, -4, 1, 1, 1, 2, 3, 3, 4, 7},
  138989. {-24,-24,-24,-24,-24,-24,-24,-18,-14, -8, -6, -6, -6, -6, -4, -2, 1},
  138990. {-26,-26,-26,-26,-26,-26,-26,-18,-16,-15,-15,-15,-15,-13,-13,-12, -8}}},*/
  138991. {{{-15,-15,-15,-15,-15,-15,-15,-10, -4, 1, 1, 1, 2, 3, 3, 4, 7},
  138992. {-24,-24,-24,-24,-24,-24,-24,-18,-14, -8, -6, -6, -6, -6, -5, -2, 0},
  138993. {-26,-26,-26,-26,-26,-26,-26,-18,-16,-15,-15,-15,-15,-13,-13,-12,-10}}},
  138994. /* 7 */
  138995. {{{-15,-15,-15,-15,-15,-15,-15,-10, -4, 1, 1, 1, 2, 3, 3, 4, 7},
  138996. {-24,-24,-24,-24,-24,-24,-24,-18,-14,-10, -8, -8, -8, -8, -6, -4, 0},
  138997. {-26,-26,-26,-26,-26,-26,-26,-22,-20,-19,-19,-19,-19,-18,-17,-16,-12}}},
  138998. /* 8 */
  138999. {{{-15,-15,-15,-15,-15,-15,-15,-10, -4, 0, 0, 0, 0, 1, 2, 3, 7},
  139000. {-26,-26,-26,-26,-26,-26,-26,-20,-16,-12,-10,-10,-10,-10, -8, -6, -2},
  139001. {-28,-28,-28,-28,-28,-28,-28,-26,-24,-24,-24,-24,-24,-24,-24,-20,-16}}},
  139002. /* 9 */
  139003. {{{-22,-22,-22,-22,-22,-22,-22,-18,-14, -8, -4, -4, -4, -4, -4, -2, 2},
  139004. {-26,-26,-26,-26,-26,-26,-26,-22,-18,-16,-16,-16,-16,-14,-12,-10, -7},
  139005. {-30,-30,-30,-30,-30,-30,-30,-30,-30,-30,-30,-30,-30,-30,-30,-24,-20}}},
  139006. /* 10 */
  139007. {{{-24,-24,-24,-24,-24,-24,-24,-24,-24,-18,-14,-14,-14,-14,-14,-12,-10},
  139008. {-30,-30,-30,-30,-30,-30,-30,-30,-30,-30,-30,-30,-30,-30,-30,-30,-20},
  139009. {-40,-40,-40,-40,-40,-40,-40,-40,-40,-40,-40,-40,-40,-40,-40,-40,-40}}},
  139010. };
  139011. /* noise bias (impulse block) */
  139012. static noise3 _psy_noisebias_impulse[12]={
  139013. /* 63 125 250 500 1k 2k 4k 8k 16k*/
  139014. /* -1 */
  139015. {{{-10,-10,-10,-10,-10, -4, 0, 0, 4, 8, 8, 8, 8, 10, 12, 14, 20},
  139016. {-30,-30,-30,-30,-26,-20,-16, -8, -6, -6, -2, 2, 2, 3, 6, 6, 15},
  139017. {-30,-30,-30,-30,-30,-24,-20,-14,-10, -6, -8, -8, -6, -6, -6, -4, -2}}},
  139018. /* 0 */
  139019. /* {{{-10,-10,-10,-10,-10, -4, 0, 0, 4, 4, 8, 8, 8, 10, 12, 14, 20},
  139020. {-30,-30,-30,-30,-26,-22,-20,-14, -6, -2, 0, 0, 0, 0, 2, 4, 10},
  139021. {-30,-30,-30,-30,-30,-24,-20,-14,-10, -6, -8, -8, -6, -6, -6, -4, -2}}},*/
  139022. {{{-10,-10,-10,-10,-10, -4, 0, 0, 4, 4, 8, 8, 8, 10, 12, 14, 20},
  139023. {-30,-30,-30,-30,-26,-22,-20,-14, -6, -2, 0, 0, 0, 0, 2, 3, 6},
  139024. {-30,-30,-30,-30,-30,-24,-20,-14,-10, -6, -8, -8, -6, -6, -6, -4, -2}}},
  139025. /* 1 */
  139026. {{{-12,-12,-12,-12,-12, -8, -6, -4, 0, 4, 4, 4, 4, 10, 12, 14, 20},
  139027. {-30,-30,-30,-30,-26,-22,-20,-14,-10, -6, -4, -4, -2, -2, -2, -2, 2},
  139028. {-30,-30,-30,-30,-26,-22,-20,-14,-10, -8,-10,-10, -8, -8, -8, -6, -4}}},
  139029. /* 2 */
  139030. {{{-14,-14,-14,-14,-14,-10, -8, -6, -2, 2, 2, 2, 2, 8, 10, 10, 16},
  139031. {-30,-30,-30,-30,-26,-22,-20,-14,-10, -6, -6, -6, -4, -4, -4, -2, 0},
  139032. {-30,-30,-30,-30,-26,-22,-20,-14,-10,-10,-10,-10,-10,-10,-10, -8, -4}}},
  139033. /* 3 */
  139034. {{{-14,-14,-14,-14,-14,-10, -8, -6, -2, 2, 2, 2, 2, 6, 8, 8, 14},
  139035. {-30,-30,-30,-30,-26,-22,-20,-14,-10, -6, -6, -6, -4, -4, -4, -2, 0},
  139036. {-30,-30,-30,-30,-26,-22,-20,-14,-10,-10,-10,-10,-10,-10,-10, -8, -4}}},
  139037. /* 4 */
  139038. {{{-16,-16,-16,-16,-16,-12,-10, -6, -2, 0, 0, 0, 0, 4, 6, 6, 12},
  139039. {-30,-30,-30,-30,-26,-22,-20,-14,-10, -6, -6, -6, -4, -4, -4, -2, 0},
  139040. {-30,-30,-30,-30,-26,-22,-20,-14,-10,-10,-10,-10,-10,-10,-10, -8, -4}}},
  139041. /* 5 */
  139042. {{{-20,-20,-20,-20,-20,-18,-14,-10, -4, 0, 0, 0, 0, 4, 4, 6, 11},
  139043. {-32,-32,-32,-32,-28,-24,-22,-16,-10, -6, -8, -8, -6, -6, -6, -4, -2},
  139044. {-34,-34,-34,-34,-30,-26,-24,-18,-14,-12,-12,-12,-12,-12,-10, -9, -5}}},
  139045. /* 6
  139046. {{{-20,-20,-20,-20,-20,-18,-14,-10, -4, 0, 0, 0, 0, 4, 4, 6, 11},
  139047. {-34,-34,-34,-34,-30,-30,-24,-20,-12,-12,-14,-14,-10, -9, -8, -6, -4},
  139048. {-34,-34,-34,-34,-34,-30,-26,-20,-16,-15,-15,-15,-15,-15,-13,-12, -8}}},*/
  139049. {{{-20,-20,-20,-20,-20,-18,-14,-10, -4, 0, 0, 0, 0, 4, 4, 6, 11},
  139050. {-34,-34,-34,-34,-30,-30,-30,-24,-16,-16,-16,-16,-16,-16,-14,-14,-12},
  139051. {-36,-36,-36,-36,-36,-34,-28,-24,-20,-20,-20,-20,-20,-20,-20,-18,-16}}},
  139052. /* 7 */
  139053. /* {{{-22,-22,-22,-22,-22,-20,-14,-10, -6, 0, 0, 0, 0, 4, 4, 6, 11},
  139054. {-34,-34,-34,-34,-30,-30,-24,-20,-14,-14,-16,-16,-14,-12,-10,-10,-10},
  139055. {-34,-34,-34,-34,-32,-32,-30,-24,-20,-19,-19,-19,-19,-19,-17,-16,-12}}},*/
  139056. {{{-22,-22,-22,-22,-22,-20,-14,-10, -6, 0, 0, 0, 0, 4, 4, 6, 11},
  139057. {-34,-34,-34,-34,-30,-30,-30,-30,-26,-26,-26,-26,-26,-26,-26,-24,-22},
  139058. {-40,-40,-40,-40,-40,-40,-40,-32,-30,-30,-30,-30,-30,-30,-30,-30,-24}}},
  139059. /* 8 */
  139060. /* {{{-24,-24,-24,-24,-24,-22,-14,-10, -6, -1, -1, -1, -1, 3, 3, 5, 10},
  139061. {-34,-34,-34,-34,-30,-30,-30,-24,-20,-20,-20,-20,-20,-18,-16,-16,-14},
  139062. {-36,-36,-36,-36,-36,-34,-28,-24,-24,-24,-24,-24,-24,-24,-24,-20,-16}}},*/
  139063. {{{-24,-24,-24,-24,-24,-22,-14,-10, -6, -1, -1, -1, -1, 3, 3, 5, 10},
  139064. {-34,-34,-34,-34,-34,-32,-32,-30,-26,-26,-26,-26,-26,-26,-26,-26,-24},
  139065. {-40,-40,-40,-40,-40,-40,-40,-32,-30,-30,-30,-30,-30,-30,-30,-30,-24}}},
  139066. /* 9 */
  139067. /* {{{-28,-28,-28,-28,-28,-28,-28,-20,-14, -8, -4, -4, -4, -4, -4, -2, 2},
  139068. {-36,-36,-36,-36,-34,-32,-32,-30,-26,-26,-26,-26,-26,-22,-20,-20,-18},
  139069. {-40,-40,-40,-40,-40,-40,-40,-32,-30,-30,-30,-30,-30,-30,-30,-24,-20}}},*/
  139070. {{{-28,-28,-28,-28,-28,-28,-28,-20,-14, -8, -4, -4, -4, -4, -4, -2, 2},
  139071. {-36,-36,-36,-36,-34,-32,-32,-30,-26,-26,-26,-26,-26,-26,-26,-26,-26},
  139072. {-40,-40,-40,-40,-40,-40,-40,-32,-30,-30,-30,-30,-30,-30,-30,-24,-20}}},
  139073. /* 10 */
  139074. {{{-30,-30,-30,-30,-30,-26,-24,-24,-24,-20,-16,-16,-16,-16,-16,-14,-12},
  139075. {-40,-40,-40,-40,-40,-40,-40,-40,-35,-30,-30,-30,-30,-30,-30,-30,-26},
  139076. {-40,-40,-40,-40,-40,-40,-40,-40,-40,-40,-40,-40,-40,-40,-40,-40,-40}}},
  139077. };
  139078. /* noise bias (padding block) */
  139079. static noise3 _psy_noisebias_padding[12]={
  139080. /* 63 125 250 500 1k 2k 4k 8k 16k*/
  139081. /* -1 */
  139082. {{{-10,-10,-10,-10,-10, -4, 0, 0, 4, 8, 8, 8, 8, 10, 12, 14, 20},
  139083. {-30,-30,-30,-30,-26,-20,-16, -8, -6, -6, -2, 2, 2, 3, 6, 6, 15},
  139084. {-30,-30,-30,-30,-30,-24,-20,-14,-10, -6, -8, -8, -6, -6, -6, -4, -2}}},
  139085. /* 0 */
  139086. {{{-10,-10,-10,-10,-10, -4, 0, 0, 4, 8, 8, 8, 8, 10, 12, 14, 20},
  139087. {-30,-30,-30,-30,-26,-22,-20,-14,-10, -4, -2, 2, 3, 6, 6, 8, 10},
  139088. {-30,-30,-30,-30,-26,-22,-20,-14,-10, -4, -4, -4, -4, -4, -2, 0, 2}}},
  139089. /* 1 */
  139090. {{{-12,-12,-12,-12,-12, -8, -6, -4, 0, 4, 4, 4, 4, 10, 12, 14, 20},
  139091. {-30,-30,-30,-30,-26,-22,-20,-14,-10, -4, 0, 0, 0, 2, 2, 4, 8},
  139092. {-30,-30,-30,-30,-26,-22,-20,-14,-10, -6, -6, -6, -6, -6, -4, -2, 0}}},
  139093. /* 2 */
  139094. /* {{{-14,-14,-14,-14,-14,-10, -8, -6, -2, 2, 2, 2, 2, 8, 10, 10, 16},
  139095. {-30,-30,-30,-30,-26,-22,-20,-14,-10, -4, 0, 0, 0, 2, 2, 4, 8},
  139096. {-30,-30,-30,-30,-26,-22,-20,-14,-10, -8, -8, -8, -8, -8, -6, -4, -2}}},*/
  139097. {{{-14,-14,-14,-14,-14,-10, -8, -6, -2, 2, 2, 2, 2, 8, 10, 10, 16},
  139098. {-30,-30,-30,-30,-26,-22,-20,-14,-10, -6, -1, -1, -1, 0, 0, 2, 6},
  139099. {-30,-30,-30,-30,-26,-22,-20,-14,-10, -8, -8, -8, -8, -8, -6, -4, -2}}},
  139100. /* 3 */
  139101. {{{-14,-14,-14,-14,-14,-10, -8, -6, -2, 2, 2, 2, 2, 6, 8, 8, 14},
  139102. {-30,-30,-30,-30,-26,-22,-20,-14,-10, -6, -1, -1, -1, 0, 0, 2, 6},
  139103. {-30,-30,-30,-30,-26,-22,-20,-14,-10, -8, -8, -8, -8, -8, -6, -4, -2}}},
  139104. /* 4 */
  139105. {{{-16,-16,-16,-16,-16,-12,-10, -6, -2, 0, 0, 0, 0, 4, 6, 6, 12},
  139106. {-30,-30,-30,-30,-26,-22,-20,-14,-10, -6, -1, -1, -1, -1, 0, 2, 6},
  139107. {-30,-30,-30,-30,-26,-22,-20,-14,-10, -8, -8, -8, -8, -8, -6, -4, -2}}},
  139108. /* 5 */
  139109. {{{-20,-20,-20,-20,-20,-18,-14,-10, -4, 0, 0, 0, 0, 4, 6, 6, 12},
  139110. {-32,-32,-32,-32,-28,-24,-22,-16,-12, -6, -3, -3, -3, -3, -2, 0, 4},
  139111. {-34,-34,-34,-34,-30,-26,-24,-18,-14,-10,-10,-10,-10,-10, -8, -5, -3}}},
  139112. /* 6 */
  139113. {{{-20,-20,-20,-20,-20,-18,-14,-10, -4, 0, 0, 0, 0, 4, 6, 6, 12},
  139114. {-34,-34,-34,-34,-30,-30,-24,-20,-14, -8, -4, -4, -4, -4, -3, -1, 4},
  139115. {-34,-34,-34,-34,-34,-30,-26,-20,-16,-13,-13,-13,-13,-13,-11, -8, -6}}},
  139116. /* 7 */
  139117. {{{-20,-20,-20,-20,-20,-18,-14,-10, -4, 0, 0, 0, 0, 4, 6, 6, 12},
  139118. {-34,-34,-34,-34,-30,-30,-30,-24,-16,-10, -8, -6, -6, -6, -5, -3, 1},
  139119. {-34,-34,-34,-34,-32,-32,-28,-22,-18,-16,-16,-16,-16,-16,-14,-12,-10}}},
  139120. /* 8 */
  139121. {{{-22,-22,-22,-22,-22,-20,-14,-10, -4, 0, 0, 0, 0, 3, 5, 5, 11},
  139122. {-34,-34,-34,-34,-30,-30,-30,-24,-16,-12,-10, -8, -8, -8, -7, -5, -2},
  139123. {-36,-36,-36,-36,-36,-34,-28,-22,-20,-20,-20,-20,-20,-20,-20,-16,-14}}},
  139124. /* 9 */
  139125. {{{-28,-28,-28,-28,-28,-28,-28,-20,-14, -8, -2, -2, -2, -2, 0, 2, 6},
  139126. {-36,-36,-36,-36,-34,-32,-32,-24,-16,-12,-12,-12,-12,-12,-10, -8, -5},
  139127. {-40,-40,-40,-40,-40,-40,-40,-32,-26,-24,-24,-24,-24,-24,-24,-20,-18}}},
  139128. /* 10 */
  139129. {{{-30,-30,-30,-30,-30,-26,-24,-24,-24,-20,-12,-12,-12,-12,-12,-10, -8},
  139130. {-40,-40,-40,-40,-40,-40,-40,-40,-35,-30,-25,-25,-25,-25,-25,-25,-15},
  139131. {-40,-40,-40,-40,-40,-40,-40,-40,-40,-40,-40,-40,-40,-40,-40,-40,-40}}},
  139132. };
  139133. static noiseguard _psy_noiseguards_44[4]={
  139134. {3,3,15},
  139135. {3,3,15},
  139136. {10,10,100},
  139137. {10,10,100},
  139138. };
  139139. static int _psy_tone_suppress[12]={
  139140. -20,-20,-20,-20,-20,-24,-30,-40,-40,-45,-45,-45,
  139141. };
  139142. static int _psy_tone_0dB[12]={
  139143. 90,90,95,95,95,95,105,105,105,105,105,105,
  139144. };
  139145. static int _psy_noise_suppress[12]={
  139146. -20,-20,-24,-24,-24,-24,-30,-40,-40,-45,-45,-45,
  139147. };
  139148. static vorbis_info_psy _psy_info_template={
  139149. /* blockflag */
  139150. -1,
  139151. /* ath_adjatt, ath_maxatt */
  139152. -140.,-140.,
  139153. /* tonemask att boost/decay,suppr,curves */
  139154. {0.f,0.f,0.f}, 0.,0., -40.f, {0.},
  139155. /*noisemaskp,supp, low/high window, low/hi guard, minimum */
  139156. 1, -0.f, .5f, .5f, 0,0,0,
  139157. /* noiseoffset*3, noisecompand, max_curve_dB */
  139158. {{-1},{-1},{-1}},{-1},105.f,
  139159. /* noise normalization - channel_p, point_p, start, partition, thresh. */
  139160. 0,0,-1,-1,0.,
  139161. };
  139162. /* ath ****************/
  139163. static int _psy_ath_floater[12]={
  139164. -100,-100,-100,-100,-100,-100,-105,-105,-105,-105,-110,-120,
  139165. };
  139166. static int _psy_ath_abs[12]={
  139167. -130,-130,-130,-130,-140,-140,-140,-140,-140,-140,-140,-150,
  139168. };
  139169. /* stereo setup. These don't map directly to quality level, there's
  139170. an additional indirection as several of the below may be used in a
  139171. single bitmanaged stream
  139172. ****************/
  139173. /* various stereo possibilities */
  139174. /* stereo mode by base quality level */
  139175. static adj_stereo _psy_stereo_modes_44[12]={
  139176. /* 0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 -1 */
  139177. {{ 4, 4, 4, 4, 4, 4, 4, 3, 2, 2, 1, 0, 0, 0, 0},
  139178. { 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 5, 4, 3},
  139179. { 1, 2, 3, 4, 4, 4, 4, 4, 4, 5, 6, 7, 8, 8, 8},
  139180. { 12,12.5, 13,13.5, 14,14.5, 15, 99, 99, 99, 99, 99, 99, 99, 99}},
  139181. /* 0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 0 */
  139182. /*{{ 4, 4, 4, 4, 4, 4, 4, 3, 2, 2, 1, 0, 0, 0, 0},
  139183. { 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 5, 4, 3},
  139184. { 1, 2, 3, 4, 5, 5, 6, 6, 6, 6, 6, 7, 8, 8, 8},
  139185. { 12,12.5, 13,13.5, 14,14.5, 15, 99, 99, 99, 99, 99, 99, 99, 99}},*/
  139186. {{ 4, 4, 4, 4, 4, 4, 4, 3, 2, 1, 0, 0, 0, 0, 0},
  139187. { 8, 8, 8, 8, 6, 6, 5, 5, 5, 5, 5, 5, 5, 4, 3},
  139188. { 1, 2, 3, 4, 4, 5, 6, 6, 6, 6, 6, 8, 8, 8, 8},
  139189. { 12,12.5, 13,13.5, 14,14.5, 15, 99, 99, 99, 99, 99, 99, 99, 99}},
  139190. /* 0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 1 */
  139191. {{ 3, 3, 3, 3, 3, 3, 3, 3, 2, 1, 0, 0, 0, 0, 0},
  139192. { 8, 8, 8, 8, 6, 6, 5, 5, 5, 5, 5, 5, 5, 4, 3},
  139193. { 1, 2, 3, 4, 4, 5, 6, 6, 6, 6, 6, 8, 8, 8, 8},
  139194. { 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99}},
  139195. /* 0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 2 */
  139196. /* {{ 3, 3, 3, 3, 3, 3, 2, 2, 2, 1, 0, 0, 0, 0, 0},
  139197. { 8, 8, 8, 6, 5, 5, 5, 5, 5, 5, 5, 4, 3, 2, 1},
  139198. { 3, 4, 4, 4, 5, 6, 6, 6, 6, 6, 6, 8, 8, 8, 8},
  139199. { 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99}}, */
  139200. {{ 3, 3, 3, 3, 3, 3, 3, 2, 1, 1, 0, 0, 0, 0, 0},
  139201. { 8, 8, 6, 6, 5, 5, 4, 4, 4, 4, 4, 4, 3, 2, 1},
  139202. { 3, 4, 4, 5, 5, 6, 6, 6, 6, 6, 6, 8, 8, 8, 8},
  139203. { 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99}},
  139204. /* 0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 3 */
  139205. {{ 2, 2, 2, 2, 2, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0},
  139206. { 5, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 3, 2, 1},
  139207. { 4, 4, 5, 6, 6, 6, 6, 6, 8, 8, 10, 10, 10, 10, 10},
  139208. { 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99}},
  139209. /* 0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 4 */
  139210. {{ 2, 2, 2, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0},
  139211. { 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 3, 3, 2, 1, 0},
  139212. { 6, 6, 6, 8, 8, 8, 8, 8, 8, 8, 10, 10, 10, 10, 10},
  139213. { 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99}},
  139214. /* 0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 5 */
  139215. /* {{ 2, 2, 2, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0},
  139216. { 3, 3, 3, 3, 3, 2, 2, 2, 2, 2, 2, 0, 0, 0, 0},
  139217. { 6, 6, 8, 8, 8, 8, 10, 10, 10, 10, 10, 10, 10, 10, 10},
  139218. { 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99}},*/
  139219. {{ 2, 2, 2, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0},
  139220. { 3, 3, 3, 3, 3, 2, 2, 2, 2, 2, 2, 0, 0, 0, 0},
  139221. { 6, 7, 8, 8, 8, 10, 10, 12, 12, 12, 12, 12, 12, 12, 12},
  139222. { 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99}},
  139223. /* 0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 6 */
  139224. /* {{ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0},
  139225. { 3, 3, 3, 2, 2, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0},
  139226. { 8, 8, 8, 8, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10},
  139227. { 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99}}, */
  139228. {{ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0},
  139229. { 3, 3, 3, 2, 2, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0},
  139230. { 8, 8, 8, 10, 10, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12},
  139231. { 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99}},
  139232. /* 0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 7 */
  139233. /* {{ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0},
  139234. { 3, 3, 3, 2, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0},
  139235. { 8, 8, 8, 8, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10},
  139236. { 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99}},*/
  139237. {{ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0},
  139238. { 3, 3, 3, 2, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0},
  139239. { 8, 8, 10, 10, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12},
  139240. { 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99}},
  139241. /* 0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 8 */
  139242. /* {{ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0},
  139243. { 2, 2, 2, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0},
  139244. { 8, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10},
  139245. { 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99}},*/
  139246. {{ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0},
  139247. { 2, 2, 2, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0},
  139248. { 8, 10, 10, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12},
  139249. { 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99}},
  139250. /* 0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 9 */
  139251. {{ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0},
  139252. { 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0},
  139253. { 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4},
  139254. { 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99}},
  139255. /* 0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 10 */
  139256. {{ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0},
  139257. { 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0},
  139258. { 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4},
  139259. { 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99}},
  139260. };
  139261. /* tone master attenuation by base quality mode and bitrate tweak */
  139262. static att3 _psy_tone_masteratt_44[12]={
  139263. {{ 35, 21, 9}, 0, 0}, /* -1 */
  139264. {{ 30, 20, 8}, -2, 1.25}, /* 0 */
  139265. /* {{ 25, 14, 4}, 0, 0}, *//* 1 */
  139266. {{ 25, 12, 2}, 0, 0}, /* 1 */
  139267. /* {{ 20, 10, -2}, 0, 0}, *//* 2 */
  139268. {{ 20, 9, -3}, 0, 0}, /* 2 */
  139269. {{ 20, 9, -4}, 0, 0}, /* 3 */
  139270. {{ 20, 9, -4}, 0, 0}, /* 4 */
  139271. {{ 20, 6, -6}, 0, 0}, /* 5 */
  139272. {{ 20, 3, -10}, 0, 0}, /* 6 */
  139273. {{ 18, 1, -14}, 0, 0}, /* 7 */
  139274. {{ 18, 0, -16}, 0, 0}, /* 8 */
  139275. {{ 18, -2, -16}, 0, 0}, /* 9 */
  139276. {{ 12, -2, -20}, 0, 0}, /* 10 */
  139277. };
  139278. /* lowpass by mode **************/
  139279. static double _psy_lowpass_44[12]={
  139280. /* 15.1,15.8,16.5,17.9,20.5,48.,999.,999.,999.,999.,999. */
  139281. 13.9,15.1,15.8,16.5,17.2,18.9,20.1,48.,999.,999.,999.,999.
  139282. };
  139283. /* noise normalization **********/
  139284. static int _noise_start_short_44[11]={
  139285. /* 16,16,16,16,32,32,9999,9999,9999,9999 */
  139286. 32,16,16,16,32,9999,9999,9999,9999,9999,9999
  139287. };
  139288. static int _noise_start_long_44[11]={
  139289. /* 128,128,128,256,512,512,9999,9999,9999,9999 */
  139290. 256,128,128,256,512,9999,9999,9999,9999,9999,9999
  139291. };
  139292. static int _noise_part_short_44[11]={
  139293. 8,8,8,8,8,8,8,8,8,8,8
  139294. };
  139295. static int _noise_part_long_44[11]={
  139296. 32,32,32,32,32,32,32,32,32,32,32
  139297. };
  139298. static double _noise_thresh_44[11]={
  139299. /* .2,.2,.3,.4,.5,.5,9999.,9999.,9999.,9999., */
  139300. .2,.2,.2,.4,.6,9999.,9999.,9999.,9999.,9999.,9999.,
  139301. };
  139302. static double _noise_thresh_5only[2]={
  139303. .5,.5,
  139304. };
  139305. /*** End of inlined file: psych_44.h ***/
  139306. static double rate_mapping_44_stereo[12]={
  139307. 22500.,32000.,40000.,48000.,56000.,64000.,
  139308. 80000.,96000.,112000.,128000.,160000.,250001.
  139309. };
  139310. static double quality_mapping_44[12]={
  139311. -.1,.0,.1,.2,.3,.4,.5,.6,.7,.8,.9,1.0
  139312. };
  139313. static int blocksize_short_44[11]={
  139314. 512,256,256,256,256,256,256,256,256,256,256
  139315. };
  139316. static int blocksize_long_44[11]={
  139317. 4096,2048,2048,2048,2048,2048,2048,2048,2048,2048,2048
  139318. };
  139319. static double _psy_compand_short_mapping[12]={
  139320. 0.5, 1., 1., 1.3, 1.6, 2., 2., 2., 2., 2., 2., 2.
  139321. };
  139322. static double _psy_compand_long_mapping[12]={
  139323. 3.5, 4., 4., 4.3, 4.6, 5., 5., 5., 5., 5., 5., 5.
  139324. };
  139325. static double _global_mapping_44[12]={
  139326. /* 1., 1., 1.5, 2., 2., 2.5, 2.7, 3.0, 3.5, 4., 4. */
  139327. 0., 1., 1., 1.5, 2., 2., 2.5, 2.7, 3.0, 3.7, 4., 4.
  139328. };
  139329. static int _floor_short_mapping_44[11]={
  139330. 1,0,0,2,2,4,5,5,5,5,5
  139331. };
  139332. static int _floor_long_mapping_44[11]={
  139333. 8,7,7,7,7,7,7,7,7,7,7
  139334. };
  139335. ve_setup_data_template ve_setup_44_stereo={
  139336. 11,
  139337. rate_mapping_44_stereo,
  139338. quality_mapping_44,
  139339. 2,
  139340. 40000,
  139341. 50000,
  139342. blocksize_short_44,
  139343. blocksize_long_44,
  139344. _psy_tone_masteratt_44,
  139345. _psy_tone_0dB,
  139346. _psy_tone_suppress,
  139347. _vp_tonemask_adj_otherblock,
  139348. _vp_tonemask_adj_longblock,
  139349. _vp_tonemask_adj_otherblock,
  139350. _psy_noiseguards_44,
  139351. _psy_noisebias_impulse,
  139352. _psy_noisebias_padding,
  139353. _psy_noisebias_trans,
  139354. _psy_noisebias_long,
  139355. _psy_noise_suppress,
  139356. _psy_compand_44,
  139357. _psy_compand_short_mapping,
  139358. _psy_compand_long_mapping,
  139359. {_noise_start_short_44,_noise_start_long_44},
  139360. {_noise_part_short_44,_noise_part_long_44},
  139361. _noise_thresh_44,
  139362. _psy_ath_floater,
  139363. _psy_ath_abs,
  139364. _psy_lowpass_44,
  139365. _psy_global_44,
  139366. _global_mapping_44,
  139367. _psy_stereo_modes_44,
  139368. _floor_books,
  139369. _floor,
  139370. _floor_short_mapping_44,
  139371. _floor_long_mapping_44,
  139372. _mapres_template_44_stereo
  139373. };
  139374. /*** End of inlined file: setup_44.h ***/
  139375. /*** Start of inlined file: setup_44u.h ***/
  139376. /*** Start of inlined file: residue_44u.h ***/
  139377. /*** Start of inlined file: res_books_uncoupled.h ***/
  139378. static long _vq_quantlist__16u0__p1_0[] = {
  139379. 1,
  139380. 0,
  139381. 2,
  139382. };
  139383. static long _vq_lengthlist__16u0__p1_0[] = {
  139384. 1, 4, 4, 5, 7, 7, 5, 7, 8, 5, 8, 8, 8,10,10, 8,
  139385. 10,11, 5, 8, 8, 8,10,10, 8,10,10, 4, 9, 9, 9,12,
  139386. 11, 8,11,11, 8,12,11,10,12,14,10,13,13, 7,11,11,
  139387. 10,14,12,11,14,14, 4, 9, 9, 8,11,11, 9,11,12, 7,
  139388. 11,11,10,13,14,10,12,14, 8,11,12,10,14,14,10,13,
  139389. 12,
  139390. };
  139391. static float _vq_quantthresh__16u0__p1_0[] = {
  139392. -0.5, 0.5,
  139393. };
  139394. static long _vq_quantmap__16u0__p1_0[] = {
  139395. 1, 0, 2,
  139396. };
  139397. static encode_aux_threshmatch _vq_auxt__16u0__p1_0 = {
  139398. _vq_quantthresh__16u0__p1_0,
  139399. _vq_quantmap__16u0__p1_0,
  139400. 3,
  139401. 3
  139402. };
  139403. static static_codebook _16u0__p1_0 = {
  139404. 4, 81,
  139405. _vq_lengthlist__16u0__p1_0,
  139406. 1, -535822336, 1611661312, 2, 0,
  139407. _vq_quantlist__16u0__p1_0,
  139408. NULL,
  139409. &_vq_auxt__16u0__p1_0,
  139410. NULL,
  139411. 0
  139412. };
  139413. static long _vq_quantlist__16u0__p2_0[] = {
  139414. 1,
  139415. 0,
  139416. 2,
  139417. };
  139418. static long _vq_lengthlist__16u0__p2_0[] = {
  139419. 2, 4, 4, 5, 6, 6, 5, 6, 6, 5, 7, 7, 7, 8, 9, 7,
  139420. 8, 9, 5, 7, 7, 7, 9, 8, 7, 9, 7, 4, 7, 7, 7, 9,
  139421. 9, 7, 8, 8, 6, 9, 8, 7, 8,11, 9,11,10, 6, 8, 9,
  139422. 8,11, 8, 9,10,11, 4, 7, 7, 7, 8, 8, 7, 9, 9, 6,
  139423. 9, 8, 9,11,10, 8, 8,11, 6, 8, 9, 9,10,11, 8,11,
  139424. 8,
  139425. };
  139426. static float _vq_quantthresh__16u0__p2_0[] = {
  139427. -0.5, 0.5,
  139428. };
  139429. static long _vq_quantmap__16u0__p2_0[] = {
  139430. 1, 0, 2,
  139431. };
  139432. static encode_aux_threshmatch _vq_auxt__16u0__p2_0 = {
  139433. _vq_quantthresh__16u0__p2_0,
  139434. _vq_quantmap__16u0__p2_0,
  139435. 3,
  139436. 3
  139437. };
  139438. static static_codebook _16u0__p2_0 = {
  139439. 4, 81,
  139440. _vq_lengthlist__16u0__p2_0,
  139441. 1, -535822336, 1611661312, 2, 0,
  139442. _vq_quantlist__16u0__p2_0,
  139443. NULL,
  139444. &_vq_auxt__16u0__p2_0,
  139445. NULL,
  139446. 0
  139447. };
  139448. static long _vq_quantlist__16u0__p3_0[] = {
  139449. 2,
  139450. 1,
  139451. 3,
  139452. 0,
  139453. 4,
  139454. };
  139455. static long _vq_lengthlist__16u0__p3_0[] = {
  139456. 1, 5, 5, 7, 7, 6, 7, 7, 8, 8, 6, 7, 8, 8, 8, 8,
  139457. 9, 9,11,11, 8, 9, 9,11,11, 6, 9, 8,10,10, 8,10,
  139458. 10,11,11, 8,10,10,11,11,10,11,10,13,12, 9,11,10,
  139459. 13,13, 6, 8, 9,10,10, 8,10,10,11,11, 8,10,10,11,
  139460. 11, 9,10,11,13,12,10,10,11,12,12, 8,11,11,14,13,
  139461. 10,12,11,15,13, 9,12,11,15,14,12,14,13,16,14,12,
  139462. 13,13,17,14, 8,11,11,13,14, 9,11,12,14,15,10,11,
  139463. 12,13,15,11,13,13,14,16,12,13,14,14,16, 5, 9, 9,
  139464. 11,11, 9,11,11,12,12, 8,11,11,12,12,11,12,12,15,
  139465. 14,10,12,12,15,15, 8,11,11,13,12,10,12,12,13,13,
  139466. 10,12,12,14,13,12,12,13,14,15,11,13,13,17,16, 7,
  139467. 11,11,13,13,10,12,12,14,13,10,12,12,13,14,12,13,
  139468. 12,15,14,11,13,13,15,14, 9,12,12,16,15,11,13,13,
  139469. 17,16,10,13,13,16,16,13,14,15,15,16,13,15,14,19,
  139470. 17, 9,12,12,14,16,11,13,13,15,16,10,13,13,17,16,
  139471. 13,14,13,17,15,12,15,15,16,17, 5, 9, 9,11,11, 8,
  139472. 11,11,13,12, 9,11,11,12,12,10,12,12,14,15,11,12,
  139473. 12,14,14, 7,11,10,13,12,10,12,12,14,13,10,11,12,
  139474. 13,13,11,13,13,15,16,12,12,13,15,15, 7,11,11,13,
  139475. 13,10,13,13,14,14,10,12,12,13,13,11,13,13,16,15,
  139476. 12,13,13,15,14, 9,12,12,15,15,10,13,13,17,16,11,
  139477. 12,13,15,15,12,15,14,18,18,13,14,14,16,17, 9,12,
  139478. 12,15,16,10,13,13,15,16,11,13,13,15,16,13,15,15,
  139479. 17,17,13,15,14,16,15, 7,11,11,15,16,10,13,12,16,
  139480. 17,10,12,13,15,17,15,16,16,18,17,13,15,15,17,18,
  139481. 8,12,12,16,16,11,13,14,17,18,11,13,13,18,16,15,
  139482. 17,16,17,19,14,15,15,17,16, 8,12,12,16,15,11,14,
  139483. 13,18,17,11,13,14,18,17,15,16,16,18,17,13,16,16,
  139484. 18,18,11,15,14,18,17,13,14,15,18, 0,12,15,15, 0,
  139485. 17,17,16,17,17,18,14,16,18,18, 0,11,14,14,17, 0,
  139486. 12,15,14,17,19,12,15,14,18, 0,15,18,16, 0,17,14,
  139487. 18,16,18, 0, 7,11,11,16,15,10,12,12,18,16,10,13,
  139488. 13,16,15,13,15,14,17,17,14,16,16,19,18, 8,12,12,
  139489. 16,16,11,13,13,18,16,11,13,14,17,16,14,15,15,19,
  139490. 18,15,16,16, 0,19, 8,12,12,16,17,11,13,13,17,17,
  139491. 11,14,13,17,17,13,15,15,17,19,15,17,17,19, 0,11,
  139492. 14,15,19,17,12,15,16,18,18,12,14,15,19,17,14,16,
  139493. 17, 0,18,16,16,19,17, 0,11,14,14,18,19,12,15,14,
  139494. 17,17,13,16,14,17,16,14,17,16,18,18,15,18,15, 0,
  139495. 18,
  139496. };
  139497. static float _vq_quantthresh__16u0__p3_0[] = {
  139498. -1.5, -0.5, 0.5, 1.5,
  139499. };
  139500. static long _vq_quantmap__16u0__p3_0[] = {
  139501. 3, 1, 0, 2, 4,
  139502. };
  139503. static encode_aux_threshmatch _vq_auxt__16u0__p3_0 = {
  139504. _vq_quantthresh__16u0__p3_0,
  139505. _vq_quantmap__16u0__p3_0,
  139506. 5,
  139507. 5
  139508. };
  139509. static static_codebook _16u0__p3_0 = {
  139510. 4, 625,
  139511. _vq_lengthlist__16u0__p3_0,
  139512. 1, -533725184, 1611661312, 3, 0,
  139513. _vq_quantlist__16u0__p3_0,
  139514. NULL,
  139515. &_vq_auxt__16u0__p3_0,
  139516. NULL,
  139517. 0
  139518. };
  139519. static long _vq_quantlist__16u0__p4_0[] = {
  139520. 2,
  139521. 1,
  139522. 3,
  139523. 0,
  139524. 4,
  139525. };
  139526. static long _vq_lengthlist__16u0__p4_0[] = {
  139527. 3, 5, 5, 8, 8, 6, 6, 6, 9, 9, 6, 6, 6, 9, 9, 9,
  139528. 10, 9,11,11, 9, 9, 9,11,11, 6, 7, 7,10,10, 7, 7,
  139529. 8,10,10, 7, 7, 8,10,10,10,10,10,11,12, 9,10,10,
  139530. 11,12, 6, 7, 7,10,10, 7, 8, 7,10,10, 7, 8, 7,10,
  139531. 10,10,11,10,12,11,10,10,10,13,10, 9,10,10,12,12,
  139532. 10,11,10,14,12, 9,11,11,13,13,11,12,13,13,13,11,
  139533. 12,12,15,13, 9,10,10,12,13, 9,11,10,12,13,10,10,
  139534. 11,12,13,11,12,12,12,13,11,12,12,13,13, 5, 7, 7,
  139535. 10,10, 7, 8, 8,10,10, 7, 8, 8,10,10,10,11,10,12,
  139536. 13,10,10,11,12,12, 6, 8, 8,11,10, 7, 8, 9,10,12,
  139537. 8, 9, 9,11,11,11,10,11,11,12,10,11,11,13,12, 7,
  139538. 8, 8,10,11, 8, 9, 8,11,10, 8, 9, 9,11,11,10,12,
  139539. 10,13,11,10,11,11,13,13,10,11,10,14,13,10,10,11,
  139540. 13,13,10,12,11,14,13,12,11,13,12,13,13,12,13,14,
  139541. 14,10,11,11,13,13,10,11,10,12,13,10,12,12,12,14,
  139542. 12,12,12,14,12,12,13,12,17,15, 5, 7, 7,10,10, 7,
  139543. 8, 8,10,10, 7, 8, 8,11,10,10,10,11,12,12,10,11,
  139544. 11,12,13, 6, 8, 8,11,10, 8, 9, 9,11,11, 7, 8, 9,
  139545. 10,11,11,11,11,12,12,10,10,11,12,13, 6, 8, 8,10,
  139546. 11, 8, 9, 9,11,11, 7, 9, 7,11,10,10,12,12,13,13,
  139547. 11,11,10,13,11, 9,11,10,14,13,11,11,11,15,13,10,
  139548. 10,11,13,13,12,13,13,14,14,12,11,12,12,13,10,11,
  139549. 11,12,13,10,11,12,13,13,10,11,10,13,12,12,12,13,
  139550. 14, 0,12,13,11,13,11, 8,10,10,13,13,10,11,11,14,
  139551. 13,10,11,11,13,12,13,14,14,14,15,12,12,12,15,14,
  139552. 9,11,10,13,12,10,10,11,13,14,11,11,11,15,12,13,
  139553. 12,14,15,16,13,13,13,14,13, 9,11,11,12,12,10,12,
  139554. 11,13,13,10,11,11,13,14,13,13,13,15,15,13,13,14,
  139555. 17,15,11,12,12,14,14,10,11,12,13,15,12,13,13, 0,
  139556. 15,13,11,14,12,16,14,16,14, 0,15,11,12,12,14,16,
  139557. 11,13,12,16,15,12,13,13,14,15,12,14,12,15,13,15,
  139558. 14,14,16,16, 8,10,10,13,13,10,11,10,13,14,10,11,
  139559. 11,13,13,13,13,12,14,14,14,13,13,16,17, 9,10,10,
  139560. 12,14,10,12,11,14,13,10,11,12,13,14,12,12,12,15,
  139561. 15,13,13,13,14,14, 9,10,10,13,13,10,11,12,12,14,
  139562. 10,11,10,13,13,13,13,13,14,16,13,13,13,14,14,11,
  139563. 12,13,15,13,12,14,13,14,16,12,12,13,13,14,13,14,
  139564. 14,17,15,13,12,17,13,16,11,12,13,14,15,12,13,14,
  139565. 14,17,11,12,11,14,14,13,16,14,16, 0,14,15,11,15,
  139566. 11,
  139567. };
  139568. static float _vq_quantthresh__16u0__p4_0[] = {
  139569. -1.5, -0.5, 0.5, 1.5,
  139570. };
  139571. static long _vq_quantmap__16u0__p4_0[] = {
  139572. 3, 1, 0, 2, 4,
  139573. };
  139574. static encode_aux_threshmatch _vq_auxt__16u0__p4_0 = {
  139575. _vq_quantthresh__16u0__p4_0,
  139576. _vq_quantmap__16u0__p4_0,
  139577. 5,
  139578. 5
  139579. };
  139580. static static_codebook _16u0__p4_0 = {
  139581. 4, 625,
  139582. _vq_lengthlist__16u0__p4_0,
  139583. 1, -533725184, 1611661312, 3, 0,
  139584. _vq_quantlist__16u0__p4_0,
  139585. NULL,
  139586. &_vq_auxt__16u0__p4_0,
  139587. NULL,
  139588. 0
  139589. };
  139590. static long _vq_quantlist__16u0__p5_0[] = {
  139591. 4,
  139592. 3,
  139593. 5,
  139594. 2,
  139595. 6,
  139596. 1,
  139597. 7,
  139598. 0,
  139599. 8,
  139600. };
  139601. static long _vq_lengthlist__16u0__p5_0[] = {
  139602. 1, 4, 4, 7, 7, 7, 7, 9, 9, 4, 6, 6, 8, 8, 8, 8,
  139603. 9, 9, 4, 6, 6, 8, 8, 8, 8, 9, 9, 7, 8, 8, 9, 9,
  139604. 9, 9,11,10, 7, 8, 8, 9, 9, 9, 9,10,11, 7, 8, 8,
  139605. 9, 9,10,10,11,11, 7, 8, 8, 9, 9,10,10,11,11, 9,
  139606. 9, 9,10,10,11,11,12,12, 9, 9, 9,10,10,11,11,12,
  139607. 12,
  139608. };
  139609. static float _vq_quantthresh__16u0__p5_0[] = {
  139610. -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5, 3.5,
  139611. };
  139612. static long _vq_quantmap__16u0__p5_0[] = {
  139613. 7, 5, 3, 1, 0, 2, 4, 6,
  139614. 8,
  139615. };
  139616. static encode_aux_threshmatch _vq_auxt__16u0__p5_0 = {
  139617. _vq_quantthresh__16u0__p5_0,
  139618. _vq_quantmap__16u0__p5_0,
  139619. 9,
  139620. 9
  139621. };
  139622. static static_codebook _16u0__p5_0 = {
  139623. 2, 81,
  139624. _vq_lengthlist__16u0__p5_0,
  139625. 1, -531628032, 1611661312, 4, 0,
  139626. _vq_quantlist__16u0__p5_0,
  139627. NULL,
  139628. &_vq_auxt__16u0__p5_0,
  139629. NULL,
  139630. 0
  139631. };
  139632. static long _vq_quantlist__16u0__p6_0[] = {
  139633. 6,
  139634. 5,
  139635. 7,
  139636. 4,
  139637. 8,
  139638. 3,
  139639. 9,
  139640. 2,
  139641. 10,
  139642. 1,
  139643. 11,
  139644. 0,
  139645. 12,
  139646. };
  139647. static long _vq_lengthlist__16u0__p6_0[] = {
  139648. 1, 4, 4, 7, 7,10,10,12,12,13,13,18,17, 3, 6, 6,
  139649. 9, 9,11,11,13,13,14,14,18,17, 3, 6, 6, 9, 9,11,
  139650. 11,13,13,14,14,17,18, 7, 9, 9,11,11,13,13,14,14,
  139651. 15,15, 0, 0, 7, 9, 9,11,11,13,13,14,14,15,16,19,
  139652. 18,10,11,11,13,13,14,14,16,15,17,18, 0, 0,10,11,
  139653. 11,13,13,14,14,15,15,16,18, 0, 0,11,13,13,14,14,
  139654. 15,15,17,17, 0,19, 0, 0,11,13,13,14,14,14,15,16,
  139655. 18, 0,19, 0, 0,13,14,14,15,15,18,17,18,18, 0,19,
  139656. 0, 0,13,14,14,15,16,16,16,18,18,19, 0, 0, 0,16,
  139657. 17,17, 0,17,19,19, 0,19, 0, 0, 0, 0,16,19,16,17,
  139658. 18, 0,19, 0, 0, 0, 0, 0, 0,
  139659. };
  139660. static float _vq_quantthresh__16u0__p6_0[] = {
  139661. -27.5, -22.5, -17.5, -12.5, -7.5, -2.5, 2.5, 7.5,
  139662. 12.5, 17.5, 22.5, 27.5,
  139663. };
  139664. static long _vq_quantmap__16u0__p6_0[] = {
  139665. 11, 9, 7, 5, 3, 1, 0, 2,
  139666. 4, 6, 8, 10, 12,
  139667. };
  139668. static encode_aux_threshmatch _vq_auxt__16u0__p6_0 = {
  139669. _vq_quantthresh__16u0__p6_0,
  139670. _vq_quantmap__16u0__p6_0,
  139671. 13,
  139672. 13
  139673. };
  139674. static static_codebook _16u0__p6_0 = {
  139675. 2, 169,
  139676. _vq_lengthlist__16u0__p6_0,
  139677. 1, -526516224, 1616117760, 4, 0,
  139678. _vq_quantlist__16u0__p6_0,
  139679. NULL,
  139680. &_vq_auxt__16u0__p6_0,
  139681. NULL,
  139682. 0
  139683. };
  139684. static long _vq_quantlist__16u0__p6_1[] = {
  139685. 2,
  139686. 1,
  139687. 3,
  139688. 0,
  139689. 4,
  139690. };
  139691. static long _vq_lengthlist__16u0__p6_1[] = {
  139692. 1, 4, 5, 6, 6, 4, 6, 6, 6, 6, 4, 6, 6, 6, 6, 6,
  139693. 6, 6, 7, 7, 6, 6, 6, 7, 7,
  139694. };
  139695. static float _vq_quantthresh__16u0__p6_1[] = {
  139696. -1.5, -0.5, 0.5, 1.5,
  139697. };
  139698. static long _vq_quantmap__16u0__p6_1[] = {
  139699. 3, 1, 0, 2, 4,
  139700. };
  139701. static encode_aux_threshmatch _vq_auxt__16u0__p6_1 = {
  139702. _vq_quantthresh__16u0__p6_1,
  139703. _vq_quantmap__16u0__p6_1,
  139704. 5,
  139705. 5
  139706. };
  139707. static static_codebook _16u0__p6_1 = {
  139708. 2, 25,
  139709. _vq_lengthlist__16u0__p6_1,
  139710. 1, -533725184, 1611661312, 3, 0,
  139711. _vq_quantlist__16u0__p6_1,
  139712. NULL,
  139713. &_vq_auxt__16u0__p6_1,
  139714. NULL,
  139715. 0
  139716. };
  139717. static long _vq_quantlist__16u0__p7_0[] = {
  139718. 1,
  139719. 0,
  139720. 2,
  139721. };
  139722. static long _vq_lengthlist__16u0__p7_0[] = {
  139723. 1, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8,
  139724. 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8,
  139725. 8, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7,
  139726. 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7,
  139727. 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7,
  139728. 7,
  139729. };
  139730. static float _vq_quantthresh__16u0__p7_0[] = {
  139731. -157.5, 157.5,
  139732. };
  139733. static long _vq_quantmap__16u0__p7_0[] = {
  139734. 1, 0, 2,
  139735. };
  139736. static encode_aux_threshmatch _vq_auxt__16u0__p7_0 = {
  139737. _vq_quantthresh__16u0__p7_0,
  139738. _vq_quantmap__16u0__p7_0,
  139739. 3,
  139740. 3
  139741. };
  139742. static static_codebook _16u0__p7_0 = {
  139743. 4, 81,
  139744. _vq_lengthlist__16u0__p7_0,
  139745. 1, -518803456, 1628680192, 2, 0,
  139746. _vq_quantlist__16u0__p7_0,
  139747. NULL,
  139748. &_vq_auxt__16u0__p7_0,
  139749. NULL,
  139750. 0
  139751. };
  139752. static long _vq_quantlist__16u0__p7_1[] = {
  139753. 7,
  139754. 6,
  139755. 8,
  139756. 5,
  139757. 9,
  139758. 4,
  139759. 10,
  139760. 3,
  139761. 11,
  139762. 2,
  139763. 12,
  139764. 1,
  139765. 13,
  139766. 0,
  139767. 14,
  139768. };
  139769. static long _vq_lengthlist__16u0__p7_1[] = {
  139770. 1, 5, 5, 6, 5, 9,10,11,11,10,10,10,10,10,10, 5,
  139771. 8, 8, 8,10,10,10,10,10,10,10,10,10,10,10, 5, 8,
  139772. 9, 9, 9,10,10,10,10,10,10,10,10,10,10, 5,10, 8,
  139773. 10,10,10,10,10,10,10,10,10,10,10,10, 4, 8, 9,10,
  139774. 10,10,10,10,10,10,10,10,10,10,10, 9,10,10,10,10,
  139775. 10,10,10,10,10,10,10,10,10,10, 9,10,10,10,10,10,
  139776. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  139777. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  139778. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  139779. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  139780. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  139781. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  139782. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  139783. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  139784. 10,
  139785. };
  139786. static float _vq_quantthresh__16u0__p7_1[] = {
  139787. -136.5, -115.5, -94.5, -73.5, -52.5, -31.5, -10.5, 10.5,
  139788. 31.5, 52.5, 73.5, 94.5, 115.5, 136.5,
  139789. };
  139790. static long _vq_quantmap__16u0__p7_1[] = {
  139791. 13, 11, 9, 7, 5, 3, 1, 0,
  139792. 2, 4, 6, 8, 10, 12, 14,
  139793. };
  139794. static encode_aux_threshmatch _vq_auxt__16u0__p7_1 = {
  139795. _vq_quantthresh__16u0__p7_1,
  139796. _vq_quantmap__16u0__p7_1,
  139797. 15,
  139798. 15
  139799. };
  139800. static static_codebook _16u0__p7_1 = {
  139801. 2, 225,
  139802. _vq_lengthlist__16u0__p7_1,
  139803. 1, -520986624, 1620377600, 4, 0,
  139804. _vq_quantlist__16u0__p7_1,
  139805. NULL,
  139806. &_vq_auxt__16u0__p7_1,
  139807. NULL,
  139808. 0
  139809. };
  139810. static long _vq_quantlist__16u0__p7_2[] = {
  139811. 10,
  139812. 9,
  139813. 11,
  139814. 8,
  139815. 12,
  139816. 7,
  139817. 13,
  139818. 6,
  139819. 14,
  139820. 5,
  139821. 15,
  139822. 4,
  139823. 16,
  139824. 3,
  139825. 17,
  139826. 2,
  139827. 18,
  139828. 1,
  139829. 19,
  139830. 0,
  139831. 20,
  139832. };
  139833. static long _vq_lengthlist__16u0__p7_2[] = {
  139834. 1, 6, 6, 7, 8, 7, 7,10, 9,10, 9,11,10, 9,11,10,
  139835. 9, 9, 9, 9,10, 6, 8, 7, 9, 9, 8, 8,10,10, 9,11,
  139836. 11,12,12,10, 9,11, 9,12,10, 9, 6, 9, 8, 9,12, 8,
  139837. 8,11, 9,11,11,12,11,12,12,10,11,11,10,10,11, 7,
  139838. 10, 9, 9, 9, 9, 9,10, 9,10, 9,10,10,12,10,10,10,
  139839. 11,12,10,10, 7, 9, 9, 9,10, 9, 9,10,10, 9, 9, 9,
  139840. 11,11,10,10,10,10, 9, 9,12, 7, 9,10, 9,11, 9,10,
  139841. 9,10,11,11,11,10,11,12, 9,12,11,10,10,10, 7, 9,
  139842. 9, 9, 9,10,12,10, 9,11,12,10,11,12,12,11, 9,10,
  139843. 11,10,11, 7, 9,10,10,11,10, 9,10,11,11,11,10,12,
  139844. 12,12,11,11,10,11,11,12, 8, 9,10,12,11,10,10,12,
  139845. 12,12,12,12,10,11,11, 9,11,10,12,11,11, 8, 9,10,
  139846. 10,11,12,11,11,10,10,10,12,12,12, 9,10,12,12,12,
  139847. 12,12, 8,10,11,10,10,12, 9,11,12,12,11,12,12,12,
  139848. 12,10,12,10,10,10,10, 8,12,11,11,11,10,10,11,12,
  139849. 12,12,12,11,12,12,12,11,11,11,12,10, 9,10,10,12,
  139850. 10,12,10,12,12,10,10,10,11,12,12,12,11,12,12,12,
  139851. 11,10,11,12,12,12,11,12,12,11,12,12,11,12,12,12,
  139852. 12,11,12,12,10,10,10,10,11,11,12,11,12,12,12,12,
  139853. 12,12,12,11,12,11,10,11,11,12,11,11, 9,10,10,10,
  139854. 12,10,10,11, 9,11,12,11,12,11,12,12,10,11,10,12,
  139855. 9, 9, 9,12,11,10,11,10,12,10,12,10,12,12,12,11,
  139856. 11,11,11,11,10, 9,10,10,11,10,11,11,12,11,10,11,
  139857. 12,12,12,11,11, 9,12,10,12, 9,10,12,10,10,11,10,
  139858. 11,11,12,11,10,11,10,11,11,11,11,12,11,11,10, 9,
  139859. 10,10,10, 9,11,11,10, 9,12,10,11,12,11,12,12,11,
  139860. 12,11,12,11,10,11,10,12,11,12,11,12,11,12,10,11,
  139861. 10,10,12,11,10,11,11,11,10,
  139862. };
  139863. static float _vq_quantthresh__16u0__p7_2[] = {
  139864. -9.5, -8.5, -7.5, -6.5, -5.5, -4.5, -3.5, -2.5,
  139865. -1.5, -0.5, 0.5, 1.5, 2.5, 3.5, 4.5, 5.5,
  139866. 6.5, 7.5, 8.5, 9.5,
  139867. };
  139868. static long _vq_quantmap__16u0__p7_2[] = {
  139869. 19, 17, 15, 13, 11, 9, 7, 5,
  139870. 3, 1, 0, 2, 4, 6, 8, 10,
  139871. 12, 14, 16, 18, 20,
  139872. };
  139873. static encode_aux_threshmatch _vq_auxt__16u0__p7_2 = {
  139874. _vq_quantthresh__16u0__p7_2,
  139875. _vq_quantmap__16u0__p7_2,
  139876. 21,
  139877. 21
  139878. };
  139879. static static_codebook _16u0__p7_2 = {
  139880. 2, 441,
  139881. _vq_lengthlist__16u0__p7_2,
  139882. 1, -529268736, 1611661312, 5, 0,
  139883. _vq_quantlist__16u0__p7_2,
  139884. NULL,
  139885. &_vq_auxt__16u0__p7_2,
  139886. NULL,
  139887. 0
  139888. };
  139889. static long _huff_lengthlist__16u0__single[] = {
  139890. 3, 5, 8, 7,14, 8, 9,19, 5, 2, 5, 5, 9, 6, 9,19,
  139891. 8, 4, 5, 7, 8, 9,13,19, 7, 4, 6, 5, 9, 6, 9,19,
  139892. 12, 8, 7, 9,10,11,13,19, 8, 5, 8, 6, 9, 6, 7,19,
  139893. 8, 8,10, 7, 7, 4, 5,19,12,17,19,15,18,13,11,18,
  139894. };
  139895. static static_codebook _huff_book__16u0__single = {
  139896. 2, 64,
  139897. _huff_lengthlist__16u0__single,
  139898. 0, 0, 0, 0, 0,
  139899. NULL,
  139900. NULL,
  139901. NULL,
  139902. NULL,
  139903. 0
  139904. };
  139905. static long _huff_lengthlist__16u1__long[] = {
  139906. 3, 6,10, 8,12, 8,14, 8,14,19, 5, 3, 5, 5, 7, 6,
  139907. 11, 7,16,19, 7, 5, 6, 7, 7, 9,11,12,19,19, 6, 4,
  139908. 7, 5, 7, 6,10, 7,18,18, 8, 6, 7, 7, 7, 7, 8, 9,
  139909. 18,18, 7, 5, 8, 5, 7, 5, 8, 6,18,18,12, 9,10, 9,
  139910. 9, 9, 8, 9,18,18, 8, 7,10, 6, 8, 5, 6, 4,11,18,
  139911. 11,15,16,12,11, 8, 8, 6, 9,18,14,18,18,18,16,16,
  139912. 16,13,16,18,
  139913. };
  139914. static static_codebook _huff_book__16u1__long = {
  139915. 2, 100,
  139916. _huff_lengthlist__16u1__long,
  139917. 0, 0, 0, 0, 0,
  139918. NULL,
  139919. NULL,
  139920. NULL,
  139921. NULL,
  139922. 0
  139923. };
  139924. static long _vq_quantlist__16u1__p1_0[] = {
  139925. 1,
  139926. 0,
  139927. 2,
  139928. };
  139929. static long _vq_lengthlist__16u1__p1_0[] = {
  139930. 1, 4, 4, 5, 7, 7, 5, 7, 7, 5, 8, 7, 7,10,10, 7,
  139931. 9,10, 5, 7, 8, 7,10, 9, 7,10,10, 5, 8, 8, 8,10,
  139932. 10, 8,10,10, 7,10,10,10,11,12,10,12,13, 7,10,10,
  139933. 9,13,11,10,12,13, 5, 8, 8, 8,10,10, 8,10,10, 7,
  139934. 10,10,10,12,12, 9,11,12, 7,10,11,10,12,12,10,13,
  139935. 11,
  139936. };
  139937. static float _vq_quantthresh__16u1__p1_0[] = {
  139938. -0.5, 0.5,
  139939. };
  139940. static long _vq_quantmap__16u1__p1_0[] = {
  139941. 1, 0, 2,
  139942. };
  139943. static encode_aux_threshmatch _vq_auxt__16u1__p1_0 = {
  139944. _vq_quantthresh__16u1__p1_0,
  139945. _vq_quantmap__16u1__p1_0,
  139946. 3,
  139947. 3
  139948. };
  139949. static static_codebook _16u1__p1_0 = {
  139950. 4, 81,
  139951. _vq_lengthlist__16u1__p1_0,
  139952. 1, -535822336, 1611661312, 2, 0,
  139953. _vq_quantlist__16u1__p1_0,
  139954. NULL,
  139955. &_vq_auxt__16u1__p1_0,
  139956. NULL,
  139957. 0
  139958. };
  139959. static long _vq_quantlist__16u1__p2_0[] = {
  139960. 1,
  139961. 0,
  139962. 2,
  139963. };
  139964. static long _vq_lengthlist__16u1__p2_0[] = {
  139965. 3, 4, 4, 5, 6, 6, 5, 6, 6, 5, 6, 6, 6, 7, 8, 6,
  139966. 7, 8, 5, 6, 6, 6, 8, 7, 6, 8, 7, 5, 6, 6, 6, 8,
  139967. 8, 6, 8, 8, 6, 8, 8, 7, 7,10, 8, 9, 9, 6, 8, 8,
  139968. 7, 9, 8, 8, 9,10, 5, 6, 6, 6, 8, 8, 7, 8, 8, 6,
  139969. 8, 8, 8,10, 9, 7, 8, 9, 6, 8, 8, 8, 9, 9, 7,10,
  139970. 8,
  139971. };
  139972. static float _vq_quantthresh__16u1__p2_0[] = {
  139973. -0.5, 0.5,
  139974. };
  139975. static long _vq_quantmap__16u1__p2_0[] = {
  139976. 1, 0, 2,
  139977. };
  139978. static encode_aux_threshmatch _vq_auxt__16u1__p2_0 = {
  139979. _vq_quantthresh__16u1__p2_0,
  139980. _vq_quantmap__16u1__p2_0,
  139981. 3,
  139982. 3
  139983. };
  139984. static static_codebook _16u1__p2_0 = {
  139985. 4, 81,
  139986. _vq_lengthlist__16u1__p2_0,
  139987. 1, -535822336, 1611661312, 2, 0,
  139988. _vq_quantlist__16u1__p2_0,
  139989. NULL,
  139990. &_vq_auxt__16u1__p2_0,
  139991. NULL,
  139992. 0
  139993. };
  139994. static long _vq_quantlist__16u1__p3_0[] = {
  139995. 2,
  139996. 1,
  139997. 3,
  139998. 0,
  139999. 4,
  140000. };
  140001. static long _vq_lengthlist__16u1__p3_0[] = {
  140002. 1, 5, 5, 8, 8, 6, 7, 7, 9, 9, 5, 7, 7, 9, 9, 9,
  140003. 10, 9,11,11, 9, 9,10,11,11, 6, 8, 8,10,10, 8, 9,
  140004. 10,11,11, 8, 9,10,11,11,10,11,11,12,13,10,11,11,
  140005. 13,13, 6, 8, 8,10,10, 8,10, 9,11,11, 8,10, 9,11,
  140006. 11,10,11,11,13,13,10,11,11,13,12, 9,11,11,14,13,
  140007. 10,12,12,15,14,10,12,11,14,13,12,13,13,15,15,12,
  140008. 13,13,16,14, 9,11,11,13,14,10,11,12,14,14,10,12,
  140009. 12,14,15,12,13,13,14,15,12,13,14,15,16, 5, 8, 8,
  140010. 11,11, 8,10,10,12,12, 8,10,10,12,12,11,12,12,14,
  140011. 14,11,12,12,14,14, 8,10,10,12,12, 9,11,12,12,13,
  140012. 10,12,12,13,13,12,12,13,14,15,11,13,13,15,15, 7,
  140013. 10,10,12,12, 9,12,11,13,12,10,11,12,13,13,12,13,
  140014. 12,15,14,11,12,13,15,15,10,12,12,15,14,11,13,13,
  140015. 16,15,11,13,13,16,15,14,13,14,15,16,13,15,15,17,
  140016. 17,10,12,12,14,15,11,12,12,15,15,11,13,13,15,16,
  140017. 13,15,13,16,15,13,15,15,16,17, 5, 8, 8,11,11, 8,
  140018. 10,10,12,12, 8,10,10,12,12,11,12,12,14,14,11,12,
  140019. 12,14,14, 7,10,10,12,12,10,12,12,14,13, 9,11,12,
  140020. 12,13,12,13,13,15,15,12,12,13,13,15, 7,10,10,12,
  140021. 13,10,11,12,13,13,10,12,11,13,13,11,13,13,15,15,
  140022. 12,13,12,15,14, 9,12,12,15,14,11,13,13,15,15,11,
  140023. 12,13,15,15,13,14,14,17,19,13,13,14,16,16,10,12,
  140024. 12,14,15,11,13,13,15,16,11,13,12,16,15,13,15,15,
  140025. 17,18,14,15,13,16,15, 8,11,11,15,14,10,12,12,16,
  140026. 15,10,12,12,16,16,14,15,15,18,17,13,14,15,16,18,
  140027. 9,12,12,15,15,11,12,14,16,17,11,13,13,16,15,15,
  140028. 15,15,17,18,14,15,16,17,17, 9,12,12,15,15,11,14,
  140029. 13,16,16,11,13,13,16,16,15,16,15,17,18,14,16,15,
  140030. 17,16,12,14,14,17,16,12,14,15,18,17,13,15,15,17,
  140031. 17,15,15,18,16,20,15,16,17,18,18,11,14,14,16,17,
  140032. 13,15,14,18,17,13,15,15,17,17,15,17,15,18,17,15,
  140033. 17,16,19,18, 8,11,11,14,15,10,12,12,15,15,10,12,
  140034. 12,16,16,13,14,14,17,16,14,15,15,17,17, 9,12,12,
  140035. 15,16,11,13,13,16,16,11,12,13,16,16,14,16,15,20,
  140036. 17,14,16,16,17,17, 9,12,12,15,16,11,13,13,16,17,
  140037. 11,13,13,17,16,14,15,15,17,18,15,15,15,18,18,11,
  140038. 14,14,17,16,13,15,15,17,17,13,14,14,18,17,15,16,
  140039. 16,18,19,15,15,17,17,19,11,14,14,16,17,13,15,14,
  140040. 17,19,13,15,14,18,17,15,17,16,18,18,15,17,15,18,
  140041. 16,
  140042. };
  140043. static float _vq_quantthresh__16u1__p3_0[] = {
  140044. -1.5, -0.5, 0.5, 1.5,
  140045. };
  140046. static long _vq_quantmap__16u1__p3_0[] = {
  140047. 3, 1, 0, 2, 4,
  140048. };
  140049. static encode_aux_threshmatch _vq_auxt__16u1__p3_0 = {
  140050. _vq_quantthresh__16u1__p3_0,
  140051. _vq_quantmap__16u1__p3_0,
  140052. 5,
  140053. 5
  140054. };
  140055. static static_codebook _16u1__p3_0 = {
  140056. 4, 625,
  140057. _vq_lengthlist__16u1__p3_0,
  140058. 1, -533725184, 1611661312, 3, 0,
  140059. _vq_quantlist__16u1__p3_0,
  140060. NULL,
  140061. &_vq_auxt__16u1__p3_0,
  140062. NULL,
  140063. 0
  140064. };
  140065. static long _vq_quantlist__16u1__p4_0[] = {
  140066. 2,
  140067. 1,
  140068. 3,
  140069. 0,
  140070. 4,
  140071. };
  140072. static long _vq_lengthlist__16u1__p4_0[] = {
  140073. 4, 5, 5, 8, 8, 6, 6, 7, 9, 9, 6, 6, 6, 9, 9, 9,
  140074. 10, 9,11,11, 9, 9,10,11,11, 6, 7, 7,10, 9, 7, 7,
  140075. 8, 9,10, 7, 7, 8,10,10,10,10,10,10,12, 9, 9,10,
  140076. 11,12, 6, 7, 7, 9, 9, 7, 8, 7,10,10, 7, 8, 7,10,
  140077. 10, 9,10, 9,12,11,10,10, 9,12,10, 9,10,10,12,11,
  140078. 10,10,10,12,12, 9,10,10,12,12,12,11,12,13,13,11,
  140079. 11,12,12,13, 9,10,10,11,12, 9,10,10,12,12,10,10,
  140080. 10,12,12,11,12,11,14,13,11,12,12,14,13, 5, 7, 7,
  140081. 10,10, 7, 8, 8,10,10, 7, 8, 7,10,10,10,10,10,12,
  140082. 12,10,10,10,12,12, 6, 8, 7,10,10, 7, 7, 9,10,11,
  140083. 8, 9, 9,11,10,10,10,11,11,13,10,10,11,12,13, 6,
  140084. 8, 8,10,10, 7, 9, 8,11,10, 8, 9, 9,10,11,10,11,
  140085. 10,13,11,10,11,10,12,12,10,11,10,12,11,10,10,10,
  140086. 12,13,10,11,11,13,12,11,11,13,11,14,12,12,13,14,
  140087. 14, 9,10,10,12,13,10,11,10,13,12,10,11,11,12,13,
  140088. 11,12,11,14,12,12,13,13,15,14, 5, 7, 7,10,10, 7,
  140089. 7, 8,10,10, 7, 8, 8,10,10,10,10,10,11,12,10,10,
  140090. 10,12,12, 7, 8, 8,10,10, 8, 9, 8,11,10, 7, 8, 9,
  140091. 10,11,10,11,11,12,12,10,10,11,11,13, 7, 7, 8,10,
  140092. 10, 8, 8, 9,10,11, 7, 9, 7,11,10,10,11,11,13,12,
  140093. 11,11,10,13,11, 9,10,10,12,12,10,11,11,13,12,10,
  140094. 10,11,12,12,12,13,13,14,14,11,11,12,12,14,10,10,
  140095. 11,12,12,10,11,11,12,13,10,10,10,13,12,12,13,13,
  140096. 15,14,12,13,10,14,11, 8,10,10,12,12,10,11,10,13,
  140097. 13, 9,10,10,12,12,12,13,13,15,14,11,12,12,13,13,
  140098. 9,10,10,13,12,10,10,11,13,13,10,11,10,13,12,12,
  140099. 12,13,14,15,12,13,12,15,13, 9,10,10,12,13,10,11,
  140100. 10,13,12,10,10,11,12,13,12,14,12,15,13,12,12,13,
  140101. 14,15,11,12,11,14,13,11,11,12,14,15,12,13,12,15,
  140102. 14,13,11,15,11,16,13,14,14,16,15,11,12,12,14,14,
  140103. 11,12,11,14,13,12,12,13,14,15,13,14,12,16,12,14,
  140104. 14,14,15,15, 8,10,10,12,12, 9,10,10,12,12,10,10,
  140105. 11,13,13,11,12,12,13,13,12,13,13,14,15, 9,10,10,
  140106. 13,12,10,11,11,13,12,10,10,11,13,13,12,13,12,15,
  140107. 14,12,12,13,13,16, 9, 9,10,12,13,10,10,11,12,13,
  140108. 10,11,10,13,13,12,12,13,13,15,13,13,12,15,13,11,
  140109. 12,12,14,14,12,13,12,15,14,11,11,12,13,14,14,14,
  140110. 14,16,15,13,12,15,12,16,11,11,12,13,14,12,13,13,
  140111. 14,15,10,12,11,14,13,14,15,14,16,16,13,14,11,15,
  140112. 11,
  140113. };
  140114. static float _vq_quantthresh__16u1__p4_0[] = {
  140115. -1.5, -0.5, 0.5, 1.5,
  140116. };
  140117. static long _vq_quantmap__16u1__p4_0[] = {
  140118. 3, 1, 0, 2, 4,
  140119. };
  140120. static encode_aux_threshmatch _vq_auxt__16u1__p4_0 = {
  140121. _vq_quantthresh__16u1__p4_0,
  140122. _vq_quantmap__16u1__p4_0,
  140123. 5,
  140124. 5
  140125. };
  140126. static static_codebook _16u1__p4_0 = {
  140127. 4, 625,
  140128. _vq_lengthlist__16u1__p4_0,
  140129. 1, -533725184, 1611661312, 3, 0,
  140130. _vq_quantlist__16u1__p4_0,
  140131. NULL,
  140132. &_vq_auxt__16u1__p4_0,
  140133. NULL,
  140134. 0
  140135. };
  140136. static long _vq_quantlist__16u1__p5_0[] = {
  140137. 4,
  140138. 3,
  140139. 5,
  140140. 2,
  140141. 6,
  140142. 1,
  140143. 7,
  140144. 0,
  140145. 8,
  140146. };
  140147. static long _vq_lengthlist__16u1__p5_0[] = {
  140148. 1, 4, 4, 7, 7, 7, 7, 9, 9, 4, 6, 6, 8, 8, 8, 8,
  140149. 10,10, 4, 5, 6, 8, 8, 8, 8,10,10, 7, 8, 8, 9, 9,
  140150. 9, 9,11,11, 7, 8, 8, 9, 9, 9, 9,11,11, 7, 8, 8,
  140151. 10, 9,11,11,12,11, 7, 8, 8, 9, 9,11,11,12,12, 9,
  140152. 10,10,11,11,12,12,13,12, 9,10,10,11,11,12,12,12,
  140153. 13,
  140154. };
  140155. static float _vq_quantthresh__16u1__p5_0[] = {
  140156. -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5, 3.5,
  140157. };
  140158. static long _vq_quantmap__16u1__p5_0[] = {
  140159. 7, 5, 3, 1, 0, 2, 4, 6,
  140160. 8,
  140161. };
  140162. static encode_aux_threshmatch _vq_auxt__16u1__p5_0 = {
  140163. _vq_quantthresh__16u1__p5_0,
  140164. _vq_quantmap__16u1__p5_0,
  140165. 9,
  140166. 9
  140167. };
  140168. static static_codebook _16u1__p5_0 = {
  140169. 2, 81,
  140170. _vq_lengthlist__16u1__p5_0,
  140171. 1, -531628032, 1611661312, 4, 0,
  140172. _vq_quantlist__16u1__p5_0,
  140173. NULL,
  140174. &_vq_auxt__16u1__p5_0,
  140175. NULL,
  140176. 0
  140177. };
  140178. static long _vq_quantlist__16u1__p6_0[] = {
  140179. 4,
  140180. 3,
  140181. 5,
  140182. 2,
  140183. 6,
  140184. 1,
  140185. 7,
  140186. 0,
  140187. 8,
  140188. };
  140189. static long _vq_lengthlist__16u1__p6_0[] = {
  140190. 3, 4, 4, 6, 6, 7, 7, 9, 9, 4, 4, 4, 6, 6, 8, 8,
  140191. 9, 9, 4, 4, 4, 6, 6, 7, 7, 9, 9, 6, 6, 6, 7, 7,
  140192. 8, 8,10, 9, 6, 6, 6, 7, 7, 8, 8, 9,10, 7, 8, 7,
  140193. 8, 8, 9, 9,10,10, 7, 8, 8, 8, 8, 9, 9,10,10, 9,
  140194. 9, 9,10,10,10,10,11,11, 9, 9, 9,10,10,10,10,11,
  140195. 11,
  140196. };
  140197. static float _vq_quantthresh__16u1__p6_0[] = {
  140198. -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5, 3.5,
  140199. };
  140200. static long _vq_quantmap__16u1__p6_0[] = {
  140201. 7, 5, 3, 1, 0, 2, 4, 6,
  140202. 8,
  140203. };
  140204. static encode_aux_threshmatch _vq_auxt__16u1__p6_0 = {
  140205. _vq_quantthresh__16u1__p6_0,
  140206. _vq_quantmap__16u1__p6_0,
  140207. 9,
  140208. 9
  140209. };
  140210. static static_codebook _16u1__p6_0 = {
  140211. 2, 81,
  140212. _vq_lengthlist__16u1__p6_0,
  140213. 1, -531628032, 1611661312, 4, 0,
  140214. _vq_quantlist__16u1__p6_0,
  140215. NULL,
  140216. &_vq_auxt__16u1__p6_0,
  140217. NULL,
  140218. 0
  140219. };
  140220. static long _vq_quantlist__16u1__p7_0[] = {
  140221. 1,
  140222. 0,
  140223. 2,
  140224. };
  140225. static long _vq_lengthlist__16u1__p7_0[] = {
  140226. 1, 4, 4, 4, 8, 8, 4, 8, 8, 5,11, 9, 8,12,11, 8,
  140227. 12,11, 5,10,11, 8,11,12, 8,11,12, 4,11,11,11,14,
  140228. 13,10,13,13, 8,14,13,12,14,16,12,16,15, 8,14,14,
  140229. 13,16,14,12,15,16, 4,11,11,10,14,13,11,14,14, 8,
  140230. 15,14,12,15,15,12,14,16, 8,14,14,11,16,15,12,15,
  140231. 13,
  140232. };
  140233. static float _vq_quantthresh__16u1__p7_0[] = {
  140234. -5.5, 5.5,
  140235. };
  140236. static long _vq_quantmap__16u1__p7_0[] = {
  140237. 1, 0, 2,
  140238. };
  140239. static encode_aux_threshmatch _vq_auxt__16u1__p7_0 = {
  140240. _vq_quantthresh__16u1__p7_0,
  140241. _vq_quantmap__16u1__p7_0,
  140242. 3,
  140243. 3
  140244. };
  140245. static static_codebook _16u1__p7_0 = {
  140246. 4, 81,
  140247. _vq_lengthlist__16u1__p7_0,
  140248. 1, -529137664, 1618345984, 2, 0,
  140249. _vq_quantlist__16u1__p7_0,
  140250. NULL,
  140251. &_vq_auxt__16u1__p7_0,
  140252. NULL,
  140253. 0
  140254. };
  140255. static long _vq_quantlist__16u1__p7_1[] = {
  140256. 5,
  140257. 4,
  140258. 6,
  140259. 3,
  140260. 7,
  140261. 2,
  140262. 8,
  140263. 1,
  140264. 9,
  140265. 0,
  140266. 10,
  140267. };
  140268. static long _vq_lengthlist__16u1__p7_1[] = {
  140269. 2, 4, 4, 6, 6, 7, 7, 8, 8, 8, 8, 4, 6, 5, 7, 7,
  140270. 8, 8, 8, 8, 8, 8, 4, 5, 6, 7, 7, 8, 8, 8, 8, 8,
  140271. 8, 6, 7, 7, 8, 8, 8, 8, 9, 9, 9, 9, 6, 7, 7, 8,
  140272. 8, 8, 8, 9, 9, 9, 9, 7, 8, 8, 8, 8, 9, 9, 9,10,
  140273. 9,10, 7, 8, 8, 8, 8, 9, 9, 9, 9,10, 9, 8, 8, 8,
  140274. 9, 9,10,10,10,10,10,10, 8, 8, 8, 9, 9, 9, 9,10,
  140275. 10,10,10, 8, 8, 8, 9, 9, 9,10,10,10,10,10, 8, 8,
  140276. 8, 9, 9,10,10,10,10,10,10,
  140277. };
  140278. static float _vq_quantthresh__16u1__p7_1[] = {
  140279. -4.5, -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5,
  140280. 3.5, 4.5,
  140281. };
  140282. static long _vq_quantmap__16u1__p7_1[] = {
  140283. 9, 7, 5, 3, 1, 0, 2, 4,
  140284. 6, 8, 10,
  140285. };
  140286. static encode_aux_threshmatch _vq_auxt__16u1__p7_1 = {
  140287. _vq_quantthresh__16u1__p7_1,
  140288. _vq_quantmap__16u1__p7_1,
  140289. 11,
  140290. 11
  140291. };
  140292. static static_codebook _16u1__p7_1 = {
  140293. 2, 121,
  140294. _vq_lengthlist__16u1__p7_1,
  140295. 1, -531365888, 1611661312, 4, 0,
  140296. _vq_quantlist__16u1__p7_1,
  140297. NULL,
  140298. &_vq_auxt__16u1__p7_1,
  140299. NULL,
  140300. 0
  140301. };
  140302. static long _vq_quantlist__16u1__p8_0[] = {
  140303. 5,
  140304. 4,
  140305. 6,
  140306. 3,
  140307. 7,
  140308. 2,
  140309. 8,
  140310. 1,
  140311. 9,
  140312. 0,
  140313. 10,
  140314. };
  140315. static long _vq_lengthlist__16u1__p8_0[] = {
  140316. 1, 4, 4, 5, 5, 8, 8,10,10,12,12, 4, 7, 7, 8, 8,
  140317. 9, 9,12,11,14,13, 4, 7, 7, 7, 8, 9,10,11,11,13,
  140318. 12, 5, 8, 8, 9, 9,11,11,12,13,15,14, 5, 7, 8, 9,
  140319. 9,11,11,13,13,17,15, 8, 9,10,11,11,12,13,17,14,
  140320. 17,16, 8,10, 9,11,11,12,12,13,15,15,17,10,11,11,
  140321. 12,13,14,15,15,16,16,17, 9,11,11,12,12,14,15,17,
  140322. 15,15,16,11,14,12,14,15,16,15,16,16,16,15,11,13,
  140323. 13,14,14,15,15,16,16,15,16,
  140324. };
  140325. static float _vq_quantthresh__16u1__p8_0[] = {
  140326. -49.5, -38.5, -27.5, -16.5, -5.5, 5.5, 16.5, 27.5,
  140327. 38.5, 49.5,
  140328. };
  140329. static long _vq_quantmap__16u1__p8_0[] = {
  140330. 9, 7, 5, 3, 1, 0, 2, 4,
  140331. 6, 8, 10,
  140332. };
  140333. static encode_aux_threshmatch _vq_auxt__16u1__p8_0 = {
  140334. _vq_quantthresh__16u1__p8_0,
  140335. _vq_quantmap__16u1__p8_0,
  140336. 11,
  140337. 11
  140338. };
  140339. static static_codebook _16u1__p8_0 = {
  140340. 2, 121,
  140341. _vq_lengthlist__16u1__p8_0,
  140342. 1, -524582912, 1618345984, 4, 0,
  140343. _vq_quantlist__16u1__p8_0,
  140344. NULL,
  140345. &_vq_auxt__16u1__p8_0,
  140346. NULL,
  140347. 0
  140348. };
  140349. static long _vq_quantlist__16u1__p8_1[] = {
  140350. 5,
  140351. 4,
  140352. 6,
  140353. 3,
  140354. 7,
  140355. 2,
  140356. 8,
  140357. 1,
  140358. 9,
  140359. 0,
  140360. 10,
  140361. };
  140362. static long _vq_lengthlist__16u1__p8_1[] = {
  140363. 2, 5, 5, 6, 6, 7, 7, 8, 8, 8, 8, 4, 6, 6, 7, 7,
  140364. 8, 7, 8, 8, 8, 8, 4, 6, 6, 7, 7, 7, 7, 8, 8, 8,
  140365. 8, 6, 7, 7, 7, 7, 8, 8, 8, 8, 8, 9, 6, 7, 7, 7,
  140366. 7, 8, 8, 8, 8, 9, 9, 7, 7, 7, 8, 8, 8, 8, 9, 9,
  140367. 9, 9, 7, 7, 7, 8, 8, 8, 8, 9, 9, 9, 9, 8, 8, 8,
  140368. 8, 8, 9, 9, 9, 9, 9, 9, 8, 8, 8, 8, 8, 9, 9, 9,
  140369. 9, 9, 9, 8, 8, 8, 9, 8, 9, 9, 9, 9, 9, 9, 8, 8,
  140370. 8, 9, 9, 9, 9, 9, 9, 9, 9,
  140371. };
  140372. static float _vq_quantthresh__16u1__p8_1[] = {
  140373. -4.5, -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5,
  140374. 3.5, 4.5,
  140375. };
  140376. static long _vq_quantmap__16u1__p8_1[] = {
  140377. 9, 7, 5, 3, 1, 0, 2, 4,
  140378. 6, 8, 10,
  140379. };
  140380. static encode_aux_threshmatch _vq_auxt__16u1__p8_1 = {
  140381. _vq_quantthresh__16u1__p8_1,
  140382. _vq_quantmap__16u1__p8_1,
  140383. 11,
  140384. 11
  140385. };
  140386. static static_codebook _16u1__p8_1 = {
  140387. 2, 121,
  140388. _vq_lengthlist__16u1__p8_1,
  140389. 1, -531365888, 1611661312, 4, 0,
  140390. _vq_quantlist__16u1__p8_1,
  140391. NULL,
  140392. &_vq_auxt__16u1__p8_1,
  140393. NULL,
  140394. 0
  140395. };
  140396. static long _vq_quantlist__16u1__p9_0[] = {
  140397. 7,
  140398. 6,
  140399. 8,
  140400. 5,
  140401. 9,
  140402. 4,
  140403. 10,
  140404. 3,
  140405. 11,
  140406. 2,
  140407. 12,
  140408. 1,
  140409. 13,
  140410. 0,
  140411. 14,
  140412. };
  140413. static long _vq_lengthlist__16u1__p9_0[] = {
  140414. 1, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,
  140415. 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,
  140416. 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,
  140417. 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,
  140418. 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,
  140419. 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,
  140420. 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,
  140421. 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,
  140422. 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,
  140423. 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,
  140424. 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,
  140425. 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,
  140426. 9, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8,
  140427. 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8,
  140428. 8,
  140429. };
  140430. static float _vq_quantthresh__16u1__p9_0[] = {
  140431. -1657.5, -1402.5, -1147.5, -892.5, -637.5, -382.5, -127.5, 127.5,
  140432. 382.5, 637.5, 892.5, 1147.5, 1402.5, 1657.5,
  140433. };
  140434. static long _vq_quantmap__16u1__p9_0[] = {
  140435. 13, 11, 9, 7, 5, 3, 1, 0,
  140436. 2, 4, 6, 8, 10, 12, 14,
  140437. };
  140438. static encode_aux_threshmatch _vq_auxt__16u1__p9_0 = {
  140439. _vq_quantthresh__16u1__p9_0,
  140440. _vq_quantmap__16u1__p9_0,
  140441. 15,
  140442. 15
  140443. };
  140444. static static_codebook _16u1__p9_0 = {
  140445. 2, 225,
  140446. _vq_lengthlist__16u1__p9_0,
  140447. 1, -514071552, 1627381760, 4, 0,
  140448. _vq_quantlist__16u1__p9_0,
  140449. NULL,
  140450. &_vq_auxt__16u1__p9_0,
  140451. NULL,
  140452. 0
  140453. };
  140454. static long _vq_quantlist__16u1__p9_1[] = {
  140455. 7,
  140456. 6,
  140457. 8,
  140458. 5,
  140459. 9,
  140460. 4,
  140461. 10,
  140462. 3,
  140463. 11,
  140464. 2,
  140465. 12,
  140466. 1,
  140467. 13,
  140468. 0,
  140469. 14,
  140470. };
  140471. static long _vq_lengthlist__16u1__p9_1[] = {
  140472. 1, 6, 5, 9, 9,10,10, 6, 7, 9, 9,10,10,10,10, 5,
  140473. 10, 8,10, 8,10,10, 8, 8,10, 9,10,10,10,10, 5, 8,
  140474. 9,10,10,10,10, 8,10,10,10,10,10,10,10, 9,10,10,
  140475. 10,10,10,10, 9, 9,10,10,10,10,10,10, 9, 9, 8, 9,
  140476. 10,10,10, 9,10,10,10,10,10,10,10,10,10,10,10,10,
  140477. 10,10,10,10,10,10,10,10,10,10,10, 8,10,10,10,10,
  140478. 10,10,10,10,10,10,10,10,10, 6, 8, 8,10,10,10, 8,
  140479. 10,10,10,10,10,10,10,10, 5, 8, 8,10,10,10, 9, 9,
  140480. 10,10,10,10,10,10,10,10, 9,10,10,10,10,10,10,10,
  140481. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  140482. 10,10,10,10,10,10,10,10, 9, 9, 9, 9, 9, 9, 9, 9,
  140483. 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,
  140484. 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,
  140485. 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,
  140486. 9,
  140487. };
  140488. static float _vq_quantthresh__16u1__p9_1[] = {
  140489. -110.5, -93.5, -76.5, -59.5, -42.5, -25.5, -8.5, 8.5,
  140490. 25.5, 42.5, 59.5, 76.5, 93.5, 110.5,
  140491. };
  140492. static long _vq_quantmap__16u1__p9_1[] = {
  140493. 13, 11, 9, 7, 5, 3, 1, 0,
  140494. 2, 4, 6, 8, 10, 12, 14,
  140495. };
  140496. static encode_aux_threshmatch _vq_auxt__16u1__p9_1 = {
  140497. _vq_quantthresh__16u1__p9_1,
  140498. _vq_quantmap__16u1__p9_1,
  140499. 15,
  140500. 15
  140501. };
  140502. static static_codebook _16u1__p9_1 = {
  140503. 2, 225,
  140504. _vq_lengthlist__16u1__p9_1,
  140505. 1, -522338304, 1620115456, 4, 0,
  140506. _vq_quantlist__16u1__p9_1,
  140507. NULL,
  140508. &_vq_auxt__16u1__p9_1,
  140509. NULL,
  140510. 0
  140511. };
  140512. static long _vq_quantlist__16u1__p9_2[] = {
  140513. 8,
  140514. 7,
  140515. 9,
  140516. 6,
  140517. 10,
  140518. 5,
  140519. 11,
  140520. 4,
  140521. 12,
  140522. 3,
  140523. 13,
  140524. 2,
  140525. 14,
  140526. 1,
  140527. 15,
  140528. 0,
  140529. 16,
  140530. };
  140531. static long _vq_lengthlist__16u1__p9_2[] = {
  140532. 1, 6, 6, 7, 8, 8,11,10, 9, 9,11, 9,10, 9,11,11,
  140533. 9, 6, 7, 6,11, 8,11, 9,10,10,11, 9,11,10,10,10,
  140534. 11, 9, 5, 7, 7, 8, 8,10,11, 8, 8,11, 9, 9,10,11,
  140535. 9,10,11, 8, 9, 6, 8, 8, 9, 9,10,10,11,11,11, 9,
  140536. 11,10, 9,11, 8, 8, 8, 9, 8, 9,10,11, 9, 9,11,11,
  140537. 10, 9, 9,11,10, 8,11, 8, 9, 8,11, 9,10, 9,10,11,
  140538. 11,10,10, 9,10,10, 8, 8, 9,10,10,10, 9,11, 9,10,
  140539. 11,11,11,11,10, 9,11, 9, 9,11,11,10, 8,11,11,11,
  140540. 9,10,10,11,10,11,11, 9,11,10, 9,11,10,10,10,10,
  140541. 9,11,10,11,10, 9, 9,10,11, 9, 8,10,11,11,10,10,
  140542. 11, 9,11,10,11,11,10,11, 9, 9, 8,10, 8, 9,11, 9,
  140543. 8,10,10, 9,11,10,11,10,11, 9,11, 8,10,11,11,11,
  140544. 11,10,10,11,11,11,11,10,11,11,10, 9, 8,10,10, 9,
  140545. 11,10,11,11,11, 9, 9, 9,11,11,11,10,10, 9, 9,10,
  140546. 9,11,11,11,11, 8,10,11,10,11,11,10,11,11, 9, 9,
  140547. 9,10, 9,11, 9,11,11,11,11,11,10,11,11,10,11,10,
  140548. 11,11, 9,11,10,11,10, 9,10, 9,10,10,11,11,11,11,
  140549. 9,10, 9,10,11,11,10,11,11,11,11,11,11,10,11,11,
  140550. 10,
  140551. };
  140552. static float _vq_quantthresh__16u1__p9_2[] = {
  140553. -7.5, -6.5, -5.5, -4.5, -3.5, -2.5, -1.5, -0.5,
  140554. 0.5, 1.5, 2.5, 3.5, 4.5, 5.5, 6.5, 7.5,
  140555. };
  140556. static long _vq_quantmap__16u1__p9_2[] = {
  140557. 15, 13, 11, 9, 7, 5, 3, 1,
  140558. 0, 2, 4, 6, 8, 10, 12, 14,
  140559. 16,
  140560. };
  140561. static encode_aux_threshmatch _vq_auxt__16u1__p9_2 = {
  140562. _vq_quantthresh__16u1__p9_2,
  140563. _vq_quantmap__16u1__p9_2,
  140564. 17,
  140565. 17
  140566. };
  140567. static static_codebook _16u1__p9_2 = {
  140568. 2, 289,
  140569. _vq_lengthlist__16u1__p9_2,
  140570. 1, -529530880, 1611661312, 5, 0,
  140571. _vq_quantlist__16u1__p9_2,
  140572. NULL,
  140573. &_vq_auxt__16u1__p9_2,
  140574. NULL,
  140575. 0
  140576. };
  140577. static long _huff_lengthlist__16u1__short[] = {
  140578. 5, 7,10, 9,11,10,15,11,13,16, 6, 4, 6, 6, 7, 7,
  140579. 10, 9,12,16,10, 6, 5, 6, 6, 7,10,11,16,16, 9, 6,
  140580. 7, 6, 7, 7,10, 8,14,16,11, 6, 5, 4, 5, 6, 8, 9,
  140581. 15,16, 9, 6, 6, 5, 6, 6, 9, 8,14,16,12, 7, 6, 6,
  140582. 5, 6, 6, 7,13,16, 8, 6, 7, 6, 5, 5, 4, 4,11,16,
  140583. 9, 8, 9, 9, 7, 7, 6, 5,13,16,14,14,16,15,16,15,
  140584. 16,16,16,16,
  140585. };
  140586. static static_codebook _huff_book__16u1__short = {
  140587. 2, 100,
  140588. _huff_lengthlist__16u1__short,
  140589. 0, 0, 0, 0, 0,
  140590. NULL,
  140591. NULL,
  140592. NULL,
  140593. NULL,
  140594. 0
  140595. };
  140596. static long _huff_lengthlist__16u2__long[] = {
  140597. 5, 7,10,10,10,11,11,13,18,19, 6, 5, 5, 6, 7, 8,
  140598. 9,12,19,19, 8, 5, 4, 4, 6, 7, 9,13,19,19, 8, 5,
  140599. 4, 4, 5, 6, 8,12,17,19, 7, 5, 5, 4, 4, 5, 7,12,
  140600. 18,18, 8, 7, 7, 6, 5, 5, 6,10,18,18, 9, 9, 9, 8,
  140601. 6, 5, 6, 9,18,18,11,13,13,13, 8, 7, 7, 9,16,18,
  140602. 13,17,18,16,11, 9, 9, 9,17,18,15,18,18,18,15,13,
  140603. 13,14,18,18,
  140604. };
  140605. static static_codebook _huff_book__16u2__long = {
  140606. 2, 100,
  140607. _huff_lengthlist__16u2__long,
  140608. 0, 0, 0, 0, 0,
  140609. NULL,
  140610. NULL,
  140611. NULL,
  140612. NULL,
  140613. 0
  140614. };
  140615. static long _huff_lengthlist__16u2__short[] = {
  140616. 8,11,12,12,14,15,16,16,16,16, 9, 7, 7, 8, 9,11,
  140617. 13,14,16,16,13, 7, 6, 6, 7, 9,12,13,15,16,15, 7,
  140618. 6, 5, 4, 6,10,11,14,16,12, 8, 7, 4, 2, 4, 7,10,
  140619. 14,16,11, 9, 7, 5, 3, 4, 6, 9,14,16,11,10, 9, 7,
  140620. 5, 5, 6, 9,16,16,10,10, 9, 8, 6, 6, 7,10,16,16,
  140621. 11,11,11,10,10,10,11,14,16,16,16,14,14,13,14,16,
  140622. 16,16,16,16,
  140623. };
  140624. static static_codebook _huff_book__16u2__short = {
  140625. 2, 100,
  140626. _huff_lengthlist__16u2__short,
  140627. 0, 0, 0, 0, 0,
  140628. NULL,
  140629. NULL,
  140630. NULL,
  140631. NULL,
  140632. 0
  140633. };
  140634. static long _vq_quantlist__16u2_p1_0[] = {
  140635. 1,
  140636. 0,
  140637. 2,
  140638. };
  140639. static long _vq_lengthlist__16u2_p1_0[] = {
  140640. 1, 5, 5, 5, 7, 7, 5, 7, 7, 5, 7, 7, 7, 9, 9, 7,
  140641. 9, 9, 5, 7, 7, 7, 9, 9, 7, 9, 9, 5, 7, 7, 8, 9,
  140642. 9, 7, 9, 9, 7, 9, 9, 9,10,10, 9,10,10, 7, 9, 9,
  140643. 9,10,10, 9,10,11, 5, 7, 8, 8, 9, 9, 8, 9, 9, 7,
  140644. 9, 9, 9,10,10, 9, 9,10, 7, 9, 9, 9,10,10, 9,11,
  140645. 10,
  140646. };
  140647. static float _vq_quantthresh__16u2_p1_0[] = {
  140648. -0.5, 0.5,
  140649. };
  140650. static long _vq_quantmap__16u2_p1_0[] = {
  140651. 1, 0, 2,
  140652. };
  140653. static encode_aux_threshmatch _vq_auxt__16u2_p1_0 = {
  140654. _vq_quantthresh__16u2_p1_0,
  140655. _vq_quantmap__16u2_p1_0,
  140656. 3,
  140657. 3
  140658. };
  140659. static static_codebook _16u2_p1_0 = {
  140660. 4, 81,
  140661. _vq_lengthlist__16u2_p1_0,
  140662. 1, -535822336, 1611661312, 2, 0,
  140663. _vq_quantlist__16u2_p1_0,
  140664. NULL,
  140665. &_vq_auxt__16u2_p1_0,
  140666. NULL,
  140667. 0
  140668. };
  140669. static long _vq_quantlist__16u2_p2_0[] = {
  140670. 2,
  140671. 1,
  140672. 3,
  140673. 0,
  140674. 4,
  140675. };
  140676. static long _vq_lengthlist__16u2_p2_0[] = {
  140677. 3, 5, 5, 8, 8, 5, 7, 7, 9, 9, 5, 7, 7, 9, 9, 9,
  140678. 10, 9,11,11, 9, 9, 9,11,11, 5, 7, 7, 9, 9, 7, 8,
  140679. 8,10,10, 7, 8, 8,10,10,10,10,10,12,12, 9,10,10,
  140680. 11,12, 5, 7, 7, 9, 9, 7, 8, 8,10,10, 7, 8, 8,10,
  140681. 10, 9,10,10,12,11,10,10,10,12,12, 9,10,10,12,12,
  140682. 10,11,10,13,12, 9,10,10,12,12,12,12,12,14,14,11,
  140683. 12,12,13,14, 9,10,10,12,12, 9,10,10,12,12,10,10,
  140684. 10,12,12,11,12,12,14,13,12,13,12,14,14, 5, 7, 7,
  140685. 9, 9, 7, 8, 8,10,10, 7, 8, 8,10,10,10,11,10,12,
  140686. 12,10,10,11,12,12, 7, 8, 8,10,10, 8, 9, 9,11,11,
  140687. 8, 9, 9,11,11,11,11,11,12,13,10,11,11,12,13, 7,
  140688. 8, 8,10,10, 8, 9, 8,11,10, 8, 9, 9,11,11,10,11,
  140689. 10,13,12,10,11,11,13,13, 9,11,10,13,13,10,11,11,
  140690. 13,13,10,11,11,13,13,12,12,13,13,15,12,12,13,14,
  140691. 15, 9,10,10,12,12,10,11,10,13,12,10,11,11,13,13,
  140692. 11,13,11,14,13,12,13,13,15,15, 5, 7, 7, 9, 9, 7,
  140693. 8, 8,10,10, 7, 8, 8,10,10,10,10,10,12,12,10,10,
  140694. 11,12,12, 7, 8, 8,10,10, 8, 9, 9,11,11, 8, 8, 9,
  140695. 10,11,10,11,11,13,13,10,10,11,12,13, 7, 8, 8,10,
  140696. 11, 8, 9, 9,11,11, 8, 9, 9,11,11,10,11,11,13,12,
  140697. 11,11,11,13,12, 9,10,10,12,12,10,11,11,13,13,10,
  140698. 10,11,12,13,12,13,13,15,14,11,11,13,12,14,10,10,
  140699. 11,13,13,10,11,11,13,13,10,11,11,13,13,12,13,13,
  140700. 14,14,12,13,12,14,13, 8,10, 9,12,12, 9,11,10,13,
  140701. 13, 9,10,10,12,13,12,13,13,14,14,12,12,13,14,14,
  140702. 9,11,10,13,13,10,11,11,13,13,10,11,11,13,13,12,
  140703. 13,13,15,15,13,13,13,14,15, 9,10,10,12,13,10,11,
  140704. 10,13,12,10,11,11,13,13,12,13,12,15,14,13,13,13,
  140705. 14,15,11,12,12,15,14,12,12,13,15,15,12,13,13,15,
  140706. 14,14,13,15,14,16,13,14,15,16,16,11,12,12,14,14,
  140707. 11,12,12,15,14,12,13,13,15,15,13,14,13,16,14,14,
  140708. 14,14,16,16, 8, 9, 9,12,12, 9,10,10,13,12, 9,10,
  140709. 10,13,13,12,12,12,14,14,12,12,13,15,15, 9,10,10,
  140710. 13,12,10,11,11,13,13,10,10,11,13,14,12,13,13,15,
  140711. 15,12,12,13,14,15, 9,10,10,13,13,10,11,11,13,13,
  140712. 10,11,11,13,13,12,13,13,14,14,13,14,13,15,14,11,
  140713. 12,12,14,14,12,13,13,15,14,11,12,12,14,15,14,14,
  140714. 14,16,15,13,12,14,14,16,11,12,13,14,15,12,13,13,
  140715. 14,16,12,13,12,15,14,13,15,14,16,16,14,15,13,16,
  140716. 13,
  140717. };
  140718. static float _vq_quantthresh__16u2_p2_0[] = {
  140719. -1.5, -0.5, 0.5, 1.5,
  140720. };
  140721. static long _vq_quantmap__16u2_p2_0[] = {
  140722. 3, 1, 0, 2, 4,
  140723. };
  140724. static encode_aux_threshmatch _vq_auxt__16u2_p2_0 = {
  140725. _vq_quantthresh__16u2_p2_0,
  140726. _vq_quantmap__16u2_p2_0,
  140727. 5,
  140728. 5
  140729. };
  140730. static static_codebook _16u2_p2_0 = {
  140731. 4, 625,
  140732. _vq_lengthlist__16u2_p2_0,
  140733. 1, -533725184, 1611661312, 3, 0,
  140734. _vq_quantlist__16u2_p2_0,
  140735. NULL,
  140736. &_vq_auxt__16u2_p2_0,
  140737. NULL,
  140738. 0
  140739. };
  140740. static long _vq_quantlist__16u2_p3_0[] = {
  140741. 4,
  140742. 3,
  140743. 5,
  140744. 2,
  140745. 6,
  140746. 1,
  140747. 7,
  140748. 0,
  140749. 8,
  140750. };
  140751. static long _vq_lengthlist__16u2_p3_0[] = {
  140752. 2, 4, 4, 6, 6, 7, 7, 9, 9, 4, 5, 5, 6, 6, 8, 7,
  140753. 9, 9, 4, 5, 5, 6, 6, 7, 8, 9, 9, 6, 6, 6, 7, 7,
  140754. 8, 8,10,10, 6, 6, 6, 7, 7, 8, 8, 9,10, 7, 8, 7,
  140755. 8, 8, 9, 9,10,10, 7, 8, 8, 8, 8, 9, 9,10,10, 9,
  140756. 9, 9,10, 9,10,10,11,11, 9, 9, 9,10,10,10,10,11,
  140757. 11,
  140758. };
  140759. static float _vq_quantthresh__16u2_p3_0[] = {
  140760. -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5, 3.5,
  140761. };
  140762. static long _vq_quantmap__16u2_p3_0[] = {
  140763. 7, 5, 3, 1, 0, 2, 4, 6,
  140764. 8,
  140765. };
  140766. static encode_aux_threshmatch _vq_auxt__16u2_p3_0 = {
  140767. _vq_quantthresh__16u2_p3_0,
  140768. _vq_quantmap__16u2_p3_0,
  140769. 9,
  140770. 9
  140771. };
  140772. static static_codebook _16u2_p3_0 = {
  140773. 2, 81,
  140774. _vq_lengthlist__16u2_p3_0,
  140775. 1, -531628032, 1611661312, 4, 0,
  140776. _vq_quantlist__16u2_p3_0,
  140777. NULL,
  140778. &_vq_auxt__16u2_p3_0,
  140779. NULL,
  140780. 0
  140781. };
  140782. static long _vq_quantlist__16u2_p4_0[] = {
  140783. 8,
  140784. 7,
  140785. 9,
  140786. 6,
  140787. 10,
  140788. 5,
  140789. 11,
  140790. 4,
  140791. 12,
  140792. 3,
  140793. 13,
  140794. 2,
  140795. 14,
  140796. 1,
  140797. 15,
  140798. 0,
  140799. 16,
  140800. };
  140801. static long _vq_lengthlist__16u2_p4_0[] = {
  140802. 2, 4, 4, 6, 6, 7, 7, 8, 8, 9, 9,10,10,11,11,11,
  140803. 11, 5, 5, 5, 7, 7, 8, 8, 9, 9, 9, 9,10,10,11,11,
  140804. 12,11, 5, 5, 5, 7, 7, 8, 8, 9, 9, 9, 9,10,10,11,
  140805. 11,12,12, 6, 7, 7, 7, 7, 8, 8, 9, 9, 9, 9,10,10,
  140806. 11,11,12,12, 6, 7, 7, 7, 7, 8, 8, 9, 9, 9, 9,10,
  140807. 10,11,11,12,12, 7, 8, 8, 8, 8, 9, 9, 9, 9,10,10,
  140808. 11,11,12,12,12,12, 7, 8, 8, 8, 8, 9, 9, 9, 9,10,
  140809. 10,11,11,11,12,12,12, 9, 9, 9, 9, 9, 9,10,10,10,
  140810. 10,10,11,11,12,12,13,13, 8, 9, 9, 9, 9,10, 9,10,
  140811. 10,10,10,11,11,12,12,13,13, 9, 9, 9, 9, 9,10,10,
  140812. 10,10,11,11,11,12,12,12,13,13, 9, 9, 9, 9, 9,10,
  140813. 10,10,10,11,11,12,11,12,12,13,13,10,10,10,10,10,
  140814. 11,11,11,11,11,12,12,12,12,13,13,14,10,10,10,10,
  140815. 10,11,11,11,11,12,11,12,12,13,12,13,13,11,11,11,
  140816. 11,11,12,12,12,12,12,12,13,13,13,13,14,14,11,11,
  140817. 11,11,11,12,12,12,12,12,12,13,12,13,13,14,14,11,
  140818. 12,12,12,12,12,12,13,13,13,13,13,13,14,14,14,14,
  140819. 11,12,12,12,12,12,12,13,13,13,13,14,13,14,14,14,
  140820. 14,
  140821. };
  140822. static float _vq_quantthresh__16u2_p4_0[] = {
  140823. -7.5, -6.5, -5.5, -4.5, -3.5, -2.5, -1.5, -0.5,
  140824. 0.5, 1.5, 2.5, 3.5, 4.5, 5.5, 6.5, 7.5,
  140825. };
  140826. static long _vq_quantmap__16u2_p4_0[] = {
  140827. 15, 13, 11, 9, 7, 5, 3, 1,
  140828. 0, 2, 4, 6, 8, 10, 12, 14,
  140829. 16,
  140830. };
  140831. static encode_aux_threshmatch _vq_auxt__16u2_p4_0 = {
  140832. _vq_quantthresh__16u2_p4_0,
  140833. _vq_quantmap__16u2_p4_0,
  140834. 17,
  140835. 17
  140836. };
  140837. static static_codebook _16u2_p4_0 = {
  140838. 2, 289,
  140839. _vq_lengthlist__16u2_p4_0,
  140840. 1, -529530880, 1611661312, 5, 0,
  140841. _vq_quantlist__16u2_p4_0,
  140842. NULL,
  140843. &_vq_auxt__16u2_p4_0,
  140844. NULL,
  140845. 0
  140846. };
  140847. static long _vq_quantlist__16u2_p5_0[] = {
  140848. 1,
  140849. 0,
  140850. 2,
  140851. };
  140852. static long _vq_lengthlist__16u2_p5_0[] = {
  140853. 1, 4, 4, 5, 7, 7, 5, 7, 7, 5, 9, 8, 7,10, 9, 7,
  140854. 10, 9, 5, 8, 9, 7, 9,10, 7, 9,10, 4, 9, 9, 9,11,
  140855. 11, 8,11,11, 7,11,11,10,10,13,10,14,13, 7,11,11,
  140856. 10,13,11,10,13,14, 5, 9, 9, 8,11,11, 9,11,11, 7,
  140857. 11,11,10,14,13,10,12,14, 7,11,11,10,13,13,10,13,
  140858. 10,
  140859. };
  140860. static float _vq_quantthresh__16u2_p5_0[] = {
  140861. -5.5, 5.5,
  140862. };
  140863. static long _vq_quantmap__16u2_p5_0[] = {
  140864. 1, 0, 2,
  140865. };
  140866. static encode_aux_threshmatch _vq_auxt__16u2_p5_0 = {
  140867. _vq_quantthresh__16u2_p5_0,
  140868. _vq_quantmap__16u2_p5_0,
  140869. 3,
  140870. 3
  140871. };
  140872. static static_codebook _16u2_p5_0 = {
  140873. 4, 81,
  140874. _vq_lengthlist__16u2_p5_0,
  140875. 1, -529137664, 1618345984, 2, 0,
  140876. _vq_quantlist__16u2_p5_0,
  140877. NULL,
  140878. &_vq_auxt__16u2_p5_0,
  140879. NULL,
  140880. 0
  140881. };
  140882. static long _vq_quantlist__16u2_p5_1[] = {
  140883. 5,
  140884. 4,
  140885. 6,
  140886. 3,
  140887. 7,
  140888. 2,
  140889. 8,
  140890. 1,
  140891. 9,
  140892. 0,
  140893. 10,
  140894. };
  140895. static long _vq_lengthlist__16u2_p5_1[] = {
  140896. 2, 5, 5, 6, 6, 7, 7, 8, 8, 8, 8, 5, 5, 5, 7, 7,
  140897. 7, 7, 8, 8, 8, 8, 5, 5, 6, 7, 7, 7, 7, 8, 8, 8,
  140898. 8, 6, 7, 7, 7, 7, 8, 8, 8, 8, 8, 8, 6, 7, 7, 7,
  140899. 7, 8, 8, 8, 8, 8, 8, 7, 7, 7, 8, 8, 8, 8, 9, 9,
  140900. 9, 9, 7, 7, 7, 8, 8, 8, 8, 9, 9, 9, 9, 8, 8, 8,
  140901. 8, 8, 9, 9, 9, 9, 9, 9, 8, 8, 8, 8, 8, 9, 9, 9,
  140902. 9, 9, 9, 8, 8, 8, 8, 8, 9, 9, 9, 9, 9, 9, 8, 8,
  140903. 8, 8, 8, 9, 9, 9, 9, 9, 9,
  140904. };
  140905. static float _vq_quantthresh__16u2_p5_1[] = {
  140906. -4.5, -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5,
  140907. 3.5, 4.5,
  140908. };
  140909. static long _vq_quantmap__16u2_p5_1[] = {
  140910. 9, 7, 5, 3, 1, 0, 2, 4,
  140911. 6, 8, 10,
  140912. };
  140913. static encode_aux_threshmatch _vq_auxt__16u2_p5_1 = {
  140914. _vq_quantthresh__16u2_p5_1,
  140915. _vq_quantmap__16u2_p5_1,
  140916. 11,
  140917. 11
  140918. };
  140919. static static_codebook _16u2_p5_1 = {
  140920. 2, 121,
  140921. _vq_lengthlist__16u2_p5_1,
  140922. 1, -531365888, 1611661312, 4, 0,
  140923. _vq_quantlist__16u2_p5_1,
  140924. NULL,
  140925. &_vq_auxt__16u2_p5_1,
  140926. NULL,
  140927. 0
  140928. };
  140929. static long _vq_quantlist__16u2_p6_0[] = {
  140930. 6,
  140931. 5,
  140932. 7,
  140933. 4,
  140934. 8,
  140935. 3,
  140936. 9,
  140937. 2,
  140938. 10,
  140939. 1,
  140940. 11,
  140941. 0,
  140942. 12,
  140943. };
  140944. static long _vq_lengthlist__16u2_p6_0[] = {
  140945. 1, 4, 4, 7, 7, 8, 8, 8, 8, 9, 9,10,10, 4, 6, 6,
  140946. 8, 8, 9, 9, 9, 9,10,10,12,11, 4, 6, 6, 8, 8, 9,
  140947. 9, 9, 9,10,10,11,12, 7, 8, 8, 9, 9,10,10,10,10,
  140948. 12,12,13,12, 7, 8, 8, 9, 9,10,10,10,10,11,12,12,
  140949. 12, 8, 9, 9,10,10,11,11,11,11,12,12,13,13, 8, 9,
  140950. 9,10,10,11,11,11,11,12,13,13,13, 8, 9, 9,10,10,
  140951. 11,11,12,12,13,13,14,14, 8, 9, 9,10,10,11,11,12,
  140952. 12,13,13,14,14, 9,10,10,11,12,13,12,13,14,14,14,
  140953. 14,14, 9,10,10,11,12,12,13,13,13,14,14,14,14,10,
  140954. 11,11,12,12,13,13,14,14,15,15,15,15,10,11,11,12,
  140955. 12,13,13,14,14,14,14,15,15,
  140956. };
  140957. static float _vq_quantthresh__16u2_p6_0[] = {
  140958. -27.5, -22.5, -17.5, -12.5, -7.5, -2.5, 2.5, 7.5,
  140959. 12.5, 17.5, 22.5, 27.5,
  140960. };
  140961. static long _vq_quantmap__16u2_p6_0[] = {
  140962. 11, 9, 7, 5, 3, 1, 0, 2,
  140963. 4, 6, 8, 10, 12,
  140964. };
  140965. static encode_aux_threshmatch _vq_auxt__16u2_p6_0 = {
  140966. _vq_quantthresh__16u2_p6_0,
  140967. _vq_quantmap__16u2_p6_0,
  140968. 13,
  140969. 13
  140970. };
  140971. static static_codebook _16u2_p6_0 = {
  140972. 2, 169,
  140973. _vq_lengthlist__16u2_p6_0,
  140974. 1, -526516224, 1616117760, 4, 0,
  140975. _vq_quantlist__16u2_p6_0,
  140976. NULL,
  140977. &_vq_auxt__16u2_p6_0,
  140978. NULL,
  140979. 0
  140980. };
  140981. static long _vq_quantlist__16u2_p6_1[] = {
  140982. 2,
  140983. 1,
  140984. 3,
  140985. 0,
  140986. 4,
  140987. };
  140988. static long _vq_lengthlist__16u2_p6_1[] = {
  140989. 2, 4, 4, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5,
  140990. 5, 5, 6, 6, 5, 5, 5, 6, 6,
  140991. };
  140992. static float _vq_quantthresh__16u2_p6_1[] = {
  140993. -1.5, -0.5, 0.5, 1.5,
  140994. };
  140995. static long _vq_quantmap__16u2_p6_1[] = {
  140996. 3, 1, 0, 2, 4,
  140997. };
  140998. static encode_aux_threshmatch _vq_auxt__16u2_p6_1 = {
  140999. _vq_quantthresh__16u2_p6_1,
  141000. _vq_quantmap__16u2_p6_1,
  141001. 5,
  141002. 5
  141003. };
  141004. static static_codebook _16u2_p6_1 = {
  141005. 2, 25,
  141006. _vq_lengthlist__16u2_p6_1,
  141007. 1, -533725184, 1611661312, 3, 0,
  141008. _vq_quantlist__16u2_p6_1,
  141009. NULL,
  141010. &_vq_auxt__16u2_p6_1,
  141011. NULL,
  141012. 0
  141013. };
  141014. static long _vq_quantlist__16u2_p7_0[] = {
  141015. 6,
  141016. 5,
  141017. 7,
  141018. 4,
  141019. 8,
  141020. 3,
  141021. 9,
  141022. 2,
  141023. 10,
  141024. 1,
  141025. 11,
  141026. 0,
  141027. 12,
  141028. };
  141029. static long _vq_lengthlist__16u2_p7_0[] = {
  141030. 1, 4, 4, 7, 7, 7, 7, 8, 8, 9, 9,10,10, 4, 6, 6,
  141031. 9, 9, 9, 9, 9, 9,10,10,11,11, 4, 6, 6, 8, 9, 9,
  141032. 9, 9, 9,10,11,12,11, 7, 8, 9,10,10,10,10,11,10,
  141033. 11,12,12,13, 7, 9, 9,10,10,10,10,10,10,11,12,13,
  141034. 13, 7, 9, 8,10,10,11,11,11,12,12,13,13,14, 7, 9,
  141035. 9,10,10,11,11,11,12,13,13,13,13, 8, 9, 9,10,11,
  141036. 11,12,12,12,13,13,13,13, 8, 9, 9,10,11,11,11,12,
  141037. 12,13,13,14,14, 9,10,10,12,11,12,13,13,13,14,13,
  141038. 13,13, 9,10,10,11,11,12,12,13,14,13,13,14,13,10,
  141039. 11,11,12,13,14,14,14,15,14,14,14,14,10,11,11,12,
  141040. 12,13,13,13,14,14,14,15,14,
  141041. };
  141042. static float _vq_quantthresh__16u2_p7_0[] = {
  141043. -60.5, -49.5, -38.5, -27.5, -16.5, -5.5, 5.5, 16.5,
  141044. 27.5, 38.5, 49.5, 60.5,
  141045. };
  141046. static long _vq_quantmap__16u2_p7_0[] = {
  141047. 11, 9, 7, 5, 3, 1, 0, 2,
  141048. 4, 6, 8, 10, 12,
  141049. };
  141050. static encode_aux_threshmatch _vq_auxt__16u2_p7_0 = {
  141051. _vq_quantthresh__16u2_p7_0,
  141052. _vq_quantmap__16u2_p7_0,
  141053. 13,
  141054. 13
  141055. };
  141056. static static_codebook _16u2_p7_0 = {
  141057. 2, 169,
  141058. _vq_lengthlist__16u2_p7_0,
  141059. 1, -523206656, 1618345984, 4, 0,
  141060. _vq_quantlist__16u2_p7_0,
  141061. NULL,
  141062. &_vq_auxt__16u2_p7_0,
  141063. NULL,
  141064. 0
  141065. };
  141066. static long _vq_quantlist__16u2_p7_1[] = {
  141067. 5,
  141068. 4,
  141069. 6,
  141070. 3,
  141071. 7,
  141072. 2,
  141073. 8,
  141074. 1,
  141075. 9,
  141076. 0,
  141077. 10,
  141078. };
  141079. static long _vq_lengthlist__16u2_p7_1[] = {
  141080. 3, 5, 5, 6, 6, 7, 7, 7, 7, 7, 7, 5, 6, 6, 7, 7,
  141081. 7, 7, 7, 7, 8, 8, 5, 6, 6, 6, 6, 7, 7, 7, 7, 8,
  141082. 8, 6, 6, 7, 7, 7, 8, 7, 8, 8, 8, 8, 6, 7, 7, 7,
  141083. 7, 7, 7, 8, 8, 8, 8, 7, 7, 7, 7, 7, 8, 8, 8, 8,
  141084. 8, 8, 7, 7, 7, 7, 8, 8, 8, 8, 8, 8, 8, 7, 7, 7,
  141085. 8, 8, 8, 8, 8, 8, 8, 8, 7, 7, 7, 8, 8, 8, 8, 8,
  141086. 8, 8, 8, 7, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 7, 8,
  141087. 8, 8, 8, 8, 8, 8, 8, 8, 8,
  141088. };
  141089. static float _vq_quantthresh__16u2_p7_1[] = {
  141090. -4.5, -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5,
  141091. 3.5, 4.5,
  141092. };
  141093. static long _vq_quantmap__16u2_p7_1[] = {
  141094. 9, 7, 5, 3, 1, 0, 2, 4,
  141095. 6, 8, 10,
  141096. };
  141097. static encode_aux_threshmatch _vq_auxt__16u2_p7_1 = {
  141098. _vq_quantthresh__16u2_p7_1,
  141099. _vq_quantmap__16u2_p7_1,
  141100. 11,
  141101. 11
  141102. };
  141103. static static_codebook _16u2_p7_1 = {
  141104. 2, 121,
  141105. _vq_lengthlist__16u2_p7_1,
  141106. 1, -531365888, 1611661312, 4, 0,
  141107. _vq_quantlist__16u2_p7_1,
  141108. NULL,
  141109. &_vq_auxt__16u2_p7_1,
  141110. NULL,
  141111. 0
  141112. };
  141113. static long _vq_quantlist__16u2_p8_0[] = {
  141114. 7,
  141115. 6,
  141116. 8,
  141117. 5,
  141118. 9,
  141119. 4,
  141120. 10,
  141121. 3,
  141122. 11,
  141123. 2,
  141124. 12,
  141125. 1,
  141126. 13,
  141127. 0,
  141128. 14,
  141129. };
  141130. static long _vq_lengthlist__16u2_p8_0[] = {
  141131. 1, 5, 5, 7, 7, 8, 8, 7, 7, 8, 8,10, 9,11,11, 4,
  141132. 6, 6, 8, 8,10, 9, 9, 8, 9, 9,10,10,12,14, 4, 6,
  141133. 7, 8, 9, 9,10, 9, 8, 9, 9,10,12,12,11, 7, 8, 8,
  141134. 10,10,10,10, 9, 9,10,10,11,13,13,12, 7, 8, 8, 9,
  141135. 11,11,10, 9, 9,11,10,12,11,11,14, 8, 9, 9,11,10,
  141136. 11,11,10,10,11,11,13,12,14,12, 8, 9, 9,11,12,11,
  141137. 11,10,10,12,11,12,12,12,14, 7, 8, 8, 9, 9,10,10,
  141138. 10,11,12,11,13,13,14,12, 7, 8, 9, 9, 9,10,10,11,
  141139. 11,11,12,12,14,14,14, 8,10, 9,10,11,11,11,11,14,
  141140. 12,12,13,14,14,13, 9, 9, 9,10,11,11,11,12,12,12,
  141141. 14,12,14,13,14,10,10,10,12,11,12,11,14,13,14,13,
  141142. 14,14,13,14, 9,10,10,11,12,11,13,12,13,13,14,14,
  141143. 14,13,14,10,13,13,12,12,11,12,14,13,14,13,14,12,
  141144. 14,13,10,11,11,12,11,12,12,14,14,14,13,14,14,14,
  141145. 14,
  141146. };
  141147. static float _vq_quantthresh__16u2_p8_0[] = {
  141148. -136.5, -115.5, -94.5, -73.5, -52.5, -31.5, -10.5, 10.5,
  141149. 31.5, 52.5, 73.5, 94.5, 115.5, 136.5,
  141150. };
  141151. static long _vq_quantmap__16u2_p8_0[] = {
  141152. 13, 11, 9, 7, 5, 3, 1, 0,
  141153. 2, 4, 6, 8, 10, 12, 14,
  141154. };
  141155. static encode_aux_threshmatch _vq_auxt__16u2_p8_0 = {
  141156. _vq_quantthresh__16u2_p8_0,
  141157. _vq_quantmap__16u2_p8_0,
  141158. 15,
  141159. 15
  141160. };
  141161. static static_codebook _16u2_p8_0 = {
  141162. 2, 225,
  141163. _vq_lengthlist__16u2_p8_0,
  141164. 1, -520986624, 1620377600, 4, 0,
  141165. _vq_quantlist__16u2_p8_0,
  141166. NULL,
  141167. &_vq_auxt__16u2_p8_0,
  141168. NULL,
  141169. 0
  141170. };
  141171. static long _vq_quantlist__16u2_p8_1[] = {
  141172. 10,
  141173. 9,
  141174. 11,
  141175. 8,
  141176. 12,
  141177. 7,
  141178. 13,
  141179. 6,
  141180. 14,
  141181. 5,
  141182. 15,
  141183. 4,
  141184. 16,
  141185. 3,
  141186. 17,
  141187. 2,
  141188. 18,
  141189. 1,
  141190. 19,
  141191. 0,
  141192. 20,
  141193. };
  141194. static long _vq_lengthlist__16u2_p8_1[] = {
  141195. 2, 5, 5, 7, 7, 8, 8, 8, 8, 9, 9,10, 9,10, 9, 9,
  141196. 9,10,10,10,10, 5, 6, 6, 7, 7, 8, 8, 9, 9, 9, 9,
  141197. 10, 9,10,10,10,10,10,10,11,10, 5, 6, 6, 7, 7, 8,
  141198. 8, 8, 9, 9,10,10,10,10,10,10,10,10,10,10,10, 7,
  141199. 7, 7, 8, 8, 9, 8, 9, 9,10, 9,10,10,10,10,10,10,
  141200. 11,10,11,10, 7, 7, 7, 8, 8, 8, 9, 9, 9,10, 9,10,
  141201. 10,10,10,10,10,10,10,10,10, 8, 8, 8, 9, 9, 9, 9,
  141202. 10, 9,10,10,10,10,10,10,10,11,10,10,11,10, 8, 8,
  141203. 8, 8, 9, 9, 9, 9,10,10,10,10,10,10,10,10,10,11,
  141204. 11,10,10, 8, 9, 9, 9, 9, 9, 9,10,10,10,10,10,10,
  141205. 11,10,11,10,11,10,11,10, 8, 9, 9, 9, 9, 9,10,10,
  141206. 10,10,10,10,10,10,10,10,11,11,10,10,10, 9,10, 9,
  141207. 9,10,10,10,11,10,10,10,10,10,10,10,10,11,11,11,
  141208. 11,11, 9, 9, 9,10, 9,10,10,10,10,10,10,11,10,11,
  141209. 10,11,11,11,11,10,10, 9,10, 9,10,10,10,10,11,10,
  141210. 10,10,10,10,11,10,11,10,11,10,10,11, 9,10,10,10,
  141211. 10,10,10,10,10,10,11,10,10,11,11,10,11,11,11,11,
  141212. 11, 9, 9,10,10,10,10,10,11,10,10,11,10,10,11,10,
  141213. 10,11,11,11,11,11, 9,10,10,10,10,10,10,10,11,10,
  141214. 11,10,11,10,11,11,11,11,11,10,11,10,10,10,10,10,
  141215. 10,10,10,10,11,11,11,11,11,11,11,11,11,10,11,11,
  141216. 10,10,10,10,10,11,10,10,10,11,10,11,11,11,11,10,
  141217. 12,11,11,11,10,10,10,10,10,10,11,10,10,10,11,11,
  141218. 12,11,11,11,11,11,11,11,11,11,10,10,10,11,10,11,
  141219. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,10,
  141220. 10,10,11,10,11,10,10,11,11,11,11,11,11,11,11,11,
  141221. 11,11,11,10,10,10,10,10,10,10,11,11,10,11,11,10,
  141222. 11,11,10,11,11,11,10,11,11,
  141223. };
  141224. static float _vq_quantthresh__16u2_p8_1[] = {
  141225. -9.5, -8.5, -7.5, -6.5, -5.5, -4.5, -3.5, -2.5,
  141226. -1.5, -0.5, 0.5, 1.5, 2.5, 3.5, 4.5, 5.5,
  141227. 6.5, 7.5, 8.5, 9.5,
  141228. };
  141229. static long _vq_quantmap__16u2_p8_1[] = {
  141230. 19, 17, 15, 13, 11, 9, 7, 5,
  141231. 3, 1, 0, 2, 4, 6, 8, 10,
  141232. 12, 14, 16, 18, 20,
  141233. };
  141234. static encode_aux_threshmatch _vq_auxt__16u2_p8_1 = {
  141235. _vq_quantthresh__16u2_p8_1,
  141236. _vq_quantmap__16u2_p8_1,
  141237. 21,
  141238. 21
  141239. };
  141240. static static_codebook _16u2_p8_1 = {
  141241. 2, 441,
  141242. _vq_lengthlist__16u2_p8_1,
  141243. 1, -529268736, 1611661312, 5, 0,
  141244. _vq_quantlist__16u2_p8_1,
  141245. NULL,
  141246. &_vq_auxt__16u2_p8_1,
  141247. NULL,
  141248. 0
  141249. };
  141250. static long _vq_quantlist__16u2_p9_0[] = {
  141251. 5586,
  141252. 4655,
  141253. 6517,
  141254. 3724,
  141255. 7448,
  141256. 2793,
  141257. 8379,
  141258. 1862,
  141259. 9310,
  141260. 931,
  141261. 10241,
  141262. 0,
  141263. 11172,
  141264. 5521,
  141265. 5651,
  141266. };
  141267. static long _vq_lengthlist__16u2_p9_0[] = {
  141268. 1,10,10,10,10,10,10,10,10,10,10,10,10, 5, 4,10,
  141269. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  141270. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  141271. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  141272. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  141273. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  141274. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  141275. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  141276. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  141277. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  141278. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  141279. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  141280. 10,10,10, 4,10,10,10,10,10,10,10,10,10,10,10,10,
  141281. 6, 6, 5,10,10,10,10, 9, 9, 9, 9, 9, 9, 9, 9, 5,
  141282. 5,
  141283. };
  141284. static float _vq_quantthresh__16u2_p9_0[] = {
  141285. -5120.5, -4189.5, -3258.5, -2327.5, -1396.5, -498, -32.5, 32.5,
  141286. 498, 1396.5, 2327.5, 3258.5, 4189.5, 5120.5,
  141287. };
  141288. static long _vq_quantmap__16u2_p9_0[] = {
  141289. 11, 9, 7, 5, 3, 1, 13, 0,
  141290. 14, 2, 4, 6, 8, 10, 12,
  141291. };
  141292. static encode_aux_threshmatch _vq_auxt__16u2_p9_0 = {
  141293. _vq_quantthresh__16u2_p9_0,
  141294. _vq_quantmap__16u2_p9_0,
  141295. 15,
  141296. 15
  141297. };
  141298. static static_codebook _16u2_p9_0 = {
  141299. 2, 225,
  141300. _vq_lengthlist__16u2_p9_0,
  141301. 1, -510275072, 1611661312, 14, 0,
  141302. _vq_quantlist__16u2_p9_0,
  141303. NULL,
  141304. &_vq_auxt__16u2_p9_0,
  141305. NULL,
  141306. 0
  141307. };
  141308. static long _vq_quantlist__16u2_p9_1[] = {
  141309. 392,
  141310. 343,
  141311. 441,
  141312. 294,
  141313. 490,
  141314. 245,
  141315. 539,
  141316. 196,
  141317. 588,
  141318. 147,
  141319. 637,
  141320. 98,
  141321. 686,
  141322. 49,
  141323. 735,
  141324. 0,
  141325. 784,
  141326. 388,
  141327. 396,
  141328. };
  141329. static long _vq_lengthlist__16u2_p9_1[] = {
  141330. 1,12,10,12,10,12,10,12,11,12,12,12,12,12,12,12,
  141331. 12, 5, 5, 9,10,12,11,11,12,12,12,12,12,12,12,12,
  141332. 12,12,12,12,10, 9, 9,11, 9,11,11,12,11,12,12,12,
  141333. 12,12,12,12,12,12,12, 8, 8,10,11, 9,12,11,12,12,
  141334. 12,12,12,12,12,12,12,12,12,12, 9, 8,10,11,12,11,
  141335. 12,11,12,12,12,12,12,12,12,12,12,12,12, 8, 9,11,
  141336. 11,10,12,12,12,12,12,12,12,12,12,12,12,12,12,12,
  141337. 9,10,11,12,11,12,11,12,12,12,12,12,12,12,12,12,
  141338. 12,12,12, 9, 9,11,12,12,12,12,12,12,12,12,12,12,
  141339. 12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,
  141340. 12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,
  141341. 12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,
  141342. 12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,
  141343. 12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,
  141344. 12,12,12,12,11,11,11,11,11,11,11,11,11,11,11,11,
  141345. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  141346. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  141347. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  141348. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  141349. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  141350. 11,11,11, 5, 8, 9, 9, 8,11, 9,11,11,11,11,11,11,
  141351. 11,11,11,11, 5, 5, 4, 8, 8, 8, 8,10, 9,10,10,11,
  141352. 11,11,11,11,11,11,11, 5, 4,
  141353. };
  141354. static float _vq_quantthresh__16u2_p9_1[] = {
  141355. -367.5, -318.5, -269.5, -220.5, -171.5, -122.5, -73.5, -26.5,
  141356. -2, 2, 26.5, 73.5, 122.5, 171.5, 220.5, 269.5,
  141357. 318.5, 367.5,
  141358. };
  141359. static long _vq_quantmap__16u2_p9_1[] = {
  141360. 15, 13, 11, 9, 7, 5, 3, 1,
  141361. 17, 0, 18, 2, 4, 6, 8, 10,
  141362. 12, 14, 16,
  141363. };
  141364. static encode_aux_threshmatch _vq_auxt__16u2_p9_1 = {
  141365. _vq_quantthresh__16u2_p9_1,
  141366. _vq_quantmap__16u2_p9_1,
  141367. 19,
  141368. 19
  141369. };
  141370. static static_codebook _16u2_p9_1 = {
  141371. 2, 361,
  141372. _vq_lengthlist__16u2_p9_1,
  141373. 1, -518488064, 1611661312, 10, 0,
  141374. _vq_quantlist__16u2_p9_1,
  141375. NULL,
  141376. &_vq_auxt__16u2_p9_1,
  141377. NULL,
  141378. 0
  141379. };
  141380. static long _vq_quantlist__16u2_p9_2[] = {
  141381. 24,
  141382. 23,
  141383. 25,
  141384. 22,
  141385. 26,
  141386. 21,
  141387. 27,
  141388. 20,
  141389. 28,
  141390. 19,
  141391. 29,
  141392. 18,
  141393. 30,
  141394. 17,
  141395. 31,
  141396. 16,
  141397. 32,
  141398. 15,
  141399. 33,
  141400. 14,
  141401. 34,
  141402. 13,
  141403. 35,
  141404. 12,
  141405. 36,
  141406. 11,
  141407. 37,
  141408. 10,
  141409. 38,
  141410. 9,
  141411. 39,
  141412. 8,
  141413. 40,
  141414. 7,
  141415. 41,
  141416. 6,
  141417. 42,
  141418. 5,
  141419. 43,
  141420. 4,
  141421. 44,
  141422. 3,
  141423. 45,
  141424. 2,
  141425. 46,
  141426. 1,
  141427. 47,
  141428. 0,
  141429. 48,
  141430. };
  141431. static long _vq_lengthlist__16u2_p9_2[] = {
  141432. 1, 3, 3, 4, 7, 7, 7, 8, 7, 7, 7, 7, 8, 8, 8, 8,
  141433. 7, 8, 8, 8, 8, 8, 8, 8, 8, 8, 7, 9, 9, 8, 9, 9,
  141434. 9, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8,12,12,10,
  141435. 11,
  141436. };
  141437. static float _vq_quantthresh__16u2_p9_2[] = {
  141438. -23.5, -22.5, -21.5, -20.5, -19.5, -18.5, -17.5, -16.5,
  141439. -15.5, -14.5, -13.5, -12.5, -11.5, -10.5, -9.5, -8.5,
  141440. -7.5, -6.5, -5.5, -4.5, -3.5, -2.5, -1.5, -0.5,
  141441. 0.5, 1.5, 2.5, 3.5, 4.5, 5.5, 6.5, 7.5,
  141442. 8.5, 9.5, 10.5, 11.5, 12.5, 13.5, 14.5, 15.5,
  141443. 16.5, 17.5, 18.5, 19.5, 20.5, 21.5, 22.5, 23.5,
  141444. };
  141445. static long _vq_quantmap__16u2_p9_2[] = {
  141446. 47, 45, 43, 41, 39, 37, 35, 33,
  141447. 31, 29, 27, 25, 23, 21, 19, 17,
  141448. 15, 13, 11, 9, 7, 5, 3, 1,
  141449. 0, 2, 4, 6, 8, 10, 12, 14,
  141450. 16, 18, 20, 22, 24, 26, 28, 30,
  141451. 32, 34, 36, 38, 40, 42, 44, 46,
  141452. 48,
  141453. };
  141454. static encode_aux_threshmatch _vq_auxt__16u2_p9_2 = {
  141455. _vq_quantthresh__16u2_p9_2,
  141456. _vq_quantmap__16u2_p9_2,
  141457. 49,
  141458. 49
  141459. };
  141460. static static_codebook _16u2_p9_2 = {
  141461. 1, 49,
  141462. _vq_lengthlist__16u2_p9_2,
  141463. 1, -526909440, 1611661312, 6, 0,
  141464. _vq_quantlist__16u2_p9_2,
  141465. NULL,
  141466. &_vq_auxt__16u2_p9_2,
  141467. NULL,
  141468. 0
  141469. };
  141470. static long _vq_quantlist__8u0__p1_0[] = {
  141471. 1,
  141472. 0,
  141473. 2,
  141474. };
  141475. static long _vq_lengthlist__8u0__p1_0[] = {
  141476. 1, 4, 4, 5, 7, 7, 5, 7, 7, 5, 8, 8, 8,10,10, 7,
  141477. 10,10, 5, 8, 8, 7,10,10, 8,10,10, 4, 9, 8, 8,11,
  141478. 11, 8,11,11, 7,11,11,10,11,13,10,13,13, 7,11,11,
  141479. 10,13,12,10,13,13, 5, 9, 8, 8,11,11, 8,11,11, 7,
  141480. 11,11, 9,13,13,10,12,13, 7,11,11,10,13,13,10,13,
  141481. 11,
  141482. };
  141483. static float _vq_quantthresh__8u0__p1_0[] = {
  141484. -0.5, 0.5,
  141485. };
  141486. static long _vq_quantmap__8u0__p1_0[] = {
  141487. 1, 0, 2,
  141488. };
  141489. static encode_aux_threshmatch _vq_auxt__8u0__p1_0 = {
  141490. _vq_quantthresh__8u0__p1_0,
  141491. _vq_quantmap__8u0__p1_0,
  141492. 3,
  141493. 3
  141494. };
  141495. static static_codebook _8u0__p1_0 = {
  141496. 4, 81,
  141497. _vq_lengthlist__8u0__p1_0,
  141498. 1, -535822336, 1611661312, 2, 0,
  141499. _vq_quantlist__8u0__p1_0,
  141500. NULL,
  141501. &_vq_auxt__8u0__p1_0,
  141502. NULL,
  141503. 0
  141504. };
  141505. static long _vq_quantlist__8u0__p2_0[] = {
  141506. 1,
  141507. 0,
  141508. 2,
  141509. };
  141510. static long _vq_lengthlist__8u0__p2_0[] = {
  141511. 2, 4, 4, 5, 6, 6, 5, 6, 6, 5, 7, 7, 6, 7, 8, 6,
  141512. 7, 8, 5, 7, 7, 6, 8, 8, 7, 9, 7, 5, 7, 7, 7, 9,
  141513. 9, 7, 8, 8, 6, 9, 8, 7, 7,10, 8,10,10, 6, 8, 8,
  141514. 8,10, 8, 8,10,10, 5, 7, 7, 7, 8, 8, 7, 8, 9, 6,
  141515. 8, 8, 8,10,10, 8, 8,10, 6, 8, 9, 8,10,10, 7,10,
  141516. 8,
  141517. };
  141518. static float _vq_quantthresh__8u0__p2_0[] = {
  141519. -0.5, 0.5,
  141520. };
  141521. static long _vq_quantmap__8u0__p2_0[] = {
  141522. 1, 0, 2,
  141523. };
  141524. static encode_aux_threshmatch _vq_auxt__8u0__p2_0 = {
  141525. _vq_quantthresh__8u0__p2_0,
  141526. _vq_quantmap__8u0__p2_0,
  141527. 3,
  141528. 3
  141529. };
  141530. static static_codebook _8u0__p2_0 = {
  141531. 4, 81,
  141532. _vq_lengthlist__8u0__p2_0,
  141533. 1, -535822336, 1611661312, 2, 0,
  141534. _vq_quantlist__8u0__p2_0,
  141535. NULL,
  141536. &_vq_auxt__8u0__p2_0,
  141537. NULL,
  141538. 0
  141539. };
  141540. static long _vq_quantlist__8u0__p3_0[] = {
  141541. 2,
  141542. 1,
  141543. 3,
  141544. 0,
  141545. 4,
  141546. };
  141547. static long _vq_lengthlist__8u0__p3_0[] = {
  141548. 1, 5, 5, 7, 7, 6, 7, 7, 9, 9, 6, 7, 7, 9, 9, 8,
  141549. 10, 9,11,11, 8, 9, 9,11,11, 6, 8, 8,10,10, 8,10,
  141550. 10,11,11, 8,10,10,11,11,10,11,11,12,12,10,11,11,
  141551. 12,13, 6, 8, 8,10,10, 8,10,10,11,11, 8,10,10,11,
  141552. 11, 9,10,11,12,12,10,11,11,12,12, 8,11,11,14,13,
  141553. 10,12,11,15,13,10,12,11,14,14,12,13,12,16,14,12,
  141554. 14,12,16,15, 8,11,11,13,14,10,11,12,13,15,10,11,
  141555. 12,13,15,11,12,13,14,15,12,12,14,14,16, 5, 8, 8,
  141556. 11,11, 9,11,11,12,12, 8,10,11,12,12,11,12,12,15,
  141557. 14,11,12,12,14,14, 7,11,10,13,12,10,11,12,13,14,
  141558. 10,12,12,14,13,12,13,13,14,15,12,13,13,15,15, 7,
  141559. 10,11,12,13,10,12,11,14,13,10,12,13,13,15,12,13,
  141560. 12,14,14,11,13,13,15,16, 9,12,12,15,14,11,13,13,
  141561. 15,16,11,13,13,16,16,13,14,15,15,15,12,14,15,17,
  141562. 16, 9,12,12,14,15,11,13,13,15,16,11,13,13,16,18,
  141563. 13,14,14,17,16,13,15,15,17,18, 5, 8, 9,11,11, 8,
  141564. 11,11,12,12, 8,10,11,12,12,11,12,12,14,14,11,12,
  141565. 12,14,15, 7,11,10,12,13,10,12,12,14,13,10,11,12,
  141566. 13,14,11,13,13,15,14,12,13,13,14,15, 7,10,11,13,
  141567. 13,10,12,12,13,14,10,12,12,13,13,11,13,13,16,16,
  141568. 12,13,13,15,14, 9,12,12,16,15,10,13,13,15,15,11,
  141569. 13,13,17,15,12,15,15,18,17,13,14,14,15,16, 9,12,
  141570. 12,15,15,11,13,13,15,16,11,13,13,15,15,12,15,15,
  141571. 16,16,13,15,14,17,15, 7,11,11,15,15,10,13,13,16,
  141572. 15,10,13,13,15,16,14,15,15,17,19,13,15,14,15,18,
  141573. 9,12,12,16,16,11,13,14,17,16,11,13,13,17,16,15,
  141574. 15,16,17,19,13,15,16, 0,18, 9,12,12,16,15,11,14,
  141575. 13,17,17,11,13,14,16,16,15,16,16,19,18,13,15,15,
  141576. 17,19,11,14,14,19,16,12,14,15, 0,18,12,16,15,18,
  141577. 17,15,15,18,16,19,14,15,17,19,19,11,14,14,18,19,
  141578. 13,15,14,19,19,12,16,15,18,17,15,17,15, 0,16,14,
  141579. 17,16,19, 0, 7,11,11,14,14,10,12,12,15,15,10,13,
  141580. 13,16,15,13,15,15,17, 0,14,15,15,16,19, 9,12,12,
  141581. 16,16,11,14,14,16,16,11,13,13,16,16,14,17,16,19,
  141582. 0,14,18,17,17,19, 9,12,12,15,16,11,13,13,15,17,
  141583. 12,14,13,19,16,13,15,15,17,19,15,17,16,17,19,11,
  141584. 14,14,19,16,12,15,15,19,17,13,14,15,17,19,14,16,
  141585. 17,19,19,16,15,16,17,19,11,15,14,16,16,12,15,15,
  141586. 19, 0,12,14,15,19,19,14,16,16, 0,18,15,19,14,18,
  141587. 16,
  141588. };
  141589. static float _vq_quantthresh__8u0__p3_0[] = {
  141590. -1.5, -0.5, 0.5, 1.5,
  141591. };
  141592. static long _vq_quantmap__8u0__p3_0[] = {
  141593. 3, 1, 0, 2, 4,
  141594. };
  141595. static encode_aux_threshmatch _vq_auxt__8u0__p3_0 = {
  141596. _vq_quantthresh__8u0__p3_0,
  141597. _vq_quantmap__8u0__p3_0,
  141598. 5,
  141599. 5
  141600. };
  141601. static static_codebook _8u0__p3_0 = {
  141602. 4, 625,
  141603. _vq_lengthlist__8u0__p3_0,
  141604. 1, -533725184, 1611661312, 3, 0,
  141605. _vq_quantlist__8u0__p3_0,
  141606. NULL,
  141607. &_vq_auxt__8u0__p3_0,
  141608. NULL,
  141609. 0
  141610. };
  141611. static long _vq_quantlist__8u0__p4_0[] = {
  141612. 2,
  141613. 1,
  141614. 3,
  141615. 0,
  141616. 4,
  141617. };
  141618. static long _vq_lengthlist__8u0__p4_0[] = {
  141619. 3, 5, 5, 8, 8, 5, 6, 7, 9, 9, 6, 7, 6, 9, 9, 9,
  141620. 9, 9,10,11, 9, 9, 9,11,10, 6, 7, 7,10,10, 7, 7,
  141621. 8,10,10, 7, 8, 8,10,10,10,10,10,10,11, 9,10,10,
  141622. 11,12, 6, 7, 7,10,10, 7, 8, 8,10,10, 7, 8, 7,10,
  141623. 10, 9,10,10,12,11,10,10,10,11,10, 9,10,10,12,11,
  141624. 10,10,10,13,11, 9,10,10,12,12,11,11,12,12,13,11,
  141625. 11,11,12,13, 9,10,10,12,12,10,10,11,12,12,10,10,
  141626. 11,12,12,11,11,11,13,13,11,12,12,13,13, 5, 7, 7,
  141627. 10,10, 7, 8, 8,10,10, 7, 8, 8,10,10,10,11,11,12,
  141628. 12,10,11,10,12,12, 7, 8, 8,11,11, 7, 8, 9,10,11,
  141629. 8, 9, 9,11,11,11,10,11,10,12,10,11,11,12,13, 7,
  141630. 8, 8,10,11, 8, 9, 8,12,10, 8, 9, 9,11,12,10,11,
  141631. 10,13,11,10,11,11,13,12, 9,11,10,13,12,10,10,11,
  141632. 12,12,10,11,11,13,13,12,10,13,11,14,11,12,12,15,
  141633. 13, 9,11,11,13,13,10,11,11,13,12,10,11,11,12,14,
  141634. 12,13,11,14,12,12,12,12,14,14, 5, 7, 7,10,10, 7,
  141635. 8, 8,10,10, 7, 8, 8,11,10,10,11,11,12,12,10,11,
  141636. 10,12,12, 7, 8, 8,10,11, 8, 9, 9,12,11, 8, 8, 9,
  141637. 10,11,10,11,11,12,13,11,10,11,11,13, 6, 8, 8,10,
  141638. 11, 8, 9, 9,11,11, 7, 9, 7,11,10,10,11,11,12,12,
  141639. 10,11,10,13,10, 9,11,10,13,12,10,12,11,13,13,10,
  141640. 10,11,12,13,11,12,13,15,14,11,11,13,12,13, 9,10,
  141641. 11,12,13,10,11,11,12,13,10,11,10,13,12,12,13,13,
  141642. 13,14,12,12,11,14,11, 8,10,10,12,13,10,11,11,13,
  141643. 13,10,11,10,13,13,12,13,14,15,14,12,12,12,14,13,
  141644. 9,10,10,13,12,10,10,12,13,13,10,11,11,15,12,12,
  141645. 12,13,15,14,12,13,13,15,13, 9,10,11,12,13,10,12,
  141646. 10,13,12,10,11,11,12,13,12,14,12,15,13,12,12,12,
  141647. 15,14,11,12,11,14,13,11,11,12,14,14,12,13,13,14,
  141648. 13,13,11,15,11,15,14,14,14,16,15,11,12,12,13,14,
  141649. 11,13,11,14,14,12,12,13,14,15,12,14,12,15,12,13,
  141650. 15,14,16,15, 8,10,10,12,12,10,10,10,12,13,10,11,
  141651. 11,13,13,12,12,12,13,14,13,13,13,15,15, 9,10,10,
  141652. 12,12,10,11,11,13,12,10,10,11,13,13,12,12,12,14,
  141653. 14,12,12,13,15,14, 9,10,10,13,12,10,10,12,12,13,
  141654. 10,11,10,13,13,12,13,13,14,14,12,13,12,14,13,11,
  141655. 12,12,14,13,12,13,12,14,14,10,12,12,14,14,14,14,
  141656. 14,16,14,13,12,14,12,15,10,12,12,14,15,12,13,13,
  141657. 14,16,11,12,11,15,14,13,14,14,14,15,13,14,11,14,
  141658. 12,
  141659. };
  141660. static float _vq_quantthresh__8u0__p4_0[] = {
  141661. -1.5, -0.5, 0.5, 1.5,
  141662. };
  141663. static long _vq_quantmap__8u0__p4_0[] = {
  141664. 3, 1, 0, 2, 4,
  141665. };
  141666. static encode_aux_threshmatch _vq_auxt__8u0__p4_0 = {
  141667. _vq_quantthresh__8u0__p4_0,
  141668. _vq_quantmap__8u0__p4_0,
  141669. 5,
  141670. 5
  141671. };
  141672. static static_codebook _8u0__p4_0 = {
  141673. 4, 625,
  141674. _vq_lengthlist__8u0__p4_0,
  141675. 1, -533725184, 1611661312, 3, 0,
  141676. _vq_quantlist__8u0__p4_0,
  141677. NULL,
  141678. &_vq_auxt__8u0__p4_0,
  141679. NULL,
  141680. 0
  141681. };
  141682. static long _vq_quantlist__8u0__p5_0[] = {
  141683. 4,
  141684. 3,
  141685. 5,
  141686. 2,
  141687. 6,
  141688. 1,
  141689. 7,
  141690. 0,
  141691. 8,
  141692. };
  141693. static long _vq_lengthlist__8u0__p5_0[] = {
  141694. 1, 4, 4, 7, 7, 7, 7, 9, 9, 4, 6, 6, 8, 7, 8, 8,
  141695. 10,10, 4, 6, 6, 8, 8, 8, 8,10,10, 6, 8, 8, 9, 9,
  141696. 9, 9,11,11, 7, 8, 8, 9, 9, 9, 9,11,11, 7, 8, 8,
  141697. 9, 9,10,10,12,11, 7, 8, 8, 9, 9,10,10,11,11, 9,
  141698. 10,10,11,11,11,12,12,12, 9,10,10,11,11,12,12,12,
  141699. 12,
  141700. };
  141701. static float _vq_quantthresh__8u0__p5_0[] = {
  141702. -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5, 3.5,
  141703. };
  141704. static long _vq_quantmap__8u0__p5_0[] = {
  141705. 7, 5, 3, 1, 0, 2, 4, 6,
  141706. 8,
  141707. };
  141708. static encode_aux_threshmatch _vq_auxt__8u0__p5_0 = {
  141709. _vq_quantthresh__8u0__p5_0,
  141710. _vq_quantmap__8u0__p5_0,
  141711. 9,
  141712. 9
  141713. };
  141714. static static_codebook _8u0__p5_0 = {
  141715. 2, 81,
  141716. _vq_lengthlist__8u0__p5_0,
  141717. 1, -531628032, 1611661312, 4, 0,
  141718. _vq_quantlist__8u0__p5_0,
  141719. NULL,
  141720. &_vq_auxt__8u0__p5_0,
  141721. NULL,
  141722. 0
  141723. };
  141724. static long _vq_quantlist__8u0__p6_0[] = {
  141725. 6,
  141726. 5,
  141727. 7,
  141728. 4,
  141729. 8,
  141730. 3,
  141731. 9,
  141732. 2,
  141733. 10,
  141734. 1,
  141735. 11,
  141736. 0,
  141737. 12,
  141738. };
  141739. static long _vq_lengthlist__8u0__p6_0[] = {
  141740. 1, 4, 4, 7, 7, 9, 9,11,11,12,12,16,16, 3, 6, 6,
  141741. 9, 9,11,11,12,12,13,14,18,16, 3, 6, 7, 9, 9,11,
  141742. 11,13,12,14,14,17,16, 7, 9, 9,11,11,12,12,14,14,
  141743. 14,14,17,16, 7, 9, 9,11,11,13,12,13,13,14,14,17,
  141744. 0, 9,11,11,12,13,14,14,14,13,15,14,17,17, 9,11,
  141745. 11,12,12,14,14,13,14,14,15, 0, 0,11,12,12,15,14,
  141746. 15,14,15,14,15,16,17, 0,11,12,13,13,13,14,14,15,
  141747. 14,15,15, 0, 0,12,14,14,15,15,14,16,15,15,17,16,
  141748. 0,18,13,14,14,15,14,15,14,15,16,17,16, 0, 0,17,
  141749. 17,18, 0,16,18,16, 0, 0, 0,17, 0, 0,16, 0, 0,16,
  141750. 16, 0,15, 0,17, 0, 0, 0, 0,
  141751. };
  141752. static float _vq_quantthresh__8u0__p6_0[] = {
  141753. -27.5, -22.5, -17.5, -12.5, -7.5, -2.5, 2.5, 7.5,
  141754. 12.5, 17.5, 22.5, 27.5,
  141755. };
  141756. static long _vq_quantmap__8u0__p6_0[] = {
  141757. 11, 9, 7, 5, 3, 1, 0, 2,
  141758. 4, 6, 8, 10, 12,
  141759. };
  141760. static encode_aux_threshmatch _vq_auxt__8u0__p6_0 = {
  141761. _vq_quantthresh__8u0__p6_0,
  141762. _vq_quantmap__8u0__p6_0,
  141763. 13,
  141764. 13
  141765. };
  141766. static static_codebook _8u0__p6_0 = {
  141767. 2, 169,
  141768. _vq_lengthlist__8u0__p6_0,
  141769. 1, -526516224, 1616117760, 4, 0,
  141770. _vq_quantlist__8u0__p6_0,
  141771. NULL,
  141772. &_vq_auxt__8u0__p6_0,
  141773. NULL,
  141774. 0
  141775. };
  141776. static long _vq_quantlist__8u0__p6_1[] = {
  141777. 2,
  141778. 1,
  141779. 3,
  141780. 0,
  141781. 4,
  141782. };
  141783. static long _vq_lengthlist__8u0__p6_1[] = {
  141784. 1, 4, 4, 6, 6, 4, 6, 5, 7, 7, 4, 5, 6, 7, 7, 6,
  141785. 7, 7, 7, 7, 6, 7, 7, 7, 7,
  141786. };
  141787. static float _vq_quantthresh__8u0__p6_1[] = {
  141788. -1.5, -0.5, 0.5, 1.5,
  141789. };
  141790. static long _vq_quantmap__8u0__p6_1[] = {
  141791. 3, 1, 0, 2, 4,
  141792. };
  141793. static encode_aux_threshmatch _vq_auxt__8u0__p6_1 = {
  141794. _vq_quantthresh__8u0__p6_1,
  141795. _vq_quantmap__8u0__p6_1,
  141796. 5,
  141797. 5
  141798. };
  141799. static static_codebook _8u0__p6_1 = {
  141800. 2, 25,
  141801. _vq_lengthlist__8u0__p6_1,
  141802. 1, -533725184, 1611661312, 3, 0,
  141803. _vq_quantlist__8u0__p6_1,
  141804. NULL,
  141805. &_vq_auxt__8u0__p6_1,
  141806. NULL,
  141807. 0
  141808. };
  141809. static long _vq_quantlist__8u0__p7_0[] = {
  141810. 1,
  141811. 0,
  141812. 2,
  141813. };
  141814. static long _vq_lengthlist__8u0__p7_0[] = {
  141815. 1, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8,
  141816. 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8,
  141817. 8, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7,
  141818. 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7,
  141819. 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7,
  141820. 7,
  141821. };
  141822. static float _vq_quantthresh__8u0__p7_0[] = {
  141823. -157.5, 157.5,
  141824. };
  141825. static long _vq_quantmap__8u0__p7_0[] = {
  141826. 1, 0, 2,
  141827. };
  141828. static encode_aux_threshmatch _vq_auxt__8u0__p7_0 = {
  141829. _vq_quantthresh__8u0__p7_0,
  141830. _vq_quantmap__8u0__p7_0,
  141831. 3,
  141832. 3
  141833. };
  141834. static static_codebook _8u0__p7_0 = {
  141835. 4, 81,
  141836. _vq_lengthlist__8u0__p7_0,
  141837. 1, -518803456, 1628680192, 2, 0,
  141838. _vq_quantlist__8u0__p7_0,
  141839. NULL,
  141840. &_vq_auxt__8u0__p7_0,
  141841. NULL,
  141842. 0
  141843. };
  141844. static long _vq_quantlist__8u0__p7_1[] = {
  141845. 7,
  141846. 6,
  141847. 8,
  141848. 5,
  141849. 9,
  141850. 4,
  141851. 10,
  141852. 3,
  141853. 11,
  141854. 2,
  141855. 12,
  141856. 1,
  141857. 13,
  141858. 0,
  141859. 14,
  141860. };
  141861. static long _vq_lengthlist__8u0__p7_1[] = {
  141862. 1, 5, 5, 5, 5,10,10,11,11,11,11,11,11,11,11, 5,
  141863. 7, 6, 8, 8, 9,10,11,11,11,11,11,11,11,11, 6, 6,
  141864. 7, 9, 7,11,10,11,11,11,11,11,11,11,11, 5, 6, 6,
  141865. 11, 8,11,11,11,11,11,11,11,11,11,11, 5, 6, 6, 9,
  141866. 10,11,10,11,11,11,11,11,11,11,11, 7,10,10,11,11,
  141867. 11,11,11,11,11,11,11,11,11,11, 7,11, 8,11,11,11,
  141868. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  141869. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  141870. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  141871. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  141872. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  141873. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  141874. 11,11,11,11,11,11,11,11,11,11,11,10,10,10,10,10,
  141875. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  141876. 10,
  141877. };
  141878. static float _vq_quantthresh__8u0__p7_1[] = {
  141879. -136.5, -115.5, -94.5, -73.5, -52.5, -31.5, -10.5, 10.5,
  141880. 31.5, 52.5, 73.5, 94.5, 115.5, 136.5,
  141881. };
  141882. static long _vq_quantmap__8u0__p7_1[] = {
  141883. 13, 11, 9, 7, 5, 3, 1, 0,
  141884. 2, 4, 6, 8, 10, 12, 14,
  141885. };
  141886. static encode_aux_threshmatch _vq_auxt__8u0__p7_1 = {
  141887. _vq_quantthresh__8u0__p7_1,
  141888. _vq_quantmap__8u0__p7_1,
  141889. 15,
  141890. 15
  141891. };
  141892. static static_codebook _8u0__p7_1 = {
  141893. 2, 225,
  141894. _vq_lengthlist__8u0__p7_1,
  141895. 1, -520986624, 1620377600, 4, 0,
  141896. _vq_quantlist__8u0__p7_1,
  141897. NULL,
  141898. &_vq_auxt__8u0__p7_1,
  141899. NULL,
  141900. 0
  141901. };
  141902. static long _vq_quantlist__8u0__p7_2[] = {
  141903. 10,
  141904. 9,
  141905. 11,
  141906. 8,
  141907. 12,
  141908. 7,
  141909. 13,
  141910. 6,
  141911. 14,
  141912. 5,
  141913. 15,
  141914. 4,
  141915. 16,
  141916. 3,
  141917. 17,
  141918. 2,
  141919. 18,
  141920. 1,
  141921. 19,
  141922. 0,
  141923. 20,
  141924. };
  141925. static long _vq_lengthlist__8u0__p7_2[] = {
  141926. 1, 6, 5, 7, 7, 9, 9, 9, 9,10,12,12,10,11,11,10,
  141927. 11,11,11,10,11, 6, 8, 8, 9, 9,10,10, 9,10,11,11,
  141928. 10,11,11,11,11,10,11,11,11,11, 6, 7, 8, 9, 9, 9,
  141929. 10,11,10,11,12,11,10,11,11,11,11,11,11,12,10, 8,
  141930. 9, 9,10, 9,10,10, 9,10,10,10,10,10, 9,10,10,10,
  141931. 10, 9,10,10, 9, 9, 9, 9,10,10, 9, 9,10,10,11,10,
  141932. 9,12,10,11,10, 9,10,10,10, 8, 9, 9,10, 9,10, 9,
  141933. 9,10,10, 9,10, 9,11,10,10,10,10,10, 9,10, 8, 8,
  141934. 9, 9,10, 9,11, 9, 8, 9, 9,10,11,10,10,10,11,12,
  141935. 9, 9,11, 8, 9, 8,11,10,11,10,10, 9,11,10,10,10,
  141936. 10,10,10,10,11,11,11,11, 8, 9, 9, 9,10,10,10,11,
  141937. 11,12,11,12,11,10,10,10,12,11,11,11,10, 8,10, 9,
  141938. 11,10,10,11,12,10,11,12,11,11,12,11,12,12,10,11,
  141939. 11,10, 9, 9,10,11,12,10,10,10,11,10,11,11,10,12,
  141940. 12,10,11,10,11,12,10, 9,10,10,11,10,11,11,11,11,
  141941. 11,12,11,11,11, 9,11,10,11,10,11,10, 9, 9,10,11,
  141942. 11,11,10,10,11,12,12,11,12,11,11,11,12,12,12,12,
  141943. 11, 9,11,11,12,10,11,11,11,11,11,11,12,11,11,12,
  141944. 11,11,11,10,11,11, 9,11,10,11,11,11,10,10,10,11,
  141945. 11,11,12,10,11,10,11,11,11,11,12, 9,11,10,11,11,
  141946. 10,10,11,11, 9,11,11,12,10,10,10,10,10,11,11,10,
  141947. 9,10,11,11,12,11,10,10,12,11,11,12,11,12,11,11,
  141948. 10,10,11,11,10,12,11,10,11,10,11,10,10,10,11,11,
  141949. 10,10,11,11,11,11,10,10,10,12,11,11,11,11,10, 9,
  141950. 10,11,11,11,12,11,11,11,12,10,11,11,11, 9,10,11,
  141951. 11,11,11,11,11,10,10,11,11,12,11,10,11,12,11,10,
  141952. 10,11, 9,10,11,11,11,11,11,10,11,11,10,12,11,11,
  141953. 11,12,11,11,11,10,10,11,11,
  141954. };
  141955. static float _vq_quantthresh__8u0__p7_2[] = {
  141956. -9.5, -8.5, -7.5, -6.5, -5.5, -4.5, -3.5, -2.5,
  141957. -1.5, -0.5, 0.5, 1.5, 2.5, 3.5, 4.5, 5.5,
  141958. 6.5, 7.5, 8.5, 9.5,
  141959. };
  141960. static long _vq_quantmap__8u0__p7_2[] = {
  141961. 19, 17, 15, 13, 11, 9, 7, 5,
  141962. 3, 1, 0, 2, 4, 6, 8, 10,
  141963. 12, 14, 16, 18, 20,
  141964. };
  141965. static encode_aux_threshmatch _vq_auxt__8u0__p7_2 = {
  141966. _vq_quantthresh__8u0__p7_2,
  141967. _vq_quantmap__8u0__p7_2,
  141968. 21,
  141969. 21
  141970. };
  141971. static static_codebook _8u0__p7_2 = {
  141972. 2, 441,
  141973. _vq_lengthlist__8u0__p7_2,
  141974. 1, -529268736, 1611661312, 5, 0,
  141975. _vq_quantlist__8u0__p7_2,
  141976. NULL,
  141977. &_vq_auxt__8u0__p7_2,
  141978. NULL,
  141979. 0
  141980. };
  141981. static long _huff_lengthlist__8u0__single[] = {
  141982. 4, 7,11, 9,12, 8, 7,10, 6, 4, 5, 5, 7, 5, 6,16,
  141983. 9, 5, 5, 6, 7, 7, 9,16, 7, 4, 6, 5, 7, 5, 7,17,
  141984. 10, 7, 7, 8, 7, 7, 8,18, 7, 5, 6, 4, 5, 4, 5,15,
  141985. 7, 6, 7, 5, 6, 4, 5,15,12,13,18,12,17,11, 9,17,
  141986. };
  141987. static static_codebook _huff_book__8u0__single = {
  141988. 2, 64,
  141989. _huff_lengthlist__8u0__single,
  141990. 0, 0, 0, 0, 0,
  141991. NULL,
  141992. NULL,
  141993. NULL,
  141994. NULL,
  141995. 0
  141996. };
  141997. static long _vq_quantlist__8u1__p1_0[] = {
  141998. 1,
  141999. 0,
  142000. 2,
  142001. };
  142002. static long _vq_lengthlist__8u1__p1_0[] = {
  142003. 1, 4, 4, 5, 7, 7, 5, 7, 7, 5, 8, 8, 7, 9,10, 7,
  142004. 9, 9, 5, 8, 8, 7,10, 9, 7, 9, 9, 5, 8, 8, 8,10,
  142005. 10, 8,10,10, 7,10,10, 9,10,12,10,12,12, 7,10,10,
  142006. 9,12,11,10,12,12, 5, 8, 8, 8,10,10, 8,10,10, 7,
  142007. 10,10,10,12,12, 9,11,12, 7,10,10,10,12,12, 9,12,
  142008. 10,
  142009. };
  142010. static float _vq_quantthresh__8u1__p1_0[] = {
  142011. -0.5, 0.5,
  142012. };
  142013. static long _vq_quantmap__8u1__p1_0[] = {
  142014. 1, 0, 2,
  142015. };
  142016. static encode_aux_threshmatch _vq_auxt__8u1__p1_0 = {
  142017. _vq_quantthresh__8u1__p1_0,
  142018. _vq_quantmap__8u1__p1_0,
  142019. 3,
  142020. 3
  142021. };
  142022. static static_codebook _8u1__p1_0 = {
  142023. 4, 81,
  142024. _vq_lengthlist__8u1__p1_0,
  142025. 1, -535822336, 1611661312, 2, 0,
  142026. _vq_quantlist__8u1__p1_0,
  142027. NULL,
  142028. &_vq_auxt__8u1__p1_0,
  142029. NULL,
  142030. 0
  142031. };
  142032. static long _vq_quantlist__8u1__p2_0[] = {
  142033. 1,
  142034. 0,
  142035. 2,
  142036. };
  142037. static long _vq_lengthlist__8u1__p2_0[] = {
  142038. 3, 4, 5, 5, 6, 6, 5, 6, 6, 5, 7, 6, 6, 7, 8, 6,
  142039. 7, 8, 5, 6, 6, 6, 8, 7, 6, 8, 7, 5, 6, 6, 7, 8,
  142040. 8, 6, 7, 7, 6, 8, 7, 7, 7, 9, 8, 9, 9, 6, 7, 8,
  142041. 7, 9, 7, 8, 9, 9, 5, 6, 6, 6, 7, 7, 7, 8, 8, 6,
  142042. 8, 7, 8, 9, 9, 7, 7, 9, 6, 7, 8, 8, 9, 9, 7, 9,
  142043. 7,
  142044. };
  142045. static float _vq_quantthresh__8u1__p2_0[] = {
  142046. -0.5, 0.5,
  142047. };
  142048. static long _vq_quantmap__8u1__p2_0[] = {
  142049. 1, 0, 2,
  142050. };
  142051. static encode_aux_threshmatch _vq_auxt__8u1__p2_0 = {
  142052. _vq_quantthresh__8u1__p2_0,
  142053. _vq_quantmap__8u1__p2_0,
  142054. 3,
  142055. 3
  142056. };
  142057. static static_codebook _8u1__p2_0 = {
  142058. 4, 81,
  142059. _vq_lengthlist__8u1__p2_0,
  142060. 1, -535822336, 1611661312, 2, 0,
  142061. _vq_quantlist__8u1__p2_0,
  142062. NULL,
  142063. &_vq_auxt__8u1__p2_0,
  142064. NULL,
  142065. 0
  142066. };
  142067. static long _vq_quantlist__8u1__p3_0[] = {
  142068. 2,
  142069. 1,
  142070. 3,
  142071. 0,
  142072. 4,
  142073. };
  142074. static long _vq_lengthlist__8u1__p3_0[] = {
  142075. 1, 5, 5, 7, 7, 6, 7, 7, 9, 9, 6, 7, 7, 9, 9, 8,
  142076. 10, 9,11,11, 9, 9, 9,11,11, 6, 8, 8,10,10, 8,10,
  142077. 10,11,11, 8, 9,10,11,11,10,11,11,12,12,10,11,11,
  142078. 12,13, 6, 8, 8,10,10, 8,10, 9,11,11, 8,10, 9,11,
  142079. 11,10,11,11,12,12,10,11,11,12,12, 9,11,11,14,13,
  142080. 10,12,11,14,14,10,12,11,14,13,12,13,13,15,14,12,
  142081. 13,13,15,14, 8,11,11,13,14,10,11,12,13,15,10,11,
  142082. 12,14,14,12,13,13,14,15,12,13,13,14,15, 5, 8, 8,
  142083. 11,11, 8,10,10,12,12, 8,10,10,12,12,11,12,12,14,
  142084. 13,11,12,12,13,14, 8,10,10,12,12, 9,11,12,13,14,
  142085. 10,12,12,13,13,12,12,13,14,14,11,13,13,15,15, 7,
  142086. 10,10,12,12, 9,12,11,14,12,10,11,12,13,14,12,13,
  142087. 12,14,14,12,13,13,15,16,10,12,12,15,14,11,12,13,
  142088. 15,15,11,13,13,15,16,14,14,15,15,16,13,14,15,17,
  142089. 15, 9,12,12,14,15,11,13,12,15,15,11,13,13,15,15,
  142090. 13,14,13,15,14,13,14,14,17, 0, 5, 8, 8,11,11, 8,
  142091. 10,10,12,12, 8,10,10,12,12,11,12,12,14,14,11,12,
  142092. 12,14,14, 7,10,10,12,12,10,12,12,13,13, 9,11,12,
  142093. 12,13,11,12,13,15,15,11,12,13,14,15, 8,10,10,12,
  142094. 12,10,12,11,13,13,10,12,11,13,13,11,13,13,15,14,
  142095. 12,13,12,15,13, 9,12,12,14,14,11,13,13,16,15,11,
  142096. 12,13,16,15,13,14,15,16,16,13,13,15,15,16,10,12,
  142097. 12,15,14,11,13,13,14,16,11,13,13,15,16,13,15,15,
  142098. 16,17,13,15,14,16,15, 8,11,11,14,15,10,12,12,15,
  142099. 15,10,12,12,15,16,14,15,15,16,17,13,14,14,16,16,
  142100. 9,12,12,15,15,11,13,14,15,17,11,13,13,15,16,14,
  142101. 15,16,19,17,13,15,15, 0,17, 9,12,12,15,15,11,14,
  142102. 13,16,15,11,13,13,15,16,15,15,15,18,17,13,15,15,
  142103. 17,17,11,15,14,18,16,12,14,15,17,17,12,15,15,18,
  142104. 18,15,15,16,15,19,14,16,16, 0, 0,11,14,14,16,17,
  142105. 12,15,14,18,17,12,15,15,18,18,15,17,15,18,16,14,
  142106. 16,16,18,18, 7,11,11,14,14,10,12,12,15,15,10,12,
  142107. 13,15,15,13,14,15,16,16,14,15,15,18,18, 9,12,12,
  142108. 15,15,11,13,13,16,15,11,12,13,16,16,14,15,15,17,
  142109. 16,15,16,16,17,17, 9,12,12,15,15,11,13,13,15,17,
  142110. 11,14,13,16,15,13,15,15,17,17,15,15,15,18,17,11,
  142111. 14,14,17,15,12,14,15,17,18,13,13,15,17,17,14,16,
  142112. 16,19,18,16,15,17,17, 0,11,14,14,17,17,12,15,15,
  142113. 18, 0,12,15,14,18,16,14,17,17,19, 0,16,18,15, 0,
  142114. 16,
  142115. };
  142116. static float _vq_quantthresh__8u1__p3_0[] = {
  142117. -1.5, -0.5, 0.5, 1.5,
  142118. };
  142119. static long _vq_quantmap__8u1__p3_0[] = {
  142120. 3, 1, 0, 2, 4,
  142121. };
  142122. static encode_aux_threshmatch _vq_auxt__8u1__p3_0 = {
  142123. _vq_quantthresh__8u1__p3_0,
  142124. _vq_quantmap__8u1__p3_0,
  142125. 5,
  142126. 5
  142127. };
  142128. static static_codebook _8u1__p3_0 = {
  142129. 4, 625,
  142130. _vq_lengthlist__8u1__p3_0,
  142131. 1, -533725184, 1611661312, 3, 0,
  142132. _vq_quantlist__8u1__p3_0,
  142133. NULL,
  142134. &_vq_auxt__8u1__p3_0,
  142135. NULL,
  142136. 0
  142137. };
  142138. static long _vq_quantlist__8u1__p4_0[] = {
  142139. 2,
  142140. 1,
  142141. 3,
  142142. 0,
  142143. 4,
  142144. };
  142145. static long _vq_lengthlist__8u1__p4_0[] = {
  142146. 4, 5, 5, 9, 9, 6, 7, 7, 9, 9, 6, 7, 7, 9, 9, 9,
  142147. 9, 9,11,11, 9, 9, 9,11,11, 6, 7, 7, 9, 9, 7, 7,
  142148. 8, 9,10, 7, 7, 8, 9,10, 9, 9,10,10,11, 9, 9,10,
  142149. 10,12, 6, 7, 7, 9, 9, 7, 8, 7,10, 9, 7, 8, 7,10,
  142150. 9, 9,10, 9,12,11,10,10, 9,12,10, 9,10,10,12,11,
  142151. 9,10,10,12,11, 9,10,10,12,12,11,11,12,12,13,11,
  142152. 11,12,12,13, 9, 9,10,12,11, 9,10,10,12,12,10,10,
  142153. 10,12,12,11,12,11,13,12,11,12,11,13,12, 6, 7, 7,
  142154. 9, 9, 7, 8, 8,10,10, 7, 8, 7,10, 9,10,10,10,12,
  142155. 12,10,10,10,12,11, 7, 8, 7,10,10, 7, 7, 9,10,11,
  142156. 8, 9, 9,11,10,10,10,11,10,12,10,10,11,12,12, 7,
  142157. 8, 8,10,10, 7, 9, 8,11,10, 8, 8, 9,11,11,10,11,
  142158. 10,12,11,10,11,11,12,12, 9,10,10,12,12, 9,10,10,
  142159. 12,12,10,11,11,13,12,11,10,12,10,14,12,12,12,13,
  142160. 14, 9,10,10,12,12, 9,11,10,12,12,10,11,11,12,12,
  142161. 11,12,11,14,12,12,12,12,14,14, 5, 7, 7, 9, 9, 7,
  142162. 7, 7, 9,10, 7, 8, 8,10,10,10,10,10,11,11,10,10,
  142163. 10,12,12, 7, 8, 8,10,10, 8, 9, 8,11,10, 7, 8, 9,
  142164. 10,11,10,10,10,11,12,10,10,11,11,13, 6, 7, 8,10,
  142165. 10, 8, 9, 9,10,10, 7, 9, 7,11,10,10,11,10,12,12,
  142166. 10,11,10,12,10, 9,10,10,12,12,10,11,11,13,12, 9,
  142167. 10,10,12,12,12,12,12,14,13,11,11,12,11,14, 9,10,
  142168. 10,11,12,10,11,11,12,13, 9,10,10,12,12,12,12,12,
  142169. 14,13,11,12,10,14,11, 9, 9,10,11,12, 9,10,10,12,
  142170. 12, 9,10,10,12,12,12,12,12,14,14,11,12,12,13,12,
  142171. 9,10, 9,12,12, 9,10,11,12,13,10,11,10,13,11,12,
  142172. 12,13,13,14,12,12,12,13,13, 9,10,10,12,12,10,11,
  142173. 10,13,12,10,10,11,12,13,12,13,12,14,13,12,12,12,
  142174. 13,14,11,12,11,14,13,10,10,11,13,13,12,12,12,14,
  142175. 13,12,10,14,10,15,13,14,14,14,14,11,11,12,13,14,
  142176. 10,12,11,13,13,12,12,12,13,15,12,13,11,15,12,13,
  142177. 13,14,14,14, 9,10, 9,12,12, 9,10,10,12,12,10,10,
  142178. 10,12,12,11,11,12,12,13,12,12,12,14,14, 9,10,10,
  142179. 12,12,10,11,10,13,12,10,10,11,12,13,12,12,12,14,
  142180. 13,12,12,13,13,14, 9,10,10,12,13,10,10,11,11,12,
  142181. 9,11,10,13,12,12,12,12,13,14,12,13,12,14,13,11,
  142182. 12,11,13,13,12,13,12,14,13,10,11,12,13,13,13,13,
  142183. 13,14,15,12,11,14,12,14,11,11,12,12,13,12,12,12,
  142184. 13,14,10,12,10,14,13,13,13,13,14,15,12,14,11,15,
  142185. 10,
  142186. };
  142187. static float _vq_quantthresh__8u1__p4_0[] = {
  142188. -1.5, -0.5, 0.5, 1.5,
  142189. };
  142190. static long _vq_quantmap__8u1__p4_0[] = {
  142191. 3, 1, 0, 2, 4,
  142192. };
  142193. static encode_aux_threshmatch _vq_auxt__8u1__p4_0 = {
  142194. _vq_quantthresh__8u1__p4_0,
  142195. _vq_quantmap__8u1__p4_0,
  142196. 5,
  142197. 5
  142198. };
  142199. static static_codebook _8u1__p4_0 = {
  142200. 4, 625,
  142201. _vq_lengthlist__8u1__p4_0,
  142202. 1, -533725184, 1611661312, 3, 0,
  142203. _vq_quantlist__8u1__p4_0,
  142204. NULL,
  142205. &_vq_auxt__8u1__p4_0,
  142206. NULL,
  142207. 0
  142208. };
  142209. static long _vq_quantlist__8u1__p5_0[] = {
  142210. 4,
  142211. 3,
  142212. 5,
  142213. 2,
  142214. 6,
  142215. 1,
  142216. 7,
  142217. 0,
  142218. 8,
  142219. };
  142220. static long _vq_lengthlist__8u1__p5_0[] = {
  142221. 1, 4, 4, 7, 7, 7, 7, 9, 9, 4, 6, 5, 8, 7, 8, 8,
  142222. 10,10, 4, 6, 6, 8, 8, 8, 8,10,10, 7, 8, 8, 9, 9,
  142223. 9, 9,11,11, 7, 8, 8, 9, 9, 9, 9,11,11, 8, 8, 8,
  142224. 9, 9,10,10,12,11, 8, 8, 8, 9, 9,10,10,11,11, 9,
  142225. 10,10,11,11,11,11,13,12, 9,10,10,11,11,12,12,12,
  142226. 13,
  142227. };
  142228. static float _vq_quantthresh__8u1__p5_0[] = {
  142229. -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5, 3.5,
  142230. };
  142231. static long _vq_quantmap__8u1__p5_0[] = {
  142232. 7, 5, 3, 1, 0, 2, 4, 6,
  142233. 8,
  142234. };
  142235. static encode_aux_threshmatch _vq_auxt__8u1__p5_0 = {
  142236. _vq_quantthresh__8u1__p5_0,
  142237. _vq_quantmap__8u1__p5_0,
  142238. 9,
  142239. 9
  142240. };
  142241. static static_codebook _8u1__p5_0 = {
  142242. 2, 81,
  142243. _vq_lengthlist__8u1__p5_0,
  142244. 1, -531628032, 1611661312, 4, 0,
  142245. _vq_quantlist__8u1__p5_0,
  142246. NULL,
  142247. &_vq_auxt__8u1__p5_0,
  142248. NULL,
  142249. 0
  142250. };
  142251. static long _vq_quantlist__8u1__p6_0[] = {
  142252. 4,
  142253. 3,
  142254. 5,
  142255. 2,
  142256. 6,
  142257. 1,
  142258. 7,
  142259. 0,
  142260. 8,
  142261. };
  142262. static long _vq_lengthlist__8u1__p6_0[] = {
  142263. 3, 4, 4, 6, 6, 7, 7, 9, 9, 4, 4, 5, 6, 6, 7, 7,
  142264. 9, 9, 4, 4, 4, 6, 6, 7, 7, 9, 9, 6, 6, 6, 7, 7,
  142265. 8, 8, 9, 9, 6, 6, 6, 7, 7, 8, 8, 9, 9, 7, 7, 7,
  142266. 8, 8, 8, 9,10,10, 7, 7, 7, 8, 8, 9, 8,10,10, 9,
  142267. 9, 9, 9, 9,10,10,10,10, 9, 9, 9, 9, 9,10,10,10,
  142268. 10,
  142269. };
  142270. static float _vq_quantthresh__8u1__p6_0[] = {
  142271. -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5, 3.5,
  142272. };
  142273. static long _vq_quantmap__8u1__p6_0[] = {
  142274. 7, 5, 3, 1, 0, 2, 4, 6,
  142275. 8,
  142276. };
  142277. static encode_aux_threshmatch _vq_auxt__8u1__p6_0 = {
  142278. _vq_quantthresh__8u1__p6_0,
  142279. _vq_quantmap__8u1__p6_0,
  142280. 9,
  142281. 9
  142282. };
  142283. static static_codebook _8u1__p6_0 = {
  142284. 2, 81,
  142285. _vq_lengthlist__8u1__p6_0,
  142286. 1, -531628032, 1611661312, 4, 0,
  142287. _vq_quantlist__8u1__p6_0,
  142288. NULL,
  142289. &_vq_auxt__8u1__p6_0,
  142290. NULL,
  142291. 0
  142292. };
  142293. static long _vq_quantlist__8u1__p7_0[] = {
  142294. 1,
  142295. 0,
  142296. 2,
  142297. };
  142298. static long _vq_lengthlist__8u1__p7_0[] = {
  142299. 1, 4, 4, 5, 7, 7, 5, 7, 7, 5, 9, 9, 8,10,10, 8,
  142300. 10,10, 5, 9, 9, 7,10,10, 8,10,10, 4,10,10, 9,12,
  142301. 12, 9,11,11, 7,12,11,10,11,13,10,13,13, 7,12,12,
  142302. 10,13,12,10,13,13, 4,10,10, 9,12,12, 9,12,12, 7,
  142303. 12,12,10,13,13,10,12,13, 7,11,12,10,13,13,10,13,
  142304. 11,
  142305. };
  142306. static float _vq_quantthresh__8u1__p7_0[] = {
  142307. -5.5, 5.5,
  142308. };
  142309. static long _vq_quantmap__8u1__p7_0[] = {
  142310. 1, 0, 2,
  142311. };
  142312. static encode_aux_threshmatch _vq_auxt__8u1__p7_0 = {
  142313. _vq_quantthresh__8u1__p7_0,
  142314. _vq_quantmap__8u1__p7_0,
  142315. 3,
  142316. 3
  142317. };
  142318. static static_codebook _8u1__p7_0 = {
  142319. 4, 81,
  142320. _vq_lengthlist__8u1__p7_0,
  142321. 1, -529137664, 1618345984, 2, 0,
  142322. _vq_quantlist__8u1__p7_0,
  142323. NULL,
  142324. &_vq_auxt__8u1__p7_0,
  142325. NULL,
  142326. 0
  142327. };
  142328. static long _vq_quantlist__8u1__p7_1[] = {
  142329. 5,
  142330. 4,
  142331. 6,
  142332. 3,
  142333. 7,
  142334. 2,
  142335. 8,
  142336. 1,
  142337. 9,
  142338. 0,
  142339. 10,
  142340. };
  142341. static long _vq_lengthlist__8u1__p7_1[] = {
  142342. 2, 4, 4, 6, 6, 7, 7, 8, 8, 8, 8, 4, 5, 5, 7, 7,
  142343. 8, 8, 9, 9, 9, 9, 4, 5, 5, 7, 7, 8, 8, 9, 9, 9,
  142344. 9, 6, 7, 7, 8, 8, 8, 8, 9, 9, 9, 9, 6, 7, 7, 8,
  142345. 8, 8, 8, 9, 9, 9, 9, 8, 8, 8, 8, 8, 9, 9, 9, 9,
  142346. 9, 9, 8, 8, 8, 8, 8, 9, 9, 9, 9, 9, 9, 8, 9, 9,
  142347. 9, 9, 9, 9,10,10,10,10, 8, 9, 9, 9, 9, 9, 9,10,
  142348. 10,10,10, 8, 9, 9, 9, 9, 9, 9,10,10,10,10, 8, 9,
  142349. 9, 9, 9, 9, 9,10,10,10,10,
  142350. };
  142351. static float _vq_quantthresh__8u1__p7_1[] = {
  142352. -4.5, -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5,
  142353. 3.5, 4.5,
  142354. };
  142355. static long _vq_quantmap__8u1__p7_1[] = {
  142356. 9, 7, 5, 3, 1, 0, 2, 4,
  142357. 6, 8, 10,
  142358. };
  142359. static encode_aux_threshmatch _vq_auxt__8u1__p7_1 = {
  142360. _vq_quantthresh__8u1__p7_1,
  142361. _vq_quantmap__8u1__p7_1,
  142362. 11,
  142363. 11
  142364. };
  142365. static static_codebook _8u1__p7_1 = {
  142366. 2, 121,
  142367. _vq_lengthlist__8u1__p7_1,
  142368. 1, -531365888, 1611661312, 4, 0,
  142369. _vq_quantlist__8u1__p7_1,
  142370. NULL,
  142371. &_vq_auxt__8u1__p7_1,
  142372. NULL,
  142373. 0
  142374. };
  142375. static long _vq_quantlist__8u1__p8_0[] = {
  142376. 5,
  142377. 4,
  142378. 6,
  142379. 3,
  142380. 7,
  142381. 2,
  142382. 8,
  142383. 1,
  142384. 9,
  142385. 0,
  142386. 10,
  142387. };
  142388. static long _vq_lengthlist__8u1__p8_0[] = {
  142389. 1, 4, 4, 6, 6, 8, 8,10,10,11,11, 4, 6, 6, 7, 7,
  142390. 9, 9,11,11,13,12, 4, 6, 6, 7, 7, 9, 9,11,11,12,
  142391. 12, 6, 7, 7, 9, 9,11,11,12,12,13,13, 6, 7, 7, 9,
  142392. 9,11,11,12,12,13,13, 8, 9, 9,11,11,12,12,13,13,
  142393. 14,14, 8, 9, 9,11,11,12,12,13,13,14,14, 9,11,11,
  142394. 12,12,13,13,14,14,15,15, 9,11,11,12,12,13,13,14,
  142395. 14,15,14,11,12,12,13,13,14,14,15,15,16,16,11,12,
  142396. 12,13,13,14,14,15,15,15,15,
  142397. };
  142398. static float _vq_quantthresh__8u1__p8_0[] = {
  142399. -49.5, -38.5, -27.5, -16.5, -5.5, 5.5, 16.5, 27.5,
  142400. 38.5, 49.5,
  142401. };
  142402. static long _vq_quantmap__8u1__p8_0[] = {
  142403. 9, 7, 5, 3, 1, 0, 2, 4,
  142404. 6, 8, 10,
  142405. };
  142406. static encode_aux_threshmatch _vq_auxt__8u1__p8_0 = {
  142407. _vq_quantthresh__8u1__p8_0,
  142408. _vq_quantmap__8u1__p8_0,
  142409. 11,
  142410. 11
  142411. };
  142412. static static_codebook _8u1__p8_0 = {
  142413. 2, 121,
  142414. _vq_lengthlist__8u1__p8_0,
  142415. 1, -524582912, 1618345984, 4, 0,
  142416. _vq_quantlist__8u1__p8_0,
  142417. NULL,
  142418. &_vq_auxt__8u1__p8_0,
  142419. NULL,
  142420. 0
  142421. };
  142422. static long _vq_quantlist__8u1__p8_1[] = {
  142423. 5,
  142424. 4,
  142425. 6,
  142426. 3,
  142427. 7,
  142428. 2,
  142429. 8,
  142430. 1,
  142431. 9,
  142432. 0,
  142433. 10,
  142434. };
  142435. static long _vq_lengthlist__8u1__p8_1[] = {
  142436. 2, 5, 5, 6, 6, 7, 7, 7, 7, 8, 8, 5, 6, 6, 7, 7,
  142437. 7, 7, 8, 8, 8, 8, 5, 6, 6, 7, 7, 7, 7, 8, 8, 8,
  142438. 8, 6, 7, 7, 7, 7, 8, 8, 8, 8, 8, 8, 6, 7, 7, 7,
  142439. 7, 8, 8, 8, 8, 8, 8, 7, 7, 7, 8, 8, 8, 8, 8, 8,
  142440. 8, 8, 7, 7, 7, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8,
  142441. 8, 8, 8, 8, 9, 8, 9, 9, 7, 8, 8, 8, 8, 8, 8, 9,
  142442. 8, 9, 9, 8, 8, 8, 8, 8, 8, 8, 9, 9, 9, 9, 8, 8,
  142443. 8, 8, 8, 8, 8, 9, 9, 9, 9,
  142444. };
  142445. static float _vq_quantthresh__8u1__p8_1[] = {
  142446. -4.5, -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5,
  142447. 3.5, 4.5,
  142448. };
  142449. static long _vq_quantmap__8u1__p8_1[] = {
  142450. 9, 7, 5, 3, 1, 0, 2, 4,
  142451. 6, 8, 10,
  142452. };
  142453. static encode_aux_threshmatch _vq_auxt__8u1__p8_1 = {
  142454. _vq_quantthresh__8u1__p8_1,
  142455. _vq_quantmap__8u1__p8_1,
  142456. 11,
  142457. 11
  142458. };
  142459. static static_codebook _8u1__p8_1 = {
  142460. 2, 121,
  142461. _vq_lengthlist__8u1__p8_1,
  142462. 1, -531365888, 1611661312, 4, 0,
  142463. _vq_quantlist__8u1__p8_1,
  142464. NULL,
  142465. &_vq_auxt__8u1__p8_1,
  142466. NULL,
  142467. 0
  142468. };
  142469. static long _vq_quantlist__8u1__p9_0[] = {
  142470. 7,
  142471. 6,
  142472. 8,
  142473. 5,
  142474. 9,
  142475. 4,
  142476. 10,
  142477. 3,
  142478. 11,
  142479. 2,
  142480. 12,
  142481. 1,
  142482. 13,
  142483. 0,
  142484. 14,
  142485. };
  142486. static long _vq_lengthlist__8u1__p9_0[] = {
  142487. 1, 4, 4,11,11,11,11,11,11,11,11,11,11,11,11, 3,
  142488. 11, 8,11,11,11,11,11,11,11,11,11,11,11,11, 3, 9,
  142489. 9,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  142490. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  142491. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  142492. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  142493. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  142494. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  142495. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  142496. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  142497. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  142498. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  142499. 11,11,11,11,11,11,11,11,11,11,10,10,10,10,10,10,
  142500. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  142501. 10,
  142502. };
  142503. static float _vq_quantthresh__8u1__p9_0[] = {
  142504. -1657.5, -1402.5, -1147.5, -892.5, -637.5, -382.5, -127.5, 127.5,
  142505. 382.5, 637.5, 892.5, 1147.5, 1402.5, 1657.5,
  142506. };
  142507. static long _vq_quantmap__8u1__p9_0[] = {
  142508. 13, 11, 9, 7, 5, 3, 1, 0,
  142509. 2, 4, 6, 8, 10, 12, 14,
  142510. };
  142511. static encode_aux_threshmatch _vq_auxt__8u1__p9_0 = {
  142512. _vq_quantthresh__8u1__p9_0,
  142513. _vq_quantmap__8u1__p9_0,
  142514. 15,
  142515. 15
  142516. };
  142517. static static_codebook _8u1__p9_0 = {
  142518. 2, 225,
  142519. _vq_lengthlist__8u1__p9_0,
  142520. 1, -514071552, 1627381760, 4, 0,
  142521. _vq_quantlist__8u1__p9_0,
  142522. NULL,
  142523. &_vq_auxt__8u1__p9_0,
  142524. NULL,
  142525. 0
  142526. };
  142527. static long _vq_quantlist__8u1__p9_1[] = {
  142528. 7,
  142529. 6,
  142530. 8,
  142531. 5,
  142532. 9,
  142533. 4,
  142534. 10,
  142535. 3,
  142536. 11,
  142537. 2,
  142538. 12,
  142539. 1,
  142540. 13,
  142541. 0,
  142542. 14,
  142543. };
  142544. static long _vq_lengthlist__8u1__p9_1[] = {
  142545. 1, 4, 4, 7, 7, 9, 9, 7, 7, 8, 8,10,10,11,11, 4,
  142546. 7, 7, 9, 9,10,10, 8, 8,10,10,10,11,10,11, 4, 7,
  142547. 7, 9, 9,10,10, 8, 8,10, 9,11,11,11,11, 7, 9, 9,
  142548. 12,12,11,12,10,10,11,10,12,11,11,11, 7, 9, 9,11,
  142549. 11,13,12, 9, 9,11,10,11,11,12,11, 9,10,10,12,12,
  142550. 14,14,10,10,11,12,12,11,11,11, 9,10,11,11,13,14,
  142551. 13,10,11,11,11,12,11,12,12, 7, 8, 8,10, 9,11,10,
  142552. 11,12,12,11,12,14,12,13, 7, 8, 8, 9,10,10,11,12,
  142553. 12,12,11,12,12,12,13, 9, 9, 9,11,11,13,12,12,12,
  142554. 12,11,12,12,13,12, 8,10,10,11,10,11,12,12,12,12,
  142555. 12,12,14,12,12, 9,11,11,11,12,12,12,12,13,13,12,
  142556. 12,13,13,12,10,11,11,12,11,12,12,12,11,12,13,12,
  142557. 12,12,13,11,11,12,12,12,13,12,12,11,12,13,13,12,
  142558. 12,13,12,11,12,12,13,13,12,13,12,13,13,13,13,14,
  142559. 13,
  142560. };
  142561. static float _vq_quantthresh__8u1__p9_1[] = {
  142562. -110.5, -93.5, -76.5, -59.5, -42.5, -25.5, -8.5, 8.5,
  142563. 25.5, 42.5, 59.5, 76.5, 93.5, 110.5,
  142564. };
  142565. static long _vq_quantmap__8u1__p9_1[] = {
  142566. 13, 11, 9, 7, 5, 3, 1, 0,
  142567. 2, 4, 6, 8, 10, 12, 14,
  142568. };
  142569. static encode_aux_threshmatch _vq_auxt__8u1__p9_1 = {
  142570. _vq_quantthresh__8u1__p9_1,
  142571. _vq_quantmap__8u1__p9_1,
  142572. 15,
  142573. 15
  142574. };
  142575. static static_codebook _8u1__p9_1 = {
  142576. 2, 225,
  142577. _vq_lengthlist__8u1__p9_1,
  142578. 1, -522338304, 1620115456, 4, 0,
  142579. _vq_quantlist__8u1__p9_1,
  142580. NULL,
  142581. &_vq_auxt__8u1__p9_1,
  142582. NULL,
  142583. 0
  142584. };
  142585. static long _vq_quantlist__8u1__p9_2[] = {
  142586. 8,
  142587. 7,
  142588. 9,
  142589. 6,
  142590. 10,
  142591. 5,
  142592. 11,
  142593. 4,
  142594. 12,
  142595. 3,
  142596. 13,
  142597. 2,
  142598. 14,
  142599. 1,
  142600. 15,
  142601. 0,
  142602. 16,
  142603. };
  142604. static long _vq_lengthlist__8u1__p9_2[] = {
  142605. 2, 5, 4, 6, 6, 8, 8, 8, 8, 8, 9, 9, 9, 9, 9, 9,
  142606. 9, 5, 6, 6, 7, 7, 8, 8, 9, 8, 9, 9, 9, 9, 9, 9,
  142607. 9, 9, 5, 6, 6, 7, 7, 8, 8, 8, 9, 9, 9, 9, 9, 9,
  142608. 9, 9, 9, 7, 7, 7, 8, 8, 9, 9, 9, 9, 9, 9, 9, 9,
  142609. 9,10,10, 9, 7, 7, 7, 8, 8, 9, 9, 9, 9, 9, 9, 9,
  142610. 9, 9, 9,10,10, 8, 8, 8, 9, 9, 9, 9,10,10,10, 9,
  142611. 10,10,10,10,10,10, 8, 8, 8, 9, 9, 9, 9, 9, 9, 9,
  142612. 10,10,10,10,10,10,10, 9, 9, 9, 9, 9, 9, 9, 9,10,
  142613. 10,10,10,10,10,10,10,10, 9, 9, 9, 9, 9,10,10,10,
  142614. 10,10,10,10,10,10,10,10,10, 9, 9, 9, 9, 9, 9,10,
  142615. 10,10,10,10,10,10,10,10,10,10, 9, 9, 9, 9, 9,10,
  142616. 10,10,10,10,10,10,10,10,10,10,10, 9, 9, 9, 9,10,
  142617. 10,10,10,10,10,10,10,10,10,10,10,10, 9, 9, 9, 9,
  142618. 9,10,10,10,10,10,10,10,10,10,10,10,10, 9, 9, 9,
  142619. 10,10,10,10,10,10,10,10,10,10,10,10,10,10, 9,10,
  142620. 9, 9, 9,10,10,10,10,10,10,10,10,10,10,10,10, 9,
  142621. 10, 9,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  142622. 9, 9,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  142623. 10,
  142624. };
  142625. static float _vq_quantthresh__8u1__p9_2[] = {
  142626. -7.5, -6.5, -5.5, -4.5, -3.5, -2.5, -1.5, -0.5,
  142627. 0.5, 1.5, 2.5, 3.5, 4.5, 5.5, 6.5, 7.5,
  142628. };
  142629. static long _vq_quantmap__8u1__p9_2[] = {
  142630. 15, 13, 11, 9, 7, 5, 3, 1,
  142631. 0, 2, 4, 6, 8, 10, 12, 14,
  142632. 16,
  142633. };
  142634. static encode_aux_threshmatch _vq_auxt__8u1__p9_2 = {
  142635. _vq_quantthresh__8u1__p9_2,
  142636. _vq_quantmap__8u1__p9_2,
  142637. 17,
  142638. 17
  142639. };
  142640. static static_codebook _8u1__p9_2 = {
  142641. 2, 289,
  142642. _vq_lengthlist__8u1__p9_2,
  142643. 1, -529530880, 1611661312, 5, 0,
  142644. _vq_quantlist__8u1__p9_2,
  142645. NULL,
  142646. &_vq_auxt__8u1__p9_2,
  142647. NULL,
  142648. 0
  142649. };
  142650. static long _huff_lengthlist__8u1__single[] = {
  142651. 4, 7,13, 9,15, 9,16, 8,10,13, 7, 5, 8, 6, 9, 7,
  142652. 10, 7,10,11,11, 6, 7, 8, 8, 9, 9, 9,12,16, 8, 5,
  142653. 8, 6, 8, 6, 9, 7,10,12,11, 7, 7, 7, 6, 7, 7, 7,
  142654. 11,15, 7, 5, 8, 6, 7, 5, 7, 6, 9,13,13, 9, 9, 8,
  142655. 6, 6, 5, 5, 9,14, 8, 6, 8, 6, 6, 4, 5, 3, 5,13,
  142656. 9, 9,11, 8,10, 7, 8, 4, 5,12,11,16,17,15,17,12,
  142657. 13, 8, 8,15,
  142658. };
  142659. static static_codebook _huff_book__8u1__single = {
  142660. 2, 100,
  142661. _huff_lengthlist__8u1__single,
  142662. 0, 0, 0, 0, 0,
  142663. NULL,
  142664. NULL,
  142665. NULL,
  142666. NULL,
  142667. 0
  142668. };
  142669. static long _huff_lengthlist__44u0__long[] = {
  142670. 5, 8,13,10,17,11,11,15, 7, 2, 4, 5, 8, 7, 9,16,
  142671. 13, 4, 3, 5, 6, 8,11,20,10, 4, 5, 5, 7, 6, 8,18,
  142672. 15, 7, 6, 7, 8,10,14,20,10, 6, 7, 6, 9, 7, 8,17,
  142673. 9, 8,10, 8,10, 5, 4,11,12,17,19,14,16,10, 7,12,
  142674. };
  142675. static static_codebook _huff_book__44u0__long = {
  142676. 2, 64,
  142677. _huff_lengthlist__44u0__long,
  142678. 0, 0, 0, 0, 0,
  142679. NULL,
  142680. NULL,
  142681. NULL,
  142682. NULL,
  142683. 0
  142684. };
  142685. static long _vq_quantlist__44u0__p1_0[] = {
  142686. 1,
  142687. 0,
  142688. 2,
  142689. };
  142690. static long _vq_lengthlist__44u0__p1_0[] = {
  142691. 1, 4, 4, 5, 8, 7, 5, 7, 8, 5, 8, 8, 8,11,11, 8,
  142692. 10,10, 5, 8, 8, 8,11,10, 8,11,11, 4, 8, 8, 8,11,
  142693. 11, 8,11,11, 8,12,11,11,13,13,11,13,14, 7,11,11,
  142694. 10,13,12,11,13,14, 4, 8, 8, 8,11,11, 8,11,12, 8,
  142695. 11,11,11,13,13,10,12,13, 8,11,11,11,14,13,11,14,
  142696. 13,
  142697. };
  142698. static float _vq_quantthresh__44u0__p1_0[] = {
  142699. -0.5, 0.5,
  142700. };
  142701. static long _vq_quantmap__44u0__p1_0[] = {
  142702. 1, 0, 2,
  142703. };
  142704. static encode_aux_threshmatch _vq_auxt__44u0__p1_0 = {
  142705. _vq_quantthresh__44u0__p1_0,
  142706. _vq_quantmap__44u0__p1_0,
  142707. 3,
  142708. 3
  142709. };
  142710. static static_codebook _44u0__p1_0 = {
  142711. 4, 81,
  142712. _vq_lengthlist__44u0__p1_0,
  142713. 1, -535822336, 1611661312, 2, 0,
  142714. _vq_quantlist__44u0__p1_0,
  142715. NULL,
  142716. &_vq_auxt__44u0__p1_0,
  142717. NULL,
  142718. 0
  142719. };
  142720. static long _vq_quantlist__44u0__p2_0[] = {
  142721. 1,
  142722. 0,
  142723. 2,
  142724. };
  142725. static long _vq_lengthlist__44u0__p2_0[] = {
  142726. 2, 4, 4, 5, 6, 6, 5, 6, 6, 5, 7, 7, 7, 8, 8, 6,
  142727. 8, 8, 5, 7, 7, 6, 8, 8, 7, 8, 8, 4, 7, 7, 7, 8,
  142728. 8, 7, 8, 8, 7, 8, 8, 8, 9,10, 8,10,10, 6, 8, 8,
  142729. 8,10, 8, 8,10,10, 5, 7, 7, 7, 8, 8, 7, 8, 8, 6,
  142730. 8, 8, 8,10,10, 8, 8,10, 6, 8, 8, 8,10,10, 8,10,
  142731. 9,
  142732. };
  142733. static float _vq_quantthresh__44u0__p2_0[] = {
  142734. -0.5, 0.5,
  142735. };
  142736. static long _vq_quantmap__44u0__p2_0[] = {
  142737. 1, 0, 2,
  142738. };
  142739. static encode_aux_threshmatch _vq_auxt__44u0__p2_0 = {
  142740. _vq_quantthresh__44u0__p2_0,
  142741. _vq_quantmap__44u0__p2_0,
  142742. 3,
  142743. 3
  142744. };
  142745. static static_codebook _44u0__p2_0 = {
  142746. 4, 81,
  142747. _vq_lengthlist__44u0__p2_0,
  142748. 1, -535822336, 1611661312, 2, 0,
  142749. _vq_quantlist__44u0__p2_0,
  142750. NULL,
  142751. &_vq_auxt__44u0__p2_0,
  142752. NULL,
  142753. 0
  142754. };
  142755. static long _vq_quantlist__44u0__p3_0[] = {
  142756. 2,
  142757. 1,
  142758. 3,
  142759. 0,
  142760. 4,
  142761. };
  142762. static long _vq_lengthlist__44u0__p3_0[] = {
  142763. 1, 5, 5, 8, 8, 5, 8, 7, 9, 9, 5, 7, 8, 9, 9, 9,
  142764. 10, 9,12,12, 9, 9,10,12,12, 6, 8, 8,11,10, 8,10,
  142765. 10,11,11, 8, 9,10,11,11,10,11,11,14,13,10,11,11,
  142766. 13,13, 5, 8, 8,10,10, 8,10,10,11,11, 8,10,10,11,
  142767. 11,10,11,11,13,13,10,11,11,13,13, 9,11,11,15,14,
  142768. 10,12,12,15,14,10,12,11,15,14,13,14,14,16,16,12,
  142769. 14,13,17,15, 9,11,11,14,15,10,11,12,14,16,10,11,
  142770. 12,14,16,12,13,14,16,16,13,13,15,15,18, 5, 8, 8,
  142771. 11,11, 8,10,10,12,12, 8,10,10,12,13,11,12,12,14,
  142772. 14,11,12,12,15,15, 8,10,10,13,13,10,12,12,13,13,
  142773. 10,12,12,14,14,12,13,13,15,15,12,13,13,16,16, 7,
  142774. 10,10,12,12,10,12,11,13,13,10,12,12,13,14,12,13,
  142775. 12,15,14,12,13,13,16,16,10,12,12,17,16,12,13,13,
  142776. 16,15,11,13,13,17,17,15,15,15,16,17,14,15,15,19,
  142777. 19,10,12,12,15,16,11,13,12,15,18,11,13,13,16,16,
  142778. 14,15,15,17,17,14,15,15,17,19, 5, 8, 8,11,11, 8,
  142779. 10,10,12,12, 8,10,10,12,12,11,12,12,16,15,11,12,
  142780. 12,14,15, 7,10,10,13,13,10,12,12,14,13,10,11,12,
  142781. 13,13,12,13,13,16,16,12,12,13,15,15, 8,10,10,13,
  142782. 13,10,12,12,14,14,10,12,12,13,13,12,13,13,16,16,
  142783. 12,13,13,15,15,10,12,12,16,15,11,13,13,17,16,11,
  142784. 12,13,16,15,13,15,15,19,17,14,15,14,17,16,10,12,
  142785. 12,16,16,11,13,13,16,17,12,13,13,15,17,14,15,15,
  142786. 17,19,14,15,15,17,17, 8,11,11,16,16,10,13,12,17,
  142787. 17,10,12,13,16,16,15,17,16,20,19,14,15,17,18,19,
  142788. 9,12,12,16,17,11,13,14,17,18,11,13,13,19,18,16,
  142789. 17,18,19,19,15,16,16,19,19, 9,12,12,16,17,11,14,
  142790. 13,18,17,11,13,13,17,17,16,17,16,20,19,14,16,16,
  142791. 18,18,12,15,15,19,17,14,15,16, 0,20,13,15,16,20,
  142792. 17,18,16,20, 0, 0,15,16,19,20, 0,12,15,14,18,19,
  142793. 13,16,15,20,19,13,16,15,20,18,17,18,17, 0,20,16,
  142794. 17,16, 0, 0, 8,11,11,16,15,10,12,12,17,17,10,13,
  142795. 13,17,16,14,16,15,18,20,15,16,16,19,19, 9,12,12,
  142796. 16,16,11,13,13,17,16,11,13,14,17,18,15,15,16,20,
  142797. 20,16,16,17,19,19, 9,13,12,16,17,11,14,13,17,17,
  142798. 11,14,14,18,17,14,16,15,18,19,16,17,18,18,19,12,
  142799. 14,15,19,18,13,15,16,18, 0,13,14,15, 0, 0,16,16,
  142800. 17,20, 0,17,17,20,20, 0,12,15,15,19,20,13,15,15,
  142801. 0, 0,14,16,15, 0, 0,15,18,16, 0, 0,17,18,16, 0,
  142802. 19,
  142803. };
  142804. static float _vq_quantthresh__44u0__p3_0[] = {
  142805. -1.5, -0.5, 0.5, 1.5,
  142806. };
  142807. static long _vq_quantmap__44u0__p3_0[] = {
  142808. 3, 1, 0, 2, 4,
  142809. };
  142810. static encode_aux_threshmatch _vq_auxt__44u0__p3_0 = {
  142811. _vq_quantthresh__44u0__p3_0,
  142812. _vq_quantmap__44u0__p3_0,
  142813. 5,
  142814. 5
  142815. };
  142816. static static_codebook _44u0__p3_0 = {
  142817. 4, 625,
  142818. _vq_lengthlist__44u0__p3_0,
  142819. 1, -533725184, 1611661312, 3, 0,
  142820. _vq_quantlist__44u0__p3_0,
  142821. NULL,
  142822. &_vq_auxt__44u0__p3_0,
  142823. NULL,
  142824. 0
  142825. };
  142826. static long _vq_quantlist__44u0__p4_0[] = {
  142827. 2,
  142828. 1,
  142829. 3,
  142830. 0,
  142831. 4,
  142832. };
  142833. static long _vq_lengthlist__44u0__p4_0[] = {
  142834. 4, 5, 5, 9, 9, 5, 6, 6, 9, 9, 5, 6, 6, 9, 9, 9,
  142835. 10, 9,12,12, 9, 9,10,12,12, 5, 7, 7,10,10, 7, 7,
  142836. 8,10,10, 6, 7, 8,10,10,10,10,10,11,13,10, 9,10,
  142837. 12,13, 5, 7, 7,10,10, 6, 8, 7,10,10, 7, 8, 7,10,
  142838. 10, 9,10,10,12,12,10,10,10,13,11, 9,10,10,13,13,
  142839. 10,11,10,13,13,10,10,10,13,13,12,12,13,14,14,12,
  142840. 12,13,14,14, 9,10,10,13,13,10,10,10,13,13,10,10,
  142841. 10,13,13,12,13,12,15,14,12,13,12,15,15, 5, 7, 6,
  142842. 10,10, 7, 8, 8,10,10, 7, 8, 8,10,10,10,11,10,13,
  142843. 13,10,10,10,12,12, 7, 8, 8,11,10, 8, 8, 9,10,11,
  142844. 8, 9, 9,11,11,11,10,11,11,14,11,11,11,13,13, 6,
  142845. 8, 8,10,10, 7, 9, 8,11,10, 8, 9, 9,11,11,10,11,
  142846. 10,14,11,10,11,11,13,13,10,11,11,14,13,10,10,11,
  142847. 14,13,10,11,11,14,14,12,11,13,12,16,13,14,14,15,
  142848. 15,10,10,11,13,14,10,11,10,14,13,10,11,11,14,14,
  142849. 12,13,12,15,13,13,13,14,15,16, 5, 7, 7,10,10, 7,
  142850. 8, 8,10,10, 7, 8, 8,10,10,10,10,10,13,13,10,10,
  142851. 11,12,13, 6, 8, 8,11,10, 8, 9, 9,11,11, 7, 8, 9,
  142852. 10,11,10,11,11,13,13,10,10,11,11,13, 6, 8, 8,10,
  142853. 11, 8, 9, 9,11,11, 8, 9, 8,12,10,10,11,11,13,13,
  142854. 10,11,10,14,11,10,10,10,14,13,10,11,11,14,13,10,
  142855. 10,11,13,13,12,14,14,16,16,12,12,13,13,15,10,11,
  142856. 11,13,14,10,11,11,14,15,10,11,10,13,13,13,14,13,
  142857. 16,16,12,13,11,15,12, 9,10,10,13,13,10,11,11,14,
  142858. 13,10,10,11,13,14,13,14,13,16,16,13,13,13,15,16,
  142859. 9,10,10,13,13,10,10,11,13,14,10,11,11,15,13,13,
  142860. 13,14,14,18,13,13,14,16,15, 9,10,10,13,14,10,11,
  142861. 10,14,13,10,11,11,13,14,13,14,13,16,15,13,13,14,
  142862. 15,16,12,13,12,16,14,11,11,13,15,15,13,14,13,16,
  142863. 15,15,12,16,12,17,14,15,15,17,17,12,13,13,14,16,
  142864. 11,13,11,16,15,12,13,14,15,16,14,15,13, 0,14,14,
  142865. 16,16, 0, 0, 9,10,10,13,13,10,11,10,14,14,10,11,
  142866. 11,13,13,12,13,13,14,16,13,14,14,16,16, 9,10,10,
  142867. 14,14,11,11,11,14,13,10,10,11,14,14,13,13,13,16,
  142868. 16,13,13,14,14,17, 9,10,10,13,14,10,11,11,13,15,
  142869. 10,11,10,14,14,13,13,13,14,17,13,14,13,17,14,12,
  142870. 13,13,16,14,13,14,13,16,15,12,12,13,15,16,15,15,
  142871. 16,18,16,15,13,15,14, 0,12,12,13,14,16,13,13,14,
  142872. 15,16,11,12,11,16,14,15,16,16,17,17,14,15,12,17,
  142873. 12,
  142874. };
  142875. static float _vq_quantthresh__44u0__p4_0[] = {
  142876. -1.5, -0.5, 0.5, 1.5,
  142877. };
  142878. static long _vq_quantmap__44u0__p4_0[] = {
  142879. 3, 1, 0, 2, 4,
  142880. };
  142881. static encode_aux_threshmatch _vq_auxt__44u0__p4_0 = {
  142882. _vq_quantthresh__44u0__p4_0,
  142883. _vq_quantmap__44u0__p4_0,
  142884. 5,
  142885. 5
  142886. };
  142887. static static_codebook _44u0__p4_0 = {
  142888. 4, 625,
  142889. _vq_lengthlist__44u0__p4_0,
  142890. 1, -533725184, 1611661312, 3, 0,
  142891. _vq_quantlist__44u0__p4_0,
  142892. NULL,
  142893. &_vq_auxt__44u0__p4_0,
  142894. NULL,
  142895. 0
  142896. };
  142897. static long _vq_quantlist__44u0__p5_0[] = {
  142898. 4,
  142899. 3,
  142900. 5,
  142901. 2,
  142902. 6,
  142903. 1,
  142904. 7,
  142905. 0,
  142906. 8,
  142907. };
  142908. static long _vq_lengthlist__44u0__p5_0[] = {
  142909. 1, 4, 4, 7, 7, 7, 7, 9, 9, 4, 6, 6, 8, 8, 8, 8,
  142910. 9, 9, 4, 6, 6, 8, 8, 8, 8, 9, 9, 7, 8, 8, 9, 9,
  142911. 9, 9,11,10, 7, 8, 8, 9, 9, 9, 9,10,10, 7, 8, 8,
  142912. 9, 9,10,10,11,11, 7, 8, 8, 9, 9,10,10,11,11, 9,
  142913. 9, 9,10,10,11,11,12,12, 9, 9, 9,10,11,11,11,12,
  142914. 12,
  142915. };
  142916. static float _vq_quantthresh__44u0__p5_0[] = {
  142917. -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5, 3.5,
  142918. };
  142919. static long _vq_quantmap__44u0__p5_0[] = {
  142920. 7, 5, 3, 1, 0, 2, 4, 6,
  142921. 8,
  142922. };
  142923. static encode_aux_threshmatch _vq_auxt__44u0__p5_0 = {
  142924. _vq_quantthresh__44u0__p5_0,
  142925. _vq_quantmap__44u0__p5_0,
  142926. 9,
  142927. 9
  142928. };
  142929. static static_codebook _44u0__p5_0 = {
  142930. 2, 81,
  142931. _vq_lengthlist__44u0__p5_0,
  142932. 1, -531628032, 1611661312, 4, 0,
  142933. _vq_quantlist__44u0__p5_0,
  142934. NULL,
  142935. &_vq_auxt__44u0__p5_0,
  142936. NULL,
  142937. 0
  142938. };
  142939. static long _vq_quantlist__44u0__p6_0[] = {
  142940. 6,
  142941. 5,
  142942. 7,
  142943. 4,
  142944. 8,
  142945. 3,
  142946. 9,
  142947. 2,
  142948. 10,
  142949. 1,
  142950. 11,
  142951. 0,
  142952. 12,
  142953. };
  142954. static long _vq_lengthlist__44u0__p6_0[] = {
  142955. 1, 4, 4, 6, 6, 8, 8,10, 9,11,10,14,13, 4, 6, 5,
  142956. 8, 8, 9, 9,11,10,11,11,14,14, 4, 5, 6, 8, 8, 9,
  142957. 9,10,10,11,11,14,14, 6, 8, 8, 9, 9,10,10,11,11,
  142958. 12,12,16,15, 7, 8, 8, 9, 9,10,10,11,11,12,12,15,
  142959. 15, 9,10,10,10,10,11,11,12,12,12,12,15,15, 9,10,
  142960. 9,10,11,11,11,12,12,12,13,15,15,10,10,11,11,11,
  142961. 12,12,13,12,13,13,16,15,10,11,11,11,11,12,12,13,
  142962. 12,13,13,16,17,11,11,12,12,12,13,13,13,14,14,15,
  142963. 17,17,11,11,12,12,12,13,13,13,14,14,14,16,18,14,
  142964. 15,15,15,15,16,16,16,16,17,18, 0, 0,14,15,15,15,
  142965. 15,17,16,17,18,17,17,18, 0,
  142966. };
  142967. static float _vq_quantthresh__44u0__p6_0[] = {
  142968. -27.5, -22.5, -17.5, -12.5, -7.5, -2.5, 2.5, 7.5,
  142969. 12.5, 17.5, 22.5, 27.5,
  142970. };
  142971. static long _vq_quantmap__44u0__p6_0[] = {
  142972. 11, 9, 7, 5, 3, 1, 0, 2,
  142973. 4, 6, 8, 10, 12,
  142974. };
  142975. static encode_aux_threshmatch _vq_auxt__44u0__p6_0 = {
  142976. _vq_quantthresh__44u0__p6_0,
  142977. _vq_quantmap__44u0__p6_0,
  142978. 13,
  142979. 13
  142980. };
  142981. static static_codebook _44u0__p6_0 = {
  142982. 2, 169,
  142983. _vq_lengthlist__44u0__p6_0,
  142984. 1, -526516224, 1616117760, 4, 0,
  142985. _vq_quantlist__44u0__p6_0,
  142986. NULL,
  142987. &_vq_auxt__44u0__p6_0,
  142988. NULL,
  142989. 0
  142990. };
  142991. static long _vq_quantlist__44u0__p6_1[] = {
  142992. 2,
  142993. 1,
  142994. 3,
  142995. 0,
  142996. 4,
  142997. };
  142998. static long _vq_lengthlist__44u0__p6_1[] = {
  142999. 2, 4, 4, 5, 5, 4, 5, 5, 5, 5, 4, 5, 5, 5, 5, 5,
  143000. 6, 6, 6, 6, 5, 6, 6, 6, 6,
  143001. };
  143002. static float _vq_quantthresh__44u0__p6_1[] = {
  143003. -1.5, -0.5, 0.5, 1.5,
  143004. };
  143005. static long _vq_quantmap__44u0__p6_1[] = {
  143006. 3, 1, 0, 2, 4,
  143007. };
  143008. static encode_aux_threshmatch _vq_auxt__44u0__p6_1 = {
  143009. _vq_quantthresh__44u0__p6_1,
  143010. _vq_quantmap__44u0__p6_1,
  143011. 5,
  143012. 5
  143013. };
  143014. static static_codebook _44u0__p6_1 = {
  143015. 2, 25,
  143016. _vq_lengthlist__44u0__p6_1,
  143017. 1, -533725184, 1611661312, 3, 0,
  143018. _vq_quantlist__44u0__p6_1,
  143019. NULL,
  143020. &_vq_auxt__44u0__p6_1,
  143021. NULL,
  143022. 0
  143023. };
  143024. static long _vq_quantlist__44u0__p7_0[] = {
  143025. 2,
  143026. 1,
  143027. 3,
  143028. 0,
  143029. 4,
  143030. };
  143031. static long _vq_lengthlist__44u0__p7_0[] = {
  143032. 1, 4, 4,11,11, 9,11,11,11,11,11,11,11,11,11,11,
  143033. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  143034. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  143035. 11,11, 9,11,11,11,11,11,11,11,11,11,11,11,11,11,
  143036. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  143037. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  143038. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  143039. 11,11,11,11,11,11,11,11,11,11,11,11,11,10,11,11,
  143040. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  143041. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  143042. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  143043. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  143044. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  143045. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  143046. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  143047. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  143048. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  143049. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  143050. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  143051. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  143052. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  143053. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  143054. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  143055. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  143056. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  143057. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  143058. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  143059. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  143060. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  143061. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  143062. 11,11,11,11,11,11,10,10,10,10,10,10,10,10,10,10,
  143063. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  143064. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  143065. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  143066. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  143067. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  143068. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  143069. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  143070. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  143071. 10,
  143072. };
  143073. static float _vq_quantthresh__44u0__p7_0[] = {
  143074. -253.5, -84.5, 84.5, 253.5,
  143075. };
  143076. static long _vq_quantmap__44u0__p7_0[] = {
  143077. 3, 1, 0, 2, 4,
  143078. };
  143079. static encode_aux_threshmatch _vq_auxt__44u0__p7_0 = {
  143080. _vq_quantthresh__44u0__p7_0,
  143081. _vq_quantmap__44u0__p7_0,
  143082. 5,
  143083. 5
  143084. };
  143085. static static_codebook _44u0__p7_0 = {
  143086. 4, 625,
  143087. _vq_lengthlist__44u0__p7_0,
  143088. 1, -518709248, 1626677248, 3, 0,
  143089. _vq_quantlist__44u0__p7_0,
  143090. NULL,
  143091. &_vq_auxt__44u0__p7_0,
  143092. NULL,
  143093. 0
  143094. };
  143095. static long _vq_quantlist__44u0__p7_1[] = {
  143096. 6,
  143097. 5,
  143098. 7,
  143099. 4,
  143100. 8,
  143101. 3,
  143102. 9,
  143103. 2,
  143104. 10,
  143105. 1,
  143106. 11,
  143107. 0,
  143108. 12,
  143109. };
  143110. static long _vq_lengthlist__44u0__p7_1[] = {
  143111. 1, 4, 4, 6, 6, 6, 6, 7, 7, 8, 8, 9, 9, 5, 7, 7,
  143112. 8, 7, 7, 7, 9, 8,10, 9,10,11, 5, 7, 7, 8, 8, 7,
  143113. 7, 8, 9,10,10,11,11, 6, 8, 8, 9, 9, 9, 9,11,10,
  143114. 12,12,15,12, 6, 8, 8, 9, 9, 9, 9,11,11,12,11,14,
  143115. 12, 7, 8, 8,10,10,12,12,13,13,13,15,13,13, 7, 8,
  143116. 8,10,10,11,11,13,12,14,15,15,15, 9,10,10,11,12,
  143117. 13,13,14,15,14,15,14,15, 8,10,10,12,12,14,14,15,
  143118. 14,14,15,15,14,10,12,12,14,14,15,14,15,15,15,14,
  143119. 15,15,10,12,12,13,14,15,14,15,15,14,15,15,15,12,
  143120. 15,13,15,14,15,15,15,15,15,15,15,15,13,13,15,15,
  143121. 15,15,15,15,15,15,15,15,15,
  143122. };
  143123. static float _vq_quantthresh__44u0__p7_1[] = {
  143124. -71.5, -58.5, -45.5, -32.5, -19.5, -6.5, 6.5, 19.5,
  143125. 32.5, 45.5, 58.5, 71.5,
  143126. };
  143127. static long _vq_quantmap__44u0__p7_1[] = {
  143128. 11, 9, 7, 5, 3, 1, 0, 2,
  143129. 4, 6, 8, 10, 12,
  143130. };
  143131. static encode_aux_threshmatch _vq_auxt__44u0__p7_1 = {
  143132. _vq_quantthresh__44u0__p7_1,
  143133. _vq_quantmap__44u0__p7_1,
  143134. 13,
  143135. 13
  143136. };
  143137. static static_codebook _44u0__p7_1 = {
  143138. 2, 169,
  143139. _vq_lengthlist__44u0__p7_1,
  143140. 1, -523010048, 1618608128, 4, 0,
  143141. _vq_quantlist__44u0__p7_1,
  143142. NULL,
  143143. &_vq_auxt__44u0__p7_1,
  143144. NULL,
  143145. 0
  143146. };
  143147. static long _vq_quantlist__44u0__p7_2[] = {
  143148. 6,
  143149. 5,
  143150. 7,
  143151. 4,
  143152. 8,
  143153. 3,
  143154. 9,
  143155. 2,
  143156. 10,
  143157. 1,
  143158. 11,
  143159. 0,
  143160. 12,
  143161. };
  143162. static long _vq_lengthlist__44u0__p7_2[] = {
  143163. 2, 5, 4, 6, 6, 7, 7, 8, 8, 8, 8, 9, 8, 5, 5, 6,
  143164. 7, 7, 8, 8, 8, 8, 9, 9, 9, 9, 5, 6, 5, 7, 7, 8,
  143165. 8, 8, 8, 9, 9, 9, 9, 6, 7, 7, 8, 8, 8, 8, 9, 8,
  143166. 9, 9, 9, 9, 6, 7, 7, 8, 7, 8, 8, 9, 9, 9, 9, 9,
  143167. 9, 7, 8, 8, 8, 8, 9, 9, 9, 9, 9, 9, 9, 9, 7, 8,
  143168. 8, 9, 8, 9, 8, 9, 9, 9, 9, 9, 9, 8, 9, 8, 9, 9,
  143169. 9, 9, 9, 9, 9, 9,10,10, 8, 8, 9, 9, 9, 9, 9, 9,
  143170. 9, 9,10, 9,10, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,
  143171. 9, 9, 8, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,
  143172. 9, 9, 9, 9, 9, 9, 9, 9,10,10,10, 9, 9, 9, 9, 9,
  143173. 9, 9, 9,10, 9, 9,10,10, 9,
  143174. };
  143175. static float _vq_quantthresh__44u0__p7_2[] = {
  143176. -5.5, -4.5, -3.5, -2.5, -1.5, -0.5, 0.5, 1.5,
  143177. 2.5, 3.5, 4.5, 5.5,
  143178. };
  143179. static long _vq_quantmap__44u0__p7_2[] = {
  143180. 11, 9, 7, 5, 3, 1, 0, 2,
  143181. 4, 6, 8, 10, 12,
  143182. };
  143183. static encode_aux_threshmatch _vq_auxt__44u0__p7_2 = {
  143184. _vq_quantthresh__44u0__p7_2,
  143185. _vq_quantmap__44u0__p7_2,
  143186. 13,
  143187. 13
  143188. };
  143189. static static_codebook _44u0__p7_2 = {
  143190. 2, 169,
  143191. _vq_lengthlist__44u0__p7_2,
  143192. 1, -531103744, 1611661312, 4, 0,
  143193. _vq_quantlist__44u0__p7_2,
  143194. NULL,
  143195. &_vq_auxt__44u0__p7_2,
  143196. NULL,
  143197. 0
  143198. };
  143199. static long _huff_lengthlist__44u0__short[] = {
  143200. 12,13,14,13,17,12,15,17, 5, 5, 6,10,10,11,15,16,
  143201. 4, 3, 3, 7, 5, 7,10,16, 7, 7, 7,10, 9,11,12,16,
  143202. 6, 5, 5, 9, 5, 6,10,16, 8, 7, 7, 9, 6, 7, 9,16,
  143203. 11, 7, 3, 6, 4, 5, 8,16,12, 9, 4, 8, 5, 7, 9,16,
  143204. };
  143205. static static_codebook _huff_book__44u0__short = {
  143206. 2, 64,
  143207. _huff_lengthlist__44u0__short,
  143208. 0, 0, 0, 0, 0,
  143209. NULL,
  143210. NULL,
  143211. NULL,
  143212. NULL,
  143213. 0
  143214. };
  143215. static long _huff_lengthlist__44u1__long[] = {
  143216. 5, 8,13,10,17,11,11,15, 7, 2, 4, 5, 8, 7, 9,16,
  143217. 13, 4, 3, 5, 6, 8,11,20,10, 4, 5, 5, 7, 6, 8,18,
  143218. 15, 7, 6, 7, 8,10,14,20,10, 6, 7, 6, 9, 7, 8,17,
  143219. 9, 8,10, 8,10, 5, 4,11,12,17,19,14,16,10, 7,12,
  143220. };
  143221. static static_codebook _huff_book__44u1__long = {
  143222. 2, 64,
  143223. _huff_lengthlist__44u1__long,
  143224. 0, 0, 0, 0, 0,
  143225. NULL,
  143226. NULL,
  143227. NULL,
  143228. NULL,
  143229. 0
  143230. };
  143231. static long _vq_quantlist__44u1__p1_0[] = {
  143232. 1,
  143233. 0,
  143234. 2,
  143235. };
  143236. static long _vq_lengthlist__44u1__p1_0[] = {
  143237. 1, 4, 4, 5, 8, 7, 5, 7, 8, 5, 8, 8, 8,11,11, 8,
  143238. 10,10, 5, 8, 8, 8,11,10, 8,11,11, 4, 8, 8, 8,11,
  143239. 11, 8,11,11, 8,12,11,11,13,13,11,13,14, 7,11,11,
  143240. 10,13,12,11,13,14, 4, 8, 8, 8,11,11, 8,11,12, 8,
  143241. 11,11,11,13,13,10,12,13, 8,11,11,11,14,13,11,14,
  143242. 13,
  143243. };
  143244. static float _vq_quantthresh__44u1__p1_0[] = {
  143245. -0.5, 0.5,
  143246. };
  143247. static long _vq_quantmap__44u1__p1_0[] = {
  143248. 1, 0, 2,
  143249. };
  143250. static encode_aux_threshmatch _vq_auxt__44u1__p1_0 = {
  143251. _vq_quantthresh__44u1__p1_0,
  143252. _vq_quantmap__44u1__p1_0,
  143253. 3,
  143254. 3
  143255. };
  143256. static static_codebook _44u1__p1_0 = {
  143257. 4, 81,
  143258. _vq_lengthlist__44u1__p1_0,
  143259. 1, -535822336, 1611661312, 2, 0,
  143260. _vq_quantlist__44u1__p1_0,
  143261. NULL,
  143262. &_vq_auxt__44u1__p1_0,
  143263. NULL,
  143264. 0
  143265. };
  143266. static long _vq_quantlist__44u1__p2_0[] = {
  143267. 1,
  143268. 0,
  143269. 2,
  143270. };
  143271. static long _vq_lengthlist__44u1__p2_0[] = {
  143272. 2, 4, 4, 5, 6, 6, 5, 6, 6, 5, 7, 7, 7, 8, 8, 6,
  143273. 8, 8, 5, 7, 7, 6, 8, 8, 7, 8, 8, 4, 7, 7, 7, 8,
  143274. 8, 7, 8, 8, 7, 8, 8, 8, 9,10, 8,10,10, 6, 8, 8,
  143275. 8,10, 8, 8,10,10, 5, 7, 7, 7, 8, 8, 7, 8, 8, 6,
  143276. 8, 8, 8,10,10, 8, 8,10, 6, 8, 8, 8,10,10, 8,10,
  143277. 9,
  143278. };
  143279. static float _vq_quantthresh__44u1__p2_0[] = {
  143280. -0.5, 0.5,
  143281. };
  143282. static long _vq_quantmap__44u1__p2_0[] = {
  143283. 1, 0, 2,
  143284. };
  143285. static encode_aux_threshmatch _vq_auxt__44u1__p2_0 = {
  143286. _vq_quantthresh__44u1__p2_0,
  143287. _vq_quantmap__44u1__p2_0,
  143288. 3,
  143289. 3
  143290. };
  143291. static static_codebook _44u1__p2_0 = {
  143292. 4, 81,
  143293. _vq_lengthlist__44u1__p2_0,
  143294. 1, -535822336, 1611661312, 2, 0,
  143295. _vq_quantlist__44u1__p2_0,
  143296. NULL,
  143297. &_vq_auxt__44u1__p2_0,
  143298. NULL,
  143299. 0
  143300. };
  143301. static long _vq_quantlist__44u1__p3_0[] = {
  143302. 2,
  143303. 1,
  143304. 3,
  143305. 0,
  143306. 4,
  143307. };
  143308. static long _vq_lengthlist__44u1__p3_0[] = {
  143309. 1, 5, 5, 8, 8, 5, 8, 7, 9, 9, 5, 7, 8, 9, 9, 9,
  143310. 10, 9,12,12, 9, 9,10,12,12, 6, 8, 8,11,10, 8,10,
  143311. 10,11,11, 8, 9,10,11,11,10,11,11,14,13,10,11,11,
  143312. 13,13, 5, 8, 8,10,10, 8,10,10,11,11, 8,10,10,11,
  143313. 11,10,11,11,13,13,10,11,11,13,13, 9,11,11,15,14,
  143314. 10,12,12,15,14,10,12,11,15,14,13,14,14,16,16,12,
  143315. 14,13,17,15, 9,11,11,14,15,10,11,12,14,16,10,11,
  143316. 12,14,16,12,13,14,16,16,13,13,15,15,18, 5, 8, 8,
  143317. 11,11, 8,10,10,12,12, 8,10,10,12,13,11,12,12,14,
  143318. 14,11,12,12,15,15, 8,10,10,13,13,10,12,12,13,13,
  143319. 10,12,12,14,14,12,13,13,15,15,12,13,13,16,16, 7,
  143320. 10,10,12,12,10,12,11,13,13,10,12,12,13,14,12,13,
  143321. 12,15,14,12,13,13,16,16,10,12,12,17,16,12,13,13,
  143322. 16,15,11,13,13,17,17,15,15,15,16,17,14,15,15,19,
  143323. 19,10,12,12,15,16,11,13,12,15,18,11,13,13,16,16,
  143324. 14,15,15,17,17,14,15,15,17,19, 5, 8, 8,11,11, 8,
  143325. 10,10,12,12, 8,10,10,12,12,11,12,12,16,15,11,12,
  143326. 12,14,15, 7,10,10,13,13,10,12,12,14,13,10,11,12,
  143327. 13,13,12,13,13,16,16,12,12,13,15,15, 8,10,10,13,
  143328. 13,10,12,12,14,14,10,12,12,13,13,12,13,13,16,16,
  143329. 12,13,13,15,15,10,12,12,16,15,11,13,13,17,16,11,
  143330. 12,13,16,15,13,15,15,19,17,14,15,14,17,16,10,12,
  143331. 12,16,16,11,13,13,16,17,12,13,13,15,17,14,15,15,
  143332. 17,19,14,15,15,17,17, 8,11,11,16,16,10,13,12,17,
  143333. 17,10,12,13,16,16,15,17,16,20,19,14,15,17,18,19,
  143334. 9,12,12,16,17,11,13,14,17,18,11,13,13,19,18,16,
  143335. 17,18,19,19,15,16,16,19,19, 9,12,12,16,17,11,14,
  143336. 13,18,17,11,13,13,17,17,16,17,16,20,19,14,16,16,
  143337. 18,18,12,15,15,19,17,14,15,16, 0,20,13,15,16,20,
  143338. 17,18,16,20, 0, 0,15,16,19,20, 0,12,15,14,18,19,
  143339. 13,16,15,20,19,13,16,15,20,18,17,18,17, 0,20,16,
  143340. 17,16, 0, 0, 8,11,11,16,15,10,12,12,17,17,10,13,
  143341. 13,17,16,14,16,15,18,20,15,16,16,19,19, 9,12,12,
  143342. 16,16,11,13,13,17,16,11,13,14,17,18,15,15,16,20,
  143343. 20,16,16,17,19,19, 9,13,12,16,17,11,14,13,17,17,
  143344. 11,14,14,18,17,14,16,15,18,19,16,17,18,18,19,12,
  143345. 14,15,19,18,13,15,16,18, 0,13,14,15, 0, 0,16,16,
  143346. 17,20, 0,17,17,20,20, 0,12,15,15,19,20,13,15,15,
  143347. 0, 0,14,16,15, 0, 0,15,18,16, 0, 0,17,18,16, 0,
  143348. 19,
  143349. };
  143350. static float _vq_quantthresh__44u1__p3_0[] = {
  143351. -1.5, -0.5, 0.5, 1.5,
  143352. };
  143353. static long _vq_quantmap__44u1__p3_0[] = {
  143354. 3, 1, 0, 2, 4,
  143355. };
  143356. static encode_aux_threshmatch _vq_auxt__44u1__p3_0 = {
  143357. _vq_quantthresh__44u1__p3_0,
  143358. _vq_quantmap__44u1__p3_0,
  143359. 5,
  143360. 5
  143361. };
  143362. static static_codebook _44u1__p3_0 = {
  143363. 4, 625,
  143364. _vq_lengthlist__44u1__p3_0,
  143365. 1, -533725184, 1611661312, 3, 0,
  143366. _vq_quantlist__44u1__p3_0,
  143367. NULL,
  143368. &_vq_auxt__44u1__p3_0,
  143369. NULL,
  143370. 0
  143371. };
  143372. static long _vq_quantlist__44u1__p4_0[] = {
  143373. 2,
  143374. 1,
  143375. 3,
  143376. 0,
  143377. 4,
  143378. };
  143379. static long _vq_lengthlist__44u1__p4_0[] = {
  143380. 4, 5, 5, 9, 9, 5, 6, 6, 9, 9, 5, 6, 6, 9, 9, 9,
  143381. 10, 9,12,12, 9, 9,10,12,12, 5, 7, 7,10,10, 7, 7,
  143382. 8,10,10, 6, 7, 8,10,10,10,10,10,11,13,10, 9,10,
  143383. 12,13, 5, 7, 7,10,10, 6, 8, 7,10,10, 7, 8, 7,10,
  143384. 10, 9,10,10,12,12,10,10,10,13,11, 9,10,10,13,13,
  143385. 10,11,10,13,13,10,10,10,13,13,12,12,13,14,14,12,
  143386. 12,13,14,14, 9,10,10,13,13,10,10,10,13,13,10,10,
  143387. 10,13,13,12,13,12,15,14,12,13,12,15,15, 5, 7, 6,
  143388. 10,10, 7, 8, 8,10,10, 7, 8, 8,10,10,10,11,10,13,
  143389. 13,10,10,10,12,12, 7, 8, 8,11,10, 8, 8, 9,10,11,
  143390. 8, 9, 9,11,11,11,10,11,11,14,11,11,11,13,13, 6,
  143391. 8, 8,10,10, 7, 9, 8,11,10, 8, 9, 9,11,11,10,11,
  143392. 10,14,11,10,11,11,13,13,10,11,11,14,13,10,10,11,
  143393. 14,13,10,11,11,14,14,12,11,13,12,16,13,14,14,15,
  143394. 15,10,10,11,13,14,10,11,10,14,13,10,11,11,14,14,
  143395. 12,13,12,15,13,13,13,14,15,16, 5, 7, 7,10,10, 7,
  143396. 8, 8,10,10, 7, 8, 8,10,10,10,10,10,13,13,10,10,
  143397. 11,12,13, 6, 8, 8,11,10, 8, 9, 9,11,11, 7, 8, 9,
  143398. 10,11,10,11,11,13,13,10,10,11,11,13, 6, 8, 8,10,
  143399. 11, 8, 9, 9,11,11, 8, 9, 8,12,10,10,11,11,13,13,
  143400. 10,11,10,14,11,10,10,10,14,13,10,11,11,14,13,10,
  143401. 10,11,13,13,12,14,14,16,16,12,12,13,13,15,10,11,
  143402. 11,13,14,10,11,11,14,15,10,11,10,13,13,13,14,13,
  143403. 16,16,12,13,11,15,12, 9,10,10,13,13,10,11,11,14,
  143404. 13,10,10,11,13,14,13,14,13,16,16,13,13,13,15,16,
  143405. 9,10,10,13,13,10,10,11,13,14,10,11,11,15,13,13,
  143406. 13,14,14,18,13,13,14,16,15, 9,10,10,13,14,10,11,
  143407. 10,14,13,10,11,11,13,14,13,14,13,16,15,13,13,14,
  143408. 15,16,12,13,12,16,14,11,11,13,15,15,13,14,13,16,
  143409. 15,15,12,16,12,17,14,15,15,17,17,12,13,13,14,16,
  143410. 11,13,11,16,15,12,13,14,15,16,14,15,13, 0,14,14,
  143411. 16,16, 0, 0, 9,10,10,13,13,10,11,10,14,14,10,11,
  143412. 11,13,13,12,13,13,14,16,13,14,14,16,16, 9,10,10,
  143413. 14,14,11,11,11,14,13,10,10,11,14,14,13,13,13,16,
  143414. 16,13,13,14,14,17, 9,10,10,13,14,10,11,11,13,15,
  143415. 10,11,10,14,14,13,13,13,14,17,13,14,13,17,14,12,
  143416. 13,13,16,14,13,14,13,16,15,12,12,13,15,16,15,15,
  143417. 16,18,16,15,13,15,14, 0,12,12,13,14,16,13,13,14,
  143418. 15,16,11,12,11,16,14,15,16,16,17,17,14,15,12,17,
  143419. 12,
  143420. };
  143421. static float _vq_quantthresh__44u1__p4_0[] = {
  143422. -1.5, -0.5, 0.5, 1.5,
  143423. };
  143424. static long _vq_quantmap__44u1__p4_0[] = {
  143425. 3, 1, 0, 2, 4,
  143426. };
  143427. static encode_aux_threshmatch _vq_auxt__44u1__p4_0 = {
  143428. _vq_quantthresh__44u1__p4_0,
  143429. _vq_quantmap__44u1__p4_0,
  143430. 5,
  143431. 5
  143432. };
  143433. static static_codebook _44u1__p4_0 = {
  143434. 4, 625,
  143435. _vq_lengthlist__44u1__p4_0,
  143436. 1, -533725184, 1611661312, 3, 0,
  143437. _vq_quantlist__44u1__p4_0,
  143438. NULL,
  143439. &_vq_auxt__44u1__p4_0,
  143440. NULL,
  143441. 0
  143442. };
  143443. static long _vq_quantlist__44u1__p5_0[] = {
  143444. 4,
  143445. 3,
  143446. 5,
  143447. 2,
  143448. 6,
  143449. 1,
  143450. 7,
  143451. 0,
  143452. 8,
  143453. };
  143454. static long _vq_lengthlist__44u1__p5_0[] = {
  143455. 1, 4, 4, 7, 7, 7, 7, 9, 9, 4, 6, 6, 8, 8, 8, 8,
  143456. 9, 9, 4, 6, 6, 8, 8, 8, 8, 9, 9, 7, 8, 8, 9, 9,
  143457. 9, 9,11,10, 7, 8, 8, 9, 9, 9, 9,10,10, 7, 8, 8,
  143458. 9, 9,10,10,11,11, 7, 8, 8, 9, 9,10,10,11,11, 9,
  143459. 9, 9,10,10,11,11,12,12, 9, 9, 9,10,11,11,11,12,
  143460. 12,
  143461. };
  143462. static float _vq_quantthresh__44u1__p5_0[] = {
  143463. -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5, 3.5,
  143464. };
  143465. static long _vq_quantmap__44u1__p5_0[] = {
  143466. 7, 5, 3, 1, 0, 2, 4, 6,
  143467. 8,
  143468. };
  143469. static encode_aux_threshmatch _vq_auxt__44u1__p5_0 = {
  143470. _vq_quantthresh__44u1__p5_0,
  143471. _vq_quantmap__44u1__p5_0,
  143472. 9,
  143473. 9
  143474. };
  143475. static static_codebook _44u1__p5_0 = {
  143476. 2, 81,
  143477. _vq_lengthlist__44u1__p5_0,
  143478. 1, -531628032, 1611661312, 4, 0,
  143479. _vq_quantlist__44u1__p5_0,
  143480. NULL,
  143481. &_vq_auxt__44u1__p5_0,
  143482. NULL,
  143483. 0
  143484. };
  143485. static long _vq_quantlist__44u1__p6_0[] = {
  143486. 6,
  143487. 5,
  143488. 7,
  143489. 4,
  143490. 8,
  143491. 3,
  143492. 9,
  143493. 2,
  143494. 10,
  143495. 1,
  143496. 11,
  143497. 0,
  143498. 12,
  143499. };
  143500. static long _vq_lengthlist__44u1__p6_0[] = {
  143501. 1, 4, 4, 6, 6, 8, 8,10, 9,11,10,14,13, 4, 6, 5,
  143502. 8, 8, 9, 9,11,10,11,11,14,14, 4, 5, 6, 8, 8, 9,
  143503. 9,10,10,11,11,14,14, 6, 8, 8, 9, 9,10,10,11,11,
  143504. 12,12,16,15, 7, 8, 8, 9, 9,10,10,11,11,12,12,15,
  143505. 15, 9,10,10,10,10,11,11,12,12,12,12,15,15, 9,10,
  143506. 9,10,11,11,11,12,12,12,13,15,15,10,10,11,11,11,
  143507. 12,12,13,12,13,13,16,15,10,11,11,11,11,12,12,13,
  143508. 12,13,13,16,17,11,11,12,12,12,13,13,13,14,14,15,
  143509. 17,17,11,11,12,12,12,13,13,13,14,14,14,16,18,14,
  143510. 15,15,15,15,16,16,16,16,17,18, 0, 0,14,15,15,15,
  143511. 15,17,16,17,18,17,17,18, 0,
  143512. };
  143513. static float _vq_quantthresh__44u1__p6_0[] = {
  143514. -27.5, -22.5, -17.5, -12.5, -7.5, -2.5, 2.5, 7.5,
  143515. 12.5, 17.5, 22.5, 27.5,
  143516. };
  143517. static long _vq_quantmap__44u1__p6_0[] = {
  143518. 11, 9, 7, 5, 3, 1, 0, 2,
  143519. 4, 6, 8, 10, 12,
  143520. };
  143521. static encode_aux_threshmatch _vq_auxt__44u1__p6_0 = {
  143522. _vq_quantthresh__44u1__p6_0,
  143523. _vq_quantmap__44u1__p6_0,
  143524. 13,
  143525. 13
  143526. };
  143527. static static_codebook _44u1__p6_0 = {
  143528. 2, 169,
  143529. _vq_lengthlist__44u1__p6_0,
  143530. 1, -526516224, 1616117760, 4, 0,
  143531. _vq_quantlist__44u1__p6_0,
  143532. NULL,
  143533. &_vq_auxt__44u1__p6_0,
  143534. NULL,
  143535. 0
  143536. };
  143537. static long _vq_quantlist__44u1__p6_1[] = {
  143538. 2,
  143539. 1,
  143540. 3,
  143541. 0,
  143542. 4,
  143543. };
  143544. static long _vq_lengthlist__44u1__p6_1[] = {
  143545. 2, 4, 4, 5, 5, 4, 5, 5, 5, 5, 4, 5, 5, 5, 5, 5,
  143546. 6, 6, 6, 6, 5, 6, 6, 6, 6,
  143547. };
  143548. static float _vq_quantthresh__44u1__p6_1[] = {
  143549. -1.5, -0.5, 0.5, 1.5,
  143550. };
  143551. static long _vq_quantmap__44u1__p6_1[] = {
  143552. 3, 1, 0, 2, 4,
  143553. };
  143554. static encode_aux_threshmatch _vq_auxt__44u1__p6_1 = {
  143555. _vq_quantthresh__44u1__p6_1,
  143556. _vq_quantmap__44u1__p6_1,
  143557. 5,
  143558. 5
  143559. };
  143560. static static_codebook _44u1__p6_1 = {
  143561. 2, 25,
  143562. _vq_lengthlist__44u1__p6_1,
  143563. 1, -533725184, 1611661312, 3, 0,
  143564. _vq_quantlist__44u1__p6_1,
  143565. NULL,
  143566. &_vq_auxt__44u1__p6_1,
  143567. NULL,
  143568. 0
  143569. };
  143570. static long _vq_quantlist__44u1__p7_0[] = {
  143571. 3,
  143572. 2,
  143573. 4,
  143574. 1,
  143575. 5,
  143576. 0,
  143577. 6,
  143578. };
  143579. static long _vq_lengthlist__44u1__p7_0[] = {
  143580. 1, 3, 2, 9, 9, 7, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,
  143581. 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,
  143582. 9, 9, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8,
  143583. 8,
  143584. };
  143585. static float _vq_quantthresh__44u1__p7_0[] = {
  143586. -422.5, -253.5, -84.5, 84.5, 253.5, 422.5,
  143587. };
  143588. static long _vq_quantmap__44u1__p7_0[] = {
  143589. 5, 3, 1, 0, 2, 4, 6,
  143590. };
  143591. static encode_aux_threshmatch _vq_auxt__44u1__p7_0 = {
  143592. _vq_quantthresh__44u1__p7_0,
  143593. _vq_quantmap__44u1__p7_0,
  143594. 7,
  143595. 7
  143596. };
  143597. static static_codebook _44u1__p7_0 = {
  143598. 2, 49,
  143599. _vq_lengthlist__44u1__p7_0,
  143600. 1, -518017024, 1626677248, 3, 0,
  143601. _vq_quantlist__44u1__p7_0,
  143602. NULL,
  143603. &_vq_auxt__44u1__p7_0,
  143604. NULL,
  143605. 0
  143606. };
  143607. static long _vq_quantlist__44u1__p7_1[] = {
  143608. 6,
  143609. 5,
  143610. 7,
  143611. 4,
  143612. 8,
  143613. 3,
  143614. 9,
  143615. 2,
  143616. 10,
  143617. 1,
  143618. 11,
  143619. 0,
  143620. 12,
  143621. };
  143622. static long _vq_lengthlist__44u1__p7_1[] = {
  143623. 1, 4, 4, 6, 6, 6, 6, 7, 7, 8, 8, 9, 9, 5, 7, 7,
  143624. 8, 7, 7, 7, 9, 8,10, 9,10,11, 5, 7, 7, 8, 8, 7,
  143625. 7, 8, 9,10,10,11,11, 6, 8, 8, 9, 9, 9, 9,11,10,
  143626. 12,12,15,12, 6, 8, 8, 9, 9, 9, 9,11,11,12,11,14,
  143627. 12, 7, 8, 8,10,10,12,12,13,13,13,15,13,13, 7, 8,
  143628. 8,10,10,11,11,13,12,14,15,15,15, 9,10,10,11,12,
  143629. 13,13,14,15,14,15,14,15, 8,10,10,12,12,14,14,15,
  143630. 14,14,15,15,14,10,12,12,14,14,15,14,15,15,15,14,
  143631. 15,15,10,12,12,13,14,15,14,15,15,14,15,15,15,12,
  143632. 15,13,15,14,15,15,15,15,15,15,15,15,13,13,15,15,
  143633. 15,15,15,15,15,15,15,15,15,
  143634. };
  143635. static float _vq_quantthresh__44u1__p7_1[] = {
  143636. -71.5, -58.5, -45.5, -32.5, -19.5, -6.5, 6.5, 19.5,
  143637. 32.5, 45.5, 58.5, 71.5,
  143638. };
  143639. static long _vq_quantmap__44u1__p7_1[] = {
  143640. 11, 9, 7, 5, 3, 1, 0, 2,
  143641. 4, 6, 8, 10, 12,
  143642. };
  143643. static encode_aux_threshmatch _vq_auxt__44u1__p7_1 = {
  143644. _vq_quantthresh__44u1__p7_1,
  143645. _vq_quantmap__44u1__p7_1,
  143646. 13,
  143647. 13
  143648. };
  143649. static static_codebook _44u1__p7_1 = {
  143650. 2, 169,
  143651. _vq_lengthlist__44u1__p7_1,
  143652. 1, -523010048, 1618608128, 4, 0,
  143653. _vq_quantlist__44u1__p7_1,
  143654. NULL,
  143655. &_vq_auxt__44u1__p7_1,
  143656. NULL,
  143657. 0
  143658. };
  143659. static long _vq_quantlist__44u1__p7_2[] = {
  143660. 6,
  143661. 5,
  143662. 7,
  143663. 4,
  143664. 8,
  143665. 3,
  143666. 9,
  143667. 2,
  143668. 10,
  143669. 1,
  143670. 11,
  143671. 0,
  143672. 12,
  143673. };
  143674. static long _vq_lengthlist__44u1__p7_2[] = {
  143675. 2, 5, 4, 6, 6, 7, 7, 8, 8, 8, 8, 9, 8, 5, 5, 6,
  143676. 7, 7, 8, 8, 8, 8, 9, 9, 9, 9, 5, 6, 5, 7, 7, 8,
  143677. 8, 8, 8, 9, 9, 9, 9, 6, 7, 7, 8, 8, 8, 8, 9, 8,
  143678. 9, 9, 9, 9, 6, 7, 7, 8, 7, 8, 8, 9, 9, 9, 9, 9,
  143679. 9, 7, 8, 8, 8, 8, 9, 9, 9, 9, 9, 9, 9, 9, 7, 8,
  143680. 8, 9, 8, 9, 8, 9, 9, 9, 9, 9, 9, 8, 9, 8, 9, 9,
  143681. 9, 9, 9, 9, 9, 9,10,10, 8, 8, 9, 9, 9, 9, 9, 9,
  143682. 9, 9,10, 9,10, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,
  143683. 9, 9, 8, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,
  143684. 9, 9, 9, 9, 9, 9, 9, 9,10,10,10, 9, 9, 9, 9, 9,
  143685. 9, 9, 9,10, 9, 9,10,10, 9,
  143686. };
  143687. static float _vq_quantthresh__44u1__p7_2[] = {
  143688. -5.5, -4.5, -3.5, -2.5, -1.5, -0.5, 0.5, 1.5,
  143689. 2.5, 3.5, 4.5, 5.5,
  143690. };
  143691. static long _vq_quantmap__44u1__p7_2[] = {
  143692. 11, 9, 7, 5, 3, 1, 0, 2,
  143693. 4, 6, 8, 10, 12,
  143694. };
  143695. static encode_aux_threshmatch _vq_auxt__44u1__p7_2 = {
  143696. _vq_quantthresh__44u1__p7_2,
  143697. _vq_quantmap__44u1__p7_2,
  143698. 13,
  143699. 13
  143700. };
  143701. static static_codebook _44u1__p7_2 = {
  143702. 2, 169,
  143703. _vq_lengthlist__44u1__p7_2,
  143704. 1, -531103744, 1611661312, 4, 0,
  143705. _vq_quantlist__44u1__p7_2,
  143706. NULL,
  143707. &_vq_auxt__44u1__p7_2,
  143708. NULL,
  143709. 0
  143710. };
  143711. static long _huff_lengthlist__44u1__short[] = {
  143712. 12,13,14,13,17,12,15,17, 5, 5, 6,10,10,11,15,16,
  143713. 4, 3, 3, 7, 5, 7,10,16, 7, 7, 7,10, 9,11,12,16,
  143714. 6, 5, 5, 9, 5, 6,10,16, 8, 7, 7, 9, 6, 7, 9,16,
  143715. 11, 7, 3, 6, 4, 5, 8,16,12, 9, 4, 8, 5, 7, 9,16,
  143716. };
  143717. static static_codebook _huff_book__44u1__short = {
  143718. 2, 64,
  143719. _huff_lengthlist__44u1__short,
  143720. 0, 0, 0, 0, 0,
  143721. NULL,
  143722. NULL,
  143723. NULL,
  143724. NULL,
  143725. 0
  143726. };
  143727. static long _huff_lengthlist__44u2__long[] = {
  143728. 5, 9,14,12,15,13,10,13, 7, 4, 5, 6, 8, 7, 8,12,
  143729. 13, 4, 3, 5, 5, 6, 9,15,12, 6, 5, 6, 6, 6, 7,14,
  143730. 14, 7, 4, 6, 4, 6, 8,15,12, 6, 6, 5, 5, 5, 6,14,
  143731. 9, 7, 8, 6, 7, 5, 4,10,10,13,14,14,15,10, 6, 8,
  143732. };
  143733. static static_codebook _huff_book__44u2__long = {
  143734. 2, 64,
  143735. _huff_lengthlist__44u2__long,
  143736. 0, 0, 0, 0, 0,
  143737. NULL,
  143738. NULL,
  143739. NULL,
  143740. NULL,
  143741. 0
  143742. };
  143743. static long _vq_quantlist__44u2__p1_0[] = {
  143744. 1,
  143745. 0,
  143746. 2,
  143747. };
  143748. static long _vq_lengthlist__44u2__p1_0[] = {
  143749. 1, 4, 4, 5, 8, 7, 5, 7, 8, 5, 8, 8, 8,11,11, 8,
  143750. 10,11, 5, 8, 8, 8,11,10, 8,11,11, 4, 8, 8, 8,11,
  143751. 11, 8,11,11, 8,11,11,11,13,14,11,13,13, 7,11,11,
  143752. 10,13,12,11,14,14, 4, 8, 8, 8,11,11, 8,11,11, 8,
  143753. 11,11,11,14,13,10,12,13, 8,11,11,11,13,13,11,13,
  143754. 13,
  143755. };
  143756. static float _vq_quantthresh__44u2__p1_0[] = {
  143757. -0.5, 0.5,
  143758. };
  143759. static long _vq_quantmap__44u2__p1_0[] = {
  143760. 1, 0, 2,
  143761. };
  143762. static encode_aux_threshmatch _vq_auxt__44u2__p1_0 = {
  143763. _vq_quantthresh__44u2__p1_0,
  143764. _vq_quantmap__44u2__p1_0,
  143765. 3,
  143766. 3
  143767. };
  143768. static static_codebook _44u2__p1_0 = {
  143769. 4, 81,
  143770. _vq_lengthlist__44u2__p1_0,
  143771. 1, -535822336, 1611661312, 2, 0,
  143772. _vq_quantlist__44u2__p1_0,
  143773. NULL,
  143774. &_vq_auxt__44u2__p1_0,
  143775. NULL,
  143776. 0
  143777. };
  143778. static long _vq_quantlist__44u2__p2_0[] = {
  143779. 1,
  143780. 0,
  143781. 2,
  143782. };
  143783. static long _vq_lengthlist__44u2__p2_0[] = {
  143784. 2, 5, 5, 5, 6, 6, 5, 6, 6, 5, 6, 6, 7, 8, 8, 6,
  143785. 8, 8, 5, 6, 6, 6, 8, 7, 7, 8, 8, 5, 6, 6, 7, 8,
  143786. 8, 6, 8, 8, 6, 8, 8, 8, 9,10, 8,10,10, 6, 8, 8,
  143787. 7,10, 8, 8,10,10, 5, 6, 6, 6, 8, 8, 7, 8, 8, 6,
  143788. 8, 8, 8,10,10, 8, 8,10, 6, 8, 8, 8,10,10, 8,10,
  143789. 9,
  143790. };
  143791. static float _vq_quantthresh__44u2__p2_0[] = {
  143792. -0.5, 0.5,
  143793. };
  143794. static long _vq_quantmap__44u2__p2_0[] = {
  143795. 1, 0, 2,
  143796. };
  143797. static encode_aux_threshmatch _vq_auxt__44u2__p2_0 = {
  143798. _vq_quantthresh__44u2__p2_0,
  143799. _vq_quantmap__44u2__p2_0,
  143800. 3,
  143801. 3
  143802. };
  143803. static static_codebook _44u2__p2_0 = {
  143804. 4, 81,
  143805. _vq_lengthlist__44u2__p2_0,
  143806. 1, -535822336, 1611661312, 2, 0,
  143807. _vq_quantlist__44u2__p2_0,
  143808. NULL,
  143809. &_vq_auxt__44u2__p2_0,
  143810. NULL,
  143811. 0
  143812. };
  143813. static long _vq_quantlist__44u2__p3_0[] = {
  143814. 2,
  143815. 1,
  143816. 3,
  143817. 0,
  143818. 4,
  143819. };
  143820. static long _vq_lengthlist__44u2__p3_0[] = {
  143821. 2, 4, 4, 7, 8, 5, 7, 7, 9, 9, 5, 7, 7, 9, 9, 8,
  143822. 9, 9,12,11, 8, 9, 9,11,12, 5, 7, 7,10,10, 7, 9,
  143823. 9,11,11, 7, 9, 9,10,11,10,11,11,13,13, 9,10,11,
  143824. 12,13, 5, 7, 7,10,10, 7, 9, 9,11,10, 7, 9, 9,11,
  143825. 11, 9,11,10,13,13,10,11,11,13,13, 8,10,10,14,13,
  143826. 10,11,11,15,14, 9,11,11,15,14,13,14,13,16,14,12,
  143827. 13,13,15,16, 8,10,10,13,14, 9,11,11,14,15,10,11,
  143828. 11,14,15,12,13,13,15,15,12,13,14,15,16, 5, 7, 7,
  143829. 10,10, 7, 9, 9,11,11, 7, 9, 9,11,12,10,11,11,14,
  143830. 13,10,11,11,14,14, 7, 9, 9,12,12, 9,11,11,13,13,
  143831. 9,11,11,13,13,12,13,12,14,14,11,12,13,15,15, 7,
  143832. 9, 9,12,12, 8,11,10,13,12, 9,11,11,13,13,11,13,
  143833. 12,15,13,11,13,13,15,16, 9,12,11,15,15,11,12,12,
  143834. 16,15,11,12,13,16,16,13,14,15,16,15,13,15,15,17,
  143835. 17, 9,11,11,14,15,10,12,12,15,15,11,13,12,15,16,
  143836. 13,15,14,16,16,13,15,15,17,19, 5, 7, 7,10,10, 7,
  143837. 9, 9,12,11, 7, 9, 9,11,11,10,11,11,14,14,10,11,
  143838. 11,13,14, 7, 9, 9,12,12, 9,11,11,13,13, 9,10,11,
  143839. 12,13,11,13,12,16,15,11,12,12,14,15, 7, 9, 9,12,
  143840. 12, 9,11,11,13,13, 9,11,11,13,12,11,13,12,15,16,
  143841. 12,13,13,15,14, 9,11,11,15,14,11,13,12,16,15,10,
  143842. 11,12,15,15,13,14,14,18,17,13,14,14,15,17,10,11,
  143843. 11,14,15,11,13,12,15,17,11,13,12,15,16,13,15,14,
  143844. 18,17,14,15,15,16,18, 7,10,10,14,14,10,12,12,15,
  143845. 15,10,12,12,15,15,14,15,15,18,17,13,15,15,16,16,
  143846. 9,11,11,16,15,11,13,13,16,18,11,13,13,16,16,15,
  143847. 16,16, 0, 0,14,15,16,18,17, 9,11,11,15,15,10,13,
  143848. 12,17,16,11,12,13,16,17,14,15,16,19,19,14,15,15,
  143849. 0,20,12,14,14, 0, 0,13,14,16,19,18,13,15,16,20,
  143850. 17,16,18, 0, 0, 0,15,16,17,18,19,11,14,14, 0,19,
  143851. 12,15,14,17,17,13,15,15, 0, 0,16,17,15,20,19,15,
  143852. 17,16,19, 0, 8,10,10,14,15,10,12,11,15,15,10,11,
  143853. 12,16,15,13,14,14,19,17,14,15,15, 0, 0, 9,11,11,
  143854. 16,15,11,13,13,17,16,10,12,13,16,17,14,15,15,18,
  143855. 18,14,15,16,20,19, 9,12,12, 0,15,11,13,13,16,17,
  143856. 11,13,13,19,17,14,16,16,18,17,15,16,16,17,19,11,
  143857. 14,14,18,18,13,14,15, 0, 0,12,14,15,19,18,15,16,
  143858. 19, 0,19,15,16,19,19,17,12,14,14,16,19,13,15,15,
  143859. 0,17,13,15,14,18,18,15,16,15, 0,18,16,17,17, 0,
  143860. 0,
  143861. };
  143862. static float _vq_quantthresh__44u2__p3_0[] = {
  143863. -1.5, -0.5, 0.5, 1.5,
  143864. };
  143865. static long _vq_quantmap__44u2__p3_0[] = {
  143866. 3, 1, 0, 2, 4,
  143867. };
  143868. static encode_aux_threshmatch _vq_auxt__44u2__p3_0 = {
  143869. _vq_quantthresh__44u2__p3_0,
  143870. _vq_quantmap__44u2__p3_0,
  143871. 5,
  143872. 5
  143873. };
  143874. static static_codebook _44u2__p3_0 = {
  143875. 4, 625,
  143876. _vq_lengthlist__44u2__p3_0,
  143877. 1, -533725184, 1611661312, 3, 0,
  143878. _vq_quantlist__44u2__p3_0,
  143879. NULL,
  143880. &_vq_auxt__44u2__p3_0,
  143881. NULL,
  143882. 0
  143883. };
  143884. static long _vq_quantlist__44u2__p4_0[] = {
  143885. 2,
  143886. 1,
  143887. 3,
  143888. 0,
  143889. 4,
  143890. };
  143891. static long _vq_lengthlist__44u2__p4_0[] = {
  143892. 4, 5, 5, 8, 8, 5, 7, 6, 9, 9, 5, 6, 7, 9, 9, 9,
  143893. 9, 9,11,11, 9, 9, 9,11,11, 5, 7, 7, 9, 9, 7, 8,
  143894. 8,10,10, 7, 7, 8,10,10,10,10,10,11,12, 9,10,10,
  143895. 11,12, 5, 7, 7, 9, 9, 6, 8, 7,10,10, 7, 8, 8,10,
  143896. 10, 9,10,10,12,11, 9,10,10,12,11, 9,10,10,12,12,
  143897. 10,10,10,13,12, 9,10,10,12,13,12,12,12,14,14,11,
  143898. 12,12,13,14, 9,10,10,12,12, 9,10,10,12,13,10,10,
  143899. 10,12,13,11,12,12,14,13,12,12,12,14,13, 5, 7, 7,
  143900. 10, 9, 7, 8, 8,10,10, 7, 8, 8,10,10,10,10,10,12,
  143901. 12,10,10,10,12,12, 7, 8, 8,11,10, 8, 8, 9,11,11,
  143902. 8, 9, 9,11,11,10,11,11,12,13,10,11,11,13,13, 6,
  143903. 8, 8,10,10, 7, 9, 8,11,10, 8, 9, 9,11,11,10,11,
  143904. 10,13,11,10,11,11,13,13, 9,10,10,13,13,10,11,11,
  143905. 13,13,10,11,11,14,13,12,11,13,12,15,12,13,13,15,
  143906. 15, 9,10,10,12,13,10,11,10,13,13,10,11,11,13,13,
  143907. 12,13,11,15,13,12,13,13,15,15, 5, 7, 7, 9,10, 7,
  143908. 8, 8,10,10, 7, 8, 8,10,10,10,10,10,12,12,10,10,
  143909. 11,12,12, 6, 8, 8,10,10, 8, 9, 9,11,11, 7, 8, 9,
  143910. 10,11,10,11,11,13,13,10,10,11,11,13, 7, 8, 8,10,
  143911. 11, 8, 9, 9,11,11, 8, 9, 8,11,11,10,11,11,13,13,
  143912. 10,11,11,13,12, 9,10,10,13,12,10,11,11,14,13,10,
  143913. 10,11,13,13,12,13,13,15,15,12,11,13,12,14, 9,10,
  143914. 10,12,13,10,11,11,13,14,10,11,11,13,13,12,13,13,
  143915. 15,15,12,13,12,15,12, 8, 9, 9,12,12, 9,11,10,13,
  143916. 13, 9,10,10,13,13,12,13,13,15,15,12,12,12,14,14,
  143917. 9,10,10,13,13,10,11,11,13,14,10,11,11,14,12,13,
  143918. 13,14,14,16,12,13,13,15,14, 9,10,10,13,13,10,11,
  143919. 10,14,13,10,11,11,13,14,12,14,13,16,14,13,13,13,
  143920. 14,15,11,13,12,15,14,11,12,13,14,15,12,13,13,16,
  143921. 15,14,12,15,12,16,14,15,15,17,16,11,12,12,14,15,
  143922. 11,13,11,15,14,12,13,13,15,16,13,15,12,17,13,14,
  143923. 15,15,16,16, 8, 9, 9,12,12, 9,10,10,13,13, 9,10,
  143924. 10,13,13,12,13,12,14,14,12,13,13,15,15, 9,10,10,
  143925. 13,13,10,11,11,14,13,10,10,11,13,14,12,13,13,15,
  143926. 14,12,12,14,14,16, 9,10,10,13,13,10,11,11,13,14,
  143927. 10,11,11,14,13,13,13,13,15,15,13,14,13,16,14,11,
  143928. 12,12,14,14,12,13,13,16,15,11,12,13,14,15,14,15,
  143929. 15,16,16,14,13,15,13,17,11,12,12,14,15,12,13,13,
  143930. 15,16,11,13,12,15,15,14,15,14,16,16,14,15,12,17,
  143931. 13,
  143932. };
  143933. static float _vq_quantthresh__44u2__p4_0[] = {
  143934. -1.5, -0.5, 0.5, 1.5,
  143935. };
  143936. static long _vq_quantmap__44u2__p4_0[] = {
  143937. 3, 1, 0, 2, 4,
  143938. };
  143939. static encode_aux_threshmatch _vq_auxt__44u2__p4_0 = {
  143940. _vq_quantthresh__44u2__p4_0,
  143941. _vq_quantmap__44u2__p4_0,
  143942. 5,
  143943. 5
  143944. };
  143945. static static_codebook _44u2__p4_0 = {
  143946. 4, 625,
  143947. _vq_lengthlist__44u2__p4_0,
  143948. 1, -533725184, 1611661312, 3, 0,
  143949. _vq_quantlist__44u2__p4_0,
  143950. NULL,
  143951. &_vq_auxt__44u2__p4_0,
  143952. NULL,
  143953. 0
  143954. };
  143955. static long _vq_quantlist__44u2__p5_0[] = {
  143956. 4,
  143957. 3,
  143958. 5,
  143959. 2,
  143960. 6,
  143961. 1,
  143962. 7,
  143963. 0,
  143964. 8,
  143965. };
  143966. static long _vq_lengthlist__44u2__p5_0[] = {
  143967. 1, 4, 4, 7, 7, 8, 8, 9, 9, 4, 6, 5, 8, 8, 8, 8,
  143968. 10,10, 4, 5, 6, 8, 8, 8, 8,10,10, 7, 8, 8, 9, 9,
  143969. 9, 9,11,11, 7, 8, 8, 9, 9, 9, 9,11,11, 8, 8, 8,
  143970. 9, 9,10,11,12,12, 8, 8, 8, 9, 9,10,10,12,12,10,
  143971. 10,10,11,11,12,12,13,13,10,10,10,11,11,12,12,13,
  143972. 13,
  143973. };
  143974. static float _vq_quantthresh__44u2__p5_0[] = {
  143975. -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5, 3.5,
  143976. };
  143977. static long _vq_quantmap__44u2__p5_0[] = {
  143978. 7, 5, 3, 1, 0, 2, 4, 6,
  143979. 8,
  143980. };
  143981. static encode_aux_threshmatch _vq_auxt__44u2__p5_0 = {
  143982. _vq_quantthresh__44u2__p5_0,
  143983. _vq_quantmap__44u2__p5_0,
  143984. 9,
  143985. 9
  143986. };
  143987. static static_codebook _44u2__p5_0 = {
  143988. 2, 81,
  143989. _vq_lengthlist__44u2__p5_0,
  143990. 1, -531628032, 1611661312, 4, 0,
  143991. _vq_quantlist__44u2__p5_0,
  143992. NULL,
  143993. &_vq_auxt__44u2__p5_0,
  143994. NULL,
  143995. 0
  143996. };
  143997. static long _vq_quantlist__44u2__p6_0[] = {
  143998. 6,
  143999. 5,
  144000. 7,
  144001. 4,
  144002. 8,
  144003. 3,
  144004. 9,
  144005. 2,
  144006. 10,
  144007. 1,
  144008. 11,
  144009. 0,
  144010. 12,
  144011. };
  144012. static long _vq_lengthlist__44u2__p6_0[] = {
  144013. 1, 4, 4, 6, 6, 8, 8,10,10,11,11,14,13, 4, 6, 5,
  144014. 8, 8, 9, 9,11,10,12,11,15,14, 4, 5, 6, 8, 8, 9,
  144015. 9,11,11,11,11,14,14, 6, 8, 8,10, 9,11,11,11,11,
  144016. 12,12,15,15, 6, 8, 8, 9, 9,11,11,11,12,12,12,15,
  144017. 15, 8,10,10,11,11,11,11,12,12,13,13,15,16, 8,10,
  144018. 10,11,11,11,11,12,12,13,13,16,16,10,11,11,12,12,
  144019. 12,12,13,13,13,13,17,16,10,11,11,12,12,12,12,13,
  144020. 13,13,14,16,17,11,12,12,13,13,13,13,14,14,15,14,
  144021. 18,17,11,12,12,13,13,13,13,14,14,14,15,19,18,14,
  144022. 15,15,15,15,16,16,18,19,18,18, 0, 0,14,15,15,16,
  144023. 15,17,17,16,18,17,18, 0, 0,
  144024. };
  144025. static float _vq_quantthresh__44u2__p6_0[] = {
  144026. -27.5, -22.5, -17.5, -12.5, -7.5, -2.5, 2.5, 7.5,
  144027. 12.5, 17.5, 22.5, 27.5,
  144028. };
  144029. static long _vq_quantmap__44u2__p6_0[] = {
  144030. 11, 9, 7, 5, 3, 1, 0, 2,
  144031. 4, 6, 8, 10, 12,
  144032. };
  144033. static encode_aux_threshmatch _vq_auxt__44u2__p6_0 = {
  144034. _vq_quantthresh__44u2__p6_0,
  144035. _vq_quantmap__44u2__p6_0,
  144036. 13,
  144037. 13
  144038. };
  144039. static static_codebook _44u2__p6_0 = {
  144040. 2, 169,
  144041. _vq_lengthlist__44u2__p6_0,
  144042. 1, -526516224, 1616117760, 4, 0,
  144043. _vq_quantlist__44u2__p6_0,
  144044. NULL,
  144045. &_vq_auxt__44u2__p6_0,
  144046. NULL,
  144047. 0
  144048. };
  144049. static long _vq_quantlist__44u2__p6_1[] = {
  144050. 2,
  144051. 1,
  144052. 3,
  144053. 0,
  144054. 4,
  144055. };
  144056. static long _vq_lengthlist__44u2__p6_1[] = {
  144057. 2, 4, 4, 5, 5, 4, 5, 5, 6, 5, 4, 5, 5, 5, 6, 5,
  144058. 6, 5, 6, 6, 5, 5, 6, 6, 6,
  144059. };
  144060. static float _vq_quantthresh__44u2__p6_1[] = {
  144061. -1.5, -0.5, 0.5, 1.5,
  144062. };
  144063. static long _vq_quantmap__44u2__p6_1[] = {
  144064. 3, 1, 0, 2, 4,
  144065. };
  144066. static encode_aux_threshmatch _vq_auxt__44u2__p6_1 = {
  144067. _vq_quantthresh__44u2__p6_1,
  144068. _vq_quantmap__44u2__p6_1,
  144069. 5,
  144070. 5
  144071. };
  144072. static static_codebook _44u2__p6_1 = {
  144073. 2, 25,
  144074. _vq_lengthlist__44u2__p6_1,
  144075. 1, -533725184, 1611661312, 3, 0,
  144076. _vq_quantlist__44u2__p6_1,
  144077. NULL,
  144078. &_vq_auxt__44u2__p6_1,
  144079. NULL,
  144080. 0
  144081. };
  144082. static long _vq_quantlist__44u2__p7_0[] = {
  144083. 4,
  144084. 3,
  144085. 5,
  144086. 2,
  144087. 6,
  144088. 1,
  144089. 7,
  144090. 0,
  144091. 8,
  144092. };
  144093. static long _vq_lengthlist__44u2__p7_0[] = {
  144094. 1, 3, 2,12,12,12,12,12,12, 4,12,12,12,12,12,12,
  144095. 12,12, 5,12,12,12,12,12,12,12,12,12,12,11,11,11,
  144096. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  144097. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  144098. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  144099. 11,
  144100. };
  144101. static float _vq_quantthresh__44u2__p7_0[] = {
  144102. -591.5, -422.5, -253.5, -84.5, 84.5, 253.5, 422.5, 591.5,
  144103. };
  144104. static long _vq_quantmap__44u2__p7_0[] = {
  144105. 7, 5, 3, 1, 0, 2, 4, 6,
  144106. 8,
  144107. };
  144108. static encode_aux_threshmatch _vq_auxt__44u2__p7_0 = {
  144109. _vq_quantthresh__44u2__p7_0,
  144110. _vq_quantmap__44u2__p7_0,
  144111. 9,
  144112. 9
  144113. };
  144114. static static_codebook _44u2__p7_0 = {
  144115. 2, 81,
  144116. _vq_lengthlist__44u2__p7_0,
  144117. 1, -516612096, 1626677248, 4, 0,
  144118. _vq_quantlist__44u2__p7_0,
  144119. NULL,
  144120. &_vq_auxt__44u2__p7_0,
  144121. NULL,
  144122. 0
  144123. };
  144124. static long _vq_quantlist__44u2__p7_1[] = {
  144125. 6,
  144126. 5,
  144127. 7,
  144128. 4,
  144129. 8,
  144130. 3,
  144131. 9,
  144132. 2,
  144133. 10,
  144134. 1,
  144135. 11,
  144136. 0,
  144137. 12,
  144138. };
  144139. static long _vq_lengthlist__44u2__p7_1[] = {
  144140. 1, 4, 4, 7, 6, 7, 6, 8, 7, 9, 7, 9, 8, 4, 7, 6,
  144141. 8, 8, 9, 8,10, 9,10,10,11,11, 4, 7, 7, 8, 8, 8,
  144142. 8, 9,10,11,11,11,11, 6, 8, 8,10,10,10,10,11,11,
  144143. 12,12,12,12, 7, 8, 8,10,10,10,10,11,11,12,12,13,
  144144. 13, 7, 9, 9,11,10,12,12,13,13,14,13,14,14, 7, 9,
  144145. 9,10,11,11,12,13,13,13,13,16,14, 9,10,10,12,12,
  144146. 13,13,14,14,15,16,15,16, 9,10,10,12,12,12,13,14,
  144147. 14,14,15,16,15,10,12,12,13,13,15,13,16,16,15,17,
  144148. 17,17,10,11,11,12,14,14,14,15,15,17,17,15,17,11,
  144149. 12,12,14,14,14,15,15,15,17,16,17,17,10,12,12,13,
  144150. 14,14,14,17,15,17,17,17,17,
  144151. };
  144152. static float _vq_quantthresh__44u2__p7_1[] = {
  144153. -71.5, -58.5, -45.5, -32.5, -19.5, -6.5, 6.5, 19.5,
  144154. 32.5, 45.5, 58.5, 71.5,
  144155. };
  144156. static long _vq_quantmap__44u2__p7_1[] = {
  144157. 11, 9, 7, 5, 3, 1, 0, 2,
  144158. 4, 6, 8, 10, 12,
  144159. };
  144160. static encode_aux_threshmatch _vq_auxt__44u2__p7_1 = {
  144161. _vq_quantthresh__44u2__p7_1,
  144162. _vq_quantmap__44u2__p7_1,
  144163. 13,
  144164. 13
  144165. };
  144166. static static_codebook _44u2__p7_1 = {
  144167. 2, 169,
  144168. _vq_lengthlist__44u2__p7_1,
  144169. 1, -523010048, 1618608128, 4, 0,
  144170. _vq_quantlist__44u2__p7_1,
  144171. NULL,
  144172. &_vq_auxt__44u2__p7_1,
  144173. NULL,
  144174. 0
  144175. };
  144176. static long _vq_quantlist__44u2__p7_2[] = {
  144177. 6,
  144178. 5,
  144179. 7,
  144180. 4,
  144181. 8,
  144182. 3,
  144183. 9,
  144184. 2,
  144185. 10,
  144186. 1,
  144187. 11,
  144188. 0,
  144189. 12,
  144190. };
  144191. static long _vq_lengthlist__44u2__p7_2[] = {
  144192. 2, 5, 5, 6, 6, 7, 7, 8, 7, 8, 8, 8, 8, 5, 6, 6,
  144193. 7, 7, 8, 8, 8, 8, 8, 8, 8, 8, 5, 6, 6, 7, 7, 8,
  144194. 7, 8, 8, 8, 8, 8, 8, 6, 7, 7, 7, 8, 8, 8, 8, 8,
  144195. 9, 9, 9, 9, 6, 7, 7, 8, 7, 8, 8, 9, 9, 9, 9, 9,
  144196. 9, 7, 8, 8, 8, 8, 8, 8, 9, 9, 9, 9, 9, 9, 7, 8,
  144197. 8, 8, 8, 8, 8, 9, 9, 9, 9, 9, 9, 8, 8, 8, 8, 9,
  144198. 9, 9, 9, 9, 9, 9, 9, 9, 8, 8, 8, 9, 9, 9, 9, 9,
  144199. 9, 9, 9, 9, 9, 8, 8, 9, 9, 9, 9, 9, 9, 9, 9, 9,
  144200. 9, 9, 8, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 8,
  144201. 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 8, 9, 9, 9,
  144202. 9, 9, 9, 9, 9, 9, 9, 9, 9,
  144203. };
  144204. static float _vq_quantthresh__44u2__p7_2[] = {
  144205. -5.5, -4.5, -3.5, -2.5, -1.5, -0.5, 0.5, 1.5,
  144206. 2.5, 3.5, 4.5, 5.5,
  144207. };
  144208. static long _vq_quantmap__44u2__p7_2[] = {
  144209. 11, 9, 7, 5, 3, 1, 0, 2,
  144210. 4, 6, 8, 10, 12,
  144211. };
  144212. static encode_aux_threshmatch _vq_auxt__44u2__p7_2 = {
  144213. _vq_quantthresh__44u2__p7_2,
  144214. _vq_quantmap__44u2__p7_2,
  144215. 13,
  144216. 13
  144217. };
  144218. static static_codebook _44u2__p7_2 = {
  144219. 2, 169,
  144220. _vq_lengthlist__44u2__p7_2,
  144221. 1, -531103744, 1611661312, 4, 0,
  144222. _vq_quantlist__44u2__p7_2,
  144223. NULL,
  144224. &_vq_auxt__44u2__p7_2,
  144225. NULL,
  144226. 0
  144227. };
  144228. static long _huff_lengthlist__44u2__short[] = {
  144229. 13,15,17,17,15,15,12,17,11, 9, 7,10,10, 9,12,17,
  144230. 10, 6, 3, 6, 5, 7,10,17,15,10, 6, 9, 8, 9,11,17,
  144231. 15, 8, 4, 7, 3, 5, 9,16,16,10, 5, 8, 4, 5, 8,16,
  144232. 13,11, 5, 8, 3, 3, 5,14,13,12, 7,10, 5, 5, 7,14,
  144233. };
  144234. static static_codebook _huff_book__44u2__short = {
  144235. 2, 64,
  144236. _huff_lengthlist__44u2__short,
  144237. 0, 0, 0, 0, 0,
  144238. NULL,
  144239. NULL,
  144240. NULL,
  144241. NULL,
  144242. 0
  144243. };
  144244. static long _huff_lengthlist__44u3__long[] = {
  144245. 6, 9,13,12,14,11,10,13, 8, 4, 5, 7, 8, 7, 8,12,
  144246. 11, 4, 3, 5, 5, 7, 9,14,11, 6, 5, 6, 6, 6, 7,13,
  144247. 13, 7, 5, 6, 4, 5, 7,14,11, 7, 6, 6, 5, 5, 6,13,
  144248. 9, 7, 8, 6, 7, 5, 3, 9, 9,12,13,12,14,10, 6, 7,
  144249. };
  144250. static static_codebook _huff_book__44u3__long = {
  144251. 2, 64,
  144252. _huff_lengthlist__44u3__long,
  144253. 0, 0, 0, 0, 0,
  144254. NULL,
  144255. NULL,
  144256. NULL,
  144257. NULL,
  144258. 0
  144259. };
  144260. static long _vq_quantlist__44u3__p1_0[] = {
  144261. 1,
  144262. 0,
  144263. 2,
  144264. };
  144265. static long _vq_lengthlist__44u3__p1_0[] = {
  144266. 1, 4, 4, 5, 8, 7, 5, 7, 8, 5, 8, 8, 8,10,11, 8,
  144267. 10,11, 5, 8, 8, 8,11,10, 8,11,11, 4, 8, 8, 8,11,
  144268. 11, 8,11,11, 8,11,11,11,13,14,11,14,14, 8,11,11,
  144269. 10,14,12,11,14,14, 4, 8, 8, 8,11,11, 8,11,11, 7,
  144270. 11,11,11,14,14,10,12,14, 8,11,11,11,14,14,11,14,
  144271. 13,
  144272. };
  144273. static float _vq_quantthresh__44u3__p1_0[] = {
  144274. -0.5, 0.5,
  144275. };
  144276. static long _vq_quantmap__44u3__p1_0[] = {
  144277. 1, 0, 2,
  144278. };
  144279. static encode_aux_threshmatch _vq_auxt__44u3__p1_0 = {
  144280. _vq_quantthresh__44u3__p1_0,
  144281. _vq_quantmap__44u3__p1_0,
  144282. 3,
  144283. 3
  144284. };
  144285. static static_codebook _44u3__p1_0 = {
  144286. 4, 81,
  144287. _vq_lengthlist__44u3__p1_0,
  144288. 1, -535822336, 1611661312, 2, 0,
  144289. _vq_quantlist__44u3__p1_0,
  144290. NULL,
  144291. &_vq_auxt__44u3__p1_0,
  144292. NULL,
  144293. 0
  144294. };
  144295. static long _vq_quantlist__44u3__p2_0[] = {
  144296. 1,
  144297. 0,
  144298. 2,
  144299. };
  144300. static long _vq_lengthlist__44u3__p2_0[] = {
  144301. 2, 5, 4, 5, 6, 6, 5, 6, 6, 5, 6, 6, 7, 8, 8, 6,
  144302. 8, 8, 5, 6, 6, 6, 8, 8, 7, 8, 8, 5, 7, 6, 7, 8,
  144303. 8, 6, 8, 8, 7, 8, 8, 8, 9,10, 8,10,10, 6, 8, 8,
  144304. 8,10, 8, 8,10,10, 5, 6, 6, 6, 8, 8, 7, 8, 8, 6,
  144305. 8, 8, 8,10,10, 8, 8,10, 7, 8, 8, 8,10,10, 8,10,
  144306. 9,
  144307. };
  144308. static float _vq_quantthresh__44u3__p2_0[] = {
  144309. -0.5, 0.5,
  144310. };
  144311. static long _vq_quantmap__44u3__p2_0[] = {
  144312. 1, 0, 2,
  144313. };
  144314. static encode_aux_threshmatch _vq_auxt__44u3__p2_0 = {
  144315. _vq_quantthresh__44u3__p2_0,
  144316. _vq_quantmap__44u3__p2_0,
  144317. 3,
  144318. 3
  144319. };
  144320. static static_codebook _44u3__p2_0 = {
  144321. 4, 81,
  144322. _vq_lengthlist__44u3__p2_0,
  144323. 1, -535822336, 1611661312, 2, 0,
  144324. _vq_quantlist__44u3__p2_0,
  144325. NULL,
  144326. &_vq_auxt__44u3__p2_0,
  144327. NULL,
  144328. 0
  144329. };
  144330. static long _vq_quantlist__44u3__p3_0[] = {
  144331. 2,
  144332. 1,
  144333. 3,
  144334. 0,
  144335. 4,
  144336. };
  144337. static long _vq_lengthlist__44u3__p3_0[] = {
  144338. 2, 4, 4, 7, 7, 5, 7, 7, 9, 9, 5, 7, 7, 9, 9, 8,
  144339. 9, 9,12,12, 8, 9, 9,11,12, 5, 7, 7,10,10, 7, 9,
  144340. 9,11,11, 7, 9, 9,10,11,10,11,11,13,13, 9,10,11,
  144341. 13,13, 5, 7, 7,10,10, 7, 9, 9,11,10, 7, 9, 9,11,
  144342. 11, 9,11,10,13,13,10,11,11,14,13, 8,10,10,14,13,
  144343. 10,11,11,15,14, 9,11,11,14,14,13,14,13,16,16,12,
  144344. 13,13,15,15, 8,10,10,13,14, 9,11,11,14,14,10,11,
  144345. 11,14,15,12,13,13,15,15,13,14,14,15,16, 5, 7, 7,
  144346. 10,10, 7, 9, 9,11,11, 7, 9, 9,11,12,10,11,11,14,
  144347. 14,10,11,11,14,14, 7, 9, 9,12,12, 9,11,11,13,13,
  144348. 9,11,11,13,13,12,12,13,15,15,11,12,13,15,16, 7,
  144349. 9, 9,11,11, 8,11,10,13,12, 9,11,11,13,13,11,13,
  144350. 12,15,13,11,13,13,15,16, 9,12,11,15,14,11,12,13,
  144351. 16,15,11,13,13,15,16,14,14,15,17,16,13,15,16, 0,
  144352. 17, 9,11,11,15,15,10,13,12,15,15,11,13,13,15,16,
  144353. 13,15,13,16,15,14,16,15, 0,19, 5, 7, 7,10,10, 7,
  144354. 9, 9,11,11, 7, 9, 9,11,11,10,12,11,14,14,10,11,
  144355. 12,14,14, 7, 9, 9,12,12, 9,11,11,14,13, 9,10,11,
  144356. 12,13,11,13,13,16,16,11,12,13,13,16, 7, 9, 9,12,
  144357. 12, 9,11,11,13,13, 9,11,11,13,13,11,13,13,15,15,
  144358. 12,13,12,15,14, 9,11,11,15,14,11,13,12,16,16,10,
  144359. 12,12,15,15,13,15,15,17,19,13,14,15,16,17,10,12,
  144360. 12,15,15,11,13,13,16,16,11,13,13,15,16,13,15,15,
  144361. 0, 0,14,15,15,16,16, 8,10,10,14,14,10,12,12,15,
  144362. 15,10,12,11,15,16,14,15,15,19,20,13,14,14,18,16,
  144363. 9,11,11,15,15,11,13,13,17,16,11,13,13,16,16,15,
  144364. 17,17,20,20,14,15,16,17,20, 9,11,11,15,15,10,13,
  144365. 12,16,15,11,13,13,15,17,14,16,15,18, 0,14,16,15,
  144366. 18,20,12,14,14, 0, 0,14,14,16, 0, 0,13,16,15, 0,
  144367. 0,17,17,18, 0, 0,16,17,19,19, 0,12,14,14,18, 0,
  144368. 12,16,14, 0,17,13,15,15,18, 0,16,18,17, 0,17,16,
  144369. 18,17, 0, 0, 7,10,10,14,14,10,12,11,15,15,10,12,
  144370. 12,16,15,13,15,15,18, 0,14,15,15,17, 0, 9,11,11,
  144371. 15,15,11,13,13,16,16,11,12,13,16,16,14,15,16,17,
  144372. 17,14,16,16,16,18, 9,11,12,16,16,11,13,13,17,17,
  144373. 11,14,13,20,17,15,16,16,19, 0,15,16,17, 0,19,11,
  144374. 13,14,17,16,14,15,15,20,18,13,14,15,17,19,16,18,
  144375. 18, 0,20,16,16,19,17, 0,12,15,14,17, 0,14,15,15,
  144376. 18,19,13,16,15,19,20,15,18,18, 0,20,17, 0,16, 0,
  144377. 0,
  144378. };
  144379. static float _vq_quantthresh__44u3__p3_0[] = {
  144380. -1.5, -0.5, 0.5, 1.5,
  144381. };
  144382. static long _vq_quantmap__44u3__p3_0[] = {
  144383. 3, 1, 0, 2, 4,
  144384. };
  144385. static encode_aux_threshmatch _vq_auxt__44u3__p3_0 = {
  144386. _vq_quantthresh__44u3__p3_0,
  144387. _vq_quantmap__44u3__p3_0,
  144388. 5,
  144389. 5
  144390. };
  144391. static static_codebook _44u3__p3_0 = {
  144392. 4, 625,
  144393. _vq_lengthlist__44u3__p3_0,
  144394. 1, -533725184, 1611661312, 3, 0,
  144395. _vq_quantlist__44u3__p3_0,
  144396. NULL,
  144397. &_vq_auxt__44u3__p3_0,
  144398. NULL,
  144399. 0
  144400. };
  144401. static long _vq_quantlist__44u3__p4_0[] = {
  144402. 2,
  144403. 1,
  144404. 3,
  144405. 0,
  144406. 4,
  144407. };
  144408. static long _vq_lengthlist__44u3__p4_0[] = {
  144409. 4, 5, 5, 8, 8, 5, 7, 6, 9, 9, 5, 6, 7, 9, 9, 9,
  144410. 9, 9,11,11, 9, 9, 9,11,11, 5, 7, 7, 9, 9, 7, 8,
  144411. 8,10,10, 7, 7, 8,10,10, 9,10,10,11,12, 9,10,10,
  144412. 11,12, 5, 7, 7, 9, 9, 7, 8, 7,10,10, 7, 8, 8,10,
  144413. 10, 9,10, 9,12,11, 9,10,10,12,11, 9,10, 9,12,12,
  144414. 9,10,10,13,12, 9,10,10,12,13,12,12,12,14,14,11,
  144415. 12,12,13,14, 9, 9,10,12,12, 9,10,10,12,12, 9,10,
  144416. 10,12,13,11,12,11,14,13,12,12,12,14,13, 5, 7, 7,
  144417. 9, 9, 7, 8, 8,10,10, 7, 8, 8,10,10,10,10,10,12,
  144418. 12, 9,10,10,12,12, 7, 8, 8,11,10, 8, 8, 9,11,11,
  144419. 8, 9, 9,11,11,11,11,11,12,13,10,11,11,13,13, 6,
  144420. 8, 8,10,10, 7, 9, 8,11,10, 8, 9, 9,11,11,10,11,
  144421. 10,13,11,10,11,11,13,13, 9,11,10,13,12,10,11,11,
  144422. 13,13,10,11,11,13,13,12,12,13,12,15,12,13,13,15,
  144423. 15, 9,10,10,12,13,10,11,10,13,12,10,11,11,13,14,
  144424. 12,13,11,15,13,12,13,13,15,15, 5, 7, 7, 9, 9, 7,
  144425. 8, 8,10,10, 7, 8, 8,10,10, 9,10,10,12,12,10,10,
  144426. 11,12,12, 6, 8, 8,10,10, 8, 9, 9,11,11, 7, 8, 9,
  144427. 10,11,10,11,11,13,13,10,10,11,11,13, 7, 8, 8,10,
  144428. 10, 8, 9, 9,11,11, 8, 9, 9,11,11,10,11,11,13,13,
  144429. 11,11,11,13,12, 9,10,10,13,12,10,11,11,14,13,10,
  144430. 10,11,12,13,12,13,13,15,15,12,11,13,13,14, 9,10,
  144431. 11,12,13,10,11,11,13,13,10,11,11,13,13,12,13,13,
  144432. 15,15,12,13,12,15,12, 8, 9, 9,12,12, 9,11,10,13,
  144433. 13, 9,10,10,13,13,12,13,13,15,14,12,12,12,14,13,
  144434. 9,10,10,13,12,10,11,11,13,13,10,11,11,14,12,13,
  144435. 13,14,14,16,12,13,13,15,15, 9,10,10,13,13,10,11,
  144436. 10,14,13,10,11,11,13,14,12,14,13,15,14,13,13,13,
  144437. 15,15,11,13,12,15,14,11,12,13,14,15,12,13,13,16,
  144438. 14,14,12,15,12,16,14,15,15,17,15,11,12,12,14,14,
  144439. 11,13,11,15,14,12,13,13,15,15,13,15,12,17,13,14,
  144440. 15,15,16,16, 8, 9, 9,12,12, 9,10,10,12,13, 9,10,
  144441. 10,13,13,12,12,12,14,14,12,13,13,15,15, 9,10,10,
  144442. 13,12,10,11,11,14,13,10,10,11,13,14,12,13,13,15,
  144443. 15,12,12,13,14,16, 9,10,10,13,13,10,11,11,13,14,
  144444. 10,11,11,14,13,12,13,13,14,15,13,14,13,16,14,11,
  144445. 12,12,14,14,12,13,13,15,14,11,12,13,14,15,14,15,
  144446. 15,16,16,13,13,15,13,16,11,12,12,14,15,12,13,13,
  144447. 14,15,11,13,12,15,14,14,15,15,16,16,14,15,12,16,
  144448. 13,
  144449. };
  144450. static float _vq_quantthresh__44u3__p4_0[] = {
  144451. -1.5, -0.5, 0.5, 1.5,
  144452. };
  144453. static long _vq_quantmap__44u3__p4_0[] = {
  144454. 3, 1, 0, 2, 4,
  144455. };
  144456. static encode_aux_threshmatch _vq_auxt__44u3__p4_0 = {
  144457. _vq_quantthresh__44u3__p4_0,
  144458. _vq_quantmap__44u3__p4_0,
  144459. 5,
  144460. 5
  144461. };
  144462. static static_codebook _44u3__p4_0 = {
  144463. 4, 625,
  144464. _vq_lengthlist__44u3__p4_0,
  144465. 1, -533725184, 1611661312, 3, 0,
  144466. _vq_quantlist__44u3__p4_0,
  144467. NULL,
  144468. &_vq_auxt__44u3__p4_0,
  144469. NULL,
  144470. 0
  144471. };
  144472. static long _vq_quantlist__44u3__p5_0[] = {
  144473. 4,
  144474. 3,
  144475. 5,
  144476. 2,
  144477. 6,
  144478. 1,
  144479. 7,
  144480. 0,
  144481. 8,
  144482. };
  144483. static long _vq_lengthlist__44u3__p5_0[] = {
  144484. 2, 3, 3, 6, 6, 7, 7, 9, 9, 4, 5, 5, 7, 7, 8, 8,
  144485. 10,10, 4, 5, 5, 7, 7, 8, 8,10,10, 6, 7, 7, 8, 8,
  144486. 9, 9,11,10, 6, 7, 7, 8, 8, 9, 9,10,10, 7, 8, 8,
  144487. 9, 9,10,10,11,11, 7, 8, 8, 9, 9,10,10,11,11, 9,
  144488. 10,10,11,10,11,11,12,12, 9,10,10,10,10,11,11,12,
  144489. 12,
  144490. };
  144491. static float _vq_quantthresh__44u3__p5_0[] = {
  144492. -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5, 3.5,
  144493. };
  144494. static long _vq_quantmap__44u3__p5_0[] = {
  144495. 7, 5, 3, 1, 0, 2, 4, 6,
  144496. 8,
  144497. };
  144498. static encode_aux_threshmatch _vq_auxt__44u3__p5_0 = {
  144499. _vq_quantthresh__44u3__p5_0,
  144500. _vq_quantmap__44u3__p5_0,
  144501. 9,
  144502. 9
  144503. };
  144504. static static_codebook _44u3__p5_0 = {
  144505. 2, 81,
  144506. _vq_lengthlist__44u3__p5_0,
  144507. 1, -531628032, 1611661312, 4, 0,
  144508. _vq_quantlist__44u3__p5_0,
  144509. NULL,
  144510. &_vq_auxt__44u3__p5_0,
  144511. NULL,
  144512. 0
  144513. };
  144514. static long _vq_quantlist__44u3__p6_0[] = {
  144515. 6,
  144516. 5,
  144517. 7,
  144518. 4,
  144519. 8,
  144520. 3,
  144521. 9,
  144522. 2,
  144523. 10,
  144524. 1,
  144525. 11,
  144526. 0,
  144527. 12,
  144528. };
  144529. static long _vq_lengthlist__44u3__p6_0[] = {
  144530. 1, 4, 4, 6, 6, 8, 8, 9, 9,10,11,13,14, 4, 6, 5,
  144531. 8, 8, 9, 9,10,10,11,11,14,14, 4, 6, 6, 8, 8, 9,
  144532. 9,10,10,11,11,14,14, 6, 8, 8, 9, 9,10,10,11,11,
  144533. 12,12,15,15, 6, 8, 8, 9, 9,10,11,11,11,12,12,15,
  144534. 15, 8, 9, 9,11,10,11,11,12,12,13,13,15,16, 8, 9,
  144535. 9,10,11,11,11,12,12,13,13,16,16,10,10,11,11,11,
  144536. 12,12,13,13,13,14,17,16, 9,10,11,12,11,12,12,13,
  144537. 13,13,13,16,18,11,12,11,12,12,13,13,13,14,15,14,
  144538. 17,17,11,11,12,12,12,13,13,13,14,14,15,18,17,14,
  144539. 15,15,15,15,16,16,17,17,19,18, 0,20,14,15,14,15,
  144540. 15,16,16,16,17,18,16,20,18,
  144541. };
  144542. static float _vq_quantthresh__44u3__p6_0[] = {
  144543. -27.5, -22.5, -17.5, -12.5, -7.5, -2.5, 2.5, 7.5,
  144544. 12.5, 17.5, 22.5, 27.5,
  144545. };
  144546. static long _vq_quantmap__44u3__p6_0[] = {
  144547. 11, 9, 7, 5, 3, 1, 0, 2,
  144548. 4, 6, 8, 10, 12,
  144549. };
  144550. static encode_aux_threshmatch _vq_auxt__44u3__p6_0 = {
  144551. _vq_quantthresh__44u3__p6_0,
  144552. _vq_quantmap__44u3__p6_0,
  144553. 13,
  144554. 13
  144555. };
  144556. static static_codebook _44u3__p6_0 = {
  144557. 2, 169,
  144558. _vq_lengthlist__44u3__p6_0,
  144559. 1, -526516224, 1616117760, 4, 0,
  144560. _vq_quantlist__44u3__p6_0,
  144561. NULL,
  144562. &_vq_auxt__44u3__p6_0,
  144563. NULL,
  144564. 0
  144565. };
  144566. static long _vq_quantlist__44u3__p6_1[] = {
  144567. 2,
  144568. 1,
  144569. 3,
  144570. 0,
  144571. 4,
  144572. };
  144573. static long _vq_lengthlist__44u3__p6_1[] = {
  144574. 2, 4, 4, 5, 5, 4, 5, 5, 6, 5, 4, 5, 5, 5, 6, 5,
  144575. 6, 5, 6, 6, 5, 5, 6, 6, 6,
  144576. };
  144577. static float _vq_quantthresh__44u3__p6_1[] = {
  144578. -1.5, -0.5, 0.5, 1.5,
  144579. };
  144580. static long _vq_quantmap__44u3__p6_1[] = {
  144581. 3, 1, 0, 2, 4,
  144582. };
  144583. static encode_aux_threshmatch _vq_auxt__44u3__p6_1 = {
  144584. _vq_quantthresh__44u3__p6_1,
  144585. _vq_quantmap__44u3__p6_1,
  144586. 5,
  144587. 5
  144588. };
  144589. static static_codebook _44u3__p6_1 = {
  144590. 2, 25,
  144591. _vq_lengthlist__44u3__p6_1,
  144592. 1, -533725184, 1611661312, 3, 0,
  144593. _vq_quantlist__44u3__p6_1,
  144594. NULL,
  144595. &_vq_auxt__44u3__p6_1,
  144596. NULL,
  144597. 0
  144598. };
  144599. static long _vq_quantlist__44u3__p7_0[] = {
  144600. 4,
  144601. 3,
  144602. 5,
  144603. 2,
  144604. 6,
  144605. 1,
  144606. 7,
  144607. 0,
  144608. 8,
  144609. };
  144610. static long _vq_lengthlist__44u3__p7_0[] = {
  144611. 1, 3, 3,10,10,10,10,10,10, 4,10,10,10,10,10,10,
  144612. 10,10, 4,10,10,10,10,10,10,10,10,10,10, 9, 9, 9,
  144613. 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,
  144614. 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,
  144615. 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,
  144616. 9,
  144617. };
  144618. static float _vq_quantthresh__44u3__p7_0[] = {
  144619. -892.5, -637.5, -382.5, -127.5, 127.5, 382.5, 637.5, 892.5,
  144620. };
  144621. static long _vq_quantmap__44u3__p7_0[] = {
  144622. 7, 5, 3, 1, 0, 2, 4, 6,
  144623. 8,
  144624. };
  144625. static encode_aux_threshmatch _vq_auxt__44u3__p7_0 = {
  144626. _vq_quantthresh__44u3__p7_0,
  144627. _vq_quantmap__44u3__p7_0,
  144628. 9,
  144629. 9
  144630. };
  144631. static static_codebook _44u3__p7_0 = {
  144632. 2, 81,
  144633. _vq_lengthlist__44u3__p7_0,
  144634. 1, -515907584, 1627381760, 4, 0,
  144635. _vq_quantlist__44u3__p7_0,
  144636. NULL,
  144637. &_vq_auxt__44u3__p7_0,
  144638. NULL,
  144639. 0
  144640. };
  144641. static long _vq_quantlist__44u3__p7_1[] = {
  144642. 7,
  144643. 6,
  144644. 8,
  144645. 5,
  144646. 9,
  144647. 4,
  144648. 10,
  144649. 3,
  144650. 11,
  144651. 2,
  144652. 12,
  144653. 1,
  144654. 13,
  144655. 0,
  144656. 14,
  144657. };
  144658. static long _vq_lengthlist__44u3__p7_1[] = {
  144659. 1, 4, 4, 6, 6, 7, 6, 8, 7, 9, 8,10, 9,11,11, 4,
  144660. 7, 7, 8, 7, 9, 9,10,10,11,11,11,11,12,12, 4, 7,
  144661. 7, 7, 7, 9, 9,10,10,11,11,12,12,12,11, 6, 8, 8,
  144662. 9, 9,10,10,11,11,12,12,13,12,13,13, 6, 8, 8, 9,
  144663. 9,10,11,11,11,12,12,13,14,13,13, 8, 9, 9,11,11,
  144664. 12,12,12,13,14,13,14,14,14,15, 8, 9, 9,11,11,11,
  144665. 12,13,14,13,14,15,17,14,15, 9,10,10,12,12,13,13,
  144666. 13,14,15,15,15,16,16,16, 9,11,11,12,12,13,13,14,
  144667. 14,14,15,16,16,16,16,10,12,12,13,13,14,14,15,15,
  144668. 15,16,17,17,17,17,10,12,11,13,13,15,14,15,14,16,
  144669. 17,16,16,16,16,11,13,12,14,14,14,14,15,16,17,16,
  144670. 17,17,17,17,11,13,12,14,14,14,15,17,16,17,17,17,
  144671. 17,17,17,12,13,13,15,16,15,16,17,17,16,16,17,17,
  144672. 17,17,12,13,13,15,15,15,16,17,17,17,16,17,16,17,
  144673. 17,
  144674. };
  144675. static float _vq_quantthresh__44u3__p7_1[] = {
  144676. -110.5, -93.5, -76.5, -59.5, -42.5, -25.5, -8.5, 8.5,
  144677. 25.5, 42.5, 59.5, 76.5, 93.5, 110.5,
  144678. };
  144679. static long _vq_quantmap__44u3__p7_1[] = {
  144680. 13, 11, 9, 7, 5, 3, 1, 0,
  144681. 2, 4, 6, 8, 10, 12, 14,
  144682. };
  144683. static encode_aux_threshmatch _vq_auxt__44u3__p7_1 = {
  144684. _vq_quantthresh__44u3__p7_1,
  144685. _vq_quantmap__44u3__p7_1,
  144686. 15,
  144687. 15
  144688. };
  144689. static static_codebook _44u3__p7_1 = {
  144690. 2, 225,
  144691. _vq_lengthlist__44u3__p7_1,
  144692. 1, -522338304, 1620115456, 4, 0,
  144693. _vq_quantlist__44u3__p7_1,
  144694. NULL,
  144695. &_vq_auxt__44u3__p7_1,
  144696. NULL,
  144697. 0
  144698. };
  144699. static long _vq_quantlist__44u3__p7_2[] = {
  144700. 8,
  144701. 7,
  144702. 9,
  144703. 6,
  144704. 10,
  144705. 5,
  144706. 11,
  144707. 4,
  144708. 12,
  144709. 3,
  144710. 13,
  144711. 2,
  144712. 14,
  144713. 1,
  144714. 15,
  144715. 0,
  144716. 16,
  144717. };
  144718. static long _vq_lengthlist__44u3__p7_2[] = {
  144719. 2, 5, 5, 7, 6, 7, 7, 8, 8, 8, 8, 9, 9, 9, 9, 9,
  144720. 9, 5, 6, 6, 7, 7, 8, 8, 8, 8, 9, 9, 9, 9, 9, 9,
  144721. 10,10, 5, 6, 6, 7, 7, 8, 8, 8, 8, 9, 8, 9, 9, 9,
  144722. 9,10, 9, 7, 7, 7, 8, 8, 8, 8, 9, 9, 9, 9, 9, 9,
  144723. 10,10,10,10, 7, 7, 7, 8, 8, 8, 8, 9, 9, 9, 9,10,
  144724. 9,10,10,10,10, 7, 8, 8, 8, 8, 9, 9, 9, 9, 9, 9,
  144725. 10,10,10,10,10,10, 7, 8, 8, 9, 8, 9, 9, 9, 9,10,
  144726. 9,10,10,10,10,10,10, 8, 8, 8, 9, 9, 9, 9, 9, 9,
  144727. 9,10,10,10,10,10,10,10, 8, 9, 8, 9, 9, 9, 9,10,
  144728. 9,10,10,10,10,10,10,10,10, 9, 9, 9, 9, 9, 9,10,
  144729. 9,10,10,10,10,10,10,10,10,10, 9, 9, 9, 9, 9,10,
  144730. 9,10,10,10,10,10,10,10,10,10,10, 9, 9, 9,10, 9,
  144731. 10,10,10,10,10,10,10,10,10,10,10,10, 9, 9, 9,10,
  144732. 10,10,10,10,10,10,10,10,10,10,10,10,10, 9, 9, 9,
  144733. 10,10,10,10,10,10,10,10,10,10,10,10,10,11, 9,10,
  144734. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,11, 9,
  144735. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  144736. 9,10,10,10,10,10,10,10,10,10,10,10,11,11,11,10,
  144737. 11,
  144738. };
  144739. static float _vq_quantthresh__44u3__p7_2[] = {
  144740. -7.5, -6.5, -5.5, -4.5, -3.5, -2.5, -1.5, -0.5,
  144741. 0.5, 1.5, 2.5, 3.5, 4.5, 5.5, 6.5, 7.5,
  144742. };
  144743. static long _vq_quantmap__44u3__p7_2[] = {
  144744. 15, 13, 11, 9, 7, 5, 3, 1,
  144745. 0, 2, 4, 6, 8, 10, 12, 14,
  144746. 16,
  144747. };
  144748. static encode_aux_threshmatch _vq_auxt__44u3__p7_2 = {
  144749. _vq_quantthresh__44u3__p7_2,
  144750. _vq_quantmap__44u3__p7_2,
  144751. 17,
  144752. 17
  144753. };
  144754. static static_codebook _44u3__p7_2 = {
  144755. 2, 289,
  144756. _vq_lengthlist__44u3__p7_2,
  144757. 1, -529530880, 1611661312, 5, 0,
  144758. _vq_quantlist__44u3__p7_2,
  144759. NULL,
  144760. &_vq_auxt__44u3__p7_2,
  144761. NULL,
  144762. 0
  144763. };
  144764. static long _huff_lengthlist__44u3__short[] = {
  144765. 14,14,14,15,13,15,12,16,10, 8, 7, 9, 9, 8,12,16,
  144766. 10, 5, 4, 6, 5, 6, 9,16,14, 8, 6, 8, 7, 8,10,16,
  144767. 14, 7, 4, 6, 3, 5, 8,16,15, 9, 5, 7, 4, 4, 7,16,
  144768. 13,10, 6, 7, 4, 3, 4,13,13,12, 7, 9, 5, 5, 6,12,
  144769. };
  144770. static static_codebook _huff_book__44u3__short = {
  144771. 2, 64,
  144772. _huff_lengthlist__44u3__short,
  144773. 0, 0, 0, 0, 0,
  144774. NULL,
  144775. NULL,
  144776. NULL,
  144777. NULL,
  144778. 0
  144779. };
  144780. static long _huff_lengthlist__44u4__long[] = {
  144781. 3, 8,12,12,13,12,11,13, 5, 4, 6, 7, 8, 8, 9,13,
  144782. 9, 5, 4, 5, 5, 7, 9,13, 9, 6, 5, 6, 6, 7, 8,12,
  144783. 12, 7, 5, 6, 4, 5, 8,13,11, 7, 6, 6, 5, 5, 6,12,
  144784. 10, 8, 8, 7, 7, 5, 3, 8,10,12,13,12,12, 9, 6, 7,
  144785. };
  144786. static static_codebook _huff_book__44u4__long = {
  144787. 2, 64,
  144788. _huff_lengthlist__44u4__long,
  144789. 0, 0, 0, 0, 0,
  144790. NULL,
  144791. NULL,
  144792. NULL,
  144793. NULL,
  144794. 0
  144795. };
  144796. static long _vq_quantlist__44u4__p1_0[] = {
  144797. 1,
  144798. 0,
  144799. 2,
  144800. };
  144801. static long _vq_lengthlist__44u4__p1_0[] = {
  144802. 1, 4, 4, 5, 8, 7, 5, 7, 8, 5, 8, 8, 8,10,11, 8,
  144803. 10,11, 5, 8, 8, 8,11,10, 8,11,11, 4, 8, 8, 8,11,
  144804. 11, 8,11,11, 8,11,11,11,13,14,11,15,14, 8,11,11,
  144805. 10,13,12,11,14,14, 4, 8, 8, 8,11,11, 8,11,11, 7,
  144806. 11,11,11,15,14,10,12,14, 8,11,11,11,14,14,11,14,
  144807. 13,
  144808. };
  144809. static float _vq_quantthresh__44u4__p1_0[] = {
  144810. -0.5, 0.5,
  144811. };
  144812. static long _vq_quantmap__44u4__p1_0[] = {
  144813. 1, 0, 2,
  144814. };
  144815. static encode_aux_threshmatch _vq_auxt__44u4__p1_0 = {
  144816. _vq_quantthresh__44u4__p1_0,
  144817. _vq_quantmap__44u4__p1_0,
  144818. 3,
  144819. 3
  144820. };
  144821. static static_codebook _44u4__p1_0 = {
  144822. 4, 81,
  144823. _vq_lengthlist__44u4__p1_0,
  144824. 1, -535822336, 1611661312, 2, 0,
  144825. _vq_quantlist__44u4__p1_0,
  144826. NULL,
  144827. &_vq_auxt__44u4__p1_0,
  144828. NULL,
  144829. 0
  144830. };
  144831. static long _vq_quantlist__44u4__p2_0[] = {
  144832. 1,
  144833. 0,
  144834. 2,
  144835. };
  144836. static long _vq_lengthlist__44u4__p2_0[] = {
  144837. 2, 5, 5, 5, 6, 6, 5, 6, 6, 5, 6, 6, 7, 8, 8, 6,
  144838. 8, 8, 5, 6, 6, 6, 8, 8, 7, 8, 8, 5, 7, 6, 6, 8,
  144839. 8, 6, 8, 8, 6, 8, 8, 8, 9,10, 8,10,10, 6, 8, 8,
  144840. 8,10, 8, 8,10,10, 5, 6, 6, 6, 8, 8, 6, 8, 8, 6,
  144841. 8, 8, 8,10,10, 8, 8,10, 6, 8, 8, 8,10,10, 8,10,
  144842. 9,
  144843. };
  144844. static float _vq_quantthresh__44u4__p2_0[] = {
  144845. -0.5, 0.5,
  144846. };
  144847. static long _vq_quantmap__44u4__p2_0[] = {
  144848. 1, 0, 2,
  144849. };
  144850. static encode_aux_threshmatch _vq_auxt__44u4__p2_0 = {
  144851. _vq_quantthresh__44u4__p2_0,
  144852. _vq_quantmap__44u4__p2_0,
  144853. 3,
  144854. 3
  144855. };
  144856. static static_codebook _44u4__p2_0 = {
  144857. 4, 81,
  144858. _vq_lengthlist__44u4__p2_0,
  144859. 1, -535822336, 1611661312, 2, 0,
  144860. _vq_quantlist__44u4__p2_0,
  144861. NULL,
  144862. &_vq_auxt__44u4__p2_0,
  144863. NULL,
  144864. 0
  144865. };
  144866. static long _vq_quantlist__44u4__p3_0[] = {
  144867. 2,
  144868. 1,
  144869. 3,
  144870. 0,
  144871. 4,
  144872. };
  144873. static long _vq_lengthlist__44u4__p3_0[] = {
  144874. 2, 4, 4, 8, 8, 5, 7, 7, 9, 9, 5, 7, 7, 9, 9, 8,
  144875. 10, 9,12,12, 8, 9,10,12,12, 5, 7, 7,10,10, 7, 9,
  144876. 9,11,11, 7, 9, 9,11,11,10,12,11,14,14, 9,10,11,
  144877. 13,14, 5, 7, 7,10,10, 7, 9, 9,11,11, 7, 9, 9,11,
  144878. 11, 9,11,10,14,13,10,11,11,14,14, 8,10,10,14,13,
  144879. 10,12,12,15,14, 9,11,11,15,14,13,14,14,17,17,12,
  144880. 14,14,16,16, 8,10,10,14,14, 9,11,11,14,15,10,12,
  144881. 12,14,15,12,14,13,16,16,13,14,15,15,18, 4, 7, 7,
  144882. 10,10, 7, 9, 9,12,11, 7, 9, 9,11,12,10,12,11,15,
  144883. 14,10,11,12,14,15, 7, 9, 9,12,12, 9,11,12,13,13,
  144884. 9,11,12,13,13,12,13,13,15,16,11,13,13,15,16, 7,
  144885. 9, 9,12,12, 9,11,10,13,12, 9,11,12,13,14,11,13,
  144886. 12,16,14,12,13,13,15,16,10,12,12,16,15,11,13,13,
  144887. 17,16,11,13,13,17,16,14,15,15,17,17,14,16,16,18,
  144888. 20, 9,11,11,15,16,11,13,12,16,16,11,13,13,16,17,
  144889. 14,15,14,18,16,14,16,16,17,20, 5, 7, 7,10,10, 7,
  144890. 9, 9,12,11, 7, 9,10,11,12,10,12,11,15,15,10,12,
  144891. 12,14,14, 7, 9, 9,12,12, 9,12,11,14,13, 9,10,11,
  144892. 12,13,12,13,14,16,16,11,12,13,14,16, 7, 9, 9,12,
  144893. 12, 9,12,11,13,13, 9,12,11,13,13,11,13,13,16,16,
  144894. 12,13,13,16,15, 9,11,11,16,14,11,13,13,16,16,11,
  144895. 12,13,16,16,14,16,16,17,17,13,14,15,16,17,10,12,
  144896. 12,15,15,11,13,13,16,17,11,13,13,16,16,14,16,15,
  144897. 19,19,14,15,15,17,18, 8,10,10,14,14,10,12,12,15,
  144898. 15,10,12,12,16,16,14,16,15,20,19,13,15,15,17,16,
  144899. 9,12,12,16,16,11,13,13,16,18,11,14,13,16,17,16,
  144900. 17,16,20, 0,15,16,18,18,20, 9,11,11,15,15,11,14,
  144901. 12,17,16,11,13,13,17,17,15,17,15,20,20,14,16,16,
  144902. 17, 0,13,15,14,18,16,14,15,16, 0,18,14,16,16, 0,
  144903. 0,18,16, 0, 0,20,16,18,18, 0, 0,12,14,14,17,18,
  144904. 13,15,14,20,18,14,16,15,19,19,16,20,16, 0,18,16,
  144905. 19,17,19, 0, 8,10,10,14,14,10,12,12,16,15,10,12,
  144906. 12,16,16,13,15,15,18,17,14,16,16,19, 0, 9,11,11,
  144907. 16,15,11,14,13,18,17,11,12,13,17,18,14,17,16,18,
  144908. 18,15,16,17,18,18, 9,12,12,16,16,11,13,13,16,18,
  144909. 11,14,13,17,17,15,16,16,18,20,16,17,17,20,20,12,
  144910. 14,14,18,17,14,16,16, 0,19,13,14,15,18, 0,16, 0,
  144911. 0, 0, 0,16,16, 0,19,20,13,15,14, 0, 0,14,16,16,
  144912. 18,19,14,16,15, 0,20,16,20,18, 0,20,17,20,17, 0,
  144913. 0,
  144914. };
  144915. static float _vq_quantthresh__44u4__p3_0[] = {
  144916. -1.5, -0.5, 0.5, 1.5,
  144917. };
  144918. static long _vq_quantmap__44u4__p3_0[] = {
  144919. 3, 1, 0, 2, 4,
  144920. };
  144921. static encode_aux_threshmatch _vq_auxt__44u4__p3_0 = {
  144922. _vq_quantthresh__44u4__p3_0,
  144923. _vq_quantmap__44u4__p3_0,
  144924. 5,
  144925. 5
  144926. };
  144927. static static_codebook _44u4__p3_0 = {
  144928. 4, 625,
  144929. _vq_lengthlist__44u4__p3_0,
  144930. 1, -533725184, 1611661312, 3, 0,
  144931. _vq_quantlist__44u4__p3_0,
  144932. NULL,
  144933. &_vq_auxt__44u4__p3_0,
  144934. NULL,
  144935. 0
  144936. };
  144937. static long _vq_quantlist__44u4__p4_0[] = {
  144938. 2,
  144939. 1,
  144940. 3,
  144941. 0,
  144942. 4,
  144943. };
  144944. static long _vq_lengthlist__44u4__p4_0[] = {
  144945. 4, 5, 5, 8, 8, 5, 7, 6, 9, 9, 5, 6, 7, 9, 9, 9,
  144946. 9, 9,11,11, 8, 9, 9,11,11, 5, 7, 7, 9, 9, 7, 8,
  144947. 8,10,10, 7, 7, 8,10,10, 9,10,10,11,12, 9,10,10,
  144948. 11,12, 5, 7, 7, 9, 9, 7, 8, 7,10,10, 7, 8, 8,10,
  144949. 10, 9,10,10,12,11, 9,10,10,12,11, 9,10, 9,12,12,
  144950. 9,10,10,13,12, 9,10,10,12,12,12,12,12,14,14,11,
  144951. 12,12,13,14, 9, 9,10,12,12, 9,10,10,13,13, 9,10,
  144952. 10,12,13,11,12,12,14,13,11,12,12,14,14, 5, 7, 7,
  144953. 9, 9, 7, 8, 8,10,10, 7, 8, 8,10,10,10,10,10,12,
  144954. 12, 9,10,10,12,12, 7, 8, 8,11,10, 8, 8, 9,11,11,
  144955. 8, 9, 9,11,11,11,11,11,12,13,10,11,11,13,13, 6,
  144956. 8, 8,10,10, 7, 9, 8,11,10, 8, 9, 9,11,11,10,11,
  144957. 10,13,11,10,11,11,13,13, 9,11,10,13,12,10,11,11,
  144958. 13,14,10,11,11,14,13,12,12,13,12,15,12,13,13,15,
  144959. 15, 9,10,10,12,13,10,11,10,13,12,10,11,11,13,14,
  144960. 12,13,11,15,13,13,13,13,15,15, 5, 7, 7, 9, 9, 7,
  144961. 8, 8,10,10, 7, 8, 8,10,10, 9,10,10,12,12,10,10,
  144962. 11,12,13, 6, 8, 8,10,10, 8, 9, 9,11,11, 7, 8, 9,
  144963. 10,11,10,11,11,13,13,10,10,11,11,13, 7, 8, 8,10,
  144964. 11, 8, 9, 9,11,11, 8, 9, 8,11,11,10,11,11,13,13,
  144965. 11,12,11,13,12, 9,10,10,13,12,10,11,11,14,13,10,
  144966. 10,11,12,13,12,13,13,15,15,12,11,13,13,14, 9,10,
  144967. 11,12,13,10,11,11,13,14,10,11,11,13,13,12,13,13,
  144968. 15,15,12,13,12,15,12, 8, 9, 9,12,12, 9,11,10,13,
  144969. 13, 9,10,10,13,13,12,13,13,15,15,12,12,12,14,14,
  144970. 9,10,10,13,13,10,11,11,13,14,10,11,11,14,13,13,
  144971. 13,14,14,16,13,13,13,15,15, 9,10,10,13,13,10,11,
  144972. 10,14,13,10,11,11,13,14,12,14,13,16,14,12,13,13,
  144973. 14,15,11,12,12,15,14,11,12,13,14,15,12,13,13,16,
  144974. 15,14,12,15,12,16,14,15,15,16,16,11,12,12,14,14,
  144975. 11,13,12,15,14,12,13,13,15,16,13,15,13,17,13,14,
  144976. 15,15,16,17, 8, 9, 9,12,12, 9,10,10,12,13, 9,10,
  144977. 10,13,13,12,12,12,14,14,12,13,13,15,15, 9,10,10,
  144978. 13,12,10,11,11,14,13,10,10,11,13,14,13,13,13,15,
  144979. 15,12,13,14,14,16, 9,10,10,13,13,10,11,11,13,14,
  144980. 10,11,11,14,14,13,13,13,15,15,13,14,13,16,14,11,
  144981. 12,12,15,14,12,13,13,16,15,11,12,13,14,15,14,15,
  144982. 15,17,16,13,13,15,13,16,11,12,13,14,15,13,13,13,
  144983. 15,16,11,13,12,15,14,14,15,15,16,16,14,15,12,17,
  144984. 13,
  144985. };
  144986. static float _vq_quantthresh__44u4__p4_0[] = {
  144987. -1.5, -0.5, 0.5, 1.5,
  144988. };
  144989. static long _vq_quantmap__44u4__p4_0[] = {
  144990. 3, 1, 0, 2, 4,
  144991. };
  144992. static encode_aux_threshmatch _vq_auxt__44u4__p4_0 = {
  144993. _vq_quantthresh__44u4__p4_0,
  144994. _vq_quantmap__44u4__p4_0,
  144995. 5,
  144996. 5
  144997. };
  144998. static static_codebook _44u4__p4_0 = {
  144999. 4, 625,
  145000. _vq_lengthlist__44u4__p4_0,
  145001. 1, -533725184, 1611661312, 3, 0,
  145002. _vq_quantlist__44u4__p4_0,
  145003. NULL,
  145004. &_vq_auxt__44u4__p4_0,
  145005. NULL,
  145006. 0
  145007. };
  145008. static long _vq_quantlist__44u4__p5_0[] = {
  145009. 4,
  145010. 3,
  145011. 5,
  145012. 2,
  145013. 6,
  145014. 1,
  145015. 7,
  145016. 0,
  145017. 8,
  145018. };
  145019. static long _vq_lengthlist__44u4__p5_0[] = {
  145020. 2, 3, 3, 6, 6, 7, 7, 9, 9, 4, 5, 5, 7, 7, 8, 8,
  145021. 10, 9, 4, 5, 5, 7, 7, 8, 8,10,10, 6, 7, 7, 8, 8,
  145022. 9, 9,11,10, 6, 7, 7, 8, 8, 9, 9,10,11, 7, 8, 8,
  145023. 9, 9,10,10,11,11, 7, 8, 8, 9, 9,10,10,11,11, 9,
  145024. 10,10,11,10,11,11,12,12, 9,10,10,10,11,11,11,12,
  145025. 12,
  145026. };
  145027. static float _vq_quantthresh__44u4__p5_0[] = {
  145028. -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5, 3.5,
  145029. };
  145030. static long _vq_quantmap__44u4__p5_0[] = {
  145031. 7, 5, 3, 1, 0, 2, 4, 6,
  145032. 8,
  145033. };
  145034. static encode_aux_threshmatch _vq_auxt__44u4__p5_0 = {
  145035. _vq_quantthresh__44u4__p5_0,
  145036. _vq_quantmap__44u4__p5_0,
  145037. 9,
  145038. 9
  145039. };
  145040. static static_codebook _44u4__p5_0 = {
  145041. 2, 81,
  145042. _vq_lengthlist__44u4__p5_0,
  145043. 1, -531628032, 1611661312, 4, 0,
  145044. _vq_quantlist__44u4__p5_0,
  145045. NULL,
  145046. &_vq_auxt__44u4__p5_0,
  145047. NULL,
  145048. 0
  145049. };
  145050. static long _vq_quantlist__44u4__p6_0[] = {
  145051. 6,
  145052. 5,
  145053. 7,
  145054. 4,
  145055. 8,
  145056. 3,
  145057. 9,
  145058. 2,
  145059. 10,
  145060. 1,
  145061. 11,
  145062. 0,
  145063. 12,
  145064. };
  145065. static long _vq_lengthlist__44u4__p6_0[] = {
  145066. 1, 4, 4, 6, 6, 8, 8, 9, 9,11,10,13,13, 4, 6, 5,
  145067. 8, 8, 9, 9,10,10,11,11,14,14, 4, 6, 6, 8, 8, 9,
  145068. 9,10,10,11,11,14,14, 6, 8, 8, 9, 9,10,10,11,11,
  145069. 12,12,15,15, 6, 8, 8, 9, 9,10,11,11,11,12,12,15,
  145070. 15, 8, 9, 9,11,10,11,11,12,12,13,13,16,16, 8, 9,
  145071. 9,10,10,11,11,12,12,13,13,16,16,10,10,10,12,11,
  145072. 12,12,13,13,14,14,16,16,10,10,10,11,12,12,12,13,
  145073. 13,13,14,16,17,11,12,11,12,12,13,13,14,14,15,14,
  145074. 18,17,11,11,12,12,12,13,13,14,14,14,15,19,18,14,
  145075. 15,14,15,15,17,16,17,17,17,17,21, 0,14,15,15,16,
  145076. 16,16,16,17,17,18,17,20,21,
  145077. };
  145078. static float _vq_quantthresh__44u4__p6_0[] = {
  145079. -27.5, -22.5, -17.5, -12.5, -7.5, -2.5, 2.5, 7.5,
  145080. 12.5, 17.5, 22.5, 27.5,
  145081. };
  145082. static long _vq_quantmap__44u4__p6_0[] = {
  145083. 11, 9, 7, 5, 3, 1, 0, 2,
  145084. 4, 6, 8, 10, 12,
  145085. };
  145086. static encode_aux_threshmatch _vq_auxt__44u4__p6_0 = {
  145087. _vq_quantthresh__44u4__p6_0,
  145088. _vq_quantmap__44u4__p6_0,
  145089. 13,
  145090. 13
  145091. };
  145092. static static_codebook _44u4__p6_0 = {
  145093. 2, 169,
  145094. _vq_lengthlist__44u4__p6_0,
  145095. 1, -526516224, 1616117760, 4, 0,
  145096. _vq_quantlist__44u4__p6_0,
  145097. NULL,
  145098. &_vq_auxt__44u4__p6_0,
  145099. NULL,
  145100. 0
  145101. };
  145102. static long _vq_quantlist__44u4__p6_1[] = {
  145103. 2,
  145104. 1,
  145105. 3,
  145106. 0,
  145107. 4,
  145108. };
  145109. static long _vq_lengthlist__44u4__p6_1[] = {
  145110. 2, 4, 4, 5, 5, 4, 5, 5, 6, 5, 4, 5, 5, 5, 6, 5,
  145111. 6, 5, 6, 6, 5, 5, 6, 6, 6,
  145112. };
  145113. static float _vq_quantthresh__44u4__p6_1[] = {
  145114. -1.5, -0.5, 0.5, 1.5,
  145115. };
  145116. static long _vq_quantmap__44u4__p6_1[] = {
  145117. 3, 1, 0, 2, 4,
  145118. };
  145119. static encode_aux_threshmatch _vq_auxt__44u4__p6_1 = {
  145120. _vq_quantthresh__44u4__p6_1,
  145121. _vq_quantmap__44u4__p6_1,
  145122. 5,
  145123. 5
  145124. };
  145125. static static_codebook _44u4__p6_1 = {
  145126. 2, 25,
  145127. _vq_lengthlist__44u4__p6_1,
  145128. 1, -533725184, 1611661312, 3, 0,
  145129. _vq_quantlist__44u4__p6_1,
  145130. NULL,
  145131. &_vq_auxt__44u4__p6_1,
  145132. NULL,
  145133. 0
  145134. };
  145135. static long _vq_quantlist__44u4__p7_0[] = {
  145136. 6,
  145137. 5,
  145138. 7,
  145139. 4,
  145140. 8,
  145141. 3,
  145142. 9,
  145143. 2,
  145144. 10,
  145145. 1,
  145146. 11,
  145147. 0,
  145148. 12,
  145149. };
  145150. static long _vq_lengthlist__44u4__p7_0[] = {
  145151. 1, 3, 3,12,12,12,12,12,12,12,12,12,12, 3,12,11,
  145152. 12,12,12,12,12,12,12,12,12,12, 4,11,10,12,12,12,
  145153. 12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,
  145154. 12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,
  145155. 12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,
  145156. 12,12,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  145157. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  145158. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  145159. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  145160. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  145161. 11,11,11,11,11,11,11,11,11,
  145162. };
  145163. static float _vq_quantthresh__44u4__p7_0[] = {
  145164. -1402.5, -1147.5, -892.5, -637.5, -382.5, -127.5, 127.5, 382.5,
  145165. 637.5, 892.5, 1147.5, 1402.5,
  145166. };
  145167. static long _vq_quantmap__44u4__p7_0[] = {
  145168. 11, 9, 7, 5, 3, 1, 0, 2,
  145169. 4, 6, 8, 10, 12,
  145170. };
  145171. static encode_aux_threshmatch _vq_auxt__44u4__p7_0 = {
  145172. _vq_quantthresh__44u4__p7_0,
  145173. _vq_quantmap__44u4__p7_0,
  145174. 13,
  145175. 13
  145176. };
  145177. static static_codebook _44u4__p7_0 = {
  145178. 2, 169,
  145179. _vq_lengthlist__44u4__p7_0,
  145180. 1, -514332672, 1627381760, 4, 0,
  145181. _vq_quantlist__44u4__p7_0,
  145182. NULL,
  145183. &_vq_auxt__44u4__p7_0,
  145184. NULL,
  145185. 0
  145186. };
  145187. static long _vq_quantlist__44u4__p7_1[] = {
  145188. 7,
  145189. 6,
  145190. 8,
  145191. 5,
  145192. 9,
  145193. 4,
  145194. 10,
  145195. 3,
  145196. 11,
  145197. 2,
  145198. 12,
  145199. 1,
  145200. 13,
  145201. 0,
  145202. 14,
  145203. };
  145204. static long _vq_lengthlist__44u4__p7_1[] = {
  145205. 1, 4, 4, 6, 6, 7, 7, 9, 8,10, 8,10, 9,11,11, 4,
  145206. 7, 6, 8, 7, 9, 9,10,10,11,10,11,10,12,10, 4, 6,
  145207. 7, 8, 8, 9, 9,10,10,11,11,11,11,12,12, 6, 8, 8,
  145208. 10, 9,11,10,12,11,12,12,12,12,13,13, 6, 8, 8,10,
  145209. 10,10,11,11,11,12,12,13,12,13,13, 8, 9, 9,11,11,
  145210. 12,11,12,12,13,13,13,13,13,13, 8, 9, 9,11,11,11,
  145211. 12,12,12,13,13,13,13,13,13, 9,10,10,12,11,13,13,
  145212. 13,13,14,13,13,14,14,14, 9,10,11,11,12,12,13,13,
  145213. 13,13,13,14,15,14,14,10,11,11,12,12,13,13,14,14,
  145214. 14,14,14,15,16,16,10,11,11,12,13,13,13,13,15,14,
  145215. 14,15,16,15,16,10,12,12,13,13,14,14,14,15,15,15,
  145216. 15,15,15,16,11,12,12,13,13,14,14,14,15,15,15,16,
  145217. 15,17,16,11,12,12,13,13,13,15,15,14,16,16,16,16,
  145218. 16,17,11,12,12,13,13,14,14,15,14,15,15,17,17,16,
  145219. 16,
  145220. };
  145221. static float _vq_quantthresh__44u4__p7_1[] = {
  145222. -110.5, -93.5, -76.5, -59.5, -42.5, -25.5, -8.5, 8.5,
  145223. 25.5, 42.5, 59.5, 76.5, 93.5, 110.5,
  145224. };
  145225. static long _vq_quantmap__44u4__p7_1[] = {
  145226. 13, 11, 9, 7, 5, 3, 1, 0,
  145227. 2, 4, 6, 8, 10, 12, 14,
  145228. };
  145229. static encode_aux_threshmatch _vq_auxt__44u4__p7_1 = {
  145230. _vq_quantthresh__44u4__p7_1,
  145231. _vq_quantmap__44u4__p7_1,
  145232. 15,
  145233. 15
  145234. };
  145235. static static_codebook _44u4__p7_1 = {
  145236. 2, 225,
  145237. _vq_lengthlist__44u4__p7_1,
  145238. 1, -522338304, 1620115456, 4, 0,
  145239. _vq_quantlist__44u4__p7_1,
  145240. NULL,
  145241. &_vq_auxt__44u4__p7_1,
  145242. NULL,
  145243. 0
  145244. };
  145245. static long _vq_quantlist__44u4__p7_2[] = {
  145246. 8,
  145247. 7,
  145248. 9,
  145249. 6,
  145250. 10,
  145251. 5,
  145252. 11,
  145253. 4,
  145254. 12,
  145255. 3,
  145256. 13,
  145257. 2,
  145258. 14,
  145259. 1,
  145260. 15,
  145261. 0,
  145262. 16,
  145263. };
  145264. static long _vq_lengthlist__44u4__p7_2[] = {
  145265. 2, 5, 5, 7, 7, 7, 7, 8, 8, 8, 8, 9, 9, 9, 9, 9,
  145266. 9, 5, 6, 6, 7, 7, 8, 8, 8, 8, 9, 9, 9, 9, 9, 9,
  145267. 9, 9, 5, 6, 6, 7, 7, 8, 8, 8, 8, 9, 9, 9, 9, 9,
  145268. 9, 9, 9, 7, 7, 7, 8, 8, 8, 8, 9, 9, 9, 9, 9, 9,
  145269. 10,10,10,10, 7, 7, 7, 8, 8, 8, 8, 9, 9, 9, 9,10,
  145270. 9,10, 9,10,10, 7, 8, 8, 8, 8, 9, 9, 9, 9, 9, 9,
  145271. 10,10,10,10,10,10, 7, 8, 8, 8, 8, 9, 9, 9, 9, 9,
  145272. 9,10,10,10,10,10,10, 8, 9, 8, 9, 9, 9, 9, 9, 9,
  145273. 10,10,10,10,10,10,10,10, 8, 8, 8, 9, 9, 9, 9, 9,
  145274. 10,10,10,10,10,10,10,10,10, 9, 9, 9, 9, 9,10,10,
  145275. 10,10,10,10,10,10,10,10,10,10, 9, 9, 9, 9, 9,10,
  145276. 10,10,10,10,10,10,10,10,10,10,10, 9, 9, 9, 9,10,
  145277. 10,10,10,10,10,10,10,10,10,10,10,10, 9, 9, 9, 9,
  145278. 10,10,10,10,10,10,10,10,10,11,10,10,10, 9, 9, 9,
  145279. 10,10,10,10,10,10,10,10,10,10,10,10,10,10, 9, 9,
  145280. 9,10,10,10,10,10,10,10,10,10,10,10,10,10,10, 9,
  145281. 10, 9,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  145282. 9,10, 9,10,10,10,10,10,10,10,10,10,10,11,10,10,
  145283. 10,
  145284. };
  145285. static float _vq_quantthresh__44u4__p7_2[] = {
  145286. -7.5, -6.5, -5.5, -4.5, -3.5, -2.5, -1.5, -0.5,
  145287. 0.5, 1.5, 2.5, 3.5, 4.5, 5.5, 6.5, 7.5,
  145288. };
  145289. static long _vq_quantmap__44u4__p7_2[] = {
  145290. 15, 13, 11, 9, 7, 5, 3, 1,
  145291. 0, 2, 4, 6, 8, 10, 12, 14,
  145292. 16,
  145293. };
  145294. static encode_aux_threshmatch _vq_auxt__44u4__p7_2 = {
  145295. _vq_quantthresh__44u4__p7_2,
  145296. _vq_quantmap__44u4__p7_2,
  145297. 17,
  145298. 17
  145299. };
  145300. static static_codebook _44u4__p7_2 = {
  145301. 2, 289,
  145302. _vq_lengthlist__44u4__p7_2,
  145303. 1, -529530880, 1611661312, 5, 0,
  145304. _vq_quantlist__44u4__p7_2,
  145305. NULL,
  145306. &_vq_auxt__44u4__p7_2,
  145307. NULL,
  145308. 0
  145309. };
  145310. static long _huff_lengthlist__44u4__short[] = {
  145311. 14,17,15,17,16,14,13,16,10, 7, 7,10,13,10,15,16,
  145312. 9, 4, 4, 6, 5, 7, 9,16,12, 8, 7, 8, 8, 8,11,16,
  145313. 14, 7, 4, 6, 3, 5, 8,15,13, 8, 5, 7, 4, 5, 7,16,
  145314. 12, 9, 6, 8, 3, 3, 5,16,14,13, 7,10, 5, 5, 7,15,
  145315. };
  145316. static static_codebook _huff_book__44u4__short = {
  145317. 2, 64,
  145318. _huff_lengthlist__44u4__short,
  145319. 0, 0, 0, 0, 0,
  145320. NULL,
  145321. NULL,
  145322. NULL,
  145323. NULL,
  145324. 0
  145325. };
  145326. static long _huff_lengthlist__44u5__long[] = {
  145327. 3, 8,13,12,14,12,16,11,13,14, 5, 4, 5, 6, 7, 8,
  145328. 10, 9,12,15,10, 5, 5, 5, 6, 8, 9, 9,13,15,10, 5,
  145329. 5, 6, 6, 7, 8, 8,11,13,12, 7, 5, 6, 4, 6, 7, 7,
  145330. 11,14,11, 7, 7, 6, 6, 6, 7, 6,10,14,14, 9, 8, 8,
  145331. 6, 7, 7, 7,11,16,11, 8, 8, 7, 6, 6, 7, 4, 7,12,
  145332. 10,10,12,10,10, 9,10, 5, 6, 9,10,12,15,13,14,14,
  145333. 14, 8, 7, 8,
  145334. };
  145335. static static_codebook _huff_book__44u5__long = {
  145336. 2, 100,
  145337. _huff_lengthlist__44u5__long,
  145338. 0, 0, 0, 0, 0,
  145339. NULL,
  145340. NULL,
  145341. NULL,
  145342. NULL,
  145343. 0
  145344. };
  145345. static long _vq_quantlist__44u5__p1_0[] = {
  145346. 1,
  145347. 0,
  145348. 2,
  145349. };
  145350. static long _vq_lengthlist__44u5__p1_0[] = {
  145351. 1, 4, 4, 5, 8, 7, 5, 7, 7, 5, 8, 8, 8,10,10, 7,
  145352. 9,10, 5, 8, 8, 7,10, 9, 8,10,10, 5, 8, 8, 8,10,
  145353. 10, 8,10,10, 8,10,10,10,12,13,10,13,13, 7,10,10,
  145354. 10,13,11,10,13,13, 4, 8, 8, 8,11,10, 8,10,10, 7,
  145355. 10,10,10,13,13,10,11,13, 8,10,11,10,13,13,10,13,
  145356. 12,
  145357. };
  145358. static float _vq_quantthresh__44u5__p1_0[] = {
  145359. -0.5, 0.5,
  145360. };
  145361. static long _vq_quantmap__44u5__p1_0[] = {
  145362. 1, 0, 2,
  145363. };
  145364. static encode_aux_threshmatch _vq_auxt__44u5__p1_0 = {
  145365. _vq_quantthresh__44u5__p1_0,
  145366. _vq_quantmap__44u5__p1_0,
  145367. 3,
  145368. 3
  145369. };
  145370. static static_codebook _44u5__p1_0 = {
  145371. 4, 81,
  145372. _vq_lengthlist__44u5__p1_0,
  145373. 1, -535822336, 1611661312, 2, 0,
  145374. _vq_quantlist__44u5__p1_0,
  145375. NULL,
  145376. &_vq_auxt__44u5__p1_0,
  145377. NULL,
  145378. 0
  145379. };
  145380. static long _vq_quantlist__44u5__p2_0[] = {
  145381. 1,
  145382. 0,
  145383. 2,
  145384. };
  145385. static long _vq_lengthlist__44u5__p2_0[] = {
  145386. 3, 4, 4, 5, 6, 6, 5, 6, 6, 5, 6, 6, 6, 8, 8, 6,
  145387. 7, 8, 5, 6, 6, 6, 8, 7, 6, 8, 8, 5, 6, 6, 6, 8,
  145388. 8, 6, 8, 8, 6, 8, 8, 8, 9, 9, 8, 9, 9, 6, 8, 7,
  145389. 7, 9, 8, 8, 9, 9, 5, 6, 6, 6, 8, 7, 6, 8, 8, 6,
  145390. 8, 7, 8, 9, 9, 7, 8, 9, 6, 8, 8, 8, 9, 9, 8, 9,
  145391. 9,
  145392. };
  145393. static float _vq_quantthresh__44u5__p2_0[] = {
  145394. -0.5, 0.5,
  145395. };
  145396. static long _vq_quantmap__44u5__p2_0[] = {
  145397. 1, 0, 2,
  145398. };
  145399. static encode_aux_threshmatch _vq_auxt__44u5__p2_0 = {
  145400. _vq_quantthresh__44u5__p2_0,
  145401. _vq_quantmap__44u5__p2_0,
  145402. 3,
  145403. 3
  145404. };
  145405. static static_codebook _44u5__p2_0 = {
  145406. 4, 81,
  145407. _vq_lengthlist__44u5__p2_0,
  145408. 1, -535822336, 1611661312, 2, 0,
  145409. _vq_quantlist__44u5__p2_0,
  145410. NULL,
  145411. &_vq_auxt__44u5__p2_0,
  145412. NULL,
  145413. 0
  145414. };
  145415. static long _vq_quantlist__44u5__p3_0[] = {
  145416. 2,
  145417. 1,
  145418. 3,
  145419. 0,
  145420. 4,
  145421. };
  145422. static long _vq_lengthlist__44u5__p3_0[] = {
  145423. 2, 4, 5, 8, 8, 5, 7, 6, 9, 9, 5, 6, 7, 9, 9, 8,
  145424. 10, 9,13,12, 8, 9,10,12,12, 5, 7, 7,10,10, 7, 9,
  145425. 9,11,11, 6, 8, 9,11,11,10,11,11,14,14, 9,10,11,
  145426. 13,14, 5, 7, 7, 9,10, 7, 9, 8,11,11, 7, 9, 9,11,
  145427. 11, 9,11,10,14,13,10,11,11,14,14, 8,10,10,13,13,
  145428. 10,11,11,15,14, 9,11,11,14,14,13,14,14,17,16,12,
  145429. 13,13,15,16, 8,10,10,13,13, 9,11,11,14,15,10,11,
  145430. 11,14,15,12,14,13,16,16,13,15,14,15,17, 5, 7, 7,
  145431. 10,10, 7, 9, 9,11,11, 7, 9, 9,11,11,10,11,11,14,
  145432. 14,10,11,12,14,14, 7, 9, 9,12,11, 9,11,11,13,13,
  145433. 9,11,11,13,13,12,13,13,15,16,11,12,13,15,16, 6,
  145434. 9, 9,11,11, 8,11,10,13,12, 9,11,11,13,14,11,13,
  145435. 12,16,14,11,13,13,16,17,10,12,11,15,15,11,13,13,
  145436. 16,16,11,13,13,17,16,14,15,15,17,17,14,16,16,17,
  145437. 18, 9,11,11,14,15,10,12,12,15,15,11,13,13,16,17,
  145438. 13,15,13,17,15,14,15,16,18, 0, 5, 7, 7,10,10, 7,
  145439. 9, 9,11,11, 7, 9, 9,11,11,10,11,11,14,14,10,11,
  145440. 12,14,15, 6, 9, 9,12,11, 9,11,11,13,13, 8,10,11,
  145441. 12,13,11,13,13,16,15,11,12,13,14,15, 7, 9, 9,11,
  145442. 12, 9,11,11,13,13, 9,11,11,13,13,11,13,13,15,16,
  145443. 11,13,13,15,14, 9,11,11,15,14,11,13,13,17,15,10,
  145444. 12,12,15,15,14,16,16,17,17,13,13,15,15,17,10,11,
  145445. 12,15,15,11,13,13,16,16,11,13,13,15,15,14,15,15,
  145446. 18,18,14,15,15,17,17, 8,10,10,13,13,10,12,11,15,
  145447. 15,10,11,12,15,15,14,15,15,18,18,13,14,14,18,18,
  145448. 9,11,11,15,16,11,13,13,17,17,11,13,13,16,16,15,
  145449. 15,16,17, 0,14,15,17, 0, 0, 9,11,11,15,15,10,13,
  145450. 12,18,16,11,13,13,15,16,14,16,15,20,20,14,15,16,
  145451. 17, 0,13,14,14,20,16,14,15,16,19,18,14,15,15,19,
  145452. 0,18,16, 0,20,20,16,18,18, 0, 0,12,14,14,18,18,
  145453. 13,15,14,18,16,14,15,16,18,20,16,19,16, 0,17,17,
  145454. 18,18,19, 0, 8,10,10,14,14,10,11,11,14,15,10,11,
  145455. 12,15,15,13,15,14,19,17,13,15,15,17, 0, 9,11,11,
  145456. 16,15,11,13,13,16,16,10,12,13,15,17,14,16,16,18,
  145457. 18,14,15,15,18, 0, 9,11,11,15,15,11,13,13,16,17,
  145458. 11,13,13,18,17,14,18,16,18,18,15,17,17,18, 0,12,
  145459. 14,14,18,18,14,15,15,20, 0,13,14,15,17, 0,16,18,
  145460. 17, 0, 0,16,16, 0,17,20,12,14,14,18,18,14,16,15,
  145461. 0,18,14,16,15,18, 0,16,19,17, 0, 0,17,18,16, 0,
  145462. 0,
  145463. };
  145464. static float _vq_quantthresh__44u5__p3_0[] = {
  145465. -1.5, -0.5, 0.5, 1.5,
  145466. };
  145467. static long _vq_quantmap__44u5__p3_0[] = {
  145468. 3, 1, 0, 2, 4,
  145469. };
  145470. static encode_aux_threshmatch _vq_auxt__44u5__p3_0 = {
  145471. _vq_quantthresh__44u5__p3_0,
  145472. _vq_quantmap__44u5__p3_0,
  145473. 5,
  145474. 5
  145475. };
  145476. static static_codebook _44u5__p3_0 = {
  145477. 4, 625,
  145478. _vq_lengthlist__44u5__p3_0,
  145479. 1, -533725184, 1611661312, 3, 0,
  145480. _vq_quantlist__44u5__p3_0,
  145481. NULL,
  145482. &_vq_auxt__44u5__p3_0,
  145483. NULL,
  145484. 0
  145485. };
  145486. static long _vq_quantlist__44u5__p4_0[] = {
  145487. 2,
  145488. 1,
  145489. 3,
  145490. 0,
  145491. 4,
  145492. };
  145493. static long _vq_lengthlist__44u5__p4_0[] = {
  145494. 4, 5, 5, 8, 8, 6, 7, 6, 9, 9, 6, 6, 7, 9, 9, 8,
  145495. 9, 9,11,11, 8, 9, 9,11,11, 6, 7, 7, 9, 9, 7, 8,
  145496. 8,10,10, 6, 7, 8, 9,10, 9,10,10,11,12, 9, 9,10,
  145497. 11,12, 6, 7, 7, 9, 9, 6, 8, 7,10, 9, 7, 8, 8,10,
  145498. 10, 9,10, 9,12,11, 9,10,10,12,11, 8, 9, 9,12,11,
  145499. 9,10,10,12,12, 9,10,10,12,12,11,12,12,13,14,11,
  145500. 11,12,13,14, 8, 9, 9,11,12, 9,10,10,12,12, 9,10,
  145501. 10,12,12,11,12,11,14,13,11,12,12,13,13, 5, 7, 7,
  145502. 9, 9, 7, 8, 8,10,10, 7, 8, 8,10,10, 9,10,10,12,
  145503. 12, 9,10,10,12,12, 7, 8, 8,10,10, 8, 8, 9,10,11,
  145504. 8, 9, 9,11,11,10,10,11,11,13,10,11,11,12,13, 6,
  145505. 7, 8,10,10, 7, 9, 8,11,10, 8, 9, 9,11,11,10,11,
  145506. 10,13,11,10,11,11,12,12, 9,10,10,12,12,10,10,11,
  145507. 12,13,10,11,11,13,13,12,11,13,12,15,12,13,13,14,
  145508. 15, 9,10,10,12,12, 9,11,10,13,12,10,11,11,13,13,
  145509. 11,13,11,14,12,12,13,13,14,15, 5, 7, 7, 9, 9, 7,
  145510. 8, 8,10,10, 7, 8, 8,10,10, 9,10,10,12,12, 9,10,
  145511. 10,12,12, 6, 8, 7,10,10, 8, 9, 9,11,11, 7, 8, 9,
  145512. 10,11,10,11,11,12,12,10,10,11,11,13, 7, 8, 8,10,
  145513. 10, 8, 9, 9,11,11, 8, 9, 8,11,10,10,11,11,13,12,
  145514. 10,11,10,13,11, 9,10,10,12,12,10,11,11,13,12, 9,
  145515. 10,10,12,13,12,13,13,14,15,11,11,13,12,14, 9,10,
  145516. 10,12,12,10,11,11,13,13,10,11,10,13,12,12,13,13,
  145517. 14,14,12,13,11,14,12, 8, 9, 9,12,12, 9,10,10,12,
  145518. 12, 9,10,10,12,12,12,12,12,14,14,11,12,12,14,13,
  145519. 9,10,10,12,12,10,11,11,13,13,10,11,11,13,12,12,
  145520. 12,13,14,15,12,13,13,15,14, 9,10,10,12,12,10,11,
  145521. 10,13,12,10,11,11,12,13,12,13,12,15,13,12,13,13,
  145522. 14,15,11,12,12,14,13,11,12,12,14,15,12,13,13,15,
  145523. 14,13,12,14,12,16,13,14,14,15,15,11,11,12,14,14,
  145524. 11,12,11,14,13,12,13,13,14,15,13,14,12,16,12,14,
  145525. 14,15,16,16, 8, 9, 9,11,12, 9,10,10,12,12, 9,10,
  145526. 10,12,13,11,12,12,13,13,12,12,13,14,14, 9,10,10,
  145527. 12,12,10,11,10,13,12,10,10,11,12,13,12,13,13,15,
  145528. 14,12,12,13,13,15, 9,10,10,12,13,10,11,11,12,13,
  145529. 10,11,11,13,13,12,13,13,14,15,12,13,12,15,14,11,
  145530. 12,11,14,13,12,13,13,15,14,11,11,12,13,14,14,15,
  145531. 14,16,15,13,12,14,13,16,11,12,12,13,14,12,13,13,
  145532. 14,15,11,12,11,14,14,14,14,14,15,16,13,15,12,16,
  145533. 12,
  145534. };
  145535. static float _vq_quantthresh__44u5__p4_0[] = {
  145536. -1.5, -0.5, 0.5, 1.5,
  145537. };
  145538. static long _vq_quantmap__44u5__p4_0[] = {
  145539. 3, 1, 0, 2, 4,
  145540. };
  145541. static encode_aux_threshmatch _vq_auxt__44u5__p4_0 = {
  145542. _vq_quantthresh__44u5__p4_0,
  145543. _vq_quantmap__44u5__p4_0,
  145544. 5,
  145545. 5
  145546. };
  145547. static static_codebook _44u5__p4_0 = {
  145548. 4, 625,
  145549. _vq_lengthlist__44u5__p4_0,
  145550. 1, -533725184, 1611661312, 3, 0,
  145551. _vq_quantlist__44u5__p4_0,
  145552. NULL,
  145553. &_vq_auxt__44u5__p4_0,
  145554. NULL,
  145555. 0
  145556. };
  145557. static long _vq_quantlist__44u5__p5_0[] = {
  145558. 4,
  145559. 3,
  145560. 5,
  145561. 2,
  145562. 6,
  145563. 1,
  145564. 7,
  145565. 0,
  145566. 8,
  145567. };
  145568. static long _vq_lengthlist__44u5__p5_0[] = {
  145569. 2, 3, 3, 6, 6, 8, 8,10,10, 4, 5, 5, 8, 7, 8, 8,
  145570. 11,10, 3, 5, 5, 7, 8, 8, 8,10,11, 6, 8, 7,10, 9,
  145571. 10,10,11,11, 6, 7, 8, 9, 9, 9,10,11,12, 8, 8, 8,
  145572. 10,10,11,11,13,12, 8, 8, 9, 9,10,11,11,12,13,10,
  145573. 11,10,12,11,13,12,14,14,10,10,11,11,12,12,13,14,
  145574. 14,
  145575. };
  145576. static float _vq_quantthresh__44u5__p5_0[] = {
  145577. -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5, 3.5,
  145578. };
  145579. static long _vq_quantmap__44u5__p5_0[] = {
  145580. 7, 5, 3, 1, 0, 2, 4, 6,
  145581. 8,
  145582. };
  145583. static encode_aux_threshmatch _vq_auxt__44u5__p5_0 = {
  145584. _vq_quantthresh__44u5__p5_0,
  145585. _vq_quantmap__44u5__p5_0,
  145586. 9,
  145587. 9
  145588. };
  145589. static static_codebook _44u5__p5_0 = {
  145590. 2, 81,
  145591. _vq_lengthlist__44u5__p5_0,
  145592. 1, -531628032, 1611661312, 4, 0,
  145593. _vq_quantlist__44u5__p5_0,
  145594. NULL,
  145595. &_vq_auxt__44u5__p5_0,
  145596. NULL,
  145597. 0
  145598. };
  145599. static long _vq_quantlist__44u5__p6_0[] = {
  145600. 4,
  145601. 3,
  145602. 5,
  145603. 2,
  145604. 6,
  145605. 1,
  145606. 7,
  145607. 0,
  145608. 8,
  145609. };
  145610. static long _vq_lengthlist__44u5__p6_0[] = {
  145611. 3, 4, 4, 5, 5, 7, 7, 9, 9, 4, 5, 4, 6, 6, 7, 7,
  145612. 9, 9, 4, 4, 5, 6, 6, 7, 7, 9, 9, 5, 6, 6, 7, 7,
  145613. 8, 8,10,10, 6, 6, 6, 7, 7, 8, 8,10,10, 7, 7, 7,
  145614. 8, 8, 9, 9,11,10, 7, 7, 7, 8, 8, 9, 9,10,11, 9,
  145615. 9, 9,10,10,11,10,11,11, 9, 9, 9,10,10,11,10,11,
  145616. 11,
  145617. };
  145618. static float _vq_quantthresh__44u5__p6_0[] = {
  145619. -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5, 3.5,
  145620. };
  145621. static long _vq_quantmap__44u5__p6_0[] = {
  145622. 7, 5, 3, 1, 0, 2, 4, 6,
  145623. 8,
  145624. };
  145625. static encode_aux_threshmatch _vq_auxt__44u5__p6_0 = {
  145626. _vq_quantthresh__44u5__p6_0,
  145627. _vq_quantmap__44u5__p6_0,
  145628. 9,
  145629. 9
  145630. };
  145631. static static_codebook _44u5__p6_0 = {
  145632. 2, 81,
  145633. _vq_lengthlist__44u5__p6_0,
  145634. 1, -531628032, 1611661312, 4, 0,
  145635. _vq_quantlist__44u5__p6_0,
  145636. NULL,
  145637. &_vq_auxt__44u5__p6_0,
  145638. NULL,
  145639. 0
  145640. };
  145641. static long _vq_quantlist__44u5__p7_0[] = {
  145642. 1,
  145643. 0,
  145644. 2,
  145645. };
  145646. static long _vq_lengthlist__44u5__p7_0[] = {
  145647. 1, 4, 4, 5, 7, 7, 5, 7, 7, 5, 9, 9, 8,11,10, 7,
  145648. 11,10, 5, 9, 9, 7,10,10, 8,10,11, 4, 9, 9, 9,12,
  145649. 12, 9,12,12, 8,12,12,11,12,12,10,12,13, 7,12,12,
  145650. 11,12,12,10,12,13, 4, 9, 9, 9,12,12, 9,12,12, 7,
  145651. 12,11,10,13,13,11,12,12, 7,12,12,10,13,13,11,12,
  145652. 12,
  145653. };
  145654. static float _vq_quantthresh__44u5__p7_0[] = {
  145655. -5.5, 5.5,
  145656. };
  145657. static long _vq_quantmap__44u5__p7_0[] = {
  145658. 1, 0, 2,
  145659. };
  145660. static encode_aux_threshmatch _vq_auxt__44u5__p7_0 = {
  145661. _vq_quantthresh__44u5__p7_0,
  145662. _vq_quantmap__44u5__p7_0,
  145663. 3,
  145664. 3
  145665. };
  145666. static static_codebook _44u5__p7_0 = {
  145667. 4, 81,
  145668. _vq_lengthlist__44u5__p7_0,
  145669. 1, -529137664, 1618345984, 2, 0,
  145670. _vq_quantlist__44u5__p7_0,
  145671. NULL,
  145672. &_vq_auxt__44u5__p7_0,
  145673. NULL,
  145674. 0
  145675. };
  145676. static long _vq_quantlist__44u5__p7_1[] = {
  145677. 5,
  145678. 4,
  145679. 6,
  145680. 3,
  145681. 7,
  145682. 2,
  145683. 8,
  145684. 1,
  145685. 9,
  145686. 0,
  145687. 10,
  145688. };
  145689. static long _vq_lengthlist__44u5__p7_1[] = {
  145690. 2, 4, 4, 6, 6, 7, 7, 8, 8, 8, 8, 4, 5, 5, 7, 7,
  145691. 8, 8, 9, 8, 8, 9, 4, 5, 5, 7, 7, 8, 8, 9, 9, 8,
  145692. 9, 6, 7, 7, 8, 8, 9, 8, 9, 9, 9, 9, 6, 7, 7, 8,
  145693. 8, 9, 9, 9, 9, 9, 9, 7, 8, 8, 9, 9, 9, 9, 9, 9,
  145694. 9, 9, 7, 8, 8, 9, 9, 9, 9, 9, 9, 9, 9, 8, 9, 9,
  145695. 9, 9, 9, 9,10,10,10,10, 8, 9, 9, 9, 9, 9, 9,10,
  145696. 10,10,10, 8, 9, 9, 9, 9, 9, 9,10,10,10,10, 8, 9,
  145697. 9, 9, 9, 9, 9,10,10,10,10,
  145698. };
  145699. static float _vq_quantthresh__44u5__p7_1[] = {
  145700. -4.5, -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5,
  145701. 3.5, 4.5,
  145702. };
  145703. static long _vq_quantmap__44u5__p7_1[] = {
  145704. 9, 7, 5, 3, 1, 0, 2, 4,
  145705. 6, 8, 10,
  145706. };
  145707. static encode_aux_threshmatch _vq_auxt__44u5__p7_1 = {
  145708. _vq_quantthresh__44u5__p7_1,
  145709. _vq_quantmap__44u5__p7_1,
  145710. 11,
  145711. 11
  145712. };
  145713. static static_codebook _44u5__p7_1 = {
  145714. 2, 121,
  145715. _vq_lengthlist__44u5__p7_1,
  145716. 1, -531365888, 1611661312, 4, 0,
  145717. _vq_quantlist__44u5__p7_1,
  145718. NULL,
  145719. &_vq_auxt__44u5__p7_1,
  145720. NULL,
  145721. 0
  145722. };
  145723. static long _vq_quantlist__44u5__p8_0[] = {
  145724. 5,
  145725. 4,
  145726. 6,
  145727. 3,
  145728. 7,
  145729. 2,
  145730. 8,
  145731. 1,
  145732. 9,
  145733. 0,
  145734. 10,
  145735. };
  145736. static long _vq_lengthlist__44u5__p8_0[] = {
  145737. 1, 4, 4, 6, 6, 8, 8, 9, 9,10,10, 4, 6, 6, 7, 7,
  145738. 9, 9,10,10,11,11, 4, 6, 6, 7, 7, 9, 9,10,10,11,
  145739. 11, 6, 8, 7, 9, 9,10,10,11,11,13,12, 6, 8, 8, 9,
  145740. 9,10,10,11,11,12,13, 8, 9, 9,10,10,12,12,13,12,
  145741. 14,13, 8, 9, 9,10,10,12,12,13,13,14,14, 9,11,11,
  145742. 12,12,13,13,14,14,15,14, 9,11,11,12,12,13,13,14,
  145743. 14,15,14,11,12,12,13,13,14,14,15,14,15,14,11,11,
  145744. 12,13,13,14,14,14,14,15,15,
  145745. };
  145746. static float _vq_quantthresh__44u5__p8_0[] = {
  145747. -49.5, -38.5, -27.5, -16.5, -5.5, 5.5, 16.5, 27.5,
  145748. 38.5, 49.5,
  145749. };
  145750. static long _vq_quantmap__44u5__p8_0[] = {
  145751. 9, 7, 5, 3, 1, 0, 2, 4,
  145752. 6, 8, 10,
  145753. };
  145754. static encode_aux_threshmatch _vq_auxt__44u5__p8_0 = {
  145755. _vq_quantthresh__44u5__p8_0,
  145756. _vq_quantmap__44u5__p8_0,
  145757. 11,
  145758. 11
  145759. };
  145760. static static_codebook _44u5__p8_0 = {
  145761. 2, 121,
  145762. _vq_lengthlist__44u5__p8_0,
  145763. 1, -524582912, 1618345984, 4, 0,
  145764. _vq_quantlist__44u5__p8_0,
  145765. NULL,
  145766. &_vq_auxt__44u5__p8_0,
  145767. NULL,
  145768. 0
  145769. };
  145770. static long _vq_quantlist__44u5__p8_1[] = {
  145771. 5,
  145772. 4,
  145773. 6,
  145774. 3,
  145775. 7,
  145776. 2,
  145777. 8,
  145778. 1,
  145779. 9,
  145780. 0,
  145781. 10,
  145782. };
  145783. static long _vq_lengthlist__44u5__p8_1[] = {
  145784. 3, 5, 5, 6, 6, 7, 7, 7, 7, 7, 7, 5, 6, 5, 7, 6,
  145785. 7, 7, 8, 8, 8, 8, 5, 5, 5, 6, 6, 7, 7, 8, 8, 8,
  145786. 8, 6, 7, 6, 7, 7, 8, 8, 8, 8, 8, 8, 6, 6, 7, 7,
  145787. 7, 8, 8, 8, 8, 8, 8, 7, 7, 7, 8, 8, 8, 8, 8, 8,
  145788. 8, 8, 7, 7, 7, 8, 8, 8, 8, 8, 8, 8, 8, 7, 8, 8,
  145789. 8, 8, 8, 8, 8, 8, 8, 8, 7, 8, 8, 8, 8, 8, 8, 8,
  145790. 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8,
  145791. 8, 8, 8, 8, 8, 8, 8, 8, 8,
  145792. };
  145793. static float _vq_quantthresh__44u5__p8_1[] = {
  145794. -4.5, -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5,
  145795. 3.5, 4.5,
  145796. };
  145797. static long _vq_quantmap__44u5__p8_1[] = {
  145798. 9, 7, 5, 3, 1, 0, 2, 4,
  145799. 6, 8, 10,
  145800. };
  145801. static encode_aux_threshmatch _vq_auxt__44u5__p8_1 = {
  145802. _vq_quantthresh__44u5__p8_1,
  145803. _vq_quantmap__44u5__p8_1,
  145804. 11,
  145805. 11
  145806. };
  145807. static static_codebook _44u5__p8_1 = {
  145808. 2, 121,
  145809. _vq_lengthlist__44u5__p8_1,
  145810. 1, -531365888, 1611661312, 4, 0,
  145811. _vq_quantlist__44u5__p8_1,
  145812. NULL,
  145813. &_vq_auxt__44u5__p8_1,
  145814. NULL,
  145815. 0
  145816. };
  145817. static long _vq_quantlist__44u5__p9_0[] = {
  145818. 6,
  145819. 5,
  145820. 7,
  145821. 4,
  145822. 8,
  145823. 3,
  145824. 9,
  145825. 2,
  145826. 10,
  145827. 1,
  145828. 11,
  145829. 0,
  145830. 12,
  145831. };
  145832. static long _vq_lengthlist__44u5__p9_0[] = {
  145833. 1, 3, 2,12,10,13,13,13,13,13,13,13,13, 4, 9, 9,
  145834. 13,13,13,13,13,13,13,13,13,13, 5,10, 9,13,13,13,
  145835. 13,13,13,13,13,13,13,12,13,13,13,13,13,13,13,13,
  145836. 13,13,13,13,11,13,13,13,13,13,13,13,13,13,13,13,
  145837. 13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,
  145838. 13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,
  145839. 13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,
  145840. 13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,
  145841. 13,13,13,13,13,13,13,13,13,13,13,13,13,12,12,12,
  145842. 12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,
  145843. 12,12,12,12,12,12,12,12,12,
  145844. };
  145845. static float _vq_quantthresh__44u5__p9_0[] = {
  145846. -1402.5, -1147.5, -892.5, -637.5, -382.5, -127.5, 127.5, 382.5,
  145847. 637.5, 892.5, 1147.5, 1402.5,
  145848. };
  145849. static long _vq_quantmap__44u5__p9_0[] = {
  145850. 11, 9, 7, 5, 3, 1, 0, 2,
  145851. 4, 6, 8, 10, 12,
  145852. };
  145853. static encode_aux_threshmatch _vq_auxt__44u5__p9_0 = {
  145854. _vq_quantthresh__44u5__p9_0,
  145855. _vq_quantmap__44u5__p9_0,
  145856. 13,
  145857. 13
  145858. };
  145859. static static_codebook _44u5__p9_0 = {
  145860. 2, 169,
  145861. _vq_lengthlist__44u5__p9_0,
  145862. 1, -514332672, 1627381760, 4, 0,
  145863. _vq_quantlist__44u5__p9_0,
  145864. NULL,
  145865. &_vq_auxt__44u5__p9_0,
  145866. NULL,
  145867. 0
  145868. };
  145869. static long _vq_quantlist__44u5__p9_1[] = {
  145870. 7,
  145871. 6,
  145872. 8,
  145873. 5,
  145874. 9,
  145875. 4,
  145876. 10,
  145877. 3,
  145878. 11,
  145879. 2,
  145880. 12,
  145881. 1,
  145882. 13,
  145883. 0,
  145884. 14,
  145885. };
  145886. static long _vq_lengthlist__44u5__p9_1[] = {
  145887. 1, 4, 4, 7, 7, 8, 8, 8, 7, 8, 7, 9, 8, 9, 9, 4,
  145888. 7, 6, 9, 8,10,10, 9, 8, 9, 9, 9, 9, 9, 8, 5, 6,
  145889. 6, 8, 9,10,10, 9, 9, 9,10,10,10,10,11, 7, 8, 8,
  145890. 10,10,11,11,10,10,11,11,11,12,11,11, 7, 8, 8,10,
  145891. 10,11,11,10,10,11,11,12,11,11,11, 8, 9, 9,11,11,
  145892. 12,12,11,11,12,11,12,12,12,12, 8, 9,10,11,11,12,
  145893. 12,11,11,12,12,12,12,12,12, 8, 9, 9,10,10,12,11,
  145894. 12,12,12,12,12,12,12,13, 8, 9, 9,11,11,11,11,12,
  145895. 12,12,12,13,12,13,13, 9,10,10,11,11,12,12,12,13,
  145896. 12,13,13,13,14,13, 9,10,10,11,11,12,12,12,13,13,
  145897. 12,13,13,14,13, 9,11,10,12,11,13,12,12,13,13,13,
  145898. 13,13,13,14, 9,10,10,12,12,12,12,12,13,13,13,13,
  145899. 13,14,14,10,11,11,12,12,12,13,13,13,14,14,13,14,
  145900. 14,14,10,11,11,12,12,12,12,13,12,13,14,13,14,14,
  145901. 14,
  145902. };
  145903. static float _vq_quantthresh__44u5__p9_1[] = {
  145904. -110.5, -93.5, -76.5, -59.5, -42.5, -25.5, -8.5, 8.5,
  145905. 25.5, 42.5, 59.5, 76.5, 93.5, 110.5,
  145906. };
  145907. static long _vq_quantmap__44u5__p9_1[] = {
  145908. 13, 11, 9, 7, 5, 3, 1, 0,
  145909. 2, 4, 6, 8, 10, 12, 14,
  145910. };
  145911. static encode_aux_threshmatch _vq_auxt__44u5__p9_1 = {
  145912. _vq_quantthresh__44u5__p9_1,
  145913. _vq_quantmap__44u5__p9_1,
  145914. 15,
  145915. 15
  145916. };
  145917. static static_codebook _44u5__p9_1 = {
  145918. 2, 225,
  145919. _vq_lengthlist__44u5__p9_1,
  145920. 1, -522338304, 1620115456, 4, 0,
  145921. _vq_quantlist__44u5__p9_1,
  145922. NULL,
  145923. &_vq_auxt__44u5__p9_1,
  145924. NULL,
  145925. 0
  145926. };
  145927. static long _vq_quantlist__44u5__p9_2[] = {
  145928. 8,
  145929. 7,
  145930. 9,
  145931. 6,
  145932. 10,
  145933. 5,
  145934. 11,
  145935. 4,
  145936. 12,
  145937. 3,
  145938. 13,
  145939. 2,
  145940. 14,
  145941. 1,
  145942. 15,
  145943. 0,
  145944. 16,
  145945. };
  145946. static long _vq_lengthlist__44u5__p9_2[] = {
  145947. 2, 5, 5, 7, 7, 8, 8, 8, 8, 8, 8, 9, 9, 9, 9, 9,
  145948. 9, 5, 6, 6, 7, 7, 8, 8, 9, 8, 9, 9, 9, 9, 9, 9,
  145949. 9, 9, 5, 6, 6, 7, 7, 8, 8, 9, 8, 9, 9, 9, 9, 9,
  145950. 9, 9, 9, 7, 7, 7, 8, 8, 9, 8, 9, 9, 9, 9, 9, 9,
  145951. 9, 9, 9, 9, 7, 7, 7, 8, 8, 9, 8, 9, 9, 9, 9, 9,
  145952. 9, 9, 9, 9, 9, 8, 8, 8, 8, 9, 9, 9, 9, 9, 9, 9,
  145953. 9,10, 9,10,10,10, 8, 8, 8, 9, 8, 9, 9, 9, 9, 9,
  145954. 9, 9,10, 9,10, 9,10, 8, 9, 9, 9, 9, 9, 9, 9, 9,
  145955. 9,10, 9,10,10,10,10,10, 8, 9, 9, 9, 9, 9, 9,10,
  145956. 9,10, 9,10,10,10,10,10,10, 9, 9, 9, 9, 9,10, 9,
  145957. 10,10,10,10,10,10,10,10,10,10, 9, 9, 9, 9, 9, 9,
  145958. 9,10, 9,10, 9,10,10,10,10,10,10, 9, 9, 9, 9, 9,
  145959. 10,10,10,10,10,10,10,10,10,10,10,10, 9, 9, 9, 9,
  145960. 9, 9,10,10,10,10,10,10,10,10,10,10,10, 9, 9, 9,
  145961. 9,10,10, 9,10,10,10,10,10,10,10,10,10,10, 9, 9,
  145962. 9, 9, 9,10,10,10,10,10,10,10,10,10,10,10,10, 9,
  145963. 9, 9, 9, 9,10,10,10,10,10,10,10,10,10,10,10,10,
  145964. 9, 9, 9,10, 9,10,10,10,10,10,10,10,10,10,10,10,
  145965. 10,
  145966. };
  145967. static float _vq_quantthresh__44u5__p9_2[] = {
  145968. -7.5, -6.5, -5.5, -4.5, -3.5, -2.5, -1.5, -0.5,
  145969. 0.5, 1.5, 2.5, 3.5, 4.5, 5.5, 6.5, 7.5,
  145970. };
  145971. static long _vq_quantmap__44u5__p9_2[] = {
  145972. 15, 13, 11, 9, 7, 5, 3, 1,
  145973. 0, 2, 4, 6, 8, 10, 12, 14,
  145974. 16,
  145975. };
  145976. static encode_aux_threshmatch _vq_auxt__44u5__p9_2 = {
  145977. _vq_quantthresh__44u5__p9_2,
  145978. _vq_quantmap__44u5__p9_2,
  145979. 17,
  145980. 17
  145981. };
  145982. static static_codebook _44u5__p9_2 = {
  145983. 2, 289,
  145984. _vq_lengthlist__44u5__p9_2,
  145985. 1, -529530880, 1611661312, 5, 0,
  145986. _vq_quantlist__44u5__p9_2,
  145987. NULL,
  145988. &_vq_auxt__44u5__p9_2,
  145989. NULL,
  145990. 0
  145991. };
  145992. static long _huff_lengthlist__44u5__short[] = {
  145993. 4,10,17,13,17,13,17,17,17,17, 3, 6, 8, 9,11, 9,
  145994. 15,12,16,17, 6, 5, 5, 7, 7, 8,10,11,17,17, 7, 8,
  145995. 7, 9, 9,10,13,13,17,17, 8, 6, 5, 7, 4, 7, 5, 8,
  145996. 14,17, 9, 9, 8, 9, 7, 9, 8,10,16,17,12,10, 7, 8,
  145997. 4, 7, 4, 7,16,17,12,11, 9,10, 6, 9, 5, 7,14,17,
  145998. 14,13,10,15, 4, 8, 3, 5,14,17,17,14,11,15, 6,10,
  145999. 6, 8,15,17,
  146000. };
  146001. static static_codebook _huff_book__44u5__short = {
  146002. 2, 100,
  146003. _huff_lengthlist__44u5__short,
  146004. 0, 0, 0, 0, 0,
  146005. NULL,
  146006. NULL,
  146007. NULL,
  146008. NULL,
  146009. 0
  146010. };
  146011. static long _huff_lengthlist__44u6__long[] = {
  146012. 3, 9,14,13,14,13,16,12,13,14, 5, 4, 6, 6, 8, 9,
  146013. 11,10,12,15,10, 5, 5, 6, 6, 8,10,10,13,16,10, 6,
  146014. 6, 6, 6, 8, 9, 9,12,14,13, 7, 6, 6, 4, 6, 6, 7,
  146015. 11,14,10, 7, 7, 7, 6, 6, 6, 7,10,13,15,10, 9, 8,
  146016. 5, 6, 5, 6,10,14,10, 9, 8, 8, 6, 6, 5, 4, 6,11,
  146017. 11,11,12,11,10, 9, 9, 5, 5, 9,10,12,15,13,13,13,
  146018. 13, 8, 7, 7,
  146019. };
  146020. static static_codebook _huff_book__44u6__long = {
  146021. 2, 100,
  146022. _huff_lengthlist__44u6__long,
  146023. 0, 0, 0, 0, 0,
  146024. NULL,
  146025. NULL,
  146026. NULL,
  146027. NULL,
  146028. 0
  146029. };
  146030. static long _vq_quantlist__44u6__p1_0[] = {
  146031. 1,
  146032. 0,
  146033. 2,
  146034. };
  146035. static long _vq_lengthlist__44u6__p1_0[] = {
  146036. 1, 4, 4, 4, 8, 7, 5, 7, 7, 5, 8, 8, 8,10,10, 7,
  146037. 9,10, 5, 8, 8, 7,10, 9, 8,10,10, 5, 8, 8, 8,10,
  146038. 10, 8,10,10, 8,10,10,10,12,13,10,13,13, 7,10,10,
  146039. 10,13,11,10,13,13, 5, 8, 8, 8,11,10, 8,10,10, 7,
  146040. 10,10,10,13,13,10,11,13, 8,10,11,10,13,13,10,13,
  146041. 12,
  146042. };
  146043. static float _vq_quantthresh__44u6__p1_0[] = {
  146044. -0.5, 0.5,
  146045. };
  146046. static long _vq_quantmap__44u6__p1_0[] = {
  146047. 1, 0, 2,
  146048. };
  146049. static encode_aux_threshmatch _vq_auxt__44u6__p1_0 = {
  146050. _vq_quantthresh__44u6__p1_0,
  146051. _vq_quantmap__44u6__p1_0,
  146052. 3,
  146053. 3
  146054. };
  146055. static static_codebook _44u6__p1_0 = {
  146056. 4, 81,
  146057. _vq_lengthlist__44u6__p1_0,
  146058. 1, -535822336, 1611661312, 2, 0,
  146059. _vq_quantlist__44u6__p1_0,
  146060. NULL,
  146061. &_vq_auxt__44u6__p1_0,
  146062. NULL,
  146063. 0
  146064. };
  146065. static long _vq_quantlist__44u6__p2_0[] = {
  146066. 1,
  146067. 0,
  146068. 2,
  146069. };
  146070. static long _vq_lengthlist__44u6__p2_0[] = {
  146071. 3, 4, 4, 5, 6, 6, 5, 6, 6, 5, 6, 6, 6, 8, 8, 6,
  146072. 7, 8, 5, 6, 6, 6, 8, 7, 6, 8, 8, 5, 6, 6, 6, 8,
  146073. 8, 6, 8, 8, 6, 8, 8, 8, 9, 9, 8, 9, 9, 6, 7, 7,
  146074. 7, 9, 8, 8, 9, 9, 5, 6, 6, 6, 8, 7, 6, 8, 8, 6,
  146075. 8, 8, 8, 9, 9, 7, 8, 9, 6, 8, 8, 8, 9, 9, 8, 9,
  146076. 9,
  146077. };
  146078. static float _vq_quantthresh__44u6__p2_0[] = {
  146079. -0.5, 0.5,
  146080. };
  146081. static long _vq_quantmap__44u6__p2_0[] = {
  146082. 1, 0, 2,
  146083. };
  146084. static encode_aux_threshmatch _vq_auxt__44u6__p2_0 = {
  146085. _vq_quantthresh__44u6__p2_0,
  146086. _vq_quantmap__44u6__p2_0,
  146087. 3,
  146088. 3
  146089. };
  146090. static static_codebook _44u6__p2_0 = {
  146091. 4, 81,
  146092. _vq_lengthlist__44u6__p2_0,
  146093. 1, -535822336, 1611661312, 2, 0,
  146094. _vq_quantlist__44u6__p2_0,
  146095. NULL,
  146096. &_vq_auxt__44u6__p2_0,
  146097. NULL,
  146098. 0
  146099. };
  146100. static long _vq_quantlist__44u6__p3_0[] = {
  146101. 2,
  146102. 1,
  146103. 3,
  146104. 0,
  146105. 4,
  146106. };
  146107. static long _vq_lengthlist__44u6__p3_0[] = {
  146108. 2, 5, 4, 8, 8, 5, 7, 6, 9, 9, 5, 6, 7, 9, 9, 8,
  146109. 9, 9,13,12, 8, 9,10,12,13, 5, 7, 7,10, 9, 7, 9,
  146110. 9,11,11, 7, 8, 9,11,11,10,11,11,14,14, 9,10,11,
  146111. 13,14, 5, 7, 7, 9,10, 6, 9, 8,11,11, 7, 9, 9,11,
  146112. 11, 9,11,10,14,13,10,11,11,14,13, 8,10,10,13,13,
  146113. 10,11,11,15,15, 9,11,11,14,14,13,14,14,17,16,12,
  146114. 13,14,16,16, 8,10,10,13,14, 9,11,11,14,15,10,11,
  146115. 12,14,15,12,14,13,16,15,13,14,14,15,17, 5, 7, 7,
  146116. 10,10, 7, 9, 9,11,11, 7, 9, 9,11,11,10,12,11,14,
  146117. 14,10,11,11,14,14, 7, 9, 9,12,11, 9,11,11,13,13,
  146118. 9,11,11,13,13,11,13,13,14,15,11,12,13,15,16, 6,
  146119. 9, 9,11,12, 8,11,10,13,12, 9,11,11,13,14,11,13,
  146120. 12,16,14,11,13,13,15,16,10,12,11,14,15,11,13,13,
  146121. 15,17,11,13,13,17,16,15,15,16,17,16,14,15,16,18,
  146122. 0, 9,11,11,14,15,10,12,12,16,15,11,13,13,16,16,
  146123. 13,15,14,18,15,14,16,16, 0, 0, 5, 7, 7,10,10, 7,
  146124. 9, 9,11,11, 7, 9, 9,11,11,10,11,11,14,14,10,11,
  146125. 12,14,14, 6, 9, 9,11,11, 9,11,11,13,13, 8,10,11,
  146126. 12,13,11,13,13,16,15,11,12,13,14,16, 7, 9, 9,11,
  146127. 12, 9,11,11,13,13, 9,11,11,13,13,11,13,13,16,15,
  146128. 11,13,12,15,15, 9,11,11,15,14,11,13,13,17,16,10,
  146129. 12,13,15,16,14,16,16, 0,18,14,14,15,15,17,10,11,
  146130. 12,15,15,11,13,13,16,16,11,13,13,16,16,14,16,16,
  146131. 19,17,14,15,15,17,17, 8,10,10,14,14,10,12,11,15,
  146132. 15,10,11,12,16,15,14,15,15,18,20,13,14,16,17,18,
  146133. 9,11,11,15,16,11,13,13,17,17,11,13,13,17,16,15,
  146134. 16,16, 0, 0,15,16,16, 0, 0, 9,11,11,15,15,10,13,
  146135. 12,17,15,11,13,13,17,16,15,17,15,20,19,15,16,16,
  146136. 19, 0,13,15,14, 0,17,14,15,16, 0,20,15,16,16, 0,
  146137. 19,17,18, 0, 0, 0,16,17,18, 0, 0,12,14,14,19,18,
  146138. 13,15,14, 0,17,14,15,16,19,19,16,18,16, 0,19,19,
  146139. 20,17,20, 0, 8,10,10,13,14,10,11,11,15,15,10,12,
  146140. 12,15,16,14,15,14,19,16,14,15,15, 0,18, 9,11,11,
  146141. 16,15,11,13,13, 0,16,11,12,13,16,17,14,16,17, 0,
  146142. 19,15,16,16,18, 0, 9,11,11,15,16,11,13,13,16,16,
  146143. 11,14,13,18,17,15,16,16,18,20,15,17,19, 0, 0,12,
  146144. 14,14,17,17,14,16,15, 0, 0,13,14,15,19, 0,16,18,
  146145. 20, 0, 0,16,16,18,18, 0,12,14,14,17,20,14,16,16,
  146146. 19, 0,14,16,14, 0,20,16,20,17, 0, 0,17, 0,15, 0,
  146147. 19,
  146148. };
  146149. static float _vq_quantthresh__44u6__p3_0[] = {
  146150. -1.5, -0.5, 0.5, 1.5,
  146151. };
  146152. static long _vq_quantmap__44u6__p3_0[] = {
  146153. 3, 1, 0, 2, 4,
  146154. };
  146155. static encode_aux_threshmatch _vq_auxt__44u6__p3_0 = {
  146156. _vq_quantthresh__44u6__p3_0,
  146157. _vq_quantmap__44u6__p3_0,
  146158. 5,
  146159. 5
  146160. };
  146161. static static_codebook _44u6__p3_0 = {
  146162. 4, 625,
  146163. _vq_lengthlist__44u6__p3_0,
  146164. 1, -533725184, 1611661312, 3, 0,
  146165. _vq_quantlist__44u6__p3_0,
  146166. NULL,
  146167. &_vq_auxt__44u6__p3_0,
  146168. NULL,
  146169. 0
  146170. };
  146171. static long _vq_quantlist__44u6__p4_0[] = {
  146172. 2,
  146173. 1,
  146174. 3,
  146175. 0,
  146176. 4,
  146177. };
  146178. static long _vq_lengthlist__44u6__p4_0[] = {
  146179. 4, 5, 5, 8, 8, 6, 7, 6, 9, 9, 6, 6, 7, 9, 9, 8,
  146180. 9, 9,11,11, 8, 9, 9,11,11, 6, 7, 7, 9, 9, 7, 8,
  146181. 8,10,10, 7, 7, 8, 9,10, 9,10,10,11,11, 9, 9,10,
  146182. 11,12, 6, 7, 7, 9, 9, 7, 8, 7,10, 9, 7, 8, 8,10,
  146183. 10, 9,10, 9,12,11, 9,10,10,12,11, 8, 9, 9,11,11,
  146184. 9,10,10,12,12, 9,10,10,12,12,11,12,12,14,13,11,
  146185. 11,12,13,13, 8, 9, 9,11,11, 9,10,10,12,12, 9,10,
  146186. 10,12,12,11,12,11,13,12,11,12,12,13,13, 5, 7, 7,
  146187. 9, 9, 7, 8, 7,10,10, 7, 7, 8,10,10, 9,10,10,12,
  146188. 11, 9,10,10,11,12, 7, 8, 8,10,10, 8, 8, 9,11,11,
  146189. 8, 9, 9,11,11,10,10,11,12,13,10,10,11,12,12, 6,
  146190. 7, 7,10,10, 7, 9, 8,11,10, 8, 8, 9,10,11,10,11,
  146191. 10,13,11,10,11,11,12,12, 9,10,10,12,12,10,10,11,
  146192. 13,13,10,11,11,12,13,12,12,12,13,14,12,12,13,14,
  146193. 14, 9,10,10,12,12, 9,10,10,13,12,10,11,11,13,13,
  146194. 11,12,11,14,12,12,13,13,14,14, 6, 7, 7, 9, 9, 7,
  146195. 8, 7,10,10, 7, 8, 8,10,10, 9,10,10,12,11, 9,10,
  146196. 10,11,12, 6, 7, 7,10,10, 8, 9, 8,11,10, 7, 8, 9,
  146197. 10,11,10,11,11,12,12,10,10,11,11,13, 7, 8, 8,10,
  146198. 10, 8, 9, 9,11,11, 8, 9, 8,11,11,10,11,10,13,12,
  146199. 10,11,11,13,12, 9,10,10,12,12,10,11,11,13,12, 9,
  146200. 10,10,12,13,12,13,12,14,14,11,11,12,12,14, 9,10,
  146201. 10,12,12,10,11,11,13,13,10,11,10,13,12,12,12,12,
  146202. 14,14,12,13,12,14,13, 8, 9, 9,11,11, 9,10,10,12,
  146203. 12, 9,10,10,12,12,11,12,12,14,13,11,12,12,13,14,
  146204. 9,10,10,12,12,10,11,11,13,13,10,11,11,13,13,12,
  146205. 12,13,14,15,12,12,13,14,14, 9,10,10,12,12, 9,11,
  146206. 10,13,12,10,10,11,12,13,12,13,12,14,13,12,12,13,
  146207. 14,15,11,12,12,14,13,11,12,12,14,14,12,13,13,14,
  146208. 14,13,13,14,14,16,13,14,14,15,15,11,12,11,13,13,
  146209. 11,12,11,14,13,12,12,13,14,15,12,14,12,15,12,13,
  146210. 14,15,15,16, 8, 9, 9,11,11, 9,10,10,12,12, 9,10,
  146211. 10,12,12,11,12,12,14,13,11,12,12,13,13, 9,10,10,
  146212. 12,12,10,11,10,13,12, 9,10,11,12,13,12,13,12,14,
  146213. 14,12,12,13,13,14, 9,10,10,12,12,10,11,11,13,13,
  146214. 10,11,11,13,13,12,13,12,14,14,12,13,13,14,14,11,
  146215. 11,11,13,13,12,13,12,14,14,11,11,12,13,14,14,14,
  146216. 14,16,15,12,12,14,12,15,11,12,12,13,14,12,13,13,
  146217. 14,15,11,12,12,14,14,13,14,14,16,16,13,14,13,16,
  146218. 13,
  146219. };
  146220. static float _vq_quantthresh__44u6__p4_0[] = {
  146221. -1.5, -0.5, 0.5, 1.5,
  146222. };
  146223. static long _vq_quantmap__44u6__p4_0[] = {
  146224. 3, 1, 0, 2, 4,
  146225. };
  146226. static encode_aux_threshmatch _vq_auxt__44u6__p4_0 = {
  146227. _vq_quantthresh__44u6__p4_0,
  146228. _vq_quantmap__44u6__p4_0,
  146229. 5,
  146230. 5
  146231. };
  146232. static static_codebook _44u6__p4_0 = {
  146233. 4, 625,
  146234. _vq_lengthlist__44u6__p4_0,
  146235. 1, -533725184, 1611661312, 3, 0,
  146236. _vq_quantlist__44u6__p4_0,
  146237. NULL,
  146238. &_vq_auxt__44u6__p4_0,
  146239. NULL,
  146240. 0
  146241. };
  146242. static long _vq_quantlist__44u6__p5_0[] = {
  146243. 4,
  146244. 3,
  146245. 5,
  146246. 2,
  146247. 6,
  146248. 1,
  146249. 7,
  146250. 0,
  146251. 8,
  146252. };
  146253. static long _vq_lengthlist__44u6__p5_0[] = {
  146254. 2, 3, 3, 6, 6, 8, 8,10,10, 4, 5, 5, 8, 7, 8, 8,
  146255. 11,11, 3, 5, 5, 7, 8, 8, 8,11,11, 6, 8, 7, 9, 9,
  146256. 10, 9,12,11, 6, 7, 8, 9, 9, 9,10,11,12, 8, 8, 8,
  146257. 10, 9,12,11,13,13, 8, 8, 9, 9,10,11,12,13,13,10,
  146258. 11,11,12,12,13,13,14,14,10,10,11,11,12,13,13,14,
  146259. 14,
  146260. };
  146261. static float _vq_quantthresh__44u6__p5_0[] = {
  146262. -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5, 3.5,
  146263. };
  146264. static long _vq_quantmap__44u6__p5_0[] = {
  146265. 7, 5, 3, 1, 0, 2, 4, 6,
  146266. 8,
  146267. };
  146268. static encode_aux_threshmatch _vq_auxt__44u6__p5_0 = {
  146269. _vq_quantthresh__44u6__p5_0,
  146270. _vq_quantmap__44u6__p5_0,
  146271. 9,
  146272. 9
  146273. };
  146274. static static_codebook _44u6__p5_0 = {
  146275. 2, 81,
  146276. _vq_lengthlist__44u6__p5_0,
  146277. 1, -531628032, 1611661312, 4, 0,
  146278. _vq_quantlist__44u6__p5_0,
  146279. NULL,
  146280. &_vq_auxt__44u6__p5_0,
  146281. NULL,
  146282. 0
  146283. };
  146284. static long _vq_quantlist__44u6__p6_0[] = {
  146285. 4,
  146286. 3,
  146287. 5,
  146288. 2,
  146289. 6,
  146290. 1,
  146291. 7,
  146292. 0,
  146293. 8,
  146294. };
  146295. static long _vq_lengthlist__44u6__p6_0[] = {
  146296. 3, 4, 4, 5, 5, 7, 7, 9, 9, 4, 5, 4, 6, 6, 7, 7,
  146297. 9, 9, 4, 4, 5, 6, 6, 7, 8, 9, 9, 5, 6, 6, 7, 7,
  146298. 8, 8,10,10, 5, 6, 6, 7, 7, 8, 8,10,10, 7, 8, 7,
  146299. 8, 8,10, 9,11,11, 7, 7, 8, 8, 8, 9,10,10,11, 9,
  146300. 9, 9,10,10,11,11,12,11, 9, 9, 9,10,10,11,11,11,
  146301. 12,
  146302. };
  146303. static float _vq_quantthresh__44u6__p6_0[] = {
  146304. -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5, 3.5,
  146305. };
  146306. static long _vq_quantmap__44u6__p6_0[] = {
  146307. 7, 5, 3, 1, 0, 2, 4, 6,
  146308. 8,
  146309. };
  146310. static encode_aux_threshmatch _vq_auxt__44u6__p6_0 = {
  146311. _vq_quantthresh__44u6__p6_0,
  146312. _vq_quantmap__44u6__p6_0,
  146313. 9,
  146314. 9
  146315. };
  146316. static static_codebook _44u6__p6_0 = {
  146317. 2, 81,
  146318. _vq_lengthlist__44u6__p6_0,
  146319. 1, -531628032, 1611661312, 4, 0,
  146320. _vq_quantlist__44u6__p6_0,
  146321. NULL,
  146322. &_vq_auxt__44u6__p6_0,
  146323. NULL,
  146324. 0
  146325. };
  146326. static long _vq_quantlist__44u6__p7_0[] = {
  146327. 1,
  146328. 0,
  146329. 2,
  146330. };
  146331. static long _vq_lengthlist__44u6__p7_0[] = {
  146332. 1, 4, 4, 5, 7, 7, 5, 7, 7, 5, 9, 8, 7,10,10, 8,
  146333. 10,10, 5, 8, 9, 7,10,10, 7,10, 9, 4, 8, 8, 9,11,
  146334. 11, 8,11,11, 7,11,11,10,10,13,10,13,13, 7,11,11,
  146335. 10,13,12,10,13,13, 5, 9, 8, 8,11,11, 9,11,11, 7,
  146336. 11,11,10,13,13,10,12,13, 7,11,11,10,13,13, 9,13,
  146337. 10,
  146338. };
  146339. static float _vq_quantthresh__44u6__p7_0[] = {
  146340. -5.5, 5.5,
  146341. };
  146342. static long _vq_quantmap__44u6__p7_0[] = {
  146343. 1, 0, 2,
  146344. };
  146345. static encode_aux_threshmatch _vq_auxt__44u6__p7_0 = {
  146346. _vq_quantthresh__44u6__p7_0,
  146347. _vq_quantmap__44u6__p7_0,
  146348. 3,
  146349. 3
  146350. };
  146351. static static_codebook _44u6__p7_0 = {
  146352. 4, 81,
  146353. _vq_lengthlist__44u6__p7_0,
  146354. 1, -529137664, 1618345984, 2, 0,
  146355. _vq_quantlist__44u6__p7_0,
  146356. NULL,
  146357. &_vq_auxt__44u6__p7_0,
  146358. NULL,
  146359. 0
  146360. };
  146361. static long _vq_quantlist__44u6__p7_1[] = {
  146362. 5,
  146363. 4,
  146364. 6,
  146365. 3,
  146366. 7,
  146367. 2,
  146368. 8,
  146369. 1,
  146370. 9,
  146371. 0,
  146372. 10,
  146373. };
  146374. static long _vq_lengthlist__44u6__p7_1[] = {
  146375. 3, 4, 4, 6, 6, 7, 7, 8, 8, 8, 8, 4, 5, 5, 7, 6,
  146376. 8, 8, 8, 8, 8, 8, 4, 5, 5, 6, 7, 8, 8, 8, 8, 8,
  146377. 8, 6, 7, 7, 7, 7, 8, 8, 8, 8, 8, 8, 6, 7, 7, 7,
  146378. 7, 8, 8, 8, 8, 8, 8, 7, 8, 8, 8, 8, 8, 8, 9, 9,
  146379. 9, 9, 7, 8, 8, 8, 8, 8, 8, 9, 9, 9, 9, 8, 8, 8,
  146380. 8, 8, 9, 9, 9, 9, 9, 9, 8, 8, 8, 8, 8, 9, 9, 9,
  146381. 9, 9, 9, 8, 8, 8, 8, 8, 9, 9, 9, 9, 9, 9, 8, 8,
  146382. 8, 8, 8, 9, 9, 9, 9, 9, 9,
  146383. };
  146384. static float _vq_quantthresh__44u6__p7_1[] = {
  146385. -4.5, -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5,
  146386. 3.5, 4.5,
  146387. };
  146388. static long _vq_quantmap__44u6__p7_1[] = {
  146389. 9, 7, 5, 3, 1, 0, 2, 4,
  146390. 6, 8, 10,
  146391. };
  146392. static encode_aux_threshmatch _vq_auxt__44u6__p7_1 = {
  146393. _vq_quantthresh__44u6__p7_1,
  146394. _vq_quantmap__44u6__p7_1,
  146395. 11,
  146396. 11
  146397. };
  146398. static static_codebook _44u6__p7_1 = {
  146399. 2, 121,
  146400. _vq_lengthlist__44u6__p7_1,
  146401. 1, -531365888, 1611661312, 4, 0,
  146402. _vq_quantlist__44u6__p7_1,
  146403. NULL,
  146404. &_vq_auxt__44u6__p7_1,
  146405. NULL,
  146406. 0
  146407. };
  146408. static long _vq_quantlist__44u6__p8_0[] = {
  146409. 5,
  146410. 4,
  146411. 6,
  146412. 3,
  146413. 7,
  146414. 2,
  146415. 8,
  146416. 1,
  146417. 9,
  146418. 0,
  146419. 10,
  146420. };
  146421. static long _vq_lengthlist__44u6__p8_0[] = {
  146422. 1, 4, 4, 6, 6, 8, 8, 9, 9,10,10, 4, 6, 6, 7, 7,
  146423. 9, 9,10,10,11,11, 4, 6, 6, 7, 7, 9, 9,10,10,11,
  146424. 11, 6, 8, 8, 9, 9,10,10,11,11,12,12, 6, 8, 8, 9,
  146425. 9,10,10,11,11,12,12, 8, 9, 9,10,10,11,11,12,12,
  146426. 13,13, 8, 9, 9,10,10,11,11,12,12,13,13,10,10,10,
  146427. 11,11,13,13,13,13,15,14, 9,10,10,12,11,12,13,13,
  146428. 13,14,15,11,12,12,13,13,13,13,15,14,15,15,11,11,
  146429. 12,13,13,14,14,14,15,15,15,
  146430. };
  146431. static float _vq_quantthresh__44u6__p8_0[] = {
  146432. -49.5, -38.5, -27.5, -16.5, -5.5, 5.5, 16.5, 27.5,
  146433. 38.5, 49.5,
  146434. };
  146435. static long _vq_quantmap__44u6__p8_0[] = {
  146436. 9, 7, 5, 3, 1, 0, 2, 4,
  146437. 6, 8, 10,
  146438. };
  146439. static encode_aux_threshmatch _vq_auxt__44u6__p8_0 = {
  146440. _vq_quantthresh__44u6__p8_0,
  146441. _vq_quantmap__44u6__p8_0,
  146442. 11,
  146443. 11
  146444. };
  146445. static static_codebook _44u6__p8_0 = {
  146446. 2, 121,
  146447. _vq_lengthlist__44u6__p8_0,
  146448. 1, -524582912, 1618345984, 4, 0,
  146449. _vq_quantlist__44u6__p8_0,
  146450. NULL,
  146451. &_vq_auxt__44u6__p8_0,
  146452. NULL,
  146453. 0
  146454. };
  146455. static long _vq_quantlist__44u6__p8_1[] = {
  146456. 5,
  146457. 4,
  146458. 6,
  146459. 3,
  146460. 7,
  146461. 2,
  146462. 8,
  146463. 1,
  146464. 9,
  146465. 0,
  146466. 10,
  146467. };
  146468. static long _vq_lengthlist__44u6__p8_1[] = {
  146469. 3, 5, 5, 6, 6, 7, 7, 7, 7, 7, 7, 5, 6, 5, 7, 7,
  146470. 7, 7, 8, 7, 8, 8, 5, 5, 6, 6, 7, 7, 7, 7, 7, 8,
  146471. 8, 6, 7, 7, 7, 7, 8, 7, 8, 8, 8, 8, 6, 6, 7, 7,
  146472. 7, 7, 8, 8, 8, 8, 8, 7, 7, 7, 8, 8, 8, 8, 8, 8,
  146473. 8, 8, 7, 7, 7, 7, 8, 8, 8, 8, 8, 8, 8, 7, 7, 7,
  146474. 8, 8, 8, 8, 8, 8, 8, 8, 7, 8, 8, 8, 8, 8, 8, 8,
  146475. 8, 8, 8, 7, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 7, 8,
  146476. 8, 8, 8, 8, 8, 8, 8, 8, 8,
  146477. };
  146478. static float _vq_quantthresh__44u6__p8_1[] = {
  146479. -4.5, -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5,
  146480. 3.5, 4.5,
  146481. };
  146482. static long _vq_quantmap__44u6__p8_1[] = {
  146483. 9, 7, 5, 3, 1, 0, 2, 4,
  146484. 6, 8, 10,
  146485. };
  146486. static encode_aux_threshmatch _vq_auxt__44u6__p8_1 = {
  146487. _vq_quantthresh__44u6__p8_1,
  146488. _vq_quantmap__44u6__p8_1,
  146489. 11,
  146490. 11
  146491. };
  146492. static static_codebook _44u6__p8_1 = {
  146493. 2, 121,
  146494. _vq_lengthlist__44u6__p8_1,
  146495. 1, -531365888, 1611661312, 4, 0,
  146496. _vq_quantlist__44u6__p8_1,
  146497. NULL,
  146498. &_vq_auxt__44u6__p8_1,
  146499. NULL,
  146500. 0
  146501. };
  146502. static long _vq_quantlist__44u6__p9_0[] = {
  146503. 7,
  146504. 6,
  146505. 8,
  146506. 5,
  146507. 9,
  146508. 4,
  146509. 10,
  146510. 3,
  146511. 11,
  146512. 2,
  146513. 12,
  146514. 1,
  146515. 13,
  146516. 0,
  146517. 14,
  146518. };
  146519. static long _vq_lengthlist__44u6__p9_0[] = {
  146520. 1, 3, 2, 9, 8,15,15,15,15,15,15,15,15,15,15, 4,
  146521. 8, 9,13,14,14,14,14,14,14,14,14,14,14,14, 5, 8,
  146522. 9,14,14,14,14,14,14,14,14,14,14,14,14,11,14,14,
  146523. 14,14,14,14,14,14,14,14,14,14,14,14,11,14,14,14,
  146524. 14,14,14,14,14,14,14,14,14,14,14,14,14,14,14,14,
  146525. 14,14,14,14,14,14,14,14,14,14,14,14,14,14,14,14,
  146526. 14,14,14,14,14,14,14,14,14,14,14,14,14,14,14,14,
  146527. 14,14,14,14,14,14,14,14,14,14,14,14,14,14,14,14,
  146528. 14,14,14,14,14,14,14,14,14,14,14,14,14,14,14,14,
  146529. 14,14,14,14,14,14,14,14,14,14,14,14,14,14,14,14,
  146530. 14,14,14,14,14,14,14,14,14,14,14,14,14,14,14,14,
  146531. 14,14,14,14,14,14,14,14,14,14,14,14,14,14,14,14,
  146532. 14,14,14,14,14,14,14,14,14,14,14,14,14,14,14,14,
  146533. 14,14,14,14,14,14,14,14,14,14,14,14,14,14,14,14,
  146534. 14,
  146535. };
  146536. static float _vq_quantthresh__44u6__p9_0[] = {
  146537. -1657.5, -1402.5, -1147.5, -892.5, -637.5, -382.5, -127.5, 127.5,
  146538. 382.5, 637.5, 892.5, 1147.5, 1402.5, 1657.5,
  146539. };
  146540. static long _vq_quantmap__44u6__p9_0[] = {
  146541. 13, 11, 9, 7, 5, 3, 1, 0,
  146542. 2, 4, 6, 8, 10, 12, 14,
  146543. };
  146544. static encode_aux_threshmatch _vq_auxt__44u6__p9_0 = {
  146545. _vq_quantthresh__44u6__p9_0,
  146546. _vq_quantmap__44u6__p9_0,
  146547. 15,
  146548. 15
  146549. };
  146550. static static_codebook _44u6__p9_0 = {
  146551. 2, 225,
  146552. _vq_lengthlist__44u6__p9_0,
  146553. 1, -514071552, 1627381760, 4, 0,
  146554. _vq_quantlist__44u6__p9_0,
  146555. NULL,
  146556. &_vq_auxt__44u6__p9_0,
  146557. NULL,
  146558. 0
  146559. };
  146560. static long _vq_quantlist__44u6__p9_1[] = {
  146561. 7,
  146562. 6,
  146563. 8,
  146564. 5,
  146565. 9,
  146566. 4,
  146567. 10,
  146568. 3,
  146569. 11,
  146570. 2,
  146571. 12,
  146572. 1,
  146573. 13,
  146574. 0,
  146575. 14,
  146576. };
  146577. static long _vq_lengthlist__44u6__p9_1[] = {
  146578. 1, 4, 4, 7, 7, 8, 9, 8, 8, 9, 8, 9, 8, 9, 9, 4,
  146579. 7, 6, 8, 8, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 4, 7,
  146580. 6, 9, 9,10,10, 9, 9,10,10,10,10,11,11, 7, 9, 8,
  146581. 10,10,11,11,10,10,11,11,11,11,11,11, 7, 8, 9,10,
  146582. 10,11,11,10,10,11,11,11,11,11,12, 8,10,10,11,11,
  146583. 12,12,11,11,12,12,12,12,13,12, 8,10,10,11,11,12,
  146584. 11,11,11,11,12,12,12,12,13, 8, 9, 9,11,10,11,11,
  146585. 12,12,12,12,13,12,13,12, 8, 9, 9,11,11,11,11,12,
  146586. 12,12,12,12,13,13,13, 9,10,10,11,12,12,12,12,12,
  146587. 13,13,13,13,13,13, 9,10,10,11,11,12,12,12,12,13,
  146588. 13,13,13,14,13,10,10,10,12,11,12,12,13,13,13,13,
  146589. 13,13,13,13,10,10,11,11,11,12,12,13,13,13,13,13,
  146590. 13,13,13,10,11,11,12,12,13,12,12,13,13,13,13,13,
  146591. 13,14,10,11,11,12,12,13,12,13,13,13,14,13,13,14,
  146592. 13,
  146593. };
  146594. static float _vq_quantthresh__44u6__p9_1[] = {
  146595. -110.5, -93.5, -76.5, -59.5, -42.5, -25.5, -8.5, 8.5,
  146596. 25.5, 42.5, 59.5, 76.5, 93.5, 110.5,
  146597. };
  146598. static long _vq_quantmap__44u6__p9_1[] = {
  146599. 13, 11, 9, 7, 5, 3, 1, 0,
  146600. 2, 4, 6, 8, 10, 12, 14,
  146601. };
  146602. static encode_aux_threshmatch _vq_auxt__44u6__p9_1 = {
  146603. _vq_quantthresh__44u6__p9_1,
  146604. _vq_quantmap__44u6__p9_1,
  146605. 15,
  146606. 15
  146607. };
  146608. static static_codebook _44u6__p9_1 = {
  146609. 2, 225,
  146610. _vq_lengthlist__44u6__p9_1,
  146611. 1, -522338304, 1620115456, 4, 0,
  146612. _vq_quantlist__44u6__p9_1,
  146613. NULL,
  146614. &_vq_auxt__44u6__p9_1,
  146615. NULL,
  146616. 0
  146617. };
  146618. static long _vq_quantlist__44u6__p9_2[] = {
  146619. 8,
  146620. 7,
  146621. 9,
  146622. 6,
  146623. 10,
  146624. 5,
  146625. 11,
  146626. 4,
  146627. 12,
  146628. 3,
  146629. 13,
  146630. 2,
  146631. 14,
  146632. 1,
  146633. 15,
  146634. 0,
  146635. 16,
  146636. };
  146637. static long _vq_lengthlist__44u6__p9_2[] = {
  146638. 3, 5, 5, 7, 7, 8, 8, 8, 8, 8, 8, 9, 8, 8, 9, 9,
  146639. 9, 5, 6, 6, 7, 7, 8, 8, 8, 8, 8, 8, 9, 9, 9, 9,
  146640. 9, 9, 5, 6, 6, 7, 7, 8, 8, 8, 8, 8, 8, 9, 9, 9,
  146641. 9, 9, 9, 7, 7, 7, 8, 8, 8, 8, 9, 9, 9, 9, 9, 9,
  146642. 9, 9, 9, 9, 7, 7, 7, 8, 8, 8, 8, 9, 9, 9, 9, 9,
  146643. 9, 9, 9, 9, 9, 8, 8, 8, 8, 8, 9, 9, 9, 9, 9, 9,
  146644. 9, 9, 9, 9, 9, 9, 8, 8, 8, 8, 8, 9, 9, 9, 9, 9,
  146645. 9, 9, 9, 9, 9, 9, 9, 8, 8, 8, 9, 9, 9, 9, 9, 9,
  146646. 9, 9, 9, 9, 9, 9, 9, 9, 8, 8, 8, 9, 9, 9, 9, 9,
  146647. 9, 9, 9, 9, 9, 9, 9, 9, 9, 8, 9, 9, 9, 9, 9, 9,
  146648. 9, 9, 9, 9, 9, 9, 9, 9,10, 9, 8, 9, 9, 9, 9, 9,
  146649. 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,
  146650. 9, 9, 9, 9, 9, 9, 9, 9, 9,10,10, 9, 9, 9, 9, 9,
  146651. 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,10, 9, 9, 9,
  146652. 9, 9, 9, 9, 9, 9, 9, 9,10, 9, 9, 9,10, 9, 9, 9,
  146653. 9, 9, 9, 9, 9, 9, 9,10, 9, 9, 9,10, 9, 9,10, 9,
  146654. 9, 9, 9, 9, 9, 9, 9, 9,10,10,10, 9,10, 9,10,10,
  146655. 9, 9, 9, 9, 9, 9, 9, 9, 9,10,10, 9,10,10, 9, 9,
  146656. 10,
  146657. };
  146658. static float _vq_quantthresh__44u6__p9_2[] = {
  146659. -7.5, -6.5, -5.5, -4.5, -3.5, -2.5, -1.5, -0.5,
  146660. 0.5, 1.5, 2.5, 3.5, 4.5, 5.5, 6.5, 7.5,
  146661. };
  146662. static long _vq_quantmap__44u6__p9_2[] = {
  146663. 15, 13, 11, 9, 7, 5, 3, 1,
  146664. 0, 2, 4, 6, 8, 10, 12, 14,
  146665. 16,
  146666. };
  146667. static encode_aux_threshmatch _vq_auxt__44u6__p9_2 = {
  146668. _vq_quantthresh__44u6__p9_2,
  146669. _vq_quantmap__44u6__p9_2,
  146670. 17,
  146671. 17
  146672. };
  146673. static static_codebook _44u6__p9_2 = {
  146674. 2, 289,
  146675. _vq_lengthlist__44u6__p9_2,
  146676. 1, -529530880, 1611661312, 5, 0,
  146677. _vq_quantlist__44u6__p9_2,
  146678. NULL,
  146679. &_vq_auxt__44u6__p9_2,
  146680. NULL,
  146681. 0
  146682. };
  146683. static long _huff_lengthlist__44u6__short[] = {
  146684. 4,11,16,13,17,13,17,16,17,17, 4, 7, 9, 9,13,10,
  146685. 16,12,16,17, 7, 6, 5, 7, 8, 9,12,12,16,17, 6, 9,
  146686. 7, 9,10,10,15,15,17,17, 6, 7, 5, 7, 5, 7, 7,10,
  146687. 16,17, 7, 9, 8, 9, 8,10,11,11,15,17, 7, 7, 7, 8,
  146688. 5, 8, 8, 9,15,17, 8, 7, 9, 9, 7, 8, 7, 2, 7,15,
  146689. 14,13,13,15, 5,10, 4, 3, 6,17,17,15,13,17, 7,11,
  146690. 7, 6, 9,16,
  146691. };
  146692. static static_codebook _huff_book__44u6__short = {
  146693. 2, 100,
  146694. _huff_lengthlist__44u6__short,
  146695. 0, 0, 0, 0, 0,
  146696. NULL,
  146697. NULL,
  146698. NULL,
  146699. NULL,
  146700. 0
  146701. };
  146702. static long _huff_lengthlist__44u7__long[] = {
  146703. 3, 9,14,13,15,14,16,13,13,14, 5, 5, 7, 7, 8, 9,
  146704. 11,10,12,15,10, 6, 5, 6, 6, 9,10,10,13,16,10, 6,
  146705. 6, 6, 6, 8, 9, 9,12,15,14, 7, 6, 6, 5, 6, 6, 8,
  146706. 12,15,10, 8, 7, 7, 6, 7, 7, 7,11,13,14,10, 9, 8,
  146707. 5, 6, 4, 5, 9,12,10, 9, 9, 8, 6, 6, 5, 3, 6,11,
  146708. 12,11,12,12,10, 9, 8, 5, 5, 8,10,11,15,13,13,13,
  146709. 12, 8, 6, 7,
  146710. };
  146711. static static_codebook _huff_book__44u7__long = {
  146712. 2, 100,
  146713. _huff_lengthlist__44u7__long,
  146714. 0, 0, 0, 0, 0,
  146715. NULL,
  146716. NULL,
  146717. NULL,
  146718. NULL,
  146719. 0
  146720. };
  146721. static long _vq_quantlist__44u7__p1_0[] = {
  146722. 1,
  146723. 0,
  146724. 2,
  146725. };
  146726. static long _vq_lengthlist__44u7__p1_0[] = {
  146727. 1, 4, 4, 4, 7, 7, 5, 7, 7, 5, 8, 8, 8,10,10, 7,
  146728. 10,10, 5, 8, 8, 7,10,10, 8,10,10, 5, 8, 8, 8,11,
  146729. 10, 8,10,10, 8,10,10,10,12,13,10,13,13, 7,10,10,
  146730. 10,13,12,10,13,13, 5, 8, 8, 8,11,10, 8,10,11, 7,
  146731. 10,10,10,13,13,10,12,13, 8,11,11,10,13,13,10,13,
  146732. 12,
  146733. };
  146734. static float _vq_quantthresh__44u7__p1_0[] = {
  146735. -0.5, 0.5,
  146736. };
  146737. static long _vq_quantmap__44u7__p1_0[] = {
  146738. 1, 0, 2,
  146739. };
  146740. static encode_aux_threshmatch _vq_auxt__44u7__p1_0 = {
  146741. _vq_quantthresh__44u7__p1_0,
  146742. _vq_quantmap__44u7__p1_0,
  146743. 3,
  146744. 3
  146745. };
  146746. static static_codebook _44u7__p1_0 = {
  146747. 4, 81,
  146748. _vq_lengthlist__44u7__p1_0,
  146749. 1, -535822336, 1611661312, 2, 0,
  146750. _vq_quantlist__44u7__p1_0,
  146751. NULL,
  146752. &_vq_auxt__44u7__p1_0,
  146753. NULL,
  146754. 0
  146755. };
  146756. static long _vq_quantlist__44u7__p2_0[] = {
  146757. 1,
  146758. 0,
  146759. 2,
  146760. };
  146761. static long _vq_lengthlist__44u7__p2_0[] = {
  146762. 3, 4, 4, 5, 6, 6, 5, 6, 6, 5, 6, 6, 6, 8, 8, 6,
  146763. 7, 8, 5, 6, 6, 6, 8, 7, 6, 8, 8, 5, 6, 6, 6, 8,
  146764. 7, 6, 8, 8, 6, 8, 8, 8, 9, 9, 8, 9, 9, 6, 8, 7,
  146765. 7, 9, 8, 8, 9, 9, 5, 6, 6, 6, 8, 7, 6, 8, 8, 6,
  146766. 8, 8, 8, 9, 9, 7, 8, 9, 6, 8, 8, 8, 9, 9, 8, 9,
  146767. 9,
  146768. };
  146769. static float _vq_quantthresh__44u7__p2_0[] = {
  146770. -0.5, 0.5,
  146771. };
  146772. static long _vq_quantmap__44u7__p2_0[] = {
  146773. 1, 0, 2,
  146774. };
  146775. static encode_aux_threshmatch _vq_auxt__44u7__p2_0 = {
  146776. _vq_quantthresh__44u7__p2_0,
  146777. _vq_quantmap__44u7__p2_0,
  146778. 3,
  146779. 3
  146780. };
  146781. static static_codebook _44u7__p2_0 = {
  146782. 4, 81,
  146783. _vq_lengthlist__44u7__p2_0,
  146784. 1, -535822336, 1611661312, 2, 0,
  146785. _vq_quantlist__44u7__p2_0,
  146786. NULL,
  146787. &_vq_auxt__44u7__p2_0,
  146788. NULL,
  146789. 0
  146790. };
  146791. static long _vq_quantlist__44u7__p3_0[] = {
  146792. 2,
  146793. 1,
  146794. 3,
  146795. 0,
  146796. 4,
  146797. };
  146798. static long _vq_lengthlist__44u7__p3_0[] = {
  146799. 2, 5, 4, 8, 8, 5, 7, 6, 9, 9, 5, 6, 7, 9, 9, 8,
  146800. 9, 9,13,12, 8, 9,10,12,13, 5, 7, 7,10, 9, 7, 9,
  146801. 9,11,11, 6, 8, 9,11,11,10,11,11,14,14, 9,10,11,
  146802. 13,14, 5, 7, 7, 9, 9, 7, 9, 8,11,11, 7, 9, 9,11,
  146803. 11, 9,11,10,14,13,10,11,11,14,14, 8,10,10,14,13,
  146804. 10,11,12,15,14, 9,11,11,15,14,13,14,14,16,16,12,
  146805. 13,14,17,16, 8,10,10,13,13, 9,11,11,14,15,10,11,
  146806. 12,14,15,12,14,13,16,16,13,14,15,15,17, 5, 7, 7,
  146807. 10,10, 7, 9, 9,11,11, 7, 9, 9,11,11,10,12,11,15,
  146808. 14,10,11,12,14,14, 7, 9, 9,12,12, 9,11,11,13,13,
  146809. 9,11,11,13,13,11,13,13,14,17,11,13,13,15,16, 6,
  146810. 9, 9,11,11, 8,11,10,13,12, 9,11,11,13,13,11,13,
  146811. 12,16,14,11,13,13,16,16,10,12,12,15,15,11,13,13,
  146812. 16,16,11,13,13,16,15,14,16,17,17,19,14,16,16,18,
  146813. 0, 9,11,11,14,15,10,13,12,16,15,11,13,13,16,16,
  146814. 14,15,14, 0,16,14,16,16,18, 0, 5, 7, 7,10,10, 7,
  146815. 9, 9,12,11, 7, 9, 9,11,12,10,11,11,15,14,10,11,
  146816. 12,14,14, 6, 9, 9,11,11, 9,11,11,13,13, 8,10,11,
  146817. 12,13,11,13,13,17,15,11,12,13,14,15, 7, 9, 9,11,
  146818. 12, 9,11,11,13,13, 9,11,11,13,13,11,13,12,16,16,
  146819. 11,13,13,15,14, 9,11,11,14,15,11,13,13,16,15,10,
  146820. 12,13,16,16,15,16,16, 0, 0,14,13,15,16,18,10,11,
  146821. 11,15,15,11,13,14,16,18,11,13,13,16,15,15,16,16,
  146822. 19, 0,14,15,15,16,16, 8,10,10,13,13,10,12,11,16,
  146823. 15,10,11,11,16,15,13,15,16,18, 0,13,14,15,17,17,
  146824. 9,11,11,15,15,11,13,13,16,18,11,13,13,16,17,15,
  146825. 16,16, 0, 0,15,18,16, 0,17, 9,11,11,15,15,11,13,
  146826. 12,17,15,11,13,14,16,17,15,18,15, 0,17,15,16,16,
  146827. 18,19,13,15,14, 0,18,14,16,16,19,18,14,16,15,19,
  146828. 19,16,18,19, 0, 0,16,17, 0, 0, 0,12,14,14,17,17,
  146829. 13,16,14, 0,18,14,16,15,18, 0,16,18,16,19,17,18,
  146830. 19,17, 0, 0, 8,10,10,14,14, 9,12,11,15,15,10,11,
  146831. 12,15,17,13,15,15,18,16,14,16,15,18,17, 9,11,11,
  146832. 16,15,11,13,13, 0,16,11,12,13,16,15,15,16,16, 0,
  146833. 17,15,15,16,18,17, 9,12,11,15,17,11,13,13,16,16,
  146834. 11,14,13,16,16,15,15,16,18,19,16,18,16, 0, 0,12,
  146835. 14,14, 0,16,14,16,16, 0,18,13,14,15,16, 0,17,16,
  146836. 18, 0, 0,16,16,17,19, 0,13,14,14,17, 0,14,17,16,
  146837. 0,19,14,15,15,18,19,17,16,18, 0, 0,15,19,16, 0,
  146838. 0,
  146839. };
  146840. static float _vq_quantthresh__44u7__p3_0[] = {
  146841. -1.5, -0.5, 0.5, 1.5,
  146842. };
  146843. static long _vq_quantmap__44u7__p3_0[] = {
  146844. 3, 1, 0, 2, 4,
  146845. };
  146846. static encode_aux_threshmatch _vq_auxt__44u7__p3_0 = {
  146847. _vq_quantthresh__44u7__p3_0,
  146848. _vq_quantmap__44u7__p3_0,
  146849. 5,
  146850. 5
  146851. };
  146852. static static_codebook _44u7__p3_0 = {
  146853. 4, 625,
  146854. _vq_lengthlist__44u7__p3_0,
  146855. 1, -533725184, 1611661312, 3, 0,
  146856. _vq_quantlist__44u7__p3_0,
  146857. NULL,
  146858. &_vq_auxt__44u7__p3_0,
  146859. NULL,
  146860. 0
  146861. };
  146862. static long _vq_quantlist__44u7__p4_0[] = {
  146863. 2,
  146864. 1,
  146865. 3,
  146866. 0,
  146867. 4,
  146868. };
  146869. static long _vq_lengthlist__44u7__p4_0[] = {
  146870. 4, 5, 5, 8, 8, 6, 7, 6, 9, 9, 6, 6, 7, 9, 9, 8,
  146871. 9, 9,11,11, 8, 9, 9,10,11, 6, 7, 7, 9, 9, 7, 8,
  146872. 8,10,10, 6, 7, 8, 9,10, 9,10,10,12,12, 9, 9,10,
  146873. 11,12, 6, 7, 7, 9, 9, 6, 8, 7,10, 9, 7, 8, 8,10,
  146874. 10, 9,10, 9,12,11, 9,10,10,12,11, 8, 9, 9,11,11,
  146875. 9,10,10,12,12, 9,10,10,12,12,11,12,12,13,14,11,
  146876. 11,12,13,13, 8, 9, 9,11,11, 9,10,10,12,11, 9,10,
  146877. 10,12,12,11,12,11,13,13,11,12,12,13,13, 6, 7, 7,
  146878. 9, 9, 7, 8, 7,10,10, 7, 7, 8,10,10, 9,10,10,12,
  146879. 11, 9,10,10,12,12, 7, 8, 8,10,10, 8, 8, 9,11,11,
  146880. 8, 9, 9,11,11,10,11,11,12,12,10,10,11,12,13, 6,
  146881. 7, 7,10,10, 7, 9, 8,11,10, 8, 8, 9,10,11,10,11,
  146882. 10,13,11,10,11,11,12,12, 9,10,10,12,12,10,10,11,
  146883. 13,13,10,11,11,13,12,12,12,13,13,14,12,12,13,14,
  146884. 14, 9,10,10,12,12, 9,10,10,12,12,10,11,11,13,13,
  146885. 11,12,11,14,12,12,13,13,14,14, 6, 7, 7, 9, 9, 7,
  146886. 8, 7,10,10, 7, 7, 8,10,10, 9,10,10,12,11, 9,10,
  146887. 10,11,12, 6, 7, 7,10,10, 8, 9, 8,11,10, 7, 8, 9,
  146888. 10,11,10,11,11,13,12,10,10,11,11,13, 7, 8, 8,10,
  146889. 10, 8, 9, 9,11,11, 8, 9, 9,11,11,10,11,10,13,12,
  146890. 10,11,11,12,12, 9,10,10,12,12,10,11,11,13,12, 9,
  146891. 10,10,12,13,12,13,12,14,14,11,11,12,12,14, 9,10,
  146892. 10,12,12,10,11,11,13,13,10,11,11,13,13,12,13,12,
  146893. 14,14,12,13,12,14,13, 8, 9, 9,11,11, 9,10,10,12,
  146894. 12, 9,10,10,12,12,11,12,12,14,13,11,12,12,13,13,
  146895. 9,10,10,12,12,10,11,11,13,13,10,11,11,13,12,12,
  146896. 13,13,14,14,12,12,13,14,14, 9,10,10,12,12, 9,11,
  146897. 10,13,12,10,10,11,12,13,11,13,12,14,13,12,12,13,
  146898. 14,14,11,12,12,13,13,11,12,13,14,14,12,13,13,14,
  146899. 14,13,13,14,14,16,13,14,14,16,16,11,11,11,13,13,
  146900. 11,12,11,14,13,12,12,13,14,15,13,14,12,16,13,14,
  146901. 14,14,15,16, 8, 9, 9,11,11, 9,10,10,12,12, 9,10,
  146902. 10,12,12,11,12,12,14,13,11,12,12,13,14, 9,10,10,
  146903. 12,12,10,11,10,13,12, 9,10,11,12,13,12,13,12,14,
  146904. 14,12,12,13,13,14, 9,10,10,12,12,10,11,11,12,13,
  146905. 10,11,11,13,13,12,13,12,14,14,12,13,13,14,14,11,
  146906. 12,12,13,13,12,13,12,14,14,11,11,12,13,14,13,15,
  146907. 14,16,15,13,12,14,13,16,11,12,12,13,13,12,13,13,
  146908. 14,14,12,12,12,14,14,13,14,14,15,15,13,14,13,16,
  146909. 14,
  146910. };
  146911. static float _vq_quantthresh__44u7__p4_0[] = {
  146912. -1.5, -0.5, 0.5, 1.5,
  146913. };
  146914. static long _vq_quantmap__44u7__p4_0[] = {
  146915. 3, 1, 0, 2, 4,
  146916. };
  146917. static encode_aux_threshmatch _vq_auxt__44u7__p4_0 = {
  146918. _vq_quantthresh__44u7__p4_0,
  146919. _vq_quantmap__44u7__p4_0,
  146920. 5,
  146921. 5
  146922. };
  146923. static static_codebook _44u7__p4_0 = {
  146924. 4, 625,
  146925. _vq_lengthlist__44u7__p4_0,
  146926. 1, -533725184, 1611661312, 3, 0,
  146927. _vq_quantlist__44u7__p4_0,
  146928. NULL,
  146929. &_vq_auxt__44u7__p4_0,
  146930. NULL,
  146931. 0
  146932. };
  146933. static long _vq_quantlist__44u7__p5_0[] = {
  146934. 4,
  146935. 3,
  146936. 5,
  146937. 2,
  146938. 6,
  146939. 1,
  146940. 7,
  146941. 0,
  146942. 8,
  146943. };
  146944. static long _vq_lengthlist__44u7__p5_0[] = {
  146945. 2, 3, 3, 6, 6, 7, 8,10,10, 4, 5, 5, 8, 7, 8, 8,
  146946. 11,11, 3, 5, 5, 7, 7, 8, 9,11,11, 6, 8, 7, 9, 9,
  146947. 10,10,12,12, 6, 7, 8, 9,10,10,10,12,12, 8, 8, 8,
  146948. 10,10,12,11,13,13, 8, 8, 9,10,10,11,11,13,13,10,
  146949. 11,11,12,12,13,13,14,14,10,11,11,12,12,13,13,14,
  146950. 14,
  146951. };
  146952. static float _vq_quantthresh__44u7__p5_0[] = {
  146953. -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5, 3.5,
  146954. };
  146955. static long _vq_quantmap__44u7__p5_0[] = {
  146956. 7, 5, 3, 1, 0, 2, 4, 6,
  146957. 8,
  146958. };
  146959. static encode_aux_threshmatch _vq_auxt__44u7__p5_0 = {
  146960. _vq_quantthresh__44u7__p5_0,
  146961. _vq_quantmap__44u7__p5_0,
  146962. 9,
  146963. 9
  146964. };
  146965. static static_codebook _44u7__p5_0 = {
  146966. 2, 81,
  146967. _vq_lengthlist__44u7__p5_0,
  146968. 1, -531628032, 1611661312, 4, 0,
  146969. _vq_quantlist__44u7__p5_0,
  146970. NULL,
  146971. &_vq_auxt__44u7__p5_0,
  146972. NULL,
  146973. 0
  146974. };
  146975. static long _vq_quantlist__44u7__p6_0[] = {
  146976. 4,
  146977. 3,
  146978. 5,
  146979. 2,
  146980. 6,
  146981. 1,
  146982. 7,
  146983. 0,
  146984. 8,
  146985. };
  146986. static long _vq_lengthlist__44u7__p6_0[] = {
  146987. 3, 4, 4, 5, 5, 7, 7, 9, 9, 4, 5, 4, 6, 6, 8, 7,
  146988. 9, 9, 4, 4, 5, 6, 6, 7, 7, 9, 9, 5, 6, 6, 7, 7,
  146989. 8, 8,10,10, 5, 6, 6, 7, 7, 8, 8,10,10, 7, 8, 7,
  146990. 8, 8,10, 9,11,11, 7, 7, 8, 8, 8, 9,10,11,11, 9,
  146991. 9, 9,10,10,11,10,12,11, 9, 9, 9,10,10,11,11,11,
  146992. 12,
  146993. };
  146994. static float _vq_quantthresh__44u7__p6_0[] = {
  146995. -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5, 3.5,
  146996. };
  146997. static long _vq_quantmap__44u7__p6_0[] = {
  146998. 7, 5, 3, 1, 0, 2, 4, 6,
  146999. 8,
  147000. };
  147001. static encode_aux_threshmatch _vq_auxt__44u7__p6_0 = {
  147002. _vq_quantthresh__44u7__p6_0,
  147003. _vq_quantmap__44u7__p6_0,
  147004. 9,
  147005. 9
  147006. };
  147007. static static_codebook _44u7__p6_0 = {
  147008. 2, 81,
  147009. _vq_lengthlist__44u7__p6_0,
  147010. 1, -531628032, 1611661312, 4, 0,
  147011. _vq_quantlist__44u7__p6_0,
  147012. NULL,
  147013. &_vq_auxt__44u7__p6_0,
  147014. NULL,
  147015. 0
  147016. };
  147017. static long _vq_quantlist__44u7__p7_0[] = {
  147018. 1,
  147019. 0,
  147020. 2,
  147021. };
  147022. static long _vq_lengthlist__44u7__p7_0[] = {
  147023. 1, 4, 4, 5, 7, 7, 5, 7, 7, 5, 9, 8, 8, 9, 9, 7,
  147024. 10,10, 5, 8, 9, 7, 9,10, 8, 9, 9, 4, 9, 9, 9,11,
  147025. 10, 8,10,10, 7,11,10,10,10,12,10,12,12, 7,10,10,
  147026. 10,12,11,10,12,12, 5, 9, 9, 8,10,10, 9,11,11, 7,
  147027. 11,10,10,12,12,10,11,12, 7,10,11,10,12,12,10,12,
  147028. 10,
  147029. };
  147030. static float _vq_quantthresh__44u7__p7_0[] = {
  147031. -5.5, 5.5,
  147032. };
  147033. static long _vq_quantmap__44u7__p7_0[] = {
  147034. 1, 0, 2,
  147035. };
  147036. static encode_aux_threshmatch _vq_auxt__44u7__p7_0 = {
  147037. _vq_quantthresh__44u7__p7_0,
  147038. _vq_quantmap__44u7__p7_0,
  147039. 3,
  147040. 3
  147041. };
  147042. static static_codebook _44u7__p7_0 = {
  147043. 4, 81,
  147044. _vq_lengthlist__44u7__p7_0,
  147045. 1, -529137664, 1618345984, 2, 0,
  147046. _vq_quantlist__44u7__p7_0,
  147047. NULL,
  147048. &_vq_auxt__44u7__p7_0,
  147049. NULL,
  147050. 0
  147051. };
  147052. static long _vq_quantlist__44u7__p7_1[] = {
  147053. 5,
  147054. 4,
  147055. 6,
  147056. 3,
  147057. 7,
  147058. 2,
  147059. 8,
  147060. 1,
  147061. 9,
  147062. 0,
  147063. 10,
  147064. };
  147065. static long _vq_lengthlist__44u7__p7_1[] = {
  147066. 3, 4, 4, 6, 6, 7, 7, 8, 8, 8, 8, 4, 5, 5, 6, 6,
  147067. 8, 7, 8, 8, 8, 8, 4, 5, 5, 6, 6, 7, 8, 8, 8, 8,
  147068. 8, 6, 7, 6, 7, 7, 8, 8, 9, 9, 9, 9, 6, 6, 7, 7,
  147069. 7, 8, 8, 9, 9, 9, 9, 7, 8, 7, 8, 8, 9, 9, 9, 9,
  147070. 9, 9, 7, 7, 8, 8, 8, 9, 9, 9, 9, 9, 9, 8, 8, 8,
  147071. 9, 9, 9, 9,10, 9, 9, 9, 8, 8, 8, 9, 9, 9, 9, 9,
  147072. 9, 9,10, 8, 8, 8, 9, 9, 9, 9,10, 9,10,10, 8, 8,
  147073. 8, 9, 9, 9, 9, 9,10,10,10,
  147074. };
  147075. static float _vq_quantthresh__44u7__p7_1[] = {
  147076. -4.5, -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5,
  147077. 3.5, 4.5,
  147078. };
  147079. static long _vq_quantmap__44u7__p7_1[] = {
  147080. 9, 7, 5, 3, 1, 0, 2, 4,
  147081. 6, 8, 10,
  147082. };
  147083. static encode_aux_threshmatch _vq_auxt__44u7__p7_1 = {
  147084. _vq_quantthresh__44u7__p7_1,
  147085. _vq_quantmap__44u7__p7_1,
  147086. 11,
  147087. 11
  147088. };
  147089. static static_codebook _44u7__p7_1 = {
  147090. 2, 121,
  147091. _vq_lengthlist__44u7__p7_1,
  147092. 1, -531365888, 1611661312, 4, 0,
  147093. _vq_quantlist__44u7__p7_1,
  147094. NULL,
  147095. &_vq_auxt__44u7__p7_1,
  147096. NULL,
  147097. 0
  147098. };
  147099. static long _vq_quantlist__44u7__p8_0[] = {
  147100. 5,
  147101. 4,
  147102. 6,
  147103. 3,
  147104. 7,
  147105. 2,
  147106. 8,
  147107. 1,
  147108. 9,
  147109. 0,
  147110. 10,
  147111. };
  147112. static long _vq_lengthlist__44u7__p8_0[] = {
  147113. 1, 4, 4, 6, 6, 8, 8,10,10,11,11, 4, 6, 6, 7, 7,
  147114. 9, 9,11,10,12,12, 5, 6, 5, 7, 7, 9, 9,10,11,12,
  147115. 12, 6, 7, 7, 8, 8,10,10,11,11,13,13, 6, 7, 7, 8,
  147116. 8,10,10,11,12,13,13, 8, 9, 9,10,10,11,11,12,12,
  147117. 14,14, 8, 9, 9,10,10,11,11,12,12,14,14,10,10,10,
  147118. 11,11,13,12,14,14,15,15,10,10,10,12,12,13,13,14,
  147119. 14,15,15,11,12,12,13,13,14,14,15,14,16,15,11,12,
  147120. 12,13,13,14,14,15,15,15,16,
  147121. };
  147122. static float _vq_quantthresh__44u7__p8_0[] = {
  147123. -49.5, -38.5, -27.5, -16.5, -5.5, 5.5, 16.5, 27.5,
  147124. 38.5, 49.5,
  147125. };
  147126. static long _vq_quantmap__44u7__p8_0[] = {
  147127. 9, 7, 5, 3, 1, 0, 2, 4,
  147128. 6, 8, 10,
  147129. };
  147130. static encode_aux_threshmatch _vq_auxt__44u7__p8_0 = {
  147131. _vq_quantthresh__44u7__p8_0,
  147132. _vq_quantmap__44u7__p8_0,
  147133. 11,
  147134. 11
  147135. };
  147136. static static_codebook _44u7__p8_0 = {
  147137. 2, 121,
  147138. _vq_lengthlist__44u7__p8_0,
  147139. 1, -524582912, 1618345984, 4, 0,
  147140. _vq_quantlist__44u7__p8_0,
  147141. NULL,
  147142. &_vq_auxt__44u7__p8_0,
  147143. NULL,
  147144. 0
  147145. };
  147146. static long _vq_quantlist__44u7__p8_1[] = {
  147147. 5,
  147148. 4,
  147149. 6,
  147150. 3,
  147151. 7,
  147152. 2,
  147153. 8,
  147154. 1,
  147155. 9,
  147156. 0,
  147157. 10,
  147158. };
  147159. static long _vq_lengthlist__44u7__p8_1[] = {
  147160. 4, 5, 5, 6, 6, 7, 7, 7, 7, 7, 7, 5, 6, 6, 7, 7,
  147161. 7, 7, 7, 7, 7, 7, 5, 6, 6, 6, 7, 7, 7, 7, 7, 7,
  147162. 7, 6, 7, 7, 7, 7, 7, 7, 7, 7, 8, 8, 6, 7, 7, 7,
  147163. 7, 7, 7, 7, 7, 8, 8, 7, 7, 7, 7, 7, 8, 7, 8, 8,
  147164. 8, 8, 7, 7, 7, 7, 7, 7, 8, 8, 8, 8, 8, 7, 7, 7,
  147165. 7, 7, 8, 8, 8, 8, 8, 8, 7, 7, 7, 7, 7, 8, 8, 8,
  147166. 8, 8, 8, 7, 7, 7, 8, 8, 8, 8, 8, 8, 8, 8, 7, 7,
  147167. 7, 8, 8, 8, 8, 8, 8, 8, 8,
  147168. };
  147169. static float _vq_quantthresh__44u7__p8_1[] = {
  147170. -4.5, -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5,
  147171. 3.5, 4.5,
  147172. };
  147173. static long _vq_quantmap__44u7__p8_1[] = {
  147174. 9, 7, 5, 3, 1, 0, 2, 4,
  147175. 6, 8, 10,
  147176. };
  147177. static encode_aux_threshmatch _vq_auxt__44u7__p8_1 = {
  147178. _vq_quantthresh__44u7__p8_1,
  147179. _vq_quantmap__44u7__p8_1,
  147180. 11,
  147181. 11
  147182. };
  147183. static static_codebook _44u7__p8_1 = {
  147184. 2, 121,
  147185. _vq_lengthlist__44u7__p8_1,
  147186. 1, -531365888, 1611661312, 4, 0,
  147187. _vq_quantlist__44u7__p8_1,
  147188. NULL,
  147189. &_vq_auxt__44u7__p8_1,
  147190. NULL,
  147191. 0
  147192. };
  147193. static long _vq_quantlist__44u7__p9_0[] = {
  147194. 5,
  147195. 4,
  147196. 6,
  147197. 3,
  147198. 7,
  147199. 2,
  147200. 8,
  147201. 1,
  147202. 9,
  147203. 0,
  147204. 10,
  147205. };
  147206. static long _vq_lengthlist__44u7__p9_0[] = {
  147207. 1, 3, 3,10,10,10,10,10,10,10,10, 4,10,10,10,10,
  147208. 10,10,10,10,10,10, 4,10,10,10,10,10,10,10,10,10,
  147209. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  147210. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  147211. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  147212. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  147213. 10,10,10,10,10,10,10,10,10,10,10,10,10, 9, 9, 9,
  147214. 9, 9, 9, 9, 9, 9, 9, 9, 9,
  147215. };
  147216. static float _vq_quantthresh__44u7__p9_0[] = {
  147217. -2866.5, -2229.5, -1592.5, -955.5, -318.5, 318.5, 955.5, 1592.5,
  147218. 2229.5, 2866.5,
  147219. };
  147220. static long _vq_quantmap__44u7__p9_0[] = {
  147221. 9, 7, 5, 3, 1, 0, 2, 4,
  147222. 6, 8, 10,
  147223. };
  147224. static encode_aux_threshmatch _vq_auxt__44u7__p9_0 = {
  147225. _vq_quantthresh__44u7__p9_0,
  147226. _vq_quantmap__44u7__p9_0,
  147227. 11,
  147228. 11
  147229. };
  147230. static static_codebook _44u7__p9_0 = {
  147231. 2, 121,
  147232. _vq_lengthlist__44u7__p9_0,
  147233. 1, -512171520, 1630791680, 4, 0,
  147234. _vq_quantlist__44u7__p9_0,
  147235. NULL,
  147236. &_vq_auxt__44u7__p9_0,
  147237. NULL,
  147238. 0
  147239. };
  147240. static long _vq_quantlist__44u7__p9_1[] = {
  147241. 6,
  147242. 5,
  147243. 7,
  147244. 4,
  147245. 8,
  147246. 3,
  147247. 9,
  147248. 2,
  147249. 10,
  147250. 1,
  147251. 11,
  147252. 0,
  147253. 12,
  147254. };
  147255. static long _vq_lengthlist__44u7__p9_1[] = {
  147256. 1, 4, 4, 6, 5, 8, 6, 9, 8,10, 9,11,10, 4, 6, 6,
  147257. 8, 8, 9, 9,11,10,11,11,11,11, 4, 6, 6, 8, 8,10,
  147258. 9,11,11,11,11,11,12, 6, 8, 8,10,10,11,11,12,12,
  147259. 13,12,13,13, 6, 8, 8,10,10,11,11,12,12,12,13,14,
  147260. 13, 8,10,10,11,11,12,13,14,14,14,14,15,15, 8,10,
  147261. 10,11,12,12,13,13,14,14,14,14,15, 9,11,11,13,13,
  147262. 14,14,15,14,16,15,17,15, 9,11,11,12,13,14,14,15,
  147263. 14,15,15,15,16,10,12,12,13,14,15,15,15,15,16,17,
  147264. 16,17,10,13,12,13,14,14,16,16,16,16,15,16,17,11,
  147265. 13,13,14,15,14,17,15,16,17,17,17,17,11,13,13,14,
  147266. 15,15,15,15,17,17,16,17,16,
  147267. };
  147268. static float _vq_quantthresh__44u7__p9_1[] = {
  147269. -269.5, -220.5, -171.5, -122.5, -73.5, -24.5, 24.5, 73.5,
  147270. 122.5, 171.5, 220.5, 269.5,
  147271. };
  147272. static long _vq_quantmap__44u7__p9_1[] = {
  147273. 11, 9, 7, 5, 3, 1, 0, 2,
  147274. 4, 6, 8, 10, 12,
  147275. };
  147276. static encode_aux_threshmatch _vq_auxt__44u7__p9_1 = {
  147277. _vq_quantthresh__44u7__p9_1,
  147278. _vq_quantmap__44u7__p9_1,
  147279. 13,
  147280. 13
  147281. };
  147282. static static_codebook _44u7__p9_1 = {
  147283. 2, 169,
  147284. _vq_lengthlist__44u7__p9_1,
  147285. 1, -518889472, 1622704128, 4, 0,
  147286. _vq_quantlist__44u7__p9_1,
  147287. NULL,
  147288. &_vq_auxt__44u7__p9_1,
  147289. NULL,
  147290. 0
  147291. };
  147292. static long _vq_quantlist__44u7__p9_2[] = {
  147293. 24,
  147294. 23,
  147295. 25,
  147296. 22,
  147297. 26,
  147298. 21,
  147299. 27,
  147300. 20,
  147301. 28,
  147302. 19,
  147303. 29,
  147304. 18,
  147305. 30,
  147306. 17,
  147307. 31,
  147308. 16,
  147309. 32,
  147310. 15,
  147311. 33,
  147312. 14,
  147313. 34,
  147314. 13,
  147315. 35,
  147316. 12,
  147317. 36,
  147318. 11,
  147319. 37,
  147320. 10,
  147321. 38,
  147322. 9,
  147323. 39,
  147324. 8,
  147325. 40,
  147326. 7,
  147327. 41,
  147328. 6,
  147329. 42,
  147330. 5,
  147331. 43,
  147332. 4,
  147333. 44,
  147334. 3,
  147335. 45,
  147336. 2,
  147337. 46,
  147338. 1,
  147339. 47,
  147340. 0,
  147341. 48,
  147342. };
  147343. static long _vq_lengthlist__44u7__p9_2[] = {
  147344. 2, 4, 4, 4, 4, 5, 5, 5, 5, 6, 6, 6, 6, 6, 6, 6,
  147345. 6, 6, 6, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7,
  147346. 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 8, 8, 8,
  147347. 8,
  147348. };
  147349. static float _vq_quantthresh__44u7__p9_2[] = {
  147350. -23.5, -22.5, -21.5, -20.5, -19.5, -18.5, -17.5, -16.5,
  147351. -15.5, -14.5, -13.5, -12.5, -11.5, -10.5, -9.5, -8.5,
  147352. -7.5, -6.5, -5.5, -4.5, -3.5, -2.5, -1.5, -0.5,
  147353. 0.5, 1.5, 2.5, 3.5, 4.5, 5.5, 6.5, 7.5,
  147354. 8.5, 9.5, 10.5, 11.5, 12.5, 13.5, 14.5, 15.5,
  147355. 16.5, 17.5, 18.5, 19.5, 20.5, 21.5, 22.5, 23.5,
  147356. };
  147357. static long _vq_quantmap__44u7__p9_2[] = {
  147358. 47, 45, 43, 41, 39, 37, 35, 33,
  147359. 31, 29, 27, 25, 23, 21, 19, 17,
  147360. 15, 13, 11, 9, 7, 5, 3, 1,
  147361. 0, 2, 4, 6, 8, 10, 12, 14,
  147362. 16, 18, 20, 22, 24, 26, 28, 30,
  147363. 32, 34, 36, 38, 40, 42, 44, 46,
  147364. 48,
  147365. };
  147366. static encode_aux_threshmatch _vq_auxt__44u7__p9_2 = {
  147367. _vq_quantthresh__44u7__p9_2,
  147368. _vq_quantmap__44u7__p9_2,
  147369. 49,
  147370. 49
  147371. };
  147372. static static_codebook _44u7__p9_2 = {
  147373. 1, 49,
  147374. _vq_lengthlist__44u7__p9_2,
  147375. 1, -526909440, 1611661312, 6, 0,
  147376. _vq_quantlist__44u7__p9_2,
  147377. NULL,
  147378. &_vq_auxt__44u7__p9_2,
  147379. NULL,
  147380. 0
  147381. };
  147382. static long _huff_lengthlist__44u7__short[] = {
  147383. 5,12,17,16,16,17,17,17,17,17, 4, 7,11,11,12, 9,
  147384. 17,10,17,17, 7, 7, 8, 9, 7, 9,11,10,15,17, 7, 9,
  147385. 10,11,10,12,14,12,16,17, 7, 8, 5, 7, 4, 7, 7, 8,
  147386. 16,16, 6,10, 9,10, 7,10,11,11,16,17, 6, 8, 8, 9,
  147387. 5, 7, 5, 8,16,17, 5, 5, 8, 7, 6, 7, 7, 6, 6,14,
  147388. 12,10,12,11, 7,11, 4, 4, 2, 7,17,15,15,15, 8,15,
  147389. 6, 8, 5, 9,
  147390. };
  147391. static static_codebook _huff_book__44u7__short = {
  147392. 2, 100,
  147393. _huff_lengthlist__44u7__short,
  147394. 0, 0, 0, 0, 0,
  147395. NULL,
  147396. NULL,
  147397. NULL,
  147398. NULL,
  147399. 0
  147400. };
  147401. static long _huff_lengthlist__44u8__long[] = {
  147402. 3, 9,13,14,14,15,14,14,15,15, 5, 4, 6, 8,10,12,
  147403. 12,14,15,15, 9, 5, 4, 5, 8,10,11,13,16,16,10, 7,
  147404. 4, 3, 5, 7, 9,11,13,13,10, 9, 7, 4, 4, 6, 8,10,
  147405. 12,14,13,11, 9, 6, 5, 5, 6, 8,12,14,13,11,10, 8,
  147406. 7, 6, 6, 7,10,14,13,11,12,10, 8, 7, 6, 6, 9,13,
  147407. 12,11,14,12,11, 9, 8, 7, 9,11,11,12,14,13,14,11,
  147408. 10, 8, 8, 9,
  147409. };
  147410. static static_codebook _huff_book__44u8__long = {
  147411. 2, 100,
  147412. _huff_lengthlist__44u8__long,
  147413. 0, 0, 0, 0, 0,
  147414. NULL,
  147415. NULL,
  147416. NULL,
  147417. NULL,
  147418. 0
  147419. };
  147420. static long _huff_lengthlist__44u8__short[] = {
  147421. 6,14,18,18,17,17,17,17,17,17, 4, 7, 9, 9,10,13,
  147422. 15,17,17,17, 6, 7, 5, 6, 8,11,16,17,16,17, 5, 7,
  147423. 5, 4, 6,10,14,17,17,17, 6, 6, 6, 5, 7,10,13,16,
  147424. 17,17, 7, 6, 7, 7, 7, 8, 7,10,15,16,12, 9, 9, 6,
  147425. 6, 5, 3, 5,11,15,14,14,13, 5, 5, 7, 3, 4, 8,15,
  147426. 17,17,13, 7, 7,10, 6, 6,10,15,17,17,16,10,11,14,
  147427. 10,10,15,17,
  147428. };
  147429. static static_codebook _huff_book__44u8__short = {
  147430. 2, 100,
  147431. _huff_lengthlist__44u8__short,
  147432. 0, 0, 0, 0, 0,
  147433. NULL,
  147434. NULL,
  147435. NULL,
  147436. NULL,
  147437. 0
  147438. };
  147439. static long _vq_quantlist__44u8_p1_0[] = {
  147440. 1,
  147441. 0,
  147442. 2,
  147443. };
  147444. static long _vq_lengthlist__44u8_p1_0[] = {
  147445. 1, 5, 5, 5, 7, 7, 5, 7, 7, 5, 7, 7, 8, 9, 9, 7,
  147446. 9, 9, 5, 7, 7, 7, 9, 9, 8, 9, 9, 5, 7, 7, 7, 9,
  147447. 9, 7, 9, 9, 7, 9, 9, 9,10,11, 9,11,10, 7, 9, 9,
  147448. 9,11,10, 9,10,11, 5, 7, 7, 7, 9, 9, 7, 9, 9, 7,
  147449. 9, 9, 9,11,10, 9,10,10, 8, 9, 9, 9,11,11, 9,11,
  147450. 10,
  147451. };
  147452. static float _vq_quantthresh__44u8_p1_0[] = {
  147453. -0.5, 0.5,
  147454. };
  147455. static long _vq_quantmap__44u8_p1_0[] = {
  147456. 1, 0, 2,
  147457. };
  147458. static encode_aux_threshmatch _vq_auxt__44u8_p1_0 = {
  147459. _vq_quantthresh__44u8_p1_0,
  147460. _vq_quantmap__44u8_p1_0,
  147461. 3,
  147462. 3
  147463. };
  147464. static static_codebook _44u8_p1_0 = {
  147465. 4, 81,
  147466. _vq_lengthlist__44u8_p1_0,
  147467. 1, -535822336, 1611661312, 2, 0,
  147468. _vq_quantlist__44u8_p1_0,
  147469. NULL,
  147470. &_vq_auxt__44u8_p1_0,
  147471. NULL,
  147472. 0
  147473. };
  147474. static long _vq_quantlist__44u8_p2_0[] = {
  147475. 2,
  147476. 1,
  147477. 3,
  147478. 0,
  147479. 4,
  147480. };
  147481. static long _vq_lengthlist__44u8_p2_0[] = {
  147482. 4, 5, 5, 8, 8, 5, 7, 6, 9, 9, 5, 6, 7, 9, 9, 8,
  147483. 9, 9,11,11, 8, 9, 9,11,11, 5, 7, 7, 9, 9, 7, 8,
  147484. 8,10,10, 7, 8, 8,10,10, 9,10,10,12,12, 9,10,10,
  147485. 11,12, 5, 7, 7, 9, 9, 7, 8, 7,10,10, 7, 8, 8,10,
  147486. 10, 9,10, 9,12,11, 9,10,10,12,12, 8, 9, 9,12,11,
  147487. 9,10,10,12,12, 9,10,10,12,12,11,12,12,14,14,11,
  147488. 11,12,13,14, 8, 9, 9,11,11, 9,10,10,12,12, 9,10,
  147489. 10,12,12,11,12,11,13,13,11,12,12,14,14, 5, 7, 7,
  147490. 9, 9, 7, 8, 8,10,10, 7, 8, 8,10,10, 9,10,10,12,
  147491. 12, 9,10,10,11,12, 7, 8, 8,10,10, 8, 9, 9,11,11,
  147492. 8, 9, 9,11,11,10,11,11,12,13,10,11,11,12,13, 6,
  147493. 8, 8,10,10, 8, 9, 8,11,10, 8, 9, 9,11,11,10,11,
  147494. 10,13,12,10,11,11,13,13, 9,10,10,12,12,10,11,11,
  147495. 13,13,10,11,11,13,13,12,12,13,13,14,12,13,13,14,
  147496. 14, 9,10,10,12,12,10,11,10,13,12,10,11,11,13,13,
  147497. 11,13,12,14,13,12,13,13,14,14, 5, 7, 7, 9, 9, 7,
  147498. 8, 8,10,10, 7, 8, 8,10,10, 9,10,10,12,12, 9,10,
  147499. 10,12,12, 7, 8, 8,10,10, 8, 9, 9,11,11, 8, 8, 9,
  147500. 10,11,10,11,11,13,13,10,10,11,12,13, 7, 8, 8,10,
  147501. 10, 8, 9, 9,11,11, 8, 9, 9,11,11,10,11,11,13,13,
  147502. 10,11,11,13,12, 9,10,10,12,12,10,11,11,13,13,10,
  147503. 10,11,12,13,12,13,13,14,14,12,12,13,13,14, 9,10,
  147504. 10,12,12,10,11,11,13,13,10,11,11,13,13,12,13,13,
  147505. 15,14,12,13,13,14,13, 8, 9, 9,11,11, 9,10,10,12,
  147506. 12, 9,10,10,12,12,12,12,12,14,13,11,12,12,14,14,
  147507. 9,10,10,12,12,10,11,11,13,13,10,11,11,13,13,12,
  147508. 13,13,14,15,12,13,13,14,15, 9,10,10,12,12,10,11,
  147509. 10,13,12,10,11,11,13,13,12,13,12,15,14,12,13,13,
  147510. 14,15,11,12,12,14,14,12,13,13,14,14,12,13,13,15,
  147511. 14,14,14,14,14,16,14,14,15,16,16,11,12,12,14,14,
  147512. 11,12,12,14,14,12,13,13,14,15,13,14,13,16,14,14,
  147513. 14,14,16,16, 8, 9, 9,11,11, 9,10,10,12,12, 9,10,
  147514. 10,12,12,11,12,12,14,13,11,12,12,14,14, 9,10,10,
  147515. 12,12,10,11,11,13,13,10,10,11,12,13,12,13,13,15,
  147516. 14,12,12,13,13,14, 9,10,10,12,12,10,11,11,13,13,
  147517. 10,11,11,13,13,12,13,13,14,14,12,13,13,15,14,11,
  147518. 12,12,14,13,12,13,13,15,14,11,12,12,13,14,14,15,
  147519. 14,16,15,13,13,14,13,16,11,12,12,14,14,12,13,13,
  147520. 14,15,12,13,12,15,14,14,14,14,16,15,14,15,13,16,
  147521. 14,
  147522. };
  147523. static float _vq_quantthresh__44u8_p2_0[] = {
  147524. -1.5, -0.5, 0.5, 1.5,
  147525. };
  147526. static long _vq_quantmap__44u8_p2_0[] = {
  147527. 3, 1, 0, 2, 4,
  147528. };
  147529. static encode_aux_threshmatch _vq_auxt__44u8_p2_0 = {
  147530. _vq_quantthresh__44u8_p2_0,
  147531. _vq_quantmap__44u8_p2_0,
  147532. 5,
  147533. 5
  147534. };
  147535. static static_codebook _44u8_p2_0 = {
  147536. 4, 625,
  147537. _vq_lengthlist__44u8_p2_0,
  147538. 1, -533725184, 1611661312, 3, 0,
  147539. _vq_quantlist__44u8_p2_0,
  147540. NULL,
  147541. &_vq_auxt__44u8_p2_0,
  147542. NULL,
  147543. 0
  147544. };
  147545. static long _vq_quantlist__44u8_p3_0[] = {
  147546. 4,
  147547. 3,
  147548. 5,
  147549. 2,
  147550. 6,
  147551. 1,
  147552. 7,
  147553. 0,
  147554. 8,
  147555. };
  147556. static long _vq_lengthlist__44u8_p3_0[] = {
  147557. 3, 4, 4, 5, 5, 7, 7, 9, 9, 4, 5, 4, 6, 6, 7, 7,
  147558. 9, 9, 4, 4, 5, 6, 6, 7, 7, 9, 9, 5, 6, 6, 7, 7,
  147559. 8, 8,10,10, 6, 6, 6, 7, 7, 8, 8,10,10, 7, 7, 7,
  147560. 8, 8, 9, 9,11,10, 7, 7, 7, 8, 8, 9, 9,10,11, 9,
  147561. 9, 9,10,10,11,10,12,11, 9, 9, 9, 9,10,11,11,11,
  147562. 12,
  147563. };
  147564. static float _vq_quantthresh__44u8_p3_0[] = {
  147565. -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5, 3.5,
  147566. };
  147567. static long _vq_quantmap__44u8_p3_0[] = {
  147568. 7, 5, 3, 1, 0, 2, 4, 6,
  147569. 8,
  147570. };
  147571. static encode_aux_threshmatch _vq_auxt__44u8_p3_0 = {
  147572. _vq_quantthresh__44u8_p3_0,
  147573. _vq_quantmap__44u8_p3_0,
  147574. 9,
  147575. 9
  147576. };
  147577. static static_codebook _44u8_p3_0 = {
  147578. 2, 81,
  147579. _vq_lengthlist__44u8_p3_0,
  147580. 1, -531628032, 1611661312, 4, 0,
  147581. _vq_quantlist__44u8_p3_0,
  147582. NULL,
  147583. &_vq_auxt__44u8_p3_0,
  147584. NULL,
  147585. 0
  147586. };
  147587. static long _vq_quantlist__44u8_p4_0[] = {
  147588. 8,
  147589. 7,
  147590. 9,
  147591. 6,
  147592. 10,
  147593. 5,
  147594. 11,
  147595. 4,
  147596. 12,
  147597. 3,
  147598. 13,
  147599. 2,
  147600. 14,
  147601. 1,
  147602. 15,
  147603. 0,
  147604. 16,
  147605. };
  147606. static long _vq_lengthlist__44u8_p4_0[] = {
  147607. 4, 4, 4, 6, 6, 7, 7, 8, 8, 8, 8,10,10,11,11,11,
  147608. 11, 4, 5, 5, 6, 6, 7, 7, 8, 8, 9, 9,10,10,11,11,
  147609. 12,12, 4, 5, 5, 6, 6, 7, 7, 8, 8, 9, 9,10,10,11,
  147610. 11,12,12, 6, 6, 6, 7, 7, 8, 8, 9, 9, 9, 9,10,10,
  147611. 11,11,12,12, 6, 6, 6, 7, 7, 8, 8, 9, 9, 9, 9,10,
  147612. 10,11,11,12,12, 7, 7, 7, 8, 8, 9, 8,10, 9,10, 9,
  147613. 11,10,12,11,13,12, 7, 7, 7, 8, 8, 8, 9, 9,10, 9,
  147614. 10,10,11,11,12,12,13, 8, 8, 8, 9, 9, 9, 9,10,10,
  147615. 11,10,11,11,12,12,13,13, 8, 8, 8, 9, 9, 9,10,10,
  147616. 10,10,11,11,11,12,12,12,13, 8, 9, 9, 9, 9,10, 9,
  147617. 11,10,11,11,12,11,13,12,13,13, 8, 9, 9, 9, 9, 9,
  147618. 10,10,11,11,11,11,12,12,13,13,13,10,10,10,10,10,
  147619. 11,10,11,11,12,11,13,12,13,13,14,13,10,10,10,10,
  147620. 10,10,11,11,11,11,12,12,13,13,13,13,14,11,11,11,
  147621. 11,11,12,11,12,12,13,12,13,13,14,13,14,14,11,11,
  147622. 11,11,11,11,12,12,12,12,13,13,13,13,14,14,14,11,
  147623. 12,12,12,12,13,12,13,12,13,13,14,13,14,14,14,14,
  147624. 11,12,12,12,12,12,12,13,13,13,13,13,14,14,14,14,
  147625. 14,
  147626. };
  147627. static float _vq_quantthresh__44u8_p4_0[] = {
  147628. -7.5, -6.5, -5.5, -4.5, -3.5, -2.5, -1.5, -0.5,
  147629. 0.5, 1.5, 2.5, 3.5, 4.5, 5.5, 6.5, 7.5,
  147630. };
  147631. static long _vq_quantmap__44u8_p4_0[] = {
  147632. 15, 13, 11, 9, 7, 5, 3, 1,
  147633. 0, 2, 4, 6, 8, 10, 12, 14,
  147634. 16,
  147635. };
  147636. static encode_aux_threshmatch _vq_auxt__44u8_p4_0 = {
  147637. _vq_quantthresh__44u8_p4_0,
  147638. _vq_quantmap__44u8_p4_0,
  147639. 17,
  147640. 17
  147641. };
  147642. static static_codebook _44u8_p4_0 = {
  147643. 2, 289,
  147644. _vq_lengthlist__44u8_p4_0,
  147645. 1, -529530880, 1611661312, 5, 0,
  147646. _vq_quantlist__44u8_p4_0,
  147647. NULL,
  147648. &_vq_auxt__44u8_p4_0,
  147649. NULL,
  147650. 0
  147651. };
  147652. static long _vq_quantlist__44u8_p5_0[] = {
  147653. 1,
  147654. 0,
  147655. 2,
  147656. };
  147657. static long _vq_lengthlist__44u8_p5_0[] = {
  147658. 1, 4, 4, 5, 7, 7, 5, 7, 7, 5, 8, 8, 8, 9, 9, 7,
  147659. 9, 9, 5, 8, 8, 7, 9, 9, 8, 9, 9, 5, 8, 8, 8,10,
  147660. 10, 8,10,10, 7,10,10, 9,10,12, 9,12,11, 7,10,10,
  147661. 9,11,10, 9,11,12, 5, 8, 8, 8,10,10, 8,10,10, 7,
  147662. 10,10, 9,11,11, 9,10,11, 7,10,10, 9,11,11,10,12,
  147663. 10,
  147664. };
  147665. static float _vq_quantthresh__44u8_p5_0[] = {
  147666. -5.5, 5.5,
  147667. };
  147668. static long _vq_quantmap__44u8_p5_0[] = {
  147669. 1, 0, 2,
  147670. };
  147671. static encode_aux_threshmatch _vq_auxt__44u8_p5_0 = {
  147672. _vq_quantthresh__44u8_p5_0,
  147673. _vq_quantmap__44u8_p5_0,
  147674. 3,
  147675. 3
  147676. };
  147677. static static_codebook _44u8_p5_0 = {
  147678. 4, 81,
  147679. _vq_lengthlist__44u8_p5_0,
  147680. 1, -529137664, 1618345984, 2, 0,
  147681. _vq_quantlist__44u8_p5_0,
  147682. NULL,
  147683. &_vq_auxt__44u8_p5_0,
  147684. NULL,
  147685. 0
  147686. };
  147687. static long _vq_quantlist__44u8_p5_1[] = {
  147688. 5,
  147689. 4,
  147690. 6,
  147691. 3,
  147692. 7,
  147693. 2,
  147694. 8,
  147695. 1,
  147696. 9,
  147697. 0,
  147698. 10,
  147699. };
  147700. static long _vq_lengthlist__44u8_p5_1[] = {
  147701. 4, 5, 5, 6, 6, 7, 7, 7, 7, 8, 8, 5, 5, 5, 6, 6,
  147702. 7, 7, 8, 8, 8, 8, 5, 5, 5, 6, 6, 7, 7, 7, 8, 8,
  147703. 8, 6, 6, 6, 7, 7, 7, 7, 8, 8, 8, 8, 6, 6, 6, 7,
  147704. 7, 7, 7, 8, 8, 8, 8, 7, 7, 7, 7, 7, 8, 8, 8, 8,
  147705. 8, 8, 7, 7, 7, 7, 7, 8, 8, 8, 8, 8, 8, 7, 8, 7,
  147706. 8, 8, 8, 8, 8, 8, 8, 8, 7, 8, 8, 8, 8, 8, 8, 8,
  147707. 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 9, 9, 8, 8,
  147708. 8, 8, 8, 8, 8, 8, 8, 9, 9,
  147709. };
  147710. static float _vq_quantthresh__44u8_p5_1[] = {
  147711. -4.5, -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5,
  147712. 3.5, 4.5,
  147713. };
  147714. static long _vq_quantmap__44u8_p5_1[] = {
  147715. 9, 7, 5, 3, 1, 0, 2, 4,
  147716. 6, 8, 10,
  147717. };
  147718. static encode_aux_threshmatch _vq_auxt__44u8_p5_1 = {
  147719. _vq_quantthresh__44u8_p5_1,
  147720. _vq_quantmap__44u8_p5_1,
  147721. 11,
  147722. 11
  147723. };
  147724. static static_codebook _44u8_p5_1 = {
  147725. 2, 121,
  147726. _vq_lengthlist__44u8_p5_1,
  147727. 1, -531365888, 1611661312, 4, 0,
  147728. _vq_quantlist__44u8_p5_1,
  147729. NULL,
  147730. &_vq_auxt__44u8_p5_1,
  147731. NULL,
  147732. 0
  147733. };
  147734. static long _vq_quantlist__44u8_p6_0[] = {
  147735. 6,
  147736. 5,
  147737. 7,
  147738. 4,
  147739. 8,
  147740. 3,
  147741. 9,
  147742. 2,
  147743. 10,
  147744. 1,
  147745. 11,
  147746. 0,
  147747. 12,
  147748. };
  147749. static long _vq_lengthlist__44u8_p6_0[] = {
  147750. 2, 4, 4, 6, 6, 7, 7, 8, 8, 9, 9,10,10, 4, 6, 5,
  147751. 7, 7, 8, 8, 8, 8, 9, 9,10,10, 4, 6, 6, 7, 7, 8,
  147752. 8, 8, 8, 9, 9,10,10, 6, 7, 7, 7, 8, 8, 8, 8, 9,
  147753. 9,10,10,10, 6, 7, 7, 8, 8, 8, 8, 9, 8,10, 9,11,
  147754. 10, 7, 8, 8, 8, 8, 8, 9, 9, 9,10,10,11,11, 7, 8,
  147755. 8, 8, 8, 9, 8, 9, 9,10,10,11,11, 8, 8, 8, 9, 9,
  147756. 9, 9, 9,10,10,10,11,11, 8, 8, 8, 9, 9, 9, 9,10,
  147757. 9,10,10,11,11, 9, 9, 9, 9,10,10,10,10,10,10,11,
  147758. 11,12, 9, 9, 9,10, 9,10,10,10,10,11,10,12,11,10,
  147759. 10,10,10,10,11,11,11,11,11,12,12,12,10,10,10,10,
  147760. 11,11,11,11,11,12,11,12,12,
  147761. };
  147762. static float _vq_quantthresh__44u8_p6_0[] = {
  147763. -27.5, -22.5, -17.5, -12.5, -7.5, -2.5, 2.5, 7.5,
  147764. 12.5, 17.5, 22.5, 27.5,
  147765. };
  147766. static long _vq_quantmap__44u8_p6_0[] = {
  147767. 11, 9, 7, 5, 3, 1, 0, 2,
  147768. 4, 6, 8, 10, 12,
  147769. };
  147770. static encode_aux_threshmatch _vq_auxt__44u8_p6_0 = {
  147771. _vq_quantthresh__44u8_p6_0,
  147772. _vq_quantmap__44u8_p6_0,
  147773. 13,
  147774. 13
  147775. };
  147776. static static_codebook _44u8_p6_0 = {
  147777. 2, 169,
  147778. _vq_lengthlist__44u8_p6_0,
  147779. 1, -526516224, 1616117760, 4, 0,
  147780. _vq_quantlist__44u8_p6_0,
  147781. NULL,
  147782. &_vq_auxt__44u8_p6_0,
  147783. NULL,
  147784. 0
  147785. };
  147786. static long _vq_quantlist__44u8_p6_1[] = {
  147787. 2,
  147788. 1,
  147789. 3,
  147790. 0,
  147791. 4,
  147792. };
  147793. static long _vq_lengthlist__44u8_p6_1[] = {
  147794. 3, 4, 4, 5, 5, 4, 5, 5, 5, 5, 4, 5, 5, 5, 5, 5,
  147795. 5, 5, 5, 5, 5, 5, 5, 5, 5,
  147796. };
  147797. static float _vq_quantthresh__44u8_p6_1[] = {
  147798. -1.5, -0.5, 0.5, 1.5,
  147799. };
  147800. static long _vq_quantmap__44u8_p6_1[] = {
  147801. 3, 1, 0, 2, 4,
  147802. };
  147803. static encode_aux_threshmatch _vq_auxt__44u8_p6_1 = {
  147804. _vq_quantthresh__44u8_p6_1,
  147805. _vq_quantmap__44u8_p6_1,
  147806. 5,
  147807. 5
  147808. };
  147809. static static_codebook _44u8_p6_1 = {
  147810. 2, 25,
  147811. _vq_lengthlist__44u8_p6_1,
  147812. 1, -533725184, 1611661312, 3, 0,
  147813. _vq_quantlist__44u8_p6_1,
  147814. NULL,
  147815. &_vq_auxt__44u8_p6_1,
  147816. NULL,
  147817. 0
  147818. };
  147819. static long _vq_quantlist__44u8_p7_0[] = {
  147820. 6,
  147821. 5,
  147822. 7,
  147823. 4,
  147824. 8,
  147825. 3,
  147826. 9,
  147827. 2,
  147828. 10,
  147829. 1,
  147830. 11,
  147831. 0,
  147832. 12,
  147833. };
  147834. static long _vq_lengthlist__44u8_p7_0[] = {
  147835. 1, 4, 5, 6, 6, 7, 7, 8, 8,10,10,11,11, 5, 6, 6,
  147836. 7, 7, 8, 8, 9, 9,11,10,12,11, 5, 6, 6, 7, 7, 8,
  147837. 8, 9, 9,10,11,11,12, 6, 7, 7, 8, 8, 9, 9,10,10,
  147838. 11,11,12,12, 6, 7, 7, 8, 8, 9, 9,10,10,11,12,13,
  147839. 12, 7, 8, 8, 9, 9,10,10,11,11,12,12,13,13, 8, 8,
  147840. 8, 9, 9,10,10,11,11,12,12,13,13, 9, 9, 9,10,10,
  147841. 11,11,12,12,13,13,14,14, 9, 9, 9,10,10,11,11,12,
  147842. 12,13,13,14,14,10,11,11,12,11,13,12,13,13,14,14,
  147843. 15,15,10,11,11,11,12,12,13,13,14,14,14,15,15,11,
  147844. 12,12,13,13,14,13,15,14,15,15,16,15,11,11,12,13,
  147845. 13,13,14,14,14,15,15,15,16,
  147846. };
  147847. static float _vq_quantthresh__44u8_p7_0[] = {
  147848. -60.5, -49.5, -38.5, -27.5, -16.5, -5.5, 5.5, 16.5,
  147849. 27.5, 38.5, 49.5, 60.5,
  147850. };
  147851. static long _vq_quantmap__44u8_p7_0[] = {
  147852. 11, 9, 7, 5, 3, 1, 0, 2,
  147853. 4, 6, 8, 10, 12,
  147854. };
  147855. static encode_aux_threshmatch _vq_auxt__44u8_p7_0 = {
  147856. _vq_quantthresh__44u8_p7_0,
  147857. _vq_quantmap__44u8_p7_0,
  147858. 13,
  147859. 13
  147860. };
  147861. static static_codebook _44u8_p7_0 = {
  147862. 2, 169,
  147863. _vq_lengthlist__44u8_p7_0,
  147864. 1, -523206656, 1618345984, 4, 0,
  147865. _vq_quantlist__44u8_p7_0,
  147866. NULL,
  147867. &_vq_auxt__44u8_p7_0,
  147868. NULL,
  147869. 0
  147870. };
  147871. static long _vq_quantlist__44u8_p7_1[] = {
  147872. 5,
  147873. 4,
  147874. 6,
  147875. 3,
  147876. 7,
  147877. 2,
  147878. 8,
  147879. 1,
  147880. 9,
  147881. 0,
  147882. 10,
  147883. };
  147884. static long _vq_lengthlist__44u8_p7_1[] = {
  147885. 4, 5, 5, 6, 6, 7, 7, 7, 7, 7, 7, 5, 6, 6, 7, 7,
  147886. 7, 7, 7, 7, 7, 7, 5, 6, 6, 7, 7, 7, 7, 7, 7, 7,
  147887. 7, 6, 7, 7, 7, 7, 7, 7, 7, 7, 8, 8, 6, 7, 7, 7,
  147888. 7, 7, 7, 7, 7, 7, 8, 7, 7, 7, 7, 7, 7, 7, 8, 8,
  147889. 8, 8, 7, 7, 7, 7, 7, 7, 7, 8, 8, 8, 8, 7, 7, 7,
  147890. 8, 7, 8, 8, 8, 8, 8, 8, 7, 7, 7, 7, 7, 8, 8, 8,
  147891. 8, 8, 8, 7, 7, 7, 8, 8, 8, 8, 8, 8, 8, 8, 7, 7,
  147892. 7, 8, 8, 8, 8, 8, 8, 8, 8,
  147893. };
  147894. static float _vq_quantthresh__44u8_p7_1[] = {
  147895. -4.5, -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5,
  147896. 3.5, 4.5,
  147897. };
  147898. static long _vq_quantmap__44u8_p7_1[] = {
  147899. 9, 7, 5, 3, 1, 0, 2, 4,
  147900. 6, 8, 10,
  147901. };
  147902. static encode_aux_threshmatch _vq_auxt__44u8_p7_1 = {
  147903. _vq_quantthresh__44u8_p7_1,
  147904. _vq_quantmap__44u8_p7_1,
  147905. 11,
  147906. 11
  147907. };
  147908. static static_codebook _44u8_p7_1 = {
  147909. 2, 121,
  147910. _vq_lengthlist__44u8_p7_1,
  147911. 1, -531365888, 1611661312, 4, 0,
  147912. _vq_quantlist__44u8_p7_1,
  147913. NULL,
  147914. &_vq_auxt__44u8_p7_1,
  147915. NULL,
  147916. 0
  147917. };
  147918. static long _vq_quantlist__44u8_p8_0[] = {
  147919. 7,
  147920. 6,
  147921. 8,
  147922. 5,
  147923. 9,
  147924. 4,
  147925. 10,
  147926. 3,
  147927. 11,
  147928. 2,
  147929. 12,
  147930. 1,
  147931. 13,
  147932. 0,
  147933. 14,
  147934. };
  147935. static long _vq_lengthlist__44u8_p8_0[] = {
  147936. 1, 4, 4, 7, 7, 8, 8, 8, 7, 9, 8,10, 9,11,10, 4,
  147937. 6, 6, 8, 8,10, 9, 9, 9,10,10,11,10,12,10, 4, 6,
  147938. 6, 8, 8,10,10, 9, 9,10,10,11,11,11,12, 7, 8, 8,
  147939. 10,10,11,11,11,10,12,11,12,12,13,11, 7, 8, 8,10,
  147940. 10,11,11,10,10,11,11,12,12,13,13, 8,10,10,11,11,
  147941. 12,11,12,11,13,12,13,12,14,13, 8,10, 9,11,11,12,
  147942. 12,12,12,12,12,13,13,14,13, 8, 9, 9,11,10,12,11,
  147943. 13,12,13,13,14,13,14,13, 8, 9, 9,10,11,12,12,12,
  147944. 12,13,13,14,15,14,14, 9,10,10,12,11,13,12,13,13,
  147945. 14,13,14,14,14,14, 9,10,10,12,12,12,12,13,13,14,
  147946. 14,14,15,14,14,10,11,11,13,12,13,12,14,14,14,14,
  147947. 14,14,15,15,10,11,11,12,12,13,13,14,14,14,15,15,
  147948. 14,16,15,11,12,12,13,12,14,14,14,13,15,14,15,15,
  147949. 15,17,11,12,12,13,13,14,14,14,15,15,14,15,15,14,
  147950. 17,
  147951. };
  147952. static float _vq_quantthresh__44u8_p8_0[] = {
  147953. -136.5, -115.5, -94.5, -73.5, -52.5, -31.5, -10.5, 10.5,
  147954. 31.5, 52.5, 73.5, 94.5, 115.5, 136.5,
  147955. };
  147956. static long _vq_quantmap__44u8_p8_0[] = {
  147957. 13, 11, 9, 7, 5, 3, 1, 0,
  147958. 2, 4, 6, 8, 10, 12, 14,
  147959. };
  147960. static encode_aux_threshmatch _vq_auxt__44u8_p8_0 = {
  147961. _vq_quantthresh__44u8_p8_0,
  147962. _vq_quantmap__44u8_p8_0,
  147963. 15,
  147964. 15
  147965. };
  147966. static static_codebook _44u8_p8_0 = {
  147967. 2, 225,
  147968. _vq_lengthlist__44u8_p8_0,
  147969. 1, -520986624, 1620377600, 4, 0,
  147970. _vq_quantlist__44u8_p8_0,
  147971. NULL,
  147972. &_vq_auxt__44u8_p8_0,
  147973. NULL,
  147974. 0
  147975. };
  147976. static long _vq_quantlist__44u8_p8_1[] = {
  147977. 10,
  147978. 9,
  147979. 11,
  147980. 8,
  147981. 12,
  147982. 7,
  147983. 13,
  147984. 6,
  147985. 14,
  147986. 5,
  147987. 15,
  147988. 4,
  147989. 16,
  147990. 3,
  147991. 17,
  147992. 2,
  147993. 18,
  147994. 1,
  147995. 19,
  147996. 0,
  147997. 20,
  147998. };
  147999. static long _vq_lengthlist__44u8_p8_1[] = {
  148000. 4, 6, 6, 7, 7, 8, 8, 8, 8, 9, 9, 9, 9, 9, 9, 9,
  148001. 9, 9, 9, 9, 9, 6, 6, 6, 7, 7, 8, 8, 8, 8, 9, 9,
  148002. 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 5, 6, 6, 7, 7, 8,
  148003. 8, 9, 8, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 7,
  148004. 7, 7, 8, 8, 8, 8, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,
  148005. 9, 9, 9, 9, 7, 7, 7, 8, 8, 8, 8, 9, 9, 9, 9, 9,
  148006. 9, 9, 9, 9, 9, 9, 9, 9, 9, 8, 8, 8, 8, 8, 9, 9,
  148007. 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,10,10, 9,10, 8, 8,
  148008. 8, 8, 8, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,10, 9,10,
  148009. 10, 9,10, 8, 9, 8, 9, 9, 9, 9, 9, 9, 9, 9,10, 9,
  148010. 10,10,10,10,10,10,10,10, 8, 9, 8, 9, 9, 9, 9, 9,
  148011. 9, 9, 9, 9, 9, 9,10,10,10,10, 9,10,10, 9, 9, 9,
  148012. 9, 9, 9, 9, 9, 9, 9, 9,10, 9,10,10,10,10,10,10,
  148013. 10,10, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,10, 9,10,
  148014. 10,10,10,10,10,10,10, 9, 9, 9, 9, 9, 9, 9,10, 9,
  148015. 10,10,10,10,10,10,10,10,10,10,10,10, 9, 9, 9, 9,
  148016. 9, 9, 9, 9, 9, 9,10,10,10,10,10,10,10,10,10,10,
  148017. 10, 9, 9, 9, 9, 9, 9,10,10,10,10,10,10,10,10,10,
  148018. 10,10,10,10,10,10, 9, 9, 9, 9, 9, 9, 9,10,10,10,
  148019. 10,10,10,10,10,10,10,10,10,10,10, 9, 9, 9, 9, 9,
  148020. 9, 9,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  148021. 9, 9, 9, 9, 9,10,10,10,10,10,10,10,10,10,10,10,
  148022. 10,10,10,10,10, 9, 9, 9,10, 9,10,10,10,10,10,10,
  148023. 10,10,10,10,10,10,10,10,10,10, 9, 9, 9, 9, 9,10,
  148024. 9,10,10,10,10,10,10,10,10,10,10,10,10,10,10, 9,
  148025. 9, 9, 9, 9, 9,10,10,10,10,10,10,10,10,10,10,10,
  148026. 10,10,10,10, 9, 9, 9,10, 9,10, 9,10,10,10,10,10,
  148027. 10,10,10,10,10,10,10,10,10,
  148028. };
  148029. static float _vq_quantthresh__44u8_p8_1[] = {
  148030. -9.5, -8.5, -7.5, -6.5, -5.5, -4.5, -3.5, -2.5,
  148031. -1.5, -0.5, 0.5, 1.5, 2.5, 3.5, 4.5, 5.5,
  148032. 6.5, 7.5, 8.5, 9.5,
  148033. };
  148034. static long _vq_quantmap__44u8_p8_1[] = {
  148035. 19, 17, 15, 13, 11, 9, 7, 5,
  148036. 3, 1, 0, 2, 4, 6, 8, 10,
  148037. 12, 14, 16, 18, 20,
  148038. };
  148039. static encode_aux_threshmatch _vq_auxt__44u8_p8_1 = {
  148040. _vq_quantthresh__44u8_p8_1,
  148041. _vq_quantmap__44u8_p8_1,
  148042. 21,
  148043. 21
  148044. };
  148045. static static_codebook _44u8_p8_1 = {
  148046. 2, 441,
  148047. _vq_lengthlist__44u8_p8_1,
  148048. 1, -529268736, 1611661312, 5, 0,
  148049. _vq_quantlist__44u8_p8_1,
  148050. NULL,
  148051. &_vq_auxt__44u8_p8_1,
  148052. NULL,
  148053. 0
  148054. };
  148055. static long _vq_quantlist__44u8_p9_0[] = {
  148056. 4,
  148057. 3,
  148058. 5,
  148059. 2,
  148060. 6,
  148061. 1,
  148062. 7,
  148063. 0,
  148064. 8,
  148065. };
  148066. static long _vq_lengthlist__44u8_p9_0[] = {
  148067. 1, 3, 3, 9, 9, 9, 9, 9, 9, 4, 9, 9, 9, 9, 9, 9,
  148068. 9, 9, 5, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,
  148069. 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,
  148070. 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,
  148071. 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 8, 8, 8,
  148072. 8,
  148073. };
  148074. static float _vq_quantthresh__44u8_p9_0[] = {
  148075. -3258.5, -2327.5, -1396.5, -465.5, 465.5, 1396.5, 2327.5, 3258.5,
  148076. };
  148077. static long _vq_quantmap__44u8_p9_0[] = {
  148078. 7, 5, 3, 1, 0, 2, 4, 6,
  148079. 8,
  148080. };
  148081. static encode_aux_threshmatch _vq_auxt__44u8_p9_0 = {
  148082. _vq_quantthresh__44u8_p9_0,
  148083. _vq_quantmap__44u8_p9_0,
  148084. 9,
  148085. 9
  148086. };
  148087. static static_codebook _44u8_p9_0 = {
  148088. 2, 81,
  148089. _vq_lengthlist__44u8_p9_0,
  148090. 1, -511895552, 1631393792, 4, 0,
  148091. _vq_quantlist__44u8_p9_0,
  148092. NULL,
  148093. &_vq_auxt__44u8_p9_0,
  148094. NULL,
  148095. 0
  148096. };
  148097. static long _vq_quantlist__44u8_p9_1[] = {
  148098. 9,
  148099. 8,
  148100. 10,
  148101. 7,
  148102. 11,
  148103. 6,
  148104. 12,
  148105. 5,
  148106. 13,
  148107. 4,
  148108. 14,
  148109. 3,
  148110. 15,
  148111. 2,
  148112. 16,
  148113. 1,
  148114. 17,
  148115. 0,
  148116. 18,
  148117. };
  148118. static long _vq_lengthlist__44u8_p9_1[] = {
  148119. 1, 4, 4, 7, 7, 8, 7, 8, 6, 9, 7,10, 8,11,10,11,
  148120. 11,11,11, 4, 7, 6, 9, 9,10, 9, 9, 9,10,10,11,10,
  148121. 11,10,11,11,13,11, 4, 7, 7, 9, 9, 9, 9, 9, 9,10,
  148122. 10,11,10,11,11,11,12,11,12, 7, 9, 8,11,11,11,11,
  148123. 10,10,11,11,12,12,12,12,12,12,14,13, 7, 8, 9,10,
  148124. 11,11,11,10,10,11,11,11,11,12,12,14,12,13,14, 8,
  148125. 9, 9,11,11,11,11,11,11,12,12,14,12,15,14,14,14,
  148126. 15,14, 8, 9, 9,11,11,11,11,12,11,12,12,13,13,13,
  148127. 13,13,13,14,14, 8, 9, 9,11,10,12,11,12,12,13,13,
  148128. 13,13,15,14,14,14,16,16, 8, 9, 9,10,11,11,12,12,
  148129. 12,13,13,13,14,14,14,15,16,15,15, 9,10,10,11,12,
  148130. 12,13,13,13,14,14,16,14,14,16,16,16,16,15, 9,10,
  148131. 10,11,11,12,13,13,14,15,14,16,14,15,16,16,16,16,
  148132. 15,10,11,11,12,13,13,14,15,15,15,15,15,16,15,16,
  148133. 15,16,15,15,10,11,11,13,13,14,13,13,15,14,15,15,
  148134. 16,15,15,15,16,15,16,10,12,12,14,14,14,14,14,16,
  148135. 16,15,15,15,16,16,16,16,16,16,11,12,12,14,14,14,
  148136. 14,15,15,16,15,16,15,16,15,16,16,16,16,12,12,13,
  148137. 14,14,15,16,16,16,16,16,16,15,16,16,16,16,16,16,
  148138. 12,13,13,14,14,14,14,15,16,15,16,16,16,16,16,16,
  148139. 16,16,16,12,13,14,14,14,16,15,16,15,16,16,16,16,
  148140. 16,16,16,16,16,16,12,14,13,14,15,15,15,16,15,16,
  148141. 16,15,16,16,16,16,16,16,16,
  148142. };
  148143. static float _vq_quantthresh__44u8_p9_1[] = {
  148144. -416.5, -367.5, -318.5, -269.5, -220.5, -171.5, -122.5, -73.5,
  148145. -24.5, 24.5, 73.5, 122.5, 171.5, 220.5, 269.5, 318.5,
  148146. 367.5, 416.5,
  148147. };
  148148. static long _vq_quantmap__44u8_p9_1[] = {
  148149. 17, 15, 13, 11, 9, 7, 5, 3,
  148150. 1, 0, 2, 4, 6, 8, 10, 12,
  148151. 14, 16, 18,
  148152. };
  148153. static encode_aux_threshmatch _vq_auxt__44u8_p9_1 = {
  148154. _vq_quantthresh__44u8_p9_1,
  148155. _vq_quantmap__44u8_p9_1,
  148156. 19,
  148157. 19
  148158. };
  148159. static static_codebook _44u8_p9_1 = {
  148160. 2, 361,
  148161. _vq_lengthlist__44u8_p9_1,
  148162. 1, -518287360, 1622704128, 5, 0,
  148163. _vq_quantlist__44u8_p9_1,
  148164. NULL,
  148165. &_vq_auxt__44u8_p9_1,
  148166. NULL,
  148167. 0
  148168. };
  148169. static long _vq_quantlist__44u8_p9_2[] = {
  148170. 24,
  148171. 23,
  148172. 25,
  148173. 22,
  148174. 26,
  148175. 21,
  148176. 27,
  148177. 20,
  148178. 28,
  148179. 19,
  148180. 29,
  148181. 18,
  148182. 30,
  148183. 17,
  148184. 31,
  148185. 16,
  148186. 32,
  148187. 15,
  148188. 33,
  148189. 14,
  148190. 34,
  148191. 13,
  148192. 35,
  148193. 12,
  148194. 36,
  148195. 11,
  148196. 37,
  148197. 10,
  148198. 38,
  148199. 9,
  148200. 39,
  148201. 8,
  148202. 40,
  148203. 7,
  148204. 41,
  148205. 6,
  148206. 42,
  148207. 5,
  148208. 43,
  148209. 4,
  148210. 44,
  148211. 3,
  148212. 45,
  148213. 2,
  148214. 46,
  148215. 1,
  148216. 47,
  148217. 0,
  148218. 48,
  148219. };
  148220. static long _vq_lengthlist__44u8_p9_2[] = {
  148221. 2, 3, 4, 5, 5, 5, 5, 5, 6, 6, 6, 6, 6, 6, 6, 6,
  148222. 6, 6, 6, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7,
  148223. 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7,
  148224. 7,
  148225. };
  148226. static float _vq_quantthresh__44u8_p9_2[] = {
  148227. -23.5, -22.5, -21.5, -20.5, -19.5, -18.5, -17.5, -16.5,
  148228. -15.5, -14.5, -13.5, -12.5, -11.5, -10.5, -9.5, -8.5,
  148229. -7.5, -6.5, -5.5, -4.5, -3.5, -2.5, -1.5, -0.5,
  148230. 0.5, 1.5, 2.5, 3.5, 4.5, 5.5, 6.5, 7.5,
  148231. 8.5, 9.5, 10.5, 11.5, 12.5, 13.5, 14.5, 15.5,
  148232. 16.5, 17.5, 18.5, 19.5, 20.5, 21.5, 22.5, 23.5,
  148233. };
  148234. static long _vq_quantmap__44u8_p9_2[] = {
  148235. 47, 45, 43, 41, 39, 37, 35, 33,
  148236. 31, 29, 27, 25, 23, 21, 19, 17,
  148237. 15, 13, 11, 9, 7, 5, 3, 1,
  148238. 0, 2, 4, 6, 8, 10, 12, 14,
  148239. 16, 18, 20, 22, 24, 26, 28, 30,
  148240. 32, 34, 36, 38, 40, 42, 44, 46,
  148241. 48,
  148242. };
  148243. static encode_aux_threshmatch _vq_auxt__44u8_p9_2 = {
  148244. _vq_quantthresh__44u8_p9_2,
  148245. _vq_quantmap__44u8_p9_2,
  148246. 49,
  148247. 49
  148248. };
  148249. static static_codebook _44u8_p9_2 = {
  148250. 1, 49,
  148251. _vq_lengthlist__44u8_p9_2,
  148252. 1, -526909440, 1611661312, 6, 0,
  148253. _vq_quantlist__44u8_p9_2,
  148254. NULL,
  148255. &_vq_auxt__44u8_p9_2,
  148256. NULL,
  148257. 0
  148258. };
  148259. static long _huff_lengthlist__44u9__long[] = {
  148260. 3, 9,13,13,14,15,14,14,15,15, 5, 5, 9,10,12,12,
  148261. 13,14,16,15,10, 6, 6, 6, 8,11,12,13,16,15,11, 7,
  148262. 5, 3, 5, 8,10,12,15,15,10,10, 7, 4, 3, 5, 8,10,
  148263. 12,12,12,12, 9, 7, 5, 4, 6, 8,10,13,13,12,11, 9,
  148264. 7, 5, 5, 6, 9,12,14,12,12,10, 8, 6, 6, 6, 7,11,
  148265. 13,12,14,13,10, 8, 7, 7, 7,10,11,11,12,13,12,11,
  148266. 10, 8, 8, 9,
  148267. };
  148268. static static_codebook _huff_book__44u9__long = {
  148269. 2, 100,
  148270. _huff_lengthlist__44u9__long,
  148271. 0, 0, 0, 0, 0,
  148272. NULL,
  148273. NULL,
  148274. NULL,
  148275. NULL,
  148276. 0
  148277. };
  148278. static long _huff_lengthlist__44u9__short[] = {
  148279. 9,16,18,18,17,17,17,17,17,17, 5, 8,11,12,11,12,
  148280. 17,17,16,16, 6, 6, 8, 8, 9,10,14,15,16,16, 6, 7,
  148281. 7, 4, 6, 9,13,16,16,16, 6, 6, 7, 4, 5, 8,11,15,
  148282. 17,16, 7, 6, 7, 6, 6, 8, 9,10,14,16,11, 8, 8, 7,
  148283. 6, 6, 3, 4,10,15,14,12,12,10, 5, 6, 3, 3, 8,13,
  148284. 15,17,15,11, 6, 8, 6, 6, 9,14,17,15,15,12, 8,10,
  148285. 9, 9,12,15,
  148286. };
  148287. static static_codebook _huff_book__44u9__short = {
  148288. 2, 100,
  148289. _huff_lengthlist__44u9__short,
  148290. 0, 0, 0, 0, 0,
  148291. NULL,
  148292. NULL,
  148293. NULL,
  148294. NULL,
  148295. 0
  148296. };
  148297. static long _vq_quantlist__44u9_p1_0[] = {
  148298. 1,
  148299. 0,
  148300. 2,
  148301. };
  148302. static long _vq_lengthlist__44u9_p1_0[] = {
  148303. 1, 5, 5, 5, 7, 7, 5, 7, 7, 5, 7, 7, 7, 9, 9, 7,
  148304. 9, 9, 5, 7, 7, 7, 9, 9, 7, 9, 9, 5, 7, 7, 7, 9,
  148305. 9, 7, 9, 9, 8, 9, 9, 9,10,11, 9,11,11, 7, 9, 9,
  148306. 9,11,10, 9,11,11, 5, 7, 7, 7, 9, 9, 8, 9,10, 7,
  148307. 9, 9, 9,11,11, 9,10,11, 7, 9,10, 9,11,11, 9,11,
  148308. 10,
  148309. };
  148310. static float _vq_quantthresh__44u9_p1_0[] = {
  148311. -0.5, 0.5,
  148312. };
  148313. static long _vq_quantmap__44u9_p1_0[] = {
  148314. 1, 0, 2,
  148315. };
  148316. static encode_aux_threshmatch _vq_auxt__44u9_p1_0 = {
  148317. _vq_quantthresh__44u9_p1_0,
  148318. _vq_quantmap__44u9_p1_0,
  148319. 3,
  148320. 3
  148321. };
  148322. static static_codebook _44u9_p1_0 = {
  148323. 4, 81,
  148324. _vq_lengthlist__44u9_p1_0,
  148325. 1, -535822336, 1611661312, 2, 0,
  148326. _vq_quantlist__44u9_p1_0,
  148327. NULL,
  148328. &_vq_auxt__44u9_p1_0,
  148329. NULL,
  148330. 0
  148331. };
  148332. static long _vq_quantlist__44u9_p2_0[] = {
  148333. 2,
  148334. 1,
  148335. 3,
  148336. 0,
  148337. 4,
  148338. };
  148339. static long _vq_lengthlist__44u9_p2_0[] = {
  148340. 3, 5, 5, 8, 8, 5, 7, 7, 9, 9, 6, 7, 7, 9, 9, 8,
  148341. 9, 9,11,10, 8, 9, 9,11,11, 6, 7, 7, 9, 9, 7, 8,
  148342. 8,10,10, 7, 8, 8, 9,10, 9,10,10,11,11, 9, 9,10,
  148343. 11,11, 6, 7, 7, 9, 9, 7, 8, 8,10, 9, 7, 8, 8,10,
  148344. 10, 9,10, 9,11,11, 9,10,10,11,11, 8, 9, 9,11,11,
  148345. 9,10,10,12,11, 9,10,10,11,12,11,11,11,13,13,11,
  148346. 11,11,12,13, 8, 9, 9,11,11, 9,10,10,11,11, 9,10,
  148347. 10,12,11,11,12,11,13,12,11,11,12,13,13, 6, 7, 7,
  148348. 9, 9, 7, 8, 8,10,10, 7, 8, 8,10,10, 9,10,10,12,
  148349. 11, 9,10,10,11,12, 7, 8, 8,10,10, 8, 9, 9,11,11,
  148350. 8, 9, 9,10,10,10,11,11,12,12,10,10,11,12,12, 7,
  148351. 8, 8,10,10, 8, 9, 8,10,10, 8, 9, 9,10,10,10,11,
  148352. 10,12,11,10,10,11,12,12, 9,10,10,11,12,10,11,11,
  148353. 12,12,10,11,10,12,12,12,12,12,13,13,11,12,12,13,
  148354. 13, 9,10,10,11,11, 9,10,10,12,12,10,11,11,12,13,
  148355. 11,12,11,13,12,12,12,12,13,14, 6, 7, 7, 9, 9, 7,
  148356. 8, 8,10,10, 7, 8, 8,10,10, 9,10,10,11,11, 9,10,
  148357. 10,11,12, 7, 8, 8,10,10, 8, 9, 9,11,10, 8, 8, 9,
  148358. 10,10,10,11,10,12,12,10,10,11,11,12, 7, 8, 8,10,
  148359. 10, 8, 9, 9,10,10, 8, 9, 9,10,10,10,11,10,12,12,
  148360. 10,11,10,12,12, 9,10,10,12,11,10,11,11,12,12, 9,
  148361. 10,10,12,12,12,12,12,13,13,11,11,12,12,14, 9,10,
  148362. 10,11,12,10,11,11,12,12,10,11,11,12,12,11,12,12,
  148363. 14,14,12,12,12,13,13, 8, 9, 9,11,11, 9,10,10,12,
  148364. 11, 9,10,10,12,12,11,12,11,13,13,11,11,12,13,13,
  148365. 9,10,10,12,12,10,11,11,12,12,10,11,11,12,12,12,
  148366. 12,12,14,14,12,12,12,13,13, 9,10,10,12,11,10,11,
  148367. 10,12,12,10,11,11,12,12,11,12,12,14,13,12,12,12,
  148368. 13,14,11,12,11,13,13,11,12,12,13,13,12,12,12,14,
  148369. 14,13,13,13,13,15,13,13,14,15,15,11,11,11,13,13,
  148370. 11,12,11,13,13,11,12,12,13,13,12,13,12,15,13,13,
  148371. 13,14,14,15, 8, 9, 9,11,11, 9,10,10,11,12, 9,10,
  148372. 10,11,12,11,12,11,13,13,11,12,12,13,13, 9,10,10,
  148373. 11,12,10,11,10,12,12,10,10,11,12,13,12,12,12,14,
  148374. 13,11,12,12,13,14, 9,10,10,12,12,10,11,11,12,12,
  148375. 10,11,11,12,12,12,12,12,14,13,12,12,12,14,13,11,
  148376. 11,11,13,13,11,12,12,14,13,11,11,12,13,13,13,13,
  148377. 13,15,14,12,12,13,13,15,11,12,12,13,13,12,12,12,
  148378. 13,14,11,12,12,13,13,13,13,14,14,15,13,13,13,14,
  148379. 14,
  148380. };
  148381. static float _vq_quantthresh__44u9_p2_0[] = {
  148382. -1.5, -0.5, 0.5, 1.5,
  148383. };
  148384. static long _vq_quantmap__44u9_p2_0[] = {
  148385. 3, 1, 0, 2, 4,
  148386. };
  148387. static encode_aux_threshmatch _vq_auxt__44u9_p2_0 = {
  148388. _vq_quantthresh__44u9_p2_0,
  148389. _vq_quantmap__44u9_p2_0,
  148390. 5,
  148391. 5
  148392. };
  148393. static static_codebook _44u9_p2_0 = {
  148394. 4, 625,
  148395. _vq_lengthlist__44u9_p2_0,
  148396. 1, -533725184, 1611661312, 3, 0,
  148397. _vq_quantlist__44u9_p2_0,
  148398. NULL,
  148399. &_vq_auxt__44u9_p2_0,
  148400. NULL,
  148401. 0
  148402. };
  148403. static long _vq_quantlist__44u9_p3_0[] = {
  148404. 4,
  148405. 3,
  148406. 5,
  148407. 2,
  148408. 6,
  148409. 1,
  148410. 7,
  148411. 0,
  148412. 8,
  148413. };
  148414. static long _vq_lengthlist__44u9_p3_0[] = {
  148415. 3, 4, 4, 5, 5, 7, 7, 8, 8, 4, 5, 5, 6, 6, 7, 7,
  148416. 9, 9, 4, 4, 5, 6, 6, 7, 7, 9, 9, 5, 6, 6, 7, 7,
  148417. 8, 8, 9, 9, 5, 6, 6, 7, 7, 8, 8, 9, 9, 7, 7, 7,
  148418. 8, 8, 9, 9,10,10, 7, 7, 7, 8, 8, 9, 9,10,10, 8,
  148419. 9, 9,10, 9,10,10,11,11, 8, 9, 9, 9,10,10,10,11,
  148420. 11,
  148421. };
  148422. static float _vq_quantthresh__44u9_p3_0[] = {
  148423. -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5, 3.5,
  148424. };
  148425. static long _vq_quantmap__44u9_p3_0[] = {
  148426. 7, 5, 3, 1, 0, 2, 4, 6,
  148427. 8,
  148428. };
  148429. static encode_aux_threshmatch _vq_auxt__44u9_p3_0 = {
  148430. _vq_quantthresh__44u9_p3_0,
  148431. _vq_quantmap__44u9_p3_0,
  148432. 9,
  148433. 9
  148434. };
  148435. static static_codebook _44u9_p3_0 = {
  148436. 2, 81,
  148437. _vq_lengthlist__44u9_p3_0,
  148438. 1, -531628032, 1611661312, 4, 0,
  148439. _vq_quantlist__44u9_p3_0,
  148440. NULL,
  148441. &_vq_auxt__44u9_p3_0,
  148442. NULL,
  148443. 0
  148444. };
  148445. static long _vq_quantlist__44u9_p4_0[] = {
  148446. 8,
  148447. 7,
  148448. 9,
  148449. 6,
  148450. 10,
  148451. 5,
  148452. 11,
  148453. 4,
  148454. 12,
  148455. 3,
  148456. 13,
  148457. 2,
  148458. 14,
  148459. 1,
  148460. 15,
  148461. 0,
  148462. 16,
  148463. };
  148464. static long _vq_lengthlist__44u9_p4_0[] = {
  148465. 4, 5, 5, 6, 6, 7, 7, 8, 8, 8, 8, 9, 9,10,10,11,
  148466. 11, 5, 5, 5, 6, 6, 7, 7, 8, 8, 8, 8, 9, 9,10,10,
  148467. 11,11, 5, 5, 5, 6, 6, 7, 7, 8, 8, 8, 8, 9, 9,10,
  148468. 10,11,11, 6, 6, 6, 7, 6, 7, 7, 8, 8, 9, 9,10,10,
  148469. 11,11,12,11, 6, 6, 6, 6, 7, 7, 7, 8, 8, 9, 9,10,
  148470. 10,11,11,11,12, 7, 7, 7, 7, 7, 8, 8, 9, 9, 9, 9,
  148471. 10,10,11,11,12,12, 7, 7, 7, 7, 7, 8, 8, 9, 9, 9,
  148472. 9,10,10,11,11,12,12, 8, 8, 8, 8, 8, 9, 8,10, 9,
  148473. 10,10,11,10,12,11,13,12, 8, 8, 8, 8, 8, 9, 9, 9,
  148474. 10,10,10,10,11,11,12,12,12, 8, 8, 8, 9, 9, 9, 9,
  148475. 10,10,11,10,12,11,12,12,13,12, 8, 8, 8, 9, 9, 9,
  148476. 9,10,10,10,11,11,11,12,12,12,13, 9, 9, 9,10,10,
  148477. 10,10,11,10,11,11,12,11,13,12,13,13, 9, 9,10,10,
  148478. 10,10,10,10,11,11,11,11,12,12,13,13,13,10,11,10,
  148479. 11,11,11,11,12,11,12,12,13,12,13,13,14,13,10,10,
  148480. 10,11,11,11,11,11,12,12,12,12,13,13,13,13,14,11,
  148481. 11,11,12,11,12,12,12,12,13,13,13,13,14,13,14,14,
  148482. 11,11,11,11,12,12,12,12,12,12,13,13,13,13,14,14,
  148483. 14,
  148484. };
  148485. static float _vq_quantthresh__44u9_p4_0[] = {
  148486. -7.5, -6.5, -5.5, -4.5, -3.5, -2.5, -1.5, -0.5,
  148487. 0.5, 1.5, 2.5, 3.5, 4.5, 5.5, 6.5, 7.5,
  148488. };
  148489. static long _vq_quantmap__44u9_p4_0[] = {
  148490. 15, 13, 11, 9, 7, 5, 3, 1,
  148491. 0, 2, 4, 6, 8, 10, 12, 14,
  148492. 16,
  148493. };
  148494. static encode_aux_threshmatch _vq_auxt__44u9_p4_0 = {
  148495. _vq_quantthresh__44u9_p4_0,
  148496. _vq_quantmap__44u9_p4_0,
  148497. 17,
  148498. 17
  148499. };
  148500. static static_codebook _44u9_p4_0 = {
  148501. 2, 289,
  148502. _vq_lengthlist__44u9_p4_0,
  148503. 1, -529530880, 1611661312, 5, 0,
  148504. _vq_quantlist__44u9_p4_0,
  148505. NULL,
  148506. &_vq_auxt__44u9_p4_0,
  148507. NULL,
  148508. 0
  148509. };
  148510. static long _vq_quantlist__44u9_p5_0[] = {
  148511. 1,
  148512. 0,
  148513. 2,
  148514. };
  148515. static long _vq_lengthlist__44u9_p5_0[] = {
  148516. 1, 4, 4, 5, 7, 7, 5, 7, 7, 5, 8, 8, 8, 9, 9, 7,
  148517. 9, 9, 5, 8, 8, 7, 9, 9, 8, 9, 9, 5, 8, 8, 8,10,
  148518. 10, 8,10,10, 7,10,10, 9,10,12, 9,11,11, 7,10,10,
  148519. 9,11,10, 9,11,12, 5, 8, 8, 8,10,10, 8,10,10, 7,
  148520. 10,10, 9,12,11, 9,10,11, 7,10,10, 9,11,11,10,12,
  148521. 10,
  148522. };
  148523. static float _vq_quantthresh__44u9_p5_0[] = {
  148524. -5.5, 5.5,
  148525. };
  148526. static long _vq_quantmap__44u9_p5_0[] = {
  148527. 1, 0, 2,
  148528. };
  148529. static encode_aux_threshmatch _vq_auxt__44u9_p5_0 = {
  148530. _vq_quantthresh__44u9_p5_0,
  148531. _vq_quantmap__44u9_p5_0,
  148532. 3,
  148533. 3
  148534. };
  148535. static static_codebook _44u9_p5_0 = {
  148536. 4, 81,
  148537. _vq_lengthlist__44u9_p5_0,
  148538. 1, -529137664, 1618345984, 2, 0,
  148539. _vq_quantlist__44u9_p5_0,
  148540. NULL,
  148541. &_vq_auxt__44u9_p5_0,
  148542. NULL,
  148543. 0
  148544. };
  148545. static long _vq_quantlist__44u9_p5_1[] = {
  148546. 5,
  148547. 4,
  148548. 6,
  148549. 3,
  148550. 7,
  148551. 2,
  148552. 8,
  148553. 1,
  148554. 9,
  148555. 0,
  148556. 10,
  148557. };
  148558. static long _vq_lengthlist__44u9_p5_1[] = {
  148559. 5, 5, 5, 6, 6, 7, 7, 7, 7, 7, 7, 5, 6, 6, 6, 6,
  148560. 7, 7, 7, 7, 8, 7, 5, 6, 6, 6, 6, 7, 7, 7, 7, 7,
  148561. 7, 6, 6, 6, 7, 7, 7, 7, 7, 7, 8, 8, 6, 6, 6, 7,
  148562. 7, 7, 7, 7, 7, 8, 8, 7, 7, 7, 7, 7, 8, 7, 8, 8,
  148563. 8, 8, 7, 7, 7, 7, 7, 7, 8, 8, 8, 8, 8, 7, 7, 7,
  148564. 8, 7, 8, 8, 8, 8, 8, 8, 7, 7, 7, 7, 8, 8, 8, 8,
  148565. 8, 8, 8, 7, 8, 7, 8, 8, 8, 8, 8, 8, 8, 8, 7, 8,
  148566. 8, 8, 8, 8, 8, 8, 8, 8, 8,
  148567. };
  148568. static float _vq_quantthresh__44u9_p5_1[] = {
  148569. -4.5, -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5,
  148570. 3.5, 4.5,
  148571. };
  148572. static long _vq_quantmap__44u9_p5_1[] = {
  148573. 9, 7, 5, 3, 1, 0, 2, 4,
  148574. 6, 8, 10,
  148575. };
  148576. static encode_aux_threshmatch _vq_auxt__44u9_p5_1 = {
  148577. _vq_quantthresh__44u9_p5_1,
  148578. _vq_quantmap__44u9_p5_1,
  148579. 11,
  148580. 11
  148581. };
  148582. static static_codebook _44u9_p5_1 = {
  148583. 2, 121,
  148584. _vq_lengthlist__44u9_p5_1,
  148585. 1, -531365888, 1611661312, 4, 0,
  148586. _vq_quantlist__44u9_p5_1,
  148587. NULL,
  148588. &_vq_auxt__44u9_p5_1,
  148589. NULL,
  148590. 0
  148591. };
  148592. static long _vq_quantlist__44u9_p6_0[] = {
  148593. 6,
  148594. 5,
  148595. 7,
  148596. 4,
  148597. 8,
  148598. 3,
  148599. 9,
  148600. 2,
  148601. 10,
  148602. 1,
  148603. 11,
  148604. 0,
  148605. 12,
  148606. };
  148607. static long _vq_lengthlist__44u9_p6_0[] = {
  148608. 2, 4, 4, 6, 6, 7, 7, 8, 8, 9, 9,10,10, 4, 6, 5,
  148609. 7, 7, 8, 8, 8, 8, 9, 9,10,10, 4, 5, 6, 7, 7, 8,
  148610. 8, 8, 8, 9, 9,10,10, 6, 7, 7, 8, 8, 8, 8, 9, 9,
  148611. 10,10,10,10, 6, 7, 7, 8, 8, 8, 8, 9, 9,10,10,10,
  148612. 10, 7, 8, 8, 8, 8, 9, 9, 9, 9,10,10,11,11, 7, 8,
  148613. 8, 8, 8, 9, 9, 9, 9,10,10,11,11, 8, 8, 8, 9, 9,
  148614. 9, 9, 9,10,10,10,11,11, 8, 8, 8, 9, 9, 9, 9,10,
  148615. 9,10,10,11,11, 9, 9, 9,10,10,10,10,10,11,11,11,
  148616. 11,12, 9, 9, 9,10,10,10,10,10,10,11,10,12,11,10,
  148617. 10,10,10,10,11,11,11,11,11,12,12,12,10,10,10,10,
  148618. 10,11,11,11,11,12,11,12,12,
  148619. };
  148620. static float _vq_quantthresh__44u9_p6_0[] = {
  148621. -27.5, -22.5, -17.5, -12.5, -7.5, -2.5, 2.5, 7.5,
  148622. 12.5, 17.5, 22.5, 27.5,
  148623. };
  148624. static long _vq_quantmap__44u9_p6_0[] = {
  148625. 11, 9, 7, 5, 3, 1, 0, 2,
  148626. 4, 6, 8, 10, 12,
  148627. };
  148628. static encode_aux_threshmatch _vq_auxt__44u9_p6_0 = {
  148629. _vq_quantthresh__44u9_p6_0,
  148630. _vq_quantmap__44u9_p6_0,
  148631. 13,
  148632. 13
  148633. };
  148634. static static_codebook _44u9_p6_0 = {
  148635. 2, 169,
  148636. _vq_lengthlist__44u9_p6_0,
  148637. 1, -526516224, 1616117760, 4, 0,
  148638. _vq_quantlist__44u9_p6_0,
  148639. NULL,
  148640. &_vq_auxt__44u9_p6_0,
  148641. NULL,
  148642. 0
  148643. };
  148644. static long _vq_quantlist__44u9_p6_1[] = {
  148645. 2,
  148646. 1,
  148647. 3,
  148648. 0,
  148649. 4,
  148650. };
  148651. static long _vq_lengthlist__44u9_p6_1[] = {
  148652. 4, 4, 4, 5, 5, 4, 5, 4, 5, 5, 4, 4, 5, 5, 5, 5,
  148653. 5, 5, 5, 5, 5, 5, 5, 5, 5,
  148654. };
  148655. static float _vq_quantthresh__44u9_p6_1[] = {
  148656. -1.5, -0.5, 0.5, 1.5,
  148657. };
  148658. static long _vq_quantmap__44u9_p6_1[] = {
  148659. 3, 1, 0, 2, 4,
  148660. };
  148661. static encode_aux_threshmatch _vq_auxt__44u9_p6_1 = {
  148662. _vq_quantthresh__44u9_p6_1,
  148663. _vq_quantmap__44u9_p6_1,
  148664. 5,
  148665. 5
  148666. };
  148667. static static_codebook _44u9_p6_1 = {
  148668. 2, 25,
  148669. _vq_lengthlist__44u9_p6_1,
  148670. 1, -533725184, 1611661312, 3, 0,
  148671. _vq_quantlist__44u9_p6_1,
  148672. NULL,
  148673. &_vq_auxt__44u9_p6_1,
  148674. NULL,
  148675. 0
  148676. };
  148677. static long _vq_quantlist__44u9_p7_0[] = {
  148678. 6,
  148679. 5,
  148680. 7,
  148681. 4,
  148682. 8,
  148683. 3,
  148684. 9,
  148685. 2,
  148686. 10,
  148687. 1,
  148688. 11,
  148689. 0,
  148690. 12,
  148691. };
  148692. static long _vq_lengthlist__44u9_p7_0[] = {
  148693. 1, 4, 5, 6, 6, 7, 7, 8, 9,10,10,11,11, 5, 6, 6,
  148694. 7, 7, 8, 8, 9, 9,10,10,11,11, 5, 6, 6, 7, 7, 8,
  148695. 8, 9, 9,10,10,11,11, 6, 7, 7, 8, 8, 9, 9,10,10,
  148696. 11,11,12,12, 6, 7, 7, 8, 8, 9, 9,10,10,11,11,12,
  148697. 12, 8, 8, 8, 9, 9,10,10,11,11,12,12,13,13, 8, 8,
  148698. 8, 9, 9,10,10,11,11,12,12,13,13, 9, 9, 9,10,10,
  148699. 11,11,12,12,13,13,13,13, 9, 9, 9,10,10,11,11,12,
  148700. 12,13,13,14,14,10,10,10,11,11,12,12,13,13,14,13,
  148701. 15,14,10,10,10,11,11,12,12,13,13,14,14,14,14,11,
  148702. 11,12,12,12,13,13,14,14,14,14,15,15,11,11,12,12,
  148703. 12,13,13,14,14,14,15,15,15,
  148704. };
  148705. static float _vq_quantthresh__44u9_p7_0[] = {
  148706. -60.5, -49.5, -38.5, -27.5, -16.5, -5.5, 5.5, 16.5,
  148707. 27.5, 38.5, 49.5, 60.5,
  148708. };
  148709. static long _vq_quantmap__44u9_p7_0[] = {
  148710. 11, 9, 7, 5, 3, 1, 0, 2,
  148711. 4, 6, 8, 10, 12,
  148712. };
  148713. static encode_aux_threshmatch _vq_auxt__44u9_p7_0 = {
  148714. _vq_quantthresh__44u9_p7_0,
  148715. _vq_quantmap__44u9_p7_0,
  148716. 13,
  148717. 13
  148718. };
  148719. static static_codebook _44u9_p7_0 = {
  148720. 2, 169,
  148721. _vq_lengthlist__44u9_p7_0,
  148722. 1, -523206656, 1618345984, 4, 0,
  148723. _vq_quantlist__44u9_p7_0,
  148724. NULL,
  148725. &_vq_auxt__44u9_p7_0,
  148726. NULL,
  148727. 0
  148728. };
  148729. static long _vq_quantlist__44u9_p7_1[] = {
  148730. 5,
  148731. 4,
  148732. 6,
  148733. 3,
  148734. 7,
  148735. 2,
  148736. 8,
  148737. 1,
  148738. 9,
  148739. 0,
  148740. 10,
  148741. };
  148742. static long _vq_lengthlist__44u9_p7_1[] = {
  148743. 5, 6, 6, 7, 7, 7, 7, 7, 7, 7, 7, 6, 6, 6, 7, 7,
  148744. 7, 7, 7, 7, 7, 7, 6, 6, 6, 7, 7, 7, 7, 7, 7, 7,
  148745. 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 6, 7, 7, 7,
  148746. 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7,
  148747. 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7,
  148748. 7, 7, 7, 7, 8, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7,
  148749. 7, 8, 8, 7, 7, 7, 7, 7, 7, 7, 8, 7, 8, 8, 7, 7,
  148750. 7, 7, 7, 7, 7, 8, 8, 8, 8,
  148751. };
  148752. static float _vq_quantthresh__44u9_p7_1[] = {
  148753. -4.5, -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5,
  148754. 3.5, 4.5,
  148755. };
  148756. static long _vq_quantmap__44u9_p7_1[] = {
  148757. 9, 7, 5, 3, 1, 0, 2, 4,
  148758. 6, 8, 10,
  148759. };
  148760. static encode_aux_threshmatch _vq_auxt__44u9_p7_1 = {
  148761. _vq_quantthresh__44u9_p7_1,
  148762. _vq_quantmap__44u9_p7_1,
  148763. 11,
  148764. 11
  148765. };
  148766. static static_codebook _44u9_p7_1 = {
  148767. 2, 121,
  148768. _vq_lengthlist__44u9_p7_1,
  148769. 1, -531365888, 1611661312, 4, 0,
  148770. _vq_quantlist__44u9_p7_1,
  148771. NULL,
  148772. &_vq_auxt__44u9_p7_1,
  148773. NULL,
  148774. 0
  148775. };
  148776. static long _vq_quantlist__44u9_p8_0[] = {
  148777. 7,
  148778. 6,
  148779. 8,
  148780. 5,
  148781. 9,
  148782. 4,
  148783. 10,
  148784. 3,
  148785. 11,
  148786. 2,
  148787. 12,
  148788. 1,
  148789. 13,
  148790. 0,
  148791. 14,
  148792. };
  148793. static long _vq_lengthlist__44u9_p8_0[] = {
  148794. 1, 4, 4, 7, 7, 8, 8, 8, 8, 9, 9,10, 9,11,10, 4,
  148795. 6, 6, 8, 8, 9, 9, 9, 9,10,10,11,10,12,10, 4, 6,
  148796. 6, 8, 8, 9,10, 9, 9,10,10,11,11,12,12, 7, 8, 8,
  148797. 10,10,11,11,10,10,11,11,12,12,13,12, 7, 8, 8,10,
  148798. 10,11,11,10,10,11,11,12,12,12,13, 8,10, 9,11,11,
  148799. 12,12,11,11,12,12,13,13,14,13, 8, 9, 9,11,11,12,
  148800. 12,11,12,12,12,13,13,14,13, 8, 9, 9,10,10,12,11,
  148801. 13,12,13,13,14,13,15,14, 8, 9, 9,10,10,11,12,12,
  148802. 12,13,13,13,14,14,14, 9,10,10,12,11,13,12,13,13,
  148803. 14,13,14,14,14,15, 9,10,10,11,12,12,12,13,13,14,
  148804. 14,14,15,15,15,10,11,11,12,12,13,13,14,14,14,14,
  148805. 15,14,16,15,10,11,11,12,12,13,13,13,14,14,14,14,
  148806. 14,15,16,11,12,12,13,13,14,13,14,14,15,14,15,16,
  148807. 16,16,11,12,12,13,13,14,13,14,14,15,15,15,16,15,
  148808. 15,
  148809. };
  148810. static float _vq_quantthresh__44u9_p8_0[] = {
  148811. -136.5, -115.5, -94.5, -73.5, -52.5, -31.5, -10.5, 10.5,
  148812. 31.5, 52.5, 73.5, 94.5, 115.5, 136.5,
  148813. };
  148814. static long _vq_quantmap__44u9_p8_0[] = {
  148815. 13, 11, 9, 7, 5, 3, 1, 0,
  148816. 2, 4, 6, 8, 10, 12, 14,
  148817. };
  148818. static encode_aux_threshmatch _vq_auxt__44u9_p8_0 = {
  148819. _vq_quantthresh__44u9_p8_0,
  148820. _vq_quantmap__44u9_p8_0,
  148821. 15,
  148822. 15
  148823. };
  148824. static static_codebook _44u9_p8_0 = {
  148825. 2, 225,
  148826. _vq_lengthlist__44u9_p8_0,
  148827. 1, -520986624, 1620377600, 4, 0,
  148828. _vq_quantlist__44u9_p8_0,
  148829. NULL,
  148830. &_vq_auxt__44u9_p8_0,
  148831. NULL,
  148832. 0
  148833. };
  148834. static long _vq_quantlist__44u9_p8_1[] = {
  148835. 10,
  148836. 9,
  148837. 11,
  148838. 8,
  148839. 12,
  148840. 7,
  148841. 13,
  148842. 6,
  148843. 14,
  148844. 5,
  148845. 15,
  148846. 4,
  148847. 16,
  148848. 3,
  148849. 17,
  148850. 2,
  148851. 18,
  148852. 1,
  148853. 19,
  148854. 0,
  148855. 20,
  148856. };
  148857. static long _vq_lengthlist__44u9_p8_1[] = {
  148858. 4, 6, 6, 7, 7, 8, 8, 8, 8, 9, 9, 9, 9, 9, 9, 9,
  148859. 9, 9, 9, 9, 9, 6, 6, 6, 7, 7, 8, 8, 8, 8, 9, 9,
  148860. 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 6, 6, 6, 7, 7, 8,
  148861. 8, 8, 8, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 7,
  148862. 7, 7, 8, 8, 8, 8, 9, 8, 9, 9, 9, 9, 9, 9, 9, 9,
  148863. 9, 9, 9, 9, 7, 7, 7, 8, 8, 8, 8, 9, 9, 9, 9, 9,
  148864. 9, 9, 9, 9, 9, 9, 9, 9, 9, 8, 8, 8, 8, 8, 9, 9,
  148865. 9, 9, 9, 9, 9, 9, 9, 9, 9,10, 9,10,10,10, 8, 8,
  148866. 8, 8, 8, 8, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,
  148867. 9,10,10, 8, 8, 8, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,
  148868. 10, 9,10, 9,10,10,10,10, 8, 8, 8, 9, 9, 9, 9, 9,
  148869. 9, 9, 9, 9, 9,10,10, 9,10,10,10,10,10, 9, 9, 9,
  148870. 9, 9, 9, 9, 9, 9, 9, 9,10, 9,10,10,10,10,10,10,
  148871. 10,10, 8, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,10,10,10,
  148872. 10,10,10,10,10,10,10, 9, 9, 9, 9, 9, 9, 9, 9, 9,
  148873. 9, 9,10,10,10,10,10,10,10,10,10,10, 9, 9, 9, 9,
  148874. 9, 9, 9, 9, 9, 9, 9,10,10,10,10,10,10,10,10,10,
  148875. 10, 9, 9, 9, 9, 9, 9, 9,10, 9,10,10,10,10,10,10,
  148876. 10,10,10,10,10,10, 9, 9, 9, 9, 9, 9, 9, 9,10,10,
  148877. 10,10,10,10,10,10,10,10,10,10,10, 9, 9, 9, 9, 9,
  148878. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  148879. 9, 9, 9, 9,10, 9, 9,10,10,10,10,10,10,10,10,10,
  148880. 10,10,10,10,10, 9, 9, 9,10, 9,10, 9,10,10,10,10,
  148881. 10,10,10,10,10,10,10,10,10,10, 9, 9, 9,10, 9,10,
  148882. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10, 9,
  148883. 9, 9, 9, 9,10,10,10,10,10,10,10,10,10,10,10,10,
  148884. 10,10,10,10, 9, 9, 9,10,10,10,10,10,10,10,10,10,
  148885. 10,10,10,10,10,10,10,10,10,
  148886. };
  148887. static float _vq_quantthresh__44u9_p8_1[] = {
  148888. -9.5, -8.5, -7.5, -6.5, -5.5, -4.5, -3.5, -2.5,
  148889. -1.5, -0.5, 0.5, 1.5, 2.5, 3.5, 4.5, 5.5,
  148890. 6.5, 7.5, 8.5, 9.5,
  148891. };
  148892. static long _vq_quantmap__44u9_p8_1[] = {
  148893. 19, 17, 15, 13, 11, 9, 7, 5,
  148894. 3, 1, 0, 2, 4, 6, 8, 10,
  148895. 12, 14, 16, 18, 20,
  148896. };
  148897. static encode_aux_threshmatch _vq_auxt__44u9_p8_1 = {
  148898. _vq_quantthresh__44u9_p8_1,
  148899. _vq_quantmap__44u9_p8_1,
  148900. 21,
  148901. 21
  148902. };
  148903. static static_codebook _44u9_p8_1 = {
  148904. 2, 441,
  148905. _vq_lengthlist__44u9_p8_1,
  148906. 1, -529268736, 1611661312, 5, 0,
  148907. _vq_quantlist__44u9_p8_1,
  148908. NULL,
  148909. &_vq_auxt__44u9_p8_1,
  148910. NULL,
  148911. 0
  148912. };
  148913. static long _vq_quantlist__44u9_p9_0[] = {
  148914. 7,
  148915. 6,
  148916. 8,
  148917. 5,
  148918. 9,
  148919. 4,
  148920. 10,
  148921. 3,
  148922. 11,
  148923. 2,
  148924. 12,
  148925. 1,
  148926. 13,
  148927. 0,
  148928. 14,
  148929. };
  148930. static long _vq_lengthlist__44u9_p9_0[] = {
  148931. 1, 3, 3,11,11,11,11,11,11,11,11,11,11,11,11, 4,
  148932. 10,11,11,11,11,11,11,11,11,11,11,11,11,11, 4,10,
  148933. 10,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  148934. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  148935. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  148936. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  148937. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  148938. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  148939. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  148940. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  148941. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  148942. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  148943. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  148944. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  148945. 10,
  148946. };
  148947. static float _vq_quantthresh__44u9_p9_0[] = {
  148948. -6051.5, -5120.5, -4189.5, -3258.5, -2327.5, -1396.5, -465.5, 465.5,
  148949. 1396.5, 2327.5, 3258.5, 4189.5, 5120.5, 6051.5,
  148950. };
  148951. static long _vq_quantmap__44u9_p9_0[] = {
  148952. 13, 11, 9, 7, 5, 3, 1, 0,
  148953. 2, 4, 6, 8, 10, 12, 14,
  148954. };
  148955. static encode_aux_threshmatch _vq_auxt__44u9_p9_0 = {
  148956. _vq_quantthresh__44u9_p9_0,
  148957. _vq_quantmap__44u9_p9_0,
  148958. 15,
  148959. 15
  148960. };
  148961. static static_codebook _44u9_p9_0 = {
  148962. 2, 225,
  148963. _vq_lengthlist__44u9_p9_0,
  148964. 1, -510036736, 1631393792, 4, 0,
  148965. _vq_quantlist__44u9_p9_0,
  148966. NULL,
  148967. &_vq_auxt__44u9_p9_0,
  148968. NULL,
  148969. 0
  148970. };
  148971. static long _vq_quantlist__44u9_p9_1[] = {
  148972. 9,
  148973. 8,
  148974. 10,
  148975. 7,
  148976. 11,
  148977. 6,
  148978. 12,
  148979. 5,
  148980. 13,
  148981. 4,
  148982. 14,
  148983. 3,
  148984. 15,
  148985. 2,
  148986. 16,
  148987. 1,
  148988. 17,
  148989. 0,
  148990. 18,
  148991. };
  148992. static long _vq_lengthlist__44u9_p9_1[] = {
  148993. 1, 4, 4, 7, 7, 8, 7, 8, 7, 9, 8,10, 9,10,10,11,
  148994. 11,12,12, 4, 7, 6, 9, 9,10, 9, 9, 8,10,10,11,10,
  148995. 12,10,13,12,13,12, 4, 6, 6, 9, 9, 9, 9, 9, 9,10,
  148996. 10,11,11,11,12,12,12,12,12, 7, 9, 8,11,10,10,10,
  148997. 11,10,11,11,12,12,13,12,13,13,13,13, 7, 8, 9,10,
  148998. 10,11,11,10,10,11,11,11,12,13,13,13,13,14,14, 8,
  148999. 9, 9,11,11,12,11,12,12,13,12,12,13,13,14,15,14,
  149000. 14,14, 8, 9, 9,10,11,11,11,12,12,13,12,13,13,14,
  149001. 14,14,15,14,16, 8, 9, 9,11,10,12,12,12,12,15,13,
  149002. 13,13,17,14,15,15,15,14, 8, 9, 9,10,11,11,12,13,
  149003. 12,13,13,13,14,15,14,14,14,16,15, 9,11,10,12,12,
  149004. 13,13,13,13,14,14,16,15,14,14,14,15,15,17, 9,10,
  149005. 10,11,11,13,13,13,14,14,13,15,14,15,14,15,16,15,
  149006. 16,10,11,11,12,12,13,14,15,14,15,14,14,15,17,16,
  149007. 15,15,17,17,10,12,11,13,12,14,14,13,14,15,15,15,
  149008. 15,16,17,17,15,17,16,11,12,12,14,13,15,14,15,16,
  149009. 17,15,17,15,17,15,15,16,17,15,11,11,12,14,14,14,
  149010. 14,14,15,15,16,15,17,17,17,16,17,16,15,12,12,13,
  149011. 14,14,14,15,14,15,15,16,16,17,16,17,15,17,17,16,
  149012. 12,14,12,14,14,15,15,15,14,14,16,16,16,15,16,16,
  149013. 15,17,15,12,13,13,14,15,14,15,17,15,17,16,17,17,
  149014. 17,16,17,16,17,17,12,13,13,14,16,15,15,15,16,15,
  149015. 17,17,15,17,15,17,16,16,17,
  149016. };
  149017. static float _vq_quantthresh__44u9_p9_1[] = {
  149018. -416.5, -367.5, -318.5, -269.5, -220.5, -171.5, -122.5, -73.5,
  149019. -24.5, 24.5, 73.5, 122.5, 171.5, 220.5, 269.5, 318.5,
  149020. 367.5, 416.5,
  149021. };
  149022. static long _vq_quantmap__44u9_p9_1[] = {
  149023. 17, 15, 13, 11, 9, 7, 5, 3,
  149024. 1, 0, 2, 4, 6, 8, 10, 12,
  149025. 14, 16, 18,
  149026. };
  149027. static encode_aux_threshmatch _vq_auxt__44u9_p9_1 = {
  149028. _vq_quantthresh__44u9_p9_1,
  149029. _vq_quantmap__44u9_p9_1,
  149030. 19,
  149031. 19
  149032. };
  149033. static static_codebook _44u9_p9_1 = {
  149034. 2, 361,
  149035. _vq_lengthlist__44u9_p9_1,
  149036. 1, -518287360, 1622704128, 5, 0,
  149037. _vq_quantlist__44u9_p9_1,
  149038. NULL,
  149039. &_vq_auxt__44u9_p9_1,
  149040. NULL,
  149041. 0
  149042. };
  149043. static long _vq_quantlist__44u9_p9_2[] = {
  149044. 24,
  149045. 23,
  149046. 25,
  149047. 22,
  149048. 26,
  149049. 21,
  149050. 27,
  149051. 20,
  149052. 28,
  149053. 19,
  149054. 29,
  149055. 18,
  149056. 30,
  149057. 17,
  149058. 31,
  149059. 16,
  149060. 32,
  149061. 15,
  149062. 33,
  149063. 14,
  149064. 34,
  149065. 13,
  149066. 35,
  149067. 12,
  149068. 36,
  149069. 11,
  149070. 37,
  149071. 10,
  149072. 38,
  149073. 9,
  149074. 39,
  149075. 8,
  149076. 40,
  149077. 7,
  149078. 41,
  149079. 6,
  149080. 42,
  149081. 5,
  149082. 43,
  149083. 4,
  149084. 44,
  149085. 3,
  149086. 45,
  149087. 2,
  149088. 46,
  149089. 1,
  149090. 47,
  149091. 0,
  149092. 48,
  149093. };
  149094. static long _vq_lengthlist__44u9_p9_2[] = {
  149095. 2, 4, 4, 5, 4, 5, 5, 5, 5, 6, 6, 6, 6, 6, 6, 6,
  149096. 6, 6, 6, 7, 6, 7, 6, 7, 7, 7, 7, 7, 7, 7, 7, 7,
  149097. 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7,
  149098. 7,
  149099. };
  149100. static float _vq_quantthresh__44u9_p9_2[] = {
  149101. -23.5, -22.5, -21.5, -20.5, -19.5, -18.5, -17.5, -16.5,
  149102. -15.5, -14.5, -13.5, -12.5, -11.5, -10.5, -9.5, -8.5,
  149103. -7.5, -6.5, -5.5, -4.5, -3.5, -2.5, -1.5, -0.5,
  149104. 0.5, 1.5, 2.5, 3.5, 4.5, 5.5, 6.5, 7.5,
  149105. 8.5, 9.5, 10.5, 11.5, 12.5, 13.5, 14.5, 15.5,
  149106. 16.5, 17.5, 18.5, 19.5, 20.5, 21.5, 22.5, 23.5,
  149107. };
  149108. static long _vq_quantmap__44u9_p9_2[] = {
  149109. 47, 45, 43, 41, 39, 37, 35, 33,
  149110. 31, 29, 27, 25, 23, 21, 19, 17,
  149111. 15, 13, 11, 9, 7, 5, 3, 1,
  149112. 0, 2, 4, 6, 8, 10, 12, 14,
  149113. 16, 18, 20, 22, 24, 26, 28, 30,
  149114. 32, 34, 36, 38, 40, 42, 44, 46,
  149115. 48,
  149116. };
  149117. static encode_aux_threshmatch _vq_auxt__44u9_p9_2 = {
  149118. _vq_quantthresh__44u9_p9_2,
  149119. _vq_quantmap__44u9_p9_2,
  149120. 49,
  149121. 49
  149122. };
  149123. static static_codebook _44u9_p9_2 = {
  149124. 1, 49,
  149125. _vq_lengthlist__44u9_p9_2,
  149126. 1, -526909440, 1611661312, 6, 0,
  149127. _vq_quantlist__44u9_p9_2,
  149128. NULL,
  149129. &_vq_auxt__44u9_p9_2,
  149130. NULL,
  149131. 0
  149132. };
  149133. static long _huff_lengthlist__44un1__long[] = {
  149134. 5, 6,12, 9,14, 9, 9,19, 6, 1, 5, 5, 8, 7, 9,19,
  149135. 12, 4, 4, 7, 7, 9,11,18, 9, 5, 6, 6, 8, 7, 8,17,
  149136. 14, 8, 7, 8, 8,10,12,18, 9, 6, 8, 6, 8, 6, 8,18,
  149137. 9, 8,11, 8,11, 7, 5,15,16,18,18,18,17,15,11,18,
  149138. };
  149139. static static_codebook _huff_book__44un1__long = {
  149140. 2, 64,
  149141. _huff_lengthlist__44un1__long,
  149142. 0, 0, 0, 0, 0,
  149143. NULL,
  149144. NULL,
  149145. NULL,
  149146. NULL,
  149147. 0
  149148. };
  149149. static long _vq_quantlist__44un1__p1_0[] = {
  149150. 1,
  149151. 0,
  149152. 2,
  149153. };
  149154. static long _vq_lengthlist__44un1__p1_0[] = {
  149155. 1, 4, 4, 5, 8, 7, 5, 7, 8, 5, 8, 8, 8,10,11, 8,
  149156. 10,11, 5, 8, 8, 8,11,10, 8,11,10, 4, 9, 9, 8,11,
  149157. 11, 8,11,11, 8,12,11,10,12,14,11,13,13, 7,11,11,
  149158. 10,13,11,11,13,14, 4, 8, 9, 8,11,11, 8,11,12, 7,
  149159. 11,11,11,14,13,10,11,13, 8,11,12,11,13,13,10,14,
  149160. 12,
  149161. };
  149162. static float _vq_quantthresh__44un1__p1_0[] = {
  149163. -0.5, 0.5,
  149164. };
  149165. static long _vq_quantmap__44un1__p1_0[] = {
  149166. 1, 0, 2,
  149167. };
  149168. static encode_aux_threshmatch _vq_auxt__44un1__p1_0 = {
  149169. _vq_quantthresh__44un1__p1_0,
  149170. _vq_quantmap__44un1__p1_0,
  149171. 3,
  149172. 3
  149173. };
  149174. static static_codebook _44un1__p1_0 = {
  149175. 4, 81,
  149176. _vq_lengthlist__44un1__p1_0,
  149177. 1, -535822336, 1611661312, 2, 0,
  149178. _vq_quantlist__44un1__p1_0,
  149179. NULL,
  149180. &_vq_auxt__44un1__p1_0,
  149181. NULL,
  149182. 0
  149183. };
  149184. static long _vq_quantlist__44un1__p2_0[] = {
  149185. 1,
  149186. 0,
  149187. 2,
  149188. };
  149189. static long _vq_lengthlist__44un1__p2_0[] = {
  149190. 2, 4, 4, 5, 6, 6, 5, 6, 6, 5, 7, 7, 7, 8, 8, 6,
  149191. 7, 9, 5, 7, 7, 6, 8, 7, 7, 9, 8, 4, 7, 7, 7, 9,
  149192. 8, 7, 8, 8, 7, 9, 8, 8, 8,10, 9,10,10, 6, 8, 8,
  149193. 7,10, 8, 9,10,10, 5, 7, 7, 7, 8, 8, 7, 8, 9, 6,
  149194. 8, 8, 9,10,10, 7, 8,10, 6, 8, 9, 9,10,10, 8,10,
  149195. 8,
  149196. };
  149197. static float _vq_quantthresh__44un1__p2_0[] = {
  149198. -0.5, 0.5,
  149199. };
  149200. static long _vq_quantmap__44un1__p2_0[] = {
  149201. 1, 0, 2,
  149202. };
  149203. static encode_aux_threshmatch _vq_auxt__44un1__p2_0 = {
  149204. _vq_quantthresh__44un1__p2_0,
  149205. _vq_quantmap__44un1__p2_0,
  149206. 3,
  149207. 3
  149208. };
  149209. static static_codebook _44un1__p2_0 = {
  149210. 4, 81,
  149211. _vq_lengthlist__44un1__p2_0,
  149212. 1, -535822336, 1611661312, 2, 0,
  149213. _vq_quantlist__44un1__p2_0,
  149214. NULL,
  149215. &_vq_auxt__44un1__p2_0,
  149216. NULL,
  149217. 0
  149218. };
  149219. static long _vq_quantlist__44un1__p3_0[] = {
  149220. 2,
  149221. 1,
  149222. 3,
  149223. 0,
  149224. 4,
  149225. };
  149226. static long _vq_lengthlist__44un1__p3_0[] = {
  149227. 1, 5, 5, 8, 8, 5, 8, 7, 9, 9, 5, 7, 8, 9, 9, 9,
  149228. 10, 9,12,12, 9, 9,10,11,12, 6, 8, 8,10,10, 8,10,
  149229. 10,11,11, 8, 9,10,11,11,10,11,11,13,13,10,11,11,
  149230. 12,13, 6, 8, 8,10,10, 8,10, 9,11,11, 8,10,10,11,
  149231. 11,10,11,11,13,12,10,11,11,13,12, 9,11,11,15,13,
  149232. 10,12,11,15,13,10,11,11,15,14,12,14,13,16,15,12,
  149233. 13,13,17,16, 9,11,11,13,15,10,11,12,14,15,10,11,
  149234. 12,14,15,12,13,13,15,16,12,13,13,16,16, 5, 8, 8,
  149235. 11,11, 8,10,10,12,12, 8,10,10,12,12,11,12,12,14,
  149236. 14,11,12,12,14,14, 8,11,10,13,12,10,11,12,12,13,
  149237. 10,12,12,13,13,12,12,13,13,15,11,12,13,15,14, 7,
  149238. 10,10,12,12, 9,12,11,13,12,10,12,12,13,14,12,13,
  149239. 12,15,13,11,13,12,14,15,10,12,12,16,14,11,12,12,
  149240. 16,15,11,13,12,17,16,13,13,15,15,17,13,15,15,20,
  149241. 17,10,12,12,14,16,11,12,12,15,15,11,13,13,15,18,
  149242. 13,14,13,15,15,13,15,14,16,16, 5, 8, 8,11,11, 8,
  149243. 10,10,12,12, 8,10,10,12,12,11,12,12,14,14,11,12,
  149244. 12,14,15, 7,10,10,13,12,10,12,12,14,13, 9,10,12,
  149245. 12,13,11,13,13,15,15,11,12,13,13,15, 8,10,10,12,
  149246. 13,10,12,12,13,13,10,12,11,13,13,11,13,12,15,15,
  149247. 12,13,12,15,13,10,12,12,16,14,11,12,12,16,15,10,
  149248. 12,12,16,14,14,15,14,18,16,13,13,14,15,16,10,12,
  149249. 12,14,16,11,13,13,16,16,11,13,12,14,16,13,15,15,
  149250. 18,18,13,15,13,16,14, 8,11,11,16,16,10,13,13,17,
  149251. 16,10,12,12,16,15,14,16,15,20,17,13,14,14,17,17,
  149252. 9,12,12,16,16,11,13,14,16,17,11,13,13,16,16,15,
  149253. 15,19,18, 0,14,15,15,18,18, 9,12,12,17,16,11,13,
  149254. 12,17,16,11,12,13,15,17,15,16,15, 0,19,14,15,14,
  149255. 19,18,12,14,14, 0,16,13,14,14,19,18,13,15,16,17,
  149256. 16,15,15,17,18, 0,14,16,16,19, 0,12,14,14,16,18,
  149257. 13,15,13,17,18,13,15,14,17,18,15,18,14,18,18,16,
  149258. 17,16, 0,17, 8,11,11,15,15,10,12,12,16,16,10,13,
  149259. 13,16,16,13,15,14,17,17,14,15,17,17,18, 9,12,12,
  149260. 16,15,11,13,13,16,16,11,12,13,17,17,14,14,15,17,
  149261. 17,14,15,16, 0,18, 9,12,12,16,17,11,13,13,16,17,
  149262. 11,14,13,18,17,14,16,14,17,17,15,17,17,18,18,12,
  149263. 14,14, 0,16,13,15,15,19, 0,12,13,15, 0, 0,14,17,
  149264. 16,19, 0,16,15,18,18, 0,12,14,14,17, 0,13,14,14,
  149265. 17, 0,13,15,14, 0,18,15,16,16, 0,18,15,18,15, 0,
  149266. 17,
  149267. };
  149268. static float _vq_quantthresh__44un1__p3_0[] = {
  149269. -1.5, -0.5, 0.5, 1.5,
  149270. };
  149271. static long _vq_quantmap__44un1__p3_0[] = {
  149272. 3, 1, 0, 2, 4,
  149273. };
  149274. static encode_aux_threshmatch _vq_auxt__44un1__p3_0 = {
  149275. _vq_quantthresh__44un1__p3_0,
  149276. _vq_quantmap__44un1__p3_0,
  149277. 5,
  149278. 5
  149279. };
  149280. static static_codebook _44un1__p3_0 = {
  149281. 4, 625,
  149282. _vq_lengthlist__44un1__p3_0,
  149283. 1, -533725184, 1611661312, 3, 0,
  149284. _vq_quantlist__44un1__p3_0,
  149285. NULL,
  149286. &_vq_auxt__44un1__p3_0,
  149287. NULL,
  149288. 0
  149289. };
  149290. static long _vq_quantlist__44un1__p4_0[] = {
  149291. 2,
  149292. 1,
  149293. 3,
  149294. 0,
  149295. 4,
  149296. };
  149297. static long _vq_lengthlist__44un1__p4_0[] = {
  149298. 3, 5, 5, 9, 9, 5, 6, 6,10, 9, 5, 6, 6, 9,10,10,
  149299. 10,10,12,11, 9,10,10,12,12, 5, 7, 7,10,10, 7, 7,
  149300. 8,10,11, 7, 7, 8,10,11,10,10,11,11,13,10,10,11,
  149301. 11,13, 6, 7, 7,10,10, 7, 8, 7,11,10, 7, 8, 7,10,
  149302. 10,10,11, 9,13,11,10,11,10,13,11,10,10,10,14,13,
  149303. 10,11,11,14,13,10,10,11,13,14,12,12,13,15,15,12,
  149304. 12,13,13,14,10,10,10,12,13,10,11,10,13,13,10,11,
  149305. 11,13,13,12,13,12,14,13,12,13,13,14,13, 5, 7, 7,
  149306. 10,10, 7, 8, 8,11,10, 7, 8, 8,10,10,11,11,11,13,
  149307. 13,10,11,11,12,12, 7, 8, 8,11,11, 7, 8, 9,10,12,
  149308. 8, 9, 9,11,11,11,10,12,11,14,11,11,12,13,13, 6,
  149309. 8, 8,10,11, 7, 9, 7,12,10, 8, 9,10,11,12,10,12,
  149310. 10,14,11,11,12,11,13,13,10,11,11,14,14,10,10,11,
  149311. 13,14,11,12,12,15,13,12,11,14,12,16,12,13,14,15,
  149312. 16,10,10,11,13,14,10,11,10,14,12,11,12,12,13,14,
  149313. 12,13,11,15,12,14,14,14,15,15, 5, 7, 7,10,10, 7,
  149314. 8, 8,10,10, 7, 8, 8,10,11,10,11,10,12,12,10,11,
  149315. 11,12,13, 6, 8, 8,11,11, 8, 9, 9,12,11, 7, 7, 9,
  149316. 10,12,11,11,11,12,13,11,10,12,11,15, 7, 8, 8,11,
  149317. 11, 8, 9, 9,11,11, 7, 9, 8,12,10,11,12,11,13,12,
  149318. 11,12,10,15,11,10,11,10,14,12,11,12,11,14,13,10,
  149319. 10,11,13,14,13,13,13,17,15,12,11,14,12,15,10,10,
  149320. 11,13,14,11,12,12,14,14,10,11,10,14,13,13,14,13,
  149321. 16,17,12,14,11,16,12, 9,10,10,14,13,10,11,10,14,
  149322. 14,10,11,11,13,13,13,14,14,16,15,12,13,13,14,14,
  149323. 9,11,10,14,13,10,10,12,13,14,11,12,11,14,13,13,
  149324. 14,14,14,15,13,14,14,15,15, 9,10,11,13,14,10,11,
  149325. 10,15,13,11,11,12,12,15,13,14,12,15,14,13,13,14,
  149326. 14,15,12,13,12,16,14,11,11,12,15,14,13,15,13,16,
  149327. 14,13,12,15,12,17,15,16,15,16,16,12,12,13,13,15,
  149328. 11,13,11,15,14,13,13,14,15,17,13,14,12, 0,13,14,
  149329. 15,14,15, 0, 9,10,10,13,13,10,11,11,13,13,10,11,
  149330. 11,13,13,12,13,12,14,14,13,14,14,15,17, 9,10,10,
  149331. 13,13,11,12,11,15,12,10,10,11,13,16,13,14,13,15,
  149332. 14,13,13,14,15,16,10,10,11,13,14,11,11,12,13,14,
  149333. 10,12,11,14,14,13,13,13,14,15,13,15,13,16,15,12,
  149334. 13,12,15,13,12,15,13,15,15,11,11,13,14,15,15,15,
  149335. 15,15,17,13,12,14,13,17,12,12,14,14,15,13,13,14,
  149336. 14,16,11,13,11,16,15,14,16,16,17, 0,14,13,11,16,
  149337. 12,
  149338. };
  149339. static float _vq_quantthresh__44un1__p4_0[] = {
  149340. -1.5, -0.5, 0.5, 1.5,
  149341. };
  149342. static long _vq_quantmap__44un1__p4_0[] = {
  149343. 3, 1, 0, 2, 4,
  149344. };
  149345. static encode_aux_threshmatch _vq_auxt__44un1__p4_0 = {
  149346. _vq_quantthresh__44un1__p4_0,
  149347. _vq_quantmap__44un1__p4_0,
  149348. 5,
  149349. 5
  149350. };
  149351. static static_codebook _44un1__p4_0 = {
  149352. 4, 625,
  149353. _vq_lengthlist__44un1__p4_0,
  149354. 1, -533725184, 1611661312, 3, 0,
  149355. _vq_quantlist__44un1__p4_0,
  149356. NULL,
  149357. &_vq_auxt__44un1__p4_0,
  149358. NULL,
  149359. 0
  149360. };
  149361. static long _vq_quantlist__44un1__p5_0[] = {
  149362. 4,
  149363. 3,
  149364. 5,
  149365. 2,
  149366. 6,
  149367. 1,
  149368. 7,
  149369. 0,
  149370. 8,
  149371. };
  149372. static long _vq_lengthlist__44un1__p5_0[] = {
  149373. 1, 4, 4, 7, 7, 8, 8, 9, 9, 4, 6, 5, 8, 7, 8, 8,
  149374. 10, 9, 4, 6, 6, 8, 8, 8, 8,10,10, 7, 8, 7, 9, 9,
  149375. 9, 9,11,10, 7, 8, 8, 9, 9, 9, 9,10,11, 8, 8, 8,
  149376. 9, 9,10,10,11,11, 8, 8, 8, 9, 9,10,10,11,11, 9,
  149377. 10,10,11,10,11,11,12,12, 9,10,10,10,11,11,11,12,
  149378. 12,
  149379. };
  149380. static float _vq_quantthresh__44un1__p5_0[] = {
  149381. -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5, 3.5,
  149382. };
  149383. static long _vq_quantmap__44un1__p5_0[] = {
  149384. 7, 5, 3, 1, 0, 2, 4, 6,
  149385. 8,
  149386. };
  149387. static encode_aux_threshmatch _vq_auxt__44un1__p5_0 = {
  149388. _vq_quantthresh__44un1__p5_0,
  149389. _vq_quantmap__44un1__p5_0,
  149390. 9,
  149391. 9
  149392. };
  149393. static static_codebook _44un1__p5_0 = {
  149394. 2, 81,
  149395. _vq_lengthlist__44un1__p5_0,
  149396. 1, -531628032, 1611661312, 4, 0,
  149397. _vq_quantlist__44un1__p5_0,
  149398. NULL,
  149399. &_vq_auxt__44un1__p5_0,
  149400. NULL,
  149401. 0
  149402. };
  149403. static long _vq_quantlist__44un1__p6_0[] = {
  149404. 6,
  149405. 5,
  149406. 7,
  149407. 4,
  149408. 8,
  149409. 3,
  149410. 9,
  149411. 2,
  149412. 10,
  149413. 1,
  149414. 11,
  149415. 0,
  149416. 12,
  149417. };
  149418. static long _vq_lengthlist__44un1__p6_0[] = {
  149419. 1, 4, 4, 6, 6, 8, 8,10,10,11,11,15,15, 4, 5, 5,
  149420. 8, 8, 9, 9,11,11,12,12,16,16, 4, 5, 6, 8, 8, 9,
  149421. 9,11,11,12,12,14,14, 7, 8, 8, 9, 9,10,10,11,12,
  149422. 13,13,16,17, 7, 8, 8, 9, 9,10,10,12,12,12,13,15,
  149423. 15, 9,10,10,10,10,11,11,12,12,13,13,15,16, 9, 9,
  149424. 9,10,10,11,11,13,12,13,13,17,17,10,11,11,11,12,
  149425. 12,12,13,13,14,15, 0,18,10,11,11,12,12,12,13,14,
  149426. 13,14,14,17,16,11,12,12,13,13,14,14,14,14,15,16,
  149427. 17,16,11,12,12,13,13,14,14,14,14,15,15,17,17,14,
  149428. 15,15,16,16,16,17,17,16, 0,17, 0,18,14,15,15,16,
  149429. 16, 0,15,18,18, 0,16, 0, 0,
  149430. };
  149431. static float _vq_quantthresh__44un1__p6_0[] = {
  149432. -27.5, -22.5, -17.5, -12.5, -7.5, -2.5, 2.5, 7.5,
  149433. 12.5, 17.5, 22.5, 27.5,
  149434. };
  149435. static long _vq_quantmap__44un1__p6_0[] = {
  149436. 11, 9, 7, 5, 3, 1, 0, 2,
  149437. 4, 6, 8, 10, 12,
  149438. };
  149439. static encode_aux_threshmatch _vq_auxt__44un1__p6_0 = {
  149440. _vq_quantthresh__44un1__p6_0,
  149441. _vq_quantmap__44un1__p6_0,
  149442. 13,
  149443. 13
  149444. };
  149445. static static_codebook _44un1__p6_0 = {
  149446. 2, 169,
  149447. _vq_lengthlist__44un1__p6_0,
  149448. 1, -526516224, 1616117760, 4, 0,
  149449. _vq_quantlist__44un1__p6_0,
  149450. NULL,
  149451. &_vq_auxt__44un1__p6_0,
  149452. NULL,
  149453. 0
  149454. };
  149455. static long _vq_quantlist__44un1__p6_1[] = {
  149456. 2,
  149457. 1,
  149458. 3,
  149459. 0,
  149460. 4,
  149461. };
  149462. static long _vq_lengthlist__44un1__p6_1[] = {
  149463. 2, 4, 4, 5, 5, 4, 5, 5, 5, 5, 4, 5, 5, 6, 5, 5,
  149464. 6, 5, 6, 6, 5, 6, 6, 6, 6,
  149465. };
  149466. static float _vq_quantthresh__44un1__p6_1[] = {
  149467. -1.5, -0.5, 0.5, 1.5,
  149468. };
  149469. static long _vq_quantmap__44un1__p6_1[] = {
  149470. 3, 1, 0, 2, 4,
  149471. };
  149472. static encode_aux_threshmatch _vq_auxt__44un1__p6_1 = {
  149473. _vq_quantthresh__44un1__p6_1,
  149474. _vq_quantmap__44un1__p6_1,
  149475. 5,
  149476. 5
  149477. };
  149478. static static_codebook _44un1__p6_1 = {
  149479. 2, 25,
  149480. _vq_lengthlist__44un1__p6_1,
  149481. 1, -533725184, 1611661312, 3, 0,
  149482. _vq_quantlist__44un1__p6_1,
  149483. NULL,
  149484. &_vq_auxt__44un1__p6_1,
  149485. NULL,
  149486. 0
  149487. };
  149488. static long _vq_quantlist__44un1__p7_0[] = {
  149489. 2,
  149490. 1,
  149491. 3,
  149492. 0,
  149493. 4,
  149494. };
  149495. static long _vq_lengthlist__44un1__p7_0[] = {
  149496. 1, 5, 3,11,11,11,11,11,11,11, 8,11,11,11,11,11,
  149497. 11,11,11,11,11,11,11,11,11,10,11,11,11,11,11,11,
  149498. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  149499. 11,11,10,11,11,11,11,11,11,11,11,11,11,11,11,11,
  149500. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  149501. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  149502. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  149503. 11,11,11,11,11,11,11,11,11,11,11,11,11, 8,11,11,
  149504. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  149505. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  149506. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,10,
  149507. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  149508. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  149509. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  149510. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  149511. 11,11,11,11,11,11,11,11,11,11, 7,11,11,11,11,11,
  149512. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  149513. 11,11,11,10,11,11,11,11,11,11,11,11,11,11,11,11,
  149514. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  149515. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  149516. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  149517. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  149518. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  149519. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  149520. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  149521. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  149522. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  149523. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  149524. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  149525. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  149526. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  149527. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  149528. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  149529. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  149530. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  149531. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  149532. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  149533. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  149534. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  149535. 10,
  149536. };
  149537. static float _vq_quantthresh__44un1__p7_0[] = {
  149538. -253.5, -84.5, 84.5, 253.5,
  149539. };
  149540. static long _vq_quantmap__44un1__p7_0[] = {
  149541. 3, 1, 0, 2, 4,
  149542. };
  149543. static encode_aux_threshmatch _vq_auxt__44un1__p7_0 = {
  149544. _vq_quantthresh__44un1__p7_0,
  149545. _vq_quantmap__44un1__p7_0,
  149546. 5,
  149547. 5
  149548. };
  149549. static static_codebook _44un1__p7_0 = {
  149550. 4, 625,
  149551. _vq_lengthlist__44un1__p7_0,
  149552. 1, -518709248, 1626677248, 3, 0,
  149553. _vq_quantlist__44un1__p7_0,
  149554. NULL,
  149555. &_vq_auxt__44un1__p7_0,
  149556. NULL,
  149557. 0
  149558. };
  149559. static long _vq_quantlist__44un1__p7_1[] = {
  149560. 6,
  149561. 5,
  149562. 7,
  149563. 4,
  149564. 8,
  149565. 3,
  149566. 9,
  149567. 2,
  149568. 10,
  149569. 1,
  149570. 11,
  149571. 0,
  149572. 12,
  149573. };
  149574. static long _vq_lengthlist__44un1__p7_1[] = {
  149575. 1, 4, 4, 6, 6, 6, 6, 9, 8, 9, 8, 8, 8, 5, 7, 7,
  149576. 7, 7, 8, 8, 8,10, 8,10, 8, 9, 5, 7, 7, 8, 7, 7,
  149577. 8,10,10,11,10,12,11, 7, 8, 8, 9, 9, 9,10,11,11,
  149578. 11,11,11,11, 7, 8, 8, 8, 9, 9, 9,10,10,10,11,11,
  149579. 12, 7, 8, 8, 9, 9,10,11,11,12,11,12,11,11, 7, 8,
  149580. 8, 9, 9,10,10,11,11,11,12,12,11, 8,10,10,10,10,
  149581. 11,11,14,11,12,12,12,13, 9,10,10,10,10,12,11,14,
  149582. 11,14,11,12,13,10,11,11,11,11,13,11,14,14,13,13,
  149583. 13,14,11,11,11,12,11,12,12,12,13,14,14,13,14,12,
  149584. 11,12,12,12,12,13,13,13,14,13,14,14,11,12,12,14,
  149585. 12,13,13,12,13,13,14,14,14,
  149586. };
  149587. static float _vq_quantthresh__44un1__p7_1[] = {
  149588. -71.5, -58.5, -45.5, -32.5, -19.5, -6.5, 6.5, 19.5,
  149589. 32.5, 45.5, 58.5, 71.5,
  149590. };
  149591. static long _vq_quantmap__44un1__p7_1[] = {
  149592. 11, 9, 7, 5, 3, 1, 0, 2,
  149593. 4, 6, 8, 10, 12,
  149594. };
  149595. static encode_aux_threshmatch _vq_auxt__44un1__p7_1 = {
  149596. _vq_quantthresh__44un1__p7_1,
  149597. _vq_quantmap__44un1__p7_1,
  149598. 13,
  149599. 13
  149600. };
  149601. static static_codebook _44un1__p7_1 = {
  149602. 2, 169,
  149603. _vq_lengthlist__44un1__p7_1,
  149604. 1, -523010048, 1618608128, 4, 0,
  149605. _vq_quantlist__44un1__p7_1,
  149606. NULL,
  149607. &_vq_auxt__44un1__p7_1,
  149608. NULL,
  149609. 0
  149610. };
  149611. static long _vq_quantlist__44un1__p7_2[] = {
  149612. 6,
  149613. 5,
  149614. 7,
  149615. 4,
  149616. 8,
  149617. 3,
  149618. 9,
  149619. 2,
  149620. 10,
  149621. 1,
  149622. 11,
  149623. 0,
  149624. 12,
  149625. };
  149626. static long _vq_lengthlist__44un1__p7_2[] = {
  149627. 3, 4, 4, 6, 6, 7, 7, 8, 8, 9, 9, 9, 8, 4, 5, 5,
  149628. 6, 6, 8, 8, 9, 8, 9, 9, 9, 9, 4, 5, 5, 7, 6, 8,
  149629. 8, 8, 8, 9, 8, 9, 8, 6, 7, 7, 7, 8, 8, 8, 9, 9,
  149630. 9, 9, 9, 9, 6, 7, 7, 7, 7, 8, 8, 9, 9, 9, 9, 9,
  149631. 9, 7, 8, 8, 8, 8, 9, 8, 9, 9,10, 9, 9,10, 7, 8,
  149632. 8, 8, 8, 9, 9, 9, 9, 9, 9,10,10, 8, 9, 9, 9, 9,
  149633. 9, 9, 9, 9,10,10, 9,10, 8, 9, 9, 9, 9, 9, 9, 9,
  149634. 9, 9, 9,10,10, 9, 9, 9,10, 9, 9,10, 9, 9,10,10,
  149635. 10,10, 9, 9, 9, 9, 9, 9, 9,10, 9,10,10,10,10, 9,
  149636. 9, 9,10, 9, 9,10,10, 9,10,10,10,10, 9, 9, 9,10,
  149637. 9, 9, 9,10,10,10,10,10,10,
  149638. };
  149639. static float _vq_quantthresh__44un1__p7_2[] = {
  149640. -5.5, -4.5, -3.5, -2.5, -1.5, -0.5, 0.5, 1.5,
  149641. 2.5, 3.5, 4.5, 5.5,
  149642. };
  149643. static long _vq_quantmap__44un1__p7_2[] = {
  149644. 11, 9, 7, 5, 3, 1, 0, 2,
  149645. 4, 6, 8, 10, 12,
  149646. };
  149647. static encode_aux_threshmatch _vq_auxt__44un1__p7_2 = {
  149648. _vq_quantthresh__44un1__p7_2,
  149649. _vq_quantmap__44un1__p7_2,
  149650. 13,
  149651. 13
  149652. };
  149653. static static_codebook _44un1__p7_2 = {
  149654. 2, 169,
  149655. _vq_lengthlist__44un1__p7_2,
  149656. 1, -531103744, 1611661312, 4, 0,
  149657. _vq_quantlist__44un1__p7_2,
  149658. NULL,
  149659. &_vq_auxt__44un1__p7_2,
  149660. NULL,
  149661. 0
  149662. };
  149663. static long _huff_lengthlist__44un1__short[] = {
  149664. 12,12,14,12,14,14,14,14,12, 6, 6, 8, 9, 9,11,14,
  149665. 12, 4, 2, 6, 6, 7,11,14,13, 6, 5, 7, 8, 9,11,14,
  149666. 13, 8, 5, 8, 6, 8,12,14,12, 7, 7, 8, 8, 8,10,14,
  149667. 12, 6, 3, 4, 4, 4, 7,14,11, 7, 4, 6, 6, 6, 8,14,
  149668. };
  149669. static static_codebook _huff_book__44un1__short = {
  149670. 2, 64,
  149671. _huff_lengthlist__44un1__short,
  149672. 0, 0, 0, 0, 0,
  149673. NULL,
  149674. NULL,
  149675. NULL,
  149676. NULL,
  149677. 0
  149678. };
  149679. /*** End of inlined file: res_books_uncoupled.h ***/
  149680. /***** residue backends *********************************************/
  149681. static vorbis_info_residue0 _residue_44_low_un={
  149682. 0,-1, -1, 8,-1,
  149683. {0},
  149684. {-1},
  149685. { .5, 1.5, 1.5, 2.5, 2.5, 4.5, 28.5},
  149686. { -1, 25, -1, 45, -1, -1, -1}
  149687. };
  149688. static vorbis_info_residue0 _residue_44_mid_un={
  149689. 0,-1, -1, 10,-1,
  149690. /* 0 1 2 3 4 5 6 7 8 9 */
  149691. {0},
  149692. {-1},
  149693. { .5, 1.5, 1.5, 2.5, 2.5, 4.5, 4.5, 16.5, 60.5},
  149694. { -1, 30, -1, 50, -1, 80, -1, -1, -1}
  149695. };
  149696. static vorbis_info_residue0 _residue_44_hi_un={
  149697. 0,-1, -1, 10,-1,
  149698. /* 0 1 2 3 4 5 6 7 8 9 */
  149699. {0},
  149700. {-1},
  149701. { .5, 1.5, 2.5, 4.5, 8.5, 16.5, 32.5, 71.5,157.5},
  149702. { -1, -1, -1, -1, -1, -1, -1, -1, -1}
  149703. };
  149704. /* mapping conventions:
  149705. only one submap (this would change for efficient 5.1 support for example)*/
  149706. /* Four psychoacoustic profiles are used, one for each blocktype */
  149707. static vorbis_info_mapping0 _map_nominal_u[2]={
  149708. {1, {0,0}, {0}, {0}, 0,{0},{0}},
  149709. {1, {0,0}, {1}, {1}, 0,{0},{0}}
  149710. };
  149711. static static_bookblock _resbook_44u_n1={
  149712. {
  149713. {0},
  149714. {0,0,&_44un1__p1_0},
  149715. {0,0,&_44un1__p2_0},
  149716. {0,0,&_44un1__p3_0},
  149717. {0,0,&_44un1__p4_0},
  149718. {0,0,&_44un1__p5_0},
  149719. {&_44un1__p6_0,&_44un1__p6_1},
  149720. {&_44un1__p7_0,&_44un1__p7_1,&_44un1__p7_2}
  149721. }
  149722. };
  149723. static static_bookblock _resbook_44u_0={
  149724. {
  149725. {0},
  149726. {0,0,&_44u0__p1_0},
  149727. {0,0,&_44u0__p2_0},
  149728. {0,0,&_44u0__p3_0},
  149729. {0,0,&_44u0__p4_0},
  149730. {0,0,&_44u0__p5_0},
  149731. {&_44u0__p6_0,&_44u0__p6_1},
  149732. {&_44u0__p7_0,&_44u0__p7_1,&_44u0__p7_2}
  149733. }
  149734. };
  149735. static static_bookblock _resbook_44u_1={
  149736. {
  149737. {0},
  149738. {0,0,&_44u1__p1_0},
  149739. {0,0,&_44u1__p2_0},
  149740. {0,0,&_44u1__p3_0},
  149741. {0,0,&_44u1__p4_0},
  149742. {0,0,&_44u1__p5_0},
  149743. {&_44u1__p6_0,&_44u1__p6_1},
  149744. {&_44u1__p7_0,&_44u1__p7_1,&_44u1__p7_2}
  149745. }
  149746. };
  149747. static static_bookblock _resbook_44u_2={
  149748. {
  149749. {0},
  149750. {0,0,&_44u2__p1_0},
  149751. {0,0,&_44u2__p2_0},
  149752. {0,0,&_44u2__p3_0},
  149753. {0,0,&_44u2__p4_0},
  149754. {0,0,&_44u2__p5_0},
  149755. {&_44u2__p6_0,&_44u2__p6_1},
  149756. {&_44u2__p7_0,&_44u2__p7_1,&_44u2__p7_2}
  149757. }
  149758. };
  149759. static static_bookblock _resbook_44u_3={
  149760. {
  149761. {0},
  149762. {0,0,&_44u3__p1_0},
  149763. {0,0,&_44u3__p2_0},
  149764. {0,0,&_44u3__p3_0},
  149765. {0,0,&_44u3__p4_0},
  149766. {0,0,&_44u3__p5_0},
  149767. {&_44u3__p6_0,&_44u3__p6_1},
  149768. {&_44u3__p7_0,&_44u3__p7_1,&_44u3__p7_2}
  149769. }
  149770. };
  149771. static static_bookblock _resbook_44u_4={
  149772. {
  149773. {0},
  149774. {0,0,&_44u4__p1_0},
  149775. {0,0,&_44u4__p2_0},
  149776. {0,0,&_44u4__p3_0},
  149777. {0,0,&_44u4__p4_0},
  149778. {0,0,&_44u4__p5_0},
  149779. {&_44u4__p6_0,&_44u4__p6_1},
  149780. {&_44u4__p7_0,&_44u4__p7_1,&_44u4__p7_2}
  149781. }
  149782. };
  149783. static static_bookblock _resbook_44u_5={
  149784. {
  149785. {0},
  149786. {0,0,&_44u5__p1_0},
  149787. {0,0,&_44u5__p2_0},
  149788. {0,0,&_44u5__p3_0},
  149789. {0,0,&_44u5__p4_0},
  149790. {0,0,&_44u5__p5_0},
  149791. {0,0,&_44u5__p6_0},
  149792. {&_44u5__p7_0,&_44u5__p7_1},
  149793. {&_44u5__p8_0,&_44u5__p8_1},
  149794. {&_44u5__p9_0,&_44u5__p9_1,&_44u5__p9_2}
  149795. }
  149796. };
  149797. static static_bookblock _resbook_44u_6={
  149798. {
  149799. {0},
  149800. {0,0,&_44u6__p1_0},
  149801. {0,0,&_44u6__p2_0},
  149802. {0,0,&_44u6__p3_0},
  149803. {0,0,&_44u6__p4_0},
  149804. {0,0,&_44u6__p5_0},
  149805. {0,0,&_44u6__p6_0},
  149806. {&_44u6__p7_0,&_44u6__p7_1},
  149807. {&_44u6__p8_0,&_44u6__p8_1},
  149808. {&_44u6__p9_0,&_44u6__p9_1,&_44u6__p9_2}
  149809. }
  149810. };
  149811. static static_bookblock _resbook_44u_7={
  149812. {
  149813. {0},
  149814. {0,0,&_44u7__p1_0},
  149815. {0,0,&_44u7__p2_0},
  149816. {0,0,&_44u7__p3_0},
  149817. {0,0,&_44u7__p4_0},
  149818. {0,0,&_44u7__p5_0},
  149819. {0,0,&_44u7__p6_0},
  149820. {&_44u7__p7_0,&_44u7__p7_1},
  149821. {&_44u7__p8_0,&_44u7__p8_1},
  149822. {&_44u7__p9_0,&_44u7__p9_1,&_44u7__p9_2}
  149823. }
  149824. };
  149825. static static_bookblock _resbook_44u_8={
  149826. {
  149827. {0},
  149828. {0,0,&_44u8_p1_0},
  149829. {0,0,&_44u8_p2_0},
  149830. {0,0,&_44u8_p3_0},
  149831. {0,0,&_44u8_p4_0},
  149832. {&_44u8_p5_0,&_44u8_p5_1},
  149833. {&_44u8_p6_0,&_44u8_p6_1},
  149834. {&_44u8_p7_0,&_44u8_p7_1},
  149835. {&_44u8_p8_0,&_44u8_p8_1},
  149836. {&_44u8_p9_0,&_44u8_p9_1,&_44u8_p9_2}
  149837. }
  149838. };
  149839. static static_bookblock _resbook_44u_9={
  149840. {
  149841. {0},
  149842. {0,0,&_44u9_p1_0},
  149843. {0,0,&_44u9_p2_0},
  149844. {0,0,&_44u9_p3_0},
  149845. {0,0,&_44u9_p4_0},
  149846. {&_44u9_p5_0,&_44u9_p5_1},
  149847. {&_44u9_p6_0,&_44u9_p6_1},
  149848. {&_44u9_p7_0,&_44u9_p7_1},
  149849. {&_44u9_p8_0,&_44u9_p8_1},
  149850. {&_44u9_p9_0,&_44u9_p9_1,&_44u9_p9_2}
  149851. }
  149852. };
  149853. static vorbis_residue_template _res_44u_n1[]={
  149854. {1,0, &_residue_44_low_un,
  149855. &_huff_book__44un1__short,&_huff_book__44un1__short,
  149856. &_resbook_44u_n1,&_resbook_44u_n1},
  149857. {1,0, &_residue_44_low_un,
  149858. &_huff_book__44un1__long,&_huff_book__44un1__long,
  149859. &_resbook_44u_n1,&_resbook_44u_n1}
  149860. };
  149861. static vorbis_residue_template _res_44u_0[]={
  149862. {1,0, &_residue_44_low_un,
  149863. &_huff_book__44u0__short,&_huff_book__44u0__short,
  149864. &_resbook_44u_0,&_resbook_44u_0},
  149865. {1,0, &_residue_44_low_un,
  149866. &_huff_book__44u0__long,&_huff_book__44u0__long,
  149867. &_resbook_44u_0,&_resbook_44u_0}
  149868. };
  149869. static vorbis_residue_template _res_44u_1[]={
  149870. {1,0, &_residue_44_low_un,
  149871. &_huff_book__44u1__short,&_huff_book__44u1__short,
  149872. &_resbook_44u_1,&_resbook_44u_1},
  149873. {1,0, &_residue_44_low_un,
  149874. &_huff_book__44u1__long,&_huff_book__44u1__long,
  149875. &_resbook_44u_1,&_resbook_44u_1}
  149876. };
  149877. static vorbis_residue_template _res_44u_2[]={
  149878. {1,0, &_residue_44_low_un,
  149879. &_huff_book__44u2__short,&_huff_book__44u2__short,
  149880. &_resbook_44u_2,&_resbook_44u_2},
  149881. {1,0, &_residue_44_low_un,
  149882. &_huff_book__44u2__long,&_huff_book__44u2__long,
  149883. &_resbook_44u_2,&_resbook_44u_2}
  149884. };
  149885. static vorbis_residue_template _res_44u_3[]={
  149886. {1,0, &_residue_44_low_un,
  149887. &_huff_book__44u3__short,&_huff_book__44u3__short,
  149888. &_resbook_44u_3,&_resbook_44u_3},
  149889. {1,0, &_residue_44_low_un,
  149890. &_huff_book__44u3__long,&_huff_book__44u3__long,
  149891. &_resbook_44u_3,&_resbook_44u_3}
  149892. };
  149893. static vorbis_residue_template _res_44u_4[]={
  149894. {1,0, &_residue_44_low_un,
  149895. &_huff_book__44u4__short,&_huff_book__44u4__short,
  149896. &_resbook_44u_4,&_resbook_44u_4},
  149897. {1,0, &_residue_44_low_un,
  149898. &_huff_book__44u4__long,&_huff_book__44u4__long,
  149899. &_resbook_44u_4,&_resbook_44u_4}
  149900. };
  149901. static vorbis_residue_template _res_44u_5[]={
  149902. {1,0, &_residue_44_mid_un,
  149903. &_huff_book__44u5__short,&_huff_book__44u5__short,
  149904. &_resbook_44u_5,&_resbook_44u_5},
  149905. {1,0, &_residue_44_mid_un,
  149906. &_huff_book__44u5__long,&_huff_book__44u5__long,
  149907. &_resbook_44u_5,&_resbook_44u_5}
  149908. };
  149909. static vorbis_residue_template _res_44u_6[]={
  149910. {1,0, &_residue_44_mid_un,
  149911. &_huff_book__44u6__short,&_huff_book__44u6__short,
  149912. &_resbook_44u_6,&_resbook_44u_6},
  149913. {1,0, &_residue_44_mid_un,
  149914. &_huff_book__44u6__long,&_huff_book__44u6__long,
  149915. &_resbook_44u_6,&_resbook_44u_6}
  149916. };
  149917. static vorbis_residue_template _res_44u_7[]={
  149918. {1,0, &_residue_44_mid_un,
  149919. &_huff_book__44u7__short,&_huff_book__44u7__short,
  149920. &_resbook_44u_7,&_resbook_44u_7},
  149921. {1,0, &_residue_44_mid_un,
  149922. &_huff_book__44u7__long,&_huff_book__44u7__long,
  149923. &_resbook_44u_7,&_resbook_44u_7}
  149924. };
  149925. static vorbis_residue_template _res_44u_8[]={
  149926. {1,0, &_residue_44_hi_un,
  149927. &_huff_book__44u8__short,&_huff_book__44u8__short,
  149928. &_resbook_44u_8,&_resbook_44u_8},
  149929. {1,0, &_residue_44_hi_un,
  149930. &_huff_book__44u8__long,&_huff_book__44u8__long,
  149931. &_resbook_44u_8,&_resbook_44u_8}
  149932. };
  149933. static vorbis_residue_template _res_44u_9[]={
  149934. {1,0, &_residue_44_hi_un,
  149935. &_huff_book__44u9__short,&_huff_book__44u9__short,
  149936. &_resbook_44u_9,&_resbook_44u_9},
  149937. {1,0, &_residue_44_hi_un,
  149938. &_huff_book__44u9__long,&_huff_book__44u9__long,
  149939. &_resbook_44u_9,&_resbook_44u_9}
  149940. };
  149941. static vorbis_mapping_template _mapres_template_44_uncoupled[]={
  149942. { _map_nominal_u, _res_44u_n1 }, /* -1 */
  149943. { _map_nominal_u, _res_44u_0 }, /* 0 */
  149944. { _map_nominal_u, _res_44u_1 }, /* 1 */
  149945. { _map_nominal_u, _res_44u_2 }, /* 2 */
  149946. { _map_nominal_u, _res_44u_3 }, /* 3 */
  149947. { _map_nominal_u, _res_44u_4 }, /* 4 */
  149948. { _map_nominal_u, _res_44u_5 }, /* 5 */
  149949. { _map_nominal_u, _res_44u_6 }, /* 6 */
  149950. { _map_nominal_u, _res_44u_7 }, /* 7 */
  149951. { _map_nominal_u, _res_44u_8 }, /* 8 */
  149952. { _map_nominal_u, _res_44u_9 }, /* 9 */
  149953. };
  149954. /*** End of inlined file: residue_44u.h ***/
  149955. static double rate_mapping_44_un[12]={
  149956. 32000.,48000.,60000.,70000.,80000.,86000.,
  149957. 96000.,110000.,120000.,140000.,160000.,240001.
  149958. };
  149959. ve_setup_data_template ve_setup_44_uncoupled={
  149960. 11,
  149961. rate_mapping_44_un,
  149962. quality_mapping_44,
  149963. -1,
  149964. 40000,
  149965. 50000,
  149966. blocksize_short_44,
  149967. blocksize_long_44,
  149968. _psy_tone_masteratt_44,
  149969. _psy_tone_0dB,
  149970. _psy_tone_suppress,
  149971. _vp_tonemask_adj_otherblock,
  149972. _vp_tonemask_adj_longblock,
  149973. _vp_tonemask_adj_otherblock,
  149974. _psy_noiseguards_44,
  149975. _psy_noisebias_impulse,
  149976. _psy_noisebias_padding,
  149977. _psy_noisebias_trans,
  149978. _psy_noisebias_long,
  149979. _psy_noise_suppress,
  149980. _psy_compand_44,
  149981. _psy_compand_short_mapping,
  149982. _psy_compand_long_mapping,
  149983. {_noise_start_short_44,_noise_start_long_44},
  149984. {_noise_part_short_44,_noise_part_long_44},
  149985. _noise_thresh_44,
  149986. _psy_ath_floater,
  149987. _psy_ath_abs,
  149988. _psy_lowpass_44,
  149989. _psy_global_44,
  149990. _global_mapping_44,
  149991. NULL,
  149992. _floor_books,
  149993. _floor,
  149994. _floor_short_mapping_44,
  149995. _floor_long_mapping_44,
  149996. _mapres_template_44_uncoupled
  149997. };
  149998. /*** End of inlined file: setup_44u.h ***/
  149999. /*** Start of inlined file: setup_32.h ***/
  150000. static double rate_mapping_32[12]={
  150001. 18000.,28000.,35000.,45000.,56000.,60000.,
  150002. 75000.,90000.,100000.,115000.,150000.,190000.,
  150003. };
  150004. static double rate_mapping_32_un[12]={
  150005. 30000.,42000.,52000.,64000.,72000.,78000.,
  150006. 86000.,92000.,110000.,120000.,140000.,190000.,
  150007. };
  150008. static double _psy_lowpass_32[12]={
  150009. 12.3,13.,13.,14.,15.,99.,99.,99.,99.,99.,99.,99.
  150010. };
  150011. ve_setup_data_template ve_setup_32_stereo={
  150012. 11,
  150013. rate_mapping_32,
  150014. quality_mapping_44,
  150015. 2,
  150016. 26000,
  150017. 40000,
  150018. blocksize_short_44,
  150019. blocksize_long_44,
  150020. _psy_tone_masteratt_44,
  150021. _psy_tone_0dB,
  150022. _psy_tone_suppress,
  150023. _vp_tonemask_adj_otherblock,
  150024. _vp_tonemask_adj_longblock,
  150025. _vp_tonemask_adj_otherblock,
  150026. _psy_noiseguards_44,
  150027. _psy_noisebias_impulse,
  150028. _psy_noisebias_padding,
  150029. _psy_noisebias_trans,
  150030. _psy_noisebias_long,
  150031. _psy_noise_suppress,
  150032. _psy_compand_44,
  150033. _psy_compand_short_mapping,
  150034. _psy_compand_long_mapping,
  150035. {_noise_start_short_44,_noise_start_long_44},
  150036. {_noise_part_short_44,_noise_part_long_44},
  150037. _noise_thresh_44,
  150038. _psy_ath_floater,
  150039. _psy_ath_abs,
  150040. _psy_lowpass_32,
  150041. _psy_global_44,
  150042. _global_mapping_44,
  150043. _psy_stereo_modes_44,
  150044. _floor_books,
  150045. _floor,
  150046. _floor_short_mapping_44,
  150047. _floor_long_mapping_44,
  150048. _mapres_template_44_stereo
  150049. };
  150050. ve_setup_data_template ve_setup_32_uncoupled={
  150051. 11,
  150052. rate_mapping_32_un,
  150053. quality_mapping_44,
  150054. -1,
  150055. 26000,
  150056. 40000,
  150057. blocksize_short_44,
  150058. blocksize_long_44,
  150059. _psy_tone_masteratt_44,
  150060. _psy_tone_0dB,
  150061. _psy_tone_suppress,
  150062. _vp_tonemask_adj_otherblock,
  150063. _vp_tonemask_adj_longblock,
  150064. _vp_tonemask_adj_otherblock,
  150065. _psy_noiseguards_44,
  150066. _psy_noisebias_impulse,
  150067. _psy_noisebias_padding,
  150068. _psy_noisebias_trans,
  150069. _psy_noisebias_long,
  150070. _psy_noise_suppress,
  150071. _psy_compand_44,
  150072. _psy_compand_short_mapping,
  150073. _psy_compand_long_mapping,
  150074. {_noise_start_short_44,_noise_start_long_44},
  150075. {_noise_part_short_44,_noise_part_long_44},
  150076. _noise_thresh_44,
  150077. _psy_ath_floater,
  150078. _psy_ath_abs,
  150079. _psy_lowpass_32,
  150080. _psy_global_44,
  150081. _global_mapping_44,
  150082. NULL,
  150083. _floor_books,
  150084. _floor,
  150085. _floor_short_mapping_44,
  150086. _floor_long_mapping_44,
  150087. _mapres_template_44_uncoupled
  150088. };
  150089. /*** End of inlined file: setup_32.h ***/
  150090. /*** Start of inlined file: setup_8.h ***/
  150091. /*** Start of inlined file: psych_8.h ***/
  150092. static att3 _psy_tone_masteratt_8[3]={
  150093. {{ 32, 25, 12}, 0, 0}, /* 0 */
  150094. {{ 30, 25, 12}, 0, 0}, /* 0 */
  150095. {{ 20, 0, -14}, 0, 0}, /* 0 */
  150096. };
  150097. static vp_adjblock _vp_tonemask_adj_8[3]={
  150098. /* adjust for mode zero */
  150099. /* 63 125 250 500 1 2 4 8 16 */
  150100. {{-15,-15,-15,-15,-10,-10, -6, 0, 0, 0, 0,10, 0, 0,99,99,99}}, /* 1 */
  150101. {{-15,-15,-15,-15,-10,-10, -6, 0, 0, 0, 0,10, 0, 0,99,99,99}}, /* 1 */
  150102. {{-15,-15,-15,-15,-10,-10, -6, 0, 0, 0, 0, 0, 0, 0,99,99,99}}, /* 1 */
  150103. };
  150104. static noise3 _psy_noisebias_8[3]={
  150105. /* 63 125 250 500 1k 2k 4k 8k 16k*/
  150106. {{{-10,-10,-10,-10, -5, -5, -5, 0, 4, 8, 8, 8, 10, 10, 99, 99, 99},
  150107. {-10,-10,-10,-10, -5, -5, -5, 0, 0, 4, 4, 4, 4, 4, 99, 99, 99},
  150108. {-30,-30,-30,-30,-30,-24,-20,-14,-10, -6, -8, -8, -6, -6, 99, 99, 99}}},
  150109. {{{-10,-10,-10,-10, -5, -5, -5, 0, 4, 8, 8, 8, 10, 10, 99, 99, 99},
  150110. {-10,-10,-10,-10,-10,-10, -5, -5, -5, 0, 0, 0, 0, 0, 99, 99, 99},
  150111. {-30,-30,-30,-30,-30,-24,-20,-14,-10, -6, -8, -8, -6, -6, 99, 99, 99}}},
  150112. {{{-15,-15,-15,-15,-15,-12,-10, -8, 0, 2, 4, 4, 5, 5, 99, 99, 99},
  150113. {-30,-30,-30,-30,-26,-22,-20,-14,-12,-12,-10,-10,-10,-10, 99, 99, 99},
  150114. {-30,-30,-30,-30,-26,-26,-26,-26,-26,-26,-26,-26,-26,-24, 99, 99, 99}}},
  150115. };
  150116. /* stereo mode by base quality level */
  150117. static adj_stereo _psy_stereo_modes_8[3]={
  150118. /* 0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 */
  150119. {{ 4, 4, 4, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3},
  150120. { 6, 5, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4},
  150121. { 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1},
  150122. { 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99}},
  150123. {{ 4, 4, 4, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3},
  150124. { 6, 5, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4},
  150125. { 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1},
  150126. { 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99}},
  150127. {{ 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3},
  150128. { 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4},
  150129. { 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1},
  150130. { 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99}},
  150131. };
  150132. static noiseguard _psy_noiseguards_8[2]={
  150133. {10,10,-1},
  150134. {10,10,-1},
  150135. };
  150136. static compandblock _psy_compand_8[2]={
  150137. {{
  150138. 0, 1, 2, 3, 4, 5, 6, 7, /* 7dB */
  150139. 8, 8, 9, 9,10,10,11, 11, /* 15dB */
  150140. 12,12,13,13,14,14,15, 15, /* 23dB */
  150141. 16,16,17,17,17,18,18, 19, /* 31dB */
  150142. 19,19,20,21,22,23,24, 25, /* 39dB */
  150143. }},
  150144. {{
  150145. 0, 1, 2, 3, 4, 5, 6, 6, /* 7dB */
  150146. 7, 7, 6, 6, 5, 5, 4, 4, /* 15dB */
  150147. 3, 3, 3, 4, 5, 6, 7, 8, /* 23dB */
  150148. 9,10,11,12,13,14,15, 16, /* 31dB */
  150149. 17,18,19,20,21,22,23, 24, /* 39dB */
  150150. }},
  150151. };
  150152. static double _psy_lowpass_8[3]={3.,4.,4.};
  150153. static int _noise_start_8[2]={
  150154. 64,64,
  150155. };
  150156. static int _noise_part_8[2]={
  150157. 8,8,
  150158. };
  150159. static int _psy_ath_floater_8[3]={
  150160. -100,-100,-105,
  150161. };
  150162. static int _psy_ath_abs_8[3]={
  150163. -130,-130,-140,
  150164. };
  150165. /*** End of inlined file: psych_8.h ***/
  150166. /*** Start of inlined file: residue_8.h ***/
  150167. /***** residue backends *********************************************/
  150168. static static_bookblock _resbook_8s_0={
  150169. {
  150170. {0},{0,0,&_8c0_s_p1_0},{0,0,&_8c0_s_p2_0},{0,0,&_8c0_s_p3_0},
  150171. {0,0,&_8c0_s_p4_0},{0,0,&_8c0_s_p5_0},{0,0,&_8c0_s_p6_0},
  150172. {&_8c0_s_p7_0,&_8c0_s_p7_1},{&_8c0_s_p8_0,&_8c0_s_p8_1},
  150173. {&_8c0_s_p9_0,&_8c0_s_p9_1,&_8c0_s_p9_2}
  150174. }
  150175. };
  150176. static static_bookblock _resbook_8s_1={
  150177. {
  150178. {0},{0,0,&_8c1_s_p1_0},{0,0,&_8c1_s_p2_0},{0,0,&_8c1_s_p3_0},
  150179. {0,0,&_8c1_s_p4_0},{0,0,&_8c1_s_p5_0},{0,0,&_8c1_s_p6_0},
  150180. {&_8c1_s_p7_0,&_8c1_s_p7_1},{&_8c1_s_p8_0,&_8c1_s_p8_1},
  150181. {&_8c1_s_p9_0,&_8c1_s_p9_1,&_8c1_s_p9_2}
  150182. }
  150183. };
  150184. static vorbis_residue_template _res_8s_0[]={
  150185. {2,0, &_residue_44_mid,
  150186. &_huff_book__8c0_s_single,&_huff_book__8c0_s_single,
  150187. &_resbook_8s_0,&_resbook_8s_0},
  150188. };
  150189. static vorbis_residue_template _res_8s_1[]={
  150190. {2,0, &_residue_44_mid,
  150191. &_huff_book__8c1_s_single,&_huff_book__8c1_s_single,
  150192. &_resbook_8s_1,&_resbook_8s_1},
  150193. };
  150194. static vorbis_mapping_template _mapres_template_8_stereo[2]={
  150195. { _map_nominal, _res_8s_0 }, /* 0 */
  150196. { _map_nominal, _res_8s_1 }, /* 1 */
  150197. };
  150198. static static_bookblock _resbook_8u_0={
  150199. {
  150200. {0},
  150201. {0,0,&_8u0__p1_0},
  150202. {0,0,&_8u0__p2_0},
  150203. {0,0,&_8u0__p3_0},
  150204. {0,0,&_8u0__p4_0},
  150205. {0,0,&_8u0__p5_0},
  150206. {&_8u0__p6_0,&_8u0__p6_1},
  150207. {&_8u0__p7_0,&_8u0__p7_1,&_8u0__p7_2}
  150208. }
  150209. };
  150210. static static_bookblock _resbook_8u_1={
  150211. {
  150212. {0},
  150213. {0,0,&_8u1__p1_0},
  150214. {0,0,&_8u1__p2_0},
  150215. {0,0,&_8u1__p3_0},
  150216. {0,0,&_8u1__p4_0},
  150217. {0,0,&_8u1__p5_0},
  150218. {0,0,&_8u1__p6_0},
  150219. {&_8u1__p7_0,&_8u1__p7_1},
  150220. {&_8u1__p8_0,&_8u1__p8_1},
  150221. {&_8u1__p9_0,&_8u1__p9_1,&_8u1__p9_2}
  150222. }
  150223. };
  150224. static vorbis_residue_template _res_8u_0[]={
  150225. {1,0, &_residue_44_low_un,
  150226. &_huff_book__8u0__single,&_huff_book__8u0__single,
  150227. &_resbook_8u_0,&_resbook_8u_0},
  150228. };
  150229. static vorbis_residue_template _res_8u_1[]={
  150230. {1,0, &_residue_44_mid_un,
  150231. &_huff_book__8u1__single,&_huff_book__8u1__single,
  150232. &_resbook_8u_1,&_resbook_8u_1},
  150233. };
  150234. static vorbis_mapping_template _mapres_template_8_uncoupled[2]={
  150235. { _map_nominal_u, _res_8u_0 }, /* 0 */
  150236. { _map_nominal_u, _res_8u_1 }, /* 1 */
  150237. };
  150238. /*** End of inlined file: residue_8.h ***/
  150239. static int blocksize_8[2]={
  150240. 512,512
  150241. };
  150242. static int _floor_mapping_8[2]={
  150243. 6,6,
  150244. };
  150245. static double rate_mapping_8[3]={
  150246. 6000.,9000.,32000.,
  150247. };
  150248. static double rate_mapping_8_uncoupled[3]={
  150249. 8000.,14000.,42000.,
  150250. };
  150251. static double quality_mapping_8[3]={
  150252. -.1,.0,1.
  150253. };
  150254. static double _psy_compand_8_mapping[3]={ 0., 1., 1.};
  150255. static double _global_mapping_8[3]={ 1., 2., 3. };
  150256. ve_setup_data_template ve_setup_8_stereo={
  150257. 2,
  150258. rate_mapping_8,
  150259. quality_mapping_8,
  150260. 2,
  150261. 8000,
  150262. 9000,
  150263. blocksize_8,
  150264. blocksize_8,
  150265. _psy_tone_masteratt_8,
  150266. _psy_tone_0dB,
  150267. _psy_tone_suppress,
  150268. _vp_tonemask_adj_8,
  150269. NULL,
  150270. _vp_tonemask_adj_8,
  150271. _psy_noiseguards_8,
  150272. _psy_noisebias_8,
  150273. _psy_noisebias_8,
  150274. NULL,
  150275. NULL,
  150276. _psy_noise_suppress,
  150277. _psy_compand_8,
  150278. _psy_compand_8_mapping,
  150279. NULL,
  150280. {_noise_start_8,_noise_start_8},
  150281. {_noise_part_8,_noise_part_8},
  150282. _noise_thresh_5only,
  150283. _psy_ath_floater_8,
  150284. _psy_ath_abs_8,
  150285. _psy_lowpass_8,
  150286. _psy_global_44,
  150287. _global_mapping_8,
  150288. _psy_stereo_modes_8,
  150289. _floor_books,
  150290. _floor,
  150291. _floor_mapping_8,
  150292. NULL,
  150293. _mapres_template_8_stereo
  150294. };
  150295. ve_setup_data_template ve_setup_8_uncoupled={
  150296. 2,
  150297. rate_mapping_8_uncoupled,
  150298. quality_mapping_8,
  150299. -1,
  150300. 8000,
  150301. 9000,
  150302. blocksize_8,
  150303. blocksize_8,
  150304. _psy_tone_masteratt_8,
  150305. _psy_tone_0dB,
  150306. _psy_tone_suppress,
  150307. _vp_tonemask_adj_8,
  150308. NULL,
  150309. _vp_tonemask_adj_8,
  150310. _psy_noiseguards_8,
  150311. _psy_noisebias_8,
  150312. _psy_noisebias_8,
  150313. NULL,
  150314. NULL,
  150315. _psy_noise_suppress,
  150316. _psy_compand_8,
  150317. _psy_compand_8_mapping,
  150318. NULL,
  150319. {_noise_start_8,_noise_start_8},
  150320. {_noise_part_8,_noise_part_8},
  150321. _noise_thresh_5only,
  150322. _psy_ath_floater_8,
  150323. _psy_ath_abs_8,
  150324. _psy_lowpass_8,
  150325. _psy_global_44,
  150326. _global_mapping_8,
  150327. _psy_stereo_modes_8,
  150328. _floor_books,
  150329. _floor,
  150330. _floor_mapping_8,
  150331. NULL,
  150332. _mapres_template_8_uncoupled
  150333. };
  150334. /*** End of inlined file: setup_8.h ***/
  150335. /*** Start of inlined file: setup_11.h ***/
  150336. /*** Start of inlined file: psych_11.h ***/
  150337. static double _psy_lowpass_11[3]={4.5,5.5,30.,};
  150338. static att3 _psy_tone_masteratt_11[3]={
  150339. {{ 30, 25, 12}, 0, 0}, /* 0 */
  150340. {{ 30, 25, 12}, 0, 0}, /* 0 */
  150341. {{ 20, 0, -14}, 0, 0}, /* 0 */
  150342. };
  150343. static vp_adjblock _vp_tonemask_adj_11[3]={
  150344. /* adjust for mode zero */
  150345. /* 63 125 250 500 1 2 4 8 16 */
  150346. {{-20,-20,-20,-20,-20,-16,-10, 0, 0, 0, 0,10, 2, 0,99,99,99}}, /* 0 */
  150347. {{-20,-20,-20,-20,-20,-16,-10, 0, 0, 0, 0, 5, 0, 0,99,99,99}}, /* 1 */
  150348. {{-20,-20,-20,-20,-20,-16,-10, 0, 0, 0, 0, 0, 0, 0,99,99,99}}, /* 2 */
  150349. };
  150350. static noise3 _psy_noisebias_11[3]={
  150351. /* 63 125 250 500 1k 2k 4k 8k 16k*/
  150352. {{{-10,-10,-10,-10, -5, -5, -5, 0, 4, 10, 10, 12, 12, 12, 99, 99, 99},
  150353. {-15,-15,-15,-15,-10,-10, -5, 0, 0, 4, 4, 5, 5, 10, 99, 99, 99},
  150354. {-30,-30,-30,-30,-30,-24,-20,-14,-10, -6, -8, -8, -6, -6, 99, 99, 99}}},
  150355. {{{-10,-10,-10,-10, -5, -5, -5, 0, 4, 10, 10, 12, 12, 12, 99, 99, 99},
  150356. {-15,-15,-15,-15,-10,-10, -5, -5, -5, 0, 0, 0, 0, 0, 99, 99, 99},
  150357. {-30,-30,-30,-30,-30,-24,-20,-14,-10, -6, -8, -8, -6, -6, 99, 99, 99}}},
  150358. {{{-15,-15,-15,-15,-15,-12,-10, -8, 0, 2, 4, 4, 5, 5, 99, 99, 99},
  150359. {-30,-30,-30,-30,-26,-22,-20,-14,-12,-12,-10,-10,-10,-10, 99, 99, 99},
  150360. {-30,-30,-30,-30,-26,-26,-26,-26,-26,-26,-26,-26,-26,-24, 99, 99, 99}}},
  150361. };
  150362. static double _noise_thresh_11[3]={ .3,.5,.5 };
  150363. /*** End of inlined file: psych_11.h ***/
  150364. static int blocksize_11[2]={
  150365. 512,512
  150366. };
  150367. static int _floor_mapping_11[2]={
  150368. 6,6,
  150369. };
  150370. static double rate_mapping_11[3]={
  150371. 8000.,13000.,44000.,
  150372. };
  150373. static double rate_mapping_11_uncoupled[3]={
  150374. 12000.,20000.,50000.,
  150375. };
  150376. static double quality_mapping_11[3]={
  150377. -.1,.0,1.
  150378. };
  150379. ve_setup_data_template ve_setup_11_stereo={
  150380. 2,
  150381. rate_mapping_11,
  150382. quality_mapping_11,
  150383. 2,
  150384. 9000,
  150385. 15000,
  150386. blocksize_11,
  150387. blocksize_11,
  150388. _psy_tone_masteratt_11,
  150389. _psy_tone_0dB,
  150390. _psy_tone_suppress,
  150391. _vp_tonemask_adj_11,
  150392. NULL,
  150393. _vp_tonemask_adj_11,
  150394. _psy_noiseguards_8,
  150395. _psy_noisebias_11,
  150396. _psy_noisebias_11,
  150397. NULL,
  150398. NULL,
  150399. _psy_noise_suppress,
  150400. _psy_compand_8,
  150401. _psy_compand_8_mapping,
  150402. NULL,
  150403. {_noise_start_8,_noise_start_8},
  150404. {_noise_part_8,_noise_part_8},
  150405. _noise_thresh_11,
  150406. _psy_ath_floater_8,
  150407. _psy_ath_abs_8,
  150408. _psy_lowpass_11,
  150409. _psy_global_44,
  150410. _global_mapping_8,
  150411. _psy_stereo_modes_8,
  150412. _floor_books,
  150413. _floor,
  150414. _floor_mapping_11,
  150415. NULL,
  150416. _mapres_template_8_stereo
  150417. };
  150418. ve_setup_data_template ve_setup_11_uncoupled={
  150419. 2,
  150420. rate_mapping_11_uncoupled,
  150421. quality_mapping_11,
  150422. -1,
  150423. 9000,
  150424. 15000,
  150425. blocksize_11,
  150426. blocksize_11,
  150427. _psy_tone_masteratt_11,
  150428. _psy_tone_0dB,
  150429. _psy_tone_suppress,
  150430. _vp_tonemask_adj_11,
  150431. NULL,
  150432. _vp_tonemask_adj_11,
  150433. _psy_noiseguards_8,
  150434. _psy_noisebias_11,
  150435. _psy_noisebias_11,
  150436. NULL,
  150437. NULL,
  150438. _psy_noise_suppress,
  150439. _psy_compand_8,
  150440. _psy_compand_8_mapping,
  150441. NULL,
  150442. {_noise_start_8,_noise_start_8},
  150443. {_noise_part_8,_noise_part_8},
  150444. _noise_thresh_11,
  150445. _psy_ath_floater_8,
  150446. _psy_ath_abs_8,
  150447. _psy_lowpass_11,
  150448. _psy_global_44,
  150449. _global_mapping_8,
  150450. _psy_stereo_modes_8,
  150451. _floor_books,
  150452. _floor,
  150453. _floor_mapping_11,
  150454. NULL,
  150455. _mapres_template_8_uncoupled
  150456. };
  150457. /*** End of inlined file: setup_11.h ***/
  150458. /*** Start of inlined file: setup_16.h ***/
  150459. /*** Start of inlined file: psych_16.h ***/
  150460. /* stereo mode by base quality level */
  150461. static adj_stereo _psy_stereo_modes_16[4]={
  150462. /* 0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 */
  150463. {{ 4, 4, 4, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3},
  150464. { 6, 5, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4},
  150465. { 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 3, 3, 4, 4},
  150466. { 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99}},
  150467. {{ 4, 4, 4, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3},
  150468. { 6, 5, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4},
  150469. { 2, 2, 2, 2, 2, 2, 2, 2, 2, 3, 4, 4, 4, 4, 4},
  150470. { 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99}},
  150471. {{ 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3},
  150472. { 5, 4, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3},
  150473. { 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4},
  150474. { 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99}},
  150475. {{ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0},
  150476. { 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0},
  150477. { 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8},
  150478. { 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99}},
  150479. };
  150480. static double _psy_lowpass_16[4]={6.5,8,30.,99.};
  150481. static att3 _psy_tone_masteratt_16[4]={
  150482. {{ 30, 25, 12}, 0, 0}, /* 0 */
  150483. {{ 25, 22, 12}, 0, 0}, /* 0 */
  150484. {{ 20, 12, 0}, 0, 0}, /* 0 */
  150485. {{ 15, 0, -14}, 0, 0}, /* 0 */
  150486. };
  150487. static vp_adjblock _vp_tonemask_adj_16[4]={
  150488. /* adjust for mode zero */
  150489. /* 63 125 250 500 1 2 4 8 16 */
  150490. {{-20,-20,-20,-20,-20,-16,-10, 0, 0, 0, 0,10, 0, 0, 0, 0, 0}}, /* 0 */
  150491. {{-20,-20,-20,-20,-20,-16,-10, 0, 0, 0, 0,10, 0, 0, 0, 0, 0}}, /* 1 */
  150492. {{-20,-20,-20,-20,-20,-16,-10, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0}}, /* 2 */
  150493. {{-30,-30,-30,-30,-30,-26,-20,-10, -5, 0, 0, 0, 0, 0, 0, 0, 0}}, /* 2 */
  150494. };
  150495. static noise3 _psy_noisebias_16_short[4]={
  150496. /* 63 125 250 500 1k 2k 4k 8k 16k*/
  150497. {{{-15,-15,-15,-15,-15,-10,-10,-5, 4, 10, 10, 10, 10, 12, 12, 14, 20},
  150498. {-15,-15,-15,-15,-15,-10,-10, -5, 0, 0, 4, 5, 5, 6, 8, 8, 15},
  150499. {-30,-30,-30,-30,-30,-24,-20,-14,-10, -6, -8, -8, -6, -6, -6, -6, -6}}},
  150500. {{{-15,-15,-15,-15,-15,-10,-10,-5, 4, 6, 6, 6, 6, 8, 10, 12, 20},
  150501. {-15,-15,-15,-15,-15,-15,-15,-10, -5, -5, -5, 4, 5, 6, 8, 8, 15},
  150502. {-30,-30,-30,-30,-30,-24,-20,-14,-10,-10,-10,-10,-10,-10,-10,-10,-10}}},
  150503. {{{-15,-15,-15,-15,-15,-12,-10, -8, 0, 2, 4, 4, 5, 5, 5, 8, 12},
  150504. {-20,-20,-20,-20,-16,-12,-20,-14,-10,-10, -8, 0, 0, 0, 0, 2, 5},
  150505. {-30,-30,-30,-30,-26,-26,-26,-26,-26,-26,-26,-26,-26,-24,-20,-20,-20}}},
  150506. {{{-15,-15,-15,-15,-15,-12,-10, -8, -5, -5, -5, -5, -5, 0, 0, 0, 6},
  150507. {-30,-30,-30,-30,-26,-22,-20,-14,-12,-12,-10,-10,-10,-10,-10,-10, -6},
  150508. {-30,-30,-30,-30,-26,-26,-26,-26,-26,-26,-26,-26,-26,-24,-20,-20,-20}}},
  150509. };
  150510. static noise3 _psy_noisebias_16_impulse[4]={
  150511. /* 63 125 250 500 1k 2k 4k 8k 16k*/
  150512. {{{-15,-15,-15,-15,-15,-10,-10,-5, 4, 10, 10, 10, 10, 12, 12, 14, 20},
  150513. {-15,-15,-15,-15,-15,-10,-10, -5, 0, 0, 4, 5, 5, 6, 8, 8, 15},
  150514. {-30,-30,-30,-30,-30,-24,-20,-14,-10, -6, -8, -8, -6, -6, -6, -6, -6}}},
  150515. {{{-15,-15,-15,-15,-15,-10,-10,-5, 4, 4, 4, 4, 5, 5, 6, 8, 15},
  150516. {-15,-15,-15,-15,-15,-15,-15,-10, -5, -5, -5, 0, 0, 0, 0, 4, 10},
  150517. {-30,-30,-30,-30,-30,-24,-20,-14,-10,-10,-10,-10,-10,-10,-10,-10,-10}}},
  150518. {{{-15,-15,-15,-15,-15,-12,-10, -8, 0, 0, 0, 0, 0, 0, 0, 4, 10},
  150519. {-20,-20,-20,-20,-16,-12,-20,-14,-10,-10,-10,-10,-10,-10,-10, -7, -5},
  150520. {-30,-30,-30,-30,-26,-26,-26,-26,-26,-26,-26,-26,-26,-24,-20,-20,-20}}},
  150521. {{{-15,-15,-15,-15,-15,-12,-10, -8, -5, -5, -5, -5, -5, 0, 0, 0, 6},
  150522. {-30,-30,-30,-30,-26,-22,-20,-18,-18,-18,-20,-20,-20,-20,-20,-20,-16},
  150523. {-30,-30,-30,-30,-26,-26,-26,-26,-26,-26,-26,-26,-26,-24,-20,-20,-20}}},
  150524. };
  150525. static noise3 _psy_noisebias_16[4]={
  150526. /* 63 125 250 500 1k 2k 4k 8k 16k*/
  150527. {{{-10,-10,-10,-10, -5, -5, -5, 0, 4, 6, 8, 8, 10, 10, 10, 14, 20},
  150528. {-10,-10,-10,-10,-10, -5, -2, -2, 0, 0, 0, 4, 5, 6, 8, 8, 15},
  150529. {-30,-30,-30,-30,-30,-24,-20,-14,-10, -6, -8, -8, -6, -6, -6, -6, -6}}},
  150530. {{{-10,-10,-10,-10, -5, -5, -5, 0, 4, 6, 6, 6, 6, 8, 10, 12, 20},
  150531. {-15,-15,-15,-15,-15,-10, -5, -5, 0, 0, 0, 4, 5, 6, 8, 8, 15},
  150532. {-30,-30,-30,-30,-30,-24,-20,-14,-10, -6, -8, -8, -6, -6, -6, -6, -6}}},
  150533. {{{-15,-15,-15,-15,-15,-12,-10, -8, 0, 2, 4, 4, 5, 5, 5, 8, 12},
  150534. {-20,-20,-20,-20,-16,-12,-20,-10, -5, -5, 0, 0, 0, 0, 0, 2, 5},
  150535. {-30,-30,-30,-30,-26,-26,-26,-26,-26,-26,-26,-26,-26,-24,-20,-20,-20}}},
  150536. {{{-15,-15,-15,-15,-15,-12,-10, -8, -5, -5, -5, -5, -5, 0, 0, 0, 6},
  150537. {-30,-30,-30,-30,-26,-22,-20,-14,-12,-12,-10,-10,-10,-10,-10,-10, -6},
  150538. {-30,-30,-30,-30,-26,-26,-26,-26,-26,-26,-26,-26,-26,-24,-20,-20,-20}}},
  150539. };
  150540. static double _noise_thresh_16[4]={ .3,.5,.5,.5 };
  150541. static int _noise_start_16[3]={ 256,256,9999 };
  150542. static int _noise_part_16[4]={ 8,8,8,8 };
  150543. static int _psy_ath_floater_16[4]={
  150544. -100,-100,-100,-105,
  150545. };
  150546. static int _psy_ath_abs_16[4]={
  150547. -130,-130,-130,-140,
  150548. };
  150549. /*** End of inlined file: psych_16.h ***/
  150550. /*** Start of inlined file: residue_16.h ***/
  150551. /***** residue backends *********************************************/
  150552. static static_bookblock _resbook_16s_0={
  150553. {
  150554. {0},
  150555. {0,0,&_16c0_s_p1_0},
  150556. {0,0,&_16c0_s_p2_0},
  150557. {0,0,&_16c0_s_p3_0},
  150558. {0,0,&_16c0_s_p4_0},
  150559. {0,0,&_16c0_s_p5_0},
  150560. {0,0,&_16c0_s_p6_0},
  150561. {&_16c0_s_p7_0,&_16c0_s_p7_1},
  150562. {&_16c0_s_p8_0,&_16c0_s_p8_1},
  150563. {&_16c0_s_p9_0,&_16c0_s_p9_1,&_16c0_s_p9_2}
  150564. }
  150565. };
  150566. static static_bookblock _resbook_16s_1={
  150567. {
  150568. {0},
  150569. {0,0,&_16c1_s_p1_0},
  150570. {0,0,&_16c1_s_p2_0},
  150571. {0,0,&_16c1_s_p3_0},
  150572. {0,0,&_16c1_s_p4_0},
  150573. {0,0,&_16c1_s_p5_0},
  150574. {0,0,&_16c1_s_p6_0},
  150575. {&_16c1_s_p7_0,&_16c1_s_p7_1},
  150576. {&_16c1_s_p8_0,&_16c1_s_p8_1},
  150577. {&_16c1_s_p9_0,&_16c1_s_p9_1,&_16c1_s_p9_2}
  150578. }
  150579. };
  150580. static static_bookblock _resbook_16s_2={
  150581. {
  150582. {0},
  150583. {0,0,&_16c2_s_p1_0},
  150584. {0,0,&_16c2_s_p2_0},
  150585. {0,0,&_16c2_s_p3_0},
  150586. {0,0,&_16c2_s_p4_0},
  150587. {&_16c2_s_p5_0,&_16c2_s_p5_1},
  150588. {&_16c2_s_p6_0,&_16c2_s_p6_1},
  150589. {&_16c2_s_p7_0,&_16c2_s_p7_1},
  150590. {&_16c2_s_p8_0,&_16c2_s_p8_1},
  150591. {&_16c2_s_p9_0,&_16c2_s_p9_1,&_16c2_s_p9_2}
  150592. }
  150593. };
  150594. static vorbis_residue_template _res_16s_0[]={
  150595. {2,0, &_residue_44_mid,
  150596. &_huff_book__16c0_s_single,&_huff_book__16c0_s_single,
  150597. &_resbook_16s_0,&_resbook_16s_0},
  150598. };
  150599. static vorbis_residue_template _res_16s_1[]={
  150600. {2,0, &_residue_44_mid,
  150601. &_huff_book__16c1_s_short,&_huff_book__16c1_s_short,
  150602. &_resbook_16s_1,&_resbook_16s_1},
  150603. {2,0, &_residue_44_mid,
  150604. &_huff_book__16c1_s_long,&_huff_book__16c1_s_long,
  150605. &_resbook_16s_1,&_resbook_16s_1}
  150606. };
  150607. static vorbis_residue_template _res_16s_2[]={
  150608. {2,0, &_residue_44_high,
  150609. &_huff_book__16c2_s_short,&_huff_book__16c2_s_short,
  150610. &_resbook_16s_2,&_resbook_16s_2},
  150611. {2,0, &_residue_44_high,
  150612. &_huff_book__16c2_s_long,&_huff_book__16c2_s_long,
  150613. &_resbook_16s_2,&_resbook_16s_2}
  150614. };
  150615. static vorbis_mapping_template _mapres_template_16_stereo[3]={
  150616. { _map_nominal, _res_16s_0 }, /* 0 */
  150617. { _map_nominal, _res_16s_1 }, /* 1 */
  150618. { _map_nominal, _res_16s_2 }, /* 2 */
  150619. };
  150620. static static_bookblock _resbook_16u_0={
  150621. {
  150622. {0},
  150623. {0,0,&_16u0__p1_0},
  150624. {0,0,&_16u0__p2_0},
  150625. {0,0,&_16u0__p3_0},
  150626. {0,0,&_16u0__p4_0},
  150627. {0,0,&_16u0__p5_0},
  150628. {&_16u0__p6_0,&_16u0__p6_1},
  150629. {&_16u0__p7_0,&_16u0__p7_1,&_16u0__p7_2}
  150630. }
  150631. };
  150632. static static_bookblock _resbook_16u_1={
  150633. {
  150634. {0},
  150635. {0,0,&_16u1__p1_0},
  150636. {0,0,&_16u1__p2_0},
  150637. {0,0,&_16u1__p3_0},
  150638. {0,0,&_16u1__p4_0},
  150639. {0,0,&_16u1__p5_0},
  150640. {0,0,&_16u1__p6_0},
  150641. {&_16u1__p7_0,&_16u1__p7_1},
  150642. {&_16u1__p8_0,&_16u1__p8_1},
  150643. {&_16u1__p9_0,&_16u1__p9_1,&_16u1__p9_2}
  150644. }
  150645. };
  150646. static static_bookblock _resbook_16u_2={
  150647. {
  150648. {0},
  150649. {0,0,&_16u2_p1_0},
  150650. {0,0,&_16u2_p2_0},
  150651. {0,0,&_16u2_p3_0},
  150652. {0,0,&_16u2_p4_0},
  150653. {&_16u2_p5_0,&_16u2_p5_1},
  150654. {&_16u2_p6_0,&_16u2_p6_1},
  150655. {&_16u2_p7_0,&_16u2_p7_1},
  150656. {&_16u2_p8_0,&_16u2_p8_1},
  150657. {&_16u2_p9_0,&_16u2_p9_1,&_16u2_p9_2}
  150658. }
  150659. };
  150660. static vorbis_residue_template _res_16u_0[]={
  150661. {1,0, &_residue_44_low_un,
  150662. &_huff_book__16u0__single,&_huff_book__16u0__single,
  150663. &_resbook_16u_0,&_resbook_16u_0},
  150664. };
  150665. static vorbis_residue_template _res_16u_1[]={
  150666. {1,0, &_residue_44_mid_un,
  150667. &_huff_book__16u1__short,&_huff_book__16u1__short,
  150668. &_resbook_16u_1,&_resbook_16u_1},
  150669. {1,0, &_residue_44_mid_un,
  150670. &_huff_book__16u1__long,&_huff_book__16u1__long,
  150671. &_resbook_16u_1,&_resbook_16u_1}
  150672. };
  150673. static vorbis_residue_template _res_16u_2[]={
  150674. {1,0, &_residue_44_hi_un,
  150675. &_huff_book__16u2__short,&_huff_book__16u2__short,
  150676. &_resbook_16u_2,&_resbook_16u_2},
  150677. {1,0, &_residue_44_hi_un,
  150678. &_huff_book__16u2__long,&_huff_book__16u2__long,
  150679. &_resbook_16u_2,&_resbook_16u_2}
  150680. };
  150681. static vorbis_mapping_template _mapres_template_16_uncoupled[3]={
  150682. { _map_nominal_u, _res_16u_0 }, /* 0 */
  150683. { _map_nominal_u, _res_16u_1 }, /* 1 */
  150684. { _map_nominal_u, _res_16u_2 }, /* 2 */
  150685. };
  150686. /*** End of inlined file: residue_16.h ***/
  150687. static int blocksize_16_short[3]={
  150688. 1024,512,512
  150689. };
  150690. static int blocksize_16_long[3]={
  150691. 1024,1024,1024
  150692. };
  150693. static int _floor_mapping_16_short[3]={
  150694. 9,3,3
  150695. };
  150696. static int _floor_mapping_16[3]={
  150697. 9,9,9
  150698. };
  150699. static double rate_mapping_16[4]={
  150700. 12000.,20000.,44000.,86000.
  150701. };
  150702. static double rate_mapping_16_uncoupled[4]={
  150703. 16000.,28000.,64000.,100000.
  150704. };
  150705. static double _global_mapping_16[4]={ 1., 2., 3., 4. };
  150706. static double quality_mapping_16[4]={ -.1,.05,.5,1. };
  150707. static double _psy_compand_16_mapping[4]={ 0., .8, 1., 1.};
  150708. ve_setup_data_template ve_setup_16_stereo={
  150709. 3,
  150710. rate_mapping_16,
  150711. quality_mapping_16,
  150712. 2,
  150713. 15000,
  150714. 19000,
  150715. blocksize_16_short,
  150716. blocksize_16_long,
  150717. _psy_tone_masteratt_16,
  150718. _psy_tone_0dB,
  150719. _psy_tone_suppress,
  150720. _vp_tonemask_adj_16,
  150721. _vp_tonemask_adj_16,
  150722. _vp_tonemask_adj_16,
  150723. _psy_noiseguards_8,
  150724. _psy_noisebias_16_impulse,
  150725. _psy_noisebias_16_short,
  150726. _psy_noisebias_16_short,
  150727. _psy_noisebias_16,
  150728. _psy_noise_suppress,
  150729. _psy_compand_8,
  150730. _psy_compand_16_mapping,
  150731. _psy_compand_16_mapping,
  150732. {_noise_start_16,_noise_start_16},
  150733. { _noise_part_16, _noise_part_16},
  150734. _noise_thresh_16,
  150735. _psy_ath_floater_16,
  150736. _psy_ath_abs_16,
  150737. _psy_lowpass_16,
  150738. _psy_global_44,
  150739. _global_mapping_16,
  150740. _psy_stereo_modes_16,
  150741. _floor_books,
  150742. _floor,
  150743. _floor_mapping_16_short,
  150744. _floor_mapping_16,
  150745. _mapres_template_16_stereo
  150746. };
  150747. ve_setup_data_template ve_setup_16_uncoupled={
  150748. 3,
  150749. rate_mapping_16_uncoupled,
  150750. quality_mapping_16,
  150751. -1,
  150752. 15000,
  150753. 19000,
  150754. blocksize_16_short,
  150755. blocksize_16_long,
  150756. _psy_tone_masteratt_16,
  150757. _psy_tone_0dB,
  150758. _psy_tone_suppress,
  150759. _vp_tonemask_adj_16,
  150760. _vp_tonemask_adj_16,
  150761. _vp_tonemask_adj_16,
  150762. _psy_noiseguards_8,
  150763. _psy_noisebias_16_impulse,
  150764. _psy_noisebias_16_short,
  150765. _psy_noisebias_16_short,
  150766. _psy_noisebias_16,
  150767. _psy_noise_suppress,
  150768. _psy_compand_8,
  150769. _psy_compand_16_mapping,
  150770. _psy_compand_16_mapping,
  150771. {_noise_start_16,_noise_start_16},
  150772. { _noise_part_16, _noise_part_16},
  150773. _noise_thresh_16,
  150774. _psy_ath_floater_16,
  150775. _psy_ath_abs_16,
  150776. _psy_lowpass_16,
  150777. _psy_global_44,
  150778. _global_mapping_16,
  150779. _psy_stereo_modes_16,
  150780. _floor_books,
  150781. _floor,
  150782. _floor_mapping_16_short,
  150783. _floor_mapping_16,
  150784. _mapres_template_16_uncoupled
  150785. };
  150786. /*** End of inlined file: setup_16.h ***/
  150787. /*** Start of inlined file: setup_22.h ***/
  150788. static double rate_mapping_22[4]={
  150789. 15000.,20000.,44000.,86000.
  150790. };
  150791. static double rate_mapping_22_uncoupled[4]={
  150792. 16000.,28000.,50000.,90000.
  150793. };
  150794. static double _psy_lowpass_22[4]={9.5,11.,30.,99.};
  150795. ve_setup_data_template ve_setup_22_stereo={
  150796. 3,
  150797. rate_mapping_22,
  150798. quality_mapping_16,
  150799. 2,
  150800. 19000,
  150801. 26000,
  150802. blocksize_16_short,
  150803. blocksize_16_long,
  150804. _psy_tone_masteratt_16,
  150805. _psy_tone_0dB,
  150806. _psy_tone_suppress,
  150807. _vp_tonemask_adj_16,
  150808. _vp_tonemask_adj_16,
  150809. _vp_tonemask_adj_16,
  150810. _psy_noiseguards_8,
  150811. _psy_noisebias_16_impulse,
  150812. _psy_noisebias_16_short,
  150813. _psy_noisebias_16_short,
  150814. _psy_noisebias_16,
  150815. _psy_noise_suppress,
  150816. _psy_compand_8,
  150817. _psy_compand_8_mapping,
  150818. _psy_compand_8_mapping,
  150819. {_noise_start_16,_noise_start_16},
  150820. { _noise_part_16, _noise_part_16},
  150821. _noise_thresh_16,
  150822. _psy_ath_floater_16,
  150823. _psy_ath_abs_16,
  150824. _psy_lowpass_22,
  150825. _psy_global_44,
  150826. _global_mapping_16,
  150827. _psy_stereo_modes_16,
  150828. _floor_books,
  150829. _floor,
  150830. _floor_mapping_16_short,
  150831. _floor_mapping_16,
  150832. _mapres_template_16_stereo
  150833. };
  150834. ve_setup_data_template ve_setup_22_uncoupled={
  150835. 3,
  150836. rate_mapping_22_uncoupled,
  150837. quality_mapping_16,
  150838. -1,
  150839. 19000,
  150840. 26000,
  150841. blocksize_16_short,
  150842. blocksize_16_long,
  150843. _psy_tone_masteratt_16,
  150844. _psy_tone_0dB,
  150845. _psy_tone_suppress,
  150846. _vp_tonemask_adj_16,
  150847. _vp_tonemask_adj_16,
  150848. _vp_tonemask_adj_16,
  150849. _psy_noiseguards_8,
  150850. _psy_noisebias_16_impulse,
  150851. _psy_noisebias_16_short,
  150852. _psy_noisebias_16_short,
  150853. _psy_noisebias_16,
  150854. _psy_noise_suppress,
  150855. _psy_compand_8,
  150856. _psy_compand_8_mapping,
  150857. _psy_compand_8_mapping,
  150858. {_noise_start_16,_noise_start_16},
  150859. { _noise_part_16, _noise_part_16},
  150860. _noise_thresh_16,
  150861. _psy_ath_floater_16,
  150862. _psy_ath_abs_16,
  150863. _psy_lowpass_22,
  150864. _psy_global_44,
  150865. _global_mapping_16,
  150866. _psy_stereo_modes_16,
  150867. _floor_books,
  150868. _floor,
  150869. _floor_mapping_16_short,
  150870. _floor_mapping_16,
  150871. _mapres_template_16_uncoupled
  150872. };
  150873. /*** End of inlined file: setup_22.h ***/
  150874. /*** Start of inlined file: setup_X.h ***/
  150875. static double rate_mapping_X[12]={
  150876. -1.,-1.,-1.,-1.,-1.,-1.,
  150877. -1.,-1.,-1.,-1.,-1.,-1.
  150878. };
  150879. ve_setup_data_template ve_setup_X_stereo={
  150880. 11,
  150881. rate_mapping_X,
  150882. quality_mapping_44,
  150883. 2,
  150884. 50000,
  150885. 200000,
  150886. blocksize_short_44,
  150887. blocksize_long_44,
  150888. _psy_tone_masteratt_44,
  150889. _psy_tone_0dB,
  150890. _psy_tone_suppress,
  150891. _vp_tonemask_adj_otherblock,
  150892. _vp_tonemask_adj_longblock,
  150893. _vp_tonemask_adj_otherblock,
  150894. _psy_noiseguards_44,
  150895. _psy_noisebias_impulse,
  150896. _psy_noisebias_padding,
  150897. _psy_noisebias_trans,
  150898. _psy_noisebias_long,
  150899. _psy_noise_suppress,
  150900. _psy_compand_44,
  150901. _psy_compand_short_mapping,
  150902. _psy_compand_long_mapping,
  150903. {_noise_start_short_44,_noise_start_long_44},
  150904. {_noise_part_short_44,_noise_part_long_44},
  150905. _noise_thresh_44,
  150906. _psy_ath_floater,
  150907. _psy_ath_abs,
  150908. _psy_lowpass_44,
  150909. _psy_global_44,
  150910. _global_mapping_44,
  150911. _psy_stereo_modes_44,
  150912. _floor_books,
  150913. _floor,
  150914. _floor_short_mapping_44,
  150915. _floor_long_mapping_44,
  150916. _mapres_template_44_stereo
  150917. };
  150918. ve_setup_data_template ve_setup_X_uncoupled={
  150919. 11,
  150920. rate_mapping_X,
  150921. quality_mapping_44,
  150922. -1,
  150923. 50000,
  150924. 200000,
  150925. blocksize_short_44,
  150926. blocksize_long_44,
  150927. _psy_tone_masteratt_44,
  150928. _psy_tone_0dB,
  150929. _psy_tone_suppress,
  150930. _vp_tonemask_adj_otherblock,
  150931. _vp_tonemask_adj_longblock,
  150932. _vp_tonemask_adj_otherblock,
  150933. _psy_noiseguards_44,
  150934. _psy_noisebias_impulse,
  150935. _psy_noisebias_padding,
  150936. _psy_noisebias_trans,
  150937. _psy_noisebias_long,
  150938. _psy_noise_suppress,
  150939. _psy_compand_44,
  150940. _psy_compand_short_mapping,
  150941. _psy_compand_long_mapping,
  150942. {_noise_start_short_44,_noise_start_long_44},
  150943. {_noise_part_short_44,_noise_part_long_44},
  150944. _noise_thresh_44,
  150945. _psy_ath_floater,
  150946. _psy_ath_abs,
  150947. _psy_lowpass_44,
  150948. _psy_global_44,
  150949. _global_mapping_44,
  150950. NULL,
  150951. _floor_books,
  150952. _floor,
  150953. _floor_short_mapping_44,
  150954. _floor_long_mapping_44,
  150955. _mapres_template_44_uncoupled
  150956. };
  150957. ve_setup_data_template ve_setup_XX_stereo={
  150958. 2,
  150959. rate_mapping_X,
  150960. quality_mapping_8,
  150961. 2,
  150962. 0,
  150963. 8000,
  150964. blocksize_8,
  150965. blocksize_8,
  150966. _psy_tone_masteratt_8,
  150967. _psy_tone_0dB,
  150968. _psy_tone_suppress,
  150969. _vp_tonemask_adj_8,
  150970. NULL,
  150971. _vp_tonemask_adj_8,
  150972. _psy_noiseguards_8,
  150973. _psy_noisebias_8,
  150974. _psy_noisebias_8,
  150975. NULL,
  150976. NULL,
  150977. _psy_noise_suppress,
  150978. _psy_compand_8,
  150979. _psy_compand_8_mapping,
  150980. NULL,
  150981. {_noise_start_8,_noise_start_8},
  150982. {_noise_part_8,_noise_part_8},
  150983. _noise_thresh_5only,
  150984. _psy_ath_floater_8,
  150985. _psy_ath_abs_8,
  150986. _psy_lowpass_8,
  150987. _psy_global_44,
  150988. _global_mapping_8,
  150989. _psy_stereo_modes_8,
  150990. _floor_books,
  150991. _floor,
  150992. _floor_mapping_8,
  150993. NULL,
  150994. _mapres_template_8_stereo
  150995. };
  150996. ve_setup_data_template ve_setup_XX_uncoupled={
  150997. 2,
  150998. rate_mapping_X,
  150999. quality_mapping_8,
  151000. -1,
  151001. 0,
  151002. 8000,
  151003. blocksize_8,
  151004. blocksize_8,
  151005. _psy_tone_masteratt_8,
  151006. _psy_tone_0dB,
  151007. _psy_tone_suppress,
  151008. _vp_tonemask_adj_8,
  151009. NULL,
  151010. _vp_tonemask_adj_8,
  151011. _psy_noiseguards_8,
  151012. _psy_noisebias_8,
  151013. _psy_noisebias_8,
  151014. NULL,
  151015. NULL,
  151016. _psy_noise_suppress,
  151017. _psy_compand_8,
  151018. _psy_compand_8_mapping,
  151019. NULL,
  151020. {_noise_start_8,_noise_start_8},
  151021. {_noise_part_8,_noise_part_8},
  151022. _noise_thresh_5only,
  151023. _psy_ath_floater_8,
  151024. _psy_ath_abs_8,
  151025. _psy_lowpass_8,
  151026. _psy_global_44,
  151027. _global_mapping_8,
  151028. _psy_stereo_modes_8,
  151029. _floor_books,
  151030. _floor,
  151031. _floor_mapping_8,
  151032. NULL,
  151033. _mapres_template_8_uncoupled
  151034. };
  151035. /*** End of inlined file: setup_X.h ***/
  151036. static ve_setup_data_template *setup_list[]={
  151037. &ve_setup_44_stereo,
  151038. &ve_setup_44_uncoupled,
  151039. &ve_setup_32_stereo,
  151040. &ve_setup_32_uncoupled,
  151041. &ve_setup_22_stereo,
  151042. &ve_setup_22_uncoupled,
  151043. &ve_setup_16_stereo,
  151044. &ve_setup_16_uncoupled,
  151045. &ve_setup_11_stereo,
  151046. &ve_setup_11_uncoupled,
  151047. &ve_setup_8_stereo,
  151048. &ve_setup_8_uncoupled,
  151049. &ve_setup_X_stereo,
  151050. &ve_setup_X_uncoupled,
  151051. &ve_setup_XX_stereo,
  151052. &ve_setup_XX_uncoupled,
  151053. 0
  151054. };
  151055. static int vorbis_encode_toplevel_setup(vorbis_info *vi,int ch,long rate){
  151056. if(vi && vi->codec_setup){
  151057. vi->version=0;
  151058. vi->channels=ch;
  151059. vi->rate=rate;
  151060. return(0);
  151061. }
  151062. return(OV_EINVAL);
  151063. }
  151064. static void vorbis_encode_floor_setup(vorbis_info *vi,double s,int block,
  151065. static_codebook ***books,
  151066. vorbis_info_floor1 *in,
  151067. int *x){
  151068. int i,k,is=s;
  151069. vorbis_info_floor1 *f=(vorbis_info_floor1*) _ogg_calloc(1,sizeof(*f));
  151070. codec_setup_info *ci=(codec_setup_info*)vi->codec_setup;
  151071. memcpy(f,in+x[is],sizeof(*f));
  151072. /* fill in the lowpass field, even if it's temporary */
  151073. f->n=ci->blocksizes[block]>>1;
  151074. /* books */
  151075. {
  151076. int partitions=f->partitions;
  151077. int maxclass=-1;
  151078. int maxbook=-1;
  151079. for(i=0;i<partitions;i++)
  151080. if(f->partitionclass[i]>maxclass)maxclass=f->partitionclass[i];
  151081. for(i=0;i<=maxclass;i++){
  151082. if(f->class_book[i]>maxbook)maxbook=f->class_book[i];
  151083. f->class_book[i]+=ci->books;
  151084. for(k=0;k<(1<<f->class_subs[i]);k++){
  151085. if(f->class_subbook[i][k]>maxbook)maxbook=f->class_subbook[i][k];
  151086. if(f->class_subbook[i][k]>=0)f->class_subbook[i][k]+=ci->books;
  151087. }
  151088. }
  151089. for(i=0;i<=maxbook;i++)
  151090. ci->book_param[ci->books++]=books[x[is]][i];
  151091. }
  151092. /* for now, we're only using floor 1 */
  151093. ci->floor_type[ci->floors]=1;
  151094. ci->floor_param[ci->floors]=f;
  151095. ci->floors++;
  151096. return;
  151097. }
  151098. static void vorbis_encode_global_psych_setup(vorbis_info *vi,double s,
  151099. vorbis_info_psy_global *in,
  151100. double *x){
  151101. int i,is=s;
  151102. double ds=s-is;
  151103. codec_setup_info *ci=(codec_setup_info*)vi->codec_setup;
  151104. vorbis_info_psy_global *g=&ci->psy_g_param;
  151105. memcpy(g,in+(int)x[is],sizeof(*g));
  151106. ds=x[is]*(1.-ds)+x[is+1]*ds;
  151107. is=(int)ds;
  151108. ds-=is;
  151109. if(ds==0 && is>0){
  151110. is--;
  151111. ds=1.;
  151112. }
  151113. /* interpolate the trigger threshholds */
  151114. for(i=0;i<4;i++){
  151115. g->preecho_thresh[i]=in[is].preecho_thresh[i]*(1.-ds)+in[is+1].preecho_thresh[i]*ds;
  151116. g->postecho_thresh[i]=in[is].postecho_thresh[i]*(1.-ds)+in[is+1].postecho_thresh[i]*ds;
  151117. }
  151118. g->ampmax_att_per_sec=ci->hi.amplitude_track_dBpersec;
  151119. return;
  151120. }
  151121. static void vorbis_encode_global_stereo(vorbis_info *vi,
  151122. highlevel_encode_setup *hi,
  151123. adj_stereo *p){
  151124. float s=hi->stereo_point_setting;
  151125. int i,is=s;
  151126. double ds=s-is;
  151127. codec_setup_info *ci=(codec_setup_info*)vi->codec_setup;
  151128. vorbis_info_psy_global *g=&ci->psy_g_param;
  151129. if(p){
  151130. memcpy(g->coupling_prepointamp,p[is].pre,sizeof(*p[is].pre)*PACKETBLOBS);
  151131. memcpy(g->coupling_postpointamp,p[is].post,sizeof(*p[is].post)*PACKETBLOBS);
  151132. if(hi->managed){
  151133. /* interpolate the kHz threshholds */
  151134. for(i=0;i<PACKETBLOBS;i++){
  151135. float kHz=p[is].kHz[i]*(1.-ds)+p[is+1].kHz[i]*ds;
  151136. g->coupling_pointlimit[0][i]=kHz*1000./vi->rate*ci->blocksizes[0];
  151137. g->coupling_pointlimit[1][i]=kHz*1000./vi->rate*ci->blocksizes[1];
  151138. g->coupling_pkHz[i]=kHz;
  151139. kHz=p[is].lowpasskHz[i]*(1.-ds)+p[is+1].lowpasskHz[i]*ds;
  151140. g->sliding_lowpass[0][i]=kHz*1000./vi->rate*ci->blocksizes[0];
  151141. g->sliding_lowpass[1][i]=kHz*1000./vi->rate*ci->blocksizes[1];
  151142. }
  151143. }else{
  151144. float kHz=p[is].kHz[PACKETBLOBS/2]*(1.-ds)+p[is+1].kHz[PACKETBLOBS/2]*ds;
  151145. for(i=0;i<PACKETBLOBS;i++){
  151146. g->coupling_pointlimit[0][i]=kHz*1000./vi->rate*ci->blocksizes[0];
  151147. g->coupling_pointlimit[1][i]=kHz*1000./vi->rate*ci->blocksizes[1];
  151148. g->coupling_pkHz[i]=kHz;
  151149. }
  151150. kHz=p[is].lowpasskHz[PACKETBLOBS/2]*(1.-ds)+p[is+1].lowpasskHz[PACKETBLOBS/2]*ds;
  151151. for(i=0;i<PACKETBLOBS;i++){
  151152. g->sliding_lowpass[0][i]=kHz*1000./vi->rate*ci->blocksizes[0];
  151153. g->sliding_lowpass[1][i]=kHz*1000./vi->rate*ci->blocksizes[1];
  151154. }
  151155. }
  151156. }else{
  151157. for(i=0;i<PACKETBLOBS;i++){
  151158. g->sliding_lowpass[0][i]=ci->blocksizes[0];
  151159. g->sliding_lowpass[1][i]=ci->blocksizes[1];
  151160. }
  151161. }
  151162. return;
  151163. }
  151164. static void vorbis_encode_psyset_setup(vorbis_info *vi,double s,
  151165. int *nn_start,
  151166. int *nn_partition,
  151167. double *nn_thresh,
  151168. int block){
  151169. codec_setup_info *ci=(codec_setup_info*) vi->codec_setup;
  151170. vorbis_info_psy *p=ci->psy_param[block];
  151171. highlevel_encode_setup *hi=&ci->hi;
  151172. int is=s;
  151173. if(block>=ci->psys)
  151174. ci->psys=block+1;
  151175. if(!p){
  151176. p=(vorbis_info_psy*)_ogg_calloc(1,sizeof(*p));
  151177. ci->psy_param[block]=p;
  151178. }
  151179. memcpy(p,&_psy_info_template,sizeof(*p));
  151180. p->blockflag=block>>1;
  151181. if(hi->noise_normalize_p){
  151182. p->normal_channel_p=1;
  151183. p->normal_point_p=1;
  151184. p->normal_start=nn_start[is];
  151185. p->normal_partition=nn_partition[is];
  151186. p->normal_thresh=nn_thresh[is];
  151187. }
  151188. return;
  151189. }
  151190. static void vorbis_encode_tonemask_setup(vorbis_info *vi,double s,int block,
  151191. att3 *att,
  151192. int *max,
  151193. vp_adjblock *in){
  151194. int i,is=s;
  151195. double ds=s-is;
  151196. codec_setup_info *ci=(codec_setup_info*) vi->codec_setup;
  151197. vorbis_info_psy *p=ci->psy_param[block];
  151198. /* 0 and 2 are only used by bitmanagement, but there's no harm to always
  151199. filling the values in here */
  151200. p->tone_masteratt[0]=att[is].att[0]*(1.-ds)+att[is+1].att[0]*ds;
  151201. p->tone_masteratt[1]=att[is].att[1]*(1.-ds)+att[is+1].att[1]*ds;
  151202. p->tone_masteratt[2]=att[is].att[2]*(1.-ds)+att[is+1].att[2]*ds;
  151203. p->tone_centerboost=att[is].boost*(1.-ds)+att[is+1].boost*ds;
  151204. p->tone_decay=att[is].decay*(1.-ds)+att[is+1].decay*ds;
  151205. p->max_curve_dB=max[is]*(1.-ds)+max[is+1]*ds;
  151206. for(i=0;i<P_BANDS;i++)
  151207. p->toneatt[i]=in[is].block[i]*(1.-ds)+in[is+1].block[i]*ds;
  151208. return;
  151209. }
  151210. static void vorbis_encode_compand_setup(vorbis_info *vi,double s,int block,
  151211. compandblock *in, double *x){
  151212. int i,is=s;
  151213. double ds=s-is;
  151214. codec_setup_info *ci=(codec_setup_info*)vi->codec_setup;
  151215. vorbis_info_psy *p=ci->psy_param[block];
  151216. ds=x[is]*(1.-ds)+x[is+1]*ds;
  151217. is=(int)ds;
  151218. ds-=is;
  151219. if(ds==0 && is>0){
  151220. is--;
  151221. ds=1.;
  151222. }
  151223. /* interpolate the compander settings */
  151224. for(i=0;i<NOISE_COMPAND_LEVELS;i++)
  151225. p->noisecompand[i]=in[is].data[i]*(1.-ds)+in[is+1].data[i]*ds;
  151226. return;
  151227. }
  151228. static void vorbis_encode_peak_setup(vorbis_info *vi,double s,int block,
  151229. int *suppress){
  151230. int is=s;
  151231. double ds=s-is;
  151232. codec_setup_info *ci=(codec_setup_info*)vi->codec_setup;
  151233. vorbis_info_psy *p=ci->psy_param[block];
  151234. p->tone_abs_limit=suppress[is]*(1.-ds)+suppress[is+1]*ds;
  151235. return;
  151236. }
  151237. static void vorbis_encode_noisebias_setup(vorbis_info *vi,double s,int block,
  151238. int *suppress,
  151239. noise3 *in,
  151240. noiseguard *guard,
  151241. double userbias){
  151242. int i,is=s,j;
  151243. double ds=s-is;
  151244. codec_setup_info *ci=(codec_setup_info*)vi->codec_setup;
  151245. vorbis_info_psy *p=ci->psy_param[block];
  151246. p->noisemaxsupp=suppress[is]*(1.-ds)+suppress[is+1]*ds;
  151247. p->noisewindowlomin=guard[block].lo;
  151248. p->noisewindowhimin=guard[block].hi;
  151249. p->noisewindowfixed=guard[block].fixed;
  151250. for(j=0;j<P_NOISECURVES;j++)
  151251. for(i=0;i<P_BANDS;i++)
  151252. p->noiseoff[j][i]=in[is].data[j][i]*(1.-ds)+in[is+1].data[j][i]*ds;
  151253. /* impulse blocks may take a user specified bias to boost the
  151254. nominal/high noise encoding depth */
  151255. for(j=0;j<P_NOISECURVES;j++){
  151256. float min=p->noiseoff[j][0]+6; /* the lowest it can go */
  151257. for(i=0;i<P_BANDS;i++){
  151258. p->noiseoff[j][i]+=userbias;
  151259. if(p->noiseoff[j][i]<min)p->noiseoff[j][i]=min;
  151260. }
  151261. }
  151262. return;
  151263. }
  151264. static void vorbis_encode_ath_setup(vorbis_info *vi,int block){
  151265. codec_setup_info *ci=(codec_setup_info*)vi->codec_setup;
  151266. vorbis_info_psy *p=ci->psy_param[block];
  151267. p->ath_adjatt=ci->hi.ath_floating_dB;
  151268. p->ath_maxatt=ci->hi.ath_absolute_dB;
  151269. return;
  151270. }
  151271. static int book_dup_or_new(codec_setup_info *ci,static_codebook *book){
  151272. int i;
  151273. for(i=0;i<ci->books;i++)
  151274. if(ci->book_param[i]==book)return(i);
  151275. return(ci->books++);
  151276. }
  151277. static void vorbis_encode_blocksize_setup(vorbis_info *vi,double s,
  151278. int *shortb,int *longb){
  151279. codec_setup_info *ci=(codec_setup_info*)vi->codec_setup;
  151280. int is=s;
  151281. int blockshort=shortb[is];
  151282. int blocklong=longb[is];
  151283. ci->blocksizes[0]=blockshort;
  151284. ci->blocksizes[1]=blocklong;
  151285. }
  151286. static void vorbis_encode_residue_setup(vorbis_info *vi,
  151287. int number, int block,
  151288. vorbis_residue_template *res){
  151289. codec_setup_info *ci=(codec_setup_info*)vi->codec_setup;
  151290. int i,n;
  151291. vorbis_info_residue0 *r=(vorbis_info_residue0*)(ci->residue_param[number]=
  151292. (vorbis_info_residue0*)_ogg_malloc(sizeof(*r)));
  151293. memcpy(r,res->res,sizeof(*r));
  151294. if(ci->residues<=number)ci->residues=number+1;
  151295. switch(ci->blocksizes[block]){
  151296. case 64:case 128:case 256:
  151297. r->grouping=16;
  151298. break;
  151299. default:
  151300. r->grouping=32;
  151301. break;
  151302. }
  151303. ci->residue_type[number]=res->res_type;
  151304. /* to be adjusted by lowpass/pointlimit later */
  151305. n=r->end=ci->blocksizes[block]>>1;
  151306. if(res->res_type==2)
  151307. n=r->end*=vi->channels;
  151308. /* fill in all the books */
  151309. {
  151310. int booklist=0,k;
  151311. if(ci->hi.managed){
  151312. for(i=0;i<r->partitions;i++)
  151313. for(k=0;k<3;k++)
  151314. if(res->books_base_managed->books[i][k])
  151315. r->secondstages[i]|=(1<<k);
  151316. r->groupbook=book_dup_or_new(ci,res->book_aux_managed);
  151317. ci->book_param[r->groupbook]=res->book_aux_managed;
  151318. for(i=0;i<r->partitions;i++){
  151319. for(k=0;k<3;k++){
  151320. if(res->books_base_managed->books[i][k]){
  151321. int bookid=book_dup_or_new(ci,res->books_base_managed->books[i][k]);
  151322. r->booklist[booklist++]=bookid;
  151323. ci->book_param[bookid]=res->books_base_managed->books[i][k];
  151324. }
  151325. }
  151326. }
  151327. }else{
  151328. for(i=0;i<r->partitions;i++)
  151329. for(k=0;k<3;k++)
  151330. if(res->books_base->books[i][k])
  151331. r->secondstages[i]|=(1<<k);
  151332. r->groupbook=book_dup_or_new(ci,res->book_aux);
  151333. ci->book_param[r->groupbook]=res->book_aux;
  151334. for(i=0;i<r->partitions;i++){
  151335. for(k=0;k<3;k++){
  151336. if(res->books_base->books[i][k]){
  151337. int bookid=book_dup_or_new(ci,res->books_base->books[i][k]);
  151338. r->booklist[booklist++]=bookid;
  151339. ci->book_param[bookid]=res->books_base->books[i][k];
  151340. }
  151341. }
  151342. }
  151343. }
  151344. }
  151345. /* lowpass setup/pointlimit */
  151346. {
  151347. double freq=ci->hi.lowpass_kHz*1000.;
  151348. vorbis_info_floor1 *f=(vorbis_info_floor1*)ci->floor_param[block]; /* by convention */
  151349. double nyq=vi->rate/2.;
  151350. long blocksize=ci->blocksizes[block]>>1;
  151351. /* lowpass needs to be set in the floor and the residue. */
  151352. if(freq>nyq)freq=nyq;
  151353. /* in the floor, the granularity can be very fine; it doesn't alter
  151354. the encoding structure, only the samples used to fit the floor
  151355. approximation */
  151356. f->n=freq/nyq*blocksize;
  151357. /* this res may by limited by the maximum pointlimit of the mode,
  151358. not the lowpass. the floor is always lowpass limited. */
  151359. if(res->limit_type){
  151360. if(ci->hi.managed)
  151361. freq=ci->psy_g_param.coupling_pkHz[PACKETBLOBS-1]*1000.;
  151362. else
  151363. freq=ci->psy_g_param.coupling_pkHz[PACKETBLOBS/2]*1000.;
  151364. if(freq>nyq)freq=nyq;
  151365. }
  151366. /* in the residue, we're constrained, physically, by partition
  151367. boundaries. We still lowpass 'wherever', but we have to round up
  151368. here to next boundary, or the vorbis spec will round it *down* to
  151369. previous boundary in encode/decode */
  151370. if(ci->residue_type[block]==2)
  151371. r->end=(int)((freq/nyq*blocksize*2)/r->grouping+.9)* /* round up only if we're well past */
  151372. r->grouping;
  151373. else
  151374. r->end=(int)((freq/nyq*blocksize)/r->grouping+.9)* /* round up only if we're well past */
  151375. r->grouping;
  151376. }
  151377. }
  151378. /* we assume two maps in this encoder */
  151379. static void vorbis_encode_map_n_res_setup(vorbis_info *vi,double s,
  151380. vorbis_mapping_template *maps){
  151381. codec_setup_info *ci=(codec_setup_info*)vi->codec_setup;
  151382. int i,j,is=s,modes=2;
  151383. vorbis_info_mapping0 *map=maps[is].map;
  151384. vorbis_info_mode *mode=_mode_template;
  151385. vorbis_residue_template *res=maps[is].res;
  151386. if(ci->blocksizes[0]==ci->blocksizes[1])modes=1;
  151387. for(i=0;i<modes;i++){
  151388. ci->map_param[i]=_ogg_calloc(1,sizeof(*map));
  151389. ci->mode_param[i]=(vorbis_info_mode*)_ogg_calloc(1,sizeof(*mode));
  151390. memcpy(ci->mode_param[i],mode+i,sizeof(*_mode_template));
  151391. if(i>=ci->modes)ci->modes=i+1;
  151392. ci->map_type[i]=0;
  151393. memcpy(ci->map_param[i],map+i,sizeof(*map));
  151394. if(i>=ci->maps)ci->maps=i+1;
  151395. for(j=0;j<map[i].submaps;j++)
  151396. vorbis_encode_residue_setup(vi,map[i].residuesubmap[j],i
  151397. ,res+map[i].residuesubmap[j]);
  151398. }
  151399. }
  151400. static double setting_to_approx_bitrate(vorbis_info *vi){
  151401. codec_setup_info *ci=(codec_setup_info*)vi->codec_setup;
  151402. highlevel_encode_setup *hi=&ci->hi;
  151403. ve_setup_data_template *setup=(ve_setup_data_template *)hi->setup;
  151404. int is=hi->base_setting;
  151405. double ds=hi->base_setting-is;
  151406. int ch=vi->channels;
  151407. double *r=setup->rate_mapping;
  151408. if(r==NULL)
  151409. return(-1);
  151410. return((r[is]*(1.-ds)+r[is+1]*ds)*ch);
  151411. }
  151412. static void get_setup_template(vorbis_info *vi,
  151413. long ch,long srate,
  151414. double req,int q_or_bitrate){
  151415. int i=0,j;
  151416. codec_setup_info *ci=(codec_setup_info*) vi->codec_setup;
  151417. highlevel_encode_setup *hi=&ci->hi;
  151418. if(q_or_bitrate)req/=ch;
  151419. while(setup_list[i]){
  151420. if(setup_list[i]->coupling_restriction==-1 ||
  151421. setup_list[i]->coupling_restriction==ch){
  151422. if(srate>=setup_list[i]->samplerate_min_restriction &&
  151423. srate<=setup_list[i]->samplerate_max_restriction){
  151424. int mappings=setup_list[i]->mappings;
  151425. double *map=(q_or_bitrate?
  151426. setup_list[i]->rate_mapping:
  151427. setup_list[i]->quality_mapping);
  151428. /* the template matches. Does the requested quality mode
  151429. fall within this template's modes? */
  151430. if(req<map[0]){++i;continue;}
  151431. if(req>map[setup_list[i]->mappings]){++i;continue;}
  151432. for(j=0;j<mappings;j++)
  151433. if(req>=map[j] && req<map[j+1])break;
  151434. /* an all-points match */
  151435. hi->setup=setup_list[i];
  151436. if(j==mappings)
  151437. hi->base_setting=j-.001;
  151438. else{
  151439. float low=map[j];
  151440. float high=map[j+1];
  151441. float del=(req-low)/(high-low);
  151442. hi->base_setting=j+del;
  151443. }
  151444. return;
  151445. }
  151446. }
  151447. i++;
  151448. }
  151449. hi->setup=NULL;
  151450. }
  151451. /* encoders will need to use vorbis_info_init beforehand and call
  151452. vorbis_info clear when all done */
  151453. /* two interfaces; this, more detailed one, and later a convenience
  151454. layer on top */
  151455. /* the final setup call */
  151456. int vorbis_encode_setup_init(vorbis_info *vi){
  151457. int i0=0,singleblock=0;
  151458. codec_setup_info *ci=(codec_setup_info*) vi->codec_setup;
  151459. ve_setup_data_template *setup=NULL;
  151460. highlevel_encode_setup *hi=&ci->hi;
  151461. if(ci==NULL)return(OV_EINVAL);
  151462. if(!hi->impulse_block_p)i0=1;
  151463. /* too low/high an ATH floater is nonsensical, but doesn't break anything */
  151464. if(hi->ath_floating_dB>-80)hi->ath_floating_dB=-80;
  151465. if(hi->ath_floating_dB<-200)hi->ath_floating_dB=-200;
  151466. /* again, bound this to avoid the app shooting itself int he foot
  151467. too badly */
  151468. if(hi->amplitude_track_dBpersec>0.)hi->amplitude_track_dBpersec=0.;
  151469. if(hi->amplitude_track_dBpersec<-99999.)hi->amplitude_track_dBpersec=-99999.;
  151470. /* get the appropriate setup template; matches the fetch in previous
  151471. stages */
  151472. setup=(ve_setup_data_template *)hi->setup;
  151473. if(setup==NULL)return(OV_EINVAL);
  151474. hi->set_in_stone=1;
  151475. /* choose block sizes from configured sizes as well as paying
  151476. attention to long_block_p and short_block_p. If the configured
  151477. short and long blocks are the same length, we set long_block_p
  151478. and unset short_block_p */
  151479. vorbis_encode_blocksize_setup(vi,hi->base_setting,
  151480. setup->blocksize_short,
  151481. setup->blocksize_long);
  151482. if(ci->blocksizes[0]==ci->blocksizes[1])singleblock=1;
  151483. /* floor setup; choose proper floor params. Allocated on the floor
  151484. stack in order; if we alloc only long floor, it's 0 */
  151485. vorbis_encode_floor_setup(vi,hi->short_setting,0,
  151486. setup->floor_books,
  151487. setup->floor_params,
  151488. setup->floor_short_mapping);
  151489. if(!singleblock)
  151490. vorbis_encode_floor_setup(vi,hi->long_setting,1,
  151491. setup->floor_books,
  151492. setup->floor_params,
  151493. setup->floor_long_mapping);
  151494. /* setup of [mostly] short block detection and stereo*/
  151495. vorbis_encode_global_psych_setup(vi,hi->trigger_setting,
  151496. setup->global_params,
  151497. setup->global_mapping);
  151498. vorbis_encode_global_stereo(vi,hi,setup->stereo_modes);
  151499. /* basic psych setup and noise normalization */
  151500. vorbis_encode_psyset_setup(vi,hi->short_setting,
  151501. setup->psy_noise_normal_start[0],
  151502. setup->psy_noise_normal_partition[0],
  151503. setup->psy_noise_normal_thresh,
  151504. 0);
  151505. vorbis_encode_psyset_setup(vi,hi->short_setting,
  151506. setup->psy_noise_normal_start[0],
  151507. setup->psy_noise_normal_partition[0],
  151508. setup->psy_noise_normal_thresh,
  151509. 1);
  151510. if(!singleblock){
  151511. vorbis_encode_psyset_setup(vi,hi->long_setting,
  151512. setup->psy_noise_normal_start[1],
  151513. setup->psy_noise_normal_partition[1],
  151514. setup->psy_noise_normal_thresh,
  151515. 2);
  151516. vorbis_encode_psyset_setup(vi,hi->long_setting,
  151517. setup->psy_noise_normal_start[1],
  151518. setup->psy_noise_normal_partition[1],
  151519. setup->psy_noise_normal_thresh,
  151520. 3);
  151521. }
  151522. /* tone masking setup */
  151523. vorbis_encode_tonemask_setup(vi,hi->block[i0].tone_mask_setting,0,
  151524. setup->psy_tone_masteratt,
  151525. setup->psy_tone_0dB,
  151526. setup->psy_tone_adj_impulse);
  151527. vorbis_encode_tonemask_setup(vi,hi->block[1].tone_mask_setting,1,
  151528. setup->psy_tone_masteratt,
  151529. setup->psy_tone_0dB,
  151530. setup->psy_tone_adj_other);
  151531. if(!singleblock){
  151532. vorbis_encode_tonemask_setup(vi,hi->block[2].tone_mask_setting,2,
  151533. setup->psy_tone_masteratt,
  151534. setup->psy_tone_0dB,
  151535. setup->psy_tone_adj_other);
  151536. vorbis_encode_tonemask_setup(vi,hi->block[3].tone_mask_setting,3,
  151537. setup->psy_tone_masteratt,
  151538. setup->psy_tone_0dB,
  151539. setup->psy_tone_adj_long);
  151540. }
  151541. /* noise companding setup */
  151542. vorbis_encode_compand_setup(vi,hi->block[i0].noise_compand_setting,0,
  151543. setup->psy_noise_compand,
  151544. setup->psy_noise_compand_short_mapping);
  151545. vorbis_encode_compand_setup(vi,hi->block[1].noise_compand_setting,1,
  151546. setup->psy_noise_compand,
  151547. setup->psy_noise_compand_short_mapping);
  151548. if(!singleblock){
  151549. vorbis_encode_compand_setup(vi,hi->block[2].noise_compand_setting,2,
  151550. setup->psy_noise_compand,
  151551. setup->psy_noise_compand_long_mapping);
  151552. vorbis_encode_compand_setup(vi,hi->block[3].noise_compand_setting,3,
  151553. setup->psy_noise_compand,
  151554. setup->psy_noise_compand_long_mapping);
  151555. }
  151556. /* peak guarding setup */
  151557. vorbis_encode_peak_setup(vi,hi->block[i0].tone_peaklimit_setting,0,
  151558. setup->psy_tone_dBsuppress);
  151559. vorbis_encode_peak_setup(vi,hi->block[1].tone_peaklimit_setting,1,
  151560. setup->psy_tone_dBsuppress);
  151561. if(!singleblock){
  151562. vorbis_encode_peak_setup(vi,hi->block[2].tone_peaklimit_setting,2,
  151563. setup->psy_tone_dBsuppress);
  151564. vorbis_encode_peak_setup(vi,hi->block[3].tone_peaklimit_setting,3,
  151565. setup->psy_tone_dBsuppress);
  151566. }
  151567. /* noise bias setup */
  151568. vorbis_encode_noisebias_setup(vi,hi->block[i0].noise_bias_setting,0,
  151569. setup->psy_noise_dBsuppress,
  151570. setup->psy_noise_bias_impulse,
  151571. setup->psy_noiseguards,
  151572. (i0==0?hi->impulse_noisetune:0.));
  151573. vorbis_encode_noisebias_setup(vi,hi->block[1].noise_bias_setting,1,
  151574. setup->psy_noise_dBsuppress,
  151575. setup->psy_noise_bias_padding,
  151576. setup->psy_noiseguards,0.);
  151577. if(!singleblock){
  151578. vorbis_encode_noisebias_setup(vi,hi->block[2].noise_bias_setting,2,
  151579. setup->psy_noise_dBsuppress,
  151580. setup->psy_noise_bias_trans,
  151581. setup->psy_noiseguards,0.);
  151582. vorbis_encode_noisebias_setup(vi,hi->block[3].noise_bias_setting,3,
  151583. setup->psy_noise_dBsuppress,
  151584. setup->psy_noise_bias_long,
  151585. setup->psy_noiseguards,0.);
  151586. }
  151587. vorbis_encode_ath_setup(vi,0);
  151588. vorbis_encode_ath_setup(vi,1);
  151589. if(!singleblock){
  151590. vorbis_encode_ath_setup(vi,2);
  151591. vorbis_encode_ath_setup(vi,3);
  151592. }
  151593. vorbis_encode_map_n_res_setup(vi,hi->base_setting,setup->maps);
  151594. /* set bitrate readonlies and management */
  151595. if(hi->bitrate_av>0)
  151596. vi->bitrate_nominal=hi->bitrate_av;
  151597. else{
  151598. vi->bitrate_nominal=setting_to_approx_bitrate(vi);
  151599. }
  151600. vi->bitrate_lower=hi->bitrate_min;
  151601. vi->bitrate_upper=hi->bitrate_max;
  151602. if(hi->bitrate_av)
  151603. vi->bitrate_window=(double)hi->bitrate_reservoir/hi->bitrate_av;
  151604. else
  151605. vi->bitrate_window=0.;
  151606. if(hi->managed){
  151607. ci->bi.avg_rate=hi->bitrate_av;
  151608. ci->bi.min_rate=hi->bitrate_min;
  151609. ci->bi.max_rate=hi->bitrate_max;
  151610. ci->bi.reservoir_bits=hi->bitrate_reservoir;
  151611. ci->bi.reservoir_bias=
  151612. hi->bitrate_reservoir_bias;
  151613. ci->bi.slew_damp=hi->bitrate_av_damp;
  151614. }
  151615. return(0);
  151616. }
  151617. static int vorbis_encode_setup_setting(vorbis_info *vi,
  151618. long channels,
  151619. long rate){
  151620. int ret=0,i,is;
  151621. codec_setup_info *ci=(codec_setup_info*)vi->codec_setup;
  151622. highlevel_encode_setup *hi=&ci->hi;
  151623. ve_setup_data_template *setup=(ve_setup_data_template*) hi->setup;
  151624. double ds;
  151625. ret=vorbis_encode_toplevel_setup(vi,channels,rate);
  151626. if(ret)return(ret);
  151627. is=hi->base_setting;
  151628. ds=hi->base_setting-is;
  151629. hi->short_setting=hi->base_setting;
  151630. hi->long_setting=hi->base_setting;
  151631. hi->managed=0;
  151632. hi->impulse_block_p=1;
  151633. hi->noise_normalize_p=1;
  151634. hi->stereo_point_setting=hi->base_setting;
  151635. hi->lowpass_kHz=
  151636. setup->psy_lowpass[is]*(1.-ds)+setup->psy_lowpass[is+1]*ds;
  151637. hi->ath_floating_dB=setup->psy_ath_float[is]*(1.-ds)+
  151638. setup->psy_ath_float[is+1]*ds;
  151639. hi->ath_absolute_dB=setup->psy_ath_abs[is]*(1.-ds)+
  151640. setup->psy_ath_abs[is+1]*ds;
  151641. hi->amplitude_track_dBpersec=-6.;
  151642. hi->trigger_setting=hi->base_setting;
  151643. for(i=0;i<4;i++){
  151644. hi->block[i].tone_mask_setting=hi->base_setting;
  151645. hi->block[i].tone_peaklimit_setting=hi->base_setting;
  151646. hi->block[i].noise_bias_setting=hi->base_setting;
  151647. hi->block[i].noise_compand_setting=hi->base_setting;
  151648. }
  151649. return(ret);
  151650. }
  151651. int vorbis_encode_setup_vbr(vorbis_info *vi,
  151652. long channels,
  151653. long rate,
  151654. float quality){
  151655. codec_setup_info *ci=(codec_setup_info*) vi->codec_setup;
  151656. highlevel_encode_setup *hi=&ci->hi;
  151657. quality+=.0000001;
  151658. if(quality>=1.)quality=.9999;
  151659. get_setup_template(vi,channels,rate,quality,0);
  151660. if(!hi->setup)return OV_EIMPL;
  151661. return vorbis_encode_setup_setting(vi,channels,rate);
  151662. }
  151663. int vorbis_encode_init_vbr(vorbis_info *vi,
  151664. long channels,
  151665. long rate,
  151666. float base_quality /* 0. to 1. */
  151667. ){
  151668. int ret=0;
  151669. ret=vorbis_encode_setup_vbr(vi,channels,rate,base_quality);
  151670. if(ret){
  151671. vorbis_info_clear(vi);
  151672. return ret;
  151673. }
  151674. ret=vorbis_encode_setup_init(vi);
  151675. if(ret)
  151676. vorbis_info_clear(vi);
  151677. return(ret);
  151678. }
  151679. int vorbis_encode_setup_managed(vorbis_info *vi,
  151680. long channels,
  151681. long rate,
  151682. long max_bitrate,
  151683. long nominal_bitrate,
  151684. long min_bitrate){
  151685. codec_setup_info *ci=(codec_setup_info*)vi->codec_setup;
  151686. highlevel_encode_setup *hi=&ci->hi;
  151687. double tnominal=nominal_bitrate;
  151688. int ret=0;
  151689. if(nominal_bitrate<=0.){
  151690. if(max_bitrate>0.){
  151691. if(min_bitrate>0.)
  151692. nominal_bitrate=(max_bitrate+min_bitrate)*.5;
  151693. else
  151694. nominal_bitrate=max_bitrate*.875;
  151695. }else{
  151696. if(min_bitrate>0.){
  151697. nominal_bitrate=min_bitrate;
  151698. }else{
  151699. return(OV_EINVAL);
  151700. }
  151701. }
  151702. }
  151703. get_setup_template(vi,channels,rate,nominal_bitrate,1);
  151704. if(!hi->setup)return OV_EIMPL;
  151705. ret=vorbis_encode_setup_setting(vi,channels,rate);
  151706. if(ret){
  151707. vorbis_info_clear(vi);
  151708. return ret;
  151709. }
  151710. /* initialize management with sane defaults */
  151711. hi->managed=1;
  151712. hi->bitrate_min=min_bitrate;
  151713. hi->bitrate_max=max_bitrate;
  151714. hi->bitrate_av=tnominal;
  151715. hi->bitrate_av_damp=1.5f; /* full range in no less than 1.5 second */
  151716. hi->bitrate_reservoir=nominal_bitrate*2;
  151717. hi->bitrate_reservoir_bias=.1; /* bias toward hoarding bits */
  151718. return(ret);
  151719. }
  151720. int vorbis_encode_init(vorbis_info *vi,
  151721. long channels,
  151722. long rate,
  151723. long max_bitrate,
  151724. long nominal_bitrate,
  151725. long min_bitrate){
  151726. int ret=vorbis_encode_setup_managed(vi,channels,rate,
  151727. max_bitrate,
  151728. nominal_bitrate,
  151729. min_bitrate);
  151730. if(ret){
  151731. vorbis_info_clear(vi);
  151732. return(ret);
  151733. }
  151734. ret=vorbis_encode_setup_init(vi);
  151735. if(ret)
  151736. vorbis_info_clear(vi);
  151737. return(ret);
  151738. }
  151739. int vorbis_encode_ctl(vorbis_info *vi,int number,void *arg){
  151740. if(vi){
  151741. codec_setup_info *ci=(codec_setup_info*)vi->codec_setup;
  151742. highlevel_encode_setup *hi=&ci->hi;
  151743. int setp=(number&0xf); /* a read request has a low nibble of 0 */
  151744. if(setp && hi->set_in_stone)return(OV_EINVAL);
  151745. switch(number){
  151746. /* now deprecated *****************/
  151747. case OV_ECTL_RATEMANAGE_GET:
  151748. {
  151749. struct ovectl_ratemanage_arg *ai=
  151750. (struct ovectl_ratemanage_arg *)arg;
  151751. ai->management_active=hi->managed;
  151752. ai->bitrate_hard_window=ai->bitrate_av_window=
  151753. (double)hi->bitrate_reservoir/vi->rate;
  151754. ai->bitrate_av_window_center=1.;
  151755. ai->bitrate_hard_min=hi->bitrate_min;
  151756. ai->bitrate_hard_max=hi->bitrate_max;
  151757. ai->bitrate_av_lo=hi->bitrate_av;
  151758. ai->bitrate_av_hi=hi->bitrate_av;
  151759. }
  151760. return(0);
  151761. /* now deprecated *****************/
  151762. case OV_ECTL_RATEMANAGE_SET:
  151763. {
  151764. struct ovectl_ratemanage_arg *ai=
  151765. (struct ovectl_ratemanage_arg *)arg;
  151766. if(ai==NULL){
  151767. hi->managed=0;
  151768. }else{
  151769. hi->managed=ai->management_active;
  151770. vorbis_encode_ctl(vi,OV_ECTL_RATEMANAGE_AVG,arg);
  151771. vorbis_encode_ctl(vi,OV_ECTL_RATEMANAGE_HARD,arg);
  151772. }
  151773. }
  151774. return 0;
  151775. /* now deprecated *****************/
  151776. case OV_ECTL_RATEMANAGE_AVG:
  151777. {
  151778. struct ovectl_ratemanage_arg *ai=
  151779. (struct ovectl_ratemanage_arg *)arg;
  151780. if(ai==NULL){
  151781. hi->bitrate_av=0;
  151782. }else{
  151783. hi->bitrate_av=(ai->bitrate_av_lo+ai->bitrate_av_hi)*.5;
  151784. }
  151785. }
  151786. return(0);
  151787. /* now deprecated *****************/
  151788. case OV_ECTL_RATEMANAGE_HARD:
  151789. {
  151790. struct ovectl_ratemanage_arg *ai=
  151791. (struct ovectl_ratemanage_arg *)arg;
  151792. if(ai==NULL){
  151793. hi->bitrate_min=0;
  151794. hi->bitrate_max=0;
  151795. }else{
  151796. hi->bitrate_min=ai->bitrate_hard_min;
  151797. hi->bitrate_max=ai->bitrate_hard_max;
  151798. hi->bitrate_reservoir=ai->bitrate_hard_window*
  151799. (hi->bitrate_max+hi->bitrate_min)*.5;
  151800. }
  151801. if(hi->bitrate_reservoir<128.)
  151802. hi->bitrate_reservoir=128.;
  151803. }
  151804. return(0);
  151805. /* replacement ratemanage interface */
  151806. case OV_ECTL_RATEMANAGE2_GET:
  151807. {
  151808. struct ovectl_ratemanage2_arg *ai=
  151809. (struct ovectl_ratemanage2_arg *)arg;
  151810. if(ai==NULL)return OV_EINVAL;
  151811. ai->management_active=hi->managed;
  151812. ai->bitrate_limit_min_kbps=hi->bitrate_min/1000;
  151813. ai->bitrate_limit_max_kbps=hi->bitrate_max/1000;
  151814. ai->bitrate_average_kbps=hi->bitrate_av/1000;
  151815. ai->bitrate_average_damping=hi->bitrate_av_damp;
  151816. ai->bitrate_limit_reservoir_bits=hi->bitrate_reservoir;
  151817. ai->bitrate_limit_reservoir_bias=hi->bitrate_reservoir_bias;
  151818. }
  151819. return (0);
  151820. case OV_ECTL_RATEMANAGE2_SET:
  151821. {
  151822. struct ovectl_ratemanage2_arg *ai=
  151823. (struct ovectl_ratemanage2_arg *)arg;
  151824. if(ai==NULL){
  151825. hi->managed=0;
  151826. }else{
  151827. /* sanity check; only catch invariant violations */
  151828. if(ai->bitrate_limit_min_kbps>0 &&
  151829. ai->bitrate_average_kbps>0 &&
  151830. ai->bitrate_limit_min_kbps>ai->bitrate_average_kbps)
  151831. return OV_EINVAL;
  151832. if(ai->bitrate_limit_max_kbps>0 &&
  151833. ai->bitrate_average_kbps>0 &&
  151834. ai->bitrate_limit_max_kbps<ai->bitrate_average_kbps)
  151835. return OV_EINVAL;
  151836. if(ai->bitrate_limit_min_kbps>0 &&
  151837. ai->bitrate_limit_max_kbps>0 &&
  151838. ai->bitrate_limit_min_kbps>ai->bitrate_limit_max_kbps)
  151839. return OV_EINVAL;
  151840. if(ai->bitrate_average_damping <= 0.)
  151841. return OV_EINVAL;
  151842. if(ai->bitrate_limit_reservoir_bits < 0)
  151843. return OV_EINVAL;
  151844. if(ai->bitrate_limit_reservoir_bias < 0.)
  151845. return OV_EINVAL;
  151846. if(ai->bitrate_limit_reservoir_bias > 1.)
  151847. return OV_EINVAL;
  151848. hi->managed=ai->management_active;
  151849. hi->bitrate_min=ai->bitrate_limit_min_kbps * 1000;
  151850. hi->bitrate_max=ai->bitrate_limit_max_kbps * 1000;
  151851. hi->bitrate_av=ai->bitrate_average_kbps * 1000;
  151852. hi->bitrate_av_damp=ai->bitrate_average_damping;
  151853. hi->bitrate_reservoir=ai->bitrate_limit_reservoir_bits;
  151854. hi->bitrate_reservoir_bias=ai->bitrate_limit_reservoir_bias;
  151855. }
  151856. }
  151857. return 0;
  151858. case OV_ECTL_LOWPASS_GET:
  151859. {
  151860. double *farg=(double *)arg;
  151861. *farg=hi->lowpass_kHz;
  151862. }
  151863. return(0);
  151864. case OV_ECTL_LOWPASS_SET:
  151865. {
  151866. double *farg=(double *)arg;
  151867. hi->lowpass_kHz=*farg;
  151868. if(hi->lowpass_kHz<2.)hi->lowpass_kHz=2.;
  151869. if(hi->lowpass_kHz>99.)hi->lowpass_kHz=99.;
  151870. }
  151871. return(0);
  151872. case OV_ECTL_IBLOCK_GET:
  151873. {
  151874. double *farg=(double *)arg;
  151875. *farg=hi->impulse_noisetune;
  151876. }
  151877. return(0);
  151878. case OV_ECTL_IBLOCK_SET:
  151879. {
  151880. double *farg=(double *)arg;
  151881. hi->impulse_noisetune=*farg;
  151882. if(hi->impulse_noisetune>0.)hi->impulse_noisetune=0.;
  151883. if(hi->impulse_noisetune<-15.)hi->impulse_noisetune=-15.;
  151884. }
  151885. return(0);
  151886. }
  151887. return(OV_EIMPL);
  151888. }
  151889. return(OV_EINVAL);
  151890. }
  151891. #endif
  151892. /*** End of inlined file: vorbisenc.c ***/
  151893. /*** Start of inlined file: vorbisfile.c ***/
  151894. /*** Start of inlined file: juce_OggVorbisHeader.h ***/
  151895. // This file is included at the start of each Ogg-Vorbis .c file, just to do a few housekeeping
  151896. // tasks..
  151897. #if JUCE_MSVC
  151898. #pragma warning (disable: 4267 4127 4244 4996 4100 4701 4702 4013 4133 4206 4305 4189 4706)
  151899. #endif
  151900. /*** End of inlined file: juce_OggVorbisHeader.h ***/
  151901. #if JUCE_USE_OGGVORBIS
  151902. #include <stdlib.h>
  151903. #include <stdio.h>
  151904. #include <errno.h>
  151905. #include <string.h>
  151906. #include <math.h>
  151907. /* A 'chained bitstream' is a Vorbis bitstream that contains more than
  151908. one logical bitstream arranged end to end (the only form of Ogg
  151909. multiplexing allowed in a Vorbis bitstream; grouping [parallel
  151910. multiplexing] is not allowed in Vorbis) */
  151911. /* A Vorbis file can be played beginning to end (streamed) without
  151912. worrying ahead of time about chaining (see decoder_example.c). If
  151913. we have the whole file, however, and want random access
  151914. (seeking/scrubbing) or desire to know the total length/time of a
  151915. file, we need to account for the possibility of chaining. */
  151916. /* We can handle things a number of ways; we can determine the entire
  151917. bitstream structure right off the bat, or find pieces on demand.
  151918. This example determines and caches structure for the entire
  151919. bitstream, but builds a virtual decoder on the fly when moving
  151920. between links in the chain. */
  151921. /* There are also different ways to implement seeking. Enough
  151922. information exists in an Ogg bitstream to seek to
  151923. sample-granularity positions in the output. Or, one can seek by
  151924. picking some portion of the stream roughly in the desired area if
  151925. we only want coarse navigation through the stream. */
  151926. /*************************************************************************
  151927. * Many, many internal helpers. The intention is not to be confusing;
  151928. * rampant duplication and monolithic function implementation would be
  151929. * harder to understand anyway. The high level functions are last. Begin
  151930. * grokking near the end of the file */
  151931. /* read a little more data from the file/pipe into the ogg_sync framer
  151932. */
  151933. #define CHUNKSIZE 8500 /* a shade over 8k; anyone using pages well
  151934. over 8k gets what they deserve */
  151935. static long _get_data(OggVorbis_File *vf){
  151936. errno=0;
  151937. if(vf->datasource){
  151938. char *buffer=ogg_sync_buffer(&vf->oy,CHUNKSIZE);
  151939. long bytes=(vf->callbacks.read_func)(buffer,1,CHUNKSIZE,vf->datasource);
  151940. if(bytes>0)ogg_sync_wrote(&vf->oy,bytes);
  151941. if(bytes==0 && errno)return(-1);
  151942. return(bytes);
  151943. }else
  151944. return(0);
  151945. }
  151946. /* save a tiny smidge of verbosity to make the code more readable */
  151947. static void _seek_helper(OggVorbis_File *vf,ogg_int64_t offset){
  151948. if(vf->datasource){
  151949. (vf->callbacks.seek_func)(vf->datasource, offset, SEEK_SET);
  151950. vf->offset=offset;
  151951. ogg_sync_reset(&vf->oy);
  151952. }else{
  151953. /* shouldn't happen unless someone writes a broken callback */
  151954. return;
  151955. }
  151956. }
  151957. /* The read/seek functions track absolute position within the stream */
  151958. /* from the head of the stream, get the next page. boundary specifies
  151959. if the function is allowed to fetch more data from the stream (and
  151960. how much) or only use internally buffered data.
  151961. boundary: -1) unbounded search
  151962. 0) read no additional data; use cached only
  151963. n) search for a new page beginning for n bytes
  151964. return: <0) did not find a page (OV_FALSE, OV_EOF, OV_EREAD)
  151965. n) found a page at absolute offset n */
  151966. static ogg_int64_t _get_next_page(OggVorbis_File *vf,ogg_page *og,
  151967. ogg_int64_t boundary){
  151968. if(boundary>0)boundary+=vf->offset;
  151969. while(1){
  151970. long more;
  151971. if(boundary>0 && vf->offset>=boundary)return(OV_FALSE);
  151972. more=ogg_sync_pageseek(&vf->oy,og);
  151973. if(more<0){
  151974. /* skipped n bytes */
  151975. vf->offset-=more;
  151976. }else{
  151977. if(more==0){
  151978. /* send more paramedics */
  151979. if(!boundary)return(OV_FALSE);
  151980. {
  151981. long ret=_get_data(vf);
  151982. if(ret==0)return(OV_EOF);
  151983. if(ret<0)return(OV_EREAD);
  151984. }
  151985. }else{
  151986. /* got a page. Return the offset at the page beginning,
  151987. advance the internal offset past the page end */
  151988. ogg_int64_t ret=vf->offset;
  151989. vf->offset+=more;
  151990. return(ret);
  151991. }
  151992. }
  151993. }
  151994. }
  151995. /* find the latest page beginning before the current stream cursor
  151996. position. Much dirtier than the above as Ogg doesn't have any
  151997. backward search linkage. no 'readp' as it will certainly have to
  151998. read. */
  151999. /* returns offset or OV_EREAD, OV_FAULT */
  152000. static ogg_int64_t _get_prev_page(OggVorbis_File *vf,ogg_page *og){
  152001. ogg_int64_t begin=vf->offset;
  152002. ogg_int64_t end=begin;
  152003. ogg_int64_t ret;
  152004. ogg_int64_t offset=-1;
  152005. while(offset==-1){
  152006. begin-=CHUNKSIZE;
  152007. if(begin<0)
  152008. begin=0;
  152009. _seek_helper(vf,begin);
  152010. while(vf->offset<end){
  152011. ret=_get_next_page(vf,og,end-vf->offset);
  152012. if(ret==OV_EREAD)return(OV_EREAD);
  152013. if(ret<0){
  152014. break;
  152015. }else{
  152016. offset=ret;
  152017. }
  152018. }
  152019. }
  152020. /* we have the offset. Actually snork and hold the page now */
  152021. _seek_helper(vf,offset);
  152022. ret=_get_next_page(vf,og,CHUNKSIZE);
  152023. if(ret<0)
  152024. /* this shouldn't be possible */
  152025. return(OV_EFAULT);
  152026. return(offset);
  152027. }
  152028. /* finds each bitstream link one at a time using a bisection search
  152029. (has to begin by knowing the offset of the lb's initial page).
  152030. Recurses for each link so it can alloc the link storage after
  152031. finding them all, then unroll and fill the cache at the same time */
  152032. static int _bisect_forward_serialno(OggVorbis_File *vf,
  152033. ogg_int64_t begin,
  152034. ogg_int64_t searched,
  152035. ogg_int64_t end,
  152036. long currentno,
  152037. long m){
  152038. ogg_int64_t endsearched=end;
  152039. ogg_int64_t next=end;
  152040. ogg_page og;
  152041. ogg_int64_t ret;
  152042. /* the below guards against garbage seperating the last and
  152043. first pages of two links. */
  152044. while(searched<endsearched){
  152045. ogg_int64_t bisect;
  152046. if(endsearched-searched<CHUNKSIZE){
  152047. bisect=searched;
  152048. }else{
  152049. bisect=(searched+endsearched)/2;
  152050. }
  152051. _seek_helper(vf,bisect);
  152052. ret=_get_next_page(vf,&og,-1);
  152053. if(ret==OV_EREAD)return(OV_EREAD);
  152054. if(ret<0 || ogg_page_serialno(&og)!=currentno){
  152055. endsearched=bisect;
  152056. if(ret>=0)next=ret;
  152057. }else{
  152058. searched=ret+og.header_len+og.body_len;
  152059. }
  152060. }
  152061. _seek_helper(vf,next);
  152062. ret=_get_next_page(vf,&og,-1);
  152063. if(ret==OV_EREAD)return(OV_EREAD);
  152064. if(searched>=end || ret<0){
  152065. vf->links=m+1;
  152066. vf->offsets=(ogg_int64_t*)_ogg_malloc((vf->links+1)*sizeof(*vf->offsets));
  152067. vf->serialnos=(long*)_ogg_malloc(vf->links*sizeof(*vf->serialnos));
  152068. vf->offsets[m+1]=searched;
  152069. }else{
  152070. ret=_bisect_forward_serialno(vf,next,vf->offset,
  152071. end,ogg_page_serialno(&og),m+1);
  152072. if(ret==OV_EREAD)return(OV_EREAD);
  152073. }
  152074. vf->offsets[m]=begin;
  152075. vf->serialnos[m]=currentno;
  152076. return(0);
  152077. }
  152078. /* uses the local ogg_stream storage in vf; this is important for
  152079. non-streaming input sources */
  152080. static int _fetch_headers(OggVorbis_File *vf,vorbis_info *vi,vorbis_comment *vc,
  152081. long *serialno,ogg_page *og_ptr){
  152082. ogg_page og;
  152083. ogg_packet op;
  152084. int i,ret;
  152085. if(!og_ptr){
  152086. ogg_int64_t llret=_get_next_page(vf,&og,CHUNKSIZE);
  152087. if(llret==OV_EREAD)return(OV_EREAD);
  152088. if(llret<0)return OV_ENOTVORBIS;
  152089. og_ptr=&og;
  152090. }
  152091. ogg_stream_reset_serialno(&vf->os,ogg_page_serialno(og_ptr));
  152092. if(serialno)*serialno=vf->os.serialno;
  152093. vf->ready_state=STREAMSET;
  152094. /* extract the initial header from the first page and verify that the
  152095. Ogg bitstream is in fact Vorbis data */
  152096. vorbis_info_init(vi);
  152097. vorbis_comment_init(vc);
  152098. i=0;
  152099. while(i<3){
  152100. ogg_stream_pagein(&vf->os,og_ptr);
  152101. while(i<3){
  152102. int result=ogg_stream_packetout(&vf->os,&op);
  152103. if(result==0)break;
  152104. if(result==-1){
  152105. ret=OV_EBADHEADER;
  152106. goto bail_header;
  152107. }
  152108. if((ret=vorbis_synthesis_headerin(vi,vc,&op))){
  152109. goto bail_header;
  152110. }
  152111. i++;
  152112. }
  152113. if(i<3)
  152114. if(_get_next_page(vf,og_ptr,CHUNKSIZE)<0){
  152115. ret=OV_EBADHEADER;
  152116. goto bail_header;
  152117. }
  152118. }
  152119. return 0;
  152120. bail_header:
  152121. vorbis_info_clear(vi);
  152122. vorbis_comment_clear(vc);
  152123. vf->ready_state=OPENED;
  152124. return ret;
  152125. }
  152126. /* last step of the OggVorbis_File initialization; get all the
  152127. vorbis_info structs and PCM positions. Only called by the seekable
  152128. initialization (local stream storage is hacked slightly; pay
  152129. attention to how that's done) */
  152130. /* this is void and does not propogate errors up because we want to be
  152131. able to open and use damaged bitstreams as well as we can. Just
  152132. watch out for missing information for links in the OggVorbis_File
  152133. struct */
  152134. static void _prefetch_all_headers(OggVorbis_File *vf, ogg_int64_t dataoffset){
  152135. ogg_page og;
  152136. int i;
  152137. ogg_int64_t ret;
  152138. vf->vi=(vorbis_info*) _ogg_realloc(vf->vi,vf->links*sizeof(*vf->vi));
  152139. vf->vc=(vorbis_comment*) _ogg_realloc(vf->vc,vf->links*sizeof(*vf->vc));
  152140. vf->dataoffsets=(ogg_int64_t*) _ogg_malloc(vf->links*sizeof(*vf->dataoffsets));
  152141. vf->pcmlengths=(ogg_int64_t*) _ogg_malloc(vf->links*2*sizeof(*vf->pcmlengths));
  152142. for(i=0;i<vf->links;i++){
  152143. if(i==0){
  152144. /* we already grabbed the initial header earlier. Just set the offset */
  152145. vf->dataoffsets[i]=dataoffset;
  152146. _seek_helper(vf,dataoffset);
  152147. }else{
  152148. /* seek to the location of the initial header */
  152149. _seek_helper(vf,vf->offsets[i]);
  152150. if(_fetch_headers(vf,vf->vi+i,vf->vc+i,NULL,NULL)<0){
  152151. vf->dataoffsets[i]=-1;
  152152. }else{
  152153. vf->dataoffsets[i]=vf->offset;
  152154. }
  152155. }
  152156. /* fetch beginning PCM offset */
  152157. if(vf->dataoffsets[i]!=-1){
  152158. ogg_int64_t accumulated=0;
  152159. long lastblock=-1;
  152160. int result;
  152161. ogg_stream_reset_serialno(&vf->os,vf->serialnos[i]);
  152162. while(1){
  152163. ogg_packet op;
  152164. ret=_get_next_page(vf,&og,-1);
  152165. if(ret<0)
  152166. /* this should not be possible unless the file is
  152167. truncated/mangled */
  152168. break;
  152169. if(ogg_page_serialno(&og)!=vf->serialnos[i])
  152170. break;
  152171. /* count blocksizes of all frames in the page */
  152172. ogg_stream_pagein(&vf->os,&og);
  152173. while((result=ogg_stream_packetout(&vf->os,&op))){
  152174. if(result>0){ /* ignore holes */
  152175. long thisblock=vorbis_packet_blocksize(vf->vi+i,&op);
  152176. if(lastblock!=-1)
  152177. accumulated+=(lastblock+thisblock)>>2;
  152178. lastblock=thisblock;
  152179. }
  152180. }
  152181. if(ogg_page_granulepos(&og)!=-1){
  152182. /* pcm offset of last packet on the first audio page */
  152183. accumulated= ogg_page_granulepos(&og)-accumulated;
  152184. break;
  152185. }
  152186. }
  152187. /* less than zero? This is a stream with samples trimmed off
  152188. the beginning, a normal occurrence; set the offset to zero */
  152189. if(accumulated<0)accumulated=0;
  152190. vf->pcmlengths[i*2]=accumulated;
  152191. }
  152192. /* get the PCM length of this link. To do this,
  152193. get the last page of the stream */
  152194. {
  152195. ogg_int64_t end=vf->offsets[i+1];
  152196. _seek_helper(vf,end);
  152197. while(1){
  152198. ret=_get_prev_page(vf,&og);
  152199. if(ret<0){
  152200. /* this should not be possible */
  152201. vorbis_info_clear(vf->vi+i);
  152202. vorbis_comment_clear(vf->vc+i);
  152203. break;
  152204. }
  152205. if(ogg_page_granulepos(&og)!=-1){
  152206. vf->pcmlengths[i*2+1]=ogg_page_granulepos(&og)-vf->pcmlengths[i*2];
  152207. break;
  152208. }
  152209. vf->offset=ret;
  152210. }
  152211. }
  152212. }
  152213. }
  152214. static int _make_decode_ready(OggVorbis_File *vf){
  152215. if(vf->ready_state>STREAMSET)return 0;
  152216. if(vf->ready_state<STREAMSET)return OV_EFAULT;
  152217. if(vf->seekable){
  152218. if(vorbis_synthesis_init(&vf->vd,vf->vi+vf->current_link))
  152219. return OV_EBADLINK;
  152220. }else{
  152221. if(vorbis_synthesis_init(&vf->vd,vf->vi))
  152222. return OV_EBADLINK;
  152223. }
  152224. vorbis_block_init(&vf->vd,&vf->vb);
  152225. vf->ready_state=INITSET;
  152226. vf->bittrack=0.f;
  152227. vf->samptrack=0.f;
  152228. return 0;
  152229. }
  152230. static int _open_seekable2(OggVorbis_File *vf){
  152231. long serialno=vf->current_serialno;
  152232. ogg_int64_t dataoffset=vf->offset, end;
  152233. ogg_page og;
  152234. /* we're partially open and have a first link header state in
  152235. storage in vf */
  152236. /* we can seek, so set out learning all about this file */
  152237. (vf->callbacks.seek_func)(vf->datasource,0,SEEK_END);
  152238. vf->offset=vf->end=(vf->callbacks.tell_func)(vf->datasource);
  152239. /* We get the offset for the last page of the physical bitstream.
  152240. Most OggVorbis files will contain a single logical bitstream */
  152241. end=_get_prev_page(vf,&og);
  152242. if(end<0)return(end);
  152243. /* more than one logical bitstream? */
  152244. if(ogg_page_serialno(&og)!=serialno){
  152245. /* Chained bitstream. Bisect-search each logical bitstream
  152246. section. Do so based on serial number only */
  152247. if(_bisect_forward_serialno(vf,0,0,end+1,serialno,0)<0)return(OV_EREAD);
  152248. }else{
  152249. /* Only one logical bitstream */
  152250. if(_bisect_forward_serialno(vf,0,end,end+1,serialno,0))return(OV_EREAD);
  152251. }
  152252. /* the initial header memory is referenced by vf after; don't free it */
  152253. _prefetch_all_headers(vf,dataoffset);
  152254. return(ov_raw_seek(vf,0));
  152255. }
  152256. /* clear out the current logical bitstream decoder */
  152257. static void _decode_clear(OggVorbis_File *vf){
  152258. vorbis_dsp_clear(&vf->vd);
  152259. vorbis_block_clear(&vf->vb);
  152260. vf->ready_state=OPENED;
  152261. }
  152262. /* fetch and process a packet. Handles the case where we're at a
  152263. bitstream boundary and dumps the decoding machine. If the decoding
  152264. machine is unloaded, it loads it. It also keeps pcm_offset up to
  152265. date (seek and read both use this. seek uses a special hack with
  152266. readp).
  152267. return: <0) error, OV_HOLE (lost packet) or OV_EOF
  152268. 0) need more data (only if readp==0)
  152269. 1) got a packet
  152270. */
  152271. static int _fetch_and_process_packet(OggVorbis_File *vf,
  152272. ogg_packet *op_in,
  152273. int readp,
  152274. int spanp){
  152275. ogg_page og;
  152276. /* handle one packet. Try to fetch it from current stream state */
  152277. /* extract packets from page */
  152278. while(1){
  152279. /* process a packet if we can. If the machine isn't loaded,
  152280. neither is a page */
  152281. if(vf->ready_state==INITSET){
  152282. while(1) {
  152283. ogg_packet op;
  152284. ogg_packet *op_ptr=(op_in?op_in:&op);
  152285. int result=ogg_stream_packetout(&vf->os,op_ptr);
  152286. ogg_int64_t granulepos;
  152287. op_in=NULL;
  152288. if(result==-1)return(OV_HOLE); /* hole in the data. */
  152289. if(result>0){
  152290. /* got a packet. process it */
  152291. granulepos=op_ptr->granulepos;
  152292. if(!vorbis_synthesis(&vf->vb,op_ptr)){ /* lazy check for lazy
  152293. header handling. The
  152294. header packets aren't
  152295. audio, so if/when we
  152296. submit them,
  152297. vorbis_synthesis will
  152298. reject them */
  152299. /* suck in the synthesis data and track bitrate */
  152300. {
  152301. int oldsamples=vorbis_synthesis_pcmout(&vf->vd,NULL);
  152302. /* for proper use of libvorbis within libvorbisfile,
  152303. oldsamples will always be zero. */
  152304. if(oldsamples)return(OV_EFAULT);
  152305. vorbis_synthesis_blockin(&vf->vd,&vf->vb);
  152306. vf->samptrack+=vorbis_synthesis_pcmout(&vf->vd,NULL)-oldsamples;
  152307. vf->bittrack+=op_ptr->bytes*8;
  152308. }
  152309. /* update the pcm offset. */
  152310. if(granulepos!=-1 && !op_ptr->e_o_s){
  152311. int link=(vf->seekable?vf->current_link:0);
  152312. int i,samples;
  152313. /* this packet has a pcm_offset on it (the last packet
  152314. completed on a page carries the offset) After processing
  152315. (above), we know the pcm position of the *last* sample
  152316. ready to be returned. Find the offset of the *first*
  152317. As an aside, this trick is inaccurate if we begin
  152318. reading anew right at the last page; the end-of-stream
  152319. granulepos declares the last frame in the stream, and the
  152320. last packet of the last page may be a partial frame.
  152321. So, we need a previous granulepos from an in-sequence page
  152322. to have a reference point. Thus the !op_ptr->e_o_s clause
  152323. above */
  152324. if(vf->seekable && link>0)
  152325. granulepos-=vf->pcmlengths[link*2];
  152326. if(granulepos<0)granulepos=0; /* actually, this
  152327. shouldn't be possible
  152328. here unless the stream
  152329. is very broken */
  152330. samples=vorbis_synthesis_pcmout(&vf->vd,NULL);
  152331. granulepos-=samples;
  152332. for(i=0;i<link;i++)
  152333. granulepos+=vf->pcmlengths[i*2+1];
  152334. vf->pcm_offset=granulepos;
  152335. }
  152336. return(1);
  152337. }
  152338. }
  152339. else
  152340. break;
  152341. }
  152342. }
  152343. if(vf->ready_state>=OPENED){
  152344. ogg_int64_t ret;
  152345. if(!readp)return(0);
  152346. if((ret=_get_next_page(vf,&og,-1))<0){
  152347. return(OV_EOF); /* eof.
  152348. leave unitialized */
  152349. }
  152350. /* bitrate tracking; add the header's bytes here, the body bytes
  152351. are done by packet above */
  152352. vf->bittrack+=og.header_len*8;
  152353. /* has our decoding just traversed a bitstream boundary? */
  152354. if(vf->ready_state==INITSET){
  152355. if(vf->current_serialno!=ogg_page_serialno(&og)){
  152356. if(!spanp)
  152357. return(OV_EOF);
  152358. _decode_clear(vf);
  152359. if(!vf->seekable){
  152360. vorbis_info_clear(vf->vi);
  152361. vorbis_comment_clear(vf->vc);
  152362. }
  152363. }
  152364. }
  152365. }
  152366. /* Do we need to load a new machine before submitting the page? */
  152367. /* This is different in the seekable and non-seekable cases.
  152368. In the seekable case, we already have all the header
  152369. information loaded and cached; we just initialize the machine
  152370. with it and continue on our merry way.
  152371. In the non-seekable (streaming) case, we'll only be at a
  152372. boundary if we just left the previous logical bitstream and
  152373. we're now nominally at the header of the next bitstream
  152374. */
  152375. if(vf->ready_state!=INITSET){
  152376. int link;
  152377. if(vf->ready_state<STREAMSET){
  152378. if(vf->seekable){
  152379. vf->current_serialno=ogg_page_serialno(&og);
  152380. /* match the serialno to bitstream section. We use this rather than
  152381. offset positions to avoid problems near logical bitstream
  152382. boundaries */
  152383. for(link=0;link<vf->links;link++)
  152384. if(vf->serialnos[link]==vf->current_serialno)break;
  152385. if(link==vf->links)return(OV_EBADLINK); /* sign of a bogus
  152386. stream. error out,
  152387. leave machine
  152388. uninitialized */
  152389. vf->current_link=link;
  152390. ogg_stream_reset_serialno(&vf->os,vf->current_serialno);
  152391. vf->ready_state=STREAMSET;
  152392. }else{
  152393. /* we're streaming */
  152394. /* fetch the three header packets, build the info struct */
  152395. int ret=_fetch_headers(vf,vf->vi,vf->vc,&vf->current_serialno,&og);
  152396. if(ret)return(ret);
  152397. vf->current_link++;
  152398. link=0;
  152399. }
  152400. }
  152401. {
  152402. int ret=_make_decode_ready(vf);
  152403. if(ret<0)return ret;
  152404. }
  152405. }
  152406. ogg_stream_pagein(&vf->os,&og);
  152407. }
  152408. }
  152409. /* if, eg, 64 bit stdio is configured by default, this will build with
  152410. fseek64 */
  152411. static int _fseek64_wrap(FILE *f,ogg_int64_t off,int whence){
  152412. if(f==NULL)return(-1);
  152413. return fseek(f,off,whence);
  152414. }
  152415. static int _ov_open1(void *f,OggVorbis_File *vf,char *initial,
  152416. long ibytes, ov_callbacks callbacks){
  152417. int offsettest=(f?callbacks.seek_func(f,0,SEEK_CUR):-1);
  152418. int ret;
  152419. memset(vf,0,sizeof(*vf));
  152420. vf->datasource=f;
  152421. vf->callbacks = callbacks;
  152422. /* init the framing state */
  152423. ogg_sync_init(&vf->oy);
  152424. /* perhaps some data was previously read into a buffer for testing
  152425. against other stream types. Allow initialization from this
  152426. previously read data (as we may be reading from a non-seekable
  152427. stream) */
  152428. if(initial){
  152429. char *buffer=ogg_sync_buffer(&vf->oy,ibytes);
  152430. memcpy(buffer,initial,ibytes);
  152431. ogg_sync_wrote(&vf->oy,ibytes);
  152432. }
  152433. /* can we seek? Stevens suggests the seek test was portable */
  152434. if(offsettest!=-1)vf->seekable=1;
  152435. /* No seeking yet; Set up a 'single' (current) logical bitstream
  152436. entry for partial open */
  152437. vf->links=1;
  152438. vf->vi=(vorbis_info*) _ogg_calloc(vf->links,sizeof(*vf->vi));
  152439. vf->vc=(vorbis_comment*) _ogg_calloc(vf->links,sizeof(*vf->vc));
  152440. ogg_stream_init(&vf->os,-1); /* fill in the serialno later */
  152441. /* Try to fetch the headers, maintaining all the storage */
  152442. if((ret=_fetch_headers(vf,vf->vi,vf->vc,&vf->current_serialno,NULL))<0){
  152443. vf->datasource=NULL;
  152444. ov_clear(vf);
  152445. }else
  152446. vf->ready_state=PARTOPEN;
  152447. return(ret);
  152448. }
  152449. static int _ov_open2(OggVorbis_File *vf){
  152450. if(vf->ready_state != PARTOPEN) return OV_EINVAL;
  152451. vf->ready_state=OPENED;
  152452. if(vf->seekable){
  152453. int ret=_open_seekable2(vf);
  152454. if(ret){
  152455. vf->datasource=NULL;
  152456. ov_clear(vf);
  152457. }
  152458. return(ret);
  152459. }else
  152460. vf->ready_state=STREAMSET;
  152461. return 0;
  152462. }
  152463. /* clear out the OggVorbis_File struct */
  152464. int ov_clear(OggVorbis_File *vf){
  152465. if(vf){
  152466. vorbis_block_clear(&vf->vb);
  152467. vorbis_dsp_clear(&vf->vd);
  152468. ogg_stream_clear(&vf->os);
  152469. if(vf->vi && vf->links){
  152470. int i;
  152471. for(i=0;i<vf->links;i++){
  152472. vorbis_info_clear(vf->vi+i);
  152473. vorbis_comment_clear(vf->vc+i);
  152474. }
  152475. _ogg_free(vf->vi);
  152476. _ogg_free(vf->vc);
  152477. }
  152478. if(vf->dataoffsets)_ogg_free(vf->dataoffsets);
  152479. if(vf->pcmlengths)_ogg_free(vf->pcmlengths);
  152480. if(vf->serialnos)_ogg_free(vf->serialnos);
  152481. if(vf->offsets)_ogg_free(vf->offsets);
  152482. ogg_sync_clear(&vf->oy);
  152483. if(vf->datasource)(vf->callbacks.close_func)(vf->datasource);
  152484. memset(vf,0,sizeof(*vf));
  152485. }
  152486. #ifdef DEBUG_LEAKS
  152487. _VDBG_dump();
  152488. #endif
  152489. return(0);
  152490. }
  152491. /* inspects the OggVorbis file and finds/documents all the logical
  152492. bitstreams contained in it. Tries to be tolerant of logical
  152493. bitstream sections that are truncated/woogie.
  152494. return: -1) error
  152495. 0) OK
  152496. */
  152497. int ov_open_callbacks(void *f,OggVorbis_File *vf,char *initial,long ibytes,
  152498. ov_callbacks callbacks){
  152499. int ret=_ov_open1(f,vf,initial,ibytes,callbacks);
  152500. if(ret)return ret;
  152501. return _ov_open2(vf);
  152502. }
  152503. int ov_open(FILE *f,OggVorbis_File *vf,char *initial,long ibytes){
  152504. ov_callbacks callbacks = {
  152505. (size_t (*)(void *, size_t, size_t, void *)) fread,
  152506. (int (*)(void *, ogg_int64_t, int)) _fseek64_wrap,
  152507. (int (*)(void *)) fclose,
  152508. (long (*)(void *)) ftell
  152509. };
  152510. return ov_open_callbacks((void *)f, vf, initial, ibytes, callbacks);
  152511. }
  152512. /* cheap hack for game usage where downsampling is desirable; there's
  152513. no need for SRC as we can just do it cheaply in libvorbis. */
  152514. int ov_halfrate(OggVorbis_File *vf,int flag){
  152515. int i;
  152516. if(vf->vi==NULL)return OV_EINVAL;
  152517. if(!vf->seekable)return OV_EINVAL;
  152518. if(vf->ready_state>=STREAMSET)
  152519. _decode_clear(vf); /* clear out stream state; later on libvorbis
  152520. will be able to swap this on the fly, but
  152521. for now dumping the decode machine is needed
  152522. to reinit the MDCT lookups. 1.1 libvorbis
  152523. is planned to be able to switch on the fly */
  152524. for(i=0;i<vf->links;i++){
  152525. if(vorbis_synthesis_halfrate(vf->vi+i,flag)){
  152526. ov_halfrate(vf,0);
  152527. return OV_EINVAL;
  152528. }
  152529. }
  152530. return 0;
  152531. }
  152532. int ov_halfrate_p(OggVorbis_File *vf){
  152533. if(vf->vi==NULL)return OV_EINVAL;
  152534. return vorbis_synthesis_halfrate_p(vf->vi);
  152535. }
  152536. /* Only partially open the vorbis file; test for Vorbisness, and load
  152537. the headers for the first chain. Do not seek (although test for
  152538. seekability). Use ov_test_open to finish opening the file, else
  152539. ov_clear to close/free it. Same return codes as open. */
  152540. int ov_test_callbacks(void *f,OggVorbis_File *vf,char *initial,long ibytes,
  152541. ov_callbacks callbacks)
  152542. {
  152543. return _ov_open1(f,vf,initial,ibytes,callbacks);
  152544. }
  152545. int ov_test(FILE *f,OggVorbis_File *vf,char *initial,long ibytes){
  152546. ov_callbacks callbacks = {
  152547. (size_t (*)(void *, size_t, size_t, void *)) fread,
  152548. (int (*)(void *, ogg_int64_t, int)) _fseek64_wrap,
  152549. (int (*)(void *)) fclose,
  152550. (long (*)(void *)) ftell
  152551. };
  152552. return ov_test_callbacks((void *)f, vf, initial, ibytes, callbacks);
  152553. }
  152554. int ov_test_open(OggVorbis_File *vf){
  152555. if(vf->ready_state!=PARTOPEN)return(OV_EINVAL);
  152556. return _ov_open2(vf);
  152557. }
  152558. /* How many logical bitstreams in this physical bitstream? */
  152559. long ov_streams(OggVorbis_File *vf){
  152560. return vf->links;
  152561. }
  152562. /* Is the FILE * associated with vf seekable? */
  152563. long ov_seekable(OggVorbis_File *vf){
  152564. return vf->seekable;
  152565. }
  152566. /* returns the bitrate for a given logical bitstream or the entire
  152567. physical bitstream. If the file is open for random access, it will
  152568. find the *actual* average bitrate. If the file is streaming, it
  152569. returns the nominal bitrate (if set) else the average of the
  152570. upper/lower bounds (if set) else -1 (unset).
  152571. If you want the actual bitrate field settings, get them from the
  152572. vorbis_info structs */
  152573. long ov_bitrate(OggVorbis_File *vf,int i){
  152574. if(vf->ready_state<OPENED)return(OV_EINVAL);
  152575. if(i>=vf->links)return(OV_EINVAL);
  152576. if(!vf->seekable && i!=0)return(ov_bitrate(vf,0));
  152577. if(i<0){
  152578. ogg_int64_t bits=0;
  152579. int i;
  152580. float br;
  152581. for(i=0;i<vf->links;i++)
  152582. bits+=(vf->offsets[i+1]-vf->dataoffsets[i])*8;
  152583. /* This once read: return(rint(bits/ov_time_total(vf,-1)));
  152584. * gcc 3.x on x86 miscompiled this at optimisation level 2 and above,
  152585. * so this is slightly transformed to make it work.
  152586. */
  152587. br = bits/ov_time_total(vf,-1);
  152588. return(rint(br));
  152589. }else{
  152590. if(vf->seekable){
  152591. /* return the actual bitrate */
  152592. return(rint((vf->offsets[i+1]-vf->dataoffsets[i])*8/ov_time_total(vf,i)));
  152593. }else{
  152594. /* return nominal if set */
  152595. if(vf->vi[i].bitrate_nominal>0){
  152596. return vf->vi[i].bitrate_nominal;
  152597. }else{
  152598. if(vf->vi[i].bitrate_upper>0){
  152599. if(vf->vi[i].bitrate_lower>0){
  152600. return (vf->vi[i].bitrate_upper+vf->vi[i].bitrate_lower)/2;
  152601. }else{
  152602. return vf->vi[i].bitrate_upper;
  152603. }
  152604. }
  152605. return(OV_FALSE);
  152606. }
  152607. }
  152608. }
  152609. }
  152610. /* returns the actual bitrate since last call. returns -1 if no
  152611. additional data to offer since last call (or at beginning of stream),
  152612. EINVAL if stream is only partially open
  152613. */
  152614. long ov_bitrate_instant(OggVorbis_File *vf){
  152615. int link=(vf->seekable?vf->current_link:0);
  152616. long ret;
  152617. if(vf->ready_state<OPENED)return(OV_EINVAL);
  152618. if(vf->samptrack==0)return(OV_FALSE);
  152619. ret=vf->bittrack/vf->samptrack*vf->vi[link].rate+.5;
  152620. vf->bittrack=0.f;
  152621. vf->samptrack=0.f;
  152622. return(ret);
  152623. }
  152624. /* Guess */
  152625. long ov_serialnumber(OggVorbis_File *vf,int i){
  152626. if(i>=vf->links)return(ov_serialnumber(vf,vf->links-1));
  152627. if(!vf->seekable && i>=0)return(ov_serialnumber(vf,-1));
  152628. if(i<0){
  152629. return(vf->current_serialno);
  152630. }else{
  152631. return(vf->serialnos[i]);
  152632. }
  152633. }
  152634. /* returns: total raw (compressed) length of content if i==-1
  152635. raw (compressed) length of that logical bitstream for i==0 to n
  152636. OV_EINVAL if the stream is not seekable (we can't know the length)
  152637. or if stream is only partially open
  152638. */
  152639. ogg_int64_t ov_raw_total(OggVorbis_File *vf,int i){
  152640. if(vf->ready_state<OPENED)return(OV_EINVAL);
  152641. if(!vf->seekable || i>=vf->links)return(OV_EINVAL);
  152642. if(i<0){
  152643. ogg_int64_t acc=0;
  152644. int i;
  152645. for(i=0;i<vf->links;i++)
  152646. acc+=ov_raw_total(vf,i);
  152647. return(acc);
  152648. }else{
  152649. return(vf->offsets[i+1]-vf->offsets[i]);
  152650. }
  152651. }
  152652. /* returns: total PCM length (samples) of content if i==-1 PCM length
  152653. (samples) of that logical bitstream for i==0 to n
  152654. OV_EINVAL if the stream is not seekable (we can't know the
  152655. length) or only partially open
  152656. */
  152657. ogg_int64_t ov_pcm_total(OggVorbis_File *vf,int i){
  152658. if(vf->ready_state<OPENED)return(OV_EINVAL);
  152659. if(!vf->seekable || i>=vf->links)return(OV_EINVAL);
  152660. if(i<0){
  152661. ogg_int64_t acc=0;
  152662. int i;
  152663. for(i=0;i<vf->links;i++)
  152664. acc+=ov_pcm_total(vf,i);
  152665. return(acc);
  152666. }else{
  152667. return(vf->pcmlengths[i*2+1]);
  152668. }
  152669. }
  152670. /* returns: total seconds of content if i==-1
  152671. seconds in that logical bitstream for i==0 to n
  152672. OV_EINVAL if the stream is not seekable (we can't know the
  152673. length) or only partially open
  152674. */
  152675. double ov_time_total(OggVorbis_File *vf,int i){
  152676. if(vf->ready_state<OPENED)return(OV_EINVAL);
  152677. if(!vf->seekable || i>=vf->links)return(OV_EINVAL);
  152678. if(i<0){
  152679. double acc=0;
  152680. int i;
  152681. for(i=0;i<vf->links;i++)
  152682. acc+=ov_time_total(vf,i);
  152683. return(acc);
  152684. }else{
  152685. return((double)(vf->pcmlengths[i*2+1])/vf->vi[i].rate);
  152686. }
  152687. }
  152688. /* seek to an offset relative to the *compressed* data. This also
  152689. scans packets to update the PCM cursor. It will cross a logical
  152690. bitstream boundary, but only if it can't get any packets out of the
  152691. tail of the bitstream we seek to (so no surprises).
  152692. returns zero on success, nonzero on failure */
  152693. int ov_raw_seek(OggVorbis_File *vf,ogg_int64_t pos){
  152694. ogg_stream_state work_os;
  152695. if(vf->ready_state<OPENED)return(OV_EINVAL);
  152696. if(!vf->seekable)
  152697. return(OV_ENOSEEK); /* don't dump machine if we can't seek */
  152698. if(pos<0 || pos>vf->end)return(OV_EINVAL);
  152699. /* don't yet clear out decoding machine (if it's initialized), in
  152700. the case we're in the same link. Restart the decode lapping, and
  152701. let _fetch_and_process_packet deal with a potential bitstream
  152702. boundary */
  152703. vf->pcm_offset=-1;
  152704. ogg_stream_reset_serialno(&vf->os,
  152705. vf->current_serialno); /* must set serialno */
  152706. vorbis_synthesis_restart(&vf->vd);
  152707. _seek_helper(vf,pos);
  152708. /* we need to make sure the pcm_offset is set, but we don't want to
  152709. advance the raw cursor past good packets just to get to the first
  152710. with a granulepos. That's not equivalent behavior to beginning
  152711. decoding as immediately after the seek position as possible.
  152712. So, a hack. We use two stream states; a local scratch state and
  152713. the shared vf->os stream state. We use the local state to
  152714. scan, and the shared state as a buffer for later decode.
  152715. Unfortuantely, on the last page we still advance to last packet
  152716. because the granulepos on the last page is not necessarily on a
  152717. packet boundary, and we need to make sure the granpos is
  152718. correct.
  152719. */
  152720. {
  152721. ogg_page og;
  152722. ogg_packet op;
  152723. int lastblock=0;
  152724. int accblock=0;
  152725. int thisblock;
  152726. int eosflag;
  152727. ogg_stream_init(&work_os,vf->current_serialno); /* get the memory ready */
  152728. ogg_stream_reset(&work_os); /* eliminate the spurious OV_HOLE
  152729. return from not necessarily
  152730. starting from the beginning */
  152731. while(1){
  152732. if(vf->ready_state>=STREAMSET){
  152733. /* snarf/scan a packet if we can */
  152734. int result=ogg_stream_packetout(&work_os,&op);
  152735. if(result>0){
  152736. if(vf->vi[vf->current_link].codec_setup){
  152737. thisblock=vorbis_packet_blocksize(vf->vi+vf->current_link,&op);
  152738. if(thisblock<0){
  152739. ogg_stream_packetout(&vf->os,NULL);
  152740. thisblock=0;
  152741. }else{
  152742. if(eosflag)
  152743. ogg_stream_packetout(&vf->os,NULL);
  152744. else
  152745. if(lastblock)accblock+=(lastblock+thisblock)>>2;
  152746. }
  152747. if(op.granulepos!=-1){
  152748. int i,link=vf->current_link;
  152749. ogg_int64_t granulepos=op.granulepos-vf->pcmlengths[link*2];
  152750. if(granulepos<0)granulepos=0;
  152751. for(i=0;i<link;i++)
  152752. granulepos+=vf->pcmlengths[i*2+1];
  152753. vf->pcm_offset=granulepos-accblock;
  152754. break;
  152755. }
  152756. lastblock=thisblock;
  152757. continue;
  152758. }else
  152759. ogg_stream_packetout(&vf->os,NULL);
  152760. }
  152761. }
  152762. if(!lastblock){
  152763. if(_get_next_page(vf,&og,-1)<0){
  152764. vf->pcm_offset=ov_pcm_total(vf,-1);
  152765. break;
  152766. }
  152767. }else{
  152768. /* huh? Bogus stream with packets but no granulepos */
  152769. vf->pcm_offset=-1;
  152770. break;
  152771. }
  152772. /* has our decoding just traversed a bitstream boundary? */
  152773. if(vf->ready_state>=STREAMSET)
  152774. if(vf->current_serialno!=ogg_page_serialno(&og)){
  152775. _decode_clear(vf); /* clear out stream state */
  152776. ogg_stream_clear(&work_os);
  152777. }
  152778. if(vf->ready_state<STREAMSET){
  152779. int link;
  152780. vf->current_serialno=ogg_page_serialno(&og);
  152781. for(link=0;link<vf->links;link++)
  152782. if(vf->serialnos[link]==vf->current_serialno)break;
  152783. if(link==vf->links)goto seek_error; /* sign of a bogus stream.
  152784. error out, leave
  152785. machine uninitialized */
  152786. vf->current_link=link;
  152787. ogg_stream_reset_serialno(&vf->os,vf->current_serialno);
  152788. ogg_stream_reset_serialno(&work_os,vf->current_serialno);
  152789. vf->ready_state=STREAMSET;
  152790. }
  152791. ogg_stream_pagein(&vf->os,&og);
  152792. ogg_stream_pagein(&work_os,&og);
  152793. eosflag=ogg_page_eos(&og);
  152794. }
  152795. }
  152796. ogg_stream_clear(&work_os);
  152797. vf->bittrack=0.f;
  152798. vf->samptrack=0.f;
  152799. return(0);
  152800. seek_error:
  152801. /* dump the machine so we're in a known state */
  152802. vf->pcm_offset=-1;
  152803. ogg_stream_clear(&work_os);
  152804. _decode_clear(vf);
  152805. return OV_EBADLINK;
  152806. }
  152807. /* Page granularity seek (faster than sample granularity because we
  152808. don't do the last bit of decode to find a specific sample).
  152809. Seek to the last [granule marked] page preceeding the specified pos
  152810. location, such that decoding past the returned point will quickly
  152811. arrive at the requested position. */
  152812. int ov_pcm_seek_page(OggVorbis_File *vf,ogg_int64_t pos){
  152813. int link=-1;
  152814. ogg_int64_t result=0;
  152815. ogg_int64_t total=ov_pcm_total(vf,-1);
  152816. if(vf->ready_state<OPENED)return(OV_EINVAL);
  152817. if(!vf->seekable)return(OV_ENOSEEK);
  152818. if(pos<0 || pos>total)return(OV_EINVAL);
  152819. /* which bitstream section does this pcm offset occur in? */
  152820. for(link=vf->links-1;link>=0;link--){
  152821. total-=vf->pcmlengths[link*2+1];
  152822. if(pos>=total)break;
  152823. }
  152824. /* search within the logical bitstream for the page with the highest
  152825. pcm_pos preceeding (or equal to) pos. There is a danger here;
  152826. missing pages or incorrect frame number information in the
  152827. bitstream could make our task impossible. Account for that (it
  152828. would be an error condition) */
  152829. /* new search algorithm by HB (Nicholas Vinen) */
  152830. {
  152831. ogg_int64_t end=vf->offsets[link+1];
  152832. ogg_int64_t begin=vf->offsets[link];
  152833. ogg_int64_t begintime = vf->pcmlengths[link*2];
  152834. ogg_int64_t endtime = vf->pcmlengths[link*2+1]+begintime;
  152835. ogg_int64_t target=pos-total+begintime;
  152836. ogg_int64_t best=begin;
  152837. ogg_page og;
  152838. while(begin<end){
  152839. ogg_int64_t bisect;
  152840. if(end-begin<CHUNKSIZE){
  152841. bisect=begin;
  152842. }else{
  152843. /* take a (pretty decent) guess. */
  152844. bisect=begin +
  152845. (target-begintime)*(end-begin)/(endtime-begintime) - CHUNKSIZE;
  152846. if(bisect<=begin)
  152847. bisect=begin+1;
  152848. }
  152849. _seek_helper(vf,bisect);
  152850. while(begin<end){
  152851. result=_get_next_page(vf,&og,end-vf->offset);
  152852. if(result==OV_EREAD) goto seek_error;
  152853. if(result<0){
  152854. if(bisect<=begin+1)
  152855. end=begin; /* found it */
  152856. else{
  152857. if(bisect==0) goto seek_error;
  152858. bisect-=CHUNKSIZE;
  152859. if(bisect<=begin)bisect=begin+1;
  152860. _seek_helper(vf,bisect);
  152861. }
  152862. }else{
  152863. ogg_int64_t granulepos=ogg_page_granulepos(&og);
  152864. if(granulepos==-1)continue;
  152865. if(granulepos<target){
  152866. best=result; /* raw offset of packet with granulepos */
  152867. begin=vf->offset; /* raw offset of next page */
  152868. begintime=granulepos;
  152869. if(target-begintime>44100)break;
  152870. bisect=begin; /* *not* begin + 1 */
  152871. }else{
  152872. if(bisect<=begin+1)
  152873. end=begin; /* found it */
  152874. else{
  152875. if(end==vf->offset){ /* we're pretty close - we'd be stuck in */
  152876. end=result;
  152877. bisect-=CHUNKSIZE; /* an endless loop otherwise. */
  152878. if(bisect<=begin)bisect=begin+1;
  152879. _seek_helper(vf,bisect);
  152880. }else{
  152881. end=result;
  152882. endtime=granulepos;
  152883. break;
  152884. }
  152885. }
  152886. }
  152887. }
  152888. }
  152889. }
  152890. /* found our page. seek to it, update pcm offset. Easier case than
  152891. raw_seek, don't keep packets preceeding granulepos. */
  152892. {
  152893. ogg_page og;
  152894. ogg_packet op;
  152895. /* seek */
  152896. _seek_helper(vf,best);
  152897. vf->pcm_offset=-1;
  152898. if(_get_next_page(vf,&og,-1)<0)return(OV_EOF); /* shouldn't happen */
  152899. if(link!=vf->current_link){
  152900. /* Different link; dump entire decode machine */
  152901. _decode_clear(vf);
  152902. vf->current_link=link;
  152903. vf->current_serialno=ogg_page_serialno(&og);
  152904. vf->ready_state=STREAMSET;
  152905. }else{
  152906. vorbis_synthesis_restart(&vf->vd);
  152907. }
  152908. ogg_stream_reset_serialno(&vf->os,vf->current_serialno);
  152909. ogg_stream_pagein(&vf->os,&og);
  152910. /* pull out all but last packet; the one with granulepos */
  152911. while(1){
  152912. result=ogg_stream_packetpeek(&vf->os,&op);
  152913. if(result==0){
  152914. /* !!! the packet finishing this page originated on a
  152915. preceeding page. Keep fetching previous pages until we
  152916. get one with a granulepos or without the 'continued' flag
  152917. set. Then just use raw_seek for simplicity. */
  152918. _seek_helper(vf,best);
  152919. while(1){
  152920. result=_get_prev_page(vf,&og);
  152921. if(result<0) goto seek_error;
  152922. if(ogg_page_granulepos(&og)>-1 ||
  152923. !ogg_page_continued(&og)){
  152924. return ov_raw_seek(vf,result);
  152925. }
  152926. vf->offset=result;
  152927. }
  152928. }
  152929. if(result<0){
  152930. result = OV_EBADPACKET;
  152931. goto seek_error;
  152932. }
  152933. if(op.granulepos!=-1){
  152934. vf->pcm_offset=op.granulepos-vf->pcmlengths[vf->current_link*2];
  152935. if(vf->pcm_offset<0)vf->pcm_offset=0;
  152936. vf->pcm_offset+=total;
  152937. break;
  152938. }else
  152939. result=ogg_stream_packetout(&vf->os,NULL);
  152940. }
  152941. }
  152942. }
  152943. /* verify result */
  152944. if(vf->pcm_offset>pos || pos>ov_pcm_total(vf,-1)){
  152945. result=OV_EFAULT;
  152946. goto seek_error;
  152947. }
  152948. vf->bittrack=0.f;
  152949. vf->samptrack=0.f;
  152950. return(0);
  152951. seek_error:
  152952. /* dump machine so we're in a known state */
  152953. vf->pcm_offset=-1;
  152954. _decode_clear(vf);
  152955. return (int)result;
  152956. }
  152957. /* seek to a sample offset relative to the decompressed pcm stream
  152958. returns zero on success, nonzero on failure */
  152959. int ov_pcm_seek(OggVorbis_File *vf,ogg_int64_t pos){
  152960. int thisblock,lastblock=0;
  152961. int ret=ov_pcm_seek_page(vf,pos);
  152962. if(ret<0)return(ret);
  152963. if((ret=_make_decode_ready(vf)))return ret;
  152964. /* discard leading packets we don't need for the lapping of the
  152965. position we want; don't decode them */
  152966. while(1){
  152967. ogg_packet op;
  152968. ogg_page og;
  152969. int ret=ogg_stream_packetpeek(&vf->os,&op);
  152970. if(ret>0){
  152971. thisblock=vorbis_packet_blocksize(vf->vi+vf->current_link,&op);
  152972. if(thisblock<0){
  152973. ogg_stream_packetout(&vf->os,NULL);
  152974. continue; /* non audio packet */
  152975. }
  152976. if(lastblock)vf->pcm_offset+=(lastblock+thisblock)>>2;
  152977. if(vf->pcm_offset+((thisblock+
  152978. vorbis_info_blocksize(vf->vi,1))>>2)>=pos)break;
  152979. /* remove the packet from packet queue and track its granulepos */
  152980. ogg_stream_packetout(&vf->os,NULL);
  152981. vorbis_synthesis_trackonly(&vf->vb,&op); /* set up a vb with
  152982. only tracking, no
  152983. pcm_decode */
  152984. vorbis_synthesis_blockin(&vf->vd,&vf->vb);
  152985. /* end of logical stream case is hard, especially with exact
  152986. length positioning. */
  152987. if(op.granulepos>-1){
  152988. int i;
  152989. /* always believe the stream markers */
  152990. vf->pcm_offset=op.granulepos-vf->pcmlengths[vf->current_link*2];
  152991. if(vf->pcm_offset<0)vf->pcm_offset=0;
  152992. for(i=0;i<vf->current_link;i++)
  152993. vf->pcm_offset+=vf->pcmlengths[i*2+1];
  152994. }
  152995. lastblock=thisblock;
  152996. }else{
  152997. if(ret<0 && ret!=OV_HOLE)break;
  152998. /* suck in a new page */
  152999. if(_get_next_page(vf,&og,-1)<0)break;
  153000. if(vf->current_serialno!=ogg_page_serialno(&og))_decode_clear(vf);
  153001. if(vf->ready_state<STREAMSET){
  153002. int link;
  153003. vf->current_serialno=ogg_page_serialno(&og);
  153004. for(link=0;link<vf->links;link++)
  153005. if(vf->serialnos[link]==vf->current_serialno)break;
  153006. if(link==vf->links)return(OV_EBADLINK);
  153007. vf->current_link=link;
  153008. ogg_stream_reset_serialno(&vf->os,vf->current_serialno);
  153009. vf->ready_state=STREAMSET;
  153010. ret=_make_decode_ready(vf);
  153011. if(ret)return ret;
  153012. lastblock=0;
  153013. }
  153014. ogg_stream_pagein(&vf->os,&og);
  153015. }
  153016. }
  153017. vf->bittrack=0.f;
  153018. vf->samptrack=0.f;
  153019. /* discard samples until we reach the desired position. Crossing a
  153020. logical bitstream boundary with abandon is OK. */
  153021. while(vf->pcm_offset<pos){
  153022. ogg_int64_t target=pos-vf->pcm_offset;
  153023. long samples=vorbis_synthesis_pcmout(&vf->vd,NULL);
  153024. if(samples>target)samples=target;
  153025. vorbis_synthesis_read(&vf->vd,samples);
  153026. vf->pcm_offset+=samples;
  153027. if(samples<target)
  153028. if(_fetch_and_process_packet(vf,NULL,1,1)<=0)
  153029. vf->pcm_offset=ov_pcm_total(vf,-1); /* eof */
  153030. }
  153031. return 0;
  153032. }
  153033. /* seek to a playback time relative to the decompressed pcm stream
  153034. returns zero on success, nonzero on failure */
  153035. int ov_time_seek(OggVorbis_File *vf,double seconds){
  153036. /* translate time to PCM position and call ov_pcm_seek */
  153037. int link=-1;
  153038. ogg_int64_t pcm_total=ov_pcm_total(vf,-1);
  153039. double time_total=ov_time_total(vf,-1);
  153040. if(vf->ready_state<OPENED)return(OV_EINVAL);
  153041. if(!vf->seekable)return(OV_ENOSEEK);
  153042. if(seconds<0 || seconds>time_total)return(OV_EINVAL);
  153043. /* which bitstream section does this time offset occur in? */
  153044. for(link=vf->links-1;link>=0;link--){
  153045. pcm_total-=vf->pcmlengths[link*2+1];
  153046. time_total-=ov_time_total(vf,link);
  153047. if(seconds>=time_total)break;
  153048. }
  153049. /* enough information to convert time offset to pcm offset */
  153050. {
  153051. ogg_int64_t target=pcm_total+(seconds-time_total)*vf->vi[link].rate;
  153052. return(ov_pcm_seek(vf,target));
  153053. }
  153054. }
  153055. /* page-granularity version of ov_time_seek
  153056. returns zero on success, nonzero on failure */
  153057. int ov_time_seek_page(OggVorbis_File *vf,double seconds){
  153058. /* translate time to PCM position and call ov_pcm_seek */
  153059. int link=-1;
  153060. ogg_int64_t pcm_total=ov_pcm_total(vf,-1);
  153061. double time_total=ov_time_total(vf,-1);
  153062. if(vf->ready_state<OPENED)return(OV_EINVAL);
  153063. if(!vf->seekable)return(OV_ENOSEEK);
  153064. if(seconds<0 || seconds>time_total)return(OV_EINVAL);
  153065. /* which bitstream section does this time offset occur in? */
  153066. for(link=vf->links-1;link>=0;link--){
  153067. pcm_total-=vf->pcmlengths[link*2+1];
  153068. time_total-=ov_time_total(vf,link);
  153069. if(seconds>=time_total)break;
  153070. }
  153071. /* enough information to convert time offset to pcm offset */
  153072. {
  153073. ogg_int64_t target=pcm_total+(seconds-time_total)*vf->vi[link].rate;
  153074. return(ov_pcm_seek_page(vf,target));
  153075. }
  153076. }
  153077. /* tell the current stream offset cursor. Note that seek followed by
  153078. tell will likely not give the set offset due to caching */
  153079. ogg_int64_t ov_raw_tell(OggVorbis_File *vf){
  153080. if(vf->ready_state<OPENED)return(OV_EINVAL);
  153081. return(vf->offset);
  153082. }
  153083. /* return PCM offset (sample) of next PCM sample to be read */
  153084. ogg_int64_t ov_pcm_tell(OggVorbis_File *vf){
  153085. if(vf->ready_state<OPENED)return(OV_EINVAL);
  153086. return(vf->pcm_offset);
  153087. }
  153088. /* return time offset (seconds) of next PCM sample to be read */
  153089. double ov_time_tell(OggVorbis_File *vf){
  153090. int link=0;
  153091. ogg_int64_t pcm_total=0;
  153092. double time_total=0.f;
  153093. if(vf->ready_state<OPENED)return(OV_EINVAL);
  153094. if(vf->seekable){
  153095. pcm_total=ov_pcm_total(vf,-1);
  153096. time_total=ov_time_total(vf,-1);
  153097. /* which bitstream section does this time offset occur in? */
  153098. for(link=vf->links-1;link>=0;link--){
  153099. pcm_total-=vf->pcmlengths[link*2+1];
  153100. time_total-=ov_time_total(vf,link);
  153101. if(vf->pcm_offset>=pcm_total)break;
  153102. }
  153103. }
  153104. return((double)time_total+(double)(vf->pcm_offset-pcm_total)/vf->vi[link].rate);
  153105. }
  153106. /* link: -1) return the vorbis_info struct for the bitstream section
  153107. currently being decoded
  153108. 0-n) to request information for a specific bitstream section
  153109. In the case of a non-seekable bitstream, any call returns the
  153110. current bitstream. NULL in the case that the machine is not
  153111. initialized */
  153112. vorbis_info *ov_info(OggVorbis_File *vf,int link){
  153113. if(vf->seekable){
  153114. if(link<0)
  153115. if(vf->ready_state>=STREAMSET)
  153116. return vf->vi+vf->current_link;
  153117. else
  153118. return vf->vi;
  153119. else
  153120. if(link>=vf->links)
  153121. return NULL;
  153122. else
  153123. return vf->vi+link;
  153124. }else{
  153125. return vf->vi;
  153126. }
  153127. }
  153128. /* grr, strong typing, grr, no templates/inheritence, grr */
  153129. vorbis_comment *ov_comment(OggVorbis_File *vf,int link){
  153130. if(vf->seekable){
  153131. if(link<0)
  153132. if(vf->ready_state>=STREAMSET)
  153133. return vf->vc+vf->current_link;
  153134. else
  153135. return vf->vc;
  153136. else
  153137. if(link>=vf->links)
  153138. return NULL;
  153139. else
  153140. return vf->vc+link;
  153141. }else{
  153142. return vf->vc;
  153143. }
  153144. }
  153145. static int host_is_big_endian() {
  153146. ogg_int32_t pattern = 0xfeedface; /* deadbeef */
  153147. unsigned char *bytewise = (unsigned char *)&pattern;
  153148. if (bytewise[0] == 0xfe) return 1;
  153149. return 0;
  153150. }
  153151. /* up to this point, everything could more or less hide the multiple
  153152. logical bitstream nature of chaining from the toplevel application
  153153. if the toplevel application didn't particularly care. However, at
  153154. the point that we actually read audio back, the multiple-section
  153155. nature must surface: Multiple bitstream sections do not necessarily
  153156. have to have the same number of channels or sampling rate.
  153157. ov_read returns the sequential logical bitstream number currently
  153158. being decoded along with the PCM data in order that the toplevel
  153159. application can take action on channel/sample rate changes. This
  153160. number will be incremented even for streamed (non-seekable) streams
  153161. (for seekable streams, it represents the actual logical bitstream
  153162. index within the physical bitstream. Note that the accessor
  153163. functions above are aware of this dichotomy).
  153164. input values: buffer) a buffer to hold packed PCM data for return
  153165. length) the byte length requested to be placed into buffer
  153166. bigendianp) should the data be packed LSB first (0) or
  153167. MSB first (1)
  153168. word) word size for output. currently 1 (byte) or
  153169. 2 (16 bit short)
  153170. return values: <0) error/hole in data (OV_HOLE), partial open (OV_EINVAL)
  153171. 0) EOF
  153172. n) number of bytes of PCM actually returned. The
  153173. below works on a packet-by-packet basis, so the
  153174. return length is not related to the 'length' passed
  153175. in, just guaranteed to fit.
  153176. *section) set to the logical bitstream number */
  153177. long ov_read(OggVorbis_File *vf,char *buffer,int length,
  153178. int bigendianp,int word,int sgned,int *bitstream){
  153179. int i,j;
  153180. int host_endian = host_is_big_endian();
  153181. float **pcm;
  153182. long samples;
  153183. if(vf->ready_state<OPENED)return(OV_EINVAL);
  153184. while(1){
  153185. if(vf->ready_state==INITSET){
  153186. samples=vorbis_synthesis_pcmout(&vf->vd,&pcm);
  153187. if(samples)break;
  153188. }
  153189. /* suck in another packet */
  153190. {
  153191. int ret=_fetch_and_process_packet(vf,NULL,1,1);
  153192. if(ret==OV_EOF)
  153193. return(0);
  153194. if(ret<=0)
  153195. return(ret);
  153196. }
  153197. }
  153198. if(samples>0){
  153199. /* yay! proceed to pack data into the byte buffer */
  153200. long channels=ov_info(vf,-1)->channels;
  153201. long bytespersample=word * channels;
  153202. vorbis_fpu_control fpu;
  153203. (void) fpu; // (to avoid a warning about it being unused)
  153204. if(samples>length/bytespersample)samples=length/bytespersample;
  153205. if(samples <= 0)
  153206. return OV_EINVAL;
  153207. /* a tight loop to pack each size */
  153208. {
  153209. int val;
  153210. if(word==1){
  153211. int off=(sgned?0:128);
  153212. vorbis_fpu_setround(&fpu);
  153213. for(j=0;j<samples;j++)
  153214. for(i=0;i<channels;i++){
  153215. val=vorbis_ftoi(pcm[i][j]*128.f);
  153216. if(val>127)val=127;
  153217. else if(val<-128)val=-128;
  153218. *buffer++=val+off;
  153219. }
  153220. vorbis_fpu_restore(fpu);
  153221. }else{
  153222. int off=(sgned?0:32768);
  153223. if(host_endian==bigendianp){
  153224. if(sgned){
  153225. vorbis_fpu_setround(&fpu);
  153226. for(i=0;i<channels;i++) { /* It's faster in this order */
  153227. float *src=pcm[i];
  153228. short *dest=((short *)buffer)+i;
  153229. for(j=0;j<samples;j++) {
  153230. val=vorbis_ftoi(src[j]*32768.f);
  153231. if(val>32767)val=32767;
  153232. else if(val<-32768)val=-32768;
  153233. *dest=val;
  153234. dest+=channels;
  153235. }
  153236. }
  153237. vorbis_fpu_restore(fpu);
  153238. }else{
  153239. vorbis_fpu_setround(&fpu);
  153240. for(i=0;i<channels;i++) {
  153241. float *src=pcm[i];
  153242. short *dest=((short *)buffer)+i;
  153243. for(j=0;j<samples;j++) {
  153244. val=vorbis_ftoi(src[j]*32768.f);
  153245. if(val>32767)val=32767;
  153246. else if(val<-32768)val=-32768;
  153247. *dest=val+off;
  153248. dest+=channels;
  153249. }
  153250. }
  153251. vorbis_fpu_restore(fpu);
  153252. }
  153253. }else if(bigendianp){
  153254. vorbis_fpu_setround(&fpu);
  153255. for(j=0;j<samples;j++)
  153256. for(i=0;i<channels;i++){
  153257. val=vorbis_ftoi(pcm[i][j]*32768.f);
  153258. if(val>32767)val=32767;
  153259. else if(val<-32768)val=-32768;
  153260. val+=off;
  153261. *buffer++=(val>>8);
  153262. *buffer++=(val&0xff);
  153263. }
  153264. vorbis_fpu_restore(fpu);
  153265. }else{
  153266. int val;
  153267. vorbis_fpu_setround(&fpu);
  153268. for(j=0;j<samples;j++)
  153269. for(i=0;i<channels;i++){
  153270. val=vorbis_ftoi(pcm[i][j]*32768.f);
  153271. if(val>32767)val=32767;
  153272. else if(val<-32768)val=-32768;
  153273. val+=off;
  153274. *buffer++=(val&0xff);
  153275. *buffer++=(val>>8);
  153276. }
  153277. vorbis_fpu_restore(fpu);
  153278. }
  153279. }
  153280. }
  153281. vorbis_synthesis_read(&vf->vd,samples);
  153282. vf->pcm_offset+=samples;
  153283. if(bitstream)*bitstream=vf->current_link;
  153284. return(samples*bytespersample);
  153285. }else{
  153286. return(samples);
  153287. }
  153288. }
  153289. /* input values: pcm_channels) a float vector per channel of output
  153290. length) the sample length being read by the app
  153291. return values: <0) error/hole in data (OV_HOLE), partial open (OV_EINVAL)
  153292. 0) EOF
  153293. n) number of samples of PCM actually returned. The
  153294. below works on a packet-by-packet basis, so the
  153295. return length is not related to the 'length' passed
  153296. in, just guaranteed to fit.
  153297. *section) set to the logical bitstream number */
  153298. long ov_read_float(OggVorbis_File *vf,float ***pcm_channels,int length,
  153299. int *bitstream){
  153300. if(vf->ready_state<OPENED)return(OV_EINVAL);
  153301. while(1){
  153302. if(vf->ready_state==INITSET){
  153303. float **pcm;
  153304. long samples=vorbis_synthesis_pcmout(&vf->vd,&pcm);
  153305. if(samples){
  153306. if(pcm_channels)*pcm_channels=pcm;
  153307. if(samples>length)samples=length;
  153308. vorbis_synthesis_read(&vf->vd,samples);
  153309. vf->pcm_offset+=samples;
  153310. if(bitstream)*bitstream=vf->current_link;
  153311. return samples;
  153312. }
  153313. }
  153314. /* suck in another packet */
  153315. {
  153316. int ret=_fetch_and_process_packet(vf,NULL,1,1);
  153317. if(ret==OV_EOF)return(0);
  153318. if(ret<=0)return(ret);
  153319. }
  153320. }
  153321. }
  153322. extern float *vorbis_window(vorbis_dsp_state *v,int W);
  153323. extern void _analysis_output_always(const char *base,int i,float *v,int n,int bark,int dB,
  153324. ogg_int64_t off);
  153325. static void _ov_splice(float **pcm,float **lappcm,
  153326. int n1, int n2,
  153327. int ch1, int ch2,
  153328. float *w1, float *w2){
  153329. int i,j;
  153330. float *w=w1;
  153331. int n=n1;
  153332. if(n1>n2){
  153333. n=n2;
  153334. w=w2;
  153335. }
  153336. /* splice */
  153337. for(j=0;j<ch1 && j<ch2;j++){
  153338. float *s=lappcm[j];
  153339. float *d=pcm[j];
  153340. for(i=0;i<n;i++){
  153341. float wd=w[i]*w[i];
  153342. float ws=1.-wd;
  153343. d[i]=d[i]*wd + s[i]*ws;
  153344. }
  153345. }
  153346. /* window from zero */
  153347. for(;j<ch2;j++){
  153348. float *d=pcm[j];
  153349. for(i=0;i<n;i++){
  153350. float wd=w[i]*w[i];
  153351. d[i]=d[i]*wd;
  153352. }
  153353. }
  153354. }
  153355. /* make sure vf is INITSET */
  153356. static int _ov_initset(OggVorbis_File *vf){
  153357. while(1){
  153358. if(vf->ready_state==INITSET)break;
  153359. /* suck in another packet */
  153360. {
  153361. int ret=_fetch_and_process_packet(vf,NULL,1,0);
  153362. if(ret<0 && ret!=OV_HOLE)return(ret);
  153363. }
  153364. }
  153365. return 0;
  153366. }
  153367. /* make sure vf is INITSET and that we have a primed buffer; if
  153368. we're crosslapping at a stream section boundary, this also makes
  153369. sure we're sanity checking against the right stream information */
  153370. static int _ov_initprime(OggVorbis_File *vf){
  153371. vorbis_dsp_state *vd=&vf->vd;
  153372. while(1){
  153373. if(vf->ready_state==INITSET)
  153374. if(vorbis_synthesis_pcmout(vd,NULL))break;
  153375. /* suck in another packet */
  153376. {
  153377. int ret=_fetch_and_process_packet(vf,NULL,1,0);
  153378. if(ret<0 && ret!=OV_HOLE)return(ret);
  153379. }
  153380. }
  153381. return 0;
  153382. }
  153383. /* grab enough data for lapping from vf; this may be in the form of
  153384. unreturned, already-decoded pcm, remaining PCM we will need to
  153385. decode, or synthetic postextrapolation from last packets. */
  153386. static void _ov_getlap(OggVorbis_File *vf,vorbis_info *vi,vorbis_dsp_state *vd,
  153387. float **lappcm,int lapsize){
  153388. int lapcount=0,i;
  153389. float **pcm;
  153390. /* try first to decode the lapping data */
  153391. while(lapcount<lapsize){
  153392. int samples=vorbis_synthesis_pcmout(vd,&pcm);
  153393. if(samples){
  153394. if(samples>lapsize-lapcount)samples=lapsize-lapcount;
  153395. for(i=0;i<vi->channels;i++)
  153396. memcpy(lappcm[i]+lapcount,pcm[i],sizeof(**pcm)*samples);
  153397. lapcount+=samples;
  153398. vorbis_synthesis_read(vd,samples);
  153399. }else{
  153400. /* suck in another packet */
  153401. int ret=_fetch_and_process_packet(vf,NULL,1,0); /* do *not* span */
  153402. if(ret==OV_EOF)break;
  153403. }
  153404. }
  153405. if(lapcount<lapsize){
  153406. /* failed to get lapping data from normal decode; pry it from the
  153407. postextrapolation buffering, or the second half of the MDCT
  153408. from the last packet */
  153409. int samples=vorbis_synthesis_lapout(&vf->vd,&pcm);
  153410. if(samples==0){
  153411. for(i=0;i<vi->channels;i++)
  153412. memset(lappcm[i]+lapcount,0,sizeof(**pcm)*lapsize-lapcount);
  153413. lapcount=lapsize;
  153414. }else{
  153415. if(samples>lapsize-lapcount)samples=lapsize-lapcount;
  153416. for(i=0;i<vi->channels;i++)
  153417. memcpy(lappcm[i]+lapcount,pcm[i],sizeof(**pcm)*samples);
  153418. lapcount+=samples;
  153419. }
  153420. }
  153421. }
  153422. /* this sets up crosslapping of a sample by using trailing data from
  153423. sample 1 and lapping it into the windowing buffer of sample 2 */
  153424. int ov_crosslap(OggVorbis_File *vf1, OggVorbis_File *vf2){
  153425. vorbis_info *vi1,*vi2;
  153426. float **lappcm;
  153427. float **pcm;
  153428. float *w1,*w2;
  153429. int n1,n2,i,ret,hs1,hs2;
  153430. if(vf1==vf2)return(0); /* degenerate case */
  153431. if(vf1->ready_state<OPENED)return(OV_EINVAL);
  153432. if(vf2->ready_state<OPENED)return(OV_EINVAL);
  153433. /* the relevant overlap buffers must be pre-checked and pre-primed
  153434. before looking at settings in the event that priming would cross
  153435. a bitstream boundary. So, do it now */
  153436. ret=_ov_initset(vf1);
  153437. if(ret)return(ret);
  153438. ret=_ov_initprime(vf2);
  153439. if(ret)return(ret);
  153440. vi1=ov_info(vf1,-1);
  153441. vi2=ov_info(vf2,-1);
  153442. hs1=ov_halfrate_p(vf1);
  153443. hs2=ov_halfrate_p(vf2);
  153444. lappcm=(float**) alloca(sizeof(*lappcm)*vi1->channels);
  153445. n1=vorbis_info_blocksize(vi1,0)>>(1+hs1);
  153446. n2=vorbis_info_blocksize(vi2,0)>>(1+hs2);
  153447. w1=vorbis_window(&vf1->vd,0);
  153448. w2=vorbis_window(&vf2->vd,0);
  153449. for(i=0;i<vi1->channels;i++)
  153450. lappcm[i]=(float*) alloca(sizeof(**lappcm)*n1);
  153451. _ov_getlap(vf1,vi1,&vf1->vd,lappcm,n1);
  153452. /* have a lapping buffer from vf1; now to splice it into the lapping
  153453. buffer of vf2 */
  153454. /* consolidate and expose the buffer. */
  153455. vorbis_synthesis_lapout(&vf2->vd,&pcm);
  153456. _analysis_output_always("pcmL",0,pcm[0],n1*2,0,0,0);
  153457. _analysis_output_always("pcmR",0,pcm[1],n1*2,0,0,0);
  153458. /* splice */
  153459. _ov_splice(pcm,lappcm,n1,n2,vi1->channels,vi2->channels,w1,w2);
  153460. /* done */
  153461. return(0);
  153462. }
  153463. static int _ov_64_seek_lap(OggVorbis_File *vf,ogg_int64_t pos,
  153464. int (*localseek)(OggVorbis_File *,ogg_int64_t)){
  153465. vorbis_info *vi;
  153466. float **lappcm;
  153467. float **pcm;
  153468. float *w1,*w2;
  153469. int n1,n2,ch1,ch2,hs;
  153470. int i,ret;
  153471. if(vf->ready_state<OPENED)return(OV_EINVAL);
  153472. ret=_ov_initset(vf);
  153473. if(ret)return(ret);
  153474. vi=ov_info(vf,-1);
  153475. hs=ov_halfrate_p(vf);
  153476. ch1=vi->channels;
  153477. n1=vorbis_info_blocksize(vi,0)>>(1+hs);
  153478. w1=vorbis_window(&vf->vd,0); /* window arrays from libvorbis are
  153479. persistent; even if the decode state
  153480. from this link gets dumped, this
  153481. window array continues to exist */
  153482. lappcm=(float**) alloca(sizeof(*lappcm)*ch1);
  153483. for(i=0;i<ch1;i++)
  153484. lappcm[i]=(float*) alloca(sizeof(**lappcm)*n1);
  153485. _ov_getlap(vf,vi,&vf->vd,lappcm,n1);
  153486. /* have lapping data; seek and prime the buffer */
  153487. ret=localseek(vf,pos);
  153488. if(ret)return ret;
  153489. ret=_ov_initprime(vf);
  153490. if(ret)return(ret);
  153491. /* Guard against cross-link changes; they're perfectly legal */
  153492. vi=ov_info(vf,-1);
  153493. ch2=vi->channels;
  153494. n2=vorbis_info_blocksize(vi,0)>>(1+hs);
  153495. w2=vorbis_window(&vf->vd,0);
  153496. /* consolidate and expose the buffer. */
  153497. vorbis_synthesis_lapout(&vf->vd,&pcm);
  153498. /* splice */
  153499. _ov_splice(pcm,lappcm,n1,n2,ch1,ch2,w1,w2);
  153500. /* done */
  153501. return(0);
  153502. }
  153503. int ov_raw_seek_lap(OggVorbis_File *vf,ogg_int64_t pos){
  153504. return _ov_64_seek_lap(vf,pos,ov_raw_seek);
  153505. }
  153506. int ov_pcm_seek_lap(OggVorbis_File *vf,ogg_int64_t pos){
  153507. return _ov_64_seek_lap(vf,pos,ov_pcm_seek);
  153508. }
  153509. int ov_pcm_seek_page_lap(OggVorbis_File *vf,ogg_int64_t pos){
  153510. return _ov_64_seek_lap(vf,pos,ov_pcm_seek_page);
  153511. }
  153512. static int _ov_d_seek_lap(OggVorbis_File *vf,double pos,
  153513. int (*localseek)(OggVorbis_File *,double)){
  153514. vorbis_info *vi;
  153515. float **lappcm;
  153516. float **pcm;
  153517. float *w1,*w2;
  153518. int n1,n2,ch1,ch2,hs;
  153519. int i,ret;
  153520. if(vf->ready_state<OPENED)return(OV_EINVAL);
  153521. ret=_ov_initset(vf);
  153522. if(ret)return(ret);
  153523. vi=ov_info(vf,-1);
  153524. hs=ov_halfrate_p(vf);
  153525. ch1=vi->channels;
  153526. n1=vorbis_info_blocksize(vi,0)>>(1+hs);
  153527. w1=vorbis_window(&vf->vd,0); /* window arrays from libvorbis are
  153528. persistent; even if the decode state
  153529. from this link gets dumped, this
  153530. window array continues to exist */
  153531. lappcm=(float**) alloca(sizeof(*lappcm)*ch1);
  153532. for(i=0;i<ch1;i++)
  153533. lappcm[i]=(float*) alloca(sizeof(**lappcm)*n1);
  153534. _ov_getlap(vf,vi,&vf->vd,lappcm,n1);
  153535. /* have lapping data; seek and prime the buffer */
  153536. ret=localseek(vf,pos);
  153537. if(ret)return ret;
  153538. ret=_ov_initprime(vf);
  153539. if(ret)return(ret);
  153540. /* Guard against cross-link changes; they're perfectly legal */
  153541. vi=ov_info(vf,-1);
  153542. ch2=vi->channels;
  153543. n2=vorbis_info_blocksize(vi,0)>>(1+hs);
  153544. w2=vorbis_window(&vf->vd,0);
  153545. /* consolidate and expose the buffer. */
  153546. vorbis_synthesis_lapout(&vf->vd,&pcm);
  153547. /* splice */
  153548. _ov_splice(pcm,lappcm,n1,n2,ch1,ch2,w1,w2);
  153549. /* done */
  153550. return(0);
  153551. }
  153552. int ov_time_seek_lap(OggVorbis_File *vf,double pos){
  153553. return _ov_d_seek_lap(vf,pos,ov_time_seek);
  153554. }
  153555. int ov_time_seek_page_lap(OggVorbis_File *vf,double pos){
  153556. return _ov_d_seek_lap(vf,pos,ov_time_seek_page);
  153557. }
  153558. #endif
  153559. /*** End of inlined file: vorbisfile.c ***/
  153560. /*** Start of inlined file: window.c ***/
  153561. /*** Start of inlined file: juce_OggVorbisHeader.h ***/
  153562. // This file is included at the start of each Ogg-Vorbis .c file, just to do a few housekeeping
  153563. // tasks..
  153564. #if JUCE_MSVC
  153565. #pragma warning (disable: 4267 4127 4244 4996 4100 4701 4702 4013 4133 4206 4305 4189 4706)
  153566. #endif
  153567. /*** End of inlined file: juce_OggVorbisHeader.h ***/
  153568. #if JUCE_USE_OGGVORBIS
  153569. #include <stdlib.h>
  153570. #include <math.h>
  153571. static float vwin64[32] = {
  153572. 0.0009460463F, 0.0085006468F, 0.0235352254F, 0.0458950567F,
  153573. 0.0753351908F, 0.1115073077F, 0.1539457973F, 0.2020557475F,
  153574. 0.2551056759F, 0.3122276645F, 0.3724270287F, 0.4346027792F,
  153575. 0.4975789974F, 0.5601459521F, 0.6211085051F, 0.6793382689F,
  153576. 0.7338252629F, 0.7837245849F, 0.8283939355F, 0.8674186656F,
  153577. 0.9006222429F, 0.9280614787F, 0.9500073081F, 0.9669131782F,
  153578. 0.9793740220F, 0.9880792941F, 0.9937636139F, 0.9971582668F,
  153579. 0.9989462667F, 0.9997230082F, 0.9999638688F, 0.9999995525F,
  153580. };
  153581. static float vwin128[64] = {
  153582. 0.0002365472F, 0.0021280687F, 0.0059065254F, 0.0115626550F,
  153583. 0.0190823442F, 0.0284463735F, 0.0396300935F, 0.0526030430F,
  153584. 0.0673285281F, 0.0837631763F, 0.1018564887F, 0.1215504095F,
  153585. 0.1427789367F, 0.1654677960F, 0.1895342001F, 0.2148867160F,
  153586. 0.2414252576F, 0.2690412240F, 0.2976177952F, 0.3270303960F,
  153587. 0.3571473350F, 0.3878306189F, 0.4189369387F, 0.4503188188F,
  153588. 0.4818259135F, 0.5133064334F, 0.5446086751F, 0.5755826278F,
  153589. 0.6060816248F, 0.6359640047F, 0.6650947483F, 0.6933470543F,
  153590. 0.7206038179F, 0.7467589810F, 0.7717187213F, 0.7954024542F,
  153591. 0.8177436264F, 0.8386902831F, 0.8582053981F, 0.8762669622F,
  153592. 0.8928678298F, 0.9080153310F, 0.9217306608F, 0.9340480615F,
  153593. 0.9450138200F, 0.9546851041F, 0.9631286621F, 0.9704194171F,
  153594. 0.9766389810F, 0.9818741197F, 0.9862151938F, 0.9897546035F,
  153595. 0.9925852598F, 0.9947991032F, 0.9964856900F, 0.9977308602F,
  153596. 0.9986155015F, 0.9992144193F, 0.9995953200F, 0.9998179155F,
  153597. 0.9999331503F, 0.9999825563F, 0.9999977357F, 0.9999999720F,
  153598. };
  153599. static float vwin256[128] = {
  153600. 0.0000591390F, 0.0005321979F, 0.0014780301F, 0.0028960636F,
  153601. 0.0047854363F, 0.0071449926F, 0.0099732775F, 0.0132685298F,
  153602. 0.0170286741F, 0.0212513119F, 0.0259337111F, 0.0310727950F,
  153603. 0.0366651302F, 0.0427069140F, 0.0491939614F, 0.0561216907F,
  153604. 0.0634851102F, 0.0712788035F, 0.0794969160F, 0.0881331402F,
  153605. 0.0971807028F, 0.1066323515F, 0.1164803426F, 0.1267164297F,
  153606. 0.1373318534F, 0.1483173323F, 0.1596630553F, 0.1713586755F,
  153607. 0.1833933062F, 0.1957555184F, 0.2084333404F, 0.2214142599F,
  153608. 0.2346852280F, 0.2482326664F, 0.2620424757F, 0.2761000481F,
  153609. 0.2903902813F, 0.3048975959F, 0.3196059553F, 0.3344988887F,
  153610. 0.3495595160F, 0.3647705766F, 0.3801144597F, 0.3955732382F,
  153611. 0.4111287047F, 0.4267624093F, 0.4424557009F, 0.4581897696F,
  153612. 0.4739456913F, 0.4897044744F, 0.5054471075F, 0.5211546088F,
  153613. 0.5368080763F, 0.5523887395F, 0.5678780103F, 0.5832575361F,
  153614. 0.5985092508F, 0.6136154277F, 0.6285587300F, 0.6433222619F,
  153615. 0.6578896175F, 0.6722449294F, 0.6863729144F, 0.7002589187F,
  153616. 0.7138889597F, 0.7272497662F, 0.7403288154F, 0.7531143679F,
  153617. 0.7655954985F, 0.7777621249F, 0.7896050322F, 0.8011158947F,
  153618. 0.8122872932F, 0.8231127294F, 0.8335866365F, 0.8437043850F,
  153619. 0.8534622861F, 0.8628575905F, 0.8718884835F, 0.8805540765F,
  153620. 0.8888543947F, 0.8967903616F, 0.9043637797F, 0.9115773078F,
  153621. 0.9184344360F, 0.9249394562F, 0.9310974312F, 0.9369141608F,
  153622. 0.9423961446F, 0.9475505439F, 0.9523851406F, 0.9569082947F,
  153623. 0.9611289005F, 0.9650563408F, 0.9687004405F, 0.9720714191F,
  153624. 0.9751798427F, 0.9780365753F, 0.9806527301F, 0.9830396204F,
  153625. 0.9852087111F, 0.9871715701F, 0.9889398207F, 0.9905250941F,
  153626. 0.9919389832F, 0.9931929973F, 0.9942985174F, 0.9952667537F,
  153627. 0.9961087037F, 0.9968351119F, 0.9974564312F, 0.9979827858F,
  153628. 0.9984239359F, 0.9987892441F, 0.9990876435F, 0.9993276081F,
  153629. 0.9995171241F, 0.9996636648F, 0.9997741654F, 0.9998550016F,
  153630. 0.9999119692F, 0.9999502656F, 0.9999744742F, 0.9999885497F,
  153631. 0.9999958064F, 0.9999989077F, 0.9999998584F, 0.9999999983F,
  153632. };
  153633. static float vwin512[256] = {
  153634. 0.0000147849F, 0.0001330607F, 0.0003695946F, 0.0007243509F,
  153635. 0.0011972759F, 0.0017882983F, 0.0024973285F, 0.0033242588F,
  153636. 0.0042689632F, 0.0053312973F, 0.0065110982F, 0.0078081841F,
  153637. 0.0092223540F, 0.0107533880F, 0.0124010466F, 0.0141650703F,
  153638. 0.0160451800F, 0.0180410758F, 0.0201524373F, 0.0223789233F,
  153639. 0.0247201710F, 0.0271757958F, 0.0297453914F, 0.0324285286F,
  153640. 0.0352247556F, 0.0381335972F, 0.0411545545F, 0.0442871045F,
  153641. 0.0475306997F, 0.0508847676F, 0.0543487103F, 0.0579219038F,
  153642. 0.0616036982F, 0.0653934164F, 0.0692903546F, 0.0732937809F,
  153643. 0.0774029356F, 0.0816170305F, 0.0859352485F, 0.0903567428F,
  153644. 0.0948806375F, 0.0995060259F, 0.1042319712F, 0.1090575056F,
  153645. 0.1139816300F, 0.1190033137F, 0.1241214941F, 0.1293350764F,
  153646. 0.1346429333F, 0.1400439046F, 0.1455367974F, 0.1511203852F,
  153647. 0.1567934083F, 0.1625545735F, 0.1684025537F, 0.1743359881F,
  153648. 0.1803534820F, 0.1864536069F, 0.1926349000F, 0.1988958650F,
  153649. 0.2052349715F, 0.2116506555F, 0.2181413191F, 0.2247053313F,
  153650. 0.2313410275F, 0.2380467105F, 0.2448206500F, 0.2516610835F,
  153651. 0.2585662164F, 0.2655342226F, 0.2725632448F, 0.2796513950F,
  153652. 0.2867967551F, 0.2939973773F, 0.3012512852F, 0.3085564739F,
  153653. 0.3159109111F, 0.3233125375F, 0.3307592680F, 0.3382489922F,
  153654. 0.3457795756F, 0.3533488602F, 0.3609546657F, 0.3685947904F,
  153655. 0.3762670121F, 0.3839690896F, 0.3916987634F, 0.3994537572F,
  153656. 0.4072317788F, 0.4150305215F, 0.4228476653F, 0.4306808783F,
  153657. 0.4385278181F, 0.4463861329F, 0.4542534630F, 0.4621274424F,
  153658. 0.4700057001F, 0.4778858615F, 0.4857655502F, 0.4936423891F,
  153659. 0.5015140023F, 0.5093780165F, 0.5172320626F, 0.5250737772F,
  153660. 0.5329008043F, 0.5407107971F, 0.5485014192F, 0.5562703465F,
  153661. 0.5640152688F, 0.5717338914F, 0.5794239366F, 0.5870831457F,
  153662. 0.5947092801F, 0.6023001235F, 0.6098534829F, 0.6173671907F,
  153663. 0.6248391059F, 0.6322671161F, 0.6396491384F, 0.6469831217F,
  153664. 0.6542670475F, 0.6614989319F, 0.6686768267F, 0.6757988210F,
  153665. 0.6828630426F, 0.6898676592F, 0.6968108799F, 0.7036909564F,
  153666. 0.7105061843F, 0.7172549043F, 0.7239355032F, 0.7305464154F,
  153667. 0.7370861235F, 0.7435531598F, 0.7499461068F, 0.7562635986F,
  153668. 0.7625043214F, 0.7686670148F, 0.7747504721F, 0.7807535410F,
  153669. 0.7866751247F, 0.7925141825F, 0.7982697296F, 0.8039408387F,
  153670. 0.8095266395F, 0.8150263196F, 0.8204391248F, 0.8257643590F,
  153671. 0.8310013848F, 0.8361496236F, 0.8412085555F, 0.8461777194F,
  153672. 0.8510567129F, 0.8558451924F, 0.8605428730F, 0.8651495278F,
  153673. 0.8696649882F, 0.8740891432F, 0.8784219392F, 0.8826633797F,
  153674. 0.8868135244F, 0.8908724888F, 0.8948404441F, 0.8987176157F,
  153675. 0.9025042831F, 0.9062007791F, 0.9098074886F, 0.9133248482F,
  153676. 0.9167533451F, 0.9200935163F, 0.9233459472F, 0.9265112712F,
  153677. 0.9295901680F, 0.9325833632F, 0.9354916263F, 0.9383157705F,
  153678. 0.9410566504F, 0.9437151618F, 0.9462922398F, 0.9487888576F,
  153679. 0.9512060252F, 0.9535447882F, 0.9558062262F, 0.9579914516F,
  153680. 0.9601016078F, 0.9621378683F, 0.9641014348F, 0.9659935361F,
  153681. 0.9678154261F, 0.9695683830F, 0.9712537071F, 0.9728727198F,
  153682. 0.9744267618F, 0.9759171916F, 0.9773453842F, 0.9787127293F,
  153683. 0.9800206298F, 0.9812705006F, 0.9824637665F, 0.9836018613F,
  153684. 0.9846862258F, 0.9857183066F, 0.9866995544F, 0.9876314227F,
  153685. 0.9885153662F, 0.9893528393F, 0.9901452948F, 0.9908941823F,
  153686. 0.9916009470F, 0.9922670279F, 0.9928938570F, 0.9934828574F,
  153687. 0.9940354423F, 0.9945530133F, 0.9950369595F, 0.9954886562F,
  153688. 0.9959094633F, 0.9963007242F, 0.9966637649F, 0.9969998925F,
  153689. 0.9973103939F, 0.9975965351F, 0.9978595598F, 0.9981006885F,
  153690. 0.9983211172F, 0.9985220166F, 0.9987045311F, 0.9988697776F,
  153691. 0.9990188449F, 0.9991527924F, 0.9992726499F, 0.9993794157F,
  153692. 0.9994740570F, 0.9995575079F, 0.9996306699F, 0.9996944099F,
  153693. 0.9997495605F, 0.9997969190F, 0.9998372465F, 0.9998712678F,
  153694. 0.9998996704F, 0.9999231041F, 0.9999421807F, 0.9999574732F,
  153695. 0.9999695157F, 0.9999788026F, 0.9999857885F, 0.9999908879F,
  153696. 0.9999944746F, 0.9999968817F, 0.9999984010F, 0.9999992833F,
  153697. 0.9999997377F, 0.9999999317F, 0.9999999911F, 0.9999999999F,
  153698. };
  153699. static float vwin1024[512] = {
  153700. 0.0000036962F, 0.0000332659F, 0.0000924041F, 0.0001811086F,
  153701. 0.0002993761F, 0.0004472021F, 0.0006245811F, 0.0008315063F,
  153702. 0.0010679699F, 0.0013339631F, 0.0016294757F, 0.0019544965F,
  153703. 0.0023090133F, 0.0026930125F, 0.0031064797F, 0.0035493989F,
  153704. 0.0040217533F, 0.0045235250F, 0.0050546946F, 0.0056152418F,
  153705. 0.0062051451F, 0.0068243817F, 0.0074729278F, 0.0081507582F,
  153706. 0.0088578466F, 0.0095941655F, 0.0103596863F, 0.0111543789F,
  153707. 0.0119782122F, 0.0128311538F, 0.0137131701F, 0.0146242260F,
  153708. 0.0155642855F, 0.0165333111F, 0.0175312640F, 0.0185581042F,
  153709. 0.0196137903F, 0.0206982797F, 0.0218115284F, 0.0229534910F,
  153710. 0.0241241208F, 0.0253233698F, 0.0265511886F, 0.0278075263F,
  153711. 0.0290923308F, 0.0304055484F, 0.0317471241F, 0.0331170013F,
  153712. 0.0345151222F, 0.0359414274F, 0.0373958560F, 0.0388783456F,
  153713. 0.0403888325F, 0.0419272511F, 0.0434935347F, 0.0450876148F,
  153714. 0.0467094213F, 0.0483588828F, 0.0500359261F, 0.0517404765F,
  153715. 0.0534724575F, 0.0552317913F, 0.0570183983F, 0.0588321971F,
  153716. 0.0606731048F, 0.0625410369F, 0.0644359070F, 0.0663576272F,
  153717. 0.0683061077F, 0.0702812571F, 0.0722829821F, 0.0743111878F,
  153718. 0.0763657775F, 0.0784466526F, 0.0805537129F, 0.0826868561F,
  153719. 0.0848459782F, 0.0870309736F, 0.0892417345F, 0.0914781514F,
  153720. 0.0937401128F, 0.0960275056F, 0.0983402145F, 0.1006781223F,
  153721. 0.1030411101F, 0.1054290568F, 0.1078418397F, 0.1102793336F,
  153722. 0.1127414119F, 0.1152279457F, 0.1177388042F, 0.1202738544F,
  153723. 0.1228329618F, 0.1254159892F, 0.1280227980F, 0.1306532471F,
  153724. 0.1333071937F, 0.1359844927F, 0.1386849970F, 0.1414085575F,
  153725. 0.1441550230F, 0.1469242403F, 0.1497160539F, 0.1525303063F,
  153726. 0.1553668381F, 0.1582254875F, 0.1611060909F, 0.1640084822F,
  153727. 0.1669324936F, 0.1698779549F, 0.1728446939F, 0.1758325362F,
  153728. 0.1788413055F, 0.1818708232F, 0.1849209084F, 0.1879913785F,
  153729. 0.1910820485F, 0.1941927312F, 0.1973232376F, 0.2004733764F,
  153730. 0.2036429541F, 0.2068317752F, 0.2100396421F, 0.2132663552F,
  153731. 0.2165117125F, 0.2197755102F, 0.2230575422F, 0.2263576007F,
  153732. 0.2296754753F, 0.2330109540F, 0.2363638225F, 0.2397338646F,
  153733. 0.2431208619F, 0.2465245941F, 0.2499448389F, 0.2533813719F,
  153734. 0.2568339669F, 0.2603023956F, 0.2637864277F, 0.2672858312F,
  153735. 0.2708003718F, 0.2743298135F, 0.2778739186F, 0.2814324472F,
  153736. 0.2850051576F, 0.2885918065F, 0.2921921485F, 0.2958059366F,
  153737. 0.2994329219F, 0.3030728538F, 0.3067254799F, 0.3103905462F,
  153738. 0.3140677969F, 0.3177569747F, 0.3214578205F, 0.3251700736F,
  153739. 0.3288934718F, 0.3326277513F, 0.3363726468F, 0.3401278914F,
  153740. 0.3438932168F, 0.3476683533F, 0.3514530297F, 0.3552469734F,
  153741. 0.3590499106F, 0.3628615659F, 0.3666816630F, 0.3705099239F,
  153742. 0.3743460698F, 0.3781898204F, 0.3820408945F, 0.3858990095F,
  153743. 0.3897638820F, 0.3936352274F, 0.3975127601F, 0.4013961936F,
  153744. 0.4052852405F, 0.4091796123F, 0.4130790198F, 0.4169831732F,
  153745. 0.4208917815F, 0.4248045534F, 0.4287211965F, 0.4326414181F,
  153746. 0.4365649248F, 0.4404914225F, 0.4444206167F, 0.4483522125F,
  153747. 0.4522859146F, 0.4562214270F, 0.4601584538F, 0.4640966984F,
  153748. 0.4680358644F, 0.4719756548F, 0.4759157726F, 0.4798559209F,
  153749. 0.4837958024F, 0.4877351199F, 0.4916735765F, 0.4956108751F,
  153750. 0.4995467188F, 0.5034808109F, 0.5074128550F, 0.5113425550F,
  153751. 0.5152696149F, 0.5191937395F, 0.5231146336F, 0.5270320028F,
  153752. 0.5309455530F, 0.5348549910F, 0.5387600239F, 0.5426603597F,
  153753. 0.5465557070F, 0.5504457754F, 0.5543302752F, 0.5582089175F,
  153754. 0.5620814145F, 0.5659474793F, 0.5698068262F, 0.5736591704F,
  153755. 0.5775042283F, 0.5813417176F, 0.5851713571F, 0.5889928670F,
  153756. 0.5928059689F, 0.5966103856F, 0.6004058415F, 0.6041920626F,
  153757. 0.6079687761F, 0.6117357113F, 0.6154925986F, 0.6192391705F,
  153758. 0.6229751612F, 0.6267003064F, 0.6304143441F, 0.6341170137F,
  153759. 0.6378080569F, 0.6414872173F, 0.6451542405F, 0.6488088741F,
  153760. 0.6524508681F, 0.6560799742F, 0.6596959469F, 0.6632985424F,
  153761. 0.6668875197F, 0.6704626398F, 0.6740236662F, 0.6775703649F,
  153762. 0.6811025043F, 0.6846198554F, 0.6881221916F, 0.6916092892F,
  153763. 0.6950809269F, 0.6985368861F, 0.7019769510F, 0.7054009085F,
  153764. 0.7088085484F, 0.7121996632F, 0.7155740484F, 0.7189315023F,
  153765. 0.7222718263F, 0.7255948245F, 0.7289003043F, 0.7321880760F,
  153766. 0.7354579530F, 0.7387097518F, 0.7419432921F, 0.7451583966F,
  153767. 0.7483548915F, 0.7515326059F, 0.7546913723F, 0.7578310265F,
  153768. 0.7609514077F, 0.7640523581F, 0.7671337237F, 0.7701953535F,
  153769. 0.7732371001F, 0.7762588195F, 0.7792603711F, 0.7822416178F,
  153770. 0.7852024259F, 0.7881426654F, 0.7910622097F, 0.7939609356F,
  153771. 0.7968387237F, 0.7996954579F, 0.8025310261F, 0.8053453193F,
  153772. 0.8081382324F, 0.8109096638F, 0.8136595156F, 0.8163876936F,
  153773. 0.8190941071F, 0.8217786690F, 0.8244412960F, 0.8270819086F,
  153774. 0.8297004305F, 0.8322967896F, 0.8348709171F, 0.8374227481F,
  153775. 0.8399522213F, 0.8424592789F, 0.8449438672F, 0.8474059356F,
  153776. 0.8498454378F, 0.8522623306F, 0.8546565748F, 0.8570281348F,
  153777. 0.8593769787F, 0.8617030779F, 0.8640064080F, 0.8662869477F,
  153778. 0.8685446796F, 0.8707795899F, 0.8729916682F, 0.8751809079F,
  153779. 0.8773473059F, 0.8794908626F, 0.8816115819F, 0.8837094713F,
  153780. 0.8857845418F, 0.8878368079F, 0.8898662874F, 0.8918730019F,
  153781. 0.8938569760F, 0.8958182380F, 0.8977568194F, 0.8996727552F,
  153782. 0.9015660837F, 0.9034368465F, 0.9052850885F, 0.9071108577F,
  153783. 0.9089142057F, 0.9106951869F, 0.9124538591F, 0.9141902832F,
  153784. 0.9159045233F, 0.9175966464F, 0.9192667228F, 0.9209148257F,
  153785. 0.9225410313F, 0.9241454187F, 0.9257280701F, 0.9272890704F,
  153786. 0.9288285075F, 0.9303464720F, 0.9318430576F, 0.9333183603F,
  153787. 0.9347724792F, 0.9362055158F, 0.9376175745F, 0.9390087622F,
  153788. 0.9403791881F, 0.9417289644F, 0.9430582055F, 0.9443670283F,
  153789. 0.9456555521F, 0.9469238986F, 0.9481721917F, 0.9494005577F,
  153790. 0.9506091252F, 0.9517980248F, 0.9529673894F, 0.9541173540F,
  153791. 0.9552480557F, 0.9563596334F, 0.9574522282F, 0.9585259830F,
  153792. 0.9595810428F, 0.9606175542F, 0.9616356656F, 0.9626355274F,
  153793. 0.9636172915F, 0.9645811114F, 0.9655271425F, 0.9664555414F,
  153794. 0.9673664664F, 0.9682600774F, 0.9691365355F, 0.9699960034F,
  153795. 0.9708386448F, 0.9716646250F, 0.9724741103F, 0.9732672685F,
  153796. 0.9740442683F, 0.9748052795F, 0.9755504729F, 0.9762800205F,
  153797. 0.9769940950F, 0.9776928703F, 0.9783765210F, 0.9790452223F,
  153798. 0.9796991504F, 0.9803384823F, 0.9809633954F, 0.9815740679F,
  153799. 0.9821706784F, 0.9827534063F, 0.9833224312F, 0.9838779332F,
  153800. 0.9844200928F, 0.9849490910F, 0.9854651087F, 0.9859683274F,
  153801. 0.9864589286F, 0.9869370940F, 0.9874030054F, 0.9878568447F,
  153802. 0.9882987937F, 0.9887290343F, 0.9891477481F, 0.9895551169F,
  153803. 0.9899513220F, 0.9903365446F, 0.9907109658F, 0.9910747662F,
  153804. 0.9914281260F, 0.9917712252F, 0.9921042433F, 0.9924273593F,
  153805. 0.9927407516F, 0.9930445982F, 0.9933390763F, 0.9936243626F,
  153806. 0.9939006331F, 0.9941680631F, 0.9944268269F, 0.9946770982F,
  153807. 0.9949190498F, 0.9951528537F, 0.9953786808F, 0.9955967011F,
  153808. 0.9958070836F, 0.9960099963F, 0.9962056061F, 0.9963940787F,
  153809. 0.9965755786F, 0.9967502693F, 0.9969183129F, 0.9970798704F,
  153810. 0.9972351013F, 0.9973841640F, 0.9975272151F, 0.9976644103F,
  153811. 0.9977959036F, 0.9979218476F, 0.9980423932F, 0.9981576901F,
  153812. 0.9982678862F, 0.9983731278F, 0.9984735596F, 0.9985693247F,
  153813. 0.9986605645F, 0.9987474186F, 0.9988300248F, 0.9989085193F,
  153814. 0.9989830364F, 0.9990537085F, 0.9991206662F, 0.9991840382F,
  153815. 0.9992439513F, 0.9993005303F, 0.9993538982F, 0.9994041757F,
  153816. 0.9994514817F, 0.9994959330F, 0.9995376444F, 0.9995767286F,
  153817. 0.9996132960F, 0.9996474550F, 0.9996793121F, 0.9997089710F,
  153818. 0.9997365339F, 0.9997621003F, 0.9997857677F, 0.9998076311F,
  153819. 0.9998277836F, 0.9998463156F, 0.9998633155F, 0.9998788692F,
  153820. 0.9998930603F, 0.9999059701F, 0.9999176774F, 0.9999282586F,
  153821. 0.9999377880F, 0.9999463370F, 0.9999539749F, 0.9999607685F,
  153822. 0.9999667820F, 0.9999720773F, 0.9999767136F, 0.9999807479F,
  153823. 0.9999842344F, 0.9999872249F, 0.9999897688F, 0.9999919127F,
  153824. 0.9999937009F, 0.9999951749F, 0.9999963738F, 0.9999973342F,
  153825. 0.9999980900F, 0.9999986724F, 0.9999991103F, 0.9999994297F,
  153826. 0.9999996543F, 0.9999998049F, 0.9999999000F, 0.9999999552F,
  153827. 0.9999999836F, 0.9999999957F, 0.9999999994F, 1.0000000000F,
  153828. };
  153829. static float vwin2048[1024] = {
  153830. 0.0000009241F, 0.0000083165F, 0.0000231014F, 0.0000452785F,
  153831. 0.0000748476F, 0.0001118085F, 0.0001561608F, 0.0002079041F,
  153832. 0.0002670379F, 0.0003335617F, 0.0004074748F, 0.0004887765F,
  153833. 0.0005774661F, 0.0006735427F, 0.0007770054F, 0.0008878533F,
  153834. 0.0010060853F, 0.0011317002F, 0.0012646969F, 0.0014050742F,
  153835. 0.0015528307F, 0.0017079650F, 0.0018704756F, 0.0020403610F,
  153836. 0.0022176196F, 0.0024022497F, 0.0025942495F, 0.0027936173F,
  153837. 0.0030003511F, 0.0032144490F, 0.0034359088F, 0.0036647286F,
  153838. 0.0039009061F, 0.0041444391F, 0.0043953253F, 0.0046535621F,
  153839. 0.0049191472F, 0.0051920781F, 0.0054723520F, 0.0057599664F,
  153840. 0.0060549184F, 0.0063572052F, 0.0066668239F, 0.0069837715F,
  153841. 0.0073080449F, 0.0076396410F, 0.0079785566F, 0.0083247884F,
  153842. 0.0086783330F, 0.0090391871F, 0.0094073470F, 0.0097828092F,
  153843. 0.0101655700F, 0.0105556258F, 0.0109529726F, 0.0113576065F,
  153844. 0.0117695237F, 0.0121887200F, 0.0126151913F, 0.0130489335F,
  153845. 0.0134899422F, 0.0139382130F, 0.0143937415F, 0.0148565233F,
  153846. 0.0153265536F, 0.0158038279F, 0.0162883413F, 0.0167800889F,
  153847. 0.0172790660F, 0.0177852675F, 0.0182986882F, 0.0188193231F,
  153848. 0.0193471668F, 0.0198822141F, 0.0204244594F, 0.0209738974F,
  153849. 0.0215305225F, 0.0220943289F, 0.0226653109F, 0.0232434627F,
  153850. 0.0238287784F, 0.0244212519F, 0.0250208772F, 0.0256276481F,
  153851. 0.0262415582F, 0.0268626014F, 0.0274907711F, 0.0281260608F,
  153852. 0.0287684638F, 0.0294179736F, 0.0300745833F, 0.0307382859F,
  153853. 0.0314090747F, 0.0320869424F, 0.0327718819F, 0.0334638860F,
  153854. 0.0341629474F, 0.0348690586F, 0.0355822122F, 0.0363024004F,
  153855. 0.0370296157F, 0.0377638502F, 0.0385050960F, 0.0392533451F,
  153856. 0.0400085896F, 0.0407708211F, 0.0415400315F, 0.0423162123F,
  153857. 0.0430993552F, 0.0438894515F, 0.0446864926F, 0.0454904698F,
  153858. 0.0463013742F, 0.0471191969F, 0.0479439288F, 0.0487755607F,
  153859. 0.0496140836F, 0.0504594879F, 0.0513117642F, 0.0521709031F,
  153860. 0.0530368949F, 0.0539097297F, 0.0547893979F, 0.0556758894F,
  153861. 0.0565691941F, 0.0574693019F, 0.0583762026F, 0.0592898858F,
  153862. 0.0602103410F, 0.0611375576F, 0.0620715250F, 0.0630122324F,
  153863. 0.0639596688F, 0.0649138234F, 0.0658746848F, 0.0668422421F,
  153864. 0.0678164838F, 0.0687973985F, 0.0697849746F, 0.0707792005F,
  153865. 0.0717800645F, 0.0727875547F, 0.0738016591F, 0.0748223656F,
  153866. 0.0758496620F, 0.0768835359F, 0.0779239751F, 0.0789709668F,
  153867. 0.0800244985F, 0.0810845574F, 0.0821511306F, 0.0832242052F,
  153868. 0.0843037679F, 0.0853898056F, 0.0864823050F, 0.0875812525F,
  153869. 0.0886866347F, 0.0897984378F, 0.0909166480F, 0.0920412513F,
  153870. 0.0931722338F, 0.0943095813F, 0.0954532795F, 0.0966033140F,
  153871. 0.0977596702F, 0.0989223336F, 0.1000912894F, 0.1012665227F,
  153872. 0.1024480185F, 0.1036357616F, 0.1048297369F, 0.1060299290F,
  153873. 0.1072363224F, 0.1084489014F, 0.1096676504F, 0.1108925534F,
  153874. 0.1121235946F, 0.1133607577F, 0.1146040267F, 0.1158533850F,
  153875. 0.1171088163F, 0.1183703040F, 0.1196378312F, 0.1209113812F,
  153876. 0.1221909370F, 0.1234764815F, 0.1247679974F, 0.1260654674F,
  153877. 0.1273688740F, 0.1286781995F, 0.1299934263F, 0.1313145365F,
  153878. 0.1326415121F, 0.1339743349F, 0.1353129866F, 0.1366574490F,
  153879. 0.1380077035F, 0.1393637315F, 0.1407255141F, 0.1420930325F,
  153880. 0.1434662677F, 0.1448452004F, 0.1462298115F, 0.1476200814F,
  153881. 0.1490159906F, 0.1504175195F, 0.1518246482F, 0.1532373569F,
  153882. 0.1546556253F, 0.1560794333F, 0.1575087606F, 0.1589435866F,
  153883. 0.1603838909F, 0.1618296526F, 0.1632808509F, 0.1647374648F,
  153884. 0.1661994731F, 0.1676668546F, 0.1691395880F, 0.1706176516F,
  153885. 0.1721010238F, 0.1735896829F, 0.1750836068F, 0.1765827736F,
  153886. 0.1780871610F, 0.1795967468F, 0.1811115084F, 0.1826314234F,
  153887. 0.1841564689F, 0.1856866221F, 0.1872218600F, 0.1887621595F,
  153888. 0.1903074974F, 0.1918578503F, 0.1934131947F, 0.1949735068F,
  153889. 0.1965387630F, 0.1981089393F, 0.1996840117F, 0.2012639560F,
  153890. 0.2028487479F, 0.2044383630F, 0.2060327766F, 0.2076319642F,
  153891. 0.2092359007F, 0.2108445614F, 0.2124579211F, 0.2140759545F,
  153892. 0.2156986364F, 0.2173259411F, 0.2189578432F, 0.2205943168F,
  153893. 0.2222353361F, 0.2238808751F, 0.2255309076F, 0.2271854073F,
  153894. 0.2288443480F, 0.2305077030F, 0.2321754457F, 0.2338475493F,
  153895. 0.2355239869F, 0.2372047315F, 0.2388897560F, 0.2405790329F,
  153896. 0.2422725350F, 0.2439702347F, 0.2456721043F, 0.2473781159F,
  153897. 0.2490882418F, 0.2508024539F, 0.2525207240F, 0.2542430237F,
  153898. 0.2559693248F, 0.2576995986F, 0.2594338166F, 0.2611719498F,
  153899. 0.2629139695F, 0.2646598466F, 0.2664095520F, 0.2681630564F,
  153900. 0.2699203304F, 0.2716813445F, 0.2734460691F, 0.2752144744F,
  153901. 0.2769865307F, 0.2787622079F, 0.2805414760F, 0.2823243047F,
  153902. 0.2841106637F, 0.2859005227F, 0.2876938509F, 0.2894906179F,
  153903. 0.2912907928F, 0.2930943447F, 0.2949012426F, 0.2967114554F,
  153904. 0.2985249520F, 0.3003417009F, 0.3021616708F, 0.3039848301F,
  153905. 0.3058111471F, 0.3076405901F, 0.3094731273F, 0.3113087266F,
  153906. 0.3131473560F, 0.3149889833F, 0.3168335762F, 0.3186811024F,
  153907. 0.3205315294F, 0.3223848245F, 0.3242409552F, 0.3260998886F,
  153908. 0.3279615918F, 0.3298260319F, 0.3316931758F, 0.3335629903F,
  153909. 0.3354354423F, 0.3373104982F, 0.3391881247F, 0.3410682882F,
  153910. 0.3429509551F, 0.3448360917F, 0.3467236642F, 0.3486136387F,
  153911. 0.3505059811F, 0.3524006575F, 0.3542976336F, 0.3561968753F,
  153912. 0.3580983482F, 0.3600020179F, 0.3619078499F, 0.3638158096F,
  153913. 0.3657258625F, 0.3676379737F, 0.3695521086F, 0.3714682321F,
  153914. 0.3733863094F, 0.3753063055F, 0.3772281852F, 0.3791519134F,
  153915. 0.3810774548F, 0.3830047742F, 0.3849338362F, 0.3868646053F,
  153916. 0.3887970459F, 0.3907311227F, 0.3926667998F, 0.3946040417F,
  153917. 0.3965428125F, 0.3984830765F, 0.4004247978F, 0.4023679403F,
  153918. 0.4043124683F, 0.4062583455F, 0.4082055359F, 0.4101540034F,
  153919. 0.4121037117F, 0.4140546246F, 0.4160067058F, 0.4179599190F,
  153920. 0.4199142277F, 0.4218695956F, 0.4238259861F, 0.4257833627F,
  153921. 0.4277416888F, 0.4297009279F, 0.4316610433F, 0.4336219983F,
  153922. 0.4355837562F, 0.4375462803F, 0.4395095337F, 0.4414734797F,
  153923. 0.4434380815F, 0.4454033021F, 0.4473691046F, 0.4493354521F,
  153924. 0.4513023078F, 0.4532696345F, 0.4552373954F, 0.4572055533F,
  153925. 0.4591740713F, 0.4611429123F, 0.4631120393F, 0.4650814151F,
  153926. 0.4670510028F, 0.4690207650F, 0.4709906649F, 0.4729606651F,
  153927. 0.4749307287F, 0.4769008185F, 0.4788708972F, 0.4808409279F,
  153928. 0.4828108732F, 0.4847806962F, 0.4867503597F, 0.4887198264F,
  153929. 0.4906890593F, 0.4926580213F, 0.4946266753F, 0.4965949840F,
  153930. 0.4985629105F, 0.5005304176F, 0.5024974683F, 0.5044640255F,
  153931. 0.5064300522F, 0.5083955114F, 0.5103603659F, 0.5123245790F,
  153932. 0.5142881136F, 0.5162509328F, 0.5182129997F, 0.5201742774F,
  153933. 0.5221347290F, 0.5240943178F, 0.5260530070F, 0.5280107598F,
  153934. 0.5299675395F, 0.5319233095F, 0.5338780330F, 0.5358316736F,
  153935. 0.5377841946F, 0.5397355596F, 0.5416857320F, 0.5436346755F,
  153936. 0.5455823538F, 0.5475287304F, 0.5494737691F, 0.5514174337F,
  153937. 0.5533596881F, 0.5553004962F, 0.5572398218F, 0.5591776291F,
  153938. 0.5611138821F, 0.5630485449F, 0.5649815818F, 0.5669129570F,
  153939. 0.5688426349F, 0.5707705799F, 0.5726967564F, 0.5746211290F,
  153940. 0.5765436624F, 0.5784643212F, 0.5803830702F, 0.5822998743F,
  153941. 0.5842146984F, 0.5861275076F, 0.5880382669F, 0.5899469416F,
  153942. 0.5918534968F, 0.5937578981F, 0.5956601107F, 0.5975601004F,
  153943. 0.5994578326F, 0.6013532732F, 0.6032463880F, 0.6051371429F,
  153944. 0.6070255039F, 0.6089114372F, 0.6107949090F, 0.6126758856F,
  153945. 0.6145543334F, 0.6164302191F, 0.6183035092F, 0.6201741706F,
  153946. 0.6220421700F, 0.6239074745F, 0.6257700513F, 0.6276298674F,
  153947. 0.6294868903F, 0.6313410873F, 0.6331924262F, 0.6350408745F,
  153948. 0.6368864001F, 0.6387289710F, 0.6405685552F, 0.6424051209F,
  153949. 0.6442386364F, 0.6460690702F, 0.6478963910F, 0.6497205673F,
  153950. 0.6515415682F, 0.6533593625F, 0.6551739194F, 0.6569852082F,
  153951. 0.6587931984F, 0.6605978593F, 0.6623991609F, 0.6641970728F,
  153952. 0.6659915652F, 0.6677826081F, 0.6695701718F, 0.6713542268F,
  153953. 0.6731347437F, 0.6749116932F, 0.6766850461F, 0.6784547736F,
  153954. 0.6802208469F, 0.6819832374F, 0.6837419164F, 0.6854968559F,
  153955. 0.6872480275F, 0.6889954034F, 0.6907389556F, 0.6924786566F,
  153956. 0.6942144788F, 0.6959463950F, 0.6976743780F, 0.6993984008F,
  153957. 0.7011184365F, 0.7028344587F, 0.7045464407F, 0.7062543564F,
  153958. 0.7079581796F, 0.7096578844F, 0.7113534450F, 0.7130448359F,
  153959. 0.7147320316F, 0.7164150070F, 0.7180937371F, 0.7197681970F,
  153960. 0.7214383620F, 0.7231042077F, 0.7247657098F, 0.7264228443F,
  153961. 0.7280755871F, 0.7297239147F, 0.7313678035F, 0.7330072301F,
  153962. 0.7346421715F, 0.7362726046F, 0.7378985069F, 0.7395198556F,
  153963. 0.7411366285F, 0.7427488034F, 0.7443563584F, 0.7459592717F,
  153964. 0.7475575218F, 0.7491510873F, 0.7507399471F, 0.7523240803F,
  153965. 0.7539034661F, 0.7554780839F, 0.7570479136F, 0.7586129349F,
  153966. 0.7601731279F, 0.7617284730F, 0.7632789506F, 0.7648245416F,
  153967. 0.7663652267F, 0.7679009872F, 0.7694318044F, 0.7709576599F,
  153968. 0.7724785354F, 0.7739944130F, 0.7755052749F, 0.7770111035F,
  153969. 0.7785118815F, 0.7800075916F, 0.7814982170F, 0.7829837410F,
  153970. 0.7844641472F, 0.7859394191F, 0.7874095408F, 0.7888744965F,
  153971. 0.7903342706F, 0.7917888476F, 0.7932382124F, 0.7946823501F,
  153972. 0.7961212460F, 0.7975548855F, 0.7989832544F, 0.8004063386F,
  153973. 0.8018241244F, 0.8032365981F, 0.8046437463F, 0.8060455560F,
  153974. 0.8074420141F, 0.8088331080F, 0.8102188253F, 0.8115991536F,
  153975. 0.8129740810F, 0.8143435957F, 0.8157076861F, 0.8170663409F,
  153976. 0.8184195489F, 0.8197672994F, 0.8211095817F, 0.8224463853F,
  153977. 0.8237777001F, 0.8251035161F, 0.8264238235F, 0.8277386129F,
  153978. 0.8290478750F, 0.8303516008F, 0.8316497814F, 0.8329424083F,
  153979. 0.8342294731F, 0.8355109677F, 0.8367868841F, 0.8380572148F,
  153980. 0.8393219523F, 0.8405810893F, 0.8418346190F, 0.8430825345F,
  153981. 0.8443248294F, 0.8455614974F, 0.8467925323F, 0.8480179285F,
  153982. 0.8492376802F, 0.8504517822F, 0.8516602292F, 0.8528630164F,
  153983. 0.8540601391F, 0.8552515928F, 0.8564373733F, 0.8576174766F,
  153984. 0.8587918990F, 0.8599606368F, 0.8611236868F, 0.8622810460F,
  153985. 0.8634327113F, 0.8645786802F, 0.8657189504F, 0.8668535195F,
  153986. 0.8679823857F, 0.8691055472F, 0.8702230025F, 0.8713347503F,
  153987. 0.8724407896F, 0.8735411194F, 0.8746357394F, 0.8757246489F,
  153988. 0.8768078479F, 0.8778853364F, 0.8789571146F, 0.8800231832F,
  153989. 0.8810835427F, 0.8821381942F, 0.8831871387F, 0.8842303777F,
  153990. 0.8852679127F, 0.8862997456F, 0.8873258784F, 0.8883463132F,
  153991. 0.8893610527F, 0.8903700994F, 0.8913734562F, 0.8923711263F,
  153992. 0.8933631129F, 0.8943494196F, 0.8953300500F, 0.8963050083F,
  153993. 0.8972742985F, 0.8982379249F, 0.8991958922F, 0.9001482052F,
  153994. 0.9010948688F, 0.9020358883F, 0.9029712690F, 0.9039010165F,
  153995. 0.9048251367F, 0.9057436357F, 0.9066565195F, 0.9075637946F,
  153996. 0.9084654678F, 0.9093615456F, 0.9102520353F, 0.9111369440F,
  153997. 0.9120162792F, 0.9128900484F, 0.9137582595F, 0.9146209204F,
  153998. 0.9154780394F, 0.9163296248F, 0.9171756853F, 0.9180162296F,
  153999. 0.9188512667F, 0.9196808057F, 0.9205048559F, 0.9213234270F,
  154000. 0.9221365285F, 0.9229441704F, 0.9237463629F, 0.9245431160F,
  154001. 0.9253344404F, 0.9261203465F, 0.9269008453F, 0.9276759477F,
  154002. 0.9284456648F, 0.9292100080F, 0.9299689889F, 0.9307226190F,
  154003. 0.9314709103F, 0.9322138747F, 0.9329515245F, 0.9336838721F,
  154004. 0.9344109300F, 0.9351327108F, 0.9358492275F, 0.9365604931F,
  154005. 0.9372665208F, 0.9379673239F, 0.9386629160F, 0.9393533107F,
  154006. 0.9400385220F, 0.9407185637F, 0.9413934501F, 0.9420631954F,
  154007. 0.9427278141F, 0.9433873208F, 0.9440417304F, 0.9446910576F,
  154008. 0.9453353176F, 0.9459745255F, 0.9466086968F, 0.9472378469F,
  154009. 0.9478619915F, 0.9484811463F, 0.9490953274F, 0.9497045506F,
  154010. 0.9503088323F, 0.9509081888F, 0.9515026365F, 0.9520921921F,
  154011. 0.9526768723F, 0.9532566940F, 0.9538316742F, 0.9544018300F,
  154012. 0.9549671786F, 0.9555277375F, 0.9560835241F, 0.9566345562F,
  154013. 0.9571808513F, 0.9577224275F, 0.9582593027F, 0.9587914949F,
  154014. 0.9593190225F, 0.9598419038F, 0.9603601571F, 0.9608738012F,
  154015. 0.9613828546F, 0.9618873361F, 0.9623872646F, 0.9628826591F,
  154016. 0.9633735388F, 0.9638599227F, 0.9643418303F, 0.9648192808F,
  154017. 0.9652922939F, 0.9657608890F, 0.9662250860F, 0.9666849046F,
  154018. 0.9671403646F, 0.9675914861F, 0.9680382891F, 0.9684807937F,
  154019. 0.9689190202F, 0.9693529890F, 0.9697827203F, 0.9702082347F,
  154020. 0.9706295529F, 0.9710466953F, 0.9714596828F, 0.9718685362F,
  154021. 0.9722732762F, 0.9726739240F, 0.9730705005F, 0.9734630267F,
  154022. 0.9738515239F, 0.9742360134F, 0.9746165163F, 0.9749930540F,
  154023. 0.9753656481F, 0.9757343198F, 0.9760990909F, 0.9764599829F,
  154024. 0.9768170175F, 0.9771702164F, 0.9775196013F, 0.9778651941F,
  154025. 0.9782070167F, 0.9785450909F, 0.9788794388F, 0.9792100824F,
  154026. 0.9795370437F, 0.9798603449F, 0.9801800080F, 0.9804960554F,
  154027. 0.9808085092F, 0.9811173916F, 0.9814227251F, 0.9817245318F,
  154028. 0.9820228343F, 0.9823176549F, 0.9826090160F, 0.9828969402F,
  154029. 0.9831814498F, 0.9834625674F, 0.9837403156F, 0.9840147169F,
  154030. 0.9842857939F, 0.9845535692F, 0.9848180654F, 0.9850793052F,
  154031. 0.9853373113F, 0.9855921062F, 0.9858437127F, 0.9860921535F,
  154032. 0.9863374512F, 0.9865796287F, 0.9868187085F, 0.9870547136F,
  154033. 0.9872876664F, 0.9875175899F, 0.9877445067F, 0.9879684396F,
  154034. 0.9881894112F, 0.9884074444F, 0.9886225619F, 0.9888347863F,
  154035. 0.9890441404F, 0.9892506468F, 0.9894543284F, 0.9896552077F,
  154036. 0.9898533074F, 0.9900486502F, 0.9902412587F, 0.9904311555F,
  154037. 0.9906183633F, 0.9908029045F, 0.9909848019F, 0.9911640779F,
  154038. 0.9913407550F, 0.9915148557F, 0.9916864025F, 0.9918554179F,
  154039. 0.9920219241F, 0.9921859437F, 0.9923474989F, 0.9925066120F,
  154040. 0.9926633054F, 0.9928176012F, 0.9929695218F, 0.9931190891F,
  154041. 0.9932663254F, 0.9934112527F, 0.9935538932F, 0.9936942686F,
  154042. 0.9938324012F, 0.9939683126F, 0.9941020248F, 0.9942335597F,
  154043. 0.9943629388F, 0.9944901841F, 0.9946153170F, 0.9947383593F,
  154044. 0.9948593325F, 0.9949782579F, 0.9950951572F, 0.9952100516F,
  154045. 0.9953229625F, 0.9954339111F, 0.9955429186F, 0.9956500062F,
  154046. 0.9957551948F, 0.9958585056F, 0.9959599593F, 0.9960595769F,
  154047. 0.9961573792F, 0.9962533869F, 0.9963476206F, 0.9964401009F,
  154048. 0.9965308483F, 0.9966198833F, 0.9967072261F, 0.9967928971F,
  154049. 0.9968769164F, 0.9969593041F, 0.9970400804F, 0.9971192651F,
  154050. 0.9971968781F, 0.9972729391F, 0.9973474680F, 0.9974204842F,
  154051. 0.9974920074F, 0.9975620569F, 0.9976306521F, 0.9976978122F,
  154052. 0.9977635565F, 0.9978279039F, 0.9978908736F, 0.9979524842F,
  154053. 0.9980127547F, 0.9980717037F, 0.9981293499F, 0.9981857116F,
  154054. 0.9982408073F, 0.9982946554F, 0.9983472739F, 0.9983986810F,
  154055. 0.9984488947F, 0.9984979328F, 0.9985458132F, 0.9985925534F,
  154056. 0.9986381711F, 0.9986826838F, 0.9987261086F, 0.9987684630F,
  154057. 0.9988097640F, 0.9988500286F, 0.9988892738F, 0.9989275163F,
  154058. 0.9989647727F, 0.9990010597F, 0.9990363938F, 0.9990707911F,
  154059. 0.9991042679F, 0.9991368404F, 0.9991685244F, 0.9991993358F,
  154060. 0.9992292905F, 0.9992584038F, 0.9992866914F, 0.9993141686F,
  154061. 0.9993408506F, 0.9993667526F, 0.9993918895F, 0.9994162761F,
  154062. 0.9994399273F, 0.9994628576F, 0.9994850815F, 0.9995066133F,
  154063. 0.9995274672F, 0.9995476574F, 0.9995671978F, 0.9995861021F,
  154064. 0.9996043841F, 0.9996220573F, 0.9996391352F, 0.9996556310F,
  154065. 0.9996715579F, 0.9996869288F, 0.9997017568F, 0.9997160543F,
  154066. 0.9997298342F, 0.9997431088F, 0.9997558905F, 0.9997681914F,
  154067. 0.9997800236F, 0.9997913990F, 0.9998023292F, 0.9998128261F,
  154068. 0.9998229009F, 0.9998325650F, 0.9998418296F, 0.9998507058F,
  154069. 0.9998592044F, 0.9998673362F, 0.9998751117F, 0.9998825415F,
  154070. 0.9998896358F, 0.9998964047F, 0.9999028584F, 0.9999090066F,
  154071. 0.9999148590F, 0.9999204253F, 0.9999257148F, 0.9999307368F,
  154072. 0.9999355003F, 0.9999400144F, 0.9999442878F, 0.9999483293F,
  154073. 0.9999521472F, 0.9999557499F, 0.9999591457F, 0.9999623426F,
  154074. 0.9999653483F, 0.9999681708F, 0.9999708175F, 0.9999732959F,
  154075. 0.9999756132F, 0.9999777765F, 0.9999797928F, 0.9999816688F,
  154076. 0.9999834113F, 0.9999850266F, 0.9999865211F, 0.9999879009F,
  154077. 0.9999891721F, 0.9999903405F, 0.9999914118F, 0.9999923914F,
  154078. 0.9999932849F, 0.9999940972F, 0.9999948336F, 0.9999954989F,
  154079. 0.9999960978F, 0.9999966349F, 0.9999971146F, 0.9999975411F,
  154080. 0.9999979185F, 0.9999982507F, 0.9999985414F, 0.9999987944F,
  154081. 0.9999990129F, 0.9999992003F, 0.9999993596F, 0.9999994939F,
  154082. 0.9999996059F, 0.9999996981F, 0.9999997732F, 0.9999998333F,
  154083. 0.9999998805F, 0.9999999170F, 0.9999999444F, 0.9999999643F,
  154084. 0.9999999784F, 0.9999999878F, 0.9999999937F, 0.9999999972F,
  154085. 0.9999999990F, 0.9999999997F, 1.0000000000F, 1.0000000000F,
  154086. };
  154087. static float vwin4096[2048] = {
  154088. 0.0000002310F, 0.0000020791F, 0.0000057754F, 0.0000113197F,
  154089. 0.0000187121F, 0.0000279526F, 0.0000390412F, 0.0000519777F,
  154090. 0.0000667623F, 0.0000833949F, 0.0001018753F, 0.0001222036F,
  154091. 0.0001443798F, 0.0001684037F, 0.0001942754F, 0.0002219947F,
  154092. 0.0002515616F, 0.0002829761F, 0.0003162380F, 0.0003513472F,
  154093. 0.0003883038F, 0.0004271076F, 0.0004677584F, 0.0005102563F,
  154094. 0.0005546011F, 0.0006007928F, 0.0006488311F, 0.0006987160F,
  154095. 0.0007504474F, 0.0008040251F, 0.0008594490F, 0.0009167191F,
  154096. 0.0009758351F, 0.0010367969F, 0.0010996044F, 0.0011642574F,
  154097. 0.0012307558F, 0.0012990994F, 0.0013692880F, 0.0014413216F,
  154098. 0.0015151998F, 0.0015909226F, 0.0016684898F, 0.0017479011F,
  154099. 0.0018291565F, 0.0019122556F, 0.0019971983F, 0.0020839845F,
  154100. 0.0021726138F, 0.0022630861F, 0.0023554012F, 0.0024495588F,
  154101. 0.0025455588F, 0.0026434008F, 0.0027430847F, 0.0028446103F,
  154102. 0.0029479772F, 0.0030531853F, 0.0031602342F, 0.0032691238F,
  154103. 0.0033798538F, 0.0034924239F, 0.0036068338F, 0.0037230833F,
  154104. 0.0038411721F, 0.0039610999F, 0.0040828664F, 0.0042064714F,
  154105. 0.0043319145F, 0.0044591954F, 0.0045883139F, 0.0047192696F,
  154106. 0.0048520622F, 0.0049866914F, 0.0051231569F, 0.0052614583F,
  154107. 0.0054015953F, 0.0055435676F, 0.0056873748F, 0.0058330166F,
  154108. 0.0059804926F, 0.0061298026F, 0.0062809460F, 0.0064339226F,
  154109. 0.0065887320F, 0.0067453738F, 0.0069038476F, 0.0070641531F,
  154110. 0.0072262899F, 0.0073902575F, 0.0075560556F, 0.0077236838F,
  154111. 0.0078931417F, 0.0080644288F, 0.0082375447F, 0.0084124891F,
  154112. 0.0085892615F, 0.0087678614F, 0.0089482885F, 0.0091305422F,
  154113. 0.0093146223F, 0.0095005281F, 0.0096882592F, 0.0098778153F,
  154114. 0.0100691958F, 0.0102624002F, 0.0104574281F, 0.0106542791F,
  154115. 0.0108529525F, 0.0110534480F, 0.0112557651F, 0.0114599032F,
  154116. 0.0116658618F, 0.0118736405F, 0.0120832387F, 0.0122946560F,
  154117. 0.0125078917F, 0.0127229454F, 0.0129398166F, 0.0131585046F,
  154118. 0.0133790090F, 0.0136013292F, 0.0138254647F, 0.0140514149F,
  154119. 0.0142791792F, 0.0145087572F, 0.0147401481F, 0.0149733515F,
  154120. 0.0152083667F, 0.0154451932F, 0.0156838304F, 0.0159242777F,
  154121. 0.0161665345F, 0.0164106001F, 0.0166564741F, 0.0169041557F,
  154122. 0.0171536443F, 0.0174049393F, 0.0176580401F, 0.0179129461F,
  154123. 0.0181696565F, 0.0184281708F, 0.0186884883F, 0.0189506084F,
  154124. 0.0192145303F, 0.0194802535F, 0.0197477772F, 0.0200171008F,
  154125. 0.0202882236F, 0.0205611449F, 0.0208358639F, 0.0211123801F,
  154126. 0.0213906927F, 0.0216708011F, 0.0219527043F, 0.0222364019F,
  154127. 0.0225218930F, 0.0228091769F, 0.0230982529F, 0.0233891203F,
  154128. 0.0236817782F, 0.0239762259F, 0.0242724628F, 0.0245704880F,
  154129. 0.0248703007F, 0.0251719002F, 0.0254752858F, 0.0257804565F,
  154130. 0.0260874117F, 0.0263961506F, 0.0267066722F, 0.0270189760F,
  154131. 0.0273330609F, 0.0276489263F, 0.0279665712F, 0.0282859949F,
  154132. 0.0286071966F, 0.0289301753F, 0.0292549303F, 0.0295814607F,
  154133. 0.0299097656F, 0.0302398442F, 0.0305716957F, 0.0309053191F,
  154134. 0.0312407135F, 0.0315778782F, 0.0319168122F, 0.0322575145F,
  154135. 0.0325999844F, 0.0329442209F, 0.0332902231F, 0.0336379900F,
  154136. 0.0339875208F, 0.0343388146F, 0.0346918703F, 0.0350466871F,
  154137. 0.0354032640F, 0.0357616000F, 0.0361216943F, 0.0364835458F,
  154138. 0.0368471535F, 0.0372125166F, 0.0375796339F, 0.0379485046F,
  154139. 0.0383191276F, 0.0386915020F, 0.0390656267F, 0.0394415008F,
  154140. 0.0398191231F, 0.0401984927F, 0.0405796086F, 0.0409624698F,
  154141. 0.0413470751F, 0.0417334235F, 0.0421215141F, 0.0425113457F,
  154142. 0.0429029172F, 0.0432962277F, 0.0436912760F, 0.0440880610F,
  154143. 0.0444865817F, 0.0448868370F, 0.0452888257F, 0.0456925468F,
  154144. 0.0460979992F, 0.0465051816F, 0.0469140931F, 0.0473247325F,
  154145. 0.0477370986F, 0.0481511902F, 0.0485670064F, 0.0489845458F,
  154146. 0.0494038074F, 0.0498247899F, 0.0502474922F, 0.0506719131F,
  154147. 0.0510980514F, 0.0515259060F, 0.0519554756F, 0.0523867590F,
  154148. 0.0528197550F, 0.0532544624F, 0.0536908800F, 0.0541290066F,
  154149. 0.0545688408F, 0.0550103815F, 0.0554536274F, 0.0558985772F,
  154150. 0.0563452297F, 0.0567935837F, 0.0572436377F, 0.0576953907F,
  154151. 0.0581488412F, 0.0586039880F, 0.0590608297F, 0.0595193651F,
  154152. 0.0599795929F, 0.0604415117F, 0.0609051202F, 0.0613704170F,
  154153. 0.0618374009F, 0.0623060704F, 0.0627764243F, 0.0632484611F,
  154154. 0.0637221795F, 0.0641975781F, 0.0646746555F, 0.0651534104F,
  154155. 0.0656338413F, 0.0661159469F, 0.0665997257F, 0.0670851763F,
  154156. 0.0675722973F, 0.0680610873F, 0.0685515448F, 0.0690436684F,
  154157. 0.0695374567F, 0.0700329081F, 0.0705300213F, 0.0710287947F,
  154158. 0.0715292269F, 0.0720313163F, 0.0725350616F, 0.0730404612F,
  154159. 0.0735475136F, 0.0740562172F, 0.0745665707F, 0.0750785723F,
  154160. 0.0755922207F, 0.0761075143F, 0.0766244515F, 0.0771430307F,
  154161. 0.0776632505F, 0.0781851092F, 0.0787086052F, 0.0792337371F,
  154162. 0.0797605032F, 0.0802889018F, 0.0808189315F, 0.0813505905F,
  154163. 0.0818838773F, 0.0824187903F, 0.0829553277F, 0.0834934881F,
  154164. 0.0840332697F, 0.0845746708F, 0.0851176899F, 0.0856623252F,
  154165. 0.0862085751F, 0.0867564379F, 0.0873059119F, 0.0878569954F,
  154166. 0.0884096867F, 0.0889639840F, 0.0895198858F, 0.0900773902F,
  154167. 0.0906364955F, 0.0911972000F, 0.0917595019F, 0.0923233995F,
  154168. 0.0928888909F, 0.0934559745F, 0.0940246485F, 0.0945949110F,
  154169. 0.0951667604F, 0.0957401946F, 0.0963152121F, 0.0968918109F,
  154170. 0.0974699893F, 0.0980497454F, 0.0986310773F, 0.0992139832F,
  154171. 0.0997984614F, 0.1003845098F, 0.1009721267F, 0.1015613101F,
  154172. 0.1021520582F, 0.1027443692F, 0.1033382410F, 0.1039336718F,
  154173. 0.1045306597F, 0.1051292027F, 0.1057292990F, 0.1063309466F,
  154174. 0.1069341435F, 0.1075388878F, 0.1081451776F, 0.1087530108F,
  154175. 0.1093623856F, 0.1099732998F, 0.1105857516F, 0.1111997389F,
  154176. 0.1118152597F, 0.1124323121F, 0.1130508939F, 0.1136710032F,
  154177. 0.1142926379F, 0.1149157960F, 0.1155404755F, 0.1161666742F,
  154178. 0.1167943901F, 0.1174236211F, 0.1180543652F, 0.1186866202F,
  154179. 0.1193203841F, 0.1199556548F, 0.1205924300F, 0.1212307078F,
  154180. 0.1218704860F, 0.1225117624F, 0.1231545349F, 0.1237988013F,
  154181. 0.1244445596F, 0.1250918074F, 0.1257405427F, 0.1263907632F,
  154182. 0.1270424667F, 0.1276956512F, 0.1283503142F, 0.1290064537F,
  154183. 0.1296640674F, 0.1303231530F, 0.1309837084F, 0.1316457312F,
  154184. 0.1323092193F, 0.1329741703F, 0.1336405820F, 0.1343084520F,
  154185. 0.1349777782F, 0.1356485582F, 0.1363207897F, 0.1369944704F,
  154186. 0.1376695979F, 0.1383461700F, 0.1390241842F, 0.1397036384F,
  154187. 0.1403845300F, 0.1410668567F, 0.1417506162F, 0.1424358061F,
  154188. 0.1431224240F, 0.1438104674F, 0.1444999341F, 0.1451908216F,
  154189. 0.1458831274F, 0.1465768492F, 0.1472719844F, 0.1479685308F,
  154190. 0.1486664857F, 0.1493658468F, 0.1500666115F, 0.1507687775F,
  154191. 0.1514723422F, 0.1521773031F, 0.1528836577F, 0.1535914035F,
  154192. 0.1543005380F, 0.1550110587F, 0.1557229631F, 0.1564362485F,
  154193. 0.1571509124F, 0.1578669524F, 0.1585843657F, 0.1593031499F,
  154194. 0.1600233024F, 0.1607448205F, 0.1614677017F, 0.1621919433F,
  154195. 0.1629175428F, 0.1636444975F, 0.1643728047F, 0.1651024619F,
  154196. 0.1658334665F, 0.1665658156F, 0.1672995067F, 0.1680345371F,
  154197. 0.1687709041F, 0.1695086050F, 0.1702476372F, 0.1709879978F,
  154198. 0.1717296843F, 0.1724726938F, 0.1732170237F, 0.1739626711F,
  154199. 0.1747096335F, 0.1754579079F, 0.1762074916F, 0.1769583819F,
  154200. 0.1777105760F, 0.1784640710F, 0.1792188642F, 0.1799749529F,
  154201. 0.1807323340F, 0.1814910049F, 0.1822509628F, 0.1830122046F,
  154202. 0.1837747277F, 0.1845385292F, 0.1853036062F, 0.1860699558F,
  154203. 0.1868375751F, 0.1876064613F, 0.1883766114F, 0.1891480226F,
  154204. 0.1899206919F, 0.1906946164F, 0.1914697932F, 0.1922462194F,
  154205. 0.1930238919F, 0.1938028079F, 0.1945829643F, 0.1953643583F,
  154206. 0.1961469868F, 0.1969308468F, 0.1977159353F, 0.1985022494F,
  154207. 0.1992897859F, 0.2000785420F, 0.2008685145F, 0.2016597005F,
  154208. 0.2024520968F, 0.2032457005F, 0.2040405084F, 0.2048365175F,
  154209. 0.2056337247F, 0.2064321269F, 0.2072317211F, 0.2080325041F,
  154210. 0.2088344727F, 0.2096376240F, 0.2104419547F, 0.2112474618F,
  154211. 0.2120541420F, 0.2128619923F, 0.2136710094F, 0.2144811902F,
  154212. 0.2152925315F, 0.2161050301F, 0.2169186829F, 0.2177334866F,
  154213. 0.2185494381F, 0.2193665340F, 0.2201847712F, 0.2210041465F,
  154214. 0.2218246565F, 0.2226462981F, 0.2234690680F, 0.2242929629F,
  154215. 0.2251179796F, 0.2259441147F, 0.2267713650F, 0.2275997272F,
  154216. 0.2284291979F, 0.2292597739F, 0.2300914518F, 0.2309242283F,
  154217. 0.2317581001F, 0.2325930638F, 0.2334291160F, 0.2342662534F,
  154218. 0.2351044727F, 0.2359437703F, 0.2367841431F, 0.2376255875F,
  154219. 0.2384681001F, 0.2393116776F, 0.2401563165F, 0.2410020134F,
  154220. 0.2418487649F, 0.2426965675F, 0.2435454178F, 0.2443953122F,
  154221. 0.2452462474F, 0.2460982199F, 0.2469512262F, 0.2478052628F,
  154222. 0.2486603262F, 0.2495164129F, 0.2503735194F, 0.2512316421F,
  154223. 0.2520907776F, 0.2529509222F, 0.2538120726F, 0.2546742250F,
  154224. 0.2555373760F, 0.2564015219F, 0.2572666593F, 0.2581327845F,
  154225. 0.2589998939F, 0.2598679840F, 0.2607370510F, 0.2616070916F,
  154226. 0.2624781019F, 0.2633500783F, 0.2642230173F, 0.2650969152F,
  154227. 0.2659717684F, 0.2668475731F, 0.2677243257F, 0.2686020226F,
  154228. 0.2694806601F, 0.2703602344F, 0.2712407419F, 0.2721221789F,
  154229. 0.2730045417F, 0.2738878265F, 0.2747720297F, 0.2756571474F,
  154230. 0.2765431760F, 0.2774301117F, 0.2783179508F, 0.2792066895F,
  154231. 0.2800963240F, 0.2809868505F, 0.2818782654F, 0.2827705647F,
  154232. 0.2836637447F, 0.2845578016F, 0.2854527315F, 0.2863485307F,
  154233. 0.2872451953F, 0.2881427215F, 0.2890411055F, 0.2899403433F,
  154234. 0.2908404312F, 0.2917413654F, 0.2926431418F, 0.2935457567F,
  154235. 0.2944492061F, 0.2953534863F, 0.2962585932F, 0.2971645230F,
  154236. 0.2980712717F, 0.2989788356F, 0.2998872105F, 0.3007963927F,
  154237. 0.3017063781F, 0.3026171629F, 0.3035287430F, 0.3044411145F,
  154238. 0.3053542736F, 0.3062682161F, 0.3071829381F, 0.3080984356F,
  154239. 0.3090147047F, 0.3099317413F, 0.3108495414F, 0.3117681011F,
  154240. 0.3126874163F, 0.3136074830F, 0.3145282972F, 0.3154498548F,
  154241. 0.3163721517F, 0.3172951841F, 0.3182189477F, 0.3191434385F,
  154242. 0.3200686525F, 0.3209945856F, 0.3219212336F, 0.3228485927F,
  154243. 0.3237766585F, 0.3247054271F, 0.3256348943F, 0.3265650560F,
  154244. 0.3274959081F, 0.3284274465F, 0.3293596671F, 0.3302925657F,
  154245. 0.3312261382F, 0.3321603804F, 0.3330952882F, 0.3340308574F,
  154246. 0.3349670838F, 0.3359039634F, 0.3368414919F, 0.3377796651F,
  154247. 0.3387184789F, 0.3396579290F, 0.3405980113F, 0.3415387216F,
  154248. 0.3424800556F, 0.3434220091F, 0.3443645779F, 0.3453077578F,
  154249. 0.3462515446F, 0.3471959340F, 0.3481409217F, 0.3490865036F,
  154250. 0.3500326754F, 0.3509794328F, 0.3519267715F, 0.3528746873F,
  154251. 0.3538231759F, 0.3547722330F, 0.3557218544F, 0.3566720357F,
  154252. 0.3576227727F, 0.3585740610F, 0.3595258964F, 0.3604782745F,
  154253. 0.3614311910F, 0.3623846417F, 0.3633386221F, 0.3642931280F,
  154254. 0.3652481549F, 0.3662036987F, 0.3671597548F, 0.3681163191F,
  154255. 0.3690733870F, 0.3700309544F, 0.3709890167F, 0.3719475696F,
  154256. 0.3729066089F, 0.3738661299F, 0.3748261285F, 0.3757866002F,
  154257. 0.3767475406F, 0.3777089453F, 0.3786708100F, 0.3796331302F,
  154258. 0.3805959014F, 0.3815591194F, 0.3825227796F, 0.3834868777F,
  154259. 0.3844514093F, 0.3854163698F, 0.3863817549F, 0.3873475601F,
  154260. 0.3883137810F, 0.3892804131F, 0.3902474521F, 0.3912148933F,
  154261. 0.3921827325F, 0.3931509650F, 0.3941195865F, 0.3950885925F,
  154262. 0.3960579785F, 0.3970277400F, 0.3979978725F, 0.3989683716F,
  154263. 0.3999392328F, 0.4009104516F, 0.4018820234F, 0.4028539438F,
  154264. 0.4038262084F, 0.4047988125F, 0.4057717516F, 0.4067450214F,
  154265. 0.4077186172F, 0.4086925345F, 0.4096667688F, 0.4106413155F,
  154266. 0.4116161703F, 0.4125913284F, 0.4135667854F, 0.4145425368F,
  154267. 0.4155185780F, 0.4164949044F, 0.4174715116F, 0.4184483949F,
  154268. 0.4194255498F, 0.4204029718F, 0.4213806563F, 0.4223585987F,
  154269. 0.4233367946F, 0.4243152392F, 0.4252939281F, 0.4262728566F,
  154270. 0.4272520202F, 0.4282314144F, 0.4292110345F, 0.4301908760F,
  154271. 0.4311709343F, 0.4321512047F, 0.4331316828F, 0.4341123639F,
  154272. 0.4350932435F, 0.4360743168F, 0.4370555794F, 0.4380370267F,
  154273. 0.4390186540F, 0.4400004567F, 0.4409824303F, 0.4419645701F,
  154274. 0.4429468716F, 0.4439293300F, 0.4449119409F, 0.4458946996F,
  154275. 0.4468776014F, 0.4478606418F, 0.4488438162F, 0.4498271199F,
  154276. 0.4508105483F, 0.4517940967F, 0.4527777607F, 0.4537615355F,
  154277. 0.4547454165F, 0.4557293991F, 0.4567134786F, 0.4576976505F,
  154278. 0.4586819101F, 0.4596662527F, 0.4606506738F, 0.4616351687F,
  154279. 0.4626197328F, 0.4636043614F, 0.4645890499F, 0.4655737936F,
  154280. 0.4665585880F, 0.4675434284F, 0.4685283101F, 0.4695132286F,
  154281. 0.4704981791F, 0.4714831570F, 0.4724681577F, 0.4734531766F,
  154282. 0.4744382089F, 0.4754232501F, 0.4764082956F, 0.4773933406F,
  154283. 0.4783783806F, 0.4793634108F, 0.4803484267F, 0.4813334237F,
  154284. 0.4823183969F, 0.4833033419F, 0.4842882540F, 0.4852731285F,
  154285. 0.4862579608F, 0.4872427462F, 0.4882274802F, 0.4892121580F,
  154286. 0.4901967751F, 0.4911813267F, 0.4921658083F, 0.4931502151F,
  154287. 0.4941345427F, 0.4951187863F, 0.4961029412F, 0.4970870029F,
  154288. 0.4980709667F, 0.4990548280F, 0.5000385822F, 0.5010222245F,
  154289. 0.5020057505F, 0.5029891553F, 0.5039724345F, 0.5049555834F,
  154290. 0.5059385973F, 0.5069214716F, 0.5079042018F, 0.5088867831F,
  154291. 0.5098692110F, 0.5108514808F, 0.5118335879F, 0.5128155277F,
  154292. 0.5137972956F, 0.5147788869F, 0.5157602971F, 0.5167415215F,
  154293. 0.5177225555F, 0.5187033945F, 0.5196840339F, 0.5206644692F,
  154294. 0.5216446956F, 0.5226247086F, 0.5236045035F, 0.5245840759F,
  154295. 0.5255634211F, 0.5265425344F, 0.5275214114F, 0.5285000474F,
  154296. 0.5294784378F, 0.5304565781F, 0.5314344637F, 0.5324120899F,
  154297. 0.5333894522F, 0.5343665461F, 0.5353433670F, 0.5363199102F,
  154298. 0.5372961713F, 0.5382721457F, 0.5392478287F, 0.5402232159F,
  154299. 0.5411983027F, 0.5421730845F, 0.5431475569F, 0.5441217151F,
  154300. 0.5450955548F, 0.5460690714F, 0.5470422602F, 0.5480151169F,
  154301. 0.5489876368F, 0.5499598155F, 0.5509316484F, 0.5519031310F,
  154302. 0.5528742587F, 0.5538450271F, 0.5548154317F, 0.5557854680F,
  154303. 0.5567551314F, 0.5577244174F, 0.5586933216F, 0.5596618395F,
  154304. 0.5606299665F, 0.5615976983F, 0.5625650302F, 0.5635319580F,
  154305. 0.5644984770F, 0.5654645828F, 0.5664302709F, 0.5673955370F,
  154306. 0.5683603765F, 0.5693247850F, 0.5702887580F, 0.5712522912F,
  154307. 0.5722153800F, 0.5731780200F, 0.5741402069F, 0.5751019362F,
  154308. 0.5760632034F, 0.5770240042F, 0.5779843341F, 0.5789441889F,
  154309. 0.5799035639F, 0.5808624549F, 0.5818208575F, 0.5827787673F,
  154310. 0.5837361800F, 0.5846930910F, 0.5856494961F, 0.5866053910F,
  154311. 0.5875607712F, 0.5885156324F, 0.5894699703F, 0.5904237804F,
  154312. 0.5913770586F, 0.5923298004F, 0.5932820016F, 0.5942336578F,
  154313. 0.5951847646F, 0.5961353179F, 0.5970853132F, 0.5980347464F,
  154314. 0.5989836131F, 0.5999319090F, 0.6008796298F, 0.6018267713F,
  154315. 0.6027733292F, 0.6037192993F, 0.6046646773F, 0.6056094589F,
  154316. 0.6065536400F, 0.6074972162F, 0.6084401833F, 0.6093825372F,
  154317. 0.6103242736F, 0.6112653884F, 0.6122058772F, 0.6131457359F,
  154318. 0.6140849604F, 0.6150235464F, 0.6159614897F, 0.6168987862F,
  154319. 0.6178354318F, 0.6187714223F, 0.6197067535F, 0.6206414213F,
  154320. 0.6215754215F, 0.6225087501F, 0.6234414028F, 0.6243733757F,
  154321. 0.6253046646F, 0.6262352654F, 0.6271651739F, 0.6280943862F,
  154322. 0.6290228982F, 0.6299507057F, 0.6308778048F, 0.6318041913F,
  154323. 0.6327298612F, 0.6336548105F, 0.6345790352F, 0.6355025312F,
  154324. 0.6364252945F, 0.6373473211F, 0.6382686070F, 0.6391891483F,
  154325. 0.6401089409F, 0.6410279808F, 0.6419462642F, 0.6428637869F,
  154326. 0.6437805452F, 0.6446965350F, 0.6456117524F, 0.6465261935F,
  154327. 0.6474398544F, 0.6483527311F, 0.6492648197F, 0.6501761165F,
  154328. 0.6510866174F, 0.6519963186F, 0.6529052162F, 0.6538133064F,
  154329. 0.6547205854F, 0.6556270492F, 0.6565326941F, 0.6574375162F,
  154330. 0.6583415117F, 0.6592446769F, 0.6601470079F, 0.6610485009F,
  154331. 0.6619491521F, 0.6628489578F, 0.6637479143F, 0.6646460177F,
  154332. 0.6655432643F, 0.6664396505F, 0.6673351724F, 0.6682298264F,
  154333. 0.6691236087F, 0.6700165157F, 0.6709085436F, 0.6717996889F,
  154334. 0.6726899478F, 0.6735793167F, 0.6744677918F, 0.6753553697F,
  154335. 0.6762420466F, 0.6771278190F, 0.6780126832F, 0.6788966357F,
  154336. 0.6797796728F, 0.6806617909F, 0.6815429866F, 0.6824232562F,
  154337. 0.6833025961F, 0.6841810030F, 0.6850584731F, 0.6859350031F,
  154338. 0.6868105894F, 0.6876852284F, 0.6885589168F, 0.6894316510F,
  154339. 0.6903034275F, 0.6911742430F, 0.6920440939F, 0.6929129769F,
  154340. 0.6937808884F, 0.6946478251F, 0.6955137837F, 0.6963787606F,
  154341. 0.6972427525F, 0.6981057560F, 0.6989677678F, 0.6998287845F,
  154342. 0.7006888028F, 0.7015478194F, 0.7024058309F, 0.7032628340F,
  154343. 0.7041188254F, 0.7049738019F, 0.7058277601F, 0.7066806969F,
  154344. 0.7075326089F, 0.7083834929F, 0.7092333457F, 0.7100821640F,
  154345. 0.7109299447F, 0.7117766846F, 0.7126223804F, 0.7134670291F,
  154346. 0.7143106273F, 0.7151531721F, 0.7159946602F, 0.7168350885F,
  154347. 0.7176744539F, 0.7185127534F, 0.7193499837F, 0.7201861418F,
  154348. 0.7210212247F, 0.7218552293F, 0.7226881526F, 0.7235199914F,
  154349. 0.7243507428F, 0.7251804039F, 0.7260089715F, 0.7268364426F,
  154350. 0.7276628144F, 0.7284880839F, 0.7293122481F, 0.7301353040F,
  154351. 0.7309572487F, 0.7317780794F, 0.7325977930F, 0.7334163868F,
  154352. 0.7342338579F, 0.7350502033F, 0.7358654202F, 0.7366795059F,
  154353. 0.7374924573F, 0.7383042718F, 0.7391149465F, 0.7399244787F,
  154354. 0.7407328655F, 0.7415401041F, 0.7423461920F, 0.7431511261F,
  154355. 0.7439549040F, 0.7447575227F, 0.7455589797F, 0.7463592723F,
  154356. 0.7471583976F, 0.7479563532F, 0.7487531363F, 0.7495487443F,
  154357. 0.7503431745F, 0.7511364244F, 0.7519284913F, 0.7527193726F,
  154358. 0.7535090658F, 0.7542975683F, 0.7550848776F, 0.7558709910F,
  154359. 0.7566559062F, 0.7574396205F, 0.7582221314F, 0.7590034366F,
  154360. 0.7597835334F, 0.7605624194F, 0.7613400923F, 0.7621165495F,
  154361. 0.7628917886F, 0.7636658072F, 0.7644386030F, 0.7652101735F,
  154362. 0.7659805164F, 0.7667496292F, 0.7675175098F, 0.7682841556F,
  154363. 0.7690495645F, 0.7698137341F, 0.7705766622F, 0.7713383463F,
  154364. 0.7720987844F, 0.7728579741F, 0.7736159132F, 0.7743725994F,
  154365. 0.7751280306F, 0.7758822046F, 0.7766351192F, 0.7773867722F,
  154366. 0.7781371614F, 0.7788862848F, 0.7796341401F, 0.7803807253F,
  154367. 0.7811260383F, 0.7818700769F, 0.7826128392F, 0.7833543230F,
  154368. 0.7840945263F, 0.7848334471F, 0.7855710833F, 0.7863074330F,
  154369. 0.7870424941F, 0.7877762647F, 0.7885087428F, 0.7892399264F,
  154370. 0.7899698137F, 0.7906984026F, 0.7914256914F, 0.7921516780F,
  154371. 0.7928763607F, 0.7935997375F, 0.7943218065F, 0.7950425661F,
  154372. 0.7957620142F, 0.7964801492F, 0.7971969692F, 0.7979124724F,
  154373. 0.7986266570F, 0.7993395214F, 0.8000510638F, 0.8007612823F,
  154374. 0.8014701754F, 0.8021777413F, 0.8028839784F, 0.8035888849F,
  154375. 0.8042924592F, 0.8049946997F, 0.8056956048F, 0.8063951727F,
  154376. 0.8070934020F, 0.8077902910F, 0.8084858381F, 0.8091800419F,
  154377. 0.8098729007F, 0.8105644130F, 0.8112545774F, 0.8119433922F,
  154378. 0.8126308561F, 0.8133169676F, 0.8140017251F, 0.8146851272F,
  154379. 0.8153671726F, 0.8160478598F, 0.8167271874F, 0.8174051539F,
  154380. 0.8180817582F, 0.8187569986F, 0.8194308741F, 0.8201033831F,
  154381. 0.8207745244F, 0.8214442966F, 0.8221126986F, 0.8227797290F,
  154382. 0.8234453865F, 0.8241096700F, 0.8247725781F, 0.8254341097F,
  154383. 0.8260942636F, 0.8267530385F, 0.8274104334F, 0.8280664470F,
  154384. 0.8287210782F, 0.8293743259F, 0.8300261889F, 0.8306766662F,
  154385. 0.8313257566F, 0.8319734591F, 0.8326197727F, 0.8332646963F,
  154386. 0.8339082288F, 0.8345503692F, 0.8351911167F, 0.8358304700F,
  154387. 0.8364684284F, 0.8371049907F, 0.8377401562F, 0.8383739238F,
  154388. 0.8390062927F, 0.8396372618F, 0.8402668305F, 0.8408949977F,
  154389. 0.8415217626F, 0.8421471245F, 0.8427710823F, 0.8433936354F,
  154390. 0.8440147830F, 0.8446345242F, 0.8452528582F, 0.8458697844F,
  154391. 0.8464853020F, 0.8470994102F, 0.8477121084F, 0.8483233958F,
  154392. 0.8489332718F, 0.8495417356F, 0.8501487866F, 0.8507544243F,
  154393. 0.8513586479F, 0.8519614568F, 0.8525628505F, 0.8531628283F,
  154394. 0.8537613897F, 0.8543585341F, 0.8549542611F, 0.8555485699F,
  154395. 0.8561414603F, 0.8567329315F, 0.8573229832F, 0.8579116149F,
  154396. 0.8584988262F, 0.8590846165F, 0.8596689855F, 0.8602519327F,
  154397. 0.8608334577F, 0.8614135603F, 0.8619922399F, 0.8625694962F,
  154398. 0.8631453289F, 0.8637197377F, 0.8642927222F, 0.8648642821F,
  154399. 0.8654344172F, 0.8660031272F, 0.8665704118F, 0.8671362708F,
  154400. 0.8677007039F, 0.8682637109F, 0.8688252917F, 0.8693854460F,
  154401. 0.8699441737F, 0.8705014745F, 0.8710573485F, 0.8716117953F,
  154402. 0.8721648150F, 0.8727164073F, 0.8732665723F, 0.8738153098F,
  154403. 0.8743626197F, 0.8749085021F, 0.8754529569F, 0.8759959840F,
  154404. 0.8765375835F, 0.8770777553F, 0.8776164996F, 0.8781538162F,
  154405. 0.8786897054F, 0.8792241670F, 0.8797572013F, 0.8802888082F,
  154406. 0.8808189880F, 0.8813477407F, 0.8818750664F, 0.8824009653F,
  154407. 0.8829254375F, 0.8834484833F, 0.8839701028F, 0.8844902961F,
  154408. 0.8850090636F, 0.8855264054F, 0.8860423218F, 0.8865568131F,
  154409. 0.8870698794F, 0.8875815212F, 0.8880917386F, 0.8886005319F,
  154410. 0.8891079016F, 0.8896138479F, 0.8901183712F, 0.8906214719F,
  154411. 0.8911231503F, 0.8916234067F, 0.8921222417F, 0.8926196556F,
  154412. 0.8931156489F, 0.8936102219F, 0.8941033752F, 0.8945951092F,
  154413. 0.8950854244F, 0.8955743212F, 0.8960618003F, 0.8965478621F,
  154414. 0.8970325071F, 0.8975157359F, 0.8979975490F, 0.8984779471F,
  154415. 0.8989569307F, 0.8994345004F, 0.8999106568F, 0.9003854005F,
  154416. 0.9008587323F, 0.9013306526F, 0.9018011623F, 0.9022702619F,
  154417. 0.9027379521F, 0.9032042337F, 0.9036691074F, 0.9041325739F,
  154418. 0.9045946339F, 0.9050552882F, 0.9055145376F, 0.9059723828F,
  154419. 0.9064288246F, 0.9068838638F, 0.9073375013F, 0.9077897379F,
  154420. 0.9082405743F, 0.9086900115F, 0.9091380503F, 0.9095846917F,
  154421. 0.9100299364F, 0.9104737854F, 0.9109162397F, 0.9113573001F,
  154422. 0.9117969675F, 0.9122352430F, 0.9126721275F, 0.9131076219F,
  154423. 0.9135417273F, 0.9139744447F, 0.9144057750F, 0.9148357194F,
  154424. 0.9152642787F, 0.9156914542F, 0.9161172468F, 0.9165416576F,
  154425. 0.9169646877F, 0.9173863382F, 0.9178066102F, 0.9182255048F,
  154426. 0.9186430232F, 0.9190591665F, 0.9194739359F, 0.9198873324F,
  154427. 0.9202993574F, 0.9207100120F, 0.9211192973F, 0.9215272147F,
  154428. 0.9219337653F, 0.9223389504F, 0.9227427713F, 0.9231452290F,
  154429. 0.9235463251F, 0.9239460607F, 0.9243444371F, 0.9247414557F,
  154430. 0.9251371177F, 0.9255314245F, 0.9259243774F, 0.9263159778F,
  154431. 0.9267062270F, 0.9270951264F, 0.9274826774F, 0.9278688814F,
  154432. 0.9282537398F, 0.9286372540F, 0.9290194254F, 0.9294002555F,
  154433. 0.9297797458F, 0.9301578976F, 0.9305347125F, 0.9309101919F,
  154434. 0.9312843373F, 0.9316571503F, 0.9320286323F, 0.9323987849F,
  154435. 0.9327676097F, 0.9331351080F, 0.9335012816F, 0.9338661320F,
  154436. 0.9342296607F, 0.9345918694F, 0.9349527596F, 0.9353123330F,
  154437. 0.9356705911F, 0.9360275357F, 0.9363831683F, 0.9367374905F,
  154438. 0.9370905042F, 0.9374422108F, 0.9377926122F, 0.9381417099F,
  154439. 0.9384895057F, 0.9388360014F, 0.9391811985F, 0.9395250989F,
  154440. 0.9398677043F, 0.9402090165F, 0.9405490371F, 0.9408877680F,
  154441. 0.9412252110F, 0.9415613678F, 0.9418962402F, 0.9422298301F,
  154442. 0.9425621392F, 0.9428931695F, 0.9432229226F, 0.9435514005F,
  154443. 0.9438786050F, 0.9442045381F, 0.9445292014F, 0.9448525971F,
  154444. 0.9451747268F, 0.9454955926F, 0.9458151963F, 0.9461335399F,
  154445. 0.9464506253F, 0.9467664545F, 0.9470810293F, 0.9473943517F,
  154446. 0.9477064238F, 0.9480172474F, 0.9483268246F, 0.9486351573F,
  154447. 0.9489422475F, 0.9492480973F, 0.9495527087F, 0.9498560837F,
  154448. 0.9501582243F, 0.9504591325F, 0.9507588105F, 0.9510572603F,
  154449. 0.9513544839F, 0.9516504834F, 0.9519452609F, 0.9522388186F,
  154450. 0.9525311584F, 0.9528222826F, 0.9531121932F, 0.9534008923F,
  154451. 0.9536883821F, 0.9539746647F, 0.9542597424F, 0.9545436171F,
  154452. 0.9548262912F, 0.9551077667F, 0.9553880459F, 0.9556671309F,
  154453. 0.9559450239F, 0.9562217272F, 0.9564972429F, 0.9567715733F,
  154454. 0.9570447206F, 0.9573166871F, 0.9575874749F, 0.9578570863F,
  154455. 0.9581255236F, 0.9583927890F, 0.9586588849F, 0.9589238134F,
  154456. 0.9591875769F, 0.9594501777F, 0.9597116180F, 0.9599719003F,
  154457. 0.9602310267F, 0.9604889995F, 0.9607458213F, 0.9610014942F,
  154458. 0.9612560206F, 0.9615094028F, 0.9617616433F, 0.9620127443F,
  154459. 0.9622627083F, 0.9625115376F, 0.9627592345F, 0.9630058016F,
  154460. 0.9632512411F, 0.9634955555F, 0.9637387471F, 0.9639808185F,
  154461. 0.9642217720F, 0.9644616100F, 0.9647003349F, 0.9649379493F,
  154462. 0.9651744556F, 0.9654098561F, 0.9656441534F, 0.9658773499F,
  154463. 0.9661094480F, 0.9663404504F, 0.9665703593F, 0.9667991774F,
  154464. 0.9670269071F, 0.9672535509F, 0.9674791114F, 0.9677035909F,
  154465. 0.9679269921F, 0.9681493174F, 0.9683705694F, 0.9685907506F,
  154466. 0.9688098636F, 0.9690279108F, 0.9692448948F, 0.9694608182F,
  154467. 0.9696756836F, 0.9698894934F, 0.9701022503F, 0.9703139569F,
  154468. 0.9705246156F, 0.9707342291F, 0.9709428000F, 0.9711503309F,
  154469. 0.9713568243F, 0.9715622829F, 0.9717667093F, 0.9719701060F,
  154470. 0.9721724757F, 0.9723738210F, 0.9725741446F, 0.9727734490F,
  154471. 0.9729717369F, 0.9731690109F, 0.9733652737F, 0.9735605279F,
  154472. 0.9737547762F, 0.9739480212F, 0.9741402656F, 0.9743315120F,
  154473. 0.9745217631F, 0.9747110216F, 0.9748992901F, 0.9750865714F,
  154474. 0.9752728681F, 0.9754581829F, 0.9756425184F, 0.9758258775F,
  154475. 0.9760082627F, 0.9761896768F, 0.9763701224F, 0.9765496024F,
  154476. 0.9767281193F, 0.9769056760F, 0.9770822751F, 0.9772579193F,
  154477. 0.9774326114F, 0.9776063542F, 0.9777791502F, 0.9779510023F,
  154478. 0.9781219133F, 0.9782918858F, 0.9784609226F, 0.9786290264F,
  154479. 0.9787962000F, 0.9789624461F, 0.9791277676F, 0.9792921671F,
  154480. 0.9794556474F, 0.9796182113F, 0.9797798615F, 0.9799406009F,
  154481. 0.9801004321F, 0.9802593580F, 0.9804173813F, 0.9805745049F,
  154482. 0.9807307314F, 0.9808860637F, 0.9810405046F, 0.9811940568F,
  154483. 0.9813467232F, 0.9814985065F, 0.9816494095F, 0.9817994351F,
  154484. 0.9819485860F, 0.9820968650F, 0.9822442750F, 0.9823908186F,
  154485. 0.9825364988F, 0.9826813184F, 0.9828252801F, 0.9829683868F,
  154486. 0.9831106413F, 0.9832520463F, 0.9833926048F, 0.9835323195F,
  154487. 0.9836711932F, 0.9838092288F, 0.9839464291F, 0.9840827969F,
  154488. 0.9842183351F, 0.9843530464F, 0.9844869337F, 0.9846199998F,
  154489. 0.9847522475F, 0.9848836798F, 0.9850142993F, 0.9851441090F,
  154490. 0.9852731117F, 0.9854013101F, 0.9855287073F, 0.9856553058F,
  154491. 0.9857811087F, 0.9859061188F, 0.9860303388F, 0.9861537717F,
  154492. 0.9862764202F, 0.9863982872F, 0.9865193756F, 0.9866396882F,
  154493. 0.9867592277F, 0.9868779972F, 0.9869959993F, 0.9871132370F,
  154494. 0.9872297131F, 0.9873454304F, 0.9874603918F, 0.9875746001F,
  154495. 0.9876880581F, 0.9878007688F, 0.9879127348F, 0.9880239592F,
  154496. 0.9881344447F, 0.9882441941F, 0.9883532104F, 0.9884614962F,
  154497. 0.9885690546F, 0.9886758883F, 0.9887820001F, 0.9888873930F,
  154498. 0.9889920697F, 0.9890960331F, 0.9891992859F, 0.9893018312F,
  154499. 0.9894036716F, 0.9895048100F, 0.9896052493F, 0.9897049923F,
  154500. 0.9898040418F, 0.9899024006F, 0.9900000717F, 0.9900970577F,
  154501. 0.9901933616F, 0.9902889862F, 0.9903839343F, 0.9904782087F,
  154502. 0.9905718122F, 0.9906647477F, 0.9907570180F, 0.9908486259F,
  154503. 0.9909395742F, 0.9910298658F, 0.9911195034F, 0.9912084899F,
  154504. 0.9912968281F, 0.9913845208F, 0.9914715708F, 0.9915579810F,
  154505. 0.9916437540F, 0.9917288928F, 0.9918134001F, 0.9918972788F,
  154506. 0.9919805316F, 0.9920631613F, 0.9921451707F, 0.9922265626F,
  154507. 0.9923073399F, 0.9923875052F, 0.9924670615F, 0.9925460114F,
  154508. 0.9926243577F, 0.9927021033F, 0.9927792508F, 0.9928558032F,
  154509. 0.9929317631F, 0.9930071333F, 0.9930819167F, 0.9931561158F,
  154510. 0.9932297337F, 0.9933027728F, 0.9933752362F, 0.9934471264F,
  154511. 0.9935184462F, 0.9935891985F, 0.9936593859F, 0.9937290112F,
  154512. 0.9937980771F, 0.9938665864F, 0.9939345418F, 0.9940019460F,
  154513. 0.9940688018F, 0.9941351118F, 0.9942008789F, 0.9942661057F,
  154514. 0.9943307950F, 0.9943949494F, 0.9944585717F, 0.9945216645F,
  154515. 0.9945842307F, 0.9946462728F, 0.9947077936F, 0.9947687957F,
  154516. 0.9948292820F, 0.9948892550F, 0.9949487174F, 0.9950076719F,
  154517. 0.9950661212F, 0.9951240679F, 0.9951815148F, 0.9952384645F,
  154518. 0.9952949196F, 0.9953508828F, 0.9954063568F, 0.9954613442F,
  154519. 0.9955158476F, 0.9955698697F, 0.9956234132F, 0.9956764806F,
  154520. 0.9957290746F, 0.9957811978F, 0.9958328528F, 0.9958840423F,
  154521. 0.9959347688F, 0.9959850351F, 0.9960348435F, 0.9960841969F,
  154522. 0.9961330977F, 0.9961815486F, 0.9962295521F, 0.9962771108F,
  154523. 0.9963242274F, 0.9963709043F, 0.9964171441F, 0.9964629494F,
  154524. 0.9965083228F, 0.9965532668F, 0.9965977840F, 0.9966418768F,
  154525. 0.9966855479F, 0.9967287998F, 0.9967716350F, 0.9968140559F,
  154526. 0.9968560653F, 0.9968976655F, 0.9969388591F, 0.9969796485F,
  154527. 0.9970200363F, 0.9970600250F, 0.9970996170F, 0.9971388149F,
  154528. 0.9971776211F, 0.9972160380F, 0.9972540683F, 0.9972917142F,
  154529. 0.9973289783F, 0.9973658631F, 0.9974023709F, 0.9974385042F,
  154530. 0.9974742655F, 0.9975096571F, 0.9975446816F, 0.9975793413F,
  154531. 0.9976136386F, 0.9976475759F, 0.9976811557F, 0.9977143803F,
  154532. 0.9977472521F, 0.9977797736F, 0.9978119470F, 0.9978437748F,
  154533. 0.9978752593F, 0.9979064029F, 0.9979372079F, 0.9979676768F,
  154534. 0.9979978117F, 0.9980276151F, 0.9980570893F, 0.9980862367F,
  154535. 0.9981150595F, 0.9981435600F, 0.9981717406F, 0.9981996035F,
  154536. 0.9982271511F, 0.9982543856F, 0.9982813093F, 0.9983079246F,
  154537. 0.9983342336F, 0.9983602386F, 0.9983859418F, 0.9984113456F,
  154538. 0.9984364522F, 0.9984612638F, 0.9984857825F, 0.9985100108F,
  154539. 0.9985339507F, 0.9985576044F, 0.9985809743F, 0.9986040624F,
  154540. 0.9986268710F, 0.9986494022F, 0.9986716583F, 0.9986936413F,
  154541. 0.9987153535F, 0.9987367969F, 0.9987579738F, 0.9987788864F,
  154542. 0.9987995366F, 0.9988199267F, 0.9988400587F, 0.9988599348F,
  154543. 0.9988795572F, 0.9988989278F, 0.9989180487F, 0.9989369222F,
  154544. 0.9989555501F, 0.9989739347F, 0.9989920780F, 0.9990099820F,
  154545. 0.9990276487F, 0.9990450803F, 0.9990622787F, 0.9990792460F,
  154546. 0.9990959841F, 0.9991124952F, 0.9991287812F, 0.9991448440F,
  154547. 0.9991606858F, 0.9991763084F, 0.9991917139F, 0.9992069042F,
  154548. 0.9992218813F, 0.9992366471F, 0.9992512035F, 0.9992655525F,
  154549. 0.9992796961F, 0.9992936361F, 0.9993073744F, 0.9993209131F,
  154550. 0.9993342538F, 0.9993473987F, 0.9993603494F, 0.9993731080F,
  154551. 0.9993856762F, 0.9993980559F, 0.9994102490F, 0.9994222573F,
  154552. 0.9994340827F, 0.9994457269F, 0.9994571918F, 0.9994684793F,
  154553. 0.9994795910F, 0.9994905288F, 0.9995012945F, 0.9995118898F,
  154554. 0.9995223165F, 0.9995325765F, 0.9995426713F, 0.9995526029F,
  154555. 0.9995623728F, 0.9995719829F, 0.9995814349F, 0.9995907304F,
  154556. 0.9995998712F, 0.9996088590F, 0.9996176954F, 0.9996263821F,
  154557. 0.9996349208F, 0.9996433132F, 0.9996515609F, 0.9996596656F,
  154558. 0.9996676288F, 0.9996754522F, 0.9996831375F, 0.9996906862F,
  154559. 0.9996981000F, 0.9997053804F, 0.9997125290F, 0.9997195474F,
  154560. 0.9997264371F, 0.9997331998F, 0.9997398369F, 0.9997463500F,
  154561. 0.9997527406F, 0.9997590103F, 0.9997651606F, 0.9997711930F,
  154562. 0.9997771089F, 0.9997829098F, 0.9997885973F, 0.9997941728F,
  154563. 0.9997996378F, 0.9998049936F, 0.9998102419F, 0.9998153839F,
  154564. 0.9998204211F, 0.9998253550F, 0.9998301868F, 0.9998349182F,
  154565. 0.9998395503F, 0.9998440847F, 0.9998485226F, 0.9998528654F,
  154566. 0.9998571146F, 0.9998612713F, 0.9998653370F, 0.9998693130F,
  154567. 0.9998732007F, 0.9998770012F, 0.9998807159F, 0.9998843461F,
  154568. 0.9998878931F, 0.9998913581F, 0.9998947424F, 0.9998980473F,
  154569. 0.9999012740F, 0.9999044237F, 0.9999074976F, 0.9999104971F,
  154570. 0.9999134231F, 0.9999162771F, 0.9999190601F, 0.9999217733F,
  154571. 0.9999244179F, 0.9999269950F, 0.9999295058F, 0.9999319515F,
  154572. 0.9999343332F, 0.9999366519F, 0.9999389088F, 0.9999411050F,
  154573. 0.9999432416F, 0.9999453196F, 0.9999473402F, 0.9999493044F,
  154574. 0.9999512132F, 0.9999530677F, 0.9999548690F, 0.9999566180F,
  154575. 0.9999583157F, 0.9999599633F, 0.9999615616F, 0.9999631116F,
  154576. 0.9999646144F, 0.9999660709F, 0.9999674820F, 0.9999688487F,
  154577. 0.9999701719F, 0.9999714526F, 0.9999726917F, 0.9999738900F,
  154578. 0.9999750486F, 0.9999761682F, 0.9999772497F, 0.9999782941F,
  154579. 0.9999793021F, 0.9999802747F, 0.9999812126F, 0.9999821167F,
  154580. 0.9999829878F, 0.9999838268F, 0.9999846343F, 0.9999854113F,
  154581. 0.9999861584F, 0.9999868765F, 0.9999875664F, 0.9999882287F,
  154582. 0.9999888642F, 0.9999894736F, 0.9999900577F, 0.9999906172F,
  154583. 0.9999911528F, 0.9999916651F, 0.9999921548F, 0.9999926227F,
  154584. 0.9999930693F, 0.9999934954F, 0.9999939015F, 0.9999942883F,
  154585. 0.9999946564F, 0.9999950064F, 0.9999953390F, 0.9999956547F,
  154586. 0.9999959541F, 0.9999962377F, 0.9999965062F, 0.9999967601F,
  154587. 0.9999969998F, 0.9999972260F, 0.9999974392F, 0.9999976399F,
  154588. 0.9999978285F, 0.9999980056F, 0.9999981716F, 0.9999983271F,
  154589. 0.9999984724F, 0.9999986081F, 0.9999987345F, 0.9999988521F,
  154590. 0.9999989613F, 0.9999990625F, 0.9999991562F, 0.9999992426F,
  154591. 0.9999993223F, 0.9999993954F, 0.9999994625F, 0.9999995239F,
  154592. 0.9999995798F, 0.9999996307F, 0.9999996768F, 0.9999997184F,
  154593. 0.9999997559F, 0.9999997895F, 0.9999998195F, 0.9999998462F,
  154594. 0.9999998698F, 0.9999998906F, 0.9999999088F, 0.9999999246F,
  154595. 0.9999999383F, 0.9999999500F, 0.9999999600F, 0.9999999684F,
  154596. 0.9999999754F, 0.9999999811F, 0.9999999858F, 0.9999999896F,
  154597. 0.9999999925F, 0.9999999948F, 0.9999999965F, 0.9999999978F,
  154598. 0.9999999986F, 0.9999999992F, 0.9999999996F, 0.9999999998F,
  154599. 0.9999999999F, 1.0000000000F, 1.0000000000F, 1.0000000000F,
  154600. };
  154601. static float vwin8192[4096] = {
  154602. 0.0000000578F, 0.0000005198F, 0.0000014438F, 0.0000028299F,
  154603. 0.0000046780F, 0.0000069882F, 0.0000097604F, 0.0000129945F,
  154604. 0.0000166908F, 0.0000208490F, 0.0000254692F, 0.0000305515F,
  154605. 0.0000360958F, 0.0000421021F, 0.0000485704F, 0.0000555006F,
  154606. 0.0000628929F, 0.0000707472F, 0.0000790635F, 0.0000878417F,
  154607. 0.0000970820F, 0.0001067842F, 0.0001169483F, 0.0001275744F,
  154608. 0.0001386625F, 0.0001502126F, 0.0001622245F, 0.0001746984F,
  154609. 0.0001876343F, 0.0002010320F, 0.0002148917F, 0.0002292132F,
  154610. 0.0002439967F, 0.0002592421F, 0.0002749493F, 0.0002911184F,
  154611. 0.0003077493F, 0.0003248421F, 0.0003423967F, 0.0003604132F,
  154612. 0.0003788915F, 0.0003978316F, 0.0004172335F, 0.0004370971F,
  154613. 0.0004574226F, 0.0004782098F, 0.0004994587F, 0.0005211694F,
  154614. 0.0005433418F, 0.0005659759F, 0.0005890717F, 0.0006126292F,
  154615. 0.0006366484F, 0.0006611292F, 0.0006860716F, 0.0007114757F,
  154616. 0.0007373414F, 0.0007636687F, 0.0007904576F, 0.0008177080F,
  154617. 0.0008454200F, 0.0008735935F, 0.0009022285F, 0.0009313250F,
  154618. 0.0009608830F, 0.0009909025F, 0.0010213834F, 0.0010523257F,
  154619. 0.0010837295F, 0.0011155946F, 0.0011479211F, 0.0011807090F,
  154620. 0.0012139582F, 0.0012476687F, 0.0012818405F, 0.0013164736F,
  154621. 0.0013515679F, 0.0013871235F, 0.0014231402F, 0.0014596182F,
  154622. 0.0014965573F, 0.0015339576F, 0.0015718190F, 0.0016101415F,
  154623. 0.0016489251F, 0.0016881698F, 0.0017278754F, 0.0017680421F,
  154624. 0.0018086698F, 0.0018497584F, 0.0018913080F, 0.0019333185F,
  154625. 0.0019757898F, 0.0020187221F, 0.0020621151F, 0.0021059690F,
  154626. 0.0021502837F, 0.0021950591F, 0.0022402953F, 0.0022859921F,
  154627. 0.0023321497F, 0.0023787679F, 0.0024258467F, 0.0024733861F,
  154628. 0.0025213861F, 0.0025698466F, 0.0026187676F, 0.0026681491F,
  154629. 0.0027179911F, 0.0027682935F, 0.0028190562F, 0.0028702794F,
  154630. 0.0029219628F, 0.0029741066F, 0.0030267107F, 0.0030797749F,
  154631. 0.0031332994F, 0.0031872841F, 0.0032417289F, 0.0032966338F,
  154632. 0.0033519988F, 0.0034078238F, 0.0034641089F, 0.0035208539F,
  154633. 0.0035780589F, 0.0036357237F, 0.0036938485F, 0.0037524331F,
  154634. 0.0038114775F, 0.0038709817F, 0.0039309456F, 0.0039913692F,
  154635. 0.0040522524F, 0.0041135953F, 0.0041753978F, 0.0042376599F,
  154636. 0.0043003814F, 0.0043635624F, 0.0044272029F, 0.0044913028F,
  154637. 0.0045558620F, 0.0046208806F, 0.0046863585F, 0.0047522955F,
  154638. 0.0048186919F, 0.0048855473F, 0.0049528619F, 0.0050206356F,
  154639. 0.0050888684F, 0.0051575601F, 0.0052267108F, 0.0052963204F,
  154640. 0.0053663890F, 0.0054369163F, 0.0055079025F, 0.0055793474F,
  154641. 0.0056512510F, 0.0057236133F, 0.0057964342F, 0.0058697137F,
  154642. 0.0059434517F, 0.0060176482F, 0.0060923032F, 0.0061674166F,
  154643. 0.0062429883F, 0.0063190183F, 0.0063955066F, 0.0064724532F,
  154644. 0.0065498579F, 0.0066277207F, 0.0067060416F, 0.0067848205F,
  154645. 0.0068640575F, 0.0069437523F, 0.0070239051F, 0.0071045157F,
  154646. 0.0071855840F, 0.0072671102F, 0.0073490940F, 0.0074315355F,
  154647. 0.0075144345F, 0.0075977911F, 0.0076816052F, 0.0077658768F,
  154648. 0.0078506057F, 0.0079357920F, 0.0080214355F, 0.0081075363F,
  154649. 0.0081940943F, 0.0082811094F, 0.0083685816F, 0.0084565108F,
  154650. 0.0085448970F, 0.0086337401F, 0.0087230401F, 0.0088127969F,
  154651. 0.0089030104F, 0.0089936807F, 0.0090848076F, 0.0091763911F,
  154652. 0.0092684311F, 0.0093609276F, 0.0094538805F, 0.0095472898F,
  154653. 0.0096411554F, 0.0097354772F, 0.0098302552F, 0.0099254894F,
  154654. 0.0100211796F, 0.0101173259F, 0.0102139281F, 0.0103109863F,
  154655. 0.0104085002F, 0.0105064700F, 0.0106048955F, 0.0107037766F,
  154656. 0.0108031133F, 0.0109029056F, 0.0110031534F, 0.0111038565F,
  154657. 0.0112050151F, 0.0113066289F, 0.0114086980F, 0.0115112222F,
  154658. 0.0116142015F, 0.0117176359F, 0.0118215252F, 0.0119258695F,
  154659. 0.0120306686F, 0.0121359225F, 0.0122416312F, 0.0123477944F,
  154660. 0.0124544123F, 0.0125614847F, 0.0126690116F, 0.0127769928F,
  154661. 0.0128854284F, 0.0129943182F, 0.0131036623F, 0.0132134604F,
  154662. 0.0133237126F, 0.0134344188F, 0.0135455790F, 0.0136571929F,
  154663. 0.0137692607F, 0.0138817821F, 0.0139947572F, 0.0141081859F,
  154664. 0.0142220681F, 0.0143364037F, 0.0144511927F, 0.0145664350F,
  154665. 0.0146821304F, 0.0147982791F, 0.0149148808F, 0.0150319355F,
  154666. 0.0151494431F, 0.0152674036F, 0.0153858168F, 0.0155046828F,
  154667. 0.0156240014F, 0.0157437726F, 0.0158639962F, 0.0159846723F,
  154668. 0.0161058007F, 0.0162273814F, 0.0163494142F, 0.0164718991F,
  154669. 0.0165948361F, 0.0167182250F, 0.0168420658F, 0.0169663584F,
  154670. 0.0170911027F, 0.0172162987F, 0.0173419462F, 0.0174680452F,
  154671. 0.0175945956F, 0.0177215974F, 0.0178490504F, 0.0179769545F,
  154672. 0.0181053098F, 0.0182341160F, 0.0183633732F, 0.0184930812F,
  154673. 0.0186232399F, 0.0187538494F, 0.0188849094F, 0.0190164200F,
  154674. 0.0191483809F, 0.0192807923F, 0.0194136539F, 0.0195469656F,
  154675. 0.0196807275F, 0.0198149394F, 0.0199496012F, 0.0200847128F,
  154676. 0.0202202742F, 0.0203562853F, 0.0204927460F, 0.0206296561F,
  154677. 0.0207670157F, 0.0209048245F, 0.0210430826F, 0.0211817899F,
  154678. 0.0213209462F, 0.0214605515F, 0.0216006057F, 0.0217411086F,
  154679. 0.0218820603F, 0.0220234605F, 0.0221653093F, 0.0223076066F,
  154680. 0.0224503521F, 0.0225935459F, 0.0227371879F, 0.0228812779F,
  154681. 0.0230258160F, 0.0231708018F, 0.0233162355F, 0.0234621169F,
  154682. 0.0236084459F, 0.0237552224F, 0.0239024462F, 0.0240501175F,
  154683. 0.0241982359F, 0.0243468015F, 0.0244958141F, 0.0246452736F,
  154684. 0.0247951800F, 0.0249455331F, 0.0250963329F, 0.0252475792F,
  154685. 0.0253992720F, 0.0255514111F, 0.0257039965F, 0.0258570281F,
  154686. 0.0260105057F, 0.0261644293F, 0.0263187987F, 0.0264736139F,
  154687. 0.0266288747F, 0.0267845811F, 0.0269407330F, 0.0270973302F,
  154688. 0.0272543727F, 0.0274118604F, 0.0275697930F, 0.0277281707F,
  154689. 0.0278869932F, 0.0280462604F, 0.0282059723F, 0.0283661287F,
  154690. 0.0285267295F, 0.0286877747F, 0.0288492641F, 0.0290111976F,
  154691. 0.0291735751F, 0.0293363965F, 0.0294996617F, 0.0296633706F,
  154692. 0.0298275231F, 0.0299921190F, 0.0301571583F, 0.0303226409F,
  154693. 0.0304885667F, 0.0306549354F, 0.0308217472F, 0.0309890017F,
  154694. 0.0311566989F, 0.0313248388F, 0.0314934211F, 0.0316624459F,
  154695. 0.0318319128F, 0.0320018220F, 0.0321721732F, 0.0323429663F,
  154696. 0.0325142013F, 0.0326858779F, 0.0328579962F, 0.0330305559F,
  154697. 0.0332035570F, 0.0333769994F, 0.0335508829F, 0.0337252074F,
  154698. 0.0338999728F, 0.0340751790F, 0.0342508259F, 0.0344269134F,
  154699. 0.0346034412F, 0.0347804094F, 0.0349578178F, 0.0351356663F,
  154700. 0.0353139548F, 0.0354926831F, 0.0356718511F, 0.0358514588F,
  154701. 0.0360315059F, 0.0362119924F, 0.0363929182F, 0.0365742831F,
  154702. 0.0367560870F, 0.0369383297F, 0.0371210113F, 0.0373041315F,
  154703. 0.0374876902F, 0.0376716873F, 0.0378561226F, 0.0380409961F,
  154704. 0.0382263077F, 0.0384120571F, 0.0385982443F, 0.0387848691F,
  154705. 0.0389719315F, 0.0391594313F, 0.0393473683F, 0.0395357425F,
  154706. 0.0397245537F, 0.0399138017F, 0.0401034866F, 0.0402936080F,
  154707. 0.0404841660F, 0.0406751603F, 0.0408665909F, 0.0410584576F,
  154708. 0.0412507603F, 0.0414434988F, 0.0416366731F, 0.0418302829F,
  154709. 0.0420243282F, 0.0422188088F, 0.0424137246F, 0.0426090755F,
  154710. 0.0428048613F, 0.0430010819F, 0.0431977371F, 0.0433948269F,
  154711. 0.0435923511F, 0.0437903095F, 0.0439887020F, 0.0441875285F,
  154712. 0.0443867889F, 0.0445864830F, 0.0447866106F, 0.0449871717F,
  154713. 0.0451881661F, 0.0453895936F, 0.0455914542F, 0.0457937477F,
  154714. 0.0459964738F, 0.0461996326F, 0.0464032239F, 0.0466072475F,
  154715. 0.0468117032F, 0.0470165910F, 0.0472219107F, 0.0474276622F,
  154716. 0.0476338452F, 0.0478404597F, 0.0480475056F, 0.0482549827F,
  154717. 0.0484628907F, 0.0486712297F, 0.0488799994F, 0.0490891998F,
  154718. 0.0492988306F, 0.0495088917F, 0.0497193830F, 0.0499303043F,
  154719. 0.0501416554F, 0.0503534363F, 0.0505656468F, 0.0507782867F,
  154720. 0.0509913559F, 0.0512048542F, 0.0514187815F, 0.0516331376F,
  154721. 0.0518479225F, 0.0520631358F, 0.0522787775F, 0.0524948475F,
  154722. 0.0527113455F, 0.0529282715F, 0.0531456252F, 0.0533634066F,
  154723. 0.0535816154F, 0.0538002515F, 0.0540193148F, 0.0542388051F,
  154724. 0.0544587222F, 0.0546790660F, 0.0548998364F, 0.0551210331F,
  154725. 0.0553426561F, 0.0555647051F, 0.0557871801F, 0.0560100807F,
  154726. 0.0562334070F, 0.0564571587F, 0.0566813357F, 0.0569059378F,
  154727. 0.0571309649F, 0.0573564168F, 0.0575822933F, 0.0578085942F,
  154728. 0.0580353195F, 0.0582624689F, 0.0584900423F, 0.0587180396F,
  154729. 0.0589464605F, 0.0591753049F, 0.0594045726F, 0.0596342635F,
  154730. 0.0598643774F, 0.0600949141F, 0.0603258735F, 0.0605572555F,
  154731. 0.0607890597F, 0.0610212862F, 0.0612539346F, 0.0614870049F,
  154732. 0.0617204968F, 0.0619544103F, 0.0621887451F, 0.0624235010F,
  154733. 0.0626586780F, 0.0628942758F, 0.0631302942F, 0.0633667331F,
  154734. 0.0636035923F, 0.0638408717F, 0.0640785710F, 0.0643166901F,
  154735. 0.0645552288F, 0.0647941870F, 0.0650335645F, 0.0652733610F,
  154736. 0.0655135765F, 0.0657542108F, 0.0659952636F, 0.0662367348F,
  154737. 0.0664786242F, 0.0667209316F, 0.0669636570F, 0.0672068000F,
  154738. 0.0674503605F, 0.0676943384F, 0.0679387334F, 0.0681835454F,
  154739. 0.0684287742F, 0.0686744196F, 0.0689204814F, 0.0691669595F,
  154740. 0.0694138536F, 0.0696611637F, 0.0699088894F, 0.0701570307F,
  154741. 0.0704055873F, 0.0706545590F, 0.0709039458F, 0.0711537473F,
  154742. 0.0714039634F, 0.0716545939F, 0.0719056387F, 0.0721570975F,
  154743. 0.0724089702F, 0.0726612565F, 0.0729139563F, 0.0731670694F,
  154744. 0.0734205956F, 0.0736745347F, 0.0739288866F, 0.0741836510F,
  154745. 0.0744388277F, 0.0746944166F, 0.0749504175F, 0.0752068301F,
  154746. 0.0754636543F, 0.0757208899F, 0.0759785367F, 0.0762365946F,
  154747. 0.0764950632F, 0.0767539424F, 0.0770132320F, 0.0772729319F,
  154748. 0.0775330418F, 0.0777935616F, 0.0780544909F, 0.0783158298F,
  154749. 0.0785775778F, 0.0788397349F, 0.0791023009F, 0.0793652755F,
  154750. 0.0796286585F, 0.0798924498F, 0.0801566492F, 0.0804212564F,
  154751. 0.0806862712F, 0.0809516935F, 0.0812175231F, 0.0814837597F,
  154752. 0.0817504031F, 0.0820174532F, 0.0822849097F, 0.0825527724F,
  154753. 0.0828210412F, 0.0830897158F, 0.0833587960F, 0.0836282816F,
  154754. 0.0838981724F, 0.0841684682F, 0.0844391688F, 0.0847102740F,
  154755. 0.0849817835F, 0.0852536973F, 0.0855260150F, 0.0857987364F,
  154756. 0.0860718614F, 0.0863453897F, 0.0866193211F, 0.0868936554F,
  154757. 0.0871683924F, 0.0874435319F, 0.0877190737F, 0.0879950175F,
  154758. 0.0882713632F, 0.0885481105F, 0.0888252592F, 0.0891028091F,
  154759. 0.0893807600F, 0.0896591117F, 0.0899378639F, 0.0902170165F,
  154760. 0.0904965692F, 0.0907765218F, 0.0910568740F, 0.0913376258F,
  154761. 0.0916187767F, 0.0919003268F, 0.0921822756F, 0.0924646230F,
  154762. 0.0927473687F, 0.0930305126F, 0.0933140545F, 0.0935979940F,
  154763. 0.0938823310F, 0.0941670653F, 0.0944521966F, 0.0947377247F,
  154764. 0.0950236494F, 0.0953099704F, 0.0955966876F, 0.0958838007F,
  154765. 0.0961713094F, 0.0964592136F, 0.0967475131F, 0.0970362075F,
  154766. 0.0973252967F, 0.0976147805F, 0.0979046585F, 0.0981949307F,
  154767. 0.0984855967F, 0.0987766563F, 0.0990681093F, 0.0993599555F,
  154768. 0.0996521945F, 0.0999448263F, 0.1002378506F, 0.1005312671F,
  154769. 0.1008250755F, 0.1011192757F, 0.1014138675F, 0.1017088505F,
  154770. 0.1020042246F, 0.1022999895F, 0.1025961450F, 0.1028926909F,
  154771. 0.1031896268F, 0.1034869526F, 0.1037846680F, 0.1040827729F,
  154772. 0.1043812668F, 0.1046801497F, 0.1049794213F, 0.1052790813F,
  154773. 0.1055791294F, 0.1058795656F, 0.1061803894F, 0.1064816006F,
  154774. 0.1067831991F, 0.1070851846F, 0.1073875568F, 0.1076903155F,
  154775. 0.1079934604F, 0.1082969913F, 0.1086009079F, 0.1089052101F,
  154776. 0.1092098975F, 0.1095149699F, 0.1098204270F, 0.1101262687F,
  154777. 0.1104324946F, 0.1107391045F, 0.1110460982F, 0.1113534754F,
  154778. 0.1116612359F, 0.1119693793F, 0.1122779055F, 0.1125868142F,
  154779. 0.1128961052F, 0.1132057781F, 0.1135158328F, 0.1138262690F,
  154780. 0.1141370863F, 0.1144482847F, 0.1147598638F, 0.1150718233F,
  154781. 0.1153841631F, 0.1156968828F, 0.1160099822F, 0.1163234610F,
  154782. 0.1166373190F, 0.1169515559F, 0.1172661714F, 0.1175811654F,
  154783. 0.1178965374F, 0.1182122874F, 0.1185284149F, 0.1188449198F,
  154784. 0.1191618018F, 0.1194790606F, 0.1197966960F, 0.1201147076F,
  154785. 0.1204330953F, 0.1207518587F, 0.1210709976F, 0.1213905118F,
  154786. 0.1217104009F, 0.1220306647F, 0.1223513029F, 0.1226723153F,
  154787. 0.1229937016F, 0.1233154615F, 0.1236375948F, 0.1239601011F,
  154788. 0.1242829803F, 0.1246062319F, 0.1249298559F, 0.1252538518F,
  154789. 0.1255782195F, 0.1259029586F, 0.1262280689F, 0.1265535501F,
  154790. 0.1268794019F, 0.1272056241F, 0.1275322163F, 0.1278591784F,
  154791. 0.1281865099F, 0.1285142108F, 0.1288422805F, 0.1291707190F,
  154792. 0.1294995259F, 0.1298287009F, 0.1301582437F, 0.1304881542F,
  154793. 0.1308184319F, 0.1311490766F, 0.1314800881F, 0.1318114660F,
  154794. 0.1321432100F, 0.1324753200F, 0.1328077955F, 0.1331406364F,
  154795. 0.1334738422F, 0.1338074129F, 0.1341413479F, 0.1344756472F,
  154796. 0.1348103103F, 0.1351453370F, 0.1354807270F, 0.1358164801F,
  154797. 0.1361525959F, 0.1364890741F, 0.1368259145F, 0.1371631167F,
  154798. 0.1375006805F, 0.1378386056F, 0.1381768917F, 0.1385155384F,
  154799. 0.1388545456F, 0.1391939129F, 0.1395336400F, 0.1398737266F,
  154800. 0.1402141724F, 0.1405549772F, 0.1408961406F, 0.1412376623F,
  154801. 0.1415795421F, 0.1419217797F, 0.1422643746F, 0.1426073268F,
  154802. 0.1429506358F, 0.1432943013F, 0.1436383231F, 0.1439827008F,
  154803. 0.1443274342F, 0.1446725229F, 0.1450179667F, 0.1453637652F,
  154804. 0.1457099181F, 0.1460564252F, 0.1464032861F, 0.1467505006F,
  154805. 0.1470980682F, 0.1474459888F, 0.1477942620F, 0.1481428875F,
  154806. 0.1484918651F, 0.1488411942F, 0.1491908748F, 0.1495409065F,
  154807. 0.1498912889F, 0.1502420218F, 0.1505931048F, 0.1509445376F,
  154808. 0.1512963200F, 0.1516484516F, 0.1520009321F, 0.1523537612F,
  154809. 0.1527069385F, 0.1530604638F, 0.1534143368F, 0.1537685571F,
  154810. 0.1541231244F, 0.1544780384F, 0.1548332987F, 0.1551889052F,
  154811. 0.1555448574F, 0.1559011550F, 0.1562577978F, 0.1566147853F,
  154812. 0.1569721173F, 0.1573297935F, 0.1576878135F, 0.1580461771F,
  154813. 0.1584048838F, 0.1587639334F, 0.1591233255F, 0.1594830599F,
  154814. 0.1598431361F, 0.1602035540F, 0.1605643131F, 0.1609254131F,
  154815. 0.1612868537F, 0.1616486346F, 0.1620107555F, 0.1623732160F,
  154816. 0.1627360158F, 0.1630991545F, 0.1634626319F, 0.1638264476F,
  154817. 0.1641906013F, 0.1645550926F, 0.1649199212F, 0.1652850869F,
  154818. 0.1656505892F, 0.1660164278F, 0.1663826024F, 0.1667491127F,
  154819. 0.1671159583F, 0.1674831388F, 0.1678506541F, 0.1682185036F,
  154820. 0.1685866872F, 0.1689552044F, 0.1693240549F, 0.1696932384F,
  154821. 0.1700627545F, 0.1704326029F, 0.1708027833F, 0.1711732952F,
  154822. 0.1715441385F, 0.1719153127F, 0.1722868175F, 0.1726586526F,
  154823. 0.1730308176F, 0.1734033121F, 0.1737761359F, 0.1741492886F,
  154824. 0.1745227698F, 0.1748965792F, 0.1752707164F, 0.1756451812F,
  154825. 0.1760199731F, 0.1763950918F, 0.1767705370F, 0.1771463083F,
  154826. 0.1775224054F, 0.1778988279F, 0.1782755754F, 0.1786526477F,
  154827. 0.1790300444F, 0.1794077651F, 0.1797858094F, 0.1801641771F,
  154828. 0.1805428677F, 0.1809218810F, 0.1813012165F, 0.1816808739F,
  154829. 0.1820608528F, 0.1824411530F, 0.1828217739F, 0.1832027154F,
  154830. 0.1835839770F, 0.1839655584F, 0.1843474592F, 0.1847296790F,
  154831. 0.1851122175F, 0.1854950744F, 0.1858782492F, 0.1862617417F,
  154832. 0.1866455514F, 0.1870296780F, 0.1874141211F, 0.1877988804F,
  154833. 0.1881839555F, 0.1885693461F, 0.1889550517F, 0.1893410721F,
  154834. 0.1897274068F, 0.1901140555F, 0.1905010178F, 0.1908882933F,
  154835. 0.1912758818F, 0.1916637828F, 0.1920519959F, 0.1924405208F,
  154836. 0.1928293571F, 0.1932185044F, 0.1936079625F, 0.1939977308F,
  154837. 0.1943878091F, 0.1947781969F, 0.1951688939F, 0.1955598998F,
  154838. 0.1959512141F, 0.1963428364F, 0.1967347665F, 0.1971270038F,
  154839. 0.1975195482F, 0.1979123990F, 0.1983055561F, 0.1986990190F,
  154840. 0.1990927873F, 0.1994868607F, 0.1998812388F, 0.2002759212F,
  154841. 0.2006709075F, 0.2010661974F, 0.2014617904F, 0.2018576862F,
  154842. 0.2022538844F, 0.2026503847F, 0.2030471865F, 0.2034442897F,
  154843. 0.2038416937F, 0.2042393982F, 0.2046374028F, 0.2050357071F,
  154844. 0.2054343107F, 0.2058332133F, 0.2062324145F, 0.2066319138F,
  154845. 0.2070317110F, 0.2074318055F, 0.2078321970F, 0.2082328852F,
  154846. 0.2086338696F, 0.2090351498F, 0.2094367255F, 0.2098385962F,
  154847. 0.2102407617F, 0.2106432213F, 0.2110459749F, 0.2114490220F,
  154848. 0.2118523621F, 0.2122559950F, 0.2126599202F, 0.2130641373F,
  154849. 0.2134686459F, 0.2138734456F, 0.2142785361F, 0.2146839168F,
  154850. 0.2150895875F, 0.2154955478F, 0.2159017972F, 0.2163083353F,
  154851. 0.2167151617F, 0.2171222761F, 0.2175296780F, 0.2179373670F,
  154852. 0.2183453428F, 0.2187536049F, 0.2191621529F, 0.2195709864F,
  154853. 0.2199801051F, 0.2203895085F, 0.2207991961F, 0.2212091677F,
  154854. 0.2216194228F, 0.2220299610F, 0.2224407818F, 0.2228518850F,
  154855. 0.2232632699F, 0.2236749364F, 0.2240868839F, 0.2244991121F,
  154856. 0.2249116204F, 0.2253244086F, 0.2257374763F, 0.2261508229F,
  154857. 0.2265644481F, 0.2269783514F, 0.2273925326F, 0.2278069911F,
  154858. 0.2282217265F, 0.2286367384F, 0.2290520265F, 0.2294675902F,
  154859. 0.2298834292F, 0.2302995431F, 0.2307159314F, 0.2311325937F,
  154860. 0.2315495297F, 0.2319667388F, 0.2323842207F, 0.2328019749F,
  154861. 0.2332200011F, 0.2336382988F, 0.2340568675F, 0.2344757070F,
  154862. 0.2348948166F, 0.2353141961F, 0.2357338450F, 0.2361537629F,
  154863. 0.2365739493F, 0.2369944038F, 0.2374151261F, 0.2378361156F,
  154864. 0.2382573720F, 0.2386788948F, 0.2391006836F, 0.2395227380F,
  154865. 0.2399450575F, 0.2403676417F, 0.2407904902F, 0.2412136026F,
  154866. 0.2416369783F, 0.2420606171F, 0.2424845185F, 0.2429086820F,
  154867. 0.2433331072F, 0.2437577936F, 0.2441827409F, 0.2446079486F,
  154868. 0.2450334163F, 0.2454591435F, 0.2458851298F, 0.2463113747F,
  154869. 0.2467378779F, 0.2471646389F, 0.2475916573F, 0.2480189325F,
  154870. 0.2484464643F, 0.2488742521F, 0.2493022955F, 0.2497305940F,
  154871. 0.2501591473F, 0.2505879549F, 0.2510170163F, 0.2514463311F,
  154872. 0.2518758989F, 0.2523057193F, 0.2527357916F, 0.2531661157F,
  154873. 0.2535966909F, 0.2540275169F, 0.2544585931F, 0.2548899193F,
  154874. 0.2553214948F, 0.2557533193F, 0.2561853924F, 0.2566177135F,
  154875. 0.2570502822F, 0.2574830981F, 0.2579161608F, 0.2583494697F,
  154876. 0.2587830245F, 0.2592168246F, 0.2596508697F, 0.2600851593F,
  154877. 0.2605196929F, 0.2609544701F, 0.2613894904F, 0.2618247534F,
  154878. 0.2622602586F, 0.2626960055F, 0.2631319938F, 0.2635682230F,
  154879. 0.2640046925F, 0.2644414021F, 0.2648783511F, 0.2653155391F,
  154880. 0.2657529657F, 0.2661906305F, 0.2666285329F, 0.2670666725F,
  154881. 0.2675050489F, 0.2679436616F, 0.2683825101F, 0.2688215940F,
  154882. 0.2692609127F, 0.2697004660F, 0.2701402532F, 0.2705802739F,
  154883. 0.2710205278F, 0.2714610142F, 0.2719017327F, 0.2723426830F,
  154884. 0.2727838644F, 0.2732252766F, 0.2736669191F, 0.2741087914F,
  154885. 0.2745508930F, 0.2749932235F, 0.2754357824F, 0.2758785693F,
  154886. 0.2763215837F, 0.2767648251F, 0.2772082930F, 0.2776519870F,
  154887. 0.2780959066F, 0.2785400513F, 0.2789844207F, 0.2794290143F,
  154888. 0.2798738316F, 0.2803188722F, 0.2807641355F, 0.2812096211F,
  154889. 0.2816553286F, 0.2821012574F, 0.2825474071F, 0.2829937773F,
  154890. 0.2834403673F, 0.2838871768F, 0.2843342053F, 0.2847814523F,
  154891. 0.2852289174F, 0.2856765999F, 0.2861244996F, 0.2865726159F,
  154892. 0.2870209482F, 0.2874694962F, 0.2879182594F, 0.2883672372F,
  154893. 0.2888164293F, 0.2892658350F, 0.2897154540F, 0.2901652858F,
  154894. 0.2906153298F, 0.2910655856F, 0.2915160527F, 0.2919667306F,
  154895. 0.2924176189F, 0.2928687171F, 0.2933200246F, 0.2937715409F,
  154896. 0.2942232657F, 0.2946751984F, 0.2951273386F, 0.2955796856F,
  154897. 0.2960322391F, 0.2964849986F, 0.2969379636F, 0.2973911335F,
  154898. 0.2978445080F, 0.2982980864F, 0.2987518684F, 0.2992058534F,
  154899. 0.2996600409F, 0.3001144305F, 0.3005690217F, 0.3010238139F,
  154900. 0.3014788067F, 0.3019339995F, 0.3023893920F, 0.3028449835F,
  154901. 0.3033007736F, 0.3037567618F, 0.3042129477F, 0.3046693306F,
  154902. 0.3051259102F, 0.3055826859F, 0.3060396572F, 0.3064968236F,
  154903. 0.3069541847F, 0.3074117399F, 0.3078694887F, 0.3083274307F,
  154904. 0.3087855653F, 0.3092438920F, 0.3097024104F, 0.3101611199F,
  154905. 0.3106200200F, 0.3110791103F, 0.3115383902F, 0.3119978592F,
  154906. 0.3124575169F, 0.3129173627F, 0.3133773961F, 0.3138376166F,
  154907. 0.3142980238F, 0.3147586170F, 0.3152193959F, 0.3156803598F,
  154908. 0.3161415084F, 0.3166028410F, 0.3170643573F, 0.3175260566F,
  154909. 0.3179879384F, 0.3184500023F, 0.3189122478F, 0.3193746743F,
  154910. 0.3198372814F, 0.3203000685F, 0.3207630351F, 0.3212261807F,
  154911. 0.3216895048F, 0.3221530069F, 0.3226166865F, 0.3230805430F,
  154912. 0.3235445760F, 0.3240087849F, 0.3244731693F, 0.3249377285F,
  154913. 0.3254024622F, 0.3258673698F, 0.3263324507F, 0.3267977045F,
  154914. 0.3272631306F, 0.3277287286F, 0.3281944978F, 0.3286604379F,
  154915. 0.3291265482F, 0.3295928284F, 0.3300592777F, 0.3305258958F,
  154916. 0.3309926821F, 0.3314596361F, 0.3319267573F, 0.3323940451F,
  154917. 0.3328614990F, 0.3333291186F, 0.3337969033F, 0.3342648525F,
  154918. 0.3347329658F, 0.3352012427F, 0.3356696825F, 0.3361382849F,
  154919. 0.3366070492F, 0.3370759749F, 0.3375450616F, 0.3380143087F,
  154920. 0.3384837156F, 0.3389532819F, 0.3394230071F, 0.3398928905F,
  154921. 0.3403629317F, 0.3408331302F, 0.3413034854F, 0.3417739967F,
  154922. 0.3422446638F, 0.3427154860F, 0.3431864628F, 0.3436575938F,
  154923. 0.3441288782F, 0.3446003158F, 0.3450719058F, 0.3455436478F,
  154924. 0.3460155412F, 0.3464875856F, 0.3469597804F, 0.3474321250F,
  154925. 0.3479046189F, 0.3483772617F, 0.3488500527F, 0.3493229914F,
  154926. 0.3497960774F, 0.3502693100F, 0.3507426887F, 0.3512162131F,
  154927. 0.3516898825F, 0.3521636965F, 0.3526376545F, 0.3531117559F,
  154928. 0.3535860003F, 0.3540603870F, 0.3545349157F, 0.3550095856F,
  154929. 0.3554843964F, 0.3559593474F, 0.3564344381F, 0.3569096680F,
  154930. 0.3573850366F, 0.3578605432F, 0.3583361875F, 0.3588119687F,
  154931. 0.3592878865F, 0.3597639402F, 0.3602401293F, 0.3607164533F,
  154932. 0.3611929117F, 0.3616695038F, 0.3621462292F, 0.3626230873F,
  154933. 0.3631000776F, 0.3635771995F, 0.3640544525F, 0.3645318360F,
  154934. 0.3650093496F, 0.3654869926F, 0.3659647645F, 0.3664426648F,
  154935. 0.3669206930F, 0.3673988484F, 0.3678771306F, 0.3683555390F,
  154936. 0.3688340731F, 0.3693127322F, 0.3697915160F, 0.3702704237F,
  154937. 0.3707494549F, 0.3712286091F, 0.3717078857F, 0.3721872840F,
  154938. 0.3726668037F, 0.3731464441F, 0.3736262047F, 0.3741060850F,
  154939. 0.3745860843F, 0.3750662023F, 0.3755464382F, 0.3760267915F,
  154940. 0.3765072618F, 0.3769878484F, 0.3774685509F, 0.3779493686F,
  154941. 0.3784303010F, 0.3789113475F, 0.3793925076F, 0.3798737809F,
  154942. 0.3803551666F, 0.3808366642F, 0.3813182733F, 0.3817999932F,
  154943. 0.3822818234F, 0.3827637633F, 0.3832458124F, 0.3837279702F,
  154944. 0.3842102360F, 0.3846926093F, 0.3851750897F, 0.3856576764F,
  154945. 0.3861403690F, 0.3866231670F, 0.3871060696F, 0.3875890765F,
  154946. 0.3880721870F, 0.3885554007F, 0.3890387168F, 0.3895221349F,
  154947. 0.3900056544F, 0.3904892748F, 0.3909729955F, 0.3914568160F,
  154948. 0.3919407356F, 0.3924247539F, 0.3929088702F, 0.3933930841F,
  154949. 0.3938773949F, 0.3943618021F, 0.3948463052F, 0.3953309035F,
  154950. 0.3958155966F, 0.3963003838F, 0.3967852646F, 0.3972702385F,
  154951. 0.3977553048F, 0.3982404631F, 0.3987257127F, 0.3992110531F,
  154952. 0.3996964838F, 0.4001820041F, 0.4006676136F, 0.4011533116F,
  154953. 0.4016390976F, 0.4021249710F, 0.4026109313F, 0.4030969779F,
  154954. 0.4035831102F, 0.4040693277F, 0.4045556299F, 0.4050420160F,
  154955. 0.4055284857F, 0.4060150383F, 0.4065016732F, 0.4069883899F,
  154956. 0.4074751879F, 0.4079620665F, 0.4084490252F, 0.4089360635F,
  154957. 0.4094231807F, 0.4099103763F, 0.4103976498F, 0.4108850005F,
  154958. 0.4113724280F, 0.4118599315F, 0.4123475107F, 0.4128351648F,
  154959. 0.4133228934F, 0.4138106959F, 0.4142985716F, 0.4147865201F,
  154960. 0.4152745408F, 0.4157626330F, 0.4162507963F, 0.4167390301F,
  154961. 0.4172273337F, 0.4177157067F, 0.4182041484F, 0.4186926583F,
  154962. 0.4191812359F, 0.4196698805F, 0.4201585915F, 0.4206473685F,
  154963. 0.4211362108F, 0.4216251179F, 0.4221140892F, 0.4226031241F,
  154964. 0.4230922221F, 0.4235813826F, 0.4240706050F, 0.4245598887F,
  154965. 0.4250492332F, 0.4255386379F, 0.4260281022F, 0.4265176256F,
  154966. 0.4270072075F, 0.4274968473F, 0.4279865445F, 0.4284762984F,
  154967. 0.4289661086F, 0.4294559743F, 0.4299458951F, 0.4304358704F,
  154968. 0.4309258996F, 0.4314159822F, 0.4319061175F, 0.4323963050F,
  154969. 0.4328865441F, 0.4333768342F, 0.4338671749F, 0.4343575654F,
  154970. 0.4348480052F, 0.4353384938F, 0.4358290306F, 0.4363196149F,
  154971. 0.4368102463F, 0.4373009241F, 0.4377916478F, 0.4382824168F,
  154972. 0.4387732305F, 0.4392640884F, 0.4397549899F, 0.4402459343F,
  154973. 0.4407369212F, 0.4412279499F, 0.4417190198F, 0.4422101305F,
  154974. 0.4427012813F, 0.4431924717F, 0.4436837010F, 0.4441749686F,
  154975. 0.4446662742F, 0.4451576169F, 0.4456489963F, 0.4461404118F,
  154976. 0.4466318628F, 0.4471233487F, 0.4476148690F, 0.4481064230F,
  154977. 0.4485980103F, 0.4490896302F, 0.4495812821F, 0.4500729654F,
  154978. 0.4505646797F, 0.4510564243F, 0.4515481986F, 0.4520400021F,
  154979. 0.4525318341F, 0.4530236942F, 0.4535155816F, 0.4540074959F,
  154980. 0.4544994365F, 0.4549914028F, 0.4554833941F, 0.4559754100F,
  154981. 0.4564674499F, 0.4569595131F, 0.4574515991F, 0.4579437074F,
  154982. 0.4584358372F, 0.4589279881F, 0.4594201595F, 0.4599123508F,
  154983. 0.4604045615F, 0.4608967908F, 0.4613890383F, 0.4618813034F,
  154984. 0.4623735855F, 0.4628658841F, 0.4633581984F, 0.4638505281F,
  154985. 0.4643428724F, 0.4648352308F, 0.4653276028F, 0.4658199877F,
  154986. 0.4663123849F, 0.4668047940F, 0.4672972143F, 0.4677896451F,
  154987. 0.4682820861F, 0.4687745365F, 0.4692669958F, 0.4697594634F,
  154988. 0.4702519387F, 0.4707444211F, 0.4712369102F, 0.4717294052F,
  154989. 0.4722219056F, 0.4727144109F, 0.4732069204F, 0.4736994336F,
  154990. 0.4741919498F, 0.4746844686F, 0.4751769893F, 0.4756695113F,
  154991. 0.4761620341F, 0.4766545571F, 0.4771470797F, 0.4776396013F,
  154992. 0.4781321213F, 0.4786246392F, 0.4791171544F, 0.4796096663F,
  154993. 0.4801021744F, 0.4805946779F, 0.4810871765F, 0.4815796694F,
  154994. 0.4820721561F, 0.4825646360F, 0.4830571086F, 0.4835495732F,
  154995. 0.4840420293F, 0.4845344763F, 0.4850269136F, 0.4855193407F,
  154996. 0.4860117569F, 0.4865041617F, 0.4869965545F, 0.4874889347F,
  154997. 0.4879813018F, 0.4884736551F, 0.4889659941F, 0.4894583182F,
  154998. 0.4899506268F, 0.4904429193F, 0.4909351952F, 0.4914274538F,
  154999. 0.4919196947F, 0.4924119172F, 0.4929041207F, 0.4933963046F,
  155000. 0.4938884685F, 0.4943806116F, 0.4948727335F, 0.4953648335F,
  155001. 0.4958569110F, 0.4963489656F, 0.4968409965F, 0.4973330032F,
  155002. 0.4978249852F, 0.4983169419F, 0.4988088726F, 0.4993007768F,
  155003. 0.4997926539F, 0.5002845034F, 0.5007763247F, 0.5012681171F,
  155004. 0.5017598801F, 0.5022516132F, 0.5027433157F, 0.5032349871F,
  155005. 0.5037266268F, 0.5042182341F, 0.5047098086F, 0.5052013497F,
  155006. 0.5056928567F, 0.5061843292F, 0.5066757664F, 0.5071671679F,
  155007. 0.5076585330F, 0.5081498613F, 0.5086411520F, 0.5091324047F,
  155008. 0.5096236187F, 0.5101147934F, 0.5106059284F, 0.5110970230F,
  155009. 0.5115880766F, 0.5120790887F, 0.5125700587F, 0.5130609860F,
  155010. 0.5135518700F, 0.5140427102F, 0.5145335059F, 0.5150242566F,
  155011. 0.5155149618F, 0.5160056208F, 0.5164962331F, 0.5169867980F,
  155012. 0.5174773151F, 0.5179677837F, 0.5184582033F, 0.5189485733F,
  155013. 0.5194388931F, 0.5199291621F, 0.5204193798F, 0.5209095455F,
  155014. 0.5213996588F, 0.5218897190F, 0.5223797256F, 0.5228696779F,
  155015. 0.5233595755F, 0.5238494177F, 0.5243392039F, 0.5248289337F,
  155016. 0.5253186063F, 0.5258082213F, 0.5262977781F, 0.5267872760F,
  155017. 0.5272767146F, 0.5277660932F, 0.5282554112F, 0.5287446682F,
  155018. 0.5292338635F, 0.5297229965F, 0.5302120667F, 0.5307010736F,
  155019. 0.5311900164F, 0.5316788947F, 0.5321677079F, 0.5326564554F,
  155020. 0.5331451366F, 0.5336337511F, 0.5341222981F, 0.5346107771F,
  155021. 0.5350991876F, 0.5355875290F, 0.5360758007F, 0.5365640021F,
  155022. 0.5370521327F, 0.5375401920F, 0.5380281792F, 0.5385160939F,
  155023. 0.5390039355F, 0.5394917034F, 0.5399793971F, 0.5404670159F,
  155024. 0.5409545594F, 0.5414420269F, 0.5419294179F, 0.5424167318F,
  155025. 0.5429039680F, 0.5433911261F, 0.5438782053F, 0.5443652051F,
  155026. 0.5448521250F, 0.5453389644F, 0.5458257228F, 0.5463123995F,
  155027. 0.5467989940F, 0.5472855057F, 0.5477719341F, 0.5482582786F,
  155028. 0.5487445387F, 0.5492307137F, 0.5497168031F, 0.5502028063F,
  155029. 0.5506887228F, 0.5511745520F, 0.5516602934F, 0.5521459463F,
  155030. 0.5526315103F, 0.5531169847F, 0.5536023690F, 0.5540876626F,
  155031. 0.5545728649F, 0.5550579755F, 0.5555429937F, 0.5560279189F,
  155032. 0.5565127507F, 0.5569974884F, 0.5574821315F, 0.5579666794F,
  155033. 0.5584511316F, 0.5589354875F, 0.5594197465F, 0.5599039080F,
  155034. 0.5603879716F, 0.5608719367F, 0.5613558026F, 0.5618395689F,
  155035. 0.5623232350F, 0.5628068002F, 0.5632902642F, 0.5637736262F,
  155036. 0.5642568858F, 0.5647400423F, 0.5652230953F, 0.5657060442F,
  155037. 0.5661888883F, 0.5666716272F, 0.5671542603F, 0.5676367870F,
  155038. 0.5681192069F, 0.5686015192F, 0.5690837235F, 0.5695658192F,
  155039. 0.5700478058F, 0.5705296827F, 0.5710114494F, 0.5714931052F,
  155040. 0.5719746497F, 0.5724560822F, 0.5729374023F, 0.5734186094F,
  155041. 0.5738997029F, 0.5743806823F, 0.5748615470F, 0.5753422965F,
  155042. 0.5758229301F, 0.5763034475F, 0.5767838480F, 0.5772641310F,
  155043. 0.5777442960F, 0.5782243426F, 0.5787042700F, 0.5791840778F,
  155044. 0.5796637654F, 0.5801433322F, 0.5806227778F, 0.5811021016F,
  155045. 0.5815813029F, 0.5820603814F, 0.5825393363F, 0.5830181673F,
  155046. 0.5834968737F, 0.5839754549F, 0.5844539105F, 0.5849322399F,
  155047. 0.5854104425F, 0.5858885179F, 0.5863664653F, 0.5868442844F,
  155048. 0.5873219746F, 0.5877995353F, 0.5882769660F, 0.5887542661F,
  155049. 0.5892314351F, 0.5897084724F, 0.5901853776F, 0.5906621500F,
  155050. 0.5911387892F, 0.5916152945F, 0.5920916655F, 0.5925679016F,
  155051. 0.5930440022F, 0.5935199669F, 0.5939957950F, 0.5944714861F,
  155052. 0.5949470396F, 0.5954224550F, 0.5958977317F, 0.5963728692F,
  155053. 0.5968478669F, 0.5973227244F, 0.5977974411F, 0.5982720163F,
  155054. 0.5987464497F, 0.5992207407F, 0.5996948887F, 0.6001688932F,
  155055. 0.6006427537F, 0.6011164696F, 0.6015900405F, 0.6020634657F,
  155056. 0.6025367447F, 0.6030098770F, 0.6034828621F, 0.6039556995F,
  155057. 0.6044283885F, 0.6049009288F, 0.6053733196F, 0.6058455606F,
  155058. 0.6063176512F, 0.6067895909F, 0.6072613790F, 0.6077330152F,
  155059. 0.6082044989F, 0.6086758295F, 0.6091470065F, 0.6096180294F,
  155060. 0.6100888977F, 0.6105596108F, 0.6110301682F, 0.6115005694F,
  155061. 0.6119708139F, 0.6124409011F, 0.6129108305F, 0.6133806017F,
  155062. 0.6138502139F, 0.6143196669F, 0.6147889599F, 0.6152580926F,
  155063. 0.6157270643F, 0.6161958746F, 0.6166645230F, 0.6171330088F,
  155064. 0.6176013317F, 0.6180694910F, 0.6185374863F, 0.6190053171F,
  155065. 0.6194729827F, 0.6199404828F, 0.6204078167F, 0.6208749841F,
  155066. 0.6213419842F, 0.6218088168F, 0.6222754811F, 0.6227419768F,
  155067. 0.6232083032F, 0.6236744600F, 0.6241404465F, 0.6246062622F,
  155068. 0.6250719067F, 0.6255373795F, 0.6260026799F, 0.6264678076F,
  155069. 0.6269327619F, 0.6273975425F, 0.6278621487F, 0.6283265800F,
  155070. 0.6287908361F, 0.6292549163F, 0.6297188201F, 0.6301825471F,
  155071. 0.6306460966F, 0.6311094683F, 0.6315726617F, 0.6320356761F,
  155072. 0.6324985111F, 0.6329611662F, 0.6334236410F, 0.6338859348F,
  155073. 0.6343480472F, 0.6348099777F, 0.6352717257F, 0.6357332909F,
  155074. 0.6361946726F, 0.6366558704F, 0.6371168837F, 0.6375777122F,
  155075. 0.6380383552F, 0.6384988123F, 0.6389590830F, 0.6394191668F,
  155076. 0.6398790631F, 0.6403387716F, 0.6407982916F, 0.6412576228F,
  155077. 0.6417167645F, 0.6421757163F, 0.6426344778F, 0.6430930483F,
  155078. 0.6435514275F, 0.6440096149F, 0.6444676098F, 0.6449254119F,
  155079. 0.6453830207F, 0.6458404356F, 0.6462976562F, 0.6467546820F,
  155080. 0.6472115125F, 0.6476681472F, 0.6481245856F, 0.6485808273F,
  155081. 0.6490368717F, 0.6494927183F, 0.6499483667F, 0.6504038164F,
  155082. 0.6508590670F, 0.6513141178F, 0.6517689684F, 0.6522236185F,
  155083. 0.6526780673F, 0.6531323146F, 0.6535863598F, 0.6540402024F,
  155084. 0.6544938419F, 0.6549472779F, 0.6554005099F, 0.6558535373F,
  155085. 0.6563063598F, 0.6567589769F, 0.6572113880F, 0.6576635927F,
  155086. 0.6581155906F, 0.6585673810F, 0.6590189637F, 0.6594703380F,
  155087. 0.6599215035F, 0.6603724598F, 0.6608232064F, 0.6612737427F,
  155088. 0.6617240684F, 0.6621741829F, 0.6626240859F, 0.6630737767F,
  155089. 0.6635232550F, 0.6639725202F, 0.6644215720F, 0.6648704098F,
  155090. 0.6653190332F, 0.6657674417F, 0.6662156348F, 0.6666636121F,
  155091. 0.6671113731F, 0.6675589174F, 0.6680062445F, 0.6684533538F,
  155092. 0.6689002450F, 0.6693469177F, 0.6697933712F, 0.6702396052F,
  155093. 0.6706856193F, 0.6711314129F, 0.6715769855F, 0.6720223369F,
  155094. 0.6724674664F, 0.6729123736F, 0.6733570581F, 0.6738015194F,
  155095. 0.6742457570F, 0.6746897706F, 0.6751335596F, 0.6755771236F,
  155096. 0.6760204621F, 0.6764635747F, 0.6769064609F, 0.6773491204F,
  155097. 0.6777915525F, 0.6782337570F, 0.6786757332F, 0.6791174809F,
  155098. 0.6795589995F, 0.6800002886F, 0.6804413477F, 0.6808821765F,
  155099. 0.6813227743F, 0.6817631409F, 0.6822032758F, 0.6826431785F,
  155100. 0.6830828485F, 0.6835222855F, 0.6839614890F, 0.6844004585F,
  155101. 0.6848391936F, 0.6852776939F, 0.6857159589F, 0.6861539883F,
  155102. 0.6865917815F, 0.6870293381F, 0.6874666576F, 0.6879037398F,
  155103. 0.6883405840F, 0.6887771899F, 0.6892135571F, 0.6896496850F,
  155104. 0.6900855733F, 0.6905212216F, 0.6909566294F, 0.6913917963F,
  155105. 0.6918267218F, 0.6922614055F, 0.6926958471F, 0.6931300459F,
  155106. 0.6935640018F, 0.6939977141F, 0.6944311825F, 0.6948644066F,
  155107. 0.6952973859F, 0.6957301200F, 0.6961626085F, 0.6965948510F,
  155108. 0.6970268470F, 0.6974585961F, 0.6978900980F, 0.6983213521F,
  155109. 0.6987523580F, 0.6991831154F, 0.6996136238F, 0.7000438828F,
  155110. 0.7004738921F, 0.7009036510F, 0.7013331594F, 0.7017624166F,
  155111. 0.7021914224F, 0.7026201763F, 0.7030486779F, 0.7034769268F,
  155112. 0.7039049226F, 0.7043326648F, 0.7047601531F, 0.7051873870F,
  155113. 0.7056143662F, 0.7060410902F, 0.7064675586F, 0.7068937711F,
  155114. 0.7073197271F, 0.7077454264F, 0.7081708684F, 0.7085960529F,
  155115. 0.7090209793F, 0.7094456474F, 0.7098700566F, 0.7102942066F,
  155116. 0.7107180970F, 0.7111417274F, 0.7115650974F, 0.7119882066F,
  155117. 0.7124110545F, 0.7128336409F, 0.7132559653F, 0.7136780272F,
  155118. 0.7140998264F, 0.7145213624F, 0.7149426348F, 0.7153636433F,
  155119. 0.7157843874F, 0.7162048668F, 0.7166250810F, 0.7170450296F,
  155120. 0.7174647124F, 0.7178841289F, 0.7183032786F, 0.7187221613F,
  155121. 0.7191407765F, 0.7195591239F, 0.7199772030F, 0.7203950135F,
  155122. 0.7208125550F, 0.7212298271F, 0.7216468294F, 0.7220635616F,
  155123. 0.7224800233F, 0.7228962140F, 0.7233121335F, 0.7237277813F,
  155124. 0.7241431571F, 0.7245582604F, 0.7249730910F, 0.7253876484F,
  155125. 0.7258019322F, 0.7262159422F, 0.7266296778F, 0.7270431388F,
  155126. 0.7274563247F, 0.7278692353F, 0.7282818700F, 0.7286942287F,
  155127. 0.7291063108F, 0.7295181160F, 0.7299296440F, 0.7303408944F,
  155128. 0.7307518669F, 0.7311625609F, 0.7315729763F, 0.7319831126F,
  155129. 0.7323929695F, 0.7328025466F, 0.7332118435F, 0.7336208600F,
  155130. 0.7340295955F, 0.7344380499F, 0.7348462226F, 0.7352541134F,
  155131. 0.7356617220F, 0.7360690478F, 0.7364760907F, 0.7368828502F,
  155132. 0.7372893259F, 0.7376955176F, 0.7381014249F, 0.7385070475F,
  155133. 0.7389123849F, 0.7393174368F, 0.7397222029F, 0.7401266829F,
  155134. 0.7405308763F, 0.7409347829F, 0.7413384023F, 0.7417417341F,
  155135. 0.7421447780F, 0.7425475338F, 0.7429500009F, 0.7433521791F,
  155136. 0.7437540681F, 0.7441556674F, 0.7445569769F, 0.7449579960F,
  155137. 0.7453587245F, 0.7457591621F, 0.7461593084F, 0.7465591631F,
  155138. 0.7469587259F, 0.7473579963F, 0.7477569741F, 0.7481556590F,
  155139. 0.7485540506F, 0.7489521486F, 0.7493499526F, 0.7497474623F,
  155140. 0.7501446775F, 0.7505415977F, 0.7509382227F, 0.7513345521F,
  155141. 0.7517305856F, 0.7521263229F, 0.7525217636F, 0.7529169074F,
  155142. 0.7533117541F, 0.7537063032F, 0.7541005545F, 0.7544945076F,
  155143. 0.7548881623F, 0.7552815182F, 0.7556745749F, 0.7560673323F,
  155144. 0.7564597899F, 0.7568519474F, 0.7572438046F, 0.7576353611F,
  155145. 0.7580266166F, 0.7584175708F, 0.7588082235F, 0.7591985741F,
  155146. 0.7595886226F, 0.7599783685F, 0.7603678116F, 0.7607569515F,
  155147. 0.7611457879F, 0.7615343206F, 0.7619225493F, 0.7623104735F,
  155148. 0.7626980931F, 0.7630854078F, 0.7634724171F, 0.7638591209F,
  155149. 0.7642455188F, 0.7646316106F, 0.7650173959F, 0.7654028744F,
  155150. 0.7657880459F, 0.7661729100F, 0.7665574664F, 0.7669417150F,
  155151. 0.7673256553F, 0.7677092871F, 0.7680926100F, 0.7684756239F,
  155152. 0.7688583284F, 0.7692407232F, 0.7696228080F, 0.7700045826F,
  155153. 0.7703860467F, 0.7707671999F, 0.7711480420F, 0.7715285728F,
  155154. 0.7719087918F, 0.7722886989F, 0.7726682938F, 0.7730475762F,
  155155. 0.7734265458F, 0.7738052023F, 0.7741835454F, 0.7745615750F,
  155156. 0.7749392906F, 0.7753166921F, 0.7756937791F, 0.7760705514F,
  155157. 0.7764470087F, 0.7768231508F, 0.7771989773F, 0.7775744880F,
  155158. 0.7779496827F, 0.7783245610F, 0.7786991227F, 0.7790733676F,
  155159. 0.7794472953F, 0.7798209056F, 0.7801941982F, 0.7805671729F,
  155160. 0.7809398294F, 0.7813121675F, 0.7816841869F, 0.7820558873F,
  155161. 0.7824272684F, 0.7827983301F, 0.7831690720F, 0.7835394940F,
  155162. 0.7839095957F, 0.7842793768F, 0.7846488373F, 0.7850179767F,
  155163. 0.7853867948F, 0.7857552914F, 0.7861234663F, 0.7864913191F,
  155164. 0.7868588497F, 0.7872260578F, 0.7875929431F, 0.7879595055F,
  155165. 0.7883257445F, 0.7886916601F, 0.7890572520F, 0.7894225198F,
  155166. 0.7897874635F, 0.7901520827F, 0.7905163772F, 0.7908803468F,
  155167. 0.7912439912F, 0.7916073102F, 0.7919703035F, 0.7923329710F,
  155168. 0.7926953124F, 0.7930573274F, 0.7934190158F, 0.7937803774F,
  155169. 0.7941414120F, 0.7945021193F, 0.7948624991F, 0.7952225511F,
  155170. 0.7955822752F, 0.7959416711F, 0.7963007387F, 0.7966594775F,
  155171. 0.7970178875F, 0.7973759685F, 0.7977337201F, 0.7980911422F,
  155172. 0.7984482346F, 0.7988049970F, 0.7991614292F, 0.7995175310F,
  155173. 0.7998733022F, 0.8002287426F, 0.8005838519F, 0.8009386299F,
  155174. 0.8012930765F, 0.8016471914F, 0.8020009744F, 0.8023544253F,
  155175. 0.8027075438F, 0.8030603298F, 0.8034127831F, 0.8037649035F,
  155176. 0.8041166906F, 0.8044681445F, 0.8048192647F, 0.8051700512F,
  155177. 0.8055205038F, 0.8058706222F, 0.8062204062F, 0.8065698556F,
  155178. 0.8069189702F, 0.8072677499F, 0.8076161944F, 0.8079643036F,
  155179. 0.8083120772F, 0.8086595151F, 0.8090066170F, 0.8093533827F,
  155180. 0.8096998122F, 0.8100459051F, 0.8103916613F, 0.8107370806F,
  155181. 0.8110821628F, 0.8114269077F, 0.8117713151F, 0.8121153849F,
  155182. 0.8124591169F, 0.8128025108F, 0.8131455666F, 0.8134882839F,
  155183. 0.8138306627F, 0.8141727027F, 0.8145144038F, 0.8148557658F,
  155184. 0.8151967886F, 0.8155374718F, 0.8158778154F, 0.8162178192F,
  155185. 0.8165574830F, 0.8168968067F, 0.8172357900F, 0.8175744328F,
  155186. 0.8179127349F, 0.8182506962F, 0.8185883164F, 0.8189255955F,
  155187. 0.8192625332F, 0.8195991295F, 0.8199353840F, 0.8202712967F,
  155188. 0.8206068673F, 0.8209420958F, 0.8212769820F, 0.8216115256F,
  155189. 0.8219457266F, 0.8222795848F, 0.8226131000F, 0.8229462721F,
  155190. 0.8232791009F, 0.8236115863F, 0.8239437280F, 0.8242755260F,
  155191. 0.8246069801F, 0.8249380901F, 0.8252688559F, 0.8255992774F,
  155192. 0.8259293544F, 0.8262590867F, 0.8265884741F, 0.8269175167F,
  155193. 0.8272462141F, 0.8275745663F, 0.8279025732F, 0.8282302344F,
  155194. 0.8285575501F, 0.8288845199F, 0.8292111437F, 0.8295374215F,
  155195. 0.8298633530F, 0.8301889382F, 0.8305141768F, 0.8308390688F,
  155196. 0.8311636141F, 0.8314878124F, 0.8318116637F, 0.8321351678F,
  155197. 0.8324583246F, 0.8327811340F, 0.8331035957F, 0.8334257098F,
  155198. 0.8337474761F, 0.8340688944F, 0.8343899647F, 0.8347106867F,
  155199. 0.8350310605F, 0.8353510857F, 0.8356707624F, 0.8359900904F,
  155200. 0.8363090696F, 0.8366276999F, 0.8369459811F, 0.8372639131F,
  155201. 0.8375814958F, 0.8378987292F, 0.8382156130F, 0.8385321472F,
  155202. 0.8388483316F, 0.8391641662F, 0.8394796508F, 0.8397947853F,
  155203. 0.8401095697F, 0.8404240037F, 0.8407380873F, 0.8410518204F,
  155204. 0.8413652029F, 0.8416782347F, 0.8419909156F, 0.8423032456F,
  155205. 0.8426152245F, 0.8429268523F, 0.8432381289F, 0.8435490541F,
  155206. 0.8438596279F, 0.8441698502F, 0.8444797208F, 0.8447892396F,
  155207. 0.8450984067F, 0.8454072218F, 0.8457156849F, 0.8460237959F,
  155208. 0.8463315547F, 0.8466389612F, 0.8469460154F, 0.8472527170F,
  155209. 0.8475590661F, 0.8478650625F, 0.8481707063F, 0.8484759971F,
  155210. 0.8487809351F, 0.8490855201F, 0.8493897521F, 0.8496936308F,
  155211. 0.8499971564F, 0.8503003286F, 0.8506031474F, 0.8509056128F,
  155212. 0.8512077246F, 0.8515094828F, 0.8518108872F, 0.8521119379F,
  155213. 0.8524126348F, 0.8527129777F, 0.8530129666F, 0.8533126015F,
  155214. 0.8536118822F, 0.8539108087F, 0.8542093809F, 0.8545075988F,
  155215. 0.8548054623F, 0.8551029712F, 0.8554001257F, 0.8556969255F,
  155216. 0.8559933707F, 0.8562894611F, 0.8565851968F, 0.8568805775F,
  155217. 0.8571756034F, 0.8574702743F, 0.8577645902F, 0.8580585509F,
  155218. 0.8583521566F, 0.8586454070F, 0.8589383021F, 0.8592308420F,
  155219. 0.8595230265F, 0.8598148556F, 0.8601063292F, 0.8603974473F,
  155220. 0.8606882098F, 0.8609786167F, 0.8612686680F, 0.8615583636F,
  155221. 0.8618477034F, 0.8621366874F, 0.8624253156F, 0.8627135878F,
  155222. 0.8630015042F, 0.8632890646F, 0.8635762690F, 0.8638631173F,
  155223. 0.8641496096F, 0.8644357457F, 0.8647215257F, 0.8650069495F,
  155224. 0.8652920171F, 0.8655767283F, 0.8658610833F, 0.8661450820F,
  155225. 0.8664287243F, 0.8667120102F, 0.8669949397F, 0.8672775127F,
  155226. 0.8675597293F, 0.8678415894F, 0.8681230929F, 0.8684042398F,
  155227. 0.8686850302F, 0.8689654640F, 0.8692455412F, 0.8695252617F,
  155228. 0.8698046255F, 0.8700836327F, 0.8703622831F, 0.8706405768F,
  155229. 0.8709185138F, 0.8711960940F, 0.8714733174F, 0.8717501840F,
  155230. 0.8720266939F, 0.8723028469F, 0.8725786430F, 0.8728540824F,
  155231. 0.8731291648F, 0.8734038905F, 0.8736782592F, 0.8739522711F,
  155232. 0.8742259261F, 0.8744992242F, 0.8747721653F, 0.8750447496F,
  155233. 0.8753169770F, 0.8755888475F, 0.8758603611F, 0.8761315177F,
  155234. 0.8764023175F, 0.8766727603F, 0.8769428462F, 0.8772125752F,
  155235. 0.8774819474F, 0.8777509626F, 0.8780196209F, 0.8782879224F,
  155236. 0.8785558669F, 0.8788234546F, 0.8790906854F, 0.8793575594F,
  155237. 0.8796240765F, 0.8798902368F, 0.8801560403F, 0.8804214870F,
  155238. 0.8806865768F, 0.8809513099F, 0.8812156863F, 0.8814797059F,
  155239. 0.8817433687F, 0.8820066749F, 0.8822696243F, 0.8825322171F,
  155240. 0.8827944532F, 0.8830563327F, 0.8833178556F, 0.8835790219F,
  155241. 0.8838398316F, 0.8841002848F, 0.8843603815F, 0.8846201217F,
  155242. 0.8848795054F, 0.8851385327F, 0.8853972036F, 0.8856555182F,
  155243. 0.8859134764F, 0.8861710783F, 0.8864283239F, 0.8866852133F,
  155244. 0.8869417464F, 0.8871979234F, 0.8874537443F, 0.8877092090F,
  155245. 0.8879643177F, 0.8882190704F, 0.8884734671F, 0.8887275078F,
  155246. 0.8889811927F, 0.8892345216F, 0.8894874948F, 0.8897401122F,
  155247. 0.8899923738F, 0.8902442798F, 0.8904958301F, 0.8907470248F,
  155248. 0.8909978640F, 0.8912483477F, 0.8914984759F, 0.8917482487F,
  155249. 0.8919976662F, 0.8922467284F, 0.8924954353F, 0.8927437871F,
  155250. 0.8929917837F, 0.8932394252F, 0.8934867118F, 0.8937336433F,
  155251. 0.8939802199F, 0.8942264417F, 0.8944723087F, 0.8947178210F,
  155252. 0.8949629785F, 0.8952077815F, 0.8954522299F, 0.8956963239F,
  155253. 0.8959400634F, 0.8961834486F, 0.8964264795F, 0.8966691561F,
  155254. 0.8969114786F, 0.8971534470F, 0.8973950614F, 0.8976363219F,
  155255. 0.8978772284F, 0.8981177812F, 0.8983579802F, 0.8985978256F,
  155256. 0.8988373174F, 0.8990764556F, 0.8993152405F, 0.8995536720F,
  155257. 0.8997917502F, 0.9000294751F, 0.9002668470F, 0.9005038658F,
  155258. 0.9007405317F, 0.9009768446F, 0.9012128048F, 0.9014484123F,
  155259. 0.9016836671F, 0.9019185693F, 0.9021531191F, 0.9023873165F,
  155260. 0.9026211616F, 0.9028546546F, 0.9030877954F, 0.9033205841F,
  155261. 0.9035530210F, 0.9037851059F, 0.9040168392F, 0.9042482207F,
  155262. 0.9044792507F, 0.9047099293F, 0.9049402564F, 0.9051702323F,
  155263. 0.9053998569F, 0.9056291305F, 0.9058580531F, 0.9060866248F,
  155264. 0.9063148457F, 0.9065427159F, 0.9067702355F, 0.9069974046F,
  155265. 0.9072242233F, 0.9074506917F, 0.9076768100F, 0.9079025782F,
  155266. 0.9081279964F, 0.9083530647F, 0.9085777833F, 0.9088021523F,
  155267. 0.9090261717F, 0.9092498417F, 0.9094731623F, 0.9096961338F,
  155268. 0.9099187561F, 0.9101410295F, 0.9103629540F, 0.9105845297F,
  155269. 0.9108057568F, 0.9110266354F, 0.9112471656F, 0.9114673475F,
  155270. 0.9116871812F, 0.9119066668F, 0.9121258046F, 0.9123445945F,
  155271. 0.9125630367F, 0.9127811314F, 0.9129988786F, 0.9132162785F,
  155272. 0.9134333312F, 0.9136500368F, 0.9138663954F, 0.9140824073F,
  155273. 0.9142980724F, 0.9145133910F, 0.9147283632F, 0.9149429890F,
  155274. 0.9151572687F, 0.9153712023F, 0.9155847900F, 0.9157980319F,
  155275. 0.9160109282F, 0.9162234790F, 0.9164356844F, 0.9166475445F,
  155276. 0.9168590595F, 0.9170702296F, 0.9172810548F, 0.9174915354F,
  155277. 0.9177016714F, 0.9179114629F, 0.9181209102F, 0.9183300134F,
  155278. 0.9185387726F, 0.9187471879F, 0.9189552595F, 0.9191629876F,
  155279. 0.9193703723F, 0.9195774136F, 0.9197841119F, 0.9199904672F,
  155280. 0.9201964797F, 0.9204021495F, 0.9206074767F, 0.9208124616F,
  155281. 0.9210171043F, 0.9212214049F, 0.9214253636F, 0.9216289805F,
  155282. 0.9218322558F, 0.9220351896F, 0.9222377821F, 0.9224400335F,
  155283. 0.9226419439F, 0.9228435134F, 0.9230447423F, 0.9232456307F,
  155284. 0.9234461787F, 0.9236463865F, 0.9238462543F, 0.9240457822F,
  155285. 0.9242449704F, 0.9244438190F, 0.9246423282F, 0.9248404983F,
  155286. 0.9250383293F, 0.9252358214F, 0.9254329747F, 0.9256297896F,
  155287. 0.9258262660F, 0.9260224042F, 0.9262182044F, 0.9264136667F,
  155288. 0.9266087913F, 0.9268035783F, 0.9269980280F, 0.9271921405F,
  155289. 0.9273859160F, 0.9275793546F, 0.9277724566F, 0.9279652221F,
  155290. 0.9281576513F, 0.9283497443F, 0.9285415014F, 0.9287329227F,
  155291. 0.9289240084F, 0.9291147586F, 0.9293051737F, 0.9294952536F,
  155292. 0.9296849987F, 0.9298744091F, 0.9300634850F, 0.9302522266F,
  155293. 0.9304406340F, 0.9306287074F, 0.9308164471F, 0.9310038532F,
  155294. 0.9311909259F, 0.9313776654F, 0.9315640719F, 0.9317501455F,
  155295. 0.9319358865F, 0.9321212951F, 0.9323063713F, 0.9324911155F,
  155296. 0.9326755279F, 0.9328596085F, 0.9330433577F, 0.9332267756F,
  155297. 0.9334098623F, 0.9335926182F, 0.9337750434F, 0.9339571380F,
  155298. 0.9341389023F, 0.9343203366F, 0.9345014409F, 0.9346822155F,
  155299. 0.9348626606F, 0.9350427763F, 0.9352225630F, 0.9354020207F,
  155300. 0.9355811498F, 0.9357599503F, 0.9359384226F, 0.9361165667F,
  155301. 0.9362943830F, 0.9364718716F, 0.9366490327F, 0.9368258666F,
  155302. 0.9370023733F, 0.9371785533F, 0.9373544066F, 0.9375299335F,
  155303. 0.9377051341F, 0.9378800087F, 0.9380545576F, 0.9382287809F,
  155304. 0.9384026787F, 0.9385762515F, 0.9387494993F, 0.9389224223F,
  155305. 0.9390950209F, 0.9392672951F, 0.9394392453F, 0.9396108716F,
  155306. 0.9397821743F, 0.9399531536F, 0.9401238096F, 0.9402941427F,
  155307. 0.9404641530F, 0.9406338407F, 0.9408032061F, 0.9409722495F,
  155308. 0.9411409709F, 0.9413093707F, 0.9414774491F, 0.9416452062F,
  155309. 0.9418126424F, 0.9419797579F, 0.9421465528F, 0.9423130274F,
  155310. 0.9424791819F, 0.9426450166F, 0.9428105317F, 0.9429757274F,
  155311. 0.9431406039F, 0.9433051616F, 0.9434694005F, 0.9436333209F,
  155312. 0.9437969232F, 0.9439602074F, 0.9441231739F, 0.9442858229F,
  155313. 0.9444481545F, 0.9446101691F, 0.9447718669F, 0.9449332481F,
  155314. 0.9450943129F, 0.9452550617F, 0.9454154945F, 0.9455756118F,
  155315. 0.9457354136F, 0.9458949003F, 0.9460540721F, 0.9462129292F,
  155316. 0.9463714719F, 0.9465297003F, 0.9466876149F, 0.9468452157F,
  155317. 0.9470025031F, 0.9471594772F, 0.9473161384F, 0.9474724869F,
  155318. 0.9476285229F, 0.9477842466F, 0.9479396584F, 0.9480947585F,
  155319. 0.9482495470F, 0.9484040243F, 0.9485581906F, 0.9487120462F,
  155320. 0.9488655913F, 0.9490188262F, 0.9491717511F, 0.9493243662F,
  155321. 0.9494766718F, 0.9496286683F, 0.9497803557F, 0.9499317345F,
  155322. 0.9500828047F, 0.9502335668F, 0.9503840209F, 0.9505341673F,
  155323. 0.9506840062F, 0.9508335380F, 0.9509827629F, 0.9511316810F,
  155324. 0.9512802928F, 0.9514285984F, 0.9515765982F, 0.9517242923F,
  155325. 0.9518716810F, 0.9520187646F, 0.9521655434F, 0.9523120176F,
  155326. 0.9524581875F, 0.9526040534F, 0.9527496154F, 0.9528948739F,
  155327. 0.9530398292F, 0.9531844814F, 0.9533288310F, 0.9534728780F,
  155328. 0.9536166229F, 0.9537600659F, 0.9539032071F, 0.9540460470F,
  155329. 0.9541885858F, 0.9543308237F, 0.9544727611F, 0.9546143981F,
  155330. 0.9547557351F, 0.9548967723F, 0.9550375100F, 0.9551779485F,
  155331. 0.9553180881F, 0.9554579290F, 0.9555974714F, 0.9557367158F,
  155332. 0.9558756623F, 0.9560143112F, 0.9561526628F, 0.9562907174F,
  155333. 0.9564284752F, 0.9565659366F, 0.9567031017F, 0.9568399710F,
  155334. 0.9569765446F, 0.9571128229F, 0.9572488061F, 0.9573844944F,
  155335. 0.9575198883F, 0.9576549879F, 0.9577897936F, 0.9579243056F,
  155336. 0.9580585242F, 0.9581924497F, 0.9583260824F, 0.9584594226F,
  155337. 0.9585924705F, 0.9587252264F, 0.9588576906F, 0.9589898634F,
  155338. 0.9591217452F, 0.9592533360F, 0.9593846364F, 0.9595156465F,
  155339. 0.9596463666F, 0.9597767971F, 0.9599069382F, 0.9600367901F,
  155340. 0.9601663533F, 0.9602956279F, 0.9604246143F, 0.9605533128F,
  155341. 0.9606817236F, 0.9608098471F, 0.9609376835F, 0.9610652332F,
  155342. 0.9611924963F, 0.9613194733F, 0.9614461644F, 0.9615725699F,
  155343. 0.9616986901F, 0.9618245253F, 0.9619500757F, 0.9620753418F,
  155344. 0.9622003238F, 0.9623250219F, 0.9624494365F, 0.9625735679F,
  155345. 0.9626974163F, 0.9628209821F, 0.9629442656F, 0.9630672671F,
  155346. 0.9631899868F, 0.9633124251F, 0.9634345822F, 0.9635564585F,
  155347. 0.9636780543F, 0.9637993699F, 0.9639204056F, 0.9640411616F,
  155348. 0.9641616383F, 0.9642818359F, 0.9644017549F, 0.9645213955F,
  155349. 0.9646407579F, 0.9647598426F, 0.9648786497F, 0.9649971797F,
  155350. 0.9651154328F, 0.9652334092F, 0.9653511095F, 0.9654685337F,
  155351. 0.9655856823F, 0.9657025556F, 0.9658191538F, 0.9659354773F,
  155352. 0.9660515263F, 0.9661673013F, 0.9662828024F, 0.9663980300F,
  155353. 0.9665129845F, 0.9666276660F, 0.9667420750F, 0.9668562118F,
  155354. 0.9669700766F, 0.9670836698F, 0.9671969917F, 0.9673100425F,
  155355. 0.9674228227F, 0.9675353325F, 0.9676475722F, 0.9677595422F,
  155356. 0.9678712428F, 0.9679826742F, 0.9680938368F, 0.9682047309F,
  155357. 0.9683153569F, 0.9684257150F, 0.9685358056F, 0.9686456289F,
  155358. 0.9687551853F, 0.9688644752F, 0.9689734987F, 0.9690822564F,
  155359. 0.9691907483F, 0.9692989750F, 0.9694069367F, 0.9695146337F,
  155360. 0.9696220663F, 0.9697292349F, 0.9698361398F, 0.9699427813F,
  155361. 0.9700491597F, 0.9701552754F, 0.9702611286F, 0.9703667197F,
  155362. 0.9704720490F, 0.9705771169F, 0.9706819236F, 0.9707864695F,
  155363. 0.9708907549F, 0.9709947802F, 0.9710985456F, 0.9712020514F,
  155364. 0.9713052981F, 0.9714082859F, 0.9715110151F, 0.9716134862F,
  155365. 0.9717156993F, 0.9718176549F, 0.9719193532F, 0.9720207946F,
  155366. 0.9721219794F, 0.9722229080F, 0.9723235806F, 0.9724239976F,
  155367. 0.9725241593F, 0.9726240661F, 0.9727237183F, 0.9728231161F,
  155368. 0.9729222601F, 0.9730211503F, 0.9731197873F, 0.9732181713F,
  155369. 0.9733163027F, 0.9734141817F, 0.9735118088F, 0.9736091842F,
  155370. 0.9737063083F, 0.9738031814F, 0.9738998039F, 0.9739961760F,
  155371. 0.9740922981F, 0.9741881706F, 0.9742837938F, 0.9743791680F,
  155372. 0.9744742935F, 0.9745691707F, 0.9746637999F, 0.9747581814F,
  155373. 0.9748523157F, 0.9749462029F, 0.9750398435F, 0.9751332378F,
  155374. 0.9752263861F, 0.9753192887F, 0.9754119461F, 0.9755043585F,
  155375. 0.9755965262F, 0.9756884496F, 0.9757801291F, 0.9758715650F,
  155376. 0.9759627575F, 0.9760537071F, 0.9761444141F, 0.9762348789F,
  155377. 0.9763251016F, 0.9764150828F, 0.9765048228F, 0.9765943218F,
  155378. 0.9766835802F, 0.9767725984F, 0.9768613767F, 0.9769499154F,
  155379. 0.9770382149F, 0.9771262755F, 0.9772140976F, 0.9773016815F,
  155380. 0.9773890275F, 0.9774761360F, 0.9775630073F, 0.9776496418F,
  155381. 0.9777360398F, 0.9778222016F, 0.9779081277F, 0.9779938182F,
  155382. 0.9780792736F, 0.9781644943F, 0.9782494805F, 0.9783342326F,
  155383. 0.9784187509F, 0.9785030359F, 0.9785870877F, 0.9786709069F,
  155384. 0.9787544936F, 0.9788378484F, 0.9789209714F, 0.9790038631F,
  155385. 0.9790865238F, 0.9791689538F, 0.9792511535F, 0.9793331232F,
  155386. 0.9794148633F, 0.9794963742F, 0.9795776561F, 0.9796587094F,
  155387. 0.9797395345F, 0.9798201316F, 0.9799005013F, 0.9799806437F,
  155388. 0.9800605593F, 0.9801402483F, 0.9802197112F, 0.9802989483F,
  155389. 0.9803779600F, 0.9804567465F, 0.9805353082F, 0.9806136455F,
  155390. 0.9806917587F, 0.9807696482F, 0.9808473143F, 0.9809247574F,
  155391. 0.9810019778F, 0.9810789759F, 0.9811557519F, 0.9812323064F,
  155392. 0.9813086395F, 0.9813847517F, 0.9814606433F, 0.9815363147F,
  155393. 0.9816117662F, 0.9816869981F, 0.9817620108F, 0.9818368047F,
  155394. 0.9819113801F, 0.9819857374F, 0.9820598769F, 0.9821337989F,
  155395. 0.9822075038F, 0.9822809920F, 0.9823542638F, 0.9824273195F,
  155396. 0.9825001596F, 0.9825727843F, 0.9826451940F, 0.9827173891F,
  155397. 0.9827893700F, 0.9828611368F, 0.9829326901F, 0.9830040302F,
  155398. 0.9830751574F, 0.9831460720F, 0.9832167745F, 0.9832872652F,
  155399. 0.9833575444F, 0.9834276124F, 0.9834974697F, 0.9835671166F,
  155400. 0.9836365535F, 0.9837057806F, 0.9837747983F, 0.9838436071F,
  155401. 0.9839122072F, 0.9839805990F, 0.9840487829F, 0.9841167591F,
  155402. 0.9841845282F, 0.9842520903F, 0.9843194459F, 0.9843865953F,
  155403. 0.9844535389F, 0.9845202771F, 0.9845868101F, 0.9846531383F,
  155404. 0.9847192622F, 0.9847851820F, 0.9848508980F, 0.9849164108F,
  155405. 0.9849817205F, 0.9850468276F, 0.9851117324F, 0.9851764352F,
  155406. 0.9852409365F, 0.9853052366F, 0.9853693358F, 0.9854332344F,
  155407. 0.9854969330F, 0.9855604317F, 0.9856237309F, 0.9856868310F,
  155408. 0.9857497325F, 0.9858124355F, 0.9858749404F, 0.9859372477F,
  155409. 0.9859993577F, 0.9860612707F, 0.9861229871F, 0.9861845072F,
  155410. 0.9862458315F, 0.9863069601F, 0.9863678936F, 0.9864286322F,
  155411. 0.9864891764F, 0.9865495264F, 0.9866096826F, 0.9866696454F,
  155412. 0.9867294152F, 0.9867889922F, 0.9868483769F, 0.9869075695F,
  155413. 0.9869665706F, 0.9870253803F, 0.9870839991F, 0.9871424273F,
  155414. 0.9872006653F, 0.9872587135F, 0.9873165721F, 0.9873742415F,
  155415. 0.9874317222F, 0.9874890144F, 0.9875461185F, 0.9876030348F,
  155416. 0.9876597638F, 0.9877163057F, 0.9877726610F, 0.9878288300F,
  155417. 0.9878848130F, 0.9879406104F, 0.9879962225F, 0.9880516497F,
  155418. 0.9881068924F, 0.9881619509F, 0.9882168256F, 0.9882715168F,
  155419. 0.9883260249F, 0.9883803502F, 0.9884344931F, 0.9884884539F,
  155420. 0.9885422331F, 0.9885958309F, 0.9886492477F, 0.9887024838F,
  155421. 0.9887555397F, 0.9888084157F, 0.9888611120F, 0.9889136292F,
  155422. 0.9889659675F, 0.9890181273F, 0.9890701089F, 0.9891219128F,
  155423. 0.9891735392F, 0.9892249885F, 0.9892762610F, 0.9893273572F,
  155424. 0.9893782774F, 0.9894290219F, 0.9894795911F, 0.9895299853F,
  155425. 0.9895802049F, 0.9896302502F, 0.9896801217F, 0.9897298196F,
  155426. 0.9897793443F, 0.9898286961F, 0.9898778755F, 0.9899268828F,
  155427. 0.9899757183F, 0.9900243823F, 0.9900728753F, 0.9901211976F,
  155428. 0.9901693495F, 0.9902173314F, 0.9902651436F, 0.9903127865F,
  155429. 0.9903602605F, 0.9904075659F, 0.9904547031F, 0.9905016723F,
  155430. 0.9905484740F, 0.9905951086F, 0.9906415763F, 0.9906878775F,
  155431. 0.9907340126F, 0.9907799819F, 0.9908257858F, 0.9908714247F,
  155432. 0.9909168988F, 0.9909622086F, 0.9910073543F, 0.9910523364F,
  155433. 0.9910971552F, 0.9911418110F, 0.9911863042F, 0.9912306351F,
  155434. 0.9912748042F, 0.9913188117F, 0.9913626580F, 0.9914063435F,
  155435. 0.9914498684F, 0.9914932333F, 0.9915364383F, 0.9915794839F,
  155436. 0.9916223703F, 0.9916650981F, 0.9917076674F, 0.9917500787F,
  155437. 0.9917923323F, 0.9918344286F, 0.9918763679F, 0.9919181505F,
  155438. 0.9919597769F, 0.9920012473F, 0.9920425621F, 0.9920837217F,
  155439. 0.9921247263F, 0.9921655765F, 0.9922062724F, 0.9922468145F,
  155440. 0.9922872030F, 0.9923274385F, 0.9923675211F, 0.9924074513F,
  155441. 0.9924472294F, 0.9924868557F, 0.9925263306F, 0.9925656544F,
  155442. 0.9926048275F, 0.9926438503F, 0.9926827230F, 0.9927214461F,
  155443. 0.9927600199F, 0.9927984446F, 0.9928367208F, 0.9928748486F,
  155444. 0.9929128285F, 0.9929506608F, 0.9929883459F, 0.9930258841F,
  155445. 0.9930632757F, 0.9931005211F, 0.9931376207F, 0.9931745747F,
  155446. 0.9932113836F, 0.9932480476F, 0.9932845671F, 0.9933209425F,
  155447. 0.9933571742F, 0.9933932623F, 0.9934292074F, 0.9934650097F,
  155448. 0.9935006696F, 0.9935361874F, 0.9935715635F, 0.9936067982F,
  155449. 0.9936418919F, 0.9936768448F, 0.9937116574F, 0.9937463300F,
  155450. 0.9937808629F, 0.9938152565F, 0.9938495111F, 0.9938836271F,
  155451. 0.9939176047F, 0.9939514444F, 0.9939851465F, 0.9940187112F,
  155452. 0.9940521391F, 0.9940854303F, 0.9941185853F, 0.9941516044F,
  155453. 0.9941844879F, 0.9942172361F, 0.9942498495F, 0.9942823283F,
  155454. 0.9943146729F, 0.9943468836F, 0.9943789608F, 0.9944109047F,
  155455. 0.9944427158F, 0.9944743944F, 0.9945059408F, 0.9945373553F,
  155456. 0.9945686384F, 0.9945997902F, 0.9946308112F, 0.9946617017F,
  155457. 0.9946924621F, 0.9947230926F, 0.9947535937F, 0.9947839656F,
  155458. 0.9948142086F, 0.9948443232F, 0.9948743097F, 0.9949041683F,
  155459. 0.9949338995F, 0.9949635035F, 0.9949929807F, 0.9950223315F,
  155460. 0.9950515561F, 0.9950806549F, 0.9951096282F, 0.9951384764F,
  155461. 0.9951671998F, 0.9951957987F, 0.9952242735F, 0.9952526245F,
  155462. 0.9952808520F, 0.9953089564F, 0.9953369380F, 0.9953647971F,
  155463. 0.9953925340F, 0.9954201491F, 0.9954476428F, 0.9954750153F,
  155464. 0.9955022670F, 0.9955293981F, 0.9955564092F, 0.9955833003F,
  155465. 0.9956100720F, 0.9956367245F, 0.9956632582F, 0.9956896733F,
  155466. 0.9957159703F, 0.9957421494F, 0.9957682110F, 0.9957941553F,
  155467. 0.9958199828F, 0.9958456937F, 0.9958712884F, 0.9958967672F,
  155468. 0.9959221305F, 0.9959473784F, 0.9959725115F, 0.9959975300F,
  155469. 0.9960224342F, 0.9960472244F, 0.9960719011F, 0.9960964644F,
  155470. 0.9961209148F, 0.9961452525F, 0.9961694779F, 0.9961935913F,
  155471. 0.9962175930F, 0.9962414834F, 0.9962652627F, 0.9962889313F,
  155472. 0.9963124895F, 0.9963359377F, 0.9963592761F, 0.9963825051F,
  155473. 0.9964056250F, 0.9964286361F, 0.9964515387F, 0.9964743332F,
  155474. 0.9964970198F, 0.9965195990F, 0.9965420709F, 0.9965644360F,
  155475. 0.9965866946F, 0.9966088469F, 0.9966308932F, 0.9966528340F,
  155476. 0.9966746695F, 0.9966964001F, 0.9967180260F, 0.9967395475F,
  155477. 0.9967609651F, 0.9967822789F, 0.9968034894F, 0.9968245968F,
  155478. 0.9968456014F, 0.9968665036F, 0.9968873037F, 0.9969080019F,
  155479. 0.9969285987F, 0.9969490942F, 0.9969694889F, 0.9969897830F,
  155480. 0.9970099769F, 0.9970300708F, 0.9970500651F, 0.9970699601F,
  155481. 0.9970897561F, 0.9971094533F, 0.9971290522F, 0.9971485531F,
  155482. 0.9971679561F, 0.9971872617F, 0.9972064702F, 0.9972255818F,
  155483. 0.9972445968F, 0.9972635157F, 0.9972823386F, 0.9973010659F,
  155484. 0.9973196980F, 0.9973382350F, 0.9973566773F, 0.9973750253F,
  155485. 0.9973932791F, 0.9974114392F, 0.9974295059F, 0.9974474793F,
  155486. 0.9974653599F, 0.9974831480F, 0.9975008438F, 0.9975184476F,
  155487. 0.9975359598F, 0.9975533806F, 0.9975707104F, 0.9975879495F,
  155488. 0.9976050981F, 0.9976221566F, 0.9976391252F, 0.9976560043F,
  155489. 0.9976727941F, 0.9976894950F, 0.9977061073F, 0.9977226312F,
  155490. 0.9977390671F, 0.9977554152F, 0.9977716759F, 0.9977878495F,
  155491. 0.9978039361F, 0.9978199363F, 0.9978358501F, 0.9978516780F,
  155492. 0.9978674202F, 0.9978830771F, 0.9978986488F, 0.9979141358F,
  155493. 0.9979295383F, 0.9979448566F, 0.9979600909F, 0.9979752417F,
  155494. 0.9979903091F, 0.9980052936F, 0.9980201952F, 0.9980350145F,
  155495. 0.9980497515F, 0.9980644067F, 0.9980789804F, 0.9980934727F,
  155496. 0.9981078841F, 0.9981222147F, 0.9981364649F, 0.9981506350F,
  155497. 0.9981647253F, 0.9981787360F, 0.9981926674F, 0.9982065199F,
  155498. 0.9982202936F, 0.9982339890F, 0.9982476062F, 0.9982611456F,
  155499. 0.9982746074F, 0.9982879920F, 0.9983012996F, 0.9983145304F,
  155500. 0.9983276849F, 0.9983407632F, 0.9983537657F, 0.9983666926F,
  155501. 0.9983795442F, 0.9983923208F, 0.9984050226F, 0.9984176501F,
  155502. 0.9984302033F, 0.9984426827F, 0.9984550884F, 0.9984674208F,
  155503. 0.9984796802F, 0.9984918667F, 0.9985039808F, 0.9985160227F,
  155504. 0.9985279926F, 0.9985398909F, 0.9985517177F, 0.9985634734F,
  155505. 0.9985751583F, 0.9985867727F, 0.9985983167F, 0.9986097907F,
  155506. 0.9986211949F, 0.9986325297F, 0.9986437953F, 0.9986549919F,
  155507. 0.9986661199F, 0.9986771795F, 0.9986881710F, 0.9986990946F,
  155508. 0.9987099507F, 0.9987207394F, 0.9987314611F, 0.9987421161F,
  155509. 0.9987527045F, 0.9987632267F, 0.9987736829F, 0.9987840734F,
  155510. 0.9987943985F, 0.9988046584F, 0.9988148534F, 0.9988249838F,
  155511. 0.9988350498F, 0.9988450516F, 0.9988549897F, 0.9988648641F,
  155512. 0.9988746753F, 0.9988844233F, 0.9988941086F, 0.9989037313F,
  155513. 0.9989132918F, 0.9989227902F, 0.9989322269F, 0.9989416021F,
  155514. 0.9989509160F, 0.9989601690F, 0.9989693613F, 0.9989784931F,
  155515. 0.9989875647F, 0.9989965763F, 0.9990055283F, 0.9990144208F,
  155516. 0.9990232541F, 0.9990320286F, 0.9990407443F, 0.9990494016F,
  155517. 0.9990580008F, 0.9990665421F, 0.9990750257F, 0.9990834519F,
  155518. 0.9990918209F, 0.9991001331F, 0.9991083886F, 0.9991165877F,
  155519. 0.9991247307F, 0.9991328177F, 0.9991408491F, 0.9991488251F,
  155520. 0.9991567460F, 0.9991646119F, 0.9991724232F, 0.9991801801F,
  155521. 0.9991878828F, 0.9991955316F, 0.9992031267F, 0.9992106684F,
  155522. 0.9992181569F, 0.9992255925F, 0.9992329753F, 0.9992403057F,
  155523. 0.9992475839F, 0.9992548101F, 0.9992619846F, 0.9992691076F,
  155524. 0.9992761793F, 0.9992832001F, 0.9992901701F, 0.9992970895F,
  155525. 0.9993039587F, 0.9993107777F, 0.9993175470F, 0.9993242667F,
  155526. 0.9993309371F, 0.9993375583F, 0.9993441307F, 0.9993506545F,
  155527. 0.9993571298F, 0.9993635570F, 0.9993699362F, 0.9993762678F,
  155528. 0.9993825519F, 0.9993887887F, 0.9993949785F, 0.9994011216F,
  155529. 0.9994072181F, 0.9994132683F, 0.9994192725F, 0.9994252307F,
  155530. 0.9994311434F, 0.9994370107F, 0.9994428327F, 0.9994486099F,
  155531. 0.9994543423F, 0.9994600303F, 0.9994656739F, 0.9994712736F,
  155532. 0.9994768294F, 0.9994823417F, 0.9994878105F, 0.9994932363F,
  155533. 0.9994986191F, 0.9995039592F, 0.9995092568F, 0.9995145122F,
  155534. 0.9995197256F, 0.9995248971F, 0.9995300270F, 0.9995351156F,
  155535. 0.9995401630F, 0.9995451695F, 0.9995501352F, 0.9995550604F,
  155536. 0.9995599454F, 0.9995647903F, 0.9995695953F, 0.9995743607F,
  155537. 0.9995790866F, 0.9995837734F, 0.9995884211F, 0.9995930300F,
  155538. 0.9995976004F, 0.9996021324F, 0.9996066263F, 0.9996110822F,
  155539. 0.9996155004F, 0.9996198810F, 0.9996242244F, 0.9996285306F,
  155540. 0.9996327999F, 0.9996370326F, 0.9996412287F, 0.9996453886F,
  155541. 0.9996495125F, 0.9996536004F, 0.9996576527F, 0.9996616696F,
  155542. 0.9996656512F, 0.9996695977F, 0.9996735094F, 0.9996773865F,
  155543. 0.9996812291F, 0.9996850374F, 0.9996888118F, 0.9996925523F,
  155544. 0.9996962591F, 0.9996999325F, 0.9997035727F, 0.9997071798F,
  155545. 0.9997107541F, 0.9997142957F, 0.9997178049F, 0.9997212818F,
  155546. 0.9997247266F, 0.9997281396F, 0.9997315209F, 0.9997348708F,
  155547. 0.9997381893F, 0.9997414767F, 0.9997447333F, 0.9997479591F,
  155548. 0.9997511544F, 0.9997543194F, 0.9997574542F, 0.9997605591F,
  155549. 0.9997636342F, 0.9997666797F, 0.9997696958F, 0.9997726828F,
  155550. 0.9997756407F, 0.9997785698F, 0.9997814703F, 0.9997843423F,
  155551. 0.9997871860F, 0.9997900016F, 0.9997927894F, 0.9997955494F,
  155552. 0.9997982818F, 0.9998009869F, 0.9998036648F, 0.9998063157F,
  155553. 0.9998089398F, 0.9998115373F, 0.9998141082F, 0.9998166529F,
  155554. 0.9998191715F, 0.9998216642F, 0.9998241311F, 0.9998265724F,
  155555. 0.9998289884F, 0.9998313790F, 0.9998337447F, 0.9998360854F,
  155556. 0.9998384015F, 0.9998406930F, 0.9998429602F, 0.9998452031F,
  155557. 0.9998474221F, 0.9998496171F, 0.9998517885F, 0.9998539364F,
  155558. 0.9998560610F, 0.9998581624F, 0.9998602407F, 0.9998622962F,
  155559. 0.9998643291F, 0.9998663394F, 0.9998683274F, 0.9998702932F,
  155560. 0.9998722370F, 0.9998741589F, 0.9998760591F, 0.9998779378F,
  155561. 0.9998797952F, 0.9998816313F, 0.9998834464F, 0.9998852406F,
  155562. 0.9998870141F, 0.9998887670F, 0.9998904995F, 0.9998922117F,
  155563. 0.9998939039F, 0.9998955761F, 0.9998972285F, 0.9998988613F,
  155564. 0.9999004746F, 0.9999020686F, 0.9999036434F, 0.9999051992F,
  155565. 0.9999067362F, 0.9999082544F, 0.9999097541F, 0.9999112354F,
  155566. 0.9999126984F, 0.9999141433F, 0.9999155703F, 0.9999169794F,
  155567. 0.9999183709F, 0.9999197449F, 0.9999211014F, 0.9999224408F,
  155568. 0.9999237631F, 0.9999250684F, 0.9999263570F, 0.9999276289F,
  155569. 0.9999288843F, 0.9999301233F, 0.9999313461F, 0.9999325529F,
  155570. 0.9999337437F, 0.9999349187F, 0.9999360780F, 0.9999372218F,
  155571. 0.9999383503F, 0.9999394635F, 0.9999405616F, 0.9999416447F,
  155572. 0.9999427129F, 0.9999437665F, 0.9999448055F, 0.9999458301F,
  155573. 0.9999468404F, 0.9999478365F, 0.9999488185F, 0.9999497867F,
  155574. 0.9999507411F, 0.9999516819F, 0.9999526091F, 0.9999535230F,
  155575. 0.9999544236F, 0.9999553111F, 0.9999561856F, 0.9999570472F,
  155576. 0.9999578960F, 0.9999587323F, 0.9999595560F, 0.9999603674F,
  155577. 0.9999611666F, 0.9999619536F, 0.9999627286F, 0.9999634917F,
  155578. 0.9999642431F, 0.9999649828F, 0.9999657110F, 0.9999664278F,
  155579. 0.9999671334F, 0.9999678278F, 0.9999685111F, 0.9999691835F,
  155580. 0.9999698451F, 0.9999704960F, 0.9999711364F, 0.9999717662F,
  155581. 0.9999723858F, 0.9999729950F, 0.9999735942F, 0.9999741834F,
  155582. 0.9999747626F, 0.9999753321F, 0.9999758919F, 0.9999764421F,
  155583. 0.9999769828F, 0.9999775143F, 0.9999780364F, 0.9999785495F,
  155584. 0.9999790535F, 0.9999795485F, 0.9999800348F, 0.9999805124F,
  155585. 0.9999809813F, 0.9999814417F, 0.9999818938F, 0.9999823375F,
  155586. 0.9999827731F, 0.9999832005F, 0.9999836200F, 0.9999840316F,
  155587. 0.9999844353F, 0.9999848314F, 0.9999852199F, 0.9999856008F,
  155588. 0.9999859744F, 0.9999863407F, 0.9999866997F, 0.9999870516F,
  155589. 0.9999873965F, 0.9999877345F, 0.9999880656F, 0.9999883900F,
  155590. 0.9999887078F, 0.9999890190F, 0.9999893237F, 0.9999896220F,
  155591. 0.9999899140F, 0.9999901999F, 0.9999904796F, 0.9999907533F,
  155592. 0.9999910211F, 0.9999912830F, 0.9999915391F, 0.9999917896F,
  155593. 0.9999920345F, 0.9999922738F, 0.9999925077F, 0.9999927363F,
  155594. 0.9999929596F, 0.9999931777F, 0.9999933907F, 0.9999935987F,
  155595. 0.9999938018F, 0.9999940000F, 0.9999941934F, 0.9999943820F,
  155596. 0.9999945661F, 0.9999947456F, 0.9999949206F, 0.9999950912F,
  155597. 0.9999952575F, 0.9999954195F, 0.9999955773F, 0.9999957311F,
  155598. 0.9999958807F, 0.9999960265F, 0.9999961683F, 0.9999963063F,
  155599. 0.9999964405F, 0.9999965710F, 0.9999966979F, 0.9999968213F,
  155600. 0.9999969412F, 0.9999970576F, 0.9999971707F, 0.9999972805F,
  155601. 0.9999973871F, 0.9999974905F, 0.9999975909F, 0.9999976881F,
  155602. 0.9999977824F, 0.9999978738F, 0.9999979624F, 0.9999980481F,
  155603. 0.9999981311F, 0.9999982115F, 0.9999982892F, 0.9999983644F,
  155604. 0.9999984370F, 0.9999985072F, 0.9999985750F, 0.9999986405F,
  155605. 0.9999987037F, 0.9999987647F, 0.9999988235F, 0.9999988802F,
  155606. 0.9999989348F, 0.9999989873F, 0.9999990379F, 0.9999990866F,
  155607. 0.9999991334F, 0.9999991784F, 0.9999992217F, 0.9999992632F,
  155608. 0.9999993030F, 0.9999993411F, 0.9999993777F, 0.9999994128F,
  155609. 0.9999994463F, 0.9999994784F, 0.9999995091F, 0.9999995384F,
  155610. 0.9999995663F, 0.9999995930F, 0.9999996184F, 0.9999996426F,
  155611. 0.9999996657F, 0.9999996876F, 0.9999997084F, 0.9999997282F,
  155612. 0.9999997469F, 0.9999997647F, 0.9999997815F, 0.9999997973F,
  155613. 0.9999998123F, 0.9999998265F, 0.9999998398F, 0.9999998524F,
  155614. 0.9999998642F, 0.9999998753F, 0.9999998857F, 0.9999998954F,
  155615. 0.9999999045F, 0.9999999130F, 0.9999999209F, 0.9999999282F,
  155616. 0.9999999351F, 0.9999999414F, 0.9999999472F, 0.9999999526F,
  155617. 0.9999999576F, 0.9999999622F, 0.9999999664F, 0.9999999702F,
  155618. 0.9999999737F, 0.9999999769F, 0.9999999798F, 0.9999999824F,
  155619. 0.9999999847F, 0.9999999868F, 0.9999999887F, 0.9999999904F,
  155620. 0.9999999919F, 0.9999999932F, 0.9999999943F, 0.9999999953F,
  155621. 0.9999999961F, 0.9999999969F, 0.9999999975F, 0.9999999980F,
  155622. 0.9999999985F, 0.9999999988F, 0.9999999991F, 0.9999999993F,
  155623. 0.9999999995F, 0.9999999997F, 0.9999999998F, 0.9999999999F,
  155624. 0.9999999999F, 1.0000000000F, 1.0000000000F, 1.0000000000F,
  155625. 1.0000000000F, 1.0000000000F, 1.0000000000F, 1.0000000000F,
  155626. };
  155627. static float *vwin[8] = {
  155628. vwin64,
  155629. vwin128,
  155630. vwin256,
  155631. vwin512,
  155632. vwin1024,
  155633. vwin2048,
  155634. vwin4096,
  155635. vwin8192,
  155636. };
  155637. float *_vorbis_window_get(int n){
  155638. return vwin[n];
  155639. }
  155640. void _vorbis_apply_window(float *d,int *winno,long *blocksizes,
  155641. int lW,int W,int nW){
  155642. lW=(W?lW:0);
  155643. nW=(W?nW:0);
  155644. {
  155645. float *windowLW=vwin[winno[lW]];
  155646. float *windowNW=vwin[winno[nW]];
  155647. long n=blocksizes[W];
  155648. long ln=blocksizes[lW];
  155649. long rn=blocksizes[nW];
  155650. long leftbegin=n/4-ln/4;
  155651. long leftend=leftbegin+ln/2;
  155652. long rightbegin=n/2+n/4-rn/4;
  155653. long rightend=rightbegin+rn/2;
  155654. int i,p;
  155655. for(i=0;i<leftbegin;i++)
  155656. d[i]=0.f;
  155657. for(p=0;i<leftend;i++,p++)
  155658. d[i]*=windowLW[p];
  155659. for(i=rightbegin,p=rn/2-1;i<rightend;i++,p--)
  155660. d[i]*=windowNW[p];
  155661. for(;i<n;i++)
  155662. d[i]=0.f;
  155663. }
  155664. }
  155665. #endif
  155666. /*** End of inlined file: window.c ***/
  155667. #else
  155668. #include <vorbis/vorbisenc.h>
  155669. #include <vorbis/codec.h>
  155670. #include <vorbis/vorbisfile.h>
  155671. #endif
  155672. }
  155673. #undef max
  155674. #undef min
  155675. BEGIN_JUCE_NAMESPACE
  155676. static const char* const oggFormatName = "Ogg-Vorbis file";
  155677. static const juce_wchar* const oggExtensions[] = { T(".ogg"), 0 };
  155678. class OggReader : public AudioFormatReader
  155679. {
  155680. OggVorbisNamespace::OggVorbis_File ovFile;
  155681. OggVorbisNamespace::ov_callbacks callbacks;
  155682. AudioSampleBuffer reservoir;
  155683. int reservoirStart, samplesInReservoir;
  155684. public:
  155685. OggReader (InputStream* const inp)
  155686. : AudioFormatReader (inp, TRANS (oggFormatName)),
  155687. reservoir (2, 4096),
  155688. reservoirStart (0),
  155689. samplesInReservoir (0)
  155690. {
  155691. using namespace OggVorbisNamespace;
  155692. sampleRate = 0;
  155693. usesFloatingPointData = true;
  155694. callbacks.read_func = &oggReadCallback;
  155695. callbacks.seek_func = &oggSeekCallback;
  155696. callbacks.close_func = &oggCloseCallback;
  155697. callbacks.tell_func = &oggTellCallback;
  155698. const int err = ov_open_callbacks (input, &ovFile, 0, 0, callbacks);
  155699. if (err == 0)
  155700. {
  155701. vorbis_info* info = ov_info (&ovFile, -1);
  155702. lengthInSamples = (uint32) ov_pcm_total (&ovFile, -1);
  155703. numChannels = info->channels;
  155704. bitsPerSample = 16;
  155705. sampleRate = info->rate;
  155706. reservoir.setSize (numChannels,
  155707. (int) jmin (lengthInSamples, (int64) reservoir.getNumSamples()));
  155708. }
  155709. }
  155710. ~OggReader()
  155711. {
  155712. OggVorbisNamespace::ov_clear (&ovFile);
  155713. }
  155714. bool readSamples (int** destSamples, int numDestChannels, int startOffsetInDestBuffer,
  155715. int64 startSampleInFile, int numSamples)
  155716. {
  155717. while (numSamples > 0)
  155718. {
  155719. const int numAvailable = reservoirStart + samplesInReservoir - startSampleInFile;
  155720. if (startSampleInFile >= reservoirStart && numAvailable > 0)
  155721. {
  155722. // got a few samples overlapping, so use them before seeking..
  155723. const int numToUse = jmin (numSamples, numAvailable);
  155724. for (int i = jmin (numDestChannels, reservoir.getNumChannels()); --i >= 0;)
  155725. if (destSamples[i] != 0)
  155726. memcpy (destSamples[i] + startOffsetInDestBuffer,
  155727. reservoir.getSampleData (i, (int) (startSampleInFile - reservoirStart)),
  155728. sizeof (float) * numToUse);
  155729. startSampleInFile += numToUse;
  155730. numSamples -= numToUse;
  155731. startOffsetInDestBuffer += numToUse;
  155732. if (numSamples == 0)
  155733. break;
  155734. }
  155735. if (startSampleInFile < reservoirStart
  155736. || startSampleInFile + numSamples > reservoirStart + samplesInReservoir)
  155737. {
  155738. // buffer miss, so refill the reservoir
  155739. int bitStream = 0;
  155740. reservoirStart = jmax (0, (int) startSampleInFile);
  155741. samplesInReservoir = reservoir.getNumSamples();
  155742. if (reservoirStart != (int) OggVorbisNamespace::ov_pcm_tell (&ovFile))
  155743. OggVorbisNamespace::ov_pcm_seek (&ovFile, reservoirStart);
  155744. int offset = 0;
  155745. int numToRead = samplesInReservoir;
  155746. while (numToRead > 0)
  155747. {
  155748. float** dataIn = 0;
  155749. const int samps = OggVorbisNamespace::ov_read_float (&ovFile, &dataIn, numToRead, &bitStream);
  155750. if (samps <= 0)
  155751. break;
  155752. jassert (samps <= numToRead);
  155753. for (int i = jmin ((int) numChannels, reservoir.getNumChannels()); --i >= 0;)
  155754. {
  155755. memcpy (reservoir.getSampleData (i, offset),
  155756. dataIn[i],
  155757. sizeof (float) * samps);
  155758. }
  155759. numToRead -= samps;
  155760. offset += samps;
  155761. }
  155762. if (numToRead > 0)
  155763. reservoir.clear (offset, numToRead);
  155764. }
  155765. }
  155766. if (numSamples > 0)
  155767. {
  155768. for (int i = numDestChannels; --i >= 0;)
  155769. if (destSamples[i] != 0)
  155770. zeromem (destSamples[i] + startOffsetInDestBuffer,
  155771. sizeof (int) * numSamples);
  155772. }
  155773. return true;
  155774. }
  155775. static size_t oggReadCallback (void* ptr, size_t size, size_t nmemb, void* datasource)
  155776. {
  155777. return (size_t) (static_cast <InputStream*> (datasource)->read (ptr, (int) (size * nmemb)) / size);
  155778. }
  155779. static int oggSeekCallback (void* datasource, OggVorbisNamespace::ogg_int64_t offset, int whence)
  155780. {
  155781. InputStream* const in = static_cast <InputStream*> (datasource);
  155782. if (whence == SEEK_CUR)
  155783. offset += in->getPosition();
  155784. else if (whence == SEEK_END)
  155785. offset += in->getTotalLength();
  155786. in->setPosition (offset);
  155787. return 0;
  155788. }
  155789. static int oggCloseCallback (void*)
  155790. {
  155791. return 0;
  155792. }
  155793. static long oggTellCallback (void* datasource)
  155794. {
  155795. return (long) static_cast <InputStream*> (datasource)->getPosition();
  155796. }
  155797. juce_UseDebuggingNewOperator
  155798. };
  155799. class OggWriter : public AudioFormatWriter
  155800. {
  155801. OggVorbisNamespace::ogg_stream_state os;
  155802. OggVorbisNamespace::ogg_page og;
  155803. OggVorbisNamespace::ogg_packet op;
  155804. OggVorbisNamespace::vorbis_info vi;
  155805. OggVorbisNamespace::vorbis_comment vc;
  155806. OggVorbisNamespace::vorbis_dsp_state vd;
  155807. OggVorbisNamespace::vorbis_block vb;
  155808. public:
  155809. bool ok;
  155810. OggWriter (OutputStream* const out,
  155811. const double sampleRate,
  155812. const int numChannels,
  155813. const int bitsPerSample,
  155814. const int qualityIndex)
  155815. : AudioFormatWriter (out, TRANS (oggFormatName),
  155816. sampleRate,
  155817. numChannels,
  155818. bitsPerSample)
  155819. {
  155820. using namespace OggVorbisNamespace;
  155821. ok = false;
  155822. vorbis_info_init (&vi);
  155823. if (vorbis_encode_init_vbr (&vi,
  155824. numChannels,
  155825. (int) sampleRate,
  155826. jlimit (0.0f, 1.0f, qualityIndex * 0.5f)) == 0)
  155827. {
  155828. vorbis_comment_init (&vc);
  155829. if (JUCEApplication::getInstance() != 0)
  155830. vorbis_comment_add_tag (&vc, "ENCODER", const_cast <char*> (JUCEApplication::getInstance()->getApplicationName().toUTF8()));
  155831. vorbis_analysis_init (&vd, &vi);
  155832. vorbis_block_init (&vd, &vb);
  155833. ogg_stream_init (&os, Random::getSystemRandom().nextInt());
  155834. ogg_packet header;
  155835. ogg_packet header_comm;
  155836. ogg_packet header_code;
  155837. vorbis_analysis_headerout (&vd, &vc, &header, &header_comm, &header_code);
  155838. ogg_stream_packetin (&os, &header);
  155839. ogg_stream_packetin (&os, &header_comm);
  155840. ogg_stream_packetin (&os, &header_code);
  155841. for (;;)
  155842. {
  155843. if (ogg_stream_flush (&os, &og) == 0)
  155844. break;
  155845. output->write (og.header, og.header_len);
  155846. output->write (og.body, og.body_len);
  155847. }
  155848. ok = true;
  155849. }
  155850. }
  155851. ~OggWriter()
  155852. {
  155853. using namespace OggVorbisNamespace;
  155854. if (ok)
  155855. {
  155856. // write a zero-length packet to show ogg that we're finished..
  155857. write (0, 0);
  155858. ogg_stream_clear (&os);
  155859. vorbis_block_clear (&vb);
  155860. vorbis_dsp_clear (&vd);
  155861. vorbis_comment_clear (&vc);
  155862. vorbis_info_clear (&vi);
  155863. output->flush();
  155864. }
  155865. else
  155866. {
  155867. vorbis_info_clear (&vi);
  155868. output = 0; // to stop the base class deleting this, as it needs to be returned
  155869. // to the caller of createWriter()
  155870. }
  155871. }
  155872. bool write (const int** samplesToWrite, int numSamples)
  155873. {
  155874. using namespace OggVorbisNamespace;
  155875. if (! ok)
  155876. return false;
  155877. if (numSamples > 0)
  155878. {
  155879. const double gain = 1.0 / 0x80000000u;
  155880. float** const vorbisBuffer = vorbis_analysis_buffer (&vd, numSamples);
  155881. for (int i = numChannels; --i >= 0;)
  155882. {
  155883. float* const dst = vorbisBuffer[i];
  155884. const int* const src = samplesToWrite [i];
  155885. if (src != 0 && dst != 0)
  155886. {
  155887. for (int j = 0; j < numSamples; ++j)
  155888. dst[j] = (float) (src[j] * gain);
  155889. }
  155890. }
  155891. }
  155892. vorbis_analysis_wrote (&vd, numSamples);
  155893. while (vorbis_analysis_blockout (&vd, &vb) == 1)
  155894. {
  155895. vorbis_analysis (&vb, 0);
  155896. vorbis_bitrate_addblock (&vb);
  155897. while (vorbis_bitrate_flushpacket (&vd, &op))
  155898. {
  155899. ogg_stream_packetin (&os, &op);
  155900. for (;;)
  155901. {
  155902. if (ogg_stream_pageout (&os, &og) == 0)
  155903. break;
  155904. output->write (og.header, og.header_len);
  155905. output->write (og.body, og.body_len);
  155906. if (ogg_page_eos (&og))
  155907. break;
  155908. }
  155909. }
  155910. }
  155911. return true;
  155912. }
  155913. juce_UseDebuggingNewOperator
  155914. };
  155915. OggVorbisAudioFormat::OggVorbisAudioFormat()
  155916. : AudioFormat (TRANS (oggFormatName), (const juce_wchar**) oggExtensions)
  155917. {
  155918. }
  155919. OggVorbisAudioFormat::~OggVorbisAudioFormat()
  155920. {
  155921. }
  155922. const Array <int> OggVorbisAudioFormat::getPossibleSampleRates()
  155923. {
  155924. const int rates[] = { 22050, 32000, 44100, 48000, 0 };
  155925. return Array <int> (rates);
  155926. }
  155927. const Array <int> OggVorbisAudioFormat::getPossibleBitDepths()
  155928. {
  155929. Array <int> depths;
  155930. depths.add (32);
  155931. return depths;
  155932. }
  155933. bool OggVorbisAudioFormat::canDoStereo()
  155934. {
  155935. return true;
  155936. }
  155937. bool OggVorbisAudioFormat::canDoMono()
  155938. {
  155939. return true;
  155940. }
  155941. AudioFormatReader* OggVorbisAudioFormat::createReaderFor (InputStream* in,
  155942. const bool deleteStreamIfOpeningFails)
  155943. {
  155944. ScopedPointer <OggReader> r (new OggReader (in));
  155945. if (r->sampleRate != 0)
  155946. return r.release();
  155947. if (! deleteStreamIfOpeningFails)
  155948. r->input = 0;
  155949. return 0;
  155950. }
  155951. AudioFormatWriter* OggVorbisAudioFormat::createWriterFor (OutputStream* out,
  155952. double sampleRate,
  155953. unsigned int numChannels,
  155954. int bitsPerSample,
  155955. const StringPairArray& /*metadataValues*/,
  155956. int qualityOptionIndex)
  155957. {
  155958. ScopedPointer <OggWriter> w (new OggWriter (out,
  155959. sampleRate,
  155960. numChannels,
  155961. bitsPerSample,
  155962. qualityOptionIndex));
  155963. return w->ok ? w.release() : 0;
  155964. }
  155965. bool OggVorbisAudioFormat::isCompressed()
  155966. {
  155967. return true;
  155968. }
  155969. const StringArray OggVorbisAudioFormat::getQualityOptions()
  155970. {
  155971. StringArray s;
  155972. s.add ("Low Quality");
  155973. s.add ("Medium Quality");
  155974. s.add ("High Quality");
  155975. return s;
  155976. }
  155977. int OggVorbisAudioFormat::estimateOggFileQuality (const File& source)
  155978. {
  155979. FileInputStream* const in = source.createInputStream();
  155980. if (in != 0)
  155981. {
  155982. ScopedPointer <AudioFormatReader> r (createReaderFor (in, true));
  155983. if (r != 0)
  155984. {
  155985. const int64 numSamps = r->lengthInSamples;
  155986. r = 0;
  155987. const int64 fileNumSamps = source.getSize() / 4;
  155988. const double ratio = numSamps / (double) fileNumSamps;
  155989. if (ratio > 12.0)
  155990. return 0;
  155991. else if (ratio > 6.0)
  155992. return 1;
  155993. else
  155994. return 2;
  155995. }
  155996. }
  155997. return 1;
  155998. }
  155999. END_JUCE_NAMESPACE
  156000. #endif
  156001. /*** End of inlined file: juce_OggVorbisAudioFormat.cpp ***/
  156002. #endif
  156003. #if JUCE_BUILD_CORE && ! JUCE_ONLY_BUILD_CORE_LIBRARY // do these in the core section to help balance the sizes
  156004. /*** Start of inlined file: juce_JPEGLoader.cpp ***/
  156005. #if JUCE_MSVC
  156006. #pragma warning (push)
  156007. #endif
  156008. namespace jpeglibNamespace
  156009. {
  156010. #if JUCE_INCLUDE_JPEGLIB_CODE
  156011. #if JUCE_MINGW
  156012. typedef unsigned char boolean;
  156013. #endif
  156014. extern "C"
  156015. {
  156016. #define JPEG_INTERNALS
  156017. #undef FAR
  156018. /*** Start of inlined file: jpeglib.h ***/
  156019. #ifndef JPEGLIB_H
  156020. #define JPEGLIB_H
  156021. /*
  156022. * First we include the configuration files that record how this
  156023. * installation of the JPEG library is set up. jconfig.h can be
  156024. * generated automatically for many systems. jmorecfg.h contains
  156025. * manual configuration options that most people need not worry about.
  156026. */
  156027. #ifndef JCONFIG_INCLUDED /* in case jinclude.h already did */
  156028. /*** Start of inlined file: jconfig.h ***/
  156029. /* see jconfig.doc for explanations */
  156030. // disable all the warnings under MSVC
  156031. #ifdef _MSC_VER
  156032. #pragma warning (disable: 4996 4267 4100 4127 4702 4244)
  156033. #endif
  156034. #ifdef __BORLANDC__
  156035. #pragma warn -8057
  156036. #pragma warn -8019
  156037. #pragma warn -8004
  156038. #pragma warn -8008
  156039. #endif
  156040. #define HAVE_PROTOTYPES
  156041. #define HAVE_UNSIGNED_CHAR
  156042. #define HAVE_UNSIGNED_SHORT
  156043. /* #define void char */
  156044. /* #define const */
  156045. #undef CHAR_IS_UNSIGNED
  156046. #define HAVE_STDDEF_H
  156047. #define HAVE_STDLIB_H
  156048. #undef NEED_BSD_STRINGS
  156049. #undef NEED_SYS_TYPES_H
  156050. #undef NEED_FAR_POINTERS /* we presume a 32-bit flat memory model */
  156051. #undef NEED_SHORT_EXTERNAL_NAMES
  156052. #undef INCOMPLETE_TYPES_BROKEN
  156053. /* Define "boolean" as unsigned char, not int, per Windows custom */
  156054. #ifndef __RPCNDR_H__ /* don't conflict if rpcndr.h already read */
  156055. typedef unsigned char boolean;
  156056. #endif
  156057. #define HAVE_BOOLEAN /* prevent jmorecfg.h from redefining it */
  156058. #ifdef JPEG_INTERNALS
  156059. #undef RIGHT_SHIFT_IS_UNSIGNED
  156060. #endif /* JPEG_INTERNALS */
  156061. #ifdef JPEG_CJPEG_DJPEG
  156062. #define BMP_SUPPORTED /* BMP image file format */
  156063. #define GIF_SUPPORTED /* GIF image file format */
  156064. #define PPM_SUPPORTED /* PBMPLUS PPM/PGM image file format */
  156065. #undef RLE_SUPPORTED /* Utah RLE image file format */
  156066. #define TARGA_SUPPORTED /* Targa image file format */
  156067. #define TWO_FILE_COMMANDLINE /* optional */
  156068. #define USE_SETMODE /* Microsoft has setmode() */
  156069. #undef NEED_SIGNAL_CATCHER
  156070. #undef DONT_USE_B_MODE
  156071. #undef PROGRESS_REPORT /* optional */
  156072. #endif /* JPEG_CJPEG_DJPEG */
  156073. /*** End of inlined file: jconfig.h ***/
  156074. /* widely used configuration options */
  156075. #endif
  156076. /*** Start of inlined file: jmorecfg.h ***/
  156077. /*
  156078. * Define BITS_IN_JSAMPLE as either
  156079. * 8 for 8-bit sample values (the usual setting)
  156080. * 12 for 12-bit sample values
  156081. * Only 8 and 12 are legal data precisions for lossy JPEG according to the
  156082. * JPEG standard, and the IJG code does not support anything else!
  156083. * We do not support run-time selection of data precision, sorry.
  156084. */
  156085. #define BITS_IN_JSAMPLE 8 /* use 8 or 12 */
  156086. /*
  156087. * Maximum number of components (color channels) allowed in JPEG image.
  156088. * To meet the letter of the JPEG spec, set this to 255. However, darn
  156089. * few applications need more than 4 channels (maybe 5 for CMYK + alpha
  156090. * mask). We recommend 10 as a reasonable compromise; use 4 if you are
  156091. * really short on memory. (Each allowed component costs a hundred or so
  156092. * bytes of storage, whether actually used in an image or not.)
  156093. */
  156094. #define MAX_COMPONENTS 10 /* maximum number of image components */
  156095. /*
  156096. * Basic data types.
  156097. * You may need to change these if you have a machine with unusual data
  156098. * type sizes; for example, "char" not 8 bits, "short" not 16 bits,
  156099. * or "long" not 32 bits. We don't care whether "int" is 16 or 32 bits,
  156100. * but it had better be at least 16.
  156101. */
  156102. /* Representation of a single sample (pixel element value).
  156103. * We frequently allocate large arrays of these, so it's important to keep
  156104. * them small. But if you have memory to burn and access to char or short
  156105. * arrays is very slow on your hardware, you might want to change these.
  156106. */
  156107. #if BITS_IN_JSAMPLE == 8
  156108. /* JSAMPLE should be the smallest type that will hold the values 0..255.
  156109. * You can use a signed char by having GETJSAMPLE mask it with 0xFF.
  156110. */
  156111. #ifdef HAVE_UNSIGNED_CHAR
  156112. typedef unsigned char JSAMPLE;
  156113. #define GETJSAMPLE(value) ((int) (value))
  156114. #else /* not HAVE_UNSIGNED_CHAR */
  156115. typedef char JSAMPLE;
  156116. #ifdef CHAR_IS_UNSIGNED
  156117. #define GETJSAMPLE(value) ((int) (value))
  156118. #else
  156119. #define GETJSAMPLE(value) ((int) (value) & 0xFF)
  156120. #endif /* CHAR_IS_UNSIGNED */
  156121. #endif /* HAVE_UNSIGNED_CHAR */
  156122. #define MAXJSAMPLE 255
  156123. #define CENTERJSAMPLE 128
  156124. #endif /* BITS_IN_JSAMPLE == 8 */
  156125. #if BITS_IN_JSAMPLE == 12
  156126. /* JSAMPLE should be the smallest type that will hold the values 0..4095.
  156127. * On nearly all machines "short" will do nicely.
  156128. */
  156129. typedef short JSAMPLE;
  156130. #define GETJSAMPLE(value) ((int) (value))
  156131. #define MAXJSAMPLE 4095
  156132. #define CENTERJSAMPLE 2048
  156133. #endif /* BITS_IN_JSAMPLE == 12 */
  156134. /* Representation of a DCT frequency coefficient.
  156135. * This should be a signed value of at least 16 bits; "short" is usually OK.
  156136. * Again, we allocate large arrays of these, but you can change to int
  156137. * if you have memory to burn and "short" is really slow.
  156138. */
  156139. typedef short JCOEF;
  156140. /* Compressed datastreams are represented as arrays of JOCTET.
  156141. * These must be EXACTLY 8 bits wide, at least once they are written to
  156142. * external storage. Note that when using the stdio data source/destination
  156143. * managers, this is also the data type passed to fread/fwrite.
  156144. */
  156145. #ifdef HAVE_UNSIGNED_CHAR
  156146. typedef unsigned char JOCTET;
  156147. #define GETJOCTET(value) (value)
  156148. #else /* not HAVE_UNSIGNED_CHAR */
  156149. typedef char JOCTET;
  156150. #ifdef CHAR_IS_UNSIGNED
  156151. #define GETJOCTET(value) (value)
  156152. #else
  156153. #define GETJOCTET(value) ((value) & 0xFF)
  156154. #endif /* CHAR_IS_UNSIGNED */
  156155. #endif /* HAVE_UNSIGNED_CHAR */
  156156. /* These typedefs are used for various table entries and so forth.
  156157. * They must be at least as wide as specified; but making them too big
  156158. * won't cost a huge amount of memory, so we don't provide special
  156159. * extraction code like we did for JSAMPLE. (In other words, these
  156160. * typedefs live at a different point on the speed/space tradeoff curve.)
  156161. */
  156162. /* UINT8 must hold at least the values 0..255. */
  156163. #ifdef HAVE_UNSIGNED_CHAR
  156164. typedef unsigned char UINT8;
  156165. #else /* not HAVE_UNSIGNED_CHAR */
  156166. #ifdef CHAR_IS_UNSIGNED
  156167. typedef char UINT8;
  156168. #else /* not CHAR_IS_UNSIGNED */
  156169. typedef short UINT8;
  156170. #endif /* CHAR_IS_UNSIGNED */
  156171. #endif /* HAVE_UNSIGNED_CHAR */
  156172. /* UINT16 must hold at least the values 0..65535. */
  156173. #ifdef HAVE_UNSIGNED_SHORT
  156174. typedef unsigned short UINT16;
  156175. #else /* not HAVE_UNSIGNED_SHORT */
  156176. typedef unsigned int UINT16;
  156177. #endif /* HAVE_UNSIGNED_SHORT */
  156178. /* INT16 must hold at least the values -32768..32767. */
  156179. #ifndef XMD_H /* X11/xmd.h correctly defines INT16 */
  156180. typedef short INT16;
  156181. #endif
  156182. /* INT32 must hold at least signed 32-bit values. */
  156183. #ifndef XMD_H /* X11/xmd.h correctly defines INT32 */
  156184. typedef long INT32;
  156185. #endif
  156186. /* Datatype used for image dimensions. The JPEG standard only supports
  156187. * images up to 64K*64K due to 16-bit fields in SOF markers. Therefore
  156188. * "unsigned int" is sufficient on all machines. However, if you need to
  156189. * handle larger images and you don't mind deviating from the spec, you
  156190. * can change this datatype.
  156191. */
  156192. typedef unsigned int JDIMENSION;
  156193. #define JPEG_MAX_DIMENSION 65500L /* a tad under 64K to prevent overflows */
  156194. /* These macros are used in all function definitions and extern declarations.
  156195. * You could modify them if you need to change function linkage conventions;
  156196. * in particular, you'll need to do that to make the library a Windows DLL.
  156197. * Another application is to make all functions global for use with debuggers
  156198. * or code profilers that require it.
  156199. */
  156200. /* a function called through method pointers: */
  156201. #define METHODDEF(type) static type
  156202. /* a function used only in its module: */
  156203. #define LOCAL(type) static type
  156204. /* a function referenced thru EXTERNs: */
  156205. #define GLOBAL(type) type
  156206. /* a reference to a GLOBAL function: */
  156207. #define EXTERN(type) extern type
  156208. /* This macro is used to declare a "method", that is, a function pointer.
  156209. * We want to supply prototype parameters if the compiler can cope.
  156210. * Note that the arglist parameter must be parenthesized!
  156211. * Again, you can customize this if you need special linkage keywords.
  156212. */
  156213. #ifdef HAVE_PROTOTYPES
  156214. #define JMETHOD(type,methodname,arglist) type (*methodname) arglist
  156215. #else
  156216. #define JMETHOD(type,methodname,arglist) type (*methodname) ()
  156217. #endif
  156218. /* Here is the pseudo-keyword for declaring pointers that must be "far"
  156219. * on 80x86 machines. Most of the specialized coding for 80x86 is handled
  156220. * by just saying "FAR *" where such a pointer is needed. In a few places
  156221. * explicit coding is needed; see uses of the NEED_FAR_POINTERS symbol.
  156222. */
  156223. #ifdef NEED_FAR_POINTERS
  156224. #define FAR far
  156225. #else
  156226. #define FAR
  156227. #endif
  156228. /*
  156229. * On a few systems, type boolean and/or its values FALSE, TRUE may appear
  156230. * in standard header files. Or you may have conflicts with application-
  156231. * specific header files that you want to include together with these files.
  156232. * Defining HAVE_BOOLEAN before including jpeglib.h should make it work.
  156233. */
  156234. #ifndef HAVE_BOOLEAN
  156235. typedef int boolean;
  156236. #endif
  156237. #ifndef FALSE /* in case these macros already exist */
  156238. #define FALSE 0 /* values of boolean */
  156239. #endif
  156240. #ifndef TRUE
  156241. #define TRUE 1
  156242. #endif
  156243. /*
  156244. * The remaining options affect code selection within the JPEG library,
  156245. * but they don't need to be visible to most applications using the library.
  156246. * To minimize application namespace pollution, the symbols won't be
  156247. * defined unless JPEG_INTERNALS or JPEG_INTERNAL_OPTIONS has been defined.
  156248. */
  156249. #ifdef JPEG_INTERNALS
  156250. #define JPEG_INTERNAL_OPTIONS
  156251. #endif
  156252. #ifdef JPEG_INTERNAL_OPTIONS
  156253. /*
  156254. * These defines indicate whether to include various optional functions.
  156255. * Undefining some of these symbols will produce a smaller but less capable
  156256. * library. Note that you can leave certain source files out of the
  156257. * compilation/linking process if you've #undef'd the corresponding symbols.
  156258. * (You may HAVE to do that if your compiler doesn't like null source files.)
  156259. */
  156260. /* Arithmetic coding is unsupported for legal reasons. Complaints to IBM. */
  156261. /* Capability options common to encoder and decoder: */
  156262. #define DCT_ISLOW_SUPPORTED /* slow but accurate integer algorithm */
  156263. #define DCT_IFAST_SUPPORTED /* faster, less accurate integer method */
  156264. #define DCT_FLOAT_SUPPORTED /* floating-point: accurate, fast on fast HW */
  156265. /* Encoder capability options: */
  156266. #undef C_ARITH_CODING_SUPPORTED /* Arithmetic coding back end? */
  156267. #define C_MULTISCAN_FILES_SUPPORTED /* Multiple-scan JPEG files? */
  156268. #define C_PROGRESSIVE_SUPPORTED /* Progressive JPEG? (Requires MULTISCAN)*/
  156269. #define ENTROPY_OPT_SUPPORTED /* Optimization of entropy coding parms? */
  156270. /* Note: if you selected 12-bit data precision, it is dangerous to turn off
  156271. * ENTROPY_OPT_SUPPORTED. The standard Huffman tables are only good for 8-bit
  156272. * precision, so jchuff.c normally uses entropy optimization to compute
  156273. * usable tables for higher precision. If you don't want to do optimization,
  156274. * you'll have to supply different default Huffman tables.
  156275. * The exact same statements apply for progressive JPEG: the default tables
  156276. * don't work for progressive mode. (This may get fixed, however.)
  156277. */
  156278. #define INPUT_SMOOTHING_SUPPORTED /* Input image smoothing option? */
  156279. /* Decoder capability options: */
  156280. #undef D_ARITH_CODING_SUPPORTED /* Arithmetic coding back end? */
  156281. #define D_MULTISCAN_FILES_SUPPORTED /* Multiple-scan JPEG files? */
  156282. #define D_PROGRESSIVE_SUPPORTED /* Progressive JPEG? (Requires MULTISCAN)*/
  156283. #define SAVE_MARKERS_SUPPORTED /* jpeg_save_markers() needed? */
  156284. #define BLOCK_SMOOTHING_SUPPORTED /* Block smoothing? (Progressive only) */
  156285. #define IDCT_SCALING_SUPPORTED /* Output rescaling via IDCT? */
  156286. #undef UPSAMPLE_SCALING_SUPPORTED /* Output rescaling at upsample stage? */
  156287. #define UPSAMPLE_MERGING_SUPPORTED /* Fast path for sloppy upsampling? */
  156288. #define QUANT_1PASS_SUPPORTED /* 1-pass color quantization? */
  156289. #define QUANT_2PASS_SUPPORTED /* 2-pass color quantization? */
  156290. /* more capability options later, no doubt */
  156291. /*
  156292. * Ordering of RGB data in scanlines passed to or from the application.
  156293. * If your application wants to deal with data in the order B,G,R, just
  156294. * change these macros. You can also deal with formats such as R,G,B,X
  156295. * (one extra byte per pixel) by changing RGB_PIXELSIZE. Note that changing
  156296. * the offsets will also change the order in which colormap data is organized.
  156297. * RESTRICTIONS:
  156298. * 1. The sample applications cjpeg,djpeg do NOT support modified RGB formats.
  156299. * 2. These macros only affect RGB<=>YCbCr color conversion, so they are not
  156300. * useful if you are using JPEG color spaces other than YCbCr or grayscale.
  156301. * 3. The color quantizer modules will not behave desirably if RGB_PIXELSIZE
  156302. * is not 3 (they don't understand about dummy color components!). So you
  156303. * can't use color quantization if you change that value.
  156304. */
  156305. #define RGB_RED 0 /* Offset of Red in an RGB scanline element */
  156306. #define RGB_GREEN 1 /* Offset of Green */
  156307. #define RGB_BLUE 2 /* Offset of Blue */
  156308. #define RGB_PIXELSIZE 3 /* JSAMPLEs per RGB scanline element */
  156309. /* Definitions for speed-related optimizations. */
  156310. /* If your compiler supports inline functions, define INLINE
  156311. * as the inline keyword; otherwise define it as empty.
  156312. */
  156313. #ifndef INLINE
  156314. #ifdef __GNUC__ /* for instance, GNU C knows about inline */
  156315. #define INLINE __inline__
  156316. #endif
  156317. #ifndef INLINE
  156318. #define INLINE /* default is to define it as empty */
  156319. #endif
  156320. #endif
  156321. /* On some machines (notably 68000 series) "int" is 32 bits, but multiplying
  156322. * two 16-bit shorts is faster than multiplying two ints. Define MULTIPLIER
  156323. * as short on such a machine. MULTIPLIER must be at least 16 bits wide.
  156324. */
  156325. #ifndef MULTIPLIER
  156326. #define MULTIPLIER int /* type for fastest integer multiply */
  156327. #endif
  156328. /* FAST_FLOAT should be either float or double, whichever is done faster
  156329. * by your compiler. (Note that this type is only used in the floating point
  156330. * DCT routines, so it only matters if you've defined DCT_FLOAT_SUPPORTED.)
  156331. * Typically, float is faster in ANSI C compilers, while double is faster in
  156332. * pre-ANSI compilers (because they insist on converting to double anyway).
  156333. * The code below therefore chooses float if we have ANSI-style prototypes.
  156334. */
  156335. #ifndef FAST_FLOAT
  156336. #ifdef HAVE_PROTOTYPES
  156337. #define FAST_FLOAT float
  156338. #else
  156339. #define FAST_FLOAT double
  156340. #endif
  156341. #endif
  156342. #endif /* JPEG_INTERNAL_OPTIONS */
  156343. /*** End of inlined file: jmorecfg.h ***/
  156344. /* seldom changed options */
  156345. /* Version ID for the JPEG library.
  156346. * Might be useful for tests like "#if JPEG_LIB_VERSION >= 60".
  156347. */
  156348. #define JPEG_LIB_VERSION 62 /* Version 6b */
  156349. /* Various constants determining the sizes of things.
  156350. * All of these are specified by the JPEG standard, so don't change them
  156351. * if you want to be compatible.
  156352. */
  156353. #define DCTSIZE 8 /* The basic DCT block is 8x8 samples */
  156354. #define DCTSIZE2 64 /* DCTSIZE squared; # of elements in a block */
  156355. #define NUM_QUANT_TBLS 4 /* Quantization tables are numbered 0..3 */
  156356. #define NUM_HUFF_TBLS 4 /* Huffman tables are numbered 0..3 */
  156357. #define NUM_ARITH_TBLS 16 /* Arith-coding tables are numbered 0..15 */
  156358. #define MAX_COMPS_IN_SCAN 4 /* JPEG limit on # of components in one scan */
  156359. #define MAX_SAMP_FACTOR 4 /* JPEG limit on sampling factors */
  156360. /* Unfortunately, some bozo at Adobe saw no reason to be bound by the standard;
  156361. * the PostScript DCT filter can emit files with many more than 10 blocks/MCU.
  156362. * If you happen to run across such a file, you can up D_MAX_BLOCKS_IN_MCU
  156363. * to handle it. We even let you do this from the jconfig.h file. However,
  156364. * we strongly discourage changing C_MAX_BLOCKS_IN_MCU; just because Adobe
  156365. * sometimes emits noncompliant files doesn't mean you should too.
  156366. */
  156367. #define C_MAX_BLOCKS_IN_MCU 10 /* compressor's limit on blocks per MCU */
  156368. #ifndef D_MAX_BLOCKS_IN_MCU
  156369. #define D_MAX_BLOCKS_IN_MCU 10 /* decompressor's limit on blocks per MCU */
  156370. #endif
  156371. /* Data structures for images (arrays of samples and of DCT coefficients).
  156372. * On 80x86 machines, the image arrays are too big for near pointers,
  156373. * but the pointer arrays can fit in near memory.
  156374. */
  156375. typedef JSAMPLE FAR *JSAMPROW; /* ptr to one image row of pixel samples. */
  156376. typedef JSAMPROW *JSAMPARRAY; /* ptr to some rows (a 2-D sample array) */
  156377. typedef JSAMPARRAY *JSAMPIMAGE; /* a 3-D sample array: top index is color */
  156378. typedef JCOEF JBLOCK[DCTSIZE2]; /* one block of coefficients */
  156379. typedef JBLOCK FAR *JBLOCKROW; /* pointer to one row of coefficient blocks */
  156380. typedef JBLOCKROW *JBLOCKARRAY; /* a 2-D array of coefficient blocks */
  156381. typedef JBLOCKARRAY *JBLOCKIMAGE; /* a 3-D array of coefficient blocks */
  156382. typedef JCOEF FAR *JCOEFPTR; /* useful in a couple of places */
  156383. /* Types for JPEG compression parameters and working tables. */
  156384. /* DCT coefficient quantization tables. */
  156385. typedef struct {
  156386. /* This array gives the coefficient quantizers in natural array order
  156387. * (not the zigzag order in which they are stored in a JPEG DQT marker).
  156388. * CAUTION: IJG versions prior to v6a kept this array in zigzag order.
  156389. */
  156390. UINT16 quantval[DCTSIZE2]; /* quantization step for each coefficient */
  156391. /* This field is used only during compression. It's initialized FALSE when
  156392. * the table is created, and set TRUE when it's been output to the file.
  156393. * You could suppress output of a table by setting this to TRUE.
  156394. * (See jpeg_suppress_tables for an example.)
  156395. */
  156396. boolean sent_table; /* TRUE when table has been output */
  156397. } JQUANT_TBL;
  156398. /* Huffman coding tables. */
  156399. typedef struct {
  156400. /* These two fields directly represent the contents of a JPEG DHT marker */
  156401. UINT8 bits[17]; /* bits[k] = # of symbols with codes of */
  156402. /* length k bits; bits[0] is unused */
  156403. UINT8 huffval[256]; /* The symbols, in order of incr code length */
  156404. /* This field is used only during compression. It's initialized FALSE when
  156405. * the table is created, and set TRUE when it's been output to the file.
  156406. * You could suppress output of a table by setting this to TRUE.
  156407. * (See jpeg_suppress_tables for an example.)
  156408. */
  156409. boolean sent_table; /* TRUE when table has been output */
  156410. } JHUFF_TBL;
  156411. /* Basic info about one component (color channel). */
  156412. typedef struct {
  156413. /* These values are fixed over the whole image. */
  156414. /* For compression, they must be supplied by parameter setup; */
  156415. /* for decompression, they are read from the SOF marker. */
  156416. int component_id; /* identifier for this component (0..255) */
  156417. int component_index; /* its index in SOF or cinfo->comp_info[] */
  156418. int h_samp_factor; /* horizontal sampling factor (1..4) */
  156419. int v_samp_factor; /* vertical sampling factor (1..4) */
  156420. int quant_tbl_no; /* quantization table selector (0..3) */
  156421. /* These values may vary between scans. */
  156422. /* For compression, they must be supplied by parameter setup; */
  156423. /* for decompression, they are read from the SOS marker. */
  156424. /* The decompressor output side may not use these variables. */
  156425. int dc_tbl_no; /* DC entropy table selector (0..3) */
  156426. int ac_tbl_no; /* AC entropy table selector (0..3) */
  156427. /* Remaining fields should be treated as private by applications. */
  156428. /* These values are computed during compression or decompression startup: */
  156429. /* Component's size in DCT blocks.
  156430. * Any dummy blocks added to complete an MCU are not counted; therefore
  156431. * these values do not depend on whether a scan is interleaved or not.
  156432. */
  156433. JDIMENSION width_in_blocks;
  156434. JDIMENSION height_in_blocks;
  156435. /* Size of a DCT block in samples. Always DCTSIZE for compression.
  156436. * For decompression this is the size of the output from one DCT block,
  156437. * reflecting any scaling we choose to apply during the IDCT step.
  156438. * Values of 1,2,4,8 are likely to be supported. Note that different
  156439. * components may receive different IDCT scalings.
  156440. */
  156441. int DCT_scaled_size;
  156442. /* The downsampled dimensions are the component's actual, unpadded number
  156443. * of samples at the main buffer (preprocessing/compression interface), thus
  156444. * downsampled_width = ceil(image_width * Hi/Hmax)
  156445. * and similarly for height. For decompression, IDCT scaling is included, so
  156446. * downsampled_width = ceil(image_width * Hi/Hmax * DCT_scaled_size/DCTSIZE)
  156447. */
  156448. JDIMENSION downsampled_width; /* actual width in samples */
  156449. JDIMENSION downsampled_height; /* actual height in samples */
  156450. /* This flag is used only for decompression. In cases where some of the
  156451. * components will be ignored (eg grayscale output from YCbCr image),
  156452. * we can skip most computations for the unused components.
  156453. */
  156454. boolean component_needed; /* do we need the value of this component? */
  156455. /* These values are computed before starting a scan of the component. */
  156456. /* The decompressor output side may not use these variables. */
  156457. int MCU_width; /* number of blocks per MCU, horizontally */
  156458. int MCU_height; /* number of blocks per MCU, vertically */
  156459. int MCU_blocks; /* MCU_width * MCU_height */
  156460. int MCU_sample_width; /* MCU width in samples, MCU_width*DCT_scaled_size */
  156461. int last_col_width; /* # of non-dummy blocks across in last MCU */
  156462. int last_row_height; /* # of non-dummy blocks down in last MCU */
  156463. /* Saved quantization table for component; NULL if none yet saved.
  156464. * See jdinput.c comments about the need for this information.
  156465. * This field is currently used only for decompression.
  156466. */
  156467. JQUANT_TBL * quant_table;
  156468. /* Private per-component storage for DCT or IDCT subsystem. */
  156469. void * dct_table;
  156470. } jpeg_component_info;
  156471. /* The script for encoding a multiple-scan file is an array of these: */
  156472. typedef struct {
  156473. int comps_in_scan; /* number of components encoded in this scan */
  156474. int component_index[MAX_COMPS_IN_SCAN]; /* their SOF/comp_info[] indexes */
  156475. int Ss, Se; /* progressive JPEG spectral selection parms */
  156476. int Ah, Al; /* progressive JPEG successive approx. parms */
  156477. } jpeg_scan_info;
  156478. /* The decompressor can save APPn and COM markers in a list of these: */
  156479. typedef struct jpeg_marker_struct FAR * jpeg_saved_marker_ptr;
  156480. struct jpeg_marker_struct {
  156481. jpeg_saved_marker_ptr next; /* next in list, or NULL */
  156482. UINT8 marker; /* marker code: JPEG_COM, or JPEG_APP0+n */
  156483. unsigned int original_length; /* # bytes of data in the file */
  156484. unsigned int data_length; /* # bytes of data saved at data[] */
  156485. JOCTET FAR * data; /* the data contained in the marker */
  156486. /* the marker length word is not counted in data_length or original_length */
  156487. };
  156488. /* Known color spaces. */
  156489. typedef enum {
  156490. JCS_UNKNOWN, /* error/unspecified */
  156491. JCS_GRAYSCALE, /* monochrome */
  156492. JCS_RGB, /* red/green/blue */
  156493. JCS_YCbCr, /* Y/Cb/Cr (also known as YUV) */
  156494. JCS_CMYK, /* C/M/Y/K */
  156495. JCS_YCCK /* Y/Cb/Cr/K */
  156496. } J_COLOR_SPACE;
  156497. /* DCT/IDCT algorithm options. */
  156498. typedef enum {
  156499. JDCT_ISLOW, /* slow but accurate integer algorithm */
  156500. JDCT_IFAST, /* faster, less accurate integer method */
  156501. JDCT_FLOAT /* floating-point: accurate, fast on fast HW */
  156502. } J_DCT_METHOD;
  156503. #ifndef JDCT_DEFAULT /* may be overridden in jconfig.h */
  156504. #define JDCT_DEFAULT JDCT_ISLOW
  156505. #endif
  156506. #ifndef JDCT_FASTEST /* may be overridden in jconfig.h */
  156507. #define JDCT_FASTEST JDCT_IFAST
  156508. #endif
  156509. /* Dithering options for decompression. */
  156510. typedef enum {
  156511. JDITHER_NONE, /* no dithering */
  156512. JDITHER_ORDERED, /* simple ordered dither */
  156513. JDITHER_FS /* Floyd-Steinberg error diffusion dither */
  156514. } J_DITHER_MODE;
  156515. /* Common fields between JPEG compression and decompression master structs. */
  156516. #define jpeg_common_fields \
  156517. struct jpeg_error_mgr * err; /* Error handler module */\
  156518. struct jpeg_memory_mgr * mem; /* Memory manager module */\
  156519. struct jpeg_progress_mgr * progress; /* Progress monitor, or NULL if none */\
  156520. void * client_data; /* Available for use by application */\
  156521. boolean is_decompressor; /* So common code can tell which is which */\
  156522. int global_state /* For checking call sequence validity */
  156523. /* Routines that are to be used by both halves of the library are declared
  156524. * to receive a pointer to this structure. There are no actual instances of
  156525. * jpeg_common_struct, only of jpeg_compress_struct and jpeg_decompress_struct.
  156526. */
  156527. struct jpeg_common_struct {
  156528. jpeg_common_fields; /* Fields common to both master struct types */
  156529. /* Additional fields follow in an actual jpeg_compress_struct or
  156530. * jpeg_decompress_struct. All three structs must agree on these
  156531. * initial fields! (This would be a lot cleaner in C++.)
  156532. */
  156533. };
  156534. typedef struct jpeg_common_struct * j_common_ptr;
  156535. typedef struct jpeg_compress_struct * j_compress_ptr;
  156536. typedef struct jpeg_decompress_struct * j_decompress_ptr;
  156537. /* Master record for a compression instance */
  156538. struct jpeg_compress_struct {
  156539. jpeg_common_fields; /* Fields shared with jpeg_decompress_struct */
  156540. /* Destination for compressed data */
  156541. struct jpeg_destination_mgr * dest;
  156542. /* Description of source image --- these fields must be filled in by
  156543. * outer application before starting compression. in_color_space must
  156544. * be correct before you can even call jpeg_set_defaults().
  156545. */
  156546. JDIMENSION image_width; /* input image width */
  156547. JDIMENSION image_height; /* input image height */
  156548. int input_components; /* # of color components in input image */
  156549. J_COLOR_SPACE in_color_space; /* colorspace of input image */
  156550. double input_gamma; /* image gamma of input image */
  156551. /* Compression parameters --- these fields must be set before calling
  156552. * jpeg_start_compress(). We recommend calling jpeg_set_defaults() to
  156553. * initialize everything to reasonable defaults, then changing anything
  156554. * the application specifically wants to change. That way you won't get
  156555. * burnt when new parameters are added. Also note that there are several
  156556. * helper routines to simplify changing parameters.
  156557. */
  156558. int data_precision; /* bits of precision in image data */
  156559. int num_components; /* # of color components in JPEG image */
  156560. J_COLOR_SPACE jpeg_color_space; /* colorspace of JPEG image */
  156561. jpeg_component_info * comp_info;
  156562. /* comp_info[i] describes component that appears i'th in SOF */
  156563. JQUANT_TBL * quant_tbl_ptrs[NUM_QUANT_TBLS];
  156564. /* ptrs to coefficient quantization tables, or NULL if not defined */
  156565. JHUFF_TBL * dc_huff_tbl_ptrs[NUM_HUFF_TBLS];
  156566. JHUFF_TBL * ac_huff_tbl_ptrs[NUM_HUFF_TBLS];
  156567. /* ptrs to Huffman coding tables, or NULL if not defined */
  156568. UINT8 arith_dc_L[NUM_ARITH_TBLS]; /* L values for DC arith-coding tables */
  156569. UINT8 arith_dc_U[NUM_ARITH_TBLS]; /* U values for DC arith-coding tables */
  156570. UINT8 arith_ac_K[NUM_ARITH_TBLS]; /* Kx values for AC arith-coding tables */
  156571. int num_scans; /* # of entries in scan_info array */
  156572. const jpeg_scan_info * scan_info; /* script for multi-scan file, or NULL */
  156573. /* The default value of scan_info is NULL, which causes a single-scan
  156574. * sequential JPEG file to be emitted. To create a multi-scan file,
  156575. * set num_scans and scan_info to point to an array of scan definitions.
  156576. */
  156577. boolean raw_data_in; /* TRUE=caller supplies downsampled data */
  156578. boolean arith_code; /* TRUE=arithmetic coding, FALSE=Huffman */
  156579. boolean optimize_coding; /* TRUE=optimize entropy encoding parms */
  156580. boolean CCIR601_sampling; /* TRUE=first samples are cosited */
  156581. int smoothing_factor; /* 1..100, or 0 for no input smoothing */
  156582. J_DCT_METHOD dct_method; /* DCT algorithm selector */
  156583. /* The restart interval can be specified in absolute MCUs by setting
  156584. * restart_interval, or in MCU rows by setting restart_in_rows
  156585. * (in which case the correct restart_interval will be figured
  156586. * for each scan).
  156587. */
  156588. unsigned int restart_interval; /* MCUs per restart, or 0 for no restart */
  156589. int restart_in_rows; /* if > 0, MCU rows per restart interval */
  156590. /* Parameters controlling emission of special markers. */
  156591. boolean write_JFIF_header; /* should a JFIF marker be written? */
  156592. UINT8 JFIF_major_version; /* What to write for the JFIF version number */
  156593. UINT8 JFIF_minor_version;
  156594. /* These three values are not used by the JPEG code, merely copied */
  156595. /* into the JFIF APP0 marker. density_unit can be 0 for unknown, */
  156596. /* 1 for dots/inch, or 2 for dots/cm. Note that the pixel aspect */
  156597. /* ratio is defined by X_density/Y_density even when density_unit=0. */
  156598. UINT8 density_unit; /* JFIF code for pixel size units */
  156599. UINT16 X_density; /* Horizontal pixel density */
  156600. UINT16 Y_density; /* Vertical pixel density */
  156601. boolean write_Adobe_marker; /* should an Adobe marker be written? */
  156602. /* State variable: index of next scanline to be written to
  156603. * jpeg_write_scanlines(). Application may use this to control its
  156604. * processing loop, e.g., "while (next_scanline < image_height)".
  156605. */
  156606. JDIMENSION next_scanline; /* 0 .. image_height-1 */
  156607. /* Remaining fields are known throughout compressor, but generally
  156608. * should not be touched by a surrounding application.
  156609. */
  156610. /*
  156611. * These fields are computed during compression startup
  156612. */
  156613. boolean progressive_mode; /* TRUE if scan script uses progressive mode */
  156614. int max_h_samp_factor; /* largest h_samp_factor */
  156615. int max_v_samp_factor; /* largest v_samp_factor */
  156616. JDIMENSION total_iMCU_rows; /* # of iMCU rows to be input to coef ctlr */
  156617. /* The coefficient controller receives data in units of MCU rows as defined
  156618. * for fully interleaved scans (whether the JPEG file is interleaved or not).
  156619. * There are v_samp_factor * DCTSIZE sample rows of each component in an
  156620. * "iMCU" (interleaved MCU) row.
  156621. */
  156622. /*
  156623. * These fields are valid during any one scan.
  156624. * They describe the components and MCUs actually appearing in the scan.
  156625. */
  156626. int comps_in_scan; /* # of JPEG components in this scan */
  156627. jpeg_component_info * cur_comp_info[MAX_COMPS_IN_SCAN];
  156628. /* *cur_comp_info[i] describes component that appears i'th in SOS */
  156629. JDIMENSION MCUs_per_row; /* # of MCUs across the image */
  156630. JDIMENSION MCU_rows_in_scan; /* # of MCU rows in the image */
  156631. int blocks_in_MCU; /* # of DCT blocks per MCU */
  156632. int MCU_membership[C_MAX_BLOCKS_IN_MCU];
  156633. /* MCU_membership[i] is index in cur_comp_info of component owning */
  156634. /* i'th block in an MCU */
  156635. int Ss, Se, Ah, Al; /* progressive JPEG parameters for scan */
  156636. /*
  156637. * Links to compression subobjects (methods and private variables of modules)
  156638. */
  156639. struct jpeg_comp_master * master;
  156640. struct jpeg_c_main_controller * main;
  156641. struct jpeg_c_prep_controller * prep;
  156642. struct jpeg_c_coef_controller * coef;
  156643. struct jpeg_marker_writer * marker;
  156644. struct jpeg_color_converter * cconvert;
  156645. struct jpeg_downsampler * downsample;
  156646. struct jpeg_forward_dct * fdct;
  156647. struct jpeg_entropy_encoder * entropy;
  156648. jpeg_scan_info * script_space; /* workspace for jpeg_simple_progression */
  156649. int script_space_size;
  156650. };
  156651. /* Master record for a decompression instance */
  156652. struct jpeg_decompress_struct {
  156653. jpeg_common_fields; /* Fields shared with jpeg_compress_struct */
  156654. /* Source of compressed data */
  156655. struct jpeg_source_mgr * src;
  156656. /* Basic description of image --- filled in by jpeg_read_header(). */
  156657. /* Application may inspect these values to decide how to process image. */
  156658. JDIMENSION image_width; /* nominal image width (from SOF marker) */
  156659. JDIMENSION image_height; /* nominal image height */
  156660. int num_components; /* # of color components in JPEG image */
  156661. J_COLOR_SPACE jpeg_color_space; /* colorspace of JPEG image */
  156662. /* Decompression processing parameters --- these fields must be set before
  156663. * calling jpeg_start_decompress(). Note that jpeg_read_header() initializes
  156664. * them to default values.
  156665. */
  156666. J_COLOR_SPACE out_color_space; /* colorspace for output */
  156667. unsigned int scale_num, scale_denom; /* fraction by which to scale image */
  156668. double output_gamma; /* image gamma wanted in output */
  156669. boolean buffered_image; /* TRUE=multiple output passes */
  156670. boolean raw_data_out; /* TRUE=downsampled data wanted */
  156671. J_DCT_METHOD dct_method; /* IDCT algorithm selector */
  156672. boolean do_fancy_upsampling; /* TRUE=apply fancy upsampling */
  156673. boolean do_block_smoothing; /* TRUE=apply interblock smoothing */
  156674. boolean quantize_colors; /* TRUE=colormapped output wanted */
  156675. /* the following are ignored if not quantize_colors: */
  156676. J_DITHER_MODE dither_mode; /* type of color dithering to use */
  156677. boolean two_pass_quantize; /* TRUE=use two-pass color quantization */
  156678. int desired_number_of_colors; /* max # colors to use in created colormap */
  156679. /* these are significant only in buffered-image mode: */
  156680. boolean enable_1pass_quant; /* enable future use of 1-pass quantizer */
  156681. boolean enable_external_quant;/* enable future use of external colormap */
  156682. boolean enable_2pass_quant; /* enable future use of 2-pass quantizer */
  156683. /* Description of actual output image that will be returned to application.
  156684. * These fields are computed by jpeg_start_decompress().
  156685. * You can also use jpeg_calc_output_dimensions() to determine these values
  156686. * in advance of calling jpeg_start_decompress().
  156687. */
  156688. JDIMENSION output_width; /* scaled image width */
  156689. JDIMENSION output_height; /* scaled image height */
  156690. int out_color_components; /* # of color components in out_color_space */
  156691. int output_components; /* # of color components returned */
  156692. /* output_components is 1 (a colormap index) when quantizing colors;
  156693. * otherwise it equals out_color_components.
  156694. */
  156695. int rec_outbuf_height; /* min recommended height of scanline buffer */
  156696. /* If the buffer passed to jpeg_read_scanlines() is less than this many rows
  156697. * high, space and time will be wasted due to unnecessary data copying.
  156698. * Usually rec_outbuf_height will be 1 or 2, at most 4.
  156699. */
  156700. /* When quantizing colors, the output colormap is described by these fields.
  156701. * The application can supply a colormap by setting colormap non-NULL before
  156702. * calling jpeg_start_decompress; otherwise a colormap is created during
  156703. * jpeg_start_decompress or jpeg_start_output.
  156704. * The map has out_color_components rows and actual_number_of_colors columns.
  156705. */
  156706. int actual_number_of_colors; /* number of entries in use */
  156707. JSAMPARRAY colormap; /* The color map as a 2-D pixel array */
  156708. /* State variables: these variables indicate the progress of decompression.
  156709. * The application may examine these but must not modify them.
  156710. */
  156711. /* Row index of next scanline to be read from jpeg_read_scanlines().
  156712. * Application may use this to control its processing loop, e.g.,
  156713. * "while (output_scanline < output_height)".
  156714. */
  156715. JDIMENSION output_scanline; /* 0 .. output_height-1 */
  156716. /* Current input scan number and number of iMCU rows completed in scan.
  156717. * These indicate the progress of the decompressor input side.
  156718. */
  156719. int input_scan_number; /* Number of SOS markers seen so far */
  156720. JDIMENSION input_iMCU_row; /* Number of iMCU rows completed */
  156721. /* The "output scan number" is the notional scan being displayed by the
  156722. * output side. The decompressor will not allow output scan/row number
  156723. * to get ahead of input scan/row, but it can fall arbitrarily far behind.
  156724. */
  156725. int output_scan_number; /* Nominal scan number being displayed */
  156726. JDIMENSION output_iMCU_row; /* Number of iMCU rows read */
  156727. /* Current progression status. coef_bits[c][i] indicates the precision
  156728. * with which component c's DCT coefficient i (in zigzag order) is known.
  156729. * It is -1 when no data has yet been received, otherwise it is the point
  156730. * transform (shift) value for the most recent scan of the coefficient
  156731. * (thus, 0 at completion of the progression).
  156732. * This pointer is NULL when reading a non-progressive file.
  156733. */
  156734. int (*coef_bits)[DCTSIZE2]; /* -1 or current Al value for each coef */
  156735. /* Internal JPEG parameters --- the application usually need not look at
  156736. * these fields. Note that the decompressor output side may not use
  156737. * any parameters that can change between scans.
  156738. */
  156739. /* Quantization and Huffman tables are carried forward across input
  156740. * datastreams when processing abbreviated JPEG datastreams.
  156741. */
  156742. JQUANT_TBL * quant_tbl_ptrs[NUM_QUANT_TBLS];
  156743. /* ptrs to coefficient quantization tables, or NULL if not defined */
  156744. JHUFF_TBL * dc_huff_tbl_ptrs[NUM_HUFF_TBLS];
  156745. JHUFF_TBL * ac_huff_tbl_ptrs[NUM_HUFF_TBLS];
  156746. /* ptrs to Huffman coding tables, or NULL if not defined */
  156747. /* These parameters are never carried across datastreams, since they
  156748. * are given in SOF/SOS markers or defined to be reset by SOI.
  156749. */
  156750. int data_precision; /* bits of precision in image data */
  156751. jpeg_component_info * comp_info;
  156752. /* comp_info[i] describes component that appears i'th in SOF */
  156753. boolean progressive_mode; /* TRUE if SOFn specifies progressive mode */
  156754. boolean arith_code; /* TRUE=arithmetic coding, FALSE=Huffman */
  156755. UINT8 arith_dc_L[NUM_ARITH_TBLS]; /* L values for DC arith-coding tables */
  156756. UINT8 arith_dc_U[NUM_ARITH_TBLS]; /* U values for DC arith-coding tables */
  156757. UINT8 arith_ac_K[NUM_ARITH_TBLS]; /* Kx values for AC arith-coding tables */
  156758. unsigned int restart_interval; /* MCUs per restart interval, or 0 for no restart */
  156759. /* These fields record data obtained from optional markers recognized by
  156760. * the JPEG library.
  156761. */
  156762. boolean saw_JFIF_marker; /* TRUE iff a JFIF APP0 marker was found */
  156763. /* Data copied from JFIF marker; only valid if saw_JFIF_marker is TRUE: */
  156764. UINT8 JFIF_major_version; /* JFIF version number */
  156765. UINT8 JFIF_minor_version;
  156766. UINT8 density_unit; /* JFIF code for pixel size units */
  156767. UINT16 X_density; /* Horizontal pixel density */
  156768. UINT16 Y_density; /* Vertical pixel density */
  156769. boolean saw_Adobe_marker; /* TRUE iff an Adobe APP14 marker was found */
  156770. UINT8 Adobe_transform; /* Color transform code from Adobe marker */
  156771. boolean CCIR601_sampling; /* TRUE=first samples are cosited */
  156772. /* Aside from the specific data retained from APPn markers known to the
  156773. * library, the uninterpreted contents of any or all APPn and COM markers
  156774. * can be saved in a list for examination by the application.
  156775. */
  156776. jpeg_saved_marker_ptr marker_list; /* Head of list of saved markers */
  156777. /* Remaining fields are known throughout decompressor, but generally
  156778. * should not be touched by a surrounding application.
  156779. */
  156780. /*
  156781. * These fields are computed during decompression startup
  156782. */
  156783. int max_h_samp_factor; /* largest h_samp_factor */
  156784. int max_v_samp_factor; /* largest v_samp_factor */
  156785. int min_DCT_scaled_size; /* smallest DCT_scaled_size of any component */
  156786. JDIMENSION total_iMCU_rows; /* # of iMCU rows in image */
  156787. /* The coefficient controller's input and output progress is measured in
  156788. * units of "iMCU" (interleaved MCU) rows. These are the same as MCU rows
  156789. * in fully interleaved JPEG scans, but are used whether the scan is
  156790. * interleaved or not. We define an iMCU row as v_samp_factor DCT block
  156791. * rows of each component. Therefore, the IDCT output contains
  156792. * v_samp_factor*DCT_scaled_size sample rows of a component per iMCU row.
  156793. */
  156794. JSAMPLE * sample_range_limit; /* table for fast range-limiting */
  156795. /*
  156796. * These fields are valid during any one scan.
  156797. * They describe the components and MCUs actually appearing in the scan.
  156798. * Note that the decompressor output side must not use these fields.
  156799. */
  156800. int comps_in_scan; /* # of JPEG components in this scan */
  156801. jpeg_component_info * cur_comp_info[MAX_COMPS_IN_SCAN];
  156802. /* *cur_comp_info[i] describes component that appears i'th in SOS */
  156803. JDIMENSION MCUs_per_row; /* # of MCUs across the image */
  156804. JDIMENSION MCU_rows_in_scan; /* # of MCU rows in the image */
  156805. int blocks_in_MCU; /* # of DCT blocks per MCU */
  156806. int MCU_membership[D_MAX_BLOCKS_IN_MCU];
  156807. /* MCU_membership[i] is index in cur_comp_info of component owning */
  156808. /* i'th block in an MCU */
  156809. int Ss, Se, Ah, Al; /* progressive JPEG parameters for scan */
  156810. /* This field is shared between entropy decoder and marker parser.
  156811. * It is either zero or the code of a JPEG marker that has been
  156812. * read from the data source, but has not yet been processed.
  156813. */
  156814. int unread_marker;
  156815. /*
  156816. * Links to decompression subobjects (methods, private variables of modules)
  156817. */
  156818. struct jpeg_decomp_master * master;
  156819. struct jpeg_d_main_controller * main;
  156820. struct jpeg_d_coef_controller * coef;
  156821. struct jpeg_d_post_controller * post;
  156822. struct jpeg_input_controller * inputctl;
  156823. struct jpeg_marker_reader * marker;
  156824. struct jpeg_entropy_decoder * entropy;
  156825. struct jpeg_inverse_dct * idct;
  156826. struct jpeg_upsampler * upsample;
  156827. struct jpeg_color_deconverter * cconvert;
  156828. struct jpeg_color_quantizer * cquantize;
  156829. };
  156830. /* "Object" declarations for JPEG modules that may be supplied or called
  156831. * directly by the surrounding application.
  156832. * As with all objects in the JPEG library, these structs only define the
  156833. * publicly visible methods and state variables of a module. Additional
  156834. * private fields may exist after the public ones.
  156835. */
  156836. /* Error handler object */
  156837. struct jpeg_error_mgr {
  156838. /* Error exit handler: does not return to caller */
  156839. JMETHOD(void, error_exit, (j_common_ptr cinfo));
  156840. /* Conditionally emit a trace or warning message */
  156841. JMETHOD(void, emit_message, (j_common_ptr cinfo, int msg_level));
  156842. /* Routine that actually outputs a trace or error message */
  156843. JMETHOD(void, output_message, (j_common_ptr cinfo));
  156844. /* Format a message string for the most recent JPEG error or message */
  156845. JMETHOD(void, format_message, (j_common_ptr cinfo, char * buffer));
  156846. #define JMSG_LENGTH_MAX 200 /* recommended size of format_message buffer */
  156847. /* Reset error state variables at start of a new image */
  156848. JMETHOD(void, reset_error_mgr, (j_common_ptr cinfo));
  156849. /* The message ID code and any parameters are saved here.
  156850. * A message can have one string parameter or up to 8 int parameters.
  156851. */
  156852. int msg_code;
  156853. #define JMSG_STR_PARM_MAX 80
  156854. union {
  156855. int i[8];
  156856. char s[JMSG_STR_PARM_MAX];
  156857. } msg_parm;
  156858. /* Standard state variables for error facility */
  156859. int trace_level; /* max msg_level that will be displayed */
  156860. /* For recoverable corrupt-data errors, we emit a warning message,
  156861. * but keep going unless emit_message chooses to abort. emit_message
  156862. * should count warnings in num_warnings. The surrounding application
  156863. * can check for bad data by seeing if num_warnings is nonzero at the
  156864. * end of processing.
  156865. */
  156866. long num_warnings; /* number of corrupt-data warnings */
  156867. /* These fields point to the table(s) of error message strings.
  156868. * An application can change the table pointer to switch to a different
  156869. * message list (typically, to change the language in which errors are
  156870. * reported). Some applications may wish to add additional error codes
  156871. * that will be handled by the JPEG library error mechanism; the second
  156872. * table pointer is used for this purpose.
  156873. *
  156874. * First table includes all errors generated by JPEG library itself.
  156875. * Error code 0 is reserved for a "no such error string" message.
  156876. */
  156877. const char * const * jpeg_message_table; /* Library errors */
  156878. int last_jpeg_message; /* Table contains strings 0..last_jpeg_message */
  156879. /* Second table can be added by application (see cjpeg/djpeg for example).
  156880. * It contains strings numbered first_addon_message..last_addon_message.
  156881. */
  156882. const char * const * addon_message_table; /* Non-library errors */
  156883. int first_addon_message; /* code for first string in addon table */
  156884. int last_addon_message; /* code for last string in addon table */
  156885. };
  156886. /* Progress monitor object */
  156887. struct jpeg_progress_mgr {
  156888. JMETHOD(void, progress_monitor, (j_common_ptr cinfo));
  156889. long pass_counter; /* work units completed in this pass */
  156890. long pass_limit; /* total number of work units in this pass */
  156891. int completed_passes; /* passes completed so far */
  156892. int total_passes; /* total number of passes expected */
  156893. };
  156894. /* Data destination object for compression */
  156895. struct jpeg_destination_mgr {
  156896. JOCTET * next_output_byte; /* => next byte to write in buffer */
  156897. size_t free_in_buffer; /* # of byte spaces remaining in buffer */
  156898. JMETHOD(void, init_destination, (j_compress_ptr cinfo));
  156899. JMETHOD(boolean, empty_output_buffer, (j_compress_ptr cinfo));
  156900. JMETHOD(void, term_destination, (j_compress_ptr cinfo));
  156901. };
  156902. /* Data source object for decompression */
  156903. struct jpeg_source_mgr {
  156904. const JOCTET * next_input_byte; /* => next byte to read from buffer */
  156905. size_t bytes_in_buffer; /* # of bytes remaining in buffer */
  156906. JMETHOD(void, init_source, (j_decompress_ptr cinfo));
  156907. JMETHOD(boolean, fill_input_buffer, (j_decompress_ptr cinfo));
  156908. JMETHOD(void, skip_input_data, (j_decompress_ptr cinfo, long num_bytes));
  156909. JMETHOD(boolean, resync_to_restart, (j_decompress_ptr cinfo, int desired));
  156910. JMETHOD(void, term_source, (j_decompress_ptr cinfo));
  156911. };
  156912. /* Memory manager object.
  156913. * Allocates "small" objects (a few K total), "large" objects (tens of K),
  156914. * and "really big" objects (virtual arrays with backing store if needed).
  156915. * The memory manager does not allow individual objects to be freed; rather,
  156916. * each created object is assigned to a pool, and whole pools can be freed
  156917. * at once. This is faster and more convenient than remembering exactly what
  156918. * to free, especially where malloc()/free() are not too speedy.
  156919. * NB: alloc routines never return NULL. They exit to error_exit if not
  156920. * successful.
  156921. */
  156922. #define JPOOL_PERMANENT 0 /* lasts until master record is destroyed */
  156923. #define JPOOL_IMAGE 1 /* lasts until done with image/datastream */
  156924. #define JPOOL_NUMPOOLS 2
  156925. typedef struct jvirt_sarray_control * jvirt_sarray_ptr;
  156926. typedef struct jvirt_barray_control * jvirt_barray_ptr;
  156927. struct jpeg_memory_mgr {
  156928. /* Method pointers */
  156929. JMETHOD(void *, alloc_small, (j_common_ptr cinfo, int pool_id,
  156930. size_t sizeofobject));
  156931. JMETHOD(void FAR *, alloc_large, (j_common_ptr cinfo, int pool_id,
  156932. size_t sizeofobject));
  156933. JMETHOD(JSAMPARRAY, alloc_sarray, (j_common_ptr cinfo, int pool_id,
  156934. JDIMENSION samplesperrow,
  156935. JDIMENSION numrows));
  156936. JMETHOD(JBLOCKARRAY, alloc_barray, (j_common_ptr cinfo, int pool_id,
  156937. JDIMENSION blocksperrow,
  156938. JDIMENSION numrows));
  156939. JMETHOD(jvirt_sarray_ptr, request_virt_sarray, (j_common_ptr cinfo,
  156940. int pool_id,
  156941. boolean pre_zero,
  156942. JDIMENSION samplesperrow,
  156943. JDIMENSION numrows,
  156944. JDIMENSION maxaccess));
  156945. JMETHOD(jvirt_barray_ptr, request_virt_barray, (j_common_ptr cinfo,
  156946. int pool_id,
  156947. boolean pre_zero,
  156948. JDIMENSION blocksperrow,
  156949. JDIMENSION numrows,
  156950. JDIMENSION maxaccess));
  156951. JMETHOD(void, realize_virt_arrays, (j_common_ptr cinfo));
  156952. JMETHOD(JSAMPARRAY, access_virt_sarray, (j_common_ptr cinfo,
  156953. jvirt_sarray_ptr ptr,
  156954. JDIMENSION start_row,
  156955. JDIMENSION num_rows,
  156956. boolean writable));
  156957. JMETHOD(JBLOCKARRAY, access_virt_barray, (j_common_ptr cinfo,
  156958. jvirt_barray_ptr ptr,
  156959. JDIMENSION start_row,
  156960. JDIMENSION num_rows,
  156961. boolean writable));
  156962. JMETHOD(void, free_pool, (j_common_ptr cinfo, int pool_id));
  156963. JMETHOD(void, self_destruct, (j_common_ptr cinfo));
  156964. /* Limit on memory allocation for this JPEG object. (Note that this is
  156965. * merely advisory, not a guaranteed maximum; it only affects the space
  156966. * used for virtual-array buffers.) May be changed by outer application
  156967. * after creating the JPEG object.
  156968. */
  156969. long max_memory_to_use;
  156970. /* Maximum allocation request accepted by alloc_large. */
  156971. long max_alloc_chunk;
  156972. };
  156973. /* Routine signature for application-supplied marker processing methods.
  156974. * Need not pass marker code since it is stored in cinfo->unread_marker.
  156975. */
  156976. typedef JMETHOD(boolean, jpeg_marker_parser_method, (j_decompress_ptr cinfo));
  156977. /* Declarations for routines called by application.
  156978. * The JPP macro hides prototype parameters from compilers that can't cope.
  156979. * Note JPP requires double parentheses.
  156980. */
  156981. #ifdef HAVE_PROTOTYPES
  156982. #define JPP(arglist) arglist
  156983. #else
  156984. #define JPP(arglist) ()
  156985. #endif
  156986. /* Short forms of external names for systems with brain-damaged linkers.
  156987. * We shorten external names to be unique in the first six letters, which
  156988. * is good enough for all known systems.
  156989. * (If your compiler itself needs names to be unique in less than 15
  156990. * characters, you are out of luck. Get a better compiler.)
  156991. */
  156992. #ifdef NEED_SHORT_EXTERNAL_NAMES
  156993. #define jpeg_std_error jStdError
  156994. #define jpeg_CreateCompress jCreaCompress
  156995. #define jpeg_CreateDecompress jCreaDecompress
  156996. #define jpeg_destroy_compress jDestCompress
  156997. #define jpeg_destroy_decompress jDestDecompress
  156998. #define jpeg_stdio_dest jStdDest
  156999. #define jpeg_stdio_src jStdSrc
  157000. #define jpeg_set_defaults jSetDefaults
  157001. #define jpeg_set_colorspace jSetColorspace
  157002. #define jpeg_default_colorspace jDefColorspace
  157003. #define jpeg_set_quality jSetQuality
  157004. #define jpeg_set_linear_quality jSetLQuality
  157005. #define jpeg_add_quant_table jAddQuantTable
  157006. #define jpeg_quality_scaling jQualityScaling
  157007. #define jpeg_simple_progression jSimProgress
  157008. #define jpeg_suppress_tables jSuppressTables
  157009. #define jpeg_alloc_quant_table jAlcQTable
  157010. #define jpeg_alloc_huff_table jAlcHTable
  157011. #define jpeg_start_compress jStrtCompress
  157012. #define jpeg_write_scanlines jWrtScanlines
  157013. #define jpeg_finish_compress jFinCompress
  157014. #define jpeg_write_raw_data jWrtRawData
  157015. #define jpeg_write_marker jWrtMarker
  157016. #define jpeg_write_m_header jWrtMHeader
  157017. #define jpeg_write_m_byte jWrtMByte
  157018. #define jpeg_write_tables jWrtTables
  157019. #define jpeg_read_header jReadHeader
  157020. #define jpeg_start_decompress jStrtDecompress
  157021. #define jpeg_read_scanlines jReadScanlines
  157022. #define jpeg_finish_decompress jFinDecompress
  157023. #define jpeg_read_raw_data jReadRawData
  157024. #define jpeg_has_multiple_scans jHasMultScn
  157025. #define jpeg_start_output jStrtOutput
  157026. #define jpeg_finish_output jFinOutput
  157027. #define jpeg_input_complete jInComplete
  157028. #define jpeg_new_colormap jNewCMap
  157029. #define jpeg_consume_input jConsumeInput
  157030. #define jpeg_calc_output_dimensions jCalcDimensions
  157031. #define jpeg_save_markers jSaveMarkers
  157032. #define jpeg_set_marker_processor jSetMarker
  157033. #define jpeg_read_coefficients jReadCoefs
  157034. #define jpeg_write_coefficients jWrtCoefs
  157035. #define jpeg_copy_critical_parameters jCopyCrit
  157036. #define jpeg_abort_compress jAbrtCompress
  157037. #define jpeg_abort_decompress jAbrtDecompress
  157038. #define jpeg_abort jAbort
  157039. #define jpeg_destroy jDestroy
  157040. #define jpeg_resync_to_restart jResyncRestart
  157041. #endif /* NEED_SHORT_EXTERNAL_NAMES */
  157042. /* Default error-management setup */
  157043. EXTERN(struct jpeg_error_mgr *) jpeg_std_error
  157044. JPP((struct jpeg_error_mgr * err));
  157045. /* Initialization of JPEG compression objects.
  157046. * jpeg_create_compress() and jpeg_create_decompress() are the exported
  157047. * names that applications should call. These expand to calls on
  157048. * jpeg_CreateCompress and jpeg_CreateDecompress with additional information
  157049. * passed for version mismatch checking.
  157050. * NB: you must set up the error-manager BEFORE calling jpeg_create_xxx.
  157051. */
  157052. #define jpeg_create_compress(cinfo) \
  157053. jpeg_CreateCompress((cinfo), JPEG_LIB_VERSION, \
  157054. (size_t) sizeof(struct jpeg_compress_struct))
  157055. #define jpeg_create_decompress(cinfo) \
  157056. jpeg_CreateDecompress((cinfo), JPEG_LIB_VERSION, \
  157057. (size_t) sizeof(struct jpeg_decompress_struct))
  157058. EXTERN(void) jpeg_CreateCompress JPP((j_compress_ptr cinfo,
  157059. int version, size_t structsize));
  157060. EXTERN(void) jpeg_CreateDecompress JPP((j_decompress_ptr cinfo,
  157061. int version, size_t structsize));
  157062. /* Destruction of JPEG compression objects */
  157063. EXTERN(void) jpeg_destroy_compress JPP((j_compress_ptr cinfo));
  157064. EXTERN(void) jpeg_destroy_decompress JPP((j_decompress_ptr cinfo));
  157065. /* Standard data source and destination managers: stdio streams. */
  157066. /* Caller is responsible for opening the file before and closing after. */
  157067. EXTERN(void) jpeg_stdio_dest JPP((j_compress_ptr cinfo, FILE * outfile));
  157068. EXTERN(void) jpeg_stdio_src JPP((j_decompress_ptr cinfo, FILE * infile));
  157069. /* Default parameter setup for compression */
  157070. EXTERN(void) jpeg_set_defaults JPP((j_compress_ptr cinfo));
  157071. /* Compression parameter setup aids */
  157072. EXTERN(void) jpeg_set_colorspace JPP((j_compress_ptr cinfo,
  157073. J_COLOR_SPACE colorspace));
  157074. EXTERN(void) jpeg_default_colorspace JPP((j_compress_ptr cinfo));
  157075. EXTERN(void) jpeg_set_quality JPP((j_compress_ptr cinfo, int quality,
  157076. boolean force_baseline));
  157077. EXTERN(void) jpeg_set_linear_quality JPP((j_compress_ptr cinfo,
  157078. int scale_factor,
  157079. boolean force_baseline));
  157080. EXTERN(void) jpeg_add_quant_table JPP((j_compress_ptr cinfo, int which_tbl,
  157081. const unsigned int *basic_table,
  157082. int scale_factor,
  157083. boolean force_baseline));
  157084. EXTERN(int) jpeg_quality_scaling JPP((int quality));
  157085. EXTERN(void) jpeg_simple_progression JPP((j_compress_ptr cinfo));
  157086. EXTERN(void) jpeg_suppress_tables JPP((j_compress_ptr cinfo,
  157087. boolean suppress));
  157088. EXTERN(JQUANT_TBL *) jpeg_alloc_quant_table JPP((j_common_ptr cinfo));
  157089. EXTERN(JHUFF_TBL *) jpeg_alloc_huff_table JPP((j_common_ptr cinfo));
  157090. /* Main entry points for compression */
  157091. EXTERN(void) jpeg_start_compress JPP((j_compress_ptr cinfo,
  157092. boolean write_all_tables));
  157093. EXTERN(JDIMENSION) jpeg_write_scanlines JPP((j_compress_ptr cinfo,
  157094. JSAMPARRAY scanlines,
  157095. JDIMENSION num_lines));
  157096. EXTERN(void) jpeg_finish_compress JPP((j_compress_ptr cinfo));
  157097. /* Replaces jpeg_write_scanlines when writing raw downsampled data. */
  157098. EXTERN(JDIMENSION) jpeg_write_raw_data JPP((j_compress_ptr cinfo,
  157099. JSAMPIMAGE data,
  157100. JDIMENSION num_lines));
  157101. /* Write a special marker. See libjpeg.doc concerning safe usage. */
  157102. EXTERN(void) jpeg_write_marker
  157103. JPP((j_compress_ptr cinfo, int marker,
  157104. const JOCTET * dataptr, unsigned int datalen));
  157105. /* Same, but piecemeal. */
  157106. EXTERN(void) jpeg_write_m_header
  157107. JPP((j_compress_ptr cinfo, int marker, unsigned int datalen));
  157108. EXTERN(void) jpeg_write_m_byte
  157109. JPP((j_compress_ptr cinfo, int val));
  157110. /* Alternate compression function: just write an abbreviated table file */
  157111. EXTERN(void) jpeg_write_tables JPP((j_compress_ptr cinfo));
  157112. /* Decompression startup: read start of JPEG datastream to see what's there */
  157113. EXTERN(int) jpeg_read_header JPP((j_decompress_ptr cinfo,
  157114. boolean require_image));
  157115. /* Return value is one of: */
  157116. #define JPEG_SUSPENDED 0 /* Suspended due to lack of input data */
  157117. #define JPEG_HEADER_OK 1 /* Found valid image datastream */
  157118. #define JPEG_HEADER_TABLES_ONLY 2 /* Found valid table-specs-only datastream */
  157119. /* If you pass require_image = TRUE (normal case), you need not check for
  157120. * a TABLES_ONLY return code; an abbreviated file will cause an error exit.
  157121. * JPEG_SUSPENDED is only possible if you use a data source module that can
  157122. * give a suspension return (the stdio source module doesn't).
  157123. */
  157124. /* Main entry points for decompression */
  157125. EXTERN(boolean) jpeg_start_decompress JPP((j_decompress_ptr cinfo));
  157126. EXTERN(JDIMENSION) jpeg_read_scanlines JPP((j_decompress_ptr cinfo,
  157127. JSAMPARRAY scanlines,
  157128. JDIMENSION max_lines));
  157129. EXTERN(boolean) jpeg_finish_decompress JPP((j_decompress_ptr cinfo));
  157130. /* Replaces jpeg_read_scanlines when reading raw downsampled data. */
  157131. EXTERN(JDIMENSION) jpeg_read_raw_data JPP((j_decompress_ptr cinfo,
  157132. JSAMPIMAGE data,
  157133. JDIMENSION max_lines));
  157134. /* Additional entry points for buffered-image mode. */
  157135. EXTERN(boolean) jpeg_has_multiple_scans JPP((j_decompress_ptr cinfo));
  157136. EXTERN(boolean) jpeg_start_output JPP((j_decompress_ptr cinfo,
  157137. int scan_number));
  157138. EXTERN(boolean) jpeg_finish_output JPP((j_decompress_ptr cinfo));
  157139. EXTERN(boolean) jpeg_input_complete JPP((j_decompress_ptr cinfo));
  157140. EXTERN(void) jpeg_new_colormap JPP((j_decompress_ptr cinfo));
  157141. EXTERN(int) jpeg_consume_input JPP((j_decompress_ptr cinfo));
  157142. /* Return value is one of: */
  157143. /* #define JPEG_SUSPENDED 0 Suspended due to lack of input data */
  157144. #define JPEG_REACHED_SOS 1 /* Reached start of new scan */
  157145. #define JPEG_REACHED_EOI 2 /* Reached end of image */
  157146. #define JPEG_ROW_COMPLETED 3 /* Completed one iMCU row */
  157147. #define JPEG_SCAN_COMPLETED 4 /* Completed last iMCU row of a scan */
  157148. /* Precalculate output dimensions for current decompression parameters. */
  157149. EXTERN(void) jpeg_calc_output_dimensions JPP((j_decompress_ptr cinfo));
  157150. /* Control saving of COM and APPn markers into marker_list. */
  157151. EXTERN(void) jpeg_save_markers
  157152. JPP((j_decompress_ptr cinfo, int marker_code,
  157153. unsigned int length_limit));
  157154. /* Install a special processing method for COM or APPn markers. */
  157155. EXTERN(void) jpeg_set_marker_processor
  157156. JPP((j_decompress_ptr cinfo, int marker_code,
  157157. jpeg_marker_parser_method routine));
  157158. /* Read or write raw DCT coefficients --- useful for lossless transcoding. */
  157159. EXTERN(jvirt_barray_ptr *) jpeg_read_coefficients JPP((j_decompress_ptr cinfo));
  157160. EXTERN(void) jpeg_write_coefficients JPP((j_compress_ptr cinfo,
  157161. jvirt_barray_ptr * coef_arrays));
  157162. EXTERN(void) jpeg_copy_critical_parameters JPP((j_decompress_ptr srcinfo,
  157163. j_compress_ptr dstinfo));
  157164. /* If you choose to abort compression or decompression before completing
  157165. * jpeg_finish_(de)compress, then you need to clean up to release memory,
  157166. * temporary files, etc. You can just call jpeg_destroy_(de)compress
  157167. * if you're done with the JPEG object, but if you want to clean it up and
  157168. * reuse it, call this:
  157169. */
  157170. EXTERN(void) jpeg_abort_compress JPP((j_compress_ptr cinfo));
  157171. EXTERN(void) jpeg_abort_decompress JPP((j_decompress_ptr cinfo));
  157172. /* Generic versions of jpeg_abort and jpeg_destroy that work on either
  157173. * flavor of JPEG object. These may be more convenient in some places.
  157174. */
  157175. EXTERN(void) jpeg_abort JPP((j_common_ptr cinfo));
  157176. EXTERN(void) jpeg_destroy JPP((j_common_ptr cinfo));
  157177. /* Default restart-marker-resync procedure for use by data source modules */
  157178. EXTERN(boolean) jpeg_resync_to_restart JPP((j_decompress_ptr cinfo,
  157179. int desired));
  157180. /* These marker codes are exported since applications and data source modules
  157181. * are likely to want to use them.
  157182. */
  157183. #define JPEG_RST0 0xD0 /* RST0 marker code */
  157184. #define JPEG_EOI 0xD9 /* EOI marker code */
  157185. #define JPEG_APP0 0xE0 /* APP0 marker code */
  157186. #define JPEG_COM 0xFE /* COM marker code */
  157187. /* If we have a brain-damaged compiler that emits warnings (or worse, errors)
  157188. * for structure definitions that are never filled in, keep it quiet by
  157189. * supplying dummy definitions for the various substructures.
  157190. */
  157191. #ifdef INCOMPLETE_TYPES_BROKEN
  157192. #ifndef JPEG_INTERNALS /* will be defined in jpegint.h */
  157193. struct jvirt_sarray_control { long dummy; };
  157194. struct jvirt_barray_control { long dummy; };
  157195. struct jpeg_comp_master { long dummy; };
  157196. struct jpeg_c_main_controller { long dummy; };
  157197. struct jpeg_c_prep_controller { long dummy; };
  157198. struct jpeg_c_coef_controller { long dummy; };
  157199. struct jpeg_marker_writer { long dummy; };
  157200. struct jpeg_color_converter { long dummy; };
  157201. struct jpeg_downsampler { long dummy; };
  157202. struct jpeg_forward_dct { long dummy; };
  157203. struct jpeg_entropy_encoder { long dummy; };
  157204. struct jpeg_decomp_master { long dummy; };
  157205. struct jpeg_d_main_controller { long dummy; };
  157206. struct jpeg_d_coef_controller { long dummy; };
  157207. struct jpeg_d_post_controller { long dummy; };
  157208. struct jpeg_input_controller { long dummy; };
  157209. struct jpeg_marker_reader { long dummy; };
  157210. struct jpeg_entropy_decoder { long dummy; };
  157211. struct jpeg_inverse_dct { long dummy; };
  157212. struct jpeg_upsampler { long dummy; };
  157213. struct jpeg_color_deconverter { long dummy; };
  157214. struct jpeg_color_quantizer { long dummy; };
  157215. #endif /* JPEG_INTERNALS */
  157216. #endif /* INCOMPLETE_TYPES_BROKEN */
  157217. /*
  157218. * The JPEG library modules define JPEG_INTERNALS before including this file.
  157219. * The internal structure declarations are read only when that is true.
  157220. * Applications using the library should not include jpegint.h, but may wish
  157221. * to include jerror.h.
  157222. */
  157223. #ifdef JPEG_INTERNALS
  157224. /*** Start of inlined file: jpegint.h ***/
  157225. /* Declarations for both compression & decompression */
  157226. typedef enum { /* Operating modes for buffer controllers */
  157227. JBUF_PASS_THRU, /* Plain stripwise operation */
  157228. /* Remaining modes require a full-image buffer to have been created */
  157229. JBUF_SAVE_SOURCE, /* Run source subobject only, save output */
  157230. JBUF_CRANK_DEST, /* Run dest subobject only, using saved data */
  157231. JBUF_SAVE_AND_PASS /* Run both subobjects, save output */
  157232. } J_BUF_MODE;
  157233. /* Values of global_state field (jdapi.c has some dependencies on ordering!) */
  157234. #define CSTATE_START 100 /* after create_compress */
  157235. #define CSTATE_SCANNING 101 /* start_compress done, write_scanlines OK */
  157236. #define CSTATE_RAW_OK 102 /* start_compress done, write_raw_data OK */
  157237. #define CSTATE_WRCOEFS 103 /* jpeg_write_coefficients done */
  157238. #define DSTATE_START 200 /* after create_decompress */
  157239. #define DSTATE_INHEADER 201 /* reading header markers, no SOS yet */
  157240. #define DSTATE_READY 202 /* found SOS, ready for start_decompress */
  157241. #define DSTATE_PRELOAD 203 /* reading multiscan file in start_decompress*/
  157242. #define DSTATE_PRESCAN 204 /* performing dummy pass for 2-pass quant */
  157243. #define DSTATE_SCANNING 205 /* start_decompress done, read_scanlines OK */
  157244. #define DSTATE_RAW_OK 206 /* start_decompress done, read_raw_data OK */
  157245. #define DSTATE_BUFIMAGE 207 /* expecting jpeg_start_output */
  157246. #define DSTATE_BUFPOST 208 /* looking for SOS/EOI in jpeg_finish_output */
  157247. #define DSTATE_RDCOEFS 209 /* reading file in jpeg_read_coefficients */
  157248. #define DSTATE_STOPPING 210 /* looking for EOI in jpeg_finish_decompress */
  157249. /* Declarations for compression modules */
  157250. /* Master control module */
  157251. struct jpeg_comp_master {
  157252. JMETHOD(void, prepare_for_pass, (j_compress_ptr cinfo));
  157253. JMETHOD(void, pass_startup, (j_compress_ptr cinfo));
  157254. JMETHOD(void, finish_pass, (j_compress_ptr cinfo));
  157255. /* State variables made visible to other modules */
  157256. boolean call_pass_startup; /* True if pass_startup must be called */
  157257. boolean is_last_pass; /* True during last pass */
  157258. };
  157259. /* Main buffer control (downsampled-data buffer) */
  157260. struct jpeg_c_main_controller {
  157261. JMETHOD(void, start_pass, (j_compress_ptr cinfo, J_BUF_MODE pass_mode));
  157262. JMETHOD(void, process_data, (j_compress_ptr cinfo,
  157263. JSAMPARRAY input_buf, JDIMENSION *in_row_ctr,
  157264. JDIMENSION in_rows_avail));
  157265. };
  157266. /* Compression preprocessing (downsampling input buffer control) */
  157267. struct jpeg_c_prep_controller {
  157268. JMETHOD(void, start_pass, (j_compress_ptr cinfo, J_BUF_MODE pass_mode));
  157269. JMETHOD(void, pre_process_data, (j_compress_ptr cinfo,
  157270. JSAMPARRAY input_buf,
  157271. JDIMENSION *in_row_ctr,
  157272. JDIMENSION in_rows_avail,
  157273. JSAMPIMAGE output_buf,
  157274. JDIMENSION *out_row_group_ctr,
  157275. JDIMENSION out_row_groups_avail));
  157276. };
  157277. /* Coefficient buffer control */
  157278. struct jpeg_c_coef_controller {
  157279. JMETHOD(void, start_pass, (j_compress_ptr cinfo, J_BUF_MODE pass_mode));
  157280. JMETHOD(boolean, compress_data, (j_compress_ptr cinfo,
  157281. JSAMPIMAGE input_buf));
  157282. };
  157283. /* Colorspace conversion */
  157284. struct jpeg_color_converter {
  157285. JMETHOD(void, start_pass, (j_compress_ptr cinfo));
  157286. JMETHOD(void, color_convert, (j_compress_ptr cinfo,
  157287. JSAMPARRAY input_buf, JSAMPIMAGE output_buf,
  157288. JDIMENSION output_row, int num_rows));
  157289. };
  157290. /* Downsampling */
  157291. struct jpeg_downsampler {
  157292. JMETHOD(void, start_pass, (j_compress_ptr cinfo));
  157293. JMETHOD(void, downsample, (j_compress_ptr cinfo,
  157294. JSAMPIMAGE input_buf, JDIMENSION in_row_index,
  157295. JSAMPIMAGE output_buf,
  157296. JDIMENSION out_row_group_index));
  157297. boolean need_context_rows; /* TRUE if need rows above & below */
  157298. };
  157299. /* Forward DCT (also controls coefficient quantization) */
  157300. struct jpeg_forward_dct {
  157301. JMETHOD(void, start_pass, (j_compress_ptr cinfo));
  157302. /* perhaps this should be an array??? */
  157303. JMETHOD(void, forward_DCT, (j_compress_ptr cinfo,
  157304. jpeg_component_info * compptr,
  157305. JSAMPARRAY sample_data, JBLOCKROW coef_blocks,
  157306. JDIMENSION start_row, JDIMENSION start_col,
  157307. JDIMENSION num_blocks));
  157308. };
  157309. /* Entropy encoding */
  157310. struct jpeg_entropy_encoder {
  157311. JMETHOD(void, start_pass, (j_compress_ptr cinfo, boolean gather_statistics));
  157312. JMETHOD(boolean, encode_mcu, (j_compress_ptr cinfo, JBLOCKROW *MCU_data));
  157313. JMETHOD(void, finish_pass, (j_compress_ptr cinfo));
  157314. };
  157315. /* Marker writing */
  157316. struct jpeg_marker_writer {
  157317. JMETHOD(void, write_file_header, (j_compress_ptr cinfo));
  157318. JMETHOD(void, write_frame_header, (j_compress_ptr cinfo));
  157319. JMETHOD(void, write_scan_header, (j_compress_ptr cinfo));
  157320. JMETHOD(void, write_file_trailer, (j_compress_ptr cinfo));
  157321. JMETHOD(void, write_tables_only, (j_compress_ptr cinfo));
  157322. /* These routines are exported to allow insertion of extra markers */
  157323. /* Probably only COM and APPn markers should be written this way */
  157324. JMETHOD(void, write_marker_header, (j_compress_ptr cinfo, int marker,
  157325. unsigned int datalen));
  157326. JMETHOD(void, write_marker_byte, (j_compress_ptr cinfo, int val));
  157327. };
  157328. /* Declarations for decompression modules */
  157329. /* Master control module */
  157330. struct jpeg_decomp_master {
  157331. JMETHOD(void, prepare_for_output_pass, (j_decompress_ptr cinfo));
  157332. JMETHOD(void, finish_output_pass, (j_decompress_ptr cinfo));
  157333. /* State variables made visible to other modules */
  157334. boolean is_dummy_pass; /* True during 1st pass for 2-pass quant */
  157335. };
  157336. /* Input control module */
  157337. struct jpeg_input_controller {
  157338. JMETHOD(int, consume_input, (j_decompress_ptr cinfo));
  157339. JMETHOD(void, reset_input_controller, (j_decompress_ptr cinfo));
  157340. JMETHOD(void, start_input_pass, (j_decompress_ptr cinfo));
  157341. JMETHOD(void, finish_input_pass, (j_decompress_ptr cinfo));
  157342. /* State variables made visible to other modules */
  157343. boolean has_multiple_scans; /* True if file has multiple scans */
  157344. boolean eoi_reached; /* True when EOI has been consumed */
  157345. };
  157346. /* Main buffer control (downsampled-data buffer) */
  157347. struct jpeg_d_main_controller {
  157348. JMETHOD(void, start_pass, (j_decompress_ptr cinfo, J_BUF_MODE pass_mode));
  157349. JMETHOD(void, process_data, (j_decompress_ptr cinfo,
  157350. JSAMPARRAY output_buf, JDIMENSION *out_row_ctr,
  157351. JDIMENSION out_rows_avail));
  157352. };
  157353. /* Coefficient buffer control */
  157354. struct jpeg_d_coef_controller {
  157355. JMETHOD(void, start_input_pass, (j_decompress_ptr cinfo));
  157356. JMETHOD(int, consume_data, (j_decompress_ptr cinfo));
  157357. JMETHOD(void, start_output_pass, (j_decompress_ptr cinfo));
  157358. JMETHOD(int, decompress_data, (j_decompress_ptr cinfo,
  157359. JSAMPIMAGE output_buf));
  157360. /* Pointer to array of coefficient virtual arrays, or NULL if none */
  157361. jvirt_barray_ptr *coef_arrays;
  157362. };
  157363. /* Decompression postprocessing (color quantization buffer control) */
  157364. struct jpeg_d_post_controller {
  157365. JMETHOD(void, start_pass, (j_decompress_ptr cinfo, J_BUF_MODE pass_mode));
  157366. JMETHOD(void, post_process_data, (j_decompress_ptr cinfo,
  157367. JSAMPIMAGE input_buf,
  157368. JDIMENSION *in_row_group_ctr,
  157369. JDIMENSION in_row_groups_avail,
  157370. JSAMPARRAY output_buf,
  157371. JDIMENSION *out_row_ctr,
  157372. JDIMENSION out_rows_avail));
  157373. };
  157374. /* Marker reading & parsing */
  157375. struct jpeg_marker_reader {
  157376. JMETHOD(void, reset_marker_reader, (j_decompress_ptr cinfo));
  157377. /* Read markers until SOS or EOI.
  157378. * Returns same codes as are defined for jpeg_consume_input:
  157379. * JPEG_SUSPENDED, JPEG_REACHED_SOS, or JPEG_REACHED_EOI.
  157380. */
  157381. JMETHOD(int, read_markers, (j_decompress_ptr cinfo));
  157382. /* Read a restart marker --- exported for use by entropy decoder only */
  157383. jpeg_marker_parser_method read_restart_marker;
  157384. /* State of marker reader --- nominally internal, but applications
  157385. * supplying COM or APPn handlers might like to know the state.
  157386. */
  157387. boolean saw_SOI; /* found SOI? */
  157388. boolean saw_SOF; /* found SOF? */
  157389. int next_restart_num; /* next restart number expected (0-7) */
  157390. unsigned int discarded_bytes; /* # of bytes skipped looking for a marker */
  157391. };
  157392. /* Entropy decoding */
  157393. struct jpeg_entropy_decoder {
  157394. JMETHOD(void, start_pass, (j_decompress_ptr cinfo));
  157395. JMETHOD(boolean, decode_mcu, (j_decompress_ptr cinfo,
  157396. JBLOCKROW *MCU_data));
  157397. /* This is here to share code between baseline and progressive decoders; */
  157398. /* other modules probably should not use it */
  157399. boolean insufficient_data; /* set TRUE after emitting warning */
  157400. };
  157401. /* Inverse DCT (also performs dequantization) */
  157402. typedef JMETHOD(void, inverse_DCT_method_ptr,
  157403. (j_decompress_ptr cinfo, jpeg_component_info * compptr,
  157404. JCOEFPTR coef_block,
  157405. JSAMPARRAY output_buf, JDIMENSION output_col));
  157406. struct jpeg_inverse_dct {
  157407. JMETHOD(void, start_pass, (j_decompress_ptr cinfo));
  157408. /* It is useful to allow each component to have a separate IDCT method. */
  157409. inverse_DCT_method_ptr inverse_DCT[MAX_COMPONENTS];
  157410. };
  157411. /* Upsampling (note that upsampler must also call color converter) */
  157412. struct jpeg_upsampler {
  157413. JMETHOD(void, start_pass, (j_decompress_ptr cinfo));
  157414. JMETHOD(void, upsample, (j_decompress_ptr cinfo,
  157415. JSAMPIMAGE input_buf,
  157416. JDIMENSION *in_row_group_ctr,
  157417. JDIMENSION in_row_groups_avail,
  157418. JSAMPARRAY output_buf,
  157419. JDIMENSION *out_row_ctr,
  157420. JDIMENSION out_rows_avail));
  157421. boolean need_context_rows; /* TRUE if need rows above & below */
  157422. };
  157423. /* Colorspace conversion */
  157424. struct jpeg_color_deconverter {
  157425. JMETHOD(void, start_pass, (j_decompress_ptr cinfo));
  157426. JMETHOD(void, color_convert, (j_decompress_ptr cinfo,
  157427. JSAMPIMAGE input_buf, JDIMENSION input_row,
  157428. JSAMPARRAY output_buf, int num_rows));
  157429. };
  157430. /* Color quantization or color precision reduction */
  157431. struct jpeg_color_quantizer {
  157432. JMETHOD(void, start_pass, (j_decompress_ptr cinfo, boolean is_pre_scan));
  157433. JMETHOD(void, color_quantize, (j_decompress_ptr cinfo,
  157434. JSAMPARRAY input_buf, JSAMPARRAY output_buf,
  157435. int num_rows));
  157436. JMETHOD(void, finish_pass, (j_decompress_ptr cinfo));
  157437. JMETHOD(void, new_color_map, (j_decompress_ptr cinfo));
  157438. };
  157439. /* Miscellaneous useful macros */
  157440. #undef MAX
  157441. #define MAX(a,b) ((a) > (b) ? (a) : (b))
  157442. #undef MIN
  157443. #define MIN(a,b) ((a) < (b) ? (a) : (b))
  157444. /* We assume that right shift corresponds to signed division by 2 with
  157445. * rounding towards minus infinity. This is correct for typical "arithmetic
  157446. * shift" instructions that shift in copies of the sign bit. But some
  157447. * C compilers implement >> with an unsigned shift. For these machines you
  157448. * must define RIGHT_SHIFT_IS_UNSIGNED.
  157449. * RIGHT_SHIFT provides a proper signed right shift of an INT32 quantity.
  157450. * It is only applied with constant shift counts. SHIFT_TEMPS must be
  157451. * included in the variables of any routine using RIGHT_SHIFT.
  157452. */
  157453. #ifdef RIGHT_SHIFT_IS_UNSIGNED
  157454. #define SHIFT_TEMPS INT32 shift_temp;
  157455. #define RIGHT_SHIFT(x,shft) \
  157456. ((shift_temp = (x)) < 0 ? \
  157457. (shift_temp >> (shft)) | ((~((INT32) 0)) << (32-(shft))) : \
  157458. (shift_temp >> (shft)))
  157459. #else
  157460. #define SHIFT_TEMPS
  157461. #define RIGHT_SHIFT(x,shft) ((x) >> (shft))
  157462. #endif
  157463. /* Short forms of external names for systems with brain-damaged linkers. */
  157464. #ifdef NEED_SHORT_EXTERNAL_NAMES
  157465. #define jinit_compress_master jICompress
  157466. #define jinit_c_master_control jICMaster
  157467. #define jinit_c_main_controller jICMainC
  157468. #define jinit_c_prep_controller jICPrepC
  157469. #define jinit_c_coef_controller jICCoefC
  157470. #define jinit_color_converter jICColor
  157471. #define jinit_downsampler jIDownsampler
  157472. #define jinit_forward_dct jIFDCT
  157473. #define jinit_huff_encoder jIHEncoder
  157474. #define jinit_phuff_encoder jIPHEncoder
  157475. #define jinit_marker_writer jIMWriter
  157476. #define jinit_master_decompress jIDMaster
  157477. #define jinit_d_main_controller jIDMainC
  157478. #define jinit_d_coef_controller jIDCoefC
  157479. #define jinit_d_post_controller jIDPostC
  157480. #define jinit_input_controller jIInCtlr
  157481. #define jinit_marker_reader jIMReader
  157482. #define jinit_huff_decoder jIHDecoder
  157483. #define jinit_phuff_decoder jIPHDecoder
  157484. #define jinit_inverse_dct jIIDCT
  157485. #define jinit_upsampler jIUpsampler
  157486. #define jinit_color_deconverter jIDColor
  157487. #define jinit_1pass_quantizer jI1Quant
  157488. #define jinit_2pass_quantizer jI2Quant
  157489. #define jinit_merged_upsampler jIMUpsampler
  157490. #define jinit_memory_mgr jIMemMgr
  157491. #define jdiv_round_up jDivRound
  157492. #define jround_up jRound
  157493. #define jcopy_sample_rows jCopySamples
  157494. #define jcopy_block_row jCopyBlocks
  157495. #define jzero_far jZeroFar
  157496. #define jpeg_zigzag_order jZIGTable
  157497. #define jpeg_natural_order jZAGTable
  157498. #endif /* NEED_SHORT_EXTERNAL_NAMES */
  157499. /* Compression module initialization routines */
  157500. EXTERN(void) jinit_compress_master JPP((j_compress_ptr cinfo));
  157501. EXTERN(void) jinit_c_master_control JPP((j_compress_ptr cinfo,
  157502. boolean transcode_only));
  157503. EXTERN(void) jinit_c_main_controller JPP((j_compress_ptr cinfo,
  157504. boolean need_full_buffer));
  157505. EXTERN(void) jinit_c_prep_controller JPP((j_compress_ptr cinfo,
  157506. boolean need_full_buffer));
  157507. EXTERN(void) jinit_c_coef_controller JPP((j_compress_ptr cinfo,
  157508. boolean need_full_buffer));
  157509. EXTERN(void) jinit_color_converter JPP((j_compress_ptr cinfo));
  157510. EXTERN(void) jinit_downsampler JPP((j_compress_ptr cinfo));
  157511. EXTERN(void) jinit_forward_dct JPP((j_compress_ptr cinfo));
  157512. EXTERN(void) jinit_huff_encoder JPP((j_compress_ptr cinfo));
  157513. EXTERN(void) jinit_phuff_encoder JPP((j_compress_ptr cinfo));
  157514. EXTERN(void) jinit_marker_writer JPP((j_compress_ptr cinfo));
  157515. /* Decompression module initialization routines */
  157516. EXTERN(void) jinit_master_decompress JPP((j_decompress_ptr cinfo));
  157517. EXTERN(void) jinit_d_main_controller JPP((j_decompress_ptr cinfo,
  157518. boolean need_full_buffer));
  157519. EXTERN(void) jinit_d_coef_controller JPP((j_decompress_ptr cinfo,
  157520. boolean need_full_buffer));
  157521. EXTERN(void) jinit_d_post_controller JPP((j_decompress_ptr cinfo,
  157522. boolean need_full_buffer));
  157523. EXTERN(void) jinit_input_controller JPP((j_decompress_ptr cinfo));
  157524. EXTERN(void) jinit_marker_reader JPP((j_decompress_ptr cinfo));
  157525. EXTERN(void) jinit_huff_decoder JPP((j_decompress_ptr cinfo));
  157526. EXTERN(void) jinit_phuff_decoder JPP((j_decompress_ptr cinfo));
  157527. EXTERN(void) jinit_inverse_dct JPP((j_decompress_ptr cinfo));
  157528. EXTERN(void) jinit_upsampler JPP((j_decompress_ptr cinfo));
  157529. EXTERN(void) jinit_color_deconverter JPP((j_decompress_ptr cinfo));
  157530. EXTERN(void) jinit_1pass_quantizer JPP((j_decompress_ptr cinfo));
  157531. EXTERN(void) jinit_2pass_quantizer JPP((j_decompress_ptr cinfo));
  157532. EXTERN(void) jinit_merged_upsampler JPP((j_decompress_ptr cinfo));
  157533. /* Memory manager initialization */
  157534. EXTERN(void) jinit_memory_mgr JPP((j_common_ptr cinfo));
  157535. /* Utility routines in jutils.c */
  157536. EXTERN(long) jdiv_round_up JPP((long a, long b));
  157537. EXTERN(long) jround_up JPP((long a, long b));
  157538. EXTERN(void) jcopy_sample_rows JPP((JSAMPARRAY input_array, int source_row,
  157539. JSAMPARRAY output_array, int dest_row,
  157540. int num_rows, JDIMENSION num_cols));
  157541. EXTERN(void) jcopy_block_row JPP((JBLOCKROW input_row, JBLOCKROW output_row,
  157542. JDIMENSION num_blocks));
  157543. EXTERN(void) jzero_far JPP((void FAR * target, size_t bytestozero));
  157544. /* Constant tables in jutils.c */
  157545. #if 0 /* This table is not actually needed in v6a */
  157546. extern const int jpeg_zigzag_order[]; /* natural coef order to zigzag order */
  157547. #endif
  157548. extern const int jpeg_natural_order[]; /* zigzag coef order to natural order */
  157549. /* Suppress undefined-structure complaints if necessary. */
  157550. #ifdef INCOMPLETE_TYPES_BROKEN
  157551. #ifndef AM_MEMORY_MANAGER /* only jmemmgr.c defines these */
  157552. struct jvirt_sarray_control { long dummy; };
  157553. struct jvirt_barray_control { long dummy; };
  157554. #endif
  157555. #endif /* INCOMPLETE_TYPES_BROKEN */
  157556. /*** End of inlined file: jpegint.h ***/
  157557. /* fetch private declarations */
  157558. /*** Start of inlined file: jerror.h ***/
  157559. /*
  157560. * To define the enum list of message codes, include this file without
  157561. * defining macro JMESSAGE. To create a message string table, include it
  157562. * again with a suitable JMESSAGE definition (see jerror.c for an example).
  157563. */
  157564. #ifndef JMESSAGE
  157565. #ifndef JERROR_H
  157566. /* First time through, define the enum list */
  157567. #define JMAKE_ENUM_LIST
  157568. #else
  157569. /* Repeated inclusions of this file are no-ops unless JMESSAGE is defined */
  157570. #define JMESSAGE(code,string)
  157571. #endif /* JERROR_H */
  157572. #endif /* JMESSAGE */
  157573. #ifdef JMAKE_ENUM_LIST
  157574. typedef enum {
  157575. #define JMESSAGE(code,string) code ,
  157576. #endif /* JMAKE_ENUM_LIST */
  157577. JMESSAGE(JMSG_NOMESSAGE, "Bogus message code %d") /* Must be first entry! */
  157578. /* For maintenance convenience, list is alphabetical by message code name */
  157579. JMESSAGE(JERR_ARITH_NOTIMPL,
  157580. "Sorry, there are legal restrictions on arithmetic coding")
  157581. JMESSAGE(JERR_BAD_ALIGN_TYPE, "ALIGN_TYPE is wrong, please fix")
  157582. JMESSAGE(JERR_BAD_ALLOC_CHUNK, "MAX_ALLOC_CHUNK is wrong, please fix")
  157583. JMESSAGE(JERR_BAD_BUFFER_MODE, "Bogus buffer control mode")
  157584. JMESSAGE(JERR_BAD_COMPONENT_ID, "Invalid component ID %d in SOS")
  157585. JMESSAGE(JERR_BAD_DCT_COEF, "DCT coefficient out of range")
  157586. JMESSAGE(JERR_BAD_DCTSIZE, "IDCT output block size %d not supported")
  157587. JMESSAGE(JERR_BAD_HUFF_TABLE, "Bogus Huffman table definition")
  157588. JMESSAGE(JERR_BAD_IN_COLORSPACE, "Bogus input colorspace")
  157589. JMESSAGE(JERR_BAD_J_COLORSPACE, "Bogus JPEG colorspace")
  157590. JMESSAGE(JERR_BAD_LENGTH, "Bogus marker length")
  157591. JMESSAGE(JERR_BAD_LIB_VERSION,
  157592. "Wrong JPEG library version: library is %d, caller expects %d")
  157593. JMESSAGE(JERR_BAD_MCU_SIZE, "Sampling factors too large for interleaved scan")
  157594. JMESSAGE(JERR_BAD_POOL_ID, "Invalid memory pool code %d")
  157595. JMESSAGE(JERR_BAD_PRECISION, "Unsupported JPEG data precision %d")
  157596. JMESSAGE(JERR_BAD_PROGRESSION,
  157597. "Invalid progressive parameters Ss=%d Se=%d Ah=%d Al=%d")
  157598. JMESSAGE(JERR_BAD_PROG_SCRIPT,
  157599. "Invalid progressive parameters at scan script entry %d")
  157600. JMESSAGE(JERR_BAD_SAMPLING, "Bogus sampling factors")
  157601. JMESSAGE(JERR_BAD_SCAN_SCRIPT, "Invalid scan script at entry %d")
  157602. JMESSAGE(JERR_BAD_STATE, "Improper call to JPEG library in state %d")
  157603. JMESSAGE(JERR_BAD_STRUCT_SIZE,
  157604. "JPEG parameter struct mismatch: library thinks size is %u, caller expects %u")
  157605. JMESSAGE(JERR_BAD_VIRTUAL_ACCESS, "Bogus virtual array access")
  157606. JMESSAGE(JERR_BUFFER_SIZE, "Buffer passed to JPEG library is too small")
  157607. JMESSAGE(JERR_CANT_SUSPEND, "Suspension not allowed here")
  157608. JMESSAGE(JERR_CCIR601_NOTIMPL, "CCIR601 sampling not implemented yet")
  157609. JMESSAGE(JERR_COMPONENT_COUNT, "Too many color components: %d, max %d")
  157610. JMESSAGE(JERR_CONVERSION_NOTIMPL, "Unsupported color conversion request")
  157611. JMESSAGE(JERR_DAC_INDEX, "Bogus DAC index %d")
  157612. JMESSAGE(JERR_DAC_VALUE, "Bogus DAC value 0x%x")
  157613. JMESSAGE(JERR_DHT_INDEX, "Bogus DHT index %d")
  157614. JMESSAGE(JERR_DQT_INDEX, "Bogus DQT index %d")
  157615. JMESSAGE(JERR_EMPTY_IMAGE, "Empty JPEG image (DNL not supported)")
  157616. JMESSAGE(JERR_EMS_READ, "Read from EMS failed")
  157617. JMESSAGE(JERR_EMS_WRITE, "Write to EMS failed")
  157618. JMESSAGE(JERR_EOI_EXPECTED, "Didn't expect more than one scan")
  157619. JMESSAGE(JERR_FILE_READ, "Input file read error")
  157620. JMESSAGE(JERR_FILE_WRITE, "Output file write error --- out of disk space?")
  157621. JMESSAGE(JERR_FRACT_SAMPLE_NOTIMPL, "Fractional sampling not implemented yet")
  157622. JMESSAGE(JERR_HUFF_CLEN_OVERFLOW, "Huffman code size table overflow")
  157623. JMESSAGE(JERR_HUFF_MISSING_CODE, "Missing Huffman code table entry")
  157624. JMESSAGE(JERR_IMAGE_TOO_BIG, "Maximum supported image dimension is %u pixels")
  157625. JMESSAGE(JERR_INPUT_EMPTY, "Empty input file")
  157626. JMESSAGE(JERR_INPUT_EOF, "Premature end of input file")
  157627. JMESSAGE(JERR_MISMATCHED_QUANT_TABLE,
  157628. "Cannot transcode due to multiple use of quantization table %d")
  157629. JMESSAGE(JERR_MISSING_DATA, "Scan script does not transmit all data")
  157630. JMESSAGE(JERR_MODE_CHANGE, "Invalid color quantization mode change")
  157631. JMESSAGE(JERR_NOTIMPL, "Not implemented yet")
  157632. JMESSAGE(JERR_NOT_COMPILED, "Requested feature was omitted at compile time")
  157633. JMESSAGE(JERR_NO_BACKING_STORE, "Backing store not supported")
  157634. JMESSAGE(JERR_NO_HUFF_TABLE, "Huffman table 0x%02x was not defined")
  157635. JMESSAGE(JERR_NO_IMAGE, "JPEG datastream contains no image")
  157636. JMESSAGE(JERR_NO_QUANT_TABLE, "Quantization table 0x%02x was not defined")
  157637. JMESSAGE(JERR_NO_SOI, "Not a JPEG file: starts with 0x%02x 0x%02x")
  157638. JMESSAGE(JERR_OUT_OF_MEMORY, "Insufficient memory (case %d)")
  157639. JMESSAGE(JERR_QUANT_COMPONENTS,
  157640. "Cannot quantize more than %d color components")
  157641. JMESSAGE(JERR_QUANT_FEW_COLORS, "Cannot quantize to fewer than %d colors")
  157642. JMESSAGE(JERR_QUANT_MANY_COLORS, "Cannot quantize to more than %d colors")
  157643. JMESSAGE(JERR_SOF_DUPLICATE, "Invalid JPEG file structure: two SOF markers")
  157644. JMESSAGE(JERR_SOF_NO_SOS, "Invalid JPEG file structure: missing SOS marker")
  157645. JMESSAGE(JERR_SOF_UNSUPPORTED, "Unsupported JPEG process: SOF type 0x%02x")
  157646. JMESSAGE(JERR_SOI_DUPLICATE, "Invalid JPEG file structure: two SOI markers")
  157647. JMESSAGE(JERR_SOS_NO_SOF, "Invalid JPEG file structure: SOS before SOF")
  157648. JMESSAGE(JERR_TFILE_CREATE, "Failed to create temporary file %s")
  157649. JMESSAGE(JERR_TFILE_READ, "Read failed on temporary file")
  157650. JMESSAGE(JERR_TFILE_SEEK, "Seek failed on temporary file")
  157651. JMESSAGE(JERR_TFILE_WRITE,
  157652. "Write failed on temporary file --- out of disk space?")
  157653. JMESSAGE(JERR_TOO_LITTLE_DATA, "Application transferred too few scanlines")
  157654. JMESSAGE(JERR_UNKNOWN_MARKER, "Unsupported marker type 0x%02x")
  157655. JMESSAGE(JERR_VIRTUAL_BUG, "Virtual array controller messed up")
  157656. JMESSAGE(JERR_WIDTH_OVERFLOW, "Image too wide for this implementation")
  157657. JMESSAGE(JERR_XMS_READ, "Read from XMS failed")
  157658. JMESSAGE(JERR_XMS_WRITE, "Write to XMS failed")
  157659. JMESSAGE(JMSG_COPYRIGHT, JCOPYRIGHT)
  157660. JMESSAGE(JMSG_VERSION, JVERSION)
  157661. JMESSAGE(JTRC_16BIT_TABLES,
  157662. "Caution: quantization tables are too coarse for baseline JPEG")
  157663. JMESSAGE(JTRC_ADOBE,
  157664. "Adobe APP14 marker: version %d, flags 0x%04x 0x%04x, transform %d")
  157665. JMESSAGE(JTRC_APP0, "Unknown APP0 marker (not JFIF), length %u")
  157666. JMESSAGE(JTRC_APP14, "Unknown APP14 marker (not Adobe), length %u")
  157667. JMESSAGE(JTRC_DAC, "Define Arithmetic Table 0x%02x: 0x%02x")
  157668. JMESSAGE(JTRC_DHT, "Define Huffman Table 0x%02x")
  157669. JMESSAGE(JTRC_DQT, "Define Quantization Table %d precision %d")
  157670. JMESSAGE(JTRC_DRI, "Define Restart Interval %u")
  157671. JMESSAGE(JTRC_EMS_CLOSE, "Freed EMS handle %u")
  157672. JMESSAGE(JTRC_EMS_OPEN, "Obtained EMS handle %u")
  157673. JMESSAGE(JTRC_EOI, "End Of Image")
  157674. JMESSAGE(JTRC_HUFFBITS, " %3d %3d %3d %3d %3d %3d %3d %3d")
  157675. JMESSAGE(JTRC_JFIF, "JFIF APP0 marker: version %d.%02d, density %dx%d %d")
  157676. JMESSAGE(JTRC_JFIF_BADTHUMBNAILSIZE,
  157677. "Warning: thumbnail image size does not match data length %u")
  157678. JMESSAGE(JTRC_JFIF_EXTENSION,
  157679. "JFIF extension marker: type 0x%02x, length %u")
  157680. JMESSAGE(JTRC_JFIF_THUMBNAIL, " with %d x %d thumbnail image")
  157681. JMESSAGE(JTRC_MISC_MARKER, "Miscellaneous marker 0x%02x, length %u")
  157682. JMESSAGE(JTRC_PARMLESS_MARKER, "Unexpected marker 0x%02x")
  157683. JMESSAGE(JTRC_QUANTVALS, " %4u %4u %4u %4u %4u %4u %4u %4u")
  157684. JMESSAGE(JTRC_QUANT_3_NCOLORS, "Quantizing to %d = %d*%d*%d colors")
  157685. JMESSAGE(JTRC_QUANT_NCOLORS, "Quantizing to %d colors")
  157686. JMESSAGE(JTRC_QUANT_SELECTED, "Selected %d colors for quantization")
  157687. JMESSAGE(JTRC_RECOVERY_ACTION, "At marker 0x%02x, recovery action %d")
  157688. JMESSAGE(JTRC_RST, "RST%d")
  157689. JMESSAGE(JTRC_SMOOTH_NOTIMPL,
  157690. "Smoothing not supported with nonstandard sampling ratios")
  157691. JMESSAGE(JTRC_SOF, "Start Of Frame 0x%02x: width=%u, height=%u, components=%d")
  157692. JMESSAGE(JTRC_SOF_COMPONENT, " Component %d: %dhx%dv q=%d")
  157693. JMESSAGE(JTRC_SOI, "Start of Image")
  157694. JMESSAGE(JTRC_SOS, "Start Of Scan: %d components")
  157695. JMESSAGE(JTRC_SOS_COMPONENT, " Component %d: dc=%d ac=%d")
  157696. JMESSAGE(JTRC_SOS_PARAMS, " Ss=%d, Se=%d, Ah=%d, Al=%d")
  157697. JMESSAGE(JTRC_TFILE_CLOSE, "Closed temporary file %s")
  157698. JMESSAGE(JTRC_TFILE_OPEN, "Opened temporary file %s")
  157699. JMESSAGE(JTRC_THUMB_JPEG,
  157700. "JFIF extension marker: JPEG-compressed thumbnail image, length %u")
  157701. JMESSAGE(JTRC_THUMB_PALETTE,
  157702. "JFIF extension marker: palette thumbnail image, length %u")
  157703. JMESSAGE(JTRC_THUMB_RGB,
  157704. "JFIF extension marker: RGB thumbnail image, length %u")
  157705. JMESSAGE(JTRC_UNKNOWN_IDS,
  157706. "Unrecognized component IDs %d %d %d, assuming YCbCr")
  157707. JMESSAGE(JTRC_XMS_CLOSE, "Freed XMS handle %u")
  157708. JMESSAGE(JTRC_XMS_OPEN, "Obtained XMS handle %u")
  157709. JMESSAGE(JWRN_ADOBE_XFORM, "Unknown Adobe color transform code %d")
  157710. JMESSAGE(JWRN_BOGUS_PROGRESSION,
  157711. "Inconsistent progression sequence for component %d coefficient %d")
  157712. JMESSAGE(JWRN_EXTRANEOUS_DATA,
  157713. "Corrupt JPEG data: %u extraneous bytes before marker 0x%02x")
  157714. JMESSAGE(JWRN_HIT_MARKER, "Corrupt JPEG data: premature end of data segment")
  157715. JMESSAGE(JWRN_HUFF_BAD_CODE, "Corrupt JPEG data: bad Huffman code")
  157716. JMESSAGE(JWRN_JFIF_MAJOR, "Warning: unknown JFIF revision number %d.%02d")
  157717. JMESSAGE(JWRN_JPEG_EOF, "Premature end of JPEG file")
  157718. JMESSAGE(JWRN_MUST_RESYNC,
  157719. "Corrupt JPEG data: found marker 0x%02x instead of RST%d")
  157720. JMESSAGE(JWRN_NOT_SEQUENTIAL, "Invalid SOS parameters for sequential JPEG")
  157721. JMESSAGE(JWRN_TOO_MUCH_DATA, "Application transferred too many scanlines")
  157722. #ifdef JMAKE_ENUM_LIST
  157723. JMSG_LASTMSGCODE
  157724. } J_MESSAGE_CODE;
  157725. #undef JMAKE_ENUM_LIST
  157726. #endif /* JMAKE_ENUM_LIST */
  157727. /* Zap JMESSAGE macro so that future re-inclusions do nothing by default */
  157728. #undef JMESSAGE
  157729. #ifndef JERROR_H
  157730. #define JERROR_H
  157731. /* Macros to simplify using the error and trace message stuff */
  157732. /* The first parameter is either type of cinfo pointer */
  157733. /* Fatal errors (print message and exit) */
  157734. #define ERREXIT(cinfo,code) \
  157735. ((cinfo)->err->msg_code = (code), \
  157736. (*(cinfo)->err->error_exit) ((j_common_ptr) (cinfo)))
  157737. #define ERREXIT1(cinfo,code,p1) \
  157738. ((cinfo)->err->msg_code = (code), \
  157739. (cinfo)->err->msg_parm.i[0] = (p1), \
  157740. (*(cinfo)->err->error_exit) ((j_common_ptr) (cinfo)))
  157741. #define ERREXIT2(cinfo,code,p1,p2) \
  157742. ((cinfo)->err->msg_code = (code), \
  157743. (cinfo)->err->msg_parm.i[0] = (p1), \
  157744. (cinfo)->err->msg_parm.i[1] = (p2), \
  157745. (*(cinfo)->err->error_exit) ((j_common_ptr) (cinfo)))
  157746. #define ERREXIT3(cinfo,code,p1,p2,p3) \
  157747. ((cinfo)->err->msg_code = (code), \
  157748. (cinfo)->err->msg_parm.i[0] = (p1), \
  157749. (cinfo)->err->msg_parm.i[1] = (p2), \
  157750. (cinfo)->err->msg_parm.i[2] = (p3), \
  157751. (*(cinfo)->err->error_exit) ((j_common_ptr) (cinfo)))
  157752. #define ERREXIT4(cinfo,code,p1,p2,p3,p4) \
  157753. ((cinfo)->err->msg_code = (code), \
  157754. (cinfo)->err->msg_parm.i[0] = (p1), \
  157755. (cinfo)->err->msg_parm.i[1] = (p2), \
  157756. (cinfo)->err->msg_parm.i[2] = (p3), \
  157757. (cinfo)->err->msg_parm.i[3] = (p4), \
  157758. (*(cinfo)->err->error_exit) ((j_common_ptr) (cinfo)))
  157759. #define ERREXITS(cinfo,code,str) \
  157760. ((cinfo)->err->msg_code = (code), \
  157761. strncpy((cinfo)->err->msg_parm.s, (str), JMSG_STR_PARM_MAX), \
  157762. (*(cinfo)->err->error_exit) ((j_common_ptr) (cinfo)))
  157763. #define MAKESTMT(stuff) do { stuff } while (0)
  157764. /* Nonfatal errors (we can keep going, but the data is probably corrupt) */
  157765. #define WARNMS(cinfo,code) \
  157766. ((cinfo)->err->msg_code = (code), \
  157767. (*(cinfo)->err->emit_message) ((j_common_ptr) (cinfo), -1))
  157768. #define WARNMS1(cinfo,code,p1) \
  157769. ((cinfo)->err->msg_code = (code), \
  157770. (cinfo)->err->msg_parm.i[0] = (p1), \
  157771. (*(cinfo)->err->emit_message) ((j_common_ptr) (cinfo), -1))
  157772. #define WARNMS2(cinfo,code,p1,p2) \
  157773. ((cinfo)->err->msg_code = (code), \
  157774. (cinfo)->err->msg_parm.i[0] = (p1), \
  157775. (cinfo)->err->msg_parm.i[1] = (p2), \
  157776. (*(cinfo)->err->emit_message) ((j_common_ptr) (cinfo), -1))
  157777. /* Informational/debugging messages */
  157778. #define TRACEMS(cinfo,lvl,code) \
  157779. ((cinfo)->err->msg_code = (code), \
  157780. (*(cinfo)->err->emit_message) ((j_common_ptr) (cinfo), (lvl)))
  157781. #define TRACEMS1(cinfo,lvl,code,p1) \
  157782. ((cinfo)->err->msg_code = (code), \
  157783. (cinfo)->err->msg_parm.i[0] = (p1), \
  157784. (*(cinfo)->err->emit_message) ((j_common_ptr) (cinfo), (lvl)))
  157785. #define TRACEMS2(cinfo,lvl,code,p1,p2) \
  157786. ((cinfo)->err->msg_code = (code), \
  157787. (cinfo)->err->msg_parm.i[0] = (p1), \
  157788. (cinfo)->err->msg_parm.i[1] = (p2), \
  157789. (*(cinfo)->err->emit_message) ((j_common_ptr) (cinfo), (lvl)))
  157790. #define TRACEMS3(cinfo,lvl,code,p1,p2,p3) \
  157791. MAKESTMT(int * _mp = (cinfo)->err->msg_parm.i; \
  157792. _mp[0] = (p1); _mp[1] = (p2); _mp[2] = (p3); \
  157793. (cinfo)->err->msg_code = (code); \
  157794. (*(cinfo)->err->emit_message) ((j_common_ptr) (cinfo), (lvl)); )
  157795. #define TRACEMS4(cinfo,lvl,code,p1,p2,p3,p4) \
  157796. MAKESTMT(int * _mp = (cinfo)->err->msg_parm.i; \
  157797. _mp[0] = (p1); _mp[1] = (p2); _mp[2] = (p3); _mp[3] = (p4); \
  157798. (cinfo)->err->msg_code = (code); \
  157799. (*(cinfo)->err->emit_message) ((j_common_ptr) (cinfo), (lvl)); )
  157800. #define TRACEMS5(cinfo,lvl,code,p1,p2,p3,p4,p5) \
  157801. MAKESTMT(int * _mp = (cinfo)->err->msg_parm.i; \
  157802. _mp[0] = (p1); _mp[1] = (p2); _mp[2] = (p3); _mp[3] = (p4); \
  157803. _mp[4] = (p5); \
  157804. (cinfo)->err->msg_code = (code); \
  157805. (*(cinfo)->err->emit_message) ((j_common_ptr) (cinfo), (lvl)); )
  157806. #define TRACEMS8(cinfo,lvl,code,p1,p2,p3,p4,p5,p6,p7,p8) \
  157807. MAKESTMT(int * _mp = (cinfo)->err->msg_parm.i; \
  157808. _mp[0] = (p1); _mp[1] = (p2); _mp[2] = (p3); _mp[3] = (p4); \
  157809. _mp[4] = (p5); _mp[5] = (p6); _mp[6] = (p7); _mp[7] = (p8); \
  157810. (cinfo)->err->msg_code = (code); \
  157811. (*(cinfo)->err->emit_message) ((j_common_ptr) (cinfo), (lvl)); )
  157812. #define TRACEMSS(cinfo,lvl,code,str) \
  157813. ((cinfo)->err->msg_code = (code), \
  157814. strncpy((cinfo)->err->msg_parm.s, (str), JMSG_STR_PARM_MAX), \
  157815. (*(cinfo)->err->emit_message) ((j_common_ptr) (cinfo), (lvl)))
  157816. #endif /* JERROR_H */
  157817. /*** End of inlined file: jerror.h ***/
  157818. /* fetch error codes too */
  157819. #endif
  157820. #endif /* JPEGLIB_H */
  157821. /*** End of inlined file: jpeglib.h ***/
  157822. /*** Start of inlined file: jcapimin.c ***/
  157823. #define JPEG_INTERNALS
  157824. /*** Start of inlined file: jinclude.h ***/
  157825. /* Include auto-config file to find out which system include files we need. */
  157826. #ifndef __jinclude_h__
  157827. #define __jinclude_h__
  157828. /*** Start of inlined file: jconfig.h ***/
  157829. /* see jconfig.doc for explanations */
  157830. // disable all the warnings under MSVC
  157831. #ifdef _MSC_VER
  157832. #pragma warning (disable: 4996 4267 4100 4127 4702 4244)
  157833. #endif
  157834. #ifdef __BORLANDC__
  157835. #pragma warn -8057
  157836. #pragma warn -8019
  157837. #pragma warn -8004
  157838. #pragma warn -8008
  157839. #endif
  157840. #define HAVE_PROTOTYPES
  157841. #define HAVE_UNSIGNED_CHAR
  157842. #define HAVE_UNSIGNED_SHORT
  157843. /* #define void char */
  157844. /* #define const */
  157845. #undef CHAR_IS_UNSIGNED
  157846. #define HAVE_STDDEF_H
  157847. #define HAVE_STDLIB_H
  157848. #undef NEED_BSD_STRINGS
  157849. #undef NEED_SYS_TYPES_H
  157850. #undef NEED_FAR_POINTERS /* we presume a 32-bit flat memory model */
  157851. #undef NEED_SHORT_EXTERNAL_NAMES
  157852. #undef INCOMPLETE_TYPES_BROKEN
  157853. /* Define "boolean" as unsigned char, not int, per Windows custom */
  157854. #ifndef __RPCNDR_H__ /* don't conflict if rpcndr.h already read */
  157855. typedef unsigned char boolean;
  157856. #endif
  157857. #define HAVE_BOOLEAN /* prevent jmorecfg.h from redefining it */
  157858. #ifdef JPEG_INTERNALS
  157859. #undef RIGHT_SHIFT_IS_UNSIGNED
  157860. #endif /* JPEG_INTERNALS */
  157861. #ifdef JPEG_CJPEG_DJPEG
  157862. #define BMP_SUPPORTED /* BMP image file format */
  157863. #define GIF_SUPPORTED /* GIF image file format */
  157864. #define PPM_SUPPORTED /* PBMPLUS PPM/PGM image file format */
  157865. #undef RLE_SUPPORTED /* Utah RLE image file format */
  157866. #define TARGA_SUPPORTED /* Targa image file format */
  157867. #define TWO_FILE_COMMANDLINE /* optional */
  157868. #define USE_SETMODE /* Microsoft has setmode() */
  157869. #undef NEED_SIGNAL_CATCHER
  157870. #undef DONT_USE_B_MODE
  157871. #undef PROGRESS_REPORT /* optional */
  157872. #endif /* JPEG_CJPEG_DJPEG */
  157873. /*** End of inlined file: jconfig.h ***/
  157874. /* auto configuration options */
  157875. #define JCONFIG_INCLUDED /* so that jpeglib.h doesn't do it again */
  157876. /*
  157877. * We need the NULL macro and size_t typedef.
  157878. * On an ANSI-conforming system it is sufficient to include <stddef.h>.
  157879. * Otherwise, we get them from <stdlib.h> or <stdio.h>; we may have to
  157880. * pull in <sys/types.h> as well.
  157881. * Note that the core JPEG library does not require <stdio.h>;
  157882. * only the default error handler and data source/destination modules do.
  157883. * But we must pull it in because of the references to FILE in jpeglib.h.
  157884. * You can remove those references if you want to compile without <stdio.h>.
  157885. */
  157886. #ifdef HAVE_STDDEF_H
  157887. #include <stddef.h>
  157888. #endif
  157889. #ifdef HAVE_STDLIB_H
  157890. #include <stdlib.h>
  157891. #endif
  157892. #ifdef NEED_SYS_TYPES_H
  157893. #include <sys/types.h>
  157894. #endif
  157895. #include <stdio.h>
  157896. /*
  157897. * We need memory copying and zeroing functions, plus strncpy().
  157898. * ANSI and System V implementations declare these in <string.h>.
  157899. * BSD doesn't have the mem() functions, but it does have bcopy()/bzero().
  157900. * Some systems may declare memset and memcpy in <memory.h>.
  157901. *
  157902. * NOTE: we assume the size parameters to these functions are of type size_t.
  157903. * Change the casts in these macros if not!
  157904. */
  157905. #ifdef NEED_BSD_STRINGS
  157906. #include <strings.h>
  157907. #define MEMZERO(target,size) bzero((void *)(target), (size_t)(size))
  157908. #define MEMCOPY(dest,src,size) bcopy((const void *)(src), (void *)(dest), (size_t)(size))
  157909. #else /* not BSD, assume ANSI/SysV string lib */
  157910. #include <string.h>
  157911. #define MEMZERO(target,size) memset((void *)(target), 0, (size_t)(size))
  157912. #define MEMCOPY(dest,src,size) memcpy((void *)(dest), (const void *)(src), (size_t)(size))
  157913. #endif
  157914. /*
  157915. * In ANSI C, and indeed any rational implementation, size_t is also the
  157916. * type returned by sizeof(). However, it seems there are some irrational
  157917. * implementations out there, in which sizeof() returns an int even though
  157918. * size_t is defined as long or unsigned long. To ensure consistent results
  157919. * we always use this SIZEOF() macro in place of using sizeof() directly.
  157920. */
  157921. #define SIZEOF(object) ((size_t) sizeof(object))
  157922. /*
  157923. * The modules that use fread() and fwrite() always invoke them through
  157924. * these macros. On some systems you may need to twiddle the argument casts.
  157925. * CAUTION: argument order is different from underlying functions!
  157926. */
  157927. #define JFREAD(file,buf,sizeofbuf) \
  157928. ((size_t) fread((void *) (buf), (size_t) 1, (size_t) (sizeofbuf), (file)))
  157929. #define JFWRITE(file,buf,sizeofbuf) \
  157930. ((size_t) fwrite((const void *) (buf), (size_t) 1, (size_t) (sizeofbuf), (file)))
  157931. typedef enum { /* JPEG marker codes */
  157932. M_SOF0 = 0xc0,
  157933. M_SOF1 = 0xc1,
  157934. M_SOF2 = 0xc2,
  157935. M_SOF3 = 0xc3,
  157936. M_SOF5 = 0xc5,
  157937. M_SOF6 = 0xc6,
  157938. M_SOF7 = 0xc7,
  157939. M_JPG = 0xc8,
  157940. M_SOF9 = 0xc9,
  157941. M_SOF10 = 0xca,
  157942. M_SOF11 = 0xcb,
  157943. M_SOF13 = 0xcd,
  157944. M_SOF14 = 0xce,
  157945. M_SOF15 = 0xcf,
  157946. M_DHT = 0xc4,
  157947. M_DAC = 0xcc,
  157948. M_RST0 = 0xd0,
  157949. M_RST1 = 0xd1,
  157950. M_RST2 = 0xd2,
  157951. M_RST3 = 0xd3,
  157952. M_RST4 = 0xd4,
  157953. M_RST5 = 0xd5,
  157954. M_RST6 = 0xd6,
  157955. M_RST7 = 0xd7,
  157956. M_SOI = 0xd8,
  157957. M_EOI = 0xd9,
  157958. M_SOS = 0xda,
  157959. M_DQT = 0xdb,
  157960. M_DNL = 0xdc,
  157961. M_DRI = 0xdd,
  157962. M_DHP = 0xde,
  157963. M_EXP = 0xdf,
  157964. M_APP0 = 0xe0,
  157965. M_APP1 = 0xe1,
  157966. M_APP2 = 0xe2,
  157967. M_APP3 = 0xe3,
  157968. M_APP4 = 0xe4,
  157969. M_APP5 = 0xe5,
  157970. M_APP6 = 0xe6,
  157971. M_APP7 = 0xe7,
  157972. M_APP8 = 0xe8,
  157973. M_APP9 = 0xe9,
  157974. M_APP10 = 0xea,
  157975. M_APP11 = 0xeb,
  157976. M_APP12 = 0xec,
  157977. M_APP13 = 0xed,
  157978. M_APP14 = 0xee,
  157979. M_APP15 = 0xef,
  157980. M_JPG0 = 0xf0,
  157981. M_JPG13 = 0xfd,
  157982. M_COM = 0xfe,
  157983. M_TEM = 0x01,
  157984. M_ERROR = 0x100
  157985. } JPEG_MARKER;
  157986. /*
  157987. * Figure F.12: extend sign bit.
  157988. * On some machines, a shift and add will be faster than a table lookup.
  157989. */
  157990. #ifdef AVOID_TABLES
  157991. #define HUFF_EXTEND(x,s) ((x) < (1<<((s)-1)) ? (x) + (((-1)<<(s)) + 1) : (x))
  157992. #else
  157993. #define HUFF_EXTEND(x,s) ((x) < extend_test[s] ? (x) + extend_offset[s] : (x))
  157994. static const int extend_test[16] = /* entry n is 2**(n-1) */
  157995. { 0, 0x0001, 0x0002, 0x0004, 0x0008, 0x0010, 0x0020, 0x0040, 0x0080,
  157996. 0x0100, 0x0200, 0x0400, 0x0800, 0x1000, 0x2000, 0x4000 };
  157997. static const int extend_offset[16] = /* entry n is (-1 << n) + 1 */
  157998. { 0, ((-1)<<1) + 1, ((-1)<<2) + 1, ((-1)<<3) + 1, ((-1)<<4) + 1,
  157999. ((-1)<<5) + 1, ((-1)<<6) + 1, ((-1)<<7) + 1, ((-1)<<8) + 1,
  158000. ((-1)<<9) + 1, ((-1)<<10) + 1, ((-1)<<11) + 1, ((-1)<<12) + 1,
  158001. ((-1)<<13) + 1, ((-1)<<14) + 1, ((-1)<<15) + 1 };
  158002. #endif /* AVOID_TABLES */
  158003. #endif
  158004. /*** End of inlined file: jinclude.h ***/
  158005. /*
  158006. * Initialization of a JPEG compression object.
  158007. * The error manager must already be set up (in case memory manager fails).
  158008. */
  158009. GLOBAL(void)
  158010. jpeg_CreateCompress (j_compress_ptr cinfo, int version, size_t structsize)
  158011. {
  158012. int i;
  158013. /* Guard against version mismatches between library and caller. */
  158014. cinfo->mem = NULL; /* so jpeg_destroy knows mem mgr not called */
  158015. if (version != JPEG_LIB_VERSION)
  158016. ERREXIT2(cinfo, JERR_BAD_LIB_VERSION, JPEG_LIB_VERSION, version);
  158017. if (structsize != SIZEOF(struct jpeg_compress_struct))
  158018. ERREXIT2(cinfo, JERR_BAD_STRUCT_SIZE,
  158019. (int) SIZEOF(struct jpeg_compress_struct), (int) structsize);
  158020. /* For debugging purposes, we zero the whole master structure.
  158021. * But the application has already set the err pointer, and may have set
  158022. * client_data, so we have to save and restore those fields.
  158023. * Note: if application hasn't set client_data, tools like Purify may
  158024. * complain here.
  158025. */
  158026. {
  158027. struct jpeg_error_mgr * err = cinfo->err;
  158028. void * client_data = cinfo->client_data; /* ignore Purify complaint here */
  158029. MEMZERO(cinfo, SIZEOF(struct jpeg_compress_struct));
  158030. cinfo->err = err;
  158031. cinfo->client_data = client_data;
  158032. }
  158033. cinfo->is_decompressor = FALSE;
  158034. /* Initialize a memory manager instance for this object */
  158035. jinit_memory_mgr((j_common_ptr) cinfo);
  158036. /* Zero out pointers to permanent structures. */
  158037. cinfo->progress = NULL;
  158038. cinfo->dest = NULL;
  158039. cinfo->comp_info = NULL;
  158040. for (i = 0; i < NUM_QUANT_TBLS; i++)
  158041. cinfo->quant_tbl_ptrs[i] = NULL;
  158042. for (i = 0; i < NUM_HUFF_TBLS; i++) {
  158043. cinfo->dc_huff_tbl_ptrs[i] = NULL;
  158044. cinfo->ac_huff_tbl_ptrs[i] = NULL;
  158045. }
  158046. cinfo->script_space = NULL;
  158047. cinfo->input_gamma = 1.0; /* in case application forgets */
  158048. /* OK, I'm ready */
  158049. cinfo->global_state = CSTATE_START;
  158050. }
  158051. /*
  158052. * Destruction of a JPEG compression object
  158053. */
  158054. GLOBAL(void)
  158055. jpeg_destroy_compress (j_compress_ptr cinfo)
  158056. {
  158057. jpeg_destroy((j_common_ptr) cinfo); /* use common routine */
  158058. }
  158059. /*
  158060. * Abort processing of a JPEG compression operation,
  158061. * but don't destroy the object itself.
  158062. */
  158063. GLOBAL(void)
  158064. jpeg_abort_compress (j_compress_ptr cinfo)
  158065. {
  158066. jpeg_abort((j_common_ptr) cinfo); /* use common routine */
  158067. }
  158068. /*
  158069. * Forcibly suppress or un-suppress all quantization and Huffman tables.
  158070. * Marks all currently defined tables as already written (if suppress)
  158071. * or not written (if !suppress). This will control whether they get emitted
  158072. * by a subsequent jpeg_start_compress call.
  158073. *
  158074. * This routine is exported for use by applications that want to produce
  158075. * abbreviated JPEG datastreams. It logically belongs in jcparam.c, but
  158076. * since it is called by jpeg_start_compress, we put it here --- otherwise
  158077. * jcparam.o would be linked whether the application used it or not.
  158078. */
  158079. GLOBAL(void)
  158080. jpeg_suppress_tables (j_compress_ptr cinfo, boolean suppress)
  158081. {
  158082. int i;
  158083. JQUANT_TBL * qtbl;
  158084. JHUFF_TBL * htbl;
  158085. for (i = 0; i < NUM_QUANT_TBLS; i++) {
  158086. if ((qtbl = cinfo->quant_tbl_ptrs[i]) != NULL)
  158087. qtbl->sent_table = suppress;
  158088. }
  158089. for (i = 0; i < NUM_HUFF_TBLS; i++) {
  158090. if ((htbl = cinfo->dc_huff_tbl_ptrs[i]) != NULL)
  158091. htbl->sent_table = suppress;
  158092. if ((htbl = cinfo->ac_huff_tbl_ptrs[i]) != NULL)
  158093. htbl->sent_table = suppress;
  158094. }
  158095. }
  158096. /*
  158097. * Finish JPEG compression.
  158098. *
  158099. * If a multipass operating mode was selected, this may do a great deal of
  158100. * work including most of the actual output.
  158101. */
  158102. GLOBAL(void)
  158103. jpeg_finish_compress (j_compress_ptr cinfo)
  158104. {
  158105. JDIMENSION iMCU_row;
  158106. if (cinfo->global_state == CSTATE_SCANNING ||
  158107. cinfo->global_state == CSTATE_RAW_OK) {
  158108. /* Terminate first pass */
  158109. if (cinfo->next_scanline < cinfo->image_height)
  158110. ERREXIT(cinfo, JERR_TOO_LITTLE_DATA);
  158111. (*cinfo->master->finish_pass) (cinfo);
  158112. } else if (cinfo->global_state != CSTATE_WRCOEFS)
  158113. ERREXIT1(cinfo, JERR_BAD_STATE, cinfo->global_state);
  158114. /* Perform any remaining passes */
  158115. while (! cinfo->master->is_last_pass) {
  158116. (*cinfo->master->prepare_for_pass) (cinfo);
  158117. for (iMCU_row = 0; iMCU_row < cinfo->total_iMCU_rows; iMCU_row++) {
  158118. if (cinfo->progress != NULL) {
  158119. cinfo->progress->pass_counter = (long) iMCU_row;
  158120. cinfo->progress->pass_limit = (long) cinfo->total_iMCU_rows;
  158121. (*cinfo->progress->progress_monitor) ((j_common_ptr) cinfo);
  158122. }
  158123. /* We bypass the main controller and invoke coef controller directly;
  158124. * all work is being done from the coefficient buffer.
  158125. */
  158126. if (! (*cinfo->coef->compress_data) (cinfo, (JSAMPIMAGE) NULL))
  158127. ERREXIT(cinfo, JERR_CANT_SUSPEND);
  158128. }
  158129. (*cinfo->master->finish_pass) (cinfo);
  158130. }
  158131. /* Write EOI, do final cleanup */
  158132. (*cinfo->marker->write_file_trailer) (cinfo);
  158133. (*cinfo->dest->term_destination) (cinfo);
  158134. /* We can use jpeg_abort to release memory and reset global_state */
  158135. jpeg_abort((j_common_ptr) cinfo);
  158136. }
  158137. /*
  158138. * Write a special marker.
  158139. * This is only recommended for writing COM or APPn markers.
  158140. * Must be called after jpeg_start_compress() and before
  158141. * first call to jpeg_write_scanlines() or jpeg_write_raw_data().
  158142. */
  158143. GLOBAL(void)
  158144. jpeg_write_marker (j_compress_ptr cinfo, int marker,
  158145. const JOCTET *dataptr, unsigned int datalen)
  158146. {
  158147. JMETHOD(void, write_marker_byte, (j_compress_ptr info, int val));
  158148. if (cinfo->next_scanline != 0 ||
  158149. (cinfo->global_state != CSTATE_SCANNING &&
  158150. cinfo->global_state != CSTATE_RAW_OK &&
  158151. cinfo->global_state != CSTATE_WRCOEFS))
  158152. ERREXIT1(cinfo, JERR_BAD_STATE, cinfo->global_state);
  158153. (*cinfo->marker->write_marker_header) (cinfo, marker, datalen);
  158154. write_marker_byte = cinfo->marker->write_marker_byte; /* copy for speed */
  158155. while (datalen--) {
  158156. (*write_marker_byte) (cinfo, *dataptr);
  158157. dataptr++;
  158158. }
  158159. }
  158160. /* Same, but piecemeal. */
  158161. GLOBAL(void)
  158162. jpeg_write_m_header (j_compress_ptr cinfo, int marker, unsigned int datalen)
  158163. {
  158164. if (cinfo->next_scanline != 0 ||
  158165. (cinfo->global_state != CSTATE_SCANNING &&
  158166. cinfo->global_state != CSTATE_RAW_OK &&
  158167. cinfo->global_state != CSTATE_WRCOEFS))
  158168. ERREXIT1(cinfo, JERR_BAD_STATE, cinfo->global_state);
  158169. (*cinfo->marker->write_marker_header) (cinfo, marker, datalen);
  158170. }
  158171. GLOBAL(void)
  158172. jpeg_write_m_byte (j_compress_ptr cinfo, int val)
  158173. {
  158174. (*cinfo->marker->write_marker_byte) (cinfo, val);
  158175. }
  158176. /*
  158177. * Alternate compression function: just write an abbreviated table file.
  158178. * Before calling this, all parameters and a data destination must be set up.
  158179. *
  158180. * To produce a pair of files containing abbreviated tables and abbreviated
  158181. * image data, one would proceed as follows:
  158182. *
  158183. * initialize JPEG object
  158184. * set JPEG parameters
  158185. * set destination to table file
  158186. * jpeg_write_tables(cinfo);
  158187. * set destination to image file
  158188. * jpeg_start_compress(cinfo, FALSE);
  158189. * write data...
  158190. * jpeg_finish_compress(cinfo);
  158191. *
  158192. * jpeg_write_tables has the side effect of marking all tables written
  158193. * (same as jpeg_suppress_tables(..., TRUE)). Thus a subsequent start_compress
  158194. * will not re-emit the tables unless it is passed write_all_tables=TRUE.
  158195. */
  158196. GLOBAL(void)
  158197. jpeg_write_tables (j_compress_ptr cinfo)
  158198. {
  158199. if (cinfo->global_state != CSTATE_START)
  158200. ERREXIT1(cinfo, JERR_BAD_STATE, cinfo->global_state);
  158201. /* (Re)initialize error mgr and destination modules */
  158202. (*cinfo->err->reset_error_mgr) ((j_common_ptr) cinfo);
  158203. (*cinfo->dest->init_destination) (cinfo);
  158204. /* Initialize the marker writer ... bit of a crock to do it here. */
  158205. jinit_marker_writer(cinfo);
  158206. /* Write them tables! */
  158207. (*cinfo->marker->write_tables_only) (cinfo);
  158208. /* And clean up. */
  158209. (*cinfo->dest->term_destination) (cinfo);
  158210. /*
  158211. * In library releases up through v6a, we called jpeg_abort() here to free
  158212. * any working memory allocated by the destination manager and marker
  158213. * writer. Some applications had a problem with that: they allocated space
  158214. * of their own from the library memory manager, and didn't want it to go
  158215. * away during write_tables. So now we do nothing. This will cause a
  158216. * memory leak if an app calls write_tables repeatedly without doing a full
  158217. * compression cycle or otherwise resetting the JPEG object. However, that
  158218. * seems less bad than unexpectedly freeing memory in the normal case.
  158219. * An app that prefers the old behavior can call jpeg_abort for itself after
  158220. * each call to jpeg_write_tables().
  158221. */
  158222. }
  158223. /*** End of inlined file: jcapimin.c ***/
  158224. /*** Start of inlined file: jcapistd.c ***/
  158225. #define JPEG_INTERNALS
  158226. /*
  158227. * Compression initialization.
  158228. * Before calling this, all parameters and a data destination must be set up.
  158229. *
  158230. * We require a write_all_tables parameter as a failsafe check when writing
  158231. * multiple datastreams from the same compression object. Since prior runs
  158232. * will have left all the tables marked sent_table=TRUE, a subsequent run
  158233. * would emit an abbreviated stream (no tables) by default. This may be what
  158234. * is wanted, but for safety's sake it should not be the default behavior:
  158235. * programmers should have to make a deliberate choice to emit abbreviated
  158236. * images. Therefore the documentation and examples should encourage people
  158237. * to pass write_all_tables=TRUE; then it will take active thought to do the
  158238. * wrong thing.
  158239. */
  158240. GLOBAL(void)
  158241. jpeg_start_compress (j_compress_ptr cinfo, boolean write_all_tables)
  158242. {
  158243. if (cinfo->global_state != CSTATE_START)
  158244. ERREXIT1(cinfo, JERR_BAD_STATE, cinfo->global_state);
  158245. if (write_all_tables)
  158246. jpeg_suppress_tables(cinfo, FALSE); /* mark all tables to be written */
  158247. /* (Re)initialize error mgr and destination modules */
  158248. (*cinfo->err->reset_error_mgr) ((j_common_ptr) cinfo);
  158249. (*cinfo->dest->init_destination) (cinfo);
  158250. /* Perform master selection of active modules */
  158251. jinit_compress_master(cinfo);
  158252. /* Set up for the first pass */
  158253. (*cinfo->master->prepare_for_pass) (cinfo);
  158254. /* Ready for application to drive first pass through jpeg_write_scanlines
  158255. * or jpeg_write_raw_data.
  158256. */
  158257. cinfo->next_scanline = 0;
  158258. cinfo->global_state = (cinfo->raw_data_in ? CSTATE_RAW_OK : CSTATE_SCANNING);
  158259. }
  158260. /*
  158261. * Write some scanlines of data to the JPEG compressor.
  158262. *
  158263. * The return value will be the number of lines actually written.
  158264. * This should be less than the supplied num_lines only in case that
  158265. * the data destination module has requested suspension of the compressor,
  158266. * or if more than image_height scanlines are passed in.
  158267. *
  158268. * Note: we warn about excess calls to jpeg_write_scanlines() since
  158269. * this likely signals an application programmer error. However,
  158270. * excess scanlines passed in the last valid call are *silently* ignored,
  158271. * so that the application need not adjust num_lines for end-of-image
  158272. * when using a multiple-scanline buffer.
  158273. */
  158274. GLOBAL(JDIMENSION)
  158275. jpeg_write_scanlines (j_compress_ptr cinfo, JSAMPARRAY scanlines,
  158276. JDIMENSION num_lines)
  158277. {
  158278. JDIMENSION row_ctr, rows_left;
  158279. if (cinfo->global_state != CSTATE_SCANNING)
  158280. ERREXIT1(cinfo, JERR_BAD_STATE, cinfo->global_state);
  158281. if (cinfo->next_scanline >= cinfo->image_height)
  158282. WARNMS(cinfo, JWRN_TOO_MUCH_DATA);
  158283. /* Call progress monitor hook if present */
  158284. if (cinfo->progress != NULL) {
  158285. cinfo->progress->pass_counter = (long) cinfo->next_scanline;
  158286. cinfo->progress->pass_limit = (long) cinfo->image_height;
  158287. (*cinfo->progress->progress_monitor) ((j_common_ptr) cinfo);
  158288. }
  158289. /* Give master control module another chance if this is first call to
  158290. * jpeg_write_scanlines. This lets output of the frame/scan headers be
  158291. * delayed so that application can write COM, etc, markers between
  158292. * jpeg_start_compress and jpeg_write_scanlines.
  158293. */
  158294. if (cinfo->master->call_pass_startup)
  158295. (*cinfo->master->pass_startup) (cinfo);
  158296. /* Ignore any extra scanlines at bottom of image. */
  158297. rows_left = cinfo->image_height - cinfo->next_scanline;
  158298. if (num_lines > rows_left)
  158299. num_lines = rows_left;
  158300. row_ctr = 0;
  158301. (*cinfo->main->process_data) (cinfo, scanlines, &row_ctr, num_lines);
  158302. cinfo->next_scanline += row_ctr;
  158303. return row_ctr;
  158304. }
  158305. /*
  158306. * Alternate entry point to write raw data.
  158307. * Processes exactly one iMCU row per call, unless suspended.
  158308. */
  158309. GLOBAL(JDIMENSION)
  158310. jpeg_write_raw_data (j_compress_ptr cinfo, JSAMPIMAGE data,
  158311. JDIMENSION num_lines)
  158312. {
  158313. JDIMENSION lines_per_iMCU_row;
  158314. if (cinfo->global_state != CSTATE_RAW_OK)
  158315. ERREXIT1(cinfo, JERR_BAD_STATE, cinfo->global_state);
  158316. if (cinfo->next_scanline >= cinfo->image_height) {
  158317. WARNMS(cinfo, JWRN_TOO_MUCH_DATA);
  158318. return 0;
  158319. }
  158320. /* Call progress monitor hook if present */
  158321. if (cinfo->progress != NULL) {
  158322. cinfo->progress->pass_counter = (long) cinfo->next_scanline;
  158323. cinfo->progress->pass_limit = (long) cinfo->image_height;
  158324. (*cinfo->progress->progress_monitor) ((j_common_ptr) cinfo);
  158325. }
  158326. /* Give master control module another chance if this is first call to
  158327. * jpeg_write_raw_data. This lets output of the frame/scan headers be
  158328. * delayed so that application can write COM, etc, markers between
  158329. * jpeg_start_compress and jpeg_write_raw_data.
  158330. */
  158331. if (cinfo->master->call_pass_startup)
  158332. (*cinfo->master->pass_startup) (cinfo);
  158333. /* Verify that at least one iMCU row has been passed. */
  158334. lines_per_iMCU_row = cinfo->max_v_samp_factor * DCTSIZE;
  158335. if (num_lines < lines_per_iMCU_row)
  158336. ERREXIT(cinfo, JERR_BUFFER_SIZE);
  158337. /* Directly compress the row. */
  158338. if (! (*cinfo->coef->compress_data) (cinfo, data)) {
  158339. /* If compressor did not consume the whole row, suspend processing. */
  158340. return 0;
  158341. }
  158342. /* OK, we processed one iMCU row. */
  158343. cinfo->next_scanline += lines_per_iMCU_row;
  158344. return lines_per_iMCU_row;
  158345. }
  158346. /*** End of inlined file: jcapistd.c ***/
  158347. /*** Start of inlined file: jccoefct.c ***/
  158348. #define JPEG_INTERNALS
  158349. /* We use a full-image coefficient buffer when doing Huffman optimization,
  158350. * and also for writing multiple-scan JPEG files. In all cases, the DCT
  158351. * step is run during the first pass, and subsequent passes need only read
  158352. * the buffered coefficients.
  158353. */
  158354. #ifdef ENTROPY_OPT_SUPPORTED
  158355. #define FULL_COEF_BUFFER_SUPPORTED
  158356. #else
  158357. #ifdef C_MULTISCAN_FILES_SUPPORTED
  158358. #define FULL_COEF_BUFFER_SUPPORTED
  158359. #endif
  158360. #endif
  158361. /* Private buffer controller object */
  158362. typedef struct {
  158363. struct jpeg_c_coef_controller pub; /* public fields */
  158364. JDIMENSION iMCU_row_num; /* iMCU row # within image */
  158365. JDIMENSION mcu_ctr; /* counts MCUs processed in current row */
  158366. int MCU_vert_offset; /* counts MCU rows within iMCU row */
  158367. int MCU_rows_per_iMCU_row; /* number of such rows needed */
  158368. /* For single-pass compression, it's sufficient to buffer just one MCU
  158369. * (although this may prove a bit slow in practice). We allocate a
  158370. * workspace of C_MAX_BLOCKS_IN_MCU coefficient blocks, and reuse it for each
  158371. * MCU constructed and sent. (On 80x86, the workspace is FAR even though
  158372. * it's not really very big; this is to keep the module interfaces unchanged
  158373. * when a large coefficient buffer is necessary.)
  158374. * In multi-pass modes, this array points to the current MCU's blocks
  158375. * within the virtual arrays.
  158376. */
  158377. JBLOCKROW MCU_buffer[C_MAX_BLOCKS_IN_MCU];
  158378. /* In multi-pass modes, we need a virtual block array for each component. */
  158379. jvirt_barray_ptr whole_image[MAX_COMPONENTS];
  158380. } my_coef_controller;
  158381. typedef my_coef_controller * my_coef_ptr;
  158382. /* Forward declarations */
  158383. METHODDEF(boolean) compress_data
  158384. JPP((j_compress_ptr cinfo, JSAMPIMAGE input_buf));
  158385. #ifdef FULL_COEF_BUFFER_SUPPORTED
  158386. METHODDEF(boolean) compress_first_pass
  158387. JPP((j_compress_ptr cinfo, JSAMPIMAGE input_buf));
  158388. METHODDEF(boolean) compress_output
  158389. JPP((j_compress_ptr cinfo, JSAMPIMAGE input_buf));
  158390. #endif
  158391. LOCAL(void)
  158392. start_iMCU_row (j_compress_ptr cinfo)
  158393. /* Reset within-iMCU-row counters for a new row */
  158394. {
  158395. my_coef_ptr coef = (my_coef_ptr) cinfo->coef;
  158396. /* In an interleaved scan, an MCU row is the same as an iMCU row.
  158397. * In a noninterleaved scan, an iMCU row has v_samp_factor MCU rows.
  158398. * But at the bottom of the image, process only what's left.
  158399. */
  158400. if (cinfo->comps_in_scan > 1) {
  158401. coef->MCU_rows_per_iMCU_row = 1;
  158402. } else {
  158403. if (coef->iMCU_row_num < (cinfo->total_iMCU_rows-1))
  158404. coef->MCU_rows_per_iMCU_row = cinfo->cur_comp_info[0]->v_samp_factor;
  158405. else
  158406. coef->MCU_rows_per_iMCU_row = cinfo->cur_comp_info[0]->last_row_height;
  158407. }
  158408. coef->mcu_ctr = 0;
  158409. coef->MCU_vert_offset = 0;
  158410. }
  158411. /*
  158412. * Initialize for a processing pass.
  158413. */
  158414. METHODDEF(void)
  158415. start_pass_coef (j_compress_ptr cinfo, J_BUF_MODE pass_mode)
  158416. {
  158417. my_coef_ptr coef = (my_coef_ptr) cinfo->coef;
  158418. coef->iMCU_row_num = 0;
  158419. start_iMCU_row(cinfo);
  158420. switch (pass_mode) {
  158421. case JBUF_PASS_THRU:
  158422. if (coef->whole_image[0] != NULL)
  158423. ERREXIT(cinfo, JERR_BAD_BUFFER_MODE);
  158424. coef->pub.compress_data = compress_data;
  158425. break;
  158426. #ifdef FULL_COEF_BUFFER_SUPPORTED
  158427. case JBUF_SAVE_AND_PASS:
  158428. if (coef->whole_image[0] == NULL)
  158429. ERREXIT(cinfo, JERR_BAD_BUFFER_MODE);
  158430. coef->pub.compress_data = compress_first_pass;
  158431. break;
  158432. case JBUF_CRANK_DEST:
  158433. if (coef->whole_image[0] == NULL)
  158434. ERREXIT(cinfo, JERR_BAD_BUFFER_MODE);
  158435. coef->pub.compress_data = compress_output;
  158436. break;
  158437. #endif
  158438. default:
  158439. ERREXIT(cinfo, JERR_BAD_BUFFER_MODE);
  158440. break;
  158441. }
  158442. }
  158443. /*
  158444. * Process some data in the single-pass case.
  158445. * We process the equivalent of one fully interleaved MCU row ("iMCU" row)
  158446. * per call, ie, v_samp_factor block rows for each component in the image.
  158447. * Returns TRUE if the iMCU row is completed, FALSE if suspended.
  158448. *
  158449. * NB: input_buf contains a plane for each component in image,
  158450. * which we index according to the component's SOF position.
  158451. */
  158452. METHODDEF(boolean)
  158453. compress_data (j_compress_ptr cinfo, JSAMPIMAGE input_buf)
  158454. {
  158455. my_coef_ptr coef = (my_coef_ptr) cinfo->coef;
  158456. JDIMENSION MCU_col_num; /* index of current MCU within row */
  158457. JDIMENSION last_MCU_col = cinfo->MCUs_per_row - 1;
  158458. JDIMENSION last_iMCU_row = cinfo->total_iMCU_rows - 1;
  158459. int blkn, bi, ci, yindex, yoffset, blockcnt;
  158460. JDIMENSION ypos, xpos;
  158461. jpeg_component_info *compptr;
  158462. /* Loop to write as much as one whole iMCU row */
  158463. for (yoffset = coef->MCU_vert_offset; yoffset < coef->MCU_rows_per_iMCU_row;
  158464. yoffset++) {
  158465. for (MCU_col_num = coef->mcu_ctr; MCU_col_num <= last_MCU_col;
  158466. MCU_col_num++) {
  158467. /* Determine where data comes from in input_buf and do the DCT thing.
  158468. * Each call on forward_DCT processes a horizontal row of DCT blocks
  158469. * as wide as an MCU; we rely on having allocated the MCU_buffer[] blocks
  158470. * sequentially. Dummy blocks at the right or bottom edge are filled in
  158471. * specially. The data in them does not matter for image reconstruction,
  158472. * so we fill them with values that will encode to the smallest amount of
  158473. * data, viz: all zeroes in the AC entries, DC entries equal to previous
  158474. * block's DC value. (Thanks to Thomas Kinsman for this idea.)
  158475. */
  158476. blkn = 0;
  158477. for (ci = 0; ci < cinfo->comps_in_scan; ci++) {
  158478. compptr = cinfo->cur_comp_info[ci];
  158479. blockcnt = (MCU_col_num < last_MCU_col) ? compptr->MCU_width
  158480. : compptr->last_col_width;
  158481. xpos = MCU_col_num * compptr->MCU_sample_width;
  158482. ypos = yoffset * DCTSIZE; /* ypos == (yoffset+yindex) * DCTSIZE */
  158483. for (yindex = 0; yindex < compptr->MCU_height; yindex++) {
  158484. if (coef->iMCU_row_num < last_iMCU_row ||
  158485. yoffset+yindex < compptr->last_row_height) {
  158486. (*cinfo->fdct->forward_DCT) (cinfo, compptr,
  158487. input_buf[compptr->component_index],
  158488. coef->MCU_buffer[blkn],
  158489. ypos, xpos, (JDIMENSION) blockcnt);
  158490. if (blockcnt < compptr->MCU_width) {
  158491. /* Create some dummy blocks at the right edge of the image. */
  158492. jzero_far((void FAR *) coef->MCU_buffer[blkn + blockcnt],
  158493. (compptr->MCU_width - blockcnt) * SIZEOF(JBLOCK));
  158494. for (bi = blockcnt; bi < compptr->MCU_width; bi++) {
  158495. coef->MCU_buffer[blkn+bi][0][0] = coef->MCU_buffer[blkn+bi-1][0][0];
  158496. }
  158497. }
  158498. } else {
  158499. /* Create a row of dummy blocks at the bottom of the image. */
  158500. jzero_far((void FAR *) coef->MCU_buffer[blkn],
  158501. compptr->MCU_width * SIZEOF(JBLOCK));
  158502. for (bi = 0; bi < compptr->MCU_width; bi++) {
  158503. coef->MCU_buffer[blkn+bi][0][0] = coef->MCU_buffer[blkn-1][0][0];
  158504. }
  158505. }
  158506. blkn += compptr->MCU_width;
  158507. ypos += DCTSIZE;
  158508. }
  158509. }
  158510. /* Try to write the MCU. In event of a suspension failure, we will
  158511. * re-DCT the MCU on restart (a bit inefficient, could be fixed...)
  158512. */
  158513. if (! (*cinfo->entropy->encode_mcu) (cinfo, coef->MCU_buffer)) {
  158514. /* Suspension forced; update state counters and exit */
  158515. coef->MCU_vert_offset = yoffset;
  158516. coef->mcu_ctr = MCU_col_num;
  158517. return FALSE;
  158518. }
  158519. }
  158520. /* Completed an MCU row, but perhaps not an iMCU row */
  158521. coef->mcu_ctr = 0;
  158522. }
  158523. /* Completed the iMCU row, advance counters for next one */
  158524. coef->iMCU_row_num++;
  158525. start_iMCU_row(cinfo);
  158526. return TRUE;
  158527. }
  158528. #ifdef FULL_COEF_BUFFER_SUPPORTED
  158529. /*
  158530. * Process some data in the first pass of a multi-pass case.
  158531. * We process the equivalent of one fully interleaved MCU row ("iMCU" row)
  158532. * per call, ie, v_samp_factor block rows for each component in the image.
  158533. * This amount of data is read from the source buffer, DCT'd and quantized,
  158534. * and saved into the virtual arrays. We also generate suitable dummy blocks
  158535. * as needed at the right and lower edges. (The dummy blocks are constructed
  158536. * in the virtual arrays, which have been padded appropriately.) This makes
  158537. * it possible for subsequent passes not to worry about real vs. dummy blocks.
  158538. *
  158539. * We must also emit the data to the entropy encoder. This is conveniently
  158540. * done by calling compress_output() after we've loaded the current strip
  158541. * of the virtual arrays.
  158542. *
  158543. * NB: input_buf contains a plane for each component in image. All
  158544. * components are DCT'd and loaded into the virtual arrays in this pass.
  158545. * However, it may be that only a subset of the components are emitted to
  158546. * the entropy encoder during this first pass; be careful about looking
  158547. * at the scan-dependent variables (MCU dimensions, etc).
  158548. */
  158549. METHODDEF(boolean)
  158550. compress_first_pass (j_compress_ptr cinfo, JSAMPIMAGE input_buf)
  158551. {
  158552. my_coef_ptr coef = (my_coef_ptr) cinfo->coef;
  158553. JDIMENSION last_iMCU_row = cinfo->total_iMCU_rows - 1;
  158554. JDIMENSION blocks_across, MCUs_across, MCUindex;
  158555. int bi, ci, h_samp_factor, block_row, block_rows, ndummy;
  158556. JCOEF lastDC;
  158557. jpeg_component_info *compptr;
  158558. JBLOCKARRAY buffer;
  158559. JBLOCKROW thisblockrow, lastblockrow;
  158560. for (ci = 0, compptr = cinfo->comp_info; ci < cinfo->num_components;
  158561. ci++, compptr++) {
  158562. /* Align the virtual buffer for this component. */
  158563. buffer = (*cinfo->mem->access_virt_barray)
  158564. ((j_common_ptr) cinfo, coef->whole_image[ci],
  158565. coef->iMCU_row_num * compptr->v_samp_factor,
  158566. (JDIMENSION) compptr->v_samp_factor, TRUE);
  158567. /* Count non-dummy DCT block rows in this iMCU row. */
  158568. if (coef->iMCU_row_num < last_iMCU_row)
  158569. block_rows = compptr->v_samp_factor;
  158570. else {
  158571. /* NB: can't use last_row_height here, since may not be set! */
  158572. block_rows = (int) (compptr->height_in_blocks % compptr->v_samp_factor);
  158573. if (block_rows == 0) block_rows = compptr->v_samp_factor;
  158574. }
  158575. blocks_across = compptr->width_in_blocks;
  158576. h_samp_factor = compptr->h_samp_factor;
  158577. /* Count number of dummy blocks to be added at the right margin. */
  158578. ndummy = (int) (blocks_across % h_samp_factor);
  158579. if (ndummy > 0)
  158580. ndummy = h_samp_factor - ndummy;
  158581. /* Perform DCT for all non-dummy blocks in this iMCU row. Each call
  158582. * on forward_DCT processes a complete horizontal row of DCT blocks.
  158583. */
  158584. for (block_row = 0; block_row < block_rows; block_row++) {
  158585. thisblockrow = buffer[block_row];
  158586. (*cinfo->fdct->forward_DCT) (cinfo, compptr,
  158587. input_buf[ci], thisblockrow,
  158588. (JDIMENSION) (block_row * DCTSIZE),
  158589. (JDIMENSION) 0, blocks_across);
  158590. if (ndummy > 0) {
  158591. /* Create dummy blocks at the right edge of the image. */
  158592. thisblockrow += blocks_across; /* => first dummy block */
  158593. jzero_far((void FAR *) thisblockrow, ndummy * SIZEOF(JBLOCK));
  158594. lastDC = thisblockrow[-1][0];
  158595. for (bi = 0; bi < ndummy; bi++) {
  158596. thisblockrow[bi][0] = lastDC;
  158597. }
  158598. }
  158599. }
  158600. /* If at end of image, create dummy block rows as needed.
  158601. * The tricky part here is that within each MCU, we want the DC values
  158602. * of the dummy blocks to match the last real block's DC value.
  158603. * This squeezes a few more bytes out of the resulting file...
  158604. */
  158605. if (coef->iMCU_row_num == last_iMCU_row) {
  158606. blocks_across += ndummy; /* include lower right corner */
  158607. MCUs_across = blocks_across / h_samp_factor;
  158608. for (block_row = block_rows; block_row < compptr->v_samp_factor;
  158609. block_row++) {
  158610. thisblockrow = buffer[block_row];
  158611. lastblockrow = buffer[block_row-1];
  158612. jzero_far((void FAR *) thisblockrow,
  158613. (size_t) (blocks_across * SIZEOF(JBLOCK)));
  158614. for (MCUindex = 0; MCUindex < MCUs_across; MCUindex++) {
  158615. lastDC = lastblockrow[h_samp_factor-1][0];
  158616. for (bi = 0; bi < h_samp_factor; bi++) {
  158617. thisblockrow[bi][0] = lastDC;
  158618. }
  158619. thisblockrow += h_samp_factor; /* advance to next MCU in row */
  158620. lastblockrow += h_samp_factor;
  158621. }
  158622. }
  158623. }
  158624. }
  158625. /* NB: compress_output will increment iMCU_row_num if successful.
  158626. * A suspension return will result in redoing all the work above next time.
  158627. */
  158628. /* Emit data to the entropy encoder, sharing code with subsequent passes */
  158629. return compress_output(cinfo, input_buf);
  158630. }
  158631. /*
  158632. * Process some data in subsequent passes of a multi-pass case.
  158633. * We process the equivalent of one fully interleaved MCU row ("iMCU" row)
  158634. * per call, ie, v_samp_factor block rows for each component in the scan.
  158635. * The data is obtained from the virtual arrays and fed to the entropy coder.
  158636. * Returns TRUE if the iMCU row is completed, FALSE if suspended.
  158637. *
  158638. * NB: input_buf is ignored; it is likely to be a NULL pointer.
  158639. */
  158640. METHODDEF(boolean)
  158641. compress_output (j_compress_ptr cinfo, JSAMPIMAGE input_buf)
  158642. {
  158643. my_coef_ptr coef = (my_coef_ptr) cinfo->coef;
  158644. JDIMENSION MCU_col_num; /* index of current MCU within row */
  158645. int blkn, ci, xindex, yindex, yoffset;
  158646. JDIMENSION start_col;
  158647. JBLOCKARRAY buffer[MAX_COMPS_IN_SCAN];
  158648. JBLOCKROW buffer_ptr;
  158649. jpeg_component_info *compptr;
  158650. /* Align the virtual buffers for the components used in this scan.
  158651. * NB: during first pass, this is safe only because the buffers will
  158652. * already be aligned properly, so jmemmgr.c won't need to do any I/O.
  158653. */
  158654. for (ci = 0; ci < cinfo->comps_in_scan; ci++) {
  158655. compptr = cinfo->cur_comp_info[ci];
  158656. buffer[ci] = (*cinfo->mem->access_virt_barray)
  158657. ((j_common_ptr) cinfo, coef->whole_image[compptr->component_index],
  158658. coef->iMCU_row_num * compptr->v_samp_factor,
  158659. (JDIMENSION) compptr->v_samp_factor, FALSE);
  158660. }
  158661. /* Loop to process one whole iMCU row */
  158662. for (yoffset = coef->MCU_vert_offset; yoffset < coef->MCU_rows_per_iMCU_row;
  158663. yoffset++) {
  158664. for (MCU_col_num = coef->mcu_ctr; MCU_col_num < cinfo->MCUs_per_row;
  158665. MCU_col_num++) {
  158666. /* Construct list of pointers to DCT blocks belonging to this MCU */
  158667. blkn = 0; /* index of current DCT block within MCU */
  158668. for (ci = 0; ci < cinfo->comps_in_scan; ci++) {
  158669. compptr = cinfo->cur_comp_info[ci];
  158670. start_col = MCU_col_num * compptr->MCU_width;
  158671. for (yindex = 0; yindex < compptr->MCU_height; yindex++) {
  158672. buffer_ptr = buffer[ci][yindex+yoffset] + start_col;
  158673. for (xindex = 0; xindex < compptr->MCU_width; xindex++) {
  158674. coef->MCU_buffer[blkn++] = buffer_ptr++;
  158675. }
  158676. }
  158677. }
  158678. /* Try to write the MCU. */
  158679. if (! (*cinfo->entropy->encode_mcu) (cinfo, coef->MCU_buffer)) {
  158680. /* Suspension forced; update state counters and exit */
  158681. coef->MCU_vert_offset = yoffset;
  158682. coef->mcu_ctr = MCU_col_num;
  158683. return FALSE;
  158684. }
  158685. }
  158686. /* Completed an MCU row, but perhaps not an iMCU row */
  158687. coef->mcu_ctr = 0;
  158688. }
  158689. /* Completed the iMCU row, advance counters for next one */
  158690. coef->iMCU_row_num++;
  158691. start_iMCU_row(cinfo);
  158692. return TRUE;
  158693. }
  158694. #endif /* FULL_COEF_BUFFER_SUPPORTED */
  158695. /*
  158696. * Initialize coefficient buffer controller.
  158697. */
  158698. GLOBAL(void)
  158699. jinit_c_coef_controller (j_compress_ptr cinfo, boolean need_full_buffer)
  158700. {
  158701. my_coef_ptr coef;
  158702. coef = (my_coef_ptr)
  158703. (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_IMAGE,
  158704. SIZEOF(my_coef_controller));
  158705. cinfo->coef = (struct jpeg_c_coef_controller *) coef;
  158706. coef->pub.start_pass = start_pass_coef;
  158707. /* Create the coefficient buffer. */
  158708. if (need_full_buffer) {
  158709. #ifdef FULL_COEF_BUFFER_SUPPORTED
  158710. /* Allocate a full-image virtual array for each component, */
  158711. /* padded to a multiple of samp_factor DCT blocks in each direction. */
  158712. int ci;
  158713. jpeg_component_info *compptr;
  158714. for (ci = 0, compptr = cinfo->comp_info; ci < cinfo->num_components;
  158715. ci++, compptr++) {
  158716. coef->whole_image[ci] = (*cinfo->mem->request_virt_barray)
  158717. ((j_common_ptr) cinfo, JPOOL_IMAGE, FALSE,
  158718. (JDIMENSION) jround_up((long) compptr->width_in_blocks,
  158719. (long) compptr->h_samp_factor),
  158720. (JDIMENSION) jround_up((long) compptr->height_in_blocks,
  158721. (long) compptr->v_samp_factor),
  158722. (JDIMENSION) compptr->v_samp_factor);
  158723. }
  158724. #else
  158725. ERREXIT(cinfo, JERR_BAD_BUFFER_MODE);
  158726. #endif
  158727. } else {
  158728. /* We only need a single-MCU buffer. */
  158729. JBLOCKROW buffer;
  158730. int i;
  158731. buffer = (JBLOCKROW)
  158732. (*cinfo->mem->alloc_large) ((j_common_ptr) cinfo, JPOOL_IMAGE,
  158733. C_MAX_BLOCKS_IN_MCU * SIZEOF(JBLOCK));
  158734. for (i = 0; i < C_MAX_BLOCKS_IN_MCU; i++) {
  158735. coef->MCU_buffer[i] = buffer + i;
  158736. }
  158737. coef->whole_image[0] = NULL; /* flag for no virtual arrays */
  158738. }
  158739. }
  158740. /*** End of inlined file: jccoefct.c ***/
  158741. /*** Start of inlined file: jccolor.c ***/
  158742. #define JPEG_INTERNALS
  158743. /* Private subobject */
  158744. typedef struct {
  158745. struct jpeg_color_converter pub; /* public fields */
  158746. /* Private state for RGB->YCC conversion */
  158747. INT32 * rgb_ycc_tab; /* => table for RGB to YCbCr conversion */
  158748. } my_color_converter;
  158749. typedef my_color_converter * my_cconvert_ptr;
  158750. /**************** RGB -> YCbCr conversion: most common case **************/
  158751. /*
  158752. * YCbCr is defined per CCIR 601-1, except that Cb and Cr are
  158753. * normalized to the range 0..MAXJSAMPLE rather than -0.5 .. 0.5.
  158754. * The conversion equations to be implemented are therefore
  158755. * Y = 0.29900 * R + 0.58700 * G + 0.11400 * B
  158756. * Cb = -0.16874 * R - 0.33126 * G + 0.50000 * B + CENTERJSAMPLE
  158757. * Cr = 0.50000 * R - 0.41869 * G - 0.08131 * B + CENTERJSAMPLE
  158758. * (These numbers are derived from TIFF 6.0 section 21, dated 3-June-92.)
  158759. * Note: older versions of the IJG code used a zero offset of MAXJSAMPLE/2,
  158760. * rather than CENTERJSAMPLE, for Cb and Cr. This gave equal positive and
  158761. * negative swings for Cb/Cr, but meant that grayscale values (Cb=Cr=0)
  158762. * were not represented exactly. Now we sacrifice exact representation of
  158763. * maximum red and maximum blue in order to get exact grayscales.
  158764. *
  158765. * To avoid floating-point arithmetic, we represent the fractional constants
  158766. * as integers scaled up by 2^16 (about 4 digits precision); we have to divide
  158767. * the products by 2^16, with appropriate rounding, to get the correct answer.
  158768. *
  158769. * For even more speed, we avoid doing any multiplications in the inner loop
  158770. * by precalculating the constants times R,G,B for all possible values.
  158771. * For 8-bit JSAMPLEs this is very reasonable (only 256 entries per table);
  158772. * for 12-bit samples it is still acceptable. It's not very reasonable for
  158773. * 16-bit samples, but if you want lossless storage you shouldn't be changing
  158774. * colorspace anyway.
  158775. * The CENTERJSAMPLE offsets and the rounding fudge-factor of 0.5 are included
  158776. * in the tables to save adding them separately in the inner loop.
  158777. */
  158778. #define SCALEBITS 16 /* speediest right-shift on some machines */
  158779. #define CBCR_OFFSET ((INT32) CENTERJSAMPLE << SCALEBITS)
  158780. #define ONE_HALF ((INT32) 1 << (SCALEBITS-1))
  158781. #define FIX(x) ((INT32) ((x) * (1L<<SCALEBITS) + 0.5))
  158782. /* We allocate one big table and divide it up into eight parts, instead of
  158783. * doing eight alloc_small requests. This lets us use a single table base
  158784. * address, which can be held in a register in the inner loops on many
  158785. * machines (more than can hold all eight addresses, anyway).
  158786. */
  158787. #define R_Y_OFF 0 /* offset to R => Y section */
  158788. #define G_Y_OFF (1*(MAXJSAMPLE+1)) /* offset to G => Y section */
  158789. #define B_Y_OFF (2*(MAXJSAMPLE+1)) /* etc. */
  158790. #define R_CB_OFF (3*(MAXJSAMPLE+1))
  158791. #define G_CB_OFF (4*(MAXJSAMPLE+1))
  158792. #define B_CB_OFF (5*(MAXJSAMPLE+1))
  158793. #define R_CR_OFF B_CB_OFF /* B=>Cb, R=>Cr are the same */
  158794. #define G_CR_OFF (6*(MAXJSAMPLE+1))
  158795. #define B_CR_OFF (7*(MAXJSAMPLE+1))
  158796. #define TABLE_SIZE (8*(MAXJSAMPLE+1))
  158797. /*
  158798. * Initialize for RGB->YCC colorspace conversion.
  158799. */
  158800. METHODDEF(void)
  158801. rgb_ycc_start (j_compress_ptr cinfo)
  158802. {
  158803. my_cconvert_ptr cconvert = (my_cconvert_ptr) cinfo->cconvert;
  158804. INT32 * rgb_ycc_tab;
  158805. INT32 i;
  158806. /* Allocate and fill in the conversion tables. */
  158807. cconvert->rgb_ycc_tab = rgb_ycc_tab = (INT32 *)
  158808. (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_IMAGE,
  158809. (TABLE_SIZE * SIZEOF(INT32)));
  158810. for (i = 0; i <= MAXJSAMPLE; i++) {
  158811. rgb_ycc_tab[i+R_Y_OFF] = FIX(0.29900) * i;
  158812. rgb_ycc_tab[i+G_Y_OFF] = FIX(0.58700) * i;
  158813. rgb_ycc_tab[i+B_Y_OFF] = FIX(0.11400) * i + ONE_HALF;
  158814. rgb_ycc_tab[i+R_CB_OFF] = (-FIX(0.16874)) * i;
  158815. rgb_ycc_tab[i+G_CB_OFF] = (-FIX(0.33126)) * i;
  158816. /* We use a rounding fudge-factor of 0.5-epsilon for Cb and Cr.
  158817. * This ensures that the maximum output will round to MAXJSAMPLE
  158818. * not MAXJSAMPLE+1, and thus that we don't have to range-limit.
  158819. */
  158820. rgb_ycc_tab[i+B_CB_OFF] = FIX(0.50000) * i + CBCR_OFFSET + ONE_HALF-1;
  158821. /* B=>Cb and R=>Cr tables are the same
  158822. rgb_ycc_tab[i+R_CR_OFF] = FIX(0.50000) * i + CBCR_OFFSET + ONE_HALF-1;
  158823. */
  158824. rgb_ycc_tab[i+G_CR_OFF] = (-FIX(0.41869)) * i;
  158825. rgb_ycc_tab[i+B_CR_OFF] = (-FIX(0.08131)) * i;
  158826. }
  158827. }
  158828. /*
  158829. * Convert some rows of samples to the JPEG colorspace.
  158830. *
  158831. * Note that we change from the application's interleaved-pixel format
  158832. * to our internal noninterleaved, one-plane-per-component format.
  158833. * The input buffer is therefore three times as wide as the output buffer.
  158834. *
  158835. * A starting row offset is provided only for the output buffer. The caller
  158836. * can easily adjust the passed input_buf value to accommodate any row
  158837. * offset required on that side.
  158838. */
  158839. METHODDEF(void)
  158840. rgb_ycc_convert (j_compress_ptr cinfo,
  158841. JSAMPARRAY input_buf, JSAMPIMAGE output_buf,
  158842. JDIMENSION output_row, int num_rows)
  158843. {
  158844. my_cconvert_ptr cconvert = (my_cconvert_ptr) cinfo->cconvert;
  158845. register int r, g, b;
  158846. register INT32 * ctab = cconvert->rgb_ycc_tab;
  158847. register JSAMPROW inptr;
  158848. register JSAMPROW outptr0, outptr1, outptr2;
  158849. register JDIMENSION col;
  158850. JDIMENSION num_cols = cinfo->image_width;
  158851. while (--num_rows >= 0) {
  158852. inptr = *input_buf++;
  158853. outptr0 = output_buf[0][output_row];
  158854. outptr1 = output_buf[1][output_row];
  158855. outptr2 = output_buf[2][output_row];
  158856. output_row++;
  158857. for (col = 0; col < num_cols; col++) {
  158858. r = GETJSAMPLE(inptr[RGB_RED]);
  158859. g = GETJSAMPLE(inptr[RGB_GREEN]);
  158860. b = GETJSAMPLE(inptr[RGB_BLUE]);
  158861. inptr += RGB_PIXELSIZE;
  158862. /* If the inputs are 0..MAXJSAMPLE, the outputs of these equations
  158863. * must be too; we do not need an explicit range-limiting operation.
  158864. * Hence the value being shifted is never negative, and we don't
  158865. * need the general RIGHT_SHIFT macro.
  158866. */
  158867. /* Y */
  158868. outptr0[col] = (JSAMPLE)
  158869. ((ctab[r+R_Y_OFF] + ctab[g+G_Y_OFF] + ctab[b+B_Y_OFF])
  158870. >> SCALEBITS);
  158871. /* Cb */
  158872. outptr1[col] = (JSAMPLE)
  158873. ((ctab[r+R_CB_OFF] + ctab[g+G_CB_OFF] + ctab[b+B_CB_OFF])
  158874. >> SCALEBITS);
  158875. /* Cr */
  158876. outptr2[col] = (JSAMPLE)
  158877. ((ctab[r+R_CR_OFF] + ctab[g+G_CR_OFF] + ctab[b+B_CR_OFF])
  158878. >> SCALEBITS);
  158879. }
  158880. }
  158881. }
  158882. /**************** Cases other than RGB -> YCbCr **************/
  158883. /*
  158884. * Convert some rows of samples to the JPEG colorspace.
  158885. * This version handles RGB->grayscale conversion, which is the same
  158886. * as the RGB->Y portion of RGB->YCbCr.
  158887. * We assume rgb_ycc_start has been called (we only use the Y tables).
  158888. */
  158889. METHODDEF(void)
  158890. rgb_gray_convert (j_compress_ptr cinfo,
  158891. JSAMPARRAY input_buf, JSAMPIMAGE output_buf,
  158892. JDIMENSION output_row, int num_rows)
  158893. {
  158894. my_cconvert_ptr cconvert = (my_cconvert_ptr) cinfo->cconvert;
  158895. register int r, g, b;
  158896. register INT32 * ctab = cconvert->rgb_ycc_tab;
  158897. register JSAMPROW inptr;
  158898. register JSAMPROW outptr;
  158899. register JDIMENSION col;
  158900. JDIMENSION num_cols = cinfo->image_width;
  158901. while (--num_rows >= 0) {
  158902. inptr = *input_buf++;
  158903. outptr = output_buf[0][output_row];
  158904. output_row++;
  158905. for (col = 0; col < num_cols; col++) {
  158906. r = GETJSAMPLE(inptr[RGB_RED]);
  158907. g = GETJSAMPLE(inptr[RGB_GREEN]);
  158908. b = GETJSAMPLE(inptr[RGB_BLUE]);
  158909. inptr += RGB_PIXELSIZE;
  158910. /* Y */
  158911. outptr[col] = (JSAMPLE)
  158912. ((ctab[r+R_Y_OFF] + ctab[g+G_Y_OFF] + ctab[b+B_Y_OFF])
  158913. >> SCALEBITS);
  158914. }
  158915. }
  158916. }
  158917. /*
  158918. * Convert some rows of samples to the JPEG colorspace.
  158919. * This version handles Adobe-style CMYK->YCCK conversion,
  158920. * where we convert R=1-C, G=1-M, and B=1-Y to YCbCr using the same
  158921. * conversion as above, while passing K (black) unchanged.
  158922. * We assume rgb_ycc_start has been called.
  158923. */
  158924. METHODDEF(void)
  158925. cmyk_ycck_convert (j_compress_ptr cinfo,
  158926. JSAMPARRAY input_buf, JSAMPIMAGE output_buf,
  158927. JDIMENSION output_row, int num_rows)
  158928. {
  158929. my_cconvert_ptr cconvert = (my_cconvert_ptr) cinfo->cconvert;
  158930. register int r, g, b;
  158931. register INT32 * ctab = cconvert->rgb_ycc_tab;
  158932. register JSAMPROW inptr;
  158933. register JSAMPROW outptr0, outptr1, outptr2, outptr3;
  158934. register JDIMENSION col;
  158935. JDIMENSION num_cols = cinfo->image_width;
  158936. while (--num_rows >= 0) {
  158937. inptr = *input_buf++;
  158938. outptr0 = output_buf[0][output_row];
  158939. outptr1 = output_buf[1][output_row];
  158940. outptr2 = output_buf[2][output_row];
  158941. outptr3 = output_buf[3][output_row];
  158942. output_row++;
  158943. for (col = 0; col < num_cols; col++) {
  158944. r = MAXJSAMPLE - GETJSAMPLE(inptr[0]);
  158945. g = MAXJSAMPLE - GETJSAMPLE(inptr[1]);
  158946. b = MAXJSAMPLE - GETJSAMPLE(inptr[2]);
  158947. /* K passes through as-is */
  158948. outptr3[col] = inptr[3]; /* don't need GETJSAMPLE here */
  158949. inptr += 4;
  158950. /* If the inputs are 0..MAXJSAMPLE, the outputs of these equations
  158951. * must be too; we do not need an explicit range-limiting operation.
  158952. * Hence the value being shifted is never negative, and we don't
  158953. * need the general RIGHT_SHIFT macro.
  158954. */
  158955. /* Y */
  158956. outptr0[col] = (JSAMPLE)
  158957. ((ctab[r+R_Y_OFF] + ctab[g+G_Y_OFF] + ctab[b+B_Y_OFF])
  158958. >> SCALEBITS);
  158959. /* Cb */
  158960. outptr1[col] = (JSAMPLE)
  158961. ((ctab[r+R_CB_OFF] + ctab[g+G_CB_OFF] + ctab[b+B_CB_OFF])
  158962. >> SCALEBITS);
  158963. /* Cr */
  158964. outptr2[col] = (JSAMPLE)
  158965. ((ctab[r+R_CR_OFF] + ctab[g+G_CR_OFF] + ctab[b+B_CR_OFF])
  158966. >> SCALEBITS);
  158967. }
  158968. }
  158969. }
  158970. /*
  158971. * Convert some rows of samples to the JPEG colorspace.
  158972. * This version handles grayscale output with no conversion.
  158973. * The source can be either plain grayscale or YCbCr (since Y == gray).
  158974. */
  158975. METHODDEF(void)
  158976. grayscale_convert (j_compress_ptr cinfo,
  158977. JSAMPARRAY input_buf, JSAMPIMAGE output_buf,
  158978. JDIMENSION output_row, int num_rows)
  158979. {
  158980. register JSAMPROW inptr;
  158981. register JSAMPROW outptr;
  158982. register JDIMENSION col;
  158983. JDIMENSION num_cols = cinfo->image_width;
  158984. int instride = cinfo->input_components;
  158985. while (--num_rows >= 0) {
  158986. inptr = *input_buf++;
  158987. outptr = output_buf[0][output_row];
  158988. output_row++;
  158989. for (col = 0; col < num_cols; col++) {
  158990. outptr[col] = inptr[0]; /* don't need GETJSAMPLE() here */
  158991. inptr += instride;
  158992. }
  158993. }
  158994. }
  158995. /*
  158996. * Convert some rows of samples to the JPEG colorspace.
  158997. * This version handles multi-component colorspaces without conversion.
  158998. * We assume input_components == num_components.
  158999. */
  159000. METHODDEF(void)
  159001. null_convert (j_compress_ptr cinfo,
  159002. JSAMPARRAY input_buf, JSAMPIMAGE output_buf,
  159003. JDIMENSION output_row, int num_rows)
  159004. {
  159005. register JSAMPROW inptr;
  159006. register JSAMPROW outptr;
  159007. register JDIMENSION col;
  159008. register int ci;
  159009. int nc = cinfo->num_components;
  159010. JDIMENSION num_cols = cinfo->image_width;
  159011. while (--num_rows >= 0) {
  159012. /* It seems fastest to make a separate pass for each component. */
  159013. for (ci = 0; ci < nc; ci++) {
  159014. inptr = *input_buf;
  159015. outptr = output_buf[ci][output_row];
  159016. for (col = 0; col < num_cols; col++) {
  159017. outptr[col] = inptr[ci]; /* don't need GETJSAMPLE() here */
  159018. inptr += nc;
  159019. }
  159020. }
  159021. input_buf++;
  159022. output_row++;
  159023. }
  159024. }
  159025. /*
  159026. * Empty method for start_pass.
  159027. */
  159028. METHODDEF(void)
  159029. null_method (j_compress_ptr cinfo)
  159030. {
  159031. /* no work needed */
  159032. }
  159033. /*
  159034. * Module initialization routine for input colorspace conversion.
  159035. */
  159036. GLOBAL(void)
  159037. jinit_color_converter (j_compress_ptr cinfo)
  159038. {
  159039. my_cconvert_ptr cconvert;
  159040. cconvert = (my_cconvert_ptr)
  159041. (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_IMAGE,
  159042. SIZEOF(my_color_converter));
  159043. cinfo->cconvert = (struct jpeg_color_converter *) cconvert;
  159044. /* set start_pass to null method until we find out differently */
  159045. cconvert->pub.start_pass = null_method;
  159046. /* Make sure input_components agrees with in_color_space */
  159047. switch (cinfo->in_color_space) {
  159048. case JCS_GRAYSCALE:
  159049. if (cinfo->input_components != 1)
  159050. ERREXIT(cinfo, JERR_BAD_IN_COLORSPACE);
  159051. break;
  159052. case JCS_RGB:
  159053. #if RGB_PIXELSIZE != 3
  159054. if (cinfo->input_components != RGB_PIXELSIZE)
  159055. ERREXIT(cinfo, JERR_BAD_IN_COLORSPACE);
  159056. break;
  159057. #endif /* else share code with YCbCr */
  159058. case JCS_YCbCr:
  159059. if (cinfo->input_components != 3)
  159060. ERREXIT(cinfo, JERR_BAD_IN_COLORSPACE);
  159061. break;
  159062. case JCS_CMYK:
  159063. case JCS_YCCK:
  159064. if (cinfo->input_components != 4)
  159065. ERREXIT(cinfo, JERR_BAD_IN_COLORSPACE);
  159066. break;
  159067. default: /* JCS_UNKNOWN can be anything */
  159068. if (cinfo->input_components < 1)
  159069. ERREXIT(cinfo, JERR_BAD_IN_COLORSPACE);
  159070. break;
  159071. }
  159072. /* Check num_components, set conversion method based on requested space */
  159073. switch (cinfo->jpeg_color_space) {
  159074. case JCS_GRAYSCALE:
  159075. if (cinfo->num_components != 1)
  159076. ERREXIT(cinfo, JERR_BAD_J_COLORSPACE);
  159077. if (cinfo->in_color_space == JCS_GRAYSCALE)
  159078. cconvert->pub.color_convert = grayscale_convert;
  159079. else if (cinfo->in_color_space == JCS_RGB) {
  159080. cconvert->pub.start_pass = rgb_ycc_start;
  159081. cconvert->pub.color_convert = rgb_gray_convert;
  159082. } else if (cinfo->in_color_space == JCS_YCbCr)
  159083. cconvert->pub.color_convert = grayscale_convert;
  159084. else
  159085. ERREXIT(cinfo, JERR_CONVERSION_NOTIMPL);
  159086. break;
  159087. case JCS_RGB:
  159088. if (cinfo->num_components != 3)
  159089. ERREXIT(cinfo, JERR_BAD_J_COLORSPACE);
  159090. if (cinfo->in_color_space == JCS_RGB && RGB_PIXELSIZE == 3)
  159091. cconvert->pub.color_convert = null_convert;
  159092. else
  159093. ERREXIT(cinfo, JERR_CONVERSION_NOTIMPL);
  159094. break;
  159095. case JCS_YCbCr:
  159096. if (cinfo->num_components != 3)
  159097. ERREXIT(cinfo, JERR_BAD_J_COLORSPACE);
  159098. if (cinfo->in_color_space == JCS_RGB) {
  159099. cconvert->pub.start_pass = rgb_ycc_start;
  159100. cconvert->pub.color_convert = rgb_ycc_convert;
  159101. } else if (cinfo->in_color_space == JCS_YCbCr)
  159102. cconvert->pub.color_convert = null_convert;
  159103. else
  159104. ERREXIT(cinfo, JERR_CONVERSION_NOTIMPL);
  159105. break;
  159106. case JCS_CMYK:
  159107. if (cinfo->num_components != 4)
  159108. ERREXIT(cinfo, JERR_BAD_J_COLORSPACE);
  159109. if (cinfo->in_color_space == JCS_CMYK)
  159110. cconvert->pub.color_convert = null_convert;
  159111. else
  159112. ERREXIT(cinfo, JERR_CONVERSION_NOTIMPL);
  159113. break;
  159114. case JCS_YCCK:
  159115. if (cinfo->num_components != 4)
  159116. ERREXIT(cinfo, JERR_BAD_J_COLORSPACE);
  159117. if (cinfo->in_color_space == JCS_CMYK) {
  159118. cconvert->pub.start_pass = rgb_ycc_start;
  159119. cconvert->pub.color_convert = cmyk_ycck_convert;
  159120. } else if (cinfo->in_color_space == JCS_YCCK)
  159121. cconvert->pub.color_convert = null_convert;
  159122. else
  159123. ERREXIT(cinfo, JERR_CONVERSION_NOTIMPL);
  159124. break;
  159125. default: /* allow null conversion of JCS_UNKNOWN */
  159126. if (cinfo->jpeg_color_space != cinfo->in_color_space ||
  159127. cinfo->num_components != cinfo->input_components)
  159128. ERREXIT(cinfo, JERR_CONVERSION_NOTIMPL);
  159129. cconvert->pub.color_convert = null_convert;
  159130. break;
  159131. }
  159132. }
  159133. /*** End of inlined file: jccolor.c ***/
  159134. #undef FIX
  159135. /*** Start of inlined file: jcdctmgr.c ***/
  159136. #define JPEG_INTERNALS
  159137. /*** Start of inlined file: jdct.h ***/
  159138. /*
  159139. * A forward DCT routine is given a pointer to a work area of type DCTELEM[];
  159140. * the DCT is to be performed in-place in that buffer. Type DCTELEM is int
  159141. * for 8-bit samples, INT32 for 12-bit samples. (NOTE: Floating-point DCT
  159142. * implementations use an array of type FAST_FLOAT, instead.)
  159143. * The DCT inputs are expected to be signed (range +-CENTERJSAMPLE).
  159144. * The DCT outputs are returned scaled up by a factor of 8; they therefore
  159145. * have a range of +-8K for 8-bit data, +-128K for 12-bit data. This
  159146. * convention improves accuracy in integer implementations and saves some
  159147. * work in floating-point ones.
  159148. * Quantization of the output coefficients is done by jcdctmgr.c.
  159149. */
  159150. #ifndef __jdct_h__
  159151. #define __jdct_h__
  159152. #if BITS_IN_JSAMPLE == 8
  159153. typedef int DCTELEM; /* 16 or 32 bits is fine */
  159154. #else
  159155. typedef INT32 DCTELEM; /* must have 32 bits */
  159156. #endif
  159157. typedef JMETHOD(void, forward_DCT_method_ptr, (DCTELEM * data));
  159158. typedef JMETHOD(void, float_DCT_method_ptr, (FAST_FLOAT * data));
  159159. /*
  159160. * An inverse DCT routine is given a pointer to the input JBLOCK and a pointer
  159161. * to an output sample array. The routine must dequantize the input data as
  159162. * well as perform the IDCT; for dequantization, it uses the multiplier table
  159163. * pointed to by compptr->dct_table. The output data is to be placed into the
  159164. * sample array starting at a specified column. (Any row offset needed will
  159165. * be applied to the array pointer before it is passed to the IDCT code.)
  159166. * Note that the number of samples emitted by the IDCT routine is
  159167. * DCT_scaled_size * DCT_scaled_size.
  159168. */
  159169. /* typedef inverse_DCT_method_ptr is declared in jpegint.h */
  159170. /*
  159171. * Each IDCT routine has its own ideas about the best dct_table element type.
  159172. */
  159173. typedef MULTIPLIER ISLOW_MULT_TYPE; /* short or int, whichever is faster */
  159174. #if BITS_IN_JSAMPLE == 8
  159175. typedef MULTIPLIER IFAST_MULT_TYPE; /* 16 bits is OK, use short if faster */
  159176. #define IFAST_SCALE_BITS 2 /* fractional bits in scale factors */
  159177. #else
  159178. typedef INT32 IFAST_MULT_TYPE; /* need 32 bits for scaled quantizers */
  159179. #define IFAST_SCALE_BITS 13 /* fractional bits in scale factors */
  159180. #endif
  159181. typedef FAST_FLOAT FLOAT_MULT_TYPE; /* preferred floating type */
  159182. /*
  159183. * Each IDCT routine is responsible for range-limiting its results and
  159184. * converting them to unsigned form (0..MAXJSAMPLE). The raw outputs could
  159185. * be quite far out of range if the input data is corrupt, so a bulletproof
  159186. * range-limiting step is required. We use a mask-and-table-lookup method
  159187. * to do the combined operations quickly. See the comments with
  159188. * prepare_range_limit_table (in jdmaster.c) for more info.
  159189. */
  159190. #define IDCT_range_limit(cinfo) ((cinfo)->sample_range_limit + CENTERJSAMPLE)
  159191. #define RANGE_MASK (MAXJSAMPLE * 4 + 3) /* 2 bits wider than legal samples */
  159192. /* Short forms of external names for systems with brain-damaged linkers. */
  159193. #ifdef NEED_SHORT_EXTERNAL_NAMES
  159194. #define jpeg_fdct_islow jFDislow
  159195. #define jpeg_fdct_ifast jFDifast
  159196. #define jpeg_fdct_float jFDfloat
  159197. #define jpeg_idct_islow jRDislow
  159198. #define jpeg_idct_ifast jRDifast
  159199. #define jpeg_idct_float jRDfloat
  159200. #define jpeg_idct_4x4 jRD4x4
  159201. #define jpeg_idct_2x2 jRD2x2
  159202. #define jpeg_idct_1x1 jRD1x1
  159203. #endif /* NEED_SHORT_EXTERNAL_NAMES */
  159204. /* Extern declarations for the forward and inverse DCT routines. */
  159205. EXTERN(void) jpeg_fdct_islow JPP((DCTELEM * data));
  159206. EXTERN(void) jpeg_fdct_ifast JPP((DCTELEM * data));
  159207. EXTERN(void) jpeg_fdct_float JPP((FAST_FLOAT * data));
  159208. EXTERN(void) jpeg_idct_islow
  159209. JPP((j_decompress_ptr cinfo, jpeg_component_info * compptr,
  159210. JCOEFPTR coef_block, JSAMPARRAY output_buf, JDIMENSION output_col));
  159211. EXTERN(void) jpeg_idct_ifast
  159212. JPP((j_decompress_ptr cinfo, jpeg_component_info * compptr,
  159213. JCOEFPTR coef_block, JSAMPARRAY output_buf, JDIMENSION output_col));
  159214. EXTERN(void) jpeg_idct_float
  159215. JPP((j_decompress_ptr cinfo, jpeg_component_info * compptr,
  159216. JCOEFPTR coef_block, JSAMPARRAY output_buf, JDIMENSION output_col));
  159217. EXTERN(void) jpeg_idct_4x4
  159218. JPP((j_decompress_ptr cinfo, jpeg_component_info * compptr,
  159219. JCOEFPTR coef_block, JSAMPARRAY output_buf, JDIMENSION output_col));
  159220. EXTERN(void) jpeg_idct_2x2
  159221. JPP((j_decompress_ptr cinfo, jpeg_component_info * compptr,
  159222. JCOEFPTR coef_block, JSAMPARRAY output_buf, JDIMENSION output_col));
  159223. EXTERN(void) jpeg_idct_1x1
  159224. JPP((j_decompress_ptr cinfo, jpeg_component_info * compptr,
  159225. JCOEFPTR coef_block, JSAMPARRAY output_buf, JDIMENSION output_col));
  159226. /*
  159227. * Macros for handling fixed-point arithmetic; these are used by many
  159228. * but not all of the DCT/IDCT modules.
  159229. *
  159230. * All values are expected to be of type INT32.
  159231. * Fractional constants are scaled left by CONST_BITS bits.
  159232. * CONST_BITS is defined within each module using these macros,
  159233. * and may differ from one module to the next.
  159234. */
  159235. #define ONE ((INT32) 1)
  159236. #define CONST_SCALE (ONE << CONST_BITS)
  159237. /* Convert a positive real constant to an integer scaled by CONST_SCALE.
  159238. * Caution: some C compilers fail to reduce "FIX(constant)" at compile time,
  159239. * thus causing a lot of useless floating-point operations at run time.
  159240. */
  159241. #define FIX(x) ((INT32) ((x) * CONST_SCALE + 0.5))
  159242. /* Descale and correctly round an INT32 value that's scaled by N bits.
  159243. * We assume RIGHT_SHIFT rounds towards minus infinity, so adding
  159244. * the fudge factor is correct for either sign of X.
  159245. */
  159246. #define DESCALE(x,n) RIGHT_SHIFT((x) + (ONE << ((n)-1)), n)
  159247. /* Multiply an INT32 variable by an INT32 constant to yield an INT32 result.
  159248. * This macro is used only when the two inputs will actually be no more than
  159249. * 16 bits wide, so that a 16x16->32 bit multiply can be used instead of a
  159250. * full 32x32 multiply. This provides a useful speedup on many machines.
  159251. * Unfortunately there is no way to specify a 16x16->32 multiply portably
  159252. * in C, but some C compilers will do the right thing if you provide the
  159253. * correct combination of casts.
  159254. */
  159255. #ifdef SHORTxSHORT_32 /* may work if 'int' is 32 bits */
  159256. #define MULTIPLY16C16(var,const) (((INT16) (var)) * ((INT16) (const)))
  159257. #endif
  159258. #ifdef SHORTxLCONST_32 /* known to work with Microsoft C 6.0 */
  159259. #define MULTIPLY16C16(var,const) (((INT16) (var)) * ((INT32) (const)))
  159260. #endif
  159261. #ifndef MULTIPLY16C16 /* default definition */
  159262. #define MULTIPLY16C16(var,const) ((var) * (const))
  159263. #endif
  159264. /* Same except both inputs are variables. */
  159265. #ifdef SHORTxSHORT_32 /* may work if 'int' is 32 bits */
  159266. #define MULTIPLY16V16(var1,var2) (((INT16) (var1)) * ((INT16) (var2)))
  159267. #endif
  159268. #ifndef MULTIPLY16V16 /* default definition */
  159269. #define MULTIPLY16V16(var1,var2) ((var1) * (var2))
  159270. #endif
  159271. #endif
  159272. /*** End of inlined file: jdct.h ***/
  159273. /* Private declarations for DCT subsystem */
  159274. /* Private subobject for this module */
  159275. typedef struct {
  159276. struct jpeg_forward_dct pub; /* public fields */
  159277. /* Pointer to the DCT routine actually in use */
  159278. forward_DCT_method_ptr do_dct;
  159279. /* The actual post-DCT divisors --- not identical to the quant table
  159280. * entries, because of scaling (especially for an unnormalized DCT).
  159281. * Each table is given in normal array order.
  159282. */
  159283. DCTELEM * divisors[NUM_QUANT_TBLS];
  159284. #ifdef DCT_FLOAT_SUPPORTED
  159285. /* Same as above for the floating-point case. */
  159286. float_DCT_method_ptr do_float_dct;
  159287. FAST_FLOAT * float_divisors[NUM_QUANT_TBLS];
  159288. #endif
  159289. } my_fdct_controller;
  159290. typedef my_fdct_controller * my_fdct_ptr;
  159291. /*
  159292. * Initialize for a processing pass.
  159293. * Verify that all referenced Q-tables are present, and set up
  159294. * the divisor table for each one.
  159295. * In the current implementation, DCT of all components is done during
  159296. * the first pass, even if only some components will be output in the
  159297. * first scan. Hence all components should be examined here.
  159298. */
  159299. METHODDEF(void)
  159300. start_pass_fdctmgr (j_compress_ptr cinfo)
  159301. {
  159302. my_fdct_ptr fdct = (my_fdct_ptr) cinfo->fdct;
  159303. int ci, qtblno, i;
  159304. jpeg_component_info *compptr;
  159305. JQUANT_TBL * qtbl;
  159306. DCTELEM * dtbl;
  159307. for (ci = 0, compptr = cinfo->comp_info; ci < cinfo->num_components;
  159308. ci++, compptr++) {
  159309. qtblno = compptr->quant_tbl_no;
  159310. /* Make sure specified quantization table is present */
  159311. if (qtblno < 0 || qtblno >= NUM_QUANT_TBLS ||
  159312. cinfo->quant_tbl_ptrs[qtblno] == NULL)
  159313. ERREXIT1(cinfo, JERR_NO_QUANT_TABLE, qtblno);
  159314. qtbl = cinfo->quant_tbl_ptrs[qtblno];
  159315. /* Compute divisors for this quant table */
  159316. /* We may do this more than once for same table, but it's not a big deal */
  159317. switch (cinfo->dct_method) {
  159318. #ifdef DCT_ISLOW_SUPPORTED
  159319. case JDCT_ISLOW:
  159320. /* For LL&M IDCT method, divisors are equal to raw quantization
  159321. * coefficients multiplied by 8 (to counteract scaling).
  159322. */
  159323. if (fdct->divisors[qtblno] == NULL) {
  159324. fdct->divisors[qtblno] = (DCTELEM *)
  159325. (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_IMAGE,
  159326. DCTSIZE2 * SIZEOF(DCTELEM));
  159327. }
  159328. dtbl = fdct->divisors[qtblno];
  159329. for (i = 0; i < DCTSIZE2; i++) {
  159330. dtbl[i] = ((DCTELEM) qtbl->quantval[i]) << 3;
  159331. }
  159332. break;
  159333. #endif
  159334. #ifdef DCT_IFAST_SUPPORTED
  159335. case JDCT_IFAST:
  159336. {
  159337. /* For AA&N IDCT method, divisors are equal to quantization
  159338. * coefficients scaled by scalefactor[row]*scalefactor[col], where
  159339. * scalefactor[0] = 1
  159340. * scalefactor[k] = cos(k*PI/16) * sqrt(2) for k=1..7
  159341. * We apply a further scale factor of 8.
  159342. */
  159343. #define CONST_BITS 14
  159344. static const INT16 aanscales[DCTSIZE2] = {
  159345. /* precomputed values scaled up by 14 bits */
  159346. 16384, 22725, 21407, 19266, 16384, 12873, 8867, 4520,
  159347. 22725, 31521, 29692, 26722, 22725, 17855, 12299, 6270,
  159348. 21407, 29692, 27969, 25172, 21407, 16819, 11585, 5906,
  159349. 19266, 26722, 25172, 22654, 19266, 15137, 10426, 5315,
  159350. 16384, 22725, 21407, 19266, 16384, 12873, 8867, 4520,
  159351. 12873, 17855, 16819, 15137, 12873, 10114, 6967, 3552,
  159352. 8867, 12299, 11585, 10426, 8867, 6967, 4799, 2446,
  159353. 4520, 6270, 5906, 5315, 4520, 3552, 2446, 1247
  159354. };
  159355. SHIFT_TEMPS
  159356. if (fdct->divisors[qtblno] == NULL) {
  159357. fdct->divisors[qtblno] = (DCTELEM *)
  159358. (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_IMAGE,
  159359. DCTSIZE2 * SIZEOF(DCTELEM));
  159360. }
  159361. dtbl = fdct->divisors[qtblno];
  159362. for (i = 0; i < DCTSIZE2; i++) {
  159363. dtbl[i] = (DCTELEM)
  159364. DESCALE(MULTIPLY16V16((INT32) qtbl->quantval[i],
  159365. (INT32) aanscales[i]),
  159366. CONST_BITS-3);
  159367. }
  159368. }
  159369. break;
  159370. #endif
  159371. #ifdef DCT_FLOAT_SUPPORTED
  159372. case JDCT_FLOAT:
  159373. {
  159374. /* For float AA&N IDCT method, divisors are equal to quantization
  159375. * coefficients scaled by scalefactor[row]*scalefactor[col], where
  159376. * scalefactor[0] = 1
  159377. * scalefactor[k] = cos(k*PI/16) * sqrt(2) for k=1..7
  159378. * We apply a further scale factor of 8.
  159379. * What's actually stored is 1/divisor so that the inner loop can
  159380. * use a multiplication rather than a division.
  159381. */
  159382. FAST_FLOAT * fdtbl;
  159383. int row, col;
  159384. static const double aanscalefactor[DCTSIZE] = {
  159385. 1.0, 1.387039845, 1.306562965, 1.175875602,
  159386. 1.0, 0.785694958, 0.541196100, 0.275899379
  159387. };
  159388. if (fdct->float_divisors[qtblno] == NULL) {
  159389. fdct->float_divisors[qtblno] = (FAST_FLOAT *)
  159390. (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_IMAGE,
  159391. DCTSIZE2 * SIZEOF(FAST_FLOAT));
  159392. }
  159393. fdtbl = fdct->float_divisors[qtblno];
  159394. i = 0;
  159395. for (row = 0; row < DCTSIZE; row++) {
  159396. for (col = 0; col < DCTSIZE; col++) {
  159397. fdtbl[i] = (FAST_FLOAT)
  159398. (1.0 / (((double) qtbl->quantval[i] *
  159399. aanscalefactor[row] * aanscalefactor[col] * 8.0)));
  159400. i++;
  159401. }
  159402. }
  159403. }
  159404. break;
  159405. #endif
  159406. default:
  159407. ERREXIT(cinfo, JERR_NOT_COMPILED);
  159408. break;
  159409. }
  159410. }
  159411. }
  159412. /*
  159413. * Perform forward DCT on one or more blocks of a component.
  159414. *
  159415. * The input samples are taken from the sample_data[] array starting at
  159416. * position start_row/start_col, and moving to the right for any additional
  159417. * blocks. The quantized coefficients are returned in coef_blocks[].
  159418. */
  159419. METHODDEF(void)
  159420. forward_DCT (j_compress_ptr cinfo, jpeg_component_info * compptr,
  159421. JSAMPARRAY sample_data, JBLOCKROW coef_blocks,
  159422. JDIMENSION start_row, JDIMENSION start_col,
  159423. JDIMENSION num_blocks)
  159424. /* This version is used for integer DCT implementations. */
  159425. {
  159426. /* This routine is heavily used, so it's worth coding it tightly. */
  159427. my_fdct_ptr fdct = (my_fdct_ptr) cinfo->fdct;
  159428. forward_DCT_method_ptr do_dct = fdct->do_dct;
  159429. DCTELEM * divisors = fdct->divisors[compptr->quant_tbl_no];
  159430. DCTELEM workspace[DCTSIZE2]; /* work area for FDCT subroutine */
  159431. JDIMENSION bi;
  159432. sample_data += start_row; /* fold in the vertical offset once */
  159433. for (bi = 0; bi < num_blocks; bi++, start_col += DCTSIZE) {
  159434. /* Load data into workspace, applying unsigned->signed conversion */
  159435. { register DCTELEM *workspaceptr;
  159436. register JSAMPROW elemptr;
  159437. register int elemr;
  159438. workspaceptr = workspace;
  159439. for (elemr = 0; elemr < DCTSIZE; elemr++) {
  159440. elemptr = sample_data[elemr] + start_col;
  159441. #if DCTSIZE == 8 /* unroll the inner loop */
  159442. *workspaceptr++ = GETJSAMPLE(*elemptr++) - CENTERJSAMPLE;
  159443. *workspaceptr++ = GETJSAMPLE(*elemptr++) - CENTERJSAMPLE;
  159444. *workspaceptr++ = GETJSAMPLE(*elemptr++) - CENTERJSAMPLE;
  159445. *workspaceptr++ = GETJSAMPLE(*elemptr++) - CENTERJSAMPLE;
  159446. *workspaceptr++ = GETJSAMPLE(*elemptr++) - CENTERJSAMPLE;
  159447. *workspaceptr++ = GETJSAMPLE(*elemptr++) - CENTERJSAMPLE;
  159448. *workspaceptr++ = GETJSAMPLE(*elemptr++) - CENTERJSAMPLE;
  159449. *workspaceptr++ = GETJSAMPLE(*elemptr++) - CENTERJSAMPLE;
  159450. #else
  159451. { register int elemc;
  159452. for (elemc = DCTSIZE; elemc > 0; elemc--) {
  159453. *workspaceptr++ = GETJSAMPLE(*elemptr++) - CENTERJSAMPLE;
  159454. }
  159455. }
  159456. #endif
  159457. }
  159458. }
  159459. /* Perform the DCT */
  159460. (*do_dct) (workspace);
  159461. /* Quantize/descale the coefficients, and store into coef_blocks[] */
  159462. { register DCTELEM temp, qval;
  159463. register int i;
  159464. register JCOEFPTR output_ptr = coef_blocks[bi];
  159465. for (i = 0; i < DCTSIZE2; i++) {
  159466. qval = divisors[i];
  159467. temp = workspace[i];
  159468. /* Divide the coefficient value by qval, ensuring proper rounding.
  159469. * Since C does not specify the direction of rounding for negative
  159470. * quotients, we have to force the dividend positive for portability.
  159471. *
  159472. * In most files, at least half of the output values will be zero
  159473. * (at default quantization settings, more like three-quarters...)
  159474. * so we should ensure that this case is fast. On many machines,
  159475. * a comparison is enough cheaper than a divide to make a special test
  159476. * a win. Since both inputs will be nonnegative, we need only test
  159477. * for a < b to discover whether a/b is 0.
  159478. * If your machine's division is fast enough, define FAST_DIVIDE.
  159479. */
  159480. #ifdef FAST_DIVIDE
  159481. #define DIVIDE_BY(a,b) a /= b
  159482. #else
  159483. #define DIVIDE_BY(a,b) if (a >= b) a /= b; else a = 0
  159484. #endif
  159485. if (temp < 0) {
  159486. temp = -temp;
  159487. temp += qval>>1; /* for rounding */
  159488. DIVIDE_BY(temp, qval);
  159489. temp = -temp;
  159490. } else {
  159491. temp += qval>>1; /* for rounding */
  159492. DIVIDE_BY(temp, qval);
  159493. }
  159494. output_ptr[i] = (JCOEF) temp;
  159495. }
  159496. }
  159497. }
  159498. }
  159499. #ifdef DCT_FLOAT_SUPPORTED
  159500. METHODDEF(void)
  159501. forward_DCT_float (j_compress_ptr cinfo, jpeg_component_info * compptr,
  159502. JSAMPARRAY sample_data, JBLOCKROW coef_blocks,
  159503. JDIMENSION start_row, JDIMENSION start_col,
  159504. JDIMENSION num_blocks)
  159505. /* This version is used for floating-point DCT implementations. */
  159506. {
  159507. /* This routine is heavily used, so it's worth coding it tightly. */
  159508. my_fdct_ptr fdct = (my_fdct_ptr) cinfo->fdct;
  159509. float_DCT_method_ptr do_dct = fdct->do_float_dct;
  159510. FAST_FLOAT * divisors = fdct->float_divisors[compptr->quant_tbl_no];
  159511. FAST_FLOAT workspace[DCTSIZE2]; /* work area for FDCT subroutine */
  159512. JDIMENSION bi;
  159513. sample_data += start_row; /* fold in the vertical offset once */
  159514. for (bi = 0; bi < num_blocks; bi++, start_col += DCTSIZE) {
  159515. /* Load data into workspace, applying unsigned->signed conversion */
  159516. { register FAST_FLOAT *workspaceptr;
  159517. register JSAMPROW elemptr;
  159518. register int elemr;
  159519. workspaceptr = workspace;
  159520. for (elemr = 0; elemr < DCTSIZE; elemr++) {
  159521. elemptr = sample_data[elemr] + start_col;
  159522. #if DCTSIZE == 8 /* unroll the inner loop */
  159523. *workspaceptr++ = (FAST_FLOAT)(GETJSAMPLE(*elemptr++) - CENTERJSAMPLE);
  159524. *workspaceptr++ = (FAST_FLOAT)(GETJSAMPLE(*elemptr++) - CENTERJSAMPLE);
  159525. *workspaceptr++ = (FAST_FLOAT)(GETJSAMPLE(*elemptr++) - CENTERJSAMPLE);
  159526. *workspaceptr++ = (FAST_FLOAT)(GETJSAMPLE(*elemptr++) - CENTERJSAMPLE);
  159527. *workspaceptr++ = (FAST_FLOAT)(GETJSAMPLE(*elemptr++) - CENTERJSAMPLE);
  159528. *workspaceptr++ = (FAST_FLOAT)(GETJSAMPLE(*elemptr++) - CENTERJSAMPLE);
  159529. *workspaceptr++ = (FAST_FLOAT)(GETJSAMPLE(*elemptr++) - CENTERJSAMPLE);
  159530. *workspaceptr++ = (FAST_FLOAT)(GETJSAMPLE(*elemptr++) - CENTERJSAMPLE);
  159531. #else
  159532. { register int elemc;
  159533. for (elemc = DCTSIZE; elemc > 0; elemc--) {
  159534. *workspaceptr++ = (FAST_FLOAT)
  159535. (GETJSAMPLE(*elemptr++) - CENTERJSAMPLE);
  159536. }
  159537. }
  159538. #endif
  159539. }
  159540. }
  159541. /* Perform the DCT */
  159542. (*do_dct) (workspace);
  159543. /* Quantize/descale the coefficients, and store into coef_blocks[] */
  159544. { register FAST_FLOAT temp;
  159545. register int i;
  159546. register JCOEFPTR output_ptr = coef_blocks[bi];
  159547. for (i = 0; i < DCTSIZE2; i++) {
  159548. /* Apply the quantization and scaling factor */
  159549. temp = workspace[i] * divisors[i];
  159550. /* Round to nearest integer.
  159551. * Since C does not specify the direction of rounding for negative
  159552. * quotients, we have to force the dividend positive for portability.
  159553. * The maximum coefficient size is +-16K (for 12-bit data), so this
  159554. * code should work for either 16-bit or 32-bit ints.
  159555. */
  159556. output_ptr[i] = (JCOEF) ((int) (temp + (FAST_FLOAT) 16384.5) - 16384);
  159557. }
  159558. }
  159559. }
  159560. }
  159561. #endif /* DCT_FLOAT_SUPPORTED */
  159562. /*
  159563. * Initialize FDCT manager.
  159564. */
  159565. GLOBAL(void)
  159566. jinit_forward_dct (j_compress_ptr cinfo)
  159567. {
  159568. my_fdct_ptr fdct;
  159569. int i;
  159570. fdct = (my_fdct_ptr)
  159571. (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_IMAGE,
  159572. SIZEOF(my_fdct_controller));
  159573. cinfo->fdct = (struct jpeg_forward_dct *) fdct;
  159574. fdct->pub.start_pass = start_pass_fdctmgr;
  159575. switch (cinfo->dct_method) {
  159576. #ifdef DCT_ISLOW_SUPPORTED
  159577. case JDCT_ISLOW:
  159578. fdct->pub.forward_DCT = forward_DCT;
  159579. fdct->do_dct = jpeg_fdct_islow;
  159580. break;
  159581. #endif
  159582. #ifdef DCT_IFAST_SUPPORTED
  159583. case JDCT_IFAST:
  159584. fdct->pub.forward_DCT = forward_DCT;
  159585. fdct->do_dct = jpeg_fdct_ifast;
  159586. break;
  159587. #endif
  159588. #ifdef DCT_FLOAT_SUPPORTED
  159589. case JDCT_FLOAT:
  159590. fdct->pub.forward_DCT = forward_DCT_float;
  159591. fdct->do_float_dct = jpeg_fdct_float;
  159592. break;
  159593. #endif
  159594. default:
  159595. ERREXIT(cinfo, JERR_NOT_COMPILED);
  159596. break;
  159597. }
  159598. /* Mark divisor tables unallocated */
  159599. for (i = 0; i < NUM_QUANT_TBLS; i++) {
  159600. fdct->divisors[i] = NULL;
  159601. #ifdef DCT_FLOAT_SUPPORTED
  159602. fdct->float_divisors[i] = NULL;
  159603. #endif
  159604. }
  159605. }
  159606. /*** End of inlined file: jcdctmgr.c ***/
  159607. #undef CONST_BITS
  159608. /*** Start of inlined file: jchuff.c ***/
  159609. #define JPEG_INTERNALS
  159610. /*** Start of inlined file: jchuff.h ***/
  159611. /* The legal range of a DCT coefficient is
  159612. * -1024 .. +1023 for 8-bit data;
  159613. * -16384 .. +16383 for 12-bit data.
  159614. * Hence the magnitude should always fit in 10 or 14 bits respectively.
  159615. */
  159616. #ifndef _jchuff_h_
  159617. #define _jchuff_h_
  159618. #if BITS_IN_JSAMPLE == 8
  159619. #define MAX_COEF_BITS 10
  159620. #else
  159621. #define MAX_COEF_BITS 14
  159622. #endif
  159623. /* Derived data constructed for each Huffman table */
  159624. typedef struct {
  159625. unsigned int ehufco[256]; /* code for each symbol */
  159626. char ehufsi[256]; /* length of code for each symbol */
  159627. /* If no code has been allocated for a symbol S, ehufsi[S] contains 0 */
  159628. } c_derived_tbl;
  159629. /* Short forms of external names for systems with brain-damaged linkers. */
  159630. #ifdef NEED_SHORT_EXTERNAL_NAMES
  159631. #define jpeg_make_c_derived_tbl jMkCDerived
  159632. #define jpeg_gen_optimal_table jGenOptTbl
  159633. #endif /* NEED_SHORT_EXTERNAL_NAMES */
  159634. /* Expand a Huffman table definition into the derived format */
  159635. EXTERN(void) jpeg_make_c_derived_tbl
  159636. JPP((j_compress_ptr cinfo, boolean isDC, int tblno,
  159637. c_derived_tbl ** pdtbl));
  159638. /* Generate an optimal table definition given the specified counts */
  159639. EXTERN(void) jpeg_gen_optimal_table
  159640. JPP((j_compress_ptr cinfo, JHUFF_TBL * htbl, long freq[]));
  159641. #endif
  159642. /*** End of inlined file: jchuff.h ***/
  159643. /* Declarations shared with jcphuff.c */
  159644. /* Expanded entropy encoder object for Huffman encoding.
  159645. *
  159646. * The savable_state subrecord contains fields that change within an MCU,
  159647. * but must not be updated permanently until we complete the MCU.
  159648. */
  159649. typedef struct {
  159650. INT32 put_buffer; /* current bit-accumulation buffer */
  159651. int put_bits; /* # of bits now in it */
  159652. int last_dc_val[MAX_COMPS_IN_SCAN]; /* last DC coef for each component */
  159653. } savable_state;
  159654. /* This macro is to work around compilers with missing or broken
  159655. * structure assignment. You'll need to fix this code if you have
  159656. * such a compiler and you change MAX_COMPS_IN_SCAN.
  159657. */
  159658. #ifndef NO_STRUCT_ASSIGN
  159659. #define ASSIGN_STATE(dest,src) ((dest) = (src))
  159660. #else
  159661. #if MAX_COMPS_IN_SCAN == 4
  159662. #define ASSIGN_STATE(dest,src) \
  159663. ((dest).put_buffer = (src).put_buffer, \
  159664. (dest).put_bits = (src).put_bits, \
  159665. (dest).last_dc_val[0] = (src).last_dc_val[0], \
  159666. (dest).last_dc_val[1] = (src).last_dc_val[1], \
  159667. (dest).last_dc_val[2] = (src).last_dc_val[2], \
  159668. (dest).last_dc_val[3] = (src).last_dc_val[3])
  159669. #endif
  159670. #endif
  159671. typedef struct {
  159672. struct jpeg_entropy_encoder pub; /* public fields */
  159673. savable_state saved; /* Bit buffer & DC state at start of MCU */
  159674. /* These fields are NOT loaded into local working state. */
  159675. unsigned int restarts_to_go; /* MCUs left in this restart interval */
  159676. int next_restart_num; /* next restart number to write (0-7) */
  159677. /* Pointers to derived tables (these workspaces have image lifespan) */
  159678. c_derived_tbl * dc_derived_tbls[NUM_HUFF_TBLS];
  159679. c_derived_tbl * ac_derived_tbls[NUM_HUFF_TBLS];
  159680. #ifdef ENTROPY_OPT_SUPPORTED /* Statistics tables for optimization */
  159681. long * dc_count_ptrs[NUM_HUFF_TBLS];
  159682. long * ac_count_ptrs[NUM_HUFF_TBLS];
  159683. #endif
  159684. } huff_entropy_encoder;
  159685. typedef huff_entropy_encoder * huff_entropy_ptr;
  159686. /* Working state while writing an MCU.
  159687. * This struct contains all the fields that are needed by subroutines.
  159688. */
  159689. typedef struct {
  159690. JOCTET * next_output_byte; /* => next byte to write in buffer */
  159691. size_t free_in_buffer; /* # of byte spaces remaining in buffer */
  159692. savable_state cur; /* Current bit buffer & DC state */
  159693. j_compress_ptr cinfo; /* dump_buffer needs access to this */
  159694. } working_state;
  159695. /* Forward declarations */
  159696. METHODDEF(boolean) encode_mcu_huff JPP((j_compress_ptr cinfo,
  159697. JBLOCKROW *MCU_data));
  159698. METHODDEF(void) finish_pass_huff JPP((j_compress_ptr cinfo));
  159699. #ifdef ENTROPY_OPT_SUPPORTED
  159700. METHODDEF(boolean) encode_mcu_gather JPP((j_compress_ptr cinfo,
  159701. JBLOCKROW *MCU_data));
  159702. METHODDEF(void) finish_pass_gather JPP((j_compress_ptr cinfo));
  159703. #endif
  159704. /*
  159705. * Initialize for a Huffman-compressed scan.
  159706. * If gather_statistics is TRUE, we do not output anything during the scan,
  159707. * just count the Huffman symbols used and generate Huffman code tables.
  159708. */
  159709. METHODDEF(void)
  159710. start_pass_huff (j_compress_ptr cinfo, boolean gather_statistics)
  159711. {
  159712. huff_entropy_ptr entropy = (huff_entropy_ptr) cinfo->entropy;
  159713. int ci, dctbl, actbl;
  159714. jpeg_component_info * compptr;
  159715. if (gather_statistics) {
  159716. #ifdef ENTROPY_OPT_SUPPORTED
  159717. entropy->pub.encode_mcu = encode_mcu_gather;
  159718. entropy->pub.finish_pass = finish_pass_gather;
  159719. #else
  159720. ERREXIT(cinfo, JERR_NOT_COMPILED);
  159721. #endif
  159722. } else {
  159723. entropy->pub.encode_mcu = encode_mcu_huff;
  159724. entropy->pub.finish_pass = finish_pass_huff;
  159725. }
  159726. for (ci = 0; ci < cinfo->comps_in_scan; ci++) {
  159727. compptr = cinfo->cur_comp_info[ci];
  159728. dctbl = compptr->dc_tbl_no;
  159729. actbl = compptr->ac_tbl_no;
  159730. if (gather_statistics) {
  159731. #ifdef ENTROPY_OPT_SUPPORTED
  159732. /* Check for invalid table indexes */
  159733. /* (make_c_derived_tbl does this in the other path) */
  159734. if (dctbl < 0 || dctbl >= NUM_HUFF_TBLS)
  159735. ERREXIT1(cinfo, JERR_NO_HUFF_TABLE, dctbl);
  159736. if (actbl < 0 || actbl >= NUM_HUFF_TBLS)
  159737. ERREXIT1(cinfo, JERR_NO_HUFF_TABLE, actbl);
  159738. /* Allocate and zero the statistics tables */
  159739. /* Note that jpeg_gen_optimal_table expects 257 entries in each table! */
  159740. if (entropy->dc_count_ptrs[dctbl] == NULL)
  159741. entropy->dc_count_ptrs[dctbl] = (long *)
  159742. (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_IMAGE,
  159743. 257 * SIZEOF(long));
  159744. MEMZERO(entropy->dc_count_ptrs[dctbl], 257 * SIZEOF(long));
  159745. if (entropy->ac_count_ptrs[actbl] == NULL)
  159746. entropy->ac_count_ptrs[actbl] = (long *)
  159747. (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_IMAGE,
  159748. 257 * SIZEOF(long));
  159749. MEMZERO(entropy->ac_count_ptrs[actbl], 257 * SIZEOF(long));
  159750. #endif
  159751. } else {
  159752. /* Compute derived values for Huffman tables */
  159753. /* We may do this more than once for a table, but it's not expensive */
  159754. jpeg_make_c_derived_tbl(cinfo, TRUE, dctbl,
  159755. & entropy->dc_derived_tbls[dctbl]);
  159756. jpeg_make_c_derived_tbl(cinfo, FALSE, actbl,
  159757. & entropy->ac_derived_tbls[actbl]);
  159758. }
  159759. /* Initialize DC predictions to 0 */
  159760. entropy->saved.last_dc_val[ci] = 0;
  159761. }
  159762. /* Initialize bit buffer to empty */
  159763. entropy->saved.put_buffer = 0;
  159764. entropy->saved.put_bits = 0;
  159765. /* Initialize restart stuff */
  159766. entropy->restarts_to_go = cinfo->restart_interval;
  159767. entropy->next_restart_num = 0;
  159768. }
  159769. /*
  159770. * Compute the derived values for a Huffman table.
  159771. * This routine also performs some validation checks on the table.
  159772. *
  159773. * Note this is also used by jcphuff.c.
  159774. */
  159775. GLOBAL(void)
  159776. jpeg_make_c_derived_tbl (j_compress_ptr cinfo, boolean isDC, int tblno,
  159777. c_derived_tbl ** pdtbl)
  159778. {
  159779. JHUFF_TBL *htbl;
  159780. c_derived_tbl *dtbl;
  159781. int p, i, l, lastp, si, maxsymbol;
  159782. char huffsize[257];
  159783. unsigned int huffcode[257];
  159784. unsigned int code;
  159785. /* Note that huffsize[] and huffcode[] are filled in code-length order,
  159786. * paralleling the order of the symbols themselves in htbl->huffval[].
  159787. */
  159788. /* Find the input Huffman table */
  159789. if (tblno < 0 || tblno >= NUM_HUFF_TBLS)
  159790. ERREXIT1(cinfo, JERR_NO_HUFF_TABLE, tblno);
  159791. htbl =
  159792. isDC ? cinfo->dc_huff_tbl_ptrs[tblno] : cinfo->ac_huff_tbl_ptrs[tblno];
  159793. if (htbl == NULL)
  159794. ERREXIT1(cinfo, JERR_NO_HUFF_TABLE, tblno);
  159795. /* Allocate a workspace if we haven't already done so. */
  159796. if (*pdtbl == NULL)
  159797. *pdtbl = (c_derived_tbl *)
  159798. (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_IMAGE,
  159799. SIZEOF(c_derived_tbl));
  159800. dtbl = *pdtbl;
  159801. /* Figure C.1: make table of Huffman code length for each symbol */
  159802. p = 0;
  159803. for (l = 1; l <= 16; l++) {
  159804. i = (int) htbl->bits[l];
  159805. if (i < 0 || p + i > 256) /* protect against table overrun */
  159806. ERREXIT(cinfo, JERR_BAD_HUFF_TABLE);
  159807. while (i--)
  159808. huffsize[p++] = (char) l;
  159809. }
  159810. huffsize[p] = 0;
  159811. lastp = p;
  159812. /* Figure C.2: generate the codes themselves */
  159813. /* We also validate that the counts represent a legal Huffman code tree. */
  159814. code = 0;
  159815. si = huffsize[0];
  159816. p = 0;
  159817. while (huffsize[p]) {
  159818. while (((int) huffsize[p]) == si) {
  159819. huffcode[p++] = code;
  159820. code++;
  159821. }
  159822. /* code is now 1 more than the last code used for codelength si; but
  159823. * it must still fit in si bits, since no code is allowed to be all ones.
  159824. */
  159825. if (((INT32) code) >= (((INT32) 1) << si))
  159826. ERREXIT(cinfo, JERR_BAD_HUFF_TABLE);
  159827. code <<= 1;
  159828. si++;
  159829. }
  159830. /* Figure C.3: generate encoding tables */
  159831. /* These are code and size indexed by symbol value */
  159832. /* Set all codeless symbols to have code length 0;
  159833. * this lets us detect duplicate VAL entries here, and later
  159834. * allows emit_bits to detect any attempt to emit such symbols.
  159835. */
  159836. MEMZERO(dtbl->ehufsi, SIZEOF(dtbl->ehufsi));
  159837. /* This is also a convenient place to check for out-of-range
  159838. * and duplicated VAL entries. We allow 0..255 for AC symbols
  159839. * but only 0..15 for DC. (We could constrain them further
  159840. * based on data depth and mode, but this seems enough.)
  159841. */
  159842. maxsymbol = isDC ? 15 : 255;
  159843. for (p = 0; p < lastp; p++) {
  159844. i = htbl->huffval[p];
  159845. if (i < 0 || i > maxsymbol || dtbl->ehufsi[i])
  159846. ERREXIT(cinfo, JERR_BAD_HUFF_TABLE);
  159847. dtbl->ehufco[i] = huffcode[p];
  159848. dtbl->ehufsi[i] = huffsize[p];
  159849. }
  159850. }
  159851. /* Outputting bytes to the file */
  159852. /* Emit a byte, taking 'action' if must suspend. */
  159853. #define emit_byte(state,val,action) \
  159854. { *(state)->next_output_byte++ = (JOCTET) (val); \
  159855. if (--(state)->free_in_buffer == 0) \
  159856. if (! dump_buffer(state)) \
  159857. { action; } }
  159858. LOCAL(boolean)
  159859. dump_buffer (working_state * state)
  159860. /* Empty the output buffer; return TRUE if successful, FALSE if must suspend */
  159861. {
  159862. struct jpeg_destination_mgr * dest = state->cinfo->dest;
  159863. if (! (*dest->empty_output_buffer) (state->cinfo))
  159864. return FALSE;
  159865. /* After a successful buffer dump, must reset buffer pointers */
  159866. state->next_output_byte = dest->next_output_byte;
  159867. state->free_in_buffer = dest->free_in_buffer;
  159868. return TRUE;
  159869. }
  159870. /* Outputting bits to the file */
  159871. /* Only the right 24 bits of put_buffer are used; the valid bits are
  159872. * left-justified in this part. At most 16 bits can be passed to emit_bits
  159873. * in one call, and we never retain more than 7 bits in put_buffer
  159874. * between calls, so 24 bits are sufficient.
  159875. */
  159876. INLINE
  159877. LOCAL(boolean)
  159878. emit_bits (working_state * state, unsigned int code, int size)
  159879. /* Emit some bits; return TRUE if successful, FALSE if must suspend */
  159880. {
  159881. /* This routine is heavily used, so it's worth coding tightly. */
  159882. register INT32 put_buffer = (INT32) code;
  159883. register int put_bits = state->cur.put_bits;
  159884. /* if size is 0, caller used an invalid Huffman table entry */
  159885. if (size == 0)
  159886. ERREXIT(state->cinfo, JERR_HUFF_MISSING_CODE);
  159887. put_buffer &= (((INT32) 1)<<size) - 1; /* mask off any extra bits in code */
  159888. put_bits += size; /* new number of bits in buffer */
  159889. put_buffer <<= 24 - put_bits; /* align incoming bits */
  159890. put_buffer |= state->cur.put_buffer; /* and merge with old buffer contents */
  159891. while (put_bits >= 8) {
  159892. int c = (int) ((put_buffer >> 16) & 0xFF);
  159893. emit_byte(state, c, return FALSE);
  159894. if (c == 0xFF) { /* need to stuff a zero byte? */
  159895. emit_byte(state, 0, return FALSE);
  159896. }
  159897. put_buffer <<= 8;
  159898. put_bits -= 8;
  159899. }
  159900. state->cur.put_buffer = put_buffer; /* update state variables */
  159901. state->cur.put_bits = put_bits;
  159902. return TRUE;
  159903. }
  159904. LOCAL(boolean)
  159905. flush_bits (working_state * state)
  159906. {
  159907. if (! emit_bits(state, 0x7F, 7)) /* fill any partial byte with ones */
  159908. return FALSE;
  159909. state->cur.put_buffer = 0; /* and reset bit-buffer to empty */
  159910. state->cur.put_bits = 0;
  159911. return TRUE;
  159912. }
  159913. /* Encode a single block's worth of coefficients */
  159914. LOCAL(boolean)
  159915. encode_one_block (working_state * state, JCOEFPTR block, int last_dc_val,
  159916. c_derived_tbl *dctbl, c_derived_tbl *actbl)
  159917. {
  159918. register int temp, temp2;
  159919. register int nbits;
  159920. register int k, r, i;
  159921. /* Encode the DC coefficient difference per section F.1.2.1 */
  159922. temp = temp2 = block[0] - last_dc_val;
  159923. if (temp < 0) {
  159924. temp = -temp; /* temp is abs value of input */
  159925. /* For a negative input, want temp2 = bitwise complement of abs(input) */
  159926. /* This code assumes we are on a two's complement machine */
  159927. temp2--;
  159928. }
  159929. /* Find the number of bits needed for the magnitude of the coefficient */
  159930. nbits = 0;
  159931. while (temp) {
  159932. nbits++;
  159933. temp >>= 1;
  159934. }
  159935. /* Check for out-of-range coefficient values.
  159936. * Since we're encoding a difference, the range limit is twice as much.
  159937. */
  159938. if (nbits > MAX_COEF_BITS+1)
  159939. ERREXIT(state->cinfo, JERR_BAD_DCT_COEF);
  159940. /* Emit the Huffman-coded symbol for the number of bits */
  159941. if (! emit_bits(state, dctbl->ehufco[nbits], dctbl->ehufsi[nbits]))
  159942. return FALSE;
  159943. /* Emit that number of bits of the value, if positive, */
  159944. /* or the complement of its magnitude, if negative. */
  159945. if (nbits) /* emit_bits rejects calls with size 0 */
  159946. if (! emit_bits(state, (unsigned int) temp2, nbits))
  159947. return FALSE;
  159948. /* Encode the AC coefficients per section F.1.2.2 */
  159949. r = 0; /* r = run length of zeros */
  159950. for (k = 1; k < DCTSIZE2; k++) {
  159951. if ((temp = block[jpeg_natural_order[k]]) == 0) {
  159952. r++;
  159953. } else {
  159954. /* if run length > 15, must emit special run-length-16 codes (0xF0) */
  159955. while (r > 15) {
  159956. if (! emit_bits(state, actbl->ehufco[0xF0], actbl->ehufsi[0xF0]))
  159957. return FALSE;
  159958. r -= 16;
  159959. }
  159960. temp2 = temp;
  159961. if (temp < 0) {
  159962. temp = -temp; /* temp is abs value of input */
  159963. /* This code assumes we are on a two's complement machine */
  159964. temp2--;
  159965. }
  159966. /* Find the number of bits needed for the magnitude of the coefficient */
  159967. nbits = 1; /* there must be at least one 1 bit */
  159968. while ((temp >>= 1))
  159969. nbits++;
  159970. /* Check for out-of-range coefficient values */
  159971. if (nbits > MAX_COEF_BITS)
  159972. ERREXIT(state->cinfo, JERR_BAD_DCT_COEF);
  159973. /* Emit Huffman symbol for run length / number of bits */
  159974. i = (r << 4) + nbits;
  159975. if (! emit_bits(state, actbl->ehufco[i], actbl->ehufsi[i]))
  159976. return FALSE;
  159977. /* Emit that number of bits of the value, if positive, */
  159978. /* or the complement of its magnitude, if negative. */
  159979. if (! emit_bits(state, (unsigned int) temp2, nbits))
  159980. return FALSE;
  159981. r = 0;
  159982. }
  159983. }
  159984. /* If the last coef(s) were zero, emit an end-of-block code */
  159985. if (r > 0)
  159986. if (! emit_bits(state, actbl->ehufco[0], actbl->ehufsi[0]))
  159987. return FALSE;
  159988. return TRUE;
  159989. }
  159990. /*
  159991. * Emit a restart marker & resynchronize predictions.
  159992. */
  159993. LOCAL(boolean)
  159994. emit_restart (working_state * state, int restart_num)
  159995. {
  159996. int ci;
  159997. if (! flush_bits(state))
  159998. return FALSE;
  159999. emit_byte(state, 0xFF, return FALSE);
  160000. emit_byte(state, JPEG_RST0 + restart_num, return FALSE);
  160001. /* Re-initialize DC predictions to 0 */
  160002. for (ci = 0; ci < state->cinfo->comps_in_scan; ci++)
  160003. state->cur.last_dc_val[ci] = 0;
  160004. /* The restart counter is not updated until we successfully write the MCU. */
  160005. return TRUE;
  160006. }
  160007. /*
  160008. * Encode and output one MCU's worth of Huffman-compressed coefficients.
  160009. */
  160010. METHODDEF(boolean)
  160011. encode_mcu_huff (j_compress_ptr cinfo, JBLOCKROW *MCU_data)
  160012. {
  160013. huff_entropy_ptr entropy = (huff_entropy_ptr) cinfo->entropy;
  160014. working_state state;
  160015. int blkn, ci;
  160016. jpeg_component_info * compptr;
  160017. /* Load up working state */
  160018. state.next_output_byte = cinfo->dest->next_output_byte;
  160019. state.free_in_buffer = cinfo->dest->free_in_buffer;
  160020. ASSIGN_STATE(state.cur, entropy->saved);
  160021. state.cinfo = cinfo;
  160022. /* Emit restart marker if needed */
  160023. if (cinfo->restart_interval) {
  160024. if (entropy->restarts_to_go == 0)
  160025. if (! emit_restart(&state, entropy->next_restart_num))
  160026. return FALSE;
  160027. }
  160028. /* Encode the MCU data blocks */
  160029. for (blkn = 0; blkn < cinfo->blocks_in_MCU; blkn++) {
  160030. ci = cinfo->MCU_membership[blkn];
  160031. compptr = cinfo->cur_comp_info[ci];
  160032. if (! encode_one_block(&state,
  160033. MCU_data[blkn][0], state.cur.last_dc_val[ci],
  160034. entropy->dc_derived_tbls[compptr->dc_tbl_no],
  160035. entropy->ac_derived_tbls[compptr->ac_tbl_no]))
  160036. return FALSE;
  160037. /* Update last_dc_val */
  160038. state.cur.last_dc_val[ci] = MCU_data[blkn][0][0];
  160039. }
  160040. /* Completed MCU, so update state */
  160041. cinfo->dest->next_output_byte = state.next_output_byte;
  160042. cinfo->dest->free_in_buffer = state.free_in_buffer;
  160043. ASSIGN_STATE(entropy->saved, state.cur);
  160044. /* Update restart-interval state too */
  160045. if (cinfo->restart_interval) {
  160046. if (entropy->restarts_to_go == 0) {
  160047. entropy->restarts_to_go = cinfo->restart_interval;
  160048. entropy->next_restart_num++;
  160049. entropy->next_restart_num &= 7;
  160050. }
  160051. entropy->restarts_to_go--;
  160052. }
  160053. return TRUE;
  160054. }
  160055. /*
  160056. * Finish up at the end of a Huffman-compressed scan.
  160057. */
  160058. METHODDEF(void)
  160059. finish_pass_huff (j_compress_ptr cinfo)
  160060. {
  160061. huff_entropy_ptr entropy = (huff_entropy_ptr) cinfo->entropy;
  160062. working_state state;
  160063. /* Load up working state ... flush_bits needs it */
  160064. state.next_output_byte = cinfo->dest->next_output_byte;
  160065. state.free_in_buffer = cinfo->dest->free_in_buffer;
  160066. ASSIGN_STATE(state.cur, entropy->saved);
  160067. state.cinfo = cinfo;
  160068. /* Flush out the last data */
  160069. if (! flush_bits(&state))
  160070. ERREXIT(cinfo, JERR_CANT_SUSPEND);
  160071. /* Update state */
  160072. cinfo->dest->next_output_byte = state.next_output_byte;
  160073. cinfo->dest->free_in_buffer = state.free_in_buffer;
  160074. ASSIGN_STATE(entropy->saved, state.cur);
  160075. }
  160076. /*
  160077. * Huffman coding optimization.
  160078. *
  160079. * We first scan the supplied data and count the number of uses of each symbol
  160080. * that is to be Huffman-coded. (This process MUST agree with the code above.)
  160081. * Then we build a Huffman coding tree for the observed counts.
  160082. * Symbols which are not needed at all for the particular image are not
  160083. * assigned any code, which saves space in the DHT marker as well as in
  160084. * the compressed data.
  160085. */
  160086. #ifdef ENTROPY_OPT_SUPPORTED
  160087. /* Process a single block's worth of coefficients */
  160088. LOCAL(void)
  160089. htest_one_block (j_compress_ptr cinfo, JCOEFPTR block, int last_dc_val,
  160090. long dc_counts[], long ac_counts[])
  160091. {
  160092. register int temp;
  160093. register int nbits;
  160094. register int k, r;
  160095. /* Encode the DC coefficient difference per section F.1.2.1 */
  160096. temp = block[0] - last_dc_val;
  160097. if (temp < 0)
  160098. temp = -temp;
  160099. /* Find the number of bits needed for the magnitude of the coefficient */
  160100. nbits = 0;
  160101. while (temp) {
  160102. nbits++;
  160103. temp >>= 1;
  160104. }
  160105. /* Check for out-of-range coefficient values.
  160106. * Since we're encoding a difference, the range limit is twice as much.
  160107. */
  160108. if (nbits > MAX_COEF_BITS+1)
  160109. ERREXIT(cinfo, JERR_BAD_DCT_COEF);
  160110. /* Count the Huffman symbol for the number of bits */
  160111. dc_counts[nbits]++;
  160112. /* Encode the AC coefficients per section F.1.2.2 */
  160113. r = 0; /* r = run length of zeros */
  160114. for (k = 1; k < DCTSIZE2; k++) {
  160115. if ((temp = block[jpeg_natural_order[k]]) == 0) {
  160116. r++;
  160117. } else {
  160118. /* if run length > 15, must emit special run-length-16 codes (0xF0) */
  160119. while (r > 15) {
  160120. ac_counts[0xF0]++;
  160121. r -= 16;
  160122. }
  160123. /* Find the number of bits needed for the magnitude of the coefficient */
  160124. if (temp < 0)
  160125. temp = -temp;
  160126. /* Find the number of bits needed for the magnitude of the coefficient */
  160127. nbits = 1; /* there must be at least one 1 bit */
  160128. while ((temp >>= 1))
  160129. nbits++;
  160130. /* Check for out-of-range coefficient values */
  160131. if (nbits > MAX_COEF_BITS)
  160132. ERREXIT(cinfo, JERR_BAD_DCT_COEF);
  160133. /* Count Huffman symbol for run length / number of bits */
  160134. ac_counts[(r << 4) + nbits]++;
  160135. r = 0;
  160136. }
  160137. }
  160138. /* If the last coef(s) were zero, emit an end-of-block code */
  160139. if (r > 0)
  160140. ac_counts[0]++;
  160141. }
  160142. /*
  160143. * Trial-encode one MCU's worth of Huffman-compressed coefficients.
  160144. * No data is actually output, so no suspension return is possible.
  160145. */
  160146. METHODDEF(boolean)
  160147. encode_mcu_gather (j_compress_ptr cinfo, JBLOCKROW *MCU_data)
  160148. {
  160149. huff_entropy_ptr entropy = (huff_entropy_ptr) cinfo->entropy;
  160150. int blkn, ci;
  160151. jpeg_component_info * compptr;
  160152. /* Take care of restart intervals if needed */
  160153. if (cinfo->restart_interval) {
  160154. if (entropy->restarts_to_go == 0) {
  160155. /* Re-initialize DC predictions to 0 */
  160156. for (ci = 0; ci < cinfo->comps_in_scan; ci++)
  160157. entropy->saved.last_dc_val[ci] = 0;
  160158. /* Update restart state */
  160159. entropy->restarts_to_go = cinfo->restart_interval;
  160160. }
  160161. entropy->restarts_to_go--;
  160162. }
  160163. for (blkn = 0; blkn < cinfo->blocks_in_MCU; blkn++) {
  160164. ci = cinfo->MCU_membership[blkn];
  160165. compptr = cinfo->cur_comp_info[ci];
  160166. htest_one_block(cinfo, MCU_data[blkn][0], entropy->saved.last_dc_val[ci],
  160167. entropy->dc_count_ptrs[compptr->dc_tbl_no],
  160168. entropy->ac_count_ptrs[compptr->ac_tbl_no]);
  160169. entropy->saved.last_dc_val[ci] = MCU_data[blkn][0][0];
  160170. }
  160171. return TRUE;
  160172. }
  160173. /*
  160174. * Generate the best Huffman code table for the given counts, fill htbl.
  160175. * Note this is also used by jcphuff.c.
  160176. *
  160177. * The JPEG standard requires that no symbol be assigned a codeword of all
  160178. * one bits (so that padding bits added at the end of a compressed segment
  160179. * can't look like a valid code). Because of the canonical ordering of
  160180. * codewords, this just means that there must be an unused slot in the
  160181. * longest codeword length category. Section K.2 of the JPEG spec suggests
  160182. * reserving such a slot by pretending that symbol 256 is a valid symbol
  160183. * with count 1. In theory that's not optimal; giving it count zero but
  160184. * including it in the symbol set anyway should give a better Huffman code.
  160185. * But the theoretically better code actually seems to come out worse in
  160186. * practice, because it produces more all-ones bytes (which incur stuffed
  160187. * zero bytes in the final file). In any case the difference is tiny.
  160188. *
  160189. * The JPEG standard requires Huffman codes to be no more than 16 bits long.
  160190. * If some symbols have a very small but nonzero probability, the Huffman tree
  160191. * must be adjusted to meet the code length restriction. We currently use
  160192. * the adjustment method suggested in JPEG section K.2. This method is *not*
  160193. * optimal; it may not choose the best possible limited-length code. But
  160194. * typically only very-low-frequency symbols will be given less-than-optimal
  160195. * lengths, so the code is almost optimal. Experimental comparisons against
  160196. * an optimal limited-length-code algorithm indicate that the difference is
  160197. * microscopic --- usually less than a hundredth of a percent of total size.
  160198. * So the extra complexity of an optimal algorithm doesn't seem worthwhile.
  160199. */
  160200. GLOBAL(void)
  160201. jpeg_gen_optimal_table (j_compress_ptr cinfo, JHUFF_TBL * htbl, long freq[])
  160202. {
  160203. #define MAX_CLEN 32 /* assumed maximum initial code length */
  160204. UINT8 bits[MAX_CLEN+1]; /* bits[k] = # of symbols with code length k */
  160205. int codesize[257]; /* codesize[k] = code length of symbol k */
  160206. int others[257]; /* next symbol in current branch of tree */
  160207. int c1, c2;
  160208. int p, i, j;
  160209. long v;
  160210. /* This algorithm is explained in section K.2 of the JPEG standard */
  160211. MEMZERO(bits, SIZEOF(bits));
  160212. MEMZERO(codesize, SIZEOF(codesize));
  160213. for (i = 0; i < 257; i++)
  160214. others[i] = -1; /* init links to empty */
  160215. freq[256] = 1; /* make sure 256 has a nonzero count */
  160216. /* Including the pseudo-symbol 256 in the Huffman procedure guarantees
  160217. * that no real symbol is given code-value of all ones, because 256
  160218. * will be placed last in the largest codeword category.
  160219. */
  160220. /* Huffman's basic algorithm to assign optimal code lengths to symbols */
  160221. for (;;) {
  160222. /* Find the smallest nonzero frequency, set c1 = its symbol */
  160223. /* In case of ties, take the larger symbol number */
  160224. c1 = -1;
  160225. v = 1000000000L;
  160226. for (i = 0; i <= 256; i++) {
  160227. if (freq[i] && freq[i] <= v) {
  160228. v = freq[i];
  160229. c1 = i;
  160230. }
  160231. }
  160232. /* Find the next smallest nonzero frequency, set c2 = its symbol */
  160233. /* In case of ties, take the larger symbol number */
  160234. c2 = -1;
  160235. v = 1000000000L;
  160236. for (i = 0; i <= 256; i++) {
  160237. if (freq[i] && freq[i] <= v && i != c1) {
  160238. v = freq[i];
  160239. c2 = i;
  160240. }
  160241. }
  160242. /* Done if we've merged everything into one frequency */
  160243. if (c2 < 0)
  160244. break;
  160245. /* Else merge the two counts/trees */
  160246. freq[c1] += freq[c2];
  160247. freq[c2] = 0;
  160248. /* Increment the codesize of everything in c1's tree branch */
  160249. codesize[c1]++;
  160250. while (others[c1] >= 0) {
  160251. c1 = others[c1];
  160252. codesize[c1]++;
  160253. }
  160254. others[c1] = c2; /* chain c2 onto c1's tree branch */
  160255. /* Increment the codesize of everything in c2's tree branch */
  160256. codesize[c2]++;
  160257. while (others[c2] >= 0) {
  160258. c2 = others[c2];
  160259. codesize[c2]++;
  160260. }
  160261. }
  160262. /* Now count the number of symbols of each code length */
  160263. for (i = 0; i <= 256; i++) {
  160264. if (codesize[i]) {
  160265. /* The JPEG standard seems to think that this can't happen, */
  160266. /* but I'm paranoid... */
  160267. if (codesize[i] > MAX_CLEN)
  160268. ERREXIT(cinfo, JERR_HUFF_CLEN_OVERFLOW);
  160269. bits[codesize[i]]++;
  160270. }
  160271. }
  160272. /* JPEG doesn't allow symbols with code lengths over 16 bits, so if the pure
  160273. * Huffman procedure assigned any such lengths, we must adjust the coding.
  160274. * Here is what the JPEG spec says about how this next bit works:
  160275. * Since symbols are paired for the longest Huffman code, the symbols are
  160276. * removed from this length category two at a time. The prefix for the pair
  160277. * (which is one bit shorter) is allocated to one of the pair; then,
  160278. * skipping the BITS entry for that prefix length, a code word from the next
  160279. * shortest nonzero BITS entry is converted into a prefix for two code words
  160280. * one bit longer.
  160281. */
  160282. for (i = MAX_CLEN; i > 16; i--) {
  160283. while (bits[i] > 0) {
  160284. j = i - 2; /* find length of new prefix to be used */
  160285. while (bits[j] == 0)
  160286. j--;
  160287. bits[i] -= 2; /* remove two symbols */
  160288. bits[i-1]++; /* one goes in this length */
  160289. bits[j+1] += 2; /* two new symbols in this length */
  160290. bits[j]--; /* symbol of this length is now a prefix */
  160291. }
  160292. }
  160293. /* Remove the count for the pseudo-symbol 256 from the largest codelength */
  160294. while (bits[i] == 0) /* find largest codelength still in use */
  160295. i--;
  160296. bits[i]--;
  160297. /* Return final symbol counts (only for lengths 0..16) */
  160298. MEMCOPY(htbl->bits, bits, SIZEOF(htbl->bits));
  160299. /* Return a list of the symbols sorted by code length */
  160300. /* It's not real clear to me why we don't need to consider the codelength
  160301. * changes made above, but the JPEG spec seems to think this works.
  160302. */
  160303. p = 0;
  160304. for (i = 1; i <= MAX_CLEN; i++) {
  160305. for (j = 0; j <= 255; j++) {
  160306. if (codesize[j] == i) {
  160307. htbl->huffval[p] = (UINT8) j;
  160308. p++;
  160309. }
  160310. }
  160311. }
  160312. /* Set sent_table FALSE so updated table will be written to JPEG file. */
  160313. htbl->sent_table = FALSE;
  160314. }
  160315. /*
  160316. * Finish up a statistics-gathering pass and create the new Huffman tables.
  160317. */
  160318. METHODDEF(void)
  160319. finish_pass_gather (j_compress_ptr cinfo)
  160320. {
  160321. huff_entropy_ptr entropy = (huff_entropy_ptr) cinfo->entropy;
  160322. int ci, dctbl, actbl;
  160323. jpeg_component_info * compptr;
  160324. JHUFF_TBL **htblptr;
  160325. boolean did_dc[NUM_HUFF_TBLS];
  160326. boolean did_ac[NUM_HUFF_TBLS];
  160327. /* It's important not to apply jpeg_gen_optimal_table more than once
  160328. * per table, because it clobbers the input frequency counts!
  160329. */
  160330. MEMZERO(did_dc, SIZEOF(did_dc));
  160331. MEMZERO(did_ac, SIZEOF(did_ac));
  160332. for (ci = 0; ci < cinfo->comps_in_scan; ci++) {
  160333. compptr = cinfo->cur_comp_info[ci];
  160334. dctbl = compptr->dc_tbl_no;
  160335. actbl = compptr->ac_tbl_no;
  160336. if (! did_dc[dctbl]) {
  160337. htblptr = & cinfo->dc_huff_tbl_ptrs[dctbl];
  160338. if (*htblptr == NULL)
  160339. *htblptr = jpeg_alloc_huff_table((j_common_ptr) cinfo);
  160340. jpeg_gen_optimal_table(cinfo, *htblptr, entropy->dc_count_ptrs[dctbl]);
  160341. did_dc[dctbl] = TRUE;
  160342. }
  160343. if (! did_ac[actbl]) {
  160344. htblptr = & cinfo->ac_huff_tbl_ptrs[actbl];
  160345. if (*htblptr == NULL)
  160346. *htblptr = jpeg_alloc_huff_table((j_common_ptr) cinfo);
  160347. jpeg_gen_optimal_table(cinfo, *htblptr, entropy->ac_count_ptrs[actbl]);
  160348. did_ac[actbl] = TRUE;
  160349. }
  160350. }
  160351. }
  160352. #endif /* ENTROPY_OPT_SUPPORTED */
  160353. /*
  160354. * Module initialization routine for Huffman entropy encoding.
  160355. */
  160356. GLOBAL(void)
  160357. jinit_huff_encoder (j_compress_ptr cinfo)
  160358. {
  160359. huff_entropy_ptr entropy;
  160360. int i;
  160361. entropy = (huff_entropy_ptr)
  160362. (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_IMAGE,
  160363. SIZEOF(huff_entropy_encoder));
  160364. cinfo->entropy = (struct jpeg_entropy_encoder *) entropy;
  160365. entropy->pub.start_pass = start_pass_huff;
  160366. /* Mark tables unallocated */
  160367. for (i = 0; i < NUM_HUFF_TBLS; i++) {
  160368. entropy->dc_derived_tbls[i] = entropy->ac_derived_tbls[i] = NULL;
  160369. #ifdef ENTROPY_OPT_SUPPORTED
  160370. entropy->dc_count_ptrs[i] = entropy->ac_count_ptrs[i] = NULL;
  160371. #endif
  160372. }
  160373. }
  160374. /*** End of inlined file: jchuff.c ***/
  160375. #undef emit_byte
  160376. /*** Start of inlined file: jcinit.c ***/
  160377. #define JPEG_INTERNALS
  160378. /*
  160379. * Master selection of compression modules.
  160380. * This is done once at the start of processing an image. We determine
  160381. * which modules will be used and give them appropriate initialization calls.
  160382. */
  160383. GLOBAL(void)
  160384. jinit_compress_master (j_compress_ptr cinfo)
  160385. {
  160386. /* Initialize master control (includes parameter checking/processing) */
  160387. jinit_c_master_control(cinfo, FALSE /* full compression */);
  160388. /* Preprocessing */
  160389. if (! cinfo->raw_data_in) {
  160390. jinit_color_converter(cinfo);
  160391. jinit_downsampler(cinfo);
  160392. jinit_c_prep_controller(cinfo, FALSE /* never need full buffer here */);
  160393. }
  160394. /* Forward DCT */
  160395. jinit_forward_dct(cinfo);
  160396. /* Entropy encoding: either Huffman or arithmetic coding. */
  160397. if (cinfo->arith_code) {
  160398. ERREXIT(cinfo, JERR_ARITH_NOTIMPL);
  160399. } else {
  160400. if (cinfo->progressive_mode) {
  160401. #ifdef C_PROGRESSIVE_SUPPORTED
  160402. jinit_phuff_encoder(cinfo);
  160403. #else
  160404. ERREXIT(cinfo, JERR_NOT_COMPILED);
  160405. #endif
  160406. } else
  160407. jinit_huff_encoder(cinfo);
  160408. }
  160409. /* Need a full-image coefficient buffer in any multi-pass mode. */
  160410. jinit_c_coef_controller(cinfo,
  160411. (boolean) (cinfo->num_scans > 1 || cinfo->optimize_coding));
  160412. jinit_c_main_controller(cinfo, FALSE /* never need full buffer here */);
  160413. jinit_marker_writer(cinfo);
  160414. /* We can now tell the memory manager to allocate virtual arrays. */
  160415. (*cinfo->mem->realize_virt_arrays) ((j_common_ptr) cinfo);
  160416. /* Write the datastream header (SOI) immediately.
  160417. * Frame and scan headers are postponed till later.
  160418. * This lets application insert special markers after the SOI.
  160419. */
  160420. (*cinfo->marker->write_file_header) (cinfo);
  160421. }
  160422. /*** End of inlined file: jcinit.c ***/
  160423. /*** Start of inlined file: jcmainct.c ***/
  160424. #define JPEG_INTERNALS
  160425. /* Note: currently, there is no operating mode in which a full-image buffer
  160426. * is needed at this step. If there were, that mode could not be used with
  160427. * "raw data" input, since this module is bypassed in that case. However,
  160428. * we've left the code here for possible use in special applications.
  160429. */
  160430. #undef FULL_MAIN_BUFFER_SUPPORTED
  160431. /* Private buffer controller object */
  160432. typedef struct {
  160433. struct jpeg_c_main_controller pub; /* public fields */
  160434. JDIMENSION cur_iMCU_row; /* number of current iMCU row */
  160435. JDIMENSION rowgroup_ctr; /* counts row groups received in iMCU row */
  160436. boolean suspended; /* remember if we suspended output */
  160437. J_BUF_MODE pass_mode; /* current operating mode */
  160438. /* If using just a strip buffer, this points to the entire set of buffers
  160439. * (we allocate one for each component). In the full-image case, this
  160440. * points to the currently accessible strips of the virtual arrays.
  160441. */
  160442. JSAMPARRAY buffer[MAX_COMPONENTS];
  160443. #ifdef FULL_MAIN_BUFFER_SUPPORTED
  160444. /* If using full-image storage, this array holds pointers to virtual-array
  160445. * control blocks for each component. Unused if not full-image storage.
  160446. */
  160447. jvirt_sarray_ptr whole_image[MAX_COMPONENTS];
  160448. #endif
  160449. } my_main_controller;
  160450. typedef my_main_controller * my_main_ptr;
  160451. /* Forward declarations */
  160452. METHODDEF(void) process_data_simple_main
  160453. JPP((j_compress_ptr cinfo, JSAMPARRAY input_buf,
  160454. JDIMENSION *in_row_ctr, JDIMENSION in_rows_avail));
  160455. #ifdef FULL_MAIN_BUFFER_SUPPORTED
  160456. METHODDEF(void) process_data_buffer_main
  160457. JPP((j_compress_ptr cinfo, JSAMPARRAY input_buf,
  160458. JDIMENSION *in_row_ctr, JDIMENSION in_rows_avail));
  160459. #endif
  160460. /*
  160461. * Initialize for a processing pass.
  160462. */
  160463. METHODDEF(void)
  160464. start_pass_main (j_compress_ptr cinfo, J_BUF_MODE pass_mode)
  160465. {
  160466. my_main_ptr main_ = (my_main_ptr) cinfo->main;
  160467. /* Do nothing in raw-data mode. */
  160468. if (cinfo->raw_data_in)
  160469. return;
  160470. main_->cur_iMCU_row = 0; /* initialize counters */
  160471. main_->rowgroup_ctr = 0;
  160472. main_->suspended = FALSE;
  160473. main_->pass_mode = pass_mode; /* save mode for use by process_data */
  160474. switch (pass_mode) {
  160475. case JBUF_PASS_THRU:
  160476. #ifdef FULL_MAIN_BUFFER_SUPPORTED
  160477. if (main_->whole_image[0] != NULL)
  160478. ERREXIT(cinfo, JERR_BAD_BUFFER_MODE);
  160479. #endif
  160480. main_->pub.process_data = process_data_simple_main;
  160481. break;
  160482. #ifdef FULL_MAIN_BUFFER_SUPPORTED
  160483. case JBUF_SAVE_SOURCE:
  160484. case JBUF_CRANK_DEST:
  160485. case JBUF_SAVE_AND_PASS:
  160486. if (main_->whole_image[0] == NULL)
  160487. ERREXIT(cinfo, JERR_BAD_BUFFER_MODE);
  160488. main_->pub.process_data = process_data_buffer_main;
  160489. break;
  160490. #endif
  160491. default:
  160492. ERREXIT(cinfo, JERR_BAD_BUFFER_MODE);
  160493. break;
  160494. }
  160495. }
  160496. /*
  160497. * Process some data.
  160498. * This routine handles the simple pass-through mode,
  160499. * where we have only a strip buffer.
  160500. */
  160501. METHODDEF(void)
  160502. process_data_simple_main (j_compress_ptr cinfo,
  160503. JSAMPARRAY input_buf, JDIMENSION *in_row_ctr,
  160504. JDIMENSION in_rows_avail)
  160505. {
  160506. my_main_ptr main_ = (my_main_ptr) cinfo->main;
  160507. while (main_->cur_iMCU_row < cinfo->total_iMCU_rows) {
  160508. /* Read input data if we haven't filled the main buffer yet */
  160509. if (main_->rowgroup_ctr < DCTSIZE)
  160510. (*cinfo->prep->pre_process_data) (cinfo,
  160511. input_buf, in_row_ctr, in_rows_avail,
  160512. main_->buffer, &main_->rowgroup_ctr,
  160513. (JDIMENSION) DCTSIZE);
  160514. /* If we don't have a full iMCU row buffered, return to application for
  160515. * more data. Note that preprocessor will always pad to fill the iMCU row
  160516. * at the bottom of the image.
  160517. */
  160518. if (main_->rowgroup_ctr != DCTSIZE)
  160519. return;
  160520. /* Send the completed row to the compressor */
  160521. if (! (*cinfo->coef->compress_data) (cinfo, main_->buffer)) {
  160522. /* If compressor did not consume the whole row, then we must need to
  160523. * suspend processing and return to the application. In this situation
  160524. * we pretend we didn't yet consume the last input row; otherwise, if
  160525. * it happened to be the last row of the image, the application would
  160526. * think we were done.
  160527. */
  160528. if (! main_->suspended) {
  160529. (*in_row_ctr)--;
  160530. main_->suspended = TRUE;
  160531. }
  160532. return;
  160533. }
  160534. /* We did finish the row. Undo our little suspension hack if a previous
  160535. * call suspended; then mark the main buffer empty.
  160536. */
  160537. if (main_->suspended) {
  160538. (*in_row_ctr)++;
  160539. main_->suspended = FALSE;
  160540. }
  160541. main_->rowgroup_ctr = 0;
  160542. main_->cur_iMCU_row++;
  160543. }
  160544. }
  160545. #ifdef FULL_MAIN_BUFFER_SUPPORTED
  160546. /*
  160547. * Process some data.
  160548. * This routine handles all of the modes that use a full-size buffer.
  160549. */
  160550. METHODDEF(void)
  160551. process_data_buffer_main (j_compress_ptr cinfo,
  160552. JSAMPARRAY input_buf, JDIMENSION *in_row_ctr,
  160553. JDIMENSION in_rows_avail)
  160554. {
  160555. my_main_ptr main = (my_main_ptr) cinfo->main;
  160556. int ci;
  160557. jpeg_component_info *compptr;
  160558. boolean writing = (main->pass_mode != JBUF_CRANK_DEST);
  160559. while (main->cur_iMCU_row < cinfo->total_iMCU_rows) {
  160560. /* Realign the virtual buffers if at the start of an iMCU row. */
  160561. if (main->rowgroup_ctr == 0) {
  160562. for (ci = 0, compptr = cinfo->comp_info; ci < cinfo->num_components;
  160563. ci++, compptr++) {
  160564. main->buffer[ci] = (*cinfo->mem->access_virt_sarray)
  160565. ((j_common_ptr) cinfo, main->whole_image[ci],
  160566. main->cur_iMCU_row * (compptr->v_samp_factor * DCTSIZE),
  160567. (JDIMENSION) (compptr->v_samp_factor * DCTSIZE), writing);
  160568. }
  160569. /* In a read pass, pretend we just read some source data. */
  160570. if (! writing) {
  160571. *in_row_ctr += cinfo->max_v_samp_factor * DCTSIZE;
  160572. main->rowgroup_ctr = DCTSIZE;
  160573. }
  160574. }
  160575. /* If a write pass, read input data until the current iMCU row is full. */
  160576. /* Note: preprocessor will pad if necessary to fill the last iMCU row. */
  160577. if (writing) {
  160578. (*cinfo->prep->pre_process_data) (cinfo,
  160579. input_buf, in_row_ctr, in_rows_avail,
  160580. main->buffer, &main->rowgroup_ctr,
  160581. (JDIMENSION) DCTSIZE);
  160582. /* Return to application if we need more data to fill the iMCU row. */
  160583. if (main->rowgroup_ctr < DCTSIZE)
  160584. return;
  160585. }
  160586. /* Emit data, unless this is a sink-only pass. */
  160587. if (main->pass_mode != JBUF_SAVE_SOURCE) {
  160588. if (! (*cinfo->coef->compress_data) (cinfo, main->buffer)) {
  160589. /* If compressor did not consume the whole row, then we must need to
  160590. * suspend processing and return to the application. In this situation
  160591. * we pretend we didn't yet consume the last input row; otherwise, if
  160592. * it happened to be the last row of the image, the application would
  160593. * think we were done.
  160594. */
  160595. if (! main->suspended) {
  160596. (*in_row_ctr)--;
  160597. main->suspended = TRUE;
  160598. }
  160599. return;
  160600. }
  160601. /* We did finish the row. Undo our little suspension hack if a previous
  160602. * call suspended; then mark the main buffer empty.
  160603. */
  160604. if (main->suspended) {
  160605. (*in_row_ctr)++;
  160606. main->suspended = FALSE;
  160607. }
  160608. }
  160609. /* If get here, we are done with this iMCU row. Mark buffer empty. */
  160610. main->rowgroup_ctr = 0;
  160611. main->cur_iMCU_row++;
  160612. }
  160613. }
  160614. #endif /* FULL_MAIN_BUFFER_SUPPORTED */
  160615. /*
  160616. * Initialize main buffer controller.
  160617. */
  160618. GLOBAL(void)
  160619. jinit_c_main_controller (j_compress_ptr cinfo, boolean need_full_buffer)
  160620. {
  160621. my_main_ptr main_;
  160622. int ci;
  160623. jpeg_component_info *compptr;
  160624. main_ = (my_main_ptr)
  160625. (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_IMAGE,
  160626. SIZEOF(my_main_controller));
  160627. cinfo->main = (struct jpeg_c_main_controller *) main_;
  160628. main_->pub.start_pass = start_pass_main;
  160629. /* We don't need to create a buffer in raw-data mode. */
  160630. if (cinfo->raw_data_in)
  160631. return;
  160632. /* Create the buffer. It holds downsampled data, so each component
  160633. * may be of a different size.
  160634. */
  160635. if (need_full_buffer) {
  160636. #ifdef FULL_MAIN_BUFFER_SUPPORTED
  160637. /* Allocate a full-image virtual array for each component */
  160638. /* Note we pad the bottom to a multiple of the iMCU height */
  160639. for (ci = 0, compptr = cinfo->comp_info; ci < cinfo->num_components;
  160640. ci++, compptr++) {
  160641. main->whole_image[ci] = (*cinfo->mem->request_virt_sarray)
  160642. ((j_common_ptr) cinfo, JPOOL_IMAGE, FALSE,
  160643. compptr->width_in_blocks * DCTSIZE,
  160644. (JDIMENSION) jround_up((long) compptr->height_in_blocks,
  160645. (long) compptr->v_samp_factor) * DCTSIZE,
  160646. (JDIMENSION) (compptr->v_samp_factor * DCTSIZE));
  160647. }
  160648. #else
  160649. ERREXIT(cinfo, JERR_BAD_BUFFER_MODE);
  160650. #endif
  160651. } else {
  160652. #ifdef FULL_MAIN_BUFFER_SUPPORTED
  160653. main_->whole_image[0] = NULL; /* flag for no virtual arrays */
  160654. #endif
  160655. /* Allocate a strip buffer for each component */
  160656. for (ci = 0, compptr = cinfo->comp_info; ci < cinfo->num_components;
  160657. ci++, compptr++) {
  160658. main_->buffer[ci] = (*cinfo->mem->alloc_sarray)
  160659. ((j_common_ptr) cinfo, JPOOL_IMAGE,
  160660. compptr->width_in_blocks * DCTSIZE,
  160661. (JDIMENSION) (compptr->v_samp_factor * DCTSIZE));
  160662. }
  160663. }
  160664. }
  160665. /*** End of inlined file: jcmainct.c ***/
  160666. /*** Start of inlined file: jcmarker.c ***/
  160667. #define JPEG_INTERNALS
  160668. /* Private state */
  160669. typedef struct {
  160670. struct jpeg_marker_writer pub; /* public fields */
  160671. unsigned int last_restart_interval; /* last DRI value emitted; 0 after SOI */
  160672. } my_marker_writer;
  160673. typedef my_marker_writer * my_marker_ptr;
  160674. /*
  160675. * Basic output routines.
  160676. *
  160677. * Note that we do not support suspension while writing a marker.
  160678. * Therefore, an application using suspension must ensure that there is
  160679. * enough buffer space for the initial markers (typ. 600-700 bytes) before
  160680. * calling jpeg_start_compress, and enough space to write the trailing EOI
  160681. * (a few bytes) before calling jpeg_finish_compress. Multipass compression
  160682. * modes are not supported at all with suspension, so those two are the only
  160683. * points where markers will be written.
  160684. */
  160685. LOCAL(void)
  160686. emit_byte (j_compress_ptr cinfo, int val)
  160687. /* Emit a byte */
  160688. {
  160689. struct jpeg_destination_mgr * dest = cinfo->dest;
  160690. *(dest->next_output_byte)++ = (JOCTET) val;
  160691. if (--dest->free_in_buffer == 0) {
  160692. if (! (*dest->empty_output_buffer) (cinfo))
  160693. ERREXIT(cinfo, JERR_CANT_SUSPEND);
  160694. }
  160695. }
  160696. LOCAL(void)
  160697. emit_marker (j_compress_ptr cinfo, JPEG_MARKER mark)
  160698. /* Emit a marker code */
  160699. {
  160700. emit_byte(cinfo, 0xFF);
  160701. emit_byte(cinfo, (int) mark);
  160702. }
  160703. LOCAL(void)
  160704. emit_2bytes (j_compress_ptr cinfo, int value)
  160705. /* Emit a 2-byte integer; these are always MSB first in JPEG files */
  160706. {
  160707. emit_byte(cinfo, (value >> 8) & 0xFF);
  160708. emit_byte(cinfo, value & 0xFF);
  160709. }
  160710. /*
  160711. * Routines to write specific marker types.
  160712. */
  160713. LOCAL(int)
  160714. emit_dqt (j_compress_ptr cinfo, int index)
  160715. /* Emit a DQT marker */
  160716. /* Returns the precision used (0 = 8bits, 1 = 16bits) for baseline checking */
  160717. {
  160718. JQUANT_TBL * qtbl = cinfo->quant_tbl_ptrs[index];
  160719. int prec;
  160720. int i;
  160721. if (qtbl == NULL)
  160722. ERREXIT1(cinfo, JERR_NO_QUANT_TABLE, index);
  160723. prec = 0;
  160724. for (i = 0; i < DCTSIZE2; i++) {
  160725. if (qtbl->quantval[i] > 255)
  160726. prec = 1;
  160727. }
  160728. if (! qtbl->sent_table) {
  160729. emit_marker(cinfo, M_DQT);
  160730. emit_2bytes(cinfo, prec ? DCTSIZE2*2 + 1 + 2 : DCTSIZE2 + 1 + 2);
  160731. emit_byte(cinfo, index + (prec<<4));
  160732. for (i = 0; i < DCTSIZE2; i++) {
  160733. /* The table entries must be emitted in zigzag order. */
  160734. unsigned int qval = qtbl->quantval[jpeg_natural_order[i]];
  160735. if (prec)
  160736. emit_byte(cinfo, (int) (qval >> 8));
  160737. emit_byte(cinfo, (int) (qval & 0xFF));
  160738. }
  160739. qtbl->sent_table = TRUE;
  160740. }
  160741. return prec;
  160742. }
  160743. LOCAL(void)
  160744. emit_dht (j_compress_ptr cinfo, int index, boolean is_ac)
  160745. /* Emit a DHT marker */
  160746. {
  160747. JHUFF_TBL * htbl;
  160748. int length, i;
  160749. if (is_ac) {
  160750. htbl = cinfo->ac_huff_tbl_ptrs[index];
  160751. index += 0x10; /* output index has AC bit set */
  160752. } else {
  160753. htbl = cinfo->dc_huff_tbl_ptrs[index];
  160754. }
  160755. if (htbl == NULL)
  160756. ERREXIT1(cinfo, JERR_NO_HUFF_TABLE, index);
  160757. if (! htbl->sent_table) {
  160758. emit_marker(cinfo, M_DHT);
  160759. length = 0;
  160760. for (i = 1; i <= 16; i++)
  160761. length += htbl->bits[i];
  160762. emit_2bytes(cinfo, length + 2 + 1 + 16);
  160763. emit_byte(cinfo, index);
  160764. for (i = 1; i <= 16; i++)
  160765. emit_byte(cinfo, htbl->bits[i]);
  160766. for (i = 0; i < length; i++)
  160767. emit_byte(cinfo, htbl->huffval[i]);
  160768. htbl->sent_table = TRUE;
  160769. }
  160770. }
  160771. LOCAL(void)
  160772. emit_dac (j_compress_ptr cinfo)
  160773. /* Emit a DAC marker */
  160774. /* Since the useful info is so small, we want to emit all the tables in */
  160775. /* one DAC marker. Therefore this routine does its own scan of the table. */
  160776. {
  160777. #ifdef C_ARITH_CODING_SUPPORTED
  160778. char dc_in_use[NUM_ARITH_TBLS];
  160779. char ac_in_use[NUM_ARITH_TBLS];
  160780. int length, i;
  160781. jpeg_component_info *compptr;
  160782. for (i = 0; i < NUM_ARITH_TBLS; i++)
  160783. dc_in_use[i] = ac_in_use[i] = 0;
  160784. for (i = 0; i < cinfo->comps_in_scan; i++) {
  160785. compptr = cinfo->cur_comp_info[i];
  160786. dc_in_use[compptr->dc_tbl_no] = 1;
  160787. ac_in_use[compptr->ac_tbl_no] = 1;
  160788. }
  160789. length = 0;
  160790. for (i = 0; i < NUM_ARITH_TBLS; i++)
  160791. length += dc_in_use[i] + ac_in_use[i];
  160792. emit_marker(cinfo, M_DAC);
  160793. emit_2bytes(cinfo, length*2 + 2);
  160794. for (i = 0; i < NUM_ARITH_TBLS; i++) {
  160795. if (dc_in_use[i]) {
  160796. emit_byte(cinfo, i);
  160797. emit_byte(cinfo, cinfo->arith_dc_L[i] + (cinfo->arith_dc_U[i]<<4));
  160798. }
  160799. if (ac_in_use[i]) {
  160800. emit_byte(cinfo, i + 0x10);
  160801. emit_byte(cinfo, cinfo->arith_ac_K[i]);
  160802. }
  160803. }
  160804. #endif /* C_ARITH_CODING_SUPPORTED */
  160805. }
  160806. LOCAL(void)
  160807. emit_dri (j_compress_ptr cinfo)
  160808. /* Emit a DRI marker */
  160809. {
  160810. emit_marker(cinfo, M_DRI);
  160811. emit_2bytes(cinfo, 4); /* fixed length */
  160812. emit_2bytes(cinfo, (int) cinfo->restart_interval);
  160813. }
  160814. LOCAL(void)
  160815. emit_sof (j_compress_ptr cinfo, JPEG_MARKER code)
  160816. /* Emit a SOF marker */
  160817. {
  160818. int ci;
  160819. jpeg_component_info *compptr;
  160820. emit_marker(cinfo, code);
  160821. emit_2bytes(cinfo, 3 * cinfo->num_components + 2 + 5 + 1); /* length */
  160822. /* Make sure image isn't bigger than SOF field can handle */
  160823. if ((long) cinfo->image_height > 65535L ||
  160824. (long) cinfo->image_width > 65535L)
  160825. ERREXIT1(cinfo, JERR_IMAGE_TOO_BIG, (unsigned int) 65535);
  160826. emit_byte(cinfo, cinfo->data_precision);
  160827. emit_2bytes(cinfo, (int) cinfo->image_height);
  160828. emit_2bytes(cinfo, (int) cinfo->image_width);
  160829. emit_byte(cinfo, cinfo->num_components);
  160830. for (ci = 0, compptr = cinfo->comp_info; ci < cinfo->num_components;
  160831. ci++, compptr++) {
  160832. emit_byte(cinfo, compptr->component_id);
  160833. emit_byte(cinfo, (compptr->h_samp_factor << 4) + compptr->v_samp_factor);
  160834. emit_byte(cinfo, compptr->quant_tbl_no);
  160835. }
  160836. }
  160837. LOCAL(void)
  160838. emit_sos (j_compress_ptr cinfo)
  160839. /* Emit a SOS marker */
  160840. {
  160841. int i, td, ta;
  160842. jpeg_component_info *compptr;
  160843. emit_marker(cinfo, M_SOS);
  160844. emit_2bytes(cinfo, 2 * cinfo->comps_in_scan + 2 + 1 + 3); /* length */
  160845. emit_byte(cinfo, cinfo->comps_in_scan);
  160846. for (i = 0; i < cinfo->comps_in_scan; i++) {
  160847. compptr = cinfo->cur_comp_info[i];
  160848. emit_byte(cinfo, compptr->component_id);
  160849. td = compptr->dc_tbl_no;
  160850. ta = compptr->ac_tbl_no;
  160851. if (cinfo->progressive_mode) {
  160852. /* Progressive mode: only DC or only AC tables are used in one scan;
  160853. * furthermore, Huffman coding of DC refinement uses no table at all.
  160854. * We emit 0 for unused field(s); this is recommended by the P&M text
  160855. * but does not seem to be specified in the standard.
  160856. */
  160857. if (cinfo->Ss == 0) {
  160858. ta = 0; /* DC scan */
  160859. if (cinfo->Ah != 0 && !cinfo->arith_code)
  160860. td = 0; /* no DC table either */
  160861. } else {
  160862. td = 0; /* AC scan */
  160863. }
  160864. }
  160865. emit_byte(cinfo, (td << 4) + ta);
  160866. }
  160867. emit_byte(cinfo, cinfo->Ss);
  160868. emit_byte(cinfo, cinfo->Se);
  160869. emit_byte(cinfo, (cinfo->Ah << 4) + cinfo->Al);
  160870. }
  160871. LOCAL(void)
  160872. emit_jfif_app0 (j_compress_ptr cinfo)
  160873. /* Emit a JFIF-compliant APP0 marker */
  160874. {
  160875. /*
  160876. * Length of APP0 block (2 bytes)
  160877. * Block ID (4 bytes - ASCII "JFIF")
  160878. * Zero byte (1 byte to terminate the ID string)
  160879. * Version Major, Minor (2 bytes - major first)
  160880. * Units (1 byte - 0x00 = none, 0x01 = inch, 0x02 = cm)
  160881. * Xdpu (2 bytes - dots per unit horizontal)
  160882. * Ydpu (2 bytes - dots per unit vertical)
  160883. * Thumbnail X size (1 byte)
  160884. * Thumbnail Y size (1 byte)
  160885. */
  160886. emit_marker(cinfo, M_APP0);
  160887. emit_2bytes(cinfo, 2 + 4 + 1 + 2 + 1 + 2 + 2 + 1 + 1); /* length */
  160888. emit_byte(cinfo, 0x4A); /* Identifier: ASCII "JFIF" */
  160889. emit_byte(cinfo, 0x46);
  160890. emit_byte(cinfo, 0x49);
  160891. emit_byte(cinfo, 0x46);
  160892. emit_byte(cinfo, 0);
  160893. emit_byte(cinfo, cinfo->JFIF_major_version); /* Version fields */
  160894. emit_byte(cinfo, cinfo->JFIF_minor_version);
  160895. emit_byte(cinfo, cinfo->density_unit); /* Pixel size information */
  160896. emit_2bytes(cinfo, (int) cinfo->X_density);
  160897. emit_2bytes(cinfo, (int) cinfo->Y_density);
  160898. emit_byte(cinfo, 0); /* No thumbnail image */
  160899. emit_byte(cinfo, 0);
  160900. }
  160901. LOCAL(void)
  160902. emit_adobe_app14 (j_compress_ptr cinfo)
  160903. /* Emit an Adobe APP14 marker */
  160904. {
  160905. /*
  160906. * Length of APP14 block (2 bytes)
  160907. * Block ID (5 bytes - ASCII "Adobe")
  160908. * Version Number (2 bytes - currently 100)
  160909. * Flags0 (2 bytes - currently 0)
  160910. * Flags1 (2 bytes - currently 0)
  160911. * Color transform (1 byte)
  160912. *
  160913. * Although Adobe TN 5116 mentions Version = 101, all the Adobe files
  160914. * now in circulation seem to use Version = 100, so that's what we write.
  160915. *
  160916. * We write the color transform byte as 1 if the JPEG color space is
  160917. * YCbCr, 2 if it's YCCK, 0 otherwise. Adobe's definition has to do with
  160918. * whether the encoder performed a transformation, which is pretty useless.
  160919. */
  160920. emit_marker(cinfo, M_APP14);
  160921. emit_2bytes(cinfo, 2 + 5 + 2 + 2 + 2 + 1); /* length */
  160922. emit_byte(cinfo, 0x41); /* Identifier: ASCII "Adobe" */
  160923. emit_byte(cinfo, 0x64);
  160924. emit_byte(cinfo, 0x6F);
  160925. emit_byte(cinfo, 0x62);
  160926. emit_byte(cinfo, 0x65);
  160927. emit_2bytes(cinfo, 100); /* Version */
  160928. emit_2bytes(cinfo, 0); /* Flags0 */
  160929. emit_2bytes(cinfo, 0); /* Flags1 */
  160930. switch (cinfo->jpeg_color_space) {
  160931. case JCS_YCbCr:
  160932. emit_byte(cinfo, 1); /* Color transform = 1 */
  160933. break;
  160934. case JCS_YCCK:
  160935. emit_byte(cinfo, 2); /* Color transform = 2 */
  160936. break;
  160937. default:
  160938. emit_byte(cinfo, 0); /* Color transform = 0 */
  160939. break;
  160940. }
  160941. }
  160942. /*
  160943. * These routines allow writing an arbitrary marker with parameters.
  160944. * The only intended use is to emit COM or APPn markers after calling
  160945. * write_file_header and before calling write_frame_header.
  160946. * Other uses are not guaranteed to produce desirable results.
  160947. * Counting the parameter bytes properly is the caller's responsibility.
  160948. */
  160949. METHODDEF(void)
  160950. write_marker_header (j_compress_ptr cinfo, int marker, unsigned int datalen)
  160951. /* Emit an arbitrary marker header */
  160952. {
  160953. if (datalen > (unsigned int) 65533) /* safety check */
  160954. ERREXIT(cinfo, JERR_BAD_LENGTH);
  160955. emit_marker(cinfo, (JPEG_MARKER) marker);
  160956. emit_2bytes(cinfo, (int) (datalen + 2)); /* total length */
  160957. }
  160958. METHODDEF(void)
  160959. write_marker_byte (j_compress_ptr cinfo, int val)
  160960. /* Emit one byte of marker parameters following write_marker_header */
  160961. {
  160962. emit_byte(cinfo, val);
  160963. }
  160964. /*
  160965. * Write datastream header.
  160966. * This consists of an SOI and optional APPn markers.
  160967. * We recommend use of the JFIF marker, but not the Adobe marker,
  160968. * when using YCbCr or grayscale data. The JFIF marker should NOT
  160969. * be used for any other JPEG colorspace. The Adobe marker is helpful
  160970. * to distinguish RGB, CMYK, and YCCK colorspaces.
  160971. * Note that an application can write additional header markers after
  160972. * jpeg_start_compress returns.
  160973. */
  160974. METHODDEF(void)
  160975. write_file_header (j_compress_ptr cinfo)
  160976. {
  160977. my_marker_ptr marker = (my_marker_ptr) cinfo->marker;
  160978. emit_marker(cinfo, M_SOI); /* first the SOI */
  160979. /* SOI is defined to reset restart interval to 0 */
  160980. marker->last_restart_interval = 0;
  160981. if (cinfo->write_JFIF_header) /* next an optional JFIF APP0 */
  160982. emit_jfif_app0(cinfo);
  160983. if (cinfo->write_Adobe_marker) /* next an optional Adobe APP14 */
  160984. emit_adobe_app14(cinfo);
  160985. }
  160986. /*
  160987. * Write frame header.
  160988. * This consists of DQT and SOFn markers.
  160989. * Note that we do not emit the SOF until we have emitted the DQT(s).
  160990. * This avoids compatibility problems with incorrect implementations that
  160991. * try to error-check the quant table numbers as soon as they see the SOF.
  160992. */
  160993. METHODDEF(void)
  160994. write_frame_header (j_compress_ptr cinfo)
  160995. {
  160996. int ci, prec;
  160997. boolean is_baseline;
  160998. jpeg_component_info *compptr;
  160999. /* Emit DQT for each quantization table.
  161000. * Note that emit_dqt() suppresses any duplicate tables.
  161001. */
  161002. prec = 0;
  161003. for (ci = 0, compptr = cinfo->comp_info; ci < cinfo->num_components;
  161004. ci++, compptr++) {
  161005. prec += emit_dqt(cinfo, compptr->quant_tbl_no);
  161006. }
  161007. /* now prec is nonzero iff there are any 16-bit quant tables. */
  161008. /* Check for a non-baseline specification.
  161009. * Note we assume that Huffman table numbers won't be changed later.
  161010. */
  161011. if (cinfo->arith_code || cinfo->progressive_mode ||
  161012. cinfo->data_precision != 8) {
  161013. is_baseline = FALSE;
  161014. } else {
  161015. is_baseline = TRUE;
  161016. for (ci = 0, compptr = cinfo->comp_info; ci < cinfo->num_components;
  161017. ci++, compptr++) {
  161018. if (compptr->dc_tbl_no > 1 || compptr->ac_tbl_no > 1)
  161019. is_baseline = FALSE;
  161020. }
  161021. if (prec && is_baseline) {
  161022. is_baseline = FALSE;
  161023. /* If it's baseline except for quantizer size, warn the user */
  161024. TRACEMS(cinfo, 0, JTRC_16BIT_TABLES);
  161025. }
  161026. }
  161027. /* Emit the proper SOF marker */
  161028. if (cinfo->arith_code) {
  161029. emit_sof(cinfo, M_SOF9); /* SOF code for arithmetic coding */
  161030. } else {
  161031. if (cinfo->progressive_mode)
  161032. emit_sof(cinfo, M_SOF2); /* SOF code for progressive Huffman */
  161033. else if (is_baseline)
  161034. emit_sof(cinfo, M_SOF0); /* SOF code for baseline implementation */
  161035. else
  161036. emit_sof(cinfo, M_SOF1); /* SOF code for non-baseline Huffman file */
  161037. }
  161038. }
  161039. /*
  161040. * Write scan header.
  161041. * This consists of DHT or DAC markers, optional DRI, and SOS.
  161042. * Compressed data will be written following the SOS.
  161043. */
  161044. METHODDEF(void)
  161045. write_scan_header (j_compress_ptr cinfo)
  161046. {
  161047. my_marker_ptr marker = (my_marker_ptr) cinfo->marker;
  161048. int i;
  161049. jpeg_component_info *compptr;
  161050. if (cinfo->arith_code) {
  161051. /* Emit arith conditioning info. We may have some duplication
  161052. * if the file has multiple scans, but it's so small it's hardly
  161053. * worth worrying about.
  161054. */
  161055. emit_dac(cinfo);
  161056. } else {
  161057. /* Emit Huffman tables.
  161058. * Note that emit_dht() suppresses any duplicate tables.
  161059. */
  161060. for (i = 0; i < cinfo->comps_in_scan; i++) {
  161061. compptr = cinfo->cur_comp_info[i];
  161062. if (cinfo->progressive_mode) {
  161063. /* Progressive mode: only DC or only AC tables are used in one scan */
  161064. if (cinfo->Ss == 0) {
  161065. if (cinfo->Ah == 0) /* DC needs no table for refinement scan */
  161066. emit_dht(cinfo, compptr->dc_tbl_no, FALSE);
  161067. } else {
  161068. emit_dht(cinfo, compptr->ac_tbl_no, TRUE);
  161069. }
  161070. } else {
  161071. /* Sequential mode: need both DC and AC tables */
  161072. emit_dht(cinfo, compptr->dc_tbl_no, FALSE);
  161073. emit_dht(cinfo, compptr->ac_tbl_no, TRUE);
  161074. }
  161075. }
  161076. }
  161077. /* Emit DRI if required --- note that DRI value could change for each scan.
  161078. * We avoid wasting space with unnecessary DRIs, however.
  161079. */
  161080. if (cinfo->restart_interval != marker->last_restart_interval) {
  161081. emit_dri(cinfo);
  161082. marker->last_restart_interval = cinfo->restart_interval;
  161083. }
  161084. emit_sos(cinfo);
  161085. }
  161086. /*
  161087. * Write datastream trailer.
  161088. */
  161089. METHODDEF(void)
  161090. write_file_trailer (j_compress_ptr cinfo)
  161091. {
  161092. emit_marker(cinfo, M_EOI);
  161093. }
  161094. /*
  161095. * Write an abbreviated table-specification datastream.
  161096. * This consists of SOI, DQT and DHT tables, and EOI.
  161097. * Any table that is defined and not marked sent_table = TRUE will be
  161098. * emitted. Note that all tables will be marked sent_table = TRUE at exit.
  161099. */
  161100. METHODDEF(void)
  161101. write_tables_only (j_compress_ptr cinfo)
  161102. {
  161103. int i;
  161104. emit_marker(cinfo, M_SOI);
  161105. for (i = 0; i < NUM_QUANT_TBLS; i++) {
  161106. if (cinfo->quant_tbl_ptrs[i] != NULL)
  161107. (void) emit_dqt(cinfo, i);
  161108. }
  161109. if (! cinfo->arith_code) {
  161110. for (i = 0; i < NUM_HUFF_TBLS; i++) {
  161111. if (cinfo->dc_huff_tbl_ptrs[i] != NULL)
  161112. emit_dht(cinfo, i, FALSE);
  161113. if (cinfo->ac_huff_tbl_ptrs[i] != NULL)
  161114. emit_dht(cinfo, i, TRUE);
  161115. }
  161116. }
  161117. emit_marker(cinfo, M_EOI);
  161118. }
  161119. /*
  161120. * Initialize the marker writer module.
  161121. */
  161122. GLOBAL(void)
  161123. jinit_marker_writer (j_compress_ptr cinfo)
  161124. {
  161125. my_marker_ptr marker;
  161126. /* Create the subobject */
  161127. marker = (my_marker_ptr)
  161128. (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_IMAGE,
  161129. SIZEOF(my_marker_writer));
  161130. cinfo->marker = (struct jpeg_marker_writer *) marker;
  161131. /* Initialize method pointers */
  161132. marker->pub.write_file_header = write_file_header;
  161133. marker->pub.write_frame_header = write_frame_header;
  161134. marker->pub.write_scan_header = write_scan_header;
  161135. marker->pub.write_file_trailer = write_file_trailer;
  161136. marker->pub.write_tables_only = write_tables_only;
  161137. marker->pub.write_marker_header = write_marker_header;
  161138. marker->pub.write_marker_byte = write_marker_byte;
  161139. /* Initialize private state */
  161140. marker->last_restart_interval = 0;
  161141. }
  161142. /*** End of inlined file: jcmarker.c ***/
  161143. /*** Start of inlined file: jcmaster.c ***/
  161144. #define JPEG_INTERNALS
  161145. /* Private state */
  161146. typedef enum {
  161147. main_pass, /* input data, also do first output step */
  161148. huff_opt_pass, /* Huffman code optimization pass */
  161149. output_pass /* data output pass */
  161150. } c_pass_type;
  161151. typedef struct {
  161152. struct jpeg_comp_master pub; /* public fields */
  161153. c_pass_type pass_type; /* the type of the current pass */
  161154. int pass_number; /* # of passes completed */
  161155. int total_passes; /* total # of passes needed */
  161156. int scan_number; /* current index in scan_info[] */
  161157. } my_comp_master;
  161158. typedef my_comp_master * my_master_ptr;
  161159. /*
  161160. * Support routines that do various essential calculations.
  161161. */
  161162. LOCAL(void)
  161163. initial_setup (j_compress_ptr cinfo)
  161164. /* Do computations that are needed before master selection phase */
  161165. {
  161166. int ci;
  161167. jpeg_component_info *compptr;
  161168. long samplesperrow;
  161169. JDIMENSION jd_samplesperrow;
  161170. /* Sanity check on image dimensions */
  161171. if (cinfo->image_height <= 0 || cinfo->image_width <= 0
  161172. || cinfo->num_components <= 0 || cinfo->input_components <= 0)
  161173. ERREXIT(cinfo, JERR_EMPTY_IMAGE);
  161174. /* Make sure image isn't bigger than I can handle */
  161175. if ((long) cinfo->image_height > (long) JPEG_MAX_DIMENSION ||
  161176. (long) cinfo->image_width > (long) JPEG_MAX_DIMENSION)
  161177. ERREXIT1(cinfo, JERR_IMAGE_TOO_BIG, (unsigned int) JPEG_MAX_DIMENSION);
  161178. /* Width of an input scanline must be representable as JDIMENSION. */
  161179. samplesperrow = (long) cinfo->image_width * (long) cinfo->input_components;
  161180. jd_samplesperrow = (JDIMENSION) samplesperrow;
  161181. if ((long) jd_samplesperrow != samplesperrow)
  161182. ERREXIT(cinfo, JERR_WIDTH_OVERFLOW);
  161183. /* For now, precision must match compiled-in value... */
  161184. if (cinfo->data_precision != BITS_IN_JSAMPLE)
  161185. ERREXIT1(cinfo, JERR_BAD_PRECISION, cinfo->data_precision);
  161186. /* Check that number of components won't exceed internal array sizes */
  161187. if (cinfo->num_components > MAX_COMPONENTS)
  161188. ERREXIT2(cinfo, JERR_COMPONENT_COUNT, cinfo->num_components,
  161189. MAX_COMPONENTS);
  161190. /* Compute maximum sampling factors; check factor validity */
  161191. cinfo->max_h_samp_factor = 1;
  161192. cinfo->max_v_samp_factor = 1;
  161193. for (ci = 0, compptr = cinfo->comp_info; ci < cinfo->num_components;
  161194. ci++, compptr++) {
  161195. if (compptr->h_samp_factor<=0 || compptr->h_samp_factor>MAX_SAMP_FACTOR ||
  161196. compptr->v_samp_factor<=0 || compptr->v_samp_factor>MAX_SAMP_FACTOR)
  161197. ERREXIT(cinfo, JERR_BAD_SAMPLING);
  161198. cinfo->max_h_samp_factor = MAX(cinfo->max_h_samp_factor,
  161199. compptr->h_samp_factor);
  161200. cinfo->max_v_samp_factor = MAX(cinfo->max_v_samp_factor,
  161201. compptr->v_samp_factor);
  161202. }
  161203. /* Compute dimensions of components */
  161204. for (ci = 0, compptr = cinfo->comp_info; ci < cinfo->num_components;
  161205. ci++, compptr++) {
  161206. /* Fill in the correct component_index value; don't rely on application */
  161207. compptr->component_index = ci;
  161208. /* For compression, we never do DCT scaling. */
  161209. compptr->DCT_scaled_size = DCTSIZE;
  161210. /* Size in DCT blocks */
  161211. compptr->width_in_blocks = (JDIMENSION)
  161212. jdiv_round_up((long) cinfo->image_width * (long) compptr->h_samp_factor,
  161213. (long) (cinfo->max_h_samp_factor * DCTSIZE));
  161214. compptr->height_in_blocks = (JDIMENSION)
  161215. jdiv_round_up((long) cinfo->image_height * (long) compptr->v_samp_factor,
  161216. (long) (cinfo->max_v_samp_factor * DCTSIZE));
  161217. /* Size in samples */
  161218. compptr->downsampled_width = (JDIMENSION)
  161219. jdiv_round_up((long) cinfo->image_width * (long) compptr->h_samp_factor,
  161220. (long) cinfo->max_h_samp_factor);
  161221. compptr->downsampled_height = (JDIMENSION)
  161222. jdiv_round_up((long) cinfo->image_height * (long) compptr->v_samp_factor,
  161223. (long) cinfo->max_v_samp_factor);
  161224. /* Mark component needed (this flag isn't actually used for compression) */
  161225. compptr->component_needed = TRUE;
  161226. }
  161227. /* Compute number of fully interleaved MCU rows (number of times that
  161228. * main controller will call coefficient controller).
  161229. */
  161230. cinfo->total_iMCU_rows = (JDIMENSION)
  161231. jdiv_round_up((long) cinfo->image_height,
  161232. (long) (cinfo->max_v_samp_factor*DCTSIZE));
  161233. }
  161234. #ifdef C_MULTISCAN_FILES_SUPPORTED
  161235. LOCAL(void)
  161236. validate_script (j_compress_ptr cinfo)
  161237. /* Verify that the scan script in cinfo->scan_info[] is valid; also
  161238. * determine whether it uses progressive JPEG, and set cinfo->progressive_mode.
  161239. */
  161240. {
  161241. const jpeg_scan_info * scanptr;
  161242. int scanno, ncomps, ci, coefi, thisi;
  161243. int Ss, Se, Ah, Al;
  161244. boolean component_sent[MAX_COMPONENTS];
  161245. #ifdef C_PROGRESSIVE_SUPPORTED
  161246. int * last_bitpos_ptr;
  161247. int last_bitpos[MAX_COMPONENTS][DCTSIZE2];
  161248. /* -1 until that coefficient has been seen; then last Al for it */
  161249. #endif
  161250. if (cinfo->num_scans <= 0)
  161251. ERREXIT1(cinfo, JERR_BAD_SCAN_SCRIPT, 0);
  161252. /* For sequential JPEG, all scans must have Ss=0, Se=DCTSIZE2-1;
  161253. * for progressive JPEG, no scan can have this.
  161254. */
  161255. scanptr = cinfo->scan_info;
  161256. if (scanptr->Ss != 0 || scanptr->Se != DCTSIZE2-1) {
  161257. #ifdef C_PROGRESSIVE_SUPPORTED
  161258. cinfo->progressive_mode = TRUE;
  161259. last_bitpos_ptr = & last_bitpos[0][0];
  161260. for (ci = 0; ci < cinfo->num_components; ci++)
  161261. for (coefi = 0; coefi < DCTSIZE2; coefi++)
  161262. *last_bitpos_ptr++ = -1;
  161263. #else
  161264. ERREXIT(cinfo, JERR_NOT_COMPILED);
  161265. #endif
  161266. } else {
  161267. cinfo->progressive_mode = FALSE;
  161268. for (ci = 0; ci < cinfo->num_components; ci++)
  161269. component_sent[ci] = FALSE;
  161270. }
  161271. for (scanno = 1; scanno <= cinfo->num_scans; scanptr++, scanno++) {
  161272. /* Validate component indexes */
  161273. ncomps = scanptr->comps_in_scan;
  161274. if (ncomps <= 0 || ncomps > MAX_COMPS_IN_SCAN)
  161275. ERREXIT2(cinfo, JERR_COMPONENT_COUNT, ncomps, MAX_COMPS_IN_SCAN);
  161276. for (ci = 0; ci < ncomps; ci++) {
  161277. thisi = scanptr->component_index[ci];
  161278. if (thisi < 0 || thisi >= cinfo->num_components)
  161279. ERREXIT1(cinfo, JERR_BAD_SCAN_SCRIPT, scanno);
  161280. /* Components must appear in SOF order within each scan */
  161281. if (ci > 0 && thisi <= scanptr->component_index[ci-1])
  161282. ERREXIT1(cinfo, JERR_BAD_SCAN_SCRIPT, scanno);
  161283. }
  161284. /* Validate progression parameters */
  161285. Ss = scanptr->Ss;
  161286. Se = scanptr->Se;
  161287. Ah = scanptr->Ah;
  161288. Al = scanptr->Al;
  161289. if (cinfo->progressive_mode) {
  161290. #ifdef C_PROGRESSIVE_SUPPORTED
  161291. /* The JPEG spec simply gives the ranges 0..13 for Ah and Al, but that
  161292. * seems wrong: the upper bound ought to depend on data precision.
  161293. * Perhaps they really meant 0..N+1 for N-bit precision.
  161294. * Here we allow 0..10 for 8-bit data; Al larger than 10 results in
  161295. * out-of-range reconstructed DC values during the first DC scan,
  161296. * which might cause problems for some decoders.
  161297. */
  161298. #if BITS_IN_JSAMPLE == 8
  161299. #define MAX_AH_AL 10
  161300. #else
  161301. #define MAX_AH_AL 13
  161302. #endif
  161303. if (Ss < 0 || Ss >= DCTSIZE2 || Se < Ss || Se >= DCTSIZE2 ||
  161304. Ah < 0 || Ah > MAX_AH_AL || Al < 0 || Al > MAX_AH_AL)
  161305. ERREXIT1(cinfo, JERR_BAD_PROG_SCRIPT, scanno);
  161306. if (Ss == 0) {
  161307. if (Se != 0) /* DC and AC together not OK */
  161308. ERREXIT1(cinfo, JERR_BAD_PROG_SCRIPT, scanno);
  161309. } else {
  161310. if (ncomps != 1) /* AC scans must be for only one component */
  161311. ERREXIT1(cinfo, JERR_BAD_PROG_SCRIPT, scanno);
  161312. }
  161313. for (ci = 0; ci < ncomps; ci++) {
  161314. last_bitpos_ptr = & last_bitpos[scanptr->component_index[ci]][0];
  161315. if (Ss != 0 && last_bitpos_ptr[0] < 0) /* AC without prior DC scan */
  161316. ERREXIT1(cinfo, JERR_BAD_PROG_SCRIPT, scanno);
  161317. for (coefi = Ss; coefi <= Se; coefi++) {
  161318. if (last_bitpos_ptr[coefi] < 0) {
  161319. /* first scan of this coefficient */
  161320. if (Ah != 0)
  161321. ERREXIT1(cinfo, JERR_BAD_PROG_SCRIPT, scanno);
  161322. } else {
  161323. /* not first scan */
  161324. if (Ah != last_bitpos_ptr[coefi] || Al != Ah-1)
  161325. ERREXIT1(cinfo, JERR_BAD_PROG_SCRIPT, scanno);
  161326. }
  161327. last_bitpos_ptr[coefi] = Al;
  161328. }
  161329. }
  161330. #endif
  161331. } else {
  161332. /* For sequential JPEG, all progression parameters must be these: */
  161333. if (Ss != 0 || Se != DCTSIZE2-1 || Ah != 0 || Al != 0)
  161334. ERREXIT1(cinfo, JERR_BAD_PROG_SCRIPT, scanno);
  161335. /* Make sure components are not sent twice */
  161336. for (ci = 0; ci < ncomps; ci++) {
  161337. thisi = scanptr->component_index[ci];
  161338. if (component_sent[thisi])
  161339. ERREXIT1(cinfo, JERR_BAD_SCAN_SCRIPT, scanno);
  161340. component_sent[thisi] = TRUE;
  161341. }
  161342. }
  161343. }
  161344. /* Now verify that everything got sent. */
  161345. if (cinfo->progressive_mode) {
  161346. #ifdef C_PROGRESSIVE_SUPPORTED
  161347. /* For progressive mode, we only check that at least some DC data
  161348. * got sent for each component; the spec does not require that all bits
  161349. * of all coefficients be transmitted. Would it be wiser to enforce
  161350. * transmission of all coefficient bits??
  161351. */
  161352. for (ci = 0; ci < cinfo->num_components; ci++) {
  161353. if (last_bitpos[ci][0] < 0)
  161354. ERREXIT(cinfo, JERR_MISSING_DATA);
  161355. }
  161356. #endif
  161357. } else {
  161358. for (ci = 0; ci < cinfo->num_components; ci++) {
  161359. if (! component_sent[ci])
  161360. ERREXIT(cinfo, JERR_MISSING_DATA);
  161361. }
  161362. }
  161363. }
  161364. #endif /* C_MULTISCAN_FILES_SUPPORTED */
  161365. LOCAL(void)
  161366. select_scan_parameters (j_compress_ptr cinfo)
  161367. /* Set up the scan parameters for the current scan */
  161368. {
  161369. int ci;
  161370. #ifdef C_MULTISCAN_FILES_SUPPORTED
  161371. if (cinfo->scan_info != NULL) {
  161372. /* Prepare for current scan --- the script is already validated */
  161373. my_master_ptr master = (my_master_ptr) cinfo->master;
  161374. const jpeg_scan_info * scanptr = cinfo->scan_info + master->scan_number;
  161375. cinfo->comps_in_scan = scanptr->comps_in_scan;
  161376. for (ci = 0; ci < scanptr->comps_in_scan; ci++) {
  161377. cinfo->cur_comp_info[ci] =
  161378. &cinfo->comp_info[scanptr->component_index[ci]];
  161379. }
  161380. cinfo->Ss = scanptr->Ss;
  161381. cinfo->Se = scanptr->Se;
  161382. cinfo->Ah = scanptr->Ah;
  161383. cinfo->Al = scanptr->Al;
  161384. }
  161385. else
  161386. #endif
  161387. {
  161388. /* Prepare for single sequential-JPEG scan containing all components */
  161389. if (cinfo->num_components > MAX_COMPS_IN_SCAN)
  161390. ERREXIT2(cinfo, JERR_COMPONENT_COUNT, cinfo->num_components,
  161391. MAX_COMPS_IN_SCAN);
  161392. cinfo->comps_in_scan = cinfo->num_components;
  161393. for (ci = 0; ci < cinfo->num_components; ci++) {
  161394. cinfo->cur_comp_info[ci] = &cinfo->comp_info[ci];
  161395. }
  161396. cinfo->Ss = 0;
  161397. cinfo->Se = DCTSIZE2-1;
  161398. cinfo->Ah = 0;
  161399. cinfo->Al = 0;
  161400. }
  161401. }
  161402. LOCAL(void)
  161403. per_scan_setup (j_compress_ptr cinfo)
  161404. /* Do computations that are needed before processing a JPEG scan */
  161405. /* cinfo->comps_in_scan and cinfo->cur_comp_info[] are already set */
  161406. {
  161407. int ci, mcublks, tmp;
  161408. jpeg_component_info *compptr;
  161409. if (cinfo->comps_in_scan == 1) {
  161410. /* Noninterleaved (single-component) scan */
  161411. compptr = cinfo->cur_comp_info[0];
  161412. /* Overall image size in MCUs */
  161413. cinfo->MCUs_per_row = compptr->width_in_blocks;
  161414. cinfo->MCU_rows_in_scan = compptr->height_in_blocks;
  161415. /* For noninterleaved scan, always one block per MCU */
  161416. compptr->MCU_width = 1;
  161417. compptr->MCU_height = 1;
  161418. compptr->MCU_blocks = 1;
  161419. compptr->MCU_sample_width = DCTSIZE;
  161420. compptr->last_col_width = 1;
  161421. /* For noninterleaved scans, it is convenient to define last_row_height
  161422. * as the number of block rows present in the last iMCU row.
  161423. */
  161424. tmp = (int) (compptr->height_in_blocks % compptr->v_samp_factor);
  161425. if (tmp == 0) tmp = compptr->v_samp_factor;
  161426. compptr->last_row_height = tmp;
  161427. /* Prepare array describing MCU composition */
  161428. cinfo->blocks_in_MCU = 1;
  161429. cinfo->MCU_membership[0] = 0;
  161430. } else {
  161431. /* Interleaved (multi-component) scan */
  161432. if (cinfo->comps_in_scan <= 0 || cinfo->comps_in_scan > MAX_COMPS_IN_SCAN)
  161433. ERREXIT2(cinfo, JERR_COMPONENT_COUNT, cinfo->comps_in_scan,
  161434. MAX_COMPS_IN_SCAN);
  161435. /* Overall image size in MCUs */
  161436. cinfo->MCUs_per_row = (JDIMENSION)
  161437. jdiv_round_up((long) cinfo->image_width,
  161438. (long) (cinfo->max_h_samp_factor*DCTSIZE));
  161439. cinfo->MCU_rows_in_scan = (JDIMENSION)
  161440. jdiv_round_up((long) cinfo->image_height,
  161441. (long) (cinfo->max_v_samp_factor*DCTSIZE));
  161442. cinfo->blocks_in_MCU = 0;
  161443. for (ci = 0; ci < cinfo->comps_in_scan; ci++) {
  161444. compptr = cinfo->cur_comp_info[ci];
  161445. /* Sampling factors give # of blocks of component in each MCU */
  161446. compptr->MCU_width = compptr->h_samp_factor;
  161447. compptr->MCU_height = compptr->v_samp_factor;
  161448. compptr->MCU_blocks = compptr->MCU_width * compptr->MCU_height;
  161449. compptr->MCU_sample_width = compptr->MCU_width * DCTSIZE;
  161450. /* Figure number of non-dummy blocks in last MCU column & row */
  161451. tmp = (int) (compptr->width_in_blocks % compptr->MCU_width);
  161452. if (tmp == 0) tmp = compptr->MCU_width;
  161453. compptr->last_col_width = tmp;
  161454. tmp = (int) (compptr->height_in_blocks % compptr->MCU_height);
  161455. if (tmp == 0) tmp = compptr->MCU_height;
  161456. compptr->last_row_height = tmp;
  161457. /* Prepare array describing MCU composition */
  161458. mcublks = compptr->MCU_blocks;
  161459. if (cinfo->blocks_in_MCU + mcublks > C_MAX_BLOCKS_IN_MCU)
  161460. ERREXIT(cinfo, JERR_BAD_MCU_SIZE);
  161461. while (mcublks-- > 0) {
  161462. cinfo->MCU_membership[cinfo->blocks_in_MCU++] = ci;
  161463. }
  161464. }
  161465. }
  161466. /* Convert restart specified in rows to actual MCU count. */
  161467. /* Note that count must fit in 16 bits, so we provide limiting. */
  161468. if (cinfo->restart_in_rows > 0) {
  161469. long nominal = (long) cinfo->restart_in_rows * (long) cinfo->MCUs_per_row;
  161470. cinfo->restart_interval = (unsigned int) MIN(nominal, 65535L);
  161471. }
  161472. }
  161473. /*
  161474. * Per-pass setup.
  161475. * This is called at the beginning of each pass. We determine which modules
  161476. * will be active during this pass and give them appropriate start_pass calls.
  161477. * We also set is_last_pass to indicate whether any more passes will be
  161478. * required.
  161479. */
  161480. METHODDEF(void)
  161481. prepare_for_pass (j_compress_ptr cinfo)
  161482. {
  161483. my_master_ptr master = (my_master_ptr) cinfo->master;
  161484. switch (master->pass_type) {
  161485. case main_pass:
  161486. /* Initial pass: will collect input data, and do either Huffman
  161487. * optimization or data output for the first scan.
  161488. */
  161489. select_scan_parameters(cinfo);
  161490. per_scan_setup(cinfo);
  161491. if (! cinfo->raw_data_in) {
  161492. (*cinfo->cconvert->start_pass) (cinfo);
  161493. (*cinfo->downsample->start_pass) (cinfo);
  161494. (*cinfo->prep->start_pass) (cinfo, JBUF_PASS_THRU);
  161495. }
  161496. (*cinfo->fdct->start_pass) (cinfo);
  161497. (*cinfo->entropy->start_pass) (cinfo, cinfo->optimize_coding);
  161498. (*cinfo->coef->start_pass) (cinfo,
  161499. (master->total_passes > 1 ?
  161500. JBUF_SAVE_AND_PASS : JBUF_PASS_THRU));
  161501. (*cinfo->main->start_pass) (cinfo, JBUF_PASS_THRU);
  161502. if (cinfo->optimize_coding) {
  161503. /* No immediate data output; postpone writing frame/scan headers */
  161504. master->pub.call_pass_startup = FALSE;
  161505. } else {
  161506. /* Will write frame/scan headers at first jpeg_write_scanlines call */
  161507. master->pub.call_pass_startup = TRUE;
  161508. }
  161509. break;
  161510. #ifdef ENTROPY_OPT_SUPPORTED
  161511. case huff_opt_pass:
  161512. /* Do Huffman optimization for a scan after the first one. */
  161513. select_scan_parameters(cinfo);
  161514. per_scan_setup(cinfo);
  161515. if (cinfo->Ss != 0 || cinfo->Ah == 0 || cinfo->arith_code) {
  161516. (*cinfo->entropy->start_pass) (cinfo, TRUE);
  161517. (*cinfo->coef->start_pass) (cinfo, JBUF_CRANK_DEST);
  161518. master->pub.call_pass_startup = FALSE;
  161519. break;
  161520. }
  161521. /* Special case: Huffman DC refinement scans need no Huffman table
  161522. * and therefore we can skip the optimization pass for them.
  161523. */
  161524. master->pass_type = output_pass;
  161525. master->pass_number++;
  161526. /*FALLTHROUGH*/
  161527. #endif
  161528. case output_pass:
  161529. /* Do a data-output pass. */
  161530. /* We need not repeat per-scan setup if prior optimization pass did it. */
  161531. if (! cinfo->optimize_coding) {
  161532. select_scan_parameters(cinfo);
  161533. per_scan_setup(cinfo);
  161534. }
  161535. (*cinfo->entropy->start_pass) (cinfo, FALSE);
  161536. (*cinfo->coef->start_pass) (cinfo, JBUF_CRANK_DEST);
  161537. /* We emit frame/scan headers now */
  161538. if (master->scan_number == 0)
  161539. (*cinfo->marker->write_frame_header) (cinfo);
  161540. (*cinfo->marker->write_scan_header) (cinfo);
  161541. master->pub.call_pass_startup = FALSE;
  161542. break;
  161543. default:
  161544. ERREXIT(cinfo, JERR_NOT_COMPILED);
  161545. }
  161546. master->pub.is_last_pass = (master->pass_number == master->total_passes-1);
  161547. /* Set up progress monitor's pass info if present */
  161548. if (cinfo->progress != NULL) {
  161549. cinfo->progress->completed_passes = master->pass_number;
  161550. cinfo->progress->total_passes = master->total_passes;
  161551. }
  161552. }
  161553. /*
  161554. * Special start-of-pass hook.
  161555. * This is called by jpeg_write_scanlines if call_pass_startup is TRUE.
  161556. * In single-pass processing, we need this hook because we don't want to
  161557. * write frame/scan headers during jpeg_start_compress; we want to let the
  161558. * application write COM markers etc. between jpeg_start_compress and the
  161559. * jpeg_write_scanlines loop.
  161560. * In multi-pass processing, this routine is not used.
  161561. */
  161562. METHODDEF(void)
  161563. pass_startup (j_compress_ptr cinfo)
  161564. {
  161565. cinfo->master->call_pass_startup = FALSE; /* reset flag so call only once */
  161566. (*cinfo->marker->write_frame_header) (cinfo);
  161567. (*cinfo->marker->write_scan_header) (cinfo);
  161568. }
  161569. /*
  161570. * Finish up at end of pass.
  161571. */
  161572. METHODDEF(void)
  161573. finish_pass_master (j_compress_ptr cinfo)
  161574. {
  161575. my_master_ptr master = (my_master_ptr) cinfo->master;
  161576. /* The entropy coder always needs an end-of-pass call,
  161577. * either to analyze statistics or to flush its output buffer.
  161578. */
  161579. (*cinfo->entropy->finish_pass) (cinfo);
  161580. /* Update state for next pass */
  161581. switch (master->pass_type) {
  161582. case main_pass:
  161583. /* next pass is either output of scan 0 (after optimization)
  161584. * or output of scan 1 (if no optimization).
  161585. */
  161586. master->pass_type = output_pass;
  161587. if (! cinfo->optimize_coding)
  161588. master->scan_number++;
  161589. break;
  161590. case huff_opt_pass:
  161591. /* next pass is always output of current scan */
  161592. master->pass_type = output_pass;
  161593. break;
  161594. case output_pass:
  161595. /* next pass is either optimization or output of next scan */
  161596. if (cinfo->optimize_coding)
  161597. master->pass_type = huff_opt_pass;
  161598. master->scan_number++;
  161599. break;
  161600. }
  161601. master->pass_number++;
  161602. }
  161603. /*
  161604. * Initialize master compression control.
  161605. */
  161606. GLOBAL(void)
  161607. jinit_c_master_control (j_compress_ptr cinfo, boolean transcode_only)
  161608. {
  161609. my_master_ptr master;
  161610. master = (my_master_ptr)
  161611. (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_IMAGE,
  161612. SIZEOF(my_comp_master));
  161613. cinfo->master = (struct jpeg_comp_master *) master;
  161614. master->pub.prepare_for_pass = prepare_for_pass;
  161615. master->pub.pass_startup = pass_startup;
  161616. master->pub.finish_pass = finish_pass_master;
  161617. master->pub.is_last_pass = FALSE;
  161618. /* Validate parameters, determine derived values */
  161619. initial_setup(cinfo);
  161620. if (cinfo->scan_info != NULL) {
  161621. #ifdef C_MULTISCAN_FILES_SUPPORTED
  161622. validate_script(cinfo);
  161623. #else
  161624. ERREXIT(cinfo, JERR_NOT_COMPILED);
  161625. #endif
  161626. } else {
  161627. cinfo->progressive_mode = FALSE;
  161628. cinfo->num_scans = 1;
  161629. }
  161630. if (cinfo->progressive_mode) /* TEMPORARY HACK ??? */
  161631. cinfo->optimize_coding = TRUE; /* assume default tables no good for progressive mode */
  161632. /* Initialize my private state */
  161633. if (transcode_only) {
  161634. /* no main pass in transcoding */
  161635. if (cinfo->optimize_coding)
  161636. master->pass_type = huff_opt_pass;
  161637. else
  161638. master->pass_type = output_pass;
  161639. } else {
  161640. /* for normal compression, first pass is always this type: */
  161641. master->pass_type = main_pass;
  161642. }
  161643. master->scan_number = 0;
  161644. master->pass_number = 0;
  161645. if (cinfo->optimize_coding)
  161646. master->total_passes = cinfo->num_scans * 2;
  161647. else
  161648. master->total_passes = cinfo->num_scans;
  161649. }
  161650. /*** End of inlined file: jcmaster.c ***/
  161651. /*** Start of inlined file: jcomapi.c ***/
  161652. #define JPEG_INTERNALS
  161653. /*
  161654. * Abort processing of a JPEG compression or decompression operation,
  161655. * but don't destroy the object itself.
  161656. *
  161657. * For this, we merely clean up all the nonpermanent memory pools.
  161658. * Note that temp files (virtual arrays) are not allowed to belong to
  161659. * the permanent pool, so we will be able to close all temp files here.
  161660. * Closing a data source or destination, if necessary, is the application's
  161661. * responsibility.
  161662. */
  161663. GLOBAL(void)
  161664. jpeg_abort (j_common_ptr cinfo)
  161665. {
  161666. int pool;
  161667. /* Do nothing if called on a not-initialized or destroyed JPEG object. */
  161668. if (cinfo->mem == NULL)
  161669. return;
  161670. /* Releasing pools in reverse order might help avoid fragmentation
  161671. * with some (brain-damaged) malloc libraries.
  161672. */
  161673. for (pool = JPOOL_NUMPOOLS-1; pool > JPOOL_PERMANENT; pool--) {
  161674. (*cinfo->mem->free_pool) (cinfo, pool);
  161675. }
  161676. /* Reset overall state for possible reuse of object */
  161677. if (cinfo->is_decompressor) {
  161678. cinfo->global_state = DSTATE_START;
  161679. /* Try to keep application from accessing now-deleted marker list.
  161680. * A bit kludgy to do it here, but this is the most central place.
  161681. */
  161682. ((j_decompress_ptr) cinfo)->marker_list = NULL;
  161683. } else {
  161684. cinfo->global_state = CSTATE_START;
  161685. }
  161686. }
  161687. /*
  161688. * Destruction of a JPEG object.
  161689. *
  161690. * Everything gets deallocated except the master jpeg_compress_struct itself
  161691. * and the error manager struct. Both of these are supplied by the application
  161692. * and must be freed, if necessary, by the application. (Often they are on
  161693. * the stack and so don't need to be freed anyway.)
  161694. * Closing a data source or destination, if necessary, is the application's
  161695. * responsibility.
  161696. */
  161697. GLOBAL(void)
  161698. jpeg_destroy (j_common_ptr cinfo)
  161699. {
  161700. /* We need only tell the memory manager to release everything. */
  161701. /* NB: mem pointer is NULL if memory mgr failed to initialize. */
  161702. if (cinfo->mem != NULL)
  161703. (*cinfo->mem->self_destruct) (cinfo);
  161704. cinfo->mem = NULL; /* be safe if jpeg_destroy is called twice */
  161705. cinfo->global_state = 0; /* mark it destroyed */
  161706. }
  161707. /*
  161708. * Convenience routines for allocating quantization and Huffman tables.
  161709. * (Would jutils.c be a more reasonable place to put these?)
  161710. */
  161711. GLOBAL(JQUANT_TBL *)
  161712. jpeg_alloc_quant_table (j_common_ptr cinfo)
  161713. {
  161714. JQUANT_TBL *tbl;
  161715. tbl = (JQUANT_TBL *)
  161716. (*cinfo->mem->alloc_small) (cinfo, JPOOL_PERMANENT, SIZEOF(JQUANT_TBL));
  161717. tbl->sent_table = FALSE; /* make sure this is false in any new table */
  161718. return tbl;
  161719. }
  161720. GLOBAL(JHUFF_TBL *)
  161721. jpeg_alloc_huff_table (j_common_ptr cinfo)
  161722. {
  161723. JHUFF_TBL *tbl;
  161724. tbl = (JHUFF_TBL *)
  161725. (*cinfo->mem->alloc_small) (cinfo, JPOOL_PERMANENT, SIZEOF(JHUFF_TBL));
  161726. tbl->sent_table = FALSE; /* make sure this is false in any new table */
  161727. return tbl;
  161728. }
  161729. /*** End of inlined file: jcomapi.c ***/
  161730. /*** Start of inlined file: jcparam.c ***/
  161731. #define JPEG_INTERNALS
  161732. /*
  161733. * Quantization table setup routines
  161734. */
  161735. GLOBAL(void)
  161736. jpeg_add_quant_table (j_compress_ptr cinfo, int which_tbl,
  161737. const unsigned int *basic_table,
  161738. int scale_factor, boolean force_baseline)
  161739. /* Define a quantization table equal to the basic_table times
  161740. * a scale factor (given as a percentage).
  161741. * If force_baseline is TRUE, the computed quantization table entries
  161742. * are limited to 1..255 for JPEG baseline compatibility.
  161743. */
  161744. {
  161745. JQUANT_TBL ** qtblptr;
  161746. int i;
  161747. long temp;
  161748. /* Safety check to ensure start_compress not called yet. */
  161749. if (cinfo->global_state != CSTATE_START)
  161750. ERREXIT1(cinfo, JERR_BAD_STATE, cinfo->global_state);
  161751. if (which_tbl < 0 || which_tbl >= NUM_QUANT_TBLS)
  161752. ERREXIT1(cinfo, JERR_DQT_INDEX, which_tbl);
  161753. qtblptr = & cinfo->quant_tbl_ptrs[which_tbl];
  161754. if (*qtblptr == NULL)
  161755. *qtblptr = jpeg_alloc_quant_table((j_common_ptr) cinfo);
  161756. for (i = 0; i < DCTSIZE2; i++) {
  161757. temp = ((long) basic_table[i] * scale_factor + 50L) / 100L;
  161758. /* limit the values to the valid range */
  161759. if (temp <= 0L) temp = 1L;
  161760. if (temp > 32767L) temp = 32767L; /* max quantizer needed for 12 bits */
  161761. if (force_baseline && temp > 255L)
  161762. temp = 255L; /* limit to baseline range if requested */
  161763. (*qtblptr)->quantval[i] = (UINT16) temp;
  161764. }
  161765. /* Initialize sent_table FALSE so table will be written to JPEG file. */
  161766. (*qtblptr)->sent_table = FALSE;
  161767. }
  161768. GLOBAL(void)
  161769. jpeg_set_linear_quality (j_compress_ptr cinfo, int scale_factor,
  161770. boolean force_baseline)
  161771. /* Set or change the 'quality' (quantization) setting, using default tables
  161772. * and a straight percentage-scaling quality scale. In most cases it's better
  161773. * to use jpeg_set_quality (below); this entry point is provided for
  161774. * applications that insist on a linear percentage scaling.
  161775. */
  161776. {
  161777. /* These are the sample quantization tables given in JPEG spec section K.1.
  161778. * The spec says that the values given produce "good" quality, and
  161779. * when divided by 2, "very good" quality.
  161780. */
  161781. static const unsigned int std_luminance_quant_tbl[DCTSIZE2] = {
  161782. 16, 11, 10, 16, 24, 40, 51, 61,
  161783. 12, 12, 14, 19, 26, 58, 60, 55,
  161784. 14, 13, 16, 24, 40, 57, 69, 56,
  161785. 14, 17, 22, 29, 51, 87, 80, 62,
  161786. 18, 22, 37, 56, 68, 109, 103, 77,
  161787. 24, 35, 55, 64, 81, 104, 113, 92,
  161788. 49, 64, 78, 87, 103, 121, 120, 101,
  161789. 72, 92, 95, 98, 112, 100, 103, 99
  161790. };
  161791. static const unsigned int std_chrominance_quant_tbl[DCTSIZE2] = {
  161792. 17, 18, 24, 47, 99, 99, 99, 99,
  161793. 18, 21, 26, 66, 99, 99, 99, 99,
  161794. 24, 26, 56, 99, 99, 99, 99, 99,
  161795. 47, 66, 99, 99, 99, 99, 99, 99,
  161796. 99, 99, 99, 99, 99, 99, 99, 99,
  161797. 99, 99, 99, 99, 99, 99, 99, 99,
  161798. 99, 99, 99, 99, 99, 99, 99, 99,
  161799. 99, 99, 99, 99, 99, 99, 99, 99
  161800. };
  161801. /* Set up two quantization tables using the specified scaling */
  161802. jpeg_add_quant_table(cinfo, 0, std_luminance_quant_tbl,
  161803. scale_factor, force_baseline);
  161804. jpeg_add_quant_table(cinfo, 1, std_chrominance_quant_tbl,
  161805. scale_factor, force_baseline);
  161806. }
  161807. GLOBAL(int)
  161808. jpeg_quality_scaling (int quality)
  161809. /* Convert a user-specified quality rating to a percentage scaling factor
  161810. * for an underlying quantization table, using our recommended scaling curve.
  161811. * The input 'quality' factor should be 0 (terrible) to 100 (very good).
  161812. */
  161813. {
  161814. /* Safety limit on quality factor. Convert 0 to 1 to avoid zero divide. */
  161815. if (quality <= 0) quality = 1;
  161816. if (quality > 100) quality = 100;
  161817. /* The basic table is used as-is (scaling 100) for a quality of 50.
  161818. * Qualities 50..100 are converted to scaling percentage 200 - 2*Q;
  161819. * note that at Q=100 the scaling is 0, which will cause jpeg_add_quant_table
  161820. * to make all the table entries 1 (hence, minimum quantization loss).
  161821. * Qualities 1..50 are converted to scaling percentage 5000/Q.
  161822. */
  161823. if (quality < 50)
  161824. quality = 5000 / quality;
  161825. else
  161826. quality = 200 - quality*2;
  161827. return quality;
  161828. }
  161829. GLOBAL(void)
  161830. jpeg_set_quality (j_compress_ptr cinfo, int quality, boolean force_baseline)
  161831. /* Set or change the 'quality' (quantization) setting, using default tables.
  161832. * This is the standard quality-adjusting entry point for typical user
  161833. * interfaces; only those who want detailed control over quantization tables
  161834. * would use the preceding three routines directly.
  161835. */
  161836. {
  161837. /* Convert user 0-100 rating to percentage scaling */
  161838. quality = jpeg_quality_scaling(quality);
  161839. /* Set up standard quality tables */
  161840. jpeg_set_linear_quality(cinfo, quality, force_baseline);
  161841. }
  161842. /*
  161843. * Huffman table setup routines
  161844. */
  161845. LOCAL(void)
  161846. add_huff_table (j_compress_ptr cinfo,
  161847. JHUFF_TBL **htblptr, const UINT8 *bits, const UINT8 *val)
  161848. /* Define a Huffman table */
  161849. {
  161850. int nsymbols, len;
  161851. if (*htblptr == NULL)
  161852. *htblptr = jpeg_alloc_huff_table((j_common_ptr) cinfo);
  161853. /* Copy the number-of-symbols-of-each-code-length counts */
  161854. MEMCOPY((*htblptr)->bits, bits, SIZEOF((*htblptr)->bits));
  161855. /* Validate the counts. We do this here mainly so we can copy the right
  161856. * number of symbols from the val[] array, without risking marching off
  161857. * the end of memory. jchuff.c will do a more thorough test later.
  161858. */
  161859. nsymbols = 0;
  161860. for (len = 1; len <= 16; len++)
  161861. nsymbols += bits[len];
  161862. if (nsymbols < 1 || nsymbols > 256)
  161863. ERREXIT(cinfo, JERR_BAD_HUFF_TABLE);
  161864. MEMCOPY((*htblptr)->huffval, val, nsymbols * SIZEOF(UINT8));
  161865. /* Initialize sent_table FALSE so table will be written to JPEG file. */
  161866. (*htblptr)->sent_table = FALSE;
  161867. }
  161868. LOCAL(void)
  161869. std_huff_tables (j_compress_ptr cinfo)
  161870. /* Set up the standard Huffman tables (cf. JPEG standard section K.3) */
  161871. /* IMPORTANT: these are only valid for 8-bit data precision! */
  161872. {
  161873. static const UINT8 bits_dc_luminance[17] =
  161874. { /* 0-base */ 0, 0, 1, 5, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0 };
  161875. static const UINT8 val_dc_luminance[] =
  161876. { 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11 };
  161877. static const UINT8 bits_dc_chrominance[17] =
  161878. { /* 0-base */ 0, 0, 3, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0 };
  161879. static const UINT8 val_dc_chrominance[] =
  161880. { 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11 };
  161881. static const UINT8 bits_ac_luminance[17] =
  161882. { /* 0-base */ 0, 0, 2, 1, 3, 3, 2, 4, 3, 5, 5, 4, 4, 0, 0, 1, 0x7d };
  161883. static const UINT8 val_ac_luminance[] =
  161884. { 0x01, 0x02, 0x03, 0x00, 0x04, 0x11, 0x05, 0x12,
  161885. 0x21, 0x31, 0x41, 0x06, 0x13, 0x51, 0x61, 0x07,
  161886. 0x22, 0x71, 0x14, 0x32, 0x81, 0x91, 0xa1, 0x08,
  161887. 0x23, 0x42, 0xb1, 0xc1, 0x15, 0x52, 0xd1, 0xf0,
  161888. 0x24, 0x33, 0x62, 0x72, 0x82, 0x09, 0x0a, 0x16,
  161889. 0x17, 0x18, 0x19, 0x1a, 0x25, 0x26, 0x27, 0x28,
  161890. 0x29, 0x2a, 0x34, 0x35, 0x36, 0x37, 0x38, 0x39,
  161891. 0x3a, 0x43, 0x44, 0x45, 0x46, 0x47, 0x48, 0x49,
  161892. 0x4a, 0x53, 0x54, 0x55, 0x56, 0x57, 0x58, 0x59,
  161893. 0x5a, 0x63, 0x64, 0x65, 0x66, 0x67, 0x68, 0x69,
  161894. 0x6a, 0x73, 0x74, 0x75, 0x76, 0x77, 0x78, 0x79,
  161895. 0x7a, 0x83, 0x84, 0x85, 0x86, 0x87, 0x88, 0x89,
  161896. 0x8a, 0x92, 0x93, 0x94, 0x95, 0x96, 0x97, 0x98,
  161897. 0x99, 0x9a, 0xa2, 0xa3, 0xa4, 0xa5, 0xa6, 0xa7,
  161898. 0xa8, 0xa9, 0xaa, 0xb2, 0xb3, 0xb4, 0xb5, 0xb6,
  161899. 0xb7, 0xb8, 0xb9, 0xba, 0xc2, 0xc3, 0xc4, 0xc5,
  161900. 0xc6, 0xc7, 0xc8, 0xc9, 0xca, 0xd2, 0xd3, 0xd4,
  161901. 0xd5, 0xd6, 0xd7, 0xd8, 0xd9, 0xda, 0xe1, 0xe2,
  161902. 0xe3, 0xe4, 0xe5, 0xe6, 0xe7, 0xe8, 0xe9, 0xea,
  161903. 0xf1, 0xf2, 0xf3, 0xf4, 0xf5, 0xf6, 0xf7, 0xf8,
  161904. 0xf9, 0xfa };
  161905. static const UINT8 bits_ac_chrominance[17] =
  161906. { /* 0-base */ 0, 0, 2, 1, 2, 4, 4, 3, 4, 7, 5, 4, 4, 0, 1, 2, 0x77 };
  161907. static const UINT8 val_ac_chrominance[] =
  161908. { 0x00, 0x01, 0x02, 0x03, 0x11, 0x04, 0x05, 0x21,
  161909. 0x31, 0x06, 0x12, 0x41, 0x51, 0x07, 0x61, 0x71,
  161910. 0x13, 0x22, 0x32, 0x81, 0x08, 0x14, 0x42, 0x91,
  161911. 0xa1, 0xb1, 0xc1, 0x09, 0x23, 0x33, 0x52, 0xf0,
  161912. 0x15, 0x62, 0x72, 0xd1, 0x0a, 0x16, 0x24, 0x34,
  161913. 0xe1, 0x25, 0xf1, 0x17, 0x18, 0x19, 0x1a, 0x26,
  161914. 0x27, 0x28, 0x29, 0x2a, 0x35, 0x36, 0x37, 0x38,
  161915. 0x39, 0x3a, 0x43, 0x44, 0x45, 0x46, 0x47, 0x48,
  161916. 0x49, 0x4a, 0x53, 0x54, 0x55, 0x56, 0x57, 0x58,
  161917. 0x59, 0x5a, 0x63, 0x64, 0x65, 0x66, 0x67, 0x68,
  161918. 0x69, 0x6a, 0x73, 0x74, 0x75, 0x76, 0x77, 0x78,
  161919. 0x79, 0x7a, 0x82, 0x83, 0x84, 0x85, 0x86, 0x87,
  161920. 0x88, 0x89, 0x8a, 0x92, 0x93, 0x94, 0x95, 0x96,
  161921. 0x97, 0x98, 0x99, 0x9a, 0xa2, 0xa3, 0xa4, 0xa5,
  161922. 0xa6, 0xa7, 0xa8, 0xa9, 0xaa, 0xb2, 0xb3, 0xb4,
  161923. 0xb5, 0xb6, 0xb7, 0xb8, 0xb9, 0xba, 0xc2, 0xc3,
  161924. 0xc4, 0xc5, 0xc6, 0xc7, 0xc8, 0xc9, 0xca, 0xd2,
  161925. 0xd3, 0xd4, 0xd5, 0xd6, 0xd7, 0xd8, 0xd9, 0xda,
  161926. 0xe2, 0xe3, 0xe4, 0xe5, 0xe6, 0xe7, 0xe8, 0xe9,
  161927. 0xea, 0xf2, 0xf3, 0xf4, 0xf5, 0xf6, 0xf7, 0xf8,
  161928. 0xf9, 0xfa };
  161929. add_huff_table(cinfo, &cinfo->dc_huff_tbl_ptrs[0],
  161930. bits_dc_luminance, val_dc_luminance);
  161931. add_huff_table(cinfo, &cinfo->ac_huff_tbl_ptrs[0],
  161932. bits_ac_luminance, val_ac_luminance);
  161933. add_huff_table(cinfo, &cinfo->dc_huff_tbl_ptrs[1],
  161934. bits_dc_chrominance, val_dc_chrominance);
  161935. add_huff_table(cinfo, &cinfo->ac_huff_tbl_ptrs[1],
  161936. bits_ac_chrominance, val_ac_chrominance);
  161937. }
  161938. /*
  161939. * Default parameter setup for compression.
  161940. *
  161941. * Applications that don't choose to use this routine must do their
  161942. * own setup of all these parameters. Alternately, you can call this
  161943. * to establish defaults and then alter parameters selectively. This
  161944. * is the recommended approach since, if we add any new parameters,
  161945. * your code will still work (they'll be set to reasonable defaults).
  161946. */
  161947. GLOBAL(void)
  161948. jpeg_set_defaults (j_compress_ptr cinfo)
  161949. {
  161950. int i;
  161951. /* Safety check to ensure start_compress not called yet. */
  161952. if (cinfo->global_state != CSTATE_START)
  161953. ERREXIT1(cinfo, JERR_BAD_STATE, cinfo->global_state);
  161954. /* Allocate comp_info array large enough for maximum component count.
  161955. * Array is made permanent in case application wants to compress
  161956. * multiple images at same param settings.
  161957. */
  161958. if (cinfo->comp_info == NULL)
  161959. cinfo->comp_info = (jpeg_component_info *)
  161960. (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_PERMANENT,
  161961. MAX_COMPONENTS * SIZEOF(jpeg_component_info));
  161962. /* Initialize everything not dependent on the color space */
  161963. cinfo->data_precision = BITS_IN_JSAMPLE;
  161964. /* Set up two quantization tables using default quality of 75 */
  161965. jpeg_set_quality(cinfo, 75, TRUE);
  161966. /* Set up two Huffman tables */
  161967. std_huff_tables(cinfo);
  161968. /* Initialize default arithmetic coding conditioning */
  161969. for (i = 0; i < NUM_ARITH_TBLS; i++) {
  161970. cinfo->arith_dc_L[i] = 0;
  161971. cinfo->arith_dc_U[i] = 1;
  161972. cinfo->arith_ac_K[i] = 5;
  161973. }
  161974. /* Default is no multiple-scan output */
  161975. cinfo->scan_info = NULL;
  161976. cinfo->num_scans = 0;
  161977. /* Expect normal source image, not raw downsampled data */
  161978. cinfo->raw_data_in = FALSE;
  161979. /* Use Huffman coding, not arithmetic coding, by default */
  161980. cinfo->arith_code = FALSE;
  161981. /* By default, don't do extra passes to optimize entropy coding */
  161982. cinfo->optimize_coding = FALSE;
  161983. /* The standard Huffman tables are only valid for 8-bit data precision.
  161984. * If the precision is higher, force optimization on so that usable
  161985. * tables will be computed. This test can be removed if default tables
  161986. * are supplied that are valid for the desired precision.
  161987. */
  161988. if (cinfo->data_precision > 8)
  161989. cinfo->optimize_coding = TRUE;
  161990. /* By default, use the simpler non-cosited sampling alignment */
  161991. cinfo->CCIR601_sampling = FALSE;
  161992. /* No input smoothing */
  161993. cinfo->smoothing_factor = 0;
  161994. /* DCT algorithm preference */
  161995. cinfo->dct_method = JDCT_DEFAULT;
  161996. /* No restart markers */
  161997. cinfo->restart_interval = 0;
  161998. cinfo->restart_in_rows = 0;
  161999. /* Fill in default JFIF marker parameters. Note that whether the marker
  162000. * will actually be written is determined by jpeg_set_colorspace.
  162001. *
  162002. * By default, the library emits JFIF version code 1.01.
  162003. * An application that wants to emit JFIF 1.02 extension markers should set
  162004. * JFIF_minor_version to 2. We could probably get away with just defaulting
  162005. * to 1.02, but there may still be some decoders in use that will complain
  162006. * about that; saying 1.01 should minimize compatibility problems.
  162007. */
  162008. cinfo->JFIF_major_version = 1; /* Default JFIF version = 1.01 */
  162009. cinfo->JFIF_minor_version = 1;
  162010. cinfo->density_unit = 0; /* Pixel size is unknown by default */
  162011. cinfo->X_density = 1; /* Pixel aspect ratio is square by default */
  162012. cinfo->Y_density = 1;
  162013. /* Choose JPEG colorspace based on input space, set defaults accordingly */
  162014. jpeg_default_colorspace(cinfo);
  162015. }
  162016. /*
  162017. * Select an appropriate JPEG colorspace for in_color_space.
  162018. */
  162019. GLOBAL(void)
  162020. jpeg_default_colorspace (j_compress_ptr cinfo)
  162021. {
  162022. switch (cinfo->in_color_space) {
  162023. case JCS_GRAYSCALE:
  162024. jpeg_set_colorspace(cinfo, JCS_GRAYSCALE);
  162025. break;
  162026. case JCS_RGB:
  162027. jpeg_set_colorspace(cinfo, JCS_YCbCr);
  162028. break;
  162029. case JCS_YCbCr:
  162030. jpeg_set_colorspace(cinfo, JCS_YCbCr);
  162031. break;
  162032. case JCS_CMYK:
  162033. jpeg_set_colorspace(cinfo, JCS_CMYK); /* By default, no translation */
  162034. break;
  162035. case JCS_YCCK:
  162036. jpeg_set_colorspace(cinfo, JCS_YCCK);
  162037. break;
  162038. case JCS_UNKNOWN:
  162039. jpeg_set_colorspace(cinfo, JCS_UNKNOWN);
  162040. break;
  162041. default:
  162042. ERREXIT(cinfo, JERR_BAD_IN_COLORSPACE);
  162043. }
  162044. }
  162045. /*
  162046. * Set the JPEG colorspace, and choose colorspace-dependent default values.
  162047. */
  162048. GLOBAL(void)
  162049. jpeg_set_colorspace (j_compress_ptr cinfo, J_COLOR_SPACE colorspace)
  162050. {
  162051. jpeg_component_info * compptr;
  162052. int ci;
  162053. #define SET_COMP(index,id,hsamp,vsamp,quant,dctbl,actbl) \
  162054. (compptr = &cinfo->comp_info[index], \
  162055. compptr->component_id = (id), \
  162056. compptr->h_samp_factor = (hsamp), \
  162057. compptr->v_samp_factor = (vsamp), \
  162058. compptr->quant_tbl_no = (quant), \
  162059. compptr->dc_tbl_no = (dctbl), \
  162060. compptr->ac_tbl_no = (actbl) )
  162061. /* Safety check to ensure start_compress not called yet. */
  162062. if (cinfo->global_state != CSTATE_START)
  162063. ERREXIT1(cinfo, JERR_BAD_STATE, cinfo->global_state);
  162064. /* For all colorspaces, we use Q and Huff tables 0 for luminance components,
  162065. * tables 1 for chrominance components.
  162066. */
  162067. cinfo->jpeg_color_space = colorspace;
  162068. cinfo->write_JFIF_header = FALSE; /* No marker for non-JFIF colorspaces */
  162069. cinfo->write_Adobe_marker = FALSE; /* write no Adobe marker by default */
  162070. switch (colorspace) {
  162071. case JCS_GRAYSCALE:
  162072. cinfo->write_JFIF_header = TRUE; /* Write a JFIF marker */
  162073. cinfo->num_components = 1;
  162074. /* JFIF specifies component ID 1 */
  162075. SET_COMP(0, 1, 1,1, 0, 0,0);
  162076. break;
  162077. case JCS_RGB:
  162078. cinfo->write_Adobe_marker = TRUE; /* write Adobe marker to flag RGB */
  162079. cinfo->num_components = 3;
  162080. SET_COMP(0, 0x52 /* 'R' */, 1,1, 0, 0,0);
  162081. SET_COMP(1, 0x47 /* 'G' */, 1,1, 0, 0,0);
  162082. SET_COMP(2, 0x42 /* 'B' */, 1,1, 0, 0,0);
  162083. break;
  162084. case JCS_YCbCr:
  162085. cinfo->write_JFIF_header = TRUE; /* Write a JFIF marker */
  162086. cinfo->num_components = 3;
  162087. /* JFIF specifies component IDs 1,2,3 */
  162088. /* We default to 2x2 subsamples of chrominance */
  162089. SET_COMP(0, 1, 2,2, 0, 0,0);
  162090. SET_COMP(1, 2, 1,1, 1, 1,1);
  162091. SET_COMP(2, 3, 1,1, 1, 1,1);
  162092. break;
  162093. case JCS_CMYK:
  162094. cinfo->write_Adobe_marker = TRUE; /* write Adobe marker to flag CMYK */
  162095. cinfo->num_components = 4;
  162096. SET_COMP(0, 0x43 /* 'C' */, 1,1, 0, 0,0);
  162097. SET_COMP(1, 0x4D /* 'M' */, 1,1, 0, 0,0);
  162098. SET_COMP(2, 0x59 /* 'Y' */, 1,1, 0, 0,0);
  162099. SET_COMP(3, 0x4B /* 'K' */, 1,1, 0, 0,0);
  162100. break;
  162101. case JCS_YCCK:
  162102. cinfo->write_Adobe_marker = TRUE; /* write Adobe marker to flag YCCK */
  162103. cinfo->num_components = 4;
  162104. SET_COMP(0, 1, 2,2, 0, 0,0);
  162105. SET_COMP(1, 2, 1,1, 1, 1,1);
  162106. SET_COMP(2, 3, 1,1, 1, 1,1);
  162107. SET_COMP(3, 4, 2,2, 0, 0,0);
  162108. break;
  162109. case JCS_UNKNOWN:
  162110. cinfo->num_components = cinfo->input_components;
  162111. if (cinfo->num_components < 1 || cinfo->num_components > MAX_COMPONENTS)
  162112. ERREXIT2(cinfo, JERR_COMPONENT_COUNT, cinfo->num_components,
  162113. MAX_COMPONENTS);
  162114. for (ci = 0; ci < cinfo->num_components; ci++) {
  162115. SET_COMP(ci, ci, 1,1, 0, 0,0);
  162116. }
  162117. break;
  162118. default:
  162119. ERREXIT(cinfo, JERR_BAD_J_COLORSPACE);
  162120. }
  162121. }
  162122. #ifdef C_PROGRESSIVE_SUPPORTED
  162123. LOCAL(jpeg_scan_info *)
  162124. fill_a_scan (jpeg_scan_info * scanptr, int ci,
  162125. int Ss, int Se, int Ah, int Al)
  162126. /* Support routine: generate one scan for specified component */
  162127. {
  162128. scanptr->comps_in_scan = 1;
  162129. scanptr->component_index[0] = ci;
  162130. scanptr->Ss = Ss;
  162131. scanptr->Se = Se;
  162132. scanptr->Ah = Ah;
  162133. scanptr->Al = Al;
  162134. scanptr++;
  162135. return scanptr;
  162136. }
  162137. LOCAL(jpeg_scan_info *)
  162138. fill_scans (jpeg_scan_info * scanptr, int ncomps,
  162139. int Ss, int Se, int Ah, int Al)
  162140. /* Support routine: generate one scan for each component */
  162141. {
  162142. int ci;
  162143. for (ci = 0; ci < ncomps; ci++) {
  162144. scanptr->comps_in_scan = 1;
  162145. scanptr->component_index[0] = ci;
  162146. scanptr->Ss = Ss;
  162147. scanptr->Se = Se;
  162148. scanptr->Ah = Ah;
  162149. scanptr->Al = Al;
  162150. scanptr++;
  162151. }
  162152. return scanptr;
  162153. }
  162154. LOCAL(jpeg_scan_info *)
  162155. fill_dc_scans (jpeg_scan_info * scanptr, int ncomps, int Ah, int Al)
  162156. /* Support routine: generate interleaved DC scan if possible, else N scans */
  162157. {
  162158. int ci;
  162159. if (ncomps <= MAX_COMPS_IN_SCAN) {
  162160. /* Single interleaved DC scan */
  162161. scanptr->comps_in_scan = ncomps;
  162162. for (ci = 0; ci < ncomps; ci++)
  162163. scanptr->component_index[ci] = ci;
  162164. scanptr->Ss = scanptr->Se = 0;
  162165. scanptr->Ah = Ah;
  162166. scanptr->Al = Al;
  162167. scanptr++;
  162168. } else {
  162169. /* Noninterleaved DC scan for each component */
  162170. scanptr = fill_scans(scanptr, ncomps, 0, 0, Ah, Al);
  162171. }
  162172. return scanptr;
  162173. }
  162174. /*
  162175. * Create a recommended progressive-JPEG script.
  162176. * cinfo->num_components and cinfo->jpeg_color_space must be correct.
  162177. */
  162178. GLOBAL(void)
  162179. jpeg_simple_progression (j_compress_ptr cinfo)
  162180. {
  162181. int ncomps = cinfo->num_components;
  162182. int nscans;
  162183. jpeg_scan_info * scanptr;
  162184. /* Safety check to ensure start_compress not called yet. */
  162185. if (cinfo->global_state != CSTATE_START)
  162186. ERREXIT1(cinfo, JERR_BAD_STATE, cinfo->global_state);
  162187. /* Figure space needed for script. Calculation must match code below! */
  162188. if (ncomps == 3 && cinfo->jpeg_color_space == JCS_YCbCr) {
  162189. /* Custom script for YCbCr color images. */
  162190. nscans = 10;
  162191. } else {
  162192. /* All-purpose script for other color spaces. */
  162193. if (ncomps > MAX_COMPS_IN_SCAN)
  162194. nscans = 6 * ncomps; /* 2 DC + 4 AC scans per component */
  162195. else
  162196. nscans = 2 + 4 * ncomps; /* 2 DC scans; 4 AC scans per component */
  162197. }
  162198. /* Allocate space for script.
  162199. * We need to put it in the permanent pool in case the application performs
  162200. * multiple compressions without changing the settings. To avoid a memory
  162201. * leak if jpeg_simple_progression is called repeatedly for the same JPEG
  162202. * object, we try to re-use previously allocated space, and we allocate
  162203. * enough space to handle YCbCr even if initially asked for grayscale.
  162204. */
  162205. if (cinfo->script_space == NULL || cinfo->script_space_size < nscans) {
  162206. cinfo->script_space_size = MAX(nscans, 10);
  162207. cinfo->script_space = (jpeg_scan_info *)
  162208. (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_PERMANENT,
  162209. cinfo->script_space_size * SIZEOF(jpeg_scan_info));
  162210. }
  162211. scanptr = cinfo->script_space;
  162212. cinfo->scan_info = scanptr;
  162213. cinfo->num_scans = nscans;
  162214. if (ncomps == 3 && cinfo->jpeg_color_space == JCS_YCbCr) {
  162215. /* Custom script for YCbCr color images. */
  162216. /* Initial DC scan */
  162217. scanptr = fill_dc_scans(scanptr, ncomps, 0, 1);
  162218. /* Initial AC scan: get some luma data out in a hurry */
  162219. scanptr = fill_a_scan(scanptr, 0, 1, 5, 0, 2);
  162220. /* Chroma data is too small to be worth expending many scans on */
  162221. scanptr = fill_a_scan(scanptr, 2, 1, 63, 0, 1);
  162222. scanptr = fill_a_scan(scanptr, 1, 1, 63, 0, 1);
  162223. /* Complete spectral selection for luma AC */
  162224. scanptr = fill_a_scan(scanptr, 0, 6, 63, 0, 2);
  162225. /* Refine next bit of luma AC */
  162226. scanptr = fill_a_scan(scanptr, 0, 1, 63, 2, 1);
  162227. /* Finish DC successive approximation */
  162228. scanptr = fill_dc_scans(scanptr, ncomps, 1, 0);
  162229. /* Finish AC successive approximation */
  162230. scanptr = fill_a_scan(scanptr, 2, 1, 63, 1, 0);
  162231. scanptr = fill_a_scan(scanptr, 1, 1, 63, 1, 0);
  162232. /* Luma bottom bit comes last since it's usually largest scan */
  162233. scanptr = fill_a_scan(scanptr, 0, 1, 63, 1, 0);
  162234. } else {
  162235. /* All-purpose script for other color spaces. */
  162236. /* Successive approximation first pass */
  162237. scanptr = fill_dc_scans(scanptr, ncomps, 0, 1);
  162238. scanptr = fill_scans(scanptr, ncomps, 1, 5, 0, 2);
  162239. scanptr = fill_scans(scanptr, ncomps, 6, 63, 0, 2);
  162240. /* Successive approximation second pass */
  162241. scanptr = fill_scans(scanptr, ncomps, 1, 63, 2, 1);
  162242. /* Successive approximation final pass */
  162243. scanptr = fill_dc_scans(scanptr, ncomps, 1, 0);
  162244. scanptr = fill_scans(scanptr, ncomps, 1, 63, 1, 0);
  162245. }
  162246. }
  162247. #endif /* C_PROGRESSIVE_SUPPORTED */
  162248. /*** End of inlined file: jcparam.c ***/
  162249. /*** Start of inlined file: jcphuff.c ***/
  162250. #define JPEG_INTERNALS
  162251. #ifdef C_PROGRESSIVE_SUPPORTED
  162252. /* Expanded entropy encoder object for progressive Huffman encoding. */
  162253. typedef struct {
  162254. struct jpeg_entropy_encoder pub; /* public fields */
  162255. /* Mode flag: TRUE for optimization, FALSE for actual data output */
  162256. boolean gather_statistics;
  162257. /* Bit-level coding status.
  162258. * next_output_byte/free_in_buffer are local copies of cinfo->dest fields.
  162259. */
  162260. JOCTET * next_output_byte; /* => next byte to write in buffer */
  162261. size_t free_in_buffer; /* # of byte spaces remaining in buffer */
  162262. INT32 put_buffer; /* current bit-accumulation buffer */
  162263. int put_bits; /* # of bits now in it */
  162264. j_compress_ptr cinfo; /* link to cinfo (needed for dump_buffer) */
  162265. /* Coding status for DC components */
  162266. int last_dc_val[MAX_COMPS_IN_SCAN]; /* last DC coef for each component */
  162267. /* Coding status for AC components */
  162268. int ac_tbl_no; /* the table number of the single component */
  162269. unsigned int EOBRUN; /* run length of EOBs */
  162270. unsigned int BE; /* # of buffered correction bits before MCU */
  162271. char * bit_buffer; /* buffer for correction bits (1 per char) */
  162272. /* packing correction bits tightly would save some space but cost time... */
  162273. unsigned int restarts_to_go; /* MCUs left in this restart interval */
  162274. int next_restart_num; /* next restart number to write (0-7) */
  162275. /* Pointers to derived tables (these workspaces have image lifespan).
  162276. * Since any one scan codes only DC or only AC, we only need one set
  162277. * of tables, not one for DC and one for AC.
  162278. */
  162279. c_derived_tbl * derived_tbls[NUM_HUFF_TBLS];
  162280. /* Statistics tables for optimization; again, one set is enough */
  162281. long * count_ptrs[NUM_HUFF_TBLS];
  162282. } phuff_entropy_encoder;
  162283. typedef phuff_entropy_encoder * phuff_entropy_ptr;
  162284. /* MAX_CORR_BITS is the number of bits the AC refinement correction-bit
  162285. * buffer can hold. Larger sizes may slightly improve compression, but
  162286. * 1000 is already well into the realm of overkill.
  162287. * The minimum safe size is 64 bits.
  162288. */
  162289. #define MAX_CORR_BITS 1000 /* Max # of correction bits I can buffer */
  162290. /* IRIGHT_SHIFT is like RIGHT_SHIFT, but works on int rather than INT32.
  162291. * We assume that int right shift is unsigned if INT32 right shift is,
  162292. * which should be safe.
  162293. */
  162294. #ifdef RIGHT_SHIFT_IS_UNSIGNED
  162295. #define ISHIFT_TEMPS int ishift_temp;
  162296. #define IRIGHT_SHIFT(x,shft) \
  162297. ((ishift_temp = (x)) < 0 ? \
  162298. (ishift_temp >> (shft)) | ((~0) << (16-(shft))) : \
  162299. (ishift_temp >> (shft)))
  162300. #else
  162301. #define ISHIFT_TEMPS
  162302. #define IRIGHT_SHIFT(x,shft) ((x) >> (shft))
  162303. #endif
  162304. /* Forward declarations */
  162305. METHODDEF(boolean) encode_mcu_DC_first JPP((j_compress_ptr cinfo,
  162306. JBLOCKROW *MCU_data));
  162307. METHODDEF(boolean) encode_mcu_AC_first JPP((j_compress_ptr cinfo,
  162308. JBLOCKROW *MCU_data));
  162309. METHODDEF(boolean) encode_mcu_DC_refine JPP((j_compress_ptr cinfo,
  162310. JBLOCKROW *MCU_data));
  162311. METHODDEF(boolean) encode_mcu_AC_refine JPP((j_compress_ptr cinfo,
  162312. JBLOCKROW *MCU_data));
  162313. METHODDEF(void) finish_pass_phuff JPP((j_compress_ptr cinfo));
  162314. METHODDEF(void) finish_pass_gather_phuff JPP((j_compress_ptr cinfo));
  162315. /*
  162316. * Initialize for a Huffman-compressed scan using progressive JPEG.
  162317. */
  162318. METHODDEF(void)
  162319. start_pass_phuff (j_compress_ptr cinfo, boolean gather_statistics)
  162320. {
  162321. phuff_entropy_ptr entropy = (phuff_entropy_ptr) cinfo->entropy;
  162322. boolean is_DC_band;
  162323. int ci, tbl;
  162324. jpeg_component_info * compptr;
  162325. entropy->cinfo = cinfo;
  162326. entropy->gather_statistics = gather_statistics;
  162327. is_DC_band = (cinfo->Ss == 0);
  162328. /* We assume jcmaster.c already validated the scan parameters. */
  162329. /* Select execution routines */
  162330. if (cinfo->Ah == 0) {
  162331. if (is_DC_band)
  162332. entropy->pub.encode_mcu = encode_mcu_DC_first;
  162333. else
  162334. entropy->pub.encode_mcu = encode_mcu_AC_first;
  162335. } else {
  162336. if (is_DC_band)
  162337. entropy->pub.encode_mcu = encode_mcu_DC_refine;
  162338. else {
  162339. entropy->pub.encode_mcu = encode_mcu_AC_refine;
  162340. /* AC refinement needs a correction bit buffer */
  162341. if (entropy->bit_buffer == NULL)
  162342. entropy->bit_buffer = (char *)
  162343. (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_IMAGE,
  162344. MAX_CORR_BITS * SIZEOF(char));
  162345. }
  162346. }
  162347. if (gather_statistics)
  162348. entropy->pub.finish_pass = finish_pass_gather_phuff;
  162349. else
  162350. entropy->pub.finish_pass = finish_pass_phuff;
  162351. /* Only DC coefficients may be interleaved, so cinfo->comps_in_scan = 1
  162352. * for AC coefficients.
  162353. */
  162354. for (ci = 0; ci < cinfo->comps_in_scan; ci++) {
  162355. compptr = cinfo->cur_comp_info[ci];
  162356. /* Initialize DC predictions to 0 */
  162357. entropy->last_dc_val[ci] = 0;
  162358. /* Get table index */
  162359. if (is_DC_band) {
  162360. if (cinfo->Ah != 0) /* DC refinement needs no table */
  162361. continue;
  162362. tbl = compptr->dc_tbl_no;
  162363. } else {
  162364. entropy->ac_tbl_no = tbl = compptr->ac_tbl_no;
  162365. }
  162366. if (gather_statistics) {
  162367. /* Check for invalid table index */
  162368. /* (make_c_derived_tbl does this in the other path) */
  162369. if (tbl < 0 || tbl >= NUM_HUFF_TBLS)
  162370. ERREXIT1(cinfo, JERR_NO_HUFF_TABLE, tbl);
  162371. /* Allocate and zero the statistics tables */
  162372. /* Note that jpeg_gen_optimal_table expects 257 entries in each table! */
  162373. if (entropy->count_ptrs[tbl] == NULL)
  162374. entropy->count_ptrs[tbl] = (long *)
  162375. (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_IMAGE,
  162376. 257 * SIZEOF(long));
  162377. MEMZERO(entropy->count_ptrs[tbl], 257 * SIZEOF(long));
  162378. } else {
  162379. /* Compute derived values for Huffman table */
  162380. /* We may do this more than once for a table, but it's not expensive */
  162381. jpeg_make_c_derived_tbl(cinfo, is_DC_band, tbl,
  162382. & entropy->derived_tbls[tbl]);
  162383. }
  162384. }
  162385. /* Initialize AC stuff */
  162386. entropy->EOBRUN = 0;
  162387. entropy->BE = 0;
  162388. /* Initialize bit buffer to empty */
  162389. entropy->put_buffer = 0;
  162390. entropy->put_bits = 0;
  162391. /* Initialize restart stuff */
  162392. entropy->restarts_to_go = cinfo->restart_interval;
  162393. entropy->next_restart_num = 0;
  162394. }
  162395. /* Outputting bytes to the file.
  162396. * NB: these must be called only when actually outputting,
  162397. * that is, entropy->gather_statistics == FALSE.
  162398. */
  162399. /* Emit a byte */
  162400. #define emit_byte(entropy,val) \
  162401. { *(entropy)->next_output_byte++ = (JOCTET) (val); \
  162402. if (--(entropy)->free_in_buffer == 0) \
  162403. dump_buffer_p(entropy); }
  162404. LOCAL(void)
  162405. dump_buffer_p (phuff_entropy_ptr entropy)
  162406. /* Empty the output buffer; we do not support suspension in this module. */
  162407. {
  162408. struct jpeg_destination_mgr * dest = entropy->cinfo->dest;
  162409. if (! (*dest->empty_output_buffer) (entropy->cinfo))
  162410. ERREXIT(entropy->cinfo, JERR_CANT_SUSPEND);
  162411. /* After a successful buffer dump, must reset buffer pointers */
  162412. entropy->next_output_byte = dest->next_output_byte;
  162413. entropy->free_in_buffer = dest->free_in_buffer;
  162414. }
  162415. /* Outputting bits to the file */
  162416. /* Only the right 24 bits of put_buffer are used; the valid bits are
  162417. * left-justified in this part. At most 16 bits can be passed to emit_bits
  162418. * in one call, and we never retain more than 7 bits in put_buffer
  162419. * between calls, so 24 bits are sufficient.
  162420. */
  162421. INLINE
  162422. LOCAL(void)
  162423. emit_bits_p (phuff_entropy_ptr entropy, unsigned int code, int size)
  162424. /* Emit some bits, unless we are in gather mode */
  162425. {
  162426. /* This routine is heavily used, so it's worth coding tightly. */
  162427. register INT32 put_buffer = (INT32) code;
  162428. register int put_bits = entropy->put_bits;
  162429. /* if size is 0, caller used an invalid Huffman table entry */
  162430. if (size == 0)
  162431. ERREXIT(entropy->cinfo, JERR_HUFF_MISSING_CODE);
  162432. if (entropy->gather_statistics)
  162433. return; /* do nothing if we're only getting stats */
  162434. put_buffer &= (((INT32) 1)<<size) - 1; /* mask off any extra bits in code */
  162435. put_bits += size; /* new number of bits in buffer */
  162436. put_buffer <<= 24 - put_bits; /* align incoming bits */
  162437. put_buffer |= entropy->put_buffer; /* and merge with old buffer contents */
  162438. while (put_bits >= 8) {
  162439. int c = (int) ((put_buffer >> 16) & 0xFF);
  162440. emit_byte(entropy, c);
  162441. if (c == 0xFF) { /* need to stuff a zero byte? */
  162442. emit_byte(entropy, 0);
  162443. }
  162444. put_buffer <<= 8;
  162445. put_bits -= 8;
  162446. }
  162447. entropy->put_buffer = put_buffer; /* update variables */
  162448. entropy->put_bits = put_bits;
  162449. }
  162450. LOCAL(void)
  162451. flush_bits_p (phuff_entropy_ptr entropy)
  162452. {
  162453. emit_bits_p(entropy, 0x7F, 7); /* fill any partial byte with ones */
  162454. entropy->put_buffer = 0; /* and reset bit-buffer to empty */
  162455. entropy->put_bits = 0;
  162456. }
  162457. /*
  162458. * Emit (or just count) a Huffman symbol.
  162459. */
  162460. INLINE
  162461. LOCAL(void)
  162462. emit_symbol (phuff_entropy_ptr entropy, int tbl_no, int symbol)
  162463. {
  162464. if (entropy->gather_statistics)
  162465. entropy->count_ptrs[tbl_no][symbol]++;
  162466. else {
  162467. c_derived_tbl * tbl = entropy->derived_tbls[tbl_no];
  162468. emit_bits_p(entropy, tbl->ehufco[symbol], tbl->ehufsi[symbol]);
  162469. }
  162470. }
  162471. /*
  162472. * Emit bits from a correction bit buffer.
  162473. */
  162474. LOCAL(void)
  162475. emit_buffered_bits (phuff_entropy_ptr entropy, char * bufstart,
  162476. unsigned int nbits)
  162477. {
  162478. if (entropy->gather_statistics)
  162479. return; /* no real work */
  162480. while (nbits > 0) {
  162481. emit_bits_p(entropy, (unsigned int) (*bufstart), 1);
  162482. bufstart++;
  162483. nbits--;
  162484. }
  162485. }
  162486. /*
  162487. * Emit any pending EOBRUN symbol.
  162488. */
  162489. LOCAL(void)
  162490. emit_eobrun (phuff_entropy_ptr entropy)
  162491. {
  162492. register int temp, nbits;
  162493. if (entropy->EOBRUN > 0) { /* if there is any pending EOBRUN */
  162494. temp = entropy->EOBRUN;
  162495. nbits = 0;
  162496. while ((temp >>= 1))
  162497. nbits++;
  162498. /* safety check: shouldn't happen given limited correction-bit buffer */
  162499. if (nbits > 14)
  162500. ERREXIT(entropy->cinfo, JERR_HUFF_MISSING_CODE);
  162501. emit_symbol(entropy, entropy->ac_tbl_no, nbits << 4);
  162502. if (nbits)
  162503. emit_bits_p(entropy, entropy->EOBRUN, nbits);
  162504. entropy->EOBRUN = 0;
  162505. /* Emit any buffered correction bits */
  162506. emit_buffered_bits(entropy, entropy->bit_buffer, entropy->BE);
  162507. entropy->BE = 0;
  162508. }
  162509. }
  162510. /*
  162511. * Emit a restart marker & resynchronize predictions.
  162512. */
  162513. LOCAL(void)
  162514. emit_restart_p (phuff_entropy_ptr entropy, int restart_num)
  162515. {
  162516. int ci;
  162517. emit_eobrun(entropy);
  162518. if (! entropy->gather_statistics) {
  162519. flush_bits_p(entropy);
  162520. emit_byte(entropy, 0xFF);
  162521. emit_byte(entropy, JPEG_RST0 + restart_num);
  162522. }
  162523. if (entropy->cinfo->Ss == 0) {
  162524. /* Re-initialize DC predictions to 0 */
  162525. for (ci = 0; ci < entropy->cinfo->comps_in_scan; ci++)
  162526. entropy->last_dc_val[ci] = 0;
  162527. } else {
  162528. /* Re-initialize all AC-related fields to 0 */
  162529. entropy->EOBRUN = 0;
  162530. entropy->BE = 0;
  162531. }
  162532. }
  162533. /*
  162534. * MCU encoding for DC initial scan (either spectral selection,
  162535. * or first pass of successive approximation).
  162536. */
  162537. METHODDEF(boolean)
  162538. encode_mcu_DC_first (j_compress_ptr cinfo, JBLOCKROW *MCU_data)
  162539. {
  162540. phuff_entropy_ptr entropy = (phuff_entropy_ptr) cinfo->entropy;
  162541. register int temp, temp2;
  162542. register int nbits;
  162543. int blkn, ci;
  162544. int Al = cinfo->Al;
  162545. JBLOCKROW block;
  162546. jpeg_component_info * compptr;
  162547. ISHIFT_TEMPS
  162548. entropy->next_output_byte = cinfo->dest->next_output_byte;
  162549. entropy->free_in_buffer = cinfo->dest->free_in_buffer;
  162550. /* Emit restart marker if needed */
  162551. if (cinfo->restart_interval)
  162552. if (entropy->restarts_to_go == 0)
  162553. emit_restart_p(entropy, entropy->next_restart_num);
  162554. /* Encode the MCU data blocks */
  162555. for (blkn = 0; blkn < cinfo->blocks_in_MCU; blkn++) {
  162556. block = MCU_data[blkn];
  162557. ci = cinfo->MCU_membership[blkn];
  162558. compptr = cinfo->cur_comp_info[ci];
  162559. /* Compute the DC value after the required point transform by Al.
  162560. * This is simply an arithmetic right shift.
  162561. */
  162562. temp2 = IRIGHT_SHIFT((int) ((*block)[0]), Al);
  162563. /* DC differences are figured on the point-transformed values. */
  162564. temp = temp2 - entropy->last_dc_val[ci];
  162565. entropy->last_dc_val[ci] = temp2;
  162566. /* Encode the DC coefficient difference per section G.1.2.1 */
  162567. temp2 = temp;
  162568. if (temp < 0) {
  162569. temp = -temp; /* temp is abs value of input */
  162570. /* For a negative input, want temp2 = bitwise complement of abs(input) */
  162571. /* This code assumes we are on a two's complement machine */
  162572. temp2--;
  162573. }
  162574. /* Find the number of bits needed for the magnitude of the coefficient */
  162575. nbits = 0;
  162576. while (temp) {
  162577. nbits++;
  162578. temp >>= 1;
  162579. }
  162580. /* Check for out-of-range coefficient values.
  162581. * Since we're encoding a difference, the range limit is twice as much.
  162582. */
  162583. if (nbits > MAX_COEF_BITS+1)
  162584. ERREXIT(cinfo, JERR_BAD_DCT_COEF);
  162585. /* Count/emit the Huffman-coded symbol for the number of bits */
  162586. emit_symbol(entropy, compptr->dc_tbl_no, nbits);
  162587. /* Emit that number of bits of the value, if positive, */
  162588. /* or the complement of its magnitude, if negative. */
  162589. if (nbits) /* emit_bits rejects calls with size 0 */
  162590. emit_bits_p(entropy, (unsigned int) temp2, nbits);
  162591. }
  162592. cinfo->dest->next_output_byte = entropy->next_output_byte;
  162593. cinfo->dest->free_in_buffer = entropy->free_in_buffer;
  162594. /* Update restart-interval state too */
  162595. if (cinfo->restart_interval) {
  162596. if (entropy->restarts_to_go == 0) {
  162597. entropy->restarts_to_go = cinfo->restart_interval;
  162598. entropy->next_restart_num++;
  162599. entropy->next_restart_num &= 7;
  162600. }
  162601. entropy->restarts_to_go--;
  162602. }
  162603. return TRUE;
  162604. }
  162605. /*
  162606. * MCU encoding for AC initial scan (either spectral selection,
  162607. * or first pass of successive approximation).
  162608. */
  162609. METHODDEF(boolean)
  162610. encode_mcu_AC_first (j_compress_ptr cinfo, JBLOCKROW *MCU_data)
  162611. {
  162612. phuff_entropy_ptr entropy = (phuff_entropy_ptr) cinfo->entropy;
  162613. register int temp, temp2;
  162614. register int nbits;
  162615. register int r, k;
  162616. int Se = cinfo->Se;
  162617. int Al = cinfo->Al;
  162618. JBLOCKROW block;
  162619. entropy->next_output_byte = cinfo->dest->next_output_byte;
  162620. entropy->free_in_buffer = cinfo->dest->free_in_buffer;
  162621. /* Emit restart marker if needed */
  162622. if (cinfo->restart_interval)
  162623. if (entropy->restarts_to_go == 0)
  162624. emit_restart_p(entropy, entropy->next_restart_num);
  162625. /* Encode the MCU data block */
  162626. block = MCU_data[0];
  162627. /* Encode the AC coefficients per section G.1.2.2, fig. G.3 */
  162628. r = 0; /* r = run length of zeros */
  162629. for (k = cinfo->Ss; k <= Se; k++) {
  162630. if ((temp = (*block)[jpeg_natural_order[k]]) == 0) {
  162631. r++;
  162632. continue;
  162633. }
  162634. /* We must apply the point transform by Al. For AC coefficients this
  162635. * is an integer division with rounding towards 0. To do this portably
  162636. * in C, we shift after obtaining the absolute value; so the code is
  162637. * interwoven with finding the abs value (temp) and output bits (temp2).
  162638. */
  162639. if (temp < 0) {
  162640. temp = -temp; /* temp is abs value of input */
  162641. temp >>= Al; /* apply the point transform */
  162642. /* For a negative coef, want temp2 = bitwise complement of abs(coef) */
  162643. temp2 = ~temp;
  162644. } else {
  162645. temp >>= Al; /* apply the point transform */
  162646. temp2 = temp;
  162647. }
  162648. /* Watch out for case that nonzero coef is zero after point transform */
  162649. if (temp == 0) {
  162650. r++;
  162651. continue;
  162652. }
  162653. /* Emit any pending EOBRUN */
  162654. if (entropy->EOBRUN > 0)
  162655. emit_eobrun(entropy);
  162656. /* if run length > 15, must emit special run-length-16 codes (0xF0) */
  162657. while (r > 15) {
  162658. emit_symbol(entropy, entropy->ac_tbl_no, 0xF0);
  162659. r -= 16;
  162660. }
  162661. /* Find the number of bits needed for the magnitude of the coefficient */
  162662. nbits = 1; /* there must be at least one 1 bit */
  162663. while ((temp >>= 1))
  162664. nbits++;
  162665. /* Check for out-of-range coefficient values */
  162666. if (nbits > MAX_COEF_BITS)
  162667. ERREXIT(cinfo, JERR_BAD_DCT_COEF);
  162668. /* Count/emit Huffman symbol for run length / number of bits */
  162669. emit_symbol(entropy, entropy->ac_tbl_no, (r << 4) + nbits);
  162670. /* Emit that number of bits of the value, if positive, */
  162671. /* or the complement of its magnitude, if negative. */
  162672. emit_bits_p(entropy, (unsigned int) temp2, nbits);
  162673. r = 0; /* reset zero run length */
  162674. }
  162675. if (r > 0) { /* If there are trailing zeroes, */
  162676. entropy->EOBRUN++; /* count an EOB */
  162677. if (entropy->EOBRUN == 0x7FFF)
  162678. emit_eobrun(entropy); /* force it out to avoid overflow */
  162679. }
  162680. cinfo->dest->next_output_byte = entropy->next_output_byte;
  162681. cinfo->dest->free_in_buffer = entropy->free_in_buffer;
  162682. /* Update restart-interval state too */
  162683. if (cinfo->restart_interval) {
  162684. if (entropy->restarts_to_go == 0) {
  162685. entropy->restarts_to_go = cinfo->restart_interval;
  162686. entropy->next_restart_num++;
  162687. entropy->next_restart_num &= 7;
  162688. }
  162689. entropy->restarts_to_go--;
  162690. }
  162691. return TRUE;
  162692. }
  162693. /*
  162694. * MCU encoding for DC successive approximation refinement scan.
  162695. * Note: we assume such scans can be multi-component, although the spec
  162696. * is not very clear on the point.
  162697. */
  162698. METHODDEF(boolean)
  162699. encode_mcu_DC_refine (j_compress_ptr cinfo, JBLOCKROW *MCU_data)
  162700. {
  162701. phuff_entropy_ptr entropy = (phuff_entropy_ptr) cinfo->entropy;
  162702. register int temp;
  162703. int blkn;
  162704. int Al = cinfo->Al;
  162705. JBLOCKROW block;
  162706. entropy->next_output_byte = cinfo->dest->next_output_byte;
  162707. entropy->free_in_buffer = cinfo->dest->free_in_buffer;
  162708. /* Emit restart marker if needed */
  162709. if (cinfo->restart_interval)
  162710. if (entropy->restarts_to_go == 0)
  162711. emit_restart_p(entropy, entropy->next_restart_num);
  162712. /* Encode the MCU data blocks */
  162713. for (blkn = 0; blkn < cinfo->blocks_in_MCU; blkn++) {
  162714. block = MCU_data[blkn];
  162715. /* We simply emit the Al'th bit of the DC coefficient value. */
  162716. temp = (*block)[0];
  162717. emit_bits_p(entropy, (unsigned int) (temp >> Al), 1);
  162718. }
  162719. cinfo->dest->next_output_byte = entropy->next_output_byte;
  162720. cinfo->dest->free_in_buffer = entropy->free_in_buffer;
  162721. /* Update restart-interval state too */
  162722. if (cinfo->restart_interval) {
  162723. if (entropy->restarts_to_go == 0) {
  162724. entropy->restarts_to_go = cinfo->restart_interval;
  162725. entropy->next_restart_num++;
  162726. entropy->next_restart_num &= 7;
  162727. }
  162728. entropy->restarts_to_go--;
  162729. }
  162730. return TRUE;
  162731. }
  162732. /*
  162733. * MCU encoding for AC successive approximation refinement scan.
  162734. */
  162735. METHODDEF(boolean)
  162736. encode_mcu_AC_refine (j_compress_ptr cinfo, JBLOCKROW *MCU_data)
  162737. {
  162738. phuff_entropy_ptr entropy = (phuff_entropy_ptr) cinfo->entropy;
  162739. register int temp;
  162740. register int r, k;
  162741. int EOB;
  162742. char *BR_buffer;
  162743. unsigned int BR;
  162744. int Se = cinfo->Se;
  162745. int Al = cinfo->Al;
  162746. JBLOCKROW block;
  162747. int absvalues[DCTSIZE2];
  162748. entropy->next_output_byte = cinfo->dest->next_output_byte;
  162749. entropy->free_in_buffer = cinfo->dest->free_in_buffer;
  162750. /* Emit restart marker if needed */
  162751. if (cinfo->restart_interval)
  162752. if (entropy->restarts_to_go == 0)
  162753. emit_restart_p(entropy, entropy->next_restart_num);
  162754. /* Encode the MCU data block */
  162755. block = MCU_data[0];
  162756. /* It is convenient to make a pre-pass to determine the transformed
  162757. * coefficients' absolute values and the EOB position.
  162758. */
  162759. EOB = 0;
  162760. for (k = cinfo->Ss; k <= Se; k++) {
  162761. temp = (*block)[jpeg_natural_order[k]];
  162762. /* We must apply the point transform by Al. For AC coefficients this
  162763. * is an integer division with rounding towards 0. To do this portably
  162764. * in C, we shift after obtaining the absolute value.
  162765. */
  162766. if (temp < 0)
  162767. temp = -temp; /* temp is abs value of input */
  162768. temp >>= Al; /* apply the point transform */
  162769. absvalues[k] = temp; /* save abs value for main pass */
  162770. if (temp == 1)
  162771. EOB = k; /* EOB = index of last newly-nonzero coef */
  162772. }
  162773. /* Encode the AC coefficients per section G.1.2.3, fig. G.7 */
  162774. r = 0; /* r = run length of zeros */
  162775. BR = 0; /* BR = count of buffered bits added now */
  162776. BR_buffer = entropy->bit_buffer + entropy->BE; /* Append bits to buffer */
  162777. for (k = cinfo->Ss; k <= Se; k++) {
  162778. if ((temp = absvalues[k]) == 0) {
  162779. r++;
  162780. continue;
  162781. }
  162782. /* Emit any required ZRLs, but not if they can be folded into EOB */
  162783. while (r > 15 && k <= EOB) {
  162784. /* emit any pending EOBRUN and the BE correction bits */
  162785. emit_eobrun(entropy);
  162786. /* Emit ZRL */
  162787. emit_symbol(entropy, entropy->ac_tbl_no, 0xF0);
  162788. r -= 16;
  162789. /* Emit buffered correction bits that must be associated with ZRL */
  162790. emit_buffered_bits(entropy, BR_buffer, BR);
  162791. BR_buffer = entropy->bit_buffer; /* BE bits are gone now */
  162792. BR = 0;
  162793. }
  162794. /* If the coef was previously nonzero, it only needs a correction bit.
  162795. * NOTE: a straight translation of the spec's figure G.7 would suggest
  162796. * that we also need to test r > 15. But if r > 15, we can only get here
  162797. * if k > EOB, which implies that this coefficient is not 1.
  162798. */
  162799. if (temp > 1) {
  162800. /* The correction bit is the next bit of the absolute value. */
  162801. BR_buffer[BR++] = (char) (temp & 1);
  162802. continue;
  162803. }
  162804. /* Emit any pending EOBRUN and the BE correction bits */
  162805. emit_eobrun(entropy);
  162806. /* Count/emit Huffman symbol for run length / number of bits */
  162807. emit_symbol(entropy, entropy->ac_tbl_no, (r << 4) + 1);
  162808. /* Emit output bit for newly-nonzero coef */
  162809. temp = ((*block)[jpeg_natural_order[k]] < 0) ? 0 : 1;
  162810. emit_bits_p(entropy, (unsigned int) temp, 1);
  162811. /* Emit buffered correction bits that must be associated with this code */
  162812. emit_buffered_bits(entropy, BR_buffer, BR);
  162813. BR_buffer = entropy->bit_buffer; /* BE bits are gone now */
  162814. BR = 0;
  162815. r = 0; /* reset zero run length */
  162816. }
  162817. if (r > 0 || BR > 0) { /* If there are trailing zeroes, */
  162818. entropy->EOBRUN++; /* count an EOB */
  162819. entropy->BE += BR; /* concat my correction bits to older ones */
  162820. /* We force out the EOB if we risk either:
  162821. * 1. overflow of the EOB counter;
  162822. * 2. overflow of the correction bit buffer during the next MCU.
  162823. */
  162824. if (entropy->EOBRUN == 0x7FFF || entropy->BE > (MAX_CORR_BITS-DCTSIZE2+1))
  162825. emit_eobrun(entropy);
  162826. }
  162827. cinfo->dest->next_output_byte = entropy->next_output_byte;
  162828. cinfo->dest->free_in_buffer = entropy->free_in_buffer;
  162829. /* Update restart-interval state too */
  162830. if (cinfo->restart_interval) {
  162831. if (entropy->restarts_to_go == 0) {
  162832. entropy->restarts_to_go = cinfo->restart_interval;
  162833. entropy->next_restart_num++;
  162834. entropy->next_restart_num &= 7;
  162835. }
  162836. entropy->restarts_to_go--;
  162837. }
  162838. return TRUE;
  162839. }
  162840. /*
  162841. * Finish up at the end of a Huffman-compressed progressive scan.
  162842. */
  162843. METHODDEF(void)
  162844. finish_pass_phuff (j_compress_ptr cinfo)
  162845. {
  162846. phuff_entropy_ptr entropy = (phuff_entropy_ptr) cinfo->entropy;
  162847. entropy->next_output_byte = cinfo->dest->next_output_byte;
  162848. entropy->free_in_buffer = cinfo->dest->free_in_buffer;
  162849. /* Flush out any buffered data */
  162850. emit_eobrun(entropy);
  162851. flush_bits_p(entropy);
  162852. cinfo->dest->next_output_byte = entropy->next_output_byte;
  162853. cinfo->dest->free_in_buffer = entropy->free_in_buffer;
  162854. }
  162855. /*
  162856. * Finish up a statistics-gathering pass and create the new Huffman tables.
  162857. */
  162858. METHODDEF(void)
  162859. finish_pass_gather_phuff (j_compress_ptr cinfo)
  162860. {
  162861. phuff_entropy_ptr entropy = (phuff_entropy_ptr) cinfo->entropy;
  162862. boolean is_DC_band;
  162863. int ci, tbl;
  162864. jpeg_component_info * compptr;
  162865. JHUFF_TBL **htblptr;
  162866. boolean did[NUM_HUFF_TBLS];
  162867. /* Flush out buffered data (all we care about is counting the EOB symbol) */
  162868. emit_eobrun(entropy);
  162869. is_DC_band = (cinfo->Ss == 0);
  162870. /* It's important not to apply jpeg_gen_optimal_table more than once
  162871. * per table, because it clobbers the input frequency counts!
  162872. */
  162873. MEMZERO(did, SIZEOF(did));
  162874. for (ci = 0; ci < cinfo->comps_in_scan; ci++) {
  162875. compptr = cinfo->cur_comp_info[ci];
  162876. if (is_DC_band) {
  162877. if (cinfo->Ah != 0) /* DC refinement needs no table */
  162878. continue;
  162879. tbl = compptr->dc_tbl_no;
  162880. } else {
  162881. tbl = compptr->ac_tbl_no;
  162882. }
  162883. if (! did[tbl]) {
  162884. if (is_DC_band)
  162885. htblptr = & cinfo->dc_huff_tbl_ptrs[tbl];
  162886. else
  162887. htblptr = & cinfo->ac_huff_tbl_ptrs[tbl];
  162888. if (*htblptr == NULL)
  162889. *htblptr = jpeg_alloc_huff_table((j_common_ptr) cinfo);
  162890. jpeg_gen_optimal_table(cinfo, *htblptr, entropy->count_ptrs[tbl]);
  162891. did[tbl] = TRUE;
  162892. }
  162893. }
  162894. }
  162895. /*
  162896. * Module initialization routine for progressive Huffman entropy encoding.
  162897. */
  162898. GLOBAL(void)
  162899. jinit_phuff_encoder (j_compress_ptr cinfo)
  162900. {
  162901. phuff_entropy_ptr entropy;
  162902. int i;
  162903. entropy = (phuff_entropy_ptr)
  162904. (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_IMAGE,
  162905. SIZEOF(phuff_entropy_encoder));
  162906. cinfo->entropy = (struct jpeg_entropy_encoder *) entropy;
  162907. entropy->pub.start_pass = start_pass_phuff;
  162908. /* Mark tables unallocated */
  162909. for (i = 0; i < NUM_HUFF_TBLS; i++) {
  162910. entropy->derived_tbls[i] = NULL;
  162911. entropy->count_ptrs[i] = NULL;
  162912. }
  162913. entropy->bit_buffer = NULL; /* needed only in AC refinement scan */
  162914. }
  162915. #endif /* C_PROGRESSIVE_SUPPORTED */
  162916. /*** End of inlined file: jcphuff.c ***/
  162917. /*** Start of inlined file: jcprepct.c ***/
  162918. #define JPEG_INTERNALS
  162919. /* At present, jcsample.c can request context rows only for smoothing.
  162920. * In the future, we might also need context rows for CCIR601 sampling
  162921. * or other more-complex downsampling procedures. The code to support
  162922. * context rows should be compiled only if needed.
  162923. */
  162924. #ifdef INPUT_SMOOTHING_SUPPORTED
  162925. #define CONTEXT_ROWS_SUPPORTED
  162926. #endif
  162927. /*
  162928. * For the simple (no-context-row) case, we just need to buffer one
  162929. * row group's worth of pixels for the downsampling step. At the bottom of
  162930. * the image, we pad to a full row group by replicating the last pixel row.
  162931. * The downsampler's last output row is then replicated if needed to pad
  162932. * out to a full iMCU row.
  162933. *
  162934. * When providing context rows, we must buffer three row groups' worth of
  162935. * pixels. Three row groups are physically allocated, but the row pointer
  162936. * arrays are made five row groups high, with the extra pointers above and
  162937. * below "wrapping around" to point to the last and first real row groups.
  162938. * This allows the downsampler to access the proper context rows.
  162939. * At the top and bottom of the image, we create dummy context rows by
  162940. * copying the first or last real pixel row. This copying could be avoided
  162941. * by pointer hacking as is done in jdmainct.c, but it doesn't seem worth the
  162942. * trouble on the compression side.
  162943. */
  162944. /* Private buffer controller object */
  162945. typedef struct {
  162946. struct jpeg_c_prep_controller pub; /* public fields */
  162947. /* Downsampling input buffer. This buffer holds color-converted data
  162948. * until we have enough to do a downsample step.
  162949. */
  162950. JSAMPARRAY color_buf[MAX_COMPONENTS];
  162951. JDIMENSION rows_to_go; /* counts rows remaining in source image */
  162952. int next_buf_row; /* index of next row to store in color_buf */
  162953. #ifdef CONTEXT_ROWS_SUPPORTED /* only needed for context case */
  162954. int this_row_group; /* starting row index of group to process */
  162955. int next_buf_stop; /* downsample when we reach this index */
  162956. #endif
  162957. } my_prep_controller;
  162958. typedef my_prep_controller * my_prep_ptr;
  162959. /*
  162960. * Initialize for a processing pass.
  162961. */
  162962. METHODDEF(void)
  162963. start_pass_prep (j_compress_ptr cinfo, J_BUF_MODE pass_mode)
  162964. {
  162965. my_prep_ptr prep = (my_prep_ptr) cinfo->prep;
  162966. if (pass_mode != JBUF_PASS_THRU)
  162967. ERREXIT(cinfo, JERR_BAD_BUFFER_MODE);
  162968. /* Initialize total-height counter for detecting bottom of image */
  162969. prep->rows_to_go = cinfo->image_height;
  162970. /* Mark the conversion buffer empty */
  162971. prep->next_buf_row = 0;
  162972. #ifdef CONTEXT_ROWS_SUPPORTED
  162973. /* Preset additional state variables for context mode.
  162974. * These aren't used in non-context mode, so we needn't test which mode.
  162975. */
  162976. prep->this_row_group = 0;
  162977. /* Set next_buf_stop to stop after two row groups have been read in. */
  162978. prep->next_buf_stop = 2 * cinfo->max_v_samp_factor;
  162979. #endif
  162980. }
  162981. /*
  162982. * Expand an image vertically from height input_rows to height output_rows,
  162983. * by duplicating the bottom row.
  162984. */
  162985. LOCAL(void)
  162986. expand_bottom_edge (JSAMPARRAY image_data, JDIMENSION num_cols,
  162987. int input_rows, int output_rows)
  162988. {
  162989. register int row;
  162990. for (row = input_rows; row < output_rows; row++) {
  162991. jcopy_sample_rows(image_data, input_rows-1, image_data, row,
  162992. 1, num_cols);
  162993. }
  162994. }
  162995. /*
  162996. * Process some data in the simple no-context case.
  162997. *
  162998. * Preprocessor output data is counted in "row groups". A row group
  162999. * is defined to be v_samp_factor sample rows of each component.
  163000. * Downsampling will produce this much data from each max_v_samp_factor
  163001. * input rows.
  163002. */
  163003. METHODDEF(void)
  163004. pre_process_data (j_compress_ptr cinfo,
  163005. JSAMPARRAY input_buf, JDIMENSION *in_row_ctr,
  163006. JDIMENSION in_rows_avail,
  163007. JSAMPIMAGE output_buf, JDIMENSION *out_row_group_ctr,
  163008. JDIMENSION out_row_groups_avail)
  163009. {
  163010. my_prep_ptr prep = (my_prep_ptr) cinfo->prep;
  163011. int numrows, ci;
  163012. JDIMENSION inrows;
  163013. jpeg_component_info * compptr;
  163014. while (*in_row_ctr < in_rows_avail &&
  163015. *out_row_group_ctr < out_row_groups_avail) {
  163016. /* Do color conversion to fill the conversion buffer. */
  163017. inrows = in_rows_avail - *in_row_ctr;
  163018. numrows = cinfo->max_v_samp_factor - prep->next_buf_row;
  163019. numrows = (int) MIN((JDIMENSION) numrows, inrows);
  163020. (*cinfo->cconvert->color_convert) (cinfo, input_buf + *in_row_ctr,
  163021. prep->color_buf,
  163022. (JDIMENSION) prep->next_buf_row,
  163023. numrows);
  163024. *in_row_ctr += numrows;
  163025. prep->next_buf_row += numrows;
  163026. prep->rows_to_go -= numrows;
  163027. /* If at bottom of image, pad to fill the conversion buffer. */
  163028. if (prep->rows_to_go == 0 &&
  163029. prep->next_buf_row < cinfo->max_v_samp_factor) {
  163030. for (ci = 0; ci < cinfo->num_components; ci++) {
  163031. expand_bottom_edge(prep->color_buf[ci], cinfo->image_width,
  163032. prep->next_buf_row, cinfo->max_v_samp_factor);
  163033. }
  163034. prep->next_buf_row = cinfo->max_v_samp_factor;
  163035. }
  163036. /* If we've filled the conversion buffer, empty it. */
  163037. if (prep->next_buf_row == cinfo->max_v_samp_factor) {
  163038. (*cinfo->downsample->downsample) (cinfo,
  163039. prep->color_buf, (JDIMENSION) 0,
  163040. output_buf, *out_row_group_ctr);
  163041. prep->next_buf_row = 0;
  163042. (*out_row_group_ctr)++;
  163043. }
  163044. /* If at bottom of image, pad the output to a full iMCU height.
  163045. * Note we assume the caller is providing a one-iMCU-height output buffer!
  163046. */
  163047. if (prep->rows_to_go == 0 &&
  163048. *out_row_group_ctr < out_row_groups_avail) {
  163049. for (ci = 0, compptr = cinfo->comp_info; ci < cinfo->num_components;
  163050. ci++, compptr++) {
  163051. expand_bottom_edge(output_buf[ci],
  163052. compptr->width_in_blocks * DCTSIZE,
  163053. (int) (*out_row_group_ctr * compptr->v_samp_factor),
  163054. (int) (out_row_groups_avail * compptr->v_samp_factor));
  163055. }
  163056. *out_row_group_ctr = out_row_groups_avail;
  163057. break; /* can exit outer loop without test */
  163058. }
  163059. }
  163060. }
  163061. #ifdef CONTEXT_ROWS_SUPPORTED
  163062. /*
  163063. * Process some data in the context case.
  163064. */
  163065. METHODDEF(void)
  163066. pre_process_context (j_compress_ptr cinfo,
  163067. JSAMPARRAY input_buf, JDIMENSION *in_row_ctr,
  163068. JDIMENSION in_rows_avail,
  163069. JSAMPIMAGE output_buf, JDIMENSION *out_row_group_ctr,
  163070. JDIMENSION out_row_groups_avail)
  163071. {
  163072. my_prep_ptr prep = (my_prep_ptr) cinfo->prep;
  163073. int numrows, ci;
  163074. int buf_height = cinfo->max_v_samp_factor * 3;
  163075. JDIMENSION inrows;
  163076. while (*out_row_group_ctr < out_row_groups_avail) {
  163077. if (*in_row_ctr < in_rows_avail) {
  163078. /* Do color conversion to fill the conversion buffer. */
  163079. inrows = in_rows_avail - *in_row_ctr;
  163080. numrows = prep->next_buf_stop - prep->next_buf_row;
  163081. numrows = (int) MIN((JDIMENSION) numrows, inrows);
  163082. (*cinfo->cconvert->color_convert) (cinfo, input_buf + *in_row_ctr,
  163083. prep->color_buf,
  163084. (JDIMENSION) prep->next_buf_row,
  163085. numrows);
  163086. /* Pad at top of image, if first time through */
  163087. if (prep->rows_to_go == cinfo->image_height) {
  163088. for (ci = 0; ci < cinfo->num_components; ci++) {
  163089. int row;
  163090. for (row = 1; row <= cinfo->max_v_samp_factor; row++) {
  163091. jcopy_sample_rows(prep->color_buf[ci], 0,
  163092. prep->color_buf[ci], -row,
  163093. 1, cinfo->image_width);
  163094. }
  163095. }
  163096. }
  163097. *in_row_ctr += numrows;
  163098. prep->next_buf_row += numrows;
  163099. prep->rows_to_go -= numrows;
  163100. } else {
  163101. /* Return for more data, unless we are at the bottom of the image. */
  163102. if (prep->rows_to_go != 0)
  163103. break;
  163104. /* When at bottom of image, pad to fill the conversion buffer. */
  163105. if (prep->next_buf_row < prep->next_buf_stop) {
  163106. for (ci = 0; ci < cinfo->num_components; ci++) {
  163107. expand_bottom_edge(prep->color_buf[ci], cinfo->image_width,
  163108. prep->next_buf_row, prep->next_buf_stop);
  163109. }
  163110. prep->next_buf_row = prep->next_buf_stop;
  163111. }
  163112. }
  163113. /* If we've gotten enough data, downsample a row group. */
  163114. if (prep->next_buf_row == prep->next_buf_stop) {
  163115. (*cinfo->downsample->downsample) (cinfo,
  163116. prep->color_buf,
  163117. (JDIMENSION) prep->this_row_group,
  163118. output_buf, *out_row_group_ctr);
  163119. (*out_row_group_ctr)++;
  163120. /* Advance pointers with wraparound as necessary. */
  163121. prep->this_row_group += cinfo->max_v_samp_factor;
  163122. if (prep->this_row_group >= buf_height)
  163123. prep->this_row_group = 0;
  163124. if (prep->next_buf_row >= buf_height)
  163125. prep->next_buf_row = 0;
  163126. prep->next_buf_stop = prep->next_buf_row + cinfo->max_v_samp_factor;
  163127. }
  163128. }
  163129. }
  163130. /*
  163131. * Create the wrapped-around downsampling input buffer needed for context mode.
  163132. */
  163133. LOCAL(void)
  163134. create_context_buffer (j_compress_ptr cinfo)
  163135. {
  163136. my_prep_ptr prep = (my_prep_ptr) cinfo->prep;
  163137. int rgroup_height = cinfo->max_v_samp_factor;
  163138. int ci, i;
  163139. jpeg_component_info * compptr;
  163140. JSAMPARRAY true_buffer, fake_buffer;
  163141. /* Grab enough space for fake row pointers for all the components;
  163142. * we need five row groups' worth of pointers for each component.
  163143. */
  163144. fake_buffer = (JSAMPARRAY)
  163145. (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_IMAGE,
  163146. (cinfo->num_components * 5 * rgroup_height) *
  163147. SIZEOF(JSAMPROW));
  163148. for (ci = 0, compptr = cinfo->comp_info; ci < cinfo->num_components;
  163149. ci++, compptr++) {
  163150. /* Allocate the actual buffer space (3 row groups) for this component.
  163151. * We make the buffer wide enough to allow the downsampler to edge-expand
  163152. * horizontally within the buffer, if it so chooses.
  163153. */
  163154. true_buffer = (*cinfo->mem->alloc_sarray)
  163155. ((j_common_ptr) cinfo, JPOOL_IMAGE,
  163156. (JDIMENSION) (((long) compptr->width_in_blocks * DCTSIZE *
  163157. cinfo->max_h_samp_factor) / compptr->h_samp_factor),
  163158. (JDIMENSION) (3 * rgroup_height));
  163159. /* Copy true buffer row pointers into the middle of the fake row array */
  163160. MEMCOPY(fake_buffer + rgroup_height, true_buffer,
  163161. 3 * rgroup_height * SIZEOF(JSAMPROW));
  163162. /* Fill in the above and below wraparound pointers */
  163163. for (i = 0; i < rgroup_height; i++) {
  163164. fake_buffer[i] = true_buffer[2 * rgroup_height + i];
  163165. fake_buffer[4 * rgroup_height + i] = true_buffer[i];
  163166. }
  163167. prep->color_buf[ci] = fake_buffer + rgroup_height;
  163168. fake_buffer += 5 * rgroup_height; /* point to space for next component */
  163169. }
  163170. }
  163171. #endif /* CONTEXT_ROWS_SUPPORTED */
  163172. /*
  163173. * Initialize preprocessing controller.
  163174. */
  163175. GLOBAL(void)
  163176. jinit_c_prep_controller (j_compress_ptr cinfo, boolean need_full_buffer)
  163177. {
  163178. my_prep_ptr prep;
  163179. int ci;
  163180. jpeg_component_info * compptr;
  163181. if (need_full_buffer) /* safety check */
  163182. ERREXIT(cinfo, JERR_BAD_BUFFER_MODE);
  163183. prep = (my_prep_ptr)
  163184. (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_IMAGE,
  163185. SIZEOF(my_prep_controller));
  163186. cinfo->prep = (struct jpeg_c_prep_controller *) prep;
  163187. prep->pub.start_pass = start_pass_prep;
  163188. /* Allocate the color conversion buffer.
  163189. * We make the buffer wide enough to allow the downsampler to edge-expand
  163190. * horizontally within the buffer, if it so chooses.
  163191. */
  163192. if (cinfo->downsample->need_context_rows) {
  163193. /* Set up to provide context rows */
  163194. #ifdef CONTEXT_ROWS_SUPPORTED
  163195. prep->pub.pre_process_data = pre_process_context;
  163196. create_context_buffer(cinfo);
  163197. #else
  163198. ERREXIT(cinfo, JERR_NOT_COMPILED);
  163199. #endif
  163200. } else {
  163201. /* No context, just make it tall enough for one row group */
  163202. prep->pub.pre_process_data = pre_process_data;
  163203. for (ci = 0, compptr = cinfo->comp_info; ci < cinfo->num_components;
  163204. ci++, compptr++) {
  163205. prep->color_buf[ci] = (*cinfo->mem->alloc_sarray)
  163206. ((j_common_ptr) cinfo, JPOOL_IMAGE,
  163207. (JDIMENSION) (((long) compptr->width_in_blocks * DCTSIZE *
  163208. cinfo->max_h_samp_factor) / compptr->h_samp_factor),
  163209. (JDIMENSION) cinfo->max_v_samp_factor);
  163210. }
  163211. }
  163212. }
  163213. /*** End of inlined file: jcprepct.c ***/
  163214. /*** Start of inlined file: jcsample.c ***/
  163215. #define JPEG_INTERNALS
  163216. /* Pointer to routine to downsample a single component */
  163217. typedef JMETHOD(void, downsample1_ptr,
  163218. (j_compress_ptr cinfo, jpeg_component_info * compptr,
  163219. JSAMPARRAY input_data, JSAMPARRAY output_data));
  163220. /* Private subobject */
  163221. typedef struct {
  163222. struct jpeg_downsampler pub; /* public fields */
  163223. /* Downsampling method pointers, one per component */
  163224. downsample1_ptr methods[MAX_COMPONENTS];
  163225. } my_downsampler;
  163226. typedef my_downsampler * my_downsample_ptr;
  163227. /*
  163228. * Initialize for a downsampling pass.
  163229. */
  163230. METHODDEF(void)
  163231. start_pass_downsample (j_compress_ptr cinfo)
  163232. {
  163233. /* no work for now */
  163234. }
  163235. /*
  163236. * Expand a component horizontally from width input_cols to width output_cols,
  163237. * by duplicating the rightmost samples.
  163238. */
  163239. LOCAL(void)
  163240. expand_right_edge (JSAMPARRAY image_data, int num_rows,
  163241. JDIMENSION input_cols, JDIMENSION output_cols)
  163242. {
  163243. register JSAMPROW ptr;
  163244. register JSAMPLE pixval;
  163245. register int count;
  163246. int row;
  163247. int numcols = (int) (output_cols - input_cols);
  163248. if (numcols > 0) {
  163249. for (row = 0; row < num_rows; row++) {
  163250. ptr = image_data[row] + input_cols;
  163251. pixval = ptr[-1]; /* don't need GETJSAMPLE() here */
  163252. for (count = numcols; count > 0; count--)
  163253. *ptr++ = pixval;
  163254. }
  163255. }
  163256. }
  163257. /*
  163258. * Do downsampling for a whole row group (all components).
  163259. *
  163260. * In this version we simply downsample each component independently.
  163261. */
  163262. METHODDEF(void)
  163263. sep_downsample (j_compress_ptr cinfo,
  163264. JSAMPIMAGE input_buf, JDIMENSION in_row_index,
  163265. JSAMPIMAGE output_buf, JDIMENSION out_row_group_index)
  163266. {
  163267. my_downsample_ptr downsample = (my_downsample_ptr) cinfo->downsample;
  163268. int ci;
  163269. jpeg_component_info * compptr;
  163270. JSAMPARRAY in_ptr, out_ptr;
  163271. for (ci = 0, compptr = cinfo->comp_info; ci < cinfo->num_components;
  163272. ci++, compptr++) {
  163273. in_ptr = input_buf[ci] + in_row_index;
  163274. out_ptr = output_buf[ci] + (out_row_group_index * compptr->v_samp_factor);
  163275. (*downsample->methods[ci]) (cinfo, compptr, in_ptr, out_ptr);
  163276. }
  163277. }
  163278. /*
  163279. * Downsample pixel values of a single component.
  163280. * One row group is processed per call.
  163281. * This version handles arbitrary integral sampling ratios, without smoothing.
  163282. * Note that this version is not actually used for customary sampling ratios.
  163283. */
  163284. METHODDEF(void)
  163285. int_downsample (j_compress_ptr cinfo, jpeg_component_info * compptr,
  163286. JSAMPARRAY input_data, JSAMPARRAY output_data)
  163287. {
  163288. int inrow, outrow, h_expand, v_expand, numpix, numpix2, h, v;
  163289. JDIMENSION outcol, outcol_h; /* outcol_h == outcol*h_expand */
  163290. JDIMENSION output_cols = compptr->width_in_blocks * DCTSIZE;
  163291. JSAMPROW inptr, outptr;
  163292. INT32 outvalue;
  163293. h_expand = cinfo->max_h_samp_factor / compptr->h_samp_factor;
  163294. v_expand = cinfo->max_v_samp_factor / compptr->v_samp_factor;
  163295. numpix = h_expand * v_expand;
  163296. numpix2 = numpix/2;
  163297. /* Expand input data enough to let all the output samples be generated
  163298. * by the standard loop. Special-casing padded output would be more
  163299. * efficient.
  163300. */
  163301. expand_right_edge(input_data, cinfo->max_v_samp_factor,
  163302. cinfo->image_width, output_cols * h_expand);
  163303. inrow = 0;
  163304. for (outrow = 0; outrow < compptr->v_samp_factor; outrow++) {
  163305. outptr = output_data[outrow];
  163306. for (outcol = 0, outcol_h = 0; outcol < output_cols;
  163307. outcol++, outcol_h += h_expand) {
  163308. outvalue = 0;
  163309. for (v = 0; v < v_expand; v++) {
  163310. inptr = input_data[inrow+v] + outcol_h;
  163311. for (h = 0; h < h_expand; h++) {
  163312. outvalue += (INT32) GETJSAMPLE(*inptr++);
  163313. }
  163314. }
  163315. *outptr++ = (JSAMPLE) ((outvalue + numpix2) / numpix);
  163316. }
  163317. inrow += v_expand;
  163318. }
  163319. }
  163320. /*
  163321. * Downsample pixel values of a single component.
  163322. * This version handles the special case of a full-size component,
  163323. * without smoothing.
  163324. */
  163325. METHODDEF(void)
  163326. fullsize_downsample (j_compress_ptr cinfo, jpeg_component_info * compptr,
  163327. JSAMPARRAY input_data, JSAMPARRAY output_data)
  163328. {
  163329. /* Copy the data */
  163330. jcopy_sample_rows(input_data, 0, output_data, 0,
  163331. cinfo->max_v_samp_factor, cinfo->image_width);
  163332. /* Edge-expand */
  163333. expand_right_edge(output_data, cinfo->max_v_samp_factor,
  163334. cinfo->image_width, compptr->width_in_blocks * DCTSIZE);
  163335. }
  163336. /*
  163337. * Downsample pixel values of a single component.
  163338. * This version handles the common case of 2:1 horizontal and 1:1 vertical,
  163339. * without smoothing.
  163340. *
  163341. * A note about the "bias" calculations: when rounding fractional values to
  163342. * integer, we do not want to always round 0.5 up to the next integer.
  163343. * If we did that, we'd introduce a noticeable bias towards larger values.
  163344. * Instead, this code is arranged so that 0.5 will be rounded up or down at
  163345. * alternate pixel locations (a simple ordered dither pattern).
  163346. */
  163347. METHODDEF(void)
  163348. h2v1_downsample (j_compress_ptr cinfo, jpeg_component_info * compptr,
  163349. JSAMPARRAY input_data, JSAMPARRAY output_data)
  163350. {
  163351. int outrow;
  163352. JDIMENSION outcol;
  163353. JDIMENSION output_cols = compptr->width_in_blocks * DCTSIZE;
  163354. register JSAMPROW inptr, outptr;
  163355. register int bias;
  163356. /* Expand input data enough to let all the output samples be generated
  163357. * by the standard loop. Special-casing padded output would be more
  163358. * efficient.
  163359. */
  163360. expand_right_edge(input_data, cinfo->max_v_samp_factor,
  163361. cinfo->image_width, output_cols * 2);
  163362. for (outrow = 0; outrow < compptr->v_samp_factor; outrow++) {
  163363. outptr = output_data[outrow];
  163364. inptr = input_data[outrow];
  163365. bias = 0; /* bias = 0,1,0,1,... for successive samples */
  163366. for (outcol = 0; outcol < output_cols; outcol++) {
  163367. *outptr++ = (JSAMPLE) ((GETJSAMPLE(*inptr) + GETJSAMPLE(inptr[1])
  163368. + bias) >> 1);
  163369. bias ^= 1; /* 0=>1, 1=>0 */
  163370. inptr += 2;
  163371. }
  163372. }
  163373. }
  163374. /*
  163375. * Downsample pixel values of a single component.
  163376. * This version handles the standard case of 2:1 horizontal and 2:1 vertical,
  163377. * without smoothing.
  163378. */
  163379. METHODDEF(void)
  163380. h2v2_downsample (j_compress_ptr cinfo, jpeg_component_info * compptr,
  163381. JSAMPARRAY input_data, JSAMPARRAY output_data)
  163382. {
  163383. int inrow, outrow;
  163384. JDIMENSION outcol;
  163385. JDIMENSION output_cols = compptr->width_in_blocks * DCTSIZE;
  163386. register JSAMPROW inptr0, inptr1, outptr;
  163387. register int bias;
  163388. /* Expand input data enough to let all the output samples be generated
  163389. * by the standard loop. Special-casing padded output would be more
  163390. * efficient.
  163391. */
  163392. expand_right_edge(input_data, cinfo->max_v_samp_factor,
  163393. cinfo->image_width, output_cols * 2);
  163394. inrow = 0;
  163395. for (outrow = 0; outrow < compptr->v_samp_factor; outrow++) {
  163396. outptr = output_data[outrow];
  163397. inptr0 = input_data[inrow];
  163398. inptr1 = input_data[inrow+1];
  163399. bias = 1; /* bias = 1,2,1,2,... for successive samples */
  163400. for (outcol = 0; outcol < output_cols; outcol++) {
  163401. *outptr++ = (JSAMPLE) ((GETJSAMPLE(*inptr0) + GETJSAMPLE(inptr0[1]) +
  163402. GETJSAMPLE(*inptr1) + GETJSAMPLE(inptr1[1])
  163403. + bias) >> 2);
  163404. bias ^= 3; /* 1=>2, 2=>1 */
  163405. inptr0 += 2; inptr1 += 2;
  163406. }
  163407. inrow += 2;
  163408. }
  163409. }
  163410. #ifdef INPUT_SMOOTHING_SUPPORTED
  163411. /*
  163412. * Downsample pixel values of a single component.
  163413. * This version handles the standard case of 2:1 horizontal and 2:1 vertical,
  163414. * with smoothing. One row of context is required.
  163415. */
  163416. METHODDEF(void)
  163417. h2v2_smooth_downsample (j_compress_ptr cinfo, jpeg_component_info * compptr,
  163418. JSAMPARRAY input_data, JSAMPARRAY output_data)
  163419. {
  163420. int inrow, outrow;
  163421. JDIMENSION colctr;
  163422. JDIMENSION output_cols = compptr->width_in_blocks * DCTSIZE;
  163423. register JSAMPROW inptr0, inptr1, above_ptr, below_ptr, outptr;
  163424. INT32 membersum, neighsum, memberscale, neighscale;
  163425. /* Expand input data enough to let all the output samples be generated
  163426. * by the standard loop. Special-casing padded output would be more
  163427. * efficient.
  163428. */
  163429. expand_right_edge(input_data - 1, cinfo->max_v_samp_factor + 2,
  163430. cinfo->image_width, output_cols * 2);
  163431. /* We don't bother to form the individual "smoothed" input pixel values;
  163432. * we can directly compute the output which is the average of the four
  163433. * smoothed values. Each of the four member pixels contributes a fraction
  163434. * (1-8*SF) to its own smoothed image and a fraction SF to each of the three
  163435. * other smoothed pixels, therefore a total fraction (1-5*SF)/4 to the final
  163436. * output. The four corner-adjacent neighbor pixels contribute a fraction
  163437. * SF to just one smoothed pixel, or SF/4 to the final output; while the
  163438. * eight edge-adjacent neighbors contribute SF to each of two smoothed
  163439. * pixels, or SF/2 overall. In order to use integer arithmetic, these
  163440. * factors are scaled by 2^16 = 65536.
  163441. * Also recall that SF = smoothing_factor / 1024.
  163442. */
  163443. memberscale = 16384 - cinfo->smoothing_factor * 80; /* scaled (1-5*SF)/4 */
  163444. neighscale = cinfo->smoothing_factor * 16; /* scaled SF/4 */
  163445. inrow = 0;
  163446. for (outrow = 0; outrow < compptr->v_samp_factor; outrow++) {
  163447. outptr = output_data[outrow];
  163448. inptr0 = input_data[inrow];
  163449. inptr1 = input_data[inrow+1];
  163450. above_ptr = input_data[inrow-1];
  163451. below_ptr = input_data[inrow+2];
  163452. /* Special case for first column: pretend column -1 is same as column 0 */
  163453. membersum = GETJSAMPLE(*inptr0) + GETJSAMPLE(inptr0[1]) +
  163454. GETJSAMPLE(*inptr1) + GETJSAMPLE(inptr1[1]);
  163455. neighsum = GETJSAMPLE(*above_ptr) + GETJSAMPLE(above_ptr[1]) +
  163456. GETJSAMPLE(*below_ptr) + GETJSAMPLE(below_ptr[1]) +
  163457. GETJSAMPLE(*inptr0) + GETJSAMPLE(inptr0[2]) +
  163458. GETJSAMPLE(*inptr1) + GETJSAMPLE(inptr1[2]);
  163459. neighsum += neighsum;
  163460. neighsum += GETJSAMPLE(*above_ptr) + GETJSAMPLE(above_ptr[2]) +
  163461. GETJSAMPLE(*below_ptr) + GETJSAMPLE(below_ptr[2]);
  163462. membersum = membersum * memberscale + neighsum * neighscale;
  163463. *outptr++ = (JSAMPLE) ((membersum + 32768) >> 16);
  163464. inptr0 += 2; inptr1 += 2; above_ptr += 2; below_ptr += 2;
  163465. for (colctr = output_cols - 2; colctr > 0; colctr--) {
  163466. /* sum of pixels directly mapped to this output element */
  163467. membersum = GETJSAMPLE(*inptr0) + GETJSAMPLE(inptr0[1]) +
  163468. GETJSAMPLE(*inptr1) + GETJSAMPLE(inptr1[1]);
  163469. /* sum of edge-neighbor pixels */
  163470. neighsum = GETJSAMPLE(*above_ptr) + GETJSAMPLE(above_ptr[1]) +
  163471. GETJSAMPLE(*below_ptr) + GETJSAMPLE(below_ptr[1]) +
  163472. GETJSAMPLE(inptr0[-1]) + GETJSAMPLE(inptr0[2]) +
  163473. GETJSAMPLE(inptr1[-1]) + GETJSAMPLE(inptr1[2]);
  163474. /* The edge-neighbors count twice as much as corner-neighbors */
  163475. neighsum += neighsum;
  163476. /* Add in the corner-neighbors */
  163477. neighsum += GETJSAMPLE(above_ptr[-1]) + GETJSAMPLE(above_ptr[2]) +
  163478. GETJSAMPLE(below_ptr[-1]) + GETJSAMPLE(below_ptr[2]);
  163479. /* form final output scaled up by 2^16 */
  163480. membersum = membersum * memberscale + neighsum * neighscale;
  163481. /* round, descale and output it */
  163482. *outptr++ = (JSAMPLE) ((membersum + 32768) >> 16);
  163483. inptr0 += 2; inptr1 += 2; above_ptr += 2; below_ptr += 2;
  163484. }
  163485. /* Special case for last column */
  163486. membersum = GETJSAMPLE(*inptr0) + GETJSAMPLE(inptr0[1]) +
  163487. GETJSAMPLE(*inptr1) + GETJSAMPLE(inptr1[1]);
  163488. neighsum = GETJSAMPLE(*above_ptr) + GETJSAMPLE(above_ptr[1]) +
  163489. GETJSAMPLE(*below_ptr) + GETJSAMPLE(below_ptr[1]) +
  163490. GETJSAMPLE(inptr0[-1]) + GETJSAMPLE(inptr0[1]) +
  163491. GETJSAMPLE(inptr1[-1]) + GETJSAMPLE(inptr1[1]);
  163492. neighsum += neighsum;
  163493. neighsum += GETJSAMPLE(above_ptr[-1]) + GETJSAMPLE(above_ptr[1]) +
  163494. GETJSAMPLE(below_ptr[-1]) + GETJSAMPLE(below_ptr[1]);
  163495. membersum = membersum * memberscale + neighsum * neighscale;
  163496. *outptr = (JSAMPLE) ((membersum + 32768) >> 16);
  163497. inrow += 2;
  163498. }
  163499. }
  163500. /*
  163501. * Downsample pixel values of a single component.
  163502. * This version handles the special case of a full-size component,
  163503. * with smoothing. One row of context is required.
  163504. */
  163505. METHODDEF(void)
  163506. fullsize_smooth_downsample (j_compress_ptr cinfo, jpeg_component_info *compptr,
  163507. JSAMPARRAY input_data, JSAMPARRAY output_data)
  163508. {
  163509. int outrow;
  163510. JDIMENSION colctr;
  163511. JDIMENSION output_cols = compptr->width_in_blocks * DCTSIZE;
  163512. register JSAMPROW inptr, above_ptr, below_ptr, outptr;
  163513. INT32 membersum, neighsum, memberscale, neighscale;
  163514. int colsum, lastcolsum, nextcolsum;
  163515. /* Expand input data enough to let all the output samples be generated
  163516. * by the standard loop. Special-casing padded output would be more
  163517. * efficient.
  163518. */
  163519. expand_right_edge(input_data - 1, cinfo->max_v_samp_factor + 2,
  163520. cinfo->image_width, output_cols);
  163521. /* Each of the eight neighbor pixels contributes a fraction SF to the
  163522. * smoothed pixel, while the main pixel contributes (1-8*SF). In order
  163523. * to use integer arithmetic, these factors are multiplied by 2^16 = 65536.
  163524. * Also recall that SF = smoothing_factor / 1024.
  163525. */
  163526. memberscale = 65536L - cinfo->smoothing_factor * 512L; /* scaled 1-8*SF */
  163527. neighscale = cinfo->smoothing_factor * 64; /* scaled SF */
  163528. for (outrow = 0; outrow < compptr->v_samp_factor; outrow++) {
  163529. outptr = output_data[outrow];
  163530. inptr = input_data[outrow];
  163531. above_ptr = input_data[outrow-1];
  163532. below_ptr = input_data[outrow+1];
  163533. /* Special case for first column */
  163534. colsum = GETJSAMPLE(*above_ptr++) + GETJSAMPLE(*below_ptr++) +
  163535. GETJSAMPLE(*inptr);
  163536. membersum = GETJSAMPLE(*inptr++);
  163537. nextcolsum = GETJSAMPLE(*above_ptr) + GETJSAMPLE(*below_ptr) +
  163538. GETJSAMPLE(*inptr);
  163539. neighsum = colsum + (colsum - membersum) + nextcolsum;
  163540. membersum = membersum * memberscale + neighsum * neighscale;
  163541. *outptr++ = (JSAMPLE) ((membersum + 32768) >> 16);
  163542. lastcolsum = colsum; colsum = nextcolsum;
  163543. for (colctr = output_cols - 2; colctr > 0; colctr--) {
  163544. membersum = GETJSAMPLE(*inptr++);
  163545. above_ptr++; below_ptr++;
  163546. nextcolsum = GETJSAMPLE(*above_ptr) + GETJSAMPLE(*below_ptr) +
  163547. GETJSAMPLE(*inptr);
  163548. neighsum = lastcolsum + (colsum - membersum) + nextcolsum;
  163549. membersum = membersum * memberscale + neighsum * neighscale;
  163550. *outptr++ = (JSAMPLE) ((membersum + 32768) >> 16);
  163551. lastcolsum = colsum; colsum = nextcolsum;
  163552. }
  163553. /* Special case for last column */
  163554. membersum = GETJSAMPLE(*inptr);
  163555. neighsum = lastcolsum + (colsum - membersum) + colsum;
  163556. membersum = membersum * memberscale + neighsum * neighscale;
  163557. *outptr = (JSAMPLE) ((membersum + 32768) >> 16);
  163558. }
  163559. }
  163560. #endif /* INPUT_SMOOTHING_SUPPORTED */
  163561. /*
  163562. * Module initialization routine for downsampling.
  163563. * Note that we must select a routine for each component.
  163564. */
  163565. GLOBAL(void)
  163566. jinit_downsampler (j_compress_ptr cinfo)
  163567. {
  163568. my_downsample_ptr downsample;
  163569. int ci;
  163570. jpeg_component_info * compptr;
  163571. boolean smoothok = TRUE;
  163572. downsample = (my_downsample_ptr)
  163573. (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_IMAGE,
  163574. SIZEOF(my_downsampler));
  163575. cinfo->downsample = (struct jpeg_downsampler *) downsample;
  163576. downsample->pub.start_pass = start_pass_downsample;
  163577. downsample->pub.downsample = sep_downsample;
  163578. downsample->pub.need_context_rows = FALSE;
  163579. if (cinfo->CCIR601_sampling)
  163580. ERREXIT(cinfo, JERR_CCIR601_NOTIMPL);
  163581. /* Verify we can handle the sampling factors, and set up method pointers */
  163582. for (ci = 0, compptr = cinfo->comp_info; ci < cinfo->num_components;
  163583. ci++, compptr++) {
  163584. if (compptr->h_samp_factor == cinfo->max_h_samp_factor &&
  163585. compptr->v_samp_factor == cinfo->max_v_samp_factor) {
  163586. #ifdef INPUT_SMOOTHING_SUPPORTED
  163587. if (cinfo->smoothing_factor) {
  163588. downsample->methods[ci] = fullsize_smooth_downsample;
  163589. downsample->pub.need_context_rows = TRUE;
  163590. } else
  163591. #endif
  163592. downsample->methods[ci] = fullsize_downsample;
  163593. } else if (compptr->h_samp_factor * 2 == cinfo->max_h_samp_factor &&
  163594. compptr->v_samp_factor == cinfo->max_v_samp_factor) {
  163595. smoothok = FALSE;
  163596. downsample->methods[ci] = h2v1_downsample;
  163597. } else if (compptr->h_samp_factor * 2 == cinfo->max_h_samp_factor &&
  163598. compptr->v_samp_factor * 2 == cinfo->max_v_samp_factor) {
  163599. #ifdef INPUT_SMOOTHING_SUPPORTED
  163600. if (cinfo->smoothing_factor) {
  163601. downsample->methods[ci] = h2v2_smooth_downsample;
  163602. downsample->pub.need_context_rows = TRUE;
  163603. } else
  163604. #endif
  163605. downsample->methods[ci] = h2v2_downsample;
  163606. } else if ((cinfo->max_h_samp_factor % compptr->h_samp_factor) == 0 &&
  163607. (cinfo->max_v_samp_factor % compptr->v_samp_factor) == 0) {
  163608. smoothok = FALSE;
  163609. downsample->methods[ci] = int_downsample;
  163610. } else
  163611. ERREXIT(cinfo, JERR_FRACT_SAMPLE_NOTIMPL);
  163612. }
  163613. #ifdef INPUT_SMOOTHING_SUPPORTED
  163614. if (cinfo->smoothing_factor && !smoothok)
  163615. TRACEMS(cinfo, 0, JTRC_SMOOTH_NOTIMPL);
  163616. #endif
  163617. }
  163618. /*** End of inlined file: jcsample.c ***/
  163619. /*** Start of inlined file: jctrans.c ***/
  163620. #define JPEG_INTERNALS
  163621. /* Forward declarations */
  163622. LOCAL(void) transencode_master_selection
  163623. JPP((j_compress_ptr cinfo, jvirt_barray_ptr * coef_arrays));
  163624. LOCAL(void) transencode_coef_controller
  163625. JPP((j_compress_ptr cinfo, jvirt_barray_ptr * coef_arrays));
  163626. /*
  163627. * Compression initialization for writing raw-coefficient data.
  163628. * Before calling this, all parameters and a data destination must be set up.
  163629. * Call jpeg_finish_compress() to actually write the data.
  163630. *
  163631. * The number of passed virtual arrays must match cinfo->num_components.
  163632. * Note that the virtual arrays need not be filled or even realized at
  163633. * the time write_coefficients is called; indeed, if the virtual arrays
  163634. * were requested from this compression object's memory manager, they
  163635. * typically will be realized during this routine and filled afterwards.
  163636. */
  163637. GLOBAL(void)
  163638. jpeg_write_coefficients (j_compress_ptr cinfo, jvirt_barray_ptr * coef_arrays)
  163639. {
  163640. if (cinfo->global_state != CSTATE_START)
  163641. ERREXIT1(cinfo, JERR_BAD_STATE, cinfo->global_state);
  163642. /* Mark all tables to be written */
  163643. jpeg_suppress_tables(cinfo, FALSE);
  163644. /* (Re)initialize error mgr and destination modules */
  163645. (*cinfo->err->reset_error_mgr) ((j_common_ptr) cinfo);
  163646. (*cinfo->dest->init_destination) (cinfo);
  163647. /* Perform master selection of active modules */
  163648. transencode_master_selection(cinfo, coef_arrays);
  163649. /* Wait for jpeg_finish_compress() call */
  163650. cinfo->next_scanline = 0; /* so jpeg_write_marker works */
  163651. cinfo->global_state = CSTATE_WRCOEFS;
  163652. }
  163653. /*
  163654. * Initialize the compression object with default parameters,
  163655. * then copy from the source object all parameters needed for lossless
  163656. * transcoding. Parameters that can be varied without loss (such as
  163657. * scan script and Huffman optimization) are left in their default states.
  163658. */
  163659. GLOBAL(void)
  163660. jpeg_copy_critical_parameters (j_decompress_ptr srcinfo,
  163661. j_compress_ptr dstinfo)
  163662. {
  163663. JQUANT_TBL ** qtblptr;
  163664. jpeg_component_info *incomp, *outcomp;
  163665. JQUANT_TBL *c_quant, *slot_quant;
  163666. int tblno, ci, coefi;
  163667. /* Safety check to ensure start_compress not called yet. */
  163668. if (dstinfo->global_state != CSTATE_START)
  163669. ERREXIT1(dstinfo, JERR_BAD_STATE, dstinfo->global_state);
  163670. /* Copy fundamental image dimensions */
  163671. dstinfo->image_width = srcinfo->image_width;
  163672. dstinfo->image_height = srcinfo->image_height;
  163673. dstinfo->input_components = srcinfo->num_components;
  163674. dstinfo->in_color_space = srcinfo->jpeg_color_space;
  163675. /* Initialize all parameters to default values */
  163676. jpeg_set_defaults(dstinfo);
  163677. /* jpeg_set_defaults may choose wrong colorspace, eg YCbCr if input is RGB.
  163678. * Fix it to get the right header markers for the image colorspace.
  163679. */
  163680. jpeg_set_colorspace(dstinfo, srcinfo->jpeg_color_space);
  163681. dstinfo->data_precision = srcinfo->data_precision;
  163682. dstinfo->CCIR601_sampling = srcinfo->CCIR601_sampling;
  163683. /* Copy the source's quantization tables. */
  163684. for (tblno = 0; tblno < NUM_QUANT_TBLS; tblno++) {
  163685. if (srcinfo->quant_tbl_ptrs[tblno] != NULL) {
  163686. qtblptr = & dstinfo->quant_tbl_ptrs[tblno];
  163687. if (*qtblptr == NULL)
  163688. *qtblptr = jpeg_alloc_quant_table((j_common_ptr) dstinfo);
  163689. MEMCOPY((*qtblptr)->quantval,
  163690. srcinfo->quant_tbl_ptrs[tblno]->quantval,
  163691. SIZEOF((*qtblptr)->quantval));
  163692. (*qtblptr)->sent_table = FALSE;
  163693. }
  163694. }
  163695. /* Copy the source's per-component info.
  163696. * Note we assume jpeg_set_defaults has allocated the dest comp_info array.
  163697. */
  163698. dstinfo->num_components = srcinfo->num_components;
  163699. if (dstinfo->num_components < 1 || dstinfo->num_components > MAX_COMPONENTS)
  163700. ERREXIT2(dstinfo, JERR_COMPONENT_COUNT, dstinfo->num_components,
  163701. MAX_COMPONENTS);
  163702. for (ci = 0, incomp = srcinfo->comp_info, outcomp = dstinfo->comp_info;
  163703. ci < dstinfo->num_components; ci++, incomp++, outcomp++) {
  163704. outcomp->component_id = incomp->component_id;
  163705. outcomp->h_samp_factor = incomp->h_samp_factor;
  163706. outcomp->v_samp_factor = incomp->v_samp_factor;
  163707. outcomp->quant_tbl_no = incomp->quant_tbl_no;
  163708. /* Make sure saved quantization table for component matches the qtable
  163709. * slot. If not, the input file re-used this qtable slot.
  163710. * IJG encoder currently cannot duplicate this.
  163711. */
  163712. tblno = outcomp->quant_tbl_no;
  163713. if (tblno < 0 || tblno >= NUM_QUANT_TBLS ||
  163714. srcinfo->quant_tbl_ptrs[tblno] == NULL)
  163715. ERREXIT1(dstinfo, JERR_NO_QUANT_TABLE, tblno);
  163716. slot_quant = srcinfo->quant_tbl_ptrs[tblno];
  163717. c_quant = incomp->quant_table;
  163718. if (c_quant != NULL) {
  163719. for (coefi = 0; coefi < DCTSIZE2; coefi++) {
  163720. if (c_quant->quantval[coefi] != slot_quant->quantval[coefi])
  163721. ERREXIT1(dstinfo, JERR_MISMATCHED_QUANT_TABLE, tblno);
  163722. }
  163723. }
  163724. /* Note: we do not copy the source's Huffman table assignments;
  163725. * instead we rely on jpeg_set_colorspace to have made a suitable choice.
  163726. */
  163727. }
  163728. /* Also copy JFIF version and resolution information, if available.
  163729. * Strictly speaking this isn't "critical" info, but it's nearly
  163730. * always appropriate to copy it if available. In particular,
  163731. * if the application chooses to copy JFIF 1.02 extension markers from
  163732. * the source file, we need to copy the version to make sure we don't
  163733. * emit a file that has 1.02 extensions but a claimed version of 1.01.
  163734. * We will *not*, however, copy version info from mislabeled "2.01" files.
  163735. */
  163736. if (srcinfo->saw_JFIF_marker) {
  163737. if (srcinfo->JFIF_major_version == 1) {
  163738. dstinfo->JFIF_major_version = srcinfo->JFIF_major_version;
  163739. dstinfo->JFIF_minor_version = srcinfo->JFIF_minor_version;
  163740. }
  163741. dstinfo->density_unit = srcinfo->density_unit;
  163742. dstinfo->X_density = srcinfo->X_density;
  163743. dstinfo->Y_density = srcinfo->Y_density;
  163744. }
  163745. }
  163746. /*
  163747. * Master selection of compression modules for transcoding.
  163748. * This substitutes for jcinit.c's initialization of the full compressor.
  163749. */
  163750. LOCAL(void)
  163751. transencode_master_selection (j_compress_ptr cinfo,
  163752. jvirt_barray_ptr * coef_arrays)
  163753. {
  163754. /* Although we don't actually use input_components for transcoding,
  163755. * jcmaster.c's initial_setup will complain if input_components is 0.
  163756. */
  163757. cinfo->input_components = 1;
  163758. /* Initialize master control (includes parameter checking/processing) */
  163759. jinit_c_master_control(cinfo, TRUE /* transcode only */);
  163760. /* Entropy encoding: either Huffman or arithmetic coding. */
  163761. if (cinfo->arith_code) {
  163762. ERREXIT(cinfo, JERR_ARITH_NOTIMPL);
  163763. } else {
  163764. if (cinfo->progressive_mode) {
  163765. #ifdef C_PROGRESSIVE_SUPPORTED
  163766. jinit_phuff_encoder(cinfo);
  163767. #else
  163768. ERREXIT(cinfo, JERR_NOT_COMPILED);
  163769. #endif
  163770. } else
  163771. jinit_huff_encoder(cinfo);
  163772. }
  163773. /* We need a special coefficient buffer controller. */
  163774. transencode_coef_controller(cinfo, coef_arrays);
  163775. jinit_marker_writer(cinfo);
  163776. /* We can now tell the memory manager to allocate virtual arrays. */
  163777. (*cinfo->mem->realize_virt_arrays) ((j_common_ptr) cinfo);
  163778. /* Write the datastream header (SOI, JFIF) immediately.
  163779. * Frame and scan headers are postponed till later.
  163780. * This lets application insert special markers after the SOI.
  163781. */
  163782. (*cinfo->marker->write_file_header) (cinfo);
  163783. }
  163784. /*
  163785. * The rest of this file is a special implementation of the coefficient
  163786. * buffer controller. This is similar to jccoefct.c, but it handles only
  163787. * output from presupplied virtual arrays. Furthermore, we generate any
  163788. * dummy padding blocks on-the-fly rather than expecting them to be present
  163789. * in the arrays.
  163790. */
  163791. /* Private buffer controller object */
  163792. typedef struct {
  163793. struct jpeg_c_coef_controller pub; /* public fields */
  163794. JDIMENSION iMCU_row_num; /* iMCU row # within image */
  163795. JDIMENSION mcu_ctr; /* counts MCUs processed in current row */
  163796. int MCU_vert_offset; /* counts MCU rows within iMCU row */
  163797. int MCU_rows_per_iMCU_row; /* number of such rows needed */
  163798. /* Virtual block array for each component. */
  163799. jvirt_barray_ptr * whole_image;
  163800. /* Workspace for constructing dummy blocks at right/bottom edges. */
  163801. JBLOCKROW dummy_buffer[C_MAX_BLOCKS_IN_MCU];
  163802. } my_coef_controller2;
  163803. typedef my_coef_controller2 * my_coef_ptr2;
  163804. LOCAL(void)
  163805. start_iMCU_row2 (j_compress_ptr cinfo)
  163806. /* Reset within-iMCU-row counters for a new row */
  163807. {
  163808. my_coef_ptr2 coef = (my_coef_ptr2) cinfo->coef;
  163809. /* In an interleaved scan, an MCU row is the same as an iMCU row.
  163810. * In a noninterleaved scan, an iMCU row has v_samp_factor MCU rows.
  163811. * But at the bottom of the image, process only what's left.
  163812. */
  163813. if (cinfo->comps_in_scan > 1) {
  163814. coef->MCU_rows_per_iMCU_row = 1;
  163815. } else {
  163816. if (coef->iMCU_row_num < (cinfo->total_iMCU_rows-1))
  163817. coef->MCU_rows_per_iMCU_row = cinfo->cur_comp_info[0]->v_samp_factor;
  163818. else
  163819. coef->MCU_rows_per_iMCU_row = cinfo->cur_comp_info[0]->last_row_height;
  163820. }
  163821. coef->mcu_ctr = 0;
  163822. coef->MCU_vert_offset = 0;
  163823. }
  163824. /*
  163825. * Initialize for a processing pass.
  163826. */
  163827. METHODDEF(void)
  163828. start_pass_coef2 (j_compress_ptr cinfo, J_BUF_MODE pass_mode)
  163829. {
  163830. my_coef_ptr2 coef = (my_coef_ptr2) cinfo->coef;
  163831. if (pass_mode != JBUF_CRANK_DEST)
  163832. ERREXIT(cinfo, JERR_BAD_BUFFER_MODE);
  163833. coef->iMCU_row_num = 0;
  163834. start_iMCU_row2(cinfo);
  163835. }
  163836. /*
  163837. * Process some data.
  163838. * We process the equivalent of one fully interleaved MCU row ("iMCU" row)
  163839. * per call, ie, v_samp_factor block rows for each component in the scan.
  163840. * The data is obtained from the virtual arrays and fed to the entropy coder.
  163841. * Returns TRUE if the iMCU row is completed, FALSE if suspended.
  163842. *
  163843. * NB: input_buf is ignored; it is likely to be a NULL pointer.
  163844. */
  163845. METHODDEF(boolean)
  163846. compress_output2 (j_compress_ptr cinfo, JSAMPIMAGE input_buf)
  163847. {
  163848. my_coef_ptr2 coef = (my_coef_ptr2) cinfo->coef;
  163849. JDIMENSION MCU_col_num; /* index of current MCU within row */
  163850. JDIMENSION last_MCU_col = cinfo->MCUs_per_row - 1;
  163851. JDIMENSION last_iMCU_row = cinfo->total_iMCU_rows - 1;
  163852. int blkn, ci, xindex, yindex, yoffset, blockcnt;
  163853. JDIMENSION start_col;
  163854. JBLOCKARRAY buffer[MAX_COMPS_IN_SCAN];
  163855. JBLOCKROW MCU_buffer[C_MAX_BLOCKS_IN_MCU];
  163856. JBLOCKROW buffer_ptr;
  163857. jpeg_component_info *compptr;
  163858. /* Align the virtual buffers for the components used in this scan. */
  163859. for (ci = 0; ci < cinfo->comps_in_scan; ci++) {
  163860. compptr = cinfo->cur_comp_info[ci];
  163861. buffer[ci] = (*cinfo->mem->access_virt_barray)
  163862. ((j_common_ptr) cinfo, coef->whole_image[compptr->component_index],
  163863. coef->iMCU_row_num * compptr->v_samp_factor,
  163864. (JDIMENSION) compptr->v_samp_factor, FALSE);
  163865. }
  163866. /* Loop to process one whole iMCU row */
  163867. for (yoffset = coef->MCU_vert_offset; yoffset < coef->MCU_rows_per_iMCU_row;
  163868. yoffset++) {
  163869. for (MCU_col_num = coef->mcu_ctr; MCU_col_num < cinfo->MCUs_per_row;
  163870. MCU_col_num++) {
  163871. /* Construct list of pointers to DCT blocks belonging to this MCU */
  163872. blkn = 0; /* index of current DCT block within MCU */
  163873. for (ci = 0; ci < cinfo->comps_in_scan; ci++) {
  163874. compptr = cinfo->cur_comp_info[ci];
  163875. start_col = MCU_col_num * compptr->MCU_width;
  163876. blockcnt = (MCU_col_num < last_MCU_col) ? compptr->MCU_width
  163877. : compptr->last_col_width;
  163878. for (yindex = 0; yindex < compptr->MCU_height; yindex++) {
  163879. if (coef->iMCU_row_num < last_iMCU_row ||
  163880. yindex+yoffset < compptr->last_row_height) {
  163881. /* Fill in pointers to real blocks in this row */
  163882. buffer_ptr = buffer[ci][yindex+yoffset] + start_col;
  163883. for (xindex = 0; xindex < blockcnt; xindex++)
  163884. MCU_buffer[blkn++] = buffer_ptr++;
  163885. } else {
  163886. /* At bottom of image, need a whole row of dummy blocks */
  163887. xindex = 0;
  163888. }
  163889. /* Fill in any dummy blocks needed in this row.
  163890. * Dummy blocks are filled in the same way as in jccoefct.c:
  163891. * all zeroes in the AC entries, DC entries equal to previous
  163892. * block's DC value. The init routine has already zeroed the
  163893. * AC entries, so we need only set the DC entries correctly.
  163894. */
  163895. for (; xindex < compptr->MCU_width; xindex++) {
  163896. MCU_buffer[blkn] = coef->dummy_buffer[blkn];
  163897. MCU_buffer[blkn][0][0] = MCU_buffer[blkn-1][0][0];
  163898. blkn++;
  163899. }
  163900. }
  163901. }
  163902. /* Try to write the MCU. */
  163903. if (! (*cinfo->entropy->encode_mcu) (cinfo, MCU_buffer)) {
  163904. /* Suspension forced; update state counters and exit */
  163905. coef->MCU_vert_offset = yoffset;
  163906. coef->mcu_ctr = MCU_col_num;
  163907. return FALSE;
  163908. }
  163909. }
  163910. /* Completed an MCU row, but perhaps not an iMCU row */
  163911. coef->mcu_ctr = 0;
  163912. }
  163913. /* Completed the iMCU row, advance counters for next one */
  163914. coef->iMCU_row_num++;
  163915. start_iMCU_row2(cinfo);
  163916. return TRUE;
  163917. }
  163918. /*
  163919. * Initialize coefficient buffer controller.
  163920. *
  163921. * Each passed coefficient array must be the right size for that
  163922. * coefficient: width_in_blocks wide and height_in_blocks high,
  163923. * with unitheight at least v_samp_factor.
  163924. */
  163925. LOCAL(void)
  163926. transencode_coef_controller (j_compress_ptr cinfo,
  163927. jvirt_barray_ptr * coef_arrays)
  163928. {
  163929. my_coef_ptr2 coef;
  163930. JBLOCKROW buffer;
  163931. int i;
  163932. coef = (my_coef_ptr2)
  163933. (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_IMAGE,
  163934. SIZEOF(my_coef_controller2));
  163935. cinfo->coef = (struct jpeg_c_coef_controller *) coef;
  163936. coef->pub.start_pass = start_pass_coef2;
  163937. coef->pub.compress_data = compress_output2;
  163938. /* Save pointer to virtual arrays */
  163939. coef->whole_image = coef_arrays;
  163940. /* Allocate and pre-zero space for dummy DCT blocks. */
  163941. buffer = (JBLOCKROW)
  163942. (*cinfo->mem->alloc_large) ((j_common_ptr) cinfo, JPOOL_IMAGE,
  163943. C_MAX_BLOCKS_IN_MCU * SIZEOF(JBLOCK));
  163944. jzero_far((void FAR *) buffer, C_MAX_BLOCKS_IN_MCU * SIZEOF(JBLOCK));
  163945. for (i = 0; i < C_MAX_BLOCKS_IN_MCU; i++) {
  163946. coef->dummy_buffer[i] = buffer + i;
  163947. }
  163948. }
  163949. /*** End of inlined file: jctrans.c ***/
  163950. /*** Start of inlined file: jdapistd.c ***/
  163951. #define JPEG_INTERNALS
  163952. /* Forward declarations */
  163953. LOCAL(boolean) output_pass_setup JPP((j_decompress_ptr cinfo));
  163954. /*
  163955. * Decompression initialization.
  163956. * jpeg_read_header must be completed before calling this.
  163957. *
  163958. * If a multipass operating mode was selected, this will do all but the
  163959. * last pass, and thus may take a great deal of time.
  163960. *
  163961. * Returns FALSE if suspended. The return value need be inspected only if
  163962. * a suspending data source is used.
  163963. */
  163964. GLOBAL(boolean)
  163965. jpeg_start_decompress (j_decompress_ptr cinfo)
  163966. {
  163967. if (cinfo->global_state == DSTATE_READY) {
  163968. /* First call: initialize master control, select active modules */
  163969. jinit_master_decompress(cinfo);
  163970. if (cinfo->buffered_image) {
  163971. /* No more work here; expecting jpeg_start_output next */
  163972. cinfo->global_state = DSTATE_BUFIMAGE;
  163973. return TRUE;
  163974. }
  163975. cinfo->global_state = DSTATE_PRELOAD;
  163976. }
  163977. if (cinfo->global_state == DSTATE_PRELOAD) {
  163978. /* If file has multiple scans, absorb them all into the coef buffer */
  163979. if (cinfo->inputctl->has_multiple_scans) {
  163980. #ifdef D_MULTISCAN_FILES_SUPPORTED
  163981. for (;;) {
  163982. int retcode;
  163983. /* Call progress monitor hook if present */
  163984. if (cinfo->progress != NULL)
  163985. (*cinfo->progress->progress_monitor) ((j_common_ptr) cinfo);
  163986. /* Absorb some more input */
  163987. retcode = (*cinfo->inputctl->consume_input) (cinfo);
  163988. if (retcode == JPEG_SUSPENDED)
  163989. return FALSE;
  163990. if (retcode == JPEG_REACHED_EOI)
  163991. break;
  163992. /* Advance progress counter if appropriate */
  163993. if (cinfo->progress != NULL &&
  163994. (retcode == JPEG_ROW_COMPLETED || retcode == JPEG_REACHED_SOS)) {
  163995. if (++cinfo->progress->pass_counter >= cinfo->progress->pass_limit) {
  163996. /* jdmaster underestimated number of scans; ratchet up one scan */
  163997. cinfo->progress->pass_limit += (long) cinfo->total_iMCU_rows;
  163998. }
  163999. }
  164000. }
  164001. #else
  164002. ERREXIT(cinfo, JERR_NOT_COMPILED);
  164003. #endif /* D_MULTISCAN_FILES_SUPPORTED */
  164004. }
  164005. cinfo->output_scan_number = cinfo->input_scan_number;
  164006. } else if (cinfo->global_state != DSTATE_PRESCAN)
  164007. ERREXIT1(cinfo, JERR_BAD_STATE, cinfo->global_state);
  164008. /* Perform any dummy output passes, and set up for the final pass */
  164009. return output_pass_setup(cinfo);
  164010. }
  164011. /*
  164012. * Set up for an output pass, and perform any dummy pass(es) needed.
  164013. * Common subroutine for jpeg_start_decompress and jpeg_start_output.
  164014. * Entry: global_state = DSTATE_PRESCAN only if previously suspended.
  164015. * Exit: If done, returns TRUE and sets global_state for proper output mode.
  164016. * If suspended, returns FALSE and sets global_state = DSTATE_PRESCAN.
  164017. */
  164018. LOCAL(boolean)
  164019. output_pass_setup (j_decompress_ptr cinfo)
  164020. {
  164021. if (cinfo->global_state != DSTATE_PRESCAN) {
  164022. /* First call: do pass setup */
  164023. (*cinfo->master->prepare_for_output_pass) (cinfo);
  164024. cinfo->output_scanline = 0;
  164025. cinfo->global_state = DSTATE_PRESCAN;
  164026. }
  164027. /* Loop over any required dummy passes */
  164028. while (cinfo->master->is_dummy_pass) {
  164029. #ifdef QUANT_2PASS_SUPPORTED
  164030. /* Crank through the dummy pass */
  164031. while (cinfo->output_scanline < cinfo->output_height) {
  164032. JDIMENSION last_scanline;
  164033. /* Call progress monitor hook if present */
  164034. if (cinfo->progress != NULL) {
  164035. cinfo->progress->pass_counter = (long) cinfo->output_scanline;
  164036. cinfo->progress->pass_limit = (long) cinfo->output_height;
  164037. (*cinfo->progress->progress_monitor) ((j_common_ptr) cinfo);
  164038. }
  164039. /* Process some data */
  164040. last_scanline = cinfo->output_scanline;
  164041. (*cinfo->main->process_data) (cinfo, (JSAMPARRAY) NULL,
  164042. &cinfo->output_scanline, (JDIMENSION) 0);
  164043. if (cinfo->output_scanline == last_scanline)
  164044. return FALSE; /* No progress made, must suspend */
  164045. }
  164046. /* Finish up dummy pass, and set up for another one */
  164047. (*cinfo->master->finish_output_pass) (cinfo);
  164048. (*cinfo->master->prepare_for_output_pass) (cinfo);
  164049. cinfo->output_scanline = 0;
  164050. #else
  164051. ERREXIT(cinfo, JERR_NOT_COMPILED);
  164052. #endif /* QUANT_2PASS_SUPPORTED */
  164053. }
  164054. /* Ready for application to drive output pass through
  164055. * jpeg_read_scanlines or jpeg_read_raw_data.
  164056. */
  164057. cinfo->global_state = cinfo->raw_data_out ? DSTATE_RAW_OK : DSTATE_SCANNING;
  164058. return TRUE;
  164059. }
  164060. /*
  164061. * Read some scanlines of data from the JPEG decompressor.
  164062. *
  164063. * The return value will be the number of lines actually read.
  164064. * This may be less than the number requested in several cases,
  164065. * including bottom of image, data source suspension, and operating
  164066. * modes that emit multiple scanlines at a time.
  164067. *
  164068. * Note: we warn about excess calls to jpeg_read_scanlines() since
  164069. * this likely signals an application programmer error. However,
  164070. * an oversize buffer (max_lines > scanlines remaining) is not an error.
  164071. */
  164072. GLOBAL(JDIMENSION)
  164073. jpeg_read_scanlines (j_decompress_ptr cinfo, JSAMPARRAY scanlines,
  164074. JDIMENSION max_lines)
  164075. {
  164076. JDIMENSION row_ctr;
  164077. if (cinfo->global_state != DSTATE_SCANNING)
  164078. ERREXIT1(cinfo, JERR_BAD_STATE, cinfo->global_state);
  164079. if (cinfo->output_scanline >= cinfo->output_height) {
  164080. WARNMS(cinfo, JWRN_TOO_MUCH_DATA);
  164081. return 0;
  164082. }
  164083. /* Call progress monitor hook if present */
  164084. if (cinfo->progress != NULL) {
  164085. cinfo->progress->pass_counter = (long) cinfo->output_scanline;
  164086. cinfo->progress->pass_limit = (long) cinfo->output_height;
  164087. (*cinfo->progress->progress_monitor) ((j_common_ptr) cinfo);
  164088. }
  164089. /* Process some data */
  164090. row_ctr = 0;
  164091. (*cinfo->main->process_data) (cinfo, scanlines, &row_ctr, max_lines);
  164092. cinfo->output_scanline += row_ctr;
  164093. return row_ctr;
  164094. }
  164095. /*
  164096. * Alternate entry point to read raw data.
  164097. * Processes exactly one iMCU row per call, unless suspended.
  164098. */
  164099. GLOBAL(JDIMENSION)
  164100. jpeg_read_raw_data (j_decompress_ptr cinfo, JSAMPIMAGE data,
  164101. JDIMENSION max_lines)
  164102. {
  164103. JDIMENSION lines_per_iMCU_row;
  164104. if (cinfo->global_state != DSTATE_RAW_OK)
  164105. ERREXIT1(cinfo, JERR_BAD_STATE, cinfo->global_state);
  164106. if (cinfo->output_scanline >= cinfo->output_height) {
  164107. WARNMS(cinfo, JWRN_TOO_MUCH_DATA);
  164108. return 0;
  164109. }
  164110. /* Call progress monitor hook if present */
  164111. if (cinfo->progress != NULL) {
  164112. cinfo->progress->pass_counter = (long) cinfo->output_scanline;
  164113. cinfo->progress->pass_limit = (long) cinfo->output_height;
  164114. (*cinfo->progress->progress_monitor) ((j_common_ptr) cinfo);
  164115. }
  164116. /* Verify that at least one iMCU row can be returned. */
  164117. lines_per_iMCU_row = cinfo->max_v_samp_factor * cinfo->min_DCT_scaled_size;
  164118. if (max_lines < lines_per_iMCU_row)
  164119. ERREXIT(cinfo, JERR_BUFFER_SIZE);
  164120. /* Decompress directly into user's buffer. */
  164121. if (! (*cinfo->coef->decompress_data) (cinfo, data))
  164122. return 0; /* suspension forced, can do nothing more */
  164123. /* OK, we processed one iMCU row. */
  164124. cinfo->output_scanline += lines_per_iMCU_row;
  164125. return lines_per_iMCU_row;
  164126. }
  164127. /* Additional entry points for buffered-image mode. */
  164128. #ifdef D_MULTISCAN_FILES_SUPPORTED
  164129. /*
  164130. * Initialize for an output pass in buffered-image mode.
  164131. */
  164132. GLOBAL(boolean)
  164133. jpeg_start_output (j_decompress_ptr cinfo, int scan_number)
  164134. {
  164135. if (cinfo->global_state != DSTATE_BUFIMAGE &&
  164136. cinfo->global_state != DSTATE_PRESCAN)
  164137. ERREXIT1(cinfo, JERR_BAD_STATE, cinfo->global_state);
  164138. /* Limit scan number to valid range */
  164139. if (scan_number <= 0)
  164140. scan_number = 1;
  164141. if (cinfo->inputctl->eoi_reached &&
  164142. scan_number > cinfo->input_scan_number)
  164143. scan_number = cinfo->input_scan_number;
  164144. cinfo->output_scan_number = scan_number;
  164145. /* Perform any dummy output passes, and set up for the real pass */
  164146. return output_pass_setup(cinfo);
  164147. }
  164148. /*
  164149. * Finish up after an output pass in buffered-image mode.
  164150. *
  164151. * Returns FALSE if suspended. The return value need be inspected only if
  164152. * a suspending data source is used.
  164153. */
  164154. GLOBAL(boolean)
  164155. jpeg_finish_output (j_decompress_ptr cinfo)
  164156. {
  164157. if ((cinfo->global_state == DSTATE_SCANNING ||
  164158. cinfo->global_state == DSTATE_RAW_OK) && cinfo->buffered_image) {
  164159. /* Terminate this pass. */
  164160. /* We do not require the whole pass to have been completed. */
  164161. (*cinfo->master->finish_output_pass) (cinfo);
  164162. cinfo->global_state = DSTATE_BUFPOST;
  164163. } else if (cinfo->global_state != DSTATE_BUFPOST) {
  164164. /* BUFPOST = repeat call after a suspension, anything else is error */
  164165. ERREXIT1(cinfo, JERR_BAD_STATE, cinfo->global_state);
  164166. }
  164167. /* Read markers looking for SOS or EOI */
  164168. while (cinfo->input_scan_number <= cinfo->output_scan_number &&
  164169. ! cinfo->inputctl->eoi_reached) {
  164170. if ((*cinfo->inputctl->consume_input) (cinfo) == JPEG_SUSPENDED)
  164171. return FALSE; /* Suspend, come back later */
  164172. }
  164173. cinfo->global_state = DSTATE_BUFIMAGE;
  164174. return TRUE;
  164175. }
  164176. #endif /* D_MULTISCAN_FILES_SUPPORTED */
  164177. /*** End of inlined file: jdapistd.c ***/
  164178. /*** Start of inlined file: jdapimin.c ***/
  164179. #define JPEG_INTERNALS
  164180. /*
  164181. * Initialization of a JPEG decompression object.
  164182. * The error manager must already be set up (in case memory manager fails).
  164183. */
  164184. GLOBAL(void)
  164185. jpeg_CreateDecompress (j_decompress_ptr cinfo, int version, size_t structsize)
  164186. {
  164187. int i;
  164188. /* Guard against version mismatches between library and caller. */
  164189. cinfo->mem = NULL; /* so jpeg_destroy knows mem mgr not called */
  164190. if (version != JPEG_LIB_VERSION)
  164191. ERREXIT2(cinfo, JERR_BAD_LIB_VERSION, JPEG_LIB_VERSION, version);
  164192. if (structsize != SIZEOF(struct jpeg_decompress_struct))
  164193. ERREXIT2(cinfo, JERR_BAD_STRUCT_SIZE,
  164194. (int) SIZEOF(struct jpeg_decompress_struct), (int) structsize);
  164195. /* For debugging purposes, we zero the whole master structure.
  164196. * But the application has already set the err pointer, and may have set
  164197. * client_data, so we have to save and restore those fields.
  164198. * Note: if application hasn't set client_data, tools like Purify may
  164199. * complain here.
  164200. */
  164201. {
  164202. struct jpeg_error_mgr * err = cinfo->err;
  164203. void * client_data = cinfo->client_data; /* ignore Purify complaint here */
  164204. MEMZERO(cinfo, SIZEOF(struct jpeg_decompress_struct));
  164205. cinfo->err = err;
  164206. cinfo->client_data = client_data;
  164207. }
  164208. cinfo->is_decompressor = TRUE;
  164209. /* Initialize a memory manager instance for this object */
  164210. jinit_memory_mgr((j_common_ptr) cinfo);
  164211. /* Zero out pointers to permanent structures. */
  164212. cinfo->progress = NULL;
  164213. cinfo->src = NULL;
  164214. for (i = 0; i < NUM_QUANT_TBLS; i++)
  164215. cinfo->quant_tbl_ptrs[i] = NULL;
  164216. for (i = 0; i < NUM_HUFF_TBLS; i++) {
  164217. cinfo->dc_huff_tbl_ptrs[i] = NULL;
  164218. cinfo->ac_huff_tbl_ptrs[i] = NULL;
  164219. }
  164220. /* Initialize marker processor so application can override methods
  164221. * for COM, APPn markers before calling jpeg_read_header.
  164222. */
  164223. cinfo->marker_list = NULL;
  164224. jinit_marker_reader(cinfo);
  164225. /* And initialize the overall input controller. */
  164226. jinit_input_controller(cinfo);
  164227. /* OK, I'm ready */
  164228. cinfo->global_state = DSTATE_START;
  164229. }
  164230. /*
  164231. * Destruction of a JPEG decompression object
  164232. */
  164233. GLOBAL(void)
  164234. jpeg_destroy_decompress (j_decompress_ptr cinfo)
  164235. {
  164236. jpeg_destroy((j_common_ptr) cinfo); /* use common routine */
  164237. }
  164238. /*
  164239. * Abort processing of a JPEG decompression operation,
  164240. * but don't destroy the object itself.
  164241. */
  164242. GLOBAL(void)
  164243. jpeg_abort_decompress (j_decompress_ptr cinfo)
  164244. {
  164245. jpeg_abort((j_common_ptr) cinfo); /* use common routine */
  164246. }
  164247. /*
  164248. * Set default decompression parameters.
  164249. */
  164250. LOCAL(void)
  164251. default_decompress_parms (j_decompress_ptr cinfo)
  164252. {
  164253. /* Guess the input colorspace, and set output colorspace accordingly. */
  164254. /* (Wish JPEG committee had provided a real way to specify this...) */
  164255. /* Note application may override our guesses. */
  164256. switch (cinfo->num_components) {
  164257. case 1:
  164258. cinfo->jpeg_color_space = JCS_GRAYSCALE;
  164259. cinfo->out_color_space = JCS_GRAYSCALE;
  164260. break;
  164261. case 3:
  164262. if (cinfo->saw_JFIF_marker) {
  164263. cinfo->jpeg_color_space = JCS_YCbCr; /* JFIF implies YCbCr */
  164264. } else if (cinfo->saw_Adobe_marker) {
  164265. switch (cinfo->Adobe_transform) {
  164266. case 0:
  164267. cinfo->jpeg_color_space = JCS_RGB;
  164268. break;
  164269. case 1:
  164270. cinfo->jpeg_color_space = JCS_YCbCr;
  164271. break;
  164272. default:
  164273. WARNMS1(cinfo, JWRN_ADOBE_XFORM, cinfo->Adobe_transform);
  164274. cinfo->jpeg_color_space = JCS_YCbCr; /* assume it's YCbCr */
  164275. break;
  164276. }
  164277. } else {
  164278. /* Saw no special markers, try to guess from the component IDs */
  164279. int cid0 = cinfo->comp_info[0].component_id;
  164280. int cid1 = cinfo->comp_info[1].component_id;
  164281. int cid2 = cinfo->comp_info[2].component_id;
  164282. if (cid0 == 1 && cid1 == 2 && cid2 == 3)
  164283. cinfo->jpeg_color_space = JCS_YCbCr; /* assume JFIF w/out marker */
  164284. else if (cid0 == 82 && cid1 == 71 && cid2 == 66)
  164285. cinfo->jpeg_color_space = JCS_RGB; /* ASCII 'R', 'G', 'B' */
  164286. else {
  164287. TRACEMS3(cinfo, 1, JTRC_UNKNOWN_IDS, cid0, cid1, cid2);
  164288. cinfo->jpeg_color_space = JCS_YCbCr; /* assume it's YCbCr */
  164289. }
  164290. }
  164291. /* Always guess RGB is proper output colorspace. */
  164292. cinfo->out_color_space = JCS_RGB;
  164293. break;
  164294. case 4:
  164295. if (cinfo->saw_Adobe_marker) {
  164296. switch (cinfo->Adobe_transform) {
  164297. case 0:
  164298. cinfo->jpeg_color_space = JCS_CMYK;
  164299. break;
  164300. case 2:
  164301. cinfo->jpeg_color_space = JCS_YCCK;
  164302. break;
  164303. default:
  164304. WARNMS1(cinfo, JWRN_ADOBE_XFORM, cinfo->Adobe_transform);
  164305. cinfo->jpeg_color_space = JCS_YCCK; /* assume it's YCCK */
  164306. break;
  164307. }
  164308. } else {
  164309. /* No special markers, assume straight CMYK. */
  164310. cinfo->jpeg_color_space = JCS_CMYK;
  164311. }
  164312. cinfo->out_color_space = JCS_CMYK;
  164313. break;
  164314. default:
  164315. cinfo->jpeg_color_space = JCS_UNKNOWN;
  164316. cinfo->out_color_space = JCS_UNKNOWN;
  164317. break;
  164318. }
  164319. /* Set defaults for other decompression parameters. */
  164320. cinfo->scale_num = 1; /* 1:1 scaling */
  164321. cinfo->scale_denom = 1;
  164322. cinfo->output_gamma = 1.0;
  164323. cinfo->buffered_image = FALSE;
  164324. cinfo->raw_data_out = FALSE;
  164325. cinfo->dct_method = JDCT_DEFAULT;
  164326. cinfo->do_fancy_upsampling = TRUE;
  164327. cinfo->do_block_smoothing = TRUE;
  164328. cinfo->quantize_colors = FALSE;
  164329. /* We set these in case application only sets quantize_colors. */
  164330. cinfo->dither_mode = JDITHER_FS;
  164331. #ifdef QUANT_2PASS_SUPPORTED
  164332. cinfo->two_pass_quantize = TRUE;
  164333. #else
  164334. cinfo->two_pass_quantize = FALSE;
  164335. #endif
  164336. cinfo->desired_number_of_colors = 256;
  164337. cinfo->colormap = NULL;
  164338. /* Initialize for no mode change in buffered-image mode. */
  164339. cinfo->enable_1pass_quant = FALSE;
  164340. cinfo->enable_external_quant = FALSE;
  164341. cinfo->enable_2pass_quant = FALSE;
  164342. }
  164343. /*
  164344. * Decompression startup: read start of JPEG datastream to see what's there.
  164345. * Need only initialize JPEG object and supply a data source before calling.
  164346. *
  164347. * This routine will read as far as the first SOS marker (ie, actual start of
  164348. * compressed data), and will save all tables and parameters in the JPEG
  164349. * object. It will also initialize the decompression parameters to default
  164350. * values, and finally return JPEG_HEADER_OK. On return, the application may
  164351. * adjust the decompression parameters and then call jpeg_start_decompress.
  164352. * (Or, if the application only wanted to determine the image parameters,
  164353. * the data need not be decompressed. In that case, call jpeg_abort or
  164354. * jpeg_destroy to release any temporary space.)
  164355. * If an abbreviated (tables only) datastream is presented, the routine will
  164356. * return JPEG_HEADER_TABLES_ONLY upon reaching EOI. The application may then
  164357. * re-use the JPEG object to read the abbreviated image datastream(s).
  164358. * It is unnecessary (but OK) to call jpeg_abort in this case.
  164359. * The JPEG_SUSPENDED return code only occurs if the data source module
  164360. * requests suspension of the decompressor. In this case the application
  164361. * should load more source data and then re-call jpeg_read_header to resume
  164362. * processing.
  164363. * If a non-suspending data source is used and require_image is TRUE, then the
  164364. * return code need not be inspected since only JPEG_HEADER_OK is possible.
  164365. *
  164366. * This routine is now just a front end to jpeg_consume_input, with some
  164367. * extra error checking.
  164368. */
  164369. GLOBAL(int)
  164370. jpeg_read_header (j_decompress_ptr cinfo, boolean require_image)
  164371. {
  164372. int retcode;
  164373. if (cinfo->global_state != DSTATE_START &&
  164374. cinfo->global_state != DSTATE_INHEADER)
  164375. ERREXIT1(cinfo, JERR_BAD_STATE, cinfo->global_state);
  164376. retcode = jpeg_consume_input(cinfo);
  164377. switch (retcode) {
  164378. case JPEG_REACHED_SOS:
  164379. retcode = JPEG_HEADER_OK;
  164380. break;
  164381. case JPEG_REACHED_EOI:
  164382. if (require_image) /* Complain if application wanted an image */
  164383. ERREXIT(cinfo, JERR_NO_IMAGE);
  164384. /* Reset to start state; it would be safer to require the application to
  164385. * call jpeg_abort, but we can't change it now for compatibility reasons.
  164386. * A side effect is to free any temporary memory (there shouldn't be any).
  164387. */
  164388. jpeg_abort((j_common_ptr) cinfo); /* sets state = DSTATE_START */
  164389. retcode = JPEG_HEADER_TABLES_ONLY;
  164390. break;
  164391. case JPEG_SUSPENDED:
  164392. /* no work */
  164393. break;
  164394. }
  164395. return retcode;
  164396. }
  164397. /*
  164398. * Consume data in advance of what the decompressor requires.
  164399. * This can be called at any time once the decompressor object has
  164400. * been created and a data source has been set up.
  164401. *
  164402. * This routine is essentially a state machine that handles a couple
  164403. * of critical state-transition actions, namely initial setup and
  164404. * transition from header scanning to ready-for-start_decompress.
  164405. * All the actual input is done via the input controller's consume_input
  164406. * method.
  164407. */
  164408. GLOBAL(int)
  164409. jpeg_consume_input (j_decompress_ptr cinfo)
  164410. {
  164411. int retcode = JPEG_SUSPENDED;
  164412. /* NB: every possible DSTATE value should be listed in this switch */
  164413. switch (cinfo->global_state) {
  164414. case DSTATE_START:
  164415. /* Start-of-datastream actions: reset appropriate modules */
  164416. (*cinfo->inputctl->reset_input_controller) (cinfo);
  164417. /* Initialize application's data source module */
  164418. (*cinfo->src->init_source) (cinfo);
  164419. cinfo->global_state = DSTATE_INHEADER;
  164420. /*FALLTHROUGH*/
  164421. case DSTATE_INHEADER:
  164422. retcode = (*cinfo->inputctl->consume_input) (cinfo);
  164423. if (retcode == JPEG_REACHED_SOS) { /* Found SOS, prepare to decompress */
  164424. /* Set up default parameters based on header data */
  164425. default_decompress_parms(cinfo);
  164426. /* Set global state: ready for start_decompress */
  164427. cinfo->global_state = DSTATE_READY;
  164428. }
  164429. break;
  164430. case DSTATE_READY:
  164431. /* Can't advance past first SOS until start_decompress is called */
  164432. retcode = JPEG_REACHED_SOS;
  164433. break;
  164434. case DSTATE_PRELOAD:
  164435. case DSTATE_PRESCAN:
  164436. case DSTATE_SCANNING:
  164437. case DSTATE_RAW_OK:
  164438. case DSTATE_BUFIMAGE:
  164439. case DSTATE_BUFPOST:
  164440. case DSTATE_STOPPING:
  164441. retcode = (*cinfo->inputctl->consume_input) (cinfo);
  164442. break;
  164443. default:
  164444. ERREXIT1(cinfo, JERR_BAD_STATE, cinfo->global_state);
  164445. }
  164446. return retcode;
  164447. }
  164448. /*
  164449. * Have we finished reading the input file?
  164450. */
  164451. GLOBAL(boolean)
  164452. jpeg_input_complete (j_decompress_ptr cinfo)
  164453. {
  164454. /* Check for valid jpeg object */
  164455. if (cinfo->global_state < DSTATE_START ||
  164456. cinfo->global_state > DSTATE_STOPPING)
  164457. ERREXIT1(cinfo, JERR_BAD_STATE, cinfo->global_state);
  164458. return cinfo->inputctl->eoi_reached;
  164459. }
  164460. /*
  164461. * Is there more than one scan?
  164462. */
  164463. GLOBAL(boolean)
  164464. jpeg_has_multiple_scans (j_decompress_ptr cinfo)
  164465. {
  164466. /* Only valid after jpeg_read_header completes */
  164467. if (cinfo->global_state < DSTATE_READY ||
  164468. cinfo->global_state > DSTATE_STOPPING)
  164469. ERREXIT1(cinfo, JERR_BAD_STATE, cinfo->global_state);
  164470. return cinfo->inputctl->has_multiple_scans;
  164471. }
  164472. /*
  164473. * Finish JPEG decompression.
  164474. *
  164475. * This will normally just verify the file trailer and release temp storage.
  164476. *
  164477. * Returns FALSE if suspended. The return value need be inspected only if
  164478. * a suspending data source is used.
  164479. */
  164480. GLOBAL(boolean)
  164481. jpeg_finish_decompress (j_decompress_ptr cinfo)
  164482. {
  164483. if ((cinfo->global_state == DSTATE_SCANNING ||
  164484. cinfo->global_state == DSTATE_RAW_OK) && ! cinfo->buffered_image) {
  164485. /* Terminate final pass of non-buffered mode */
  164486. if (cinfo->output_scanline < cinfo->output_height)
  164487. ERREXIT(cinfo, JERR_TOO_LITTLE_DATA);
  164488. (*cinfo->master->finish_output_pass) (cinfo);
  164489. cinfo->global_state = DSTATE_STOPPING;
  164490. } else if (cinfo->global_state == DSTATE_BUFIMAGE) {
  164491. /* Finishing after a buffered-image operation */
  164492. cinfo->global_state = DSTATE_STOPPING;
  164493. } else if (cinfo->global_state != DSTATE_STOPPING) {
  164494. /* STOPPING = repeat call after a suspension, anything else is error */
  164495. ERREXIT1(cinfo, JERR_BAD_STATE, cinfo->global_state);
  164496. }
  164497. /* Read until EOI */
  164498. while (! cinfo->inputctl->eoi_reached) {
  164499. if ((*cinfo->inputctl->consume_input) (cinfo) == JPEG_SUSPENDED)
  164500. return FALSE; /* Suspend, come back later */
  164501. }
  164502. /* Do final cleanup */
  164503. (*cinfo->src->term_source) (cinfo);
  164504. /* We can use jpeg_abort to release memory and reset global_state */
  164505. jpeg_abort((j_common_ptr) cinfo);
  164506. return TRUE;
  164507. }
  164508. /*** End of inlined file: jdapimin.c ***/
  164509. /*** Start of inlined file: jdatasrc.c ***/
  164510. /* this is not a core library module, so it doesn't define JPEG_INTERNALS */
  164511. /*** Start of inlined file: jerror.h ***/
  164512. /*
  164513. * To define the enum list of message codes, include this file without
  164514. * defining macro JMESSAGE. To create a message string table, include it
  164515. * again with a suitable JMESSAGE definition (see jerror.c for an example).
  164516. */
  164517. #ifndef JMESSAGE
  164518. #ifndef JERROR_H
  164519. /* First time through, define the enum list */
  164520. #define JMAKE_ENUM_LIST
  164521. #else
  164522. /* Repeated inclusions of this file are no-ops unless JMESSAGE is defined */
  164523. #define JMESSAGE(code,string)
  164524. #endif /* JERROR_H */
  164525. #endif /* JMESSAGE */
  164526. #ifdef JMAKE_ENUM_LIST
  164527. typedef enum {
  164528. #define JMESSAGE(code,string) code ,
  164529. #endif /* JMAKE_ENUM_LIST */
  164530. JMESSAGE(JMSG_NOMESSAGE, "Bogus message code %d") /* Must be first entry! */
  164531. /* For maintenance convenience, list is alphabetical by message code name */
  164532. JMESSAGE(JERR_ARITH_NOTIMPL,
  164533. "Sorry, there are legal restrictions on arithmetic coding")
  164534. JMESSAGE(JERR_BAD_ALIGN_TYPE, "ALIGN_TYPE is wrong, please fix")
  164535. JMESSAGE(JERR_BAD_ALLOC_CHUNK, "MAX_ALLOC_CHUNK is wrong, please fix")
  164536. JMESSAGE(JERR_BAD_BUFFER_MODE, "Bogus buffer control mode")
  164537. JMESSAGE(JERR_BAD_COMPONENT_ID, "Invalid component ID %d in SOS")
  164538. JMESSAGE(JERR_BAD_DCT_COEF, "DCT coefficient out of range")
  164539. JMESSAGE(JERR_BAD_DCTSIZE, "IDCT output block size %d not supported")
  164540. JMESSAGE(JERR_BAD_HUFF_TABLE, "Bogus Huffman table definition")
  164541. JMESSAGE(JERR_BAD_IN_COLORSPACE, "Bogus input colorspace")
  164542. JMESSAGE(JERR_BAD_J_COLORSPACE, "Bogus JPEG colorspace")
  164543. JMESSAGE(JERR_BAD_LENGTH, "Bogus marker length")
  164544. JMESSAGE(JERR_BAD_LIB_VERSION,
  164545. "Wrong JPEG library version: library is %d, caller expects %d")
  164546. JMESSAGE(JERR_BAD_MCU_SIZE, "Sampling factors too large for interleaved scan")
  164547. JMESSAGE(JERR_BAD_POOL_ID, "Invalid memory pool code %d")
  164548. JMESSAGE(JERR_BAD_PRECISION, "Unsupported JPEG data precision %d")
  164549. JMESSAGE(JERR_BAD_PROGRESSION,
  164550. "Invalid progressive parameters Ss=%d Se=%d Ah=%d Al=%d")
  164551. JMESSAGE(JERR_BAD_PROG_SCRIPT,
  164552. "Invalid progressive parameters at scan script entry %d")
  164553. JMESSAGE(JERR_BAD_SAMPLING, "Bogus sampling factors")
  164554. JMESSAGE(JERR_BAD_SCAN_SCRIPT, "Invalid scan script at entry %d")
  164555. JMESSAGE(JERR_BAD_STATE, "Improper call to JPEG library in state %d")
  164556. JMESSAGE(JERR_BAD_STRUCT_SIZE,
  164557. "JPEG parameter struct mismatch: library thinks size is %u, caller expects %u")
  164558. JMESSAGE(JERR_BAD_VIRTUAL_ACCESS, "Bogus virtual array access")
  164559. JMESSAGE(JERR_BUFFER_SIZE, "Buffer passed to JPEG library is too small")
  164560. JMESSAGE(JERR_CANT_SUSPEND, "Suspension not allowed here")
  164561. JMESSAGE(JERR_CCIR601_NOTIMPL, "CCIR601 sampling not implemented yet")
  164562. JMESSAGE(JERR_COMPONENT_COUNT, "Too many color components: %d, max %d")
  164563. JMESSAGE(JERR_CONVERSION_NOTIMPL, "Unsupported color conversion request")
  164564. JMESSAGE(JERR_DAC_INDEX, "Bogus DAC index %d")
  164565. JMESSAGE(JERR_DAC_VALUE, "Bogus DAC value 0x%x")
  164566. JMESSAGE(JERR_DHT_INDEX, "Bogus DHT index %d")
  164567. JMESSAGE(JERR_DQT_INDEX, "Bogus DQT index %d")
  164568. JMESSAGE(JERR_EMPTY_IMAGE, "Empty JPEG image (DNL not supported)")
  164569. JMESSAGE(JERR_EMS_READ, "Read from EMS failed")
  164570. JMESSAGE(JERR_EMS_WRITE, "Write to EMS failed")
  164571. JMESSAGE(JERR_EOI_EXPECTED, "Didn't expect more than one scan")
  164572. JMESSAGE(JERR_FILE_READ, "Input file read error")
  164573. JMESSAGE(JERR_FILE_WRITE, "Output file write error --- out of disk space?")
  164574. JMESSAGE(JERR_FRACT_SAMPLE_NOTIMPL, "Fractional sampling not implemented yet")
  164575. JMESSAGE(JERR_HUFF_CLEN_OVERFLOW, "Huffman code size table overflow")
  164576. JMESSAGE(JERR_HUFF_MISSING_CODE, "Missing Huffman code table entry")
  164577. JMESSAGE(JERR_IMAGE_TOO_BIG, "Maximum supported image dimension is %u pixels")
  164578. JMESSAGE(JERR_INPUT_EMPTY, "Empty input file")
  164579. JMESSAGE(JERR_INPUT_EOF, "Premature end of input file")
  164580. JMESSAGE(JERR_MISMATCHED_QUANT_TABLE,
  164581. "Cannot transcode due to multiple use of quantization table %d")
  164582. JMESSAGE(JERR_MISSING_DATA, "Scan script does not transmit all data")
  164583. JMESSAGE(JERR_MODE_CHANGE, "Invalid color quantization mode change")
  164584. JMESSAGE(JERR_NOTIMPL, "Not implemented yet")
  164585. JMESSAGE(JERR_NOT_COMPILED, "Requested feature was omitted at compile time")
  164586. JMESSAGE(JERR_NO_BACKING_STORE, "Backing store not supported")
  164587. JMESSAGE(JERR_NO_HUFF_TABLE, "Huffman table 0x%02x was not defined")
  164588. JMESSAGE(JERR_NO_IMAGE, "JPEG datastream contains no image")
  164589. JMESSAGE(JERR_NO_QUANT_TABLE, "Quantization table 0x%02x was not defined")
  164590. JMESSAGE(JERR_NO_SOI, "Not a JPEG file: starts with 0x%02x 0x%02x")
  164591. JMESSAGE(JERR_OUT_OF_MEMORY, "Insufficient memory (case %d)")
  164592. JMESSAGE(JERR_QUANT_COMPONENTS,
  164593. "Cannot quantize more than %d color components")
  164594. JMESSAGE(JERR_QUANT_FEW_COLORS, "Cannot quantize to fewer than %d colors")
  164595. JMESSAGE(JERR_QUANT_MANY_COLORS, "Cannot quantize to more than %d colors")
  164596. JMESSAGE(JERR_SOF_DUPLICATE, "Invalid JPEG file structure: two SOF markers")
  164597. JMESSAGE(JERR_SOF_NO_SOS, "Invalid JPEG file structure: missing SOS marker")
  164598. JMESSAGE(JERR_SOF_UNSUPPORTED, "Unsupported JPEG process: SOF type 0x%02x")
  164599. JMESSAGE(JERR_SOI_DUPLICATE, "Invalid JPEG file structure: two SOI markers")
  164600. JMESSAGE(JERR_SOS_NO_SOF, "Invalid JPEG file structure: SOS before SOF")
  164601. JMESSAGE(JERR_TFILE_CREATE, "Failed to create temporary file %s")
  164602. JMESSAGE(JERR_TFILE_READ, "Read failed on temporary file")
  164603. JMESSAGE(JERR_TFILE_SEEK, "Seek failed on temporary file")
  164604. JMESSAGE(JERR_TFILE_WRITE,
  164605. "Write failed on temporary file --- out of disk space?")
  164606. JMESSAGE(JERR_TOO_LITTLE_DATA, "Application transferred too few scanlines")
  164607. JMESSAGE(JERR_UNKNOWN_MARKER, "Unsupported marker type 0x%02x")
  164608. JMESSAGE(JERR_VIRTUAL_BUG, "Virtual array controller messed up")
  164609. JMESSAGE(JERR_WIDTH_OVERFLOW, "Image too wide for this implementation")
  164610. JMESSAGE(JERR_XMS_READ, "Read from XMS failed")
  164611. JMESSAGE(JERR_XMS_WRITE, "Write to XMS failed")
  164612. JMESSAGE(JMSG_COPYRIGHT, JCOPYRIGHT)
  164613. JMESSAGE(JMSG_VERSION, JVERSION)
  164614. JMESSAGE(JTRC_16BIT_TABLES,
  164615. "Caution: quantization tables are too coarse for baseline JPEG")
  164616. JMESSAGE(JTRC_ADOBE,
  164617. "Adobe APP14 marker: version %d, flags 0x%04x 0x%04x, transform %d")
  164618. JMESSAGE(JTRC_APP0, "Unknown APP0 marker (not JFIF), length %u")
  164619. JMESSAGE(JTRC_APP14, "Unknown APP14 marker (not Adobe), length %u")
  164620. JMESSAGE(JTRC_DAC, "Define Arithmetic Table 0x%02x: 0x%02x")
  164621. JMESSAGE(JTRC_DHT, "Define Huffman Table 0x%02x")
  164622. JMESSAGE(JTRC_DQT, "Define Quantization Table %d precision %d")
  164623. JMESSAGE(JTRC_DRI, "Define Restart Interval %u")
  164624. JMESSAGE(JTRC_EMS_CLOSE, "Freed EMS handle %u")
  164625. JMESSAGE(JTRC_EMS_OPEN, "Obtained EMS handle %u")
  164626. JMESSAGE(JTRC_EOI, "End Of Image")
  164627. JMESSAGE(JTRC_HUFFBITS, " %3d %3d %3d %3d %3d %3d %3d %3d")
  164628. JMESSAGE(JTRC_JFIF, "JFIF APP0 marker: version %d.%02d, density %dx%d %d")
  164629. JMESSAGE(JTRC_JFIF_BADTHUMBNAILSIZE,
  164630. "Warning: thumbnail image size does not match data length %u")
  164631. JMESSAGE(JTRC_JFIF_EXTENSION,
  164632. "JFIF extension marker: type 0x%02x, length %u")
  164633. JMESSAGE(JTRC_JFIF_THUMBNAIL, " with %d x %d thumbnail image")
  164634. JMESSAGE(JTRC_MISC_MARKER, "Miscellaneous marker 0x%02x, length %u")
  164635. JMESSAGE(JTRC_PARMLESS_MARKER, "Unexpected marker 0x%02x")
  164636. JMESSAGE(JTRC_QUANTVALS, " %4u %4u %4u %4u %4u %4u %4u %4u")
  164637. JMESSAGE(JTRC_QUANT_3_NCOLORS, "Quantizing to %d = %d*%d*%d colors")
  164638. JMESSAGE(JTRC_QUANT_NCOLORS, "Quantizing to %d colors")
  164639. JMESSAGE(JTRC_QUANT_SELECTED, "Selected %d colors for quantization")
  164640. JMESSAGE(JTRC_RECOVERY_ACTION, "At marker 0x%02x, recovery action %d")
  164641. JMESSAGE(JTRC_RST, "RST%d")
  164642. JMESSAGE(JTRC_SMOOTH_NOTIMPL,
  164643. "Smoothing not supported with nonstandard sampling ratios")
  164644. JMESSAGE(JTRC_SOF, "Start Of Frame 0x%02x: width=%u, height=%u, components=%d")
  164645. JMESSAGE(JTRC_SOF_COMPONENT, " Component %d: %dhx%dv q=%d")
  164646. JMESSAGE(JTRC_SOI, "Start of Image")
  164647. JMESSAGE(JTRC_SOS, "Start Of Scan: %d components")
  164648. JMESSAGE(JTRC_SOS_COMPONENT, " Component %d: dc=%d ac=%d")
  164649. JMESSAGE(JTRC_SOS_PARAMS, " Ss=%d, Se=%d, Ah=%d, Al=%d")
  164650. JMESSAGE(JTRC_TFILE_CLOSE, "Closed temporary file %s")
  164651. JMESSAGE(JTRC_TFILE_OPEN, "Opened temporary file %s")
  164652. JMESSAGE(JTRC_THUMB_JPEG,
  164653. "JFIF extension marker: JPEG-compressed thumbnail image, length %u")
  164654. JMESSAGE(JTRC_THUMB_PALETTE,
  164655. "JFIF extension marker: palette thumbnail image, length %u")
  164656. JMESSAGE(JTRC_THUMB_RGB,
  164657. "JFIF extension marker: RGB thumbnail image, length %u")
  164658. JMESSAGE(JTRC_UNKNOWN_IDS,
  164659. "Unrecognized component IDs %d %d %d, assuming YCbCr")
  164660. JMESSAGE(JTRC_XMS_CLOSE, "Freed XMS handle %u")
  164661. JMESSAGE(JTRC_XMS_OPEN, "Obtained XMS handle %u")
  164662. JMESSAGE(JWRN_ADOBE_XFORM, "Unknown Adobe color transform code %d")
  164663. JMESSAGE(JWRN_BOGUS_PROGRESSION,
  164664. "Inconsistent progression sequence for component %d coefficient %d")
  164665. JMESSAGE(JWRN_EXTRANEOUS_DATA,
  164666. "Corrupt JPEG data: %u extraneous bytes before marker 0x%02x")
  164667. JMESSAGE(JWRN_HIT_MARKER, "Corrupt JPEG data: premature end of data segment")
  164668. JMESSAGE(JWRN_HUFF_BAD_CODE, "Corrupt JPEG data: bad Huffman code")
  164669. JMESSAGE(JWRN_JFIF_MAJOR, "Warning: unknown JFIF revision number %d.%02d")
  164670. JMESSAGE(JWRN_JPEG_EOF, "Premature end of JPEG file")
  164671. JMESSAGE(JWRN_MUST_RESYNC,
  164672. "Corrupt JPEG data: found marker 0x%02x instead of RST%d")
  164673. JMESSAGE(JWRN_NOT_SEQUENTIAL, "Invalid SOS parameters for sequential JPEG")
  164674. JMESSAGE(JWRN_TOO_MUCH_DATA, "Application transferred too many scanlines")
  164675. #ifdef JMAKE_ENUM_LIST
  164676. JMSG_LASTMSGCODE
  164677. } J_MESSAGE_CODE;
  164678. #undef JMAKE_ENUM_LIST
  164679. #endif /* JMAKE_ENUM_LIST */
  164680. /* Zap JMESSAGE macro so that future re-inclusions do nothing by default */
  164681. #undef JMESSAGE
  164682. #ifndef JERROR_H
  164683. #define JERROR_H
  164684. /* Macros to simplify using the error and trace message stuff */
  164685. /* The first parameter is either type of cinfo pointer */
  164686. /* Fatal errors (print message and exit) */
  164687. #define ERREXIT(cinfo,code) \
  164688. ((cinfo)->err->msg_code = (code), \
  164689. (*(cinfo)->err->error_exit) ((j_common_ptr) (cinfo)))
  164690. #define ERREXIT1(cinfo,code,p1) \
  164691. ((cinfo)->err->msg_code = (code), \
  164692. (cinfo)->err->msg_parm.i[0] = (p1), \
  164693. (*(cinfo)->err->error_exit) ((j_common_ptr) (cinfo)))
  164694. #define ERREXIT2(cinfo,code,p1,p2) \
  164695. ((cinfo)->err->msg_code = (code), \
  164696. (cinfo)->err->msg_parm.i[0] = (p1), \
  164697. (cinfo)->err->msg_parm.i[1] = (p2), \
  164698. (*(cinfo)->err->error_exit) ((j_common_ptr) (cinfo)))
  164699. #define ERREXIT3(cinfo,code,p1,p2,p3) \
  164700. ((cinfo)->err->msg_code = (code), \
  164701. (cinfo)->err->msg_parm.i[0] = (p1), \
  164702. (cinfo)->err->msg_parm.i[1] = (p2), \
  164703. (cinfo)->err->msg_parm.i[2] = (p3), \
  164704. (*(cinfo)->err->error_exit) ((j_common_ptr) (cinfo)))
  164705. #define ERREXIT4(cinfo,code,p1,p2,p3,p4) \
  164706. ((cinfo)->err->msg_code = (code), \
  164707. (cinfo)->err->msg_parm.i[0] = (p1), \
  164708. (cinfo)->err->msg_parm.i[1] = (p2), \
  164709. (cinfo)->err->msg_parm.i[2] = (p3), \
  164710. (cinfo)->err->msg_parm.i[3] = (p4), \
  164711. (*(cinfo)->err->error_exit) ((j_common_ptr) (cinfo)))
  164712. #define ERREXITS(cinfo,code,str) \
  164713. ((cinfo)->err->msg_code = (code), \
  164714. strncpy((cinfo)->err->msg_parm.s, (str), JMSG_STR_PARM_MAX), \
  164715. (*(cinfo)->err->error_exit) ((j_common_ptr) (cinfo)))
  164716. #define MAKESTMT(stuff) do { stuff } while (0)
  164717. /* Nonfatal errors (we can keep going, but the data is probably corrupt) */
  164718. #define WARNMS(cinfo,code) \
  164719. ((cinfo)->err->msg_code = (code), \
  164720. (*(cinfo)->err->emit_message) ((j_common_ptr) (cinfo), -1))
  164721. #define WARNMS1(cinfo,code,p1) \
  164722. ((cinfo)->err->msg_code = (code), \
  164723. (cinfo)->err->msg_parm.i[0] = (p1), \
  164724. (*(cinfo)->err->emit_message) ((j_common_ptr) (cinfo), -1))
  164725. #define WARNMS2(cinfo,code,p1,p2) \
  164726. ((cinfo)->err->msg_code = (code), \
  164727. (cinfo)->err->msg_parm.i[0] = (p1), \
  164728. (cinfo)->err->msg_parm.i[1] = (p2), \
  164729. (*(cinfo)->err->emit_message) ((j_common_ptr) (cinfo), -1))
  164730. /* Informational/debugging messages */
  164731. #define TRACEMS(cinfo,lvl,code) \
  164732. ((cinfo)->err->msg_code = (code), \
  164733. (*(cinfo)->err->emit_message) ((j_common_ptr) (cinfo), (lvl)))
  164734. #define TRACEMS1(cinfo,lvl,code,p1) \
  164735. ((cinfo)->err->msg_code = (code), \
  164736. (cinfo)->err->msg_parm.i[0] = (p1), \
  164737. (*(cinfo)->err->emit_message) ((j_common_ptr) (cinfo), (lvl)))
  164738. #define TRACEMS2(cinfo,lvl,code,p1,p2) \
  164739. ((cinfo)->err->msg_code = (code), \
  164740. (cinfo)->err->msg_parm.i[0] = (p1), \
  164741. (cinfo)->err->msg_parm.i[1] = (p2), \
  164742. (*(cinfo)->err->emit_message) ((j_common_ptr) (cinfo), (lvl)))
  164743. #define TRACEMS3(cinfo,lvl,code,p1,p2,p3) \
  164744. MAKESTMT(int * _mp = (cinfo)->err->msg_parm.i; \
  164745. _mp[0] = (p1); _mp[1] = (p2); _mp[2] = (p3); \
  164746. (cinfo)->err->msg_code = (code); \
  164747. (*(cinfo)->err->emit_message) ((j_common_ptr) (cinfo), (lvl)); )
  164748. #define TRACEMS4(cinfo,lvl,code,p1,p2,p3,p4) \
  164749. MAKESTMT(int * _mp = (cinfo)->err->msg_parm.i; \
  164750. _mp[0] = (p1); _mp[1] = (p2); _mp[2] = (p3); _mp[3] = (p4); \
  164751. (cinfo)->err->msg_code = (code); \
  164752. (*(cinfo)->err->emit_message) ((j_common_ptr) (cinfo), (lvl)); )
  164753. #define TRACEMS5(cinfo,lvl,code,p1,p2,p3,p4,p5) \
  164754. MAKESTMT(int * _mp = (cinfo)->err->msg_parm.i; \
  164755. _mp[0] = (p1); _mp[1] = (p2); _mp[2] = (p3); _mp[3] = (p4); \
  164756. _mp[4] = (p5); \
  164757. (cinfo)->err->msg_code = (code); \
  164758. (*(cinfo)->err->emit_message) ((j_common_ptr) (cinfo), (lvl)); )
  164759. #define TRACEMS8(cinfo,lvl,code,p1,p2,p3,p4,p5,p6,p7,p8) \
  164760. MAKESTMT(int * _mp = (cinfo)->err->msg_parm.i; \
  164761. _mp[0] = (p1); _mp[1] = (p2); _mp[2] = (p3); _mp[3] = (p4); \
  164762. _mp[4] = (p5); _mp[5] = (p6); _mp[6] = (p7); _mp[7] = (p8); \
  164763. (cinfo)->err->msg_code = (code); \
  164764. (*(cinfo)->err->emit_message) ((j_common_ptr) (cinfo), (lvl)); )
  164765. #define TRACEMSS(cinfo,lvl,code,str) \
  164766. ((cinfo)->err->msg_code = (code), \
  164767. strncpy((cinfo)->err->msg_parm.s, (str), JMSG_STR_PARM_MAX), \
  164768. (*(cinfo)->err->emit_message) ((j_common_ptr) (cinfo), (lvl)))
  164769. #endif /* JERROR_H */
  164770. /*** End of inlined file: jerror.h ***/
  164771. /* Expanded data source object for stdio input */
  164772. typedef struct {
  164773. struct jpeg_source_mgr pub; /* public fields */
  164774. FILE * infile; /* source stream */
  164775. JOCTET * buffer; /* start of buffer */
  164776. boolean start_of_file; /* have we gotten any data yet? */
  164777. } my_source_mgr;
  164778. typedef my_source_mgr * my_src_ptr;
  164779. #define INPUT_BUF_SIZE 4096 /* choose an efficiently fread'able size */
  164780. /*
  164781. * Initialize source --- called by jpeg_read_header
  164782. * before any data is actually read.
  164783. */
  164784. METHODDEF(void)
  164785. init_source (j_decompress_ptr cinfo)
  164786. {
  164787. my_src_ptr src = (my_src_ptr) cinfo->src;
  164788. /* We reset the empty-input-file flag for each image,
  164789. * but we don't clear the input buffer.
  164790. * This is correct behavior for reading a series of images from one source.
  164791. */
  164792. src->start_of_file = TRUE;
  164793. }
  164794. /*
  164795. * Fill the input buffer --- called whenever buffer is emptied.
  164796. *
  164797. * In typical applications, this should read fresh data into the buffer
  164798. * (ignoring the current state of next_input_byte & bytes_in_buffer),
  164799. * reset the pointer & count to the start of the buffer, and return TRUE
  164800. * indicating that the buffer has been reloaded. It is not necessary to
  164801. * fill the buffer entirely, only to obtain at least one more byte.
  164802. *
  164803. * There is no such thing as an EOF return. If the end of the file has been
  164804. * reached, the routine has a choice of ERREXIT() or inserting fake data into
  164805. * the buffer. In most cases, generating a warning message and inserting a
  164806. * fake EOI marker is the best course of action --- this will allow the
  164807. * decompressor to output however much of the image is there. However,
  164808. * the resulting error message is misleading if the real problem is an empty
  164809. * input file, so we handle that case specially.
  164810. *
  164811. * In applications that need to be able to suspend compression due to input
  164812. * not being available yet, a FALSE return indicates that no more data can be
  164813. * obtained right now, but more may be forthcoming later. In this situation,
  164814. * the decompressor will return to its caller (with an indication of the
  164815. * number of scanlines it has read, if any). The application should resume
  164816. * decompression after it has loaded more data into the input buffer. Note
  164817. * that there are substantial restrictions on the use of suspension --- see
  164818. * the documentation.
  164819. *
  164820. * When suspending, the decompressor will back up to a convenient restart point
  164821. * (typically the start of the current MCU). next_input_byte & bytes_in_buffer
  164822. * indicate where the restart point will be if the current call returns FALSE.
  164823. * Data beyond this point must be rescanned after resumption, so move it to
  164824. * the front of the buffer rather than discarding it.
  164825. */
  164826. METHODDEF(boolean)
  164827. fill_input_buffer (j_decompress_ptr cinfo)
  164828. {
  164829. my_src_ptr src = (my_src_ptr) cinfo->src;
  164830. size_t nbytes;
  164831. nbytes = JFREAD(src->infile, src->buffer, INPUT_BUF_SIZE);
  164832. if (nbytes <= 0) {
  164833. if (src->start_of_file) /* Treat empty input file as fatal error */
  164834. ERREXIT(cinfo, JERR_INPUT_EMPTY);
  164835. WARNMS(cinfo, JWRN_JPEG_EOF);
  164836. /* Insert a fake EOI marker */
  164837. src->buffer[0] = (JOCTET) 0xFF;
  164838. src->buffer[1] = (JOCTET) JPEG_EOI;
  164839. nbytes = 2;
  164840. }
  164841. src->pub.next_input_byte = src->buffer;
  164842. src->pub.bytes_in_buffer = nbytes;
  164843. src->start_of_file = FALSE;
  164844. return TRUE;
  164845. }
  164846. /*
  164847. * Skip data --- used to skip over a potentially large amount of
  164848. * uninteresting data (such as an APPn marker).
  164849. *
  164850. * Writers of suspendable-input applications must note that skip_input_data
  164851. * is not granted the right to give a suspension return. If the skip extends
  164852. * beyond the data currently in the buffer, the buffer can be marked empty so
  164853. * that the next read will cause a fill_input_buffer call that can suspend.
  164854. * Arranging for additional bytes to be discarded before reloading the input
  164855. * buffer is the application writer's problem.
  164856. */
  164857. METHODDEF(void)
  164858. skip_input_data (j_decompress_ptr cinfo, long num_bytes)
  164859. {
  164860. my_src_ptr src = (my_src_ptr) cinfo->src;
  164861. /* Just a dumb implementation for now. Could use fseek() except
  164862. * it doesn't work on pipes. Not clear that being smart is worth
  164863. * any trouble anyway --- large skips are infrequent.
  164864. */
  164865. if (num_bytes > 0) {
  164866. while (num_bytes > (long) src->pub.bytes_in_buffer) {
  164867. num_bytes -= (long) src->pub.bytes_in_buffer;
  164868. (void) fill_input_buffer(cinfo);
  164869. /* note we assume that fill_input_buffer will never return FALSE,
  164870. * so suspension need not be handled.
  164871. */
  164872. }
  164873. src->pub.next_input_byte += (size_t) num_bytes;
  164874. src->pub.bytes_in_buffer -= (size_t) num_bytes;
  164875. }
  164876. }
  164877. /*
  164878. * An additional method that can be provided by data source modules is the
  164879. * resync_to_restart method for error recovery in the presence of RST markers.
  164880. * For the moment, this source module just uses the default resync method
  164881. * provided by the JPEG library. That method assumes that no backtracking
  164882. * is possible.
  164883. */
  164884. /*
  164885. * Terminate source --- called by jpeg_finish_decompress
  164886. * after all data has been read. Often a no-op.
  164887. *
  164888. * NB: *not* called by jpeg_abort or jpeg_destroy; surrounding
  164889. * application must deal with any cleanup that should happen even
  164890. * for error exit.
  164891. */
  164892. METHODDEF(void)
  164893. term_source (j_decompress_ptr cinfo)
  164894. {
  164895. /* no work necessary here */
  164896. }
  164897. /*
  164898. * Prepare for input from a stdio stream.
  164899. * The caller must have already opened the stream, and is responsible
  164900. * for closing it after finishing decompression.
  164901. */
  164902. GLOBAL(void)
  164903. jpeg_stdio_src (j_decompress_ptr cinfo, FILE * infile)
  164904. {
  164905. my_src_ptr src;
  164906. /* The source object and input buffer are made permanent so that a series
  164907. * of JPEG images can be read from the same file by calling jpeg_stdio_src
  164908. * only before the first one. (If we discarded the buffer at the end of
  164909. * one image, we'd likely lose the start of the next one.)
  164910. * This makes it unsafe to use this manager and a different source
  164911. * manager serially with the same JPEG object. Caveat programmer.
  164912. */
  164913. if (cinfo->src == NULL) { /* first time for this JPEG object? */
  164914. cinfo->src = (struct jpeg_source_mgr *)
  164915. (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_PERMANENT,
  164916. SIZEOF(my_source_mgr));
  164917. src = (my_src_ptr) cinfo->src;
  164918. src->buffer = (JOCTET *)
  164919. (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_PERMANENT,
  164920. INPUT_BUF_SIZE * SIZEOF(JOCTET));
  164921. }
  164922. src = (my_src_ptr) cinfo->src;
  164923. src->pub.init_source = init_source;
  164924. src->pub.fill_input_buffer = fill_input_buffer;
  164925. src->pub.skip_input_data = skip_input_data;
  164926. src->pub.resync_to_restart = jpeg_resync_to_restart; /* use default method */
  164927. src->pub.term_source = term_source;
  164928. src->infile = infile;
  164929. src->pub.bytes_in_buffer = 0; /* forces fill_input_buffer on first read */
  164930. src->pub.next_input_byte = NULL; /* until buffer loaded */
  164931. }
  164932. /*** End of inlined file: jdatasrc.c ***/
  164933. /*** Start of inlined file: jdcoefct.c ***/
  164934. #define JPEG_INTERNALS
  164935. /* Block smoothing is only applicable for progressive JPEG, so: */
  164936. #ifndef D_PROGRESSIVE_SUPPORTED
  164937. #undef BLOCK_SMOOTHING_SUPPORTED
  164938. #endif
  164939. /* Private buffer controller object */
  164940. typedef struct {
  164941. struct jpeg_d_coef_controller pub; /* public fields */
  164942. /* These variables keep track of the current location of the input side. */
  164943. /* cinfo->input_iMCU_row is also used for this. */
  164944. JDIMENSION MCU_ctr; /* counts MCUs processed in current row */
  164945. int MCU_vert_offset; /* counts MCU rows within iMCU row */
  164946. int MCU_rows_per_iMCU_row; /* number of such rows needed */
  164947. /* The output side's location is represented by cinfo->output_iMCU_row. */
  164948. /* In single-pass modes, it's sufficient to buffer just one MCU.
  164949. * We allocate a workspace of D_MAX_BLOCKS_IN_MCU coefficient blocks,
  164950. * and let the entropy decoder write into that workspace each time.
  164951. * (On 80x86, the workspace is FAR even though it's not really very big;
  164952. * this is to keep the module interfaces unchanged when a large coefficient
  164953. * buffer is necessary.)
  164954. * In multi-pass modes, this array points to the current MCU's blocks
  164955. * within the virtual arrays; it is used only by the input side.
  164956. */
  164957. JBLOCKROW MCU_buffer[D_MAX_BLOCKS_IN_MCU];
  164958. #ifdef D_MULTISCAN_FILES_SUPPORTED
  164959. /* In multi-pass modes, we need a virtual block array for each component. */
  164960. jvirt_barray_ptr whole_image[MAX_COMPONENTS];
  164961. #endif
  164962. #ifdef BLOCK_SMOOTHING_SUPPORTED
  164963. /* When doing block smoothing, we latch coefficient Al values here */
  164964. int * coef_bits_latch;
  164965. #define SAVED_COEFS 6 /* we save coef_bits[0..5] */
  164966. #endif
  164967. } my_coef_controller3;
  164968. typedef my_coef_controller3 * my_coef_ptr3;
  164969. /* Forward declarations */
  164970. METHODDEF(int) decompress_onepass
  164971. JPP((j_decompress_ptr cinfo, JSAMPIMAGE output_buf));
  164972. #ifdef D_MULTISCAN_FILES_SUPPORTED
  164973. METHODDEF(int) decompress_data
  164974. JPP((j_decompress_ptr cinfo, JSAMPIMAGE output_buf));
  164975. #endif
  164976. #ifdef BLOCK_SMOOTHING_SUPPORTED
  164977. LOCAL(boolean) smoothing_ok JPP((j_decompress_ptr cinfo));
  164978. METHODDEF(int) decompress_smooth_data
  164979. JPP((j_decompress_ptr cinfo, JSAMPIMAGE output_buf));
  164980. #endif
  164981. LOCAL(void)
  164982. start_iMCU_row3 (j_decompress_ptr cinfo)
  164983. /* Reset within-iMCU-row counters for a new row (input side) */
  164984. {
  164985. my_coef_ptr3 coef = (my_coef_ptr3) cinfo->coef;
  164986. /* In an interleaved scan, an MCU row is the same as an iMCU row.
  164987. * In a noninterleaved scan, an iMCU row has v_samp_factor MCU rows.
  164988. * But at the bottom of the image, process only what's left.
  164989. */
  164990. if (cinfo->comps_in_scan > 1) {
  164991. coef->MCU_rows_per_iMCU_row = 1;
  164992. } else {
  164993. if (cinfo->input_iMCU_row < (cinfo->total_iMCU_rows-1))
  164994. coef->MCU_rows_per_iMCU_row = cinfo->cur_comp_info[0]->v_samp_factor;
  164995. else
  164996. coef->MCU_rows_per_iMCU_row = cinfo->cur_comp_info[0]->last_row_height;
  164997. }
  164998. coef->MCU_ctr = 0;
  164999. coef->MCU_vert_offset = 0;
  165000. }
  165001. /*
  165002. * Initialize for an input processing pass.
  165003. */
  165004. METHODDEF(void)
  165005. start_input_pass (j_decompress_ptr cinfo)
  165006. {
  165007. cinfo->input_iMCU_row = 0;
  165008. start_iMCU_row3(cinfo);
  165009. }
  165010. /*
  165011. * Initialize for an output processing pass.
  165012. */
  165013. METHODDEF(void)
  165014. start_output_pass (j_decompress_ptr cinfo)
  165015. {
  165016. #ifdef BLOCK_SMOOTHING_SUPPORTED
  165017. my_coef_ptr3 coef = (my_coef_ptr3) cinfo->coef;
  165018. /* If multipass, check to see whether to use block smoothing on this pass */
  165019. if (coef->pub.coef_arrays != NULL) {
  165020. if (cinfo->do_block_smoothing && smoothing_ok(cinfo))
  165021. coef->pub.decompress_data = decompress_smooth_data;
  165022. else
  165023. coef->pub.decompress_data = decompress_data;
  165024. }
  165025. #endif
  165026. cinfo->output_iMCU_row = 0;
  165027. }
  165028. /*
  165029. * Decompress and return some data in the single-pass case.
  165030. * Always attempts to emit one fully interleaved MCU row ("iMCU" row).
  165031. * Input and output must run in lockstep since we have only a one-MCU buffer.
  165032. * Return value is JPEG_ROW_COMPLETED, JPEG_SCAN_COMPLETED, or JPEG_SUSPENDED.
  165033. *
  165034. * NB: output_buf contains a plane for each component in image,
  165035. * which we index according to the component's SOF position.
  165036. */
  165037. METHODDEF(int)
  165038. decompress_onepass (j_decompress_ptr cinfo, JSAMPIMAGE output_buf)
  165039. {
  165040. my_coef_ptr3 coef = (my_coef_ptr3) cinfo->coef;
  165041. JDIMENSION MCU_col_num; /* index of current MCU within row */
  165042. JDIMENSION last_MCU_col = cinfo->MCUs_per_row - 1;
  165043. JDIMENSION last_iMCU_row = cinfo->total_iMCU_rows - 1;
  165044. int blkn, ci, xindex, yindex, yoffset, useful_width;
  165045. JSAMPARRAY output_ptr;
  165046. JDIMENSION start_col, output_col;
  165047. jpeg_component_info *compptr;
  165048. inverse_DCT_method_ptr inverse_DCT;
  165049. /* Loop to process as much as one whole iMCU row */
  165050. for (yoffset = coef->MCU_vert_offset; yoffset < coef->MCU_rows_per_iMCU_row;
  165051. yoffset++) {
  165052. for (MCU_col_num = coef->MCU_ctr; MCU_col_num <= last_MCU_col;
  165053. MCU_col_num++) {
  165054. /* Try to fetch an MCU. Entropy decoder expects buffer to be zeroed. */
  165055. jzero_far((void FAR *) coef->MCU_buffer[0],
  165056. (size_t) (cinfo->blocks_in_MCU * SIZEOF(JBLOCK)));
  165057. if (! (*cinfo->entropy->decode_mcu) (cinfo, coef->MCU_buffer)) {
  165058. /* Suspension forced; update state counters and exit */
  165059. coef->MCU_vert_offset = yoffset;
  165060. coef->MCU_ctr = MCU_col_num;
  165061. return JPEG_SUSPENDED;
  165062. }
  165063. /* Determine where data should go in output_buf and do the IDCT thing.
  165064. * We skip dummy blocks at the right and bottom edges (but blkn gets
  165065. * incremented past them!). Note the inner loop relies on having
  165066. * allocated the MCU_buffer[] blocks sequentially.
  165067. */
  165068. blkn = 0; /* index of current DCT block within MCU */
  165069. for (ci = 0; ci < cinfo->comps_in_scan; ci++) {
  165070. compptr = cinfo->cur_comp_info[ci];
  165071. /* Don't bother to IDCT an uninteresting component. */
  165072. if (! compptr->component_needed) {
  165073. blkn += compptr->MCU_blocks;
  165074. continue;
  165075. }
  165076. inverse_DCT = cinfo->idct->inverse_DCT[compptr->component_index];
  165077. useful_width = (MCU_col_num < last_MCU_col) ? compptr->MCU_width
  165078. : compptr->last_col_width;
  165079. output_ptr = output_buf[compptr->component_index] +
  165080. yoffset * compptr->DCT_scaled_size;
  165081. start_col = MCU_col_num * compptr->MCU_sample_width;
  165082. for (yindex = 0; yindex < compptr->MCU_height; yindex++) {
  165083. if (cinfo->input_iMCU_row < last_iMCU_row ||
  165084. yoffset+yindex < compptr->last_row_height) {
  165085. output_col = start_col;
  165086. for (xindex = 0; xindex < useful_width; xindex++) {
  165087. (*inverse_DCT) (cinfo, compptr,
  165088. (JCOEFPTR) coef->MCU_buffer[blkn+xindex],
  165089. output_ptr, output_col);
  165090. output_col += compptr->DCT_scaled_size;
  165091. }
  165092. }
  165093. blkn += compptr->MCU_width;
  165094. output_ptr += compptr->DCT_scaled_size;
  165095. }
  165096. }
  165097. }
  165098. /* Completed an MCU row, but perhaps not an iMCU row */
  165099. coef->MCU_ctr = 0;
  165100. }
  165101. /* Completed the iMCU row, advance counters for next one */
  165102. cinfo->output_iMCU_row++;
  165103. if (++(cinfo->input_iMCU_row) < cinfo->total_iMCU_rows) {
  165104. start_iMCU_row3(cinfo);
  165105. return JPEG_ROW_COMPLETED;
  165106. }
  165107. /* Completed the scan */
  165108. (*cinfo->inputctl->finish_input_pass) (cinfo);
  165109. return JPEG_SCAN_COMPLETED;
  165110. }
  165111. /*
  165112. * Dummy consume-input routine for single-pass operation.
  165113. */
  165114. METHODDEF(int)
  165115. dummy_consume_data (j_decompress_ptr cinfo)
  165116. {
  165117. return JPEG_SUSPENDED; /* Always indicate nothing was done */
  165118. }
  165119. #ifdef D_MULTISCAN_FILES_SUPPORTED
  165120. /*
  165121. * Consume input data and store it in the full-image coefficient buffer.
  165122. * We read as much as one fully interleaved MCU row ("iMCU" row) per call,
  165123. * ie, v_samp_factor block rows for each component in the scan.
  165124. * Return value is JPEG_ROW_COMPLETED, JPEG_SCAN_COMPLETED, or JPEG_SUSPENDED.
  165125. */
  165126. METHODDEF(int)
  165127. consume_data (j_decompress_ptr cinfo)
  165128. {
  165129. my_coef_ptr3 coef = (my_coef_ptr3) cinfo->coef;
  165130. JDIMENSION MCU_col_num; /* index of current MCU within row */
  165131. int blkn, ci, xindex, yindex, yoffset;
  165132. JDIMENSION start_col;
  165133. JBLOCKARRAY buffer[MAX_COMPS_IN_SCAN];
  165134. JBLOCKROW buffer_ptr;
  165135. jpeg_component_info *compptr;
  165136. /* Align the virtual buffers for the components used in this scan. */
  165137. for (ci = 0; ci < cinfo->comps_in_scan; ci++) {
  165138. compptr = cinfo->cur_comp_info[ci];
  165139. buffer[ci] = (*cinfo->mem->access_virt_barray)
  165140. ((j_common_ptr) cinfo, coef->whole_image[compptr->component_index],
  165141. cinfo->input_iMCU_row * compptr->v_samp_factor,
  165142. (JDIMENSION) compptr->v_samp_factor, TRUE);
  165143. /* Note: entropy decoder expects buffer to be zeroed,
  165144. * but this is handled automatically by the memory manager
  165145. * because we requested a pre-zeroed array.
  165146. */
  165147. }
  165148. /* Loop to process one whole iMCU row */
  165149. for (yoffset = coef->MCU_vert_offset; yoffset < coef->MCU_rows_per_iMCU_row;
  165150. yoffset++) {
  165151. for (MCU_col_num = coef->MCU_ctr; MCU_col_num < cinfo->MCUs_per_row;
  165152. MCU_col_num++) {
  165153. /* Construct list of pointers to DCT blocks belonging to this MCU */
  165154. blkn = 0; /* index of current DCT block within MCU */
  165155. for (ci = 0; ci < cinfo->comps_in_scan; ci++) {
  165156. compptr = cinfo->cur_comp_info[ci];
  165157. start_col = MCU_col_num * compptr->MCU_width;
  165158. for (yindex = 0; yindex < compptr->MCU_height; yindex++) {
  165159. buffer_ptr = buffer[ci][yindex+yoffset] + start_col;
  165160. for (xindex = 0; xindex < compptr->MCU_width; xindex++) {
  165161. coef->MCU_buffer[blkn++] = buffer_ptr++;
  165162. }
  165163. }
  165164. }
  165165. /* Try to fetch the MCU. */
  165166. if (! (*cinfo->entropy->decode_mcu) (cinfo, coef->MCU_buffer)) {
  165167. /* Suspension forced; update state counters and exit */
  165168. coef->MCU_vert_offset = yoffset;
  165169. coef->MCU_ctr = MCU_col_num;
  165170. return JPEG_SUSPENDED;
  165171. }
  165172. }
  165173. /* Completed an MCU row, but perhaps not an iMCU row */
  165174. coef->MCU_ctr = 0;
  165175. }
  165176. /* Completed the iMCU row, advance counters for next one */
  165177. if (++(cinfo->input_iMCU_row) < cinfo->total_iMCU_rows) {
  165178. start_iMCU_row3(cinfo);
  165179. return JPEG_ROW_COMPLETED;
  165180. }
  165181. /* Completed the scan */
  165182. (*cinfo->inputctl->finish_input_pass) (cinfo);
  165183. return JPEG_SCAN_COMPLETED;
  165184. }
  165185. /*
  165186. * Decompress and return some data in the multi-pass case.
  165187. * Always attempts to emit one fully interleaved MCU row ("iMCU" row).
  165188. * Return value is JPEG_ROW_COMPLETED, JPEG_SCAN_COMPLETED, or JPEG_SUSPENDED.
  165189. *
  165190. * NB: output_buf contains a plane for each component in image.
  165191. */
  165192. METHODDEF(int)
  165193. decompress_data (j_decompress_ptr cinfo, JSAMPIMAGE output_buf)
  165194. {
  165195. my_coef_ptr3 coef = (my_coef_ptr3) cinfo->coef;
  165196. JDIMENSION last_iMCU_row = cinfo->total_iMCU_rows - 1;
  165197. JDIMENSION block_num;
  165198. int ci, block_row, block_rows;
  165199. JBLOCKARRAY buffer;
  165200. JBLOCKROW buffer_ptr;
  165201. JSAMPARRAY output_ptr;
  165202. JDIMENSION output_col;
  165203. jpeg_component_info *compptr;
  165204. inverse_DCT_method_ptr inverse_DCT;
  165205. /* Force some input to be done if we are getting ahead of the input. */
  165206. while (cinfo->input_scan_number < cinfo->output_scan_number ||
  165207. (cinfo->input_scan_number == cinfo->output_scan_number &&
  165208. cinfo->input_iMCU_row <= cinfo->output_iMCU_row)) {
  165209. if ((*cinfo->inputctl->consume_input)(cinfo) == JPEG_SUSPENDED)
  165210. return JPEG_SUSPENDED;
  165211. }
  165212. /* OK, output from the virtual arrays. */
  165213. for (ci = 0, compptr = cinfo->comp_info; ci < cinfo->num_components;
  165214. ci++, compptr++) {
  165215. /* Don't bother to IDCT an uninteresting component. */
  165216. if (! compptr->component_needed)
  165217. continue;
  165218. /* Align the virtual buffer for this component. */
  165219. buffer = (*cinfo->mem->access_virt_barray)
  165220. ((j_common_ptr) cinfo, coef->whole_image[ci],
  165221. cinfo->output_iMCU_row * compptr->v_samp_factor,
  165222. (JDIMENSION) compptr->v_samp_factor, FALSE);
  165223. /* Count non-dummy DCT block rows in this iMCU row. */
  165224. if (cinfo->output_iMCU_row < last_iMCU_row)
  165225. block_rows = compptr->v_samp_factor;
  165226. else {
  165227. /* NB: can't use last_row_height here; it is input-side-dependent! */
  165228. block_rows = (int) (compptr->height_in_blocks % compptr->v_samp_factor);
  165229. if (block_rows == 0) block_rows = compptr->v_samp_factor;
  165230. }
  165231. inverse_DCT = cinfo->idct->inverse_DCT[ci];
  165232. output_ptr = output_buf[ci];
  165233. /* Loop over all DCT blocks to be processed. */
  165234. for (block_row = 0; block_row < block_rows; block_row++) {
  165235. buffer_ptr = buffer[block_row];
  165236. output_col = 0;
  165237. for (block_num = 0; block_num < compptr->width_in_blocks; block_num++) {
  165238. (*inverse_DCT) (cinfo, compptr, (JCOEFPTR) buffer_ptr,
  165239. output_ptr, output_col);
  165240. buffer_ptr++;
  165241. output_col += compptr->DCT_scaled_size;
  165242. }
  165243. output_ptr += compptr->DCT_scaled_size;
  165244. }
  165245. }
  165246. if (++(cinfo->output_iMCU_row) < cinfo->total_iMCU_rows)
  165247. return JPEG_ROW_COMPLETED;
  165248. return JPEG_SCAN_COMPLETED;
  165249. }
  165250. #endif /* D_MULTISCAN_FILES_SUPPORTED */
  165251. #ifdef BLOCK_SMOOTHING_SUPPORTED
  165252. /*
  165253. * This code applies interblock smoothing as described by section K.8
  165254. * of the JPEG standard: the first 5 AC coefficients are estimated from
  165255. * the DC values of a DCT block and its 8 neighboring blocks.
  165256. * We apply smoothing only for progressive JPEG decoding, and only if
  165257. * the coefficients it can estimate are not yet known to full precision.
  165258. */
  165259. /* Natural-order array positions of the first 5 zigzag-order coefficients */
  165260. #define Q01_POS 1
  165261. #define Q10_POS 8
  165262. #define Q20_POS 16
  165263. #define Q11_POS 9
  165264. #define Q02_POS 2
  165265. /*
  165266. * Determine whether block smoothing is applicable and safe.
  165267. * We also latch the current states of the coef_bits[] entries for the
  165268. * AC coefficients; otherwise, if the input side of the decompressor
  165269. * advances into a new scan, we might think the coefficients are known
  165270. * more accurately than they really are.
  165271. */
  165272. LOCAL(boolean)
  165273. smoothing_ok (j_decompress_ptr cinfo)
  165274. {
  165275. my_coef_ptr3 coef = (my_coef_ptr3) cinfo->coef;
  165276. boolean smoothing_useful = FALSE;
  165277. int ci, coefi;
  165278. jpeg_component_info *compptr;
  165279. JQUANT_TBL * qtable;
  165280. int * coef_bits;
  165281. int * coef_bits_latch;
  165282. if (! cinfo->progressive_mode || cinfo->coef_bits == NULL)
  165283. return FALSE;
  165284. /* Allocate latch area if not already done */
  165285. if (coef->coef_bits_latch == NULL)
  165286. coef->coef_bits_latch = (int *)
  165287. (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_IMAGE,
  165288. cinfo->num_components *
  165289. (SAVED_COEFS * SIZEOF(int)));
  165290. coef_bits_latch = coef->coef_bits_latch;
  165291. for (ci = 0, compptr = cinfo->comp_info; ci < cinfo->num_components;
  165292. ci++, compptr++) {
  165293. /* All components' quantization values must already be latched. */
  165294. if ((qtable = compptr->quant_table) == NULL)
  165295. return FALSE;
  165296. /* Verify DC & first 5 AC quantizers are nonzero to avoid zero-divide. */
  165297. if (qtable->quantval[0] == 0 ||
  165298. qtable->quantval[Q01_POS] == 0 ||
  165299. qtable->quantval[Q10_POS] == 0 ||
  165300. qtable->quantval[Q20_POS] == 0 ||
  165301. qtable->quantval[Q11_POS] == 0 ||
  165302. qtable->quantval[Q02_POS] == 0)
  165303. return FALSE;
  165304. /* DC values must be at least partly known for all components. */
  165305. coef_bits = cinfo->coef_bits[ci];
  165306. if (coef_bits[0] < 0)
  165307. return FALSE;
  165308. /* Block smoothing is helpful if some AC coefficients remain inaccurate. */
  165309. for (coefi = 1; coefi <= 5; coefi++) {
  165310. coef_bits_latch[coefi] = coef_bits[coefi];
  165311. if (coef_bits[coefi] != 0)
  165312. smoothing_useful = TRUE;
  165313. }
  165314. coef_bits_latch += SAVED_COEFS;
  165315. }
  165316. return smoothing_useful;
  165317. }
  165318. /*
  165319. * Variant of decompress_data for use when doing block smoothing.
  165320. */
  165321. METHODDEF(int)
  165322. decompress_smooth_data (j_decompress_ptr cinfo, JSAMPIMAGE output_buf)
  165323. {
  165324. my_coef_ptr3 coef = (my_coef_ptr3) cinfo->coef;
  165325. JDIMENSION last_iMCU_row = cinfo->total_iMCU_rows - 1;
  165326. JDIMENSION block_num, last_block_column;
  165327. int ci, block_row, block_rows, access_rows;
  165328. JBLOCKARRAY buffer;
  165329. JBLOCKROW buffer_ptr, prev_block_row, next_block_row;
  165330. JSAMPARRAY output_ptr;
  165331. JDIMENSION output_col;
  165332. jpeg_component_info *compptr;
  165333. inverse_DCT_method_ptr inverse_DCT;
  165334. boolean first_row, last_row;
  165335. JBLOCK workspace;
  165336. int *coef_bits;
  165337. JQUANT_TBL *quanttbl;
  165338. INT32 Q00,Q01,Q02,Q10,Q11,Q20, num;
  165339. int DC1,DC2,DC3,DC4,DC5,DC6,DC7,DC8,DC9;
  165340. int Al, pred;
  165341. /* Force some input to be done if we are getting ahead of the input. */
  165342. while (cinfo->input_scan_number <= cinfo->output_scan_number &&
  165343. ! cinfo->inputctl->eoi_reached) {
  165344. if (cinfo->input_scan_number == cinfo->output_scan_number) {
  165345. /* If input is working on current scan, we ordinarily want it to
  165346. * have completed the current row. But if input scan is DC,
  165347. * we want it to keep one row ahead so that next block row's DC
  165348. * values are up to date.
  165349. */
  165350. JDIMENSION delta = (cinfo->Ss == 0) ? 1 : 0;
  165351. if (cinfo->input_iMCU_row > cinfo->output_iMCU_row+delta)
  165352. break;
  165353. }
  165354. if ((*cinfo->inputctl->consume_input)(cinfo) == JPEG_SUSPENDED)
  165355. return JPEG_SUSPENDED;
  165356. }
  165357. /* OK, output from the virtual arrays. */
  165358. for (ci = 0, compptr = cinfo->comp_info; ci < cinfo->num_components;
  165359. ci++, compptr++) {
  165360. /* Don't bother to IDCT an uninteresting component. */
  165361. if (! compptr->component_needed)
  165362. continue;
  165363. /* Count non-dummy DCT block rows in this iMCU row. */
  165364. if (cinfo->output_iMCU_row < last_iMCU_row) {
  165365. block_rows = compptr->v_samp_factor;
  165366. access_rows = block_rows * 2; /* this and next iMCU row */
  165367. last_row = FALSE;
  165368. } else {
  165369. /* NB: can't use last_row_height here; it is input-side-dependent! */
  165370. block_rows = (int) (compptr->height_in_blocks % compptr->v_samp_factor);
  165371. if (block_rows == 0) block_rows = compptr->v_samp_factor;
  165372. access_rows = block_rows; /* this iMCU row only */
  165373. last_row = TRUE;
  165374. }
  165375. /* Align the virtual buffer for this component. */
  165376. if (cinfo->output_iMCU_row > 0) {
  165377. access_rows += compptr->v_samp_factor; /* prior iMCU row too */
  165378. buffer = (*cinfo->mem->access_virt_barray)
  165379. ((j_common_ptr) cinfo, coef->whole_image[ci],
  165380. (cinfo->output_iMCU_row - 1) * compptr->v_samp_factor,
  165381. (JDIMENSION) access_rows, FALSE);
  165382. buffer += compptr->v_samp_factor; /* point to current iMCU row */
  165383. first_row = FALSE;
  165384. } else {
  165385. buffer = (*cinfo->mem->access_virt_barray)
  165386. ((j_common_ptr) cinfo, coef->whole_image[ci],
  165387. (JDIMENSION) 0, (JDIMENSION) access_rows, FALSE);
  165388. first_row = TRUE;
  165389. }
  165390. /* Fetch component-dependent info */
  165391. coef_bits = coef->coef_bits_latch + (ci * SAVED_COEFS);
  165392. quanttbl = compptr->quant_table;
  165393. Q00 = quanttbl->quantval[0];
  165394. Q01 = quanttbl->quantval[Q01_POS];
  165395. Q10 = quanttbl->quantval[Q10_POS];
  165396. Q20 = quanttbl->quantval[Q20_POS];
  165397. Q11 = quanttbl->quantval[Q11_POS];
  165398. Q02 = quanttbl->quantval[Q02_POS];
  165399. inverse_DCT = cinfo->idct->inverse_DCT[ci];
  165400. output_ptr = output_buf[ci];
  165401. /* Loop over all DCT blocks to be processed. */
  165402. for (block_row = 0; block_row < block_rows; block_row++) {
  165403. buffer_ptr = buffer[block_row];
  165404. if (first_row && block_row == 0)
  165405. prev_block_row = buffer_ptr;
  165406. else
  165407. prev_block_row = buffer[block_row-1];
  165408. if (last_row && block_row == block_rows-1)
  165409. next_block_row = buffer_ptr;
  165410. else
  165411. next_block_row = buffer[block_row+1];
  165412. /* We fetch the surrounding DC values using a sliding-register approach.
  165413. * Initialize all nine here so as to do the right thing on narrow pics.
  165414. */
  165415. DC1 = DC2 = DC3 = (int) prev_block_row[0][0];
  165416. DC4 = DC5 = DC6 = (int) buffer_ptr[0][0];
  165417. DC7 = DC8 = DC9 = (int) next_block_row[0][0];
  165418. output_col = 0;
  165419. last_block_column = compptr->width_in_blocks - 1;
  165420. for (block_num = 0; block_num <= last_block_column; block_num++) {
  165421. /* Fetch current DCT block into workspace so we can modify it. */
  165422. jcopy_block_row(buffer_ptr, (JBLOCKROW) workspace, (JDIMENSION) 1);
  165423. /* Update DC values */
  165424. if (block_num < last_block_column) {
  165425. DC3 = (int) prev_block_row[1][0];
  165426. DC6 = (int) buffer_ptr[1][0];
  165427. DC9 = (int) next_block_row[1][0];
  165428. }
  165429. /* Compute coefficient estimates per K.8.
  165430. * An estimate is applied only if coefficient is still zero,
  165431. * and is not known to be fully accurate.
  165432. */
  165433. /* AC01 */
  165434. if ((Al=coef_bits[1]) != 0 && workspace[1] == 0) {
  165435. num = 36 * Q00 * (DC4 - DC6);
  165436. if (num >= 0) {
  165437. pred = (int) (((Q01<<7) + num) / (Q01<<8));
  165438. if (Al > 0 && pred >= (1<<Al))
  165439. pred = (1<<Al)-1;
  165440. } else {
  165441. pred = (int) (((Q01<<7) - num) / (Q01<<8));
  165442. if (Al > 0 && pred >= (1<<Al))
  165443. pred = (1<<Al)-1;
  165444. pred = -pred;
  165445. }
  165446. workspace[1] = (JCOEF) pred;
  165447. }
  165448. /* AC10 */
  165449. if ((Al=coef_bits[2]) != 0 && workspace[8] == 0) {
  165450. num = 36 * Q00 * (DC2 - DC8);
  165451. if (num >= 0) {
  165452. pred = (int) (((Q10<<7) + num) / (Q10<<8));
  165453. if (Al > 0 && pred >= (1<<Al))
  165454. pred = (1<<Al)-1;
  165455. } else {
  165456. pred = (int) (((Q10<<7) - num) / (Q10<<8));
  165457. if (Al > 0 && pred >= (1<<Al))
  165458. pred = (1<<Al)-1;
  165459. pred = -pred;
  165460. }
  165461. workspace[8] = (JCOEF) pred;
  165462. }
  165463. /* AC20 */
  165464. if ((Al=coef_bits[3]) != 0 && workspace[16] == 0) {
  165465. num = 9 * Q00 * (DC2 + DC8 - 2*DC5);
  165466. if (num >= 0) {
  165467. pred = (int) (((Q20<<7) + num) / (Q20<<8));
  165468. if (Al > 0 && pred >= (1<<Al))
  165469. pred = (1<<Al)-1;
  165470. } else {
  165471. pred = (int) (((Q20<<7) - num) / (Q20<<8));
  165472. if (Al > 0 && pred >= (1<<Al))
  165473. pred = (1<<Al)-1;
  165474. pred = -pred;
  165475. }
  165476. workspace[16] = (JCOEF) pred;
  165477. }
  165478. /* AC11 */
  165479. if ((Al=coef_bits[4]) != 0 && workspace[9] == 0) {
  165480. num = 5 * Q00 * (DC1 - DC3 - DC7 + DC9);
  165481. if (num >= 0) {
  165482. pred = (int) (((Q11<<7) + num) / (Q11<<8));
  165483. if (Al > 0 && pred >= (1<<Al))
  165484. pred = (1<<Al)-1;
  165485. } else {
  165486. pred = (int) (((Q11<<7) - num) / (Q11<<8));
  165487. if (Al > 0 && pred >= (1<<Al))
  165488. pred = (1<<Al)-1;
  165489. pred = -pred;
  165490. }
  165491. workspace[9] = (JCOEF) pred;
  165492. }
  165493. /* AC02 */
  165494. if ((Al=coef_bits[5]) != 0 && workspace[2] == 0) {
  165495. num = 9 * Q00 * (DC4 + DC6 - 2*DC5);
  165496. if (num >= 0) {
  165497. pred = (int) (((Q02<<7) + num) / (Q02<<8));
  165498. if (Al > 0 && pred >= (1<<Al))
  165499. pred = (1<<Al)-1;
  165500. } else {
  165501. pred = (int) (((Q02<<7) - num) / (Q02<<8));
  165502. if (Al > 0 && pred >= (1<<Al))
  165503. pred = (1<<Al)-1;
  165504. pred = -pred;
  165505. }
  165506. workspace[2] = (JCOEF) pred;
  165507. }
  165508. /* OK, do the IDCT */
  165509. (*inverse_DCT) (cinfo, compptr, (JCOEFPTR) workspace,
  165510. output_ptr, output_col);
  165511. /* Advance for next column */
  165512. DC1 = DC2; DC2 = DC3;
  165513. DC4 = DC5; DC5 = DC6;
  165514. DC7 = DC8; DC8 = DC9;
  165515. buffer_ptr++, prev_block_row++, next_block_row++;
  165516. output_col += compptr->DCT_scaled_size;
  165517. }
  165518. output_ptr += compptr->DCT_scaled_size;
  165519. }
  165520. }
  165521. if (++(cinfo->output_iMCU_row) < cinfo->total_iMCU_rows)
  165522. return JPEG_ROW_COMPLETED;
  165523. return JPEG_SCAN_COMPLETED;
  165524. }
  165525. #endif /* BLOCK_SMOOTHING_SUPPORTED */
  165526. /*
  165527. * Initialize coefficient buffer controller.
  165528. */
  165529. GLOBAL(void)
  165530. jinit_d_coef_controller (j_decompress_ptr cinfo, boolean need_full_buffer)
  165531. {
  165532. my_coef_ptr3 coef;
  165533. coef = (my_coef_ptr3)
  165534. (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_IMAGE,
  165535. SIZEOF(my_coef_controller3));
  165536. cinfo->coef = (struct jpeg_d_coef_controller *) coef;
  165537. coef->pub.start_input_pass = start_input_pass;
  165538. coef->pub.start_output_pass = start_output_pass;
  165539. #ifdef BLOCK_SMOOTHING_SUPPORTED
  165540. coef->coef_bits_latch = NULL;
  165541. #endif
  165542. /* Create the coefficient buffer. */
  165543. if (need_full_buffer) {
  165544. #ifdef D_MULTISCAN_FILES_SUPPORTED
  165545. /* Allocate a full-image virtual array for each component, */
  165546. /* padded to a multiple of samp_factor DCT blocks in each direction. */
  165547. /* Note we ask for a pre-zeroed array. */
  165548. int ci, access_rows;
  165549. jpeg_component_info *compptr;
  165550. for (ci = 0, compptr = cinfo->comp_info; ci < cinfo->num_components;
  165551. ci++, compptr++) {
  165552. access_rows = compptr->v_samp_factor;
  165553. #ifdef BLOCK_SMOOTHING_SUPPORTED
  165554. /* If block smoothing could be used, need a bigger window */
  165555. if (cinfo->progressive_mode)
  165556. access_rows *= 3;
  165557. #endif
  165558. coef->whole_image[ci] = (*cinfo->mem->request_virt_barray)
  165559. ((j_common_ptr) cinfo, JPOOL_IMAGE, TRUE,
  165560. (JDIMENSION) jround_up((long) compptr->width_in_blocks,
  165561. (long) compptr->h_samp_factor),
  165562. (JDIMENSION) jround_up((long) compptr->height_in_blocks,
  165563. (long) compptr->v_samp_factor),
  165564. (JDIMENSION) access_rows);
  165565. }
  165566. coef->pub.consume_data = consume_data;
  165567. coef->pub.decompress_data = decompress_data;
  165568. coef->pub.coef_arrays = coef->whole_image; /* link to virtual arrays */
  165569. #else
  165570. ERREXIT(cinfo, JERR_NOT_COMPILED);
  165571. #endif
  165572. } else {
  165573. /* We only need a single-MCU buffer. */
  165574. JBLOCKROW buffer;
  165575. int i;
  165576. buffer = (JBLOCKROW)
  165577. (*cinfo->mem->alloc_large) ((j_common_ptr) cinfo, JPOOL_IMAGE,
  165578. D_MAX_BLOCKS_IN_MCU * SIZEOF(JBLOCK));
  165579. for (i = 0; i < D_MAX_BLOCKS_IN_MCU; i++) {
  165580. coef->MCU_buffer[i] = buffer + i;
  165581. }
  165582. coef->pub.consume_data = dummy_consume_data;
  165583. coef->pub.decompress_data = decompress_onepass;
  165584. coef->pub.coef_arrays = NULL; /* flag for no virtual arrays */
  165585. }
  165586. }
  165587. /*** End of inlined file: jdcoefct.c ***/
  165588. #undef FIX
  165589. /*** Start of inlined file: jdcolor.c ***/
  165590. #define JPEG_INTERNALS
  165591. /* Private subobject */
  165592. typedef struct {
  165593. struct jpeg_color_deconverter pub; /* public fields */
  165594. /* Private state for YCC->RGB conversion */
  165595. int * Cr_r_tab; /* => table for Cr to R conversion */
  165596. int * Cb_b_tab; /* => table for Cb to B conversion */
  165597. INT32 * Cr_g_tab; /* => table for Cr to G conversion */
  165598. INT32 * Cb_g_tab; /* => table for Cb to G conversion */
  165599. } my_color_deconverter2;
  165600. typedef my_color_deconverter2 * my_cconvert_ptr2;
  165601. /**************** YCbCr -> RGB conversion: most common case **************/
  165602. /*
  165603. * YCbCr is defined per CCIR 601-1, except that Cb and Cr are
  165604. * normalized to the range 0..MAXJSAMPLE rather than -0.5 .. 0.5.
  165605. * The conversion equations to be implemented are therefore
  165606. * R = Y + 1.40200 * Cr
  165607. * G = Y - 0.34414 * Cb - 0.71414 * Cr
  165608. * B = Y + 1.77200 * Cb
  165609. * where Cb and Cr represent the incoming values less CENTERJSAMPLE.
  165610. * (These numbers are derived from TIFF 6.0 section 21, dated 3-June-92.)
  165611. *
  165612. * To avoid floating-point arithmetic, we represent the fractional constants
  165613. * as integers scaled up by 2^16 (about 4 digits precision); we have to divide
  165614. * the products by 2^16, with appropriate rounding, to get the correct answer.
  165615. * Notice that Y, being an integral input, does not contribute any fraction
  165616. * so it need not participate in the rounding.
  165617. *
  165618. * For even more speed, we avoid doing any multiplications in the inner loop
  165619. * by precalculating the constants times Cb and Cr for all possible values.
  165620. * For 8-bit JSAMPLEs this is very reasonable (only 256 entries per table);
  165621. * for 12-bit samples it is still acceptable. It's not very reasonable for
  165622. * 16-bit samples, but if you want lossless storage you shouldn't be changing
  165623. * colorspace anyway.
  165624. * The Cr=>R and Cb=>B values can be rounded to integers in advance; the
  165625. * values for the G calculation are left scaled up, since we must add them
  165626. * together before rounding.
  165627. */
  165628. #define SCALEBITS 16 /* speediest right-shift on some machines */
  165629. #define ONE_HALF ((INT32) 1 << (SCALEBITS-1))
  165630. #define FIX(x) ((INT32) ((x) * (1L<<SCALEBITS) + 0.5))
  165631. /*
  165632. * Initialize tables for YCC->RGB colorspace conversion.
  165633. */
  165634. LOCAL(void)
  165635. build_ycc_rgb_table (j_decompress_ptr cinfo)
  165636. {
  165637. my_cconvert_ptr2 cconvert = (my_cconvert_ptr2) cinfo->cconvert;
  165638. int i;
  165639. INT32 x;
  165640. SHIFT_TEMPS
  165641. cconvert->Cr_r_tab = (int *)
  165642. (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_IMAGE,
  165643. (MAXJSAMPLE+1) * SIZEOF(int));
  165644. cconvert->Cb_b_tab = (int *)
  165645. (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_IMAGE,
  165646. (MAXJSAMPLE+1) * SIZEOF(int));
  165647. cconvert->Cr_g_tab = (INT32 *)
  165648. (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_IMAGE,
  165649. (MAXJSAMPLE+1) * SIZEOF(INT32));
  165650. cconvert->Cb_g_tab = (INT32 *)
  165651. (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_IMAGE,
  165652. (MAXJSAMPLE+1) * SIZEOF(INT32));
  165653. for (i = 0, x = -CENTERJSAMPLE; i <= MAXJSAMPLE; i++, x++) {
  165654. /* i is the actual input pixel value, in the range 0..MAXJSAMPLE */
  165655. /* The Cb or Cr value we are thinking of is x = i - CENTERJSAMPLE */
  165656. /* Cr=>R value is nearest int to 1.40200 * x */
  165657. cconvert->Cr_r_tab[i] = (int)
  165658. RIGHT_SHIFT(FIX(1.40200) * x + ONE_HALF, SCALEBITS);
  165659. /* Cb=>B value is nearest int to 1.77200 * x */
  165660. cconvert->Cb_b_tab[i] = (int)
  165661. RIGHT_SHIFT(FIX(1.77200) * x + ONE_HALF, SCALEBITS);
  165662. /* Cr=>G value is scaled-up -0.71414 * x */
  165663. cconvert->Cr_g_tab[i] = (- FIX(0.71414)) * x;
  165664. /* Cb=>G value is scaled-up -0.34414 * x */
  165665. /* We also add in ONE_HALF so that need not do it in inner loop */
  165666. cconvert->Cb_g_tab[i] = (- FIX(0.34414)) * x + ONE_HALF;
  165667. }
  165668. }
  165669. /*
  165670. * Convert some rows of samples to the output colorspace.
  165671. *
  165672. * Note that we change from noninterleaved, one-plane-per-component format
  165673. * to interleaved-pixel format. The output buffer is therefore three times
  165674. * as wide as the input buffer.
  165675. * A starting row offset is provided only for the input buffer. The caller
  165676. * can easily adjust the passed output_buf value to accommodate any row
  165677. * offset required on that side.
  165678. */
  165679. METHODDEF(void)
  165680. ycc_rgb_convert (j_decompress_ptr cinfo,
  165681. JSAMPIMAGE input_buf, JDIMENSION input_row,
  165682. JSAMPARRAY output_buf, int num_rows)
  165683. {
  165684. my_cconvert_ptr2 cconvert = (my_cconvert_ptr2) cinfo->cconvert;
  165685. register int y, cb, cr;
  165686. register JSAMPROW outptr;
  165687. register JSAMPROW inptr0, inptr1, inptr2;
  165688. register JDIMENSION col;
  165689. JDIMENSION num_cols = cinfo->output_width;
  165690. /* copy these pointers into registers if possible */
  165691. register JSAMPLE * range_limit = cinfo->sample_range_limit;
  165692. register int * Crrtab = cconvert->Cr_r_tab;
  165693. register int * Cbbtab = cconvert->Cb_b_tab;
  165694. register INT32 * Crgtab = cconvert->Cr_g_tab;
  165695. register INT32 * Cbgtab = cconvert->Cb_g_tab;
  165696. SHIFT_TEMPS
  165697. while (--num_rows >= 0) {
  165698. inptr0 = input_buf[0][input_row];
  165699. inptr1 = input_buf[1][input_row];
  165700. inptr2 = input_buf[2][input_row];
  165701. input_row++;
  165702. outptr = *output_buf++;
  165703. for (col = 0; col < num_cols; col++) {
  165704. y = GETJSAMPLE(inptr0[col]);
  165705. cb = GETJSAMPLE(inptr1[col]);
  165706. cr = GETJSAMPLE(inptr2[col]);
  165707. /* Range-limiting is essential due to noise introduced by DCT losses. */
  165708. outptr[RGB_RED] = range_limit[y + Crrtab[cr]];
  165709. outptr[RGB_GREEN] = range_limit[y +
  165710. ((int) RIGHT_SHIFT(Cbgtab[cb] + Crgtab[cr],
  165711. SCALEBITS))];
  165712. outptr[RGB_BLUE] = range_limit[y + Cbbtab[cb]];
  165713. outptr += RGB_PIXELSIZE;
  165714. }
  165715. }
  165716. }
  165717. /**************** Cases other than YCbCr -> RGB **************/
  165718. /*
  165719. * Color conversion for no colorspace change: just copy the data,
  165720. * converting from separate-planes to interleaved representation.
  165721. */
  165722. METHODDEF(void)
  165723. null_convert2 (j_decompress_ptr cinfo,
  165724. JSAMPIMAGE input_buf, JDIMENSION input_row,
  165725. JSAMPARRAY output_buf, int num_rows)
  165726. {
  165727. register JSAMPROW inptr, outptr;
  165728. register JDIMENSION count;
  165729. register int num_components = cinfo->num_components;
  165730. JDIMENSION num_cols = cinfo->output_width;
  165731. int ci;
  165732. while (--num_rows >= 0) {
  165733. for (ci = 0; ci < num_components; ci++) {
  165734. inptr = input_buf[ci][input_row];
  165735. outptr = output_buf[0] + ci;
  165736. for (count = num_cols; count > 0; count--) {
  165737. *outptr = *inptr++; /* needn't bother with GETJSAMPLE() here */
  165738. outptr += num_components;
  165739. }
  165740. }
  165741. input_row++;
  165742. output_buf++;
  165743. }
  165744. }
  165745. /*
  165746. * Color conversion for grayscale: just copy the data.
  165747. * This also works for YCbCr -> grayscale conversion, in which
  165748. * we just copy the Y (luminance) component and ignore chrominance.
  165749. */
  165750. METHODDEF(void)
  165751. grayscale_convert2 (j_decompress_ptr cinfo,
  165752. JSAMPIMAGE input_buf, JDIMENSION input_row,
  165753. JSAMPARRAY output_buf, int num_rows)
  165754. {
  165755. jcopy_sample_rows(input_buf[0], (int) input_row, output_buf, 0,
  165756. num_rows, cinfo->output_width);
  165757. }
  165758. /*
  165759. * Convert grayscale to RGB: just duplicate the graylevel three times.
  165760. * This is provided to support applications that don't want to cope
  165761. * with grayscale as a separate case.
  165762. */
  165763. METHODDEF(void)
  165764. gray_rgb_convert (j_decompress_ptr cinfo,
  165765. JSAMPIMAGE input_buf, JDIMENSION input_row,
  165766. JSAMPARRAY output_buf, int num_rows)
  165767. {
  165768. register JSAMPROW inptr, outptr;
  165769. register JDIMENSION col;
  165770. JDIMENSION num_cols = cinfo->output_width;
  165771. while (--num_rows >= 0) {
  165772. inptr = input_buf[0][input_row++];
  165773. outptr = *output_buf++;
  165774. for (col = 0; col < num_cols; col++) {
  165775. /* We can dispense with GETJSAMPLE() here */
  165776. outptr[RGB_RED] = outptr[RGB_GREEN] = outptr[RGB_BLUE] = inptr[col];
  165777. outptr += RGB_PIXELSIZE;
  165778. }
  165779. }
  165780. }
  165781. /*
  165782. * Adobe-style YCCK->CMYK conversion.
  165783. * We convert YCbCr to R=1-C, G=1-M, and B=1-Y using the same
  165784. * conversion as above, while passing K (black) unchanged.
  165785. * We assume build_ycc_rgb_table has been called.
  165786. */
  165787. METHODDEF(void)
  165788. ycck_cmyk_convert (j_decompress_ptr cinfo,
  165789. JSAMPIMAGE input_buf, JDIMENSION input_row,
  165790. JSAMPARRAY output_buf, int num_rows)
  165791. {
  165792. my_cconvert_ptr2 cconvert = (my_cconvert_ptr2) cinfo->cconvert;
  165793. register int y, cb, cr;
  165794. register JSAMPROW outptr;
  165795. register JSAMPROW inptr0, inptr1, inptr2, inptr3;
  165796. register JDIMENSION col;
  165797. JDIMENSION num_cols = cinfo->output_width;
  165798. /* copy these pointers into registers if possible */
  165799. register JSAMPLE * range_limit = cinfo->sample_range_limit;
  165800. register int * Crrtab = cconvert->Cr_r_tab;
  165801. register int * Cbbtab = cconvert->Cb_b_tab;
  165802. register INT32 * Crgtab = cconvert->Cr_g_tab;
  165803. register INT32 * Cbgtab = cconvert->Cb_g_tab;
  165804. SHIFT_TEMPS
  165805. while (--num_rows >= 0) {
  165806. inptr0 = input_buf[0][input_row];
  165807. inptr1 = input_buf[1][input_row];
  165808. inptr2 = input_buf[2][input_row];
  165809. inptr3 = input_buf[3][input_row];
  165810. input_row++;
  165811. outptr = *output_buf++;
  165812. for (col = 0; col < num_cols; col++) {
  165813. y = GETJSAMPLE(inptr0[col]);
  165814. cb = GETJSAMPLE(inptr1[col]);
  165815. cr = GETJSAMPLE(inptr2[col]);
  165816. /* Range-limiting is essential due to noise introduced by DCT losses. */
  165817. outptr[0] = range_limit[MAXJSAMPLE - (y + Crrtab[cr])]; /* red */
  165818. outptr[1] = range_limit[MAXJSAMPLE - (y + /* green */
  165819. ((int) RIGHT_SHIFT(Cbgtab[cb] + Crgtab[cr],
  165820. SCALEBITS)))];
  165821. outptr[2] = range_limit[MAXJSAMPLE - (y + Cbbtab[cb])]; /* blue */
  165822. /* K passes through unchanged */
  165823. outptr[3] = inptr3[col]; /* don't need GETJSAMPLE here */
  165824. outptr += 4;
  165825. }
  165826. }
  165827. }
  165828. /*
  165829. * Empty method for start_pass.
  165830. */
  165831. METHODDEF(void)
  165832. start_pass_dcolor (j_decompress_ptr cinfo)
  165833. {
  165834. /* no work needed */
  165835. }
  165836. /*
  165837. * Module initialization routine for output colorspace conversion.
  165838. */
  165839. GLOBAL(void)
  165840. jinit_color_deconverter (j_decompress_ptr cinfo)
  165841. {
  165842. my_cconvert_ptr2 cconvert;
  165843. int ci;
  165844. cconvert = (my_cconvert_ptr2)
  165845. (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_IMAGE,
  165846. SIZEOF(my_color_deconverter2));
  165847. cinfo->cconvert = (struct jpeg_color_deconverter *) cconvert;
  165848. cconvert->pub.start_pass = start_pass_dcolor;
  165849. /* Make sure num_components agrees with jpeg_color_space */
  165850. switch (cinfo->jpeg_color_space) {
  165851. case JCS_GRAYSCALE:
  165852. if (cinfo->num_components != 1)
  165853. ERREXIT(cinfo, JERR_BAD_J_COLORSPACE);
  165854. break;
  165855. case JCS_RGB:
  165856. case JCS_YCbCr:
  165857. if (cinfo->num_components != 3)
  165858. ERREXIT(cinfo, JERR_BAD_J_COLORSPACE);
  165859. break;
  165860. case JCS_CMYK:
  165861. case JCS_YCCK:
  165862. if (cinfo->num_components != 4)
  165863. ERREXIT(cinfo, JERR_BAD_J_COLORSPACE);
  165864. break;
  165865. default: /* JCS_UNKNOWN can be anything */
  165866. if (cinfo->num_components < 1)
  165867. ERREXIT(cinfo, JERR_BAD_J_COLORSPACE);
  165868. break;
  165869. }
  165870. /* Set out_color_components and conversion method based on requested space.
  165871. * Also clear the component_needed flags for any unused components,
  165872. * so that earlier pipeline stages can avoid useless computation.
  165873. */
  165874. switch (cinfo->out_color_space) {
  165875. case JCS_GRAYSCALE:
  165876. cinfo->out_color_components = 1;
  165877. if (cinfo->jpeg_color_space == JCS_GRAYSCALE ||
  165878. cinfo->jpeg_color_space == JCS_YCbCr) {
  165879. cconvert->pub.color_convert = grayscale_convert2;
  165880. /* For color->grayscale conversion, only the Y (0) component is needed */
  165881. for (ci = 1; ci < cinfo->num_components; ci++)
  165882. cinfo->comp_info[ci].component_needed = FALSE;
  165883. } else
  165884. ERREXIT(cinfo, JERR_CONVERSION_NOTIMPL);
  165885. break;
  165886. case JCS_RGB:
  165887. cinfo->out_color_components = RGB_PIXELSIZE;
  165888. if (cinfo->jpeg_color_space == JCS_YCbCr) {
  165889. cconvert->pub.color_convert = ycc_rgb_convert;
  165890. build_ycc_rgb_table(cinfo);
  165891. } else if (cinfo->jpeg_color_space == JCS_GRAYSCALE) {
  165892. cconvert->pub.color_convert = gray_rgb_convert;
  165893. } else if (cinfo->jpeg_color_space == JCS_RGB && RGB_PIXELSIZE == 3) {
  165894. cconvert->pub.color_convert = null_convert2;
  165895. } else
  165896. ERREXIT(cinfo, JERR_CONVERSION_NOTIMPL);
  165897. break;
  165898. case JCS_CMYK:
  165899. cinfo->out_color_components = 4;
  165900. if (cinfo->jpeg_color_space == JCS_YCCK) {
  165901. cconvert->pub.color_convert = ycck_cmyk_convert;
  165902. build_ycc_rgb_table(cinfo);
  165903. } else if (cinfo->jpeg_color_space == JCS_CMYK) {
  165904. cconvert->pub.color_convert = null_convert2;
  165905. } else
  165906. ERREXIT(cinfo, JERR_CONVERSION_NOTIMPL);
  165907. break;
  165908. default:
  165909. /* Permit null conversion to same output space */
  165910. if (cinfo->out_color_space == cinfo->jpeg_color_space) {
  165911. cinfo->out_color_components = cinfo->num_components;
  165912. cconvert->pub.color_convert = null_convert2;
  165913. } else /* unsupported non-null conversion */
  165914. ERREXIT(cinfo, JERR_CONVERSION_NOTIMPL);
  165915. break;
  165916. }
  165917. if (cinfo->quantize_colors)
  165918. cinfo->output_components = 1; /* single colormapped output component */
  165919. else
  165920. cinfo->output_components = cinfo->out_color_components;
  165921. }
  165922. /*** End of inlined file: jdcolor.c ***/
  165923. #undef FIX
  165924. /*** Start of inlined file: jddctmgr.c ***/
  165925. #define JPEG_INTERNALS
  165926. /*
  165927. * The decompressor input side (jdinput.c) saves away the appropriate
  165928. * quantization table for each component at the start of the first scan
  165929. * involving that component. (This is necessary in order to correctly
  165930. * decode files that reuse Q-table slots.)
  165931. * When we are ready to make an output pass, the saved Q-table is converted
  165932. * to a multiplier table that will actually be used by the IDCT routine.
  165933. * The multiplier table contents are IDCT-method-dependent. To support
  165934. * application changes in IDCT method between scans, we can remake the
  165935. * multiplier tables if necessary.
  165936. * In buffered-image mode, the first output pass may occur before any data
  165937. * has been seen for some components, and thus before their Q-tables have
  165938. * been saved away. To handle this case, multiplier tables are preset
  165939. * to zeroes; the result of the IDCT will be a neutral gray level.
  165940. */
  165941. /* Private subobject for this module */
  165942. typedef struct {
  165943. struct jpeg_inverse_dct pub; /* public fields */
  165944. /* This array contains the IDCT method code that each multiplier table
  165945. * is currently set up for, or -1 if it's not yet set up.
  165946. * The actual multiplier tables are pointed to by dct_table in the
  165947. * per-component comp_info structures.
  165948. */
  165949. int cur_method[MAX_COMPONENTS];
  165950. } my_idct_controller;
  165951. typedef my_idct_controller * my_idct_ptr;
  165952. /* Allocated multiplier tables: big enough for any supported variant */
  165953. typedef union {
  165954. ISLOW_MULT_TYPE islow_array[DCTSIZE2];
  165955. #ifdef DCT_IFAST_SUPPORTED
  165956. IFAST_MULT_TYPE ifast_array[DCTSIZE2];
  165957. #endif
  165958. #ifdef DCT_FLOAT_SUPPORTED
  165959. FLOAT_MULT_TYPE float_array[DCTSIZE2];
  165960. #endif
  165961. } multiplier_table;
  165962. /* The current scaled-IDCT routines require ISLOW-style multiplier tables,
  165963. * so be sure to compile that code if either ISLOW or SCALING is requested.
  165964. */
  165965. #ifdef DCT_ISLOW_SUPPORTED
  165966. #define PROVIDE_ISLOW_TABLES
  165967. #else
  165968. #ifdef IDCT_SCALING_SUPPORTED
  165969. #define PROVIDE_ISLOW_TABLES
  165970. #endif
  165971. #endif
  165972. /*
  165973. * Prepare for an output pass.
  165974. * Here we select the proper IDCT routine for each component and build
  165975. * a matching multiplier table.
  165976. */
  165977. METHODDEF(void)
  165978. start_pass (j_decompress_ptr cinfo)
  165979. {
  165980. my_idct_ptr idct = (my_idct_ptr) cinfo->idct;
  165981. int ci, i;
  165982. jpeg_component_info *compptr;
  165983. int method = 0;
  165984. inverse_DCT_method_ptr method_ptr = NULL;
  165985. JQUANT_TBL * qtbl;
  165986. for (ci = 0, compptr = cinfo->comp_info; ci < cinfo->num_components;
  165987. ci++, compptr++) {
  165988. /* Select the proper IDCT routine for this component's scaling */
  165989. switch (compptr->DCT_scaled_size) {
  165990. #ifdef IDCT_SCALING_SUPPORTED
  165991. case 1:
  165992. method_ptr = jpeg_idct_1x1;
  165993. method = JDCT_ISLOW; /* jidctred uses islow-style table */
  165994. break;
  165995. case 2:
  165996. method_ptr = jpeg_idct_2x2;
  165997. method = JDCT_ISLOW; /* jidctred uses islow-style table */
  165998. break;
  165999. case 4:
  166000. method_ptr = jpeg_idct_4x4;
  166001. method = JDCT_ISLOW; /* jidctred uses islow-style table */
  166002. break;
  166003. #endif
  166004. case DCTSIZE:
  166005. switch (cinfo->dct_method) {
  166006. #ifdef DCT_ISLOW_SUPPORTED
  166007. case JDCT_ISLOW:
  166008. method_ptr = jpeg_idct_islow;
  166009. method = JDCT_ISLOW;
  166010. break;
  166011. #endif
  166012. #ifdef DCT_IFAST_SUPPORTED
  166013. case JDCT_IFAST:
  166014. method_ptr = jpeg_idct_ifast;
  166015. method = JDCT_IFAST;
  166016. break;
  166017. #endif
  166018. #ifdef DCT_FLOAT_SUPPORTED
  166019. case JDCT_FLOAT:
  166020. method_ptr = jpeg_idct_float;
  166021. method = JDCT_FLOAT;
  166022. break;
  166023. #endif
  166024. default:
  166025. ERREXIT(cinfo, JERR_NOT_COMPILED);
  166026. break;
  166027. }
  166028. break;
  166029. default:
  166030. ERREXIT1(cinfo, JERR_BAD_DCTSIZE, compptr->DCT_scaled_size);
  166031. break;
  166032. }
  166033. idct->pub.inverse_DCT[ci] = method_ptr;
  166034. /* Create multiplier table from quant table.
  166035. * However, we can skip this if the component is uninteresting
  166036. * or if we already built the table. Also, if no quant table
  166037. * has yet been saved for the component, we leave the
  166038. * multiplier table all-zero; we'll be reading zeroes from the
  166039. * coefficient controller's buffer anyway.
  166040. */
  166041. if (! compptr->component_needed || idct->cur_method[ci] == method)
  166042. continue;
  166043. qtbl = compptr->quant_table;
  166044. if (qtbl == NULL) /* happens if no data yet for component */
  166045. continue;
  166046. idct->cur_method[ci] = method;
  166047. switch (method) {
  166048. #ifdef PROVIDE_ISLOW_TABLES
  166049. case JDCT_ISLOW:
  166050. {
  166051. /* For LL&M IDCT method, multipliers are equal to raw quantization
  166052. * coefficients, but are stored as ints to ensure access efficiency.
  166053. */
  166054. ISLOW_MULT_TYPE * ismtbl = (ISLOW_MULT_TYPE *) compptr->dct_table;
  166055. for (i = 0; i < DCTSIZE2; i++) {
  166056. ismtbl[i] = (ISLOW_MULT_TYPE) qtbl->quantval[i];
  166057. }
  166058. }
  166059. break;
  166060. #endif
  166061. #ifdef DCT_IFAST_SUPPORTED
  166062. case JDCT_IFAST:
  166063. {
  166064. /* For AA&N IDCT method, multipliers are equal to quantization
  166065. * coefficients scaled by scalefactor[row]*scalefactor[col], where
  166066. * scalefactor[0] = 1
  166067. * scalefactor[k] = cos(k*PI/16) * sqrt(2) for k=1..7
  166068. * For integer operation, the multiplier table is to be scaled by
  166069. * IFAST_SCALE_BITS.
  166070. */
  166071. IFAST_MULT_TYPE * ifmtbl = (IFAST_MULT_TYPE *) compptr->dct_table;
  166072. #define CONST_BITS 14
  166073. static const INT16 aanscales[DCTSIZE2] = {
  166074. /* precomputed values scaled up by 14 bits */
  166075. 16384, 22725, 21407, 19266, 16384, 12873, 8867, 4520,
  166076. 22725, 31521, 29692, 26722, 22725, 17855, 12299, 6270,
  166077. 21407, 29692, 27969, 25172, 21407, 16819, 11585, 5906,
  166078. 19266, 26722, 25172, 22654, 19266, 15137, 10426, 5315,
  166079. 16384, 22725, 21407, 19266, 16384, 12873, 8867, 4520,
  166080. 12873, 17855, 16819, 15137, 12873, 10114, 6967, 3552,
  166081. 8867, 12299, 11585, 10426, 8867, 6967, 4799, 2446,
  166082. 4520, 6270, 5906, 5315, 4520, 3552, 2446, 1247
  166083. };
  166084. SHIFT_TEMPS
  166085. for (i = 0; i < DCTSIZE2; i++) {
  166086. ifmtbl[i] = (IFAST_MULT_TYPE)
  166087. DESCALE(MULTIPLY16V16((INT32) qtbl->quantval[i],
  166088. (INT32) aanscales[i]),
  166089. CONST_BITS-IFAST_SCALE_BITS);
  166090. }
  166091. }
  166092. break;
  166093. #endif
  166094. #ifdef DCT_FLOAT_SUPPORTED
  166095. case JDCT_FLOAT:
  166096. {
  166097. /* For float AA&N IDCT method, multipliers are equal to quantization
  166098. * coefficients scaled by scalefactor[row]*scalefactor[col], where
  166099. * scalefactor[0] = 1
  166100. * scalefactor[k] = cos(k*PI/16) * sqrt(2) for k=1..7
  166101. */
  166102. FLOAT_MULT_TYPE * fmtbl = (FLOAT_MULT_TYPE *) compptr->dct_table;
  166103. int row, col;
  166104. static const double aanscalefactor[DCTSIZE] = {
  166105. 1.0, 1.387039845, 1.306562965, 1.175875602,
  166106. 1.0, 0.785694958, 0.541196100, 0.275899379
  166107. };
  166108. i = 0;
  166109. for (row = 0; row < DCTSIZE; row++) {
  166110. for (col = 0; col < DCTSIZE; col++) {
  166111. fmtbl[i] = (FLOAT_MULT_TYPE)
  166112. ((double) qtbl->quantval[i] *
  166113. aanscalefactor[row] * aanscalefactor[col]);
  166114. i++;
  166115. }
  166116. }
  166117. }
  166118. break;
  166119. #endif
  166120. default:
  166121. ERREXIT(cinfo, JERR_NOT_COMPILED);
  166122. break;
  166123. }
  166124. }
  166125. }
  166126. /*
  166127. * Initialize IDCT manager.
  166128. */
  166129. GLOBAL(void)
  166130. jinit_inverse_dct (j_decompress_ptr cinfo)
  166131. {
  166132. my_idct_ptr idct;
  166133. int ci;
  166134. jpeg_component_info *compptr;
  166135. idct = (my_idct_ptr)
  166136. (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_IMAGE,
  166137. SIZEOF(my_idct_controller));
  166138. cinfo->idct = (struct jpeg_inverse_dct *) idct;
  166139. idct->pub.start_pass = start_pass;
  166140. for (ci = 0, compptr = cinfo->comp_info; ci < cinfo->num_components;
  166141. ci++, compptr++) {
  166142. /* Allocate and pre-zero a multiplier table for each component */
  166143. compptr->dct_table =
  166144. (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_IMAGE,
  166145. SIZEOF(multiplier_table));
  166146. MEMZERO(compptr->dct_table, SIZEOF(multiplier_table));
  166147. /* Mark multiplier table not yet set up for any method */
  166148. idct->cur_method[ci] = -1;
  166149. }
  166150. }
  166151. /*** End of inlined file: jddctmgr.c ***/
  166152. #undef CONST_BITS
  166153. #undef ASSIGN_STATE
  166154. /*** Start of inlined file: jdhuff.c ***/
  166155. #define JPEG_INTERNALS
  166156. /*** Start of inlined file: jdhuff.h ***/
  166157. /* Short forms of external names for systems with brain-damaged linkers. */
  166158. #ifndef __jdhuff_h__
  166159. #define __jdhuff_h__
  166160. #ifdef NEED_SHORT_EXTERNAL_NAMES
  166161. #define jpeg_make_d_derived_tbl jMkDDerived
  166162. #define jpeg_fill_bit_buffer jFilBitBuf
  166163. #define jpeg_huff_decode jHufDecode
  166164. #endif /* NEED_SHORT_EXTERNAL_NAMES */
  166165. /* Derived data constructed for each Huffman table */
  166166. #define HUFF_LOOKAHEAD 8 /* # of bits of lookahead */
  166167. typedef struct {
  166168. /* Basic tables: (element [0] of each array is unused) */
  166169. INT32 maxcode[18]; /* largest code of length k (-1 if none) */
  166170. /* (maxcode[17] is a sentinel to ensure jpeg_huff_decode terminates) */
  166171. INT32 valoffset[17]; /* huffval[] offset for codes of length k */
  166172. /* valoffset[k] = huffval[] index of 1st symbol of code length k, less
  166173. * the smallest code of length k; so given a code of length k, the
  166174. * corresponding symbol is huffval[code + valoffset[k]]
  166175. */
  166176. /* Link to public Huffman table (needed only in jpeg_huff_decode) */
  166177. JHUFF_TBL *pub;
  166178. /* Lookahead tables: indexed by the next HUFF_LOOKAHEAD bits of
  166179. * the input data stream. If the next Huffman code is no more
  166180. * than HUFF_LOOKAHEAD bits long, we can obtain its length and
  166181. * the corresponding symbol directly from these tables.
  166182. */
  166183. int look_nbits[1<<HUFF_LOOKAHEAD]; /* # bits, or 0 if too long */
  166184. UINT8 look_sym[1<<HUFF_LOOKAHEAD]; /* symbol, or unused */
  166185. } d_derived_tbl;
  166186. /* Expand a Huffman table definition into the derived format */
  166187. EXTERN(void) jpeg_make_d_derived_tbl
  166188. JPP((j_decompress_ptr cinfo, boolean isDC, int tblno,
  166189. d_derived_tbl ** pdtbl));
  166190. /*
  166191. * Fetching the next N bits from the input stream is a time-critical operation
  166192. * for the Huffman decoders. We implement it with a combination of inline
  166193. * macros and out-of-line subroutines. Note that N (the number of bits
  166194. * demanded at one time) never exceeds 15 for JPEG use.
  166195. *
  166196. * We read source bytes into get_buffer and dole out bits as needed.
  166197. * If get_buffer already contains enough bits, they are fetched in-line
  166198. * by the macros CHECK_BIT_BUFFER and GET_BITS. When there aren't enough
  166199. * bits, jpeg_fill_bit_buffer is called; it will attempt to fill get_buffer
  166200. * as full as possible (not just to the number of bits needed; this
  166201. * prefetching reduces the overhead cost of calling jpeg_fill_bit_buffer).
  166202. * Note that jpeg_fill_bit_buffer may return FALSE to indicate suspension.
  166203. * On TRUE return, jpeg_fill_bit_buffer guarantees that get_buffer contains
  166204. * at least the requested number of bits --- dummy zeroes are inserted if
  166205. * necessary.
  166206. */
  166207. typedef INT32 bit_buf_type; /* type of bit-extraction buffer */
  166208. #define BIT_BUF_SIZE 32 /* size of buffer in bits */
  166209. /* If long is > 32 bits on your machine, and shifting/masking longs is
  166210. * reasonably fast, making bit_buf_type be long and setting BIT_BUF_SIZE
  166211. * appropriately should be a win. Unfortunately we can't define the size
  166212. * with something like #define BIT_BUF_SIZE (sizeof(bit_buf_type)*8)
  166213. * because not all machines measure sizeof in 8-bit bytes.
  166214. */
  166215. typedef struct { /* Bitreading state saved across MCUs */
  166216. bit_buf_type get_buffer; /* current bit-extraction buffer */
  166217. int bits_left; /* # of unused bits in it */
  166218. } bitread_perm_state;
  166219. typedef struct { /* Bitreading working state within an MCU */
  166220. /* Current data source location */
  166221. /* We need a copy, rather than munging the original, in case of suspension */
  166222. const JOCTET * next_input_byte; /* => next byte to read from source */
  166223. size_t bytes_in_buffer; /* # of bytes remaining in source buffer */
  166224. /* Bit input buffer --- note these values are kept in register variables,
  166225. * not in this struct, inside the inner loops.
  166226. */
  166227. bit_buf_type get_buffer; /* current bit-extraction buffer */
  166228. int bits_left; /* # of unused bits in it */
  166229. /* Pointer needed by jpeg_fill_bit_buffer. */
  166230. j_decompress_ptr cinfo; /* back link to decompress master record */
  166231. } bitread_working_state;
  166232. /* Macros to declare and load/save bitread local variables. */
  166233. #define BITREAD_STATE_VARS \
  166234. register bit_buf_type get_buffer; \
  166235. register int bits_left; \
  166236. bitread_working_state br_state
  166237. #define BITREAD_LOAD_STATE(cinfop,permstate) \
  166238. br_state.cinfo = cinfop; \
  166239. br_state.next_input_byte = cinfop->src->next_input_byte; \
  166240. br_state.bytes_in_buffer = cinfop->src->bytes_in_buffer; \
  166241. get_buffer = permstate.get_buffer; \
  166242. bits_left = permstate.bits_left;
  166243. #define BITREAD_SAVE_STATE(cinfop,permstate) \
  166244. cinfop->src->next_input_byte = br_state.next_input_byte; \
  166245. cinfop->src->bytes_in_buffer = br_state.bytes_in_buffer; \
  166246. permstate.get_buffer = get_buffer; \
  166247. permstate.bits_left = bits_left
  166248. /*
  166249. * These macros provide the in-line portion of bit fetching.
  166250. * Use CHECK_BIT_BUFFER to ensure there are N bits in get_buffer
  166251. * before using GET_BITS, PEEK_BITS, or DROP_BITS.
  166252. * The variables get_buffer and bits_left are assumed to be locals,
  166253. * but the state struct might not be (jpeg_huff_decode needs this).
  166254. * CHECK_BIT_BUFFER(state,n,action);
  166255. * Ensure there are N bits in get_buffer; if suspend, take action.
  166256. * val = GET_BITS(n);
  166257. * Fetch next N bits.
  166258. * val = PEEK_BITS(n);
  166259. * Fetch next N bits without removing them from the buffer.
  166260. * DROP_BITS(n);
  166261. * Discard next N bits.
  166262. * The value N should be a simple variable, not an expression, because it
  166263. * is evaluated multiple times.
  166264. */
  166265. #define CHECK_BIT_BUFFER(state,nbits,action) \
  166266. { if (bits_left < (nbits)) { \
  166267. if (! jpeg_fill_bit_buffer(&(state),get_buffer,bits_left,nbits)) \
  166268. { action; } \
  166269. get_buffer = (state).get_buffer; bits_left = (state).bits_left; } }
  166270. #define GET_BITS(nbits) \
  166271. (((int) (get_buffer >> (bits_left -= (nbits)))) & ((1<<(nbits))-1))
  166272. #define PEEK_BITS(nbits) \
  166273. (((int) (get_buffer >> (bits_left - (nbits)))) & ((1<<(nbits))-1))
  166274. #define DROP_BITS(nbits) \
  166275. (bits_left -= (nbits))
  166276. /* Load up the bit buffer to a depth of at least nbits */
  166277. EXTERN(boolean) jpeg_fill_bit_buffer
  166278. JPP((bitread_working_state * state, register bit_buf_type get_buffer,
  166279. register int bits_left, int nbits));
  166280. /*
  166281. * Code for extracting next Huffman-coded symbol from input bit stream.
  166282. * Again, this is time-critical and we make the main paths be macros.
  166283. *
  166284. * We use a lookahead table to process codes of up to HUFF_LOOKAHEAD bits
  166285. * without looping. Usually, more than 95% of the Huffman codes will be 8
  166286. * or fewer bits long. The few overlength codes are handled with a loop,
  166287. * which need not be inline code.
  166288. *
  166289. * Notes about the HUFF_DECODE macro:
  166290. * 1. Near the end of the data segment, we may fail to get enough bits
  166291. * for a lookahead. In that case, we do it the hard way.
  166292. * 2. If the lookahead table contains no entry, the next code must be
  166293. * more than HUFF_LOOKAHEAD bits long.
  166294. * 3. jpeg_huff_decode returns -1 if forced to suspend.
  166295. */
  166296. #define HUFF_DECODE(result,state,htbl,failaction,slowlabel) \
  166297. { register int nb, look; \
  166298. if (bits_left < HUFF_LOOKAHEAD) { \
  166299. if (! jpeg_fill_bit_buffer(&state,get_buffer,bits_left, 0)) {failaction;} \
  166300. get_buffer = state.get_buffer; bits_left = state.bits_left; \
  166301. if (bits_left < HUFF_LOOKAHEAD) { \
  166302. nb = 1; goto slowlabel; \
  166303. } \
  166304. } \
  166305. look = PEEK_BITS(HUFF_LOOKAHEAD); \
  166306. if ((nb = htbl->look_nbits[look]) != 0) { \
  166307. DROP_BITS(nb); \
  166308. result = htbl->look_sym[look]; \
  166309. } else { \
  166310. nb = HUFF_LOOKAHEAD+1; \
  166311. slowlabel: \
  166312. if ((result=jpeg_huff_decode(&state,get_buffer,bits_left,htbl,nb)) < 0) \
  166313. { failaction; } \
  166314. get_buffer = state.get_buffer; bits_left = state.bits_left; \
  166315. } \
  166316. }
  166317. /* Out-of-line case for Huffman code fetching */
  166318. EXTERN(int) jpeg_huff_decode
  166319. JPP((bitread_working_state * state, register bit_buf_type get_buffer,
  166320. register int bits_left, d_derived_tbl * htbl, int min_bits));
  166321. #endif
  166322. /*** End of inlined file: jdhuff.h ***/
  166323. /* Declarations shared with jdphuff.c */
  166324. /*
  166325. * Expanded entropy decoder object for Huffman decoding.
  166326. *
  166327. * The savable_state subrecord contains fields that change within an MCU,
  166328. * but must not be updated permanently until we complete the MCU.
  166329. */
  166330. typedef struct {
  166331. int last_dc_val[MAX_COMPS_IN_SCAN]; /* last DC coef for each component */
  166332. } savable_state2;
  166333. /* This macro is to work around compilers with missing or broken
  166334. * structure assignment. You'll need to fix this code if you have
  166335. * such a compiler and you change MAX_COMPS_IN_SCAN.
  166336. */
  166337. #ifndef NO_STRUCT_ASSIGN
  166338. #define ASSIGN_STATE(dest,src) ((dest) = (src))
  166339. #else
  166340. #if MAX_COMPS_IN_SCAN == 4
  166341. #define ASSIGN_STATE(dest,src) \
  166342. ((dest).last_dc_val[0] = (src).last_dc_val[0], \
  166343. (dest).last_dc_val[1] = (src).last_dc_val[1], \
  166344. (dest).last_dc_val[2] = (src).last_dc_val[2], \
  166345. (dest).last_dc_val[3] = (src).last_dc_val[3])
  166346. #endif
  166347. #endif
  166348. typedef struct {
  166349. struct jpeg_entropy_decoder pub; /* public fields */
  166350. /* These fields are loaded into local variables at start of each MCU.
  166351. * In case of suspension, we exit WITHOUT updating them.
  166352. */
  166353. bitread_perm_state bitstate; /* Bit buffer at start of MCU */
  166354. savable_state2 saved; /* Other state at start of MCU */
  166355. /* These fields are NOT loaded into local working state. */
  166356. unsigned int restarts_to_go; /* MCUs left in this restart interval */
  166357. /* Pointers to derived tables (these workspaces have image lifespan) */
  166358. d_derived_tbl * dc_derived_tbls[NUM_HUFF_TBLS];
  166359. d_derived_tbl * ac_derived_tbls[NUM_HUFF_TBLS];
  166360. /* Precalculated info set up by start_pass for use in decode_mcu: */
  166361. /* Pointers to derived tables to be used for each block within an MCU */
  166362. d_derived_tbl * dc_cur_tbls[D_MAX_BLOCKS_IN_MCU];
  166363. d_derived_tbl * ac_cur_tbls[D_MAX_BLOCKS_IN_MCU];
  166364. /* Whether we care about the DC and AC coefficient values for each block */
  166365. boolean dc_needed[D_MAX_BLOCKS_IN_MCU];
  166366. boolean ac_needed[D_MAX_BLOCKS_IN_MCU];
  166367. } huff_entropy_decoder2;
  166368. typedef huff_entropy_decoder2 * huff_entropy_ptr2;
  166369. /*
  166370. * Initialize for a Huffman-compressed scan.
  166371. */
  166372. METHODDEF(void)
  166373. start_pass_huff_decoder (j_decompress_ptr cinfo)
  166374. {
  166375. huff_entropy_ptr2 entropy = (huff_entropy_ptr2) cinfo->entropy;
  166376. int ci, blkn, dctbl, actbl;
  166377. jpeg_component_info * compptr;
  166378. /* Check that the scan parameters Ss, Se, Ah/Al are OK for sequential JPEG.
  166379. * This ought to be an error condition, but we make it a warning because
  166380. * there are some baseline files out there with all zeroes in these bytes.
  166381. */
  166382. if (cinfo->Ss != 0 || cinfo->Se != DCTSIZE2-1 ||
  166383. cinfo->Ah != 0 || cinfo->Al != 0)
  166384. WARNMS(cinfo, JWRN_NOT_SEQUENTIAL);
  166385. for (ci = 0; ci < cinfo->comps_in_scan; ci++) {
  166386. compptr = cinfo->cur_comp_info[ci];
  166387. dctbl = compptr->dc_tbl_no;
  166388. actbl = compptr->ac_tbl_no;
  166389. /* Compute derived values for Huffman tables */
  166390. /* We may do this more than once for a table, but it's not expensive */
  166391. jpeg_make_d_derived_tbl(cinfo, TRUE, dctbl,
  166392. & entropy->dc_derived_tbls[dctbl]);
  166393. jpeg_make_d_derived_tbl(cinfo, FALSE, actbl,
  166394. & entropy->ac_derived_tbls[actbl]);
  166395. /* Initialize DC predictions to 0 */
  166396. entropy->saved.last_dc_val[ci] = 0;
  166397. }
  166398. /* Precalculate decoding info for each block in an MCU of this scan */
  166399. for (blkn = 0; blkn < cinfo->blocks_in_MCU; blkn++) {
  166400. ci = cinfo->MCU_membership[blkn];
  166401. compptr = cinfo->cur_comp_info[ci];
  166402. /* Precalculate which table to use for each block */
  166403. entropy->dc_cur_tbls[blkn] = entropy->dc_derived_tbls[compptr->dc_tbl_no];
  166404. entropy->ac_cur_tbls[blkn] = entropy->ac_derived_tbls[compptr->ac_tbl_no];
  166405. /* Decide whether we really care about the coefficient values */
  166406. if (compptr->component_needed) {
  166407. entropy->dc_needed[blkn] = TRUE;
  166408. /* we don't need the ACs if producing a 1/8th-size image */
  166409. entropy->ac_needed[blkn] = (compptr->DCT_scaled_size > 1);
  166410. } else {
  166411. entropy->dc_needed[blkn] = entropy->ac_needed[blkn] = FALSE;
  166412. }
  166413. }
  166414. /* Initialize bitread state variables */
  166415. entropy->bitstate.bits_left = 0;
  166416. entropy->bitstate.get_buffer = 0; /* unnecessary, but keeps Purify quiet */
  166417. entropy->pub.insufficient_data = FALSE;
  166418. /* Initialize restart counter */
  166419. entropy->restarts_to_go = cinfo->restart_interval;
  166420. }
  166421. /*
  166422. * Compute the derived values for a Huffman table.
  166423. * This routine also performs some validation checks on the table.
  166424. *
  166425. * Note this is also used by jdphuff.c.
  166426. */
  166427. GLOBAL(void)
  166428. jpeg_make_d_derived_tbl (j_decompress_ptr cinfo, boolean isDC, int tblno,
  166429. d_derived_tbl ** pdtbl)
  166430. {
  166431. JHUFF_TBL *htbl;
  166432. d_derived_tbl *dtbl;
  166433. int p, i, l, si, numsymbols;
  166434. int lookbits, ctr;
  166435. char huffsize[257];
  166436. unsigned int huffcode[257];
  166437. unsigned int code;
  166438. /* Note that huffsize[] and huffcode[] are filled in code-length order,
  166439. * paralleling the order of the symbols themselves in htbl->huffval[].
  166440. */
  166441. /* Find the input Huffman table */
  166442. if (tblno < 0 || tblno >= NUM_HUFF_TBLS)
  166443. ERREXIT1(cinfo, JERR_NO_HUFF_TABLE, tblno);
  166444. htbl =
  166445. isDC ? cinfo->dc_huff_tbl_ptrs[tblno] : cinfo->ac_huff_tbl_ptrs[tblno];
  166446. if (htbl == NULL)
  166447. ERREXIT1(cinfo, JERR_NO_HUFF_TABLE, tblno);
  166448. /* Allocate a workspace if we haven't already done so. */
  166449. if (*pdtbl == NULL)
  166450. *pdtbl = (d_derived_tbl *)
  166451. (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_IMAGE,
  166452. SIZEOF(d_derived_tbl));
  166453. dtbl = *pdtbl;
  166454. dtbl->pub = htbl; /* fill in back link */
  166455. /* Figure C.1: make table of Huffman code length for each symbol */
  166456. p = 0;
  166457. for (l = 1; l <= 16; l++) {
  166458. i = (int) htbl->bits[l];
  166459. if (i < 0 || p + i > 256) /* protect against table overrun */
  166460. ERREXIT(cinfo, JERR_BAD_HUFF_TABLE);
  166461. while (i--)
  166462. huffsize[p++] = (char) l;
  166463. }
  166464. huffsize[p] = 0;
  166465. numsymbols = p;
  166466. /* Figure C.2: generate the codes themselves */
  166467. /* We also validate that the counts represent a legal Huffman code tree. */
  166468. code = 0;
  166469. si = huffsize[0];
  166470. p = 0;
  166471. while (huffsize[p]) {
  166472. while (((int) huffsize[p]) == si) {
  166473. huffcode[p++] = code;
  166474. code++;
  166475. }
  166476. /* code is now 1 more than the last code used for codelength si; but
  166477. * it must still fit in si bits, since no code is allowed to be all ones.
  166478. */
  166479. if (((INT32) code) >= (((INT32) 1) << si))
  166480. ERREXIT(cinfo, JERR_BAD_HUFF_TABLE);
  166481. code <<= 1;
  166482. si++;
  166483. }
  166484. /* Figure F.15: generate decoding tables for bit-sequential decoding */
  166485. p = 0;
  166486. for (l = 1; l <= 16; l++) {
  166487. if (htbl->bits[l]) {
  166488. /* valoffset[l] = huffval[] index of 1st symbol of code length l,
  166489. * minus the minimum code of length l
  166490. */
  166491. dtbl->valoffset[l] = (INT32) p - (INT32) huffcode[p];
  166492. p += htbl->bits[l];
  166493. dtbl->maxcode[l] = huffcode[p-1]; /* maximum code of length l */
  166494. } else {
  166495. dtbl->maxcode[l] = -1; /* -1 if no codes of this length */
  166496. }
  166497. }
  166498. dtbl->maxcode[17] = 0xFFFFFL; /* ensures jpeg_huff_decode terminates */
  166499. /* Compute lookahead tables to speed up decoding.
  166500. * First we set all the table entries to 0, indicating "too long";
  166501. * then we iterate through the Huffman codes that are short enough and
  166502. * fill in all the entries that correspond to bit sequences starting
  166503. * with that code.
  166504. */
  166505. MEMZERO(dtbl->look_nbits, SIZEOF(dtbl->look_nbits));
  166506. p = 0;
  166507. for (l = 1; l <= HUFF_LOOKAHEAD; l++) {
  166508. for (i = 1; i <= (int) htbl->bits[l]; i++, p++) {
  166509. /* l = current code's length, p = its index in huffcode[] & huffval[]. */
  166510. /* Generate left-justified code followed by all possible bit sequences */
  166511. lookbits = huffcode[p] << (HUFF_LOOKAHEAD-l);
  166512. for (ctr = 1 << (HUFF_LOOKAHEAD-l); ctr > 0; ctr--) {
  166513. dtbl->look_nbits[lookbits] = l;
  166514. dtbl->look_sym[lookbits] = htbl->huffval[p];
  166515. lookbits++;
  166516. }
  166517. }
  166518. }
  166519. /* Validate symbols as being reasonable.
  166520. * For AC tables, we make no check, but accept all byte values 0..255.
  166521. * For DC tables, we require the symbols to be in range 0..15.
  166522. * (Tighter bounds could be applied depending on the data depth and mode,
  166523. * but this is sufficient to ensure safe decoding.)
  166524. */
  166525. if (isDC) {
  166526. for (i = 0; i < numsymbols; i++) {
  166527. int sym = htbl->huffval[i];
  166528. if (sym < 0 || sym > 15)
  166529. ERREXIT(cinfo, JERR_BAD_HUFF_TABLE);
  166530. }
  166531. }
  166532. }
  166533. /*
  166534. * Out-of-line code for bit fetching (shared with jdphuff.c).
  166535. * See jdhuff.h for info about usage.
  166536. * Note: current values of get_buffer and bits_left are passed as parameters,
  166537. * but are returned in the corresponding fields of the state struct.
  166538. *
  166539. * On most machines MIN_GET_BITS should be 25 to allow the full 32-bit width
  166540. * of get_buffer to be used. (On machines with wider words, an even larger
  166541. * buffer could be used.) However, on some machines 32-bit shifts are
  166542. * quite slow and take time proportional to the number of places shifted.
  166543. * (This is true with most PC compilers, for instance.) In this case it may
  166544. * be a win to set MIN_GET_BITS to the minimum value of 15. This reduces the
  166545. * average shift distance at the cost of more calls to jpeg_fill_bit_buffer.
  166546. */
  166547. #ifdef SLOW_SHIFT_32
  166548. #define MIN_GET_BITS 15 /* minimum allowable value */
  166549. #else
  166550. #define MIN_GET_BITS (BIT_BUF_SIZE-7)
  166551. #endif
  166552. GLOBAL(boolean)
  166553. jpeg_fill_bit_buffer (bitread_working_state * state,
  166554. register bit_buf_type get_buffer, register int bits_left,
  166555. int nbits)
  166556. /* Load up the bit buffer to a depth of at least nbits */
  166557. {
  166558. /* Copy heavily used state fields into locals (hopefully registers) */
  166559. register const JOCTET * next_input_byte = state->next_input_byte;
  166560. register size_t bytes_in_buffer = state->bytes_in_buffer;
  166561. j_decompress_ptr cinfo = state->cinfo;
  166562. /* Attempt to load at least MIN_GET_BITS bits into get_buffer. */
  166563. /* (It is assumed that no request will be for more than that many bits.) */
  166564. /* We fail to do so only if we hit a marker or are forced to suspend. */
  166565. if (cinfo->unread_marker == 0) { /* cannot advance past a marker */
  166566. while (bits_left < MIN_GET_BITS) {
  166567. register int c;
  166568. /* Attempt to read a byte */
  166569. if (bytes_in_buffer == 0) {
  166570. if (! (*cinfo->src->fill_input_buffer) (cinfo))
  166571. return FALSE;
  166572. next_input_byte = cinfo->src->next_input_byte;
  166573. bytes_in_buffer = cinfo->src->bytes_in_buffer;
  166574. }
  166575. bytes_in_buffer--;
  166576. c = GETJOCTET(*next_input_byte++);
  166577. /* If it's 0xFF, check and discard stuffed zero byte */
  166578. if (c == 0xFF) {
  166579. /* Loop here to discard any padding FF's on terminating marker,
  166580. * so that we can save a valid unread_marker value. NOTE: we will
  166581. * accept multiple FF's followed by a 0 as meaning a single FF data
  166582. * byte. This data pattern is not valid according to the standard.
  166583. */
  166584. do {
  166585. if (bytes_in_buffer == 0) {
  166586. if (! (*cinfo->src->fill_input_buffer) (cinfo))
  166587. return FALSE;
  166588. next_input_byte = cinfo->src->next_input_byte;
  166589. bytes_in_buffer = cinfo->src->bytes_in_buffer;
  166590. }
  166591. bytes_in_buffer--;
  166592. c = GETJOCTET(*next_input_byte++);
  166593. } while (c == 0xFF);
  166594. if (c == 0) {
  166595. /* Found FF/00, which represents an FF data byte */
  166596. c = 0xFF;
  166597. } else {
  166598. /* Oops, it's actually a marker indicating end of compressed data.
  166599. * Save the marker code for later use.
  166600. * Fine point: it might appear that we should save the marker into
  166601. * bitread working state, not straight into permanent state. But
  166602. * once we have hit a marker, we cannot need to suspend within the
  166603. * current MCU, because we will read no more bytes from the data
  166604. * source. So it is OK to update permanent state right away.
  166605. */
  166606. cinfo->unread_marker = c;
  166607. /* See if we need to insert some fake zero bits. */
  166608. goto no_more_bytes;
  166609. }
  166610. }
  166611. /* OK, load c into get_buffer */
  166612. get_buffer = (get_buffer << 8) | c;
  166613. bits_left += 8;
  166614. } /* end while */
  166615. } else {
  166616. no_more_bytes:
  166617. /* We get here if we've read the marker that terminates the compressed
  166618. * data segment. There should be enough bits in the buffer register
  166619. * to satisfy the request; if so, no problem.
  166620. */
  166621. if (nbits > bits_left) {
  166622. /* Uh-oh. Report corrupted data to user and stuff zeroes into
  166623. * the data stream, so that we can produce some kind of image.
  166624. * We use a nonvolatile flag to ensure that only one warning message
  166625. * appears per data segment.
  166626. */
  166627. if (! cinfo->entropy->insufficient_data) {
  166628. WARNMS(cinfo, JWRN_HIT_MARKER);
  166629. cinfo->entropy->insufficient_data = TRUE;
  166630. }
  166631. /* Fill the buffer with zero bits */
  166632. get_buffer <<= MIN_GET_BITS - bits_left;
  166633. bits_left = MIN_GET_BITS;
  166634. }
  166635. }
  166636. /* Unload the local registers */
  166637. state->next_input_byte = next_input_byte;
  166638. state->bytes_in_buffer = bytes_in_buffer;
  166639. state->get_buffer = get_buffer;
  166640. state->bits_left = bits_left;
  166641. return TRUE;
  166642. }
  166643. /*
  166644. * Out-of-line code for Huffman code decoding.
  166645. * See jdhuff.h for info about usage.
  166646. */
  166647. GLOBAL(int)
  166648. jpeg_huff_decode (bitread_working_state * state,
  166649. register bit_buf_type get_buffer, register int bits_left,
  166650. d_derived_tbl * htbl, int min_bits)
  166651. {
  166652. register int l = min_bits;
  166653. register INT32 code;
  166654. /* HUFF_DECODE has determined that the code is at least min_bits */
  166655. /* bits long, so fetch that many bits in one swoop. */
  166656. CHECK_BIT_BUFFER(*state, l, return -1);
  166657. code = GET_BITS(l);
  166658. /* Collect the rest of the Huffman code one bit at a time. */
  166659. /* This is per Figure F.16 in the JPEG spec. */
  166660. while (code > htbl->maxcode[l]) {
  166661. code <<= 1;
  166662. CHECK_BIT_BUFFER(*state, 1, return -1);
  166663. code |= GET_BITS(1);
  166664. l++;
  166665. }
  166666. /* Unload the local registers */
  166667. state->get_buffer = get_buffer;
  166668. state->bits_left = bits_left;
  166669. /* With garbage input we may reach the sentinel value l = 17. */
  166670. if (l > 16) {
  166671. WARNMS(state->cinfo, JWRN_HUFF_BAD_CODE);
  166672. return 0; /* fake a zero as the safest result */
  166673. }
  166674. return htbl->pub->huffval[ (int) (code + htbl->valoffset[l]) ];
  166675. }
  166676. /*
  166677. * Check for a restart marker & resynchronize decoder.
  166678. * Returns FALSE if must suspend.
  166679. */
  166680. LOCAL(boolean)
  166681. process_restart (j_decompress_ptr cinfo)
  166682. {
  166683. huff_entropy_ptr2 entropy = (huff_entropy_ptr2) cinfo->entropy;
  166684. int ci;
  166685. /* Throw away any unused bits remaining in bit buffer; */
  166686. /* include any full bytes in next_marker's count of discarded bytes */
  166687. cinfo->marker->discarded_bytes += entropy->bitstate.bits_left / 8;
  166688. entropy->bitstate.bits_left = 0;
  166689. /* Advance past the RSTn marker */
  166690. if (! (*cinfo->marker->read_restart_marker) (cinfo))
  166691. return FALSE;
  166692. /* Re-initialize DC predictions to 0 */
  166693. for (ci = 0; ci < cinfo->comps_in_scan; ci++)
  166694. entropy->saved.last_dc_val[ci] = 0;
  166695. /* Reset restart counter */
  166696. entropy->restarts_to_go = cinfo->restart_interval;
  166697. /* Reset out-of-data flag, unless read_restart_marker left us smack up
  166698. * against a marker. In that case we will end up treating the next data
  166699. * segment as empty, and we can avoid producing bogus output pixels by
  166700. * leaving the flag set.
  166701. */
  166702. if (cinfo->unread_marker == 0)
  166703. entropy->pub.insufficient_data = FALSE;
  166704. return TRUE;
  166705. }
  166706. /*
  166707. * Decode and return one MCU's worth of Huffman-compressed coefficients.
  166708. * The coefficients are reordered from zigzag order into natural array order,
  166709. * but are not dequantized.
  166710. *
  166711. * The i'th block of the MCU is stored into the block pointed to by
  166712. * MCU_data[i]. WE ASSUME THIS AREA HAS BEEN ZEROED BY THE CALLER.
  166713. * (Wholesale zeroing is usually a little faster than retail...)
  166714. *
  166715. * Returns FALSE if data source requested suspension. In that case no
  166716. * changes have been made to permanent state. (Exception: some output
  166717. * coefficients may already have been assigned. This is harmless for
  166718. * this module, since we'll just re-assign them on the next call.)
  166719. */
  166720. METHODDEF(boolean)
  166721. decode_mcu (j_decompress_ptr cinfo, JBLOCKROW *MCU_data)
  166722. {
  166723. huff_entropy_ptr2 entropy = (huff_entropy_ptr2) cinfo->entropy;
  166724. int blkn;
  166725. BITREAD_STATE_VARS;
  166726. savable_state2 state;
  166727. /* Process restart marker if needed; may have to suspend */
  166728. if (cinfo->restart_interval) {
  166729. if (entropy->restarts_to_go == 0)
  166730. if (! process_restart(cinfo))
  166731. return FALSE;
  166732. }
  166733. /* If we've run out of data, just leave the MCU set to zeroes.
  166734. * This way, we return uniform gray for the remainder of the segment.
  166735. */
  166736. if (! entropy->pub.insufficient_data) {
  166737. /* Load up working state */
  166738. BITREAD_LOAD_STATE(cinfo,entropy->bitstate);
  166739. ASSIGN_STATE(state, entropy->saved);
  166740. /* Outer loop handles each block in the MCU */
  166741. for (blkn = 0; blkn < cinfo->blocks_in_MCU; blkn++) {
  166742. JBLOCKROW block = MCU_data[blkn];
  166743. d_derived_tbl * dctbl = entropy->dc_cur_tbls[blkn];
  166744. d_derived_tbl * actbl = entropy->ac_cur_tbls[blkn];
  166745. register int s, k, r;
  166746. /* Decode a single block's worth of coefficients */
  166747. /* Section F.2.2.1: decode the DC coefficient difference */
  166748. HUFF_DECODE(s, br_state, dctbl, return FALSE, label1);
  166749. if (s) {
  166750. CHECK_BIT_BUFFER(br_state, s, return FALSE);
  166751. r = GET_BITS(s);
  166752. s = HUFF_EXTEND(r, s);
  166753. }
  166754. if (entropy->dc_needed[blkn]) {
  166755. /* Convert DC difference to actual value, update last_dc_val */
  166756. int ci = cinfo->MCU_membership[blkn];
  166757. s += state.last_dc_val[ci];
  166758. state.last_dc_val[ci] = s;
  166759. /* Output the DC coefficient (assumes jpeg_natural_order[0] = 0) */
  166760. (*block)[0] = (JCOEF) s;
  166761. }
  166762. if (entropy->ac_needed[blkn]) {
  166763. /* Section F.2.2.2: decode the AC coefficients */
  166764. /* Since zeroes are skipped, output area must be cleared beforehand */
  166765. for (k = 1; k < DCTSIZE2; k++) {
  166766. HUFF_DECODE(s, br_state, actbl, return FALSE, label2);
  166767. r = s >> 4;
  166768. s &= 15;
  166769. if (s) {
  166770. k += r;
  166771. CHECK_BIT_BUFFER(br_state, s, return FALSE);
  166772. r = GET_BITS(s);
  166773. s = HUFF_EXTEND(r, s);
  166774. /* Output coefficient in natural (dezigzagged) order.
  166775. * Note: the extra entries in jpeg_natural_order[] will save us
  166776. * if k >= DCTSIZE2, which could happen if the data is corrupted.
  166777. */
  166778. (*block)[jpeg_natural_order[k]] = (JCOEF) s;
  166779. } else {
  166780. if (r != 15)
  166781. break;
  166782. k += 15;
  166783. }
  166784. }
  166785. } else {
  166786. /* Section F.2.2.2: decode the AC coefficients */
  166787. /* In this path we just discard the values */
  166788. for (k = 1; k < DCTSIZE2; k++) {
  166789. HUFF_DECODE(s, br_state, actbl, return FALSE, label3);
  166790. r = s >> 4;
  166791. s &= 15;
  166792. if (s) {
  166793. k += r;
  166794. CHECK_BIT_BUFFER(br_state, s, return FALSE);
  166795. DROP_BITS(s);
  166796. } else {
  166797. if (r != 15)
  166798. break;
  166799. k += 15;
  166800. }
  166801. }
  166802. }
  166803. }
  166804. /* Completed MCU, so update state */
  166805. BITREAD_SAVE_STATE(cinfo,entropy->bitstate);
  166806. ASSIGN_STATE(entropy->saved, state);
  166807. }
  166808. /* Account for restart interval (no-op if not using restarts) */
  166809. entropy->restarts_to_go--;
  166810. return TRUE;
  166811. }
  166812. /*
  166813. * Module initialization routine for Huffman entropy decoding.
  166814. */
  166815. GLOBAL(void)
  166816. jinit_huff_decoder (j_decompress_ptr cinfo)
  166817. {
  166818. huff_entropy_ptr2 entropy;
  166819. int i;
  166820. entropy = (huff_entropy_ptr2)
  166821. (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_IMAGE,
  166822. SIZEOF(huff_entropy_decoder2));
  166823. cinfo->entropy = (struct jpeg_entropy_decoder *) entropy;
  166824. entropy->pub.start_pass = start_pass_huff_decoder;
  166825. entropy->pub.decode_mcu = decode_mcu;
  166826. /* Mark tables unallocated */
  166827. for (i = 0; i < NUM_HUFF_TBLS; i++) {
  166828. entropy->dc_derived_tbls[i] = entropy->ac_derived_tbls[i] = NULL;
  166829. }
  166830. }
  166831. /*** End of inlined file: jdhuff.c ***/
  166832. /*** Start of inlined file: jdinput.c ***/
  166833. #define JPEG_INTERNALS
  166834. /* Private state */
  166835. typedef struct {
  166836. struct jpeg_input_controller pub; /* public fields */
  166837. boolean inheaders; /* TRUE until first SOS is reached */
  166838. } my_input_controller;
  166839. typedef my_input_controller * my_inputctl_ptr;
  166840. /* Forward declarations */
  166841. METHODDEF(int) consume_markers JPP((j_decompress_ptr cinfo));
  166842. /*
  166843. * Routines to calculate various quantities related to the size of the image.
  166844. */
  166845. LOCAL(void)
  166846. initial_setup2 (j_decompress_ptr cinfo)
  166847. /* Called once, when first SOS marker is reached */
  166848. {
  166849. int ci;
  166850. jpeg_component_info *compptr;
  166851. /* Make sure image isn't bigger than I can handle */
  166852. if ((long) cinfo->image_height > (long) JPEG_MAX_DIMENSION ||
  166853. (long) cinfo->image_width > (long) JPEG_MAX_DIMENSION)
  166854. ERREXIT1(cinfo, JERR_IMAGE_TOO_BIG, (unsigned int) JPEG_MAX_DIMENSION);
  166855. /* For now, precision must match compiled-in value... */
  166856. if (cinfo->data_precision != BITS_IN_JSAMPLE)
  166857. ERREXIT1(cinfo, JERR_BAD_PRECISION, cinfo->data_precision);
  166858. /* Check that number of components won't exceed internal array sizes */
  166859. if (cinfo->num_components > MAX_COMPONENTS)
  166860. ERREXIT2(cinfo, JERR_COMPONENT_COUNT, cinfo->num_components,
  166861. MAX_COMPONENTS);
  166862. /* Compute maximum sampling factors; check factor validity */
  166863. cinfo->max_h_samp_factor = 1;
  166864. cinfo->max_v_samp_factor = 1;
  166865. for (ci = 0, compptr = cinfo->comp_info; ci < cinfo->num_components;
  166866. ci++, compptr++) {
  166867. if (compptr->h_samp_factor<=0 || compptr->h_samp_factor>MAX_SAMP_FACTOR ||
  166868. compptr->v_samp_factor<=0 || compptr->v_samp_factor>MAX_SAMP_FACTOR)
  166869. ERREXIT(cinfo, JERR_BAD_SAMPLING);
  166870. cinfo->max_h_samp_factor = MAX(cinfo->max_h_samp_factor,
  166871. compptr->h_samp_factor);
  166872. cinfo->max_v_samp_factor = MAX(cinfo->max_v_samp_factor,
  166873. compptr->v_samp_factor);
  166874. }
  166875. /* We initialize DCT_scaled_size and min_DCT_scaled_size to DCTSIZE.
  166876. * In the full decompressor, this will be overridden by jdmaster.c;
  166877. * but in the transcoder, jdmaster.c is not used, so we must do it here.
  166878. */
  166879. cinfo->min_DCT_scaled_size = DCTSIZE;
  166880. /* Compute dimensions of components */
  166881. for (ci = 0, compptr = cinfo->comp_info; ci < cinfo->num_components;
  166882. ci++, compptr++) {
  166883. compptr->DCT_scaled_size = DCTSIZE;
  166884. /* Size in DCT blocks */
  166885. compptr->width_in_blocks = (JDIMENSION)
  166886. jdiv_round_up((long) cinfo->image_width * (long) compptr->h_samp_factor,
  166887. (long) (cinfo->max_h_samp_factor * DCTSIZE));
  166888. compptr->height_in_blocks = (JDIMENSION)
  166889. jdiv_round_up((long) cinfo->image_height * (long) compptr->v_samp_factor,
  166890. (long) (cinfo->max_v_samp_factor * DCTSIZE));
  166891. /* downsampled_width and downsampled_height will also be overridden by
  166892. * jdmaster.c if we are doing full decompression. The transcoder library
  166893. * doesn't use these values, but the calling application might.
  166894. */
  166895. /* Size in samples */
  166896. compptr->downsampled_width = (JDIMENSION)
  166897. jdiv_round_up((long) cinfo->image_width * (long) compptr->h_samp_factor,
  166898. (long) cinfo->max_h_samp_factor);
  166899. compptr->downsampled_height = (JDIMENSION)
  166900. jdiv_round_up((long) cinfo->image_height * (long) compptr->v_samp_factor,
  166901. (long) cinfo->max_v_samp_factor);
  166902. /* Mark component needed, until color conversion says otherwise */
  166903. compptr->component_needed = TRUE;
  166904. /* Mark no quantization table yet saved for component */
  166905. compptr->quant_table = NULL;
  166906. }
  166907. /* Compute number of fully interleaved MCU rows. */
  166908. cinfo->total_iMCU_rows = (JDIMENSION)
  166909. jdiv_round_up((long) cinfo->image_height,
  166910. (long) (cinfo->max_v_samp_factor*DCTSIZE));
  166911. /* Decide whether file contains multiple scans */
  166912. if (cinfo->comps_in_scan < cinfo->num_components || cinfo->progressive_mode)
  166913. cinfo->inputctl->has_multiple_scans = TRUE;
  166914. else
  166915. cinfo->inputctl->has_multiple_scans = FALSE;
  166916. }
  166917. LOCAL(void)
  166918. per_scan_setup2 (j_decompress_ptr cinfo)
  166919. /* Do computations that are needed before processing a JPEG scan */
  166920. /* cinfo->comps_in_scan and cinfo->cur_comp_info[] were set from SOS marker */
  166921. {
  166922. int ci, mcublks, tmp;
  166923. jpeg_component_info *compptr;
  166924. if (cinfo->comps_in_scan == 1) {
  166925. /* Noninterleaved (single-component) scan */
  166926. compptr = cinfo->cur_comp_info[0];
  166927. /* Overall image size in MCUs */
  166928. cinfo->MCUs_per_row = compptr->width_in_blocks;
  166929. cinfo->MCU_rows_in_scan = compptr->height_in_blocks;
  166930. /* For noninterleaved scan, always one block per MCU */
  166931. compptr->MCU_width = 1;
  166932. compptr->MCU_height = 1;
  166933. compptr->MCU_blocks = 1;
  166934. compptr->MCU_sample_width = compptr->DCT_scaled_size;
  166935. compptr->last_col_width = 1;
  166936. /* For noninterleaved scans, it is convenient to define last_row_height
  166937. * as the number of block rows present in the last iMCU row.
  166938. */
  166939. tmp = (int) (compptr->height_in_blocks % compptr->v_samp_factor);
  166940. if (tmp == 0) tmp = compptr->v_samp_factor;
  166941. compptr->last_row_height = tmp;
  166942. /* Prepare array describing MCU composition */
  166943. cinfo->blocks_in_MCU = 1;
  166944. cinfo->MCU_membership[0] = 0;
  166945. } else {
  166946. /* Interleaved (multi-component) scan */
  166947. if (cinfo->comps_in_scan <= 0 || cinfo->comps_in_scan > MAX_COMPS_IN_SCAN)
  166948. ERREXIT2(cinfo, JERR_COMPONENT_COUNT, cinfo->comps_in_scan,
  166949. MAX_COMPS_IN_SCAN);
  166950. /* Overall image size in MCUs */
  166951. cinfo->MCUs_per_row = (JDIMENSION)
  166952. jdiv_round_up((long) cinfo->image_width,
  166953. (long) (cinfo->max_h_samp_factor*DCTSIZE));
  166954. cinfo->MCU_rows_in_scan = (JDIMENSION)
  166955. jdiv_round_up((long) cinfo->image_height,
  166956. (long) (cinfo->max_v_samp_factor*DCTSIZE));
  166957. cinfo->blocks_in_MCU = 0;
  166958. for (ci = 0; ci < cinfo->comps_in_scan; ci++) {
  166959. compptr = cinfo->cur_comp_info[ci];
  166960. /* Sampling factors give # of blocks of component in each MCU */
  166961. compptr->MCU_width = compptr->h_samp_factor;
  166962. compptr->MCU_height = compptr->v_samp_factor;
  166963. compptr->MCU_blocks = compptr->MCU_width * compptr->MCU_height;
  166964. compptr->MCU_sample_width = compptr->MCU_width * compptr->DCT_scaled_size;
  166965. /* Figure number of non-dummy blocks in last MCU column & row */
  166966. tmp = (int) (compptr->width_in_blocks % compptr->MCU_width);
  166967. if (tmp == 0) tmp = compptr->MCU_width;
  166968. compptr->last_col_width = tmp;
  166969. tmp = (int) (compptr->height_in_blocks % compptr->MCU_height);
  166970. if (tmp == 0) tmp = compptr->MCU_height;
  166971. compptr->last_row_height = tmp;
  166972. /* Prepare array describing MCU composition */
  166973. mcublks = compptr->MCU_blocks;
  166974. if (cinfo->blocks_in_MCU + mcublks > D_MAX_BLOCKS_IN_MCU)
  166975. ERREXIT(cinfo, JERR_BAD_MCU_SIZE);
  166976. while (mcublks-- > 0) {
  166977. cinfo->MCU_membership[cinfo->blocks_in_MCU++] = ci;
  166978. }
  166979. }
  166980. }
  166981. }
  166982. /*
  166983. * Save away a copy of the Q-table referenced by each component present
  166984. * in the current scan, unless already saved during a prior scan.
  166985. *
  166986. * In a multiple-scan JPEG file, the encoder could assign different components
  166987. * the same Q-table slot number, but change table definitions between scans
  166988. * so that each component uses a different Q-table. (The IJG encoder is not
  166989. * currently capable of doing this, but other encoders might.) Since we want
  166990. * to be able to dequantize all the components at the end of the file, this
  166991. * means that we have to save away the table actually used for each component.
  166992. * We do this by copying the table at the start of the first scan containing
  166993. * the component.
  166994. * The JPEG spec prohibits the encoder from changing the contents of a Q-table
  166995. * slot between scans of a component using that slot. If the encoder does so
  166996. * anyway, this decoder will simply use the Q-table values that were current
  166997. * at the start of the first scan for the component.
  166998. *
  166999. * The decompressor output side looks only at the saved quant tables,
  167000. * not at the current Q-table slots.
  167001. */
  167002. LOCAL(void)
  167003. latch_quant_tables (j_decompress_ptr cinfo)
  167004. {
  167005. int ci, qtblno;
  167006. jpeg_component_info *compptr;
  167007. JQUANT_TBL * qtbl;
  167008. for (ci = 0; ci < cinfo->comps_in_scan; ci++) {
  167009. compptr = cinfo->cur_comp_info[ci];
  167010. /* No work if we already saved Q-table for this component */
  167011. if (compptr->quant_table != NULL)
  167012. continue;
  167013. /* Make sure specified quantization table is present */
  167014. qtblno = compptr->quant_tbl_no;
  167015. if (qtblno < 0 || qtblno >= NUM_QUANT_TBLS ||
  167016. cinfo->quant_tbl_ptrs[qtblno] == NULL)
  167017. ERREXIT1(cinfo, JERR_NO_QUANT_TABLE, qtblno);
  167018. /* OK, save away the quantization table */
  167019. qtbl = (JQUANT_TBL *)
  167020. (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_IMAGE,
  167021. SIZEOF(JQUANT_TBL));
  167022. MEMCOPY(qtbl, cinfo->quant_tbl_ptrs[qtblno], SIZEOF(JQUANT_TBL));
  167023. compptr->quant_table = qtbl;
  167024. }
  167025. }
  167026. /*
  167027. * Initialize the input modules to read a scan of compressed data.
  167028. * The first call to this is done by jdmaster.c after initializing
  167029. * the entire decompressor (during jpeg_start_decompress).
  167030. * Subsequent calls come from consume_markers, below.
  167031. */
  167032. METHODDEF(void)
  167033. start_input_pass2 (j_decompress_ptr cinfo)
  167034. {
  167035. per_scan_setup2(cinfo);
  167036. latch_quant_tables(cinfo);
  167037. (*cinfo->entropy->start_pass) (cinfo);
  167038. (*cinfo->coef->start_input_pass) (cinfo);
  167039. cinfo->inputctl->consume_input = cinfo->coef->consume_data;
  167040. }
  167041. /*
  167042. * Finish up after inputting a compressed-data scan.
  167043. * This is called by the coefficient controller after it's read all
  167044. * the expected data of the scan.
  167045. */
  167046. METHODDEF(void)
  167047. finish_input_pass (j_decompress_ptr cinfo)
  167048. {
  167049. cinfo->inputctl->consume_input = consume_markers;
  167050. }
  167051. /*
  167052. * Read JPEG markers before, between, or after compressed-data scans.
  167053. * Change state as necessary when a new scan is reached.
  167054. * Return value is JPEG_SUSPENDED, JPEG_REACHED_SOS, or JPEG_REACHED_EOI.
  167055. *
  167056. * The consume_input method pointer points either here or to the
  167057. * coefficient controller's consume_data routine, depending on whether
  167058. * we are reading a compressed data segment or inter-segment markers.
  167059. */
  167060. METHODDEF(int)
  167061. consume_markers (j_decompress_ptr cinfo)
  167062. {
  167063. my_inputctl_ptr inputctl = (my_inputctl_ptr) cinfo->inputctl;
  167064. int val;
  167065. if (inputctl->pub.eoi_reached) /* After hitting EOI, read no further */
  167066. return JPEG_REACHED_EOI;
  167067. val = (*cinfo->marker->read_markers) (cinfo);
  167068. switch (val) {
  167069. case JPEG_REACHED_SOS: /* Found SOS */
  167070. if (inputctl->inheaders) { /* 1st SOS */
  167071. initial_setup2(cinfo);
  167072. inputctl->inheaders = FALSE;
  167073. /* Note: start_input_pass must be called by jdmaster.c
  167074. * before any more input can be consumed. jdapimin.c is
  167075. * responsible for enforcing this sequencing.
  167076. */
  167077. } else { /* 2nd or later SOS marker */
  167078. if (! inputctl->pub.has_multiple_scans)
  167079. ERREXIT(cinfo, JERR_EOI_EXPECTED); /* Oops, I wasn't expecting this! */
  167080. start_input_pass2(cinfo);
  167081. }
  167082. break;
  167083. case JPEG_REACHED_EOI: /* Found EOI */
  167084. inputctl->pub.eoi_reached = TRUE;
  167085. if (inputctl->inheaders) { /* Tables-only datastream, apparently */
  167086. if (cinfo->marker->saw_SOF)
  167087. ERREXIT(cinfo, JERR_SOF_NO_SOS);
  167088. } else {
  167089. /* Prevent infinite loop in coef ctlr's decompress_data routine
  167090. * if user set output_scan_number larger than number of scans.
  167091. */
  167092. if (cinfo->output_scan_number > cinfo->input_scan_number)
  167093. cinfo->output_scan_number = cinfo->input_scan_number;
  167094. }
  167095. break;
  167096. case JPEG_SUSPENDED:
  167097. break;
  167098. }
  167099. return val;
  167100. }
  167101. /*
  167102. * Reset state to begin a fresh datastream.
  167103. */
  167104. METHODDEF(void)
  167105. reset_input_controller (j_decompress_ptr cinfo)
  167106. {
  167107. my_inputctl_ptr inputctl = (my_inputctl_ptr) cinfo->inputctl;
  167108. inputctl->pub.consume_input = consume_markers;
  167109. inputctl->pub.has_multiple_scans = FALSE; /* "unknown" would be better */
  167110. inputctl->pub.eoi_reached = FALSE;
  167111. inputctl->inheaders = TRUE;
  167112. /* Reset other modules */
  167113. (*cinfo->err->reset_error_mgr) ((j_common_ptr) cinfo);
  167114. (*cinfo->marker->reset_marker_reader) (cinfo);
  167115. /* Reset progression state -- would be cleaner if entropy decoder did this */
  167116. cinfo->coef_bits = NULL;
  167117. }
  167118. /*
  167119. * Initialize the input controller module.
  167120. * This is called only once, when the decompression object is created.
  167121. */
  167122. GLOBAL(void)
  167123. jinit_input_controller (j_decompress_ptr cinfo)
  167124. {
  167125. my_inputctl_ptr inputctl;
  167126. /* Create subobject in permanent pool */
  167127. inputctl = (my_inputctl_ptr)
  167128. (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_PERMANENT,
  167129. SIZEOF(my_input_controller));
  167130. cinfo->inputctl = (struct jpeg_input_controller *) inputctl;
  167131. /* Initialize method pointers */
  167132. inputctl->pub.consume_input = consume_markers;
  167133. inputctl->pub.reset_input_controller = reset_input_controller;
  167134. inputctl->pub.start_input_pass = start_input_pass2;
  167135. inputctl->pub.finish_input_pass = finish_input_pass;
  167136. /* Initialize state: can't use reset_input_controller since we don't
  167137. * want to try to reset other modules yet.
  167138. */
  167139. inputctl->pub.has_multiple_scans = FALSE; /* "unknown" would be better */
  167140. inputctl->pub.eoi_reached = FALSE;
  167141. inputctl->inheaders = TRUE;
  167142. }
  167143. /*** End of inlined file: jdinput.c ***/
  167144. /*** Start of inlined file: jdmainct.c ***/
  167145. #define JPEG_INTERNALS
  167146. /*
  167147. * In the current system design, the main buffer need never be a full-image
  167148. * buffer; any full-height buffers will be found inside the coefficient or
  167149. * postprocessing controllers. Nonetheless, the main controller is not
  167150. * trivial. Its responsibility is to provide context rows for upsampling/
  167151. * rescaling, and doing this in an efficient fashion is a bit tricky.
  167152. *
  167153. * Postprocessor input data is counted in "row groups". A row group
  167154. * is defined to be (v_samp_factor * DCT_scaled_size / min_DCT_scaled_size)
  167155. * sample rows of each component. (We require DCT_scaled_size values to be
  167156. * chosen such that these numbers are integers. In practice DCT_scaled_size
  167157. * values will likely be powers of two, so we actually have the stronger
  167158. * condition that DCT_scaled_size / min_DCT_scaled_size is an integer.)
  167159. * Upsampling will typically produce max_v_samp_factor pixel rows from each
  167160. * row group (times any additional scale factor that the upsampler is
  167161. * applying).
  167162. *
  167163. * The coefficient controller will deliver data to us one iMCU row at a time;
  167164. * each iMCU row contains v_samp_factor * DCT_scaled_size sample rows, or
  167165. * exactly min_DCT_scaled_size row groups. (This amount of data corresponds
  167166. * to one row of MCUs when the image is fully interleaved.) Note that the
  167167. * number of sample rows varies across components, but the number of row
  167168. * groups does not. Some garbage sample rows may be included in the last iMCU
  167169. * row at the bottom of the image.
  167170. *
  167171. * Depending on the vertical scaling algorithm used, the upsampler may need
  167172. * access to the sample row(s) above and below its current input row group.
  167173. * The upsampler is required to set need_context_rows TRUE at global selection
  167174. * time if so. When need_context_rows is FALSE, this controller can simply
  167175. * obtain one iMCU row at a time from the coefficient controller and dole it
  167176. * out as row groups to the postprocessor.
  167177. *
  167178. * When need_context_rows is TRUE, this controller guarantees that the buffer
  167179. * passed to postprocessing contains at least one row group's worth of samples
  167180. * above and below the row group(s) being processed. Note that the context
  167181. * rows "above" the first passed row group appear at negative row offsets in
  167182. * the passed buffer. At the top and bottom of the image, the required
  167183. * context rows are manufactured by duplicating the first or last real sample
  167184. * row; this avoids having special cases in the upsampling inner loops.
  167185. *
  167186. * The amount of context is fixed at one row group just because that's a
  167187. * convenient number for this controller to work with. The existing
  167188. * upsamplers really only need one sample row of context. An upsampler
  167189. * supporting arbitrary output rescaling might wish for more than one row
  167190. * group of context when shrinking the image; tough, we don't handle that.
  167191. * (This is justified by the assumption that downsizing will be handled mostly
  167192. * by adjusting the DCT_scaled_size values, so that the actual scale factor at
  167193. * the upsample step needn't be much less than one.)
  167194. *
  167195. * To provide the desired context, we have to retain the last two row groups
  167196. * of one iMCU row while reading in the next iMCU row. (The last row group
  167197. * can't be processed until we have another row group for its below-context,
  167198. * and so we have to save the next-to-last group too for its above-context.)
  167199. * We could do this most simply by copying data around in our buffer, but
  167200. * that'd be very slow. We can avoid copying any data by creating a rather
  167201. * strange pointer structure. Here's how it works. We allocate a workspace
  167202. * consisting of M+2 row groups (where M = min_DCT_scaled_size is the number
  167203. * of row groups per iMCU row). We create two sets of redundant pointers to
  167204. * the workspace. Labeling the physical row groups 0 to M+1, the synthesized
  167205. * pointer lists look like this:
  167206. * M+1 M-1
  167207. * master pointer --> 0 master pointer --> 0
  167208. * 1 1
  167209. * ... ...
  167210. * M-3 M-3
  167211. * M-2 M
  167212. * M-1 M+1
  167213. * M M-2
  167214. * M+1 M-1
  167215. * 0 0
  167216. * We read alternate iMCU rows using each master pointer; thus the last two
  167217. * row groups of the previous iMCU row remain un-overwritten in the workspace.
  167218. * The pointer lists are set up so that the required context rows appear to
  167219. * be adjacent to the proper places when we pass the pointer lists to the
  167220. * upsampler.
  167221. *
  167222. * The above pictures describe the normal state of the pointer lists.
  167223. * At top and bottom of the image, we diddle the pointer lists to duplicate
  167224. * the first or last sample row as necessary (this is cheaper than copying
  167225. * sample rows around).
  167226. *
  167227. * This scheme breaks down if M < 2, ie, min_DCT_scaled_size is 1. In that
  167228. * situation each iMCU row provides only one row group so the buffering logic
  167229. * must be different (eg, we must read two iMCU rows before we can emit the
  167230. * first row group). For now, we simply do not support providing context
  167231. * rows when min_DCT_scaled_size is 1. That combination seems unlikely to
  167232. * be worth providing --- if someone wants a 1/8th-size preview, they probably
  167233. * want it quick and dirty, so a context-free upsampler is sufficient.
  167234. */
  167235. /* Private buffer controller object */
  167236. typedef struct {
  167237. struct jpeg_d_main_controller pub; /* public fields */
  167238. /* Pointer to allocated workspace (M or M+2 row groups). */
  167239. JSAMPARRAY buffer[MAX_COMPONENTS];
  167240. boolean buffer_full; /* Have we gotten an iMCU row from decoder? */
  167241. JDIMENSION rowgroup_ctr; /* counts row groups output to postprocessor */
  167242. /* Remaining fields are only used in the context case. */
  167243. /* These are the master pointers to the funny-order pointer lists. */
  167244. JSAMPIMAGE xbuffer[2]; /* pointers to weird pointer lists */
  167245. int whichptr; /* indicates which pointer set is now in use */
  167246. int context_state; /* process_data state machine status */
  167247. JDIMENSION rowgroups_avail; /* row groups available to postprocessor */
  167248. JDIMENSION iMCU_row_ctr; /* counts iMCU rows to detect image top/bot */
  167249. } my_main_controller4;
  167250. typedef my_main_controller4 * my_main_ptr4;
  167251. /* context_state values: */
  167252. #define CTX_PREPARE_FOR_IMCU 0 /* need to prepare for MCU row */
  167253. #define CTX_PROCESS_IMCU 1 /* feeding iMCU to postprocessor */
  167254. #define CTX_POSTPONED_ROW 2 /* feeding postponed row group */
  167255. /* Forward declarations */
  167256. METHODDEF(void) process_data_simple_main2
  167257. JPP((j_decompress_ptr cinfo, JSAMPARRAY output_buf,
  167258. JDIMENSION *out_row_ctr, JDIMENSION out_rows_avail));
  167259. METHODDEF(void) process_data_context_main
  167260. JPP((j_decompress_ptr cinfo, JSAMPARRAY output_buf,
  167261. JDIMENSION *out_row_ctr, JDIMENSION out_rows_avail));
  167262. #ifdef QUANT_2PASS_SUPPORTED
  167263. METHODDEF(void) process_data_crank_post
  167264. JPP((j_decompress_ptr cinfo, JSAMPARRAY output_buf,
  167265. JDIMENSION *out_row_ctr, JDIMENSION out_rows_avail));
  167266. #endif
  167267. LOCAL(void)
  167268. alloc_funny_pointers (j_decompress_ptr cinfo)
  167269. /* Allocate space for the funny pointer lists.
  167270. * This is done only once, not once per pass.
  167271. */
  167272. {
  167273. my_main_ptr4 main_ = (my_main_ptr4) cinfo->main;
  167274. int ci, rgroup;
  167275. int M = cinfo->min_DCT_scaled_size;
  167276. jpeg_component_info *compptr;
  167277. JSAMPARRAY xbuf;
  167278. /* Get top-level space for component array pointers.
  167279. * We alloc both arrays with one call to save a few cycles.
  167280. */
  167281. main_->xbuffer[0] = (JSAMPIMAGE)
  167282. (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_IMAGE,
  167283. cinfo->num_components * 2 * SIZEOF(JSAMPARRAY));
  167284. main_->xbuffer[1] = main_->xbuffer[0] + cinfo->num_components;
  167285. for (ci = 0, compptr = cinfo->comp_info; ci < cinfo->num_components;
  167286. ci++, compptr++) {
  167287. rgroup = (compptr->v_samp_factor * compptr->DCT_scaled_size) /
  167288. cinfo->min_DCT_scaled_size; /* height of a row group of component */
  167289. /* Get space for pointer lists --- M+4 row groups in each list.
  167290. * We alloc both pointer lists with one call to save a few cycles.
  167291. */
  167292. xbuf = (JSAMPARRAY)
  167293. (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_IMAGE,
  167294. 2 * (rgroup * (M + 4)) * SIZEOF(JSAMPROW));
  167295. xbuf += rgroup; /* want one row group at negative offsets */
  167296. main_->xbuffer[0][ci] = xbuf;
  167297. xbuf += rgroup * (M + 4);
  167298. main_->xbuffer[1][ci] = xbuf;
  167299. }
  167300. }
  167301. LOCAL(void)
  167302. make_funny_pointers (j_decompress_ptr cinfo)
  167303. /* Create the funny pointer lists discussed in the comments above.
  167304. * The actual workspace is already allocated (in main->buffer),
  167305. * and the space for the pointer lists is allocated too.
  167306. * This routine just fills in the curiously ordered lists.
  167307. * This will be repeated at the beginning of each pass.
  167308. */
  167309. {
  167310. my_main_ptr4 main_ = (my_main_ptr4) cinfo->main;
  167311. int ci, i, rgroup;
  167312. int M = cinfo->min_DCT_scaled_size;
  167313. jpeg_component_info *compptr;
  167314. JSAMPARRAY buf, xbuf0, xbuf1;
  167315. for (ci = 0, compptr = cinfo->comp_info; ci < cinfo->num_components;
  167316. ci++, compptr++) {
  167317. rgroup = (compptr->v_samp_factor * compptr->DCT_scaled_size) /
  167318. cinfo->min_DCT_scaled_size; /* height of a row group of component */
  167319. xbuf0 = main_->xbuffer[0][ci];
  167320. xbuf1 = main_->xbuffer[1][ci];
  167321. /* First copy the workspace pointers as-is */
  167322. buf = main_->buffer[ci];
  167323. for (i = 0; i < rgroup * (M + 2); i++) {
  167324. xbuf0[i] = xbuf1[i] = buf[i];
  167325. }
  167326. /* In the second list, put the last four row groups in swapped order */
  167327. for (i = 0; i < rgroup * 2; i++) {
  167328. xbuf1[rgroup*(M-2) + i] = buf[rgroup*M + i];
  167329. xbuf1[rgroup*M + i] = buf[rgroup*(M-2) + i];
  167330. }
  167331. /* The wraparound pointers at top and bottom will be filled later
  167332. * (see set_wraparound_pointers, below). Initially we want the "above"
  167333. * pointers to duplicate the first actual data line. This only needs
  167334. * to happen in xbuffer[0].
  167335. */
  167336. for (i = 0; i < rgroup; i++) {
  167337. xbuf0[i - rgroup] = xbuf0[0];
  167338. }
  167339. }
  167340. }
  167341. LOCAL(void)
  167342. set_wraparound_pointers (j_decompress_ptr cinfo)
  167343. /* Set up the "wraparound" pointers at top and bottom of the pointer lists.
  167344. * This changes the pointer list state from top-of-image to the normal state.
  167345. */
  167346. {
  167347. my_main_ptr4 main_ = (my_main_ptr4) cinfo->main;
  167348. int ci, i, rgroup;
  167349. int M = cinfo->min_DCT_scaled_size;
  167350. jpeg_component_info *compptr;
  167351. JSAMPARRAY xbuf0, xbuf1;
  167352. for (ci = 0, compptr = cinfo->comp_info; ci < cinfo->num_components;
  167353. ci++, compptr++) {
  167354. rgroup = (compptr->v_samp_factor * compptr->DCT_scaled_size) /
  167355. cinfo->min_DCT_scaled_size; /* height of a row group of component */
  167356. xbuf0 = main_->xbuffer[0][ci];
  167357. xbuf1 = main_->xbuffer[1][ci];
  167358. for (i = 0; i < rgroup; i++) {
  167359. xbuf0[i - rgroup] = xbuf0[rgroup*(M+1) + i];
  167360. xbuf1[i - rgroup] = xbuf1[rgroup*(M+1) + i];
  167361. xbuf0[rgroup*(M+2) + i] = xbuf0[i];
  167362. xbuf1[rgroup*(M+2) + i] = xbuf1[i];
  167363. }
  167364. }
  167365. }
  167366. LOCAL(void)
  167367. set_bottom_pointers (j_decompress_ptr cinfo)
  167368. /* Change the pointer lists to duplicate the last sample row at the bottom
  167369. * of the image. whichptr indicates which xbuffer holds the final iMCU row.
  167370. * Also sets rowgroups_avail to indicate number of nondummy row groups in row.
  167371. */
  167372. {
  167373. my_main_ptr4 main_ = (my_main_ptr4) cinfo->main;
  167374. int ci, i, rgroup, iMCUheight, rows_left;
  167375. jpeg_component_info *compptr;
  167376. JSAMPARRAY xbuf;
  167377. for (ci = 0, compptr = cinfo->comp_info; ci < cinfo->num_components;
  167378. ci++, compptr++) {
  167379. /* Count sample rows in one iMCU row and in one row group */
  167380. iMCUheight = compptr->v_samp_factor * compptr->DCT_scaled_size;
  167381. rgroup = iMCUheight / cinfo->min_DCT_scaled_size;
  167382. /* Count nondummy sample rows remaining for this component */
  167383. rows_left = (int) (compptr->downsampled_height % (JDIMENSION) iMCUheight);
  167384. if (rows_left == 0) rows_left = iMCUheight;
  167385. /* Count nondummy row groups. Should get same answer for each component,
  167386. * so we need only do it once.
  167387. */
  167388. if (ci == 0) {
  167389. main_->rowgroups_avail = (JDIMENSION) ((rows_left-1) / rgroup + 1);
  167390. }
  167391. /* Duplicate the last real sample row rgroup*2 times; this pads out the
  167392. * last partial rowgroup and ensures at least one full rowgroup of context.
  167393. */
  167394. xbuf = main_->xbuffer[main_->whichptr][ci];
  167395. for (i = 0; i < rgroup * 2; i++) {
  167396. xbuf[rows_left + i] = xbuf[rows_left-1];
  167397. }
  167398. }
  167399. }
  167400. /*
  167401. * Initialize for a processing pass.
  167402. */
  167403. METHODDEF(void)
  167404. start_pass_main2 (j_decompress_ptr cinfo, J_BUF_MODE pass_mode)
  167405. {
  167406. my_main_ptr4 main_ = (my_main_ptr4) cinfo->main;
  167407. switch (pass_mode) {
  167408. case JBUF_PASS_THRU:
  167409. if (cinfo->upsample->need_context_rows) {
  167410. main_->pub.process_data = process_data_context_main;
  167411. make_funny_pointers(cinfo); /* Create the xbuffer[] lists */
  167412. main_->whichptr = 0; /* Read first iMCU row into xbuffer[0] */
  167413. main_->context_state = CTX_PREPARE_FOR_IMCU;
  167414. main_->iMCU_row_ctr = 0;
  167415. } else {
  167416. /* Simple case with no context needed */
  167417. main_->pub.process_data = process_data_simple_main2;
  167418. }
  167419. main_->buffer_full = FALSE; /* Mark buffer empty */
  167420. main_->rowgroup_ctr = 0;
  167421. break;
  167422. #ifdef QUANT_2PASS_SUPPORTED
  167423. case JBUF_CRANK_DEST:
  167424. /* For last pass of 2-pass quantization, just crank the postprocessor */
  167425. main_->pub.process_data = process_data_crank_post;
  167426. break;
  167427. #endif
  167428. default:
  167429. ERREXIT(cinfo, JERR_BAD_BUFFER_MODE);
  167430. break;
  167431. }
  167432. }
  167433. /*
  167434. * Process some data.
  167435. * This handles the simple case where no context is required.
  167436. */
  167437. METHODDEF(void)
  167438. process_data_simple_main2 (j_decompress_ptr cinfo,
  167439. JSAMPARRAY output_buf, JDIMENSION *out_row_ctr,
  167440. JDIMENSION out_rows_avail)
  167441. {
  167442. my_main_ptr4 main_ = (my_main_ptr4) cinfo->main;
  167443. JDIMENSION rowgroups_avail;
  167444. /* Read input data if we haven't filled the main buffer yet */
  167445. if (! main_->buffer_full) {
  167446. if (! (*cinfo->coef->decompress_data) (cinfo, main_->buffer))
  167447. return; /* suspension forced, can do nothing more */
  167448. main_->buffer_full = TRUE; /* OK, we have an iMCU row to work with */
  167449. }
  167450. /* There are always min_DCT_scaled_size row groups in an iMCU row. */
  167451. rowgroups_avail = (JDIMENSION) cinfo->min_DCT_scaled_size;
  167452. /* Note: at the bottom of the image, we may pass extra garbage row groups
  167453. * to the postprocessor. The postprocessor has to check for bottom
  167454. * of image anyway (at row resolution), so no point in us doing it too.
  167455. */
  167456. /* Feed the postprocessor */
  167457. (*cinfo->post->post_process_data) (cinfo, main_->buffer,
  167458. &main_->rowgroup_ctr, rowgroups_avail,
  167459. output_buf, out_row_ctr, out_rows_avail);
  167460. /* Has postprocessor consumed all the data yet? If so, mark buffer empty */
  167461. if (main_->rowgroup_ctr >= rowgroups_avail) {
  167462. main_->buffer_full = FALSE;
  167463. main_->rowgroup_ctr = 0;
  167464. }
  167465. }
  167466. /*
  167467. * Process some data.
  167468. * This handles the case where context rows must be provided.
  167469. */
  167470. METHODDEF(void)
  167471. process_data_context_main (j_decompress_ptr cinfo,
  167472. JSAMPARRAY output_buf, JDIMENSION *out_row_ctr,
  167473. JDIMENSION out_rows_avail)
  167474. {
  167475. my_main_ptr4 main_ = (my_main_ptr4) cinfo->main;
  167476. /* Read input data if we haven't filled the main buffer yet */
  167477. if (! main_->buffer_full) {
  167478. if (! (*cinfo->coef->decompress_data) (cinfo,
  167479. main_->xbuffer[main_->whichptr]))
  167480. return; /* suspension forced, can do nothing more */
  167481. main_->buffer_full = TRUE; /* OK, we have an iMCU row to work with */
  167482. main_->iMCU_row_ctr++; /* count rows received */
  167483. }
  167484. /* Postprocessor typically will not swallow all the input data it is handed
  167485. * in one call (due to filling the output buffer first). Must be prepared
  167486. * to exit and restart. This switch lets us keep track of how far we got.
  167487. * Note that each case falls through to the next on successful completion.
  167488. */
  167489. switch (main_->context_state) {
  167490. case CTX_POSTPONED_ROW:
  167491. /* Call postprocessor using previously set pointers for postponed row */
  167492. (*cinfo->post->post_process_data) (cinfo, main_->xbuffer[main_->whichptr],
  167493. &main_->rowgroup_ctr, main_->rowgroups_avail,
  167494. output_buf, out_row_ctr, out_rows_avail);
  167495. if (main_->rowgroup_ctr < main_->rowgroups_avail)
  167496. return; /* Need to suspend */
  167497. main_->context_state = CTX_PREPARE_FOR_IMCU;
  167498. if (*out_row_ctr >= out_rows_avail)
  167499. return; /* Postprocessor exactly filled output buf */
  167500. /*FALLTHROUGH*/
  167501. case CTX_PREPARE_FOR_IMCU:
  167502. /* Prepare to process first M-1 row groups of this iMCU row */
  167503. main_->rowgroup_ctr = 0;
  167504. main_->rowgroups_avail = (JDIMENSION) (cinfo->min_DCT_scaled_size - 1);
  167505. /* Check for bottom of image: if so, tweak pointers to "duplicate"
  167506. * the last sample row, and adjust rowgroups_avail to ignore padding rows.
  167507. */
  167508. if (main_->iMCU_row_ctr == cinfo->total_iMCU_rows)
  167509. set_bottom_pointers(cinfo);
  167510. main_->context_state = CTX_PROCESS_IMCU;
  167511. /*FALLTHROUGH*/
  167512. case CTX_PROCESS_IMCU:
  167513. /* Call postprocessor using previously set pointers */
  167514. (*cinfo->post->post_process_data) (cinfo, main_->xbuffer[main_->whichptr],
  167515. &main_->rowgroup_ctr, main_->rowgroups_avail,
  167516. output_buf, out_row_ctr, out_rows_avail);
  167517. if (main_->rowgroup_ctr < main_->rowgroups_avail)
  167518. return; /* Need to suspend */
  167519. /* After the first iMCU, change wraparound pointers to normal state */
  167520. if (main_->iMCU_row_ctr == 1)
  167521. set_wraparound_pointers(cinfo);
  167522. /* Prepare to load new iMCU row using other xbuffer list */
  167523. main_->whichptr ^= 1; /* 0=>1 or 1=>0 */
  167524. main_->buffer_full = FALSE;
  167525. /* Still need to process last row group of this iMCU row, */
  167526. /* which is saved at index M+1 of the other xbuffer */
  167527. main_->rowgroup_ctr = (JDIMENSION) (cinfo->min_DCT_scaled_size + 1);
  167528. main_->rowgroups_avail = (JDIMENSION) (cinfo->min_DCT_scaled_size + 2);
  167529. main_->context_state = CTX_POSTPONED_ROW;
  167530. }
  167531. }
  167532. /*
  167533. * Process some data.
  167534. * Final pass of two-pass quantization: just call the postprocessor.
  167535. * Source data will be the postprocessor controller's internal buffer.
  167536. */
  167537. #ifdef QUANT_2PASS_SUPPORTED
  167538. METHODDEF(void)
  167539. process_data_crank_post (j_decompress_ptr cinfo,
  167540. JSAMPARRAY output_buf, JDIMENSION *out_row_ctr,
  167541. JDIMENSION out_rows_avail)
  167542. {
  167543. (*cinfo->post->post_process_data) (cinfo, (JSAMPIMAGE) NULL,
  167544. (JDIMENSION *) NULL, (JDIMENSION) 0,
  167545. output_buf, out_row_ctr, out_rows_avail);
  167546. }
  167547. #endif /* QUANT_2PASS_SUPPORTED */
  167548. /*
  167549. * Initialize main buffer controller.
  167550. */
  167551. GLOBAL(void)
  167552. jinit_d_main_controller (j_decompress_ptr cinfo, boolean need_full_buffer)
  167553. {
  167554. my_main_ptr4 main_;
  167555. int ci, rgroup, ngroups;
  167556. jpeg_component_info *compptr;
  167557. main_ = (my_main_ptr4)
  167558. (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_IMAGE,
  167559. SIZEOF(my_main_controller4));
  167560. cinfo->main = (struct jpeg_d_main_controller *) main_;
  167561. main_->pub.start_pass = start_pass_main2;
  167562. if (need_full_buffer) /* shouldn't happen */
  167563. ERREXIT(cinfo, JERR_BAD_BUFFER_MODE);
  167564. /* Allocate the workspace.
  167565. * ngroups is the number of row groups we need.
  167566. */
  167567. if (cinfo->upsample->need_context_rows) {
  167568. if (cinfo->min_DCT_scaled_size < 2) /* unsupported, see comments above */
  167569. ERREXIT(cinfo, JERR_NOTIMPL);
  167570. alloc_funny_pointers(cinfo); /* Alloc space for xbuffer[] lists */
  167571. ngroups = cinfo->min_DCT_scaled_size + 2;
  167572. } else {
  167573. ngroups = cinfo->min_DCT_scaled_size;
  167574. }
  167575. for (ci = 0, compptr = cinfo->comp_info; ci < cinfo->num_components;
  167576. ci++, compptr++) {
  167577. rgroup = (compptr->v_samp_factor * compptr->DCT_scaled_size) /
  167578. cinfo->min_DCT_scaled_size; /* height of a row group of component */
  167579. main_->buffer[ci] = (*cinfo->mem->alloc_sarray)
  167580. ((j_common_ptr) cinfo, JPOOL_IMAGE,
  167581. compptr->width_in_blocks * compptr->DCT_scaled_size,
  167582. (JDIMENSION) (rgroup * ngroups));
  167583. }
  167584. }
  167585. /*** End of inlined file: jdmainct.c ***/
  167586. /*** Start of inlined file: jdmarker.c ***/
  167587. #define JPEG_INTERNALS
  167588. /* Private state */
  167589. typedef struct {
  167590. struct jpeg_marker_reader pub; /* public fields */
  167591. /* Application-overridable marker processing methods */
  167592. jpeg_marker_parser_method process_COM;
  167593. jpeg_marker_parser_method process_APPn[16];
  167594. /* Limit on marker data length to save for each marker type */
  167595. unsigned int length_limit_COM;
  167596. unsigned int length_limit_APPn[16];
  167597. /* Status of COM/APPn marker saving */
  167598. jpeg_saved_marker_ptr cur_marker; /* NULL if not processing a marker */
  167599. unsigned int bytes_read; /* data bytes read so far in marker */
  167600. /* Note: cur_marker is not linked into marker_list until it's all read. */
  167601. } my_marker_reader;
  167602. typedef my_marker_reader * my_marker_ptr2;
  167603. /*
  167604. * Macros for fetching data from the data source module.
  167605. *
  167606. * At all times, cinfo->src->next_input_byte and ->bytes_in_buffer reflect
  167607. * the current restart point; we update them only when we have reached a
  167608. * suitable place to restart if a suspension occurs.
  167609. */
  167610. /* Declare and initialize local copies of input pointer/count */
  167611. #define INPUT_VARS(cinfo) \
  167612. struct jpeg_source_mgr * datasrc = (cinfo)->src; \
  167613. const JOCTET * next_input_byte = datasrc->next_input_byte; \
  167614. size_t bytes_in_buffer = datasrc->bytes_in_buffer
  167615. /* Unload the local copies --- do this only at a restart boundary */
  167616. #define INPUT_SYNC(cinfo) \
  167617. ( datasrc->next_input_byte = next_input_byte, \
  167618. datasrc->bytes_in_buffer = bytes_in_buffer )
  167619. /* Reload the local copies --- used only in MAKE_BYTE_AVAIL */
  167620. #define INPUT_RELOAD(cinfo) \
  167621. ( next_input_byte = datasrc->next_input_byte, \
  167622. bytes_in_buffer = datasrc->bytes_in_buffer )
  167623. /* Internal macro for INPUT_BYTE and INPUT_2BYTES: make a byte available.
  167624. * Note we do *not* do INPUT_SYNC before calling fill_input_buffer,
  167625. * but we must reload the local copies after a successful fill.
  167626. */
  167627. #define MAKE_BYTE_AVAIL(cinfo,action) \
  167628. if (bytes_in_buffer == 0) { \
  167629. if (! (*datasrc->fill_input_buffer) (cinfo)) \
  167630. { action; } \
  167631. INPUT_RELOAD(cinfo); \
  167632. }
  167633. /* Read a byte into variable V.
  167634. * If must suspend, take the specified action (typically "return FALSE").
  167635. */
  167636. #define INPUT_BYTE(cinfo,V,action) \
  167637. MAKESTMT( MAKE_BYTE_AVAIL(cinfo,action); \
  167638. bytes_in_buffer--; \
  167639. V = GETJOCTET(*next_input_byte++); )
  167640. /* As above, but read two bytes interpreted as an unsigned 16-bit integer.
  167641. * V should be declared unsigned int or perhaps INT32.
  167642. */
  167643. #define INPUT_2BYTES(cinfo,V,action) \
  167644. MAKESTMT( MAKE_BYTE_AVAIL(cinfo,action); \
  167645. bytes_in_buffer--; \
  167646. V = ((unsigned int) GETJOCTET(*next_input_byte++)) << 8; \
  167647. MAKE_BYTE_AVAIL(cinfo,action); \
  167648. bytes_in_buffer--; \
  167649. V += GETJOCTET(*next_input_byte++); )
  167650. /*
  167651. * Routines to process JPEG markers.
  167652. *
  167653. * Entry condition: JPEG marker itself has been read and its code saved
  167654. * in cinfo->unread_marker; input restart point is just after the marker.
  167655. *
  167656. * Exit: if return TRUE, have read and processed any parameters, and have
  167657. * updated the restart point to point after the parameters.
  167658. * If return FALSE, was forced to suspend before reaching end of
  167659. * marker parameters; restart point has not been moved. Same routine
  167660. * will be called again after application supplies more input data.
  167661. *
  167662. * This approach to suspension assumes that all of a marker's parameters
  167663. * can fit into a single input bufferload. This should hold for "normal"
  167664. * markers. Some COM/APPn markers might have large parameter segments
  167665. * that might not fit. If we are simply dropping such a marker, we use
  167666. * skip_input_data to get past it, and thereby put the problem on the
  167667. * source manager's shoulders. If we are saving the marker's contents
  167668. * into memory, we use a slightly different convention: when forced to
  167669. * suspend, the marker processor updates the restart point to the end of
  167670. * what it's consumed (ie, the end of the buffer) before returning FALSE.
  167671. * On resumption, cinfo->unread_marker still contains the marker code,
  167672. * but the data source will point to the next chunk of marker data.
  167673. * The marker processor must retain internal state to deal with this.
  167674. *
  167675. * Note that we don't bother to avoid duplicate trace messages if a
  167676. * suspension occurs within marker parameters. Other side effects
  167677. * require more care.
  167678. */
  167679. LOCAL(boolean)
  167680. get_soi (j_decompress_ptr cinfo)
  167681. /* Process an SOI marker */
  167682. {
  167683. int i;
  167684. TRACEMS(cinfo, 1, JTRC_SOI);
  167685. if (cinfo->marker->saw_SOI)
  167686. ERREXIT(cinfo, JERR_SOI_DUPLICATE);
  167687. /* Reset all parameters that are defined to be reset by SOI */
  167688. for (i = 0; i < NUM_ARITH_TBLS; i++) {
  167689. cinfo->arith_dc_L[i] = 0;
  167690. cinfo->arith_dc_U[i] = 1;
  167691. cinfo->arith_ac_K[i] = 5;
  167692. }
  167693. cinfo->restart_interval = 0;
  167694. /* Set initial assumptions for colorspace etc */
  167695. cinfo->jpeg_color_space = JCS_UNKNOWN;
  167696. cinfo->CCIR601_sampling = FALSE; /* Assume non-CCIR sampling??? */
  167697. cinfo->saw_JFIF_marker = FALSE;
  167698. cinfo->JFIF_major_version = 1; /* set default JFIF APP0 values */
  167699. cinfo->JFIF_minor_version = 1;
  167700. cinfo->density_unit = 0;
  167701. cinfo->X_density = 1;
  167702. cinfo->Y_density = 1;
  167703. cinfo->saw_Adobe_marker = FALSE;
  167704. cinfo->Adobe_transform = 0;
  167705. cinfo->marker->saw_SOI = TRUE;
  167706. return TRUE;
  167707. }
  167708. LOCAL(boolean)
  167709. get_sof (j_decompress_ptr cinfo, boolean is_prog, boolean is_arith)
  167710. /* Process a SOFn marker */
  167711. {
  167712. INT32 length;
  167713. int c, ci;
  167714. jpeg_component_info * compptr;
  167715. INPUT_VARS(cinfo);
  167716. cinfo->progressive_mode = is_prog;
  167717. cinfo->arith_code = is_arith;
  167718. INPUT_2BYTES(cinfo, length, return FALSE);
  167719. INPUT_BYTE(cinfo, cinfo->data_precision, return FALSE);
  167720. INPUT_2BYTES(cinfo, cinfo->image_height, return FALSE);
  167721. INPUT_2BYTES(cinfo, cinfo->image_width, return FALSE);
  167722. INPUT_BYTE(cinfo, cinfo->num_components, return FALSE);
  167723. length -= 8;
  167724. TRACEMS4(cinfo, 1, JTRC_SOF, cinfo->unread_marker,
  167725. (int) cinfo->image_width, (int) cinfo->image_height,
  167726. cinfo->num_components);
  167727. if (cinfo->marker->saw_SOF)
  167728. ERREXIT(cinfo, JERR_SOF_DUPLICATE);
  167729. /* We don't support files in which the image height is initially specified */
  167730. /* as 0 and is later redefined by DNL. As long as we have to check that, */
  167731. /* might as well have a general sanity check. */
  167732. if (cinfo->image_height <= 0 || cinfo->image_width <= 0
  167733. || cinfo->num_components <= 0)
  167734. ERREXIT(cinfo, JERR_EMPTY_IMAGE);
  167735. if (length != (cinfo->num_components * 3))
  167736. ERREXIT(cinfo, JERR_BAD_LENGTH);
  167737. if (cinfo->comp_info == NULL) /* do only once, even if suspend */
  167738. cinfo->comp_info = (jpeg_component_info *) (*cinfo->mem->alloc_small)
  167739. ((j_common_ptr) cinfo, JPOOL_IMAGE,
  167740. cinfo->num_components * SIZEOF(jpeg_component_info));
  167741. for (ci = 0, compptr = cinfo->comp_info; ci < cinfo->num_components;
  167742. ci++, compptr++) {
  167743. compptr->component_index = ci;
  167744. INPUT_BYTE(cinfo, compptr->component_id, return FALSE);
  167745. INPUT_BYTE(cinfo, c, return FALSE);
  167746. compptr->h_samp_factor = (c >> 4) & 15;
  167747. compptr->v_samp_factor = (c ) & 15;
  167748. INPUT_BYTE(cinfo, compptr->quant_tbl_no, return FALSE);
  167749. TRACEMS4(cinfo, 1, JTRC_SOF_COMPONENT,
  167750. compptr->component_id, compptr->h_samp_factor,
  167751. compptr->v_samp_factor, compptr->quant_tbl_no);
  167752. }
  167753. cinfo->marker->saw_SOF = TRUE;
  167754. INPUT_SYNC(cinfo);
  167755. return TRUE;
  167756. }
  167757. LOCAL(boolean)
  167758. get_sos (j_decompress_ptr cinfo)
  167759. /* Process a SOS marker */
  167760. {
  167761. INT32 length;
  167762. int i, ci, n, c, cc;
  167763. jpeg_component_info * compptr;
  167764. INPUT_VARS(cinfo);
  167765. if (! cinfo->marker->saw_SOF)
  167766. ERREXIT(cinfo, JERR_SOS_NO_SOF);
  167767. INPUT_2BYTES(cinfo, length, return FALSE);
  167768. INPUT_BYTE(cinfo, n, return FALSE); /* Number of components */
  167769. TRACEMS1(cinfo, 1, JTRC_SOS, n);
  167770. if (length != (n * 2 + 6) || n < 1 || n > MAX_COMPS_IN_SCAN)
  167771. ERREXIT(cinfo, JERR_BAD_LENGTH);
  167772. cinfo->comps_in_scan = n;
  167773. /* Collect the component-spec parameters */
  167774. for (i = 0; i < n; i++) {
  167775. INPUT_BYTE(cinfo, cc, return FALSE);
  167776. INPUT_BYTE(cinfo, c, return FALSE);
  167777. for (ci = 0, compptr = cinfo->comp_info; ci < cinfo->num_components;
  167778. ci++, compptr++) {
  167779. if (cc == compptr->component_id)
  167780. goto id_found;
  167781. }
  167782. ERREXIT1(cinfo, JERR_BAD_COMPONENT_ID, cc);
  167783. id_found:
  167784. cinfo->cur_comp_info[i] = compptr;
  167785. compptr->dc_tbl_no = (c >> 4) & 15;
  167786. compptr->ac_tbl_no = (c ) & 15;
  167787. TRACEMS3(cinfo, 1, JTRC_SOS_COMPONENT, cc,
  167788. compptr->dc_tbl_no, compptr->ac_tbl_no);
  167789. }
  167790. /* Collect the additional scan parameters Ss, Se, Ah/Al. */
  167791. INPUT_BYTE(cinfo, c, return FALSE);
  167792. cinfo->Ss = c;
  167793. INPUT_BYTE(cinfo, c, return FALSE);
  167794. cinfo->Se = c;
  167795. INPUT_BYTE(cinfo, c, return FALSE);
  167796. cinfo->Ah = (c >> 4) & 15;
  167797. cinfo->Al = (c ) & 15;
  167798. TRACEMS4(cinfo, 1, JTRC_SOS_PARAMS, cinfo->Ss, cinfo->Se,
  167799. cinfo->Ah, cinfo->Al);
  167800. /* Prepare to scan data & restart markers */
  167801. cinfo->marker->next_restart_num = 0;
  167802. /* Count another SOS marker */
  167803. cinfo->input_scan_number++;
  167804. INPUT_SYNC(cinfo);
  167805. return TRUE;
  167806. }
  167807. #ifdef D_ARITH_CODING_SUPPORTED
  167808. LOCAL(boolean)
  167809. get_dac (j_decompress_ptr cinfo)
  167810. /* Process a DAC marker */
  167811. {
  167812. INT32 length;
  167813. int index, val;
  167814. INPUT_VARS(cinfo);
  167815. INPUT_2BYTES(cinfo, length, return FALSE);
  167816. length -= 2;
  167817. while (length > 0) {
  167818. INPUT_BYTE(cinfo, index, return FALSE);
  167819. INPUT_BYTE(cinfo, val, return FALSE);
  167820. length -= 2;
  167821. TRACEMS2(cinfo, 1, JTRC_DAC, index, val);
  167822. if (index < 0 || index >= (2*NUM_ARITH_TBLS))
  167823. ERREXIT1(cinfo, JERR_DAC_INDEX, index);
  167824. if (index >= NUM_ARITH_TBLS) { /* define AC table */
  167825. cinfo->arith_ac_K[index-NUM_ARITH_TBLS] = (UINT8) val;
  167826. } else { /* define DC table */
  167827. cinfo->arith_dc_L[index] = (UINT8) (val & 0x0F);
  167828. cinfo->arith_dc_U[index] = (UINT8) (val >> 4);
  167829. if (cinfo->arith_dc_L[index] > cinfo->arith_dc_U[index])
  167830. ERREXIT1(cinfo, JERR_DAC_VALUE, val);
  167831. }
  167832. }
  167833. if (length != 0)
  167834. ERREXIT(cinfo, JERR_BAD_LENGTH);
  167835. INPUT_SYNC(cinfo);
  167836. return TRUE;
  167837. }
  167838. #else /* ! D_ARITH_CODING_SUPPORTED */
  167839. #define get_dac(cinfo) skip_variable(cinfo)
  167840. #endif /* D_ARITH_CODING_SUPPORTED */
  167841. LOCAL(boolean)
  167842. get_dht (j_decompress_ptr cinfo)
  167843. /* Process a DHT marker */
  167844. {
  167845. INT32 length;
  167846. UINT8 bits[17];
  167847. UINT8 huffval[256];
  167848. int i, index, count;
  167849. JHUFF_TBL **htblptr;
  167850. INPUT_VARS(cinfo);
  167851. INPUT_2BYTES(cinfo, length, return FALSE);
  167852. length -= 2;
  167853. while (length > 16) {
  167854. INPUT_BYTE(cinfo, index, return FALSE);
  167855. TRACEMS1(cinfo, 1, JTRC_DHT, index);
  167856. bits[0] = 0;
  167857. count = 0;
  167858. for (i = 1; i <= 16; i++) {
  167859. INPUT_BYTE(cinfo, bits[i], return FALSE);
  167860. count += bits[i];
  167861. }
  167862. length -= 1 + 16;
  167863. TRACEMS8(cinfo, 2, JTRC_HUFFBITS,
  167864. bits[1], bits[2], bits[3], bits[4],
  167865. bits[5], bits[6], bits[7], bits[8]);
  167866. TRACEMS8(cinfo, 2, JTRC_HUFFBITS,
  167867. bits[9], bits[10], bits[11], bits[12],
  167868. bits[13], bits[14], bits[15], bits[16]);
  167869. /* Here we just do minimal validation of the counts to avoid walking
  167870. * off the end of our table space. jdhuff.c will check more carefully.
  167871. */
  167872. if (count > 256 || ((INT32) count) > length)
  167873. ERREXIT(cinfo, JERR_BAD_HUFF_TABLE);
  167874. for (i = 0; i < count; i++)
  167875. INPUT_BYTE(cinfo, huffval[i], return FALSE);
  167876. length -= count;
  167877. if (index & 0x10) { /* AC table definition */
  167878. index -= 0x10;
  167879. htblptr = &cinfo->ac_huff_tbl_ptrs[index];
  167880. } else { /* DC table definition */
  167881. htblptr = &cinfo->dc_huff_tbl_ptrs[index];
  167882. }
  167883. if (index < 0 || index >= NUM_HUFF_TBLS)
  167884. ERREXIT1(cinfo, JERR_DHT_INDEX, index);
  167885. if (*htblptr == NULL)
  167886. *htblptr = jpeg_alloc_huff_table((j_common_ptr) cinfo);
  167887. MEMCOPY((*htblptr)->bits, bits, SIZEOF((*htblptr)->bits));
  167888. MEMCOPY((*htblptr)->huffval, huffval, SIZEOF((*htblptr)->huffval));
  167889. }
  167890. if (length != 0)
  167891. ERREXIT(cinfo, JERR_BAD_LENGTH);
  167892. INPUT_SYNC(cinfo);
  167893. return TRUE;
  167894. }
  167895. LOCAL(boolean)
  167896. get_dqt (j_decompress_ptr cinfo)
  167897. /* Process a DQT marker */
  167898. {
  167899. INT32 length;
  167900. int n, i, prec;
  167901. unsigned int tmp;
  167902. JQUANT_TBL *quant_ptr;
  167903. INPUT_VARS(cinfo);
  167904. INPUT_2BYTES(cinfo, length, return FALSE);
  167905. length -= 2;
  167906. while (length > 0) {
  167907. INPUT_BYTE(cinfo, n, return FALSE);
  167908. prec = n >> 4;
  167909. n &= 0x0F;
  167910. TRACEMS2(cinfo, 1, JTRC_DQT, n, prec);
  167911. if (n >= NUM_QUANT_TBLS)
  167912. ERREXIT1(cinfo, JERR_DQT_INDEX, n);
  167913. if (cinfo->quant_tbl_ptrs[n] == NULL)
  167914. cinfo->quant_tbl_ptrs[n] = jpeg_alloc_quant_table((j_common_ptr) cinfo);
  167915. quant_ptr = cinfo->quant_tbl_ptrs[n];
  167916. for (i = 0; i < DCTSIZE2; i++) {
  167917. if (prec)
  167918. INPUT_2BYTES(cinfo, tmp, return FALSE);
  167919. else
  167920. INPUT_BYTE(cinfo, tmp, return FALSE);
  167921. /* We convert the zigzag-order table to natural array order. */
  167922. quant_ptr->quantval[jpeg_natural_order[i]] = (UINT16) tmp;
  167923. }
  167924. if (cinfo->err->trace_level >= 2) {
  167925. for (i = 0; i < DCTSIZE2; i += 8) {
  167926. TRACEMS8(cinfo, 2, JTRC_QUANTVALS,
  167927. quant_ptr->quantval[i], quant_ptr->quantval[i+1],
  167928. quant_ptr->quantval[i+2], quant_ptr->quantval[i+3],
  167929. quant_ptr->quantval[i+4], quant_ptr->quantval[i+5],
  167930. quant_ptr->quantval[i+6], quant_ptr->quantval[i+7]);
  167931. }
  167932. }
  167933. length -= DCTSIZE2+1;
  167934. if (prec) length -= DCTSIZE2;
  167935. }
  167936. if (length != 0)
  167937. ERREXIT(cinfo, JERR_BAD_LENGTH);
  167938. INPUT_SYNC(cinfo);
  167939. return TRUE;
  167940. }
  167941. LOCAL(boolean)
  167942. get_dri (j_decompress_ptr cinfo)
  167943. /* Process a DRI marker */
  167944. {
  167945. INT32 length;
  167946. unsigned int tmp;
  167947. INPUT_VARS(cinfo);
  167948. INPUT_2BYTES(cinfo, length, return FALSE);
  167949. if (length != 4)
  167950. ERREXIT(cinfo, JERR_BAD_LENGTH);
  167951. INPUT_2BYTES(cinfo, tmp, return FALSE);
  167952. TRACEMS1(cinfo, 1, JTRC_DRI, tmp);
  167953. cinfo->restart_interval = tmp;
  167954. INPUT_SYNC(cinfo);
  167955. return TRUE;
  167956. }
  167957. /*
  167958. * Routines for processing APPn and COM markers.
  167959. * These are either saved in memory or discarded, per application request.
  167960. * APP0 and APP14 are specially checked to see if they are
  167961. * JFIF and Adobe markers, respectively.
  167962. */
  167963. #define APP0_DATA_LEN 14 /* Length of interesting data in APP0 */
  167964. #define APP14_DATA_LEN 12 /* Length of interesting data in APP14 */
  167965. #define APPN_DATA_LEN 14 /* Must be the largest of the above!! */
  167966. LOCAL(void)
  167967. examine_app0 (j_decompress_ptr cinfo, JOCTET FAR * data,
  167968. unsigned int datalen, INT32 remaining)
  167969. /* Examine first few bytes from an APP0.
  167970. * Take appropriate action if it is a JFIF marker.
  167971. * datalen is # of bytes at data[], remaining is length of rest of marker data.
  167972. */
  167973. {
  167974. INT32 totallen = (INT32) datalen + remaining;
  167975. if (datalen >= APP0_DATA_LEN &&
  167976. GETJOCTET(data[0]) == 0x4A &&
  167977. GETJOCTET(data[1]) == 0x46 &&
  167978. GETJOCTET(data[2]) == 0x49 &&
  167979. GETJOCTET(data[3]) == 0x46 &&
  167980. GETJOCTET(data[4]) == 0) {
  167981. /* Found JFIF APP0 marker: save info */
  167982. cinfo->saw_JFIF_marker = TRUE;
  167983. cinfo->JFIF_major_version = GETJOCTET(data[5]);
  167984. cinfo->JFIF_minor_version = GETJOCTET(data[6]);
  167985. cinfo->density_unit = GETJOCTET(data[7]);
  167986. cinfo->X_density = (GETJOCTET(data[8]) << 8) + GETJOCTET(data[9]);
  167987. cinfo->Y_density = (GETJOCTET(data[10]) << 8) + GETJOCTET(data[11]);
  167988. /* Check version.
  167989. * Major version must be 1, anything else signals an incompatible change.
  167990. * (We used to treat this as an error, but now it's a nonfatal warning,
  167991. * because some bozo at Hijaak couldn't read the spec.)
  167992. * Minor version should be 0..2, but process anyway if newer.
  167993. */
  167994. if (cinfo->JFIF_major_version != 1)
  167995. WARNMS2(cinfo, JWRN_JFIF_MAJOR,
  167996. cinfo->JFIF_major_version, cinfo->JFIF_minor_version);
  167997. /* Generate trace messages */
  167998. TRACEMS5(cinfo, 1, JTRC_JFIF,
  167999. cinfo->JFIF_major_version, cinfo->JFIF_minor_version,
  168000. cinfo->X_density, cinfo->Y_density, cinfo->density_unit);
  168001. /* Validate thumbnail dimensions and issue appropriate messages */
  168002. if (GETJOCTET(data[12]) | GETJOCTET(data[13]))
  168003. TRACEMS2(cinfo, 1, JTRC_JFIF_THUMBNAIL,
  168004. GETJOCTET(data[12]), GETJOCTET(data[13]));
  168005. totallen -= APP0_DATA_LEN;
  168006. if (totallen !=
  168007. ((INT32)GETJOCTET(data[12]) * (INT32)GETJOCTET(data[13]) * (INT32) 3))
  168008. TRACEMS1(cinfo, 1, JTRC_JFIF_BADTHUMBNAILSIZE, (int) totallen);
  168009. } else if (datalen >= 6 &&
  168010. GETJOCTET(data[0]) == 0x4A &&
  168011. GETJOCTET(data[1]) == 0x46 &&
  168012. GETJOCTET(data[2]) == 0x58 &&
  168013. GETJOCTET(data[3]) == 0x58 &&
  168014. GETJOCTET(data[4]) == 0) {
  168015. /* Found JFIF "JFXX" extension APP0 marker */
  168016. /* The library doesn't actually do anything with these,
  168017. * but we try to produce a helpful trace message.
  168018. */
  168019. switch (GETJOCTET(data[5])) {
  168020. case 0x10:
  168021. TRACEMS1(cinfo, 1, JTRC_THUMB_JPEG, (int) totallen);
  168022. break;
  168023. case 0x11:
  168024. TRACEMS1(cinfo, 1, JTRC_THUMB_PALETTE, (int) totallen);
  168025. break;
  168026. case 0x13:
  168027. TRACEMS1(cinfo, 1, JTRC_THUMB_RGB, (int) totallen);
  168028. break;
  168029. default:
  168030. TRACEMS2(cinfo, 1, JTRC_JFIF_EXTENSION,
  168031. GETJOCTET(data[5]), (int) totallen);
  168032. break;
  168033. }
  168034. } else {
  168035. /* Start of APP0 does not match "JFIF" or "JFXX", or too short */
  168036. TRACEMS1(cinfo, 1, JTRC_APP0, (int) totallen);
  168037. }
  168038. }
  168039. LOCAL(void)
  168040. examine_app14 (j_decompress_ptr cinfo, JOCTET FAR * data,
  168041. unsigned int datalen, INT32 remaining)
  168042. /* Examine first few bytes from an APP14.
  168043. * Take appropriate action if it is an Adobe marker.
  168044. * datalen is # of bytes at data[], remaining is length of rest of marker data.
  168045. */
  168046. {
  168047. unsigned int version, flags0, flags1, transform;
  168048. if (datalen >= APP14_DATA_LEN &&
  168049. GETJOCTET(data[0]) == 0x41 &&
  168050. GETJOCTET(data[1]) == 0x64 &&
  168051. GETJOCTET(data[2]) == 0x6F &&
  168052. GETJOCTET(data[3]) == 0x62 &&
  168053. GETJOCTET(data[4]) == 0x65) {
  168054. /* Found Adobe APP14 marker */
  168055. version = (GETJOCTET(data[5]) << 8) + GETJOCTET(data[6]);
  168056. flags0 = (GETJOCTET(data[7]) << 8) + GETJOCTET(data[8]);
  168057. flags1 = (GETJOCTET(data[9]) << 8) + GETJOCTET(data[10]);
  168058. transform = GETJOCTET(data[11]);
  168059. TRACEMS4(cinfo, 1, JTRC_ADOBE, version, flags0, flags1, transform);
  168060. cinfo->saw_Adobe_marker = TRUE;
  168061. cinfo->Adobe_transform = (UINT8) transform;
  168062. } else {
  168063. /* Start of APP14 does not match "Adobe", or too short */
  168064. TRACEMS1(cinfo, 1, JTRC_APP14, (int) (datalen + remaining));
  168065. }
  168066. }
  168067. METHODDEF(boolean)
  168068. get_interesting_appn (j_decompress_ptr cinfo)
  168069. /* Process an APP0 or APP14 marker without saving it */
  168070. {
  168071. INT32 length;
  168072. JOCTET b[APPN_DATA_LEN];
  168073. unsigned int i, numtoread;
  168074. INPUT_VARS(cinfo);
  168075. INPUT_2BYTES(cinfo, length, return FALSE);
  168076. length -= 2;
  168077. /* get the interesting part of the marker data */
  168078. if (length >= APPN_DATA_LEN)
  168079. numtoread = APPN_DATA_LEN;
  168080. else if (length > 0)
  168081. numtoread = (unsigned int) length;
  168082. else
  168083. numtoread = 0;
  168084. for (i = 0; i < numtoread; i++)
  168085. INPUT_BYTE(cinfo, b[i], return FALSE);
  168086. length -= numtoread;
  168087. /* process it */
  168088. switch (cinfo->unread_marker) {
  168089. case M_APP0:
  168090. examine_app0(cinfo, (JOCTET FAR *) b, numtoread, length);
  168091. break;
  168092. case M_APP14:
  168093. examine_app14(cinfo, (JOCTET FAR *) b, numtoread, length);
  168094. break;
  168095. default:
  168096. /* can't get here unless jpeg_save_markers chooses wrong processor */
  168097. ERREXIT1(cinfo, JERR_UNKNOWN_MARKER, cinfo->unread_marker);
  168098. break;
  168099. }
  168100. /* skip any remaining data -- could be lots */
  168101. INPUT_SYNC(cinfo);
  168102. if (length > 0)
  168103. (*cinfo->src->skip_input_data) (cinfo, (long) length);
  168104. return TRUE;
  168105. }
  168106. #ifdef SAVE_MARKERS_SUPPORTED
  168107. METHODDEF(boolean)
  168108. save_marker (j_decompress_ptr cinfo)
  168109. /* Save an APPn or COM marker into the marker list */
  168110. {
  168111. my_marker_ptr2 marker = (my_marker_ptr2) cinfo->marker;
  168112. jpeg_saved_marker_ptr cur_marker = marker->cur_marker;
  168113. unsigned int bytes_read, data_length;
  168114. JOCTET FAR * data;
  168115. INT32 length = 0;
  168116. INPUT_VARS(cinfo);
  168117. if (cur_marker == NULL) {
  168118. /* begin reading a marker */
  168119. INPUT_2BYTES(cinfo, length, return FALSE);
  168120. length -= 2;
  168121. if (length >= 0) { /* watch out for bogus length word */
  168122. /* figure out how much we want to save */
  168123. unsigned int limit;
  168124. if (cinfo->unread_marker == (int) M_COM)
  168125. limit = marker->length_limit_COM;
  168126. else
  168127. limit = marker->length_limit_APPn[cinfo->unread_marker - (int) M_APP0];
  168128. if ((unsigned int) length < limit)
  168129. limit = (unsigned int) length;
  168130. /* allocate and initialize the marker item */
  168131. cur_marker = (jpeg_saved_marker_ptr)
  168132. (*cinfo->mem->alloc_large) ((j_common_ptr) cinfo, JPOOL_IMAGE,
  168133. SIZEOF(struct jpeg_marker_struct) + limit);
  168134. cur_marker->next = NULL;
  168135. cur_marker->marker = (UINT8) cinfo->unread_marker;
  168136. cur_marker->original_length = (unsigned int) length;
  168137. cur_marker->data_length = limit;
  168138. /* data area is just beyond the jpeg_marker_struct */
  168139. data = cur_marker->data = (JOCTET FAR *) (cur_marker + 1);
  168140. marker->cur_marker = cur_marker;
  168141. marker->bytes_read = 0;
  168142. bytes_read = 0;
  168143. data_length = limit;
  168144. } else {
  168145. /* deal with bogus length word */
  168146. bytes_read = data_length = 0;
  168147. data = NULL;
  168148. }
  168149. } else {
  168150. /* resume reading a marker */
  168151. bytes_read = marker->bytes_read;
  168152. data_length = cur_marker->data_length;
  168153. data = cur_marker->data + bytes_read;
  168154. }
  168155. while (bytes_read < data_length) {
  168156. INPUT_SYNC(cinfo); /* move the restart point to here */
  168157. marker->bytes_read = bytes_read;
  168158. /* If there's not at least one byte in buffer, suspend */
  168159. MAKE_BYTE_AVAIL(cinfo, return FALSE);
  168160. /* Copy bytes with reasonable rapidity */
  168161. while (bytes_read < data_length && bytes_in_buffer > 0) {
  168162. *data++ = *next_input_byte++;
  168163. bytes_in_buffer--;
  168164. bytes_read++;
  168165. }
  168166. }
  168167. /* Done reading what we want to read */
  168168. if (cur_marker != NULL) { /* will be NULL if bogus length word */
  168169. /* Add new marker to end of list */
  168170. if (cinfo->marker_list == NULL) {
  168171. cinfo->marker_list = cur_marker;
  168172. } else {
  168173. jpeg_saved_marker_ptr prev = cinfo->marker_list;
  168174. while (prev->next != NULL)
  168175. prev = prev->next;
  168176. prev->next = cur_marker;
  168177. }
  168178. /* Reset pointer & calc remaining data length */
  168179. data = cur_marker->data;
  168180. length = cur_marker->original_length - data_length;
  168181. }
  168182. /* Reset to initial state for next marker */
  168183. marker->cur_marker = NULL;
  168184. /* Process the marker if interesting; else just make a generic trace msg */
  168185. switch (cinfo->unread_marker) {
  168186. case M_APP0:
  168187. examine_app0(cinfo, data, data_length, length);
  168188. break;
  168189. case M_APP14:
  168190. examine_app14(cinfo, data, data_length, length);
  168191. break;
  168192. default:
  168193. TRACEMS2(cinfo, 1, JTRC_MISC_MARKER, cinfo->unread_marker,
  168194. (int) (data_length + length));
  168195. break;
  168196. }
  168197. /* skip any remaining data -- could be lots */
  168198. INPUT_SYNC(cinfo); /* do before skip_input_data */
  168199. if (length > 0)
  168200. (*cinfo->src->skip_input_data) (cinfo, (long) length);
  168201. return TRUE;
  168202. }
  168203. #endif /* SAVE_MARKERS_SUPPORTED */
  168204. METHODDEF(boolean)
  168205. skip_variable (j_decompress_ptr cinfo)
  168206. /* Skip over an unknown or uninteresting variable-length marker */
  168207. {
  168208. INT32 length;
  168209. INPUT_VARS(cinfo);
  168210. INPUT_2BYTES(cinfo, length, return FALSE);
  168211. length -= 2;
  168212. TRACEMS2(cinfo, 1, JTRC_MISC_MARKER, cinfo->unread_marker, (int) length);
  168213. INPUT_SYNC(cinfo); /* do before skip_input_data */
  168214. if (length > 0)
  168215. (*cinfo->src->skip_input_data) (cinfo, (long) length);
  168216. return TRUE;
  168217. }
  168218. /*
  168219. * Find the next JPEG marker, save it in cinfo->unread_marker.
  168220. * Returns FALSE if had to suspend before reaching a marker;
  168221. * in that case cinfo->unread_marker is unchanged.
  168222. *
  168223. * Note that the result might not be a valid marker code,
  168224. * but it will never be 0 or FF.
  168225. */
  168226. LOCAL(boolean)
  168227. next_marker (j_decompress_ptr cinfo)
  168228. {
  168229. int c;
  168230. INPUT_VARS(cinfo);
  168231. for (;;) {
  168232. INPUT_BYTE(cinfo, c, return FALSE);
  168233. /* Skip any non-FF bytes.
  168234. * This may look a bit inefficient, but it will not occur in a valid file.
  168235. * We sync after each discarded byte so that a suspending data source
  168236. * can discard the byte from its buffer.
  168237. */
  168238. while (c != 0xFF) {
  168239. cinfo->marker->discarded_bytes++;
  168240. INPUT_SYNC(cinfo);
  168241. INPUT_BYTE(cinfo, c, return FALSE);
  168242. }
  168243. /* This loop swallows any duplicate FF bytes. Extra FFs are legal as
  168244. * pad bytes, so don't count them in discarded_bytes. We assume there
  168245. * will not be so many consecutive FF bytes as to overflow a suspending
  168246. * data source's input buffer.
  168247. */
  168248. do {
  168249. INPUT_BYTE(cinfo, c, return FALSE);
  168250. } while (c == 0xFF);
  168251. if (c != 0)
  168252. break; /* found a valid marker, exit loop */
  168253. /* Reach here if we found a stuffed-zero data sequence (FF/00).
  168254. * Discard it and loop back to try again.
  168255. */
  168256. cinfo->marker->discarded_bytes += 2;
  168257. INPUT_SYNC(cinfo);
  168258. }
  168259. if (cinfo->marker->discarded_bytes != 0) {
  168260. WARNMS2(cinfo, JWRN_EXTRANEOUS_DATA, cinfo->marker->discarded_bytes, c);
  168261. cinfo->marker->discarded_bytes = 0;
  168262. }
  168263. cinfo->unread_marker = c;
  168264. INPUT_SYNC(cinfo);
  168265. return TRUE;
  168266. }
  168267. LOCAL(boolean)
  168268. first_marker (j_decompress_ptr cinfo)
  168269. /* Like next_marker, but used to obtain the initial SOI marker. */
  168270. /* For this marker, we do not allow preceding garbage or fill; otherwise,
  168271. * we might well scan an entire input file before realizing it ain't JPEG.
  168272. * If an application wants to process non-JFIF files, it must seek to the
  168273. * SOI before calling the JPEG library.
  168274. */
  168275. {
  168276. int c, c2;
  168277. INPUT_VARS(cinfo);
  168278. INPUT_BYTE(cinfo, c, return FALSE);
  168279. INPUT_BYTE(cinfo, c2, return FALSE);
  168280. if (c != 0xFF || c2 != (int) M_SOI)
  168281. ERREXIT2(cinfo, JERR_NO_SOI, c, c2);
  168282. cinfo->unread_marker = c2;
  168283. INPUT_SYNC(cinfo);
  168284. return TRUE;
  168285. }
  168286. /*
  168287. * Read markers until SOS or EOI.
  168288. *
  168289. * Returns same codes as are defined for jpeg_consume_input:
  168290. * JPEG_SUSPENDED, JPEG_REACHED_SOS, or JPEG_REACHED_EOI.
  168291. */
  168292. METHODDEF(int)
  168293. read_markers (j_decompress_ptr cinfo)
  168294. {
  168295. /* Outer loop repeats once for each marker. */
  168296. for (;;) {
  168297. /* Collect the marker proper, unless we already did. */
  168298. /* NB: first_marker() enforces the requirement that SOI appear first. */
  168299. if (cinfo->unread_marker == 0) {
  168300. if (! cinfo->marker->saw_SOI) {
  168301. if (! first_marker(cinfo))
  168302. return JPEG_SUSPENDED;
  168303. } else {
  168304. if (! next_marker(cinfo))
  168305. return JPEG_SUSPENDED;
  168306. }
  168307. }
  168308. /* At this point cinfo->unread_marker contains the marker code and the
  168309. * input point is just past the marker proper, but before any parameters.
  168310. * A suspension will cause us to return with this state still true.
  168311. */
  168312. switch (cinfo->unread_marker) {
  168313. case M_SOI:
  168314. if (! get_soi(cinfo))
  168315. return JPEG_SUSPENDED;
  168316. break;
  168317. case M_SOF0: /* Baseline */
  168318. case M_SOF1: /* Extended sequential, Huffman */
  168319. if (! get_sof(cinfo, FALSE, FALSE))
  168320. return JPEG_SUSPENDED;
  168321. break;
  168322. case M_SOF2: /* Progressive, Huffman */
  168323. if (! get_sof(cinfo, TRUE, FALSE))
  168324. return JPEG_SUSPENDED;
  168325. break;
  168326. case M_SOF9: /* Extended sequential, arithmetic */
  168327. if (! get_sof(cinfo, FALSE, TRUE))
  168328. return JPEG_SUSPENDED;
  168329. break;
  168330. case M_SOF10: /* Progressive, arithmetic */
  168331. if (! get_sof(cinfo, TRUE, TRUE))
  168332. return JPEG_SUSPENDED;
  168333. break;
  168334. /* Currently unsupported SOFn types */
  168335. case M_SOF3: /* Lossless, Huffman */
  168336. case M_SOF5: /* Differential sequential, Huffman */
  168337. case M_SOF6: /* Differential progressive, Huffman */
  168338. case M_SOF7: /* Differential lossless, Huffman */
  168339. case M_JPG: /* Reserved for JPEG extensions */
  168340. case M_SOF11: /* Lossless, arithmetic */
  168341. case M_SOF13: /* Differential sequential, arithmetic */
  168342. case M_SOF14: /* Differential progressive, arithmetic */
  168343. case M_SOF15: /* Differential lossless, arithmetic */
  168344. ERREXIT1(cinfo, JERR_SOF_UNSUPPORTED, cinfo->unread_marker);
  168345. break;
  168346. case M_SOS:
  168347. if (! get_sos(cinfo))
  168348. return JPEG_SUSPENDED;
  168349. cinfo->unread_marker = 0; /* processed the marker */
  168350. return JPEG_REACHED_SOS;
  168351. case M_EOI:
  168352. TRACEMS(cinfo, 1, JTRC_EOI);
  168353. cinfo->unread_marker = 0; /* processed the marker */
  168354. return JPEG_REACHED_EOI;
  168355. case M_DAC:
  168356. if (! get_dac(cinfo))
  168357. return JPEG_SUSPENDED;
  168358. break;
  168359. case M_DHT:
  168360. if (! get_dht(cinfo))
  168361. return JPEG_SUSPENDED;
  168362. break;
  168363. case M_DQT:
  168364. if (! get_dqt(cinfo))
  168365. return JPEG_SUSPENDED;
  168366. break;
  168367. case M_DRI:
  168368. if (! get_dri(cinfo))
  168369. return JPEG_SUSPENDED;
  168370. break;
  168371. case M_APP0:
  168372. case M_APP1:
  168373. case M_APP2:
  168374. case M_APP3:
  168375. case M_APP4:
  168376. case M_APP5:
  168377. case M_APP6:
  168378. case M_APP7:
  168379. case M_APP8:
  168380. case M_APP9:
  168381. case M_APP10:
  168382. case M_APP11:
  168383. case M_APP12:
  168384. case M_APP13:
  168385. case M_APP14:
  168386. case M_APP15:
  168387. if (! (*((my_marker_ptr2) cinfo->marker)->process_APPn[
  168388. cinfo->unread_marker - (int) M_APP0]) (cinfo))
  168389. return JPEG_SUSPENDED;
  168390. break;
  168391. case M_COM:
  168392. if (! (*((my_marker_ptr2) cinfo->marker)->process_COM) (cinfo))
  168393. return JPEG_SUSPENDED;
  168394. break;
  168395. case M_RST0: /* these are all parameterless */
  168396. case M_RST1:
  168397. case M_RST2:
  168398. case M_RST3:
  168399. case M_RST4:
  168400. case M_RST5:
  168401. case M_RST6:
  168402. case M_RST7:
  168403. case M_TEM:
  168404. TRACEMS1(cinfo, 1, JTRC_PARMLESS_MARKER, cinfo->unread_marker);
  168405. break;
  168406. case M_DNL: /* Ignore DNL ... perhaps the wrong thing */
  168407. if (! skip_variable(cinfo))
  168408. return JPEG_SUSPENDED;
  168409. break;
  168410. default: /* must be DHP, EXP, JPGn, or RESn */
  168411. /* For now, we treat the reserved markers as fatal errors since they are
  168412. * likely to be used to signal incompatible JPEG Part 3 extensions.
  168413. * Once the JPEG 3 version-number marker is well defined, this code
  168414. * ought to change!
  168415. */
  168416. ERREXIT1(cinfo, JERR_UNKNOWN_MARKER, cinfo->unread_marker);
  168417. break;
  168418. }
  168419. /* Successfully processed marker, so reset state variable */
  168420. cinfo->unread_marker = 0;
  168421. } /* end loop */
  168422. }
  168423. /*
  168424. * Read a restart marker, which is expected to appear next in the datastream;
  168425. * if the marker is not there, take appropriate recovery action.
  168426. * Returns FALSE if suspension is required.
  168427. *
  168428. * This is called by the entropy decoder after it has read an appropriate
  168429. * number of MCUs. cinfo->unread_marker may be nonzero if the entropy decoder
  168430. * has already read a marker from the data source. Under normal conditions
  168431. * cinfo->unread_marker will be reset to 0 before returning; if not reset,
  168432. * it holds a marker which the decoder will be unable to read past.
  168433. */
  168434. METHODDEF(boolean)
  168435. read_restart_marker (j_decompress_ptr cinfo)
  168436. {
  168437. /* Obtain a marker unless we already did. */
  168438. /* Note that next_marker will complain if it skips any data. */
  168439. if (cinfo->unread_marker == 0) {
  168440. if (! next_marker(cinfo))
  168441. return FALSE;
  168442. }
  168443. if (cinfo->unread_marker ==
  168444. ((int) M_RST0 + cinfo->marker->next_restart_num)) {
  168445. /* Normal case --- swallow the marker and let entropy decoder continue */
  168446. TRACEMS1(cinfo, 3, JTRC_RST, cinfo->marker->next_restart_num);
  168447. cinfo->unread_marker = 0;
  168448. } else {
  168449. /* Uh-oh, the restart markers have been messed up. */
  168450. /* Let the data source manager determine how to resync. */
  168451. if (! (*cinfo->src->resync_to_restart) (cinfo,
  168452. cinfo->marker->next_restart_num))
  168453. return FALSE;
  168454. }
  168455. /* Update next-restart state */
  168456. cinfo->marker->next_restart_num = (cinfo->marker->next_restart_num + 1) & 7;
  168457. return TRUE;
  168458. }
  168459. /*
  168460. * This is the default resync_to_restart method for data source managers
  168461. * to use if they don't have any better approach. Some data source managers
  168462. * may be able to back up, or may have additional knowledge about the data
  168463. * which permits a more intelligent recovery strategy; such managers would
  168464. * presumably supply their own resync method.
  168465. *
  168466. * read_restart_marker calls resync_to_restart if it finds a marker other than
  168467. * the restart marker it was expecting. (This code is *not* used unless
  168468. * a nonzero restart interval has been declared.) cinfo->unread_marker is
  168469. * the marker code actually found (might be anything, except 0 or FF).
  168470. * The desired restart marker number (0..7) is passed as a parameter.
  168471. * This routine is supposed to apply whatever error recovery strategy seems
  168472. * appropriate in order to position the input stream to the next data segment.
  168473. * Note that cinfo->unread_marker is treated as a marker appearing before
  168474. * the current data-source input point; usually it should be reset to zero
  168475. * before returning.
  168476. * Returns FALSE if suspension is required.
  168477. *
  168478. * This implementation is substantially constrained by wanting to treat the
  168479. * input as a data stream; this means we can't back up. Therefore, we have
  168480. * only the following actions to work with:
  168481. * 1. Simply discard the marker and let the entropy decoder resume at next
  168482. * byte of file.
  168483. * 2. Read forward until we find another marker, discarding intervening
  168484. * data. (In theory we could look ahead within the current bufferload,
  168485. * without having to discard data if we don't find the desired marker.
  168486. * This idea is not implemented here, in part because it makes behavior
  168487. * dependent on buffer size and chance buffer-boundary positions.)
  168488. * 3. Leave the marker unread (by failing to zero cinfo->unread_marker).
  168489. * This will cause the entropy decoder to process an empty data segment,
  168490. * inserting dummy zeroes, and then we will reprocess the marker.
  168491. *
  168492. * #2 is appropriate if we think the desired marker lies ahead, while #3 is
  168493. * appropriate if the found marker is a future restart marker (indicating
  168494. * that we have missed the desired restart marker, probably because it got
  168495. * corrupted).
  168496. * We apply #2 or #3 if the found marker is a restart marker no more than
  168497. * two counts behind or ahead of the expected one. We also apply #2 if the
  168498. * found marker is not a legal JPEG marker code (it's certainly bogus data).
  168499. * If the found marker is a restart marker more than 2 counts away, we do #1
  168500. * (too much risk that the marker is erroneous; with luck we will be able to
  168501. * resync at some future point).
  168502. * For any valid non-restart JPEG marker, we apply #3. This keeps us from
  168503. * overrunning the end of a scan. An implementation limited to single-scan
  168504. * files might find it better to apply #2 for markers other than EOI, since
  168505. * any other marker would have to be bogus data in that case.
  168506. */
  168507. GLOBAL(boolean)
  168508. jpeg_resync_to_restart (j_decompress_ptr cinfo, int desired)
  168509. {
  168510. int marker = cinfo->unread_marker;
  168511. int action = 1;
  168512. /* Always put up a warning. */
  168513. WARNMS2(cinfo, JWRN_MUST_RESYNC, marker, desired);
  168514. /* Outer loop handles repeated decision after scanning forward. */
  168515. for (;;) {
  168516. if (marker < (int) M_SOF0)
  168517. action = 2; /* invalid marker */
  168518. else if (marker < (int) M_RST0 || marker > (int) M_RST7)
  168519. action = 3; /* valid non-restart marker */
  168520. else {
  168521. if (marker == ((int) M_RST0 + ((desired+1) & 7)) ||
  168522. marker == ((int) M_RST0 + ((desired+2) & 7)))
  168523. action = 3; /* one of the next two expected restarts */
  168524. else if (marker == ((int) M_RST0 + ((desired-1) & 7)) ||
  168525. marker == ((int) M_RST0 + ((desired-2) & 7)))
  168526. action = 2; /* a prior restart, so advance */
  168527. else
  168528. action = 1; /* desired restart or too far away */
  168529. }
  168530. TRACEMS2(cinfo, 4, JTRC_RECOVERY_ACTION, marker, action);
  168531. switch (action) {
  168532. case 1:
  168533. /* Discard marker and let entropy decoder resume processing. */
  168534. cinfo->unread_marker = 0;
  168535. return TRUE;
  168536. case 2:
  168537. /* Scan to the next marker, and repeat the decision loop. */
  168538. if (! next_marker(cinfo))
  168539. return FALSE;
  168540. marker = cinfo->unread_marker;
  168541. break;
  168542. case 3:
  168543. /* Return without advancing past this marker. */
  168544. /* Entropy decoder will be forced to process an empty segment. */
  168545. return TRUE;
  168546. }
  168547. } /* end loop */
  168548. }
  168549. /*
  168550. * Reset marker processing state to begin a fresh datastream.
  168551. */
  168552. METHODDEF(void)
  168553. reset_marker_reader (j_decompress_ptr cinfo)
  168554. {
  168555. my_marker_ptr2 marker = (my_marker_ptr2) cinfo->marker;
  168556. cinfo->comp_info = NULL; /* until allocated by get_sof */
  168557. cinfo->input_scan_number = 0; /* no SOS seen yet */
  168558. cinfo->unread_marker = 0; /* no pending marker */
  168559. marker->pub.saw_SOI = FALSE; /* set internal state too */
  168560. marker->pub.saw_SOF = FALSE;
  168561. marker->pub.discarded_bytes = 0;
  168562. marker->cur_marker = NULL;
  168563. }
  168564. /*
  168565. * Initialize the marker reader module.
  168566. * This is called only once, when the decompression object is created.
  168567. */
  168568. GLOBAL(void)
  168569. jinit_marker_reader (j_decompress_ptr cinfo)
  168570. {
  168571. my_marker_ptr2 marker;
  168572. int i;
  168573. /* Create subobject in permanent pool */
  168574. marker = (my_marker_ptr2)
  168575. (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_PERMANENT,
  168576. SIZEOF(my_marker_reader));
  168577. cinfo->marker = (struct jpeg_marker_reader *) marker;
  168578. /* Initialize public method pointers */
  168579. marker->pub.reset_marker_reader = reset_marker_reader;
  168580. marker->pub.read_markers = read_markers;
  168581. marker->pub.read_restart_marker = read_restart_marker;
  168582. /* Initialize COM/APPn processing.
  168583. * By default, we examine and then discard APP0 and APP14,
  168584. * but simply discard COM and all other APPn.
  168585. */
  168586. marker->process_COM = skip_variable;
  168587. marker->length_limit_COM = 0;
  168588. for (i = 0; i < 16; i++) {
  168589. marker->process_APPn[i] = skip_variable;
  168590. marker->length_limit_APPn[i] = 0;
  168591. }
  168592. marker->process_APPn[0] = get_interesting_appn;
  168593. marker->process_APPn[14] = get_interesting_appn;
  168594. /* Reset marker processing state */
  168595. reset_marker_reader(cinfo);
  168596. }
  168597. /*
  168598. * Control saving of COM and APPn markers into marker_list.
  168599. */
  168600. #ifdef SAVE_MARKERS_SUPPORTED
  168601. GLOBAL(void)
  168602. jpeg_save_markers (j_decompress_ptr cinfo, int marker_code,
  168603. unsigned int length_limit)
  168604. {
  168605. my_marker_ptr2 marker = (my_marker_ptr2) cinfo->marker;
  168606. long maxlength;
  168607. jpeg_marker_parser_method processor;
  168608. /* Length limit mustn't be larger than what we can allocate
  168609. * (should only be a concern in a 16-bit environment).
  168610. */
  168611. maxlength = cinfo->mem->max_alloc_chunk - SIZEOF(struct jpeg_marker_struct);
  168612. if (((long) length_limit) > maxlength)
  168613. length_limit = (unsigned int) maxlength;
  168614. /* Choose processor routine to use.
  168615. * APP0/APP14 have special requirements.
  168616. */
  168617. if (length_limit) {
  168618. processor = save_marker;
  168619. /* If saving APP0/APP14, save at least enough for our internal use. */
  168620. if (marker_code == (int) M_APP0 && length_limit < APP0_DATA_LEN)
  168621. length_limit = APP0_DATA_LEN;
  168622. else if (marker_code == (int) M_APP14 && length_limit < APP14_DATA_LEN)
  168623. length_limit = APP14_DATA_LEN;
  168624. } else {
  168625. processor = skip_variable;
  168626. /* If discarding APP0/APP14, use our regular on-the-fly processor. */
  168627. if (marker_code == (int) M_APP0 || marker_code == (int) M_APP14)
  168628. processor = get_interesting_appn;
  168629. }
  168630. if (marker_code == (int) M_COM) {
  168631. marker->process_COM = processor;
  168632. marker->length_limit_COM = length_limit;
  168633. } else if (marker_code >= (int) M_APP0 && marker_code <= (int) M_APP15) {
  168634. marker->process_APPn[marker_code - (int) M_APP0] = processor;
  168635. marker->length_limit_APPn[marker_code - (int) M_APP0] = length_limit;
  168636. } else
  168637. ERREXIT1(cinfo, JERR_UNKNOWN_MARKER, marker_code);
  168638. }
  168639. #endif /* SAVE_MARKERS_SUPPORTED */
  168640. /*
  168641. * Install a special processing method for COM or APPn markers.
  168642. */
  168643. GLOBAL(void)
  168644. jpeg_set_marker_processor (j_decompress_ptr cinfo, int marker_code,
  168645. jpeg_marker_parser_method routine)
  168646. {
  168647. my_marker_ptr2 marker = (my_marker_ptr2) cinfo->marker;
  168648. if (marker_code == (int) M_COM)
  168649. marker->process_COM = routine;
  168650. else if (marker_code >= (int) M_APP0 && marker_code <= (int) M_APP15)
  168651. marker->process_APPn[marker_code - (int) M_APP0] = routine;
  168652. else
  168653. ERREXIT1(cinfo, JERR_UNKNOWN_MARKER, marker_code);
  168654. }
  168655. /*** End of inlined file: jdmarker.c ***/
  168656. /*** Start of inlined file: jdmaster.c ***/
  168657. #define JPEG_INTERNALS
  168658. /* Private state */
  168659. typedef struct {
  168660. struct jpeg_decomp_master pub; /* public fields */
  168661. int pass_number; /* # of passes completed */
  168662. boolean using_merged_upsample; /* TRUE if using merged upsample/cconvert */
  168663. /* Saved references to initialized quantizer modules,
  168664. * in case we need to switch modes.
  168665. */
  168666. struct jpeg_color_quantizer * quantizer_1pass;
  168667. struct jpeg_color_quantizer * quantizer_2pass;
  168668. } my_decomp_master;
  168669. typedef my_decomp_master * my_master_ptr6;
  168670. /*
  168671. * Determine whether merged upsample/color conversion should be used.
  168672. * CRUCIAL: this must match the actual capabilities of jdmerge.c!
  168673. */
  168674. LOCAL(boolean)
  168675. use_merged_upsample (j_decompress_ptr cinfo)
  168676. {
  168677. #ifdef UPSAMPLE_MERGING_SUPPORTED
  168678. /* Merging is the equivalent of plain box-filter upsampling */
  168679. if (cinfo->do_fancy_upsampling || cinfo->CCIR601_sampling)
  168680. return FALSE;
  168681. /* jdmerge.c only supports YCC=>RGB color conversion */
  168682. if (cinfo->jpeg_color_space != JCS_YCbCr || cinfo->num_components != 3 ||
  168683. cinfo->out_color_space != JCS_RGB ||
  168684. cinfo->out_color_components != RGB_PIXELSIZE)
  168685. return FALSE;
  168686. /* and it only handles 2h1v or 2h2v sampling ratios */
  168687. if (cinfo->comp_info[0].h_samp_factor != 2 ||
  168688. cinfo->comp_info[1].h_samp_factor != 1 ||
  168689. cinfo->comp_info[2].h_samp_factor != 1 ||
  168690. cinfo->comp_info[0].v_samp_factor > 2 ||
  168691. cinfo->comp_info[1].v_samp_factor != 1 ||
  168692. cinfo->comp_info[2].v_samp_factor != 1)
  168693. return FALSE;
  168694. /* furthermore, it doesn't work if we've scaled the IDCTs differently */
  168695. if (cinfo->comp_info[0].DCT_scaled_size != cinfo->min_DCT_scaled_size ||
  168696. cinfo->comp_info[1].DCT_scaled_size != cinfo->min_DCT_scaled_size ||
  168697. cinfo->comp_info[2].DCT_scaled_size != cinfo->min_DCT_scaled_size)
  168698. return FALSE;
  168699. /* ??? also need to test for upsample-time rescaling, when & if supported */
  168700. return TRUE; /* by golly, it'll work... */
  168701. #else
  168702. return FALSE;
  168703. #endif
  168704. }
  168705. /*
  168706. * Compute output image dimensions and related values.
  168707. * NOTE: this is exported for possible use by application.
  168708. * Hence it mustn't do anything that can't be done twice.
  168709. * Also note that it may be called before the master module is initialized!
  168710. */
  168711. GLOBAL(void)
  168712. jpeg_calc_output_dimensions (j_decompress_ptr cinfo)
  168713. /* Do computations that are needed before master selection phase */
  168714. {
  168715. #ifdef IDCT_SCALING_SUPPORTED
  168716. int ci;
  168717. jpeg_component_info *compptr;
  168718. #endif
  168719. /* Prevent application from calling me at wrong times */
  168720. if (cinfo->global_state != DSTATE_READY)
  168721. ERREXIT1(cinfo, JERR_BAD_STATE, cinfo->global_state);
  168722. #ifdef IDCT_SCALING_SUPPORTED
  168723. /* Compute actual output image dimensions and DCT scaling choices. */
  168724. if (cinfo->scale_num * 8 <= cinfo->scale_denom) {
  168725. /* Provide 1/8 scaling */
  168726. cinfo->output_width = (JDIMENSION)
  168727. jdiv_round_up((long) cinfo->image_width, 8L);
  168728. cinfo->output_height = (JDIMENSION)
  168729. jdiv_round_up((long) cinfo->image_height, 8L);
  168730. cinfo->min_DCT_scaled_size = 1;
  168731. } else if (cinfo->scale_num * 4 <= cinfo->scale_denom) {
  168732. /* Provide 1/4 scaling */
  168733. cinfo->output_width = (JDIMENSION)
  168734. jdiv_round_up((long) cinfo->image_width, 4L);
  168735. cinfo->output_height = (JDIMENSION)
  168736. jdiv_round_up((long) cinfo->image_height, 4L);
  168737. cinfo->min_DCT_scaled_size = 2;
  168738. } else if (cinfo->scale_num * 2 <= cinfo->scale_denom) {
  168739. /* Provide 1/2 scaling */
  168740. cinfo->output_width = (JDIMENSION)
  168741. jdiv_round_up((long) cinfo->image_width, 2L);
  168742. cinfo->output_height = (JDIMENSION)
  168743. jdiv_round_up((long) cinfo->image_height, 2L);
  168744. cinfo->min_DCT_scaled_size = 4;
  168745. } else {
  168746. /* Provide 1/1 scaling */
  168747. cinfo->output_width = cinfo->image_width;
  168748. cinfo->output_height = cinfo->image_height;
  168749. cinfo->min_DCT_scaled_size = DCTSIZE;
  168750. }
  168751. /* In selecting the actual DCT scaling for each component, we try to
  168752. * scale up the chroma components via IDCT scaling rather than upsampling.
  168753. * This saves time if the upsampler gets to use 1:1 scaling.
  168754. * Note this code assumes that the supported DCT scalings are powers of 2.
  168755. */
  168756. for (ci = 0, compptr = cinfo->comp_info; ci < cinfo->num_components;
  168757. ci++, compptr++) {
  168758. int ssize = cinfo->min_DCT_scaled_size;
  168759. while (ssize < DCTSIZE &&
  168760. (compptr->h_samp_factor * ssize * 2 <=
  168761. cinfo->max_h_samp_factor * cinfo->min_DCT_scaled_size) &&
  168762. (compptr->v_samp_factor * ssize * 2 <=
  168763. cinfo->max_v_samp_factor * cinfo->min_DCT_scaled_size)) {
  168764. ssize = ssize * 2;
  168765. }
  168766. compptr->DCT_scaled_size = ssize;
  168767. }
  168768. /* Recompute downsampled dimensions of components;
  168769. * application needs to know these if using raw downsampled data.
  168770. */
  168771. for (ci = 0, compptr = cinfo->comp_info; ci < cinfo->num_components;
  168772. ci++, compptr++) {
  168773. /* Size in samples, after IDCT scaling */
  168774. compptr->downsampled_width = (JDIMENSION)
  168775. jdiv_round_up((long) cinfo->image_width *
  168776. (long) (compptr->h_samp_factor * compptr->DCT_scaled_size),
  168777. (long) (cinfo->max_h_samp_factor * DCTSIZE));
  168778. compptr->downsampled_height = (JDIMENSION)
  168779. jdiv_round_up((long) cinfo->image_height *
  168780. (long) (compptr->v_samp_factor * compptr->DCT_scaled_size),
  168781. (long) (cinfo->max_v_samp_factor * DCTSIZE));
  168782. }
  168783. #else /* !IDCT_SCALING_SUPPORTED */
  168784. /* Hardwire it to "no scaling" */
  168785. cinfo->output_width = cinfo->image_width;
  168786. cinfo->output_height = cinfo->image_height;
  168787. /* jdinput.c has already initialized DCT_scaled_size to DCTSIZE,
  168788. * and has computed unscaled downsampled_width and downsampled_height.
  168789. */
  168790. #endif /* IDCT_SCALING_SUPPORTED */
  168791. /* Report number of components in selected colorspace. */
  168792. /* Probably this should be in the color conversion module... */
  168793. switch (cinfo->out_color_space) {
  168794. case JCS_GRAYSCALE:
  168795. cinfo->out_color_components = 1;
  168796. break;
  168797. case JCS_RGB:
  168798. #if RGB_PIXELSIZE != 3
  168799. cinfo->out_color_components = RGB_PIXELSIZE;
  168800. break;
  168801. #endif /* else share code with YCbCr */
  168802. case JCS_YCbCr:
  168803. cinfo->out_color_components = 3;
  168804. break;
  168805. case JCS_CMYK:
  168806. case JCS_YCCK:
  168807. cinfo->out_color_components = 4;
  168808. break;
  168809. default: /* else must be same colorspace as in file */
  168810. cinfo->out_color_components = cinfo->num_components;
  168811. break;
  168812. }
  168813. cinfo->output_components = (cinfo->quantize_colors ? 1 :
  168814. cinfo->out_color_components);
  168815. /* See if upsampler will want to emit more than one row at a time */
  168816. if (use_merged_upsample(cinfo))
  168817. cinfo->rec_outbuf_height = cinfo->max_v_samp_factor;
  168818. else
  168819. cinfo->rec_outbuf_height = 1;
  168820. }
  168821. /*
  168822. * Several decompression processes need to range-limit values to the range
  168823. * 0..MAXJSAMPLE; the input value may fall somewhat outside this range
  168824. * due to noise introduced by quantization, roundoff error, etc. These
  168825. * processes are inner loops and need to be as fast as possible. On most
  168826. * machines, particularly CPUs with pipelines or instruction prefetch,
  168827. * a (subscript-check-less) C table lookup
  168828. * x = sample_range_limit[x];
  168829. * is faster than explicit tests
  168830. * if (x < 0) x = 0;
  168831. * else if (x > MAXJSAMPLE) x = MAXJSAMPLE;
  168832. * These processes all use a common table prepared by the routine below.
  168833. *
  168834. * For most steps we can mathematically guarantee that the initial value
  168835. * of x is within MAXJSAMPLE+1 of the legal range, so a table running from
  168836. * -(MAXJSAMPLE+1) to 2*MAXJSAMPLE+1 is sufficient. But for the initial
  168837. * limiting step (just after the IDCT), a wildly out-of-range value is
  168838. * possible if the input data is corrupt. To avoid any chance of indexing
  168839. * off the end of memory and getting a bad-pointer trap, we perform the
  168840. * post-IDCT limiting thus:
  168841. * x = range_limit[x & MASK];
  168842. * where MASK is 2 bits wider than legal sample data, ie 10 bits for 8-bit
  168843. * samples. Under normal circumstances this is more than enough range and
  168844. * a correct output will be generated; with bogus input data the mask will
  168845. * cause wraparound, and we will safely generate a bogus-but-in-range output.
  168846. * For the post-IDCT step, we want to convert the data from signed to unsigned
  168847. * representation by adding CENTERJSAMPLE at the same time that we limit it.
  168848. * So the post-IDCT limiting table ends up looking like this:
  168849. * CENTERJSAMPLE,CENTERJSAMPLE+1,...,MAXJSAMPLE,
  168850. * MAXJSAMPLE (repeat 2*(MAXJSAMPLE+1)-CENTERJSAMPLE times),
  168851. * 0 (repeat 2*(MAXJSAMPLE+1)-CENTERJSAMPLE times),
  168852. * 0,1,...,CENTERJSAMPLE-1
  168853. * Negative inputs select values from the upper half of the table after
  168854. * masking.
  168855. *
  168856. * We can save some space by overlapping the start of the post-IDCT table
  168857. * with the simpler range limiting table. The post-IDCT table begins at
  168858. * sample_range_limit + CENTERJSAMPLE.
  168859. *
  168860. * Note that the table is allocated in near data space on PCs; it's small
  168861. * enough and used often enough to justify this.
  168862. */
  168863. LOCAL(void)
  168864. prepare_range_limit_table (j_decompress_ptr cinfo)
  168865. /* Allocate and fill in the sample_range_limit table */
  168866. {
  168867. JSAMPLE * table;
  168868. int i;
  168869. table = (JSAMPLE *)
  168870. (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_IMAGE,
  168871. (5 * (MAXJSAMPLE+1) + CENTERJSAMPLE) * SIZEOF(JSAMPLE));
  168872. table += (MAXJSAMPLE+1); /* allow negative subscripts of simple table */
  168873. cinfo->sample_range_limit = table;
  168874. /* First segment of "simple" table: limit[x] = 0 for x < 0 */
  168875. MEMZERO(table - (MAXJSAMPLE+1), (MAXJSAMPLE+1) * SIZEOF(JSAMPLE));
  168876. /* Main part of "simple" table: limit[x] = x */
  168877. for (i = 0; i <= MAXJSAMPLE; i++)
  168878. table[i] = (JSAMPLE) i;
  168879. table += CENTERJSAMPLE; /* Point to where post-IDCT table starts */
  168880. /* End of simple table, rest of first half of post-IDCT table */
  168881. for (i = CENTERJSAMPLE; i < 2*(MAXJSAMPLE+1); i++)
  168882. table[i] = MAXJSAMPLE;
  168883. /* Second half of post-IDCT table */
  168884. MEMZERO(table + (2 * (MAXJSAMPLE+1)),
  168885. (2 * (MAXJSAMPLE+1) - CENTERJSAMPLE) * SIZEOF(JSAMPLE));
  168886. MEMCOPY(table + (4 * (MAXJSAMPLE+1) - CENTERJSAMPLE),
  168887. cinfo->sample_range_limit, CENTERJSAMPLE * SIZEOF(JSAMPLE));
  168888. }
  168889. /*
  168890. * Master selection of decompression modules.
  168891. * This is done once at jpeg_start_decompress time. We determine
  168892. * which modules will be used and give them appropriate initialization calls.
  168893. * We also initialize the decompressor input side to begin consuming data.
  168894. *
  168895. * Since jpeg_read_header has finished, we know what is in the SOF
  168896. * and (first) SOS markers. We also have all the application parameter
  168897. * settings.
  168898. */
  168899. LOCAL(void)
  168900. master_selection (j_decompress_ptr cinfo)
  168901. {
  168902. my_master_ptr6 master = (my_master_ptr6) cinfo->master;
  168903. boolean use_c_buffer;
  168904. long samplesperrow;
  168905. JDIMENSION jd_samplesperrow;
  168906. /* Initialize dimensions and other stuff */
  168907. jpeg_calc_output_dimensions(cinfo);
  168908. prepare_range_limit_table(cinfo);
  168909. /* Width of an output scanline must be representable as JDIMENSION. */
  168910. samplesperrow = (long) cinfo->output_width * (long) cinfo->out_color_components;
  168911. jd_samplesperrow = (JDIMENSION) samplesperrow;
  168912. if ((long) jd_samplesperrow != samplesperrow)
  168913. ERREXIT(cinfo, JERR_WIDTH_OVERFLOW);
  168914. /* Initialize my private state */
  168915. master->pass_number = 0;
  168916. master->using_merged_upsample = use_merged_upsample(cinfo);
  168917. /* Color quantizer selection */
  168918. master->quantizer_1pass = NULL;
  168919. master->quantizer_2pass = NULL;
  168920. /* No mode changes if not using buffered-image mode. */
  168921. if (! cinfo->quantize_colors || ! cinfo->buffered_image) {
  168922. cinfo->enable_1pass_quant = FALSE;
  168923. cinfo->enable_external_quant = FALSE;
  168924. cinfo->enable_2pass_quant = FALSE;
  168925. }
  168926. if (cinfo->quantize_colors) {
  168927. if (cinfo->raw_data_out)
  168928. ERREXIT(cinfo, JERR_NOTIMPL);
  168929. /* 2-pass quantizer only works in 3-component color space. */
  168930. if (cinfo->out_color_components != 3) {
  168931. cinfo->enable_1pass_quant = TRUE;
  168932. cinfo->enable_external_quant = FALSE;
  168933. cinfo->enable_2pass_quant = FALSE;
  168934. cinfo->colormap = NULL;
  168935. } else if (cinfo->colormap != NULL) {
  168936. cinfo->enable_external_quant = TRUE;
  168937. } else if (cinfo->two_pass_quantize) {
  168938. cinfo->enable_2pass_quant = TRUE;
  168939. } else {
  168940. cinfo->enable_1pass_quant = TRUE;
  168941. }
  168942. if (cinfo->enable_1pass_quant) {
  168943. #ifdef QUANT_1PASS_SUPPORTED
  168944. jinit_1pass_quantizer(cinfo);
  168945. master->quantizer_1pass = cinfo->cquantize;
  168946. #else
  168947. ERREXIT(cinfo, JERR_NOT_COMPILED);
  168948. #endif
  168949. }
  168950. /* We use the 2-pass code to map to external colormaps. */
  168951. if (cinfo->enable_2pass_quant || cinfo->enable_external_quant) {
  168952. #ifdef QUANT_2PASS_SUPPORTED
  168953. jinit_2pass_quantizer(cinfo);
  168954. master->quantizer_2pass = cinfo->cquantize;
  168955. #else
  168956. ERREXIT(cinfo, JERR_NOT_COMPILED);
  168957. #endif
  168958. }
  168959. /* If both quantizers are initialized, the 2-pass one is left active;
  168960. * this is necessary for starting with quantization to an external map.
  168961. */
  168962. }
  168963. /* Post-processing: in particular, color conversion first */
  168964. if (! cinfo->raw_data_out) {
  168965. if (master->using_merged_upsample) {
  168966. #ifdef UPSAMPLE_MERGING_SUPPORTED
  168967. jinit_merged_upsampler(cinfo); /* does color conversion too */
  168968. #else
  168969. ERREXIT(cinfo, JERR_NOT_COMPILED);
  168970. #endif
  168971. } else {
  168972. jinit_color_deconverter(cinfo);
  168973. jinit_upsampler(cinfo);
  168974. }
  168975. jinit_d_post_controller(cinfo, cinfo->enable_2pass_quant);
  168976. }
  168977. /* Inverse DCT */
  168978. jinit_inverse_dct(cinfo);
  168979. /* Entropy decoding: either Huffman or arithmetic coding. */
  168980. if (cinfo->arith_code) {
  168981. ERREXIT(cinfo, JERR_ARITH_NOTIMPL);
  168982. } else {
  168983. if (cinfo->progressive_mode) {
  168984. #ifdef D_PROGRESSIVE_SUPPORTED
  168985. jinit_phuff_decoder(cinfo);
  168986. #else
  168987. ERREXIT(cinfo, JERR_NOT_COMPILED);
  168988. #endif
  168989. } else
  168990. jinit_huff_decoder(cinfo);
  168991. }
  168992. /* Initialize principal buffer controllers. */
  168993. use_c_buffer = cinfo->inputctl->has_multiple_scans || cinfo->buffered_image;
  168994. jinit_d_coef_controller(cinfo, use_c_buffer);
  168995. if (! cinfo->raw_data_out)
  168996. jinit_d_main_controller(cinfo, FALSE /* never need full buffer here */);
  168997. /* We can now tell the memory manager to allocate virtual arrays. */
  168998. (*cinfo->mem->realize_virt_arrays) ((j_common_ptr) cinfo);
  168999. /* Initialize input side of decompressor to consume first scan. */
  169000. (*cinfo->inputctl->start_input_pass) (cinfo);
  169001. #ifdef D_MULTISCAN_FILES_SUPPORTED
  169002. /* If jpeg_start_decompress will read the whole file, initialize
  169003. * progress monitoring appropriately. The input step is counted
  169004. * as one pass.
  169005. */
  169006. if (cinfo->progress != NULL && ! cinfo->buffered_image &&
  169007. cinfo->inputctl->has_multiple_scans) {
  169008. int nscans;
  169009. /* Estimate number of scans to set pass_limit. */
  169010. if (cinfo->progressive_mode) {
  169011. /* Arbitrarily estimate 2 interleaved DC scans + 3 AC scans/component. */
  169012. nscans = 2 + 3 * cinfo->num_components;
  169013. } else {
  169014. /* For a nonprogressive multiscan file, estimate 1 scan per component. */
  169015. nscans = cinfo->num_components;
  169016. }
  169017. cinfo->progress->pass_counter = 0L;
  169018. cinfo->progress->pass_limit = (long) cinfo->total_iMCU_rows * nscans;
  169019. cinfo->progress->completed_passes = 0;
  169020. cinfo->progress->total_passes = (cinfo->enable_2pass_quant ? 3 : 2);
  169021. /* Count the input pass as done */
  169022. master->pass_number++;
  169023. }
  169024. #endif /* D_MULTISCAN_FILES_SUPPORTED */
  169025. }
  169026. /*
  169027. * Per-pass setup.
  169028. * This is called at the beginning of each output pass. We determine which
  169029. * modules will be active during this pass and give them appropriate
  169030. * start_pass calls. We also set is_dummy_pass to indicate whether this
  169031. * is a "real" output pass or a dummy pass for color quantization.
  169032. * (In the latter case, jdapistd.c will crank the pass to completion.)
  169033. */
  169034. METHODDEF(void)
  169035. prepare_for_output_pass (j_decompress_ptr cinfo)
  169036. {
  169037. my_master_ptr6 master = (my_master_ptr6) cinfo->master;
  169038. if (master->pub.is_dummy_pass) {
  169039. #ifdef QUANT_2PASS_SUPPORTED
  169040. /* Final pass of 2-pass quantization */
  169041. master->pub.is_dummy_pass = FALSE;
  169042. (*cinfo->cquantize->start_pass) (cinfo, FALSE);
  169043. (*cinfo->post->start_pass) (cinfo, JBUF_CRANK_DEST);
  169044. (*cinfo->main->start_pass) (cinfo, JBUF_CRANK_DEST);
  169045. #else
  169046. ERREXIT(cinfo, JERR_NOT_COMPILED);
  169047. #endif /* QUANT_2PASS_SUPPORTED */
  169048. } else {
  169049. if (cinfo->quantize_colors && cinfo->colormap == NULL) {
  169050. /* Select new quantization method */
  169051. if (cinfo->two_pass_quantize && cinfo->enable_2pass_quant) {
  169052. cinfo->cquantize = master->quantizer_2pass;
  169053. master->pub.is_dummy_pass = TRUE;
  169054. } else if (cinfo->enable_1pass_quant) {
  169055. cinfo->cquantize = master->quantizer_1pass;
  169056. } else {
  169057. ERREXIT(cinfo, JERR_MODE_CHANGE);
  169058. }
  169059. }
  169060. (*cinfo->idct->start_pass) (cinfo);
  169061. (*cinfo->coef->start_output_pass) (cinfo);
  169062. if (! cinfo->raw_data_out) {
  169063. if (! master->using_merged_upsample)
  169064. (*cinfo->cconvert->start_pass) (cinfo);
  169065. (*cinfo->upsample->start_pass) (cinfo);
  169066. if (cinfo->quantize_colors)
  169067. (*cinfo->cquantize->start_pass) (cinfo, master->pub.is_dummy_pass);
  169068. (*cinfo->post->start_pass) (cinfo,
  169069. (master->pub.is_dummy_pass ? JBUF_SAVE_AND_PASS : JBUF_PASS_THRU));
  169070. (*cinfo->main->start_pass) (cinfo, JBUF_PASS_THRU);
  169071. }
  169072. }
  169073. /* Set up progress monitor's pass info if present */
  169074. if (cinfo->progress != NULL) {
  169075. cinfo->progress->completed_passes = master->pass_number;
  169076. cinfo->progress->total_passes = master->pass_number +
  169077. (master->pub.is_dummy_pass ? 2 : 1);
  169078. /* In buffered-image mode, we assume one more output pass if EOI not
  169079. * yet reached, but no more passes if EOI has been reached.
  169080. */
  169081. if (cinfo->buffered_image && ! cinfo->inputctl->eoi_reached) {
  169082. cinfo->progress->total_passes += (cinfo->enable_2pass_quant ? 2 : 1);
  169083. }
  169084. }
  169085. }
  169086. /*
  169087. * Finish up at end of an output pass.
  169088. */
  169089. METHODDEF(void)
  169090. finish_output_pass (j_decompress_ptr cinfo)
  169091. {
  169092. my_master_ptr6 master = (my_master_ptr6) cinfo->master;
  169093. if (cinfo->quantize_colors)
  169094. (*cinfo->cquantize->finish_pass) (cinfo);
  169095. master->pass_number++;
  169096. }
  169097. #ifdef D_MULTISCAN_FILES_SUPPORTED
  169098. /*
  169099. * Switch to a new external colormap between output passes.
  169100. */
  169101. GLOBAL(void)
  169102. jpeg_new_colormap (j_decompress_ptr cinfo)
  169103. {
  169104. my_master_ptr6 master = (my_master_ptr6) cinfo->master;
  169105. /* Prevent application from calling me at wrong times */
  169106. if (cinfo->global_state != DSTATE_BUFIMAGE)
  169107. ERREXIT1(cinfo, JERR_BAD_STATE, cinfo->global_state);
  169108. if (cinfo->quantize_colors && cinfo->enable_external_quant &&
  169109. cinfo->colormap != NULL) {
  169110. /* Select 2-pass quantizer for external colormap use */
  169111. cinfo->cquantize = master->quantizer_2pass;
  169112. /* Notify quantizer of colormap change */
  169113. (*cinfo->cquantize->new_color_map) (cinfo);
  169114. master->pub.is_dummy_pass = FALSE; /* just in case */
  169115. } else
  169116. ERREXIT(cinfo, JERR_MODE_CHANGE);
  169117. }
  169118. #endif /* D_MULTISCAN_FILES_SUPPORTED */
  169119. /*
  169120. * Initialize master decompression control and select active modules.
  169121. * This is performed at the start of jpeg_start_decompress.
  169122. */
  169123. GLOBAL(void)
  169124. jinit_master_decompress (j_decompress_ptr cinfo)
  169125. {
  169126. my_master_ptr6 master;
  169127. master = (my_master_ptr6)
  169128. (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_IMAGE,
  169129. SIZEOF(my_decomp_master));
  169130. cinfo->master = (struct jpeg_decomp_master *) master;
  169131. master->pub.prepare_for_output_pass = prepare_for_output_pass;
  169132. master->pub.finish_output_pass = finish_output_pass;
  169133. master->pub.is_dummy_pass = FALSE;
  169134. master_selection(cinfo);
  169135. }
  169136. /*** End of inlined file: jdmaster.c ***/
  169137. #undef FIX
  169138. /*** Start of inlined file: jdmerge.c ***/
  169139. #define JPEG_INTERNALS
  169140. #ifdef UPSAMPLE_MERGING_SUPPORTED
  169141. /* Private subobject */
  169142. typedef struct {
  169143. struct jpeg_upsampler pub; /* public fields */
  169144. /* Pointer to routine to do actual upsampling/conversion of one row group */
  169145. JMETHOD(void, upmethod, (j_decompress_ptr cinfo,
  169146. JSAMPIMAGE input_buf, JDIMENSION in_row_group_ctr,
  169147. JSAMPARRAY output_buf));
  169148. /* Private state for YCC->RGB conversion */
  169149. int * Cr_r_tab; /* => table for Cr to R conversion */
  169150. int * Cb_b_tab; /* => table for Cb to B conversion */
  169151. INT32 * Cr_g_tab; /* => table for Cr to G conversion */
  169152. INT32 * Cb_g_tab; /* => table for Cb to G conversion */
  169153. /* For 2:1 vertical sampling, we produce two output rows at a time.
  169154. * We need a "spare" row buffer to hold the second output row if the
  169155. * application provides just a one-row buffer; we also use the spare
  169156. * to discard the dummy last row if the image height is odd.
  169157. */
  169158. JSAMPROW spare_row;
  169159. boolean spare_full; /* T if spare buffer is occupied */
  169160. JDIMENSION out_row_width; /* samples per output row */
  169161. JDIMENSION rows_to_go; /* counts rows remaining in image */
  169162. } my_upsampler;
  169163. typedef my_upsampler * my_upsample_ptr;
  169164. #define SCALEBITS 16 /* speediest right-shift on some machines */
  169165. #define ONE_HALF ((INT32) 1 << (SCALEBITS-1))
  169166. #define FIX(x) ((INT32) ((x) * (1L<<SCALEBITS) + 0.5))
  169167. /*
  169168. * Initialize tables for YCC->RGB colorspace conversion.
  169169. * This is taken directly from jdcolor.c; see that file for more info.
  169170. */
  169171. LOCAL(void)
  169172. build_ycc_rgb_table2 (j_decompress_ptr cinfo)
  169173. {
  169174. my_upsample_ptr upsample = (my_upsample_ptr) cinfo->upsample;
  169175. int i;
  169176. INT32 x;
  169177. SHIFT_TEMPS
  169178. upsample->Cr_r_tab = (int *)
  169179. (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_IMAGE,
  169180. (MAXJSAMPLE+1) * SIZEOF(int));
  169181. upsample->Cb_b_tab = (int *)
  169182. (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_IMAGE,
  169183. (MAXJSAMPLE+1) * SIZEOF(int));
  169184. upsample->Cr_g_tab = (INT32 *)
  169185. (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_IMAGE,
  169186. (MAXJSAMPLE+1) * SIZEOF(INT32));
  169187. upsample->Cb_g_tab = (INT32 *)
  169188. (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_IMAGE,
  169189. (MAXJSAMPLE+1) * SIZEOF(INT32));
  169190. for (i = 0, x = -CENTERJSAMPLE; i <= MAXJSAMPLE; i++, x++) {
  169191. /* i is the actual input pixel value, in the range 0..MAXJSAMPLE */
  169192. /* The Cb or Cr value we are thinking of is x = i - CENTERJSAMPLE */
  169193. /* Cr=>R value is nearest int to 1.40200 * x */
  169194. upsample->Cr_r_tab[i] = (int)
  169195. RIGHT_SHIFT(FIX(1.40200) * x + ONE_HALF, SCALEBITS);
  169196. /* Cb=>B value is nearest int to 1.77200 * x */
  169197. upsample->Cb_b_tab[i] = (int)
  169198. RIGHT_SHIFT(FIX(1.77200) * x + ONE_HALF, SCALEBITS);
  169199. /* Cr=>G value is scaled-up -0.71414 * x */
  169200. upsample->Cr_g_tab[i] = (- FIX(0.71414)) * x;
  169201. /* Cb=>G value is scaled-up -0.34414 * x */
  169202. /* We also add in ONE_HALF so that need not do it in inner loop */
  169203. upsample->Cb_g_tab[i] = (- FIX(0.34414)) * x + ONE_HALF;
  169204. }
  169205. }
  169206. /*
  169207. * Initialize for an upsampling pass.
  169208. */
  169209. METHODDEF(void)
  169210. start_pass_merged_upsample (j_decompress_ptr cinfo)
  169211. {
  169212. my_upsample_ptr upsample = (my_upsample_ptr) cinfo->upsample;
  169213. /* Mark the spare buffer empty */
  169214. upsample->spare_full = FALSE;
  169215. /* Initialize total-height counter for detecting bottom of image */
  169216. upsample->rows_to_go = cinfo->output_height;
  169217. }
  169218. /*
  169219. * Control routine to do upsampling (and color conversion).
  169220. *
  169221. * The control routine just handles the row buffering considerations.
  169222. */
  169223. METHODDEF(void)
  169224. merged_2v_upsample (j_decompress_ptr cinfo,
  169225. JSAMPIMAGE input_buf, JDIMENSION *in_row_group_ctr,
  169226. JDIMENSION in_row_groups_avail,
  169227. JSAMPARRAY output_buf, JDIMENSION *out_row_ctr,
  169228. JDIMENSION out_rows_avail)
  169229. /* 2:1 vertical sampling case: may need a spare row. */
  169230. {
  169231. my_upsample_ptr upsample = (my_upsample_ptr) cinfo->upsample;
  169232. JSAMPROW work_ptrs[2];
  169233. JDIMENSION num_rows; /* number of rows returned to caller */
  169234. if (upsample->spare_full) {
  169235. /* If we have a spare row saved from a previous cycle, just return it. */
  169236. jcopy_sample_rows(& upsample->spare_row, 0, output_buf + *out_row_ctr, 0,
  169237. 1, upsample->out_row_width);
  169238. num_rows = 1;
  169239. upsample->spare_full = FALSE;
  169240. } else {
  169241. /* Figure number of rows to return to caller. */
  169242. num_rows = 2;
  169243. /* Not more than the distance to the end of the image. */
  169244. if (num_rows > upsample->rows_to_go)
  169245. num_rows = upsample->rows_to_go;
  169246. /* And not more than what the client can accept: */
  169247. out_rows_avail -= *out_row_ctr;
  169248. if (num_rows > out_rows_avail)
  169249. num_rows = out_rows_avail;
  169250. /* Create output pointer array for upsampler. */
  169251. work_ptrs[0] = output_buf[*out_row_ctr];
  169252. if (num_rows > 1) {
  169253. work_ptrs[1] = output_buf[*out_row_ctr + 1];
  169254. } else {
  169255. work_ptrs[1] = upsample->spare_row;
  169256. upsample->spare_full = TRUE;
  169257. }
  169258. /* Now do the upsampling. */
  169259. (*upsample->upmethod) (cinfo, input_buf, *in_row_group_ctr, work_ptrs);
  169260. }
  169261. /* Adjust counts */
  169262. *out_row_ctr += num_rows;
  169263. upsample->rows_to_go -= num_rows;
  169264. /* When the buffer is emptied, declare this input row group consumed */
  169265. if (! upsample->spare_full)
  169266. (*in_row_group_ctr)++;
  169267. }
  169268. METHODDEF(void)
  169269. merged_1v_upsample (j_decompress_ptr cinfo,
  169270. JSAMPIMAGE input_buf, JDIMENSION *in_row_group_ctr,
  169271. JDIMENSION in_row_groups_avail,
  169272. JSAMPARRAY output_buf, JDIMENSION *out_row_ctr,
  169273. JDIMENSION out_rows_avail)
  169274. /* 1:1 vertical sampling case: much easier, never need a spare row. */
  169275. {
  169276. my_upsample_ptr upsample = (my_upsample_ptr) cinfo->upsample;
  169277. /* Just do the upsampling. */
  169278. (*upsample->upmethod) (cinfo, input_buf, *in_row_group_ctr,
  169279. output_buf + *out_row_ctr);
  169280. /* Adjust counts */
  169281. (*out_row_ctr)++;
  169282. (*in_row_group_ctr)++;
  169283. }
  169284. /*
  169285. * These are the routines invoked by the control routines to do
  169286. * the actual upsampling/conversion. One row group is processed per call.
  169287. *
  169288. * Note: since we may be writing directly into application-supplied buffers,
  169289. * we have to be honest about the output width; we can't assume the buffer
  169290. * has been rounded up to an even width.
  169291. */
  169292. /*
  169293. * Upsample and color convert for the case of 2:1 horizontal and 1:1 vertical.
  169294. */
  169295. METHODDEF(void)
  169296. h2v1_merged_upsample (j_decompress_ptr cinfo,
  169297. JSAMPIMAGE input_buf, JDIMENSION in_row_group_ctr,
  169298. JSAMPARRAY output_buf)
  169299. {
  169300. my_upsample_ptr upsample = (my_upsample_ptr) cinfo->upsample;
  169301. register int y, cred, cgreen, cblue;
  169302. int cb, cr;
  169303. register JSAMPROW outptr;
  169304. JSAMPROW inptr0, inptr1, inptr2;
  169305. JDIMENSION col;
  169306. /* copy these pointers into registers if possible */
  169307. register JSAMPLE * range_limit = cinfo->sample_range_limit;
  169308. int * Crrtab = upsample->Cr_r_tab;
  169309. int * Cbbtab = upsample->Cb_b_tab;
  169310. INT32 * Crgtab = upsample->Cr_g_tab;
  169311. INT32 * Cbgtab = upsample->Cb_g_tab;
  169312. SHIFT_TEMPS
  169313. inptr0 = input_buf[0][in_row_group_ctr];
  169314. inptr1 = input_buf[1][in_row_group_ctr];
  169315. inptr2 = input_buf[2][in_row_group_ctr];
  169316. outptr = output_buf[0];
  169317. /* Loop for each pair of output pixels */
  169318. for (col = cinfo->output_width >> 1; col > 0; col--) {
  169319. /* Do the chroma part of the calculation */
  169320. cb = GETJSAMPLE(*inptr1++);
  169321. cr = GETJSAMPLE(*inptr2++);
  169322. cred = Crrtab[cr];
  169323. cgreen = (int) RIGHT_SHIFT(Cbgtab[cb] + Crgtab[cr], SCALEBITS);
  169324. cblue = Cbbtab[cb];
  169325. /* Fetch 2 Y values and emit 2 pixels */
  169326. y = GETJSAMPLE(*inptr0++);
  169327. outptr[RGB_RED] = range_limit[y + cred];
  169328. outptr[RGB_GREEN] = range_limit[y + cgreen];
  169329. outptr[RGB_BLUE] = range_limit[y + cblue];
  169330. outptr += RGB_PIXELSIZE;
  169331. y = GETJSAMPLE(*inptr0++);
  169332. outptr[RGB_RED] = range_limit[y + cred];
  169333. outptr[RGB_GREEN] = range_limit[y + cgreen];
  169334. outptr[RGB_BLUE] = range_limit[y + cblue];
  169335. outptr += RGB_PIXELSIZE;
  169336. }
  169337. /* If image width is odd, do the last output column separately */
  169338. if (cinfo->output_width & 1) {
  169339. cb = GETJSAMPLE(*inptr1);
  169340. cr = GETJSAMPLE(*inptr2);
  169341. cred = Crrtab[cr];
  169342. cgreen = (int) RIGHT_SHIFT(Cbgtab[cb] + Crgtab[cr], SCALEBITS);
  169343. cblue = Cbbtab[cb];
  169344. y = GETJSAMPLE(*inptr0);
  169345. outptr[RGB_RED] = range_limit[y + cred];
  169346. outptr[RGB_GREEN] = range_limit[y + cgreen];
  169347. outptr[RGB_BLUE] = range_limit[y + cblue];
  169348. }
  169349. }
  169350. /*
  169351. * Upsample and color convert for the case of 2:1 horizontal and 2:1 vertical.
  169352. */
  169353. METHODDEF(void)
  169354. h2v2_merged_upsample (j_decompress_ptr cinfo,
  169355. JSAMPIMAGE input_buf, JDIMENSION in_row_group_ctr,
  169356. JSAMPARRAY output_buf)
  169357. {
  169358. my_upsample_ptr upsample = (my_upsample_ptr) cinfo->upsample;
  169359. register int y, cred, cgreen, cblue;
  169360. int cb, cr;
  169361. register JSAMPROW outptr0, outptr1;
  169362. JSAMPROW inptr00, inptr01, inptr1, inptr2;
  169363. JDIMENSION col;
  169364. /* copy these pointers into registers if possible */
  169365. register JSAMPLE * range_limit = cinfo->sample_range_limit;
  169366. int * Crrtab = upsample->Cr_r_tab;
  169367. int * Cbbtab = upsample->Cb_b_tab;
  169368. INT32 * Crgtab = upsample->Cr_g_tab;
  169369. INT32 * Cbgtab = upsample->Cb_g_tab;
  169370. SHIFT_TEMPS
  169371. inptr00 = input_buf[0][in_row_group_ctr*2];
  169372. inptr01 = input_buf[0][in_row_group_ctr*2 + 1];
  169373. inptr1 = input_buf[1][in_row_group_ctr];
  169374. inptr2 = input_buf[2][in_row_group_ctr];
  169375. outptr0 = output_buf[0];
  169376. outptr1 = output_buf[1];
  169377. /* Loop for each group of output pixels */
  169378. for (col = cinfo->output_width >> 1; col > 0; col--) {
  169379. /* Do the chroma part of the calculation */
  169380. cb = GETJSAMPLE(*inptr1++);
  169381. cr = GETJSAMPLE(*inptr2++);
  169382. cred = Crrtab[cr];
  169383. cgreen = (int) RIGHT_SHIFT(Cbgtab[cb] + Crgtab[cr], SCALEBITS);
  169384. cblue = Cbbtab[cb];
  169385. /* Fetch 4 Y values and emit 4 pixels */
  169386. y = GETJSAMPLE(*inptr00++);
  169387. outptr0[RGB_RED] = range_limit[y + cred];
  169388. outptr0[RGB_GREEN] = range_limit[y + cgreen];
  169389. outptr0[RGB_BLUE] = range_limit[y + cblue];
  169390. outptr0 += RGB_PIXELSIZE;
  169391. y = GETJSAMPLE(*inptr00++);
  169392. outptr0[RGB_RED] = range_limit[y + cred];
  169393. outptr0[RGB_GREEN] = range_limit[y + cgreen];
  169394. outptr0[RGB_BLUE] = range_limit[y + cblue];
  169395. outptr0 += RGB_PIXELSIZE;
  169396. y = GETJSAMPLE(*inptr01++);
  169397. outptr1[RGB_RED] = range_limit[y + cred];
  169398. outptr1[RGB_GREEN] = range_limit[y + cgreen];
  169399. outptr1[RGB_BLUE] = range_limit[y + cblue];
  169400. outptr1 += RGB_PIXELSIZE;
  169401. y = GETJSAMPLE(*inptr01++);
  169402. outptr1[RGB_RED] = range_limit[y + cred];
  169403. outptr1[RGB_GREEN] = range_limit[y + cgreen];
  169404. outptr1[RGB_BLUE] = range_limit[y + cblue];
  169405. outptr1 += RGB_PIXELSIZE;
  169406. }
  169407. /* If image width is odd, do the last output column separately */
  169408. if (cinfo->output_width & 1) {
  169409. cb = GETJSAMPLE(*inptr1);
  169410. cr = GETJSAMPLE(*inptr2);
  169411. cred = Crrtab[cr];
  169412. cgreen = (int) RIGHT_SHIFT(Cbgtab[cb] + Crgtab[cr], SCALEBITS);
  169413. cblue = Cbbtab[cb];
  169414. y = GETJSAMPLE(*inptr00);
  169415. outptr0[RGB_RED] = range_limit[y + cred];
  169416. outptr0[RGB_GREEN] = range_limit[y + cgreen];
  169417. outptr0[RGB_BLUE] = range_limit[y + cblue];
  169418. y = GETJSAMPLE(*inptr01);
  169419. outptr1[RGB_RED] = range_limit[y + cred];
  169420. outptr1[RGB_GREEN] = range_limit[y + cgreen];
  169421. outptr1[RGB_BLUE] = range_limit[y + cblue];
  169422. }
  169423. }
  169424. /*
  169425. * Module initialization routine for merged upsampling/color conversion.
  169426. *
  169427. * NB: this is called under the conditions determined by use_merged_upsample()
  169428. * in jdmaster.c. That routine MUST correspond to the actual capabilities
  169429. * of this module; no safety checks are made here.
  169430. */
  169431. GLOBAL(void)
  169432. jinit_merged_upsampler (j_decompress_ptr cinfo)
  169433. {
  169434. my_upsample_ptr upsample;
  169435. upsample = (my_upsample_ptr)
  169436. (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_IMAGE,
  169437. SIZEOF(my_upsampler));
  169438. cinfo->upsample = (struct jpeg_upsampler *) upsample;
  169439. upsample->pub.start_pass = start_pass_merged_upsample;
  169440. upsample->pub.need_context_rows = FALSE;
  169441. upsample->out_row_width = cinfo->output_width * cinfo->out_color_components;
  169442. if (cinfo->max_v_samp_factor == 2) {
  169443. upsample->pub.upsample = merged_2v_upsample;
  169444. upsample->upmethod = h2v2_merged_upsample;
  169445. /* Allocate a spare row buffer */
  169446. upsample->spare_row = (JSAMPROW)
  169447. (*cinfo->mem->alloc_large) ((j_common_ptr) cinfo, JPOOL_IMAGE,
  169448. (size_t) (upsample->out_row_width * SIZEOF(JSAMPLE)));
  169449. } else {
  169450. upsample->pub.upsample = merged_1v_upsample;
  169451. upsample->upmethod = h2v1_merged_upsample;
  169452. /* No spare row needed */
  169453. upsample->spare_row = NULL;
  169454. }
  169455. build_ycc_rgb_table2(cinfo);
  169456. }
  169457. #endif /* UPSAMPLE_MERGING_SUPPORTED */
  169458. /*** End of inlined file: jdmerge.c ***/
  169459. #undef ASSIGN_STATE
  169460. /*** Start of inlined file: jdphuff.c ***/
  169461. #define JPEG_INTERNALS
  169462. #ifdef D_PROGRESSIVE_SUPPORTED
  169463. /*
  169464. * Expanded entropy decoder object for progressive Huffman decoding.
  169465. *
  169466. * The savable_state subrecord contains fields that change within an MCU,
  169467. * but must not be updated permanently until we complete the MCU.
  169468. */
  169469. typedef struct {
  169470. unsigned int EOBRUN; /* remaining EOBs in EOBRUN */
  169471. int last_dc_val[MAX_COMPS_IN_SCAN]; /* last DC coef for each component */
  169472. } savable_state3;
  169473. /* This macro is to work around compilers with missing or broken
  169474. * structure assignment. You'll need to fix this code if you have
  169475. * such a compiler and you change MAX_COMPS_IN_SCAN.
  169476. */
  169477. #ifndef NO_STRUCT_ASSIGN
  169478. #define ASSIGN_STATE(dest,src) ((dest) = (src))
  169479. #else
  169480. #if MAX_COMPS_IN_SCAN == 4
  169481. #define ASSIGN_STATE(dest,src) \
  169482. ((dest).EOBRUN = (src).EOBRUN, \
  169483. (dest).last_dc_val[0] = (src).last_dc_val[0], \
  169484. (dest).last_dc_val[1] = (src).last_dc_val[1], \
  169485. (dest).last_dc_val[2] = (src).last_dc_val[2], \
  169486. (dest).last_dc_val[3] = (src).last_dc_val[3])
  169487. #endif
  169488. #endif
  169489. typedef struct {
  169490. struct jpeg_entropy_decoder pub; /* public fields */
  169491. /* These fields are loaded into local variables at start of each MCU.
  169492. * In case of suspension, we exit WITHOUT updating them.
  169493. */
  169494. bitread_perm_state bitstate; /* Bit buffer at start of MCU */
  169495. savable_state3 saved; /* Other state at start of MCU */
  169496. /* These fields are NOT loaded into local working state. */
  169497. unsigned int restarts_to_go; /* MCUs left in this restart interval */
  169498. /* Pointers to derived tables (these workspaces have image lifespan) */
  169499. d_derived_tbl * derived_tbls[NUM_HUFF_TBLS];
  169500. d_derived_tbl * ac_derived_tbl; /* active table during an AC scan */
  169501. } phuff_entropy_decoder;
  169502. typedef phuff_entropy_decoder * phuff_entropy_ptr2;
  169503. /* Forward declarations */
  169504. METHODDEF(boolean) decode_mcu_DC_first JPP((j_decompress_ptr cinfo,
  169505. JBLOCKROW *MCU_data));
  169506. METHODDEF(boolean) decode_mcu_AC_first JPP((j_decompress_ptr cinfo,
  169507. JBLOCKROW *MCU_data));
  169508. METHODDEF(boolean) decode_mcu_DC_refine JPP((j_decompress_ptr cinfo,
  169509. JBLOCKROW *MCU_data));
  169510. METHODDEF(boolean) decode_mcu_AC_refine JPP((j_decompress_ptr cinfo,
  169511. JBLOCKROW *MCU_data));
  169512. /*
  169513. * Initialize for a Huffman-compressed scan.
  169514. */
  169515. METHODDEF(void)
  169516. start_pass_phuff_decoder (j_decompress_ptr cinfo)
  169517. {
  169518. phuff_entropy_ptr2 entropy = (phuff_entropy_ptr2) cinfo->entropy;
  169519. boolean is_DC_band, bad;
  169520. int ci, coefi, tbl;
  169521. int *coef_bit_ptr;
  169522. jpeg_component_info * compptr;
  169523. is_DC_band = (cinfo->Ss == 0);
  169524. /* Validate scan parameters */
  169525. bad = FALSE;
  169526. if (is_DC_band) {
  169527. if (cinfo->Se != 0)
  169528. bad = TRUE;
  169529. } else {
  169530. /* need not check Ss/Se < 0 since they came from unsigned bytes */
  169531. if (cinfo->Ss > cinfo->Se || cinfo->Se >= DCTSIZE2)
  169532. bad = TRUE;
  169533. /* AC scans may have only one component */
  169534. if (cinfo->comps_in_scan != 1)
  169535. bad = TRUE;
  169536. }
  169537. if (cinfo->Ah != 0) {
  169538. /* Successive approximation refinement scan: must have Al = Ah-1. */
  169539. if (cinfo->Al != cinfo->Ah-1)
  169540. bad = TRUE;
  169541. }
  169542. if (cinfo->Al > 13) /* need not check for < 0 */
  169543. bad = TRUE;
  169544. /* Arguably the maximum Al value should be less than 13 for 8-bit precision,
  169545. * but the spec doesn't say so, and we try to be liberal about what we
  169546. * accept. Note: large Al values could result in out-of-range DC
  169547. * coefficients during early scans, leading to bizarre displays due to
  169548. * overflows in the IDCT math. But we won't crash.
  169549. */
  169550. if (bad)
  169551. ERREXIT4(cinfo, JERR_BAD_PROGRESSION,
  169552. cinfo->Ss, cinfo->Se, cinfo->Ah, cinfo->Al);
  169553. /* Update progression status, and verify that scan order is legal.
  169554. * Note that inter-scan inconsistencies are treated as warnings
  169555. * not fatal errors ... not clear if this is right way to behave.
  169556. */
  169557. for (ci = 0; ci < cinfo->comps_in_scan; ci++) {
  169558. int cindex = cinfo->cur_comp_info[ci]->component_index;
  169559. coef_bit_ptr = & cinfo->coef_bits[cindex][0];
  169560. if (!is_DC_band && coef_bit_ptr[0] < 0) /* AC without prior DC scan */
  169561. WARNMS2(cinfo, JWRN_BOGUS_PROGRESSION, cindex, 0);
  169562. for (coefi = cinfo->Ss; coefi <= cinfo->Se; coefi++) {
  169563. int expected = (coef_bit_ptr[coefi] < 0) ? 0 : coef_bit_ptr[coefi];
  169564. if (cinfo->Ah != expected)
  169565. WARNMS2(cinfo, JWRN_BOGUS_PROGRESSION, cindex, coefi);
  169566. coef_bit_ptr[coefi] = cinfo->Al;
  169567. }
  169568. }
  169569. /* Select MCU decoding routine */
  169570. if (cinfo->Ah == 0) {
  169571. if (is_DC_band)
  169572. entropy->pub.decode_mcu = decode_mcu_DC_first;
  169573. else
  169574. entropy->pub.decode_mcu = decode_mcu_AC_first;
  169575. } else {
  169576. if (is_DC_band)
  169577. entropy->pub.decode_mcu = decode_mcu_DC_refine;
  169578. else
  169579. entropy->pub.decode_mcu = decode_mcu_AC_refine;
  169580. }
  169581. for (ci = 0; ci < cinfo->comps_in_scan; ci++) {
  169582. compptr = cinfo->cur_comp_info[ci];
  169583. /* Make sure requested tables are present, and compute derived tables.
  169584. * We may build same derived table more than once, but it's not expensive.
  169585. */
  169586. if (is_DC_band) {
  169587. if (cinfo->Ah == 0) { /* DC refinement needs no table */
  169588. tbl = compptr->dc_tbl_no;
  169589. jpeg_make_d_derived_tbl(cinfo, TRUE, tbl,
  169590. & entropy->derived_tbls[tbl]);
  169591. }
  169592. } else {
  169593. tbl = compptr->ac_tbl_no;
  169594. jpeg_make_d_derived_tbl(cinfo, FALSE, tbl,
  169595. & entropy->derived_tbls[tbl]);
  169596. /* remember the single active table */
  169597. entropy->ac_derived_tbl = entropy->derived_tbls[tbl];
  169598. }
  169599. /* Initialize DC predictions to 0 */
  169600. entropy->saved.last_dc_val[ci] = 0;
  169601. }
  169602. /* Initialize bitread state variables */
  169603. entropy->bitstate.bits_left = 0;
  169604. entropy->bitstate.get_buffer = 0; /* unnecessary, but keeps Purify quiet */
  169605. entropy->pub.insufficient_data = FALSE;
  169606. /* Initialize private state variables */
  169607. entropy->saved.EOBRUN = 0;
  169608. /* Initialize restart counter */
  169609. entropy->restarts_to_go = cinfo->restart_interval;
  169610. }
  169611. /*
  169612. * Check for a restart marker & resynchronize decoder.
  169613. * Returns FALSE if must suspend.
  169614. */
  169615. LOCAL(boolean)
  169616. process_restartp (j_decompress_ptr cinfo)
  169617. {
  169618. phuff_entropy_ptr2 entropy = (phuff_entropy_ptr2) cinfo->entropy;
  169619. int ci;
  169620. /* Throw away any unused bits remaining in bit buffer; */
  169621. /* include any full bytes in next_marker's count of discarded bytes */
  169622. cinfo->marker->discarded_bytes += entropy->bitstate.bits_left / 8;
  169623. entropy->bitstate.bits_left = 0;
  169624. /* Advance past the RSTn marker */
  169625. if (! (*cinfo->marker->read_restart_marker) (cinfo))
  169626. return FALSE;
  169627. /* Re-initialize DC predictions to 0 */
  169628. for (ci = 0; ci < cinfo->comps_in_scan; ci++)
  169629. entropy->saved.last_dc_val[ci] = 0;
  169630. /* Re-init EOB run count, too */
  169631. entropy->saved.EOBRUN = 0;
  169632. /* Reset restart counter */
  169633. entropy->restarts_to_go = cinfo->restart_interval;
  169634. /* Reset out-of-data flag, unless read_restart_marker left us smack up
  169635. * against a marker. In that case we will end up treating the next data
  169636. * segment as empty, and we can avoid producing bogus output pixels by
  169637. * leaving the flag set.
  169638. */
  169639. if (cinfo->unread_marker == 0)
  169640. entropy->pub.insufficient_data = FALSE;
  169641. return TRUE;
  169642. }
  169643. /*
  169644. * Huffman MCU decoding.
  169645. * Each of these routines decodes and returns one MCU's worth of
  169646. * Huffman-compressed coefficients.
  169647. * The coefficients are reordered from zigzag order into natural array order,
  169648. * but are not dequantized.
  169649. *
  169650. * The i'th block of the MCU is stored into the block pointed to by
  169651. * MCU_data[i]. WE ASSUME THIS AREA IS INITIALLY ZEROED BY THE CALLER.
  169652. *
  169653. * We return FALSE if data source requested suspension. In that case no
  169654. * changes have been made to permanent state. (Exception: some output
  169655. * coefficients may already have been assigned. This is harmless for
  169656. * spectral selection, since we'll just re-assign them on the next call.
  169657. * Successive approximation AC refinement has to be more careful, however.)
  169658. */
  169659. /*
  169660. * MCU decoding for DC initial scan (either spectral selection,
  169661. * or first pass of successive approximation).
  169662. */
  169663. METHODDEF(boolean)
  169664. decode_mcu_DC_first (j_decompress_ptr cinfo, JBLOCKROW *MCU_data)
  169665. {
  169666. phuff_entropy_ptr2 entropy = (phuff_entropy_ptr2) cinfo->entropy;
  169667. int Al = cinfo->Al;
  169668. register int s, r;
  169669. int blkn, ci;
  169670. JBLOCKROW block;
  169671. BITREAD_STATE_VARS;
  169672. savable_state3 state;
  169673. d_derived_tbl * tbl;
  169674. jpeg_component_info * compptr;
  169675. /* Process restart marker if needed; may have to suspend */
  169676. if (cinfo->restart_interval) {
  169677. if (entropy->restarts_to_go == 0)
  169678. if (! process_restartp(cinfo))
  169679. return FALSE;
  169680. }
  169681. /* If we've run out of data, just leave the MCU set to zeroes.
  169682. * This way, we return uniform gray for the remainder of the segment.
  169683. */
  169684. if (! entropy->pub.insufficient_data) {
  169685. /* Load up working state */
  169686. BITREAD_LOAD_STATE(cinfo,entropy->bitstate);
  169687. ASSIGN_STATE(state, entropy->saved);
  169688. /* Outer loop handles each block in the MCU */
  169689. for (blkn = 0; blkn < cinfo->blocks_in_MCU; blkn++) {
  169690. block = MCU_data[blkn];
  169691. ci = cinfo->MCU_membership[blkn];
  169692. compptr = cinfo->cur_comp_info[ci];
  169693. tbl = entropy->derived_tbls[compptr->dc_tbl_no];
  169694. /* Decode a single block's worth of coefficients */
  169695. /* Section F.2.2.1: decode the DC coefficient difference */
  169696. HUFF_DECODE(s, br_state, tbl, return FALSE, label1);
  169697. if (s) {
  169698. CHECK_BIT_BUFFER(br_state, s, return FALSE);
  169699. r = GET_BITS(s);
  169700. s = HUFF_EXTEND(r, s);
  169701. }
  169702. /* Convert DC difference to actual value, update last_dc_val */
  169703. s += state.last_dc_val[ci];
  169704. state.last_dc_val[ci] = s;
  169705. /* Scale and output the coefficient (assumes jpeg_natural_order[0]=0) */
  169706. (*block)[0] = (JCOEF) (s << Al);
  169707. }
  169708. /* Completed MCU, so update state */
  169709. BITREAD_SAVE_STATE(cinfo,entropy->bitstate);
  169710. ASSIGN_STATE(entropy->saved, state);
  169711. }
  169712. /* Account for restart interval (no-op if not using restarts) */
  169713. entropy->restarts_to_go--;
  169714. return TRUE;
  169715. }
  169716. /*
  169717. * MCU decoding for AC initial scan (either spectral selection,
  169718. * or first pass of successive approximation).
  169719. */
  169720. METHODDEF(boolean)
  169721. decode_mcu_AC_first (j_decompress_ptr cinfo, JBLOCKROW *MCU_data)
  169722. {
  169723. phuff_entropy_ptr2 entropy = (phuff_entropy_ptr2) cinfo->entropy;
  169724. int Se = cinfo->Se;
  169725. int Al = cinfo->Al;
  169726. register int s, k, r;
  169727. unsigned int EOBRUN;
  169728. JBLOCKROW block;
  169729. BITREAD_STATE_VARS;
  169730. d_derived_tbl * tbl;
  169731. /* Process restart marker if needed; may have to suspend */
  169732. if (cinfo->restart_interval) {
  169733. if (entropy->restarts_to_go == 0)
  169734. if (! process_restartp(cinfo))
  169735. return FALSE;
  169736. }
  169737. /* If we've run out of data, just leave the MCU set to zeroes.
  169738. * This way, we return uniform gray for the remainder of the segment.
  169739. */
  169740. if (! entropy->pub.insufficient_data) {
  169741. /* Load up working state.
  169742. * We can avoid loading/saving bitread state if in an EOB run.
  169743. */
  169744. EOBRUN = entropy->saved.EOBRUN; /* only part of saved state we need */
  169745. /* There is always only one block per MCU */
  169746. if (EOBRUN > 0) /* if it's a band of zeroes... */
  169747. EOBRUN--; /* ...process it now (we do nothing) */
  169748. else {
  169749. BITREAD_LOAD_STATE(cinfo,entropy->bitstate);
  169750. block = MCU_data[0];
  169751. tbl = entropy->ac_derived_tbl;
  169752. for (k = cinfo->Ss; k <= Se; k++) {
  169753. HUFF_DECODE(s, br_state, tbl, return FALSE, label2);
  169754. r = s >> 4;
  169755. s &= 15;
  169756. if (s) {
  169757. k += r;
  169758. CHECK_BIT_BUFFER(br_state, s, return FALSE);
  169759. r = GET_BITS(s);
  169760. s = HUFF_EXTEND(r, s);
  169761. /* Scale and output coefficient in natural (dezigzagged) order */
  169762. (*block)[jpeg_natural_order[k]] = (JCOEF) (s << Al);
  169763. } else {
  169764. if (r == 15) { /* ZRL */
  169765. k += 15; /* skip 15 zeroes in band */
  169766. } else { /* EOBr, run length is 2^r + appended bits */
  169767. EOBRUN = 1 << r;
  169768. if (r) { /* EOBr, r > 0 */
  169769. CHECK_BIT_BUFFER(br_state, r, return FALSE);
  169770. r = GET_BITS(r);
  169771. EOBRUN += r;
  169772. }
  169773. EOBRUN--; /* this band is processed at this moment */
  169774. break; /* force end-of-band */
  169775. }
  169776. }
  169777. }
  169778. BITREAD_SAVE_STATE(cinfo,entropy->bitstate);
  169779. }
  169780. /* Completed MCU, so update state */
  169781. entropy->saved.EOBRUN = EOBRUN; /* only part of saved state we need */
  169782. }
  169783. /* Account for restart interval (no-op if not using restarts) */
  169784. entropy->restarts_to_go--;
  169785. return TRUE;
  169786. }
  169787. /*
  169788. * MCU decoding for DC successive approximation refinement scan.
  169789. * Note: we assume such scans can be multi-component, although the spec
  169790. * is not very clear on the point.
  169791. */
  169792. METHODDEF(boolean)
  169793. decode_mcu_DC_refine (j_decompress_ptr cinfo, JBLOCKROW *MCU_data)
  169794. {
  169795. phuff_entropy_ptr2 entropy = (phuff_entropy_ptr2) cinfo->entropy;
  169796. int p1 = 1 << cinfo->Al; /* 1 in the bit position being coded */
  169797. int blkn;
  169798. JBLOCKROW block;
  169799. BITREAD_STATE_VARS;
  169800. /* Process restart marker if needed; may have to suspend */
  169801. if (cinfo->restart_interval) {
  169802. if (entropy->restarts_to_go == 0)
  169803. if (! process_restartp(cinfo))
  169804. return FALSE;
  169805. }
  169806. /* Not worth the cycles to check insufficient_data here,
  169807. * since we will not change the data anyway if we read zeroes.
  169808. */
  169809. /* Load up working state */
  169810. BITREAD_LOAD_STATE(cinfo,entropy->bitstate);
  169811. /* Outer loop handles each block in the MCU */
  169812. for (blkn = 0; blkn < cinfo->blocks_in_MCU; blkn++) {
  169813. block = MCU_data[blkn];
  169814. /* Encoded data is simply the next bit of the two's-complement DC value */
  169815. CHECK_BIT_BUFFER(br_state, 1, return FALSE);
  169816. if (GET_BITS(1))
  169817. (*block)[0] |= p1;
  169818. /* Note: since we use |=, repeating the assignment later is safe */
  169819. }
  169820. /* Completed MCU, so update state */
  169821. BITREAD_SAVE_STATE(cinfo,entropy->bitstate);
  169822. /* Account for restart interval (no-op if not using restarts) */
  169823. entropy->restarts_to_go--;
  169824. return TRUE;
  169825. }
  169826. /*
  169827. * MCU decoding for AC successive approximation refinement scan.
  169828. */
  169829. METHODDEF(boolean)
  169830. decode_mcu_AC_refine (j_decompress_ptr cinfo, JBLOCKROW *MCU_data)
  169831. {
  169832. phuff_entropy_ptr2 entropy = (phuff_entropy_ptr2) cinfo->entropy;
  169833. int Se = cinfo->Se;
  169834. int p1 = 1 << cinfo->Al; /* 1 in the bit position being coded */
  169835. int m1 = (-1) << cinfo->Al; /* -1 in the bit position being coded */
  169836. register int s, k, r;
  169837. unsigned int EOBRUN;
  169838. JBLOCKROW block;
  169839. JCOEFPTR thiscoef;
  169840. BITREAD_STATE_VARS;
  169841. d_derived_tbl * tbl;
  169842. int num_newnz;
  169843. int newnz_pos[DCTSIZE2];
  169844. /* Process restart marker if needed; may have to suspend */
  169845. if (cinfo->restart_interval) {
  169846. if (entropy->restarts_to_go == 0)
  169847. if (! process_restartp(cinfo))
  169848. return FALSE;
  169849. }
  169850. /* If we've run out of data, don't modify the MCU.
  169851. */
  169852. if (! entropy->pub.insufficient_data) {
  169853. /* Load up working state */
  169854. BITREAD_LOAD_STATE(cinfo,entropy->bitstate);
  169855. EOBRUN = entropy->saved.EOBRUN; /* only part of saved state we need */
  169856. /* There is always only one block per MCU */
  169857. block = MCU_data[0];
  169858. tbl = entropy->ac_derived_tbl;
  169859. /* If we are forced to suspend, we must undo the assignments to any newly
  169860. * nonzero coefficients in the block, because otherwise we'd get confused
  169861. * next time about which coefficients were already nonzero.
  169862. * But we need not undo addition of bits to already-nonzero coefficients;
  169863. * instead, we can test the current bit to see if we already did it.
  169864. */
  169865. num_newnz = 0;
  169866. /* initialize coefficient loop counter to start of band */
  169867. k = cinfo->Ss;
  169868. if (EOBRUN == 0) {
  169869. for (; k <= Se; k++) {
  169870. HUFF_DECODE(s, br_state, tbl, goto undoit, label3);
  169871. r = s >> 4;
  169872. s &= 15;
  169873. if (s) {
  169874. if (s != 1) /* size of new coef should always be 1 */
  169875. WARNMS(cinfo, JWRN_HUFF_BAD_CODE);
  169876. CHECK_BIT_BUFFER(br_state, 1, goto undoit);
  169877. if (GET_BITS(1))
  169878. s = p1; /* newly nonzero coef is positive */
  169879. else
  169880. s = m1; /* newly nonzero coef is negative */
  169881. } else {
  169882. if (r != 15) {
  169883. EOBRUN = 1 << r; /* EOBr, run length is 2^r + appended bits */
  169884. if (r) {
  169885. CHECK_BIT_BUFFER(br_state, r, goto undoit);
  169886. r = GET_BITS(r);
  169887. EOBRUN += r;
  169888. }
  169889. break; /* rest of block is handled by EOB logic */
  169890. }
  169891. /* note s = 0 for processing ZRL */
  169892. }
  169893. /* Advance over already-nonzero coefs and r still-zero coefs,
  169894. * appending correction bits to the nonzeroes. A correction bit is 1
  169895. * if the absolute value of the coefficient must be increased.
  169896. */
  169897. do {
  169898. thiscoef = *block + jpeg_natural_order[k];
  169899. if (*thiscoef != 0) {
  169900. CHECK_BIT_BUFFER(br_state, 1, goto undoit);
  169901. if (GET_BITS(1)) {
  169902. if ((*thiscoef & p1) == 0) { /* do nothing if already set it */
  169903. if (*thiscoef >= 0)
  169904. *thiscoef += p1;
  169905. else
  169906. *thiscoef += m1;
  169907. }
  169908. }
  169909. } else {
  169910. if (--r < 0)
  169911. break; /* reached target zero coefficient */
  169912. }
  169913. k++;
  169914. } while (k <= Se);
  169915. if (s) {
  169916. int pos = jpeg_natural_order[k];
  169917. /* Output newly nonzero coefficient */
  169918. (*block)[pos] = (JCOEF) s;
  169919. /* Remember its position in case we have to suspend */
  169920. newnz_pos[num_newnz++] = pos;
  169921. }
  169922. }
  169923. }
  169924. if (EOBRUN > 0) {
  169925. /* Scan any remaining coefficient positions after the end-of-band
  169926. * (the last newly nonzero coefficient, if any). Append a correction
  169927. * bit to each already-nonzero coefficient. A correction bit is 1
  169928. * if the absolute value of the coefficient must be increased.
  169929. */
  169930. for (; k <= Se; k++) {
  169931. thiscoef = *block + jpeg_natural_order[k];
  169932. if (*thiscoef != 0) {
  169933. CHECK_BIT_BUFFER(br_state, 1, goto undoit);
  169934. if (GET_BITS(1)) {
  169935. if ((*thiscoef & p1) == 0) { /* do nothing if already changed it */
  169936. if (*thiscoef >= 0)
  169937. *thiscoef += p1;
  169938. else
  169939. *thiscoef += m1;
  169940. }
  169941. }
  169942. }
  169943. }
  169944. /* Count one block completed in EOB run */
  169945. EOBRUN--;
  169946. }
  169947. /* Completed MCU, so update state */
  169948. BITREAD_SAVE_STATE(cinfo,entropy->bitstate);
  169949. entropy->saved.EOBRUN = EOBRUN; /* only part of saved state we need */
  169950. }
  169951. /* Account for restart interval (no-op if not using restarts) */
  169952. entropy->restarts_to_go--;
  169953. return TRUE;
  169954. undoit:
  169955. /* Re-zero any output coefficients that we made newly nonzero */
  169956. while (num_newnz > 0)
  169957. (*block)[newnz_pos[--num_newnz]] = 0;
  169958. return FALSE;
  169959. }
  169960. /*
  169961. * Module initialization routine for progressive Huffman entropy decoding.
  169962. */
  169963. GLOBAL(void)
  169964. jinit_phuff_decoder (j_decompress_ptr cinfo)
  169965. {
  169966. phuff_entropy_ptr2 entropy;
  169967. int *coef_bit_ptr;
  169968. int ci, i;
  169969. entropy = (phuff_entropy_ptr2)
  169970. (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_IMAGE,
  169971. SIZEOF(phuff_entropy_decoder));
  169972. cinfo->entropy = (struct jpeg_entropy_decoder *) entropy;
  169973. entropy->pub.start_pass = start_pass_phuff_decoder;
  169974. /* Mark derived tables unallocated */
  169975. for (i = 0; i < NUM_HUFF_TBLS; i++) {
  169976. entropy->derived_tbls[i] = NULL;
  169977. }
  169978. /* Create progression status table */
  169979. cinfo->coef_bits = (int (*)[DCTSIZE2])
  169980. (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_IMAGE,
  169981. cinfo->num_components*DCTSIZE2*SIZEOF(int));
  169982. coef_bit_ptr = & cinfo->coef_bits[0][0];
  169983. for (ci = 0; ci < cinfo->num_components; ci++)
  169984. for (i = 0; i < DCTSIZE2; i++)
  169985. *coef_bit_ptr++ = -1;
  169986. }
  169987. #endif /* D_PROGRESSIVE_SUPPORTED */
  169988. /*** End of inlined file: jdphuff.c ***/
  169989. /*** Start of inlined file: jdpostct.c ***/
  169990. #define JPEG_INTERNALS
  169991. /* Private buffer controller object */
  169992. typedef struct {
  169993. struct jpeg_d_post_controller pub; /* public fields */
  169994. /* Color quantization source buffer: this holds output data from
  169995. * the upsample/color conversion step to be passed to the quantizer.
  169996. * For two-pass color quantization, we need a full-image buffer;
  169997. * for one-pass operation, a strip buffer is sufficient.
  169998. */
  169999. jvirt_sarray_ptr whole_image; /* virtual array, or NULL if one-pass */
  170000. JSAMPARRAY buffer; /* strip buffer, or current strip of virtual */
  170001. JDIMENSION strip_height; /* buffer size in rows */
  170002. /* for two-pass mode only: */
  170003. JDIMENSION starting_row; /* row # of first row in current strip */
  170004. JDIMENSION next_row; /* index of next row to fill/empty in strip */
  170005. } my_post_controller;
  170006. typedef my_post_controller * my_post_ptr;
  170007. /* Forward declarations */
  170008. METHODDEF(void) post_process_1pass
  170009. JPP((j_decompress_ptr cinfo,
  170010. JSAMPIMAGE input_buf, JDIMENSION *in_row_group_ctr,
  170011. JDIMENSION in_row_groups_avail,
  170012. JSAMPARRAY output_buf, JDIMENSION *out_row_ctr,
  170013. JDIMENSION out_rows_avail));
  170014. #ifdef QUANT_2PASS_SUPPORTED
  170015. METHODDEF(void) post_process_prepass
  170016. JPP((j_decompress_ptr cinfo,
  170017. JSAMPIMAGE input_buf, JDIMENSION *in_row_group_ctr,
  170018. JDIMENSION in_row_groups_avail,
  170019. JSAMPARRAY output_buf, JDIMENSION *out_row_ctr,
  170020. JDIMENSION out_rows_avail));
  170021. METHODDEF(void) post_process_2pass
  170022. JPP((j_decompress_ptr cinfo,
  170023. JSAMPIMAGE input_buf, JDIMENSION *in_row_group_ctr,
  170024. JDIMENSION in_row_groups_avail,
  170025. JSAMPARRAY output_buf, JDIMENSION *out_row_ctr,
  170026. JDIMENSION out_rows_avail));
  170027. #endif
  170028. /*
  170029. * Initialize for a processing pass.
  170030. */
  170031. METHODDEF(void)
  170032. start_pass_dpost (j_decompress_ptr cinfo, J_BUF_MODE pass_mode)
  170033. {
  170034. my_post_ptr post = (my_post_ptr) cinfo->post;
  170035. switch (pass_mode) {
  170036. case JBUF_PASS_THRU:
  170037. if (cinfo->quantize_colors) {
  170038. /* Single-pass processing with color quantization. */
  170039. post->pub.post_process_data = post_process_1pass;
  170040. /* We could be doing buffered-image output before starting a 2-pass
  170041. * color quantization; in that case, jinit_d_post_controller did not
  170042. * allocate a strip buffer. Use the virtual-array buffer as workspace.
  170043. */
  170044. if (post->buffer == NULL) {
  170045. post->buffer = (*cinfo->mem->access_virt_sarray)
  170046. ((j_common_ptr) cinfo, post->whole_image,
  170047. (JDIMENSION) 0, post->strip_height, TRUE);
  170048. }
  170049. } else {
  170050. /* For single-pass processing without color quantization,
  170051. * I have no work to do; just call the upsampler directly.
  170052. */
  170053. post->pub.post_process_data = cinfo->upsample->upsample;
  170054. }
  170055. break;
  170056. #ifdef QUANT_2PASS_SUPPORTED
  170057. case JBUF_SAVE_AND_PASS:
  170058. /* First pass of 2-pass quantization */
  170059. if (post->whole_image == NULL)
  170060. ERREXIT(cinfo, JERR_BAD_BUFFER_MODE);
  170061. post->pub.post_process_data = post_process_prepass;
  170062. break;
  170063. case JBUF_CRANK_DEST:
  170064. /* Second pass of 2-pass quantization */
  170065. if (post->whole_image == NULL)
  170066. ERREXIT(cinfo, JERR_BAD_BUFFER_MODE);
  170067. post->pub.post_process_data = post_process_2pass;
  170068. break;
  170069. #endif /* QUANT_2PASS_SUPPORTED */
  170070. default:
  170071. ERREXIT(cinfo, JERR_BAD_BUFFER_MODE);
  170072. break;
  170073. }
  170074. post->starting_row = post->next_row = 0;
  170075. }
  170076. /*
  170077. * Process some data in the one-pass (strip buffer) case.
  170078. * This is used for color precision reduction as well as one-pass quantization.
  170079. */
  170080. METHODDEF(void)
  170081. post_process_1pass (j_decompress_ptr cinfo,
  170082. JSAMPIMAGE input_buf, JDIMENSION *in_row_group_ctr,
  170083. JDIMENSION in_row_groups_avail,
  170084. JSAMPARRAY output_buf, JDIMENSION *out_row_ctr,
  170085. JDIMENSION out_rows_avail)
  170086. {
  170087. my_post_ptr post = (my_post_ptr) cinfo->post;
  170088. JDIMENSION num_rows, max_rows;
  170089. /* Fill the buffer, but not more than what we can dump out in one go. */
  170090. /* Note we rely on the upsampler to detect bottom of image. */
  170091. max_rows = out_rows_avail - *out_row_ctr;
  170092. if (max_rows > post->strip_height)
  170093. max_rows = post->strip_height;
  170094. num_rows = 0;
  170095. (*cinfo->upsample->upsample) (cinfo,
  170096. input_buf, in_row_group_ctr, in_row_groups_avail,
  170097. post->buffer, &num_rows, max_rows);
  170098. /* Quantize and emit data. */
  170099. (*cinfo->cquantize->color_quantize) (cinfo,
  170100. post->buffer, output_buf + *out_row_ctr, (int) num_rows);
  170101. *out_row_ctr += num_rows;
  170102. }
  170103. #ifdef QUANT_2PASS_SUPPORTED
  170104. /*
  170105. * Process some data in the first pass of 2-pass quantization.
  170106. */
  170107. METHODDEF(void)
  170108. post_process_prepass (j_decompress_ptr cinfo,
  170109. JSAMPIMAGE input_buf, JDIMENSION *in_row_group_ctr,
  170110. JDIMENSION in_row_groups_avail,
  170111. JSAMPARRAY output_buf, JDIMENSION *out_row_ctr,
  170112. JDIMENSION out_rows_avail)
  170113. {
  170114. my_post_ptr post = (my_post_ptr) cinfo->post;
  170115. JDIMENSION old_next_row, num_rows;
  170116. /* Reposition virtual buffer if at start of strip. */
  170117. if (post->next_row == 0) {
  170118. post->buffer = (*cinfo->mem->access_virt_sarray)
  170119. ((j_common_ptr) cinfo, post->whole_image,
  170120. post->starting_row, post->strip_height, TRUE);
  170121. }
  170122. /* Upsample some data (up to a strip height's worth). */
  170123. old_next_row = post->next_row;
  170124. (*cinfo->upsample->upsample) (cinfo,
  170125. input_buf, in_row_group_ctr, in_row_groups_avail,
  170126. post->buffer, &post->next_row, post->strip_height);
  170127. /* Allow quantizer to scan new data. No data is emitted, */
  170128. /* but we advance out_row_ctr so outer loop can tell when we're done. */
  170129. if (post->next_row > old_next_row) {
  170130. num_rows = post->next_row - old_next_row;
  170131. (*cinfo->cquantize->color_quantize) (cinfo, post->buffer + old_next_row,
  170132. (JSAMPARRAY) NULL, (int) num_rows);
  170133. *out_row_ctr += num_rows;
  170134. }
  170135. /* Advance if we filled the strip. */
  170136. if (post->next_row >= post->strip_height) {
  170137. post->starting_row += post->strip_height;
  170138. post->next_row = 0;
  170139. }
  170140. }
  170141. /*
  170142. * Process some data in the second pass of 2-pass quantization.
  170143. */
  170144. METHODDEF(void)
  170145. post_process_2pass (j_decompress_ptr cinfo,
  170146. JSAMPIMAGE input_buf, JDIMENSION *in_row_group_ctr,
  170147. JDIMENSION in_row_groups_avail,
  170148. JSAMPARRAY output_buf, JDIMENSION *out_row_ctr,
  170149. JDIMENSION out_rows_avail)
  170150. {
  170151. my_post_ptr post = (my_post_ptr) cinfo->post;
  170152. JDIMENSION num_rows, max_rows;
  170153. /* Reposition virtual buffer if at start of strip. */
  170154. if (post->next_row == 0) {
  170155. post->buffer = (*cinfo->mem->access_virt_sarray)
  170156. ((j_common_ptr) cinfo, post->whole_image,
  170157. post->starting_row, post->strip_height, FALSE);
  170158. }
  170159. /* Determine number of rows to emit. */
  170160. num_rows = post->strip_height - post->next_row; /* available in strip */
  170161. max_rows = out_rows_avail - *out_row_ctr; /* available in output area */
  170162. if (num_rows > max_rows)
  170163. num_rows = max_rows;
  170164. /* We have to check bottom of image here, can't depend on upsampler. */
  170165. max_rows = cinfo->output_height - post->starting_row;
  170166. if (num_rows > max_rows)
  170167. num_rows = max_rows;
  170168. /* Quantize and emit data. */
  170169. (*cinfo->cquantize->color_quantize) (cinfo,
  170170. post->buffer + post->next_row, output_buf + *out_row_ctr,
  170171. (int) num_rows);
  170172. *out_row_ctr += num_rows;
  170173. /* Advance if we filled the strip. */
  170174. post->next_row += num_rows;
  170175. if (post->next_row >= post->strip_height) {
  170176. post->starting_row += post->strip_height;
  170177. post->next_row = 0;
  170178. }
  170179. }
  170180. #endif /* QUANT_2PASS_SUPPORTED */
  170181. /*
  170182. * Initialize postprocessing controller.
  170183. */
  170184. GLOBAL(void)
  170185. jinit_d_post_controller (j_decompress_ptr cinfo, boolean need_full_buffer)
  170186. {
  170187. my_post_ptr post;
  170188. post = (my_post_ptr)
  170189. (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_IMAGE,
  170190. SIZEOF(my_post_controller));
  170191. cinfo->post = (struct jpeg_d_post_controller *) post;
  170192. post->pub.start_pass = start_pass_dpost;
  170193. post->whole_image = NULL; /* flag for no virtual arrays */
  170194. post->buffer = NULL; /* flag for no strip buffer */
  170195. /* Create the quantization buffer, if needed */
  170196. if (cinfo->quantize_colors) {
  170197. /* The buffer strip height is max_v_samp_factor, which is typically
  170198. * an efficient number of rows for upsampling to return.
  170199. * (In the presence of output rescaling, we might want to be smarter?)
  170200. */
  170201. post->strip_height = (JDIMENSION) cinfo->max_v_samp_factor;
  170202. if (need_full_buffer) {
  170203. /* Two-pass color quantization: need full-image storage. */
  170204. /* We round up the number of rows to a multiple of the strip height. */
  170205. #ifdef QUANT_2PASS_SUPPORTED
  170206. post->whole_image = (*cinfo->mem->request_virt_sarray)
  170207. ((j_common_ptr) cinfo, JPOOL_IMAGE, FALSE,
  170208. cinfo->output_width * cinfo->out_color_components,
  170209. (JDIMENSION) jround_up((long) cinfo->output_height,
  170210. (long) post->strip_height),
  170211. post->strip_height);
  170212. #else
  170213. ERREXIT(cinfo, JERR_BAD_BUFFER_MODE);
  170214. #endif /* QUANT_2PASS_SUPPORTED */
  170215. } else {
  170216. /* One-pass color quantization: just make a strip buffer. */
  170217. post->buffer = (*cinfo->mem->alloc_sarray)
  170218. ((j_common_ptr) cinfo, JPOOL_IMAGE,
  170219. cinfo->output_width * cinfo->out_color_components,
  170220. post->strip_height);
  170221. }
  170222. }
  170223. }
  170224. /*** End of inlined file: jdpostct.c ***/
  170225. #undef FIX
  170226. /*** Start of inlined file: jdsample.c ***/
  170227. #define JPEG_INTERNALS
  170228. /* Pointer to routine to upsample a single component */
  170229. typedef JMETHOD(void, upsample1_ptr,
  170230. (j_decompress_ptr cinfo, jpeg_component_info * compptr,
  170231. JSAMPARRAY input_data, JSAMPARRAY * output_data_ptr));
  170232. /* Private subobject */
  170233. typedef struct {
  170234. struct jpeg_upsampler pub; /* public fields */
  170235. /* Color conversion buffer. When using separate upsampling and color
  170236. * conversion steps, this buffer holds one upsampled row group until it
  170237. * has been color converted and output.
  170238. * Note: we do not allocate any storage for component(s) which are full-size,
  170239. * ie do not need rescaling. The corresponding entry of color_buf[] is
  170240. * simply set to point to the input data array, thereby avoiding copying.
  170241. */
  170242. JSAMPARRAY color_buf[MAX_COMPONENTS];
  170243. /* Per-component upsampling method pointers */
  170244. upsample1_ptr methods[MAX_COMPONENTS];
  170245. int next_row_out; /* counts rows emitted from color_buf */
  170246. JDIMENSION rows_to_go; /* counts rows remaining in image */
  170247. /* Height of an input row group for each component. */
  170248. int rowgroup_height[MAX_COMPONENTS];
  170249. /* These arrays save pixel expansion factors so that int_expand need not
  170250. * recompute them each time. They are unused for other upsampling methods.
  170251. */
  170252. UINT8 h_expand[MAX_COMPONENTS];
  170253. UINT8 v_expand[MAX_COMPONENTS];
  170254. } my_upsampler2;
  170255. typedef my_upsampler2 * my_upsample_ptr2;
  170256. /*
  170257. * Initialize for an upsampling pass.
  170258. */
  170259. METHODDEF(void)
  170260. start_pass_upsample (j_decompress_ptr cinfo)
  170261. {
  170262. my_upsample_ptr2 upsample = (my_upsample_ptr2) cinfo->upsample;
  170263. /* Mark the conversion buffer empty */
  170264. upsample->next_row_out = cinfo->max_v_samp_factor;
  170265. /* Initialize total-height counter for detecting bottom of image */
  170266. upsample->rows_to_go = cinfo->output_height;
  170267. }
  170268. /*
  170269. * Control routine to do upsampling (and color conversion).
  170270. *
  170271. * In this version we upsample each component independently.
  170272. * We upsample one row group into the conversion buffer, then apply
  170273. * color conversion a row at a time.
  170274. */
  170275. METHODDEF(void)
  170276. sep_upsample (j_decompress_ptr cinfo,
  170277. JSAMPIMAGE input_buf, JDIMENSION *in_row_group_ctr,
  170278. JDIMENSION in_row_groups_avail,
  170279. JSAMPARRAY output_buf, JDIMENSION *out_row_ctr,
  170280. JDIMENSION out_rows_avail)
  170281. {
  170282. my_upsample_ptr2 upsample = (my_upsample_ptr2) cinfo->upsample;
  170283. int ci;
  170284. jpeg_component_info * compptr;
  170285. JDIMENSION num_rows;
  170286. /* Fill the conversion buffer, if it's empty */
  170287. if (upsample->next_row_out >= cinfo->max_v_samp_factor) {
  170288. for (ci = 0, compptr = cinfo->comp_info; ci < cinfo->num_components;
  170289. ci++, compptr++) {
  170290. /* Invoke per-component upsample method. Notice we pass a POINTER
  170291. * to color_buf[ci], so that fullsize_upsample can change it.
  170292. */
  170293. (*upsample->methods[ci]) (cinfo, compptr,
  170294. input_buf[ci] + (*in_row_group_ctr * upsample->rowgroup_height[ci]),
  170295. upsample->color_buf + ci);
  170296. }
  170297. upsample->next_row_out = 0;
  170298. }
  170299. /* Color-convert and emit rows */
  170300. /* How many we have in the buffer: */
  170301. num_rows = (JDIMENSION) (cinfo->max_v_samp_factor - upsample->next_row_out);
  170302. /* Not more than the distance to the end of the image. Need this test
  170303. * in case the image height is not a multiple of max_v_samp_factor:
  170304. */
  170305. if (num_rows > upsample->rows_to_go)
  170306. num_rows = upsample->rows_to_go;
  170307. /* And not more than what the client can accept: */
  170308. out_rows_avail -= *out_row_ctr;
  170309. if (num_rows > out_rows_avail)
  170310. num_rows = out_rows_avail;
  170311. (*cinfo->cconvert->color_convert) (cinfo, upsample->color_buf,
  170312. (JDIMENSION) upsample->next_row_out,
  170313. output_buf + *out_row_ctr,
  170314. (int) num_rows);
  170315. /* Adjust counts */
  170316. *out_row_ctr += num_rows;
  170317. upsample->rows_to_go -= num_rows;
  170318. upsample->next_row_out += num_rows;
  170319. /* When the buffer is emptied, declare this input row group consumed */
  170320. if (upsample->next_row_out >= cinfo->max_v_samp_factor)
  170321. (*in_row_group_ctr)++;
  170322. }
  170323. /*
  170324. * These are the routines invoked by sep_upsample to upsample pixel values
  170325. * of a single component. One row group is processed per call.
  170326. */
  170327. /*
  170328. * For full-size components, we just make color_buf[ci] point at the
  170329. * input buffer, and thus avoid copying any data. Note that this is
  170330. * safe only because sep_upsample doesn't declare the input row group
  170331. * "consumed" until we are done color converting and emitting it.
  170332. */
  170333. METHODDEF(void)
  170334. fullsize_upsample (j_decompress_ptr cinfo, jpeg_component_info * compptr,
  170335. JSAMPARRAY input_data, JSAMPARRAY * output_data_ptr)
  170336. {
  170337. *output_data_ptr = input_data;
  170338. }
  170339. /*
  170340. * This is a no-op version used for "uninteresting" components.
  170341. * These components will not be referenced by color conversion.
  170342. */
  170343. METHODDEF(void)
  170344. noop_upsample (j_decompress_ptr cinfo, jpeg_component_info * compptr,
  170345. JSAMPARRAY input_data, JSAMPARRAY * output_data_ptr)
  170346. {
  170347. *output_data_ptr = NULL; /* safety check */
  170348. }
  170349. /*
  170350. * This version handles any integral sampling ratios.
  170351. * This is not used for typical JPEG files, so it need not be fast.
  170352. * Nor, for that matter, is it particularly accurate: the algorithm is
  170353. * simple replication of the input pixel onto the corresponding output
  170354. * pixels. The hi-falutin sampling literature refers to this as a
  170355. * "box filter". A box filter tends to introduce visible artifacts,
  170356. * so if you are actually going to use 3:1 or 4:1 sampling ratios
  170357. * you would be well advised to improve this code.
  170358. */
  170359. METHODDEF(void)
  170360. int_upsample (j_decompress_ptr cinfo, jpeg_component_info * compptr,
  170361. JSAMPARRAY input_data, JSAMPARRAY * output_data_ptr)
  170362. {
  170363. my_upsample_ptr2 upsample = (my_upsample_ptr2) cinfo->upsample;
  170364. JSAMPARRAY output_data = *output_data_ptr;
  170365. register JSAMPROW inptr, outptr;
  170366. register JSAMPLE invalue;
  170367. register int h;
  170368. JSAMPROW outend;
  170369. int h_expand, v_expand;
  170370. int inrow, outrow;
  170371. h_expand = upsample->h_expand[compptr->component_index];
  170372. v_expand = upsample->v_expand[compptr->component_index];
  170373. inrow = outrow = 0;
  170374. while (outrow < cinfo->max_v_samp_factor) {
  170375. /* Generate one output row with proper horizontal expansion */
  170376. inptr = input_data[inrow];
  170377. outptr = output_data[outrow];
  170378. outend = outptr + cinfo->output_width;
  170379. while (outptr < outend) {
  170380. invalue = *inptr++; /* don't need GETJSAMPLE() here */
  170381. for (h = h_expand; h > 0; h--) {
  170382. *outptr++ = invalue;
  170383. }
  170384. }
  170385. /* Generate any additional output rows by duplicating the first one */
  170386. if (v_expand > 1) {
  170387. jcopy_sample_rows(output_data, outrow, output_data, outrow+1,
  170388. v_expand-1, cinfo->output_width);
  170389. }
  170390. inrow++;
  170391. outrow += v_expand;
  170392. }
  170393. }
  170394. /*
  170395. * Fast processing for the common case of 2:1 horizontal and 1:1 vertical.
  170396. * It's still a box filter.
  170397. */
  170398. METHODDEF(void)
  170399. h2v1_upsample (j_decompress_ptr cinfo, jpeg_component_info * compptr,
  170400. JSAMPARRAY input_data, JSAMPARRAY * output_data_ptr)
  170401. {
  170402. JSAMPARRAY output_data = *output_data_ptr;
  170403. register JSAMPROW inptr, outptr;
  170404. register JSAMPLE invalue;
  170405. JSAMPROW outend;
  170406. int inrow;
  170407. for (inrow = 0; inrow < cinfo->max_v_samp_factor; inrow++) {
  170408. inptr = input_data[inrow];
  170409. outptr = output_data[inrow];
  170410. outend = outptr + cinfo->output_width;
  170411. while (outptr < outend) {
  170412. invalue = *inptr++; /* don't need GETJSAMPLE() here */
  170413. *outptr++ = invalue;
  170414. *outptr++ = invalue;
  170415. }
  170416. }
  170417. }
  170418. /*
  170419. * Fast processing for the common case of 2:1 horizontal and 2:1 vertical.
  170420. * It's still a box filter.
  170421. */
  170422. METHODDEF(void)
  170423. h2v2_upsample (j_decompress_ptr cinfo, jpeg_component_info * compptr,
  170424. JSAMPARRAY input_data, JSAMPARRAY * output_data_ptr)
  170425. {
  170426. JSAMPARRAY output_data = *output_data_ptr;
  170427. register JSAMPROW inptr, outptr;
  170428. register JSAMPLE invalue;
  170429. JSAMPROW outend;
  170430. int inrow, outrow;
  170431. inrow = outrow = 0;
  170432. while (outrow < cinfo->max_v_samp_factor) {
  170433. inptr = input_data[inrow];
  170434. outptr = output_data[outrow];
  170435. outend = outptr + cinfo->output_width;
  170436. while (outptr < outend) {
  170437. invalue = *inptr++; /* don't need GETJSAMPLE() here */
  170438. *outptr++ = invalue;
  170439. *outptr++ = invalue;
  170440. }
  170441. jcopy_sample_rows(output_data, outrow, output_data, outrow+1,
  170442. 1, cinfo->output_width);
  170443. inrow++;
  170444. outrow += 2;
  170445. }
  170446. }
  170447. /*
  170448. * Fancy processing for the common case of 2:1 horizontal and 1:1 vertical.
  170449. *
  170450. * The upsampling algorithm is linear interpolation between pixel centers,
  170451. * also known as a "triangle filter". This is a good compromise between
  170452. * speed and visual quality. The centers of the output pixels are 1/4 and 3/4
  170453. * of the way between input pixel centers.
  170454. *
  170455. * A note about the "bias" calculations: when rounding fractional values to
  170456. * integer, we do not want to always round 0.5 up to the next integer.
  170457. * If we did that, we'd introduce a noticeable bias towards larger values.
  170458. * Instead, this code is arranged so that 0.5 will be rounded up or down at
  170459. * alternate pixel locations (a simple ordered dither pattern).
  170460. */
  170461. METHODDEF(void)
  170462. h2v1_fancy_upsample (j_decompress_ptr cinfo, jpeg_component_info * compptr,
  170463. JSAMPARRAY input_data, JSAMPARRAY * output_data_ptr)
  170464. {
  170465. JSAMPARRAY output_data = *output_data_ptr;
  170466. register JSAMPROW inptr, outptr;
  170467. register int invalue;
  170468. register JDIMENSION colctr;
  170469. int inrow;
  170470. for (inrow = 0; inrow < cinfo->max_v_samp_factor; inrow++) {
  170471. inptr = input_data[inrow];
  170472. outptr = output_data[inrow];
  170473. /* Special case for first column */
  170474. invalue = GETJSAMPLE(*inptr++);
  170475. *outptr++ = (JSAMPLE) invalue;
  170476. *outptr++ = (JSAMPLE) ((invalue * 3 + GETJSAMPLE(*inptr) + 2) >> 2);
  170477. for (colctr = compptr->downsampled_width - 2; colctr > 0; colctr--) {
  170478. /* General case: 3/4 * nearer pixel + 1/4 * further pixel */
  170479. invalue = GETJSAMPLE(*inptr++) * 3;
  170480. *outptr++ = (JSAMPLE) ((invalue + GETJSAMPLE(inptr[-2]) + 1) >> 2);
  170481. *outptr++ = (JSAMPLE) ((invalue + GETJSAMPLE(*inptr) + 2) >> 2);
  170482. }
  170483. /* Special case for last column */
  170484. invalue = GETJSAMPLE(*inptr);
  170485. *outptr++ = (JSAMPLE) ((invalue * 3 + GETJSAMPLE(inptr[-1]) + 1) >> 2);
  170486. *outptr++ = (JSAMPLE) invalue;
  170487. }
  170488. }
  170489. /*
  170490. * Fancy processing for the common case of 2:1 horizontal and 2:1 vertical.
  170491. * Again a triangle filter; see comments for h2v1 case, above.
  170492. *
  170493. * It is OK for us to reference the adjacent input rows because we demanded
  170494. * context from the main buffer controller (see initialization code).
  170495. */
  170496. METHODDEF(void)
  170497. h2v2_fancy_upsample (j_decompress_ptr cinfo, jpeg_component_info * compptr,
  170498. JSAMPARRAY input_data, JSAMPARRAY * output_data_ptr)
  170499. {
  170500. JSAMPARRAY output_data = *output_data_ptr;
  170501. register JSAMPROW inptr0, inptr1, outptr;
  170502. #if BITS_IN_JSAMPLE == 8
  170503. register int thiscolsum, lastcolsum, nextcolsum;
  170504. #else
  170505. register INT32 thiscolsum, lastcolsum, nextcolsum;
  170506. #endif
  170507. register JDIMENSION colctr;
  170508. int inrow, outrow, v;
  170509. inrow = outrow = 0;
  170510. while (outrow < cinfo->max_v_samp_factor) {
  170511. for (v = 0; v < 2; v++) {
  170512. /* inptr0 points to nearest input row, inptr1 points to next nearest */
  170513. inptr0 = input_data[inrow];
  170514. if (v == 0) /* next nearest is row above */
  170515. inptr1 = input_data[inrow-1];
  170516. else /* next nearest is row below */
  170517. inptr1 = input_data[inrow+1];
  170518. outptr = output_data[outrow++];
  170519. /* Special case for first column */
  170520. thiscolsum = GETJSAMPLE(*inptr0++) * 3 + GETJSAMPLE(*inptr1++);
  170521. nextcolsum = GETJSAMPLE(*inptr0++) * 3 + GETJSAMPLE(*inptr1++);
  170522. *outptr++ = (JSAMPLE) ((thiscolsum * 4 + 8) >> 4);
  170523. *outptr++ = (JSAMPLE) ((thiscolsum * 3 + nextcolsum + 7) >> 4);
  170524. lastcolsum = thiscolsum; thiscolsum = nextcolsum;
  170525. for (colctr = compptr->downsampled_width - 2; colctr > 0; colctr--) {
  170526. /* General case: 3/4 * nearer pixel + 1/4 * further pixel in each */
  170527. /* dimension, thus 9/16, 3/16, 3/16, 1/16 overall */
  170528. nextcolsum = GETJSAMPLE(*inptr0++) * 3 + GETJSAMPLE(*inptr1++);
  170529. *outptr++ = (JSAMPLE) ((thiscolsum * 3 + lastcolsum + 8) >> 4);
  170530. *outptr++ = (JSAMPLE) ((thiscolsum * 3 + nextcolsum + 7) >> 4);
  170531. lastcolsum = thiscolsum; thiscolsum = nextcolsum;
  170532. }
  170533. /* Special case for last column */
  170534. *outptr++ = (JSAMPLE) ((thiscolsum * 3 + lastcolsum + 8) >> 4);
  170535. *outptr++ = (JSAMPLE) ((thiscolsum * 4 + 7) >> 4);
  170536. }
  170537. inrow++;
  170538. }
  170539. }
  170540. /*
  170541. * Module initialization routine for upsampling.
  170542. */
  170543. GLOBAL(void)
  170544. jinit_upsampler (j_decompress_ptr cinfo)
  170545. {
  170546. my_upsample_ptr2 upsample;
  170547. int ci;
  170548. jpeg_component_info * compptr;
  170549. boolean need_buffer, do_fancy;
  170550. int h_in_group, v_in_group, h_out_group, v_out_group;
  170551. upsample = (my_upsample_ptr2)
  170552. (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_IMAGE,
  170553. SIZEOF(my_upsampler2));
  170554. cinfo->upsample = (struct jpeg_upsampler *) upsample;
  170555. upsample->pub.start_pass = start_pass_upsample;
  170556. upsample->pub.upsample = sep_upsample;
  170557. upsample->pub.need_context_rows = FALSE; /* until we find out differently */
  170558. if (cinfo->CCIR601_sampling) /* this isn't supported */
  170559. ERREXIT(cinfo, JERR_CCIR601_NOTIMPL);
  170560. /* jdmainct.c doesn't support context rows when min_DCT_scaled_size = 1,
  170561. * so don't ask for it.
  170562. */
  170563. do_fancy = cinfo->do_fancy_upsampling && cinfo->min_DCT_scaled_size > 1;
  170564. /* Verify we can handle the sampling factors, select per-component methods,
  170565. * and create storage as needed.
  170566. */
  170567. for (ci = 0, compptr = cinfo->comp_info; ci < cinfo->num_components;
  170568. ci++, compptr++) {
  170569. /* Compute size of an "input group" after IDCT scaling. This many samples
  170570. * are to be converted to max_h_samp_factor * max_v_samp_factor pixels.
  170571. */
  170572. h_in_group = (compptr->h_samp_factor * compptr->DCT_scaled_size) /
  170573. cinfo->min_DCT_scaled_size;
  170574. v_in_group = (compptr->v_samp_factor * compptr->DCT_scaled_size) /
  170575. cinfo->min_DCT_scaled_size;
  170576. h_out_group = cinfo->max_h_samp_factor;
  170577. v_out_group = cinfo->max_v_samp_factor;
  170578. upsample->rowgroup_height[ci] = v_in_group; /* save for use later */
  170579. need_buffer = TRUE;
  170580. if (! compptr->component_needed) {
  170581. /* Don't bother to upsample an uninteresting component. */
  170582. upsample->methods[ci] = noop_upsample;
  170583. need_buffer = FALSE;
  170584. } else if (h_in_group == h_out_group && v_in_group == v_out_group) {
  170585. /* Fullsize components can be processed without any work. */
  170586. upsample->methods[ci] = fullsize_upsample;
  170587. need_buffer = FALSE;
  170588. } else if (h_in_group * 2 == h_out_group &&
  170589. v_in_group == v_out_group) {
  170590. /* Special cases for 2h1v upsampling */
  170591. if (do_fancy && compptr->downsampled_width > 2)
  170592. upsample->methods[ci] = h2v1_fancy_upsample;
  170593. else
  170594. upsample->methods[ci] = h2v1_upsample;
  170595. } else if (h_in_group * 2 == h_out_group &&
  170596. v_in_group * 2 == v_out_group) {
  170597. /* Special cases for 2h2v upsampling */
  170598. if (do_fancy && compptr->downsampled_width > 2) {
  170599. upsample->methods[ci] = h2v2_fancy_upsample;
  170600. upsample->pub.need_context_rows = TRUE;
  170601. } else
  170602. upsample->methods[ci] = h2v2_upsample;
  170603. } else if ((h_out_group % h_in_group) == 0 &&
  170604. (v_out_group % v_in_group) == 0) {
  170605. /* Generic integral-factors upsampling method */
  170606. upsample->methods[ci] = int_upsample;
  170607. upsample->h_expand[ci] = (UINT8) (h_out_group / h_in_group);
  170608. upsample->v_expand[ci] = (UINT8) (v_out_group / v_in_group);
  170609. } else
  170610. ERREXIT(cinfo, JERR_FRACT_SAMPLE_NOTIMPL);
  170611. if (need_buffer) {
  170612. upsample->color_buf[ci] = (*cinfo->mem->alloc_sarray)
  170613. ((j_common_ptr) cinfo, JPOOL_IMAGE,
  170614. (JDIMENSION) jround_up((long) cinfo->output_width,
  170615. (long) cinfo->max_h_samp_factor),
  170616. (JDIMENSION) cinfo->max_v_samp_factor);
  170617. }
  170618. }
  170619. }
  170620. /*** End of inlined file: jdsample.c ***/
  170621. /*** Start of inlined file: jdtrans.c ***/
  170622. #define JPEG_INTERNALS
  170623. /* Forward declarations */
  170624. LOCAL(void) transdecode_master_selection JPP((j_decompress_ptr cinfo));
  170625. /*
  170626. * Read the coefficient arrays from a JPEG file.
  170627. * jpeg_read_header must be completed before calling this.
  170628. *
  170629. * The entire image is read into a set of virtual coefficient-block arrays,
  170630. * one per component. The return value is a pointer to the array of
  170631. * virtual-array descriptors. These can be manipulated directly via the
  170632. * JPEG memory manager, or handed off to jpeg_write_coefficients().
  170633. * To release the memory occupied by the virtual arrays, call
  170634. * jpeg_finish_decompress() when done with the data.
  170635. *
  170636. * An alternative usage is to simply obtain access to the coefficient arrays
  170637. * during a buffered-image-mode decompression operation. This is allowed
  170638. * after any jpeg_finish_output() call. The arrays can be accessed until
  170639. * jpeg_finish_decompress() is called. (Note that any call to the library
  170640. * may reposition the arrays, so don't rely on access_virt_barray() results
  170641. * to stay valid across library calls.)
  170642. *
  170643. * Returns NULL if suspended. This case need be checked only if
  170644. * a suspending data source is used.
  170645. */
  170646. GLOBAL(jvirt_barray_ptr *)
  170647. jpeg_read_coefficients (j_decompress_ptr cinfo)
  170648. {
  170649. if (cinfo->global_state == DSTATE_READY) {
  170650. /* First call: initialize active modules */
  170651. transdecode_master_selection(cinfo);
  170652. cinfo->global_state = DSTATE_RDCOEFS;
  170653. }
  170654. if (cinfo->global_state == DSTATE_RDCOEFS) {
  170655. /* Absorb whole file into the coef buffer */
  170656. for (;;) {
  170657. int retcode;
  170658. /* Call progress monitor hook if present */
  170659. if (cinfo->progress != NULL)
  170660. (*cinfo->progress->progress_monitor) ((j_common_ptr) cinfo);
  170661. /* Absorb some more input */
  170662. retcode = (*cinfo->inputctl->consume_input) (cinfo);
  170663. if (retcode == JPEG_SUSPENDED)
  170664. return NULL;
  170665. if (retcode == JPEG_REACHED_EOI)
  170666. break;
  170667. /* Advance progress counter if appropriate */
  170668. if (cinfo->progress != NULL &&
  170669. (retcode == JPEG_ROW_COMPLETED || retcode == JPEG_REACHED_SOS)) {
  170670. if (++cinfo->progress->pass_counter >= cinfo->progress->pass_limit) {
  170671. /* startup underestimated number of scans; ratchet up one scan */
  170672. cinfo->progress->pass_limit += (long) cinfo->total_iMCU_rows;
  170673. }
  170674. }
  170675. }
  170676. /* Set state so that jpeg_finish_decompress does the right thing */
  170677. cinfo->global_state = DSTATE_STOPPING;
  170678. }
  170679. /* At this point we should be in state DSTATE_STOPPING if being used
  170680. * standalone, or in state DSTATE_BUFIMAGE if being invoked to get access
  170681. * to the coefficients during a full buffered-image-mode decompression.
  170682. */
  170683. if ((cinfo->global_state == DSTATE_STOPPING ||
  170684. cinfo->global_state == DSTATE_BUFIMAGE) && cinfo->buffered_image) {
  170685. return cinfo->coef->coef_arrays;
  170686. }
  170687. /* Oops, improper usage */
  170688. ERREXIT1(cinfo, JERR_BAD_STATE, cinfo->global_state);
  170689. return NULL; /* keep compiler happy */
  170690. }
  170691. /*
  170692. * Master selection of decompression modules for transcoding.
  170693. * This substitutes for jdmaster.c's initialization of the full decompressor.
  170694. */
  170695. LOCAL(void)
  170696. transdecode_master_selection (j_decompress_ptr cinfo)
  170697. {
  170698. /* This is effectively a buffered-image operation. */
  170699. cinfo->buffered_image = TRUE;
  170700. /* Entropy decoding: either Huffman or arithmetic coding. */
  170701. if (cinfo->arith_code) {
  170702. ERREXIT(cinfo, JERR_ARITH_NOTIMPL);
  170703. } else {
  170704. if (cinfo->progressive_mode) {
  170705. #ifdef D_PROGRESSIVE_SUPPORTED
  170706. jinit_phuff_decoder(cinfo);
  170707. #else
  170708. ERREXIT(cinfo, JERR_NOT_COMPILED);
  170709. #endif
  170710. } else
  170711. jinit_huff_decoder(cinfo);
  170712. }
  170713. /* Always get a full-image coefficient buffer. */
  170714. jinit_d_coef_controller(cinfo, TRUE);
  170715. /* We can now tell the memory manager to allocate virtual arrays. */
  170716. (*cinfo->mem->realize_virt_arrays) ((j_common_ptr) cinfo);
  170717. /* Initialize input side of decompressor to consume first scan. */
  170718. (*cinfo->inputctl->start_input_pass) (cinfo);
  170719. /* Initialize progress monitoring. */
  170720. if (cinfo->progress != NULL) {
  170721. int nscans;
  170722. /* Estimate number of scans to set pass_limit. */
  170723. if (cinfo->progressive_mode) {
  170724. /* Arbitrarily estimate 2 interleaved DC scans + 3 AC scans/component. */
  170725. nscans = 2 + 3 * cinfo->num_components;
  170726. } else if (cinfo->inputctl->has_multiple_scans) {
  170727. /* For a nonprogressive multiscan file, estimate 1 scan per component. */
  170728. nscans = cinfo->num_components;
  170729. } else {
  170730. nscans = 1;
  170731. }
  170732. cinfo->progress->pass_counter = 0L;
  170733. cinfo->progress->pass_limit = (long) cinfo->total_iMCU_rows * nscans;
  170734. cinfo->progress->completed_passes = 0;
  170735. cinfo->progress->total_passes = 1;
  170736. }
  170737. }
  170738. /*** End of inlined file: jdtrans.c ***/
  170739. /*** Start of inlined file: jfdctflt.c ***/
  170740. #define JPEG_INTERNALS
  170741. #ifdef DCT_FLOAT_SUPPORTED
  170742. /*
  170743. * This module is specialized to the case DCTSIZE = 8.
  170744. */
  170745. #if DCTSIZE != 8
  170746. Sorry, this code only copes with 8x8 DCTs. /* deliberate syntax err */
  170747. #endif
  170748. /*
  170749. * Perform the forward DCT on one block of samples.
  170750. */
  170751. GLOBAL(void)
  170752. jpeg_fdct_float (FAST_FLOAT * data)
  170753. {
  170754. FAST_FLOAT tmp0, tmp1, tmp2, tmp3, tmp4, tmp5, tmp6, tmp7;
  170755. FAST_FLOAT tmp10, tmp11, tmp12, tmp13;
  170756. FAST_FLOAT z1, z2, z3, z4, z5, z11, z13;
  170757. FAST_FLOAT *dataptr;
  170758. int ctr;
  170759. /* Pass 1: process rows. */
  170760. dataptr = data;
  170761. for (ctr = DCTSIZE-1; ctr >= 0; ctr--) {
  170762. tmp0 = dataptr[0] + dataptr[7];
  170763. tmp7 = dataptr[0] - dataptr[7];
  170764. tmp1 = dataptr[1] + dataptr[6];
  170765. tmp6 = dataptr[1] - dataptr[6];
  170766. tmp2 = dataptr[2] + dataptr[5];
  170767. tmp5 = dataptr[2] - dataptr[5];
  170768. tmp3 = dataptr[3] + dataptr[4];
  170769. tmp4 = dataptr[3] - dataptr[4];
  170770. /* Even part */
  170771. tmp10 = tmp0 + tmp3; /* phase 2 */
  170772. tmp13 = tmp0 - tmp3;
  170773. tmp11 = tmp1 + tmp2;
  170774. tmp12 = tmp1 - tmp2;
  170775. dataptr[0] = tmp10 + tmp11; /* phase 3 */
  170776. dataptr[4] = tmp10 - tmp11;
  170777. z1 = (tmp12 + tmp13) * ((FAST_FLOAT) 0.707106781); /* c4 */
  170778. dataptr[2] = tmp13 + z1; /* phase 5 */
  170779. dataptr[6] = tmp13 - z1;
  170780. /* Odd part */
  170781. tmp10 = tmp4 + tmp5; /* phase 2 */
  170782. tmp11 = tmp5 + tmp6;
  170783. tmp12 = tmp6 + tmp7;
  170784. /* The rotator is modified from fig 4-8 to avoid extra negations. */
  170785. z5 = (tmp10 - tmp12) * ((FAST_FLOAT) 0.382683433); /* c6 */
  170786. z2 = ((FAST_FLOAT) 0.541196100) * tmp10 + z5; /* c2-c6 */
  170787. z4 = ((FAST_FLOAT) 1.306562965) * tmp12 + z5; /* c2+c6 */
  170788. z3 = tmp11 * ((FAST_FLOAT) 0.707106781); /* c4 */
  170789. z11 = tmp7 + z3; /* phase 5 */
  170790. z13 = tmp7 - z3;
  170791. dataptr[5] = z13 + z2; /* phase 6 */
  170792. dataptr[3] = z13 - z2;
  170793. dataptr[1] = z11 + z4;
  170794. dataptr[7] = z11 - z4;
  170795. dataptr += DCTSIZE; /* advance pointer to next row */
  170796. }
  170797. /* Pass 2: process columns. */
  170798. dataptr = data;
  170799. for (ctr = DCTSIZE-1; ctr >= 0; ctr--) {
  170800. tmp0 = dataptr[DCTSIZE*0] + dataptr[DCTSIZE*7];
  170801. tmp7 = dataptr[DCTSIZE*0] - dataptr[DCTSIZE*7];
  170802. tmp1 = dataptr[DCTSIZE*1] + dataptr[DCTSIZE*6];
  170803. tmp6 = dataptr[DCTSIZE*1] - dataptr[DCTSIZE*6];
  170804. tmp2 = dataptr[DCTSIZE*2] + dataptr[DCTSIZE*5];
  170805. tmp5 = dataptr[DCTSIZE*2] - dataptr[DCTSIZE*5];
  170806. tmp3 = dataptr[DCTSIZE*3] + dataptr[DCTSIZE*4];
  170807. tmp4 = dataptr[DCTSIZE*3] - dataptr[DCTSIZE*4];
  170808. /* Even part */
  170809. tmp10 = tmp0 + tmp3; /* phase 2 */
  170810. tmp13 = tmp0 - tmp3;
  170811. tmp11 = tmp1 + tmp2;
  170812. tmp12 = tmp1 - tmp2;
  170813. dataptr[DCTSIZE*0] = tmp10 + tmp11; /* phase 3 */
  170814. dataptr[DCTSIZE*4] = tmp10 - tmp11;
  170815. z1 = (tmp12 + tmp13) * ((FAST_FLOAT) 0.707106781); /* c4 */
  170816. dataptr[DCTSIZE*2] = tmp13 + z1; /* phase 5 */
  170817. dataptr[DCTSIZE*6] = tmp13 - z1;
  170818. /* Odd part */
  170819. tmp10 = tmp4 + tmp5; /* phase 2 */
  170820. tmp11 = tmp5 + tmp6;
  170821. tmp12 = tmp6 + tmp7;
  170822. /* The rotator is modified from fig 4-8 to avoid extra negations. */
  170823. z5 = (tmp10 - tmp12) * ((FAST_FLOAT) 0.382683433); /* c6 */
  170824. z2 = ((FAST_FLOAT) 0.541196100) * tmp10 + z5; /* c2-c6 */
  170825. z4 = ((FAST_FLOAT) 1.306562965) * tmp12 + z5; /* c2+c6 */
  170826. z3 = tmp11 * ((FAST_FLOAT) 0.707106781); /* c4 */
  170827. z11 = tmp7 + z3; /* phase 5 */
  170828. z13 = tmp7 - z3;
  170829. dataptr[DCTSIZE*5] = z13 + z2; /* phase 6 */
  170830. dataptr[DCTSIZE*3] = z13 - z2;
  170831. dataptr[DCTSIZE*1] = z11 + z4;
  170832. dataptr[DCTSIZE*7] = z11 - z4;
  170833. dataptr++; /* advance pointer to next column */
  170834. }
  170835. }
  170836. #endif /* DCT_FLOAT_SUPPORTED */
  170837. /*** End of inlined file: jfdctflt.c ***/
  170838. /*** Start of inlined file: jfdctint.c ***/
  170839. #define JPEG_INTERNALS
  170840. #ifdef DCT_ISLOW_SUPPORTED
  170841. /*
  170842. * This module is specialized to the case DCTSIZE = 8.
  170843. */
  170844. #if DCTSIZE != 8
  170845. Sorry, this code only copes with 8x8 DCTs. /* deliberate syntax err */
  170846. #endif
  170847. /*
  170848. * The poop on this scaling stuff is as follows:
  170849. *
  170850. * Each 1-D DCT step produces outputs which are a factor of sqrt(N)
  170851. * larger than the true DCT outputs. The final outputs are therefore
  170852. * a factor of N larger than desired; since N=8 this can be cured by
  170853. * a simple right shift at the end of the algorithm. The advantage of
  170854. * this arrangement is that we save two multiplications per 1-D DCT,
  170855. * because the y0 and y4 outputs need not be divided by sqrt(N).
  170856. * In the IJG code, this factor of 8 is removed by the quantization step
  170857. * (in jcdctmgr.c), NOT in this module.
  170858. *
  170859. * We have to do addition and subtraction of the integer inputs, which
  170860. * is no problem, and multiplication by fractional constants, which is
  170861. * a problem to do in integer arithmetic. We multiply all the constants
  170862. * by CONST_SCALE and convert them to integer constants (thus retaining
  170863. * CONST_BITS bits of precision in the constants). After doing a
  170864. * multiplication we have to divide the product by CONST_SCALE, with proper
  170865. * rounding, to produce the correct output. This division can be done
  170866. * cheaply as a right shift of CONST_BITS bits. We postpone shifting
  170867. * as long as possible so that partial sums can be added together with
  170868. * full fractional precision.
  170869. *
  170870. * The outputs of the first pass are scaled up by PASS1_BITS bits so that
  170871. * they are represented to better-than-integral precision. These outputs
  170872. * require BITS_IN_JSAMPLE + PASS1_BITS + 3 bits; this fits in a 16-bit word
  170873. * with the recommended scaling. (For 12-bit sample data, the intermediate
  170874. * array is INT32 anyway.)
  170875. *
  170876. * To avoid overflow of the 32-bit intermediate results in pass 2, we must
  170877. * have BITS_IN_JSAMPLE + CONST_BITS + PASS1_BITS <= 26. Error analysis
  170878. * shows that the values given below are the most effective.
  170879. */
  170880. #if BITS_IN_JSAMPLE == 8
  170881. #define CONST_BITS 13
  170882. #define PASS1_BITS 2
  170883. #else
  170884. #define CONST_BITS 13
  170885. #define PASS1_BITS 1 /* lose a little precision to avoid overflow */
  170886. #endif
  170887. /* Some C compilers fail to reduce "FIX(constant)" at compile time, thus
  170888. * causing a lot of useless floating-point operations at run time.
  170889. * To get around this we use the following pre-calculated constants.
  170890. * If you change CONST_BITS you may want to add appropriate values.
  170891. * (With a reasonable C compiler, you can just rely on the FIX() macro...)
  170892. */
  170893. #if CONST_BITS == 13
  170894. #define FIX_0_298631336 ((INT32) 2446) /* FIX(0.298631336) */
  170895. #define FIX_0_390180644 ((INT32) 3196) /* FIX(0.390180644) */
  170896. #define FIX_0_541196100 ((INT32) 4433) /* FIX(0.541196100) */
  170897. #define FIX_0_765366865 ((INT32) 6270) /* FIX(0.765366865) */
  170898. #define FIX_0_899976223 ((INT32) 7373) /* FIX(0.899976223) */
  170899. #define FIX_1_175875602 ((INT32) 9633) /* FIX(1.175875602) */
  170900. #define FIX_1_501321110 ((INT32) 12299) /* FIX(1.501321110) */
  170901. #define FIX_1_847759065 ((INT32) 15137) /* FIX(1.847759065) */
  170902. #define FIX_1_961570560 ((INT32) 16069) /* FIX(1.961570560) */
  170903. #define FIX_2_053119869 ((INT32) 16819) /* FIX(2.053119869) */
  170904. #define FIX_2_562915447 ((INT32) 20995) /* FIX(2.562915447) */
  170905. #define FIX_3_072711026 ((INT32) 25172) /* FIX(3.072711026) */
  170906. #else
  170907. #define FIX_0_298631336 FIX(0.298631336)
  170908. #define FIX_0_390180644 FIX(0.390180644)
  170909. #define FIX_0_541196100 FIX(0.541196100)
  170910. #define FIX_0_765366865 FIX(0.765366865)
  170911. #define FIX_0_899976223 FIX(0.899976223)
  170912. #define FIX_1_175875602 FIX(1.175875602)
  170913. #define FIX_1_501321110 FIX(1.501321110)
  170914. #define FIX_1_847759065 FIX(1.847759065)
  170915. #define FIX_1_961570560 FIX(1.961570560)
  170916. #define FIX_2_053119869 FIX(2.053119869)
  170917. #define FIX_2_562915447 FIX(2.562915447)
  170918. #define FIX_3_072711026 FIX(3.072711026)
  170919. #endif
  170920. /* Multiply an INT32 variable by an INT32 constant to yield an INT32 result.
  170921. * For 8-bit samples with the recommended scaling, all the variable
  170922. * and constant values involved are no more than 16 bits wide, so a
  170923. * 16x16->32 bit multiply can be used instead of a full 32x32 multiply.
  170924. * For 12-bit samples, a full 32-bit multiplication will be needed.
  170925. */
  170926. #if BITS_IN_JSAMPLE == 8
  170927. #define MULTIPLY(var,const) MULTIPLY16C16(var,const)
  170928. #else
  170929. #define MULTIPLY(var,const) ((var) * (const))
  170930. #endif
  170931. /*
  170932. * Perform the forward DCT on one block of samples.
  170933. */
  170934. GLOBAL(void)
  170935. jpeg_fdct_islow (DCTELEM * data)
  170936. {
  170937. INT32 tmp0, tmp1, tmp2, tmp3, tmp4, tmp5, tmp6, tmp7;
  170938. INT32 tmp10, tmp11, tmp12, tmp13;
  170939. INT32 z1, z2, z3, z4, z5;
  170940. DCTELEM *dataptr;
  170941. int ctr;
  170942. SHIFT_TEMPS
  170943. /* Pass 1: process rows. */
  170944. /* Note results are scaled up by sqrt(8) compared to a true DCT; */
  170945. /* furthermore, we scale the results by 2**PASS1_BITS. */
  170946. dataptr = data;
  170947. for (ctr = DCTSIZE-1; ctr >= 0; ctr--) {
  170948. tmp0 = dataptr[0] + dataptr[7];
  170949. tmp7 = dataptr[0] - dataptr[7];
  170950. tmp1 = dataptr[1] + dataptr[6];
  170951. tmp6 = dataptr[1] - dataptr[6];
  170952. tmp2 = dataptr[2] + dataptr[5];
  170953. tmp5 = dataptr[2] - dataptr[5];
  170954. tmp3 = dataptr[3] + dataptr[4];
  170955. tmp4 = dataptr[3] - dataptr[4];
  170956. /* Even part per LL&M figure 1 --- note that published figure is faulty;
  170957. * rotator "sqrt(2)*c1" should be "sqrt(2)*c6".
  170958. */
  170959. tmp10 = tmp0 + tmp3;
  170960. tmp13 = tmp0 - tmp3;
  170961. tmp11 = tmp1 + tmp2;
  170962. tmp12 = tmp1 - tmp2;
  170963. dataptr[0] = (DCTELEM) ((tmp10 + tmp11) << PASS1_BITS);
  170964. dataptr[4] = (DCTELEM) ((tmp10 - tmp11) << PASS1_BITS);
  170965. z1 = MULTIPLY(tmp12 + tmp13, FIX_0_541196100);
  170966. dataptr[2] = (DCTELEM) DESCALE(z1 + MULTIPLY(tmp13, FIX_0_765366865),
  170967. CONST_BITS-PASS1_BITS);
  170968. dataptr[6] = (DCTELEM) DESCALE(z1 + MULTIPLY(tmp12, - FIX_1_847759065),
  170969. CONST_BITS-PASS1_BITS);
  170970. /* Odd part per figure 8 --- note paper omits factor of sqrt(2).
  170971. * cK represents cos(K*pi/16).
  170972. * i0..i3 in the paper are tmp4..tmp7 here.
  170973. */
  170974. z1 = tmp4 + tmp7;
  170975. z2 = tmp5 + tmp6;
  170976. z3 = tmp4 + tmp6;
  170977. z4 = tmp5 + tmp7;
  170978. z5 = MULTIPLY(z3 + z4, FIX_1_175875602); /* sqrt(2) * c3 */
  170979. tmp4 = MULTIPLY(tmp4, FIX_0_298631336); /* sqrt(2) * (-c1+c3+c5-c7) */
  170980. tmp5 = MULTIPLY(tmp5, FIX_2_053119869); /* sqrt(2) * ( c1+c3-c5+c7) */
  170981. tmp6 = MULTIPLY(tmp6, FIX_3_072711026); /* sqrt(2) * ( c1+c3+c5-c7) */
  170982. tmp7 = MULTIPLY(tmp7, FIX_1_501321110); /* sqrt(2) * ( c1+c3-c5-c7) */
  170983. z1 = MULTIPLY(z1, - FIX_0_899976223); /* sqrt(2) * (c7-c3) */
  170984. z2 = MULTIPLY(z2, - FIX_2_562915447); /* sqrt(2) * (-c1-c3) */
  170985. z3 = MULTIPLY(z3, - FIX_1_961570560); /* sqrt(2) * (-c3-c5) */
  170986. z4 = MULTIPLY(z4, - FIX_0_390180644); /* sqrt(2) * (c5-c3) */
  170987. z3 += z5;
  170988. z4 += z5;
  170989. dataptr[7] = (DCTELEM) DESCALE(tmp4 + z1 + z3, CONST_BITS-PASS1_BITS);
  170990. dataptr[5] = (DCTELEM) DESCALE(tmp5 + z2 + z4, CONST_BITS-PASS1_BITS);
  170991. dataptr[3] = (DCTELEM) DESCALE(tmp6 + z2 + z3, CONST_BITS-PASS1_BITS);
  170992. dataptr[1] = (DCTELEM) DESCALE(tmp7 + z1 + z4, CONST_BITS-PASS1_BITS);
  170993. dataptr += DCTSIZE; /* advance pointer to next row */
  170994. }
  170995. /* Pass 2: process columns.
  170996. * We remove the PASS1_BITS scaling, but leave the results scaled up
  170997. * by an overall factor of 8.
  170998. */
  170999. dataptr = data;
  171000. for (ctr = DCTSIZE-1; ctr >= 0; ctr--) {
  171001. tmp0 = dataptr[DCTSIZE*0] + dataptr[DCTSIZE*7];
  171002. tmp7 = dataptr[DCTSIZE*0] - dataptr[DCTSIZE*7];
  171003. tmp1 = dataptr[DCTSIZE*1] + dataptr[DCTSIZE*6];
  171004. tmp6 = dataptr[DCTSIZE*1] - dataptr[DCTSIZE*6];
  171005. tmp2 = dataptr[DCTSIZE*2] + dataptr[DCTSIZE*5];
  171006. tmp5 = dataptr[DCTSIZE*2] - dataptr[DCTSIZE*5];
  171007. tmp3 = dataptr[DCTSIZE*3] + dataptr[DCTSIZE*4];
  171008. tmp4 = dataptr[DCTSIZE*3] - dataptr[DCTSIZE*4];
  171009. /* Even part per LL&M figure 1 --- note that published figure is faulty;
  171010. * rotator "sqrt(2)*c1" should be "sqrt(2)*c6".
  171011. */
  171012. tmp10 = tmp0 + tmp3;
  171013. tmp13 = tmp0 - tmp3;
  171014. tmp11 = tmp1 + tmp2;
  171015. tmp12 = tmp1 - tmp2;
  171016. dataptr[DCTSIZE*0] = (DCTELEM) DESCALE(tmp10 + tmp11, PASS1_BITS);
  171017. dataptr[DCTSIZE*4] = (DCTELEM) DESCALE(tmp10 - tmp11, PASS1_BITS);
  171018. z1 = MULTIPLY(tmp12 + tmp13, FIX_0_541196100);
  171019. dataptr[DCTSIZE*2] = (DCTELEM) DESCALE(z1 + MULTIPLY(tmp13, FIX_0_765366865),
  171020. CONST_BITS+PASS1_BITS);
  171021. dataptr[DCTSIZE*6] = (DCTELEM) DESCALE(z1 + MULTIPLY(tmp12, - FIX_1_847759065),
  171022. CONST_BITS+PASS1_BITS);
  171023. /* Odd part per figure 8 --- note paper omits factor of sqrt(2).
  171024. * cK represents cos(K*pi/16).
  171025. * i0..i3 in the paper are tmp4..tmp7 here.
  171026. */
  171027. z1 = tmp4 + tmp7;
  171028. z2 = tmp5 + tmp6;
  171029. z3 = tmp4 + tmp6;
  171030. z4 = tmp5 + tmp7;
  171031. z5 = MULTIPLY(z3 + z4, FIX_1_175875602); /* sqrt(2) * c3 */
  171032. tmp4 = MULTIPLY(tmp4, FIX_0_298631336); /* sqrt(2) * (-c1+c3+c5-c7) */
  171033. tmp5 = MULTIPLY(tmp5, FIX_2_053119869); /* sqrt(2) * ( c1+c3-c5+c7) */
  171034. tmp6 = MULTIPLY(tmp6, FIX_3_072711026); /* sqrt(2) * ( c1+c3+c5-c7) */
  171035. tmp7 = MULTIPLY(tmp7, FIX_1_501321110); /* sqrt(2) * ( c1+c3-c5-c7) */
  171036. z1 = MULTIPLY(z1, - FIX_0_899976223); /* sqrt(2) * (c7-c3) */
  171037. z2 = MULTIPLY(z2, - FIX_2_562915447); /* sqrt(2) * (-c1-c3) */
  171038. z3 = MULTIPLY(z3, - FIX_1_961570560); /* sqrt(2) * (-c3-c5) */
  171039. z4 = MULTIPLY(z4, - FIX_0_390180644); /* sqrt(2) * (c5-c3) */
  171040. z3 += z5;
  171041. z4 += z5;
  171042. dataptr[DCTSIZE*7] = (DCTELEM) DESCALE(tmp4 + z1 + z3,
  171043. CONST_BITS+PASS1_BITS);
  171044. dataptr[DCTSIZE*5] = (DCTELEM) DESCALE(tmp5 + z2 + z4,
  171045. CONST_BITS+PASS1_BITS);
  171046. dataptr[DCTSIZE*3] = (DCTELEM) DESCALE(tmp6 + z2 + z3,
  171047. CONST_BITS+PASS1_BITS);
  171048. dataptr[DCTSIZE*1] = (DCTELEM) DESCALE(tmp7 + z1 + z4,
  171049. CONST_BITS+PASS1_BITS);
  171050. dataptr++; /* advance pointer to next column */
  171051. }
  171052. }
  171053. #endif /* DCT_ISLOW_SUPPORTED */
  171054. /*** End of inlined file: jfdctint.c ***/
  171055. #undef CONST_BITS
  171056. #undef MULTIPLY
  171057. #undef FIX_0_541196100
  171058. /*** Start of inlined file: jfdctfst.c ***/
  171059. #define JPEG_INTERNALS
  171060. #ifdef DCT_IFAST_SUPPORTED
  171061. /*
  171062. * This module is specialized to the case DCTSIZE = 8.
  171063. */
  171064. #if DCTSIZE != 8
  171065. Sorry, this code only copes with 8x8 DCTs. /* deliberate syntax err */
  171066. #endif
  171067. /* Scaling decisions are generally the same as in the LL&M algorithm;
  171068. * see jfdctint.c for more details. However, we choose to descale
  171069. * (right shift) multiplication products as soon as they are formed,
  171070. * rather than carrying additional fractional bits into subsequent additions.
  171071. * This compromises accuracy slightly, but it lets us save a few shifts.
  171072. * More importantly, 16-bit arithmetic is then adequate (for 8-bit samples)
  171073. * everywhere except in the multiplications proper; this saves a good deal
  171074. * of work on 16-bit-int machines.
  171075. *
  171076. * Again to save a few shifts, the intermediate results between pass 1 and
  171077. * pass 2 are not upscaled, but are represented only to integral precision.
  171078. *
  171079. * A final compromise is to represent the multiplicative constants to only
  171080. * 8 fractional bits, rather than 13. This saves some shifting work on some
  171081. * machines, and may also reduce the cost of multiplication (since there
  171082. * are fewer one-bits in the constants).
  171083. */
  171084. #define CONST_BITS 8
  171085. /* Some C compilers fail to reduce "FIX(constant)" at compile time, thus
  171086. * causing a lot of useless floating-point operations at run time.
  171087. * To get around this we use the following pre-calculated constants.
  171088. * If you change CONST_BITS you may want to add appropriate values.
  171089. * (With a reasonable C compiler, you can just rely on the FIX() macro...)
  171090. */
  171091. #if CONST_BITS == 8
  171092. #define FIX_0_382683433 ((INT32) 98) /* FIX(0.382683433) */
  171093. #define FIX_0_541196100 ((INT32) 139) /* FIX(0.541196100) */
  171094. #define FIX_0_707106781 ((INT32) 181) /* FIX(0.707106781) */
  171095. #define FIX_1_306562965 ((INT32) 334) /* FIX(1.306562965) */
  171096. #else
  171097. #define FIX_0_382683433 FIX(0.382683433)
  171098. #define FIX_0_541196100 FIX(0.541196100)
  171099. #define FIX_0_707106781 FIX(0.707106781)
  171100. #define FIX_1_306562965 FIX(1.306562965)
  171101. #endif
  171102. /* We can gain a little more speed, with a further compromise in accuracy,
  171103. * by omitting the addition in a descaling shift. This yields an incorrectly
  171104. * rounded result half the time...
  171105. */
  171106. #ifndef USE_ACCURATE_ROUNDING
  171107. #undef DESCALE
  171108. #define DESCALE(x,n) RIGHT_SHIFT(x, n)
  171109. #endif
  171110. /* Multiply a DCTELEM variable by an INT32 constant, and immediately
  171111. * descale to yield a DCTELEM result.
  171112. */
  171113. #define MULTIPLY(var,const) ((DCTELEM) DESCALE((var) * (const), CONST_BITS))
  171114. /*
  171115. * Perform the forward DCT on one block of samples.
  171116. */
  171117. GLOBAL(void)
  171118. jpeg_fdct_ifast (DCTELEM * data)
  171119. {
  171120. DCTELEM tmp0, tmp1, tmp2, tmp3, tmp4, tmp5, tmp6, tmp7;
  171121. DCTELEM tmp10, tmp11, tmp12, tmp13;
  171122. DCTELEM z1, z2, z3, z4, z5, z11, z13;
  171123. DCTELEM *dataptr;
  171124. int ctr;
  171125. SHIFT_TEMPS
  171126. /* Pass 1: process rows. */
  171127. dataptr = data;
  171128. for (ctr = DCTSIZE-1; ctr >= 0; ctr--) {
  171129. tmp0 = dataptr[0] + dataptr[7];
  171130. tmp7 = dataptr[0] - dataptr[7];
  171131. tmp1 = dataptr[1] + dataptr[6];
  171132. tmp6 = dataptr[1] - dataptr[6];
  171133. tmp2 = dataptr[2] + dataptr[5];
  171134. tmp5 = dataptr[2] - dataptr[5];
  171135. tmp3 = dataptr[3] + dataptr[4];
  171136. tmp4 = dataptr[3] - dataptr[4];
  171137. /* Even part */
  171138. tmp10 = tmp0 + tmp3; /* phase 2 */
  171139. tmp13 = tmp0 - tmp3;
  171140. tmp11 = tmp1 + tmp2;
  171141. tmp12 = tmp1 - tmp2;
  171142. dataptr[0] = tmp10 + tmp11; /* phase 3 */
  171143. dataptr[4] = tmp10 - tmp11;
  171144. z1 = MULTIPLY(tmp12 + tmp13, FIX_0_707106781); /* c4 */
  171145. dataptr[2] = tmp13 + z1; /* phase 5 */
  171146. dataptr[6] = tmp13 - z1;
  171147. /* Odd part */
  171148. tmp10 = tmp4 + tmp5; /* phase 2 */
  171149. tmp11 = tmp5 + tmp6;
  171150. tmp12 = tmp6 + tmp7;
  171151. /* The rotator is modified from fig 4-8 to avoid extra negations. */
  171152. z5 = MULTIPLY(tmp10 - tmp12, FIX_0_382683433); /* c6 */
  171153. z2 = MULTIPLY(tmp10, FIX_0_541196100) + z5; /* c2-c6 */
  171154. z4 = MULTIPLY(tmp12, FIX_1_306562965) + z5; /* c2+c6 */
  171155. z3 = MULTIPLY(tmp11, FIX_0_707106781); /* c4 */
  171156. z11 = tmp7 + z3; /* phase 5 */
  171157. z13 = tmp7 - z3;
  171158. dataptr[5] = z13 + z2; /* phase 6 */
  171159. dataptr[3] = z13 - z2;
  171160. dataptr[1] = z11 + z4;
  171161. dataptr[7] = z11 - z4;
  171162. dataptr += DCTSIZE; /* advance pointer to next row */
  171163. }
  171164. /* Pass 2: process columns. */
  171165. dataptr = data;
  171166. for (ctr = DCTSIZE-1; ctr >= 0; ctr--) {
  171167. tmp0 = dataptr[DCTSIZE*0] + dataptr[DCTSIZE*7];
  171168. tmp7 = dataptr[DCTSIZE*0] - dataptr[DCTSIZE*7];
  171169. tmp1 = dataptr[DCTSIZE*1] + dataptr[DCTSIZE*6];
  171170. tmp6 = dataptr[DCTSIZE*1] - dataptr[DCTSIZE*6];
  171171. tmp2 = dataptr[DCTSIZE*2] + dataptr[DCTSIZE*5];
  171172. tmp5 = dataptr[DCTSIZE*2] - dataptr[DCTSIZE*5];
  171173. tmp3 = dataptr[DCTSIZE*3] + dataptr[DCTSIZE*4];
  171174. tmp4 = dataptr[DCTSIZE*3] - dataptr[DCTSIZE*4];
  171175. /* Even part */
  171176. tmp10 = tmp0 + tmp3; /* phase 2 */
  171177. tmp13 = tmp0 - tmp3;
  171178. tmp11 = tmp1 + tmp2;
  171179. tmp12 = tmp1 - tmp2;
  171180. dataptr[DCTSIZE*0] = tmp10 + tmp11; /* phase 3 */
  171181. dataptr[DCTSIZE*4] = tmp10 - tmp11;
  171182. z1 = MULTIPLY(tmp12 + tmp13, FIX_0_707106781); /* c4 */
  171183. dataptr[DCTSIZE*2] = tmp13 + z1; /* phase 5 */
  171184. dataptr[DCTSIZE*6] = tmp13 - z1;
  171185. /* Odd part */
  171186. tmp10 = tmp4 + tmp5; /* phase 2 */
  171187. tmp11 = tmp5 + tmp6;
  171188. tmp12 = tmp6 + tmp7;
  171189. /* The rotator is modified from fig 4-8 to avoid extra negations. */
  171190. z5 = MULTIPLY(tmp10 - tmp12, FIX_0_382683433); /* c6 */
  171191. z2 = MULTIPLY(tmp10, FIX_0_541196100) + z5; /* c2-c6 */
  171192. z4 = MULTIPLY(tmp12, FIX_1_306562965) + z5; /* c2+c6 */
  171193. z3 = MULTIPLY(tmp11, FIX_0_707106781); /* c4 */
  171194. z11 = tmp7 + z3; /* phase 5 */
  171195. z13 = tmp7 - z3;
  171196. dataptr[DCTSIZE*5] = z13 + z2; /* phase 6 */
  171197. dataptr[DCTSIZE*3] = z13 - z2;
  171198. dataptr[DCTSIZE*1] = z11 + z4;
  171199. dataptr[DCTSIZE*7] = z11 - z4;
  171200. dataptr++; /* advance pointer to next column */
  171201. }
  171202. }
  171203. #endif /* DCT_IFAST_SUPPORTED */
  171204. /*** End of inlined file: jfdctfst.c ***/
  171205. #undef FIX_0_541196100
  171206. /*** Start of inlined file: jidctflt.c ***/
  171207. #define JPEG_INTERNALS
  171208. #ifdef DCT_FLOAT_SUPPORTED
  171209. /*
  171210. * This module is specialized to the case DCTSIZE = 8.
  171211. */
  171212. #if DCTSIZE != 8
  171213. Sorry, this code only copes with 8x8 DCTs. /* deliberate syntax err */
  171214. #endif
  171215. /* Dequantize a coefficient by multiplying it by the multiplier-table
  171216. * entry; produce a float result.
  171217. */
  171218. #define DEQUANTIZE(coef,quantval) (((FAST_FLOAT) (coef)) * (quantval))
  171219. /*
  171220. * Perform dequantization and inverse DCT on one block of coefficients.
  171221. */
  171222. GLOBAL(void)
  171223. jpeg_idct_float (j_decompress_ptr cinfo, jpeg_component_info * compptr,
  171224. JCOEFPTR coef_block,
  171225. JSAMPARRAY output_buf, JDIMENSION output_col)
  171226. {
  171227. FAST_FLOAT tmp0, tmp1, tmp2, tmp3, tmp4, tmp5, tmp6, tmp7;
  171228. FAST_FLOAT tmp10, tmp11, tmp12, tmp13;
  171229. FAST_FLOAT z5, z10, z11, z12, z13;
  171230. JCOEFPTR inptr;
  171231. FLOAT_MULT_TYPE * quantptr;
  171232. FAST_FLOAT * wsptr;
  171233. JSAMPROW outptr;
  171234. JSAMPLE *range_limit = IDCT_range_limit(cinfo);
  171235. int ctr;
  171236. FAST_FLOAT workspace[DCTSIZE2]; /* buffers data between passes */
  171237. SHIFT_TEMPS
  171238. /* Pass 1: process columns from input, store into work array. */
  171239. inptr = coef_block;
  171240. quantptr = (FLOAT_MULT_TYPE *) compptr->dct_table;
  171241. wsptr = workspace;
  171242. for (ctr = DCTSIZE; ctr > 0; ctr--) {
  171243. /* Due to quantization, we will usually find that many of the input
  171244. * coefficients are zero, especially the AC terms. We can exploit this
  171245. * by short-circuiting the IDCT calculation for any column in which all
  171246. * the AC terms are zero. In that case each output is equal to the
  171247. * DC coefficient (with scale factor as needed).
  171248. * With typical images and quantization tables, half or more of the
  171249. * column DCT calculations can be simplified this way.
  171250. */
  171251. if (inptr[DCTSIZE*1] == 0 && inptr[DCTSIZE*2] == 0 &&
  171252. inptr[DCTSIZE*3] == 0 && inptr[DCTSIZE*4] == 0 &&
  171253. inptr[DCTSIZE*5] == 0 && inptr[DCTSIZE*6] == 0 &&
  171254. inptr[DCTSIZE*7] == 0) {
  171255. /* AC terms all zero */
  171256. FAST_FLOAT dcval = DEQUANTIZE(inptr[DCTSIZE*0], quantptr[DCTSIZE*0]);
  171257. wsptr[DCTSIZE*0] = dcval;
  171258. wsptr[DCTSIZE*1] = dcval;
  171259. wsptr[DCTSIZE*2] = dcval;
  171260. wsptr[DCTSIZE*3] = dcval;
  171261. wsptr[DCTSIZE*4] = dcval;
  171262. wsptr[DCTSIZE*5] = dcval;
  171263. wsptr[DCTSIZE*6] = dcval;
  171264. wsptr[DCTSIZE*7] = dcval;
  171265. inptr++; /* advance pointers to next column */
  171266. quantptr++;
  171267. wsptr++;
  171268. continue;
  171269. }
  171270. /* Even part */
  171271. tmp0 = DEQUANTIZE(inptr[DCTSIZE*0], quantptr[DCTSIZE*0]);
  171272. tmp1 = DEQUANTIZE(inptr[DCTSIZE*2], quantptr[DCTSIZE*2]);
  171273. tmp2 = DEQUANTIZE(inptr[DCTSIZE*4], quantptr[DCTSIZE*4]);
  171274. tmp3 = DEQUANTIZE(inptr[DCTSIZE*6], quantptr[DCTSIZE*6]);
  171275. tmp10 = tmp0 + tmp2; /* phase 3 */
  171276. tmp11 = tmp0 - tmp2;
  171277. tmp13 = tmp1 + tmp3; /* phases 5-3 */
  171278. tmp12 = (tmp1 - tmp3) * ((FAST_FLOAT) 1.414213562) - tmp13; /* 2*c4 */
  171279. tmp0 = tmp10 + tmp13; /* phase 2 */
  171280. tmp3 = tmp10 - tmp13;
  171281. tmp1 = tmp11 + tmp12;
  171282. tmp2 = tmp11 - tmp12;
  171283. /* Odd part */
  171284. tmp4 = DEQUANTIZE(inptr[DCTSIZE*1], quantptr[DCTSIZE*1]);
  171285. tmp5 = DEQUANTIZE(inptr[DCTSIZE*3], quantptr[DCTSIZE*3]);
  171286. tmp6 = DEQUANTIZE(inptr[DCTSIZE*5], quantptr[DCTSIZE*5]);
  171287. tmp7 = DEQUANTIZE(inptr[DCTSIZE*7], quantptr[DCTSIZE*7]);
  171288. z13 = tmp6 + tmp5; /* phase 6 */
  171289. z10 = tmp6 - tmp5;
  171290. z11 = tmp4 + tmp7;
  171291. z12 = tmp4 - tmp7;
  171292. tmp7 = z11 + z13; /* phase 5 */
  171293. tmp11 = (z11 - z13) * ((FAST_FLOAT) 1.414213562); /* 2*c4 */
  171294. z5 = (z10 + z12) * ((FAST_FLOAT) 1.847759065); /* 2*c2 */
  171295. tmp10 = ((FAST_FLOAT) 1.082392200) * z12 - z5; /* 2*(c2-c6) */
  171296. tmp12 = ((FAST_FLOAT) -2.613125930) * z10 + z5; /* -2*(c2+c6) */
  171297. tmp6 = tmp12 - tmp7; /* phase 2 */
  171298. tmp5 = tmp11 - tmp6;
  171299. tmp4 = tmp10 + tmp5;
  171300. wsptr[DCTSIZE*0] = tmp0 + tmp7;
  171301. wsptr[DCTSIZE*7] = tmp0 - tmp7;
  171302. wsptr[DCTSIZE*1] = tmp1 + tmp6;
  171303. wsptr[DCTSIZE*6] = tmp1 - tmp6;
  171304. wsptr[DCTSIZE*2] = tmp2 + tmp5;
  171305. wsptr[DCTSIZE*5] = tmp2 - tmp5;
  171306. wsptr[DCTSIZE*4] = tmp3 + tmp4;
  171307. wsptr[DCTSIZE*3] = tmp3 - tmp4;
  171308. inptr++; /* advance pointers to next column */
  171309. quantptr++;
  171310. wsptr++;
  171311. }
  171312. /* Pass 2: process rows from work array, store into output array. */
  171313. /* Note that we must descale the results by a factor of 8 == 2**3. */
  171314. wsptr = workspace;
  171315. for (ctr = 0; ctr < DCTSIZE; ctr++) {
  171316. outptr = output_buf[ctr] + output_col;
  171317. /* Rows of zeroes can be exploited in the same way as we did with columns.
  171318. * However, the column calculation has created many nonzero AC terms, so
  171319. * the simplification applies less often (typically 5% to 10% of the time).
  171320. * And testing floats for zero is relatively expensive, so we don't bother.
  171321. */
  171322. /* Even part */
  171323. tmp10 = wsptr[0] + wsptr[4];
  171324. tmp11 = wsptr[0] - wsptr[4];
  171325. tmp13 = wsptr[2] + wsptr[6];
  171326. tmp12 = (wsptr[2] - wsptr[6]) * ((FAST_FLOAT) 1.414213562) - tmp13;
  171327. tmp0 = tmp10 + tmp13;
  171328. tmp3 = tmp10 - tmp13;
  171329. tmp1 = tmp11 + tmp12;
  171330. tmp2 = tmp11 - tmp12;
  171331. /* Odd part */
  171332. z13 = wsptr[5] + wsptr[3];
  171333. z10 = wsptr[5] - wsptr[3];
  171334. z11 = wsptr[1] + wsptr[7];
  171335. z12 = wsptr[1] - wsptr[7];
  171336. tmp7 = z11 + z13;
  171337. tmp11 = (z11 - z13) * ((FAST_FLOAT) 1.414213562);
  171338. z5 = (z10 + z12) * ((FAST_FLOAT) 1.847759065); /* 2*c2 */
  171339. tmp10 = ((FAST_FLOAT) 1.082392200) * z12 - z5; /* 2*(c2-c6) */
  171340. tmp12 = ((FAST_FLOAT) -2.613125930) * z10 + z5; /* -2*(c2+c6) */
  171341. tmp6 = tmp12 - tmp7;
  171342. tmp5 = tmp11 - tmp6;
  171343. tmp4 = tmp10 + tmp5;
  171344. /* Final output stage: scale down by a factor of 8 and range-limit */
  171345. outptr[0] = range_limit[(int) DESCALE((INT32) (tmp0 + tmp7), 3)
  171346. & RANGE_MASK];
  171347. outptr[7] = range_limit[(int) DESCALE((INT32) (tmp0 - tmp7), 3)
  171348. & RANGE_MASK];
  171349. outptr[1] = range_limit[(int) DESCALE((INT32) (tmp1 + tmp6), 3)
  171350. & RANGE_MASK];
  171351. outptr[6] = range_limit[(int) DESCALE((INT32) (tmp1 - tmp6), 3)
  171352. & RANGE_MASK];
  171353. outptr[2] = range_limit[(int) DESCALE((INT32) (tmp2 + tmp5), 3)
  171354. & RANGE_MASK];
  171355. outptr[5] = range_limit[(int) DESCALE((INT32) (tmp2 - tmp5), 3)
  171356. & RANGE_MASK];
  171357. outptr[4] = range_limit[(int) DESCALE((INT32) (tmp3 + tmp4), 3)
  171358. & RANGE_MASK];
  171359. outptr[3] = range_limit[(int) DESCALE((INT32) (tmp3 - tmp4), 3)
  171360. & RANGE_MASK];
  171361. wsptr += DCTSIZE; /* advance pointer to next row */
  171362. }
  171363. }
  171364. #endif /* DCT_FLOAT_SUPPORTED */
  171365. /*** End of inlined file: jidctflt.c ***/
  171366. #undef CONST_BITS
  171367. #undef FIX_1_847759065
  171368. #undef MULTIPLY
  171369. #undef DEQUANTIZE
  171370. #undef DESCALE
  171371. /*** Start of inlined file: jidctfst.c ***/
  171372. #define JPEG_INTERNALS
  171373. #ifdef DCT_IFAST_SUPPORTED
  171374. /*
  171375. * This module is specialized to the case DCTSIZE = 8.
  171376. */
  171377. #if DCTSIZE != 8
  171378. Sorry, this code only copes with 8x8 DCTs. /* deliberate syntax err */
  171379. #endif
  171380. /* Scaling decisions are generally the same as in the LL&M algorithm;
  171381. * see jidctint.c for more details. However, we choose to descale
  171382. * (right shift) multiplication products as soon as they are formed,
  171383. * rather than carrying additional fractional bits into subsequent additions.
  171384. * This compromises accuracy slightly, but it lets us save a few shifts.
  171385. * More importantly, 16-bit arithmetic is then adequate (for 8-bit samples)
  171386. * everywhere except in the multiplications proper; this saves a good deal
  171387. * of work on 16-bit-int machines.
  171388. *
  171389. * The dequantized coefficients are not integers because the AA&N scaling
  171390. * factors have been incorporated. We represent them scaled up by PASS1_BITS,
  171391. * so that the first and second IDCT rounds have the same input scaling.
  171392. * For 8-bit JSAMPLEs, we choose IFAST_SCALE_BITS = PASS1_BITS so as to
  171393. * avoid a descaling shift; this compromises accuracy rather drastically
  171394. * for small quantization table entries, but it saves a lot of shifts.
  171395. * For 12-bit JSAMPLEs, there's no hope of using 16x16 multiplies anyway,
  171396. * so we use a much larger scaling factor to preserve accuracy.
  171397. *
  171398. * A final compromise is to represent the multiplicative constants to only
  171399. * 8 fractional bits, rather than 13. This saves some shifting work on some
  171400. * machines, and may also reduce the cost of multiplication (since there
  171401. * are fewer one-bits in the constants).
  171402. */
  171403. #if BITS_IN_JSAMPLE == 8
  171404. #define CONST_BITS 8
  171405. #define PASS1_BITS 2
  171406. #else
  171407. #define CONST_BITS 8
  171408. #define PASS1_BITS 1 /* lose a little precision to avoid overflow */
  171409. #endif
  171410. /* Some C compilers fail to reduce "FIX(constant)" at compile time, thus
  171411. * causing a lot of useless floating-point operations at run time.
  171412. * To get around this we use the following pre-calculated constants.
  171413. * If you change CONST_BITS you may want to add appropriate values.
  171414. * (With a reasonable C compiler, you can just rely on the FIX() macro...)
  171415. */
  171416. #if CONST_BITS == 8
  171417. #define FIX_1_082392200 ((INT32) 277) /* FIX(1.082392200) */
  171418. #define FIX_1_414213562 ((INT32) 362) /* FIX(1.414213562) */
  171419. #define FIX_1_847759065 ((INT32) 473) /* FIX(1.847759065) */
  171420. #define FIX_2_613125930 ((INT32) 669) /* FIX(2.613125930) */
  171421. #else
  171422. #define FIX_1_082392200 FIX(1.082392200)
  171423. #define FIX_1_414213562 FIX(1.414213562)
  171424. #define FIX_1_847759065 FIX(1.847759065)
  171425. #define FIX_2_613125930 FIX(2.613125930)
  171426. #endif
  171427. /* We can gain a little more speed, with a further compromise in accuracy,
  171428. * by omitting the addition in a descaling shift. This yields an incorrectly
  171429. * rounded result half the time...
  171430. */
  171431. #ifndef USE_ACCURATE_ROUNDING
  171432. #undef DESCALE
  171433. #define DESCALE(x,n) RIGHT_SHIFT(x, n)
  171434. #endif
  171435. /* Multiply a DCTELEM variable by an INT32 constant, and immediately
  171436. * descale to yield a DCTELEM result.
  171437. */
  171438. #define MULTIPLY(var,const) ((DCTELEM) DESCALE((var) * (const), CONST_BITS))
  171439. /* Dequantize a coefficient by multiplying it by the multiplier-table
  171440. * entry; produce a DCTELEM result. For 8-bit data a 16x16->16
  171441. * multiplication will do. For 12-bit data, the multiplier table is
  171442. * declared INT32, so a 32-bit multiply will be used.
  171443. */
  171444. #if BITS_IN_JSAMPLE == 8
  171445. #define DEQUANTIZE(coef,quantval) (((IFAST_MULT_TYPE) (coef)) * (quantval))
  171446. #else
  171447. #define DEQUANTIZE(coef,quantval) \
  171448. DESCALE((coef)*(quantval), IFAST_SCALE_BITS-PASS1_BITS)
  171449. #endif
  171450. /* Like DESCALE, but applies to a DCTELEM and produces an int.
  171451. * We assume that int right shift is unsigned if INT32 right shift is.
  171452. */
  171453. #ifdef RIGHT_SHIFT_IS_UNSIGNED
  171454. #define ISHIFT_TEMPS DCTELEM ishift_temp;
  171455. #if BITS_IN_JSAMPLE == 8
  171456. #define DCTELEMBITS 16 /* DCTELEM may be 16 or 32 bits */
  171457. #else
  171458. #define DCTELEMBITS 32 /* DCTELEM must be 32 bits */
  171459. #endif
  171460. #define IRIGHT_SHIFT(x,shft) \
  171461. ((ishift_temp = (x)) < 0 ? \
  171462. (ishift_temp >> (shft)) | ((~((DCTELEM) 0)) << (DCTELEMBITS-(shft))) : \
  171463. (ishift_temp >> (shft)))
  171464. #else
  171465. #define ISHIFT_TEMPS
  171466. #define IRIGHT_SHIFT(x,shft) ((x) >> (shft))
  171467. #endif
  171468. #ifdef USE_ACCURATE_ROUNDING
  171469. #define IDESCALE(x,n) ((int) IRIGHT_SHIFT((x) + (1 << ((n)-1)), n))
  171470. #else
  171471. #define IDESCALE(x,n) ((int) IRIGHT_SHIFT(x, n))
  171472. #endif
  171473. /*
  171474. * Perform dequantization and inverse DCT on one block of coefficients.
  171475. */
  171476. GLOBAL(void)
  171477. jpeg_idct_ifast (j_decompress_ptr cinfo, jpeg_component_info * compptr,
  171478. JCOEFPTR coef_block,
  171479. JSAMPARRAY output_buf, JDIMENSION output_col)
  171480. {
  171481. DCTELEM tmp0, tmp1, tmp2, tmp3, tmp4, tmp5, tmp6, tmp7;
  171482. DCTELEM tmp10, tmp11, tmp12, tmp13;
  171483. DCTELEM z5, z10, z11, z12, z13;
  171484. JCOEFPTR inptr;
  171485. IFAST_MULT_TYPE * quantptr;
  171486. int * wsptr;
  171487. JSAMPROW outptr;
  171488. JSAMPLE *range_limit = IDCT_range_limit(cinfo);
  171489. int ctr;
  171490. int workspace[DCTSIZE2]; /* buffers data between passes */
  171491. SHIFT_TEMPS /* for DESCALE */
  171492. ISHIFT_TEMPS /* for IDESCALE */
  171493. /* Pass 1: process columns from input, store into work array. */
  171494. inptr = coef_block;
  171495. quantptr = (IFAST_MULT_TYPE *) compptr->dct_table;
  171496. wsptr = workspace;
  171497. for (ctr = DCTSIZE; ctr > 0; ctr--) {
  171498. /* Due to quantization, we will usually find that many of the input
  171499. * coefficients are zero, especially the AC terms. We can exploit this
  171500. * by short-circuiting the IDCT calculation for any column in which all
  171501. * the AC terms are zero. In that case each output is equal to the
  171502. * DC coefficient (with scale factor as needed).
  171503. * With typical images and quantization tables, half or more of the
  171504. * column DCT calculations can be simplified this way.
  171505. */
  171506. if (inptr[DCTSIZE*1] == 0 && inptr[DCTSIZE*2] == 0 &&
  171507. inptr[DCTSIZE*3] == 0 && inptr[DCTSIZE*4] == 0 &&
  171508. inptr[DCTSIZE*5] == 0 && inptr[DCTSIZE*6] == 0 &&
  171509. inptr[DCTSIZE*7] == 0) {
  171510. /* AC terms all zero */
  171511. int dcval = (int) DEQUANTIZE(inptr[DCTSIZE*0], quantptr[DCTSIZE*0]);
  171512. wsptr[DCTSIZE*0] = dcval;
  171513. wsptr[DCTSIZE*1] = dcval;
  171514. wsptr[DCTSIZE*2] = dcval;
  171515. wsptr[DCTSIZE*3] = dcval;
  171516. wsptr[DCTSIZE*4] = dcval;
  171517. wsptr[DCTSIZE*5] = dcval;
  171518. wsptr[DCTSIZE*6] = dcval;
  171519. wsptr[DCTSIZE*7] = dcval;
  171520. inptr++; /* advance pointers to next column */
  171521. quantptr++;
  171522. wsptr++;
  171523. continue;
  171524. }
  171525. /* Even part */
  171526. tmp0 = DEQUANTIZE(inptr[DCTSIZE*0], quantptr[DCTSIZE*0]);
  171527. tmp1 = DEQUANTIZE(inptr[DCTSIZE*2], quantptr[DCTSIZE*2]);
  171528. tmp2 = DEQUANTIZE(inptr[DCTSIZE*4], quantptr[DCTSIZE*4]);
  171529. tmp3 = DEQUANTIZE(inptr[DCTSIZE*6], quantptr[DCTSIZE*6]);
  171530. tmp10 = tmp0 + tmp2; /* phase 3 */
  171531. tmp11 = tmp0 - tmp2;
  171532. tmp13 = tmp1 + tmp3; /* phases 5-3 */
  171533. tmp12 = MULTIPLY(tmp1 - tmp3, FIX_1_414213562) - tmp13; /* 2*c4 */
  171534. tmp0 = tmp10 + tmp13; /* phase 2 */
  171535. tmp3 = tmp10 - tmp13;
  171536. tmp1 = tmp11 + tmp12;
  171537. tmp2 = tmp11 - tmp12;
  171538. /* Odd part */
  171539. tmp4 = DEQUANTIZE(inptr[DCTSIZE*1], quantptr[DCTSIZE*1]);
  171540. tmp5 = DEQUANTIZE(inptr[DCTSIZE*3], quantptr[DCTSIZE*3]);
  171541. tmp6 = DEQUANTIZE(inptr[DCTSIZE*5], quantptr[DCTSIZE*5]);
  171542. tmp7 = DEQUANTIZE(inptr[DCTSIZE*7], quantptr[DCTSIZE*7]);
  171543. z13 = tmp6 + tmp5; /* phase 6 */
  171544. z10 = tmp6 - tmp5;
  171545. z11 = tmp4 + tmp7;
  171546. z12 = tmp4 - tmp7;
  171547. tmp7 = z11 + z13; /* phase 5 */
  171548. tmp11 = MULTIPLY(z11 - z13, FIX_1_414213562); /* 2*c4 */
  171549. z5 = MULTIPLY(z10 + z12, FIX_1_847759065); /* 2*c2 */
  171550. tmp10 = MULTIPLY(z12, FIX_1_082392200) - z5; /* 2*(c2-c6) */
  171551. tmp12 = MULTIPLY(z10, - FIX_2_613125930) + z5; /* -2*(c2+c6) */
  171552. tmp6 = tmp12 - tmp7; /* phase 2 */
  171553. tmp5 = tmp11 - tmp6;
  171554. tmp4 = tmp10 + tmp5;
  171555. wsptr[DCTSIZE*0] = (int) (tmp0 + tmp7);
  171556. wsptr[DCTSIZE*7] = (int) (tmp0 - tmp7);
  171557. wsptr[DCTSIZE*1] = (int) (tmp1 + tmp6);
  171558. wsptr[DCTSIZE*6] = (int) (tmp1 - tmp6);
  171559. wsptr[DCTSIZE*2] = (int) (tmp2 + tmp5);
  171560. wsptr[DCTSIZE*5] = (int) (tmp2 - tmp5);
  171561. wsptr[DCTSIZE*4] = (int) (tmp3 + tmp4);
  171562. wsptr[DCTSIZE*3] = (int) (tmp3 - tmp4);
  171563. inptr++; /* advance pointers to next column */
  171564. quantptr++;
  171565. wsptr++;
  171566. }
  171567. /* Pass 2: process rows from work array, store into output array. */
  171568. /* Note that we must descale the results by a factor of 8 == 2**3, */
  171569. /* and also undo the PASS1_BITS scaling. */
  171570. wsptr = workspace;
  171571. for (ctr = 0; ctr < DCTSIZE; ctr++) {
  171572. outptr = output_buf[ctr] + output_col;
  171573. /* Rows of zeroes can be exploited in the same way as we did with columns.
  171574. * However, the column calculation has created many nonzero AC terms, so
  171575. * the simplification applies less often (typically 5% to 10% of the time).
  171576. * On machines with very fast multiplication, it's possible that the
  171577. * test takes more time than it's worth. In that case this section
  171578. * may be commented out.
  171579. */
  171580. #ifndef NO_ZERO_ROW_TEST
  171581. if (wsptr[1] == 0 && wsptr[2] == 0 && wsptr[3] == 0 && wsptr[4] == 0 &&
  171582. wsptr[5] == 0 && wsptr[6] == 0 && wsptr[7] == 0) {
  171583. /* AC terms all zero */
  171584. JSAMPLE dcval = range_limit[IDESCALE(wsptr[0], PASS1_BITS+3)
  171585. & RANGE_MASK];
  171586. outptr[0] = dcval;
  171587. outptr[1] = dcval;
  171588. outptr[2] = dcval;
  171589. outptr[3] = dcval;
  171590. outptr[4] = dcval;
  171591. outptr[5] = dcval;
  171592. outptr[6] = dcval;
  171593. outptr[7] = dcval;
  171594. wsptr += DCTSIZE; /* advance pointer to next row */
  171595. continue;
  171596. }
  171597. #endif
  171598. /* Even part */
  171599. tmp10 = ((DCTELEM) wsptr[0] + (DCTELEM) wsptr[4]);
  171600. tmp11 = ((DCTELEM) wsptr[0] - (DCTELEM) wsptr[4]);
  171601. tmp13 = ((DCTELEM) wsptr[2] + (DCTELEM) wsptr[6]);
  171602. tmp12 = MULTIPLY((DCTELEM) wsptr[2] - (DCTELEM) wsptr[6], FIX_1_414213562)
  171603. - tmp13;
  171604. tmp0 = tmp10 + tmp13;
  171605. tmp3 = tmp10 - tmp13;
  171606. tmp1 = tmp11 + tmp12;
  171607. tmp2 = tmp11 - tmp12;
  171608. /* Odd part */
  171609. z13 = (DCTELEM) wsptr[5] + (DCTELEM) wsptr[3];
  171610. z10 = (DCTELEM) wsptr[5] - (DCTELEM) wsptr[3];
  171611. z11 = (DCTELEM) wsptr[1] + (DCTELEM) wsptr[7];
  171612. z12 = (DCTELEM) wsptr[1] - (DCTELEM) wsptr[7];
  171613. tmp7 = z11 + z13; /* phase 5 */
  171614. tmp11 = MULTIPLY(z11 - z13, FIX_1_414213562); /* 2*c4 */
  171615. z5 = MULTIPLY(z10 + z12, FIX_1_847759065); /* 2*c2 */
  171616. tmp10 = MULTIPLY(z12, FIX_1_082392200) - z5; /* 2*(c2-c6) */
  171617. tmp12 = MULTIPLY(z10, - FIX_2_613125930) + z5; /* -2*(c2+c6) */
  171618. tmp6 = tmp12 - tmp7; /* phase 2 */
  171619. tmp5 = tmp11 - tmp6;
  171620. tmp4 = tmp10 + tmp5;
  171621. /* Final output stage: scale down by a factor of 8 and range-limit */
  171622. outptr[0] = range_limit[IDESCALE(tmp0 + tmp7, PASS1_BITS+3)
  171623. & RANGE_MASK];
  171624. outptr[7] = range_limit[IDESCALE(tmp0 - tmp7, PASS1_BITS+3)
  171625. & RANGE_MASK];
  171626. outptr[1] = range_limit[IDESCALE(tmp1 + tmp6, PASS1_BITS+3)
  171627. & RANGE_MASK];
  171628. outptr[6] = range_limit[IDESCALE(tmp1 - tmp6, PASS1_BITS+3)
  171629. & RANGE_MASK];
  171630. outptr[2] = range_limit[IDESCALE(tmp2 + tmp5, PASS1_BITS+3)
  171631. & RANGE_MASK];
  171632. outptr[5] = range_limit[IDESCALE(tmp2 - tmp5, PASS1_BITS+3)
  171633. & RANGE_MASK];
  171634. outptr[4] = range_limit[IDESCALE(tmp3 + tmp4, PASS1_BITS+3)
  171635. & RANGE_MASK];
  171636. outptr[3] = range_limit[IDESCALE(tmp3 - tmp4, PASS1_BITS+3)
  171637. & RANGE_MASK];
  171638. wsptr += DCTSIZE; /* advance pointer to next row */
  171639. }
  171640. }
  171641. #endif /* DCT_IFAST_SUPPORTED */
  171642. /*** End of inlined file: jidctfst.c ***/
  171643. #undef CONST_BITS
  171644. #undef FIX_1_847759065
  171645. #undef MULTIPLY
  171646. #undef DEQUANTIZE
  171647. /*** Start of inlined file: jidctint.c ***/
  171648. #define JPEG_INTERNALS
  171649. #ifdef DCT_ISLOW_SUPPORTED
  171650. /*
  171651. * This module is specialized to the case DCTSIZE = 8.
  171652. */
  171653. #if DCTSIZE != 8
  171654. Sorry, this code only copes with 8x8 DCTs. /* deliberate syntax err */
  171655. #endif
  171656. /*
  171657. * The poop on this scaling stuff is as follows:
  171658. *
  171659. * Each 1-D IDCT step produces outputs which are a factor of sqrt(N)
  171660. * larger than the true IDCT outputs. The final outputs are therefore
  171661. * a factor of N larger than desired; since N=8 this can be cured by
  171662. * a simple right shift at the end of the algorithm. The advantage of
  171663. * this arrangement is that we save two multiplications per 1-D IDCT,
  171664. * because the y0 and y4 inputs need not be divided by sqrt(N).
  171665. *
  171666. * We have to do addition and subtraction of the integer inputs, which
  171667. * is no problem, and multiplication by fractional constants, which is
  171668. * a problem to do in integer arithmetic. We multiply all the constants
  171669. * by CONST_SCALE and convert them to integer constants (thus retaining
  171670. * CONST_BITS bits of precision in the constants). After doing a
  171671. * multiplication we have to divide the product by CONST_SCALE, with proper
  171672. * rounding, to produce the correct output. This division can be done
  171673. * cheaply as a right shift of CONST_BITS bits. We postpone shifting
  171674. * as long as possible so that partial sums can be added together with
  171675. * full fractional precision.
  171676. *
  171677. * The outputs of the first pass are scaled up by PASS1_BITS bits so that
  171678. * they are represented to better-than-integral precision. These outputs
  171679. * require BITS_IN_JSAMPLE + PASS1_BITS + 3 bits; this fits in a 16-bit word
  171680. * with the recommended scaling. (To scale up 12-bit sample data further, an
  171681. * intermediate INT32 array would be needed.)
  171682. *
  171683. * To avoid overflow of the 32-bit intermediate results in pass 2, we must
  171684. * have BITS_IN_JSAMPLE + CONST_BITS + PASS1_BITS <= 26. Error analysis
  171685. * shows that the values given below are the most effective.
  171686. */
  171687. #if BITS_IN_JSAMPLE == 8
  171688. #define CONST_BITS 13
  171689. #define PASS1_BITS 2
  171690. #else
  171691. #define CONST_BITS 13
  171692. #define PASS1_BITS 1 /* lose a little precision to avoid overflow */
  171693. #endif
  171694. /* Some C compilers fail to reduce "FIX(constant)" at compile time, thus
  171695. * causing a lot of useless floating-point operations at run time.
  171696. * To get around this we use the following pre-calculated constants.
  171697. * If you change CONST_BITS you may want to add appropriate values.
  171698. * (With a reasonable C compiler, you can just rely on the FIX() macro...)
  171699. */
  171700. #if CONST_BITS == 13
  171701. #define FIX_0_298631336 ((INT32) 2446) /* FIX(0.298631336) */
  171702. #define FIX_0_390180644 ((INT32) 3196) /* FIX(0.390180644) */
  171703. #define FIX_0_541196100 ((INT32) 4433) /* FIX(0.541196100) */
  171704. #define FIX_0_765366865 ((INT32) 6270) /* FIX(0.765366865) */
  171705. #define FIX_0_899976223 ((INT32) 7373) /* FIX(0.899976223) */
  171706. #define FIX_1_175875602 ((INT32) 9633) /* FIX(1.175875602) */
  171707. #define FIX_1_501321110 ((INT32) 12299) /* FIX(1.501321110) */
  171708. #define FIX_1_847759065 ((INT32) 15137) /* FIX(1.847759065) */
  171709. #define FIX_1_961570560 ((INT32) 16069) /* FIX(1.961570560) */
  171710. #define FIX_2_053119869 ((INT32) 16819) /* FIX(2.053119869) */
  171711. #define FIX_2_562915447 ((INT32) 20995) /* FIX(2.562915447) */
  171712. #define FIX_3_072711026 ((INT32) 25172) /* FIX(3.072711026) */
  171713. #else
  171714. #define FIX_0_298631336 FIX(0.298631336)
  171715. #define FIX_0_390180644 FIX(0.390180644)
  171716. #define FIX_0_541196100 FIX(0.541196100)
  171717. #define FIX_0_765366865 FIX(0.765366865)
  171718. #define FIX_0_899976223 FIX(0.899976223)
  171719. #define FIX_1_175875602 FIX(1.175875602)
  171720. #define FIX_1_501321110 FIX(1.501321110)
  171721. #define FIX_1_847759065 FIX(1.847759065)
  171722. #define FIX_1_961570560 FIX(1.961570560)
  171723. #define FIX_2_053119869 FIX(2.053119869)
  171724. #define FIX_2_562915447 FIX(2.562915447)
  171725. #define FIX_3_072711026 FIX(3.072711026)
  171726. #endif
  171727. /* Multiply an INT32 variable by an INT32 constant to yield an INT32 result.
  171728. * For 8-bit samples with the recommended scaling, all the variable
  171729. * and constant values involved are no more than 16 bits wide, so a
  171730. * 16x16->32 bit multiply can be used instead of a full 32x32 multiply.
  171731. * For 12-bit samples, a full 32-bit multiplication will be needed.
  171732. */
  171733. #if BITS_IN_JSAMPLE == 8
  171734. #define MULTIPLY(var,const) MULTIPLY16C16(var,const)
  171735. #else
  171736. #define MULTIPLY(var,const) ((var) * (const))
  171737. #endif
  171738. /* Dequantize a coefficient by multiplying it by the multiplier-table
  171739. * entry; produce an int result. In this module, both inputs and result
  171740. * are 16 bits or less, so either int or short multiply will work.
  171741. */
  171742. #define DEQUANTIZE(coef,quantval) (((ISLOW_MULT_TYPE) (coef)) * (quantval))
  171743. /*
  171744. * Perform dequantization and inverse DCT on one block of coefficients.
  171745. */
  171746. GLOBAL(void)
  171747. jpeg_idct_islow (j_decompress_ptr cinfo, jpeg_component_info * compptr,
  171748. JCOEFPTR coef_block,
  171749. JSAMPARRAY output_buf, JDIMENSION output_col)
  171750. {
  171751. INT32 tmp0, tmp1, tmp2, tmp3;
  171752. INT32 tmp10, tmp11, tmp12, tmp13;
  171753. INT32 z1, z2, z3, z4, z5;
  171754. JCOEFPTR inptr;
  171755. ISLOW_MULT_TYPE * quantptr;
  171756. int * wsptr;
  171757. JSAMPROW outptr;
  171758. JSAMPLE *range_limit = IDCT_range_limit(cinfo);
  171759. int ctr;
  171760. int workspace[DCTSIZE2]; /* buffers data between passes */
  171761. SHIFT_TEMPS
  171762. /* Pass 1: process columns from input, store into work array. */
  171763. /* Note results are scaled up by sqrt(8) compared to a true IDCT; */
  171764. /* furthermore, we scale the results by 2**PASS1_BITS. */
  171765. inptr = coef_block;
  171766. quantptr = (ISLOW_MULT_TYPE *) compptr->dct_table;
  171767. wsptr = workspace;
  171768. for (ctr = DCTSIZE; ctr > 0; ctr--) {
  171769. /* Due to quantization, we will usually find that many of the input
  171770. * coefficients are zero, especially the AC terms. We can exploit this
  171771. * by short-circuiting the IDCT calculation for any column in which all
  171772. * the AC terms are zero. In that case each output is equal to the
  171773. * DC coefficient (with scale factor as needed).
  171774. * With typical images and quantization tables, half or more of the
  171775. * column DCT calculations can be simplified this way.
  171776. */
  171777. if (inptr[DCTSIZE*1] == 0 && inptr[DCTSIZE*2] == 0 &&
  171778. inptr[DCTSIZE*3] == 0 && inptr[DCTSIZE*4] == 0 &&
  171779. inptr[DCTSIZE*5] == 0 && inptr[DCTSIZE*6] == 0 &&
  171780. inptr[DCTSIZE*7] == 0) {
  171781. /* AC terms all zero */
  171782. int dcval = DEQUANTIZE(inptr[DCTSIZE*0], quantptr[DCTSIZE*0]) << PASS1_BITS;
  171783. wsptr[DCTSIZE*0] = dcval;
  171784. wsptr[DCTSIZE*1] = dcval;
  171785. wsptr[DCTSIZE*2] = dcval;
  171786. wsptr[DCTSIZE*3] = dcval;
  171787. wsptr[DCTSIZE*4] = dcval;
  171788. wsptr[DCTSIZE*5] = dcval;
  171789. wsptr[DCTSIZE*6] = dcval;
  171790. wsptr[DCTSIZE*7] = dcval;
  171791. inptr++; /* advance pointers to next column */
  171792. quantptr++;
  171793. wsptr++;
  171794. continue;
  171795. }
  171796. /* Even part: reverse the even part of the forward DCT. */
  171797. /* The rotator is sqrt(2)*c(-6). */
  171798. z2 = DEQUANTIZE(inptr[DCTSIZE*2], quantptr[DCTSIZE*2]);
  171799. z3 = DEQUANTIZE(inptr[DCTSIZE*6], quantptr[DCTSIZE*6]);
  171800. z1 = MULTIPLY(z2 + z3, FIX_0_541196100);
  171801. tmp2 = z1 + MULTIPLY(z3, - FIX_1_847759065);
  171802. tmp3 = z1 + MULTIPLY(z2, FIX_0_765366865);
  171803. z2 = DEQUANTIZE(inptr[DCTSIZE*0], quantptr[DCTSIZE*0]);
  171804. z3 = DEQUANTIZE(inptr[DCTSIZE*4], quantptr[DCTSIZE*4]);
  171805. tmp0 = (z2 + z3) << CONST_BITS;
  171806. tmp1 = (z2 - z3) << CONST_BITS;
  171807. tmp10 = tmp0 + tmp3;
  171808. tmp13 = tmp0 - tmp3;
  171809. tmp11 = tmp1 + tmp2;
  171810. tmp12 = tmp1 - tmp2;
  171811. /* Odd part per figure 8; the matrix is unitary and hence its
  171812. * transpose is its inverse. i0..i3 are y7,y5,y3,y1 respectively.
  171813. */
  171814. tmp0 = DEQUANTIZE(inptr[DCTSIZE*7], quantptr[DCTSIZE*7]);
  171815. tmp1 = DEQUANTIZE(inptr[DCTSIZE*5], quantptr[DCTSIZE*5]);
  171816. tmp2 = DEQUANTIZE(inptr[DCTSIZE*3], quantptr[DCTSIZE*3]);
  171817. tmp3 = DEQUANTIZE(inptr[DCTSIZE*1], quantptr[DCTSIZE*1]);
  171818. z1 = tmp0 + tmp3;
  171819. z2 = tmp1 + tmp2;
  171820. z3 = tmp0 + tmp2;
  171821. z4 = tmp1 + tmp3;
  171822. z5 = MULTIPLY(z3 + z4, FIX_1_175875602); /* sqrt(2) * c3 */
  171823. tmp0 = MULTIPLY(tmp0, FIX_0_298631336); /* sqrt(2) * (-c1+c3+c5-c7) */
  171824. tmp1 = MULTIPLY(tmp1, FIX_2_053119869); /* sqrt(2) * ( c1+c3-c5+c7) */
  171825. tmp2 = MULTIPLY(tmp2, FIX_3_072711026); /* sqrt(2) * ( c1+c3+c5-c7) */
  171826. tmp3 = MULTIPLY(tmp3, FIX_1_501321110); /* sqrt(2) * ( c1+c3-c5-c7) */
  171827. z1 = MULTIPLY(z1, - FIX_0_899976223); /* sqrt(2) * (c7-c3) */
  171828. z2 = MULTIPLY(z2, - FIX_2_562915447); /* sqrt(2) * (-c1-c3) */
  171829. z3 = MULTIPLY(z3, - FIX_1_961570560); /* sqrt(2) * (-c3-c5) */
  171830. z4 = MULTIPLY(z4, - FIX_0_390180644); /* sqrt(2) * (c5-c3) */
  171831. z3 += z5;
  171832. z4 += z5;
  171833. tmp0 += z1 + z3;
  171834. tmp1 += z2 + z4;
  171835. tmp2 += z2 + z3;
  171836. tmp3 += z1 + z4;
  171837. /* Final output stage: inputs are tmp10..tmp13, tmp0..tmp3 */
  171838. wsptr[DCTSIZE*0] = (int) DESCALE(tmp10 + tmp3, CONST_BITS-PASS1_BITS);
  171839. wsptr[DCTSIZE*7] = (int) DESCALE(tmp10 - tmp3, CONST_BITS-PASS1_BITS);
  171840. wsptr[DCTSIZE*1] = (int) DESCALE(tmp11 + tmp2, CONST_BITS-PASS1_BITS);
  171841. wsptr[DCTSIZE*6] = (int) DESCALE(tmp11 - tmp2, CONST_BITS-PASS1_BITS);
  171842. wsptr[DCTSIZE*2] = (int) DESCALE(tmp12 + tmp1, CONST_BITS-PASS1_BITS);
  171843. wsptr[DCTSIZE*5] = (int) DESCALE(tmp12 - tmp1, CONST_BITS-PASS1_BITS);
  171844. wsptr[DCTSIZE*3] = (int) DESCALE(tmp13 + tmp0, CONST_BITS-PASS1_BITS);
  171845. wsptr[DCTSIZE*4] = (int) DESCALE(tmp13 - tmp0, CONST_BITS-PASS1_BITS);
  171846. inptr++; /* advance pointers to next column */
  171847. quantptr++;
  171848. wsptr++;
  171849. }
  171850. /* Pass 2: process rows from work array, store into output array. */
  171851. /* Note that we must descale the results by a factor of 8 == 2**3, */
  171852. /* and also undo the PASS1_BITS scaling. */
  171853. wsptr = workspace;
  171854. for (ctr = 0; ctr < DCTSIZE; ctr++) {
  171855. outptr = output_buf[ctr] + output_col;
  171856. /* Rows of zeroes can be exploited in the same way as we did with columns.
  171857. * However, the column calculation has created many nonzero AC terms, so
  171858. * the simplification applies less often (typically 5% to 10% of the time).
  171859. * On machines with very fast multiplication, it's possible that the
  171860. * test takes more time than it's worth. In that case this section
  171861. * may be commented out.
  171862. */
  171863. #ifndef NO_ZERO_ROW_TEST
  171864. if (wsptr[1] == 0 && wsptr[2] == 0 && wsptr[3] == 0 && wsptr[4] == 0 &&
  171865. wsptr[5] == 0 && wsptr[6] == 0 && wsptr[7] == 0) {
  171866. /* AC terms all zero */
  171867. JSAMPLE dcval = range_limit[(int) DESCALE((INT32) wsptr[0], PASS1_BITS+3)
  171868. & RANGE_MASK];
  171869. outptr[0] = dcval;
  171870. outptr[1] = dcval;
  171871. outptr[2] = dcval;
  171872. outptr[3] = dcval;
  171873. outptr[4] = dcval;
  171874. outptr[5] = dcval;
  171875. outptr[6] = dcval;
  171876. outptr[7] = dcval;
  171877. wsptr += DCTSIZE; /* advance pointer to next row */
  171878. continue;
  171879. }
  171880. #endif
  171881. /* Even part: reverse the even part of the forward DCT. */
  171882. /* The rotator is sqrt(2)*c(-6). */
  171883. z2 = (INT32) wsptr[2];
  171884. z3 = (INT32) wsptr[6];
  171885. z1 = MULTIPLY(z2 + z3, FIX_0_541196100);
  171886. tmp2 = z1 + MULTIPLY(z3, - FIX_1_847759065);
  171887. tmp3 = z1 + MULTIPLY(z2, FIX_0_765366865);
  171888. tmp0 = ((INT32) wsptr[0] + (INT32) wsptr[4]) << CONST_BITS;
  171889. tmp1 = ((INT32) wsptr[0] - (INT32) wsptr[4]) << CONST_BITS;
  171890. tmp10 = tmp0 + tmp3;
  171891. tmp13 = tmp0 - tmp3;
  171892. tmp11 = tmp1 + tmp2;
  171893. tmp12 = tmp1 - tmp2;
  171894. /* Odd part per figure 8; the matrix is unitary and hence its
  171895. * transpose is its inverse. i0..i3 are y7,y5,y3,y1 respectively.
  171896. */
  171897. tmp0 = (INT32) wsptr[7];
  171898. tmp1 = (INT32) wsptr[5];
  171899. tmp2 = (INT32) wsptr[3];
  171900. tmp3 = (INT32) wsptr[1];
  171901. z1 = tmp0 + tmp3;
  171902. z2 = tmp1 + tmp2;
  171903. z3 = tmp0 + tmp2;
  171904. z4 = tmp1 + tmp3;
  171905. z5 = MULTIPLY(z3 + z4, FIX_1_175875602); /* sqrt(2) * c3 */
  171906. tmp0 = MULTIPLY(tmp0, FIX_0_298631336); /* sqrt(2) * (-c1+c3+c5-c7) */
  171907. tmp1 = MULTIPLY(tmp1, FIX_2_053119869); /* sqrt(2) * ( c1+c3-c5+c7) */
  171908. tmp2 = MULTIPLY(tmp2, FIX_3_072711026); /* sqrt(2) * ( c1+c3+c5-c7) */
  171909. tmp3 = MULTIPLY(tmp3, FIX_1_501321110); /* sqrt(2) * ( c1+c3-c5-c7) */
  171910. z1 = MULTIPLY(z1, - FIX_0_899976223); /* sqrt(2) * (c7-c3) */
  171911. z2 = MULTIPLY(z2, - FIX_2_562915447); /* sqrt(2) * (-c1-c3) */
  171912. z3 = MULTIPLY(z3, - FIX_1_961570560); /* sqrt(2) * (-c3-c5) */
  171913. z4 = MULTIPLY(z4, - FIX_0_390180644); /* sqrt(2) * (c5-c3) */
  171914. z3 += z5;
  171915. z4 += z5;
  171916. tmp0 += z1 + z3;
  171917. tmp1 += z2 + z4;
  171918. tmp2 += z2 + z3;
  171919. tmp3 += z1 + z4;
  171920. /* Final output stage: inputs are tmp10..tmp13, tmp0..tmp3 */
  171921. outptr[0] = range_limit[(int) DESCALE(tmp10 + tmp3,
  171922. CONST_BITS+PASS1_BITS+3)
  171923. & RANGE_MASK];
  171924. outptr[7] = range_limit[(int) DESCALE(tmp10 - tmp3,
  171925. CONST_BITS+PASS1_BITS+3)
  171926. & RANGE_MASK];
  171927. outptr[1] = range_limit[(int) DESCALE(tmp11 + tmp2,
  171928. CONST_BITS+PASS1_BITS+3)
  171929. & RANGE_MASK];
  171930. outptr[6] = range_limit[(int) DESCALE(tmp11 - tmp2,
  171931. CONST_BITS+PASS1_BITS+3)
  171932. & RANGE_MASK];
  171933. outptr[2] = range_limit[(int) DESCALE(tmp12 + tmp1,
  171934. CONST_BITS+PASS1_BITS+3)
  171935. & RANGE_MASK];
  171936. outptr[5] = range_limit[(int) DESCALE(tmp12 - tmp1,
  171937. CONST_BITS+PASS1_BITS+3)
  171938. & RANGE_MASK];
  171939. outptr[3] = range_limit[(int) DESCALE(tmp13 + tmp0,
  171940. CONST_BITS+PASS1_BITS+3)
  171941. & RANGE_MASK];
  171942. outptr[4] = range_limit[(int) DESCALE(tmp13 - tmp0,
  171943. CONST_BITS+PASS1_BITS+3)
  171944. & RANGE_MASK];
  171945. wsptr += DCTSIZE; /* advance pointer to next row */
  171946. }
  171947. }
  171948. #endif /* DCT_ISLOW_SUPPORTED */
  171949. /*** End of inlined file: jidctint.c ***/
  171950. /*** Start of inlined file: jidctred.c ***/
  171951. #define JPEG_INTERNALS
  171952. #ifdef IDCT_SCALING_SUPPORTED
  171953. /*
  171954. * This module is specialized to the case DCTSIZE = 8.
  171955. */
  171956. #if DCTSIZE != 8
  171957. Sorry, this code only copes with 8x8 DCTs. /* deliberate syntax err */
  171958. #endif
  171959. /* Scaling is the same as in jidctint.c. */
  171960. #if BITS_IN_JSAMPLE == 8
  171961. #define CONST_BITS 13
  171962. #define PASS1_BITS 2
  171963. #else
  171964. #define CONST_BITS 13
  171965. #define PASS1_BITS 1 /* lose a little precision to avoid overflow */
  171966. #endif
  171967. /* Some C compilers fail to reduce "FIX(constant)" at compile time, thus
  171968. * causing a lot of useless floating-point operations at run time.
  171969. * To get around this we use the following pre-calculated constants.
  171970. * If you change CONST_BITS you may want to add appropriate values.
  171971. * (With a reasonable C compiler, you can just rely on the FIX() macro...)
  171972. */
  171973. #if CONST_BITS == 13
  171974. #define FIX_0_211164243 ((INT32) 1730) /* FIX(0.211164243) */
  171975. #define FIX_0_509795579 ((INT32) 4176) /* FIX(0.509795579) */
  171976. #define FIX_0_601344887 ((INT32) 4926) /* FIX(0.601344887) */
  171977. #define FIX_0_720959822 ((INT32) 5906) /* FIX(0.720959822) */
  171978. #define FIX_0_765366865 ((INT32) 6270) /* FIX(0.765366865) */
  171979. #define FIX_0_850430095 ((INT32) 6967) /* FIX(0.850430095) */
  171980. #define FIX_0_899976223 ((INT32) 7373) /* FIX(0.899976223) */
  171981. #define FIX_1_061594337 ((INT32) 8697) /* FIX(1.061594337) */
  171982. #define FIX_1_272758580 ((INT32) 10426) /* FIX(1.272758580) */
  171983. #define FIX_1_451774981 ((INT32) 11893) /* FIX(1.451774981) */
  171984. #define FIX_1_847759065 ((INT32) 15137) /* FIX(1.847759065) */
  171985. #define FIX_2_172734803 ((INT32) 17799) /* FIX(2.172734803) */
  171986. #define FIX_2_562915447 ((INT32) 20995) /* FIX(2.562915447) */
  171987. #define FIX_3_624509785 ((INT32) 29692) /* FIX(3.624509785) */
  171988. #else
  171989. #define FIX_0_211164243 FIX(0.211164243)
  171990. #define FIX_0_509795579 FIX(0.509795579)
  171991. #define FIX_0_601344887 FIX(0.601344887)
  171992. #define FIX_0_720959822 FIX(0.720959822)
  171993. #define FIX_0_765366865 FIX(0.765366865)
  171994. #define FIX_0_850430095 FIX(0.850430095)
  171995. #define FIX_0_899976223 FIX(0.899976223)
  171996. #define FIX_1_061594337 FIX(1.061594337)
  171997. #define FIX_1_272758580 FIX(1.272758580)
  171998. #define FIX_1_451774981 FIX(1.451774981)
  171999. #define FIX_1_847759065 FIX(1.847759065)
  172000. #define FIX_2_172734803 FIX(2.172734803)
  172001. #define FIX_2_562915447 FIX(2.562915447)
  172002. #define FIX_3_624509785 FIX(3.624509785)
  172003. #endif
  172004. /* Multiply an INT32 variable by an INT32 constant to yield an INT32 result.
  172005. * For 8-bit samples with the recommended scaling, all the variable
  172006. * and constant values involved are no more than 16 bits wide, so a
  172007. * 16x16->32 bit multiply can be used instead of a full 32x32 multiply.
  172008. * For 12-bit samples, a full 32-bit multiplication will be needed.
  172009. */
  172010. #if BITS_IN_JSAMPLE == 8
  172011. #define MULTIPLY(var,const) MULTIPLY16C16(var,const)
  172012. #else
  172013. #define MULTIPLY(var,const) ((var) * (const))
  172014. #endif
  172015. /* Dequantize a coefficient by multiplying it by the multiplier-table
  172016. * entry; produce an int result. In this module, both inputs and result
  172017. * are 16 bits or less, so either int or short multiply will work.
  172018. */
  172019. #define DEQUANTIZE(coef,quantval) (((ISLOW_MULT_TYPE) (coef)) * (quantval))
  172020. /*
  172021. * Perform dequantization and inverse DCT on one block of coefficients,
  172022. * producing a reduced-size 4x4 output block.
  172023. */
  172024. GLOBAL(void)
  172025. jpeg_idct_4x4 (j_decompress_ptr cinfo, jpeg_component_info * compptr,
  172026. JCOEFPTR coef_block,
  172027. JSAMPARRAY output_buf, JDIMENSION output_col)
  172028. {
  172029. INT32 tmp0, tmp2, tmp10, tmp12;
  172030. INT32 z1, z2, z3, z4;
  172031. JCOEFPTR inptr;
  172032. ISLOW_MULT_TYPE * quantptr;
  172033. int * wsptr;
  172034. JSAMPROW outptr;
  172035. JSAMPLE *range_limit = IDCT_range_limit(cinfo);
  172036. int ctr;
  172037. int workspace[DCTSIZE*4]; /* buffers data between passes */
  172038. SHIFT_TEMPS
  172039. /* Pass 1: process columns from input, store into work array. */
  172040. inptr = coef_block;
  172041. quantptr = (ISLOW_MULT_TYPE *) compptr->dct_table;
  172042. wsptr = workspace;
  172043. for (ctr = DCTSIZE; ctr > 0; inptr++, quantptr++, wsptr++, ctr--) {
  172044. /* Don't bother to process column 4, because second pass won't use it */
  172045. if (ctr == DCTSIZE-4)
  172046. continue;
  172047. if (inptr[DCTSIZE*1] == 0 && inptr[DCTSIZE*2] == 0 &&
  172048. inptr[DCTSIZE*3] == 0 && inptr[DCTSIZE*5] == 0 &&
  172049. inptr[DCTSIZE*6] == 0 && inptr[DCTSIZE*7] == 0) {
  172050. /* AC terms all zero; we need not examine term 4 for 4x4 output */
  172051. int dcval = DEQUANTIZE(inptr[DCTSIZE*0], quantptr[DCTSIZE*0]) << PASS1_BITS;
  172052. wsptr[DCTSIZE*0] = dcval;
  172053. wsptr[DCTSIZE*1] = dcval;
  172054. wsptr[DCTSIZE*2] = dcval;
  172055. wsptr[DCTSIZE*3] = dcval;
  172056. continue;
  172057. }
  172058. /* Even part */
  172059. tmp0 = DEQUANTIZE(inptr[DCTSIZE*0], quantptr[DCTSIZE*0]);
  172060. tmp0 <<= (CONST_BITS+1);
  172061. z2 = DEQUANTIZE(inptr[DCTSIZE*2], quantptr[DCTSIZE*2]);
  172062. z3 = DEQUANTIZE(inptr[DCTSIZE*6], quantptr[DCTSIZE*6]);
  172063. tmp2 = MULTIPLY(z2, FIX_1_847759065) + MULTIPLY(z3, - FIX_0_765366865);
  172064. tmp10 = tmp0 + tmp2;
  172065. tmp12 = tmp0 - tmp2;
  172066. /* Odd part */
  172067. z1 = DEQUANTIZE(inptr[DCTSIZE*7], quantptr[DCTSIZE*7]);
  172068. z2 = DEQUANTIZE(inptr[DCTSIZE*5], quantptr[DCTSIZE*5]);
  172069. z3 = DEQUANTIZE(inptr[DCTSIZE*3], quantptr[DCTSIZE*3]);
  172070. z4 = DEQUANTIZE(inptr[DCTSIZE*1], quantptr[DCTSIZE*1]);
  172071. tmp0 = MULTIPLY(z1, - FIX_0_211164243) /* sqrt(2) * (c3-c1) */
  172072. + MULTIPLY(z2, FIX_1_451774981) /* sqrt(2) * (c3+c7) */
  172073. + MULTIPLY(z3, - FIX_2_172734803) /* sqrt(2) * (-c1-c5) */
  172074. + MULTIPLY(z4, FIX_1_061594337); /* sqrt(2) * (c5+c7) */
  172075. tmp2 = MULTIPLY(z1, - FIX_0_509795579) /* sqrt(2) * (c7-c5) */
  172076. + MULTIPLY(z2, - FIX_0_601344887) /* sqrt(2) * (c5-c1) */
  172077. + MULTIPLY(z3, FIX_0_899976223) /* sqrt(2) * (c3-c7) */
  172078. + MULTIPLY(z4, FIX_2_562915447); /* sqrt(2) * (c1+c3) */
  172079. /* Final output stage */
  172080. wsptr[DCTSIZE*0] = (int) DESCALE(tmp10 + tmp2, CONST_BITS-PASS1_BITS+1);
  172081. wsptr[DCTSIZE*3] = (int) DESCALE(tmp10 - tmp2, CONST_BITS-PASS1_BITS+1);
  172082. wsptr[DCTSIZE*1] = (int) DESCALE(tmp12 + tmp0, CONST_BITS-PASS1_BITS+1);
  172083. wsptr[DCTSIZE*2] = (int) DESCALE(tmp12 - tmp0, CONST_BITS-PASS1_BITS+1);
  172084. }
  172085. /* Pass 2: process 4 rows from work array, store into output array. */
  172086. wsptr = workspace;
  172087. for (ctr = 0; ctr < 4; ctr++) {
  172088. outptr = output_buf[ctr] + output_col;
  172089. /* It's not clear whether a zero row test is worthwhile here ... */
  172090. #ifndef NO_ZERO_ROW_TEST
  172091. if (wsptr[1] == 0 && wsptr[2] == 0 && wsptr[3] == 0 &&
  172092. wsptr[5] == 0 && wsptr[6] == 0 && wsptr[7] == 0) {
  172093. /* AC terms all zero */
  172094. JSAMPLE dcval = range_limit[(int) DESCALE((INT32) wsptr[0], PASS1_BITS+3)
  172095. & RANGE_MASK];
  172096. outptr[0] = dcval;
  172097. outptr[1] = dcval;
  172098. outptr[2] = dcval;
  172099. outptr[3] = dcval;
  172100. wsptr += DCTSIZE; /* advance pointer to next row */
  172101. continue;
  172102. }
  172103. #endif
  172104. /* Even part */
  172105. tmp0 = ((INT32) wsptr[0]) << (CONST_BITS+1);
  172106. tmp2 = MULTIPLY((INT32) wsptr[2], FIX_1_847759065)
  172107. + MULTIPLY((INT32) wsptr[6], - FIX_0_765366865);
  172108. tmp10 = tmp0 + tmp2;
  172109. tmp12 = tmp0 - tmp2;
  172110. /* Odd part */
  172111. z1 = (INT32) wsptr[7];
  172112. z2 = (INT32) wsptr[5];
  172113. z3 = (INT32) wsptr[3];
  172114. z4 = (INT32) wsptr[1];
  172115. tmp0 = MULTIPLY(z1, - FIX_0_211164243) /* sqrt(2) * (c3-c1) */
  172116. + MULTIPLY(z2, FIX_1_451774981) /* sqrt(2) * (c3+c7) */
  172117. + MULTIPLY(z3, - FIX_2_172734803) /* sqrt(2) * (-c1-c5) */
  172118. + MULTIPLY(z4, FIX_1_061594337); /* sqrt(2) * (c5+c7) */
  172119. tmp2 = MULTIPLY(z1, - FIX_0_509795579) /* sqrt(2) * (c7-c5) */
  172120. + MULTIPLY(z2, - FIX_0_601344887) /* sqrt(2) * (c5-c1) */
  172121. + MULTIPLY(z3, FIX_0_899976223) /* sqrt(2) * (c3-c7) */
  172122. + MULTIPLY(z4, FIX_2_562915447); /* sqrt(2) * (c1+c3) */
  172123. /* Final output stage */
  172124. outptr[0] = range_limit[(int) DESCALE(tmp10 + tmp2,
  172125. CONST_BITS+PASS1_BITS+3+1)
  172126. & RANGE_MASK];
  172127. outptr[3] = range_limit[(int) DESCALE(tmp10 - tmp2,
  172128. CONST_BITS+PASS1_BITS+3+1)
  172129. & RANGE_MASK];
  172130. outptr[1] = range_limit[(int) DESCALE(tmp12 + tmp0,
  172131. CONST_BITS+PASS1_BITS+3+1)
  172132. & RANGE_MASK];
  172133. outptr[2] = range_limit[(int) DESCALE(tmp12 - tmp0,
  172134. CONST_BITS+PASS1_BITS+3+1)
  172135. & RANGE_MASK];
  172136. wsptr += DCTSIZE; /* advance pointer to next row */
  172137. }
  172138. }
  172139. /*
  172140. * Perform dequantization and inverse DCT on one block of coefficients,
  172141. * producing a reduced-size 2x2 output block.
  172142. */
  172143. GLOBAL(void)
  172144. jpeg_idct_2x2 (j_decompress_ptr cinfo, jpeg_component_info * compptr,
  172145. JCOEFPTR coef_block,
  172146. JSAMPARRAY output_buf, JDIMENSION output_col)
  172147. {
  172148. INT32 tmp0, tmp10, z1;
  172149. JCOEFPTR inptr;
  172150. ISLOW_MULT_TYPE * quantptr;
  172151. int * wsptr;
  172152. JSAMPROW outptr;
  172153. JSAMPLE *range_limit = IDCT_range_limit(cinfo);
  172154. int ctr;
  172155. int workspace[DCTSIZE*2]; /* buffers data between passes */
  172156. SHIFT_TEMPS
  172157. /* Pass 1: process columns from input, store into work array. */
  172158. inptr = coef_block;
  172159. quantptr = (ISLOW_MULT_TYPE *) compptr->dct_table;
  172160. wsptr = workspace;
  172161. for (ctr = DCTSIZE; ctr > 0; inptr++, quantptr++, wsptr++, ctr--) {
  172162. /* Don't bother to process columns 2,4,6 */
  172163. if (ctr == DCTSIZE-2 || ctr == DCTSIZE-4 || ctr == DCTSIZE-6)
  172164. continue;
  172165. if (inptr[DCTSIZE*1] == 0 && inptr[DCTSIZE*3] == 0 &&
  172166. inptr[DCTSIZE*5] == 0 && inptr[DCTSIZE*7] == 0) {
  172167. /* AC terms all zero; we need not examine terms 2,4,6 for 2x2 output */
  172168. int dcval = DEQUANTIZE(inptr[DCTSIZE*0], quantptr[DCTSIZE*0]) << PASS1_BITS;
  172169. wsptr[DCTSIZE*0] = dcval;
  172170. wsptr[DCTSIZE*1] = dcval;
  172171. continue;
  172172. }
  172173. /* Even part */
  172174. z1 = DEQUANTIZE(inptr[DCTSIZE*0], quantptr[DCTSIZE*0]);
  172175. tmp10 = z1 << (CONST_BITS+2);
  172176. /* Odd part */
  172177. z1 = DEQUANTIZE(inptr[DCTSIZE*7], quantptr[DCTSIZE*7]);
  172178. tmp0 = MULTIPLY(z1, - FIX_0_720959822); /* sqrt(2) * (c7-c5+c3-c1) */
  172179. z1 = DEQUANTIZE(inptr[DCTSIZE*5], quantptr[DCTSIZE*5]);
  172180. tmp0 += MULTIPLY(z1, FIX_0_850430095); /* sqrt(2) * (-c1+c3+c5+c7) */
  172181. z1 = DEQUANTIZE(inptr[DCTSIZE*3], quantptr[DCTSIZE*3]);
  172182. tmp0 += MULTIPLY(z1, - FIX_1_272758580); /* sqrt(2) * (-c1+c3-c5-c7) */
  172183. z1 = DEQUANTIZE(inptr[DCTSIZE*1], quantptr[DCTSIZE*1]);
  172184. tmp0 += MULTIPLY(z1, FIX_3_624509785); /* sqrt(2) * (c1+c3+c5+c7) */
  172185. /* Final output stage */
  172186. wsptr[DCTSIZE*0] = (int) DESCALE(tmp10 + tmp0, CONST_BITS-PASS1_BITS+2);
  172187. wsptr[DCTSIZE*1] = (int) DESCALE(tmp10 - tmp0, CONST_BITS-PASS1_BITS+2);
  172188. }
  172189. /* Pass 2: process 2 rows from work array, store into output array. */
  172190. wsptr = workspace;
  172191. for (ctr = 0; ctr < 2; ctr++) {
  172192. outptr = output_buf[ctr] + output_col;
  172193. /* It's not clear whether a zero row test is worthwhile here ... */
  172194. #ifndef NO_ZERO_ROW_TEST
  172195. if (wsptr[1] == 0 && wsptr[3] == 0 && wsptr[5] == 0 && wsptr[7] == 0) {
  172196. /* AC terms all zero */
  172197. JSAMPLE dcval = range_limit[(int) DESCALE((INT32) wsptr[0], PASS1_BITS+3)
  172198. & RANGE_MASK];
  172199. outptr[0] = dcval;
  172200. outptr[1] = dcval;
  172201. wsptr += DCTSIZE; /* advance pointer to next row */
  172202. continue;
  172203. }
  172204. #endif
  172205. /* Even part */
  172206. tmp10 = ((INT32) wsptr[0]) << (CONST_BITS+2);
  172207. /* Odd part */
  172208. tmp0 = MULTIPLY((INT32) wsptr[7], - FIX_0_720959822) /* sqrt(2) * (c7-c5+c3-c1) */
  172209. + MULTIPLY((INT32) wsptr[5], FIX_0_850430095) /* sqrt(2) * (-c1+c3+c5+c7) */
  172210. + MULTIPLY((INT32) wsptr[3], - FIX_1_272758580) /* sqrt(2) * (-c1+c3-c5-c7) */
  172211. + MULTIPLY((INT32) wsptr[1], FIX_3_624509785); /* sqrt(2) * (c1+c3+c5+c7) */
  172212. /* Final output stage */
  172213. outptr[0] = range_limit[(int) DESCALE(tmp10 + tmp0,
  172214. CONST_BITS+PASS1_BITS+3+2)
  172215. & RANGE_MASK];
  172216. outptr[1] = range_limit[(int) DESCALE(tmp10 - tmp0,
  172217. CONST_BITS+PASS1_BITS+3+2)
  172218. & RANGE_MASK];
  172219. wsptr += DCTSIZE; /* advance pointer to next row */
  172220. }
  172221. }
  172222. /*
  172223. * Perform dequantization and inverse DCT on one block of coefficients,
  172224. * producing a reduced-size 1x1 output block.
  172225. */
  172226. GLOBAL(void)
  172227. jpeg_idct_1x1 (j_decompress_ptr cinfo, jpeg_component_info * compptr,
  172228. JCOEFPTR coef_block,
  172229. JSAMPARRAY output_buf, JDIMENSION output_col)
  172230. {
  172231. int dcval;
  172232. ISLOW_MULT_TYPE * quantptr;
  172233. JSAMPLE *range_limit = IDCT_range_limit(cinfo);
  172234. SHIFT_TEMPS
  172235. /* We hardly need an inverse DCT routine for this: just take the
  172236. * average pixel value, which is one-eighth of the DC coefficient.
  172237. */
  172238. quantptr = (ISLOW_MULT_TYPE *) compptr->dct_table;
  172239. dcval = DEQUANTIZE(coef_block[0], quantptr[0]);
  172240. dcval = (int) DESCALE((INT32) dcval, 3);
  172241. output_buf[0][output_col] = range_limit[dcval & RANGE_MASK];
  172242. }
  172243. #endif /* IDCT_SCALING_SUPPORTED */
  172244. /*** End of inlined file: jidctred.c ***/
  172245. /*** Start of inlined file: jmemmgr.c ***/
  172246. #define JPEG_INTERNALS
  172247. #define AM_MEMORY_MANAGER /* we define jvirt_Xarray_control structs */
  172248. /*** Start of inlined file: jmemsys.h ***/
  172249. #ifndef __jmemsys_h__
  172250. #define __jmemsys_h__
  172251. /* Short forms of external names for systems with brain-damaged linkers. */
  172252. #ifdef NEED_SHORT_EXTERNAL_NAMES
  172253. #define jpeg_get_small jGetSmall
  172254. #define jpeg_free_small jFreeSmall
  172255. #define jpeg_get_large jGetLarge
  172256. #define jpeg_free_large jFreeLarge
  172257. #define jpeg_mem_available jMemAvail
  172258. #define jpeg_open_backing_store jOpenBackStore
  172259. #define jpeg_mem_init jMemInit
  172260. #define jpeg_mem_term jMemTerm
  172261. #endif /* NEED_SHORT_EXTERNAL_NAMES */
  172262. /*
  172263. * These two functions are used to allocate and release small chunks of
  172264. * memory. (Typically the total amount requested through jpeg_get_small is
  172265. * no more than 20K or so; this will be requested in chunks of a few K each.)
  172266. * Behavior should be the same as for the standard library functions malloc
  172267. * and free; in particular, jpeg_get_small must return NULL on failure.
  172268. * On most systems, these ARE malloc and free. jpeg_free_small is passed the
  172269. * size of the object being freed, just in case it's needed.
  172270. * On an 80x86 machine using small-data memory model, these manage near heap.
  172271. */
  172272. EXTERN(void *) jpeg_get_small JPP((j_common_ptr cinfo, size_t sizeofobject));
  172273. EXTERN(void) jpeg_free_small JPP((j_common_ptr cinfo, void * object,
  172274. size_t sizeofobject));
  172275. /*
  172276. * These two functions are used to allocate and release large chunks of
  172277. * memory (up to the total free space designated by jpeg_mem_available).
  172278. * The interface is the same as above, except that on an 80x86 machine,
  172279. * far pointers are used. On most other machines these are identical to
  172280. * the jpeg_get/free_small routines; but we keep them separate anyway,
  172281. * in case a different allocation strategy is desirable for large chunks.
  172282. */
  172283. EXTERN(void FAR *) jpeg_get_large JPP((j_common_ptr cinfo,
  172284. size_t sizeofobject));
  172285. EXTERN(void) jpeg_free_large JPP((j_common_ptr cinfo, void FAR * object,
  172286. size_t sizeofobject));
  172287. /*
  172288. * The macro MAX_ALLOC_CHUNK designates the maximum number of bytes that may
  172289. * be requested in a single call to jpeg_get_large (and jpeg_get_small for that
  172290. * matter, but that case should never come into play). This macro is needed
  172291. * to model the 64Kb-segment-size limit of far addressing on 80x86 machines.
  172292. * On those machines, we expect that jconfig.h will provide a proper value.
  172293. * On machines with 32-bit flat address spaces, any large constant may be used.
  172294. *
  172295. * NB: jmemmgr.c expects that MAX_ALLOC_CHUNK will be representable as type
  172296. * size_t and will be a multiple of sizeof(align_type).
  172297. */
  172298. #ifndef MAX_ALLOC_CHUNK /* may be overridden in jconfig.h */
  172299. #define MAX_ALLOC_CHUNK 1000000000L
  172300. #endif
  172301. /*
  172302. * This routine computes the total space still available for allocation by
  172303. * jpeg_get_large. If more space than this is needed, backing store will be
  172304. * used. NOTE: any memory already allocated must not be counted.
  172305. *
  172306. * There is a minimum space requirement, corresponding to the minimum
  172307. * feasible buffer sizes; jmemmgr.c will request that much space even if
  172308. * jpeg_mem_available returns zero. The maximum space needed, enough to hold
  172309. * all working storage in memory, is also passed in case it is useful.
  172310. * Finally, the total space already allocated is passed. If no better
  172311. * method is available, cinfo->mem->max_memory_to_use - already_allocated
  172312. * is often a suitable calculation.
  172313. *
  172314. * It is OK for jpeg_mem_available to underestimate the space available
  172315. * (that'll just lead to more backing-store access than is really necessary).
  172316. * However, an overestimate will lead to failure. Hence it's wise to subtract
  172317. * a slop factor from the true available space. 5% should be enough.
  172318. *
  172319. * On machines with lots of virtual memory, any large constant may be returned.
  172320. * Conversely, zero may be returned to always use the minimum amount of memory.
  172321. */
  172322. EXTERN(long) jpeg_mem_available JPP((j_common_ptr cinfo,
  172323. long min_bytes_needed,
  172324. long max_bytes_needed,
  172325. long already_allocated));
  172326. /*
  172327. * This structure holds whatever state is needed to access a single
  172328. * backing-store object. The read/write/close method pointers are called
  172329. * by jmemmgr.c to manipulate the backing-store object; all other fields
  172330. * are private to the system-dependent backing store routines.
  172331. */
  172332. #define TEMP_NAME_LENGTH 64 /* max length of a temporary file's name */
  172333. #ifdef USE_MSDOS_MEMMGR /* DOS-specific junk */
  172334. typedef unsigned short XMSH; /* type of extended-memory handles */
  172335. typedef unsigned short EMSH; /* type of expanded-memory handles */
  172336. typedef union {
  172337. short file_handle; /* DOS file handle if it's a temp file */
  172338. XMSH xms_handle; /* handle if it's a chunk of XMS */
  172339. EMSH ems_handle; /* handle if it's a chunk of EMS */
  172340. } handle_union;
  172341. #endif /* USE_MSDOS_MEMMGR */
  172342. #ifdef USE_MAC_MEMMGR /* Mac-specific junk */
  172343. #include <Files.h>
  172344. #endif /* USE_MAC_MEMMGR */
  172345. //typedef struct backing_store_struct * backing_store_ptr;
  172346. typedef struct backing_store_struct {
  172347. /* Methods for reading/writing/closing this backing-store object */
  172348. JMETHOD(void, read_backing_store, (j_common_ptr cinfo,
  172349. struct backing_store_struct *info,
  172350. void FAR * buffer_address,
  172351. long file_offset, long byte_count));
  172352. JMETHOD(void, write_backing_store, (j_common_ptr cinfo,
  172353. struct backing_store_struct *info,
  172354. void FAR * buffer_address,
  172355. long file_offset, long byte_count));
  172356. JMETHOD(void, close_backing_store, (j_common_ptr cinfo,
  172357. struct backing_store_struct *info));
  172358. /* Private fields for system-dependent backing-store management */
  172359. #ifdef USE_MSDOS_MEMMGR
  172360. /* For the MS-DOS manager (jmemdos.c), we need: */
  172361. handle_union handle; /* reference to backing-store storage object */
  172362. char temp_name[TEMP_NAME_LENGTH]; /* name if it's a file */
  172363. #else
  172364. #ifdef USE_MAC_MEMMGR
  172365. /* For the Mac manager (jmemmac.c), we need: */
  172366. short temp_file; /* file reference number to temp file */
  172367. FSSpec tempSpec; /* the FSSpec for the temp file */
  172368. char temp_name[TEMP_NAME_LENGTH]; /* name if it's a file */
  172369. #else
  172370. /* For a typical implementation with temp files, we need: */
  172371. FILE * temp_file; /* stdio reference to temp file */
  172372. char temp_name[TEMP_NAME_LENGTH]; /* name of temp file */
  172373. #endif
  172374. #endif
  172375. } backing_store_info;
  172376. /*
  172377. * Initial opening of a backing-store object. This must fill in the
  172378. * read/write/close pointers in the object. The read/write routines
  172379. * may take an error exit if the specified maximum file size is exceeded.
  172380. * (If jpeg_mem_available always returns a large value, this routine can
  172381. * just take an error exit.)
  172382. */
  172383. EXTERN(void) jpeg_open_backing_store JPP((j_common_ptr cinfo,
  172384. struct backing_store_struct *info,
  172385. long total_bytes_needed));
  172386. /*
  172387. * These routines take care of any system-dependent initialization and
  172388. * cleanup required. jpeg_mem_init will be called before anything is
  172389. * allocated (and, therefore, nothing in cinfo is of use except the error
  172390. * manager pointer). It should return a suitable default value for
  172391. * max_memory_to_use; this may subsequently be overridden by the surrounding
  172392. * application. (Note that max_memory_to_use is only important if
  172393. * jpeg_mem_available chooses to consult it ... no one else will.)
  172394. * jpeg_mem_term may assume that all requested memory has been freed and that
  172395. * all opened backing-store objects have been closed.
  172396. */
  172397. EXTERN(long) jpeg_mem_init JPP((j_common_ptr cinfo));
  172398. EXTERN(void) jpeg_mem_term JPP((j_common_ptr cinfo));
  172399. #endif
  172400. /*** End of inlined file: jmemsys.h ***/
  172401. /* import the system-dependent declarations */
  172402. #ifndef NO_GETENV
  172403. #ifndef HAVE_STDLIB_H /* <stdlib.h> should declare getenv() */
  172404. extern char * getenv JPP((const char * name));
  172405. #endif
  172406. #endif
  172407. /*
  172408. * Some important notes:
  172409. * The allocation routines provided here must never return NULL.
  172410. * They should exit to error_exit if unsuccessful.
  172411. *
  172412. * It's not a good idea to try to merge the sarray and barray routines,
  172413. * even though they are textually almost the same, because samples are
  172414. * usually stored as bytes while coefficients are shorts or ints. Thus,
  172415. * in machines where byte pointers have a different representation from
  172416. * word pointers, the resulting machine code could not be the same.
  172417. */
  172418. /*
  172419. * Many machines require storage alignment: longs must start on 4-byte
  172420. * boundaries, doubles on 8-byte boundaries, etc. On such machines, malloc()
  172421. * always returns pointers that are multiples of the worst-case alignment
  172422. * requirement, and we had better do so too.
  172423. * There isn't any really portable way to determine the worst-case alignment
  172424. * requirement. This module assumes that the alignment requirement is
  172425. * multiples of sizeof(ALIGN_TYPE).
  172426. * By default, we define ALIGN_TYPE as double. This is necessary on some
  172427. * workstations (where doubles really do need 8-byte alignment) and will work
  172428. * fine on nearly everything. If your machine has lesser alignment needs,
  172429. * you can save a few bytes by making ALIGN_TYPE smaller.
  172430. * The only place I know of where this will NOT work is certain Macintosh
  172431. * 680x0 compilers that define double as a 10-byte IEEE extended float.
  172432. * Doing 10-byte alignment is counterproductive because longwords won't be
  172433. * aligned well. Put "#define ALIGN_TYPE long" in jconfig.h if you have
  172434. * such a compiler.
  172435. */
  172436. #ifndef ALIGN_TYPE /* so can override from jconfig.h */
  172437. #define ALIGN_TYPE double
  172438. #endif
  172439. /*
  172440. * We allocate objects from "pools", where each pool is gotten with a single
  172441. * request to jpeg_get_small() or jpeg_get_large(). There is no per-object
  172442. * overhead within a pool, except for alignment padding. Each pool has a
  172443. * header with a link to the next pool of the same class.
  172444. * Small and large pool headers are identical except that the latter's
  172445. * link pointer must be FAR on 80x86 machines.
  172446. * Notice that the "real" header fields are union'ed with a dummy ALIGN_TYPE
  172447. * field. This forces the compiler to make SIZEOF(small_pool_hdr) a multiple
  172448. * of the alignment requirement of ALIGN_TYPE.
  172449. */
  172450. typedef union small_pool_struct * small_pool_ptr;
  172451. typedef union small_pool_struct {
  172452. struct {
  172453. small_pool_ptr next; /* next in list of pools */
  172454. size_t bytes_used; /* how many bytes already used within pool */
  172455. size_t bytes_left; /* bytes still available in this pool */
  172456. } hdr;
  172457. ALIGN_TYPE dummy; /* included in union to ensure alignment */
  172458. } small_pool_hdr;
  172459. typedef union large_pool_struct FAR * large_pool_ptr;
  172460. typedef union large_pool_struct {
  172461. struct {
  172462. large_pool_ptr next; /* next in list of pools */
  172463. size_t bytes_used; /* how many bytes already used within pool */
  172464. size_t bytes_left; /* bytes still available in this pool */
  172465. } hdr;
  172466. ALIGN_TYPE dummy; /* included in union to ensure alignment */
  172467. } large_pool_hdr;
  172468. /*
  172469. * Here is the full definition of a memory manager object.
  172470. */
  172471. typedef struct {
  172472. struct jpeg_memory_mgr pub; /* public fields */
  172473. /* Each pool identifier (lifetime class) names a linked list of pools. */
  172474. small_pool_ptr small_list[JPOOL_NUMPOOLS];
  172475. large_pool_ptr large_list[JPOOL_NUMPOOLS];
  172476. /* Since we only have one lifetime class of virtual arrays, only one
  172477. * linked list is necessary (for each datatype). Note that the virtual
  172478. * array control blocks being linked together are actually stored somewhere
  172479. * in the small-pool list.
  172480. */
  172481. jvirt_sarray_ptr virt_sarray_list;
  172482. jvirt_barray_ptr virt_barray_list;
  172483. /* This counts total space obtained from jpeg_get_small/large */
  172484. long total_space_allocated;
  172485. /* alloc_sarray and alloc_barray set this value for use by virtual
  172486. * array routines.
  172487. */
  172488. JDIMENSION last_rowsperchunk; /* from most recent alloc_sarray/barray */
  172489. } my_memory_mgr;
  172490. typedef my_memory_mgr * my_mem_ptr;
  172491. /*
  172492. * The control blocks for virtual arrays.
  172493. * Note that these blocks are allocated in the "small" pool area.
  172494. * System-dependent info for the associated backing store (if any) is hidden
  172495. * inside the backing_store_info struct.
  172496. */
  172497. struct jvirt_sarray_control {
  172498. JSAMPARRAY mem_buffer; /* => the in-memory buffer */
  172499. JDIMENSION rows_in_array; /* total virtual array height */
  172500. JDIMENSION samplesperrow; /* width of array (and of memory buffer) */
  172501. JDIMENSION maxaccess; /* max rows accessed by access_virt_sarray */
  172502. JDIMENSION rows_in_mem; /* height of memory buffer */
  172503. JDIMENSION rowsperchunk; /* allocation chunk size in mem_buffer */
  172504. JDIMENSION cur_start_row; /* first logical row # in the buffer */
  172505. JDIMENSION first_undef_row; /* row # of first uninitialized row */
  172506. boolean pre_zero; /* pre-zero mode requested? */
  172507. boolean dirty; /* do current buffer contents need written? */
  172508. boolean b_s_open; /* is backing-store data valid? */
  172509. jvirt_sarray_ptr next; /* link to next virtual sarray control block */
  172510. backing_store_info b_s_info; /* System-dependent control info */
  172511. };
  172512. struct jvirt_barray_control {
  172513. JBLOCKARRAY mem_buffer; /* => the in-memory buffer */
  172514. JDIMENSION rows_in_array; /* total virtual array height */
  172515. JDIMENSION blocksperrow; /* width of array (and of memory buffer) */
  172516. JDIMENSION maxaccess; /* max rows accessed by access_virt_barray */
  172517. JDIMENSION rows_in_mem; /* height of memory buffer */
  172518. JDIMENSION rowsperchunk; /* allocation chunk size in mem_buffer */
  172519. JDIMENSION cur_start_row; /* first logical row # in the buffer */
  172520. JDIMENSION first_undef_row; /* row # of first uninitialized row */
  172521. boolean pre_zero; /* pre-zero mode requested? */
  172522. boolean dirty; /* do current buffer contents need written? */
  172523. boolean b_s_open; /* is backing-store data valid? */
  172524. jvirt_barray_ptr next; /* link to next virtual barray control block */
  172525. backing_store_info b_s_info; /* System-dependent control info */
  172526. };
  172527. #ifdef MEM_STATS /* optional extra stuff for statistics */
  172528. LOCAL(void)
  172529. print_mem_stats (j_common_ptr cinfo, int pool_id)
  172530. {
  172531. my_mem_ptr mem = (my_mem_ptr) cinfo->mem;
  172532. small_pool_ptr shdr_ptr;
  172533. large_pool_ptr lhdr_ptr;
  172534. /* Since this is only a debugging stub, we can cheat a little by using
  172535. * fprintf directly rather than going through the trace message code.
  172536. * This is helpful because message parm array can't handle longs.
  172537. */
  172538. fprintf(stderr, "Freeing pool %d, total space = %ld\n",
  172539. pool_id, mem->total_space_allocated);
  172540. for (lhdr_ptr = mem->large_list[pool_id]; lhdr_ptr != NULL;
  172541. lhdr_ptr = lhdr_ptr->hdr.next) {
  172542. fprintf(stderr, " Large chunk used %ld\n",
  172543. (long) lhdr_ptr->hdr.bytes_used);
  172544. }
  172545. for (shdr_ptr = mem->small_list[pool_id]; shdr_ptr != NULL;
  172546. shdr_ptr = shdr_ptr->hdr.next) {
  172547. fprintf(stderr, " Small chunk used %ld free %ld\n",
  172548. (long) shdr_ptr->hdr.bytes_used,
  172549. (long) shdr_ptr->hdr.bytes_left);
  172550. }
  172551. }
  172552. #endif /* MEM_STATS */
  172553. LOCAL(void)
  172554. out_of_memory (j_common_ptr cinfo, int which)
  172555. /* Report an out-of-memory error and stop execution */
  172556. /* If we compiled MEM_STATS support, report alloc requests before dying */
  172557. {
  172558. #ifdef MEM_STATS
  172559. cinfo->err->trace_level = 2; /* force self_destruct to report stats */
  172560. #endif
  172561. ERREXIT1(cinfo, JERR_OUT_OF_MEMORY, which);
  172562. }
  172563. /*
  172564. * Allocation of "small" objects.
  172565. *
  172566. * For these, we use pooled storage. When a new pool must be created,
  172567. * we try to get enough space for the current request plus a "slop" factor,
  172568. * where the slop will be the amount of leftover space in the new pool.
  172569. * The speed vs. space tradeoff is largely determined by the slop values.
  172570. * A different slop value is provided for each pool class (lifetime),
  172571. * and we also distinguish the first pool of a class from later ones.
  172572. * NOTE: the values given work fairly well on both 16- and 32-bit-int
  172573. * machines, but may be too small if longs are 64 bits or more.
  172574. */
  172575. static const size_t first_pool_slop[JPOOL_NUMPOOLS] =
  172576. {
  172577. 1600, /* first PERMANENT pool */
  172578. 16000 /* first IMAGE pool */
  172579. };
  172580. static const size_t extra_pool_slop[JPOOL_NUMPOOLS] =
  172581. {
  172582. 0, /* additional PERMANENT pools */
  172583. 5000 /* additional IMAGE pools */
  172584. };
  172585. #define MIN_SLOP 50 /* greater than 0 to avoid futile looping */
  172586. METHODDEF(void *)
  172587. alloc_small (j_common_ptr cinfo, int pool_id, size_t sizeofobject)
  172588. /* Allocate a "small" object */
  172589. {
  172590. my_mem_ptr mem = (my_mem_ptr) cinfo->mem;
  172591. small_pool_ptr hdr_ptr, prev_hdr_ptr;
  172592. char * data_ptr;
  172593. size_t odd_bytes, min_request, slop;
  172594. /* Check for unsatisfiable request (do now to ensure no overflow below) */
  172595. if (sizeofobject > (size_t) (MAX_ALLOC_CHUNK-SIZEOF(small_pool_hdr)))
  172596. out_of_memory(cinfo, 1); /* request exceeds malloc's ability */
  172597. /* Round up the requested size to a multiple of SIZEOF(ALIGN_TYPE) */
  172598. odd_bytes = sizeofobject % SIZEOF(ALIGN_TYPE);
  172599. if (odd_bytes > 0)
  172600. sizeofobject += SIZEOF(ALIGN_TYPE) - odd_bytes;
  172601. /* See if space is available in any existing pool */
  172602. if (pool_id < 0 || pool_id >= JPOOL_NUMPOOLS)
  172603. ERREXIT1(cinfo, JERR_BAD_POOL_ID, pool_id); /* safety check */
  172604. prev_hdr_ptr = NULL;
  172605. hdr_ptr = mem->small_list[pool_id];
  172606. while (hdr_ptr != NULL) {
  172607. if (hdr_ptr->hdr.bytes_left >= sizeofobject)
  172608. break; /* found pool with enough space */
  172609. prev_hdr_ptr = hdr_ptr;
  172610. hdr_ptr = hdr_ptr->hdr.next;
  172611. }
  172612. /* Time to make a new pool? */
  172613. if (hdr_ptr == NULL) {
  172614. /* min_request is what we need now, slop is what will be leftover */
  172615. min_request = sizeofobject + SIZEOF(small_pool_hdr);
  172616. if (prev_hdr_ptr == NULL) /* first pool in class? */
  172617. slop = first_pool_slop[pool_id];
  172618. else
  172619. slop = extra_pool_slop[pool_id];
  172620. /* Don't ask for more than MAX_ALLOC_CHUNK */
  172621. if (slop > (size_t) (MAX_ALLOC_CHUNK-min_request))
  172622. slop = (size_t) (MAX_ALLOC_CHUNK-min_request);
  172623. /* Try to get space, if fail reduce slop and try again */
  172624. for (;;) {
  172625. hdr_ptr = (small_pool_ptr) jpeg_get_small(cinfo, min_request + slop);
  172626. if (hdr_ptr != NULL)
  172627. break;
  172628. slop /= 2;
  172629. if (slop < MIN_SLOP) /* give up when it gets real small */
  172630. out_of_memory(cinfo, 2); /* jpeg_get_small failed */
  172631. }
  172632. mem->total_space_allocated += min_request + slop;
  172633. /* Success, initialize the new pool header and add to end of list */
  172634. hdr_ptr->hdr.next = NULL;
  172635. hdr_ptr->hdr.bytes_used = 0;
  172636. hdr_ptr->hdr.bytes_left = sizeofobject + slop;
  172637. if (prev_hdr_ptr == NULL) /* first pool in class? */
  172638. mem->small_list[pool_id] = hdr_ptr;
  172639. else
  172640. prev_hdr_ptr->hdr.next = hdr_ptr;
  172641. }
  172642. /* OK, allocate the object from the current pool */
  172643. data_ptr = (char *) (hdr_ptr + 1); /* point to first data byte in pool */
  172644. data_ptr += hdr_ptr->hdr.bytes_used; /* point to place for object */
  172645. hdr_ptr->hdr.bytes_used += sizeofobject;
  172646. hdr_ptr->hdr.bytes_left -= sizeofobject;
  172647. return (void *) data_ptr;
  172648. }
  172649. /*
  172650. * Allocation of "large" objects.
  172651. *
  172652. * The external semantics of these are the same as "small" objects,
  172653. * except that FAR pointers are used on 80x86. However the pool
  172654. * management heuristics are quite different. We assume that each
  172655. * request is large enough that it may as well be passed directly to
  172656. * jpeg_get_large; the pool management just links everything together
  172657. * so that we can free it all on demand.
  172658. * Note: the major use of "large" objects is in JSAMPARRAY and JBLOCKARRAY
  172659. * structures. The routines that create these structures (see below)
  172660. * deliberately bunch rows together to ensure a large request size.
  172661. */
  172662. METHODDEF(void FAR *)
  172663. alloc_large (j_common_ptr cinfo, int pool_id, size_t sizeofobject)
  172664. /* Allocate a "large" object */
  172665. {
  172666. my_mem_ptr mem = (my_mem_ptr) cinfo->mem;
  172667. large_pool_ptr hdr_ptr;
  172668. size_t odd_bytes;
  172669. /* Check for unsatisfiable request (do now to ensure no overflow below) */
  172670. if (sizeofobject > (size_t) (MAX_ALLOC_CHUNK-SIZEOF(large_pool_hdr)))
  172671. out_of_memory(cinfo, 3); /* request exceeds malloc's ability */
  172672. /* Round up the requested size to a multiple of SIZEOF(ALIGN_TYPE) */
  172673. odd_bytes = sizeofobject % SIZEOF(ALIGN_TYPE);
  172674. if (odd_bytes > 0)
  172675. sizeofobject += SIZEOF(ALIGN_TYPE) - odd_bytes;
  172676. /* Always make a new pool */
  172677. if (pool_id < 0 || pool_id >= JPOOL_NUMPOOLS)
  172678. ERREXIT1(cinfo, JERR_BAD_POOL_ID, pool_id); /* safety check */
  172679. hdr_ptr = (large_pool_ptr) jpeg_get_large(cinfo, sizeofobject +
  172680. SIZEOF(large_pool_hdr));
  172681. if (hdr_ptr == NULL)
  172682. out_of_memory(cinfo, 4); /* jpeg_get_large failed */
  172683. mem->total_space_allocated += sizeofobject + SIZEOF(large_pool_hdr);
  172684. /* Success, initialize the new pool header and add to list */
  172685. hdr_ptr->hdr.next = mem->large_list[pool_id];
  172686. /* We maintain space counts in each pool header for statistical purposes,
  172687. * even though they are not needed for allocation.
  172688. */
  172689. hdr_ptr->hdr.bytes_used = sizeofobject;
  172690. hdr_ptr->hdr.bytes_left = 0;
  172691. mem->large_list[pool_id] = hdr_ptr;
  172692. return (void FAR *) (hdr_ptr + 1); /* point to first data byte in pool */
  172693. }
  172694. /*
  172695. * Creation of 2-D sample arrays.
  172696. * The pointers are in near heap, the samples themselves in FAR heap.
  172697. *
  172698. * To minimize allocation overhead and to allow I/O of large contiguous
  172699. * blocks, we allocate the sample rows in groups of as many rows as possible
  172700. * without exceeding MAX_ALLOC_CHUNK total bytes per allocation request.
  172701. * NB: the virtual array control routines, later in this file, know about
  172702. * this chunking of rows. The rowsperchunk value is left in the mem manager
  172703. * object so that it can be saved away if this sarray is the workspace for
  172704. * a virtual array.
  172705. */
  172706. METHODDEF(JSAMPARRAY)
  172707. alloc_sarray (j_common_ptr cinfo, int pool_id,
  172708. JDIMENSION samplesperrow, JDIMENSION numrows)
  172709. /* Allocate a 2-D sample array */
  172710. {
  172711. my_mem_ptr mem = (my_mem_ptr) cinfo->mem;
  172712. JSAMPARRAY result;
  172713. JSAMPROW workspace;
  172714. JDIMENSION rowsperchunk, currow, i;
  172715. long ltemp;
  172716. /* Calculate max # of rows allowed in one allocation chunk */
  172717. ltemp = (MAX_ALLOC_CHUNK-SIZEOF(large_pool_hdr)) /
  172718. ((long) samplesperrow * SIZEOF(JSAMPLE));
  172719. if (ltemp <= 0)
  172720. ERREXIT(cinfo, JERR_WIDTH_OVERFLOW);
  172721. if (ltemp < (long) numrows)
  172722. rowsperchunk = (JDIMENSION) ltemp;
  172723. else
  172724. rowsperchunk = numrows;
  172725. mem->last_rowsperchunk = rowsperchunk;
  172726. /* Get space for row pointers (small object) */
  172727. result = (JSAMPARRAY) alloc_small(cinfo, pool_id,
  172728. (size_t) (numrows * SIZEOF(JSAMPROW)));
  172729. /* Get the rows themselves (large objects) */
  172730. currow = 0;
  172731. while (currow < numrows) {
  172732. rowsperchunk = MIN(rowsperchunk, numrows - currow);
  172733. workspace = (JSAMPROW) alloc_large(cinfo, pool_id,
  172734. (size_t) ((size_t) rowsperchunk * (size_t) samplesperrow
  172735. * SIZEOF(JSAMPLE)));
  172736. for (i = rowsperchunk; i > 0; i--) {
  172737. result[currow++] = workspace;
  172738. workspace += samplesperrow;
  172739. }
  172740. }
  172741. return result;
  172742. }
  172743. /*
  172744. * Creation of 2-D coefficient-block arrays.
  172745. * This is essentially the same as the code for sample arrays, above.
  172746. */
  172747. METHODDEF(JBLOCKARRAY)
  172748. alloc_barray (j_common_ptr cinfo, int pool_id,
  172749. JDIMENSION blocksperrow, JDIMENSION numrows)
  172750. /* Allocate a 2-D coefficient-block array */
  172751. {
  172752. my_mem_ptr mem = (my_mem_ptr) cinfo->mem;
  172753. JBLOCKARRAY result;
  172754. JBLOCKROW workspace;
  172755. JDIMENSION rowsperchunk, currow, i;
  172756. long ltemp;
  172757. /* Calculate max # of rows allowed in one allocation chunk */
  172758. ltemp = (MAX_ALLOC_CHUNK-SIZEOF(large_pool_hdr)) /
  172759. ((long) blocksperrow * SIZEOF(JBLOCK));
  172760. if (ltemp <= 0)
  172761. ERREXIT(cinfo, JERR_WIDTH_OVERFLOW);
  172762. if (ltemp < (long) numrows)
  172763. rowsperchunk = (JDIMENSION) ltemp;
  172764. else
  172765. rowsperchunk = numrows;
  172766. mem->last_rowsperchunk = rowsperchunk;
  172767. /* Get space for row pointers (small object) */
  172768. result = (JBLOCKARRAY) alloc_small(cinfo, pool_id,
  172769. (size_t) (numrows * SIZEOF(JBLOCKROW)));
  172770. /* Get the rows themselves (large objects) */
  172771. currow = 0;
  172772. while (currow < numrows) {
  172773. rowsperchunk = MIN(rowsperchunk, numrows - currow);
  172774. workspace = (JBLOCKROW) alloc_large(cinfo, pool_id,
  172775. (size_t) ((size_t) rowsperchunk * (size_t) blocksperrow
  172776. * SIZEOF(JBLOCK)));
  172777. for (i = rowsperchunk; i > 0; i--) {
  172778. result[currow++] = workspace;
  172779. workspace += blocksperrow;
  172780. }
  172781. }
  172782. return result;
  172783. }
  172784. /*
  172785. * About virtual array management:
  172786. *
  172787. * The above "normal" array routines are only used to allocate strip buffers
  172788. * (as wide as the image, but just a few rows high). Full-image-sized buffers
  172789. * are handled as "virtual" arrays. The array is still accessed a strip at a
  172790. * time, but the memory manager must save the whole array for repeated
  172791. * accesses. The intended implementation is that there is a strip buffer in
  172792. * memory (as high as is possible given the desired memory limit), plus a
  172793. * backing file that holds the rest of the array.
  172794. *
  172795. * The request_virt_array routines are told the total size of the image and
  172796. * the maximum number of rows that will be accessed at once. The in-memory
  172797. * buffer must be at least as large as the maxaccess value.
  172798. *
  172799. * The request routines create control blocks but not the in-memory buffers.
  172800. * That is postponed until realize_virt_arrays is called. At that time the
  172801. * total amount of space needed is known (approximately, anyway), so free
  172802. * memory can be divided up fairly.
  172803. *
  172804. * The access_virt_array routines are responsible for making a specific strip
  172805. * area accessible (after reading or writing the backing file, if necessary).
  172806. * Note that the access routines are told whether the caller intends to modify
  172807. * the accessed strip; during a read-only pass this saves having to rewrite
  172808. * data to disk. The access routines are also responsible for pre-zeroing
  172809. * any newly accessed rows, if pre-zeroing was requested.
  172810. *
  172811. * In current usage, the access requests are usually for nonoverlapping
  172812. * strips; that is, successive access start_row numbers differ by exactly
  172813. * num_rows = maxaccess. This means we can get good performance with simple
  172814. * buffer dump/reload logic, by making the in-memory buffer be a multiple
  172815. * of the access height; then there will never be accesses across bufferload
  172816. * boundaries. The code will still work with overlapping access requests,
  172817. * but it doesn't handle bufferload overlaps very efficiently.
  172818. */
  172819. METHODDEF(jvirt_sarray_ptr)
  172820. request_virt_sarray (j_common_ptr cinfo, int pool_id, boolean pre_zero,
  172821. JDIMENSION samplesperrow, JDIMENSION numrows,
  172822. JDIMENSION maxaccess)
  172823. /* Request a virtual 2-D sample array */
  172824. {
  172825. my_mem_ptr mem = (my_mem_ptr) cinfo->mem;
  172826. jvirt_sarray_ptr result;
  172827. /* Only IMAGE-lifetime virtual arrays are currently supported */
  172828. if (pool_id != JPOOL_IMAGE)
  172829. ERREXIT1(cinfo, JERR_BAD_POOL_ID, pool_id); /* safety check */
  172830. /* get control block */
  172831. result = (jvirt_sarray_ptr) alloc_small(cinfo, pool_id,
  172832. SIZEOF(struct jvirt_sarray_control));
  172833. result->mem_buffer = NULL; /* marks array not yet realized */
  172834. result->rows_in_array = numrows;
  172835. result->samplesperrow = samplesperrow;
  172836. result->maxaccess = maxaccess;
  172837. result->pre_zero = pre_zero;
  172838. result->b_s_open = FALSE; /* no associated backing-store object */
  172839. result->next = mem->virt_sarray_list; /* add to list of virtual arrays */
  172840. mem->virt_sarray_list = result;
  172841. return result;
  172842. }
  172843. METHODDEF(jvirt_barray_ptr)
  172844. request_virt_barray (j_common_ptr cinfo, int pool_id, boolean pre_zero,
  172845. JDIMENSION blocksperrow, JDIMENSION numrows,
  172846. JDIMENSION maxaccess)
  172847. /* Request a virtual 2-D coefficient-block array */
  172848. {
  172849. my_mem_ptr mem = (my_mem_ptr) cinfo->mem;
  172850. jvirt_barray_ptr result;
  172851. /* Only IMAGE-lifetime virtual arrays are currently supported */
  172852. if (pool_id != JPOOL_IMAGE)
  172853. ERREXIT1(cinfo, JERR_BAD_POOL_ID, pool_id); /* safety check */
  172854. /* get control block */
  172855. result = (jvirt_barray_ptr) alloc_small(cinfo, pool_id,
  172856. SIZEOF(struct jvirt_barray_control));
  172857. result->mem_buffer = NULL; /* marks array not yet realized */
  172858. result->rows_in_array = numrows;
  172859. result->blocksperrow = blocksperrow;
  172860. result->maxaccess = maxaccess;
  172861. result->pre_zero = pre_zero;
  172862. result->b_s_open = FALSE; /* no associated backing-store object */
  172863. result->next = mem->virt_barray_list; /* add to list of virtual arrays */
  172864. mem->virt_barray_list = result;
  172865. return result;
  172866. }
  172867. METHODDEF(void)
  172868. realize_virt_arrays (j_common_ptr cinfo)
  172869. /* Allocate the in-memory buffers for any unrealized virtual arrays */
  172870. {
  172871. my_mem_ptr mem = (my_mem_ptr) cinfo->mem;
  172872. long space_per_minheight, maximum_space, avail_mem;
  172873. long minheights, max_minheights;
  172874. jvirt_sarray_ptr sptr;
  172875. jvirt_barray_ptr bptr;
  172876. /* Compute the minimum space needed (maxaccess rows in each buffer)
  172877. * and the maximum space needed (full image height in each buffer).
  172878. * These may be of use to the system-dependent jpeg_mem_available routine.
  172879. */
  172880. space_per_minheight = 0;
  172881. maximum_space = 0;
  172882. for (sptr = mem->virt_sarray_list; sptr != NULL; sptr = sptr->next) {
  172883. if (sptr->mem_buffer == NULL) { /* if not realized yet */
  172884. space_per_minheight += (long) sptr->maxaccess *
  172885. (long) sptr->samplesperrow * SIZEOF(JSAMPLE);
  172886. maximum_space += (long) sptr->rows_in_array *
  172887. (long) sptr->samplesperrow * SIZEOF(JSAMPLE);
  172888. }
  172889. }
  172890. for (bptr = mem->virt_barray_list; bptr != NULL; bptr = bptr->next) {
  172891. if (bptr->mem_buffer == NULL) { /* if not realized yet */
  172892. space_per_minheight += (long) bptr->maxaccess *
  172893. (long) bptr->blocksperrow * SIZEOF(JBLOCK);
  172894. maximum_space += (long) bptr->rows_in_array *
  172895. (long) bptr->blocksperrow * SIZEOF(JBLOCK);
  172896. }
  172897. }
  172898. if (space_per_minheight <= 0)
  172899. return; /* no unrealized arrays, no work */
  172900. /* Determine amount of memory to actually use; this is system-dependent. */
  172901. avail_mem = jpeg_mem_available(cinfo, space_per_minheight, maximum_space,
  172902. mem->total_space_allocated);
  172903. /* If the maximum space needed is available, make all the buffers full
  172904. * height; otherwise parcel it out with the same number of minheights
  172905. * in each buffer.
  172906. */
  172907. if (avail_mem >= maximum_space)
  172908. max_minheights = 1000000000L;
  172909. else {
  172910. max_minheights = avail_mem / space_per_minheight;
  172911. /* If there doesn't seem to be enough space, try to get the minimum
  172912. * anyway. This allows a "stub" implementation of jpeg_mem_available().
  172913. */
  172914. if (max_minheights <= 0)
  172915. max_minheights = 1;
  172916. }
  172917. /* Allocate the in-memory buffers and initialize backing store as needed. */
  172918. for (sptr = mem->virt_sarray_list; sptr != NULL; sptr = sptr->next) {
  172919. if (sptr->mem_buffer == NULL) { /* if not realized yet */
  172920. minheights = ((long) sptr->rows_in_array - 1L) / sptr->maxaccess + 1L;
  172921. if (minheights <= max_minheights) {
  172922. /* This buffer fits in memory */
  172923. sptr->rows_in_mem = sptr->rows_in_array;
  172924. } else {
  172925. /* It doesn't fit in memory, create backing store. */
  172926. sptr->rows_in_mem = (JDIMENSION) (max_minheights * sptr->maxaccess);
  172927. jpeg_open_backing_store(cinfo, & sptr->b_s_info,
  172928. (long) sptr->rows_in_array *
  172929. (long) sptr->samplesperrow *
  172930. (long) SIZEOF(JSAMPLE));
  172931. sptr->b_s_open = TRUE;
  172932. }
  172933. sptr->mem_buffer = alloc_sarray(cinfo, JPOOL_IMAGE,
  172934. sptr->samplesperrow, sptr->rows_in_mem);
  172935. sptr->rowsperchunk = mem->last_rowsperchunk;
  172936. sptr->cur_start_row = 0;
  172937. sptr->first_undef_row = 0;
  172938. sptr->dirty = FALSE;
  172939. }
  172940. }
  172941. for (bptr = mem->virt_barray_list; bptr != NULL; bptr = bptr->next) {
  172942. if (bptr->mem_buffer == NULL) { /* if not realized yet */
  172943. minheights = ((long) bptr->rows_in_array - 1L) / bptr->maxaccess + 1L;
  172944. if (minheights <= max_minheights) {
  172945. /* This buffer fits in memory */
  172946. bptr->rows_in_mem = bptr->rows_in_array;
  172947. } else {
  172948. /* It doesn't fit in memory, create backing store. */
  172949. bptr->rows_in_mem = (JDIMENSION) (max_minheights * bptr->maxaccess);
  172950. jpeg_open_backing_store(cinfo, & bptr->b_s_info,
  172951. (long) bptr->rows_in_array *
  172952. (long) bptr->blocksperrow *
  172953. (long) SIZEOF(JBLOCK));
  172954. bptr->b_s_open = TRUE;
  172955. }
  172956. bptr->mem_buffer = alloc_barray(cinfo, JPOOL_IMAGE,
  172957. bptr->blocksperrow, bptr->rows_in_mem);
  172958. bptr->rowsperchunk = mem->last_rowsperchunk;
  172959. bptr->cur_start_row = 0;
  172960. bptr->first_undef_row = 0;
  172961. bptr->dirty = FALSE;
  172962. }
  172963. }
  172964. }
  172965. LOCAL(void)
  172966. do_sarray_io (j_common_ptr cinfo, jvirt_sarray_ptr ptr, boolean writing)
  172967. /* Do backing store read or write of a virtual sample array */
  172968. {
  172969. long bytesperrow, file_offset, byte_count, rows, thisrow, i;
  172970. bytesperrow = (long) ptr->samplesperrow * SIZEOF(JSAMPLE);
  172971. file_offset = ptr->cur_start_row * bytesperrow;
  172972. /* Loop to read or write each allocation chunk in mem_buffer */
  172973. for (i = 0; i < (long) ptr->rows_in_mem; i += ptr->rowsperchunk) {
  172974. /* One chunk, but check for short chunk at end of buffer */
  172975. rows = MIN((long) ptr->rowsperchunk, (long) ptr->rows_in_mem - i);
  172976. /* Transfer no more than is currently defined */
  172977. thisrow = (long) ptr->cur_start_row + i;
  172978. rows = MIN(rows, (long) ptr->first_undef_row - thisrow);
  172979. /* Transfer no more than fits in file */
  172980. rows = MIN(rows, (long) ptr->rows_in_array - thisrow);
  172981. if (rows <= 0) /* this chunk might be past end of file! */
  172982. break;
  172983. byte_count = rows * bytesperrow;
  172984. if (writing)
  172985. (*ptr->b_s_info.write_backing_store) (cinfo, & ptr->b_s_info,
  172986. (void FAR *) ptr->mem_buffer[i],
  172987. file_offset, byte_count);
  172988. else
  172989. (*ptr->b_s_info.read_backing_store) (cinfo, & ptr->b_s_info,
  172990. (void FAR *) ptr->mem_buffer[i],
  172991. file_offset, byte_count);
  172992. file_offset += byte_count;
  172993. }
  172994. }
  172995. LOCAL(void)
  172996. do_barray_io (j_common_ptr cinfo, jvirt_barray_ptr ptr, boolean writing)
  172997. /* Do backing store read or write of a virtual coefficient-block array */
  172998. {
  172999. long bytesperrow, file_offset, byte_count, rows, thisrow, i;
  173000. bytesperrow = (long) ptr->blocksperrow * SIZEOF(JBLOCK);
  173001. file_offset = ptr->cur_start_row * bytesperrow;
  173002. /* Loop to read or write each allocation chunk in mem_buffer */
  173003. for (i = 0; i < (long) ptr->rows_in_mem; i += ptr->rowsperchunk) {
  173004. /* One chunk, but check for short chunk at end of buffer */
  173005. rows = MIN((long) ptr->rowsperchunk, (long) ptr->rows_in_mem - i);
  173006. /* Transfer no more than is currently defined */
  173007. thisrow = (long) ptr->cur_start_row + i;
  173008. rows = MIN(rows, (long) ptr->first_undef_row - thisrow);
  173009. /* Transfer no more than fits in file */
  173010. rows = MIN(rows, (long) ptr->rows_in_array - thisrow);
  173011. if (rows <= 0) /* this chunk might be past end of file! */
  173012. break;
  173013. byte_count = rows * bytesperrow;
  173014. if (writing)
  173015. (*ptr->b_s_info.write_backing_store) (cinfo, & ptr->b_s_info,
  173016. (void FAR *) ptr->mem_buffer[i],
  173017. file_offset, byte_count);
  173018. else
  173019. (*ptr->b_s_info.read_backing_store) (cinfo, & ptr->b_s_info,
  173020. (void FAR *) ptr->mem_buffer[i],
  173021. file_offset, byte_count);
  173022. file_offset += byte_count;
  173023. }
  173024. }
  173025. METHODDEF(JSAMPARRAY)
  173026. access_virt_sarray (j_common_ptr cinfo, jvirt_sarray_ptr ptr,
  173027. JDIMENSION start_row, JDIMENSION num_rows,
  173028. boolean writable)
  173029. /* Access the part of a virtual sample array starting at start_row */
  173030. /* and extending for num_rows rows. writable is true if */
  173031. /* caller intends to modify the accessed area. */
  173032. {
  173033. JDIMENSION end_row = start_row + num_rows;
  173034. JDIMENSION undef_row;
  173035. /* debugging check */
  173036. if (end_row > ptr->rows_in_array || num_rows > ptr->maxaccess ||
  173037. ptr->mem_buffer == NULL)
  173038. ERREXIT(cinfo, JERR_BAD_VIRTUAL_ACCESS);
  173039. /* Make the desired part of the virtual array accessible */
  173040. if (start_row < ptr->cur_start_row ||
  173041. end_row > ptr->cur_start_row+ptr->rows_in_mem) {
  173042. if (! ptr->b_s_open)
  173043. ERREXIT(cinfo, JERR_VIRTUAL_BUG);
  173044. /* Flush old buffer contents if necessary */
  173045. if (ptr->dirty) {
  173046. do_sarray_io(cinfo, ptr, TRUE);
  173047. ptr->dirty = FALSE;
  173048. }
  173049. /* Decide what part of virtual array to access.
  173050. * Algorithm: if target address > current window, assume forward scan,
  173051. * load starting at target address. If target address < current window,
  173052. * assume backward scan, load so that target area is top of window.
  173053. * Note that when switching from forward write to forward read, will have
  173054. * start_row = 0, so the limiting case applies and we load from 0 anyway.
  173055. */
  173056. if (start_row > ptr->cur_start_row) {
  173057. ptr->cur_start_row = start_row;
  173058. } else {
  173059. /* use long arithmetic here to avoid overflow & unsigned problems */
  173060. long ltemp;
  173061. ltemp = (long) end_row - (long) ptr->rows_in_mem;
  173062. if (ltemp < 0)
  173063. ltemp = 0; /* don't fall off front end of file */
  173064. ptr->cur_start_row = (JDIMENSION) ltemp;
  173065. }
  173066. /* Read in the selected part of the array.
  173067. * During the initial write pass, we will do no actual read
  173068. * because the selected part is all undefined.
  173069. */
  173070. do_sarray_io(cinfo, ptr, FALSE);
  173071. }
  173072. /* Ensure the accessed part of the array is defined; prezero if needed.
  173073. * To improve locality of access, we only prezero the part of the array
  173074. * that the caller is about to access, not the entire in-memory array.
  173075. */
  173076. if (ptr->first_undef_row < end_row) {
  173077. if (ptr->first_undef_row < start_row) {
  173078. if (writable) /* writer skipped over a section of array */
  173079. ERREXIT(cinfo, JERR_BAD_VIRTUAL_ACCESS);
  173080. undef_row = start_row; /* but reader is allowed to read ahead */
  173081. } else {
  173082. undef_row = ptr->first_undef_row;
  173083. }
  173084. if (writable)
  173085. ptr->first_undef_row = end_row;
  173086. if (ptr->pre_zero) {
  173087. size_t bytesperrow = (size_t) ptr->samplesperrow * SIZEOF(JSAMPLE);
  173088. undef_row -= ptr->cur_start_row; /* make indexes relative to buffer */
  173089. end_row -= ptr->cur_start_row;
  173090. while (undef_row < end_row) {
  173091. jzero_far((void FAR *) ptr->mem_buffer[undef_row], bytesperrow);
  173092. undef_row++;
  173093. }
  173094. } else {
  173095. if (! writable) /* reader looking at undefined data */
  173096. ERREXIT(cinfo, JERR_BAD_VIRTUAL_ACCESS);
  173097. }
  173098. }
  173099. /* Flag the buffer dirty if caller will write in it */
  173100. if (writable)
  173101. ptr->dirty = TRUE;
  173102. /* Return address of proper part of the buffer */
  173103. return ptr->mem_buffer + (start_row - ptr->cur_start_row);
  173104. }
  173105. METHODDEF(JBLOCKARRAY)
  173106. access_virt_barray (j_common_ptr cinfo, jvirt_barray_ptr ptr,
  173107. JDIMENSION start_row, JDIMENSION num_rows,
  173108. boolean writable)
  173109. /* Access the part of a virtual block array starting at start_row */
  173110. /* and extending for num_rows rows. writable is true if */
  173111. /* caller intends to modify the accessed area. */
  173112. {
  173113. JDIMENSION end_row = start_row + num_rows;
  173114. JDIMENSION undef_row;
  173115. /* debugging check */
  173116. if (end_row > ptr->rows_in_array || num_rows > ptr->maxaccess ||
  173117. ptr->mem_buffer == NULL)
  173118. ERREXIT(cinfo, JERR_BAD_VIRTUAL_ACCESS);
  173119. /* Make the desired part of the virtual array accessible */
  173120. if (start_row < ptr->cur_start_row ||
  173121. end_row > ptr->cur_start_row+ptr->rows_in_mem) {
  173122. if (! ptr->b_s_open)
  173123. ERREXIT(cinfo, JERR_VIRTUAL_BUG);
  173124. /* Flush old buffer contents if necessary */
  173125. if (ptr->dirty) {
  173126. do_barray_io(cinfo, ptr, TRUE);
  173127. ptr->dirty = FALSE;
  173128. }
  173129. /* Decide what part of virtual array to access.
  173130. * Algorithm: if target address > current window, assume forward scan,
  173131. * load starting at target address. If target address < current window,
  173132. * assume backward scan, load so that target area is top of window.
  173133. * Note that when switching from forward write to forward read, will have
  173134. * start_row = 0, so the limiting case applies and we load from 0 anyway.
  173135. */
  173136. if (start_row > ptr->cur_start_row) {
  173137. ptr->cur_start_row = start_row;
  173138. } else {
  173139. /* use long arithmetic here to avoid overflow & unsigned problems */
  173140. long ltemp;
  173141. ltemp = (long) end_row - (long) ptr->rows_in_mem;
  173142. if (ltemp < 0)
  173143. ltemp = 0; /* don't fall off front end of file */
  173144. ptr->cur_start_row = (JDIMENSION) ltemp;
  173145. }
  173146. /* Read in the selected part of the array.
  173147. * During the initial write pass, we will do no actual read
  173148. * because the selected part is all undefined.
  173149. */
  173150. do_barray_io(cinfo, ptr, FALSE);
  173151. }
  173152. /* Ensure the accessed part of the array is defined; prezero if needed.
  173153. * To improve locality of access, we only prezero the part of the array
  173154. * that the caller is about to access, not the entire in-memory array.
  173155. */
  173156. if (ptr->first_undef_row < end_row) {
  173157. if (ptr->first_undef_row < start_row) {
  173158. if (writable) /* writer skipped over a section of array */
  173159. ERREXIT(cinfo, JERR_BAD_VIRTUAL_ACCESS);
  173160. undef_row = start_row; /* but reader is allowed to read ahead */
  173161. } else {
  173162. undef_row = ptr->first_undef_row;
  173163. }
  173164. if (writable)
  173165. ptr->first_undef_row = end_row;
  173166. if (ptr->pre_zero) {
  173167. size_t bytesperrow = (size_t) ptr->blocksperrow * SIZEOF(JBLOCK);
  173168. undef_row -= ptr->cur_start_row; /* make indexes relative to buffer */
  173169. end_row -= ptr->cur_start_row;
  173170. while (undef_row < end_row) {
  173171. jzero_far((void FAR *) ptr->mem_buffer[undef_row], bytesperrow);
  173172. undef_row++;
  173173. }
  173174. } else {
  173175. if (! writable) /* reader looking at undefined data */
  173176. ERREXIT(cinfo, JERR_BAD_VIRTUAL_ACCESS);
  173177. }
  173178. }
  173179. /* Flag the buffer dirty if caller will write in it */
  173180. if (writable)
  173181. ptr->dirty = TRUE;
  173182. /* Return address of proper part of the buffer */
  173183. return ptr->mem_buffer + (start_row - ptr->cur_start_row);
  173184. }
  173185. /*
  173186. * Release all objects belonging to a specified pool.
  173187. */
  173188. METHODDEF(void)
  173189. free_pool (j_common_ptr cinfo, int pool_id)
  173190. {
  173191. my_mem_ptr mem = (my_mem_ptr) cinfo->mem;
  173192. small_pool_ptr shdr_ptr;
  173193. large_pool_ptr lhdr_ptr;
  173194. size_t space_freed;
  173195. if (pool_id < 0 || pool_id >= JPOOL_NUMPOOLS)
  173196. ERREXIT1(cinfo, JERR_BAD_POOL_ID, pool_id); /* safety check */
  173197. #ifdef MEM_STATS
  173198. if (cinfo->err->trace_level > 1)
  173199. print_mem_stats(cinfo, pool_id); /* print pool's memory usage statistics */
  173200. #endif
  173201. /* If freeing IMAGE pool, close any virtual arrays first */
  173202. if (pool_id == JPOOL_IMAGE) {
  173203. jvirt_sarray_ptr sptr;
  173204. jvirt_barray_ptr bptr;
  173205. for (sptr = mem->virt_sarray_list; sptr != NULL; sptr = sptr->next) {
  173206. if (sptr->b_s_open) { /* there may be no backing store */
  173207. sptr->b_s_open = FALSE; /* prevent recursive close if error */
  173208. (*sptr->b_s_info.close_backing_store) (cinfo, & sptr->b_s_info);
  173209. }
  173210. }
  173211. mem->virt_sarray_list = NULL;
  173212. for (bptr = mem->virt_barray_list; bptr != NULL; bptr = bptr->next) {
  173213. if (bptr->b_s_open) { /* there may be no backing store */
  173214. bptr->b_s_open = FALSE; /* prevent recursive close if error */
  173215. (*bptr->b_s_info.close_backing_store) (cinfo, & bptr->b_s_info);
  173216. }
  173217. }
  173218. mem->virt_barray_list = NULL;
  173219. }
  173220. /* Release large objects */
  173221. lhdr_ptr = mem->large_list[pool_id];
  173222. mem->large_list[pool_id] = NULL;
  173223. while (lhdr_ptr != NULL) {
  173224. large_pool_ptr next_lhdr_ptr = lhdr_ptr->hdr.next;
  173225. space_freed = lhdr_ptr->hdr.bytes_used +
  173226. lhdr_ptr->hdr.bytes_left +
  173227. SIZEOF(large_pool_hdr);
  173228. jpeg_free_large(cinfo, (void FAR *) lhdr_ptr, space_freed);
  173229. mem->total_space_allocated -= space_freed;
  173230. lhdr_ptr = next_lhdr_ptr;
  173231. }
  173232. /* Release small objects */
  173233. shdr_ptr = mem->small_list[pool_id];
  173234. mem->small_list[pool_id] = NULL;
  173235. while (shdr_ptr != NULL) {
  173236. small_pool_ptr next_shdr_ptr = shdr_ptr->hdr.next;
  173237. space_freed = shdr_ptr->hdr.bytes_used +
  173238. shdr_ptr->hdr.bytes_left +
  173239. SIZEOF(small_pool_hdr);
  173240. jpeg_free_small(cinfo, (void *) shdr_ptr, space_freed);
  173241. mem->total_space_allocated -= space_freed;
  173242. shdr_ptr = next_shdr_ptr;
  173243. }
  173244. }
  173245. /*
  173246. * Close up shop entirely.
  173247. * Note that this cannot be called unless cinfo->mem is non-NULL.
  173248. */
  173249. METHODDEF(void)
  173250. self_destruct (j_common_ptr cinfo)
  173251. {
  173252. int pool;
  173253. /* Close all backing store, release all memory.
  173254. * Releasing pools in reverse order might help avoid fragmentation
  173255. * with some (brain-damaged) malloc libraries.
  173256. */
  173257. for (pool = JPOOL_NUMPOOLS-1; pool >= JPOOL_PERMANENT; pool--) {
  173258. free_pool(cinfo, pool);
  173259. }
  173260. /* Release the memory manager control block too. */
  173261. jpeg_free_small(cinfo, (void *) cinfo->mem, SIZEOF(my_memory_mgr));
  173262. cinfo->mem = NULL; /* ensures I will be called only once */
  173263. jpeg_mem_term(cinfo); /* system-dependent cleanup */
  173264. }
  173265. /*
  173266. * Memory manager initialization.
  173267. * When this is called, only the error manager pointer is valid in cinfo!
  173268. */
  173269. GLOBAL(void)
  173270. jinit_memory_mgr (j_common_ptr cinfo)
  173271. {
  173272. my_mem_ptr mem;
  173273. long max_to_use;
  173274. int pool;
  173275. size_t test_mac;
  173276. cinfo->mem = NULL; /* for safety if init fails */
  173277. /* Check for configuration errors.
  173278. * SIZEOF(ALIGN_TYPE) should be a power of 2; otherwise, it probably
  173279. * doesn't reflect any real hardware alignment requirement.
  173280. * The test is a little tricky: for X>0, X and X-1 have no one-bits
  173281. * in common if and only if X is a power of 2, ie has only one one-bit.
  173282. * Some compilers may give an "unreachable code" warning here; ignore it.
  173283. */
  173284. if ((SIZEOF(ALIGN_TYPE) & (SIZEOF(ALIGN_TYPE)-1)) != 0)
  173285. ERREXIT(cinfo, JERR_BAD_ALIGN_TYPE);
  173286. /* MAX_ALLOC_CHUNK must be representable as type size_t, and must be
  173287. * a multiple of SIZEOF(ALIGN_TYPE).
  173288. * Again, an "unreachable code" warning may be ignored here.
  173289. * But a "constant too large" warning means you need to fix MAX_ALLOC_CHUNK.
  173290. */
  173291. test_mac = (size_t) MAX_ALLOC_CHUNK;
  173292. if ((long) test_mac != MAX_ALLOC_CHUNK ||
  173293. (MAX_ALLOC_CHUNK % SIZEOF(ALIGN_TYPE)) != 0)
  173294. ERREXIT(cinfo, JERR_BAD_ALLOC_CHUNK);
  173295. max_to_use = jpeg_mem_init(cinfo); /* system-dependent initialization */
  173296. /* Attempt to allocate memory manager's control block */
  173297. mem = (my_mem_ptr) jpeg_get_small(cinfo, SIZEOF(my_memory_mgr));
  173298. if (mem == NULL) {
  173299. jpeg_mem_term(cinfo); /* system-dependent cleanup */
  173300. ERREXIT1(cinfo, JERR_OUT_OF_MEMORY, 0);
  173301. }
  173302. /* OK, fill in the method pointers */
  173303. mem->pub.alloc_small = alloc_small;
  173304. mem->pub.alloc_large = alloc_large;
  173305. mem->pub.alloc_sarray = alloc_sarray;
  173306. mem->pub.alloc_barray = alloc_barray;
  173307. mem->pub.request_virt_sarray = request_virt_sarray;
  173308. mem->pub.request_virt_barray = request_virt_barray;
  173309. mem->pub.realize_virt_arrays = realize_virt_arrays;
  173310. mem->pub.access_virt_sarray = access_virt_sarray;
  173311. mem->pub.access_virt_barray = access_virt_barray;
  173312. mem->pub.free_pool = free_pool;
  173313. mem->pub.self_destruct = self_destruct;
  173314. /* Make MAX_ALLOC_CHUNK accessible to other modules */
  173315. mem->pub.max_alloc_chunk = MAX_ALLOC_CHUNK;
  173316. /* Initialize working state */
  173317. mem->pub.max_memory_to_use = max_to_use;
  173318. for (pool = JPOOL_NUMPOOLS-1; pool >= JPOOL_PERMANENT; pool--) {
  173319. mem->small_list[pool] = NULL;
  173320. mem->large_list[pool] = NULL;
  173321. }
  173322. mem->virt_sarray_list = NULL;
  173323. mem->virt_barray_list = NULL;
  173324. mem->total_space_allocated = SIZEOF(my_memory_mgr);
  173325. /* Declare ourselves open for business */
  173326. cinfo->mem = & mem->pub;
  173327. /* Check for an environment variable JPEGMEM; if found, override the
  173328. * default max_memory setting from jpeg_mem_init. Note that the
  173329. * surrounding application may again override this value.
  173330. * If your system doesn't support getenv(), define NO_GETENV to disable
  173331. * this feature.
  173332. */
  173333. #ifndef NO_GETENV
  173334. { char * memenv;
  173335. if ((memenv = getenv("JPEGMEM")) != NULL) {
  173336. char ch = 'x';
  173337. if (sscanf(memenv, "%ld%c", &max_to_use, &ch) > 0) {
  173338. if (ch == 'm' || ch == 'M')
  173339. max_to_use *= 1000L;
  173340. mem->pub.max_memory_to_use = max_to_use * 1000L;
  173341. }
  173342. }
  173343. }
  173344. #endif
  173345. }
  173346. /*** End of inlined file: jmemmgr.c ***/
  173347. /*** Start of inlined file: jmemnobs.c ***/
  173348. #define JPEG_INTERNALS
  173349. #ifndef HAVE_STDLIB_H /* <stdlib.h> should declare malloc(),free() */
  173350. extern void * malloc JPP((size_t size));
  173351. extern void free JPP((void *ptr));
  173352. #endif
  173353. /*
  173354. * Memory allocation and freeing are controlled by the regular library
  173355. * routines malloc() and free().
  173356. */
  173357. GLOBAL(void *)
  173358. jpeg_get_small (j_common_ptr cinfo, size_t sizeofobject)
  173359. {
  173360. return (void *) malloc(sizeofobject);
  173361. }
  173362. GLOBAL(void)
  173363. jpeg_free_small (j_common_ptr cinfo, void * object, size_t sizeofobject)
  173364. {
  173365. free(object);
  173366. }
  173367. /*
  173368. * "Large" objects are treated the same as "small" ones.
  173369. * NB: although we include FAR keywords in the routine declarations,
  173370. * this file won't actually work in 80x86 small/medium model; at least,
  173371. * you probably won't be able to process useful-size images in only 64KB.
  173372. */
  173373. GLOBAL(void FAR *)
  173374. jpeg_get_large (j_common_ptr cinfo, size_t sizeofobject)
  173375. {
  173376. return (void FAR *) malloc(sizeofobject);
  173377. }
  173378. GLOBAL(void)
  173379. jpeg_free_large (j_common_ptr cinfo, void FAR * object, size_t sizeofobject)
  173380. {
  173381. free(object);
  173382. }
  173383. /*
  173384. * This routine computes the total memory space available for allocation.
  173385. * Here we always say, "we got all you want bud!"
  173386. */
  173387. GLOBAL(long)
  173388. jpeg_mem_available (j_common_ptr cinfo, long min_bytes_needed,
  173389. long max_bytes_needed, long already_allocated)
  173390. {
  173391. return max_bytes_needed;
  173392. }
  173393. /*
  173394. * Backing store (temporary file) management.
  173395. * Since jpeg_mem_available always promised the moon,
  173396. * this should never be called and we can just error out.
  173397. */
  173398. GLOBAL(void)
  173399. jpeg_open_backing_store (j_common_ptr cinfo, struct backing_store_struct *info,
  173400. long total_bytes_needed)
  173401. {
  173402. ERREXIT(cinfo, JERR_NO_BACKING_STORE);
  173403. }
  173404. /*
  173405. * These routines take care of any system-dependent initialization and
  173406. * cleanup required. Here, there isn't any.
  173407. */
  173408. GLOBAL(long)
  173409. jpeg_mem_init (j_common_ptr cinfo)
  173410. {
  173411. return 0; /* just set max_memory_to_use to 0 */
  173412. }
  173413. GLOBAL(void)
  173414. jpeg_mem_term (j_common_ptr cinfo)
  173415. {
  173416. /* no work */
  173417. }
  173418. /*** End of inlined file: jmemnobs.c ***/
  173419. /*** Start of inlined file: jquant1.c ***/
  173420. #define JPEG_INTERNALS
  173421. #ifdef QUANT_1PASS_SUPPORTED
  173422. /*
  173423. * The main purpose of 1-pass quantization is to provide a fast, if not very
  173424. * high quality, colormapped output capability. A 2-pass quantizer usually
  173425. * gives better visual quality; however, for quantized grayscale output this
  173426. * quantizer is perfectly adequate. Dithering is highly recommended with this
  173427. * quantizer, though you can turn it off if you really want to.
  173428. *
  173429. * In 1-pass quantization the colormap must be chosen in advance of seeing the
  173430. * image. We use a map consisting of all combinations of Ncolors[i] color
  173431. * values for the i'th component. The Ncolors[] values are chosen so that
  173432. * their product, the total number of colors, is no more than that requested.
  173433. * (In most cases, the product will be somewhat less.)
  173434. *
  173435. * Since the colormap is orthogonal, the representative value for each color
  173436. * component can be determined without considering the other components;
  173437. * then these indexes can be combined into a colormap index by a standard
  173438. * N-dimensional-array-subscript calculation. Most of the arithmetic involved
  173439. * can be precalculated and stored in the lookup table colorindex[].
  173440. * colorindex[i][j] maps pixel value j in component i to the nearest
  173441. * representative value (grid plane) for that component; this index is
  173442. * multiplied by the array stride for component i, so that the
  173443. * index of the colormap entry closest to a given pixel value is just
  173444. * sum( colorindex[component-number][pixel-component-value] )
  173445. * Aside from being fast, this scheme allows for variable spacing between
  173446. * representative values with no additional lookup cost.
  173447. *
  173448. * If gamma correction has been applied in color conversion, it might be wise
  173449. * to adjust the color grid spacing so that the representative colors are
  173450. * equidistant in linear space. At this writing, gamma correction is not
  173451. * implemented by jdcolor, so nothing is done here.
  173452. */
  173453. /* Declarations for ordered dithering.
  173454. *
  173455. * We use a standard 16x16 ordered dither array. The basic concept of ordered
  173456. * dithering is described in many references, for instance Dale Schumacher's
  173457. * chapter II.2 of Graphics Gems II (James Arvo, ed. Academic Press, 1991).
  173458. * In place of Schumacher's comparisons against a "threshold" value, we add a
  173459. * "dither" value to the input pixel and then round the result to the nearest
  173460. * output value. The dither value is equivalent to (0.5 - threshold) times
  173461. * the distance between output values. For ordered dithering, we assume that
  173462. * the output colors are equally spaced; if not, results will probably be
  173463. * worse, since the dither may be too much or too little at a given point.
  173464. *
  173465. * The normal calculation would be to form pixel value + dither, range-limit
  173466. * this to 0..MAXJSAMPLE, and then index into the colorindex table as usual.
  173467. * We can skip the separate range-limiting step by extending the colorindex
  173468. * table in both directions.
  173469. */
  173470. #define ODITHER_SIZE 16 /* dimension of dither matrix */
  173471. /* NB: if ODITHER_SIZE is not a power of 2, ODITHER_MASK uses will break */
  173472. #define ODITHER_CELLS (ODITHER_SIZE*ODITHER_SIZE) /* # cells in matrix */
  173473. #define ODITHER_MASK (ODITHER_SIZE-1) /* mask for wrapping around counters */
  173474. typedef int ODITHER_MATRIX[ODITHER_SIZE][ODITHER_SIZE];
  173475. typedef int (*ODITHER_MATRIX_PTR)[ODITHER_SIZE];
  173476. static const UINT8 base_dither_matrix[ODITHER_SIZE][ODITHER_SIZE] = {
  173477. /* Bayer's order-4 dither array. Generated by the code given in
  173478. * Stephen Hawley's article "Ordered Dithering" in Graphics Gems I.
  173479. * The values in this array must range from 0 to ODITHER_CELLS-1.
  173480. */
  173481. { 0,192, 48,240, 12,204, 60,252, 3,195, 51,243, 15,207, 63,255 },
  173482. { 128, 64,176,112,140, 76,188,124,131, 67,179,115,143, 79,191,127 },
  173483. { 32,224, 16,208, 44,236, 28,220, 35,227, 19,211, 47,239, 31,223 },
  173484. { 160, 96,144, 80,172,108,156, 92,163, 99,147, 83,175,111,159, 95 },
  173485. { 8,200, 56,248, 4,196, 52,244, 11,203, 59,251, 7,199, 55,247 },
  173486. { 136, 72,184,120,132, 68,180,116,139, 75,187,123,135, 71,183,119 },
  173487. { 40,232, 24,216, 36,228, 20,212, 43,235, 27,219, 39,231, 23,215 },
  173488. { 168,104,152, 88,164,100,148, 84,171,107,155, 91,167,103,151, 87 },
  173489. { 2,194, 50,242, 14,206, 62,254, 1,193, 49,241, 13,205, 61,253 },
  173490. { 130, 66,178,114,142, 78,190,126,129, 65,177,113,141, 77,189,125 },
  173491. { 34,226, 18,210, 46,238, 30,222, 33,225, 17,209, 45,237, 29,221 },
  173492. { 162, 98,146, 82,174,110,158, 94,161, 97,145, 81,173,109,157, 93 },
  173493. { 10,202, 58,250, 6,198, 54,246, 9,201, 57,249, 5,197, 53,245 },
  173494. { 138, 74,186,122,134, 70,182,118,137, 73,185,121,133, 69,181,117 },
  173495. { 42,234, 26,218, 38,230, 22,214, 41,233, 25,217, 37,229, 21,213 },
  173496. { 170,106,154, 90,166,102,150, 86,169,105,153, 89,165,101,149, 85 }
  173497. };
  173498. /* Declarations for Floyd-Steinberg dithering.
  173499. *
  173500. * Errors are accumulated into the array fserrors[], at a resolution of
  173501. * 1/16th of a pixel count. The error at a given pixel is propagated
  173502. * to its not-yet-processed neighbors using the standard F-S fractions,
  173503. * ... (here) 7/16
  173504. * 3/16 5/16 1/16
  173505. * We work left-to-right on even rows, right-to-left on odd rows.
  173506. *
  173507. * We can get away with a single array (holding one row's worth of errors)
  173508. * by using it to store the current row's errors at pixel columns not yet
  173509. * processed, but the next row's errors at columns already processed. We
  173510. * need only a few extra variables to hold the errors immediately around the
  173511. * current column. (If we are lucky, those variables are in registers, but
  173512. * even if not, they're probably cheaper to access than array elements are.)
  173513. *
  173514. * The fserrors[] array is indexed [component#][position].
  173515. * We provide (#columns + 2) entries per component; the extra entry at each
  173516. * end saves us from special-casing the first and last pixels.
  173517. *
  173518. * Note: on a wide image, we might not have enough room in a PC's near data
  173519. * segment to hold the error array; so it is allocated with alloc_large.
  173520. */
  173521. #if BITS_IN_JSAMPLE == 8
  173522. typedef INT16 FSERROR; /* 16 bits should be enough */
  173523. typedef int LOCFSERROR; /* use 'int' for calculation temps */
  173524. #else
  173525. typedef INT32 FSERROR; /* may need more than 16 bits */
  173526. typedef INT32 LOCFSERROR; /* be sure calculation temps are big enough */
  173527. #endif
  173528. typedef FSERROR FAR *FSERRPTR; /* pointer to error array (in FAR storage!) */
  173529. /* Private subobject */
  173530. #define MAX_Q_COMPS 4 /* max components I can handle */
  173531. typedef struct {
  173532. struct jpeg_color_quantizer pub; /* public fields */
  173533. /* Initially allocated colormap is saved here */
  173534. JSAMPARRAY sv_colormap; /* The color map as a 2-D pixel array */
  173535. int sv_actual; /* number of entries in use */
  173536. JSAMPARRAY colorindex; /* Precomputed mapping for speed */
  173537. /* colorindex[i][j] = index of color closest to pixel value j in component i,
  173538. * premultiplied as described above. Since colormap indexes must fit into
  173539. * JSAMPLEs, the entries of this array will too.
  173540. */
  173541. boolean is_padded; /* is the colorindex padded for odither? */
  173542. int Ncolors[MAX_Q_COMPS]; /* # of values alloced to each component */
  173543. /* Variables for ordered dithering */
  173544. int row_index; /* cur row's vertical index in dither matrix */
  173545. ODITHER_MATRIX_PTR odither[MAX_Q_COMPS]; /* one dither array per component */
  173546. /* Variables for Floyd-Steinberg dithering */
  173547. FSERRPTR fserrors[MAX_Q_COMPS]; /* accumulated errors */
  173548. boolean on_odd_row; /* flag to remember which row we are on */
  173549. } my_cquantizer;
  173550. typedef my_cquantizer * my_cquantize_ptr;
  173551. /*
  173552. * Policy-making subroutines for create_colormap and create_colorindex.
  173553. * These routines determine the colormap to be used. The rest of the module
  173554. * only assumes that the colormap is orthogonal.
  173555. *
  173556. * * select_ncolors decides how to divvy up the available colors
  173557. * among the components.
  173558. * * output_value defines the set of representative values for a component.
  173559. * * largest_input_value defines the mapping from input values to
  173560. * representative values for a component.
  173561. * Note that the latter two routines may impose different policies for
  173562. * different components, though this is not currently done.
  173563. */
  173564. LOCAL(int)
  173565. select_ncolors (j_decompress_ptr cinfo, int Ncolors[])
  173566. /* Determine allocation of desired colors to components, */
  173567. /* and fill in Ncolors[] array to indicate choice. */
  173568. /* Return value is total number of colors (product of Ncolors[] values). */
  173569. {
  173570. int nc = cinfo->out_color_components; /* number of color components */
  173571. int max_colors = cinfo->desired_number_of_colors;
  173572. int total_colors, iroot, i, j;
  173573. boolean changed;
  173574. long temp;
  173575. static const int RGB_order[3] = { RGB_GREEN, RGB_RED, RGB_BLUE };
  173576. /* We can allocate at least the nc'th root of max_colors per component. */
  173577. /* Compute floor(nc'th root of max_colors). */
  173578. iroot = 1;
  173579. do {
  173580. iroot++;
  173581. temp = iroot; /* set temp = iroot ** nc */
  173582. for (i = 1; i < nc; i++)
  173583. temp *= iroot;
  173584. } while (temp <= (long) max_colors); /* repeat till iroot exceeds root */
  173585. iroot--; /* now iroot = floor(root) */
  173586. /* Must have at least 2 color values per component */
  173587. if (iroot < 2)
  173588. ERREXIT1(cinfo, JERR_QUANT_FEW_COLORS, (int) temp);
  173589. /* Initialize to iroot color values for each component */
  173590. total_colors = 1;
  173591. for (i = 0; i < nc; i++) {
  173592. Ncolors[i] = iroot;
  173593. total_colors *= iroot;
  173594. }
  173595. /* We may be able to increment the count for one or more components without
  173596. * exceeding max_colors, though we know not all can be incremented.
  173597. * Sometimes, the first component can be incremented more than once!
  173598. * (Example: for 16 colors, we start at 2*2*2, go to 3*2*2, then 4*2*2.)
  173599. * In RGB colorspace, try to increment G first, then R, then B.
  173600. */
  173601. do {
  173602. changed = FALSE;
  173603. for (i = 0; i < nc; i++) {
  173604. j = (cinfo->out_color_space == JCS_RGB ? RGB_order[i] : i);
  173605. /* calculate new total_colors if Ncolors[j] is incremented */
  173606. temp = total_colors / Ncolors[j];
  173607. temp *= Ncolors[j]+1; /* done in long arith to avoid oflo */
  173608. if (temp > (long) max_colors)
  173609. break; /* won't fit, done with this pass */
  173610. Ncolors[j]++; /* OK, apply the increment */
  173611. total_colors = (int) temp;
  173612. changed = TRUE;
  173613. }
  173614. } while (changed);
  173615. return total_colors;
  173616. }
  173617. LOCAL(int)
  173618. output_value (j_decompress_ptr cinfo, int ci, int j, int maxj)
  173619. /* Return j'th output value, where j will range from 0 to maxj */
  173620. /* The output values must fall in 0..MAXJSAMPLE in increasing order */
  173621. {
  173622. /* We always provide values 0 and MAXJSAMPLE for each component;
  173623. * any additional values are equally spaced between these limits.
  173624. * (Forcing the upper and lower values to the limits ensures that
  173625. * dithering can't produce a color outside the selected gamut.)
  173626. */
  173627. return (int) (((INT32) j * MAXJSAMPLE + maxj/2) / maxj);
  173628. }
  173629. LOCAL(int)
  173630. largest_input_value (j_decompress_ptr cinfo, int ci, int j, int maxj)
  173631. /* Return largest input value that should map to j'th output value */
  173632. /* Must have largest(j=0) >= 0, and largest(j=maxj) >= MAXJSAMPLE */
  173633. {
  173634. /* Breakpoints are halfway between values returned by output_value */
  173635. return (int) (((INT32) (2*j + 1) * MAXJSAMPLE + maxj) / (2*maxj));
  173636. }
  173637. /*
  173638. * Create the colormap.
  173639. */
  173640. LOCAL(void)
  173641. create_colormap (j_decompress_ptr cinfo)
  173642. {
  173643. my_cquantize_ptr cquantize = (my_cquantize_ptr) cinfo->cquantize;
  173644. JSAMPARRAY colormap; /* Created colormap */
  173645. int total_colors; /* Number of distinct output colors */
  173646. int i,j,k, nci, blksize, blkdist, ptr, val;
  173647. /* Select number of colors for each component */
  173648. total_colors = select_ncolors(cinfo, cquantize->Ncolors);
  173649. /* Report selected color counts */
  173650. if (cinfo->out_color_components == 3)
  173651. TRACEMS4(cinfo, 1, JTRC_QUANT_3_NCOLORS,
  173652. total_colors, cquantize->Ncolors[0],
  173653. cquantize->Ncolors[1], cquantize->Ncolors[2]);
  173654. else
  173655. TRACEMS1(cinfo, 1, JTRC_QUANT_NCOLORS, total_colors);
  173656. /* Allocate and fill in the colormap. */
  173657. /* The colors are ordered in the map in standard row-major order, */
  173658. /* i.e. rightmost (highest-indexed) color changes most rapidly. */
  173659. colormap = (*cinfo->mem->alloc_sarray)
  173660. ((j_common_ptr) cinfo, JPOOL_IMAGE,
  173661. (JDIMENSION) total_colors, (JDIMENSION) cinfo->out_color_components);
  173662. /* blksize is number of adjacent repeated entries for a component */
  173663. /* blkdist is distance between groups of identical entries for a component */
  173664. blkdist = total_colors;
  173665. for (i = 0; i < cinfo->out_color_components; i++) {
  173666. /* fill in colormap entries for i'th color component */
  173667. nci = cquantize->Ncolors[i]; /* # of distinct values for this color */
  173668. blksize = blkdist / nci;
  173669. for (j = 0; j < nci; j++) {
  173670. /* Compute j'th output value (out of nci) for component */
  173671. val = output_value(cinfo, i, j, nci-1);
  173672. /* Fill in all colormap entries that have this value of this component */
  173673. for (ptr = j * blksize; ptr < total_colors; ptr += blkdist) {
  173674. /* fill in blksize entries beginning at ptr */
  173675. for (k = 0; k < blksize; k++)
  173676. colormap[i][ptr+k] = (JSAMPLE) val;
  173677. }
  173678. }
  173679. blkdist = blksize; /* blksize of this color is blkdist of next */
  173680. }
  173681. /* Save the colormap in private storage,
  173682. * where it will survive color quantization mode changes.
  173683. */
  173684. cquantize->sv_colormap = colormap;
  173685. cquantize->sv_actual = total_colors;
  173686. }
  173687. /*
  173688. * Create the color index table.
  173689. */
  173690. LOCAL(void)
  173691. create_colorindex (j_decompress_ptr cinfo)
  173692. {
  173693. my_cquantize_ptr cquantize = (my_cquantize_ptr) cinfo->cquantize;
  173694. JSAMPROW indexptr;
  173695. int i,j,k, nci, blksize, val, pad;
  173696. /* For ordered dither, we pad the color index tables by MAXJSAMPLE in
  173697. * each direction (input index values can be -MAXJSAMPLE .. 2*MAXJSAMPLE).
  173698. * This is not necessary in the other dithering modes. However, we
  173699. * flag whether it was done in case user changes dithering mode.
  173700. */
  173701. if (cinfo->dither_mode == JDITHER_ORDERED) {
  173702. pad = MAXJSAMPLE*2;
  173703. cquantize->is_padded = TRUE;
  173704. } else {
  173705. pad = 0;
  173706. cquantize->is_padded = FALSE;
  173707. }
  173708. cquantize->colorindex = (*cinfo->mem->alloc_sarray)
  173709. ((j_common_ptr) cinfo, JPOOL_IMAGE,
  173710. (JDIMENSION) (MAXJSAMPLE+1 + pad),
  173711. (JDIMENSION) cinfo->out_color_components);
  173712. /* blksize is number of adjacent repeated entries for a component */
  173713. blksize = cquantize->sv_actual;
  173714. for (i = 0; i < cinfo->out_color_components; i++) {
  173715. /* fill in colorindex entries for i'th color component */
  173716. nci = cquantize->Ncolors[i]; /* # of distinct values for this color */
  173717. blksize = blksize / nci;
  173718. /* adjust colorindex pointers to provide padding at negative indexes. */
  173719. if (pad)
  173720. cquantize->colorindex[i] += MAXJSAMPLE;
  173721. /* in loop, val = index of current output value, */
  173722. /* and k = largest j that maps to current val */
  173723. indexptr = cquantize->colorindex[i];
  173724. val = 0;
  173725. k = largest_input_value(cinfo, i, 0, nci-1);
  173726. for (j = 0; j <= MAXJSAMPLE; j++) {
  173727. while (j > k) /* advance val if past boundary */
  173728. k = largest_input_value(cinfo, i, ++val, nci-1);
  173729. /* premultiply so that no multiplication needed in main processing */
  173730. indexptr[j] = (JSAMPLE) (val * blksize);
  173731. }
  173732. /* Pad at both ends if necessary */
  173733. if (pad)
  173734. for (j = 1; j <= MAXJSAMPLE; j++) {
  173735. indexptr[-j] = indexptr[0];
  173736. indexptr[MAXJSAMPLE+j] = indexptr[MAXJSAMPLE];
  173737. }
  173738. }
  173739. }
  173740. /*
  173741. * Create an ordered-dither array for a component having ncolors
  173742. * distinct output values.
  173743. */
  173744. LOCAL(ODITHER_MATRIX_PTR)
  173745. make_odither_array (j_decompress_ptr cinfo, int ncolors)
  173746. {
  173747. ODITHER_MATRIX_PTR odither;
  173748. int j,k;
  173749. INT32 num,den;
  173750. odither = (ODITHER_MATRIX_PTR)
  173751. (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_IMAGE,
  173752. SIZEOF(ODITHER_MATRIX));
  173753. /* The inter-value distance for this color is MAXJSAMPLE/(ncolors-1).
  173754. * Hence the dither value for the matrix cell with fill order f
  173755. * (f=0..N-1) should be (N-1-2*f)/(2*N) * MAXJSAMPLE/(ncolors-1).
  173756. * On 16-bit-int machine, be careful to avoid overflow.
  173757. */
  173758. den = 2 * ODITHER_CELLS * ((INT32) (ncolors - 1));
  173759. for (j = 0; j < ODITHER_SIZE; j++) {
  173760. for (k = 0; k < ODITHER_SIZE; k++) {
  173761. num = ((INT32) (ODITHER_CELLS-1 - 2*((int)base_dither_matrix[j][k])))
  173762. * MAXJSAMPLE;
  173763. /* Ensure round towards zero despite C's lack of consistency
  173764. * about rounding negative values in integer division...
  173765. */
  173766. odither[j][k] = (int) (num<0 ? -((-num)/den) : num/den);
  173767. }
  173768. }
  173769. return odither;
  173770. }
  173771. /*
  173772. * Create the ordered-dither tables.
  173773. * Components having the same number of representative colors may
  173774. * share a dither table.
  173775. */
  173776. LOCAL(void)
  173777. create_odither_tables (j_decompress_ptr cinfo)
  173778. {
  173779. my_cquantize_ptr cquantize = (my_cquantize_ptr) cinfo->cquantize;
  173780. ODITHER_MATRIX_PTR odither;
  173781. int i, j, nci;
  173782. for (i = 0; i < cinfo->out_color_components; i++) {
  173783. nci = cquantize->Ncolors[i]; /* # of distinct values for this color */
  173784. odither = NULL; /* search for matching prior component */
  173785. for (j = 0; j < i; j++) {
  173786. if (nci == cquantize->Ncolors[j]) {
  173787. odither = cquantize->odither[j];
  173788. break;
  173789. }
  173790. }
  173791. if (odither == NULL) /* need a new table? */
  173792. odither = make_odither_array(cinfo, nci);
  173793. cquantize->odither[i] = odither;
  173794. }
  173795. }
  173796. /*
  173797. * Map some rows of pixels to the output colormapped representation.
  173798. */
  173799. METHODDEF(void)
  173800. color_quantize (j_decompress_ptr cinfo, JSAMPARRAY input_buf,
  173801. JSAMPARRAY output_buf, int num_rows)
  173802. /* General case, no dithering */
  173803. {
  173804. my_cquantize_ptr cquantize = (my_cquantize_ptr) cinfo->cquantize;
  173805. JSAMPARRAY colorindex = cquantize->colorindex;
  173806. register int pixcode, ci;
  173807. register JSAMPROW ptrin, ptrout;
  173808. int row;
  173809. JDIMENSION col;
  173810. JDIMENSION width = cinfo->output_width;
  173811. register int nc = cinfo->out_color_components;
  173812. for (row = 0; row < num_rows; row++) {
  173813. ptrin = input_buf[row];
  173814. ptrout = output_buf[row];
  173815. for (col = width; col > 0; col--) {
  173816. pixcode = 0;
  173817. for (ci = 0; ci < nc; ci++) {
  173818. pixcode += GETJSAMPLE(colorindex[ci][GETJSAMPLE(*ptrin++)]);
  173819. }
  173820. *ptrout++ = (JSAMPLE) pixcode;
  173821. }
  173822. }
  173823. }
  173824. METHODDEF(void)
  173825. color_quantize3 (j_decompress_ptr cinfo, JSAMPARRAY input_buf,
  173826. JSAMPARRAY output_buf, int num_rows)
  173827. /* Fast path for out_color_components==3, no dithering */
  173828. {
  173829. my_cquantize_ptr cquantize = (my_cquantize_ptr) cinfo->cquantize;
  173830. register int pixcode;
  173831. register JSAMPROW ptrin, ptrout;
  173832. JSAMPROW colorindex0 = cquantize->colorindex[0];
  173833. JSAMPROW colorindex1 = cquantize->colorindex[1];
  173834. JSAMPROW colorindex2 = cquantize->colorindex[2];
  173835. int row;
  173836. JDIMENSION col;
  173837. JDIMENSION width = cinfo->output_width;
  173838. for (row = 0; row < num_rows; row++) {
  173839. ptrin = input_buf[row];
  173840. ptrout = output_buf[row];
  173841. for (col = width; col > 0; col--) {
  173842. pixcode = GETJSAMPLE(colorindex0[GETJSAMPLE(*ptrin++)]);
  173843. pixcode += GETJSAMPLE(colorindex1[GETJSAMPLE(*ptrin++)]);
  173844. pixcode += GETJSAMPLE(colorindex2[GETJSAMPLE(*ptrin++)]);
  173845. *ptrout++ = (JSAMPLE) pixcode;
  173846. }
  173847. }
  173848. }
  173849. METHODDEF(void)
  173850. quantize_ord_dither (j_decompress_ptr cinfo, JSAMPARRAY input_buf,
  173851. JSAMPARRAY output_buf, int num_rows)
  173852. /* General case, with ordered dithering */
  173853. {
  173854. my_cquantize_ptr cquantize = (my_cquantize_ptr) cinfo->cquantize;
  173855. register JSAMPROW input_ptr;
  173856. register JSAMPROW output_ptr;
  173857. JSAMPROW colorindex_ci;
  173858. int * dither; /* points to active row of dither matrix */
  173859. int row_index, col_index; /* current indexes into dither matrix */
  173860. int nc = cinfo->out_color_components;
  173861. int ci;
  173862. int row;
  173863. JDIMENSION col;
  173864. JDIMENSION width = cinfo->output_width;
  173865. for (row = 0; row < num_rows; row++) {
  173866. /* Initialize output values to 0 so can process components separately */
  173867. jzero_far((void FAR *) output_buf[row],
  173868. (size_t) (width * SIZEOF(JSAMPLE)));
  173869. row_index = cquantize->row_index;
  173870. for (ci = 0; ci < nc; ci++) {
  173871. input_ptr = input_buf[row] + ci;
  173872. output_ptr = output_buf[row];
  173873. colorindex_ci = cquantize->colorindex[ci];
  173874. dither = cquantize->odither[ci][row_index];
  173875. col_index = 0;
  173876. for (col = width; col > 0; col--) {
  173877. /* Form pixel value + dither, range-limit to 0..MAXJSAMPLE,
  173878. * select output value, accumulate into output code for this pixel.
  173879. * Range-limiting need not be done explicitly, as we have extended
  173880. * the colorindex table to produce the right answers for out-of-range
  173881. * inputs. The maximum dither is +- MAXJSAMPLE; this sets the
  173882. * required amount of padding.
  173883. */
  173884. *output_ptr += colorindex_ci[GETJSAMPLE(*input_ptr)+dither[col_index]];
  173885. input_ptr += nc;
  173886. output_ptr++;
  173887. col_index = (col_index + 1) & ODITHER_MASK;
  173888. }
  173889. }
  173890. /* Advance row index for next row */
  173891. row_index = (row_index + 1) & ODITHER_MASK;
  173892. cquantize->row_index = row_index;
  173893. }
  173894. }
  173895. METHODDEF(void)
  173896. quantize3_ord_dither (j_decompress_ptr cinfo, JSAMPARRAY input_buf,
  173897. JSAMPARRAY output_buf, int num_rows)
  173898. /* Fast path for out_color_components==3, with ordered dithering */
  173899. {
  173900. my_cquantize_ptr cquantize = (my_cquantize_ptr) cinfo->cquantize;
  173901. register int pixcode;
  173902. register JSAMPROW input_ptr;
  173903. register JSAMPROW output_ptr;
  173904. JSAMPROW colorindex0 = cquantize->colorindex[0];
  173905. JSAMPROW colorindex1 = cquantize->colorindex[1];
  173906. JSAMPROW colorindex2 = cquantize->colorindex[2];
  173907. int * dither0; /* points to active row of dither matrix */
  173908. int * dither1;
  173909. int * dither2;
  173910. int row_index, col_index; /* current indexes into dither matrix */
  173911. int row;
  173912. JDIMENSION col;
  173913. JDIMENSION width = cinfo->output_width;
  173914. for (row = 0; row < num_rows; row++) {
  173915. row_index = cquantize->row_index;
  173916. input_ptr = input_buf[row];
  173917. output_ptr = output_buf[row];
  173918. dither0 = cquantize->odither[0][row_index];
  173919. dither1 = cquantize->odither[1][row_index];
  173920. dither2 = cquantize->odither[2][row_index];
  173921. col_index = 0;
  173922. for (col = width; col > 0; col--) {
  173923. pixcode = GETJSAMPLE(colorindex0[GETJSAMPLE(*input_ptr++) +
  173924. dither0[col_index]]);
  173925. pixcode += GETJSAMPLE(colorindex1[GETJSAMPLE(*input_ptr++) +
  173926. dither1[col_index]]);
  173927. pixcode += GETJSAMPLE(colorindex2[GETJSAMPLE(*input_ptr++) +
  173928. dither2[col_index]]);
  173929. *output_ptr++ = (JSAMPLE) pixcode;
  173930. col_index = (col_index + 1) & ODITHER_MASK;
  173931. }
  173932. row_index = (row_index + 1) & ODITHER_MASK;
  173933. cquantize->row_index = row_index;
  173934. }
  173935. }
  173936. METHODDEF(void)
  173937. quantize_fs_dither (j_decompress_ptr cinfo, JSAMPARRAY input_buf,
  173938. JSAMPARRAY output_buf, int num_rows)
  173939. /* General case, with Floyd-Steinberg dithering */
  173940. {
  173941. my_cquantize_ptr cquantize = (my_cquantize_ptr) cinfo->cquantize;
  173942. register LOCFSERROR cur; /* current error or pixel value */
  173943. LOCFSERROR belowerr; /* error for pixel below cur */
  173944. LOCFSERROR bpreverr; /* error for below/prev col */
  173945. LOCFSERROR bnexterr; /* error for below/next col */
  173946. LOCFSERROR delta;
  173947. register FSERRPTR errorptr; /* => fserrors[] at column before current */
  173948. register JSAMPROW input_ptr;
  173949. register JSAMPROW output_ptr;
  173950. JSAMPROW colorindex_ci;
  173951. JSAMPROW colormap_ci;
  173952. int pixcode;
  173953. int nc = cinfo->out_color_components;
  173954. int dir; /* 1 for left-to-right, -1 for right-to-left */
  173955. int dirnc; /* dir * nc */
  173956. int ci;
  173957. int row;
  173958. JDIMENSION col;
  173959. JDIMENSION width = cinfo->output_width;
  173960. JSAMPLE *range_limit = cinfo->sample_range_limit;
  173961. SHIFT_TEMPS
  173962. for (row = 0; row < num_rows; row++) {
  173963. /* Initialize output values to 0 so can process components separately */
  173964. jzero_far((void FAR *) output_buf[row],
  173965. (size_t) (width * SIZEOF(JSAMPLE)));
  173966. for (ci = 0; ci < nc; ci++) {
  173967. input_ptr = input_buf[row] + ci;
  173968. output_ptr = output_buf[row];
  173969. if (cquantize->on_odd_row) {
  173970. /* work right to left in this row */
  173971. input_ptr += (width-1) * nc; /* so point to rightmost pixel */
  173972. output_ptr += width-1;
  173973. dir = -1;
  173974. dirnc = -nc;
  173975. errorptr = cquantize->fserrors[ci] + (width+1); /* => entry after last column */
  173976. } else {
  173977. /* work left to right in this row */
  173978. dir = 1;
  173979. dirnc = nc;
  173980. errorptr = cquantize->fserrors[ci]; /* => entry before first column */
  173981. }
  173982. colorindex_ci = cquantize->colorindex[ci];
  173983. colormap_ci = cquantize->sv_colormap[ci];
  173984. /* Preset error values: no error propagated to first pixel from left */
  173985. cur = 0;
  173986. /* and no error propagated to row below yet */
  173987. belowerr = bpreverr = 0;
  173988. for (col = width; col > 0; col--) {
  173989. /* cur holds the error propagated from the previous pixel on the
  173990. * current line. Add the error propagated from the previous line
  173991. * to form the complete error correction term for this pixel, and
  173992. * round the error term (which is expressed * 16) to an integer.
  173993. * RIGHT_SHIFT rounds towards minus infinity, so adding 8 is correct
  173994. * for either sign of the error value.
  173995. * Note: errorptr points to *previous* column's array entry.
  173996. */
  173997. cur = RIGHT_SHIFT(cur + errorptr[dir] + 8, 4);
  173998. /* Form pixel value + error, and range-limit to 0..MAXJSAMPLE.
  173999. * The maximum error is +- MAXJSAMPLE; this sets the required size
  174000. * of the range_limit array.
  174001. */
  174002. cur += GETJSAMPLE(*input_ptr);
  174003. cur = GETJSAMPLE(range_limit[cur]);
  174004. /* Select output value, accumulate into output code for this pixel */
  174005. pixcode = GETJSAMPLE(colorindex_ci[cur]);
  174006. *output_ptr += (JSAMPLE) pixcode;
  174007. /* Compute actual representation error at this pixel */
  174008. /* Note: we can do this even though we don't have the final */
  174009. /* pixel code, because the colormap is orthogonal. */
  174010. cur -= GETJSAMPLE(colormap_ci[pixcode]);
  174011. /* Compute error fractions to be propagated to adjacent pixels.
  174012. * Add these into the running sums, and simultaneously shift the
  174013. * next-line error sums left by 1 column.
  174014. */
  174015. bnexterr = cur;
  174016. delta = cur * 2;
  174017. cur += delta; /* form error * 3 */
  174018. errorptr[0] = (FSERROR) (bpreverr + cur);
  174019. cur += delta; /* form error * 5 */
  174020. bpreverr = belowerr + cur;
  174021. belowerr = bnexterr;
  174022. cur += delta; /* form error * 7 */
  174023. /* At this point cur contains the 7/16 error value to be propagated
  174024. * to the next pixel on the current line, and all the errors for the
  174025. * next line have been shifted over. We are therefore ready to move on.
  174026. */
  174027. input_ptr += dirnc; /* advance input ptr to next column */
  174028. output_ptr += dir; /* advance output ptr to next column */
  174029. errorptr += dir; /* advance errorptr to current column */
  174030. }
  174031. /* Post-loop cleanup: we must unload the final error value into the
  174032. * final fserrors[] entry. Note we need not unload belowerr because
  174033. * it is for the dummy column before or after the actual array.
  174034. */
  174035. errorptr[0] = (FSERROR) bpreverr; /* unload prev err into array */
  174036. }
  174037. cquantize->on_odd_row = (cquantize->on_odd_row ? FALSE : TRUE);
  174038. }
  174039. }
  174040. /*
  174041. * Allocate workspace for Floyd-Steinberg errors.
  174042. */
  174043. LOCAL(void)
  174044. alloc_fs_workspace (j_decompress_ptr cinfo)
  174045. {
  174046. my_cquantize_ptr cquantize = (my_cquantize_ptr) cinfo->cquantize;
  174047. size_t arraysize;
  174048. int i;
  174049. arraysize = (size_t) ((cinfo->output_width + 2) * SIZEOF(FSERROR));
  174050. for (i = 0; i < cinfo->out_color_components; i++) {
  174051. cquantize->fserrors[i] = (FSERRPTR)
  174052. (*cinfo->mem->alloc_large)((j_common_ptr) cinfo, JPOOL_IMAGE, arraysize);
  174053. }
  174054. }
  174055. /*
  174056. * Initialize for one-pass color quantization.
  174057. */
  174058. METHODDEF(void)
  174059. start_pass_1_quant (j_decompress_ptr cinfo, boolean is_pre_scan)
  174060. {
  174061. my_cquantize_ptr cquantize = (my_cquantize_ptr) cinfo->cquantize;
  174062. size_t arraysize;
  174063. int i;
  174064. /* Install my colormap. */
  174065. cinfo->colormap = cquantize->sv_colormap;
  174066. cinfo->actual_number_of_colors = cquantize->sv_actual;
  174067. /* Initialize for desired dithering mode. */
  174068. switch (cinfo->dither_mode) {
  174069. case JDITHER_NONE:
  174070. if (cinfo->out_color_components == 3)
  174071. cquantize->pub.color_quantize = color_quantize3;
  174072. else
  174073. cquantize->pub.color_quantize = color_quantize;
  174074. break;
  174075. case JDITHER_ORDERED:
  174076. if (cinfo->out_color_components == 3)
  174077. cquantize->pub.color_quantize = quantize3_ord_dither;
  174078. else
  174079. cquantize->pub.color_quantize = quantize_ord_dither;
  174080. cquantize->row_index = 0; /* initialize state for ordered dither */
  174081. /* If user changed to ordered dither from another mode,
  174082. * we must recreate the color index table with padding.
  174083. * This will cost extra space, but probably isn't very likely.
  174084. */
  174085. if (! cquantize->is_padded)
  174086. create_colorindex(cinfo);
  174087. /* Create ordered-dither tables if we didn't already. */
  174088. if (cquantize->odither[0] == NULL)
  174089. create_odither_tables(cinfo);
  174090. break;
  174091. case JDITHER_FS:
  174092. cquantize->pub.color_quantize = quantize_fs_dither;
  174093. cquantize->on_odd_row = FALSE; /* initialize state for F-S dither */
  174094. /* Allocate Floyd-Steinberg workspace if didn't already. */
  174095. if (cquantize->fserrors[0] == NULL)
  174096. alloc_fs_workspace(cinfo);
  174097. /* Initialize the propagated errors to zero. */
  174098. arraysize = (size_t) ((cinfo->output_width + 2) * SIZEOF(FSERROR));
  174099. for (i = 0; i < cinfo->out_color_components; i++)
  174100. jzero_far((void FAR *) cquantize->fserrors[i], arraysize);
  174101. break;
  174102. default:
  174103. ERREXIT(cinfo, JERR_NOT_COMPILED);
  174104. break;
  174105. }
  174106. }
  174107. /*
  174108. * Finish up at the end of the pass.
  174109. */
  174110. METHODDEF(void)
  174111. finish_pass_1_quant (j_decompress_ptr cinfo)
  174112. {
  174113. /* no work in 1-pass case */
  174114. }
  174115. /*
  174116. * Switch to a new external colormap between output passes.
  174117. * Shouldn't get to this module!
  174118. */
  174119. METHODDEF(void)
  174120. new_color_map_1_quant (j_decompress_ptr cinfo)
  174121. {
  174122. ERREXIT(cinfo, JERR_MODE_CHANGE);
  174123. }
  174124. /*
  174125. * Module initialization routine for 1-pass color quantization.
  174126. */
  174127. GLOBAL(void)
  174128. jinit_1pass_quantizer (j_decompress_ptr cinfo)
  174129. {
  174130. my_cquantize_ptr cquantize;
  174131. cquantize = (my_cquantize_ptr)
  174132. (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_IMAGE,
  174133. SIZEOF(my_cquantizer));
  174134. cinfo->cquantize = (struct jpeg_color_quantizer *) cquantize;
  174135. cquantize->pub.start_pass = start_pass_1_quant;
  174136. cquantize->pub.finish_pass = finish_pass_1_quant;
  174137. cquantize->pub.new_color_map = new_color_map_1_quant;
  174138. cquantize->fserrors[0] = NULL; /* Flag FS workspace not allocated */
  174139. cquantize->odither[0] = NULL; /* Also flag odither arrays not allocated */
  174140. /* Make sure my internal arrays won't overflow */
  174141. if (cinfo->out_color_components > MAX_Q_COMPS)
  174142. ERREXIT1(cinfo, JERR_QUANT_COMPONENTS, MAX_Q_COMPS);
  174143. /* Make sure colormap indexes can be represented by JSAMPLEs */
  174144. if (cinfo->desired_number_of_colors > (MAXJSAMPLE+1))
  174145. ERREXIT1(cinfo, JERR_QUANT_MANY_COLORS, MAXJSAMPLE+1);
  174146. /* Create the colormap and color index table. */
  174147. create_colormap(cinfo);
  174148. create_colorindex(cinfo);
  174149. /* Allocate Floyd-Steinberg workspace now if requested.
  174150. * We do this now since it is FAR storage and may affect the memory
  174151. * manager's space calculations. If the user changes to FS dither
  174152. * mode in a later pass, we will allocate the space then, and will
  174153. * possibly overrun the max_memory_to_use setting.
  174154. */
  174155. if (cinfo->dither_mode == JDITHER_FS)
  174156. alloc_fs_workspace(cinfo);
  174157. }
  174158. #endif /* QUANT_1PASS_SUPPORTED */
  174159. /*** End of inlined file: jquant1.c ***/
  174160. /*** Start of inlined file: jquant2.c ***/
  174161. #define JPEG_INTERNALS
  174162. #ifdef QUANT_2PASS_SUPPORTED
  174163. /*
  174164. * This module implements the well-known Heckbert paradigm for color
  174165. * quantization. Most of the ideas used here can be traced back to
  174166. * Heckbert's seminal paper
  174167. * Heckbert, Paul. "Color Image Quantization for Frame Buffer Display",
  174168. * Proc. SIGGRAPH '82, Computer Graphics v.16 #3 (July 1982), pp 297-304.
  174169. *
  174170. * In the first pass over the image, we accumulate a histogram showing the
  174171. * usage count of each possible color. To keep the histogram to a reasonable
  174172. * size, we reduce the precision of the input; typical practice is to retain
  174173. * 5 or 6 bits per color, so that 8 or 4 different input values are counted
  174174. * in the same histogram cell.
  174175. *
  174176. * Next, the color-selection step begins with a box representing the whole
  174177. * color space, and repeatedly splits the "largest" remaining box until we
  174178. * have as many boxes as desired colors. Then the mean color in each
  174179. * remaining box becomes one of the possible output colors.
  174180. *
  174181. * The second pass over the image maps each input pixel to the closest output
  174182. * color (optionally after applying a Floyd-Steinberg dithering correction).
  174183. * This mapping is logically trivial, but making it go fast enough requires
  174184. * considerable care.
  174185. *
  174186. * Heckbert-style quantizers vary a good deal in their policies for choosing
  174187. * the "largest" box and deciding where to cut it. The particular policies
  174188. * used here have proved out well in experimental comparisons, but better ones
  174189. * may yet be found.
  174190. *
  174191. * In earlier versions of the IJG code, this module quantized in YCbCr color
  174192. * space, processing the raw upsampled data without a color conversion step.
  174193. * This allowed the color conversion math to be done only once per colormap
  174194. * entry, not once per pixel. However, that optimization precluded other
  174195. * useful optimizations (such as merging color conversion with upsampling)
  174196. * and it also interfered with desired capabilities such as quantizing to an
  174197. * externally-supplied colormap. We have therefore abandoned that approach.
  174198. * The present code works in the post-conversion color space, typically RGB.
  174199. *
  174200. * To improve the visual quality of the results, we actually work in scaled
  174201. * RGB space, giving G distances more weight than R, and R in turn more than
  174202. * B. To do everything in integer math, we must use integer scale factors.
  174203. * The 2/3/1 scale factors used here correspond loosely to the relative
  174204. * weights of the colors in the NTSC grayscale equation.
  174205. * If you want to use this code to quantize a non-RGB color space, you'll
  174206. * probably need to change these scale factors.
  174207. */
  174208. #define R_SCALE 2 /* scale R distances by this much */
  174209. #define G_SCALE 3 /* scale G distances by this much */
  174210. #define B_SCALE 1 /* and B by this much */
  174211. /* Relabel R/G/B as components 0/1/2, respecting the RGB ordering defined
  174212. * in jmorecfg.h. As the code stands, it will do the right thing for R,G,B
  174213. * and B,G,R orders. If you define some other weird order in jmorecfg.h,
  174214. * you'll get compile errors until you extend this logic. In that case
  174215. * you'll probably want to tweak the histogram sizes too.
  174216. */
  174217. #if RGB_RED == 0
  174218. #define C0_SCALE R_SCALE
  174219. #endif
  174220. #if RGB_BLUE == 0
  174221. #define C0_SCALE B_SCALE
  174222. #endif
  174223. #if RGB_GREEN == 1
  174224. #define C1_SCALE G_SCALE
  174225. #endif
  174226. #if RGB_RED == 2
  174227. #define C2_SCALE R_SCALE
  174228. #endif
  174229. #if RGB_BLUE == 2
  174230. #define C2_SCALE B_SCALE
  174231. #endif
  174232. /*
  174233. * First we have the histogram data structure and routines for creating it.
  174234. *
  174235. * The number of bits of precision can be adjusted by changing these symbols.
  174236. * We recommend keeping 6 bits for G and 5 each for R and B.
  174237. * If you have plenty of memory and cycles, 6 bits all around gives marginally
  174238. * better results; if you are short of memory, 5 bits all around will save
  174239. * some space but degrade the results.
  174240. * To maintain a fully accurate histogram, we'd need to allocate a "long"
  174241. * (preferably unsigned long) for each cell. In practice this is overkill;
  174242. * we can get by with 16 bits per cell. Few of the cell counts will overflow,
  174243. * and clamping those that do overflow to the maximum value will give close-
  174244. * enough results. This reduces the recommended histogram size from 256Kb
  174245. * to 128Kb, which is a useful savings on PC-class machines.
  174246. * (In the second pass the histogram space is re-used for pixel mapping data;
  174247. * in that capacity, each cell must be able to store zero to the number of
  174248. * desired colors. 16 bits/cell is plenty for that too.)
  174249. * Since the JPEG code is intended to run in small memory model on 80x86
  174250. * machines, we can't just allocate the histogram in one chunk. Instead
  174251. * of a true 3-D array, we use a row of pointers to 2-D arrays. Each
  174252. * pointer corresponds to a C0 value (typically 2^5 = 32 pointers) and
  174253. * each 2-D array has 2^6*2^5 = 2048 or 2^6*2^6 = 4096 entries. Note that
  174254. * on 80x86 machines, the pointer row is in near memory but the actual
  174255. * arrays are in far memory (same arrangement as we use for image arrays).
  174256. */
  174257. #define MAXNUMCOLORS (MAXJSAMPLE+1) /* maximum size of colormap */
  174258. /* These will do the right thing for either R,G,B or B,G,R color order,
  174259. * but you may not like the results for other color orders.
  174260. */
  174261. #define HIST_C0_BITS 5 /* bits of precision in R/B histogram */
  174262. #define HIST_C1_BITS 6 /* bits of precision in G histogram */
  174263. #define HIST_C2_BITS 5 /* bits of precision in B/R histogram */
  174264. /* Number of elements along histogram axes. */
  174265. #define HIST_C0_ELEMS (1<<HIST_C0_BITS)
  174266. #define HIST_C1_ELEMS (1<<HIST_C1_BITS)
  174267. #define HIST_C2_ELEMS (1<<HIST_C2_BITS)
  174268. /* These are the amounts to shift an input value to get a histogram index. */
  174269. #define C0_SHIFT (BITS_IN_JSAMPLE-HIST_C0_BITS)
  174270. #define C1_SHIFT (BITS_IN_JSAMPLE-HIST_C1_BITS)
  174271. #define C2_SHIFT (BITS_IN_JSAMPLE-HIST_C2_BITS)
  174272. typedef UINT16 histcell; /* histogram cell; prefer an unsigned type */
  174273. typedef histcell FAR * histptr; /* for pointers to histogram cells */
  174274. typedef histcell hist1d[HIST_C2_ELEMS]; /* typedefs for the array */
  174275. typedef hist1d FAR * hist2d; /* type for the 2nd-level pointers */
  174276. typedef hist2d * hist3d; /* type for top-level pointer */
  174277. /* Declarations for Floyd-Steinberg dithering.
  174278. *
  174279. * Errors are accumulated into the array fserrors[], at a resolution of
  174280. * 1/16th of a pixel count. The error at a given pixel is propagated
  174281. * to its not-yet-processed neighbors using the standard F-S fractions,
  174282. * ... (here) 7/16
  174283. * 3/16 5/16 1/16
  174284. * We work left-to-right on even rows, right-to-left on odd rows.
  174285. *
  174286. * We can get away with a single array (holding one row's worth of errors)
  174287. * by using it to store the current row's errors at pixel columns not yet
  174288. * processed, but the next row's errors at columns already processed. We
  174289. * need only a few extra variables to hold the errors immediately around the
  174290. * current column. (If we are lucky, those variables are in registers, but
  174291. * even if not, they're probably cheaper to access than array elements are.)
  174292. *
  174293. * The fserrors[] array has (#columns + 2) entries; the extra entry at
  174294. * each end saves us from special-casing the first and last pixels.
  174295. * Each entry is three values long, one value for each color component.
  174296. *
  174297. * Note: on a wide image, we might not have enough room in a PC's near data
  174298. * segment to hold the error array; so it is allocated with alloc_large.
  174299. */
  174300. #if BITS_IN_JSAMPLE == 8
  174301. typedef INT16 FSERROR; /* 16 bits should be enough */
  174302. typedef int LOCFSERROR; /* use 'int' for calculation temps */
  174303. #else
  174304. typedef INT32 FSERROR; /* may need more than 16 bits */
  174305. typedef INT32 LOCFSERROR; /* be sure calculation temps are big enough */
  174306. #endif
  174307. typedef FSERROR FAR *FSERRPTR; /* pointer to error array (in FAR storage!) */
  174308. /* Private subobject */
  174309. typedef struct {
  174310. struct jpeg_color_quantizer pub; /* public fields */
  174311. /* Space for the eventually created colormap is stashed here */
  174312. JSAMPARRAY sv_colormap; /* colormap allocated at init time */
  174313. int desired; /* desired # of colors = size of colormap */
  174314. /* Variables for accumulating image statistics */
  174315. hist3d histogram; /* pointer to the histogram */
  174316. boolean needs_zeroed; /* TRUE if next pass must zero histogram */
  174317. /* Variables for Floyd-Steinberg dithering */
  174318. FSERRPTR fserrors; /* accumulated errors */
  174319. boolean on_odd_row; /* flag to remember which row we are on */
  174320. int * error_limiter; /* table for clamping the applied error */
  174321. } my_cquantizer2;
  174322. typedef my_cquantizer2 * my_cquantize_ptr2;
  174323. /*
  174324. * Prescan some rows of pixels.
  174325. * In this module the prescan simply updates the histogram, which has been
  174326. * initialized to zeroes by start_pass.
  174327. * An output_buf parameter is required by the method signature, but no data
  174328. * is actually output (in fact the buffer controller is probably passing a
  174329. * NULL pointer).
  174330. */
  174331. METHODDEF(void)
  174332. prescan_quantize (j_decompress_ptr cinfo, JSAMPARRAY input_buf,
  174333. JSAMPARRAY output_buf, int num_rows)
  174334. {
  174335. my_cquantize_ptr2 cquantize = (my_cquantize_ptr2) cinfo->cquantize;
  174336. register JSAMPROW ptr;
  174337. register histptr histp;
  174338. register hist3d histogram = cquantize->histogram;
  174339. int row;
  174340. JDIMENSION col;
  174341. JDIMENSION width = cinfo->output_width;
  174342. for (row = 0; row < num_rows; row++) {
  174343. ptr = input_buf[row];
  174344. for (col = width; col > 0; col--) {
  174345. /* get pixel value and index into the histogram */
  174346. histp = & histogram[GETJSAMPLE(ptr[0]) >> C0_SHIFT]
  174347. [GETJSAMPLE(ptr[1]) >> C1_SHIFT]
  174348. [GETJSAMPLE(ptr[2]) >> C2_SHIFT];
  174349. /* increment, check for overflow and undo increment if so. */
  174350. if (++(*histp) <= 0)
  174351. (*histp)--;
  174352. ptr += 3;
  174353. }
  174354. }
  174355. }
  174356. /*
  174357. * Next we have the really interesting routines: selection of a colormap
  174358. * given the completed histogram.
  174359. * These routines work with a list of "boxes", each representing a rectangular
  174360. * subset of the input color space (to histogram precision).
  174361. */
  174362. typedef struct {
  174363. /* The bounds of the box (inclusive); expressed as histogram indexes */
  174364. int c0min, c0max;
  174365. int c1min, c1max;
  174366. int c2min, c2max;
  174367. /* The volume (actually 2-norm) of the box */
  174368. INT32 volume;
  174369. /* The number of nonzero histogram cells within this box */
  174370. long colorcount;
  174371. } box;
  174372. typedef box * boxptr;
  174373. LOCAL(boxptr)
  174374. find_biggest_color_pop (boxptr boxlist, int numboxes)
  174375. /* Find the splittable box with the largest color population */
  174376. /* Returns NULL if no splittable boxes remain */
  174377. {
  174378. register boxptr boxp;
  174379. register int i;
  174380. register long maxc = 0;
  174381. boxptr which = NULL;
  174382. for (i = 0, boxp = boxlist; i < numboxes; i++, boxp++) {
  174383. if (boxp->colorcount > maxc && boxp->volume > 0) {
  174384. which = boxp;
  174385. maxc = boxp->colorcount;
  174386. }
  174387. }
  174388. return which;
  174389. }
  174390. LOCAL(boxptr)
  174391. find_biggest_volume (boxptr boxlist, int numboxes)
  174392. /* Find the splittable box with the largest (scaled) volume */
  174393. /* Returns NULL if no splittable boxes remain */
  174394. {
  174395. register boxptr boxp;
  174396. register int i;
  174397. register INT32 maxv = 0;
  174398. boxptr which = NULL;
  174399. for (i = 0, boxp = boxlist; i < numboxes; i++, boxp++) {
  174400. if (boxp->volume > maxv) {
  174401. which = boxp;
  174402. maxv = boxp->volume;
  174403. }
  174404. }
  174405. return which;
  174406. }
  174407. LOCAL(void)
  174408. update_box (j_decompress_ptr cinfo, boxptr boxp)
  174409. /* Shrink the min/max bounds of a box to enclose only nonzero elements, */
  174410. /* and recompute its volume and population */
  174411. {
  174412. my_cquantize_ptr2 cquantize = (my_cquantize_ptr2) cinfo->cquantize;
  174413. hist3d histogram = cquantize->histogram;
  174414. histptr histp;
  174415. int c0,c1,c2;
  174416. int c0min,c0max,c1min,c1max,c2min,c2max;
  174417. INT32 dist0,dist1,dist2;
  174418. long ccount;
  174419. c0min = boxp->c0min; c0max = boxp->c0max;
  174420. c1min = boxp->c1min; c1max = boxp->c1max;
  174421. c2min = boxp->c2min; c2max = boxp->c2max;
  174422. if (c0max > c0min)
  174423. for (c0 = c0min; c0 <= c0max; c0++)
  174424. for (c1 = c1min; c1 <= c1max; c1++) {
  174425. histp = & histogram[c0][c1][c2min];
  174426. for (c2 = c2min; c2 <= c2max; c2++)
  174427. if (*histp++ != 0) {
  174428. boxp->c0min = c0min = c0;
  174429. goto have_c0min;
  174430. }
  174431. }
  174432. have_c0min:
  174433. if (c0max > c0min)
  174434. for (c0 = c0max; c0 >= c0min; c0--)
  174435. for (c1 = c1min; c1 <= c1max; c1++) {
  174436. histp = & histogram[c0][c1][c2min];
  174437. for (c2 = c2min; c2 <= c2max; c2++)
  174438. if (*histp++ != 0) {
  174439. boxp->c0max = c0max = c0;
  174440. goto have_c0max;
  174441. }
  174442. }
  174443. have_c0max:
  174444. if (c1max > c1min)
  174445. for (c1 = c1min; c1 <= c1max; c1++)
  174446. for (c0 = c0min; c0 <= c0max; c0++) {
  174447. histp = & histogram[c0][c1][c2min];
  174448. for (c2 = c2min; c2 <= c2max; c2++)
  174449. if (*histp++ != 0) {
  174450. boxp->c1min = c1min = c1;
  174451. goto have_c1min;
  174452. }
  174453. }
  174454. have_c1min:
  174455. if (c1max > c1min)
  174456. for (c1 = c1max; c1 >= c1min; c1--)
  174457. for (c0 = c0min; c0 <= c0max; c0++) {
  174458. histp = & histogram[c0][c1][c2min];
  174459. for (c2 = c2min; c2 <= c2max; c2++)
  174460. if (*histp++ != 0) {
  174461. boxp->c1max = c1max = c1;
  174462. goto have_c1max;
  174463. }
  174464. }
  174465. have_c1max:
  174466. if (c2max > c2min)
  174467. for (c2 = c2min; c2 <= c2max; c2++)
  174468. for (c0 = c0min; c0 <= c0max; c0++) {
  174469. histp = & histogram[c0][c1min][c2];
  174470. for (c1 = c1min; c1 <= c1max; c1++, histp += HIST_C2_ELEMS)
  174471. if (*histp != 0) {
  174472. boxp->c2min = c2min = c2;
  174473. goto have_c2min;
  174474. }
  174475. }
  174476. have_c2min:
  174477. if (c2max > c2min)
  174478. for (c2 = c2max; c2 >= c2min; c2--)
  174479. for (c0 = c0min; c0 <= c0max; c0++) {
  174480. histp = & histogram[c0][c1min][c2];
  174481. for (c1 = c1min; c1 <= c1max; c1++, histp += HIST_C2_ELEMS)
  174482. if (*histp != 0) {
  174483. boxp->c2max = c2max = c2;
  174484. goto have_c2max;
  174485. }
  174486. }
  174487. have_c2max:
  174488. /* Update box volume.
  174489. * We use 2-norm rather than real volume here; this biases the method
  174490. * against making long narrow boxes, and it has the side benefit that
  174491. * a box is splittable iff norm > 0.
  174492. * Since the differences are expressed in histogram-cell units,
  174493. * we have to shift back to JSAMPLE units to get consistent distances;
  174494. * after which, we scale according to the selected distance scale factors.
  174495. */
  174496. dist0 = ((c0max - c0min) << C0_SHIFT) * C0_SCALE;
  174497. dist1 = ((c1max - c1min) << C1_SHIFT) * C1_SCALE;
  174498. dist2 = ((c2max - c2min) << C2_SHIFT) * C2_SCALE;
  174499. boxp->volume = dist0*dist0 + dist1*dist1 + dist2*dist2;
  174500. /* Now scan remaining volume of box and compute population */
  174501. ccount = 0;
  174502. for (c0 = c0min; c0 <= c0max; c0++)
  174503. for (c1 = c1min; c1 <= c1max; c1++) {
  174504. histp = & histogram[c0][c1][c2min];
  174505. for (c2 = c2min; c2 <= c2max; c2++, histp++)
  174506. if (*histp != 0) {
  174507. ccount++;
  174508. }
  174509. }
  174510. boxp->colorcount = ccount;
  174511. }
  174512. LOCAL(int)
  174513. median_cut (j_decompress_ptr cinfo, boxptr boxlist, int numboxes,
  174514. int desired_colors)
  174515. /* Repeatedly select and split the largest box until we have enough boxes */
  174516. {
  174517. int n,lb;
  174518. int c0,c1,c2,cmax;
  174519. register boxptr b1,b2;
  174520. while (numboxes < desired_colors) {
  174521. /* Select box to split.
  174522. * Current algorithm: by population for first half, then by volume.
  174523. */
  174524. if (numboxes*2 <= desired_colors) {
  174525. b1 = find_biggest_color_pop(boxlist, numboxes);
  174526. } else {
  174527. b1 = find_biggest_volume(boxlist, numboxes);
  174528. }
  174529. if (b1 == NULL) /* no splittable boxes left! */
  174530. break;
  174531. b2 = &boxlist[numboxes]; /* where new box will go */
  174532. /* Copy the color bounds to the new box. */
  174533. b2->c0max = b1->c0max; b2->c1max = b1->c1max; b2->c2max = b1->c2max;
  174534. b2->c0min = b1->c0min; b2->c1min = b1->c1min; b2->c2min = b1->c2min;
  174535. /* Choose which axis to split the box on.
  174536. * Current algorithm: longest scaled axis.
  174537. * See notes in update_box about scaling distances.
  174538. */
  174539. c0 = ((b1->c0max - b1->c0min) << C0_SHIFT) * C0_SCALE;
  174540. c1 = ((b1->c1max - b1->c1min) << C1_SHIFT) * C1_SCALE;
  174541. c2 = ((b1->c2max - b1->c2min) << C2_SHIFT) * C2_SCALE;
  174542. /* We want to break any ties in favor of green, then red, blue last.
  174543. * This code does the right thing for R,G,B or B,G,R color orders only.
  174544. */
  174545. #if RGB_RED == 0
  174546. cmax = c1; n = 1;
  174547. if (c0 > cmax) { cmax = c0; n = 0; }
  174548. if (c2 > cmax) { n = 2; }
  174549. #else
  174550. cmax = c1; n = 1;
  174551. if (c2 > cmax) { cmax = c2; n = 2; }
  174552. if (c0 > cmax) { n = 0; }
  174553. #endif
  174554. /* Choose split point along selected axis, and update box bounds.
  174555. * Current algorithm: split at halfway point.
  174556. * (Since the box has been shrunk to minimum volume,
  174557. * any split will produce two nonempty subboxes.)
  174558. * Note that lb value is max for lower box, so must be < old max.
  174559. */
  174560. switch (n) {
  174561. case 0:
  174562. lb = (b1->c0max + b1->c0min) / 2;
  174563. b1->c0max = lb;
  174564. b2->c0min = lb+1;
  174565. break;
  174566. case 1:
  174567. lb = (b1->c1max + b1->c1min) / 2;
  174568. b1->c1max = lb;
  174569. b2->c1min = lb+1;
  174570. break;
  174571. case 2:
  174572. lb = (b1->c2max + b1->c2min) / 2;
  174573. b1->c2max = lb;
  174574. b2->c2min = lb+1;
  174575. break;
  174576. }
  174577. /* Update stats for boxes */
  174578. update_box(cinfo, b1);
  174579. update_box(cinfo, b2);
  174580. numboxes++;
  174581. }
  174582. return numboxes;
  174583. }
  174584. LOCAL(void)
  174585. compute_color (j_decompress_ptr cinfo, boxptr boxp, int icolor)
  174586. /* Compute representative color for a box, put it in colormap[icolor] */
  174587. {
  174588. /* Current algorithm: mean weighted by pixels (not colors) */
  174589. /* Note it is important to get the rounding correct! */
  174590. my_cquantize_ptr2 cquantize = (my_cquantize_ptr2) cinfo->cquantize;
  174591. hist3d histogram = cquantize->histogram;
  174592. histptr histp;
  174593. int c0,c1,c2;
  174594. int c0min,c0max,c1min,c1max,c2min,c2max;
  174595. long count;
  174596. long total = 0;
  174597. long c0total = 0;
  174598. long c1total = 0;
  174599. long c2total = 0;
  174600. c0min = boxp->c0min; c0max = boxp->c0max;
  174601. c1min = boxp->c1min; c1max = boxp->c1max;
  174602. c2min = boxp->c2min; c2max = boxp->c2max;
  174603. for (c0 = c0min; c0 <= c0max; c0++)
  174604. for (c1 = c1min; c1 <= c1max; c1++) {
  174605. histp = & histogram[c0][c1][c2min];
  174606. for (c2 = c2min; c2 <= c2max; c2++) {
  174607. if ((count = *histp++) != 0) {
  174608. total += count;
  174609. c0total += ((c0 << C0_SHIFT) + ((1<<C0_SHIFT)>>1)) * count;
  174610. c1total += ((c1 << C1_SHIFT) + ((1<<C1_SHIFT)>>1)) * count;
  174611. c2total += ((c2 << C2_SHIFT) + ((1<<C2_SHIFT)>>1)) * count;
  174612. }
  174613. }
  174614. }
  174615. cinfo->colormap[0][icolor] = (JSAMPLE) ((c0total + (total>>1)) / total);
  174616. cinfo->colormap[1][icolor] = (JSAMPLE) ((c1total + (total>>1)) / total);
  174617. cinfo->colormap[2][icolor] = (JSAMPLE) ((c2total + (total>>1)) / total);
  174618. }
  174619. LOCAL(void)
  174620. select_colors (j_decompress_ptr cinfo, int desired_colors)
  174621. /* Master routine for color selection */
  174622. {
  174623. boxptr boxlist;
  174624. int numboxes;
  174625. int i;
  174626. /* Allocate workspace for box list */
  174627. boxlist = (boxptr) (*cinfo->mem->alloc_small)
  174628. ((j_common_ptr) cinfo, JPOOL_IMAGE, desired_colors * SIZEOF(box));
  174629. /* Initialize one box containing whole space */
  174630. numboxes = 1;
  174631. boxlist[0].c0min = 0;
  174632. boxlist[0].c0max = MAXJSAMPLE >> C0_SHIFT;
  174633. boxlist[0].c1min = 0;
  174634. boxlist[0].c1max = MAXJSAMPLE >> C1_SHIFT;
  174635. boxlist[0].c2min = 0;
  174636. boxlist[0].c2max = MAXJSAMPLE >> C2_SHIFT;
  174637. /* Shrink it to actually-used volume and set its statistics */
  174638. update_box(cinfo, & boxlist[0]);
  174639. /* Perform median-cut to produce final box list */
  174640. numboxes = median_cut(cinfo, boxlist, numboxes, desired_colors);
  174641. /* Compute the representative color for each box, fill colormap */
  174642. for (i = 0; i < numboxes; i++)
  174643. compute_color(cinfo, & boxlist[i], i);
  174644. cinfo->actual_number_of_colors = numboxes;
  174645. TRACEMS1(cinfo, 1, JTRC_QUANT_SELECTED, numboxes);
  174646. }
  174647. /*
  174648. * These routines are concerned with the time-critical task of mapping input
  174649. * colors to the nearest color in the selected colormap.
  174650. *
  174651. * We re-use the histogram space as an "inverse color map", essentially a
  174652. * cache for the results of nearest-color searches. All colors within a
  174653. * histogram cell will be mapped to the same colormap entry, namely the one
  174654. * closest to the cell's center. This may not be quite the closest entry to
  174655. * the actual input color, but it's almost as good. A zero in the cache
  174656. * indicates we haven't found the nearest color for that cell yet; the array
  174657. * is cleared to zeroes before starting the mapping pass. When we find the
  174658. * nearest color for a cell, its colormap index plus one is recorded in the
  174659. * cache for future use. The pass2 scanning routines call fill_inverse_cmap
  174660. * when they need to use an unfilled entry in the cache.
  174661. *
  174662. * Our method of efficiently finding nearest colors is based on the "locally
  174663. * sorted search" idea described by Heckbert and on the incremental distance
  174664. * calculation described by Spencer W. Thomas in chapter III.1 of Graphics
  174665. * Gems II (James Arvo, ed. Academic Press, 1991). Thomas points out that
  174666. * the distances from a given colormap entry to each cell of the histogram can
  174667. * be computed quickly using an incremental method: the differences between
  174668. * distances to adjacent cells themselves differ by a constant. This allows a
  174669. * fairly fast implementation of the "brute force" approach of computing the
  174670. * distance from every colormap entry to every histogram cell. Unfortunately,
  174671. * it needs a work array to hold the best-distance-so-far for each histogram
  174672. * cell (because the inner loop has to be over cells, not colormap entries).
  174673. * The work array elements have to be INT32s, so the work array would need
  174674. * 256Kb at our recommended precision. This is not feasible in DOS machines.
  174675. *
  174676. * To get around these problems, we apply Thomas' method to compute the
  174677. * nearest colors for only the cells within a small subbox of the histogram.
  174678. * The work array need be only as big as the subbox, so the memory usage
  174679. * problem is solved. Furthermore, we need not fill subboxes that are never
  174680. * referenced in pass2; many images use only part of the color gamut, so a
  174681. * fair amount of work is saved. An additional advantage of this
  174682. * approach is that we can apply Heckbert's locality criterion to quickly
  174683. * eliminate colormap entries that are far away from the subbox; typically
  174684. * three-fourths of the colormap entries are rejected by Heckbert's criterion,
  174685. * and we need not compute their distances to individual cells in the subbox.
  174686. * The speed of this approach is heavily influenced by the subbox size: too
  174687. * small means too much overhead, too big loses because Heckbert's criterion
  174688. * can't eliminate as many colormap entries. Empirically the best subbox
  174689. * size seems to be about 1/512th of the histogram (1/8th in each direction).
  174690. *
  174691. * Thomas' article also describes a refined method which is asymptotically
  174692. * faster than the brute-force method, but it is also far more complex and
  174693. * cannot efficiently be applied to small subboxes. It is therefore not
  174694. * useful for programs intended to be portable to DOS machines. On machines
  174695. * with plenty of memory, filling the whole histogram in one shot with Thomas'
  174696. * refined method might be faster than the present code --- but then again,
  174697. * it might not be any faster, and it's certainly more complicated.
  174698. */
  174699. /* log2(histogram cells in update box) for each axis; this can be adjusted */
  174700. #define BOX_C0_LOG (HIST_C0_BITS-3)
  174701. #define BOX_C1_LOG (HIST_C1_BITS-3)
  174702. #define BOX_C2_LOG (HIST_C2_BITS-3)
  174703. #define BOX_C0_ELEMS (1<<BOX_C0_LOG) /* # of hist cells in update box */
  174704. #define BOX_C1_ELEMS (1<<BOX_C1_LOG)
  174705. #define BOX_C2_ELEMS (1<<BOX_C2_LOG)
  174706. #define BOX_C0_SHIFT (C0_SHIFT + BOX_C0_LOG)
  174707. #define BOX_C1_SHIFT (C1_SHIFT + BOX_C1_LOG)
  174708. #define BOX_C2_SHIFT (C2_SHIFT + BOX_C2_LOG)
  174709. /*
  174710. * The next three routines implement inverse colormap filling. They could
  174711. * all be folded into one big routine, but splitting them up this way saves
  174712. * some stack space (the mindist[] and bestdist[] arrays need not coexist)
  174713. * and may allow some compilers to produce better code by registerizing more
  174714. * inner-loop variables.
  174715. */
  174716. LOCAL(int)
  174717. find_nearby_colors (j_decompress_ptr cinfo, int minc0, int minc1, int minc2,
  174718. JSAMPLE colorlist[])
  174719. /* Locate the colormap entries close enough to an update box to be candidates
  174720. * for the nearest entry to some cell(s) in the update box. The update box
  174721. * is specified by the center coordinates of its first cell. The number of
  174722. * candidate colormap entries is returned, and their colormap indexes are
  174723. * placed in colorlist[].
  174724. * This routine uses Heckbert's "locally sorted search" criterion to select
  174725. * the colors that need further consideration.
  174726. */
  174727. {
  174728. int numcolors = cinfo->actual_number_of_colors;
  174729. int maxc0, maxc1, maxc2;
  174730. int centerc0, centerc1, centerc2;
  174731. int i, x, ncolors;
  174732. INT32 minmaxdist, min_dist, max_dist, tdist;
  174733. INT32 mindist[MAXNUMCOLORS]; /* min distance to colormap entry i */
  174734. /* Compute true coordinates of update box's upper corner and center.
  174735. * Actually we compute the coordinates of the center of the upper-corner
  174736. * histogram cell, which are the upper bounds of the volume we care about.
  174737. * Note that since ">>" rounds down, the "center" values may be closer to
  174738. * min than to max; hence comparisons to them must be "<=", not "<".
  174739. */
  174740. maxc0 = minc0 + ((1 << BOX_C0_SHIFT) - (1 << C0_SHIFT));
  174741. centerc0 = (minc0 + maxc0) >> 1;
  174742. maxc1 = minc1 + ((1 << BOX_C1_SHIFT) - (1 << C1_SHIFT));
  174743. centerc1 = (minc1 + maxc1) >> 1;
  174744. maxc2 = minc2 + ((1 << BOX_C2_SHIFT) - (1 << C2_SHIFT));
  174745. centerc2 = (minc2 + maxc2) >> 1;
  174746. /* For each color in colormap, find:
  174747. * 1. its minimum squared-distance to any point in the update box
  174748. * (zero if color is within update box);
  174749. * 2. its maximum squared-distance to any point in the update box.
  174750. * Both of these can be found by considering only the corners of the box.
  174751. * We save the minimum distance for each color in mindist[];
  174752. * only the smallest maximum distance is of interest.
  174753. */
  174754. minmaxdist = 0x7FFFFFFFL;
  174755. for (i = 0; i < numcolors; i++) {
  174756. /* We compute the squared-c0-distance term, then add in the other two. */
  174757. x = GETJSAMPLE(cinfo->colormap[0][i]);
  174758. if (x < minc0) {
  174759. tdist = (x - minc0) * C0_SCALE;
  174760. min_dist = tdist*tdist;
  174761. tdist = (x - maxc0) * C0_SCALE;
  174762. max_dist = tdist*tdist;
  174763. } else if (x > maxc0) {
  174764. tdist = (x - maxc0) * C0_SCALE;
  174765. min_dist = tdist*tdist;
  174766. tdist = (x - minc0) * C0_SCALE;
  174767. max_dist = tdist*tdist;
  174768. } else {
  174769. /* within cell range so no contribution to min_dist */
  174770. min_dist = 0;
  174771. if (x <= centerc0) {
  174772. tdist = (x - maxc0) * C0_SCALE;
  174773. max_dist = tdist*tdist;
  174774. } else {
  174775. tdist = (x - minc0) * C0_SCALE;
  174776. max_dist = tdist*tdist;
  174777. }
  174778. }
  174779. x = GETJSAMPLE(cinfo->colormap[1][i]);
  174780. if (x < minc1) {
  174781. tdist = (x - minc1) * C1_SCALE;
  174782. min_dist += tdist*tdist;
  174783. tdist = (x - maxc1) * C1_SCALE;
  174784. max_dist += tdist*tdist;
  174785. } else if (x > maxc1) {
  174786. tdist = (x - maxc1) * C1_SCALE;
  174787. min_dist += tdist*tdist;
  174788. tdist = (x - minc1) * C1_SCALE;
  174789. max_dist += tdist*tdist;
  174790. } else {
  174791. /* within cell range so no contribution to min_dist */
  174792. if (x <= centerc1) {
  174793. tdist = (x - maxc1) * C1_SCALE;
  174794. max_dist += tdist*tdist;
  174795. } else {
  174796. tdist = (x - minc1) * C1_SCALE;
  174797. max_dist += tdist*tdist;
  174798. }
  174799. }
  174800. x = GETJSAMPLE(cinfo->colormap[2][i]);
  174801. if (x < minc2) {
  174802. tdist = (x - minc2) * C2_SCALE;
  174803. min_dist += tdist*tdist;
  174804. tdist = (x - maxc2) * C2_SCALE;
  174805. max_dist += tdist*tdist;
  174806. } else if (x > maxc2) {
  174807. tdist = (x - maxc2) * C2_SCALE;
  174808. min_dist += tdist*tdist;
  174809. tdist = (x - minc2) * C2_SCALE;
  174810. max_dist += tdist*tdist;
  174811. } else {
  174812. /* within cell range so no contribution to min_dist */
  174813. if (x <= centerc2) {
  174814. tdist = (x - maxc2) * C2_SCALE;
  174815. max_dist += tdist*tdist;
  174816. } else {
  174817. tdist = (x - minc2) * C2_SCALE;
  174818. max_dist += tdist*tdist;
  174819. }
  174820. }
  174821. mindist[i] = min_dist; /* save away the results */
  174822. if (max_dist < minmaxdist)
  174823. minmaxdist = max_dist;
  174824. }
  174825. /* Now we know that no cell in the update box is more than minmaxdist
  174826. * away from some colormap entry. Therefore, only colors that are
  174827. * within minmaxdist of some part of the box need be considered.
  174828. */
  174829. ncolors = 0;
  174830. for (i = 0; i < numcolors; i++) {
  174831. if (mindist[i] <= minmaxdist)
  174832. colorlist[ncolors++] = (JSAMPLE) i;
  174833. }
  174834. return ncolors;
  174835. }
  174836. LOCAL(void)
  174837. find_best_colors (j_decompress_ptr cinfo, int minc0, int minc1, int minc2,
  174838. int numcolors, JSAMPLE colorlist[], JSAMPLE bestcolor[])
  174839. /* Find the closest colormap entry for each cell in the update box,
  174840. * given the list of candidate colors prepared by find_nearby_colors.
  174841. * Return the indexes of the closest entries in the bestcolor[] array.
  174842. * This routine uses Thomas' incremental distance calculation method to
  174843. * find the distance from a colormap entry to successive cells in the box.
  174844. */
  174845. {
  174846. int ic0, ic1, ic2;
  174847. int i, icolor;
  174848. register INT32 * bptr; /* pointer into bestdist[] array */
  174849. JSAMPLE * cptr; /* pointer into bestcolor[] array */
  174850. INT32 dist0, dist1; /* initial distance values */
  174851. register INT32 dist2; /* current distance in inner loop */
  174852. INT32 xx0, xx1; /* distance increments */
  174853. register INT32 xx2;
  174854. INT32 inc0, inc1, inc2; /* initial values for increments */
  174855. /* This array holds the distance to the nearest-so-far color for each cell */
  174856. INT32 bestdist[BOX_C0_ELEMS * BOX_C1_ELEMS * BOX_C2_ELEMS];
  174857. /* Initialize best-distance for each cell of the update box */
  174858. bptr = bestdist;
  174859. for (i = BOX_C0_ELEMS*BOX_C1_ELEMS*BOX_C2_ELEMS-1; i >= 0; i--)
  174860. *bptr++ = 0x7FFFFFFFL;
  174861. /* For each color selected by find_nearby_colors,
  174862. * compute its distance to the center of each cell in the box.
  174863. * If that's less than best-so-far, update best distance and color number.
  174864. */
  174865. /* Nominal steps between cell centers ("x" in Thomas article) */
  174866. #define STEP_C0 ((1 << C0_SHIFT) * C0_SCALE)
  174867. #define STEP_C1 ((1 << C1_SHIFT) * C1_SCALE)
  174868. #define STEP_C2 ((1 << C2_SHIFT) * C2_SCALE)
  174869. for (i = 0; i < numcolors; i++) {
  174870. icolor = GETJSAMPLE(colorlist[i]);
  174871. /* Compute (square of) distance from minc0/c1/c2 to this color */
  174872. inc0 = (minc0 - GETJSAMPLE(cinfo->colormap[0][icolor])) * C0_SCALE;
  174873. dist0 = inc0*inc0;
  174874. inc1 = (minc1 - GETJSAMPLE(cinfo->colormap[1][icolor])) * C1_SCALE;
  174875. dist0 += inc1*inc1;
  174876. inc2 = (minc2 - GETJSAMPLE(cinfo->colormap[2][icolor])) * C2_SCALE;
  174877. dist0 += inc2*inc2;
  174878. /* Form the initial difference increments */
  174879. inc0 = inc0 * (2 * STEP_C0) + STEP_C0 * STEP_C0;
  174880. inc1 = inc1 * (2 * STEP_C1) + STEP_C1 * STEP_C1;
  174881. inc2 = inc2 * (2 * STEP_C2) + STEP_C2 * STEP_C2;
  174882. /* Now loop over all cells in box, updating distance per Thomas method */
  174883. bptr = bestdist;
  174884. cptr = bestcolor;
  174885. xx0 = inc0;
  174886. for (ic0 = BOX_C0_ELEMS-1; ic0 >= 0; ic0--) {
  174887. dist1 = dist0;
  174888. xx1 = inc1;
  174889. for (ic1 = BOX_C1_ELEMS-1; ic1 >= 0; ic1--) {
  174890. dist2 = dist1;
  174891. xx2 = inc2;
  174892. for (ic2 = BOX_C2_ELEMS-1; ic2 >= 0; ic2--) {
  174893. if (dist2 < *bptr) {
  174894. *bptr = dist2;
  174895. *cptr = (JSAMPLE) icolor;
  174896. }
  174897. dist2 += xx2;
  174898. xx2 += 2 * STEP_C2 * STEP_C2;
  174899. bptr++;
  174900. cptr++;
  174901. }
  174902. dist1 += xx1;
  174903. xx1 += 2 * STEP_C1 * STEP_C1;
  174904. }
  174905. dist0 += xx0;
  174906. xx0 += 2 * STEP_C0 * STEP_C0;
  174907. }
  174908. }
  174909. }
  174910. LOCAL(void)
  174911. fill_inverse_cmap (j_decompress_ptr cinfo, int c0, int c1, int c2)
  174912. /* Fill the inverse-colormap entries in the update box that contains */
  174913. /* histogram cell c0/c1/c2. (Only that one cell MUST be filled, but */
  174914. /* we can fill as many others as we wish.) */
  174915. {
  174916. my_cquantize_ptr2 cquantize = (my_cquantize_ptr2) cinfo->cquantize;
  174917. hist3d histogram = cquantize->histogram;
  174918. int minc0, minc1, minc2; /* lower left corner of update box */
  174919. int ic0, ic1, ic2;
  174920. register JSAMPLE * cptr; /* pointer into bestcolor[] array */
  174921. register histptr cachep; /* pointer into main cache array */
  174922. /* This array lists the candidate colormap indexes. */
  174923. JSAMPLE colorlist[MAXNUMCOLORS];
  174924. int numcolors; /* number of candidate colors */
  174925. /* This array holds the actually closest colormap index for each cell. */
  174926. JSAMPLE bestcolor[BOX_C0_ELEMS * BOX_C1_ELEMS * BOX_C2_ELEMS];
  174927. /* Convert cell coordinates to update box ID */
  174928. c0 >>= BOX_C0_LOG;
  174929. c1 >>= BOX_C1_LOG;
  174930. c2 >>= BOX_C2_LOG;
  174931. /* Compute true coordinates of update box's origin corner.
  174932. * Actually we compute the coordinates of the center of the corner
  174933. * histogram cell, which are the lower bounds of the volume we care about.
  174934. */
  174935. minc0 = (c0 << BOX_C0_SHIFT) + ((1 << C0_SHIFT) >> 1);
  174936. minc1 = (c1 << BOX_C1_SHIFT) + ((1 << C1_SHIFT) >> 1);
  174937. minc2 = (c2 << BOX_C2_SHIFT) + ((1 << C2_SHIFT) >> 1);
  174938. /* Determine which colormap entries are close enough to be candidates
  174939. * for the nearest entry to some cell in the update box.
  174940. */
  174941. numcolors = find_nearby_colors(cinfo, minc0, minc1, minc2, colorlist);
  174942. /* Determine the actually nearest colors. */
  174943. find_best_colors(cinfo, minc0, minc1, minc2, numcolors, colorlist,
  174944. bestcolor);
  174945. /* Save the best color numbers (plus 1) in the main cache array */
  174946. c0 <<= BOX_C0_LOG; /* convert ID back to base cell indexes */
  174947. c1 <<= BOX_C1_LOG;
  174948. c2 <<= BOX_C2_LOG;
  174949. cptr = bestcolor;
  174950. for (ic0 = 0; ic0 < BOX_C0_ELEMS; ic0++) {
  174951. for (ic1 = 0; ic1 < BOX_C1_ELEMS; ic1++) {
  174952. cachep = & histogram[c0+ic0][c1+ic1][c2];
  174953. for (ic2 = 0; ic2 < BOX_C2_ELEMS; ic2++) {
  174954. *cachep++ = (histcell) (GETJSAMPLE(*cptr++) + 1);
  174955. }
  174956. }
  174957. }
  174958. }
  174959. /*
  174960. * Map some rows of pixels to the output colormapped representation.
  174961. */
  174962. METHODDEF(void)
  174963. pass2_no_dither (j_decompress_ptr cinfo,
  174964. JSAMPARRAY input_buf, JSAMPARRAY output_buf, int num_rows)
  174965. /* This version performs no dithering */
  174966. {
  174967. my_cquantize_ptr2 cquantize = (my_cquantize_ptr2) cinfo->cquantize;
  174968. hist3d histogram = cquantize->histogram;
  174969. register JSAMPROW inptr, outptr;
  174970. register histptr cachep;
  174971. register int c0, c1, c2;
  174972. int row;
  174973. JDIMENSION col;
  174974. JDIMENSION width = cinfo->output_width;
  174975. for (row = 0; row < num_rows; row++) {
  174976. inptr = input_buf[row];
  174977. outptr = output_buf[row];
  174978. for (col = width; col > 0; col--) {
  174979. /* get pixel value and index into the cache */
  174980. c0 = GETJSAMPLE(*inptr++) >> C0_SHIFT;
  174981. c1 = GETJSAMPLE(*inptr++) >> C1_SHIFT;
  174982. c2 = GETJSAMPLE(*inptr++) >> C2_SHIFT;
  174983. cachep = & histogram[c0][c1][c2];
  174984. /* If we have not seen this color before, find nearest colormap entry */
  174985. /* and update the cache */
  174986. if (*cachep == 0)
  174987. fill_inverse_cmap(cinfo, c0,c1,c2);
  174988. /* Now emit the colormap index for this cell */
  174989. *outptr++ = (JSAMPLE) (*cachep - 1);
  174990. }
  174991. }
  174992. }
  174993. METHODDEF(void)
  174994. pass2_fs_dither (j_decompress_ptr cinfo,
  174995. JSAMPARRAY input_buf, JSAMPARRAY output_buf, int num_rows)
  174996. /* This version performs Floyd-Steinberg dithering */
  174997. {
  174998. my_cquantize_ptr2 cquantize = (my_cquantize_ptr2) cinfo->cquantize;
  174999. hist3d histogram = cquantize->histogram;
  175000. register LOCFSERROR cur0, cur1, cur2; /* current error or pixel value */
  175001. LOCFSERROR belowerr0, belowerr1, belowerr2; /* error for pixel below cur */
  175002. LOCFSERROR bpreverr0, bpreverr1, bpreverr2; /* error for below/prev col */
  175003. register FSERRPTR errorptr; /* => fserrors[] at column before current */
  175004. JSAMPROW inptr; /* => current input pixel */
  175005. JSAMPROW outptr; /* => current output pixel */
  175006. histptr cachep;
  175007. int dir; /* +1 or -1 depending on direction */
  175008. int dir3; /* 3*dir, for advancing inptr & errorptr */
  175009. int row;
  175010. JDIMENSION col;
  175011. JDIMENSION width = cinfo->output_width;
  175012. JSAMPLE *range_limit = cinfo->sample_range_limit;
  175013. int *error_limit = cquantize->error_limiter;
  175014. JSAMPROW colormap0 = cinfo->colormap[0];
  175015. JSAMPROW colormap1 = cinfo->colormap[1];
  175016. JSAMPROW colormap2 = cinfo->colormap[2];
  175017. SHIFT_TEMPS
  175018. for (row = 0; row < num_rows; row++) {
  175019. inptr = input_buf[row];
  175020. outptr = output_buf[row];
  175021. if (cquantize->on_odd_row) {
  175022. /* work right to left in this row */
  175023. inptr += (width-1) * 3; /* so point to rightmost pixel */
  175024. outptr += width-1;
  175025. dir = -1;
  175026. dir3 = -3;
  175027. errorptr = cquantize->fserrors + (width+1)*3; /* => entry after last column */
  175028. cquantize->on_odd_row = FALSE; /* flip for next time */
  175029. } else {
  175030. /* work left to right in this row */
  175031. dir = 1;
  175032. dir3 = 3;
  175033. errorptr = cquantize->fserrors; /* => entry before first real column */
  175034. cquantize->on_odd_row = TRUE; /* flip for next time */
  175035. }
  175036. /* Preset error values: no error propagated to first pixel from left */
  175037. cur0 = cur1 = cur2 = 0;
  175038. /* and no error propagated to row below yet */
  175039. belowerr0 = belowerr1 = belowerr2 = 0;
  175040. bpreverr0 = bpreverr1 = bpreverr2 = 0;
  175041. for (col = width; col > 0; col--) {
  175042. /* curN holds the error propagated from the previous pixel on the
  175043. * current line. Add the error propagated from the previous line
  175044. * to form the complete error correction term for this pixel, and
  175045. * round the error term (which is expressed * 16) to an integer.
  175046. * RIGHT_SHIFT rounds towards minus infinity, so adding 8 is correct
  175047. * for either sign of the error value.
  175048. * Note: errorptr points to *previous* column's array entry.
  175049. */
  175050. cur0 = RIGHT_SHIFT(cur0 + errorptr[dir3+0] + 8, 4);
  175051. cur1 = RIGHT_SHIFT(cur1 + errorptr[dir3+1] + 8, 4);
  175052. cur2 = RIGHT_SHIFT(cur2 + errorptr[dir3+2] + 8, 4);
  175053. /* Limit the error using transfer function set by init_error_limit.
  175054. * See comments with init_error_limit for rationale.
  175055. */
  175056. cur0 = error_limit[cur0];
  175057. cur1 = error_limit[cur1];
  175058. cur2 = error_limit[cur2];
  175059. /* Form pixel value + error, and range-limit to 0..MAXJSAMPLE.
  175060. * The maximum error is +- MAXJSAMPLE (or less with error limiting);
  175061. * this sets the required size of the range_limit array.
  175062. */
  175063. cur0 += GETJSAMPLE(inptr[0]);
  175064. cur1 += GETJSAMPLE(inptr[1]);
  175065. cur2 += GETJSAMPLE(inptr[2]);
  175066. cur0 = GETJSAMPLE(range_limit[cur0]);
  175067. cur1 = GETJSAMPLE(range_limit[cur1]);
  175068. cur2 = GETJSAMPLE(range_limit[cur2]);
  175069. /* Index into the cache with adjusted pixel value */
  175070. cachep = & histogram[cur0>>C0_SHIFT][cur1>>C1_SHIFT][cur2>>C2_SHIFT];
  175071. /* If we have not seen this color before, find nearest colormap */
  175072. /* entry and update the cache */
  175073. if (*cachep == 0)
  175074. fill_inverse_cmap(cinfo, cur0>>C0_SHIFT,cur1>>C1_SHIFT,cur2>>C2_SHIFT);
  175075. /* Now emit the colormap index for this cell */
  175076. { register int pixcode = *cachep - 1;
  175077. *outptr = (JSAMPLE) pixcode;
  175078. /* Compute representation error for this pixel */
  175079. cur0 -= GETJSAMPLE(colormap0[pixcode]);
  175080. cur1 -= GETJSAMPLE(colormap1[pixcode]);
  175081. cur2 -= GETJSAMPLE(colormap2[pixcode]);
  175082. }
  175083. /* Compute error fractions to be propagated to adjacent pixels.
  175084. * Add these into the running sums, and simultaneously shift the
  175085. * next-line error sums left by 1 column.
  175086. */
  175087. { register LOCFSERROR bnexterr, delta;
  175088. bnexterr = cur0; /* Process component 0 */
  175089. delta = cur0 * 2;
  175090. cur0 += delta; /* form error * 3 */
  175091. errorptr[0] = (FSERROR) (bpreverr0 + cur0);
  175092. cur0 += delta; /* form error * 5 */
  175093. bpreverr0 = belowerr0 + cur0;
  175094. belowerr0 = bnexterr;
  175095. cur0 += delta; /* form error * 7 */
  175096. bnexterr = cur1; /* Process component 1 */
  175097. delta = cur1 * 2;
  175098. cur1 += delta; /* form error * 3 */
  175099. errorptr[1] = (FSERROR) (bpreverr1 + cur1);
  175100. cur1 += delta; /* form error * 5 */
  175101. bpreverr1 = belowerr1 + cur1;
  175102. belowerr1 = bnexterr;
  175103. cur1 += delta; /* form error * 7 */
  175104. bnexterr = cur2; /* Process component 2 */
  175105. delta = cur2 * 2;
  175106. cur2 += delta; /* form error * 3 */
  175107. errorptr[2] = (FSERROR) (bpreverr2 + cur2);
  175108. cur2 += delta; /* form error * 5 */
  175109. bpreverr2 = belowerr2 + cur2;
  175110. belowerr2 = bnexterr;
  175111. cur2 += delta; /* form error * 7 */
  175112. }
  175113. /* At this point curN contains the 7/16 error value to be propagated
  175114. * to the next pixel on the current line, and all the errors for the
  175115. * next line have been shifted over. We are therefore ready to move on.
  175116. */
  175117. inptr += dir3; /* Advance pixel pointers to next column */
  175118. outptr += dir;
  175119. errorptr += dir3; /* advance errorptr to current column */
  175120. }
  175121. /* Post-loop cleanup: we must unload the final error values into the
  175122. * final fserrors[] entry. Note we need not unload belowerrN because
  175123. * it is for the dummy column before or after the actual array.
  175124. */
  175125. errorptr[0] = (FSERROR) bpreverr0; /* unload prev errs into array */
  175126. errorptr[1] = (FSERROR) bpreverr1;
  175127. errorptr[2] = (FSERROR) bpreverr2;
  175128. }
  175129. }
  175130. /*
  175131. * Initialize the error-limiting transfer function (lookup table).
  175132. * The raw F-S error computation can potentially compute error values of up to
  175133. * +- MAXJSAMPLE. But we want the maximum correction applied to a pixel to be
  175134. * much less, otherwise obviously wrong pixels will be created. (Typical
  175135. * effects include weird fringes at color-area boundaries, isolated bright
  175136. * pixels in a dark area, etc.) The standard advice for avoiding this problem
  175137. * is to ensure that the "corners" of the color cube are allocated as output
  175138. * colors; then repeated errors in the same direction cannot cause cascading
  175139. * error buildup. However, that only prevents the error from getting
  175140. * completely out of hand; Aaron Giles reports that error limiting improves
  175141. * the results even with corner colors allocated.
  175142. * A simple clamping of the error values to about +- MAXJSAMPLE/8 works pretty
  175143. * well, but the smoother transfer function used below is even better. Thanks
  175144. * to Aaron Giles for this idea.
  175145. */
  175146. LOCAL(void)
  175147. init_error_limit (j_decompress_ptr cinfo)
  175148. /* Allocate and fill in the error_limiter table */
  175149. {
  175150. my_cquantize_ptr2 cquantize = (my_cquantize_ptr2) cinfo->cquantize;
  175151. int * table;
  175152. int in, out;
  175153. table = (int *) (*cinfo->mem->alloc_small)
  175154. ((j_common_ptr) cinfo, JPOOL_IMAGE, (MAXJSAMPLE*2+1) * SIZEOF(int));
  175155. table += MAXJSAMPLE; /* so can index -MAXJSAMPLE .. +MAXJSAMPLE */
  175156. cquantize->error_limiter = table;
  175157. #define STEPSIZE ((MAXJSAMPLE+1)/16)
  175158. /* Map errors 1:1 up to +- MAXJSAMPLE/16 */
  175159. out = 0;
  175160. for (in = 0; in < STEPSIZE; in++, out++) {
  175161. table[in] = out; table[-in] = -out;
  175162. }
  175163. /* Map errors 1:2 up to +- 3*MAXJSAMPLE/16 */
  175164. for (; in < STEPSIZE*3; in++, out += (in&1) ? 0 : 1) {
  175165. table[in] = out; table[-in] = -out;
  175166. }
  175167. /* Clamp the rest to final out value (which is (MAXJSAMPLE+1)/8) */
  175168. for (; in <= MAXJSAMPLE; in++) {
  175169. table[in] = out; table[-in] = -out;
  175170. }
  175171. #undef STEPSIZE
  175172. }
  175173. /*
  175174. * Finish up at the end of each pass.
  175175. */
  175176. METHODDEF(void)
  175177. finish_pass1 (j_decompress_ptr cinfo)
  175178. {
  175179. my_cquantize_ptr2 cquantize = (my_cquantize_ptr2) cinfo->cquantize;
  175180. /* Select the representative colors and fill in cinfo->colormap */
  175181. cinfo->colormap = cquantize->sv_colormap;
  175182. select_colors(cinfo, cquantize->desired);
  175183. /* Force next pass to zero the color index table */
  175184. cquantize->needs_zeroed = TRUE;
  175185. }
  175186. METHODDEF(void)
  175187. finish_pass2 (j_decompress_ptr cinfo)
  175188. {
  175189. /* no work */
  175190. }
  175191. /*
  175192. * Initialize for each processing pass.
  175193. */
  175194. METHODDEF(void)
  175195. start_pass_2_quant (j_decompress_ptr cinfo, boolean is_pre_scan)
  175196. {
  175197. my_cquantize_ptr2 cquantize = (my_cquantize_ptr2) cinfo->cquantize;
  175198. hist3d histogram = cquantize->histogram;
  175199. int i;
  175200. /* Only F-S dithering or no dithering is supported. */
  175201. /* If user asks for ordered dither, give him F-S. */
  175202. if (cinfo->dither_mode != JDITHER_NONE)
  175203. cinfo->dither_mode = JDITHER_FS;
  175204. if (is_pre_scan) {
  175205. /* Set up method pointers */
  175206. cquantize->pub.color_quantize = prescan_quantize;
  175207. cquantize->pub.finish_pass = finish_pass1;
  175208. cquantize->needs_zeroed = TRUE; /* Always zero histogram */
  175209. } else {
  175210. /* Set up method pointers */
  175211. if (cinfo->dither_mode == JDITHER_FS)
  175212. cquantize->pub.color_quantize = pass2_fs_dither;
  175213. else
  175214. cquantize->pub.color_quantize = pass2_no_dither;
  175215. cquantize->pub.finish_pass = finish_pass2;
  175216. /* Make sure color count is acceptable */
  175217. i = cinfo->actual_number_of_colors;
  175218. if (i < 1)
  175219. ERREXIT1(cinfo, JERR_QUANT_FEW_COLORS, 1);
  175220. if (i > MAXNUMCOLORS)
  175221. ERREXIT1(cinfo, JERR_QUANT_MANY_COLORS, MAXNUMCOLORS);
  175222. if (cinfo->dither_mode == JDITHER_FS) {
  175223. size_t arraysize = (size_t) ((cinfo->output_width + 2) *
  175224. (3 * SIZEOF(FSERROR)));
  175225. /* Allocate Floyd-Steinberg workspace if we didn't already. */
  175226. if (cquantize->fserrors == NULL)
  175227. cquantize->fserrors = (FSERRPTR) (*cinfo->mem->alloc_large)
  175228. ((j_common_ptr) cinfo, JPOOL_IMAGE, arraysize);
  175229. /* Initialize the propagated errors to zero. */
  175230. jzero_far((void FAR *) cquantize->fserrors, arraysize);
  175231. /* Make the error-limit table if we didn't already. */
  175232. if (cquantize->error_limiter == NULL)
  175233. init_error_limit(cinfo);
  175234. cquantize->on_odd_row = FALSE;
  175235. }
  175236. }
  175237. /* Zero the histogram or inverse color map, if necessary */
  175238. if (cquantize->needs_zeroed) {
  175239. for (i = 0; i < HIST_C0_ELEMS; i++) {
  175240. jzero_far((void FAR *) histogram[i],
  175241. HIST_C1_ELEMS*HIST_C2_ELEMS * SIZEOF(histcell));
  175242. }
  175243. cquantize->needs_zeroed = FALSE;
  175244. }
  175245. }
  175246. /*
  175247. * Switch to a new external colormap between output passes.
  175248. */
  175249. METHODDEF(void)
  175250. new_color_map_2_quant (j_decompress_ptr cinfo)
  175251. {
  175252. my_cquantize_ptr2 cquantize = (my_cquantize_ptr2) cinfo->cquantize;
  175253. /* Reset the inverse color map */
  175254. cquantize->needs_zeroed = TRUE;
  175255. }
  175256. /*
  175257. * Module initialization routine for 2-pass color quantization.
  175258. */
  175259. GLOBAL(void)
  175260. jinit_2pass_quantizer (j_decompress_ptr cinfo)
  175261. {
  175262. my_cquantize_ptr2 cquantize;
  175263. int i;
  175264. cquantize = (my_cquantize_ptr2)
  175265. (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_IMAGE,
  175266. SIZEOF(my_cquantizer2));
  175267. cinfo->cquantize = (struct jpeg_color_quantizer *) cquantize;
  175268. cquantize->pub.start_pass = start_pass_2_quant;
  175269. cquantize->pub.new_color_map = new_color_map_2_quant;
  175270. cquantize->fserrors = NULL; /* flag optional arrays not allocated */
  175271. cquantize->error_limiter = NULL;
  175272. /* Make sure jdmaster didn't give me a case I can't handle */
  175273. if (cinfo->out_color_components != 3)
  175274. ERREXIT(cinfo, JERR_NOTIMPL);
  175275. /* Allocate the histogram/inverse colormap storage */
  175276. cquantize->histogram = (hist3d) (*cinfo->mem->alloc_small)
  175277. ((j_common_ptr) cinfo, JPOOL_IMAGE, HIST_C0_ELEMS * SIZEOF(hist2d));
  175278. for (i = 0; i < HIST_C0_ELEMS; i++) {
  175279. cquantize->histogram[i] = (hist2d) (*cinfo->mem->alloc_large)
  175280. ((j_common_ptr) cinfo, JPOOL_IMAGE,
  175281. HIST_C1_ELEMS*HIST_C2_ELEMS * SIZEOF(histcell));
  175282. }
  175283. cquantize->needs_zeroed = TRUE; /* histogram is garbage now */
  175284. /* Allocate storage for the completed colormap, if required.
  175285. * We do this now since it is FAR storage and may affect
  175286. * the memory manager's space calculations.
  175287. */
  175288. if (cinfo->enable_2pass_quant) {
  175289. /* Make sure color count is acceptable */
  175290. int desired = cinfo->desired_number_of_colors;
  175291. /* Lower bound on # of colors ... somewhat arbitrary as long as > 0 */
  175292. if (desired < 8)
  175293. ERREXIT1(cinfo, JERR_QUANT_FEW_COLORS, 8);
  175294. /* Make sure colormap indexes can be represented by JSAMPLEs */
  175295. if (desired > MAXNUMCOLORS)
  175296. ERREXIT1(cinfo, JERR_QUANT_MANY_COLORS, MAXNUMCOLORS);
  175297. cquantize->sv_colormap = (*cinfo->mem->alloc_sarray)
  175298. ((j_common_ptr) cinfo,JPOOL_IMAGE, (JDIMENSION) desired, (JDIMENSION) 3);
  175299. cquantize->desired = desired;
  175300. } else
  175301. cquantize->sv_colormap = NULL;
  175302. /* Only F-S dithering or no dithering is supported. */
  175303. /* If user asks for ordered dither, give him F-S. */
  175304. if (cinfo->dither_mode != JDITHER_NONE)
  175305. cinfo->dither_mode = JDITHER_FS;
  175306. /* Allocate Floyd-Steinberg workspace if necessary.
  175307. * This isn't really needed until pass 2, but again it is FAR storage.
  175308. * Although we will cope with a later change in dither_mode,
  175309. * we do not promise to honor max_memory_to_use if dither_mode changes.
  175310. */
  175311. if (cinfo->dither_mode == JDITHER_FS) {
  175312. cquantize->fserrors = (FSERRPTR) (*cinfo->mem->alloc_large)
  175313. ((j_common_ptr) cinfo, JPOOL_IMAGE,
  175314. (size_t) ((cinfo->output_width + 2) * (3 * SIZEOF(FSERROR))));
  175315. /* Might as well create the error-limiting table too. */
  175316. init_error_limit(cinfo);
  175317. }
  175318. }
  175319. #endif /* QUANT_2PASS_SUPPORTED */
  175320. /*** End of inlined file: jquant2.c ***/
  175321. /*** Start of inlined file: jutils.c ***/
  175322. #define JPEG_INTERNALS
  175323. /*
  175324. * jpeg_zigzag_order[i] is the zigzag-order position of the i'th element
  175325. * of a DCT block read in natural order (left to right, top to bottom).
  175326. */
  175327. #if 0 /* This table is not actually needed in v6a */
  175328. const int jpeg_zigzag_order[DCTSIZE2] = {
  175329. 0, 1, 5, 6, 14, 15, 27, 28,
  175330. 2, 4, 7, 13, 16, 26, 29, 42,
  175331. 3, 8, 12, 17, 25, 30, 41, 43,
  175332. 9, 11, 18, 24, 31, 40, 44, 53,
  175333. 10, 19, 23, 32, 39, 45, 52, 54,
  175334. 20, 22, 33, 38, 46, 51, 55, 60,
  175335. 21, 34, 37, 47, 50, 56, 59, 61,
  175336. 35, 36, 48, 49, 57, 58, 62, 63
  175337. };
  175338. #endif
  175339. /*
  175340. * jpeg_natural_order[i] is the natural-order position of the i'th element
  175341. * of zigzag order.
  175342. *
  175343. * When reading corrupted data, the Huffman decoders could attempt
  175344. * to reference an entry beyond the end of this array (if the decoded
  175345. * zero run length reaches past the end of the block). To prevent
  175346. * wild stores without adding an inner-loop test, we put some extra
  175347. * "63"s after the real entries. This will cause the extra coefficient
  175348. * to be stored in location 63 of the block, not somewhere random.
  175349. * The worst case would be a run-length of 15, which means we need 16
  175350. * fake entries.
  175351. */
  175352. const int jpeg_natural_order[DCTSIZE2+16] = {
  175353. 0, 1, 8, 16, 9, 2, 3, 10,
  175354. 17, 24, 32, 25, 18, 11, 4, 5,
  175355. 12, 19, 26, 33, 40, 48, 41, 34,
  175356. 27, 20, 13, 6, 7, 14, 21, 28,
  175357. 35, 42, 49, 56, 57, 50, 43, 36,
  175358. 29, 22, 15, 23, 30, 37, 44, 51,
  175359. 58, 59, 52, 45, 38, 31, 39, 46,
  175360. 53, 60, 61, 54, 47, 55, 62, 63,
  175361. 63, 63, 63, 63, 63, 63, 63, 63, /* extra entries for safety in decoder */
  175362. 63, 63, 63, 63, 63, 63, 63, 63
  175363. };
  175364. /*
  175365. * Arithmetic utilities
  175366. */
  175367. GLOBAL(long)
  175368. jdiv_round_up (long a, long b)
  175369. /* Compute a/b rounded up to next integer, ie, ceil(a/b) */
  175370. /* Assumes a >= 0, b > 0 */
  175371. {
  175372. return (a + b - 1L) / b;
  175373. }
  175374. GLOBAL(long)
  175375. jround_up (long a, long b)
  175376. /* Compute a rounded up to next multiple of b, ie, ceil(a/b)*b */
  175377. /* Assumes a >= 0, b > 0 */
  175378. {
  175379. a += b - 1L;
  175380. return a - (a % b);
  175381. }
  175382. /* On normal machines we can apply MEMCOPY() and MEMZERO() to sample arrays
  175383. * and coefficient-block arrays. This won't work on 80x86 because the arrays
  175384. * are FAR and we're assuming a small-pointer memory model. However, some
  175385. * DOS compilers provide far-pointer versions of memcpy() and memset() even
  175386. * in the small-model libraries. These will be used if USE_FMEM is defined.
  175387. * Otherwise, the routines below do it the hard way. (The performance cost
  175388. * is not all that great, because these routines aren't very heavily used.)
  175389. */
  175390. #ifndef NEED_FAR_POINTERS /* normal case, same as regular macros */
  175391. #define FMEMCOPY(dest,src,size) MEMCOPY(dest,src,size)
  175392. #define FMEMZERO(target,size) MEMZERO(target,size)
  175393. #else /* 80x86 case, define if we can */
  175394. #ifdef USE_FMEM
  175395. #define FMEMCOPY(dest,src,size) _fmemcpy((void FAR *)(dest), (const void FAR *)(src), (size_t)(size))
  175396. #define FMEMZERO(target,size) _fmemset((void FAR *)(target), 0, (size_t)(size))
  175397. #endif
  175398. #endif
  175399. GLOBAL(void)
  175400. jcopy_sample_rows (JSAMPARRAY input_array, int source_row,
  175401. JSAMPARRAY output_array, int dest_row,
  175402. int num_rows, JDIMENSION num_cols)
  175403. /* Copy some rows of samples from one place to another.
  175404. * num_rows rows are copied from input_array[source_row++]
  175405. * to output_array[dest_row++]; these areas may overlap for duplication.
  175406. * The source and destination arrays must be at least as wide as num_cols.
  175407. */
  175408. {
  175409. register JSAMPROW inptr, outptr;
  175410. #ifdef FMEMCOPY
  175411. register size_t count = (size_t) (num_cols * SIZEOF(JSAMPLE));
  175412. #else
  175413. register JDIMENSION count;
  175414. #endif
  175415. register int row;
  175416. input_array += source_row;
  175417. output_array += dest_row;
  175418. for (row = num_rows; row > 0; row--) {
  175419. inptr = *input_array++;
  175420. outptr = *output_array++;
  175421. #ifdef FMEMCOPY
  175422. FMEMCOPY(outptr, inptr, count);
  175423. #else
  175424. for (count = num_cols; count > 0; count--)
  175425. *outptr++ = *inptr++; /* needn't bother with GETJSAMPLE() here */
  175426. #endif
  175427. }
  175428. }
  175429. GLOBAL(void)
  175430. jcopy_block_row (JBLOCKROW input_row, JBLOCKROW output_row,
  175431. JDIMENSION num_blocks)
  175432. /* Copy a row of coefficient blocks from one place to another. */
  175433. {
  175434. #ifdef FMEMCOPY
  175435. FMEMCOPY(output_row, input_row, num_blocks * (DCTSIZE2 * SIZEOF(JCOEF)));
  175436. #else
  175437. register JCOEFPTR inptr, outptr;
  175438. register long count;
  175439. inptr = (JCOEFPTR) input_row;
  175440. outptr = (JCOEFPTR) output_row;
  175441. for (count = (long) num_blocks * DCTSIZE2; count > 0; count--) {
  175442. *outptr++ = *inptr++;
  175443. }
  175444. #endif
  175445. }
  175446. GLOBAL(void)
  175447. jzero_far (void FAR * target, size_t bytestozero)
  175448. /* Zero out a chunk of FAR memory. */
  175449. /* This might be sample-array data, block-array data, or alloc_large data. */
  175450. {
  175451. #ifdef FMEMZERO
  175452. FMEMZERO(target, bytestozero);
  175453. #else
  175454. register char FAR * ptr = (char FAR *) target;
  175455. register size_t count;
  175456. for (count = bytestozero; count > 0; count--) {
  175457. *ptr++ = 0;
  175458. }
  175459. #endif
  175460. }
  175461. /*** End of inlined file: jutils.c ***/
  175462. /*** Start of inlined file: transupp.c ***/
  175463. /* Although this file really shouldn't have access to the library internals,
  175464. * it's helpful to let it call jround_up() and jcopy_block_row().
  175465. */
  175466. #define JPEG_INTERNALS
  175467. /*** Start of inlined file: transupp.h ***/
  175468. /* If you happen not to want the image transform support, disable it here */
  175469. #ifndef TRANSFORMS_SUPPORTED
  175470. #define TRANSFORMS_SUPPORTED 1 /* 0 disables transform code */
  175471. #endif
  175472. /* Short forms of external names for systems with brain-damaged linkers. */
  175473. #ifdef NEED_SHORT_EXTERNAL_NAMES
  175474. #define jtransform_request_workspace jTrRequest
  175475. #define jtransform_adjust_parameters jTrAdjust
  175476. #define jtransform_execute_transformation jTrExec
  175477. #define jcopy_markers_setup jCMrkSetup
  175478. #define jcopy_markers_execute jCMrkExec
  175479. #endif /* NEED_SHORT_EXTERNAL_NAMES */
  175480. /*
  175481. * Codes for supported types of image transformations.
  175482. */
  175483. typedef enum {
  175484. JXFORM_NONE, /* no transformation */
  175485. JXFORM_FLIP_H, /* horizontal flip */
  175486. JXFORM_FLIP_V, /* vertical flip */
  175487. JXFORM_TRANSPOSE, /* transpose across UL-to-LR axis */
  175488. JXFORM_TRANSVERSE, /* transpose across UR-to-LL axis */
  175489. JXFORM_ROT_90, /* 90-degree clockwise rotation */
  175490. JXFORM_ROT_180, /* 180-degree rotation */
  175491. JXFORM_ROT_270 /* 270-degree clockwise (or 90 ccw) */
  175492. } JXFORM_CODE;
  175493. /*
  175494. * Although rotating and flipping data expressed as DCT coefficients is not
  175495. * hard, there is an asymmetry in the JPEG format specification for images
  175496. * whose dimensions aren't multiples of the iMCU size. The right and bottom
  175497. * image edges are padded out to the next iMCU boundary with junk data; but
  175498. * no padding is possible at the top and left edges. If we were to flip
  175499. * the whole image including the pad data, then pad garbage would become
  175500. * visible at the top and/or left, and real pixels would disappear into the
  175501. * pad margins --- perhaps permanently, since encoders & decoders may not
  175502. * bother to preserve DCT blocks that appear to be completely outside the
  175503. * nominal image area. So, we have to exclude any partial iMCUs from the
  175504. * basic transformation.
  175505. *
  175506. * Transpose is the only transformation that can handle partial iMCUs at the
  175507. * right and bottom edges completely cleanly. flip_h can flip partial iMCUs
  175508. * at the bottom, but leaves any partial iMCUs at the right edge untouched.
  175509. * Similarly flip_v leaves any partial iMCUs at the bottom edge untouched.
  175510. * The other transforms are defined as combinations of these basic transforms
  175511. * and process edge blocks in a way that preserves the equivalence.
  175512. *
  175513. * The "trim" option causes untransformable partial iMCUs to be dropped;
  175514. * this is not strictly lossless, but it usually gives the best-looking
  175515. * result for odd-size images. Note that when this option is active,
  175516. * the expected mathematical equivalences between the transforms may not hold.
  175517. * (For example, -rot 270 -trim trims only the bottom edge, but -rot 90 -trim
  175518. * followed by -rot 180 -trim trims both edges.)
  175519. *
  175520. * We also offer a "force to grayscale" option, which simply discards the
  175521. * chrominance channels of a YCbCr image. This is lossless in the sense that
  175522. * the luminance channel is preserved exactly. It's not the same kind of
  175523. * thing as the rotate/flip transformations, but it's convenient to handle it
  175524. * as part of this package, mainly because the transformation routines have to
  175525. * be aware of the option to know how many components to work on.
  175526. */
  175527. typedef struct {
  175528. /* Options: set by caller */
  175529. JXFORM_CODE transform; /* image transform operator */
  175530. boolean trim; /* if TRUE, trim partial MCUs as needed */
  175531. boolean force_grayscale; /* if TRUE, convert color image to grayscale */
  175532. /* Internal workspace: caller should not touch these */
  175533. int num_components; /* # of components in workspace */
  175534. jvirt_barray_ptr * workspace_coef_arrays; /* workspace for transformations */
  175535. } jpeg_transform_info;
  175536. #if TRANSFORMS_SUPPORTED
  175537. /* Request any required workspace */
  175538. EXTERN(void) jtransform_request_workspace
  175539. JPP((j_decompress_ptr srcinfo, jpeg_transform_info *info));
  175540. /* Adjust output image parameters */
  175541. EXTERN(jvirt_barray_ptr *) jtransform_adjust_parameters
  175542. JPP((j_decompress_ptr srcinfo, j_compress_ptr dstinfo,
  175543. jvirt_barray_ptr *src_coef_arrays,
  175544. jpeg_transform_info *info));
  175545. /* Execute the actual transformation, if any */
  175546. EXTERN(void) jtransform_execute_transformation
  175547. JPP((j_decompress_ptr srcinfo, j_compress_ptr dstinfo,
  175548. jvirt_barray_ptr *src_coef_arrays,
  175549. jpeg_transform_info *info));
  175550. #endif /* TRANSFORMS_SUPPORTED */
  175551. /*
  175552. * Support for copying optional markers from source to destination file.
  175553. */
  175554. typedef enum {
  175555. JCOPYOPT_NONE, /* copy no optional markers */
  175556. JCOPYOPT_COMMENTS, /* copy only comment (COM) markers */
  175557. JCOPYOPT_ALL /* copy all optional markers */
  175558. } JCOPY_OPTION;
  175559. #define JCOPYOPT_DEFAULT JCOPYOPT_COMMENTS /* recommended default */
  175560. /* Setup decompression object to save desired markers in memory */
  175561. EXTERN(void) jcopy_markers_setup
  175562. JPP((j_decompress_ptr srcinfo, JCOPY_OPTION option));
  175563. /* Copy markers saved in the given source object to the destination object */
  175564. EXTERN(void) jcopy_markers_execute
  175565. JPP((j_decompress_ptr srcinfo, j_compress_ptr dstinfo,
  175566. JCOPY_OPTION option));
  175567. /*** End of inlined file: transupp.h ***/
  175568. /* My own external interface */
  175569. #if TRANSFORMS_SUPPORTED
  175570. /*
  175571. * Lossless image transformation routines. These routines work on DCT
  175572. * coefficient arrays and thus do not require any lossy decompression
  175573. * or recompression of the image.
  175574. * Thanks to Guido Vollbeding for the initial design and code of this feature.
  175575. *
  175576. * Horizontal flipping is done in-place, using a single top-to-bottom
  175577. * pass through the virtual source array. It will thus be much the
  175578. * fastest option for images larger than main memory.
  175579. *
  175580. * The other routines require a set of destination virtual arrays, so they
  175581. * need twice as much memory as jpegtran normally does. The destination
  175582. * arrays are always written in normal scan order (top to bottom) because
  175583. * the virtual array manager expects this. The source arrays will be scanned
  175584. * in the corresponding order, which means multiple passes through the source
  175585. * arrays for most of the transforms. That could result in much thrashing
  175586. * if the image is larger than main memory.
  175587. *
  175588. * Some notes about the operating environment of the individual transform
  175589. * routines:
  175590. * 1. Both the source and destination virtual arrays are allocated from the
  175591. * source JPEG object, and therefore should be manipulated by calling the
  175592. * source's memory manager.
  175593. * 2. The destination's component count should be used. It may be smaller
  175594. * than the source's when forcing to grayscale.
  175595. * 3. Likewise the destination's sampling factors should be used. When
  175596. * forcing to grayscale the destination's sampling factors will be all 1,
  175597. * and we may as well take that as the effective iMCU size.
  175598. * 4. When "trim" is in effect, the destination's dimensions will be the
  175599. * trimmed values but the source's will be untrimmed.
  175600. * 5. All the routines assume that the source and destination buffers are
  175601. * padded out to a full iMCU boundary. This is true, although for the
  175602. * source buffer it is an undocumented property of jdcoefct.c.
  175603. * Notes 2,3,4 boil down to this: generally we should use the destination's
  175604. * dimensions and ignore the source's.
  175605. */
  175606. LOCAL(void)
  175607. do_flip_h (j_decompress_ptr srcinfo, j_compress_ptr dstinfo,
  175608. jvirt_barray_ptr *src_coef_arrays)
  175609. /* Horizontal flip; done in-place, so no separate dest array is required */
  175610. {
  175611. JDIMENSION MCU_cols, comp_width, blk_x, blk_y;
  175612. int ci, k, offset_y;
  175613. JBLOCKARRAY buffer;
  175614. JCOEFPTR ptr1, ptr2;
  175615. JCOEF temp1, temp2;
  175616. jpeg_component_info *compptr;
  175617. /* Horizontal mirroring of DCT blocks is accomplished by swapping
  175618. * pairs of blocks in-place. Within a DCT block, we perform horizontal
  175619. * mirroring by changing the signs of odd-numbered columns.
  175620. * Partial iMCUs at the right edge are left untouched.
  175621. */
  175622. MCU_cols = dstinfo->image_width / (dstinfo->max_h_samp_factor * DCTSIZE);
  175623. for (ci = 0; ci < dstinfo->num_components; ci++) {
  175624. compptr = dstinfo->comp_info + ci;
  175625. comp_width = MCU_cols * compptr->h_samp_factor;
  175626. for (blk_y = 0; blk_y < compptr->height_in_blocks;
  175627. blk_y += compptr->v_samp_factor) {
  175628. buffer = (*srcinfo->mem->access_virt_barray)
  175629. ((j_common_ptr) srcinfo, src_coef_arrays[ci], blk_y,
  175630. (JDIMENSION) compptr->v_samp_factor, TRUE);
  175631. for (offset_y = 0; offset_y < compptr->v_samp_factor; offset_y++) {
  175632. for (blk_x = 0; blk_x * 2 < comp_width; blk_x++) {
  175633. ptr1 = buffer[offset_y][blk_x];
  175634. ptr2 = buffer[offset_y][comp_width - blk_x - 1];
  175635. /* this unrolled loop doesn't need to know which row it's on... */
  175636. for (k = 0; k < DCTSIZE2; k += 2) {
  175637. temp1 = *ptr1; /* swap even column */
  175638. temp2 = *ptr2;
  175639. *ptr1++ = temp2;
  175640. *ptr2++ = temp1;
  175641. temp1 = *ptr1; /* swap odd column with sign change */
  175642. temp2 = *ptr2;
  175643. *ptr1++ = -temp2;
  175644. *ptr2++ = -temp1;
  175645. }
  175646. }
  175647. }
  175648. }
  175649. }
  175650. }
  175651. LOCAL(void)
  175652. do_flip_v (j_decompress_ptr srcinfo, j_compress_ptr dstinfo,
  175653. jvirt_barray_ptr *src_coef_arrays,
  175654. jvirt_barray_ptr *dst_coef_arrays)
  175655. /* Vertical flip */
  175656. {
  175657. JDIMENSION MCU_rows, comp_height, dst_blk_x, dst_blk_y;
  175658. int ci, i, j, offset_y;
  175659. JBLOCKARRAY src_buffer, dst_buffer;
  175660. JBLOCKROW src_row_ptr, dst_row_ptr;
  175661. JCOEFPTR src_ptr, dst_ptr;
  175662. jpeg_component_info *compptr;
  175663. /* We output into a separate array because we can't touch different
  175664. * rows of the source virtual array simultaneously. Otherwise, this
  175665. * is a pretty straightforward analog of horizontal flip.
  175666. * Within a DCT block, vertical mirroring is done by changing the signs
  175667. * of odd-numbered rows.
  175668. * Partial iMCUs at the bottom edge are copied verbatim.
  175669. */
  175670. MCU_rows = dstinfo->image_height / (dstinfo->max_v_samp_factor * DCTSIZE);
  175671. for (ci = 0; ci < dstinfo->num_components; ci++) {
  175672. compptr = dstinfo->comp_info + ci;
  175673. comp_height = MCU_rows * compptr->v_samp_factor;
  175674. for (dst_blk_y = 0; dst_blk_y < compptr->height_in_blocks;
  175675. dst_blk_y += compptr->v_samp_factor) {
  175676. dst_buffer = (*srcinfo->mem->access_virt_barray)
  175677. ((j_common_ptr) srcinfo, dst_coef_arrays[ci], dst_blk_y,
  175678. (JDIMENSION) compptr->v_samp_factor, TRUE);
  175679. if (dst_blk_y < comp_height) {
  175680. /* Row is within the mirrorable area. */
  175681. src_buffer = (*srcinfo->mem->access_virt_barray)
  175682. ((j_common_ptr) srcinfo, src_coef_arrays[ci],
  175683. comp_height - dst_blk_y - (JDIMENSION) compptr->v_samp_factor,
  175684. (JDIMENSION) compptr->v_samp_factor, FALSE);
  175685. } else {
  175686. /* Bottom-edge blocks will be copied verbatim. */
  175687. src_buffer = (*srcinfo->mem->access_virt_barray)
  175688. ((j_common_ptr) srcinfo, src_coef_arrays[ci], dst_blk_y,
  175689. (JDIMENSION) compptr->v_samp_factor, FALSE);
  175690. }
  175691. for (offset_y = 0; offset_y < compptr->v_samp_factor; offset_y++) {
  175692. if (dst_blk_y < comp_height) {
  175693. /* Row is within the mirrorable area. */
  175694. dst_row_ptr = dst_buffer[offset_y];
  175695. src_row_ptr = src_buffer[compptr->v_samp_factor - offset_y - 1];
  175696. for (dst_blk_x = 0; dst_blk_x < compptr->width_in_blocks;
  175697. dst_blk_x++) {
  175698. dst_ptr = dst_row_ptr[dst_blk_x];
  175699. src_ptr = src_row_ptr[dst_blk_x];
  175700. for (i = 0; i < DCTSIZE; i += 2) {
  175701. /* copy even row */
  175702. for (j = 0; j < DCTSIZE; j++)
  175703. *dst_ptr++ = *src_ptr++;
  175704. /* copy odd row with sign change */
  175705. for (j = 0; j < DCTSIZE; j++)
  175706. *dst_ptr++ = - *src_ptr++;
  175707. }
  175708. }
  175709. } else {
  175710. /* Just copy row verbatim. */
  175711. jcopy_block_row(src_buffer[offset_y], dst_buffer[offset_y],
  175712. compptr->width_in_blocks);
  175713. }
  175714. }
  175715. }
  175716. }
  175717. }
  175718. LOCAL(void)
  175719. do_transpose (j_decompress_ptr srcinfo, j_compress_ptr dstinfo,
  175720. jvirt_barray_ptr *src_coef_arrays,
  175721. jvirt_barray_ptr *dst_coef_arrays)
  175722. /* Transpose source into destination */
  175723. {
  175724. JDIMENSION dst_blk_x, dst_blk_y;
  175725. int ci, i, j, offset_x, offset_y;
  175726. JBLOCKARRAY src_buffer, dst_buffer;
  175727. JCOEFPTR src_ptr, dst_ptr;
  175728. jpeg_component_info *compptr;
  175729. /* Transposing pixels within a block just requires transposing the
  175730. * DCT coefficients.
  175731. * Partial iMCUs at the edges require no special treatment; we simply
  175732. * process all the available DCT blocks for every component.
  175733. */
  175734. for (ci = 0; ci < dstinfo->num_components; ci++) {
  175735. compptr = dstinfo->comp_info + ci;
  175736. for (dst_blk_y = 0; dst_blk_y < compptr->height_in_blocks;
  175737. dst_blk_y += compptr->v_samp_factor) {
  175738. dst_buffer = (*srcinfo->mem->access_virt_barray)
  175739. ((j_common_ptr) srcinfo, dst_coef_arrays[ci], dst_blk_y,
  175740. (JDIMENSION) compptr->v_samp_factor, TRUE);
  175741. for (offset_y = 0; offset_y < compptr->v_samp_factor; offset_y++) {
  175742. for (dst_blk_x = 0; dst_blk_x < compptr->width_in_blocks;
  175743. dst_blk_x += compptr->h_samp_factor) {
  175744. src_buffer = (*srcinfo->mem->access_virt_barray)
  175745. ((j_common_ptr) srcinfo, src_coef_arrays[ci], dst_blk_x,
  175746. (JDIMENSION) compptr->h_samp_factor, FALSE);
  175747. for (offset_x = 0; offset_x < compptr->h_samp_factor; offset_x++) {
  175748. src_ptr = src_buffer[offset_x][dst_blk_y + offset_y];
  175749. dst_ptr = dst_buffer[offset_y][dst_blk_x + offset_x];
  175750. for (i = 0; i < DCTSIZE; i++)
  175751. for (j = 0; j < DCTSIZE; j++)
  175752. dst_ptr[j*DCTSIZE+i] = src_ptr[i*DCTSIZE+j];
  175753. }
  175754. }
  175755. }
  175756. }
  175757. }
  175758. }
  175759. LOCAL(void)
  175760. do_rot_90 (j_decompress_ptr srcinfo, j_compress_ptr dstinfo,
  175761. jvirt_barray_ptr *src_coef_arrays,
  175762. jvirt_barray_ptr *dst_coef_arrays)
  175763. /* 90 degree rotation is equivalent to
  175764. * 1. Transposing the image;
  175765. * 2. Horizontal mirroring.
  175766. * These two steps are merged into a single processing routine.
  175767. */
  175768. {
  175769. JDIMENSION MCU_cols, comp_width, dst_blk_x, dst_blk_y;
  175770. int ci, i, j, offset_x, offset_y;
  175771. JBLOCKARRAY src_buffer, dst_buffer;
  175772. JCOEFPTR src_ptr, dst_ptr;
  175773. jpeg_component_info *compptr;
  175774. /* Because of the horizontal mirror step, we can't process partial iMCUs
  175775. * at the (output) right edge properly. They just get transposed and
  175776. * not mirrored.
  175777. */
  175778. MCU_cols = dstinfo->image_width / (dstinfo->max_h_samp_factor * DCTSIZE);
  175779. for (ci = 0; ci < dstinfo->num_components; ci++) {
  175780. compptr = dstinfo->comp_info + ci;
  175781. comp_width = MCU_cols * compptr->h_samp_factor;
  175782. for (dst_blk_y = 0; dst_blk_y < compptr->height_in_blocks;
  175783. dst_blk_y += compptr->v_samp_factor) {
  175784. dst_buffer = (*srcinfo->mem->access_virt_barray)
  175785. ((j_common_ptr) srcinfo, dst_coef_arrays[ci], dst_blk_y,
  175786. (JDIMENSION) compptr->v_samp_factor, TRUE);
  175787. for (offset_y = 0; offset_y < compptr->v_samp_factor; offset_y++) {
  175788. for (dst_blk_x = 0; dst_blk_x < compptr->width_in_blocks;
  175789. dst_blk_x += compptr->h_samp_factor) {
  175790. src_buffer = (*srcinfo->mem->access_virt_barray)
  175791. ((j_common_ptr) srcinfo, src_coef_arrays[ci], dst_blk_x,
  175792. (JDIMENSION) compptr->h_samp_factor, FALSE);
  175793. for (offset_x = 0; offset_x < compptr->h_samp_factor; offset_x++) {
  175794. src_ptr = src_buffer[offset_x][dst_blk_y + offset_y];
  175795. if (dst_blk_x < comp_width) {
  175796. /* Block is within the mirrorable area. */
  175797. dst_ptr = dst_buffer[offset_y]
  175798. [comp_width - dst_blk_x - offset_x - 1];
  175799. for (i = 0; i < DCTSIZE; i++) {
  175800. for (j = 0; j < DCTSIZE; j++)
  175801. dst_ptr[j*DCTSIZE+i] = src_ptr[i*DCTSIZE+j];
  175802. i++;
  175803. for (j = 0; j < DCTSIZE; j++)
  175804. dst_ptr[j*DCTSIZE+i] = -src_ptr[i*DCTSIZE+j];
  175805. }
  175806. } else {
  175807. /* Edge blocks are transposed but not mirrored. */
  175808. dst_ptr = dst_buffer[offset_y][dst_blk_x + offset_x];
  175809. for (i = 0; i < DCTSIZE; i++)
  175810. for (j = 0; j < DCTSIZE; j++)
  175811. dst_ptr[j*DCTSIZE+i] = src_ptr[i*DCTSIZE+j];
  175812. }
  175813. }
  175814. }
  175815. }
  175816. }
  175817. }
  175818. }
  175819. LOCAL(void)
  175820. do_rot_270 (j_decompress_ptr srcinfo, j_compress_ptr dstinfo,
  175821. jvirt_barray_ptr *src_coef_arrays,
  175822. jvirt_barray_ptr *dst_coef_arrays)
  175823. /* 270 degree rotation is equivalent to
  175824. * 1. Horizontal mirroring;
  175825. * 2. Transposing the image.
  175826. * These two steps are merged into a single processing routine.
  175827. */
  175828. {
  175829. JDIMENSION MCU_rows, comp_height, dst_blk_x, dst_blk_y;
  175830. int ci, i, j, offset_x, offset_y;
  175831. JBLOCKARRAY src_buffer, dst_buffer;
  175832. JCOEFPTR src_ptr, dst_ptr;
  175833. jpeg_component_info *compptr;
  175834. /* Because of the horizontal mirror step, we can't process partial iMCUs
  175835. * at the (output) bottom edge properly. They just get transposed and
  175836. * not mirrored.
  175837. */
  175838. MCU_rows = dstinfo->image_height / (dstinfo->max_v_samp_factor * DCTSIZE);
  175839. for (ci = 0; ci < dstinfo->num_components; ci++) {
  175840. compptr = dstinfo->comp_info + ci;
  175841. comp_height = MCU_rows * compptr->v_samp_factor;
  175842. for (dst_blk_y = 0; dst_blk_y < compptr->height_in_blocks;
  175843. dst_blk_y += compptr->v_samp_factor) {
  175844. dst_buffer = (*srcinfo->mem->access_virt_barray)
  175845. ((j_common_ptr) srcinfo, dst_coef_arrays[ci], dst_blk_y,
  175846. (JDIMENSION) compptr->v_samp_factor, TRUE);
  175847. for (offset_y = 0; offset_y < compptr->v_samp_factor; offset_y++) {
  175848. for (dst_blk_x = 0; dst_blk_x < compptr->width_in_blocks;
  175849. dst_blk_x += compptr->h_samp_factor) {
  175850. src_buffer = (*srcinfo->mem->access_virt_barray)
  175851. ((j_common_ptr) srcinfo, src_coef_arrays[ci], dst_blk_x,
  175852. (JDIMENSION) compptr->h_samp_factor, FALSE);
  175853. for (offset_x = 0; offset_x < compptr->h_samp_factor; offset_x++) {
  175854. dst_ptr = dst_buffer[offset_y][dst_blk_x + offset_x];
  175855. if (dst_blk_y < comp_height) {
  175856. /* Block is within the mirrorable area. */
  175857. src_ptr = src_buffer[offset_x]
  175858. [comp_height - dst_blk_y - offset_y - 1];
  175859. for (i = 0; i < DCTSIZE; i++) {
  175860. for (j = 0; j < DCTSIZE; j++) {
  175861. dst_ptr[j*DCTSIZE+i] = src_ptr[i*DCTSIZE+j];
  175862. j++;
  175863. dst_ptr[j*DCTSIZE+i] = -src_ptr[i*DCTSIZE+j];
  175864. }
  175865. }
  175866. } else {
  175867. /* Edge blocks are transposed but not mirrored. */
  175868. src_ptr = src_buffer[offset_x][dst_blk_y + offset_y];
  175869. for (i = 0; i < DCTSIZE; i++)
  175870. for (j = 0; j < DCTSIZE; j++)
  175871. dst_ptr[j*DCTSIZE+i] = src_ptr[i*DCTSIZE+j];
  175872. }
  175873. }
  175874. }
  175875. }
  175876. }
  175877. }
  175878. }
  175879. LOCAL(void)
  175880. do_rot_180 (j_decompress_ptr srcinfo, j_compress_ptr dstinfo,
  175881. jvirt_barray_ptr *src_coef_arrays,
  175882. jvirt_barray_ptr *dst_coef_arrays)
  175883. /* 180 degree rotation is equivalent to
  175884. * 1. Vertical mirroring;
  175885. * 2. Horizontal mirroring.
  175886. * These two steps are merged into a single processing routine.
  175887. */
  175888. {
  175889. JDIMENSION MCU_cols, MCU_rows, comp_width, comp_height, dst_blk_x, dst_blk_y;
  175890. int ci, i, j, offset_y;
  175891. JBLOCKARRAY src_buffer, dst_buffer;
  175892. JBLOCKROW src_row_ptr, dst_row_ptr;
  175893. JCOEFPTR src_ptr, dst_ptr;
  175894. jpeg_component_info *compptr;
  175895. MCU_cols = dstinfo->image_width / (dstinfo->max_h_samp_factor * DCTSIZE);
  175896. MCU_rows = dstinfo->image_height / (dstinfo->max_v_samp_factor * DCTSIZE);
  175897. for (ci = 0; ci < dstinfo->num_components; ci++) {
  175898. compptr = dstinfo->comp_info + ci;
  175899. comp_width = MCU_cols * compptr->h_samp_factor;
  175900. comp_height = MCU_rows * compptr->v_samp_factor;
  175901. for (dst_blk_y = 0; dst_blk_y < compptr->height_in_blocks;
  175902. dst_blk_y += compptr->v_samp_factor) {
  175903. dst_buffer = (*srcinfo->mem->access_virt_barray)
  175904. ((j_common_ptr) srcinfo, dst_coef_arrays[ci], dst_blk_y,
  175905. (JDIMENSION) compptr->v_samp_factor, TRUE);
  175906. if (dst_blk_y < comp_height) {
  175907. /* Row is within the vertically mirrorable area. */
  175908. src_buffer = (*srcinfo->mem->access_virt_barray)
  175909. ((j_common_ptr) srcinfo, src_coef_arrays[ci],
  175910. comp_height - dst_blk_y - (JDIMENSION) compptr->v_samp_factor,
  175911. (JDIMENSION) compptr->v_samp_factor, FALSE);
  175912. } else {
  175913. /* Bottom-edge rows are only mirrored horizontally. */
  175914. src_buffer = (*srcinfo->mem->access_virt_barray)
  175915. ((j_common_ptr) srcinfo, src_coef_arrays[ci], dst_blk_y,
  175916. (JDIMENSION) compptr->v_samp_factor, FALSE);
  175917. }
  175918. for (offset_y = 0; offset_y < compptr->v_samp_factor; offset_y++) {
  175919. if (dst_blk_y < comp_height) {
  175920. /* Row is within the mirrorable area. */
  175921. dst_row_ptr = dst_buffer[offset_y];
  175922. src_row_ptr = src_buffer[compptr->v_samp_factor - offset_y - 1];
  175923. /* Process the blocks that can be mirrored both ways. */
  175924. for (dst_blk_x = 0; dst_blk_x < comp_width; dst_blk_x++) {
  175925. dst_ptr = dst_row_ptr[dst_blk_x];
  175926. src_ptr = src_row_ptr[comp_width - dst_blk_x - 1];
  175927. for (i = 0; i < DCTSIZE; i += 2) {
  175928. /* For even row, negate every odd column. */
  175929. for (j = 0; j < DCTSIZE; j += 2) {
  175930. *dst_ptr++ = *src_ptr++;
  175931. *dst_ptr++ = - *src_ptr++;
  175932. }
  175933. /* For odd row, negate every even column. */
  175934. for (j = 0; j < DCTSIZE; j += 2) {
  175935. *dst_ptr++ = - *src_ptr++;
  175936. *dst_ptr++ = *src_ptr++;
  175937. }
  175938. }
  175939. }
  175940. /* Any remaining right-edge blocks are only mirrored vertically. */
  175941. for (; dst_blk_x < compptr->width_in_blocks; dst_blk_x++) {
  175942. dst_ptr = dst_row_ptr[dst_blk_x];
  175943. src_ptr = src_row_ptr[dst_blk_x];
  175944. for (i = 0; i < DCTSIZE; i += 2) {
  175945. for (j = 0; j < DCTSIZE; j++)
  175946. *dst_ptr++ = *src_ptr++;
  175947. for (j = 0; j < DCTSIZE; j++)
  175948. *dst_ptr++ = - *src_ptr++;
  175949. }
  175950. }
  175951. } else {
  175952. /* Remaining rows are just mirrored horizontally. */
  175953. dst_row_ptr = dst_buffer[offset_y];
  175954. src_row_ptr = src_buffer[offset_y];
  175955. /* Process the blocks that can be mirrored. */
  175956. for (dst_blk_x = 0; dst_blk_x < comp_width; dst_blk_x++) {
  175957. dst_ptr = dst_row_ptr[dst_blk_x];
  175958. src_ptr = src_row_ptr[comp_width - dst_blk_x - 1];
  175959. for (i = 0; i < DCTSIZE2; i += 2) {
  175960. *dst_ptr++ = *src_ptr++;
  175961. *dst_ptr++ = - *src_ptr++;
  175962. }
  175963. }
  175964. /* Any remaining right-edge blocks are only copied. */
  175965. for (; dst_blk_x < compptr->width_in_blocks; dst_blk_x++) {
  175966. dst_ptr = dst_row_ptr[dst_blk_x];
  175967. src_ptr = src_row_ptr[dst_blk_x];
  175968. for (i = 0; i < DCTSIZE2; i++)
  175969. *dst_ptr++ = *src_ptr++;
  175970. }
  175971. }
  175972. }
  175973. }
  175974. }
  175975. }
  175976. LOCAL(void)
  175977. do_transverse (j_decompress_ptr srcinfo, j_compress_ptr dstinfo,
  175978. jvirt_barray_ptr *src_coef_arrays,
  175979. jvirt_barray_ptr *dst_coef_arrays)
  175980. /* Transverse transpose is equivalent to
  175981. * 1. 180 degree rotation;
  175982. * 2. Transposition;
  175983. * or
  175984. * 1. Horizontal mirroring;
  175985. * 2. Transposition;
  175986. * 3. Horizontal mirroring.
  175987. * These steps are merged into a single processing routine.
  175988. */
  175989. {
  175990. JDIMENSION MCU_cols, MCU_rows, comp_width, comp_height, dst_blk_x, dst_blk_y;
  175991. int ci, i, j, offset_x, offset_y;
  175992. JBLOCKARRAY src_buffer, dst_buffer;
  175993. JCOEFPTR src_ptr, dst_ptr;
  175994. jpeg_component_info *compptr;
  175995. MCU_cols = dstinfo->image_width / (dstinfo->max_h_samp_factor * DCTSIZE);
  175996. MCU_rows = dstinfo->image_height / (dstinfo->max_v_samp_factor * DCTSIZE);
  175997. for (ci = 0; ci < dstinfo->num_components; ci++) {
  175998. compptr = dstinfo->comp_info + ci;
  175999. comp_width = MCU_cols * compptr->h_samp_factor;
  176000. comp_height = MCU_rows * compptr->v_samp_factor;
  176001. for (dst_blk_y = 0; dst_blk_y < compptr->height_in_blocks;
  176002. dst_blk_y += compptr->v_samp_factor) {
  176003. dst_buffer = (*srcinfo->mem->access_virt_barray)
  176004. ((j_common_ptr) srcinfo, dst_coef_arrays[ci], dst_blk_y,
  176005. (JDIMENSION) compptr->v_samp_factor, TRUE);
  176006. for (offset_y = 0; offset_y < compptr->v_samp_factor; offset_y++) {
  176007. for (dst_blk_x = 0; dst_blk_x < compptr->width_in_blocks;
  176008. dst_blk_x += compptr->h_samp_factor) {
  176009. src_buffer = (*srcinfo->mem->access_virt_barray)
  176010. ((j_common_ptr) srcinfo, src_coef_arrays[ci], dst_blk_x,
  176011. (JDIMENSION) compptr->h_samp_factor, FALSE);
  176012. for (offset_x = 0; offset_x < compptr->h_samp_factor; offset_x++) {
  176013. if (dst_blk_y < comp_height) {
  176014. src_ptr = src_buffer[offset_x]
  176015. [comp_height - dst_blk_y - offset_y - 1];
  176016. if (dst_blk_x < comp_width) {
  176017. /* Block is within the mirrorable area. */
  176018. dst_ptr = dst_buffer[offset_y]
  176019. [comp_width - dst_blk_x - offset_x - 1];
  176020. for (i = 0; i < DCTSIZE; i++) {
  176021. for (j = 0; j < DCTSIZE; j++) {
  176022. dst_ptr[j*DCTSIZE+i] = src_ptr[i*DCTSIZE+j];
  176023. j++;
  176024. dst_ptr[j*DCTSIZE+i] = -src_ptr[i*DCTSIZE+j];
  176025. }
  176026. i++;
  176027. for (j = 0; j < DCTSIZE; j++) {
  176028. dst_ptr[j*DCTSIZE+i] = -src_ptr[i*DCTSIZE+j];
  176029. j++;
  176030. dst_ptr[j*DCTSIZE+i] = src_ptr[i*DCTSIZE+j];
  176031. }
  176032. }
  176033. } else {
  176034. /* Right-edge blocks are mirrored in y only */
  176035. dst_ptr = dst_buffer[offset_y][dst_blk_x + offset_x];
  176036. for (i = 0; i < DCTSIZE; i++) {
  176037. for (j = 0; j < DCTSIZE; j++) {
  176038. dst_ptr[j*DCTSIZE+i] = src_ptr[i*DCTSIZE+j];
  176039. j++;
  176040. dst_ptr[j*DCTSIZE+i] = -src_ptr[i*DCTSIZE+j];
  176041. }
  176042. }
  176043. }
  176044. } else {
  176045. src_ptr = src_buffer[offset_x][dst_blk_y + offset_y];
  176046. if (dst_blk_x < comp_width) {
  176047. /* Bottom-edge blocks are mirrored in x only */
  176048. dst_ptr = dst_buffer[offset_y]
  176049. [comp_width - dst_blk_x - offset_x - 1];
  176050. for (i = 0; i < DCTSIZE; i++) {
  176051. for (j = 0; j < DCTSIZE; j++)
  176052. dst_ptr[j*DCTSIZE+i] = src_ptr[i*DCTSIZE+j];
  176053. i++;
  176054. for (j = 0; j < DCTSIZE; j++)
  176055. dst_ptr[j*DCTSIZE+i] = -src_ptr[i*DCTSIZE+j];
  176056. }
  176057. } else {
  176058. /* At lower right corner, just transpose, no mirroring */
  176059. dst_ptr = dst_buffer[offset_y][dst_blk_x + offset_x];
  176060. for (i = 0; i < DCTSIZE; i++)
  176061. for (j = 0; j < DCTSIZE; j++)
  176062. dst_ptr[j*DCTSIZE+i] = src_ptr[i*DCTSIZE+j];
  176063. }
  176064. }
  176065. }
  176066. }
  176067. }
  176068. }
  176069. }
  176070. }
  176071. /* Request any required workspace.
  176072. *
  176073. * We allocate the workspace virtual arrays from the source decompression
  176074. * object, so that all the arrays (both the original data and the workspace)
  176075. * will be taken into account while making memory management decisions.
  176076. * Hence, this routine must be called after jpeg_read_header (which reads
  176077. * the image dimensions) and before jpeg_read_coefficients (which realizes
  176078. * the source's virtual arrays).
  176079. */
  176080. GLOBAL(void)
  176081. jtransform_request_workspace (j_decompress_ptr srcinfo,
  176082. jpeg_transform_info *info)
  176083. {
  176084. jvirt_barray_ptr *coef_arrays = NULL;
  176085. jpeg_component_info *compptr;
  176086. int ci;
  176087. if (info->force_grayscale &&
  176088. srcinfo->jpeg_color_space == JCS_YCbCr &&
  176089. srcinfo->num_components == 3) {
  176090. /* We'll only process the first component */
  176091. info->num_components = 1;
  176092. } else {
  176093. /* Process all the components */
  176094. info->num_components = srcinfo->num_components;
  176095. }
  176096. switch (info->transform) {
  176097. case JXFORM_NONE:
  176098. case JXFORM_FLIP_H:
  176099. /* Don't need a workspace array */
  176100. break;
  176101. case JXFORM_FLIP_V:
  176102. case JXFORM_ROT_180:
  176103. /* Need workspace arrays having same dimensions as source image.
  176104. * Note that we allocate arrays padded out to the next iMCU boundary,
  176105. * so that transform routines need not worry about missing edge blocks.
  176106. */
  176107. coef_arrays = (jvirt_barray_ptr *)
  176108. (*srcinfo->mem->alloc_small) ((j_common_ptr) srcinfo, JPOOL_IMAGE,
  176109. SIZEOF(jvirt_barray_ptr) * info->num_components);
  176110. for (ci = 0; ci < info->num_components; ci++) {
  176111. compptr = srcinfo->comp_info + ci;
  176112. coef_arrays[ci] = (*srcinfo->mem->request_virt_barray)
  176113. ((j_common_ptr) srcinfo, JPOOL_IMAGE, FALSE,
  176114. (JDIMENSION) jround_up((long) compptr->width_in_blocks,
  176115. (long) compptr->h_samp_factor),
  176116. (JDIMENSION) jround_up((long) compptr->height_in_blocks,
  176117. (long) compptr->v_samp_factor),
  176118. (JDIMENSION) compptr->v_samp_factor);
  176119. }
  176120. break;
  176121. case JXFORM_TRANSPOSE:
  176122. case JXFORM_TRANSVERSE:
  176123. case JXFORM_ROT_90:
  176124. case JXFORM_ROT_270:
  176125. /* Need workspace arrays having transposed dimensions.
  176126. * Note that we allocate arrays padded out to the next iMCU boundary,
  176127. * so that transform routines need not worry about missing edge blocks.
  176128. */
  176129. coef_arrays = (jvirt_barray_ptr *)
  176130. (*srcinfo->mem->alloc_small) ((j_common_ptr) srcinfo, JPOOL_IMAGE,
  176131. SIZEOF(jvirt_barray_ptr) * info->num_components);
  176132. for (ci = 0; ci < info->num_components; ci++) {
  176133. compptr = srcinfo->comp_info + ci;
  176134. coef_arrays[ci] = (*srcinfo->mem->request_virt_barray)
  176135. ((j_common_ptr) srcinfo, JPOOL_IMAGE, FALSE,
  176136. (JDIMENSION) jround_up((long) compptr->height_in_blocks,
  176137. (long) compptr->v_samp_factor),
  176138. (JDIMENSION) jround_up((long) compptr->width_in_blocks,
  176139. (long) compptr->h_samp_factor),
  176140. (JDIMENSION) compptr->h_samp_factor);
  176141. }
  176142. break;
  176143. }
  176144. info->workspace_coef_arrays = coef_arrays;
  176145. }
  176146. /* Transpose destination image parameters */
  176147. LOCAL(void)
  176148. transpose_critical_parameters (j_compress_ptr dstinfo)
  176149. {
  176150. int tblno, i, j, ci, itemp;
  176151. jpeg_component_info *compptr;
  176152. JQUANT_TBL *qtblptr;
  176153. JDIMENSION dtemp;
  176154. UINT16 qtemp;
  176155. /* Transpose basic image dimensions */
  176156. dtemp = dstinfo->image_width;
  176157. dstinfo->image_width = dstinfo->image_height;
  176158. dstinfo->image_height = dtemp;
  176159. /* Transpose sampling factors */
  176160. for (ci = 0; ci < dstinfo->num_components; ci++) {
  176161. compptr = dstinfo->comp_info + ci;
  176162. itemp = compptr->h_samp_factor;
  176163. compptr->h_samp_factor = compptr->v_samp_factor;
  176164. compptr->v_samp_factor = itemp;
  176165. }
  176166. /* Transpose quantization tables */
  176167. for (tblno = 0; tblno < NUM_QUANT_TBLS; tblno++) {
  176168. qtblptr = dstinfo->quant_tbl_ptrs[tblno];
  176169. if (qtblptr != NULL) {
  176170. for (i = 0; i < DCTSIZE; i++) {
  176171. for (j = 0; j < i; j++) {
  176172. qtemp = qtblptr->quantval[i*DCTSIZE+j];
  176173. qtblptr->quantval[i*DCTSIZE+j] = qtblptr->quantval[j*DCTSIZE+i];
  176174. qtblptr->quantval[j*DCTSIZE+i] = qtemp;
  176175. }
  176176. }
  176177. }
  176178. }
  176179. }
  176180. /* Trim off any partial iMCUs on the indicated destination edge */
  176181. LOCAL(void)
  176182. trim_right_edge (j_compress_ptr dstinfo)
  176183. {
  176184. int ci, max_h_samp_factor;
  176185. JDIMENSION MCU_cols;
  176186. /* We have to compute max_h_samp_factor ourselves,
  176187. * because it hasn't been set yet in the destination
  176188. * (and we don't want to use the source's value).
  176189. */
  176190. max_h_samp_factor = 1;
  176191. for (ci = 0; ci < dstinfo->num_components; ci++) {
  176192. int h_samp_factor = dstinfo->comp_info[ci].h_samp_factor;
  176193. max_h_samp_factor = MAX(max_h_samp_factor, h_samp_factor);
  176194. }
  176195. MCU_cols = dstinfo->image_width / (max_h_samp_factor * DCTSIZE);
  176196. if (MCU_cols > 0) /* can't trim to 0 pixels */
  176197. dstinfo->image_width = MCU_cols * (max_h_samp_factor * DCTSIZE);
  176198. }
  176199. LOCAL(void)
  176200. trim_bottom_edge (j_compress_ptr dstinfo)
  176201. {
  176202. int ci, max_v_samp_factor;
  176203. JDIMENSION MCU_rows;
  176204. /* We have to compute max_v_samp_factor ourselves,
  176205. * because it hasn't been set yet in the destination
  176206. * (and we don't want to use the source's value).
  176207. */
  176208. max_v_samp_factor = 1;
  176209. for (ci = 0; ci < dstinfo->num_components; ci++) {
  176210. int v_samp_factor = dstinfo->comp_info[ci].v_samp_factor;
  176211. max_v_samp_factor = MAX(max_v_samp_factor, v_samp_factor);
  176212. }
  176213. MCU_rows = dstinfo->image_height / (max_v_samp_factor * DCTSIZE);
  176214. if (MCU_rows > 0) /* can't trim to 0 pixels */
  176215. dstinfo->image_height = MCU_rows * (max_v_samp_factor * DCTSIZE);
  176216. }
  176217. /* Adjust output image parameters as needed.
  176218. *
  176219. * This must be called after jpeg_copy_critical_parameters()
  176220. * and before jpeg_write_coefficients().
  176221. *
  176222. * The return value is the set of virtual coefficient arrays to be written
  176223. * (either the ones allocated by jtransform_request_workspace, or the
  176224. * original source data arrays). The caller will need to pass this value
  176225. * to jpeg_write_coefficients().
  176226. */
  176227. GLOBAL(jvirt_barray_ptr *)
  176228. jtransform_adjust_parameters (j_decompress_ptr srcinfo,
  176229. j_compress_ptr dstinfo,
  176230. jvirt_barray_ptr *src_coef_arrays,
  176231. jpeg_transform_info *info)
  176232. {
  176233. /* If force-to-grayscale is requested, adjust destination parameters */
  176234. if (info->force_grayscale) {
  176235. /* We use jpeg_set_colorspace to make sure subsidiary settings get fixed
  176236. * properly. Among other things, the target h_samp_factor & v_samp_factor
  176237. * will get set to 1, which typically won't match the source.
  176238. * In fact we do this even if the source is already grayscale; that
  176239. * provides an easy way of coercing a grayscale JPEG with funny sampling
  176240. * factors to the customary 1,1. (Some decoders fail on other factors.)
  176241. */
  176242. if ((dstinfo->jpeg_color_space == JCS_YCbCr &&
  176243. dstinfo->num_components == 3) ||
  176244. (dstinfo->jpeg_color_space == JCS_GRAYSCALE &&
  176245. dstinfo->num_components == 1)) {
  176246. /* We have to preserve the source's quantization table number. */
  176247. int sv_quant_tbl_no = dstinfo->comp_info[0].quant_tbl_no;
  176248. jpeg_set_colorspace(dstinfo, JCS_GRAYSCALE);
  176249. dstinfo->comp_info[0].quant_tbl_no = sv_quant_tbl_no;
  176250. } else {
  176251. /* Sorry, can't do it */
  176252. ERREXIT(dstinfo, JERR_CONVERSION_NOTIMPL);
  176253. }
  176254. }
  176255. /* Correct the destination's image dimensions etc if necessary */
  176256. switch (info->transform) {
  176257. case JXFORM_NONE:
  176258. /* Nothing to do */
  176259. break;
  176260. case JXFORM_FLIP_H:
  176261. if (info->trim)
  176262. trim_right_edge(dstinfo);
  176263. break;
  176264. case JXFORM_FLIP_V:
  176265. if (info->trim)
  176266. trim_bottom_edge(dstinfo);
  176267. break;
  176268. case JXFORM_TRANSPOSE:
  176269. transpose_critical_parameters(dstinfo);
  176270. /* transpose does NOT have to trim anything */
  176271. break;
  176272. case JXFORM_TRANSVERSE:
  176273. transpose_critical_parameters(dstinfo);
  176274. if (info->trim) {
  176275. trim_right_edge(dstinfo);
  176276. trim_bottom_edge(dstinfo);
  176277. }
  176278. break;
  176279. case JXFORM_ROT_90:
  176280. transpose_critical_parameters(dstinfo);
  176281. if (info->trim)
  176282. trim_right_edge(dstinfo);
  176283. break;
  176284. case JXFORM_ROT_180:
  176285. if (info->trim) {
  176286. trim_right_edge(dstinfo);
  176287. trim_bottom_edge(dstinfo);
  176288. }
  176289. break;
  176290. case JXFORM_ROT_270:
  176291. transpose_critical_parameters(dstinfo);
  176292. if (info->trim)
  176293. trim_bottom_edge(dstinfo);
  176294. break;
  176295. }
  176296. /* Return the appropriate output data set */
  176297. if (info->workspace_coef_arrays != NULL)
  176298. return info->workspace_coef_arrays;
  176299. return src_coef_arrays;
  176300. }
  176301. /* Execute the actual transformation, if any.
  176302. *
  176303. * This must be called *after* jpeg_write_coefficients, because it depends
  176304. * on jpeg_write_coefficients to have computed subsidiary values such as
  176305. * the per-component width and height fields in the destination object.
  176306. *
  176307. * Note that some transformations will modify the source data arrays!
  176308. */
  176309. GLOBAL(void)
  176310. jtransform_execute_transformation (j_decompress_ptr srcinfo,
  176311. j_compress_ptr dstinfo,
  176312. jvirt_barray_ptr *src_coef_arrays,
  176313. jpeg_transform_info *info)
  176314. {
  176315. jvirt_barray_ptr *dst_coef_arrays = info->workspace_coef_arrays;
  176316. switch (info->transform) {
  176317. case JXFORM_NONE:
  176318. break;
  176319. case JXFORM_FLIP_H:
  176320. do_flip_h(srcinfo, dstinfo, src_coef_arrays);
  176321. break;
  176322. case JXFORM_FLIP_V:
  176323. do_flip_v(srcinfo, dstinfo, src_coef_arrays, dst_coef_arrays);
  176324. break;
  176325. case JXFORM_TRANSPOSE:
  176326. do_transpose(srcinfo, dstinfo, src_coef_arrays, dst_coef_arrays);
  176327. break;
  176328. case JXFORM_TRANSVERSE:
  176329. do_transverse(srcinfo, dstinfo, src_coef_arrays, dst_coef_arrays);
  176330. break;
  176331. case JXFORM_ROT_90:
  176332. do_rot_90(srcinfo, dstinfo, src_coef_arrays, dst_coef_arrays);
  176333. break;
  176334. case JXFORM_ROT_180:
  176335. do_rot_180(srcinfo, dstinfo, src_coef_arrays, dst_coef_arrays);
  176336. break;
  176337. case JXFORM_ROT_270:
  176338. do_rot_270(srcinfo, dstinfo, src_coef_arrays, dst_coef_arrays);
  176339. break;
  176340. }
  176341. }
  176342. #endif /* TRANSFORMS_SUPPORTED */
  176343. /* Setup decompression object to save desired markers in memory.
  176344. * This must be called before jpeg_read_header() to have the desired effect.
  176345. */
  176346. GLOBAL(void)
  176347. jcopy_markers_setup (j_decompress_ptr srcinfo, JCOPY_OPTION option)
  176348. {
  176349. #ifdef SAVE_MARKERS_SUPPORTED
  176350. int m;
  176351. /* Save comments except under NONE option */
  176352. if (option != JCOPYOPT_NONE) {
  176353. jpeg_save_markers(srcinfo, JPEG_COM, 0xFFFF);
  176354. }
  176355. /* Save all types of APPn markers iff ALL option */
  176356. if (option == JCOPYOPT_ALL) {
  176357. for (m = 0; m < 16; m++)
  176358. jpeg_save_markers(srcinfo, JPEG_APP0 + m, 0xFFFF);
  176359. }
  176360. #endif /* SAVE_MARKERS_SUPPORTED */
  176361. }
  176362. /* Copy markers saved in the given source object to the destination object.
  176363. * This should be called just after jpeg_start_compress() or
  176364. * jpeg_write_coefficients().
  176365. * Note that those routines will have written the SOI, and also the
  176366. * JFIF APP0 or Adobe APP14 markers if selected.
  176367. */
  176368. GLOBAL(void)
  176369. jcopy_markers_execute (j_decompress_ptr srcinfo, j_compress_ptr dstinfo,
  176370. JCOPY_OPTION option)
  176371. {
  176372. jpeg_saved_marker_ptr marker;
  176373. /* In the current implementation, we don't actually need to examine the
  176374. * option flag here; we just copy everything that got saved.
  176375. * But to avoid confusion, we do not output JFIF and Adobe APP14 markers
  176376. * if the encoder library already wrote one.
  176377. */
  176378. for (marker = srcinfo->marker_list; marker != NULL; marker = marker->next) {
  176379. if (dstinfo->write_JFIF_header &&
  176380. marker->marker == JPEG_APP0 &&
  176381. marker->data_length >= 5 &&
  176382. GETJOCTET(marker->data[0]) == 0x4A &&
  176383. GETJOCTET(marker->data[1]) == 0x46 &&
  176384. GETJOCTET(marker->data[2]) == 0x49 &&
  176385. GETJOCTET(marker->data[3]) == 0x46 &&
  176386. GETJOCTET(marker->data[4]) == 0)
  176387. continue; /* reject duplicate JFIF */
  176388. if (dstinfo->write_Adobe_marker &&
  176389. marker->marker == JPEG_APP0+14 &&
  176390. marker->data_length >= 5 &&
  176391. GETJOCTET(marker->data[0]) == 0x41 &&
  176392. GETJOCTET(marker->data[1]) == 0x64 &&
  176393. GETJOCTET(marker->data[2]) == 0x6F &&
  176394. GETJOCTET(marker->data[3]) == 0x62 &&
  176395. GETJOCTET(marker->data[4]) == 0x65)
  176396. continue; /* reject duplicate Adobe */
  176397. #ifdef NEED_FAR_POINTERS
  176398. /* We could use jpeg_write_marker if the data weren't FAR... */
  176399. {
  176400. unsigned int i;
  176401. jpeg_write_m_header(dstinfo, marker->marker, marker->data_length);
  176402. for (i = 0; i < marker->data_length; i++)
  176403. jpeg_write_m_byte(dstinfo, marker->data[i]);
  176404. }
  176405. #else
  176406. jpeg_write_marker(dstinfo, marker->marker,
  176407. marker->data, marker->data_length);
  176408. #endif
  176409. }
  176410. }
  176411. /*** End of inlined file: transupp.c ***/
  176412. }
  176413. #else
  176414. #define JPEG_INTERNALS
  176415. #undef FAR
  176416. #include <jpeglib.h>
  176417. #endif
  176418. }
  176419. #undef max
  176420. #undef min
  176421. #if JUCE_MSVC
  176422. #pragma warning (pop)
  176423. #endif
  176424. BEGIN_JUCE_NAMESPACE
  176425. namespace JPEGHelpers
  176426. {
  176427. using namespace jpeglibNamespace;
  176428. #if ! JUCE_MSVC
  176429. using jpeglibNamespace::boolean;
  176430. #endif
  176431. struct JPEGDecodingFailure {};
  176432. static void fatalErrorHandler (j_common_ptr)
  176433. {
  176434. throw JPEGDecodingFailure();
  176435. }
  176436. static void silentErrorCallback1 (j_common_ptr) {}
  176437. static void silentErrorCallback2 (j_common_ptr, int) {}
  176438. static void silentErrorCallback3 (j_common_ptr, char*) {}
  176439. static void setupSilentErrorHandler (struct jpeg_error_mgr& err)
  176440. {
  176441. zerostruct (err);
  176442. err.error_exit = fatalErrorHandler;
  176443. err.emit_message = silentErrorCallback2;
  176444. err.output_message = silentErrorCallback1;
  176445. err.format_message = silentErrorCallback3;
  176446. err.reset_error_mgr = silentErrorCallback1;
  176447. }
  176448. static void dummyCallback1 (j_decompress_ptr)
  176449. {
  176450. }
  176451. static void jpegSkip (j_decompress_ptr decompStruct, long num)
  176452. {
  176453. decompStruct->src->next_input_byte += num;
  176454. num = jmin (num, (long) decompStruct->src->bytes_in_buffer);
  176455. decompStruct->src->bytes_in_buffer -= num;
  176456. }
  176457. static boolean jpegFill (j_decompress_ptr)
  176458. {
  176459. return 0;
  176460. }
  176461. static const int jpegBufferSize = 512;
  176462. struct JuceJpegDest : public jpeg_destination_mgr
  176463. {
  176464. OutputStream* output;
  176465. char* buffer;
  176466. };
  176467. static void jpegWriteInit (j_compress_ptr)
  176468. {
  176469. }
  176470. static void jpegWriteTerminate (j_compress_ptr cinfo)
  176471. {
  176472. JuceJpegDest* const dest = static_cast <JuceJpegDest*> (cinfo->dest);
  176473. const size_t numToWrite = jpegBufferSize - dest->free_in_buffer;
  176474. dest->output->write (dest->buffer, (int) numToWrite);
  176475. }
  176476. static boolean jpegWriteFlush (j_compress_ptr cinfo)
  176477. {
  176478. JuceJpegDest* const dest = static_cast <JuceJpegDest*> (cinfo->dest);
  176479. const int numToWrite = jpegBufferSize;
  176480. dest->next_output_byte = reinterpret_cast <JOCTET*> (dest->buffer);
  176481. dest->free_in_buffer = jpegBufferSize;
  176482. return dest->output->write (dest->buffer, numToWrite);
  176483. }
  176484. }
  176485. JPEGImageFormat::JPEGImageFormat()
  176486. : quality (-1.0f)
  176487. {
  176488. }
  176489. JPEGImageFormat::~JPEGImageFormat() {}
  176490. void JPEGImageFormat::setQuality (const float newQuality)
  176491. {
  176492. quality = newQuality;
  176493. }
  176494. const String JPEGImageFormat::getFormatName()
  176495. {
  176496. return "JPEG";
  176497. }
  176498. bool JPEGImageFormat::canUnderstand (InputStream& in)
  176499. {
  176500. const int bytesNeeded = 10;
  176501. uint8 header [bytesNeeded];
  176502. if (in.read (header, bytesNeeded) == bytesNeeded)
  176503. {
  176504. return header[0] == 0xff
  176505. && header[1] == 0xd8
  176506. && header[2] == 0xff
  176507. && (header[3] == 0xe0 || header[3] == 0xe1);
  176508. }
  176509. return false;
  176510. }
  176511. Image* JPEGImageFormat::decodeImage (InputStream& in)
  176512. {
  176513. using namespace jpeglibNamespace;
  176514. using namespace JPEGHelpers;
  176515. MemoryBlock mb;
  176516. in.readIntoMemoryBlock (mb);
  176517. Image* image = 0;
  176518. if (mb.getSize() > 16)
  176519. {
  176520. struct jpeg_decompress_struct jpegDecompStruct;
  176521. struct jpeg_error_mgr jerr;
  176522. setupSilentErrorHandler (jerr);
  176523. jpegDecompStruct.err = &jerr;
  176524. jpeg_create_decompress (&jpegDecompStruct);
  176525. jpegDecompStruct.src = (jpeg_source_mgr*)(jpegDecompStruct.mem->alloc_small)
  176526. ((j_common_ptr)(&jpegDecompStruct), JPOOL_PERMANENT, sizeof (jpeg_source_mgr));
  176527. jpegDecompStruct.src->init_source = dummyCallback1;
  176528. jpegDecompStruct.src->fill_input_buffer = jpegFill;
  176529. jpegDecompStruct.src->skip_input_data = jpegSkip;
  176530. jpegDecompStruct.src->resync_to_restart = jpeg_resync_to_restart;
  176531. jpegDecompStruct.src->term_source = dummyCallback1;
  176532. jpegDecompStruct.src->next_input_byte = static_cast <const unsigned char*> (mb.getData());
  176533. jpegDecompStruct.src->bytes_in_buffer = mb.getSize();
  176534. try
  176535. {
  176536. jpeg_read_header (&jpegDecompStruct, TRUE);
  176537. jpeg_calc_output_dimensions (&jpegDecompStruct);
  176538. const int width = jpegDecompStruct.output_width;
  176539. const int height = jpegDecompStruct.output_height;
  176540. jpegDecompStruct.out_color_space = JCS_RGB;
  176541. JSAMPARRAY buffer
  176542. = (*jpegDecompStruct.mem->alloc_sarray) ((j_common_ptr) &jpegDecompStruct,
  176543. JPOOL_IMAGE,
  176544. width * 3, 1);
  176545. if (jpeg_start_decompress (&jpegDecompStruct))
  176546. {
  176547. image = Image::createNativeImage (Image::RGB, width, height, false);
  176548. const bool hasAlphaChan = image->hasAlphaChannel();
  176549. const Image::BitmapData destData (*image, 0, 0, width, height, true);
  176550. for (int y = 0; y < height; ++y)
  176551. {
  176552. jpeg_read_scanlines (&jpegDecompStruct, buffer, 1);
  176553. const uint8* src = *buffer;
  176554. uint8* dest = destData.getLinePointer (y);
  176555. if (hasAlphaChan)
  176556. {
  176557. for (int i = width; --i >= 0;)
  176558. {
  176559. ((PixelARGB*) dest)->setARGB (0xff, src[0], src[1], src[2]);
  176560. ((PixelARGB*) dest)->premultiply();
  176561. dest += destData.pixelStride;
  176562. src += 3;
  176563. }
  176564. }
  176565. else
  176566. {
  176567. for (int i = width; --i >= 0;)
  176568. {
  176569. ((PixelRGB*) dest)->setARGB (0xff, src[0], src[1], src[2]);
  176570. dest += destData.pixelStride;
  176571. src += 3;
  176572. }
  176573. }
  176574. }
  176575. jpeg_finish_decompress (&jpegDecompStruct);
  176576. in.setPosition (((char*) jpegDecompStruct.src->next_input_byte) - (char*) mb.getData());
  176577. }
  176578. jpeg_destroy_decompress (&jpegDecompStruct);
  176579. }
  176580. catch (...)
  176581. {}
  176582. }
  176583. return image;
  176584. }
  176585. bool JPEGImageFormat::writeImageToStream (const Image& image, OutputStream& out)
  176586. {
  176587. using namespace jpeglibNamespace;
  176588. using namespace JPEGHelpers;
  176589. if (image.hasAlphaChannel())
  176590. {
  176591. // this method could fill the background in white and still save the image..
  176592. jassertfalse
  176593. return true;
  176594. }
  176595. struct jpeg_compress_struct jpegCompStruct;
  176596. struct jpeg_error_mgr jerr;
  176597. setupSilentErrorHandler (jerr);
  176598. jpegCompStruct.err = &jerr;
  176599. jpeg_create_compress (&jpegCompStruct);
  176600. JuceJpegDest dest;
  176601. jpegCompStruct.dest = &dest;
  176602. dest.output = &out;
  176603. HeapBlock <char> tempBuffer (jpegBufferSize);
  176604. dest.buffer = tempBuffer;
  176605. dest.next_output_byte = (JOCTET*) dest.buffer;
  176606. dest.free_in_buffer = jpegBufferSize;
  176607. dest.init_destination = jpegWriteInit;
  176608. dest.empty_output_buffer = jpegWriteFlush;
  176609. dest.term_destination = jpegWriteTerminate;
  176610. jpegCompStruct.image_width = image.getWidth();
  176611. jpegCompStruct.image_height = image.getHeight();
  176612. jpegCompStruct.input_components = 3;
  176613. jpegCompStruct.in_color_space = JCS_RGB;
  176614. jpegCompStruct.write_JFIF_header = 1;
  176615. jpegCompStruct.X_density = 72;
  176616. jpegCompStruct.Y_density = 72;
  176617. jpeg_set_defaults (&jpegCompStruct);
  176618. jpegCompStruct.dct_method = JDCT_FLOAT;
  176619. jpegCompStruct.optimize_coding = 1;
  176620. //jpegCompStruct.smoothing_factor = 10;
  176621. if (quality < 0.0f)
  176622. quality = 0.85f;
  176623. jpeg_set_quality (&jpegCompStruct, jlimit (0, 100, roundToInt (quality * 100.0f)), TRUE);
  176624. jpeg_start_compress (&jpegCompStruct, TRUE);
  176625. const int strideBytes = jpegCompStruct.image_width * jpegCompStruct.input_components;
  176626. JSAMPARRAY buffer = (*jpegCompStruct.mem->alloc_sarray) ((j_common_ptr) &jpegCompStruct,
  176627. JPOOL_IMAGE, strideBytes, 1);
  176628. const Image::BitmapData srcData (image, 0, 0, jpegCompStruct.image_width, jpegCompStruct.image_height);
  176629. while (jpegCompStruct.next_scanline < jpegCompStruct.image_height)
  176630. {
  176631. const uint8* src = srcData.getLinePointer (jpegCompStruct.next_scanline);
  176632. uint8* dst = *buffer;
  176633. for (int i = jpegCompStruct.image_width; --i >= 0;)
  176634. {
  176635. *dst++ = ((const PixelRGB*) src)->getRed();
  176636. *dst++ = ((const PixelRGB*) src)->getGreen();
  176637. *dst++ = ((const PixelRGB*) src)->getBlue();
  176638. src += srcData.pixelStride;
  176639. }
  176640. jpeg_write_scanlines (&jpegCompStruct, buffer, 1);
  176641. }
  176642. jpeg_finish_compress (&jpegCompStruct);
  176643. jpeg_destroy_compress (&jpegCompStruct);
  176644. out.flush();
  176645. return true;
  176646. }
  176647. END_JUCE_NAMESPACE
  176648. /*** End of inlined file: juce_JPEGLoader.cpp ***/
  176649. /*** Start of inlined file: juce_PNGLoader.cpp ***/
  176650. #ifdef _MSC_VER
  176651. #pragma warning (push)
  176652. #pragma warning (disable: 4390 4611)
  176653. #endif
  176654. namespace zlibNamespace
  176655. {
  176656. #if JUCE_INCLUDE_ZLIB_CODE
  176657. #undef OS_CODE
  176658. #undef fdopen
  176659. #undef OS_CODE
  176660. #else
  176661. #include <zlib.h>
  176662. #endif
  176663. }
  176664. namespace pnglibNamespace
  176665. {
  176666. using namespace zlibNamespace;
  176667. #if JUCE_INCLUDE_PNGLIB_CODE
  176668. #if _MSC_VER != 1310
  176669. using ::calloc; // (causes conflict in VS.NET 2003)
  176670. using ::malloc;
  176671. using ::free;
  176672. #endif
  176673. extern "C"
  176674. {
  176675. using ::abs;
  176676. #define PNG_INTERNAL
  176677. #define NO_DUMMY_DECL
  176678. #define PNG_SETJMP_NOT_SUPPORTED
  176679. /*** Start of inlined file: png.h ***/
  176680. /* png.h - header file for PNG reference library
  176681. *
  176682. * libpng version 1.2.21 - October 4, 2007
  176683. * Copyright (c) 1998-2007 Glenn Randers-Pehrson
  176684. * (Version 0.96 Copyright (c) 1996, 1997 Andreas Dilger)
  176685. * (Version 0.88 Copyright (c) 1995, 1996 Guy Eric Schalnat, Group 42, Inc.)
  176686. *
  176687. * Authors and maintainers:
  176688. * libpng versions 0.71, May 1995, through 0.88, January 1996: Guy Schalnat
  176689. * libpng versions 0.89c, June 1996, through 0.96, May 1997: Andreas Dilger
  176690. * libpng versions 0.97, January 1998, through 1.2.21 - October 4, 2007: Glenn
  176691. * See also "Contributing Authors", below.
  176692. *
  176693. * Note about libpng version numbers:
  176694. *
  176695. * Due to various miscommunications, unforeseen code incompatibilities
  176696. * and occasional factors outside the authors' control, version numbering
  176697. * on the library has not always been consistent and straightforward.
  176698. * The following table summarizes matters since version 0.89c, which was
  176699. * the first widely used release:
  176700. *
  176701. * source png.h png.h shared-lib
  176702. * version string int version
  176703. * ------- ------ ----- ----------
  176704. * 0.89c "1.0 beta 3" 0.89 89 1.0.89
  176705. * 0.90 "1.0 beta 4" 0.90 90 0.90 [should have been 2.0.90]
  176706. * 0.95 "1.0 beta 5" 0.95 95 0.95 [should have been 2.0.95]
  176707. * 0.96 "1.0 beta 6" 0.96 96 0.96 [should have been 2.0.96]
  176708. * 0.97b "1.00.97 beta 7" 1.00.97 97 1.0.1 [should have been 2.0.97]
  176709. * 0.97c 0.97 97 2.0.97
  176710. * 0.98 0.98 98 2.0.98
  176711. * 0.99 0.99 98 2.0.99
  176712. * 0.99a-m 0.99 99 2.0.99
  176713. * 1.00 1.00 100 2.1.0 [100 should be 10000]
  176714. * 1.0.0 (from here on, the 100 2.1.0 [100 should be 10000]
  176715. * 1.0.1 png.h string is 10001 2.1.0
  176716. * 1.0.1a-e identical to the 10002 from here on, the shared library
  176717. * 1.0.2 source version) 10002 is 2.V where V is the source code
  176718. * 1.0.2a-b 10003 version, except as noted.
  176719. * 1.0.3 10003
  176720. * 1.0.3a-d 10004
  176721. * 1.0.4 10004
  176722. * 1.0.4a-f 10005
  176723. * 1.0.5 (+ 2 patches) 10005
  176724. * 1.0.5a-d 10006
  176725. * 1.0.5e-r 10100 (not source compatible)
  176726. * 1.0.5s-v 10006 (not binary compatible)
  176727. * 1.0.6 (+ 3 patches) 10006 (still binary incompatible)
  176728. * 1.0.6d-f 10007 (still binary incompatible)
  176729. * 1.0.6g 10007
  176730. * 1.0.6h 10007 10.6h (testing xy.z so-numbering)
  176731. * 1.0.6i 10007 10.6i
  176732. * 1.0.6j 10007 2.1.0.6j (incompatible with 1.0.0)
  176733. * 1.0.7beta11-14 DLLNUM 10007 2.1.0.7beta11-14 (binary compatible)
  176734. * 1.0.7beta15-18 1 10007 2.1.0.7beta15-18 (binary compatible)
  176735. * 1.0.7rc1-2 1 10007 2.1.0.7rc1-2 (binary compatible)
  176736. * 1.0.7 1 10007 (still compatible)
  176737. * 1.0.8beta1-4 1 10008 2.1.0.8beta1-4
  176738. * 1.0.8rc1 1 10008 2.1.0.8rc1
  176739. * 1.0.8 1 10008 2.1.0.8
  176740. * 1.0.9beta1-6 1 10009 2.1.0.9beta1-6
  176741. * 1.0.9rc1 1 10009 2.1.0.9rc1
  176742. * 1.0.9beta7-10 1 10009 2.1.0.9beta7-10
  176743. * 1.0.9rc2 1 10009 2.1.0.9rc2
  176744. * 1.0.9 1 10009 2.1.0.9
  176745. * 1.0.10beta1 1 10010 2.1.0.10beta1
  176746. * 1.0.10rc1 1 10010 2.1.0.10rc1
  176747. * 1.0.10 1 10010 2.1.0.10
  176748. * 1.0.11beta1-3 1 10011 2.1.0.11beta1-3
  176749. * 1.0.11rc1 1 10011 2.1.0.11rc1
  176750. * 1.0.11 1 10011 2.1.0.11
  176751. * 1.0.12beta1-2 2 10012 2.1.0.12beta1-2
  176752. * 1.0.12rc1 2 10012 2.1.0.12rc1
  176753. * 1.0.12 2 10012 2.1.0.12
  176754. * 1.1.0a-f - 10100 2.1.1.0a-f (branch abandoned)
  176755. * 1.2.0beta1-2 2 10200 2.1.2.0beta1-2
  176756. * 1.2.0beta3-5 3 10200 3.1.2.0beta3-5
  176757. * 1.2.0rc1 3 10200 3.1.2.0rc1
  176758. * 1.2.0 3 10200 3.1.2.0
  176759. * 1.2.1beta1-4 3 10201 3.1.2.1beta1-4
  176760. * 1.2.1rc1-2 3 10201 3.1.2.1rc1-2
  176761. * 1.2.1 3 10201 3.1.2.1
  176762. * 1.2.2beta1-6 12 10202 12.so.0.1.2.2beta1-6
  176763. * 1.0.13beta1 10 10013 10.so.0.1.0.13beta1
  176764. * 1.0.13rc1 10 10013 10.so.0.1.0.13rc1
  176765. * 1.2.2rc1 12 10202 12.so.0.1.2.2rc1
  176766. * 1.0.13 10 10013 10.so.0.1.0.13
  176767. * 1.2.2 12 10202 12.so.0.1.2.2
  176768. * 1.2.3rc1-6 12 10203 12.so.0.1.2.3rc1-6
  176769. * 1.2.3 12 10203 12.so.0.1.2.3
  176770. * 1.2.4beta1-3 13 10204 12.so.0.1.2.4beta1-3
  176771. * 1.0.14rc1 13 10014 10.so.0.1.0.14rc1
  176772. * 1.2.4rc1 13 10204 12.so.0.1.2.4rc1
  176773. * 1.0.14 10 10014 10.so.0.1.0.14
  176774. * 1.2.4 13 10204 12.so.0.1.2.4
  176775. * 1.2.5beta1-2 13 10205 12.so.0.1.2.5beta1-2
  176776. * 1.0.15rc1-3 10 10015 10.so.0.1.0.15rc1-3
  176777. * 1.2.5rc1-3 13 10205 12.so.0.1.2.5rc1-3
  176778. * 1.0.15 10 10015 10.so.0.1.0.15
  176779. * 1.2.5 13 10205 12.so.0.1.2.5
  176780. * 1.2.6beta1-4 13 10206 12.so.0.1.2.6beta1-4
  176781. * 1.0.16 10 10016 10.so.0.1.0.16
  176782. * 1.2.6 13 10206 12.so.0.1.2.6
  176783. * 1.2.7beta1-2 13 10207 12.so.0.1.2.7beta1-2
  176784. * 1.0.17rc1 10 10017 10.so.0.1.0.17rc1
  176785. * 1.2.7rc1 13 10207 12.so.0.1.2.7rc1
  176786. * 1.0.17 10 10017 10.so.0.1.0.17
  176787. * 1.2.7 13 10207 12.so.0.1.2.7
  176788. * 1.2.8beta1-5 13 10208 12.so.0.1.2.8beta1-5
  176789. * 1.0.18rc1-5 10 10018 10.so.0.1.0.18rc1-5
  176790. * 1.2.8rc1-5 13 10208 12.so.0.1.2.8rc1-5
  176791. * 1.0.18 10 10018 10.so.0.1.0.18
  176792. * 1.2.8 13 10208 12.so.0.1.2.8
  176793. * 1.2.9beta1-3 13 10209 12.so.0.1.2.9beta1-3
  176794. * 1.2.9beta4-11 13 10209 12.so.0.9[.0]
  176795. * 1.2.9rc1 13 10209 12.so.0.9[.0]
  176796. * 1.2.9 13 10209 12.so.0.9[.0]
  176797. * 1.2.10beta1-8 13 10210 12.so.0.10[.0]
  176798. * 1.2.10rc1-3 13 10210 12.so.0.10[.0]
  176799. * 1.2.10 13 10210 12.so.0.10[.0]
  176800. * 1.2.11beta1-4 13 10211 12.so.0.11[.0]
  176801. * 1.0.19rc1-5 10 10019 10.so.0.19[.0]
  176802. * 1.2.11rc1-5 13 10211 12.so.0.11[.0]
  176803. * 1.0.19 10 10019 10.so.0.19[.0]
  176804. * 1.2.11 13 10211 12.so.0.11[.0]
  176805. * 1.0.20 10 10020 10.so.0.20[.0]
  176806. * 1.2.12 13 10212 12.so.0.12[.0]
  176807. * 1.2.13beta1 13 10213 12.so.0.13[.0]
  176808. * 1.0.21 10 10021 10.so.0.21[.0]
  176809. * 1.2.13 13 10213 12.so.0.13[.0]
  176810. * 1.2.14beta1-2 13 10214 12.so.0.14[.0]
  176811. * 1.0.22rc1 10 10022 10.so.0.22[.0]
  176812. * 1.2.14rc1 13 10214 12.so.0.14[.0]
  176813. * 1.0.22 10 10022 10.so.0.22[.0]
  176814. * 1.2.14 13 10214 12.so.0.14[.0]
  176815. * 1.2.15beta1-6 13 10215 12.so.0.15[.0]
  176816. * 1.0.23rc1-5 10 10023 10.so.0.23[.0]
  176817. * 1.2.15rc1-5 13 10215 12.so.0.15[.0]
  176818. * 1.0.23 10 10023 10.so.0.23[.0]
  176819. * 1.2.15 13 10215 12.so.0.15[.0]
  176820. * 1.2.16beta1-2 13 10216 12.so.0.16[.0]
  176821. * 1.2.16rc1 13 10216 12.so.0.16[.0]
  176822. * 1.0.24 10 10024 10.so.0.24[.0]
  176823. * 1.2.16 13 10216 12.so.0.16[.0]
  176824. * 1.2.17beta1-2 13 10217 12.so.0.17[.0]
  176825. * 1.0.25rc1 10 10025 10.so.0.25[.0]
  176826. * 1.2.17rc1-3 13 10217 12.so.0.17[.0]
  176827. * 1.0.25 10 10025 10.so.0.25[.0]
  176828. * 1.2.17 13 10217 12.so.0.17[.0]
  176829. * 1.0.26 10 10026 10.so.0.26[.0]
  176830. * 1.2.18 13 10218 12.so.0.18[.0]
  176831. * 1.2.19beta1-31 13 10219 12.so.0.19[.0]
  176832. * 1.0.27rc1-6 10 10027 10.so.0.27[.0]
  176833. * 1.2.19rc1-6 13 10219 12.so.0.19[.0]
  176834. * 1.0.27 10 10027 10.so.0.27[.0]
  176835. * 1.2.19 13 10219 12.so.0.19[.0]
  176836. * 1.2.20beta01-04 13 10220 12.so.0.20[.0]
  176837. * 1.0.28rc1-6 10 10028 10.so.0.28[.0]
  176838. * 1.2.20rc1-6 13 10220 12.so.0.20[.0]
  176839. * 1.0.28 10 10028 10.so.0.28[.0]
  176840. * 1.2.20 13 10220 12.so.0.20[.0]
  176841. * 1.2.21beta1-2 13 10221 12.so.0.21[.0]
  176842. * 1.2.21rc1-3 13 10221 12.so.0.21[.0]
  176843. * 1.0.29 10 10029 10.so.0.29[.0]
  176844. * 1.2.21 13 10221 12.so.0.21[.0]
  176845. *
  176846. * Henceforth the source version will match the shared-library major
  176847. * and minor numbers; the shared-library major version number will be
  176848. * used for changes in backward compatibility, as it is intended. The
  176849. * PNG_LIBPNG_VER macro, which is not used within libpng but is available
  176850. * for applications, is an unsigned integer of the form xyyzz corresponding
  176851. * to the source version x.y.z (leading zeros in y and z). Beta versions
  176852. * were given the previous public release number plus a letter, until
  176853. * version 1.0.6j; from then on they were given the upcoming public
  176854. * release number plus "betaNN" or "rcN".
  176855. *
  176856. * Binary incompatibility exists only when applications make direct access
  176857. * to the info_ptr or png_ptr members through png.h, and the compiled
  176858. * application is loaded with a different version of the library.
  176859. *
  176860. * DLLNUM will change each time there are forward or backward changes
  176861. * in binary compatibility (e.g., when a new feature is added).
  176862. *
  176863. * See libpng.txt or libpng.3 for more information. The PNG specification
  176864. * is available as a W3C Recommendation and as an ISO Specification,
  176865. * <http://www.w3.org/TR/2003/REC-PNG-20031110/
  176866. */
  176867. /*
  176868. * COPYRIGHT NOTICE, DISCLAIMER, and LICENSE:
  176869. *
  176870. * If you modify libpng you may insert additional notices immediately following
  176871. * this sentence.
  176872. *
  176873. * libpng versions 1.2.6, August 15, 2004, through 1.2.21, October 4, 2007, are
  176874. * Copyright (c) 2004, 2006-2007 Glenn Randers-Pehrson, and are
  176875. * distributed according to the same disclaimer and license as libpng-1.2.5
  176876. * with the following individual added to the list of Contributing Authors:
  176877. *
  176878. * Cosmin Truta
  176879. *
  176880. * libpng versions 1.0.7, July 1, 2000, through 1.2.5, October 3, 2002, are
  176881. * Copyright (c) 2000-2002 Glenn Randers-Pehrson, and are
  176882. * distributed according to the same disclaimer and license as libpng-1.0.6
  176883. * with the following individuals added to the list of Contributing Authors:
  176884. *
  176885. * Simon-Pierre Cadieux
  176886. * Eric S. Raymond
  176887. * Gilles Vollant
  176888. *
  176889. * and with the following additions to the disclaimer:
  176890. *
  176891. * There is no warranty against interference with your enjoyment of the
  176892. * library or against infringement. There is no warranty that our
  176893. * efforts or the library will fulfill any of your particular purposes
  176894. * or needs. This library is provided with all faults, and the entire
  176895. * risk of satisfactory quality, performance, accuracy, and effort is with
  176896. * the user.
  176897. *
  176898. * libpng versions 0.97, January 1998, through 1.0.6, March 20, 2000, are
  176899. * Copyright (c) 1998, 1999, 2000 Glenn Randers-Pehrson, and are
  176900. * distributed according to the same disclaimer and license as libpng-0.96,
  176901. * with the following individuals added to the list of Contributing Authors:
  176902. *
  176903. * Tom Lane
  176904. * Glenn Randers-Pehrson
  176905. * Willem van Schaik
  176906. *
  176907. * libpng versions 0.89, June 1996, through 0.96, May 1997, are
  176908. * Copyright (c) 1996, 1997 Andreas Dilger
  176909. * Distributed according to the same disclaimer and license as libpng-0.88,
  176910. * with the following individuals added to the list of Contributing Authors:
  176911. *
  176912. * John Bowler
  176913. * Kevin Bracey
  176914. * Sam Bushell
  176915. * Magnus Holmgren
  176916. * Greg Roelofs
  176917. * Tom Tanner
  176918. *
  176919. * libpng versions 0.5, May 1995, through 0.88, January 1996, are
  176920. * Copyright (c) 1995, 1996 Guy Eric Schalnat, Group 42, Inc.
  176921. *
  176922. * For the purposes of this copyright and license, "Contributing Authors"
  176923. * is defined as the following set of individuals:
  176924. *
  176925. * Andreas Dilger
  176926. * Dave Martindale
  176927. * Guy Eric Schalnat
  176928. * Paul Schmidt
  176929. * Tim Wegner
  176930. *
  176931. * The PNG Reference Library is supplied "AS IS". The Contributing Authors
  176932. * and Group 42, Inc. disclaim all warranties, expressed or implied,
  176933. * including, without limitation, the warranties of merchantability and of
  176934. * fitness for any purpose. The Contributing Authors and Group 42, Inc.
  176935. * assume no liability for direct, indirect, incidental, special, exemplary,
  176936. * or consequential damages, which may result from the use of the PNG
  176937. * Reference Library, even if advised of the possibility of such damage.
  176938. *
  176939. * Permission is hereby granted to use, copy, modify, and distribute this
  176940. * source code, or portions hereof, for any purpose, without fee, subject
  176941. * to the following restrictions:
  176942. *
  176943. * 1. The origin of this source code must not be misrepresented.
  176944. *
  176945. * 2. Altered versions must be plainly marked as such and
  176946. * must not be misrepresented as being the original source.
  176947. *
  176948. * 3. This Copyright notice may not be removed or altered from
  176949. * any source or altered source distribution.
  176950. *
  176951. * The Contributing Authors and Group 42, Inc. specifically permit, without
  176952. * fee, and encourage the use of this source code as a component to
  176953. * supporting the PNG file format in commercial products. If you use this
  176954. * source code in a product, acknowledgment is not required but would be
  176955. * appreciated.
  176956. */
  176957. /*
  176958. * A "png_get_copyright" function is available, for convenient use in "about"
  176959. * boxes and the like:
  176960. *
  176961. * printf("%s",png_get_copyright(NULL));
  176962. *
  176963. * Also, the PNG logo (in PNG format, of course) is supplied in the
  176964. * files "pngbar.png" and "pngbar.jpg (88x31) and "pngnow.png" (98x31).
  176965. */
  176966. /*
  176967. * Libpng is OSI Certified Open Source Software. OSI Certified is a
  176968. * certification mark of the Open Source Initiative.
  176969. */
  176970. /*
  176971. * The contributing authors would like to thank all those who helped
  176972. * with testing, bug fixes, and patience. This wouldn't have been
  176973. * possible without all of you.
  176974. *
  176975. * Thanks to Frank J. T. Wojcik for helping with the documentation.
  176976. */
  176977. /*
  176978. * Y2K compliance in libpng:
  176979. * =========================
  176980. *
  176981. * October 4, 2007
  176982. *
  176983. * Since the PNG Development group is an ad-hoc body, we can't make
  176984. * an official declaration.
  176985. *
  176986. * This is your unofficial assurance that libpng from version 0.71 and
  176987. * upward through 1.2.21 are Y2K compliant. It is my belief that earlier
  176988. * versions were also Y2K compliant.
  176989. *
  176990. * Libpng only has three year fields. One is a 2-byte unsigned integer
  176991. * that will hold years up to 65535. The other two hold the date in text
  176992. * format, and will hold years up to 9999.
  176993. *
  176994. * The integer is
  176995. * "png_uint_16 year" in png_time_struct.
  176996. *
  176997. * The strings are
  176998. * "png_charp time_buffer" in png_struct and
  176999. * "near_time_buffer", which is a local character string in png.c.
  177000. *
  177001. * There are seven time-related functions:
  177002. * png.c: png_convert_to_rfc_1123() in png.c
  177003. * (formerly png_convert_to_rfc_1152() in error)
  177004. * png_convert_from_struct_tm() in pngwrite.c, called in pngwrite.c
  177005. * png_convert_from_time_t() in pngwrite.c
  177006. * png_get_tIME() in pngget.c
  177007. * png_handle_tIME() in pngrutil.c, called in pngread.c
  177008. * png_set_tIME() in pngset.c
  177009. * png_write_tIME() in pngwutil.c, called in pngwrite.c
  177010. *
  177011. * All handle dates properly in a Y2K environment. The
  177012. * png_convert_from_time_t() function calls gmtime() to convert from system
  177013. * clock time, which returns (year - 1900), which we properly convert to
  177014. * the full 4-digit year. There is a possibility that applications using
  177015. * libpng are not passing 4-digit years into the png_convert_to_rfc_1123()
  177016. * function, or that they are incorrectly passing only a 2-digit year
  177017. * instead of "year - 1900" into the png_convert_from_struct_tm() function,
  177018. * but this is not under our control. The libpng documentation has always
  177019. * stated that it works with 4-digit years, and the APIs have been
  177020. * documented as such.
  177021. *
  177022. * The tIME chunk itself is also Y2K compliant. It uses a 2-byte unsigned
  177023. * integer to hold the year, and can hold years as large as 65535.
  177024. *
  177025. * zlib, upon which libpng depends, is also Y2K compliant. It contains
  177026. * no date-related code.
  177027. *
  177028. * Glenn Randers-Pehrson
  177029. * libpng maintainer
  177030. * PNG Development Group
  177031. */
  177032. #ifndef PNG_H
  177033. #define PNG_H
  177034. /* This is not the place to learn how to use libpng. The file libpng.txt
  177035. * describes how to use libpng, and the file example.c summarizes it
  177036. * with some code on which to build. This file is useful for looking
  177037. * at the actual function definitions and structure components.
  177038. */
  177039. /* Version information for png.h - this should match the version in png.c */
  177040. #define PNG_LIBPNG_VER_STRING "1.2.21"
  177041. #define PNG_HEADER_VERSION_STRING \
  177042. " libpng version 1.2.21 - October 4, 2007\n"
  177043. #define PNG_LIBPNG_VER_SONUM 0
  177044. #define PNG_LIBPNG_VER_DLLNUM 13
  177045. /* These should match the first 3 components of PNG_LIBPNG_VER_STRING: */
  177046. #define PNG_LIBPNG_VER_MAJOR 1
  177047. #define PNG_LIBPNG_VER_MINOR 2
  177048. #define PNG_LIBPNG_VER_RELEASE 21
  177049. /* This should match the numeric part of the final component of
  177050. * PNG_LIBPNG_VER_STRING, omitting any leading zero: */
  177051. #define PNG_LIBPNG_VER_BUILD 0
  177052. /* Release Status */
  177053. #define PNG_LIBPNG_BUILD_ALPHA 1
  177054. #define PNG_LIBPNG_BUILD_BETA 2
  177055. #define PNG_LIBPNG_BUILD_RC 3
  177056. #define PNG_LIBPNG_BUILD_STABLE 4
  177057. #define PNG_LIBPNG_BUILD_RELEASE_STATUS_MASK 7
  177058. /* Release-Specific Flags */
  177059. #define PNG_LIBPNG_BUILD_PATCH 8 /* Can be OR'ed with
  177060. PNG_LIBPNG_BUILD_STABLE only */
  177061. #define PNG_LIBPNG_BUILD_PRIVATE 16 /* Cannot be OR'ed with
  177062. PNG_LIBPNG_BUILD_SPECIAL */
  177063. #define PNG_LIBPNG_BUILD_SPECIAL 32 /* Cannot be OR'ed with
  177064. PNG_LIBPNG_BUILD_PRIVATE */
  177065. #define PNG_LIBPNG_BUILD_BASE_TYPE PNG_LIBPNG_BUILD_STABLE
  177066. /* Careful here. At one time, Guy wanted to use 082, but that would be octal.
  177067. * We must not include leading zeros.
  177068. * Versions 0.7 through 1.0.0 were in the range 0 to 100 here (only
  177069. * version 1.0.0 was mis-numbered 100 instead of 10000). From
  177070. * version 1.0.1 it's xxyyzz, where x=major, y=minor, z=release */
  177071. #define PNG_LIBPNG_VER 10221 /* 1.2.21 */
  177072. #ifndef PNG_VERSION_INFO_ONLY
  177073. /* include the compression library's header */
  177074. #endif
  177075. /* include all user configurable info, including optional assembler routines */
  177076. /*** Start of inlined file: pngconf.h ***/
  177077. /* pngconf.h - machine configurable file for libpng
  177078. *
  177079. * libpng version 1.2.21 - October 4, 2007
  177080. * For conditions of distribution and use, see copyright notice in png.h
  177081. * Copyright (c) 1998-2007 Glenn Randers-Pehrson
  177082. * (Version 0.96 Copyright (c) 1996, 1997 Andreas Dilger)
  177083. * (Version 0.88 Copyright (c) 1995, 1996 Guy Eric Schalnat, Group 42, Inc.)
  177084. */
  177085. /* Any machine specific code is near the front of this file, so if you
  177086. * are configuring libpng for a machine, you may want to read the section
  177087. * starting here down to where it starts to typedef png_color, png_text,
  177088. * and png_info.
  177089. */
  177090. #ifndef PNGCONF_H
  177091. #define PNGCONF_H
  177092. #define PNG_1_2_X
  177093. // These are some Juce config settings that should remove any unnecessary code bloat..
  177094. #define PNG_NO_STDIO 1
  177095. #define PNG_DEBUG 0
  177096. #define PNG_NO_WARNINGS 1
  177097. #define PNG_NO_ERROR_TEXT 1
  177098. #define PNG_NO_ERROR_NUMBERS 1
  177099. #define PNG_NO_USER_MEM 1
  177100. #define PNG_NO_READ_iCCP 1
  177101. #define PNG_NO_READ_UNKNOWN_CHUNKS 1
  177102. #define PNG_NO_READ_USER_CHUNKS 1
  177103. #define PNG_NO_READ_iTXt 1
  177104. #define PNG_NO_READ_sCAL 1
  177105. #define PNG_NO_READ_sPLT 1
  177106. #define png_error(a, b) png_err(a)
  177107. #define png_warning(a, b)
  177108. #define png_chunk_error(a, b) png_err(a)
  177109. #define png_chunk_warning(a, b)
  177110. /*
  177111. * PNG_USER_CONFIG has to be defined on the compiler command line. This
  177112. * includes the resource compiler for Windows DLL configurations.
  177113. */
  177114. #ifdef PNG_USER_CONFIG
  177115. # ifndef PNG_USER_PRIVATEBUILD
  177116. # define PNG_USER_PRIVATEBUILD
  177117. # endif
  177118. #include "pngusr.h"
  177119. #endif
  177120. /* PNG_CONFIGURE_LIBPNG is set by the "configure" script. */
  177121. #ifdef PNG_CONFIGURE_LIBPNG
  177122. #ifdef HAVE_CONFIG_H
  177123. #include "config.h"
  177124. #endif
  177125. #endif
  177126. /*
  177127. * Added at libpng-1.2.8
  177128. *
  177129. * If you create a private DLL you need to define in "pngusr.h" the followings:
  177130. * #define PNG_USER_PRIVATEBUILD <Describes by whom and why this version of
  177131. * the DLL was built>
  177132. * e.g. #define PNG_USER_PRIVATEBUILD "Build by MyCompany for xyz reasons."
  177133. * #define PNG_USER_DLLFNAME_POSTFIX <two-letter postfix that serve to
  177134. * distinguish your DLL from those of the official release. These
  177135. * correspond to the trailing letters that come after the version
  177136. * number and must match your private DLL name>
  177137. * e.g. // private DLL "libpng13gx.dll"
  177138. * #define PNG_USER_DLLFNAME_POSTFIX "gx"
  177139. *
  177140. * The following macros are also at your disposal if you want to complete the
  177141. * DLL VERSIONINFO structure.
  177142. * - PNG_USER_VERSIONINFO_COMMENTS
  177143. * - PNG_USER_VERSIONINFO_COMPANYNAME
  177144. * - PNG_USER_VERSIONINFO_LEGALTRADEMARKS
  177145. */
  177146. #ifdef __STDC__
  177147. #ifdef SPECIALBUILD
  177148. # pragma message("PNG_LIBPNG_SPECIALBUILD (and deprecated SPECIALBUILD)\
  177149. are now LIBPNG reserved macros. Use PNG_USER_PRIVATEBUILD instead.")
  177150. #endif
  177151. #ifdef PRIVATEBUILD
  177152. # pragma message("PRIVATEBUILD is deprecated.\
  177153. Use PNG_USER_PRIVATEBUILD instead.")
  177154. # define PNG_USER_PRIVATEBUILD PRIVATEBUILD
  177155. #endif
  177156. #endif /* __STDC__ */
  177157. #ifndef PNG_VERSION_INFO_ONLY
  177158. /* End of material added to libpng-1.2.8 */
  177159. /* Added at libpng-1.2.19, removed at libpng-1.2.20 because it caused trouble
  177160. Restored at libpng-1.2.21 */
  177161. # define PNG_WARN_UNINITIALIZED_ROW 1
  177162. /* End of material added at libpng-1.2.19/1.2.21 */
  177163. /* This is the size of the compression buffer, and thus the size of
  177164. * an IDAT chunk. Make this whatever size you feel is best for your
  177165. * machine. One of these will be allocated per png_struct. When this
  177166. * is full, it writes the data to the disk, and does some other
  177167. * calculations. Making this an extremely small size will slow
  177168. * the library down, but you may want to experiment to determine
  177169. * where it becomes significant, if you are concerned with memory
  177170. * usage. Note that zlib allocates at least 32Kb also. For readers,
  177171. * this describes the size of the buffer available to read the data in.
  177172. * Unless this gets smaller than the size of a row (compressed),
  177173. * it should not make much difference how big this is.
  177174. */
  177175. #ifndef PNG_ZBUF_SIZE
  177176. # define PNG_ZBUF_SIZE 8192
  177177. #endif
  177178. /* Enable if you want a write-only libpng */
  177179. #ifndef PNG_NO_READ_SUPPORTED
  177180. # define PNG_READ_SUPPORTED
  177181. #endif
  177182. /* Enable if you want a read-only libpng */
  177183. #ifndef PNG_NO_WRITE_SUPPORTED
  177184. # define PNG_WRITE_SUPPORTED
  177185. #endif
  177186. /* Enabled by default in 1.2.0. You can disable this if you don't need to
  177187. support PNGs that are embedded in MNG datastreams */
  177188. #if !defined(PNG_1_0_X) && !defined(PNG_NO_MNG_FEATURES)
  177189. # ifndef PNG_MNG_FEATURES_SUPPORTED
  177190. # define PNG_MNG_FEATURES_SUPPORTED
  177191. # endif
  177192. #endif
  177193. #ifndef PNG_NO_FLOATING_POINT_SUPPORTED
  177194. # ifndef PNG_FLOATING_POINT_SUPPORTED
  177195. # define PNG_FLOATING_POINT_SUPPORTED
  177196. # endif
  177197. #endif
  177198. /* If you are running on a machine where you cannot allocate more
  177199. * than 64K of memory at once, uncomment this. While libpng will not
  177200. * normally need that much memory in a chunk (unless you load up a very
  177201. * large file), zlib needs to know how big of a chunk it can use, and
  177202. * libpng thus makes sure to check any memory allocation to verify it
  177203. * will fit into memory.
  177204. #define PNG_MAX_MALLOC_64K
  177205. */
  177206. #if defined(MAXSEG_64K) && !defined(PNG_MAX_MALLOC_64K)
  177207. # define PNG_MAX_MALLOC_64K
  177208. #endif
  177209. /* Special munging to support doing things the 'cygwin' way:
  177210. * 'Normal' png-on-win32 defines/defaults:
  177211. * PNG_BUILD_DLL -- building dll
  177212. * PNG_USE_DLL -- building an application, linking to dll
  177213. * (no define) -- building static library, or building an
  177214. * application and linking to the static lib
  177215. * 'Cygwin' defines/defaults:
  177216. * PNG_BUILD_DLL -- (ignored) building the dll
  177217. * (no define) -- (ignored) building an application, linking to the dll
  177218. * PNG_STATIC -- (ignored) building the static lib, or building an
  177219. * application that links to the static lib.
  177220. * ALL_STATIC -- (ignored) building various static libs, or building an
  177221. * application that links to the static libs.
  177222. * Thus,
  177223. * a cygwin user should define either PNG_BUILD_DLL or PNG_STATIC, and
  177224. * this bit of #ifdefs will define the 'correct' config variables based on
  177225. * that. If a cygwin user *wants* to define 'PNG_USE_DLL' that's okay, but
  177226. * unnecessary.
  177227. *
  177228. * Also, the precedence order is:
  177229. * ALL_STATIC (since we can't #undef something outside our namespace)
  177230. * PNG_BUILD_DLL
  177231. * PNG_STATIC
  177232. * (nothing) == PNG_USE_DLL
  177233. *
  177234. * CYGWIN (2002-01-20): The preceding is now obsolete. With the advent
  177235. * of auto-import in binutils, we no longer need to worry about
  177236. * __declspec(dllexport) / __declspec(dllimport) and friends. Therefore,
  177237. * we don't need to worry about PNG_STATIC or ALL_STATIC when it comes
  177238. * to __declspec() stuff. However, we DO need to worry about
  177239. * PNG_BUILD_DLL and PNG_STATIC because those change some defaults
  177240. * such as CONSOLE_IO and whether GLOBAL_ARRAYS are allowed.
  177241. */
  177242. #if defined(__CYGWIN__)
  177243. # if defined(ALL_STATIC)
  177244. # if defined(PNG_BUILD_DLL)
  177245. # undef PNG_BUILD_DLL
  177246. # endif
  177247. # if defined(PNG_USE_DLL)
  177248. # undef PNG_USE_DLL
  177249. # endif
  177250. # if defined(PNG_DLL)
  177251. # undef PNG_DLL
  177252. # endif
  177253. # if !defined(PNG_STATIC)
  177254. # define PNG_STATIC
  177255. # endif
  177256. # else
  177257. # if defined (PNG_BUILD_DLL)
  177258. # if defined(PNG_STATIC)
  177259. # undef PNG_STATIC
  177260. # endif
  177261. # if defined(PNG_USE_DLL)
  177262. # undef PNG_USE_DLL
  177263. # endif
  177264. # if !defined(PNG_DLL)
  177265. # define PNG_DLL
  177266. # endif
  177267. # else
  177268. # if defined(PNG_STATIC)
  177269. # if defined(PNG_USE_DLL)
  177270. # undef PNG_USE_DLL
  177271. # endif
  177272. # if defined(PNG_DLL)
  177273. # undef PNG_DLL
  177274. # endif
  177275. # else
  177276. # if !defined(PNG_USE_DLL)
  177277. # define PNG_USE_DLL
  177278. # endif
  177279. # if !defined(PNG_DLL)
  177280. # define PNG_DLL
  177281. # endif
  177282. # endif
  177283. # endif
  177284. # endif
  177285. #endif
  177286. /* This protects us against compilers that run on a windowing system
  177287. * and thus don't have or would rather us not use the stdio types:
  177288. * stdin, stdout, and stderr. The only one currently used is stderr
  177289. * in png_error() and png_warning(). #defining PNG_NO_CONSOLE_IO will
  177290. * prevent these from being compiled and used. #defining PNG_NO_STDIO
  177291. * will also prevent these, plus will prevent the entire set of stdio
  177292. * macros and functions (FILE *, printf, etc.) from being compiled and used,
  177293. * unless (PNG_DEBUG > 0) has been #defined.
  177294. *
  177295. * #define PNG_NO_CONSOLE_IO
  177296. * #define PNG_NO_STDIO
  177297. */
  177298. #if defined(_WIN32_WCE)
  177299. # include <windows.h>
  177300. /* Console I/O functions are not supported on WindowsCE */
  177301. # define PNG_NO_CONSOLE_IO
  177302. # ifdef PNG_DEBUG
  177303. # undef PNG_DEBUG
  177304. # endif
  177305. #endif
  177306. #ifdef PNG_BUILD_DLL
  177307. # ifndef PNG_CONSOLE_IO_SUPPORTED
  177308. # ifndef PNG_NO_CONSOLE_IO
  177309. # define PNG_NO_CONSOLE_IO
  177310. # endif
  177311. # endif
  177312. #endif
  177313. # ifdef PNG_NO_STDIO
  177314. # ifndef PNG_NO_CONSOLE_IO
  177315. # define PNG_NO_CONSOLE_IO
  177316. # endif
  177317. # ifdef PNG_DEBUG
  177318. # if (PNG_DEBUG > 0)
  177319. # include <stdio.h>
  177320. # endif
  177321. # endif
  177322. # else
  177323. # if !defined(_WIN32_WCE)
  177324. /* "stdio.h" functions are not supported on WindowsCE */
  177325. # include <stdio.h>
  177326. # endif
  177327. # endif
  177328. /* This macro protects us against machines that don't have function
  177329. * prototypes (ie K&R style headers). If your compiler does not handle
  177330. * function prototypes, define this macro and use the included ansi2knr.
  177331. * I've always been able to use _NO_PROTO as the indicator, but you may
  177332. * need to drag the empty declaration out in front of here, or change the
  177333. * ifdef to suit your own needs.
  177334. */
  177335. #ifndef PNGARG
  177336. #ifdef OF /* zlib prototype munger */
  177337. # define PNGARG(arglist) OF(arglist)
  177338. #else
  177339. #ifdef _NO_PROTO
  177340. # define PNGARG(arglist) ()
  177341. # ifndef PNG_TYPECAST_NULL
  177342. # define PNG_TYPECAST_NULL
  177343. # endif
  177344. #else
  177345. # define PNGARG(arglist) arglist
  177346. #endif /* _NO_PROTO */
  177347. #endif /* OF */
  177348. #endif /* PNGARG */
  177349. /* Try to determine if we are compiling on a Mac. Note that testing for
  177350. * just __MWERKS__ is not good enough, because the Codewarrior is now used
  177351. * on non-Mac platforms.
  177352. */
  177353. #ifndef MACOS
  177354. # if (defined(__MWERKS__) && defined(macintosh)) || defined(applec) || \
  177355. defined(THINK_C) || defined(__SC__) || defined(TARGET_OS_MAC)
  177356. # define MACOS
  177357. # endif
  177358. #endif
  177359. /* enough people need this for various reasons to include it here */
  177360. #if !defined(MACOS) && !defined(RISCOS) && !defined(_WIN32_WCE)
  177361. # include <sys/types.h>
  177362. #endif
  177363. #if !defined(PNG_SETJMP_NOT_SUPPORTED) && !defined(PNG_NO_SETJMP_SUPPORTED)
  177364. # define PNG_SETJMP_SUPPORTED
  177365. #endif
  177366. #ifdef PNG_SETJMP_SUPPORTED
  177367. /* This is an attempt to force a single setjmp behaviour on Linux. If
  177368. * the X config stuff didn't define _BSD_SOURCE we wouldn't need this.
  177369. */
  177370. # ifdef __linux__
  177371. # ifdef _BSD_SOURCE
  177372. # define PNG_SAVE_BSD_SOURCE
  177373. # undef _BSD_SOURCE
  177374. # endif
  177375. # ifdef _SETJMP_H
  177376. /* If you encounter a compiler error here, see the explanation
  177377. * near the end of INSTALL.
  177378. */
  177379. __png.h__ already includes setjmp.h;
  177380. __dont__ include it again.;
  177381. # endif
  177382. # endif /* __linux__ */
  177383. /* include setjmp.h for error handling */
  177384. # include <setjmp.h>
  177385. # ifdef __linux__
  177386. # ifdef PNG_SAVE_BSD_SOURCE
  177387. # define _BSD_SOURCE
  177388. # undef PNG_SAVE_BSD_SOURCE
  177389. # endif
  177390. # endif /* __linux__ */
  177391. #endif /* PNG_SETJMP_SUPPORTED */
  177392. #ifdef BSD
  177393. #if ! JUCE_MAC
  177394. # include <strings.h>
  177395. #endif
  177396. #else
  177397. # include <string.h>
  177398. #endif
  177399. /* Other defines for things like memory and the like can go here. */
  177400. #ifdef PNG_INTERNAL
  177401. #include <stdlib.h>
  177402. /* The functions exported by PNG_EXTERN are PNG_INTERNAL functions, which
  177403. * aren't usually used outside the library (as far as I know), so it is
  177404. * debatable if they should be exported at all. In the future, when it is
  177405. * possible to have run-time registry of chunk-handling functions, some of
  177406. * these will be made available again.
  177407. #define PNG_EXTERN extern
  177408. */
  177409. #define PNG_EXTERN
  177410. /* Other defines specific to compilers can go here. Try to keep
  177411. * them inside an appropriate ifdef/endif pair for portability.
  177412. */
  177413. #if defined(PNG_FLOATING_POINT_SUPPORTED)
  177414. # if defined(MACOS)
  177415. /* We need to check that <math.h> hasn't already been included earlier
  177416. * as it seems it doesn't agree with <fp.h>, yet we should really use
  177417. * <fp.h> if possible.
  177418. */
  177419. # if !defined(__MATH_H__) && !defined(__MATH_H) && !defined(__cmath__)
  177420. # include <fp.h>
  177421. # endif
  177422. # else
  177423. # include <math.h>
  177424. # endif
  177425. # if defined(_AMIGA) && defined(__SASC) && defined(_M68881)
  177426. /* Amiga SAS/C: We must include builtin FPU functions when compiling using
  177427. * MATH=68881
  177428. */
  177429. # include <m68881.h>
  177430. # endif
  177431. #endif
  177432. /* Codewarrior on NT has linking problems without this. */
  177433. #if (defined(__MWERKS__) && defined(WIN32)) || defined(__STDC__)
  177434. # define PNG_ALWAYS_EXTERN
  177435. #endif
  177436. /* This provides the non-ANSI (far) memory allocation routines. */
  177437. #if defined(__TURBOC__) && defined(__MSDOS__)
  177438. # include <mem.h>
  177439. # include <alloc.h>
  177440. #endif
  177441. /* I have no idea why is this necessary... */
  177442. #if defined(_MSC_VER) && (defined(WIN32) || defined(_Windows) || \
  177443. defined(_WINDOWS) || defined(_WIN32) || defined(__WIN32__))
  177444. # include <malloc.h>
  177445. #endif
  177446. /* This controls how fine the dithering gets. As this allocates
  177447. * a largish chunk of memory (32K), those who are not as concerned
  177448. * with dithering quality can decrease some or all of these.
  177449. */
  177450. #ifndef PNG_DITHER_RED_BITS
  177451. # define PNG_DITHER_RED_BITS 5
  177452. #endif
  177453. #ifndef PNG_DITHER_GREEN_BITS
  177454. # define PNG_DITHER_GREEN_BITS 5
  177455. #endif
  177456. #ifndef PNG_DITHER_BLUE_BITS
  177457. # define PNG_DITHER_BLUE_BITS 5
  177458. #endif
  177459. /* This controls how fine the gamma correction becomes when you
  177460. * are only interested in 8 bits anyway. Increasing this value
  177461. * results in more memory being used, and more pow() functions
  177462. * being called to fill in the gamma tables. Don't set this value
  177463. * less then 8, and even that may not work (I haven't tested it).
  177464. */
  177465. #ifndef PNG_MAX_GAMMA_8
  177466. # define PNG_MAX_GAMMA_8 11
  177467. #endif
  177468. /* This controls how much a difference in gamma we can tolerate before
  177469. * we actually start doing gamma conversion.
  177470. */
  177471. #ifndef PNG_GAMMA_THRESHOLD
  177472. # define PNG_GAMMA_THRESHOLD 0.05
  177473. #endif
  177474. #endif /* PNG_INTERNAL */
  177475. /* The following uses const char * instead of char * for error
  177476. * and warning message functions, so some compilers won't complain.
  177477. * If you do not want to use const, define PNG_NO_CONST here.
  177478. */
  177479. #ifndef PNG_NO_CONST
  177480. # define PNG_CONST const
  177481. #else
  177482. # define PNG_CONST
  177483. #endif
  177484. /* The following defines give you the ability to remove code from the
  177485. * library that you will not be using. I wish I could figure out how to
  177486. * automate this, but I can't do that without making it seriously hard
  177487. * on the users. So if you are not using an ability, change the #define
  177488. * to and #undef, and that part of the library will not be compiled. If
  177489. * your linker can't find a function, you may want to make sure the
  177490. * ability is defined here. Some of these depend upon some others being
  177491. * defined. I haven't figured out all the interactions here, so you may
  177492. * have to experiment awhile to get everything to compile. If you are
  177493. * creating or using a shared library, you probably shouldn't touch this,
  177494. * as it will affect the size of the structures, and this will cause bad
  177495. * things to happen if the library and/or application ever change.
  177496. */
  177497. /* Any features you will not be using can be undef'ed here */
  177498. /* GR-P, 0.96a: Set "*TRANSFORMS_SUPPORTED as default but allow user
  177499. * to turn it off with "*TRANSFORMS_NOT_SUPPORTED" or *PNG_NO_*_TRANSFORMS
  177500. * on the compile line, then pick and choose which ones to define without
  177501. * having to edit this file. It is safe to use the *TRANSFORMS_NOT_SUPPORTED
  177502. * if you only want to have a png-compliant reader/writer but don't need
  177503. * any of the extra transformations. This saves about 80 kbytes in a
  177504. * typical installation of the library. (PNG_NO_* form added in version
  177505. * 1.0.1c, for consistency)
  177506. */
  177507. /* The size of the png_text structure changed in libpng-1.0.6 when
  177508. * iTXt support was added. iTXt support was turned off by default through
  177509. * libpng-1.2.x, to support old apps that malloc the png_text structure
  177510. * instead of calling png_set_text() and letting libpng malloc it. It
  177511. * was turned on by default in libpng-1.3.0.
  177512. */
  177513. #if defined(PNG_1_0_X) || defined (PNG_1_2_X)
  177514. # ifndef PNG_NO_iTXt_SUPPORTED
  177515. # define PNG_NO_iTXt_SUPPORTED
  177516. # endif
  177517. # ifndef PNG_NO_READ_iTXt
  177518. # define PNG_NO_READ_iTXt
  177519. # endif
  177520. # ifndef PNG_NO_WRITE_iTXt
  177521. # define PNG_NO_WRITE_iTXt
  177522. # endif
  177523. #endif
  177524. #if !defined(PNG_NO_iTXt_SUPPORTED)
  177525. # if !defined(PNG_READ_iTXt_SUPPORTED) && !defined(PNG_NO_READ_iTXt)
  177526. # define PNG_READ_iTXt
  177527. # endif
  177528. # if !defined(PNG_WRITE_iTXt_SUPPORTED) && !defined(PNG_NO_WRITE_iTXt)
  177529. # define PNG_WRITE_iTXt
  177530. # endif
  177531. #endif
  177532. /* The following support, added after version 1.0.0, can be turned off here en
  177533. * masse by defining PNG_LEGACY_SUPPORTED in case you need binary compatibility
  177534. * with old applications that require the length of png_struct and png_info
  177535. * to remain unchanged.
  177536. */
  177537. #ifdef PNG_LEGACY_SUPPORTED
  177538. # define PNG_NO_FREE_ME
  177539. # define PNG_NO_READ_UNKNOWN_CHUNKS
  177540. # define PNG_NO_WRITE_UNKNOWN_CHUNKS
  177541. # define PNG_NO_READ_USER_CHUNKS
  177542. # define PNG_NO_READ_iCCP
  177543. # define PNG_NO_WRITE_iCCP
  177544. # define PNG_NO_READ_iTXt
  177545. # define PNG_NO_WRITE_iTXt
  177546. # define PNG_NO_READ_sCAL
  177547. # define PNG_NO_WRITE_sCAL
  177548. # define PNG_NO_READ_sPLT
  177549. # define PNG_NO_WRITE_sPLT
  177550. # define PNG_NO_INFO_IMAGE
  177551. # define PNG_NO_READ_RGB_TO_GRAY
  177552. # define PNG_NO_READ_USER_TRANSFORM
  177553. # define PNG_NO_WRITE_USER_TRANSFORM
  177554. # define PNG_NO_USER_MEM
  177555. # define PNG_NO_READ_EMPTY_PLTE
  177556. # define PNG_NO_MNG_FEATURES
  177557. # define PNG_NO_FIXED_POINT_SUPPORTED
  177558. #endif
  177559. /* Ignore attempt to turn off both floating and fixed point support */
  177560. #if !defined(PNG_FLOATING_POINT_SUPPORTED) || \
  177561. !defined(PNG_NO_FIXED_POINT_SUPPORTED)
  177562. # define PNG_FIXED_POINT_SUPPORTED
  177563. #endif
  177564. #ifndef PNG_NO_FREE_ME
  177565. # define PNG_FREE_ME_SUPPORTED
  177566. #endif
  177567. #if defined(PNG_READ_SUPPORTED)
  177568. #if !defined(PNG_READ_TRANSFORMS_NOT_SUPPORTED) && \
  177569. !defined(PNG_NO_READ_TRANSFORMS)
  177570. # define PNG_READ_TRANSFORMS_SUPPORTED
  177571. #endif
  177572. #ifdef PNG_READ_TRANSFORMS_SUPPORTED
  177573. # ifndef PNG_NO_READ_EXPAND
  177574. # define PNG_READ_EXPAND_SUPPORTED
  177575. # endif
  177576. # ifndef PNG_NO_READ_SHIFT
  177577. # define PNG_READ_SHIFT_SUPPORTED
  177578. # endif
  177579. # ifndef PNG_NO_READ_PACK
  177580. # define PNG_READ_PACK_SUPPORTED
  177581. # endif
  177582. # ifndef PNG_NO_READ_BGR
  177583. # define PNG_READ_BGR_SUPPORTED
  177584. # endif
  177585. # ifndef PNG_NO_READ_SWAP
  177586. # define PNG_READ_SWAP_SUPPORTED
  177587. # endif
  177588. # ifndef PNG_NO_READ_PACKSWAP
  177589. # define PNG_READ_PACKSWAP_SUPPORTED
  177590. # endif
  177591. # ifndef PNG_NO_READ_INVERT
  177592. # define PNG_READ_INVERT_SUPPORTED
  177593. # endif
  177594. # ifndef PNG_NO_READ_DITHER
  177595. # define PNG_READ_DITHER_SUPPORTED
  177596. # endif
  177597. # ifndef PNG_NO_READ_BACKGROUND
  177598. # define PNG_READ_BACKGROUND_SUPPORTED
  177599. # endif
  177600. # ifndef PNG_NO_READ_16_TO_8
  177601. # define PNG_READ_16_TO_8_SUPPORTED
  177602. # endif
  177603. # ifndef PNG_NO_READ_FILLER
  177604. # define PNG_READ_FILLER_SUPPORTED
  177605. # endif
  177606. # ifndef PNG_NO_READ_GAMMA
  177607. # define PNG_READ_GAMMA_SUPPORTED
  177608. # endif
  177609. # ifndef PNG_NO_READ_GRAY_TO_RGB
  177610. # define PNG_READ_GRAY_TO_RGB_SUPPORTED
  177611. # endif
  177612. # ifndef PNG_NO_READ_SWAP_ALPHA
  177613. # define PNG_READ_SWAP_ALPHA_SUPPORTED
  177614. # endif
  177615. # ifndef PNG_NO_READ_INVERT_ALPHA
  177616. # define PNG_READ_INVERT_ALPHA_SUPPORTED
  177617. # endif
  177618. # ifndef PNG_NO_READ_STRIP_ALPHA
  177619. # define PNG_READ_STRIP_ALPHA_SUPPORTED
  177620. # endif
  177621. # ifndef PNG_NO_READ_USER_TRANSFORM
  177622. # define PNG_READ_USER_TRANSFORM_SUPPORTED
  177623. # endif
  177624. # ifndef PNG_NO_READ_RGB_TO_GRAY
  177625. # define PNG_READ_RGB_TO_GRAY_SUPPORTED
  177626. # endif
  177627. #endif /* PNG_READ_TRANSFORMS_SUPPORTED */
  177628. #if !defined(PNG_NO_PROGRESSIVE_READ) && \
  177629. !defined(PNG_PROGRESSIVE_READ_SUPPORTED) /* if you don't do progressive */
  177630. # define PNG_PROGRESSIVE_READ_SUPPORTED /* reading. This is not talking */
  177631. #endif /* about interlacing capability! You'll */
  177632. /* still have interlacing unless you change the following line: */
  177633. #define PNG_READ_INTERLACING_SUPPORTED /* required in PNG-compliant decoders */
  177634. #ifndef PNG_NO_READ_COMPOSITE_NODIV
  177635. # ifndef PNG_NO_READ_COMPOSITED_NODIV /* libpng-1.0.x misspelling */
  177636. # define PNG_READ_COMPOSITE_NODIV_SUPPORTED /* well tested on Intel, SGI */
  177637. # endif
  177638. #endif
  177639. #if defined(PNG_1_0_X) || defined (PNG_1_2_X)
  177640. /* Deprecated, will be removed from version 2.0.0.
  177641. Use PNG_MNG_FEATURES_SUPPORTED instead. */
  177642. #ifndef PNG_NO_READ_EMPTY_PLTE
  177643. # define PNG_READ_EMPTY_PLTE_SUPPORTED
  177644. #endif
  177645. #endif
  177646. #endif /* PNG_READ_SUPPORTED */
  177647. #if defined(PNG_WRITE_SUPPORTED)
  177648. # if !defined(PNG_WRITE_TRANSFORMS_NOT_SUPPORTED) && \
  177649. !defined(PNG_NO_WRITE_TRANSFORMS)
  177650. # define PNG_WRITE_TRANSFORMS_SUPPORTED
  177651. #endif
  177652. #ifdef PNG_WRITE_TRANSFORMS_SUPPORTED
  177653. # ifndef PNG_NO_WRITE_SHIFT
  177654. # define PNG_WRITE_SHIFT_SUPPORTED
  177655. # endif
  177656. # ifndef PNG_NO_WRITE_PACK
  177657. # define PNG_WRITE_PACK_SUPPORTED
  177658. # endif
  177659. # ifndef PNG_NO_WRITE_BGR
  177660. # define PNG_WRITE_BGR_SUPPORTED
  177661. # endif
  177662. # ifndef PNG_NO_WRITE_SWAP
  177663. # define PNG_WRITE_SWAP_SUPPORTED
  177664. # endif
  177665. # ifndef PNG_NO_WRITE_PACKSWAP
  177666. # define PNG_WRITE_PACKSWAP_SUPPORTED
  177667. # endif
  177668. # ifndef PNG_NO_WRITE_INVERT
  177669. # define PNG_WRITE_INVERT_SUPPORTED
  177670. # endif
  177671. # ifndef PNG_NO_WRITE_FILLER
  177672. # define PNG_WRITE_FILLER_SUPPORTED /* same as WRITE_STRIP_ALPHA */
  177673. # endif
  177674. # ifndef PNG_NO_WRITE_SWAP_ALPHA
  177675. # define PNG_WRITE_SWAP_ALPHA_SUPPORTED
  177676. # endif
  177677. # ifndef PNG_NO_WRITE_INVERT_ALPHA
  177678. # define PNG_WRITE_INVERT_ALPHA_SUPPORTED
  177679. # endif
  177680. # ifndef PNG_NO_WRITE_USER_TRANSFORM
  177681. # define PNG_WRITE_USER_TRANSFORM_SUPPORTED
  177682. # endif
  177683. #endif /* PNG_WRITE_TRANSFORMS_SUPPORTED */
  177684. #if !defined(PNG_NO_WRITE_INTERLACING_SUPPORTED) && \
  177685. !defined(PNG_WRITE_INTERLACING_SUPPORTED)
  177686. #define PNG_WRITE_INTERLACING_SUPPORTED /* not required for PNG-compliant
  177687. encoders, but can cause trouble
  177688. if left undefined */
  177689. #endif
  177690. #if !defined(PNG_NO_WRITE_WEIGHTED_FILTER) && \
  177691. !defined(PNG_WRITE_WEIGHTED_FILTER) && \
  177692. defined(PNG_FLOATING_POINT_SUPPORTED)
  177693. # define PNG_WRITE_WEIGHTED_FILTER_SUPPORTED
  177694. #endif
  177695. #ifndef PNG_NO_WRITE_FLUSH
  177696. # define PNG_WRITE_FLUSH_SUPPORTED
  177697. #endif
  177698. #if defined(PNG_1_0_X) || defined (PNG_1_2_X)
  177699. /* Deprecated, see PNG_MNG_FEATURES_SUPPORTED, above */
  177700. #ifndef PNG_NO_WRITE_EMPTY_PLTE
  177701. # define PNG_WRITE_EMPTY_PLTE_SUPPORTED
  177702. #endif
  177703. #endif
  177704. #endif /* PNG_WRITE_SUPPORTED */
  177705. #ifndef PNG_1_0_X
  177706. # ifndef PNG_NO_ERROR_NUMBERS
  177707. # define PNG_ERROR_NUMBERS_SUPPORTED
  177708. # endif
  177709. #endif /* PNG_1_0_X */
  177710. #if defined(PNG_READ_USER_TRANSFORM_SUPPORTED) || \
  177711. defined(PNG_WRITE_USER_TRANSFORM_SUPPORTED)
  177712. # ifndef PNG_NO_USER_TRANSFORM_PTR
  177713. # define PNG_USER_TRANSFORM_PTR_SUPPORTED
  177714. # endif
  177715. #endif
  177716. #ifndef PNG_NO_STDIO
  177717. # define PNG_TIME_RFC1123_SUPPORTED
  177718. #endif
  177719. /* This adds extra functions in pngget.c for accessing data from the
  177720. * info pointer (added in version 0.99)
  177721. * png_get_image_width()
  177722. * png_get_image_height()
  177723. * png_get_bit_depth()
  177724. * png_get_color_type()
  177725. * png_get_compression_type()
  177726. * png_get_filter_type()
  177727. * png_get_interlace_type()
  177728. * png_get_pixel_aspect_ratio()
  177729. * png_get_pixels_per_meter()
  177730. * png_get_x_offset_pixels()
  177731. * png_get_y_offset_pixels()
  177732. * png_get_x_offset_microns()
  177733. * png_get_y_offset_microns()
  177734. */
  177735. #if !defined(PNG_NO_EASY_ACCESS) && !defined(PNG_EASY_ACCESS_SUPPORTED)
  177736. # define PNG_EASY_ACCESS_SUPPORTED
  177737. #endif
  177738. /* PNG_ASSEMBLER_CODE was enabled by default in version 1.2.0
  177739. * and removed from version 1.2.20. The following will be removed
  177740. * from libpng-1.4.0
  177741. */
  177742. #if defined(PNG_READ_SUPPORTED) && !defined(PNG_NO_OPTIMIZED_CODE)
  177743. # ifndef PNG_OPTIMIZED_CODE_SUPPORTED
  177744. # define PNG_OPTIMIZED_CODE_SUPPORTED
  177745. # endif
  177746. #endif
  177747. #if defined(PNG_READ_SUPPORTED) && !defined(PNG_NO_ASSEMBLER_CODE)
  177748. # ifndef PNG_ASSEMBLER_CODE_SUPPORTED
  177749. # define PNG_ASSEMBLER_CODE_SUPPORTED
  177750. # endif
  177751. # if defined(__GNUC__) && defined(__x86_64__) && (__GNUC__ < 4)
  177752. /* work around 64-bit gcc compiler bugs in gcc-3.x */
  177753. # if !defined(PNG_MMX_CODE_SUPPORTED) && !defined(PNG_NO_MMX_CODE)
  177754. # define PNG_NO_MMX_CODE
  177755. # endif
  177756. # endif
  177757. # if defined(__APPLE__)
  177758. # if !defined(PNG_MMX_CODE_SUPPORTED) && !defined(PNG_NO_MMX_CODE)
  177759. # define PNG_NO_MMX_CODE
  177760. # endif
  177761. # endif
  177762. # if (defined(__MWERKS__) && ((__MWERKS__ < 0x0900) || macintosh))
  177763. # if !defined(PNG_MMX_CODE_SUPPORTED) && !defined(PNG_NO_MMX_CODE)
  177764. # define PNG_NO_MMX_CODE
  177765. # endif
  177766. # endif
  177767. # if !defined(PNG_MMX_CODE_SUPPORTED) && !defined(PNG_NO_MMX_CODE)
  177768. # define PNG_MMX_CODE_SUPPORTED
  177769. # endif
  177770. #endif
  177771. /* end of obsolete code to be removed from libpng-1.4.0 */
  177772. #if !defined(PNG_1_0_X)
  177773. #if !defined(PNG_NO_USER_MEM) && !defined(PNG_USER_MEM_SUPPORTED)
  177774. # define PNG_USER_MEM_SUPPORTED
  177775. #endif
  177776. #endif /* PNG_1_0_X */
  177777. /* Added at libpng-1.2.6 */
  177778. #if !defined(PNG_1_0_X)
  177779. #ifndef PNG_SET_USER_LIMITS_SUPPORTED
  177780. #if !defined(PNG_NO_SET_USER_LIMITS) && !defined(PNG_SET_USER_LIMITS_SUPPORTED)
  177781. # define PNG_SET_USER_LIMITS_SUPPORTED
  177782. #endif
  177783. #endif
  177784. #endif /* PNG_1_0_X */
  177785. /* Added at libpng-1.0.16 and 1.2.6. To accept all valid PNGS no matter
  177786. * how large, set these limits to 0x7fffffffL
  177787. */
  177788. #ifndef PNG_USER_WIDTH_MAX
  177789. # define PNG_USER_WIDTH_MAX 1000000L
  177790. #endif
  177791. #ifndef PNG_USER_HEIGHT_MAX
  177792. # define PNG_USER_HEIGHT_MAX 1000000L
  177793. #endif
  177794. /* These are currently experimental features, define them if you want */
  177795. /* very little testing */
  177796. /*
  177797. #ifdef PNG_READ_SUPPORTED
  177798. # ifndef PNG_READ_16_TO_8_ACCURATE_SCALE_SUPPORTED
  177799. # define PNG_READ_16_TO_8_ACCURATE_SCALE_SUPPORTED
  177800. # endif
  177801. #endif
  177802. */
  177803. /* This is only for PowerPC big-endian and 680x0 systems */
  177804. /* some testing */
  177805. /*
  177806. #ifndef PNG_READ_BIG_ENDIAN_SUPPORTED
  177807. # define PNG_READ_BIG_ENDIAN_SUPPORTED
  177808. #endif
  177809. */
  177810. /* Buggy compilers (e.g., gcc 2.7.2.2) need this */
  177811. /*
  177812. #define PNG_NO_POINTER_INDEXING
  177813. */
  177814. /* These functions are turned off by default, as they will be phased out. */
  177815. /*
  177816. #define PNG_USELESS_TESTS_SUPPORTED
  177817. #define PNG_CORRECT_PALETTE_SUPPORTED
  177818. */
  177819. /* Any chunks you are not interested in, you can undef here. The
  177820. * ones that allocate memory may be expecially important (hIST,
  177821. * tEXt, zTXt, tRNS, pCAL). Others will just save time and make png_info
  177822. * a bit smaller.
  177823. */
  177824. #if defined(PNG_READ_SUPPORTED) && \
  177825. !defined(PNG_READ_ANCILLARY_CHUNKS_NOT_SUPPORTED) && \
  177826. !defined(PNG_NO_READ_ANCILLARY_CHUNKS)
  177827. # define PNG_READ_ANCILLARY_CHUNKS_SUPPORTED
  177828. #endif
  177829. #if defined(PNG_WRITE_SUPPORTED) && \
  177830. !defined(PNG_WRITE_ANCILLARY_CHUNKS_NOT_SUPPORTED) && \
  177831. !defined(PNG_NO_WRITE_ANCILLARY_CHUNKS)
  177832. # define PNG_WRITE_ANCILLARY_CHUNKS_SUPPORTED
  177833. #endif
  177834. #ifdef PNG_READ_ANCILLARY_CHUNKS_SUPPORTED
  177835. #ifdef PNG_NO_READ_TEXT
  177836. # define PNG_NO_READ_iTXt
  177837. # define PNG_NO_READ_tEXt
  177838. # define PNG_NO_READ_zTXt
  177839. #endif
  177840. #ifndef PNG_NO_READ_bKGD
  177841. # define PNG_READ_bKGD_SUPPORTED
  177842. # define PNG_bKGD_SUPPORTED
  177843. #endif
  177844. #ifndef PNG_NO_READ_cHRM
  177845. # define PNG_READ_cHRM_SUPPORTED
  177846. # define PNG_cHRM_SUPPORTED
  177847. #endif
  177848. #ifndef PNG_NO_READ_gAMA
  177849. # define PNG_READ_gAMA_SUPPORTED
  177850. # define PNG_gAMA_SUPPORTED
  177851. #endif
  177852. #ifndef PNG_NO_READ_hIST
  177853. # define PNG_READ_hIST_SUPPORTED
  177854. # define PNG_hIST_SUPPORTED
  177855. #endif
  177856. #ifndef PNG_NO_READ_iCCP
  177857. # define PNG_READ_iCCP_SUPPORTED
  177858. # define PNG_iCCP_SUPPORTED
  177859. #endif
  177860. #ifndef PNG_NO_READ_iTXt
  177861. # ifndef PNG_READ_iTXt_SUPPORTED
  177862. # define PNG_READ_iTXt_SUPPORTED
  177863. # endif
  177864. # ifndef PNG_iTXt_SUPPORTED
  177865. # define PNG_iTXt_SUPPORTED
  177866. # endif
  177867. #endif
  177868. #ifndef PNG_NO_READ_oFFs
  177869. # define PNG_READ_oFFs_SUPPORTED
  177870. # define PNG_oFFs_SUPPORTED
  177871. #endif
  177872. #ifndef PNG_NO_READ_pCAL
  177873. # define PNG_READ_pCAL_SUPPORTED
  177874. # define PNG_pCAL_SUPPORTED
  177875. #endif
  177876. #ifndef PNG_NO_READ_sCAL
  177877. # define PNG_READ_sCAL_SUPPORTED
  177878. # define PNG_sCAL_SUPPORTED
  177879. #endif
  177880. #ifndef PNG_NO_READ_pHYs
  177881. # define PNG_READ_pHYs_SUPPORTED
  177882. # define PNG_pHYs_SUPPORTED
  177883. #endif
  177884. #ifndef PNG_NO_READ_sBIT
  177885. # define PNG_READ_sBIT_SUPPORTED
  177886. # define PNG_sBIT_SUPPORTED
  177887. #endif
  177888. #ifndef PNG_NO_READ_sPLT
  177889. # define PNG_READ_sPLT_SUPPORTED
  177890. # define PNG_sPLT_SUPPORTED
  177891. #endif
  177892. #ifndef PNG_NO_READ_sRGB
  177893. # define PNG_READ_sRGB_SUPPORTED
  177894. # define PNG_sRGB_SUPPORTED
  177895. #endif
  177896. #ifndef PNG_NO_READ_tEXt
  177897. # define PNG_READ_tEXt_SUPPORTED
  177898. # define PNG_tEXt_SUPPORTED
  177899. #endif
  177900. #ifndef PNG_NO_READ_tIME
  177901. # define PNG_READ_tIME_SUPPORTED
  177902. # define PNG_tIME_SUPPORTED
  177903. #endif
  177904. #ifndef PNG_NO_READ_tRNS
  177905. # define PNG_READ_tRNS_SUPPORTED
  177906. # define PNG_tRNS_SUPPORTED
  177907. #endif
  177908. #ifndef PNG_NO_READ_zTXt
  177909. # define PNG_READ_zTXt_SUPPORTED
  177910. # define PNG_zTXt_SUPPORTED
  177911. #endif
  177912. #ifndef PNG_NO_READ_UNKNOWN_CHUNKS
  177913. # define PNG_READ_UNKNOWN_CHUNKS_SUPPORTED
  177914. # ifndef PNG_UNKNOWN_CHUNKS_SUPPORTED
  177915. # define PNG_UNKNOWN_CHUNKS_SUPPORTED
  177916. # endif
  177917. # ifndef PNG_NO_HANDLE_AS_UNKNOWN
  177918. # define PNG_HANDLE_AS_UNKNOWN_SUPPORTED
  177919. # endif
  177920. #endif
  177921. #if !defined(PNG_NO_READ_USER_CHUNKS) && \
  177922. defined(PNG_READ_UNKNOWN_CHUNKS_SUPPORTED)
  177923. # define PNG_READ_USER_CHUNKS_SUPPORTED
  177924. # define PNG_USER_CHUNKS_SUPPORTED
  177925. # ifdef PNG_NO_READ_UNKNOWN_CHUNKS
  177926. # undef PNG_NO_READ_UNKNOWN_CHUNKS
  177927. # endif
  177928. # ifdef PNG_NO_HANDLE_AS_UNKNOWN
  177929. # undef PNG_NO_HANDLE_AS_UNKNOWN
  177930. # endif
  177931. #endif
  177932. #ifndef PNG_NO_READ_OPT_PLTE
  177933. # define PNG_READ_OPT_PLTE_SUPPORTED /* only affects support of the */
  177934. #endif /* optional PLTE chunk in RGB and RGBA images */
  177935. #if defined(PNG_READ_iTXt_SUPPORTED) || defined(PNG_READ_tEXt_SUPPORTED) || \
  177936. defined(PNG_READ_zTXt_SUPPORTED)
  177937. # define PNG_READ_TEXT_SUPPORTED
  177938. # define PNG_TEXT_SUPPORTED
  177939. #endif
  177940. #endif /* PNG_READ_ANCILLARY_CHUNKS_SUPPORTED */
  177941. #ifdef PNG_WRITE_ANCILLARY_CHUNKS_SUPPORTED
  177942. #ifdef PNG_NO_WRITE_TEXT
  177943. # define PNG_NO_WRITE_iTXt
  177944. # define PNG_NO_WRITE_tEXt
  177945. # define PNG_NO_WRITE_zTXt
  177946. #endif
  177947. #ifndef PNG_NO_WRITE_bKGD
  177948. # define PNG_WRITE_bKGD_SUPPORTED
  177949. # ifndef PNG_bKGD_SUPPORTED
  177950. # define PNG_bKGD_SUPPORTED
  177951. # endif
  177952. #endif
  177953. #ifndef PNG_NO_WRITE_cHRM
  177954. # define PNG_WRITE_cHRM_SUPPORTED
  177955. # ifndef PNG_cHRM_SUPPORTED
  177956. # define PNG_cHRM_SUPPORTED
  177957. # endif
  177958. #endif
  177959. #ifndef PNG_NO_WRITE_gAMA
  177960. # define PNG_WRITE_gAMA_SUPPORTED
  177961. # ifndef PNG_gAMA_SUPPORTED
  177962. # define PNG_gAMA_SUPPORTED
  177963. # endif
  177964. #endif
  177965. #ifndef PNG_NO_WRITE_hIST
  177966. # define PNG_WRITE_hIST_SUPPORTED
  177967. # ifndef PNG_hIST_SUPPORTED
  177968. # define PNG_hIST_SUPPORTED
  177969. # endif
  177970. #endif
  177971. #ifndef PNG_NO_WRITE_iCCP
  177972. # define PNG_WRITE_iCCP_SUPPORTED
  177973. # ifndef PNG_iCCP_SUPPORTED
  177974. # define PNG_iCCP_SUPPORTED
  177975. # endif
  177976. #endif
  177977. #ifndef PNG_NO_WRITE_iTXt
  177978. # ifndef PNG_WRITE_iTXt_SUPPORTED
  177979. # define PNG_WRITE_iTXt_SUPPORTED
  177980. # endif
  177981. # ifndef PNG_iTXt_SUPPORTED
  177982. # define PNG_iTXt_SUPPORTED
  177983. # endif
  177984. #endif
  177985. #ifndef PNG_NO_WRITE_oFFs
  177986. # define PNG_WRITE_oFFs_SUPPORTED
  177987. # ifndef PNG_oFFs_SUPPORTED
  177988. # define PNG_oFFs_SUPPORTED
  177989. # endif
  177990. #endif
  177991. #ifndef PNG_NO_WRITE_pCAL
  177992. # define PNG_WRITE_pCAL_SUPPORTED
  177993. # ifndef PNG_pCAL_SUPPORTED
  177994. # define PNG_pCAL_SUPPORTED
  177995. # endif
  177996. #endif
  177997. #ifndef PNG_NO_WRITE_sCAL
  177998. # define PNG_WRITE_sCAL_SUPPORTED
  177999. # ifndef PNG_sCAL_SUPPORTED
  178000. # define PNG_sCAL_SUPPORTED
  178001. # endif
  178002. #endif
  178003. #ifndef PNG_NO_WRITE_pHYs
  178004. # define PNG_WRITE_pHYs_SUPPORTED
  178005. # ifndef PNG_pHYs_SUPPORTED
  178006. # define PNG_pHYs_SUPPORTED
  178007. # endif
  178008. #endif
  178009. #ifndef PNG_NO_WRITE_sBIT
  178010. # define PNG_WRITE_sBIT_SUPPORTED
  178011. # ifndef PNG_sBIT_SUPPORTED
  178012. # define PNG_sBIT_SUPPORTED
  178013. # endif
  178014. #endif
  178015. #ifndef PNG_NO_WRITE_sPLT
  178016. # define PNG_WRITE_sPLT_SUPPORTED
  178017. # ifndef PNG_sPLT_SUPPORTED
  178018. # define PNG_sPLT_SUPPORTED
  178019. # endif
  178020. #endif
  178021. #ifndef PNG_NO_WRITE_sRGB
  178022. # define PNG_WRITE_sRGB_SUPPORTED
  178023. # ifndef PNG_sRGB_SUPPORTED
  178024. # define PNG_sRGB_SUPPORTED
  178025. # endif
  178026. #endif
  178027. #ifndef PNG_NO_WRITE_tEXt
  178028. # define PNG_WRITE_tEXt_SUPPORTED
  178029. # ifndef PNG_tEXt_SUPPORTED
  178030. # define PNG_tEXt_SUPPORTED
  178031. # endif
  178032. #endif
  178033. #ifndef PNG_NO_WRITE_tIME
  178034. # define PNG_WRITE_tIME_SUPPORTED
  178035. # ifndef PNG_tIME_SUPPORTED
  178036. # define PNG_tIME_SUPPORTED
  178037. # endif
  178038. #endif
  178039. #ifndef PNG_NO_WRITE_tRNS
  178040. # define PNG_WRITE_tRNS_SUPPORTED
  178041. # ifndef PNG_tRNS_SUPPORTED
  178042. # define PNG_tRNS_SUPPORTED
  178043. # endif
  178044. #endif
  178045. #ifndef PNG_NO_WRITE_zTXt
  178046. # define PNG_WRITE_zTXt_SUPPORTED
  178047. # ifndef PNG_zTXt_SUPPORTED
  178048. # define PNG_zTXt_SUPPORTED
  178049. # endif
  178050. #endif
  178051. #ifndef PNG_NO_WRITE_UNKNOWN_CHUNKS
  178052. # define PNG_WRITE_UNKNOWN_CHUNKS_SUPPORTED
  178053. # ifndef PNG_UNKNOWN_CHUNKS_SUPPORTED
  178054. # define PNG_UNKNOWN_CHUNKS_SUPPORTED
  178055. # endif
  178056. # ifndef PNG_NO_HANDLE_AS_UNKNOWN
  178057. # ifndef PNG_HANDLE_AS_UNKNOWN_SUPPORTED
  178058. # define PNG_HANDLE_AS_UNKNOWN_SUPPORTED
  178059. # endif
  178060. # endif
  178061. #endif
  178062. #if defined(PNG_WRITE_iTXt_SUPPORTED) || defined(PNG_WRITE_tEXt_SUPPORTED) || \
  178063. defined(PNG_WRITE_zTXt_SUPPORTED)
  178064. # define PNG_WRITE_TEXT_SUPPORTED
  178065. # ifndef PNG_TEXT_SUPPORTED
  178066. # define PNG_TEXT_SUPPORTED
  178067. # endif
  178068. #endif
  178069. #endif /* PNG_WRITE_ANCILLARY_CHUNKS_SUPPORTED */
  178070. /* Turn this off to disable png_read_png() and
  178071. * png_write_png() and leave the row_pointers member
  178072. * out of the info structure.
  178073. */
  178074. #ifndef PNG_NO_INFO_IMAGE
  178075. # define PNG_INFO_IMAGE_SUPPORTED
  178076. #endif
  178077. /* need the time information for reading tIME chunks */
  178078. #if defined(PNG_tIME_SUPPORTED)
  178079. # if !defined(_WIN32_WCE)
  178080. /* "time.h" functions are not supported on WindowsCE */
  178081. # include <time.h>
  178082. # endif
  178083. #endif
  178084. /* Some typedefs to get us started. These should be safe on most of the
  178085. * common platforms. The typedefs should be at least as large as the
  178086. * numbers suggest (a png_uint_32 must be at least 32 bits long), but they
  178087. * don't have to be exactly that size. Some compilers dislike passing
  178088. * unsigned shorts as function parameters, so you may be better off using
  178089. * unsigned int for png_uint_16. Likewise, for 64-bit systems, you may
  178090. * want to have unsigned int for png_uint_32 instead of unsigned long.
  178091. */
  178092. typedef unsigned long png_uint_32;
  178093. typedef long png_int_32;
  178094. typedef unsigned short png_uint_16;
  178095. typedef short png_int_16;
  178096. typedef unsigned char png_byte;
  178097. /* This is usually size_t. It is typedef'ed just in case you need it to
  178098. change (I'm not sure if you will or not, so I thought I'd be safe) */
  178099. #ifdef PNG_SIZE_T
  178100. typedef PNG_SIZE_T png_size_t;
  178101. # define png_sizeof(x) png_convert_size(sizeof (x))
  178102. #else
  178103. typedef size_t png_size_t;
  178104. # define png_sizeof(x) sizeof (x)
  178105. #endif
  178106. /* The following is needed for medium model support. It cannot be in the
  178107. * PNG_INTERNAL section. Needs modification for other compilers besides
  178108. * MSC. Model independent support declares all arrays and pointers to be
  178109. * large using the far keyword. The zlib version used must also support
  178110. * model independent data. As of version zlib 1.0.4, the necessary changes
  178111. * have been made in zlib. The USE_FAR_KEYWORD define triggers other
  178112. * changes that are needed. (Tim Wegner)
  178113. */
  178114. /* Separate compiler dependencies (problem here is that zlib.h always
  178115. defines FAR. (SJT) */
  178116. #ifdef __BORLANDC__
  178117. # if defined(__LARGE__) || defined(__HUGE__) || defined(__COMPACT__)
  178118. # define LDATA 1
  178119. # else
  178120. # define LDATA 0
  178121. # endif
  178122. /* GRR: why is Cygwin in here? Cygwin is not Borland C... */
  178123. # if !defined(__WIN32__) && !defined(__FLAT__) && !defined(__CYGWIN__)
  178124. # define PNG_MAX_MALLOC_64K
  178125. # if (LDATA != 1)
  178126. # ifndef FAR
  178127. # define FAR __far
  178128. # endif
  178129. # define USE_FAR_KEYWORD
  178130. # endif /* LDATA != 1 */
  178131. /* Possibly useful for moving data out of default segment.
  178132. * Uncomment it if you want. Could also define FARDATA as
  178133. * const if your compiler supports it. (SJT)
  178134. # define FARDATA FAR
  178135. */
  178136. # endif /* __WIN32__, __FLAT__, __CYGWIN__ */
  178137. #endif /* __BORLANDC__ */
  178138. /* Suggest testing for specific compiler first before testing for
  178139. * FAR. The Watcom compiler defines both __MEDIUM__ and M_I86MM,
  178140. * making reliance oncertain keywords suspect. (SJT)
  178141. */
  178142. /* MSC Medium model */
  178143. #if defined(FAR)
  178144. # if defined(M_I86MM)
  178145. # define USE_FAR_KEYWORD
  178146. # define FARDATA FAR
  178147. # include <dos.h>
  178148. # endif
  178149. #endif
  178150. /* SJT: default case */
  178151. #ifndef FAR
  178152. # define FAR
  178153. #endif
  178154. /* At this point FAR is always defined */
  178155. #ifndef FARDATA
  178156. # define FARDATA
  178157. #endif
  178158. /* Typedef for floating-point numbers that are converted
  178159. to fixed-point with a multiple of 100,000, e.g., int_gamma */
  178160. typedef png_int_32 png_fixed_point;
  178161. /* Add typedefs for pointers */
  178162. typedef void FAR * png_voidp;
  178163. typedef png_byte FAR * png_bytep;
  178164. typedef png_uint_32 FAR * png_uint_32p;
  178165. typedef png_int_32 FAR * png_int_32p;
  178166. typedef png_uint_16 FAR * png_uint_16p;
  178167. typedef png_int_16 FAR * png_int_16p;
  178168. typedef PNG_CONST char FAR * png_const_charp;
  178169. typedef char FAR * png_charp;
  178170. typedef png_fixed_point FAR * png_fixed_point_p;
  178171. #ifndef PNG_NO_STDIO
  178172. #if defined(_WIN32_WCE)
  178173. typedef HANDLE png_FILE_p;
  178174. #else
  178175. typedef FILE * png_FILE_p;
  178176. #endif
  178177. #endif
  178178. #ifdef PNG_FLOATING_POINT_SUPPORTED
  178179. typedef double FAR * png_doublep;
  178180. #endif
  178181. /* Pointers to pointers; i.e. arrays */
  178182. typedef png_byte FAR * FAR * png_bytepp;
  178183. typedef png_uint_32 FAR * FAR * png_uint_32pp;
  178184. typedef png_int_32 FAR * FAR * png_int_32pp;
  178185. typedef png_uint_16 FAR * FAR * png_uint_16pp;
  178186. typedef png_int_16 FAR * FAR * png_int_16pp;
  178187. typedef PNG_CONST char FAR * FAR * png_const_charpp;
  178188. typedef char FAR * FAR * png_charpp;
  178189. typedef png_fixed_point FAR * FAR * png_fixed_point_pp;
  178190. #ifdef PNG_FLOATING_POINT_SUPPORTED
  178191. typedef double FAR * FAR * png_doublepp;
  178192. #endif
  178193. /* Pointers to pointers to pointers; i.e., pointer to array */
  178194. typedef char FAR * FAR * FAR * png_charppp;
  178195. #if 0
  178196. /* SPC - Is this stuff deprecated? */
  178197. /* It'll be removed as of libpng-1.3.0 - GR-P */
  178198. /* libpng typedefs for types in zlib. If zlib changes
  178199. * or another compression library is used, then change these.
  178200. * Eliminates need to change all the source files.
  178201. */
  178202. typedef charf * png_zcharp;
  178203. typedef charf * FAR * png_zcharpp;
  178204. typedef z_stream FAR * png_zstreamp;
  178205. #endif /* (PNG_1_0_X) || defined(PNG_1_2_X) */
  178206. /*
  178207. * Define PNG_BUILD_DLL if the module being built is a Windows
  178208. * LIBPNG DLL.
  178209. *
  178210. * Define PNG_USE_DLL if you want to *link* to the Windows LIBPNG DLL.
  178211. * It is equivalent to Microsoft predefined macro _DLL that is
  178212. * automatically defined when you compile using the share
  178213. * version of the CRT (C Run-Time library)
  178214. *
  178215. * The cygwin mods make this behavior a little different:
  178216. * Define PNG_BUILD_DLL if you are building a dll for use with cygwin
  178217. * Define PNG_STATIC if you are building a static library for use with cygwin,
  178218. * -or- if you are building an application that you want to link to the
  178219. * static library.
  178220. * PNG_USE_DLL is defined by default (no user action needed) unless one of
  178221. * the other flags is defined.
  178222. */
  178223. #if !defined(PNG_DLL) && (defined(PNG_BUILD_DLL) || defined(PNG_USE_DLL))
  178224. # define PNG_DLL
  178225. #endif
  178226. /* If CYGWIN, then disallow GLOBAL ARRAYS unless building a static lib.
  178227. * When building a static lib, default to no GLOBAL ARRAYS, but allow
  178228. * command-line override
  178229. */
  178230. #if defined(__CYGWIN__)
  178231. # if !defined(PNG_STATIC)
  178232. # if defined(PNG_USE_GLOBAL_ARRAYS)
  178233. # undef PNG_USE_GLOBAL_ARRAYS
  178234. # endif
  178235. # if !defined(PNG_USE_LOCAL_ARRAYS)
  178236. # define PNG_USE_LOCAL_ARRAYS
  178237. # endif
  178238. # else
  178239. # if defined(PNG_USE_LOCAL_ARRAYS) || defined(PNG_NO_GLOBAL_ARRAYS)
  178240. # if defined(PNG_USE_GLOBAL_ARRAYS)
  178241. # undef PNG_USE_GLOBAL_ARRAYS
  178242. # endif
  178243. # endif
  178244. # endif
  178245. # if !defined(PNG_USE_LOCAL_ARRAYS) && !defined(PNG_USE_GLOBAL_ARRAYS)
  178246. # define PNG_USE_LOCAL_ARRAYS
  178247. # endif
  178248. #endif
  178249. /* Do not use global arrays (helps with building DLL's)
  178250. * They are no longer used in libpng itself, since version 1.0.5c,
  178251. * but might be required for some pre-1.0.5c applications.
  178252. */
  178253. #if !defined(PNG_USE_LOCAL_ARRAYS) && !defined(PNG_USE_GLOBAL_ARRAYS)
  178254. # if defined(PNG_NO_GLOBAL_ARRAYS) || \
  178255. (defined(__GNUC__) && defined(PNG_DLL)) || defined(_MSC_VER)
  178256. # define PNG_USE_LOCAL_ARRAYS
  178257. # else
  178258. # define PNG_USE_GLOBAL_ARRAYS
  178259. # endif
  178260. #endif
  178261. #if defined(__CYGWIN__)
  178262. # undef PNGAPI
  178263. # define PNGAPI __cdecl
  178264. # undef PNG_IMPEXP
  178265. # define PNG_IMPEXP
  178266. #endif
  178267. /* If you define PNGAPI, e.g., with compiler option "-DPNGAPI=__stdcall",
  178268. * you may get warnings regarding the linkage of png_zalloc and png_zfree.
  178269. * Don't ignore those warnings; you must also reset the default calling
  178270. * convention in your compiler to match your PNGAPI, and you must build
  178271. * zlib and your applications the same way you build libpng.
  178272. */
  178273. #if defined(__MINGW32__) && !defined(PNG_MODULEDEF)
  178274. # ifndef PNG_NO_MODULEDEF
  178275. # define PNG_NO_MODULEDEF
  178276. # endif
  178277. #endif
  178278. #if !defined(PNG_IMPEXP) && defined(PNG_BUILD_DLL) && !defined(PNG_NO_MODULEDEF)
  178279. # define PNG_IMPEXP
  178280. #endif
  178281. #if defined(PNG_DLL) || defined(_DLL) || defined(__DLL__ ) || \
  178282. (( defined(_Windows) || defined(_WINDOWS) || \
  178283. defined(WIN32) || defined(_WIN32) || defined(__WIN32__) ))
  178284. # ifndef PNGAPI
  178285. # if defined(__GNUC__) || (defined (_MSC_VER) && (_MSC_VER >= 800))
  178286. # define PNGAPI __cdecl
  178287. # else
  178288. # define PNGAPI _cdecl
  178289. # endif
  178290. # endif
  178291. # if !defined(PNG_IMPEXP) && (!defined(PNG_DLL) || \
  178292. 0 /* WINCOMPILER_WITH_NO_SUPPORT_FOR_DECLIMPEXP */)
  178293. # define PNG_IMPEXP
  178294. # endif
  178295. # if !defined(PNG_IMPEXP)
  178296. # define PNG_EXPORT_TYPE1(type,symbol) PNG_IMPEXP type PNGAPI symbol
  178297. # define PNG_EXPORT_TYPE2(type,symbol) type PNG_IMPEXP PNGAPI symbol
  178298. /* Borland/Microsoft */
  178299. # if defined(_MSC_VER) || defined(__BORLANDC__)
  178300. # if (_MSC_VER >= 800) || (__BORLANDC__ >= 0x500)
  178301. # define PNG_EXPORT PNG_EXPORT_TYPE1
  178302. # else
  178303. # define PNG_EXPORT PNG_EXPORT_TYPE2
  178304. # if defined(PNG_BUILD_DLL)
  178305. # define PNG_IMPEXP __export
  178306. # else
  178307. # define PNG_IMPEXP /*__import */ /* doesn't exist AFAIK in
  178308. VC++ */
  178309. # endif /* Exists in Borland C++ for
  178310. C++ classes (== huge) */
  178311. # endif
  178312. # endif
  178313. # if !defined(PNG_IMPEXP)
  178314. # if defined(PNG_BUILD_DLL)
  178315. # define PNG_IMPEXP __declspec(dllexport)
  178316. # else
  178317. # define PNG_IMPEXP __declspec(dllimport)
  178318. # endif
  178319. # endif
  178320. # endif /* PNG_IMPEXP */
  178321. #else /* !(DLL || non-cygwin WINDOWS) */
  178322. # if (defined(__IBMC__) || defined(__IBMCPP__)) && defined(__OS2__)
  178323. # ifndef PNGAPI
  178324. # define PNGAPI _System
  178325. # endif
  178326. # else
  178327. # if 0 /* ... other platforms, with other meanings */
  178328. # endif
  178329. # endif
  178330. #endif
  178331. #ifndef PNGAPI
  178332. # define PNGAPI
  178333. #endif
  178334. #ifndef PNG_IMPEXP
  178335. # define PNG_IMPEXP
  178336. #endif
  178337. #ifdef PNG_BUILDSYMS
  178338. # ifndef PNG_EXPORT
  178339. # define PNG_EXPORT(type,symbol) PNG_FUNCTION_EXPORT symbol END
  178340. # endif
  178341. # ifdef PNG_USE_GLOBAL_ARRAYS
  178342. # ifndef PNG_EXPORT_VAR
  178343. # define PNG_EXPORT_VAR(type) PNG_DATA_EXPORT
  178344. # endif
  178345. # endif
  178346. #endif
  178347. #ifndef PNG_EXPORT
  178348. # define PNG_EXPORT(type,symbol) PNG_IMPEXP type PNGAPI symbol
  178349. #endif
  178350. #ifdef PNG_USE_GLOBAL_ARRAYS
  178351. # ifndef PNG_EXPORT_VAR
  178352. # define PNG_EXPORT_VAR(type) extern PNG_IMPEXP type
  178353. # endif
  178354. #endif
  178355. /* User may want to use these so they are not in PNG_INTERNAL. Any library
  178356. * functions that are passed far data must be model independent.
  178357. */
  178358. #ifndef PNG_ABORT
  178359. # define PNG_ABORT() abort()
  178360. #endif
  178361. #ifdef PNG_SETJMP_SUPPORTED
  178362. # define png_jmpbuf(png_ptr) ((png_ptr)->jmpbuf)
  178363. #else
  178364. # define png_jmpbuf(png_ptr) \
  178365. (LIBPNG_WAS_COMPILED_WITH__PNG_SETJMP_NOT_SUPPORTED)
  178366. #endif
  178367. #if defined(USE_FAR_KEYWORD) /* memory model independent fns */
  178368. /* use this to make far-to-near assignments */
  178369. # define CHECK 1
  178370. # define NOCHECK 0
  178371. # define CVT_PTR(ptr) (png_far_to_near(png_ptr,ptr,CHECK))
  178372. # define CVT_PTR_NOCHECK(ptr) (png_far_to_near(png_ptr,ptr,NOCHECK))
  178373. # define png_snprintf _fsnprintf /* Added to v 1.2.19 */
  178374. # define png_strcpy _fstrcpy
  178375. # define png_strncpy _fstrncpy /* Added to v 1.2.6 */
  178376. # define png_strlen _fstrlen
  178377. # define png_memcmp _fmemcmp /* SJT: added */
  178378. # define png_memcpy _fmemcpy
  178379. # define png_memset _fmemset
  178380. #else /* use the usual functions */
  178381. # define CVT_PTR(ptr) (ptr)
  178382. # define CVT_PTR_NOCHECK(ptr) (ptr)
  178383. # ifndef PNG_NO_SNPRINTF
  178384. # ifdef _MSC_VER
  178385. # define png_snprintf _snprintf /* Added to v 1.2.19 */
  178386. # define png_snprintf2 _snprintf
  178387. # define png_snprintf6 _snprintf
  178388. # else
  178389. # define png_snprintf snprintf /* Added to v 1.2.19 */
  178390. # define png_snprintf2 snprintf
  178391. # define png_snprintf6 snprintf
  178392. # endif
  178393. # else
  178394. /* You don't have or don't want to use snprintf(). Caution: Using
  178395. * sprintf instead of snprintf exposes your application to accidental
  178396. * or malevolent buffer overflows. If you don't have snprintf()
  178397. * as a general rule you should provide one (you can get one from
  178398. * Portable OpenSSH). */
  178399. # define png_snprintf(s1,n,fmt,x1) sprintf(s1,fmt,x1)
  178400. # define png_snprintf2(s1,n,fmt,x1,x2) sprintf(s1,fmt,x1,x2)
  178401. # define png_snprintf6(s1,n,fmt,x1,x2,x3,x4,x5,x6) \
  178402. sprintf(s1,fmt,x1,x2,x3,x4,x5,x6)
  178403. # endif
  178404. # define png_strcpy strcpy
  178405. # define png_strncpy strncpy /* Added to v 1.2.6 */
  178406. # define png_strlen strlen
  178407. # define png_memcmp memcmp /* SJT: added */
  178408. # define png_memcpy memcpy
  178409. # define png_memset memset
  178410. #endif
  178411. /* End of memory model independent support */
  178412. /* Just a little check that someone hasn't tried to define something
  178413. * contradictory.
  178414. */
  178415. #if (PNG_ZBUF_SIZE > 65536L) && defined(PNG_MAX_MALLOC_64K)
  178416. # undef PNG_ZBUF_SIZE
  178417. # define PNG_ZBUF_SIZE 65536L
  178418. #endif
  178419. /* Added at libpng-1.2.8 */
  178420. #endif /* PNG_VERSION_INFO_ONLY */
  178421. #endif /* PNGCONF_H */
  178422. /*** End of inlined file: pngconf.h ***/
  178423. #ifdef _MSC_VER
  178424. #pragma warning (disable: 4996 4100)
  178425. #endif
  178426. /*
  178427. * Added at libpng-1.2.8 */
  178428. /* Ref MSDN: Private as priority over Special
  178429. * VS_FF_PRIVATEBUILD File *was not* built using standard release
  178430. * procedures. If this value is given, the StringFileInfo block must
  178431. * contain a PrivateBuild string.
  178432. *
  178433. * VS_FF_SPECIALBUILD File *was* built by the original company using
  178434. * standard release procedures but is a variation of the standard
  178435. * file of the same version number. If this value is given, the
  178436. * StringFileInfo block must contain a SpecialBuild string.
  178437. */
  178438. #if defined(PNG_USER_PRIVATEBUILD)
  178439. # define PNG_LIBPNG_BUILD_TYPE \
  178440. (PNG_LIBPNG_BUILD_BASE_TYPE | PNG_LIBPNG_BUILD_PRIVATE)
  178441. #else
  178442. # if defined(PNG_LIBPNG_SPECIALBUILD)
  178443. # define PNG_LIBPNG_BUILD_TYPE \
  178444. (PNG_LIBPNG_BUILD_BASE_TYPE | PNG_LIBPNG_BUILD_SPECIAL)
  178445. # else
  178446. # define PNG_LIBPNG_BUILD_TYPE (PNG_LIBPNG_BUILD_BASE_TYPE)
  178447. # endif
  178448. #endif
  178449. #ifndef PNG_VERSION_INFO_ONLY
  178450. /* Inhibit C++ name-mangling for libpng functions but not for system calls. */
  178451. #ifdef __cplusplus
  178452. extern "C" {
  178453. #endif /* __cplusplus */
  178454. /* This file is arranged in several sections. The first section contains
  178455. * structure and type definitions. The second section contains the external
  178456. * library functions, while the third has the internal library functions,
  178457. * which applications aren't expected to use directly.
  178458. */
  178459. #ifndef PNG_NO_TYPECAST_NULL
  178460. #define int_p_NULL (int *)NULL
  178461. #define png_bytep_NULL (png_bytep)NULL
  178462. #define png_bytepp_NULL (png_bytepp)NULL
  178463. #define png_doublep_NULL (png_doublep)NULL
  178464. #define png_error_ptr_NULL (png_error_ptr)NULL
  178465. #define png_flush_ptr_NULL (png_flush_ptr)NULL
  178466. #define png_free_ptr_NULL (png_free_ptr)NULL
  178467. #define png_infopp_NULL (png_infopp)NULL
  178468. #define png_malloc_ptr_NULL (png_malloc_ptr)NULL
  178469. #define png_read_status_ptr_NULL (png_read_status_ptr)NULL
  178470. #define png_rw_ptr_NULL (png_rw_ptr)NULL
  178471. #define png_structp_NULL (png_structp)NULL
  178472. #define png_uint_16p_NULL (png_uint_16p)NULL
  178473. #define png_voidp_NULL (png_voidp)NULL
  178474. #define png_write_status_ptr_NULL (png_write_status_ptr)NULL
  178475. #else
  178476. #define int_p_NULL NULL
  178477. #define png_bytep_NULL NULL
  178478. #define png_bytepp_NULL NULL
  178479. #define png_doublep_NULL NULL
  178480. #define png_error_ptr_NULL NULL
  178481. #define png_flush_ptr_NULL NULL
  178482. #define png_free_ptr_NULL NULL
  178483. #define png_infopp_NULL NULL
  178484. #define png_malloc_ptr_NULL NULL
  178485. #define png_read_status_ptr_NULL NULL
  178486. #define png_rw_ptr_NULL NULL
  178487. #define png_structp_NULL NULL
  178488. #define png_uint_16p_NULL NULL
  178489. #define png_voidp_NULL NULL
  178490. #define png_write_status_ptr_NULL NULL
  178491. #endif
  178492. /* variables declared in png.c - only it needs to define PNG_NO_EXTERN */
  178493. #if !defined(PNG_NO_EXTERN) || defined(PNG_ALWAYS_EXTERN)
  178494. /* Version information for C files, stored in png.c. This had better match
  178495. * the version above.
  178496. */
  178497. #ifdef PNG_USE_GLOBAL_ARRAYS
  178498. PNG_EXPORT_VAR (PNG_CONST char) png_libpng_ver[18];
  178499. /* need room for 99.99.99beta99z */
  178500. #else
  178501. #define png_libpng_ver png_get_header_ver(NULL)
  178502. #endif
  178503. #ifdef PNG_USE_GLOBAL_ARRAYS
  178504. /* This was removed in version 1.0.5c */
  178505. /* Structures to facilitate easy interlacing. See png.c for more details */
  178506. PNG_EXPORT_VAR (PNG_CONST int FARDATA) png_pass_start[7];
  178507. PNG_EXPORT_VAR (PNG_CONST int FARDATA) png_pass_inc[7];
  178508. PNG_EXPORT_VAR (PNG_CONST int FARDATA) png_pass_ystart[7];
  178509. PNG_EXPORT_VAR (PNG_CONST int FARDATA) png_pass_yinc[7];
  178510. PNG_EXPORT_VAR (PNG_CONST int FARDATA) png_pass_mask[7];
  178511. PNG_EXPORT_VAR (PNG_CONST int FARDATA) png_pass_dsp_mask[7];
  178512. /* This isn't currently used. If you need it, see png.c for more details.
  178513. PNG_EXPORT_VAR (PNG_CONST int FARDATA) png_pass_height[7];
  178514. */
  178515. #endif
  178516. #endif /* PNG_NO_EXTERN */
  178517. /* Three color definitions. The order of the red, green, and blue, (and the
  178518. * exact size) is not important, although the size of the fields need to
  178519. * be png_byte or png_uint_16 (as defined below).
  178520. */
  178521. typedef struct png_color_struct
  178522. {
  178523. png_byte red;
  178524. png_byte green;
  178525. png_byte blue;
  178526. } png_color;
  178527. typedef png_color FAR * png_colorp;
  178528. typedef png_color FAR * FAR * png_colorpp;
  178529. typedef struct png_color_16_struct
  178530. {
  178531. png_byte index; /* used for palette files */
  178532. png_uint_16 red; /* for use in red green blue files */
  178533. png_uint_16 green;
  178534. png_uint_16 blue;
  178535. png_uint_16 gray; /* for use in grayscale files */
  178536. } png_color_16;
  178537. typedef png_color_16 FAR * png_color_16p;
  178538. typedef png_color_16 FAR * FAR * png_color_16pp;
  178539. typedef struct png_color_8_struct
  178540. {
  178541. png_byte red; /* for use in red green blue files */
  178542. png_byte green;
  178543. png_byte blue;
  178544. png_byte gray; /* for use in grayscale files */
  178545. png_byte alpha; /* for alpha channel files */
  178546. } png_color_8;
  178547. typedef png_color_8 FAR * png_color_8p;
  178548. typedef png_color_8 FAR * FAR * png_color_8pp;
  178549. /*
  178550. * The following two structures are used for the in-core representation
  178551. * of sPLT chunks.
  178552. */
  178553. typedef struct png_sPLT_entry_struct
  178554. {
  178555. png_uint_16 red;
  178556. png_uint_16 green;
  178557. png_uint_16 blue;
  178558. png_uint_16 alpha;
  178559. png_uint_16 frequency;
  178560. } png_sPLT_entry;
  178561. typedef png_sPLT_entry FAR * png_sPLT_entryp;
  178562. typedef png_sPLT_entry FAR * FAR * png_sPLT_entrypp;
  178563. /* When the depth of the sPLT palette is 8 bits, the color and alpha samples
  178564. * occupy the LSB of their respective members, and the MSB of each member
  178565. * is zero-filled. The frequency member always occupies the full 16 bits.
  178566. */
  178567. typedef struct png_sPLT_struct
  178568. {
  178569. png_charp name; /* palette name */
  178570. png_byte depth; /* depth of palette samples */
  178571. png_sPLT_entryp entries; /* palette entries */
  178572. png_int_32 nentries; /* number of palette entries */
  178573. } png_sPLT_t;
  178574. typedef png_sPLT_t FAR * png_sPLT_tp;
  178575. typedef png_sPLT_t FAR * FAR * png_sPLT_tpp;
  178576. #ifdef PNG_TEXT_SUPPORTED
  178577. /* png_text holds the contents of a text/ztxt/itxt chunk in a PNG file,
  178578. * and whether that contents is compressed or not. The "key" field
  178579. * points to a regular zero-terminated C string. The "text", "lang", and
  178580. * "lang_key" fields can be regular C strings, empty strings, or NULL pointers.
  178581. * However, the * structure returned by png_get_text() will always contain
  178582. * regular zero-terminated C strings (possibly empty), never NULL pointers,
  178583. * so they can be safely used in printf() and other string-handling functions.
  178584. */
  178585. typedef struct png_text_struct
  178586. {
  178587. int compression; /* compression value:
  178588. -1: tEXt, none
  178589. 0: zTXt, deflate
  178590. 1: iTXt, none
  178591. 2: iTXt, deflate */
  178592. png_charp key; /* keyword, 1-79 character description of "text" */
  178593. png_charp text; /* comment, may be an empty string (ie "")
  178594. or a NULL pointer */
  178595. png_size_t text_length; /* length of the text string */
  178596. #ifdef PNG_iTXt_SUPPORTED
  178597. png_size_t itxt_length; /* length of the itxt string */
  178598. png_charp lang; /* language code, 0-79 characters
  178599. or a NULL pointer */
  178600. png_charp lang_key; /* keyword translated UTF-8 string, 0 or more
  178601. chars or a NULL pointer */
  178602. #endif
  178603. } png_text;
  178604. typedef png_text FAR * png_textp;
  178605. typedef png_text FAR * FAR * png_textpp;
  178606. #endif
  178607. /* Supported compression types for text in PNG files (tEXt, and zTXt).
  178608. * The values of the PNG_TEXT_COMPRESSION_ defines should NOT be changed. */
  178609. #define PNG_TEXT_COMPRESSION_NONE_WR -3
  178610. #define PNG_TEXT_COMPRESSION_zTXt_WR -2
  178611. #define PNG_TEXT_COMPRESSION_NONE -1
  178612. #define PNG_TEXT_COMPRESSION_zTXt 0
  178613. #define PNG_ITXT_COMPRESSION_NONE 1
  178614. #define PNG_ITXT_COMPRESSION_zTXt 2
  178615. #define PNG_TEXT_COMPRESSION_LAST 3 /* Not a valid value */
  178616. /* png_time is a way to hold the time in an machine independent way.
  178617. * Two conversions are provided, both from time_t and struct tm. There
  178618. * is no portable way to convert to either of these structures, as far
  178619. * as I know. If you know of a portable way, send it to me. As a side
  178620. * note - PNG has always been Year 2000 compliant!
  178621. */
  178622. typedef struct png_time_struct
  178623. {
  178624. png_uint_16 year; /* full year, as in, 1995 */
  178625. png_byte month; /* month of year, 1 - 12 */
  178626. png_byte day; /* day of month, 1 - 31 */
  178627. png_byte hour; /* hour of day, 0 - 23 */
  178628. png_byte minute; /* minute of hour, 0 - 59 */
  178629. png_byte second; /* second of minute, 0 - 60 (for leap seconds) */
  178630. } png_time;
  178631. typedef png_time FAR * png_timep;
  178632. typedef png_time FAR * FAR * png_timepp;
  178633. #if defined(PNG_UNKNOWN_CHUNKS_SUPPORTED)
  178634. /* png_unknown_chunk is a structure to hold queued chunks for which there is
  178635. * no specific support. The idea is that we can use this to queue
  178636. * up private chunks for output even though the library doesn't actually
  178637. * know about their semantics.
  178638. */
  178639. typedef struct png_unknown_chunk_t
  178640. {
  178641. png_byte name[5];
  178642. png_byte *data;
  178643. png_size_t size;
  178644. /* libpng-using applications should NOT directly modify this byte. */
  178645. png_byte location; /* mode of operation at read time */
  178646. }
  178647. png_unknown_chunk;
  178648. typedef png_unknown_chunk FAR * png_unknown_chunkp;
  178649. typedef png_unknown_chunk FAR * FAR * png_unknown_chunkpp;
  178650. #endif
  178651. /* png_info is a structure that holds the information in a PNG file so
  178652. * that the application can find out the characteristics of the image.
  178653. * If you are reading the file, this structure will tell you what is
  178654. * in the PNG file. If you are writing the file, fill in the information
  178655. * you want to put into the PNG file, then call png_write_info().
  178656. * The names chosen should be very close to the PNG specification, so
  178657. * consult that document for information about the meaning of each field.
  178658. *
  178659. * With libpng < 0.95, it was only possible to directly set and read the
  178660. * the values in the png_info_struct, which meant that the contents and
  178661. * order of the values had to remain fixed. With libpng 0.95 and later,
  178662. * however, there are now functions that abstract the contents of
  178663. * png_info_struct from the application, so this makes it easier to use
  178664. * libpng with dynamic libraries, and even makes it possible to use
  178665. * libraries that don't have all of the libpng ancillary chunk-handing
  178666. * functionality.
  178667. *
  178668. * In any case, the order of the parameters in png_info_struct should NOT
  178669. * be changed for as long as possible to keep compatibility with applications
  178670. * that use the old direct-access method with png_info_struct.
  178671. *
  178672. * The following members may have allocated storage attached that should be
  178673. * cleaned up before the structure is discarded: palette, trans, text,
  178674. * pcal_purpose, pcal_units, pcal_params, hist, iccp_name, iccp_profile,
  178675. * splt_palettes, scal_unit, row_pointers, and unknowns. By default, these
  178676. * are automatically freed when the info structure is deallocated, if they were
  178677. * allocated internally by libpng. This behavior can be changed by means
  178678. * of the png_data_freer() function.
  178679. *
  178680. * More allocation details: all the chunk-reading functions that
  178681. * change these members go through the corresponding png_set_*
  178682. * functions. A function to clear these members is available: see
  178683. * png_free_data(). The png_set_* functions do not depend on being
  178684. * able to point info structure members to any of the storage they are
  178685. * passed (they make their own copies), EXCEPT that the png_set_text
  178686. * functions use the same storage passed to them in the text_ptr or
  178687. * itxt_ptr structure argument, and the png_set_rows and png_set_unknowns
  178688. * functions do not make their own copies.
  178689. */
  178690. typedef struct png_info_struct
  178691. {
  178692. /* the following are necessary for every PNG file */
  178693. png_uint_32 width; /* width of image in pixels (from IHDR) */
  178694. png_uint_32 height; /* height of image in pixels (from IHDR) */
  178695. png_uint_32 valid; /* valid chunk data (see PNG_INFO_ below) */
  178696. png_uint_32 rowbytes; /* bytes needed to hold an untransformed row */
  178697. png_colorp palette; /* array of color values (valid & PNG_INFO_PLTE) */
  178698. png_uint_16 num_palette; /* number of color entries in "palette" (PLTE) */
  178699. png_uint_16 num_trans; /* number of transparent palette color (tRNS) */
  178700. png_byte bit_depth; /* 1, 2, 4, 8, or 16 bits/channel (from IHDR) */
  178701. png_byte color_type; /* see PNG_COLOR_TYPE_ below (from IHDR) */
  178702. /* The following three should have been named *_method not *_type */
  178703. png_byte compression_type; /* must be PNG_COMPRESSION_TYPE_BASE (IHDR) */
  178704. png_byte filter_type; /* must be PNG_FILTER_TYPE_BASE (from IHDR) */
  178705. png_byte interlace_type; /* One of PNG_INTERLACE_NONE, PNG_INTERLACE_ADAM7 */
  178706. /* The following is informational only on read, and not used on writes. */
  178707. png_byte channels; /* number of data channels per pixel (1, 2, 3, 4) */
  178708. png_byte pixel_depth; /* number of bits per pixel */
  178709. png_byte spare_byte; /* to align the data, and for future use */
  178710. png_byte signature[8]; /* magic bytes read by libpng from start of file */
  178711. /* The rest of the data is optional. If you are reading, check the
  178712. * valid field to see if the information in these are valid. If you
  178713. * are writing, set the valid field to those chunks you want written,
  178714. * and initialize the appropriate fields below.
  178715. */
  178716. #if defined(PNG_gAMA_SUPPORTED) && defined(PNG_FLOATING_POINT_SUPPORTED)
  178717. /* The gAMA chunk describes the gamma characteristics of the system
  178718. * on which the image was created, normally in the range [1.0, 2.5].
  178719. * Data is valid if (valid & PNG_INFO_gAMA) is non-zero.
  178720. */
  178721. float gamma; /* gamma value of image, if (valid & PNG_INFO_gAMA) */
  178722. #endif
  178723. #if defined(PNG_sRGB_SUPPORTED)
  178724. /* GR-P, 0.96a */
  178725. /* Data valid if (valid & PNG_INFO_sRGB) non-zero. */
  178726. png_byte srgb_intent; /* sRGB rendering intent [0, 1, 2, or 3] */
  178727. #endif
  178728. #if defined(PNG_TEXT_SUPPORTED)
  178729. /* The tEXt, and zTXt chunks contain human-readable textual data in
  178730. * uncompressed, compressed, and optionally compressed forms, respectively.
  178731. * The data in "text" is an array of pointers to uncompressed,
  178732. * null-terminated C strings. Each chunk has a keyword that describes the
  178733. * textual data contained in that chunk. Keywords are not required to be
  178734. * unique, and the text string may be empty. Any number of text chunks may
  178735. * be in an image.
  178736. */
  178737. int num_text; /* number of comments read/to write */
  178738. int max_text; /* current size of text array */
  178739. png_textp text; /* array of comments read/to write */
  178740. #endif /* PNG_TEXT_SUPPORTED */
  178741. #if defined(PNG_tIME_SUPPORTED)
  178742. /* The tIME chunk holds the last time the displayed image data was
  178743. * modified. See the png_time struct for the contents of this struct.
  178744. */
  178745. png_time mod_time;
  178746. #endif
  178747. #if defined(PNG_sBIT_SUPPORTED)
  178748. /* The sBIT chunk specifies the number of significant high-order bits
  178749. * in the pixel data. Values are in the range [1, bit_depth], and are
  178750. * only specified for the channels in the pixel data. The contents of
  178751. * the low-order bits is not specified. Data is valid if
  178752. * (valid & PNG_INFO_sBIT) is non-zero.
  178753. */
  178754. png_color_8 sig_bit; /* significant bits in color channels */
  178755. #endif
  178756. #if defined(PNG_tRNS_SUPPORTED) || defined(PNG_READ_EXPAND_SUPPORTED) || \
  178757. defined(PNG_READ_BACKGROUND_SUPPORTED)
  178758. /* The tRNS chunk supplies transparency data for paletted images and
  178759. * other image types that don't need a full alpha channel. There are
  178760. * "num_trans" transparency values for a paletted image, stored in the
  178761. * same order as the palette colors, starting from index 0. Values
  178762. * for the data are in the range [0, 255], ranging from fully transparent
  178763. * to fully opaque, respectively. For non-paletted images, there is a
  178764. * single color specified that should be treated as fully transparent.
  178765. * Data is valid if (valid & PNG_INFO_tRNS) is non-zero.
  178766. */
  178767. png_bytep trans; /* transparent values for paletted image */
  178768. png_color_16 trans_values; /* transparent color for non-palette image */
  178769. #endif
  178770. #if defined(PNG_bKGD_SUPPORTED) || defined(PNG_READ_BACKGROUND_SUPPORTED)
  178771. /* The bKGD chunk gives the suggested image background color if the
  178772. * display program does not have its own background color and the image
  178773. * is needs to composited onto a background before display. The colors
  178774. * in "background" are normally in the same color space/depth as the
  178775. * pixel data. Data is valid if (valid & PNG_INFO_bKGD) is non-zero.
  178776. */
  178777. png_color_16 background;
  178778. #endif
  178779. #if defined(PNG_oFFs_SUPPORTED)
  178780. /* The oFFs chunk gives the offset in "offset_unit_type" units rightwards
  178781. * and downwards from the top-left corner of the display, page, or other
  178782. * application-specific co-ordinate space. See the PNG_OFFSET_ defines
  178783. * below for the unit types. Valid if (valid & PNG_INFO_oFFs) non-zero.
  178784. */
  178785. png_int_32 x_offset; /* x offset on page */
  178786. png_int_32 y_offset; /* y offset on page */
  178787. png_byte offset_unit_type; /* offset units type */
  178788. #endif
  178789. #if defined(PNG_pHYs_SUPPORTED)
  178790. /* The pHYs chunk gives the physical pixel density of the image for
  178791. * display or printing in "phys_unit_type" units (see PNG_RESOLUTION_
  178792. * defines below). Data is valid if (valid & PNG_INFO_pHYs) is non-zero.
  178793. */
  178794. png_uint_32 x_pixels_per_unit; /* horizontal pixel density */
  178795. png_uint_32 y_pixels_per_unit; /* vertical pixel density */
  178796. png_byte phys_unit_type; /* resolution type (see PNG_RESOLUTION_ below) */
  178797. #endif
  178798. #if defined(PNG_hIST_SUPPORTED)
  178799. /* The hIST chunk contains the relative frequency or importance of the
  178800. * various palette entries, so that a viewer can intelligently select a
  178801. * reduced-color palette, if required. Data is an array of "num_palette"
  178802. * values in the range [0,65535]. Data valid if (valid & PNG_INFO_hIST)
  178803. * is non-zero.
  178804. */
  178805. png_uint_16p hist;
  178806. #endif
  178807. #ifdef PNG_cHRM_SUPPORTED
  178808. /* The cHRM chunk describes the CIE color characteristics of the monitor
  178809. * on which the PNG was created. This data allows the viewer to do gamut
  178810. * mapping of the input image to ensure that the viewer sees the same
  178811. * colors in the image as the creator. Values are in the range
  178812. * [0.0, 0.8]. Data valid if (valid & PNG_INFO_cHRM) non-zero.
  178813. */
  178814. #ifdef PNG_FLOATING_POINT_SUPPORTED
  178815. float x_white;
  178816. float y_white;
  178817. float x_red;
  178818. float y_red;
  178819. float x_green;
  178820. float y_green;
  178821. float x_blue;
  178822. float y_blue;
  178823. #endif
  178824. #endif
  178825. #if defined(PNG_pCAL_SUPPORTED)
  178826. /* The pCAL chunk describes a transformation between the stored pixel
  178827. * values and original physical data values used to create the image.
  178828. * The integer range [0, 2^bit_depth - 1] maps to the floating-point
  178829. * range given by [pcal_X0, pcal_X1], and are further transformed by a
  178830. * (possibly non-linear) transformation function given by "pcal_type"
  178831. * and "pcal_params" into "pcal_units". Please see the PNG_EQUATION_
  178832. * defines below, and the PNG-Group's PNG extensions document for a
  178833. * complete description of the transformations and how they should be
  178834. * implemented, and for a description of the ASCII parameter strings.
  178835. * Data values are valid if (valid & PNG_INFO_pCAL) non-zero.
  178836. */
  178837. png_charp pcal_purpose; /* pCAL chunk description string */
  178838. png_int_32 pcal_X0; /* minimum value */
  178839. png_int_32 pcal_X1; /* maximum value */
  178840. png_charp pcal_units; /* Latin-1 string giving physical units */
  178841. png_charpp pcal_params; /* ASCII strings containing parameter values */
  178842. png_byte pcal_type; /* equation type (see PNG_EQUATION_ below) */
  178843. png_byte pcal_nparams; /* number of parameters given in pcal_params */
  178844. #endif
  178845. /* New members added in libpng-1.0.6 */
  178846. #ifdef PNG_FREE_ME_SUPPORTED
  178847. png_uint_32 free_me; /* flags items libpng is responsible for freeing */
  178848. #endif
  178849. #if defined(PNG_UNKNOWN_CHUNKS_SUPPORTED)
  178850. /* storage for unknown chunks that the library doesn't recognize. */
  178851. png_unknown_chunkp unknown_chunks;
  178852. png_size_t unknown_chunks_num;
  178853. #endif
  178854. #if defined(PNG_iCCP_SUPPORTED)
  178855. /* iCCP chunk data. */
  178856. png_charp iccp_name; /* profile name */
  178857. png_charp iccp_profile; /* International Color Consortium profile data */
  178858. /* Note to maintainer: should be png_bytep */
  178859. png_uint_32 iccp_proflen; /* ICC profile data length */
  178860. png_byte iccp_compression; /* Always zero */
  178861. #endif
  178862. #if defined(PNG_sPLT_SUPPORTED)
  178863. /* data on sPLT chunks (there may be more than one). */
  178864. png_sPLT_tp splt_palettes;
  178865. png_uint_32 splt_palettes_num;
  178866. #endif
  178867. #if defined(PNG_sCAL_SUPPORTED)
  178868. /* The sCAL chunk describes the actual physical dimensions of the
  178869. * subject matter of the graphic. The chunk contains a unit specification
  178870. * a byte value, and two ASCII strings representing floating-point
  178871. * values. The values are width and height corresponsing to one pixel
  178872. * in the image. This external representation is converted to double
  178873. * here. Data values are valid if (valid & PNG_INFO_sCAL) is non-zero.
  178874. */
  178875. png_byte scal_unit; /* unit of physical scale */
  178876. #ifdef PNG_FLOATING_POINT_SUPPORTED
  178877. double scal_pixel_width; /* width of one pixel */
  178878. double scal_pixel_height; /* height of one pixel */
  178879. #endif
  178880. #ifdef PNG_FIXED_POINT_SUPPORTED
  178881. png_charp scal_s_width; /* string containing height */
  178882. png_charp scal_s_height; /* string containing width */
  178883. #endif
  178884. #endif
  178885. #if defined(PNG_INFO_IMAGE_SUPPORTED)
  178886. /* Memory has been allocated if (valid & PNG_ALLOCATED_INFO_ROWS) non-zero */
  178887. /* Data valid if (valid & PNG_INFO_IDAT) non-zero */
  178888. png_bytepp row_pointers; /* the image bits */
  178889. #endif
  178890. #if defined(PNG_FIXED_POINT_SUPPORTED) && defined(PNG_gAMA_SUPPORTED)
  178891. png_fixed_point int_gamma; /* gamma of image, if (valid & PNG_INFO_gAMA) */
  178892. #endif
  178893. #if defined(PNG_cHRM_SUPPORTED) && defined(PNG_FIXED_POINT_SUPPORTED)
  178894. png_fixed_point int_x_white;
  178895. png_fixed_point int_y_white;
  178896. png_fixed_point int_x_red;
  178897. png_fixed_point int_y_red;
  178898. png_fixed_point int_x_green;
  178899. png_fixed_point int_y_green;
  178900. png_fixed_point int_x_blue;
  178901. png_fixed_point int_y_blue;
  178902. #endif
  178903. } png_info;
  178904. typedef png_info FAR * png_infop;
  178905. typedef png_info FAR * FAR * png_infopp;
  178906. /* Maximum positive integer used in PNG is (2^31)-1 */
  178907. #define PNG_UINT_31_MAX ((png_uint_32)0x7fffffffL)
  178908. #define PNG_UINT_32_MAX ((png_uint_32)(-1))
  178909. #define PNG_SIZE_MAX ((png_size_t)(-1))
  178910. #if defined(PNG_1_0_X) || defined (PNG_1_2_X)
  178911. /* PNG_MAX_UINT is deprecated; use PNG_UINT_31_MAX instead. */
  178912. #define PNG_MAX_UINT PNG_UINT_31_MAX
  178913. #endif
  178914. /* These describe the color_type field in png_info. */
  178915. /* color type masks */
  178916. #define PNG_COLOR_MASK_PALETTE 1
  178917. #define PNG_COLOR_MASK_COLOR 2
  178918. #define PNG_COLOR_MASK_ALPHA 4
  178919. /* color types. Note that not all combinations are legal */
  178920. #define PNG_COLOR_TYPE_GRAY 0
  178921. #define PNG_COLOR_TYPE_PALETTE (PNG_COLOR_MASK_COLOR | PNG_COLOR_MASK_PALETTE)
  178922. #define PNG_COLOR_TYPE_RGB (PNG_COLOR_MASK_COLOR)
  178923. #define PNG_COLOR_TYPE_RGB_ALPHA (PNG_COLOR_MASK_COLOR | PNG_COLOR_MASK_ALPHA)
  178924. #define PNG_COLOR_TYPE_GRAY_ALPHA (PNG_COLOR_MASK_ALPHA)
  178925. /* aliases */
  178926. #define PNG_COLOR_TYPE_RGBA PNG_COLOR_TYPE_RGB_ALPHA
  178927. #define PNG_COLOR_TYPE_GA PNG_COLOR_TYPE_GRAY_ALPHA
  178928. /* This is for compression type. PNG 1.0-1.2 only define the single type. */
  178929. #define PNG_COMPRESSION_TYPE_BASE 0 /* Deflate method 8, 32K window */
  178930. #define PNG_COMPRESSION_TYPE_DEFAULT PNG_COMPRESSION_TYPE_BASE
  178931. /* This is for filter type. PNG 1.0-1.2 only define the single type. */
  178932. #define PNG_FILTER_TYPE_BASE 0 /* Single row per-byte filtering */
  178933. #define PNG_INTRAPIXEL_DIFFERENCING 64 /* Used only in MNG datastreams */
  178934. #define PNG_FILTER_TYPE_DEFAULT PNG_FILTER_TYPE_BASE
  178935. /* These are for the interlacing type. These values should NOT be changed. */
  178936. #define PNG_INTERLACE_NONE 0 /* Non-interlaced image */
  178937. #define PNG_INTERLACE_ADAM7 1 /* Adam7 interlacing */
  178938. #define PNG_INTERLACE_LAST 2 /* Not a valid value */
  178939. /* These are for the oFFs chunk. These values should NOT be changed. */
  178940. #define PNG_OFFSET_PIXEL 0 /* Offset in pixels */
  178941. #define PNG_OFFSET_MICROMETER 1 /* Offset in micrometers (1/10^6 meter) */
  178942. #define PNG_OFFSET_LAST 2 /* Not a valid value */
  178943. /* These are for the pCAL chunk. These values should NOT be changed. */
  178944. #define PNG_EQUATION_LINEAR 0 /* Linear transformation */
  178945. #define PNG_EQUATION_BASE_E 1 /* Exponential base e transform */
  178946. #define PNG_EQUATION_ARBITRARY 2 /* Arbitrary base exponential transform */
  178947. #define PNG_EQUATION_HYPERBOLIC 3 /* Hyperbolic sine transformation */
  178948. #define PNG_EQUATION_LAST 4 /* Not a valid value */
  178949. /* These are for the sCAL chunk. These values should NOT be changed. */
  178950. #define PNG_SCALE_UNKNOWN 0 /* unknown unit (image scale) */
  178951. #define PNG_SCALE_METER 1 /* meters per pixel */
  178952. #define PNG_SCALE_RADIAN 2 /* radians per pixel */
  178953. #define PNG_SCALE_LAST 3 /* Not a valid value */
  178954. /* These are for the pHYs chunk. These values should NOT be changed. */
  178955. #define PNG_RESOLUTION_UNKNOWN 0 /* pixels/unknown unit (aspect ratio) */
  178956. #define PNG_RESOLUTION_METER 1 /* pixels/meter */
  178957. #define PNG_RESOLUTION_LAST 2 /* Not a valid value */
  178958. /* These are for the sRGB chunk. These values should NOT be changed. */
  178959. #define PNG_sRGB_INTENT_PERCEPTUAL 0
  178960. #define PNG_sRGB_INTENT_RELATIVE 1
  178961. #define PNG_sRGB_INTENT_SATURATION 2
  178962. #define PNG_sRGB_INTENT_ABSOLUTE 3
  178963. #define PNG_sRGB_INTENT_LAST 4 /* Not a valid value */
  178964. /* This is for text chunks */
  178965. #define PNG_KEYWORD_MAX_LENGTH 79
  178966. /* Maximum number of entries in PLTE/sPLT/tRNS arrays */
  178967. #define PNG_MAX_PALETTE_LENGTH 256
  178968. /* These determine if an ancillary chunk's data has been successfully read
  178969. * from the PNG header, or if the application has filled in the corresponding
  178970. * data in the info_struct to be written into the output file. The values
  178971. * of the PNG_INFO_<chunk> defines should NOT be changed.
  178972. */
  178973. #define PNG_INFO_gAMA 0x0001
  178974. #define PNG_INFO_sBIT 0x0002
  178975. #define PNG_INFO_cHRM 0x0004
  178976. #define PNG_INFO_PLTE 0x0008
  178977. #define PNG_INFO_tRNS 0x0010
  178978. #define PNG_INFO_bKGD 0x0020
  178979. #define PNG_INFO_hIST 0x0040
  178980. #define PNG_INFO_pHYs 0x0080
  178981. #define PNG_INFO_oFFs 0x0100
  178982. #define PNG_INFO_tIME 0x0200
  178983. #define PNG_INFO_pCAL 0x0400
  178984. #define PNG_INFO_sRGB 0x0800 /* GR-P, 0.96a */
  178985. #define PNG_INFO_iCCP 0x1000 /* ESR, 1.0.6 */
  178986. #define PNG_INFO_sPLT 0x2000 /* ESR, 1.0.6 */
  178987. #define PNG_INFO_sCAL 0x4000 /* ESR, 1.0.6 */
  178988. #define PNG_INFO_IDAT 0x8000L /* ESR, 1.0.6 */
  178989. /* This is used for the transformation routines, as some of them
  178990. * change these values for the row. It also should enable using
  178991. * the routines for other purposes.
  178992. */
  178993. typedef struct png_row_info_struct
  178994. {
  178995. png_uint_32 width; /* width of row */
  178996. png_uint_32 rowbytes; /* number of bytes in row */
  178997. png_byte color_type; /* color type of row */
  178998. png_byte bit_depth; /* bit depth of row */
  178999. png_byte channels; /* number of channels (1, 2, 3, or 4) */
  179000. png_byte pixel_depth; /* bits per pixel (depth * channels) */
  179001. } png_row_info;
  179002. typedef png_row_info FAR * png_row_infop;
  179003. typedef png_row_info FAR * FAR * png_row_infopp;
  179004. /* These are the function types for the I/O functions and for the functions
  179005. * that allow the user to override the default I/O functions with his or her
  179006. * own. The png_error_ptr type should match that of user-supplied warning
  179007. * and error functions, while the png_rw_ptr type should match that of the
  179008. * user read/write data functions.
  179009. */
  179010. typedef struct png_struct_def png_struct;
  179011. typedef png_struct FAR * png_structp;
  179012. typedef void (PNGAPI *png_error_ptr) PNGARG((png_structp, png_const_charp));
  179013. typedef void (PNGAPI *png_rw_ptr) PNGARG((png_structp, png_bytep, png_size_t));
  179014. typedef void (PNGAPI *png_flush_ptr) PNGARG((png_structp));
  179015. typedef void (PNGAPI *png_read_status_ptr) PNGARG((png_structp, png_uint_32,
  179016. int));
  179017. typedef void (PNGAPI *png_write_status_ptr) PNGARG((png_structp, png_uint_32,
  179018. int));
  179019. #ifdef PNG_PROGRESSIVE_READ_SUPPORTED
  179020. typedef void (PNGAPI *png_progressive_info_ptr) PNGARG((png_structp, png_infop));
  179021. typedef void (PNGAPI *png_progressive_end_ptr) PNGARG((png_structp, png_infop));
  179022. typedef void (PNGAPI *png_progressive_row_ptr) PNGARG((png_structp, png_bytep,
  179023. png_uint_32, int));
  179024. #endif
  179025. #if defined(PNG_READ_USER_TRANSFORM_SUPPORTED) || \
  179026. defined(PNG_WRITE_USER_TRANSFORM_SUPPORTED) || \
  179027. defined(PNG_LEGACY_SUPPORTED)
  179028. typedef void (PNGAPI *png_user_transform_ptr) PNGARG((png_structp,
  179029. png_row_infop, png_bytep));
  179030. #endif
  179031. #if defined(PNG_USER_CHUNKS_SUPPORTED)
  179032. typedef int (PNGAPI *png_user_chunk_ptr) PNGARG((png_structp, png_unknown_chunkp));
  179033. #endif
  179034. #if defined(PNG_UNKNOWN_CHUNKS_SUPPORTED)
  179035. typedef void (PNGAPI *png_unknown_chunk_ptr) PNGARG((png_structp));
  179036. #endif
  179037. /* Transform masks for the high-level interface */
  179038. #define PNG_TRANSFORM_IDENTITY 0x0000 /* read and write */
  179039. #define PNG_TRANSFORM_STRIP_16 0x0001 /* read only */
  179040. #define PNG_TRANSFORM_STRIP_ALPHA 0x0002 /* read only */
  179041. #define PNG_TRANSFORM_PACKING 0x0004 /* read and write */
  179042. #define PNG_TRANSFORM_PACKSWAP 0x0008 /* read and write */
  179043. #define PNG_TRANSFORM_EXPAND 0x0010 /* read only */
  179044. #define PNG_TRANSFORM_INVERT_MONO 0x0020 /* read and write */
  179045. #define PNG_TRANSFORM_SHIFT 0x0040 /* read and write */
  179046. #define PNG_TRANSFORM_BGR 0x0080 /* read and write */
  179047. #define PNG_TRANSFORM_SWAP_ALPHA 0x0100 /* read and write */
  179048. #define PNG_TRANSFORM_SWAP_ENDIAN 0x0200 /* read and write */
  179049. #define PNG_TRANSFORM_INVERT_ALPHA 0x0400 /* read and write */
  179050. #define PNG_TRANSFORM_STRIP_FILLER 0x0800 /* WRITE only */
  179051. /* Flags for MNG supported features */
  179052. #define PNG_FLAG_MNG_EMPTY_PLTE 0x01
  179053. #define PNG_FLAG_MNG_FILTER_64 0x04
  179054. #define PNG_ALL_MNG_FEATURES 0x05
  179055. typedef png_voidp (*png_malloc_ptr) PNGARG((png_structp, png_size_t));
  179056. typedef void (*png_free_ptr) PNGARG((png_structp, png_voidp));
  179057. /* The structure that holds the information to read and write PNG files.
  179058. * The only people who need to care about what is inside of this are the
  179059. * people who will be modifying the library for their own special needs.
  179060. * It should NOT be accessed directly by an application, except to store
  179061. * the jmp_buf.
  179062. */
  179063. struct png_struct_def
  179064. {
  179065. #ifdef PNG_SETJMP_SUPPORTED
  179066. jmp_buf jmpbuf; /* used in png_error */
  179067. #endif
  179068. png_error_ptr error_fn; /* function for printing errors and aborting */
  179069. png_error_ptr warning_fn; /* function for printing warnings */
  179070. png_voidp error_ptr; /* user supplied struct for error functions */
  179071. png_rw_ptr write_data_fn; /* function for writing output data */
  179072. png_rw_ptr read_data_fn; /* function for reading input data */
  179073. png_voidp io_ptr; /* ptr to application struct for I/O functions */
  179074. #if defined(PNG_READ_USER_TRANSFORM_SUPPORTED)
  179075. png_user_transform_ptr read_user_transform_fn; /* user read transform */
  179076. #endif
  179077. #if defined(PNG_WRITE_USER_TRANSFORM_SUPPORTED)
  179078. png_user_transform_ptr write_user_transform_fn; /* user write transform */
  179079. #endif
  179080. /* These were added in libpng-1.0.2 */
  179081. #if defined(PNG_USER_TRANSFORM_PTR_SUPPORTED)
  179082. #if defined(PNG_READ_USER_TRANSFORM_SUPPORTED) || \
  179083. defined(PNG_WRITE_USER_TRANSFORM_SUPPORTED)
  179084. png_voidp user_transform_ptr; /* user supplied struct for user transform */
  179085. png_byte user_transform_depth; /* bit depth of user transformed pixels */
  179086. png_byte user_transform_channels; /* channels in user transformed pixels */
  179087. #endif
  179088. #endif
  179089. png_uint_32 mode; /* tells us where we are in the PNG file */
  179090. png_uint_32 flags; /* flags indicating various things to libpng */
  179091. png_uint_32 transformations; /* which transformations to perform */
  179092. z_stream zstream; /* pointer to decompression structure (below) */
  179093. png_bytep zbuf; /* buffer for zlib */
  179094. png_size_t zbuf_size; /* size of zbuf */
  179095. int zlib_level; /* holds zlib compression level */
  179096. int zlib_method; /* holds zlib compression method */
  179097. int zlib_window_bits; /* holds zlib compression window bits */
  179098. int zlib_mem_level; /* holds zlib compression memory level */
  179099. int zlib_strategy; /* holds zlib compression strategy */
  179100. png_uint_32 width; /* width of image in pixels */
  179101. png_uint_32 height; /* height of image in pixels */
  179102. png_uint_32 num_rows; /* number of rows in current pass */
  179103. png_uint_32 usr_width; /* width of row at start of write */
  179104. png_uint_32 rowbytes; /* size of row in bytes */
  179105. png_uint_32 irowbytes; /* size of current interlaced row in bytes */
  179106. png_uint_32 iwidth; /* width of current interlaced row in pixels */
  179107. png_uint_32 row_number; /* current row in interlace pass */
  179108. png_bytep prev_row; /* buffer to save previous (unfiltered) row */
  179109. png_bytep row_buf; /* buffer to save current (unfiltered) row */
  179110. png_bytep sub_row; /* buffer to save "sub" row when filtering */
  179111. png_bytep up_row; /* buffer to save "up" row when filtering */
  179112. png_bytep avg_row; /* buffer to save "avg" row when filtering */
  179113. png_bytep paeth_row; /* buffer to save "Paeth" row when filtering */
  179114. png_row_info row_info; /* used for transformation routines */
  179115. png_uint_32 idat_size; /* current IDAT size for read */
  179116. png_uint_32 crc; /* current chunk CRC value */
  179117. png_colorp palette; /* palette from the input file */
  179118. png_uint_16 num_palette; /* number of color entries in palette */
  179119. png_uint_16 num_trans; /* number of transparency values */
  179120. png_byte chunk_name[5]; /* null-terminated name of current chunk */
  179121. png_byte compression; /* file compression type (always 0) */
  179122. png_byte filter; /* file filter type (always 0) */
  179123. png_byte interlaced; /* PNG_INTERLACE_NONE, PNG_INTERLACE_ADAM7 */
  179124. png_byte pass; /* current interlace pass (0 - 6) */
  179125. png_byte do_filter; /* row filter flags (see PNG_FILTER_ below ) */
  179126. png_byte color_type; /* color type of file */
  179127. png_byte bit_depth; /* bit depth of file */
  179128. png_byte usr_bit_depth; /* bit depth of users row */
  179129. png_byte pixel_depth; /* number of bits per pixel */
  179130. png_byte channels; /* number of channels in file */
  179131. png_byte usr_channels; /* channels at start of write */
  179132. png_byte sig_bytes; /* magic bytes read/written from start of file */
  179133. #if defined(PNG_READ_FILLER_SUPPORTED) || defined(PNG_WRITE_FILLER_SUPPORTED)
  179134. #ifdef PNG_LEGACY_SUPPORTED
  179135. png_byte filler; /* filler byte for pixel expansion */
  179136. #else
  179137. png_uint_16 filler; /* filler bytes for pixel expansion */
  179138. #endif
  179139. #endif
  179140. #if defined(PNG_bKGD_SUPPORTED)
  179141. png_byte background_gamma_type;
  179142. # ifdef PNG_FLOATING_POINT_SUPPORTED
  179143. float background_gamma;
  179144. # endif
  179145. png_color_16 background; /* background color in screen gamma space */
  179146. #if defined(PNG_READ_GAMMA_SUPPORTED)
  179147. png_color_16 background_1; /* background normalized to gamma 1.0 */
  179148. #endif
  179149. #endif /* PNG_bKGD_SUPPORTED */
  179150. #if defined(PNG_WRITE_FLUSH_SUPPORTED)
  179151. png_flush_ptr output_flush_fn;/* Function for flushing output */
  179152. png_uint_32 flush_dist; /* how many rows apart to flush, 0 - no flush */
  179153. png_uint_32 flush_rows; /* number of rows written since last flush */
  179154. #endif
  179155. #if defined(PNG_READ_GAMMA_SUPPORTED) || defined(PNG_READ_BACKGROUND_SUPPORTED)
  179156. int gamma_shift; /* number of "insignificant" bits 16-bit gamma */
  179157. #ifdef PNG_FLOATING_POINT_SUPPORTED
  179158. float gamma; /* file gamma value */
  179159. float screen_gamma; /* screen gamma value (display_exponent) */
  179160. #endif
  179161. #endif
  179162. #if defined(PNG_READ_GAMMA_SUPPORTED) || defined(PNG_READ_BACKGROUND_SUPPORTED)
  179163. png_bytep gamma_table; /* gamma table for 8-bit depth files */
  179164. png_bytep gamma_from_1; /* converts from 1.0 to screen */
  179165. png_bytep gamma_to_1; /* converts from file to 1.0 */
  179166. png_uint_16pp gamma_16_table; /* gamma table for 16-bit depth files */
  179167. png_uint_16pp gamma_16_from_1; /* converts from 1.0 to screen */
  179168. png_uint_16pp gamma_16_to_1; /* converts from file to 1.0 */
  179169. #endif
  179170. #if defined(PNG_READ_GAMMA_SUPPORTED) || defined(PNG_sBIT_SUPPORTED)
  179171. png_color_8 sig_bit; /* significant bits in each available channel */
  179172. #endif
  179173. #if defined(PNG_READ_SHIFT_SUPPORTED) || defined(PNG_WRITE_SHIFT_SUPPORTED)
  179174. png_color_8 shift; /* shift for significant bit tranformation */
  179175. #endif
  179176. #if defined(PNG_tRNS_SUPPORTED) || defined(PNG_READ_BACKGROUND_SUPPORTED) \
  179177. || defined(PNG_READ_EXPAND_SUPPORTED) || defined(PNG_READ_BACKGROUND_SUPPORTED)
  179178. png_bytep trans; /* transparency values for paletted files */
  179179. png_color_16 trans_values; /* transparency values for non-paletted files */
  179180. #endif
  179181. png_read_status_ptr read_row_fn; /* called after each row is decoded */
  179182. png_write_status_ptr write_row_fn; /* called after each row is encoded */
  179183. #ifdef PNG_PROGRESSIVE_READ_SUPPORTED
  179184. png_progressive_info_ptr info_fn; /* called after header data fully read */
  179185. png_progressive_row_ptr row_fn; /* called after each prog. row is decoded */
  179186. png_progressive_end_ptr end_fn; /* called after image is complete */
  179187. png_bytep save_buffer_ptr; /* current location in save_buffer */
  179188. png_bytep save_buffer; /* buffer for previously read data */
  179189. png_bytep current_buffer_ptr; /* current location in current_buffer */
  179190. png_bytep current_buffer; /* buffer for recently used data */
  179191. png_uint_32 push_length; /* size of current input chunk */
  179192. png_uint_32 skip_length; /* bytes to skip in input data */
  179193. png_size_t save_buffer_size; /* amount of data now in save_buffer */
  179194. png_size_t save_buffer_max; /* total size of save_buffer */
  179195. png_size_t buffer_size; /* total amount of available input data */
  179196. png_size_t current_buffer_size; /* amount of data now in current_buffer */
  179197. int process_mode; /* what push library is currently doing */
  179198. int cur_palette; /* current push library palette index */
  179199. # if defined(PNG_TEXT_SUPPORTED)
  179200. png_size_t current_text_size; /* current size of text input data */
  179201. png_size_t current_text_left; /* how much text left to read in input */
  179202. png_charp current_text; /* current text chunk buffer */
  179203. png_charp current_text_ptr; /* current location in current_text */
  179204. # endif /* PNG_TEXT_SUPPORTED */
  179205. #endif /* PNG_PROGRESSIVE_READ_SUPPORTED */
  179206. #if defined(__TURBOC__) && !defined(_Windows) && !defined(__FLAT__)
  179207. /* for the Borland special 64K segment handler */
  179208. png_bytepp offset_table_ptr;
  179209. png_bytep offset_table;
  179210. png_uint_16 offset_table_number;
  179211. png_uint_16 offset_table_count;
  179212. png_uint_16 offset_table_count_free;
  179213. #endif
  179214. #if defined(PNG_READ_DITHER_SUPPORTED)
  179215. png_bytep palette_lookup; /* lookup table for dithering */
  179216. png_bytep dither_index; /* index translation for palette files */
  179217. #endif
  179218. #if defined(PNG_READ_DITHER_SUPPORTED) || defined(PNG_hIST_SUPPORTED)
  179219. png_uint_16p hist; /* histogram */
  179220. #endif
  179221. #if defined(PNG_WRITE_WEIGHTED_FILTER_SUPPORTED)
  179222. png_byte heuristic_method; /* heuristic for row filter selection */
  179223. png_byte num_prev_filters; /* number of weights for previous rows */
  179224. png_bytep prev_filters; /* filter type(s) of previous row(s) */
  179225. png_uint_16p filter_weights; /* weight(s) for previous line(s) */
  179226. png_uint_16p inv_filter_weights; /* 1/weight(s) for previous line(s) */
  179227. png_uint_16p filter_costs; /* relative filter calculation cost */
  179228. png_uint_16p inv_filter_costs; /* 1/relative filter calculation cost */
  179229. #endif
  179230. #if defined(PNG_TIME_RFC1123_SUPPORTED)
  179231. png_charp time_buffer; /* String to hold RFC 1123 time text */
  179232. #endif
  179233. /* New members added in libpng-1.0.6 */
  179234. #ifdef PNG_FREE_ME_SUPPORTED
  179235. png_uint_32 free_me; /* flags items libpng is responsible for freeing */
  179236. #endif
  179237. #if defined(PNG_USER_CHUNKS_SUPPORTED)
  179238. png_voidp user_chunk_ptr;
  179239. png_user_chunk_ptr read_user_chunk_fn; /* user read chunk handler */
  179240. #endif
  179241. #if defined(PNG_UNKNOWN_CHUNKS_SUPPORTED)
  179242. int num_chunk_list;
  179243. png_bytep chunk_list;
  179244. #endif
  179245. /* New members added in libpng-1.0.3 */
  179246. #if defined(PNG_READ_RGB_TO_GRAY_SUPPORTED)
  179247. png_byte rgb_to_gray_status;
  179248. /* These were changed from png_byte in libpng-1.0.6 */
  179249. png_uint_16 rgb_to_gray_red_coeff;
  179250. png_uint_16 rgb_to_gray_green_coeff;
  179251. png_uint_16 rgb_to_gray_blue_coeff;
  179252. #endif
  179253. /* New member added in libpng-1.0.4 (renamed in 1.0.9) */
  179254. #if defined(PNG_MNG_FEATURES_SUPPORTED) || \
  179255. defined(PNG_READ_EMPTY_PLTE_SUPPORTED) || \
  179256. defined(PNG_WRITE_EMPTY_PLTE_SUPPORTED)
  179257. /* changed from png_byte to png_uint_32 at version 1.2.0 */
  179258. #ifdef PNG_1_0_X
  179259. png_byte mng_features_permitted;
  179260. #else
  179261. png_uint_32 mng_features_permitted;
  179262. #endif /* PNG_1_0_X */
  179263. #endif
  179264. /* New member added in libpng-1.0.7 */
  179265. #if defined(PNG_READ_GAMMA_SUPPORTED) || defined(PNG_READ_BACKGROUND_SUPPORTED)
  179266. png_fixed_point int_gamma;
  179267. #endif
  179268. /* New member added in libpng-1.0.9, ifdef'ed out in 1.0.12, enabled in 1.2.0 */
  179269. #if defined(PNG_MNG_FEATURES_SUPPORTED)
  179270. png_byte filter_type;
  179271. #endif
  179272. #if defined(PNG_1_0_X)
  179273. /* New member added in libpng-1.0.10, ifdef'ed out in 1.2.0 */
  179274. png_uint_32 row_buf_size;
  179275. #endif
  179276. /* New members added in libpng-1.2.0 */
  179277. #if defined(PNG_ASSEMBLER_CODE_SUPPORTED)
  179278. # if !defined(PNG_1_0_X)
  179279. # if defined(PNG_MMX_CODE_SUPPORTED)
  179280. png_byte mmx_bitdepth_threshold;
  179281. png_uint_32 mmx_rowbytes_threshold;
  179282. # endif
  179283. png_uint_32 asm_flags;
  179284. # endif
  179285. #endif
  179286. /* New members added in libpng-1.0.2 but first enabled by default in 1.2.0 */
  179287. #ifdef PNG_USER_MEM_SUPPORTED
  179288. png_voidp mem_ptr; /* user supplied struct for mem functions */
  179289. png_malloc_ptr malloc_fn; /* function for allocating memory */
  179290. png_free_ptr free_fn; /* function for freeing memory */
  179291. #endif
  179292. /* New member added in libpng-1.0.13 and 1.2.0 */
  179293. png_bytep big_row_buf; /* buffer to save current (unfiltered) row */
  179294. #if defined(PNG_READ_DITHER_SUPPORTED)
  179295. /* The following three members were added at version 1.0.14 and 1.2.4 */
  179296. png_bytep dither_sort; /* working sort array */
  179297. png_bytep index_to_palette; /* where the original index currently is */
  179298. /* in the palette */
  179299. png_bytep palette_to_index; /* which original index points to this */
  179300. /* palette color */
  179301. #endif
  179302. /* New members added in libpng-1.0.16 and 1.2.6 */
  179303. png_byte compression_type;
  179304. #ifdef PNG_SET_USER_LIMITS_SUPPORTED
  179305. png_uint_32 user_width_max;
  179306. png_uint_32 user_height_max;
  179307. #endif
  179308. /* New member added in libpng-1.0.25 and 1.2.17 */
  179309. #if defined(PNG_UNKNOWN_CHUNKS_SUPPORTED)
  179310. /* storage for unknown chunk that the library doesn't recognize. */
  179311. png_unknown_chunk unknown_chunk;
  179312. #endif
  179313. };
  179314. /* This triggers a compiler error in png.c, if png.c and png.h
  179315. * do not agree upon the version number.
  179316. */
  179317. typedef png_structp version_1_2_21;
  179318. typedef png_struct FAR * FAR * png_structpp;
  179319. /* Here are the function definitions most commonly used. This is not
  179320. * the place to find out how to use libpng. See libpng.txt for the
  179321. * full explanation, see example.c for the summary. This just provides
  179322. * a simple one line description of the use of each function.
  179323. */
  179324. /* Returns the version number of the library */
  179325. extern PNG_EXPORT(png_uint_32,png_access_version_number) PNGARG((void));
  179326. /* Tell lib we have already handled the first <num_bytes> magic bytes.
  179327. * Handling more than 8 bytes from the beginning of the file is an error.
  179328. */
  179329. extern PNG_EXPORT(void,png_set_sig_bytes) PNGARG((png_structp png_ptr,
  179330. int num_bytes));
  179331. /* Check sig[start] through sig[start + num_to_check - 1] to see if it's a
  179332. * PNG file. Returns zero if the supplied bytes match the 8-byte PNG
  179333. * signature, and non-zero otherwise. Having num_to_check == 0 or
  179334. * start > 7 will always fail (ie return non-zero).
  179335. */
  179336. extern PNG_EXPORT(int,png_sig_cmp) PNGARG((png_bytep sig, png_size_t start,
  179337. png_size_t num_to_check));
  179338. /* Simple signature checking function. This is the same as calling
  179339. * png_check_sig(sig, n) := !png_sig_cmp(sig, 0, n).
  179340. */
  179341. extern PNG_EXPORT(int,png_check_sig) PNGARG((png_bytep sig, int num));
  179342. /* Allocate and initialize png_ptr struct for reading, and any other memory. */
  179343. extern PNG_EXPORT(png_structp,png_create_read_struct)
  179344. PNGARG((png_const_charp user_png_ver, png_voidp error_ptr,
  179345. png_error_ptr error_fn, png_error_ptr warn_fn));
  179346. /* Allocate and initialize png_ptr struct for writing, and any other memory */
  179347. extern PNG_EXPORT(png_structp,png_create_write_struct)
  179348. PNGARG((png_const_charp user_png_ver, png_voidp error_ptr,
  179349. png_error_ptr error_fn, png_error_ptr warn_fn));
  179350. #ifdef PNG_WRITE_SUPPORTED
  179351. extern PNG_EXPORT(png_uint_32,png_get_compression_buffer_size)
  179352. PNGARG((png_structp png_ptr));
  179353. #endif
  179354. #ifdef PNG_WRITE_SUPPORTED
  179355. extern PNG_EXPORT(void,png_set_compression_buffer_size)
  179356. PNGARG((png_structp png_ptr, png_uint_32 size));
  179357. #endif
  179358. /* Reset the compression stream */
  179359. extern PNG_EXPORT(int,png_reset_zstream) PNGARG((png_structp png_ptr));
  179360. /* New functions added in libpng-1.0.2 (not enabled by default until 1.2.0) */
  179361. #ifdef PNG_USER_MEM_SUPPORTED
  179362. extern PNG_EXPORT(png_structp,png_create_read_struct_2)
  179363. PNGARG((png_const_charp user_png_ver, png_voidp error_ptr,
  179364. png_error_ptr error_fn, png_error_ptr warn_fn, png_voidp mem_ptr,
  179365. png_malloc_ptr malloc_fn, png_free_ptr free_fn));
  179366. extern PNG_EXPORT(png_structp,png_create_write_struct_2)
  179367. PNGARG((png_const_charp user_png_ver, png_voidp error_ptr,
  179368. png_error_ptr error_fn, png_error_ptr warn_fn, png_voidp mem_ptr,
  179369. png_malloc_ptr malloc_fn, png_free_ptr free_fn));
  179370. #endif
  179371. /* Write a PNG chunk - size, type, (optional) data, CRC. */
  179372. extern PNG_EXPORT(void,png_write_chunk) PNGARG((png_structp png_ptr,
  179373. png_bytep chunk_name, png_bytep data, png_size_t length));
  179374. /* Write the start of a PNG chunk - length and chunk name. */
  179375. extern PNG_EXPORT(void,png_write_chunk_start) PNGARG((png_structp png_ptr,
  179376. png_bytep chunk_name, png_uint_32 length));
  179377. /* Write the data of a PNG chunk started with png_write_chunk_start(). */
  179378. extern PNG_EXPORT(void,png_write_chunk_data) PNGARG((png_structp png_ptr,
  179379. png_bytep data, png_size_t length));
  179380. /* Finish a chunk started with png_write_chunk_start() (includes CRC). */
  179381. extern PNG_EXPORT(void,png_write_chunk_end) PNGARG((png_structp png_ptr));
  179382. /* Allocate and initialize the info structure */
  179383. extern PNG_EXPORT(png_infop,png_create_info_struct)
  179384. PNGARG((png_structp png_ptr));
  179385. #if defined(PNG_1_0_X) || defined (PNG_1_2_X)
  179386. /* Initialize the info structure (old interface - DEPRECATED) */
  179387. extern PNG_EXPORT(void,png_info_init) PNGARG((png_infop info_ptr));
  179388. #undef png_info_init
  179389. #define png_info_init(info_ptr) png_info_init_3(&info_ptr,\
  179390. png_sizeof(png_info));
  179391. #endif
  179392. extern PNG_EXPORT(void,png_info_init_3) PNGARG((png_infopp info_ptr,
  179393. png_size_t png_info_struct_size));
  179394. /* Writes all the PNG information before the image. */
  179395. extern PNG_EXPORT(void,png_write_info_before_PLTE) PNGARG((png_structp png_ptr,
  179396. png_infop info_ptr));
  179397. extern PNG_EXPORT(void,png_write_info) PNGARG((png_structp png_ptr,
  179398. png_infop info_ptr));
  179399. #ifndef PNG_NO_SEQUENTIAL_READ_SUPPORTED
  179400. /* read the information before the actual image data. */
  179401. extern PNG_EXPORT(void,png_read_info) PNGARG((png_structp png_ptr,
  179402. png_infop info_ptr));
  179403. #endif
  179404. #if defined(PNG_TIME_RFC1123_SUPPORTED)
  179405. extern PNG_EXPORT(png_charp,png_convert_to_rfc1123)
  179406. PNGARG((png_structp png_ptr, png_timep ptime));
  179407. #endif
  179408. #if !defined(_WIN32_WCE)
  179409. /* "time.h" functions are not supported on WindowsCE */
  179410. #if defined(PNG_WRITE_tIME_SUPPORTED)
  179411. /* convert from a struct tm to png_time */
  179412. extern PNG_EXPORT(void,png_convert_from_struct_tm) PNGARG((png_timep ptime,
  179413. struct tm FAR * ttime));
  179414. /* convert from time_t to png_time. Uses gmtime() */
  179415. extern PNG_EXPORT(void,png_convert_from_time_t) PNGARG((png_timep ptime,
  179416. time_t ttime));
  179417. #endif /* PNG_WRITE_tIME_SUPPORTED */
  179418. #endif /* _WIN32_WCE */
  179419. #if defined(PNG_READ_EXPAND_SUPPORTED)
  179420. /* Expand data to 24-bit RGB, or 8-bit grayscale, with alpha if available. */
  179421. extern PNG_EXPORT(void,png_set_expand) PNGARG((png_structp png_ptr));
  179422. #if !defined(PNG_1_0_X)
  179423. extern PNG_EXPORT(void,png_set_expand_gray_1_2_4_to_8) PNGARG((png_structp
  179424. png_ptr));
  179425. #endif
  179426. extern PNG_EXPORT(void,png_set_palette_to_rgb) PNGARG((png_structp png_ptr));
  179427. extern PNG_EXPORT(void,png_set_tRNS_to_alpha) PNGARG((png_structp png_ptr));
  179428. #if defined(PNG_1_0_X) || defined (PNG_1_2_X)
  179429. /* Deprecated */
  179430. extern PNG_EXPORT(void,png_set_gray_1_2_4_to_8) PNGARG((png_structp png_ptr));
  179431. #endif
  179432. #endif
  179433. #if defined(PNG_READ_BGR_SUPPORTED) || defined(PNG_WRITE_BGR_SUPPORTED)
  179434. /* Use blue, green, red order for pixels. */
  179435. extern PNG_EXPORT(void,png_set_bgr) PNGARG((png_structp png_ptr));
  179436. #endif
  179437. #if defined(PNG_READ_GRAY_TO_RGB_SUPPORTED)
  179438. /* Expand the grayscale to 24-bit RGB if necessary. */
  179439. extern PNG_EXPORT(void,png_set_gray_to_rgb) PNGARG((png_structp png_ptr));
  179440. #endif
  179441. #if defined(PNG_READ_RGB_TO_GRAY_SUPPORTED)
  179442. /* Reduce RGB to grayscale. */
  179443. #ifdef PNG_FLOATING_POINT_SUPPORTED
  179444. extern PNG_EXPORT(void,png_set_rgb_to_gray) PNGARG((png_structp png_ptr,
  179445. int error_action, double red, double green ));
  179446. #endif
  179447. extern PNG_EXPORT(void,png_set_rgb_to_gray_fixed) PNGARG((png_structp png_ptr,
  179448. int error_action, png_fixed_point red, png_fixed_point green ));
  179449. extern PNG_EXPORT(png_byte,png_get_rgb_to_gray_status) PNGARG((png_structp
  179450. png_ptr));
  179451. #endif
  179452. extern PNG_EXPORT(void,png_build_grayscale_palette) PNGARG((int bit_depth,
  179453. png_colorp palette));
  179454. #if defined(PNG_READ_STRIP_ALPHA_SUPPORTED)
  179455. extern PNG_EXPORT(void,png_set_strip_alpha) PNGARG((png_structp png_ptr));
  179456. #endif
  179457. #if defined(PNG_READ_SWAP_ALPHA_SUPPORTED) || \
  179458. defined(PNG_WRITE_SWAP_ALPHA_SUPPORTED)
  179459. extern PNG_EXPORT(void,png_set_swap_alpha) PNGARG((png_structp png_ptr));
  179460. #endif
  179461. #if defined(PNG_READ_INVERT_ALPHA_SUPPORTED) || \
  179462. defined(PNG_WRITE_INVERT_ALPHA_SUPPORTED)
  179463. extern PNG_EXPORT(void,png_set_invert_alpha) PNGARG((png_structp png_ptr));
  179464. #endif
  179465. #if defined(PNG_READ_FILLER_SUPPORTED) || defined(PNG_WRITE_FILLER_SUPPORTED)
  179466. /* Add a filler byte to 8-bit Gray or 24-bit RGB images. */
  179467. extern PNG_EXPORT(void,png_set_filler) PNGARG((png_structp png_ptr,
  179468. png_uint_32 filler, int flags));
  179469. /* The values of the PNG_FILLER_ defines should NOT be changed */
  179470. #define PNG_FILLER_BEFORE 0
  179471. #define PNG_FILLER_AFTER 1
  179472. /* Add an alpha byte to 8-bit Gray or 24-bit RGB images. */
  179473. #if !defined(PNG_1_0_X)
  179474. extern PNG_EXPORT(void,png_set_add_alpha) PNGARG((png_structp png_ptr,
  179475. png_uint_32 filler, int flags));
  179476. #endif
  179477. #endif /* PNG_READ_FILLER_SUPPORTED || PNG_WRITE_FILLER_SUPPORTED */
  179478. #if defined(PNG_READ_SWAP_SUPPORTED) || defined(PNG_WRITE_SWAP_SUPPORTED)
  179479. /* Swap bytes in 16-bit depth files. */
  179480. extern PNG_EXPORT(void,png_set_swap) PNGARG((png_structp png_ptr));
  179481. #endif
  179482. #if defined(PNG_READ_PACK_SUPPORTED) || defined(PNG_WRITE_PACK_SUPPORTED)
  179483. /* Use 1 byte per pixel in 1, 2, or 4-bit depth files. */
  179484. extern PNG_EXPORT(void,png_set_packing) PNGARG((png_structp png_ptr));
  179485. #endif
  179486. #if defined(PNG_READ_PACKSWAP_SUPPORTED) || defined(PNG_WRITE_PACKSWAP_SUPPORTED)
  179487. /* Swap packing order of pixels in bytes. */
  179488. extern PNG_EXPORT(void,png_set_packswap) PNGARG((png_structp png_ptr));
  179489. #endif
  179490. #if defined(PNG_READ_SHIFT_SUPPORTED) || defined(PNG_WRITE_SHIFT_SUPPORTED)
  179491. /* Converts files to legal bit depths. */
  179492. extern PNG_EXPORT(void,png_set_shift) PNGARG((png_structp png_ptr,
  179493. png_color_8p true_bits));
  179494. #endif
  179495. #if defined(PNG_READ_INTERLACING_SUPPORTED) || \
  179496. defined(PNG_WRITE_INTERLACING_SUPPORTED)
  179497. /* Have the code handle the interlacing. Returns the number of passes. */
  179498. extern PNG_EXPORT(int,png_set_interlace_handling) PNGARG((png_structp png_ptr));
  179499. #endif
  179500. #if defined(PNG_READ_INVERT_SUPPORTED) || defined(PNG_WRITE_INVERT_SUPPORTED)
  179501. /* Invert monochrome files */
  179502. extern PNG_EXPORT(void,png_set_invert_mono) PNGARG((png_structp png_ptr));
  179503. #endif
  179504. #if defined(PNG_READ_BACKGROUND_SUPPORTED)
  179505. /* Handle alpha and tRNS by replacing with a background color. */
  179506. #ifdef PNG_FLOATING_POINT_SUPPORTED
  179507. extern PNG_EXPORT(void,png_set_background) PNGARG((png_structp png_ptr,
  179508. png_color_16p background_color, int background_gamma_code,
  179509. int need_expand, double background_gamma));
  179510. #endif
  179511. #define PNG_BACKGROUND_GAMMA_UNKNOWN 0
  179512. #define PNG_BACKGROUND_GAMMA_SCREEN 1
  179513. #define PNG_BACKGROUND_GAMMA_FILE 2
  179514. #define PNG_BACKGROUND_GAMMA_UNIQUE 3
  179515. #endif
  179516. #if defined(PNG_READ_16_TO_8_SUPPORTED)
  179517. /* strip the second byte of information from a 16-bit depth file. */
  179518. extern PNG_EXPORT(void,png_set_strip_16) PNGARG((png_structp png_ptr));
  179519. #endif
  179520. #if defined(PNG_READ_DITHER_SUPPORTED)
  179521. /* Turn on dithering, and reduce the palette to the number of colors available. */
  179522. extern PNG_EXPORT(void,png_set_dither) PNGARG((png_structp png_ptr,
  179523. png_colorp palette, int num_palette, int maximum_colors,
  179524. png_uint_16p histogram, int full_dither));
  179525. #endif
  179526. #if defined(PNG_READ_GAMMA_SUPPORTED)
  179527. /* Handle gamma correction. Screen_gamma=(display_exponent) */
  179528. #ifdef PNG_FLOATING_POINT_SUPPORTED
  179529. extern PNG_EXPORT(void,png_set_gamma) PNGARG((png_structp png_ptr,
  179530. double screen_gamma, double default_file_gamma));
  179531. #endif
  179532. #endif
  179533. #if defined(PNG_1_0_X) || defined (PNG_1_2_X)
  179534. #if defined(PNG_READ_EMPTY_PLTE_SUPPORTED) || \
  179535. defined(PNG_WRITE_EMPTY_PLTE_SUPPORTED)
  179536. /* Permit or disallow empty PLTE (0: not permitted, 1: permitted) */
  179537. /* Deprecated and will be removed. Use png_permit_mng_features() instead. */
  179538. extern PNG_EXPORT(void,png_permit_empty_plte) PNGARG((png_structp png_ptr,
  179539. int empty_plte_permitted));
  179540. #endif
  179541. #endif
  179542. #if defined(PNG_WRITE_FLUSH_SUPPORTED)
  179543. /* Set how many lines between output flushes - 0 for no flushing */
  179544. extern PNG_EXPORT(void,png_set_flush) PNGARG((png_structp png_ptr, int nrows));
  179545. /* Flush the current PNG output buffer */
  179546. extern PNG_EXPORT(void,png_write_flush) PNGARG((png_structp png_ptr));
  179547. #endif
  179548. /* optional update palette with requested transformations */
  179549. extern PNG_EXPORT(void,png_start_read_image) PNGARG((png_structp png_ptr));
  179550. /* optional call to update the users info structure */
  179551. extern PNG_EXPORT(void,png_read_update_info) PNGARG((png_structp png_ptr,
  179552. png_infop info_ptr));
  179553. #ifndef PNG_NO_SEQUENTIAL_READ_SUPPORTED
  179554. /* read one or more rows of image data. */
  179555. extern PNG_EXPORT(void,png_read_rows) PNGARG((png_structp png_ptr,
  179556. png_bytepp row, png_bytepp display_row, png_uint_32 num_rows));
  179557. #endif
  179558. #ifndef PNG_NO_SEQUENTIAL_READ_SUPPORTED
  179559. /* read a row of data. */
  179560. extern PNG_EXPORT(void,png_read_row) PNGARG((png_structp png_ptr,
  179561. png_bytep row,
  179562. png_bytep display_row));
  179563. #endif
  179564. #ifndef PNG_NO_SEQUENTIAL_READ_SUPPORTED
  179565. /* read the whole image into memory at once. */
  179566. extern PNG_EXPORT(void,png_read_image) PNGARG((png_structp png_ptr,
  179567. png_bytepp image));
  179568. #endif
  179569. /* write a row of image data */
  179570. extern PNG_EXPORT(void,png_write_row) PNGARG((png_structp png_ptr,
  179571. png_bytep row));
  179572. /* write a few rows of image data */
  179573. extern PNG_EXPORT(void,png_write_rows) PNGARG((png_structp png_ptr,
  179574. png_bytepp row, png_uint_32 num_rows));
  179575. /* write the image data */
  179576. extern PNG_EXPORT(void,png_write_image) PNGARG((png_structp png_ptr,
  179577. png_bytepp image));
  179578. /* writes the end of the PNG file. */
  179579. extern PNG_EXPORT(void,png_write_end) PNGARG((png_structp png_ptr,
  179580. png_infop info_ptr));
  179581. #ifndef PNG_NO_SEQUENTIAL_READ_SUPPORTED
  179582. /* read the end of the PNG file. */
  179583. extern PNG_EXPORT(void,png_read_end) PNGARG((png_structp png_ptr,
  179584. png_infop info_ptr));
  179585. #endif
  179586. /* free any memory associated with the png_info_struct */
  179587. extern PNG_EXPORT(void,png_destroy_info_struct) PNGARG((png_structp png_ptr,
  179588. png_infopp info_ptr_ptr));
  179589. /* free any memory associated with the png_struct and the png_info_structs */
  179590. extern PNG_EXPORT(void,png_destroy_read_struct) PNGARG((png_structpp
  179591. png_ptr_ptr, png_infopp info_ptr_ptr, png_infopp end_info_ptr_ptr));
  179592. /* free all memory used by the read (old method - NOT DLL EXPORTED) */
  179593. extern void png_read_destroy PNGARG((png_structp png_ptr, png_infop info_ptr,
  179594. png_infop end_info_ptr));
  179595. /* free any memory associated with the png_struct and the png_info_structs */
  179596. extern PNG_EXPORT(void,png_destroy_write_struct)
  179597. PNGARG((png_structpp png_ptr_ptr, png_infopp info_ptr_ptr));
  179598. /* free any memory used in png_ptr struct (old method - NOT DLL EXPORTED) */
  179599. extern void png_write_destroy PNGARG((png_structp png_ptr));
  179600. /* set the libpng method of handling chunk CRC errors */
  179601. extern PNG_EXPORT(void,png_set_crc_action) PNGARG((png_structp png_ptr,
  179602. int crit_action, int ancil_action));
  179603. /* Values for png_set_crc_action() to say how to handle CRC errors in
  179604. * ancillary and critical chunks, and whether to use the data contained
  179605. * therein. Note that it is impossible to "discard" data in a critical
  179606. * chunk. For versions prior to 0.90, the action was always error/quit,
  179607. * whereas in version 0.90 and later, the action for CRC errors in ancillary
  179608. * chunks is warn/discard. These values should NOT be changed.
  179609. *
  179610. * value action:critical action:ancillary
  179611. */
  179612. #define PNG_CRC_DEFAULT 0 /* error/quit warn/discard data */
  179613. #define PNG_CRC_ERROR_QUIT 1 /* error/quit error/quit */
  179614. #define PNG_CRC_WARN_DISCARD 2 /* (INVALID) warn/discard data */
  179615. #define PNG_CRC_WARN_USE 3 /* warn/use data warn/use data */
  179616. #define PNG_CRC_QUIET_USE 4 /* quiet/use data quiet/use data */
  179617. #define PNG_CRC_NO_CHANGE 5 /* use current value use current value */
  179618. /* These functions give the user control over the scan-line filtering in
  179619. * libpng and the compression methods used by zlib. These functions are
  179620. * mainly useful for testing, as the defaults should work with most users.
  179621. * Those users who are tight on memory or want faster performance at the
  179622. * expense of compression can modify them. See the compression library
  179623. * header file (zlib.h) for an explination of the compression functions.
  179624. */
  179625. /* set the filtering method(s) used by libpng. Currently, the only valid
  179626. * value for "method" is 0.
  179627. */
  179628. extern PNG_EXPORT(void,png_set_filter) PNGARG((png_structp png_ptr, int method,
  179629. int filters));
  179630. /* Flags for png_set_filter() to say which filters to use. The flags
  179631. * are chosen so that they don't conflict with real filter types
  179632. * below, in case they are supplied instead of the #defined constants.
  179633. * These values should NOT be changed.
  179634. */
  179635. #define PNG_NO_FILTERS 0x00
  179636. #define PNG_FILTER_NONE 0x08
  179637. #define PNG_FILTER_SUB 0x10
  179638. #define PNG_FILTER_UP 0x20
  179639. #define PNG_FILTER_AVG 0x40
  179640. #define PNG_FILTER_PAETH 0x80
  179641. #define PNG_ALL_FILTERS (PNG_FILTER_NONE | PNG_FILTER_SUB | PNG_FILTER_UP | \
  179642. PNG_FILTER_AVG | PNG_FILTER_PAETH)
  179643. /* Filter values (not flags) - used in pngwrite.c, pngwutil.c for now.
  179644. * These defines should NOT be changed.
  179645. */
  179646. #define PNG_FILTER_VALUE_NONE 0
  179647. #define PNG_FILTER_VALUE_SUB 1
  179648. #define PNG_FILTER_VALUE_UP 2
  179649. #define PNG_FILTER_VALUE_AVG 3
  179650. #define PNG_FILTER_VALUE_PAETH 4
  179651. #define PNG_FILTER_VALUE_LAST 5
  179652. #if defined(PNG_WRITE_WEIGHTED_FILTER_SUPPORTED) /* EXPERIMENTAL */
  179653. /* The "heuristic_method" is given by one of the PNG_FILTER_HEURISTIC_
  179654. * defines, either the default (minimum-sum-of-absolute-differences), or
  179655. * the experimental method (weighted-minimum-sum-of-absolute-differences).
  179656. *
  179657. * Weights are factors >= 1.0, indicating how important it is to keep the
  179658. * filter type consistent between rows. Larger numbers mean the current
  179659. * filter is that many times as likely to be the same as the "num_weights"
  179660. * previous filters. This is cumulative for each previous row with a weight.
  179661. * There needs to be "num_weights" values in "filter_weights", or it can be
  179662. * NULL if the weights aren't being specified. Weights have no influence on
  179663. * the selection of the first row filter. Well chosen weights can (in theory)
  179664. * improve the compression for a given image.
  179665. *
  179666. * Costs are factors >= 1.0 indicating the relative decoding costs of a
  179667. * filter type. Higher costs indicate more decoding expense, and are
  179668. * therefore less likely to be selected over a filter with lower computational
  179669. * costs. There needs to be a value in "filter_costs" for each valid filter
  179670. * type (given by PNG_FILTER_VALUE_LAST), or it can be NULL if you aren't
  179671. * setting the costs. Costs try to improve the speed of decompression without
  179672. * unduly increasing the compressed image size.
  179673. *
  179674. * A negative weight or cost indicates the default value is to be used, and
  179675. * values in the range [0.0, 1.0) indicate the value is to remain unchanged.
  179676. * The default values for both weights and costs are currently 1.0, but may
  179677. * change if good general weighting/cost heuristics can be found. If both
  179678. * the weights and costs are set to 1.0, this degenerates the WEIGHTED method
  179679. * to the UNWEIGHTED method, but with added encoding time/computation.
  179680. */
  179681. #ifdef PNG_FLOATING_POINT_SUPPORTED
  179682. extern PNG_EXPORT(void,png_set_filter_heuristics) PNGARG((png_structp png_ptr,
  179683. int heuristic_method, int num_weights, png_doublep filter_weights,
  179684. png_doublep filter_costs));
  179685. #endif
  179686. #endif /* PNG_WRITE_WEIGHTED_FILTER_SUPPORTED */
  179687. /* Heuristic used for row filter selection. These defines should NOT be
  179688. * changed.
  179689. */
  179690. #define PNG_FILTER_HEURISTIC_DEFAULT 0 /* Currently "UNWEIGHTED" */
  179691. #define PNG_FILTER_HEURISTIC_UNWEIGHTED 1 /* Used by libpng < 0.95 */
  179692. #define PNG_FILTER_HEURISTIC_WEIGHTED 2 /* Experimental feature */
  179693. #define PNG_FILTER_HEURISTIC_LAST 3 /* Not a valid value */
  179694. /* Set the library compression level. Currently, valid values range from
  179695. * 0 - 9, corresponding directly to the zlib compression levels 0 - 9
  179696. * (0 - no compression, 9 - "maximal" compression). Note that tests have
  179697. * shown that zlib compression levels 3-6 usually perform as well as level 9
  179698. * for PNG images, and do considerably fewer caclulations. In the future,
  179699. * these values may not correspond directly to the zlib compression levels.
  179700. */
  179701. extern PNG_EXPORT(void,png_set_compression_level) PNGARG((png_structp png_ptr,
  179702. int level));
  179703. extern PNG_EXPORT(void,png_set_compression_mem_level)
  179704. PNGARG((png_structp png_ptr, int mem_level));
  179705. extern PNG_EXPORT(void,png_set_compression_strategy)
  179706. PNGARG((png_structp png_ptr, int strategy));
  179707. extern PNG_EXPORT(void,png_set_compression_window_bits)
  179708. PNGARG((png_structp png_ptr, int window_bits));
  179709. extern PNG_EXPORT(void,png_set_compression_method) PNGARG((png_structp png_ptr,
  179710. int method));
  179711. /* These next functions are called for input/output, memory, and error
  179712. * handling. They are in the file pngrio.c, pngwio.c, and pngerror.c,
  179713. * and call standard C I/O routines such as fread(), fwrite(), and
  179714. * fprintf(). These functions can be made to use other I/O routines
  179715. * at run time for those applications that need to handle I/O in a
  179716. * different manner by calling png_set_???_fn(). See libpng.txt for
  179717. * more information.
  179718. */
  179719. #if !defined(PNG_NO_STDIO)
  179720. /* Initialize the input/output for the PNG file to the default functions. */
  179721. extern PNG_EXPORT(void,png_init_io) PNGARG((png_structp png_ptr, png_FILE_p fp));
  179722. #endif
  179723. /* Replace the (error and abort), and warning functions with user
  179724. * supplied functions. If no messages are to be printed you must still
  179725. * write and use replacement functions. The replacement error_fn should
  179726. * still do a longjmp to the last setjmp location if you are using this
  179727. * method of error handling. If error_fn or warning_fn is NULL, the
  179728. * default function will be used.
  179729. */
  179730. extern PNG_EXPORT(void,png_set_error_fn) PNGARG((png_structp png_ptr,
  179731. png_voidp error_ptr, png_error_ptr error_fn, png_error_ptr warning_fn));
  179732. /* Return the user pointer associated with the error functions */
  179733. extern PNG_EXPORT(png_voidp,png_get_error_ptr) PNGARG((png_structp png_ptr));
  179734. /* Replace the default data output functions with a user supplied one(s).
  179735. * If buffered output is not used, then output_flush_fn can be set to NULL.
  179736. * If PNG_WRITE_FLUSH_SUPPORTED is not defined at libpng compile time
  179737. * output_flush_fn will be ignored (and thus can be NULL).
  179738. */
  179739. extern PNG_EXPORT(void,png_set_write_fn) PNGARG((png_structp png_ptr,
  179740. png_voidp io_ptr, png_rw_ptr write_data_fn, png_flush_ptr output_flush_fn));
  179741. /* Replace the default data input function with a user supplied one. */
  179742. extern PNG_EXPORT(void,png_set_read_fn) PNGARG((png_structp png_ptr,
  179743. png_voidp io_ptr, png_rw_ptr read_data_fn));
  179744. /* Return the user pointer associated with the I/O functions */
  179745. extern PNG_EXPORT(png_voidp,png_get_io_ptr) PNGARG((png_structp png_ptr));
  179746. extern PNG_EXPORT(void,png_set_read_status_fn) PNGARG((png_structp png_ptr,
  179747. png_read_status_ptr read_row_fn));
  179748. extern PNG_EXPORT(void,png_set_write_status_fn) PNGARG((png_structp png_ptr,
  179749. png_write_status_ptr write_row_fn));
  179750. #ifdef PNG_USER_MEM_SUPPORTED
  179751. /* Replace the default memory allocation functions with user supplied one(s). */
  179752. extern PNG_EXPORT(void,png_set_mem_fn) PNGARG((png_structp png_ptr,
  179753. png_voidp mem_ptr, png_malloc_ptr malloc_fn, png_free_ptr free_fn));
  179754. /* Return the user pointer associated with the memory functions */
  179755. extern PNG_EXPORT(png_voidp,png_get_mem_ptr) PNGARG((png_structp png_ptr));
  179756. #endif
  179757. #if defined(PNG_READ_USER_TRANSFORM_SUPPORTED) || \
  179758. defined(PNG_LEGACY_SUPPORTED)
  179759. extern PNG_EXPORT(void,png_set_read_user_transform_fn) PNGARG((png_structp
  179760. png_ptr, png_user_transform_ptr read_user_transform_fn));
  179761. #endif
  179762. #if defined(PNG_WRITE_USER_TRANSFORM_SUPPORTED) || \
  179763. defined(PNG_LEGACY_SUPPORTED)
  179764. extern PNG_EXPORT(void,png_set_write_user_transform_fn) PNGARG((png_structp
  179765. png_ptr, png_user_transform_ptr write_user_transform_fn));
  179766. #endif
  179767. #if defined(PNG_READ_USER_TRANSFORM_SUPPORTED) || \
  179768. defined(PNG_WRITE_USER_TRANSFORM_SUPPORTED) || \
  179769. defined(PNG_LEGACY_SUPPORTED)
  179770. extern PNG_EXPORT(void,png_set_user_transform_info) PNGARG((png_structp
  179771. png_ptr, png_voidp user_transform_ptr, int user_transform_depth,
  179772. int user_transform_channels));
  179773. /* Return the user pointer associated with the user transform functions */
  179774. extern PNG_EXPORT(png_voidp,png_get_user_transform_ptr)
  179775. PNGARG((png_structp png_ptr));
  179776. #endif
  179777. #ifdef PNG_USER_CHUNKS_SUPPORTED
  179778. extern PNG_EXPORT(void,png_set_read_user_chunk_fn) PNGARG((png_structp png_ptr,
  179779. png_voidp user_chunk_ptr, png_user_chunk_ptr read_user_chunk_fn));
  179780. extern PNG_EXPORT(png_voidp,png_get_user_chunk_ptr) PNGARG((png_structp
  179781. png_ptr));
  179782. #endif
  179783. #ifdef PNG_PROGRESSIVE_READ_SUPPORTED
  179784. /* Sets the function callbacks for the push reader, and a pointer to a
  179785. * user-defined structure available to the callback functions.
  179786. */
  179787. extern PNG_EXPORT(void,png_set_progressive_read_fn) PNGARG((png_structp png_ptr,
  179788. png_voidp progressive_ptr,
  179789. png_progressive_info_ptr info_fn, png_progressive_row_ptr row_fn,
  179790. png_progressive_end_ptr end_fn));
  179791. /* returns the user pointer associated with the push read functions */
  179792. extern PNG_EXPORT(png_voidp,png_get_progressive_ptr)
  179793. PNGARG((png_structp png_ptr));
  179794. /* function to be called when data becomes available */
  179795. extern PNG_EXPORT(void,png_process_data) PNGARG((png_structp png_ptr,
  179796. png_infop info_ptr, png_bytep buffer, png_size_t buffer_size));
  179797. /* function that combines rows. Not very much different than the
  179798. * png_combine_row() call. Is this even used?????
  179799. */
  179800. extern PNG_EXPORT(void,png_progressive_combine_row) PNGARG((png_structp png_ptr,
  179801. png_bytep old_row, png_bytep new_row));
  179802. #endif /* PNG_PROGRESSIVE_READ_SUPPORTED */
  179803. extern PNG_EXPORT(png_voidp,png_malloc) PNGARG((png_structp png_ptr,
  179804. png_uint_32 size));
  179805. #if defined(PNG_1_0_X)
  179806. # define png_malloc_warn png_malloc
  179807. #else
  179808. /* Added at libpng version 1.2.4 */
  179809. extern PNG_EXPORT(png_voidp,png_malloc_warn) PNGARG((png_structp png_ptr,
  179810. png_uint_32 size));
  179811. #endif
  179812. /* frees a pointer allocated by png_malloc() */
  179813. extern PNG_EXPORT(void,png_free) PNGARG((png_structp png_ptr, png_voidp ptr));
  179814. #if defined(PNG_1_0_X)
  179815. /* Function to allocate memory for zlib. */
  179816. extern PNG_EXPORT(voidpf,png_zalloc) PNGARG((voidpf png_ptr, uInt items,
  179817. uInt size));
  179818. /* Function to free memory for zlib */
  179819. extern PNG_EXPORT(void,png_zfree) PNGARG((voidpf png_ptr, voidpf ptr));
  179820. #endif
  179821. /* Free data that was allocated internally */
  179822. extern PNG_EXPORT(void,png_free_data) PNGARG((png_structp png_ptr,
  179823. png_infop info_ptr, png_uint_32 free_me, int num));
  179824. #ifdef PNG_FREE_ME_SUPPORTED
  179825. /* Reassign responsibility for freeing existing data, whether allocated
  179826. * by libpng or by the application */
  179827. extern PNG_EXPORT(void,png_data_freer) PNGARG((png_structp png_ptr,
  179828. png_infop info_ptr, int freer, png_uint_32 mask));
  179829. #endif
  179830. /* assignments for png_data_freer */
  179831. #define PNG_DESTROY_WILL_FREE_DATA 1
  179832. #define PNG_SET_WILL_FREE_DATA 1
  179833. #define PNG_USER_WILL_FREE_DATA 2
  179834. /* Flags for png_ptr->free_me and info_ptr->free_me */
  179835. #define PNG_FREE_HIST 0x0008
  179836. #define PNG_FREE_ICCP 0x0010
  179837. #define PNG_FREE_SPLT 0x0020
  179838. #define PNG_FREE_ROWS 0x0040
  179839. #define PNG_FREE_PCAL 0x0080
  179840. #define PNG_FREE_SCAL 0x0100
  179841. #define PNG_FREE_UNKN 0x0200
  179842. #define PNG_FREE_LIST 0x0400
  179843. #define PNG_FREE_PLTE 0x1000
  179844. #define PNG_FREE_TRNS 0x2000
  179845. #define PNG_FREE_TEXT 0x4000
  179846. #define PNG_FREE_ALL 0x7fff
  179847. #define PNG_FREE_MUL 0x4220 /* PNG_FREE_SPLT|PNG_FREE_TEXT|PNG_FREE_UNKN */
  179848. #ifdef PNG_USER_MEM_SUPPORTED
  179849. extern PNG_EXPORT(png_voidp,png_malloc_default) PNGARG((png_structp png_ptr,
  179850. png_uint_32 size));
  179851. extern PNG_EXPORT(void,png_free_default) PNGARG((png_structp png_ptr,
  179852. png_voidp ptr));
  179853. #endif
  179854. extern PNG_EXPORT(png_voidp,png_memcpy_check) PNGARG((png_structp png_ptr,
  179855. png_voidp s1, png_voidp s2, png_uint_32 size));
  179856. extern PNG_EXPORT(png_voidp,png_memset_check) PNGARG((png_structp png_ptr,
  179857. png_voidp s1, int value, png_uint_32 size));
  179858. #if defined(USE_FAR_KEYWORD) /* memory model conversion function */
  179859. extern void *png_far_to_near PNGARG((png_structp png_ptr,png_voidp ptr,
  179860. int check));
  179861. #endif /* USE_FAR_KEYWORD */
  179862. #ifndef PNG_NO_ERROR_TEXT
  179863. /* Fatal error in PNG image of libpng - can't continue */
  179864. extern PNG_EXPORT(void,png_error) PNGARG((png_structp png_ptr,
  179865. png_const_charp error_message));
  179866. /* The same, but the chunk name is prepended to the error string. */
  179867. extern PNG_EXPORT(void,png_chunk_error) PNGARG((png_structp png_ptr,
  179868. png_const_charp error_message));
  179869. #else
  179870. /* Fatal error in PNG image of libpng - can't continue */
  179871. extern PNG_EXPORT(void,png_err) PNGARG((png_structp png_ptr));
  179872. #endif
  179873. #ifndef PNG_NO_WARNINGS
  179874. /* Non-fatal error in libpng. Can continue, but may have a problem. */
  179875. extern PNG_EXPORT(void,png_warning) PNGARG((png_structp png_ptr,
  179876. png_const_charp warning_message));
  179877. #ifdef PNG_READ_SUPPORTED
  179878. /* Non-fatal error in libpng, chunk name is prepended to message. */
  179879. extern PNG_EXPORT(void,png_chunk_warning) PNGARG((png_structp png_ptr,
  179880. png_const_charp warning_message));
  179881. #endif /* PNG_READ_SUPPORTED */
  179882. #endif /* PNG_NO_WARNINGS */
  179883. /* The png_set_<chunk> functions are for storing values in the png_info_struct.
  179884. * Similarly, the png_get_<chunk> calls are used to read values from the
  179885. * png_info_struct, either storing the parameters in the passed variables, or
  179886. * setting pointers into the png_info_struct where the data is stored. The
  179887. * png_get_<chunk> functions return a non-zero value if the data was available
  179888. * in info_ptr, or return zero and do not change any of the parameters if the
  179889. * data was not available.
  179890. *
  179891. * These functions should be used instead of directly accessing png_info
  179892. * to avoid problems with future changes in the size and internal layout of
  179893. * png_info_struct.
  179894. */
  179895. /* Returns "flag" if chunk data is valid in info_ptr. */
  179896. extern PNG_EXPORT(png_uint_32,png_get_valid) PNGARG((png_structp png_ptr,
  179897. png_infop info_ptr, png_uint_32 flag));
  179898. /* Returns number of bytes needed to hold a transformed row. */
  179899. extern PNG_EXPORT(png_uint_32,png_get_rowbytes) PNGARG((png_structp png_ptr,
  179900. png_infop info_ptr));
  179901. #if defined(PNG_INFO_IMAGE_SUPPORTED)
  179902. /* Returns row_pointers, which is an array of pointers to scanlines that was
  179903. returned from png_read_png(). */
  179904. extern PNG_EXPORT(png_bytepp,png_get_rows) PNGARG((png_structp png_ptr,
  179905. png_infop info_ptr));
  179906. /* Set row_pointers, which is an array of pointers to scanlines for use
  179907. by png_write_png(). */
  179908. extern PNG_EXPORT(void,png_set_rows) PNGARG((png_structp png_ptr,
  179909. png_infop info_ptr, png_bytepp row_pointers));
  179910. #endif
  179911. /* Returns number of color channels in image. */
  179912. extern PNG_EXPORT(png_byte,png_get_channels) PNGARG((png_structp png_ptr,
  179913. png_infop info_ptr));
  179914. #ifdef PNG_EASY_ACCESS_SUPPORTED
  179915. /* Returns image width in pixels. */
  179916. extern PNG_EXPORT(png_uint_32, png_get_image_width) PNGARG((png_structp
  179917. png_ptr, png_infop info_ptr));
  179918. /* Returns image height in pixels. */
  179919. extern PNG_EXPORT(png_uint_32, png_get_image_height) PNGARG((png_structp
  179920. png_ptr, png_infop info_ptr));
  179921. /* Returns image bit_depth. */
  179922. extern PNG_EXPORT(png_byte, png_get_bit_depth) PNGARG((png_structp
  179923. png_ptr, png_infop info_ptr));
  179924. /* Returns image color_type. */
  179925. extern PNG_EXPORT(png_byte, png_get_color_type) PNGARG((png_structp
  179926. png_ptr, png_infop info_ptr));
  179927. /* Returns image filter_type. */
  179928. extern PNG_EXPORT(png_byte, png_get_filter_type) PNGARG((png_structp
  179929. png_ptr, png_infop info_ptr));
  179930. /* Returns image interlace_type. */
  179931. extern PNG_EXPORT(png_byte, png_get_interlace_type) PNGARG((png_structp
  179932. png_ptr, png_infop info_ptr));
  179933. /* Returns image compression_type. */
  179934. extern PNG_EXPORT(png_byte, png_get_compression_type) PNGARG((png_structp
  179935. png_ptr, png_infop info_ptr));
  179936. /* Returns image resolution in pixels per meter, from pHYs chunk data. */
  179937. extern PNG_EXPORT(png_uint_32, png_get_pixels_per_meter) PNGARG((png_structp
  179938. png_ptr, png_infop info_ptr));
  179939. extern PNG_EXPORT(png_uint_32, png_get_x_pixels_per_meter) PNGARG((png_structp
  179940. png_ptr, png_infop info_ptr));
  179941. extern PNG_EXPORT(png_uint_32, png_get_y_pixels_per_meter) PNGARG((png_structp
  179942. png_ptr, png_infop info_ptr));
  179943. /* Returns pixel aspect ratio, computed from pHYs chunk data. */
  179944. #ifdef PNG_FLOATING_POINT_SUPPORTED
  179945. extern PNG_EXPORT(float, png_get_pixel_aspect_ratio) PNGARG((png_structp
  179946. png_ptr, png_infop info_ptr));
  179947. #endif
  179948. /* Returns image x, y offset in pixels or microns, from oFFs chunk data. */
  179949. extern PNG_EXPORT(png_int_32, png_get_x_offset_pixels) PNGARG((png_structp
  179950. png_ptr, png_infop info_ptr));
  179951. extern PNG_EXPORT(png_int_32, png_get_y_offset_pixels) PNGARG((png_structp
  179952. png_ptr, png_infop info_ptr));
  179953. extern PNG_EXPORT(png_int_32, png_get_x_offset_microns) PNGARG((png_structp
  179954. png_ptr, png_infop info_ptr));
  179955. extern PNG_EXPORT(png_int_32, png_get_y_offset_microns) PNGARG((png_structp
  179956. png_ptr, png_infop info_ptr));
  179957. #endif /* PNG_EASY_ACCESS_SUPPORTED */
  179958. /* Returns pointer to signature string read from PNG header */
  179959. extern PNG_EXPORT(png_bytep,png_get_signature) PNGARG((png_structp png_ptr,
  179960. png_infop info_ptr));
  179961. #if defined(PNG_bKGD_SUPPORTED)
  179962. extern PNG_EXPORT(png_uint_32,png_get_bKGD) PNGARG((png_structp png_ptr,
  179963. png_infop info_ptr, png_color_16p *background));
  179964. #endif
  179965. #if defined(PNG_bKGD_SUPPORTED)
  179966. extern PNG_EXPORT(void,png_set_bKGD) PNGARG((png_structp png_ptr,
  179967. png_infop info_ptr, png_color_16p background));
  179968. #endif
  179969. #if defined(PNG_cHRM_SUPPORTED)
  179970. #ifdef PNG_FLOATING_POINT_SUPPORTED
  179971. extern PNG_EXPORT(png_uint_32,png_get_cHRM) PNGARG((png_structp png_ptr,
  179972. png_infop info_ptr, double *white_x, double *white_y, double *red_x,
  179973. double *red_y, double *green_x, double *green_y, double *blue_x,
  179974. double *blue_y));
  179975. #endif
  179976. #ifdef PNG_FIXED_POINT_SUPPORTED
  179977. extern PNG_EXPORT(png_uint_32,png_get_cHRM_fixed) PNGARG((png_structp png_ptr,
  179978. png_infop info_ptr, png_fixed_point *int_white_x, png_fixed_point
  179979. *int_white_y, png_fixed_point *int_red_x, png_fixed_point *int_red_y,
  179980. png_fixed_point *int_green_x, png_fixed_point *int_green_y, png_fixed_point
  179981. *int_blue_x, png_fixed_point *int_blue_y));
  179982. #endif
  179983. #endif
  179984. #if defined(PNG_cHRM_SUPPORTED)
  179985. #ifdef PNG_FLOATING_POINT_SUPPORTED
  179986. extern PNG_EXPORT(void,png_set_cHRM) PNGARG((png_structp png_ptr,
  179987. png_infop info_ptr, double white_x, double white_y, double red_x,
  179988. double red_y, double green_x, double green_y, double blue_x, double blue_y));
  179989. #endif
  179990. #ifdef PNG_FIXED_POINT_SUPPORTED
  179991. extern PNG_EXPORT(void,png_set_cHRM_fixed) PNGARG((png_structp png_ptr,
  179992. png_infop info_ptr, png_fixed_point int_white_x, png_fixed_point int_white_y,
  179993. png_fixed_point int_red_x, png_fixed_point int_red_y, png_fixed_point
  179994. int_green_x, png_fixed_point int_green_y, png_fixed_point int_blue_x,
  179995. png_fixed_point int_blue_y));
  179996. #endif
  179997. #endif
  179998. #if defined(PNG_gAMA_SUPPORTED)
  179999. #ifdef PNG_FLOATING_POINT_SUPPORTED
  180000. extern PNG_EXPORT(png_uint_32,png_get_gAMA) PNGARG((png_structp png_ptr,
  180001. png_infop info_ptr, double *file_gamma));
  180002. #endif
  180003. extern PNG_EXPORT(png_uint_32,png_get_gAMA_fixed) PNGARG((png_structp png_ptr,
  180004. png_infop info_ptr, png_fixed_point *int_file_gamma));
  180005. #endif
  180006. #if defined(PNG_gAMA_SUPPORTED)
  180007. #ifdef PNG_FLOATING_POINT_SUPPORTED
  180008. extern PNG_EXPORT(void,png_set_gAMA) PNGARG((png_structp png_ptr,
  180009. png_infop info_ptr, double file_gamma));
  180010. #endif
  180011. extern PNG_EXPORT(void,png_set_gAMA_fixed) PNGARG((png_structp png_ptr,
  180012. png_infop info_ptr, png_fixed_point int_file_gamma));
  180013. #endif
  180014. #if defined(PNG_hIST_SUPPORTED)
  180015. extern PNG_EXPORT(png_uint_32,png_get_hIST) PNGARG((png_structp png_ptr,
  180016. png_infop info_ptr, png_uint_16p *hist));
  180017. #endif
  180018. #if defined(PNG_hIST_SUPPORTED)
  180019. extern PNG_EXPORT(void,png_set_hIST) PNGARG((png_structp png_ptr,
  180020. png_infop info_ptr, png_uint_16p hist));
  180021. #endif
  180022. extern PNG_EXPORT(png_uint_32,png_get_IHDR) PNGARG((png_structp png_ptr,
  180023. png_infop info_ptr, png_uint_32 *width, png_uint_32 *height,
  180024. int *bit_depth, int *color_type, int *interlace_method,
  180025. int *compression_method, int *filter_method));
  180026. extern PNG_EXPORT(void,png_set_IHDR) PNGARG((png_structp png_ptr,
  180027. png_infop info_ptr, png_uint_32 width, png_uint_32 height, int bit_depth,
  180028. int color_type, int interlace_method, int compression_method,
  180029. int filter_method));
  180030. #if defined(PNG_oFFs_SUPPORTED)
  180031. extern PNG_EXPORT(png_uint_32,png_get_oFFs) PNGARG((png_structp png_ptr,
  180032. png_infop info_ptr, png_int_32 *offset_x, png_int_32 *offset_y,
  180033. int *unit_type));
  180034. #endif
  180035. #if defined(PNG_oFFs_SUPPORTED)
  180036. extern PNG_EXPORT(void,png_set_oFFs) PNGARG((png_structp png_ptr,
  180037. png_infop info_ptr, png_int_32 offset_x, png_int_32 offset_y,
  180038. int unit_type));
  180039. #endif
  180040. #if defined(PNG_pCAL_SUPPORTED)
  180041. extern PNG_EXPORT(png_uint_32,png_get_pCAL) PNGARG((png_structp png_ptr,
  180042. png_infop info_ptr, png_charp *purpose, png_int_32 *X0, png_int_32 *X1,
  180043. int *type, int *nparams, png_charp *units, png_charpp *params));
  180044. #endif
  180045. #if defined(PNG_pCAL_SUPPORTED)
  180046. extern PNG_EXPORT(void,png_set_pCAL) PNGARG((png_structp png_ptr,
  180047. png_infop info_ptr, png_charp purpose, png_int_32 X0, png_int_32 X1,
  180048. int type, int nparams, png_charp units, png_charpp params));
  180049. #endif
  180050. #if defined(PNG_pHYs_SUPPORTED)
  180051. extern PNG_EXPORT(png_uint_32,png_get_pHYs) PNGARG((png_structp png_ptr,
  180052. png_infop info_ptr, png_uint_32 *res_x, png_uint_32 *res_y, int *unit_type));
  180053. #endif
  180054. #if defined(PNG_pHYs_SUPPORTED)
  180055. extern PNG_EXPORT(void,png_set_pHYs) PNGARG((png_structp png_ptr,
  180056. png_infop info_ptr, png_uint_32 res_x, png_uint_32 res_y, int unit_type));
  180057. #endif
  180058. extern PNG_EXPORT(png_uint_32,png_get_PLTE) PNGARG((png_structp png_ptr,
  180059. png_infop info_ptr, png_colorp *palette, int *num_palette));
  180060. extern PNG_EXPORT(void,png_set_PLTE) PNGARG((png_structp png_ptr,
  180061. png_infop info_ptr, png_colorp palette, int num_palette));
  180062. #if defined(PNG_sBIT_SUPPORTED)
  180063. extern PNG_EXPORT(png_uint_32,png_get_sBIT) PNGARG((png_structp png_ptr,
  180064. png_infop info_ptr, png_color_8p *sig_bit));
  180065. #endif
  180066. #if defined(PNG_sBIT_SUPPORTED)
  180067. extern PNG_EXPORT(void,png_set_sBIT) PNGARG((png_structp png_ptr,
  180068. png_infop info_ptr, png_color_8p sig_bit));
  180069. #endif
  180070. #if defined(PNG_sRGB_SUPPORTED)
  180071. extern PNG_EXPORT(png_uint_32,png_get_sRGB) PNGARG((png_structp png_ptr,
  180072. png_infop info_ptr, int *intent));
  180073. #endif
  180074. #if defined(PNG_sRGB_SUPPORTED)
  180075. extern PNG_EXPORT(void,png_set_sRGB) PNGARG((png_structp png_ptr,
  180076. png_infop info_ptr, int intent));
  180077. extern PNG_EXPORT(void,png_set_sRGB_gAMA_and_cHRM) PNGARG((png_structp png_ptr,
  180078. png_infop info_ptr, int intent));
  180079. #endif
  180080. #if defined(PNG_iCCP_SUPPORTED)
  180081. extern PNG_EXPORT(png_uint_32,png_get_iCCP) PNGARG((png_structp png_ptr,
  180082. png_infop info_ptr, png_charpp name, int *compression_type,
  180083. png_charpp profile, png_uint_32 *proflen));
  180084. /* Note to maintainer: profile should be png_bytepp */
  180085. #endif
  180086. #if defined(PNG_iCCP_SUPPORTED)
  180087. extern PNG_EXPORT(void,png_set_iCCP) PNGARG((png_structp png_ptr,
  180088. png_infop info_ptr, png_charp name, int compression_type,
  180089. png_charp profile, png_uint_32 proflen));
  180090. /* Note to maintainer: profile should be png_bytep */
  180091. #endif
  180092. #if defined(PNG_sPLT_SUPPORTED)
  180093. extern PNG_EXPORT(png_uint_32,png_get_sPLT) PNGARG((png_structp png_ptr,
  180094. png_infop info_ptr, png_sPLT_tpp entries));
  180095. #endif
  180096. #if defined(PNG_sPLT_SUPPORTED)
  180097. extern PNG_EXPORT(void,png_set_sPLT) PNGARG((png_structp png_ptr,
  180098. png_infop info_ptr, png_sPLT_tp entries, int nentries));
  180099. #endif
  180100. #if defined(PNG_TEXT_SUPPORTED)
  180101. /* png_get_text also returns the number of text chunks in *num_text */
  180102. extern PNG_EXPORT(png_uint_32,png_get_text) PNGARG((png_structp png_ptr,
  180103. png_infop info_ptr, png_textp *text_ptr, int *num_text));
  180104. #endif
  180105. /*
  180106. * Note while png_set_text() will accept a structure whose text,
  180107. * language, and translated keywords are NULL pointers, the structure
  180108. * returned by png_get_text will always contain regular
  180109. * zero-terminated C strings. They might be empty strings but
  180110. * they will never be NULL pointers.
  180111. */
  180112. #if defined(PNG_TEXT_SUPPORTED)
  180113. extern PNG_EXPORT(void,png_set_text) PNGARG((png_structp png_ptr,
  180114. png_infop info_ptr, png_textp text_ptr, int num_text));
  180115. #endif
  180116. #if defined(PNG_tIME_SUPPORTED)
  180117. extern PNG_EXPORT(png_uint_32,png_get_tIME) PNGARG((png_structp png_ptr,
  180118. png_infop info_ptr, png_timep *mod_time));
  180119. #endif
  180120. #if defined(PNG_tIME_SUPPORTED)
  180121. extern PNG_EXPORT(void,png_set_tIME) PNGARG((png_structp png_ptr,
  180122. png_infop info_ptr, png_timep mod_time));
  180123. #endif
  180124. #if defined(PNG_tRNS_SUPPORTED)
  180125. extern PNG_EXPORT(png_uint_32,png_get_tRNS) PNGARG((png_structp png_ptr,
  180126. png_infop info_ptr, png_bytep *trans, int *num_trans,
  180127. png_color_16p *trans_values));
  180128. #endif
  180129. #if defined(PNG_tRNS_SUPPORTED)
  180130. extern PNG_EXPORT(void,png_set_tRNS) PNGARG((png_structp png_ptr,
  180131. png_infop info_ptr, png_bytep trans, int num_trans,
  180132. png_color_16p trans_values));
  180133. #endif
  180134. #if defined(PNG_tRNS_SUPPORTED)
  180135. #endif
  180136. #if defined(PNG_sCAL_SUPPORTED)
  180137. #ifdef PNG_FLOATING_POINT_SUPPORTED
  180138. extern PNG_EXPORT(png_uint_32,png_get_sCAL) PNGARG((png_structp png_ptr,
  180139. png_infop info_ptr, int *unit, double *width, double *height));
  180140. #else
  180141. #ifdef PNG_FIXED_POINT_SUPPORTED
  180142. extern PNG_EXPORT(png_uint_32,png_get_sCAL_s) PNGARG((png_structp png_ptr,
  180143. png_infop info_ptr, int *unit, png_charpp swidth, png_charpp sheight));
  180144. #endif
  180145. #endif
  180146. #endif /* PNG_sCAL_SUPPORTED */
  180147. #if defined(PNG_sCAL_SUPPORTED)
  180148. #ifdef PNG_FLOATING_POINT_SUPPORTED
  180149. extern PNG_EXPORT(void,png_set_sCAL) PNGARG((png_structp png_ptr,
  180150. png_infop info_ptr, int unit, double width, double height));
  180151. #else
  180152. #ifdef PNG_FIXED_POINT_SUPPORTED
  180153. extern PNG_EXPORT(void,png_set_sCAL_s) PNGARG((png_structp png_ptr,
  180154. png_infop info_ptr, int unit, png_charp swidth, png_charp sheight));
  180155. #endif
  180156. #endif
  180157. #endif /* PNG_sCAL_SUPPORTED || PNG_WRITE_sCAL_SUPPORTED */
  180158. #if defined(PNG_UNKNOWN_CHUNKS_SUPPORTED)
  180159. /* provide a list of chunks and how they are to be handled, if the built-in
  180160. handling or default unknown chunk handling is not desired. Any chunks not
  180161. listed will be handled in the default manner. The IHDR and IEND chunks
  180162. must not be listed.
  180163. keep = 0: follow default behaviour
  180164. = 1: do not keep
  180165. = 2: keep only if safe-to-copy
  180166. = 3: keep even if unsafe-to-copy
  180167. */
  180168. extern PNG_EXPORT(void, png_set_keep_unknown_chunks) PNGARG((png_structp
  180169. png_ptr, int keep, png_bytep chunk_list, int num_chunks));
  180170. extern PNG_EXPORT(void, png_set_unknown_chunks) PNGARG((png_structp png_ptr,
  180171. png_infop info_ptr, png_unknown_chunkp unknowns, int num_unknowns));
  180172. extern PNG_EXPORT(void, png_set_unknown_chunk_location)
  180173. PNGARG((png_structp png_ptr, png_infop info_ptr, int chunk, int location));
  180174. extern PNG_EXPORT(png_uint_32,png_get_unknown_chunks) PNGARG((png_structp
  180175. png_ptr, png_infop info_ptr, png_unknown_chunkpp entries));
  180176. #endif
  180177. #ifdef PNG_HANDLE_AS_UNKNOWN_SUPPORTED
  180178. PNG_EXPORT(int,png_handle_as_unknown) PNGARG((png_structp png_ptr, png_bytep
  180179. chunk_name));
  180180. #endif
  180181. /* Png_free_data() will turn off the "valid" flag for anything it frees.
  180182. If you need to turn it off for a chunk that your application has freed,
  180183. you can use png_set_invalid(png_ptr, info_ptr, PNG_INFO_CHNK); */
  180184. extern PNG_EXPORT(void, png_set_invalid) PNGARG((png_structp png_ptr,
  180185. png_infop info_ptr, int mask));
  180186. #if defined(PNG_INFO_IMAGE_SUPPORTED)
  180187. /* The "params" pointer is currently not used and is for future expansion. */
  180188. extern PNG_EXPORT(void, png_read_png) PNGARG((png_structp png_ptr,
  180189. png_infop info_ptr,
  180190. int transforms,
  180191. png_voidp params));
  180192. extern PNG_EXPORT(void, png_write_png) PNGARG((png_structp png_ptr,
  180193. png_infop info_ptr,
  180194. int transforms,
  180195. png_voidp params));
  180196. #endif
  180197. /* Define PNG_DEBUG at compile time for debugging information. Higher
  180198. * numbers for PNG_DEBUG mean more debugging information. This has
  180199. * only been added since version 0.95 so it is not implemented throughout
  180200. * libpng yet, but more support will be added as needed.
  180201. */
  180202. #ifdef PNG_DEBUG
  180203. #if (PNG_DEBUG > 0)
  180204. #if !defined(PNG_DEBUG_FILE) && defined(_MSC_VER)
  180205. #include <crtdbg.h>
  180206. #if (PNG_DEBUG > 1)
  180207. #define png_debug(l,m) _RPT0(_CRT_WARN,m)
  180208. #define png_debug1(l,m,p1) _RPT1(_CRT_WARN,m,p1)
  180209. #define png_debug2(l,m,p1,p2) _RPT2(_CRT_WARN,m,p1,p2)
  180210. #endif
  180211. #else /* PNG_DEBUG_FILE || !_MSC_VER */
  180212. #ifndef PNG_DEBUG_FILE
  180213. #define PNG_DEBUG_FILE stderr
  180214. #endif /* PNG_DEBUG_FILE */
  180215. #if (PNG_DEBUG > 1)
  180216. #define png_debug(l,m) \
  180217. { \
  180218. int num_tabs=l; \
  180219. fprintf(PNG_DEBUG_FILE,"%s"m,(num_tabs==1 ? "\t" : \
  180220. (num_tabs==2 ? "\t\t":(num_tabs>2 ? "\t\t\t":"")))); \
  180221. }
  180222. #define png_debug1(l,m,p1) \
  180223. { \
  180224. int num_tabs=l; \
  180225. fprintf(PNG_DEBUG_FILE,"%s"m,(num_tabs==1 ? "\t" : \
  180226. (num_tabs==2 ? "\t\t":(num_tabs>2 ? "\t\t\t":""))),p1); \
  180227. }
  180228. #define png_debug2(l,m,p1,p2) \
  180229. { \
  180230. int num_tabs=l; \
  180231. fprintf(PNG_DEBUG_FILE,"%s"m,(num_tabs==1 ? "\t" : \
  180232. (num_tabs==2 ? "\t\t":(num_tabs>2 ? "\t\t\t":""))),p1,p2); \
  180233. }
  180234. #endif /* (PNG_DEBUG > 1) */
  180235. #endif /* _MSC_VER */
  180236. #endif /* (PNG_DEBUG > 0) */
  180237. #endif /* PNG_DEBUG */
  180238. #ifndef png_debug
  180239. #define png_debug(l, m)
  180240. #endif
  180241. #ifndef png_debug1
  180242. #define png_debug1(l, m, p1)
  180243. #endif
  180244. #ifndef png_debug2
  180245. #define png_debug2(l, m, p1, p2)
  180246. #endif
  180247. extern PNG_EXPORT(png_charp,png_get_copyright) PNGARG((png_structp png_ptr));
  180248. extern PNG_EXPORT(png_charp,png_get_header_ver) PNGARG((png_structp png_ptr));
  180249. extern PNG_EXPORT(png_charp,png_get_header_version) PNGARG((png_structp png_ptr));
  180250. extern PNG_EXPORT(png_charp,png_get_libpng_ver) PNGARG((png_structp png_ptr));
  180251. #ifdef PNG_MNG_FEATURES_SUPPORTED
  180252. extern PNG_EXPORT(png_uint_32,png_permit_mng_features) PNGARG((png_structp
  180253. png_ptr, png_uint_32 mng_features_permitted));
  180254. #endif
  180255. /* For use in png_set_keep_unknown, added to version 1.2.6 */
  180256. #define PNG_HANDLE_CHUNK_AS_DEFAULT 0
  180257. #define PNG_HANDLE_CHUNK_NEVER 1
  180258. #define PNG_HANDLE_CHUNK_IF_SAFE 2
  180259. #define PNG_HANDLE_CHUNK_ALWAYS 3
  180260. /* Added to version 1.2.0 */
  180261. #if defined(PNG_ASSEMBLER_CODE_SUPPORTED)
  180262. #if defined(PNG_MMX_CODE_SUPPORTED)
  180263. #define PNG_ASM_FLAG_MMX_SUPPORT_COMPILED 0x01 /* not user-settable */
  180264. #define PNG_ASM_FLAG_MMX_SUPPORT_IN_CPU 0x02 /* not user-settable */
  180265. #define PNG_ASM_FLAG_MMX_READ_COMBINE_ROW 0x04
  180266. #define PNG_ASM_FLAG_MMX_READ_INTERLACE 0x08
  180267. #define PNG_ASM_FLAG_MMX_READ_FILTER_SUB 0x10
  180268. #define PNG_ASM_FLAG_MMX_READ_FILTER_UP 0x20
  180269. #define PNG_ASM_FLAG_MMX_READ_FILTER_AVG 0x40
  180270. #define PNG_ASM_FLAG_MMX_READ_FILTER_PAETH 0x80
  180271. #define PNG_ASM_FLAGS_INITIALIZED 0x80000000 /* not user-settable */
  180272. #define PNG_MMX_READ_FLAGS ( PNG_ASM_FLAG_MMX_READ_COMBINE_ROW \
  180273. | PNG_ASM_FLAG_MMX_READ_INTERLACE \
  180274. | PNG_ASM_FLAG_MMX_READ_FILTER_SUB \
  180275. | PNG_ASM_FLAG_MMX_READ_FILTER_UP \
  180276. | PNG_ASM_FLAG_MMX_READ_FILTER_AVG \
  180277. | PNG_ASM_FLAG_MMX_READ_FILTER_PAETH )
  180278. #define PNG_MMX_WRITE_FLAGS ( 0 )
  180279. #define PNG_MMX_FLAGS ( PNG_ASM_FLAG_MMX_SUPPORT_COMPILED \
  180280. | PNG_ASM_FLAG_MMX_SUPPORT_IN_CPU \
  180281. | PNG_MMX_READ_FLAGS \
  180282. | PNG_MMX_WRITE_FLAGS )
  180283. #define PNG_SELECT_READ 1
  180284. #define PNG_SELECT_WRITE 2
  180285. #endif /* PNG_MMX_CODE_SUPPORTED */
  180286. #if !defined(PNG_1_0_X)
  180287. /* pngget.c */
  180288. extern PNG_EXPORT(png_uint_32,png_get_mmx_flagmask)
  180289. PNGARG((int flag_select, int *compilerID));
  180290. /* pngget.c */
  180291. extern PNG_EXPORT(png_uint_32,png_get_asm_flagmask)
  180292. PNGARG((int flag_select));
  180293. /* pngget.c */
  180294. extern PNG_EXPORT(png_uint_32,png_get_asm_flags)
  180295. PNGARG((png_structp png_ptr));
  180296. /* pngget.c */
  180297. extern PNG_EXPORT(png_byte,png_get_mmx_bitdepth_threshold)
  180298. PNGARG((png_structp png_ptr));
  180299. /* pngget.c */
  180300. extern PNG_EXPORT(png_uint_32,png_get_mmx_rowbytes_threshold)
  180301. PNGARG((png_structp png_ptr));
  180302. /* pngset.c */
  180303. extern PNG_EXPORT(void,png_set_asm_flags)
  180304. PNGARG((png_structp png_ptr, png_uint_32 asm_flags));
  180305. /* pngset.c */
  180306. extern PNG_EXPORT(void,png_set_mmx_thresholds)
  180307. PNGARG((png_structp png_ptr, png_byte mmx_bitdepth_threshold,
  180308. png_uint_32 mmx_rowbytes_threshold));
  180309. #endif /* PNG_1_0_X */
  180310. #if !defined(PNG_1_0_X)
  180311. /* png.c, pnggccrd.c, or pngvcrd.c */
  180312. extern PNG_EXPORT(int,png_mmx_support) PNGARG((void));
  180313. #endif /* PNG_ASSEMBLER_CODE_SUPPORTED */
  180314. /* Strip the prepended error numbers ("#nnn ") from error and warning
  180315. * messages before passing them to the error or warning handler. */
  180316. #ifdef PNG_ERROR_NUMBERS_SUPPORTED
  180317. extern PNG_EXPORT(void,png_set_strip_error_numbers) PNGARG((png_structp
  180318. png_ptr, png_uint_32 strip_mode));
  180319. #endif
  180320. #endif /* PNG_1_0_X */
  180321. /* Added at libpng-1.2.6 */
  180322. #ifdef PNG_SET_USER_LIMITS_SUPPORTED
  180323. extern PNG_EXPORT(void,png_set_user_limits) PNGARG((png_structp
  180324. png_ptr, png_uint_32 user_width_max, png_uint_32 user_height_max));
  180325. extern PNG_EXPORT(png_uint_32,png_get_user_width_max) PNGARG((png_structp
  180326. png_ptr));
  180327. extern PNG_EXPORT(png_uint_32,png_get_user_height_max) PNGARG((png_structp
  180328. png_ptr));
  180329. #endif
  180330. /* Maintainer: Put new public prototypes here ^, in libpng.3, and project defs */
  180331. #ifdef PNG_READ_COMPOSITE_NODIV_SUPPORTED
  180332. /* With these routines we avoid an integer divide, which will be slower on
  180333. * most machines. However, it does take more operations than the corresponding
  180334. * divide method, so it may be slower on a few RISC systems. There are two
  180335. * shifts (by 8 or 16 bits) and an addition, versus a single integer divide.
  180336. *
  180337. * Note that the rounding factors are NOT supposed to be the same! 128 and
  180338. * 32768 are correct for the NODIV code; 127 and 32767 are correct for the
  180339. * standard method.
  180340. *
  180341. * [Optimized code by Greg Roelofs and Mark Adler...blame us for bugs. :-) ]
  180342. */
  180343. /* fg and bg should be in `gamma 1.0' space; alpha is the opacity */
  180344. # define png_composite(composite, fg, alpha, bg) \
  180345. { png_uint_16 temp = (png_uint_16)((png_uint_16)(fg) * (png_uint_16)(alpha) \
  180346. + (png_uint_16)(bg)*(png_uint_16)(255 - \
  180347. (png_uint_16)(alpha)) + (png_uint_16)128); \
  180348. (composite) = (png_byte)((temp + (temp >> 8)) >> 8); }
  180349. # define png_composite_16(composite, fg, alpha, bg) \
  180350. { png_uint_32 temp = (png_uint_32)((png_uint_32)(fg) * (png_uint_32)(alpha) \
  180351. + (png_uint_32)(bg)*(png_uint_32)(65535L - \
  180352. (png_uint_32)(alpha)) + (png_uint_32)32768L); \
  180353. (composite) = (png_uint_16)((temp + (temp >> 16)) >> 16); }
  180354. #else /* standard method using integer division */
  180355. # define png_composite(composite, fg, alpha, bg) \
  180356. (composite) = (png_byte)(((png_uint_16)(fg) * (png_uint_16)(alpha) + \
  180357. (png_uint_16)(bg) * (png_uint_16)(255 - (png_uint_16)(alpha)) + \
  180358. (png_uint_16)127) / 255)
  180359. # define png_composite_16(composite, fg, alpha, bg) \
  180360. (composite) = (png_uint_16)(((png_uint_32)(fg) * (png_uint_32)(alpha) + \
  180361. (png_uint_32)(bg)*(png_uint_32)(65535L - (png_uint_32)(alpha)) + \
  180362. (png_uint_32)32767) / (png_uint_32)65535L)
  180363. #endif /* PNG_READ_COMPOSITE_NODIV_SUPPORTED */
  180364. /* Inline macros to do direct reads of bytes from the input buffer. These
  180365. * require that you are using an architecture that uses PNG byte ordering
  180366. * (MSB first) and supports unaligned data storage. I think that PowerPC
  180367. * in big-endian mode and 680x0 are the only ones that will support this.
  180368. * The x86 line of processors definitely do not. The png_get_int_32()
  180369. * routine also assumes we are using two's complement format for negative
  180370. * values, which is almost certainly true.
  180371. */
  180372. #if defined(PNG_READ_BIG_ENDIAN_SUPPORTED)
  180373. # define png_get_uint_32(buf) ( *((png_uint_32p) (buf)))
  180374. # define png_get_uint_16(buf) ( *((png_uint_16p) (buf)))
  180375. # define png_get_int_32(buf) ( *((png_int_32p) (buf)))
  180376. #else
  180377. extern PNG_EXPORT(png_uint_32,png_get_uint_32) PNGARG((png_bytep buf));
  180378. extern PNG_EXPORT(png_uint_16,png_get_uint_16) PNGARG((png_bytep buf));
  180379. extern PNG_EXPORT(png_int_32,png_get_int_32) PNGARG((png_bytep buf));
  180380. #endif /* !PNG_READ_BIG_ENDIAN_SUPPORTED */
  180381. extern PNG_EXPORT(png_uint_32,png_get_uint_31)
  180382. PNGARG((png_structp png_ptr, png_bytep buf));
  180383. /* No png_get_int_16 -- may be added if there's a real need for it. */
  180384. /* Place a 32-bit number into a buffer in PNG byte order (big-endian).
  180385. */
  180386. extern PNG_EXPORT(void,png_save_uint_32)
  180387. PNGARG((png_bytep buf, png_uint_32 i));
  180388. extern PNG_EXPORT(void,png_save_int_32)
  180389. PNGARG((png_bytep buf, png_int_32 i));
  180390. /* Place a 16-bit number into a buffer in PNG byte order.
  180391. * The parameter is declared unsigned int, not png_uint_16,
  180392. * just to avoid potential problems on pre-ANSI C compilers.
  180393. */
  180394. extern PNG_EXPORT(void,png_save_uint_16)
  180395. PNGARG((png_bytep buf, unsigned int i));
  180396. /* No png_save_int_16 -- may be added if there's a real need for it. */
  180397. /* ************************************************************************* */
  180398. /* These next functions are used internally in the code. They generally
  180399. * shouldn't be used unless you are writing code to add or replace some
  180400. * functionality in libpng. More information about most functions can
  180401. * be found in the files where the functions are located.
  180402. */
  180403. /* Various modes of operation, that are visible to applications because
  180404. * they are used for unknown chunk location.
  180405. */
  180406. #define PNG_HAVE_IHDR 0x01
  180407. #define PNG_HAVE_PLTE 0x02
  180408. #define PNG_HAVE_IDAT 0x04
  180409. #define PNG_AFTER_IDAT 0x08 /* Have complete zlib datastream */
  180410. #define PNG_HAVE_IEND 0x10
  180411. #if defined(PNG_INTERNAL)
  180412. /* More modes of operation. Note that after an init, mode is set to
  180413. * zero automatically when the structure is created.
  180414. */
  180415. #define PNG_HAVE_gAMA 0x20
  180416. #define PNG_HAVE_cHRM 0x40
  180417. #define PNG_HAVE_sRGB 0x80
  180418. #define PNG_HAVE_CHUNK_HEADER 0x100
  180419. #define PNG_WROTE_tIME 0x200
  180420. #define PNG_WROTE_INFO_BEFORE_PLTE 0x400
  180421. #define PNG_BACKGROUND_IS_GRAY 0x800
  180422. #define PNG_HAVE_PNG_SIGNATURE 0x1000
  180423. #define PNG_HAVE_CHUNK_AFTER_IDAT 0x2000 /* Have another chunk after IDAT */
  180424. /* flags for the transformations the PNG library does on the image data */
  180425. #define PNG_BGR 0x0001
  180426. #define PNG_INTERLACE 0x0002
  180427. #define PNG_PACK 0x0004
  180428. #define PNG_SHIFT 0x0008
  180429. #define PNG_SWAP_BYTES 0x0010
  180430. #define PNG_INVERT_MONO 0x0020
  180431. #define PNG_DITHER 0x0040
  180432. #define PNG_BACKGROUND 0x0080
  180433. #define PNG_BACKGROUND_EXPAND 0x0100
  180434. /* 0x0200 unused */
  180435. #define PNG_16_TO_8 0x0400
  180436. #define PNG_RGBA 0x0800
  180437. #define PNG_EXPAND 0x1000
  180438. #define PNG_GAMMA 0x2000
  180439. #define PNG_GRAY_TO_RGB 0x4000
  180440. #define PNG_FILLER 0x8000L
  180441. #define PNG_PACKSWAP 0x10000L
  180442. #define PNG_SWAP_ALPHA 0x20000L
  180443. #define PNG_STRIP_ALPHA 0x40000L
  180444. #define PNG_INVERT_ALPHA 0x80000L
  180445. #define PNG_USER_TRANSFORM 0x100000L
  180446. #define PNG_RGB_TO_GRAY_ERR 0x200000L
  180447. #define PNG_RGB_TO_GRAY_WARN 0x400000L
  180448. #define PNG_RGB_TO_GRAY 0x600000L /* two bits, RGB_TO_GRAY_ERR|WARN */
  180449. /* 0x800000L Unused */
  180450. #define PNG_ADD_ALPHA 0x1000000L /* Added to libpng-1.2.7 */
  180451. #define PNG_EXPAND_tRNS 0x2000000L /* Added to libpng-1.2.9 */
  180452. /* 0x4000000L unused */
  180453. /* 0x8000000L unused */
  180454. /* 0x10000000L unused */
  180455. /* 0x20000000L unused */
  180456. /* 0x40000000L unused */
  180457. /* flags for png_create_struct */
  180458. #define PNG_STRUCT_PNG 0x0001
  180459. #define PNG_STRUCT_INFO 0x0002
  180460. /* Scaling factor for filter heuristic weighting calculations */
  180461. #define PNG_WEIGHT_SHIFT 8
  180462. #define PNG_WEIGHT_FACTOR (1<<(PNG_WEIGHT_SHIFT))
  180463. #define PNG_COST_SHIFT 3
  180464. #define PNG_COST_FACTOR (1<<(PNG_COST_SHIFT))
  180465. /* flags for the png_ptr->flags rather than declaring a byte for each one */
  180466. #define PNG_FLAG_ZLIB_CUSTOM_STRATEGY 0x0001
  180467. #define PNG_FLAG_ZLIB_CUSTOM_LEVEL 0x0002
  180468. #define PNG_FLAG_ZLIB_CUSTOM_MEM_LEVEL 0x0004
  180469. #define PNG_FLAG_ZLIB_CUSTOM_WINDOW_BITS 0x0008
  180470. #define PNG_FLAG_ZLIB_CUSTOM_METHOD 0x0010
  180471. #define PNG_FLAG_ZLIB_FINISHED 0x0020
  180472. #define PNG_FLAG_ROW_INIT 0x0040
  180473. #define PNG_FLAG_FILLER_AFTER 0x0080
  180474. #define PNG_FLAG_CRC_ANCILLARY_USE 0x0100
  180475. #define PNG_FLAG_CRC_ANCILLARY_NOWARN 0x0200
  180476. #define PNG_FLAG_CRC_CRITICAL_USE 0x0400
  180477. #define PNG_FLAG_CRC_CRITICAL_IGNORE 0x0800
  180478. #define PNG_FLAG_FREE_PLTE 0x1000
  180479. #define PNG_FLAG_FREE_TRNS 0x2000
  180480. #define PNG_FLAG_FREE_HIST 0x4000
  180481. #define PNG_FLAG_KEEP_UNKNOWN_CHUNKS 0x8000L
  180482. #define PNG_FLAG_KEEP_UNSAFE_CHUNKS 0x10000L
  180483. #define PNG_FLAG_LIBRARY_MISMATCH 0x20000L
  180484. #define PNG_FLAG_STRIP_ERROR_NUMBERS 0x40000L
  180485. #define PNG_FLAG_STRIP_ERROR_TEXT 0x80000L
  180486. #define PNG_FLAG_MALLOC_NULL_MEM_OK 0x100000L
  180487. #define PNG_FLAG_ADD_ALPHA 0x200000L /* Added to libpng-1.2.8 */
  180488. #define PNG_FLAG_STRIP_ALPHA 0x400000L /* Added to libpng-1.2.8 */
  180489. /* 0x800000L unused */
  180490. /* 0x1000000L unused */
  180491. /* 0x2000000L unused */
  180492. /* 0x4000000L unused */
  180493. /* 0x8000000L unused */
  180494. /* 0x10000000L unused */
  180495. /* 0x20000000L unused */
  180496. /* 0x40000000L unused */
  180497. #define PNG_FLAG_CRC_ANCILLARY_MASK (PNG_FLAG_CRC_ANCILLARY_USE | \
  180498. PNG_FLAG_CRC_ANCILLARY_NOWARN)
  180499. #define PNG_FLAG_CRC_CRITICAL_MASK (PNG_FLAG_CRC_CRITICAL_USE | \
  180500. PNG_FLAG_CRC_CRITICAL_IGNORE)
  180501. #define PNG_FLAG_CRC_MASK (PNG_FLAG_CRC_ANCILLARY_MASK | \
  180502. PNG_FLAG_CRC_CRITICAL_MASK)
  180503. /* save typing and make code easier to understand */
  180504. #define PNG_COLOR_DIST(c1, c2) (abs((int)((c1).red) - (int)((c2).red)) + \
  180505. abs((int)((c1).green) - (int)((c2).green)) + \
  180506. abs((int)((c1).blue) - (int)((c2).blue)))
  180507. /* Added to libpng-1.2.6 JB */
  180508. #define PNG_ROWBYTES(pixel_bits, width) \
  180509. ((pixel_bits) >= 8 ? \
  180510. ((width) * (((png_uint_32)(pixel_bits)) >> 3)) : \
  180511. (( ((width) * ((png_uint_32)(pixel_bits))) + 7) >> 3) )
  180512. /* PNG_OUT_OF_RANGE returns true if value is outside the range
  180513. ideal-delta..ideal+delta. Each argument is evaluated twice.
  180514. "ideal" and "delta" should be constants, normally simple
  180515. integers, "value" a variable. Added to libpng-1.2.6 JB */
  180516. #define PNG_OUT_OF_RANGE(value, ideal, delta) \
  180517. ( (value) < (ideal)-(delta) || (value) > (ideal)+(delta) )
  180518. /* variables declared in png.c - only it needs to define PNG_NO_EXTERN */
  180519. #if !defined(PNG_NO_EXTERN) || defined(PNG_ALWAYS_EXTERN)
  180520. /* place to hold the signature string for a PNG file. */
  180521. #ifdef PNG_USE_GLOBAL_ARRAYS
  180522. PNG_EXPORT_VAR (PNG_CONST png_byte FARDATA) png_sig[8];
  180523. #else
  180524. #endif
  180525. #endif /* PNG_NO_EXTERN */
  180526. /* Constant strings for known chunk types. If you need to add a chunk,
  180527. * define the name here, and add an invocation of the macro in png.c and
  180528. * wherever it's needed.
  180529. */
  180530. #define PNG_IHDR png_byte png_IHDR[5] = { 73, 72, 68, 82, '\0'}
  180531. #define PNG_IDAT png_byte png_IDAT[5] = { 73, 68, 65, 84, '\0'}
  180532. #define PNG_IEND png_byte png_IEND[5] = { 73, 69, 78, 68, '\0'}
  180533. #define PNG_PLTE png_byte png_PLTE[5] = { 80, 76, 84, 69, '\0'}
  180534. #define PNG_bKGD png_byte png_bKGD[5] = { 98, 75, 71, 68, '\0'}
  180535. #define PNG_cHRM png_byte png_cHRM[5] = { 99, 72, 82, 77, '\0'}
  180536. #define PNG_gAMA png_byte png_gAMA[5] = {103, 65, 77, 65, '\0'}
  180537. #define PNG_hIST png_byte png_hIST[5] = {104, 73, 83, 84, '\0'}
  180538. #define PNG_iCCP png_byte png_iCCP[5] = {105, 67, 67, 80, '\0'}
  180539. #define PNG_iTXt png_byte png_iTXt[5] = {105, 84, 88, 116, '\0'}
  180540. #define PNG_oFFs png_byte png_oFFs[5] = {111, 70, 70, 115, '\0'}
  180541. #define PNG_pCAL png_byte png_pCAL[5] = {112, 67, 65, 76, '\0'}
  180542. #define PNG_sCAL png_byte png_sCAL[5] = {115, 67, 65, 76, '\0'}
  180543. #define PNG_pHYs png_byte png_pHYs[5] = {112, 72, 89, 115, '\0'}
  180544. #define PNG_sBIT png_byte png_sBIT[5] = {115, 66, 73, 84, '\0'}
  180545. #define PNG_sPLT png_byte png_sPLT[5] = {115, 80, 76, 84, '\0'}
  180546. #define PNG_sRGB png_byte png_sRGB[5] = {115, 82, 71, 66, '\0'}
  180547. #define PNG_tEXt png_byte png_tEXt[5] = {116, 69, 88, 116, '\0'}
  180548. #define PNG_tIME png_byte png_tIME[5] = {116, 73, 77, 69, '\0'}
  180549. #define PNG_tRNS png_byte png_tRNS[5] = {116, 82, 78, 83, '\0'}
  180550. #define PNG_zTXt png_byte png_zTXt[5] = {122, 84, 88, 116, '\0'}
  180551. #ifdef PNG_USE_GLOBAL_ARRAYS
  180552. PNG_EXPORT_VAR (png_byte FARDATA) png_IHDR[5];
  180553. PNG_EXPORT_VAR (png_byte FARDATA) png_IDAT[5];
  180554. PNG_EXPORT_VAR (png_byte FARDATA) png_IEND[5];
  180555. PNG_EXPORT_VAR (png_byte FARDATA) png_PLTE[5];
  180556. PNG_EXPORT_VAR (png_byte FARDATA) png_bKGD[5];
  180557. PNG_EXPORT_VAR (png_byte FARDATA) png_cHRM[5];
  180558. PNG_EXPORT_VAR (png_byte FARDATA) png_gAMA[5];
  180559. PNG_EXPORT_VAR (png_byte FARDATA) png_hIST[5];
  180560. PNG_EXPORT_VAR (png_byte FARDATA) png_iCCP[5];
  180561. PNG_EXPORT_VAR (png_byte FARDATA) png_iTXt[5];
  180562. PNG_EXPORT_VAR (png_byte FARDATA) png_oFFs[5];
  180563. PNG_EXPORT_VAR (png_byte FARDATA) png_pCAL[5];
  180564. PNG_EXPORT_VAR (png_byte FARDATA) png_sCAL[5];
  180565. PNG_EXPORT_VAR (png_byte FARDATA) png_pHYs[5];
  180566. PNG_EXPORT_VAR (png_byte FARDATA) png_sBIT[5];
  180567. PNG_EXPORT_VAR (png_byte FARDATA) png_sPLT[5];
  180568. PNG_EXPORT_VAR (png_byte FARDATA) png_sRGB[5];
  180569. PNG_EXPORT_VAR (png_byte FARDATA) png_tEXt[5];
  180570. PNG_EXPORT_VAR (png_byte FARDATA) png_tIME[5];
  180571. PNG_EXPORT_VAR (png_byte FARDATA) png_tRNS[5];
  180572. PNG_EXPORT_VAR (png_byte FARDATA) png_zTXt[5];
  180573. #endif /* PNG_USE_GLOBAL_ARRAYS */
  180574. #if defined(PNG_1_0_X) || defined (PNG_1_2_X)
  180575. /* Initialize png_ptr struct for reading, and allocate any other memory.
  180576. * (old interface - DEPRECATED - use png_create_read_struct instead).
  180577. */
  180578. extern PNG_EXPORT(void,png_read_init) PNGARG((png_structp png_ptr));
  180579. #undef png_read_init
  180580. #define png_read_init(png_ptr) png_read_init_3(&png_ptr, \
  180581. PNG_LIBPNG_VER_STRING, png_sizeof(png_struct));
  180582. #endif
  180583. extern PNG_EXPORT(void,png_read_init_3) PNGARG((png_structpp ptr_ptr,
  180584. png_const_charp user_png_ver, png_size_t png_struct_size));
  180585. #if defined(PNG_1_0_X) || defined (PNG_1_2_X)
  180586. extern PNG_EXPORT(void,png_read_init_2) PNGARG((png_structp png_ptr,
  180587. png_const_charp user_png_ver, png_size_t png_struct_size, png_size_t
  180588. png_info_size));
  180589. #endif
  180590. #if defined(PNG_1_0_X) || defined (PNG_1_2_X)
  180591. /* Initialize png_ptr struct for writing, and allocate any other memory.
  180592. * (old interface - DEPRECATED - use png_create_write_struct instead).
  180593. */
  180594. extern PNG_EXPORT(void,png_write_init) PNGARG((png_structp png_ptr));
  180595. #undef png_write_init
  180596. #define png_write_init(png_ptr) png_write_init_3(&png_ptr, \
  180597. PNG_LIBPNG_VER_STRING, png_sizeof(png_struct));
  180598. #endif
  180599. extern PNG_EXPORT(void,png_write_init_3) PNGARG((png_structpp ptr_ptr,
  180600. png_const_charp user_png_ver, png_size_t png_struct_size));
  180601. extern PNG_EXPORT(void,png_write_init_2) PNGARG((png_structp png_ptr,
  180602. png_const_charp user_png_ver, png_size_t png_struct_size, png_size_t
  180603. png_info_size));
  180604. /* Allocate memory for an internal libpng struct */
  180605. PNG_EXTERN png_voidp png_create_struct PNGARG((int type));
  180606. /* Free memory from internal libpng struct */
  180607. PNG_EXTERN void png_destroy_struct PNGARG((png_voidp struct_ptr));
  180608. PNG_EXTERN png_voidp png_create_struct_2 PNGARG((int type, png_malloc_ptr
  180609. malloc_fn, png_voidp mem_ptr));
  180610. PNG_EXTERN void png_destroy_struct_2 PNGARG((png_voidp struct_ptr,
  180611. png_free_ptr free_fn, png_voidp mem_ptr));
  180612. /* Free any memory that info_ptr points to and reset struct. */
  180613. PNG_EXTERN void png_info_destroy PNGARG((png_structp png_ptr,
  180614. png_infop info_ptr));
  180615. #ifndef PNG_1_0_X
  180616. /* Function to allocate memory for zlib. */
  180617. PNG_EXTERN voidpf png_zalloc PNGARG((voidpf png_ptr, uInt items, uInt size));
  180618. /* Function to free memory for zlib */
  180619. PNG_EXTERN void png_zfree PNGARG((voidpf png_ptr, voidpf ptr));
  180620. #ifdef PNG_SIZE_T
  180621. /* Function to convert a sizeof an item to png_sizeof item */
  180622. PNG_EXTERN png_size_t PNGAPI png_convert_size PNGARG((size_t size));
  180623. #endif
  180624. /* Next four functions are used internally as callbacks. PNGAPI is required
  180625. * but not PNG_EXPORT. PNGAPI added at libpng version 1.2.3. */
  180626. PNG_EXTERN void PNGAPI png_default_read_data PNGARG((png_structp png_ptr,
  180627. png_bytep data, png_size_t length));
  180628. #ifdef PNG_PROGRESSIVE_READ_SUPPORTED
  180629. PNG_EXTERN void PNGAPI png_push_fill_buffer PNGARG((png_structp png_ptr,
  180630. png_bytep buffer, png_size_t length));
  180631. #endif
  180632. PNG_EXTERN void PNGAPI png_default_write_data PNGARG((png_structp png_ptr,
  180633. png_bytep data, png_size_t length));
  180634. #if defined(PNG_WRITE_FLUSH_SUPPORTED)
  180635. #if !defined(PNG_NO_STDIO)
  180636. PNG_EXTERN void PNGAPI png_default_flush PNGARG((png_structp png_ptr));
  180637. #endif
  180638. #endif
  180639. #else /* PNG_1_0_X */
  180640. #ifdef PNG_PROGRESSIVE_READ_SUPPORTED
  180641. PNG_EXTERN void png_push_fill_buffer PNGARG((png_structp png_ptr,
  180642. png_bytep buffer, png_size_t length));
  180643. #endif
  180644. #endif /* PNG_1_0_X */
  180645. /* Reset the CRC variable */
  180646. PNG_EXTERN void png_reset_crc PNGARG((png_structp png_ptr));
  180647. /* Write the "data" buffer to whatever output you are using. */
  180648. PNG_EXTERN void png_write_data PNGARG((png_structp png_ptr, png_bytep data,
  180649. png_size_t length));
  180650. /* Read data from whatever input you are using into the "data" buffer */
  180651. PNG_EXTERN void png_read_data PNGARG((png_structp png_ptr, png_bytep data,
  180652. png_size_t length));
  180653. /* Read bytes into buf, and update png_ptr->crc */
  180654. PNG_EXTERN void png_crc_read PNGARG((png_structp png_ptr, png_bytep buf,
  180655. png_size_t length));
  180656. /* Decompress data in a chunk that uses compression */
  180657. #if defined(PNG_zTXt_SUPPORTED) || defined(PNG_iTXt_SUPPORTED) || \
  180658. defined(PNG_iCCP_SUPPORTED) || defined(PNG_sPLT_SUPPORTED)
  180659. PNG_EXTERN png_charp png_decompress_chunk PNGARG((png_structp png_ptr,
  180660. int comp_type, png_charp chunkdata, png_size_t chunklength,
  180661. png_size_t prefix_length, png_size_t *data_length));
  180662. #endif
  180663. /* Read "skip" bytes, read the file crc, and (optionally) verify png_ptr->crc */
  180664. PNG_EXTERN int png_crc_finish PNGARG((png_structp png_ptr, png_uint_32 skip));
  180665. /* Read the CRC from the file and compare it to the libpng calculated CRC */
  180666. PNG_EXTERN int png_crc_error PNGARG((png_structp png_ptr));
  180667. /* Calculate the CRC over a section of data. Note that we are only
  180668. * passing a maximum of 64K on systems that have this as a memory limit,
  180669. * since this is the maximum buffer size we can specify.
  180670. */
  180671. PNG_EXTERN void png_calculate_crc PNGARG((png_structp png_ptr, png_bytep ptr,
  180672. png_size_t length));
  180673. #if defined(PNG_WRITE_FLUSH_SUPPORTED)
  180674. PNG_EXTERN void png_flush PNGARG((png_structp png_ptr));
  180675. #endif
  180676. /* simple function to write the signature */
  180677. PNG_EXTERN void png_write_sig PNGARG((png_structp png_ptr));
  180678. /* write various chunks */
  180679. /* Write the IHDR chunk, and update the png_struct with the necessary
  180680. * information.
  180681. */
  180682. PNG_EXTERN void png_write_IHDR PNGARG((png_structp png_ptr, png_uint_32 width,
  180683. png_uint_32 height,
  180684. int bit_depth, int color_type, int compression_method, int filter_method,
  180685. int interlace_method));
  180686. PNG_EXTERN void png_write_PLTE PNGARG((png_structp png_ptr, png_colorp palette,
  180687. png_uint_32 num_pal));
  180688. PNG_EXTERN void png_write_IDAT PNGARG((png_structp png_ptr, png_bytep data,
  180689. png_size_t length));
  180690. PNG_EXTERN void png_write_IEND PNGARG((png_structp png_ptr));
  180691. #if defined(PNG_WRITE_gAMA_SUPPORTED)
  180692. #ifdef PNG_FLOATING_POINT_SUPPORTED
  180693. PNG_EXTERN void png_write_gAMA PNGARG((png_structp png_ptr, double file_gamma));
  180694. #endif
  180695. #ifdef PNG_FIXED_POINT_SUPPORTED
  180696. PNG_EXTERN void png_write_gAMA_fixed PNGARG((png_structp png_ptr, png_fixed_point
  180697. file_gamma));
  180698. #endif
  180699. #endif
  180700. #if defined(PNG_WRITE_sBIT_SUPPORTED)
  180701. PNG_EXTERN void png_write_sBIT PNGARG((png_structp png_ptr, png_color_8p sbit,
  180702. int color_type));
  180703. #endif
  180704. #if defined(PNG_WRITE_cHRM_SUPPORTED)
  180705. #ifdef PNG_FLOATING_POINT_SUPPORTED
  180706. PNG_EXTERN void png_write_cHRM PNGARG((png_structp png_ptr,
  180707. double white_x, double white_y,
  180708. double red_x, double red_y, double green_x, double green_y,
  180709. double blue_x, double blue_y));
  180710. #endif
  180711. #ifdef PNG_FIXED_POINT_SUPPORTED
  180712. PNG_EXTERN void png_write_cHRM_fixed PNGARG((png_structp png_ptr,
  180713. png_fixed_point int_white_x, png_fixed_point int_white_y,
  180714. png_fixed_point int_red_x, png_fixed_point int_red_y, png_fixed_point
  180715. int_green_x, png_fixed_point int_green_y, png_fixed_point int_blue_x,
  180716. png_fixed_point int_blue_y));
  180717. #endif
  180718. #endif
  180719. #if defined(PNG_WRITE_sRGB_SUPPORTED)
  180720. PNG_EXTERN void png_write_sRGB PNGARG((png_structp png_ptr,
  180721. int intent));
  180722. #endif
  180723. #if defined(PNG_WRITE_iCCP_SUPPORTED)
  180724. PNG_EXTERN void png_write_iCCP PNGARG((png_structp png_ptr,
  180725. png_charp name, int compression_type,
  180726. png_charp profile, int proflen));
  180727. /* Note to maintainer: profile should be png_bytep */
  180728. #endif
  180729. #if defined(PNG_WRITE_sPLT_SUPPORTED)
  180730. PNG_EXTERN void png_write_sPLT PNGARG((png_structp png_ptr,
  180731. png_sPLT_tp palette));
  180732. #endif
  180733. #if defined(PNG_WRITE_tRNS_SUPPORTED)
  180734. PNG_EXTERN void png_write_tRNS PNGARG((png_structp png_ptr, png_bytep trans,
  180735. png_color_16p values, int number, int color_type));
  180736. #endif
  180737. #if defined(PNG_WRITE_bKGD_SUPPORTED)
  180738. PNG_EXTERN void png_write_bKGD PNGARG((png_structp png_ptr,
  180739. png_color_16p values, int color_type));
  180740. #endif
  180741. #if defined(PNG_WRITE_hIST_SUPPORTED)
  180742. PNG_EXTERN void png_write_hIST PNGARG((png_structp png_ptr, png_uint_16p hist,
  180743. int num_hist));
  180744. #endif
  180745. #if defined(PNG_WRITE_TEXT_SUPPORTED) || defined(PNG_WRITE_pCAL_SUPPORTED) || \
  180746. defined(PNG_WRITE_iCCP_SUPPORTED) || defined(PNG_WRITE_sPLT_SUPPORTED)
  180747. PNG_EXTERN png_size_t png_check_keyword PNGARG((png_structp png_ptr,
  180748. png_charp key, png_charpp new_key));
  180749. #endif
  180750. #if defined(PNG_WRITE_tEXt_SUPPORTED)
  180751. PNG_EXTERN void png_write_tEXt PNGARG((png_structp png_ptr, png_charp key,
  180752. png_charp text, png_size_t text_len));
  180753. #endif
  180754. #if defined(PNG_WRITE_zTXt_SUPPORTED)
  180755. PNG_EXTERN void png_write_zTXt PNGARG((png_structp png_ptr, png_charp key,
  180756. png_charp text, png_size_t text_len, int compression));
  180757. #endif
  180758. #if defined(PNG_WRITE_iTXt_SUPPORTED)
  180759. PNG_EXTERN void png_write_iTXt PNGARG((png_structp png_ptr,
  180760. int compression, png_charp key, png_charp lang, png_charp lang_key,
  180761. png_charp text));
  180762. #endif
  180763. #if defined(PNG_TEXT_SUPPORTED) /* Added at version 1.0.14 and 1.2.4 */
  180764. PNG_EXTERN int png_set_text_2 PNGARG((png_structp png_ptr,
  180765. png_infop info_ptr, png_textp text_ptr, int num_text));
  180766. #endif
  180767. #if defined(PNG_WRITE_oFFs_SUPPORTED)
  180768. PNG_EXTERN void png_write_oFFs PNGARG((png_structp png_ptr,
  180769. png_int_32 x_offset, png_int_32 y_offset, int unit_type));
  180770. #endif
  180771. #if defined(PNG_WRITE_pCAL_SUPPORTED)
  180772. PNG_EXTERN void png_write_pCAL PNGARG((png_structp png_ptr, png_charp purpose,
  180773. png_int_32 X0, png_int_32 X1, int type, int nparams,
  180774. png_charp units, png_charpp params));
  180775. #endif
  180776. #if defined(PNG_WRITE_pHYs_SUPPORTED)
  180777. PNG_EXTERN void png_write_pHYs PNGARG((png_structp png_ptr,
  180778. png_uint_32 x_pixels_per_unit, png_uint_32 y_pixels_per_unit,
  180779. int unit_type));
  180780. #endif
  180781. #if defined(PNG_WRITE_tIME_SUPPORTED)
  180782. PNG_EXTERN void png_write_tIME PNGARG((png_structp png_ptr,
  180783. png_timep mod_time));
  180784. #endif
  180785. #if defined(PNG_WRITE_sCAL_SUPPORTED)
  180786. #if defined(PNG_FLOATING_POINT_SUPPORTED) && !defined(PNG_NO_STDIO)
  180787. PNG_EXTERN void png_write_sCAL PNGARG((png_structp png_ptr,
  180788. int unit, double width, double height));
  180789. #else
  180790. #ifdef PNG_FIXED_POINT_SUPPORTED
  180791. PNG_EXTERN void png_write_sCAL_s PNGARG((png_structp png_ptr,
  180792. int unit, png_charp width, png_charp height));
  180793. #endif
  180794. #endif
  180795. #endif
  180796. /* Called when finished processing a row of data */
  180797. PNG_EXTERN void png_write_finish_row PNGARG((png_structp png_ptr));
  180798. /* Internal use only. Called before first row of data */
  180799. PNG_EXTERN void png_write_start_row PNGARG((png_structp png_ptr));
  180800. #if defined(PNG_READ_GAMMA_SUPPORTED)
  180801. PNG_EXTERN void png_build_gamma_table PNGARG((png_structp png_ptr));
  180802. #endif
  180803. /* combine a row of data, dealing with alpha, etc. if requested */
  180804. PNG_EXTERN void png_combine_row PNGARG((png_structp png_ptr, png_bytep row,
  180805. int mask));
  180806. #if defined(PNG_READ_INTERLACING_SUPPORTED)
  180807. /* expand an interlaced row */
  180808. /* OLD pre-1.0.9 interface:
  180809. PNG_EXTERN void png_do_read_interlace PNGARG((png_row_infop row_info,
  180810. png_bytep row, int pass, png_uint_32 transformations));
  180811. */
  180812. PNG_EXTERN void png_do_read_interlace PNGARG((png_structp png_ptr));
  180813. #endif
  180814. /* GRR TO DO (2.0 or whenever): simplify other internal calling interfaces */
  180815. #if defined(PNG_WRITE_INTERLACING_SUPPORTED)
  180816. /* grab pixels out of a row for an interlaced pass */
  180817. PNG_EXTERN void png_do_write_interlace PNGARG((png_row_infop row_info,
  180818. png_bytep row, int pass));
  180819. #endif
  180820. /* unfilter a row */
  180821. PNG_EXTERN void png_read_filter_row PNGARG((png_structp png_ptr,
  180822. png_row_infop row_info, png_bytep row, png_bytep prev_row, int filter));
  180823. /* Choose the best filter to use and filter the row data */
  180824. PNG_EXTERN void png_write_find_filter PNGARG((png_structp png_ptr,
  180825. png_row_infop row_info));
  180826. /* Write out the filtered row. */
  180827. PNG_EXTERN void png_write_filtered_row PNGARG((png_structp png_ptr,
  180828. png_bytep filtered_row));
  180829. /* finish a row while reading, dealing with interlacing passes, etc. */
  180830. PNG_EXTERN void png_read_finish_row PNGARG((png_structp png_ptr));
  180831. /* initialize the row buffers, etc. */
  180832. PNG_EXTERN void png_read_start_row PNGARG((png_structp png_ptr));
  180833. /* optional call to update the users info structure */
  180834. PNG_EXTERN void png_read_transform_info PNGARG((png_structp png_ptr,
  180835. png_infop info_ptr));
  180836. /* these are the functions that do the transformations */
  180837. #if defined(PNG_READ_FILLER_SUPPORTED)
  180838. PNG_EXTERN void png_do_read_filler PNGARG((png_row_infop row_info,
  180839. png_bytep row, png_uint_32 filler, png_uint_32 flags));
  180840. #endif
  180841. #if defined(PNG_READ_SWAP_ALPHA_SUPPORTED)
  180842. PNG_EXTERN void png_do_read_swap_alpha PNGARG((png_row_infop row_info,
  180843. png_bytep row));
  180844. #endif
  180845. #if defined(PNG_WRITE_SWAP_ALPHA_SUPPORTED)
  180846. PNG_EXTERN void png_do_write_swap_alpha PNGARG((png_row_infop row_info,
  180847. png_bytep row));
  180848. #endif
  180849. #if defined(PNG_READ_INVERT_ALPHA_SUPPORTED)
  180850. PNG_EXTERN void png_do_read_invert_alpha PNGARG((png_row_infop row_info,
  180851. png_bytep row));
  180852. #endif
  180853. #if defined(PNG_WRITE_INVERT_ALPHA_SUPPORTED)
  180854. PNG_EXTERN void png_do_write_invert_alpha PNGARG((png_row_infop row_info,
  180855. png_bytep row));
  180856. #endif
  180857. #if defined(PNG_WRITE_FILLER_SUPPORTED) || \
  180858. defined(PNG_READ_STRIP_ALPHA_SUPPORTED)
  180859. PNG_EXTERN void png_do_strip_filler PNGARG((png_row_infop row_info,
  180860. png_bytep row, png_uint_32 flags));
  180861. #endif
  180862. #if defined(PNG_READ_SWAP_SUPPORTED) || defined(PNG_WRITE_SWAP_SUPPORTED)
  180863. PNG_EXTERN void png_do_swap PNGARG((png_row_infop row_info, png_bytep row));
  180864. #endif
  180865. #if defined(PNG_READ_PACKSWAP_SUPPORTED) || defined(PNG_WRITE_PACKSWAP_SUPPORTED)
  180866. PNG_EXTERN void png_do_packswap PNGARG((png_row_infop row_info, png_bytep row));
  180867. #endif
  180868. #if defined(PNG_READ_RGB_TO_GRAY_SUPPORTED)
  180869. PNG_EXTERN int png_do_rgb_to_gray PNGARG((png_structp png_ptr, png_row_infop
  180870. row_info, png_bytep row));
  180871. #endif
  180872. #if defined(PNG_READ_GRAY_TO_RGB_SUPPORTED)
  180873. PNG_EXTERN void png_do_gray_to_rgb PNGARG((png_row_infop row_info,
  180874. png_bytep row));
  180875. #endif
  180876. #if defined(PNG_READ_PACK_SUPPORTED)
  180877. PNG_EXTERN void png_do_unpack PNGARG((png_row_infop row_info, png_bytep row));
  180878. #endif
  180879. #if defined(PNG_READ_SHIFT_SUPPORTED)
  180880. PNG_EXTERN void png_do_unshift PNGARG((png_row_infop row_info, png_bytep row,
  180881. png_color_8p sig_bits));
  180882. #endif
  180883. #if defined(PNG_READ_INVERT_SUPPORTED) || defined(PNG_WRITE_INVERT_SUPPORTED)
  180884. PNG_EXTERN void png_do_invert PNGARG((png_row_infop row_info, png_bytep row));
  180885. #endif
  180886. #if defined(PNG_READ_16_TO_8_SUPPORTED)
  180887. PNG_EXTERN void png_do_chop PNGARG((png_row_infop row_info, png_bytep row));
  180888. #endif
  180889. #if defined(PNG_READ_DITHER_SUPPORTED)
  180890. PNG_EXTERN void png_do_dither PNGARG((png_row_infop row_info,
  180891. png_bytep row, png_bytep palette_lookup, png_bytep dither_lookup));
  180892. # if defined(PNG_CORRECT_PALETTE_SUPPORTED)
  180893. PNG_EXTERN void png_correct_palette PNGARG((png_structp png_ptr,
  180894. png_colorp palette, int num_palette));
  180895. # endif
  180896. #endif
  180897. #if defined(PNG_READ_BGR_SUPPORTED) || defined(PNG_WRITE_BGR_SUPPORTED)
  180898. PNG_EXTERN void png_do_bgr PNGARG((png_row_infop row_info, png_bytep row));
  180899. #endif
  180900. #if defined(PNG_WRITE_PACK_SUPPORTED)
  180901. PNG_EXTERN void png_do_pack PNGARG((png_row_infop row_info,
  180902. png_bytep row, png_uint_32 bit_depth));
  180903. #endif
  180904. #if defined(PNG_WRITE_SHIFT_SUPPORTED)
  180905. PNG_EXTERN void png_do_shift PNGARG((png_row_infop row_info, png_bytep row,
  180906. png_color_8p bit_depth));
  180907. #endif
  180908. #if defined(PNG_READ_BACKGROUND_SUPPORTED)
  180909. #if defined(PNG_READ_GAMMA_SUPPORTED)
  180910. PNG_EXTERN void png_do_background PNGARG((png_row_infop row_info, png_bytep row,
  180911. png_color_16p trans_values, png_color_16p background,
  180912. png_color_16p background_1,
  180913. png_bytep gamma_table, png_bytep gamma_from_1, png_bytep gamma_to_1,
  180914. png_uint_16pp gamma_16, png_uint_16pp gamma_16_from_1,
  180915. png_uint_16pp gamma_16_to_1, int gamma_shift));
  180916. #else
  180917. PNG_EXTERN void png_do_background PNGARG((png_row_infop row_info, png_bytep row,
  180918. png_color_16p trans_values, png_color_16p background));
  180919. #endif
  180920. #endif
  180921. #if defined(PNG_READ_GAMMA_SUPPORTED)
  180922. PNG_EXTERN void png_do_gamma PNGARG((png_row_infop row_info, png_bytep row,
  180923. png_bytep gamma_table, png_uint_16pp gamma_16_table,
  180924. int gamma_shift));
  180925. #endif
  180926. #if defined(PNG_READ_EXPAND_SUPPORTED)
  180927. PNG_EXTERN void png_do_expand_palette PNGARG((png_row_infop row_info,
  180928. png_bytep row, png_colorp palette, png_bytep trans, int num_trans));
  180929. PNG_EXTERN void png_do_expand PNGARG((png_row_infop row_info,
  180930. png_bytep row, png_color_16p trans_value));
  180931. #endif
  180932. /* The following decodes the appropriate chunks, and does error correction,
  180933. * then calls the appropriate callback for the chunk if it is valid.
  180934. */
  180935. /* decode the IHDR chunk */
  180936. PNG_EXTERN void png_handle_IHDR PNGARG((png_structp png_ptr, png_infop info_ptr,
  180937. png_uint_32 length));
  180938. PNG_EXTERN void png_handle_PLTE PNGARG((png_structp png_ptr, png_infop info_ptr,
  180939. png_uint_32 length));
  180940. PNG_EXTERN void png_handle_IEND PNGARG((png_structp png_ptr, png_infop info_ptr,
  180941. png_uint_32 length));
  180942. #if defined(PNG_READ_bKGD_SUPPORTED)
  180943. PNG_EXTERN void png_handle_bKGD PNGARG((png_structp png_ptr, png_infop info_ptr,
  180944. png_uint_32 length));
  180945. #endif
  180946. #if defined(PNG_READ_cHRM_SUPPORTED)
  180947. PNG_EXTERN void png_handle_cHRM PNGARG((png_structp png_ptr, png_infop info_ptr,
  180948. png_uint_32 length));
  180949. #endif
  180950. #if defined(PNG_READ_gAMA_SUPPORTED)
  180951. PNG_EXTERN void png_handle_gAMA PNGARG((png_structp png_ptr, png_infop info_ptr,
  180952. png_uint_32 length));
  180953. #endif
  180954. #if defined(PNG_READ_hIST_SUPPORTED)
  180955. PNG_EXTERN void png_handle_hIST PNGARG((png_structp png_ptr, png_infop info_ptr,
  180956. png_uint_32 length));
  180957. #endif
  180958. #if defined(PNG_READ_iCCP_SUPPORTED)
  180959. extern void png_handle_iCCP PNGARG((png_structp png_ptr, png_infop info_ptr,
  180960. png_uint_32 length));
  180961. #endif /* PNG_READ_iCCP_SUPPORTED */
  180962. #if defined(PNG_READ_iTXt_SUPPORTED)
  180963. PNG_EXTERN void png_handle_iTXt PNGARG((png_structp png_ptr, png_infop info_ptr,
  180964. png_uint_32 length));
  180965. #endif
  180966. #if defined(PNG_READ_oFFs_SUPPORTED)
  180967. PNG_EXTERN void png_handle_oFFs PNGARG((png_structp png_ptr, png_infop info_ptr,
  180968. png_uint_32 length));
  180969. #endif
  180970. #if defined(PNG_READ_pCAL_SUPPORTED)
  180971. PNG_EXTERN void png_handle_pCAL PNGARG((png_structp png_ptr, png_infop info_ptr,
  180972. png_uint_32 length));
  180973. #endif
  180974. #if defined(PNG_READ_pHYs_SUPPORTED)
  180975. PNG_EXTERN void png_handle_pHYs PNGARG((png_structp png_ptr, png_infop info_ptr,
  180976. png_uint_32 length));
  180977. #endif
  180978. #if defined(PNG_READ_sBIT_SUPPORTED)
  180979. PNG_EXTERN void png_handle_sBIT PNGARG((png_structp png_ptr, png_infop info_ptr,
  180980. png_uint_32 length));
  180981. #endif
  180982. #if defined(PNG_READ_sCAL_SUPPORTED)
  180983. PNG_EXTERN void png_handle_sCAL PNGARG((png_structp png_ptr, png_infop info_ptr,
  180984. png_uint_32 length));
  180985. #endif
  180986. #if defined(PNG_READ_sPLT_SUPPORTED)
  180987. extern void png_handle_sPLT PNGARG((png_structp png_ptr, png_infop info_ptr,
  180988. png_uint_32 length));
  180989. #endif /* PNG_READ_sPLT_SUPPORTED */
  180990. #if defined(PNG_READ_sRGB_SUPPORTED)
  180991. PNG_EXTERN void png_handle_sRGB PNGARG((png_structp png_ptr, png_infop info_ptr,
  180992. png_uint_32 length));
  180993. #endif
  180994. #if defined(PNG_READ_tEXt_SUPPORTED)
  180995. PNG_EXTERN void png_handle_tEXt PNGARG((png_structp png_ptr, png_infop info_ptr,
  180996. png_uint_32 length));
  180997. #endif
  180998. #if defined(PNG_READ_tIME_SUPPORTED)
  180999. PNG_EXTERN void png_handle_tIME PNGARG((png_structp png_ptr, png_infop info_ptr,
  181000. png_uint_32 length));
  181001. #endif
  181002. #if defined(PNG_READ_tRNS_SUPPORTED)
  181003. PNG_EXTERN void png_handle_tRNS PNGARG((png_structp png_ptr, png_infop info_ptr,
  181004. png_uint_32 length));
  181005. #endif
  181006. #if defined(PNG_READ_zTXt_SUPPORTED)
  181007. PNG_EXTERN void png_handle_zTXt PNGARG((png_structp png_ptr, png_infop info_ptr,
  181008. png_uint_32 length));
  181009. #endif
  181010. PNG_EXTERN void png_handle_unknown PNGARG((png_structp png_ptr,
  181011. png_infop info_ptr, png_uint_32 length));
  181012. PNG_EXTERN void png_check_chunk_name PNGARG((png_structp png_ptr,
  181013. png_bytep chunk_name));
  181014. /* handle the transformations for reading and writing */
  181015. PNG_EXTERN void png_do_read_transformations PNGARG((png_structp png_ptr));
  181016. PNG_EXTERN void png_do_write_transformations PNGARG((png_structp png_ptr));
  181017. PNG_EXTERN void png_init_read_transformations PNGARG((png_structp png_ptr));
  181018. #ifdef PNG_PROGRESSIVE_READ_SUPPORTED
  181019. PNG_EXTERN void png_push_read_chunk PNGARG((png_structp png_ptr,
  181020. png_infop info_ptr));
  181021. PNG_EXTERN void png_push_read_sig PNGARG((png_structp png_ptr,
  181022. png_infop info_ptr));
  181023. PNG_EXTERN void png_push_check_crc PNGARG((png_structp png_ptr));
  181024. PNG_EXTERN void png_push_crc_skip PNGARG((png_structp png_ptr,
  181025. png_uint_32 length));
  181026. PNG_EXTERN void png_push_crc_finish PNGARG((png_structp png_ptr));
  181027. PNG_EXTERN void png_push_save_buffer PNGARG((png_structp png_ptr));
  181028. PNG_EXTERN void png_push_restore_buffer PNGARG((png_structp png_ptr,
  181029. png_bytep buffer, png_size_t buffer_length));
  181030. PNG_EXTERN void png_push_read_IDAT PNGARG((png_structp png_ptr));
  181031. PNG_EXTERN void png_process_IDAT_data PNGARG((png_structp png_ptr,
  181032. png_bytep buffer, png_size_t buffer_length));
  181033. PNG_EXTERN void png_push_process_row PNGARG((png_structp png_ptr));
  181034. PNG_EXTERN void png_push_handle_unknown PNGARG((png_structp png_ptr,
  181035. png_infop info_ptr, png_uint_32 length));
  181036. PNG_EXTERN void png_push_have_info PNGARG((png_structp png_ptr,
  181037. png_infop info_ptr));
  181038. PNG_EXTERN void png_push_have_end PNGARG((png_structp png_ptr,
  181039. png_infop info_ptr));
  181040. PNG_EXTERN void png_push_have_row PNGARG((png_structp png_ptr, png_bytep row));
  181041. PNG_EXTERN void png_push_read_end PNGARG((png_structp png_ptr,
  181042. png_infop info_ptr));
  181043. PNG_EXTERN void png_process_some_data PNGARG((png_structp png_ptr,
  181044. png_infop info_ptr));
  181045. PNG_EXTERN void png_read_push_finish_row PNGARG((png_structp png_ptr));
  181046. #if defined(PNG_READ_tEXt_SUPPORTED)
  181047. PNG_EXTERN void png_push_handle_tEXt PNGARG((png_structp png_ptr,
  181048. png_infop info_ptr, png_uint_32 length));
  181049. PNG_EXTERN void png_push_read_tEXt PNGARG((png_structp png_ptr,
  181050. png_infop info_ptr));
  181051. #endif
  181052. #if defined(PNG_READ_zTXt_SUPPORTED)
  181053. PNG_EXTERN void png_push_handle_zTXt PNGARG((png_structp png_ptr,
  181054. png_infop info_ptr, png_uint_32 length));
  181055. PNG_EXTERN void png_push_read_zTXt PNGARG((png_structp png_ptr,
  181056. png_infop info_ptr));
  181057. #endif
  181058. #if defined(PNG_READ_iTXt_SUPPORTED)
  181059. PNG_EXTERN void png_push_handle_iTXt PNGARG((png_structp png_ptr,
  181060. png_infop info_ptr, png_uint_32 length));
  181061. PNG_EXTERN void png_push_read_iTXt PNGARG((png_structp png_ptr,
  181062. png_infop info_ptr));
  181063. #endif
  181064. #endif /* PNG_PROGRESSIVE_READ_SUPPORTED */
  181065. #ifdef PNG_MNG_FEATURES_SUPPORTED
  181066. PNG_EXTERN void png_do_read_intrapixel PNGARG((png_row_infop row_info,
  181067. png_bytep row));
  181068. PNG_EXTERN void png_do_write_intrapixel PNGARG((png_row_infop row_info,
  181069. png_bytep row));
  181070. #endif
  181071. #if defined(PNG_ASSEMBLER_CODE_SUPPORTED)
  181072. #if defined(PNG_MMX_CODE_SUPPORTED)
  181073. /* png.c */ /* PRIVATE */
  181074. PNG_EXTERN void png_init_mmx_flags PNGARG((png_structp png_ptr));
  181075. #endif
  181076. #endif
  181077. #if defined(PNG_INCH_CONVERSIONS) && defined(PNG_FLOATING_POINT_SUPPORTED)
  181078. PNG_EXTERN png_uint_32 png_get_pixels_per_inch PNGARG((png_structp png_ptr,
  181079. png_infop info_ptr));
  181080. PNG_EXTERN png_uint_32 png_get_x_pixels_per_inch PNGARG((png_structp png_ptr,
  181081. png_infop info_ptr));
  181082. PNG_EXTERN png_uint_32 png_get_y_pixels_per_inch PNGARG((png_structp png_ptr,
  181083. png_infop info_ptr));
  181084. PNG_EXTERN float png_get_x_offset_inches PNGARG((png_structp png_ptr,
  181085. png_infop info_ptr));
  181086. PNG_EXTERN float png_get_y_offset_inches PNGARG((png_structp png_ptr,
  181087. png_infop info_ptr));
  181088. #if defined(PNG_pHYs_SUPPORTED)
  181089. PNG_EXTERN png_uint_32 png_get_pHYs_dpi PNGARG((png_structp png_ptr,
  181090. png_infop info_ptr, png_uint_32 *res_x, png_uint_32 *res_y, int *unit_type));
  181091. #endif /* PNG_pHYs_SUPPORTED */
  181092. #endif /* PNG_INCH_CONVERSIONS && PNG_FLOATING_POINT_SUPPORTED */
  181093. /* Maintainer: Put new private prototypes here ^ and in libpngpf.3 */
  181094. #endif /* PNG_INTERNAL */
  181095. #ifdef __cplusplus
  181096. }
  181097. #endif
  181098. #endif /* PNG_VERSION_INFO_ONLY */
  181099. /* do not put anything past this line */
  181100. #endif /* PNG_H */
  181101. /*** End of inlined file: png.h ***/
  181102. #define PNG_NO_EXTERN
  181103. /*** Start of inlined file: png.c ***/
  181104. /* png.c - location for general purpose libpng functions
  181105. *
  181106. * Last changed in libpng 1.2.21 [October 4, 2007]
  181107. * For conditions of distribution and use, see copyright notice in png.h
  181108. * Copyright (c) 1998-2007 Glenn Randers-Pehrson
  181109. * (Version 0.96 Copyright (c) 1996, 1997 Andreas Dilger)
  181110. * (Version 0.88 Copyright (c) 1995, 1996 Guy Eric Schalnat, Group 42, Inc.)
  181111. */
  181112. #define PNG_INTERNAL
  181113. #define PNG_NO_EXTERN
  181114. /* Generate a compiler error if there is an old png.h in the search path. */
  181115. typedef version_1_2_21 Your_png_h_is_not_version_1_2_21;
  181116. /* Version information for C files. This had better match the version
  181117. * string defined in png.h. */
  181118. #ifdef PNG_USE_GLOBAL_ARRAYS
  181119. /* png_libpng_ver was changed to a function in version 1.0.5c */
  181120. PNG_CONST char png_libpng_ver[18] = PNG_LIBPNG_VER_STRING;
  181121. #ifdef PNG_READ_SUPPORTED
  181122. /* png_sig was changed to a function in version 1.0.5c */
  181123. /* Place to hold the signature string for a PNG file. */
  181124. PNG_CONST png_byte FARDATA png_sig[8] = {137, 80, 78, 71, 13, 10, 26, 10};
  181125. #endif /* PNG_READ_SUPPORTED */
  181126. /* Invoke global declarations for constant strings for known chunk types */
  181127. PNG_IHDR;
  181128. PNG_IDAT;
  181129. PNG_IEND;
  181130. PNG_PLTE;
  181131. PNG_bKGD;
  181132. PNG_cHRM;
  181133. PNG_gAMA;
  181134. PNG_hIST;
  181135. PNG_iCCP;
  181136. PNG_iTXt;
  181137. PNG_oFFs;
  181138. PNG_pCAL;
  181139. PNG_sCAL;
  181140. PNG_pHYs;
  181141. PNG_sBIT;
  181142. PNG_sPLT;
  181143. PNG_sRGB;
  181144. PNG_tEXt;
  181145. PNG_tIME;
  181146. PNG_tRNS;
  181147. PNG_zTXt;
  181148. #ifdef PNG_READ_SUPPORTED
  181149. /* arrays to facilitate easy interlacing - use pass (0 - 6) as index */
  181150. /* start of interlace block */
  181151. PNG_CONST int FARDATA png_pass_start[] = {0, 4, 0, 2, 0, 1, 0};
  181152. /* offset to next interlace block */
  181153. PNG_CONST int FARDATA png_pass_inc[] = {8, 8, 4, 4, 2, 2, 1};
  181154. /* start of interlace block in the y direction */
  181155. PNG_CONST int FARDATA png_pass_ystart[] = {0, 0, 4, 0, 2, 0, 1};
  181156. /* offset to next interlace block in the y direction */
  181157. PNG_CONST int FARDATA png_pass_yinc[] = {8, 8, 8, 4, 4, 2, 2};
  181158. /* Height of interlace block. This is not currently used - if you need
  181159. * it, uncomment it here and in png.h
  181160. PNG_CONST int FARDATA png_pass_height[] = {8, 8, 4, 4, 2, 2, 1};
  181161. */
  181162. /* Mask to determine which pixels are valid in a pass */
  181163. PNG_CONST int FARDATA png_pass_mask[] = {0x80, 0x08, 0x88, 0x22, 0xaa, 0x55, 0xff};
  181164. /* Mask to determine which pixels to overwrite while displaying */
  181165. PNG_CONST int FARDATA png_pass_dsp_mask[]
  181166. = {0xff, 0x0f, 0xff, 0x33, 0xff, 0x55, 0xff};
  181167. #endif /* PNG_READ_SUPPORTED */
  181168. #endif /* PNG_USE_GLOBAL_ARRAYS */
  181169. /* Tells libpng that we have already handled the first "num_bytes" bytes
  181170. * of the PNG file signature. If the PNG data is embedded into another
  181171. * stream we can set num_bytes = 8 so that libpng will not attempt to read
  181172. * or write any of the magic bytes before it starts on the IHDR.
  181173. */
  181174. #ifdef PNG_READ_SUPPORTED
  181175. void PNGAPI
  181176. png_set_sig_bytes(png_structp png_ptr, int num_bytes)
  181177. {
  181178. if(png_ptr == NULL) return;
  181179. png_debug(1, "in png_set_sig_bytes\n");
  181180. if (num_bytes > 8)
  181181. png_error(png_ptr, "Too many bytes for PNG signature.");
  181182. png_ptr->sig_bytes = (png_byte)(num_bytes < 0 ? 0 : num_bytes);
  181183. }
  181184. /* Checks whether the supplied bytes match the PNG signature. We allow
  181185. * checking less than the full 8-byte signature so that those apps that
  181186. * already read the first few bytes of a file to determine the file type
  181187. * can simply check the remaining bytes for extra assurance. Returns
  181188. * an integer less than, equal to, or greater than zero if sig is found,
  181189. * respectively, to be less than, to match, or be greater than the correct
  181190. * PNG signature (this is the same behaviour as strcmp, memcmp, etc).
  181191. */
  181192. int PNGAPI
  181193. png_sig_cmp(png_bytep sig, png_size_t start, png_size_t num_to_check)
  181194. {
  181195. png_byte png_signature[8] = {137, 80, 78, 71, 13, 10, 26, 10};
  181196. if (num_to_check > 8)
  181197. num_to_check = 8;
  181198. else if (num_to_check < 1)
  181199. return (-1);
  181200. if (start > 7)
  181201. return (-1);
  181202. if (start + num_to_check > 8)
  181203. num_to_check = 8 - start;
  181204. return ((int)(png_memcmp(&sig[start], &png_signature[start], num_to_check)));
  181205. }
  181206. #if defined(PNG_1_0_X) || defined(PNG_1_2_X)
  181207. /* (Obsolete) function to check signature bytes. It does not allow one
  181208. * to check a partial signature. This function might be removed in the
  181209. * future - use png_sig_cmp(). Returns true (nonzero) if the file is PNG.
  181210. */
  181211. int PNGAPI
  181212. png_check_sig(png_bytep sig, int num)
  181213. {
  181214. return ((int)!png_sig_cmp(sig, (png_size_t)0, (png_size_t)num));
  181215. }
  181216. #endif
  181217. #endif /* PNG_READ_SUPPORTED */
  181218. #if defined(PNG_READ_SUPPORTED) || defined(PNG_WRITE_SUPPORTED)
  181219. /* Function to allocate memory for zlib and clear it to 0. */
  181220. #ifdef PNG_1_0_X
  181221. voidpf PNGAPI
  181222. #else
  181223. voidpf /* private */
  181224. #endif
  181225. png_zalloc(voidpf png_ptr, uInt items, uInt size)
  181226. {
  181227. png_voidp ptr;
  181228. png_structp p=(png_structp)png_ptr;
  181229. png_uint_32 save_flags=p->flags;
  181230. png_uint_32 num_bytes;
  181231. if(png_ptr == NULL) return (NULL);
  181232. if (items > PNG_UINT_32_MAX/size)
  181233. {
  181234. png_warning (p, "Potential overflow in png_zalloc()");
  181235. return (NULL);
  181236. }
  181237. num_bytes = (png_uint_32)items * size;
  181238. p->flags|=PNG_FLAG_MALLOC_NULL_MEM_OK;
  181239. ptr = (png_voidp)png_malloc((png_structp)png_ptr, num_bytes);
  181240. p->flags=save_flags;
  181241. #if defined(PNG_1_0_X) && !defined(PNG_NO_ZALLOC_ZERO)
  181242. if (ptr == NULL)
  181243. return ((voidpf)ptr);
  181244. if (num_bytes > (png_uint_32)0x8000L)
  181245. {
  181246. png_memset(ptr, 0, (png_size_t)0x8000L);
  181247. png_memset((png_bytep)ptr + (png_size_t)0x8000L, 0,
  181248. (png_size_t)(num_bytes - (png_uint_32)0x8000L));
  181249. }
  181250. else
  181251. {
  181252. png_memset(ptr, 0, (png_size_t)num_bytes);
  181253. }
  181254. #endif
  181255. return ((voidpf)ptr);
  181256. }
  181257. /* function to free memory for zlib */
  181258. #ifdef PNG_1_0_X
  181259. void PNGAPI
  181260. #else
  181261. void /* private */
  181262. #endif
  181263. png_zfree(voidpf png_ptr, voidpf ptr)
  181264. {
  181265. png_free((png_structp)png_ptr, (png_voidp)ptr);
  181266. }
  181267. /* Reset the CRC variable to 32 bits of 1's. Care must be taken
  181268. * in case CRC is > 32 bits to leave the top bits 0.
  181269. */
  181270. void /* PRIVATE */
  181271. png_reset_crc(png_structp png_ptr)
  181272. {
  181273. png_ptr->crc = crc32(0, Z_NULL, 0);
  181274. }
  181275. /* Calculate the CRC over a section of data. We can only pass as
  181276. * much data to this routine as the largest single buffer size. We
  181277. * also check that this data will actually be used before going to the
  181278. * trouble of calculating it.
  181279. */
  181280. void /* PRIVATE */
  181281. png_calculate_crc(png_structp png_ptr, png_bytep ptr, png_size_t length)
  181282. {
  181283. int need_crc = 1;
  181284. if (png_ptr->chunk_name[0] & 0x20) /* ancillary */
  181285. {
  181286. if ((png_ptr->flags & PNG_FLAG_CRC_ANCILLARY_MASK) ==
  181287. (PNG_FLAG_CRC_ANCILLARY_USE | PNG_FLAG_CRC_ANCILLARY_NOWARN))
  181288. need_crc = 0;
  181289. }
  181290. else /* critical */
  181291. {
  181292. if (png_ptr->flags & PNG_FLAG_CRC_CRITICAL_IGNORE)
  181293. need_crc = 0;
  181294. }
  181295. if (need_crc)
  181296. png_ptr->crc = crc32(png_ptr->crc, ptr, (uInt)length);
  181297. }
  181298. /* Allocate the memory for an info_struct for the application. We don't
  181299. * really need the png_ptr, but it could potentially be useful in the
  181300. * future. This should be used in favour of malloc(png_sizeof(png_info))
  181301. * and png_info_init() so that applications that want to use a shared
  181302. * libpng don't have to be recompiled if png_info changes size.
  181303. */
  181304. png_infop PNGAPI
  181305. png_create_info_struct(png_structp png_ptr)
  181306. {
  181307. png_infop info_ptr;
  181308. png_debug(1, "in png_create_info_struct\n");
  181309. if(png_ptr == NULL) return (NULL);
  181310. #ifdef PNG_USER_MEM_SUPPORTED
  181311. info_ptr = (png_infop)png_create_struct_2(PNG_STRUCT_INFO,
  181312. png_ptr->malloc_fn, png_ptr->mem_ptr);
  181313. #else
  181314. info_ptr = (png_infop)png_create_struct(PNG_STRUCT_INFO);
  181315. #endif
  181316. if (info_ptr != NULL)
  181317. png_info_init_3(&info_ptr, png_sizeof(png_info));
  181318. return (info_ptr);
  181319. }
  181320. /* This function frees the memory associated with a single info struct.
  181321. * Normally, one would use either png_destroy_read_struct() or
  181322. * png_destroy_write_struct() to free an info struct, but this may be
  181323. * useful for some applications.
  181324. */
  181325. void PNGAPI
  181326. png_destroy_info_struct(png_structp png_ptr, png_infopp info_ptr_ptr)
  181327. {
  181328. png_infop info_ptr = NULL;
  181329. if(png_ptr == NULL) return;
  181330. png_debug(1, "in png_destroy_info_struct\n");
  181331. if (info_ptr_ptr != NULL)
  181332. info_ptr = *info_ptr_ptr;
  181333. if (info_ptr != NULL)
  181334. {
  181335. png_info_destroy(png_ptr, info_ptr);
  181336. #ifdef PNG_USER_MEM_SUPPORTED
  181337. png_destroy_struct_2((png_voidp)info_ptr, png_ptr->free_fn,
  181338. png_ptr->mem_ptr);
  181339. #else
  181340. png_destroy_struct((png_voidp)info_ptr);
  181341. #endif
  181342. *info_ptr_ptr = NULL;
  181343. }
  181344. }
  181345. /* Initialize the info structure. This is now an internal function (0.89)
  181346. * and applications using it are urged to use png_create_info_struct()
  181347. * instead.
  181348. */
  181349. #if defined(PNG_1_0_X) || defined(PNG_1_2_X)
  181350. #undef png_info_init
  181351. void PNGAPI
  181352. png_info_init(png_infop info_ptr)
  181353. {
  181354. /* We only come here via pre-1.0.12-compiled applications */
  181355. png_info_init_3(&info_ptr, 0);
  181356. }
  181357. #endif
  181358. void PNGAPI
  181359. png_info_init_3(png_infopp ptr_ptr, png_size_t png_info_struct_size)
  181360. {
  181361. png_infop info_ptr = *ptr_ptr;
  181362. if(info_ptr == NULL) return;
  181363. png_debug(1, "in png_info_init_3\n");
  181364. if(png_sizeof(png_info) > png_info_struct_size)
  181365. {
  181366. png_destroy_struct(info_ptr);
  181367. info_ptr = (png_infop)png_create_struct(PNG_STRUCT_INFO);
  181368. *ptr_ptr = info_ptr;
  181369. }
  181370. /* set everything to 0 */
  181371. png_memset(info_ptr, 0, png_sizeof (png_info));
  181372. }
  181373. #ifdef PNG_FREE_ME_SUPPORTED
  181374. void PNGAPI
  181375. png_data_freer(png_structp png_ptr, png_infop info_ptr,
  181376. int freer, png_uint_32 mask)
  181377. {
  181378. png_debug(1, "in png_data_freer\n");
  181379. if (png_ptr == NULL || info_ptr == NULL)
  181380. return;
  181381. if(freer == PNG_DESTROY_WILL_FREE_DATA)
  181382. info_ptr->free_me |= mask;
  181383. else if(freer == PNG_USER_WILL_FREE_DATA)
  181384. info_ptr->free_me &= ~mask;
  181385. else
  181386. png_warning(png_ptr,
  181387. "Unknown freer parameter in png_data_freer.");
  181388. }
  181389. #endif
  181390. void PNGAPI
  181391. png_free_data(png_structp png_ptr, png_infop info_ptr, png_uint_32 mask,
  181392. int num)
  181393. {
  181394. png_debug(1, "in png_free_data\n");
  181395. if (png_ptr == NULL || info_ptr == NULL)
  181396. return;
  181397. #if defined(PNG_TEXT_SUPPORTED)
  181398. /* free text item num or (if num == -1) all text items */
  181399. #ifdef PNG_FREE_ME_SUPPORTED
  181400. if ((mask & PNG_FREE_TEXT) & info_ptr->free_me)
  181401. #else
  181402. if (mask & PNG_FREE_TEXT)
  181403. #endif
  181404. {
  181405. if (num != -1)
  181406. {
  181407. if (info_ptr->text && info_ptr->text[num].key)
  181408. {
  181409. png_free(png_ptr, info_ptr->text[num].key);
  181410. info_ptr->text[num].key = NULL;
  181411. }
  181412. }
  181413. else
  181414. {
  181415. int i;
  181416. for (i = 0; i < info_ptr->num_text; i++)
  181417. png_free_data(png_ptr, info_ptr, PNG_FREE_TEXT, i);
  181418. png_free(png_ptr, info_ptr->text);
  181419. info_ptr->text = NULL;
  181420. info_ptr->num_text=0;
  181421. }
  181422. }
  181423. #endif
  181424. #if defined(PNG_tRNS_SUPPORTED)
  181425. /* free any tRNS entry */
  181426. #ifdef PNG_FREE_ME_SUPPORTED
  181427. if ((mask & PNG_FREE_TRNS) & info_ptr->free_me)
  181428. #else
  181429. if ((mask & PNG_FREE_TRNS) && (png_ptr->flags & PNG_FLAG_FREE_TRNS))
  181430. #endif
  181431. {
  181432. png_free(png_ptr, info_ptr->trans);
  181433. info_ptr->valid &= ~PNG_INFO_tRNS;
  181434. #ifndef PNG_FREE_ME_SUPPORTED
  181435. png_ptr->flags &= ~PNG_FLAG_FREE_TRNS;
  181436. #endif
  181437. info_ptr->trans = NULL;
  181438. }
  181439. #endif
  181440. #if defined(PNG_sCAL_SUPPORTED)
  181441. /* free any sCAL entry */
  181442. #ifdef PNG_FREE_ME_SUPPORTED
  181443. if ((mask & PNG_FREE_SCAL) & info_ptr->free_me)
  181444. #else
  181445. if (mask & PNG_FREE_SCAL)
  181446. #endif
  181447. {
  181448. #if defined(PNG_FIXED_POINT_SUPPORTED) && !defined(PNG_FLOATING_POINT_SUPPORTED)
  181449. png_free(png_ptr, info_ptr->scal_s_width);
  181450. png_free(png_ptr, info_ptr->scal_s_height);
  181451. info_ptr->scal_s_width = NULL;
  181452. info_ptr->scal_s_height = NULL;
  181453. #endif
  181454. info_ptr->valid &= ~PNG_INFO_sCAL;
  181455. }
  181456. #endif
  181457. #if defined(PNG_pCAL_SUPPORTED)
  181458. /* free any pCAL entry */
  181459. #ifdef PNG_FREE_ME_SUPPORTED
  181460. if ((mask & PNG_FREE_PCAL) & info_ptr->free_me)
  181461. #else
  181462. if (mask & PNG_FREE_PCAL)
  181463. #endif
  181464. {
  181465. png_free(png_ptr, info_ptr->pcal_purpose);
  181466. png_free(png_ptr, info_ptr->pcal_units);
  181467. info_ptr->pcal_purpose = NULL;
  181468. info_ptr->pcal_units = NULL;
  181469. if (info_ptr->pcal_params != NULL)
  181470. {
  181471. int i;
  181472. for (i = 0; i < (int)info_ptr->pcal_nparams; i++)
  181473. {
  181474. png_free(png_ptr, info_ptr->pcal_params[i]);
  181475. info_ptr->pcal_params[i]=NULL;
  181476. }
  181477. png_free(png_ptr, info_ptr->pcal_params);
  181478. info_ptr->pcal_params = NULL;
  181479. }
  181480. info_ptr->valid &= ~PNG_INFO_pCAL;
  181481. }
  181482. #endif
  181483. #if defined(PNG_iCCP_SUPPORTED)
  181484. /* free any iCCP entry */
  181485. #ifdef PNG_FREE_ME_SUPPORTED
  181486. if ((mask & PNG_FREE_ICCP) & info_ptr->free_me)
  181487. #else
  181488. if (mask & PNG_FREE_ICCP)
  181489. #endif
  181490. {
  181491. png_free(png_ptr, info_ptr->iccp_name);
  181492. png_free(png_ptr, info_ptr->iccp_profile);
  181493. info_ptr->iccp_name = NULL;
  181494. info_ptr->iccp_profile = NULL;
  181495. info_ptr->valid &= ~PNG_INFO_iCCP;
  181496. }
  181497. #endif
  181498. #if defined(PNG_sPLT_SUPPORTED)
  181499. /* free a given sPLT entry, or (if num == -1) all sPLT entries */
  181500. #ifdef PNG_FREE_ME_SUPPORTED
  181501. if ((mask & PNG_FREE_SPLT) & info_ptr->free_me)
  181502. #else
  181503. if (mask & PNG_FREE_SPLT)
  181504. #endif
  181505. {
  181506. if (num != -1)
  181507. {
  181508. if(info_ptr->splt_palettes)
  181509. {
  181510. png_free(png_ptr, info_ptr->splt_palettes[num].name);
  181511. png_free(png_ptr, info_ptr->splt_palettes[num].entries);
  181512. info_ptr->splt_palettes[num].name = NULL;
  181513. info_ptr->splt_palettes[num].entries = NULL;
  181514. }
  181515. }
  181516. else
  181517. {
  181518. if(info_ptr->splt_palettes_num)
  181519. {
  181520. int i;
  181521. for (i = 0; i < (int)info_ptr->splt_palettes_num; i++)
  181522. png_free_data(png_ptr, info_ptr, PNG_FREE_SPLT, i);
  181523. png_free(png_ptr, info_ptr->splt_palettes);
  181524. info_ptr->splt_palettes = NULL;
  181525. info_ptr->splt_palettes_num = 0;
  181526. }
  181527. info_ptr->valid &= ~PNG_INFO_sPLT;
  181528. }
  181529. }
  181530. #endif
  181531. #if defined(PNG_UNKNOWN_CHUNKS_SUPPORTED)
  181532. if(png_ptr->unknown_chunk.data)
  181533. {
  181534. png_free(png_ptr, png_ptr->unknown_chunk.data);
  181535. png_ptr->unknown_chunk.data = NULL;
  181536. }
  181537. #ifdef PNG_FREE_ME_SUPPORTED
  181538. if ((mask & PNG_FREE_UNKN) & info_ptr->free_me)
  181539. #else
  181540. if (mask & PNG_FREE_UNKN)
  181541. #endif
  181542. {
  181543. if (num != -1)
  181544. {
  181545. if(info_ptr->unknown_chunks)
  181546. {
  181547. png_free(png_ptr, info_ptr->unknown_chunks[num].data);
  181548. info_ptr->unknown_chunks[num].data = NULL;
  181549. }
  181550. }
  181551. else
  181552. {
  181553. int i;
  181554. if(info_ptr->unknown_chunks_num)
  181555. {
  181556. for (i = 0; i < (int)info_ptr->unknown_chunks_num; i++)
  181557. png_free_data(png_ptr, info_ptr, PNG_FREE_UNKN, i);
  181558. png_free(png_ptr, info_ptr->unknown_chunks);
  181559. info_ptr->unknown_chunks = NULL;
  181560. info_ptr->unknown_chunks_num = 0;
  181561. }
  181562. }
  181563. }
  181564. #endif
  181565. #if defined(PNG_hIST_SUPPORTED)
  181566. /* free any hIST entry */
  181567. #ifdef PNG_FREE_ME_SUPPORTED
  181568. if ((mask & PNG_FREE_HIST) & info_ptr->free_me)
  181569. #else
  181570. if ((mask & PNG_FREE_HIST) && (png_ptr->flags & PNG_FLAG_FREE_HIST))
  181571. #endif
  181572. {
  181573. png_free(png_ptr, info_ptr->hist);
  181574. info_ptr->hist = NULL;
  181575. info_ptr->valid &= ~PNG_INFO_hIST;
  181576. #ifndef PNG_FREE_ME_SUPPORTED
  181577. png_ptr->flags &= ~PNG_FLAG_FREE_HIST;
  181578. #endif
  181579. }
  181580. #endif
  181581. /* free any PLTE entry that was internally allocated */
  181582. #ifdef PNG_FREE_ME_SUPPORTED
  181583. if ((mask & PNG_FREE_PLTE) & info_ptr->free_me)
  181584. #else
  181585. if ((mask & PNG_FREE_PLTE) && (png_ptr->flags & PNG_FLAG_FREE_PLTE))
  181586. #endif
  181587. {
  181588. png_zfree(png_ptr, info_ptr->palette);
  181589. info_ptr->palette = NULL;
  181590. info_ptr->valid &= ~PNG_INFO_PLTE;
  181591. #ifndef PNG_FREE_ME_SUPPORTED
  181592. png_ptr->flags &= ~PNG_FLAG_FREE_PLTE;
  181593. #endif
  181594. info_ptr->num_palette = 0;
  181595. }
  181596. #if defined(PNG_INFO_IMAGE_SUPPORTED)
  181597. /* free any image bits attached to the info structure */
  181598. #ifdef PNG_FREE_ME_SUPPORTED
  181599. if ((mask & PNG_FREE_ROWS) & info_ptr->free_me)
  181600. #else
  181601. if (mask & PNG_FREE_ROWS)
  181602. #endif
  181603. {
  181604. if(info_ptr->row_pointers)
  181605. {
  181606. int row;
  181607. for (row = 0; row < (int)info_ptr->height; row++)
  181608. {
  181609. png_free(png_ptr, info_ptr->row_pointers[row]);
  181610. info_ptr->row_pointers[row]=NULL;
  181611. }
  181612. png_free(png_ptr, info_ptr->row_pointers);
  181613. info_ptr->row_pointers=NULL;
  181614. }
  181615. info_ptr->valid &= ~PNG_INFO_IDAT;
  181616. }
  181617. #endif
  181618. #ifdef PNG_FREE_ME_SUPPORTED
  181619. if(num == -1)
  181620. info_ptr->free_me &= ~mask;
  181621. else
  181622. info_ptr->free_me &= ~(mask & ~PNG_FREE_MUL);
  181623. #endif
  181624. }
  181625. /* This is an internal routine to free any memory that the info struct is
  181626. * pointing to before re-using it or freeing the struct itself. Recall
  181627. * that png_free() checks for NULL pointers for us.
  181628. */
  181629. void /* PRIVATE */
  181630. png_info_destroy(png_structp png_ptr, png_infop info_ptr)
  181631. {
  181632. png_debug(1, "in png_info_destroy\n");
  181633. png_free_data(png_ptr, info_ptr, PNG_FREE_ALL, -1);
  181634. #if defined(PNG_UNKNOWN_CHUNKS_SUPPORTED)
  181635. if (png_ptr->num_chunk_list)
  181636. {
  181637. png_free(png_ptr, png_ptr->chunk_list);
  181638. png_ptr->chunk_list=NULL;
  181639. png_ptr->num_chunk_list=0;
  181640. }
  181641. #endif
  181642. png_info_init_3(&info_ptr, png_sizeof(png_info));
  181643. }
  181644. #endif /* defined(PNG_READ_SUPPORTED) || defined(PNG_WRITE_SUPPORTED) */
  181645. /* This function returns a pointer to the io_ptr associated with the user
  181646. * functions. The application should free any memory associated with this
  181647. * pointer before png_write_destroy() or png_read_destroy() are called.
  181648. */
  181649. png_voidp PNGAPI
  181650. png_get_io_ptr(png_structp png_ptr)
  181651. {
  181652. if(png_ptr == NULL) return (NULL);
  181653. return (png_ptr->io_ptr);
  181654. }
  181655. #if defined(PNG_READ_SUPPORTED) || defined(PNG_WRITE_SUPPORTED)
  181656. #if !defined(PNG_NO_STDIO)
  181657. /* Initialize the default input/output functions for the PNG file. If you
  181658. * use your own read or write routines, you can call either png_set_read_fn()
  181659. * or png_set_write_fn() instead of png_init_io(). If you have defined
  181660. * PNG_NO_STDIO, you must use a function of your own because "FILE *" isn't
  181661. * necessarily available.
  181662. */
  181663. void PNGAPI
  181664. png_init_io(png_structp png_ptr, png_FILE_p fp)
  181665. {
  181666. png_debug(1, "in png_init_io\n");
  181667. if(png_ptr == NULL) return;
  181668. png_ptr->io_ptr = (png_voidp)fp;
  181669. }
  181670. #endif
  181671. #if defined(PNG_TIME_RFC1123_SUPPORTED)
  181672. /* Convert the supplied time into an RFC 1123 string suitable for use in
  181673. * a "Creation Time" or other text-based time string.
  181674. */
  181675. png_charp PNGAPI
  181676. png_convert_to_rfc1123(png_structp png_ptr, png_timep ptime)
  181677. {
  181678. static PNG_CONST char short_months[12][4] =
  181679. {"Jan", "Feb", "Mar", "Apr", "May", "Jun",
  181680. "Jul", "Aug", "Sep", "Oct", "Nov", "Dec"};
  181681. if(png_ptr == NULL) return (NULL);
  181682. if (png_ptr->time_buffer == NULL)
  181683. {
  181684. png_ptr->time_buffer = (png_charp)png_malloc(png_ptr, (png_uint_32)(29*
  181685. png_sizeof(char)));
  181686. }
  181687. #if defined(_WIN32_WCE)
  181688. {
  181689. wchar_t time_buf[29];
  181690. wsprintf(time_buf, TEXT("%d %S %d %02d:%02d:%02d +0000"),
  181691. ptime->day % 32, short_months[(ptime->month - 1) % 12],
  181692. ptime->year, ptime->hour % 24, ptime->minute % 60,
  181693. ptime->second % 61);
  181694. WideCharToMultiByte(CP_ACP, 0, time_buf, -1, png_ptr->time_buffer, 29,
  181695. NULL, NULL);
  181696. }
  181697. #else
  181698. #ifdef USE_FAR_KEYWORD
  181699. {
  181700. char near_time_buf[29];
  181701. png_snprintf6(near_time_buf,29,"%d %s %d %02d:%02d:%02d +0000",
  181702. ptime->day % 32, short_months[(ptime->month - 1) % 12],
  181703. ptime->year, ptime->hour % 24, ptime->minute % 60,
  181704. ptime->second % 61);
  181705. png_memcpy(png_ptr->time_buffer, near_time_buf,
  181706. 29*png_sizeof(char));
  181707. }
  181708. #else
  181709. png_snprintf6(png_ptr->time_buffer,29,"%d %s %d %02d:%02d:%02d +0000",
  181710. ptime->day % 32, short_months[(ptime->month - 1) % 12],
  181711. ptime->year, ptime->hour % 24, ptime->minute % 60,
  181712. ptime->second % 61);
  181713. #endif
  181714. #endif /* _WIN32_WCE */
  181715. return ((png_charp)png_ptr->time_buffer);
  181716. }
  181717. #endif /* PNG_TIME_RFC1123_SUPPORTED */
  181718. #endif /* defined(PNG_READ_SUPPORTED) || defined(PNG_WRITE_SUPPORTED) */
  181719. png_charp PNGAPI
  181720. png_get_copyright(png_structp png_ptr)
  181721. {
  181722. png_ptr = png_ptr; /* silence compiler warning about unused png_ptr */
  181723. return ((png_charp) "\n libpng version 1.2.21 - October 4, 2007\n\
  181724. Copyright (c) 1998-2007 Glenn Randers-Pehrson\n\
  181725. Copyright (c) 1996-1997 Andreas Dilger\n\
  181726. Copyright (c) 1995-1996 Guy Eric Schalnat, Group 42, Inc.\n");
  181727. }
  181728. /* The following return the library version as a short string in the
  181729. * format 1.0.0 through 99.99.99zz. To get the version of *.h files
  181730. * used with your application, print out PNG_LIBPNG_VER_STRING, which
  181731. * is defined in png.h.
  181732. * Note: now there is no difference between png_get_libpng_ver() and
  181733. * png_get_header_ver(). Due to the version_nn_nn_nn typedef guard,
  181734. * it is guaranteed that png.c uses the correct version of png.h.
  181735. */
  181736. png_charp PNGAPI
  181737. png_get_libpng_ver(png_structp png_ptr)
  181738. {
  181739. /* Version of *.c files used when building libpng */
  181740. png_ptr = png_ptr; /* silence compiler warning about unused png_ptr */
  181741. return ((png_charp) PNG_LIBPNG_VER_STRING);
  181742. }
  181743. png_charp PNGAPI
  181744. png_get_header_ver(png_structp png_ptr)
  181745. {
  181746. /* Version of *.h files used when building libpng */
  181747. png_ptr = png_ptr; /* silence compiler warning about unused png_ptr */
  181748. return ((png_charp) PNG_LIBPNG_VER_STRING);
  181749. }
  181750. png_charp PNGAPI
  181751. png_get_header_version(png_structp png_ptr)
  181752. {
  181753. /* Returns longer string containing both version and date */
  181754. png_ptr = png_ptr; /* silence compiler warning about unused png_ptr */
  181755. return ((png_charp) PNG_HEADER_VERSION_STRING
  181756. #ifndef PNG_READ_SUPPORTED
  181757. " (NO READ SUPPORT)"
  181758. #endif
  181759. "\n");
  181760. }
  181761. #if defined(PNG_READ_SUPPORTED) || defined(PNG_WRITE_SUPPORTED)
  181762. #ifdef PNG_HANDLE_AS_UNKNOWN_SUPPORTED
  181763. int PNGAPI
  181764. png_handle_as_unknown(png_structp png_ptr, png_bytep chunk_name)
  181765. {
  181766. /* check chunk_name and return "keep" value if it's on the list, else 0 */
  181767. int i;
  181768. png_bytep p;
  181769. if(png_ptr == NULL || chunk_name == NULL || png_ptr->num_chunk_list<=0)
  181770. return 0;
  181771. p=png_ptr->chunk_list+png_ptr->num_chunk_list*5-5;
  181772. for (i = png_ptr->num_chunk_list; i; i--, p-=5)
  181773. if (!png_memcmp(chunk_name, p, 4))
  181774. return ((int)*(p+4));
  181775. return 0;
  181776. }
  181777. #endif
  181778. /* This function, added to libpng-1.0.6g, is untested. */
  181779. int PNGAPI
  181780. png_reset_zstream(png_structp png_ptr)
  181781. {
  181782. if (png_ptr == NULL) return Z_STREAM_ERROR;
  181783. return (inflateReset(&png_ptr->zstream));
  181784. }
  181785. #endif /* defined(PNG_READ_SUPPORTED) || defined(PNG_WRITE_SUPPORTED) */
  181786. /* This function was added to libpng-1.0.7 */
  181787. png_uint_32 PNGAPI
  181788. png_access_version_number(void)
  181789. {
  181790. /* Version of *.c files used when building libpng */
  181791. return((png_uint_32) PNG_LIBPNG_VER);
  181792. }
  181793. #if defined(PNG_READ_SUPPORTED) && defined(PNG_ASSEMBLER_CODE_SUPPORTED)
  181794. #if !defined(PNG_1_0_X)
  181795. /* this function was added to libpng 1.2.0 */
  181796. int PNGAPI
  181797. png_mmx_support(void)
  181798. {
  181799. /* obsolete, to be removed from libpng-1.4.0 */
  181800. return -1;
  181801. }
  181802. #endif /* PNG_1_0_X */
  181803. #endif /* PNG_READ_SUPPORTED && PNG_ASSEMBLER_CODE_SUPPORTED */
  181804. #if defined(PNG_READ_SUPPORTED) || defined(PNG_WRITE_SUPPORTED)
  181805. #ifdef PNG_SIZE_T
  181806. /* Added at libpng version 1.2.6 */
  181807. PNG_EXTERN png_size_t PNGAPI png_convert_size PNGARG((size_t size));
  181808. png_size_t PNGAPI
  181809. png_convert_size(size_t size)
  181810. {
  181811. if (size > (png_size_t)-1)
  181812. PNG_ABORT(); /* We haven't got access to png_ptr, so no png_error() */
  181813. return ((png_size_t)size);
  181814. }
  181815. #endif /* PNG_SIZE_T */
  181816. #endif /* defined(PNG_READ_SUPPORTED) || defined(PNG_WRITE_SUPPORTED) */
  181817. /*** End of inlined file: png.c ***/
  181818. /*** Start of inlined file: pngerror.c ***/
  181819. /* pngerror.c - stub functions for i/o and memory allocation
  181820. *
  181821. * Last changed in libpng 1.2.20 October 4, 2007
  181822. * For conditions of distribution and use, see copyright notice in png.h
  181823. * Copyright (c) 1998-2007 Glenn Randers-Pehrson
  181824. * (Version 0.96 Copyright (c) 1996, 1997 Andreas Dilger)
  181825. * (Version 0.88 Copyright (c) 1995, 1996 Guy Eric Schalnat, Group 42, Inc.)
  181826. *
  181827. * This file provides a location for all error handling. Users who
  181828. * need special error handling are expected to write replacement functions
  181829. * and use png_set_error_fn() to use those functions. See the instructions
  181830. * at each function.
  181831. */
  181832. #define PNG_INTERNAL
  181833. #if defined(PNG_READ_SUPPORTED) || defined(PNG_WRITE_SUPPORTED)
  181834. static void /* PRIVATE */
  181835. png_default_error PNGARG((png_structp png_ptr,
  181836. png_const_charp error_message));
  181837. #ifndef PNG_NO_WARNINGS
  181838. static void /* PRIVATE */
  181839. png_default_warning PNGARG((png_structp png_ptr,
  181840. png_const_charp warning_message));
  181841. #endif /* PNG_NO_WARNINGS */
  181842. /* This function is called whenever there is a fatal error. This function
  181843. * should not be changed. If there is a need to handle errors differently,
  181844. * you should supply a replacement error function and use png_set_error_fn()
  181845. * to replace the error function at run-time.
  181846. */
  181847. #ifndef PNG_NO_ERROR_TEXT
  181848. void PNGAPI
  181849. png_error(png_structp png_ptr, png_const_charp error_message)
  181850. {
  181851. #ifdef PNG_ERROR_NUMBERS_SUPPORTED
  181852. char msg[16];
  181853. if (png_ptr != NULL)
  181854. {
  181855. if (png_ptr->flags&
  181856. (PNG_FLAG_STRIP_ERROR_NUMBERS|PNG_FLAG_STRIP_ERROR_TEXT))
  181857. {
  181858. if (*error_message == '#')
  181859. {
  181860. int offset;
  181861. for (offset=1; offset<15; offset++)
  181862. if (*(error_message+offset) == ' ')
  181863. break;
  181864. if (png_ptr->flags&PNG_FLAG_STRIP_ERROR_TEXT)
  181865. {
  181866. int i;
  181867. for (i=0; i<offset-1; i++)
  181868. msg[i]=error_message[i+1];
  181869. msg[i]='\0';
  181870. error_message=msg;
  181871. }
  181872. else
  181873. error_message+=offset;
  181874. }
  181875. else
  181876. {
  181877. if (png_ptr->flags&PNG_FLAG_STRIP_ERROR_TEXT)
  181878. {
  181879. msg[0]='0';
  181880. msg[1]='\0';
  181881. error_message=msg;
  181882. }
  181883. }
  181884. }
  181885. }
  181886. #endif
  181887. if (png_ptr != NULL && png_ptr->error_fn != NULL)
  181888. (*(png_ptr->error_fn))(png_ptr, error_message);
  181889. /* If the custom handler doesn't exist, or if it returns,
  181890. use the default handler, which will not return. */
  181891. png_default_error(png_ptr, error_message);
  181892. }
  181893. #else
  181894. void PNGAPI
  181895. png_err(png_structp png_ptr)
  181896. {
  181897. if (png_ptr != NULL && png_ptr->error_fn != NULL)
  181898. (*(png_ptr->error_fn))(png_ptr, '\0');
  181899. /* If the custom handler doesn't exist, or if it returns,
  181900. use the default handler, which will not return. */
  181901. png_default_error(png_ptr, '\0');
  181902. }
  181903. #endif /* PNG_NO_ERROR_TEXT */
  181904. #ifndef PNG_NO_WARNINGS
  181905. /* This function is called whenever there is a non-fatal error. This function
  181906. * should not be changed. If there is a need to handle warnings differently,
  181907. * you should supply a replacement warning function and use
  181908. * png_set_error_fn() to replace the warning function at run-time.
  181909. */
  181910. void PNGAPI
  181911. png_warning(png_structp png_ptr, png_const_charp warning_message)
  181912. {
  181913. int offset = 0;
  181914. if (png_ptr != NULL)
  181915. {
  181916. #ifdef PNG_ERROR_NUMBERS_SUPPORTED
  181917. if (png_ptr->flags&
  181918. (PNG_FLAG_STRIP_ERROR_NUMBERS|PNG_FLAG_STRIP_ERROR_TEXT))
  181919. #endif
  181920. {
  181921. if (*warning_message == '#')
  181922. {
  181923. for (offset=1; offset<15; offset++)
  181924. if (*(warning_message+offset) == ' ')
  181925. break;
  181926. }
  181927. }
  181928. if (png_ptr != NULL && png_ptr->warning_fn != NULL)
  181929. (*(png_ptr->warning_fn))(png_ptr, warning_message+offset);
  181930. }
  181931. else
  181932. png_default_warning(png_ptr, warning_message+offset);
  181933. }
  181934. #endif /* PNG_NO_WARNINGS */
  181935. /* These utilities are used internally to build an error message that relates
  181936. * to the current chunk. The chunk name comes from png_ptr->chunk_name,
  181937. * this is used to prefix the message. The message is limited in length
  181938. * to 63 bytes, the name characters are output as hex digits wrapped in []
  181939. * if the character is invalid.
  181940. */
  181941. #define isnonalpha(c) ((c) < 65 || (c) > 122 || ((c) > 90 && (c) < 97))
  181942. /*static PNG_CONST char png_digit[16] = {
  181943. '0', '1', '2', '3', '4', '5', '6', '7', '8', '9',
  181944. 'A', 'B', 'C', 'D', 'E', 'F'
  181945. };*/
  181946. #if !defined(PNG_NO_WARNINGS) || !defined(PNG_NO_ERROR_TEXT)
  181947. static void /* PRIVATE */
  181948. png_format_buffer(png_structp png_ptr, png_charp buffer, png_const_charp
  181949. error_message)
  181950. {
  181951. int iout = 0, iin = 0;
  181952. while (iin < 4)
  181953. {
  181954. int c = png_ptr->chunk_name[iin++];
  181955. if (isnonalpha(c))
  181956. {
  181957. buffer[iout++] = '[';
  181958. buffer[iout++] = png_digit[(c & 0xf0) >> 4];
  181959. buffer[iout++] = png_digit[c & 0x0f];
  181960. buffer[iout++] = ']';
  181961. }
  181962. else
  181963. {
  181964. buffer[iout++] = (png_byte)c;
  181965. }
  181966. }
  181967. if (error_message == NULL)
  181968. buffer[iout] = 0;
  181969. else
  181970. {
  181971. buffer[iout++] = ':';
  181972. buffer[iout++] = ' ';
  181973. png_strncpy(buffer+iout, error_message, 63);
  181974. buffer[iout+63] = 0;
  181975. }
  181976. }
  181977. #ifdef PNG_READ_SUPPORTED
  181978. void PNGAPI
  181979. png_chunk_error(png_structp png_ptr, png_const_charp error_message)
  181980. {
  181981. char msg[18+64];
  181982. if (png_ptr == NULL)
  181983. png_error(png_ptr, error_message);
  181984. else
  181985. {
  181986. png_format_buffer(png_ptr, msg, error_message);
  181987. png_error(png_ptr, msg);
  181988. }
  181989. }
  181990. #endif /* PNG_READ_SUPPORTED */
  181991. #endif /* !defined(PNG_NO_WARNINGS) || !defined(PNG_NO_ERROR_TEXT) */
  181992. #ifndef PNG_NO_WARNINGS
  181993. void PNGAPI
  181994. png_chunk_warning(png_structp png_ptr, png_const_charp warning_message)
  181995. {
  181996. char msg[18+64];
  181997. if (png_ptr == NULL)
  181998. png_warning(png_ptr, warning_message);
  181999. else
  182000. {
  182001. png_format_buffer(png_ptr, msg, warning_message);
  182002. png_warning(png_ptr, msg);
  182003. }
  182004. }
  182005. #endif /* PNG_NO_WARNINGS */
  182006. /* This is the default error handling function. Note that replacements for
  182007. * this function MUST NOT RETURN, or the program will likely crash. This
  182008. * function is used by default, or if the program supplies NULL for the
  182009. * error function pointer in png_set_error_fn().
  182010. */
  182011. static void /* PRIVATE */
  182012. png_default_error(png_structp png_ptr, png_const_charp error_message)
  182013. {
  182014. #ifndef PNG_NO_CONSOLE_IO
  182015. #ifdef PNG_ERROR_NUMBERS_SUPPORTED
  182016. if (*error_message == '#')
  182017. {
  182018. int offset;
  182019. char error_number[16];
  182020. for (offset=0; offset<15; offset++)
  182021. {
  182022. error_number[offset] = *(error_message+offset+1);
  182023. if (*(error_message+offset) == ' ')
  182024. break;
  182025. }
  182026. if((offset > 1) && (offset < 15))
  182027. {
  182028. error_number[offset-1]='\0';
  182029. fprintf(stderr, "libpng error no. %s: %s\n", error_number,
  182030. error_message+offset);
  182031. }
  182032. else
  182033. fprintf(stderr, "libpng error: %s, offset=%d\n", error_message,offset);
  182034. }
  182035. else
  182036. #endif
  182037. fprintf(stderr, "libpng error: %s\n", error_message);
  182038. #endif
  182039. #ifdef PNG_SETJMP_SUPPORTED
  182040. if (png_ptr)
  182041. {
  182042. # ifdef USE_FAR_KEYWORD
  182043. {
  182044. jmp_buf jmpbuf;
  182045. png_memcpy(jmpbuf, png_ptr->jmpbuf, png_sizeof(jmp_buf));
  182046. longjmp(jmpbuf, 1);
  182047. }
  182048. # else
  182049. longjmp(png_ptr->jmpbuf, 1);
  182050. # endif
  182051. }
  182052. #else
  182053. PNG_ABORT();
  182054. #endif
  182055. #ifdef PNG_NO_CONSOLE_IO
  182056. error_message = error_message; /* make compiler happy */
  182057. #endif
  182058. }
  182059. #ifndef PNG_NO_WARNINGS
  182060. /* This function is called when there is a warning, but the library thinks
  182061. * it can continue anyway. Replacement functions don't have to do anything
  182062. * here if you don't want them to. In the default configuration, png_ptr is
  182063. * not used, but it is passed in case it may be useful.
  182064. */
  182065. static void /* PRIVATE */
  182066. png_default_warning(png_structp png_ptr, png_const_charp warning_message)
  182067. {
  182068. #ifndef PNG_NO_CONSOLE_IO
  182069. # ifdef PNG_ERROR_NUMBERS_SUPPORTED
  182070. if (*warning_message == '#')
  182071. {
  182072. int offset;
  182073. char warning_number[16];
  182074. for (offset=0; offset<15; offset++)
  182075. {
  182076. warning_number[offset]=*(warning_message+offset+1);
  182077. if (*(warning_message+offset) == ' ')
  182078. break;
  182079. }
  182080. if((offset > 1) && (offset < 15))
  182081. {
  182082. warning_number[offset-1]='\0';
  182083. fprintf(stderr, "libpng warning no. %s: %s\n", warning_number,
  182084. warning_message+offset);
  182085. }
  182086. else
  182087. fprintf(stderr, "libpng warning: %s\n", warning_message);
  182088. }
  182089. else
  182090. # endif
  182091. fprintf(stderr, "libpng warning: %s\n", warning_message);
  182092. #else
  182093. warning_message = warning_message; /* make compiler happy */
  182094. #endif
  182095. png_ptr = png_ptr; /* make compiler happy */
  182096. }
  182097. #endif /* PNG_NO_WARNINGS */
  182098. /* This function is called when the application wants to use another method
  182099. * of handling errors and warnings. Note that the error function MUST NOT
  182100. * return to the calling routine or serious problems will occur. The return
  182101. * method used in the default routine calls longjmp(png_ptr->jmpbuf, 1)
  182102. */
  182103. void PNGAPI
  182104. png_set_error_fn(png_structp png_ptr, png_voidp error_ptr,
  182105. png_error_ptr error_fn, png_error_ptr warning_fn)
  182106. {
  182107. if (png_ptr == NULL)
  182108. return;
  182109. png_ptr->error_ptr = error_ptr;
  182110. png_ptr->error_fn = error_fn;
  182111. png_ptr->warning_fn = warning_fn;
  182112. }
  182113. /* This function returns a pointer to the error_ptr associated with the user
  182114. * functions. The application should free any memory associated with this
  182115. * pointer before png_write_destroy and png_read_destroy are called.
  182116. */
  182117. png_voidp PNGAPI
  182118. png_get_error_ptr(png_structp png_ptr)
  182119. {
  182120. if (png_ptr == NULL)
  182121. return NULL;
  182122. return ((png_voidp)png_ptr->error_ptr);
  182123. }
  182124. #ifdef PNG_ERROR_NUMBERS_SUPPORTED
  182125. void PNGAPI
  182126. png_set_strip_error_numbers(png_structp png_ptr, png_uint_32 strip_mode)
  182127. {
  182128. if(png_ptr != NULL)
  182129. {
  182130. png_ptr->flags &=
  182131. ((~(PNG_FLAG_STRIP_ERROR_NUMBERS|PNG_FLAG_STRIP_ERROR_TEXT))&strip_mode);
  182132. }
  182133. }
  182134. #endif
  182135. #endif /* PNG_READ_SUPPORTED || PNG_WRITE_SUPPORTED */
  182136. /*** End of inlined file: pngerror.c ***/
  182137. /*** Start of inlined file: pngget.c ***/
  182138. /* pngget.c - retrieval of values from info struct
  182139. *
  182140. * Last changed in libpng 1.2.15 January 5, 2007
  182141. * For conditions of distribution and use, see copyright notice in png.h
  182142. * Copyright (c) 1998-2007 Glenn Randers-Pehrson
  182143. * (Version 0.96 Copyright (c) 1996, 1997 Andreas Dilger)
  182144. * (Version 0.88 Copyright (c) 1995, 1996 Guy Eric Schalnat, Group 42, Inc.)
  182145. */
  182146. #define PNG_INTERNAL
  182147. #if defined(PNG_READ_SUPPORTED) || defined(PNG_WRITE_SUPPORTED)
  182148. png_uint_32 PNGAPI
  182149. png_get_valid(png_structp png_ptr, png_infop info_ptr, png_uint_32 flag)
  182150. {
  182151. if (png_ptr != NULL && info_ptr != NULL)
  182152. return(info_ptr->valid & flag);
  182153. else
  182154. return(0);
  182155. }
  182156. png_uint_32 PNGAPI
  182157. png_get_rowbytes(png_structp png_ptr, png_infop info_ptr)
  182158. {
  182159. if (png_ptr != NULL && info_ptr != NULL)
  182160. return(info_ptr->rowbytes);
  182161. else
  182162. return(0);
  182163. }
  182164. #if defined(PNG_INFO_IMAGE_SUPPORTED)
  182165. png_bytepp PNGAPI
  182166. png_get_rows(png_structp png_ptr, png_infop info_ptr)
  182167. {
  182168. if (png_ptr != NULL && info_ptr != NULL)
  182169. return(info_ptr->row_pointers);
  182170. else
  182171. return(0);
  182172. }
  182173. #endif
  182174. #ifdef PNG_EASY_ACCESS_SUPPORTED
  182175. /* easy access to info, added in libpng-0.99 */
  182176. png_uint_32 PNGAPI
  182177. png_get_image_width(png_structp png_ptr, png_infop info_ptr)
  182178. {
  182179. if (png_ptr != NULL && info_ptr != NULL)
  182180. {
  182181. return info_ptr->width;
  182182. }
  182183. return (0);
  182184. }
  182185. png_uint_32 PNGAPI
  182186. png_get_image_height(png_structp png_ptr, png_infop info_ptr)
  182187. {
  182188. if (png_ptr != NULL && info_ptr != NULL)
  182189. {
  182190. return info_ptr->height;
  182191. }
  182192. return (0);
  182193. }
  182194. png_byte PNGAPI
  182195. png_get_bit_depth(png_structp png_ptr, png_infop info_ptr)
  182196. {
  182197. if (png_ptr != NULL && info_ptr != NULL)
  182198. {
  182199. return info_ptr->bit_depth;
  182200. }
  182201. return (0);
  182202. }
  182203. png_byte PNGAPI
  182204. png_get_color_type(png_structp png_ptr, png_infop info_ptr)
  182205. {
  182206. if (png_ptr != NULL && info_ptr != NULL)
  182207. {
  182208. return info_ptr->color_type;
  182209. }
  182210. return (0);
  182211. }
  182212. png_byte PNGAPI
  182213. png_get_filter_type(png_structp png_ptr, png_infop info_ptr)
  182214. {
  182215. if (png_ptr != NULL && info_ptr != NULL)
  182216. {
  182217. return info_ptr->filter_type;
  182218. }
  182219. return (0);
  182220. }
  182221. png_byte PNGAPI
  182222. png_get_interlace_type(png_structp png_ptr, png_infop info_ptr)
  182223. {
  182224. if (png_ptr != NULL && info_ptr != NULL)
  182225. {
  182226. return info_ptr->interlace_type;
  182227. }
  182228. return (0);
  182229. }
  182230. png_byte PNGAPI
  182231. png_get_compression_type(png_structp png_ptr, png_infop info_ptr)
  182232. {
  182233. if (png_ptr != NULL && info_ptr != NULL)
  182234. {
  182235. return info_ptr->compression_type;
  182236. }
  182237. return (0);
  182238. }
  182239. png_uint_32 PNGAPI
  182240. png_get_x_pixels_per_meter(png_structp png_ptr, png_infop info_ptr)
  182241. {
  182242. if (png_ptr != NULL && info_ptr != NULL)
  182243. #if defined(PNG_pHYs_SUPPORTED)
  182244. if (info_ptr->valid & PNG_INFO_pHYs)
  182245. {
  182246. png_debug1(1, "in %s retrieval function\n", "png_get_x_pixels_per_meter");
  182247. if(info_ptr->phys_unit_type != PNG_RESOLUTION_METER)
  182248. return (0);
  182249. else return (info_ptr->x_pixels_per_unit);
  182250. }
  182251. #else
  182252. return (0);
  182253. #endif
  182254. return (0);
  182255. }
  182256. png_uint_32 PNGAPI
  182257. png_get_y_pixels_per_meter(png_structp png_ptr, png_infop info_ptr)
  182258. {
  182259. if (png_ptr != NULL && info_ptr != NULL)
  182260. #if defined(PNG_pHYs_SUPPORTED)
  182261. if (info_ptr->valid & PNG_INFO_pHYs)
  182262. {
  182263. png_debug1(1, "in %s retrieval function\n", "png_get_y_pixels_per_meter");
  182264. if(info_ptr->phys_unit_type != PNG_RESOLUTION_METER)
  182265. return (0);
  182266. else return (info_ptr->y_pixels_per_unit);
  182267. }
  182268. #else
  182269. return (0);
  182270. #endif
  182271. return (0);
  182272. }
  182273. png_uint_32 PNGAPI
  182274. png_get_pixels_per_meter(png_structp png_ptr, png_infop info_ptr)
  182275. {
  182276. if (png_ptr != NULL && info_ptr != NULL)
  182277. #if defined(PNG_pHYs_SUPPORTED)
  182278. if (info_ptr->valid & PNG_INFO_pHYs)
  182279. {
  182280. png_debug1(1, "in %s retrieval function\n", "png_get_pixels_per_meter");
  182281. if(info_ptr->phys_unit_type != PNG_RESOLUTION_METER ||
  182282. info_ptr->x_pixels_per_unit != info_ptr->y_pixels_per_unit)
  182283. return (0);
  182284. else return (info_ptr->x_pixels_per_unit);
  182285. }
  182286. #else
  182287. return (0);
  182288. #endif
  182289. return (0);
  182290. }
  182291. #ifdef PNG_FLOATING_POINT_SUPPORTED
  182292. float PNGAPI
  182293. png_get_pixel_aspect_ratio(png_structp png_ptr, png_infop info_ptr)
  182294. {
  182295. if (png_ptr != NULL && info_ptr != NULL)
  182296. #if defined(PNG_pHYs_SUPPORTED)
  182297. if (info_ptr->valid & PNG_INFO_pHYs)
  182298. {
  182299. png_debug1(1, "in %s retrieval function\n", "png_get_aspect_ratio");
  182300. if (info_ptr->x_pixels_per_unit == 0)
  182301. return ((float)0.0);
  182302. else
  182303. return ((float)((float)info_ptr->y_pixels_per_unit
  182304. /(float)info_ptr->x_pixels_per_unit));
  182305. }
  182306. #else
  182307. return (0.0);
  182308. #endif
  182309. return ((float)0.0);
  182310. }
  182311. #endif
  182312. png_int_32 PNGAPI
  182313. png_get_x_offset_microns(png_structp png_ptr, png_infop info_ptr)
  182314. {
  182315. if (png_ptr != NULL && info_ptr != NULL)
  182316. #if defined(PNG_oFFs_SUPPORTED)
  182317. if (info_ptr->valid & PNG_INFO_oFFs)
  182318. {
  182319. png_debug1(1, "in %s retrieval function\n", "png_get_x_offset_microns");
  182320. if(info_ptr->offset_unit_type != PNG_OFFSET_MICROMETER)
  182321. return (0);
  182322. else return (info_ptr->x_offset);
  182323. }
  182324. #else
  182325. return (0);
  182326. #endif
  182327. return (0);
  182328. }
  182329. png_int_32 PNGAPI
  182330. png_get_y_offset_microns(png_structp png_ptr, png_infop info_ptr)
  182331. {
  182332. if (png_ptr != NULL && info_ptr != NULL)
  182333. #if defined(PNG_oFFs_SUPPORTED)
  182334. if (info_ptr->valid & PNG_INFO_oFFs)
  182335. {
  182336. png_debug1(1, "in %s retrieval function\n", "png_get_y_offset_microns");
  182337. if(info_ptr->offset_unit_type != PNG_OFFSET_MICROMETER)
  182338. return (0);
  182339. else return (info_ptr->y_offset);
  182340. }
  182341. #else
  182342. return (0);
  182343. #endif
  182344. return (0);
  182345. }
  182346. png_int_32 PNGAPI
  182347. png_get_x_offset_pixels(png_structp png_ptr, png_infop info_ptr)
  182348. {
  182349. if (png_ptr != NULL && info_ptr != NULL)
  182350. #if defined(PNG_oFFs_SUPPORTED)
  182351. if (info_ptr->valid & PNG_INFO_oFFs)
  182352. {
  182353. png_debug1(1, "in %s retrieval function\n", "png_get_x_offset_microns");
  182354. if(info_ptr->offset_unit_type != PNG_OFFSET_PIXEL)
  182355. return (0);
  182356. else return (info_ptr->x_offset);
  182357. }
  182358. #else
  182359. return (0);
  182360. #endif
  182361. return (0);
  182362. }
  182363. png_int_32 PNGAPI
  182364. png_get_y_offset_pixels(png_structp png_ptr, png_infop info_ptr)
  182365. {
  182366. if (png_ptr != NULL && info_ptr != NULL)
  182367. #if defined(PNG_oFFs_SUPPORTED)
  182368. if (info_ptr->valid & PNG_INFO_oFFs)
  182369. {
  182370. png_debug1(1, "in %s retrieval function\n", "png_get_y_offset_microns");
  182371. if(info_ptr->offset_unit_type != PNG_OFFSET_PIXEL)
  182372. return (0);
  182373. else return (info_ptr->y_offset);
  182374. }
  182375. #else
  182376. return (0);
  182377. #endif
  182378. return (0);
  182379. }
  182380. #if defined(PNG_INCH_CONVERSIONS) && defined(PNG_FLOATING_POINT_SUPPORTED)
  182381. png_uint_32 PNGAPI
  182382. png_get_pixels_per_inch(png_structp png_ptr, png_infop info_ptr)
  182383. {
  182384. return ((png_uint_32)((float)png_get_pixels_per_meter(png_ptr, info_ptr)
  182385. *.0254 +.5));
  182386. }
  182387. png_uint_32 PNGAPI
  182388. png_get_x_pixels_per_inch(png_structp png_ptr, png_infop info_ptr)
  182389. {
  182390. return ((png_uint_32)((float)png_get_x_pixels_per_meter(png_ptr, info_ptr)
  182391. *.0254 +.5));
  182392. }
  182393. png_uint_32 PNGAPI
  182394. png_get_y_pixels_per_inch(png_structp png_ptr, png_infop info_ptr)
  182395. {
  182396. return ((png_uint_32)((float)png_get_y_pixels_per_meter(png_ptr, info_ptr)
  182397. *.0254 +.5));
  182398. }
  182399. float PNGAPI
  182400. png_get_x_offset_inches(png_structp png_ptr, png_infop info_ptr)
  182401. {
  182402. return ((float)png_get_x_offset_microns(png_ptr, info_ptr)
  182403. *.00003937);
  182404. }
  182405. float PNGAPI
  182406. png_get_y_offset_inches(png_structp png_ptr, png_infop info_ptr)
  182407. {
  182408. return ((float)png_get_y_offset_microns(png_ptr, info_ptr)
  182409. *.00003937);
  182410. }
  182411. #if defined(PNG_pHYs_SUPPORTED)
  182412. png_uint_32 PNGAPI
  182413. png_get_pHYs_dpi(png_structp png_ptr, png_infop info_ptr,
  182414. png_uint_32 *res_x, png_uint_32 *res_y, int *unit_type)
  182415. {
  182416. png_uint_32 retval = 0;
  182417. if (png_ptr != NULL && info_ptr != NULL && (info_ptr->valid & PNG_INFO_pHYs))
  182418. {
  182419. png_debug1(1, "in %s retrieval function\n", "pHYs");
  182420. if (res_x != NULL)
  182421. {
  182422. *res_x = info_ptr->x_pixels_per_unit;
  182423. retval |= PNG_INFO_pHYs;
  182424. }
  182425. if (res_y != NULL)
  182426. {
  182427. *res_y = info_ptr->y_pixels_per_unit;
  182428. retval |= PNG_INFO_pHYs;
  182429. }
  182430. if (unit_type != NULL)
  182431. {
  182432. *unit_type = (int)info_ptr->phys_unit_type;
  182433. retval |= PNG_INFO_pHYs;
  182434. if(*unit_type == 1)
  182435. {
  182436. if (res_x != NULL) *res_x = (png_uint_32)(*res_x * .0254 + .50);
  182437. if (res_y != NULL) *res_y = (png_uint_32)(*res_y * .0254 + .50);
  182438. }
  182439. }
  182440. }
  182441. return (retval);
  182442. }
  182443. #endif /* PNG_pHYs_SUPPORTED */
  182444. #endif /* PNG_INCH_CONVERSIONS && PNG_FLOATING_POINT_SUPPORTED */
  182445. /* png_get_channels really belongs in here, too, but it's been around longer */
  182446. #endif /* PNG_EASY_ACCESS_SUPPORTED */
  182447. png_byte PNGAPI
  182448. png_get_channels(png_structp png_ptr, png_infop info_ptr)
  182449. {
  182450. if (png_ptr != NULL && info_ptr != NULL)
  182451. return(info_ptr->channels);
  182452. else
  182453. return (0);
  182454. }
  182455. png_bytep PNGAPI
  182456. png_get_signature(png_structp png_ptr, png_infop info_ptr)
  182457. {
  182458. if (png_ptr != NULL && info_ptr != NULL)
  182459. return(info_ptr->signature);
  182460. else
  182461. return (NULL);
  182462. }
  182463. #if defined(PNG_bKGD_SUPPORTED)
  182464. png_uint_32 PNGAPI
  182465. png_get_bKGD(png_structp png_ptr, png_infop info_ptr,
  182466. png_color_16p *background)
  182467. {
  182468. if (png_ptr != NULL && info_ptr != NULL && (info_ptr->valid & PNG_INFO_bKGD)
  182469. && background != NULL)
  182470. {
  182471. png_debug1(1, "in %s retrieval function\n", "bKGD");
  182472. *background = &(info_ptr->background);
  182473. return (PNG_INFO_bKGD);
  182474. }
  182475. return (0);
  182476. }
  182477. #endif
  182478. #if defined(PNG_cHRM_SUPPORTED)
  182479. #ifdef PNG_FLOATING_POINT_SUPPORTED
  182480. png_uint_32 PNGAPI
  182481. png_get_cHRM(png_structp png_ptr, png_infop info_ptr,
  182482. double *white_x, double *white_y, double *red_x, double *red_y,
  182483. double *green_x, double *green_y, double *blue_x, double *blue_y)
  182484. {
  182485. if (png_ptr != NULL && info_ptr != NULL && (info_ptr->valid & PNG_INFO_cHRM))
  182486. {
  182487. png_debug1(1, "in %s retrieval function\n", "cHRM");
  182488. if (white_x != NULL)
  182489. *white_x = (double)info_ptr->x_white;
  182490. if (white_y != NULL)
  182491. *white_y = (double)info_ptr->y_white;
  182492. if (red_x != NULL)
  182493. *red_x = (double)info_ptr->x_red;
  182494. if (red_y != NULL)
  182495. *red_y = (double)info_ptr->y_red;
  182496. if (green_x != NULL)
  182497. *green_x = (double)info_ptr->x_green;
  182498. if (green_y != NULL)
  182499. *green_y = (double)info_ptr->y_green;
  182500. if (blue_x != NULL)
  182501. *blue_x = (double)info_ptr->x_blue;
  182502. if (blue_y != NULL)
  182503. *blue_y = (double)info_ptr->y_blue;
  182504. return (PNG_INFO_cHRM);
  182505. }
  182506. return (0);
  182507. }
  182508. #endif
  182509. #ifdef PNG_FIXED_POINT_SUPPORTED
  182510. png_uint_32 PNGAPI
  182511. png_get_cHRM_fixed(png_structp png_ptr, png_infop info_ptr,
  182512. png_fixed_point *white_x, png_fixed_point *white_y, png_fixed_point *red_x,
  182513. png_fixed_point *red_y, png_fixed_point *green_x, png_fixed_point *green_y,
  182514. png_fixed_point *blue_x, png_fixed_point *blue_y)
  182515. {
  182516. if (png_ptr != NULL && info_ptr != NULL && (info_ptr->valid & PNG_INFO_cHRM))
  182517. {
  182518. png_debug1(1, "in %s retrieval function\n", "cHRM");
  182519. if (white_x != NULL)
  182520. *white_x = info_ptr->int_x_white;
  182521. if (white_y != NULL)
  182522. *white_y = info_ptr->int_y_white;
  182523. if (red_x != NULL)
  182524. *red_x = info_ptr->int_x_red;
  182525. if (red_y != NULL)
  182526. *red_y = info_ptr->int_y_red;
  182527. if (green_x != NULL)
  182528. *green_x = info_ptr->int_x_green;
  182529. if (green_y != NULL)
  182530. *green_y = info_ptr->int_y_green;
  182531. if (blue_x != NULL)
  182532. *blue_x = info_ptr->int_x_blue;
  182533. if (blue_y != NULL)
  182534. *blue_y = info_ptr->int_y_blue;
  182535. return (PNG_INFO_cHRM);
  182536. }
  182537. return (0);
  182538. }
  182539. #endif
  182540. #endif
  182541. #if defined(PNG_gAMA_SUPPORTED)
  182542. #ifdef PNG_FLOATING_POINT_SUPPORTED
  182543. png_uint_32 PNGAPI
  182544. png_get_gAMA(png_structp png_ptr, png_infop info_ptr, double *file_gamma)
  182545. {
  182546. if (png_ptr != NULL && info_ptr != NULL && (info_ptr->valid & PNG_INFO_gAMA)
  182547. && file_gamma != NULL)
  182548. {
  182549. png_debug1(1, "in %s retrieval function\n", "gAMA");
  182550. *file_gamma = (double)info_ptr->gamma;
  182551. return (PNG_INFO_gAMA);
  182552. }
  182553. return (0);
  182554. }
  182555. #endif
  182556. #ifdef PNG_FIXED_POINT_SUPPORTED
  182557. png_uint_32 PNGAPI
  182558. png_get_gAMA_fixed(png_structp png_ptr, png_infop info_ptr,
  182559. png_fixed_point *int_file_gamma)
  182560. {
  182561. if (png_ptr != NULL && info_ptr != NULL && (info_ptr->valid & PNG_INFO_gAMA)
  182562. && int_file_gamma != NULL)
  182563. {
  182564. png_debug1(1, "in %s retrieval function\n", "gAMA");
  182565. *int_file_gamma = info_ptr->int_gamma;
  182566. return (PNG_INFO_gAMA);
  182567. }
  182568. return (0);
  182569. }
  182570. #endif
  182571. #endif
  182572. #if defined(PNG_sRGB_SUPPORTED)
  182573. png_uint_32 PNGAPI
  182574. png_get_sRGB(png_structp png_ptr, png_infop info_ptr, int *file_srgb_intent)
  182575. {
  182576. if (png_ptr != NULL && info_ptr != NULL && (info_ptr->valid & PNG_INFO_sRGB)
  182577. && file_srgb_intent != NULL)
  182578. {
  182579. png_debug1(1, "in %s retrieval function\n", "sRGB");
  182580. *file_srgb_intent = (int)info_ptr->srgb_intent;
  182581. return (PNG_INFO_sRGB);
  182582. }
  182583. return (0);
  182584. }
  182585. #endif
  182586. #if defined(PNG_iCCP_SUPPORTED)
  182587. png_uint_32 PNGAPI
  182588. png_get_iCCP(png_structp png_ptr, png_infop info_ptr,
  182589. png_charpp name, int *compression_type,
  182590. png_charpp profile, png_uint_32 *proflen)
  182591. {
  182592. if (png_ptr != NULL && info_ptr != NULL && (info_ptr->valid & PNG_INFO_iCCP)
  182593. && name != NULL && profile != NULL && proflen != NULL)
  182594. {
  182595. png_debug1(1, "in %s retrieval function\n", "iCCP");
  182596. *name = info_ptr->iccp_name;
  182597. *profile = info_ptr->iccp_profile;
  182598. /* compression_type is a dummy so the API won't have to change
  182599. if we introduce multiple compression types later. */
  182600. *proflen = (int)info_ptr->iccp_proflen;
  182601. *compression_type = (int)info_ptr->iccp_compression;
  182602. return (PNG_INFO_iCCP);
  182603. }
  182604. return (0);
  182605. }
  182606. #endif
  182607. #if defined(PNG_sPLT_SUPPORTED)
  182608. png_uint_32 PNGAPI
  182609. png_get_sPLT(png_structp png_ptr, png_infop info_ptr,
  182610. png_sPLT_tpp spalettes)
  182611. {
  182612. if (png_ptr != NULL && info_ptr != NULL && spalettes != NULL)
  182613. {
  182614. *spalettes = info_ptr->splt_palettes;
  182615. return ((png_uint_32)info_ptr->splt_palettes_num);
  182616. }
  182617. return (0);
  182618. }
  182619. #endif
  182620. #if defined(PNG_hIST_SUPPORTED)
  182621. png_uint_32 PNGAPI
  182622. png_get_hIST(png_structp png_ptr, png_infop info_ptr, png_uint_16p *hist)
  182623. {
  182624. if (png_ptr != NULL && info_ptr != NULL && (info_ptr->valid & PNG_INFO_hIST)
  182625. && hist != NULL)
  182626. {
  182627. png_debug1(1, "in %s retrieval function\n", "hIST");
  182628. *hist = info_ptr->hist;
  182629. return (PNG_INFO_hIST);
  182630. }
  182631. return (0);
  182632. }
  182633. #endif
  182634. png_uint_32 PNGAPI
  182635. png_get_IHDR(png_structp png_ptr, png_infop info_ptr,
  182636. png_uint_32 *width, png_uint_32 *height, int *bit_depth,
  182637. int *color_type, int *interlace_type, int *compression_type,
  182638. int *filter_type)
  182639. {
  182640. if (png_ptr != NULL && info_ptr != NULL && width != NULL && height != NULL &&
  182641. bit_depth != NULL && color_type != NULL)
  182642. {
  182643. png_debug1(1, "in %s retrieval function\n", "IHDR");
  182644. *width = info_ptr->width;
  182645. *height = info_ptr->height;
  182646. *bit_depth = info_ptr->bit_depth;
  182647. if (info_ptr->bit_depth < 1 || info_ptr->bit_depth > 16)
  182648. png_error(png_ptr, "Invalid bit depth");
  182649. *color_type = info_ptr->color_type;
  182650. if (info_ptr->color_type > 6)
  182651. png_error(png_ptr, "Invalid color type");
  182652. if (compression_type != NULL)
  182653. *compression_type = info_ptr->compression_type;
  182654. if (filter_type != NULL)
  182655. *filter_type = info_ptr->filter_type;
  182656. if (interlace_type != NULL)
  182657. *interlace_type = info_ptr->interlace_type;
  182658. /* check for potential overflow of rowbytes */
  182659. if (*width == 0 || *width > PNG_UINT_31_MAX)
  182660. png_error(png_ptr, "Invalid image width");
  182661. if (*height == 0 || *height > PNG_UINT_31_MAX)
  182662. png_error(png_ptr, "Invalid image height");
  182663. if (info_ptr->width > (PNG_UINT_32_MAX
  182664. >> 3) /* 8-byte RGBA pixels */
  182665. - 64 /* bigrowbuf hack */
  182666. - 1 /* filter byte */
  182667. - 7*8 /* rounding of width to multiple of 8 pixels */
  182668. - 8) /* extra max_pixel_depth pad */
  182669. {
  182670. png_warning(png_ptr,
  182671. "Width too large for libpng to process image data.");
  182672. }
  182673. return (1);
  182674. }
  182675. return (0);
  182676. }
  182677. #if defined(PNG_oFFs_SUPPORTED)
  182678. png_uint_32 PNGAPI
  182679. png_get_oFFs(png_structp png_ptr, png_infop info_ptr,
  182680. png_int_32 *offset_x, png_int_32 *offset_y, int *unit_type)
  182681. {
  182682. if (png_ptr != NULL && info_ptr != NULL && (info_ptr->valid & PNG_INFO_oFFs)
  182683. && offset_x != NULL && offset_y != NULL && unit_type != NULL)
  182684. {
  182685. png_debug1(1, "in %s retrieval function\n", "oFFs");
  182686. *offset_x = info_ptr->x_offset;
  182687. *offset_y = info_ptr->y_offset;
  182688. *unit_type = (int)info_ptr->offset_unit_type;
  182689. return (PNG_INFO_oFFs);
  182690. }
  182691. return (0);
  182692. }
  182693. #endif
  182694. #if defined(PNG_pCAL_SUPPORTED)
  182695. png_uint_32 PNGAPI
  182696. png_get_pCAL(png_structp png_ptr, png_infop info_ptr,
  182697. png_charp *purpose, png_int_32 *X0, png_int_32 *X1, int *type, int *nparams,
  182698. png_charp *units, png_charpp *params)
  182699. {
  182700. if (png_ptr != NULL && info_ptr != NULL && (info_ptr->valid & PNG_INFO_pCAL)
  182701. && purpose != NULL && X0 != NULL && X1 != NULL && type != NULL &&
  182702. nparams != NULL && units != NULL && params != NULL)
  182703. {
  182704. png_debug1(1, "in %s retrieval function\n", "pCAL");
  182705. *purpose = info_ptr->pcal_purpose;
  182706. *X0 = info_ptr->pcal_X0;
  182707. *X1 = info_ptr->pcal_X1;
  182708. *type = (int)info_ptr->pcal_type;
  182709. *nparams = (int)info_ptr->pcal_nparams;
  182710. *units = info_ptr->pcal_units;
  182711. *params = info_ptr->pcal_params;
  182712. return (PNG_INFO_pCAL);
  182713. }
  182714. return (0);
  182715. }
  182716. #endif
  182717. #if defined(PNG_sCAL_SUPPORTED)
  182718. #ifdef PNG_FLOATING_POINT_SUPPORTED
  182719. png_uint_32 PNGAPI
  182720. png_get_sCAL(png_structp png_ptr, png_infop info_ptr,
  182721. int *unit, double *width, double *height)
  182722. {
  182723. if (png_ptr != NULL && info_ptr != NULL &&
  182724. (info_ptr->valid & PNG_INFO_sCAL))
  182725. {
  182726. *unit = info_ptr->scal_unit;
  182727. *width = info_ptr->scal_pixel_width;
  182728. *height = info_ptr->scal_pixel_height;
  182729. return (PNG_INFO_sCAL);
  182730. }
  182731. return(0);
  182732. }
  182733. #else
  182734. #ifdef PNG_FIXED_POINT_SUPPORTED
  182735. png_uint_32 PNGAPI
  182736. png_get_sCAL_s(png_structp png_ptr, png_infop info_ptr,
  182737. int *unit, png_charpp width, png_charpp height)
  182738. {
  182739. if (png_ptr != NULL && info_ptr != NULL &&
  182740. (info_ptr->valid & PNG_INFO_sCAL))
  182741. {
  182742. *unit = info_ptr->scal_unit;
  182743. *width = info_ptr->scal_s_width;
  182744. *height = info_ptr->scal_s_height;
  182745. return (PNG_INFO_sCAL);
  182746. }
  182747. return(0);
  182748. }
  182749. #endif
  182750. #endif
  182751. #endif
  182752. #if defined(PNG_pHYs_SUPPORTED)
  182753. png_uint_32 PNGAPI
  182754. png_get_pHYs(png_structp png_ptr, png_infop info_ptr,
  182755. png_uint_32 *res_x, png_uint_32 *res_y, int *unit_type)
  182756. {
  182757. png_uint_32 retval = 0;
  182758. if (png_ptr != NULL && info_ptr != NULL &&
  182759. (info_ptr->valid & PNG_INFO_pHYs))
  182760. {
  182761. png_debug1(1, "in %s retrieval function\n", "pHYs");
  182762. if (res_x != NULL)
  182763. {
  182764. *res_x = info_ptr->x_pixels_per_unit;
  182765. retval |= PNG_INFO_pHYs;
  182766. }
  182767. if (res_y != NULL)
  182768. {
  182769. *res_y = info_ptr->y_pixels_per_unit;
  182770. retval |= PNG_INFO_pHYs;
  182771. }
  182772. if (unit_type != NULL)
  182773. {
  182774. *unit_type = (int)info_ptr->phys_unit_type;
  182775. retval |= PNG_INFO_pHYs;
  182776. }
  182777. }
  182778. return (retval);
  182779. }
  182780. #endif
  182781. png_uint_32 PNGAPI
  182782. png_get_PLTE(png_structp png_ptr, png_infop info_ptr, png_colorp *palette,
  182783. int *num_palette)
  182784. {
  182785. if (png_ptr != NULL && info_ptr != NULL && (info_ptr->valid & PNG_INFO_PLTE)
  182786. && palette != NULL)
  182787. {
  182788. png_debug1(1, "in %s retrieval function\n", "PLTE");
  182789. *palette = info_ptr->palette;
  182790. *num_palette = info_ptr->num_palette;
  182791. png_debug1(3, "num_palette = %d\n", *num_palette);
  182792. return (PNG_INFO_PLTE);
  182793. }
  182794. return (0);
  182795. }
  182796. #if defined(PNG_sBIT_SUPPORTED)
  182797. png_uint_32 PNGAPI
  182798. png_get_sBIT(png_structp png_ptr, png_infop info_ptr, png_color_8p *sig_bit)
  182799. {
  182800. if (png_ptr != NULL && info_ptr != NULL && (info_ptr->valid & PNG_INFO_sBIT)
  182801. && sig_bit != NULL)
  182802. {
  182803. png_debug1(1, "in %s retrieval function\n", "sBIT");
  182804. *sig_bit = &(info_ptr->sig_bit);
  182805. return (PNG_INFO_sBIT);
  182806. }
  182807. return (0);
  182808. }
  182809. #endif
  182810. #if defined(PNG_TEXT_SUPPORTED)
  182811. png_uint_32 PNGAPI
  182812. png_get_text(png_structp png_ptr, png_infop info_ptr, png_textp *text_ptr,
  182813. int *num_text)
  182814. {
  182815. if (png_ptr != NULL && info_ptr != NULL && info_ptr->num_text > 0)
  182816. {
  182817. png_debug1(1, "in %s retrieval function\n",
  182818. (png_ptr->chunk_name[0] == '\0' ? "text"
  182819. : (png_const_charp)png_ptr->chunk_name));
  182820. if (text_ptr != NULL)
  182821. *text_ptr = info_ptr->text;
  182822. if (num_text != NULL)
  182823. *num_text = info_ptr->num_text;
  182824. return ((png_uint_32)info_ptr->num_text);
  182825. }
  182826. if (num_text != NULL)
  182827. *num_text = 0;
  182828. return(0);
  182829. }
  182830. #endif
  182831. #if defined(PNG_tIME_SUPPORTED)
  182832. png_uint_32 PNGAPI
  182833. png_get_tIME(png_structp png_ptr, png_infop info_ptr, png_timep *mod_time)
  182834. {
  182835. if (png_ptr != NULL && info_ptr != NULL && (info_ptr->valid & PNG_INFO_tIME)
  182836. && mod_time != NULL)
  182837. {
  182838. png_debug1(1, "in %s retrieval function\n", "tIME");
  182839. *mod_time = &(info_ptr->mod_time);
  182840. return (PNG_INFO_tIME);
  182841. }
  182842. return (0);
  182843. }
  182844. #endif
  182845. #if defined(PNG_tRNS_SUPPORTED)
  182846. png_uint_32 PNGAPI
  182847. png_get_tRNS(png_structp png_ptr, png_infop info_ptr,
  182848. png_bytep *trans, int *num_trans, png_color_16p *trans_values)
  182849. {
  182850. png_uint_32 retval = 0;
  182851. if (png_ptr != NULL && info_ptr != NULL && (info_ptr->valid & PNG_INFO_tRNS))
  182852. {
  182853. png_debug1(1, "in %s retrieval function\n", "tRNS");
  182854. if (info_ptr->color_type == PNG_COLOR_TYPE_PALETTE)
  182855. {
  182856. if (trans != NULL)
  182857. {
  182858. *trans = info_ptr->trans;
  182859. retval |= PNG_INFO_tRNS;
  182860. }
  182861. if (trans_values != NULL)
  182862. *trans_values = &(info_ptr->trans_values);
  182863. }
  182864. else /* if (info_ptr->color_type != PNG_COLOR_TYPE_PALETTE) */
  182865. {
  182866. if (trans_values != NULL)
  182867. {
  182868. *trans_values = &(info_ptr->trans_values);
  182869. retval |= PNG_INFO_tRNS;
  182870. }
  182871. if(trans != NULL)
  182872. *trans = NULL;
  182873. }
  182874. if(num_trans != NULL)
  182875. {
  182876. *num_trans = info_ptr->num_trans;
  182877. retval |= PNG_INFO_tRNS;
  182878. }
  182879. }
  182880. return (retval);
  182881. }
  182882. #endif
  182883. #if defined(PNG_UNKNOWN_CHUNKS_SUPPORTED)
  182884. png_uint_32 PNGAPI
  182885. png_get_unknown_chunks(png_structp png_ptr, png_infop info_ptr,
  182886. png_unknown_chunkpp unknowns)
  182887. {
  182888. if (png_ptr != NULL && info_ptr != NULL && unknowns != NULL)
  182889. {
  182890. *unknowns = info_ptr->unknown_chunks;
  182891. return ((png_uint_32)info_ptr->unknown_chunks_num);
  182892. }
  182893. return (0);
  182894. }
  182895. #endif
  182896. #if defined(PNG_READ_RGB_TO_GRAY_SUPPORTED)
  182897. png_byte PNGAPI
  182898. png_get_rgb_to_gray_status (png_structp png_ptr)
  182899. {
  182900. return (png_byte)(png_ptr? png_ptr->rgb_to_gray_status : 0);
  182901. }
  182902. #endif
  182903. #if defined(PNG_USER_CHUNKS_SUPPORTED)
  182904. png_voidp PNGAPI
  182905. png_get_user_chunk_ptr(png_structp png_ptr)
  182906. {
  182907. return (png_ptr? png_ptr->user_chunk_ptr : NULL);
  182908. }
  182909. #endif
  182910. #ifdef PNG_WRITE_SUPPORTED
  182911. png_uint_32 PNGAPI
  182912. png_get_compression_buffer_size(png_structp png_ptr)
  182913. {
  182914. return (png_uint_32)(png_ptr? png_ptr->zbuf_size : 0L);
  182915. }
  182916. #endif
  182917. #ifdef PNG_ASSEMBLER_CODE_SUPPORTED
  182918. #ifndef PNG_1_0_X
  182919. /* this function was added to libpng 1.2.0 and should exist by default */
  182920. png_uint_32 PNGAPI
  182921. png_get_asm_flags (png_structp png_ptr)
  182922. {
  182923. /* obsolete, to be removed from libpng-1.4.0 */
  182924. return (png_ptr? 0L: 0L);
  182925. }
  182926. /* this function was added to libpng 1.2.0 and should exist by default */
  182927. png_uint_32 PNGAPI
  182928. png_get_asm_flagmask (int flag_select)
  182929. {
  182930. /* obsolete, to be removed from libpng-1.4.0 */
  182931. flag_select=flag_select;
  182932. return 0L;
  182933. }
  182934. /* GRR: could add this: && defined(PNG_MMX_CODE_SUPPORTED) */
  182935. /* this function was added to libpng 1.2.0 */
  182936. png_uint_32 PNGAPI
  182937. png_get_mmx_flagmask (int flag_select, int *compilerID)
  182938. {
  182939. /* obsolete, to be removed from libpng-1.4.0 */
  182940. flag_select=flag_select;
  182941. *compilerID = -1; /* unknown (i.e., no asm/MMX code compiled) */
  182942. return 0L;
  182943. }
  182944. /* this function was added to libpng 1.2.0 */
  182945. png_byte PNGAPI
  182946. png_get_mmx_bitdepth_threshold (png_structp png_ptr)
  182947. {
  182948. /* obsolete, to be removed from libpng-1.4.0 */
  182949. return (png_ptr? 0: 0);
  182950. }
  182951. /* this function was added to libpng 1.2.0 */
  182952. png_uint_32 PNGAPI
  182953. png_get_mmx_rowbytes_threshold (png_structp png_ptr)
  182954. {
  182955. /* obsolete, to be removed from libpng-1.4.0 */
  182956. return (png_ptr? 0L: 0L);
  182957. }
  182958. #endif /* ?PNG_1_0_X */
  182959. #endif /* ?PNG_ASSEMBLER_CODE_SUPPORTED */
  182960. #ifdef PNG_SET_USER_LIMITS_SUPPORTED
  182961. /* these functions were added to libpng 1.2.6 */
  182962. png_uint_32 PNGAPI
  182963. png_get_user_width_max (png_structp png_ptr)
  182964. {
  182965. return (png_ptr? png_ptr->user_width_max : 0);
  182966. }
  182967. png_uint_32 PNGAPI
  182968. png_get_user_height_max (png_structp png_ptr)
  182969. {
  182970. return (png_ptr? png_ptr->user_height_max : 0);
  182971. }
  182972. #endif /* ?PNG_SET_USER_LIMITS_SUPPORTED */
  182973. #endif /* PNG_READ_SUPPORTED || PNG_WRITE_SUPPORTED */
  182974. /*** End of inlined file: pngget.c ***/
  182975. /*** Start of inlined file: pngmem.c ***/
  182976. /* pngmem.c - stub functions for memory allocation
  182977. *
  182978. * Last changed in libpng 1.2.13 November 13, 2006
  182979. * For conditions of distribution and use, see copyright notice in png.h
  182980. * Copyright (c) 1998-2006 Glenn Randers-Pehrson
  182981. * (Version 0.96 Copyright (c) 1996, 1997 Andreas Dilger)
  182982. * (Version 0.88 Copyright (c) 1995, 1996 Guy Eric Schalnat, Group 42, Inc.)
  182983. *
  182984. * This file provides a location for all memory allocation. Users who
  182985. * need special memory handling are expected to supply replacement
  182986. * functions for png_malloc() and png_free(), and to use
  182987. * png_create_read_struct_2() and png_create_write_struct_2() to
  182988. * identify the replacement functions.
  182989. */
  182990. #define PNG_INTERNAL
  182991. #if defined(PNG_READ_SUPPORTED) || defined(PNG_WRITE_SUPPORTED)
  182992. /* Borland DOS special memory handler */
  182993. #if defined(__TURBOC__) && !defined(_Windows) && !defined(__FLAT__)
  182994. /* if you change this, be sure to change the one in png.h also */
  182995. /* Allocate memory for a png_struct. The malloc and memset can be replaced
  182996. by a single call to calloc() if this is thought to improve performance. */
  182997. png_voidp /* PRIVATE */
  182998. png_create_struct(int type)
  182999. {
  183000. #ifdef PNG_USER_MEM_SUPPORTED
  183001. return (png_create_struct_2(type, png_malloc_ptr_NULL, png_voidp_NULL));
  183002. }
  183003. /* Alternate version of png_create_struct, for use with user-defined malloc. */
  183004. png_voidp /* PRIVATE */
  183005. png_create_struct_2(int type, png_malloc_ptr malloc_fn, png_voidp mem_ptr)
  183006. {
  183007. #endif /* PNG_USER_MEM_SUPPORTED */
  183008. png_size_t size;
  183009. png_voidp struct_ptr;
  183010. if (type == PNG_STRUCT_INFO)
  183011. size = png_sizeof(png_info);
  183012. else if (type == PNG_STRUCT_PNG)
  183013. size = png_sizeof(png_struct);
  183014. else
  183015. return (png_get_copyright(NULL));
  183016. #ifdef PNG_USER_MEM_SUPPORTED
  183017. if(malloc_fn != NULL)
  183018. {
  183019. png_struct dummy_struct;
  183020. png_structp png_ptr = &dummy_struct;
  183021. png_ptr->mem_ptr=mem_ptr;
  183022. struct_ptr = (*(malloc_fn))(png_ptr, (png_uint_32)size);
  183023. }
  183024. else
  183025. #endif /* PNG_USER_MEM_SUPPORTED */
  183026. struct_ptr = (png_voidp)farmalloc(size);
  183027. if (struct_ptr != NULL)
  183028. png_memset(struct_ptr, 0, size);
  183029. return (struct_ptr);
  183030. }
  183031. /* Free memory allocated by a png_create_struct() call */
  183032. void /* PRIVATE */
  183033. png_destroy_struct(png_voidp struct_ptr)
  183034. {
  183035. #ifdef PNG_USER_MEM_SUPPORTED
  183036. png_destroy_struct_2(struct_ptr, png_free_ptr_NULL, png_voidp_NULL);
  183037. }
  183038. /* Free memory allocated by a png_create_struct() call */
  183039. void /* PRIVATE */
  183040. png_destroy_struct_2(png_voidp struct_ptr, png_free_ptr free_fn,
  183041. png_voidp mem_ptr)
  183042. {
  183043. #endif
  183044. if (struct_ptr != NULL)
  183045. {
  183046. #ifdef PNG_USER_MEM_SUPPORTED
  183047. if(free_fn != NULL)
  183048. {
  183049. png_struct dummy_struct;
  183050. png_structp png_ptr = &dummy_struct;
  183051. png_ptr->mem_ptr=mem_ptr;
  183052. (*(free_fn))(png_ptr, struct_ptr);
  183053. return;
  183054. }
  183055. #endif /* PNG_USER_MEM_SUPPORTED */
  183056. farfree (struct_ptr);
  183057. }
  183058. }
  183059. /* Allocate memory. For reasonable files, size should never exceed
  183060. * 64K. However, zlib may allocate more then 64K if you don't tell
  183061. * it not to. See zconf.h and png.h for more information. zlib does
  183062. * need to allocate exactly 64K, so whatever you call here must
  183063. * have the ability to do that.
  183064. *
  183065. * Borland seems to have a problem in DOS mode for exactly 64K.
  183066. * It gives you a segment with an offset of 8 (perhaps to store its
  183067. * memory stuff). zlib doesn't like this at all, so we have to
  183068. * detect and deal with it. This code should not be needed in
  183069. * Windows or OS/2 modes, and only in 16 bit mode. This code has
  183070. * been updated by Alexander Lehmann for version 0.89 to waste less
  183071. * memory.
  183072. *
  183073. * Note that we can't use png_size_t for the "size" declaration,
  183074. * since on some systems a png_size_t is a 16-bit quantity, and as a
  183075. * result, we would be truncating potentially larger memory requests
  183076. * (which should cause a fatal error) and introducing major problems.
  183077. */
  183078. png_voidp PNGAPI
  183079. png_malloc(png_structp png_ptr, png_uint_32 size)
  183080. {
  183081. png_voidp ret;
  183082. if (png_ptr == NULL || size == 0)
  183083. return (NULL);
  183084. #ifdef PNG_USER_MEM_SUPPORTED
  183085. if(png_ptr->malloc_fn != NULL)
  183086. ret = ((png_voidp)(*(png_ptr->malloc_fn))(png_ptr, (png_size_t)size));
  183087. else
  183088. ret = (png_malloc_default(png_ptr, size));
  183089. if (ret == NULL && (png_ptr->flags&PNG_FLAG_MALLOC_NULL_MEM_OK) == 0)
  183090. png_error(png_ptr, "Out of memory!");
  183091. return (ret);
  183092. }
  183093. png_voidp PNGAPI
  183094. png_malloc_default(png_structp png_ptr, png_uint_32 size)
  183095. {
  183096. png_voidp ret;
  183097. #endif /* PNG_USER_MEM_SUPPORTED */
  183098. if (png_ptr == NULL || size == 0)
  183099. return (NULL);
  183100. #ifdef PNG_MAX_MALLOC_64K
  183101. if (size > (png_uint_32)65536L)
  183102. {
  183103. png_warning(png_ptr, "Cannot Allocate > 64K");
  183104. ret = NULL;
  183105. }
  183106. else
  183107. #endif
  183108. if (size != (size_t)size)
  183109. ret = NULL;
  183110. else if (size == (png_uint_32)65536L)
  183111. {
  183112. if (png_ptr->offset_table == NULL)
  183113. {
  183114. /* try to see if we need to do any of this fancy stuff */
  183115. ret = farmalloc(size);
  183116. if (ret == NULL || ((png_size_t)ret & 0xffff))
  183117. {
  183118. int num_blocks;
  183119. png_uint_32 total_size;
  183120. png_bytep table;
  183121. int i;
  183122. png_byte huge * hptr;
  183123. if (ret != NULL)
  183124. {
  183125. farfree(ret);
  183126. ret = NULL;
  183127. }
  183128. if(png_ptr->zlib_window_bits > 14)
  183129. num_blocks = (int)(1 << (png_ptr->zlib_window_bits - 14));
  183130. else
  183131. num_blocks = 1;
  183132. if (png_ptr->zlib_mem_level >= 7)
  183133. num_blocks += (int)(1 << (png_ptr->zlib_mem_level - 7));
  183134. else
  183135. num_blocks++;
  183136. total_size = ((png_uint_32)65536L) * (png_uint_32)num_blocks+16;
  183137. table = farmalloc(total_size);
  183138. if (table == NULL)
  183139. {
  183140. #ifndef PNG_USER_MEM_SUPPORTED
  183141. if ((png_ptr->flags&PNG_FLAG_MALLOC_NULL_MEM_OK) == 0)
  183142. png_error(png_ptr, "Out Of Memory."); /* Note "O" and "M" */
  183143. else
  183144. png_warning(png_ptr, "Out Of Memory.");
  183145. #endif
  183146. return (NULL);
  183147. }
  183148. if ((png_size_t)table & 0xfff0)
  183149. {
  183150. #ifndef PNG_USER_MEM_SUPPORTED
  183151. if ((png_ptr->flags&PNG_FLAG_MALLOC_NULL_MEM_OK) == 0)
  183152. png_error(png_ptr,
  183153. "Farmalloc didn't return normalized pointer");
  183154. else
  183155. png_warning(png_ptr,
  183156. "Farmalloc didn't return normalized pointer");
  183157. #endif
  183158. return (NULL);
  183159. }
  183160. png_ptr->offset_table = table;
  183161. png_ptr->offset_table_ptr = farmalloc(num_blocks *
  183162. png_sizeof (png_bytep));
  183163. if (png_ptr->offset_table_ptr == NULL)
  183164. {
  183165. #ifndef PNG_USER_MEM_SUPPORTED
  183166. if ((png_ptr->flags&PNG_FLAG_MALLOC_NULL_MEM_OK) == 0)
  183167. png_error(png_ptr, "Out Of memory."); /* Note "O" and "M" */
  183168. else
  183169. png_warning(png_ptr, "Out Of memory.");
  183170. #endif
  183171. return (NULL);
  183172. }
  183173. hptr = (png_byte huge *)table;
  183174. if ((png_size_t)hptr & 0xf)
  183175. {
  183176. hptr = (png_byte huge *)((long)(hptr) & 0xfffffff0L);
  183177. hptr = hptr + 16L; /* "hptr += 16L" fails on Turbo C++ 3.0 */
  183178. }
  183179. for (i = 0; i < num_blocks; i++)
  183180. {
  183181. png_ptr->offset_table_ptr[i] = (png_bytep)hptr;
  183182. hptr = hptr + (png_uint_32)65536L; /* "+=" fails on TC++3.0 */
  183183. }
  183184. png_ptr->offset_table_number = num_blocks;
  183185. png_ptr->offset_table_count = 0;
  183186. png_ptr->offset_table_count_free = 0;
  183187. }
  183188. }
  183189. if (png_ptr->offset_table_count >= png_ptr->offset_table_number)
  183190. {
  183191. #ifndef PNG_USER_MEM_SUPPORTED
  183192. if ((png_ptr->flags&PNG_FLAG_MALLOC_NULL_MEM_OK) == 0)
  183193. png_error(png_ptr, "Out of Memory."); /* Note "o" and "M" */
  183194. else
  183195. png_warning(png_ptr, "Out of Memory.");
  183196. #endif
  183197. return (NULL);
  183198. }
  183199. ret = png_ptr->offset_table_ptr[png_ptr->offset_table_count++];
  183200. }
  183201. else
  183202. ret = farmalloc(size);
  183203. #ifndef PNG_USER_MEM_SUPPORTED
  183204. if (ret == NULL)
  183205. {
  183206. if ((png_ptr->flags&PNG_FLAG_MALLOC_NULL_MEM_OK) == 0)
  183207. png_error(png_ptr, "Out of memory."); /* Note "o" and "m" */
  183208. else
  183209. png_warning(png_ptr, "Out of memory."); /* Note "o" and "m" */
  183210. }
  183211. #endif
  183212. return (ret);
  183213. }
  183214. /* free a pointer allocated by png_malloc(). In the default
  183215. configuration, png_ptr is not used, but is passed in case it
  183216. is needed. If ptr is NULL, return without taking any action. */
  183217. void PNGAPI
  183218. png_free(png_structp png_ptr, png_voidp ptr)
  183219. {
  183220. if (png_ptr == NULL || ptr == NULL)
  183221. return;
  183222. #ifdef PNG_USER_MEM_SUPPORTED
  183223. if (png_ptr->free_fn != NULL)
  183224. {
  183225. (*(png_ptr->free_fn))(png_ptr, ptr);
  183226. return;
  183227. }
  183228. else png_free_default(png_ptr, ptr);
  183229. }
  183230. void PNGAPI
  183231. png_free_default(png_structp png_ptr, png_voidp ptr)
  183232. {
  183233. #endif /* PNG_USER_MEM_SUPPORTED */
  183234. if(png_ptr == NULL) return;
  183235. if (png_ptr->offset_table != NULL)
  183236. {
  183237. int i;
  183238. for (i = 0; i < png_ptr->offset_table_count; i++)
  183239. {
  183240. if (ptr == png_ptr->offset_table_ptr[i])
  183241. {
  183242. ptr = NULL;
  183243. png_ptr->offset_table_count_free++;
  183244. break;
  183245. }
  183246. }
  183247. if (png_ptr->offset_table_count_free == png_ptr->offset_table_count)
  183248. {
  183249. farfree(png_ptr->offset_table);
  183250. farfree(png_ptr->offset_table_ptr);
  183251. png_ptr->offset_table = NULL;
  183252. png_ptr->offset_table_ptr = NULL;
  183253. }
  183254. }
  183255. if (ptr != NULL)
  183256. {
  183257. farfree(ptr);
  183258. }
  183259. }
  183260. #else /* Not the Borland DOS special memory handler */
  183261. /* Allocate memory for a png_struct or a png_info. The malloc and
  183262. memset can be replaced by a single call to calloc() if this is thought
  183263. to improve performance noticably. */
  183264. png_voidp /* PRIVATE */
  183265. png_create_struct(int type)
  183266. {
  183267. #ifdef PNG_USER_MEM_SUPPORTED
  183268. return (png_create_struct_2(type, png_malloc_ptr_NULL, png_voidp_NULL));
  183269. }
  183270. /* Allocate memory for a png_struct or a png_info. The malloc and
  183271. memset can be replaced by a single call to calloc() if this is thought
  183272. to improve performance noticably. */
  183273. png_voidp /* PRIVATE */
  183274. png_create_struct_2(int type, png_malloc_ptr malloc_fn, png_voidp mem_ptr)
  183275. {
  183276. #endif /* PNG_USER_MEM_SUPPORTED */
  183277. png_size_t size;
  183278. png_voidp struct_ptr;
  183279. if (type == PNG_STRUCT_INFO)
  183280. size = png_sizeof(png_info);
  183281. else if (type == PNG_STRUCT_PNG)
  183282. size = png_sizeof(png_struct);
  183283. else
  183284. return (NULL);
  183285. #ifdef PNG_USER_MEM_SUPPORTED
  183286. if(malloc_fn != NULL)
  183287. {
  183288. png_struct dummy_struct;
  183289. png_structp png_ptr = &dummy_struct;
  183290. png_ptr->mem_ptr=mem_ptr;
  183291. struct_ptr = (*(malloc_fn))(png_ptr, size);
  183292. if (struct_ptr != NULL)
  183293. png_memset(struct_ptr, 0, size);
  183294. return (struct_ptr);
  183295. }
  183296. #endif /* PNG_USER_MEM_SUPPORTED */
  183297. #if defined(__TURBOC__) && !defined(__FLAT__)
  183298. struct_ptr = (png_voidp)farmalloc(size);
  183299. #else
  183300. # if defined(_MSC_VER) && defined(MAXSEG_64K)
  183301. struct_ptr = (png_voidp)halloc(size,1);
  183302. # else
  183303. struct_ptr = (png_voidp)malloc(size);
  183304. # endif
  183305. #endif
  183306. if (struct_ptr != NULL)
  183307. png_memset(struct_ptr, 0, size);
  183308. return (struct_ptr);
  183309. }
  183310. /* Free memory allocated by a png_create_struct() call */
  183311. void /* PRIVATE */
  183312. png_destroy_struct(png_voidp struct_ptr)
  183313. {
  183314. #ifdef PNG_USER_MEM_SUPPORTED
  183315. png_destroy_struct_2(struct_ptr, png_free_ptr_NULL, png_voidp_NULL);
  183316. }
  183317. /* Free memory allocated by a png_create_struct() call */
  183318. void /* PRIVATE */
  183319. png_destroy_struct_2(png_voidp struct_ptr, png_free_ptr free_fn,
  183320. png_voidp mem_ptr)
  183321. {
  183322. #endif /* PNG_USER_MEM_SUPPORTED */
  183323. if (struct_ptr != NULL)
  183324. {
  183325. #ifdef PNG_USER_MEM_SUPPORTED
  183326. if(free_fn != NULL)
  183327. {
  183328. png_struct dummy_struct;
  183329. png_structp png_ptr = &dummy_struct;
  183330. png_ptr->mem_ptr=mem_ptr;
  183331. (*(free_fn))(png_ptr, struct_ptr);
  183332. return;
  183333. }
  183334. #endif /* PNG_USER_MEM_SUPPORTED */
  183335. #if defined(__TURBOC__) && !defined(__FLAT__)
  183336. farfree(struct_ptr);
  183337. #else
  183338. # if defined(_MSC_VER) && defined(MAXSEG_64K)
  183339. hfree(struct_ptr);
  183340. # else
  183341. free(struct_ptr);
  183342. # endif
  183343. #endif
  183344. }
  183345. }
  183346. /* Allocate memory. For reasonable files, size should never exceed
  183347. 64K. However, zlib may allocate more then 64K if you don't tell
  183348. it not to. See zconf.h and png.h for more information. zlib does
  183349. need to allocate exactly 64K, so whatever you call here must
  183350. have the ability to do that. */
  183351. png_voidp PNGAPI
  183352. png_malloc(png_structp png_ptr, png_uint_32 size)
  183353. {
  183354. png_voidp ret;
  183355. #ifdef PNG_USER_MEM_SUPPORTED
  183356. if (png_ptr == NULL || size == 0)
  183357. return (NULL);
  183358. if(png_ptr->malloc_fn != NULL)
  183359. ret = ((png_voidp)(*(png_ptr->malloc_fn))(png_ptr, (png_size_t)size));
  183360. else
  183361. ret = (png_malloc_default(png_ptr, size));
  183362. if (ret == NULL && (png_ptr->flags&PNG_FLAG_MALLOC_NULL_MEM_OK) == 0)
  183363. png_error(png_ptr, "Out of Memory!");
  183364. return (ret);
  183365. }
  183366. png_voidp PNGAPI
  183367. png_malloc_default(png_structp png_ptr, png_uint_32 size)
  183368. {
  183369. png_voidp ret;
  183370. #endif /* PNG_USER_MEM_SUPPORTED */
  183371. if (png_ptr == NULL || size == 0)
  183372. return (NULL);
  183373. #ifdef PNG_MAX_MALLOC_64K
  183374. if (size > (png_uint_32)65536L)
  183375. {
  183376. #ifndef PNG_USER_MEM_SUPPORTED
  183377. if(png_ptr->flags&PNG_FLAG_MALLOC_NULL_MEM_OK) == 0)
  183378. png_error(png_ptr, "Cannot Allocate > 64K");
  183379. else
  183380. #endif
  183381. return NULL;
  183382. }
  183383. #endif
  183384. /* Check for overflow */
  183385. #if defined(__TURBOC__) && !defined(__FLAT__)
  183386. if (size != (unsigned long)size)
  183387. ret = NULL;
  183388. else
  183389. ret = farmalloc(size);
  183390. #else
  183391. # if defined(_MSC_VER) && defined(MAXSEG_64K)
  183392. if (size != (unsigned long)size)
  183393. ret = NULL;
  183394. else
  183395. ret = halloc(size, 1);
  183396. # else
  183397. if (size != (size_t)size)
  183398. ret = NULL;
  183399. else
  183400. ret = malloc((size_t)size);
  183401. # endif
  183402. #endif
  183403. #ifndef PNG_USER_MEM_SUPPORTED
  183404. if (ret == NULL && (png_ptr->flags&PNG_FLAG_MALLOC_NULL_MEM_OK) == 0)
  183405. png_error(png_ptr, "Out of Memory");
  183406. #endif
  183407. return (ret);
  183408. }
  183409. /* Free a pointer allocated by png_malloc(). If ptr is NULL, return
  183410. without taking any action. */
  183411. void PNGAPI
  183412. png_free(png_structp png_ptr, png_voidp ptr)
  183413. {
  183414. if (png_ptr == NULL || ptr == NULL)
  183415. return;
  183416. #ifdef PNG_USER_MEM_SUPPORTED
  183417. if (png_ptr->free_fn != NULL)
  183418. {
  183419. (*(png_ptr->free_fn))(png_ptr, ptr);
  183420. return;
  183421. }
  183422. else png_free_default(png_ptr, ptr);
  183423. }
  183424. void PNGAPI
  183425. png_free_default(png_structp png_ptr, png_voidp ptr)
  183426. {
  183427. if (png_ptr == NULL || ptr == NULL)
  183428. return;
  183429. #endif /* PNG_USER_MEM_SUPPORTED */
  183430. #if defined(__TURBOC__) && !defined(__FLAT__)
  183431. farfree(ptr);
  183432. #else
  183433. # if defined(_MSC_VER) && defined(MAXSEG_64K)
  183434. hfree(ptr);
  183435. # else
  183436. free(ptr);
  183437. # endif
  183438. #endif
  183439. }
  183440. #endif /* Not Borland DOS special memory handler */
  183441. #if defined(PNG_1_0_X)
  183442. # define png_malloc_warn png_malloc
  183443. #else
  183444. /* This function was added at libpng version 1.2.3. The png_malloc_warn()
  183445. * function will set up png_malloc() to issue a png_warning and return NULL
  183446. * instead of issuing a png_error, if it fails to allocate the requested
  183447. * memory.
  183448. */
  183449. png_voidp PNGAPI
  183450. png_malloc_warn(png_structp png_ptr, png_uint_32 size)
  183451. {
  183452. png_voidp ptr;
  183453. png_uint_32 save_flags;
  183454. if(png_ptr == NULL) return (NULL);
  183455. save_flags=png_ptr->flags;
  183456. png_ptr->flags|=PNG_FLAG_MALLOC_NULL_MEM_OK;
  183457. ptr = (png_voidp)png_malloc((png_structp)png_ptr, size);
  183458. png_ptr->flags=save_flags;
  183459. return(ptr);
  183460. }
  183461. #endif
  183462. png_voidp PNGAPI
  183463. png_memcpy_check (png_structp png_ptr, png_voidp s1, png_voidp s2,
  183464. png_uint_32 length)
  183465. {
  183466. png_size_t size;
  183467. size = (png_size_t)length;
  183468. if ((png_uint_32)size != length)
  183469. png_error(png_ptr,"Overflow in png_memcpy_check.");
  183470. return(png_memcpy (s1, s2, size));
  183471. }
  183472. png_voidp PNGAPI
  183473. png_memset_check (png_structp png_ptr, png_voidp s1, int value,
  183474. png_uint_32 length)
  183475. {
  183476. png_size_t size;
  183477. size = (png_size_t)length;
  183478. if ((png_uint_32)size != length)
  183479. png_error(png_ptr,"Overflow in png_memset_check.");
  183480. return (png_memset (s1, value, size));
  183481. }
  183482. #ifdef PNG_USER_MEM_SUPPORTED
  183483. /* This function is called when the application wants to use another method
  183484. * of allocating and freeing memory.
  183485. */
  183486. void PNGAPI
  183487. png_set_mem_fn(png_structp png_ptr, png_voidp mem_ptr, png_malloc_ptr
  183488. malloc_fn, png_free_ptr free_fn)
  183489. {
  183490. if(png_ptr != NULL) {
  183491. png_ptr->mem_ptr = mem_ptr;
  183492. png_ptr->malloc_fn = malloc_fn;
  183493. png_ptr->free_fn = free_fn;
  183494. }
  183495. }
  183496. /* This function returns a pointer to the mem_ptr associated with the user
  183497. * functions. The application should free any memory associated with this
  183498. * pointer before png_write_destroy and png_read_destroy are called.
  183499. */
  183500. png_voidp PNGAPI
  183501. png_get_mem_ptr(png_structp png_ptr)
  183502. {
  183503. if(png_ptr == NULL) return (NULL);
  183504. return ((png_voidp)png_ptr->mem_ptr);
  183505. }
  183506. #endif /* PNG_USER_MEM_SUPPORTED */
  183507. #endif /* PNG_READ_SUPPORTED || PNG_WRITE_SUPPORTED */
  183508. /*** End of inlined file: pngmem.c ***/
  183509. /*** Start of inlined file: pngread.c ***/
  183510. /* pngread.c - read a PNG file
  183511. *
  183512. * Last changed in libpng 1.2.20 September 7, 2007
  183513. * For conditions of distribution and use, see copyright notice in png.h
  183514. * Copyright (c) 1998-2007 Glenn Randers-Pehrson
  183515. * (Version 0.96 Copyright (c) 1996, 1997 Andreas Dilger)
  183516. * (Version 0.88 Copyright (c) 1995, 1996 Guy Eric Schalnat, Group 42, Inc.)
  183517. *
  183518. * This file contains routines that an application calls directly to
  183519. * read a PNG file or stream.
  183520. */
  183521. #define PNG_INTERNAL
  183522. #if defined(PNG_READ_SUPPORTED)
  183523. /* Create a PNG structure for reading, and allocate any memory needed. */
  183524. png_structp PNGAPI
  183525. png_create_read_struct(png_const_charp user_png_ver, png_voidp error_ptr,
  183526. png_error_ptr error_fn, png_error_ptr warn_fn)
  183527. {
  183528. #ifdef PNG_USER_MEM_SUPPORTED
  183529. return (png_create_read_struct_2(user_png_ver, error_ptr, error_fn,
  183530. warn_fn, png_voidp_NULL, png_malloc_ptr_NULL, png_free_ptr_NULL));
  183531. }
  183532. /* Alternate create PNG structure for reading, and allocate any memory needed. */
  183533. png_structp PNGAPI
  183534. png_create_read_struct_2(png_const_charp user_png_ver, png_voidp error_ptr,
  183535. png_error_ptr error_fn, png_error_ptr warn_fn, png_voidp mem_ptr,
  183536. png_malloc_ptr malloc_fn, png_free_ptr free_fn)
  183537. {
  183538. #endif /* PNG_USER_MEM_SUPPORTED */
  183539. png_structp png_ptr;
  183540. #ifdef PNG_SETJMP_SUPPORTED
  183541. #ifdef USE_FAR_KEYWORD
  183542. jmp_buf jmpbuf;
  183543. #endif
  183544. #endif
  183545. int i;
  183546. png_debug(1, "in png_create_read_struct\n");
  183547. #ifdef PNG_USER_MEM_SUPPORTED
  183548. png_ptr = (png_structp)png_create_struct_2(PNG_STRUCT_PNG,
  183549. (png_malloc_ptr)malloc_fn, (png_voidp)mem_ptr);
  183550. #else
  183551. png_ptr = (png_structp)png_create_struct(PNG_STRUCT_PNG);
  183552. #endif
  183553. if (png_ptr == NULL)
  183554. return (NULL);
  183555. /* added at libpng-1.2.6 */
  183556. #ifdef PNG_SET_USER_LIMITS_SUPPORTED
  183557. png_ptr->user_width_max=PNG_USER_WIDTH_MAX;
  183558. png_ptr->user_height_max=PNG_USER_HEIGHT_MAX;
  183559. #endif
  183560. #ifdef PNG_SETJMP_SUPPORTED
  183561. #ifdef USE_FAR_KEYWORD
  183562. if (setjmp(jmpbuf))
  183563. #else
  183564. if (setjmp(png_ptr->jmpbuf))
  183565. #endif
  183566. {
  183567. png_free(png_ptr, png_ptr->zbuf);
  183568. png_ptr->zbuf=NULL;
  183569. #ifdef PNG_USER_MEM_SUPPORTED
  183570. png_destroy_struct_2((png_voidp)png_ptr,
  183571. (png_free_ptr)free_fn, (png_voidp)mem_ptr);
  183572. #else
  183573. png_destroy_struct((png_voidp)png_ptr);
  183574. #endif
  183575. return (NULL);
  183576. }
  183577. #ifdef USE_FAR_KEYWORD
  183578. png_memcpy(png_ptr->jmpbuf,jmpbuf,png_sizeof(jmp_buf));
  183579. #endif
  183580. #endif
  183581. #ifdef PNG_USER_MEM_SUPPORTED
  183582. png_set_mem_fn(png_ptr, mem_ptr, malloc_fn, free_fn);
  183583. #endif
  183584. png_set_error_fn(png_ptr, error_ptr, error_fn, warn_fn);
  183585. i=0;
  183586. do
  183587. {
  183588. if(user_png_ver[i] != png_libpng_ver[i])
  183589. png_ptr->flags |= PNG_FLAG_LIBRARY_MISMATCH;
  183590. } while (png_libpng_ver[i++]);
  183591. if (png_ptr->flags & PNG_FLAG_LIBRARY_MISMATCH)
  183592. {
  183593. /* Libpng 0.90 and later are binary incompatible with libpng 0.89, so
  183594. * we must recompile any applications that use any older library version.
  183595. * For versions after libpng 1.0, we will be compatible, so we need
  183596. * only check the first digit.
  183597. */
  183598. if (user_png_ver == NULL || user_png_ver[0] != png_libpng_ver[0] ||
  183599. (user_png_ver[0] == '1' && user_png_ver[2] != png_libpng_ver[2]) ||
  183600. (user_png_ver[0] == '0' && user_png_ver[2] < '9'))
  183601. {
  183602. #if !defined(PNG_NO_STDIO) && !defined(_WIN32_WCE)
  183603. char msg[80];
  183604. if (user_png_ver)
  183605. {
  183606. png_snprintf(msg, 80,
  183607. "Application was compiled with png.h from libpng-%.20s",
  183608. user_png_ver);
  183609. png_warning(png_ptr, msg);
  183610. }
  183611. png_snprintf(msg, 80,
  183612. "Application is running with png.c from libpng-%.20s",
  183613. png_libpng_ver);
  183614. png_warning(png_ptr, msg);
  183615. #endif
  183616. #ifdef PNG_ERROR_NUMBERS_SUPPORTED
  183617. png_ptr->flags=0;
  183618. #endif
  183619. png_error(png_ptr,
  183620. "Incompatible libpng version in application and library");
  183621. }
  183622. }
  183623. /* initialize zbuf - compression buffer */
  183624. png_ptr->zbuf_size = PNG_ZBUF_SIZE;
  183625. png_ptr->zbuf = (png_bytep)png_malloc(png_ptr,
  183626. (png_uint_32)png_ptr->zbuf_size);
  183627. png_ptr->zstream.zalloc = png_zalloc;
  183628. png_ptr->zstream.zfree = png_zfree;
  183629. png_ptr->zstream.opaque = (voidpf)png_ptr;
  183630. switch (inflateInit(&png_ptr->zstream))
  183631. {
  183632. case Z_OK: /* Do nothing */ break;
  183633. case Z_MEM_ERROR:
  183634. case Z_STREAM_ERROR: png_error(png_ptr, "zlib memory error"); break;
  183635. case Z_VERSION_ERROR: png_error(png_ptr, "zlib version error"); break;
  183636. default: png_error(png_ptr, "Unknown zlib error");
  183637. }
  183638. png_ptr->zstream.next_out = png_ptr->zbuf;
  183639. png_ptr->zstream.avail_out = (uInt)png_ptr->zbuf_size;
  183640. png_set_read_fn(png_ptr, png_voidp_NULL, png_rw_ptr_NULL);
  183641. #ifdef PNG_SETJMP_SUPPORTED
  183642. /* Applications that neglect to set up their own setjmp() and then encounter
  183643. a png_error() will longjmp here. Since the jmpbuf is then meaningless we
  183644. abort instead of returning. */
  183645. #ifdef USE_FAR_KEYWORD
  183646. if (setjmp(jmpbuf))
  183647. PNG_ABORT();
  183648. png_memcpy(png_ptr->jmpbuf,jmpbuf,png_sizeof(jmp_buf));
  183649. #else
  183650. if (setjmp(png_ptr->jmpbuf))
  183651. PNG_ABORT();
  183652. #endif
  183653. #endif
  183654. return (png_ptr);
  183655. }
  183656. #if defined(PNG_1_0_X) || defined(PNG_1_2_X)
  183657. /* Initialize PNG structure for reading, and allocate any memory needed.
  183658. This interface is deprecated in favour of the png_create_read_struct(),
  183659. and it will disappear as of libpng-1.3.0. */
  183660. #undef png_read_init
  183661. void PNGAPI
  183662. png_read_init(png_structp png_ptr)
  183663. {
  183664. /* We only come here via pre-1.0.7-compiled applications */
  183665. png_read_init_2(png_ptr, "1.0.6 or earlier", 0, 0);
  183666. }
  183667. void PNGAPI
  183668. png_read_init_2(png_structp png_ptr, png_const_charp user_png_ver,
  183669. png_size_t png_struct_size, png_size_t png_info_size)
  183670. {
  183671. /* We only come here via pre-1.0.12-compiled applications */
  183672. if(png_ptr == NULL) return;
  183673. #if !defined(PNG_NO_STDIO) && !defined(_WIN32_WCE)
  183674. if(png_sizeof(png_struct) > png_struct_size ||
  183675. png_sizeof(png_info) > png_info_size)
  183676. {
  183677. char msg[80];
  183678. png_ptr->warning_fn=NULL;
  183679. if (user_png_ver)
  183680. {
  183681. png_snprintf(msg, 80,
  183682. "Application was compiled with png.h from libpng-%.20s",
  183683. user_png_ver);
  183684. png_warning(png_ptr, msg);
  183685. }
  183686. png_snprintf(msg, 80,
  183687. "Application is running with png.c from libpng-%.20s",
  183688. png_libpng_ver);
  183689. png_warning(png_ptr, msg);
  183690. }
  183691. #endif
  183692. if(png_sizeof(png_struct) > png_struct_size)
  183693. {
  183694. png_ptr->error_fn=NULL;
  183695. #ifdef PNG_ERROR_NUMBERS_SUPPORTED
  183696. png_ptr->flags=0;
  183697. #endif
  183698. png_error(png_ptr,
  183699. "The png struct allocated by the application for reading is too small.");
  183700. }
  183701. if(png_sizeof(png_info) > png_info_size)
  183702. {
  183703. png_ptr->error_fn=NULL;
  183704. #ifdef PNG_ERROR_NUMBERS_SUPPORTED
  183705. png_ptr->flags=0;
  183706. #endif
  183707. png_error(png_ptr,
  183708. "The info struct allocated by application for reading is too small.");
  183709. }
  183710. png_read_init_3(&png_ptr, user_png_ver, png_struct_size);
  183711. }
  183712. #endif /* PNG_1_0_X || PNG_1_2_X */
  183713. void PNGAPI
  183714. png_read_init_3(png_structpp ptr_ptr, png_const_charp user_png_ver,
  183715. png_size_t png_struct_size)
  183716. {
  183717. #ifdef PNG_SETJMP_SUPPORTED
  183718. jmp_buf tmp_jmp; /* to save current jump buffer */
  183719. #endif
  183720. int i=0;
  183721. png_structp png_ptr=*ptr_ptr;
  183722. if(png_ptr == NULL) return;
  183723. do
  183724. {
  183725. if(user_png_ver[i] != png_libpng_ver[i])
  183726. {
  183727. #ifdef PNG_LEGACY_SUPPORTED
  183728. png_ptr->flags |= PNG_FLAG_LIBRARY_MISMATCH;
  183729. #else
  183730. png_ptr->warning_fn=NULL;
  183731. png_warning(png_ptr,
  183732. "Application uses deprecated png_read_init() and should be recompiled.");
  183733. break;
  183734. #endif
  183735. }
  183736. } while (png_libpng_ver[i++]);
  183737. png_debug(1, "in png_read_init_3\n");
  183738. #ifdef PNG_SETJMP_SUPPORTED
  183739. /* save jump buffer and error functions */
  183740. png_memcpy(tmp_jmp, png_ptr->jmpbuf, png_sizeof (jmp_buf));
  183741. #endif
  183742. if(png_sizeof(png_struct) > png_struct_size)
  183743. {
  183744. png_destroy_struct(png_ptr);
  183745. *ptr_ptr = (png_structp)png_create_struct(PNG_STRUCT_PNG);
  183746. png_ptr = *ptr_ptr;
  183747. }
  183748. /* reset all variables to 0 */
  183749. png_memset(png_ptr, 0, png_sizeof (png_struct));
  183750. #ifdef PNG_SETJMP_SUPPORTED
  183751. /* restore jump buffer */
  183752. png_memcpy(png_ptr->jmpbuf, tmp_jmp, png_sizeof (jmp_buf));
  183753. #endif
  183754. /* added at libpng-1.2.6 */
  183755. #ifdef PNG_SET_USER_LIMITS_SUPPORTED
  183756. png_ptr->user_width_max=PNG_USER_WIDTH_MAX;
  183757. png_ptr->user_height_max=PNG_USER_HEIGHT_MAX;
  183758. #endif
  183759. /* initialize zbuf - compression buffer */
  183760. png_ptr->zbuf_size = PNG_ZBUF_SIZE;
  183761. png_ptr->zbuf = (png_bytep)png_malloc(png_ptr,
  183762. (png_uint_32)png_ptr->zbuf_size);
  183763. png_ptr->zstream.zalloc = png_zalloc;
  183764. png_ptr->zstream.zfree = png_zfree;
  183765. png_ptr->zstream.opaque = (voidpf)png_ptr;
  183766. switch (inflateInit(&png_ptr->zstream))
  183767. {
  183768. case Z_OK: /* Do nothing */ break;
  183769. case Z_MEM_ERROR:
  183770. case Z_STREAM_ERROR: png_error(png_ptr, "zlib memory"); break;
  183771. case Z_VERSION_ERROR: png_error(png_ptr, "zlib version"); break;
  183772. default: png_error(png_ptr, "Unknown zlib error");
  183773. }
  183774. png_ptr->zstream.next_out = png_ptr->zbuf;
  183775. png_ptr->zstream.avail_out = (uInt)png_ptr->zbuf_size;
  183776. png_set_read_fn(png_ptr, png_voidp_NULL, png_rw_ptr_NULL);
  183777. }
  183778. #ifndef PNG_NO_SEQUENTIAL_READ_SUPPORTED
  183779. /* Read the information before the actual image data. This has been
  183780. * changed in v0.90 to allow reading a file that already has the magic
  183781. * bytes read from the stream. You can tell libpng how many bytes have
  183782. * been read from the beginning of the stream (up to the maximum of 8)
  183783. * via png_set_sig_bytes(), and we will only check the remaining bytes
  183784. * here. The application can then have access to the signature bytes we
  183785. * read if it is determined that this isn't a valid PNG file.
  183786. */
  183787. void PNGAPI
  183788. png_read_info(png_structp png_ptr, png_infop info_ptr)
  183789. {
  183790. if(png_ptr == NULL) return;
  183791. png_debug(1, "in png_read_info\n");
  183792. /* If we haven't checked all of the PNG signature bytes, do so now. */
  183793. if (png_ptr->sig_bytes < 8)
  183794. {
  183795. png_size_t num_checked = png_ptr->sig_bytes,
  183796. num_to_check = 8 - num_checked;
  183797. png_read_data(png_ptr, &(info_ptr->signature[num_checked]), num_to_check);
  183798. png_ptr->sig_bytes = 8;
  183799. if (png_sig_cmp(info_ptr->signature, num_checked, num_to_check))
  183800. {
  183801. if (num_checked < 4 &&
  183802. png_sig_cmp(info_ptr->signature, num_checked, num_to_check - 4))
  183803. png_error(png_ptr, "Not a PNG file");
  183804. else
  183805. png_error(png_ptr, "PNG file corrupted by ASCII conversion");
  183806. }
  183807. if (num_checked < 3)
  183808. png_ptr->mode |= PNG_HAVE_PNG_SIGNATURE;
  183809. }
  183810. for(;;)
  183811. {
  183812. #ifdef PNG_USE_LOCAL_ARRAYS
  183813. PNG_CONST PNG_IHDR;
  183814. PNG_CONST PNG_IDAT;
  183815. PNG_CONST PNG_IEND;
  183816. PNG_CONST PNG_PLTE;
  183817. #if defined(PNG_READ_bKGD_SUPPORTED)
  183818. PNG_CONST PNG_bKGD;
  183819. #endif
  183820. #if defined(PNG_READ_cHRM_SUPPORTED)
  183821. PNG_CONST PNG_cHRM;
  183822. #endif
  183823. #if defined(PNG_READ_gAMA_SUPPORTED)
  183824. PNG_CONST PNG_gAMA;
  183825. #endif
  183826. #if defined(PNG_READ_hIST_SUPPORTED)
  183827. PNG_CONST PNG_hIST;
  183828. #endif
  183829. #if defined(PNG_READ_iCCP_SUPPORTED)
  183830. PNG_CONST PNG_iCCP;
  183831. #endif
  183832. #if defined(PNG_READ_iTXt_SUPPORTED)
  183833. PNG_CONST PNG_iTXt;
  183834. #endif
  183835. #if defined(PNG_READ_oFFs_SUPPORTED)
  183836. PNG_CONST PNG_oFFs;
  183837. #endif
  183838. #if defined(PNG_READ_pCAL_SUPPORTED)
  183839. PNG_CONST PNG_pCAL;
  183840. #endif
  183841. #if defined(PNG_READ_pHYs_SUPPORTED)
  183842. PNG_CONST PNG_pHYs;
  183843. #endif
  183844. #if defined(PNG_READ_sBIT_SUPPORTED)
  183845. PNG_CONST PNG_sBIT;
  183846. #endif
  183847. #if defined(PNG_READ_sCAL_SUPPORTED)
  183848. PNG_CONST PNG_sCAL;
  183849. #endif
  183850. #if defined(PNG_READ_sPLT_SUPPORTED)
  183851. PNG_CONST PNG_sPLT;
  183852. #endif
  183853. #if defined(PNG_READ_sRGB_SUPPORTED)
  183854. PNG_CONST PNG_sRGB;
  183855. #endif
  183856. #if defined(PNG_READ_tEXt_SUPPORTED)
  183857. PNG_CONST PNG_tEXt;
  183858. #endif
  183859. #if defined(PNG_READ_tIME_SUPPORTED)
  183860. PNG_CONST PNG_tIME;
  183861. #endif
  183862. #if defined(PNG_READ_tRNS_SUPPORTED)
  183863. PNG_CONST PNG_tRNS;
  183864. #endif
  183865. #if defined(PNG_READ_zTXt_SUPPORTED)
  183866. PNG_CONST PNG_zTXt;
  183867. #endif
  183868. #endif /* PNG_USE_LOCAL_ARRAYS */
  183869. png_byte chunk_length[4];
  183870. png_uint_32 length;
  183871. png_read_data(png_ptr, chunk_length, 4);
  183872. length = png_get_uint_31(png_ptr,chunk_length);
  183873. png_reset_crc(png_ptr);
  183874. png_crc_read(png_ptr, png_ptr->chunk_name, 4);
  183875. png_debug2(0, "Reading %s chunk, length=%lu.\n", png_ptr->chunk_name,
  183876. length);
  183877. /* This should be a binary subdivision search or a hash for
  183878. * matching the chunk name rather than a linear search.
  183879. */
  183880. if (!png_memcmp(png_ptr->chunk_name, png_IDAT, 4))
  183881. if(png_ptr->mode & PNG_AFTER_IDAT)
  183882. png_ptr->mode |= PNG_HAVE_CHUNK_AFTER_IDAT;
  183883. if (!png_memcmp(png_ptr->chunk_name, png_IHDR, 4))
  183884. png_handle_IHDR(png_ptr, info_ptr, length);
  183885. else if (!png_memcmp(png_ptr->chunk_name, png_IEND, 4))
  183886. png_handle_IEND(png_ptr, info_ptr, length);
  183887. #ifdef PNG_HANDLE_AS_UNKNOWN_SUPPORTED
  183888. else if (png_handle_as_unknown(png_ptr, png_ptr->chunk_name))
  183889. {
  183890. if (!png_memcmp(png_ptr->chunk_name, png_IDAT, 4))
  183891. png_ptr->mode |= PNG_HAVE_IDAT;
  183892. png_handle_unknown(png_ptr, info_ptr, length);
  183893. if (!png_memcmp(png_ptr->chunk_name, png_PLTE, 4))
  183894. png_ptr->mode |= PNG_HAVE_PLTE;
  183895. else if (!png_memcmp(png_ptr->chunk_name, png_IDAT, 4))
  183896. {
  183897. if (!(png_ptr->mode & PNG_HAVE_IHDR))
  183898. png_error(png_ptr, "Missing IHDR before IDAT");
  183899. else if (png_ptr->color_type == PNG_COLOR_TYPE_PALETTE &&
  183900. !(png_ptr->mode & PNG_HAVE_PLTE))
  183901. png_error(png_ptr, "Missing PLTE before IDAT");
  183902. break;
  183903. }
  183904. }
  183905. #endif
  183906. else if (!png_memcmp(png_ptr->chunk_name, png_PLTE, 4))
  183907. png_handle_PLTE(png_ptr, info_ptr, length);
  183908. else if (!png_memcmp(png_ptr->chunk_name, png_IDAT, 4))
  183909. {
  183910. if (!(png_ptr->mode & PNG_HAVE_IHDR))
  183911. png_error(png_ptr, "Missing IHDR before IDAT");
  183912. else if (png_ptr->color_type == PNG_COLOR_TYPE_PALETTE &&
  183913. !(png_ptr->mode & PNG_HAVE_PLTE))
  183914. png_error(png_ptr, "Missing PLTE before IDAT");
  183915. png_ptr->idat_size = length;
  183916. png_ptr->mode |= PNG_HAVE_IDAT;
  183917. break;
  183918. }
  183919. #if defined(PNG_READ_bKGD_SUPPORTED)
  183920. else if (!png_memcmp(png_ptr->chunk_name, png_bKGD, 4))
  183921. png_handle_bKGD(png_ptr, info_ptr, length);
  183922. #endif
  183923. #if defined(PNG_READ_cHRM_SUPPORTED)
  183924. else if (!png_memcmp(png_ptr->chunk_name, png_cHRM, 4))
  183925. png_handle_cHRM(png_ptr, info_ptr, length);
  183926. #endif
  183927. #if defined(PNG_READ_gAMA_SUPPORTED)
  183928. else if (!png_memcmp(png_ptr->chunk_name, png_gAMA, 4))
  183929. png_handle_gAMA(png_ptr, info_ptr, length);
  183930. #endif
  183931. #if defined(PNG_READ_hIST_SUPPORTED)
  183932. else if (!png_memcmp(png_ptr->chunk_name, png_hIST, 4))
  183933. png_handle_hIST(png_ptr, info_ptr, length);
  183934. #endif
  183935. #if defined(PNG_READ_oFFs_SUPPORTED)
  183936. else if (!png_memcmp(png_ptr->chunk_name, png_oFFs, 4))
  183937. png_handle_oFFs(png_ptr, info_ptr, length);
  183938. #endif
  183939. #if defined(PNG_READ_pCAL_SUPPORTED)
  183940. else if (!png_memcmp(png_ptr->chunk_name, png_pCAL, 4))
  183941. png_handle_pCAL(png_ptr, info_ptr, length);
  183942. #endif
  183943. #if defined(PNG_READ_sCAL_SUPPORTED)
  183944. else if (!png_memcmp(png_ptr->chunk_name, png_sCAL, 4))
  183945. png_handle_sCAL(png_ptr, info_ptr, length);
  183946. #endif
  183947. #if defined(PNG_READ_pHYs_SUPPORTED)
  183948. else if (!png_memcmp(png_ptr->chunk_name, png_pHYs, 4))
  183949. png_handle_pHYs(png_ptr, info_ptr, length);
  183950. #endif
  183951. #if defined(PNG_READ_sBIT_SUPPORTED)
  183952. else if (!png_memcmp(png_ptr->chunk_name, png_sBIT, 4))
  183953. png_handle_sBIT(png_ptr, info_ptr, length);
  183954. #endif
  183955. #if defined(PNG_READ_sRGB_SUPPORTED)
  183956. else if (!png_memcmp(png_ptr->chunk_name, png_sRGB, 4))
  183957. png_handle_sRGB(png_ptr, info_ptr, length);
  183958. #endif
  183959. #if defined(PNG_READ_iCCP_SUPPORTED)
  183960. else if (!png_memcmp(png_ptr->chunk_name, png_iCCP, 4))
  183961. png_handle_iCCP(png_ptr, info_ptr, length);
  183962. #endif
  183963. #if defined(PNG_READ_sPLT_SUPPORTED)
  183964. else if (!png_memcmp(png_ptr->chunk_name, png_sPLT, 4))
  183965. png_handle_sPLT(png_ptr, info_ptr, length);
  183966. #endif
  183967. #if defined(PNG_READ_tEXt_SUPPORTED)
  183968. else if (!png_memcmp(png_ptr->chunk_name, png_tEXt, 4))
  183969. png_handle_tEXt(png_ptr, info_ptr, length);
  183970. #endif
  183971. #if defined(PNG_READ_tIME_SUPPORTED)
  183972. else if (!png_memcmp(png_ptr->chunk_name, png_tIME, 4))
  183973. png_handle_tIME(png_ptr, info_ptr, length);
  183974. #endif
  183975. #if defined(PNG_READ_tRNS_SUPPORTED)
  183976. else if (!png_memcmp(png_ptr->chunk_name, png_tRNS, 4))
  183977. png_handle_tRNS(png_ptr, info_ptr, length);
  183978. #endif
  183979. #if defined(PNG_READ_zTXt_SUPPORTED)
  183980. else if (!png_memcmp(png_ptr->chunk_name, png_zTXt, 4))
  183981. png_handle_zTXt(png_ptr, info_ptr, length);
  183982. #endif
  183983. #if defined(PNG_READ_iTXt_SUPPORTED)
  183984. else if (!png_memcmp(png_ptr->chunk_name, png_iTXt, 4))
  183985. png_handle_iTXt(png_ptr, info_ptr, length);
  183986. #endif
  183987. else
  183988. png_handle_unknown(png_ptr, info_ptr, length);
  183989. }
  183990. }
  183991. #endif /* PNG_NO_SEQUENTIAL_READ_SUPPORTED */
  183992. /* optional call to update the users info_ptr structure */
  183993. void PNGAPI
  183994. png_read_update_info(png_structp png_ptr, png_infop info_ptr)
  183995. {
  183996. png_debug(1, "in png_read_update_info\n");
  183997. if(png_ptr == NULL) return;
  183998. if (!(png_ptr->flags & PNG_FLAG_ROW_INIT))
  183999. png_read_start_row(png_ptr);
  184000. else
  184001. png_warning(png_ptr,
  184002. "Ignoring extra png_read_update_info() call; row buffer not reallocated");
  184003. png_read_transform_info(png_ptr, info_ptr);
  184004. }
  184005. #ifndef PNG_NO_SEQUENTIAL_READ_SUPPORTED
  184006. /* Initialize palette, background, etc, after transformations
  184007. * are set, but before any reading takes place. This allows
  184008. * the user to obtain a gamma-corrected palette, for example.
  184009. * If the user doesn't call this, we will do it ourselves.
  184010. */
  184011. void PNGAPI
  184012. png_start_read_image(png_structp png_ptr)
  184013. {
  184014. png_debug(1, "in png_start_read_image\n");
  184015. if(png_ptr == NULL) return;
  184016. if (!(png_ptr->flags & PNG_FLAG_ROW_INIT))
  184017. png_read_start_row(png_ptr);
  184018. }
  184019. #endif /* PNG_NO_SEQUENTIAL_READ_SUPPORTED */
  184020. #ifndef PNG_NO_SEQUENTIAL_READ_SUPPORTED
  184021. void PNGAPI
  184022. png_read_row(png_structp png_ptr, png_bytep row, png_bytep dsp_row)
  184023. {
  184024. #ifdef PNG_USE_LOCAL_ARRAYS
  184025. PNG_CONST PNG_IDAT;
  184026. PNG_CONST int png_pass_dsp_mask[7] = {0xff, 0x0f, 0xff, 0x33, 0xff, 0x55,
  184027. 0xff};
  184028. PNG_CONST int png_pass_mask[7] = {0x80, 0x08, 0x88, 0x22, 0xaa, 0x55, 0xff};
  184029. #endif
  184030. int ret;
  184031. if(png_ptr == NULL) return;
  184032. png_debug2(1, "in png_read_row (row %lu, pass %d)\n",
  184033. png_ptr->row_number, png_ptr->pass);
  184034. if (!(png_ptr->flags & PNG_FLAG_ROW_INIT))
  184035. png_read_start_row(png_ptr);
  184036. if (png_ptr->row_number == 0 && png_ptr->pass == 0)
  184037. {
  184038. /* check for transforms that have been set but were defined out */
  184039. #if defined(PNG_WRITE_INVERT_SUPPORTED) && !defined(PNG_READ_INVERT_SUPPORTED)
  184040. if (png_ptr->transformations & PNG_INVERT_MONO)
  184041. png_warning(png_ptr, "PNG_READ_INVERT_SUPPORTED is not defined.");
  184042. #endif
  184043. #if defined(PNG_WRITE_FILLER_SUPPORTED) && !defined(PNG_READ_FILLER_SUPPORTED)
  184044. if (png_ptr->transformations & PNG_FILLER)
  184045. png_warning(png_ptr, "PNG_READ_FILLER_SUPPORTED is not defined.");
  184046. #endif
  184047. #if defined(PNG_WRITE_PACKSWAP_SUPPORTED) && !defined(PNG_READ_PACKSWAP_SUPPORTED)
  184048. if (png_ptr->transformations & PNG_PACKSWAP)
  184049. png_warning(png_ptr, "PNG_READ_PACKSWAP_SUPPORTED is not defined.");
  184050. #endif
  184051. #if defined(PNG_WRITE_PACK_SUPPORTED) && !defined(PNG_READ_PACK_SUPPORTED)
  184052. if (png_ptr->transformations & PNG_PACK)
  184053. png_warning(png_ptr, "PNG_READ_PACK_SUPPORTED is not defined.");
  184054. #endif
  184055. #if defined(PNG_WRITE_SHIFT_SUPPORTED) && !defined(PNG_READ_SHIFT_SUPPORTED)
  184056. if (png_ptr->transformations & PNG_SHIFT)
  184057. png_warning(png_ptr, "PNG_READ_SHIFT_SUPPORTED is not defined.");
  184058. #endif
  184059. #if defined(PNG_WRITE_BGR_SUPPORTED) && !defined(PNG_READ_BGR_SUPPORTED)
  184060. if (png_ptr->transformations & PNG_BGR)
  184061. png_warning(png_ptr, "PNG_READ_BGR_SUPPORTED is not defined.");
  184062. #endif
  184063. #if defined(PNG_WRITE_SWAP_SUPPORTED) && !defined(PNG_READ_SWAP_SUPPORTED)
  184064. if (png_ptr->transformations & PNG_SWAP_BYTES)
  184065. png_warning(png_ptr, "PNG_READ_SWAP_SUPPORTED is not defined.");
  184066. #endif
  184067. }
  184068. #if defined(PNG_READ_INTERLACING_SUPPORTED)
  184069. /* if interlaced and we do not need a new row, combine row and return */
  184070. if (png_ptr->interlaced && (png_ptr->transformations & PNG_INTERLACE))
  184071. {
  184072. switch (png_ptr->pass)
  184073. {
  184074. case 0:
  184075. if (png_ptr->row_number & 0x07)
  184076. {
  184077. if (dsp_row != NULL)
  184078. png_combine_row(png_ptr, dsp_row,
  184079. png_pass_dsp_mask[png_ptr->pass]);
  184080. png_read_finish_row(png_ptr);
  184081. return;
  184082. }
  184083. break;
  184084. case 1:
  184085. if ((png_ptr->row_number & 0x07) || png_ptr->width < 5)
  184086. {
  184087. if (dsp_row != NULL)
  184088. png_combine_row(png_ptr, dsp_row,
  184089. png_pass_dsp_mask[png_ptr->pass]);
  184090. png_read_finish_row(png_ptr);
  184091. return;
  184092. }
  184093. break;
  184094. case 2:
  184095. if ((png_ptr->row_number & 0x07) != 4)
  184096. {
  184097. if (dsp_row != NULL && (png_ptr->row_number & 4))
  184098. png_combine_row(png_ptr, dsp_row,
  184099. png_pass_dsp_mask[png_ptr->pass]);
  184100. png_read_finish_row(png_ptr);
  184101. return;
  184102. }
  184103. break;
  184104. case 3:
  184105. if ((png_ptr->row_number & 3) || png_ptr->width < 3)
  184106. {
  184107. if (dsp_row != NULL)
  184108. png_combine_row(png_ptr, dsp_row,
  184109. png_pass_dsp_mask[png_ptr->pass]);
  184110. png_read_finish_row(png_ptr);
  184111. return;
  184112. }
  184113. break;
  184114. case 4:
  184115. if ((png_ptr->row_number & 3) != 2)
  184116. {
  184117. if (dsp_row != NULL && (png_ptr->row_number & 2))
  184118. png_combine_row(png_ptr, dsp_row,
  184119. png_pass_dsp_mask[png_ptr->pass]);
  184120. png_read_finish_row(png_ptr);
  184121. return;
  184122. }
  184123. break;
  184124. case 5:
  184125. if ((png_ptr->row_number & 1) || png_ptr->width < 2)
  184126. {
  184127. if (dsp_row != NULL)
  184128. png_combine_row(png_ptr, dsp_row,
  184129. png_pass_dsp_mask[png_ptr->pass]);
  184130. png_read_finish_row(png_ptr);
  184131. return;
  184132. }
  184133. break;
  184134. case 6:
  184135. if (!(png_ptr->row_number & 1))
  184136. {
  184137. png_read_finish_row(png_ptr);
  184138. return;
  184139. }
  184140. break;
  184141. }
  184142. }
  184143. #endif
  184144. if (!(png_ptr->mode & PNG_HAVE_IDAT))
  184145. png_error(png_ptr, "Invalid attempt to read row data");
  184146. png_ptr->zstream.next_out = png_ptr->row_buf;
  184147. png_ptr->zstream.avail_out = (uInt)png_ptr->irowbytes;
  184148. do
  184149. {
  184150. if (!(png_ptr->zstream.avail_in))
  184151. {
  184152. while (!png_ptr->idat_size)
  184153. {
  184154. png_byte chunk_length[4];
  184155. png_crc_finish(png_ptr, 0);
  184156. png_read_data(png_ptr, chunk_length, 4);
  184157. png_ptr->idat_size = png_get_uint_31(png_ptr,chunk_length);
  184158. png_reset_crc(png_ptr);
  184159. png_crc_read(png_ptr, png_ptr->chunk_name, 4);
  184160. if (png_memcmp(png_ptr->chunk_name, png_IDAT, 4))
  184161. png_error(png_ptr, "Not enough image data");
  184162. }
  184163. png_ptr->zstream.avail_in = (uInt)png_ptr->zbuf_size;
  184164. png_ptr->zstream.next_in = png_ptr->zbuf;
  184165. if (png_ptr->zbuf_size > png_ptr->idat_size)
  184166. png_ptr->zstream.avail_in = (uInt)png_ptr->idat_size;
  184167. png_crc_read(png_ptr, png_ptr->zbuf,
  184168. (png_size_t)png_ptr->zstream.avail_in);
  184169. png_ptr->idat_size -= png_ptr->zstream.avail_in;
  184170. }
  184171. ret = inflate(&png_ptr->zstream, Z_PARTIAL_FLUSH);
  184172. if (ret == Z_STREAM_END)
  184173. {
  184174. if (png_ptr->zstream.avail_out || png_ptr->zstream.avail_in ||
  184175. png_ptr->idat_size)
  184176. png_error(png_ptr, "Extra compressed data");
  184177. png_ptr->mode |= PNG_AFTER_IDAT;
  184178. png_ptr->flags |= PNG_FLAG_ZLIB_FINISHED;
  184179. break;
  184180. }
  184181. if (ret != Z_OK)
  184182. png_error(png_ptr, png_ptr->zstream.msg ? png_ptr->zstream.msg :
  184183. "Decompression error");
  184184. } while (png_ptr->zstream.avail_out);
  184185. png_ptr->row_info.color_type = png_ptr->color_type;
  184186. png_ptr->row_info.width = png_ptr->iwidth;
  184187. png_ptr->row_info.channels = png_ptr->channels;
  184188. png_ptr->row_info.bit_depth = png_ptr->bit_depth;
  184189. png_ptr->row_info.pixel_depth = png_ptr->pixel_depth;
  184190. png_ptr->row_info.rowbytes = PNG_ROWBYTES(png_ptr->row_info.pixel_depth,
  184191. png_ptr->row_info.width);
  184192. if(png_ptr->row_buf[0])
  184193. png_read_filter_row(png_ptr, &(png_ptr->row_info),
  184194. png_ptr->row_buf + 1, png_ptr->prev_row + 1,
  184195. (int)(png_ptr->row_buf[0]));
  184196. png_memcpy_check(png_ptr, png_ptr->prev_row, png_ptr->row_buf,
  184197. png_ptr->rowbytes + 1);
  184198. #if defined(PNG_MNG_FEATURES_SUPPORTED)
  184199. if((png_ptr->mng_features_permitted & PNG_FLAG_MNG_FILTER_64) &&
  184200. (png_ptr->filter_type == PNG_INTRAPIXEL_DIFFERENCING))
  184201. {
  184202. /* Intrapixel differencing */
  184203. png_do_read_intrapixel(&(png_ptr->row_info), png_ptr->row_buf + 1);
  184204. }
  184205. #endif
  184206. if (png_ptr->transformations || (png_ptr->flags&PNG_FLAG_STRIP_ALPHA))
  184207. png_do_read_transformations(png_ptr);
  184208. #if defined(PNG_READ_INTERLACING_SUPPORTED)
  184209. /* blow up interlaced rows to full size */
  184210. if (png_ptr->interlaced &&
  184211. (png_ptr->transformations & PNG_INTERLACE))
  184212. {
  184213. if (png_ptr->pass < 6)
  184214. /* old interface (pre-1.0.9):
  184215. png_do_read_interlace(&(png_ptr->row_info),
  184216. png_ptr->row_buf + 1, png_ptr->pass, png_ptr->transformations);
  184217. */
  184218. png_do_read_interlace(png_ptr);
  184219. if (dsp_row != NULL)
  184220. png_combine_row(png_ptr, dsp_row,
  184221. png_pass_dsp_mask[png_ptr->pass]);
  184222. if (row != NULL)
  184223. png_combine_row(png_ptr, row,
  184224. png_pass_mask[png_ptr->pass]);
  184225. }
  184226. else
  184227. #endif
  184228. {
  184229. if (row != NULL)
  184230. png_combine_row(png_ptr, row, 0xff);
  184231. if (dsp_row != NULL)
  184232. png_combine_row(png_ptr, dsp_row, 0xff);
  184233. }
  184234. png_read_finish_row(png_ptr);
  184235. if (png_ptr->read_row_fn != NULL)
  184236. (*(png_ptr->read_row_fn))(png_ptr, png_ptr->row_number, png_ptr->pass);
  184237. }
  184238. #endif /* PNG_NO_SEQUENTIAL_READ_SUPPORTED */
  184239. #ifndef PNG_NO_SEQUENTIAL_READ_SUPPORTED
  184240. /* Read one or more rows of image data. If the image is interlaced,
  184241. * and png_set_interlace_handling() has been called, the rows need to
  184242. * contain the contents of the rows from the previous pass. If the
  184243. * image has alpha or transparency, and png_handle_alpha()[*] has been
  184244. * called, the rows contents must be initialized to the contents of the
  184245. * screen.
  184246. *
  184247. * "row" holds the actual image, and pixels are placed in it
  184248. * as they arrive. If the image is displayed after each pass, it will
  184249. * appear to "sparkle" in. "display_row" can be used to display a
  184250. * "chunky" progressive image, with finer detail added as it becomes
  184251. * available. If you do not want this "chunky" display, you may pass
  184252. * NULL for display_row. If you do not want the sparkle display, and
  184253. * you have not called png_handle_alpha(), you may pass NULL for rows.
  184254. * If you have called png_handle_alpha(), and the image has either an
  184255. * alpha channel or a transparency chunk, you must provide a buffer for
  184256. * rows. In this case, you do not have to provide a display_row buffer
  184257. * also, but you may. If the image is not interlaced, or if you have
  184258. * not called png_set_interlace_handling(), the display_row buffer will
  184259. * be ignored, so pass NULL to it.
  184260. *
  184261. * [*] png_handle_alpha() does not exist yet, as of this version of libpng
  184262. */
  184263. void PNGAPI
  184264. png_read_rows(png_structp png_ptr, png_bytepp row,
  184265. png_bytepp display_row, png_uint_32 num_rows)
  184266. {
  184267. png_uint_32 i;
  184268. png_bytepp rp;
  184269. png_bytepp dp;
  184270. png_debug(1, "in png_read_rows\n");
  184271. if(png_ptr == NULL) return;
  184272. rp = row;
  184273. dp = display_row;
  184274. if (rp != NULL && dp != NULL)
  184275. for (i = 0; i < num_rows; i++)
  184276. {
  184277. png_bytep rptr = *rp++;
  184278. png_bytep dptr = *dp++;
  184279. png_read_row(png_ptr, rptr, dptr);
  184280. }
  184281. else if(rp != NULL)
  184282. for (i = 0; i < num_rows; i++)
  184283. {
  184284. png_bytep rptr = *rp;
  184285. png_read_row(png_ptr, rptr, png_bytep_NULL);
  184286. rp++;
  184287. }
  184288. else if(dp != NULL)
  184289. for (i = 0; i < num_rows; i++)
  184290. {
  184291. png_bytep dptr = *dp;
  184292. png_read_row(png_ptr, png_bytep_NULL, dptr);
  184293. dp++;
  184294. }
  184295. }
  184296. #endif /* PNG_NO_SEQUENTIAL_READ_SUPPORTED */
  184297. #ifndef PNG_NO_SEQUENTIAL_READ_SUPPORTED
  184298. /* Read the entire image. If the image has an alpha channel or a tRNS
  184299. * chunk, and you have called png_handle_alpha()[*], you will need to
  184300. * initialize the image to the current image that PNG will be overlaying.
  184301. * We set the num_rows again here, in case it was incorrectly set in
  184302. * png_read_start_row() by a call to png_read_update_info() or
  184303. * png_start_read_image() if png_set_interlace_handling() wasn't called
  184304. * prior to either of these functions like it should have been. You can
  184305. * only call this function once. If you desire to have an image for
  184306. * each pass of a interlaced image, use png_read_rows() instead.
  184307. *
  184308. * [*] png_handle_alpha() does not exist yet, as of this version of libpng
  184309. */
  184310. void PNGAPI
  184311. png_read_image(png_structp png_ptr, png_bytepp image)
  184312. {
  184313. png_uint_32 i,image_height;
  184314. int pass, j;
  184315. png_bytepp rp;
  184316. png_debug(1, "in png_read_image\n");
  184317. if(png_ptr == NULL) return;
  184318. #ifdef PNG_READ_INTERLACING_SUPPORTED
  184319. pass = png_set_interlace_handling(png_ptr);
  184320. #else
  184321. if (png_ptr->interlaced)
  184322. png_error(png_ptr,
  184323. "Cannot read interlaced image -- interlace handler disabled.");
  184324. pass = 1;
  184325. #endif
  184326. image_height=png_ptr->height;
  184327. png_ptr->num_rows = image_height; /* Make sure this is set correctly */
  184328. for (j = 0; j < pass; j++)
  184329. {
  184330. rp = image;
  184331. for (i = 0; i < image_height; i++)
  184332. {
  184333. png_read_row(png_ptr, *rp, png_bytep_NULL);
  184334. rp++;
  184335. }
  184336. }
  184337. }
  184338. #endif /* PNG_NO_SEQUENTIAL_READ_SUPPORTED */
  184339. #ifndef PNG_NO_SEQUENTIAL_READ_SUPPORTED
  184340. /* Read the end of the PNG file. Will not read past the end of the
  184341. * file, will verify the end is accurate, and will read any comments
  184342. * or time information at the end of the file, if info is not NULL.
  184343. */
  184344. void PNGAPI
  184345. png_read_end(png_structp png_ptr, png_infop info_ptr)
  184346. {
  184347. png_byte chunk_length[4];
  184348. png_uint_32 length;
  184349. png_debug(1, "in png_read_end\n");
  184350. if(png_ptr == NULL) return;
  184351. png_crc_finish(png_ptr, 0); /* Finish off CRC from last IDAT chunk */
  184352. do
  184353. {
  184354. #ifdef PNG_USE_LOCAL_ARRAYS
  184355. PNG_CONST PNG_IHDR;
  184356. PNG_CONST PNG_IDAT;
  184357. PNG_CONST PNG_IEND;
  184358. PNG_CONST PNG_PLTE;
  184359. #if defined(PNG_READ_bKGD_SUPPORTED)
  184360. PNG_CONST PNG_bKGD;
  184361. #endif
  184362. #if defined(PNG_READ_cHRM_SUPPORTED)
  184363. PNG_CONST PNG_cHRM;
  184364. #endif
  184365. #if defined(PNG_READ_gAMA_SUPPORTED)
  184366. PNG_CONST PNG_gAMA;
  184367. #endif
  184368. #if defined(PNG_READ_hIST_SUPPORTED)
  184369. PNG_CONST PNG_hIST;
  184370. #endif
  184371. #if defined(PNG_READ_iCCP_SUPPORTED)
  184372. PNG_CONST PNG_iCCP;
  184373. #endif
  184374. #if defined(PNG_READ_iTXt_SUPPORTED)
  184375. PNG_CONST PNG_iTXt;
  184376. #endif
  184377. #if defined(PNG_READ_oFFs_SUPPORTED)
  184378. PNG_CONST PNG_oFFs;
  184379. #endif
  184380. #if defined(PNG_READ_pCAL_SUPPORTED)
  184381. PNG_CONST PNG_pCAL;
  184382. #endif
  184383. #if defined(PNG_READ_pHYs_SUPPORTED)
  184384. PNG_CONST PNG_pHYs;
  184385. #endif
  184386. #if defined(PNG_READ_sBIT_SUPPORTED)
  184387. PNG_CONST PNG_sBIT;
  184388. #endif
  184389. #if defined(PNG_READ_sCAL_SUPPORTED)
  184390. PNG_CONST PNG_sCAL;
  184391. #endif
  184392. #if defined(PNG_READ_sPLT_SUPPORTED)
  184393. PNG_CONST PNG_sPLT;
  184394. #endif
  184395. #if defined(PNG_READ_sRGB_SUPPORTED)
  184396. PNG_CONST PNG_sRGB;
  184397. #endif
  184398. #if defined(PNG_READ_tEXt_SUPPORTED)
  184399. PNG_CONST PNG_tEXt;
  184400. #endif
  184401. #if defined(PNG_READ_tIME_SUPPORTED)
  184402. PNG_CONST PNG_tIME;
  184403. #endif
  184404. #if defined(PNG_READ_tRNS_SUPPORTED)
  184405. PNG_CONST PNG_tRNS;
  184406. #endif
  184407. #if defined(PNG_READ_zTXt_SUPPORTED)
  184408. PNG_CONST PNG_zTXt;
  184409. #endif
  184410. #endif /* PNG_USE_LOCAL_ARRAYS */
  184411. png_read_data(png_ptr, chunk_length, 4);
  184412. length = png_get_uint_31(png_ptr,chunk_length);
  184413. png_reset_crc(png_ptr);
  184414. png_crc_read(png_ptr, png_ptr->chunk_name, 4);
  184415. png_debug1(0, "Reading %s chunk.\n", png_ptr->chunk_name);
  184416. if (!png_memcmp(png_ptr->chunk_name, png_IHDR, 4))
  184417. png_handle_IHDR(png_ptr, info_ptr, length);
  184418. else if (!png_memcmp(png_ptr->chunk_name, png_IEND, 4))
  184419. png_handle_IEND(png_ptr, info_ptr, length);
  184420. #ifdef PNG_HANDLE_AS_UNKNOWN_SUPPORTED
  184421. else if (png_handle_as_unknown(png_ptr, png_ptr->chunk_name))
  184422. {
  184423. if (!png_memcmp(png_ptr->chunk_name, png_IDAT, 4))
  184424. {
  184425. if ((length > 0) || (png_ptr->mode & PNG_HAVE_CHUNK_AFTER_IDAT))
  184426. png_error(png_ptr, "Too many IDAT's found");
  184427. }
  184428. png_handle_unknown(png_ptr, info_ptr, length);
  184429. if (!png_memcmp(png_ptr->chunk_name, png_PLTE, 4))
  184430. png_ptr->mode |= PNG_HAVE_PLTE;
  184431. }
  184432. #endif
  184433. else if (!png_memcmp(png_ptr->chunk_name, png_IDAT, 4))
  184434. {
  184435. /* Zero length IDATs are legal after the last IDAT has been
  184436. * read, but not after other chunks have been read.
  184437. */
  184438. if ((length > 0) || (png_ptr->mode & PNG_HAVE_CHUNK_AFTER_IDAT))
  184439. png_error(png_ptr, "Too many IDAT's found");
  184440. png_crc_finish(png_ptr, length);
  184441. }
  184442. else if (!png_memcmp(png_ptr->chunk_name, png_PLTE, 4))
  184443. png_handle_PLTE(png_ptr, info_ptr, length);
  184444. #if defined(PNG_READ_bKGD_SUPPORTED)
  184445. else if (!png_memcmp(png_ptr->chunk_name, png_bKGD, 4))
  184446. png_handle_bKGD(png_ptr, info_ptr, length);
  184447. #endif
  184448. #if defined(PNG_READ_cHRM_SUPPORTED)
  184449. else if (!png_memcmp(png_ptr->chunk_name, png_cHRM, 4))
  184450. png_handle_cHRM(png_ptr, info_ptr, length);
  184451. #endif
  184452. #if defined(PNG_READ_gAMA_SUPPORTED)
  184453. else if (!png_memcmp(png_ptr->chunk_name, png_gAMA, 4))
  184454. png_handle_gAMA(png_ptr, info_ptr, length);
  184455. #endif
  184456. #if defined(PNG_READ_hIST_SUPPORTED)
  184457. else if (!png_memcmp(png_ptr->chunk_name, png_hIST, 4))
  184458. png_handle_hIST(png_ptr, info_ptr, length);
  184459. #endif
  184460. #if defined(PNG_READ_oFFs_SUPPORTED)
  184461. else if (!png_memcmp(png_ptr->chunk_name, png_oFFs, 4))
  184462. png_handle_oFFs(png_ptr, info_ptr, length);
  184463. #endif
  184464. #if defined(PNG_READ_pCAL_SUPPORTED)
  184465. else if (!png_memcmp(png_ptr->chunk_name, png_pCAL, 4))
  184466. png_handle_pCAL(png_ptr, info_ptr, length);
  184467. #endif
  184468. #if defined(PNG_READ_sCAL_SUPPORTED)
  184469. else if (!png_memcmp(png_ptr->chunk_name, png_sCAL, 4))
  184470. png_handle_sCAL(png_ptr, info_ptr, length);
  184471. #endif
  184472. #if defined(PNG_READ_pHYs_SUPPORTED)
  184473. else if (!png_memcmp(png_ptr->chunk_name, png_pHYs, 4))
  184474. png_handle_pHYs(png_ptr, info_ptr, length);
  184475. #endif
  184476. #if defined(PNG_READ_sBIT_SUPPORTED)
  184477. else if (!png_memcmp(png_ptr->chunk_name, png_sBIT, 4))
  184478. png_handle_sBIT(png_ptr, info_ptr, length);
  184479. #endif
  184480. #if defined(PNG_READ_sRGB_SUPPORTED)
  184481. else if (!png_memcmp(png_ptr->chunk_name, png_sRGB, 4))
  184482. png_handle_sRGB(png_ptr, info_ptr, length);
  184483. #endif
  184484. #if defined(PNG_READ_iCCP_SUPPORTED)
  184485. else if (!png_memcmp(png_ptr->chunk_name, png_iCCP, 4))
  184486. png_handle_iCCP(png_ptr, info_ptr, length);
  184487. #endif
  184488. #if defined(PNG_READ_sPLT_SUPPORTED)
  184489. else if (!png_memcmp(png_ptr->chunk_name, png_sPLT, 4))
  184490. png_handle_sPLT(png_ptr, info_ptr, length);
  184491. #endif
  184492. #if defined(PNG_READ_tEXt_SUPPORTED)
  184493. else if (!png_memcmp(png_ptr->chunk_name, png_tEXt, 4))
  184494. png_handle_tEXt(png_ptr, info_ptr, length);
  184495. #endif
  184496. #if defined(PNG_READ_tIME_SUPPORTED)
  184497. else if (!png_memcmp(png_ptr->chunk_name, png_tIME, 4))
  184498. png_handle_tIME(png_ptr, info_ptr, length);
  184499. #endif
  184500. #if defined(PNG_READ_tRNS_SUPPORTED)
  184501. else if (!png_memcmp(png_ptr->chunk_name, png_tRNS, 4))
  184502. png_handle_tRNS(png_ptr, info_ptr, length);
  184503. #endif
  184504. #if defined(PNG_READ_zTXt_SUPPORTED)
  184505. else if (!png_memcmp(png_ptr->chunk_name, png_zTXt, 4))
  184506. png_handle_zTXt(png_ptr, info_ptr, length);
  184507. #endif
  184508. #if defined(PNG_READ_iTXt_SUPPORTED)
  184509. else if (!png_memcmp(png_ptr->chunk_name, png_iTXt, 4))
  184510. png_handle_iTXt(png_ptr, info_ptr, length);
  184511. #endif
  184512. else
  184513. png_handle_unknown(png_ptr, info_ptr, length);
  184514. } while (!(png_ptr->mode & PNG_HAVE_IEND));
  184515. }
  184516. #endif /* PNG_NO_SEQUENTIAL_READ_SUPPORTED */
  184517. /* free all memory used by the read */
  184518. void PNGAPI
  184519. png_destroy_read_struct(png_structpp png_ptr_ptr, png_infopp info_ptr_ptr,
  184520. png_infopp end_info_ptr_ptr)
  184521. {
  184522. png_structp png_ptr = NULL;
  184523. png_infop info_ptr = NULL, end_info_ptr = NULL;
  184524. #ifdef PNG_USER_MEM_SUPPORTED
  184525. png_free_ptr free_fn;
  184526. png_voidp mem_ptr;
  184527. #endif
  184528. png_debug(1, "in png_destroy_read_struct\n");
  184529. if (png_ptr_ptr != NULL)
  184530. png_ptr = *png_ptr_ptr;
  184531. if (info_ptr_ptr != NULL)
  184532. info_ptr = *info_ptr_ptr;
  184533. if (end_info_ptr_ptr != NULL)
  184534. end_info_ptr = *end_info_ptr_ptr;
  184535. #ifdef PNG_USER_MEM_SUPPORTED
  184536. free_fn = png_ptr->free_fn;
  184537. mem_ptr = png_ptr->mem_ptr;
  184538. #endif
  184539. png_read_destroy(png_ptr, info_ptr, end_info_ptr);
  184540. if (info_ptr != NULL)
  184541. {
  184542. #if defined(PNG_TEXT_SUPPORTED)
  184543. png_free_data(png_ptr, info_ptr, PNG_FREE_TEXT, -1);
  184544. #endif
  184545. #ifdef PNG_USER_MEM_SUPPORTED
  184546. png_destroy_struct_2((png_voidp)info_ptr, (png_free_ptr)free_fn,
  184547. (png_voidp)mem_ptr);
  184548. #else
  184549. png_destroy_struct((png_voidp)info_ptr);
  184550. #endif
  184551. *info_ptr_ptr = NULL;
  184552. }
  184553. if (end_info_ptr != NULL)
  184554. {
  184555. #if defined(PNG_READ_TEXT_SUPPORTED)
  184556. png_free_data(png_ptr, end_info_ptr, PNG_FREE_TEXT, -1);
  184557. #endif
  184558. #ifdef PNG_USER_MEM_SUPPORTED
  184559. png_destroy_struct_2((png_voidp)end_info_ptr, (png_free_ptr)free_fn,
  184560. (png_voidp)mem_ptr);
  184561. #else
  184562. png_destroy_struct((png_voidp)end_info_ptr);
  184563. #endif
  184564. *end_info_ptr_ptr = NULL;
  184565. }
  184566. if (png_ptr != NULL)
  184567. {
  184568. #ifdef PNG_USER_MEM_SUPPORTED
  184569. png_destroy_struct_2((png_voidp)png_ptr, (png_free_ptr)free_fn,
  184570. (png_voidp)mem_ptr);
  184571. #else
  184572. png_destroy_struct((png_voidp)png_ptr);
  184573. #endif
  184574. *png_ptr_ptr = NULL;
  184575. }
  184576. }
  184577. /* free all memory used by the read (old method) */
  184578. void /* PRIVATE */
  184579. png_read_destroy(png_structp png_ptr, png_infop info_ptr, png_infop end_info_ptr)
  184580. {
  184581. #ifdef PNG_SETJMP_SUPPORTED
  184582. jmp_buf tmp_jmp;
  184583. #endif
  184584. png_error_ptr error_fn;
  184585. png_error_ptr warning_fn;
  184586. png_voidp error_ptr;
  184587. #ifdef PNG_USER_MEM_SUPPORTED
  184588. png_free_ptr free_fn;
  184589. #endif
  184590. png_debug(1, "in png_read_destroy\n");
  184591. if (info_ptr != NULL)
  184592. png_info_destroy(png_ptr, info_ptr);
  184593. if (end_info_ptr != NULL)
  184594. png_info_destroy(png_ptr, end_info_ptr);
  184595. png_free(png_ptr, png_ptr->zbuf);
  184596. png_free(png_ptr, png_ptr->big_row_buf);
  184597. png_free(png_ptr, png_ptr->prev_row);
  184598. #if defined(PNG_READ_DITHER_SUPPORTED)
  184599. png_free(png_ptr, png_ptr->palette_lookup);
  184600. png_free(png_ptr, png_ptr->dither_index);
  184601. #endif
  184602. #if defined(PNG_READ_GAMMA_SUPPORTED)
  184603. png_free(png_ptr, png_ptr->gamma_table);
  184604. #endif
  184605. #if defined(PNG_READ_BACKGROUND_SUPPORTED)
  184606. png_free(png_ptr, png_ptr->gamma_from_1);
  184607. png_free(png_ptr, png_ptr->gamma_to_1);
  184608. #endif
  184609. #ifdef PNG_FREE_ME_SUPPORTED
  184610. if (png_ptr->free_me & PNG_FREE_PLTE)
  184611. png_zfree(png_ptr, png_ptr->palette);
  184612. png_ptr->free_me &= ~PNG_FREE_PLTE;
  184613. #else
  184614. if (png_ptr->flags & PNG_FLAG_FREE_PLTE)
  184615. png_zfree(png_ptr, png_ptr->palette);
  184616. png_ptr->flags &= ~PNG_FLAG_FREE_PLTE;
  184617. #endif
  184618. #if defined(PNG_tRNS_SUPPORTED) || \
  184619. defined(PNG_READ_EXPAND_SUPPORTED) || defined(PNG_READ_BACKGROUND_SUPPORTED)
  184620. #ifdef PNG_FREE_ME_SUPPORTED
  184621. if (png_ptr->free_me & PNG_FREE_TRNS)
  184622. png_free(png_ptr, png_ptr->trans);
  184623. png_ptr->free_me &= ~PNG_FREE_TRNS;
  184624. #else
  184625. if (png_ptr->flags & PNG_FLAG_FREE_TRNS)
  184626. png_free(png_ptr, png_ptr->trans);
  184627. png_ptr->flags &= ~PNG_FLAG_FREE_TRNS;
  184628. #endif
  184629. #endif
  184630. #if defined(PNG_READ_hIST_SUPPORTED)
  184631. #ifdef PNG_FREE_ME_SUPPORTED
  184632. if (png_ptr->free_me & PNG_FREE_HIST)
  184633. png_free(png_ptr, png_ptr->hist);
  184634. png_ptr->free_me &= ~PNG_FREE_HIST;
  184635. #else
  184636. if (png_ptr->flags & PNG_FLAG_FREE_HIST)
  184637. png_free(png_ptr, png_ptr->hist);
  184638. png_ptr->flags &= ~PNG_FLAG_FREE_HIST;
  184639. #endif
  184640. #endif
  184641. #if defined(PNG_READ_GAMMA_SUPPORTED)
  184642. if (png_ptr->gamma_16_table != NULL)
  184643. {
  184644. int i;
  184645. int istop = (1 << (8 - png_ptr->gamma_shift));
  184646. for (i = 0; i < istop; i++)
  184647. {
  184648. png_free(png_ptr, png_ptr->gamma_16_table[i]);
  184649. }
  184650. png_free(png_ptr, png_ptr->gamma_16_table);
  184651. }
  184652. #if defined(PNG_READ_BACKGROUND_SUPPORTED)
  184653. if (png_ptr->gamma_16_from_1 != NULL)
  184654. {
  184655. int i;
  184656. int istop = (1 << (8 - png_ptr->gamma_shift));
  184657. for (i = 0; i < istop; i++)
  184658. {
  184659. png_free(png_ptr, png_ptr->gamma_16_from_1[i]);
  184660. }
  184661. png_free(png_ptr, png_ptr->gamma_16_from_1);
  184662. }
  184663. if (png_ptr->gamma_16_to_1 != NULL)
  184664. {
  184665. int i;
  184666. int istop = (1 << (8 - png_ptr->gamma_shift));
  184667. for (i = 0; i < istop; i++)
  184668. {
  184669. png_free(png_ptr, png_ptr->gamma_16_to_1[i]);
  184670. }
  184671. png_free(png_ptr, png_ptr->gamma_16_to_1);
  184672. }
  184673. #endif
  184674. #endif
  184675. #if defined(PNG_TIME_RFC1123_SUPPORTED)
  184676. png_free(png_ptr, png_ptr->time_buffer);
  184677. #endif
  184678. inflateEnd(&png_ptr->zstream);
  184679. #ifdef PNG_PROGRESSIVE_READ_SUPPORTED
  184680. png_free(png_ptr, png_ptr->save_buffer);
  184681. #endif
  184682. #ifdef PNG_PROGRESSIVE_READ_SUPPORTED
  184683. #ifdef PNG_TEXT_SUPPORTED
  184684. png_free(png_ptr, png_ptr->current_text);
  184685. #endif /* PNG_TEXT_SUPPORTED */
  184686. #endif /* PNG_PROGRESSIVE_READ_SUPPORTED */
  184687. /* Save the important info out of the png_struct, in case it is
  184688. * being used again.
  184689. */
  184690. #ifdef PNG_SETJMP_SUPPORTED
  184691. png_memcpy(tmp_jmp, png_ptr->jmpbuf, png_sizeof (jmp_buf));
  184692. #endif
  184693. error_fn = png_ptr->error_fn;
  184694. warning_fn = png_ptr->warning_fn;
  184695. error_ptr = png_ptr->error_ptr;
  184696. #ifdef PNG_USER_MEM_SUPPORTED
  184697. free_fn = png_ptr->free_fn;
  184698. #endif
  184699. png_memset(png_ptr, 0, png_sizeof (png_struct));
  184700. png_ptr->error_fn = error_fn;
  184701. png_ptr->warning_fn = warning_fn;
  184702. png_ptr->error_ptr = error_ptr;
  184703. #ifdef PNG_USER_MEM_SUPPORTED
  184704. png_ptr->free_fn = free_fn;
  184705. #endif
  184706. #ifdef PNG_SETJMP_SUPPORTED
  184707. png_memcpy(png_ptr->jmpbuf, tmp_jmp, png_sizeof (jmp_buf));
  184708. #endif
  184709. }
  184710. void PNGAPI
  184711. png_set_read_status_fn(png_structp png_ptr, png_read_status_ptr read_row_fn)
  184712. {
  184713. if(png_ptr == NULL) return;
  184714. png_ptr->read_row_fn = read_row_fn;
  184715. }
  184716. #ifndef PNG_NO_SEQUENTIAL_READ_SUPPORTED
  184717. #if defined(PNG_INFO_IMAGE_SUPPORTED)
  184718. void PNGAPI
  184719. png_read_png(png_structp png_ptr, png_infop info_ptr,
  184720. int transforms,
  184721. voidp params)
  184722. {
  184723. int row;
  184724. if(png_ptr == NULL) return;
  184725. #if defined(PNG_READ_INVERT_ALPHA_SUPPORTED)
  184726. /* invert the alpha channel from opacity to transparency
  184727. */
  184728. if (transforms & PNG_TRANSFORM_INVERT_ALPHA)
  184729. png_set_invert_alpha(png_ptr);
  184730. #endif
  184731. /* png_read_info() gives us all of the information from the
  184732. * PNG file before the first IDAT (image data chunk).
  184733. */
  184734. png_read_info(png_ptr, info_ptr);
  184735. if (info_ptr->height > PNG_UINT_32_MAX/png_sizeof(png_bytep))
  184736. png_error(png_ptr,"Image is too high to process with png_read_png()");
  184737. /* -------------- image transformations start here ------------------- */
  184738. #if defined(PNG_READ_16_TO_8_SUPPORTED)
  184739. /* tell libpng to strip 16 bit/color files down to 8 bits per color
  184740. */
  184741. if (transforms & PNG_TRANSFORM_STRIP_16)
  184742. png_set_strip_16(png_ptr);
  184743. #endif
  184744. #if defined(PNG_READ_STRIP_ALPHA_SUPPORTED)
  184745. /* Strip alpha bytes from the input data without combining with
  184746. * the background (not recommended).
  184747. */
  184748. if (transforms & PNG_TRANSFORM_STRIP_ALPHA)
  184749. png_set_strip_alpha(png_ptr);
  184750. #endif
  184751. #if defined(PNG_READ_PACK_SUPPORTED) && !defined(PNG_READ_EXPAND_SUPPORTED)
  184752. /* Extract multiple pixels with bit depths of 1, 2, or 4 from a single
  184753. * byte into separate bytes (useful for paletted and grayscale images).
  184754. */
  184755. if (transforms & PNG_TRANSFORM_PACKING)
  184756. png_set_packing(png_ptr);
  184757. #endif
  184758. #if defined(PNG_READ_PACKSWAP_SUPPORTED)
  184759. /* Change the order of packed pixels to least significant bit first
  184760. * (not useful if you are using png_set_packing).
  184761. */
  184762. if (transforms & PNG_TRANSFORM_PACKSWAP)
  184763. png_set_packswap(png_ptr);
  184764. #endif
  184765. #if defined(PNG_READ_EXPAND_SUPPORTED)
  184766. /* Expand paletted colors into true RGB triplets
  184767. * Expand grayscale images to full 8 bits from 1, 2, or 4 bits/pixel
  184768. * Expand paletted or RGB images with transparency to full alpha
  184769. * channels so the data will be available as RGBA quartets.
  184770. */
  184771. if (transforms & PNG_TRANSFORM_EXPAND)
  184772. if ((png_ptr->bit_depth < 8) ||
  184773. (png_ptr->color_type == PNG_COLOR_TYPE_PALETTE) ||
  184774. (png_get_valid(png_ptr, info_ptr, PNG_INFO_tRNS)))
  184775. png_set_expand(png_ptr);
  184776. #endif
  184777. /* We don't handle background color or gamma transformation or dithering.
  184778. */
  184779. #if defined(PNG_READ_INVERT_SUPPORTED)
  184780. /* invert monochrome files to have 0 as white and 1 as black
  184781. */
  184782. if (transforms & PNG_TRANSFORM_INVERT_MONO)
  184783. png_set_invert_mono(png_ptr);
  184784. #endif
  184785. #if defined(PNG_READ_SHIFT_SUPPORTED)
  184786. /* If you want to shift the pixel values from the range [0,255] or
  184787. * [0,65535] to the original [0,7] or [0,31], or whatever range the
  184788. * colors were originally in:
  184789. */
  184790. if ((transforms & PNG_TRANSFORM_SHIFT)
  184791. && png_get_valid(png_ptr, info_ptr, PNG_INFO_sBIT))
  184792. {
  184793. png_color_8p sig_bit;
  184794. png_get_sBIT(png_ptr, info_ptr, &sig_bit);
  184795. png_set_shift(png_ptr, sig_bit);
  184796. }
  184797. #endif
  184798. #if defined(PNG_READ_BGR_SUPPORTED)
  184799. /* flip the RGB pixels to BGR (or RGBA to BGRA)
  184800. */
  184801. if (transforms & PNG_TRANSFORM_BGR)
  184802. png_set_bgr(png_ptr);
  184803. #endif
  184804. #if defined(PNG_READ_SWAP_ALPHA_SUPPORTED)
  184805. /* swap the RGBA or GA data to ARGB or AG (or BGRA to ABGR)
  184806. */
  184807. if (transforms & PNG_TRANSFORM_SWAP_ALPHA)
  184808. png_set_swap_alpha(png_ptr);
  184809. #endif
  184810. #if defined(PNG_READ_SWAP_SUPPORTED)
  184811. /* swap bytes of 16 bit files to least significant byte first
  184812. */
  184813. if (transforms & PNG_TRANSFORM_SWAP_ENDIAN)
  184814. png_set_swap(png_ptr);
  184815. #endif
  184816. /* We don't handle adding filler bytes */
  184817. /* Optional call to gamma correct and add the background to the palette
  184818. * and update info structure. REQUIRED if you are expecting libpng to
  184819. * update the palette for you (i.e., you selected such a transform above).
  184820. */
  184821. png_read_update_info(png_ptr, info_ptr);
  184822. /* -------------- image transformations end here ------------------- */
  184823. #ifdef PNG_FREE_ME_SUPPORTED
  184824. png_free_data(png_ptr, info_ptr, PNG_FREE_ROWS, 0);
  184825. #endif
  184826. if(info_ptr->row_pointers == NULL)
  184827. {
  184828. info_ptr->row_pointers = (png_bytepp)png_malloc(png_ptr,
  184829. info_ptr->height * png_sizeof(png_bytep));
  184830. #ifdef PNG_FREE_ME_SUPPORTED
  184831. info_ptr->free_me |= PNG_FREE_ROWS;
  184832. #endif
  184833. for (row = 0; row < (int)info_ptr->height; row++)
  184834. {
  184835. info_ptr->row_pointers[row] = (png_bytep)png_malloc(png_ptr,
  184836. png_get_rowbytes(png_ptr, info_ptr));
  184837. }
  184838. }
  184839. png_read_image(png_ptr, info_ptr->row_pointers);
  184840. info_ptr->valid |= PNG_INFO_IDAT;
  184841. /* read rest of file, and get additional chunks in info_ptr - REQUIRED */
  184842. png_read_end(png_ptr, info_ptr);
  184843. transforms = transforms; /* quiet compiler warnings */
  184844. params = params;
  184845. }
  184846. #endif /* PNG_INFO_IMAGE_SUPPORTED */
  184847. #endif /* PNG_NO_SEQUENTIAL_READ_SUPPORTED */
  184848. #endif /* PNG_READ_SUPPORTED */
  184849. /*** End of inlined file: pngread.c ***/
  184850. /*** Start of inlined file: pngpread.c ***/
  184851. /* pngpread.c - read a png file in push mode
  184852. *
  184853. * Last changed in libpng 1.2.21 October 4, 2007
  184854. * For conditions of distribution and use, see copyright notice in png.h
  184855. * Copyright (c) 1998-2007 Glenn Randers-Pehrson
  184856. * (Version 0.96 Copyright (c) 1996, 1997 Andreas Dilger)
  184857. * (Version 0.88 Copyright (c) 1995, 1996 Guy Eric Schalnat, Group 42, Inc.)
  184858. */
  184859. #define PNG_INTERNAL
  184860. #ifdef PNG_PROGRESSIVE_READ_SUPPORTED
  184861. /* push model modes */
  184862. #define PNG_READ_SIG_MODE 0
  184863. #define PNG_READ_CHUNK_MODE 1
  184864. #define PNG_READ_IDAT_MODE 2
  184865. #define PNG_SKIP_MODE 3
  184866. #define PNG_READ_tEXt_MODE 4
  184867. #define PNG_READ_zTXt_MODE 5
  184868. #define PNG_READ_DONE_MODE 6
  184869. #define PNG_READ_iTXt_MODE 7
  184870. #define PNG_ERROR_MODE 8
  184871. void PNGAPI
  184872. png_process_data(png_structp png_ptr, png_infop info_ptr,
  184873. png_bytep buffer, png_size_t buffer_size)
  184874. {
  184875. if(png_ptr == NULL) return;
  184876. png_push_restore_buffer(png_ptr, buffer, buffer_size);
  184877. while (png_ptr->buffer_size)
  184878. {
  184879. png_process_some_data(png_ptr, info_ptr);
  184880. }
  184881. }
  184882. /* What we do with the incoming data depends on what we were previously
  184883. * doing before we ran out of data...
  184884. */
  184885. void /* PRIVATE */
  184886. png_process_some_data(png_structp png_ptr, png_infop info_ptr)
  184887. {
  184888. if(png_ptr == NULL) return;
  184889. switch (png_ptr->process_mode)
  184890. {
  184891. case PNG_READ_SIG_MODE:
  184892. {
  184893. png_push_read_sig(png_ptr, info_ptr);
  184894. break;
  184895. }
  184896. case PNG_READ_CHUNK_MODE:
  184897. {
  184898. png_push_read_chunk(png_ptr, info_ptr);
  184899. break;
  184900. }
  184901. case PNG_READ_IDAT_MODE:
  184902. {
  184903. png_push_read_IDAT(png_ptr);
  184904. break;
  184905. }
  184906. #if defined(PNG_READ_tEXt_SUPPORTED)
  184907. case PNG_READ_tEXt_MODE:
  184908. {
  184909. png_push_read_tEXt(png_ptr, info_ptr);
  184910. break;
  184911. }
  184912. #endif
  184913. #if defined(PNG_READ_zTXt_SUPPORTED)
  184914. case PNG_READ_zTXt_MODE:
  184915. {
  184916. png_push_read_zTXt(png_ptr, info_ptr);
  184917. break;
  184918. }
  184919. #endif
  184920. #if defined(PNG_READ_iTXt_SUPPORTED)
  184921. case PNG_READ_iTXt_MODE:
  184922. {
  184923. png_push_read_iTXt(png_ptr, info_ptr);
  184924. break;
  184925. }
  184926. #endif
  184927. case PNG_SKIP_MODE:
  184928. {
  184929. png_push_crc_finish(png_ptr);
  184930. break;
  184931. }
  184932. default:
  184933. {
  184934. png_ptr->buffer_size = 0;
  184935. break;
  184936. }
  184937. }
  184938. }
  184939. /* Read any remaining signature bytes from the stream and compare them with
  184940. * the correct PNG signature. It is possible that this routine is called
  184941. * with bytes already read from the signature, either because they have been
  184942. * checked by the calling application, or because of multiple calls to this
  184943. * routine.
  184944. */
  184945. void /* PRIVATE */
  184946. png_push_read_sig(png_structp png_ptr, png_infop info_ptr)
  184947. {
  184948. png_size_t num_checked = png_ptr->sig_bytes,
  184949. num_to_check = 8 - num_checked;
  184950. if (png_ptr->buffer_size < num_to_check)
  184951. {
  184952. num_to_check = png_ptr->buffer_size;
  184953. }
  184954. png_push_fill_buffer(png_ptr, &(info_ptr->signature[num_checked]),
  184955. num_to_check);
  184956. png_ptr->sig_bytes = (png_byte)(png_ptr->sig_bytes+num_to_check);
  184957. if (png_sig_cmp(info_ptr->signature, num_checked, num_to_check))
  184958. {
  184959. if (num_checked < 4 &&
  184960. png_sig_cmp(info_ptr->signature, num_checked, num_to_check - 4))
  184961. png_error(png_ptr, "Not a PNG file");
  184962. else
  184963. png_error(png_ptr, "PNG file corrupted by ASCII conversion");
  184964. }
  184965. else
  184966. {
  184967. if (png_ptr->sig_bytes >= 8)
  184968. {
  184969. png_ptr->process_mode = PNG_READ_CHUNK_MODE;
  184970. }
  184971. }
  184972. }
  184973. void /* PRIVATE */
  184974. png_push_read_chunk(png_structp png_ptr, png_infop info_ptr)
  184975. {
  184976. #ifdef PNG_USE_LOCAL_ARRAYS
  184977. PNG_CONST PNG_IHDR;
  184978. PNG_CONST PNG_IDAT;
  184979. PNG_CONST PNG_IEND;
  184980. PNG_CONST PNG_PLTE;
  184981. #if defined(PNG_READ_bKGD_SUPPORTED)
  184982. PNG_CONST PNG_bKGD;
  184983. #endif
  184984. #if defined(PNG_READ_cHRM_SUPPORTED)
  184985. PNG_CONST PNG_cHRM;
  184986. #endif
  184987. #if defined(PNG_READ_gAMA_SUPPORTED)
  184988. PNG_CONST PNG_gAMA;
  184989. #endif
  184990. #if defined(PNG_READ_hIST_SUPPORTED)
  184991. PNG_CONST PNG_hIST;
  184992. #endif
  184993. #if defined(PNG_READ_iCCP_SUPPORTED)
  184994. PNG_CONST PNG_iCCP;
  184995. #endif
  184996. #if defined(PNG_READ_iTXt_SUPPORTED)
  184997. PNG_CONST PNG_iTXt;
  184998. #endif
  184999. #if defined(PNG_READ_oFFs_SUPPORTED)
  185000. PNG_CONST PNG_oFFs;
  185001. #endif
  185002. #if defined(PNG_READ_pCAL_SUPPORTED)
  185003. PNG_CONST PNG_pCAL;
  185004. #endif
  185005. #if defined(PNG_READ_pHYs_SUPPORTED)
  185006. PNG_CONST PNG_pHYs;
  185007. #endif
  185008. #if defined(PNG_READ_sBIT_SUPPORTED)
  185009. PNG_CONST PNG_sBIT;
  185010. #endif
  185011. #if defined(PNG_READ_sCAL_SUPPORTED)
  185012. PNG_CONST PNG_sCAL;
  185013. #endif
  185014. #if defined(PNG_READ_sRGB_SUPPORTED)
  185015. PNG_CONST PNG_sRGB;
  185016. #endif
  185017. #if defined(PNG_READ_sPLT_SUPPORTED)
  185018. PNG_CONST PNG_sPLT;
  185019. #endif
  185020. #if defined(PNG_READ_tEXt_SUPPORTED)
  185021. PNG_CONST PNG_tEXt;
  185022. #endif
  185023. #if defined(PNG_READ_tIME_SUPPORTED)
  185024. PNG_CONST PNG_tIME;
  185025. #endif
  185026. #if defined(PNG_READ_tRNS_SUPPORTED)
  185027. PNG_CONST PNG_tRNS;
  185028. #endif
  185029. #if defined(PNG_READ_zTXt_SUPPORTED)
  185030. PNG_CONST PNG_zTXt;
  185031. #endif
  185032. #endif /* PNG_USE_LOCAL_ARRAYS */
  185033. /* First we make sure we have enough data for the 4 byte chunk name
  185034. * and the 4 byte chunk length before proceeding with decoding the
  185035. * chunk data. To fully decode each of these chunks, we also make
  185036. * sure we have enough data in the buffer for the 4 byte CRC at the
  185037. * end of every chunk (except IDAT, which is handled separately).
  185038. */
  185039. if (!(png_ptr->mode & PNG_HAVE_CHUNK_HEADER))
  185040. {
  185041. png_byte chunk_length[4];
  185042. if (png_ptr->buffer_size < 8)
  185043. {
  185044. png_push_save_buffer(png_ptr);
  185045. return;
  185046. }
  185047. png_push_fill_buffer(png_ptr, chunk_length, 4);
  185048. png_ptr->push_length = png_get_uint_31(png_ptr,chunk_length);
  185049. png_reset_crc(png_ptr);
  185050. png_crc_read(png_ptr, png_ptr->chunk_name, 4);
  185051. png_ptr->mode |= PNG_HAVE_CHUNK_HEADER;
  185052. }
  185053. if (!png_memcmp(png_ptr->chunk_name, png_IDAT, 4))
  185054. if(png_ptr->mode & PNG_AFTER_IDAT)
  185055. png_ptr->mode |= PNG_HAVE_CHUNK_AFTER_IDAT;
  185056. if (!png_memcmp(png_ptr->chunk_name, png_IHDR, 4))
  185057. {
  185058. if (png_ptr->push_length + 4 > png_ptr->buffer_size)
  185059. {
  185060. png_push_save_buffer(png_ptr);
  185061. return;
  185062. }
  185063. png_handle_IHDR(png_ptr, info_ptr, png_ptr->push_length);
  185064. }
  185065. else if (!png_memcmp(png_ptr->chunk_name, png_IEND, 4))
  185066. {
  185067. if (png_ptr->push_length + 4 > png_ptr->buffer_size)
  185068. {
  185069. png_push_save_buffer(png_ptr);
  185070. return;
  185071. }
  185072. png_handle_IEND(png_ptr, info_ptr, png_ptr->push_length);
  185073. png_ptr->process_mode = PNG_READ_DONE_MODE;
  185074. png_push_have_end(png_ptr, info_ptr);
  185075. }
  185076. #ifdef PNG_HANDLE_AS_UNKNOWN_SUPPORTED
  185077. else if (png_handle_as_unknown(png_ptr, png_ptr->chunk_name))
  185078. {
  185079. if (png_ptr->push_length + 4 > png_ptr->buffer_size)
  185080. {
  185081. png_push_save_buffer(png_ptr);
  185082. return;
  185083. }
  185084. if (!png_memcmp(png_ptr->chunk_name, png_IDAT, 4))
  185085. png_ptr->mode |= PNG_HAVE_IDAT;
  185086. png_handle_unknown(png_ptr, info_ptr, png_ptr->push_length);
  185087. if (!png_memcmp(png_ptr->chunk_name, png_PLTE, 4))
  185088. png_ptr->mode |= PNG_HAVE_PLTE;
  185089. else if (!png_memcmp(png_ptr->chunk_name, png_IDAT, 4))
  185090. {
  185091. if (!(png_ptr->mode & PNG_HAVE_IHDR))
  185092. png_error(png_ptr, "Missing IHDR before IDAT");
  185093. else if (png_ptr->color_type == PNG_COLOR_TYPE_PALETTE &&
  185094. !(png_ptr->mode & PNG_HAVE_PLTE))
  185095. png_error(png_ptr, "Missing PLTE before IDAT");
  185096. }
  185097. }
  185098. #endif
  185099. else if (!png_memcmp(png_ptr->chunk_name, png_PLTE, 4))
  185100. {
  185101. if (png_ptr->push_length + 4 > png_ptr->buffer_size)
  185102. {
  185103. png_push_save_buffer(png_ptr);
  185104. return;
  185105. }
  185106. png_handle_PLTE(png_ptr, info_ptr, png_ptr->push_length);
  185107. }
  185108. else if (!png_memcmp(png_ptr->chunk_name, png_IDAT, 4))
  185109. {
  185110. /* If we reach an IDAT chunk, this means we have read all of the
  185111. * header chunks, and we can start reading the image (or if this
  185112. * is called after the image has been read - we have an error).
  185113. */
  185114. if (!(png_ptr->mode & PNG_HAVE_IHDR))
  185115. png_error(png_ptr, "Missing IHDR before IDAT");
  185116. else if (png_ptr->color_type == PNG_COLOR_TYPE_PALETTE &&
  185117. !(png_ptr->mode & PNG_HAVE_PLTE))
  185118. png_error(png_ptr, "Missing PLTE before IDAT");
  185119. if (png_ptr->mode & PNG_HAVE_IDAT)
  185120. {
  185121. if (!(png_ptr->mode & PNG_HAVE_CHUNK_AFTER_IDAT))
  185122. if (png_ptr->push_length == 0)
  185123. return;
  185124. if (png_ptr->mode & PNG_AFTER_IDAT)
  185125. png_error(png_ptr, "Too many IDAT's found");
  185126. }
  185127. png_ptr->idat_size = png_ptr->push_length;
  185128. png_ptr->mode |= PNG_HAVE_IDAT;
  185129. png_ptr->process_mode = PNG_READ_IDAT_MODE;
  185130. png_push_have_info(png_ptr, info_ptr);
  185131. png_ptr->zstream.avail_out = (uInt)png_ptr->irowbytes;
  185132. png_ptr->zstream.next_out = png_ptr->row_buf;
  185133. return;
  185134. }
  185135. #if defined(PNG_READ_gAMA_SUPPORTED)
  185136. else if (!png_memcmp(png_ptr->chunk_name, png_gAMA, 4))
  185137. {
  185138. if (png_ptr->push_length + 4 > png_ptr->buffer_size)
  185139. {
  185140. png_push_save_buffer(png_ptr);
  185141. return;
  185142. }
  185143. png_handle_gAMA(png_ptr, info_ptr, png_ptr->push_length);
  185144. }
  185145. #endif
  185146. #if defined(PNG_READ_sBIT_SUPPORTED)
  185147. else if (!png_memcmp(png_ptr->chunk_name, png_sBIT, 4))
  185148. {
  185149. if (png_ptr->push_length + 4 > png_ptr->buffer_size)
  185150. {
  185151. png_push_save_buffer(png_ptr);
  185152. return;
  185153. }
  185154. png_handle_sBIT(png_ptr, info_ptr, png_ptr->push_length);
  185155. }
  185156. #endif
  185157. #if defined(PNG_READ_cHRM_SUPPORTED)
  185158. else if (!png_memcmp(png_ptr->chunk_name, png_cHRM, 4))
  185159. {
  185160. if (png_ptr->push_length + 4 > png_ptr->buffer_size)
  185161. {
  185162. png_push_save_buffer(png_ptr);
  185163. return;
  185164. }
  185165. png_handle_cHRM(png_ptr, info_ptr, png_ptr->push_length);
  185166. }
  185167. #endif
  185168. #if defined(PNG_READ_sRGB_SUPPORTED)
  185169. else if (!png_memcmp(png_ptr->chunk_name, png_sRGB, 4))
  185170. {
  185171. if (png_ptr->push_length + 4 > png_ptr->buffer_size)
  185172. {
  185173. png_push_save_buffer(png_ptr);
  185174. return;
  185175. }
  185176. png_handle_sRGB(png_ptr, info_ptr, png_ptr->push_length);
  185177. }
  185178. #endif
  185179. #if defined(PNG_READ_iCCP_SUPPORTED)
  185180. else if (!png_memcmp(png_ptr->chunk_name, png_iCCP, 4))
  185181. {
  185182. if (png_ptr->push_length + 4 > png_ptr->buffer_size)
  185183. {
  185184. png_push_save_buffer(png_ptr);
  185185. return;
  185186. }
  185187. png_handle_iCCP(png_ptr, info_ptr, png_ptr->push_length);
  185188. }
  185189. #endif
  185190. #if defined(PNG_READ_sPLT_SUPPORTED)
  185191. else if (!png_memcmp(png_ptr->chunk_name, png_sPLT, 4))
  185192. {
  185193. if (png_ptr->push_length + 4 > png_ptr->buffer_size)
  185194. {
  185195. png_push_save_buffer(png_ptr);
  185196. return;
  185197. }
  185198. png_handle_sPLT(png_ptr, info_ptr, png_ptr->push_length);
  185199. }
  185200. #endif
  185201. #if defined(PNG_READ_tRNS_SUPPORTED)
  185202. else if (!png_memcmp(png_ptr->chunk_name, png_tRNS, 4))
  185203. {
  185204. if (png_ptr->push_length + 4 > png_ptr->buffer_size)
  185205. {
  185206. png_push_save_buffer(png_ptr);
  185207. return;
  185208. }
  185209. png_handle_tRNS(png_ptr, info_ptr, png_ptr->push_length);
  185210. }
  185211. #endif
  185212. #if defined(PNG_READ_bKGD_SUPPORTED)
  185213. else if (!png_memcmp(png_ptr->chunk_name, png_bKGD, 4))
  185214. {
  185215. if (png_ptr->push_length + 4 > png_ptr->buffer_size)
  185216. {
  185217. png_push_save_buffer(png_ptr);
  185218. return;
  185219. }
  185220. png_handle_bKGD(png_ptr, info_ptr, png_ptr->push_length);
  185221. }
  185222. #endif
  185223. #if defined(PNG_READ_hIST_SUPPORTED)
  185224. else if (!png_memcmp(png_ptr->chunk_name, png_hIST, 4))
  185225. {
  185226. if (png_ptr->push_length + 4 > png_ptr->buffer_size)
  185227. {
  185228. png_push_save_buffer(png_ptr);
  185229. return;
  185230. }
  185231. png_handle_hIST(png_ptr, info_ptr, png_ptr->push_length);
  185232. }
  185233. #endif
  185234. #if defined(PNG_READ_pHYs_SUPPORTED)
  185235. else if (!png_memcmp(png_ptr->chunk_name, png_pHYs, 4))
  185236. {
  185237. if (png_ptr->push_length + 4 > png_ptr->buffer_size)
  185238. {
  185239. png_push_save_buffer(png_ptr);
  185240. return;
  185241. }
  185242. png_handle_pHYs(png_ptr, info_ptr, png_ptr->push_length);
  185243. }
  185244. #endif
  185245. #if defined(PNG_READ_oFFs_SUPPORTED)
  185246. else if (!png_memcmp(png_ptr->chunk_name, png_oFFs, 4))
  185247. {
  185248. if (png_ptr->push_length + 4 > png_ptr->buffer_size)
  185249. {
  185250. png_push_save_buffer(png_ptr);
  185251. return;
  185252. }
  185253. png_handle_oFFs(png_ptr, info_ptr, png_ptr->push_length);
  185254. }
  185255. #endif
  185256. #if defined(PNG_READ_pCAL_SUPPORTED)
  185257. else if (!png_memcmp(png_ptr->chunk_name, png_pCAL, 4))
  185258. {
  185259. if (png_ptr->push_length + 4 > png_ptr->buffer_size)
  185260. {
  185261. png_push_save_buffer(png_ptr);
  185262. return;
  185263. }
  185264. png_handle_pCAL(png_ptr, info_ptr, png_ptr->push_length);
  185265. }
  185266. #endif
  185267. #if defined(PNG_READ_sCAL_SUPPORTED)
  185268. else if (!png_memcmp(png_ptr->chunk_name, png_sCAL, 4))
  185269. {
  185270. if (png_ptr->push_length + 4 > png_ptr->buffer_size)
  185271. {
  185272. png_push_save_buffer(png_ptr);
  185273. return;
  185274. }
  185275. png_handle_sCAL(png_ptr, info_ptr, png_ptr->push_length);
  185276. }
  185277. #endif
  185278. #if defined(PNG_READ_tIME_SUPPORTED)
  185279. else if (!png_memcmp(png_ptr->chunk_name, png_tIME, 4))
  185280. {
  185281. if (png_ptr->push_length + 4 > png_ptr->buffer_size)
  185282. {
  185283. png_push_save_buffer(png_ptr);
  185284. return;
  185285. }
  185286. png_handle_tIME(png_ptr, info_ptr, png_ptr->push_length);
  185287. }
  185288. #endif
  185289. #if defined(PNG_READ_tEXt_SUPPORTED)
  185290. else if (!png_memcmp(png_ptr->chunk_name, png_tEXt, 4))
  185291. {
  185292. if (png_ptr->push_length + 4 > png_ptr->buffer_size)
  185293. {
  185294. png_push_save_buffer(png_ptr);
  185295. return;
  185296. }
  185297. png_push_handle_tEXt(png_ptr, info_ptr, png_ptr->push_length);
  185298. }
  185299. #endif
  185300. #if defined(PNG_READ_zTXt_SUPPORTED)
  185301. else if (!png_memcmp(png_ptr->chunk_name, png_zTXt, 4))
  185302. {
  185303. if (png_ptr->push_length + 4 > png_ptr->buffer_size)
  185304. {
  185305. png_push_save_buffer(png_ptr);
  185306. return;
  185307. }
  185308. png_push_handle_zTXt(png_ptr, info_ptr, png_ptr->push_length);
  185309. }
  185310. #endif
  185311. #if defined(PNG_READ_iTXt_SUPPORTED)
  185312. else if (!png_memcmp(png_ptr->chunk_name, png_iTXt, 4))
  185313. {
  185314. if (png_ptr->push_length + 4 > png_ptr->buffer_size)
  185315. {
  185316. png_push_save_buffer(png_ptr);
  185317. return;
  185318. }
  185319. png_push_handle_iTXt(png_ptr, info_ptr, png_ptr->push_length);
  185320. }
  185321. #endif
  185322. else
  185323. {
  185324. if (png_ptr->push_length + 4 > png_ptr->buffer_size)
  185325. {
  185326. png_push_save_buffer(png_ptr);
  185327. return;
  185328. }
  185329. png_push_handle_unknown(png_ptr, info_ptr, png_ptr->push_length);
  185330. }
  185331. png_ptr->mode &= ~PNG_HAVE_CHUNK_HEADER;
  185332. }
  185333. void /* PRIVATE */
  185334. png_push_crc_skip(png_structp png_ptr, png_uint_32 skip)
  185335. {
  185336. png_ptr->process_mode = PNG_SKIP_MODE;
  185337. png_ptr->skip_length = skip;
  185338. }
  185339. void /* PRIVATE */
  185340. png_push_crc_finish(png_structp png_ptr)
  185341. {
  185342. if (png_ptr->skip_length && png_ptr->save_buffer_size)
  185343. {
  185344. png_size_t save_size;
  185345. if (png_ptr->skip_length < (png_uint_32)png_ptr->save_buffer_size)
  185346. save_size = (png_size_t)png_ptr->skip_length;
  185347. else
  185348. save_size = png_ptr->save_buffer_size;
  185349. png_calculate_crc(png_ptr, png_ptr->save_buffer_ptr, save_size);
  185350. png_ptr->skip_length -= save_size;
  185351. png_ptr->buffer_size -= save_size;
  185352. png_ptr->save_buffer_size -= save_size;
  185353. png_ptr->save_buffer_ptr += save_size;
  185354. }
  185355. if (png_ptr->skip_length && png_ptr->current_buffer_size)
  185356. {
  185357. png_size_t save_size;
  185358. if (png_ptr->skip_length < (png_uint_32)png_ptr->current_buffer_size)
  185359. save_size = (png_size_t)png_ptr->skip_length;
  185360. else
  185361. save_size = png_ptr->current_buffer_size;
  185362. png_calculate_crc(png_ptr, png_ptr->current_buffer_ptr, save_size);
  185363. png_ptr->skip_length -= save_size;
  185364. png_ptr->buffer_size -= save_size;
  185365. png_ptr->current_buffer_size -= save_size;
  185366. png_ptr->current_buffer_ptr += save_size;
  185367. }
  185368. if (!png_ptr->skip_length)
  185369. {
  185370. if (png_ptr->buffer_size < 4)
  185371. {
  185372. png_push_save_buffer(png_ptr);
  185373. return;
  185374. }
  185375. png_crc_finish(png_ptr, 0);
  185376. png_ptr->process_mode = PNG_READ_CHUNK_MODE;
  185377. }
  185378. }
  185379. void PNGAPI
  185380. png_push_fill_buffer(png_structp png_ptr, png_bytep buffer, png_size_t length)
  185381. {
  185382. png_bytep ptr;
  185383. if(png_ptr == NULL) return;
  185384. ptr = buffer;
  185385. if (png_ptr->save_buffer_size)
  185386. {
  185387. png_size_t save_size;
  185388. if (length < png_ptr->save_buffer_size)
  185389. save_size = length;
  185390. else
  185391. save_size = png_ptr->save_buffer_size;
  185392. png_memcpy(ptr, png_ptr->save_buffer_ptr, save_size);
  185393. length -= save_size;
  185394. ptr += save_size;
  185395. png_ptr->buffer_size -= save_size;
  185396. png_ptr->save_buffer_size -= save_size;
  185397. png_ptr->save_buffer_ptr += save_size;
  185398. }
  185399. if (length && png_ptr->current_buffer_size)
  185400. {
  185401. png_size_t save_size;
  185402. if (length < png_ptr->current_buffer_size)
  185403. save_size = length;
  185404. else
  185405. save_size = png_ptr->current_buffer_size;
  185406. png_memcpy(ptr, png_ptr->current_buffer_ptr, save_size);
  185407. png_ptr->buffer_size -= save_size;
  185408. png_ptr->current_buffer_size -= save_size;
  185409. png_ptr->current_buffer_ptr += save_size;
  185410. }
  185411. }
  185412. void /* PRIVATE */
  185413. png_push_save_buffer(png_structp png_ptr)
  185414. {
  185415. if (png_ptr->save_buffer_size)
  185416. {
  185417. if (png_ptr->save_buffer_ptr != png_ptr->save_buffer)
  185418. {
  185419. png_size_t i,istop;
  185420. png_bytep sp;
  185421. png_bytep dp;
  185422. istop = png_ptr->save_buffer_size;
  185423. for (i = 0, sp = png_ptr->save_buffer_ptr, dp = png_ptr->save_buffer;
  185424. i < istop; i++, sp++, dp++)
  185425. {
  185426. *dp = *sp;
  185427. }
  185428. }
  185429. }
  185430. if (png_ptr->save_buffer_size + png_ptr->current_buffer_size >
  185431. png_ptr->save_buffer_max)
  185432. {
  185433. png_size_t new_max;
  185434. png_bytep old_buffer;
  185435. if (png_ptr->save_buffer_size > PNG_SIZE_MAX -
  185436. (png_ptr->current_buffer_size + 256))
  185437. {
  185438. png_error(png_ptr, "Potential overflow of save_buffer");
  185439. }
  185440. new_max = png_ptr->save_buffer_size + png_ptr->current_buffer_size + 256;
  185441. old_buffer = png_ptr->save_buffer;
  185442. png_ptr->save_buffer = (png_bytep)png_malloc(png_ptr,
  185443. (png_uint_32)new_max);
  185444. png_memcpy(png_ptr->save_buffer, old_buffer, png_ptr->save_buffer_size);
  185445. png_free(png_ptr, old_buffer);
  185446. png_ptr->save_buffer_max = new_max;
  185447. }
  185448. if (png_ptr->current_buffer_size)
  185449. {
  185450. png_memcpy(png_ptr->save_buffer + png_ptr->save_buffer_size,
  185451. png_ptr->current_buffer_ptr, png_ptr->current_buffer_size);
  185452. png_ptr->save_buffer_size += png_ptr->current_buffer_size;
  185453. png_ptr->current_buffer_size = 0;
  185454. }
  185455. png_ptr->save_buffer_ptr = png_ptr->save_buffer;
  185456. png_ptr->buffer_size = 0;
  185457. }
  185458. void /* PRIVATE */
  185459. png_push_restore_buffer(png_structp png_ptr, png_bytep buffer,
  185460. png_size_t buffer_length)
  185461. {
  185462. png_ptr->current_buffer = buffer;
  185463. png_ptr->current_buffer_size = buffer_length;
  185464. png_ptr->buffer_size = buffer_length + png_ptr->save_buffer_size;
  185465. png_ptr->current_buffer_ptr = png_ptr->current_buffer;
  185466. }
  185467. void /* PRIVATE */
  185468. png_push_read_IDAT(png_structp png_ptr)
  185469. {
  185470. #ifdef PNG_USE_LOCAL_ARRAYS
  185471. PNG_CONST PNG_IDAT;
  185472. #endif
  185473. if (!(png_ptr->mode & PNG_HAVE_CHUNK_HEADER))
  185474. {
  185475. png_byte chunk_length[4];
  185476. if (png_ptr->buffer_size < 8)
  185477. {
  185478. png_push_save_buffer(png_ptr);
  185479. return;
  185480. }
  185481. png_push_fill_buffer(png_ptr, chunk_length, 4);
  185482. png_ptr->push_length = png_get_uint_31(png_ptr,chunk_length);
  185483. png_reset_crc(png_ptr);
  185484. png_crc_read(png_ptr, png_ptr->chunk_name, 4);
  185485. png_ptr->mode |= PNG_HAVE_CHUNK_HEADER;
  185486. if (png_memcmp(png_ptr->chunk_name, png_IDAT, 4))
  185487. {
  185488. png_ptr->process_mode = PNG_READ_CHUNK_MODE;
  185489. if (!(png_ptr->flags & PNG_FLAG_ZLIB_FINISHED))
  185490. png_error(png_ptr, "Not enough compressed data");
  185491. return;
  185492. }
  185493. png_ptr->idat_size = png_ptr->push_length;
  185494. }
  185495. if (png_ptr->idat_size && png_ptr->save_buffer_size)
  185496. {
  185497. png_size_t save_size;
  185498. if (png_ptr->idat_size < (png_uint_32)png_ptr->save_buffer_size)
  185499. {
  185500. save_size = (png_size_t)png_ptr->idat_size;
  185501. /* check for overflow */
  185502. if((png_uint_32)save_size != png_ptr->idat_size)
  185503. png_error(png_ptr, "save_size overflowed in pngpread");
  185504. }
  185505. else
  185506. save_size = png_ptr->save_buffer_size;
  185507. png_calculate_crc(png_ptr, png_ptr->save_buffer_ptr, save_size);
  185508. if (!(png_ptr->flags & PNG_FLAG_ZLIB_FINISHED))
  185509. png_process_IDAT_data(png_ptr, png_ptr->save_buffer_ptr, save_size);
  185510. png_ptr->idat_size -= save_size;
  185511. png_ptr->buffer_size -= save_size;
  185512. png_ptr->save_buffer_size -= save_size;
  185513. png_ptr->save_buffer_ptr += save_size;
  185514. }
  185515. if (png_ptr->idat_size && png_ptr->current_buffer_size)
  185516. {
  185517. png_size_t save_size;
  185518. if (png_ptr->idat_size < (png_uint_32)png_ptr->current_buffer_size)
  185519. {
  185520. save_size = (png_size_t)png_ptr->idat_size;
  185521. /* check for overflow */
  185522. if((png_uint_32)save_size != png_ptr->idat_size)
  185523. png_error(png_ptr, "save_size overflowed in pngpread");
  185524. }
  185525. else
  185526. save_size = png_ptr->current_buffer_size;
  185527. png_calculate_crc(png_ptr, png_ptr->current_buffer_ptr, save_size);
  185528. if (!(png_ptr->flags & PNG_FLAG_ZLIB_FINISHED))
  185529. png_process_IDAT_data(png_ptr, png_ptr->current_buffer_ptr, save_size);
  185530. png_ptr->idat_size -= save_size;
  185531. png_ptr->buffer_size -= save_size;
  185532. png_ptr->current_buffer_size -= save_size;
  185533. png_ptr->current_buffer_ptr += save_size;
  185534. }
  185535. if (!png_ptr->idat_size)
  185536. {
  185537. if (png_ptr->buffer_size < 4)
  185538. {
  185539. png_push_save_buffer(png_ptr);
  185540. return;
  185541. }
  185542. png_crc_finish(png_ptr, 0);
  185543. png_ptr->mode &= ~PNG_HAVE_CHUNK_HEADER;
  185544. png_ptr->mode |= PNG_AFTER_IDAT;
  185545. }
  185546. }
  185547. void /* PRIVATE */
  185548. png_process_IDAT_data(png_structp png_ptr, png_bytep buffer,
  185549. png_size_t buffer_length)
  185550. {
  185551. int ret;
  185552. if ((png_ptr->flags & PNG_FLAG_ZLIB_FINISHED) && buffer_length)
  185553. png_error(png_ptr, "Extra compression data");
  185554. png_ptr->zstream.next_in = buffer;
  185555. png_ptr->zstream.avail_in = (uInt)buffer_length;
  185556. for(;;)
  185557. {
  185558. ret = inflate(&png_ptr->zstream, Z_PARTIAL_FLUSH);
  185559. if (ret != Z_OK)
  185560. {
  185561. if (ret == Z_STREAM_END)
  185562. {
  185563. if (png_ptr->zstream.avail_in)
  185564. png_error(png_ptr, "Extra compressed data");
  185565. if (!(png_ptr->zstream.avail_out))
  185566. {
  185567. png_push_process_row(png_ptr);
  185568. }
  185569. png_ptr->mode |= PNG_AFTER_IDAT;
  185570. png_ptr->flags |= PNG_FLAG_ZLIB_FINISHED;
  185571. break;
  185572. }
  185573. else if (ret == Z_BUF_ERROR)
  185574. break;
  185575. else
  185576. png_error(png_ptr, "Decompression Error");
  185577. }
  185578. if (!(png_ptr->zstream.avail_out))
  185579. {
  185580. if ((
  185581. #if defined(PNG_READ_INTERLACING_SUPPORTED)
  185582. png_ptr->interlaced && png_ptr->pass > 6) ||
  185583. (!png_ptr->interlaced &&
  185584. #endif
  185585. png_ptr->row_number == png_ptr->num_rows))
  185586. {
  185587. if (png_ptr->zstream.avail_in)
  185588. {
  185589. png_warning(png_ptr, "Too much data in IDAT chunks");
  185590. }
  185591. png_ptr->flags |= PNG_FLAG_ZLIB_FINISHED;
  185592. break;
  185593. }
  185594. png_push_process_row(png_ptr);
  185595. png_ptr->zstream.avail_out = (uInt)png_ptr->irowbytes;
  185596. png_ptr->zstream.next_out = png_ptr->row_buf;
  185597. }
  185598. else
  185599. break;
  185600. }
  185601. }
  185602. void /* PRIVATE */
  185603. png_push_process_row(png_structp png_ptr)
  185604. {
  185605. png_ptr->row_info.color_type = png_ptr->color_type;
  185606. png_ptr->row_info.width = png_ptr->iwidth;
  185607. png_ptr->row_info.channels = png_ptr->channels;
  185608. png_ptr->row_info.bit_depth = png_ptr->bit_depth;
  185609. png_ptr->row_info.pixel_depth = png_ptr->pixel_depth;
  185610. png_ptr->row_info.rowbytes = PNG_ROWBYTES(png_ptr->row_info.pixel_depth,
  185611. png_ptr->row_info.width);
  185612. png_read_filter_row(png_ptr, &(png_ptr->row_info),
  185613. png_ptr->row_buf + 1, png_ptr->prev_row + 1,
  185614. (int)(png_ptr->row_buf[0]));
  185615. png_memcpy_check(png_ptr, png_ptr->prev_row, png_ptr->row_buf,
  185616. png_ptr->rowbytes + 1);
  185617. if (png_ptr->transformations || (png_ptr->flags&PNG_FLAG_STRIP_ALPHA))
  185618. png_do_read_transformations(png_ptr);
  185619. #if defined(PNG_READ_INTERLACING_SUPPORTED)
  185620. /* blow up interlaced rows to full size */
  185621. if (png_ptr->interlaced && (png_ptr->transformations & PNG_INTERLACE))
  185622. {
  185623. if (png_ptr->pass < 6)
  185624. /* old interface (pre-1.0.9):
  185625. png_do_read_interlace(&(png_ptr->row_info),
  185626. png_ptr->row_buf + 1, png_ptr->pass, png_ptr->transformations);
  185627. */
  185628. png_do_read_interlace(png_ptr);
  185629. switch (png_ptr->pass)
  185630. {
  185631. case 0:
  185632. {
  185633. int i;
  185634. for (i = 0; i < 8 && png_ptr->pass == 0; i++)
  185635. {
  185636. png_push_have_row(png_ptr, png_ptr->row_buf + 1);
  185637. png_read_push_finish_row(png_ptr); /* updates png_ptr->pass */
  185638. }
  185639. if (png_ptr->pass == 2) /* pass 1 might be empty */
  185640. {
  185641. for (i = 0; i < 4 && png_ptr->pass == 2; i++)
  185642. {
  185643. png_push_have_row(png_ptr, png_bytep_NULL);
  185644. png_read_push_finish_row(png_ptr);
  185645. }
  185646. }
  185647. if (png_ptr->pass == 4 && png_ptr->height <= 4)
  185648. {
  185649. for (i = 0; i < 2 && png_ptr->pass == 4; i++)
  185650. {
  185651. png_push_have_row(png_ptr, png_bytep_NULL);
  185652. png_read_push_finish_row(png_ptr);
  185653. }
  185654. }
  185655. if (png_ptr->pass == 6 && png_ptr->height <= 4)
  185656. {
  185657. png_push_have_row(png_ptr, png_bytep_NULL);
  185658. png_read_push_finish_row(png_ptr);
  185659. }
  185660. break;
  185661. }
  185662. case 1:
  185663. {
  185664. int i;
  185665. for (i = 0; i < 8 && png_ptr->pass == 1; i++)
  185666. {
  185667. png_push_have_row(png_ptr, png_ptr->row_buf + 1);
  185668. png_read_push_finish_row(png_ptr);
  185669. }
  185670. if (png_ptr->pass == 2) /* skip top 4 generated rows */
  185671. {
  185672. for (i = 0; i < 4 && png_ptr->pass == 2; i++)
  185673. {
  185674. png_push_have_row(png_ptr, png_bytep_NULL);
  185675. png_read_push_finish_row(png_ptr);
  185676. }
  185677. }
  185678. break;
  185679. }
  185680. case 2:
  185681. {
  185682. int i;
  185683. for (i = 0; i < 4 && png_ptr->pass == 2; i++)
  185684. {
  185685. png_push_have_row(png_ptr, png_ptr->row_buf + 1);
  185686. png_read_push_finish_row(png_ptr);
  185687. }
  185688. for (i = 0; i < 4 && png_ptr->pass == 2; i++)
  185689. {
  185690. png_push_have_row(png_ptr, png_bytep_NULL);
  185691. png_read_push_finish_row(png_ptr);
  185692. }
  185693. if (png_ptr->pass == 4) /* pass 3 might be empty */
  185694. {
  185695. for (i = 0; i < 2 && png_ptr->pass == 4; i++)
  185696. {
  185697. png_push_have_row(png_ptr, png_bytep_NULL);
  185698. png_read_push_finish_row(png_ptr);
  185699. }
  185700. }
  185701. break;
  185702. }
  185703. case 3:
  185704. {
  185705. int i;
  185706. for (i = 0; i < 4 && png_ptr->pass == 3; i++)
  185707. {
  185708. png_push_have_row(png_ptr, png_ptr->row_buf + 1);
  185709. png_read_push_finish_row(png_ptr);
  185710. }
  185711. if (png_ptr->pass == 4) /* skip top two generated rows */
  185712. {
  185713. for (i = 0; i < 2 && png_ptr->pass == 4; i++)
  185714. {
  185715. png_push_have_row(png_ptr, png_bytep_NULL);
  185716. png_read_push_finish_row(png_ptr);
  185717. }
  185718. }
  185719. break;
  185720. }
  185721. case 4:
  185722. {
  185723. int i;
  185724. for (i = 0; i < 2 && png_ptr->pass == 4; i++)
  185725. {
  185726. png_push_have_row(png_ptr, png_ptr->row_buf + 1);
  185727. png_read_push_finish_row(png_ptr);
  185728. }
  185729. for (i = 0; i < 2 && png_ptr->pass == 4; i++)
  185730. {
  185731. png_push_have_row(png_ptr, png_bytep_NULL);
  185732. png_read_push_finish_row(png_ptr);
  185733. }
  185734. if (png_ptr->pass == 6) /* pass 5 might be empty */
  185735. {
  185736. png_push_have_row(png_ptr, png_bytep_NULL);
  185737. png_read_push_finish_row(png_ptr);
  185738. }
  185739. break;
  185740. }
  185741. case 5:
  185742. {
  185743. int i;
  185744. for (i = 0; i < 2 && png_ptr->pass == 5; i++)
  185745. {
  185746. png_push_have_row(png_ptr, png_ptr->row_buf + 1);
  185747. png_read_push_finish_row(png_ptr);
  185748. }
  185749. if (png_ptr->pass == 6) /* skip top generated row */
  185750. {
  185751. png_push_have_row(png_ptr, png_bytep_NULL);
  185752. png_read_push_finish_row(png_ptr);
  185753. }
  185754. break;
  185755. }
  185756. case 6:
  185757. {
  185758. png_push_have_row(png_ptr, png_ptr->row_buf + 1);
  185759. png_read_push_finish_row(png_ptr);
  185760. if (png_ptr->pass != 6)
  185761. break;
  185762. png_push_have_row(png_ptr, png_bytep_NULL);
  185763. png_read_push_finish_row(png_ptr);
  185764. }
  185765. }
  185766. }
  185767. else
  185768. #endif
  185769. {
  185770. png_push_have_row(png_ptr, png_ptr->row_buf + 1);
  185771. png_read_push_finish_row(png_ptr);
  185772. }
  185773. }
  185774. void /* PRIVATE */
  185775. png_read_push_finish_row(png_structp png_ptr)
  185776. {
  185777. #ifdef PNG_USE_LOCAL_ARRAYS
  185778. /* arrays to facilitate easy interlacing - use pass (0 - 6) as index */
  185779. /* start of interlace block */
  185780. PNG_CONST int FARDATA png_pass_start[] = {0, 4, 0, 2, 0, 1, 0};
  185781. /* offset to next interlace block */
  185782. PNG_CONST int FARDATA png_pass_inc[] = {8, 8, 4, 4, 2, 2, 1};
  185783. /* start of interlace block in the y direction */
  185784. PNG_CONST int FARDATA png_pass_ystart[] = {0, 0, 4, 0, 2, 0, 1};
  185785. /* offset to next interlace block in the y direction */
  185786. PNG_CONST int FARDATA png_pass_yinc[] = {8, 8, 8, 4, 4, 2, 2};
  185787. /* Height of interlace block. This is not currently used - if you need
  185788. * it, uncomment it here and in png.h
  185789. PNG_CONST int FARDATA png_pass_height[] = {8, 8, 4, 4, 2, 2, 1};
  185790. */
  185791. #endif
  185792. png_ptr->row_number++;
  185793. if (png_ptr->row_number < png_ptr->num_rows)
  185794. return;
  185795. if (png_ptr->interlaced)
  185796. {
  185797. png_ptr->row_number = 0;
  185798. png_memset_check(png_ptr, png_ptr->prev_row, 0,
  185799. png_ptr->rowbytes + 1);
  185800. do
  185801. {
  185802. png_ptr->pass++;
  185803. if ((png_ptr->pass == 1 && png_ptr->width < 5) ||
  185804. (png_ptr->pass == 3 && png_ptr->width < 3) ||
  185805. (png_ptr->pass == 5 && png_ptr->width < 2))
  185806. png_ptr->pass++;
  185807. if (png_ptr->pass > 7)
  185808. png_ptr->pass--;
  185809. if (png_ptr->pass >= 7)
  185810. break;
  185811. png_ptr->iwidth = (png_ptr->width +
  185812. png_pass_inc[png_ptr->pass] - 1 -
  185813. png_pass_start[png_ptr->pass]) /
  185814. png_pass_inc[png_ptr->pass];
  185815. png_ptr->irowbytes = PNG_ROWBYTES(png_ptr->pixel_depth,
  185816. png_ptr->iwidth) + 1;
  185817. if (png_ptr->transformations & PNG_INTERLACE)
  185818. break;
  185819. png_ptr->num_rows = (png_ptr->height +
  185820. png_pass_yinc[png_ptr->pass] - 1 -
  185821. png_pass_ystart[png_ptr->pass]) /
  185822. png_pass_yinc[png_ptr->pass];
  185823. } while (png_ptr->iwidth == 0 || png_ptr->num_rows == 0);
  185824. }
  185825. }
  185826. #if defined(PNG_READ_tEXt_SUPPORTED)
  185827. void /* PRIVATE */
  185828. png_push_handle_tEXt(png_structp png_ptr, png_infop info_ptr, png_uint_32
  185829. length)
  185830. {
  185831. if (!(png_ptr->mode & PNG_HAVE_IHDR) || (png_ptr->mode & PNG_HAVE_IEND))
  185832. {
  185833. png_error(png_ptr, "Out of place tEXt");
  185834. info_ptr = info_ptr; /* to quiet some compiler warnings */
  185835. }
  185836. #ifdef PNG_MAX_MALLOC_64K
  185837. png_ptr->skip_length = 0; /* This may not be necessary */
  185838. if (length > (png_uint_32)65535L) /* Can't hold entire string in memory */
  185839. {
  185840. png_warning(png_ptr, "tEXt chunk too large to fit in memory");
  185841. png_ptr->skip_length = length - (png_uint_32)65535L;
  185842. length = (png_uint_32)65535L;
  185843. }
  185844. #endif
  185845. png_ptr->current_text = (png_charp)png_malloc(png_ptr,
  185846. (png_uint_32)(length+1));
  185847. png_ptr->current_text[length] = '\0';
  185848. png_ptr->current_text_ptr = png_ptr->current_text;
  185849. png_ptr->current_text_size = (png_size_t)length;
  185850. png_ptr->current_text_left = (png_size_t)length;
  185851. png_ptr->process_mode = PNG_READ_tEXt_MODE;
  185852. }
  185853. void /* PRIVATE */
  185854. png_push_read_tEXt(png_structp png_ptr, png_infop info_ptr)
  185855. {
  185856. if (png_ptr->buffer_size && png_ptr->current_text_left)
  185857. {
  185858. png_size_t text_size;
  185859. if (png_ptr->buffer_size < png_ptr->current_text_left)
  185860. text_size = png_ptr->buffer_size;
  185861. else
  185862. text_size = png_ptr->current_text_left;
  185863. png_crc_read(png_ptr, (png_bytep)png_ptr->current_text_ptr, text_size);
  185864. png_ptr->current_text_left -= text_size;
  185865. png_ptr->current_text_ptr += text_size;
  185866. }
  185867. if (!(png_ptr->current_text_left))
  185868. {
  185869. png_textp text_ptr;
  185870. png_charp text;
  185871. png_charp key;
  185872. int ret;
  185873. if (png_ptr->buffer_size < 4)
  185874. {
  185875. png_push_save_buffer(png_ptr);
  185876. return;
  185877. }
  185878. png_push_crc_finish(png_ptr);
  185879. #if defined(PNG_MAX_MALLOC_64K)
  185880. if (png_ptr->skip_length)
  185881. return;
  185882. #endif
  185883. key = png_ptr->current_text;
  185884. for (text = key; *text; text++)
  185885. /* empty loop */ ;
  185886. if (text < key + png_ptr->current_text_size)
  185887. text++;
  185888. text_ptr = (png_textp)png_malloc(png_ptr,
  185889. (png_uint_32)png_sizeof(png_text));
  185890. text_ptr->compression = PNG_TEXT_COMPRESSION_NONE;
  185891. text_ptr->key = key;
  185892. #ifdef PNG_iTXt_SUPPORTED
  185893. text_ptr->lang = NULL;
  185894. text_ptr->lang_key = NULL;
  185895. #endif
  185896. text_ptr->text = text;
  185897. ret = png_set_text_2(png_ptr, info_ptr, text_ptr, 1);
  185898. png_free(png_ptr, key);
  185899. png_free(png_ptr, text_ptr);
  185900. png_ptr->current_text = NULL;
  185901. if (ret)
  185902. png_warning(png_ptr, "Insufficient memory to store text chunk.");
  185903. }
  185904. }
  185905. #endif
  185906. #if defined(PNG_READ_zTXt_SUPPORTED)
  185907. void /* PRIVATE */
  185908. png_push_handle_zTXt(png_structp png_ptr, png_infop info_ptr, png_uint_32
  185909. length)
  185910. {
  185911. if (!(png_ptr->mode & PNG_HAVE_IHDR) || (png_ptr->mode & PNG_HAVE_IEND))
  185912. {
  185913. png_error(png_ptr, "Out of place zTXt");
  185914. info_ptr = info_ptr; /* to quiet some compiler warnings */
  185915. }
  185916. #ifdef PNG_MAX_MALLOC_64K
  185917. /* We can't handle zTXt chunks > 64K, since we don't have enough space
  185918. * to be able to store the uncompressed data. Actually, the threshold
  185919. * is probably around 32K, but it isn't as definite as 64K is.
  185920. */
  185921. if (length > (png_uint_32)65535L)
  185922. {
  185923. png_warning(png_ptr, "zTXt chunk too large to fit in memory");
  185924. png_push_crc_skip(png_ptr, length);
  185925. return;
  185926. }
  185927. #endif
  185928. png_ptr->current_text = (png_charp)png_malloc(png_ptr,
  185929. (png_uint_32)(length+1));
  185930. png_ptr->current_text[length] = '\0';
  185931. png_ptr->current_text_ptr = png_ptr->current_text;
  185932. png_ptr->current_text_size = (png_size_t)length;
  185933. png_ptr->current_text_left = (png_size_t)length;
  185934. png_ptr->process_mode = PNG_READ_zTXt_MODE;
  185935. }
  185936. void /* PRIVATE */
  185937. png_push_read_zTXt(png_structp png_ptr, png_infop info_ptr)
  185938. {
  185939. if (png_ptr->buffer_size && png_ptr->current_text_left)
  185940. {
  185941. png_size_t text_size;
  185942. if (png_ptr->buffer_size < (png_uint_32)png_ptr->current_text_left)
  185943. text_size = png_ptr->buffer_size;
  185944. else
  185945. text_size = png_ptr->current_text_left;
  185946. png_crc_read(png_ptr, (png_bytep)png_ptr->current_text_ptr, text_size);
  185947. png_ptr->current_text_left -= text_size;
  185948. png_ptr->current_text_ptr += text_size;
  185949. }
  185950. if (!(png_ptr->current_text_left))
  185951. {
  185952. png_textp text_ptr;
  185953. png_charp text;
  185954. png_charp key;
  185955. int ret;
  185956. png_size_t text_size, key_size;
  185957. if (png_ptr->buffer_size < 4)
  185958. {
  185959. png_push_save_buffer(png_ptr);
  185960. return;
  185961. }
  185962. png_push_crc_finish(png_ptr);
  185963. key = png_ptr->current_text;
  185964. for (text = key; *text; text++)
  185965. /* empty loop */ ;
  185966. /* zTXt can't have zero text */
  185967. if (text >= key + png_ptr->current_text_size)
  185968. {
  185969. png_ptr->current_text = NULL;
  185970. png_free(png_ptr, key);
  185971. return;
  185972. }
  185973. text++;
  185974. if (*text != PNG_TEXT_COMPRESSION_zTXt) /* check compression byte */
  185975. {
  185976. png_ptr->current_text = NULL;
  185977. png_free(png_ptr, key);
  185978. return;
  185979. }
  185980. text++;
  185981. png_ptr->zstream.next_in = (png_bytep )text;
  185982. png_ptr->zstream.avail_in = (uInt)(png_ptr->current_text_size -
  185983. (text - key));
  185984. png_ptr->zstream.next_out = png_ptr->zbuf;
  185985. png_ptr->zstream.avail_out = (uInt)png_ptr->zbuf_size;
  185986. key_size = text - key;
  185987. text_size = 0;
  185988. text = NULL;
  185989. ret = Z_STREAM_END;
  185990. while (png_ptr->zstream.avail_in)
  185991. {
  185992. ret = inflate(&png_ptr->zstream, Z_PARTIAL_FLUSH);
  185993. if (ret != Z_OK && ret != Z_STREAM_END)
  185994. {
  185995. inflateReset(&png_ptr->zstream);
  185996. png_ptr->zstream.avail_in = 0;
  185997. png_ptr->current_text = NULL;
  185998. png_free(png_ptr, key);
  185999. png_free(png_ptr, text);
  186000. return;
  186001. }
  186002. if (!(png_ptr->zstream.avail_out) || ret == Z_STREAM_END)
  186003. {
  186004. if (text == NULL)
  186005. {
  186006. text = (png_charp)png_malloc(png_ptr,
  186007. (png_uint_32)(png_ptr->zbuf_size - png_ptr->zstream.avail_out
  186008. + key_size + 1));
  186009. png_memcpy(text + key_size, png_ptr->zbuf,
  186010. png_ptr->zbuf_size - png_ptr->zstream.avail_out);
  186011. png_memcpy(text, key, key_size);
  186012. text_size = key_size + png_ptr->zbuf_size -
  186013. png_ptr->zstream.avail_out;
  186014. *(text + text_size) = '\0';
  186015. }
  186016. else
  186017. {
  186018. png_charp tmp;
  186019. tmp = text;
  186020. text = (png_charp)png_malloc(png_ptr, text_size +
  186021. (png_uint_32)(png_ptr->zbuf_size - png_ptr->zstream.avail_out
  186022. + 1));
  186023. png_memcpy(text, tmp, text_size);
  186024. png_free(png_ptr, tmp);
  186025. png_memcpy(text + text_size, png_ptr->zbuf,
  186026. png_ptr->zbuf_size - png_ptr->zstream.avail_out);
  186027. text_size += png_ptr->zbuf_size - png_ptr->zstream.avail_out;
  186028. *(text + text_size) = '\0';
  186029. }
  186030. if (ret != Z_STREAM_END)
  186031. {
  186032. png_ptr->zstream.next_out = png_ptr->zbuf;
  186033. png_ptr->zstream.avail_out = (uInt)png_ptr->zbuf_size;
  186034. }
  186035. }
  186036. else
  186037. {
  186038. break;
  186039. }
  186040. if (ret == Z_STREAM_END)
  186041. break;
  186042. }
  186043. inflateReset(&png_ptr->zstream);
  186044. png_ptr->zstream.avail_in = 0;
  186045. if (ret != Z_STREAM_END)
  186046. {
  186047. png_ptr->current_text = NULL;
  186048. png_free(png_ptr, key);
  186049. png_free(png_ptr, text);
  186050. return;
  186051. }
  186052. png_ptr->current_text = NULL;
  186053. png_free(png_ptr, key);
  186054. key = text;
  186055. text += key_size;
  186056. text_ptr = (png_textp)png_malloc(png_ptr,
  186057. (png_uint_32)png_sizeof(png_text));
  186058. text_ptr->compression = PNG_TEXT_COMPRESSION_zTXt;
  186059. text_ptr->key = key;
  186060. #ifdef PNG_iTXt_SUPPORTED
  186061. text_ptr->lang = NULL;
  186062. text_ptr->lang_key = NULL;
  186063. #endif
  186064. text_ptr->text = text;
  186065. ret = png_set_text_2(png_ptr, info_ptr, text_ptr, 1);
  186066. png_free(png_ptr, key);
  186067. png_free(png_ptr, text_ptr);
  186068. if (ret)
  186069. png_warning(png_ptr, "Insufficient memory to store text chunk.");
  186070. }
  186071. }
  186072. #endif
  186073. #if defined(PNG_READ_iTXt_SUPPORTED)
  186074. void /* PRIVATE */
  186075. png_push_handle_iTXt(png_structp png_ptr, png_infop info_ptr, png_uint_32
  186076. length)
  186077. {
  186078. if (!(png_ptr->mode & PNG_HAVE_IHDR) || (png_ptr->mode & PNG_HAVE_IEND))
  186079. {
  186080. png_error(png_ptr, "Out of place iTXt");
  186081. info_ptr = info_ptr; /* to quiet some compiler warnings */
  186082. }
  186083. #ifdef PNG_MAX_MALLOC_64K
  186084. png_ptr->skip_length = 0; /* This may not be necessary */
  186085. if (length > (png_uint_32)65535L) /* Can't hold entire string in memory */
  186086. {
  186087. png_warning(png_ptr, "iTXt chunk too large to fit in memory");
  186088. png_ptr->skip_length = length - (png_uint_32)65535L;
  186089. length = (png_uint_32)65535L;
  186090. }
  186091. #endif
  186092. png_ptr->current_text = (png_charp)png_malloc(png_ptr,
  186093. (png_uint_32)(length+1));
  186094. png_ptr->current_text[length] = '\0';
  186095. png_ptr->current_text_ptr = png_ptr->current_text;
  186096. png_ptr->current_text_size = (png_size_t)length;
  186097. png_ptr->current_text_left = (png_size_t)length;
  186098. png_ptr->process_mode = PNG_READ_iTXt_MODE;
  186099. }
  186100. void /* PRIVATE */
  186101. png_push_read_iTXt(png_structp png_ptr, png_infop info_ptr)
  186102. {
  186103. if (png_ptr->buffer_size && png_ptr->current_text_left)
  186104. {
  186105. png_size_t text_size;
  186106. if (png_ptr->buffer_size < png_ptr->current_text_left)
  186107. text_size = png_ptr->buffer_size;
  186108. else
  186109. text_size = png_ptr->current_text_left;
  186110. png_crc_read(png_ptr, (png_bytep)png_ptr->current_text_ptr, text_size);
  186111. png_ptr->current_text_left -= text_size;
  186112. png_ptr->current_text_ptr += text_size;
  186113. }
  186114. if (!(png_ptr->current_text_left))
  186115. {
  186116. png_textp text_ptr;
  186117. png_charp key;
  186118. int comp_flag;
  186119. png_charp lang;
  186120. png_charp lang_key;
  186121. png_charp text;
  186122. int ret;
  186123. if (png_ptr->buffer_size < 4)
  186124. {
  186125. png_push_save_buffer(png_ptr);
  186126. return;
  186127. }
  186128. png_push_crc_finish(png_ptr);
  186129. #if defined(PNG_MAX_MALLOC_64K)
  186130. if (png_ptr->skip_length)
  186131. return;
  186132. #endif
  186133. key = png_ptr->current_text;
  186134. for (lang = key; *lang; lang++)
  186135. /* empty loop */ ;
  186136. if (lang < key + png_ptr->current_text_size - 3)
  186137. lang++;
  186138. comp_flag = *lang++;
  186139. lang++; /* skip comp_type, always zero */
  186140. for (lang_key = lang; *lang_key; lang_key++)
  186141. /* empty loop */ ;
  186142. lang_key++; /* skip NUL separator */
  186143. text=lang_key;
  186144. if (lang_key < key + png_ptr->current_text_size - 1)
  186145. {
  186146. for (; *text; text++)
  186147. /* empty loop */ ;
  186148. }
  186149. if (text < key + png_ptr->current_text_size)
  186150. text++;
  186151. text_ptr = (png_textp)png_malloc(png_ptr,
  186152. (png_uint_32)png_sizeof(png_text));
  186153. text_ptr->compression = comp_flag + 2;
  186154. text_ptr->key = key;
  186155. text_ptr->lang = lang;
  186156. text_ptr->lang_key = lang_key;
  186157. text_ptr->text = text;
  186158. text_ptr->text_length = 0;
  186159. text_ptr->itxt_length = png_strlen(text);
  186160. ret = png_set_text_2(png_ptr, info_ptr, text_ptr, 1);
  186161. png_ptr->current_text = NULL;
  186162. png_free(png_ptr, text_ptr);
  186163. if (ret)
  186164. png_warning(png_ptr, "Insufficient memory to store iTXt chunk.");
  186165. }
  186166. }
  186167. #endif
  186168. /* This function is called when we haven't found a handler for this
  186169. * chunk. If there isn't a problem with the chunk itself (ie a bad chunk
  186170. * name or a critical chunk), the chunk is (currently) silently ignored.
  186171. */
  186172. void /* PRIVATE */
  186173. png_push_handle_unknown(png_structp png_ptr, png_infop info_ptr, png_uint_32
  186174. length)
  186175. {
  186176. png_uint_32 skip=0;
  186177. png_check_chunk_name(png_ptr, png_ptr->chunk_name);
  186178. if (!(png_ptr->chunk_name[0] & 0x20))
  186179. {
  186180. #if defined(PNG_READ_UNKNOWN_CHUNKS_SUPPORTED)
  186181. if(png_handle_as_unknown(png_ptr, png_ptr->chunk_name) !=
  186182. PNG_HANDLE_CHUNK_ALWAYS
  186183. #if defined(PNG_READ_USER_CHUNKS_SUPPORTED)
  186184. && png_ptr->read_user_chunk_fn == NULL
  186185. #endif
  186186. )
  186187. #endif
  186188. png_chunk_error(png_ptr, "unknown critical chunk");
  186189. info_ptr = info_ptr; /* to quiet some compiler warnings */
  186190. }
  186191. #if defined(PNG_READ_UNKNOWN_CHUNKS_SUPPORTED)
  186192. if (png_ptr->flags & PNG_FLAG_KEEP_UNKNOWN_CHUNKS)
  186193. {
  186194. #ifdef PNG_MAX_MALLOC_64K
  186195. if (length > (png_uint_32)65535L)
  186196. {
  186197. png_warning(png_ptr, "unknown chunk too large to fit in memory");
  186198. skip = length - (png_uint_32)65535L;
  186199. length = (png_uint_32)65535L;
  186200. }
  186201. #endif
  186202. png_strncpy((png_charp)png_ptr->unknown_chunk.name,
  186203. (png_charp)png_ptr->chunk_name, 5);
  186204. png_ptr->unknown_chunk.data = (png_bytep)png_malloc(png_ptr, length);
  186205. png_ptr->unknown_chunk.size = (png_size_t)length;
  186206. png_crc_read(png_ptr, (png_bytep)png_ptr->unknown_chunk.data, length);
  186207. #if defined(PNG_READ_USER_CHUNKS_SUPPORTED)
  186208. if(png_ptr->read_user_chunk_fn != NULL)
  186209. {
  186210. /* callback to user unknown chunk handler */
  186211. int ret;
  186212. ret = (*(png_ptr->read_user_chunk_fn))
  186213. (png_ptr, &png_ptr->unknown_chunk);
  186214. if (ret < 0)
  186215. png_chunk_error(png_ptr, "error in user chunk");
  186216. if (ret == 0)
  186217. {
  186218. if (!(png_ptr->chunk_name[0] & 0x20))
  186219. if(png_handle_as_unknown(png_ptr, png_ptr->chunk_name) !=
  186220. PNG_HANDLE_CHUNK_ALWAYS)
  186221. png_chunk_error(png_ptr, "unknown critical chunk");
  186222. png_set_unknown_chunks(png_ptr, info_ptr,
  186223. &png_ptr->unknown_chunk, 1);
  186224. }
  186225. }
  186226. #else
  186227. png_set_unknown_chunks(png_ptr, info_ptr, &png_ptr->unknown_chunk, 1);
  186228. #endif
  186229. png_free(png_ptr, png_ptr->unknown_chunk.data);
  186230. png_ptr->unknown_chunk.data = NULL;
  186231. }
  186232. else
  186233. #endif
  186234. skip=length;
  186235. png_push_crc_skip(png_ptr, skip);
  186236. }
  186237. void /* PRIVATE */
  186238. png_push_have_info(png_structp png_ptr, png_infop info_ptr)
  186239. {
  186240. if (png_ptr->info_fn != NULL)
  186241. (*(png_ptr->info_fn))(png_ptr, info_ptr);
  186242. }
  186243. void /* PRIVATE */
  186244. png_push_have_end(png_structp png_ptr, png_infop info_ptr)
  186245. {
  186246. if (png_ptr->end_fn != NULL)
  186247. (*(png_ptr->end_fn))(png_ptr, info_ptr);
  186248. }
  186249. void /* PRIVATE */
  186250. png_push_have_row(png_structp png_ptr, png_bytep row)
  186251. {
  186252. if (png_ptr->row_fn != NULL)
  186253. (*(png_ptr->row_fn))(png_ptr, row, png_ptr->row_number,
  186254. (int)png_ptr->pass);
  186255. }
  186256. void PNGAPI
  186257. png_progressive_combine_row (png_structp png_ptr,
  186258. png_bytep old_row, png_bytep new_row)
  186259. {
  186260. #ifdef PNG_USE_LOCAL_ARRAYS
  186261. PNG_CONST int FARDATA png_pass_dsp_mask[7] =
  186262. {0xff, 0x0f, 0xff, 0x33, 0xff, 0x55, 0xff};
  186263. #endif
  186264. if(png_ptr == NULL) return;
  186265. if (new_row != NULL) /* new_row must == png_ptr->row_buf here. */
  186266. png_combine_row(png_ptr, old_row, png_pass_dsp_mask[png_ptr->pass]);
  186267. }
  186268. void PNGAPI
  186269. png_set_progressive_read_fn(png_structp png_ptr, png_voidp progressive_ptr,
  186270. png_progressive_info_ptr info_fn, png_progressive_row_ptr row_fn,
  186271. png_progressive_end_ptr end_fn)
  186272. {
  186273. if(png_ptr == NULL) return;
  186274. png_ptr->info_fn = info_fn;
  186275. png_ptr->row_fn = row_fn;
  186276. png_ptr->end_fn = end_fn;
  186277. png_set_read_fn(png_ptr, progressive_ptr, png_push_fill_buffer);
  186278. }
  186279. png_voidp PNGAPI
  186280. png_get_progressive_ptr(png_structp png_ptr)
  186281. {
  186282. if(png_ptr == NULL) return (NULL);
  186283. return png_ptr->io_ptr;
  186284. }
  186285. #endif /* PNG_PROGRESSIVE_READ_SUPPORTED */
  186286. /*** End of inlined file: pngpread.c ***/
  186287. /*** Start of inlined file: pngrio.c ***/
  186288. /* pngrio.c - functions for data input
  186289. *
  186290. * Last changed in libpng 1.2.13 November 13, 2006
  186291. * For conditions of distribution and use, see copyright notice in png.h
  186292. * Copyright (c) 1998-2006 Glenn Randers-Pehrson
  186293. * (Version 0.96 Copyright (c) 1996, 1997 Andreas Dilger)
  186294. * (Version 0.88 Copyright (c) 1995, 1996 Guy Eric Schalnat, Group 42, Inc.)
  186295. *
  186296. * This file provides a location for all input. Users who need
  186297. * special handling are expected to write a function that has the same
  186298. * arguments as this and performs a similar function, but that possibly
  186299. * has a different input method. Note that you shouldn't change this
  186300. * function, but rather write a replacement function and then make
  186301. * libpng use it at run time with png_set_read_fn(...).
  186302. */
  186303. #define PNG_INTERNAL
  186304. #if defined(PNG_READ_SUPPORTED)
  186305. /* Read the data from whatever input you are using. The default routine
  186306. reads from a file pointer. Note that this routine sometimes gets called
  186307. with very small lengths, so you should implement some kind of simple
  186308. buffering if you are using unbuffered reads. This should never be asked
  186309. to read more then 64K on a 16 bit machine. */
  186310. void /* PRIVATE */
  186311. png_read_data(png_structp png_ptr, png_bytep data, png_size_t length)
  186312. {
  186313. png_debug1(4,"reading %d bytes\n", (int)length);
  186314. if (png_ptr->read_data_fn != NULL)
  186315. (*(png_ptr->read_data_fn))(png_ptr, data, length);
  186316. else
  186317. png_error(png_ptr, "Call to NULL read function");
  186318. }
  186319. #if !defined(PNG_NO_STDIO)
  186320. /* This is the function that does the actual reading of data. If you are
  186321. not reading from a standard C stream, you should create a replacement
  186322. read_data function and use it at run time with png_set_read_fn(), rather
  186323. than changing the library. */
  186324. #ifndef USE_FAR_KEYWORD
  186325. void PNGAPI
  186326. png_default_read_data(png_structp png_ptr, png_bytep data, png_size_t length)
  186327. {
  186328. png_size_t check;
  186329. if(png_ptr == NULL) return;
  186330. /* fread() returns 0 on error, so it is OK to store this in a png_size_t
  186331. * instead of an int, which is what fread() actually returns.
  186332. */
  186333. #if defined(_WIN32_WCE)
  186334. if ( !ReadFile((HANDLE)(png_ptr->io_ptr), data, length, &check, NULL) )
  186335. check = 0;
  186336. #else
  186337. check = (png_size_t)fread(data, (png_size_t)1, length,
  186338. (png_FILE_p)png_ptr->io_ptr);
  186339. #endif
  186340. if (check != length)
  186341. png_error(png_ptr, "Read Error");
  186342. }
  186343. #else
  186344. /* this is the model-independent version. Since the standard I/O library
  186345. can't handle far buffers in the medium and small models, we have to copy
  186346. the data.
  186347. */
  186348. #define NEAR_BUF_SIZE 1024
  186349. #define MIN(a,b) (a <= b ? a : b)
  186350. static void PNGAPI
  186351. png_default_read_data(png_structp png_ptr, png_bytep data, png_size_t length)
  186352. {
  186353. int check;
  186354. png_byte *n_data;
  186355. png_FILE_p io_ptr;
  186356. if(png_ptr == NULL) return;
  186357. /* Check if data really is near. If so, use usual code. */
  186358. n_data = (png_byte *)CVT_PTR_NOCHECK(data);
  186359. io_ptr = (png_FILE_p)CVT_PTR(png_ptr->io_ptr);
  186360. if ((png_bytep)n_data == data)
  186361. {
  186362. #if defined(_WIN32_WCE)
  186363. if ( !ReadFile((HANDLE)(png_ptr->io_ptr), data, length, &check, NULL) )
  186364. check = 0;
  186365. #else
  186366. check = fread(n_data, 1, length, io_ptr);
  186367. #endif
  186368. }
  186369. else
  186370. {
  186371. png_byte buf[NEAR_BUF_SIZE];
  186372. png_size_t read, remaining, err;
  186373. check = 0;
  186374. remaining = length;
  186375. do
  186376. {
  186377. read = MIN(NEAR_BUF_SIZE, remaining);
  186378. #if defined(_WIN32_WCE)
  186379. if ( !ReadFile((HANDLE)(io_ptr), buf, read, &err, NULL) )
  186380. err = 0;
  186381. #else
  186382. err = fread(buf, (png_size_t)1, read, io_ptr);
  186383. #endif
  186384. png_memcpy(data, buf, read); /* copy far buffer to near buffer */
  186385. if(err != read)
  186386. break;
  186387. else
  186388. check += err;
  186389. data += read;
  186390. remaining -= read;
  186391. }
  186392. while (remaining != 0);
  186393. }
  186394. if ((png_uint_32)check != (png_uint_32)length)
  186395. png_error(png_ptr, "read Error");
  186396. }
  186397. #endif
  186398. #endif
  186399. /* This function allows the application to supply a new input function
  186400. for libpng if standard C streams aren't being used.
  186401. This function takes as its arguments:
  186402. png_ptr - pointer to a png input data structure
  186403. io_ptr - pointer to user supplied structure containing info about
  186404. the input functions. May be NULL.
  186405. read_data_fn - pointer to a new input function that takes as its
  186406. arguments a pointer to a png_struct, a pointer to
  186407. a location where input data can be stored, and a 32-bit
  186408. unsigned int that is the number of bytes to be read.
  186409. To exit and output any fatal error messages the new write
  186410. function should call png_error(png_ptr, "Error msg"). */
  186411. void PNGAPI
  186412. png_set_read_fn(png_structp png_ptr, png_voidp io_ptr,
  186413. png_rw_ptr read_data_fn)
  186414. {
  186415. if(png_ptr == NULL) return;
  186416. png_ptr->io_ptr = io_ptr;
  186417. #if !defined(PNG_NO_STDIO)
  186418. if (read_data_fn != NULL)
  186419. png_ptr->read_data_fn = read_data_fn;
  186420. else
  186421. png_ptr->read_data_fn = png_default_read_data;
  186422. #else
  186423. png_ptr->read_data_fn = read_data_fn;
  186424. #endif
  186425. /* It is an error to write to a read device */
  186426. if (png_ptr->write_data_fn != NULL)
  186427. {
  186428. png_ptr->write_data_fn = NULL;
  186429. png_warning(png_ptr,
  186430. "It's an error to set both read_data_fn and write_data_fn in the ");
  186431. png_warning(png_ptr,
  186432. "same structure. Resetting write_data_fn to NULL.");
  186433. }
  186434. #if defined(PNG_WRITE_FLUSH_SUPPORTED)
  186435. png_ptr->output_flush_fn = NULL;
  186436. #endif
  186437. }
  186438. #endif /* PNG_READ_SUPPORTED */
  186439. /*** End of inlined file: pngrio.c ***/
  186440. /*** Start of inlined file: pngrtran.c ***/
  186441. /* pngrtran.c - transforms the data in a row for PNG readers
  186442. *
  186443. * Last changed in libpng 1.2.21 [October 4, 2007]
  186444. * For conditions of distribution and use, see copyright notice in png.h
  186445. * Copyright (c) 1998-2007 Glenn Randers-Pehrson
  186446. * (Version 0.96 Copyright (c) 1996, 1997 Andreas Dilger)
  186447. * (Version 0.88 Copyright (c) 1995, 1996 Guy Eric Schalnat, Group 42, Inc.)
  186448. *
  186449. * This file contains functions optionally called by an application
  186450. * in order to tell libpng how to handle data when reading a PNG.
  186451. * Transformations that are used in both reading and writing are
  186452. * in pngtrans.c.
  186453. */
  186454. #define PNG_INTERNAL
  186455. #if defined(PNG_READ_SUPPORTED)
  186456. /* Set the action on getting a CRC error for an ancillary or critical chunk. */
  186457. void PNGAPI
  186458. png_set_crc_action(png_structp png_ptr, int crit_action, int ancil_action)
  186459. {
  186460. png_debug(1, "in png_set_crc_action\n");
  186461. /* Tell libpng how we react to CRC errors in critical chunks */
  186462. if(png_ptr == NULL) return;
  186463. switch (crit_action)
  186464. {
  186465. case PNG_CRC_NO_CHANGE: /* leave setting as is */
  186466. break;
  186467. case PNG_CRC_WARN_USE: /* warn/use data */
  186468. png_ptr->flags &= ~PNG_FLAG_CRC_CRITICAL_MASK;
  186469. png_ptr->flags |= PNG_FLAG_CRC_CRITICAL_USE;
  186470. break;
  186471. case PNG_CRC_QUIET_USE: /* quiet/use data */
  186472. png_ptr->flags &= ~PNG_FLAG_CRC_CRITICAL_MASK;
  186473. png_ptr->flags |= PNG_FLAG_CRC_CRITICAL_USE |
  186474. PNG_FLAG_CRC_CRITICAL_IGNORE;
  186475. break;
  186476. case PNG_CRC_WARN_DISCARD: /* not a valid action for critical data */
  186477. png_warning(png_ptr, "Can't discard critical data on CRC error.");
  186478. case PNG_CRC_ERROR_QUIT: /* error/quit */
  186479. case PNG_CRC_DEFAULT:
  186480. default:
  186481. png_ptr->flags &= ~PNG_FLAG_CRC_CRITICAL_MASK;
  186482. break;
  186483. }
  186484. switch (ancil_action)
  186485. {
  186486. case PNG_CRC_NO_CHANGE: /* leave setting as is */
  186487. break;
  186488. case PNG_CRC_WARN_USE: /* warn/use data */
  186489. png_ptr->flags &= ~PNG_FLAG_CRC_ANCILLARY_MASK;
  186490. png_ptr->flags |= PNG_FLAG_CRC_ANCILLARY_USE;
  186491. break;
  186492. case PNG_CRC_QUIET_USE: /* quiet/use data */
  186493. png_ptr->flags &= ~PNG_FLAG_CRC_ANCILLARY_MASK;
  186494. png_ptr->flags |= PNG_FLAG_CRC_ANCILLARY_USE |
  186495. PNG_FLAG_CRC_ANCILLARY_NOWARN;
  186496. break;
  186497. case PNG_CRC_ERROR_QUIT: /* error/quit */
  186498. png_ptr->flags &= ~PNG_FLAG_CRC_ANCILLARY_MASK;
  186499. png_ptr->flags |= PNG_FLAG_CRC_ANCILLARY_NOWARN;
  186500. break;
  186501. case PNG_CRC_WARN_DISCARD: /* warn/discard data */
  186502. case PNG_CRC_DEFAULT:
  186503. default:
  186504. png_ptr->flags &= ~PNG_FLAG_CRC_ANCILLARY_MASK;
  186505. break;
  186506. }
  186507. }
  186508. #if defined(PNG_READ_BACKGROUND_SUPPORTED) && \
  186509. defined(PNG_FLOATING_POINT_SUPPORTED)
  186510. /* handle alpha and tRNS via a background color */
  186511. void PNGAPI
  186512. png_set_background(png_structp png_ptr,
  186513. png_color_16p background_color, int background_gamma_code,
  186514. int need_expand, double background_gamma)
  186515. {
  186516. png_debug(1, "in png_set_background\n");
  186517. if(png_ptr == NULL) return;
  186518. if (background_gamma_code == PNG_BACKGROUND_GAMMA_UNKNOWN)
  186519. {
  186520. png_warning(png_ptr, "Application must supply a known background gamma");
  186521. return;
  186522. }
  186523. png_ptr->transformations |= PNG_BACKGROUND;
  186524. png_memcpy(&(png_ptr->background), background_color,
  186525. png_sizeof(png_color_16));
  186526. png_ptr->background_gamma = (float)background_gamma;
  186527. png_ptr->background_gamma_type = (png_byte)(background_gamma_code);
  186528. png_ptr->transformations |= (need_expand ? PNG_BACKGROUND_EXPAND : 0);
  186529. }
  186530. #endif
  186531. #if defined(PNG_READ_16_TO_8_SUPPORTED)
  186532. /* strip 16 bit depth files to 8 bit depth */
  186533. void PNGAPI
  186534. png_set_strip_16(png_structp png_ptr)
  186535. {
  186536. png_debug(1, "in png_set_strip_16\n");
  186537. if(png_ptr == NULL) return;
  186538. png_ptr->transformations |= PNG_16_TO_8;
  186539. }
  186540. #endif
  186541. #if defined(PNG_READ_STRIP_ALPHA_SUPPORTED)
  186542. void PNGAPI
  186543. png_set_strip_alpha(png_structp png_ptr)
  186544. {
  186545. png_debug(1, "in png_set_strip_alpha\n");
  186546. if(png_ptr == NULL) return;
  186547. png_ptr->flags |= PNG_FLAG_STRIP_ALPHA;
  186548. }
  186549. #endif
  186550. #if defined(PNG_READ_DITHER_SUPPORTED)
  186551. /* Dither file to 8 bit. Supply a palette, the current number
  186552. * of elements in the palette, the maximum number of elements
  186553. * allowed, and a histogram if possible. If the current number
  186554. * of colors is greater then the maximum number, the palette will be
  186555. * modified to fit in the maximum number. "full_dither" indicates
  186556. * whether we need a dithering cube set up for RGB images, or if we
  186557. * simply are reducing the number of colors in a paletted image.
  186558. */
  186559. typedef struct png_dsort_struct
  186560. {
  186561. struct png_dsort_struct FAR * next;
  186562. png_byte left;
  186563. png_byte right;
  186564. } png_dsort;
  186565. typedef png_dsort FAR * png_dsortp;
  186566. typedef png_dsort FAR * FAR * png_dsortpp;
  186567. void PNGAPI
  186568. png_set_dither(png_structp png_ptr, png_colorp palette,
  186569. int num_palette, int maximum_colors, png_uint_16p histogram,
  186570. int full_dither)
  186571. {
  186572. png_debug(1, "in png_set_dither\n");
  186573. if(png_ptr == NULL) return;
  186574. png_ptr->transformations |= PNG_DITHER;
  186575. if (!full_dither)
  186576. {
  186577. int i;
  186578. png_ptr->dither_index = (png_bytep)png_malloc(png_ptr,
  186579. (png_uint_32)(num_palette * png_sizeof (png_byte)));
  186580. for (i = 0; i < num_palette; i++)
  186581. png_ptr->dither_index[i] = (png_byte)i;
  186582. }
  186583. if (num_palette > maximum_colors)
  186584. {
  186585. if (histogram != NULL)
  186586. {
  186587. /* This is easy enough, just throw out the least used colors.
  186588. Perhaps not the best solution, but good enough. */
  186589. int i;
  186590. /* initialize an array to sort colors */
  186591. png_ptr->dither_sort = (png_bytep)png_malloc(png_ptr,
  186592. (png_uint_32)(num_palette * png_sizeof (png_byte)));
  186593. /* initialize the dither_sort array */
  186594. for (i = 0; i < num_palette; i++)
  186595. png_ptr->dither_sort[i] = (png_byte)i;
  186596. /* Find the least used palette entries by starting a
  186597. bubble sort, and running it until we have sorted
  186598. out enough colors. Note that we don't care about
  186599. sorting all the colors, just finding which are
  186600. least used. */
  186601. for (i = num_palette - 1; i >= maximum_colors; i--)
  186602. {
  186603. int done; /* to stop early if the list is pre-sorted */
  186604. int j;
  186605. done = 1;
  186606. for (j = 0; j < i; j++)
  186607. {
  186608. if (histogram[png_ptr->dither_sort[j]]
  186609. < histogram[png_ptr->dither_sort[j + 1]])
  186610. {
  186611. png_byte t;
  186612. t = png_ptr->dither_sort[j];
  186613. png_ptr->dither_sort[j] = png_ptr->dither_sort[j + 1];
  186614. png_ptr->dither_sort[j + 1] = t;
  186615. done = 0;
  186616. }
  186617. }
  186618. if (done)
  186619. break;
  186620. }
  186621. /* swap the palette around, and set up a table, if necessary */
  186622. if (full_dither)
  186623. {
  186624. int j = num_palette;
  186625. /* put all the useful colors within the max, but don't
  186626. move the others */
  186627. for (i = 0; i < maximum_colors; i++)
  186628. {
  186629. if ((int)png_ptr->dither_sort[i] >= maximum_colors)
  186630. {
  186631. do
  186632. j--;
  186633. while ((int)png_ptr->dither_sort[j] >= maximum_colors);
  186634. palette[i] = palette[j];
  186635. }
  186636. }
  186637. }
  186638. else
  186639. {
  186640. int j = num_palette;
  186641. /* move all the used colors inside the max limit, and
  186642. develop a translation table */
  186643. for (i = 0; i < maximum_colors; i++)
  186644. {
  186645. /* only move the colors we need to */
  186646. if ((int)png_ptr->dither_sort[i] >= maximum_colors)
  186647. {
  186648. png_color tmp_color;
  186649. do
  186650. j--;
  186651. while ((int)png_ptr->dither_sort[j] >= maximum_colors);
  186652. tmp_color = palette[j];
  186653. palette[j] = palette[i];
  186654. palette[i] = tmp_color;
  186655. /* indicate where the color went */
  186656. png_ptr->dither_index[j] = (png_byte)i;
  186657. png_ptr->dither_index[i] = (png_byte)j;
  186658. }
  186659. }
  186660. /* find closest color for those colors we are not using */
  186661. for (i = 0; i < num_palette; i++)
  186662. {
  186663. if ((int)png_ptr->dither_index[i] >= maximum_colors)
  186664. {
  186665. int min_d, k, min_k, d_index;
  186666. /* find the closest color to one we threw out */
  186667. d_index = png_ptr->dither_index[i];
  186668. min_d = PNG_COLOR_DIST(palette[d_index], palette[0]);
  186669. for (k = 1, min_k = 0; k < maximum_colors; k++)
  186670. {
  186671. int d;
  186672. d = PNG_COLOR_DIST(palette[d_index], palette[k]);
  186673. if (d < min_d)
  186674. {
  186675. min_d = d;
  186676. min_k = k;
  186677. }
  186678. }
  186679. /* point to closest color */
  186680. png_ptr->dither_index[i] = (png_byte)min_k;
  186681. }
  186682. }
  186683. }
  186684. png_free(png_ptr, png_ptr->dither_sort);
  186685. png_ptr->dither_sort=NULL;
  186686. }
  186687. else
  186688. {
  186689. /* This is much harder to do simply (and quickly). Perhaps
  186690. we need to go through a median cut routine, but those
  186691. don't always behave themselves with only a few colors
  186692. as input. So we will just find the closest two colors,
  186693. and throw out one of them (chosen somewhat randomly).
  186694. [We don't understand this at all, so if someone wants to
  186695. work on improving it, be our guest - AED, GRP]
  186696. */
  186697. int i;
  186698. int max_d;
  186699. int num_new_palette;
  186700. png_dsortp t;
  186701. png_dsortpp hash;
  186702. t=NULL;
  186703. /* initialize palette index arrays */
  186704. png_ptr->index_to_palette = (png_bytep)png_malloc(png_ptr,
  186705. (png_uint_32)(num_palette * png_sizeof (png_byte)));
  186706. png_ptr->palette_to_index = (png_bytep)png_malloc(png_ptr,
  186707. (png_uint_32)(num_palette * png_sizeof (png_byte)));
  186708. /* initialize the sort array */
  186709. for (i = 0; i < num_palette; i++)
  186710. {
  186711. png_ptr->index_to_palette[i] = (png_byte)i;
  186712. png_ptr->palette_to_index[i] = (png_byte)i;
  186713. }
  186714. hash = (png_dsortpp)png_malloc(png_ptr, (png_uint_32)(769 *
  186715. png_sizeof (png_dsortp)));
  186716. for (i = 0; i < 769; i++)
  186717. hash[i] = NULL;
  186718. /* png_memset(hash, 0, 769 * png_sizeof (png_dsortp)); */
  186719. num_new_palette = num_palette;
  186720. /* initial wild guess at how far apart the farthest pixel
  186721. pair we will be eliminating will be. Larger
  186722. numbers mean more areas will be allocated, Smaller
  186723. numbers run the risk of not saving enough data, and
  186724. having to do this all over again.
  186725. I have not done extensive checking on this number.
  186726. */
  186727. max_d = 96;
  186728. while (num_new_palette > maximum_colors)
  186729. {
  186730. for (i = 0; i < num_new_palette - 1; i++)
  186731. {
  186732. int j;
  186733. for (j = i + 1; j < num_new_palette; j++)
  186734. {
  186735. int d;
  186736. d = PNG_COLOR_DIST(palette[i], palette[j]);
  186737. if (d <= max_d)
  186738. {
  186739. t = (png_dsortp)png_malloc_warn(png_ptr,
  186740. (png_uint_32)(png_sizeof(png_dsort)));
  186741. if (t == NULL)
  186742. break;
  186743. t->next = hash[d];
  186744. t->left = (png_byte)i;
  186745. t->right = (png_byte)j;
  186746. hash[d] = t;
  186747. }
  186748. }
  186749. if (t == NULL)
  186750. break;
  186751. }
  186752. if (t != NULL)
  186753. for (i = 0; i <= max_d; i++)
  186754. {
  186755. if (hash[i] != NULL)
  186756. {
  186757. png_dsortp p;
  186758. for (p = hash[i]; p; p = p->next)
  186759. {
  186760. if ((int)png_ptr->index_to_palette[p->left]
  186761. < num_new_palette &&
  186762. (int)png_ptr->index_to_palette[p->right]
  186763. < num_new_palette)
  186764. {
  186765. int j, next_j;
  186766. if (num_new_palette & 0x01)
  186767. {
  186768. j = p->left;
  186769. next_j = p->right;
  186770. }
  186771. else
  186772. {
  186773. j = p->right;
  186774. next_j = p->left;
  186775. }
  186776. num_new_palette--;
  186777. palette[png_ptr->index_to_palette[j]]
  186778. = palette[num_new_palette];
  186779. if (!full_dither)
  186780. {
  186781. int k;
  186782. for (k = 0; k < num_palette; k++)
  186783. {
  186784. if (png_ptr->dither_index[k] ==
  186785. png_ptr->index_to_palette[j])
  186786. png_ptr->dither_index[k] =
  186787. png_ptr->index_to_palette[next_j];
  186788. if ((int)png_ptr->dither_index[k] ==
  186789. num_new_palette)
  186790. png_ptr->dither_index[k] =
  186791. png_ptr->index_to_palette[j];
  186792. }
  186793. }
  186794. png_ptr->index_to_palette[png_ptr->palette_to_index
  186795. [num_new_palette]] = png_ptr->index_to_palette[j];
  186796. png_ptr->palette_to_index[png_ptr->index_to_palette[j]]
  186797. = png_ptr->palette_to_index[num_new_palette];
  186798. png_ptr->index_to_palette[j] = (png_byte)num_new_palette;
  186799. png_ptr->palette_to_index[num_new_palette] = (png_byte)j;
  186800. }
  186801. if (num_new_palette <= maximum_colors)
  186802. break;
  186803. }
  186804. if (num_new_palette <= maximum_colors)
  186805. break;
  186806. }
  186807. }
  186808. for (i = 0; i < 769; i++)
  186809. {
  186810. if (hash[i] != NULL)
  186811. {
  186812. png_dsortp p = hash[i];
  186813. while (p)
  186814. {
  186815. t = p->next;
  186816. png_free(png_ptr, p);
  186817. p = t;
  186818. }
  186819. }
  186820. hash[i] = 0;
  186821. }
  186822. max_d += 96;
  186823. }
  186824. png_free(png_ptr, hash);
  186825. png_free(png_ptr, png_ptr->palette_to_index);
  186826. png_free(png_ptr, png_ptr->index_to_palette);
  186827. png_ptr->palette_to_index=NULL;
  186828. png_ptr->index_to_palette=NULL;
  186829. }
  186830. num_palette = maximum_colors;
  186831. }
  186832. if (png_ptr->palette == NULL)
  186833. {
  186834. png_ptr->palette = palette;
  186835. }
  186836. png_ptr->num_palette = (png_uint_16)num_palette;
  186837. if (full_dither)
  186838. {
  186839. int i;
  186840. png_bytep distance;
  186841. int total_bits = PNG_DITHER_RED_BITS + PNG_DITHER_GREEN_BITS +
  186842. PNG_DITHER_BLUE_BITS;
  186843. int num_red = (1 << PNG_DITHER_RED_BITS);
  186844. int num_green = (1 << PNG_DITHER_GREEN_BITS);
  186845. int num_blue = (1 << PNG_DITHER_BLUE_BITS);
  186846. png_size_t num_entries = ((png_size_t)1 << total_bits);
  186847. png_ptr->palette_lookup = (png_bytep )png_malloc(png_ptr,
  186848. (png_uint_32)(num_entries * png_sizeof (png_byte)));
  186849. png_memset(png_ptr->palette_lookup, 0, num_entries *
  186850. png_sizeof (png_byte));
  186851. distance = (png_bytep)png_malloc(png_ptr, (png_uint_32)(num_entries *
  186852. png_sizeof(png_byte)));
  186853. png_memset(distance, 0xff, num_entries * png_sizeof(png_byte));
  186854. for (i = 0; i < num_palette; i++)
  186855. {
  186856. int ir, ig, ib;
  186857. int r = (palette[i].red >> (8 - PNG_DITHER_RED_BITS));
  186858. int g = (palette[i].green >> (8 - PNG_DITHER_GREEN_BITS));
  186859. int b = (palette[i].blue >> (8 - PNG_DITHER_BLUE_BITS));
  186860. for (ir = 0; ir < num_red; ir++)
  186861. {
  186862. /* int dr = abs(ir - r); */
  186863. int dr = ((ir > r) ? ir - r : r - ir);
  186864. int index_r = (ir << (PNG_DITHER_BLUE_BITS + PNG_DITHER_GREEN_BITS));
  186865. for (ig = 0; ig < num_green; ig++)
  186866. {
  186867. /* int dg = abs(ig - g); */
  186868. int dg = ((ig > g) ? ig - g : g - ig);
  186869. int dt = dr + dg;
  186870. int dm = ((dr > dg) ? dr : dg);
  186871. int index_g = index_r | (ig << PNG_DITHER_BLUE_BITS);
  186872. for (ib = 0; ib < num_blue; ib++)
  186873. {
  186874. int d_index = index_g | ib;
  186875. /* int db = abs(ib - b); */
  186876. int db = ((ib > b) ? ib - b : b - ib);
  186877. int dmax = ((dm > db) ? dm : db);
  186878. int d = dmax + dt + db;
  186879. if (d < (int)distance[d_index])
  186880. {
  186881. distance[d_index] = (png_byte)d;
  186882. png_ptr->palette_lookup[d_index] = (png_byte)i;
  186883. }
  186884. }
  186885. }
  186886. }
  186887. }
  186888. png_free(png_ptr, distance);
  186889. }
  186890. }
  186891. #endif
  186892. #if defined(PNG_READ_GAMMA_SUPPORTED) && defined(PNG_FLOATING_POINT_SUPPORTED)
  186893. /* Transform the image from the file_gamma to the screen_gamma. We
  186894. * only do transformations on images where the file_gamma and screen_gamma
  186895. * are not close reciprocals, otherwise it slows things down slightly, and
  186896. * also needlessly introduces small errors.
  186897. *
  186898. * We will turn off gamma transformation later if no semitransparent entries
  186899. * are present in the tRNS array for palette images. We can't do it here
  186900. * because we don't necessarily have the tRNS chunk yet.
  186901. */
  186902. void PNGAPI
  186903. png_set_gamma(png_structp png_ptr, double scrn_gamma, double file_gamma)
  186904. {
  186905. png_debug(1, "in png_set_gamma\n");
  186906. if(png_ptr == NULL) return;
  186907. if ((fabs(scrn_gamma * file_gamma - 1.0) > PNG_GAMMA_THRESHOLD) ||
  186908. (png_ptr->color_type & PNG_COLOR_MASK_ALPHA) ||
  186909. (png_ptr->color_type == PNG_COLOR_TYPE_PALETTE))
  186910. png_ptr->transformations |= PNG_GAMMA;
  186911. png_ptr->gamma = (float)file_gamma;
  186912. png_ptr->screen_gamma = (float)scrn_gamma;
  186913. }
  186914. #endif
  186915. #if defined(PNG_READ_EXPAND_SUPPORTED)
  186916. /* Expand paletted images to RGB, expand grayscale images of
  186917. * less than 8-bit depth to 8-bit depth, and expand tRNS chunks
  186918. * to alpha channels.
  186919. */
  186920. void PNGAPI
  186921. png_set_expand(png_structp png_ptr)
  186922. {
  186923. png_debug(1, "in png_set_expand\n");
  186924. if(png_ptr == NULL) return;
  186925. png_ptr->transformations |= (PNG_EXPAND | PNG_EXPAND_tRNS);
  186926. #ifdef PNG_WARN_UNINITIALIZED_ROW
  186927. png_ptr->flags &= ~PNG_FLAG_ROW_INIT;
  186928. #endif
  186929. }
  186930. /* GRR 19990627: the following three functions currently are identical
  186931. * to png_set_expand(). However, it is entirely reasonable that someone
  186932. * might wish to expand an indexed image to RGB but *not* expand a single,
  186933. * fully transparent palette entry to a full alpha channel--perhaps instead
  186934. * convert tRNS to the grayscale/RGB format (16-bit RGB value), or replace
  186935. * the transparent color with a particular RGB value, or drop tRNS entirely.
  186936. * IOW, a future version of the library may make the transformations flag
  186937. * a bit more fine-grained, with separate bits for each of these three
  186938. * functions.
  186939. *
  186940. * More to the point, these functions make it obvious what libpng will be
  186941. * doing, whereas "expand" can (and does) mean any number of things.
  186942. *
  186943. * GRP 20060307: In libpng-1.4.0, png_set_gray_1_2_4_to_8() was modified
  186944. * to expand only the sample depth but not to expand the tRNS to alpha.
  186945. */
  186946. /* Expand paletted images to RGB. */
  186947. void PNGAPI
  186948. png_set_palette_to_rgb(png_structp png_ptr)
  186949. {
  186950. png_debug(1, "in png_set_palette_to_rgb\n");
  186951. if(png_ptr == NULL) return;
  186952. png_ptr->transformations |= (PNG_EXPAND | PNG_EXPAND_tRNS);
  186953. #ifdef PNG_WARN_UNINITIALIZED_ROW
  186954. png_ptr->flags &= !(PNG_FLAG_ROW_INIT);
  186955. png_ptr->flags &= ~PNG_FLAG_ROW_INIT;
  186956. #endif
  186957. }
  186958. #if !defined(PNG_1_0_X)
  186959. /* Expand grayscale images of less than 8-bit depth to 8 bits. */
  186960. void PNGAPI
  186961. png_set_expand_gray_1_2_4_to_8(png_structp png_ptr)
  186962. {
  186963. png_debug(1, "in png_set_expand_gray_1_2_4_to_8\n");
  186964. if(png_ptr == NULL) return;
  186965. png_ptr->transformations |= PNG_EXPAND;
  186966. #ifdef PNG_WARN_UNINITIALIZED_ROW
  186967. png_ptr->flags &= ~PNG_FLAG_ROW_INIT;
  186968. #endif
  186969. }
  186970. #endif
  186971. #if defined(PNG_1_0_X) || defined(PNG_1_2_X)
  186972. /* Expand grayscale images of less than 8-bit depth to 8 bits. */
  186973. /* Deprecated as of libpng-1.2.9 */
  186974. void PNGAPI
  186975. png_set_gray_1_2_4_to_8(png_structp png_ptr)
  186976. {
  186977. png_debug(1, "in png_set_gray_1_2_4_to_8\n");
  186978. if(png_ptr == NULL) return;
  186979. png_ptr->transformations |= (PNG_EXPAND | PNG_EXPAND_tRNS);
  186980. }
  186981. #endif
  186982. /* Expand tRNS chunks to alpha channels. */
  186983. void PNGAPI
  186984. png_set_tRNS_to_alpha(png_structp png_ptr)
  186985. {
  186986. png_debug(1, "in png_set_tRNS_to_alpha\n");
  186987. png_ptr->transformations |= (PNG_EXPAND | PNG_EXPAND_tRNS);
  186988. #ifdef PNG_WARN_UNINITIALIZED_ROW
  186989. png_ptr->flags &= ~PNG_FLAG_ROW_INIT;
  186990. #endif
  186991. }
  186992. #endif /* defined(PNG_READ_EXPAND_SUPPORTED) */
  186993. #if defined(PNG_READ_GRAY_TO_RGB_SUPPORTED)
  186994. void PNGAPI
  186995. png_set_gray_to_rgb(png_structp png_ptr)
  186996. {
  186997. png_debug(1, "in png_set_gray_to_rgb\n");
  186998. png_ptr->transformations |= PNG_GRAY_TO_RGB;
  186999. #ifdef PNG_WARN_UNINITIALIZED_ROW
  187000. png_ptr->flags &= ~PNG_FLAG_ROW_INIT;
  187001. #endif
  187002. }
  187003. #endif
  187004. #if defined(PNG_READ_RGB_TO_GRAY_SUPPORTED)
  187005. #if defined(PNG_FLOATING_POINT_SUPPORTED)
  187006. /* Convert a RGB image to a grayscale of the same width. This allows us,
  187007. * for example, to convert a 24 bpp RGB image into an 8 bpp grayscale image.
  187008. */
  187009. void PNGAPI
  187010. png_set_rgb_to_gray(png_structp png_ptr, int error_action, double red,
  187011. double green)
  187012. {
  187013. int red_fixed = (int)((float)red*100000.0 + 0.5);
  187014. int green_fixed = (int)((float)green*100000.0 + 0.5);
  187015. if(png_ptr == NULL) return;
  187016. png_set_rgb_to_gray_fixed(png_ptr, error_action, red_fixed, green_fixed);
  187017. }
  187018. #endif
  187019. void PNGAPI
  187020. png_set_rgb_to_gray_fixed(png_structp png_ptr, int error_action,
  187021. png_fixed_point red, png_fixed_point green)
  187022. {
  187023. png_debug(1, "in png_set_rgb_to_gray\n");
  187024. if(png_ptr == NULL) return;
  187025. switch(error_action)
  187026. {
  187027. case 1: png_ptr->transformations |= PNG_RGB_TO_GRAY;
  187028. break;
  187029. case 2: png_ptr->transformations |= PNG_RGB_TO_GRAY_WARN;
  187030. break;
  187031. case 3: png_ptr->transformations |= PNG_RGB_TO_GRAY_ERR;
  187032. }
  187033. if (png_ptr->color_type == PNG_COLOR_TYPE_PALETTE)
  187034. #if defined(PNG_READ_EXPAND_SUPPORTED)
  187035. png_ptr->transformations |= PNG_EXPAND;
  187036. #else
  187037. {
  187038. png_warning(png_ptr, "Cannot do RGB_TO_GRAY without EXPAND_SUPPORTED.");
  187039. png_ptr->transformations &= ~PNG_RGB_TO_GRAY;
  187040. }
  187041. #endif
  187042. {
  187043. png_uint_16 red_int, green_int;
  187044. if(red < 0 || green < 0)
  187045. {
  187046. red_int = 6968; /* .212671 * 32768 + .5 */
  187047. green_int = 23434; /* .715160 * 32768 + .5 */
  187048. }
  187049. else if(red + green < 100000L)
  187050. {
  187051. red_int = (png_uint_16)(((png_uint_32)red*32768L)/100000L);
  187052. green_int = (png_uint_16)(((png_uint_32)green*32768L)/100000L);
  187053. }
  187054. else
  187055. {
  187056. png_warning(png_ptr, "ignoring out of range rgb_to_gray coefficients");
  187057. red_int = 6968;
  187058. green_int = 23434;
  187059. }
  187060. png_ptr->rgb_to_gray_red_coeff = red_int;
  187061. png_ptr->rgb_to_gray_green_coeff = green_int;
  187062. png_ptr->rgb_to_gray_blue_coeff = (png_uint_16)(32768-red_int-green_int);
  187063. }
  187064. }
  187065. #endif
  187066. #if defined(PNG_READ_USER_TRANSFORM_SUPPORTED) || \
  187067. defined(PNG_WRITE_USER_TRANSFORM_SUPPORTED) || \
  187068. defined(PNG_LEGACY_SUPPORTED)
  187069. void PNGAPI
  187070. png_set_read_user_transform_fn(png_structp png_ptr, png_user_transform_ptr
  187071. read_user_transform_fn)
  187072. {
  187073. png_debug(1, "in png_set_read_user_transform_fn\n");
  187074. if(png_ptr == NULL) return;
  187075. #if defined(PNG_READ_USER_TRANSFORM_SUPPORTED)
  187076. png_ptr->transformations |= PNG_USER_TRANSFORM;
  187077. png_ptr->read_user_transform_fn = read_user_transform_fn;
  187078. #endif
  187079. #ifdef PNG_LEGACY_SUPPORTED
  187080. if(read_user_transform_fn)
  187081. png_warning(png_ptr,
  187082. "This version of libpng does not support user transforms");
  187083. #endif
  187084. }
  187085. #endif
  187086. /* Initialize everything needed for the read. This includes modifying
  187087. * the palette.
  187088. */
  187089. void /* PRIVATE */
  187090. png_init_read_transformations(png_structp png_ptr)
  187091. {
  187092. png_debug(1, "in png_init_read_transformations\n");
  187093. #if defined(PNG_USELESS_TESTS_SUPPORTED)
  187094. if(png_ptr != NULL)
  187095. #endif
  187096. {
  187097. #if defined(PNG_READ_BACKGROUND_SUPPORTED) || defined(PNG_READ_SHIFT_SUPPORTED) \
  187098. || defined(PNG_READ_GAMMA_SUPPORTED)
  187099. int color_type = png_ptr->color_type;
  187100. #endif
  187101. #if defined(PNG_READ_EXPAND_SUPPORTED) && defined(PNG_READ_BACKGROUND_SUPPORTED)
  187102. #if defined(PNG_READ_GRAY_TO_RGB_SUPPORTED)
  187103. /* Detect gray background and attempt to enable optimization
  187104. * for gray --> RGB case */
  187105. /* Note: if PNG_BACKGROUND_EXPAND is set and color_type is either RGB or
  187106. * RGB_ALPHA (in which case need_expand is superfluous anyway), the
  187107. * background color might actually be gray yet not be flagged as such.
  187108. * This is not a problem for the current code, which uses
  187109. * PNG_BACKGROUND_IS_GRAY only to decide when to do the
  187110. * png_do_gray_to_rgb() transformation.
  187111. */
  187112. if ((png_ptr->transformations & PNG_BACKGROUND_EXPAND) &&
  187113. !(color_type & PNG_COLOR_MASK_COLOR))
  187114. {
  187115. png_ptr->mode |= PNG_BACKGROUND_IS_GRAY;
  187116. } else if ((png_ptr->transformations & PNG_BACKGROUND) &&
  187117. !(png_ptr->transformations & PNG_BACKGROUND_EXPAND) &&
  187118. (png_ptr->transformations & PNG_GRAY_TO_RGB) &&
  187119. png_ptr->background.red == png_ptr->background.green &&
  187120. png_ptr->background.red == png_ptr->background.blue)
  187121. {
  187122. png_ptr->mode |= PNG_BACKGROUND_IS_GRAY;
  187123. png_ptr->background.gray = png_ptr->background.red;
  187124. }
  187125. #endif
  187126. if ((png_ptr->transformations & PNG_BACKGROUND_EXPAND) &&
  187127. (png_ptr->transformations & PNG_EXPAND))
  187128. {
  187129. if (!(color_type & PNG_COLOR_MASK_COLOR)) /* i.e., GRAY or GRAY_ALPHA */
  187130. {
  187131. /* expand background and tRNS chunks */
  187132. switch (png_ptr->bit_depth)
  187133. {
  187134. case 1:
  187135. png_ptr->background.gray *= (png_uint_16)0xff;
  187136. png_ptr->background.red = png_ptr->background.green
  187137. = png_ptr->background.blue = png_ptr->background.gray;
  187138. if (!(png_ptr->transformations & PNG_EXPAND_tRNS))
  187139. {
  187140. png_ptr->trans_values.gray *= (png_uint_16)0xff;
  187141. png_ptr->trans_values.red = png_ptr->trans_values.green
  187142. = png_ptr->trans_values.blue = png_ptr->trans_values.gray;
  187143. }
  187144. break;
  187145. case 2:
  187146. png_ptr->background.gray *= (png_uint_16)0x55;
  187147. png_ptr->background.red = png_ptr->background.green
  187148. = png_ptr->background.blue = png_ptr->background.gray;
  187149. if (!(png_ptr->transformations & PNG_EXPAND_tRNS))
  187150. {
  187151. png_ptr->trans_values.gray *= (png_uint_16)0x55;
  187152. png_ptr->trans_values.red = png_ptr->trans_values.green
  187153. = png_ptr->trans_values.blue = png_ptr->trans_values.gray;
  187154. }
  187155. break;
  187156. case 4:
  187157. png_ptr->background.gray *= (png_uint_16)0x11;
  187158. png_ptr->background.red = png_ptr->background.green
  187159. = png_ptr->background.blue = png_ptr->background.gray;
  187160. if (!(png_ptr->transformations & PNG_EXPAND_tRNS))
  187161. {
  187162. png_ptr->trans_values.gray *= (png_uint_16)0x11;
  187163. png_ptr->trans_values.red = png_ptr->trans_values.green
  187164. = png_ptr->trans_values.blue = png_ptr->trans_values.gray;
  187165. }
  187166. break;
  187167. case 8:
  187168. case 16:
  187169. png_ptr->background.red = png_ptr->background.green
  187170. = png_ptr->background.blue = png_ptr->background.gray;
  187171. break;
  187172. }
  187173. }
  187174. else if (color_type == PNG_COLOR_TYPE_PALETTE)
  187175. {
  187176. png_ptr->background.red =
  187177. png_ptr->palette[png_ptr->background.index].red;
  187178. png_ptr->background.green =
  187179. png_ptr->palette[png_ptr->background.index].green;
  187180. png_ptr->background.blue =
  187181. png_ptr->palette[png_ptr->background.index].blue;
  187182. #if defined(PNG_READ_INVERT_ALPHA_SUPPORTED)
  187183. if (png_ptr->transformations & PNG_INVERT_ALPHA)
  187184. {
  187185. #if defined(PNG_READ_EXPAND_SUPPORTED)
  187186. if (!(png_ptr->transformations & PNG_EXPAND_tRNS))
  187187. #endif
  187188. {
  187189. /* invert the alpha channel (in tRNS) unless the pixels are
  187190. going to be expanded, in which case leave it for later */
  187191. int i,istop;
  187192. istop=(int)png_ptr->num_trans;
  187193. for (i=0; i<istop; i++)
  187194. png_ptr->trans[i] = (png_byte)(255 - png_ptr->trans[i]);
  187195. }
  187196. }
  187197. #endif
  187198. }
  187199. }
  187200. #endif
  187201. #if defined(PNG_READ_BACKGROUND_SUPPORTED) && defined(PNG_READ_GAMMA_SUPPORTED)
  187202. png_ptr->background_1 = png_ptr->background;
  187203. #endif
  187204. #if defined(PNG_READ_GAMMA_SUPPORTED) && defined(PNG_FLOATING_POINT_SUPPORTED)
  187205. if ((color_type == PNG_COLOR_TYPE_PALETTE && png_ptr->num_trans != 0)
  187206. && (fabs(png_ptr->screen_gamma * png_ptr->gamma - 1.0)
  187207. < PNG_GAMMA_THRESHOLD))
  187208. {
  187209. int i,k;
  187210. k=0;
  187211. for (i=0; i<png_ptr->num_trans; i++)
  187212. {
  187213. if (png_ptr->trans[i] != 0 && png_ptr->trans[i] != 0xff)
  187214. k=1; /* partial transparency is present */
  187215. }
  187216. if (k == 0)
  187217. png_ptr->transformations &= (~PNG_GAMMA);
  187218. }
  187219. if ((png_ptr->transformations & (PNG_GAMMA | PNG_RGB_TO_GRAY)) &&
  187220. png_ptr->gamma != 0.0)
  187221. {
  187222. png_build_gamma_table(png_ptr);
  187223. #if defined(PNG_READ_BACKGROUND_SUPPORTED)
  187224. if (png_ptr->transformations & PNG_BACKGROUND)
  187225. {
  187226. if (color_type == PNG_COLOR_TYPE_PALETTE)
  187227. {
  187228. /* could skip if no transparency and
  187229. */
  187230. png_color back, back_1;
  187231. png_colorp palette = png_ptr->palette;
  187232. int num_palette = png_ptr->num_palette;
  187233. int i;
  187234. if (png_ptr->background_gamma_type == PNG_BACKGROUND_GAMMA_FILE)
  187235. {
  187236. back.red = png_ptr->gamma_table[png_ptr->background.red];
  187237. back.green = png_ptr->gamma_table[png_ptr->background.green];
  187238. back.blue = png_ptr->gamma_table[png_ptr->background.blue];
  187239. back_1.red = png_ptr->gamma_to_1[png_ptr->background.red];
  187240. back_1.green = png_ptr->gamma_to_1[png_ptr->background.green];
  187241. back_1.blue = png_ptr->gamma_to_1[png_ptr->background.blue];
  187242. }
  187243. else
  187244. {
  187245. double g, gs;
  187246. switch (png_ptr->background_gamma_type)
  187247. {
  187248. case PNG_BACKGROUND_GAMMA_SCREEN:
  187249. g = (png_ptr->screen_gamma);
  187250. gs = 1.0;
  187251. break;
  187252. case PNG_BACKGROUND_GAMMA_FILE:
  187253. g = 1.0 / (png_ptr->gamma);
  187254. gs = 1.0 / (png_ptr->gamma * png_ptr->screen_gamma);
  187255. break;
  187256. case PNG_BACKGROUND_GAMMA_UNIQUE:
  187257. g = 1.0 / (png_ptr->background_gamma);
  187258. gs = 1.0 / (png_ptr->background_gamma *
  187259. png_ptr->screen_gamma);
  187260. break;
  187261. default:
  187262. g = 1.0; /* back_1 */
  187263. gs = 1.0; /* back */
  187264. }
  187265. if ( fabs(gs - 1.0) < PNG_GAMMA_THRESHOLD)
  187266. {
  187267. back.red = (png_byte)png_ptr->background.red;
  187268. back.green = (png_byte)png_ptr->background.green;
  187269. back.blue = (png_byte)png_ptr->background.blue;
  187270. }
  187271. else
  187272. {
  187273. back.red = (png_byte)(pow(
  187274. (double)png_ptr->background.red/255, gs) * 255.0 + .5);
  187275. back.green = (png_byte)(pow(
  187276. (double)png_ptr->background.green/255, gs) * 255.0 + .5);
  187277. back.blue = (png_byte)(pow(
  187278. (double)png_ptr->background.blue/255, gs) * 255.0 + .5);
  187279. }
  187280. back_1.red = (png_byte)(pow(
  187281. (double)png_ptr->background.red/255, g) * 255.0 + .5);
  187282. back_1.green = (png_byte)(pow(
  187283. (double)png_ptr->background.green/255, g) * 255.0 + .5);
  187284. back_1.blue = (png_byte)(pow(
  187285. (double)png_ptr->background.blue/255, g) * 255.0 + .5);
  187286. }
  187287. for (i = 0; i < num_palette; i++)
  187288. {
  187289. if (i < (int)png_ptr->num_trans && png_ptr->trans[i] != 0xff)
  187290. {
  187291. if (png_ptr->trans[i] == 0)
  187292. {
  187293. palette[i] = back;
  187294. }
  187295. else /* if (png_ptr->trans[i] != 0xff) */
  187296. {
  187297. png_byte v, w;
  187298. v = png_ptr->gamma_to_1[palette[i].red];
  187299. png_composite(w, v, png_ptr->trans[i], back_1.red);
  187300. palette[i].red = png_ptr->gamma_from_1[w];
  187301. v = png_ptr->gamma_to_1[palette[i].green];
  187302. png_composite(w, v, png_ptr->trans[i], back_1.green);
  187303. palette[i].green = png_ptr->gamma_from_1[w];
  187304. v = png_ptr->gamma_to_1[palette[i].blue];
  187305. png_composite(w, v, png_ptr->trans[i], back_1.blue);
  187306. palette[i].blue = png_ptr->gamma_from_1[w];
  187307. }
  187308. }
  187309. else
  187310. {
  187311. palette[i].red = png_ptr->gamma_table[palette[i].red];
  187312. palette[i].green = png_ptr->gamma_table[palette[i].green];
  187313. palette[i].blue = png_ptr->gamma_table[palette[i].blue];
  187314. }
  187315. }
  187316. }
  187317. /* if (png_ptr->background_gamma_type!=PNG_BACKGROUND_GAMMA_UNKNOWN) */
  187318. else
  187319. /* color_type != PNG_COLOR_TYPE_PALETTE */
  187320. {
  187321. double m = (double)(((png_uint_32)1 << png_ptr->bit_depth) - 1);
  187322. double g = 1.0;
  187323. double gs = 1.0;
  187324. switch (png_ptr->background_gamma_type)
  187325. {
  187326. case PNG_BACKGROUND_GAMMA_SCREEN:
  187327. g = (png_ptr->screen_gamma);
  187328. gs = 1.0;
  187329. break;
  187330. case PNG_BACKGROUND_GAMMA_FILE:
  187331. g = 1.0 / (png_ptr->gamma);
  187332. gs = 1.0 / (png_ptr->gamma * png_ptr->screen_gamma);
  187333. break;
  187334. case PNG_BACKGROUND_GAMMA_UNIQUE:
  187335. g = 1.0 / (png_ptr->background_gamma);
  187336. gs = 1.0 / (png_ptr->background_gamma *
  187337. png_ptr->screen_gamma);
  187338. break;
  187339. }
  187340. png_ptr->background_1.gray = (png_uint_16)(pow(
  187341. (double)png_ptr->background.gray / m, g) * m + .5);
  187342. png_ptr->background.gray = (png_uint_16)(pow(
  187343. (double)png_ptr->background.gray / m, gs) * m + .5);
  187344. if ((png_ptr->background.red != png_ptr->background.green) ||
  187345. (png_ptr->background.red != png_ptr->background.blue) ||
  187346. (png_ptr->background.red != png_ptr->background.gray))
  187347. {
  187348. /* RGB or RGBA with color background */
  187349. png_ptr->background_1.red = (png_uint_16)(pow(
  187350. (double)png_ptr->background.red / m, g) * m + .5);
  187351. png_ptr->background_1.green = (png_uint_16)(pow(
  187352. (double)png_ptr->background.green / m, g) * m + .5);
  187353. png_ptr->background_1.blue = (png_uint_16)(pow(
  187354. (double)png_ptr->background.blue / m, g) * m + .5);
  187355. png_ptr->background.red = (png_uint_16)(pow(
  187356. (double)png_ptr->background.red / m, gs) * m + .5);
  187357. png_ptr->background.green = (png_uint_16)(pow(
  187358. (double)png_ptr->background.green / m, gs) * m + .5);
  187359. png_ptr->background.blue = (png_uint_16)(pow(
  187360. (double)png_ptr->background.blue / m, gs) * m + .5);
  187361. }
  187362. else
  187363. {
  187364. /* GRAY, GRAY ALPHA, RGB, or RGBA with gray background */
  187365. png_ptr->background_1.red = png_ptr->background_1.green
  187366. = png_ptr->background_1.blue = png_ptr->background_1.gray;
  187367. png_ptr->background.red = png_ptr->background.green
  187368. = png_ptr->background.blue = png_ptr->background.gray;
  187369. }
  187370. }
  187371. }
  187372. else
  187373. /* transformation does not include PNG_BACKGROUND */
  187374. #endif /* PNG_READ_BACKGROUND_SUPPORTED */
  187375. if (color_type == PNG_COLOR_TYPE_PALETTE)
  187376. {
  187377. png_colorp palette = png_ptr->palette;
  187378. int num_palette = png_ptr->num_palette;
  187379. int i;
  187380. for (i = 0; i < num_palette; i++)
  187381. {
  187382. palette[i].red = png_ptr->gamma_table[palette[i].red];
  187383. palette[i].green = png_ptr->gamma_table[palette[i].green];
  187384. palette[i].blue = png_ptr->gamma_table[palette[i].blue];
  187385. }
  187386. }
  187387. }
  187388. #if defined(PNG_READ_BACKGROUND_SUPPORTED)
  187389. else
  187390. #endif
  187391. #endif /* PNG_READ_GAMMA_SUPPORTED && PNG_FLOATING_POINT_SUPPORTED */
  187392. #if defined(PNG_READ_BACKGROUND_SUPPORTED)
  187393. /* No GAMMA transformation */
  187394. if ((png_ptr->transformations & PNG_BACKGROUND) &&
  187395. (color_type == PNG_COLOR_TYPE_PALETTE))
  187396. {
  187397. int i;
  187398. int istop = (int)png_ptr->num_trans;
  187399. png_color back;
  187400. png_colorp palette = png_ptr->palette;
  187401. back.red = (png_byte)png_ptr->background.red;
  187402. back.green = (png_byte)png_ptr->background.green;
  187403. back.blue = (png_byte)png_ptr->background.blue;
  187404. for (i = 0; i < istop; i++)
  187405. {
  187406. if (png_ptr->trans[i] == 0)
  187407. {
  187408. palette[i] = back;
  187409. }
  187410. else if (png_ptr->trans[i] != 0xff)
  187411. {
  187412. /* The png_composite() macro is defined in png.h */
  187413. png_composite(palette[i].red, palette[i].red,
  187414. png_ptr->trans[i], back.red);
  187415. png_composite(palette[i].green, palette[i].green,
  187416. png_ptr->trans[i], back.green);
  187417. png_composite(palette[i].blue, palette[i].blue,
  187418. png_ptr->trans[i], back.blue);
  187419. }
  187420. }
  187421. }
  187422. #endif /* PNG_READ_BACKGROUND_SUPPORTED */
  187423. #if defined(PNG_READ_SHIFT_SUPPORTED)
  187424. if ((png_ptr->transformations & PNG_SHIFT) &&
  187425. (color_type == PNG_COLOR_TYPE_PALETTE))
  187426. {
  187427. png_uint_16 i;
  187428. png_uint_16 istop = png_ptr->num_palette;
  187429. int sr = 8 - png_ptr->sig_bit.red;
  187430. int sg = 8 - png_ptr->sig_bit.green;
  187431. int sb = 8 - png_ptr->sig_bit.blue;
  187432. if (sr < 0 || sr > 8)
  187433. sr = 0;
  187434. if (sg < 0 || sg > 8)
  187435. sg = 0;
  187436. if (sb < 0 || sb > 8)
  187437. sb = 0;
  187438. for (i = 0; i < istop; i++)
  187439. {
  187440. png_ptr->palette[i].red >>= sr;
  187441. png_ptr->palette[i].green >>= sg;
  187442. png_ptr->palette[i].blue >>= sb;
  187443. }
  187444. }
  187445. #endif /* PNG_READ_SHIFT_SUPPORTED */
  187446. }
  187447. #if !defined(PNG_READ_GAMMA_SUPPORTED) && !defined(PNG_READ_SHIFT_SUPPORTED) \
  187448. && !defined(PNG_READ_BACKGROUND_SUPPORTED)
  187449. if(png_ptr)
  187450. return;
  187451. #endif
  187452. }
  187453. /* Modify the info structure to reflect the transformations. The
  187454. * info should be updated so a PNG file could be written with it,
  187455. * assuming the transformations result in valid PNG data.
  187456. */
  187457. void /* PRIVATE */
  187458. png_read_transform_info(png_structp png_ptr, png_infop info_ptr)
  187459. {
  187460. png_debug(1, "in png_read_transform_info\n");
  187461. #if defined(PNG_READ_EXPAND_SUPPORTED)
  187462. if (png_ptr->transformations & PNG_EXPAND)
  187463. {
  187464. if (info_ptr->color_type == PNG_COLOR_TYPE_PALETTE)
  187465. {
  187466. if (png_ptr->num_trans && (png_ptr->transformations & PNG_EXPAND_tRNS))
  187467. info_ptr->color_type = PNG_COLOR_TYPE_RGB_ALPHA;
  187468. else
  187469. info_ptr->color_type = PNG_COLOR_TYPE_RGB;
  187470. info_ptr->bit_depth = 8;
  187471. info_ptr->num_trans = 0;
  187472. }
  187473. else
  187474. {
  187475. if (png_ptr->num_trans)
  187476. {
  187477. if (png_ptr->transformations & PNG_EXPAND_tRNS)
  187478. info_ptr->color_type |= PNG_COLOR_MASK_ALPHA;
  187479. else
  187480. info_ptr->color_type |= PNG_COLOR_MASK_COLOR;
  187481. }
  187482. if (info_ptr->bit_depth < 8)
  187483. info_ptr->bit_depth = 8;
  187484. info_ptr->num_trans = 0;
  187485. }
  187486. }
  187487. #endif
  187488. #if defined(PNG_READ_BACKGROUND_SUPPORTED)
  187489. if (png_ptr->transformations & PNG_BACKGROUND)
  187490. {
  187491. info_ptr->color_type &= ~PNG_COLOR_MASK_ALPHA;
  187492. info_ptr->num_trans = 0;
  187493. info_ptr->background = png_ptr->background;
  187494. }
  187495. #endif
  187496. #if defined(PNG_READ_GAMMA_SUPPORTED)
  187497. if (png_ptr->transformations & PNG_GAMMA)
  187498. {
  187499. #ifdef PNG_FLOATING_POINT_SUPPORTED
  187500. info_ptr->gamma = png_ptr->gamma;
  187501. #endif
  187502. #ifdef PNG_FIXED_POINT_SUPPORTED
  187503. info_ptr->int_gamma = png_ptr->int_gamma;
  187504. #endif
  187505. }
  187506. #endif
  187507. #if defined(PNG_READ_16_TO_8_SUPPORTED)
  187508. if ((png_ptr->transformations & PNG_16_TO_8) && (info_ptr->bit_depth == 16))
  187509. info_ptr->bit_depth = 8;
  187510. #endif
  187511. #if defined(PNG_READ_GRAY_TO_RGB_SUPPORTED)
  187512. if (png_ptr->transformations & PNG_GRAY_TO_RGB)
  187513. info_ptr->color_type |= PNG_COLOR_MASK_COLOR;
  187514. #endif
  187515. #if defined(PNG_READ_RGB_TO_GRAY_SUPPORTED)
  187516. if (png_ptr->transformations & PNG_RGB_TO_GRAY)
  187517. info_ptr->color_type &= ~PNG_COLOR_MASK_COLOR;
  187518. #endif
  187519. #if defined(PNG_READ_DITHER_SUPPORTED)
  187520. if (png_ptr->transformations & PNG_DITHER)
  187521. {
  187522. if (((info_ptr->color_type == PNG_COLOR_TYPE_RGB) ||
  187523. (info_ptr->color_type == PNG_COLOR_TYPE_RGB_ALPHA)) &&
  187524. png_ptr->palette_lookup && info_ptr->bit_depth == 8)
  187525. {
  187526. info_ptr->color_type = PNG_COLOR_TYPE_PALETTE;
  187527. }
  187528. }
  187529. #endif
  187530. #if defined(PNG_READ_PACK_SUPPORTED)
  187531. if ((png_ptr->transformations & PNG_PACK) && (info_ptr->bit_depth < 8))
  187532. info_ptr->bit_depth = 8;
  187533. #endif
  187534. if (info_ptr->color_type == PNG_COLOR_TYPE_PALETTE)
  187535. info_ptr->channels = 1;
  187536. else if (info_ptr->color_type & PNG_COLOR_MASK_COLOR)
  187537. info_ptr->channels = 3;
  187538. else
  187539. info_ptr->channels = 1;
  187540. #if defined(PNG_READ_STRIP_ALPHA_SUPPORTED)
  187541. if (png_ptr->flags & PNG_FLAG_STRIP_ALPHA)
  187542. info_ptr->color_type &= ~PNG_COLOR_MASK_ALPHA;
  187543. #endif
  187544. if (info_ptr->color_type & PNG_COLOR_MASK_ALPHA)
  187545. info_ptr->channels++;
  187546. #if defined(PNG_READ_FILLER_SUPPORTED)
  187547. /* STRIP_ALPHA and FILLER allowed: MASK_ALPHA bit stripped above */
  187548. if ((png_ptr->transformations & PNG_FILLER) &&
  187549. ((info_ptr->color_type == PNG_COLOR_TYPE_RGB) ||
  187550. (info_ptr->color_type == PNG_COLOR_TYPE_GRAY)))
  187551. {
  187552. info_ptr->channels++;
  187553. /* if adding a true alpha channel not just filler */
  187554. #if !defined(PNG_1_0_X)
  187555. if (png_ptr->transformations & PNG_ADD_ALPHA)
  187556. info_ptr->color_type |= PNG_COLOR_MASK_ALPHA;
  187557. #endif
  187558. }
  187559. #endif
  187560. #if defined(PNG_USER_TRANSFORM_PTR_SUPPORTED) && \
  187561. defined(PNG_READ_USER_TRANSFORM_SUPPORTED)
  187562. if(png_ptr->transformations & PNG_USER_TRANSFORM)
  187563. {
  187564. if(info_ptr->bit_depth < png_ptr->user_transform_depth)
  187565. info_ptr->bit_depth = png_ptr->user_transform_depth;
  187566. if(info_ptr->channels < png_ptr->user_transform_channels)
  187567. info_ptr->channels = png_ptr->user_transform_channels;
  187568. }
  187569. #endif
  187570. info_ptr->pixel_depth = (png_byte)(info_ptr->channels *
  187571. info_ptr->bit_depth);
  187572. info_ptr->rowbytes = PNG_ROWBYTES(info_ptr->pixel_depth,info_ptr->width);
  187573. #if !defined(PNG_READ_EXPAND_SUPPORTED)
  187574. if(png_ptr)
  187575. return;
  187576. #endif
  187577. }
  187578. /* Transform the row. The order of transformations is significant,
  187579. * and is very touchy. If you add a transformation, take care to
  187580. * decide how it fits in with the other transformations here.
  187581. */
  187582. void /* PRIVATE */
  187583. png_do_read_transformations(png_structp png_ptr)
  187584. {
  187585. png_debug(1, "in png_do_read_transformations\n");
  187586. if (png_ptr->row_buf == NULL)
  187587. {
  187588. #if !defined(PNG_NO_STDIO) && !defined(_WIN32_WCE)
  187589. char msg[50];
  187590. png_snprintf2(msg, 50,
  187591. "NULL row buffer for row %ld, pass %d", png_ptr->row_number,
  187592. png_ptr->pass);
  187593. png_error(png_ptr, msg);
  187594. #else
  187595. png_error(png_ptr, "NULL row buffer");
  187596. #endif
  187597. }
  187598. #ifdef PNG_WARN_UNINITIALIZED_ROW
  187599. if (!(png_ptr->flags & PNG_FLAG_ROW_INIT))
  187600. /* Application has failed to call either png_read_start_image()
  187601. * or png_read_update_info() after setting transforms that expand
  187602. * pixels. This check added to libpng-1.2.19 */
  187603. #if (PNG_WARN_UNINITIALIZED_ROW==1)
  187604. png_error(png_ptr, "Uninitialized row");
  187605. #else
  187606. png_warning(png_ptr, "Uninitialized row");
  187607. #endif
  187608. #endif
  187609. #if defined(PNG_READ_EXPAND_SUPPORTED)
  187610. if (png_ptr->transformations & PNG_EXPAND)
  187611. {
  187612. if (png_ptr->row_info.color_type == PNG_COLOR_TYPE_PALETTE)
  187613. {
  187614. png_do_expand_palette(&(png_ptr->row_info), png_ptr->row_buf + 1,
  187615. png_ptr->palette, png_ptr->trans, png_ptr->num_trans);
  187616. }
  187617. else
  187618. {
  187619. if (png_ptr->num_trans &&
  187620. (png_ptr->transformations & PNG_EXPAND_tRNS))
  187621. png_do_expand(&(png_ptr->row_info), png_ptr->row_buf + 1,
  187622. &(png_ptr->trans_values));
  187623. else
  187624. png_do_expand(&(png_ptr->row_info), png_ptr->row_buf + 1,
  187625. NULL);
  187626. }
  187627. }
  187628. #endif
  187629. #if defined(PNG_READ_STRIP_ALPHA_SUPPORTED)
  187630. if (png_ptr->flags & PNG_FLAG_STRIP_ALPHA)
  187631. png_do_strip_filler(&(png_ptr->row_info), png_ptr->row_buf + 1,
  187632. PNG_FLAG_FILLER_AFTER | (png_ptr->flags & PNG_FLAG_STRIP_ALPHA));
  187633. #endif
  187634. #if defined(PNG_READ_RGB_TO_GRAY_SUPPORTED)
  187635. if (png_ptr->transformations & PNG_RGB_TO_GRAY)
  187636. {
  187637. int rgb_error =
  187638. png_do_rgb_to_gray(png_ptr, &(png_ptr->row_info), png_ptr->row_buf + 1);
  187639. if(rgb_error)
  187640. {
  187641. png_ptr->rgb_to_gray_status=1;
  187642. if((png_ptr->transformations & PNG_RGB_TO_GRAY) ==
  187643. PNG_RGB_TO_GRAY_WARN)
  187644. png_warning(png_ptr, "png_do_rgb_to_gray found nongray pixel");
  187645. if((png_ptr->transformations & PNG_RGB_TO_GRAY) ==
  187646. PNG_RGB_TO_GRAY_ERR)
  187647. png_error(png_ptr, "png_do_rgb_to_gray found nongray pixel");
  187648. }
  187649. }
  187650. #endif
  187651. /*
  187652. From Andreas Dilger e-mail to png-implement, 26 March 1998:
  187653. In most cases, the "simple transparency" should be done prior to doing
  187654. gray-to-RGB, or you will have to test 3x as many bytes to check if a
  187655. pixel is transparent. You would also need to make sure that the
  187656. transparency information is upgraded to RGB.
  187657. To summarize, the current flow is:
  187658. - Gray + simple transparency -> compare 1 or 2 gray bytes and composite
  187659. with background "in place" if transparent,
  187660. convert to RGB if necessary
  187661. - Gray + alpha -> composite with gray background and remove alpha bytes,
  187662. convert to RGB if necessary
  187663. To support RGB backgrounds for gray images we need:
  187664. - Gray + simple transparency -> convert to RGB + simple transparency, compare
  187665. 3 or 6 bytes and composite with background
  187666. "in place" if transparent (3x compare/pixel
  187667. compared to doing composite with gray bkgrnd)
  187668. - Gray + alpha -> convert to RGB + alpha, composite with background and
  187669. remove alpha bytes (3x float operations/pixel
  187670. compared with composite on gray background)
  187671. Greg's change will do this. The reason it wasn't done before is for
  187672. performance, as this increases the per-pixel operations. If we would check
  187673. in advance if the background was gray or RGB, and position the gray-to-RGB
  187674. transform appropriately, then it would save a lot of work/time.
  187675. */
  187676. #if defined(PNG_READ_GRAY_TO_RGB_SUPPORTED)
  187677. /* if gray -> RGB, do so now only if background is non-gray; else do later
  187678. * for performance reasons */
  187679. if ((png_ptr->transformations & PNG_GRAY_TO_RGB) &&
  187680. !(png_ptr->mode & PNG_BACKGROUND_IS_GRAY))
  187681. png_do_gray_to_rgb(&(png_ptr->row_info), png_ptr->row_buf + 1);
  187682. #endif
  187683. #if defined(PNG_READ_BACKGROUND_SUPPORTED)
  187684. if ((png_ptr->transformations & PNG_BACKGROUND) &&
  187685. ((png_ptr->num_trans != 0 ) ||
  187686. (png_ptr->color_type & PNG_COLOR_MASK_ALPHA)))
  187687. png_do_background(&(png_ptr->row_info), png_ptr->row_buf + 1,
  187688. &(png_ptr->trans_values), &(png_ptr->background)
  187689. #if defined(PNG_READ_GAMMA_SUPPORTED)
  187690. , &(png_ptr->background_1),
  187691. png_ptr->gamma_table, png_ptr->gamma_from_1,
  187692. png_ptr->gamma_to_1, png_ptr->gamma_16_table,
  187693. png_ptr->gamma_16_from_1, png_ptr->gamma_16_to_1,
  187694. png_ptr->gamma_shift
  187695. #endif
  187696. );
  187697. #endif
  187698. #if defined(PNG_READ_GAMMA_SUPPORTED)
  187699. if ((png_ptr->transformations & PNG_GAMMA) &&
  187700. #if defined(PNG_READ_BACKGROUND_SUPPORTED)
  187701. !((png_ptr->transformations & PNG_BACKGROUND) &&
  187702. ((png_ptr->num_trans != 0) ||
  187703. (png_ptr->color_type & PNG_COLOR_MASK_ALPHA))) &&
  187704. #endif
  187705. (png_ptr->color_type != PNG_COLOR_TYPE_PALETTE))
  187706. png_do_gamma(&(png_ptr->row_info), png_ptr->row_buf + 1,
  187707. png_ptr->gamma_table, png_ptr->gamma_16_table,
  187708. png_ptr->gamma_shift);
  187709. #endif
  187710. #if defined(PNG_READ_16_TO_8_SUPPORTED)
  187711. if (png_ptr->transformations & PNG_16_TO_8)
  187712. png_do_chop(&(png_ptr->row_info), png_ptr->row_buf + 1);
  187713. #endif
  187714. #if defined(PNG_READ_DITHER_SUPPORTED)
  187715. if (png_ptr->transformations & PNG_DITHER)
  187716. {
  187717. png_do_dither((png_row_infop)&(png_ptr->row_info), png_ptr->row_buf + 1,
  187718. png_ptr->palette_lookup, png_ptr->dither_index);
  187719. if(png_ptr->row_info.rowbytes == (png_uint_32)0)
  187720. png_error(png_ptr, "png_do_dither returned rowbytes=0");
  187721. }
  187722. #endif
  187723. #if defined(PNG_READ_INVERT_SUPPORTED)
  187724. if (png_ptr->transformations & PNG_INVERT_MONO)
  187725. png_do_invert(&(png_ptr->row_info), png_ptr->row_buf + 1);
  187726. #endif
  187727. #if defined(PNG_READ_SHIFT_SUPPORTED)
  187728. if (png_ptr->transformations & PNG_SHIFT)
  187729. png_do_unshift(&(png_ptr->row_info), png_ptr->row_buf + 1,
  187730. &(png_ptr->shift));
  187731. #endif
  187732. #if defined(PNG_READ_PACK_SUPPORTED)
  187733. if (png_ptr->transformations & PNG_PACK)
  187734. png_do_unpack(&(png_ptr->row_info), png_ptr->row_buf + 1);
  187735. #endif
  187736. #if defined(PNG_READ_BGR_SUPPORTED)
  187737. if (png_ptr->transformations & PNG_BGR)
  187738. png_do_bgr(&(png_ptr->row_info), png_ptr->row_buf + 1);
  187739. #endif
  187740. #if defined(PNG_READ_PACKSWAP_SUPPORTED)
  187741. if (png_ptr->transformations & PNG_PACKSWAP)
  187742. png_do_packswap(&(png_ptr->row_info), png_ptr->row_buf + 1);
  187743. #endif
  187744. #if defined(PNG_READ_GRAY_TO_RGB_SUPPORTED)
  187745. /* if gray -> RGB, do so now only if we did not do so above */
  187746. if ((png_ptr->transformations & PNG_GRAY_TO_RGB) &&
  187747. (png_ptr->mode & PNG_BACKGROUND_IS_GRAY))
  187748. png_do_gray_to_rgb(&(png_ptr->row_info), png_ptr->row_buf + 1);
  187749. #endif
  187750. #if defined(PNG_READ_FILLER_SUPPORTED)
  187751. if (png_ptr->transformations & PNG_FILLER)
  187752. png_do_read_filler(&(png_ptr->row_info), png_ptr->row_buf + 1,
  187753. (png_uint_32)png_ptr->filler, png_ptr->flags);
  187754. #endif
  187755. #if defined(PNG_READ_INVERT_ALPHA_SUPPORTED)
  187756. if (png_ptr->transformations & PNG_INVERT_ALPHA)
  187757. png_do_read_invert_alpha(&(png_ptr->row_info), png_ptr->row_buf + 1);
  187758. #endif
  187759. #if defined(PNG_READ_SWAP_ALPHA_SUPPORTED)
  187760. if (png_ptr->transformations & PNG_SWAP_ALPHA)
  187761. png_do_read_swap_alpha(&(png_ptr->row_info), png_ptr->row_buf + 1);
  187762. #endif
  187763. #if defined(PNG_READ_SWAP_SUPPORTED)
  187764. if (png_ptr->transformations & PNG_SWAP_BYTES)
  187765. png_do_swap(&(png_ptr->row_info), png_ptr->row_buf + 1);
  187766. #endif
  187767. #if defined(PNG_READ_USER_TRANSFORM_SUPPORTED)
  187768. if (png_ptr->transformations & PNG_USER_TRANSFORM)
  187769. {
  187770. if(png_ptr->read_user_transform_fn != NULL)
  187771. (*(png_ptr->read_user_transform_fn)) /* user read transform function */
  187772. (png_ptr, /* png_ptr */
  187773. &(png_ptr->row_info), /* row_info: */
  187774. /* png_uint_32 width; width of row */
  187775. /* png_uint_32 rowbytes; number of bytes in row */
  187776. /* png_byte color_type; color type of pixels */
  187777. /* png_byte bit_depth; bit depth of samples */
  187778. /* png_byte channels; number of channels (1-4) */
  187779. /* png_byte pixel_depth; bits per pixel (depth*channels) */
  187780. png_ptr->row_buf + 1); /* start of pixel data for row */
  187781. #if defined(PNG_USER_TRANSFORM_PTR_SUPPORTED)
  187782. if(png_ptr->user_transform_depth)
  187783. png_ptr->row_info.bit_depth = png_ptr->user_transform_depth;
  187784. if(png_ptr->user_transform_channels)
  187785. png_ptr->row_info.channels = png_ptr->user_transform_channels;
  187786. #endif
  187787. png_ptr->row_info.pixel_depth = (png_byte)(png_ptr->row_info.bit_depth *
  187788. png_ptr->row_info.channels);
  187789. png_ptr->row_info.rowbytes = PNG_ROWBYTES(png_ptr->row_info.pixel_depth,
  187790. png_ptr->row_info.width);
  187791. }
  187792. #endif
  187793. }
  187794. #if defined(PNG_READ_PACK_SUPPORTED)
  187795. /* Unpack pixels of 1, 2, or 4 bits per pixel into 1 byte per pixel,
  187796. * without changing the actual values. Thus, if you had a row with
  187797. * a bit depth of 1, you would end up with bytes that only contained
  187798. * the numbers 0 or 1. If you would rather they contain 0 and 255, use
  187799. * png_do_shift() after this.
  187800. */
  187801. void /* PRIVATE */
  187802. png_do_unpack(png_row_infop row_info, png_bytep row)
  187803. {
  187804. png_debug(1, "in png_do_unpack\n");
  187805. #if defined(PNG_USELESS_TESTS_SUPPORTED)
  187806. if (row != NULL && row_info != NULL && row_info->bit_depth < 8)
  187807. #else
  187808. if (row_info->bit_depth < 8)
  187809. #endif
  187810. {
  187811. png_uint_32 i;
  187812. png_uint_32 row_width=row_info->width;
  187813. switch (row_info->bit_depth)
  187814. {
  187815. case 1:
  187816. {
  187817. png_bytep sp = row + (png_size_t)((row_width - 1) >> 3);
  187818. png_bytep dp = row + (png_size_t)row_width - 1;
  187819. png_uint_32 shift = 7 - (int)((row_width + 7) & 0x07);
  187820. for (i = 0; i < row_width; i++)
  187821. {
  187822. *dp = (png_byte)((*sp >> shift) & 0x01);
  187823. if (shift == 7)
  187824. {
  187825. shift = 0;
  187826. sp--;
  187827. }
  187828. else
  187829. shift++;
  187830. dp--;
  187831. }
  187832. break;
  187833. }
  187834. case 2:
  187835. {
  187836. png_bytep sp = row + (png_size_t)((row_width - 1) >> 2);
  187837. png_bytep dp = row + (png_size_t)row_width - 1;
  187838. png_uint_32 shift = (int)((3 - ((row_width + 3) & 0x03)) << 1);
  187839. for (i = 0; i < row_width; i++)
  187840. {
  187841. *dp = (png_byte)((*sp >> shift) & 0x03);
  187842. if (shift == 6)
  187843. {
  187844. shift = 0;
  187845. sp--;
  187846. }
  187847. else
  187848. shift += 2;
  187849. dp--;
  187850. }
  187851. break;
  187852. }
  187853. case 4:
  187854. {
  187855. png_bytep sp = row + (png_size_t)((row_width - 1) >> 1);
  187856. png_bytep dp = row + (png_size_t)row_width - 1;
  187857. png_uint_32 shift = (int)((1 - ((row_width + 1) & 0x01)) << 2);
  187858. for (i = 0; i < row_width; i++)
  187859. {
  187860. *dp = (png_byte)((*sp >> shift) & 0x0f);
  187861. if (shift == 4)
  187862. {
  187863. shift = 0;
  187864. sp--;
  187865. }
  187866. else
  187867. shift = 4;
  187868. dp--;
  187869. }
  187870. break;
  187871. }
  187872. }
  187873. row_info->bit_depth = 8;
  187874. row_info->pixel_depth = (png_byte)(8 * row_info->channels);
  187875. row_info->rowbytes = row_width * row_info->channels;
  187876. }
  187877. }
  187878. #endif
  187879. #if defined(PNG_READ_SHIFT_SUPPORTED)
  187880. /* Reverse the effects of png_do_shift. This routine merely shifts the
  187881. * pixels back to their significant bits values. Thus, if you have
  187882. * a row of bit depth 8, but only 5 are significant, this will shift
  187883. * the values back to 0 through 31.
  187884. */
  187885. void /* PRIVATE */
  187886. png_do_unshift(png_row_infop row_info, png_bytep row, png_color_8p sig_bits)
  187887. {
  187888. png_debug(1, "in png_do_unshift\n");
  187889. if (
  187890. #if defined(PNG_USELESS_TESTS_SUPPORTED)
  187891. row != NULL && row_info != NULL && sig_bits != NULL &&
  187892. #endif
  187893. row_info->color_type != PNG_COLOR_TYPE_PALETTE)
  187894. {
  187895. int shift[4];
  187896. int channels = 0;
  187897. int c;
  187898. png_uint_16 value = 0;
  187899. png_uint_32 row_width = row_info->width;
  187900. if (row_info->color_type & PNG_COLOR_MASK_COLOR)
  187901. {
  187902. shift[channels++] = row_info->bit_depth - sig_bits->red;
  187903. shift[channels++] = row_info->bit_depth - sig_bits->green;
  187904. shift[channels++] = row_info->bit_depth - sig_bits->blue;
  187905. }
  187906. else
  187907. {
  187908. shift[channels++] = row_info->bit_depth - sig_bits->gray;
  187909. }
  187910. if (row_info->color_type & PNG_COLOR_MASK_ALPHA)
  187911. {
  187912. shift[channels++] = row_info->bit_depth - sig_bits->alpha;
  187913. }
  187914. for (c = 0; c < channels; c++)
  187915. {
  187916. if (shift[c] <= 0)
  187917. shift[c] = 0;
  187918. else
  187919. value = 1;
  187920. }
  187921. if (!value)
  187922. return;
  187923. switch (row_info->bit_depth)
  187924. {
  187925. case 2:
  187926. {
  187927. png_bytep bp;
  187928. png_uint_32 i;
  187929. png_uint_32 istop = row_info->rowbytes;
  187930. for (bp = row, i = 0; i < istop; i++)
  187931. {
  187932. *bp >>= 1;
  187933. *bp++ &= 0x55;
  187934. }
  187935. break;
  187936. }
  187937. case 4:
  187938. {
  187939. png_bytep bp = row;
  187940. png_uint_32 i;
  187941. png_uint_32 istop = row_info->rowbytes;
  187942. png_byte mask = (png_byte)((((int)0xf0 >> shift[0]) & (int)0xf0) |
  187943. (png_byte)((int)0xf >> shift[0]));
  187944. for (i = 0; i < istop; i++)
  187945. {
  187946. *bp >>= shift[0];
  187947. *bp++ &= mask;
  187948. }
  187949. break;
  187950. }
  187951. case 8:
  187952. {
  187953. png_bytep bp = row;
  187954. png_uint_32 i;
  187955. png_uint_32 istop = row_width * channels;
  187956. for (i = 0; i < istop; i++)
  187957. {
  187958. *bp++ >>= shift[i%channels];
  187959. }
  187960. break;
  187961. }
  187962. case 16:
  187963. {
  187964. png_bytep bp = row;
  187965. png_uint_32 i;
  187966. png_uint_32 istop = channels * row_width;
  187967. for (i = 0; i < istop; i++)
  187968. {
  187969. value = (png_uint_16)((*bp << 8) + *(bp + 1));
  187970. value >>= shift[i%channels];
  187971. *bp++ = (png_byte)(value >> 8);
  187972. *bp++ = (png_byte)(value & 0xff);
  187973. }
  187974. break;
  187975. }
  187976. }
  187977. }
  187978. }
  187979. #endif
  187980. #if defined(PNG_READ_16_TO_8_SUPPORTED)
  187981. /* chop rows of bit depth 16 down to 8 */
  187982. void /* PRIVATE */
  187983. png_do_chop(png_row_infop row_info, png_bytep row)
  187984. {
  187985. png_debug(1, "in png_do_chop\n");
  187986. #if defined(PNG_USELESS_TESTS_SUPPORTED)
  187987. if (row != NULL && row_info != NULL && row_info->bit_depth == 16)
  187988. #else
  187989. if (row_info->bit_depth == 16)
  187990. #endif
  187991. {
  187992. png_bytep sp = row;
  187993. png_bytep dp = row;
  187994. png_uint_32 i;
  187995. png_uint_32 istop = row_info->width * row_info->channels;
  187996. for (i = 0; i<istop; i++, sp += 2, dp++)
  187997. {
  187998. #if defined(PNG_READ_16_TO_8_ACCURATE_SCALE_SUPPORTED)
  187999. /* This does a more accurate scaling of the 16-bit color
  188000. * value, rather than a simple low-byte truncation.
  188001. *
  188002. * What the ideal calculation should be:
  188003. * *dp = (((((png_uint_32)(*sp) << 8) |
  188004. * (png_uint_32)(*(sp + 1))) * 255 + 127) / (png_uint_32)65535L;
  188005. *
  188006. * GRR: no, I think this is what it really should be:
  188007. * *dp = (((((png_uint_32)(*sp) << 8) |
  188008. * (png_uint_32)(*(sp + 1))) + 128L) / (png_uint_32)257L;
  188009. *
  188010. * GRR: here's the exact calculation with shifts:
  188011. * temp = (((png_uint_32)(*sp) << 8) | (png_uint_32)(*(sp + 1))) + 128L;
  188012. * *dp = (temp - (temp >> 8)) >> 8;
  188013. *
  188014. * Approximate calculation with shift/add instead of multiply/divide:
  188015. * *dp = ((((png_uint_32)(*sp) << 8) |
  188016. * (png_uint_32)((int)(*(sp + 1)) - *sp)) + 128) >> 8;
  188017. *
  188018. * What we actually do to avoid extra shifting and conversion:
  188019. */
  188020. *dp = *sp + ((((int)(*(sp + 1)) - *sp) > 128) ? 1 : 0);
  188021. #else
  188022. /* Simply discard the low order byte */
  188023. *dp = *sp;
  188024. #endif
  188025. }
  188026. row_info->bit_depth = 8;
  188027. row_info->pixel_depth = (png_byte)(8 * row_info->channels);
  188028. row_info->rowbytes = row_info->width * row_info->channels;
  188029. }
  188030. }
  188031. #endif
  188032. #if defined(PNG_READ_SWAP_ALPHA_SUPPORTED)
  188033. void /* PRIVATE */
  188034. png_do_read_swap_alpha(png_row_infop row_info, png_bytep row)
  188035. {
  188036. png_debug(1, "in png_do_read_swap_alpha\n");
  188037. #if defined(PNG_USELESS_TESTS_SUPPORTED)
  188038. if (row != NULL && row_info != NULL)
  188039. #endif
  188040. {
  188041. png_uint_32 row_width = row_info->width;
  188042. if (row_info->color_type == PNG_COLOR_TYPE_RGB_ALPHA)
  188043. {
  188044. /* This converts from RGBA to ARGB */
  188045. if (row_info->bit_depth == 8)
  188046. {
  188047. png_bytep sp = row + row_info->rowbytes;
  188048. png_bytep dp = sp;
  188049. png_byte save;
  188050. png_uint_32 i;
  188051. for (i = 0; i < row_width; i++)
  188052. {
  188053. save = *(--sp);
  188054. *(--dp) = *(--sp);
  188055. *(--dp) = *(--sp);
  188056. *(--dp) = *(--sp);
  188057. *(--dp) = save;
  188058. }
  188059. }
  188060. /* This converts from RRGGBBAA to AARRGGBB */
  188061. else
  188062. {
  188063. png_bytep sp = row + row_info->rowbytes;
  188064. png_bytep dp = sp;
  188065. png_byte save[2];
  188066. png_uint_32 i;
  188067. for (i = 0; i < row_width; i++)
  188068. {
  188069. save[0] = *(--sp);
  188070. save[1] = *(--sp);
  188071. *(--dp) = *(--sp);
  188072. *(--dp) = *(--sp);
  188073. *(--dp) = *(--sp);
  188074. *(--dp) = *(--sp);
  188075. *(--dp) = *(--sp);
  188076. *(--dp) = *(--sp);
  188077. *(--dp) = save[0];
  188078. *(--dp) = save[1];
  188079. }
  188080. }
  188081. }
  188082. else if (row_info->color_type == PNG_COLOR_TYPE_GRAY_ALPHA)
  188083. {
  188084. /* This converts from GA to AG */
  188085. if (row_info->bit_depth == 8)
  188086. {
  188087. png_bytep sp = row + row_info->rowbytes;
  188088. png_bytep dp = sp;
  188089. png_byte save;
  188090. png_uint_32 i;
  188091. for (i = 0; i < row_width; i++)
  188092. {
  188093. save = *(--sp);
  188094. *(--dp) = *(--sp);
  188095. *(--dp) = save;
  188096. }
  188097. }
  188098. /* This converts from GGAA to AAGG */
  188099. else
  188100. {
  188101. png_bytep sp = row + row_info->rowbytes;
  188102. png_bytep dp = sp;
  188103. png_byte save[2];
  188104. png_uint_32 i;
  188105. for (i = 0; i < row_width; i++)
  188106. {
  188107. save[0] = *(--sp);
  188108. save[1] = *(--sp);
  188109. *(--dp) = *(--sp);
  188110. *(--dp) = *(--sp);
  188111. *(--dp) = save[0];
  188112. *(--dp) = save[1];
  188113. }
  188114. }
  188115. }
  188116. }
  188117. }
  188118. #endif
  188119. #if defined(PNG_READ_INVERT_ALPHA_SUPPORTED)
  188120. void /* PRIVATE */
  188121. png_do_read_invert_alpha(png_row_infop row_info, png_bytep row)
  188122. {
  188123. png_debug(1, "in png_do_read_invert_alpha\n");
  188124. #if defined(PNG_USELESS_TESTS_SUPPORTED)
  188125. if (row != NULL && row_info != NULL)
  188126. #endif
  188127. {
  188128. png_uint_32 row_width = row_info->width;
  188129. if (row_info->color_type == PNG_COLOR_TYPE_RGB_ALPHA)
  188130. {
  188131. /* This inverts the alpha channel in RGBA */
  188132. if (row_info->bit_depth == 8)
  188133. {
  188134. png_bytep sp = row + row_info->rowbytes;
  188135. png_bytep dp = sp;
  188136. png_uint_32 i;
  188137. for (i = 0; i < row_width; i++)
  188138. {
  188139. *(--dp) = (png_byte)(255 - *(--sp));
  188140. /* This does nothing:
  188141. *(--dp) = *(--sp);
  188142. *(--dp) = *(--sp);
  188143. *(--dp) = *(--sp);
  188144. We can replace it with:
  188145. */
  188146. sp-=3;
  188147. dp=sp;
  188148. }
  188149. }
  188150. /* This inverts the alpha channel in RRGGBBAA */
  188151. else
  188152. {
  188153. png_bytep sp = row + row_info->rowbytes;
  188154. png_bytep dp = sp;
  188155. png_uint_32 i;
  188156. for (i = 0; i < row_width; i++)
  188157. {
  188158. *(--dp) = (png_byte)(255 - *(--sp));
  188159. *(--dp) = (png_byte)(255 - *(--sp));
  188160. /* This does nothing:
  188161. *(--dp) = *(--sp);
  188162. *(--dp) = *(--sp);
  188163. *(--dp) = *(--sp);
  188164. *(--dp) = *(--sp);
  188165. *(--dp) = *(--sp);
  188166. *(--dp) = *(--sp);
  188167. We can replace it with:
  188168. */
  188169. sp-=6;
  188170. dp=sp;
  188171. }
  188172. }
  188173. }
  188174. else if (row_info->color_type == PNG_COLOR_TYPE_GRAY_ALPHA)
  188175. {
  188176. /* This inverts the alpha channel in GA */
  188177. if (row_info->bit_depth == 8)
  188178. {
  188179. png_bytep sp = row + row_info->rowbytes;
  188180. png_bytep dp = sp;
  188181. png_uint_32 i;
  188182. for (i = 0; i < row_width; i++)
  188183. {
  188184. *(--dp) = (png_byte)(255 - *(--sp));
  188185. *(--dp) = *(--sp);
  188186. }
  188187. }
  188188. /* This inverts the alpha channel in GGAA */
  188189. else
  188190. {
  188191. png_bytep sp = row + row_info->rowbytes;
  188192. png_bytep dp = sp;
  188193. png_uint_32 i;
  188194. for (i = 0; i < row_width; i++)
  188195. {
  188196. *(--dp) = (png_byte)(255 - *(--sp));
  188197. *(--dp) = (png_byte)(255 - *(--sp));
  188198. /*
  188199. *(--dp) = *(--sp);
  188200. *(--dp) = *(--sp);
  188201. */
  188202. sp-=2;
  188203. dp=sp;
  188204. }
  188205. }
  188206. }
  188207. }
  188208. }
  188209. #endif
  188210. #if defined(PNG_READ_FILLER_SUPPORTED)
  188211. /* Add filler channel if we have RGB color */
  188212. void /* PRIVATE */
  188213. png_do_read_filler(png_row_infop row_info, png_bytep row,
  188214. png_uint_32 filler, png_uint_32 flags)
  188215. {
  188216. png_uint_32 i;
  188217. png_uint_32 row_width = row_info->width;
  188218. png_byte hi_filler = (png_byte)((filler>>8) & 0xff);
  188219. png_byte lo_filler = (png_byte)(filler & 0xff);
  188220. png_debug(1, "in png_do_read_filler\n");
  188221. if (
  188222. #if defined(PNG_USELESS_TESTS_SUPPORTED)
  188223. row != NULL && row_info != NULL &&
  188224. #endif
  188225. row_info->color_type == PNG_COLOR_TYPE_GRAY)
  188226. {
  188227. if(row_info->bit_depth == 8)
  188228. {
  188229. /* This changes the data from G to GX */
  188230. if (flags & PNG_FLAG_FILLER_AFTER)
  188231. {
  188232. png_bytep sp = row + (png_size_t)row_width;
  188233. png_bytep dp = sp + (png_size_t)row_width;
  188234. for (i = 1; i < row_width; i++)
  188235. {
  188236. *(--dp) = lo_filler;
  188237. *(--dp) = *(--sp);
  188238. }
  188239. *(--dp) = lo_filler;
  188240. row_info->channels = 2;
  188241. row_info->pixel_depth = 16;
  188242. row_info->rowbytes = row_width * 2;
  188243. }
  188244. /* This changes the data from G to XG */
  188245. else
  188246. {
  188247. png_bytep sp = row + (png_size_t)row_width;
  188248. png_bytep dp = sp + (png_size_t)row_width;
  188249. for (i = 0; i < row_width; i++)
  188250. {
  188251. *(--dp) = *(--sp);
  188252. *(--dp) = lo_filler;
  188253. }
  188254. row_info->channels = 2;
  188255. row_info->pixel_depth = 16;
  188256. row_info->rowbytes = row_width * 2;
  188257. }
  188258. }
  188259. else if(row_info->bit_depth == 16)
  188260. {
  188261. /* This changes the data from GG to GGXX */
  188262. if (flags & PNG_FLAG_FILLER_AFTER)
  188263. {
  188264. png_bytep sp = row + (png_size_t)row_width * 2;
  188265. png_bytep dp = sp + (png_size_t)row_width * 2;
  188266. for (i = 1; i < row_width; i++)
  188267. {
  188268. *(--dp) = hi_filler;
  188269. *(--dp) = lo_filler;
  188270. *(--dp) = *(--sp);
  188271. *(--dp) = *(--sp);
  188272. }
  188273. *(--dp) = hi_filler;
  188274. *(--dp) = lo_filler;
  188275. row_info->channels = 2;
  188276. row_info->pixel_depth = 32;
  188277. row_info->rowbytes = row_width * 4;
  188278. }
  188279. /* This changes the data from GG to XXGG */
  188280. else
  188281. {
  188282. png_bytep sp = row + (png_size_t)row_width * 2;
  188283. png_bytep dp = sp + (png_size_t)row_width * 2;
  188284. for (i = 0; i < row_width; i++)
  188285. {
  188286. *(--dp) = *(--sp);
  188287. *(--dp) = *(--sp);
  188288. *(--dp) = hi_filler;
  188289. *(--dp) = lo_filler;
  188290. }
  188291. row_info->channels = 2;
  188292. row_info->pixel_depth = 32;
  188293. row_info->rowbytes = row_width * 4;
  188294. }
  188295. }
  188296. } /* COLOR_TYPE == GRAY */
  188297. else if (row_info->color_type == PNG_COLOR_TYPE_RGB)
  188298. {
  188299. if(row_info->bit_depth == 8)
  188300. {
  188301. /* This changes the data from RGB to RGBX */
  188302. if (flags & PNG_FLAG_FILLER_AFTER)
  188303. {
  188304. png_bytep sp = row + (png_size_t)row_width * 3;
  188305. png_bytep dp = sp + (png_size_t)row_width;
  188306. for (i = 1; i < row_width; i++)
  188307. {
  188308. *(--dp) = lo_filler;
  188309. *(--dp) = *(--sp);
  188310. *(--dp) = *(--sp);
  188311. *(--dp) = *(--sp);
  188312. }
  188313. *(--dp) = lo_filler;
  188314. row_info->channels = 4;
  188315. row_info->pixel_depth = 32;
  188316. row_info->rowbytes = row_width * 4;
  188317. }
  188318. /* This changes the data from RGB to XRGB */
  188319. else
  188320. {
  188321. png_bytep sp = row + (png_size_t)row_width * 3;
  188322. png_bytep dp = sp + (png_size_t)row_width;
  188323. for (i = 0; i < row_width; i++)
  188324. {
  188325. *(--dp) = *(--sp);
  188326. *(--dp) = *(--sp);
  188327. *(--dp) = *(--sp);
  188328. *(--dp) = lo_filler;
  188329. }
  188330. row_info->channels = 4;
  188331. row_info->pixel_depth = 32;
  188332. row_info->rowbytes = row_width * 4;
  188333. }
  188334. }
  188335. else if(row_info->bit_depth == 16)
  188336. {
  188337. /* This changes the data from RRGGBB to RRGGBBXX */
  188338. if (flags & PNG_FLAG_FILLER_AFTER)
  188339. {
  188340. png_bytep sp = row + (png_size_t)row_width * 6;
  188341. png_bytep dp = sp + (png_size_t)row_width * 2;
  188342. for (i = 1; i < row_width; i++)
  188343. {
  188344. *(--dp) = hi_filler;
  188345. *(--dp) = lo_filler;
  188346. *(--dp) = *(--sp);
  188347. *(--dp) = *(--sp);
  188348. *(--dp) = *(--sp);
  188349. *(--dp) = *(--sp);
  188350. *(--dp) = *(--sp);
  188351. *(--dp) = *(--sp);
  188352. }
  188353. *(--dp) = hi_filler;
  188354. *(--dp) = lo_filler;
  188355. row_info->channels = 4;
  188356. row_info->pixel_depth = 64;
  188357. row_info->rowbytes = row_width * 8;
  188358. }
  188359. /* This changes the data from RRGGBB to XXRRGGBB */
  188360. else
  188361. {
  188362. png_bytep sp = row + (png_size_t)row_width * 6;
  188363. png_bytep dp = sp + (png_size_t)row_width * 2;
  188364. for (i = 0; i < row_width; i++)
  188365. {
  188366. *(--dp) = *(--sp);
  188367. *(--dp) = *(--sp);
  188368. *(--dp) = *(--sp);
  188369. *(--dp) = *(--sp);
  188370. *(--dp) = *(--sp);
  188371. *(--dp) = *(--sp);
  188372. *(--dp) = hi_filler;
  188373. *(--dp) = lo_filler;
  188374. }
  188375. row_info->channels = 4;
  188376. row_info->pixel_depth = 64;
  188377. row_info->rowbytes = row_width * 8;
  188378. }
  188379. }
  188380. } /* COLOR_TYPE == RGB */
  188381. }
  188382. #endif
  188383. #if defined(PNG_READ_GRAY_TO_RGB_SUPPORTED)
  188384. /* expand grayscale files to RGB, with or without alpha */
  188385. void /* PRIVATE */
  188386. png_do_gray_to_rgb(png_row_infop row_info, png_bytep row)
  188387. {
  188388. png_uint_32 i;
  188389. png_uint_32 row_width = row_info->width;
  188390. png_debug(1, "in png_do_gray_to_rgb\n");
  188391. if (row_info->bit_depth >= 8 &&
  188392. #if defined(PNG_USELESS_TESTS_SUPPORTED)
  188393. row != NULL && row_info != NULL &&
  188394. #endif
  188395. !(row_info->color_type & PNG_COLOR_MASK_COLOR))
  188396. {
  188397. if (row_info->color_type == PNG_COLOR_TYPE_GRAY)
  188398. {
  188399. if (row_info->bit_depth == 8)
  188400. {
  188401. png_bytep sp = row + (png_size_t)row_width - 1;
  188402. png_bytep dp = sp + (png_size_t)row_width * 2;
  188403. for (i = 0; i < row_width; i++)
  188404. {
  188405. *(dp--) = *sp;
  188406. *(dp--) = *sp;
  188407. *(dp--) = *(sp--);
  188408. }
  188409. }
  188410. else
  188411. {
  188412. png_bytep sp = row + (png_size_t)row_width * 2 - 1;
  188413. png_bytep dp = sp + (png_size_t)row_width * 4;
  188414. for (i = 0; i < row_width; i++)
  188415. {
  188416. *(dp--) = *sp;
  188417. *(dp--) = *(sp - 1);
  188418. *(dp--) = *sp;
  188419. *(dp--) = *(sp - 1);
  188420. *(dp--) = *(sp--);
  188421. *(dp--) = *(sp--);
  188422. }
  188423. }
  188424. }
  188425. else if (row_info->color_type == PNG_COLOR_TYPE_GRAY_ALPHA)
  188426. {
  188427. if (row_info->bit_depth == 8)
  188428. {
  188429. png_bytep sp = row + (png_size_t)row_width * 2 - 1;
  188430. png_bytep dp = sp + (png_size_t)row_width * 2;
  188431. for (i = 0; i < row_width; i++)
  188432. {
  188433. *(dp--) = *(sp--);
  188434. *(dp--) = *sp;
  188435. *(dp--) = *sp;
  188436. *(dp--) = *(sp--);
  188437. }
  188438. }
  188439. else
  188440. {
  188441. png_bytep sp = row + (png_size_t)row_width * 4 - 1;
  188442. png_bytep dp = sp + (png_size_t)row_width * 4;
  188443. for (i = 0; i < row_width; i++)
  188444. {
  188445. *(dp--) = *(sp--);
  188446. *(dp--) = *(sp--);
  188447. *(dp--) = *sp;
  188448. *(dp--) = *(sp - 1);
  188449. *(dp--) = *sp;
  188450. *(dp--) = *(sp - 1);
  188451. *(dp--) = *(sp--);
  188452. *(dp--) = *(sp--);
  188453. }
  188454. }
  188455. }
  188456. row_info->channels += (png_byte)2;
  188457. row_info->color_type |= PNG_COLOR_MASK_COLOR;
  188458. row_info->pixel_depth = (png_byte)(row_info->channels *
  188459. row_info->bit_depth);
  188460. row_info->rowbytes = PNG_ROWBYTES(row_info->pixel_depth,row_width);
  188461. }
  188462. }
  188463. #endif
  188464. #if defined(PNG_READ_RGB_TO_GRAY_SUPPORTED)
  188465. /* reduce RGB files to grayscale, with or without alpha
  188466. * using the equation given in Poynton's ColorFAQ at
  188467. * <http://www.inforamp.net/~poynton/>
  188468. * Copyright (c) 1998-01-04 Charles Poynton poynton at inforamp.net
  188469. *
  188470. * Y = 0.212671 * R + 0.715160 * G + 0.072169 * B
  188471. *
  188472. * We approximate this with
  188473. *
  188474. * Y = 0.21268 * R + 0.7151 * G + 0.07217 * B
  188475. *
  188476. * which can be expressed with integers as
  188477. *
  188478. * Y = (6969 * R + 23434 * G + 2365 * B)/32768
  188479. *
  188480. * The calculation is to be done in a linear colorspace.
  188481. *
  188482. * Other integer coefficents can be used via png_set_rgb_to_gray().
  188483. */
  188484. int /* PRIVATE */
  188485. png_do_rgb_to_gray(png_structp png_ptr, png_row_infop row_info, png_bytep row)
  188486. {
  188487. png_uint_32 i;
  188488. png_uint_32 row_width = row_info->width;
  188489. int rgb_error = 0;
  188490. png_debug(1, "in png_do_rgb_to_gray\n");
  188491. if (
  188492. #if defined(PNG_USELESS_TESTS_SUPPORTED)
  188493. row != NULL && row_info != NULL &&
  188494. #endif
  188495. (row_info->color_type & PNG_COLOR_MASK_COLOR))
  188496. {
  188497. png_uint_32 rc = png_ptr->rgb_to_gray_red_coeff;
  188498. png_uint_32 gc = png_ptr->rgb_to_gray_green_coeff;
  188499. png_uint_32 bc = png_ptr->rgb_to_gray_blue_coeff;
  188500. if (row_info->color_type == PNG_COLOR_TYPE_RGB)
  188501. {
  188502. if (row_info->bit_depth == 8)
  188503. {
  188504. #if defined(PNG_READ_GAMMA_SUPPORTED) || defined(PNG_READ_BACKGROUND_SUPPORTED)
  188505. if (png_ptr->gamma_from_1 != NULL && png_ptr->gamma_to_1 != NULL)
  188506. {
  188507. png_bytep sp = row;
  188508. png_bytep dp = row;
  188509. for (i = 0; i < row_width; i++)
  188510. {
  188511. png_byte red = png_ptr->gamma_to_1[*(sp++)];
  188512. png_byte green = png_ptr->gamma_to_1[*(sp++)];
  188513. png_byte blue = png_ptr->gamma_to_1[*(sp++)];
  188514. if(red != green || red != blue)
  188515. {
  188516. rgb_error |= 1;
  188517. *(dp++) = png_ptr->gamma_from_1[
  188518. (rc*red+gc*green+bc*blue)>>15];
  188519. }
  188520. else
  188521. *(dp++) = *(sp-1);
  188522. }
  188523. }
  188524. else
  188525. #endif
  188526. {
  188527. png_bytep sp = row;
  188528. png_bytep dp = row;
  188529. for (i = 0; i < row_width; i++)
  188530. {
  188531. png_byte red = *(sp++);
  188532. png_byte green = *(sp++);
  188533. png_byte blue = *(sp++);
  188534. if(red != green || red != blue)
  188535. {
  188536. rgb_error |= 1;
  188537. *(dp++) = (png_byte)((rc*red+gc*green+bc*blue)>>15);
  188538. }
  188539. else
  188540. *(dp++) = *(sp-1);
  188541. }
  188542. }
  188543. }
  188544. else /* RGB bit_depth == 16 */
  188545. {
  188546. #if defined(PNG_READ_GAMMA_SUPPORTED) || defined(PNG_READ_BACKGROUND_SUPPORTED)
  188547. if (png_ptr->gamma_16_to_1 != NULL &&
  188548. png_ptr->gamma_16_from_1 != NULL)
  188549. {
  188550. png_bytep sp = row;
  188551. png_bytep dp = row;
  188552. for (i = 0; i < row_width; i++)
  188553. {
  188554. png_uint_16 red, green, blue, w;
  188555. red = (png_uint_16)(((*(sp))<<8) | *(sp+1)); sp+=2;
  188556. green = (png_uint_16)(((*(sp))<<8) | *(sp+1)); sp+=2;
  188557. blue = (png_uint_16)(((*(sp))<<8) | *(sp+1)); sp+=2;
  188558. if(red == green && red == blue)
  188559. w = red;
  188560. else
  188561. {
  188562. png_uint_16 red_1 = png_ptr->gamma_16_to_1[(red&0xff) >>
  188563. png_ptr->gamma_shift][red>>8];
  188564. png_uint_16 green_1 = png_ptr->gamma_16_to_1[(green&0xff) >>
  188565. png_ptr->gamma_shift][green>>8];
  188566. png_uint_16 blue_1 = png_ptr->gamma_16_to_1[(blue&0xff) >>
  188567. png_ptr->gamma_shift][blue>>8];
  188568. png_uint_16 gray16 = (png_uint_16)((rc*red_1 + gc*green_1
  188569. + bc*blue_1)>>15);
  188570. w = png_ptr->gamma_16_from_1[(gray16&0xff) >>
  188571. png_ptr->gamma_shift][gray16 >> 8];
  188572. rgb_error |= 1;
  188573. }
  188574. *(dp++) = (png_byte)((w>>8) & 0xff);
  188575. *(dp++) = (png_byte)(w & 0xff);
  188576. }
  188577. }
  188578. else
  188579. #endif
  188580. {
  188581. png_bytep sp = row;
  188582. png_bytep dp = row;
  188583. for (i = 0; i < row_width; i++)
  188584. {
  188585. png_uint_16 red, green, blue, gray16;
  188586. red = (png_uint_16)(((*(sp))<<8) | *(sp+1)); sp+=2;
  188587. green = (png_uint_16)(((*(sp))<<8) | *(sp+1)); sp+=2;
  188588. blue = (png_uint_16)(((*(sp))<<8) | *(sp+1)); sp+=2;
  188589. if(red != green || red != blue)
  188590. rgb_error |= 1;
  188591. gray16 = (png_uint_16)((rc*red + gc*green + bc*blue)>>15);
  188592. *(dp++) = (png_byte)((gray16>>8) & 0xff);
  188593. *(dp++) = (png_byte)(gray16 & 0xff);
  188594. }
  188595. }
  188596. }
  188597. }
  188598. if (row_info->color_type == PNG_COLOR_TYPE_RGB_ALPHA)
  188599. {
  188600. if (row_info->bit_depth == 8)
  188601. {
  188602. #if defined(PNG_READ_GAMMA_SUPPORTED) || defined(PNG_READ_BACKGROUND_SUPPORTED)
  188603. if (png_ptr->gamma_from_1 != NULL && png_ptr->gamma_to_1 != NULL)
  188604. {
  188605. png_bytep sp = row;
  188606. png_bytep dp = row;
  188607. for (i = 0; i < row_width; i++)
  188608. {
  188609. png_byte red = png_ptr->gamma_to_1[*(sp++)];
  188610. png_byte green = png_ptr->gamma_to_1[*(sp++)];
  188611. png_byte blue = png_ptr->gamma_to_1[*(sp++)];
  188612. if(red != green || red != blue)
  188613. rgb_error |= 1;
  188614. *(dp++) = png_ptr->gamma_from_1
  188615. [(rc*red + gc*green + bc*blue)>>15];
  188616. *(dp++) = *(sp++); /* alpha */
  188617. }
  188618. }
  188619. else
  188620. #endif
  188621. {
  188622. png_bytep sp = row;
  188623. png_bytep dp = row;
  188624. for (i = 0; i < row_width; i++)
  188625. {
  188626. png_byte red = *(sp++);
  188627. png_byte green = *(sp++);
  188628. png_byte blue = *(sp++);
  188629. if(red != green || red != blue)
  188630. rgb_error |= 1;
  188631. *(dp++) = (png_byte)((rc*red + gc*green + bc*blue)>>15);
  188632. *(dp++) = *(sp++); /* alpha */
  188633. }
  188634. }
  188635. }
  188636. else /* RGBA bit_depth == 16 */
  188637. {
  188638. #if defined(PNG_READ_GAMMA_SUPPORTED) || defined(PNG_READ_BACKGROUND_SUPPORTED)
  188639. if (png_ptr->gamma_16_to_1 != NULL &&
  188640. png_ptr->gamma_16_from_1 != NULL)
  188641. {
  188642. png_bytep sp = row;
  188643. png_bytep dp = row;
  188644. for (i = 0; i < row_width; i++)
  188645. {
  188646. png_uint_16 red, green, blue, w;
  188647. red = (png_uint_16)(((*(sp))<<8) | *(sp+1)); sp+=2;
  188648. green = (png_uint_16)(((*(sp))<<8) | *(sp+1)); sp+=2;
  188649. blue = (png_uint_16)(((*(sp))<<8) | *(sp+1)); sp+=2;
  188650. if(red == green && red == blue)
  188651. w = red;
  188652. else
  188653. {
  188654. png_uint_16 red_1 = png_ptr->gamma_16_to_1[(red&0xff) >>
  188655. png_ptr->gamma_shift][red>>8];
  188656. png_uint_16 green_1 = png_ptr->gamma_16_to_1[(green&0xff) >>
  188657. png_ptr->gamma_shift][green>>8];
  188658. png_uint_16 blue_1 = png_ptr->gamma_16_to_1[(blue&0xff) >>
  188659. png_ptr->gamma_shift][blue>>8];
  188660. png_uint_16 gray16 = (png_uint_16)((rc * red_1
  188661. + gc * green_1 + bc * blue_1)>>15);
  188662. w = png_ptr->gamma_16_from_1[(gray16&0xff) >>
  188663. png_ptr->gamma_shift][gray16 >> 8];
  188664. rgb_error |= 1;
  188665. }
  188666. *(dp++) = (png_byte)((w>>8) & 0xff);
  188667. *(dp++) = (png_byte)(w & 0xff);
  188668. *(dp++) = *(sp++); /* alpha */
  188669. *(dp++) = *(sp++);
  188670. }
  188671. }
  188672. else
  188673. #endif
  188674. {
  188675. png_bytep sp = row;
  188676. png_bytep dp = row;
  188677. for (i = 0; i < row_width; i++)
  188678. {
  188679. png_uint_16 red, green, blue, gray16;
  188680. red = (png_uint_16)((*(sp)<<8) | *(sp+1)); sp+=2;
  188681. green = (png_uint_16)((*(sp)<<8) | *(sp+1)); sp+=2;
  188682. blue = (png_uint_16)((*(sp)<<8) | *(sp+1)); sp+=2;
  188683. if(red != green || red != blue)
  188684. rgb_error |= 1;
  188685. gray16 = (png_uint_16)((rc*red + gc*green + bc*blue)>>15);
  188686. *(dp++) = (png_byte)((gray16>>8) & 0xff);
  188687. *(dp++) = (png_byte)(gray16 & 0xff);
  188688. *(dp++) = *(sp++); /* alpha */
  188689. *(dp++) = *(sp++);
  188690. }
  188691. }
  188692. }
  188693. }
  188694. row_info->channels -= (png_byte)2;
  188695. row_info->color_type &= ~PNG_COLOR_MASK_COLOR;
  188696. row_info->pixel_depth = (png_byte)(row_info->channels *
  188697. row_info->bit_depth);
  188698. row_info->rowbytes = PNG_ROWBYTES(row_info->pixel_depth,row_width);
  188699. }
  188700. return rgb_error;
  188701. }
  188702. #endif
  188703. /* Build a grayscale palette. Palette is assumed to be 1 << bit_depth
  188704. * large of png_color. This lets grayscale images be treated as
  188705. * paletted. Most useful for gamma correction and simplification
  188706. * of code.
  188707. */
  188708. void PNGAPI
  188709. png_build_grayscale_palette(int bit_depth, png_colorp palette)
  188710. {
  188711. int num_palette;
  188712. int color_inc;
  188713. int i;
  188714. int v;
  188715. png_debug(1, "in png_do_build_grayscale_palette\n");
  188716. if (palette == NULL)
  188717. return;
  188718. switch (bit_depth)
  188719. {
  188720. case 1:
  188721. num_palette = 2;
  188722. color_inc = 0xff;
  188723. break;
  188724. case 2:
  188725. num_palette = 4;
  188726. color_inc = 0x55;
  188727. break;
  188728. case 4:
  188729. num_palette = 16;
  188730. color_inc = 0x11;
  188731. break;
  188732. case 8:
  188733. num_palette = 256;
  188734. color_inc = 1;
  188735. break;
  188736. default:
  188737. num_palette = 0;
  188738. color_inc = 0;
  188739. break;
  188740. }
  188741. for (i = 0, v = 0; i < num_palette; i++, v += color_inc)
  188742. {
  188743. palette[i].red = (png_byte)v;
  188744. palette[i].green = (png_byte)v;
  188745. palette[i].blue = (png_byte)v;
  188746. }
  188747. }
  188748. /* This function is currently unused. Do we really need it? */
  188749. #if defined(PNG_READ_DITHER_SUPPORTED) && defined(PNG_CORRECT_PALETTE_SUPPORTED)
  188750. void /* PRIVATE */
  188751. png_correct_palette(png_structp png_ptr, png_colorp palette,
  188752. int num_palette)
  188753. {
  188754. png_debug(1, "in png_correct_palette\n");
  188755. #if defined(PNG_READ_BACKGROUND_SUPPORTED) && \
  188756. defined(PNG_READ_GAMMA_SUPPORTED) && defined(PNG_FLOATING_POINT_SUPPORTED)
  188757. if (png_ptr->transformations & (PNG_GAMMA | PNG_BACKGROUND))
  188758. {
  188759. png_color back, back_1;
  188760. if (png_ptr->background_gamma_type == PNG_BACKGROUND_GAMMA_FILE)
  188761. {
  188762. back.red = png_ptr->gamma_table[png_ptr->background.red];
  188763. back.green = png_ptr->gamma_table[png_ptr->background.green];
  188764. back.blue = png_ptr->gamma_table[png_ptr->background.blue];
  188765. back_1.red = png_ptr->gamma_to_1[png_ptr->background.red];
  188766. back_1.green = png_ptr->gamma_to_1[png_ptr->background.green];
  188767. back_1.blue = png_ptr->gamma_to_1[png_ptr->background.blue];
  188768. }
  188769. else
  188770. {
  188771. double g;
  188772. g = 1.0 / (png_ptr->background_gamma * png_ptr->screen_gamma);
  188773. if (png_ptr->background_gamma_type == PNG_BACKGROUND_GAMMA_SCREEN ||
  188774. fabs(g - 1.0) < PNG_GAMMA_THRESHOLD)
  188775. {
  188776. back.red = png_ptr->background.red;
  188777. back.green = png_ptr->background.green;
  188778. back.blue = png_ptr->background.blue;
  188779. }
  188780. else
  188781. {
  188782. back.red =
  188783. (png_byte)(pow((double)png_ptr->background.red/255, g) *
  188784. 255.0 + 0.5);
  188785. back.green =
  188786. (png_byte)(pow((double)png_ptr->background.green/255, g) *
  188787. 255.0 + 0.5);
  188788. back.blue =
  188789. (png_byte)(pow((double)png_ptr->background.blue/255, g) *
  188790. 255.0 + 0.5);
  188791. }
  188792. g = 1.0 / png_ptr->background_gamma;
  188793. back_1.red =
  188794. (png_byte)(pow((double)png_ptr->background.red/255, g) *
  188795. 255.0 + 0.5);
  188796. back_1.green =
  188797. (png_byte)(pow((double)png_ptr->background.green/255, g) *
  188798. 255.0 + 0.5);
  188799. back_1.blue =
  188800. (png_byte)(pow((double)png_ptr->background.blue/255, g) *
  188801. 255.0 + 0.5);
  188802. }
  188803. if (png_ptr->color_type == PNG_COLOR_TYPE_PALETTE)
  188804. {
  188805. png_uint_32 i;
  188806. for (i = 0; i < (png_uint_32)num_palette; i++)
  188807. {
  188808. if (i < png_ptr->num_trans && png_ptr->trans[i] == 0)
  188809. {
  188810. palette[i] = back;
  188811. }
  188812. else if (i < png_ptr->num_trans && png_ptr->trans[i] != 0xff)
  188813. {
  188814. png_byte v, w;
  188815. v = png_ptr->gamma_to_1[png_ptr->palette[i].red];
  188816. png_composite(w, v, png_ptr->trans[i], back_1.red);
  188817. palette[i].red = png_ptr->gamma_from_1[w];
  188818. v = png_ptr->gamma_to_1[png_ptr->palette[i].green];
  188819. png_composite(w, v, png_ptr->trans[i], back_1.green);
  188820. palette[i].green = png_ptr->gamma_from_1[w];
  188821. v = png_ptr->gamma_to_1[png_ptr->palette[i].blue];
  188822. png_composite(w, v, png_ptr->trans[i], back_1.blue);
  188823. palette[i].blue = png_ptr->gamma_from_1[w];
  188824. }
  188825. else
  188826. {
  188827. palette[i].red = png_ptr->gamma_table[palette[i].red];
  188828. palette[i].green = png_ptr->gamma_table[palette[i].green];
  188829. palette[i].blue = png_ptr->gamma_table[palette[i].blue];
  188830. }
  188831. }
  188832. }
  188833. else
  188834. {
  188835. int i;
  188836. for (i = 0; i < num_palette; i++)
  188837. {
  188838. if (palette[i].red == (png_byte)png_ptr->trans_values.gray)
  188839. {
  188840. palette[i] = back;
  188841. }
  188842. else
  188843. {
  188844. palette[i].red = png_ptr->gamma_table[palette[i].red];
  188845. palette[i].green = png_ptr->gamma_table[palette[i].green];
  188846. palette[i].blue = png_ptr->gamma_table[palette[i].blue];
  188847. }
  188848. }
  188849. }
  188850. }
  188851. else
  188852. #endif
  188853. #if defined(PNG_READ_GAMMA_SUPPORTED)
  188854. if (png_ptr->transformations & PNG_GAMMA)
  188855. {
  188856. int i;
  188857. for (i = 0; i < num_palette; i++)
  188858. {
  188859. palette[i].red = png_ptr->gamma_table[palette[i].red];
  188860. palette[i].green = png_ptr->gamma_table[palette[i].green];
  188861. palette[i].blue = png_ptr->gamma_table[palette[i].blue];
  188862. }
  188863. }
  188864. #if defined(PNG_READ_BACKGROUND_SUPPORTED)
  188865. else
  188866. #endif
  188867. #endif
  188868. #if defined(PNG_READ_BACKGROUND_SUPPORTED)
  188869. if (png_ptr->transformations & PNG_BACKGROUND)
  188870. {
  188871. if (png_ptr->color_type == PNG_COLOR_TYPE_PALETTE)
  188872. {
  188873. png_color back;
  188874. back.red = (png_byte)png_ptr->background.red;
  188875. back.green = (png_byte)png_ptr->background.green;
  188876. back.blue = (png_byte)png_ptr->background.blue;
  188877. for (i = 0; i < (int)png_ptr->num_trans; i++)
  188878. {
  188879. if (png_ptr->trans[i] == 0)
  188880. {
  188881. palette[i].red = back.red;
  188882. palette[i].green = back.green;
  188883. palette[i].blue = back.blue;
  188884. }
  188885. else if (png_ptr->trans[i] != 0xff)
  188886. {
  188887. png_composite(palette[i].red, png_ptr->palette[i].red,
  188888. png_ptr->trans[i], back.red);
  188889. png_composite(palette[i].green, png_ptr->palette[i].green,
  188890. png_ptr->trans[i], back.green);
  188891. png_composite(palette[i].blue, png_ptr->palette[i].blue,
  188892. png_ptr->trans[i], back.blue);
  188893. }
  188894. }
  188895. }
  188896. else /* assume grayscale palette (what else could it be?) */
  188897. {
  188898. int i;
  188899. for (i = 0; i < num_palette; i++)
  188900. {
  188901. if (i == (png_byte)png_ptr->trans_values.gray)
  188902. {
  188903. palette[i].red = (png_byte)png_ptr->background.red;
  188904. palette[i].green = (png_byte)png_ptr->background.green;
  188905. palette[i].blue = (png_byte)png_ptr->background.blue;
  188906. }
  188907. }
  188908. }
  188909. }
  188910. #endif
  188911. }
  188912. #endif
  188913. #if defined(PNG_READ_BACKGROUND_SUPPORTED)
  188914. /* Replace any alpha or transparency with the supplied background color.
  188915. * "background" is already in the screen gamma, while "background_1" is
  188916. * at a gamma of 1.0. Paletted files have already been taken care of.
  188917. */
  188918. void /* PRIVATE */
  188919. png_do_background(png_row_infop row_info, png_bytep row,
  188920. png_color_16p trans_values, png_color_16p background
  188921. #if defined(PNG_READ_GAMMA_SUPPORTED)
  188922. , png_color_16p background_1,
  188923. png_bytep gamma_table, png_bytep gamma_from_1, png_bytep gamma_to_1,
  188924. png_uint_16pp gamma_16, png_uint_16pp gamma_16_from_1,
  188925. png_uint_16pp gamma_16_to_1, int gamma_shift
  188926. #endif
  188927. )
  188928. {
  188929. png_bytep sp, dp;
  188930. png_uint_32 i;
  188931. png_uint_32 row_width=row_info->width;
  188932. int shift;
  188933. png_debug(1, "in png_do_background\n");
  188934. if (background != NULL &&
  188935. #if defined(PNG_USELESS_TESTS_SUPPORTED)
  188936. row != NULL && row_info != NULL &&
  188937. #endif
  188938. (!(row_info->color_type & PNG_COLOR_MASK_ALPHA) ||
  188939. (row_info->color_type != PNG_COLOR_TYPE_PALETTE && trans_values)))
  188940. {
  188941. switch (row_info->color_type)
  188942. {
  188943. case PNG_COLOR_TYPE_GRAY:
  188944. {
  188945. switch (row_info->bit_depth)
  188946. {
  188947. case 1:
  188948. {
  188949. sp = row;
  188950. shift = 7;
  188951. for (i = 0; i < row_width; i++)
  188952. {
  188953. if ((png_uint_16)((*sp >> shift) & 0x01)
  188954. == trans_values->gray)
  188955. {
  188956. *sp &= (png_byte)((0x7f7f >> (7 - shift)) & 0xff);
  188957. *sp |= (png_byte)(background->gray << shift);
  188958. }
  188959. if (!shift)
  188960. {
  188961. shift = 7;
  188962. sp++;
  188963. }
  188964. else
  188965. shift--;
  188966. }
  188967. break;
  188968. }
  188969. case 2:
  188970. {
  188971. #if defined(PNG_READ_GAMMA_SUPPORTED)
  188972. if (gamma_table != NULL)
  188973. {
  188974. sp = row;
  188975. shift = 6;
  188976. for (i = 0; i < row_width; i++)
  188977. {
  188978. if ((png_uint_16)((*sp >> shift) & 0x03)
  188979. == trans_values->gray)
  188980. {
  188981. *sp &= (png_byte)((0x3f3f >> (6 - shift)) & 0xff);
  188982. *sp |= (png_byte)(background->gray << shift);
  188983. }
  188984. else
  188985. {
  188986. png_byte p = (png_byte)((*sp >> shift) & 0x03);
  188987. png_byte g = (png_byte)((gamma_table [p | (p << 2) |
  188988. (p << 4) | (p << 6)] >> 6) & 0x03);
  188989. *sp &= (png_byte)((0x3f3f >> (6 - shift)) & 0xff);
  188990. *sp |= (png_byte)(g << shift);
  188991. }
  188992. if (!shift)
  188993. {
  188994. shift = 6;
  188995. sp++;
  188996. }
  188997. else
  188998. shift -= 2;
  188999. }
  189000. }
  189001. else
  189002. #endif
  189003. {
  189004. sp = row;
  189005. shift = 6;
  189006. for (i = 0; i < row_width; i++)
  189007. {
  189008. if ((png_uint_16)((*sp >> shift) & 0x03)
  189009. == trans_values->gray)
  189010. {
  189011. *sp &= (png_byte)((0x3f3f >> (6 - shift)) & 0xff);
  189012. *sp |= (png_byte)(background->gray << shift);
  189013. }
  189014. if (!shift)
  189015. {
  189016. shift = 6;
  189017. sp++;
  189018. }
  189019. else
  189020. shift -= 2;
  189021. }
  189022. }
  189023. break;
  189024. }
  189025. case 4:
  189026. {
  189027. #if defined(PNG_READ_GAMMA_SUPPORTED)
  189028. if (gamma_table != NULL)
  189029. {
  189030. sp = row;
  189031. shift = 4;
  189032. for (i = 0; i < row_width; i++)
  189033. {
  189034. if ((png_uint_16)((*sp >> shift) & 0x0f)
  189035. == trans_values->gray)
  189036. {
  189037. *sp &= (png_byte)((0xf0f >> (4 - shift)) & 0xff);
  189038. *sp |= (png_byte)(background->gray << shift);
  189039. }
  189040. else
  189041. {
  189042. png_byte p = (png_byte)((*sp >> shift) & 0x0f);
  189043. png_byte g = (png_byte)((gamma_table[p |
  189044. (p << 4)] >> 4) & 0x0f);
  189045. *sp &= (png_byte)((0xf0f >> (4 - shift)) & 0xff);
  189046. *sp |= (png_byte)(g << shift);
  189047. }
  189048. if (!shift)
  189049. {
  189050. shift = 4;
  189051. sp++;
  189052. }
  189053. else
  189054. shift -= 4;
  189055. }
  189056. }
  189057. else
  189058. #endif
  189059. {
  189060. sp = row;
  189061. shift = 4;
  189062. for (i = 0; i < row_width; i++)
  189063. {
  189064. if ((png_uint_16)((*sp >> shift) & 0x0f)
  189065. == trans_values->gray)
  189066. {
  189067. *sp &= (png_byte)((0xf0f >> (4 - shift)) & 0xff);
  189068. *sp |= (png_byte)(background->gray << shift);
  189069. }
  189070. if (!shift)
  189071. {
  189072. shift = 4;
  189073. sp++;
  189074. }
  189075. else
  189076. shift -= 4;
  189077. }
  189078. }
  189079. break;
  189080. }
  189081. case 8:
  189082. {
  189083. #if defined(PNG_READ_GAMMA_SUPPORTED)
  189084. if (gamma_table != NULL)
  189085. {
  189086. sp = row;
  189087. for (i = 0; i < row_width; i++, sp++)
  189088. {
  189089. if (*sp == trans_values->gray)
  189090. {
  189091. *sp = (png_byte)background->gray;
  189092. }
  189093. else
  189094. {
  189095. *sp = gamma_table[*sp];
  189096. }
  189097. }
  189098. }
  189099. else
  189100. #endif
  189101. {
  189102. sp = row;
  189103. for (i = 0; i < row_width; i++, sp++)
  189104. {
  189105. if (*sp == trans_values->gray)
  189106. {
  189107. *sp = (png_byte)background->gray;
  189108. }
  189109. }
  189110. }
  189111. break;
  189112. }
  189113. case 16:
  189114. {
  189115. #if defined(PNG_READ_GAMMA_SUPPORTED)
  189116. if (gamma_16 != NULL)
  189117. {
  189118. sp = row;
  189119. for (i = 0; i < row_width; i++, sp += 2)
  189120. {
  189121. png_uint_16 v;
  189122. v = (png_uint_16)(((*sp) << 8) + *(sp + 1));
  189123. if (v == trans_values->gray)
  189124. {
  189125. /* background is already in screen gamma */
  189126. *sp = (png_byte)((background->gray >> 8) & 0xff);
  189127. *(sp + 1) = (png_byte)(background->gray & 0xff);
  189128. }
  189129. else
  189130. {
  189131. v = gamma_16[*(sp + 1) >> gamma_shift][*sp];
  189132. *sp = (png_byte)((v >> 8) & 0xff);
  189133. *(sp + 1) = (png_byte)(v & 0xff);
  189134. }
  189135. }
  189136. }
  189137. else
  189138. #endif
  189139. {
  189140. sp = row;
  189141. for (i = 0; i < row_width; i++, sp += 2)
  189142. {
  189143. png_uint_16 v;
  189144. v = (png_uint_16)(((*sp) << 8) + *(sp + 1));
  189145. if (v == trans_values->gray)
  189146. {
  189147. *sp = (png_byte)((background->gray >> 8) & 0xff);
  189148. *(sp + 1) = (png_byte)(background->gray & 0xff);
  189149. }
  189150. }
  189151. }
  189152. break;
  189153. }
  189154. }
  189155. break;
  189156. }
  189157. case PNG_COLOR_TYPE_RGB:
  189158. {
  189159. if (row_info->bit_depth == 8)
  189160. {
  189161. #if defined(PNG_READ_GAMMA_SUPPORTED)
  189162. if (gamma_table != NULL)
  189163. {
  189164. sp = row;
  189165. for (i = 0; i < row_width; i++, sp += 3)
  189166. {
  189167. if (*sp == trans_values->red &&
  189168. *(sp + 1) == trans_values->green &&
  189169. *(sp + 2) == trans_values->blue)
  189170. {
  189171. *sp = (png_byte)background->red;
  189172. *(sp + 1) = (png_byte)background->green;
  189173. *(sp + 2) = (png_byte)background->blue;
  189174. }
  189175. else
  189176. {
  189177. *sp = gamma_table[*sp];
  189178. *(sp + 1) = gamma_table[*(sp + 1)];
  189179. *(sp + 2) = gamma_table[*(sp + 2)];
  189180. }
  189181. }
  189182. }
  189183. else
  189184. #endif
  189185. {
  189186. sp = row;
  189187. for (i = 0; i < row_width; i++, sp += 3)
  189188. {
  189189. if (*sp == trans_values->red &&
  189190. *(sp + 1) == trans_values->green &&
  189191. *(sp + 2) == trans_values->blue)
  189192. {
  189193. *sp = (png_byte)background->red;
  189194. *(sp + 1) = (png_byte)background->green;
  189195. *(sp + 2) = (png_byte)background->blue;
  189196. }
  189197. }
  189198. }
  189199. }
  189200. else /* if (row_info->bit_depth == 16) */
  189201. {
  189202. #if defined(PNG_READ_GAMMA_SUPPORTED)
  189203. if (gamma_16 != NULL)
  189204. {
  189205. sp = row;
  189206. for (i = 0; i < row_width; i++, sp += 6)
  189207. {
  189208. png_uint_16 r = (png_uint_16)(((*sp) << 8) + *(sp + 1));
  189209. png_uint_16 g = (png_uint_16)(((*(sp+2)) << 8) + *(sp+3));
  189210. png_uint_16 b = (png_uint_16)(((*(sp+4)) << 8) + *(sp+5));
  189211. if (r == trans_values->red && g == trans_values->green &&
  189212. b == trans_values->blue)
  189213. {
  189214. /* background is already in screen gamma */
  189215. *sp = (png_byte)((background->red >> 8) & 0xff);
  189216. *(sp + 1) = (png_byte)(background->red & 0xff);
  189217. *(sp + 2) = (png_byte)((background->green >> 8) & 0xff);
  189218. *(sp + 3) = (png_byte)(background->green & 0xff);
  189219. *(sp + 4) = (png_byte)((background->blue >> 8) & 0xff);
  189220. *(sp + 5) = (png_byte)(background->blue & 0xff);
  189221. }
  189222. else
  189223. {
  189224. png_uint_16 v = gamma_16[*(sp + 1) >> gamma_shift][*sp];
  189225. *sp = (png_byte)((v >> 8) & 0xff);
  189226. *(sp + 1) = (png_byte)(v & 0xff);
  189227. v = gamma_16[*(sp + 3) >> gamma_shift][*(sp + 2)];
  189228. *(sp + 2) = (png_byte)((v >> 8) & 0xff);
  189229. *(sp + 3) = (png_byte)(v & 0xff);
  189230. v = gamma_16[*(sp + 5) >> gamma_shift][*(sp + 4)];
  189231. *(sp + 4) = (png_byte)((v >> 8) & 0xff);
  189232. *(sp + 5) = (png_byte)(v & 0xff);
  189233. }
  189234. }
  189235. }
  189236. else
  189237. #endif
  189238. {
  189239. sp = row;
  189240. for (i = 0; i < row_width; i++, sp += 6)
  189241. {
  189242. png_uint_16 r = (png_uint_16)(((*sp) << 8) + *(sp+1));
  189243. png_uint_16 g = (png_uint_16)(((*(sp+2)) << 8) + *(sp+3));
  189244. png_uint_16 b = (png_uint_16)(((*(sp+4)) << 8) + *(sp+5));
  189245. if (r == trans_values->red && g == trans_values->green &&
  189246. b == trans_values->blue)
  189247. {
  189248. *sp = (png_byte)((background->red >> 8) & 0xff);
  189249. *(sp + 1) = (png_byte)(background->red & 0xff);
  189250. *(sp + 2) = (png_byte)((background->green >> 8) & 0xff);
  189251. *(sp + 3) = (png_byte)(background->green & 0xff);
  189252. *(sp + 4) = (png_byte)((background->blue >> 8) & 0xff);
  189253. *(sp + 5) = (png_byte)(background->blue & 0xff);
  189254. }
  189255. }
  189256. }
  189257. }
  189258. break;
  189259. }
  189260. case PNG_COLOR_TYPE_GRAY_ALPHA:
  189261. {
  189262. if (row_info->bit_depth == 8)
  189263. {
  189264. #if defined(PNG_READ_GAMMA_SUPPORTED)
  189265. if (gamma_to_1 != NULL && gamma_from_1 != NULL &&
  189266. gamma_table != NULL)
  189267. {
  189268. sp = row;
  189269. dp = row;
  189270. for (i = 0; i < row_width; i++, sp += 2, dp++)
  189271. {
  189272. png_uint_16 a = *(sp + 1);
  189273. if (a == 0xff)
  189274. {
  189275. *dp = gamma_table[*sp];
  189276. }
  189277. else if (a == 0)
  189278. {
  189279. /* background is already in screen gamma */
  189280. *dp = (png_byte)background->gray;
  189281. }
  189282. else
  189283. {
  189284. png_byte v, w;
  189285. v = gamma_to_1[*sp];
  189286. png_composite(w, v, a, background_1->gray);
  189287. *dp = gamma_from_1[w];
  189288. }
  189289. }
  189290. }
  189291. else
  189292. #endif
  189293. {
  189294. sp = row;
  189295. dp = row;
  189296. for (i = 0; i < row_width; i++, sp += 2, dp++)
  189297. {
  189298. png_byte a = *(sp + 1);
  189299. if (a == 0xff)
  189300. {
  189301. *dp = *sp;
  189302. }
  189303. #if defined(PNG_READ_GAMMA_SUPPORTED)
  189304. else if (a == 0)
  189305. {
  189306. *dp = (png_byte)background->gray;
  189307. }
  189308. else
  189309. {
  189310. png_composite(*dp, *sp, a, background_1->gray);
  189311. }
  189312. #else
  189313. *dp = (png_byte)background->gray;
  189314. #endif
  189315. }
  189316. }
  189317. }
  189318. else /* if (png_ptr->bit_depth == 16) */
  189319. {
  189320. #if defined(PNG_READ_GAMMA_SUPPORTED)
  189321. if (gamma_16 != NULL && gamma_16_from_1 != NULL &&
  189322. gamma_16_to_1 != NULL)
  189323. {
  189324. sp = row;
  189325. dp = row;
  189326. for (i = 0; i < row_width; i++, sp += 4, dp += 2)
  189327. {
  189328. png_uint_16 a = (png_uint_16)(((*(sp+2)) << 8) + *(sp+3));
  189329. if (a == (png_uint_16)0xffff)
  189330. {
  189331. png_uint_16 v;
  189332. v = gamma_16[*(sp + 1) >> gamma_shift][*sp];
  189333. *dp = (png_byte)((v >> 8) & 0xff);
  189334. *(dp + 1) = (png_byte)(v & 0xff);
  189335. }
  189336. #if defined(PNG_READ_GAMMA_SUPPORTED)
  189337. else if (a == 0)
  189338. #else
  189339. else
  189340. #endif
  189341. {
  189342. /* background is already in screen gamma */
  189343. *dp = (png_byte)((background->gray >> 8) & 0xff);
  189344. *(dp + 1) = (png_byte)(background->gray & 0xff);
  189345. }
  189346. #if defined(PNG_READ_GAMMA_SUPPORTED)
  189347. else
  189348. {
  189349. png_uint_16 g, v, w;
  189350. g = gamma_16_to_1[*(sp + 1) >> gamma_shift][*sp];
  189351. png_composite_16(v, g, a, background_1->gray);
  189352. w = gamma_16_from_1[(v&0xff) >> gamma_shift][v >> 8];
  189353. *dp = (png_byte)((w >> 8) & 0xff);
  189354. *(dp + 1) = (png_byte)(w & 0xff);
  189355. }
  189356. #endif
  189357. }
  189358. }
  189359. else
  189360. #endif
  189361. {
  189362. sp = row;
  189363. dp = row;
  189364. for (i = 0; i < row_width; i++, sp += 4, dp += 2)
  189365. {
  189366. png_uint_16 a = (png_uint_16)(((*(sp+2)) << 8) + *(sp+3));
  189367. if (a == (png_uint_16)0xffff)
  189368. {
  189369. png_memcpy(dp, sp, 2);
  189370. }
  189371. #if defined(PNG_READ_GAMMA_SUPPORTED)
  189372. else if (a == 0)
  189373. #else
  189374. else
  189375. #endif
  189376. {
  189377. *dp = (png_byte)((background->gray >> 8) & 0xff);
  189378. *(dp + 1) = (png_byte)(background->gray & 0xff);
  189379. }
  189380. #if defined(PNG_READ_GAMMA_SUPPORTED)
  189381. else
  189382. {
  189383. png_uint_16 g, v;
  189384. g = (png_uint_16)(((*sp) << 8) + *(sp + 1));
  189385. png_composite_16(v, g, a, background_1->gray);
  189386. *dp = (png_byte)((v >> 8) & 0xff);
  189387. *(dp + 1) = (png_byte)(v & 0xff);
  189388. }
  189389. #endif
  189390. }
  189391. }
  189392. }
  189393. break;
  189394. }
  189395. case PNG_COLOR_TYPE_RGB_ALPHA:
  189396. {
  189397. if (row_info->bit_depth == 8)
  189398. {
  189399. #if defined(PNG_READ_GAMMA_SUPPORTED)
  189400. if (gamma_to_1 != NULL && gamma_from_1 != NULL &&
  189401. gamma_table != NULL)
  189402. {
  189403. sp = row;
  189404. dp = row;
  189405. for (i = 0; i < row_width; i++, sp += 4, dp += 3)
  189406. {
  189407. png_byte a = *(sp + 3);
  189408. if (a == 0xff)
  189409. {
  189410. *dp = gamma_table[*sp];
  189411. *(dp + 1) = gamma_table[*(sp + 1)];
  189412. *(dp + 2) = gamma_table[*(sp + 2)];
  189413. }
  189414. else if (a == 0)
  189415. {
  189416. /* background is already in screen gamma */
  189417. *dp = (png_byte)background->red;
  189418. *(dp + 1) = (png_byte)background->green;
  189419. *(dp + 2) = (png_byte)background->blue;
  189420. }
  189421. else
  189422. {
  189423. png_byte v, w;
  189424. v = gamma_to_1[*sp];
  189425. png_composite(w, v, a, background_1->red);
  189426. *dp = gamma_from_1[w];
  189427. v = gamma_to_1[*(sp + 1)];
  189428. png_composite(w, v, a, background_1->green);
  189429. *(dp + 1) = gamma_from_1[w];
  189430. v = gamma_to_1[*(sp + 2)];
  189431. png_composite(w, v, a, background_1->blue);
  189432. *(dp + 2) = gamma_from_1[w];
  189433. }
  189434. }
  189435. }
  189436. else
  189437. #endif
  189438. {
  189439. sp = row;
  189440. dp = row;
  189441. for (i = 0; i < row_width; i++, sp += 4, dp += 3)
  189442. {
  189443. png_byte a = *(sp + 3);
  189444. if (a == 0xff)
  189445. {
  189446. *dp = *sp;
  189447. *(dp + 1) = *(sp + 1);
  189448. *(dp + 2) = *(sp + 2);
  189449. }
  189450. else if (a == 0)
  189451. {
  189452. *dp = (png_byte)background->red;
  189453. *(dp + 1) = (png_byte)background->green;
  189454. *(dp + 2) = (png_byte)background->blue;
  189455. }
  189456. else
  189457. {
  189458. png_composite(*dp, *sp, a, background->red);
  189459. png_composite(*(dp + 1), *(sp + 1), a,
  189460. background->green);
  189461. png_composite(*(dp + 2), *(sp + 2), a,
  189462. background->blue);
  189463. }
  189464. }
  189465. }
  189466. }
  189467. else /* if (row_info->bit_depth == 16) */
  189468. {
  189469. #if defined(PNG_READ_GAMMA_SUPPORTED)
  189470. if (gamma_16 != NULL && gamma_16_from_1 != NULL &&
  189471. gamma_16_to_1 != NULL)
  189472. {
  189473. sp = row;
  189474. dp = row;
  189475. for (i = 0; i < row_width; i++, sp += 8, dp += 6)
  189476. {
  189477. png_uint_16 a = (png_uint_16)(((png_uint_16)(*(sp + 6))
  189478. << 8) + (png_uint_16)(*(sp + 7)));
  189479. if (a == (png_uint_16)0xffff)
  189480. {
  189481. png_uint_16 v;
  189482. v = gamma_16[*(sp + 1) >> gamma_shift][*sp];
  189483. *dp = (png_byte)((v >> 8) & 0xff);
  189484. *(dp + 1) = (png_byte)(v & 0xff);
  189485. v = gamma_16[*(sp + 3) >> gamma_shift][*(sp + 2)];
  189486. *(dp + 2) = (png_byte)((v >> 8) & 0xff);
  189487. *(dp + 3) = (png_byte)(v & 0xff);
  189488. v = gamma_16[*(sp + 5) >> gamma_shift][*(sp + 4)];
  189489. *(dp + 4) = (png_byte)((v >> 8) & 0xff);
  189490. *(dp + 5) = (png_byte)(v & 0xff);
  189491. }
  189492. else if (a == 0)
  189493. {
  189494. /* background is already in screen gamma */
  189495. *dp = (png_byte)((background->red >> 8) & 0xff);
  189496. *(dp + 1) = (png_byte)(background->red & 0xff);
  189497. *(dp + 2) = (png_byte)((background->green >> 8) & 0xff);
  189498. *(dp + 3) = (png_byte)(background->green & 0xff);
  189499. *(dp + 4) = (png_byte)((background->blue >> 8) & 0xff);
  189500. *(dp + 5) = (png_byte)(background->blue & 0xff);
  189501. }
  189502. else
  189503. {
  189504. png_uint_16 v, w, x;
  189505. v = gamma_16_to_1[*(sp + 1) >> gamma_shift][*sp];
  189506. png_composite_16(w, v, a, background_1->red);
  189507. x = gamma_16_from_1[((w&0xff) >> gamma_shift)][w >> 8];
  189508. *dp = (png_byte)((x >> 8) & 0xff);
  189509. *(dp + 1) = (png_byte)(x & 0xff);
  189510. v = gamma_16_to_1[*(sp + 3) >> gamma_shift][*(sp + 2)];
  189511. png_composite_16(w, v, a, background_1->green);
  189512. x = gamma_16_from_1[((w&0xff) >> gamma_shift)][w >> 8];
  189513. *(dp + 2) = (png_byte)((x >> 8) & 0xff);
  189514. *(dp + 3) = (png_byte)(x & 0xff);
  189515. v = gamma_16_to_1[*(sp + 5) >> gamma_shift][*(sp + 4)];
  189516. png_composite_16(w, v, a, background_1->blue);
  189517. x = gamma_16_from_1[(w & 0xff) >> gamma_shift][w >> 8];
  189518. *(dp + 4) = (png_byte)((x >> 8) & 0xff);
  189519. *(dp + 5) = (png_byte)(x & 0xff);
  189520. }
  189521. }
  189522. }
  189523. else
  189524. #endif
  189525. {
  189526. sp = row;
  189527. dp = row;
  189528. for (i = 0; i < row_width; i++, sp += 8, dp += 6)
  189529. {
  189530. png_uint_16 a = (png_uint_16)(((png_uint_16)(*(sp + 6))
  189531. << 8) + (png_uint_16)(*(sp + 7)));
  189532. if (a == (png_uint_16)0xffff)
  189533. {
  189534. png_memcpy(dp, sp, 6);
  189535. }
  189536. else if (a == 0)
  189537. {
  189538. *dp = (png_byte)((background->red >> 8) & 0xff);
  189539. *(dp + 1) = (png_byte)(background->red & 0xff);
  189540. *(dp + 2) = (png_byte)((background->green >> 8) & 0xff);
  189541. *(dp + 3) = (png_byte)(background->green & 0xff);
  189542. *(dp + 4) = (png_byte)((background->blue >> 8) & 0xff);
  189543. *(dp + 5) = (png_byte)(background->blue & 0xff);
  189544. }
  189545. else
  189546. {
  189547. png_uint_16 v;
  189548. png_uint_16 r = (png_uint_16)(((*sp) << 8) + *(sp + 1));
  189549. png_uint_16 g = (png_uint_16)(((*(sp + 2)) << 8)
  189550. + *(sp + 3));
  189551. png_uint_16 b = (png_uint_16)(((*(sp + 4)) << 8)
  189552. + *(sp + 5));
  189553. png_composite_16(v, r, a, background->red);
  189554. *dp = (png_byte)((v >> 8) & 0xff);
  189555. *(dp + 1) = (png_byte)(v & 0xff);
  189556. png_composite_16(v, g, a, background->green);
  189557. *(dp + 2) = (png_byte)((v >> 8) & 0xff);
  189558. *(dp + 3) = (png_byte)(v & 0xff);
  189559. png_composite_16(v, b, a, background->blue);
  189560. *(dp + 4) = (png_byte)((v >> 8) & 0xff);
  189561. *(dp + 5) = (png_byte)(v & 0xff);
  189562. }
  189563. }
  189564. }
  189565. }
  189566. break;
  189567. }
  189568. }
  189569. if (row_info->color_type & PNG_COLOR_MASK_ALPHA)
  189570. {
  189571. row_info->color_type &= ~PNG_COLOR_MASK_ALPHA;
  189572. row_info->channels--;
  189573. row_info->pixel_depth = (png_byte)(row_info->channels *
  189574. row_info->bit_depth);
  189575. row_info->rowbytes = PNG_ROWBYTES(row_info->pixel_depth,row_width);
  189576. }
  189577. }
  189578. }
  189579. #endif
  189580. #if defined(PNG_READ_GAMMA_SUPPORTED)
  189581. /* Gamma correct the image, avoiding the alpha channel. Make sure
  189582. * you do this after you deal with the transparency issue on grayscale
  189583. * or RGB images. If your bit depth is 8, use gamma_table, if it
  189584. * is 16, use gamma_16_table and gamma_shift. Build these with
  189585. * build_gamma_table().
  189586. */
  189587. void /* PRIVATE */
  189588. png_do_gamma(png_row_infop row_info, png_bytep row,
  189589. png_bytep gamma_table, png_uint_16pp gamma_16_table,
  189590. int gamma_shift)
  189591. {
  189592. png_bytep sp;
  189593. png_uint_32 i;
  189594. png_uint_32 row_width=row_info->width;
  189595. png_debug(1, "in png_do_gamma\n");
  189596. if (
  189597. #if defined(PNG_USELESS_TESTS_SUPPORTED)
  189598. row != NULL && row_info != NULL &&
  189599. #endif
  189600. ((row_info->bit_depth <= 8 && gamma_table != NULL) ||
  189601. (row_info->bit_depth == 16 && gamma_16_table != NULL)))
  189602. {
  189603. switch (row_info->color_type)
  189604. {
  189605. case PNG_COLOR_TYPE_RGB:
  189606. {
  189607. if (row_info->bit_depth == 8)
  189608. {
  189609. sp = row;
  189610. for (i = 0; i < row_width; i++)
  189611. {
  189612. *sp = gamma_table[*sp];
  189613. sp++;
  189614. *sp = gamma_table[*sp];
  189615. sp++;
  189616. *sp = gamma_table[*sp];
  189617. sp++;
  189618. }
  189619. }
  189620. else /* if (row_info->bit_depth == 16) */
  189621. {
  189622. sp = row;
  189623. for (i = 0; i < row_width; i++)
  189624. {
  189625. png_uint_16 v;
  189626. v = gamma_16_table[*(sp + 1) >> gamma_shift][*sp];
  189627. *sp = (png_byte)((v >> 8) & 0xff);
  189628. *(sp + 1) = (png_byte)(v & 0xff);
  189629. sp += 2;
  189630. v = gamma_16_table[*(sp + 1) >> gamma_shift][*sp];
  189631. *sp = (png_byte)((v >> 8) & 0xff);
  189632. *(sp + 1) = (png_byte)(v & 0xff);
  189633. sp += 2;
  189634. v = gamma_16_table[*(sp + 1) >> gamma_shift][*sp];
  189635. *sp = (png_byte)((v >> 8) & 0xff);
  189636. *(sp + 1) = (png_byte)(v & 0xff);
  189637. sp += 2;
  189638. }
  189639. }
  189640. break;
  189641. }
  189642. case PNG_COLOR_TYPE_RGB_ALPHA:
  189643. {
  189644. if (row_info->bit_depth == 8)
  189645. {
  189646. sp = row;
  189647. for (i = 0; i < row_width; i++)
  189648. {
  189649. *sp = gamma_table[*sp];
  189650. sp++;
  189651. *sp = gamma_table[*sp];
  189652. sp++;
  189653. *sp = gamma_table[*sp];
  189654. sp++;
  189655. sp++;
  189656. }
  189657. }
  189658. else /* if (row_info->bit_depth == 16) */
  189659. {
  189660. sp = row;
  189661. for (i = 0; i < row_width; i++)
  189662. {
  189663. png_uint_16 v = gamma_16_table[*(sp + 1) >> gamma_shift][*sp];
  189664. *sp = (png_byte)((v >> 8) & 0xff);
  189665. *(sp + 1) = (png_byte)(v & 0xff);
  189666. sp += 2;
  189667. v = gamma_16_table[*(sp + 1) >> gamma_shift][*sp];
  189668. *sp = (png_byte)((v >> 8) & 0xff);
  189669. *(sp + 1) = (png_byte)(v & 0xff);
  189670. sp += 2;
  189671. v = gamma_16_table[*(sp + 1) >> gamma_shift][*sp];
  189672. *sp = (png_byte)((v >> 8) & 0xff);
  189673. *(sp + 1) = (png_byte)(v & 0xff);
  189674. sp += 4;
  189675. }
  189676. }
  189677. break;
  189678. }
  189679. case PNG_COLOR_TYPE_GRAY_ALPHA:
  189680. {
  189681. if (row_info->bit_depth == 8)
  189682. {
  189683. sp = row;
  189684. for (i = 0; i < row_width; i++)
  189685. {
  189686. *sp = gamma_table[*sp];
  189687. sp += 2;
  189688. }
  189689. }
  189690. else /* if (row_info->bit_depth == 16) */
  189691. {
  189692. sp = row;
  189693. for (i = 0; i < row_width; i++)
  189694. {
  189695. png_uint_16 v = gamma_16_table[*(sp + 1) >> gamma_shift][*sp];
  189696. *sp = (png_byte)((v >> 8) & 0xff);
  189697. *(sp + 1) = (png_byte)(v & 0xff);
  189698. sp += 4;
  189699. }
  189700. }
  189701. break;
  189702. }
  189703. case PNG_COLOR_TYPE_GRAY:
  189704. {
  189705. if (row_info->bit_depth == 2)
  189706. {
  189707. sp = row;
  189708. for (i = 0; i < row_width; i += 4)
  189709. {
  189710. int a = *sp & 0xc0;
  189711. int b = *sp & 0x30;
  189712. int c = *sp & 0x0c;
  189713. int d = *sp & 0x03;
  189714. *sp = (png_byte)(
  189715. ((((int)gamma_table[a|(a>>2)|(a>>4)|(a>>6)]) ) & 0xc0)|
  189716. ((((int)gamma_table[(b<<2)|b|(b>>2)|(b>>4)])>>2) & 0x30)|
  189717. ((((int)gamma_table[(c<<4)|(c<<2)|c|(c>>2)])>>4) & 0x0c)|
  189718. ((((int)gamma_table[(d<<6)|(d<<4)|(d<<2)|d])>>6) ));
  189719. sp++;
  189720. }
  189721. }
  189722. if (row_info->bit_depth == 4)
  189723. {
  189724. sp = row;
  189725. for (i = 0; i < row_width; i += 2)
  189726. {
  189727. int msb = *sp & 0xf0;
  189728. int lsb = *sp & 0x0f;
  189729. *sp = (png_byte)((((int)gamma_table[msb | (msb >> 4)]) & 0xf0)
  189730. | (((int)gamma_table[(lsb << 4) | lsb]) >> 4));
  189731. sp++;
  189732. }
  189733. }
  189734. else if (row_info->bit_depth == 8)
  189735. {
  189736. sp = row;
  189737. for (i = 0; i < row_width; i++)
  189738. {
  189739. *sp = gamma_table[*sp];
  189740. sp++;
  189741. }
  189742. }
  189743. else if (row_info->bit_depth == 16)
  189744. {
  189745. sp = row;
  189746. for (i = 0; i < row_width; i++)
  189747. {
  189748. png_uint_16 v = gamma_16_table[*(sp + 1) >> gamma_shift][*sp];
  189749. *sp = (png_byte)((v >> 8) & 0xff);
  189750. *(sp + 1) = (png_byte)(v & 0xff);
  189751. sp += 2;
  189752. }
  189753. }
  189754. break;
  189755. }
  189756. }
  189757. }
  189758. }
  189759. #endif
  189760. #if defined(PNG_READ_EXPAND_SUPPORTED)
  189761. /* Expands a palette row to an RGB or RGBA row depending
  189762. * upon whether you supply trans and num_trans.
  189763. */
  189764. void /* PRIVATE */
  189765. png_do_expand_palette(png_row_infop row_info, png_bytep row,
  189766. png_colorp palette, png_bytep trans, int num_trans)
  189767. {
  189768. int shift, value;
  189769. png_bytep sp, dp;
  189770. png_uint_32 i;
  189771. png_uint_32 row_width=row_info->width;
  189772. png_debug(1, "in png_do_expand_palette\n");
  189773. if (
  189774. #if defined(PNG_USELESS_TESTS_SUPPORTED)
  189775. row != NULL && row_info != NULL &&
  189776. #endif
  189777. row_info->color_type == PNG_COLOR_TYPE_PALETTE)
  189778. {
  189779. if (row_info->bit_depth < 8)
  189780. {
  189781. switch (row_info->bit_depth)
  189782. {
  189783. case 1:
  189784. {
  189785. sp = row + (png_size_t)((row_width - 1) >> 3);
  189786. dp = row + (png_size_t)row_width - 1;
  189787. shift = 7 - (int)((row_width + 7) & 0x07);
  189788. for (i = 0; i < row_width; i++)
  189789. {
  189790. if ((*sp >> shift) & 0x01)
  189791. *dp = 1;
  189792. else
  189793. *dp = 0;
  189794. if (shift == 7)
  189795. {
  189796. shift = 0;
  189797. sp--;
  189798. }
  189799. else
  189800. shift++;
  189801. dp--;
  189802. }
  189803. break;
  189804. }
  189805. case 2:
  189806. {
  189807. sp = row + (png_size_t)((row_width - 1) >> 2);
  189808. dp = row + (png_size_t)row_width - 1;
  189809. shift = (int)((3 - ((row_width + 3) & 0x03)) << 1);
  189810. for (i = 0; i < row_width; i++)
  189811. {
  189812. value = (*sp >> shift) & 0x03;
  189813. *dp = (png_byte)value;
  189814. if (shift == 6)
  189815. {
  189816. shift = 0;
  189817. sp--;
  189818. }
  189819. else
  189820. shift += 2;
  189821. dp--;
  189822. }
  189823. break;
  189824. }
  189825. case 4:
  189826. {
  189827. sp = row + (png_size_t)((row_width - 1) >> 1);
  189828. dp = row + (png_size_t)row_width - 1;
  189829. shift = (int)((row_width & 0x01) << 2);
  189830. for (i = 0; i < row_width; i++)
  189831. {
  189832. value = (*sp >> shift) & 0x0f;
  189833. *dp = (png_byte)value;
  189834. if (shift == 4)
  189835. {
  189836. shift = 0;
  189837. sp--;
  189838. }
  189839. else
  189840. shift += 4;
  189841. dp--;
  189842. }
  189843. break;
  189844. }
  189845. }
  189846. row_info->bit_depth = 8;
  189847. row_info->pixel_depth = 8;
  189848. row_info->rowbytes = row_width;
  189849. }
  189850. switch (row_info->bit_depth)
  189851. {
  189852. case 8:
  189853. {
  189854. if (trans != NULL)
  189855. {
  189856. sp = row + (png_size_t)row_width - 1;
  189857. dp = row + (png_size_t)(row_width << 2) - 1;
  189858. for (i = 0; i < row_width; i++)
  189859. {
  189860. if ((int)(*sp) >= num_trans)
  189861. *dp-- = 0xff;
  189862. else
  189863. *dp-- = trans[*sp];
  189864. *dp-- = palette[*sp].blue;
  189865. *dp-- = palette[*sp].green;
  189866. *dp-- = palette[*sp].red;
  189867. sp--;
  189868. }
  189869. row_info->bit_depth = 8;
  189870. row_info->pixel_depth = 32;
  189871. row_info->rowbytes = row_width * 4;
  189872. row_info->color_type = 6;
  189873. row_info->channels = 4;
  189874. }
  189875. else
  189876. {
  189877. sp = row + (png_size_t)row_width - 1;
  189878. dp = row + (png_size_t)(row_width * 3) - 1;
  189879. for (i = 0; i < row_width; i++)
  189880. {
  189881. *dp-- = palette[*sp].blue;
  189882. *dp-- = palette[*sp].green;
  189883. *dp-- = palette[*sp].red;
  189884. sp--;
  189885. }
  189886. row_info->bit_depth = 8;
  189887. row_info->pixel_depth = 24;
  189888. row_info->rowbytes = row_width * 3;
  189889. row_info->color_type = 2;
  189890. row_info->channels = 3;
  189891. }
  189892. break;
  189893. }
  189894. }
  189895. }
  189896. }
  189897. /* If the bit depth < 8, it is expanded to 8. Also, if the already
  189898. * expanded transparency value is supplied, an alpha channel is built.
  189899. */
  189900. void /* PRIVATE */
  189901. png_do_expand(png_row_infop row_info, png_bytep row,
  189902. png_color_16p trans_value)
  189903. {
  189904. int shift, value;
  189905. png_bytep sp, dp;
  189906. png_uint_32 i;
  189907. png_uint_32 row_width=row_info->width;
  189908. png_debug(1, "in png_do_expand\n");
  189909. #if defined(PNG_USELESS_TESTS_SUPPORTED)
  189910. if (row != NULL && row_info != NULL)
  189911. #endif
  189912. {
  189913. if (row_info->color_type == PNG_COLOR_TYPE_GRAY)
  189914. {
  189915. png_uint_16 gray = (png_uint_16)(trans_value ? trans_value->gray : 0);
  189916. if (row_info->bit_depth < 8)
  189917. {
  189918. switch (row_info->bit_depth)
  189919. {
  189920. case 1:
  189921. {
  189922. gray = (png_uint_16)((gray&0x01)*0xff);
  189923. sp = row + (png_size_t)((row_width - 1) >> 3);
  189924. dp = row + (png_size_t)row_width - 1;
  189925. shift = 7 - (int)((row_width + 7) & 0x07);
  189926. for (i = 0; i < row_width; i++)
  189927. {
  189928. if ((*sp >> shift) & 0x01)
  189929. *dp = 0xff;
  189930. else
  189931. *dp = 0;
  189932. if (shift == 7)
  189933. {
  189934. shift = 0;
  189935. sp--;
  189936. }
  189937. else
  189938. shift++;
  189939. dp--;
  189940. }
  189941. break;
  189942. }
  189943. case 2:
  189944. {
  189945. gray = (png_uint_16)((gray&0x03)*0x55);
  189946. sp = row + (png_size_t)((row_width - 1) >> 2);
  189947. dp = row + (png_size_t)row_width - 1;
  189948. shift = (int)((3 - ((row_width + 3) & 0x03)) << 1);
  189949. for (i = 0; i < row_width; i++)
  189950. {
  189951. value = (*sp >> shift) & 0x03;
  189952. *dp = (png_byte)(value | (value << 2) | (value << 4) |
  189953. (value << 6));
  189954. if (shift == 6)
  189955. {
  189956. shift = 0;
  189957. sp--;
  189958. }
  189959. else
  189960. shift += 2;
  189961. dp--;
  189962. }
  189963. break;
  189964. }
  189965. case 4:
  189966. {
  189967. gray = (png_uint_16)((gray&0x0f)*0x11);
  189968. sp = row + (png_size_t)((row_width - 1) >> 1);
  189969. dp = row + (png_size_t)row_width - 1;
  189970. shift = (int)((1 - ((row_width + 1) & 0x01)) << 2);
  189971. for (i = 0; i < row_width; i++)
  189972. {
  189973. value = (*sp >> shift) & 0x0f;
  189974. *dp = (png_byte)(value | (value << 4));
  189975. if (shift == 4)
  189976. {
  189977. shift = 0;
  189978. sp--;
  189979. }
  189980. else
  189981. shift = 4;
  189982. dp--;
  189983. }
  189984. break;
  189985. }
  189986. }
  189987. row_info->bit_depth = 8;
  189988. row_info->pixel_depth = 8;
  189989. row_info->rowbytes = row_width;
  189990. }
  189991. if (trans_value != NULL)
  189992. {
  189993. if (row_info->bit_depth == 8)
  189994. {
  189995. gray = gray & 0xff;
  189996. sp = row + (png_size_t)row_width - 1;
  189997. dp = row + (png_size_t)(row_width << 1) - 1;
  189998. for (i = 0; i < row_width; i++)
  189999. {
  190000. if (*sp == gray)
  190001. *dp-- = 0;
  190002. else
  190003. *dp-- = 0xff;
  190004. *dp-- = *sp--;
  190005. }
  190006. }
  190007. else if (row_info->bit_depth == 16)
  190008. {
  190009. png_byte gray_high = (gray >> 8) & 0xff;
  190010. png_byte gray_low = gray & 0xff;
  190011. sp = row + row_info->rowbytes - 1;
  190012. dp = row + (row_info->rowbytes << 1) - 1;
  190013. for (i = 0; i < row_width; i++)
  190014. {
  190015. if (*(sp-1) == gray_high && *(sp) == gray_low)
  190016. {
  190017. *dp-- = 0;
  190018. *dp-- = 0;
  190019. }
  190020. else
  190021. {
  190022. *dp-- = 0xff;
  190023. *dp-- = 0xff;
  190024. }
  190025. *dp-- = *sp--;
  190026. *dp-- = *sp--;
  190027. }
  190028. }
  190029. row_info->color_type = PNG_COLOR_TYPE_GRAY_ALPHA;
  190030. row_info->channels = 2;
  190031. row_info->pixel_depth = (png_byte)(row_info->bit_depth << 1);
  190032. row_info->rowbytes = PNG_ROWBYTES(row_info->pixel_depth,
  190033. row_width);
  190034. }
  190035. }
  190036. else if (row_info->color_type == PNG_COLOR_TYPE_RGB && trans_value)
  190037. {
  190038. if (row_info->bit_depth == 8)
  190039. {
  190040. png_byte red = trans_value->red & 0xff;
  190041. png_byte green = trans_value->green & 0xff;
  190042. png_byte blue = trans_value->blue & 0xff;
  190043. sp = row + (png_size_t)row_info->rowbytes - 1;
  190044. dp = row + (png_size_t)(row_width << 2) - 1;
  190045. for (i = 0; i < row_width; i++)
  190046. {
  190047. if (*(sp - 2) == red && *(sp - 1) == green && *(sp) == blue)
  190048. *dp-- = 0;
  190049. else
  190050. *dp-- = 0xff;
  190051. *dp-- = *sp--;
  190052. *dp-- = *sp--;
  190053. *dp-- = *sp--;
  190054. }
  190055. }
  190056. else if (row_info->bit_depth == 16)
  190057. {
  190058. png_byte red_high = (trans_value->red >> 8) & 0xff;
  190059. png_byte green_high = (trans_value->green >> 8) & 0xff;
  190060. png_byte blue_high = (trans_value->blue >> 8) & 0xff;
  190061. png_byte red_low = trans_value->red & 0xff;
  190062. png_byte green_low = trans_value->green & 0xff;
  190063. png_byte blue_low = trans_value->blue & 0xff;
  190064. sp = row + row_info->rowbytes - 1;
  190065. dp = row + (png_size_t)(row_width << 3) - 1;
  190066. for (i = 0; i < row_width; i++)
  190067. {
  190068. if (*(sp - 5) == red_high &&
  190069. *(sp - 4) == red_low &&
  190070. *(sp - 3) == green_high &&
  190071. *(sp - 2) == green_low &&
  190072. *(sp - 1) == blue_high &&
  190073. *(sp ) == blue_low)
  190074. {
  190075. *dp-- = 0;
  190076. *dp-- = 0;
  190077. }
  190078. else
  190079. {
  190080. *dp-- = 0xff;
  190081. *dp-- = 0xff;
  190082. }
  190083. *dp-- = *sp--;
  190084. *dp-- = *sp--;
  190085. *dp-- = *sp--;
  190086. *dp-- = *sp--;
  190087. *dp-- = *sp--;
  190088. *dp-- = *sp--;
  190089. }
  190090. }
  190091. row_info->color_type = PNG_COLOR_TYPE_RGB_ALPHA;
  190092. row_info->channels = 4;
  190093. row_info->pixel_depth = (png_byte)(row_info->bit_depth << 2);
  190094. row_info->rowbytes = PNG_ROWBYTES(row_info->pixel_depth,row_width);
  190095. }
  190096. }
  190097. }
  190098. #endif
  190099. #if defined(PNG_READ_DITHER_SUPPORTED)
  190100. void /* PRIVATE */
  190101. png_do_dither(png_row_infop row_info, png_bytep row,
  190102. png_bytep palette_lookup, png_bytep dither_lookup)
  190103. {
  190104. png_bytep sp, dp;
  190105. png_uint_32 i;
  190106. png_uint_32 row_width=row_info->width;
  190107. png_debug(1, "in png_do_dither\n");
  190108. #if defined(PNG_USELESS_TESTS_SUPPORTED)
  190109. if (row != NULL && row_info != NULL)
  190110. #endif
  190111. {
  190112. if (row_info->color_type == PNG_COLOR_TYPE_RGB &&
  190113. palette_lookup && row_info->bit_depth == 8)
  190114. {
  190115. int r, g, b, p;
  190116. sp = row;
  190117. dp = row;
  190118. for (i = 0; i < row_width; i++)
  190119. {
  190120. r = *sp++;
  190121. g = *sp++;
  190122. b = *sp++;
  190123. /* this looks real messy, but the compiler will reduce
  190124. it down to a reasonable formula. For example, with
  190125. 5 bits per color, we get:
  190126. p = (((r >> 3) & 0x1f) << 10) |
  190127. (((g >> 3) & 0x1f) << 5) |
  190128. ((b >> 3) & 0x1f);
  190129. */
  190130. p = (((r >> (8 - PNG_DITHER_RED_BITS)) &
  190131. ((1 << PNG_DITHER_RED_BITS) - 1)) <<
  190132. (PNG_DITHER_GREEN_BITS + PNG_DITHER_BLUE_BITS)) |
  190133. (((g >> (8 - PNG_DITHER_GREEN_BITS)) &
  190134. ((1 << PNG_DITHER_GREEN_BITS) - 1)) <<
  190135. (PNG_DITHER_BLUE_BITS)) |
  190136. ((b >> (8 - PNG_DITHER_BLUE_BITS)) &
  190137. ((1 << PNG_DITHER_BLUE_BITS) - 1));
  190138. *dp++ = palette_lookup[p];
  190139. }
  190140. row_info->color_type = PNG_COLOR_TYPE_PALETTE;
  190141. row_info->channels = 1;
  190142. row_info->pixel_depth = row_info->bit_depth;
  190143. row_info->rowbytes = PNG_ROWBYTES(row_info->pixel_depth,row_width);
  190144. }
  190145. else if (row_info->color_type == PNG_COLOR_TYPE_RGB_ALPHA &&
  190146. palette_lookup != NULL && row_info->bit_depth == 8)
  190147. {
  190148. int r, g, b, p;
  190149. sp = row;
  190150. dp = row;
  190151. for (i = 0; i < row_width; i++)
  190152. {
  190153. r = *sp++;
  190154. g = *sp++;
  190155. b = *sp++;
  190156. sp++;
  190157. p = (((r >> (8 - PNG_DITHER_RED_BITS)) &
  190158. ((1 << PNG_DITHER_RED_BITS) - 1)) <<
  190159. (PNG_DITHER_GREEN_BITS + PNG_DITHER_BLUE_BITS)) |
  190160. (((g >> (8 - PNG_DITHER_GREEN_BITS)) &
  190161. ((1 << PNG_DITHER_GREEN_BITS) - 1)) <<
  190162. (PNG_DITHER_BLUE_BITS)) |
  190163. ((b >> (8 - PNG_DITHER_BLUE_BITS)) &
  190164. ((1 << PNG_DITHER_BLUE_BITS) - 1));
  190165. *dp++ = palette_lookup[p];
  190166. }
  190167. row_info->color_type = PNG_COLOR_TYPE_PALETTE;
  190168. row_info->channels = 1;
  190169. row_info->pixel_depth = row_info->bit_depth;
  190170. row_info->rowbytes = PNG_ROWBYTES(row_info->pixel_depth,row_width);
  190171. }
  190172. else if (row_info->color_type == PNG_COLOR_TYPE_PALETTE &&
  190173. dither_lookup && row_info->bit_depth == 8)
  190174. {
  190175. sp = row;
  190176. for (i = 0; i < row_width; i++, sp++)
  190177. {
  190178. *sp = dither_lookup[*sp];
  190179. }
  190180. }
  190181. }
  190182. }
  190183. #endif
  190184. #ifdef PNG_FLOATING_POINT_SUPPORTED
  190185. #if defined(PNG_READ_GAMMA_SUPPORTED)
  190186. static PNG_CONST int png_gamma_shift[] =
  190187. {0x10, 0x21, 0x42, 0x84, 0x110, 0x248, 0x550, 0xff0, 0x00};
  190188. /* We build the 8- or 16-bit gamma tables here. Note that for 16-bit
  190189. * tables, we don't make a full table if we are reducing to 8-bit in
  190190. * the future. Note also how the gamma_16 tables are segmented so that
  190191. * we don't need to allocate > 64K chunks for a full 16-bit table.
  190192. */
  190193. void /* PRIVATE */
  190194. png_build_gamma_table(png_structp png_ptr)
  190195. {
  190196. png_debug(1, "in png_build_gamma_table\n");
  190197. if (png_ptr->bit_depth <= 8)
  190198. {
  190199. int i;
  190200. double g;
  190201. if (png_ptr->screen_gamma > .000001)
  190202. g = 1.0 / (png_ptr->gamma * png_ptr->screen_gamma);
  190203. else
  190204. g = 1.0;
  190205. png_ptr->gamma_table = (png_bytep)png_malloc(png_ptr,
  190206. (png_uint_32)256);
  190207. for (i = 0; i < 256; i++)
  190208. {
  190209. png_ptr->gamma_table[i] = (png_byte)(pow((double)i / 255.0,
  190210. g) * 255.0 + .5);
  190211. }
  190212. #if defined(PNG_READ_BACKGROUND_SUPPORTED) || \
  190213. defined(PNG_READ_RGB_TO_GRAY_SUPPORTED)
  190214. if (png_ptr->transformations & ((PNG_BACKGROUND) | PNG_RGB_TO_GRAY))
  190215. {
  190216. g = 1.0 / (png_ptr->gamma);
  190217. png_ptr->gamma_to_1 = (png_bytep)png_malloc(png_ptr,
  190218. (png_uint_32)256);
  190219. for (i = 0; i < 256; i++)
  190220. {
  190221. png_ptr->gamma_to_1[i] = (png_byte)(pow((double)i / 255.0,
  190222. g) * 255.0 + .5);
  190223. }
  190224. png_ptr->gamma_from_1 = (png_bytep)png_malloc(png_ptr,
  190225. (png_uint_32)256);
  190226. if(png_ptr->screen_gamma > 0.000001)
  190227. g = 1.0 / png_ptr->screen_gamma;
  190228. else
  190229. g = png_ptr->gamma; /* probably doing rgb_to_gray */
  190230. for (i = 0; i < 256; i++)
  190231. {
  190232. png_ptr->gamma_from_1[i] = (png_byte)(pow((double)i / 255.0,
  190233. g) * 255.0 + .5);
  190234. }
  190235. }
  190236. #endif /* PNG_READ_BACKGROUND_SUPPORTED || PNG_RGB_TO_GRAY_SUPPORTED */
  190237. }
  190238. else
  190239. {
  190240. double g;
  190241. int i, j, shift, num;
  190242. int sig_bit;
  190243. png_uint_32 ig;
  190244. if (png_ptr->color_type & PNG_COLOR_MASK_COLOR)
  190245. {
  190246. sig_bit = (int)png_ptr->sig_bit.red;
  190247. if ((int)png_ptr->sig_bit.green > sig_bit)
  190248. sig_bit = png_ptr->sig_bit.green;
  190249. if ((int)png_ptr->sig_bit.blue > sig_bit)
  190250. sig_bit = png_ptr->sig_bit.blue;
  190251. }
  190252. else
  190253. {
  190254. sig_bit = (int)png_ptr->sig_bit.gray;
  190255. }
  190256. if (sig_bit > 0)
  190257. shift = 16 - sig_bit;
  190258. else
  190259. shift = 0;
  190260. if (png_ptr->transformations & PNG_16_TO_8)
  190261. {
  190262. if (shift < (16 - PNG_MAX_GAMMA_8))
  190263. shift = (16 - PNG_MAX_GAMMA_8);
  190264. }
  190265. if (shift > 8)
  190266. shift = 8;
  190267. if (shift < 0)
  190268. shift = 0;
  190269. png_ptr->gamma_shift = (png_byte)shift;
  190270. num = (1 << (8 - shift));
  190271. if (png_ptr->screen_gamma > .000001)
  190272. g = 1.0 / (png_ptr->gamma * png_ptr->screen_gamma);
  190273. else
  190274. g = 1.0;
  190275. png_ptr->gamma_16_table = (png_uint_16pp)png_malloc(png_ptr,
  190276. (png_uint_32)(num * png_sizeof (png_uint_16p)));
  190277. if (png_ptr->transformations & (PNG_16_TO_8 | PNG_BACKGROUND))
  190278. {
  190279. double fin, fout;
  190280. png_uint_32 last, max;
  190281. for (i = 0; i < num; i++)
  190282. {
  190283. png_ptr->gamma_16_table[i] = (png_uint_16p)png_malloc(png_ptr,
  190284. (png_uint_32)(256 * png_sizeof (png_uint_16)));
  190285. }
  190286. g = 1.0 / g;
  190287. last = 0;
  190288. for (i = 0; i < 256; i++)
  190289. {
  190290. fout = ((double)i + 0.5) / 256.0;
  190291. fin = pow(fout, g);
  190292. max = (png_uint_32)(fin * (double)((png_uint_32)num << 8));
  190293. while (last <= max)
  190294. {
  190295. png_ptr->gamma_16_table[(int)(last & (0xff >> shift))]
  190296. [(int)(last >> (8 - shift))] = (png_uint_16)(
  190297. (png_uint_16)i | ((png_uint_16)i << 8));
  190298. last++;
  190299. }
  190300. }
  190301. while (last < ((png_uint_32)num << 8))
  190302. {
  190303. png_ptr->gamma_16_table[(int)(last & (0xff >> shift))]
  190304. [(int)(last >> (8 - shift))] = (png_uint_16)65535L;
  190305. last++;
  190306. }
  190307. }
  190308. else
  190309. {
  190310. for (i = 0; i < num; i++)
  190311. {
  190312. png_ptr->gamma_16_table[i] = (png_uint_16p)png_malloc(png_ptr,
  190313. (png_uint_32)(256 * png_sizeof (png_uint_16)));
  190314. ig = (((png_uint_32)i * (png_uint_32)png_gamma_shift[shift]) >> 4);
  190315. for (j = 0; j < 256; j++)
  190316. {
  190317. png_ptr->gamma_16_table[i][j] =
  190318. (png_uint_16)(pow((double)(ig + ((png_uint_32)j << 8)) /
  190319. 65535.0, g) * 65535.0 + .5);
  190320. }
  190321. }
  190322. }
  190323. #if defined(PNG_READ_BACKGROUND_SUPPORTED) || \
  190324. defined(PNG_READ_RGB_TO_GRAY_SUPPORTED)
  190325. if (png_ptr->transformations & (PNG_BACKGROUND | PNG_RGB_TO_GRAY))
  190326. {
  190327. g = 1.0 / (png_ptr->gamma);
  190328. png_ptr->gamma_16_to_1 = (png_uint_16pp)png_malloc(png_ptr,
  190329. (png_uint_32)(num * png_sizeof (png_uint_16p )));
  190330. for (i = 0; i < num; i++)
  190331. {
  190332. png_ptr->gamma_16_to_1[i] = (png_uint_16p)png_malloc(png_ptr,
  190333. (png_uint_32)(256 * png_sizeof (png_uint_16)));
  190334. ig = (((png_uint_32)i *
  190335. (png_uint_32)png_gamma_shift[shift]) >> 4);
  190336. for (j = 0; j < 256; j++)
  190337. {
  190338. png_ptr->gamma_16_to_1[i][j] =
  190339. (png_uint_16)(pow((double)(ig + ((png_uint_32)j << 8)) /
  190340. 65535.0, g) * 65535.0 + .5);
  190341. }
  190342. }
  190343. if(png_ptr->screen_gamma > 0.000001)
  190344. g = 1.0 / png_ptr->screen_gamma;
  190345. else
  190346. g = png_ptr->gamma; /* probably doing rgb_to_gray */
  190347. png_ptr->gamma_16_from_1 = (png_uint_16pp)png_malloc(png_ptr,
  190348. (png_uint_32)(num * png_sizeof (png_uint_16p)));
  190349. for (i = 0; i < num; i++)
  190350. {
  190351. png_ptr->gamma_16_from_1[i] = (png_uint_16p)png_malloc(png_ptr,
  190352. (png_uint_32)(256 * png_sizeof (png_uint_16)));
  190353. ig = (((png_uint_32)i *
  190354. (png_uint_32)png_gamma_shift[shift]) >> 4);
  190355. for (j = 0; j < 256; j++)
  190356. {
  190357. png_ptr->gamma_16_from_1[i][j] =
  190358. (png_uint_16)(pow((double)(ig + ((png_uint_32)j << 8)) /
  190359. 65535.0, g) * 65535.0 + .5);
  190360. }
  190361. }
  190362. }
  190363. #endif /* PNG_READ_BACKGROUND_SUPPORTED || PNG_RGB_TO_GRAY_SUPPORTED */
  190364. }
  190365. }
  190366. #endif
  190367. /* To do: install integer version of png_build_gamma_table here */
  190368. #endif
  190369. #if defined(PNG_MNG_FEATURES_SUPPORTED)
  190370. /* undoes intrapixel differencing */
  190371. void /* PRIVATE */
  190372. png_do_read_intrapixel(png_row_infop row_info, png_bytep row)
  190373. {
  190374. png_debug(1, "in png_do_read_intrapixel\n");
  190375. if (
  190376. #if defined(PNG_USELESS_TESTS_SUPPORTED)
  190377. row != NULL && row_info != NULL &&
  190378. #endif
  190379. (row_info->color_type & PNG_COLOR_MASK_COLOR))
  190380. {
  190381. int bytes_per_pixel;
  190382. png_uint_32 row_width = row_info->width;
  190383. if (row_info->bit_depth == 8)
  190384. {
  190385. png_bytep rp;
  190386. png_uint_32 i;
  190387. if (row_info->color_type == PNG_COLOR_TYPE_RGB)
  190388. bytes_per_pixel = 3;
  190389. else if (row_info->color_type == PNG_COLOR_TYPE_RGB_ALPHA)
  190390. bytes_per_pixel = 4;
  190391. else
  190392. return;
  190393. for (i = 0, rp = row; i < row_width; i++, rp += bytes_per_pixel)
  190394. {
  190395. *(rp) = (png_byte)((256 + *rp + *(rp+1))&0xff);
  190396. *(rp+2) = (png_byte)((256 + *(rp+2) + *(rp+1))&0xff);
  190397. }
  190398. }
  190399. else if (row_info->bit_depth == 16)
  190400. {
  190401. png_bytep rp;
  190402. png_uint_32 i;
  190403. if (row_info->color_type == PNG_COLOR_TYPE_RGB)
  190404. bytes_per_pixel = 6;
  190405. else if (row_info->color_type == PNG_COLOR_TYPE_RGB_ALPHA)
  190406. bytes_per_pixel = 8;
  190407. else
  190408. return;
  190409. for (i = 0, rp = row; i < row_width; i++, rp += bytes_per_pixel)
  190410. {
  190411. png_uint_32 s0 = (*(rp ) << 8) | *(rp+1);
  190412. png_uint_32 s1 = (*(rp+2) << 8) | *(rp+3);
  190413. png_uint_32 s2 = (*(rp+4) << 8) | *(rp+5);
  190414. png_uint_32 red = (png_uint_32)((s0+s1+65536L) & 0xffffL);
  190415. png_uint_32 blue = (png_uint_32)((s2+s1+65536L) & 0xffffL);
  190416. *(rp ) = (png_byte)((red >> 8) & 0xff);
  190417. *(rp+1) = (png_byte)(red & 0xff);
  190418. *(rp+4) = (png_byte)((blue >> 8) & 0xff);
  190419. *(rp+5) = (png_byte)(blue & 0xff);
  190420. }
  190421. }
  190422. }
  190423. }
  190424. #endif /* PNG_MNG_FEATURES_SUPPORTED */
  190425. #endif /* PNG_READ_SUPPORTED */
  190426. /*** End of inlined file: pngrtran.c ***/
  190427. /*** Start of inlined file: pngrutil.c ***/
  190428. /* pngrutil.c - utilities to read a PNG file
  190429. *
  190430. * Last changed in libpng 1.2.21 [October 4, 2007]
  190431. * For conditions of distribution and use, see copyright notice in png.h
  190432. * Copyright (c) 1998-2007 Glenn Randers-Pehrson
  190433. * (Version 0.96 Copyright (c) 1996, 1997 Andreas Dilger)
  190434. * (Version 0.88 Copyright (c) 1995, 1996 Guy Eric Schalnat, Group 42, Inc.)
  190435. *
  190436. * This file contains routines that are only called from within
  190437. * libpng itself during the course of reading an image.
  190438. */
  190439. #define PNG_INTERNAL
  190440. #if defined(PNG_READ_SUPPORTED)
  190441. #if defined(_WIN32_WCE) && (_WIN32_WCE<0x500)
  190442. # define WIN32_WCE_OLD
  190443. #endif
  190444. #ifdef PNG_FLOATING_POINT_SUPPORTED
  190445. # if defined(WIN32_WCE_OLD)
  190446. /* strtod() function is not supported on WindowsCE */
  190447. __inline double png_strtod(png_structp png_ptr, PNG_CONST char *nptr, char **endptr)
  190448. {
  190449. double result = 0;
  190450. int len;
  190451. wchar_t *str, *end;
  190452. len = MultiByteToWideChar(CP_ACP, 0, nptr, -1, NULL, 0);
  190453. str = (wchar_t *)png_malloc(png_ptr, len * sizeof(wchar_t));
  190454. if ( NULL != str )
  190455. {
  190456. MultiByteToWideChar(CP_ACP, 0, nptr, -1, str, len);
  190457. result = wcstod(str, &end);
  190458. len = WideCharToMultiByte(CP_ACP, 0, end, -1, NULL, 0, NULL, NULL);
  190459. *endptr = (char *)nptr + (png_strlen(nptr) - len + 1);
  190460. png_free(png_ptr, str);
  190461. }
  190462. return result;
  190463. }
  190464. # else
  190465. # define png_strtod(p,a,b) strtod(a,b)
  190466. # endif
  190467. #endif
  190468. png_uint_32 PNGAPI
  190469. png_get_uint_31(png_structp png_ptr, png_bytep buf)
  190470. {
  190471. png_uint_32 i = png_get_uint_32(buf);
  190472. if (i > PNG_UINT_31_MAX)
  190473. png_error(png_ptr, "PNG unsigned integer out of range.");
  190474. return (i);
  190475. }
  190476. #ifndef PNG_READ_BIG_ENDIAN_SUPPORTED
  190477. /* Grab an unsigned 32-bit integer from a buffer in big-endian format. */
  190478. png_uint_32 PNGAPI
  190479. png_get_uint_32(png_bytep buf)
  190480. {
  190481. png_uint_32 i = ((png_uint_32)(*buf) << 24) +
  190482. ((png_uint_32)(*(buf + 1)) << 16) +
  190483. ((png_uint_32)(*(buf + 2)) << 8) +
  190484. (png_uint_32)(*(buf + 3));
  190485. return (i);
  190486. }
  190487. /* Grab a signed 32-bit integer from a buffer in big-endian format. The
  190488. * data is stored in the PNG file in two's complement format, and it is
  190489. * assumed that the machine format for signed integers is the same. */
  190490. png_int_32 PNGAPI
  190491. png_get_int_32(png_bytep buf)
  190492. {
  190493. png_int_32 i = ((png_int_32)(*buf) << 24) +
  190494. ((png_int_32)(*(buf + 1)) << 16) +
  190495. ((png_int_32)(*(buf + 2)) << 8) +
  190496. (png_int_32)(*(buf + 3));
  190497. return (i);
  190498. }
  190499. /* Grab an unsigned 16-bit integer from a buffer in big-endian format. */
  190500. png_uint_16 PNGAPI
  190501. png_get_uint_16(png_bytep buf)
  190502. {
  190503. png_uint_16 i = (png_uint_16)(((png_uint_16)(*buf) << 8) +
  190504. (png_uint_16)(*(buf + 1)));
  190505. return (i);
  190506. }
  190507. #endif /* PNG_READ_BIG_ENDIAN_SUPPORTED */
  190508. /* Read data, and (optionally) run it through the CRC. */
  190509. void /* PRIVATE */
  190510. png_crc_read(png_structp png_ptr, png_bytep buf, png_size_t length)
  190511. {
  190512. if(png_ptr == NULL) return;
  190513. png_read_data(png_ptr, buf, length);
  190514. png_calculate_crc(png_ptr, buf, length);
  190515. }
  190516. /* Optionally skip data and then check the CRC. Depending on whether we
  190517. are reading a ancillary or critical chunk, and how the program has set
  190518. things up, we may calculate the CRC on the data and print a message.
  190519. Returns '1' if there was a CRC error, '0' otherwise. */
  190520. int /* PRIVATE */
  190521. png_crc_finish(png_structp png_ptr, png_uint_32 skip)
  190522. {
  190523. png_size_t i;
  190524. png_size_t istop = png_ptr->zbuf_size;
  190525. for (i = (png_size_t)skip; i > istop; i -= istop)
  190526. {
  190527. png_crc_read(png_ptr, png_ptr->zbuf, png_ptr->zbuf_size);
  190528. }
  190529. if (i)
  190530. {
  190531. png_crc_read(png_ptr, png_ptr->zbuf, i);
  190532. }
  190533. if (png_crc_error(png_ptr))
  190534. {
  190535. if (((png_ptr->chunk_name[0] & 0x20) && /* Ancillary */
  190536. !(png_ptr->flags & PNG_FLAG_CRC_ANCILLARY_NOWARN)) ||
  190537. (!(png_ptr->chunk_name[0] & 0x20) && /* Critical */
  190538. (png_ptr->flags & PNG_FLAG_CRC_CRITICAL_USE)))
  190539. {
  190540. png_chunk_warning(png_ptr, "CRC error");
  190541. }
  190542. else
  190543. {
  190544. png_chunk_error(png_ptr, "CRC error");
  190545. }
  190546. return (1);
  190547. }
  190548. return (0);
  190549. }
  190550. /* Compare the CRC stored in the PNG file with that calculated by libpng from
  190551. the data it has read thus far. */
  190552. int /* PRIVATE */
  190553. png_crc_error(png_structp png_ptr)
  190554. {
  190555. png_byte crc_bytes[4];
  190556. png_uint_32 crc;
  190557. int need_crc = 1;
  190558. if (png_ptr->chunk_name[0] & 0x20) /* ancillary */
  190559. {
  190560. if ((png_ptr->flags & PNG_FLAG_CRC_ANCILLARY_MASK) ==
  190561. (PNG_FLAG_CRC_ANCILLARY_USE | PNG_FLAG_CRC_ANCILLARY_NOWARN))
  190562. need_crc = 0;
  190563. }
  190564. else /* critical */
  190565. {
  190566. if (png_ptr->flags & PNG_FLAG_CRC_CRITICAL_IGNORE)
  190567. need_crc = 0;
  190568. }
  190569. png_read_data(png_ptr, crc_bytes, 4);
  190570. if (need_crc)
  190571. {
  190572. crc = png_get_uint_32(crc_bytes);
  190573. return ((int)(crc != png_ptr->crc));
  190574. }
  190575. else
  190576. return (0);
  190577. }
  190578. #if defined(PNG_READ_zTXt_SUPPORTED) || defined(PNG_READ_iTXt_SUPPORTED) || \
  190579. defined(PNG_READ_iCCP_SUPPORTED)
  190580. /*
  190581. * Decompress trailing data in a chunk. The assumption is that chunkdata
  190582. * points at an allocated area holding the contents of a chunk with a
  190583. * trailing compressed part. What we get back is an allocated area
  190584. * holding the original prefix part and an uncompressed version of the
  190585. * trailing part (the malloc area passed in is freed).
  190586. */
  190587. png_charp /* PRIVATE */
  190588. png_decompress_chunk(png_structp png_ptr, int comp_type,
  190589. png_charp chunkdata, png_size_t chunklength,
  190590. png_size_t prefix_size, png_size_t *newlength)
  190591. {
  190592. static PNG_CONST char msg[] = "Error decoding compressed text";
  190593. png_charp text;
  190594. png_size_t text_size;
  190595. if (comp_type == PNG_COMPRESSION_TYPE_BASE)
  190596. {
  190597. int ret = Z_OK;
  190598. png_ptr->zstream.next_in = (png_bytep)(chunkdata + prefix_size);
  190599. png_ptr->zstream.avail_in = (uInt)(chunklength - prefix_size);
  190600. png_ptr->zstream.next_out = png_ptr->zbuf;
  190601. png_ptr->zstream.avail_out = (uInt)png_ptr->zbuf_size;
  190602. text_size = 0;
  190603. text = NULL;
  190604. while (png_ptr->zstream.avail_in)
  190605. {
  190606. ret = inflate(&png_ptr->zstream, Z_PARTIAL_FLUSH);
  190607. if (ret != Z_OK && ret != Z_STREAM_END)
  190608. {
  190609. if (png_ptr->zstream.msg != NULL)
  190610. png_warning(png_ptr, png_ptr->zstream.msg);
  190611. else
  190612. png_warning(png_ptr, msg);
  190613. inflateReset(&png_ptr->zstream);
  190614. png_ptr->zstream.avail_in = 0;
  190615. if (text == NULL)
  190616. {
  190617. text_size = prefix_size + png_sizeof(msg) + 1;
  190618. text = (png_charp)png_malloc_warn(png_ptr, text_size);
  190619. if (text == NULL)
  190620. {
  190621. png_free(png_ptr,chunkdata);
  190622. png_error(png_ptr,"Not enough memory to decompress chunk");
  190623. }
  190624. png_memcpy(text, chunkdata, prefix_size);
  190625. }
  190626. text[text_size - 1] = 0x00;
  190627. /* Copy what we can of the error message into the text chunk */
  190628. text_size = (png_size_t)(chunklength - (text - chunkdata) - 1);
  190629. text_size = png_sizeof(msg) > text_size ? text_size :
  190630. png_sizeof(msg);
  190631. png_memcpy(text + prefix_size, msg, text_size + 1);
  190632. break;
  190633. }
  190634. if (!png_ptr->zstream.avail_out || ret == Z_STREAM_END)
  190635. {
  190636. if (text == NULL)
  190637. {
  190638. text_size = prefix_size +
  190639. png_ptr->zbuf_size - png_ptr->zstream.avail_out;
  190640. text = (png_charp)png_malloc_warn(png_ptr, text_size + 1);
  190641. if (text == NULL)
  190642. {
  190643. png_free(png_ptr,chunkdata);
  190644. png_error(png_ptr,"Not enough memory to decompress chunk.");
  190645. }
  190646. png_memcpy(text + prefix_size, png_ptr->zbuf,
  190647. text_size - prefix_size);
  190648. png_memcpy(text, chunkdata, prefix_size);
  190649. *(text + text_size) = 0x00;
  190650. }
  190651. else
  190652. {
  190653. png_charp tmp;
  190654. tmp = text;
  190655. text = (png_charp)png_malloc_warn(png_ptr,
  190656. (png_uint_32)(text_size +
  190657. png_ptr->zbuf_size - png_ptr->zstream.avail_out + 1));
  190658. if (text == NULL)
  190659. {
  190660. png_free(png_ptr, tmp);
  190661. png_free(png_ptr, chunkdata);
  190662. png_error(png_ptr,"Not enough memory to decompress chunk..");
  190663. }
  190664. png_memcpy(text, tmp, text_size);
  190665. png_free(png_ptr, tmp);
  190666. png_memcpy(text + text_size, png_ptr->zbuf,
  190667. (png_ptr->zbuf_size - png_ptr->zstream.avail_out));
  190668. text_size += png_ptr->zbuf_size - png_ptr->zstream.avail_out;
  190669. *(text + text_size) = 0x00;
  190670. }
  190671. if (ret == Z_STREAM_END)
  190672. break;
  190673. else
  190674. {
  190675. png_ptr->zstream.next_out = png_ptr->zbuf;
  190676. png_ptr->zstream.avail_out = (uInt)png_ptr->zbuf_size;
  190677. }
  190678. }
  190679. }
  190680. if (ret != Z_STREAM_END)
  190681. {
  190682. #if !defined(PNG_NO_STDIO) && !defined(_WIN32_WCE)
  190683. char umsg[52];
  190684. if (ret == Z_BUF_ERROR)
  190685. png_snprintf(umsg, 52,
  190686. "Buffer error in compressed datastream in %s chunk",
  190687. png_ptr->chunk_name);
  190688. else if (ret == Z_DATA_ERROR)
  190689. png_snprintf(umsg, 52,
  190690. "Data error in compressed datastream in %s chunk",
  190691. png_ptr->chunk_name);
  190692. else
  190693. png_snprintf(umsg, 52,
  190694. "Incomplete compressed datastream in %s chunk",
  190695. png_ptr->chunk_name);
  190696. png_warning(png_ptr, umsg);
  190697. #else
  190698. png_warning(png_ptr,
  190699. "Incomplete compressed datastream in chunk other than IDAT");
  190700. #endif
  190701. text_size=prefix_size;
  190702. if (text == NULL)
  190703. {
  190704. text = (png_charp)png_malloc_warn(png_ptr, text_size+1);
  190705. if (text == NULL)
  190706. {
  190707. png_free(png_ptr, chunkdata);
  190708. png_error(png_ptr,"Not enough memory for text.");
  190709. }
  190710. png_memcpy(text, chunkdata, prefix_size);
  190711. }
  190712. *(text + text_size) = 0x00;
  190713. }
  190714. inflateReset(&png_ptr->zstream);
  190715. png_ptr->zstream.avail_in = 0;
  190716. png_free(png_ptr, chunkdata);
  190717. chunkdata = text;
  190718. *newlength=text_size;
  190719. }
  190720. else /* if (comp_type != PNG_COMPRESSION_TYPE_BASE) */
  190721. {
  190722. #if !defined(PNG_NO_STDIO) && !defined(_WIN32_WCE)
  190723. char umsg[50];
  190724. png_snprintf(umsg, 50,
  190725. "Unknown zTXt compression type %d", comp_type);
  190726. png_warning(png_ptr, umsg);
  190727. #else
  190728. png_warning(png_ptr, "Unknown zTXt compression type");
  190729. #endif
  190730. *(chunkdata + prefix_size) = 0x00;
  190731. *newlength=prefix_size;
  190732. }
  190733. return chunkdata;
  190734. }
  190735. #endif
  190736. /* read and check the IDHR chunk */
  190737. void /* PRIVATE */
  190738. png_handle_IHDR(png_structp png_ptr, png_infop info_ptr, png_uint_32 length)
  190739. {
  190740. png_byte buf[13];
  190741. png_uint_32 width, height;
  190742. int bit_depth, color_type, compression_type, filter_type;
  190743. int interlace_type;
  190744. png_debug(1, "in png_handle_IHDR\n");
  190745. if (png_ptr->mode & PNG_HAVE_IHDR)
  190746. png_error(png_ptr, "Out of place IHDR");
  190747. /* check the length */
  190748. if (length != 13)
  190749. png_error(png_ptr, "Invalid IHDR chunk");
  190750. png_ptr->mode |= PNG_HAVE_IHDR;
  190751. png_crc_read(png_ptr, buf, 13);
  190752. png_crc_finish(png_ptr, 0);
  190753. width = png_get_uint_31(png_ptr, buf);
  190754. height = png_get_uint_31(png_ptr, buf + 4);
  190755. bit_depth = buf[8];
  190756. color_type = buf[9];
  190757. compression_type = buf[10];
  190758. filter_type = buf[11];
  190759. interlace_type = buf[12];
  190760. /* set internal variables */
  190761. png_ptr->width = width;
  190762. png_ptr->height = height;
  190763. png_ptr->bit_depth = (png_byte)bit_depth;
  190764. png_ptr->interlaced = (png_byte)interlace_type;
  190765. png_ptr->color_type = (png_byte)color_type;
  190766. #if defined(PNG_MNG_FEATURES_SUPPORTED)
  190767. png_ptr->filter_type = (png_byte)filter_type;
  190768. #endif
  190769. png_ptr->compression_type = (png_byte)compression_type;
  190770. /* find number of channels */
  190771. switch (png_ptr->color_type)
  190772. {
  190773. case PNG_COLOR_TYPE_GRAY:
  190774. case PNG_COLOR_TYPE_PALETTE:
  190775. png_ptr->channels = 1;
  190776. break;
  190777. case PNG_COLOR_TYPE_RGB:
  190778. png_ptr->channels = 3;
  190779. break;
  190780. case PNG_COLOR_TYPE_GRAY_ALPHA:
  190781. png_ptr->channels = 2;
  190782. break;
  190783. case PNG_COLOR_TYPE_RGB_ALPHA:
  190784. png_ptr->channels = 4;
  190785. break;
  190786. }
  190787. /* set up other useful info */
  190788. png_ptr->pixel_depth = (png_byte)(png_ptr->bit_depth *
  190789. png_ptr->channels);
  190790. png_ptr->rowbytes = PNG_ROWBYTES(png_ptr->pixel_depth,png_ptr->width);
  190791. png_debug1(3,"bit_depth = %d\n", png_ptr->bit_depth);
  190792. png_debug1(3,"channels = %d\n", png_ptr->channels);
  190793. png_debug1(3,"rowbytes = %lu\n", png_ptr->rowbytes);
  190794. png_set_IHDR(png_ptr, info_ptr, width, height, bit_depth,
  190795. color_type, interlace_type, compression_type, filter_type);
  190796. }
  190797. /* read and check the palette */
  190798. void /* PRIVATE */
  190799. png_handle_PLTE(png_structp png_ptr, png_infop info_ptr, png_uint_32 length)
  190800. {
  190801. png_color palette[PNG_MAX_PALETTE_LENGTH];
  190802. int num, i;
  190803. #ifndef PNG_NO_POINTER_INDEXING
  190804. png_colorp pal_ptr;
  190805. #endif
  190806. png_debug(1, "in png_handle_PLTE\n");
  190807. if (!(png_ptr->mode & PNG_HAVE_IHDR))
  190808. png_error(png_ptr, "Missing IHDR before PLTE");
  190809. else if (png_ptr->mode & PNG_HAVE_IDAT)
  190810. {
  190811. png_warning(png_ptr, "Invalid PLTE after IDAT");
  190812. png_crc_finish(png_ptr, length);
  190813. return;
  190814. }
  190815. else if (png_ptr->mode & PNG_HAVE_PLTE)
  190816. png_error(png_ptr, "Duplicate PLTE chunk");
  190817. png_ptr->mode |= PNG_HAVE_PLTE;
  190818. if (!(png_ptr->color_type&PNG_COLOR_MASK_COLOR))
  190819. {
  190820. png_warning(png_ptr,
  190821. "Ignoring PLTE chunk in grayscale PNG");
  190822. png_crc_finish(png_ptr, length);
  190823. return;
  190824. }
  190825. #if !defined(PNG_READ_OPT_PLTE_SUPPORTED)
  190826. if (png_ptr->color_type != PNG_COLOR_TYPE_PALETTE)
  190827. {
  190828. png_crc_finish(png_ptr, length);
  190829. return;
  190830. }
  190831. #endif
  190832. if (length > 3*PNG_MAX_PALETTE_LENGTH || length % 3)
  190833. {
  190834. if (png_ptr->color_type != PNG_COLOR_TYPE_PALETTE)
  190835. {
  190836. png_warning(png_ptr, "Invalid palette chunk");
  190837. png_crc_finish(png_ptr, length);
  190838. return;
  190839. }
  190840. else
  190841. {
  190842. png_error(png_ptr, "Invalid palette chunk");
  190843. }
  190844. }
  190845. num = (int)length / 3;
  190846. #ifndef PNG_NO_POINTER_INDEXING
  190847. for (i = 0, pal_ptr = palette; i < num; i++, pal_ptr++)
  190848. {
  190849. png_byte buf[3];
  190850. png_crc_read(png_ptr, buf, 3);
  190851. pal_ptr->red = buf[0];
  190852. pal_ptr->green = buf[1];
  190853. pal_ptr->blue = buf[2];
  190854. }
  190855. #else
  190856. for (i = 0; i < num; i++)
  190857. {
  190858. png_byte buf[3];
  190859. png_crc_read(png_ptr, buf, 3);
  190860. /* don't depend upon png_color being any order */
  190861. palette[i].red = buf[0];
  190862. palette[i].green = buf[1];
  190863. palette[i].blue = buf[2];
  190864. }
  190865. #endif
  190866. /* If we actually NEED the PLTE chunk (ie for a paletted image), we do
  190867. whatever the normal CRC configuration tells us. However, if we
  190868. have an RGB image, the PLTE can be considered ancillary, so
  190869. we will act as though it is. */
  190870. #if !defined(PNG_READ_OPT_PLTE_SUPPORTED)
  190871. if (png_ptr->color_type == PNG_COLOR_TYPE_PALETTE)
  190872. #endif
  190873. {
  190874. png_crc_finish(png_ptr, 0);
  190875. }
  190876. #if !defined(PNG_READ_OPT_PLTE_SUPPORTED)
  190877. else if (png_crc_error(png_ptr)) /* Only if we have a CRC error */
  190878. {
  190879. /* If we don't want to use the data from an ancillary chunk,
  190880. we have two options: an error abort, or a warning and we
  190881. ignore the data in this chunk (which should be OK, since
  190882. it's considered ancillary for a RGB or RGBA image). */
  190883. if (!(png_ptr->flags & PNG_FLAG_CRC_ANCILLARY_USE))
  190884. {
  190885. if (png_ptr->flags & PNG_FLAG_CRC_ANCILLARY_NOWARN)
  190886. {
  190887. png_chunk_error(png_ptr, "CRC error");
  190888. }
  190889. else
  190890. {
  190891. png_chunk_warning(png_ptr, "CRC error");
  190892. return;
  190893. }
  190894. }
  190895. /* Otherwise, we (optionally) emit a warning and use the chunk. */
  190896. else if (!(png_ptr->flags & PNG_FLAG_CRC_ANCILLARY_NOWARN))
  190897. {
  190898. png_chunk_warning(png_ptr, "CRC error");
  190899. }
  190900. }
  190901. #endif
  190902. png_set_PLTE(png_ptr, info_ptr, palette, num);
  190903. #if defined(PNG_READ_tRNS_SUPPORTED)
  190904. if (png_ptr->color_type == PNG_COLOR_TYPE_PALETTE)
  190905. {
  190906. if (info_ptr != NULL && (info_ptr->valid & PNG_INFO_tRNS))
  190907. {
  190908. if (png_ptr->num_trans > (png_uint_16)num)
  190909. {
  190910. png_warning(png_ptr, "Truncating incorrect tRNS chunk length");
  190911. png_ptr->num_trans = (png_uint_16)num;
  190912. }
  190913. if (info_ptr->num_trans > (png_uint_16)num)
  190914. {
  190915. png_warning(png_ptr, "Truncating incorrect info tRNS chunk length");
  190916. info_ptr->num_trans = (png_uint_16)num;
  190917. }
  190918. }
  190919. }
  190920. #endif
  190921. }
  190922. void /* PRIVATE */
  190923. png_handle_IEND(png_structp png_ptr, png_infop info_ptr, png_uint_32 length)
  190924. {
  190925. png_debug(1, "in png_handle_IEND\n");
  190926. if (!(png_ptr->mode & PNG_HAVE_IHDR) || !(png_ptr->mode & PNG_HAVE_IDAT))
  190927. {
  190928. png_error(png_ptr, "No image in file");
  190929. }
  190930. png_ptr->mode |= (PNG_AFTER_IDAT | PNG_HAVE_IEND);
  190931. if (length != 0)
  190932. {
  190933. png_warning(png_ptr, "Incorrect IEND chunk length");
  190934. }
  190935. png_crc_finish(png_ptr, length);
  190936. info_ptr =info_ptr; /* quiet compiler warnings about unused info_ptr */
  190937. }
  190938. #if defined(PNG_READ_gAMA_SUPPORTED)
  190939. void /* PRIVATE */
  190940. png_handle_gAMA(png_structp png_ptr, png_infop info_ptr, png_uint_32 length)
  190941. {
  190942. png_fixed_point igamma;
  190943. #ifdef PNG_FLOATING_POINT_SUPPORTED
  190944. float file_gamma;
  190945. #endif
  190946. png_byte buf[4];
  190947. png_debug(1, "in png_handle_gAMA\n");
  190948. if (!(png_ptr->mode & PNG_HAVE_IHDR))
  190949. png_error(png_ptr, "Missing IHDR before gAMA");
  190950. else if (png_ptr->mode & PNG_HAVE_IDAT)
  190951. {
  190952. png_warning(png_ptr, "Invalid gAMA after IDAT");
  190953. png_crc_finish(png_ptr, length);
  190954. return;
  190955. }
  190956. else if (png_ptr->mode & PNG_HAVE_PLTE)
  190957. /* Should be an error, but we can cope with it */
  190958. png_warning(png_ptr, "Out of place gAMA chunk");
  190959. if (info_ptr != NULL && (info_ptr->valid & PNG_INFO_gAMA)
  190960. #if defined(PNG_READ_sRGB_SUPPORTED)
  190961. && !(info_ptr->valid & PNG_INFO_sRGB)
  190962. #endif
  190963. )
  190964. {
  190965. png_warning(png_ptr, "Duplicate gAMA chunk");
  190966. png_crc_finish(png_ptr, length);
  190967. return;
  190968. }
  190969. if (length != 4)
  190970. {
  190971. png_warning(png_ptr, "Incorrect gAMA chunk length");
  190972. png_crc_finish(png_ptr, length);
  190973. return;
  190974. }
  190975. png_crc_read(png_ptr, buf, 4);
  190976. if (png_crc_finish(png_ptr, 0))
  190977. return;
  190978. igamma = (png_fixed_point)png_get_uint_32(buf);
  190979. /* check for zero gamma */
  190980. if (igamma == 0)
  190981. {
  190982. png_warning(png_ptr,
  190983. "Ignoring gAMA chunk with gamma=0");
  190984. return;
  190985. }
  190986. #if defined(PNG_READ_sRGB_SUPPORTED)
  190987. if (info_ptr != NULL && (info_ptr->valid & PNG_INFO_sRGB))
  190988. if (PNG_OUT_OF_RANGE(igamma, 45500L, 500))
  190989. {
  190990. png_warning(png_ptr,
  190991. "Ignoring incorrect gAMA value when sRGB is also present");
  190992. #ifndef PNG_NO_CONSOLE_IO
  190993. fprintf(stderr, "gamma = (%d/100000)\n", (int)igamma);
  190994. #endif
  190995. return;
  190996. }
  190997. #endif /* PNG_READ_sRGB_SUPPORTED */
  190998. #ifdef PNG_FLOATING_POINT_SUPPORTED
  190999. file_gamma = (float)igamma / (float)100000.0;
  191000. # ifdef PNG_READ_GAMMA_SUPPORTED
  191001. png_ptr->gamma = file_gamma;
  191002. # endif
  191003. png_set_gAMA(png_ptr, info_ptr, file_gamma);
  191004. #endif
  191005. #ifdef PNG_FIXED_POINT_SUPPORTED
  191006. png_set_gAMA_fixed(png_ptr, info_ptr, igamma);
  191007. #endif
  191008. }
  191009. #endif
  191010. #if defined(PNG_READ_sBIT_SUPPORTED)
  191011. void /* PRIVATE */
  191012. png_handle_sBIT(png_structp png_ptr, png_infop info_ptr, png_uint_32 length)
  191013. {
  191014. png_size_t truelen;
  191015. png_byte buf[4];
  191016. png_debug(1, "in png_handle_sBIT\n");
  191017. buf[0] = buf[1] = buf[2] = buf[3] = 0;
  191018. if (!(png_ptr->mode & PNG_HAVE_IHDR))
  191019. png_error(png_ptr, "Missing IHDR before sBIT");
  191020. else if (png_ptr->mode & PNG_HAVE_IDAT)
  191021. {
  191022. png_warning(png_ptr, "Invalid sBIT after IDAT");
  191023. png_crc_finish(png_ptr, length);
  191024. return;
  191025. }
  191026. else if (png_ptr->mode & PNG_HAVE_PLTE)
  191027. {
  191028. /* Should be an error, but we can cope with it */
  191029. png_warning(png_ptr, "Out of place sBIT chunk");
  191030. }
  191031. if (info_ptr != NULL && (info_ptr->valid & PNG_INFO_sBIT))
  191032. {
  191033. png_warning(png_ptr, "Duplicate sBIT chunk");
  191034. png_crc_finish(png_ptr, length);
  191035. return;
  191036. }
  191037. if (png_ptr->color_type == PNG_COLOR_TYPE_PALETTE)
  191038. truelen = 3;
  191039. else
  191040. truelen = (png_size_t)png_ptr->channels;
  191041. if (length != truelen || length > 4)
  191042. {
  191043. png_warning(png_ptr, "Incorrect sBIT chunk length");
  191044. png_crc_finish(png_ptr, length);
  191045. return;
  191046. }
  191047. png_crc_read(png_ptr, buf, truelen);
  191048. if (png_crc_finish(png_ptr, 0))
  191049. return;
  191050. if (png_ptr->color_type & PNG_COLOR_MASK_COLOR)
  191051. {
  191052. png_ptr->sig_bit.red = buf[0];
  191053. png_ptr->sig_bit.green = buf[1];
  191054. png_ptr->sig_bit.blue = buf[2];
  191055. png_ptr->sig_bit.alpha = buf[3];
  191056. }
  191057. else
  191058. {
  191059. png_ptr->sig_bit.gray = buf[0];
  191060. png_ptr->sig_bit.red = buf[0];
  191061. png_ptr->sig_bit.green = buf[0];
  191062. png_ptr->sig_bit.blue = buf[0];
  191063. png_ptr->sig_bit.alpha = buf[1];
  191064. }
  191065. png_set_sBIT(png_ptr, info_ptr, &(png_ptr->sig_bit));
  191066. }
  191067. #endif
  191068. #if defined(PNG_READ_cHRM_SUPPORTED)
  191069. void /* PRIVATE */
  191070. png_handle_cHRM(png_structp png_ptr, png_infop info_ptr, png_uint_32 length)
  191071. {
  191072. png_byte buf[4];
  191073. #ifdef PNG_FLOATING_POINT_SUPPORTED
  191074. float white_x, white_y, red_x, red_y, green_x, green_y, blue_x, blue_y;
  191075. #endif
  191076. png_fixed_point int_x_white, int_y_white, int_x_red, int_y_red, int_x_green,
  191077. int_y_green, int_x_blue, int_y_blue;
  191078. png_uint_32 uint_x, uint_y;
  191079. png_debug(1, "in png_handle_cHRM\n");
  191080. if (!(png_ptr->mode & PNG_HAVE_IHDR))
  191081. png_error(png_ptr, "Missing IHDR before cHRM");
  191082. else if (png_ptr->mode & PNG_HAVE_IDAT)
  191083. {
  191084. png_warning(png_ptr, "Invalid cHRM after IDAT");
  191085. png_crc_finish(png_ptr, length);
  191086. return;
  191087. }
  191088. else if (png_ptr->mode & PNG_HAVE_PLTE)
  191089. /* Should be an error, but we can cope with it */
  191090. png_warning(png_ptr, "Missing PLTE before cHRM");
  191091. if (info_ptr != NULL && (info_ptr->valid & PNG_INFO_cHRM)
  191092. #if defined(PNG_READ_sRGB_SUPPORTED)
  191093. && !(info_ptr->valid & PNG_INFO_sRGB)
  191094. #endif
  191095. )
  191096. {
  191097. png_warning(png_ptr, "Duplicate cHRM chunk");
  191098. png_crc_finish(png_ptr, length);
  191099. return;
  191100. }
  191101. if (length != 32)
  191102. {
  191103. png_warning(png_ptr, "Incorrect cHRM chunk length");
  191104. png_crc_finish(png_ptr, length);
  191105. return;
  191106. }
  191107. png_crc_read(png_ptr, buf, 4);
  191108. uint_x = png_get_uint_32(buf);
  191109. png_crc_read(png_ptr, buf, 4);
  191110. uint_y = png_get_uint_32(buf);
  191111. if (uint_x > 80000L || uint_y > 80000L ||
  191112. uint_x + uint_y > 100000L)
  191113. {
  191114. png_warning(png_ptr, "Invalid cHRM white point");
  191115. png_crc_finish(png_ptr, 24);
  191116. return;
  191117. }
  191118. int_x_white = (png_fixed_point)uint_x;
  191119. int_y_white = (png_fixed_point)uint_y;
  191120. png_crc_read(png_ptr, buf, 4);
  191121. uint_x = png_get_uint_32(buf);
  191122. png_crc_read(png_ptr, buf, 4);
  191123. uint_y = png_get_uint_32(buf);
  191124. if (uint_x + uint_y > 100000L)
  191125. {
  191126. png_warning(png_ptr, "Invalid cHRM red point");
  191127. png_crc_finish(png_ptr, 16);
  191128. return;
  191129. }
  191130. int_x_red = (png_fixed_point)uint_x;
  191131. int_y_red = (png_fixed_point)uint_y;
  191132. png_crc_read(png_ptr, buf, 4);
  191133. uint_x = png_get_uint_32(buf);
  191134. png_crc_read(png_ptr, buf, 4);
  191135. uint_y = png_get_uint_32(buf);
  191136. if (uint_x + uint_y > 100000L)
  191137. {
  191138. png_warning(png_ptr, "Invalid cHRM green point");
  191139. png_crc_finish(png_ptr, 8);
  191140. return;
  191141. }
  191142. int_x_green = (png_fixed_point)uint_x;
  191143. int_y_green = (png_fixed_point)uint_y;
  191144. png_crc_read(png_ptr, buf, 4);
  191145. uint_x = png_get_uint_32(buf);
  191146. png_crc_read(png_ptr, buf, 4);
  191147. uint_y = png_get_uint_32(buf);
  191148. if (uint_x + uint_y > 100000L)
  191149. {
  191150. png_warning(png_ptr, "Invalid cHRM blue point");
  191151. png_crc_finish(png_ptr, 0);
  191152. return;
  191153. }
  191154. int_x_blue = (png_fixed_point)uint_x;
  191155. int_y_blue = (png_fixed_point)uint_y;
  191156. #ifdef PNG_FLOATING_POINT_SUPPORTED
  191157. white_x = (float)int_x_white / (float)100000.0;
  191158. white_y = (float)int_y_white / (float)100000.0;
  191159. red_x = (float)int_x_red / (float)100000.0;
  191160. red_y = (float)int_y_red / (float)100000.0;
  191161. green_x = (float)int_x_green / (float)100000.0;
  191162. green_y = (float)int_y_green / (float)100000.0;
  191163. blue_x = (float)int_x_blue / (float)100000.0;
  191164. blue_y = (float)int_y_blue / (float)100000.0;
  191165. #endif
  191166. #if defined(PNG_READ_sRGB_SUPPORTED)
  191167. if ((info_ptr != NULL) && (info_ptr->valid & PNG_INFO_sRGB))
  191168. {
  191169. if (PNG_OUT_OF_RANGE(int_x_white, 31270, 1000) ||
  191170. PNG_OUT_OF_RANGE(int_y_white, 32900, 1000) ||
  191171. PNG_OUT_OF_RANGE(int_x_red, 64000L, 1000) ||
  191172. PNG_OUT_OF_RANGE(int_y_red, 33000, 1000) ||
  191173. PNG_OUT_OF_RANGE(int_x_green, 30000, 1000) ||
  191174. PNG_OUT_OF_RANGE(int_y_green, 60000L, 1000) ||
  191175. PNG_OUT_OF_RANGE(int_x_blue, 15000, 1000) ||
  191176. PNG_OUT_OF_RANGE(int_y_blue, 6000, 1000))
  191177. {
  191178. png_warning(png_ptr,
  191179. "Ignoring incorrect cHRM value when sRGB is also present");
  191180. #ifndef PNG_NO_CONSOLE_IO
  191181. #ifdef PNG_FLOATING_POINT_SUPPORTED
  191182. fprintf(stderr,"wx=%f, wy=%f, rx=%f, ry=%f\n",
  191183. white_x, white_y, red_x, red_y);
  191184. fprintf(stderr,"gx=%f, gy=%f, bx=%f, by=%f\n",
  191185. green_x, green_y, blue_x, blue_y);
  191186. #else
  191187. fprintf(stderr,"wx=%ld, wy=%ld, rx=%ld, ry=%ld\n",
  191188. int_x_white, int_y_white, int_x_red, int_y_red);
  191189. fprintf(stderr,"gx=%ld, gy=%ld, bx=%ld, by=%ld\n",
  191190. int_x_green, int_y_green, int_x_blue, int_y_blue);
  191191. #endif
  191192. #endif /* PNG_NO_CONSOLE_IO */
  191193. }
  191194. png_crc_finish(png_ptr, 0);
  191195. return;
  191196. }
  191197. #endif /* PNG_READ_sRGB_SUPPORTED */
  191198. #ifdef PNG_FLOATING_POINT_SUPPORTED
  191199. png_set_cHRM(png_ptr, info_ptr,
  191200. white_x, white_y, red_x, red_y, green_x, green_y, blue_x, blue_y);
  191201. #endif
  191202. #ifdef PNG_FIXED_POINT_SUPPORTED
  191203. png_set_cHRM_fixed(png_ptr, info_ptr,
  191204. int_x_white, int_y_white, int_x_red, int_y_red, int_x_green,
  191205. int_y_green, int_x_blue, int_y_blue);
  191206. #endif
  191207. if (png_crc_finish(png_ptr, 0))
  191208. return;
  191209. }
  191210. #endif
  191211. #if defined(PNG_READ_sRGB_SUPPORTED)
  191212. void /* PRIVATE */
  191213. png_handle_sRGB(png_structp png_ptr, png_infop info_ptr, png_uint_32 length)
  191214. {
  191215. int intent;
  191216. png_byte buf[1];
  191217. png_debug(1, "in png_handle_sRGB\n");
  191218. if (!(png_ptr->mode & PNG_HAVE_IHDR))
  191219. png_error(png_ptr, "Missing IHDR before sRGB");
  191220. else if (png_ptr->mode & PNG_HAVE_IDAT)
  191221. {
  191222. png_warning(png_ptr, "Invalid sRGB after IDAT");
  191223. png_crc_finish(png_ptr, length);
  191224. return;
  191225. }
  191226. else if (png_ptr->mode & PNG_HAVE_PLTE)
  191227. /* Should be an error, but we can cope with it */
  191228. png_warning(png_ptr, "Out of place sRGB chunk");
  191229. if (info_ptr != NULL && (info_ptr->valid & PNG_INFO_sRGB))
  191230. {
  191231. png_warning(png_ptr, "Duplicate sRGB chunk");
  191232. png_crc_finish(png_ptr, length);
  191233. return;
  191234. }
  191235. if (length != 1)
  191236. {
  191237. png_warning(png_ptr, "Incorrect sRGB chunk length");
  191238. png_crc_finish(png_ptr, length);
  191239. return;
  191240. }
  191241. png_crc_read(png_ptr, buf, 1);
  191242. if (png_crc_finish(png_ptr, 0))
  191243. return;
  191244. intent = buf[0];
  191245. /* check for bad intent */
  191246. if (intent >= PNG_sRGB_INTENT_LAST)
  191247. {
  191248. png_warning(png_ptr, "Unknown sRGB intent");
  191249. return;
  191250. }
  191251. #if defined(PNG_READ_gAMA_SUPPORTED) && defined(PNG_READ_GAMMA_SUPPORTED)
  191252. if (info_ptr != NULL && (info_ptr->valid & PNG_INFO_gAMA))
  191253. {
  191254. png_fixed_point igamma;
  191255. #ifdef PNG_FIXED_POINT_SUPPORTED
  191256. igamma=info_ptr->int_gamma;
  191257. #else
  191258. # ifdef PNG_FLOATING_POINT_SUPPORTED
  191259. igamma=(png_fixed_point)(info_ptr->gamma * 100000.);
  191260. # endif
  191261. #endif
  191262. if (PNG_OUT_OF_RANGE(igamma, 45500L, 500))
  191263. {
  191264. png_warning(png_ptr,
  191265. "Ignoring incorrect gAMA value when sRGB is also present");
  191266. #ifndef PNG_NO_CONSOLE_IO
  191267. # ifdef PNG_FIXED_POINT_SUPPORTED
  191268. fprintf(stderr,"incorrect gamma=(%d/100000)\n",(int)png_ptr->int_gamma);
  191269. # else
  191270. # ifdef PNG_FLOATING_POINT_SUPPORTED
  191271. fprintf(stderr,"incorrect gamma=%f\n",png_ptr->gamma);
  191272. # endif
  191273. # endif
  191274. #endif
  191275. }
  191276. }
  191277. #endif /* PNG_READ_gAMA_SUPPORTED */
  191278. #ifdef PNG_READ_cHRM_SUPPORTED
  191279. #ifdef PNG_FIXED_POINT_SUPPORTED
  191280. if (info_ptr != NULL && (info_ptr->valid & PNG_INFO_cHRM))
  191281. if (PNG_OUT_OF_RANGE(info_ptr->int_x_white, 31270, 1000) ||
  191282. PNG_OUT_OF_RANGE(info_ptr->int_y_white, 32900, 1000) ||
  191283. PNG_OUT_OF_RANGE(info_ptr->int_x_red, 64000L, 1000) ||
  191284. PNG_OUT_OF_RANGE(info_ptr->int_y_red, 33000, 1000) ||
  191285. PNG_OUT_OF_RANGE(info_ptr->int_x_green, 30000, 1000) ||
  191286. PNG_OUT_OF_RANGE(info_ptr->int_y_green, 60000L, 1000) ||
  191287. PNG_OUT_OF_RANGE(info_ptr->int_x_blue, 15000, 1000) ||
  191288. PNG_OUT_OF_RANGE(info_ptr->int_y_blue, 6000, 1000))
  191289. {
  191290. png_warning(png_ptr,
  191291. "Ignoring incorrect cHRM value when sRGB is also present");
  191292. }
  191293. #endif /* PNG_FIXED_POINT_SUPPORTED */
  191294. #endif /* PNG_READ_cHRM_SUPPORTED */
  191295. png_set_sRGB_gAMA_and_cHRM(png_ptr, info_ptr, intent);
  191296. }
  191297. #endif /* PNG_READ_sRGB_SUPPORTED */
  191298. #if defined(PNG_READ_iCCP_SUPPORTED)
  191299. void /* PRIVATE */
  191300. png_handle_iCCP(png_structp png_ptr, png_infop info_ptr, png_uint_32 length)
  191301. /* Note: this does not properly handle chunks that are > 64K under DOS */
  191302. {
  191303. png_charp chunkdata;
  191304. png_byte compression_type;
  191305. png_bytep pC;
  191306. png_charp profile;
  191307. png_uint_32 skip = 0;
  191308. png_uint_32 profile_size, profile_length;
  191309. png_size_t slength, prefix_length, data_length;
  191310. png_debug(1, "in png_handle_iCCP\n");
  191311. if (!(png_ptr->mode & PNG_HAVE_IHDR))
  191312. png_error(png_ptr, "Missing IHDR before iCCP");
  191313. else if (png_ptr->mode & PNG_HAVE_IDAT)
  191314. {
  191315. png_warning(png_ptr, "Invalid iCCP after IDAT");
  191316. png_crc_finish(png_ptr, length);
  191317. return;
  191318. }
  191319. else if (png_ptr->mode & PNG_HAVE_PLTE)
  191320. /* Should be an error, but we can cope with it */
  191321. png_warning(png_ptr, "Out of place iCCP chunk");
  191322. if (info_ptr != NULL && (info_ptr->valid & PNG_INFO_iCCP))
  191323. {
  191324. png_warning(png_ptr, "Duplicate iCCP chunk");
  191325. png_crc_finish(png_ptr, length);
  191326. return;
  191327. }
  191328. #ifdef PNG_MAX_MALLOC_64K
  191329. if (length > (png_uint_32)65535L)
  191330. {
  191331. png_warning(png_ptr, "iCCP chunk too large to fit in memory");
  191332. skip = length - (png_uint_32)65535L;
  191333. length = (png_uint_32)65535L;
  191334. }
  191335. #endif
  191336. chunkdata = (png_charp)png_malloc(png_ptr, length + 1);
  191337. slength = (png_size_t)length;
  191338. png_crc_read(png_ptr, (png_bytep)chunkdata, slength);
  191339. if (png_crc_finish(png_ptr, skip))
  191340. {
  191341. png_free(png_ptr, chunkdata);
  191342. return;
  191343. }
  191344. chunkdata[slength] = 0x00;
  191345. for (profile = chunkdata; *profile; profile++)
  191346. /* empty loop to find end of name */ ;
  191347. ++profile;
  191348. /* there should be at least one zero (the compression type byte)
  191349. following the separator, and we should be on it */
  191350. if ( profile >= chunkdata + slength - 1)
  191351. {
  191352. png_free(png_ptr, chunkdata);
  191353. png_warning(png_ptr, "Malformed iCCP chunk");
  191354. return;
  191355. }
  191356. /* compression_type should always be zero */
  191357. compression_type = *profile++;
  191358. if (compression_type)
  191359. {
  191360. png_warning(png_ptr, "Ignoring nonzero compression type in iCCP chunk");
  191361. compression_type=0x00; /* Reset it to zero (libpng-1.0.6 through 1.0.8
  191362. wrote nonzero) */
  191363. }
  191364. prefix_length = profile - chunkdata;
  191365. chunkdata = png_decompress_chunk(png_ptr, compression_type, chunkdata,
  191366. slength, prefix_length, &data_length);
  191367. profile_length = data_length - prefix_length;
  191368. if ( prefix_length > data_length || profile_length < 4)
  191369. {
  191370. png_free(png_ptr, chunkdata);
  191371. png_warning(png_ptr, "Profile size field missing from iCCP chunk");
  191372. return;
  191373. }
  191374. /* Check the profile_size recorded in the first 32 bits of the ICC profile */
  191375. pC = (png_bytep)(chunkdata+prefix_length);
  191376. profile_size = ((*(pC ))<<24) |
  191377. ((*(pC+1))<<16) |
  191378. ((*(pC+2))<< 8) |
  191379. ((*(pC+3)) );
  191380. if(profile_size < profile_length)
  191381. profile_length = profile_size;
  191382. if(profile_size > profile_length)
  191383. {
  191384. png_free(png_ptr, chunkdata);
  191385. png_warning(png_ptr, "Ignoring truncated iCCP profile.");
  191386. return;
  191387. }
  191388. png_set_iCCP(png_ptr, info_ptr, chunkdata, compression_type,
  191389. chunkdata + prefix_length, profile_length);
  191390. png_free(png_ptr, chunkdata);
  191391. }
  191392. #endif /* PNG_READ_iCCP_SUPPORTED */
  191393. #if defined(PNG_READ_sPLT_SUPPORTED)
  191394. void /* PRIVATE */
  191395. png_handle_sPLT(png_structp png_ptr, png_infop info_ptr, png_uint_32 length)
  191396. /* Note: this does not properly handle chunks that are > 64K under DOS */
  191397. {
  191398. png_bytep chunkdata;
  191399. png_bytep entry_start;
  191400. png_sPLT_t new_palette;
  191401. #ifdef PNG_NO_POINTER_INDEXING
  191402. png_sPLT_entryp pp;
  191403. #endif
  191404. int data_length, entry_size, i;
  191405. png_uint_32 skip = 0;
  191406. png_size_t slength;
  191407. png_debug(1, "in png_handle_sPLT\n");
  191408. if (!(png_ptr->mode & PNG_HAVE_IHDR))
  191409. png_error(png_ptr, "Missing IHDR before sPLT");
  191410. else if (png_ptr->mode & PNG_HAVE_IDAT)
  191411. {
  191412. png_warning(png_ptr, "Invalid sPLT after IDAT");
  191413. png_crc_finish(png_ptr, length);
  191414. return;
  191415. }
  191416. #ifdef PNG_MAX_MALLOC_64K
  191417. if (length > (png_uint_32)65535L)
  191418. {
  191419. png_warning(png_ptr, "sPLT chunk too large to fit in memory");
  191420. skip = length - (png_uint_32)65535L;
  191421. length = (png_uint_32)65535L;
  191422. }
  191423. #endif
  191424. chunkdata = (png_bytep)png_malloc(png_ptr, length + 1);
  191425. slength = (png_size_t)length;
  191426. png_crc_read(png_ptr, (png_bytep)chunkdata, slength);
  191427. if (png_crc_finish(png_ptr, skip))
  191428. {
  191429. png_free(png_ptr, chunkdata);
  191430. return;
  191431. }
  191432. chunkdata[slength] = 0x00;
  191433. for (entry_start = chunkdata; *entry_start; entry_start++)
  191434. /* empty loop to find end of name */ ;
  191435. ++entry_start;
  191436. /* a sample depth should follow the separator, and we should be on it */
  191437. if (entry_start > chunkdata + slength - 2)
  191438. {
  191439. png_free(png_ptr, chunkdata);
  191440. png_warning(png_ptr, "malformed sPLT chunk");
  191441. return;
  191442. }
  191443. new_palette.depth = *entry_start++;
  191444. entry_size = (new_palette.depth == 8 ? 6 : 10);
  191445. data_length = (slength - (entry_start - chunkdata));
  191446. /* integrity-check the data length */
  191447. if (data_length % entry_size)
  191448. {
  191449. png_free(png_ptr, chunkdata);
  191450. png_warning(png_ptr, "sPLT chunk has bad length");
  191451. return;
  191452. }
  191453. new_palette.nentries = (png_int_32) ( data_length / entry_size);
  191454. if ((png_uint_32) new_palette.nentries > (png_uint_32) (PNG_SIZE_MAX /
  191455. png_sizeof(png_sPLT_entry)))
  191456. {
  191457. png_warning(png_ptr, "sPLT chunk too long");
  191458. return;
  191459. }
  191460. new_palette.entries = (png_sPLT_entryp)png_malloc_warn(
  191461. png_ptr, new_palette.nentries * png_sizeof(png_sPLT_entry));
  191462. if (new_palette.entries == NULL)
  191463. {
  191464. png_warning(png_ptr, "sPLT chunk requires too much memory");
  191465. return;
  191466. }
  191467. #ifndef PNG_NO_POINTER_INDEXING
  191468. for (i = 0; i < new_palette.nentries; i++)
  191469. {
  191470. png_sPLT_entryp pp = new_palette.entries + i;
  191471. if (new_palette.depth == 8)
  191472. {
  191473. pp->red = *entry_start++;
  191474. pp->green = *entry_start++;
  191475. pp->blue = *entry_start++;
  191476. pp->alpha = *entry_start++;
  191477. }
  191478. else
  191479. {
  191480. pp->red = png_get_uint_16(entry_start); entry_start += 2;
  191481. pp->green = png_get_uint_16(entry_start); entry_start += 2;
  191482. pp->blue = png_get_uint_16(entry_start); entry_start += 2;
  191483. pp->alpha = png_get_uint_16(entry_start); entry_start += 2;
  191484. }
  191485. pp->frequency = png_get_uint_16(entry_start); entry_start += 2;
  191486. }
  191487. #else
  191488. pp = new_palette.entries;
  191489. for (i = 0; i < new_palette.nentries; i++)
  191490. {
  191491. if (new_palette.depth == 8)
  191492. {
  191493. pp[i].red = *entry_start++;
  191494. pp[i].green = *entry_start++;
  191495. pp[i].blue = *entry_start++;
  191496. pp[i].alpha = *entry_start++;
  191497. }
  191498. else
  191499. {
  191500. pp[i].red = png_get_uint_16(entry_start); entry_start += 2;
  191501. pp[i].green = png_get_uint_16(entry_start); entry_start += 2;
  191502. pp[i].blue = png_get_uint_16(entry_start); entry_start += 2;
  191503. pp[i].alpha = png_get_uint_16(entry_start); entry_start += 2;
  191504. }
  191505. pp->frequency = png_get_uint_16(entry_start); entry_start += 2;
  191506. }
  191507. #endif
  191508. /* discard all chunk data except the name and stash that */
  191509. new_palette.name = (png_charp)chunkdata;
  191510. png_set_sPLT(png_ptr, info_ptr, &new_palette, 1);
  191511. png_free(png_ptr, chunkdata);
  191512. png_free(png_ptr, new_palette.entries);
  191513. }
  191514. #endif /* PNG_READ_sPLT_SUPPORTED */
  191515. #if defined(PNG_READ_tRNS_SUPPORTED)
  191516. void /* PRIVATE */
  191517. png_handle_tRNS(png_structp png_ptr, png_infop info_ptr, png_uint_32 length)
  191518. {
  191519. png_byte readbuf[PNG_MAX_PALETTE_LENGTH];
  191520. int bit_mask;
  191521. png_debug(1, "in png_handle_tRNS\n");
  191522. /* For non-indexed color, mask off any bits in the tRNS value that
  191523. * exceed the bit depth. Some creators were writing extra bits there.
  191524. * This is not needed for indexed color. */
  191525. bit_mask = (1 << png_ptr->bit_depth) - 1;
  191526. if (!(png_ptr->mode & PNG_HAVE_IHDR))
  191527. png_error(png_ptr, "Missing IHDR before tRNS");
  191528. else if (png_ptr->mode & PNG_HAVE_IDAT)
  191529. {
  191530. png_warning(png_ptr, "Invalid tRNS after IDAT");
  191531. png_crc_finish(png_ptr, length);
  191532. return;
  191533. }
  191534. else if (info_ptr != NULL && (info_ptr->valid & PNG_INFO_tRNS))
  191535. {
  191536. png_warning(png_ptr, "Duplicate tRNS chunk");
  191537. png_crc_finish(png_ptr, length);
  191538. return;
  191539. }
  191540. if (png_ptr->color_type == PNG_COLOR_TYPE_GRAY)
  191541. {
  191542. png_byte buf[2];
  191543. if (length != 2)
  191544. {
  191545. png_warning(png_ptr, "Incorrect tRNS chunk length");
  191546. png_crc_finish(png_ptr, length);
  191547. return;
  191548. }
  191549. png_crc_read(png_ptr, buf, 2);
  191550. png_ptr->num_trans = 1;
  191551. png_ptr->trans_values.gray = png_get_uint_16(buf) & bit_mask;
  191552. }
  191553. else if (png_ptr->color_type == PNG_COLOR_TYPE_RGB)
  191554. {
  191555. png_byte buf[6];
  191556. if (length != 6)
  191557. {
  191558. png_warning(png_ptr, "Incorrect tRNS chunk length");
  191559. png_crc_finish(png_ptr, length);
  191560. return;
  191561. }
  191562. png_crc_read(png_ptr, buf, (png_size_t)length);
  191563. png_ptr->num_trans = 1;
  191564. png_ptr->trans_values.red = png_get_uint_16(buf) & bit_mask;
  191565. png_ptr->trans_values.green = png_get_uint_16(buf + 2) & bit_mask;
  191566. png_ptr->trans_values.blue = png_get_uint_16(buf + 4) & bit_mask;
  191567. }
  191568. else if (png_ptr->color_type == PNG_COLOR_TYPE_PALETTE)
  191569. {
  191570. if (!(png_ptr->mode & PNG_HAVE_PLTE))
  191571. {
  191572. /* Should be an error, but we can cope with it. */
  191573. png_warning(png_ptr, "Missing PLTE before tRNS");
  191574. }
  191575. if (length > (png_uint_32)png_ptr->num_palette ||
  191576. length > PNG_MAX_PALETTE_LENGTH)
  191577. {
  191578. png_warning(png_ptr, "Incorrect tRNS chunk length");
  191579. png_crc_finish(png_ptr, length);
  191580. return;
  191581. }
  191582. if (length == 0)
  191583. {
  191584. png_warning(png_ptr, "Zero length tRNS chunk");
  191585. png_crc_finish(png_ptr, length);
  191586. return;
  191587. }
  191588. png_crc_read(png_ptr, readbuf, (png_size_t)length);
  191589. png_ptr->num_trans = (png_uint_16)length;
  191590. }
  191591. else
  191592. {
  191593. png_warning(png_ptr, "tRNS chunk not allowed with alpha channel");
  191594. png_crc_finish(png_ptr, length);
  191595. return;
  191596. }
  191597. if (png_crc_finish(png_ptr, 0))
  191598. {
  191599. png_ptr->num_trans = 0;
  191600. return;
  191601. }
  191602. png_set_tRNS(png_ptr, info_ptr, readbuf, png_ptr->num_trans,
  191603. &(png_ptr->trans_values));
  191604. }
  191605. #endif
  191606. #if defined(PNG_READ_bKGD_SUPPORTED)
  191607. void /* PRIVATE */
  191608. png_handle_bKGD(png_structp png_ptr, png_infop info_ptr, png_uint_32 length)
  191609. {
  191610. png_size_t truelen;
  191611. png_byte buf[6];
  191612. png_debug(1, "in png_handle_bKGD\n");
  191613. if (!(png_ptr->mode & PNG_HAVE_IHDR))
  191614. png_error(png_ptr, "Missing IHDR before bKGD");
  191615. else if (png_ptr->mode & PNG_HAVE_IDAT)
  191616. {
  191617. png_warning(png_ptr, "Invalid bKGD after IDAT");
  191618. png_crc_finish(png_ptr, length);
  191619. return;
  191620. }
  191621. else if (png_ptr->color_type == PNG_COLOR_TYPE_PALETTE &&
  191622. !(png_ptr->mode & PNG_HAVE_PLTE))
  191623. {
  191624. png_warning(png_ptr, "Missing PLTE before bKGD");
  191625. png_crc_finish(png_ptr, length);
  191626. return;
  191627. }
  191628. else if (info_ptr != NULL && (info_ptr->valid & PNG_INFO_bKGD))
  191629. {
  191630. png_warning(png_ptr, "Duplicate bKGD chunk");
  191631. png_crc_finish(png_ptr, length);
  191632. return;
  191633. }
  191634. if (png_ptr->color_type == PNG_COLOR_TYPE_PALETTE)
  191635. truelen = 1;
  191636. else if (png_ptr->color_type & PNG_COLOR_MASK_COLOR)
  191637. truelen = 6;
  191638. else
  191639. truelen = 2;
  191640. if (length != truelen)
  191641. {
  191642. png_warning(png_ptr, "Incorrect bKGD chunk length");
  191643. png_crc_finish(png_ptr, length);
  191644. return;
  191645. }
  191646. png_crc_read(png_ptr, buf, truelen);
  191647. if (png_crc_finish(png_ptr, 0))
  191648. return;
  191649. /* We convert the index value into RGB components so that we can allow
  191650. * arbitrary RGB values for background when we have transparency, and
  191651. * so it is easy to determine the RGB values of the background color
  191652. * from the info_ptr struct. */
  191653. if (png_ptr->color_type == PNG_COLOR_TYPE_PALETTE)
  191654. {
  191655. png_ptr->background.index = buf[0];
  191656. if(info_ptr->num_palette)
  191657. {
  191658. if(buf[0] > info_ptr->num_palette)
  191659. {
  191660. png_warning(png_ptr, "Incorrect bKGD chunk index value");
  191661. return;
  191662. }
  191663. png_ptr->background.red =
  191664. (png_uint_16)png_ptr->palette[buf[0]].red;
  191665. png_ptr->background.green =
  191666. (png_uint_16)png_ptr->palette[buf[0]].green;
  191667. png_ptr->background.blue =
  191668. (png_uint_16)png_ptr->palette[buf[0]].blue;
  191669. }
  191670. }
  191671. else if (!(png_ptr->color_type & PNG_COLOR_MASK_COLOR)) /* GRAY */
  191672. {
  191673. png_ptr->background.red =
  191674. png_ptr->background.green =
  191675. png_ptr->background.blue =
  191676. png_ptr->background.gray = png_get_uint_16(buf);
  191677. }
  191678. else
  191679. {
  191680. png_ptr->background.red = png_get_uint_16(buf);
  191681. png_ptr->background.green = png_get_uint_16(buf + 2);
  191682. png_ptr->background.blue = png_get_uint_16(buf + 4);
  191683. }
  191684. png_set_bKGD(png_ptr, info_ptr, &(png_ptr->background));
  191685. }
  191686. #endif
  191687. #if defined(PNG_READ_hIST_SUPPORTED)
  191688. void /* PRIVATE */
  191689. png_handle_hIST(png_structp png_ptr, png_infop info_ptr, png_uint_32 length)
  191690. {
  191691. unsigned int num, i;
  191692. png_uint_16 readbuf[PNG_MAX_PALETTE_LENGTH];
  191693. png_debug(1, "in png_handle_hIST\n");
  191694. if (!(png_ptr->mode & PNG_HAVE_IHDR))
  191695. png_error(png_ptr, "Missing IHDR before hIST");
  191696. else if (png_ptr->mode & PNG_HAVE_IDAT)
  191697. {
  191698. png_warning(png_ptr, "Invalid hIST after IDAT");
  191699. png_crc_finish(png_ptr, length);
  191700. return;
  191701. }
  191702. else if (!(png_ptr->mode & PNG_HAVE_PLTE))
  191703. {
  191704. png_warning(png_ptr, "Missing PLTE before hIST");
  191705. png_crc_finish(png_ptr, length);
  191706. return;
  191707. }
  191708. else if (info_ptr != NULL && (info_ptr->valid & PNG_INFO_hIST))
  191709. {
  191710. png_warning(png_ptr, "Duplicate hIST chunk");
  191711. png_crc_finish(png_ptr, length);
  191712. return;
  191713. }
  191714. num = length / 2 ;
  191715. if (num != (unsigned int) png_ptr->num_palette || num >
  191716. (unsigned int) PNG_MAX_PALETTE_LENGTH)
  191717. {
  191718. png_warning(png_ptr, "Incorrect hIST chunk length");
  191719. png_crc_finish(png_ptr, length);
  191720. return;
  191721. }
  191722. for (i = 0; i < num; i++)
  191723. {
  191724. png_byte buf[2];
  191725. png_crc_read(png_ptr, buf, 2);
  191726. readbuf[i] = png_get_uint_16(buf);
  191727. }
  191728. if (png_crc_finish(png_ptr, 0))
  191729. return;
  191730. png_set_hIST(png_ptr, info_ptr, readbuf);
  191731. }
  191732. #endif
  191733. #if defined(PNG_READ_pHYs_SUPPORTED)
  191734. void /* PRIVATE */
  191735. png_handle_pHYs(png_structp png_ptr, png_infop info_ptr, png_uint_32 length)
  191736. {
  191737. png_byte buf[9];
  191738. png_uint_32 res_x, res_y;
  191739. int unit_type;
  191740. png_debug(1, "in png_handle_pHYs\n");
  191741. if (!(png_ptr->mode & PNG_HAVE_IHDR))
  191742. png_error(png_ptr, "Missing IHDR before pHYs");
  191743. else if (png_ptr->mode & PNG_HAVE_IDAT)
  191744. {
  191745. png_warning(png_ptr, "Invalid pHYs after IDAT");
  191746. png_crc_finish(png_ptr, length);
  191747. return;
  191748. }
  191749. else if (info_ptr != NULL && (info_ptr->valid & PNG_INFO_pHYs))
  191750. {
  191751. png_warning(png_ptr, "Duplicate pHYs chunk");
  191752. png_crc_finish(png_ptr, length);
  191753. return;
  191754. }
  191755. if (length != 9)
  191756. {
  191757. png_warning(png_ptr, "Incorrect pHYs chunk length");
  191758. png_crc_finish(png_ptr, length);
  191759. return;
  191760. }
  191761. png_crc_read(png_ptr, buf, 9);
  191762. if (png_crc_finish(png_ptr, 0))
  191763. return;
  191764. res_x = png_get_uint_32(buf);
  191765. res_y = png_get_uint_32(buf + 4);
  191766. unit_type = buf[8];
  191767. png_set_pHYs(png_ptr, info_ptr, res_x, res_y, unit_type);
  191768. }
  191769. #endif
  191770. #if defined(PNG_READ_oFFs_SUPPORTED)
  191771. void /* PRIVATE */
  191772. png_handle_oFFs(png_structp png_ptr, png_infop info_ptr, png_uint_32 length)
  191773. {
  191774. png_byte buf[9];
  191775. png_int_32 offset_x, offset_y;
  191776. int unit_type;
  191777. png_debug(1, "in png_handle_oFFs\n");
  191778. if (!(png_ptr->mode & PNG_HAVE_IHDR))
  191779. png_error(png_ptr, "Missing IHDR before oFFs");
  191780. else if (png_ptr->mode & PNG_HAVE_IDAT)
  191781. {
  191782. png_warning(png_ptr, "Invalid oFFs after IDAT");
  191783. png_crc_finish(png_ptr, length);
  191784. return;
  191785. }
  191786. else if (info_ptr != NULL && (info_ptr->valid & PNG_INFO_oFFs))
  191787. {
  191788. png_warning(png_ptr, "Duplicate oFFs chunk");
  191789. png_crc_finish(png_ptr, length);
  191790. return;
  191791. }
  191792. if (length != 9)
  191793. {
  191794. png_warning(png_ptr, "Incorrect oFFs chunk length");
  191795. png_crc_finish(png_ptr, length);
  191796. return;
  191797. }
  191798. png_crc_read(png_ptr, buf, 9);
  191799. if (png_crc_finish(png_ptr, 0))
  191800. return;
  191801. offset_x = png_get_int_32(buf);
  191802. offset_y = png_get_int_32(buf + 4);
  191803. unit_type = buf[8];
  191804. png_set_oFFs(png_ptr, info_ptr, offset_x, offset_y, unit_type);
  191805. }
  191806. #endif
  191807. #if defined(PNG_READ_pCAL_SUPPORTED)
  191808. /* read the pCAL chunk (described in the PNG Extensions document) */
  191809. void /* PRIVATE */
  191810. png_handle_pCAL(png_structp png_ptr, png_infop info_ptr, png_uint_32 length)
  191811. {
  191812. png_charp purpose;
  191813. png_int_32 X0, X1;
  191814. png_byte type, nparams;
  191815. png_charp buf, units, endptr;
  191816. png_charpp params;
  191817. png_size_t slength;
  191818. int i;
  191819. png_debug(1, "in png_handle_pCAL\n");
  191820. if (!(png_ptr->mode & PNG_HAVE_IHDR))
  191821. png_error(png_ptr, "Missing IHDR before pCAL");
  191822. else if (png_ptr->mode & PNG_HAVE_IDAT)
  191823. {
  191824. png_warning(png_ptr, "Invalid pCAL after IDAT");
  191825. png_crc_finish(png_ptr, length);
  191826. return;
  191827. }
  191828. else if (info_ptr != NULL && (info_ptr->valid & PNG_INFO_pCAL))
  191829. {
  191830. png_warning(png_ptr, "Duplicate pCAL chunk");
  191831. png_crc_finish(png_ptr, length);
  191832. return;
  191833. }
  191834. png_debug1(2, "Allocating and reading pCAL chunk data (%lu bytes)\n",
  191835. length + 1);
  191836. purpose = (png_charp)png_malloc_warn(png_ptr, length + 1);
  191837. if (purpose == NULL)
  191838. {
  191839. png_warning(png_ptr, "No memory for pCAL purpose.");
  191840. return;
  191841. }
  191842. slength = (png_size_t)length;
  191843. png_crc_read(png_ptr, (png_bytep)purpose, slength);
  191844. if (png_crc_finish(png_ptr, 0))
  191845. {
  191846. png_free(png_ptr, purpose);
  191847. return;
  191848. }
  191849. purpose[slength] = 0x00; /* null terminate the last string */
  191850. png_debug(3, "Finding end of pCAL purpose string\n");
  191851. for (buf = purpose; *buf; buf++)
  191852. /* empty loop */ ;
  191853. endptr = purpose + slength;
  191854. /* We need to have at least 12 bytes after the purpose string
  191855. in order to get the parameter information. */
  191856. if (endptr <= buf + 12)
  191857. {
  191858. png_warning(png_ptr, "Invalid pCAL data");
  191859. png_free(png_ptr, purpose);
  191860. return;
  191861. }
  191862. png_debug(3, "Reading pCAL X0, X1, type, nparams, and units\n");
  191863. X0 = png_get_int_32((png_bytep)buf+1);
  191864. X1 = png_get_int_32((png_bytep)buf+5);
  191865. type = buf[9];
  191866. nparams = buf[10];
  191867. units = buf + 11;
  191868. png_debug(3, "Checking pCAL equation type and number of parameters\n");
  191869. /* Check that we have the right number of parameters for known
  191870. equation types. */
  191871. if ((type == PNG_EQUATION_LINEAR && nparams != 2) ||
  191872. (type == PNG_EQUATION_BASE_E && nparams != 3) ||
  191873. (type == PNG_EQUATION_ARBITRARY && nparams != 3) ||
  191874. (type == PNG_EQUATION_HYPERBOLIC && nparams != 4))
  191875. {
  191876. png_warning(png_ptr, "Invalid pCAL parameters for equation type");
  191877. png_free(png_ptr, purpose);
  191878. return;
  191879. }
  191880. else if (type >= PNG_EQUATION_LAST)
  191881. {
  191882. png_warning(png_ptr, "Unrecognized equation type for pCAL chunk");
  191883. }
  191884. for (buf = units; *buf; buf++)
  191885. /* Empty loop to move past the units string. */ ;
  191886. png_debug(3, "Allocating pCAL parameters array\n");
  191887. params = (png_charpp)png_malloc_warn(png_ptr, (png_uint_32)(nparams
  191888. *png_sizeof(png_charp))) ;
  191889. if (params == NULL)
  191890. {
  191891. png_free(png_ptr, purpose);
  191892. png_warning(png_ptr, "No memory for pCAL params.");
  191893. return;
  191894. }
  191895. /* Get pointers to the start of each parameter string. */
  191896. for (i = 0; i < (int)nparams; i++)
  191897. {
  191898. buf++; /* Skip the null string terminator from previous parameter. */
  191899. png_debug1(3, "Reading pCAL parameter %d\n", i);
  191900. for (params[i] = buf; buf <= endptr && *buf != 0x00; buf++)
  191901. /* Empty loop to move past each parameter string */ ;
  191902. /* Make sure we haven't run out of data yet */
  191903. if (buf > endptr)
  191904. {
  191905. png_warning(png_ptr, "Invalid pCAL data");
  191906. png_free(png_ptr, purpose);
  191907. png_free(png_ptr, params);
  191908. return;
  191909. }
  191910. }
  191911. png_set_pCAL(png_ptr, info_ptr, purpose, X0, X1, type, nparams,
  191912. units, params);
  191913. png_free(png_ptr, purpose);
  191914. png_free(png_ptr, params);
  191915. }
  191916. #endif
  191917. #if defined(PNG_READ_sCAL_SUPPORTED)
  191918. /* read the sCAL chunk */
  191919. void /* PRIVATE */
  191920. png_handle_sCAL(png_structp png_ptr, png_infop info_ptr, png_uint_32 length)
  191921. {
  191922. png_charp buffer, ep;
  191923. #ifdef PNG_FLOATING_POINT_SUPPORTED
  191924. double width, height;
  191925. png_charp vp;
  191926. #else
  191927. #ifdef PNG_FIXED_POINT_SUPPORTED
  191928. png_charp swidth, sheight;
  191929. #endif
  191930. #endif
  191931. png_size_t slength;
  191932. png_debug(1, "in png_handle_sCAL\n");
  191933. if (!(png_ptr->mode & PNG_HAVE_IHDR))
  191934. png_error(png_ptr, "Missing IHDR before sCAL");
  191935. else if (png_ptr->mode & PNG_HAVE_IDAT)
  191936. {
  191937. png_warning(png_ptr, "Invalid sCAL after IDAT");
  191938. png_crc_finish(png_ptr, length);
  191939. return;
  191940. }
  191941. else if (info_ptr != NULL && (info_ptr->valid & PNG_INFO_sCAL))
  191942. {
  191943. png_warning(png_ptr, "Duplicate sCAL chunk");
  191944. png_crc_finish(png_ptr, length);
  191945. return;
  191946. }
  191947. png_debug1(2, "Allocating and reading sCAL chunk data (%lu bytes)\n",
  191948. length + 1);
  191949. buffer = (png_charp)png_malloc_warn(png_ptr, length + 1);
  191950. if (buffer == NULL)
  191951. {
  191952. png_warning(png_ptr, "Out of memory while processing sCAL chunk");
  191953. return;
  191954. }
  191955. slength = (png_size_t)length;
  191956. png_crc_read(png_ptr, (png_bytep)buffer, slength);
  191957. if (png_crc_finish(png_ptr, 0))
  191958. {
  191959. png_free(png_ptr, buffer);
  191960. return;
  191961. }
  191962. buffer[slength] = 0x00; /* null terminate the last string */
  191963. ep = buffer + 1; /* skip unit byte */
  191964. #ifdef PNG_FLOATING_POINT_SUPPORTED
  191965. width = png_strtod(png_ptr, ep, &vp);
  191966. if (*vp)
  191967. {
  191968. png_warning(png_ptr, "malformed width string in sCAL chunk");
  191969. return;
  191970. }
  191971. #else
  191972. #ifdef PNG_FIXED_POINT_SUPPORTED
  191973. swidth = (png_charp)png_malloc_warn(png_ptr, png_strlen(ep) + 1);
  191974. if (swidth == NULL)
  191975. {
  191976. png_warning(png_ptr, "Out of memory while processing sCAL chunk width");
  191977. return;
  191978. }
  191979. png_memcpy(swidth, ep, (png_size_t)png_strlen(ep));
  191980. #endif
  191981. #endif
  191982. for (ep = buffer; *ep; ep++)
  191983. /* empty loop */ ;
  191984. ep++;
  191985. if (buffer + slength < ep)
  191986. {
  191987. png_warning(png_ptr, "Truncated sCAL chunk");
  191988. #if defined(PNG_FIXED_POINT_SUPPORTED) && \
  191989. !defined(PNG_FLOATING_POINT_SUPPORTED)
  191990. png_free(png_ptr, swidth);
  191991. #endif
  191992. png_free(png_ptr, buffer);
  191993. return;
  191994. }
  191995. #ifdef PNG_FLOATING_POINT_SUPPORTED
  191996. height = png_strtod(png_ptr, ep, &vp);
  191997. if (*vp)
  191998. {
  191999. png_warning(png_ptr, "malformed height string in sCAL chunk");
  192000. return;
  192001. }
  192002. #else
  192003. #ifdef PNG_FIXED_POINT_SUPPORTED
  192004. sheight = (png_charp)png_malloc_warn(png_ptr, png_strlen(ep) + 1);
  192005. if (swidth == NULL)
  192006. {
  192007. png_warning(png_ptr, "Out of memory while processing sCAL chunk height");
  192008. return;
  192009. }
  192010. png_memcpy(sheight, ep, (png_size_t)png_strlen(ep));
  192011. #endif
  192012. #endif
  192013. if (buffer + slength < ep
  192014. #ifdef PNG_FLOATING_POINT_SUPPORTED
  192015. || width <= 0. || height <= 0.
  192016. #endif
  192017. )
  192018. {
  192019. png_warning(png_ptr, "Invalid sCAL data");
  192020. png_free(png_ptr, buffer);
  192021. #if defined(PNG_FIXED_POINT_SUPPORTED) && !defined(PNG_FLOATING_POINT_SUPPORTED)
  192022. png_free(png_ptr, swidth);
  192023. png_free(png_ptr, sheight);
  192024. #endif
  192025. return;
  192026. }
  192027. #ifdef PNG_FLOATING_POINT_SUPPORTED
  192028. png_set_sCAL(png_ptr, info_ptr, buffer[0], width, height);
  192029. #else
  192030. #ifdef PNG_FIXED_POINT_SUPPORTED
  192031. png_set_sCAL_s(png_ptr, info_ptr, buffer[0], swidth, sheight);
  192032. #endif
  192033. #endif
  192034. png_free(png_ptr, buffer);
  192035. #if defined(PNG_FIXED_POINT_SUPPORTED) && !defined(PNG_FLOATING_POINT_SUPPORTED)
  192036. png_free(png_ptr, swidth);
  192037. png_free(png_ptr, sheight);
  192038. #endif
  192039. }
  192040. #endif
  192041. #if defined(PNG_READ_tIME_SUPPORTED)
  192042. void /* PRIVATE */
  192043. png_handle_tIME(png_structp png_ptr, png_infop info_ptr, png_uint_32 length)
  192044. {
  192045. png_byte buf[7];
  192046. png_time mod_time;
  192047. png_debug(1, "in png_handle_tIME\n");
  192048. if (!(png_ptr->mode & PNG_HAVE_IHDR))
  192049. png_error(png_ptr, "Out of place tIME chunk");
  192050. else if (info_ptr != NULL && (info_ptr->valid & PNG_INFO_tIME))
  192051. {
  192052. png_warning(png_ptr, "Duplicate tIME chunk");
  192053. png_crc_finish(png_ptr, length);
  192054. return;
  192055. }
  192056. if (png_ptr->mode & PNG_HAVE_IDAT)
  192057. png_ptr->mode |= PNG_AFTER_IDAT;
  192058. if (length != 7)
  192059. {
  192060. png_warning(png_ptr, "Incorrect tIME chunk length");
  192061. png_crc_finish(png_ptr, length);
  192062. return;
  192063. }
  192064. png_crc_read(png_ptr, buf, 7);
  192065. if (png_crc_finish(png_ptr, 0))
  192066. return;
  192067. mod_time.second = buf[6];
  192068. mod_time.minute = buf[5];
  192069. mod_time.hour = buf[4];
  192070. mod_time.day = buf[3];
  192071. mod_time.month = buf[2];
  192072. mod_time.year = png_get_uint_16(buf);
  192073. png_set_tIME(png_ptr, info_ptr, &mod_time);
  192074. }
  192075. #endif
  192076. #if defined(PNG_READ_tEXt_SUPPORTED)
  192077. /* Note: this does not properly handle chunks that are > 64K under DOS */
  192078. void /* PRIVATE */
  192079. png_handle_tEXt(png_structp png_ptr, png_infop info_ptr, png_uint_32 length)
  192080. {
  192081. png_textp text_ptr;
  192082. png_charp key;
  192083. png_charp text;
  192084. png_uint_32 skip = 0;
  192085. png_size_t slength;
  192086. int ret;
  192087. png_debug(1, "in png_handle_tEXt\n");
  192088. if (!(png_ptr->mode & PNG_HAVE_IHDR))
  192089. png_error(png_ptr, "Missing IHDR before tEXt");
  192090. if (png_ptr->mode & PNG_HAVE_IDAT)
  192091. png_ptr->mode |= PNG_AFTER_IDAT;
  192092. #ifdef PNG_MAX_MALLOC_64K
  192093. if (length > (png_uint_32)65535L)
  192094. {
  192095. png_warning(png_ptr, "tEXt chunk too large to fit in memory");
  192096. skip = length - (png_uint_32)65535L;
  192097. length = (png_uint_32)65535L;
  192098. }
  192099. #endif
  192100. key = (png_charp)png_malloc_warn(png_ptr, length + 1);
  192101. if (key == NULL)
  192102. {
  192103. png_warning(png_ptr, "No memory to process text chunk.");
  192104. return;
  192105. }
  192106. slength = (png_size_t)length;
  192107. png_crc_read(png_ptr, (png_bytep)key, slength);
  192108. if (png_crc_finish(png_ptr, skip))
  192109. {
  192110. png_free(png_ptr, key);
  192111. return;
  192112. }
  192113. key[slength] = 0x00;
  192114. for (text = key; *text; text++)
  192115. /* empty loop to find end of key */ ;
  192116. if (text != key + slength)
  192117. text++;
  192118. text_ptr = (png_textp)png_malloc_warn(png_ptr,
  192119. (png_uint_32)png_sizeof(png_text));
  192120. if (text_ptr == NULL)
  192121. {
  192122. png_warning(png_ptr, "Not enough memory to process text chunk.");
  192123. png_free(png_ptr, key);
  192124. return;
  192125. }
  192126. text_ptr->compression = PNG_TEXT_COMPRESSION_NONE;
  192127. text_ptr->key = key;
  192128. #ifdef PNG_iTXt_SUPPORTED
  192129. text_ptr->lang = NULL;
  192130. text_ptr->lang_key = NULL;
  192131. text_ptr->itxt_length = 0;
  192132. #endif
  192133. text_ptr->text = text;
  192134. text_ptr->text_length = png_strlen(text);
  192135. ret=png_set_text_2(png_ptr, info_ptr, text_ptr, 1);
  192136. png_free(png_ptr, key);
  192137. png_free(png_ptr, text_ptr);
  192138. if (ret)
  192139. png_warning(png_ptr, "Insufficient memory to process text chunk.");
  192140. }
  192141. #endif
  192142. #if defined(PNG_READ_zTXt_SUPPORTED)
  192143. /* note: this does not correctly handle chunks that are > 64K under DOS */
  192144. void /* PRIVATE */
  192145. png_handle_zTXt(png_structp png_ptr, png_infop info_ptr, png_uint_32 length)
  192146. {
  192147. png_textp text_ptr;
  192148. png_charp chunkdata;
  192149. png_charp text;
  192150. int comp_type;
  192151. int ret;
  192152. png_size_t slength, prefix_len, data_len;
  192153. png_debug(1, "in png_handle_zTXt\n");
  192154. if (!(png_ptr->mode & PNG_HAVE_IHDR))
  192155. png_error(png_ptr, "Missing IHDR before zTXt");
  192156. if (png_ptr->mode & PNG_HAVE_IDAT)
  192157. png_ptr->mode |= PNG_AFTER_IDAT;
  192158. #ifdef PNG_MAX_MALLOC_64K
  192159. /* We will no doubt have problems with chunks even half this size, but
  192160. there is no hard and fast rule to tell us where to stop. */
  192161. if (length > (png_uint_32)65535L)
  192162. {
  192163. png_warning(png_ptr,"zTXt chunk too large to fit in memory");
  192164. png_crc_finish(png_ptr, length);
  192165. return;
  192166. }
  192167. #endif
  192168. chunkdata = (png_charp)png_malloc_warn(png_ptr, length + 1);
  192169. if (chunkdata == NULL)
  192170. {
  192171. png_warning(png_ptr,"Out of memory processing zTXt chunk.");
  192172. return;
  192173. }
  192174. slength = (png_size_t)length;
  192175. png_crc_read(png_ptr, (png_bytep)chunkdata, slength);
  192176. if (png_crc_finish(png_ptr, 0))
  192177. {
  192178. png_free(png_ptr, chunkdata);
  192179. return;
  192180. }
  192181. chunkdata[slength] = 0x00;
  192182. for (text = chunkdata; *text; text++)
  192183. /* empty loop */ ;
  192184. /* zTXt must have some text after the chunkdataword */
  192185. if (text >= chunkdata + slength - 2)
  192186. {
  192187. png_warning(png_ptr, "Truncated zTXt chunk");
  192188. png_free(png_ptr, chunkdata);
  192189. return;
  192190. }
  192191. else
  192192. {
  192193. comp_type = *(++text);
  192194. if (comp_type != PNG_TEXT_COMPRESSION_zTXt)
  192195. {
  192196. png_warning(png_ptr, "Unknown compression type in zTXt chunk");
  192197. comp_type = PNG_TEXT_COMPRESSION_zTXt;
  192198. }
  192199. text++; /* skip the compression_method byte */
  192200. }
  192201. prefix_len = text - chunkdata;
  192202. chunkdata = (png_charp)png_decompress_chunk(png_ptr, comp_type, chunkdata,
  192203. (png_size_t)length, prefix_len, &data_len);
  192204. text_ptr = (png_textp)png_malloc_warn(png_ptr,
  192205. (png_uint_32)png_sizeof(png_text));
  192206. if (text_ptr == NULL)
  192207. {
  192208. png_warning(png_ptr,"Not enough memory to process zTXt chunk.");
  192209. png_free(png_ptr, chunkdata);
  192210. return;
  192211. }
  192212. text_ptr->compression = comp_type;
  192213. text_ptr->key = chunkdata;
  192214. #ifdef PNG_iTXt_SUPPORTED
  192215. text_ptr->lang = NULL;
  192216. text_ptr->lang_key = NULL;
  192217. text_ptr->itxt_length = 0;
  192218. #endif
  192219. text_ptr->text = chunkdata + prefix_len;
  192220. text_ptr->text_length = data_len;
  192221. ret=png_set_text_2(png_ptr, info_ptr, text_ptr, 1);
  192222. png_free(png_ptr, text_ptr);
  192223. png_free(png_ptr, chunkdata);
  192224. if (ret)
  192225. png_error(png_ptr, "Insufficient memory to store zTXt chunk.");
  192226. }
  192227. #endif
  192228. #if defined(PNG_READ_iTXt_SUPPORTED)
  192229. /* note: this does not correctly handle chunks that are > 64K under DOS */
  192230. void /* PRIVATE */
  192231. png_handle_iTXt(png_structp png_ptr, png_infop info_ptr, png_uint_32 length)
  192232. {
  192233. png_textp text_ptr;
  192234. png_charp chunkdata;
  192235. png_charp key, lang, text, lang_key;
  192236. int comp_flag;
  192237. int comp_type = 0;
  192238. int ret;
  192239. png_size_t slength, prefix_len, data_len;
  192240. png_debug(1, "in png_handle_iTXt\n");
  192241. if (!(png_ptr->mode & PNG_HAVE_IHDR))
  192242. png_error(png_ptr, "Missing IHDR before iTXt");
  192243. if (png_ptr->mode & PNG_HAVE_IDAT)
  192244. png_ptr->mode |= PNG_AFTER_IDAT;
  192245. #ifdef PNG_MAX_MALLOC_64K
  192246. /* We will no doubt have problems with chunks even half this size, but
  192247. there is no hard and fast rule to tell us where to stop. */
  192248. if (length > (png_uint_32)65535L)
  192249. {
  192250. png_warning(png_ptr,"iTXt chunk too large to fit in memory");
  192251. png_crc_finish(png_ptr, length);
  192252. return;
  192253. }
  192254. #endif
  192255. chunkdata = (png_charp)png_malloc_warn(png_ptr, length + 1);
  192256. if (chunkdata == NULL)
  192257. {
  192258. png_warning(png_ptr, "No memory to process iTXt chunk.");
  192259. return;
  192260. }
  192261. slength = (png_size_t)length;
  192262. png_crc_read(png_ptr, (png_bytep)chunkdata, slength);
  192263. if (png_crc_finish(png_ptr, 0))
  192264. {
  192265. png_free(png_ptr, chunkdata);
  192266. return;
  192267. }
  192268. chunkdata[slength] = 0x00;
  192269. for (lang = chunkdata; *lang; lang++)
  192270. /* empty loop */ ;
  192271. lang++; /* skip NUL separator */
  192272. /* iTXt must have a language tag (possibly empty), two compression bytes,
  192273. translated keyword (possibly empty), and possibly some text after the
  192274. keyword */
  192275. if (lang >= chunkdata + slength - 3)
  192276. {
  192277. png_warning(png_ptr, "Truncated iTXt chunk");
  192278. png_free(png_ptr, chunkdata);
  192279. return;
  192280. }
  192281. else
  192282. {
  192283. comp_flag = *lang++;
  192284. comp_type = *lang++;
  192285. }
  192286. for (lang_key = lang; *lang_key; lang_key++)
  192287. /* empty loop */ ;
  192288. lang_key++; /* skip NUL separator */
  192289. if (lang_key >= chunkdata + slength)
  192290. {
  192291. png_warning(png_ptr, "Truncated iTXt chunk");
  192292. png_free(png_ptr, chunkdata);
  192293. return;
  192294. }
  192295. for (text = lang_key; *text; text++)
  192296. /* empty loop */ ;
  192297. text++; /* skip NUL separator */
  192298. if (text >= chunkdata + slength)
  192299. {
  192300. png_warning(png_ptr, "Malformed iTXt chunk");
  192301. png_free(png_ptr, chunkdata);
  192302. return;
  192303. }
  192304. prefix_len = text - chunkdata;
  192305. key=chunkdata;
  192306. if (comp_flag)
  192307. chunkdata = png_decompress_chunk(png_ptr, comp_type, chunkdata,
  192308. (size_t)length, prefix_len, &data_len);
  192309. else
  192310. data_len=png_strlen(chunkdata + prefix_len);
  192311. text_ptr = (png_textp)png_malloc_warn(png_ptr,
  192312. (png_uint_32)png_sizeof(png_text));
  192313. if (text_ptr == NULL)
  192314. {
  192315. png_warning(png_ptr,"Not enough memory to process iTXt chunk.");
  192316. png_free(png_ptr, chunkdata);
  192317. return;
  192318. }
  192319. text_ptr->compression = (int)comp_flag + 1;
  192320. text_ptr->lang_key = chunkdata+(lang_key-key);
  192321. text_ptr->lang = chunkdata+(lang-key);
  192322. text_ptr->itxt_length = data_len;
  192323. text_ptr->text_length = 0;
  192324. text_ptr->key = chunkdata;
  192325. text_ptr->text = chunkdata + prefix_len;
  192326. ret=png_set_text_2(png_ptr, info_ptr, text_ptr, 1);
  192327. png_free(png_ptr, text_ptr);
  192328. png_free(png_ptr, chunkdata);
  192329. if (ret)
  192330. png_error(png_ptr, "Insufficient memory to store iTXt chunk.");
  192331. }
  192332. #endif
  192333. /* This function is called when we haven't found a handler for a
  192334. chunk. If there isn't a problem with the chunk itself (ie bad
  192335. chunk name, CRC, or a critical chunk), the chunk is silently ignored
  192336. -- unless the PNG_FLAG_UNKNOWN_CHUNKS_SUPPORTED flag is on in which
  192337. case it will be saved away to be written out later. */
  192338. void /* PRIVATE */
  192339. png_handle_unknown(png_structp png_ptr, png_infop info_ptr, png_uint_32 length)
  192340. {
  192341. png_uint_32 skip = 0;
  192342. png_debug(1, "in png_handle_unknown\n");
  192343. if (png_ptr->mode & PNG_HAVE_IDAT)
  192344. {
  192345. #ifdef PNG_USE_LOCAL_ARRAYS
  192346. PNG_CONST PNG_IDAT;
  192347. #endif
  192348. if (png_memcmp(png_ptr->chunk_name, png_IDAT, 4)) /* not an IDAT */
  192349. png_ptr->mode |= PNG_AFTER_IDAT;
  192350. }
  192351. png_check_chunk_name(png_ptr, png_ptr->chunk_name);
  192352. if (!(png_ptr->chunk_name[0] & 0x20))
  192353. {
  192354. #if defined(PNG_READ_UNKNOWN_CHUNKS_SUPPORTED)
  192355. if(png_handle_as_unknown(png_ptr, png_ptr->chunk_name) !=
  192356. PNG_HANDLE_CHUNK_ALWAYS
  192357. #if defined(PNG_READ_USER_CHUNKS_SUPPORTED)
  192358. && png_ptr->read_user_chunk_fn == NULL
  192359. #endif
  192360. )
  192361. #endif
  192362. png_chunk_error(png_ptr, "unknown critical chunk");
  192363. }
  192364. #if defined(PNG_READ_UNKNOWN_CHUNKS_SUPPORTED)
  192365. if ((png_ptr->flags & PNG_FLAG_KEEP_UNKNOWN_CHUNKS) ||
  192366. (png_ptr->read_user_chunk_fn != NULL))
  192367. {
  192368. #ifdef PNG_MAX_MALLOC_64K
  192369. if (length > (png_uint_32)65535L)
  192370. {
  192371. png_warning(png_ptr, "unknown chunk too large to fit in memory");
  192372. skip = length - (png_uint_32)65535L;
  192373. length = (png_uint_32)65535L;
  192374. }
  192375. #endif
  192376. png_strncpy((png_charp)png_ptr->unknown_chunk.name,
  192377. (png_charp)png_ptr->chunk_name, 5);
  192378. png_ptr->unknown_chunk.data = (png_bytep)png_malloc(png_ptr, length);
  192379. png_ptr->unknown_chunk.size = (png_size_t)length;
  192380. png_crc_read(png_ptr, (png_bytep)png_ptr->unknown_chunk.data, length);
  192381. #if defined(PNG_READ_USER_CHUNKS_SUPPORTED)
  192382. if(png_ptr->read_user_chunk_fn != NULL)
  192383. {
  192384. /* callback to user unknown chunk handler */
  192385. int ret;
  192386. ret = (*(png_ptr->read_user_chunk_fn))
  192387. (png_ptr, &png_ptr->unknown_chunk);
  192388. if (ret < 0)
  192389. png_chunk_error(png_ptr, "error in user chunk");
  192390. if (ret == 0)
  192391. {
  192392. if (!(png_ptr->chunk_name[0] & 0x20))
  192393. if(png_handle_as_unknown(png_ptr, png_ptr->chunk_name) !=
  192394. PNG_HANDLE_CHUNK_ALWAYS)
  192395. png_chunk_error(png_ptr, "unknown critical chunk");
  192396. png_set_unknown_chunks(png_ptr, info_ptr,
  192397. &png_ptr->unknown_chunk, 1);
  192398. }
  192399. }
  192400. #else
  192401. png_set_unknown_chunks(png_ptr, info_ptr, &png_ptr->unknown_chunk, 1);
  192402. #endif
  192403. png_free(png_ptr, png_ptr->unknown_chunk.data);
  192404. png_ptr->unknown_chunk.data = NULL;
  192405. }
  192406. else
  192407. #endif
  192408. skip = length;
  192409. png_crc_finish(png_ptr, skip);
  192410. #if !defined(PNG_READ_USER_CHUNKS_SUPPORTED)
  192411. info_ptr = info_ptr; /* quiet compiler warnings about unused info_ptr */
  192412. #endif
  192413. }
  192414. /* This function is called to verify that a chunk name is valid.
  192415. This function can't have the "critical chunk check" incorporated
  192416. into it, since in the future we will need to be able to call user
  192417. functions to handle unknown critical chunks after we check that
  192418. the chunk name itself is valid. */
  192419. #define isnonalpha(c) ((c) < 65 || (c) > 122 || ((c) > 90 && (c) < 97))
  192420. void /* PRIVATE */
  192421. png_check_chunk_name(png_structp png_ptr, png_bytep chunk_name)
  192422. {
  192423. png_debug(1, "in png_check_chunk_name\n");
  192424. if (isnonalpha(chunk_name[0]) || isnonalpha(chunk_name[1]) ||
  192425. isnonalpha(chunk_name[2]) || isnonalpha(chunk_name[3]))
  192426. {
  192427. png_chunk_error(png_ptr, "invalid chunk type");
  192428. }
  192429. }
  192430. /* Combines the row recently read in with the existing pixels in the
  192431. row. This routine takes care of alpha and transparency if requested.
  192432. This routine also handles the two methods of progressive display
  192433. of interlaced images, depending on the mask value.
  192434. The mask value describes which pixels are to be combined with
  192435. the row. The pattern always repeats every 8 pixels, so just 8
  192436. bits are needed. A one indicates the pixel is to be combined,
  192437. a zero indicates the pixel is to be skipped. This is in addition
  192438. to any alpha or transparency value associated with the pixel. If
  192439. you want all pixels to be combined, pass 0xff (255) in mask. */
  192440. void /* PRIVATE */
  192441. png_combine_row(png_structp png_ptr, png_bytep row, int mask)
  192442. {
  192443. png_debug(1,"in png_combine_row\n");
  192444. if (mask == 0xff)
  192445. {
  192446. png_memcpy(row, png_ptr->row_buf + 1,
  192447. PNG_ROWBYTES(png_ptr->row_info.pixel_depth, png_ptr->width));
  192448. }
  192449. else
  192450. {
  192451. switch (png_ptr->row_info.pixel_depth)
  192452. {
  192453. case 1:
  192454. {
  192455. png_bytep sp = png_ptr->row_buf + 1;
  192456. png_bytep dp = row;
  192457. int s_inc, s_start, s_end;
  192458. int m = 0x80;
  192459. int shift;
  192460. png_uint_32 i;
  192461. png_uint_32 row_width = png_ptr->width;
  192462. #if defined(PNG_READ_PACKSWAP_SUPPORTED)
  192463. if (png_ptr->transformations & PNG_PACKSWAP)
  192464. {
  192465. s_start = 0;
  192466. s_end = 7;
  192467. s_inc = 1;
  192468. }
  192469. else
  192470. #endif
  192471. {
  192472. s_start = 7;
  192473. s_end = 0;
  192474. s_inc = -1;
  192475. }
  192476. shift = s_start;
  192477. for (i = 0; i < row_width; i++)
  192478. {
  192479. if (m & mask)
  192480. {
  192481. int value;
  192482. value = (*sp >> shift) & 0x01;
  192483. *dp &= (png_byte)((0x7f7f >> (7 - shift)) & 0xff);
  192484. *dp |= (png_byte)(value << shift);
  192485. }
  192486. if (shift == s_end)
  192487. {
  192488. shift = s_start;
  192489. sp++;
  192490. dp++;
  192491. }
  192492. else
  192493. shift += s_inc;
  192494. if (m == 1)
  192495. m = 0x80;
  192496. else
  192497. m >>= 1;
  192498. }
  192499. break;
  192500. }
  192501. case 2:
  192502. {
  192503. png_bytep sp = png_ptr->row_buf + 1;
  192504. png_bytep dp = row;
  192505. int s_start, s_end, s_inc;
  192506. int m = 0x80;
  192507. int shift;
  192508. png_uint_32 i;
  192509. png_uint_32 row_width = png_ptr->width;
  192510. int value;
  192511. #if defined(PNG_READ_PACKSWAP_SUPPORTED)
  192512. if (png_ptr->transformations & PNG_PACKSWAP)
  192513. {
  192514. s_start = 0;
  192515. s_end = 6;
  192516. s_inc = 2;
  192517. }
  192518. else
  192519. #endif
  192520. {
  192521. s_start = 6;
  192522. s_end = 0;
  192523. s_inc = -2;
  192524. }
  192525. shift = s_start;
  192526. for (i = 0; i < row_width; i++)
  192527. {
  192528. if (m & mask)
  192529. {
  192530. value = (*sp >> shift) & 0x03;
  192531. *dp &= (png_byte)((0x3f3f >> (6 - shift)) & 0xff);
  192532. *dp |= (png_byte)(value << shift);
  192533. }
  192534. if (shift == s_end)
  192535. {
  192536. shift = s_start;
  192537. sp++;
  192538. dp++;
  192539. }
  192540. else
  192541. shift += s_inc;
  192542. if (m == 1)
  192543. m = 0x80;
  192544. else
  192545. m >>= 1;
  192546. }
  192547. break;
  192548. }
  192549. case 4:
  192550. {
  192551. png_bytep sp = png_ptr->row_buf + 1;
  192552. png_bytep dp = row;
  192553. int s_start, s_end, s_inc;
  192554. int m = 0x80;
  192555. int shift;
  192556. png_uint_32 i;
  192557. png_uint_32 row_width = png_ptr->width;
  192558. int value;
  192559. #if defined(PNG_READ_PACKSWAP_SUPPORTED)
  192560. if (png_ptr->transformations & PNG_PACKSWAP)
  192561. {
  192562. s_start = 0;
  192563. s_end = 4;
  192564. s_inc = 4;
  192565. }
  192566. else
  192567. #endif
  192568. {
  192569. s_start = 4;
  192570. s_end = 0;
  192571. s_inc = -4;
  192572. }
  192573. shift = s_start;
  192574. for (i = 0; i < row_width; i++)
  192575. {
  192576. if (m & mask)
  192577. {
  192578. value = (*sp >> shift) & 0xf;
  192579. *dp &= (png_byte)((0xf0f >> (4 - shift)) & 0xff);
  192580. *dp |= (png_byte)(value << shift);
  192581. }
  192582. if (shift == s_end)
  192583. {
  192584. shift = s_start;
  192585. sp++;
  192586. dp++;
  192587. }
  192588. else
  192589. shift += s_inc;
  192590. if (m == 1)
  192591. m = 0x80;
  192592. else
  192593. m >>= 1;
  192594. }
  192595. break;
  192596. }
  192597. default:
  192598. {
  192599. png_bytep sp = png_ptr->row_buf + 1;
  192600. png_bytep dp = row;
  192601. png_size_t pixel_bytes = (png_ptr->row_info.pixel_depth >> 3);
  192602. png_uint_32 i;
  192603. png_uint_32 row_width = png_ptr->width;
  192604. png_byte m = 0x80;
  192605. for (i = 0; i < row_width; i++)
  192606. {
  192607. if (m & mask)
  192608. {
  192609. png_memcpy(dp, sp, pixel_bytes);
  192610. }
  192611. sp += pixel_bytes;
  192612. dp += pixel_bytes;
  192613. if (m == 1)
  192614. m = 0x80;
  192615. else
  192616. m >>= 1;
  192617. }
  192618. break;
  192619. }
  192620. }
  192621. }
  192622. }
  192623. #ifdef PNG_READ_INTERLACING_SUPPORTED
  192624. /* OLD pre-1.0.9 interface:
  192625. void png_do_read_interlace(png_row_infop row_info, png_bytep row, int pass,
  192626. png_uint_32 transformations)
  192627. */
  192628. void /* PRIVATE */
  192629. png_do_read_interlace(png_structp png_ptr)
  192630. {
  192631. png_row_infop row_info = &(png_ptr->row_info);
  192632. png_bytep row = png_ptr->row_buf + 1;
  192633. int pass = png_ptr->pass;
  192634. png_uint_32 transformations = png_ptr->transformations;
  192635. #ifdef PNG_USE_LOCAL_ARRAYS
  192636. /* arrays to facilitate easy interlacing - use pass (0 - 6) as index */
  192637. /* offset to next interlace block */
  192638. PNG_CONST int png_pass_inc[7] = {8, 8, 4, 4, 2, 2, 1};
  192639. #endif
  192640. png_debug(1,"in png_do_read_interlace\n");
  192641. if (row != NULL && row_info != NULL)
  192642. {
  192643. png_uint_32 final_width;
  192644. final_width = row_info->width * png_pass_inc[pass];
  192645. switch (row_info->pixel_depth)
  192646. {
  192647. case 1:
  192648. {
  192649. png_bytep sp = row + (png_size_t)((row_info->width - 1) >> 3);
  192650. png_bytep dp = row + (png_size_t)((final_width - 1) >> 3);
  192651. int sshift, dshift;
  192652. int s_start, s_end, s_inc;
  192653. int jstop = png_pass_inc[pass];
  192654. png_byte v;
  192655. png_uint_32 i;
  192656. int j;
  192657. #if defined(PNG_READ_PACKSWAP_SUPPORTED)
  192658. if (transformations & PNG_PACKSWAP)
  192659. {
  192660. sshift = (int)((row_info->width + 7) & 0x07);
  192661. dshift = (int)((final_width + 7) & 0x07);
  192662. s_start = 7;
  192663. s_end = 0;
  192664. s_inc = -1;
  192665. }
  192666. else
  192667. #endif
  192668. {
  192669. sshift = 7 - (int)((row_info->width + 7) & 0x07);
  192670. dshift = 7 - (int)((final_width + 7) & 0x07);
  192671. s_start = 0;
  192672. s_end = 7;
  192673. s_inc = 1;
  192674. }
  192675. for (i = 0; i < row_info->width; i++)
  192676. {
  192677. v = (png_byte)((*sp >> sshift) & 0x01);
  192678. for (j = 0; j < jstop; j++)
  192679. {
  192680. *dp &= (png_byte)((0x7f7f >> (7 - dshift)) & 0xff);
  192681. *dp |= (png_byte)(v << dshift);
  192682. if (dshift == s_end)
  192683. {
  192684. dshift = s_start;
  192685. dp--;
  192686. }
  192687. else
  192688. dshift += s_inc;
  192689. }
  192690. if (sshift == s_end)
  192691. {
  192692. sshift = s_start;
  192693. sp--;
  192694. }
  192695. else
  192696. sshift += s_inc;
  192697. }
  192698. break;
  192699. }
  192700. case 2:
  192701. {
  192702. png_bytep sp = row + (png_uint_32)((row_info->width - 1) >> 2);
  192703. png_bytep dp = row + (png_uint_32)((final_width - 1) >> 2);
  192704. int sshift, dshift;
  192705. int s_start, s_end, s_inc;
  192706. int jstop = png_pass_inc[pass];
  192707. png_uint_32 i;
  192708. #if defined(PNG_READ_PACKSWAP_SUPPORTED)
  192709. if (transformations & PNG_PACKSWAP)
  192710. {
  192711. sshift = (int)(((row_info->width + 3) & 0x03) << 1);
  192712. dshift = (int)(((final_width + 3) & 0x03) << 1);
  192713. s_start = 6;
  192714. s_end = 0;
  192715. s_inc = -2;
  192716. }
  192717. else
  192718. #endif
  192719. {
  192720. sshift = (int)((3 - ((row_info->width + 3) & 0x03)) << 1);
  192721. dshift = (int)((3 - ((final_width + 3) & 0x03)) << 1);
  192722. s_start = 0;
  192723. s_end = 6;
  192724. s_inc = 2;
  192725. }
  192726. for (i = 0; i < row_info->width; i++)
  192727. {
  192728. png_byte v;
  192729. int j;
  192730. v = (png_byte)((*sp >> sshift) & 0x03);
  192731. for (j = 0; j < jstop; j++)
  192732. {
  192733. *dp &= (png_byte)((0x3f3f >> (6 - dshift)) & 0xff);
  192734. *dp |= (png_byte)(v << dshift);
  192735. if (dshift == s_end)
  192736. {
  192737. dshift = s_start;
  192738. dp--;
  192739. }
  192740. else
  192741. dshift += s_inc;
  192742. }
  192743. if (sshift == s_end)
  192744. {
  192745. sshift = s_start;
  192746. sp--;
  192747. }
  192748. else
  192749. sshift += s_inc;
  192750. }
  192751. break;
  192752. }
  192753. case 4:
  192754. {
  192755. png_bytep sp = row + (png_size_t)((row_info->width - 1) >> 1);
  192756. png_bytep dp = row + (png_size_t)((final_width - 1) >> 1);
  192757. int sshift, dshift;
  192758. int s_start, s_end, s_inc;
  192759. png_uint_32 i;
  192760. int jstop = png_pass_inc[pass];
  192761. #if defined(PNG_READ_PACKSWAP_SUPPORTED)
  192762. if (transformations & PNG_PACKSWAP)
  192763. {
  192764. sshift = (int)(((row_info->width + 1) & 0x01) << 2);
  192765. dshift = (int)(((final_width + 1) & 0x01) << 2);
  192766. s_start = 4;
  192767. s_end = 0;
  192768. s_inc = -4;
  192769. }
  192770. else
  192771. #endif
  192772. {
  192773. sshift = (int)((1 - ((row_info->width + 1) & 0x01)) << 2);
  192774. dshift = (int)((1 - ((final_width + 1) & 0x01)) << 2);
  192775. s_start = 0;
  192776. s_end = 4;
  192777. s_inc = 4;
  192778. }
  192779. for (i = 0; i < row_info->width; i++)
  192780. {
  192781. png_byte v = (png_byte)((*sp >> sshift) & 0xf);
  192782. int j;
  192783. for (j = 0; j < jstop; j++)
  192784. {
  192785. *dp &= (png_byte)((0xf0f >> (4 - dshift)) & 0xff);
  192786. *dp |= (png_byte)(v << dshift);
  192787. if (dshift == s_end)
  192788. {
  192789. dshift = s_start;
  192790. dp--;
  192791. }
  192792. else
  192793. dshift += s_inc;
  192794. }
  192795. if (sshift == s_end)
  192796. {
  192797. sshift = s_start;
  192798. sp--;
  192799. }
  192800. else
  192801. sshift += s_inc;
  192802. }
  192803. break;
  192804. }
  192805. default:
  192806. {
  192807. png_size_t pixel_bytes = (row_info->pixel_depth >> 3);
  192808. png_bytep sp = row + (png_size_t)(row_info->width - 1) * pixel_bytes;
  192809. png_bytep dp = row + (png_size_t)(final_width - 1) * pixel_bytes;
  192810. int jstop = png_pass_inc[pass];
  192811. png_uint_32 i;
  192812. for (i = 0; i < row_info->width; i++)
  192813. {
  192814. png_byte v[8];
  192815. int j;
  192816. png_memcpy(v, sp, pixel_bytes);
  192817. for (j = 0; j < jstop; j++)
  192818. {
  192819. png_memcpy(dp, v, pixel_bytes);
  192820. dp -= pixel_bytes;
  192821. }
  192822. sp -= pixel_bytes;
  192823. }
  192824. break;
  192825. }
  192826. }
  192827. row_info->width = final_width;
  192828. row_info->rowbytes = PNG_ROWBYTES(row_info->pixel_depth,final_width);
  192829. }
  192830. #if !defined(PNG_READ_PACKSWAP_SUPPORTED)
  192831. transformations = transformations; /* silence compiler warning */
  192832. #endif
  192833. }
  192834. #endif /* PNG_READ_INTERLACING_SUPPORTED */
  192835. void /* PRIVATE */
  192836. png_read_filter_row(png_structp png_ptr, png_row_infop row_info, png_bytep row,
  192837. png_bytep prev_row, int filter)
  192838. {
  192839. png_debug(1, "in png_read_filter_row\n");
  192840. png_debug2(2,"row = %lu, filter = %d\n", png_ptr->row_number, filter);
  192841. switch (filter)
  192842. {
  192843. case PNG_FILTER_VALUE_NONE:
  192844. break;
  192845. case PNG_FILTER_VALUE_SUB:
  192846. {
  192847. png_uint_32 i;
  192848. png_uint_32 istop = row_info->rowbytes;
  192849. png_uint_32 bpp = (row_info->pixel_depth + 7) >> 3;
  192850. png_bytep rp = row + bpp;
  192851. png_bytep lp = row;
  192852. for (i = bpp; i < istop; i++)
  192853. {
  192854. *rp = (png_byte)(((int)(*rp) + (int)(*lp++)) & 0xff);
  192855. rp++;
  192856. }
  192857. break;
  192858. }
  192859. case PNG_FILTER_VALUE_UP:
  192860. {
  192861. png_uint_32 i;
  192862. png_uint_32 istop = row_info->rowbytes;
  192863. png_bytep rp = row;
  192864. png_bytep pp = prev_row;
  192865. for (i = 0; i < istop; i++)
  192866. {
  192867. *rp = (png_byte)(((int)(*rp) + (int)(*pp++)) & 0xff);
  192868. rp++;
  192869. }
  192870. break;
  192871. }
  192872. case PNG_FILTER_VALUE_AVG:
  192873. {
  192874. png_uint_32 i;
  192875. png_bytep rp = row;
  192876. png_bytep pp = prev_row;
  192877. png_bytep lp = row;
  192878. png_uint_32 bpp = (row_info->pixel_depth + 7) >> 3;
  192879. png_uint_32 istop = row_info->rowbytes - bpp;
  192880. for (i = 0; i < bpp; i++)
  192881. {
  192882. *rp = (png_byte)(((int)(*rp) +
  192883. ((int)(*pp++) / 2 )) & 0xff);
  192884. rp++;
  192885. }
  192886. for (i = 0; i < istop; i++)
  192887. {
  192888. *rp = (png_byte)(((int)(*rp) +
  192889. (int)(*pp++ + *lp++) / 2 ) & 0xff);
  192890. rp++;
  192891. }
  192892. break;
  192893. }
  192894. case PNG_FILTER_VALUE_PAETH:
  192895. {
  192896. png_uint_32 i;
  192897. png_bytep rp = row;
  192898. png_bytep pp = prev_row;
  192899. png_bytep lp = row;
  192900. png_bytep cp = prev_row;
  192901. png_uint_32 bpp = (row_info->pixel_depth + 7) >> 3;
  192902. png_uint_32 istop=row_info->rowbytes - bpp;
  192903. for (i = 0; i < bpp; i++)
  192904. {
  192905. *rp = (png_byte)(((int)(*rp) + (int)(*pp++)) & 0xff);
  192906. rp++;
  192907. }
  192908. for (i = 0; i < istop; i++) /* use leftover rp,pp */
  192909. {
  192910. int a, b, c, pa, pb, pc, p;
  192911. a = *lp++;
  192912. b = *pp++;
  192913. c = *cp++;
  192914. p = b - c;
  192915. pc = a - c;
  192916. #ifdef PNG_USE_ABS
  192917. pa = abs(p);
  192918. pb = abs(pc);
  192919. pc = abs(p + pc);
  192920. #else
  192921. pa = p < 0 ? -p : p;
  192922. pb = pc < 0 ? -pc : pc;
  192923. pc = (p + pc) < 0 ? -(p + pc) : p + pc;
  192924. #endif
  192925. /*
  192926. if (pa <= pb && pa <= pc)
  192927. p = a;
  192928. else if (pb <= pc)
  192929. p = b;
  192930. else
  192931. p = c;
  192932. */
  192933. p = (pa <= pb && pa <=pc) ? a : (pb <= pc) ? b : c;
  192934. *rp = (png_byte)(((int)(*rp) + p) & 0xff);
  192935. rp++;
  192936. }
  192937. break;
  192938. }
  192939. default:
  192940. png_warning(png_ptr, "Ignoring bad adaptive filter type");
  192941. *row=0;
  192942. break;
  192943. }
  192944. }
  192945. void /* PRIVATE */
  192946. png_read_finish_row(png_structp png_ptr)
  192947. {
  192948. #ifdef PNG_USE_LOCAL_ARRAYS
  192949. /* arrays to facilitate easy interlacing - use pass (0 - 6) as index */
  192950. /* start of interlace block */
  192951. PNG_CONST int png_pass_start[7] = {0, 4, 0, 2, 0, 1, 0};
  192952. /* offset to next interlace block */
  192953. PNG_CONST int png_pass_inc[7] = {8, 8, 4, 4, 2, 2, 1};
  192954. /* start of interlace block in the y direction */
  192955. PNG_CONST int png_pass_ystart[7] = {0, 0, 4, 0, 2, 0, 1};
  192956. /* offset to next interlace block in the y direction */
  192957. PNG_CONST int png_pass_yinc[7] = {8, 8, 8, 4, 4, 2, 2};
  192958. #endif
  192959. png_debug(1, "in png_read_finish_row\n");
  192960. png_ptr->row_number++;
  192961. if (png_ptr->row_number < png_ptr->num_rows)
  192962. return;
  192963. if (png_ptr->interlaced)
  192964. {
  192965. png_ptr->row_number = 0;
  192966. png_memset_check(png_ptr, png_ptr->prev_row, 0,
  192967. png_ptr->rowbytes + 1);
  192968. do
  192969. {
  192970. png_ptr->pass++;
  192971. if (png_ptr->pass >= 7)
  192972. break;
  192973. png_ptr->iwidth = (png_ptr->width +
  192974. png_pass_inc[png_ptr->pass] - 1 -
  192975. png_pass_start[png_ptr->pass]) /
  192976. png_pass_inc[png_ptr->pass];
  192977. png_ptr->irowbytes = PNG_ROWBYTES(png_ptr->pixel_depth,
  192978. png_ptr->iwidth) + 1;
  192979. if (!(png_ptr->transformations & PNG_INTERLACE))
  192980. {
  192981. png_ptr->num_rows = (png_ptr->height +
  192982. png_pass_yinc[png_ptr->pass] - 1 -
  192983. png_pass_ystart[png_ptr->pass]) /
  192984. png_pass_yinc[png_ptr->pass];
  192985. if (!(png_ptr->num_rows))
  192986. continue;
  192987. }
  192988. else /* if (png_ptr->transformations & PNG_INTERLACE) */
  192989. break;
  192990. } while (png_ptr->iwidth == 0);
  192991. if (png_ptr->pass < 7)
  192992. return;
  192993. }
  192994. if (!(png_ptr->flags & PNG_FLAG_ZLIB_FINISHED))
  192995. {
  192996. #ifdef PNG_USE_LOCAL_ARRAYS
  192997. PNG_CONST PNG_IDAT;
  192998. #endif
  192999. char extra;
  193000. int ret;
  193001. png_ptr->zstream.next_out = (Bytef *)&extra;
  193002. png_ptr->zstream.avail_out = (uInt)1;
  193003. for(;;)
  193004. {
  193005. if (!(png_ptr->zstream.avail_in))
  193006. {
  193007. while (!png_ptr->idat_size)
  193008. {
  193009. png_byte chunk_length[4];
  193010. png_crc_finish(png_ptr, 0);
  193011. png_read_data(png_ptr, chunk_length, 4);
  193012. png_ptr->idat_size = png_get_uint_31(png_ptr, chunk_length);
  193013. png_reset_crc(png_ptr);
  193014. png_crc_read(png_ptr, png_ptr->chunk_name, 4);
  193015. if (png_memcmp(png_ptr->chunk_name, png_IDAT, 4))
  193016. png_error(png_ptr, "Not enough image data");
  193017. }
  193018. png_ptr->zstream.avail_in = (uInt)png_ptr->zbuf_size;
  193019. png_ptr->zstream.next_in = png_ptr->zbuf;
  193020. if (png_ptr->zbuf_size > png_ptr->idat_size)
  193021. png_ptr->zstream.avail_in = (uInt)png_ptr->idat_size;
  193022. png_crc_read(png_ptr, png_ptr->zbuf, png_ptr->zstream.avail_in);
  193023. png_ptr->idat_size -= png_ptr->zstream.avail_in;
  193024. }
  193025. ret = inflate(&png_ptr->zstream, Z_PARTIAL_FLUSH);
  193026. if (ret == Z_STREAM_END)
  193027. {
  193028. if (!(png_ptr->zstream.avail_out) || png_ptr->zstream.avail_in ||
  193029. png_ptr->idat_size)
  193030. png_warning(png_ptr, "Extra compressed data");
  193031. png_ptr->mode |= PNG_AFTER_IDAT;
  193032. png_ptr->flags |= PNG_FLAG_ZLIB_FINISHED;
  193033. break;
  193034. }
  193035. if (ret != Z_OK)
  193036. png_error(png_ptr, png_ptr->zstream.msg ? png_ptr->zstream.msg :
  193037. "Decompression Error");
  193038. if (!(png_ptr->zstream.avail_out))
  193039. {
  193040. png_warning(png_ptr, "Extra compressed data.");
  193041. png_ptr->mode |= PNG_AFTER_IDAT;
  193042. png_ptr->flags |= PNG_FLAG_ZLIB_FINISHED;
  193043. break;
  193044. }
  193045. }
  193046. png_ptr->zstream.avail_out = 0;
  193047. }
  193048. if (png_ptr->idat_size || png_ptr->zstream.avail_in)
  193049. png_warning(png_ptr, "Extra compression data");
  193050. inflateReset(&png_ptr->zstream);
  193051. png_ptr->mode |= PNG_AFTER_IDAT;
  193052. }
  193053. void /* PRIVATE */
  193054. png_read_start_row(png_structp png_ptr)
  193055. {
  193056. #ifdef PNG_USE_LOCAL_ARRAYS
  193057. /* arrays to facilitate easy interlacing - use pass (0 - 6) as index */
  193058. /* start of interlace block */
  193059. PNG_CONST int png_pass_start[7] = {0, 4, 0, 2, 0, 1, 0};
  193060. /* offset to next interlace block */
  193061. PNG_CONST int png_pass_inc[7] = {8, 8, 4, 4, 2, 2, 1};
  193062. /* start of interlace block in the y direction */
  193063. PNG_CONST int png_pass_ystart[7] = {0, 0, 4, 0, 2, 0, 1};
  193064. /* offset to next interlace block in the y direction */
  193065. PNG_CONST int png_pass_yinc[7] = {8, 8, 8, 4, 4, 2, 2};
  193066. #endif
  193067. int max_pixel_depth;
  193068. png_uint_32 row_bytes;
  193069. png_debug(1, "in png_read_start_row\n");
  193070. png_ptr->zstream.avail_in = 0;
  193071. png_init_read_transformations(png_ptr);
  193072. if (png_ptr->interlaced)
  193073. {
  193074. if (!(png_ptr->transformations & PNG_INTERLACE))
  193075. png_ptr->num_rows = (png_ptr->height + png_pass_yinc[0] - 1 -
  193076. png_pass_ystart[0]) / png_pass_yinc[0];
  193077. else
  193078. png_ptr->num_rows = png_ptr->height;
  193079. png_ptr->iwidth = (png_ptr->width +
  193080. png_pass_inc[png_ptr->pass] - 1 -
  193081. png_pass_start[png_ptr->pass]) /
  193082. png_pass_inc[png_ptr->pass];
  193083. row_bytes = PNG_ROWBYTES(png_ptr->pixel_depth,png_ptr->iwidth) + 1;
  193084. png_ptr->irowbytes = (png_size_t)row_bytes;
  193085. if((png_uint_32)png_ptr->irowbytes != row_bytes)
  193086. png_error(png_ptr, "Rowbytes overflow in png_read_start_row");
  193087. }
  193088. else
  193089. {
  193090. png_ptr->num_rows = png_ptr->height;
  193091. png_ptr->iwidth = png_ptr->width;
  193092. png_ptr->irowbytes = png_ptr->rowbytes + 1;
  193093. }
  193094. max_pixel_depth = png_ptr->pixel_depth;
  193095. #if defined(PNG_READ_PACK_SUPPORTED)
  193096. if ((png_ptr->transformations & PNG_PACK) && png_ptr->bit_depth < 8)
  193097. max_pixel_depth = 8;
  193098. #endif
  193099. #if defined(PNG_READ_EXPAND_SUPPORTED)
  193100. if (png_ptr->transformations & PNG_EXPAND)
  193101. {
  193102. if (png_ptr->color_type == PNG_COLOR_TYPE_PALETTE)
  193103. {
  193104. if (png_ptr->num_trans)
  193105. max_pixel_depth = 32;
  193106. else
  193107. max_pixel_depth = 24;
  193108. }
  193109. else if (png_ptr->color_type == PNG_COLOR_TYPE_GRAY)
  193110. {
  193111. if (max_pixel_depth < 8)
  193112. max_pixel_depth = 8;
  193113. if (png_ptr->num_trans)
  193114. max_pixel_depth *= 2;
  193115. }
  193116. else if (png_ptr->color_type == PNG_COLOR_TYPE_RGB)
  193117. {
  193118. if (png_ptr->num_trans)
  193119. {
  193120. max_pixel_depth *= 4;
  193121. max_pixel_depth /= 3;
  193122. }
  193123. }
  193124. }
  193125. #endif
  193126. #if defined(PNG_READ_FILLER_SUPPORTED)
  193127. if (png_ptr->transformations & (PNG_FILLER))
  193128. {
  193129. if (png_ptr->color_type == PNG_COLOR_TYPE_PALETTE)
  193130. max_pixel_depth = 32;
  193131. else if (png_ptr->color_type == PNG_COLOR_TYPE_GRAY)
  193132. {
  193133. if (max_pixel_depth <= 8)
  193134. max_pixel_depth = 16;
  193135. else
  193136. max_pixel_depth = 32;
  193137. }
  193138. else if (png_ptr->color_type == PNG_COLOR_TYPE_RGB)
  193139. {
  193140. if (max_pixel_depth <= 32)
  193141. max_pixel_depth = 32;
  193142. else
  193143. max_pixel_depth = 64;
  193144. }
  193145. }
  193146. #endif
  193147. #if defined(PNG_READ_GRAY_TO_RGB_SUPPORTED)
  193148. if (png_ptr->transformations & PNG_GRAY_TO_RGB)
  193149. {
  193150. if (
  193151. #if defined(PNG_READ_EXPAND_SUPPORTED)
  193152. (png_ptr->num_trans && (png_ptr->transformations & PNG_EXPAND)) ||
  193153. #endif
  193154. #if defined(PNG_READ_FILLER_SUPPORTED)
  193155. (png_ptr->transformations & (PNG_FILLER)) ||
  193156. #endif
  193157. png_ptr->color_type == PNG_COLOR_TYPE_GRAY_ALPHA)
  193158. {
  193159. if (max_pixel_depth <= 16)
  193160. max_pixel_depth = 32;
  193161. else
  193162. max_pixel_depth = 64;
  193163. }
  193164. else
  193165. {
  193166. if (max_pixel_depth <= 8)
  193167. {
  193168. if (png_ptr->color_type == PNG_COLOR_TYPE_RGB_ALPHA)
  193169. max_pixel_depth = 32;
  193170. else
  193171. max_pixel_depth = 24;
  193172. }
  193173. else if (png_ptr->color_type == PNG_COLOR_TYPE_RGB_ALPHA)
  193174. max_pixel_depth = 64;
  193175. else
  193176. max_pixel_depth = 48;
  193177. }
  193178. }
  193179. #endif
  193180. #if defined(PNG_READ_USER_TRANSFORM_SUPPORTED) && \
  193181. defined(PNG_USER_TRANSFORM_PTR_SUPPORTED)
  193182. if(png_ptr->transformations & PNG_USER_TRANSFORM)
  193183. {
  193184. int user_pixel_depth=png_ptr->user_transform_depth*
  193185. png_ptr->user_transform_channels;
  193186. if(user_pixel_depth > max_pixel_depth)
  193187. max_pixel_depth=user_pixel_depth;
  193188. }
  193189. #endif
  193190. /* align the width on the next larger 8 pixels. Mainly used
  193191. for interlacing */
  193192. row_bytes = ((png_ptr->width + 7) & ~((png_uint_32)7));
  193193. /* calculate the maximum bytes needed, adding a byte and a pixel
  193194. for safety's sake */
  193195. row_bytes = PNG_ROWBYTES(max_pixel_depth,row_bytes) +
  193196. 1 + ((max_pixel_depth + 7) >> 3);
  193197. #ifdef PNG_MAX_MALLOC_64K
  193198. if (row_bytes > (png_uint_32)65536L)
  193199. png_error(png_ptr, "This image requires a row greater than 64KB");
  193200. #endif
  193201. png_ptr->big_row_buf = (png_bytep)png_malloc(png_ptr, row_bytes+64);
  193202. png_ptr->row_buf = png_ptr->big_row_buf+32;
  193203. #ifdef PNG_MAX_MALLOC_64K
  193204. if ((png_uint_32)png_ptr->rowbytes + 1 > (png_uint_32)65536L)
  193205. png_error(png_ptr, "This image requires a row greater than 64KB");
  193206. #endif
  193207. if ((png_uint_32)png_ptr->rowbytes > (png_uint_32)(PNG_SIZE_MAX - 1))
  193208. png_error(png_ptr, "Row has too many bytes to allocate in memory.");
  193209. png_ptr->prev_row = (png_bytep)png_malloc(png_ptr, (png_uint_32)(
  193210. png_ptr->rowbytes + 1));
  193211. png_memset_check(png_ptr, png_ptr->prev_row, 0, png_ptr->rowbytes + 1);
  193212. png_debug1(3, "width = %lu,\n", png_ptr->width);
  193213. png_debug1(3, "height = %lu,\n", png_ptr->height);
  193214. png_debug1(3, "iwidth = %lu,\n", png_ptr->iwidth);
  193215. png_debug1(3, "num_rows = %lu\n", png_ptr->num_rows);
  193216. png_debug1(3, "rowbytes = %lu,\n", png_ptr->rowbytes);
  193217. png_debug1(3, "irowbytes = %lu,\n", png_ptr->irowbytes);
  193218. png_ptr->flags |= PNG_FLAG_ROW_INIT;
  193219. }
  193220. #endif /* PNG_READ_SUPPORTED */
  193221. /*** End of inlined file: pngrutil.c ***/
  193222. /*** Start of inlined file: pngset.c ***/
  193223. /* pngset.c - storage of image information into info struct
  193224. *
  193225. * Last changed in libpng 1.2.21 [October 4, 2007]
  193226. * For conditions of distribution and use, see copyright notice in png.h
  193227. * Copyright (c) 1998-2007 Glenn Randers-Pehrson
  193228. * (Version 0.96 Copyright (c) 1996, 1997 Andreas Dilger)
  193229. * (Version 0.88 Copyright (c) 1995, 1996 Guy Eric Schalnat, Group 42, Inc.)
  193230. *
  193231. * The functions here are used during reads to store data from the file
  193232. * into the info struct, and during writes to store application data
  193233. * into the info struct for writing into the file. This abstracts the
  193234. * info struct and allows us to change the structure in the future.
  193235. */
  193236. #define PNG_INTERNAL
  193237. #if defined(PNG_READ_SUPPORTED) || defined(PNG_WRITE_SUPPORTED)
  193238. #if defined(PNG_bKGD_SUPPORTED)
  193239. void PNGAPI
  193240. png_set_bKGD(png_structp png_ptr, png_infop info_ptr, png_color_16p background)
  193241. {
  193242. png_debug1(1, "in %s storage function\n", "bKGD");
  193243. if (png_ptr == NULL || info_ptr == NULL)
  193244. return;
  193245. png_memcpy(&(info_ptr->background), background, png_sizeof(png_color_16));
  193246. info_ptr->valid |= PNG_INFO_bKGD;
  193247. }
  193248. #endif
  193249. #if defined(PNG_cHRM_SUPPORTED)
  193250. #ifdef PNG_FLOATING_POINT_SUPPORTED
  193251. void PNGAPI
  193252. png_set_cHRM(png_structp png_ptr, png_infop info_ptr,
  193253. double white_x, double white_y, double red_x, double red_y,
  193254. double green_x, double green_y, double blue_x, double blue_y)
  193255. {
  193256. png_debug1(1, "in %s storage function\n", "cHRM");
  193257. if (png_ptr == NULL || info_ptr == NULL)
  193258. return;
  193259. if (white_x < 0.0 || white_y < 0.0 ||
  193260. red_x < 0.0 || red_y < 0.0 ||
  193261. green_x < 0.0 || green_y < 0.0 ||
  193262. blue_x < 0.0 || blue_y < 0.0)
  193263. {
  193264. png_warning(png_ptr,
  193265. "Ignoring attempt to set negative chromaticity value");
  193266. return;
  193267. }
  193268. if (white_x > 21474.83 || white_y > 21474.83 ||
  193269. red_x > 21474.83 || red_y > 21474.83 ||
  193270. green_x > 21474.83 || green_y > 21474.83 ||
  193271. blue_x > 21474.83 || blue_y > 21474.83)
  193272. {
  193273. png_warning(png_ptr,
  193274. "Ignoring attempt to set chromaticity value exceeding 21474.83");
  193275. return;
  193276. }
  193277. info_ptr->x_white = (float)white_x;
  193278. info_ptr->y_white = (float)white_y;
  193279. info_ptr->x_red = (float)red_x;
  193280. info_ptr->y_red = (float)red_y;
  193281. info_ptr->x_green = (float)green_x;
  193282. info_ptr->y_green = (float)green_y;
  193283. info_ptr->x_blue = (float)blue_x;
  193284. info_ptr->y_blue = (float)blue_y;
  193285. #ifdef PNG_FIXED_POINT_SUPPORTED
  193286. info_ptr->int_x_white = (png_fixed_point)(white_x*100000.+0.5);
  193287. info_ptr->int_y_white = (png_fixed_point)(white_y*100000.+0.5);
  193288. info_ptr->int_x_red = (png_fixed_point)( red_x*100000.+0.5);
  193289. info_ptr->int_y_red = (png_fixed_point)( red_y*100000.+0.5);
  193290. info_ptr->int_x_green = (png_fixed_point)(green_x*100000.+0.5);
  193291. info_ptr->int_y_green = (png_fixed_point)(green_y*100000.+0.5);
  193292. info_ptr->int_x_blue = (png_fixed_point)( blue_x*100000.+0.5);
  193293. info_ptr->int_y_blue = (png_fixed_point)( blue_y*100000.+0.5);
  193294. #endif
  193295. info_ptr->valid |= PNG_INFO_cHRM;
  193296. }
  193297. #endif
  193298. #ifdef PNG_FIXED_POINT_SUPPORTED
  193299. void PNGAPI
  193300. png_set_cHRM_fixed(png_structp png_ptr, png_infop info_ptr,
  193301. png_fixed_point white_x, png_fixed_point white_y, png_fixed_point red_x,
  193302. png_fixed_point red_y, png_fixed_point green_x, png_fixed_point green_y,
  193303. png_fixed_point blue_x, png_fixed_point blue_y)
  193304. {
  193305. png_debug1(1, "in %s storage function\n", "cHRM");
  193306. if (png_ptr == NULL || info_ptr == NULL)
  193307. return;
  193308. if (white_x < 0 || white_y < 0 ||
  193309. red_x < 0 || red_y < 0 ||
  193310. green_x < 0 || green_y < 0 ||
  193311. blue_x < 0 || blue_y < 0)
  193312. {
  193313. png_warning(png_ptr,
  193314. "Ignoring attempt to set negative chromaticity value");
  193315. return;
  193316. }
  193317. #ifdef PNG_FLOATING_POINT_SUPPORTED
  193318. if (white_x > (double) PNG_UINT_31_MAX ||
  193319. white_y > (double) PNG_UINT_31_MAX ||
  193320. red_x > (double) PNG_UINT_31_MAX ||
  193321. red_y > (double) PNG_UINT_31_MAX ||
  193322. green_x > (double) PNG_UINT_31_MAX ||
  193323. green_y > (double) PNG_UINT_31_MAX ||
  193324. blue_x > (double) PNG_UINT_31_MAX ||
  193325. blue_y > (double) PNG_UINT_31_MAX)
  193326. #else
  193327. if (white_x > (png_fixed_point) PNG_UINT_31_MAX/100000L ||
  193328. white_y > (png_fixed_point) PNG_UINT_31_MAX/100000L ||
  193329. red_x > (png_fixed_point) PNG_UINT_31_MAX/100000L ||
  193330. red_y > (png_fixed_point) PNG_UINT_31_MAX/100000L ||
  193331. green_x > (png_fixed_point) PNG_UINT_31_MAX/100000L ||
  193332. green_y > (png_fixed_point) PNG_UINT_31_MAX/100000L ||
  193333. blue_x > (png_fixed_point) PNG_UINT_31_MAX/100000L ||
  193334. blue_y > (png_fixed_point) PNG_UINT_31_MAX/100000L)
  193335. #endif
  193336. {
  193337. png_warning(png_ptr,
  193338. "Ignoring attempt to set chromaticity value exceeding 21474.83");
  193339. return;
  193340. }
  193341. info_ptr->int_x_white = white_x;
  193342. info_ptr->int_y_white = white_y;
  193343. info_ptr->int_x_red = red_x;
  193344. info_ptr->int_y_red = red_y;
  193345. info_ptr->int_x_green = green_x;
  193346. info_ptr->int_y_green = green_y;
  193347. info_ptr->int_x_blue = blue_x;
  193348. info_ptr->int_y_blue = blue_y;
  193349. #ifdef PNG_FLOATING_POINT_SUPPORTED
  193350. info_ptr->x_white = (float)(white_x/100000.);
  193351. info_ptr->y_white = (float)(white_y/100000.);
  193352. info_ptr->x_red = (float)( red_x/100000.);
  193353. info_ptr->y_red = (float)( red_y/100000.);
  193354. info_ptr->x_green = (float)(green_x/100000.);
  193355. info_ptr->y_green = (float)(green_y/100000.);
  193356. info_ptr->x_blue = (float)( blue_x/100000.);
  193357. info_ptr->y_blue = (float)( blue_y/100000.);
  193358. #endif
  193359. info_ptr->valid |= PNG_INFO_cHRM;
  193360. }
  193361. #endif
  193362. #endif
  193363. #if defined(PNG_gAMA_SUPPORTED)
  193364. #ifdef PNG_FLOATING_POINT_SUPPORTED
  193365. void PNGAPI
  193366. png_set_gAMA(png_structp png_ptr, png_infop info_ptr, double file_gamma)
  193367. {
  193368. double gamma;
  193369. png_debug1(1, "in %s storage function\n", "gAMA");
  193370. if (png_ptr == NULL || info_ptr == NULL)
  193371. return;
  193372. /* Check for overflow */
  193373. if (file_gamma > 21474.83)
  193374. {
  193375. png_warning(png_ptr, "Limiting gamma to 21474.83");
  193376. gamma=21474.83;
  193377. }
  193378. else
  193379. gamma=file_gamma;
  193380. info_ptr->gamma = (float)gamma;
  193381. #ifdef PNG_FIXED_POINT_SUPPORTED
  193382. info_ptr->int_gamma = (int)(gamma*100000.+.5);
  193383. #endif
  193384. info_ptr->valid |= PNG_INFO_gAMA;
  193385. if(gamma == 0.0)
  193386. png_warning(png_ptr, "Setting gamma=0");
  193387. }
  193388. #endif
  193389. void PNGAPI
  193390. png_set_gAMA_fixed(png_structp png_ptr, png_infop info_ptr, png_fixed_point
  193391. int_gamma)
  193392. {
  193393. png_fixed_point gamma;
  193394. png_debug1(1, "in %s storage function\n", "gAMA");
  193395. if (png_ptr == NULL || info_ptr == NULL)
  193396. return;
  193397. if (int_gamma > (png_fixed_point) PNG_UINT_31_MAX)
  193398. {
  193399. png_warning(png_ptr, "Limiting gamma to 21474.83");
  193400. gamma=PNG_UINT_31_MAX;
  193401. }
  193402. else
  193403. {
  193404. if (int_gamma < 0)
  193405. {
  193406. png_warning(png_ptr, "Setting negative gamma to zero");
  193407. gamma=0;
  193408. }
  193409. else
  193410. gamma=int_gamma;
  193411. }
  193412. #ifdef PNG_FLOATING_POINT_SUPPORTED
  193413. info_ptr->gamma = (float)(gamma/100000.);
  193414. #endif
  193415. #ifdef PNG_FIXED_POINT_SUPPORTED
  193416. info_ptr->int_gamma = gamma;
  193417. #endif
  193418. info_ptr->valid |= PNG_INFO_gAMA;
  193419. if(gamma == 0)
  193420. png_warning(png_ptr, "Setting gamma=0");
  193421. }
  193422. #endif
  193423. #if defined(PNG_hIST_SUPPORTED)
  193424. void PNGAPI
  193425. png_set_hIST(png_structp png_ptr, png_infop info_ptr, png_uint_16p hist)
  193426. {
  193427. int i;
  193428. png_debug1(1, "in %s storage function\n", "hIST");
  193429. if (png_ptr == NULL || info_ptr == NULL)
  193430. return;
  193431. if (info_ptr->num_palette == 0 || info_ptr->num_palette
  193432. > PNG_MAX_PALETTE_LENGTH)
  193433. {
  193434. png_warning(png_ptr,
  193435. "Invalid palette size, hIST allocation skipped.");
  193436. return;
  193437. }
  193438. #ifdef PNG_FREE_ME_SUPPORTED
  193439. png_free_data(png_ptr, info_ptr, PNG_FREE_HIST, 0);
  193440. #endif
  193441. /* Changed from info->num_palette to PNG_MAX_PALETTE_LENGTH in version
  193442. 1.2.1 */
  193443. png_ptr->hist = (png_uint_16p)png_malloc_warn(png_ptr,
  193444. (png_uint_32)(PNG_MAX_PALETTE_LENGTH * png_sizeof (png_uint_16)));
  193445. if (png_ptr->hist == NULL)
  193446. {
  193447. png_warning(png_ptr, "Insufficient memory for hIST chunk data.");
  193448. return;
  193449. }
  193450. for (i = 0; i < info_ptr->num_palette; i++)
  193451. png_ptr->hist[i] = hist[i];
  193452. info_ptr->hist = png_ptr->hist;
  193453. info_ptr->valid |= PNG_INFO_hIST;
  193454. #ifdef PNG_FREE_ME_SUPPORTED
  193455. info_ptr->free_me |= PNG_FREE_HIST;
  193456. #else
  193457. png_ptr->flags |= PNG_FLAG_FREE_HIST;
  193458. #endif
  193459. }
  193460. #endif
  193461. void PNGAPI
  193462. png_set_IHDR(png_structp png_ptr, png_infop info_ptr,
  193463. png_uint_32 width, png_uint_32 height, int bit_depth,
  193464. int color_type, int interlace_type, int compression_type,
  193465. int filter_type)
  193466. {
  193467. png_debug1(1, "in %s storage function\n", "IHDR");
  193468. if (png_ptr == NULL || info_ptr == NULL)
  193469. return;
  193470. /* check for width and height valid values */
  193471. if (width == 0 || height == 0)
  193472. png_error(png_ptr, "Image width or height is zero in IHDR");
  193473. #ifdef PNG_SET_USER_LIMITS_SUPPORTED
  193474. if (width > png_ptr->user_width_max || height > png_ptr->user_height_max)
  193475. png_error(png_ptr, "image size exceeds user limits in IHDR");
  193476. #else
  193477. if (width > PNG_USER_WIDTH_MAX || height > PNG_USER_HEIGHT_MAX)
  193478. png_error(png_ptr, "image size exceeds user limits in IHDR");
  193479. #endif
  193480. if (width > PNG_UINT_31_MAX || height > PNG_UINT_31_MAX)
  193481. png_error(png_ptr, "Invalid image size in IHDR");
  193482. if ( width > (PNG_UINT_32_MAX
  193483. >> 3) /* 8-byte RGBA pixels */
  193484. - 64 /* bigrowbuf hack */
  193485. - 1 /* filter byte */
  193486. - 7*8 /* rounding of width to multiple of 8 pixels */
  193487. - 8) /* extra max_pixel_depth pad */
  193488. png_warning(png_ptr, "Width is too large for libpng to process pixels");
  193489. /* check other values */
  193490. if (bit_depth != 1 && bit_depth != 2 && bit_depth != 4 &&
  193491. bit_depth != 8 && bit_depth != 16)
  193492. png_error(png_ptr, "Invalid bit depth in IHDR");
  193493. if (color_type < 0 || color_type == 1 ||
  193494. color_type == 5 || color_type > 6)
  193495. png_error(png_ptr, "Invalid color type in IHDR");
  193496. if (((color_type == PNG_COLOR_TYPE_PALETTE) && bit_depth > 8) ||
  193497. ((color_type == PNG_COLOR_TYPE_RGB ||
  193498. color_type == PNG_COLOR_TYPE_GRAY_ALPHA ||
  193499. color_type == PNG_COLOR_TYPE_RGB_ALPHA) && bit_depth < 8))
  193500. png_error(png_ptr, "Invalid color type/bit depth combination in IHDR");
  193501. if (interlace_type >= PNG_INTERLACE_LAST)
  193502. png_error(png_ptr, "Unknown interlace method in IHDR");
  193503. if (compression_type != PNG_COMPRESSION_TYPE_BASE)
  193504. png_error(png_ptr, "Unknown compression method in IHDR");
  193505. #if defined(PNG_MNG_FEATURES_SUPPORTED)
  193506. /* Accept filter_method 64 (intrapixel differencing) only if
  193507. * 1. Libpng was compiled with PNG_MNG_FEATURES_SUPPORTED and
  193508. * 2. Libpng did not read a PNG signature (this filter_method is only
  193509. * used in PNG datastreams that are embedded in MNG datastreams) and
  193510. * 3. The application called png_permit_mng_features with a mask that
  193511. * included PNG_FLAG_MNG_FILTER_64 and
  193512. * 4. The filter_method is 64 and
  193513. * 5. The color_type is RGB or RGBA
  193514. */
  193515. if((png_ptr->mode&PNG_HAVE_PNG_SIGNATURE)&&png_ptr->mng_features_permitted)
  193516. png_warning(png_ptr,"MNG features are not allowed in a PNG datastream");
  193517. if(filter_type != PNG_FILTER_TYPE_BASE)
  193518. {
  193519. if(!((png_ptr->mng_features_permitted & PNG_FLAG_MNG_FILTER_64) &&
  193520. (filter_type == PNG_INTRAPIXEL_DIFFERENCING) &&
  193521. ((png_ptr->mode&PNG_HAVE_PNG_SIGNATURE) == 0) &&
  193522. (color_type == PNG_COLOR_TYPE_RGB ||
  193523. color_type == PNG_COLOR_TYPE_RGB_ALPHA)))
  193524. png_error(png_ptr, "Unknown filter method in IHDR");
  193525. if(png_ptr->mode&PNG_HAVE_PNG_SIGNATURE)
  193526. png_warning(png_ptr, "Invalid filter method in IHDR");
  193527. }
  193528. #else
  193529. if(filter_type != PNG_FILTER_TYPE_BASE)
  193530. png_error(png_ptr, "Unknown filter method in IHDR");
  193531. #endif
  193532. info_ptr->width = width;
  193533. info_ptr->height = height;
  193534. info_ptr->bit_depth = (png_byte)bit_depth;
  193535. info_ptr->color_type =(png_byte) color_type;
  193536. info_ptr->compression_type = (png_byte)compression_type;
  193537. info_ptr->filter_type = (png_byte)filter_type;
  193538. info_ptr->interlace_type = (png_byte)interlace_type;
  193539. if (info_ptr->color_type == PNG_COLOR_TYPE_PALETTE)
  193540. info_ptr->channels = 1;
  193541. else if (info_ptr->color_type & PNG_COLOR_MASK_COLOR)
  193542. info_ptr->channels = 3;
  193543. else
  193544. info_ptr->channels = 1;
  193545. if (info_ptr->color_type & PNG_COLOR_MASK_ALPHA)
  193546. info_ptr->channels++;
  193547. info_ptr->pixel_depth = (png_byte)(info_ptr->channels * info_ptr->bit_depth);
  193548. /* check for potential overflow */
  193549. if (width > (PNG_UINT_32_MAX
  193550. >> 3) /* 8-byte RGBA pixels */
  193551. - 64 /* bigrowbuf hack */
  193552. - 1 /* filter byte */
  193553. - 7*8 /* rounding of width to multiple of 8 pixels */
  193554. - 8) /* extra max_pixel_depth pad */
  193555. info_ptr->rowbytes = (png_size_t)0;
  193556. else
  193557. info_ptr->rowbytes = PNG_ROWBYTES(info_ptr->pixel_depth,width);
  193558. }
  193559. #if defined(PNG_oFFs_SUPPORTED)
  193560. void PNGAPI
  193561. png_set_oFFs(png_structp png_ptr, png_infop info_ptr,
  193562. png_int_32 offset_x, png_int_32 offset_y, int unit_type)
  193563. {
  193564. png_debug1(1, "in %s storage function\n", "oFFs");
  193565. if (png_ptr == NULL || info_ptr == NULL)
  193566. return;
  193567. info_ptr->x_offset = offset_x;
  193568. info_ptr->y_offset = offset_y;
  193569. info_ptr->offset_unit_type = (png_byte)unit_type;
  193570. info_ptr->valid |= PNG_INFO_oFFs;
  193571. }
  193572. #endif
  193573. #if defined(PNG_pCAL_SUPPORTED)
  193574. void PNGAPI
  193575. png_set_pCAL(png_structp png_ptr, png_infop info_ptr,
  193576. png_charp purpose, png_int_32 X0, png_int_32 X1, int type, int nparams,
  193577. png_charp units, png_charpp params)
  193578. {
  193579. png_uint_32 length;
  193580. int i;
  193581. png_debug1(1, "in %s storage function\n", "pCAL");
  193582. if (png_ptr == NULL || info_ptr == NULL)
  193583. return;
  193584. length = png_strlen(purpose) + 1;
  193585. png_debug1(3, "allocating purpose for info (%lu bytes)\n", length);
  193586. info_ptr->pcal_purpose = (png_charp)png_malloc_warn(png_ptr, length);
  193587. if (info_ptr->pcal_purpose == NULL)
  193588. {
  193589. png_warning(png_ptr, "Insufficient memory for pCAL purpose.");
  193590. return;
  193591. }
  193592. png_memcpy(info_ptr->pcal_purpose, purpose, (png_size_t)length);
  193593. png_debug(3, "storing X0, X1, type, and nparams in info\n");
  193594. info_ptr->pcal_X0 = X0;
  193595. info_ptr->pcal_X1 = X1;
  193596. info_ptr->pcal_type = (png_byte)type;
  193597. info_ptr->pcal_nparams = (png_byte)nparams;
  193598. length = png_strlen(units) + 1;
  193599. png_debug1(3, "allocating units for info (%lu bytes)\n", length);
  193600. info_ptr->pcal_units = (png_charp)png_malloc_warn(png_ptr, length);
  193601. if (info_ptr->pcal_units == NULL)
  193602. {
  193603. png_warning(png_ptr, "Insufficient memory for pCAL units.");
  193604. return;
  193605. }
  193606. png_memcpy(info_ptr->pcal_units, units, (png_size_t)length);
  193607. info_ptr->pcal_params = (png_charpp)png_malloc_warn(png_ptr,
  193608. (png_uint_32)((nparams + 1) * png_sizeof(png_charp)));
  193609. if (info_ptr->pcal_params == NULL)
  193610. {
  193611. png_warning(png_ptr, "Insufficient memory for pCAL params.");
  193612. return;
  193613. }
  193614. info_ptr->pcal_params[nparams] = NULL;
  193615. for (i = 0; i < nparams; i++)
  193616. {
  193617. length = png_strlen(params[i]) + 1;
  193618. png_debug2(3, "allocating parameter %d for info (%lu bytes)\n", i, length);
  193619. info_ptr->pcal_params[i] = (png_charp)png_malloc_warn(png_ptr, length);
  193620. if (info_ptr->pcal_params[i] == NULL)
  193621. {
  193622. png_warning(png_ptr, "Insufficient memory for pCAL parameter.");
  193623. return;
  193624. }
  193625. png_memcpy(info_ptr->pcal_params[i], params[i], (png_size_t)length);
  193626. }
  193627. info_ptr->valid |= PNG_INFO_pCAL;
  193628. #ifdef PNG_FREE_ME_SUPPORTED
  193629. info_ptr->free_me |= PNG_FREE_PCAL;
  193630. #endif
  193631. }
  193632. #endif
  193633. #if defined(PNG_READ_sCAL_SUPPORTED) || defined(PNG_WRITE_sCAL_SUPPORTED)
  193634. #ifdef PNG_FLOATING_POINT_SUPPORTED
  193635. void PNGAPI
  193636. png_set_sCAL(png_structp png_ptr, png_infop info_ptr,
  193637. int unit, double width, double height)
  193638. {
  193639. png_debug1(1, "in %s storage function\n", "sCAL");
  193640. if (png_ptr == NULL || info_ptr == NULL)
  193641. return;
  193642. info_ptr->scal_unit = (png_byte)unit;
  193643. info_ptr->scal_pixel_width = width;
  193644. info_ptr->scal_pixel_height = height;
  193645. info_ptr->valid |= PNG_INFO_sCAL;
  193646. }
  193647. #else
  193648. #ifdef PNG_FIXED_POINT_SUPPORTED
  193649. void PNGAPI
  193650. png_set_sCAL_s(png_structp png_ptr, png_infop info_ptr,
  193651. int unit, png_charp swidth, png_charp sheight)
  193652. {
  193653. png_uint_32 length;
  193654. png_debug1(1, "in %s storage function\n", "sCAL");
  193655. if (png_ptr == NULL || info_ptr == NULL)
  193656. return;
  193657. info_ptr->scal_unit = (png_byte)unit;
  193658. length = png_strlen(swidth) + 1;
  193659. png_debug1(3, "allocating unit for info (%d bytes)\n", length);
  193660. info_ptr->scal_s_width = (png_charp)png_malloc_warn(png_ptr, length);
  193661. if (info_ptr->scal_s_width == NULL)
  193662. {
  193663. png_warning(png_ptr,
  193664. "Memory allocation failed while processing sCAL.");
  193665. }
  193666. png_memcpy(info_ptr->scal_s_width, swidth, (png_size_t)length);
  193667. length = png_strlen(sheight) + 1;
  193668. png_debug1(3, "allocating unit for info (%d bytes)\n", length);
  193669. info_ptr->scal_s_height = (png_charp)png_malloc_warn(png_ptr, length);
  193670. if (info_ptr->scal_s_height == NULL)
  193671. {
  193672. png_free (png_ptr, info_ptr->scal_s_width);
  193673. png_warning(png_ptr,
  193674. "Memory allocation failed while processing sCAL.");
  193675. }
  193676. png_memcpy(info_ptr->scal_s_height, sheight, (png_size_t)length);
  193677. info_ptr->valid |= PNG_INFO_sCAL;
  193678. #ifdef PNG_FREE_ME_SUPPORTED
  193679. info_ptr->free_me |= PNG_FREE_SCAL;
  193680. #endif
  193681. }
  193682. #endif
  193683. #endif
  193684. #endif
  193685. #if defined(PNG_pHYs_SUPPORTED)
  193686. void PNGAPI
  193687. png_set_pHYs(png_structp png_ptr, png_infop info_ptr,
  193688. png_uint_32 res_x, png_uint_32 res_y, int unit_type)
  193689. {
  193690. png_debug1(1, "in %s storage function\n", "pHYs");
  193691. if (png_ptr == NULL || info_ptr == NULL)
  193692. return;
  193693. info_ptr->x_pixels_per_unit = res_x;
  193694. info_ptr->y_pixels_per_unit = res_y;
  193695. info_ptr->phys_unit_type = (png_byte)unit_type;
  193696. info_ptr->valid |= PNG_INFO_pHYs;
  193697. }
  193698. #endif
  193699. void PNGAPI
  193700. png_set_PLTE(png_structp png_ptr, png_infop info_ptr,
  193701. png_colorp palette, int num_palette)
  193702. {
  193703. png_debug1(1, "in %s storage function\n", "PLTE");
  193704. if (png_ptr == NULL || info_ptr == NULL)
  193705. return;
  193706. if (num_palette < 0 || num_palette > PNG_MAX_PALETTE_LENGTH)
  193707. {
  193708. if (info_ptr->color_type == PNG_COLOR_TYPE_PALETTE)
  193709. png_error(png_ptr, "Invalid palette length");
  193710. else
  193711. {
  193712. png_warning(png_ptr, "Invalid palette length");
  193713. return;
  193714. }
  193715. }
  193716. /*
  193717. * It may not actually be necessary to set png_ptr->palette here;
  193718. * we do it for backward compatibility with the way the png_handle_tRNS
  193719. * function used to do the allocation.
  193720. */
  193721. #ifdef PNG_FREE_ME_SUPPORTED
  193722. png_free_data(png_ptr, info_ptr, PNG_FREE_PLTE, 0);
  193723. #endif
  193724. /* Changed in libpng-1.2.1 to allocate PNG_MAX_PALETTE_LENGTH instead
  193725. of num_palette entries,
  193726. in case of an invalid PNG file that has too-large sample values. */
  193727. png_ptr->palette = (png_colorp)png_malloc(png_ptr,
  193728. PNG_MAX_PALETTE_LENGTH * png_sizeof(png_color));
  193729. png_memset(png_ptr->palette, 0, PNG_MAX_PALETTE_LENGTH *
  193730. png_sizeof(png_color));
  193731. png_memcpy(png_ptr->palette, palette, num_palette * png_sizeof (png_color));
  193732. info_ptr->palette = png_ptr->palette;
  193733. info_ptr->num_palette = png_ptr->num_palette = (png_uint_16)num_palette;
  193734. #ifdef PNG_FREE_ME_SUPPORTED
  193735. info_ptr->free_me |= PNG_FREE_PLTE;
  193736. #else
  193737. png_ptr->flags |= PNG_FLAG_FREE_PLTE;
  193738. #endif
  193739. info_ptr->valid |= PNG_INFO_PLTE;
  193740. }
  193741. #if defined(PNG_sBIT_SUPPORTED)
  193742. void PNGAPI
  193743. png_set_sBIT(png_structp png_ptr, png_infop info_ptr,
  193744. png_color_8p sig_bit)
  193745. {
  193746. png_debug1(1, "in %s storage function\n", "sBIT");
  193747. if (png_ptr == NULL || info_ptr == NULL)
  193748. return;
  193749. png_memcpy(&(info_ptr->sig_bit), sig_bit, png_sizeof (png_color_8));
  193750. info_ptr->valid |= PNG_INFO_sBIT;
  193751. }
  193752. #endif
  193753. #if defined(PNG_sRGB_SUPPORTED)
  193754. void PNGAPI
  193755. png_set_sRGB(png_structp png_ptr, png_infop info_ptr, int intent)
  193756. {
  193757. png_debug1(1, "in %s storage function\n", "sRGB");
  193758. if (png_ptr == NULL || info_ptr == NULL)
  193759. return;
  193760. info_ptr->srgb_intent = (png_byte)intent;
  193761. info_ptr->valid |= PNG_INFO_sRGB;
  193762. }
  193763. void PNGAPI
  193764. png_set_sRGB_gAMA_and_cHRM(png_structp png_ptr, png_infop info_ptr,
  193765. int intent)
  193766. {
  193767. #if defined(PNG_gAMA_SUPPORTED)
  193768. #ifdef PNG_FLOATING_POINT_SUPPORTED
  193769. float file_gamma;
  193770. #endif
  193771. #ifdef PNG_FIXED_POINT_SUPPORTED
  193772. png_fixed_point int_file_gamma;
  193773. #endif
  193774. #endif
  193775. #if defined(PNG_cHRM_SUPPORTED)
  193776. #ifdef PNG_FLOATING_POINT_SUPPORTED
  193777. float white_x, white_y, red_x, red_y, green_x, green_y, blue_x, blue_y;
  193778. #endif
  193779. #ifdef PNG_FIXED_POINT_SUPPORTED
  193780. png_fixed_point int_white_x, int_white_y, int_red_x, int_red_y, int_green_x,
  193781. int_green_y, int_blue_x, int_blue_y;
  193782. #endif
  193783. #endif
  193784. png_debug1(1, "in %s storage function\n", "sRGB_gAMA_and_cHRM");
  193785. if (png_ptr == NULL || info_ptr == NULL)
  193786. return;
  193787. png_set_sRGB(png_ptr, info_ptr, intent);
  193788. #if defined(PNG_gAMA_SUPPORTED)
  193789. #ifdef PNG_FLOATING_POINT_SUPPORTED
  193790. file_gamma = (float).45455;
  193791. png_set_gAMA(png_ptr, info_ptr, file_gamma);
  193792. #endif
  193793. #ifdef PNG_FIXED_POINT_SUPPORTED
  193794. int_file_gamma = 45455L;
  193795. png_set_gAMA_fixed(png_ptr, info_ptr, int_file_gamma);
  193796. #endif
  193797. #endif
  193798. #if defined(PNG_cHRM_SUPPORTED)
  193799. #ifdef PNG_FIXED_POINT_SUPPORTED
  193800. int_white_x = 31270L;
  193801. int_white_y = 32900L;
  193802. int_red_x = 64000L;
  193803. int_red_y = 33000L;
  193804. int_green_x = 30000L;
  193805. int_green_y = 60000L;
  193806. int_blue_x = 15000L;
  193807. int_blue_y = 6000L;
  193808. png_set_cHRM_fixed(png_ptr, info_ptr,
  193809. int_white_x, int_white_y, int_red_x, int_red_y, int_green_x, int_green_y,
  193810. int_blue_x, int_blue_y);
  193811. #endif
  193812. #ifdef PNG_FLOATING_POINT_SUPPORTED
  193813. white_x = (float).3127;
  193814. white_y = (float).3290;
  193815. red_x = (float).64;
  193816. red_y = (float).33;
  193817. green_x = (float).30;
  193818. green_y = (float).60;
  193819. blue_x = (float).15;
  193820. blue_y = (float).06;
  193821. png_set_cHRM(png_ptr, info_ptr,
  193822. white_x, white_y, red_x, red_y, green_x, green_y, blue_x, blue_y);
  193823. #endif
  193824. #endif
  193825. }
  193826. #endif
  193827. #if defined(PNG_iCCP_SUPPORTED)
  193828. void PNGAPI
  193829. png_set_iCCP(png_structp png_ptr, png_infop info_ptr,
  193830. png_charp name, int compression_type,
  193831. png_charp profile, png_uint_32 proflen)
  193832. {
  193833. png_charp new_iccp_name;
  193834. png_charp new_iccp_profile;
  193835. png_debug1(1, "in %s storage function\n", "iCCP");
  193836. if (png_ptr == NULL || info_ptr == NULL || name == NULL || profile == NULL)
  193837. return;
  193838. new_iccp_name = (png_charp)png_malloc_warn(png_ptr, png_strlen(name)+1);
  193839. if (new_iccp_name == NULL)
  193840. {
  193841. png_warning(png_ptr, "Insufficient memory to process iCCP chunk.");
  193842. return;
  193843. }
  193844. png_strncpy(new_iccp_name, name, png_strlen(name)+1);
  193845. new_iccp_profile = (png_charp)png_malloc_warn(png_ptr, proflen);
  193846. if (new_iccp_profile == NULL)
  193847. {
  193848. png_free (png_ptr, new_iccp_name);
  193849. png_warning(png_ptr, "Insufficient memory to process iCCP profile.");
  193850. return;
  193851. }
  193852. png_memcpy(new_iccp_profile, profile, (png_size_t)proflen);
  193853. png_free_data(png_ptr, info_ptr, PNG_FREE_ICCP, 0);
  193854. info_ptr->iccp_proflen = proflen;
  193855. info_ptr->iccp_name = new_iccp_name;
  193856. info_ptr->iccp_profile = new_iccp_profile;
  193857. /* Compression is always zero but is here so the API and info structure
  193858. * does not have to change if we introduce multiple compression types */
  193859. info_ptr->iccp_compression = (png_byte)compression_type;
  193860. #ifdef PNG_FREE_ME_SUPPORTED
  193861. info_ptr->free_me |= PNG_FREE_ICCP;
  193862. #endif
  193863. info_ptr->valid |= PNG_INFO_iCCP;
  193864. }
  193865. #endif
  193866. #if defined(PNG_TEXT_SUPPORTED)
  193867. void PNGAPI
  193868. png_set_text(png_structp png_ptr, png_infop info_ptr, png_textp text_ptr,
  193869. int num_text)
  193870. {
  193871. int ret;
  193872. ret=png_set_text_2(png_ptr, info_ptr, text_ptr, num_text);
  193873. if (ret)
  193874. png_error(png_ptr, "Insufficient memory to store text");
  193875. }
  193876. int /* PRIVATE */
  193877. png_set_text_2(png_structp png_ptr, png_infop info_ptr, png_textp text_ptr,
  193878. int num_text)
  193879. {
  193880. int i;
  193881. png_debug1(1, "in %s storage function\n", (png_ptr->chunk_name[0] == '\0' ?
  193882. "text" : (png_const_charp)png_ptr->chunk_name));
  193883. if (png_ptr == NULL || info_ptr == NULL || num_text == 0)
  193884. return(0);
  193885. /* Make sure we have enough space in the "text" array in info_struct
  193886. * to hold all of the incoming text_ptr objects.
  193887. */
  193888. if (info_ptr->num_text + num_text > info_ptr->max_text)
  193889. {
  193890. if (info_ptr->text != NULL)
  193891. {
  193892. png_textp old_text;
  193893. int old_max;
  193894. old_max = info_ptr->max_text;
  193895. info_ptr->max_text = info_ptr->num_text + num_text + 8;
  193896. old_text = info_ptr->text;
  193897. info_ptr->text = (png_textp)png_malloc_warn(png_ptr,
  193898. (png_uint_32)(info_ptr->max_text * png_sizeof (png_text)));
  193899. if (info_ptr->text == NULL)
  193900. {
  193901. png_free(png_ptr, old_text);
  193902. return(1);
  193903. }
  193904. png_memcpy(info_ptr->text, old_text, (png_size_t)(old_max *
  193905. png_sizeof(png_text)));
  193906. png_free(png_ptr, old_text);
  193907. }
  193908. else
  193909. {
  193910. info_ptr->max_text = num_text + 8;
  193911. info_ptr->num_text = 0;
  193912. info_ptr->text = (png_textp)png_malloc_warn(png_ptr,
  193913. (png_uint_32)(info_ptr->max_text * png_sizeof (png_text)));
  193914. if (info_ptr->text == NULL)
  193915. return(1);
  193916. #ifdef PNG_FREE_ME_SUPPORTED
  193917. info_ptr->free_me |= PNG_FREE_TEXT;
  193918. #endif
  193919. }
  193920. png_debug1(3, "allocated %d entries for info_ptr->text\n",
  193921. info_ptr->max_text);
  193922. }
  193923. for (i = 0; i < num_text; i++)
  193924. {
  193925. png_size_t text_length,key_len;
  193926. png_size_t lang_len,lang_key_len;
  193927. png_textp textp = &(info_ptr->text[info_ptr->num_text]);
  193928. if (text_ptr[i].key == NULL)
  193929. continue;
  193930. key_len = png_strlen(text_ptr[i].key);
  193931. if(text_ptr[i].compression <= 0)
  193932. {
  193933. lang_len = 0;
  193934. lang_key_len = 0;
  193935. }
  193936. else
  193937. #ifdef PNG_iTXt_SUPPORTED
  193938. {
  193939. /* set iTXt data */
  193940. if (text_ptr[i].lang != NULL)
  193941. lang_len = png_strlen(text_ptr[i].lang);
  193942. else
  193943. lang_len = 0;
  193944. if (text_ptr[i].lang_key != NULL)
  193945. lang_key_len = png_strlen(text_ptr[i].lang_key);
  193946. else
  193947. lang_key_len = 0;
  193948. }
  193949. #else
  193950. {
  193951. png_warning(png_ptr, "iTXt chunk not supported.");
  193952. continue;
  193953. }
  193954. #endif
  193955. if (text_ptr[i].text == NULL || text_ptr[i].text[0] == '\0')
  193956. {
  193957. text_length = 0;
  193958. #ifdef PNG_iTXt_SUPPORTED
  193959. if(text_ptr[i].compression > 0)
  193960. textp->compression = PNG_ITXT_COMPRESSION_NONE;
  193961. else
  193962. #endif
  193963. textp->compression = PNG_TEXT_COMPRESSION_NONE;
  193964. }
  193965. else
  193966. {
  193967. text_length = png_strlen(text_ptr[i].text);
  193968. textp->compression = text_ptr[i].compression;
  193969. }
  193970. textp->key = (png_charp)png_malloc_warn(png_ptr,
  193971. (png_uint_32)(key_len + text_length + lang_len + lang_key_len + 4));
  193972. if (textp->key == NULL)
  193973. return(1);
  193974. png_debug2(2, "Allocated %lu bytes at %x in png_set_text\n",
  193975. (png_uint_32)(key_len + lang_len + lang_key_len + text_length + 4),
  193976. (int)textp->key);
  193977. png_memcpy(textp->key, text_ptr[i].key,
  193978. (png_size_t)(key_len));
  193979. *(textp->key+key_len) = '\0';
  193980. #ifdef PNG_iTXt_SUPPORTED
  193981. if (text_ptr[i].compression > 0)
  193982. {
  193983. textp->lang=textp->key + key_len + 1;
  193984. png_memcpy(textp->lang, text_ptr[i].lang, lang_len);
  193985. *(textp->lang+lang_len) = '\0';
  193986. textp->lang_key=textp->lang + lang_len + 1;
  193987. png_memcpy(textp->lang_key, text_ptr[i].lang_key, lang_key_len);
  193988. *(textp->lang_key+lang_key_len) = '\0';
  193989. textp->text=textp->lang_key + lang_key_len + 1;
  193990. }
  193991. else
  193992. #endif
  193993. {
  193994. #ifdef PNG_iTXt_SUPPORTED
  193995. textp->lang=NULL;
  193996. textp->lang_key=NULL;
  193997. #endif
  193998. textp->text=textp->key + key_len + 1;
  193999. }
  194000. if(text_length)
  194001. png_memcpy(textp->text, text_ptr[i].text,
  194002. (png_size_t)(text_length));
  194003. *(textp->text+text_length) = '\0';
  194004. #ifdef PNG_iTXt_SUPPORTED
  194005. if(textp->compression > 0)
  194006. {
  194007. textp->text_length = 0;
  194008. textp->itxt_length = text_length;
  194009. }
  194010. else
  194011. #endif
  194012. {
  194013. textp->text_length = text_length;
  194014. #ifdef PNG_iTXt_SUPPORTED
  194015. textp->itxt_length = 0;
  194016. #endif
  194017. }
  194018. info_ptr->num_text++;
  194019. png_debug1(3, "transferred text chunk %d\n", info_ptr->num_text);
  194020. }
  194021. return(0);
  194022. }
  194023. #endif
  194024. #if defined(PNG_tIME_SUPPORTED)
  194025. void PNGAPI
  194026. png_set_tIME(png_structp png_ptr, png_infop info_ptr, png_timep mod_time)
  194027. {
  194028. png_debug1(1, "in %s storage function\n", "tIME");
  194029. if (png_ptr == NULL || info_ptr == NULL ||
  194030. (png_ptr->mode & PNG_WROTE_tIME))
  194031. return;
  194032. png_memcpy(&(info_ptr->mod_time), mod_time, png_sizeof (png_time));
  194033. info_ptr->valid |= PNG_INFO_tIME;
  194034. }
  194035. #endif
  194036. #if defined(PNG_tRNS_SUPPORTED)
  194037. void PNGAPI
  194038. png_set_tRNS(png_structp png_ptr, png_infop info_ptr,
  194039. png_bytep trans, int num_trans, png_color_16p trans_values)
  194040. {
  194041. png_debug1(1, "in %s storage function\n", "tRNS");
  194042. if (png_ptr == NULL || info_ptr == NULL)
  194043. return;
  194044. if (trans != NULL)
  194045. {
  194046. /*
  194047. * It may not actually be necessary to set png_ptr->trans here;
  194048. * we do it for backward compatibility with the way the png_handle_tRNS
  194049. * function used to do the allocation.
  194050. */
  194051. #ifdef PNG_FREE_ME_SUPPORTED
  194052. png_free_data(png_ptr, info_ptr, PNG_FREE_TRNS, 0);
  194053. #endif
  194054. /* Changed from num_trans to PNG_MAX_PALETTE_LENGTH in version 1.2.1 */
  194055. png_ptr->trans = info_ptr->trans = (png_bytep)png_malloc(png_ptr,
  194056. (png_uint_32)PNG_MAX_PALETTE_LENGTH);
  194057. if (num_trans <= PNG_MAX_PALETTE_LENGTH)
  194058. png_memcpy(info_ptr->trans, trans, (png_size_t)num_trans);
  194059. #ifdef PNG_FREE_ME_SUPPORTED
  194060. info_ptr->free_me |= PNG_FREE_TRNS;
  194061. #else
  194062. png_ptr->flags |= PNG_FLAG_FREE_TRNS;
  194063. #endif
  194064. }
  194065. if (trans_values != NULL)
  194066. {
  194067. png_memcpy(&(info_ptr->trans_values), trans_values,
  194068. png_sizeof(png_color_16));
  194069. if (num_trans == 0)
  194070. num_trans = 1;
  194071. }
  194072. info_ptr->num_trans = (png_uint_16)num_trans;
  194073. info_ptr->valid |= PNG_INFO_tRNS;
  194074. }
  194075. #endif
  194076. #if defined(PNG_sPLT_SUPPORTED)
  194077. void PNGAPI
  194078. png_set_sPLT(png_structp png_ptr,
  194079. png_infop info_ptr, png_sPLT_tp entries, int nentries)
  194080. {
  194081. png_sPLT_tp np;
  194082. int i;
  194083. if (png_ptr == NULL || info_ptr == NULL)
  194084. return;
  194085. np = (png_sPLT_tp)png_malloc_warn(png_ptr,
  194086. (info_ptr->splt_palettes_num + nentries) * png_sizeof(png_sPLT_t));
  194087. if (np == NULL)
  194088. {
  194089. png_warning(png_ptr, "No memory for sPLT palettes.");
  194090. return;
  194091. }
  194092. png_memcpy(np, info_ptr->splt_palettes,
  194093. info_ptr->splt_palettes_num * png_sizeof(png_sPLT_t));
  194094. png_free(png_ptr, info_ptr->splt_palettes);
  194095. info_ptr->splt_palettes=NULL;
  194096. for (i = 0; i < nentries; i++)
  194097. {
  194098. png_sPLT_tp to = np + info_ptr->splt_palettes_num + i;
  194099. png_sPLT_tp from = entries + i;
  194100. to->name = (png_charp)png_malloc_warn(png_ptr,
  194101. png_strlen(from->name) + 1);
  194102. if (to->name == NULL)
  194103. {
  194104. png_warning(png_ptr,
  194105. "Out of memory while processing sPLT chunk");
  194106. }
  194107. /* TODO: use png_malloc_warn */
  194108. png_strncpy(to->name, from->name, png_strlen(from->name)+1);
  194109. to->entries = (png_sPLT_entryp)png_malloc_warn(png_ptr,
  194110. from->nentries * png_sizeof(png_sPLT_entry));
  194111. /* TODO: use png_malloc_warn */
  194112. png_memcpy(to->entries, from->entries,
  194113. from->nentries * png_sizeof(png_sPLT_entry));
  194114. if (to->entries == NULL)
  194115. {
  194116. png_warning(png_ptr,
  194117. "Out of memory while processing sPLT chunk");
  194118. png_free(png_ptr,to->name);
  194119. to->name = NULL;
  194120. }
  194121. to->nentries = from->nentries;
  194122. to->depth = from->depth;
  194123. }
  194124. info_ptr->splt_palettes = np;
  194125. info_ptr->splt_palettes_num += nentries;
  194126. info_ptr->valid |= PNG_INFO_sPLT;
  194127. #ifdef PNG_FREE_ME_SUPPORTED
  194128. info_ptr->free_me |= PNG_FREE_SPLT;
  194129. #endif
  194130. }
  194131. #endif /* PNG_sPLT_SUPPORTED */
  194132. #if defined(PNG_UNKNOWN_CHUNKS_SUPPORTED)
  194133. void PNGAPI
  194134. png_set_unknown_chunks(png_structp png_ptr,
  194135. png_infop info_ptr, png_unknown_chunkp unknowns, int num_unknowns)
  194136. {
  194137. png_unknown_chunkp np;
  194138. int i;
  194139. if (png_ptr == NULL || info_ptr == NULL || num_unknowns == 0)
  194140. return;
  194141. np = (png_unknown_chunkp)png_malloc_warn(png_ptr,
  194142. (info_ptr->unknown_chunks_num + num_unknowns) *
  194143. png_sizeof(png_unknown_chunk));
  194144. if (np == NULL)
  194145. {
  194146. png_warning(png_ptr,
  194147. "Out of memory while processing unknown chunk.");
  194148. return;
  194149. }
  194150. png_memcpy(np, info_ptr->unknown_chunks,
  194151. info_ptr->unknown_chunks_num * png_sizeof(png_unknown_chunk));
  194152. png_free(png_ptr, info_ptr->unknown_chunks);
  194153. info_ptr->unknown_chunks=NULL;
  194154. for (i = 0; i < num_unknowns; i++)
  194155. {
  194156. png_unknown_chunkp to = np + info_ptr->unknown_chunks_num + i;
  194157. png_unknown_chunkp from = unknowns + i;
  194158. png_strncpy((png_charp)to->name, (png_charp)from->name, 5);
  194159. to->data = (png_bytep)png_malloc_warn(png_ptr, from->size);
  194160. if (to->data == NULL)
  194161. {
  194162. png_warning(png_ptr,
  194163. "Out of memory while processing unknown chunk.");
  194164. }
  194165. else
  194166. {
  194167. png_memcpy(to->data, from->data, from->size);
  194168. to->size = from->size;
  194169. /* note our location in the read or write sequence */
  194170. to->location = (png_byte)(png_ptr->mode & 0xff);
  194171. }
  194172. }
  194173. info_ptr->unknown_chunks = np;
  194174. info_ptr->unknown_chunks_num += num_unknowns;
  194175. #ifdef PNG_FREE_ME_SUPPORTED
  194176. info_ptr->free_me |= PNG_FREE_UNKN;
  194177. #endif
  194178. }
  194179. void PNGAPI
  194180. png_set_unknown_chunk_location(png_structp png_ptr, png_infop info_ptr,
  194181. int chunk, int location)
  194182. {
  194183. if(png_ptr != NULL && info_ptr != NULL && chunk >= 0 && chunk <
  194184. (int)info_ptr->unknown_chunks_num)
  194185. info_ptr->unknown_chunks[chunk].location = (png_byte)location;
  194186. }
  194187. #endif
  194188. #if defined(PNG_1_0_X) || defined(PNG_1_2_X)
  194189. #if defined(PNG_READ_EMPTY_PLTE_SUPPORTED) || \
  194190. defined(PNG_WRITE_EMPTY_PLTE_SUPPORTED)
  194191. void PNGAPI
  194192. png_permit_empty_plte (png_structp png_ptr, int empty_plte_permitted)
  194193. {
  194194. /* This function is deprecated in favor of png_permit_mng_features()
  194195. and will be removed from libpng-1.3.0 */
  194196. png_debug(1, "in png_permit_empty_plte, DEPRECATED.\n");
  194197. if (png_ptr == NULL)
  194198. return;
  194199. png_ptr->mng_features_permitted = (png_byte)
  194200. ((png_ptr->mng_features_permitted & (~(PNG_FLAG_MNG_EMPTY_PLTE))) |
  194201. ((empty_plte_permitted & PNG_FLAG_MNG_EMPTY_PLTE)));
  194202. }
  194203. #endif
  194204. #endif
  194205. #if defined(PNG_MNG_FEATURES_SUPPORTED)
  194206. png_uint_32 PNGAPI
  194207. png_permit_mng_features (png_structp png_ptr, png_uint_32 mng_features)
  194208. {
  194209. png_debug(1, "in png_permit_mng_features\n");
  194210. if (png_ptr == NULL)
  194211. return (png_uint_32)0;
  194212. png_ptr->mng_features_permitted =
  194213. (png_byte)(mng_features & PNG_ALL_MNG_FEATURES);
  194214. return (png_uint_32)png_ptr->mng_features_permitted;
  194215. }
  194216. #endif
  194217. #if defined(PNG_UNKNOWN_CHUNKS_SUPPORTED)
  194218. void PNGAPI
  194219. png_set_keep_unknown_chunks(png_structp png_ptr, int keep, png_bytep
  194220. chunk_list, int num_chunks)
  194221. {
  194222. png_bytep new_list, p;
  194223. int i, old_num_chunks;
  194224. if (png_ptr == NULL)
  194225. return;
  194226. if (num_chunks == 0)
  194227. {
  194228. if(keep == PNG_HANDLE_CHUNK_ALWAYS || keep == PNG_HANDLE_CHUNK_IF_SAFE)
  194229. png_ptr->flags |= PNG_FLAG_KEEP_UNKNOWN_CHUNKS;
  194230. else
  194231. png_ptr->flags &= ~PNG_FLAG_KEEP_UNKNOWN_CHUNKS;
  194232. if(keep == PNG_HANDLE_CHUNK_ALWAYS)
  194233. png_ptr->flags |= PNG_FLAG_KEEP_UNSAFE_CHUNKS;
  194234. else
  194235. png_ptr->flags &= ~PNG_FLAG_KEEP_UNSAFE_CHUNKS;
  194236. return;
  194237. }
  194238. if (chunk_list == NULL)
  194239. return;
  194240. old_num_chunks=png_ptr->num_chunk_list;
  194241. new_list=(png_bytep)png_malloc(png_ptr,
  194242. (png_uint_32)(5*(num_chunks+old_num_chunks)));
  194243. if(png_ptr->chunk_list != NULL)
  194244. {
  194245. png_memcpy(new_list, png_ptr->chunk_list,
  194246. (png_size_t)(5*old_num_chunks));
  194247. png_free(png_ptr, png_ptr->chunk_list);
  194248. png_ptr->chunk_list=NULL;
  194249. }
  194250. png_memcpy(new_list+5*old_num_chunks, chunk_list,
  194251. (png_size_t)(5*num_chunks));
  194252. for (p=new_list+5*old_num_chunks+4, i=0; i<num_chunks; i++, p+=5)
  194253. *p=(png_byte)keep;
  194254. png_ptr->num_chunk_list=old_num_chunks+num_chunks;
  194255. png_ptr->chunk_list=new_list;
  194256. #ifdef PNG_FREE_ME_SUPPORTED
  194257. png_ptr->free_me |= PNG_FREE_LIST;
  194258. #endif
  194259. }
  194260. #endif
  194261. #if defined(PNG_READ_USER_CHUNKS_SUPPORTED)
  194262. void PNGAPI
  194263. png_set_read_user_chunk_fn(png_structp png_ptr, png_voidp user_chunk_ptr,
  194264. png_user_chunk_ptr read_user_chunk_fn)
  194265. {
  194266. png_debug(1, "in png_set_read_user_chunk_fn\n");
  194267. if (png_ptr == NULL)
  194268. return;
  194269. png_ptr->read_user_chunk_fn = read_user_chunk_fn;
  194270. png_ptr->user_chunk_ptr = user_chunk_ptr;
  194271. }
  194272. #endif
  194273. #if defined(PNG_INFO_IMAGE_SUPPORTED)
  194274. void PNGAPI
  194275. png_set_rows(png_structp png_ptr, png_infop info_ptr, png_bytepp row_pointers)
  194276. {
  194277. png_debug1(1, "in %s storage function\n", "rows");
  194278. if (png_ptr == NULL || info_ptr == NULL)
  194279. return;
  194280. if(info_ptr->row_pointers && (info_ptr->row_pointers != row_pointers))
  194281. png_free_data(png_ptr, info_ptr, PNG_FREE_ROWS, 0);
  194282. info_ptr->row_pointers = row_pointers;
  194283. if(row_pointers)
  194284. info_ptr->valid |= PNG_INFO_IDAT;
  194285. }
  194286. #endif
  194287. #ifdef PNG_WRITE_SUPPORTED
  194288. void PNGAPI
  194289. png_set_compression_buffer_size(png_structp png_ptr, png_uint_32 size)
  194290. {
  194291. if (png_ptr == NULL)
  194292. return;
  194293. if(png_ptr->zbuf)
  194294. png_free(png_ptr, png_ptr->zbuf);
  194295. png_ptr->zbuf_size = (png_size_t)size;
  194296. png_ptr->zbuf = (png_bytep)png_malloc(png_ptr, size);
  194297. png_ptr->zstream.next_out = png_ptr->zbuf;
  194298. png_ptr->zstream.avail_out = (uInt)png_ptr->zbuf_size;
  194299. }
  194300. #endif
  194301. void PNGAPI
  194302. png_set_invalid(png_structp png_ptr, png_infop info_ptr, int mask)
  194303. {
  194304. if (png_ptr && info_ptr)
  194305. info_ptr->valid &= ~(mask);
  194306. }
  194307. #ifndef PNG_1_0_X
  194308. #ifdef PNG_ASSEMBLER_CODE_SUPPORTED
  194309. /* function was added to libpng 1.2.0 and should always exist by default */
  194310. void PNGAPI
  194311. png_set_asm_flags (png_structp png_ptr, png_uint_32 asm_flags)
  194312. {
  194313. /* Obsolete as of libpng-1.2.20 and will be removed from libpng-1.4.0 */
  194314. if (png_ptr != NULL)
  194315. png_ptr->asm_flags = 0;
  194316. }
  194317. /* this function was added to libpng 1.2.0 */
  194318. void PNGAPI
  194319. png_set_mmx_thresholds (png_structp png_ptr,
  194320. png_byte mmx_bitdepth_threshold,
  194321. png_uint_32 mmx_rowbytes_threshold)
  194322. {
  194323. /* Obsolete as of libpng-1.2.20 and will be removed from libpng-1.4.0 */
  194324. if (png_ptr == NULL)
  194325. return;
  194326. }
  194327. #endif /* ?PNG_ASSEMBLER_CODE_SUPPORTED */
  194328. #ifdef PNG_SET_USER_LIMITS_SUPPORTED
  194329. /* this function was added to libpng 1.2.6 */
  194330. void PNGAPI
  194331. png_set_user_limits (png_structp png_ptr, png_uint_32 user_width_max,
  194332. png_uint_32 user_height_max)
  194333. {
  194334. /* Images with dimensions larger than these limits will be
  194335. * rejected by png_set_IHDR(). To accept any PNG datastream
  194336. * regardless of dimensions, set both limits to 0x7ffffffL.
  194337. */
  194338. if(png_ptr == NULL) return;
  194339. png_ptr->user_width_max = user_width_max;
  194340. png_ptr->user_height_max = user_height_max;
  194341. }
  194342. #endif /* ?PNG_SET_USER_LIMITS_SUPPORTED */
  194343. #endif /* ?PNG_1_0_X */
  194344. #endif /* PNG_READ_SUPPORTED || PNG_WRITE_SUPPORTED */
  194345. /*** End of inlined file: pngset.c ***/
  194346. /*** Start of inlined file: pngtrans.c ***/
  194347. /* pngtrans.c - transforms the data in a row (used by both readers and writers)
  194348. *
  194349. * Last changed in libpng 1.2.17 May 15, 2007
  194350. * For conditions of distribution and use, see copyright notice in png.h
  194351. * Copyright (c) 1998-2007 Glenn Randers-Pehrson
  194352. * (Version 0.96 Copyright (c) 1996, 1997 Andreas Dilger)
  194353. * (Version 0.88 Copyright (c) 1995, 1996 Guy Eric Schalnat, Group 42, Inc.)
  194354. */
  194355. #define PNG_INTERNAL
  194356. #if defined(PNG_READ_SUPPORTED) || defined(PNG_WRITE_SUPPORTED)
  194357. #if defined(PNG_READ_BGR_SUPPORTED) || defined(PNG_WRITE_BGR_SUPPORTED)
  194358. /* turn on BGR-to-RGB mapping */
  194359. void PNGAPI
  194360. png_set_bgr(png_structp png_ptr)
  194361. {
  194362. png_debug(1, "in png_set_bgr\n");
  194363. if(png_ptr == NULL) return;
  194364. png_ptr->transformations |= PNG_BGR;
  194365. }
  194366. #endif
  194367. #if defined(PNG_READ_SWAP_SUPPORTED) || defined(PNG_WRITE_SWAP_SUPPORTED)
  194368. /* turn on 16 bit byte swapping */
  194369. void PNGAPI
  194370. png_set_swap(png_structp png_ptr)
  194371. {
  194372. png_debug(1, "in png_set_swap\n");
  194373. if(png_ptr == NULL) return;
  194374. if (png_ptr->bit_depth == 16)
  194375. png_ptr->transformations |= PNG_SWAP_BYTES;
  194376. }
  194377. #endif
  194378. #if defined(PNG_READ_PACK_SUPPORTED) || defined(PNG_WRITE_PACK_SUPPORTED)
  194379. /* turn on pixel packing */
  194380. void PNGAPI
  194381. png_set_packing(png_structp png_ptr)
  194382. {
  194383. png_debug(1, "in png_set_packing\n");
  194384. if(png_ptr == NULL) return;
  194385. if (png_ptr->bit_depth < 8)
  194386. {
  194387. png_ptr->transformations |= PNG_PACK;
  194388. png_ptr->usr_bit_depth = 8;
  194389. }
  194390. }
  194391. #endif
  194392. #if defined(PNG_READ_PACKSWAP_SUPPORTED)||defined(PNG_WRITE_PACKSWAP_SUPPORTED)
  194393. /* turn on packed pixel swapping */
  194394. void PNGAPI
  194395. png_set_packswap(png_structp png_ptr)
  194396. {
  194397. png_debug(1, "in png_set_packswap\n");
  194398. if(png_ptr == NULL) return;
  194399. if (png_ptr->bit_depth < 8)
  194400. png_ptr->transformations |= PNG_PACKSWAP;
  194401. }
  194402. #endif
  194403. #if defined(PNG_READ_SHIFT_SUPPORTED) || defined(PNG_WRITE_SHIFT_SUPPORTED)
  194404. void PNGAPI
  194405. png_set_shift(png_structp png_ptr, png_color_8p true_bits)
  194406. {
  194407. png_debug(1, "in png_set_shift\n");
  194408. if(png_ptr == NULL) return;
  194409. png_ptr->transformations |= PNG_SHIFT;
  194410. png_ptr->shift = *true_bits;
  194411. }
  194412. #endif
  194413. #if defined(PNG_READ_INTERLACING_SUPPORTED) || \
  194414. defined(PNG_WRITE_INTERLACING_SUPPORTED)
  194415. int PNGAPI
  194416. png_set_interlace_handling(png_structp png_ptr)
  194417. {
  194418. png_debug(1, "in png_set_interlace handling\n");
  194419. if (png_ptr && png_ptr->interlaced)
  194420. {
  194421. png_ptr->transformations |= PNG_INTERLACE;
  194422. return (7);
  194423. }
  194424. return (1);
  194425. }
  194426. #endif
  194427. #if defined(PNG_READ_FILLER_SUPPORTED) || defined(PNG_WRITE_FILLER_SUPPORTED)
  194428. /* Add a filler byte on read, or remove a filler or alpha byte on write.
  194429. * The filler type has changed in v0.95 to allow future 2-byte fillers
  194430. * for 48-bit input data, as well as to avoid problems with some compilers
  194431. * that don't like bytes as parameters.
  194432. */
  194433. void PNGAPI
  194434. png_set_filler(png_structp png_ptr, png_uint_32 filler, int filler_loc)
  194435. {
  194436. png_debug(1, "in png_set_filler\n");
  194437. if(png_ptr == NULL) return;
  194438. png_ptr->transformations |= PNG_FILLER;
  194439. png_ptr->filler = (png_byte)filler;
  194440. if (filler_loc == PNG_FILLER_AFTER)
  194441. png_ptr->flags |= PNG_FLAG_FILLER_AFTER;
  194442. else
  194443. png_ptr->flags &= ~PNG_FLAG_FILLER_AFTER;
  194444. /* This should probably go in the "do_read_filler" routine.
  194445. * I attempted to do that in libpng-1.0.1a but that caused problems
  194446. * so I restored it in libpng-1.0.2a
  194447. */
  194448. if (png_ptr->color_type == PNG_COLOR_TYPE_RGB)
  194449. {
  194450. png_ptr->usr_channels = 4;
  194451. }
  194452. /* Also I added this in libpng-1.0.2a (what happens when we expand
  194453. * a less-than-8-bit grayscale to GA? */
  194454. if (png_ptr->color_type == PNG_COLOR_TYPE_GRAY && png_ptr->bit_depth >= 8)
  194455. {
  194456. png_ptr->usr_channels = 2;
  194457. }
  194458. }
  194459. #if !defined(PNG_1_0_X)
  194460. /* Added to libpng-1.2.7 */
  194461. void PNGAPI
  194462. png_set_add_alpha(png_structp png_ptr, png_uint_32 filler, int filler_loc)
  194463. {
  194464. png_debug(1, "in png_set_add_alpha\n");
  194465. if(png_ptr == NULL) return;
  194466. png_set_filler(png_ptr, filler, filler_loc);
  194467. png_ptr->transformations |= PNG_ADD_ALPHA;
  194468. }
  194469. #endif
  194470. #endif
  194471. #if defined(PNG_READ_SWAP_ALPHA_SUPPORTED) || \
  194472. defined(PNG_WRITE_SWAP_ALPHA_SUPPORTED)
  194473. void PNGAPI
  194474. png_set_swap_alpha(png_structp png_ptr)
  194475. {
  194476. png_debug(1, "in png_set_swap_alpha\n");
  194477. if(png_ptr == NULL) return;
  194478. png_ptr->transformations |= PNG_SWAP_ALPHA;
  194479. }
  194480. #endif
  194481. #if defined(PNG_READ_INVERT_ALPHA_SUPPORTED) || \
  194482. defined(PNG_WRITE_INVERT_ALPHA_SUPPORTED)
  194483. void PNGAPI
  194484. png_set_invert_alpha(png_structp png_ptr)
  194485. {
  194486. png_debug(1, "in png_set_invert_alpha\n");
  194487. if(png_ptr == NULL) return;
  194488. png_ptr->transformations |= PNG_INVERT_ALPHA;
  194489. }
  194490. #endif
  194491. #if defined(PNG_READ_INVERT_SUPPORTED) || defined(PNG_WRITE_INVERT_SUPPORTED)
  194492. void PNGAPI
  194493. png_set_invert_mono(png_structp png_ptr)
  194494. {
  194495. png_debug(1, "in png_set_invert_mono\n");
  194496. if(png_ptr == NULL) return;
  194497. png_ptr->transformations |= PNG_INVERT_MONO;
  194498. }
  194499. /* invert monochrome grayscale data */
  194500. void /* PRIVATE */
  194501. png_do_invert(png_row_infop row_info, png_bytep row)
  194502. {
  194503. png_debug(1, "in png_do_invert\n");
  194504. /* This test removed from libpng version 1.0.13 and 1.2.0:
  194505. * if (row_info->bit_depth == 1 &&
  194506. */
  194507. #if defined(PNG_USELESS_TESTS_SUPPORTED)
  194508. if (row == NULL || row_info == NULL)
  194509. return;
  194510. #endif
  194511. if (row_info->color_type == PNG_COLOR_TYPE_GRAY)
  194512. {
  194513. png_bytep rp = row;
  194514. png_uint_32 i;
  194515. png_uint_32 istop = row_info->rowbytes;
  194516. for (i = 0; i < istop; i++)
  194517. {
  194518. *rp = (png_byte)(~(*rp));
  194519. rp++;
  194520. }
  194521. }
  194522. else if (row_info->color_type == PNG_COLOR_TYPE_GRAY_ALPHA &&
  194523. row_info->bit_depth == 8)
  194524. {
  194525. png_bytep rp = row;
  194526. png_uint_32 i;
  194527. png_uint_32 istop = row_info->rowbytes;
  194528. for (i = 0; i < istop; i+=2)
  194529. {
  194530. *rp = (png_byte)(~(*rp));
  194531. rp+=2;
  194532. }
  194533. }
  194534. else if (row_info->color_type == PNG_COLOR_TYPE_GRAY_ALPHA &&
  194535. row_info->bit_depth == 16)
  194536. {
  194537. png_bytep rp = row;
  194538. png_uint_32 i;
  194539. png_uint_32 istop = row_info->rowbytes;
  194540. for (i = 0; i < istop; i+=4)
  194541. {
  194542. *rp = (png_byte)(~(*rp));
  194543. *(rp+1) = (png_byte)(~(*(rp+1)));
  194544. rp+=4;
  194545. }
  194546. }
  194547. }
  194548. #endif
  194549. #if defined(PNG_READ_SWAP_SUPPORTED) || defined(PNG_WRITE_SWAP_SUPPORTED)
  194550. /* swaps byte order on 16 bit depth images */
  194551. void /* PRIVATE */
  194552. png_do_swap(png_row_infop row_info, png_bytep row)
  194553. {
  194554. png_debug(1, "in png_do_swap\n");
  194555. if (
  194556. #if defined(PNG_USELESS_TESTS_SUPPORTED)
  194557. row != NULL && row_info != NULL &&
  194558. #endif
  194559. row_info->bit_depth == 16)
  194560. {
  194561. png_bytep rp = row;
  194562. png_uint_32 i;
  194563. png_uint_32 istop= row_info->width * row_info->channels;
  194564. for (i = 0; i < istop; i++, rp += 2)
  194565. {
  194566. png_byte t = *rp;
  194567. *rp = *(rp + 1);
  194568. *(rp + 1) = t;
  194569. }
  194570. }
  194571. }
  194572. #endif
  194573. #if defined(PNG_READ_PACKSWAP_SUPPORTED)||defined(PNG_WRITE_PACKSWAP_SUPPORTED)
  194574. static PNG_CONST png_byte onebppswaptable[256] = {
  194575. 0x00, 0x80, 0x40, 0xC0, 0x20, 0xA0, 0x60, 0xE0,
  194576. 0x10, 0x90, 0x50, 0xD0, 0x30, 0xB0, 0x70, 0xF0,
  194577. 0x08, 0x88, 0x48, 0xC8, 0x28, 0xA8, 0x68, 0xE8,
  194578. 0x18, 0x98, 0x58, 0xD8, 0x38, 0xB8, 0x78, 0xF8,
  194579. 0x04, 0x84, 0x44, 0xC4, 0x24, 0xA4, 0x64, 0xE4,
  194580. 0x14, 0x94, 0x54, 0xD4, 0x34, 0xB4, 0x74, 0xF4,
  194581. 0x0C, 0x8C, 0x4C, 0xCC, 0x2C, 0xAC, 0x6C, 0xEC,
  194582. 0x1C, 0x9C, 0x5C, 0xDC, 0x3C, 0xBC, 0x7C, 0xFC,
  194583. 0x02, 0x82, 0x42, 0xC2, 0x22, 0xA2, 0x62, 0xE2,
  194584. 0x12, 0x92, 0x52, 0xD2, 0x32, 0xB2, 0x72, 0xF2,
  194585. 0x0A, 0x8A, 0x4A, 0xCA, 0x2A, 0xAA, 0x6A, 0xEA,
  194586. 0x1A, 0x9A, 0x5A, 0xDA, 0x3A, 0xBA, 0x7A, 0xFA,
  194587. 0x06, 0x86, 0x46, 0xC6, 0x26, 0xA6, 0x66, 0xE6,
  194588. 0x16, 0x96, 0x56, 0xD6, 0x36, 0xB6, 0x76, 0xF6,
  194589. 0x0E, 0x8E, 0x4E, 0xCE, 0x2E, 0xAE, 0x6E, 0xEE,
  194590. 0x1E, 0x9E, 0x5E, 0xDE, 0x3E, 0xBE, 0x7E, 0xFE,
  194591. 0x01, 0x81, 0x41, 0xC1, 0x21, 0xA1, 0x61, 0xE1,
  194592. 0x11, 0x91, 0x51, 0xD1, 0x31, 0xB1, 0x71, 0xF1,
  194593. 0x09, 0x89, 0x49, 0xC9, 0x29, 0xA9, 0x69, 0xE9,
  194594. 0x19, 0x99, 0x59, 0xD9, 0x39, 0xB9, 0x79, 0xF9,
  194595. 0x05, 0x85, 0x45, 0xC5, 0x25, 0xA5, 0x65, 0xE5,
  194596. 0x15, 0x95, 0x55, 0xD5, 0x35, 0xB5, 0x75, 0xF5,
  194597. 0x0D, 0x8D, 0x4D, 0xCD, 0x2D, 0xAD, 0x6D, 0xED,
  194598. 0x1D, 0x9D, 0x5D, 0xDD, 0x3D, 0xBD, 0x7D, 0xFD,
  194599. 0x03, 0x83, 0x43, 0xC3, 0x23, 0xA3, 0x63, 0xE3,
  194600. 0x13, 0x93, 0x53, 0xD3, 0x33, 0xB3, 0x73, 0xF3,
  194601. 0x0B, 0x8B, 0x4B, 0xCB, 0x2B, 0xAB, 0x6B, 0xEB,
  194602. 0x1B, 0x9B, 0x5B, 0xDB, 0x3B, 0xBB, 0x7B, 0xFB,
  194603. 0x07, 0x87, 0x47, 0xC7, 0x27, 0xA7, 0x67, 0xE7,
  194604. 0x17, 0x97, 0x57, 0xD7, 0x37, 0xB7, 0x77, 0xF7,
  194605. 0x0F, 0x8F, 0x4F, 0xCF, 0x2F, 0xAF, 0x6F, 0xEF,
  194606. 0x1F, 0x9F, 0x5F, 0xDF, 0x3F, 0xBF, 0x7F, 0xFF
  194607. };
  194608. static PNG_CONST png_byte twobppswaptable[256] = {
  194609. 0x00, 0x40, 0x80, 0xC0, 0x10, 0x50, 0x90, 0xD0,
  194610. 0x20, 0x60, 0xA0, 0xE0, 0x30, 0x70, 0xB0, 0xF0,
  194611. 0x04, 0x44, 0x84, 0xC4, 0x14, 0x54, 0x94, 0xD4,
  194612. 0x24, 0x64, 0xA4, 0xE4, 0x34, 0x74, 0xB4, 0xF4,
  194613. 0x08, 0x48, 0x88, 0xC8, 0x18, 0x58, 0x98, 0xD8,
  194614. 0x28, 0x68, 0xA8, 0xE8, 0x38, 0x78, 0xB8, 0xF8,
  194615. 0x0C, 0x4C, 0x8C, 0xCC, 0x1C, 0x5C, 0x9C, 0xDC,
  194616. 0x2C, 0x6C, 0xAC, 0xEC, 0x3C, 0x7C, 0xBC, 0xFC,
  194617. 0x01, 0x41, 0x81, 0xC1, 0x11, 0x51, 0x91, 0xD1,
  194618. 0x21, 0x61, 0xA1, 0xE1, 0x31, 0x71, 0xB1, 0xF1,
  194619. 0x05, 0x45, 0x85, 0xC5, 0x15, 0x55, 0x95, 0xD5,
  194620. 0x25, 0x65, 0xA5, 0xE5, 0x35, 0x75, 0xB5, 0xF5,
  194621. 0x09, 0x49, 0x89, 0xC9, 0x19, 0x59, 0x99, 0xD9,
  194622. 0x29, 0x69, 0xA9, 0xE9, 0x39, 0x79, 0xB9, 0xF9,
  194623. 0x0D, 0x4D, 0x8D, 0xCD, 0x1D, 0x5D, 0x9D, 0xDD,
  194624. 0x2D, 0x6D, 0xAD, 0xED, 0x3D, 0x7D, 0xBD, 0xFD,
  194625. 0x02, 0x42, 0x82, 0xC2, 0x12, 0x52, 0x92, 0xD2,
  194626. 0x22, 0x62, 0xA2, 0xE2, 0x32, 0x72, 0xB2, 0xF2,
  194627. 0x06, 0x46, 0x86, 0xC6, 0x16, 0x56, 0x96, 0xD6,
  194628. 0x26, 0x66, 0xA6, 0xE6, 0x36, 0x76, 0xB6, 0xF6,
  194629. 0x0A, 0x4A, 0x8A, 0xCA, 0x1A, 0x5A, 0x9A, 0xDA,
  194630. 0x2A, 0x6A, 0xAA, 0xEA, 0x3A, 0x7A, 0xBA, 0xFA,
  194631. 0x0E, 0x4E, 0x8E, 0xCE, 0x1E, 0x5E, 0x9E, 0xDE,
  194632. 0x2E, 0x6E, 0xAE, 0xEE, 0x3E, 0x7E, 0xBE, 0xFE,
  194633. 0x03, 0x43, 0x83, 0xC3, 0x13, 0x53, 0x93, 0xD3,
  194634. 0x23, 0x63, 0xA3, 0xE3, 0x33, 0x73, 0xB3, 0xF3,
  194635. 0x07, 0x47, 0x87, 0xC7, 0x17, 0x57, 0x97, 0xD7,
  194636. 0x27, 0x67, 0xA7, 0xE7, 0x37, 0x77, 0xB7, 0xF7,
  194637. 0x0B, 0x4B, 0x8B, 0xCB, 0x1B, 0x5B, 0x9B, 0xDB,
  194638. 0x2B, 0x6B, 0xAB, 0xEB, 0x3B, 0x7B, 0xBB, 0xFB,
  194639. 0x0F, 0x4F, 0x8F, 0xCF, 0x1F, 0x5F, 0x9F, 0xDF,
  194640. 0x2F, 0x6F, 0xAF, 0xEF, 0x3F, 0x7F, 0xBF, 0xFF
  194641. };
  194642. static PNG_CONST png_byte fourbppswaptable[256] = {
  194643. 0x00, 0x10, 0x20, 0x30, 0x40, 0x50, 0x60, 0x70,
  194644. 0x80, 0x90, 0xA0, 0xB0, 0xC0, 0xD0, 0xE0, 0xF0,
  194645. 0x01, 0x11, 0x21, 0x31, 0x41, 0x51, 0x61, 0x71,
  194646. 0x81, 0x91, 0xA1, 0xB1, 0xC1, 0xD1, 0xE1, 0xF1,
  194647. 0x02, 0x12, 0x22, 0x32, 0x42, 0x52, 0x62, 0x72,
  194648. 0x82, 0x92, 0xA2, 0xB2, 0xC2, 0xD2, 0xE2, 0xF2,
  194649. 0x03, 0x13, 0x23, 0x33, 0x43, 0x53, 0x63, 0x73,
  194650. 0x83, 0x93, 0xA3, 0xB3, 0xC3, 0xD3, 0xE3, 0xF3,
  194651. 0x04, 0x14, 0x24, 0x34, 0x44, 0x54, 0x64, 0x74,
  194652. 0x84, 0x94, 0xA4, 0xB4, 0xC4, 0xD4, 0xE4, 0xF4,
  194653. 0x05, 0x15, 0x25, 0x35, 0x45, 0x55, 0x65, 0x75,
  194654. 0x85, 0x95, 0xA5, 0xB5, 0xC5, 0xD5, 0xE5, 0xF5,
  194655. 0x06, 0x16, 0x26, 0x36, 0x46, 0x56, 0x66, 0x76,
  194656. 0x86, 0x96, 0xA6, 0xB6, 0xC6, 0xD6, 0xE6, 0xF6,
  194657. 0x07, 0x17, 0x27, 0x37, 0x47, 0x57, 0x67, 0x77,
  194658. 0x87, 0x97, 0xA7, 0xB7, 0xC7, 0xD7, 0xE7, 0xF7,
  194659. 0x08, 0x18, 0x28, 0x38, 0x48, 0x58, 0x68, 0x78,
  194660. 0x88, 0x98, 0xA8, 0xB8, 0xC8, 0xD8, 0xE8, 0xF8,
  194661. 0x09, 0x19, 0x29, 0x39, 0x49, 0x59, 0x69, 0x79,
  194662. 0x89, 0x99, 0xA9, 0xB9, 0xC9, 0xD9, 0xE9, 0xF9,
  194663. 0x0A, 0x1A, 0x2A, 0x3A, 0x4A, 0x5A, 0x6A, 0x7A,
  194664. 0x8A, 0x9A, 0xAA, 0xBA, 0xCA, 0xDA, 0xEA, 0xFA,
  194665. 0x0B, 0x1B, 0x2B, 0x3B, 0x4B, 0x5B, 0x6B, 0x7B,
  194666. 0x8B, 0x9B, 0xAB, 0xBB, 0xCB, 0xDB, 0xEB, 0xFB,
  194667. 0x0C, 0x1C, 0x2C, 0x3C, 0x4C, 0x5C, 0x6C, 0x7C,
  194668. 0x8C, 0x9C, 0xAC, 0xBC, 0xCC, 0xDC, 0xEC, 0xFC,
  194669. 0x0D, 0x1D, 0x2D, 0x3D, 0x4D, 0x5D, 0x6D, 0x7D,
  194670. 0x8D, 0x9D, 0xAD, 0xBD, 0xCD, 0xDD, 0xED, 0xFD,
  194671. 0x0E, 0x1E, 0x2E, 0x3E, 0x4E, 0x5E, 0x6E, 0x7E,
  194672. 0x8E, 0x9E, 0xAE, 0xBE, 0xCE, 0xDE, 0xEE, 0xFE,
  194673. 0x0F, 0x1F, 0x2F, 0x3F, 0x4F, 0x5F, 0x6F, 0x7F,
  194674. 0x8F, 0x9F, 0xAF, 0xBF, 0xCF, 0xDF, 0xEF, 0xFF
  194675. };
  194676. /* swaps pixel packing order within bytes */
  194677. void /* PRIVATE */
  194678. png_do_packswap(png_row_infop row_info, png_bytep row)
  194679. {
  194680. png_debug(1, "in png_do_packswap\n");
  194681. if (
  194682. #if defined(PNG_USELESS_TESTS_SUPPORTED)
  194683. row != NULL && row_info != NULL &&
  194684. #endif
  194685. row_info->bit_depth < 8)
  194686. {
  194687. png_bytep rp, end, table;
  194688. end = row + row_info->rowbytes;
  194689. if (row_info->bit_depth == 1)
  194690. table = (png_bytep)onebppswaptable;
  194691. else if (row_info->bit_depth == 2)
  194692. table = (png_bytep)twobppswaptable;
  194693. else if (row_info->bit_depth == 4)
  194694. table = (png_bytep)fourbppswaptable;
  194695. else
  194696. return;
  194697. for (rp = row; rp < end; rp++)
  194698. *rp = table[*rp];
  194699. }
  194700. }
  194701. #endif /* PNG_READ_PACKSWAP_SUPPORTED or PNG_WRITE_PACKSWAP_SUPPORTED */
  194702. #if defined(PNG_WRITE_FILLER_SUPPORTED) || \
  194703. defined(PNG_READ_STRIP_ALPHA_SUPPORTED)
  194704. /* remove filler or alpha byte(s) */
  194705. void /* PRIVATE */
  194706. png_do_strip_filler(png_row_infop row_info, png_bytep row, png_uint_32 flags)
  194707. {
  194708. png_debug(1, "in png_do_strip_filler\n");
  194709. #if defined(PNG_USELESS_TESTS_SUPPORTED)
  194710. if (row != NULL && row_info != NULL)
  194711. #endif
  194712. {
  194713. png_bytep sp=row;
  194714. png_bytep dp=row;
  194715. png_uint_32 row_width=row_info->width;
  194716. png_uint_32 i;
  194717. if ((row_info->color_type == PNG_COLOR_TYPE_RGB ||
  194718. (row_info->color_type == PNG_COLOR_TYPE_RGB_ALPHA &&
  194719. (flags & PNG_FLAG_STRIP_ALPHA))) &&
  194720. row_info->channels == 4)
  194721. {
  194722. if (row_info->bit_depth == 8)
  194723. {
  194724. /* This converts from RGBX or RGBA to RGB */
  194725. if (flags & PNG_FLAG_FILLER_AFTER)
  194726. {
  194727. dp+=3; sp+=4;
  194728. for (i = 1; i < row_width; i++)
  194729. {
  194730. *dp++ = *sp++;
  194731. *dp++ = *sp++;
  194732. *dp++ = *sp++;
  194733. sp++;
  194734. }
  194735. }
  194736. /* This converts from XRGB or ARGB to RGB */
  194737. else
  194738. {
  194739. for (i = 0; i < row_width; i++)
  194740. {
  194741. sp++;
  194742. *dp++ = *sp++;
  194743. *dp++ = *sp++;
  194744. *dp++ = *sp++;
  194745. }
  194746. }
  194747. row_info->pixel_depth = 24;
  194748. row_info->rowbytes = row_width * 3;
  194749. }
  194750. else /* if (row_info->bit_depth == 16) */
  194751. {
  194752. if (flags & PNG_FLAG_FILLER_AFTER)
  194753. {
  194754. /* This converts from RRGGBBXX or RRGGBBAA to RRGGBB */
  194755. sp += 8; dp += 6;
  194756. for (i = 1; i < row_width; i++)
  194757. {
  194758. /* This could be (although png_memcpy is probably slower):
  194759. png_memcpy(dp, sp, 6);
  194760. sp += 8;
  194761. dp += 6;
  194762. */
  194763. *dp++ = *sp++;
  194764. *dp++ = *sp++;
  194765. *dp++ = *sp++;
  194766. *dp++ = *sp++;
  194767. *dp++ = *sp++;
  194768. *dp++ = *sp++;
  194769. sp += 2;
  194770. }
  194771. }
  194772. else
  194773. {
  194774. /* This converts from XXRRGGBB or AARRGGBB to RRGGBB */
  194775. for (i = 0; i < row_width; i++)
  194776. {
  194777. /* This could be (although png_memcpy is probably slower):
  194778. png_memcpy(dp, sp, 6);
  194779. sp += 8;
  194780. dp += 6;
  194781. */
  194782. sp+=2;
  194783. *dp++ = *sp++;
  194784. *dp++ = *sp++;
  194785. *dp++ = *sp++;
  194786. *dp++ = *sp++;
  194787. *dp++ = *sp++;
  194788. *dp++ = *sp++;
  194789. }
  194790. }
  194791. row_info->pixel_depth = 48;
  194792. row_info->rowbytes = row_width * 6;
  194793. }
  194794. row_info->channels = 3;
  194795. }
  194796. else if ((row_info->color_type == PNG_COLOR_TYPE_GRAY ||
  194797. (row_info->color_type == PNG_COLOR_TYPE_GRAY_ALPHA &&
  194798. (flags & PNG_FLAG_STRIP_ALPHA))) &&
  194799. row_info->channels == 2)
  194800. {
  194801. if (row_info->bit_depth == 8)
  194802. {
  194803. /* This converts from GX or GA to G */
  194804. if (flags & PNG_FLAG_FILLER_AFTER)
  194805. {
  194806. for (i = 0; i < row_width; i++)
  194807. {
  194808. *dp++ = *sp++;
  194809. sp++;
  194810. }
  194811. }
  194812. /* This converts from XG or AG to G */
  194813. else
  194814. {
  194815. for (i = 0; i < row_width; i++)
  194816. {
  194817. sp++;
  194818. *dp++ = *sp++;
  194819. }
  194820. }
  194821. row_info->pixel_depth = 8;
  194822. row_info->rowbytes = row_width;
  194823. }
  194824. else /* if (row_info->bit_depth == 16) */
  194825. {
  194826. if (flags & PNG_FLAG_FILLER_AFTER)
  194827. {
  194828. /* This converts from GGXX or GGAA to GG */
  194829. sp += 4; dp += 2;
  194830. for (i = 1; i < row_width; i++)
  194831. {
  194832. *dp++ = *sp++;
  194833. *dp++ = *sp++;
  194834. sp += 2;
  194835. }
  194836. }
  194837. else
  194838. {
  194839. /* This converts from XXGG or AAGG to GG */
  194840. for (i = 0; i < row_width; i++)
  194841. {
  194842. sp += 2;
  194843. *dp++ = *sp++;
  194844. *dp++ = *sp++;
  194845. }
  194846. }
  194847. row_info->pixel_depth = 16;
  194848. row_info->rowbytes = row_width * 2;
  194849. }
  194850. row_info->channels = 1;
  194851. }
  194852. if (flags & PNG_FLAG_STRIP_ALPHA)
  194853. row_info->color_type &= ~PNG_COLOR_MASK_ALPHA;
  194854. }
  194855. }
  194856. #endif
  194857. #if defined(PNG_READ_BGR_SUPPORTED) || defined(PNG_WRITE_BGR_SUPPORTED)
  194858. /* swaps red and blue bytes within a pixel */
  194859. void /* PRIVATE */
  194860. png_do_bgr(png_row_infop row_info, png_bytep row)
  194861. {
  194862. png_debug(1, "in png_do_bgr\n");
  194863. if (
  194864. #if defined(PNG_USELESS_TESTS_SUPPORTED)
  194865. row != NULL && row_info != NULL &&
  194866. #endif
  194867. (row_info->color_type & PNG_COLOR_MASK_COLOR))
  194868. {
  194869. png_uint_32 row_width = row_info->width;
  194870. if (row_info->bit_depth == 8)
  194871. {
  194872. if (row_info->color_type == PNG_COLOR_TYPE_RGB)
  194873. {
  194874. png_bytep rp;
  194875. png_uint_32 i;
  194876. for (i = 0, rp = row; i < row_width; i++, rp += 3)
  194877. {
  194878. png_byte save = *rp;
  194879. *rp = *(rp + 2);
  194880. *(rp + 2) = save;
  194881. }
  194882. }
  194883. else if (row_info->color_type == PNG_COLOR_TYPE_RGB_ALPHA)
  194884. {
  194885. png_bytep rp;
  194886. png_uint_32 i;
  194887. for (i = 0, rp = row; i < row_width; i++, rp += 4)
  194888. {
  194889. png_byte save = *rp;
  194890. *rp = *(rp + 2);
  194891. *(rp + 2) = save;
  194892. }
  194893. }
  194894. }
  194895. else if (row_info->bit_depth == 16)
  194896. {
  194897. if (row_info->color_type == PNG_COLOR_TYPE_RGB)
  194898. {
  194899. png_bytep rp;
  194900. png_uint_32 i;
  194901. for (i = 0, rp = row; i < row_width; i++, rp += 6)
  194902. {
  194903. png_byte save = *rp;
  194904. *rp = *(rp + 4);
  194905. *(rp + 4) = save;
  194906. save = *(rp + 1);
  194907. *(rp + 1) = *(rp + 5);
  194908. *(rp + 5) = save;
  194909. }
  194910. }
  194911. else if (row_info->color_type == PNG_COLOR_TYPE_RGB_ALPHA)
  194912. {
  194913. png_bytep rp;
  194914. png_uint_32 i;
  194915. for (i = 0, rp = row; i < row_width; i++, rp += 8)
  194916. {
  194917. png_byte save = *rp;
  194918. *rp = *(rp + 4);
  194919. *(rp + 4) = save;
  194920. save = *(rp + 1);
  194921. *(rp + 1) = *(rp + 5);
  194922. *(rp + 5) = save;
  194923. }
  194924. }
  194925. }
  194926. }
  194927. }
  194928. #endif /* PNG_READ_BGR_SUPPORTED or PNG_WRITE_BGR_SUPPORTED */
  194929. #if defined(PNG_READ_USER_TRANSFORM_SUPPORTED) || \
  194930. defined(PNG_WRITE_USER_TRANSFORM_SUPPORTED) || \
  194931. defined(PNG_LEGACY_SUPPORTED)
  194932. void PNGAPI
  194933. png_set_user_transform_info(png_structp png_ptr, png_voidp
  194934. user_transform_ptr, int user_transform_depth, int user_transform_channels)
  194935. {
  194936. png_debug(1, "in png_set_user_transform_info\n");
  194937. if(png_ptr == NULL) return;
  194938. #if defined(PNG_USER_TRANSFORM_PTR_SUPPORTED)
  194939. png_ptr->user_transform_ptr = user_transform_ptr;
  194940. png_ptr->user_transform_depth = (png_byte)user_transform_depth;
  194941. png_ptr->user_transform_channels = (png_byte)user_transform_channels;
  194942. #else
  194943. if(user_transform_ptr || user_transform_depth || user_transform_channels)
  194944. png_warning(png_ptr,
  194945. "This version of libpng does not support user transform info");
  194946. #endif
  194947. }
  194948. #endif
  194949. /* This function returns a pointer to the user_transform_ptr associated with
  194950. * the user transform functions. The application should free any memory
  194951. * associated with this pointer before png_write_destroy and png_read_destroy
  194952. * are called.
  194953. */
  194954. png_voidp PNGAPI
  194955. png_get_user_transform_ptr(png_structp png_ptr)
  194956. {
  194957. #if defined(PNG_USER_TRANSFORM_PTR_SUPPORTED)
  194958. if (png_ptr == NULL) return (NULL);
  194959. return ((png_voidp)png_ptr->user_transform_ptr);
  194960. #else
  194961. return (NULL);
  194962. #endif
  194963. }
  194964. #endif /* PNG_READ_SUPPORTED || PNG_WRITE_SUPPORTED */
  194965. /*** End of inlined file: pngtrans.c ***/
  194966. /*** Start of inlined file: pngwio.c ***/
  194967. /* pngwio.c - functions for data output
  194968. *
  194969. * Last changed in libpng 1.2.13 November 13, 2006
  194970. * For conditions of distribution and use, see copyright notice in png.h
  194971. * Copyright (c) 1998-2006 Glenn Randers-Pehrson
  194972. * (Version 0.96 Copyright (c) 1996, 1997 Andreas Dilger)
  194973. * (Version 0.88 Copyright (c) 1995, 1996 Guy Eric Schalnat, Group 42, Inc.)
  194974. *
  194975. * This file provides a location for all output. Users who need
  194976. * special handling are expected to write functions that have the same
  194977. * arguments as these and perform similar functions, but that possibly
  194978. * use different output methods. Note that you shouldn't change these
  194979. * functions, but rather write replacement functions and then change
  194980. * them at run time with png_set_write_fn(...).
  194981. */
  194982. #define PNG_INTERNAL
  194983. #ifdef PNG_WRITE_SUPPORTED
  194984. /* Write the data to whatever output you are using. The default routine
  194985. writes to a file pointer. Note that this routine sometimes gets called
  194986. with very small lengths, so you should implement some kind of simple
  194987. buffering if you are using unbuffered writes. This should never be asked
  194988. to write more than 64K on a 16 bit machine. */
  194989. void /* PRIVATE */
  194990. png_write_data(png_structp png_ptr, png_bytep data, png_size_t length)
  194991. {
  194992. if (png_ptr->write_data_fn != NULL )
  194993. (*(png_ptr->write_data_fn))(png_ptr, data, length);
  194994. else
  194995. png_error(png_ptr, "Call to NULL write function");
  194996. }
  194997. #if !defined(PNG_NO_STDIO)
  194998. /* This is the function that does the actual writing of data. If you are
  194999. not writing to a standard C stream, you should create a replacement
  195000. write_data function and use it at run time with png_set_write_fn(), rather
  195001. than changing the library. */
  195002. #ifndef USE_FAR_KEYWORD
  195003. void PNGAPI
  195004. png_default_write_data(png_structp png_ptr, png_bytep data, png_size_t length)
  195005. {
  195006. png_uint_32 check;
  195007. if(png_ptr == NULL) return;
  195008. #if defined(_WIN32_WCE)
  195009. if ( !WriteFile((HANDLE)(png_ptr->io_ptr), data, length, &check, NULL) )
  195010. check = 0;
  195011. #else
  195012. check = fwrite(data, 1, length, (png_FILE_p)(png_ptr->io_ptr));
  195013. #endif
  195014. if (check != length)
  195015. png_error(png_ptr, "Write Error");
  195016. }
  195017. #else
  195018. /* this is the model-independent version. Since the standard I/O library
  195019. can't handle far buffers in the medium and small models, we have to copy
  195020. the data.
  195021. */
  195022. #define NEAR_BUF_SIZE 1024
  195023. #define MIN(a,b) (a <= b ? a : b)
  195024. void PNGAPI
  195025. png_default_write_data(png_structp png_ptr, png_bytep data, png_size_t length)
  195026. {
  195027. png_uint_32 check;
  195028. png_byte *near_data; /* Needs to be "png_byte *" instead of "png_bytep" */
  195029. png_FILE_p io_ptr;
  195030. if(png_ptr == NULL) return;
  195031. /* Check if data really is near. If so, use usual code. */
  195032. near_data = (png_byte *)CVT_PTR_NOCHECK(data);
  195033. io_ptr = (png_FILE_p)CVT_PTR(png_ptr->io_ptr);
  195034. if ((png_bytep)near_data == data)
  195035. {
  195036. #if defined(_WIN32_WCE)
  195037. if ( !WriteFile(io_ptr, near_data, length, &check, NULL) )
  195038. check = 0;
  195039. #else
  195040. check = fwrite(near_data, 1, length, io_ptr);
  195041. #endif
  195042. }
  195043. else
  195044. {
  195045. png_byte buf[NEAR_BUF_SIZE];
  195046. png_size_t written, remaining, err;
  195047. check = 0;
  195048. remaining = length;
  195049. do
  195050. {
  195051. written = MIN(NEAR_BUF_SIZE, remaining);
  195052. png_memcpy(buf, data, written); /* copy far buffer to near buffer */
  195053. #if defined(_WIN32_WCE)
  195054. if ( !WriteFile(io_ptr, buf, written, &err, NULL) )
  195055. err = 0;
  195056. #else
  195057. err = fwrite(buf, 1, written, io_ptr);
  195058. #endif
  195059. if (err != written)
  195060. break;
  195061. else
  195062. check += err;
  195063. data += written;
  195064. remaining -= written;
  195065. }
  195066. while (remaining != 0);
  195067. }
  195068. if (check != length)
  195069. png_error(png_ptr, "Write Error");
  195070. }
  195071. #endif
  195072. #endif
  195073. /* This function is called to output any data pending writing (normally
  195074. to disk). After png_flush is called, there should be no data pending
  195075. writing in any buffers. */
  195076. #if defined(PNG_WRITE_FLUSH_SUPPORTED)
  195077. void /* PRIVATE */
  195078. png_flush(png_structp png_ptr)
  195079. {
  195080. if (png_ptr->output_flush_fn != NULL)
  195081. (*(png_ptr->output_flush_fn))(png_ptr);
  195082. }
  195083. #if !defined(PNG_NO_STDIO)
  195084. void PNGAPI
  195085. png_default_flush(png_structp png_ptr)
  195086. {
  195087. #if !defined(_WIN32_WCE)
  195088. png_FILE_p io_ptr;
  195089. #endif
  195090. if(png_ptr == NULL) return;
  195091. #if !defined(_WIN32_WCE)
  195092. io_ptr = (png_FILE_p)CVT_PTR((png_ptr->io_ptr));
  195093. if (io_ptr != NULL)
  195094. fflush(io_ptr);
  195095. #endif
  195096. }
  195097. #endif
  195098. #endif
  195099. /* This function allows the application to supply new output functions for
  195100. libpng if standard C streams aren't being used.
  195101. This function takes as its arguments:
  195102. png_ptr - pointer to a png output data structure
  195103. io_ptr - pointer to user supplied structure containing info about
  195104. the output functions. May be NULL.
  195105. write_data_fn - pointer to a new output function that takes as its
  195106. arguments a pointer to a png_struct, a pointer to
  195107. data to be written, and a 32-bit unsigned int that is
  195108. the number of bytes to be written. The new write
  195109. function should call png_error(png_ptr, "Error msg")
  195110. to exit and output any fatal error messages.
  195111. flush_data_fn - pointer to a new flush function that takes as its
  195112. arguments a pointer to a png_struct. After a call to
  195113. the flush function, there should be no data in any buffers
  195114. or pending transmission. If the output method doesn't do
  195115. any buffering of ouput, a function prototype must still be
  195116. supplied although it doesn't have to do anything. If
  195117. PNG_WRITE_FLUSH_SUPPORTED is not defined at libpng compile
  195118. time, output_flush_fn will be ignored, although it must be
  195119. supplied for compatibility. */
  195120. void PNGAPI
  195121. png_set_write_fn(png_structp png_ptr, png_voidp io_ptr,
  195122. png_rw_ptr write_data_fn, png_flush_ptr output_flush_fn)
  195123. {
  195124. if(png_ptr == NULL) return;
  195125. png_ptr->io_ptr = io_ptr;
  195126. #if !defined(PNG_NO_STDIO)
  195127. if (write_data_fn != NULL)
  195128. png_ptr->write_data_fn = write_data_fn;
  195129. else
  195130. png_ptr->write_data_fn = png_default_write_data;
  195131. #else
  195132. png_ptr->write_data_fn = write_data_fn;
  195133. #endif
  195134. #if defined(PNG_WRITE_FLUSH_SUPPORTED)
  195135. #if !defined(PNG_NO_STDIO)
  195136. if (output_flush_fn != NULL)
  195137. png_ptr->output_flush_fn = output_flush_fn;
  195138. else
  195139. png_ptr->output_flush_fn = png_default_flush;
  195140. #else
  195141. png_ptr->output_flush_fn = output_flush_fn;
  195142. #endif
  195143. #endif /* PNG_WRITE_FLUSH_SUPPORTED */
  195144. /* It is an error to read while writing a png file */
  195145. if (png_ptr->read_data_fn != NULL)
  195146. {
  195147. png_ptr->read_data_fn = NULL;
  195148. png_warning(png_ptr,
  195149. "Attempted to set both read_data_fn and write_data_fn in");
  195150. png_warning(png_ptr,
  195151. "the same structure. Resetting read_data_fn to NULL.");
  195152. }
  195153. }
  195154. #if defined(USE_FAR_KEYWORD)
  195155. #if defined(_MSC_VER)
  195156. void *png_far_to_near(png_structp png_ptr,png_voidp ptr, int check)
  195157. {
  195158. void *near_ptr;
  195159. void FAR *far_ptr;
  195160. FP_OFF(near_ptr) = FP_OFF(ptr);
  195161. far_ptr = (void FAR *)near_ptr;
  195162. if(check != 0)
  195163. if(FP_SEG(ptr) != FP_SEG(far_ptr))
  195164. png_error(png_ptr,"segment lost in conversion");
  195165. return(near_ptr);
  195166. }
  195167. # else
  195168. void *png_far_to_near(png_structp png_ptr,png_voidp ptr, int check)
  195169. {
  195170. void *near_ptr;
  195171. void FAR *far_ptr;
  195172. near_ptr = (void FAR *)ptr;
  195173. far_ptr = (void FAR *)near_ptr;
  195174. if(check != 0)
  195175. if(far_ptr != ptr)
  195176. png_error(png_ptr,"segment lost in conversion");
  195177. return(near_ptr);
  195178. }
  195179. # endif
  195180. # endif
  195181. #endif /* PNG_WRITE_SUPPORTED */
  195182. /*** End of inlined file: pngwio.c ***/
  195183. /*** Start of inlined file: pngwrite.c ***/
  195184. /* pngwrite.c - general routines to write a PNG file
  195185. *
  195186. * Last changed in libpng 1.2.15 January 5, 2007
  195187. * For conditions of distribution and use, see copyright notice in png.h
  195188. * Copyright (c) 1998-2007 Glenn Randers-Pehrson
  195189. * (Version 0.96 Copyright (c) 1996, 1997 Andreas Dilger)
  195190. * (Version 0.88 Copyright (c) 1995, 1996 Guy Eric Schalnat, Group 42, Inc.)
  195191. */
  195192. /* get internal access to png.h */
  195193. #define PNG_INTERNAL
  195194. #ifdef PNG_WRITE_SUPPORTED
  195195. /* Writes all the PNG information. This is the suggested way to use the
  195196. * library. If you have a new chunk to add, make a function to write it,
  195197. * and put it in the correct location here. If you want the chunk written
  195198. * after the image data, put it in png_write_end(). I strongly encourage
  195199. * you to supply a PNG_INFO_ flag, and check info_ptr->valid before writing
  195200. * the chunk, as that will keep the code from breaking if you want to just
  195201. * write a plain PNG file. If you have long comments, I suggest writing
  195202. * them in png_write_end(), and compressing them.
  195203. */
  195204. void PNGAPI
  195205. png_write_info_before_PLTE(png_structp png_ptr, png_infop info_ptr)
  195206. {
  195207. png_debug(1, "in png_write_info_before_PLTE\n");
  195208. if (png_ptr == NULL || info_ptr == NULL)
  195209. return;
  195210. if (!(png_ptr->mode & PNG_WROTE_INFO_BEFORE_PLTE))
  195211. {
  195212. png_write_sig(png_ptr); /* write PNG signature */
  195213. #if defined(PNG_MNG_FEATURES_SUPPORTED)
  195214. if((png_ptr->mode&PNG_HAVE_PNG_SIGNATURE)&&(png_ptr->mng_features_permitted))
  195215. {
  195216. png_warning(png_ptr,"MNG features are not allowed in a PNG datastream");
  195217. png_ptr->mng_features_permitted=0;
  195218. }
  195219. #endif
  195220. /* write IHDR information. */
  195221. png_write_IHDR(png_ptr, info_ptr->width, info_ptr->height,
  195222. info_ptr->bit_depth, info_ptr->color_type, info_ptr->compression_type,
  195223. info_ptr->filter_type,
  195224. #if defined(PNG_WRITE_INTERLACING_SUPPORTED)
  195225. info_ptr->interlace_type);
  195226. #else
  195227. 0);
  195228. #endif
  195229. /* the rest of these check to see if the valid field has the appropriate
  195230. flag set, and if it does, writes the chunk. */
  195231. #if defined(PNG_WRITE_gAMA_SUPPORTED)
  195232. if (info_ptr->valid & PNG_INFO_gAMA)
  195233. {
  195234. # ifdef PNG_FLOATING_POINT_SUPPORTED
  195235. png_write_gAMA(png_ptr, info_ptr->gamma);
  195236. #else
  195237. #ifdef PNG_FIXED_POINT_SUPPORTED
  195238. png_write_gAMA_fixed(png_ptr, info_ptr->int_gamma);
  195239. # endif
  195240. #endif
  195241. }
  195242. #endif
  195243. #if defined(PNG_WRITE_sRGB_SUPPORTED)
  195244. if (info_ptr->valid & PNG_INFO_sRGB)
  195245. png_write_sRGB(png_ptr, (int)info_ptr->srgb_intent);
  195246. #endif
  195247. #if defined(PNG_WRITE_iCCP_SUPPORTED)
  195248. if (info_ptr->valid & PNG_INFO_iCCP)
  195249. png_write_iCCP(png_ptr, info_ptr->iccp_name, PNG_COMPRESSION_TYPE_BASE,
  195250. info_ptr->iccp_profile, (int)info_ptr->iccp_proflen);
  195251. #endif
  195252. #if defined(PNG_WRITE_sBIT_SUPPORTED)
  195253. if (info_ptr->valid & PNG_INFO_sBIT)
  195254. png_write_sBIT(png_ptr, &(info_ptr->sig_bit), info_ptr->color_type);
  195255. #endif
  195256. #if defined(PNG_WRITE_cHRM_SUPPORTED)
  195257. if (info_ptr->valid & PNG_INFO_cHRM)
  195258. {
  195259. #ifdef PNG_FLOATING_POINT_SUPPORTED
  195260. png_write_cHRM(png_ptr,
  195261. info_ptr->x_white, info_ptr->y_white,
  195262. info_ptr->x_red, info_ptr->y_red,
  195263. info_ptr->x_green, info_ptr->y_green,
  195264. info_ptr->x_blue, info_ptr->y_blue);
  195265. #else
  195266. # ifdef PNG_FIXED_POINT_SUPPORTED
  195267. png_write_cHRM_fixed(png_ptr,
  195268. info_ptr->int_x_white, info_ptr->int_y_white,
  195269. info_ptr->int_x_red, info_ptr->int_y_red,
  195270. info_ptr->int_x_green, info_ptr->int_y_green,
  195271. info_ptr->int_x_blue, info_ptr->int_y_blue);
  195272. # endif
  195273. #endif
  195274. }
  195275. #endif
  195276. #if defined(PNG_WRITE_UNKNOWN_CHUNKS_SUPPORTED)
  195277. if (info_ptr->unknown_chunks_num)
  195278. {
  195279. png_unknown_chunk *up;
  195280. png_debug(5, "writing extra chunks\n");
  195281. for (up = info_ptr->unknown_chunks;
  195282. up < info_ptr->unknown_chunks + info_ptr->unknown_chunks_num;
  195283. up++)
  195284. {
  195285. int keep=png_handle_as_unknown(png_ptr, up->name);
  195286. if (keep != PNG_HANDLE_CHUNK_NEVER &&
  195287. up->location && !(up->location & PNG_HAVE_PLTE) &&
  195288. !(up->location & PNG_HAVE_IDAT) &&
  195289. ((up->name[3] & 0x20) || keep == PNG_HANDLE_CHUNK_ALWAYS ||
  195290. (png_ptr->flags & PNG_FLAG_KEEP_UNSAFE_CHUNKS)))
  195291. {
  195292. png_write_chunk(png_ptr, up->name, up->data, up->size);
  195293. }
  195294. }
  195295. }
  195296. #endif
  195297. png_ptr->mode |= PNG_WROTE_INFO_BEFORE_PLTE;
  195298. }
  195299. }
  195300. void PNGAPI
  195301. png_write_info(png_structp png_ptr, png_infop info_ptr)
  195302. {
  195303. #if defined(PNG_WRITE_TEXT_SUPPORTED) || defined(PNG_WRITE_sPLT_SUPPORTED)
  195304. int i;
  195305. #endif
  195306. png_debug(1, "in png_write_info\n");
  195307. if (png_ptr == NULL || info_ptr == NULL)
  195308. return;
  195309. png_write_info_before_PLTE(png_ptr, info_ptr);
  195310. if (info_ptr->valid & PNG_INFO_PLTE)
  195311. png_write_PLTE(png_ptr, info_ptr->palette,
  195312. (png_uint_32)info_ptr->num_palette);
  195313. else if (info_ptr->color_type == PNG_COLOR_TYPE_PALETTE)
  195314. png_error(png_ptr, "Valid palette required for paletted images");
  195315. #if defined(PNG_WRITE_tRNS_SUPPORTED)
  195316. if (info_ptr->valid & PNG_INFO_tRNS)
  195317. {
  195318. #if defined(PNG_WRITE_INVERT_ALPHA_SUPPORTED)
  195319. /* invert the alpha channel (in tRNS) */
  195320. if ((png_ptr->transformations & PNG_INVERT_ALPHA) &&
  195321. info_ptr->color_type == PNG_COLOR_TYPE_PALETTE)
  195322. {
  195323. int j;
  195324. for (j=0; j<(int)info_ptr->num_trans; j++)
  195325. info_ptr->trans[j] = (png_byte)(255 - info_ptr->trans[j]);
  195326. }
  195327. #endif
  195328. png_write_tRNS(png_ptr, info_ptr->trans, &(info_ptr->trans_values),
  195329. info_ptr->num_trans, info_ptr->color_type);
  195330. }
  195331. #endif
  195332. #if defined(PNG_WRITE_bKGD_SUPPORTED)
  195333. if (info_ptr->valid & PNG_INFO_bKGD)
  195334. png_write_bKGD(png_ptr, &(info_ptr->background), info_ptr->color_type);
  195335. #endif
  195336. #if defined(PNG_WRITE_hIST_SUPPORTED)
  195337. if (info_ptr->valid & PNG_INFO_hIST)
  195338. png_write_hIST(png_ptr, info_ptr->hist, info_ptr->num_palette);
  195339. #endif
  195340. #if defined(PNG_WRITE_oFFs_SUPPORTED)
  195341. if (info_ptr->valid & PNG_INFO_oFFs)
  195342. png_write_oFFs(png_ptr, info_ptr->x_offset, info_ptr->y_offset,
  195343. info_ptr->offset_unit_type);
  195344. #endif
  195345. #if defined(PNG_WRITE_pCAL_SUPPORTED)
  195346. if (info_ptr->valid & PNG_INFO_pCAL)
  195347. png_write_pCAL(png_ptr, info_ptr->pcal_purpose, info_ptr->pcal_X0,
  195348. info_ptr->pcal_X1, info_ptr->pcal_type, info_ptr->pcal_nparams,
  195349. info_ptr->pcal_units, info_ptr->pcal_params);
  195350. #endif
  195351. #if defined(PNG_WRITE_sCAL_SUPPORTED)
  195352. if (info_ptr->valid & PNG_INFO_sCAL)
  195353. #if defined(PNG_FLOATING_POINT_SUPPORTED) && !defined(PNG_NO_STDIO)
  195354. png_write_sCAL(png_ptr, (int)info_ptr->scal_unit,
  195355. info_ptr->scal_pixel_width, info_ptr->scal_pixel_height);
  195356. #else
  195357. #ifdef PNG_FIXED_POINT_SUPPORTED
  195358. png_write_sCAL_s(png_ptr, (int)info_ptr->scal_unit,
  195359. info_ptr->scal_s_width, info_ptr->scal_s_height);
  195360. #else
  195361. png_warning(png_ptr,
  195362. "png_write_sCAL not supported; sCAL chunk not written.");
  195363. #endif
  195364. #endif
  195365. #endif
  195366. #if defined(PNG_WRITE_pHYs_SUPPORTED)
  195367. if (info_ptr->valid & PNG_INFO_pHYs)
  195368. png_write_pHYs(png_ptr, info_ptr->x_pixels_per_unit,
  195369. info_ptr->y_pixels_per_unit, info_ptr->phys_unit_type);
  195370. #endif
  195371. #if defined(PNG_WRITE_tIME_SUPPORTED)
  195372. if (info_ptr->valid & PNG_INFO_tIME)
  195373. {
  195374. png_write_tIME(png_ptr, &(info_ptr->mod_time));
  195375. png_ptr->mode |= PNG_WROTE_tIME;
  195376. }
  195377. #endif
  195378. #if defined(PNG_WRITE_sPLT_SUPPORTED)
  195379. if (info_ptr->valid & PNG_INFO_sPLT)
  195380. for (i = 0; i < (int)info_ptr->splt_palettes_num; i++)
  195381. png_write_sPLT(png_ptr, info_ptr->splt_palettes + i);
  195382. #endif
  195383. #if defined(PNG_WRITE_TEXT_SUPPORTED)
  195384. /* Check to see if we need to write text chunks */
  195385. for (i = 0; i < info_ptr->num_text; i++)
  195386. {
  195387. png_debug2(2, "Writing header text chunk %d, type %d\n", i,
  195388. info_ptr->text[i].compression);
  195389. /* an internationalized chunk? */
  195390. if (info_ptr->text[i].compression > 0)
  195391. {
  195392. #if defined(PNG_WRITE_iTXt_SUPPORTED)
  195393. /* write international chunk */
  195394. png_write_iTXt(png_ptr,
  195395. info_ptr->text[i].compression,
  195396. info_ptr->text[i].key,
  195397. info_ptr->text[i].lang,
  195398. info_ptr->text[i].lang_key,
  195399. info_ptr->text[i].text);
  195400. #else
  195401. png_warning(png_ptr, "Unable to write international text");
  195402. #endif
  195403. /* Mark this chunk as written */
  195404. info_ptr->text[i].compression = PNG_TEXT_COMPRESSION_NONE_WR;
  195405. }
  195406. /* If we want a compressed text chunk */
  195407. else if (info_ptr->text[i].compression == PNG_TEXT_COMPRESSION_zTXt)
  195408. {
  195409. #if defined(PNG_WRITE_zTXt_SUPPORTED)
  195410. /* write compressed chunk */
  195411. png_write_zTXt(png_ptr, info_ptr->text[i].key,
  195412. info_ptr->text[i].text, 0,
  195413. info_ptr->text[i].compression);
  195414. #else
  195415. png_warning(png_ptr, "Unable to write compressed text");
  195416. #endif
  195417. /* Mark this chunk as written */
  195418. info_ptr->text[i].compression = PNG_TEXT_COMPRESSION_zTXt_WR;
  195419. }
  195420. else if (info_ptr->text[i].compression == PNG_TEXT_COMPRESSION_NONE)
  195421. {
  195422. #if defined(PNG_WRITE_tEXt_SUPPORTED)
  195423. /* write uncompressed chunk */
  195424. png_write_tEXt(png_ptr, info_ptr->text[i].key,
  195425. info_ptr->text[i].text,
  195426. 0);
  195427. #else
  195428. png_warning(png_ptr, "Unable to write uncompressed text");
  195429. #endif
  195430. /* Mark this chunk as written */
  195431. info_ptr->text[i].compression = PNG_TEXT_COMPRESSION_NONE_WR;
  195432. }
  195433. }
  195434. #endif
  195435. #if defined(PNG_WRITE_UNKNOWN_CHUNKS_SUPPORTED)
  195436. if (info_ptr->unknown_chunks_num)
  195437. {
  195438. png_unknown_chunk *up;
  195439. png_debug(5, "writing extra chunks\n");
  195440. for (up = info_ptr->unknown_chunks;
  195441. up < info_ptr->unknown_chunks + info_ptr->unknown_chunks_num;
  195442. up++)
  195443. {
  195444. int keep=png_handle_as_unknown(png_ptr, up->name);
  195445. if (keep != PNG_HANDLE_CHUNK_NEVER &&
  195446. up->location && (up->location & PNG_HAVE_PLTE) &&
  195447. !(up->location & PNG_HAVE_IDAT) &&
  195448. ((up->name[3] & 0x20) || keep == PNG_HANDLE_CHUNK_ALWAYS ||
  195449. (png_ptr->flags & PNG_FLAG_KEEP_UNSAFE_CHUNKS)))
  195450. {
  195451. png_write_chunk(png_ptr, up->name, up->data, up->size);
  195452. }
  195453. }
  195454. }
  195455. #endif
  195456. }
  195457. /* Writes the end of the PNG file. If you don't want to write comments or
  195458. * time information, you can pass NULL for info. If you already wrote these
  195459. * in png_write_info(), do not write them again here. If you have long
  195460. * comments, I suggest writing them here, and compressing them.
  195461. */
  195462. void PNGAPI
  195463. png_write_end(png_structp png_ptr, png_infop info_ptr)
  195464. {
  195465. png_debug(1, "in png_write_end\n");
  195466. if (png_ptr == NULL)
  195467. return;
  195468. if (!(png_ptr->mode & PNG_HAVE_IDAT))
  195469. png_error(png_ptr, "No IDATs written into file");
  195470. /* see if user wants us to write information chunks */
  195471. if (info_ptr != NULL)
  195472. {
  195473. #if defined(PNG_WRITE_TEXT_SUPPORTED)
  195474. int i; /* local index variable */
  195475. #endif
  195476. #if defined(PNG_WRITE_tIME_SUPPORTED)
  195477. /* check to see if user has supplied a time chunk */
  195478. if ((info_ptr->valid & PNG_INFO_tIME) &&
  195479. !(png_ptr->mode & PNG_WROTE_tIME))
  195480. png_write_tIME(png_ptr, &(info_ptr->mod_time));
  195481. #endif
  195482. #if defined(PNG_WRITE_TEXT_SUPPORTED)
  195483. /* loop through comment chunks */
  195484. for (i = 0; i < info_ptr->num_text; i++)
  195485. {
  195486. png_debug2(2, "Writing trailer text chunk %d, type %d\n", i,
  195487. info_ptr->text[i].compression);
  195488. /* an internationalized chunk? */
  195489. if (info_ptr->text[i].compression > 0)
  195490. {
  195491. #if defined(PNG_WRITE_iTXt_SUPPORTED)
  195492. /* write international chunk */
  195493. png_write_iTXt(png_ptr,
  195494. info_ptr->text[i].compression,
  195495. info_ptr->text[i].key,
  195496. info_ptr->text[i].lang,
  195497. info_ptr->text[i].lang_key,
  195498. info_ptr->text[i].text);
  195499. #else
  195500. png_warning(png_ptr, "Unable to write international text");
  195501. #endif
  195502. /* Mark this chunk as written */
  195503. info_ptr->text[i].compression = PNG_TEXT_COMPRESSION_NONE_WR;
  195504. }
  195505. else if (info_ptr->text[i].compression >= PNG_TEXT_COMPRESSION_zTXt)
  195506. {
  195507. #if defined(PNG_WRITE_zTXt_SUPPORTED)
  195508. /* write compressed chunk */
  195509. png_write_zTXt(png_ptr, info_ptr->text[i].key,
  195510. info_ptr->text[i].text, 0,
  195511. info_ptr->text[i].compression);
  195512. #else
  195513. png_warning(png_ptr, "Unable to write compressed text");
  195514. #endif
  195515. /* Mark this chunk as written */
  195516. info_ptr->text[i].compression = PNG_TEXT_COMPRESSION_zTXt_WR;
  195517. }
  195518. else if (info_ptr->text[i].compression == PNG_TEXT_COMPRESSION_NONE)
  195519. {
  195520. #if defined(PNG_WRITE_tEXt_SUPPORTED)
  195521. /* write uncompressed chunk */
  195522. png_write_tEXt(png_ptr, info_ptr->text[i].key,
  195523. info_ptr->text[i].text, 0);
  195524. #else
  195525. png_warning(png_ptr, "Unable to write uncompressed text");
  195526. #endif
  195527. /* Mark this chunk as written */
  195528. info_ptr->text[i].compression = PNG_TEXT_COMPRESSION_NONE_WR;
  195529. }
  195530. }
  195531. #endif
  195532. #if defined(PNG_WRITE_UNKNOWN_CHUNKS_SUPPORTED)
  195533. if (info_ptr->unknown_chunks_num)
  195534. {
  195535. png_unknown_chunk *up;
  195536. png_debug(5, "writing extra chunks\n");
  195537. for (up = info_ptr->unknown_chunks;
  195538. up < info_ptr->unknown_chunks + info_ptr->unknown_chunks_num;
  195539. up++)
  195540. {
  195541. int keep=png_handle_as_unknown(png_ptr, up->name);
  195542. if (keep != PNG_HANDLE_CHUNK_NEVER &&
  195543. up->location && (up->location & PNG_AFTER_IDAT) &&
  195544. ((up->name[3] & 0x20) || keep == PNG_HANDLE_CHUNK_ALWAYS ||
  195545. (png_ptr->flags & PNG_FLAG_KEEP_UNSAFE_CHUNKS)))
  195546. {
  195547. png_write_chunk(png_ptr, up->name, up->data, up->size);
  195548. }
  195549. }
  195550. }
  195551. #endif
  195552. }
  195553. png_ptr->mode |= PNG_AFTER_IDAT;
  195554. /* write end of PNG file */
  195555. png_write_IEND(png_ptr);
  195556. }
  195557. #if defined(PNG_WRITE_tIME_SUPPORTED)
  195558. #if !defined(_WIN32_WCE)
  195559. /* "time.h" functions are not supported on WindowsCE */
  195560. void PNGAPI
  195561. png_convert_from_struct_tm(png_timep ptime, struct tm FAR * ttime)
  195562. {
  195563. png_debug(1, "in png_convert_from_struct_tm\n");
  195564. ptime->year = (png_uint_16)(1900 + ttime->tm_year);
  195565. ptime->month = (png_byte)(ttime->tm_mon + 1);
  195566. ptime->day = (png_byte)ttime->tm_mday;
  195567. ptime->hour = (png_byte)ttime->tm_hour;
  195568. ptime->minute = (png_byte)ttime->tm_min;
  195569. ptime->second = (png_byte)ttime->tm_sec;
  195570. }
  195571. void PNGAPI
  195572. png_convert_from_time_t(png_timep ptime, time_t ttime)
  195573. {
  195574. struct tm *tbuf;
  195575. png_debug(1, "in png_convert_from_time_t\n");
  195576. tbuf = gmtime(&ttime);
  195577. png_convert_from_struct_tm(ptime, tbuf);
  195578. }
  195579. #endif
  195580. #endif
  195581. /* Initialize png_ptr structure, and allocate any memory needed */
  195582. png_structp PNGAPI
  195583. png_create_write_struct(png_const_charp user_png_ver, png_voidp error_ptr,
  195584. png_error_ptr error_fn, png_error_ptr warn_fn)
  195585. {
  195586. #ifdef PNG_USER_MEM_SUPPORTED
  195587. return (png_create_write_struct_2(user_png_ver, error_ptr, error_fn,
  195588. warn_fn, png_voidp_NULL, png_malloc_ptr_NULL, png_free_ptr_NULL));
  195589. }
  195590. /* Alternate initialize png_ptr structure, and allocate any memory needed */
  195591. png_structp PNGAPI
  195592. png_create_write_struct_2(png_const_charp user_png_ver, png_voidp error_ptr,
  195593. png_error_ptr error_fn, png_error_ptr warn_fn, png_voidp mem_ptr,
  195594. png_malloc_ptr malloc_fn, png_free_ptr free_fn)
  195595. {
  195596. #endif /* PNG_USER_MEM_SUPPORTED */
  195597. png_structp png_ptr;
  195598. #ifdef PNG_SETJMP_SUPPORTED
  195599. #ifdef USE_FAR_KEYWORD
  195600. jmp_buf jmpbuf;
  195601. #endif
  195602. #endif
  195603. int i;
  195604. png_debug(1, "in png_create_write_struct\n");
  195605. #ifdef PNG_USER_MEM_SUPPORTED
  195606. png_ptr = (png_structp)png_create_struct_2(PNG_STRUCT_PNG,
  195607. (png_malloc_ptr)malloc_fn, (png_voidp)mem_ptr);
  195608. #else
  195609. png_ptr = (png_structp)png_create_struct(PNG_STRUCT_PNG);
  195610. #endif /* PNG_USER_MEM_SUPPORTED */
  195611. if (png_ptr == NULL)
  195612. return (NULL);
  195613. /* added at libpng-1.2.6 */
  195614. #ifdef PNG_SET_USER_LIMITS_SUPPORTED
  195615. png_ptr->user_width_max=PNG_USER_WIDTH_MAX;
  195616. png_ptr->user_height_max=PNG_USER_HEIGHT_MAX;
  195617. #endif
  195618. #ifdef PNG_SETJMP_SUPPORTED
  195619. #ifdef USE_FAR_KEYWORD
  195620. if (setjmp(jmpbuf))
  195621. #else
  195622. if (setjmp(png_ptr->jmpbuf))
  195623. #endif
  195624. {
  195625. png_free(png_ptr, png_ptr->zbuf);
  195626. png_ptr->zbuf=NULL;
  195627. png_destroy_struct(png_ptr);
  195628. return (NULL);
  195629. }
  195630. #ifdef USE_FAR_KEYWORD
  195631. png_memcpy(png_ptr->jmpbuf,jmpbuf,png_sizeof(jmp_buf));
  195632. #endif
  195633. #endif
  195634. #ifdef PNG_USER_MEM_SUPPORTED
  195635. png_set_mem_fn(png_ptr, mem_ptr, malloc_fn, free_fn);
  195636. #endif /* PNG_USER_MEM_SUPPORTED */
  195637. png_set_error_fn(png_ptr, error_ptr, error_fn, warn_fn);
  195638. i=0;
  195639. do
  195640. {
  195641. if(user_png_ver[i] != png_libpng_ver[i])
  195642. png_ptr->flags |= PNG_FLAG_LIBRARY_MISMATCH;
  195643. } while (png_libpng_ver[i++]);
  195644. if (png_ptr->flags & PNG_FLAG_LIBRARY_MISMATCH)
  195645. {
  195646. /* Libpng 0.90 and later are binary incompatible with libpng 0.89, so
  195647. * we must recompile any applications that use any older library version.
  195648. * For versions after libpng 1.0, we will be compatible, so we need
  195649. * only check the first digit.
  195650. */
  195651. if (user_png_ver == NULL || user_png_ver[0] != png_libpng_ver[0] ||
  195652. (user_png_ver[0] == '1' && user_png_ver[2] != png_libpng_ver[2]) ||
  195653. (user_png_ver[0] == '0' && user_png_ver[2] < '9'))
  195654. {
  195655. #if !defined(PNG_NO_STDIO) && !defined(_WIN32_WCE)
  195656. char msg[80];
  195657. if (user_png_ver)
  195658. {
  195659. png_snprintf(msg, 80,
  195660. "Application was compiled with png.h from libpng-%.20s",
  195661. user_png_ver);
  195662. png_warning(png_ptr, msg);
  195663. }
  195664. png_snprintf(msg, 80,
  195665. "Application is running with png.c from libpng-%.20s",
  195666. png_libpng_ver);
  195667. png_warning(png_ptr, msg);
  195668. #endif
  195669. #ifdef PNG_ERROR_NUMBERS_SUPPORTED
  195670. png_ptr->flags=0;
  195671. #endif
  195672. png_error(png_ptr,
  195673. "Incompatible libpng version in application and library");
  195674. }
  195675. }
  195676. /* initialize zbuf - compression buffer */
  195677. png_ptr->zbuf_size = PNG_ZBUF_SIZE;
  195678. png_ptr->zbuf = (png_bytep)png_malloc(png_ptr,
  195679. (png_uint_32)png_ptr->zbuf_size);
  195680. png_set_write_fn(png_ptr, png_voidp_NULL, png_rw_ptr_NULL,
  195681. png_flush_ptr_NULL);
  195682. #if defined(PNG_WRITE_WEIGHTED_FILTER_SUPPORTED)
  195683. png_set_filter_heuristics(png_ptr, PNG_FILTER_HEURISTIC_DEFAULT,
  195684. 1, png_doublep_NULL, png_doublep_NULL);
  195685. #endif
  195686. #ifdef PNG_SETJMP_SUPPORTED
  195687. /* Applications that neglect to set up their own setjmp() and then encounter
  195688. a png_error() will longjmp here. Since the jmpbuf is then meaningless we
  195689. abort instead of returning. */
  195690. #ifdef USE_FAR_KEYWORD
  195691. if (setjmp(jmpbuf))
  195692. PNG_ABORT();
  195693. png_memcpy(png_ptr->jmpbuf,jmpbuf,png_sizeof(jmp_buf));
  195694. #else
  195695. if (setjmp(png_ptr->jmpbuf))
  195696. PNG_ABORT();
  195697. #endif
  195698. #endif
  195699. return (png_ptr);
  195700. }
  195701. /* Initialize png_ptr structure, and allocate any memory needed */
  195702. #if defined(PNG_1_0_X) || defined(PNG_1_2_X)
  195703. /* Deprecated. */
  195704. #undef png_write_init
  195705. void PNGAPI
  195706. png_write_init(png_structp png_ptr)
  195707. {
  195708. /* We only come here via pre-1.0.7-compiled applications */
  195709. png_write_init_2(png_ptr, "1.0.6 or earlier", 0, 0);
  195710. }
  195711. void PNGAPI
  195712. png_write_init_2(png_structp png_ptr, png_const_charp user_png_ver,
  195713. png_size_t png_struct_size, png_size_t png_info_size)
  195714. {
  195715. /* We only come here via pre-1.0.12-compiled applications */
  195716. if(png_ptr == NULL) return;
  195717. #if !defined(PNG_NO_STDIO) && !defined(_WIN32_WCE)
  195718. if(png_sizeof(png_struct) > png_struct_size ||
  195719. png_sizeof(png_info) > png_info_size)
  195720. {
  195721. char msg[80];
  195722. png_ptr->warning_fn=NULL;
  195723. if (user_png_ver)
  195724. {
  195725. png_snprintf(msg, 80,
  195726. "Application was compiled with png.h from libpng-%.20s",
  195727. user_png_ver);
  195728. png_warning(png_ptr, msg);
  195729. }
  195730. png_snprintf(msg, 80,
  195731. "Application is running with png.c from libpng-%.20s",
  195732. png_libpng_ver);
  195733. png_warning(png_ptr, msg);
  195734. }
  195735. #endif
  195736. if(png_sizeof(png_struct) > png_struct_size)
  195737. {
  195738. png_ptr->error_fn=NULL;
  195739. #ifdef PNG_ERROR_NUMBERS_SUPPORTED
  195740. png_ptr->flags=0;
  195741. #endif
  195742. png_error(png_ptr,
  195743. "The png struct allocated by the application for writing is too small.");
  195744. }
  195745. if(png_sizeof(png_info) > png_info_size)
  195746. {
  195747. png_ptr->error_fn=NULL;
  195748. #ifdef PNG_ERROR_NUMBERS_SUPPORTED
  195749. png_ptr->flags=0;
  195750. #endif
  195751. png_error(png_ptr,
  195752. "The info struct allocated by the application for writing is too small.");
  195753. }
  195754. png_write_init_3(&png_ptr, user_png_ver, png_struct_size);
  195755. }
  195756. #endif /* PNG_1_0_X || PNG_1_2_X */
  195757. void PNGAPI
  195758. png_write_init_3(png_structpp ptr_ptr, png_const_charp user_png_ver,
  195759. png_size_t png_struct_size)
  195760. {
  195761. png_structp png_ptr=*ptr_ptr;
  195762. #ifdef PNG_SETJMP_SUPPORTED
  195763. jmp_buf tmp_jmp; /* to save current jump buffer */
  195764. #endif
  195765. int i = 0;
  195766. if (png_ptr == NULL)
  195767. return;
  195768. do
  195769. {
  195770. if (user_png_ver[i] != png_libpng_ver[i])
  195771. {
  195772. #ifdef PNG_LEGACY_SUPPORTED
  195773. png_ptr->flags |= PNG_FLAG_LIBRARY_MISMATCH;
  195774. #else
  195775. png_ptr->warning_fn=NULL;
  195776. png_warning(png_ptr,
  195777. "Application uses deprecated png_write_init() and should be recompiled.");
  195778. break;
  195779. #endif
  195780. }
  195781. } while (png_libpng_ver[i++]);
  195782. png_debug(1, "in png_write_init_3\n");
  195783. #ifdef PNG_SETJMP_SUPPORTED
  195784. /* save jump buffer and error functions */
  195785. png_memcpy(tmp_jmp, png_ptr->jmpbuf, png_sizeof (jmp_buf));
  195786. #endif
  195787. if (png_sizeof(png_struct) > png_struct_size)
  195788. {
  195789. png_destroy_struct(png_ptr);
  195790. png_ptr = (png_structp)png_create_struct(PNG_STRUCT_PNG);
  195791. *ptr_ptr = png_ptr;
  195792. }
  195793. /* reset all variables to 0 */
  195794. png_memset(png_ptr, 0, png_sizeof (png_struct));
  195795. /* added at libpng-1.2.6 */
  195796. #ifdef PNG_SET_USER_LIMITS_SUPPORTED
  195797. png_ptr->user_width_max=PNG_USER_WIDTH_MAX;
  195798. png_ptr->user_height_max=PNG_USER_HEIGHT_MAX;
  195799. #endif
  195800. #ifdef PNG_SETJMP_SUPPORTED
  195801. /* restore jump buffer */
  195802. png_memcpy(png_ptr->jmpbuf, tmp_jmp, png_sizeof (jmp_buf));
  195803. #endif
  195804. png_set_write_fn(png_ptr, png_voidp_NULL, png_rw_ptr_NULL,
  195805. png_flush_ptr_NULL);
  195806. /* initialize zbuf - compression buffer */
  195807. png_ptr->zbuf_size = PNG_ZBUF_SIZE;
  195808. png_ptr->zbuf = (png_bytep)png_malloc(png_ptr,
  195809. (png_uint_32)png_ptr->zbuf_size);
  195810. #if defined(PNG_WRITE_WEIGHTED_FILTER_SUPPORTED)
  195811. png_set_filter_heuristics(png_ptr, PNG_FILTER_HEURISTIC_DEFAULT,
  195812. 1, png_doublep_NULL, png_doublep_NULL);
  195813. #endif
  195814. }
  195815. /* Write a few rows of image data. If the image is interlaced,
  195816. * either you will have to write the 7 sub images, or, if you
  195817. * have called png_set_interlace_handling(), you will have to
  195818. * "write" the image seven times.
  195819. */
  195820. void PNGAPI
  195821. png_write_rows(png_structp png_ptr, png_bytepp row,
  195822. png_uint_32 num_rows)
  195823. {
  195824. png_uint_32 i; /* row counter */
  195825. png_bytepp rp; /* row pointer */
  195826. png_debug(1, "in png_write_rows\n");
  195827. if (png_ptr == NULL)
  195828. return;
  195829. /* loop through the rows */
  195830. for (i = 0, rp = row; i < num_rows; i++, rp++)
  195831. {
  195832. png_write_row(png_ptr, *rp);
  195833. }
  195834. }
  195835. /* Write the image. You only need to call this function once, even
  195836. * if you are writing an interlaced image.
  195837. */
  195838. void PNGAPI
  195839. png_write_image(png_structp png_ptr, png_bytepp image)
  195840. {
  195841. png_uint_32 i; /* row index */
  195842. int pass, num_pass; /* pass variables */
  195843. png_bytepp rp; /* points to current row */
  195844. if (png_ptr == NULL)
  195845. return;
  195846. png_debug(1, "in png_write_image\n");
  195847. #if defined(PNG_WRITE_INTERLACING_SUPPORTED)
  195848. /* intialize interlace handling. If image is not interlaced,
  195849. this will set pass to 1 */
  195850. num_pass = png_set_interlace_handling(png_ptr);
  195851. #else
  195852. num_pass = 1;
  195853. #endif
  195854. /* loop through passes */
  195855. for (pass = 0; pass < num_pass; pass++)
  195856. {
  195857. /* loop through image */
  195858. for (i = 0, rp = image; i < png_ptr->height; i++, rp++)
  195859. {
  195860. png_write_row(png_ptr, *rp);
  195861. }
  195862. }
  195863. }
  195864. /* called by user to write a row of image data */
  195865. void PNGAPI
  195866. png_write_row(png_structp png_ptr, png_bytep row)
  195867. {
  195868. if (png_ptr == NULL)
  195869. return;
  195870. png_debug2(1, "in png_write_row (row %ld, pass %d)\n",
  195871. png_ptr->row_number, png_ptr->pass);
  195872. /* initialize transformations and other stuff if first time */
  195873. if (png_ptr->row_number == 0 && png_ptr->pass == 0)
  195874. {
  195875. /* make sure we wrote the header info */
  195876. if (!(png_ptr->mode & PNG_WROTE_INFO_BEFORE_PLTE))
  195877. png_error(png_ptr,
  195878. "png_write_info was never called before png_write_row.");
  195879. /* check for transforms that have been set but were defined out */
  195880. #if !defined(PNG_WRITE_INVERT_SUPPORTED) && defined(PNG_READ_INVERT_SUPPORTED)
  195881. if (png_ptr->transformations & PNG_INVERT_MONO)
  195882. png_warning(png_ptr, "PNG_WRITE_INVERT_SUPPORTED is not defined.");
  195883. #endif
  195884. #if !defined(PNG_WRITE_FILLER_SUPPORTED) && defined(PNG_READ_FILLER_SUPPORTED)
  195885. if (png_ptr->transformations & PNG_FILLER)
  195886. png_warning(png_ptr, "PNG_WRITE_FILLER_SUPPORTED is not defined.");
  195887. #endif
  195888. #if !defined(PNG_WRITE_PACKSWAP_SUPPORTED) && defined(PNG_READ_PACKSWAP_SUPPORTED)
  195889. if (png_ptr->transformations & PNG_PACKSWAP)
  195890. png_warning(png_ptr, "PNG_WRITE_PACKSWAP_SUPPORTED is not defined.");
  195891. #endif
  195892. #if !defined(PNG_WRITE_PACK_SUPPORTED) && defined(PNG_READ_PACK_SUPPORTED)
  195893. if (png_ptr->transformations & PNG_PACK)
  195894. png_warning(png_ptr, "PNG_WRITE_PACK_SUPPORTED is not defined.");
  195895. #endif
  195896. #if !defined(PNG_WRITE_SHIFT_SUPPORTED) && defined(PNG_READ_SHIFT_SUPPORTED)
  195897. if (png_ptr->transformations & PNG_SHIFT)
  195898. png_warning(png_ptr, "PNG_WRITE_SHIFT_SUPPORTED is not defined.");
  195899. #endif
  195900. #if !defined(PNG_WRITE_BGR_SUPPORTED) && defined(PNG_READ_BGR_SUPPORTED)
  195901. if (png_ptr->transformations & PNG_BGR)
  195902. png_warning(png_ptr, "PNG_WRITE_BGR_SUPPORTED is not defined.");
  195903. #endif
  195904. #if !defined(PNG_WRITE_SWAP_SUPPORTED) && defined(PNG_READ_SWAP_SUPPORTED)
  195905. if (png_ptr->transformations & PNG_SWAP_BYTES)
  195906. png_warning(png_ptr, "PNG_WRITE_SWAP_SUPPORTED is not defined.");
  195907. #endif
  195908. png_write_start_row(png_ptr);
  195909. }
  195910. #if defined(PNG_WRITE_INTERLACING_SUPPORTED)
  195911. /* if interlaced and not interested in row, return */
  195912. if (png_ptr->interlaced && (png_ptr->transformations & PNG_INTERLACE))
  195913. {
  195914. switch (png_ptr->pass)
  195915. {
  195916. case 0:
  195917. if (png_ptr->row_number & 0x07)
  195918. {
  195919. png_write_finish_row(png_ptr);
  195920. return;
  195921. }
  195922. break;
  195923. case 1:
  195924. if ((png_ptr->row_number & 0x07) || png_ptr->width < 5)
  195925. {
  195926. png_write_finish_row(png_ptr);
  195927. return;
  195928. }
  195929. break;
  195930. case 2:
  195931. if ((png_ptr->row_number & 0x07) != 4)
  195932. {
  195933. png_write_finish_row(png_ptr);
  195934. return;
  195935. }
  195936. break;
  195937. case 3:
  195938. if ((png_ptr->row_number & 0x03) || png_ptr->width < 3)
  195939. {
  195940. png_write_finish_row(png_ptr);
  195941. return;
  195942. }
  195943. break;
  195944. case 4:
  195945. if ((png_ptr->row_number & 0x03) != 2)
  195946. {
  195947. png_write_finish_row(png_ptr);
  195948. return;
  195949. }
  195950. break;
  195951. case 5:
  195952. if ((png_ptr->row_number & 0x01) || png_ptr->width < 2)
  195953. {
  195954. png_write_finish_row(png_ptr);
  195955. return;
  195956. }
  195957. break;
  195958. case 6:
  195959. if (!(png_ptr->row_number & 0x01))
  195960. {
  195961. png_write_finish_row(png_ptr);
  195962. return;
  195963. }
  195964. break;
  195965. }
  195966. }
  195967. #endif
  195968. /* set up row info for transformations */
  195969. png_ptr->row_info.color_type = png_ptr->color_type;
  195970. png_ptr->row_info.width = png_ptr->usr_width;
  195971. png_ptr->row_info.channels = png_ptr->usr_channels;
  195972. png_ptr->row_info.bit_depth = png_ptr->usr_bit_depth;
  195973. png_ptr->row_info.pixel_depth = (png_byte)(png_ptr->row_info.bit_depth *
  195974. png_ptr->row_info.channels);
  195975. png_ptr->row_info.rowbytes = PNG_ROWBYTES(png_ptr->row_info.pixel_depth,
  195976. png_ptr->row_info.width);
  195977. png_debug1(3, "row_info->color_type = %d\n", png_ptr->row_info.color_type);
  195978. png_debug1(3, "row_info->width = %lu\n", png_ptr->row_info.width);
  195979. png_debug1(3, "row_info->channels = %d\n", png_ptr->row_info.channels);
  195980. png_debug1(3, "row_info->bit_depth = %d\n", png_ptr->row_info.bit_depth);
  195981. png_debug1(3, "row_info->pixel_depth = %d\n", png_ptr->row_info.pixel_depth);
  195982. png_debug1(3, "row_info->rowbytes = %lu\n", png_ptr->row_info.rowbytes);
  195983. /* Copy user's row into buffer, leaving room for filter byte. */
  195984. png_memcpy_check(png_ptr, png_ptr->row_buf + 1, row,
  195985. png_ptr->row_info.rowbytes);
  195986. #if defined(PNG_WRITE_INTERLACING_SUPPORTED)
  195987. /* handle interlacing */
  195988. if (png_ptr->interlaced && png_ptr->pass < 6 &&
  195989. (png_ptr->transformations & PNG_INTERLACE))
  195990. {
  195991. png_do_write_interlace(&(png_ptr->row_info),
  195992. png_ptr->row_buf + 1, png_ptr->pass);
  195993. /* this should always get caught above, but still ... */
  195994. if (!(png_ptr->row_info.width))
  195995. {
  195996. png_write_finish_row(png_ptr);
  195997. return;
  195998. }
  195999. }
  196000. #endif
  196001. /* handle other transformations */
  196002. if (png_ptr->transformations)
  196003. png_do_write_transformations(png_ptr);
  196004. #if defined(PNG_MNG_FEATURES_SUPPORTED)
  196005. /* Write filter_method 64 (intrapixel differencing) only if
  196006. * 1. Libpng was compiled with PNG_MNG_FEATURES_SUPPORTED and
  196007. * 2. Libpng did not write a PNG signature (this filter_method is only
  196008. * used in PNG datastreams that are embedded in MNG datastreams) and
  196009. * 3. The application called png_permit_mng_features with a mask that
  196010. * included PNG_FLAG_MNG_FILTER_64 and
  196011. * 4. The filter_method is 64 and
  196012. * 5. The color_type is RGB or RGBA
  196013. */
  196014. if((png_ptr->mng_features_permitted & PNG_FLAG_MNG_FILTER_64) &&
  196015. (png_ptr->filter_type == PNG_INTRAPIXEL_DIFFERENCING))
  196016. {
  196017. /* Intrapixel differencing */
  196018. png_do_write_intrapixel(&(png_ptr->row_info), png_ptr->row_buf + 1);
  196019. }
  196020. #endif
  196021. /* Find a filter if necessary, filter the row and write it out. */
  196022. png_write_find_filter(png_ptr, &(png_ptr->row_info));
  196023. if (png_ptr->write_row_fn != NULL)
  196024. (*(png_ptr->write_row_fn))(png_ptr, png_ptr->row_number, png_ptr->pass);
  196025. }
  196026. #if defined(PNG_WRITE_FLUSH_SUPPORTED)
  196027. /* Set the automatic flush interval or 0 to turn flushing off */
  196028. void PNGAPI
  196029. png_set_flush(png_structp png_ptr, int nrows)
  196030. {
  196031. png_debug(1, "in png_set_flush\n");
  196032. if (png_ptr == NULL)
  196033. return;
  196034. png_ptr->flush_dist = (nrows < 0 ? 0 : nrows);
  196035. }
  196036. /* flush the current output buffers now */
  196037. void PNGAPI
  196038. png_write_flush(png_structp png_ptr)
  196039. {
  196040. int wrote_IDAT;
  196041. png_debug(1, "in png_write_flush\n");
  196042. if (png_ptr == NULL)
  196043. return;
  196044. /* We have already written out all of the data */
  196045. if (png_ptr->row_number >= png_ptr->num_rows)
  196046. return;
  196047. do
  196048. {
  196049. int ret;
  196050. /* compress the data */
  196051. ret = deflate(&png_ptr->zstream, Z_SYNC_FLUSH);
  196052. wrote_IDAT = 0;
  196053. /* check for compression errors */
  196054. if (ret != Z_OK)
  196055. {
  196056. if (png_ptr->zstream.msg != NULL)
  196057. png_error(png_ptr, png_ptr->zstream.msg);
  196058. else
  196059. png_error(png_ptr, "zlib error");
  196060. }
  196061. if (!(png_ptr->zstream.avail_out))
  196062. {
  196063. /* write the IDAT and reset the zlib output buffer */
  196064. png_write_IDAT(png_ptr, png_ptr->zbuf,
  196065. png_ptr->zbuf_size);
  196066. png_ptr->zstream.next_out = png_ptr->zbuf;
  196067. png_ptr->zstream.avail_out = (uInt)png_ptr->zbuf_size;
  196068. wrote_IDAT = 1;
  196069. }
  196070. } while(wrote_IDAT == 1);
  196071. /* If there is any data left to be output, write it into a new IDAT */
  196072. if (png_ptr->zbuf_size != png_ptr->zstream.avail_out)
  196073. {
  196074. /* write the IDAT and reset the zlib output buffer */
  196075. png_write_IDAT(png_ptr, png_ptr->zbuf,
  196076. png_ptr->zbuf_size - png_ptr->zstream.avail_out);
  196077. png_ptr->zstream.next_out = png_ptr->zbuf;
  196078. png_ptr->zstream.avail_out = (uInt)png_ptr->zbuf_size;
  196079. }
  196080. png_ptr->flush_rows = 0;
  196081. png_flush(png_ptr);
  196082. }
  196083. #endif /* PNG_WRITE_FLUSH_SUPPORTED */
  196084. /* free all memory used by the write */
  196085. void PNGAPI
  196086. png_destroy_write_struct(png_structpp png_ptr_ptr, png_infopp info_ptr_ptr)
  196087. {
  196088. png_structp png_ptr = NULL;
  196089. png_infop info_ptr = NULL;
  196090. #ifdef PNG_USER_MEM_SUPPORTED
  196091. png_free_ptr free_fn = NULL;
  196092. png_voidp mem_ptr = NULL;
  196093. #endif
  196094. png_debug(1, "in png_destroy_write_struct\n");
  196095. if (png_ptr_ptr != NULL)
  196096. {
  196097. png_ptr = *png_ptr_ptr;
  196098. #ifdef PNG_USER_MEM_SUPPORTED
  196099. free_fn = png_ptr->free_fn;
  196100. mem_ptr = png_ptr->mem_ptr;
  196101. #endif
  196102. }
  196103. if (info_ptr_ptr != NULL)
  196104. info_ptr = *info_ptr_ptr;
  196105. if (info_ptr != NULL)
  196106. {
  196107. png_free_data(png_ptr, info_ptr, PNG_FREE_ALL, -1);
  196108. #if defined(PNG_UNKNOWN_CHUNKS_SUPPORTED)
  196109. if (png_ptr->num_chunk_list)
  196110. {
  196111. png_free(png_ptr, png_ptr->chunk_list);
  196112. png_ptr->chunk_list=NULL;
  196113. png_ptr->num_chunk_list=0;
  196114. }
  196115. #endif
  196116. #ifdef PNG_USER_MEM_SUPPORTED
  196117. png_destroy_struct_2((png_voidp)info_ptr, (png_free_ptr)free_fn,
  196118. (png_voidp)mem_ptr);
  196119. #else
  196120. png_destroy_struct((png_voidp)info_ptr);
  196121. #endif
  196122. *info_ptr_ptr = NULL;
  196123. }
  196124. if (png_ptr != NULL)
  196125. {
  196126. png_write_destroy(png_ptr);
  196127. #ifdef PNG_USER_MEM_SUPPORTED
  196128. png_destroy_struct_2((png_voidp)png_ptr, (png_free_ptr)free_fn,
  196129. (png_voidp)mem_ptr);
  196130. #else
  196131. png_destroy_struct((png_voidp)png_ptr);
  196132. #endif
  196133. *png_ptr_ptr = NULL;
  196134. }
  196135. }
  196136. /* Free any memory used in png_ptr struct (old method) */
  196137. void /* PRIVATE */
  196138. png_write_destroy(png_structp png_ptr)
  196139. {
  196140. #ifdef PNG_SETJMP_SUPPORTED
  196141. jmp_buf tmp_jmp; /* save jump buffer */
  196142. #endif
  196143. png_error_ptr error_fn;
  196144. png_error_ptr warning_fn;
  196145. png_voidp error_ptr;
  196146. #ifdef PNG_USER_MEM_SUPPORTED
  196147. png_free_ptr free_fn;
  196148. #endif
  196149. png_debug(1, "in png_write_destroy\n");
  196150. /* free any memory zlib uses */
  196151. deflateEnd(&png_ptr->zstream);
  196152. /* free our memory. png_free checks NULL for us. */
  196153. png_free(png_ptr, png_ptr->zbuf);
  196154. png_free(png_ptr, png_ptr->row_buf);
  196155. png_free(png_ptr, png_ptr->prev_row);
  196156. png_free(png_ptr, png_ptr->sub_row);
  196157. png_free(png_ptr, png_ptr->up_row);
  196158. png_free(png_ptr, png_ptr->avg_row);
  196159. png_free(png_ptr, png_ptr->paeth_row);
  196160. #if defined(PNG_TIME_RFC1123_SUPPORTED)
  196161. png_free(png_ptr, png_ptr->time_buffer);
  196162. #endif
  196163. #if defined(PNG_WRITE_WEIGHTED_FILTER_SUPPORTED)
  196164. png_free(png_ptr, png_ptr->prev_filters);
  196165. png_free(png_ptr, png_ptr->filter_weights);
  196166. png_free(png_ptr, png_ptr->inv_filter_weights);
  196167. png_free(png_ptr, png_ptr->filter_costs);
  196168. png_free(png_ptr, png_ptr->inv_filter_costs);
  196169. #endif
  196170. #ifdef PNG_SETJMP_SUPPORTED
  196171. /* reset structure */
  196172. png_memcpy(tmp_jmp, png_ptr->jmpbuf, png_sizeof (jmp_buf));
  196173. #endif
  196174. error_fn = png_ptr->error_fn;
  196175. warning_fn = png_ptr->warning_fn;
  196176. error_ptr = png_ptr->error_ptr;
  196177. #ifdef PNG_USER_MEM_SUPPORTED
  196178. free_fn = png_ptr->free_fn;
  196179. #endif
  196180. png_memset(png_ptr, 0, png_sizeof (png_struct));
  196181. png_ptr->error_fn = error_fn;
  196182. png_ptr->warning_fn = warning_fn;
  196183. png_ptr->error_ptr = error_ptr;
  196184. #ifdef PNG_USER_MEM_SUPPORTED
  196185. png_ptr->free_fn = free_fn;
  196186. #endif
  196187. #ifdef PNG_SETJMP_SUPPORTED
  196188. png_memcpy(png_ptr->jmpbuf, tmp_jmp, png_sizeof (jmp_buf));
  196189. #endif
  196190. }
  196191. /* Allow the application to select one or more row filters to use. */
  196192. void PNGAPI
  196193. png_set_filter(png_structp png_ptr, int method, int filters)
  196194. {
  196195. png_debug(1, "in png_set_filter\n");
  196196. if (png_ptr == NULL)
  196197. return;
  196198. #if defined(PNG_MNG_FEATURES_SUPPORTED)
  196199. if((png_ptr->mng_features_permitted & PNG_FLAG_MNG_FILTER_64) &&
  196200. (method == PNG_INTRAPIXEL_DIFFERENCING))
  196201. method = PNG_FILTER_TYPE_BASE;
  196202. #endif
  196203. if (method == PNG_FILTER_TYPE_BASE)
  196204. {
  196205. switch (filters & (PNG_ALL_FILTERS | 0x07))
  196206. {
  196207. #ifndef PNG_NO_WRITE_FILTER
  196208. case 5:
  196209. case 6:
  196210. case 7: png_warning(png_ptr, "Unknown row filter for method 0");
  196211. #endif /* PNG_NO_WRITE_FILTER */
  196212. case PNG_FILTER_VALUE_NONE:
  196213. png_ptr->do_filter=PNG_FILTER_NONE; break;
  196214. #ifndef PNG_NO_WRITE_FILTER
  196215. case PNG_FILTER_VALUE_SUB:
  196216. png_ptr->do_filter=PNG_FILTER_SUB; break;
  196217. case PNG_FILTER_VALUE_UP:
  196218. png_ptr->do_filter=PNG_FILTER_UP; break;
  196219. case PNG_FILTER_VALUE_AVG:
  196220. png_ptr->do_filter=PNG_FILTER_AVG; break;
  196221. case PNG_FILTER_VALUE_PAETH:
  196222. png_ptr->do_filter=PNG_FILTER_PAETH; break;
  196223. default: png_ptr->do_filter = (png_byte)filters; break;
  196224. #else
  196225. default: png_warning(png_ptr, "Unknown row filter for method 0");
  196226. #endif /* PNG_NO_WRITE_FILTER */
  196227. }
  196228. /* If we have allocated the row_buf, this means we have already started
  196229. * with the image and we should have allocated all of the filter buffers
  196230. * that have been selected. If prev_row isn't already allocated, then
  196231. * it is too late to start using the filters that need it, since we
  196232. * will be missing the data in the previous row. If an application
  196233. * wants to start and stop using particular filters during compression,
  196234. * it should start out with all of the filters, and then add and
  196235. * remove them after the start of compression.
  196236. */
  196237. if (png_ptr->row_buf != NULL)
  196238. {
  196239. #ifndef PNG_NO_WRITE_FILTER
  196240. if ((png_ptr->do_filter & PNG_FILTER_SUB) && png_ptr->sub_row == NULL)
  196241. {
  196242. png_ptr->sub_row = (png_bytep)png_malloc(png_ptr,
  196243. (png_ptr->rowbytes + 1));
  196244. png_ptr->sub_row[0] = PNG_FILTER_VALUE_SUB;
  196245. }
  196246. if ((png_ptr->do_filter & PNG_FILTER_UP) && png_ptr->up_row == NULL)
  196247. {
  196248. if (png_ptr->prev_row == NULL)
  196249. {
  196250. png_warning(png_ptr, "Can't add Up filter after starting");
  196251. png_ptr->do_filter &= ~PNG_FILTER_UP;
  196252. }
  196253. else
  196254. {
  196255. png_ptr->up_row = (png_bytep)png_malloc(png_ptr,
  196256. (png_ptr->rowbytes + 1));
  196257. png_ptr->up_row[0] = PNG_FILTER_VALUE_UP;
  196258. }
  196259. }
  196260. if ((png_ptr->do_filter & PNG_FILTER_AVG) && png_ptr->avg_row == NULL)
  196261. {
  196262. if (png_ptr->prev_row == NULL)
  196263. {
  196264. png_warning(png_ptr, "Can't add Average filter after starting");
  196265. png_ptr->do_filter &= ~PNG_FILTER_AVG;
  196266. }
  196267. else
  196268. {
  196269. png_ptr->avg_row = (png_bytep)png_malloc(png_ptr,
  196270. (png_ptr->rowbytes + 1));
  196271. png_ptr->avg_row[0] = PNG_FILTER_VALUE_AVG;
  196272. }
  196273. }
  196274. if ((png_ptr->do_filter & PNG_FILTER_PAETH) &&
  196275. png_ptr->paeth_row == NULL)
  196276. {
  196277. if (png_ptr->prev_row == NULL)
  196278. {
  196279. png_warning(png_ptr, "Can't add Paeth filter after starting");
  196280. png_ptr->do_filter &= (png_byte)(~PNG_FILTER_PAETH);
  196281. }
  196282. else
  196283. {
  196284. png_ptr->paeth_row = (png_bytep)png_malloc(png_ptr,
  196285. (png_ptr->rowbytes + 1));
  196286. png_ptr->paeth_row[0] = PNG_FILTER_VALUE_PAETH;
  196287. }
  196288. }
  196289. if (png_ptr->do_filter == PNG_NO_FILTERS)
  196290. #endif /* PNG_NO_WRITE_FILTER */
  196291. png_ptr->do_filter = PNG_FILTER_NONE;
  196292. }
  196293. }
  196294. else
  196295. png_error(png_ptr, "Unknown custom filter method");
  196296. }
  196297. /* This allows us to influence the way in which libpng chooses the "best"
  196298. * filter for the current scanline. While the "minimum-sum-of-absolute-
  196299. * differences metric is relatively fast and effective, there is some
  196300. * question as to whether it can be improved upon by trying to keep the
  196301. * filtered data going to zlib more consistent, hopefully resulting in
  196302. * better compression.
  196303. */
  196304. #if defined(PNG_WRITE_WEIGHTED_FILTER_SUPPORTED) /* GRR 970116 */
  196305. void PNGAPI
  196306. png_set_filter_heuristics(png_structp png_ptr, int heuristic_method,
  196307. int num_weights, png_doublep filter_weights,
  196308. png_doublep filter_costs)
  196309. {
  196310. int i;
  196311. png_debug(1, "in png_set_filter_heuristics\n");
  196312. if (png_ptr == NULL)
  196313. return;
  196314. if (heuristic_method >= PNG_FILTER_HEURISTIC_LAST)
  196315. {
  196316. png_warning(png_ptr, "Unknown filter heuristic method");
  196317. return;
  196318. }
  196319. if (heuristic_method == PNG_FILTER_HEURISTIC_DEFAULT)
  196320. {
  196321. heuristic_method = PNG_FILTER_HEURISTIC_UNWEIGHTED;
  196322. }
  196323. if (num_weights < 0 || filter_weights == NULL ||
  196324. heuristic_method == PNG_FILTER_HEURISTIC_UNWEIGHTED)
  196325. {
  196326. num_weights = 0;
  196327. }
  196328. png_ptr->num_prev_filters = (png_byte)num_weights;
  196329. png_ptr->heuristic_method = (png_byte)heuristic_method;
  196330. if (num_weights > 0)
  196331. {
  196332. if (png_ptr->prev_filters == NULL)
  196333. {
  196334. png_ptr->prev_filters = (png_bytep)png_malloc(png_ptr,
  196335. (png_uint_32)(png_sizeof(png_byte) * num_weights));
  196336. /* To make sure that the weighting starts out fairly */
  196337. for (i = 0; i < num_weights; i++)
  196338. {
  196339. png_ptr->prev_filters[i] = 255;
  196340. }
  196341. }
  196342. if (png_ptr->filter_weights == NULL)
  196343. {
  196344. png_ptr->filter_weights = (png_uint_16p)png_malloc(png_ptr,
  196345. (png_uint_32)(png_sizeof(png_uint_16) * num_weights));
  196346. png_ptr->inv_filter_weights = (png_uint_16p)png_malloc(png_ptr,
  196347. (png_uint_32)(png_sizeof(png_uint_16) * num_weights));
  196348. for (i = 0; i < num_weights; i++)
  196349. {
  196350. png_ptr->inv_filter_weights[i] =
  196351. png_ptr->filter_weights[i] = PNG_WEIGHT_FACTOR;
  196352. }
  196353. }
  196354. for (i = 0; i < num_weights; i++)
  196355. {
  196356. if (filter_weights[i] < 0.0)
  196357. {
  196358. png_ptr->inv_filter_weights[i] =
  196359. png_ptr->filter_weights[i] = PNG_WEIGHT_FACTOR;
  196360. }
  196361. else
  196362. {
  196363. png_ptr->inv_filter_weights[i] =
  196364. (png_uint_16)((double)PNG_WEIGHT_FACTOR*filter_weights[i]+0.5);
  196365. png_ptr->filter_weights[i] =
  196366. (png_uint_16)((double)PNG_WEIGHT_FACTOR/filter_weights[i]+0.5);
  196367. }
  196368. }
  196369. }
  196370. /* If, in the future, there are other filter methods, this would
  196371. * need to be based on png_ptr->filter.
  196372. */
  196373. if (png_ptr->filter_costs == NULL)
  196374. {
  196375. png_ptr->filter_costs = (png_uint_16p)png_malloc(png_ptr,
  196376. (png_uint_32)(png_sizeof(png_uint_16) * PNG_FILTER_VALUE_LAST));
  196377. png_ptr->inv_filter_costs = (png_uint_16p)png_malloc(png_ptr,
  196378. (png_uint_32)(png_sizeof(png_uint_16) * PNG_FILTER_VALUE_LAST));
  196379. for (i = 0; i < PNG_FILTER_VALUE_LAST; i++)
  196380. {
  196381. png_ptr->inv_filter_costs[i] =
  196382. png_ptr->filter_costs[i] = PNG_COST_FACTOR;
  196383. }
  196384. }
  196385. /* Here is where we set the relative costs of the different filters. We
  196386. * should take the desired compression level into account when setting
  196387. * the costs, so that Paeth, for instance, has a high relative cost at low
  196388. * compression levels, while it has a lower relative cost at higher
  196389. * compression settings. The filter types are in order of increasing
  196390. * relative cost, so it would be possible to do this with an algorithm.
  196391. */
  196392. for (i = 0; i < PNG_FILTER_VALUE_LAST; i++)
  196393. {
  196394. if (filter_costs == NULL || filter_costs[i] < 0.0)
  196395. {
  196396. png_ptr->inv_filter_costs[i] =
  196397. png_ptr->filter_costs[i] = PNG_COST_FACTOR;
  196398. }
  196399. else if (filter_costs[i] >= 1.0)
  196400. {
  196401. png_ptr->inv_filter_costs[i] =
  196402. (png_uint_16)((double)PNG_COST_FACTOR / filter_costs[i] + 0.5);
  196403. png_ptr->filter_costs[i] =
  196404. (png_uint_16)((double)PNG_COST_FACTOR * filter_costs[i] + 0.5);
  196405. }
  196406. }
  196407. }
  196408. #endif /* PNG_WRITE_WEIGHTED_FILTER_SUPPORTED */
  196409. void PNGAPI
  196410. png_set_compression_level(png_structp png_ptr, int level)
  196411. {
  196412. png_debug(1, "in png_set_compression_level\n");
  196413. if (png_ptr == NULL)
  196414. return;
  196415. png_ptr->flags |= PNG_FLAG_ZLIB_CUSTOM_LEVEL;
  196416. png_ptr->zlib_level = level;
  196417. }
  196418. void PNGAPI
  196419. png_set_compression_mem_level(png_structp png_ptr, int mem_level)
  196420. {
  196421. png_debug(1, "in png_set_compression_mem_level\n");
  196422. if (png_ptr == NULL)
  196423. return;
  196424. png_ptr->flags |= PNG_FLAG_ZLIB_CUSTOM_MEM_LEVEL;
  196425. png_ptr->zlib_mem_level = mem_level;
  196426. }
  196427. void PNGAPI
  196428. png_set_compression_strategy(png_structp png_ptr, int strategy)
  196429. {
  196430. png_debug(1, "in png_set_compression_strategy\n");
  196431. if (png_ptr == NULL)
  196432. return;
  196433. png_ptr->flags |= PNG_FLAG_ZLIB_CUSTOM_STRATEGY;
  196434. png_ptr->zlib_strategy = strategy;
  196435. }
  196436. void PNGAPI
  196437. png_set_compression_window_bits(png_structp png_ptr, int window_bits)
  196438. {
  196439. if (png_ptr == NULL)
  196440. return;
  196441. if (window_bits > 15)
  196442. png_warning(png_ptr, "Only compression windows <= 32k supported by PNG");
  196443. else if (window_bits < 8)
  196444. png_warning(png_ptr, "Only compression windows >= 256 supported by PNG");
  196445. #ifndef WBITS_8_OK
  196446. /* avoid libpng bug with 256-byte windows */
  196447. if (window_bits == 8)
  196448. {
  196449. png_warning(png_ptr, "Compression window is being reset to 512");
  196450. window_bits=9;
  196451. }
  196452. #endif
  196453. png_ptr->flags |= PNG_FLAG_ZLIB_CUSTOM_WINDOW_BITS;
  196454. png_ptr->zlib_window_bits = window_bits;
  196455. }
  196456. void PNGAPI
  196457. png_set_compression_method(png_structp png_ptr, int method)
  196458. {
  196459. png_debug(1, "in png_set_compression_method\n");
  196460. if (png_ptr == NULL)
  196461. return;
  196462. if (method != 8)
  196463. png_warning(png_ptr, "Only compression method 8 is supported by PNG");
  196464. png_ptr->flags |= PNG_FLAG_ZLIB_CUSTOM_METHOD;
  196465. png_ptr->zlib_method = method;
  196466. }
  196467. void PNGAPI
  196468. png_set_write_status_fn(png_structp png_ptr, png_write_status_ptr write_row_fn)
  196469. {
  196470. if (png_ptr == NULL)
  196471. return;
  196472. png_ptr->write_row_fn = write_row_fn;
  196473. }
  196474. #if defined(PNG_WRITE_USER_TRANSFORM_SUPPORTED)
  196475. void PNGAPI
  196476. png_set_write_user_transform_fn(png_structp png_ptr, png_user_transform_ptr
  196477. write_user_transform_fn)
  196478. {
  196479. png_debug(1, "in png_set_write_user_transform_fn\n");
  196480. if (png_ptr == NULL)
  196481. return;
  196482. png_ptr->transformations |= PNG_USER_TRANSFORM;
  196483. png_ptr->write_user_transform_fn = write_user_transform_fn;
  196484. }
  196485. #endif
  196486. #if defined(PNG_INFO_IMAGE_SUPPORTED)
  196487. void PNGAPI
  196488. png_write_png(png_structp png_ptr, png_infop info_ptr,
  196489. int transforms, voidp params)
  196490. {
  196491. if (png_ptr == NULL || info_ptr == NULL)
  196492. return;
  196493. #if defined(PNG_WRITE_INVERT_ALPHA_SUPPORTED)
  196494. /* invert the alpha channel from opacity to transparency */
  196495. if (transforms & PNG_TRANSFORM_INVERT_ALPHA)
  196496. png_set_invert_alpha(png_ptr);
  196497. #endif
  196498. /* Write the file header information. */
  196499. png_write_info(png_ptr, info_ptr);
  196500. /* ------ these transformations don't touch the info structure ------- */
  196501. #if defined(PNG_WRITE_INVERT_SUPPORTED)
  196502. /* invert monochrome pixels */
  196503. if (transforms & PNG_TRANSFORM_INVERT_MONO)
  196504. png_set_invert_mono(png_ptr);
  196505. #endif
  196506. #if defined(PNG_WRITE_SHIFT_SUPPORTED)
  196507. /* Shift the pixels up to a legal bit depth and fill in
  196508. * as appropriate to correctly scale the image.
  196509. */
  196510. if ((transforms & PNG_TRANSFORM_SHIFT)
  196511. && (info_ptr->valid & PNG_INFO_sBIT))
  196512. png_set_shift(png_ptr, &info_ptr->sig_bit);
  196513. #endif
  196514. #if defined(PNG_WRITE_PACK_SUPPORTED)
  196515. /* pack pixels into bytes */
  196516. if (transforms & PNG_TRANSFORM_PACKING)
  196517. png_set_packing(png_ptr);
  196518. #endif
  196519. #if defined(PNG_WRITE_SWAP_ALPHA_SUPPORTED)
  196520. /* swap location of alpha bytes from ARGB to RGBA */
  196521. if (transforms & PNG_TRANSFORM_SWAP_ALPHA)
  196522. png_set_swap_alpha(png_ptr);
  196523. #endif
  196524. #if defined(PNG_WRITE_FILLER_SUPPORTED)
  196525. /* Get rid of filler (OR ALPHA) bytes, pack XRGB/RGBX/ARGB/RGBA into
  196526. * RGB (4 channels -> 3 channels). The second parameter is not used.
  196527. */
  196528. if (transforms & PNG_TRANSFORM_STRIP_FILLER)
  196529. png_set_filler(png_ptr, 0, PNG_FILLER_BEFORE);
  196530. #endif
  196531. #if defined(PNG_WRITE_BGR_SUPPORTED)
  196532. /* flip BGR pixels to RGB */
  196533. if (transforms & PNG_TRANSFORM_BGR)
  196534. png_set_bgr(png_ptr);
  196535. #endif
  196536. #if defined(PNG_WRITE_SWAP_SUPPORTED)
  196537. /* swap bytes of 16-bit files to most significant byte first */
  196538. if (transforms & PNG_TRANSFORM_SWAP_ENDIAN)
  196539. png_set_swap(png_ptr);
  196540. #endif
  196541. #if defined(PNG_WRITE_PACKSWAP_SUPPORTED)
  196542. /* swap bits of 1, 2, 4 bit packed pixel formats */
  196543. if (transforms & PNG_TRANSFORM_PACKSWAP)
  196544. png_set_packswap(png_ptr);
  196545. #endif
  196546. /* ----------------------- end of transformations ------------------- */
  196547. /* write the bits */
  196548. if (info_ptr->valid & PNG_INFO_IDAT)
  196549. png_write_image(png_ptr, info_ptr->row_pointers);
  196550. /* It is REQUIRED to call this to finish writing the rest of the file */
  196551. png_write_end(png_ptr, info_ptr);
  196552. transforms = transforms; /* quiet compiler warnings */
  196553. params = params;
  196554. }
  196555. #endif
  196556. #endif /* PNG_WRITE_SUPPORTED */
  196557. /*** End of inlined file: pngwrite.c ***/
  196558. /*** Start of inlined file: pngwtran.c ***/
  196559. /* pngwtran.c - transforms the data in a row for PNG writers
  196560. *
  196561. * Last changed in libpng 1.2.9 April 14, 2006
  196562. * For conditions of distribution and use, see copyright notice in png.h
  196563. * Copyright (c) 1998-2006 Glenn Randers-Pehrson
  196564. * (Version 0.96 Copyright (c) 1996, 1997 Andreas Dilger)
  196565. * (Version 0.88 Copyright (c) 1995, 1996 Guy Eric Schalnat, Group 42, Inc.)
  196566. */
  196567. #define PNG_INTERNAL
  196568. #ifdef PNG_WRITE_SUPPORTED
  196569. /* Transform the data according to the user's wishes. The order of
  196570. * transformations is significant.
  196571. */
  196572. void /* PRIVATE */
  196573. png_do_write_transformations(png_structp png_ptr)
  196574. {
  196575. png_debug(1, "in png_do_write_transformations\n");
  196576. if (png_ptr == NULL)
  196577. return;
  196578. #if defined(PNG_WRITE_USER_TRANSFORM_SUPPORTED)
  196579. if (png_ptr->transformations & PNG_USER_TRANSFORM)
  196580. if(png_ptr->write_user_transform_fn != NULL)
  196581. (*(png_ptr->write_user_transform_fn)) /* user write transform function */
  196582. (png_ptr, /* png_ptr */
  196583. &(png_ptr->row_info), /* row_info: */
  196584. /* png_uint_32 width; width of row */
  196585. /* png_uint_32 rowbytes; number of bytes in row */
  196586. /* png_byte color_type; color type of pixels */
  196587. /* png_byte bit_depth; bit depth of samples */
  196588. /* png_byte channels; number of channels (1-4) */
  196589. /* png_byte pixel_depth; bits per pixel (depth*channels) */
  196590. png_ptr->row_buf + 1); /* start of pixel data for row */
  196591. #endif
  196592. #if defined(PNG_WRITE_FILLER_SUPPORTED)
  196593. if (png_ptr->transformations & PNG_FILLER)
  196594. png_do_strip_filler(&(png_ptr->row_info), png_ptr->row_buf + 1,
  196595. png_ptr->flags);
  196596. #endif
  196597. #if defined(PNG_WRITE_PACKSWAP_SUPPORTED)
  196598. if (png_ptr->transformations & PNG_PACKSWAP)
  196599. png_do_packswap(&(png_ptr->row_info), png_ptr->row_buf + 1);
  196600. #endif
  196601. #if defined(PNG_WRITE_PACK_SUPPORTED)
  196602. if (png_ptr->transformations & PNG_PACK)
  196603. png_do_pack(&(png_ptr->row_info), png_ptr->row_buf + 1,
  196604. (png_uint_32)png_ptr->bit_depth);
  196605. #endif
  196606. #if defined(PNG_WRITE_SWAP_SUPPORTED)
  196607. if (png_ptr->transformations & PNG_SWAP_BYTES)
  196608. png_do_swap(&(png_ptr->row_info), png_ptr->row_buf + 1);
  196609. #endif
  196610. #if defined(PNG_WRITE_SHIFT_SUPPORTED)
  196611. if (png_ptr->transformations & PNG_SHIFT)
  196612. png_do_shift(&(png_ptr->row_info), png_ptr->row_buf + 1,
  196613. &(png_ptr->shift));
  196614. #endif
  196615. #if defined(PNG_WRITE_SWAP_ALPHA_SUPPORTED)
  196616. if (png_ptr->transformations & PNG_SWAP_ALPHA)
  196617. png_do_write_swap_alpha(&(png_ptr->row_info), png_ptr->row_buf + 1);
  196618. #endif
  196619. #if defined(PNG_WRITE_INVERT_ALPHA_SUPPORTED)
  196620. if (png_ptr->transformations & PNG_INVERT_ALPHA)
  196621. png_do_write_invert_alpha(&(png_ptr->row_info), png_ptr->row_buf + 1);
  196622. #endif
  196623. #if defined(PNG_WRITE_BGR_SUPPORTED)
  196624. if (png_ptr->transformations & PNG_BGR)
  196625. png_do_bgr(&(png_ptr->row_info), png_ptr->row_buf + 1);
  196626. #endif
  196627. #if defined(PNG_WRITE_INVERT_SUPPORTED)
  196628. if (png_ptr->transformations & PNG_INVERT_MONO)
  196629. png_do_invert(&(png_ptr->row_info), png_ptr->row_buf + 1);
  196630. #endif
  196631. }
  196632. #if defined(PNG_WRITE_PACK_SUPPORTED)
  196633. /* Pack pixels into bytes. Pass the true bit depth in bit_depth. The
  196634. * row_info bit depth should be 8 (one pixel per byte). The channels
  196635. * should be 1 (this only happens on grayscale and paletted images).
  196636. */
  196637. void /* PRIVATE */
  196638. png_do_pack(png_row_infop row_info, png_bytep row, png_uint_32 bit_depth)
  196639. {
  196640. png_debug(1, "in png_do_pack\n");
  196641. if (row_info->bit_depth == 8 &&
  196642. #if defined(PNG_USELESS_TESTS_SUPPORTED)
  196643. row != NULL && row_info != NULL &&
  196644. #endif
  196645. row_info->channels == 1)
  196646. {
  196647. switch ((int)bit_depth)
  196648. {
  196649. case 1:
  196650. {
  196651. png_bytep sp, dp;
  196652. int mask, v;
  196653. png_uint_32 i;
  196654. png_uint_32 row_width = row_info->width;
  196655. sp = row;
  196656. dp = row;
  196657. mask = 0x80;
  196658. v = 0;
  196659. for (i = 0; i < row_width; i++)
  196660. {
  196661. if (*sp != 0)
  196662. v |= mask;
  196663. sp++;
  196664. if (mask > 1)
  196665. mask >>= 1;
  196666. else
  196667. {
  196668. mask = 0x80;
  196669. *dp = (png_byte)v;
  196670. dp++;
  196671. v = 0;
  196672. }
  196673. }
  196674. if (mask != 0x80)
  196675. *dp = (png_byte)v;
  196676. break;
  196677. }
  196678. case 2:
  196679. {
  196680. png_bytep sp, dp;
  196681. int shift, v;
  196682. png_uint_32 i;
  196683. png_uint_32 row_width = row_info->width;
  196684. sp = row;
  196685. dp = row;
  196686. shift = 6;
  196687. v = 0;
  196688. for (i = 0; i < row_width; i++)
  196689. {
  196690. png_byte value;
  196691. value = (png_byte)(*sp & 0x03);
  196692. v |= (value << shift);
  196693. if (shift == 0)
  196694. {
  196695. shift = 6;
  196696. *dp = (png_byte)v;
  196697. dp++;
  196698. v = 0;
  196699. }
  196700. else
  196701. shift -= 2;
  196702. sp++;
  196703. }
  196704. if (shift != 6)
  196705. *dp = (png_byte)v;
  196706. break;
  196707. }
  196708. case 4:
  196709. {
  196710. png_bytep sp, dp;
  196711. int shift, v;
  196712. png_uint_32 i;
  196713. png_uint_32 row_width = row_info->width;
  196714. sp = row;
  196715. dp = row;
  196716. shift = 4;
  196717. v = 0;
  196718. for (i = 0; i < row_width; i++)
  196719. {
  196720. png_byte value;
  196721. value = (png_byte)(*sp & 0x0f);
  196722. v |= (value << shift);
  196723. if (shift == 0)
  196724. {
  196725. shift = 4;
  196726. *dp = (png_byte)v;
  196727. dp++;
  196728. v = 0;
  196729. }
  196730. else
  196731. shift -= 4;
  196732. sp++;
  196733. }
  196734. if (shift != 4)
  196735. *dp = (png_byte)v;
  196736. break;
  196737. }
  196738. }
  196739. row_info->bit_depth = (png_byte)bit_depth;
  196740. row_info->pixel_depth = (png_byte)(bit_depth * row_info->channels);
  196741. row_info->rowbytes = PNG_ROWBYTES(row_info->pixel_depth,
  196742. row_info->width);
  196743. }
  196744. }
  196745. #endif
  196746. #if defined(PNG_WRITE_SHIFT_SUPPORTED)
  196747. /* Shift pixel values to take advantage of whole range. Pass the
  196748. * true number of bits in bit_depth. The row should be packed
  196749. * according to row_info->bit_depth. Thus, if you had a row of
  196750. * bit depth 4, but the pixels only had values from 0 to 7, you
  196751. * would pass 3 as bit_depth, and this routine would translate the
  196752. * data to 0 to 15.
  196753. */
  196754. void /* PRIVATE */
  196755. png_do_shift(png_row_infop row_info, png_bytep row, png_color_8p bit_depth)
  196756. {
  196757. png_debug(1, "in png_do_shift\n");
  196758. #if defined(PNG_USELESS_TESTS_SUPPORTED)
  196759. if (row != NULL && row_info != NULL &&
  196760. #else
  196761. if (
  196762. #endif
  196763. row_info->color_type != PNG_COLOR_TYPE_PALETTE)
  196764. {
  196765. int shift_start[4], shift_dec[4];
  196766. int channels = 0;
  196767. if (row_info->color_type & PNG_COLOR_MASK_COLOR)
  196768. {
  196769. shift_start[channels] = row_info->bit_depth - bit_depth->red;
  196770. shift_dec[channels] = bit_depth->red;
  196771. channels++;
  196772. shift_start[channels] = row_info->bit_depth - bit_depth->green;
  196773. shift_dec[channels] = bit_depth->green;
  196774. channels++;
  196775. shift_start[channels] = row_info->bit_depth - bit_depth->blue;
  196776. shift_dec[channels] = bit_depth->blue;
  196777. channels++;
  196778. }
  196779. else
  196780. {
  196781. shift_start[channels] = row_info->bit_depth - bit_depth->gray;
  196782. shift_dec[channels] = bit_depth->gray;
  196783. channels++;
  196784. }
  196785. if (row_info->color_type & PNG_COLOR_MASK_ALPHA)
  196786. {
  196787. shift_start[channels] = row_info->bit_depth - bit_depth->alpha;
  196788. shift_dec[channels] = bit_depth->alpha;
  196789. channels++;
  196790. }
  196791. /* with low row depths, could only be grayscale, so one channel */
  196792. if (row_info->bit_depth < 8)
  196793. {
  196794. png_bytep bp = row;
  196795. png_uint_32 i;
  196796. png_byte mask;
  196797. png_uint_32 row_bytes = row_info->rowbytes;
  196798. if (bit_depth->gray == 1 && row_info->bit_depth == 2)
  196799. mask = 0x55;
  196800. else if (row_info->bit_depth == 4 && bit_depth->gray == 3)
  196801. mask = 0x11;
  196802. else
  196803. mask = 0xff;
  196804. for (i = 0; i < row_bytes; i++, bp++)
  196805. {
  196806. png_uint_16 v;
  196807. int j;
  196808. v = *bp;
  196809. *bp = 0;
  196810. for (j = shift_start[0]; j > -shift_dec[0]; j -= shift_dec[0])
  196811. {
  196812. if (j > 0)
  196813. *bp |= (png_byte)((v << j) & 0xff);
  196814. else
  196815. *bp |= (png_byte)((v >> (-j)) & mask);
  196816. }
  196817. }
  196818. }
  196819. else if (row_info->bit_depth == 8)
  196820. {
  196821. png_bytep bp = row;
  196822. png_uint_32 i;
  196823. png_uint_32 istop = channels * row_info->width;
  196824. for (i = 0; i < istop; i++, bp++)
  196825. {
  196826. png_uint_16 v;
  196827. int j;
  196828. int c = (int)(i%channels);
  196829. v = *bp;
  196830. *bp = 0;
  196831. for (j = shift_start[c]; j > -shift_dec[c]; j -= shift_dec[c])
  196832. {
  196833. if (j > 0)
  196834. *bp |= (png_byte)((v << j) & 0xff);
  196835. else
  196836. *bp |= (png_byte)((v >> (-j)) & 0xff);
  196837. }
  196838. }
  196839. }
  196840. else
  196841. {
  196842. png_bytep bp;
  196843. png_uint_32 i;
  196844. png_uint_32 istop = channels * row_info->width;
  196845. for (bp = row, i = 0; i < istop; i++)
  196846. {
  196847. int c = (int)(i%channels);
  196848. png_uint_16 value, v;
  196849. int j;
  196850. v = (png_uint_16)(((png_uint_16)(*bp) << 8) + *(bp + 1));
  196851. value = 0;
  196852. for (j = shift_start[c]; j > -shift_dec[c]; j -= shift_dec[c])
  196853. {
  196854. if (j > 0)
  196855. value |= (png_uint_16)((v << j) & (png_uint_16)0xffff);
  196856. else
  196857. value |= (png_uint_16)((v >> (-j)) & (png_uint_16)0xffff);
  196858. }
  196859. *bp++ = (png_byte)(value >> 8);
  196860. *bp++ = (png_byte)(value & 0xff);
  196861. }
  196862. }
  196863. }
  196864. }
  196865. #endif
  196866. #if defined(PNG_WRITE_SWAP_ALPHA_SUPPORTED)
  196867. void /* PRIVATE */
  196868. png_do_write_swap_alpha(png_row_infop row_info, png_bytep row)
  196869. {
  196870. png_debug(1, "in png_do_write_swap_alpha\n");
  196871. #if defined(PNG_USELESS_TESTS_SUPPORTED)
  196872. if (row != NULL && row_info != NULL)
  196873. #endif
  196874. {
  196875. if (row_info->color_type == PNG_COLOR_TYPE_RGB_ALPHA)
  196876. {
  196877. /* This converts from ARGB to RGBA */
  196878. if (row_info->bit_depth == 8)
  196879. {
  196880. png_bytep sp, dp;
  196881. png_uint_32 i;
  196882. png_uint_32 row_width = row_info->width;
  196883. for (i = 0, sp = dp = row; i < row_width; i++)
  196884. {
  196885. png_byte save = *(sp++);
  196886. *(dp++) = *(sp++);
  196887. *(dp++) = *(sp++);
  196888. *(dp++) = *(sp++);
  196889. *(dp++) = save;
  196890. }
  196891. }
  196892. /* This converts from AARRGGBB to RRGGBBAA */
  196893. else
  196894. {
  196895. png_bytep sp, dp;
  196896. png_uint_32 i;
  196897. png_uint_32 row_width = row_info->width;
  196898. for (i = 0, sp = dp = row; i < row_width; i++)
  196899. {
  196900. png_byte save[2];
  196901. save[0] = *(sp++);
  196902. save[1] = *(sp++);
  196903. *(dp++) = *(sp++);
  196904. *(dp++) = *(sp++);
  196905. *(dp++) = *(sp++);
  196906. *(dp++) = *(sp++);
  196907. *(dp++) = *(sp++);
  196908. *(dp++) = *(sp++);
  196909. *(dp++) = save[0];
  196910. *(dp++) = save[1];
  196911. }
  196912. }
  196913. }
  196914. else if (row_info->color_type == PNG_COLOR_TYPE_GRAY_ALPHA)
  196915. {
  196916. /* This converts from AG to GA */
  196917. if (row_info->bit_depth == 8)
  196918. {
  196919. png_bytep sp, dp;
  196920. png_uint_32 i;
  196921. png_uint_32 row_width = row_info->width;
  196922. for (i = 0, sp = dp = row; i < row_width; i++)
  196923. {
  196924. png_byte save = *(sp++);
  196925. *(dp++) = *(sp++);
  196926. *(dp++) = save;
  196927. }
  196928. }
  196929. /* This converts from AAGG to GGAA */
  196930. else
  196931. {
  196932. png_bytep sp, dp;
  196933. png_uint_32 i;
  196934. png_uint_32 row_width = row_info->width;
  196935. for (i = 0, sp = dp = row; i < row_width; i++)
  196936. {
  196937. png_byte save[2];
  196938. save[0] = *(sp++);
  196939. save[1] = *(sp++);
  196940. *(dp++) = *(sp++);
  196941. *(dp++) = *(sp++);
  196942. *(dp++) = save[0];
  196943. *(dp++) = save[1];
  196944. }
  196945. }
  196946. }
  196947. }
  196948. }
  196949. #endif
  196950. #if defined(PNG_WRITE_INVERT_ALPHA_SUPPORTED)
  196951. void /* PRIVATE */
  196952. png_do_write_invert_alpha(png_row_infop row_info, png_bytep row)
  196953. {
  196954. png_debug(1, "in png_do_write_invert_alpha\n");
  196955. #if defined(PNG_USELESS_TESTS_SUPPORTED)
  196956. if (row != NULL && row_info != NULL)
  196957. #endif
  196958. {
  196959. if (row_info->color_type == PNG_COLOR_TYPE_RGB_ALPHA)
  196960. {
  196961. /* This inverts the alpha channel in RGBA */
  196962. if (row_info->bit_depth == 8)
  196963. {
  196964. png_bytep sp, dp;
  196965. png_uint_32 i;
  196966. png_uint_32 row_width = row_info->width;
  196967. for (i = 0, sp = dp = row; i < row_width; i++)
  196968. {
  196969. /* does nothing
  196970. *(dp++) = *(sp++);
  196971. *(dp++) = *(sp++);
  196972. *(dp++) = *(sp++);
  196973. */
  196974. sp+=3; dp = sp;
  196975. *(dp++) = (png_byte)(255 - *(sp++));
  196976. }
  196977. }
  196978. /* This inverts the alpha channel in RRGGBBAA */
  196979. else
  196980. {
  196981. png_bytep sp, dp;
  196982. png_uint_32 i;
  196983. png_uint_32 row_width = row_info->width;
  196984. for (i = 0, sp = dp = row; i < row_width; i++)
  196985. {
  196986. /* does nothing
  196987. *(dp++) = *(sp++);
  196988. *(dp++) = *(sp++);
  196989. *(dp++) = *(sp++);
  196990. *(dp++) = *(sp++);
  196991. *(dp++) = *(sp++);
  196992. *(dp++) = *(sp++);
  196993. */
  196994. sp+=6; dp = sp;
  196995. *(dp++) = (png_byte)(255 - *(sp++));
  196996. *(dp++) = (png_byte)(255 - *(sp++));
  196997. }
  196998. }
  196999. }
  197000. else if (row_info->color_type == PNG_COLOR_TYPE_GRAY_ALPHA)
  197001. {
  197002. /* This inverts the alpha channel in GA */
  197003. if (row_info->bit_depth == 8)
  197004. {
  197005. png_bytep sp, dp;
  197006. png_uint_32 i;
  197007. png_uint_32 row_width = row_info->width;
  197008. for (i = 0, sp = dp = row; i < row_width; i++)
  197009. {
  197010. *(dp++) = *(sp++);
  197011. *(dp++) = (png_byte)(255 - *(sp++));
  197012. }
  197013. }
  197014. /* This inverts the alpha channel in GGAA */
  197015. else
  197016. {
  197017. png_bytep sp, dp;
  197018. png_uint_32 i;
  197019. png_uint_32 row_width = row_info->width;
  197020. for (i = 0, sp = dp = row; i < row_width; i++)
  197021. {
  197022. /* does nothing
  197023. *(dp++) = *(sp++);
  197024. *(dp++) = *(sp++);
  197025. */
  197026. sp+=2; dp = sp;
  197027. *(dp++) = (png_byte)(255 - *(sp++));
  197028. *(dp++) = (png_byte)(255 - *(sp++));
  197029. }
  197030. }
  197031. }
  197032. }
  197033. }
  197034. #endif
  197035. #if defined(PNG_MNG_FEATURES_SUPPORTED)
  197036. /* undoes intrapixel differencing */
  197037. void /* PRIVATE */
  197038. png_do_write_intrapixel(png_row_infop row_info, png_bytep row)
  197039. {
  197040. png_debug(1, "in png_do_write_intrapixel\n");
  197041. if (
  197042. #if defined(PNG_USELESS_TESTS_SUPPORTED)
  197043. row != NULL && row_info != NULL &&
  197044. #endif
  197045. (row_info->color_type & PNG_COLOR_MASK_COLOR))
  197046. {
  197047. int bytes_per_pixel;
  197048. png_uint_32 row_width = row_info->width;
  197049. if (row_info->bit_depth == 8)
  197050. {
  197051. png_bytep rp;
  197052. png_uint_32 i;
  197053. if (row_info->color_type == PNG_COLOR_TYPE_RGB)
  197054. bytes_per_pixel = 3;
  197055. else if (row_info->color_type == PNG_COLOR_TYPE_RGB_ALPHA)
  197056. bytes_per_pixel = 4;
  197057. else
  197058. return;
  197059. for (i = 0, rp = row; i < row_width; i++, rp += bytes_per_pixel)
  197060. {
  197061. *(rp) = (png_byte)((*rp - *(rp+1))&0xff);
  197062. *(rp+2) = (png_byte)((*(rp+2) - *(rp+1))&0xff);
  197063. }
  197064. }
  197065. else if (row_info->bit_depth == 16)
  197066. {
  197067. png_bytep rp;
  197068. png_uint_32 i;
  197069. if (row_info->color_type == PNG_COLOR_TYPE_RGB)
  197070. bytes_per_pixel = 6;
  197071. else if (row_info->color_type == PNG_COLOR_TYPE_RGB_ALPHA)
  197072. bytes_per_pixel = 8;
  197073. else
  197074. return;
  197075. for (i = 0, rp = row; i < row_width; i++, rp += bytes_per_pixel)
  197076. {
  197077. png_uint_32 s0 = (*(rp ) << 8) | *(rp+1);
  197078. png_uint_32 s1 = (*(rp+2) << 8) | *(rp+3);
  197079. png_uint_32 s2 = (*(rp+4) << 8) | *(rp+5);
  197080. png_uint_32 red = (png_uint_32)((s0-s1) & 0xffffL);
  197081. png_uint_32 blue = (png_uint_32)((s2-s1) & 0xffffL);
  197082. *(rp ) = (png_byte)((red >> 8) & 0xff);
  197083. *(rp+1) = (png_byte)(red & 0xff);
  197084. *(rp+4) = (png_byte)((blue >> 8) & 0xff);
  197085. *(rp+5) = (png_byte)(blue & 0xff);
  197086. }
  197087. }
  197088. }
  197089. }
  197090. #endif /* PNG_MNG_FEATURES_SUPPORTED */
  197091. #endif /* PNG_WRITE_SUPPORTED */
  197092. /*** End of inlined file: pngwtran.c ***/
  197093. /*** Start of inlined file: pngwutil.c ***/
  197094. /* pngwutil.c - utilities to write a PNG file
  197095. *
  197096. * Last changed in libpng 1.2.20 Septhember 3, 2007
  197097. * For conditions of distribution and use, see copyright notice in png.h
  197098. * Copyright (c) 1998-2007 Glenn Randers-Pehrson
  197099. * (Version 0.96 Copyright (c) 1996, 1997 Andreas Dilger)
  197100. * (Version 0.88 Copyright (c) 1995, 1996 Guy Eric Schalnat, Group 42, Inc.)
  197101. */
  197102. #define PNG_INTERNAL
  197103. #ifdef PNG_WRITE_SUPPORTED
  197104. /* Place a 32-bit number into a buffer in PNG byte order. We work
  197105. * with unsigned numbers for convenience, although one supported
  197106. * ancillary chunk uses signed (two's complement) numbers.
  197107. */
  197108. void PNGAPI
  197109. png_save_uint_32(png_bytep buf, png_uint_32 i)
  197110. {
  197111. buf[0] = (png_byte)((i >> 24) & 0xff);
  197112. buf[1] = (png_byte)((i >> 16) & 0xff);
  197113. buf[2] = (png_byte)((i >> 8) & 0xff);
  197114. buf[3] = (png_byte)(i & 0xff);
  197115. }
  197116. /* The png_save_int_32 function assumes integers are stored in two's
  197117. * complement format. If this isn't the case, then this routine needs to
  197118. * be modified to write data in two's complement format.
  197119. */
  197120. void PNGAPI
  197121. png_save_int_32(png_bytep buf, png_int_32 i)
  197122. {
  197123. buf[0] = (png_byte)((i >> 24) & 0xff);
  197124. buf[1] = (png_byte)((i >> 16) & 0xff);
  197125. buf[2] = (png_byte)((i >> 8) & 0xff);
  197126. buf[3] = (png_byte)(i & 0xff);
  197127. }
  197128. /* Place a 16-bit number into a buffer in PNG byte order.
  197129. * The parameter is declared unsigned int, not png_uint_16,
  197130. * just to avoid potential problems on pre-ANSI C compilers.
  197131. */
  197132. void PNGAPI
  197133. png_save_uint_16(png_bytep buf, unsigned int i)
  197134. {
  197135. buf[0] = (png_byte)((i >> 8) & 0xff);
  197136. buf[1] = (png_byte)(i & 0xff);
  197137. }
  197138. /* Write a PNG chunk all at once. The type is an array of ASCII characters
  197139. * representing the chunk name. The array must be at least 4 bytes in
  197140. * length, and does not need to be null terminated. To be safe, pass the
  197141. * pre-defined chunk names here, and if you need a new one, define it
  197142. * where the others are defined. The length is the length of the data.
  197143. * All the data must be present. If that is not possible, use the
  197144. * png_write_chunk_start(), png_write_chunk_data(), and png_write_chunk_end()
  197145. * functions instead.
  197146. */
  197147. void PNGAPI
  197148. png_write_chunk(png_structp png_ptr, png_bytep chunk_name,
  197149. png_bytep data, png_size_t length)
  197150. {
  197151. if(png_ptr == NULL) return;
  197152. png_write_chunk_start(png_ptr, chunk_name, (png_uint_32)length);
  197153. png_write_chunk_data(png_ptr, data, length);
  197154. png_write_chunk_end(png_ptr);
  197155. }
  197156. /* Write the start of a PNG chunk. The type is the chunk type.
  197157. * The total_length is the sum of the lengths of all the data you will be
  197158. * passing in png_write_chunk_data().
  197159. */
  197160. void PNGAPI
  197161. png_write_chunk_start(png_structp png_ptr, png_bytep chunk_name,
  197162. png_uint_32 length)
  197163. {
  197164. png_byte buf[4];
  197165. png_debug2(0, "Writing %s chunk (%lu bytes)\n", chunk_name, length);
  197166. if(png_ptr == NULL) return;
  197167. /* write the length */
  197168. png_save_uint_32(buf, length);
  197169. png_write_data(png_ptr, buf, (png_size_t)4);
  197170. /* write the chunk name */
  197171. png_write_data(png_ptr, chunk_name, (png_size_t)4);
  197172. /* reset the crc and run it over the chunk name */
  197173. png_reset_crc(png_ptr);
  197174. png_calculate_crc(png_ptr, chunk_name, (png_size_t)4);
  197175. }
  197176. /* Write the data of a PNG chunk started with png_write_chunk_start().
  197177. * Note that multiple calls to this function are allowed, and that the
  197178. * sum of the lengths from these calls *must* add up to the total_length
  197179. * given to png_write_chunk_start().
  197180. */
  197181. void PNGAPI
  197182. png_write_chunk_data(png_structp png_ptr, png_bytep data, png_size_t length)
  197183. {
  197184. /* write the data, and run the CRC over it */
  197185. if(png_ptr == NULL) return;
  197186. if (data != NULL && length > 0)
  197187. {
  197188. png_calculate_crc(png_ptr, data, length);
  197189. png_write_data(png_ptr, data, length);
  197190. }
  197191. }
  197192. /* Finish a chunk started with png_write_chunk_start(). */
  197193. void PNGAPI
  197194. png_write_chunk_end(png_structp png_ptr)
  197195. {
  197196. png_byte buf[4];
  197197. if(png_ptr == NULL) return;
  197198. /* write the crc */
  197199. png_save_uint_32(buf, png_ptr->crc);
  197200. png_write_data(png_ptr, buf, (png_size_t)4);
  197201. }
  197202. /* Simple function to write the signature. If we have already written
  197203. * the magic bytes of the signature, or more likely, the PNG stream is
  197204. * being embedded into another stream and doesn't need its own signature,
  197205. * we should call png_set_sig_bytes() to tell libpng how many of the
  197206. * bytes have already been written.
  197207. */
  197208. void /* PRIVATE */
  197209. png_write_sig(png_structp png_ptr)
  197210. {
  197211. png_byte png_signature[8] = {137, 80, 78, 71, 13, 10, 26, 10};
  197212. /* write the rest of the 8 byte signature */
  197213. png_write_data(png_ptr, &png_signature[png_ptr->sig_bytes],
  197214. (png_size_t)8 - png_ptr->sig_bytes);
  197215. if(png_ptr->sig_bytes < 3)
  197216. png_ptr->mode |= PNG_HAVE_PNG_SIGNATURE;
  197217. }
  197218. #if defined(PNG_WRITE_TEXT_SUPPORTED) || defined(PNG_WRITE_iCCP_SUPPORTED)
  197219. /*
  197220. * This pair of functions encapsulates the operation of (a) compressing a
  197221. * text string, and (b) issuing it later as a series of chunk data writes.
  197222. * The compression_state structure is shared context for these functions
  197223. * set up by the caller in order to make the whole mess thread-safe.
  197224. */
  197225. typedef struct
  197226. {
  197227. char *input; /* the uncompressed input data */
  197228. int input_len; /* its length */
  197229. int num_output_ptr; /* number of output pointers used */
  197230. int max_output_ptr; /* size of output_ptr */
  197231. png_charpp output_ptr; /* array of pointers to output */
  197232. } compression_state;
  197233. /* compress given text into storage in the png_ptr structure */
  197234. static int /* PRIVATE */
  197235. png_text_compress(png_structp png_ptr,
  197236. png_charp text, png_size_t text_len, int compression,
  197237. compression_state *comp)
  197238. {
  197239. int ret;
  197240. comp->num_output_ptr = 0;
  197241. comp->max_output_ptr = 0;
  197242. comp->output_ptr = NULL;
  197243. comp->input = NULL;
  197244. comp->input_len = 0;
  197245. /* we may just want to pass the text right through */
  197246. if (compression == PNG_TEXT_COMPRESSION_NONE)
  197247. {
  197248. comp->input = text;
  197249. comp->input_len = text_len;
  197250. return((int)text_len);
  197251. }
  197252. if (compression >= PNG_TEXT_COMPRESSION_LAST)
  197253. {
  197254. #if !defined(PNG_NO_STDIO) && !defined(_WIN32_WCE)
  197255. char msg[50];
  197256. png_snprintf(msg, 50, "Unknown compression type %d", compression);
  197257. png_warning(png_ptr, msg);
  197258. #else
  197259. png_warning(png_ptr, "Unknown compression type");
  197260. #endif
  197261. }
  197262. /* We can't write the chunk until we find out how much data we have,
  197263. * which means we need to run the compressor first and save the
  197264. * output. This shouldn't be a problem, as the vast majority of
  197265. * comments should be reasonable, but we will set up an array of
  197266. * malloc'd pointers to be sure.
  197267. *
  197268. * If we knew the application was well behaved, we could simplify this
  197269. * greatly by assuming we can always malloc an output buffer large
  197270. * enough to hold the compressed text ((1001 * text_len / 1000) + 12)
  197271. * and malloc this directly. The only time this would be a bad idea is
  197272. * if we can't malloc more than 64K and we have 64K of random input
  197273. * data, or if the input string is incredibly large (although this
  197274. * wouldn't cause a failure, just a slowdown due to swapping).
  197275. */
  197276. /* set up the compression buffers */
  197277. png_ptr->zstream.avail_in = (uInt)text_len;
  197278. png_ptr->zstream.next_in = (Bytef *)text;
  197279. png_ptr->zstream.avail_out = (uInt)png_ptr->zbuf_size;
  197280. png_ptr->zstream.next_out = (Bytef *)png_ptr->zbuf;
  197281. /* this is the same compression loop as in png_write_row() */
  197282. do
  197283. {
  197284. /* compress the data */
  197285. ret = deflate(&png_ptr->zstream, Z_NO_FLUSH);
  197286. if (ret != Z_OK)
  197287. {
  197288. /* error */
  197289. if (png_ptr->zstream.msg != NULL)
  197290. png_error(png_ptr, png_ptr->zstream.msg);
  197291. else
  197292. png_error(png_ptr, "zlib error");
  197293. }
  197294. /* check to see if we need more room */
  197295. if (!(png_ptr->zstream.avail_out))
  197296. {
  197297. /* make sure the output array has room */
  197298. if (comp->num_output_ptr >= comp->max_output_ptr)
  197299. {
  197300. int old_max;
  197301. old_max = comp->max_output_ptr;
  197302. comp->max_output_ptr = comp->num_output_ptr + 4;
  197303. if (comp->output_ptr != NULL)
  197304. {
  197305. png_charpp old_ptr;
  197306. old_ptr = comp->output_ptr;
  197307. comp->output_ptr = (png_charpp)png_malloc(png_ptr,
  197308. (png_uint_32)(comp->max_output_ptr *
  197309. png_sizeof (png_charpp)));
  197310. png_memcpy(comp->output_ptr, old_ptr, old_max
  197311. * png_sizeof (png_charp));
  197312. png_free(png_ptr, old_ptr);
  197313. }
  197314. else
  197315. comp->output_ptr = (png_charpp)png_malloc(png_ptr,
  197316. (png_uint_32)(comp->max_output_ptr *
  197317. png_sizeof (png_charp)));
  197318. }
  197319. /* save the data */
  197320. comp->output_ptr[comp->num_output_ptr] = (png_charp)png_malloc(png_ptr,
  197321. (png_uint_32)png_ptr->zbuf_size);
  197322. png_memcpy(comp->output_ptr[comp->num_output_ptr], png_ptr->zbuf,
  197323. png_ptr->zbuf_size);
  197324. comp->num_output_ptr++;
  197325. /* and reset the buffer */
  197326. png_ptr->zstream.avail_out = (uInt)png_ptr->zbuf_size;
  197327. png_ptr->zstream.next_out = png_ptr->zbuf;
  197328. }
  197329. /* continue until we don't have any more to compress */
  197330. } while (png_ptr->zstream.avail_in);
  197331. /* finish the compression */
  197332. do
  197333. {
  197334. /* tell zlib we are finished */
  197335. ret = deflate(&png_ptr->zstream, Z_FINISH);
  197336. if (ret == Z_OK)
  197337. {
  197338. /* check to see if we need more room */
  197339. if (!(png_ptr->zstream.avail_out))
  197340. {
  197341. /* check to make sure our output array has room */
  197342. if (comp->num_output_ptr >= comp->max_output_ptr)
  197343. {
  197344. int old_max;
  197345. old_max = comp->max_output_ptr;
  197346. comp->max_output_ptr = comp->num_output_ptr + 4;
  197347. if (comp->output_ptr != NULL)
  197348. {
  197349. png_charpp old_ptr;
  197350. old_ptr = comp->output_ptr;
  197351. /* This could be optimized to realloc() */
  197352. comp->output_ptr = (png_charpp)png_malloc(png_ptr,
  197353. (png_uint_32)(comp->max_output_ptr *
  197354. png_sizeof (png_charpp)));
  197355. png_memcpy(comp->output_ptr, old_ptr,
  197356. old_max * png_sizeof (png_charp));
  197357. png_free(png_ptr, old_ptr);
  197358. }
  197359. else
  197360. comp->output_ptr = (png_charpp)png_malloc(png_ptr,
  197361. (png_uint_32)(comp->max_output_ptr *
  197362. png_sizeof (png_charp)));
  197363. }
  197364. /* save off the data */
  197365. comp->output_ptr[comp->num_output_ptr] =
  197366. (png_charp)png_malloc(png_ptr, (png_uint_32)png_ptr->zbuf_size);
  197367. png_memcpy(comp->output_ptr[comp->num_output_ptr], png_ptr->zbuf,
  197368. png_ptr->zbuf_size);
  197369. comp->num_output_ptr++;
  197370. /* and reset the buffer pointers */
  197371. png_ptr->zstream.avail_out = (uInt)png_ptr->zbuf_size;
  197372. png_ptr->zstream.next_out = png_ptr->zbuf;
  197373. }
  197374. }
  197375. else if (ret != Z_STREAM_END)
  197376. {
  197377. /* we got an error */
  197378. if (png_ptr->zstream.msg != NULL)
  197379. png_error(png_ptr, png_ptr->zstream.msg);
  197380. else
  197381. png_error(png_ptr, "zlib error");
  197382. }
  197383. } while (ret != Z_STREAM_END);
  197384. /* text length is number of buffers plus last buffer */
  197385. text_len = png_ptr->zbuf_size * comp->num_output_ptr;
  197386. if (png_ptr->zstream.avail_out < png_ptr->zbuf_size)
  197387. text_len += png_ptr->zbuf_size - (png_size_t)png_ptr->zstream.avail_out;
  197388. return((int)text_len);
  197389. }
  197390. /* ship the compressed text out via chunk writes */
  197391. static void /* PRIVATE */
  197392. png_write_compressed_data_out(png_structp png_ptr, compression_state *comp)
  197393. {
  197394. int i;
  197395. /* handle the no-compression case */
  197396. if (comp->input)
  197397. {
  197398. png_write_chunk_data(png_ptr, (png_bytep)comp->input,
  197399. (png_size_t)comp->input_len);
  197400. return;
  197401. }
  197402. /* write saved output buffers, if any */
  197403. for (i = 0; i < comp->num_output_ptr; i++)
  197404. {
  197405. png_write_chunk_data(png_ptr,(png_bytep)comp->output_ptr[i],
  197406. png_ptr->zbuf_size);
  197407. png_free(png_ptr, comp->output_ptr[i]);
  197408. comp->output_ptr[i]=NULL;
  197409. }
  197410. if (comp->max_output_ptr != 0)
  197411. png_free(png_ptr, comp->output_ptr);
  197412. comp->output_ptr=NULL;
  197413. /* write anything left in zbuf */
  197414. if (png_ptr->zstream.avail_out < (png_uint_32)png_ptr->zbuf_size)
  197415. png_write_chunk_data(png_ptr, png_ptr->zbuf,
  197416. png_ptr->zbuf_size - png_ptr->zstream.avail_out);
  197417. /* reset zlib for another zTXt/iTXt or image data */
  197418. deflateReset(&png_ptr->zstream);
  197419. png_ptr->zstream.data_type = Z_BINARY;
  197420. }
  197421. #endif
  197422. /* Write the IHDR chunk, and update the png_struct with the necessary
  197423. * information. Note that the rest of this code depends upon this
  197424. * information being correct.
  197425. */
  197426. void /* PRIVATE */
  197427. png_write_IHDR(png_structp png_ptr, png_uint_32 width, png_uint_32 height,
  197428. int bit_depth, int color_type, int compression_type, int filter_type,
  197429. int interlace_type)
  197430. {
  197431. #ifdef PNG_USE_LOCAL_ARRAYS
  197432. PNG_IHDR;
  197433. #endif
  197434. png_byte buf[13]; /* buffer to store the IHDR info */
  197435. png_debug(1, "in png_write_IHDR\n");
  197436. /* Check that we have valid input data from the application info */
  197437. switch (color_type)
  197438. {
  197439. case PNG_COLOR_TYPE_GRAY:
  197440. switch (bit_depth)
  197441. {
  197442. case 1:
  197443. case 2:
  197444. case 4:
  197445. case 8:
  197446. case 16: png_ptr->channels = 1; break;
  197447. default: png_error(png_ptr,"Invalid bit depth for grayscale image");
  197448. }
  197449. break;
  197450. case PNG_COLOR_TYPE_RGB:
  197451. if (bit_depth != 8 && bit_depth != 16)
  197452. png_error(png_ptr, "Invalid bit depth for RGB image");
  197453. png_ptr->channels = 3;
  197454. break;
  197455. case PNG_COLOR_TYPE_PALETTE:
  197456. switch (bit_depth)
  197457. {
  197458. case 1:
  197459. case 2:
  197460. case 4:
  197461. case 8: png_ptr->channels = 1; break;
  197462. default: png_error(png_ptr, "Invalid bit depth for paletted image");
  197463. }
  197464. break;
  197465. case PNG_COLOR_TYPE_GRAY_ALPHA:
  197466. if (bit_depth != 8 && bit_depth != 16)
  197467. png_error(png_ptr, "Invalid bit depth for grayscale+alpha image");
  197468. png_ptr->channels = 2;
  197469. break;
  197470. case PNG_COLOR_TYPE_RGB_ALPHA:
  197471. if (bit_depth != 8 && bit_depth != 16)
  197472. png_error(png_ptr, "Invalid bit depth for RGBA image");
  197473. png_ptr->channels = 4;
  197474. break;
  197475. default:
  197476. png_error(png_ptr, "Invalid image color type specified");
  197477. }
  197478. if (compression_type != PNG_COMPRESSION_TYPE_BASE)
  197479. {
  197480. png_warning(png_ptr, "Invalid compression type specified");
  197481. compression_type = PNG_COMPRESSION_TYPE_BASE;
  197482. }
  197483. /* Write filter_method 64 (intrapixel differencing) only if
  197484. * 1. Libpng was compiled with PNG_MNG_FEATURES_SUPPORTED and
  197485. * 2. Libpng did not write a PNG signature (this filter_method is only
  197486. * used in PNG datastreams that are embedded in MNG datastreams) and
  197487. * 3. The application called png_permit_mng_features with a mask that
  197488. * included PNG_FLAG_MNG_FILTER_64 and
  197489. * 4. The filter_method is 64 and
  197490. * 5. The color_type is RGB or RGBA
  197491. */
  197492. if (
  197493. #if defined(PNG_MNG_FEATURES_SUPPORTED)
  197494. !((png_ptr->mng_features_permitted & PNG_FLAG_MNG_FILTER_64) &&
  197495. ((png_ptr->mode&PNG_HAVE_PNG_SIGNATURE) == 0) &&
  197496. (color_type == PNG_COLOR_TYPE_RGB ||
  197497. color_type == PNG_COLOR_TYPE_RGB_ALPHA) &&
  197498. (filter_type == PNG_INTRAPIXEL_DIFFERENCING)) &&
  197499. #endif
  197500. filter_type != PNG_FILTER_TYPE_BASE)
  197501. {
  197502. png_warning(png_ptr, "Invalid filter type specified");
  197503. filter_type = PNG_FILTER_TYPE_BASE;
  197504. }
  197505. #ifdef PNG_WRITE_INTERLACING_SUPPORTED
  197506. if (interlace_type != PNG_INTERLACE_NONE &&
  197507. interlace_type != PNG_INTERLACE_ADAM7)
  197508. {
  197509. png_warning(png_ptr, "Invalid interlace type specified");
  197510. interlace_type = PNG_INTERLACE_ADAM7;
  197511. }
  197512. #else
  197513. interlace_type=PNG_INTERLACE_NONE;
  197514. #endif
  197515. /* save off the relevent information */
  197516. png_ptr->bit_depth = (png_byte)bit_depth;
  197517. png_ptr->color_type = (png_byte)color_type;
  197518. png_ptr->interlaced = (png_byte)interlace_type;
  197519. #if defined(PNG_MNG_FEATURES_SUPPORTED)
  197520. png_ptr->filter_type = (png_byte)filter_type;
  197521. #endif
  197522. png_ptr->compression_type = (png_byte)compression_type;
  197523. png_ptr->width = width;
  197524. png_ptr->height = height;
  197525. png_ptr->pixel_depth = (png_byte)(bit_depth * png_ptr->channels);
  197526. png_ptr->rowbytes = PNG_ROWBYTES(png_ptr->pixel_depth, width);
  197527. /* set the usr info, so any transformations can modify it */
  197528. png_ptr->usr_width = png_ptr->width;
  197529. png_ptr->usr_bit_depth = png_ptr->bit_depth;
  197530. png_ptr->usr_channels = png_ptr->channels;
  197531. /* pack the header information into the buffer */
  197532. png_save_uint_32(buf, width);
  197533. png_save_uint_32(buf + 4, height);
  197534. buf[8] = (png_byte)bit_depth;
  197535. buf[9] = (png_byte)color_type;
  197536. buf[10] = (png_byte)compression_type;
  197537. buf[11] = (png_byte)filter_type;
  197538. buf[12] = (png_byte)interlace_type;
  197539. /* write the chunk */
  197540. png_write_chunk(png_ptr, png_IHDR, buf, (png_size_t)13);
  197541. /* initialize zlib with PNG info */
  197542. png_ptr->zstream.zalloc = png_zalloc;
  197543. png_ptr->zstream.zfree = png_zfree;
  197544. png_ptr->zstream.opaque = (voidpf)png_ptr;
  197545. if (!(png_ptr->do_filter))
  197546. {
  197547. if (png_ptr->color_type == PNG_COLOR_TYPE_PALETTE ||
  197548. png_ptr->bit_depth < 8)
  197549. png_ptr->do_filter = PNG_FILTER_NONE;
  197550. else
  197551. png_ptr->do_filter = PNG_ALL_FILTERS;
  197552. }
  197553. if (!(png_ptr->flags & PNG_FLAG_ZLIB_CUSTOM_STRATEGY))
  197554. {
  197555. if (png_ptr->do_filter != PNG_FILTER_NONE)
  197556. png_ptr->zlib_strategy = Z_FILTERED;
  197557. else
  197558. png_ptr->zlib_strategy = Z_DEFAULT_STRATEGY;
  197559. }
  197560. if (!(png_ptr->flags & PNG_FLAG_ZLIB_CUSTOM_LEVEL))
  197561. png_ptr->zlib_level = Z_DEFAULT_COMPRESSION;
  197562. if (!(png_ptr->flags & PNG_FLAG_ZLIB_CUSTOM_MEM_LEVEL))
  197563. png_ptr->zlib_mem_level = 8;
  197564. if (!(png_ptr->flags & PNG_FLAG_ZLIB_CUSTOM_WINDOW_BITS))
  197565. png_ptr->zlib_window_bits = 15;
  197566. if (!(png_ptr->flags & PNG_FLAG_ZLIB_CUSTOM_METHOD))
  197567. png_ptr->zlib_method = 8;
  197568. if (deflateInit2(&png_ptr->zstream, png_ptr->zlib_level,
  197569. png_ptr->zlib_method, png_ptr->zlib_window_bits,
  197570. png_ptr->zlib_mem_level, png_ptr->zlib_strategy) != Z_OK)
  197571. png_error(png_ptr, "zlib failed to initialize compressor");
  197572. png_ptr->zstream.next_out = png_ptr->zbuf;
  197573. png_ptr->zstream.avail_out = (uInt)png_ptr->zbuf_size;
  197574. /* libpng is not interested in zstream.data_type */
  197575. /* set it to a predefined value, to avoid its evaluation inside zlib */
  197576. png_ptr->zstream.data_type = Z_BINARY;
  197577. png_ptr->mode = PNG_HAVE_IHDR;
  197578. }
  197579. /* write the palette. We are careful not to trust png_color to be in the
  197580. * correct order for PNG, so people can redefine it to any convenient
  197581. * structure.
  197582. */
  197583. void /* PRIVATE */
  197584. png_write_PLTE(png_structp png_ptr, png_colorp palette, png_uint_32 num_pal)
  197585. {
  197586. #ifdef PNG_USE_LOCAL_ARRAYS
  197587. PNG_PLTE;
  197588. #endif
  197589. png_uint_32 i;
  197590. png_colorp pal_ptr;
  197591. png_byte buf[3];
  197592. png_debug(1, "in png_write_PLTE\n");
  197593. if ((
  197594. #if defined(PNG_MNG_FEATURES_SUPPORTED)
  197595. !(png_ptr->mng_features_permitted & PNG_FLAG_MNG_EMPTY_PLTE) &&
  197596. #endif
  197597. num_pal == 0) || num_pal > 256)
  197598. {
  197599. if (png_ptr->color_type == PNG_COLOR_TYPE_PALETTE)
  197600. {
  197601. png_error(png_ptr, "Invalid number of colors in palette");
  197602. }
  197603. else
  197604. {
  197605. png_warning(png_ptr, "Invalid number of colors in palette");
  197606. return;
  197607. }
  197608. }
  197609. if (!(png_ptr->color_type&PNG_COLOR_MASK_COLOR))
  197610. {
  197611. png_warning(png_ptr,
  197612. "Ignoring request to write a PLTE chunk in grayscale PNG");
  197613. return;
  197614. }
  197615. png_ptr->num_palette = (png_uint_16)num_pal;
  197616. png_debug1(3, "num_palette = %d\n", png_ptr->num_palette);
  197617. png_write_chunk_start(png_ptr, png_PLTE, num_pal * 3);
  197618. #ifndef PNG_NO_POINTER_INDEXING
  197619. for (i = 0, pal_ptr = palette; i < num_pal; i++, pal_ptr++)
  197620. {
  197621. buf[0] = pal_ptr->red;
  197622. buf[1] = pal_ptr->green;
  197623. buf[2] = pal_ptr->blue;
  197624. png_write_chunk_data(png_ptr, buf, (png_size_t)3);
  197625. }
  197626. #else
  197627. /* This is a little slower but some buggy compilers need to do this instead */
  197628. pal_ptr=palette;
  197629. for (i = 0; i < num_pal; i++)
  197630. {
  197631. buf[0] = pal_ptr[i].red;
  197632. buf[1] = pal_ptr[i].green;
  197633. buf[2] = pal_ptr[i].blue;
  197634. png_write_chunk_data(png_ptr, buf, (png_size_t)3);
  197635. }
  197636. #endif
  197637. png_write_chunk_end(png_ptr);
  197638. png_ptr->mode |= PNG_HAVE_PLTE;
  197639. }
  197640. /* write an IDAT chunk */
  197641. void /* PRIVATE */
  197642. png_write_IDAT(png_structp png_ptr, png_bytep data, png_size_t length)
  197643. {
  197644. #ifdef PNG_USE_LOCAL_ARRAYS
  197645. PNG_IDAT;
  197646. #endif
  197647. png_debug(1, "in png_write_IDAT\n");
  197648. /* Optimize the CMF field in the zlib stream. */
  197649. /* This hack of the zlib stream is compliant to the stream specification. */
  197650. if (!(png_ptr->mode & PNG_HAVE_IDAT) &&
  197651. png_ptr->compression_type == PNG_COMPRESSION_TYPE_BASE)
  197652. {
  197653. unsigned int z_cmf = data[0]; /* zlib compression method and flags */
  197654. if ((z_cmf & 0x0f) == 8 && (z_cmf & 0xf0) <= 0x70)
  197655. {
  197656. /* Avoid memory underflows and multiplication overflows. */
  197657. /* The conditions below are practically always satisfied;
  197658. however, they still must be checked. */
  197659. if (length >= 2 &&
  197660. png_ptr->height < 16384 && png_ptr->width < 16384)
  197661. {
  197662. png_uint_32 uncompressed_idat_size = png_ptr->height *
  197663. ((png_ptr->width *
  197664. png_ptr->channels * png_ptr->bit_depth + 15) >> 3);
  197665. unsigned int z_cinfo = z_cmf >> 4;
  197666. unsigned int half_z_window_size = 1 << (z_cinfo + 7);
  197667. while (uncompressed_idat_size <= half_z_window_size &&
  197668. half_z_window_size >= 256)
  197669. {
  197670. z_cinfo--;
  197671. half_z_window_size >>= 1;
  197672. }
  197673. z_cmf = (z_cmf & 0x0f) | (z_cinfo << 4);
  197674. if (data[0] != (png_byte)z_cmf)
  197675. {
  197676. data[0] = (png_byte)z_cmf;
  197677. data[1] &= 0xe0;
  197678. data[1] += (png_byte)(0x1f - ((z_cmf << 8) + data[1]) % 0x1f);
  197679. }
  197680. }
  197681. }
  197682. else
  197683. png_error(png_ptr,
  197684. "Invalid zlib compression method or flags in IDAT");
  197685. }
  197686. png_write_chunk(png_ptr, png_IDAT, data, length);
  197687. png_ptr->mode |= PNG_HAVE_IDAT;
  197688. }
  197689. /* write an IEND chunk */
  197690. void /* PRIVATE */
  197691. png_write_IEND(png_structp png_ptr)
  197692. {
  197693. #ifdef PNG_USE_LOCAL_ARRAYS
  197694. PNG_IEND;
  197695. #endif
  197696. png_debug(1, "in png_write_IEND\n");
  197697. png_write_chunk(png_ptr, png_IEND, png_bytep_NULL,
  197698. (png_size_t)0);
  197699. png_ptr->mode |= PNG_HAVE_IEND;
  197700. }
  197701. #if defined(PNG_WRITE_gAMA_SUPPORTED)
  197702. /* write a gAMA chunk */
  197703. #ifdef PNG_FLOATING_POINT_SUPPORTED
  197704. void /* PRIVATE */
  197705. png_write_gAMA(png_structp png_ptr, double file_gamma)
  197706. {
  197707. #ifdef PNG_USE_LOCAL_ARRAYS
  197708. PNG_gAMA;
  197709. #endif
  197710. png_uint_32 igamma;
  197711. png_byte buf[4];
  197712. png_debug(1, "in png_write_gAMA\n");
  197713. /* file_gamma is saved in 1/100,000ths */
  197714. igamma = (png_uint_32)(file_gamma * 100000.0 + 0.5);
  197715. png_save_uint_32(buf, igamma);
  197716. png_write_chunk(png_ptr, png_gAMA, buf, (png_size_t)4);
  197717. }
  197718. #endif
  197719. #ifdef PNG_FIXED_POINT_SUPPORTED
  197720. void /* PRIVATE */
  197721. png_write_gAMA_fixed(png_structp png_ptr, png_fixed_point file_gamma)
  197722. {
  197723. #ifdef PNG_USE_LOCAL_ARRAYS
  197724. PNG_gAMA;
  197725. #endif
  197726. png_byte buf[4];
  197727. png_debug(1, "in png_write_gAMA\n");
  197728. /* file_gamma is saved in 1/100,000ths */
  197729. png_save_uint_32(buf, (png_uint_32)file_gamma);
  197730. png_write_chunk(png_ptr, png_gAMA, buf, (png_size_t)4);
  197731. }
  197732. #endif
  197733. #endif
  197734. #if defined(PNG_WRITE_sRGB_SUPPORTED)
  197735. /* write a sRGB chunk */
  197736. void /* PRIVATE */
  197737. png_write_sRGB(png_structp png_ptr, int srgb_intent)
  197738. {
  197739. #ifdef PNG_USE_LOCAL_ARRAYS
  197740. PNG_sRGB;
  197741. #endif
  197742. png_byte buf[1];
  197743. png_debug(1, "in png_write_sRGB\n");
  197744. if(srgb_intent >= PNG_sRGB_INTENT_LAST)
  197745. png_warning(png_ptr,
  197746. "Invalid sRGB rendering intent specified");
  197747. buf[0]=(png_byte)srgb_intent;
  197748. png_write_chunk(png_ptr, png_sRGB, buf, (png_size_t)1);
  197749. }
  197750. #endif
  197751. #if defined(PNG_WRITE_iCCP_SUPPORTED)
  197752. /* write an iCCP chunk */
  197753. void /* PRIVATE */
  197754. png_write_iCCP(png_structp png_ptr, png_charp name, int compression_type,
  197755. png_charp profile, int profile_len)
  197756. {
  197757. #ifdef PNG_USE_LOCAL_ARRAYS
  197758. PNG_iCCP;
  197759. #endif
  197760. png_size_t name_len;
  197761. png_charp new_name;
  197762. compression_state comp;
  197763. int embedded_profile_len = 0;
  197764. png_debug(1, "in png_write_iCCP\n");
  197765. comp.num_output_ptr = 0;
  197766. comp.max_output_ptr = 0;
  197767. comp.output_ptr = NULL;
  197768. comp.input = NULL;
  197769. comp.input_len = 0;
  197770. if (name == NULL || (name_len = png_check_keyword(png_ptr, name,
  197771. &new_name)) == 0)
  197772. {
  197773. png_warning(png_ptr, "Empty keyword in iCCP chunk");
  197774. return;
  197775. }
  197776. if (compression_type != PNG_COMPRESSION_TYPE_BASE)
  197777. png_warning(png_ptr, "Unknown compression type in iCCP chunk");
  197778. if (profile == NULL)
  197779. profile_len = 0;
  197780. if (profile_len > 3)
  197781. embedded_profile_len =
  197782. ((*( (png_bytep)profile ))<<24) |
  197783. ((*( (png_bytep)profile+1))<<16) |
  197784. ((*( (png_bytep)profile+2))<< 8) |
  197785. ((*( (png_bytep)profile+3)) );
  197786. if (profile_len < embedded_profile_len)
  197787. {
  197788. png_warning(png_ptr,
  197789. "Embedded profile length too large in iCCP chunk");
  197790. return;
  197791. }
  197792. if (profile_len > embedded_profile_len)
  197793. {
  197794. png_warning(png_ptr,
  197795. "Truncating profile to actual length in iCCP chunk");
  197796. profile_len = embedded_profile_len;
  197797. }
  197798. if (profile_len)
  197799. profile_len = png_text_compress(png_ptr, profile, (png_size_t)profile_len,
  197800. PNG_COMPRESSION_TYPE_BASE, &comp);
  197801. /* make sure we include the NULL after the name and the compression type */
  197802. png_write_chunk_start(png_ptr, png_iCCP,
  197803. (png_uint_32)name_len+profile_len+2);
  197804. new_name[name_len+1]=0x00;
  197805. png_write_chunk_data(png_ptr, (png_bytep)new_name, name_len + 2);
  197806. if (profile_len)
  197807. png_write_compressed_data_out(png_ptr, &comp);
  197808. png_write_chunk_end(png_ptr);
  197809. png_free(png_ptr, new_name);
  197810. }
  197811. #endif
  197812. #if defined(PNG_WRITE_sPLT_SUPPORTED)
  197813. /* write a sPLT chunk */
  197814. void /* PRIVATE */
  197815. png_write_sPLT(png_structp png_ptr, png_sPLT_tp spalette)
  197816. {
  197817. #ifdef PNG_USE_LOCAL_ARRAYS
  197818. PNG_sPLT;
  197819. #endif
  197820. png_size_t name_len;
  197821. png_charp new_name;
  197822. png_byte entrybuf[10];
  197823. int entry_size = (spalette->depth == 8 ? 6 : 10);
  197824. int palette_size = entry_size * spalette->nentries;
  197825. png_sPLT_entryp ep;
  197826. #ifdef PNG_NO_POINTER_INDEXING
  197827. int i;
  197828. #endif
  197829. png_debug(1, "in png_write_sPLT\n");
  197830. if (spalette->name == NULL || (name_len = png_check_keyword(png_ptr,
  197831. spalette->name, &new_name))==0)
  197832. {
  197833. png_warning(png_ptr, "Empty keyword in sPLT chunk");
  197834. return;
  197835. }
  197836. /* make sure we include the NULL after the name */
  197837. png_write_chunk_start(png_ptr, png_sPLT,
  197838. (png_uint_32)(name_len + 2 + palette_size));
  197839. png_write_chunk_data(png_ptr, (png_bytep)new_name, name_len + 1);
  197840. png_write_chunk_data(png_ptr, (png_bytep)&spalette->depth, 1);
  197841. /* loop through each palette entry, writing appropriately */
  197842. #ifndef PNG_NO_POINTER_INDEXING
  197843. for (ep = spalette->entries; ep<spalette->entries+spalette->nentries; ep++)
  197844. {
  197845. if (spalette->depth == 8)
  197846. {
  197847. entrybuf[0] = (png_byte)ep->red;
  197848. entrybuf[1] = (png_byte)ep->green;
  197849. entrybuf[2] = (png_byte)ep->blue;
  197850. entrybuf[3] = (png_byte)ep->alpha;
  197851. png_save_uint_16(entrybuf + 4, ep->frequency);
  197852. }
  197853. else
  197854. {
  197855. png_save_uint_16(entrybuf + 0, ep->red);
  197856. png_save_uint_16(entrybuf + 2, ep->green);
  197857. png_save_uint_16(entrybuf + 4, ep->blue);
  197858. png_save_uint_16(entrybuf + 6, ep->alpha);
  197859. png_save_uint_16(entrybuf + 8, ep->frequency);
  197860. }
  197861. png_write_chunk_data(png_ptr, entrybuf, (png_size_t)entry_size);
  197862. }
  197863. #else
  197864. ep=spalette->entries;
  197865. for (i=0; i>spalette->nentries; i++)
  197866. {
  197867. if (spalette->depth == 8)
  197868. {
  197869. entrybuf[0] = (png_byte)ep[i].red;
  197870. entrybuf[1] = (png_byte)ep[i].green;
  197871. entrybuf[2] = (png_byte)ep[i].blue;
  197872. entrybuf[3] = (png_byte)ep[i].alpha;
  197873. png_save_uint_16(entrybuf + 4, ep[i].frequency);
  197874. }
  197875. else
  197876. {
  197877. png_save_uint_16(entrybuf + 0, ep[i].red);
  197878. png_save_uint_16(entrybuf + 2, ep[i].green);
  197879. png_save_uint_16(entrybuf + 4, ep[i].blue);
  197880. png_save_uint_16(entrybuf + 6, ep[i].alpha);
  197881. png_save_uint_16(entrybuf + 8, ep[i].frequency);
  197882. }
  197883. png_write_chunk_data(png_ptr, entrybuf, entry_size);
  197884. }
  197885. #endif
  197886. png_write_chunk_end(png_ptr);
  197887. png_free(png_ptr, new_name);
  197888. }
  197889. #endif
  197890. #if defined(PNG_WRITE_sBIT_SUPPORTED)
  197891. /* write the sBIT chunk */
  197892. void /* PRIVATE */
  197893. png_write_sBIT(png_structp png_ptr, png_color_8p sbit, int color_type)
  197894. {
  197895. #ifdef PNG_USE_LOCAL_ARRAYS
  197896. PNG_sBIT;
  197897. #endif
  197898. png_byte buf[4];
  197899. png_size_t size;
  197900. png_debug(1, "in png_write_sBIT\n");
  197901. /* make sure we don't depend upon the order of PNG_COLOR_8 */
  197902. if (color_type & PNG_COLOR_MASK_COLOR)
  197903. {
  197904. png_byte maxbits;
  197905. maxbits = (png_byte)(color_type==PNG_COLOR_TYPE_PALETTE ? 8 :
  197906. png_ptr->usr_bit_depth);
  197907. if (sbit->red == 0 || sbit->red > maxbits ||
  197908. sbit->green == 0 || sbit->green > maxbits ||
  197909. sbit->blue == 0 || sbit->blue > maxbits)
  197910. {
  197911. png_warning(png_ptr, "Invalid sBIT depth specified");
  197912. return;
  197913. }
  197914. buf[0] = sbit->red;
  197915. buf[1] = sbit->green;
  197916. buf[2] = sbit->blue;
  197917. size = 3;
  197918. }
  197919. else
  197920. {
  197921. if (sbit->gray == 0 || sbit->gray > png_ptr->usr_bit_depth)
  197922. {
  197923. png_warning(png_ptr, "Invalid sBIT depth specified");
  197924. return;
  197925. }
  197926. buf[0] = sbit->gray;
  197927. size = 1;
  197928. }
  197929. if (color_type & PNG_COLOR_MASK_ALPHA)
  197930. {
  197931. if (sbit->alpha == 0 || sbit->alpha > png_ptr->usr_bit_depth)
  197932. {
  197933. png_warning(png_ptr, "Invalid sBIT depth specified");
  197934. return;
  197935. }
  197936. buf[size++] = sbit->alpha;
  197937. }
  197938. png_write_chunk(png_ptr, png_sBIT, buf, size);
  197939. }
  197940. #endif
  197941. #if defined(PNG_WRITE_cHRM_SUPPORTED)
  197942. /* write the cHRM chunk */
  197943. #ifdef PNG_FLOATING_POINT_SUPPORTED
  197944. void /* PRIVATE */
  197945. png_write_cHRM(png_structp png_ptr, double white_x, double white_y,
  197946. double red_x, double red_y, double green_x, double green_y,
  197947. double blue_x, double blue_y)
  197948. {
  197949. #ifdef PNG_USE_LOCAL_ARRAYS
  197950. PNG_cHRM;
  197951. #endif
  197952. png_byte buf[32];
  197953. png_uint_32 itemp;
  197954. png_debug(1, "in png_write_cHRM\n");
  197955. /* each value is saved in 1/100,000ths */
  197956. if (white_x < 0 || white_x > 0.8 || white_y < 0 || white_y > 0.8 ||
  197957. white_x + white_y > 1.0)
  197958. {
  197959. png_warning(png_ptr, "Invalid cHRM white point specified");
  197960. #if !defined(PNG_NO_CONSOLE_IO)
  197961. fprintf(stderr,"white_x=%f, white_y=%f\n",white_x, white_y);
  197962. #endif
  197963. return;
  197964. }
  197965. itemp = (png_uint_32)(white_x * 100000.0 + 0.5);
  197966. png_save_uint_32(buf, itemp);
  197967. itemp = (png_uint_32)(white_y * 100000.0 + 0.5);
  197968. png_save_uint_32(buf + 4, itemp);
  197969. if (red_x < 0 || red_y < 0 || red_x + red_y > 1.0)
  197970. {
  197971. png_warning(png_ptr, "Invalid cHRM red point specified");
  197972. return;
  197973. }
  197974. itemp = (png_uint_32)(red_x * 100000.0 + 0.5);
  197975. png_save_uint_32(buf + 8, itemp);
  197976. itemp = (png_uint_32)(red_y * 100000.0 + 0.5);
  197977. png_save_uint_32(buf + 12, itemp);
  197978. if (green_x < 0 || green_y < 0 || green_x + green_y > 1.0)
  197979. {
  197980. png_warning(png_ptr, "Invalid cHRM green point specified");
  197981. return;
  197982. }
  197983. itemp = (png_uint_32)(green_x * 100000.0 + 0.5);
  197984. png_save_uint_32(buf + 16, itemp);
  197985. itemp = (png_uint_32)(green_y * 100000.0 + 0.5);
  197986. png_save_uint_32(buf + 20, itemp);
  197987. if (blue_x < 0 || blue_y < 0 || blue_x + blue_y > 1.0)
  197988. {
  197989. png_warning(png_ptr, "Invalid cHRM blue point specified");
  197990. return;
  197991. }
  197992. itemp = (png_uint_32)(blue_x * 100000.0 + 0.5);
  197993. png_save_uint_32(buf + 24, itemp);
  197994. itemp = (png_uint_32)(blue_y * 100000.0 + 0.5);
  197995. png_save_uint_32(buf + 28, itemp);
  197996. png_write_chunk(png_ptr, png_cHRM, buf, (png_size_t)32);
  197997. }
  197998. #endif
  197999. #ifdef PNG_FIXED_POINT_SUPPORTED
  198000. void /* PRIVATE */
  198001. png_write_cHRM_fixed(png_structp png_ptr, png_fixed_point white_x,
  198002. png_fixed_point white_y, png_fixed_point red_x, png_fixed_point red_y,
  198003. png_fixed_point green_x, png_fixed_point green_y, png_fixed_point blue_x,
  198004. png_fixed_point blue_y)
  198005. {
  198006. #ifdef PNG_USE_LOCAL_ARRAYS
  198007. PNG_cHRM;
  198008. #endif
  198009. png_byte buf[32];
  198010. png_debug(1, "in png_write_cHRM\n");
  198011. /* each value is saved in 1/100,000ths */
  198012. if (white_x > 80000L || white_y > 80000L || white_x + white_y > 100000L)
  198013. {
  198014. png_warning(png_ptr, "Invalid fixed cHRM white point specified");
  198015. #if !defined(PNG_NO_CONSOLE_IO)
  198016. fprintf(stderr,"white_x=%ld, white_y=%ld\n",white_x, white_y);
  198017. #endif
  198018. return;
  198019. }
  198020. png_save_uint_32(buf, (png_uint_32)white_x);
  198021. png_save_uint_32(buf + 4, (png_uint_32)white_y);
  198022. if (red_x + red_y > 100000L)
  198023. {
  198024. png_warning(png_ptr, "Invalid cHRM fixed red point specified");
  198025. return;
  198026. }
  198027. png_save_uint_32(buf + 8, (png_uint_32)red_x);
  198028. png_save_uint_32(buf + 12, (png_uint_32)red_y);
  198029. if (green_x + green_y > 100000L)
  198030. {
  198031. png_warning(png_ptr, "Invalid fixed cHRM green point specified");
  198032. return;
  198033. }
  198034. png_save_uint_32(buf + 16, (png_uint_32)green_x);
  198035. png_save_uint_32(buf + 20, (png_uint_32)green_y);
  198036. if (blue_x + blue_y > 100000L)
  198037. {
  198038. png_warning(png_ptr, "Invalid fixed cHRM blue point specified");
  198039. return;
  198040. }
  198041. png_save_uint_32(buf + 24, (png_uint_32)blue_x);
  198042. png_save_uint_32(buf + 28, (png_uint_32)blue_y);
  198043. png_write_chunk(png_ptr, png_cHRM, buf, (png_size_t)32);
  198044. }
  198045. #endif
  198046. #endif
  198047. #if defined(PNG_WRITE_tRNS_SUPPORTED)
  198048. /* write the tRNS chunk */
  198049. void /* PRIVATE */
  198050. png_write_tRNS(png_structp png_ptr, png_bytep trans, png_color_16p tran,
  198051. int num_trans, int color_type)
  198052. {
  198053. #ifdef PNG_USE_LOCAL_ARRAYS
  198054. PNG_tRNS;
  198055. #endif
  198056. png_byte buf[6];
  198057. png_debug(1, "in png_write_tRNS\n");
  198058. if (color_type == PNG_COLOR_TYPE_PALETTE)
  198059. {
  198060. if (num_trans <= 0 || num_trans > (int)png_ptr->num_palette)
  198061. {
  198062. png_warning(png_ptr,"Invalid number of transparent colors specified");
  198063. return;
  198064. }
  198065. /* write the chunk out as it is */
  198066. png_write_chunk(png_ptr, png_tRNS, trans, (png_size_t)num_trans);
  198067. }
  198068. else if (color_type == PNG_COLOR_TYPE_GRAY)
  198069. {
  198070. /* one 16 bit value */
  198071. if(tran->gray >= (1 << png_ptr->bit_depth))
  198072. {
  198073. png_warning(png_ptr,
  198074. "Ignoring attempt to write tRNS chunk out-of-range for bit_depth");
  198075. return;
  198076. }
  198077. png_save_uint_16(buf, tran->gray);
  198078. png_write_chunk(png_ptr, png_tRNS, buf, (png_size_t)2);
  198079. }
  198080. else if (color_type == PNG_COLOR_TYPE_RGB)
  198081. {
  198082. /* three 16 bit values */
  198083. png_save_uint_16(buf, tran->red);
  198084. png_save_uint_16(buf + 2, tran->green);
  198085. png_save_uint_16(buf + 4, tran->blue);
  198086. if(png_ptr->bit_depth == 8 && (buf[0] | buf[2] | buf[4]))
  198087. {
  198088. png_warning(png_ptr,
  198089. "Ignoring attempt to write 16-bit tRNS chunk when bit_depth is 8");
  198090. return;
  198091. }
  198092. png_write_chunk(png_ptr, png_tRNS, buf, (png_size_t)6);
  198093. }
  198094. else
  198095. {
  198096. png_warning(png_ptr, "Can't write tRNS with an alpha channel");
  198097. }
  198098. }
  198099. #endif
  198100. #if defined(PNG_WRITE_bKGD_SUPPORTED)
  198101. /* write the background chunk */
  198102. void /* PRIVATE */
  198103. png_write_bKGD(png_structp png_ptr, png_color_16p back, int color_type)
  198104. {
  198105. #ifdef PNG_USE_LOCAL_ARRAYS
  198106. PNG_bKGD;
  198107. #endif
  198108. png_byte buf[6];
  198109. png_debug(1, "in png_write_bKGD\n");
  198110. if (color_type == PNG_COLOR_TYPE_PALETTE)
  198111. {
  198112. if (
  198113. #if defined(PNG_MNG_FEATURES_SUPPORTED)
  198114. (png_ptr->num_palette ||
  198115. (!(png_ptr->mng_features_permitted & PNG_FLAG_MNG_EMPTY_PLTE))) &&
  198116. #endif
  198117. back->index > png_ptr->num_palette)
  198118. {
  198119. png_warning(png_ptr, "Invalid background palette index");
  198120. return;
  198121. }
  198122. buf[0] = back->index;
  198123. png_write_chunk(png_ptr, png_bKGD, buf, (png_size_t)1);
  198124. }
  198125. else if (color_type & PNG_COLOR_MASK_COLOR)
  198126. {
  198127. png_save_uint_16(buf, back->red);
  198128. png_save_uint_16(buf + 2, back->green);
  198129. png_save_uint_16(buf + 4, back->blue);
  198130. if(png_ptr->bit_depth == 8 && (buf[0] | buf[2] | buf[4]))
  198131. {
  198132. png_warning(png_ptr,
  198133. "Ignoring attempt to write 16-bit bKGD chunk when bit_depth is 8");
  198134. return;
  198135. }
  198136. png_write_chunk(png_ptr, png_bKGD, buf, (png_size_t)6);
  198137. }
  198138. else
  198139. {
  198140. if(back->gray >= (1 << png_ptr->bit_depth))
  198141. {
  198142. png_warning(png_ptr,
  198143. "Ignoring attempt to write bKGD chunk out-of-range for bit_depth");
  198144. return;
  198145. }
  198146. png_save_uint_16(buf, back->gray);
  198147. png_write_chunk(png_ptr, png_bKGD, buf, (png_size_t)2);
  198148. }
  198149. }
  198150. #endif
  198151. #if defined(PNG_WRITE_hIST_SUPPORTED)
  198152. /* write the histogram */
  198153. void /* PRIVATE */
  198154. png_write_hIST(png_structp png_ptr, png_uint_16p hist, int num_hist)
  198155. {
  198156. #ifdef PNG_USE_LOCAL_ARRAYS
  198157. PNG_hIST;
  198158. #endif
  198159. int i;
  198160. png_byte buf[3];
  198161. png_debug(1, "in png_write_hIST\n");
  198162. if (num_hist > (int)png_ptr->num_palette)
  198163. {
  198164. png_debug2(3, "num_hist = %d, num_palette = %d\n", num_hist,
  198165. png_ptr->num_palette);
  198166. png_warning(png_ptr, "Invalid number of histogram entries specified");
  198167. return;
  198168. }
  198169. png_write_chunk_start(png_ptr, png_hIST, (png_uint_32)(num_hist * 2));
  198170. for (i = 0; i < num_hist; i++)
  198171. {
  198172. png_save_uint_16(buf, hist[i]);
  198173. png_write_chunk_data(png_ptr, buf, (png_size_t)2);
  198174. }
  198175. png_write_chunk_end(png_ptr);
  198176. }
  198177. #endif
  198178. #if defined(PNG_WRITE_TEXT_SUPPORTED) || defined(PNG_WRITE_pCAL_SUPPORTED) || \
  198179. defined(PNG_WRITE_iCCP_SUPPORTED) || defined(PNG_WRITE_sPLT_SUPPORTED)
  198180. /* Check that the tEXt or zTXt keyword is valid per PNG 1.0 specification,
  198181. * and if invalid, correct the keyword rather than discarding the entire
  198182. * chunk. The PNG 1.0 specification requires keywords 1-79 characters in
  198183. * length, forbids leading or trailing whitespace, multiple internal spaces,
  198184. * and the non-break space (0x80) from ISO 8859-1. Returns keyword length.
  198185. *
  198186. * The new_key is allocated to hold the corrected keyword and must be freed
  198187. * by the calling routine. This avoids problems with trying to write to
  198188. * static keywords without having to have duplicate copies of the strings.
  198189. */
  198190. png_size_t /* PRIVATE */
  198191. png_check_keyword(png_structp png_ptr, png_charp key, png_charpp new_key)
  198192. {
  198193. png_size_t key_len;
  198194. png_charp kp, dp;
  198195. int kflag;
  198196. int kwarn=0;
  198197. png_debug(1, "in png_check_keyword\n");
  198198. *new_key = NULL;
  198199. if (key == NULL || (key_len = png_strlen(key)) == 0)
  198200. {
  198201. png_warning(png_ptr, "zero length keyword");
  198202. return ((png_size_t)0);
  198203. }
  198204. png_debug1(2, "Keyword to be checked is '%s'\n", key);
  198205. *new_key = (png_charp)png_malloc_warn(png_ptr, (png_uint_32)(key_len + 2));
  198206. if (*new_key == NULL)
  198207. {
  198208. png_warning(png_ptr, "Out of memory while procesing keyword");
  198209. return ((png_size_t)0);
  198210. }
  198211. /* Replace non-printing characters with a blank and print a warning */
  198212. for (kp = key, dp = *new_key; *kp != '\0'; kp++, dp++)
  198213. {
  198214. if ((png_byte)*kp < 0x20 ||
  198215. ((png_byte)*kp > 0x7E && (png_byte)*kp < 0xA1))
  198216. {
  198217. #if !defined(PNG_NO_STDIO) && !defined(_WIN32_WCE)
  198218. char msg[40];
  198219. png_snprintf(msg, 40,
  198220. "invalid keyword character 0x%02X", (png_byte)*kp);
  198221. png_warning(png_ptr, msg);
  198222. #else
  198223. png_warning(png_ptr, "invalid character in keyword");
  198224. #endif
  198225. *dp = ' ';
  198226. }
  198227. else
  198228. {
  198229. *dp = *kp;
  198230. }
  198231. }
  198232. *dp = '\0';
  198233. /* Remove any trailing white space. */
  198234. kp = *new_key + key_len - 1;
  198235. if (*kp == ' ')
  198236. {
  198237. png_warning(png_ptr, "trailing spaces removed from keyword");
  198238. while (*kp == ' ')
  198239. {
  198240. *(kp--) = '\0';
  198241. key_len--;
  198242. }
  198243. }
  198244. /* Remove any leading white space. */
  198245. kp = *new_key;
  198246. if (*kp == ' ')
  198247. {
  198248. png_warning(png_ptr, "leading spaces removed from keyword");
  198249. while (*kp == ' ')
  198250. {
  198251. kp++;
  198252. key_len--;
  198253. }
  198254. }
  198255. png_debug1(2, "Checking for multiple internal spaces in '%s'\n", kp);
  198256. /* Remove multiple internal spaces. */
  198257. for (kflag = 0, dp = *new_key; *kp != '\0'; kp++)
  198258. {
  198259. if (*kp == ' ' && kflag == 0)
  198260. {
  198261. *(dp++) = *kp;
  198262. kflag = 1;
  198263. }
  198264. else if (*kp == ' ')
  198265. {
  198266. key_len--;
  198267. kwarn=1;
  198268. }
  198269. else
  198270. {
  198271. *(dp++) = *kp;
  198272. kflag = 0;
  198273. }
  198274. }
  198275. *dp = '\0';
  198276. if(kwarn)
  198277. png_warning(png_ptr, "extra interior spaces removed from keyword");
  198278. if (key_len == 0)
  198279. {
  198280. png_free(png_ptr, *new_key);
  198281. *new_key=NULL;
  198282. png_warning(png_ptr, "Zero length keyword");
  198283. }
  198284. if (key_len > 79)
  198285. {
  198286. png_warning(png_ptr, "keyword length must be 1 - 79 characters");
  198287. new_key[79] = '\0';
  198288. key_len = 79;
  198289. }
  198290. return (key_len);
  198291. }
  198292. #endif
  198293. #if defined(PNG_WRITE_tEXt_SUPPORTED)
  198294. /* write a tEXt chunk */
  198295. void /* PRIVATE */
  198296. png_write_tEXt(png_structp png_ptr, png_charp key, png_charp text,
  198297. png_size_t text_len)
  198298. {
  198299. #ifdef PNG_USE_LOCAL_ARRAYS
  198300. PNG_tEXt;
  198301. #endif
  198302. png_size_t key_len;
  198303. png_charp new_key;
  198304. png_debug(1, "in png_write_tEXt\n");
  198305. if (key == NULL || (key_len = png_check_keyword(png_ptr, key, &new_key))==0)
  198306. {
  198307. png_warning(png_ptr, "Empty keyword in tEXt chunk");
  198308. return;
  198309. }
  198310. if (text == NULL || *text == '\0')
  198311. text_len = 0;
  198312. else
  198313. text_len = png_strlen(text);
  198314. /* make sure we include the 0 after the key */
  198315. png_write_chunk_start(png_ptr, png_tEXt, (png_uint_32)key_len+text_len+1);
  198316. /*
  198317. * We leave it to the application to meet PNG-1.0 requirements on the
  198318. * contents of the text. PNG-1.0 through PNG-1.2 discourage the use of
  198319. * any non-Latin-1 characters except for NEWLINE. ISO PNG will forbid them.
  198320. * The NUL character is forbidden by PNG-1.0 through PNG-1.2 and ISO PNG.
  198321. */
  198322. png_write_chunk_data(png_ptr, (png_bytep)new_key, key_len + 1);
  198323. if (text_len)
  198324. png_write_chunk_data(png_ptr, (png_bytep)text, text_len);
  198325. png_write_chunk_end(png_ptr);
  198326. png_free(png_ptr, new_key);
  198327. }
  198328. #endif
  198329. #if defined(PNG_WRITE_zTXt_SUPPORTED)
  198330. /* write a compressed text chunk */
  198331. void /* PRIVATE */
  198332. png_write_zTXt(png_structp png_ptr, png_charp key, png_charp text,
  198333. png_size_t text_len, int compression)
  198334. {
  198335. #ifdef PNG_USE_LOCAL_ARRAYS
  198336. PNG_zTXt;
  198337. #endif
  198338. png_size_t key_len;
  198339. char buf[1];
  198340. png_charp new_key;
  198341. compression_state comp;
  198342. png_debug(1, "in png_write_zTXt\n");
  198343. comp.num_output_ptr = 0;
  198344. comp.max_output_ptr = 0;
  198345. comp.output_ptr = NULL;
  198346. comp.input = NULL;
  198347. comp.input_len = 0;
  198348. if (key == NULL || (key_len = png_check_keyword(png_ptr, key, &new_key))==0)
  198349. {
  198350. png_warning(png_ptr, "Empty keyword in zTXt chunk");
  198351. return;
  198352. }
  198353. if (text == NULL || *text == '\0' || compression==PNG_TEXT_COMPRESSION_NONE)
  198354. {
  198355. png_write_tEXt(png_ptr, new_key, text, (png_size_t)0);
  198356. png_free(png_ptr, new_key);
  198357. return;
  198358. }
  198359. text_len = png_strlen(text);
  198360. /* compute the compressed data; do it now for the length */
  198361. text_len = png_text_compress(png_ptr, text, text_len, compression,
  198362. &comp);
  198363. /* write start of chunk */
  198364. png_write_chunk_start(png_ptr, png_zTXt, (png_uint_32)
  198365. (key_len+text_len+2));
  198366. /* write key */
  198367. png_write_chunk_data(png_ptr, (png_bytep)new_key, key_len + 1);
  198368. png_free(png_ptr, new_key);
  198369. buf[0] = (png_byte)compression;
  198370. /* write compression */
  198371. png_write_chunk_data(png_ptr, (png_bytep)buf, (png_size_t)1);
  198372. /* write the compressed data */
  198373. png_write_compressed_data_out(png_ptr, &comp);
  198374. /* close the chunk */
  198375. png_write_chunk_end(png_ptr);
  198376. }
  198377. #endif
  198378. #if defined(PNG_WRITE_iTXt_SUPPORTED)
  198379. /* write an iTXt chunk */
  198380. void /* PRIVATE */
  198381. png_write_iTXt(png_structp png_ptr, int compression, png_charp key,
  198382. png_charp lang, png_charp lang_key, png_charp text)
  198383. {
  198384. #ifdef PNG_USE_LOCAL_ARRAYS
  198385. PNG_iTXt;
  198386. #endif
  198387. png_size_t lang_len, key_len, lang_key_len, text_len;
  198388. png_charp new_lang, new_key;
  198389. png_byte cbuf[2];
  198390. compression_state comp;
  198391. png_debug(1, "in png_write_iTXt\n");
  198392. comp.num_output_ptr = 0;
  198393. comp.max_output_ptr = 0;
  198394. comp.output_ptr = NULL;
  198395. comp.input = NULL;
  198396. if (key == NULL || (key_len = png_check_keyword(png_ptr, key, &new_key))==0)
  198397. {
  198398. png_warning(png_ptr, "Empty keyword in iTXt chunk");
  198399. return;
  198400. }
  198401. if (lang == NULL || (lang_len = png_check_keyword(png_ptr, lang, &new_lang))==0)
  198402. {
  198403. png_warning(png_ptr, "Empty language field in iTXt chunk");
  198404. new_lang = NULL;
  198405. lang_len = 0;
  198406. }
  198407. if (lang_key == NULL)
  198408. lang_key_len = 0;
  198409. else
  198410. lang_key_len = png_strlen(lang_key);
  198411. if (text == NULL)
  198412. text_len = 0;
  198413. else
  198414. text_len = png_strlen(text);
  198415. /* compute the compressed data; do it now for the length */
  198416. text_len = png_text_compress(png_ptr, text, text_len, compression-2,
  198417. &comp);
  198418. /* make sure we include the compression flag, the compression byte,
  198419. * and the NULs after the key, lang, and lang_key parts */
  198420. png_write_chunk_start(png_ptr, png_iTXt,
  198421. (png_uint_32)(
  198422. 5 /* comp byte, comp flag, terminators for key, lang and lang_key */
  198423. + key_len
  198424. + lang_len
  198425. + lang_key_len
  198426. + text_len));
  198427. /*
  198428. * We leave it to the application to meet PNG-1.0 requirements on the
  198429. * contents of the text. PNG-1.0 through PNG-1.2 discourage the use of
  198430. * any non-Latin-1 characters except for NEWLINE. ISO PNG will forbid them.
  198431. * The NUL character is forbidden by PNG-1.0 through PNG-1.2 and ISO PNG.
  198432. */
  198433. png_write_chunk_data(png_ptr, (png_bytep)new_key, key_len + 1);
  198434. /* set the compression flag */
  198435. if (compression == PNG_ITXT_COMPRESSION_NONE || \
  198436. compression == PNG_TEXT_COMPRESSION_NONE)
  198437. cbuf[0] = 0;
  198438. else /* compression == PNG_ITXT_COMPRESSION_zTXt */
  198439. cbuf[0] = 1;
  198440. /* set the compression method */
  198441. cbuf[1] = 0;
  198442. png_write_chunk_data(png_ptr, cbuf, 2);
  198443. cbuf[0] = 0;
  198444. png_write_chunk_data(png_ptr, (new_lang ? (png_bytep)new_lang : cbuf), lang_len + 1);
  198445. png_write_chunk_data(png_ptr, (lang_key ? (png_bytep)lang_key : cbuf), lang_key_len + 1);
  198446. png_write_compressed_data_out(png_ptr, &comp);
  198447. png_write_chunk_end(png_ptr);
  198448. png_free(png_ptr, new_key);
  198449. if (new_lang)
  198450. png_free(png_ptr, new_lang);
  198451. }
  198452. #endif
  198453. #if defined(PNG_WRITE_oFFs_SUPPORTED)
  198454. /* write the oFFs chunk */
  198455. void /* PRIVATE */
  198456. png_write_oFFs(png_structp png_ptr, png_int_32 x_offset, png_int_32 y_offset,
  198457. int unit_type)
  198458. {
  198459. #ifdef PNG_USE_LOCAL_ARRAYS
  198460. PNG_oFFs;
  198461. #endif
  198462. png_byte buf[9];
  198463. png_debug(1, "in png_write_oFFs\n");
  198464. if (unit_type >= PNG_OFFSET_LAST)
  198465. png_warning(png_ptr, "Unrecognized unit type for oFFs chunk");
  198466. png_save_int_32(buf, x_offset);
  198467. png_save_int_32(buf + 4, y_offset);
  198468. buf[8] = (png_byte)unit_type;
  198469. png_write_chunk(png_ptr, png_oFFs, buf, (png_size_t)9);
  198470. }
  198471. #endif
  198472. #if defined(PNG_WRITE_pCAL_SUPPORTED)
  198473. /* write the pCAL chunk (described in the PNG extensions document) */
  198474. void /* PRIVATE */
  198475. png_write_pCAL(png_structp png_ptr, png_charp purpose, png_int_32 X0,
  198476. png_int_32 X1, int type, int nparams, png_charp units, png_charpp params)
  198477. {
  198478. #ifdef PNG_USE_LOCAL_ARRAYS
  198479. PNG_pCAL;
  198480. #endif
  198481. png_size_t purpose_len, units_len, total_len;
  198482. png_uint_32p params_len;
  198483. png_byte buf[10];
  198484. png_charp new_purpose;
  198485. int i;
  198486. png_debug1(1, "in png_write_pCAL (%d parameters)\n", nparams);
  198487. if (type >= PNG_EQUATION_LAST)
  198488. png_warning(png_ptr, "Unrecognized equation type for pCAL chunk");
  198489. purpose_len = png_check_keyword(png_ptr, purpose, &new_purpose) + 1;
  198490. png_debug1(3, "pCAL purpose length = %d\n", (int)purpose_len);
  198491. units_len = png_strlen(units) + (nparams == 0 ? 0 : 1);
  198492. png_debug1(3, "pCAL units length = %d\n", (int)units_len);
  198493. total_len = purpose_len + units_len + 10;
  198494. params_len = (png_uint_32p)png_malloc(png_ptr, (png_uint_32)(nparams
  198495. *png_sizeof(png_uint_32)));
  198496. /* Find the length of each parameter, making sure we don't count the
  198497. null terminator for the last parameter. */
  198498. for (i = 0; i < nparams; i++)
  198499. {
  198500. params_len[i] = png_strlen(params[i]) + (i == nparams - 1 ? 0 : 1);
  198501. png_debug2(3, "pCAL parameter %d length = %lu\n", i, params_len[i]);
  198502. total_len += (png_size_t)params_len[i];
  198503. }
  198504. png_debug1(3, "pCAL total length = %d\n", (int)total_len);
  198505. png_write_chunk_start(png_ptr, png_pCAL, (png_uint_32)total_len);
  198506. png_write_chunk_data(png_ptr, (png_bytep)new_purpose, purpose_len);
  198507. png_save_int_32(buf, X0);
  198508. png_save_int_32(buf + 4, X1);
  198509. buf[8] = (png_byte)type;
  198510. buf[9] = (png_byte)nparams;
  198511. png_write_chunk_data(png_ptr, buf, (png_size_t)10);
  198512. png_write_chunk_data(png_ptr, (png_bytep)units, (png_size_t)units_len);
  198513. png_free(png_ptr, new_purpose);
  198514. for (i = 0; i < nparams; i++)
  198515. {
  198516. png_write_chunk_data(png_ptr, (png_bytep)params[i],
  198517. (png_size_t)params_len[i]);
  198518. }
  198519. png_free(png_ptr, params_len);
  198520. png_write_chunk_end(png_ptr);
  198521. }
  198522. #endif
  198523. #if defined(PNG_WRITE_sCAL_SUPPORTED)
  198524. /* write the sCAL chunk */
  198525. #if defined(PNG_FLOATING_POINT_SUPPORTED) && !defined(PNG_NO_STDIO)
  198526. void /* PRIVATE */
  198527. png_write_sCAL(png_structp png_ptr, int unit, double width, double height)
  198528. {
  198529. #ifdef PNG_USE_LOCAL_ARRAYS
  198530. PNG_sCAL;
  198531. #endif
  198532. char buf[64];
  198533. png_size_t total_len;
  198534. png_debug(1, "in png_write_sCAL\n");
  198535. buf[0] = (char)unit;
  198536. #if defined(_WIN32_WCE)
  198537. /* sprintf() function is not supported on WindowsCE */
  198538. {
  198539. wchar_t wc_buf[32];
  198540. size_t wc_len;
  198541. swprintf(wc_buf, TEXT("%12.12e"), width);
  198542. wc_len = wcslen(wc_buf);
  198543. WideCharToMultiByte(CP_ACP, 0, wc_buf, -1, buf + 1, wc_len, NULL, NULL);
  198544. total_len = wc_len + 2;
  198545. swprintf(wc_buf, TEXT("%12.12e"), height);
  198546. wc_len = wcslen(wc_buf);
  198547. WideCharToMultiByte(CP_ACP, 0, wc_buf, -1, buf + total_len, wc_len,
  198548. NULL, NULL);
  198549. total_len += wc_len;
  198550. }
  198551. #else
  198552. png_snprintf(buf + 1, 63, "%12.12e", width);
  198553. total_len = 1 + png_strlen(buf + 1) + 1;
  198554. png_snprintf(buf + total_len, 64-total_len, "%12.12e", height);
  198555. total_len += png_strlen(buf + total_len);
  198556. #endif
  198557. png_debug1(3, "sCAL total length = %u\n", (unsigned int)total_len);
  198558. png_write_chunk(png_ptr, png_sCAL, (png_bytep)buf, total_len);
  198559. }
  198560. #else
  198561. #ifdef PNG_FIXED_POINT_SUPPORTED
  198562. void /* PRIVATE */
  198563. png_write_sCAL_s(png_structp png_ptr, int unit, png_charp width,
  198564. png_charp height)
  198565. {
  198566. #ifdef PNG_USE_LOCAL_ARRAYS
  198567. PNG_sCAL;
  198568. #endif
  198569. png_byte buf[64];
  198570. png_size_t wlen, hlen, total_len;
  198571. png_debug(1, "in png_write_sCAL_s\n");
  198572. wlen = png_strlen(width);
  198573. hlen = png_strlen(height);
  198574. total_len = wlen + hlen + 2;
  198575. if (total_len > 64)
  198576. {
  198577. png_warning(png_ptr, "Can't write sCAL (buffer too small)");
  198578. return;
  198579. }
  198580. buf[0] = (png_byte)unit;
  198581. png_memcpy(buf + 1, width, wlen + 1); /* append the '\0' here */
  198582. png_memcpy(buf + wlen + 2, height, hlen); /* do NOT append the '\0' here */
  198583. png_debug1(3, "sCAL total length = %u\n", (unsigned int)total_len);
  198584. png_write_chunk(png_ptr, png_sCAL, buf, total_len);
  198585. }
  198586. #endif
  198587. #endif
  198588. #endif
  198589. #if defined(PNG_WRITE_pHYs_SUPPORTED)
  198590. /* write the pHYs chunk */
  198591. void /* PRIVATE */
  198592. png_write_pHYs(png_structp png_ptr, png_uint_32 x_pixels_per_unit,
  198593. png_uint_32 y_pixels_per_unit,
  198594. int unit_type)
  198595. {
  198596. #ifdef PNG_USE_LOCAL_ARRAYS
  198597. PNG_pHYs;
  198598. #endif
  198599. png_byte buf[9];
  198600. png_debug(1, "in png_write_pHYs\n");
  198601. if (unit_type >= PNG_RESOLUTION_LAST)
  198602. png_warning(png_ptr, "Unrecognized unit type for pHYs chunk");
  198603. png_save_uint_32(buf, x_pixels_per_unit);
  198604. png_save_uint_32(buf + 4, y_pixels_per_unit);
  198605. buf[8] = (png_byte)unit_type;
  198606. png_write_chunk(png_ptr, png_pHYs, buf, (png_size_t)9);
  198607. }
  198608. #endif
  198609. #if defined(PNG_WRITE_tIME_SUPPORTED)
  198610. /* Write the tIME chunk. Use either png_convert_from_struct_tm()
  198611. * or png_convert_from_time_t(), or fill in the structure yourself.
  198612. */
  198613. void /* PRIVATE */
  198614. png_write_tIME(png_structp png_ptr, png_timep mod_time)
  198615. {
  198616. #ifdef PNG_USE_LOCAL_ARRAYS
  198617. PNG_tIME;
  198618. #endif
  198619. png_byte buf[7];
  198620. png_debug(1, "in png_write_tIME\n");
  198621. if (mod_time->month > 12 || mod_time->month < 1 ||
  198622. mod_time->day > 31 || mod_time->day < 1 ||
  198623. mod_time->hour > 23 || mod_time->second > 60)
  198624. {
  198625. png_warning(png_ptr, "Invalid time specified for tIME chunk");
  198626. return;
  198627. }
  198628. png_save_uint_16(buf, mod_time->year);
  198629. buf[2] = mod_time->month;
  198630. buf[3] = mod_time->day;
  198631. buf[4] = mod_time->hour;
  198632. buf[5] = mod_time->minute;
  198633. buf[6] = mod_time->second;
  198634. png_write_chunk(png_ptr, png_tIME, buf, (png_size_t)7);
  198635. }
  198636. #endif
  198637. /* initializes the row writing capability of libpng */
  198638. void /* PRIVATE */
  198639. png_write_start_row(png_structp png_ptr)
  198640. {
  198641. #ifdef PNG_WRITE_INTERLACING_SUPPORTED
  198642. #ifdef PNG_USE_LOCAL_ARRAYS
  198643. /* arrays to facilitate easy interlacing - use pass (0 - 6) as index */
  198644. /* start of interlace block */
  198645. int png_pass_start[7] = {0, 4, 0, 2, 0, 1, 0};
  198646. /* offset to next interlace block */
  198647. int png_pass_inc[7] = {8, 8, 4, 4, 2, 2, 1};
  198648. /* start of interlace block in the y direction */
  198649. int png_pass_ystart[7] = {0, 0, 4, 0, 2, 0, 1};
  198650. /* offset to next interlace block in the y direction */
  198651. int png_pass_yinc[7] = {8, 8, 8, 4, 4, 2, 2};
  198652. #endif
  198653. #endif
  198654. png_size_t buf_size;
  198655. png_debug(1, "in png_write_start_row\n");
  198656. buf_size = (png_size_t)(PNG_ROWBYTES(
  198657. png_ptr->usr_channels*png_ptr->usr_bit_depth,png_ptr->width)+1);
  198658. /* set up row buffer */
  198659. png_ptr->row_buf = (png_bytep)png_malloc(png_ptr, (png_uint_32)buf_size);
  198660. png_ptr->row_buf[0] = PNG_FILTER_VALUE_NONE;
  198661. #ifndef PNG_NO_WRITE_FILTERING
  198662. /* set up filtering buffer, if using this filter */
  198663. if (png_ptr->do_filter & PNG_FILTER_SUB)
  198664. {
  198665. png_ptr->sub_row = (png_bytep)png_malloc(png_ptr,
  198666. (png_ptr->rowbytes + 1));
  198667. png_ptr->sub_row[0] = PNG_FILTER_VALUE_SUB;
  198668. }
  198669. /* We only need to keep the previous row if we are using one of these. */
  198670. if (png_ptr->do_filter & (PNG_FILTER_AVG | PNG_FILTER_UP | PNG_FILTER_PAETH))
  198671. {
  198672. /* set up previous row buffer */
  198673. png_ptr->prev_row = (png_bytep)png_malloc(png_ptr, (png_uint_32)buf_size);
  198674. png_memset(png_ptr->prev_row, 0, buf_size);
  198675. if (png_ptr->do_filter & PNG_FILTER_UP)
  198676. {
  198677. png_ptr->up_row = (png_bytep)png_malloc(png_ptr,
  198678. (png_ptr->rowbytes + 1));
  198679. png_ptr->up_row[0] = PNG_FILTER_VALUE_UP;
  198680. }
  198681. if (png_ptr->do_filter & PNG_FILTER_AVG)
  198682. {
  198683. png_ptr->avg_row = (png_bytep)png_malloc(png_ptr,
  198684. (png_ptr->rowbytes + 1));
  198685. png_ptr->avg_row[0] = PNG_FILTER_VALUE_AVG;
  198686. }
  198687. if (png_ptr->do_filter & PNG_FILTER_PAETH)
  198688. {
  198689. png_ptr->paeth_row = (png_bytep)png_malloc(png_ptr,
  198690. (png_ptr->rowbytes + 1));
  198691. png_ptr->paeth_row[0] = PNG_FILTER_VALUE_PAETH;
  198692. }
  198693. #endif /* PNG_NO_WRITE_FILTERING */
  198694. }
  198695. #ifdef PNG_WRITE_INTERLACING_SUPPORTED
  198696. /* if interlaced, we need to set up width and height of pass */
  198697. if (png_ptr->interlaced)
  198698. {
  198699. if (!(png_ptr->transformations & PNG_INTERLACE))
  198700. {
  198701. png_ptr->num_rows = (png_ptr->height + png_pass_yinc[0] - 1 -
  198702. png_pass_ystart[0]) / png_pass_yinc[0];
  198703. png_ptr->usr_width = (png_ptr->width + png_pass_inc[0] - 1 -
  198704. png_pass_start[0]) / png_pass_inc[0];
  198705. }
  198706. else
  198707. {
  198708. png_ptr->num_rows = png_ptr->height;
  198709. png_ptr->usr_width = png_ptr->width;
  198710. }
  198711. }
  198712. else
  198713. #endif
  198714. {
  198715. png_ptr->num_rows = png_ptr->height;
  198716. png_ptr->usr_width = png_ptr->width;
  198717. }
  198718. png_ptr->zstream.avail_out = (uInt)png_ptr->zbuf_size;
  198719. png_ptr->zstream.next_out = png_ptr->zbuf;
  198720. }
  198721. /* Internal use only. Called when finished processing a row of data. */
  198722. void /* PRIVATE */
  198723. png_write_finish_row(png_structp png_ptr)
  198724. {
  198725. #ifdef PNG_WRITE_INTERLACING_SUPPORTED
  198726. #ifdef PNG_USE_LOCAL_ARRAYS
  198727. /* arrays to facilitate easy interlacing - use pass (0 - 6) as index */
  198728. /* start of interlace block */
  198729. int png_pass_start[7] = {0, 4, 0, 2, 0, 1, 0};
  198730. /* offset to next interlace block */
  198731. int png_pass_inc[7] = {8, 8, 4, 4, 2, 2, 1};
  198732. /* start of interlace block in the y direction */
  198733. int png_pass_ystart[7] = {0, 0, 4, 0, 2, 0, 1};
  198734. /* offset to next interlace block in the y direction */
  198735. int png_pass_yinc[7] = {8, 8, 8, 4, 4, 2, 2};
  198736. #endif
  198737. #endif
  198738. int ret;
  198739. png_debug(1, "in png_write_finish_row\n");
  198740. /* next row */
  198741. png_ptr->row_number++;
  198742. /* see if we are done */
  198743. if (png_ptr->row_number < png_ptr->num_rows)
  198744. return;
  198745. #ifdef PNG_WRITE_INTERLACING_SUPPORTED
  198746. /* if interlaced, go to next pass */
  198747. if (png_ptr->interlaced)
  198748. {
  198749. png_ptr->row_number = 0;
  198750. if (png_ptr->transformations & PNG_INTERLACE)
  198751. {
  198752. png_ptr->pass++;
  198753. }
  198754. else
  198755. {
  198756. /* loop until we find a non-zero width or height pass */
  198757. do
  198758. {
  198759. png_ptr->pass++;
  198760. if (png_ptr->pass >= 7)
  198761. break;
  198762. png_ptr->usr_width = (png_ptr->width +
  198763. png_pass_inc[png_ptr->pass] - 1 -
  198764. png_pass_start[png_ptr->pass]) /
  198765. png_pass_inc[png_ptr->pass];
  198766. png_ptr->num_rows = (png_ptr->height +
  198767. png_pass_yinc[png_ptr->pass] - 1 -
  198768. png_pass_ystart[png_ptr->pass]) /
  198769. png_pass_yinc[png_ptr->pass];
  198770. if (png_ptr->transformations & PNG_INTERLACE)
  198771. break;
  198772. } while (png_ptr->usr_width == 0 || png_ptr->num_rows == 0);
  198773. }
  198774. /* reset the row above the image for the next pass */
  198775. if (png_ptr->pass < 7)
  198776. {
  198777. if (png_ptr->prev_row != NULL)
  198778. png_memset(png_ptr->prev_row, 0,
  198779. (png_size_t)(PNG_ROWBYTES(png_ptr->usr_channels*
  198780. png_ptr->usr_bit_depth,png_ptr->width))+1);
  198781. return;
  198782. }
  198783. }
  198784. #endif
  198785. /* if we get here, we've just written the last row, so we need
  198786. to flush the compressor */
  198787. do
  198788. {
  198789. /* tell the compressor we are done */
  198790. ret = deflate(&png_ptr->zstream, Z_FINISH);
  198791. /* check for an error */
  198792. if (ret == Z_OK)
  198793. {
  198794. /* check to see if we need more room */
  198795. if (!(png_ptr->zstream.avail_out))
  198796. {
  198797. png_write_IDAT(png_ptr, png_ptr->zbuf, png_ptr->zbuf_size);
  198798. png_ptr->zstream.next_out = png_ptr->zbuf;
  198799. png_ptr->zstream.avail_out = (uInt)png_ptr->zbuf_size;
  198800. }
  198801. }
  198802. else if (ret != Z_STREAM_END)
  198803. {
  198804. if (png_ptr->zstream.msg != NULL)
  198805. png_error(png_ptr, png_ptr->zstream.msg);
  198806. else
  198807. png_error(png_ptr, "zlib error");
  198808. }
  198809. } while (ret != Z_STREAM_END);
  198810. /* write any extra space */
  198811. if (png_ptr->zstream.avail_out < png_ptr->zbuf_size)
  198812. {
  198813. png_write_IDAT(png_ptr, png_ptr->zbuf, png_ptr->zbuf_size -
  198814. png_ptr->zstream.avail_out);
  198815. }
  198816. deflateReset(&png_ptr->zstream);
  198817. png_ptr->zstream.data_type = Z_BINARY;
  198818. }
  198819. #if defined(PNG_WRITE_INTERLACING_SUPPORTED)
  198820. /* Pick out the correct pixels for the interlace pass.
  198821. * The basic idea here is to go through the row with a source
  198822. * pointer and a destination pointer (sp and dp), and copy the
  198823. * correct pixels for the pass. As the row gets compacted,
  198824. * sp will always be >= dp, so we should never overwrite anything.
  198825. * See the default: case for the easiest code to understand.
  198826. */
  198827. void /* PRIVATE */
  198828. png_do_write_interlace(png_row_infop row_info, png_bytep row, int pass)
  198829. {
  198830. #ifdef PNG_USE_LOCAL_ARRAYS
  198831. /* arrays to facilitate easy interlacing - use pass (0 - 6) as index */
  198832. /* start of interlace block */
  198833. int png_pass_start[7] = {0, 4, 0, 2, 0, 1, 0};
  198834. /* offset to next interlace block */
  198835. int png_pass_inc[7] = {8, 8, 4, 4, 2, 2, 1};
  198836. #endif
  198837. png_debug(1, "in png_do_write_interlace\n");
  198838. /* we don't have to do anything on the last pass (6) */
  198839. #if defined(PNG_USELESS_TESTS_SUPPORTED)
  198840. if (row != NULL && row_info != NULL && pass < 6)
  198841. #else
  198842. if (pass < 6)
  198843. #endif
  198844. {
  198845. /* each pixel depth is handled separately */
  198846. switch (row_info->pixel_depth)
  198847. {
  198848. case 1:
  198849. {
  198850. png_bytep sp;
  198851. png_bytep dp;
  198852. int shift;
  198853. int d;
  198854. int value;
  198855. png_uint_32 i;
  198856. png_uint_32 row_width = row_info->width;
  198857. dp = row;
  198858. d = 0;
  198859. shift = 7;
  198860. for (i = png_pass_start[pass]; i < row_width;
  198861. i += png_pass_inc[pass])
  198862. {
  198863. sp = row + (png_size_t)(i >> 3);
  198864. value = (int)(*sp >> (7 - (int)(i & 0x07))) & 0x01;
  198865. d |= (value << shift);
  198866. if (shift == 0)
  198867. {
  198868. shift = 7;
  198869. *dp++ = (png_byte)d;
  198870. d = 0;
  198871. }
  198872. else
  198873. shift--;
  198874. }
  198875. if (shift != 7)
  198876. *dp = (png_byte)d;
  198877. break;
  198878. }
  198879. case 2:
  198880. {
  198881. png_bytep sp;
  198882. png_bytep dp;
  198883. int shift;
  198884. int d;
  198885. int value;
  198886. png_uint_32 i;
  198887. png_uint_32 row_width = row_info->width;
  198888. dp = row;
  198889. shift = 6;
  198890. d = 0;
  198891. for (i = png_pass_start[pass]; i < row_width;
  198892. i += png_pass_inc[pass])
  198893. {
  198894. sp = row + (png_size_t)(i >> 2);
  198895. value = (*sp >> ((3 - (int)(i & 0x03)) << 1)) & 0x03;
  198896. d |= (value << shift);
  198897. if (shift == 0)
  198898. {
  198899. shift = 6;
  198900. *dp++ = (png_byte)d;
  198901. d = 0;
  198902. }
  198903. else
  198904. shift -= 2;
  198905. }
  198906. if (shift != 6)
  198907. *dp = (png_byte)d;
  198908. break;
  198909. }
  198910. case 4:
  198911. {
  198912. png_bytep sp;
  198913. png_bytep dp;
  198914. int shift;
  198915. int d;
  198916. int value;
  198917. png_uint_32 i;
  198918. png_uint_32 row_width = row_info->width;
  198919. dp = row;
  198920. shift = 4;
  198921. d = 0;
  198922. for (i = png_pass_start[pass]; i < row_width;
  198923. i += png_pass_inc[pass])
  198924. {
  198925. sp = row + (png_size_t)(i >> 1);
  198926. value = (*sp >> ((1 - (int)(i & 0x01)) << 2)) & 0x0f;
  198927. d |= (value << shift);
  198928. if (shift == 0)
  198929. {
  198930. shift = 4;
  198931. *dp++ = (png_byte)d;
  198932. d = 0;
  198933. }
  198934. else
  198935. shift -= 4;
  198936. }
  198937. if (shift != 4)
  198938. *dp = (png_byte)d;
  198939. break;
  198940. }
  198941. default:
  198942. {
  198943. png_bytep sp;
  198944. png_bytep dp;
  198945. png_uint_32 i;
  198946. png_uint_32 row_width = row_info->width;
  198947. png_size_t pixel_bytes;
  198948. /* start at the beginning */
  198949. dp = row;
  198950. /* find out how many bytes each pixel takes up */
  198951. pixel_bytes = (row_info->pixel_depth >> 3);
  198952. /* loop through the row, only looking at the pixels that
  198953. matter */
  198954. for (i = png_pass_start[pass]; i < row_width;
  198955. i += png_pass_inc[pass])
  198956. {
  198957. /* find out where the original pixel is */
  198958. sp = row + (png_size_t)i * pixel_bytes;
  198959. /* move the pixel */
  198960. if (dp != sp)
  198961. png_memcpy(dp, sp, pixel_bytes);
  198962. /* next pixel */
  198963. dp += pixel_bytes;
  198964. }
  198965. break;
  198966. }
  198967. }
  198968. /* set new row width */
  198969. row_info->width = (row_info->width +
  198970. png_pass_inc[pass] - 1 -
  198971. png_pass_start[pass]) /
  198972. png_pass_inc[pass];
  198973. row_info->rowbytes = PNG_ROWBYTES(row_info->pixel_depth,
  198974. row_info->width);
  198975. }
  198976. }
  198977. #endif
  198978. /* This filters the row, chooses which filter to use, if it has not already
  198979. * been specified by the application, and then writes the row out with the
  198980. * chosen filter.
  198981. */
  198982. #define PNG_MAXSUM (((png_uint_32)(-1)) >> 1)
  198983. #define PNG_HISHIFT 10
  198984. #define PNG_LOMASK ((png_uint_32)0xffffL)
  198985. #define PNG_HIMASK ((png_uint_32)(~PNG_LOMASK >> PNG_HISHIFT))
  198986. void /* PRIVATE */
  198987. png_write_find_filter(png_structp png_ptr, png_row_infop row_info)
  198988. {
  198989. png_bytep best_row;
  198990. #ifndef PNG_NO_WRITE_FILTER
  198991. png_bytep prev_row, row_buf;
  198992. png_uint_32 mins, bpp;
  198993. png_byte filter_to_do = png_ptr->do_filter;
  198994. png_uint_32 row_bytes = row_info->rowbytes;
  198995. #if defined(PNG_WRITE_WEIGHTED_FILTER_SUPPORTED)
  198996. int num_p_filters = (int)png_ptr->num_prev_filters;
  198997. #endif
  198998. png_debug(1, "in png_write_find_filter\n");
  198999. /* find out how many bytes offset each pixel is */
  199000. bpp = (row_info->pixel_depth + 7) >> 3;
  199001. prev_row = png_ptr->prev_row;
  199002. #endif
  199003. best_row = png_ptr->row_buf;
  199004. #ifndef PNG_NO_WRITE_FILTER
  199005. row_buf = best_row;
  199006. mins = PNG_MAXSUM;
  199007. /* The prediction method we use is to find which method provides the
  199008. * smallest value when summing the absolute values of the distances
  199009. * from zero, using anything >= 128 as negative numbers. This is known
  199010. * as the "minimum sum of absolute differences" heuristic. Other
  199011. * heuristics are the "weighted minimum sum of absolute differences"
  199012. * (experimental and can in theory improve compression), and the "zlib
  199013. * predictive" method (not implemented yet), which does test compressions
  199014. * of lines using different filter methods, and then chooses the
  199015. * (series of) filter(s) that give minimum compressed data size (VERY
  199016. * computationally expensive).
  199017. *
  199018. * GRR 980525: consider also
  199019. * (1) minimum sum of absolute differences from running average (i.e.,
  199020. * keep running sum of non-absolute differences & count of bytes)
  199021. * [track dispersion, too? restart average if dispersion too large?]
  199022. * (1b) minimum sum of absolute differences from sliding average, probably
  199023. * with window size <= deflate window (usually 32K)
  199024. * (2) minimum sum of squared differences from zero or running average
  199025. * (i.e., ~ root-mean-square approach)
  199026. */
  199027. /* We don't need to test the 'no filter' case if this is the only filter
  199028. * that has been chosen, as it doesn't actually do anything to the data.
  199029. */
  199030. if ((filter_to_do & PNG_FILTER_NONE) &&
  199031. filter_to_do != PNG_FILTER_NONE)
  199032. {
  199033. png_bytep rp;
  199034. png_uint_32 sum = 0;
  199035. png_uint_32 i;
  199036. int v;
  199037. for (i = 0, rp = row_buf + 1; i < row_bytes; i++, rp++)
  199038. {
  199039. v = *rp;
  199040. sum += (v < 128) ? v : 256 - v;
  199041. }
  199042. #if defined(PNG_WRITE_WEIGHTED_FILTER_SUPPORTED)
  199043. if (png_ptr->heuristic_method == PNG_FILTER_HEURISTIC_WEIGHTED)
  199044. {
  199045. png_uint_32 sumhi, sumlo;
  199046. int j;
  199047. sumlo = sum & PNG_LOMASK;
  199048. sumhi = (sum >> PNG_HISHIFT) & PNG_HIMASK; /* Gives us some footroom */
  199049. /* Reduce the sum if we match any of the previous rows */
  199050. for (j = 0; j < num_p_filters; j++)
  199051. {
  199052. if (png_ptr->prev_filters[j] == PNG_FILTER_VALUE_NONE)
  199053. {
  199054. sumlo = (sumlo * png_ptr->filter_weights[j]) >>
  199055. PNG_WEIGHT_SHIFT;
  199056. sumhi = (sumhi * png_ptr->filter_weights[j]) >>
  199057. PNG_WEIGHT_SHIFT;
  199058. }
  199059. }
  199060. /* Factor in the cost of this filter (this is here for completeness,
  199061. * but it makes no sense to have a "cost" for the NONE filter, as
  199062. * it has the minimum possible computational cost - none).
  199063. */
  199064. sumlo = (sumlo * png_ptr->filter_costs[PNG_FILTER_VALUE_NONE]) >>
  199065. PNG_COST_SHIFT;
  199066. sumhi = (sumhi * png_ptr->filter_costs[PNG_FILTER_VALUE_NONE]) >>
  199067. PNG_COST_SHIFT;
  199068. if (sumhi > PNG_HIMASK)
  199069. sum = PNG_MAXSUM;
  199070. else
  199071. sum = (sumhi << PNG_HISHIFT) + sumlo;
  199072. }
  199073. #endif
  199074. mins = sum;
  199075. }
  199076. /* sub filter */
  199077. if (filter_to_do == PNG_FILTER_SUB)
  199078. /* it's the only filter so no testing is needed */
  199079. {
  199080. png_bytep rp, lp, dp;
  199081. png_uint_32 i;
  199082. for (i = 0, rp = row_buf + 1, dp = png_ptr->sub_row + 1; i < bpp;
  199083. i++, rp++, dp++)
  199084. {
  199085. *dp = *rp;
  199086. }
  199087. for (lp = row_buf + 1; i < row_bytes;
  199088. i++, rp++, lp++, dp++)
  199089. {
  199090. *dp = (png_byte)(((int)*rp - (int)*lp) & 0xff);
  199091. }
  199092. best_row = png_ptr->sub_row;
  199093. }
  199094. else if (filter_to_do & PNG_FILTER_SUB)
  199095. {
  199096. png_bytep rp, dp, lp;
  199097. png_uint_32 sum = 0, lmins = mins;
  199098. png_uint_32 i;
  199099. int v;
  199100. #if defined(PNG_WRITE_WEIGHTED_FILTER_SUPPORTED)
  199101. /* We temporarily increase the "minimum sum" by the factor we
  199102. * would reduce the sum of this filter, so that we can do the
  199103. * early exit comparison without scaling the sum each time.
  199104. */
  199105. if (png_ptr->heuristic_method == PNG_FILTER_HEURISTIC_WEIGHTED)
  199106. {
  199107. int j;
  199108. png_uint_32 lmhi, lmlo;
  199109. lmlo = lmins & PNG_LOMASK;
  199110. lmhi = (lmins >> PNG_HISHIFT) & PNG_HIMASK;
  199111. for (j = 0; j < num_p_filters; j++)
  199112. {
  199113. if (png_ptr->prev_filters[j] == PNG_FILTER_VALUE_SUB)
  199114. {
  199115. lmlo = (lmlo * png_ptr->inv_filter_weights[j]) >>
  199116. PNG_WEIGHT_SHIFT;
  199117. lmhi = (lmhi * png_ptr->inv_filter_weights[j]) >>
  199118. PNG_WEIGHT_SHIFT;
  199119. }
  199120. }
  199121. lmlo = (lmlo * png_ptr->inv_filter_costs[PNG_FILTER_VALUE_SUB]) >>
  199122. PNG_COST_SHIFT;
  199123. lmhi = (lmhi * png_ptr->inv_filter_costs[PNG_FILTER_VALUE_SUB]) >>
  199124. PNG_COST_SHIFT;
  199125. if (lmhi > PNG_HIMASK)
  199126. lmins = PNG_MAXSUM;
  199127. else
  199128. lmins = (lmhi << PNG_HISHIFT) + lmlo;
  199129. }
  199130. #endif
  199131. for (i = 0, rp = row_buf + 1, dp = png_ptr->sub_row + 1; i < bpp;
  199132. i++, rp++, dp++)
  199133. {
  199134. v = *dp = *rp;
  199135. sum += (v < 128) ? v : 256 - v;
  199136. }
  199137. for (lp = row_buf + 1; i < row_bytes;
  199138. i++, rp++, lp++, dp++)
  199139. {
  199140. v = *dp = (png_byte)(((int)*rp - (int)*lp) & 0xff);
  199141. sum += (v < 128) ? v : 256 - v;
  199142. if (sum > lmins) /* We are already worse, don't continue. */
  199143. break;
  199144. }
  199145. #if defined(PNG_WRITE_WEIGHTED_FILTER_SUPPORTED)
  199146. if (png_ptr->heuristic_method == PNG_FILTER_HEURISTIC_WEIGHTED)
  199147. {
  199148. int j;
  199149. png_uint_32 sumhi, sumlo;
  199150. sumlo = sum & PNG_LOMASK;
  199151. sumhi = (sum >> PNG_HISHIFT) & PNG_HIMASK;
  199152. for (j = 0; j < num_p_filters; j++)
  199153. {
  199154. if (png_ptr->prev_filters[j] == PNG_FILTER_VALUE_SUB)
  199155. {
  199156. sumlo = (sumlo * png_ptr->inv_filter_weights[j]) >>
  199157. PNG_WEIGHT_SHIFT;
  199158. sumhi = (sumhi * png_ptr->inv_filter_weights[j]) >>
  199159. PNG_WEIGHT_SHIFT;
  199160. }
  199161. }
  199162. sumlo = (sumlo * png_ptr->inv_filter_costs[PNG_FILTER_VALUE_SUB]) >>
  199163. PNG_COST_SHIFT;
  199164. sumhi = (sumhi * png_ptr->inv_filter_costs[PNG_FILTER_VALUE_SUB]) >>
  199165. PNG_COST_SHIFT;
  199166. if (sumhi > PNG_HIMASK)
  199167. sum = PNG_MAXSUM;
  199168. else
  199169. sum = (sumhi << PNG_HISHIFT) + sumlo;
  199170. }
  199171. #endif
  199172. if (sum < mins)
  199173. {
  199174. mins = sum;
  199175. best_row = png_ptr->sub_row;
  199176. }
  199177. }
  199178. /* up filter */
  199179. if (filter_to_do == PNG_FILTER_UP)
  199180. {
  199181. png_bytep rp, dp, pp;
  199182. png_uint_32 i;
  199183. for (i = 0, rp = row_buf + 1, dp = png_ptr->up_row + 1,
  199184. pp = prev_row + 1; i < row_bytes;
  199185. i++, rp++, pp++, dp++)
  199186. {
  199187. *dp = (png_byte)(((int)*rp - (int)*pp) & 0xff);
  199188. }
  199189. best_row = png_ptr->up_row;
  199190. }
  199191. else if (filter_to_do & PNG_FILTER_UP)
  199192. {
  199193. png_bytep rp, dp, pp;
  199194. png_uint_32 sum = 0, lmins = mins;
  199195. png_uint_32 i;
  199196. int v;
  199197. #if defined(PNG_WRITE_WEIGHTED_FILTER_SUPPORTED)
  199198. if (png_ptr->heuristic_method == PNG_FILTER_HEURISTIC_WEIGHTED)
  199199. {
  199200. int j;
  199201. png_uint_32 lmhi, lmlo;
  199202. lmlo = lmins & PNG_LOMASK;
  199203. lmhi = (lmins >> PNG_HISHIFT) & PNG_HIMASK;
  199204. for (j = 0; j < num_p_filters; j++)
  199205. {
  199206. if (png_ptr->prev_filters[j] == PNG_FILTER_VALUE_UP)
  199207. {
  199208. lmlo = (lmlo * png_ptr->inv_filter_weights[j]) >>
  199209. PNG_WEIGHT_SHIFT;
  199210. lmhi = (lmhi * png_ptr->inv_filter_weights[j]) >>
  199211. PNG_WEIGHT_SHIFT;
  199212. }
  199213. }
  199214. lmlo = (lmlo * png_ptr->inv_filter_costs[PNG_FILTER_VALUE_UP]) >>
  199215. PNG_COST_SHIFT;
  199216. lmhi = (lmhi * png_ptr->inv_filter_costs[PNG_FILTER_VALUE_UP]) >>
  199217. PNG_COST_SHIFT;
  199218. if (lmhi > PNG_HIMASK)
  199219. lmins = PNG_MAXSUM;
  199220. else
  199221. lmins = (lmhi << PNG_HISHIFT) + lmlo;
  199222. }
  199223. #endif
  199224. for (i = 0, rp = row_buf + 1, dp = png_ptr->up_row + 1,
  199225. pp = prev_row + 1; i < row_bytes; i++)
  199226. {
  199227. v = *dp++ = (png_byte)(((int)*rp++ - (int)*pp++) & 0xff);
  199228. sum += (v < 128) ? v : 256 - v;
  199229. if (sum > lmins) /* We are already worse, don't continue. */
  199230. break;
  199231. }
  199232. #if defined(PNG_WRITE_WEIGHTED_FILTER_SUPPORTED)
  199233. if (png_ptr->heuristic_method == PNG_FILTER_HEURISTIC_WEIGHTED)
  199234. {
  199235. int j;
  199236. png_uint_32 sumhi, sumlo;
  199237. sumlo = sum & PNG_LOMASK;
  199238. sumhi = (sum >> PNG_HISHIFT) & PNG_HIMASK;
  199239. for (j = 0; j < num_p_filters; j++)
  199240. {
  199241. if (png_ptr->prev_filters[j] == PNG_FILTER_VALUE_UP)
  199242. {
  199243. sumlo = (sumlo * png_ptr->filter_weights[j]) >>
  199244. PNG_WEIGHT_SHIFT;
  199245. sumhi = (sumhi * png_ptr->filter_weights[j]) >>
  199246. PNG_WEIGHT_SHIFT;
  199247. }
  199248. }
  199249. sumlo = (sumlo * png_ptr->filter_costs[PNG_FILTER_VALUE_UP]) >>
  199250. PNG_COST_SHIFT;
  199251. sumhi = (sumhi * png_ptr->filter_costs[PNG_FILTER_VALUE_UP]) >>
  199252. PNG_COST_SHIFT;
  199253. if (sumhi > PNG_HIMASK)
  199254. sum = PNG_MAXSUM;
  199255. else
  199256. sum = (sumhi << PNG_HISHIFT) + sumlo;
  199257. }
  199258. #endif
  199259. if (sum < mins)
  199260. {
  199261. mins = sum;
  199262. best_row = png_ptr->up_row;
  199263. }
  199264. }
  199265. /* avg filter */
  199266. if (filter_to_do == PNG_FILTER_AVG)
  199267. {
  199268. png_bytep rp, dp, pp, lp;
  199269. png_uint_32 i;
  199270. for (i = 0, rp = row_buf + 1, dp = png_ptr->avg_row + 1,
  199271. pp = prev_row + 1; i < bpp; i++)
  199272. {
  199273. *dp++ = (png_byte)(((int)*rp++ - ((int)*pp++ / 2)) & 0xff);
  199274. }
  199275. for (lp = row_buf + 1; i < row_bytes; i++)
  199276. {
  199277. *dp++ = (png_byte)(((int)*rp++ - (((int)*pp++ + (int)*lp++) / 2))
  199278. & 0xff);
  199279. }
  199280. best_row = png_ptr->avg_row;
  199281. }
  199282. else if (filter_to_do & PNG_FILTER_AVG)
  199283. {
  199284. png_bytep rp, dp, pp, lp;
  199285. png_uint_32 sum = 0, lmins = mins;
  199286. png_uint_32 i;
  199287. int v;
  199288. #if defined(PNG_WRITE_WEIGHTED_FILTER_SUPPORTED)
  199289. if (png_ptr->heuristic_method == PNG_FILTER_HEURISTIC_WEIGHTED)
  199290. {
  199291. int j;
  199292. png_uint_32 lmhi, lmlo;
  199293. lmlo = lmins & PNG_LOMASK;
  199294. lmhi = (lmins >> PNG_HISHIFT) & PNG_HIMASK;
  199295. for (j = 0; j < num_p_filters; j++)
  199296. {
  199297. if (png_ptr->prev_filters[j] == PNG_FILTER_VALUE_AVG)
  199298. {
  199299. lmlo = (lmlo * png_ptr->inv_filter_weights[j]) >>
  199300. PNG_WEIGHT_SHIFT;
  199301. lmhi = (lmhi * png_ptr->inv_filter_weights[j]) >>
  199302. PNG_WEIGHT_SHIFT;
  199303. }
  199304. }
  199305. lmlo = (lmlo * png_ptr->inv_filter_costs[PNG_FILTER_VALUE_AVG]) >>
  199306. PNG_COST_SHIFT;
  199307. lmhi = (lmhi * png_ptr->inv_filter_costs[PNG_FILTER_VALUE_AVG]) >>
  199308. PNG_COST_SHIFT;
  199309. if (lmhi > PNG_HIMASK)
  199310. lmins = PNG_MAXSUM;
  199311. else
  199312. lmins = (lmhi << PNG_HISHIFT) + lmlo;
  199313. }
  199314. #endif
  199315. for (i = 0, rp = row_buf + 1, dp = png_ptr->avg_row + 1,
  199316. pp = prev_row + 1; i < bpp; i++)
  199317. {
  199318. v = *dp++ = (png_byte)(((int)*rp++ - ((int)*pp++ / 2)) & 0xff);
  199319. sum += (v < 128) ? v : 256 - v;
  199320. }
  199321. for (lp = row_buf + 1; i < row_bytes; i++)
  199322. {
  199323. v = *dp++ =
  199324. (png_byte)(((int)*rp++ - (((int)*pp++ + (int)*lp++) / 2)) & 0xff);
  199325. sum += (v < 128) ? v : 256 - v;
  199326. if (sum > lmins) /* We are already worse, don't continue. */
  199327. break;
  199328. }
  199329. #if defined(PNG_WRITE_WEIGHTED_FILTER_SUPPORTED)
  199330. if (png_ptr->heuristic_method == PNG_FILTER_HEURISTIC_WEIGHTED)
  199331. {
  199332. int j;
  199333. png_uint_32 sumhi, sumlo;
  199334. sumlo = sum & PNG_LOMASK;
  199335. sumhi = (sum >> PNG_HISHIFT) & PNG_HIMASK;
  199336. for (j = 0; j < num_p_filters; j++)
  199337. {
  199338. if (png_ptr->prev_filters[j] == PNG_FILTER_VALUE_NONE)
  199339. {
  199340. sumlo = (sumlo * png_ptr->filter_weights[j]) >>
  199341. PNG_WEIGHT_SHIFT;
  199342. sumhi = (sumhi * png_ptr->filter_weights[j]) >>
  199343. PNG_WEIGHT_SHIFT;
  199344. }
  199345. }
  199346. sumlo = (sumlo * png_ptr->filter_costs[PNG_FILTER_VALUE_AVG]) >>
  199347. PNG_COST_SHIFT;
  199348. sumhi = (sumhi * png_ptr->filter_costs[PNG_FILTER_VALUE_AVG]) >>
  199349. PNG_COST_SHIFT;
  199350. if (sumhi > PNG_HIMASK)
  199351. sum = PNG_MAXSUM;
  199352. else
  199353. sum = (sumhi << PNG_HISHIFT) + sumlo;
  199354. }
  199355. #endif
  199356. if (sum < mins)
  199357. {
  199358. mins = sum;
  199359. best_row = png_ptr->avg_row;
  199360. }
  199361. }
  199362. /* Paeth filter */
  199363. if (filter_to_do == PNG_FILTER_PAETH)
  199364. {
  199365. png_bytep rp, dp, pp, cp, lp;
  199366. png_uint_32 i;
  199367. for (i = 0, rp = row_buf + 1, dp = png_ptr->paeth_row + 1,
  199368. pp = prev_row + 1; i < bpp; i++)
  199369. {
  199370. *dp++ = (png_byte)(((int)*rp++ - (int)*pp++) & 0xff);
  199371. }
  199372. for (lp = row_buf + 1, cp = prev_row + 1; i < row_bytes; i++)
  199373. {
  199374. int a, b, c, pa, pb, pc, p;
  199375. b = *pp++;
  199376. c = *cp++;
  199377. a = *lp++;
  199378. p = b - c;
  199379. pc = a - c;
  199380. #ifdef PNG_USE_ABS
  199381. pa = abs(p);
  199382. pb = abs(pc);
  199383. pc = abs(p + pc);
  199384. #else
  199385. pa = p < 0 ? -p : p;
  199386. pb = pc < 0 ? -pc : pc;
  199387. pc = (p + pc) < 0 ? -(p + pc) : p + pc;
  199388. #endif
  199389. p = (pa <= pb && pa <=pc) ? a : (pb <= pc) ? b : c;
  199390. *dp++ = (png_byte)(((int)*rp++ - p) & 0xff);
  199391. }
  199392. best_row = png_ptr->paeth_row;
  199393. }
  199394. else if (filter_to_do & PNG_FILTER_PAETH)
  199395. {
  199396. png_bytep rp, dp, pp, cp, lp;
  199397. png_uint_32 sum = 0, lmins = mins;
  199398. png_uint_32 i;
  199399. int v;
  199400. #if defined(PNG_WRITE_WEIGHTED_FILTER_SUPPORTED)
  199401. if (png_ptr->heuristic_method == PNG_FILTER_HEURISTIC_WEIGHTED)
  199402. {
  199403. int j;
  199404. png_uint_32 lmhi, lmlo;
  199405. lmlo = lmins & PNG_LOMASK;
  199406. lmhi = (lmins >> PNG_HISHIFT) & PNG_HIMASK;
  199407. for (j = 0; j < num_p_filters; j++)
  199408. {
  199409. if (png_ptr->prev_filters[j] == PNG_FILTER_VALUE_PAETH)
  199410. {
  199411. lmlo = (lmlo * png_ptr->inv_filter_weights[j]) >>
  199412. PNG_WEIGHT_SHIFT;
  199413. lmhi = (lmhi * png_ptr->inv_filter_weights[j]) >>
  199414. PNG_WEIGHT_SHIFT;
  199415. }
  199416. }
  199417. lmlo = (lmlo * png_ptr->inv_filter_costs[PNG_FILTER_VALUE_PAETH]) >>
  199418. PNG_COST_SHIFT;
  199419. lmhi = (lmhi * png_ptr->inv_filter_costs[PNG_FILTER_VALUE_PAETH]) >>
  199420. PNG_COST_SHIFT;
  199421. if (lmhi > PNG_HIMASK)
  199422. lmins = PNG_MAXSUM;
  199423. else
  199424. lmins = (lmhi << PNG_HISHIFT) + lmlo;
  199425. }
  199426. #endif
  199427. for (i = 0, rp = row_buf + 1, dp = png_ptr->paeth_row + 1,
  199428. pp = prev_row + 1; i < bpp; i++)
  199429. {
  199430. v = *dp++ = (png_byte)(((int)*rp++ - (int)*pp++) & 0xff);
  199431. sum += (v < 128) ? v : 256 - v;
  199432. }
  199433. for (lp = row_buf + 1, cp = prev_row + 1; i < row_bytes; i++)
  199434. {
  199435. int a, b, c, pa, pb, pc, p;
  199436. b = *pp++;
  199437. c = *cp++;
  199438. a = *lp++;
  199439. #ifndef PNG_SLOW_PAETH
  199440. p = b - c;
  199441. pc = a - c;
  199442. #ifdef PNG_USE_ABS
  199443. pa = abs(p);
  199444. pb = abs(pc);
  199445. pc = abs(p + pc);
  199446. #else
  199447. pa = p < 0 ? -p : p;
  199448. pb = pc < 0 ? -pc : pc;
  199449. pc = (p + pc) < 0 ? -(p + pc) : p + pc;
  199450. #endif
  199451. p = (pa <= pb && pa <=pc) ? a : (pb <= pc) ? b : c;
  199452. #else /* PNG_SLOW_PAETH */
  199453. p = a + b - c;
  199454. pa = abs(p - a);
  199455. pb = abs(p - b);
  199456. pc = abs(p - c);
  199457. if (pa <= pb && pa <= pc)
  199458. p = a;
  199459. else if (pb <= pc)
  199460. p = b;
  199461. else
  199462. p = c;
  199463. #endif /* PNG_SLOW_PAETH */
  199464. v = *dp++ = (png_byte)(((int)*rp++ - p) & 0xff);
  199465. sum += (v < 128) ? v : 256 - v;
  199466. if (sum > lmins) /* We are already worse, don't continue. */
  199467. break;
  199468. }
  199469. #if defined(PNG_WRITE_WEIGHTED_FILTER_SUPPORTED)
  199470. if (png_ptr->heuristic_method == PNG_FILTER_HEURISTIC_WEIGHTED)
  199471. {
  199472. int j;
  199473. png_uint_32 sumhi, sumlo;
  199474. sumlo = sum & PNG_LOMASK;
  199475. sumhi = (sum >> PNG_HISHIFT) & PNG_HIMASK;
  199476. for (j = 0; j < num_p_filters; j++)
  199477. {
  199478. if (png_ptr->prev_filters[j] == PNG_FILTER_VALUE_PAETH)
  199479. {
  199480. sumlo = (sumlo * png_ptr->filter_weights[j]) >>
  199481. PNG_WEIGHT_SHIFT;
  199482. sumhi = (sumhi * png_ptr->filter_weights[j]) >>
  199483. PNG_WEIGHT_SHIFT;
  199484. }
  199485. }
  199486. sumlo = (sumlo * png_ptr->filter_costs[PNG_FILTER_VALUE_PAETH]) >>
  199487. PNG_COST_SHIFT;
  199488. sumhi = (sumhi * png_ptr->filter_costs[PNG_FILTER_VALUE_PAETH]) >>
  199489. PNG_COST_SHIFT;
  199490. if (sumhi > PNG_HIMASK)
  199491. sum = PNG_MAXSUM;
  199492. else
  199493. sum = (sumhi << PNG_HISHIFT) + sumlo;
  199494. }
  199495. #endif
  199496. if (sum < mins)
  199497. {
  199498. best_row = png_ptr->paeth_row;
  199499. }
  199500. }
  199501. #endif /* PNG_NO_WRITE_FILTER */
  199502. /* Do the actual writing of the filtered row data from the chosen filter. */
  199503. png_write_filtered_row(png_ptr, best_row);
  199504. #ifndef PNG_NO_WRITE_FILTER
  199505. #if defined(PNG_WRITE_WEIGHTED_FILTER_SUPPORTED)
  199506. /* Save the type of filter we picked this time for future calculations */
  199507. if (png_ptr->num_prev_filters > 0)
  199508. {
  199509. int j;
  199510. for (j = 1; j < num_p_filters; j++)
  199511. {
  199512. png_ptr->prev_filters[j] = png_ptr->prev_filters[j - 1];
  199513. }
  199514. png_ptr->prev_filters[j] = best_row[0];
  199515. }
  199516. #endif
  199517. #endif /* PNG_NO_WRITE_FILTER */
  199518. }
  199519. /* Do the actual writing of a previously filtered row. */
  199520. void /* PRIVATE */
  199521. png_write_filtered_row(png_structp png_ptr, png_bytep filtered_row)
  199522. {
  199523. png_debug(1, "in png_write_filtered_row\n");
  199524. png_debug1(2, "filter = %d\n", filtered_row[0]);
  199525. /* set up the zlib input buffer */
  199526. png_ptr->zstream.next_in = filtered_row;
  199527. png_ptr->zstream.avail_in = (uInt)png_ptr->row_info.rowbytes + 1;
  199528. /* repeat until we have compressed all the data */
  199529. do
  199530. {
  199531. int ret; /* return of zlib */
  199532. /* compress the data */
  199533. ret = deflate(&png_ptr->zstream, Z_NO_FLUSH);
  199534. /* check for compression errors */
  199535. if (ret != Z_OK)
  199536. {
  199537. if (png_ptr->zstream.msg != NULL)
  199538. png_error(png_ptr, png_ptr->zstream.msg);
  199539. else
  199540. png_error(png_ptr, "zlib error");
  199541. }
  199542. /* see if it is time to write another IDAT */
  199543. if (!(png_ptr->zstream.avail_out))
  199544. {
  199545. /* write the IDAT and reset the zlib output buffer */
  199546. png_write_IDAT(png_ptr, png_ptr->zbuf, png_ptr->zbuf_size);
  199547. png_ptr->zstream.next_out = png_ptr->zbuf;
  199548. png_ptr->zstream.avail_out = (uInt)png_ptr->zbuf_size;
  199549. }
  199550. /* repeat until all data has been compressed */
  199551. } while (png_ptr->zstream.avail_in);
  199552. /* swap the current and previous rows */
  199553. if (png_ptr->prev_row != NULL)
  199554. {
  199555. png_bytep tptr;
  199556. tptr = png_ptr->prev_row;
  199557. png_ptr->prev_row = png_ptr->row_buf;
  199558. png_ptr->row_buf = tptr;
  199559. }
  199560. /* finish row - updates counters and flushes zlib if last row */
  199561. png_write_finish_row(png_ptr);
  199562. #if defined(PNG_WRITE_FLUSH_SUPPORTED)
  199563. png_ptr->flush_rows++;
  199564. if (png_ptr->flush_dist > 0 &&
  199565. png_ptr->flush_rows >= png_ptr->flush_dist)
  199566. {
  199567. png_write_flush(png_ptr);
  199568. }
  199569. #endif
  199570. }
  199571. #endif /* PNG_WRITE_SUPPORTED */
  199572. /*** End of inlined file: pngwutil.c ***/
  199573. }
  199574. #else
  199575. extern "C"
  199576. {
  199577. #include <png.h>
  199578. #include <pngconf.h>
  199579. }
  199580. #endif
  199581. }
  199582. #undef max
  199583. #undef min
  199584. #ifdef _MSC_VER
  199585. #pragma warning (pop)
  199586. #endif
  199587. BEGIN_JUCE_NAMESPACE
  199588. using ::calloc;
  199589. using ::malloc;
  199590. using ::free;
  199591. namespace PNGHelpers
  199592. {
  199593. using namespace pnglibNamespace;
  199594. static void readCallback (png_structp png, png_bytep data, png_size_t length)
  199595. {
  199596. static_cast<InputStream*> (png_get_io_ptr (png))->read (data, (int) length);
  199597. }
  199598. static void writeDataCallback (png_structp png, png_bytep data, png_size_t length)
  199599. {
  199600. static_cast<OutputStream*> (png_get_io_ptr (png))->write (data, (int) length);
  199601. }
  199602. struct PNGErrorStruct {};
  199603. static void errorCallback (png_structp, png_const_charp)
  199604. {
  199605. throw PNGErrorStruct();
  199606. }
  199607. }
  199608. PNGImageFormat::PNGImageFormat() {}
  199609. PNGImageFormat::~PNGImageFormat() {}
  199610. const String PNGImageFormat::getFormatName()
  199611. {
  199612. return "PNG";
  199613. }
  199614. bool PNGImageFormat::canUnderstand (InputStream& in)
  199615. {
  199616. const int bytesNeeded = 4;
  199617. char header [bytesNeeded];
  199618. return in.read (header, bytesNeeded) == bytesNeeded
  199619. && header[1] == 'P'
  199620. && header[2] == 'N'
  199621. && header[3] == 'G';
  199622. }
  199623. Image* PNGImageFormat::decodeImage (InputStream& in)
  199624. {
  199625. using namespace pnglibNamespace;
  199626. Image* image = 0;
  199627. png_structp pngReadStruct;
  199628. png_infop pngInfoStruct;
  199629. pngReadStruct = png_create_read_struct (PNG_LIBPNG_VER_STRING, 0, 0, 0);
  199630. if (pngReadStruct != 0)
  199631. {
  199632. pngInfoStruct = png_create_info_struct (pngReadStruct);
  199633. if (pngInfoStruct == 0)
  199634. {
  199635. png_destroy_read_struct (&pngReadStruct, 0, 0);
  199636. return 0;
  199637. }
  199638. png_set_error_fn (pngReadStruct, 0, PNGHelpers::errorCallback, PNGHelpers::errorCallback );
  199639. // read the header..
  199640. png_set_read_fn (pngReadStruct, &in, PNGHelpers::readCallback);
  199641. png_uint_32 width, height;
  199642. int bitDepth, colorType, interlaceType;
  199643. png_read_info (pngReadStruct, pngInfoStruct);
  199644. png_get_IHDR (pngReadStruct, pngInfoStruct,
  199645. &width, &height,
  199646. &bitDepth, &colorType,
  199647. &interlaceType, 0, 0);
  199648. if (bitDepth == 16)
  199649. png_set_strip_16 (pngReadStruct);
  199650. if (colorType == PNG_COLOR_TYPE_PALETTE)
  199651. png_set_expand (pngReadStruct);
  199652. if (bitDepth < 8)
  199653. png_set_expand (pngReadStruct);
  199654. if (png_get_valid (pngReadStruct, pngInfoStruct, PNG_INFO_tRNS))
  199655. png_set_expand (pngReadStruct);
  199656. if (colorType == PNG_COLOR_TYPE_GRAY || colorType == PNG_COLOR_TYPE_GRAY_ALPHA)
  199657. png_set_gray_to_rgb (pngReadStruct);
  199658. png_set_add_alpha (pngReadStruct, 0xff, PNG_FILLER_AFTER);
  199659. bool hasAlphaChan = (colorType & PNG_COLOR_MASK_ALPHA) != 0
  199660. || pngInfoStruct->num_trans > 0;
  199661. // Load the image into a temp buffer in the pnglib format..
  199662. HeapBlock <uint8> tempBuffer (height * (width << 2));
  199663. {
  199664. HeapBlock <png_bytep> rows (height);
  199665. for (int y = (int) height; --y >= 0;)
  199666. rows[y] = (png_bytep) (tempBuffer + (width << 2) * y);
  199667. png_read_image (pngReadStruct, rows);
  199668. png_read_end (pngReadStruct, pngInfoStruct);
  199669. }
  199670. png_destroy_read_struct (&pngReadStruct, &pngInfoStruct, 0);
  199671. // now convert the data to a juce image format..
  199672. image = Image::createNativeImage (hasAlphaChan ? Image::ARGB : Image::RGB,
  199673. (int) width, (int) height, hasAlphaChan);
  199674. hasAlphaChan = image->hasAlphaChannel(); // (the native image creator may not give back what we expect)
  199675. const Image::BitmapData destData (*image, 0, 0, (int) width, (int) height, true);
  199676. uint8* srcRow = tempBuffer;
  199677. uint8* destRow = destData.data;
  199678. for (int y = 0; y < (int) height; ++y)
  199679. {
  199680. const uint8* src = srcRow;
  199681. srcRow += (width << 2);
  199682. uint8* dest = destRow;
  199683. destRow += destData.lineStride;
  199684. if (hasAlphaChan)
  199685. {
  199686. for (int i = (int) width; --i >= 0;)
  199687. {
  199688. ((PixelARGB*) dest)->setARGB (src[3], src[0], src[1], src[2]);
  199689. ((PixelARGB*) dest)->premultiply();
  199690. dest += destData.pixelStride;
  199691. src += 4;
  199692. }
  199693. }
  199694. else
  199695. {
  199696. for (int i = (int) width; --i >= 0;)
  199697. {
  199698. ((PixelRGB*) dest)->setARGB (0, src[0], src[1], src[2]);
  199699. dest += destData.pixelStride;
  199700. src += 4;
  199701. }
  199702. }
  199703. }
  199704. }
  199705. return image;
  199706. }
  199707. bool PNGImageFormat::writeImageToStream (const Image& image, OutputStream& out)
  199708. {
  199709. using namespace pnglibNamespace;
  199710. const int width = image.getWidth();
  199711. const int height = image.getHeight();
  199712. png_structp pngWriteStruct = png_create_write_struct (PNG_LIBPNG_VER_STRING, 0, 0, 0);
  199713. if (pngWriteStruct == 0)
  199714. return false;
  199715. png_infop pngInfoStruct = png_create_info_struct (pngWriteStruct);
  199716. if (pngInfoStruct == 0)
  199717. {
  199718. png_destroy_write_struct (&pngWriteStruct, (png_infopp) 0);
  199719. return false;
  199720. }
  199721. png_set_write_fn (pngWriteStruct, &out, PNGHelpers::writeDataCallback, 0);
  199722. png_set_IHDR (pngWriteStruct, pngInfoStruct, width, height, 8,
  199723. image.hasAlphaChannel() ? PNG_COLOR_TYPE_RGB_ALPHA
  199724. : PNG_COLOR_TYPE_RGB,
  199725. PNG_INTERLACE_NONE,
  199726. PNG_COMPRESSION_TYPE_BASE,
  199727. PNG_FILTER_TYPE_BASE);
  199728. HeapBlock <uint8> rowData (width * 4);
  199729. png_color_8 sig_bit;
  199730. sig_bit.red = 8;
  199731. sig_bit.green = 8;
  199732. sig_bit.blue = 8;
  199733. sig_bit.alpha = 8;
  199734. png_set_sBIT (pngWriteStruct, pngInfoStruct, &sig_bit);
  199735. png_write_info (pngWriteStruct, pngInfoStruct);
  199736. png_set_shift (pngWriteStruct, &sig_bit);
  199737. png_set_packing (pngWriteStruct);
  199738. const Image::BitmapData srcData (image, 0, 0, width, height);
  199739. for (int y = 0; y < height; ++y)
  199740. {
  199741. uint8* dst = rowData;
  199742. const uint8* src = srcData.getLinePointer (y);
  199743. if (image.hasAlphaChannel())
  199744. {
  199745. for (int i = width; --i >= 0;)
  199746. {
  199747. PixelARGB p (*(const PixelARGB*) src);
  199748. p.unpremultiply();
  199749. *dst++ = p.getRed();
  199750. *dst++ = p.getGreen();
  199751. *dst++ = p.getBlue();
  199752. *dst++ = p.getAlpha();
  199753. src += srcData.pixelStride;
  199754. }
  199755. }
  199756. else
  199757. {
  199758. for (int i = width; --i >= 0;)
  199759. {
  199760. *dst++ = ((const PixelRGB*) src)->getRed();
  199761. *dst++ = ((const PixelRGB*) src)->getGreen();
  199762. *dst++ = ((const PixelRGB*) src)->getBlue();
  199763. src += srcData.pixelStride;
  199764. }
  199765. }
  199766. png_write_rows (pngWriteStruct, &rowData, 1);
  199767. }
  199768. png_write_end (pngWriteStruct, pngInfoStruct);
  199769. png_destroy_write_struct (&pngWriteStruct, &pngInfoStruct);
  199770. out.flush();
  199771. return true;
  199772. }
  199773. END_JUCE_NAMESPACE
  199774. /*** End of inlined file: juce_PNGLoader.cpp ***/
  199775. #endif
  199776. //==============================================================================
  199777. #if JUCE_BUILD_NATIVE
  199778. #if JUCE_WINDOWS
  199779. /*** Start of inlined file: juce_win32_NativeCode.cpp ***/
  199780. /*
  199781. This file wraps together all the win32-specific code, so that
  199782. we can include all the native headers just once, and compile all our
  199783. platform-specific stuff in one big lump, keeping it out of the way of
  199784. the rest of the codebase.
  199785. */
  199786. #if JUCE_WINDOWS
  199787. BEGIN_JUCE_NAMESPACE
  199788. #define JUCE_INCLUDED_FILE 1
  199789. // Now include the actual code files..
  199790. /*** Start of inlined file: juce_win32_DynamicLibraryLoader.cpp ***/
  199791. // (This file gets included by juce_win32_NativeCode.cpp, rather than being
  199792. // compiled on its own).
  199793. #if JUCE_INCLUDED_FILE
  199794. /*** Start of inlined file: juce_win32_DynamicLibraryLoader.h ***/
  199795. #ifndef __JUCE_WIN32_DYNAMICLIBRARYLOADER_JUCEHEADER__
  199796. #define __JUCE_WIN32_DYNAMICLIBRARYLOADER_JUCEHEADER__
  199797. #ifndef DOXYGEN
  199798. // use with DynamicLibraryLoader to simplify importing functions
  199799. //
  199800. // functionName: function to import
  199801. // localFunctionName: name you want to use to actually call it (must be different)
  199802. // returnType: the return type
  199803. // object: the DynamicLibraryLoader to use
  199804. // params: list of params (bracketed)
  199805. //
  199806. #define DynamicLibraryImport(functionName, localFunctionName, returnType, object, params) \
  199807. typedef returnType (WINAPI *type##localFunctionName) params; \
  199808. type##localFunctionName localFunctionName \
  199809. = (type##localFunctionName)object.findProcAddress (#functionName);
  199810. // loads and unloads a DLL automatically
  199811. class JUCE_API DynamicLibraryLoader
  199812. {
  199813. public:
  199814. DynamicLibraryLoader (const String& name);
  199815. ~DynamicLibraryLoader();
  199816. void* findProcAddress (const String& functionName);
  199817. private:
  199818. void* libHandle;
  199819. };
  199820. #endif
  199821. #endif // __JUCE_WIN32_DYNAMICLIBRARYLOADER_JUCEHEADER__
  199822. /*** End of inlined file: juce_win32_DynamicLibraryLoader.h ***/
  199823. DynamicLibraryLoader::DynamicLibraryLoader (const String& name)
  199824. {
  199825. libHandle = LoadLibrary (name);
  199826. }
  199827. DynamicLibraryLoader::~DynamicLibraryLoader()
  199828. {
  199829. FreeLibrary ((HMODULE) libHandle);
  199830. }
  199831. void* DynamicLibraryLoader::findProcAddress (const String& functionName)
  199832. {
  199833. return GetProcAddress ((HMODULE) libHandle, functionName.toCString());
  199834. }
  199835. #endif
  199836. /*** End of inlined file: juce_win32_DynamicLibraryLoader.cpp ***/
  199837. /*** Start of inlined file: juce_win32_SystemStats.cpp ***/
  199838. // (This file gets included by juce_win32_NativeCode.cpp, rather than being
  199839. // compiled on its own).
  199840. #if JUCE_INCLUDED_FILE
  199841. extern void juce_initialiseThreadEvents();
  199842. void Logger::outputDebugString (const String& text) throw()
  199843. {
  199844. OutputDebugString (text + "\n");
  199845. }
  199846. static int64 hiResTicksPerSecond;
  199847. static double hiResTicksScaleFactor;
  199848. #if JUCE_USE_INTRINSICS
  199849. // CPU info functions using intrinsics...
  199850. #pragma intrinsic (__cpuid)
  199851. #pragma intrinsic (__rdtsc)
  199852. const String SystemStats::getCpuVendor() throw()
  199853. {
  199854. int info [4];
  199855. __cpuid (info, 0);
  199856. char v [12];
  199857. memcpy (v, info + 1, 4);
  199858. memcpy (v + 4, info + 3, 4);
  199859. memcpy (v + 8, info + 2, 4);
  199860. return String (v, 12);
  199861. }
  199862. #else
  199863. // CPU info functions using old fashioned inline asm...
  199864. static void juce_getCpuVendor (char* const v)
  199865. {
  199866. int vendor[4];
  199867. zeromem (vendor, 16);
  199868. #ifdef JUCE_64BIT
  199869. #else
  199870. #ifndef __MINGW32__
  199871. __try
  199872. #endif
  199873. {
  199874. #if JUCE_GCC
  199875. unsigned int dummy = 0;
  199876. __asm__ ("cpuid" : "=a" (dummy), "=b" (vendor[0]), "=c" (vendor[2]),"=d" (vendor[1]) : "a" (0));
  199877. #else
  199878. __asm
  199879. {
  199880. mov eax, 0
  199881. cpuid
  199882. mov [vendor], ebx
  199883. mov [vendor + 4], edx
  199884. mov [vendor + 8], ecx
  199885. }
  199886. #endif
  199887. }
  199888. #ifndef __MINGW32__
  199889. __except (EXCEPTION_EXECUTE_HANDLER)
  199890. {
  199891. *v = 0;
  199892. }
  199893. #endif
  199894. #endif
  199895. memcpy (v, vendor, 16);
  199896. }
  199897. const String SystemStats::getCpuVendor() throw()
  199898. {
  199899. char v [16];
  199900. juce_getCpuVendor (v);
  199901. return String (v, 16);
  199902. }
  199903. #endif
  199904. struct CPUFlags
  199905. {
  199906. bool hasMMX : 1;
  199907. bool hasSSE : 1;
  199908. bool hasSSE2 : 1;
  199909. bool has3DNow : 1;
  199910. };
  199911. static CPUFlags cpuFlags;
  199912. bool SystemStats::hasMMX() throw()
  199913. {
  199914. return cpuFlags.hasMMX;
  199915. }
  199916. bool SystemStats::hasSSE() throw()
  199917. {
  199918. return cpuFlags.hasSSE;
  199919. }
  199920. bool SystemStats::hasSSE2() throw()
  199921. {
  199922. return cpuFlags.hasSSE2;
  199923. }
  199924. bool SystemStats::has3DNow() throw()
  199925. {
  199926. return cpuFlags.has3DNow;
  199927. }
  199928. void SystemStats::initialiseStats() throw()
  199929. {
  199930. juce_initialiseThreadEvents();
  199931. cpuFlags.hasMMX = IsProcessorFeaturePresent (PF_MMX_INSTRUCTIONS_AVAILABLE) != 0;
  199932. cpuFlags.hasSSE = IsProcessorFeaturePresent (PF_XMMI_INSTRUCTIONS_AVAILABLE) != 0;
  199933. cpuFlags.hasSSE2 = IsProcessorFeaturePresent (PF_XMMI64_INSTRUCTIONS_AVAILABLE) != 0;
  199934. #ifdef PF_AMD3D_INSTRUCTIONS_AVAILABLE
  199935. cpuFlags.has3DNow = IsProcessorFeaturePresent (PF_AMD3D_INSTRUCTIONS_AVAILABLE) != 0;
  199936. #else
  199937. cpuFlags.has3DNow = IsProcessorFeaturePresent (PF_3DNOW_INSTRUCTIONS_AVAILABLE) != 0;
  199938. #endif
  199939. LARGE_INTEGER f;
  199940. QueryPerformanceFrequency (&f);
  199941. hiResTicksPerSecond = f.QuadPart;
  199942. hiResTicksScaleFactor = 1000.0 / hiResTicksPerSecond;
  199943. String s (SystemStats::getJUCEVersion());
  199944. #if JUCE_DEBUG
  199945. const MMRESULT res = timeBeginPeriod (1);
  199946. jassert (res == TIMERR_NOERROR);
  199947. #else
  199948. timeBeginPeriod (1);
  199949. #endif
  199950. #if JUCE_DEBUG && JUCE_MSVC && JUCE_CHECK_MEMORY_LEAKS
  199951. _CrtSetDbgFlag (_CRTDBG_ALLOC_MEM_DF | _CRTDBG_LEAK_CHECK_DF);
  199952. #endif
  199953. }
  199954. SystemStats::OperatingSystemType SystemStats::getOperatingSystemType() throw()
  199955. {
  199956. OSVERSIONINFO info;
  199957. info.dwOSVersionInfoSize = sizeof (info);
  199958. GetVersionEx (&info);
  199959. if (info.dwPlatformId == VER_PLATFORM_WIN32_NT)
  199960. {
  199961. switch (info.dwMajorVersion)
  199962. {
  199963. case 5: return (info.dwMinorVersion == 0) ? Win2000 : WinXP;
  199964. case 6: return (info.dwMinorVersion == 0) ? WinVista : Windows7;
  199965. default: jassertfalse; break; // !! not a supported OS!
  199966. }
  199967. }
  199968. else if (info.dwPlatformId == VER_PLATFORM_WIN32_WINDOWS)
  199969. {
  199970. jassert (info.dwMinorVersion != 0); // !! still running on Windows 95??
  199971. return Win98;
  199972. }
  199973. return UnknownOS;
  199974. }
  199975. const String SystemStats::getOperatingSystemName() throw()
  199976. {
  199977. const char* name = "Unknown OS";
  199978. switch (getOperatingSystemType())
  199979. {
  199980. case Windows7: name = "Windows 7"; break;
  199981. case WinVista: name = "Windows Vista"; break;
  199982. case WinXP: name = "Windows XP"; break;
  199983. case Win2000: name = "Windows 2000"; break;
  199984. case Win98: name = "Windows 98"; break;
  199985. default: jassertfalse; break; // !! new type of OS?
  199986. }
  199987. return name;
  199988. }
  199989. bool SystemStats::isOperatingSystem64Bit() throw()
  199990. {
  199991. #ifdef _WIN64
  199992. return true;
  199993. #else
  199994. typedef BOOL (WINAPI* LPFN_ISWOW64PROCESS) (HANDLE, PBOOL);
  199995. LPFN_ISWOW64PROCESS fnIsWow64Process = (LPFN_ISWOW64PROCESS) GetProcAddress (GetModuleHandle (L"kernel32"), "IsWow64Process");
  199996. BOOL isWow64 = FALSE;
  199997. return (fnIsWow64Process != 0)
  199998. && fnIsWow64Process (GetCurrentProcess(), &isWow64)
  199999. && (isWow64 != FALSE);
  200000. #endif
  200001. }
  200002. int SystemStats::getMemorySizeInMegabytes() throw()
  200003. {
  200004. MEMORYSTATUSEX mem;
  200005. mem.dwLength = sizeof (mem);
  200006. GlobalMemoryStatusEx (&mem);
  200007. return (int) (mem.ullTotalPhys / (1024 * 1024)) + 1;
  200008. }
  200009. int SystemStats::getNumCpus() throw()
  200010. {
  200011. SYSTEM_INFO systemInfo;
  200012. GetSystemInfo (&systemInfo);
  200013. return systemInfo.dwNumberOfProcessors;
  200014. }
  200015. uint32 juce_millisecondsSinceStartup() throw()
  200016. {
  200017. return (uint32) GetTickCount();
  200018. }
  200019. int64 Time::getHighResolutionTicks() throw()
  200020. {
  200021. LARGE_INTEGER ticks;
  200022. QueryPerformanceCounter (&ticks);
  200023. const int64 mainCounterAsHiResTicks = (GetTickCount() * hiResTicksPerSecond) / 1000;
  200024. const int64 newOffset = mainCounterAsHiResTicks - ticks.QuadPart;
  200025. // fix for a very obscure PCI hardware bug that can make the counter
  200026. // sometimes jump forwards by a few seconds..
  200027. static int64 hiResTicksOffset = 0;
  200028. const int64 offsetDrift = abs64 (newOffset - hiResTicksOffset);
  200029. if (offsetDrift > (hiResTicksPerSecond >> 1))
  200030. hiResTicksOffset = newOffset;
  200031. return ticks.QuadPart + hiResTicksOffset;
  200032. }
  200033. double Time::getMillisecondCounterHiRes() throw()
  200034. {
  200035. return getHighResolutionTicks() * hiResTicksScaleFactor;
  200036. }
  200037. int64 Time::getHighResolutionTicksPerSecond() throw()
  200038. {
  200039. return hiResTicksPerSecond;
  200040. }
  200041. int64 SystemStats::getClockCycleCounter() throw()
  200042. {
  200043. #if JUCE_USE_INTRINSICS
  200044. // MS intrinsics version...
  200045. return __rdtsc();
  200046. #elif JUCE_GCC
  200047. // GNU inline asm version...
  200048. unsigned int hi = 0, lo = 0;
  200049. __asm__ __volatile__ (
  200050. "xor %%eax, %%eax \n\
  200051. xor %%edx, %%edx \n\
  200052. rdtsc \n\
  200053. movl %%eax, %[lo] \n\
  200054. movl %%edx, %[hi]"
  200055. :
  200056. : [hi] "m" (hi),
  200057. [lo] "m" (lo)
  200058. : "cc", "eax", "ebx", "ecx", "edx", "memory");
  200059. return (int64) ((((uint64) hi) << 32) | lo);
  200060. #else
  200061. // MSVC inline asm version...
  200062. unsigned int hi = 0, lo = 0;
  200063. __asm
  200064. {
  200065. xor eax, eax
  200066. xor edx, edx
  200067. rdtsc
  200068. mov lo, eax
  200069. mov hi, edx
  200070. }
  200071. return (int64) ((((uint64) hi) << 32) | lo);
  200072. #endif
  200073. }
  200074. int SystemStats::getCpuSpeedInMegaherz() throw()
  200075. {
  200076. const int64 cycles = SystemStats::getClockCycleCounter();
  200077. const uint32 millis = Time::getMillisecondCounter();
  200078. int lastResult = 0;
  200079. for (;;)
  200080. {
  200081. int n = 1000000;
  200082. while (--n > 0) {}
  200083. const uint32 millisElapsed = Time::getMillisecondCounter() - millis;
  200084. const int64 cyclesNow = SystemStats::getClockCycleCounter();
  200085. if (millisElapsed > 80)
  200086. {
  200087. const int newResult = (int) (((cyclesNow - cycles) / millisElapsed) / 1000);
  200088. if (millisElapsed > 500 || (lastResult == newResult && newResult > 100))
  200089. return newResult;
  200090. lastResult = newResult;
  200091. }
  200092. }
  200093. }
  200094. bool Time::setSystemTimeToThisTime() const throw()
  200095. {
  200096. SYSTEMTIME st;
  200097. st.wDayOfWeek = 0;
  200098. st.wYear = (WORD) getYear();
  200099. st.wMonth = (WORD) (getMonth() + 1);
  200100. st.wDay = (WORD) getDayOfMonth();
  200101. st.wHour = (WORD) getHours();
  200102. st.wMinute = (WORD) getMinutes();
  200103. st.wSecond = (WORD) getSeconds();
  200104. st.wMilliseconds = (WORD) (millisSinceEpoch % 1000);
  200105. // do this twice because of daylight saving conversion problems - the
  200106. // first one sets it up, the second one kicks it in.
  200107. return SetLocalTime (&st) != 0
  200108. && SetLocalTime (&st) != 0;
  200109. }
  200110. int SystemStats::getPageSize() throw()
  200111. {
  200112. SYSTEM_INFO systemInfo;
  200113. GetSystemInfo (&systemInfo);
  200114. return systemInfo.dwPageSize;
  200115. }
  200116. const String SystemStats::getLogonName()
  200117. {
  200118. TCHAR text [256];
  200119. DWORD len = numElementsInArray (text) - 2;
  200120. zerostruct (text);
  200121. GetUserName (text, &len);
  200122. return String (text, len);
  200123. }
  200124. const String SystemStats::getFullUserName()
  200125. {
  200126. return getLogonName();
  200127. }
  200128. #endif
  200129. /*** End of inlined file: juce_win32_SystemStats.cpp ***/
  200130. /*** Start of inlined file: juce_win32_Threads.cpp ***/
  200131. // (This file gets included by juce_win32_NativeCode.cpp, rather than being
  200132. // compiled on its own).
  200133. #if JUCE_INCLUDED_FILE
  200134. #if ! JUCE_ONLY_BUILD_CORE_LIBRARY
  200135. extern HWND juce_messageWindowHandle;
  200136. #endif
  200137. #if ! JUCE_USE_INTRINSICS
  200138. // In newer compilers, the inline versions of these are used (in juce_Atomic.h), but in
  200139. // older ones we have to actually call the ops as win32 functions..
  200140. long juce_InterlockedExchange (volatile long* a, long b) throw() { return InterlockedExchange (a, b); }
  200141. long juce_InterlockedIncrement (volatile long* a) throw() { return InterlockedIncrement (a); }
  200142. long juce_InterlockedDecrement (volatile long* a) throw() { return InterlockedDecrement (a); }
  200143. long juce_InterlockedExchangeAdd (volatile long* a, long b) throw() { return InterlockedExchangeAdd (a, b); }
  200144. long juce_InterlockedCompareExchange (volatile long* a, long b, long c) throw() { return InterlockedCompareExchange (a, b, c); }
  200145. __int64 juce_InterlockedCompareExchange64 (volatile __int64* value, __int64 newValue, __int64 valueToCompare) throw()
  200146. {
  200147. jassertfalse; // This operation isn't available in old MS compiler versions!
  200148. __int64 oldValue = *value;
  200149. if (oldValue == valueToCompare)
  200150. *value = newValue;
  200151. return oldValue;
  200152. }
  200153. #endif
  200154. CriticalSection::CriticalSection() throw()
  200155. {
  200156. // (just to check the MS haven't changed this structure and broken things...)
  200157. #if _MSC_VER >= 1400
  200158. static_jassert (sizeof (CRITICAL_SECTION) <= sizeof (internal));
  200159. #else
  200160. static_jassert (sizeof (CRITICAL_SECTION) <= 24);
  200161. #endif
  200162. InitializeCriticalSection ((CRITICAL_SECTION*) internal);
  200163. }
  200164. CriticalSection::~CriticalSection() throw()
  200165. {
  200166. DeleteCriticalSection ((CRITICAL_SECTION*) internal);
  200167. }
  200168. void CriticalSection::enter() const throw()
  200169. {
  200170. EnterCriticalSection ((CRITICAL_SECTION*) internal);
  200171. }
  200172. bool CriticalSection::tryEnter() const throw()
  200173. {
  200174. return TryEnterCriticalSection ((CRITICAL_SECTION*) internal) != FALSE;
  200175. }
  200176. void CriticalSection::exit() const throw()
  200177. {
  200178. LeaveCriticalSection ((CRITICAL_SECTION*) internal);
  200179. }
  200180. WaitableEvent::WaitableEvent (const bool manualReset) throw()
  200181. : internal (CreateEvent (0, manualReset ? TRUE : FALSE, FALSE, 0))
  200182. {
  200183. }
  200184. WaitableEvent::~WaitableEvent() throw()
  200185. {
  200186. CloseHandle (internal);
  200187. }
  200188. bool WaitableEvent::wait (const int timeOutMillisecs) const throw()
  200189. {
  200190. return WaitForSingleObject (internal, timeOutMillisecs) == WAIT_OBJECT_0;
  200191. }
  200192. void WaitableEvent::signal() const throw()
  200193. {
  200194. SetEvent (internal);
  200195. }
  200196. void WaitableEvent::reset() const throw()
  200197. {
  200198. ResetEvent (internal);
  200199. }
  200200. void JUCE_API juce_threadEntryPoint (void*);
  200201. static unsigned int __stdcall threadEntryProc (void* userData)
  200202. {
  200203. #if ! JUCE_ONLY_BUILD_CORE_LIBRARY
  200204. AttachThreadInput (GetWindowThreadProcessId (juce_messageWindowHandle, 0),
  200205. GetCurrentThreadId(), TRUE);
  200206. #endif
  200207. juce_threadEntryPoint (userData);
  200208. _endthreadex (0);
  200209. return 0;
  200210. }
  200211. void juce_CloseThreadHandle (void* handle)
  200212. {
  200213. CloseHandle ((HANDLE) handle);
  200214. }
  200215. void* juce_createThread (void* userData)
  200216. {
  200217. unsigned int threadId;
  200218. return (void*) _beginthreadex (0, 0, &threadEntryProc, userData, 0, &threadId);
  200219. }
  200220. void juce_killThread (void* handle)
  200221. {
  200222. if (handle != 0)
  200223. {
  200224. #if JUCE_DEBUG
  200225. OutputDebugString (_T("** Warning - Forced thread termination **\n"));
  200226. #endif
  200227. TerminateThread (handle, 0);
  200228. }
  200229. }
  200230. void juce_setCurrentThreadName (const String& name)
  200231. {
  200232. #if JUCE_DEBUG && JUCE_MSVC
  200233. struct
  200234. {
  200235. DWORD dwType;
  200236. LPCSTR szName;
  200237. DWORD dwThreadID;
  200238. DWORD dwFlags;
  200239. } info;
  200240. info.dwType = 0x1000;
  200241. info.szName = name.toCString();
  200242. info.dwThreadID = GetCurrentThreadId();
  200243. info.dwFlags = 0;
  200244. __try
  200245. {
  200246. RaiseException (0x406d1388 /*MS_VC_EXCEPTION*/, 0, sizeof (info) / sizeof (ULONG_PTR), (ULONG_PTR*) &info);
  200247. }
  200248. __except (EXCEPTION_CONTINUE_EXECUTION)
  200249. {}
  200250. #else
  200251. (void) name;
  200252. #endif
  200253. }
  200254. Thread::ThreadID Thread::getCurrentThreadId()
  200255. {
  200256. return (ThreadID) (pointer_sized_int) GetCurrentThreadId();
  200257. }
  200258. // priority 1 to 10 where 5=normal, 1=low
  200259. bool juce_setThreadPriority (void* threadHandle, int priority)
  200260. {
  200261. int pri = THREAD_PRIORITY_TIME_CRITICAL;
  200262. if (priority < 1)
  200263. pri = THREAD_PRIORITY_IDLE;
  200264. else if (priority < 2)
  200265. pri = THREAD_PRIORITY_LOWEST;
  200266. else if (priority < 5)
  200267. pri = THREAD_PRIORITY_BELOW_NORMAL;
  200268. else if (priority < 7)
  200269. pri = THREAD_PRIORITY_NORMAL;
  200270. else if (priority < 9)
  200271. pri = THREAD_PRIORITY_ABOVE_NORMAL;
  200272. else if (priority < 10)
  200273. pri = THREAD_PRIORITY_HIGHEST;
  200274. if (threadHandle == 0)
  200275. threadHandle = GetCurrentThread();
  200276. return SetThreadPriority (threadHandle, pri) != FALSE;
  200277. }
  200278. void Thread::setCurrentThreadAffinityMask (const uint32 affinityMask)
  200279. {
  200280. SetThreadAffinityMask (GetCurrentThread(), affinityMask);
  200281. }
  200282. static HANDLE sleepEvent = 0;
  200283. void juce_initialiseThreadEvents()
  200284. {
  200285. if (sleepEvent == 0)
  200286. #if JUCE_DEBUG
  200287. sleepEvent = CreateEvent (0, 0, 0, _T("Juce Sleep Event"));
  200288. #else
  200289. sleepEvent = CreateEvent (0, 0, 0, 0);
  200290. #endif
  200291. }
  200292. void Thread::yield()
  200293. {
  200294. Sleep (0);
  200295. }
  200296. void JUCE_CALLTYPE Thread::sleep (const int millisecs)
  200297. {
  200298. if (millisecs >= 10)
  200299. {
  200300. Sleep (millisecs);
  200301. }
  200302. else
  200303. {
  200304. jassert (sleepEvent != 0);
  200305. // unlike Sleep() this is guaranteed to return to the current thread after
  200306. // the time expires, so we'll use this for short waits, which are more likely
  200307. // to need to be accurate
  200308. WaitForSingleObject (sleepEvent, millisecs);
  200309. }
  200310. }
  200311. static int lastProcessPriority = -1;
  200312. // called by WindowDriver because Windows does wierd things to process priority
  200313. // when you swap apps, and this forces an update when the app is brought to the front.
  200314. void juce_repeatLastProcessPriority()
  200315. {
  200316. if (lastProcessPriority >= 0) // (avoid changing this if it's not been explicitly set by the app..)
  200317. {
  200318. DWORD p;
  200319. switch (lastProcessPriority)
  200320. {
  200321. case Process::LowPriority: p = IDLE_PRIORITY_CLASS; break;
  200322. case Process::NormalPriority: p = NORMAL_PRIORITY_CLASS; break;
  200323. case Process::HighPriority: p = HIGH_PRIORITY_CLASS; break;
  200324. case Process::RealtimePriority: p = REALTIME_PRIORITY_CLASS; break;
  200325. default: jassertfalse; return; // bad priority value
  200326. }
  200327. SetPriorityClass (GetCurrentProcess(), p);
  200328. }
  200329. }
  200330. void Process::setPriority (ProcessPriority prior)
  200331. {
  200332. if (lastProcessPriority != (int) prior)
  200333. {
  200334. lastProcessPriority = (int) prior;
  200335. juce_repeatLastProcessPriority();
  200336. }
  200337. }
  200338. bool JUCE_PUBLIC_FUNCTION juce_isRunningUnderDebugger()
  200339. {
  200340. return IsDebuggerPresent() != FALSE;
  200341. }
  200342. bool JUCE_CALLTYPE Process::isRunningUnderDebugger()
  200343. {
  200344. return juce_isRunningUnderDebugger();
  200345. }
  200346. void Process::raisePrivilege()
  200347. {
  200348. jassertfalse // xxx not implemented
  200349. }
  200350. void Process::lowerPrivilege()
  200351. {
  200352. jassertfalse // xxx not implemented
  200353. }
  200354. void Process::terminate()
  200355. {
  200356. #if JUCE_DEBUG && JUCE_MSVC && JUCE_CHECK_MEMORY_LEAKS
  200357. _CrtDumpMemoryLeaks();
  200358. #endif
  200359. // bullet in the head in case there's a problem shutting down..
  200360. ExitProcess (0);
  200361. }
  200362. void* PlatformUtilities::loadDynamicLibrary (const String& name)
  200363. {
  200364. void* result = 0;
  200365. JUCE_TRY
  200366. {
  200367. result = LoadLibrary (name);
  200368. }
  200369. JUCE_CATCH_ALL
  200370. return result;
  200371. }
  200372. void PlatformUtilities::freeDynamicLibrary (void* h)
  200373. {
  200374. JUCE_TRY
  200375. {
  200376. if (h != 0)
  200377. FreeLibrary ((HMODULE) h);
  200378. }
  200379. JUCE_CATCH_ALL
  200380. }
  200381. void* PlatformUtilities::getProcedureEntryPoint (void* h, const String& name)
  200382. {
  200383. return (h != 0) ? GetProcAddress ((HMODULE) h, name.toCString()) : 0;
  200384. }
  200385. class InterProcessLock::Pimpl
  200386. {
  200387. public:
  200388. Pimpl (const String& name, const int timeOutMillisecs)
  200389. : handle (0), refCount (1)
  200390. {
  200391. handle = CreateMutex (0, TRUE, "Global\\" + name.replaceCharacter ('\\','/'));
  200392. if (handle != 0 && GetLastError() == ERROR_ALREADY_EXISTS)
  200393. {
  200394. if (timeOutMillisecs == 0)
  200395. {
  200396. close();
  200397. return;
  200398. }
  200399. switch (WaitForSingleObject (handle, timeOutMillisecs < 0 ? INFINITE : timeOutMillisecs))
  200400. {
  200401. case WAIT_OBJECT_0:
  200402. case WAIT_ABANDONED:
  200403. break;
  200404. case WAIT_TIMEOUT:
  200405. default:
  200406. close();
  200407. break;
  200408. }
  200409. }
  200410. }
  200411. ~Pimpl()
  200412. {
  200413. close();
  200414. }
  200415. void close()
  200416. {
  200417. if (handle != 0)
  200418. {
  200419. ReleaseMutex (handle);
  200420. CloseHandle (handle);
  200421. handle = 0;
  200422. }
  200423. }
  200424. HANDLE handle;
  200425. int refCount;
  200426. };
  200427. InterProcessLock::InterProcessLock (const String& name_)
  200428. : name (name_)
  200429. {
  200430. }
  200431. InterProcessLock::~InterProcessLock()
  200432. {
  200433. }
  200434. bool InterProcessLock::enter (const int timeOutMillisecs)
  200435. {
  200436. const ScopedLock sl (lock);
  200437. if (pimpl == 0)
  200438. {
  200439. pimpl = new Pimpl (name, timeOutMillisecs);
  200440. if (pimpl->handle == 0)
  200441. pimpl = 0;
  200442. }
  200443. else
  200444. {
  200445. pimpl->refCount++;
  200446. }
  200447. return pimpl != 0;
  200448. }
  200449. void InterProcessLock::exit()
  200450. {
  200451. const ScopedLock sl (lock);
  200452. // Trying to release the lock too many times!
  200453. jassert (pimpl != 0);
  200454. if (pimpl != 0 && --(pimpl->refCount) == 0)
  200455. pimpl = 0;
  200456. }
  200457. #endif
  200458. /*** End of inlined file: juce_win32_Threads.cpp ***/
  200459. /*** Start of inlined file: juce_win32_Files.cpp ***/
  200460. // (This file gets included by juce_win32_NativeCode.cpp, rather than being
  200461. // compiled on its own).
  200462. #if JUCE_INCLUDED_FILE
  200463. #ifndef CSIDL_MYMUSIC
  200464. #define CSIDL_MYMUSIC 0x000d
  200465. #endif
  200466. #ifndef CSIDL_MYVIDEO
  200467. #define CSIDL_MYVIDEO 0x000e
  200468. #endif
  200469. #ifndef INVALID_FILE_ATTRIBUTES
  200470. #define INVALID_FILE_ATTRIBUTES ((DWORD) -1)
  200471. #endif
  200472. const juce_wchar File::separator = '\\';
  200473. const String File::separatorString ("\\");
  200474. bool File::exists() const
  200475. {
  200476. return fullPath.isNotEmpty()
  200477. && GetFileAttributes (fullPath) != INVALID_FILE_ATTRIBUTES;
  200478. }
  200479. bool File::existsAsFile() const
  200480. {
  200481. return fullPath.isNotEmpty()
  200482. && (GetFileAttributes (fullPath) & FILE_ATTRIBUTE_DIRECTORY) == 0;
  200483. }
  200484. bool File::isDirectory() const
  200485. {
  200486. const DWORD attr = GetFileAttributes (fullPath);
  200487. return ((attr & FILE_ATTRIBUTE_DIRECTORY) != 0) && (attr != INVALID_FILE_ATTRIBUTES);
  200488. }
  200489. bool File::hasWriteAccess() const
  200490. {
  200491. if (exists())
  200492. return (GetFileAttributes (fullPath) & FILE_ATTRIBUTE_READONLY) == 0;
  200493. // on windows, it seems that even read-only directories can still be written into,
  200494. // so checking the parent directory's permissions would return the wrong result..
  200495. return true;
  200496. }
  200497. bool File::setFileReadOnlyInternal (const bool shouldBeReadOnly) const
  200498. {
  200499. DWORD attr = GetFileAttributes (fullPath);
  200500. if (attr == INVALID_FILE_ATTRIBUTES)
  200501. return false;
  200502. if (shouldBeReadOnly == ((attr & FILE_ATTRIBUTE_READONLY) != 0))
  200503. return true;
  200504. if (shouldBeReadOnly)
  200505. attr |= FILE_ATTRIBUTE_READONLY;
  200506. else
  200507. attr &= ~FILE_ATTRIBUTE_READONLY;
  200508. return SetFileAttributes (fullPath, attr) != FALSE;
  200509. }
  200510. bool File::isHidden() const
  200511. {
  200512. return (GetFileAttributes (getFullPathName()) & FILE_ATTRIBUTE_HIDDEN) != 0;
  200513. }
  200514. bool File::deleteFile() const
  200515. {
  200516. if (! exists())
  200517. return true;
  200518. else if (isDirectory())
  200519. return RemoveDirectory (fullPath) != 0;
  200520. else
  200521. return DeleteFile (fullPath) != 0;
  200522. }
  200523. bool File::moveToTrash() const
  200524. {
  200525. if (! exists())
  200526. return true;
  200527. SHFILEOPSTRUCT fos;
  200528. zerostruct (fos);
  200529. // The string we pass in must be double null terminated..
  200530. String doubleNullTermPath (getFullPathName() + " ");
  200531. TCHAR* const p = const_cast <TCHAR*> (static_cast <const TCHAR*> (doubleNullTermPath));
  200532. p [getFullPathName().length()] = 0;
  200533. fos.wFunc = FO_DELETE;
  200534. fos.pFrom = p;
  200535. fos.fFlags = FOF_ALLOWUNDO | FOF_NOERRORUI | FOF_SILENT | FOF_NOCONFIRMATION
  200536. | FOF_NOCONFIRMMKDIR | FOF_RENAMEONCOLLISION;
  200537. return SHFileOperation (&fos) == 0;
  200538. }
  200539. bool File::copyInternal (const File& dest) const
  200540. {
  200541. return CopyFile (fullPath, dest.getFullPathName(), false) != 0;
  200542. }
  200543. bool File::moveInternal (const File& dest) const
  200544. {
  200545. return MoveFile (fullPath, dest.getFullPathName()) != 0;
  200546. }
  200547. void File::createDirectoryInternal (const String& fileName) const
  200548. {
  200549. CreateDirectory (fileName, 0);
  200550. }
  200551. // return 0 if not possible
  200552. void* juce_fileOpen (const File& file, bool forWriting)
  200553. {
  200554. HANDLE h;
  200555. if (forWriting)
  200556. {
  200557. h = CreateFile (file.getFullPathName(), GENERIC_WRITE, FILE_SHARE_READ, 0,
  200558. OPEN_ALWAYS, FILE_ATTRIBUTE_NORMAL, 0);
  200559. if (h != INVALID_HANDLE_VALUE)
  200560. SetFilePointer (h, 0, 0, FILE_END);
  200561. else
  200562. h = 0;
  200563. }
  200564. else
  200565. {
  200566. h = CreateFile (file.getFullPathName(), GENERIC_READ, FILE_SHARE_READ | FILE_SHARE_WRITE, 0,
  200567. OPEN_EXISTING, FILE_ATTRIBUTE_NORMAL | FILE_FLAG_SEQUENTIAL_SCAN, 0);
  200568. if (h == INVALID_HANDLE_VALUE)
  200569. h = 0;
  200570. }
  200571. return h;
  200572. }
  200573. void juce_fileClose (void* handle)
  200574. {
  200575. CloseHandle (handle);
  200576. }
  200577. int juce_fileRead (void* handle, void* buffer, int size)
  200578. {
  200579. DWORD num = 0;
  200580. ReadFile ((HANDLE) handle, buffer, size, &num, 0);
  200581. return (int) num;
  200582. }
  200583. int juce_fileWrite (void* handle, const void* buffer, int size)
  200584. {
  200585. DWORD num;
  200586. WriteFile ((HANDLE) handle, buffer, size, &num, 0);
  200587. return (int) num;
  200588. }
  200589. int64 juce_fileSetPosition (void* handle, int64 pos)
  200590. {
  200591. LARGE_INTEGER li;
  200592. li.QuadPart = pos;
  200593. li.LowPart = SetFilePointer ((HANDLE) handle, li.LowPart, &li.HighPart, FILE_BEGIN); // (returns -1 if it fails)
  200594. return li.QuadPart;
  200595. }
  200596. int64 FileOutputStream::getPositionInternal() const
  200597. {
  200598. if (fileHandle == 0)
  200599. return -1;
  200600. LARGE_INTEGER li;
  200601. li.QuadPart = 0;
  200602. li.LowPart = SetFilePointer ((HANDLE) fileHandle, 0, &li.HighPart, FILE_CURRENT); // (returns -1 if it fails)
  200603. return jmax ((int64) 0, li.QuadPart);
  200604. }
  200605. void FileOutputStream::flushInternal()
  200606. {
  200607. if (fileHandle != 0)
  200608. FlushFileBuffers ((HANDLE) fileHandle);
  200609. }
  200610. int64 File::getSize() const
  200611. {
  200612. WIN32_FILE_ATTRIBUTE_DATA attributes;
  200613. if (GetFileAttributesEx (fullPath, GetFileExInfoStandard, &attributes))
  200614. return (((int64) attributes.nFileSizeHigh) << 32) | attributes.nFileSizeLow;
  200615. return 0;
  200616. }
  200617. static int64 fileTimeToTime (const FILETIME* const ft)
  200618. {
  200619. static_jassert (sizeof (ULARGE_INTEGER) == sizeof (FILETIME)); // tell me if this fails!
  200620. return (reinterpret_cast<const ULARGE_INTEGER*> (ft)->QuadPart - literal64bit (116444736000000000)) / 10000;
  200621. }
  200622. static void timeToFileTime (const int64 time, FILETIME* const ft)
  200623. {
  200624. reinterpret_cast<ULARGE_INTEGER*> (ft)->QuadPart = time * 10000 + literal64bit (116444736000000000);
  200625. }
  200626. void File::getFileTimesInternal (int64& modificationTime, int64& accessTime, int64& creationTime) const
  200627. {
  200628. WIN32_FILE_ATTRIBUTE_DATA attributes;
  200629. if (GetFileAttributesEx (fullPath, GetFileExInfoStandard, &attributes))
  200630. {
  200631. modificationTime = fileTimeToTime (&attributes.ftLastWriteTime);
  200632. creationTime = fileTimeToTime (&attributes.ftCreationTime);
  200633. accessTime = fileTimeToTime (&attributes.ftLastAccessTime);
  200634. }
  200635. else
  200636. {
  200637. creationTime = accessTime = modificationTime = 0;
  200638. }
  200639. }
  200640. bool File::setFileTimesInternal (int64 modificationTime, int64 accessTime, int64 creationTime) const
  200641. {
  200642. void* const h = juce_fileOpen (fullPath, true);
  200643. bool ok = false;
  200644. if (h != 0)
  200645. {
  200646. FILETIME m, a, c;
  200647. timeToFileTime (modificationTime, &m);
  200648. timeToFileTime (accessTime, &a);
  200649. timeToFileTime (creationTime, &c);
  200650. ok = SetFileTime ((HANDLE) h,
  200651. creationTime > 0 ? &c : 0,
  200652. accessTime > 0 ? &a : 0,
  200653. modificationTime > 0 ? &m : 0) != 0;
  200654. juce_fileClose (h);
  200655. }
  200656. return ok;
  200657. }
  200658. void File::findFileSystemRoots (Array<File>& destArray)
  200659. {
  200660. TCHAR buffer [2048];
  200661. buffer[0] = 0;
  200662. buffer[1] = 0;
  200663. GetLogicalDriveStrings (2048, buffer);
  200664. const TCHAR* n = buffer;
  200665. StringArray roots;
  200666. while (*n != 0)
  200667. {
  200668. roots.add (String (n));
  200669. while (*n++ != 0)
  200670. {}
  200671. }
  200672. roots.sort (true);
  200673. for (int i = 0; i < roots.size(); ++i)
  200674. destArray.add (roots [i]);
  200675. }
  200676. static const String getDriveFromPath (const String& path)
  200677. {
  200678. if (path.isNotEmpty() && path[1] == ':')
  200679. return path.substring (0, 2) + '\\';
  200680. return path;
  200681. }
  200682. const String File::getVolumeLabel() const
  200683. {
  200684. TCHAR dest[64];
  200685. if (! GetVolumeInformation (getDriveFromPath (getFullPathName()), dest,
  200686. numElementsInArray (dest), 0, 0, 0, 0, 0))
  200687. dest[0] = 0;
  200688. return dest;
  200689. }
  200690. int File::getVolumeSerialNumber() const
  200691. {
  200692. TCHAR dest[64];
  200693. DWORD serialNum;
  200694. if (! GetVolumeInformation (getDriveFromPath (getFullPathName()), dest,
  200695. numElementsInArray (dest), &serialNum, 0, 0, 0, 0))
  200696. return 0;
  200697. return (int) serialNum;
  200698. }
  200699. static int64 getDiskSpaceInfo (const String& path, const bool total)
  200700. {
  200701. ULARGE_INTEGER spc, tot, totFree;
  200702. if (GetDiskFreeSpaceEx (getDriveFromPath (path), &spc, &tot, &totFree))
  200703. return total ? (int64) tot.QuadPart
  200704. : (int64) spc.QuadPart;
  200705. return 0;
  200706. }
  200707. int64 File::getBytesFreeOnVolume() const
  200708. {
  200709. return getDiskSpaceInfo (getFullPathName(), false);
  200710. }
  200711. int64 File::getVolumeTotalSize() const
  200712. {
  200713. return getDiskSpaceInfo (getFullPathName(), true);
  200714. }
  200715. static unsigned int getWindowsDriveType (const String& path)
  200716. {
  200717. return GetDriveType (getDriveFromPath (path));
  200718. }
  200719. bool File::isOnCDRomDrive() const
  200720. {
  200721. return getWindowsDriveType (getFullPathName()) == DRIVE_CDROM;
  200722. }
  200723. bool File::isOnHardDisk() const
  200724. {
  200725. if (fullPath.isEmpty())
  200726. return false;
  200727. const unsigned int n = getWindowsDriveType (getFullPathName());
  200728. if (fullPath.toLowerCase()[0] <= 'b' && fullPath[1] == ':')
  200729. return n != DRIVE_REMOVABLE;
  200730. else
  200731. return n != DRIVE_CDROM && n != DRIVE_REMOTE;
  200732. }
  200733. bool File::isOnRemovableDrive() const
  200734. {
  200735. if (fullPath.isEmpty())
  200736. return false;
  200737. const unsigned int n = getWindowsDriveType (getFullPathName());
  200738. return n == DRIVE_CDROM
  200739. || n == DRIVE_REMOTE
  200740. || n == DRIVE_REMOVABLE
  200741. || n == DRIVE_RAMDISK;
  200742. }
  200743. static const File juce_getSpecialFolderPath (int type)
  200744. {
  200745. WCHAR path [MAX_PATH + 256];
  200746. if (SHGetSpecialFolderPath (0, path, type, FALSE))
  200747. return File (String (path));
  200748. return File::nonexistent;
  200749. }
  200750. const File JUCE_CALLTYPE File::getSpecialLocation (const SpecialLocationType type)
  200751. {
  200752. int csidlType = 0;
  200753. switch (type)
  200754. {
  200755. case userHomeDirectory: csidlType = CSIDL_PROFILE; break;
  200756. case userDocumentsDirectory: csidlType = CSIDL_PERSONAL; break;
  200757. case userDesktopDirectory: csidlType = CSIDL_DESKTOP; break;
  200758. case userApplicationDataDirectory: csidlType = CSIDL_APPDATA; break;
  200759. case commonApplicationDataDirectory: csidlType = CSIDL_COMMON_APPDATA; break;
  200760. case globalApplicationsDirectory: csidlType = CSIDL_PROGRAM_FILES; break;
  200761. case userMusicDirectory: csidlType = CSIDL_MYMUSIC; break;
  200762. case userMoviesDirectory: csidlType = CSIDL_MYVIDEO; break;
  200763. case tempDirectory:
  200764. {
  200765. WCHAR dest [2048];
  200766. dest[0] = 0;
  200767. GetTempPath (numElementsInArray (dest), dest);
  200768. return File (String (dest));
  200769. }
  200770. case invokedExecutableFile:
  200771. case currentExecutableFile:
  200772. case currentApplicationFile:
  200773. {
  200774. HINSTANCE moduleHandle = (HINSTANCE) PlatformUtilities::getCurrentModuleInstanceHandle();
  200775. WCHAR dest [MAX_PATH + 256];
  200776. dest[0] = 0;
  200777. GetModuleFileName (moduleHandle, dest, numElementsInArray (dest));
  200778. return File (String (dest));
  200779. }
  200780. break;
  200781. default:
  200782. jassertfalse // unknown type?
  200783. return File::nonexistent;
  200784. }
  200785. return juce_getSpecialFolderPath (csidlType);
  200786. }
  200787. const File File::getCurrentWorkingDirectory()
  200788. {
  200789. WCHAR dest [MAX_PATH + 256];
  200790. dest[0] = 0;
  200791. GetCurrentDirectory (numElementsInArray (dest), dest);
  200792. return File (String (dest));
  200793. }
  200794. bool File::setAsCurrentWorkingDirectory() const
  200795. {
  200796. return SetCurrentDirectory (getFullPathName()) != FALSE;
  200797. }
  200798. const String File::getVersion() const
  200799. {
  200800. String result;
  200801. DWORD handle = 0;
  200802. DWORD bufferSize = GetFileVersionInfoSize (getFullPathName(), &handle);
  200803. HeapBlock<char> buffer;
  200804. buffer.calloc (bufferSize);
  200805. if (GetFileVersionInfo (getFullPathName(), 0, bufferSize, buffer))
  200806. {
  200807. VS_FIXEDFILEINFO* vffi;
  200808. UINT len = 0;
  200809. if (VerQueryValue (buffer, (LPTSTR) _T("\\"), (LPVOID*) &vffi, &len))
  200810. {
  200811. result << (int) HIWORD (vffi->dwFileVersionMS) << '.'
  200812. << (int) LOWORD (vffi->dwFileVersionMS) << '.'
  200813. << (int) HIWORD (vffi->dwFileVersionLS) << '.'
  200814. << (int) LOWORD (vffi->dwFileVersionLS);
  200815. }
  200816. }
  200817. return result;
  200818. }
  200819. const File File::getLinkedTarget() const
  200820. {
  200821. File result (*this);
  200822. String p (getFullPathName());
  200823. if (! exists())
  200824. p += ".lnk";
  200825. else if (getFileExtension() != ".lnk")
  200826. return result;
  200827. ComSmartPtr <IShellLink> shellLink;
  200828. if (SUCCEEDED (shellLink.CoCreateInstance (CLSID_ShellLink)))
  200829. {
  200830. ComSmartPtr <IPersistFile> persistFile;
  200831. if (SUCCEEDED (shellLink->QueryInterface (IID_IPersistFile, (LPVOID*) &persistFile)))
  200832. {
  200833. if (SUCCEEDED (persistFile->Load ((const WCHAR*) p, STGM_READ))
  200834. && SUCCEEDED (shellLink->Resolve (0, SLR_ANY_MATCH | SLR_NO_UI)))
  200835. {
  200836. WIN32_FIND_DATA winFindData;
  200837. WCHAR resolvedPath [MAX_PATH];
  200838. if (SUCCEEDED (shellLink->GetPath (resolvedPath, MAX_PATH, &winFindData, SLGP_UNCPRIORITY)))
  200839. result = File (resolvedPath);
  200840. }
  200841. }
  200842. }
  200843. return result;
  200844. }
  200845. class DirectoryIterator::NativeIterator::Pimpl
  200846. {
  200847. public:
  200848. Pimpl (const File& directory, const String& wildCard)
  200849. : directoryWithWildCard (File::addTrailingSeparator (directory.getFullPathName()) + wildCard),
  200850. handle (INVALID_HANDLE_VALUE)
  200851. {
  200852. }
  200853. ~Pimpl()
  200854. {
  200855. if (handle != INVALID_HANDLE_VALUE)
  200856. FindClose (handle);
  200857. }
  200858. bool next (String& filenameFound,
  200859. bool* const isDir, bool* const isHidden, int64* const fileSize,
  200860. Time* const modTime, Time* const creationTime, bool* const isReadOnly)
  200861. {
  200862. WIN32_FIND_DATA findData;
  200863. if (handle == INVALID_HANDLE_VALUE)
  200864. {
  200865. handle = FindFirstFile (directoryWithWildCard, &findData);
  200866. if (handle == INVALID_HANDLE_VALUE)
  200867. return false;
  200868. }
  200869. else
  200870. {
  200871. if (FindNextFile (handle, &findData) == 0)
  200872. return false;
  200873. }
  200874. filenameFound = findData.cFileName;
  200875. if (isDir != 0) *isDir = ((findData.dwFileAttributes & FILE_ATTRIBUTE_DIRECTORY) != 0);
  200876. if (isHidden != 0) *isHidden = ((findData.dwFileAttributes & FILE_ATTRIBUTE_HIDDEN) != 0);
  200877. if (fileSize != 0) *fileSize = findData.nFileSizeLow + (((int64) findData.nFileSizeHigh) << 32);
  200878. if (modTime != 0) *modTime = fileTimeToTime (&findData.ftLastWriteTime);
  200879. if (creationTime != 0) *creationTime = fileTimeToTime (&findData.ftCreationTime);
  200880. if (isReadOnly != 0) *isReadOnly = ((findData.dwFileAttributes & FILE_ATTRIBUTE_READONLY) != 0);
  200881. return true;
  200882. }
  200883. juce_UseDebuggingNewOperator
  200884. private:
  200885. const String directoryWithWildCard;
  200886. HANDLE handle;
  200887. Pimpl (const Pimpl&);
  200888. Pimpl& operator= (const Pimpl&);
  200889. };
  200890. DirectoryIterator::NativeIterator::NativeIterator (const File& directory, const String& wildCard)
  200891. : pimpl (new DirectoryIterator::NativeIterator::Pimpl (directory, wildCard))
  200892. {
  200893. }
  200894. DirectoryIterator::NativeIterator::~NativeIterator()
  200895. {
  200896. }
  200897. bool DirectoryIterator::NativeIterator::next (String& filenameFound,
  200898. bool* const isDir, bool* const isHidden, int64* const fileSize,
  200899. Time* const modTime, Time* const creationTime, bool* const isReadOnly)
  200900. {
  200901. return pimpl->next (filenameFound, isDir, isHidden, fileSize, modTime, creationTime, isReadOnly);
  200902. }
  200903. bool PlatformUtilities::openDocument (const String& fileName, const String& parameters)
  200904. {
  200905. HINSTANCE hInstance = 0;
  200906. JUCE_TRY
  200907. {
  200908. hInstance = ShellExecute (0, 0, fileName, parameters, 0, SW_SHOWDEFAULT);
  200909. }
  200910. JUCE_CATCH_ALL
  200911. return hInstance > (HINSTANCE) 32;
  200912. }
  200913. void File::revealToUser() const
  200914. {
  200915. if (isDirectory())
  200916. startAsProcess();
  200917. else if (getParentDirectory().exists())
  200918. getParentDirectory().startAsProcess();
  200919. }
  200920. class NamedPipeInternal
  200921. {
  200922. public:
  200923. NamedPipeInternal (const String& file, const bool isPipe_)
  200924. : pipeH (0),
  200925. cancelEvent (0),
  200926. connected (false),
  200927. isPipe (isPipe_)
  200928. {
  200929. cancelEvent = CreateEvent (0, FALSE, FALSE, 0);
  200930. pipeH = isPipe ? CreateNamedPipe (file, PIPE_ACCESS_DUPLEX | FILE_FLAG_OVERLAPPED, 0,
  200931. PIPE_UNLIMITED_INSTANCES, 4096, 4096, 0, 0)
  200932. : CreateFile (file, GENERIC_READ | GENERIC_WRITE, 0, 0,
  200933. OPEN_EXISTING, FILE_FLAG_OVERLAPPED, 0);
  200934. }
  200935. ~NamedPipeInternal()
  200936. {
  200937. disconnectPipe();
  200938. if (pipeH != 0)
  200939. CloseHandle (pipeH);
  200940. CloseHandle (cancelEvent);
  200941. }
  200942. bool connect (const int timeOutMs)
  200943. {
  200944. if (! isPipe)
  200945. return true;
  200946. if (! connected)
  200947. {
  200948. OVERLAPPED over;
  200949. zerostruct (over);
  200950. over.hEvent = CreateEvent (0, TRUE, FALSE, 0);
  200951. if (ConnectNamedPipe (pipeH, &over))
  200952. {
  200953. connected = false; // yes, you read that right. In overlapped mode it should always return 0.
  200954. }
  200955. else
  200956. {
  200957. const int err = GetLastError();
  200958. if (err == ERROR_IO_PENDING || err == ERROR_PIPE_LISTENING)
  200959. {
  200960. HANDLE handles[] = { over.hEvent, cancelEvent };
  200961. if (WaitForMultipleObjects (2, handles, FALSE,
  200962. timeOutMs >= 0 ? timeOutMs : INFINITE) == WAIT_OBJECT_0)
  200963. connected = true;
  200964. }
  200965. else if (err == ERROR_PIPE_CONNECTED)
  200966. {
  200967. connected = true;
  200968. }
  200969. }
  200970. CloseHandle (over.hEvent);
  200971. }
  200972. return connected;
  200973. }
  200974. void disconnectPipe()
  200975. {
  200976. if (connected)
  200977. {
  200978. DisconnectNamedPipe (pipeH);
  200979. connected = false;
  200980. }
  200981. }
  200982. HANDLE pipeH;
  200983. HANDLE cancelEvent;
  200984. bool connected, isPipe;
  200985. };
  200986. void NamedPipe::close()
  200987. {
  200988. cancelPendingReads();
  200989. const ScopedLock sl (lock);
  200990. delete static_cast<NamedPipeInternal*> (internal);
  200991. internal = 0;
  200992. }
  200993. bool NamedPipe::openInternal (const String& pipeName, const bool createPipe)
  200994. {
  200995. close();
  200996. ScopedPointer<NamedPipeInternal> intern (new NamedPipeInternal ("\\\\.\\pipe\\" + pipeName, createPipe));
  200997. if (intern->pipeH != INVALID_HANDLE_VALUE)
  200998. {
  200999. internal = intern.release();
  201000. return true;
  201001. }
  201002. return false;
  201003. }
  201004. int NamedPipe::read (void* destBuffer, int maxBytesToRead, int timeOutMilliseconds)
  201005. {
  201006. const ScopedLock sl (lock);
  201007. int bytesRead = -1;
  201008. bool waitAgain = true;
  201009. while (waitAgain && internal != 0)
  201010. {
  201011. NamedPipeInternal* const intern = static_cast<NamedPipeInternal*> (internal);
  201012. waitAgain = false;
  201013. if (! intern->connect (timeOutMilliseconds))
  201014. break;
  201015. if (maxBytesToRead <= 0)
  201016. return 0;
  201017. OVERLAPPED over;
  201018. zerostruct (over);
  201019. over.hEvent = CreateEvent (0, TRUE, FALSE, 0);
  201020. unsigned long numRead;
  201021. if (ReadFile (intern->pipeH, destBuffer, maxBytesToRead, &numRead, &over))
  201022. {
  201023. bytesRead = (int) numRead;
  201024. }
  201025. else if (GetLastError() == ERROR_IO_PENDING)
  201026. {
  201027. HANDLE handles[] = { over.hEvent, intern->cancelEvent };
  201028. DWORD waitResult = WaitForMultipleObjects (2, handles, FALSE,
  201029. timeOutMilliseconds >= 0 ? timeOutMilliseconds
  201030. : INFINITE);
  201031. if (waitResult != WAIT_OBJECT_0)
  201032. {
  201033. // if the operation timed out, let's cancel it...
  201034. CancelIo (intern->pipeH);
  201035. WaitForSingleObject (over.hEvent, INFINITE); // makes sure cancel is complete
  201036. }
  201037. if (GetOverlappedResult (intern->pipeH, &over, &numRead, FALSE))
  201038. {
  201039. bytesRead = (int) numRead;
  201040. }
  201041. else if (GetLastError() == ERROR_BROKEN_PIPE && intern->isPipe)
  201042. {
  201043. intern->disconnectPipe();
  201044. waitAgain = true;
  201045. }
  201046. }
  201047. else
  201048. {
  201049. waitAgain = internal != 0;
  201050. Sleep (5);
  201051. }
  201052. CloseHandle (over.hEvent);
  201053. }
  201054. return bytesRead;
  201055. }
  201056. int NamedPipe::write (const void* sourceBuffer, int numBytesToWrite, int timeOutMilliseconds)
  201057. {
  201058. int bytesWritten = -1;
  201059. NamedPipeInternal* const intern = static_cast<NamedPipeInternal*> (internal);
  201060. if (intern != 0 && intern->connect (timeOutMilliseconds))
  201061. {
  201062. if (numBytesToWrite <= 0)
  201063. return 0;
  201064. OVERLAPPED over;
  201065. zerostruct (over);
  201066. over.hEvent = CreateEvent (0, TRUE, FALSE, 0);
  201067. unsigned long numWritten;
  201068. if (WriteFile (intern->pipeH, sourceBuffer, numBytesToWrite, &numWritten, &over))
  201069. {
  201070. bytesWritten = (int) numWritten;
  201071. }
  201072. else if (GetLastError() == ERROR_IO_PENDING)
  201073. {
  201074. HANDLE handles[] = { over.hEvent, intern->cancelEvent };
  201075. DWORD waitResult;
  201076. waitResult = WaitForMultipleObjects (2, handles, FALSE,
  201077. timeOutMilliseconds >= 0 ? timeOutMilliseconds
  201078. : INFINITE);
  201079. if (waitResult != WAIT_OBJECT_0)
  201080. {
  201081. CancelIo (intern->pipeH);
  201082. WaitForSingleObject (over.hEvent, INFINITE);
  201083. }
  201084. if (GetOverlappedResult (intern->pipeH, &over, &numWritten, FALSE))
  201085. {
  201086. bytesWritten = (int) numWritten;
  201087. }
  201088. else if (GetLastError() == ERROR_BROKEN_PIPE && intern->isPipe)
  201089. {
  201090. intern->disconnectPipe();
  201091. }
  201092. }
  201093. CloseHandle (over.hEvent);
  201094. }
  201095. return bytesWritten;
  201096. }
  201097. void NamedPipe::cancelPendingReads()
  201098. {
  201099. if (internal != 0)
  201100. SetEvent (static_cast<NamedPipeInternal*> (internal)->cancelEvent);
  201101. }
  201102. #endif
  201103. /*** End of inlined file: juce_win32_Files.cpp ***/
  201104. /*** Start of inlined file: juce_win32_Network.cpp ***/
  201105. // (This file gets included by juce_win32_NativeCode.cpp, rather than being
  201106. // compiled on its own).
  201107. #if JUCE_INCLUDED_FILE
  201108. #ifndef INTERNET_FLAG_NEED_FILE
  201109. #define INTERNET_FLAG_NEED_FILE 0x00000010
  201110. #endif
  201111. #ifndef INTERNET_OPTION_DISABLE_AUTODIAL
  201112. #define INTERNET_OPTION_DISABLE_AUTODIAL 70
  201113. #endif
  201114. struct ConnectionAndRequestStruct
  201115. {
  201116. HINTERNET connection, request;
  201117. };
  201118. static HINTERNET sessionHandle = 0;
  201119. #ifndef WORKAROUND_TIMEOUT_BUG
  201120. //#define WORKAROUND_TIMEOUT_BUG 1
  201121. #endif
  201122. #if WORKAROUND_TIMEOUT_BUG
  201123. // Required because of a Microsoft bug in setting a timeout
  201124. class InternetConnectThread : public Thread
  201125. {
  201126. public:
  201127. InternetConnectThread (URL_COMPONENTS& uc_, HINTERNET& connection_, const bool isFtp_)
  201128. : Thread ("Internet"), uc (uc_), connection (connection_), isFtp (isFtp_)
  201129. {
  201130. startThread();
  201131. }
  201132. ~InternetConnectThread()
  201133. {
  201134. stopThread (60000);
  201135. }
  201136. void run()
  201137. {
  201138. connection = InternetConnect (sessionHandle, uc.lpszHostName,
  201139. uc.nPort, _T(""), _T(""),
  201140. isFtp ? INTERNET_SERVICE_FTP
  201141. : INTERNET_SERVICE_HTTP,
  201142. 0, 0);
  201143. notify();
  201144. }
  201145. juce_UseDebuggingNewOperator
  201146. private:
  201147. URL_COMPONENTS& uc;
  201148. HINTERNET& connection;
  201149. const bool isFtp;
  201150. InternetConnectThread (const InternetConnectThread&);
  201151. InternetConnectThread& operator= (const InternetConnectThread&);
  201152. };
  201153. #endif
  201154. void* juce_openInternetFile (const String& url,
  201155. const String& headers,
  201156. const MemoryBlock& postData,
  201157. const bool isPost,
  201158. URL::OpenStreamProgressCallback* callback,
  201159. void* callbackContext,
  201160. int timeOutMs)
  201161. {
  201162. if (sessionHandle == 0)
  201163. sessionHandle = InternetOpen (_T("juce"),
  201164. INTERNET_OPEN_TYPE_PRECONFIG,
  201165. 0, 0, 0);
  201166. if (sessionHandle != 0)
  201167. {
  201168. // break up the url..
  201169. TCHAR file[1024], server[1024];
  201170. URL_COMPONENTS uc;
  201171. zerostruct (uc);
  201172. uc.dwStructSize = sizeof (uc);
  201173. uc.dwUrlPathLength = sizeof (file);
  201174. uc.dwHostNameLength = sizeof (server);
  201175. uc.lpszUrlPath = file;
  201176. uc.lpszHostName = server;
  201177. if (InternetCrackUrl (url, 0, 0, &uc))
  201178. {
  201179. int disable = 1;
  201180. InternetSetOption (sessionHandle, INTERNET_OPTION_DISABLE_AUTODIAL, &disable, sizeof (disable));
  201181. if (timeOutMs == 0)
  201182. timeOutMs = 30000;
  201183. else if (timeOutMs < 0)
  201184. timeOutMs = -1;
  201185. InternetSetOption (sessionHandle, INTERNET_OPTION_CONNECT_TIMEOUT, &timeOutMs, sizeof (timeOutMs));
  201186. const bool isFtp = url.startsWithIgnoreCase ("ftp:");
  201187. #if WORKAROUND_TIMEOUT_BUG
  201188. HINTERNET connection = 0;
  201189. {
  201190. InternetConnectThread connectThread (uc, connection, isFtp);
  201191. connectThread.wait (timeOutMs);
  201192. if (connection == 0)
  201193. {
  201194. InternetCloseHandle (sessionHandle);
  201195. sessionHandle = 0;
  201196. }
  201197. }
  201198. #else
  201199. HINTERNET connection = InternetConnect (sessionHandle,
  201200. uc.lpszHostName,
  201201. uc.nPort,
  201202. _T(""), _T(""),
  201203. isFtp ? INTERNET_SERVICE_FTP
  201204. : INTERNET_SERVICE_HTTP,
  201205. 0, 0);
  201206. #endif
  201207. if (connection != 0)
  201208. {
  201209. if (isFtp)
  201210. {
  201211. HINTERNET request = FtpOpenFile (connection,
  201212. uc.lpszUrlPath,
  201213. GENERIC_READ,
  201214. FTP_TRANSFER_TYPE_BINARY | INTERNET_FLAG_NEED_FILE,
  201215. 0);
  201216. ConnectionAndRequestStruct* const result = new ConnectionAndRequestStruct();
  201217. result->connection = connection;
  201218. result->request = request;
  201219. return result;
  201220. }
  201221. else
  201222. {
  201223. const TCHAR* mimeTypes[] = { _T("*/*"), 0 };
  201224. DWORD flags = INTERNET_FLAG_RELOAD | INTERNET_FLAG_NO_CACHE_WRITE;
  201225. if (url.startsWithIgnoreCase ("https:"))
  201226. flags |= INTERNET_FLAG_SECURE; // (this flag only seems necessary if the OS is running IE6 -
  201227. // IE7 seems to automatically work out when it's https)
  201228. HINTERNET request = HttpOpenRequest (connection,
  201229. isPost ? _T("POST")
  201230. : _T("GET"),
  201231. uc.lpszUrlPath,
  201232. 0, 0, mimeTypes, flags, 0);
  201233. if (request != 0)
  201234. {
  201235. INTERNET_BUFFERS buffers;
  201236. zerostruct (buffers);
  201237. buffers.dwStructSize = sizeof (INTERNET_BUFFERS);
  201238. buffers.lpcszHeader = (LPCTSTR) headers;
  201239. buffers.dwHeadersLength = headers.length();
  201240. buffers.dwBufferTotal = (DWORD) postData.getSize();
  201241. ConnectionAndRequestStruct* result = 0;
  201242. if (HttpSendRequestEx (request, &buffers, 0, HSR_INITIATE, 0))
  201243. {
  201244. int bytesSent = 0;
  201245. for (;;)
  201246. {
  201247. const int bytesToDo = jmin (1024, (int) postData.getSize() - bytesSent);
  201248. DWORD bytesDone = 0;
  201249. if (bytesToDo > 0
  201250. && ! InternetWriteFile (request,
  201251. static_cast <const char*> (postData.getData()) + bytesSent,
  201252. bytesToDo, &bytesDone))
  201253. {
  201254. break;
  201255. }
  201256. if (bytesToDo == 0 || (int) bytesDone < bytesToDo)
  201257. {
  201258. result = new ConnectionAndRequestStruct();
  201259. result->connection = connection;
  201260. result->request = request;
  201261. HttpEndRequest (request, 0, 0, 0);
  201262. return result;
  201263. }
  201264. bytesSent += bytesDone;
  201265. if (callback != 0 && ! callback (callbackContext, bytesSent, postData.getSize()))
  201266. break;
  201267. }
  201268. }
  201269. InternetCloseHandle (request);
  201270. }
  201271. InternetCloseHandle (connection);
  201272. }
  201273. }
  201274. }
  201275. }
  201276. return 0;
  201277. }
  201278. int juce_readFromInternetFile (void* handle, void* buffer, int bytesToRead)
  201279. {
  201280. DWORD bytesRead = 0;
  201281. const ConnectionAndRequestStruct* const crs = static_cast <ConnectionAndRequestStruct*> (handle);
  201282. if (crs != 0)
  201283. InternetReadFile (crs->request,
  201284. buffer, bytesToRead,
  201285. &bytesRead);
  201286. return bytesRead;
  201287. }
  201288. int juce_seekInInternetFile (void* handle, int newPosition)
  201289. {
  201290. if (handle != 0)
  201291. {
  201292. const ConnectionAndRequestStruct* const crs = static_cast <ConnectionAndRequestStruct*> (handle);
  201293. return InternetSetFilePointer (crs->request, newPosition, 0, FILE_BEGIN, 0);
  201294. }
  201295. return -1;
  201296. }
  201297. int64 juce_getInternetFileContentLength (void* handle)
  201298. {
  201299. const ConnectionAndRequestStruct* const crs = static_cast <ConnectionAndRequestStruct*> (handle);
  201300. if (crs != 0)
  201301. {
  201302. DWORD index = 0, result = 0, size = sizeof (result);
  201303. if (HttpQueryInfo (crs->request, HTTP_QUERY_CONTENT_LENGTH | HTTP_QUERY_FLAG_NUMBER,
  201304. &result, &size, &index))
  201305. {
  201306. return (int64) result;
  201307. }
  201308. }
  201309. return -1;
  201310. }
  201311. void juce_closeInternetFile (void* handle)
  201312. {
  201313. if (handle != 0)
  201314. {
  201315. ScopedPointer <ConnectionAndRequestStruct> crs (static_cast <ConnectionAndRequestStruct*> (handle));
  201316. InternetCloseHandle (crs->request);
  201317. InternetCloseHandle (crs->connection);
  201318. }
  201319. }
  201320. static int getMACAddressViaGetAdaptersInfo (int64* addresses, int maxNum, const bool littleEndian) throw()
  201321. {
  201322. int numFound = 0;
  201323. DynamicLibraryLoader dll ("iphlpapi.dll");
  201324. DynamicLibraryImport (GetAdaptersInfo, getAdaptersInfo, DWORD, dll, (PIP_ADAPTER_INFO, PULONG))
  201325. if (getAdaptersInfo != 0)
  201326. {
  201327. ULONG len = sizeof (IP_ADAPTER_INFO);
  201328. MemoryBlock mb;
  201329. PIP_ADAPTER_INFO adapterInfo = (PIP_ADAPTER_INFO) mb.getData();
  201330. if (getAdaptersInfo (adapterInfo, &len) == ERROR_BUFFER_OVERFLOW)
  201331. {
  201332. mb.setSize (len);
  201333. adapterInfo = (PIP_ADAPTER_INFO) mb.getData();
  201334. }
  201335. if (getAdaptersInfo (adapterInfo, &len) == NO_ERROR)
  201336. {
  201337. PIP_ADAPTER_INFO adapter = adapterInfo;
  201338. while (adapter != 0)
  201339. {
  201340. int64 mac = 0;
  201341. for (unsigned int i = 0; i < adapter->AddressLength; ++i)
  201342. mac = (mac << 8) | adapter->Address[i];
  201343. if (littleEndian)
  201344. mac = (int64) ByteOrder::swap ((uint64) mac);
  201345. if (numFound < maxNum && mac != 0)
  201346. addresses [numFound++] = mac;
  201347. adapter = adapter->Next;
  201348. }
  201349. }
  201350. }
  201351. return numFound;
  201352. }
  201353. static int getMACAddressesViaNetBios (int64* addresses, int maxNum, const bool littleEndian) throw()
  201354. {
  201355. int numFound = 0;
  201356. DynamicLibraryLoader dll ("netapi32.dll");
  201357. DynamicLibraryImport (Netbios, NetbiosCall, UCHAR, dll, (PNCB))
  201358. if (NetbiosCall != 0)
  201359. {
  201360. NCB ncb;
  201361. zerostruct (ncb);
  201362. struct ASTAT
  201363. {
  201364. ADAPTER_STATUS adapt;
  201365. NAME_BUFFER NameBuff [30];
  201366. };
  201367. ASTAT astat;
  201368. zeromem (&astat, sizeof (astat)); // (can't use zerostruct here in VC6)
  201369. LANA_ENUM enums;
  201370. zerostruct (enums);
  201371. ncb.ncb_command = NCBENUM;
  201372. ncb.ncb_buffer = (unsigned char*) &enums;
  201373. ncb.ncb_length = sizeof (LANA_ENUM);
  201374. NetbiosCall (&ncb);
  201375. for (int i = 0; i < enums.length; ++i)
  201376. {
  201377. zerostruct (ncb);
  201378. ncb.ncb_command = NCBRESET;
  201379. ncb.ncb_lana_num = enums.lana[i];
  201380. if (NetbiosCall (&ncb) == 0)
  201381. {
  201382. zerostruct (ncb);
  201383. memcpy (ncb.ncb_callname, "* ", NCBNAMSZ);
  201384. ncb.ncb_command = NCBASTAT;
  201385. ncb.ncb_lana_num = enums.lana[i];
  201386. ncb.ncb_buffer = (unsigned char*) &astat;
  201387. ncb.ncb_length = sizeof (ASTAT);
  201388. if (NetbiosCall (&ncb) == 0)
  201389. {
  201390. if (astat.adapt.adapter_type == 0xfe)
  201391. {
  201392. uint64 mac = 0;
  201393. for (int i = 6; --i >= 0;)
  201394. mac = (mac << 8) | astat.adapt.adapter_address [littleEndian ? i : (5 - i)];
  201395. if (numFound < maxNum && mac != 0)
  201396. addresses [numFound++] = mac;
  201397. }
  201398. }
  201399. }
  201400. }
  201401. }
  201402. return numFound;
  201403. }
  201404. int SystemStats::getMACAddresses (int64* addresses, int maxNum, const bool littleEndian)
  201405. {
  201406. int numFound = getMACAddressViaGetAdaptersInfo (addresses, maxNum, littleEndian);
  201407. if (numFound == 0)
  201408. numFound = getMACAddressesViaNetBios (addresses, maxNum, littleEndian);
  201409. return numFound;
  201410. }
  201411. bool PlatformUtilities::launchEmailWithAttachments (const String& targetEmailAddress,
  201412. const String& emailSubject,
  201413. const String& bodyText,
  201414. const StringArray& filesToAttach)
  201415. {
  201416. HMODULE h = LoadLibraryA ("MAPI32.dll");
  201417. typedef ULONG (WINAPI *MAPISendMailType) (LHANDLE, ULONG, lpMapiMessage, ::FLAGS, ULONG);
  201418. MAPISendMailType mapiSendMail = (MAPISendMailType) GetProcAddress (h, "MAPISendMail");
  201419. bool ok = false;
  201420. if (mapiSendMail != 0)
  201421. {
  201422. MapiMessage message;
  201423. zerostruct (message);
  201424. message.lpszSubject = (LPSTR) emailSubject.toCString();
  201425. message.lpszNoteText = (LPSTR) bodyText.toCString();
  201426. MapiRecipDesc recip;
  201427. zerostruct (recip);
  201428. recip.ulRecipClass = MAPI_TO;
  201429. String targetEmailAddress_ (targetEmailAddress);
  201430. if (targetEmailAddress_.isEmpty())
  201431. targetEmailAddress_ = " "; // (Windows Mail can't deal with a blank address)
  201432. recip.lpszName = (LPSTR) targetEmailAddress_.toCString();
  201433. message.nRecipCount = 1;
  201434. message.lpRecips = &recip;
  201435. HeapBlock <MapiFileDesc> files;
  201436. files.calloc (filesToAttach.size());
  201437. message.nFileCount = filesToAttach.size();
  201438. message.lpFiles = files;
  201439. for (int i = 0; i < filesToAttach.size(); ++i)
  201440. {
  201441. files[i].nPosition = (ULONG) -1;
  201442. files[i].lpszPathName = (LPSTR) filesToAttach[i].toCString();
  201443. }
  201444. ok = (mapiSendMail (0, 0, &message, MAPI_DIALOG | MAPI_LOGON_UI, 0) == SUCCESS_SUCCESS);
  201445. }
  201446. FreeLibrary (h);
  201447. return ok;
  201448. }
  201449. #endif
  201450. /*** End of inlined file: juce_win32_Network.cpp ***/
  201451. /*** Start of inlined file: juce_win32_PlatformUtils.cpp ***/
  201452. // (This file gets included by juce_win32_NativeCode.cpp, rather than being
  201453. // compiled on its own).
  201454. #if JUCE_INCLUDED_FILE
  201455. static HKEY findKeyForPath (String name,
  201456. const bool createForWriting,
  201457. String& valueName)
  201458. {
  201459. HKEY rootKey = 0;
  201460. if (name.startsWithIgnoreCase ("HKEY_CURRENT_USER\\"))
  201461. rootKey = HKEY_CURRENT_USER;
  201462. else if (name.startsWithIgnoreCase ("HKEY_LOCAL_MACHINE\\"))
  201463. rootKey = HKEY_LOCAL_MACHINE;
  201464. else if (name.startsWithIgnoreCase ("HKEY_CLASSES_ROOT\\"))
  201465. rootKey = HKEY_CLASSES_ROOT;
  201466. if (rootKey != 0)
  201467. {
  201468. name = name.substring (name.indexOfChar ('\\') + 1);
  201469. const int lastSlash = name.lastIndexOfChar ('\\');
  201470. valueName = name.substring (lastSlash + 1);
  201471. name = name.substring (0, lastSlash);
  201472. HKEY key;
  201473. DWORD result;
  201474. if (createForWriting)
  201475. {
  201476. if (RegCreateKeyEx (rootKey, name, 0, 0, REG_OPTION_NON_VOLATILE,
  201477. (KEY_WRITE | KEY_QUERY_VALUE), 0, &key, &result) == ERROR_SUCCESS)
  201478. return key;
  201479. }
  201480. else
  201481. {
  201482. if (RegOpenKeyEx (rootKey, name, 0, KEY_READ, &key) == ERROR_SUCCESS)
  201483. return key;
  201484. }
  201485. }
  201486. return 0;
  201487. }
  201488. const String PlatformUtilities::getRegistryValue (const String& regValuePath,
  201489. const String& defaultValue)
  201490. {
  201491. String valueName, result (defaultValue);
  201492. HKEY k = findKeyForPath (regValuePath, false, valueName);
  201493. if (k != 0)
  201494. {
  201495. WCHAR buffer [2048];
  201496. unsigned long bufferSize = sizeof (buffer);
  201497. DWORD type = REG_SZ;
  201498. if (RegQueryValueEx (k, valueName, 0, &type, (LPBYTE) buffer, &bufferSize) == ERROR_SUCCESS)
  201499. {
  201500. if (type == REG_SZ)
  201501. result = buffer;
  201502. else if (type == REG_DWORD)
  201503. result = String ((int) *(DWORD*) buffer);
  201504. }
  201505. RegCloseKey (k);
  201506. }
  201507. return result;
  201508. }
  201509. void PlatformUtilities::setRegistryValue (const String& regValuePath,
  201510. const String& value)
  201511. {
  201512. String valueName;
  201513. HKEY k = findKeyForPath (regValuePath, true, valueName);
  201514. if (k != 0)
  201515. {
  201516. RegSetValueEx (k, valueName, 0, REG_SZ,
  201517. (const BYTE*) (const WCHAR*) value,
  201518. sizeof (WCHAR) * (value.length() + 1));
  201519. RegCloseKey (k);
  201520. }
  201521. }
  201522. bool PlatformUtilities::registryValueExists (const String& regValuePath)
  201523. {
  201524. bool exists = false;
  201525. String valueName;
  201526. HKEY k = findKeyForPath (regValuePath, false, valueName);
  201527. if (k != 0)
  201528. {
  201529. unsigned char buffer [2048];
  201530. unsigned long bufferSize = sizeof (buffer);
  201531. DWORD type = 0;
  201532. if (RegQueryValueEx (k, valueName, 0, &type, buffer, &bufferSize) == ERROR_SUCCESS)
  201533. exists = true;
  201534. RegCloseKey (k);
  201535. }
  201536. return exists;
  201537. }
  201538. void PlatformUtilities::deleteRegistryValue (const String& regValuePath)
  201539. {
  201540. String valueName;
  201541. HKEY k = findKeyForPath (regValuePath, true, valueName);
  201542. if (k != 0)
  201543. {
  201544. RegDeleteValue (k, valueName);
  201545. RegCloseKey (k);
  201546. }
  201547. }
  201548. void PlatformUtilities::deleteRegistryKey (const String& regKeyPath)
  201549. {
  201550. String valueName;
  201551. HKEY k = findKeyForPath (regKeyPath, true, valueName);
  201552. if (k != 0)
  201553. {
  201554. RegDeleteKey (k, valueName);
  201555. RegCloseKey (k);
  201556. }
  201557. }
  201558. void PlatformUtilities::registerFileAssociation (const String& fileExtension,
  201559. const String& symbolicDescription,
  201560. const String& fullDescription,
  201561. const File& targetExecutable,
  201562. int iconResourceNumber)
  201563. {
  201564. setRegistryValue ("HKEY_CLASSES_ROOT\\" + fileExtension + "\\", symbolicDescription);
  201565. const String key ("HKEY_CLASSES_ROOT\\" + symbolicDescription);
  201566. if (iconResourceNumber != 0)
  201567. setRegistryValue (key + "\\DefaultIcon\\",
  201568. targetExecutable.getFullPathName() + "," + String (-iconResourceNumber));
  201569. setRegistryValue (key + "\\", fullDescription);
  201570. setRegistryValue (key + "\\shell\\open\\command\\",
  201571. targetExecutable.getFullPathName() + " %1");
  201572. }
  201573. bool juce_IsRunningInWine()
  201574. {
  201575. HKEY key;
  201576. if (RegOpenKeyEx (HKEY_CURRENT_USER, _T("Software\\Wine"), 0, KEY_READ, &key) == ERROR_SUCCESS)
  201577. {
  201578. RegCloseKey (key);
  201579. return true;
  201580. }
  201581. return false;
  201582. }
  201583. const String JUCE_CALLTYPE PlatformUtilities::getCurrentCommandLineParams() throw()
  201584. {
  201585. String s (::GetCommandLineW());
  201586. StringArray tokens;
  201587. tokens.addTokens (s, true); // tokenise so that we can remove the initial filename argument
  201588. return tokens.joinIntoString (" ", 1);
  201589. }
  201590. static void* currentModuleHandle = 0;
  201591. void* PlatformUtilities::getCurrentModuleInstanceHandle() throw()
  201592. {
  201593. if (currentModuleHandle == 0)
  201594. currentModuleHandle = GetModuleHandle (0);
  201595. return currentModuleHandle;
  201596. }
  201597. void PlatformUtilities::setCurrentModuleInstanceHandle (void* const newHandle) throw()
  201598. {
  201599. currentModuleHandle = newHandle;
  201600. }
  201601. void PlatformUtilities::fpuReset()
  201602. {
  201603. #if JUCE_MSVC
  201604. _clearfp();
  201605. #endif
  201606. }
  201607. void PlatformUtilities::beep()
  201608. {
  201609. MessageBeep (MB_OK);
  201610. }
  201611. #endif
  201612. /*** End of inlined file: juce_win32_PlatformUtils.cpp ***/
  201613. #if ! JUCE_ONLY_BUILD_CORE_LIBRARY
  201614. /*** Start of inlined file: juce_win32_Messaging.cpp ***/
  201615. // (This file gets included by juce_win32_NativeCode.cpp, rather than being
  201616. // compiled on its own).
  201617. #if JUCE_INCLUDED_FILE
  201618. static const unsigned int specialId = WM_APP + 0x4400;
  201619. static const unsigned int broadcastId = WM_APP + 0x4403;
  201620. static const unsigned int specialCallbackId = WM_APP + 0x4402;
  201621. static const TCHAR* const messageWindowName = _T("JUCEWindow");
  201622. HWND juce_messageWindowHandle = 0;
  201623. extern long improbableWindowNumber; // defined in windowing.cpp
  201624. #ifndef WM_APPCOMMAND
  201625. #define WM_APPCOMMAND 0x0319
  201626. #endif
  201627. static LRESULT CALLBACK juce_MessageWndProc (HWND h,
  201628. const UINT message,
  201629. const WPARAM wParam,
  201630. const LPARAM lParam) throw()
  201631. {
  201632. JUCE_TRY
  201633. {
  201634. if (h == juce_messageWindowHandle)
  201635. {
  201636. if (message == specialCallbackId)
  201637. {
  201638. MessageCallbackFunction* const func = (MessageCallbackFunction*) wParam;
  201639. return (LRESULT) (*func) ((void*) lParam);
  201640. }
  201641. else if (message == specialId)
  201642. {
  201643. // these are trapped early in the dispatch call, but must also be checked
  201644. // here in case there are windows modal dialog boxes doing their own
  201645. // dispatch loop and not calling our version
  201646. MessageManager::getInstance()->deliverMessage ((void*) lParam);
  201647. return 0;
  201648. }
  201649. else if (message == broadcastId)
  201650. {
  201651. const ScopedPointer <String> messageString ((String*) lParam);
  201652. MessageManager::getInstance()->deliverBroadcastMessage (*messageString);
  201653. return 0;
  201654. }
  201655. else if (message == WM_COPYDATA && ((const COPYDATASTRUCT*) lParam)->dwData == broadcastId)
  201656. {
  201657. const String messageString ((const juce_wchar*) ((const COPYDATASTRUCT*) lParam)->lpData,
  201658. ((const COPYDATASTRUCT*) lParam)->cbData / sizeof (juce_wchar));
  201659. PostMessage (juce_messageWindowHandle, broadcastId, 0, (LPARAM) new String (messageString));
  201660. return 0;
  201661. }
  201662. }
  201663. }
  201664. JUCE_CATCH_EXCEPTION
  201665. return DefWindowProc (h, message, wParam, lParam);
  201666. }
  201667. static bool isEventBlockedByModalComps (MSG& m)
  201668. {
  201669. if (Component::getNumCurrentlyModalComponents() == 0
  201670. || GetWindowLong (m.hwnd, GWLP_USERDATA) == improbableWindowNumber)
  201671. return false;
  201672. switch (m.message)
  201673. {
  201674. case WM_MOUSEMOVE:
  201675. case WM_NCMOUSEMOVE:
  201676. case 0x020A: /* WM_MOUSEWHEEL */
  201677. case 0x020E: /* WM_MOUSEHWHEEL */
  201678. case WM_KEYUP:
  201679. case WM_SYSKEYUP:
  201680. case WM_CHAR:
  201681. case WM_APPCOMMAND:
  201682. case WM_LBUTTONUP:
  201683. case WM_MBUTTONUP:
  201684. case WM_RBUTTONUP:
  201685. case WM_MOUSEACTIVATE:
  201686. case WM_NCMOUSEHOVER:
  201687. case WM_MOUSEHOVER:
  201688. return true;
  201689. case WM_NCLBUTTONDOWN:
  201690. case WM_NCLBUTTONDBLCLK:
  201691. case WM_NCRBUTTONDOWN:
  201692. case WM_NCRBUTTONDBLCLK:
  201693. case WM_NCMBUTTONDOWN:
  201694. case WM_NCMBUTTONDBLCLK:
  201695. case WM_LBUTTONDOWN:
  201696. case WM_LBUTTONDBLCLK:
  201697. case WM_MBUTTONDOWN:
  201698. case WM_MBUTTONDBLCLK:
  201699. case WM_RBUTTONDOWN:
  201700. case WM_RBUTTONDBLCLK:
  201701. case WM_KEYDOWN:
  201702. case WM_SYSKEYDOWN:
  201703. {
  201704. Component* const modal = Component::getCurrentlyModalComponent (0);
  201705. if (modal != 0)
  201706. modal->inputAttemptWhenModal();
  201707. return true;
  201708. }
  201709. default:
  201710. break;
  201711. }
  201712. return false;
  201713. }
  201714. bool juce_dispatchNextMessageOnSystemQueue (const bool returnIfNoPendingMessages)
  201715. {
  201716. MSG m;
  201717. if (returnIfNoPendingMessages && ! PeekMessage (&m, (HWND) 0, 0, 0, 0))
  201718. return false;
  201719. if (GetMessage (&m, (HWND) 0, 0, 0) >= 0)
  201720. {
  201721. if (m.message == specialId && m.hwnd == juce_messageWindowHandle)
  201722. {
  201723. MessageManager::getInstance()->deliverMessage ((void*) m.lParam);
  201724. }
  201725. else if (m.message == WM_QUIT)
  201726. {
  201727. if (JUCEApplication::getInstance())
  201728. JUCEApplication::getInstance()->systemRequestedQuit();
  201729. }
  201730. else if (! isEventBlockedByModalComps (m))
  201731. {
  201732. if ((m.message == WM_LBUTTONDOWN || m.message == WM_RBUTTONDOWN)
  201733. && GetWindowLong (m.hwnd, GWLP_USERDATA) != improbableWindowNumber)
  201734. {
  201735. // if it's someone else's window being clicked on, and the focus is
  201736. // currently on a juce window, pass the kb focus over..
  201737. HWND currentFocus = GetFocus();
  201738. if (currentFocus == 0 || GetWindowLong (currentFocus, GWLP_USERDATA) == improbableWindowNumber)
  201739. SetFocus (m.hwnd);
  201740. }
  201741. TranslateMessage (&m);
  201742. DispatchMessage (&m);
  201743. }
  201744. }
  201745. return true;
  201746. }
  201747. bool juce_postMessageToSystemQueue (void* message)
  201748. {
  201749. return PostMessage (juce_messageWindowHandle, specialId, 0, (LPARAM) message) != 0;
  201750. }
  201751. void* MessageManager::callFunctionOnMessageThread (MessageCallbackFunction* callback,
  201752. void* userData)
  201753. {
  201754. if (MessageManager::getInstance()->isThisTheMessageThread())
  201755. {
  201756. return (*callback) (userData);
  201757. }
  201758. else
  201759. {
  201760. // If a thread has a MessageManagerLock and then tries to call this method, it'll
  201761. // deadlock because the message manager is blocked from running, and can't
  201762. // call your function..
  201763. jassert (! MessageManager::getInstance()->currentThreadHasLockedMessageManager());
  201764. return (void*) SendMessage (juce_messageWindowHandle,
  201765. specialCallbackId,
  201766. (WPARAM) callback,
  201767. (LPARAM) userData);
  201768. }
  201769. }
  201770. static BOOL CALLBACK BroadcastEnumWindowProc (HWND hwnd, LPARAM lParam)
  201771. {
  201772. if (hwnd != juce_messageWindowHandle)
  201773. reinterpret_cast <VoidArray*> (lParam)->add ((void*) hwnd);
  201774. return TRUE;
  201775. }
  201776. void MessageManager::broadcastMessage (const String& value) throw()
  201777. {
  201778. VoidArray windows;
  201779. EnumWindows (&BroadcastEnumWindowProc, (LPARAM) &windows);
  201780. const String localCopy (value);
  201781. COPYDATASTRUCT data;
  201782. data.dwData = broadcastId;
  201783. data.cbData = (localCopy.length() + 1) * sizeof (juce_wchar);
  201784. data.lpData = (void*) static_cast <const juce_wchar*> (localCopy);
  201785. for (int i = windows.size(); --i >= 0;)
  201786. {
  201787. HWND hwnd = (HWND) windows.getUnchecked(i);
  201788. TCHAR windowName [64]; // no need to read longer strings than this
  201789. GetWindowText (hwnd, windowName, 64);
  201790. windowName [63] = 0;
  201791. if (String (windowName) == messageWindowName)
  201792. {
  201793. DWORD_PTR result;
  201794. SendMessageTimeout (hwnd, WM_COPYDATA,
  201795. (WPARAM) juce_messageWindowHandle,
  201796. (LPARAM) &data,
  201797. SMTO_BLOCK | SMTO_ABORTIFHUNG,
  201798. 8000,
  201799. &result);
  201800. }
  201801. }
  201802. }
  201803. static const String getMessageWindowClassName()
  201804. {
  201805. // this name has to be different for each app/dll instance because otherwise
  201806. // poor old Win32 can get a bit confused (even despite it not being a process-global
  201807. // window class).
  201808. static int number = 0;
  201809. if (number == 0)
  201810. number = 0x7fffffff & (int) Time::getHighResolutionTicks();
  201811. return "JUCEcs_" + String (number);
  201812. }
  201813. void MessageManager::doPlatformSpecificInitialisation()
  201814. {
  201815. OleInitialize (0);
  201816. const String className (getMessageWindowClassName());
  201817. HMODULE hmod = (HMODULE) PlatformUtilities::getCurrentModuleInstanceHandle();
  201818. WNDCLASSEX wc;
  201819. zerostruct (wc);
  201820. wc.cbSize = sizeof (wc);
  201821. wc.lpfnWndProc = (WNDPROC) juce_MessageWndProc;
  201822. wc.cbWndExtra = 4;
  201823. wc.hInstance = hmod;
  201824. wc.lpszClassName = className;
  201825. RegisterClassEx (&wc);
  201826. juce_messageWindowHandle = CreateWindow (wc.lpszClassName,
  201827. messageWindowName,
  201828. 0, 0, 0, 0, 0, 0, 0,
  201829. hmod, 0);
  201830. }
  201831. void MessageManager::doPlatformSpecificShutdown()
  201832. {
  201833. DestroyWindow (juce_messageWindowHandle);
  201834. UnregisterClass (getMessageWindowClassName(), 0);
  201835. OleUninitialize();
  201836. }
  201837. #endif
  201838. /*** End of inlined file: juce_win32_Messaging.cpp ***/
  201839. /*** Start of inlined file: juce_win32_Windowing.cpp ***/
  201840. // (This file gets included by juce_win32_NativeCode.cpp, rather than being
  201841. // compiled on its own).
  201842. #if JUCE_INCLUDED_FILE
  201843. #undef GetSystemMetrics // multimon overrides this for some reason and causes a mess..
  201844. // these are in the windows SDK, but need to be repeated here for GCC..
  201845. #ifndef GET_APPCOMMAND_LPARAM
  201846. #define FAPPCOMMAND_MASK 0xF000
  201847. #define GET_APPCOMMAND_LPARAM(lParam) ((short) (HIWORD (lParam) & ~FAPPCOMMAND_MASK))
  201848. #define APPCOMMAND_MEDIA_NEXTTRACK 11
  201849. #define APPCOMMAND_MEDIA_PREVIOUSTRACK 12
  201850. #define APPCOMMAND_MEDIA_STOP 13
  201851. #define APPCOMMAND_MEDIA_PLAY_PAUSE 14
  201852. #define WM_APPCOMMAND 0x0319
  201853. #endif
  201854. extern void juce_repeatLastProcessPriority(); // in juce_win32_Threads.cpp
  201855. extern void juce_CheckCurrentlyFocusedTopLevelWindow(); // in juce_TopLevelWindow.cpp
  201856. extern bool juce_IsRunningInWine();
  201857. #ifndef ULW_ALPHA
  201858. #define ULW_ALPHA 0x00000002
  201859. #endif
  201860. #ifndef AC_SRC_ALPHA
  201861. #define AC_SRC_ALPHA 0x01
  201862. #endif
  201863. static HPALETTE palette = 0;
  201864. static bool createPaletteIfNeeded = true;
  201865. static bool shouldDeactivateTitleBar = true;
  201866. static HICON createHICONFromImage (const Image& image, const BOOL isIcon, int hotspotX, int hotspotY) throw();
  201867. #define WM_TRAYNOTIFY WM_USER + 100
  201868. using ::abs;
  201869. typedef BOOL (WINAPI* UpdateLayeredWinFunc) (HWND, HDC, POINT*, SIZE*, HDC, POINT*, COLORREF, BLENDFUNCTION*, DWORD);
  201870. static UpdateLayeredWinFunc updateLayeredWindow = 0;
  201871. bool Desktop::canUseSemiTransparentWindows() throw()
  201872. {
  201873. if (updateLayeredWindow == 0)
  201874. {
  201875. if (! juce_IsRunningInWine())
  201876. {
  201877. HMODULE user32Mod = GetModuleHandle (_T("user32.dll"));
  201878. updateLayeredWindow = (UpdateLayeredWinFunc) GetProcAddress (user32Mod, "UpdateLayeredWindow");
  201879. }
  201880. }
  201881. return updateLayeredWindow != 0;
  201882. }
  201883. const int extendedKeyModifier = 0x10000;
  201884. const int KeyPress::spaceKey = VK_SPACE;
  201885. const int KeyPress::returnKey = VK_RETURN;
  201886. const int KeyPress::escapeKey = VK_ESCAPE;
  201887. const int KeyPress::backspaceKey = VK_BACK;
  201888. const int KeyPress::deleteKey = VK_DELETE | extendedKeyModifier;
  201889. const int KeyPress::insertKey = VK_INSERT | extendedKeyModifier;
  201890. const int KeyPress::tabKey = VK_TAB;
  201891. const int KeyPress::leftKey = VK_LEFT | extendedKeyModifier;
  201892. const int KeyPress::rightKey = VK_RIGHT | extendedKeyModifier;
  201893. const int KeyPress::upKey = VK_UP | extendedKeyModifier;
  201894. const int KeyPress::downKey = VK_DOWN | extendedKeyModifier;
  201895. const int KeyPress::homeKey = VK_HOME | extendedKeyModifier;
  201896. const int KeyPress::endKey = VK_END | extendedKeyModifier;
  201897. const int KeyPress::pageUpKey = VK_PRIOR | extendedKeyModifier;
  201898. const int KeyPress::pageDownKey = VK_NEXT | extendedKeyModifier;
  201899. const int KeyPress::F1Key = VK_F1 | extendedKeyModifier;
  201900. const int KeyPress::F2Key = VK_F2 | extendedKeyModifier;
  201901. const int KeyPress::F3Key = VK_F3 | extendedKeyModifier;
  201902. const int KeyPress::F4Key = VK_F4 | extendedKeyModifier;
  201903. const int KeyPress::F5Key = VK_F5 | extendedKeyModifier;
  201904. const int KeyPress::F6Key = VK_F6 | extendedKeyModifier;
  201905. const int KeyPress::F7Key = VK_F7 | extendedKeyModifier;
  201906. const int KeyPress::F8Key = VK_F8 | extendedKeyModifier;
  201907. const int KeyPress::F9Key = VK_F9 | extendedKeyModifier;
  201908. const int KeyPress::F10Key = VK_F10 | extendedKeyModifier;
  201909. const int KeyPress::F11Key = VK_F11 | extendedKeyModifier;
  201910. const int KeyPress::F12Key = VK_F12 | extendedKeyModifier;
  201911. const int KeyPress::F13Key = VK_F13 | extendedKeyModifier;
  201912. const int KeyPress::F14Key = VK_F14 | extendedKeyModifier;
  201913. const int KeyPress::F15Key = VK_F15 | extendedKeyModifier;
  201914. const int KeyPress::F16Key = VK_F16 | extendedKeyModifier;
  201915. const int KeyPress::numberPad0 = VK_NUMPAD0 | extendedKeyModifier;
  201916. const int KeyPress::numberPad1 = VK_NUMPAD1 | extendedKeyModifier;
  201917. const int KeyPress::numberPad2 = VK_NUMPAD2 | extendedKeyModifier;
  201918. const int KeyPress::numberPad3 = VK_NUMPAD3 | extendedKeyModifier;
  201919. const int KeyPress::numberPad4 = VK_NUMPAD4 | extendedKeyModifier;
  201920. const int KeyPress::numberPad5 = VK_NUMPAD5 | extendedKeyModifier;
  201921. const int KeyPress::numberPad6 = VK_NUMPAD6 | extendedKeyModifier;
  201922. const int KeyPress::numberPad7 = VK_NUMPAD7 | extendedKeyModifier;
  201923. const int KeyPress::numberPad8 = VK_NUMPAD8 | extendedKeyModifier;
  201924. const int KeyPress::numberPad9 = VK_NUMPAD9 | extendedKeyModifier;
  201925. const int KeyPress::numberPadAdd = VK_ADD | extendedKeyModifier;
  201926. const int KeyPress::numberPadSubtract = VK_SUBTRACT | extendedKeyModifier;
  201927. const int KeyPress::numberPadMultiply = VK_MULTIPLY | extendedKeyModifier;
  201928. const int KeyPress::numberPadDivide = VK_DIVIDE | extendedKeyModifier;
  201929. const int KeyPress::numberPadSeparator = VK_SEPARATOR | extendedKeyModifier;
  201930. const int KeyPress::numberPadDecimalPoint = VK_DECIMAL | extendedKeyModifier;
  201931. const int KeyPress::numberPadEquals = 0x92 /*VK_OEM_NEC_EQUAL*/ | extendedKeyModifier;
  201932. const int KeyPress::numberPadDelete = VK_DELETE | extendedKeyModifier;
  201933. const int KeyPress::playKey = 0x30000;
  201934. const int KeyPress::stopKey = 0x30001;
  201935. const int KeyPress::fastForwardKey = 0x30002;
  201936. const int KeyPress::rewindKey = 0x30003;
  201937. class WindowsBitmapImage : public Image
  201938. {
  201939. public:
  201940. HBITMAP hBitmap;
  201941. BITMAPV4HEADER bitmapInfo;
  201942. HDC hdc;
  201943. unsigned char* bitmapData;
  201944. WindowsBitmapImage (const PixelFormat format_,
  201945. const int w, const int h, const bool clearImage)
  201946. : Image (format_, w, h)
  201947. {
  201948. jassert (format_ == RGB || format_ == ARGB);
  201949. pixelStride = (format_ == RGB) ? 3 : 4;
  201950. zerostruct (bitmapInfo);
  201951. bitmapInfo.bV4Size = sizeof (BITMAPV4HEADER);
  201952. bitmapInfo.bV4Width = w;
  201953. bitmapInfo.bV4Height = h;
  201954. bitmapInfo.bV4Planes = 1;
  201955. bitmapInfo.bV4CSType = 1;
  201956. bitmapInfo.bV4BitCount = (unsigned short) (pixelStride * 8);
  201957. if (format_ == ARGB)
  201958. {
  201959. bitmapInfo.bV4AlphaMask = 0xff000000;
  201960. bitmapInfo.bV4RedMask = 0xff0000;
  201961. bitmapInfo.bV4GreenMask = 0xff00;
  201962. bitmapInfo.bV4BlueMask = 0xff;
  201963. bitmapInfo.bV4V4Compression = BI_BITFIELDS;
  201964. }
  201965. else
  201966. {
  201967. bitmapInfo.bV4V4Compression = BI_RGB;
  201968. }
  201969. lineStride = -((w * pixelStride + 3) & ~3);
  201970. HDC dc = GetDC (0);
  201971. hdc = CreateCompatibleDC (dc);
  201972. ReleaseDC (0, dc);
  201973. SetMapMode (hdc, MM_TEXT);
  201974. hBitmap = CreateDIBSection (hdc,
  201975. (BITMAPINFO*) &(bitmapInfo),
  201976. DIB_RGB_COLORS,
  201977. (void**) &bitmapData,
  201978. 0, 0);
  201979. SelectObject (hdc, hBitmap);
  201980. if (format_ == ARGB && clearImage)
  201981. zeromem (bitmapData, abs (h * lineStride));
  201982. imageData = bitmapData - (lineStride * (h - 1));
  201983. }
  201984. ~WindowsBitmapImage()
  201985. {
  201986. DeleteDC (hdc);
  201987. DeleteObject (hBitmap);
  201988. }
  201989. void blitToWindow (HWND hwnd, HDC dc, const bool transparent,
  201990. const int x, const int y,
  201991. const RectangleList& maskedRegion) throw()
  201992. {
  201993. static HDRAWDIB hdd = 0;
  201994. static bool needToCreateDrawDib = true;
  201995. if (needToCreateDrawDib)
  201996. {
  201997. needToCreateDrawDib = false;
  201998. HDC dc = GetDC (0);
  201999. const int n = GetDeviceCaps (dc, BITSPIXEL);
  202000. ReleaseDC (0, dc);
  202001. // only open if we're not palettised
  202002. if (n > 8)
  202003. hdd = DrawDibOpen();
  202004. }
  202005. if (createPaletteIfNeeded)
  202006. {
  202007. HDC dc = GetDC (0);
  202008. const int n = GetDeviceCaps (dc, BITSPIXEL);
  202009. ReleaseDC (0, dc);
  202010. if (n <= 8)
  202011. palette = CreateHalftonePalette (dc);
  202012. createPaletteIfNeeded = false;
  202013. }
  202014. if (palette != 0)
  202015. {
  202016. SelectPalette (dc, palette, FALSE);
  202017. RealizePalette (dc);
  202018. SetStretchBltMode (dc, HALFTONE);
  202019. }
  202020. SetMapMode (dc, MM_TEXT);
  202021. if (transparent)
  202022. {
  202023. POINT p, pos;
  202024. SIZE size;
  202025. RECT windowBounds;
  202026. GetWindowRect (hwnd, &windowBounds);
  202027. p.x = -x;
  202028. p.y = -y;
  202029. pos.x = windowBounds.left;
  202030. pos.y = windowBounds.top;
  202031. size.cx = windowBounds.right - windowBounds.left;
  202032. size.cy = windowBounds.bottom - windowBounds.top;
  202033. BLENDFUNCTION bf;
  202034. bf.AlphaFormat = AC_SRC_ALPHA;
  202035. bf.BlendFlags = 0;
  202036. bf.BlendOp = AC_SRC_OVER;
  202037. bf.SourceConstantAlpha = 0xff;
  202038. if (! maskedRegion.isEmpty())
  202039. {
  202040. for (RectangleList::Iterator i (maskedRegion); i.next();)
  202041. {
  202042. const Rectangle<int>& r = *i.getRectangle();
  202043. ExcludeClipRect (hdc, r.getX(), r.getY(), r.getRight(), r.getBottom());
  202044. }
  202045. }
  202046. updateLayeredWindow (hwnd, 0, &pos, &size, hdc, &p, 0, &bf, ULW_ALPHA);
  202047. }
  202048. else
  202049. {
  202050. int savedDC = 0;
  202051. if (! maskedRegion.isEmpty())
  202052. {
  202053. savedDC = SaveDC (dc);
  202054. for (RectangleList::Iterator i (maskedRegion); i.next();)
  202055. {
  202056. const Rectangle<int>& r = *i.getRectangle();
  202057. ExcludeClipRect (dc, r.getX(), r.getY(), r.getRight(), r.getBottom());
  202058. }
  202059. }
  202060. const int w = getWidth();
  202061. const int h = getHeight();
  202062. if (hdd == 0)
  202063. {
  202064. StretchDIBits (dc,
  202065. x, y, w, h,
  202066. 0, 0, w, h,
  202067. bitmapData, (const BITMAPINFO*) &bitmapInfo,
  202068. DIB_RGB_COLORS, SRCCOPY);
  202069. }
  202070. else
  202071. {
  202072. DrawDibDraw (hdd, dc, x, y, -1, -1,
  202073. (BITMAPINFOHEADER*) &bitmapInfo, bitmapData,
  202074. 0, 0, w, h, 0);
  202075. }
  202076. if (! maskedRegion.isEmpty())
  202077. RestoreDC (dc, savedDC);
  202078. }
  202079. }
  202080. juce_UseDebuggingNewOperator
  202081. private:
  202082. WindowsBitmapImage (const WindowsBitmapImage&);
  202083. WindowsBitmapImage& operator= (const WindowsBitmapImage&);
  202084. };
  202085. long improbableWindowNumber = 0xf965aa01; // also referenced by messaging.cpp
  202086. bool KeyPress::isKeyCurrentlyDown (const int keyCode)
  202087. {
  202088. SHORT k = (SHORT) keyCode;
  202089. if ((keyCode & extendedKeyModifier) == 0
  202090. && (k >= (SHORT) 'a' && k <= (SHORT) 'z'))
  202091. k += (SHORT) 'A' - (SHORT) 'a';
  202092. const SHORT translatedValues[] = { (SHORT) ',', VK_OEM_COMMA,
  202093. (SHORT) '+', VK_OEM_PLUS,
  202094. (SHORT) '-', VK_OEM_MINUS,
  202095. (SHORT) '.', VK_OEM_PERIOD,
  202096. (SHORT) ';', VK_OEM_1,
  202097. (SHORT) ':', VK_OEM_1,
  202098. (SHORT) '/', VK_OEM_2,
  202099. (SHORT) '?', VK_OEM_2,
  202100. (SHORT) '[', VK_OEM_4,
  202101. (SHORT) ']', VK_OEM_6 };
  202102. for (int i = 0; i < numElementsInArray (translatedValues); i += 2)
  202103. if (k == translatedValues [i])
  202104. k = translatedValues [i + 1];
  202105. return (GetKeyState (k) & 0x8000) != 0;
  202106. }
  202107. static void* callFunctionIfNotLocked (MessageCallbackFunction* callback, void* userData)
  202108. {
  202109. if (MessageManager::getInstance()->currentThreadHasLockedMessageManager())
  202110. return callback (userData);
  202111. else
  202112. return MessageManager::getInstance()->callFunctionOnMessageThread (callback, userData);
  202113. }
  202114. class Win32ComponentPeer : public ComponentPeer
  202115. {
  202116. public:
  202117. Win32ComponentPeer (Component* const component,
  202118. const int windowStyleFlags)
  202119. : ComponentPeer (component, windowStyleFlags),
  202120. dontRepaint (false),
  202121. fullScreen (false),
  202122. isDragging (false),
  202123. isMouseOver (false),
  202124. hasCreatedCaret (false),
  202125. currentWindowIcon (0),
  202126. taskBarIcon (0),
  202127. dropTarget (0)
  202128. {
  202129. callFunctionIfNotLocked (&createWindowCallback, this);
  202130. setTitle (component->getName());
  202131. if ((windowStyleFlags & windowHasDropShadow) != 0
  202132. && Desktop::canUseSemiTransparentWindows())
  202133. {
  202134. shadower = component->getLookAndFeel().createDropShadowerForComponent (component);
  202135. if (shadower != 0)
  202136. shadower->setOwner (component);
  202137. }
  202138. else
  202139. {
  202140. shadower = 0;
  202141. }
  202142. }
  202143. ~Win32ComponentPeer()
  202144. {
  202145. setTaskBarIcon (0);
  202146. deleteAndZero (shadower);
  202147. // do this before the next bit to avoid messages arriving for this window
  202148. // before it's destroyed
  202149. SetWindowLongPtr (hwnd, GWLP_USERDATA, 0);
  202150. callFunctionIfNotLocked (&destroyWindowCallback, (void*) hwnd);
  202151. if (currentWindowIcon != 0)
  202152. DestroyIcon (currentWindowIcon);
  202153. if (dropTarget != 0)
  202154. {
  202155. dropTarget->Release();
  202156. dropTarget = 0;
  202157. }
  202158. }
  202159. void* getNativeHandle() const
  202160. {
  202161. return hwnd;
  202162. }
  202163. void setVisible (bool shouldBeVisible)
  202164. {
  202165. ShowWindow (hwnd, shouldBeVisible ? SW_SHOWNA : SW_HIDE);
  202166. if (shouldBeVisible)
  202167. InvalidateRect (hwnd, 0, 0);
  202168. else
  202169. lastPaintTime = 0;
  202170. }
  202171. void setTitle (const String& title)
  202172. {
  202173. SetWindowText (hwnd, title);
  202174. }
  202175. void setPosition (int x, int y)
  202176. {
  202177. offsetWithinParent (x, y);
  202178. SetWindowPos (hwnd, 0,
  202179. x - windowBorder.getLeft(),
  202180. y - windowBorder.getTop(),
  202181. 0, 0,
  202182. SWP_NOACTIVATE | SWP_NOSIZE | SWP_NOZORDER | SWP_NOOWNERZORDER);
  202183. }
  202184. void repaintNowIfTransparent()
  202185. {
  202186. if (isTransparent() && lastPaintTime > 0 && Time::getMillisecondCounter() > lastPaintTime + 30)
  202187. handlePaintMessage();
  202188. }
  202189. void updateBorderSize()
  202190. {
  202191. WINDOWINFO info;
  202192. info.cbSize = sizeof (info);
  202193. if (GetWindowInfo (hwnd, &info))
  202194. {
  202195. windowBorder = BorderSize (info.rcClient.top - info.rcWindow.top,
  202196. info.rcClient.left - info.rcWindow.left,
  202197. info.rcWindow.bottom - info.rcClient.bottom,
  202198. info.rcWindow.right - info.rcClient.right);
  202199. }
  202200. }
  202201. void setSize (int w, int h)
  202202. {
  202203. SetWindowPos (hwnd, 0, 0, 0,
  202204. w + windowBorder.getLeftAndRight(),
  202205. h + windowBorder.getTopAndBottom(),
  202206. SWP_NOACTIVATE | SWP_NOMOVE | SWP_NOZORDER | SWP_NOOWNERZORDER);
  202207. updateBorderSize();
  202208. repaintNowIfTransparent();
  202209. }
  202210. void setBounds (int x, int y, int w, int h, bool isNowFullScreen)
  202211. {
  202212. fullScreen = isNowFullScreen;
  202213. offsetWithinParent (x, y);
  202214. SetWindowPos (hwnd, 0,
  202215. x - windowBorder.getLeft(),
  202216. y - windowBorder.getTop(),
  202217. w + windowBorder.getLeftAndRight(),
  202218. h + windowBorder.getTopAndBottom(),
  202219. SWP_NOACTIVATE | SWP_NOZORDER | SWP_NOOWNERZORDER);
  202220. updateBorderSize();
  202221. repaintNowIfTransparent();
  202222. }
  202223. const Rectangle<int> getBounds() const
  202224. {
  202225. RECT r;
  202226. GetWindowRect (hwnd, &r);
  202227. Rectangle<int> bounds (r.left, r.top, r.right - r.left, r.bottom - r.top);
  202228. HWND parentH = GetParent (hwnd);
  202229. if (parentH != 0)
  202230. {
  202231. GetWindowRect (parentH, &r);
  202232. bounds.translate (-r.left, -r.top);
  202233. }
  202234. return windowBorder.subtractedFrom (bounds);
  202235. }
  202236. const Point<int> getScreenPosition() const
  202237. {
  202238. RECT r;
  202239. GetWindowRect (hwnd, &r);
  202240. return Point<int> (r.left + windowBorder.getLeft(),
  202241. r.top + windowBorder.getTop());
  202242. }
  202243. const Point<int> relativePositionToGlobal (const Point<int>& relativePosition)
  202244. {
  202245. return relativePosition + getScreenPosition();
  202246. }
  202247. const Point<int> globalPositionToRelative (const Point<int>& screenPosition)
  202248. {
  202249. return screenPosition - getScreenPosition();
  202250. }
  202251. void setMinimised (bool shouldBeMinimised)
  202252. {
  202253. if (shouldBeMinimised != isMinimised())
  202254. ShowWindow (hwnd, shouldBeMinimised ? SW_MINIMIZE : SW_SHOWNORMAL);
  202255. }
  202256. bool isMinimised() const
  202257. {
  202258. WINDOWPLACEMENT wp;
  202259. wp.length = sizeof (WINDOWPLACEMENT);
  202260. GetWindowPlacement (hwnd, &wp);
  202261. return wp.showCmd == SW_SHOWMINIMIZED;
  202262. }
  202263. void setFullScreen (bool shouldBeFullScreen)
  202264. {
  202265. setMinimised (false);
  202266. if (fullScreen != shouldBeFullScreen)
  202267. {
  202268. fullScreen = shouldBeFullScreen;
  202269. const Component::SafePointer<Component> deletionChecker (component);
  202270. if (! fullScreen)
  202271. {
  202272. const Rectangle<int> boundsCopy (lastNonFullscreenBounds);
  202273. if (hasTitleBar())
  202274. ShowWindow (hwnd, SW_SHOWNORMAL);
  202275. if (! boundsCopy.isEmpty())
  202276. {
  202277. setBounds (boundsCopy.getX(),
  202278. boundsCopy.getY(),
  202279. boundsCopy.getWidth(),
  202280. boundsCopy.getHeight(),
  202281. false);
  202282. }
  202283. }
  202284. else
  202285. {
  202286. if (hasTitleBar())
  202287. ShowWindow (hwnd, SW_SHOWMAXIMIZED);
  202288. else
  202289. SendMessageW (hwnd, WM_SETTINGCHANGE, 0, 0);
  202290. }
  202291. if (deletionChecker != 0)
  202292. handleMovedOrResized();
  202293. }
  202294. }
  202295. bool isFullScreen() const
  202296. {
  202297. if (! hasTitleBar())
  202298. return fullScreen;
  202299. WINDOWPLACEMENT wp;
  202300. wp.length = sizeof (wp);
  202301. GetWindowPlacement (hwnd, &wp);
  202302. return wp.showCmd == SW_SHOWMAXIMIZED;
  202303. }
  202304. bool contains (const Point<int>& position, bool trueIfInAChildWindow) const
  202305. {
  202306. if (((unsigned int) position.getX()) >= (unsigned int) component->getWidth()
  202307. || ((unsigned int) position.getY()) >= (unsigned int) component->getHeight())
  202308. return false;
  202309. RECT r;
  202310. GetWindowRect (hwnd, &r);
  202311. POINT p;
  202312. p.x = position.getX() + r.left + windowBorder.getLeft();
  202313. p.y = position.getY() + r.top + windowBorder.getTop();
  202314. HWND w = WindowFromPoint (p);
  202315. return w == hwnd || (trueIfInAChildWindow && (IsChild (hwnd, w) != 0));
  202316. }
  202317. const BorderSize getFrameSize() const
  202318. {
  202319. return windowBorder;
  202320. }
  202321. bool setAlwaysOnTop (bool alwaysOnTop)
  202322. {
  202323. const bool oldDeactivate = shouldDeactivateTitleBar;
  202324. shouldDeactivateTitleBar = ((styleFlags & windowIsTemporary) == 0);
  202325. SetWindowPos (hwnd, alwaysOnTop ? HWND_TOPMOST : HWND_NOTOPMOST,
  202326. 0, 0, 0, 0,
  202327. SWP_NOMOVE | SWP_NOSIZE | SWP_NOACTIVATE | SWP_NOSENDCHANGING);
  202328. shouldDeactivateTitleBar = oldDeactivate;
  202329. if (shadower != 0)
  202330. shadower->componentBroughtToFront (*component);
  202331. return true;
  202332. }
  202333. void toFront (bool makeActive)
  202334. {
  202335. setMinimised (false);
  202336. const bool oldDeactivate = shouldDeactivateTitleBar;
  202337. shouldDeactivateTitleBar = ((styleFlags & windowIsTemporary) == 0);
  202338. callFunctionIfNotLocked (makeActive ? &toFrontCallback1 : &toFrontCallback2, hwnd);
  202339. shouldDeactivateTitleBar = oldDeactivate;
  202340. if (! makeActive)
  202341. {
  202342. // in this case a broughttofront call won't have occured, so do it now..
  202343. handleBroughtToFront();
  202344. }
  202345. }
  202346. void toBehind (ComponentPeer* other)
  202347. {
  202348. Win32ComponentPeer* const otherPeer = dynamic_cast <Win32ComponentPeer*> (other);
  202349. jassert (otherPeer != 0); // wrong type of window?
  202350. if (otherPeer != 0)
  202351. {
  202352. setMinimised (false);
  202353. // must be careful not to try to put a topmost window behind a normal one, or win32
  202354. // promotes the normal one to be topmost!
  202355. if (getComponent()->isAlwaysOnTop() == otherPeer->getComponent()->isAlwaysOnTop())
  202356. SetWindowPos (hwnd, otherPeer->hwnd, 0, 0, 0, 0,
  202357. SWP_NOMOVE | SWP_NOSIZE | SWP_NOACTIVATE | SWP_NOSENDCHANGING);
  202358. else if (otherPeer->getComponent()->isAlwaysOnTop())
  202359. SetWindowPos (hwnd, HWND_TOP, 0, 0, 0, 0,
  202360. SWP_NOMOVE | SWP_NOSIZE | SWP_NOACTIVATE | SWP_NOSENDCHANGING);
  202361. }
  202362. }
  202363. bool isFocused() const
  202364. {
  202365. return callFunctionIfNotLocked (&getFocusCallback, 0) == (void*) hwnd;
  202366. }
  202367. void grabFocus()
  202368. {
  202369. const bool oldDeactivate = shouldDeactivateTitleBar;
  202370. shouldDeactivateTitleBar = ((styleFlags & windowIsTemporary) == 0);
  202371. callFunctionIfNotLocked (&setFocusCallback, hwnd);
  202372. shouldDeactivateTitleBar = oldDeactivate;
  202373. }
  202374. void textInputRequired (const Point<int>&)
  202375. {
  202376. if (! hasCreatedCaret)
  202377. {
  202378. hasCreatedCaret = true;
  202379. CreateCaret (hwnd, (HBITMAP) 1, 0, 0);
  202380. }
  202381. ShowCaret (hwnd);
  202382. SetCaretPos (0, 0);
  202383. }
  202384. void repaint (int x, int y, int w, int h)
  202385. {
  202386. const RECT r = { x, y, x + w, y + h };
  202387. InvalidateRect (hwnd, &r, FALSE);
  202388. }
  202389. void performAnyPendingRepaintsNow()
  202390. {
  202391. MSG m;
  202392. if (component->isVisible() && PeekMessage (&m, hwnd, WM_PAINT, WM_PAINT, PM_REMOVE))
  202393. DispatchMessage (&m);
  202394. }
  202395. static Win32ComponentPeer* getOwnerOfWindow (HWND h) throw()
  202396. {
  202397. if (h != 0 && GetWindowLongPtr (h, GWLP_USERDATA) == improbableWindowNumber)
  202398. return (Win32ComponentPeer*) (pointer_sized_int) GetWindowLongPtr (h, 8);
  202399. return 0;
  202400. }
  202401. void setTaskBarIcon (const Image* const image)
  202402. {
  202403. if (image != 0)
  202404. {
  202405. HICON hicon = createHICONFromImage (*image, TRUE, 0, 0);
  202406. if (taskBarIcon == 0)
  202407. {
  202408. taskBarIcon = new NOTIFYICONDATA();
  202409. taskBarIcon->cbSize = sizeof (NOTIFYICONDATA);
  202410. taskBarIcon->hWnd = (HWND) hwnd;
  202411. taskBarIcon->uID = (int) (pointer_sized_int) hwnd;
  202412. taskBarIcon->uFlags = NIF_ICON | NIF_MESSAGE | NIF_TIP;
  202413. taskBarIcon->uCallbackMessage = WM_TRAYNOTIFY;
  202414. taskBarIcon->hIcon = hicon;
  202415. taskBarIcon->szTip[0] = 0;
  202416. Shell_NotifyIcon (NIM_ADD, taskBarIcon);
  202417. }
  202418. else
  202419. {
  202420. HICON oldIcon = taskBarIcon->hIcon;
  202421. taskBarIcon->hIcon = hicon;
  202422. taskBarIcon->uFlags = NIF_ICON;
  202423. Shell_NotifyIcon (NIM_MODIFY, taskBarIcon);
  202424. DestroyIcon (oldIcon);
  202425. }
  202426. DestroyIcon (hicon);
  202427. }
  202428. else if (taskBarIcon != 0)
  202429. {
  202430. taskBarIcon->uFlags = 0;
  202431. Shell_NotifyIcon (NIM_DELETE, taskBarIcon);
  202432. DestroyIcon (taskBarIcon->hIcon);
  202433. deleteAndZero (taskBarIcon);
  202434. }
  202435. }
  202436. void setTaskBarIconToolTip (const String& toolTip) const
  202437. {
  202438. if (taskBarIcon != 0)
  202439. {
  202440. taskBarIcon->uFlags = NIF_TIP;
  202441. toolTip.copyToUnicode (taskBarIcon->szTip, sizeof (taskBarIcon->szTip) - 1);
  202442. Shell_NotifyIcon (NIM_MODIFY, taskBarIcon);
  202443. }
  202444. }
  202445. bool isInside (HWND h) const
  202446. {
  202447. return GetAncestor (hwnd, GA_ROOT) == h;
  202448. }
  202449. static void updateKeyModifiers() throw()
  202450. {
  202451. int keyMods = 0;
  202452. if (GetKeyState (VK_SHIFT) & 0x8000) keyMods |= ModifierKeys::shiftModifier;
  202453. if (GetKeyState (VK_CONTROL) & 0x8000) keyMods |= ModifierKeys::ctrlModifier;
  202454. if (GetKeyState (VK_MENU) & 0x8000) keyMods |= ModifierKeys::altModifier;
  202455. if (GetKeyState (VK_RMENU) & 0x8000) keyMods &= ~(ModifierKeys::ctrlModifier | ModifierKeys::altModifier);
  202456. currentModifiers = currentModifiers.withOnlyMouseButtons().withFlags (keyMods);
  202457. }
  202458. static void updateModifiersFromWParam (const WPARAM wParam)
  202459. {
  202460. int mouseMods = 0;
  202461. if (wParam & MK_LBUTTON) mouseMods |= ModifierKeys::leftButtonModifier;
  202462. if (wParam & MK_RBUTTON) mouseMods |= ModifierKeys::rightButtonModifier;
  202463. if (wParam & MK_MBUTTON) mouseMods |= ModifierKeys::middleButtonModifier;
  202464. currentModifiers = currentModifiers.withoutMouseButtons().withFlags (mouseMods);
  202465. updateKeyModifiers();
  202466. }
  202467. static int64 getMouseEventTime()
  202468. {
  202469. static int64 eventTimeOffset = 0;
  202470. static DWORD lastMessageTime = 0;
  202471. const DWORD thisMessageTime = GetMessageTime();
  202472. if (thisMessageTime < lastMessageTime || lastMessageTime == 0)
  202473. {
  202474. lastMessageTime = thisMessageTime;
  202475. eventTimeOffset = Time::currentTimeMillis() - thisMessageTime;
  202476. }
  202477. return eventTimeOffset + thisMessageTime;
  202478. }
  202479. juce_UseDebuggingNewOperator
  202480. bool dontRepaint;
  202481. static ModifierKeys currentModifiers;
  202482. static ModifierKeys modifiersAtLastCallback;
  202483. private:
  202484. HWND hwnd;
  202485. DropShadower* shadower;
  202486. bool fullScreen, isDragging, isMouseOver, hasCreatedCaret;
  202487. BorderSize windowBorder;
  202488. HICON currentWindowIcon;
  202489. NOTIFYICONDATA* taskBarIcon;
  202490. IDropTarget* dropTarget;
  202491. class TemporaryImage : public Timer
  202492. {
  202493. public:
  202494. TemporaryImage() {}
  202495. ~TemporaryImage() {}
  202496. WindowsBitmapImage* getImage (const bool transparent, const int w, const int h) throw()
  202497. {
  202498. const Image::PixelFormat format = transparent ? Image::ARGB : Image::RGB;
  202499. if (image == 0 || image->getWidth() < w || image->getHeight() < h || image->getFormat() != format)
  202500. image = new WindowsBitmapImage (format, (w + 31) & ~31, (h + 31) & ~31, false);
  202501. startTimer (3000);
  202502. return image;
  202503. }
  202504. void timerCallback()
  202505. {
  202506. stopTimer();
  202507. image = 0;
  202508. }
  202509. private:
  202510. ScopedPointer <WindowsBitmapImage> image;
  202511. TemporaryImage (const TemporaryImage&);
  202512. TemporaryImage& operator= (const TemporaryImage&);
  202513. };
  202514. TemporaryImage offscreenImageGenerator;
  202515. class WindowClassHolder : public DeletedAtShutdown
  202516. {
  202517. public:
  202518. WindowClassHolder()
  202519. : windowClassName ("JUCE_")
  202520. {
  202521. // this name has to be different for each app/dll instance because otherwise
  202522. // poor old Win32 can get a bit confused (even despite it not being a process-global
  202523. // window class).
  202524. windowClassName << (int) (Time::currentTimeMillis() & 0x7fffffff);
  202525. HINSTANCE moduleHandle = (HINSTANCE) PlatformUtilities::getCurrentModuleInstanceHandle();
  202526. TCHAR moduleFile [1024];
  202527. moduleFile[0] = 0;
  202528. GetModuleFileName (moduleHandle, moduleFile, 1024);
  202529. WORD iconNum = 0;
  202530. WNDCLASSEX wcex;
  202531. wcex.cbSize = sizeof (wcex);
  202532. wcex.style = CS_OWNDC;
  202533. wcex.lpfnWndProc = (WNDPROC) windowProc;
  202534. wcex.lpszClassName = windowClassName;
  202535. wcex.cbClsExtra = 0;
  202536. wcex.cbWndExtra = 32;
  202537. wcex.hInstance = moduleHandle;
  202538. wcex.hIcon = ExtractAssociatedIcon (moduleHandle, moduleFile, &iconNum);
  202539. iconNum = 1;
  202540. wcex.hIconSm = ExtractAssociatedIcon (moduleHandle, moduleFile, &iconNum);
  202541. wcex.hCursor = 0;
  202542. wcex.hbrBackground = 0;
  202543. wcex.lpszMenuName = 0;
  202544. RegisterClassEx (&wcex);
  202545. }
  202546. ~WindowClassHolder()
  202547. {
  202548. if (ComponentPeer::getNumPeers() == 0)
  202549. UnregisterClass (windowClassName, (HINSTANCE) PlatformUtilities::getCurrentModuleInstanceHandle());
  202550. clearSingletonInstance();
  202551. }
  202552. String windowClassName;
  202553. juce_DeclareSingleton_SingleThreaded_Minimal (WindowClassHolder);
  202554. };
  202555. static void* createWindowCallback (void* userData)
  202556. {
  202557. static_cast <Win32ComponentPeer*> (userData)->createWindow();
  202558. return 0;
  202559. }
  202560. void createWindow()
  202561. {
  202562. DWORD exstyle = WS_EX_ACCEPTFILES;
  202563. DWORD type = WS_CLIPSIBLINGS | WS_CLIPCHILDREN;
  202564. if (hasTitleBar())
  202565. {
  202566. type |= WS_OVERLAPPED;
  202567. exstyle |= WS_EX_APPWINDOW;
  202568. if ((styleFlags & windowHasCloseButton) != 0)
  202569. {
  202570. type |= WS_SYSMENU;
  202571. }
  202572. else
  202573. {
  202574. // annoyingly, windows won't let you have a min/max button without a close button
  202575. jassert ((styleFlags & (windowHasMinimiseButton | windowHasMaximiseButton)) == 0);
  202576. }
  202577. if ((styleFlags & windowIsResizable) != 0)
  202578. type |= WS_THICKFRAME;
  202579. }
  202580. else
  202581. {
  202582. type |= WS_POPUP | WS_SYSMENU;
  202583. if ((styleFlags & windowAppearsOnTaskbar) == 0)
  202584. exstyle |= WS_EX_TOOLWINDOW;
  202585. else
  202586. exstyle |= WS_EX_APPWINDOW;
  202587. }
  202588. if ((styleFlags & windowHasMinimiseButton) != 0)
  202589. type |= WS_MINIMIZEBOX;
  202590. if ((styleFlags & windowHasMaximiseButton) != 0)
  202591. type |= WS_MAXIMIZEBOX;
  202592. if ((styleFlags & windowIgnoresMouseClicks) != 0)
  202593. exstyle |= WS_EX_TRANSPARENT;
  202594. if ((styleFlags & windowIsSemiTransparent) != 0
  202595. && Desktop::canUseSemiTransparentWindows())
  202596. exstyle |= WS_EX_LAYERED;
  202597. hwnd = CreateWindowEx (exstyle, WindowClassHolder::getInstance()->windowClassName, L"", type, 0, 0, 0, 0, 0, 0, 0, 0);
  202598. if (hwnd != 0)
  202599. {
  202600. SetWindowLongPtr (hwnd, 0, 0);
  202601. SetWindowLongPtr (hwnd, 8, (LONG_PTR) this);
  202602. SetWindowLongPtr (hwnd, GWLP_USERDATA, improbableWindowNumber);
  202603. if (dropTarget == 0)
  202604. dropTarget = new JuceDropTarget (this);
  202605. RegisterDragDrop (hwnd, dropTarget);
  202606. updateBorderSize();
  202607. // Calling this function here is (for some reason) necessary to make Windows
  202608. // correctly enable the menu items that we specify in the wm_initmenu message.
  202609. GetSystemMenu (hwnd, false);
  202610. }
  202611. else
  202612. {
  202613. jassertfalse
  202614. }
  202615. }
  202616. static void* destroyWindowCallback (void* handle)
  202617. {
  202618. RevokeDragDrop ((HWND) handle);
  202619. DestroyWindow ((HWND) handle);
  202620. return 0;
  202621. }
  202622. static void* toFrontCallback1 (void* h)
  202623. {
  202624. SetForegroundWindow ((HWND) h);
  202625. return 0;
  202626. }
  202627. static void* toFrontCallback2 (void* h)
  202628. {
  202629. SetWindowPos ((HWND) h, HWND_TOP, 0, 0, 0, 0, SWP_NOMOVE | SWP_NOSIZE | SWP_NOACTIVATE | SWP_NOSENDCHANGING);
  202630. return 0;
  202631. }
  202632. static void* setFocusCallback (void* h)
  202633. {
  202634. SetFocus ((HWND) h);
  202635. return 0;
  202636. }
  202637. static void* getFocusCallback (void*)
  202638. {
  202639. return GetFocus();
  202640. }
  202641. void offsetWithinParent (int& x, int& y) const
  202642. {
  202643. if (isTransparent())
  202644. {
  202645. HWND parentHwnd = GetParent (hwnd);
  202646. if (parentHwnd != 0)
  202647. {
  202648. RECT parentRect;
  202649. GetWindowRect (parentHwnd, &parentRect);
  202650. x += parentRect.left;
  202651. y += parentRect.top;
  202652. }
  202653. }
  202654. }
  202655. bool isTransparent() const
  202656. {
  202657. return (GetWindowLong (hwnd, GWL_EXSTYLE) & WS_EX_LAYERED) != 0;
  202658. }
  202659. inline bool hasTitleBar() const throw() { return (styleFlags & windowHasTitleBar) != 0; }
  202660. void setIcon (const Image& newIcon)
  202661. {
  202662. HICON hicon = createHICONFromImage (newIcon, TRUE, 0, 0);
  202663. if (hicon != 0)
  202664. {
  202665. SendMessage (hwnd, WM_SETICON, ICON_BIG, (LPARAM) hicon);
  202666. SendMessage (hwnd, WM_SETICON, ICON_SMALL, (LPARAM) hicon);
  202667. if (currentWindowIcon != 0)
  202668. DestroyIcon (currentWindowIcon);
  202669. currentWindowIcon = hicon;
  202670. }
  202671. }
  202672. void handlePaintMessage()
  202673. {
  202674. HRGN rgn = CreateRectRgn (0, 0, 0, 0);
  202675. const int regionType = GetUpdateRgn (hwnd, rgn, false);
  202676. PAINTSTRUCT paintStruct;
  202677. HDC dc = BeginPaint (hwnd, &paintStruct); // Note this can immediately generate a WM_NCPAINT
  202678. // message and become re-entrant, but that's OK
  202679. // if something in a paint handler calls, e.g. a message box, this can become reentrant and
  202680. // corrupt the image it's using to paint into, so do a check here.
  202681. static bool reentrant = false;
  202682. if (reentrant)
  202683. {
  202684. DeleteObject (rgn);
  202685. EndPaint (hwnd, &paintStruct);
  202686. return;
  202687. }
  202688. reentrant = true;
  202689. // this is the rectangle to update..
  202690. int x = paintStruct.rcPaint.left;
  202691. int y = paintStruct.rcPaint.top;
  202692. int w = paintStruct.rcPaint.right - x;
  202693. int h = paintStruct.rcPaint.bottom - y;
  202694. const bool transparent = isTransparent();
  202695. if (transparent)
  202696. {
  202697. // it's not possible to have a transparent window with a title bar at the moment!
  202698. jassert (! hasTitleBar());
  202699. RECT r;
  202700. GetWindowRect (hwnd, &r);
  202701. x = y = 0;
  202702. w = r.right - r.left;
  202703. h = r.bottom - r.top;
  202704. }
  202705. if (w > 0 && h > 0)
  202706. {
  202707. clearMaskedRegion();
  202708. WindowsBitmapImage* const offscreenImage = offscreenImageGenerator.getImage (transparent, w, h);
  202709. RectangleList contextClip;
  202710. bool needToPaintAll = true;
  202711. if (regionType == COMPLEXREGION && ! transparent)
  202712. {
  202713. HRGN clipRgn = CreateRectRgnIndirect (&paintStruct.rcPaint);
  202714. CombineRgn (rgn, rgn, clipRgn, RGN_AND);
  202715. DeleteObject (clipRgn);
  202716. char rgnData [8192];
  202717. const DWORD res = GetRegionData (rgn, sizeof (rgnData), (RGNDATA*) rgnData);
  202718. if (res > 0 && res <= sizeof (rgnData))
  202719. {
  202720. const RGNDATAHEADER* const hdr = &(((const RGNDATA*) rgnData)->rdh);
  202721. if (hdr->iType == RDH_RECTANGLES
  202722. && hdr->rcBound.right - hdr->rcBound.left >= w
  202723. && hdr->rcBound.bottom - hdr->rcBound.top >= h)
  202724. {
  202725. needToPaintAll = false;
  202726. const RECT* rects = (const RECT*) (rgnData + sizeof (RGNDATAHEADER));
  202727. int num = ((RGNDATA*) rgnData)->rdh.nCount;
  202728. while (--num >= 0)
  202729. {
  202730. // (need to move this one pixel to the left because of a win32 bug)
  202731. const int cx = jmax (x, (int) rects->left - 1);
  202732. const int cy = rects->top;
  202733. const int cw = rects->right - cx;
  202734. const int ch = rects->bottom - rects->top;
  202735. if (cx + cw - x <= w && cy + ch - y <= h)
  202736. {
  202737. contextClip.addWithoutMerging (Rectangle<int> (cx - x, cy - y, cw, ch));
  202738. }
  202739. else
  202740. {
  202741. needToPaintAll = true;
  202742. break;
  202743. }
  202744. ++rects;
  202745. }
  202746. }
  202747. }
  202748. }
  202749. if (needToPaintAll)
  202750. {
  202751. contextClip.clear();
  202752. contextClip.addWithoutMerging (Rectangle<int> (0, 0, w, h));
  202753. }
  202754. if (transparent)
  202755. {
  202756. RectangleList::Iterator i (contextClip);
  202757. while (i.next())
  202758. {
  202759. const Rectangle<int>& r = *i.getRectangle();
  202760. offscreenImage->clear (r.getX(), r.getY(), r.getWidth(), r.getHeight());
  202761. }
  202762. }
  202763. // if the component's not opaque, this won't draw properly unless the platform can support this
  202764. jassert (Desktop::canUseSemiTransparentWindows() || component->isOpaque());
  202765. updateCurrentModifiers();
  202766. LowLevelGraphicsSoftwareRenderer context (*offscreenImage);
  202767. context.clipToRectangleList (contextClip);
  202768. context.setOrigin (-x, -y);
  202769. handlePaint (context);
  202770. if (! dontRepaint)
  202771. offscreenImage->blitToWindow (hwnd, dc, transparent, x, y, maskedRegion);
  202772. }
  202773. DeleteObject (rgn);
  202774. EndPaint (hwnd, &paintStruct);
  202775. reentrant = false;
  202776. #ifndef JUCE_GCC //xxx should add this fn for gcc..
  202777. _fpreset(); // because some graphics cards can unmask FP exceptions
  202778. #endif
  202779. lastPaintTime = Time::getMillisecondCounter();
  202780. }
  202781. void doMouseEvent (const Point<int>& position)
  202782. {
  202783. handleMouseEvent (0, position, currentModifiers, getMouseEventTime());
  202784. }
  202785. void doMouseMove (const Point<int>& position)
  202786. {
  202787. if (! isMouseOver)
  202788. {
  202789. isMouseOver = true;
  202790. updateKeyModifiers();
  202791. TRACKMOUSEEVENT tme;
  202792. tme.cbSize = sizeof (tme);
  202793. tme.dwFlags = TME_LEAVE;
  202794. tme.hwndTrack = hwnd;
  202795. tme.dwHoverTime = 0;
  202796. if (! TrackMouseEvent (&tme))
  202797. jassertfalse;
  202798. Desktop::getInstance().getMainMouseSource().forceMouseCursorUpdate();
  202799. }
  202800. else if (! isDragging)
  202801. {
  202802. if (! contains (position, false))
  202803. return;
  202804. }
  202805. // (Throttling the incoming queue of mouse-events seems to still be required in XP..)
  202806. static uint32 lastMouseTime = 0;
  202807. const uint32 now = Time::getMillisecondCounter();
  202808. const int maxMouseMovesPerSecond = 60;
  202809. if (now > lastMouseTime + 1000 / maxMouseMovesPerSecond)
  202810. {
  202811. lastMouseTime = now;
  202812. doMouseEvent (position);
  202813. }
  202814. }
  202815. void doMouseDown (const Point<int>& position, const WPARAM wParam)
  202816. {
  202817. if (GetCapture() != hwnd)
  202818. SetCapture (hwnd);
  202819. doMouseMove (position);
  202820. updateModifiersFromWParam (wParam);
  202821. isDragging = true;
  202822. doMouseEvent (position);
  202823. }
  202824. void doMouseUp (const Point<int>& position, const WPARAM wParam)
  202825. {
  202826. updateModifiersFromWParam (wParam);
  202827. isDragging = false;
  202828. // release the mouse capture if the user has released all buttons
  202829. if ((wParam & (MK_LBUTTON | MK_RBUTTON | MK_MBUTTON)) == 0 && hwnd == GetCapture())
  202830. ReleaseCapture();
  202831. doMouseEvent (position);
  202832. }
  202833. void doCaptureChanged()
  202834. {
  202835. if (isDragging)
  202836. doMouseUp (getCurrentMousePos(), (WPARAM) 0);
  202837. }
  202838. void doMouseExit()
  202839. {
  202840. isMouseOver = false;
  202841. doMouseEvent (getCurrentMousePos());
  202842. }
  202843. void doMouseWheel (const Point<int>& position, const WPARAM wParam, const bool isVertical)
  202844. {
  202845. updateKeyModifiers();
  202846. const float amount = jlimit (-1000.0f, 1000.0f, 0.75f * (short) HIWORD (wParam));
  202847. handleMouseWheel (0, position, getMouseEventTime(),
  202848. isVertical ? 0.0f : amount,
  202849. isVertical ? amount : 0.0f);
  202850. }
  202851. void sendModifierKeyChangeIfNeeded()
  202852. {
  202853. if (modifiersAtLastCallback != currentModifiers)
  202854. {
  202855. modifiersAtLastCallback = currentModifiers;
  202856. handleModifierKeysChange();
  202857. }
  202858. }
  202859. bool doKeyUp (const WPARAM key)
  202860. {
  202861. updateKeyModifiers();
  202862. switch (key)
  202863. {
  202864. case VK_SHIFT:
  202865. case VK_CONTROL:
  202866. case VK_MENU:
  202867. case VK_CAPITAL:
  202868. case VK_LWIN:
  202869. case VK_RWIN:
  202870. case VK_APPS:
  202871. case VK_NUMLOCK:
  202872. case VK_SCROLL:
  202873. case VK_LSHIFT:
  202874. case VK_RSHIFT:
  202875. case VK_LCONTROL:
  202876. case VK_LMENU:
  202877. case VK_RCONTROL:
  202878. case VK_RMENU:
  202879. sendModifierKeyChangeIfNeeded();
  202880. }
  202881. return handleKeyUpOrDown (false)
  202882. || Component::getCurrentlyModalComponent() != 0;
  202883. }
  202884. bool doKeyDown (const WPARAM key)
  202885. {
  202886. updateKeyModifiers();
  202887. bool used = false;
  202888. switch (key)
  202889. {
  202890. case VK_SHIFT:
  202891. case VK_LSHIFT:
  202892. case VK_RSHIFT:
  202893. case VK_CONTROL:
  202894. case VK_LCONTROL:
  202895. case VK_RCONTROL:
  202896. case VK_MENU:
  202897. case VK_LMENU:
  202898. case VK_RMENU:
  202899. case VK_LWIN:
  202900. case VK_RWIN:
  202901. case VK_CAPITAL:
  202902. case VK_NUMLOCK:
  202903. case VK_SCROLL:
  202904. case VK_APPS:
  202905. sendModifierKeyChangeIfNeeded();
  202906. break;
  202907. case VK_LEFT:
  202908. case VK_RIGHT:
  202909. case VK_UP:
  202910. case VK_DOWN:
  202911. case VK_PRIOR:
  202912. case VK_NEXT:
  202913. case VK_HOME:
  202914. case VK_END:
  202915. case VK_DELETE:
  202916. case VK_INSERT:
  202917. case VK_F1:
  202918. case VK_F2:
  202919. case VK_F3:
  202920. case VK_F4:
  202921. case VK_F5:
  202922. case VK_F6:
  202923. case VK_F7:
  202924. case VK_F8:
  202925. case VK_F9:
  202926. case VK_F10:
  202927. case VK_F11:
  202928. case VK_F12:
  202929. case VK_F13:
  202930. case VK_F14:
  202931. case VK_F15:
  202932. case VK_F16:
  202933. used = handleKeyUpOrDown (true);
  202934. used = handleKeyPress (extendedKeyModifier | (int) key, 0) || used;
  202935. break;
  202936. case VK_ADD:
  202937. case VK_SUBTRACT:
  202938. case VK_MULTIPLY:
  202939. case VK_DIVIDE:
  202940. case VK_SEPARATOR:
  202941. case VK_DECIMAL:
  202942. used = handleKeyUpOrDown (true);
  202943. break;
  202944. default:
  202945. used = handleKeyUpOrDown (true);
  202946. {
  202947. MSG msg;
  202948. if (! PeekMessage (&msg, hwnd, WM_CHAR, WM_DEADCHAR, PM_NOREMOVE))
  202949. {
  202950. // if there isn't a WM_CHAR or WM_DEADCHAR message pending, we need to
  202951. // manually generate the key-press event that matches this key-down.
  202952. const UINT keyChar = MapVirtualKey (key, 2);
  202953. used = handleKeyPress ((int) LOWORD (keyChar), 0) || used;
  202954. }
  202955. }
  202956. break;
  202957. }
  202958. if (Component::getCurrentlyModalComponent() != 0)
  202959. used = true;
  202960. return used;
  202961. }
  202962. bool doKeyChar (int key, const LPARAM flags)
  202963. {
  202964. updateKeyModifiers();
  202965. juce_wchar textChar = (juce_wchar) key;
  202966. const int virtualScanCode = (flags >> 16) & 0xff;
  202967. if (key >= '0' && key <= '9')
  202968. {
  202969. switch (virtualScanCode) // check for a numeric keypad scan-code
  202970. {
  202971. case 0x52:
  202972. case 0x4f:
  202973. case 0x50:
  202974. case 0x51:
  202975. case 0x4b:
  202976. case 0x4c:
  202977. case 0x4d:
  202978. case 0x47:
  202979. case 0x48:
  202980. case 0x49:
  202981. key = (key - '0') + KeyPress::numberPad0;
  202982. break;
  202983. default:
  202984. break;
  202985. }
  202986. }
  202987. else
  202988. {
  202989. // convert the scan code to an unmodified character code..
  202990. const UINT virtualKey = MapVirtualKey (virtualScanCode, 1);
  202991. UINT keyChar = MapVirtualKey (virtualKey, 2);
  202992. keyChar = LOWORD (keyChar);
  202993. if (keyChar != 0)
  202994. key = (int) keyChar;
  202995. // avoid sending junk text characters for some control-key combinations
  202996. if (textChar < ' ' && currentModifiers.testFlags (ModifierKeys::ctrlModifier | ModifierKeys::altModifier))
  202997. textChar = 0;
  202998. }
  202999. return handleKeyPress (key, textChar);
  203000. }
  203001. bool doAppCommand (const LPARAM lParam)
  203002. {
  203003. int key = 0;
  203004. switch (GET_APPCOMMAND_LPARAM (lParam))
  203005. {
  203006. case APPCOMMAND_MEDIA_PLAY_PAUSE:
  203007. key = KeyPress::playKey;
  203008. break;
  203009. case APPCOMMAND_MEDIA_STOP:
  203010. key = KeyPress::stopKey;
  203011. break;
  203012. case APPCOMMAND_MEDIA_NEXTTRACK:
  203013. key = KeyPress::fastForwardKey;
  203014. break;
  203015. case APPCOMMAND_MEDIA_PREVIOUSTRACK:
  203016. key = KeyPress::rewindKey;
  203017. break;
  203018. }
  203019. if (key != 0)
  203020. {
  203021. updateKeyModifiers();
  203022. if (hwnd == GetActiveWindow())
  203023. {
  203024. handleKeyPress (key, 0);
  203025. return true;
  203026. }
  203027. }
  203028. return false;
  203029. }
  203030. class JuceDropTarget : public ComBaseClassHelper <IDropTarget>
  203031. {
  203032. public:
  203033. JuceDropTarget (Win32ComponentPeer* const owner_)
  203034. : owner (owner_)
  203035. {
  203036. }
  203037. ~JuceDropTarget() {}
  203038. HRESULT __stdcall DragEnter (IDataObject* pDataObject, DWORD /*grfKeyState*/, POINTL mousePos, DWORD* pdwEffect)
  203039. {
  203040. updateFileList (pDataObject);
  203041. owner->handleFileDragMove (files, owner->globalPositionToRelative (Point<int> (mousePos.x, mousePos.y)));
  203042. *pdwEffect = DROPEFFECT_COPY;
  203043. return S_OK;
  203044. }
  203045. HRESULT __stdcall DragLeave()
  203046. {
  203047. owner->handleFileDragExit (files);
  203048. return S_OK;
  203049. }
  203050. HRESULT __stdcall DragOver (DWORD /*grfKeyState*/, POINTL mousePos, DWORD* pdwEffect)
  203051. {
  203052. owner->handleFileDragMove (files, owner->globalPositionToRelative (Point<int> (mousePos.x, mousePos.y)));
  203053. *pdwEffect = DROPEFFECT_COPY;
  203054. return S_OK;
  203055. }
  203056. HRESULT __stdcall Drop (IDataObject* pDataObject, DWORD /*grfKeyState*/, POINTL mousePos, DWORD* pdwEffect)
  203057. {
  203058. updateFileList (pDataObject);
  203059. owner->handleFileDragDrop (files, owner->globalPositionToRelative (Point<int> (mousePos.x, mousePos.y)));
  203060. *pdwEffect = DROPEFFECT_COPY;
  203061. return S_OK;
  203062. }
  203063. private:
  203064. Win32ComponentPeer* const owner;
  203065. StringArray files;
  203066. void updateFileList (IDataObject* const pDataObject)
  203067. {
  203068. files.clear();
  203069. FORMATETC format = { CF_HDROP, 0, DVASPECT_CONTENT, -1, TYMED_HGLOBAL };
  203070. STGMEDIUM medium = { TYMED_HGLOBAL, { 0 }, 0 };
  203071. if (pDataObject->GetData (&format, &medium) == S_OK)
  203072. {
  203073. const SIZE_T totalLen = GlobalSize (medium.hGlobal);
  203074. const LPDROPFILES pDropFiles = (const LPDROPFILES) GlobalLock (medium.hGlobal);
  203075. unsigned int i = 0;
  203076. if (pDropFiles->fWide)
  203077. {
  203078. const WCHAR* const fname = (WCHAR*) (((const char*) pDropFiles) + sizeof (DROPFILES));
  203079. for (;;)
  203080. {
  203081. unsigned int len = 0;
  203082. while (i + len < totalLen && fname [i + len] != 0)
  203083. ++len;
  203084. if (len == 0)
  203085. break;
  203086. files.add (String (fname + i, len));
  203087. i += len + 1;
  203088. }
  203089. }
  203090. else
  203091. {
  203092. const char* const fname = ((const char*) pDropFiles) + sizeof (DROPFILES);
  203093. for (;;)
  203094. {
  203095. unsigned int len = 0;
  203096. while (i + len < totalLen && fname [i + len] != 0)
  203097. ++len;
  203098. if (len == 0)
  203099. break;
  203100. files.add (String (fname + i, len));
  203101. i += len + 1;
  203102. }
  203103. }
  203104. GlobalUnlock (medium.hGlobal);
  203105. }
  203106. }
  203107. JuceDropTarget (const JuceDropTarget&);
  203108. JuceDropTarget& operator= (const JuceDropTarget&);
  203109. };
  203110. void doSettingChange()
  203111. {
  203112. Desktop::getInstance().refreshMonitorSizes();
  203113. if (fullScreen && ! isMinimised())
  203114. {
  203115. const Rectangle<int> r (component->getParentMonitorArea());
  203116. SetWindowPos (hwnd, 0,
  203117. r.getX(), r.getY(), r.getWidth(), r.getHeight(),
  203118. SWP_NOACTIVATE | SWP_NOOWNERZORDER | SWP_NOZORDER | SWP_NOSENDCHANGING);
  203119. }
  203120. }
  203121. public:
  203122. static LRESULT CALLBACK windowProc (HWND h, UINT message, WPARAM wParam, LPARAM lParam)
  203123. {
  203124. Win32ComponentPeer* const peer = getOwnerOfWindow (h);
  203125. if (peer != 0)
  203126. return peer->peerWindowProc (h, message, wParam, lParam);
  203127. return DefWindowProcW (h, message, wParam, lParam);
  203128. }
  203129. private:
  203130. static const Point<int> getPointFromLParam (LPARAM lParam) throw()
  203131. {
  203132. return Point<int> (GET_X_LPARAM (lParam), GET_Y_LPARAM (lParam));
  203133. }
  203134. const Point<int> getCurrentMousePos() throw()
  203135. {
  203136. RECT wr;
  203137. GetWindowRect (hwnd, &wr);
  203138. const DWORD mp = GetMessagePos();
  203139. return Point<int> (GET_X_LPARAM (mp) - wr.left - windowBorder.getLeft(),
  203140. GET_Y_LPARAM (mp) - wr.top - windowBorder.getTop());
  203141. }
  203142. LRESULT peerWindowProc (HWND h, UINT message, WPARAM wParam, LPARAM lParam)
  203143. {
  203144. if (isValidPeer (this))
  203145. {
  203146. switch (message)
  203147. {
  203148. case WM_NCHITTEST:
  203149. if ((styleFlags & windowIgnoresMouseClicks) != 0)
  203150. return HTTRANSPARENT;
  203151. if (hasTitleBar())
  203152. break;
  203153. return HTCLIENT;
  203154. case WM_PAINT:
  203155. handlePaintMessage();
  203156. return 0;
  203157. case WM_NCPAINT:
  203158. if (wParam != 1)
  203159. handlePaintMessage();
  203160. if (hasTitleBar())
  203161. break;
  203162. return 0;
  203163. case WM_ERASEBKGND:
  203164. case WM_NCCALCSIZE:
  203165. if (hasTitleBar())
  203166. break;
  203167. return 1;
  203168. case WM_MOUSEMOVE:
  203169. doMouseMove (getPointFromLParam (lParam));
  203170. return 0;
  203171. case WM_MOUSELEAVE:
  203172. doMouseExit();
  203173. return 0;
  203174. case WM_LBUTTONDOWN:
  203175. case WM_MBUTTONDOWN:
  203176. case WM_RBUTTONDOWN:
  203177. doMouseDown (getPointFromLParam (lParam), wParam);
  203178. return 0;
  203179. case WM_LBUTTONUP:
  203180. case WM_MBUTTONUP:
  203181. case WM_RBUTTONUP:
  203182. doMouseUp (getPointFromLParam (lParam), wParam);
  203183. return 0;
  203184. case WM_CAPTURECHANGED:
  203185. doCaptureChanged();
  203186. return 0;
  203187. case WM_NCMOUSEMOVE:
  203188. if (hasTitleBar())
  203189. break;
  203190. return 0;
  203191. case 0x020A: /* WM_MOUSEWHEEL */
  203192. doMouseWheel (getCurrentMousePos(), wParam, true);
  203193. return 0;
  203194. case 0x020E: /* WM_MOUSEHWHEEL */
  203195. doMouseWheel (getCurrentMousePos(), wParam, false);
  203196. return 0;
  203197. case WM_WINDOWPOSCHANGING:
  203198. if ((styleFlags & (windowHasTitleBar | windowIsResizable)) == (windowHasTitleBar | windowIsResizable))
  203199. {
  203200. WINDOWPOS* const wp = (WINDOWPOS*) lParam;
  203201. if ((wp->flags & (SWP_NOMOVE | SWP_NOSIZE)) != (SWP_NOMOVE | SWP_NOSIZE))
  203202. {
  203203. if (constrainer != 0)
  203204. {
  203205. const Rectangle<int> current (component->getX() - windowBorder.getLeft(),
  203206. component->getY() - windowBorder.getTop(),
  203207. component->getWidth() + windowBorder.getLeftAndRight(),
  203208. component->getHeight() + windowBorder.getTopAndBottom());
  203209. Rectangle<int> pos (wp->x, wp->y, wp->cx, wp->cy);
  203210. constrainer->checkBounds (pos, current,
  203211. Desktop::getInstance().getAllMonitorDisplayAreas().getBounds(),
  203212. pos.getY() != current.getY() && pos.getBottom() == current.getBottom(),
  203213. pos.getX() != current.getX() && pos.getRight() == current.getRight(),
  203214. pos.getY() == current.getY() && pos.getBottom() != current.getBottom(),
  203215. pos.getX() == current.getX() && pos.getRight() != current.getRight());
  203216. wp->x = pos.getX();
  203217. wp->y = pos.getY();
  203218. wp->cx = pos.getWidth();
  203219. wp->cy = pos.getHeight();
  203220. }
  203221. }
  203222. }
  203223. return 0;
  203224. case WM_WINDOWPOSCHANGED:
  203225. handleMovedOrResized();
  203226. if (dontRepaint)
  203227. break; // needed for non-accelerated openGL windows to draw themselves correctly..
  203228. return 0;
  203229. case WM_KEYDOWN:
  203230. case WM_SYSKEYDOWN:
  203231. if (doKeyDown (wParam))
  203232. return 0;
  203233. break;
  203234. case WM_KEYUP:
  203235. case WM_SYSKEYUP:
  203236. if (doKeyUp (wParam))
  203237. return 0;
  203238. break;
  203239. case WM_CHAR:
  203240. if (doKeyChar ((int) wParam, lParam))
  203241. return 0;
  203242. break;
  203243. case WM_APPCOMMAND:
  203244. if (doAppCommand (lParam))
  203245. return TRUE;
  203246. break;
  203247. case WM_SETFOCUS:
  203248. updateKeyModifiers();
  203249. handleFocusGain();
  203250. break;
  203251. case WM_KILLFOCUS:
  203252. if (hasCreatedCaret)
  203253. {
  203254. hasCreatedCaret = false;
  203255. DestroyCaret();
  203256. }
  203257. handleFocusLoss();
  203258. break;
  203259. case WM_ACTIVATEAPP:
  203260. // Windows does weird things to process priority when you swap apps,
  203261. // so this forces an update when the app is brought to the front
  203262. if (wParam != FALSE)
  203263. juce_repeatLastProcessPriority();
  203264. else
  203265. Desktop::getInstance().setKioskModeComponent (0); // turn kiosk mode off if we lose focus
  203266. juce_CheckCurrentlyFocusedTopLevelWindow();
  203267. modifiersAtLastCallback = -1;
  203268. return 0;
  203269. case WM_ACTIVATE:
  203270. if (LOWORD (wParam) == WA_ACTIVE || LOWORD (wParam) == WA_CLICKACTIVE)
  203271. {
  203272. modifiersAtLastCallback = -1;
  203273. updateKeyModifiers();
  203274. if (isMinimised())
  203275. {
  203276. component->repaint();
  203277. handleMovedOrResized();
  203278. if (! ComponentPeer::isValidPeer (this))
  203279. return 0;
  203280. }
  203281. if (LOWORD (wParam) == WA_CLICKACTIVE
  203282. && component->isCurrentlyBlockedByAnotherModalComponent())
  203283. {
  203284. const Point<int> mousePos (component->getMouseXYRelative());
  203285. Component* const underMouse = component->getComponentAt (mousePos.getX(), mousePos.getY());
  203286. if (underMouse != 0 && underMouse->isCurrentlyBlockedByAnotherModalComponent())
  203287. Component::getCurrentlyModalComponent()->inputAttemptWhenModal();
  203288. return 0;
  203289. }
  203290. handleBroughtToFront();
  203291. if (component->isCurrentlyBlockedByAnotherModalComponent())
  203292. Component::getCurrentlyModalComponent()->toFront (true);
  203293. return 0;
  203294. }
  203295. break;
  203296. case WM_NCACTIVATE:
  203297. // while a temporary window is being shown, prevent Windows from deactivating the
  203298. // title bars of our main windows.
  203299. if (wParam == 0 && ! shouldDeactivateTitleBar)
  203300. wParam = TRUE; // change this and let it get passed to the DefWindowProc.
  203301. break;
  203302. case WM_MOUSEACTIVATE:
  203303. if (! component->getMouseClickGrabsKeyboardFocus())
  203304. return MA_NOACTIVATE;
  203305. break;
  203306. case WM_SHOWWINDOW:
  203307. if (wParam != 0)
  203308. handleBroughtToFront();
  203309. break;
  203310. case WM_CLOSE:
  203311. if (! component->isCurrentlyBlockedByAnotherModalComponent())
  203312. handleUserClosingWindow();
  203313. return 0;
  203314. case WM_QUERYENDSESSION:
  203315. if (JUCEApplication::getInstance() != 0)
  203316. {
  203317. JUCEApplication::getInstance()->systemRequestedQuit();
  203318. return MessageManager::getInstance()->hasStopMessageBeenSent();
  203319. }
  203320. return TRUE;
  203321. case WM_TRAYNOTIFY:
  203322. if (component->isCurrentlyBlockedByAnotherModalComponent())
  203323. {
  203324. if (lParam == WM_LBUTTONDOWN || lParam == WM_RBUTTONDOWN
  203325. || lParam == WM_LBUTTONDBLCLK || lParam == WM_LBUTTONDBLCLK)
  203326. {
  203327. Component* const current = Component::getCurrentlyModalComponent();
  203328. if (current != 0)
  203329. current->inputAttemptWhenModal();
  203330. }
  203331. }
  203332. else
  203333. {
  203334. ModifierKeys eventMods (ModifierKeys::getCurrentModifiersRealtime());
  203335. if (lParam == WM_LBUTTONDOWN || lParam == WM_LBUTTONDBLCLK)
  203336. eventMods = eventMods.withFlags (ModifierKeys::leftButtonModifier);
  203337. else if (lParam == WM_RBUTTONDOWN || lParam == WM_RBUTTONDBLCLK)
  203338. eventMods = eventMods.withFlags (ModifierKeys::rightButtonModifier);
  203339. else if (lParam == WM_LBUTTONUP || lParam == WM_RBUTTONUP)
  203340. eventMods = eventMods.withoutMouseButtons();
  203341. const MouseEvent e (Desktop::getInstance().getMainMouseSource(),
  203342. Point<int>(), eventMods, component, getMouseEventTime(),
  203343. Point<int>(), getMouseEventTime(), 1, false);
  203344. if (lParam == WM_LBUTTONDOWN || lParam == WM_RBUTTONDOWN)
  203345. {
  203346. SetFocus (hwnd);
  203347. SetForegroundWindow (hwnd);
  203348. component->mouseDown (e);
  203349. }
  203350. else if (lParam == WM_LBUTTONUP || lParam == WM_RBUTTONUP)
  203351. {
  203352. component->mouseUp (e);
  203353. }
  203354. else if (lParam == WM_LBUTTONDBLCLK || lParam == WM_LBUTTONDBLCLK)
  203355. {
  203356. component->mouseDoubleClick (e);
  203357. }
  203358. else if (lParam == WM_MOUSEMOVE)
  203359. {
  203360. component->mouseMove (e);
  203361. }
  203362. }
  203363. break;
  203364. case WM_SYNCPAINT:
  203365. return 0;
  203366. case WM_PALETTECHANGED:
  203367. InvalidateRect (h, 0, 0);
  203368. break;
  203369. case WM_DISPLAYCHANGE:
  203370. InvalidateRect (h, 0, 0);
  203371. createPaletteIfNeeded = true;
  203372. // intentional fall-through...
  203373. case WM_SETTINGCHANGE: // note the fall-through in the previous case!
  203374. doSettingChange();
  203375. break;
  203376. case WM_INITMENU:
  203377. if (! hasTitleBar())
  203378. {
  203379. if (isFullScreen())
  203380. {
  203381. EnableMenuItem ((HMENU) wParam, SC_RESTORE, MF_BYCOMMAND | MF_ENABLED);
  203382. EnableMenuItem ((HMENU) wParam, SC_MOVE, MF_BYCOMMAND | MF_GRAYED);
  203383. }
  203384. else if (! isMinimised())
  203385. {
  203386. EnableMenuItem ((HMENU) wParam, SC_MAXIMIZE, MF_BYCOMMAND | MF_GRAYED);
  203387. }
  203388. }
  203389. break;
  203390. case WM_SYSCOMMAND:
  203391. switch (wParam & 0xfff0)
  203392. {
  203393. case SC_CLOSE:
  203394. if (sendInputAttemptWhenModalMessage())
  203395. return 0;
  203396. if (hasTitleBar())
  203397. {
  203398. PostMessage (h, WM_CLOSE, 0, 0);
  203399. return 0;
  203400. }
  203401. break;
  203402. case SC_KEYMENU:
  203403. // (NB mustn't call sendInputAttemptWhenModalMessage() here because of very
  203404. // obscure situations that can arise if a modal loop is started from an alt-key
  203405. // keypress).
  203406. if (hasTitleBar() && h == GetCapture())
  203407. ReleaseCapture();
  203408. break;
  203409. case SC_MAXIMIZE:
  203410. if (sendInputAttemptWhenModalMessage())
  203411. return 0;
  203412. setFullScreen (true);
  203413. return 0;
  203414. case SC_MINIMIZE:
  203415. if (sendInputAttemptWhenModalMessage())
  203416. return 0;
  203417. if (! hasTitleBar())
  203418. {
  203419. setMinimised (true);
  203420. return 0;
  203421. }
  203422. break;
  203423. case SC_RESTORE:
  203424. if (sendInputAttemptWhenModalMessage())
  203425. return 0;
  203426. if (hasTitleBar())
  203427. {
  203428. if (isFullScreen())
  203429. {
  203430. setFullScreen (false);
  203431. return 0;
  203432. }
  203433. }
  203434. else
  203435. {
  203436. if (isMinimised())
  203437. setMinimised (false);
  203438. else if (isFullScreen())
  203439. setFullScreen (false);
  203440. return 0;
  203441. }
  203442. break;
  203443. }
  203444. break;
  203445. case WM_NCLBUTTONDOWN:
  203446. case WM_NCRBUTTONDOWN:
  203447. case WM_NCMBUTTONDOWN:
  203448. sendInputAttemptWhenModalMessage();
  203449. break;
  203450. //case WM_IME_STARTCOMPOSITION;
  203451. // return 0;
  203452. case WM_GETDLGCODE:
  203453. return DLGC_WANTALLKEYS;
  203454. default:
  203455. break;
  203456. }
  203457. }
  203458. return DefWindowProcW (h, message, wParam, lParam);
  203459. }
  203460. bool sendInputAttemptWhenModalMessage()
  203461. {
  203462. if (component->isCurrentlyBlockedByAnotherModalComponent())
  203463. {
  203464. Component* const current = Component::getCurrentlyModalComponent();
  203465. if (current != 0)
  203466. current->inputAttemptWhenModal();
  203467. return true;
  203468. }
  203469. return false;
  203470. }
  203471. Win32ComponentPeer (const Win32ComponentPeer&);
  203472. Win32ComponentPeer& operator= (const Win32ComponentPeer&);
  203473. };
  203474. ModifierKeys Win32ComponentPeer::currentModifiers;
  203475. ModifierKeys Win32ComponentPeer::modifiersAtLastCallback;
  203476. ComponentPeer* Component::createNewPeer (int styleFlags, void* /*nativeWindowToAttachTo*/)
  203477. {
  203478. return new Win32ComponentPeer (this, styleFlags);
  203479. }
  203480. juce_ImplementSingleton_SingleThreaded (Win32ComponentPeer::WindowClassHolder);
  203481. void ModifierKeys::updateCurrentModifiers() throw()
  203482. {
  203483. currentModifiers = Win32ComponentPeer::currentModifiers;
  203484. }
  203485. const ModifierKeys ModifierKeys::getCurrentModifiersRealtime() throw()
  203486. {
  203487. Win32ComponentPeer::updateKeyModifiers();
  203488. int keyMods = 0;
  203489. if ((GetKeyState (VK_LBUTTON) & 0x8000) != 0) keyMods |= ModifierKeys::leftButtonModifier;
  203490. if ((GetKeyState (VK_RBUTTON) & 0x8000) != 0) keyMods |= ModifierKeys::rightButtonModifier;
  203491. if ((GetKeyState (VK_MBUTTON) & 0x8000) != 0) keyMods |= ModifierKeys::middleButtonModifier;
  203492. Win32ComponentPeer::currentModifiers
  203493. = Win32ComponentPeer::currentModifiers.withOnlyMouseButtons().withFlags (keyMods);
  203494. return Win32ComponentPeer::currentModifiers;
  203495. }
  203496. void SystemTrayIconComponent::setIconImage (const Image& newImage)
  203497. {
  203498. Win32ComponentPeer* const wp = dynamic_cast <Win32ComponentPeer*> (getPeer());
  203499. if (wp != 0)
  203500. wp->setTaskBarIcon (&newImage);
  203501. }
  203502. void SystemTrayIconComponent::setIconTooltip (const String& tooltip)
  203503. {
  203504. Win32ComponentPeer* const wp = dynamic_cast <Win32ComponentPeer*> (getPeer());
  203505. if (wp != 0)
  203506. wp->setTaskBarIconToolTip (tooltip);
  203507. }
  203508. void juce_setWindowStyleBit (HWND h, const int styleType, const int feature, const bool bitIsSet) throw()
  203509. {
  203510. DWORD val = GetWindowLong (h, styleType);
  203511. if (bitIsSet)
  203512. val |= feature;
  203513. else
  203514. val &= ~feature;
  203515. SetWindowLongPtr (h, styleType, val);
  203516. SetWindowPos (h, 0, 0, 0, 0, 0,
  203517. SWP_NOACTIVATE | SWP_NOMOVE | SWP_NOSIZE | SWP_NOZORDER
  203518. | SWP_NOOWNERZORDER | SWP_FRAMECHANGED | SWP_NOSENDCHANGING);
  203519. }
  203520. bool Process::isForegroundProcess()
  203521. {
  203522. HWND fg = GetForegroundWindow();
  203523. if (fg == 0)
  203524. return true;
  203525. // when running as a plugin in IE8, the browser UI runs in a different process to the plugin, so
  203526. // process ID isn't a reliable way to check if the foreground window belongs to us - instead, we
  203527. // have to see if any of our windows are children of the foreground window
  203528. fg = GetAncestor (fg, GA_ROOT);
  203529. for (int i = ComponentPeer::getNumPeers(); --i >= 0;)
  203530. {
  203531. Win32ComponentPeer* const wp = dynamic_cast <Win32ComponentPeer*> (ComponentPeer::getPeer (i));
  203532. if (wp != 0 && wp->isInside (fg))
  203533. return true;
  203534. }
  203535. return false;
  203536. }
  203537. bool AlertWindow::showNativeDialogBox (const String& title,
  203538. const String& bodyText,
  203539. bool isOkCancel)
  203540. {
  203541. return MessageBox (0, bodyText, title,
  203542. MB_SETFOREGROUND | (isOkCancel ? MB_OKCANCEL
  203543. : MB_OK)) == IDOK;
  203544. }
  203545. void Desktop::createMouseInputSources()
  203546. {
  203547. mouseSources.add (new MouseInputSource (0, true));
  203548. }
  203549. const Point<int> Desktop::getMousePosition()
  203550. {
  203551. POINT mousePos;
  203552. GetCursorPos (&mousePos);
  203553. return Point<int> (mousePos.x, mousePos.y);
  203554. }
  203555. void Desktop::setMousePosition (const Point<int>& newPosition)
  203556. {
  203557. SetCursorPos (newPosition.getX(), newPosition.getY());
  203558. }
  203559. Image* Image::createNativeImage (const PixelFormat format, const int imageWidth, const int imageHeight, const bool clearImage)
  203560. {
  203561. return new Image (format, imageWidth, imageHeight, clearImage);
  203562. }
  203563. class ScreenSaverDefeater : public Timer,
  203564. public DeletedAtShutdown
  203565. {
  203566. public:
  203567. ScreenSaverDefeater() throw()
  203568. {
  203569. startTimer (10000);
  203570. timerCallback();
  203571. }
  203572. ~ScreenSaverDefeater() {}
  203573. void timerCallback()
  203574. {
  203575. if (Process::isForegroundProcess())
  203576. {
  203577. // simulate a shift key getting pressed..
  203578. INPUT input[2];
  203579. input[0].type = INPUT_KEYBOARD;
  203580. input[0].ki.wVk = VK_SHIFT;
  203581. input[0].ki.dwFlags = 0;
  203582. input[0].ki.dwExtraInfo = 0;
  203583. input[1].type = INPUT_KEYBOARD;
  203584. input[1].ki.wVk = VK_SHIFT;
  203585. input[1].ki.dwFlags = KEYEVENTF_KEYUP;
  203586. input[1].ki.dwExtraInfo = 0;
  203587. SendInput (2, input, sizeof (INPUT));
  203588. }
  203589. }
  203590. };
  203591. static ScreenSaverDefeater* screenSaverDefeater = 0;
  203592. void Desktop::setScreenSaverEnabled (const bool isEnabled) throw()
  203593. {
  203594. if (isEnabled)
  203595. {
  203596. deleteAndZero (screenSaverDefeater);
  203597. }
  203598. else if (screenSaverDefeater == 0)
  203599. {
  203600. screenSaverDefeater = new ScreenSaverDefeater();
  203601. }
  203602. }
  203603. bool Desktop::isScreenSaverEnabled() throw()
  203604. {
  203605. return screenSaverDefeater == 0;
  203606. }
  203607. /* (The code below is the "correct" way to disable the screen saver, but it
  203608. completely fails on winXP when the saver is password-protected...)
  203609. static bool juce_screenSaverEnabled = true;
  203610. void Desktop::setScreenSaverEnabled (const bool isEnabled) throw()
  203611. {
  203612. juce_screenSaverEnabled = isEnabled;
  203613. SetThreadExecutionState (isEnabled ? ES_CONTINUOUS
  203614. : (ES_DISPLAY_REQUIRED | ES_CONTINUOUS));
  203615. }
  203616. bool Desktop::isScreenSaverEnabled() throw()
  203617. {
  203618. return juce_screenSaverEnabled;
  203619. }
  203620. */
  203621. void juce_setKioskComponent (Component* kioskModeComponent, bool enableOrDisable, bool /*allowMenusAndBars*/)
  203622. {
  203623. if (enableOrDisable)
  203624. kioskModeComponent->setBounds (Desktop::getInstance().getMainMonitorArea (false));
  203625. }
  203626. static BOOL CALLBACK enumMonitorsProc (HMONITOR, HDC, LPRECT r, LPARAM userInfo)
  203627. {
  203628. Array <Rectangle<int> >* const monitorCoords = (Array <Rectangle<int> >*) userInfo;
  203629. monitorCoords->add (Rectangle<int> (r->left, r->top, r->right - r->left, r->bottom - r->top));
  203630. return TRUE;
  203631. }
  203632. void juce_updateMultiMonitorInfo (Array <Rectangle<int> >& monitorCoords, const bool clipToWorkArea)
  203633. {
  203634. EnumDisplayMonitors (0, 0, &enumMonitorsProc, (LPARAM) &monitorCoords);
  203635. // make sure the first in the list is the main monitor
  203636. for (int i = 1; i < monitorCoords.size(); ++i)
  203637. if (monitorCoords[i].getX() == 0 && monitorCoords[i].getY() == 0)
  203638. monitorCoords.swap (i, 0);
  203639. if (monitorCoords.size() == 0)
  203640. {
  203641. RECT r;
  203642. GetWindowRect (GetDesktopWindow(), &r);
  203643. monitorCoords.add (Rectangle<int> (r.left, r.top, r.right - r.left, r.bottom - r.top));
  203644. }
  203645. if (clipToWorkArea)
  203646. {
  203647. // clip the main monitor to the active non-taskbar area
  203648. RECT r;
  203649. SystemParametersInfo (SPI_GETWORKAREA, 0, &r, 0);
  203650. Rectangle<int>& screen = monitorCoords.getReference (0);
  203651. screen.setPosition (jmax (screen.getX(), (int) r.left),
  203652. jmax (screen.getY(), (int) r.top));
  203653. screen.setSize (jmin (screen.getRight(), (int) r.right) - screen.getX(),
  203654. jmin (screen.getBottom(), (int) r.bottom) - screen.getY());
  203655. }
  203656. }
  203657. static Image* createImageFromHBITMAP (HBITMAP bitmap) throw()
  203658. {
  203659. Image* im = 0;
  203660. if (bitmap != 0)
  203661. {
  203662. BITMAP bm;
  203663. if (GetObject (bitmap, sizeof (BITMAP), &bm)
  203664. && bm.bmWidth > 0 && bm.bmHeight > 0)
  203665. {
  203666. HDC tempDC = GetDC (0);
  203667. HDC dc = CreateCompatibleDC (tempDC);
  203668. ReleaseDC (0, tempDC);
  203669. SelectObject (dc, bitmap);
  203670. im = new Image (Image::ARGB, bm.bmWidth, bm.bmHeight, true);
  203671. for (int y = bm.bmHeight; --y >= 0;)
  203672. {
  203673. for (int x = bm.bmWidth; --x >= 0;)
  203674. {
  203675. COLORREF col = GetPixel (dc, x, y);
  203676. im->setPixelAt (x, y, Colour ((uint8) GetRValue (col),
  203677. (uint8) GetGValue (col),
  203678. (uint8) GetBValue (col)));
  203679. }
  203680. }
  203681. DeleteDC (dc);
  203682. }
  203683. }
  203684. return im;
  203685. }
  203686. static Image* createImageFromHICON (HICON icon) throw()
  203687. {
  203688. ICONINFO info;
  203689. if (GetIconInfo (icon, &info))
  203690. {
  203691. ScopedPointer<Image> mask (createImageFromHBITMAP (info.hbmMask));
  203692. if (mask == 0)
  203693. return 0;
  203694. ScopedPointer<Image> image (createImageFromHBITMAP (info.hbmColor));
  203695. if (image == 0)
  203696. return mask.release();
  203697. for (int y = image->getHeight(); --y >= 0;)
  203698. {
  203699. for (int x = image->getWidth(); --x >= 0;)
  203700. {
  203701. const float brightness = mask->getPixelAt (x, y).getBrightness();
  203702. if (brightness > 0.0f)
  203703. image->multiplyAlphaAt (x, y, 1.0f - brightness);
  203704. }
  203705. }
  203706. return image.release();
  203707. }
  203708. return 0;
  203709. }
  203710. static HICON createHICONFromImage (const Image& image, const BOOL isIcon, int hotspotX, int hotspotY) throw()
  203711. {
  203712. WindowsBitmapImage bitmap (Image::ARGB, image.getWidth(), image.getHeight(), true);
  203713. {
  203714. Graphics g (bitmap);
  203715. g.drawImageAt (&image, 0, 0);
  203716. }
  203717. HBITMAP mask = CreateBitmap (image.getWidth(), image.getHeight(), 1, 1, 0);
  203718. ICONINFO info;
  203719. info.fIcon = isIcon;
  203720. info.xHotspot = hotspotX;
  203721. info.yHotspot = hotspotY;
  203722. info.hbmMask = mask;
  203723. info.hbmColor = bitmap.hBitmap;
  203724. HICON hi = CreateIconIndirect (&info);
  203725. DeleteObject (mask);
  203726. return hi;
  203727. }
  203728. Image* juce_createIconForFile (const File& file)
  203729. {
  203730. Image* image = 0;
  203731. WCHAR filename [1024];
  203732. file.getFullPathName().copyToUnicode (filename, 1023);
  203733. WORD iconNum = 0;
  203734. HICON icon = ExtractAssociatedIcon ((HINSTANCE) PlatformUtilities::getCurrentModuleInstanceHandle(),
  203735. filename, &iconNum);
  203736. if (icon != 0)
  203737. {
  203738. image = createImageFromHICON (icon);
  203739. DestroyIcon (icon);
  203740. }
  203741. return image;
  203742. }
  203743. void* MouseCursor::createMouseCursorFromImage (const Image& image, int hotspotX, int hotspotY)
  203744. {
  203745. const int maxW = GetSystemMetrics (SM_CXCURSOR);
  203746. const int maxH = GetSystemMetrics (SM_CYCURSOR);
  203747. const Image* im = &image;
  203748. ScopedPointer<Image> newIm;
  203749. if (image.getWidth() > maxW || image.getHeight() > maxH)
  203750. {
  203751. im = newIm = image.createCopy (maxW, maxH);
  203752. hotspotX = (hotspotX * maxW) / image.getWidth();
  203753. hotspotY = (hotspotY * maxH) / image.getHeight();
  203754. }
  203755. void* cursorH = 0;
  203756. const SystemStats::OperatingSystemType os = SystemStats::getOperatingSystemType();
  203757. return createHICONFromImage (*im, FALSE, hotspotX, hotspotY);
  203758. }
  203759. void MouseCursor::deleteMouseCursor (void* const cursorHandle, const bool isStandard)
  203760. {
  203761. if (cursorHandle != 0 && ! isStandard)
  203762. DestroyCursor ((HCURSOR) cursorHandle);
  203763. }
  203764. void* MouseCursor::createStandardMouseCursor (const MouseCursor::StandardCursorType type)
  203765. {
  203766. LPCTSTR cursorName = IDC_ARROW;
  203767. switch (type)
  203768. {
  203769. case NormalCursor: break;
  203770. case NoCursor: return 0;
  203771. case WaitCursor: cursorName = IDC_WAIT; break;
  203772. case IBeamCursor: cursorName = IDC_IBEAM; break;
  203773. case PointingHandCursor: cursorName = MAKEINTRESOURCE(32649); break;
  203774. case CrosshairCursor: cursorName = IDC_CROSS; break;
  203775. case CopyingCursor: break; // can't seem to find one of these in the win32 list..
  203776. case LeftRightResizeCursor:
  203777. case LeftEdgeResizeCursor:
  203778. case RightEdgeResizeCursor: cursorName = IDC_SIZEWE; break;
  203779. case UpDownResizeCursor:
  203780. case TopEdgeResizeCursor:
  203781. case BottomEdgeResizeCursor: cursorName = IDC_SIZENS; break;
  203782. case TopLeftCornerResizeCursor:
  203783. case BottomRightCornerResizeCursor: cursorName = IDC_SIZENWSE; break;
  203784. case TopRightCornerResizeCursor:
  203785. case BottomLeftCornerResizeCursor: cursorName = IDC_SIZENESW; break;
  203786. case UpDownLeftRightResizeCursor: cursorName = IDC_SIZEALL; break;
  203787. case DraggingHandCursor:
  203788. {
  203789. static void* dragHandCursor = 0;
  203790. if (dragHandCursor == 0)
  203791. {
  203792. static const unsigned char dragHandData[] =
  203793. { 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,
  203794. 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,
  203795. 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 };
  203796. const ScopedPointer <Image> image (ImageFileFormat::loadFrom (dragHandData, sizeof (dragHandData)));
  203797. dragHandCursor = createMouseCursorFromImage (*image, 8, 7);
  203798. }
  203799. return dragHandCursor;
  203800. }
  203801. default:
  203802. jassertfalse; break;
  203803. }
  203804. HCURSOR cursorH = LoadCursor (0, cursorName);
  203805. if (cursorH == 0)
  203806. cursorH = LoadCursor (0, IDC_ARROW);
  203807. return cursorH;
  203808. }
  203809. void MouseCursor::showInWindow (ComponentPeer*) const
  203810. {
  203811. SetCursor ((HCURSOR) getHandle());
  203812. }
  203813. void MouseCursor::showInAllWindows() const
  203814. {
  203815. showInWindow (0);
  203816. }
  203817. class JuceDropSource : public ComBaseClassHelper <IDropSource>
  203818. {
  203819. public:
  203820. JuceDropSource() {}
  203821. ~JuceDropSource() {}
  203822. HRESULT __stdcall QueryContinueDrag (BOOL escapePressed, DWORD keys)
  203823. {
  203824. if (escapePressed)
  203825. return DRAGDROP_S_CANCEL;
  203826. if ((keys & (MK_LBUTTON | MK_RBUTTON)) == 0)
  203827. return DRAGDROP_S_DROP;
  203828. return S_OK;
  203829. }
  203830. HRESULT __stdcall GiveFeedback (DWORD)
  203831. {
  203832. return DRAGDROP_S_USEDEFAULTCURSORS;
  203833. }
  203834. };
  203835. class JuceEnumFormatEtc : public ComBaseClassHelper <IEnumFORMATETC>
  203836. {
  203837. public:
  203838. JuceEnumFormatEtc (const FORMATETC* const format_)
  203839. : format (format_),
  203840. index (0)
  203841. {
  203842. }
  203843. ~JuceEnumFormatEtc() {}
  203844. HRESULT __stdcall Clone (IEnumFORMATETC** result)
  203845. {
  203846. if (result == 0)
  203847. return E_POINTER;
  203848. JuceEnumFormatEtc* const newOne = new JuceEnumFormatEtc (format);
  203849. newOne->index = index;
  203850. *result = newOne;
  203851. return S_OK;
  203852. }
  203853. HRESULT __stdcall Next (ULONG celt, LPFORMATETC lpFormatEtc, ULONG* pceltFetched)
  203854. {
  203855. if (pceltFetched != 0)
  203856. *pceltFetched = 0;
  203857. else if (celt != 1)
  203858. return S_FALSE;
  203859. if (index == 0 && celt > 0 && lpFormatEtc != 0)
  203860. {
  203861. copyFormatEtc (lpFormatEtc [0], *format);
  203862. ++index;
  203863. if (pceltFetched != 0)
  203864. *pceltFetched = 1;
  203865. return S_OK;
  203866. }
  203867. return S_FALSE;
  203868. }
  203869. HRESULT __stdcall Skip (ULONG celt)
  203870. {
  203871. if (index + (int) celt >= 1)
  203872. return S_FALSE;
  203873. index += celt;
  203874. return S_OK;
  203875. }
  203876. HRESULT __stdcall Reset()
  203877. {
  203878. index = 0;
  203879. return S_OK;
  203880. }
  203881. private:
  203882. const FORMATETC* const format;
  203883. int index;
  203884. static void copyFormatEtc (FORMATETC& dest, const FORMATETC& source)
  203885. {
  203886. dest = source;
  203887. if (source.ptd != 0)
  203888. {
  203889. dest.ptd = (DVTARGETDEVICE*) CoTaskMemAlloc (sizeof (DVTARGETDEVICE));
  203890. *(dest.ptd) = *(source.ptd);
  203891. }
  203892. }
  203893. JuceEnumFormatEtc (const JuceEnumFormatEtc&);
  203894. JuceEnumFormatEtc& operator= (const JuceEnumFormatEtc&);
  203895. };
  203896. class JuceDataObject : public ComBaseClassHelper <IDataObject>
  203897. {
  203898. JuceDropSource* const dropSource;
  203899. const FORMATETC* const format;
  203900. const STGMEDIUM* const medium;
  203901. JuceDataObject (const JuceDataObject&);
  203902. JuceDataObject& operator= (const JuceDataObject&);
  203903. public:
  203904. JuceDataObject (JuceDropSource* const dropSource_,
  203905. const FORMATETC* const format_,
  203906. const STGMEDIUM* const medium_)
  203907. : dropSource (dropSource_),
  203908. format (format_),
  203909. medium (medium_)
  203910. {
  203911. }
  203912. virtual ~JuceDataObject()
  203913. {
  203914. jassert (refCount == 0);
  203915. }
  203916. HRESULT __stdcall GetData (FORMATETC __RPC_FAR* pFormatEtc, STGMEDIUM __RPC_FAR* pMedium)
  203917. {
  203918. if ((pFormatEtc->tymed & format->tymed) != 0
  203919. && pFormatEtc->cfFormat == format->cfFormat
  203920. && pFormatEtc->dwAspect == format->dwAspect)
  203921. {
  203922. pMedium->tymed = format->tymed;
  203923. pMedium->pUnkForRelease = 0;
  203924. if (format->tymed == TYMED_HGLOBAL)
  203925. {
  203926. const SIZE_T len = GlobalSize (medium->hGlobal);
  203927. void* const src = GlobalLock (medium->hGlobal);
  203928. void* const dst = GlobalAlloc (GMEM_FIXED, len);
  203929. memcpy (dst, src, len);
  203930. GlobalUnlock (medium->hGlobal);
  203931. pMedium->hGlobal = dst;
  203932. return S_OK;
  203933. }
  203934. }
  203935. return DV_E_FORMATETC;
  203936. }
  203937. HRESULT __stdcall QueryGetData (FORMATETC __RPC_FAR* f)
  203938. {
  203939. if (f == 0)
  203940. return E_INVALIDARG;
  203941. if (f->tymed == format->tymed
  203942. && f->cfFormat == format->cfFormat
  203943. && f->dwAspect == format->dwAspect)
  203944. return S_OK;
  203945. return DV_E_FORMATETC;
  203946. }
  203947. HRESULT __stdcall GetCanonicalFormatEtc (FORMATETC __RPC_FAR*, FORMATETC __RPC_FAR* pFormatEtcOut)
  203948. {
  203949. pFormatEtcOut->ptd = 0;
  203950. return E_NOTIMPL;
  203951. }
  203952. HRESULT __stdcall EnumFormatEtc (DWORD direction, IEnumFORMATETC __RPC_FAR *__RPC_FAR *result)
  203953. {
  203954. if (result == 0)
  203955. return E_POINTER;
  203956. if (direction == DATADIR_GET)
  203957. {
  203958. *result = new JuceEnumFormatEtc (format);
  203959. return S_OK;
  203960. }
  203961. *result = 0;
  203962. return E_NOTIMPL;
  203963. }
  203964. HRESULT __stdcall GetDataHere (FORMATETC __RPC_FAR*, STGMEDIUM __RPC_FAR*) { return DATA_E_FORMATETC; }
  203965. HRESULT __stdcall SetData (FORMATETC __RPC_FAR*, STGMEDIUM __RPC_FAR*, BOOL) { return E_NOTIMPL; }
  203966. HRESULT __stdcall DAdvise (FORMATETC __RPC_FAR*, DWORD, IAdviseSink __RPC_FAR*, DWORD __RPC_FAR*) { return OLE_E_ADVISENOTSUPPORTED; }
  203967. HRESULT __stdcall DUnadvise (DWORD) { return E_NOTIMPL; }
  203968. HRESULT __stdcall EnumDAdvise (IEnumSTATDATA __RPC_FAR *__RPC_FAR *) { return OLE_E_ADVISENOTSUPPORTED; }
  203969. };
  203970. static HDROP createHDrop (const StringArray& fileNames) throw()
  203971. {
  203972. int totalChars = 0;
  203973. for (int i = fileNames.size(); --i >= 0;)
  203974. totalChars += fileNames[i].length() + 1;
  203975. HDROP hDrop = (HDROP) GlobalAlloc (GMEM_MOVEABLE | GMEM_ZEROINIT,
  203976. sizeof (DROPFILES)
  203977. + sizeof (WCHAR) * (totalChars + 2));
  203978. if (hDrop != 0)
  203979. {
  203980. LPDROPFILES pDropFiles = (LPDROPFILES) GlobalLock (hDrop);
  203981. pDropFiles->pFiles = sizeof (DROPFILES);
  203982. pDropFiles->fWide = true;
  203983. WCHAR* fname = (WCHAR*) (((char*) pDropFiles) + sizeof (DROPFILES));
  203984. for (int i = 0; i < fileNames.size(); ++i)
  203985. {
  203986. fileNames[i].copyToUnicode (fname, 2048);
  203987. fname += fileNames[i].length() + 1;
  203988. }
  203989. *fname = 0;
  203990. GlobalUnlock (hDrop);
  203991. }
  203992. return hDrop;
  203993. }
  203994. static bool performDragDrop (FORMATETC* const format, STGMEDIUM* const medium, const DWORD whatToDo) throw()
  203995. {
  203996. JuceDropSource* const source = new JuceDropSource();
  203997. JuceDataObject* const data = new JuceDataObject (source, format, medium);
  203998. DWORD effect;
  203999. const HRESULT res = DoDragDrop (data, source, whatToDo, &effect);
  204000. data->Release();
  204001. source->Release();
  204002. return res == DRAGDROP_S_DROP;
  204003. }
  204004. bool DragAndDropContainer::performExternalDragDropOfFiles (const StringArray& files, const bool canMove)
  204005. {
  204006. FORMATETC format = { CF_HDROP, 0, DVASPECT_CONTENT, -1, TYMED_HGLOBAL };
  204007. STGMEDIUM medium = { TYMED_HGLOBAL, { 0 }, 0 };
  204008. medium.hGlobal = createHDrop (files);
  204009. return performDragDrop (&format, &medium, canMove ? (DROPEFFECT_COPY | DROPEFFECT_MOVE)
  204010. : DROPEFFECT_COPY);
  204011. }
  204012. bool DragAndDropContainer::performExternalDragDropOfText (const String& text)
  204013. {
  204014. FORMATETC format = { CF_TEXT, 0, DVASPECT_CONTENT, -1, TYMED_HGLOBAL };
  204015. STGMEDIUM medium = { TYMED_HGLOBAL, { 0 }, 0 };
  204016. const int numChars = text.length();
  204017. medium.hGlobal = GlobalAlloc (GMEM_MOVEABLE | GMEM_ZEROINIT, (numChars + 2) * sizeof (WCHAR));
  204018. WCHAR* const data = static_cast <WCHAR*> (GlobalLock (medium.hGlobal));
  204019. text.copyToUnicode (data, numChars + 1);
  204020. format.cfFormat = CF_UNICODETEXT;
  204021. GlobalUnlock (medium.hGlobal);
  204022. return performDragDrop (&format, &medium, DROPEFFECT_COPY | DROPEFFECT_MOVE);
  204023. }
  204024. #endif
  204025. /*** End of inlined file: juce_win32_Windowing.cpp ***/
  204026. /*** Start of inlined file: juce_win32_Fonts.cpp ***/
  204027. // (This file gets included by juce_win32_NativeCode.cpp, rather than being
  204028. // compiled on its own).
  204029. #if JUCE_INCLUDED_FILE
  204030. static int CALLBACK wfontEnum2 (ENUMLOGFONTEXW* lpelfe,
  204031. NEWTEXTMETRICEXW*,
  204032. int type,
  204033. LPARAM lParam)
  204034. {
  204035. if (lpelfe != 0 && (type & RASTER_FONTTYPE) == 0)
  204036. {
  204037. const String fontName (lpelfe->elfLogFont.lfFaceName);
  204038. ((StringArray*) lParam)->addIfNotAlreadyThere (fontName.removeCharacters ("@"));
  204039. }
  204040. return 1;
  204041. }
  204042. static int CALLBACK wfontEnum1 (ENUMLOGFONTEXW* lpelfe,
  204043. NEWTEXTMETRICEXW*,
  204044. int type,
  204045. LPARAM lParam)
  204046. {
  204047. if (lpelfe != 0 && (type & RASTER_FONTTYPE) == 0)
  204048. {
  204049. LOGFONTW lf;
  204050. zerostruct (lf);
  204051. lf.lfWeight = FW_DONTCARE;
  204052. lf.lfOutPrecision = OUT_OUTLINE_PRECIS;
  204053. lf.lfQuality = DEFAULT_QUALITY;
  204054. lf.lfCharSet = DEFAULT_CHARSET;
  204055. lf.lfClipPrecision = CLIP_DEFAULT_PRECIS;
  204056. lf.lfPitchAndFamily = FF_DONTCARE;
  204057. const String fontName (lpelfe->elfLogFont.lfFaceName);
  204058. fontName.copyToUnicode (lf.lfFaceName, LF_FACESIZE - 1);
  204059. HDC dc = CreateCompatibleDC (0);
  204060. EnumFontFamiliesEx (dc, &lf,
  204061. (FONTENUMPROCW) &wfontEnum2,
  204062. lParam, 0);
  204063. DeleteDC (dc);
  204064. }
  204065. return 1;
  204066. }
  204067. const StringArray Font::findAllTypefaceNames()
  204068. {
  204069. StringArray results;
  204070. HDC dc = CreateCompatibleDC (0);
  204071. {
  204072. LOGFONTW lf;
  204073. zerostruct (lf);
  204074. lf.lfWeight = FW_DONTCARE;
  204075. lf.lfOutPrecision = OUT_OUTLINE_PRECIS;
  204076. lf.lfQuality = DEFAULT_QUALITY;
  204077. lf.lfCharSet = DEFAULT_CHARSET;
  204078. lf.lfClipPrecision = CLIP_DEFAULT_PRECIS;
  204079. lf.lfPitchAndFamily = FF_DONTCARE;
  204080. lf.lfFaceName[0] = 0;
  204081. EnumFontFamiliesEx (dc, &lf,
  204082. (FONTENUMPROCW) &wfontEnum1,
  204083. (LPARAM) &results, 0);
  204084. }
  204085. DeleteDC (dc);
  204086. results.sort (true);
  204087. return results;
  204088. }
  204089. extern bool juce_IsRunningInWine();
  204090. void Font::getPlatformDefaultFontNames (String& defaultSans, String& defaultSerif, String& defaultFixed)
  204091. {
  204092. if (juce_IsRunningInWine())
  204093. {
  204094. // If we're running in Wine, then use fonts that might be available on Linux..
  204095. defaultSans = "Bitstream Vera Sans";
  204096. defaultSerif = "Bitstream Vera Serif";
  204097. defaultFixed = "Bitstream Vera Sans Mono";
  204098. }
  204099. else
  204100. {
  204101. defaultSans = "Verdana";
  204102. defaultSerif = "Times";
  204103. defaultFixed = "Lucida Console";
  204104. }
  204105. }
  204106. class FontDCHolder : private DeletedAtShutdown
  204107. {
  204108. public:
  204109. FontDCHolder()
  204110. : dc (0), numKPs (0), size (0),
  204111. bold (false), italic (false)
  204112. {
  204113. }
  204114. ~FontDCHolder()
  204115. {
  204116. if (dc != 0)
  204117. {
  204118. DeleteDC (dc);
  204119. DeleteObject (fontH);
  204120. }
  204121. clearSingletonInstance();
  204122. }
  204123. juce_DeclareSingleton_SingleThreaded_Minimal (FontDCHolder);
  204124. HDC loadFont (const String& fontName_, const bool bold_, const bool italic_, const int size_)
  204125. {
  204126. if (fontName != fontName_ || bold != bold_ || italic != italic_ || size != size_)
  204127. {
  204128. fontName = fontName_;
  204129. bold = bold_;
  204130. italic = italic_;
  204131. size = size_;
  204132. if (dc != 0)
  204133. {
  204134. DeleteDC (dc);
  204135. DeleteObject (fontH);
  204136. kps.free();
  204137. }
  204138. fontH = 0;
  204139. dc = CreateCompatibleDC (0);
  204140. SetMapperFlags (dc, 0);
  204141. SetMapMode (dc, MM_TEXT);
  204142. LOGFONTW lfw;
  204143. zerostruct (lfw);
  204144. lfw.lfCharSet = DEFAULT_CHARSET;
  204145. lfw.lfClipPrecision = CLIP_DEFAULT_PRECIS;
  204146. lfw.lfOutPrecision = OUT_OUTLINE_PRECIS;
  204147. lfw.lfPitchAndFamily = DEFAULT_PITCH | FF_DONTCARE;
  204148. lfw.lfQuality = PROOF_QUALITY;
  204149. lfw.lfItalic = (BYTE) (italic ? TRUE : FALSE);
  204150. lfw.lfWeight = bold ? FW_BOLD : FW_NORMAL;
  204151. fontName.copyToUnicode (lfw.lfFaceName, LF_FACESIZE - 1);
  204152. lfw.lfHeight = size > 0 ? size : -256;
  204153. HFONT standardSizedFont = CreateFontIndirect (&lfw);
  204154. if (standardSizedFont != 0)
  204155. {
  204156. if (SelectObject (dc, standardSizedFont) != 0)
  204157. {
  204158. fontH = standardSizedFont;
  204159. if (size == 0)
  204160. {
  204161. OUTLINETEXTMETRIC otm;
  204162. if (GetOutlineTextMetrics (dc, sizeof (otm), &otm) != 0)
  204163. {
  204164. lfw.lfHeight = -(int) otm.otmEMSquare;
  204165. fontH = CreateFontIndirect (&lfw);
  204166. SelectObject (dc, fontH);
  204167. DeleteObject (standardSizedFont);
  204168. }
  204169. }
  204170. }
  204171. else
  204172. {
  204173. jassertfalse
  204174. }
  204175. }
  204176. else
  204177. {
  204178. jassertfalse
  204179. }
  204180. }
  204181. return dc;
  204182. }
  204183. KERNINGPAIR* getKerningPairs (int& numKPs_)
  204184. {
  204185. if (kps == 0)
  204186. {
  204187. numKPs = GetKerningPairs (dc, 0, 0);
  204188. kps.calloc (numKPs);
  204189. GetKerningPairs (dc, numKPs, kps);
  204190. }
  204191. numKPs_ = numKPs;
  204192. return kps;
  204193. }
  204194. private:
  204195. HFONT fontH;
  204196. HDC dc;
  204197. String fontName;
  204198. HeapBlock <KERNINGPAIR> kps;
  204199. int numKPs, size;
  204200. bool bold, italic;
  204201. FontDCHolder (const FontDCHolder&);
  204202. FontDCHolder& operator= (const FontDCHolder&);
  204203. };
  204204. juce_ImplementSingleton_SingleThreaded (FontDCHolder);
  204205. class WindowsTypeface : public CustomTypeface
  204206. {
  204207. public:
  204208. WindowsTypeface (const Font& font)
  204209. {
  204210. HDC dc = FontDCHolder::getInstance()->loadFont (font.getTypefaceName(),
  204211. font.isBold(), font.isItalic(), 0);
  204212. TEXTMETRIC tm;
  204213. tm.tmAscent = tm.tmHeight = 1;
  204214. tm.tmDefaultChar = 0;
  204215. GetTextMetrics (dc, &tm);
  204216. setCharacteristics (font.getTypefaceName(),
  204217. tm.tmAscent / (float) tm.tmHeight,
  204218. font.isBold(), font.isItalic(),
  204219. tm.tmDefaultChar);
  204220. }
  204221. bool loadGlyphIfPossible (juce_wchar character)
  204222. {
  204223. HDC dc = FontDCHolder::getInstance()->loadFont (name, isBold, isItalic, 0);
  204224. GLYPHMETRICS gm;
  204225. {
  204226. const WCHAR charToTest[] = { (WCHAR) character, 0 };
  204227. WORD index = 0;
  204228. if (GetGlyphIndices (dc, charToTest, 1, &index, GGI_MARK_NONEXISTING_GLYPHS) != GDI_ERROR
  204229. && index == 0xffff)
  204230. {
  204231. return false;
  204232. }
  204233. }
  204234. Path glyphPath;
  204235. TEXTMETRIC tm;
  204236. if (! GetTextMetrics (dc, &tm))
  204237. {
  204238. addGlyph (character, glyphPath, 0);
  204239. return true;
  204240. }
  204241. const float height = (float) tm.tmHeight;
  204242. static const MAT2 identityMatrix = { { 0, 1 }, { 0, 0 }, { 0, 0 }, { 0, 1 } };
  204243. const int bufSize = GetGlyphOutline (dc, character, GGO_NATIVE,
  204244. &gm, 0, 0, &identityMatrix);
  204245. if (bufSize > 0)
  204246. {
  204247. HeapBlock<char> data (bufSize);
  204248. GetGlyphOutline (dc, character, GGO_NATIVE, &gm,
  204249. bufSize, data, &identityMatrix);
  204250. const TTPOLYGONHEADER* pheader = reinterpret_cast<TTPOLYGONHEADER*> (data.getData());
  204251. const float scaleX = 1.0f / height;
  204252. const float scaleY = -1.0f / height;
  204253. while ((char*) pheader < data + bufSize)
  204254. {
  204255. float x = scaleX * pheader->pfxStart.x.value;
  204256. float y = scaleY * pheader->pfxStart.y.value;
  204257. glyphPath.startNewSubPath (x, y);
  204258. const TTPOLYCURVE* curve = (const TTPOLYCURVE*) ((const char*) pheader + sizeof (TTPOLYGONHEADER));
  204259. const char* const curveEnd = ((const char*) pheader) + pheader->cb;
  204260. while ((const char*) curve < curveEnd)
  204261. {
  204262. if (curve->wType == TT_PRIM_LINE)
  204263. {
  204264. for (int i = 0; i < curve->cpfx; ++i)
  204265. {
  204266. x = scaleX * curve->apfx[i].x.value;
  204267. y = scaleY * curve->apfx[i].y.value;
  204268. glyphPath.lineTo (x, y);
  204269. }
  204270. }
  204271. else if (curve->wType == TT_PRIM_QSPLINE)
  204272. {
  204273. for (int i = 0; i < curve->cpfx - 1; ++i)
  204274. {
  204275. const float x2 = scaleX * curve->apfx[i].x.value;
  204276. const float y2 = scaleY * curve->apfx[i].y.value;
  204277. float x3, y3;
  204278. if (i < curve->cpfx - 2)
  204279. {
  204280. x3 = 0.5f * (x2 + scaleX * curve->apfx[i + 1].x.value);
  204281. y3 = 0.5f * (y2 + scaleY * curve->apfx[i + 1].y.value);
  204282. }
  204283. else
  204284. {
  204285. x3 = scaleX * curve->apfx[i + 1].x.value;
  204286. y3 = scaleY * curve->apfx[i + 1].y.value;
  204287. }
  204288. glyphPath.quadraticTo (x2, y2, x3, y3);
  204289. x = x3;
  204290. y = y3;
  204291. }
  204292. }
  204293. curve = (const TTPOLYCURVE*) &(curve->apfx [curve->cpfx]);
  204294. }
  204295. pheader = (const TTPOLYGONHEADER*) curve;
  204296. glyphPath.closeSubPath();
  204297. }
  204298. }
  204299. addGlyph (character, glyphPath, gm.gmCellIncX / height);
  204300. int numKPs;
  204301. const KERNINGPAIR* const kps = FontDCHolder::getInstance()->getKerningPairs (numKPs);
  204302. for (int i = 0; i < numKPs; ++i)
  204303. {
  204304. if (kps[i].wFirst == character)
  204305. addKerningPair (kps[i].wFirst, kps[i].wSecond,
  204306. kps[i].iKernAmount / height);
  204307. }
  204308. return true;
  204309. }
  204310. };
  204311. const Typeface::Ptr Typeface::createSystemTypefaceFor (const Font& font)
  204312. {
  204313. return new WindowsTypeface (font);
  204314. }
  204315. #endif
  204316. /*** End of inlined file: juce_win32_Fonts.cpp ***/
  204317. /*** Start of inlined file: juce_win32_FileChooser.cpp ***/
  204318. // (This file gets included by juce_win32_NativeCode.cpp, rather than being
  204319. // compiled on its own).
  204320. #if JUCE_INCLUDED_FILE
  204321. void juce_setWindowStyleBit (HWND h, const int styleType, const int feature, const bool bitIsSet) throw();
  204322. namespace FileChooserHelpers
  204323. {
  204324. static const void* defaultDirPath = 0;
  204325. static String returnedString; // need this to get non-existent pathnames from the directory chooser
  204326. static Component* currentExtraFileWin = 0;
  204327. static bool areThereAnyAlwaysOnTopWindows()
  204328. {
  204329. for (int i = Desktop::getInstance().getNumComponents(); --i >= 0;)
  204330. {
  204331. Component* c = Desktop::getInstance().getComponent (i);
  204332. if (c != 0 && c->isAlwaysOnTop() && c->isShowing())
  204333. return true;
  204334. }
  204335. return false;
  204336. }
  204337. static int CALLBACK browseCallbackProc (HWND hWnd, UINT msg, LPARAM lParam, LPARAM /*lpData*/)
  204338. {
  204339. if (msg == BFFM_INITIALIZED)
  204340. SendMessage (hWnd, BFFM_SETSELECTIONW, TRUE, (LPARAM) defaultDirPath);
  204341. else if (msg == BFFM_VALIDATEFAILEDW)
  204342. returnedString = (LPCWSTR) lParam;
  204343. else if (msg == BFFM_VALIDATEFAILEDA)
  204344. returnedString = (const char*) lParam;
  204345. return 0;
  204346. }
  204347. static UINT_PTR CALLBACK openCallback (HWND hdlg, UINT uiMsg, WPARAM /*wParam*/, LPARAM lParam)
  204348. {
  204349. if (currentExtraFileWin != 0)
  204350. {
  204351. if (uiMsg == WM_INITDIALOG)
  204352. {
  204353. HWND dialogH = GetParent (hdlg);
  204354. jassert (dialogH != 0);
  204355. if (dialogH == 0)
  204356. dialogH = hdlg;
  204357. RECT r, cr;
  204358. GetWindowRect (dialogH, &r);
  204359. GetClientRect (dialogH, &cr);
  204360. SetWindowPos (dialogH, 0,
  204361. r.left, r.top,
  204362. currentExtraFileWin->getWidth() + jmax (150, (int) (r.right - r.left)),
  204363. jmax (150, (int) (r.bottom - r.top)),
  204364. SWP_NOACTIVATE | SWP_NOOWNERZORDER | SWP_NOZORDER);
  204365. currentExtraFileWin->setBounds (cr.right, cr.top, currentExtraFileWin->getWidth(), cr.bottom - cr.top);
  204366. currentExtraFileWin->getChildComponent(0)->setBounds (0, 0, currentExtraFileWin->getWidth(), currentExtraFileWin->getHeight());
  204367. SetParent ((HWND) currentExtraFileWin->getWindowHandle(), (HWND) dialogH);
  204368. juce_setWindowStyleBit ((HWND)currentExtraFileWin->getWindowHandle(), GWL_STYLE, WS_CHILD, (dialogH != 0));
  204369. juce_setWindowStyleBit ((HWND)currentExtraFileWin->getWindowHandle(), GWL_STYLE, WS_POPUP, (dialogH == 0));
  204370. }
  204371. else if (uiMsg == WM_NOTIFY)
  204372. {
  204373. LPOFNOTIFY ofn = (LPOFNOTIFY) lParam;
  204374. if (ofn->hdr.code == CDN_SELCHANGE)
  204375. {
  204376. FilePreviewComponent* comp = (FilePreviewComponent*) currentExtraFileWin->getChildComponent(0);
  204377. if (comp != 0)
  204378. {
  204379. TCHAR path [MAX_PATH * 2];
  204380. path[0] = 0;
  204381. CommDlg_OpenSave_GetFilePath (GetParent (hdlg), (LPARAM) &path, MAX_PATH);
  204382. const String fn ((const WCHAR*) path);
  204383. comp->selectedFileChanged (File (fn));
  204384. }
  204385. }
  204386. }
  204387. }
  204388. return 0;
  204389. }
  204390. class FPComponentHolder : public Component
  204391. {
  204392. public:
  204393. FPComponentHolder()
  204394. {
  204395. setVisible (true);
  204396. setOpaque (true);
  204397. }
  204398. ~FPComponentHolder()
  204399. {
  204400. }
  204401. void paint (Graphics& g)
  204402. {
  204403. g.fillAll (Colours::lightgrey);
  204404. }
  204405. private:
  204406. FPComponentHolder (const FPComponentHolder&);
  204407. FPComponentHolder& operator= (const FPComponentHolder&);
  204408. };
  204409. }
  204410. void FileChooser::showPlatformDialog (Array<File>& results,
  204411. const String& title,
  204412. const File& currentFileOrDirectory,
  204413. const String& filter,
  204414. bool selectsDirectory,
  204415. bool /*selectsFiles*/,
  204416. bool isSaveDialogue,
  204417. bool warnAboutOverwritingExistingFiles,
  204418. bool selectMultipleFiles,
  204419. FilePreviewComponent* extraInfoComponent)
  204420. {
  204421. using namespace FileChooserHelpers;
  204422. const int numCharsAvailable = 32768;
  204423. MemoryBlock filenameSpace ((numCharsAvailable + 1) * sizeof (WCHAR), true);
  204424. WCHAR* const fname = (WCHAR*) filenameSpace.getData();
  204425. int fnameIdx = 0;
  204426. JUCE_TRY
  204427. {
  204428. // use a modal window as the parent for this dialog box
  204429. // to block input from other app windows
  204430. const Rectangle<int> mainMon (Desktop::getInstance().getMainMonitorArea());
  204431. Component w (String::empty);
  204432. w.setBounds (mainMon.getX() + mainMon.getWidth() / 4,
  204433. mainMon.getY() + mainMon.getHeight() / 4,
  204434. 0, 0);
  204435. w.setOpaque (true);
  204436. w.setAlwaysOnTop (areThereAnyAlwaysOnTopWindows());
  204437. w.addToDesktop (0);
  204438. if (extraInfoComponent == 0)
  204439. w.enterModalState();
  204440. String initialDir;
  204441. if (currentFileOrDirectory.isDirectory())
  204442. {
  204443. initialDir = currentFileOrDirectory.getFullPathName();
  204444. }
  204445. else
  204446. {
  204447. currentFileOrDirectory.getFileName().copyToUnicode (fname, numCharsAvailable);
  204448. initialDir = currentFileOrDirectory.getParentDirectory().getFullPathName();
  204449. }
  204450. if (currentExtraFileWin->isValidComponent())
  204451. {
  204452. jassertfalse
  204453. return;
  204454. }
  204455. if (selectsDirectory)
  204456. {
  204457. LPITEMIDLIST list = 0;
  204458. filenameSpace.fillWith (0);
  204459. {
  204460. BROWSEINFO bi;
  204461. zerostruct (bi);
  204462. bi.hwndOwner = (HWND) w.getWindowHandle();
  204463. bi.pszDisplayName = fname;
  204464. bi.lpszTitle = title;
  204465. bi.lpfn = browseCallbackProc;
  204466. #ifdef BIF_USENEWUI
  204467. bi.ulFlags = BIF_USENEWUI | BIF_VALIDATE;
  204468. #else
  204469. bi.ulFlags = 0x50;
  204470. #endif
  204471. defaultDirPath = (const WCHAR*) initialDir;
  204472. list = SHBrowseForFolder (&bi);
  204473. if (! SHGetPathFromIDListW (list, fname))
  204474. {
  204475. fname[0] = 0;
  204476. returnedString = String::empty;
  204477. }
  204478. }
  204479. LPMALLOC al;
  204480. if (list != 0 && SUCCEEDED (SHGetMalloc (&al)))
  204481. al->Free (list);
  204482. defaultDirPath = 0;
  204483. if (returnedString.isNotEmpty())
  204484. {
  204485. const String stringFName (fname);
  204486. results.add (File (stringFName).getSiblingFile (returnedString));
  204487. returnedString = String::empty;
  204488. return;
  204489. }
  204490. }
  204491. else
  204492. {
  204493. DWORD flags = OFN_EXPLORER | OFN_PATHMUSTEXIST | OFN_NOCHANGEDIR | OFN_HIDEREADONLY;
  204494. if (warnAboutOverwritingExistingFiles)
  204495. flags |= OFN_OVERWRITEPROMPT;
  204496. if (selectMultipleFiles)
  204497. flags |= OFN_ALLOWMULTISELECT;
  204498. if (extraInfoComponent != 0)
  204499. {
  204500. flags |= OFN_ENABLEHOOK;
  204501. currentExtraFileWin = new FPComponentHolder();
  204502. currentExtraFileWin->addAndMakeVisible (extraInfoComponent);
  204503. currentExtraFileWin->setSize (jlimit (20, 800, extraInfoComponent->getWidth()),
  204504. extraInfoComponent->getHeight());
  204505. currentExtraFileWin->addToDesktop (0);
  204506. currentExtraFileWin->enterModalState();
  204507. }
  204508. {
  204509. WCHAR filters [1024];
  204510. zeromem (filters, sizeof (filters));
  204511. filter.copyToUnicode (filters, 1024);
  204512. filter.copyToUnicode (filters + filter.length() + 1,
  204513. 1022 - filter.length());
  204514. OPENFILENAMEW of;
  204515. zerostruct (of);
  204516. #ifdef OPENFILENAME_SIZE_VERSION_400W
  204517. of.lStructSize = OPENFILENAME_SIZE_VERSION_400W;
  204518. #else
  204519. of.lStructSize = sizeof (of);
  204520. #endif
  204521. of.hwndOwner = (HWND) w.getWindowHandle();
  204522. of.lpstrFilter = filters;
  204523. of.nFilterIndex = 1;
  204524. of.lpstrFile = fname;
  204525. of.nMaxFile = numCharsAvailable;
  204526. of.lpstrInitialDir = initialDir;
  204527. of.lpstrTitle = title;
  204528. of.Flags = flags;
  204529. if (extraInfoComponent != 0)
  204530. of.lpfnHook = &openCallback;
  204531. if (isSaveDialogue)
  204532. {
  204533. if (! GetSaveFileName (&of))
  204534. fname[0] = 0;
  204535. else
  204536. fnameIdx = of.nFileOffset;
  204537. }
  204538. else
  204539. {
  204540. if (! GetOpenFileName (&of))
  204541. fname[0] = 0;
  204542. else
  204543. fnameIdx = of.nFileOffset;
  204544. }
  204545. }
  204546. }
  204547. }
  204548. #if JUCE_CATCH_UNHANDLED_EXCEPTIONS
  204549. catch (...)
  204550. {
  204551. fname[0] = 0;
  204552. }
  204553. #endif
  204554. deleteAndZero (currentExtraFileWin);
  204555. const WCHAR* const files = fname;
  204556. if (selectMultipleFiles && fnameIdx > 0 && files [fnameIdx - 1] == 0)
  204557. {
  204558. const WCHAR* filename = files + fnameIdx;
  204559. while (*filename != 0)
  204560. {
  204561. const String filepath (String (files) + "\\" + String (filename));
  204562. results.add (File (filepath));
  204563. filename += CharacterFunctions::length (filename) + 1;
  204564. }
  204565. }
  204566. else if (files[0] != 0)
  204567. {
  204568. results.add (File (files));
  204569. }
  204570. }
  204571. #endif
  204572. /*** End of inlined file: juce_win32_FileChooser.cpp ***/
  204573. /*** Start of inlined file: juce_win32_Misc.cpp ***/
  204574. // (This file gets included by juce_win32_NativeCode.cpp, rather than being
  204575. // compiled on its own).
  204576. #if JUCE_INCLUDED_FILE
  204577. void SystemClipboard::copyTextToClipboard (const String& text)
  204578. {
  204579. if (OpenClipboard (0) != 0)
  204580. {
  204581. if (EmptyClipboard() != 0)
  204582. {
  204583. const int len = text.length();
  204584. if (len > 0)
  204585. {
  204586. HGLOBAL bufH = GlobalAlloc (GMEM_MOVEABLE | GMEM_DDESHARE,
  204587. (len + 1) * sizeof (wchar_t));
  204588. if (bufH != 0)
  204589. {
  204590. WCHAR* const data = static_cast <WCHAR*> (GlobalLock (bufH));
  204591. text.copyToUnicode (data, len);
  204592. GlobalUnlock (bufH);
  204593. SetClipboardData (CF_UNICODETEXT, bufH);
  204594. }
  204595. }
  204596. }
  204597. CloseClipboard();
  204598. }
  204599. }
  204600. const String SystemClipboard::getTextFromClipboard()
  204601. {
  204602. String result;
  204603. if (OpenClipboard (0) != 0)
  204604. {
  204605. HANDLE bufH = GetClipboardData (CF_UNICODETEXT);
  204606. if (bufH != 0)
  204607. {
  204608. const wchar_t* const data = (const wchar_t*) GlobalLock (bufH);
  204609. if (data != 0)
  204610. {
  204611. result = String (data, (int) (GlobalSize (bufH) / sizeof (wchar_t)));
  204612. GlobalUnlock (bufH);
  204613. }
  204614. }
  204615. CloseClipboard();
  204616. }
  204617. return result;
  204618. }
  204619. #endif
  204620. /*** End of inlined file: juce_win32_Misc.cpp ***/
  204621. /*** Start of inlined file: juce_win32_ActiveXComponent.cpp ***/
  204622. // (This file gets included by juce_win32_NativeCode.cpp, rather than being
  204623. // compiled on its own).
  204624. #if JUCE_INCLUDED_FILE
  204625. namespace ActiveXHelpers
  204626. {
  204627. class JuceIStorage : public ComBaseClassHelper <IStorage>
  204628. {
  204629. public:
  204630. JuceIStorage() {}
  204631. ~JuceIStorage() {}
  204632. HRESULT __stdcall CreateStream (const WCHAR*, DWORD, DWORD, DWORD, IStream**) { return E_NOTIMPL; }
  204633. HRESULT __stdcall OpenStream (const WCHAR*, void*, DWORD, DWORD, IStream**) { return E_NOTIMPL; }
  204634. HRESULT __stdcall CreateStorage (const WCHAR*, DWORD, DWORD, DWORD, IStorage**) { return E_NOTIMPL; }
  204635. HRESULT __stdcall OpenStorage (const WCHAR*, IStorage*, DWORD, SNB, DWORD, IStorage**) { return E_NOTIMPL; }
  204636. HRESULT __stdcall CopyTo (DWORD, IID const*, SNB, IStorage*) { return E_NOTIMPL; }
  204637. HRESULT __stdcall MoveElementTo (const OLECHAR*,IStorage*, const OLECHAR*, DWORD) { return E_NOTIMPL; }
  204638. HRESULT __stdcall Commit (DWORD) { return E_NOTIMPL; }
  204639. HRESULT __stdcall Revert() { return E_NOTIMPL; }
  204640. HRESULT __stdcall EnumElements (DWORD, void*, DWORD, IEnumSTATSTG**) { return E_NOTIMPL; }
  204641. HRESULT __stdcall DestroyElement (const OLECHAR*) { return E_NOTIMPL; }
  204642. HRESULT __stdcall RenameElement (const WCHAR*, const WCHAR*) { return E_NOTIMPL; }
  204643. HRESULT __stdcall SetElementTimes (const WCHAR*, FILETIME const*, FILETIME const*, FILETIME const*) { return E_NOTIMPL; }
  204644. HRESULT __stdcall SetClass (REFCLSID) { return S_OK; }
  204645. HRESULT __stdcall SetStateBits (DWORD, DWORD) { return E_NOTIMPL; }
  204646. HRESULT __stdcall Stat (STATSTG*, DWORD) { return E_NOTIMPL; }
  204647. juce_UseDebuggingNewOperator
  204648. };
  204649. class JuceOleInPlaceFrame : public ComBaseClassHelper <IOleInPlaceFrame>
  204650. {
  204651. HWND window;
  204652. public:
  204653. JuceOleInPlaceFrame (HWND window_) : window (window_) {}
  204654. ~JuceOleInPlaceFrame() {}
  204655. HRESULT __stdcall GetWindow (HWND* lphwnd) { *lphwnd = window; return S_OK; }
  204656. HRESULT __stdcall ContextSensitiveHelp (BOOL) { return E_NOTIMPL; }
  204657. HRESULT __stdcall GetBorder (LPRECT) { return E_NOTIMPL; }
  204658. HRESULT __stdcall RequestBorderSpace (LPCBORDERWIDTHS) { return E_NOTIMPL; }
  204659. HRESULT __stdcall SetBorderSpace (LPCBORDERWIDTHS) { return E_NOTIMPL; }
  204660. HRESULT __stdcall SetActiveObject (IOleInPlaceActiveObject*, LPCOLESTR) { return S_OK; }
  204661. HRESULT __stdcall InsertMenus (HMENU, LPOLEMENUGROUPWIDTHS) { return E_NOTIMPL; }
  204662. HRESULT __stdcall SetMenu (HMENU, HOLEMENU, HWND) { return S_OK; }
  204663. HRESULT __stdcall RemoveMenus (HMENU) { return E_NOTIMPL; }
  204664. HRESULT __stdcall SetStatusText (LPCOLESTR) { return S_OK; }
  204665. HRESULT __stdcall EnableModeless (BOOL) { return S_OK; }
  204666. HRESULT __stdcall TranslateAccelerator(LPMSG, WORD) { return E_NOTIMPL; }
  204667. juce_UseDebuggingNewOperator
  204668. };
  204669. class JuceIOleInPlaceSite : public ComBaseClassHelper <IOleInPlaceSite>
  204670. {
  204671. HWND window;
  204672. JuceOleInPlaceFrame* frame;
  204673. public:
  204674. JuceIOleInPlaceSite (HWND window_)
  204675. : window (window_),
  204676. frame (new JuceOleInPlaceFrame (window))
  204677. {}
  204678. ~JuceIOleInPlaceSite()
  204679. {
  204680. frame->Release();
  204681. }
  204682. HRESULT __stdcall GetWindow (HWND* lphwnd) { *lphwnd = window; return S_OK; }
  204683. HRESULT __stdcall ContextSensitiveHelp (BOOL) { return E_NOTIMPL; }
  204684. HRESULT __stdcall CanInPlaceActivate() { return S_OK; }
  204685. HRESULT __stdcall OnInPlaceActivate() { return S_OK; }
  204686. HRESULT __stdcall OnUIActivate() { return S_OK; }
  204687. HRESULT __stdcall GetWindowContext (LPOLEINPLACEFRAME* lplpFrame, LPOLEINPLACEUIWINDOW* lplpDoc, LPRECT, LPRECT, LPOLEINPLACEFRAMEINFO lpFrameInfo)
  204688. {
  204689. *lplpFrame = frame;
  204690. *lplpDoc = 0;
  204691. lpFrameInfo->fMDIApp = FALSE;
  204692. lpFrameInfo->hwndFrame = window;
  204693. lpFrameInfo->haccel = 0;
  204694. lpFrameInfo->cAccelEntries = 0;
  204695. return S_OK;
  204696. }
  204697. HRESULT __stdcall Scroll (SIZE) { return E_NOTIMPL; }
  204698. HRESULT __stdcall OnUIDeactivate (BOOL) { return S_OK; }
  204699. HRESULT __stdcall OnInPlaceDeactivate() { return S_OK; }
  204700. HRESULT __stdcall DiscardUndoState() { return E_NOTIMPL; }
  204701. HRESULT __stdcall DeactivateAndUndo() { return E_NOTIMPL; }
  204702. HRESULT __stdcall OnPosRectChange (LPCRECT) { return S_OK; }
  204703. juce_UseDebuggingNewOperator
  204704. };
  204705. class JuceIOleClientSite : public ComBaseClassHelper <IOleClientSite>
  204706. {
  204707. JuceIOleInPlaceSite* inplaceSite;
  204708. public:
  204709. JuceIOleClientSite (HWND window)
  204710. : inplaceSite (new JuceIOleInPlaceSite (window))
  204711. {}
  204712. ~JuceIOleClientSite()
  204713. {
  204714. inplaceSite->Release();
  204715. }
  204716. HRESULT __stdcall QueryInterface (REFIID type, void __RPC_FAR* __RPC_FAR* result)
  204717. {
  204718. if (type == IID_IOleInPlaceSite)
  204719. {
  204720. inplaceSite->AddRef();
  204721. *result = static_cast <IOleInPlaceSite*> (inplaceSite);
  204722. return S_OK;
  204723. }
  204724. return ComBaseClassHelper <IOleClientSite>::QueryInterface (type, result);
  204725. }
  204726. HRESULT __stdcall SaveObject() { return E_NOTIMPL; }
  204727. HRESULT __stdcall GetMoniker (DWORD, DWORD, IMoniker**) { return E_NOTIMPL; }
  204728. HRESULT __stdcall GetContainer (LPOLECONTAINER* ppContainer) { *ppContainer = 0; return E_NOINTERFACE; }
  204729. HRESULT __stdcall ShowObject() { return S_OK; }
  204730. HRESULT __stdcall OnShowWindow (BOOL) { return E_NOTIMPL; }
  204731. HRESULT __stdcall RequestNewObjectLayout() { return E_NOTIMPL; }
  204732. juce_UseDebuggingNewOperator
  204733. };
  204734. static VoidArray activeXComps;
  204735. static HWND getHWND (const ActiveXControlComponent* const component)
  204736. {
  204737. HWND hwnd = 0;
  204738. const IID iid = IID_IOleWindow;
  204739. IOleWindow* const window = (IOleWindow*) component->queryInterface (&iid);
  204740. if (window != 0)
  204741. {
  204742. window->GetWindow (&hwnd);
  204743. window->Release();
  204744. }
  204745. return hwnd;
  204746. }
  204747. static void offerActiveXMouseEventToPeer (ComponentPeer* const peer, HWND hwnd, UINT message, LPARAM lParam)
  204748. {
  204749. RECT activeXRect, peerRect;
  204750. GetWindowRect (hwnd, &activeXRect);
  204751. GetWindowRect ((HWND) peer->getNativeHandle(), &peerRect);
  204752. const Point<int> mousePos (GET_X_LPARAM (lParam) + activeXRect.left - peerRect.left,
  204753. GET_Y_LPARAM (lParam) + activeXRect.top - peerRect.top);
  204754. const int64 mouseEventTime = Win32ComponentPeer::getMouseEventTime();
  204755. ModifierKeys::getCurrentModifiersRealtime(); // to update the mouse button flags
  204756. switch (message)
  204757. {
  204758. case WM_MOUSEMOVE:
  204759. case WM_LBUTTONDOWN:
  204760. case WM_MBUTTONDOWN:
  204761. case WM_RBUTTONDOWN:
  204762. case WM_LBUTTONUP:
  204763. case WM_MBUTTONUP:
  204764. case WM_RBUTTONUP:
  204765. peer->handleMouseEvent (0, mousePos, Win32ComponentPeer::currentModifiers, mouseEventTime);
  204766. break;
  204767. default:
  204768. break;
  204769. }
  204770. }
  204771. }
  204772. class ActiveXControlComponent::Pimpl : public ComponentMovementWatcher
  204773. {
  204774. ActiveXControlComponent* const owner;
  204775. bool wasShowing;
  204776. public:
  204777. HWND controlHWND;
  204778. IStorage* storage;
  204779. IOleClientSite* clientSite;
  204780. IOleObject* control;
  204781. Pimpl (HWND hwnd, ActiveXControlComponent* const owner_)
  204782. : ComponentMovementWatcher (owner_),
  204783. owner (owner_),
  204784. wasShowing (owner_ != 0 && owner_->isShowing()),
  204785. controlHWND (0),
  204786. storage (new ActiveXHelpers::JuceIStorage()),
  204787. clientSite (new ActiveXHelpers::JuceIOleClientSite (hwnd)),
  204788. control (0)
  204789. {
  204790. }
  204791. ~Pimpl()
  204792. {
  204793. if (control != 0)
  204794. {
  204795. control->Close (OLECLOSE_NOSAVE);
  204796. control->Release();
  204797. }
  204798. clientSite->Release();
  204799. storage->Release();
  204800. }
  204801. void componentMovedOrResized (bool /*wasMoved*/, bool /*wasResized*/)
  204802. {
  204803. Component* const topComp = owner->getTopLevelComponent();
  204804. if (topComp->getPeer() != 0)
  204805. {
  204806. const Point<int> pos (owner->relativePositionToOtherComponent (topComp, Point<int>()));
  204807. owner->setControlBounds (Rectangle<int> (pos.getX(), pos.getY(), owner->getWidth(), owner->getHeight()));
  204808. }
  204809. }
  204810. void componentPeerChanged()
  204811. {
  204812. const bool isShowingNow = owner->isShowing();
  204813. if (wasShowing != isShowingNow)
  204814. {
  204815. wasShowing = isShowingNow;
  204816. owner->setControlVisible (isShowingNow);
  204817. }
  204818. componentMovedOrResized (true, true);
  204819. }
  204820. void componentVisibilityChanged (Component&)
  204821. {
  204822. componentPeerChanged();
  204823. }
  204824. // intercepts events going to an activeX control, so we can sneakily use the mouse events
  204825. static LRESULT CALLBACK activeXHookWndProc (HWND hwnd, UINT message, WPARAM wParam, LPARAM lParam)
  204826. {
  204827. for (int i = ActiveXHelpers::activeXComps.size(); --i >= 0;)
  204828. {
  204829. const ActiveXControlComponent* const ax
  204830. = static_cast <const ActiveXControlComponent*> (ActiveXHelpers::activeXComps.getUnchecked(i));
  204831. if (ax->control != 0 && ax->control->controlHWND == hwnd)
  204832. {
  204833. switch (message)
  204834. {
  204835. case WM_MOUSEMOVE:
  204836. case WM_LBUTTONDOWN:
  204837. case WM_MBUTTONDOWN:
  204838. case WM_RBUTTONDOWN:
  204839. case WM_LBUTTONUP:
  204840. case WM_MBUTTONUP:
  204841. case WM_RBUTTONUP:
  204842. case WM_LBUTTONDBLCLK:
  204843. case WM_MBUTTONDBLCLK:
  204844. case WM_RBUTTONDBLCLK:
  204845. if (ax->isShowing())
  204846. {
  204847. ComponentPeer* const peer = ax->getPeer();
  204848. if (peer != 0)
  204849. {
  204850. ActiveXHelpers::offerActiveXMouseEventToPeer (peer, hwnd, message, lParam);
  204851. if (! ax->areMouseEventsAllowed())
  204852. return 0;
  204853. }
  204854. }
  204855. break;
  204856. default:
  204857. break;
  204858. }
  204859. return CallWindowProc ((WNDPROC) ax->originalWndProc, hwnd, message, wParam, lParam);
  204860. }
  204861. }
  204862. return DefWindowProc (hwnd, message, wParam, lParam);
  204863. }
  204864. };
  204865. ActiveXControlComponent::ActiveXControlComponent()
  204866. : originalWndProc (0),
  204867. mouseEventsAllowed (true)
  204868. {
  204869. ActiveXHelpers::activeXComps.add (this);
  204870. }
  204871. ActiveXControlComponent::~ActiveXControlComponent()
  204872. {
  204873. deleteControl();
  204874. ActiveXHelpers::activeXComps.removeValue (this);
  204875. }
  204876. void ActiveXControlComponent::paint (Graphics& g)
  204877. {
  204878. if (control == 0)
  204879. g.fillAll (Colours::lightgrey);
  204880. }
  204881. bool ActiveXControlComponent::createControl (const void* controlIID)
  204882. {
  204883. deleteControl();
  204884. ComponentPeer* const peer = getPeer();
  204885. // the component must have already been added to a real window when you call this!
  204886. jassert (dynamic_cast <Win32ComponentPeer*> (peer) != 0);
  204887. if (dynamic_cast <Win32ComponentPeer*> (peer) != 0)
  204888. {
  204889. const Point<int> pos (relativePositionToOtherComponent (getTopLevelComponent(), Point<int>()));
  204890. HWND hwnd = (HWND) peer->getNativeHandle();
  204891. ScopedPointer<Pimpl> newControl (new Pimpl (hwnd, this));
  204892. HRESULT hr;
  204893. if ((hr = OleCreate (*(const IID*) controlIID, IID_IOleObject, 1 /*OLERENDER_DRAW*/, 0,
  204894. newControl->clientSite, newControl->storage,
  204895. (void**) &(newControl->control))) == S_OK)
  204896. {
  204897. newControl->control->SetHostNames (L"Juce", 0);
  204898. if (OleSetContainedObject (newControl->control, TRUE) == S_OK)
  204899. {
  204900. RECT rect;
  204901. rect.left = pos.getX();
  204902. rect.top = pos.getY();
  204903. rect.right = pos.getX() + getWidth();
  204904. rect.bottom = pos.getY() + getHeight();
  204905. if (newControl->control->DoVerb (OLEIVERB_SHOW, 0, newControl->clientSite, 0, hwnd, &rect) == S_OK)
  204906. {
  204907. control = newControl;
  204908. setControlBounds (Rectangle<int> (pos.getX(), pos.getY(), getWidth(), getHeight()));
  204909. control->controlHWND = ActiveXHelpers::getHWND (this);
  204910. if (control->controlHWND != 0)
  204911. {
  204912. originalWndProc = (void*) (pointer_sized_int) GetWindowLongPtr ((HWND) control->controlHWND, GWLP_WNDPROC);
  204913. SetWindowLongPtr ((HWND) control->controlHWND, GWLP_WNDPROC, (LONG_PTR) Pimpl::activeXHookWndProc);
  204914. }
  204915. return true;
  204916. }
  204917. }
  204918. }
  204919. }
  204920. return false;
  204921. }
  204922. void ActiveXControlComponent::deleteControl()
  204923. {
  204924. control = 0;
  204925. originalWndProc = 0;
  204926. }
  204927. void* ActiveXControlComponent::queryInterface (const void* iid) const
  204928. {
  204929. void* result = 0;
  204930. if (control != 0 && control->control != 0
  204931. && SUCCEEDED (control->control->QueryInterface (*(const IID*) iid, &result)))
  204932. return result;
  204933. return 0;
  204934. }
  204935. void ActiveXControlComponent::setControlBounds (const Rectangle<int>& newBounds) const
  204936. {
  204937. if (control->controlHWND != 0)
  204938. MoveWindow (control->controlHWND, newBounds.getX(), newBounds.getY(), newBounds.getWidth(), newBounds.getHeight(), TRUE);
  204939. }
  204940. void ActiveXControlComponent::setControlVisible (const bool shouldBeVisible) const
  204941. {
  204942. if (control->controlHWND != 0)
  204943. ShowWindow (control->controlHWND, shouldBeVisible ? SW_SHOWNA : SW_HIDE);
  204944. }
  204945. void ActiveXControlComponent::setMouseEventsAllowed (const bool eventsCanReachControl)
  204946. {
  204947. mouseEventsAllowed = eventsCanReachControl;
  204948. }
  204949. #endif
  204950. /*** End of inlined file: juce_win32_ActiveXComponent.cpp ***/
  204951. /*** Start of inlined file: juce_win32_QuickTimeMovieComponent.cpp ***/
  204952. // (This file gets included by juce_win32_NativeCode.cpp, rather than being
  204953. // compiled on its own).
  204954. #if JUCE_INCLUDED_FILE && JUCE_QUICKTIME
  204955. using namespace QTOLibrary;
  204956. using namespace QTOControlLib;
  204957. bool juce_OpenQuickTimeMovieFromStream (InputStream* input, Movie& movie, Handle& dataHandle);
  204958. static bool isQTAvailable = false;
  204959. class QuickTimeMovieComponent::Pimpl
  204960. {
  204961. public:
  204962. Pimpl() : dataHandle (0)
  204963. {
  204964. }
  204965. ~Pimpl()
  204966. {
  204967. clearHandle();
  204968. }
  204969. void clearHandle()
  204970. {
  204971. if (dataHandle != 0)
  204972. {
  204973. DisposeHandle (dataHandle);
  204974. dataHandle = 0;
  204975. }
  204976. }
  204977. IQTControlPtr qtControl;
  204978. IQTMoviePtr qtMovie;
  204979. Handle dataHandle;
  204980. };
  204981. QuickTimeMovieComponent::QuickTimeMovieComponent()
  204982. : movieLoaded (false),
  204983. controllerVisible (true)
  204984. {
  204985. pimpl = new Pimpl();
  204986. setMouseEventsAllowed (false);
  204987. }
  204988. QuickTimeMovieComponent::~QuickTimeMovieComponent()
  204989. {
  204990. closeMovie();
  204991. pimpl->qtControl = 0;
  204992. deleteControl();
  204993. pimpl = 0;
  204994. }
  204995. bool QuickTimeMovieComponent::isQuickTimeAvailable() throw()
  204996. {
  204997. if (! isQTAvailable)
  204998. isQTAvailable = (InitializeQTML (0) == noErr) && (EnterMovies() == noErr);
  204999. return isQTAvailable;
  205000. }
  205001. void QuickTimeMovieComponent::createControlIfNeeded()
  205002. {
  205003. if (isShowing() && ! isControlCreated())
  205004. {
  205005. const IID qtIID = __uuidof (QTControl);
  205006. if (createControl (&qtIID))
  205007. {
  205008. const IID qtInterfaceIID = __uuidof (IQTControl);
  205009. pimpl->qtControl = (IQTControl*) queryInterface (&qtInterfaceIID);
  205010. if (pimpl->qtControl != 0)
  205011. {
  205012. pimpl->qtControl->Release(); // it has one ref too many at this point
  205013. pimpl->qtControl->QuickTimeInitialize();
  205014. pimpl->qtControl->PutSizing (qtMovieFitsControl);
  205015. if (movieFile != File::nonexistent)
  205016. loadMovie (movieFile, controllerVisible);
  205017. }
  205018. }
  205019. }
  205020. }
  205021. bool QuickTimeMovieComponent::isControlCreated() const
  205022. {
  205023. return isControlOpen();
  205024. }
  205025. bool QuickTimeMovieComponent::loadMovie (InputStream* movieStream,
  205026. const bool isControllerVisible)
  205027. {
  205028. const ScopedPointer<InputStream> movieStreamDeleter (movieStream);
  205029. movieFile = File::nonexistent;
  205030. movieLoaded = false;
  205031. pimpl->qtMovie = 0;
  205032. controllerVisible = isControllerVisible;
  205033. createControlIfNeeded();
  205034. if (isControlCreated())
  205035. {
  205036. if (pimpl->qtControl != 0)
  205037. {
  205038. pimpl->qtControl->Put_MovieHandle (0);
  205039. pimpl->clearHandle();
  205040. Movie movie;
  205041. if (juce_OpenQuickTimeMovieFromStream (movieStream, movie, pimpl->dataHandle))
  205042. {
  205043. pimpl->qtControl->Put_MovieHandle ((long) (pointer_sized_int) movie);
  205044. pimpl->qtMovie = pimpl->qtControl->GetMovie();
  205045. if (pimpl->qtMovie != 0)
  205046. pimpl->qtMovie->PutMovieControllerType (isControllerVisible ? qtMovieControllerTypeStandard
  205047. : qtMovieControllerTypeNone);
  205048. }
  205049. if (movie == 0)
  205050. pimpl->clearHandle();
  205051. }
  205052. movieLoaded = (pimpl->qtMovie != 0);
  205053. }
  205054. else
  205055. {
  205056. // You're trying to open a movie when the control hasn't yet been created, probably because
  205057. // you've not yet added this component to a Window and made the whole component hierarchy visible.
  205058. jassertfalse
  205059. }
  205060. return movieLoaded;
  205061. }
  205062. void QuickTimeMovieComponent::closeMovie()
  205063. {
  205064. stop();
  205065. movieFile = File::nonexistent;
  205066. movieLoaded = false;
  205067. pimpl->qtMovie = 0;
  205068. if (pimpl->qtControl != 0)
  205069. pimpl->qtControl->Put_MovieHandle (0);
  205070. pimpl->clearHandle();
  205071. }
  205072. const File QuickTimeMovieComponent::getCurrentMovieFile() const
  205073. {
  205074. return movieFile;
  205075. }
  205076. bool QuickTimeMovieComponent::isMovieOpen() const
  205077. {
  205078. return movieLoaded;
  205079. }
  205080. double QuickTimeMovieComponent::getMovieDuration() const
  205081. {
  205082. if (pimpl->qtMovie != 0)
  205083. return pimpl->qtMovie->GetDuration() / (double) pimpl->qtMovie->GetTimeScale();
  205084. return 0.0;
  205085. }
  205086. void QuickTimeMovieComponent::getMovieNormalSize (int& width, int& height) const
  205087. {
  205088. if (pimpl->qtMovie != 0)
  205089. {
  205090. struct QTRECT r = pimpl->qtMovie->GetNaturalRect();
  205091. width = r.right - r.left;
  205092. height = r.bottom - r.top;
  205093. }
  205094. else
  205095. {
  205096. width = height = 0;
  205097. }
  205098. }
  205099. void QuickTimeMovieComponent::play()
  205100. {
  205101. if (pimpl->qtMovie != 0)
  205102. pimpl->qtMovie->Play();
  205103. }
  205104. void QuickTimeMovieComponent::stop()
  205105. {
  205106. if (pimpl->qtMovie != 0)
  205107. pimpl->qtMovie->Stop();
  205108. }
  205109. bool QuickTimeMovieComponent::isPlaying() const
  205110. {
  205111. return pimpl->qtMovie != 0 && pimpl->qtMovie->GetRate() != 0.0f;
  205112. }
  205113. void QuickTimeMovieComponent::setPosition (const double seconds)
  205114. {
  205115. if (pimpl->qtMovie != 0)
  205116. pimpl->qtMovie->PutTime ((long) (seconds * pimpl->qtMovie->GetTimeScale()));
  205117. }
  205118. double QuickTimeMovieComponent::getPosition() const
  205119. {
  205120. if (pimpl->qtMovie != 0)
  205121. return pimpl->qtMovie->GetTime() / (double) pimpl->qtMovie->GetTimeScale();
  205122. return 0.0;
  205123. }
  205124. void QuickTimeMovieComponent::setSpeed (const float newSpeed)
  205125. {
  205126. if (pimpl->qtMovie != 0)
  205127. pimpl->qtMovie->PutRate (newSpeed);
  205128. }
  205129. void QuickTimeMovieComponent::setMovieVolume (const float newVolume)
  205130. {
  205131. if (pimpl->qtMovie != 0)
  205132. {
  205133. pimpl->qtMovie->PutAudioVolume (newVolume);
  205134. pimpl->qtMovie->PutAudioMute (newVolume <= 0);
  205135. }
  205136. }
  205137. float QuickTimeMovieComponent::getMovieVolume() const
  205138. {
  205139. if (pimpl->qtMovie != 0)
  205140. return pimpl->qtMovie->GetAudioVolume();
  205141. return 0.0f;
  205142. }
  205143. void QuickTimeMovieComponent::setLooping (const bool shouldLoop)
  205144. {
  205145. if (pimpl->qtMovie != 0)
  205146. pimpl->qtMovie->PutLoop (shouldLoop);
  205147. }
  205148. bool QuickTimeMovieComponent::isLooping() const
  205149. {
  205150. return pimpl->qtMovie != 0 && pimpl->qtMovie->GetLoop();
  205151. }
  205152. bool QuickTimeMovieComponent::isControllerVisible() const
  205153. {
  205154. return controllerVisible;
  205155. }
  205156. void QuickTimeMovieComponent::parentHierarchyChanged()
  205157. {
  205158. createControlIfNeeded();
  205159. QTCompBaseClass::parentHierarchyChanged();
  205160. }
  205161. void QuickTimeMovieComponent::visibilityChanged()
  205162. {
  205163. createControlIfNeeded();
  205164. QTCompBaseClass::visibilityChanged();
  205165. }
  205166. void QuickTimeMovieComponent::paint (Graphics& g)
  205167. {
  205168. if (! isControlCreated())
  205169. g.fillAll (Colours::black);
  205170. }
  205171. static Handle createHandleDataRef (Handle dataHandle, const char* fileName)
  205172. {
  205173. Handle dataRef = 0;
  205174. OSStatus err = PtrToHand (&dataHandle, &dataRef, sizeof (Handle));
  205175. if (err == noErr)
  205176. {
  205177. Str255 suffix;
  205178. CharacterFunctions::copy ((char*) suffix, fileName, 128);
  205179. StringPtr name = suffix;
  205180. err = PtrAndHand (name, dataRef, name[0] + 1);
  205181. if (err == noErr)
  205182. {
  205183. long atoms[3];
  205184. atoms[0] = EndianU32_NtoB (3 * sizeof (long));
  205185. atoms[1] = EndianU32_NtoB (kDataRefExtensionMacOSFileType);
  205186. atoms[2] = EndianU32_NtoB (MovieFileType);
  205187. err = PtrAndHand (atoms, dataRef, 3 * sizeof (long));
  205188. if (err == noErr)
  205189. return dataRef;
  205190. }
  205191. DisposeHandle (dataRef);
  205192. }
  205193. return 0;
  205194. }
  205195. static CFStringRef juceStringToCFString (const String& s)
  205196. {
  205197. const int len = s.length();
  205198. const juce_wchar* const t = s;
  205199. HeapBlock <UniChar> temp (len + 2);
  205200. for (int i = 0; i <= len; ++i)
  205201. temp[i] = t[i];
  205202. return CFStringCreateWithCharacters (kCFAllocatorDefault, temp, len);
  205203. }
  205204. static bool openMovie (QTNewMoviePropertyElement* props, int prop, Movie& movie)
  205205. {
  205206. Boolean trueBool = true;
  205207. props[prop].propClass = kQTPropertyClass_MovieInstantiation;
  205208. props[prop].propID = kQTMovieInstantiationPropertyID_DontResolveDataRefs;
  205209. props[prop].propValueSize = sizeof (trueBool);
  205210. props[prop].propValueAddress = &trueBool;
  205211. ++prop;
  205212. props[prop].propClass = kQTPropertyClass_MovieInstantiation;
  205213. props[prop].propID = kQTMovieInstantiationPropertyID_AsyncOK;
  205214. props[prop].propValueSize = sizeof (trueBool);
  205215. props[prop].propValueAddress = &trueBool;
  205216. ++prop;
  205217. Boolean isActive = true;
  205218. props[prop].propClass = kQTPropertyClass_NewMovieProperty;
  205219. props[prop].propID = kQTNewMoviePropertyID_Active;
  205220. props[prop].propValueSize = sizeof (isActive);
  205221. props[prop].propValueAddress = &isActive;
  205222. ++prop;
  205223. MacSetPort (0);
  205224. jassert (prop <= 5);
  205225. OSStatus err = NewMovieFromProperties (prop, props, 0, 0, &movie);
  205226. return err == noErr;
  205227. }
  205228. bool juce_OpenQuickTimeMovieFromStream (InputStream* input, Movie& movie, Handle& dataHandle)
  205229. {
  205230. if (input == 0)
  205231. return false;
  205232. dataHandle = 0;
  205233. bool ok = false;
  205234. QTNewMoviePropertyElement props[5];
  205235. zeromem (props, sizeof (props));
  205236. int prop = 0;
  205237. DataReferenceRecord dr;
  205238. props[prop].propClass = kQTPropertyClass_DataLocation;
  205239. props[prop].propID = kQTDataLocationPropertyID_DataReference;
  205240. props[prop].propValueSize = sizeof (dr);
  205241. props[prop].propValueAddress = &dr;
  205242. ++prop;
  205243. FileInputStream* const fin = dynamic_cast <FileInputStream*> (input);
  205244. if (fin != 0)
  205245. {
  205246. CFStringRef filePath = juceStringToCFString (fin->getFile().getFullPathName());
  205247. QTNewDataReferenceFromFullPathCFString (filePath, (QTPathStyle) kQTNativeDefaultPathStyle, 0,
  205248. &dr.dataRef, &dr.dataRefType);
  205249. ok = openMovie (props, prop, movie);
  205250. DisposeHandle (dr.dataRef);
  205251. CFRelease (filePath);
  205252. }
  205253. else
  205254. {
  205255. // sanity-check because this currently needs to load the whole stream into memory..
  205256. jassert (input->getTotalLength() < 50 * 1024 * 1024);
  205257. dataHandle = NewHandle ((Size) input->getTotalLength());
  205258. HLock (dataHandle);
  205259. // read the entire stream into memory - this is a pain, but can't get it to work
  205260. // properly using a custom callback to supply the data.
  205261. input->read (*dataHandle, (int) input->getTotalLength());
  205262. HUnlock (dataHandle);
  205263. // different types to get QT to try. (We should really be a bit smarter here by
  205264. // working out in advance which one the stream contains, rather than just trying
  205265. // each one)
  205266. const char* const suffixesToTry[] = { "\04.mov", "\04.mp3",
  205267. "\04.avi", "\04.m4a" };
  205268. for (int i = 0; i < numElementsInArray (suffixesToTry) && ! ok; ++i)
  205269. {
  205270. /* // this fails for some bizarre reason - it can be bodged to work with
  205271. // movies, but can't seem to do it for other file types..
  205272. QTNewMovieUserProcRecord procInfo;
  205273. procInfo.getMovieUserProc = NewGetMovieUPP (readMovieStreamProc);
  205274. procInfo.getMovieUserProcRefcon = this;
  205275. procInfo.defaultDataRef.dataRef = dataRef;
  205276. procInfo.defaultDataRef.dataRefType = HandleDataHandlerSubType;
  205277. props[prop].propClass = kQTPropertyClass_DataLocation;
  205278. props[prop].propID = kQTDataLocationPropertyID_MovieUserProc;
  205279. props[prop].propValueSize = sizeof (procInfo);
  205280. props[prop].propValueAddress = (void*) &procInfo;
  205281. ++prop; */
  205282. dr.dataRef = createHandleDataRef (dataHandle, suffixesToTry [i]);
  205283. dr.dataRefType = HandleDataHandlerSubType;
  205284. ok = openMovie (props, prop, movie);
  205285. DisposeHandle (dr.dataRef);
  205286. }
  205287. }
  205288. return ok;
  205289. }
  205290. bool QuickTimeMovieComponent::loadMovie (const File& movieFile_,
  205291. const bool isControllerVisible)
  205292. {
  205293. const bool ok = loadMovie (static_cast <InputStream*> (movieFile_.createInputStream()), isControllerVisible);
  205294. movieFile = movieFile_;
  205295. return ok;
  205296. }
  205297. bool QuickTimeMovieComponent::loadMovie (const URL& movieURL,
  205298. const bool isControllerVisible)
  205299. {
  205300. return loadMovie (static_cast <InputStream*> (movieURL.createInputStream (false)), isControllerVisible);
  205301. }
  205302. void QuickTimeMovieComponent::goToStart()
  205303. {
  205304. setPosition (0.0);
  205305. }
  205306. void QuickTimeMovieComponent::setBoundsWithCorrectAspectRatio (const Rectangle<int>& spaceToFitWithin,
  205307. const RectanglePlacement& placement)
  205308. {
  205309. int normalWidth, normalHeight;
  205310. getMovieNormalSize (normalWidth, normalHeight);
  205311. if (normalWidth > 0 && normalHeight > 0 && ! spaceToFitWithin.isEmpty())
  205312. {
  205313. double x = 0.0, y = 0.0, w = normalWidth, h = normalHeight;
  205314. placement.applyTo (x, y, w, h,
  205315. spaceToFitWithin.getX(), spaceToFitWithin.getY(),
  205316. spaceToFitWithin.getWidth(), spaceToFitWithin.getHeight());
  205317. if (w > 0 && h > 0)
  205318. {
  205319. setBounds (roundToInt (x), roundToInt (y),
  205320. roundToInt (w), roundToInt (h));
  205321. }
  205322. }
  205323. else
  205324. {
  205325. setBounds (spaceToFitWithin);
  205326. }
  205327. }
  205328. #endif
  205329. /*** End of inlined file: juce_win32_QuickTimeMovieComponent.cpp ***/
  205330. /*** Start of inlined file: juce_win32_WebBrowserComponent.cpp ***/
  205331. // (This file gets included by juce_win32_NativeCode.cpp, rather than being
  205332. // compiled on its own).
  205333. #if JUCE_INCLUDED_FILE && JUCE_WEB_BROWSER
  205334. class WebBrowserComponentInternal : public ActiveXControlComponent
  205335. {
  205336. public:
  205337. WebBrowserComponentInternal()
  205338. : browser (0),
  205339. connectionPoint (0),
  205340. adviseCookie (0)
  205341. {
  205342. }
  205343. ~WebBrowserComponentInternal()
  205344. {
  205345. if (connectionPoint != 0)
  205346. connectionPoint->Unadvise (adviseCookie);
  205347. if (browser != 0)
  205348. browser->Release();
  205349. }
  205350. void createBrowser()
  205351. {
  205352. createControl (&CLSID_WebBrowser);
  205353. browser = (IWebBrowser2*) queryInterface (&IID_IWebBrowser2);
  205354. IConnectionPointContainer* connectionPointContainer = (IConnectionPointContainer*) queryInterface (&IID_IConnectionPointContainer);
  205355. if (connectionPointContainer != 0)
  205356. {
  205357. connectionPointContainer->FindConnectionPoint (DIID_DWebBrowserEvents2,
  205358. &connectionPoint);
  205359. if (connectionPoint != 0)
  205360. {
  205361. WebBrowserComponent* const owner = dynamic_cast <WebBrowserComponent*> (getParentComponent());
  205362. jassert (owner != 0);
  205363. EventHandler* handler = new EventHandler (owner);
  205364. connectionPoint->Advise (handler, &adviseCookie);
  205365. handler->Release();
  205366. }
  205367. }
  205368. }
  205369. void goToURL (const String& url,
  205370. const StringArray* headers,
  205371. const MemoryBlock* postData)
  205372. {
  205373. if (browser != 0)
  205374. {
  205375. LPSAFEARRAY sa = 0;
  205376. VARIANT flags, frame, postDataVar, headersVar; // (_variant_t isn't available in all compilers)
  205377. VariantInit (&flags);
  205378. VariantInit (&frame);
  205379. VariantInit (&postDataVar);
  205380. VariantInit (&headersVar);
  205381. if (headers != 0)
  205382. {
  205383. V_VT (&headersVar) = VT_BSTR;
  205384. V_BSTR (&headersVar) = SysAllocString ((const OLECHAR*) headers->joinIntoString ("\r\n"));
  205385. }
  205386. if (postData != 0 && postData->getSize() > 0)
  205387. {
  205388. LPSAFEARRAY sa = SafeArrayCreateVector (VT_UI1, 0, postData->getSize());
  205389. if (sa != 0)
  205390. {
  205391. void* data = 0;
  205392. SafeArrayAccessData (sa, &data);
  205393. jassert (data != 0);
  205394. if (data != 0)
  205395. {
  205396. postData->copyTo (data, 0, postData->getSize());
  205397. SafeArrayUnaccessData (sa);
  205398. VARIANT postDataVar2;
  205399. VariantInit (&postDataVar2);
  205400. V_VT (&postDataVar2) = VT_ARRAY | VT_UI1;
  205401. V_ARRAY (&postDataVar2) = sa;
  205402. postDataVar = postDataVar2;
  205403. }
  205404. }
  205405. }
  205406. browser->Navigate ((BSTR) (const OLECHAR*) url,
  205407. &flags, &frame,
  205408. &postDataVar, &headersVar);
  205409. if (sa != 0)
  205410. SafeArrayDestroy (sa);
  205411. VariantClear (&flags);
  205412. VariantClear (&frame);
  205413. VariantClear (&postDataVar);
  205414. VariantClear (&headersVar);
  205415. }
  205416. }
  205417. IWebBrowser2* browser;
  205418. juce_UseDebuggingNewOperator
  205419. private:
  205420. IConnectionPoint* connectionPoint;
  205421. DWORD adviseCookie;
  205422. class EventHandler : public ComBaseClassHelper <IDispatch>,
  205423. public ComponentMovementWatcher
  205424. {
  205425. public:
  205426. EventHandler (WebBrowserComponent* owner_)
  205427. : ComponentMovementWatcher (owner_),
  205428. owner (owner_)
  205429. {
  205430. }
  205431. ~EventHandler()
  205432. {
  205433. }
  205434. HRESULT __stdcall GetTypeInfoCount (UINT __RPC_FAR*) { return E_NOTIMPL; }
  205435. HRESULT __stdcall GetTypeInfo (UINT, LCID, ITypeInfo __RPC_FAR *__RPC_FAR*) { return E_NOTIMPL; }
  205436. HRESULT __stdcall GetIDsOfNames (REFIID, LPOLESTR __RPC_FAR*, UINT, LCID, DISPID __RPC_FAR*) { return E_NOTIMPL; }
  205437. HRESULT __stdcall Invoke (DISPID dispIdMember, REFIID /*riid*/, LCID /*lcid*/,
  205438. WORD /*wFlags*/, DISPPARAMS __RPC_FAR* pDispParams,
  205439. VARIANT __RPC_FAR* /*pVarResult*/, EXCEPINFO __RPC_FAR* /*pExcepInfo*/,
  205440. UINT __RPC_FAR* /*puArgErr*/)
  205441. {
  205442. switch (dispIdMember)
  205443. {
  205444. case DISPID_BEFORENAVIGATE2:
  205445. {
  205446. VARIANT* const vurl = pDispParams->rgvarg[5].pvarVal;
  205447. String url;
  205448. if ((vurl->vt & VT_BYREF) != 0)
  205449. url = *vurl->pbstrVal;
  205450. else
  205451. url = vurl->bstrVal;
  205452. *pDispParams->rgvarg->pboolVal
  205453. = owner->pageAboutToLoad (url) ? VARIANT_FALSE
  205454. : VARIANT_TRUE;
  205455. return S_OK;
  205456. }
  205457. default:
  205458. break;
  205459. }
  205460. return E_NOTIMPL;
  205461. }
  205462. void componentMovedOrResized (bool /*wasMoved*/, bool /*wasResized*/) {}
  205463. void componentPeerChanged() {}
  205464. void componentVisibilityChanged (Component&)
  205465. {
  205466. owner->visibilityChanged();
  205467. }
  205468. juce_UseDebuggingNewOperator
  205469. private:
  205470. WebBrowserComponent* const owner;
  205471. EventHandler (const EventHandler&);
  205472. EventHandler& operator= (const EventHandler&);
  205473. };
  205474. };
  205475. WebBrowserComponent::WebBrowserComponent (const bool unloadPageWhenBrowserIsHidden_)
  205476. : browser (0),
  205477. blankPageShown (false),
  205478. unloadPageWhenBrowserIsHidden (unloadPageWhenBrowserIsHidden_)
  205479. {
  205480. setOpaque (true);
  205481. addAndMakeVisible (browser = new WebBrowserComponentInternal());
  205482. }
  205483. WebBrowserComponent::~WebBrowserComponent()
  205484. {
  205485. delete browser;
  205486. }
  205487. void WebBrowserComponent::goToURL (const String& url,
  205488. const StringArray* headers,
  205489. const MemoryBlock* postData)
  205490. {
  205491. lastURL = url;
  205492. lastHeaders.clear();
  205493. if (headers != 0)
  205494. lastHeaders = *headers;
  205495. lastPostData.setSize (0);
  205496. if (postData != 0)
  205497. lastPostData = *postData;
  205498. blankPageShown = false;
  205499. browser->goToURL (url, headers, postData);
  205500. }
  205501. void WebBrowserComponent::stop()
  205502. {
  205503. if (browser->browser != 0)
  205504. browser->browser->Stop();
  205505. }
  205506. void WebBrowserComponent::goBack()
  205507. {
  205508. lastURL = String::empty;
  205509. blankPageShown = false;
  205510. if (browser->browser != 0)
  205511. browser->browser->GoBack();
  205512. }
  205513. void WebBrowserComponent::goForward()
  205514. {
  205515. lastURL = String::empty;
  205516. if (browser->browser != 0)
  205517. browser->browser->GoForward();
  205518. }
  205519. void WebBrowserComponent::refresh()
  205520. {
  205521. if (browser->browser != 0)
  205522. browser->browser->Refresh();
  205523. }
  205524. void WebBrowserComponent::paint (Graphics& g)
  205525. {
  205526. if (browser->browser == 0)
  205527. g.fillAll (Colours::white);
  205528. }
  205529. void WebBrowserComponent::checkWindowAssociation()
  205530. {
  205531. if (isShowing())
  205532. {
  205533. if (browser->browser == 0 && getPeer() != 0)
  205534. {
  205535. browser->createBrowser();
  205536. reloadLastURL();
  205537. }
  205538. else
  205539. {
  205540. if (blankPageShown)
  205541. goBack();
  205542. }
  205543. }
  205544. else
  205545. {
  205546. if (browser != 0 && unloadPageWhenBrowserIsHidden && ! blankPageShown)
  205547. {
  205548. // when the component becomes invisible, some stuff like flash
  205549. // carries on playing audio, so we need to force it onto a blank
  205550. // page to avoid this..
  205551. blankPageShown = true;
  205552. browser->goToURL ("about:blank", 0, 0);
  205553. }
  205554. }
  205555. }
  205556. void WebBrowserComponent::reloadLastURL()
  205557. {
  205558. if (lastURL.isNotEmpty())
  205559. {
  205560. goToURL (lastURL, &lastHeaders, &lastPostData);
  205561. lastURL = String::empty;
  205562. }
  205563. }
  205564. void WebBrowserComponent::parentHierarchyChanged()
  205565. {
  205566. checkWindowAssociation();
  205567. }
  205568. void WebBrowserComponent::resized()
  205569. {
  205570. browser->setSize (getWidth(), getHeight());
  205571. }
  205572. void WebBrowserComponent::visibilityChanged()
  205573. {
  205574. checkWindowAssociation();
  205575. }
  205576. bool WebBrowserComponent::pageAboutToLoad (const String&)
  205577. {
  205578. return true;
  205579. }
  205580. #endif
  205581. /*** End of inlined file: juce_win32_WebBrowserComponent.cpp ***/
  205582. /*** Start of inlined file: juce_win32_OpenGLComponent.cpp ***/
  205583. // (This file gets included by juce_win32_NativeCode.cpp, rather than being
  205584. // compiled on its own).
  205585. #if JUCE_INCLUDED_FILE && JUCE_OPENGL
  205586. #define WGL_EXT_FUNCTION_INIT(extType, extFunc) \
  205587. ((extFunc = (extType) wglGetProcAddress (#extFunc)) != 0)
  205588. typedef const char* (WINAPI* PFNWGLGETEXTENSIONSSTRINGARBPROC) (HDC hdc);
  205589. typedef BOOL (WINAPI * PFNWGLGETPIXELFORMATATTRIBIVARBPROC) (HDC hdc, int iPixelFormat, int iLayerPlane, UINT nAttributes, const int *piAttributes, int *piValues);
  205590. typedef BOOL (WINAPI * PFNWGLCHOOSEPIXELFORMATARBPROC) (HDC hdc, const int* piAttribIList, const FLOAT *pfAttribFList, UINT nMaxFormats, int *piFormats, UINT *nNumFormats);
  205591. typedef BOOL (WINAPI * PFNWGLSWAPINTERVALEXTPROC) (int interval);
  205592. typedef int (WINAPI * PFNWGLGETSWAPINTERVALEXTPROC) (void);
  205593. #define WGL_NUMBER_PIXEL_FORMATS_ARB 0x2000
  205594. #define WGL_DRAW_TO_WINDOW_ARB 0x2001
  205595. #define WGL_ACCELERATION_ARB 0x2003
  205596. #define WGL_SWAP_METHOD_ARB 0x2007
  205597. #define WGL_SUPPORT_OPENGL_ARB 0x2010
  205598. #define WGL_PIXEL_TYPE_ARB 0x2013
  205599. #define WGL_DOUBLE_BUFFER_ARB 0x2011
  205600. #define WGL_COLOR_BITS_ARB 0x2014
  205601. #define WGL_RED_BITS_ARB 0x2015
  205602. #define WGL_GREEN_BITS_ARB 0x2017
  205603. #define WGL_BLUE_BITS_ARB 0x2019
  205604. #define WGL_ALPHA_BITS_ARB 0x201B
  205605. #define WGL_DEPTH_BITS_ARB 0x2022
  205606. #define WGL_STENCIL_BITS_ARB 0x2023
  205607. #define WGL_FULL_ACCELERATION_ARB 0x2027
  205608. #define WGL_ACCUM_RED_BITS_ARB 0x201E
  205609. #define WGL_ACCUM_GREEN_BITS_ARB 0x201F
  205610. #define WGL_ACCUM_BLUE_BITS_ARB 0x2020
  205611. #define WGL_ACCUM_ALPHA_BITS_ARB 0x2021
  205612. #define WGL_STEREO_ARB 0x2012
  205613. #define WGL_SAMPLE_BUFFERS_ARB 0x2041
  205614. #define WGL_SAMPLES_ARB 0x2042
  205615. #define WGL_TYPE_RGBA_ARB 0x202B
  205616. static void getWglExtensions (HDC dc, StringArray& result) throw()
  205617. {
  205618. PFNWGLGETEXTENSIONSSTRINGARBPROC wglGetExtensionsStringARB = 0;
  205619. if (WGL_EXT_FUNCTION_INIT (PFNWGLGETEXTENSIONSSTRINGARBPROC, wglGetExtensionsStringARB))
  205620. result.addTokens (String (wglGetExtensionsStringARB (dc)), false);
  205621. else
  205622. jassertfalse // If this fails, it may be because you didn't activate the openGL context
  205623. }
  205624. class WindowedGLContext : public OpenGLContext
  205625. {
  205626. public:
  205627. WindowedGLContext (Component* const component_,
  205628. HGLRC contextToShareWith,
  205629. const OpenGLPixelFormat& pixelFormat)
  205630. : renderContext (0),
  205631. nativeWindow (0),
  205632. dc (0),
  205633. component (component_)
  205634. {
  205635. jassert (component != 0);
  205636. createNativeWindow();
  205637. // Use a default pixel format that should be supported everywhere
  205638. PIXELFORMATDESCRIPTOR pfd;
  205639. zerostruct (pfd);
  205640. pfd.nSize = sizeof (pfd);
  205641. pfd.nVersion = 1;
  205642. pfd.dwFlags = PFD_DRAW_TO_WINDOW | PFD_SUPPORT_OPENGL | PFD_DOUBLEBUFFER;
  205643. pfd.iPixelType = PFD_TYPE_RGBA;
  205644. pfd.cColorBits = 24;
  205645. pfd.cDepthBits = 16;
  205646. const int format = ChoosePixelFormat (dc, &pfd);
  205647. if (format != 0)
  205648. SetPixelFormat (dc, format, &pfd);
  205649. renderContext = wglCreateContext (dc);
  205650. makeActive();
  205651. setPixelFormat (pixelFormat);
  205652. if (contextToShareWith != 0 && renderContext != 0)
  205653. wglShareLists (contextToShareWith, renderContext);
  205654. }
  205655. ~WindowedGLContext()
  205656. {
  205657. makeInactive();
  205658. wglDeleteContext (renderContext);
  205659. ReleaseDC ((HWND) nativeWindow->getNativeHandle(), dc);
  205660. delete nativeWindow;
  205661. }
  205662. bool makeActive() const throw()
  205663. {
  205664. jassert (renderContext != 0);
  205665. return wglMakeCurrent (dc, renderContext) != 0;
  205666. }
  205667. bool makeInactive() const throw()
  205668. {
  205669. return (! isActive()) || (wglMakeCurrent (0, 0) != 0);
  205670. }
  205671. bool isActive() const throw()
  205672. {
  205673. return wglGetCurrentContext() == renderContext;
  205674. }
  205675. const OpenGLPixelFormat getPixelFormat() const
  205676. {
  205677. OpenGLPixelFormat pf;
  205678. makeActive();
  205679. StringArray availableExtensions;
  205680. getWglExtensions (dc, availableExtensions);
  205681. fillInPixelFormatDetails (GetPixelFormat (dc), pf, availableExtensions);
  205682. return pf;
  205683. }
  205684. void* getRawContext() const throw()
  205685. {
  205686. return renderContext;
  205687. }
  205688. bool setPixelFormat (const OpenGLPixelFormat& pixelFormat)
  205689. {
  205690. makeActive();
  205691. PIXELFORMATDESCRIPTOR pfd;
  205692. zerostruct (pfd);
  205693. pfd.nSize = sizeof (pfd);
  205694. pfd.nVersion = 1;
  205695. pfd.dwFlags = PFD_SUPPORT_OPENGL | PFD_DRAW_TO_WINDOW | PFD_DOUBLEBUFFER;
  205696. pfd.iPixelType = PFD_TYPE_RGBA;
  205697. pfd.iLayerType = PFD_MAIN_PLANE;
  205698. pfd.cColorBits = (BYTE) (pixelFormat.redBits + pixelFormat.greenBits + pixelFormat.blueBits);
  205699. pfd.cRedBits = (BYTE) pixelFormat.redBits;
  205700. pfd.cGreenBits = (BYTE) pixelFormat.greenBits;
  205701. pfd.cBlueBits = (BYTE) pixelFormat.blueBits;
  205702. pfd.cAlphaBits = (BYTE) pixelFormat.alphaBits;
  205703. pfd.cDepthBits = (BYTE) pixelFormat.depthBufferBits;
  205704. pfd.cStencilBits = (BYTE) pixelFormat.stencilBufferBits;
  205705. pfd.cAccumBits = (BYTE) (pixelFormat.accumulationBufferRedBits + pixelFormat.accumulationBufferGreenBits
  205706. + pixelFormat.accumulationBufferBlueBits + pixelFormat.accumulationBufferAlphaBits);
  205707. pfd.cAccumRedBits = (BYTE) pixelFormat.accumulationBufferRedBits;
  205708. pfd.cAccumGreenBits = (BYTE) pixelFormat.accumulationBufferGreenBits;
  205709. pfd.cAccumBlueBits = (BYTE) pixelFormat.accumulationBufferBlueBits;
  205710. pfd.cAccumAlphaBits = (BYTE) pixelFormat.accumulationBufferAlphaBits;
  205711. int format = 0;
  205712. PFNWGLCHOOSEPIXELFORMATARBPROC wglChoosePixelFormatARB = 0;
  205713. StringArray availableExtensions;
  205714. getWglExtensions (dc, availableExtensions);
  205715. if (availableExtensions.contains ("WGL_ARB_pixel_format")
  205716. && WGL_EXT_FUNCTION_INIT (PFNWGLCHOOSEPIXELFORMATARBPROC, wglChoosePixelFormatARB))
  205717. {
  205718. int attributes[64];
  205719. int n = 0;
  205720. attributes[n++] = WGL_DRAW_TO_WINDOW_ARB;
  205721. attributes[n++] = GL_TRUE;
  205722. attributes[n++] = WGL_SUPPORT_OPENGL_ARB;
  205723. attributes[n++] = GL_TRUE;
  205724. attributes[n++] = WGL_ACCELERATION_ARB;
  205725. attributes[n++] = WGL_FULL_ACCELERATION_ARB;
  205726. attributes[n++] = WGL_DOUBLE_BUFFER_ARB;
  205727. attributes[n++] = GL_TRUE;
  205728. attributes[n++] = WGL_PIXEL_TYPE_ARB;
  205729. attributes[n++] = WGL_TYPE_RGBA_ARB;
  205730. attributes[n++] = WGL_COLOR_BITS_ARB;
  205731. attributes[n++] = pfd.cColorBits;
  205732. attributes[n++] = WGL_RED_BITS_ARB;
  205733. attributes[n++] = pixelFormat.redBits;
  205734. attributes[n++] = WGL_GREEN_BITS_ARB;
  205735. attributes[n++] = pixelFormat.greenBits;
  205736. attributes[n++] = WGL_BLUE_BITS_ARB;
  205737. attributes[n++] = pixelFormat.blueBits;
  205738. attributes[n++] = WGL_ALPHA_BITS_ARB;
  205739. attributes[n++] = pixelFormat.alphaBits;
  205740. attributes[n++] = WGL_DEPTH_BITS_ARB;
  205741. attributes[n++] = pixelFormat.depthBufferBits;
  205742. if (pixelFormat.stencilBufferBits > 0)
  205743. {
  205744. attributes[n++] = WGL_STENCIL_BITS_ARB;
  205745. attributes[n++] = pixelFormat.stencilBufferBits;
  205746. }
  205747. attributes[n++] = WGL_ACCUM_RED_BITS_ARB;
  205748. attributes[n++] = pixelFormat.accumulationBufferRedBits;
  205749. attributes[n++] = WGL_ACCUM_GREEN_BITS_ARB;
  205750. attributes[n++] = pixelFormat.accumulationBufferGreenBits;
  205751. attributes[n++] = WGL_ACCUM_BLUE_BITS_ARB;
  205752. attributes[n++] = pixelFormat.accumulationBufferBlueBits;
  205753. attributes[n++] = WGL_ACCUM_ALPHA_BITS_ARB;
  205754. attributes[n++] = pixelFormat.accumulationBufferAlphaBits;
  205755. if (availableExtensions.contains ("WGL_ARB_multisample")
  205756. && pixelFormat.fullSceneAntiAliasingNumSamples > 0)
  205757. {
  205758. attributes[n++] = WGL_SAMPLE_BUFFERS_ARB;
  205759. attributes[n++] = 1;
  205760. attributes[n++] = WGL_SAMPLES_ARB;
  205761. attributes[n++] = pixelFormat.fullSceneAntiAliasingNumSamples;
  205762. }
  205763. attributes[n++] = 0;
  205764. UINT formatsCount;
  205765. const BOOL ok = wglChoosePixelFormatARB (dc, attributes, 0, 1, &format, &formatsCount);
  205766. (void) ok;
  205767. jassert (ok);
  205768. }
  205769. else
  205770. {
  205771. format = ChoosePixelFormat (dc, &pfd);
  205772. }
  205773. if (format != 0)
  205774. {
  205775. makeInactive();
  205776. // win32 can't change the pixel format of a window, so need to delete the
  205777. // old one and create a new one..
  205778. jassert (nativeWindow != 0);
  205779. ReleaseDC ((HWND) nativeWindow->getNativeHandle(), dc);
  205780. delete nativeWindow;
  205781. createNativeWindow();
  205782. if (SetPixelFormat (dc, format, &pfd))
  205783. {
  205784. wglDeleteContext (renderContext);
  205785. renderContext = wglCreateContext (dc);
  205786. jassert (renderContext != 0);
  205787. return renderContext != 0;
  205788. }
  205789. }
  205790. return false;
  205791. }
  205792. void updateWindowPosition (int x, int y, int w, int h, int)
  205793. {
  205794. SetWindowPos ((HWND) nativeWindow->getNativeHandle(), 0,
  205795. x, y, w, h,
  205796. SWP_NOACTIVATE | SWP_NOZORDER | SWP_NOOWNERZORDER);
  205797. }
  205798. void repaint()
  205799. {
  205800. const Rectangle<int> bounds (nativeWindow->getBounds());
  205801. nativeWindow->repaint (0, 0, bounds.getWidth(), bounds.getHeight());
  205802. }
  205803. void swapBuffers()
  205804. {
  205805. SwapBuffers (dc);
  205806. }
  205807. bool setSwapInterval (int numFramesPerSwap)
  205808. {
  205809. makeActive();
  205810. StringArray availableExtensions;
  205811. getWglExtensions (dc, availableExtensions);
  205812. PFNWGLSWAPINTERVALEXTPROC wglSwapIntervalEXT = 0;
  205813. return availableExtensions.contains ("WGL_EXT_swap_control")
  205814. && WGL_EXT_FUNCTION_INIT (PFNWGLSWAPINTERVALEXTPROC, wglSwapIntervalEXT)
  205815. && wglSwapIntervalEXT (numFramesPerSwap) != FALSE;
  205816. }
  205817. int getSwapInterval() const
  205818. {
  205819. makeActive();
  205820. StringArray availableExtensions;
  205821. getWglExtensions (dc, availableExtensions);
  205822. PFNWGLGETSWAPINTERVALEXTPROC wglGetSwapIntervalEXT = 0;
  205823. if (availableExtensions.contains ("WGL_EXT_swap_control")
  205824. && WGL_EXT_FUNCTION_INIT (PFNWGLGETSWAPINTERVALEXTPROC, wglGetSwapIntervalEXT))
  205825. return wglGetSwapIntervalEXT();
  205826. return 0;
  205827. }
  205828. void findAlternativeOpenGLPixelFormats (OwnedArray <OpenGLPixelFormat>& results)
  205829. {
  205830. jassert (isActive());
  205831. StringArray availableExtensions;
  205832. getWglExtensions (dc, availableExtensions);
  205833. PFNWGLGETPIXELFORMATATTRIBIVARBPROC wglGetPixelFormatAttribivARB = 0;
  205834. int numTypes = 0;
  205835. if (availableExtensions.contains("WGL_ARB_pixel_format")
  205836. && WGL_EXT_FUNCTION_INIT (PFNWGLGETPIXELFORMATATTRIBIVARBPROC, wglGetPixelFormatAttribivARB))
  205837. {
  205838. int attributes = WGL_NUMBER_PIXEL_FORMATS_ARB;
  205839. if (! wglGetPixelFormatAttribivARB (dc, 1, 0, 1, &attributes, &numTypes))
  205840. jassertfalse
  205841. }
  205842. else
  205843. {
  205844. numTypes = DescribePixelFormat (dc, 0, 0, 0);
  205845. }
  205846. OpenGLPixelFormat pf;
  205847. for (int i = 0; i < numTypes; ++i)
  205848. {
  205849. if (fillInPixelFormatDetails (i + 1, pf, availableExtensions))
  205850. {
  205851. bool alreadyListed = false;
  205852. for (int j = results.size(); --j >= 0;)
  205853. if (pf == *results.getUnchecked(j))
  205854. alreadyListed = true;
  205855. if (! alreadyListed)
  205856. results.add (new OpenGLPixelFormat (pf));
  205857. }
  205858. }
  205859. }
  205860. void* getNativeWindowHandle() const
  205861. {
  205862. return nativeWindow != 0 ? nativeWindow->getNativeHandle() : 0;
  205863. }
  205864. juce_UseDebuggingNewOperator
  205865. HGLRC renderContext;
  205866. private:
  205867. Win32ComponentPeer* nativeWindow;
  205868. Component* const component;
  205869. HDC dc;
  205870. void createNativeWindow()
  205871. {
  205872. nativeWindow = new Win32ComponentPeer (component, 0);
  205873. nativeWindow->dontRepaint = true;
  205874. nativeWindow->setVisible (true);
  205875. HWND hwnd = (HWND) nativeWindow->getNativeHandle();
  205876. Win32ComponentPeer* const peer = dynamic_cast <Win32ComponentPeer*> (component->getTopLevelComponent()->getPeer());
  205877. if (peer != 0)
  205878. {
  205879. SetParent (hwnd, (HWND) peer->getNativeHandle());
  205880. juce_setWindowStyleBit (hwnd, GWL_STYLE, WS_CHILD, true);
  205881. juce_setWindowStyleBit (hwnd, GWL_STYLE, WS_POPUP, false);
  205882. }
  205883. dc = GetDC (hwnd);
  205884. }
  205885. bool fillInPixelFormatDetails (const int pixelFormatIndex,
  205886. OpenGLPixelFormat& result,
  205887. const StringArray& availableExtensions) const throw()
  205888. {
  205889. PFNWGLGETPIXELFORMATATTRIBIVARBPROC wglGetPixelFormatAttribivARB = 0;
  205890. if (availableExtensions.contains ("WGL_ARB_pixel_format")
  205891. && WGL_EXT_FUNCTION_INIT (PFNWGLGETPIXELFORMATATTRIBIVARBPROC, wglGetPixelFormatAttribivARB))
  205892. {
  205893. int attributes[32];
  205894. int numAttributes = 0;
  205895. attributes[numAttributes++] = WGL_DRAW_TO_WINDOW_ARB;
  205896. attributes[numAttributes++] = WGL_SUPPORT_OPENGL_ARB;
  205897. attributes[numAttributes++] = WGL_ACCELERATION_ARB;
  205898. attributes[numAttributes++] = WGL_DOUBLE_BUFFER_ARB;
  205899. attributes[numAttributes++] = WGL_PIXEL_TYPE_ARB;
  205900. attributes[numAttributes++] = WGL_RED_BITS_ARB;
  205901. attributes[numAttributes++] = WGL_GREEN_BITS_ARB;
  205902. attributes[numAttributes++] = WGL_BLUE_BITS_ARB;
  205903. attributes[numAttributes++] = WGL_ALPHA_BITS_ARB;
  205904. attributes[numAttributes++] = WGL_DEPTH_BITS_ARB;
  205905. attributes[numAttributes++] = WGL_STENCIL_BITS_ARB;
  205906. attributes[numAttributes++] = WGL_ACCUM_RED_BITS_ARB;
  205907. attributes[numAttributes++] = WGL_ACCUM_GREEN_BITS_ARB;
  205908. attributes[numAttributes++] = WGL_ACCUM_BLUE_BITS_ARB;
  205909. attributes[numAttributes++] = WGL_ACCUM_ALPHA_BITS_ARB;
  205910. if (availableExtensions.contains ("WGL_ARB_multisample"))
  205911. attributes[numAttributes++] = WGL_SAMPLES_ARB;
  205912. int values[32];
  205913. zeromem (values, sizeof (values));
  205914. if (wglGetPixelFormatAttribivARB (dc, pixelFormatIndex, 0, numAttributes, attributes, values))
  205915. {
  205916. int n = 0;
  205917. bool isValidFormat = (values[n++] == GL_TRUE); // WGL_DRAW_TO_WINDOW_ARB
  205918. isValidFormat = (values[n++] == GL_TRUE) && isValidFormat; // WGL_SUPPORT_OPENGL_ARB
  205919. isValidFormat = (values[n++] == WGL_FULL_ACCELERATION_ARB) && isValidFormat; // WGL_ACCELERATION_ARB
  205920. isValidFormat = (values[n++] == GL_TRUE) && isValidFormat; // WGL_DOUBLE_BUFFER_ARB:
  205921. isValidFormat = (values[n++] == WGL_TYPE_RGBA_ARB) && isValidFormat; // WGL_PIXEL_TYPE_ARB
  205922. result.redBits = values[n++]; // WGL_RED_BITS_ARB
  205923. result.greenBits = values[n++]; // WGL_GREEN_BITS_ARB
  205924. result.blueBits = values[n++]; // WGL_BLUE_BITS_ARB
  205925. result.alphaBits = values[n++]; // WGL_ALPHA_BITS_ARB
  205926. result.depthBufferBits = values[n++]; // WGL_DEPTH_BITS_ARB
  205927. result.stencilBufferBits = values[n++]; // WGL_STENCIL_BITS_ARB
  205928. result.accumulationBufferRedBits = values[n++]; // WGL_ACCUM_RED_BITS_ARB
  205929. result.accumulationBufferGreenBits = values[n++]; // WGL_ACCUM_GREEN_BITS_ARB
  205930. result.accumulationBufferBlueBits = values[n++]; // WGL_ACCUM_BLUE_BITS_ARB
  205931. result.accumulationBufferAlphaBits = values[n++]; // WGL_ACCUM_ALPHA_BITS_ARB
  205932. result.fullSceneAntiAliasingNumSamples = (uint8) values[n++]; // WGL_SAMPLES_ARB
  205933. return isValidFormat;
  205934. }
  205935. else
  205936. {
  205937. jassertfalse
  205938. }
  205939. }
  205940. else
  205941. {
  205942. PIXELFORMATDESCRIPTOR pfd;
  205943. if (DescribePixelFormat (dc, pixelFormatIndex, sizeof (pfd), &pfd))
  205944. {
  205945. result.redBits = pfd.cRedBits;
  205946. result.greenBits = pfd.cGreenBits;
  205947. result.blueBits = pfd.cBlueBits;
  205948. result.alphaBits = pfd.cAlphaBits;
  205949. result.depthBufferBits = pfd.cDepthBits;
  205950. result.stencilBufferBits = pfd.cStencilBits;
  205951. result.accumulationBufferRedBits = pfd.cAccumRedBits;
  205952. result.accumulationBufferGreenBits = pfd.cAccumGreenBits;
  205953. result.accumulationBufferBlueBits = pfd.cAccumBlueBits;
  205954. result.accumulationBufferAlphaBits = pfd.cAccumAlphaBits;
  205955. result.fullSceneAntiAliasingNumSamples = 0;
  205956. return true;
  205957. }
  205958. else
  205959. {
  205960. jassertfalse
  205961. }
  205962. }
  205963. return false;
  205964. }
  205965. WindowedGLContext (const WindowedGLContext&);
  205966. WindowedGLContext& operator= (const WindowedGLContext&);
  205967. };
  205968. OpenGLContext* OpenGLComponent::createContext()
  205969. {
  205970. ScopedPointer<WindowedGLContext> c (new WindowedGLContext (this,
  205971. contextToShareListsWith != 0 ? (HGLRC) contextToShareListsWith->getRawContext() : 0,
  205972. preferredPixelFormat));
  205973. return (c->renderContext != 0) ? c.release() : 0;
  205974. }
  205975. void* OpenGLComponent::getNativeWindowHandle() const
  205976. {
  205977. return context != 0 ? static_cast<WindowedGLContext*> (static_cast<OpenGLContext*> (context))->getNativeWindowHandle() : 0;
  205978. }
  205979. void juce_glViewport (const int w, const int h)
  205980. {
  205981. glViewport (0, 0, w, h);
  205982. }
  205983. void OpenGLPixelFormat::getAvailablePixelFormats (Component* component,
  205984. OwnedArray <OpenGLPixelFormat>& results)
  205985. {
  205986. Component tempComp;
  205987. {
  205988. WindowedGLContext wc (component, 0, OpenGLPixelFormat (8, 8, 16, 0));
  205989. wc.makeActive();
  205990. wc.findAlternativeOpenGLPixelFormats (results);
  205991. }
  205992. }
  205993. #endif
  205994. /*** End of inlined file: juce_win32_OpenGLComponent.cpp ***/
  205995. /*** Start of inlined file: juce_win32_AudioCDReader.cpp ***/
  205996. // (This file gets included by juce_win32_NativeCode.cpp, rather than being
  205997. // compiled on its own).
  205998. #if JUCE_INCLUDED_FILE
  205999. #if JUCE_USE_CDREADER
  206000. namespace CDReaderHelpers
  206001. {
  206002. //***************************************************************************
  206003. // %%% TARGET STATUS VALUES %%%
  206004. //***************************************************************************
  206005. #define STATUS_GOOD 0x00 // Status Good
  206006. #define STATUS_CHKCOND 0x02 // Check Condition
  206007. #define STATUS_CONDMET 0x04 // Condition Met
  206008. #define STATUS_BUSY 0x08 // Busy
  206009. #define STATUS_INTERM 0x10 // Intermediate
  206010. #define STATUS_INTCDMET 0x14 // Intermediate-condition met
  206011. #define STATUS_RESCONF 0x18 // Reservation conflict
  206012. #define STATUS_COMTERM 0x22 // Command Terminated
  206013. #define STATUS_QFULL 0x28 // Queue full
  206014. //***************************************************************************
  206015. // %%% SCSI MISCELLANEOUS EQUATES %%%
  206016. //***************************************************************************
  206017. #define MAXLUN 7 // Maximum Logical Unit Id
  206018. #define MAXTARG 7 // Maximum Target Id
  206019. #define MAX_SCSI_LUNS 64 // Maximum Number of SCSI LUNs
  206020. #define MAX_NUM_HA 8 // Maximum Number of SCSI HA's
  206021. //***************************************************************************
  206022. // %%% Commands for all Device Types %%%
  206023. //***************************************************************************
  206024. #define SCSI_CHANGE_DEF 0x40 // Change Definition (Optional)
  206025. #define SCSI_COMPARE 0x39 // Compare (O)
  206026. #define SCSI_COPY 0x18 // Copy (O)
  206027. #define SCSI_COP_VERIFY 0x3A // Copy and Verify (O)
  206028. #define SCSI_INQUIRY 0x12 // Inquiry (MANDATORY)
  206029. #define SCSI_LOG_SELECT 0x4C // Log Select (O)
  206030. #define SCSI_LOG_SENSE 0x4D // Log Sense (O)
  206031. #define SCSI_MODE_SEL6 0x15 // Mode Select 6-byte (Device Specific)
  206032. #define SCSI_MODE_SEL10 0x55 // Mode Select 10-byte (Device Specific)
  206033. #define SCSI_MODE_SEN6 0x1A // Mode Sense 6-byte (Device Specific)
  206034. #define SCSI_MODE_SEN10 0x5A // Mode Sense 10-byte (Device Specific)
  206035. #define SCSI_READ_BUFF 0x3C // Read Buffer (O)
  206036. #define SCSI_REQ_SENSE 0x03 // Request Sense (MANDATORY)
  206037. #define SCSI_SEND_DIAG 0x1D // Send Diagnostic (O)
  206038. #define SCSI_TST_U_RDY 0x00 // Test Unit Ready (MANDATORY)
  206039. #define SCSI_WRITE_BUFF 0x3B // Write Buffer (O)
  206040. //***************************************************************************
  206041. // %%% Commands Unique to Direct Access Devices %%%
  206042. //***************************************************************************
  206043. #define SCSI_COMPARE 0x39 // Compare (O)
  206044. #define SCSI_FORMAT 0x04 // Format Unit (MANDATORY)
  206045. #define SCSI_LCK_UN_CAC 0x36 // Lock Unlock Cache (O)
  206046. #define SCSI_PREFETCH 0x34 // Prefetch (O)
  206047. #define SCSI_MED_REMOVL 0x1E // Prevent/Allow medium Removal (O)
  206048. #define SCSI_READ6 0x08 // Read 6-byte (MANDATORY)
  206049. #define SCSI_READ10 0x28 // Read 10-byte (MANDATORY)
  206050. #define SCSI_RD_CAPAC 0x25 // Read Capacity (MANDATORY)
  206051. #define SCSI_RD_DEFECT 0x37 // Read Defect Data (O)
  206052. #define SCSI_READ_LONG 0x3E // Read Long (O)
  206053. #define SCSI_REASS_BLK 0x07 // Reassign Blocks (O)
  206054. #define SCSI_RCV_DIAG 0x1C // Receive Diagnostic Results (O)
  206055. #define SCSI_RELEASE 0x17 // Release Unit (MANDATORY)
  206056. #define SCSI_REZERO 0x01 // Rezero Unit (O)
  206057. #define SCSI_SRCH_DAT_E 0x31 // Search Data Equal (O)
  206058. #define SCSI_SRCH_DAT_H 0x30 // Search Data High (O)
  206059. #define SCSI_SRCH_DAT_L 0x32 // Search Data Low (O)
  206060. #define SCSI_SEEK6 0x0B // Seek 6-Byte (O)
  206061. #define SCSI_SEEK10 0x2B // Seek 10-Byte (O)
  206062. #define SCSI_SEND_DIAG 0x1D // Send Diagnostics (MANDATORY)
  206063. #define SCSI_SET_LIMIT 0x33 // Set Limits (O)
  206064. #define SCSI_START_STP 0x1B // Start/Stop Unit (O)
  206065. #define SCSI_SYNC_CACHE 0x35 // Synchronize Cache (O)
  206066. #define SCSI_VERIFY 0x2F // Verify (O)
  206067. #define SCSI_WRITE6 0x0A // Write 6-Byte (MANDATORY)
  206068. #define SCSI_WRITE10 0x2A // Write 10-Byte (MANDATORY)
  206069. #define SCSI_WRT_VERIFY 0x2E // Write and Verify (O)
  206070. #define SCSI_WRITE_LONG 0x3F // Write Long (O)
  206071. #define SCSI_WRITE_SAME 0x41 // Write Same (O)
  206072. //***************************************************************************
  206073. // %%% Commands Unique to Sequential Access Devices %%%
  206074. //***************************************************************************
  206075. #define SCSI_ERASE 0x19 // Erase (MANDATORY)
  206076. #define SCSI_LOAD_UN 0x1b // Load/Unload (O)
  206077. #define SCSI_LOCATE 0x2B // Locate (O)
  206078. #define SCSI_RD_BLK_LIM 0x05 // Read Block Limits (MANDATORY)
  206079. #define SCSI_READ_POS 0x34 // Read Position (O)
  206080. #define SCSI_READ_REV 0x0F // Read Reverse (O)
  206081. #define SCSI_REC_BF_DAT 0x14 // Recover Buffer Data (O)
  206082. #define SCSI_RESERVE 0x16 // Reserve Unit (MANDATORY)
  206083. #define SCSI_REWIND 0x01 // Rewind (MANDATORY)
  206084. #define SCSI_SPACE 0x11 // Space (MANDATORY)
  206085. #define SCSI_VERIFY_T 0x13 // Verify (Tape) (O)
  206086. #define SCSI_WRT_FILE 0x10 // Write Filemarks (MANDATORY)
  206087. //***************************************************************************
  206088. // %%% Commands Unique to Printer Devices %%%
  206089. //***************************************************************************
  206090. #define SCSI_PRINT 0x0A // Print (MANDATORY)
  206091. #define SCSI_SLEW_PNT 0x0B // Slew and Print (O)
  206092. #define SCSI_STOP_PNT 0x1B // Stop Print (O)
  206093. #define SCSI_SYNC_BUFF 0x10 // Synchronize Buffer (O)
  206094. //***************************************************************************
  206095. // %%% Commands Unique to Processor Devices %%%
  206096. //***************************************************************************
  206097. #define SCSI_RECEIVE 0x08 // Receive (O)
  206098. #define SCSI_SEND 0x0A // Send (O)
  206099. //***************************************************************************
  206100. // %%% Commands Unique to Write-Once Devices %%%
  206101. //***************************************************************************
  206102. #define SCSI_MEDIUM_SCN 0x38 // Medium Scan (O)
  206103. #define SCSI_SRCHDATE10 0x31 // Search Data Equal 10-Byte (O)
  206104. #define SCSI_SRCHDATE12 0xB1 // Search Data Equal 12-Byte (O)
  206105. #define SCSI_SRCHDATH10 0x30 // Search Data High 10-Byte (O)
  206106. #define SCSI_SRCHDATH12 0xB0 // Search Data High 12-Byte (O)
  206107. #define SCSI_SRCHDATL10 0x32 // Search Data Low 10-Byte (O)
  206108. #define SCSI_SRCHDATL12 0xB2 // Search Data Low 12-Byte (O)
  206109. #define SCSI_SET_LIM_10 0x33 // Set Limits 10-Byte (O)
  206110. #define SCSI_SET_LIM_12 0xB3 // Set Limits 10-Byte (O)
  206111. #define SCSI_VERIFY10 0x2F // Verify 10-Byte (O)
  206112. #define SCSI_VERIFY12 0xAF // Verify 12-Byte (O)
  206113. #define SCSI_WRITE12 0xAA // Write 12-Byte (O)
  206114. #define SCSI_WRT_VER10 0x2E // Write and Verify 10-Byte (O)
  206115. #define SCSI_WRT_VER12 0xAE // Write and Verify 12-Byte (O)
  206116. //***************************************************************************
  206117. // %%% Commands Unique to CD-ROM Devices %%%
  206118. //***************************************************************************
  206119. #define SCSI_PLAYAUD_10 0x45 // Play Audio 10-Byte (O)
  206120. #define SCSI_PLAYAUD_12 0xA5 // Play Audio 12-Byte 12-Byte (O)
  206121. #define SCSI_PLAYAUDMSF 0x47 // Play Audio MSF (O)
  206122. #define SCSI_PLAYA_TKIN 0x48 // Play Audio Track/Index (O)
  206123. #define SCSI_PLYTKREL10 0x49 // Play Track Relative 10-Byte (O)
  206124. #define SCSI_PLYTKREL12 0xA9 // Play Track Relative 12-Byte (O)
  206125. #define SCSI_READCDCAP 0x25 // Read CD-ROM Capacity (MANDATORY)
  206126. #define SCSI_READHEADER 0x44 // Read Header (O)
  206127. #define SCSI_SUBCHANNEL 0x42 // Read Subchannel (O)
  206128. #define SCSI_READ_TOC 0x43 // Read TOC (O)
  206129. //***************************************************************************
  206130. // %%% Commands Unique to Scanner Devices %%%
  206131. //***************************************************************************
  206132. #define SCSI_GETDBSTAT 0x34 // Get Data Buffer Status (O)
  206133. #define SCSI_GETWINDOW 0x25 // Get Window (O)
  206134. #define SCSI_OBJECTPOS 0x31 // Object Postion (O)
  206135. #define SCSI_SCAN 0x1B // Scan (O)
  206136. #define SCSI_SETWINDOW 0x24 // Set Window (MANDATORY)
  206137. //***************************************************************************
  206138. // %%% Commands Unique to Optical Memory Devices %%%
  206139. //***************************************************************************
  206140. #define SCSI_UpdateBlk 0x3D // Update Block (O)
  206141. //***************************************************************************
  206142. // %%% Commands Unique to Medium Changer Devices %%%
  206143. //***************************************************************************
  206144. #define SCSI_EXCHMEDIUM 0xA6 // Exchange Medium (O)
  206145. #define SCSI_INITELSTAT 0x07 // Initialize Element Status (O)
  206146. #define SCSI_POSTOELEM 0x2B // Position to Element (O)
  206147. #define SCSI_REQ_VE_ADD 0xB5 // Request Volume Element Address (O)
  206148. #define SCSI_SENDVOLTAG 0xB6 // Send Volume Tag (O)
  206149. //***************************************************************************
  206150. // %%% Commands Unique to Communication Devices %%%
  206151. //***************************************************************************
  206152. #define SCSI_GET_MSG_6 0x08 // Get Message 6-Byte (MANDATORY)
  206153. #define SCSI_GET_MSG_10 0x28 // Get Message 10-Byte (O)
  206154. #define SCSI_GET_MSG_12 0xA8 // Get Message 12-Byte (O)
  206155. #define SCSI_SND_MSG_6 0x0A // Send Message 6-Byte (MANDATORY)
  206156. #define SCSI_SND_MSG_10 0x2A // Send Message 10-Byte (O)
  206157. #define SCSI_SND_MSG_12 0xAA // Send Message 12-Byte (O)
  206158. //***************************************************************************
  206159. // %%% Request Sense Data Format %%%
  206160. //***************************************************************************
  206161. typedef struct {
  206162. BYTE ErrorCode; // Error Code (70H or 71H)
  206163. BYTE SegmentNum; // Number of current segment descriptor
  206164. BYTE SenseKey; // Sense Key(See bit definitions too)
  206165. BYTE InfoByte0; // Information MSB
  206166. BYTE InfoByte1; // Information MID
  206167. BYTE InfoByte2; // Information MID
  206168. BYTE InfoByte3; // Information LSB
  206169. BYTE AddSenLen; // Additional Sense Length
  206170. BYTE ComSpecInf0; // Command Specific Information MSB
  206171. BYTE ComSpecInf1; // Command Specific Information MID
  206172. BYTE ComSpecInf2; // Command Specific Information MID
  206173. BYTE ComSpecInf3; // Command Specific Information LSB
  206174. BYTE AddSenseCode; // Additional Sense Code
  206175. BYTE AddSenQual; // Additional Sense Code Qualifier
  206176. BYTE FieldRepUCode; // Field Replaceable Unit Code
  206177. BYTE SenKeySpec15; // Sense Key Specific 15th byte
  206178. BYTE SenKeySpec16; // Sense Key Specific 16th byte
  206179. BYTE SenKeySpec17; // Sense Key Specific 17th byte
  206180. BYTE AddSenseBytes; // Additional Sense Bytes
  206181. } SENSE_DATA_FMT;
  206182. //***************************************************************************
  206183. // %%% REQUEST SENSE ERROR CODE %%%
  206184. //***************************************************************************
  206185. #define SERROR_CURRENT 0x70 // Current Errors
  206186. #define SERROR_DEFERED 0x71 // Deferred Errors
  206187. //***************************************************************************
  206188. // %%% REQUEST SENSE BIT DEFINITIONS %%%
  206189. //***************************************************************************
  206190. #define SENSE_VALID 0x80 // Byte 0 Bit 7
  206191. #define SENSE_FILEMRK 0x80 // Byte 2 Bit 7
  206192. #define SENSE_EOM 0x40 // Byte 2 Bit 6
  206193. #define SENSE_ILI 0x20 // Byte 2 Bit 5
  206194. //***************************************************************************
  206195. // %%% REQUEST SENSE SENSE KEY DEFINITIONS %%%
  206196. //***************************************************************************
  206197. #define KEY_NOSENSE 0x00 // No Sense
  206198. #define KEY_RECERROR 0x01 // Recovered Error
  206199. #define KEY_NOTREADY 0x02 // Not Ready
  206200. #define KEY_MEDIUMERR 0x03 // Medium Error
  206201. #define KEY_HARDERROR 0x04 // Hardware Error
  206202. #define KEY_ILLGLREQ 0x05 // Illegal Request
  206203. #define KEY_UNITATT 0x06 // Unit Attention
  206204. #define KEY_DATAPROT 0x07 // Data Protect
  206205. #define KEY_BLANKCHK 0x08 // Blank Check
  206206. #define KEY_VENDSPEC 0x09 // Vendor Specific
  206207. #define KEY_COPYABORT 0x0A // Copy Abort
  206208. #define KEY_EQUAL 0x0C // Equal (Search)
  206209. #define KEY_VOLOVRFLW 0x0D // Volume Overflow
  206210. #define KEY_MISCOMP 0x0E // Miscompare (Search)
  206211. #define KEY_RESERVED 0x0F // Reserved
  206212. //***************************************************************************
  206213. // %%% PERIPHERAL DEVICE TYPE DEFINITIONS %%%
  206214. //***************************************************************************
  206215. #define DTYPE_DASD 0x00 // Disk Device
  206216. #define DTYPE_SEQD 0x01 // Tape Device
  206217. #define DTYPE_PRNT 0x02 // Printer
  206218. #define DTYPE_PROC 0x03 // Processor
  206219. #define DTYPE_WORM 0x04 // Write-once read-multiple
  206220. #define DTYPE_CROM 0x05 // CD-ROM device
  206221. #define DTYPE_SCAN 0x06 // Scanner device
  206222. #define DTYPE_OPTI 0x07 // Optical memory device
  206223. #define DTYPE_JUKE 0x08 // Medium Changer device
  206224. #define DTYPE_COMM 0x09 // Communications device
  206225. #define DTYPE_RESL 0x0A // Reserved (low)
  206226. #define DTYPE_RESH 0x1E // Reserved (high)
  206227. #define DTYPE_UNKNOWN 0x1F // Unknown or no device type
  206228. //***************************************************************************
  206229. // %%% ANSI APPROVED VERSION DEFINITIONS %%%
  206230. //***************************************************************************
  206231. #define ANSI_MAYBE 0x0 // Device may or may not be ANSI approved stand
  206232. #define ANSI_SCSI1 0x1 // Device complies to ANSI X3.131-1986 (SCSI-1)
  206233. #define ANSI_SCSI2 0x2 // Device complies to SCSI-2
  206234. #define ANSI_RESLO 0x3 // Reserved (low)
  206235. #define ANSI_RESHI 0x7 // Reserved (high)
  206236. typedef struct
  206237. {
  206238. USHORT Length;
  206239. UCHAR ScsiStatus;
  206240. UCHAR PathId;
  206241. UCHAR TargetId;
  206242. UCHAR Lun;
  206243. UCHAR CdbLength;
  206244. UCHAR SenseInfoLength;
  206245. UCHAR DataIn;
  206246. ULONG DataTransferLength;
  206247. ULONG TimeOutValue;
  206248. ULONG DataBufferOffset;
  206249. ULONG SenseInfoOffset;
  206250. UCHAR Cdb[16];
  206251. } SCSI_PASS_THROUGH, *PSCSI_PASS_THROUGH;
  206252. typedef struct
  206253. {
  206254. USHORT Length;
  206255. UCHAR ScsiStatus;
  206256. UCHAR PathId;
  206257. UCHAR TargetId;
  206258. UCHAR Lun;
  206259. UCHAR CdbLength;
  206260. UCHAR SenseInfoLength;
  206261. UCHAR DataIn;
  206262. ULONG DataTransferLength;
  206263. ULONG TimeOutValue;
  206264. PVOID DataBuffer;
  206265. ULONG SenseInfoOffset;
  206266. UCHAR Cdb[16];
  206267. } SCSI_PASS_THROUGH_DIRECT, *PSCSI_PASS_THROUGH_DIRECT;
  206268. typedef struct
  206269. {
  206270. SCSI_PASS_THROUGH_DIRECT spt;
  206271. ULONG Filler;
  206272. UCHAR ucSenseBuf[32];
  206273. } SCSI_PASS_THROUGH_DIRECT_WITH_BUFFER, *PSCSI_PASS_THROUGH_DIRECT_WITH_BUFFER;
  206274. typedef struct
  206275. {
  206276. ULONG Length;
  206277. UCHAR PortNumber;
  206278. UCHAR PathId;
  206279. UCHAR TargetId;
  206280. UCHAR Lun;
  206281. } SCSI_ADDRESS, *PSCSI_ADDRESS;
  206282. #define METHOD_BUFFERED 0
  206283. #define METHOD_IN_DIRECT 1
  206284. #define METHOD_OUT_DIRECT 2
  206285. #define METHOD_NEITHER 3
  206286. #define FILE_ANY_ACCESS 0
  206287. #ifndef FILE_READ_ACCESS
  206288. #define FILE_READ_ACCESS (0x0001)
  206289. #endif
  206290. #ifndef FILE_WRITE_ACCESS
  206291. #define FILE_WRITE_ACCESS (0x0002)
  206292. #endif
  206293. #define IOCTL_SCSI_BASE 0x00000004
  206294. #define SCSI_IOCTL_DATA_OUT 0
  206295. #define SCSI_IOCTL_DATA_IN 1
  206296. #define SCSI_IOCTL_DATA_UNSPECIFIED 2
  206297. #define CTL_CODE2( DevType, Function, Method, Access ) ( \
  206298. ((DevType) << 16) | ((Access) << 14) | ((Function) << 2) | (Method) \
  206299. )
  206300. #define IOCTL_SCSI_PASS_THROUGH CTL_CODE2( IOCTL_SCSI_BASE, 0x0401, METHOD_BUFFERED, FILE_READ_ACCESS | FILE_WRITE_ACCESS )
  206301. #define IOCTL_SCSI_GET_CAPABILITIES CTL_CODE2( IOCTL_SCSI_BASE, 0x0404, METHOD_BUFFERED, FILE_ANY_ACCESS)
  206302. #define IOCTL_SCSI_PASS_THROUGH_DIRECT CTL_CODE2( IOCTL_SCSI_BASE, 0x0405, METHOD_BUFFERED, FILE_READ_ACCESS | FILE_WRITE_ACCESS )
  206303. #define IOCTL_SCSI_GET_ADDRESS CTL_CODE2( IOCTL_SCSI_BASE, 0x0406, METHOD_BUFFERED, FILE_ANY_ACCESS )
  206304. #define SENSE_LEN 14
  206305. #define SRB_DIR_SCSI 0x00
  206306. #define SRB_POSTING 0x01
  206307. #define SRB_ENABLE_RESIDUAL_COUNT 0x04
  206308. #define SRB_DIR_IN 0x08
  206309. #define SRB_DIR_OUT 0x10
  206310. #define SRB_EVENT_NOTIFY 0x40
  206311. #define RESIDUAL_COUNT_SUPPORTED 0x02
  206312. #define MAX_SRB_TIMEOUT 1080001u
  206313. #define DEFAULT_SRB_TIMEOUT 1080001u
  206314. #define SC_HA_INQUIRY 0x00
  206315. #define SC_GET_DEV_TYPE 0x01
  206316. #define SC_EXEC_SCSI_CMD 0x02
  206317. #define SC_ABORT_SRB 0x03
  206318. #define SC_RESET_DEV 0x04
  206319. #define SC_SET_HA_PARMS 0x05
  206320. #define SC_GET_DISK_INFO 0x06
  206321. #define SC_RESCAN_SCSI_BUS 0x07
  206322. #define SC_GETSET_TIMEOUTS 0x08
  206323. #define SS_PENDING 0x00
  206324. #define SS_COMP 0x01
  206325. #define SS_ABORTED 0x02
  206326. #define SS_ABORT_FAIL 0x03
  206327. #define SS_ERR 0x04
  206328. #define SS_INVALID_CMD 0x80
  206329. #define SS_INVALID_HA 0x81
  206330. #define SS_NO_DEVICE 0x82
  206331. #define SS_INVALID_SRB 0xE0
  206332. #define SS_OLD_MANAGER 0xE1
  206333. #define SS_BUFFER_ALIGN 0xE1
  206334. #define SS_ILLEGAL_MODE 0xE2
  206335. #define SS_NO_ASPI 0xE3
  206336. #define SS_FAILED_INIT 0xE4
  206337. #define SS_ASPI_IS_BUSY 0xE5
  206338. #define SS_BUFFER_TO_BIG 0xE6
  206339. #define SS_BUFFER_TOO_BIG 0xE6
  206340. #define SS_MISMATCHED_COMPONENTS 0xE7
  206341. #define SS_NO_ADAPTERS 0xE8
  206342. #define SS_INSUFFICIENT_RESOURCES 0xE9
  206343. #define SS_ASPI_IS_SHUTDOWN 0xEA
  206344. #define SS_BAD_INSTALL 0xEB
  206345. #define HASTAT_OK 0x00
  206346. #define HASTAT_SEL_TO 0x11
  206347. #define HASTAT_DO_DU 0x12
  206348. #define HASTAT_BUS_FREE 0x13
  206349. #define HASTAT_PHASE_ERR 0x14
  206350. #define HASTAT_TIMEOUT 0x09
  206351. #define HASTAT_COMMAND_TIMEOUT 0x0B
  206352. #define HASTAT_MESSAGE_REJECT 0x0D
  206353. #define HASTAT_BUS_RESET 0x0E
  206354. #define HASTAT_PARITY_ERROR 0x0F
  206355. #define HASTAT_REQUEST_SENSE_FAILED 0x10
  206356. #define PACKED
  206357. #pragma pack(1)
  206358. typedef struct
  206359. {
  206360. BYTE SRB_Cmd;
  206361. BYTE SRB_Status;
  206362. BYTE SRB_HaID;
  206363. BYTE SRB_Flags;
  206364. DWORD SRB_Hdr_Rsvd;
  206365. BYTE HA_Count;
  206366. BYTE HA_SCSI_ID;
  206367. BYTE HA_ManagerId[16];
  206368. BYTE HA_Identifier[16];
  206369. BYTE HA_Unique[16];
  206370. WORD HA_Rsvd1;
  206371. BYTE pad[20];
  206372. } PACKED SRB_HAInquiry, *PSRB_HAInquiry, FAR *LPSRB_HAInquiry;
  206373. typedef struct
  206374. {
  206375. BYTE SRB_Cmd;
  206376. BYTE SRB_Status;
  206377. BYTE SRB_HaID;
  206378. BYTE SRB_Flags;
  206379. DWORD SRB_Hdr_Rsvd;
  206380. BYTE SRB_Target;
  206381. BYTE SRB_Lun;
  206382. BYTE SRB_DeviceType;
  206383. BYTE SRB_Rsvd1;
  206384. BYTE pad[68];
  206385. } PACKED SRB_GDEVBlock, *PSRB_GDEVBlock, FAR *LPSRB_GDEVBlock;
  206386. typedef struct
  206387. {
  206388. BYTE SRB_Cmd;
  206389. BYTE SRB_Status;
  206390. BYTE SRB_HaID;
  206391. BYTE SRB_Flags;
  206392. DWORD SRB_Hdr_Rsvd;
  206393. BYTE SRB_Target;
  206394. BYTE SRB_Lun;
  206395. WORD SRB_Rsvd1;
  206396. DWORD SRB_BufLen;
  206397. BYTE FAR *SRB_BufPointer;
  206398. BYTE SRB_SenseLen;
  206399. BYTE SRB_CDBLen;
  206400. BYTE SRB_HaStat;
  206401. BYTE SRB_TargStat;
  206402. VOID FAR *SRB_PostProc;
  206403. BYTE SRB_Rsvd2[20];
  206404. BYTE CDBByte[16];
  206405. BYTE SenseArea[SENSE_LEN+2];
  206406. } PACKED SRB_ExecSCSICmd, *PSRB_ExecSCSICmd, FAR *LPSRB_ExecSCSICmd;
  206407. typedef struct
  206408. {
  206409. BYTE SRB_Cmd;
  206410. BYTE SRB_Status;
  206411. BYTE SRB_HaId;
  206412. BYTE SRB_Flags;
  206413. DWORD SRB_Hdr_Rsvd;
  206414. } PACKED SRB, *PSRB, FAR *LPSRB;
  206415. #pragma pack()
  206416. struct CDDeviceInfo
  206417. {
  206418. char vendor[9];
  206419. char productId[17];
  206420. char rev[5];
  206421. char vendorSpec[21];
  206422. BYTE ha;
  206423. BYTE tgt;
  206424. BYTE lun;
  206425. char scsiDriveLetter; // will be 0 if not using scsi
  206426. };
  206427. class CDReadBuffer
  206428. {
  206429. public:
  206430. int startFrame;
  206431. int numFrames;
  206432. int dataStartOffset;
  206433. int dataLength;
  206434. int bufferSize;
  206435. HeapBlock<BYTE> buffer;
  206436. int index;
  206437. bool wantsIndex;
  206438. CDReadBuffer (const int numberOfFrames)
  206439. : startFrame (0),
  206440. numFrames (0),
  206441. dataStartOffset (0),
  206442. dataLength (0),
  206443. bufferSize (2352 * numberOfFrames),
  206444. buffer (bufferSize),
  206445. index (0),
  206446. wantsIndex (false)
  206447. {
  206448. }
  206449. bool isZero() const throw()
  206450. {
  206451. BYTE* p = buffer + dataStartOffset;
  206452. for (int i = dataLength; --i >= 0;)
  206453. if (*p++ != 0)
  206454. return false;
  206455. return true;
  206456. }
  206457. };
  206458. class CDDeviceHandle;
  206459. class CDController
  206460. {
  206461. public:
  206462. CDController();
  206463. virtual ~CDController();
  206464. virtual bool read (CDReadBuffer* t) = 0;
  206465. virtual void shutDown();
  206466. bool readAudio (CDReadBuffer* t, CDReadBuffer* overlapBuffer = 0);
  206467. int getLastIndex();
  206468. public:
  206469. bool initialised;
  206470. CDDeviceHandle* deviceInfo;
  206471. int framesToCheck, framesOverlap;
  206472. void prepare (SRB_ExecSCSICmd& s);
  206473. void perform (SRB_ExecSCSICmd& s);
  206474. void setPaused (bool paused);
  206475. };
  206476. #pragma pack(1)
  206477. struct TOCTRACK
  206478. {
  206479. BYTE rsvd;
  206480. BYTE ADR;
  206481. BYTE trackNumber;
  206482. BYTE rsvd2;
  206483. BYTE addr[4];
  206484. };
  206485. struct TOC
  206486. {
  206487. WORD tocLen;
  206488. BYTE firstTrack;
  206489. BYTE lastTrack;
  206490. TOCTRACK tracks[100];
  206491. };
  206492. #pragma pack()
  206493. enum
  206494. {
  206495. READTYPE_ANY = 0,
  206496. READTYPE_ATAPI1 = 1,
  206497. READTYPE_ATAPI2 = 2,
  206498. READTYPE_READ6 = 3,
  206499. READTYPE_READ10 = 4,
  206500. READTYPE_READ_D8 = 5,
  206501. READTYPE_READ_D4 = 6,
  206502. READTYPE_READ_D4_1 = 7,
  206503. READTYPE_READ10_2 = 8
  206504. };
  206505. class CDDeviceHandle
  206506. {
  206507. public:
  206508. CDDeviceHandle (const CDDeviceInfo* const device)
  206509. : scsiHandle (0),
  206510. readType (READTYPE_ANY),
  206511. controller (0)
  206512. {
  206513. memcpy (&info, device, sizeof (info));
  206514. }
  206515. ~CDDeviceHandle()
  206516. {
  206517. if (controller != 0)
  206518. {
  206519. controller->shutDown();
  206520. controller = 0;
  206521. }
  206522. if (scsiHandle != 0)
  206523. CloseHandle (scsiHandle);
  206524. }
  206525. bool readTOC (TOC* lpToc, bool useMSF);
  206526. bool readAudio (CDReadBuffer* buffer, CDReadBuffer* overlapBuffer = 0);
  206527. void openDrawer (bool shouldBeOpen);
  206528. CDDeviceInfo info;
  206529. HANDLE scsiHandle;
  206530. BYTE readType;
  206531. private:
  206532. ScopedPointer<CDController> controller;
  206533. bool testController (const int readType,
  206534. CDController* const newController,
  206535. CDReadBuffer* const bufferToUse);
  206536. };
  206537. DWORD (*fGetASPI32SupportInfo)(void);
  206538. DWORD (*fSendASPI32Command)(LPSRB);
  206539. static HINSTANCE winAspiLib = 0;
  206540. static bool usingScsi = false;
  206541. static bool initialised = false;
  206542. static bool InitialiseCDRipper()
  206543. {
  206544. if (! initialised)
  206545. {
  206546. initialised = true;
  206547. OSVERSIONINFO info;
  206548. info.dwOSVersionInfoSize = sizeof (info);
  206549. GetVersionEx (&info);
  206550. usingScsi = (info.dwPlatformId == VER_PLATFORM_WIN32_NT) && (info.dwMajorVersion > 4);
  206551. if (! usingScsi)
  206552. {
  206553. fGetASPI32SupportInfo = 0;
  206554. fSendASPI32Command = 0;
  206555. winAspiLib = LoadLibrary (_T("WNASPI32.DLL"));
  206556. if (winAspiLib != 0)
  206557. {
  206558. fGetASPI32SupportInfo = (DWORD(*)(void)) GetProcAddress (winAspiLib, "GetASPI32SupportInfo");
  206559. fSendASPI32Command = (DWORD(*)(LPSRB)) GetProcAddress (winAspiLib, "SendASPI32Command");
  206560. if (fGetASPI32SupportInfo == 0 || fSendASPI32Command == 0)
  206561. return false;
  206562. }
  206563. else
  206564. {
  206565. usingScsi = true;
  206566. }
  206567. }
  206568. }
  206569. return true;
  206570. }
  206571. static void DeinitialiseCDRipper()
  206572. {
  206573. if (winAspiLib != 0)
  206574. {
  206575. fGetASPI32SupportInfo = 0;
  206576. fSendASPI32Command = 0;
  206577. FreeLibrary (winAspiLib);
  206578. winAspiLib = 0;
  206579. }
  206580. initialised = false;
  206581. }
  206582. static HANDLE CreateSCSIDeviceHandle (char driveLetter)
  206583. {
  206584. TCHAR devicePath[] = { '\\', '\\', '.', '\\', driveLetter, ':', 0, 0 };
  206585. OSVERSIONINFO info;
  206586. info.dwOSVersionInfoSize = sizeof (info);
  206587. GetVersionEx (&info);
  206588. DWORD flags = GENERIC_READ;
  206589. if ((info.dwPlatformId == VER_PLATFORM_WIN32_NT) && (info.dwMajorVersion > 4))
  206590. flags = GENERIC_READ | GENERIC_WRITE;
  206591. HANDLE h = CreateFile (devicePath, flags, FILE_SHARE_WRITE | FILE_SHARE_READ, 0, OPEN_EXISTING, FILE_ATTRIBUTE_NORMAL, 0);
  206592. if (h == INVALID_HANDLE_VALUE)
  206593. {
  206594. flags ^= GENERIC_WRITE;
  206595. h = CreateFile (devicePath, flags, FILE_SHARE_WRITE | FILE_SHARE_READ, 0, OPEN_EXISTING, FILE_ATTRIBUTE_NORMAL, 0);
  206596. }
  206597. return h;
  206598. }
  206599. static DWORD performScsiPassThroughCommand (const LPSRB_ExecSCSICmd srb,
  206600. const char driveLetter,
  206601. HANDLE& deviceHandle,
  206602. const bool retryOnFailure = true)
  206603. {
  206604. SCSI_PASS_THROUGH_DIRECT_WITH_BUFFER s;
  206605. zerostruct (s);
  206606. s.spt.Length = sizeof (SCSI_PASS_THROUGH);
  206607. s.spt.CdbLength = srb->SRB_CDBLen;
  206608. s.spt.DataIn = (BYTE) ((srb->SRB_Flags & SRB_DIR_IN)
  206609. ? SCSI_IOCTL_DATA_IN
  206610. : ((srb->SRB_Flags & SRB_DIR_OUT)
  206611. ? SCSI_IOCTL_DATA_OUT
  206612. : SCSI_IOCTL_DATA_UNSPECIFIED));
  206613. s.spt.DataTransferLength = srb->SRB_BufLen;
  206614. s.spt.TimeOutValue = 5;
  206615. s.spt.DataBuffer = srb->SRB_BufPointer;
  206616. s.spt.SenseInfoOffset = offsetof (SCSI_PASS_THROUGH_DIRECT_WITH_BUFFER, ucSenseBuf);
  206617. memcpy (s.spt.Cdb, srb->CDBByte, srb->SRB_CDBLen);
  206618. srb->SRB_Status = SS_ERR;
  206619. srb->SRB_TargStat = 0x0004;
  206620. DWORD bytesReturned = 0;
  206621. if (DeviceIoControl (deviceHandle, IOCTL_SCSI_PASS_THROUGH_DIRECT,
  206622. &s, sizeof (s),
  206623. &s, sizeof (s),
  206624. &bytesReturned, 0) != 0)
  206625. {
  206626. srb->SRB_Status = SS_COMP;
  206627. }
  206628. else if (retryOnFailure)
  206629. {
  206630. const DWORD error = GetLastError();
  206631. if ((error == ERROR_MEDIA_CHANGED) || (error == ERROR_INVALID_HANDLE))
  206632. {
  206633. if (error != ERROR_INVALID_HANDLE)
  206634. CloseHandle (deviceHandle);
  206635. deviceHandle = CreateSCSIDeviceHandle (driveLetter);
  206636. return performScsiPassThroughCommand (srb, driveLetter, deviceHandle, false);
  206637. }
  206638. }
  206639. return srb->SRB_Status;
  206640. }
  206641. // Controller types..
  206642. class ControllerType1 : public CDController
  206643. {
  206644. public:
  206645. ControllerType1() {}
  206646. ~ControllerType1() {}
  206647. bool read (CDReadBuffer* rb)
  206648. {
  206649. if (rb->numFrames * 2352 > rb->bufferSize)
  206650. return false;
  206651. SRB_ExecSCSICmd s;
  206652. prepare (s);
  206653. s.SRB_Flags = SRB_DIR_IN | SRB_EVENT_NOTIFY;
  206654. s.SRB_BufLen = rb->bufferSize;
  206655. s.SRB_BufPointer = rb->buffer;
  206656. s.SRB_CDBLen = 12;
  206657. s.CDBByte[0] = 0xBE;
  206658. s.CDBByte[3] = (BYTE)((rb->startFrame >> 16) & 0xFF);
  206659. s.CDBByte[4] = (BYTE)((rb->startFrame >> 8) & 0xFF);
  206660. s.CDBByte[5] = (BYTE)(rb->startFrame & 0xFF);
  206661. s.CDBByte[8] = (BYTE)(rb->numFrames & 0xFF);
  206662. s.CDBByte[9] = (BYTE)((deviceInfo->readType == READTYPE_ATAPI1) ? 0x10 : 0xF0);
  206663. perform (s);
  206664. if (s.SRB_Status != SS_COMP)
  206665. return false;
  206666. rb->dataLength = rb->numFrames * 2352;
  206667. rb->dataStartOffset = 0;
  206668. return true;
  206669. }
  206670. };
  206671. class ControllerType2 : public CDController
  206672. {
  206673. public:
  206674. ControllerType2() {}
  206675. ~ControllerType2() {}
  206676. void shutDown()
  206677. {
  206678. if (initialised)
  206679. {
  206680. BYTE bufPointer[] = { 0, 0, 0, 8, 83, 0, 0, 0, 0, 0, 8, 0 };
  206681. SRB_ExecSCSICmd s;
  206682. prepare (s);
  206683. s.SRB_Flags = SRB_EVENT_NOTIFY | SRB_ENABLE_RESIDUAL_COUNT;
  206684. s.SRB_BufLen = 0x0C;
  206685. s.SRB_BufPointer = bufPointer;
  206686. s.SRB_CDBLen = 6;
  206687. s.CDBByte[0] = 0x15;
  206688. s.CDBByte[4] = 0x0C;
  206689. perform (s);
  206690. }
  206691. }
  206692. bool init()
  206693. {
  206694. SRB_ExecSCSICmd s;
  206695. s.SRB_Status = SS_ERR;
  206696. if (deviceInfo->readType == READTYPE_READ10_2)
  206697. {
  206698. BYTE bufPointer1[] = { 0, 0, 0, 8, 0, 0, 0, 0, 0, 0, 9, 48, 35, 6, 0, 0, 0, 0, 0, 128 };
  206699. BYTE bufPointer2[] = { 0, 0, 0, 8, 0, 0, 0, 0, 0, 0, 9, 48, 1, 6, 32, 7, 0, 0, 0, 0 };
  206700. for (int i = 0; i < 2; ++i)
  206701. {
  206702. prepare (s);
  206703. s.SRB_Flags = SRB_EVENT_NOTIFY;
  206704. s.SRB_BufLen = 0x14;
  206705. s.SRB_BufPointer = (i == 0) ? bufPointer1 : bufPointer2;
  206706. s.SRB_CDBLen = 6;
  206707. s.CDBByte[0] = 0x15;
  206708. s.CDBByte[1] = 0x10;
  206709. s.CDBByte[4] = 0x14;
  206710. perform (s);
  206711. if (s.SRB_Status != SS_COMP)
  206712. return false;
  206713. }
  206714. }
  206715. else
  206716. {
  206717. BYTE bufPointer[] = { 0, 0, 0, 8, 0, 0, 0, 0, 0, 0, 9, 48 };
  206718. prepare (s);
  206719. s.SRB_Flags = SRB_EVENT_NOTIFY;
  206720. s.SRB_BufLen = 0x0C;
  206721. s.SRB_BufPointer = bufPointer;
  206722. s.SRB_CDBLen = 6;
  206723. s.CDBByte[0] = 0x15;
  206724. s.CDBByte[4] = 0x0C;
  206725. perform (s);
  206726. }
  206727. return s.SRB_Status == SS_COMP;
  206728. }
  206729. bool read (CDReadBuffer* rb)
  206730. {
  206731. if (rb->numFrames * 2352 > rb->bufferSize)
  206732. return false;
  206733. if (!initialised)
  206734. {
  206735. initialised = init();
  206736. if (!initialised)
  206737. return false;
  206738. }
  206739. SRB_ExecSCSICmd s;
  206740. prepare (s);
  206741. s.SRB_Flags = SRB_DIR_IN | SRB_EVENT_NOTIFY;
  206742. s.SRB_BufLen = rb->bufferSize;
  206743. s.SRB_BufPointer = rb->buffer;
  206744. s.SRB_CDBLen = 10;
  206745. s.CDBByte[0] = 0x28;
  206746. s.CDBByte[1] = (BYTE)(deviceInfo->info.lun << 5);
  206747. s.CDBByte[3] = (BYTE)((rb->startFrame >> 16) & 0xFF);
  206748. s.CDBByte[4] = (BYTE)((rb->startFrame >> 8) & 0xFF);
  206749. s.CDBByte[5] = (BYTE)(rb->startFrame & 0xFF);
  206750. s.CDBByte[8] = (BYTE)(rb->numFrames & 0xFF);
  206751. perform (s);
  206752. if (s.SRB_Status != SS_COMP)
  206753. return false;
  206754. rb->dataLength = rb->numFrames * 2352;
  206755. rb->dataStartOffset = 0;
  206756. return true;
  206757. }
  206758. };
  206759. class ControllerType3 : public CDController
  206760. {
  206761. public:
  206762. ControllerType3() {}
  206763. ~ControllerType3() {}
  206764. bool read (CDReadBuffer* rb)
  206765. {
  206766. if (rb->numFrames * 2352 > rb->bufferSize)
  206767. return false;
  206768. if (!initialised)
  206769. {
  206770. setPaused (false);
  206771. initialised = true;
  206772. }
  206773. SRB_ExecSCSICmd s;
  206774. prepare (s);
  206775. s.SRB_Flags = SRB_DIR_IN | SRB_EVENT_NOTIFY;
  206776. s.SRB_BufLen = rb->numFrames * 2352;
  206777. s.SRB_BufPointer = rb->buffer;
  206778. s.SRB_CDBLen = 12;
  206779. s.CDBByte[0] = 0xD8;
  206780. s.CDBByte[3] = (BYTE)((rb->startFrame >> 16) & 0xFF);
  206781. s.CDBByte[4] = (BYTE)((rb->startFrame >> 8) & 0xFF);
  206782. s.CDBByte[5] = (BYTE)(rb->startFrame & 0xFF);
  206783. s.CDBByte[9] = (BYTE)(rb->numFrames & 0xFF);
  206784. perform (s);
  206785. if (s.SRB_Status != SS_COMP)
  206786. return false;
  206787. rb->dataLength = rb->numFrames * 2352;
  206788. rb->dataStartOffset = 0;
  206789. return true;
  206790. }
  206791. };
  206792. class ControllerType4 : public CDController
  206793. {
  206794. public:
  206795. ControllerType4() {}
  206796. ~ControllerType4() {}
  206797. bool selectD4Mode()
  206798. {
  206799. BYTE bufPointer[12] = { 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 9, 48 };
  206800. SRB_ExecSCSICmd s;
  206801. prepare (s);
  206802. s.SRB_Flags = SRB_EVENT_NOTIFY;
  206803. s.SRB_CDBLen = 6;
  206804. s.SRB_BufLen = 12;
  206805. s.SRB_BufPointer = bufPointer;
  206806. s.CDBByte[0] = 0x15;
  206807. s.CDBByte[1] = 0x10;
  206808. s.CDBByte[4] = 0x08;
  206809. perform (s);
  206810. return s.SRB_Status == SS_COMP;
  206811. }
  206812. bool read (CDReadBuffer* rb)
  206813. {
  206814. if (rb->numFrames * 2352 > rb->bufferSize)
  206815. return false;
  206816. if (!initialised)
  206817. {
  206818. setPaused (true);
  206819. if (deviceInfo->readType == READTYPE_READ_D4_1)
  206820. selectD4Mode();
  206821. initialised = true;
  206822. }
  206823. SRB_ExecSCSICmd s;
  206824. prepare (s);
  206825. s.SRB_Flags = SRB_DIR_IN | SRB_EVENT_NOTIFY;
  206826. s.SRB_BufLen = rb->bufferSize;
  206827. s.SRB_BufPointer = rb->buffer;
  206828. s.SRB_CDBLen = 10;
  206829. s.CDBByte[0] = 0xD4;
  206830. s.CDBByte[3] = (BYTE)((rb->startFrame >> 16) & 0xFF);
  206831. s.CDBByte[4] = (BYTE)((rb->startFrame >> 8) & 0xFF);
  206832. s.CDBByte[5] = (BYTE)(rb->startFrame & 0xFF);
  206833. s.CDBByte[8] = (BYTE)(rb->numFrames & 0xFF);
  206834. perform (s);
  206835. if (s.SRB_Status != SS_COMP)
  206836. return false;
  206837. rb->dataLength = rb->numFrames * 2352;
  206838. rb->dataStartOffset = 0;
  206839. return true;
  206840. }
  206841. };
  206842. CDController::CDController() : initialised (false)
  206843. {
  206844. }
  206845. CDController::~CDController()
  206846. {
  206847. }
  206848. void CDController::prepare (SRB_ExecSCSICmd& s)
  206849. {
  206850. zerostruct (s);
  206851. s.SRB_Cmd = SC_EXEC_SCSI_CMD;
  206852. s.SRB_HaID = deviceInfo->info.ha;
  206853. s.SRB_Target = deviceInfo->info.tgt;
  206854. s.SRB_Lun = deviceInfo->info.lun;
  206855. s.SRB_SenseLen = SENSE_LEN;
  206856. }
  206857. void CDController::perform (SRB_ExecSCSICmd& s)
  206858. {
  206859. HANDLE event = CreateEvent (0, TRUE, FALSE, 0);
  206860. s.SRB_PostProc = event;
  206861. ResetEvent (event);
  206862. DWORD status = (usingScsi) ? performScsiPassThroughCommand ((LPSRB_ExecSCSICmd)&s,
  206863. deviceInfo->info.scsiDriveLetter,
  206864. deviceInfo->scsiHandle)
  206865. : fSendASPI32Command ((LPSRB)&s);
  206866. if (status == SS_PENDING)
  206867. WaitForSingleObject (event, 4000);
  206868. CloseHandle (event);
  206869. }
  206870. void CDController::setPaused (bool paused)
  206871. {
  206872. SRB_ExecSCSICmd s;
  206873. prepare (s);
  206874. s.SRB_Flags = SRB_EVENT_NOTIFY;
  206875. s.SRB_CDBLen = 10;
  206876. s.CDBByte[0] = 0x4B;
  206877. s.CDBByte[8] = (BYTE) (paused ? 0 : 1);
  206878. perform (s);
  206879. }
  206880. void CDController::shutDown()
  206881. {
  206882. }
  206883. bool CDController::readAudio (CDReadBuffer* rb, CDReadBuffer* overlapBuffer)
  206884. {
  206885. if (overlapBuffer != 0)
  206886. {
  206887. const bool canDoJitter = (overlapBuffer->bufferSize >= 2352 * framesToCheck);
  206888. const bool doJitter = canDoJitter && ! overlapBuffer->isZero();
  206889. if (doJitter
  206890. && overlapBuffer->startFrame > 0
  206891. && overlapBuffer->numFrames > 0
  206892. && overlapBuffer->dataLength > 0)
  206893. {
  206894. const int numFrames = rb->numFrames;
  206895. if (overlapBuffer->startFrame == (rb->startFrame - framesToCheck))
  206896. {
  206897. rb->startFrame -= framesOverlap;
  206898. if (framesToCheck < framesOverlap
  206899. && numFrames + framesOverlap <= rb->bufferSize / 2352)
  206900. rb->numFrames += framesOverlap;
  206901. }
  206902. else
  206903. {
  206904. overlapBuffer->dataLength = 0;
  206905. overlapBuffer->startFrame = 0;
  206906. overlapBuffer->numFrames = 0;
  206907. }
  206908. }
  206909. if (! read (rb))
  206910. return false;
  206911. if (doJitter)
  206912. {
  206913. const int checkLen = framesToCheck * 2352;
  206914. const int maxToCheck = rb->dataLength - checkLen;
  206915. if (overlapBuffer->dataLength == 0 || overlapBuffer->isZero())
  206916. return true;
  206917. BYTE* const p = overlapBuffer->buffer + overlapBuffer->dataStartOffset;
  206918. bool found = false;
  206919. for (int i = 0; i < maxToCheck; ++i)
  206920. {
  206921. if (memcmp (p, rb->buffer + i, checkLen) == 0)
  206922. {
  206923. i += checkLen;
  206924. rb->dataStartOffset = i;
  206925. rb->dataLength -= i;
  206926. rb->startFrame = overlapBuffer->startFrame + framesToCheck;
  206927. found = true;
  206928. break;
  206929. }
  206930. }
  206931. rb->numFrames = rb->dataLength / 2352;
  206932. rb->dataLength = 2352 * rb->numFrames;
  206933. if (!found)
  206934. return false;
  206935. }
  206936. if (canDoJitter)
  206937. {
  206938. memcpy (overlapBuffer->buffer,
  206939. rb->buffer + rb->dataStartOffset + 2352 * (rb->numFrames - framesToCheck),
  206940. 2352 * framesToCheck);
  206941. overlapBuffer->startFrame = rb->startFrame + rb->numFrames - framesToCheck;
  206942. overlapBuffer->numFrames = framesToCheck;
  206943. overlapBuffer->dataLength = 2352 * framesToCheck;
  206944. overlapBuffer->dataStartOffset = 0;
  206945. }
  206946. else
  206947. {
  206948. overlapBuffer->startFrame = 0;
  206949. overlapBuffer->numFrames = 0;
  206950. overlapBuffer->dataLength = 0;
  206951. }
  206952. return true;
  206953. }
  206954. else
  206955. {
  206956. return read (rb);
  206957. }
  206958. }
  206959. int CDController::getLastIndex()
  206960. {
  206961. char qdata[100];
  206962. SRB_ExecSCSICmd s;
  206963. prepare (s);
  206964. s.SRB_Flags = SRB_DIR_IN | SRB_EVENT_NOTIFY;
  206965. s.SRB_BufLen = sizeof (qdata);
  206966. s.SRB_BufPointer = (BYTE*)qdata;
  206967. s.SRB_CDBLen = 12;
  206968. s.CDBByte[0] = 0x42;
  206969. s.CDBByte[1] = (BYTE)(deviceInfo->info.lun << 5);
  206970. s.CDBByte[2] = 64;
  206971. s.CDBByte[3] = 1; // get current position
  206972. s.CDBByte[7] = 0;
  206973. s.CDBByte[8] = (BYTE)sizeof (qdata);
  206974. perform (s);
  206975. if (s.SRB_Status == SS_COMP)
  206976. return qdata[7];
  206977. return 0;
  206978. }
  206979. bool CDDeviceHandle::readTOC (TOC* lpToc, bool useMSF)
  206980. {
  206981. HANDLE event = CreateEvent (0, TRUE, FALSE, 0);
  206982. SRB_ExecSCSICmd s;
  206983. zerostruct (s);
  206984. s.SRB_Cmd = SC_EXEC_SCSI_CMD;
  206985. s.SRB_HaID = info.ha;
  206986. s.SRB_Target = info.tgt;
  206987. s.SRB_Lun = info.lun;
  206988. s.SRB_Flags = SRB_DIR_IN | SRB_EVENT_NOTIFY;
  206989. s.SRB_BufLen = 0x324;
  206990. s.SRB_BufPointer = (BYTE*)lpToc;
  206991. s.SRB_SenseLen = 0x0E;
  206992. s.SRB_CDBLen = 0x0A;
  206993. s.SRB_PostProc = event;
  206994. s.CDBByte[0] = 0x43;
  206995. s.CDBByte[1] = (BYTE)(useMSF ? 0x02 : 0x00);
  206996. s.CDBByte[7] = 0x03;
  206997. s.CDBByte[8] = 0x24;
  206998. ResetEvent (event);
  206999. DWORD status = (usingScsi) ? performScsiPassThroughCommand ((LPSRB_ExecSCSICmd)&s, info.scsiDriveLetter, scsiHandle)
  207000. : fSendASPI32Command ((LPSRB)&s);
  207001. if (status == SS_PENDING)
  207002. WaitForSingleObject (event, 4000);
  207003. CloseHandle (event);
  207004. return (s.SRB_Status == SS_COMP);
  207005. }
  207006. bool CDDeviceHandle::readAudio (CDReadBuffer* const buffer,
  207007. CDReadBuffer* const overlapBuffer)
  207008. {
  207009. if (controller == 0)
  207010. {
  207011. testController (READTYPE_ATAPI2, new ControllerType1(), buffer)
  207012. || testController (READTYPE_ATAPI1, new ControllerType1(), buffer)
  207013. || testController (READTYPE_READ10_2, new ControllerType2(), buffer)
  207014. || testController (READTYPE_READ10, new ControllerType2(), buffer)
  207015. || testController (READTYPE_READ_D8, new ControllerType3(), buffer)
  207016. || testController (READTYPE_READ_D4, new ControllerType4(), buffer)
  207017. || testController (READTYPE_READ_D4_1, new ControllerType4(), buffer);
  207018. }
  207019. buffer->index = 0;
  207020. if ((controller != 0)
  207021. && controller->readAudio (buffer, overlapBuffer))
  207022. {
  207023. if (buffer->wantsIndex)
  207024. buffer->index = controller->getLastIndex();
  207025. return true;
  207026. }
  207027. return false;
  207028. }
  207029. void CDDeviceHandle::openDrawer (bool shouldBeOpen)
  207030. {
  207031. if (shouldBeOpen)
  207032. {
  207033. if (controller != 0)
  207034. {
  207035. controller->shutDown();
  207036. controller = 0;
  207037. }
  207038. if (scsiHandle != 0)
  207039. {
  207040. CloseHandle (scsiHandle);
  207041. scsiHandle = 0;
  207042. }
  207043. }
  207044. SRB_ExecSCSICmd s;
  207045. zerostruct (s);
  207046. s.SRB_Cmd = SC_EXEC_SCSI_CMD;
  207047. s.SRB_HaID = info.ha;
  207048. s.SRB_Target = info.tgt;
  207049. s.SRB_Lun = info.lun;
  207050. s.SRB_SenseLen = SENSE_LEN;
  207051. s.SRB_Flags = SRB_DIR_IN | SRB_EVENT_NOTIFY;
  207052. s.SRB_BufLen = 0;
  207053. s.SRB_BufPointer = 0;
  207054. s.SRB_CDBLen = 12;
  207055. s.CDBByte[0] = 0x1b;
  207056. s.CDBByte[1] = (BYTE)(info.lun << 5);
  207057. s.CDBByte[4] = (BYTE)((shouldBeOpen) ? 2 : 3);
  207058. HANDLE event = CreateEvent (0, TRUE, FALSE, 0);
  207059. s.SRB_PostProc = event;
  207060. ResetEvent (event);
  207061. DWORD status = (usingScsi) ? performScsiPassThroughCommand ((LPSRB_ExecSCSICmd)&s, info.scsiDriveLetter, scsiHandle)
  207062. : fSendASPI32Command ((LPSRB)&s);
  207063. if (status == SS_PENDING)
  207064. WaitForSingleObject (event, 4000);
  207065. CloseHandle (event);
  207066. }
  207067. bool CDDeviceHandle::testController (const int type,
  207068. CDController* const newController,
  207069. CDReadBuffer* const rb)
  207070. {
  207071. controller = newController;
  207072. readType = (BYTE)type;
  207073. controller->deviceInfo = this;
  207074. controller->framesToCheck = 1;
  207075. controller->framesOverlap = 3;
  207076. bool passed = false;
  207077. memset (rb->buffer, 0xcd, rb->bufferSize);
  207078. if (controller->read (rb))
  207079. {
  207080. passed = true;
  207081. int* p = (int*) (rb->buffer + rb->dataStartOffset);
  207082. int wrong = 0;
  207083. for (int i = rb->dataLength / 4; --i >= 0;)
  207084. {
  207085. if (*p++ == (int) 0xcdcdcdcd)
  207086. {
  207087. if (++wrong == 4)
  207088. {
  207089. passed = false;
  207090. break;
  207091. }
  207092. }
  207093. else
  207094. {
  207095. wrong = 0;
  207096. }
  207097. }
  207098. }
  207099. if (! passed)
  207100. {
  207101. controller->shutDown();
  207102. controller = 0;
  207103. }
  207104. return passed;
  207105. }
  207106. static void GetAspiDeviceInfo (CDDeviceInfo* dev, BYTE ha, BYTE tgt, BYTE lun)
  207107. {
  207108. HANDLE event = CreateEvent (0, TRUE, FALSE, 0);
  207109. const int bufSize = 128;
  207110. BYTE buffer[bufSize];
  207111. zeromem (buffer, bufSize);
  207112. SRB_ExecSCSICmd s;
  207113. zerostruct (s);
  207114. s.SRB_Cmd = SC_EXEC_SCSI_CMD;
  207115. s.SRB_HaID = ha;
  207116. s.SRB_Target = tgt;
  207117. s.SRB_Lun = lun;
  207118. s.SRB_Flags = SRB_DIR_IN | SRB_EVENT_NOTIFY;
  207119. s.SRB_BufLen = bufSize;
  207120. s.SRB_BufPointer = buffer;
  207121. s.SRB_SenseLen = SENSE_LEN;
  207122. s.SRB_CDBLen = 6;
  207123. s.SRB_PostProc = event;
  207124. s.CDBByte[0] = SCSI_INQUIRY;
  207125. s.CDBByte[4] = 100;
  207126. ResetEvent (event);
  207127. if (fSendASPI32Command ((LPSRB)&s) == SS_PENDING)
  207128. WaitForSingleObject (event, 4000);
  207129. CloseHandle (event);
  207130. if (s.SRB_Status == SS_COMP)
  207131. {
  207132. memcpy (dev->vendor, &buffer[8], 8);
  207133. memcpy (dev->productId, &buffer[16], 16);
  207134. memcpy (dev->rev, &buffer[32], 4);
  207135. memcpy (dev->vendorSpec, &buffer[36], 20);
  207136. }
  207137. }
  207138. static int FindCDDevices (CDDeviceInfo* const list,
  207139. int maxItems)
  207140. {
  207141. int count = 0;
  207142. if (usingScsi)
  207143. {
  207144. for (char driveLetter = 'b'; driveLetter <= 'z'; ++driveLetter)
  207145. {
  207146. TCHAR drivePath[8];
  207147. drivePath[0] = driveLetter;
  207148. drivePath[1] = ':';
  207149. drivePath[2] = '\\';
  207150. drivePath[3] = 0;
  207151. if (GetDriveType (drivePath) == DRIVE_CDROM)
  207152. {
  207153. HANDLE h = CreateSCSIDeviceHandle (driveLetter);
  207154. if (h != INVALID_HANDLE_VALUE)
  207155. {
  207156. BYTE buffer[100], passThroughStruct[1024];
  207157. zeromem (buffer, sizeof (buffer));
  207158. zeromem (passThroughStruct, sizeof (passThroughStruct));
  207159. PSCSI_PASS_THROUGH_DIRECT_WITH_BUFFER p = (PSCSI_PASS_THROUGH_DIRECT_WITH_BUFFER)passThroughStruct;
  207160. p->spt.Length = sizeof (SCSI_PASS_THROUGH);
  207161. p->spt.CdbLength = 6;
  207162. p->spt.SenseInfoLength = 24;
  207163. p->spt.DataIn = SCSI_IOCTL_DATA_IN;
  207164. p->spt.DataTransferLength = 100;
  207165. p->spt.TimeOutValue = 2;
  207166. p->spt.DataBuffer = buffer;
  207167. p->spt.SenseInfoOffset = offsetof (SCSI_PASS_THROUGH_DIRECT_WITH_BUFFER, ucSenseBuf);
  207168. p->spt.Cdb[0] = 0x12;
  207169. p->spt.Cdb[4] = 100;
  207170. DWORD bytesReturned = 0;
  207171. if (DeviceIoControl (h, IOCTL_SCSI_PASS_THROUGH_DIRECT,
  207172. p, sizeof (SCSI_PASS_THROUGH_DIRECT_WITH_BUFFER),
  207173. p, sizeof (SCSI_PASS_THROUGH_DIRECT_WITH_BUFFER),
  207174. &bytesReturned, 0) != 0)
  207175. {
  207176. zeromem (&list[count], sizeof (CDDeviceInfo));
  207177. list[count].scsiDriveLetter = driveLetter;
  207178. memcpy (list[count].vendor, &buffer[8], 8);
  207179. memcpy (list[count].productId, &buffer[16], 16);
  207180. memcpy (list[count].rev, &buffer[32], 4);
  207181. memcpy (list[count].vendorSpec, &buffer[36], 20);
  207182. zeromem (passThroughStruct, sizeof (passThroughStruct));
  207183. PSCSI_ADDRESS scsiAddr = (PSCSI_ADDRESS)passThroughStruct;
  207184. scsiAddr->Length = sizeof (SCSI_ADDRESS);
  207185. if (DeviceIoControl (h, IOCTL_SCSI_GET_ADDRESS,
  207186. 0, 0, scsiAddr, sizeof (SCSI_ADDRESS),
  207187. &bytesReturned, 0) != 0)
  207188. {
  207189. list[count].ha = scsiAddr->PortNumber;
  207190. list[count].tgt = scsiAddr->TargetId;
  207191. list[count].lun = scsiAddr->Lun;
  207192. ++count;
  207193. }
  207194. }
  207195. CloseHandle (h);
  207196. }
  207197. }
  207198. }
  207199. }
  207200. else
  207201. {
  207202. const DWORD d = fGetASPI32SupportInfo();
  207203. BYTE status = HIBYTE (LOWORD (d));
  207204. if (status != SS_COMP || status == SS_NO_ADAPTERS)
  207205. return 0;
  207206. const int numAdapters = LOBYTE (LOWORD (d));
  207207. for (BYTE ha = 0; ha < numAdapters; ++ha)
  207208. {
  207209. SRB_HAInquiry s;
  207210. zerostruct (s);
  207211. s.SRB_Cmd = SC_HA_INQUIRY;
  207212. s.SRB_HaID = ha;
  207213. fSendASPI32Command ((LPSRB)&s);
  207214. if (s.SRB_Status == SS_COMP)
  207215. {
  207216. maxItems = (int)s.HA_Unique[3];
  207217. if (maxItems == 0)
  207218. maxItems = 8;
  207219. for (BYTE tgt = 0; tgt < maxItems; ++tgt)
  207220. {
  207221. for (BYTE lun = 0; lun < 8; ++lun)
  207222. {
  207223. SRB_GDEVBlock sb;
  207224. zerostruct (sb);
  207225. sb.SRB_Cmd = SC_GET_DEV_TYPE;
  207226. sb.SRB_HaID = ha;
  207227. sb.SRB_Target = tgt;
  207228. sb.SRB_Lun = lun;
  207229. fSendASPI32Command ((LPSRB) &sb);
  207230. if (sb.SRB_Status == SS_COMP
  207231. && sb.SRB_DeviceType == DTYPE_CROM)
  207232. {
  207233. zeromem (&list[count], sizeof (CDDeviceInfo));
  207234. list[count].ha = ha;
  207235. list[count].tgt = tgt;
  207236. list[count].lun = lun;
  207237. GetAspiDeviceInfo (&(list[count]), ha, tgt, lun);
  207238. ++count;
  207239. }
  207240. }
  207241. }
  207242. }
  207243. }
  207244. }
  207245. return count;
  207246. }
  207247. static int ripperUsers = 0;
  207248. static bool initialisedOk = false;
  207249. class DeinitialiseTimer : private Timer,
  207250. private DeletedAtShutdown
  207251. {
  207252. DeinitialiseTimer (const DeinitialiseTimer&);
  207253. DeinitialiseTimer& operator= (const DeinitialiseTimer&);
  207254. public:
  207255. DeinitialiseTimer()
  207256. {
  207257. startTimer (4000);
  207258. }
  207259. ~DeinitialiseTimer()
  207260. {
  207261. if (--ripperUsers == 0)
  207262. DeinitialiseCDRipper();
  207263. }
  207264. void timerCallback()
  207265. {
  207266. delete this;
  207267. }
  207268. juce_UseDebuggingNewOperator
  207269. };
  207270. static void incUserCount()
  207271. {
  207272. if (ripperUsers++ == 0)
  207273. initialisedOk = InitialiseCDRipper();
  207274. }
  207275. static void decUserCount()
  207276. {
  207277. new DeinitialiseTimer();
  207278. }
  207279. struct CDDeviceWrapper
  207280. {
  207281. ScopedPointer<CDDeviceHandle> cdH;
  207282. ScopedPointer<CDReadBuffer> overlapBuffer;
  207283. bool jitter;
  207284. };
  207285. static int getAddressOf (const TOCTRACK* const t)
  207286. {
  207287. return (((DWORD)t->addr[0]) << 24) + (((DWORD)t->addr[1]) << 16) +
  207288. (((DWORD)t->addr[2]) << 8) + ((DWORD)t->addr[3]);
  207289. }
  207290. static int getMSFAddressOf (const TOCTRACK* const t)
  207291. {
  207292. return 60 * t->addr[1] + t->addr[2];
  207293. }
  207294. static const int samplesPerFrame = 44100 / 75;
  207295. static const int bytesPerFrame = samplesPerFrame * 4;
  207296. static CDDeviceHandle* openHandle (const CDDeviceInfo* const device)
  207297. {
  207298. SRB_GDEVBlock s;
  207299. zerostruct (s);
  207300. s.SRB_Cmd = SC_GET_DEV_TYPE;
  207301. s.SRB_HaID = device->ha;
  207302. s.SRB_Target = device->tgt;
  207303. s.SRB_Lun = device->lun;
  207304. if (usingScsi)
  207305. {
  207306. HANDLE h = CreateSCSIDeviceHandle (device->scsiDriveLetter);
  207307. if (h != INVALID_HANDLE_VALUE)
  207308. {
  207309. CDDeviceHandle* cdh = new CDDeviceHandle (device);
  207310. cdh->scsiHandle = h;
  207311. return cdh;
  207312. }
  207313. }
  207314. else
  207315. {
  207316. if (fSendASPI32Command ((LPSRB)&s) == SS_COMP
  207317. && s.SRB_DeviceType == DTYPE_CROM)
  207318. {
  207319. return new CDDeviceHandle (device);
  207320. }
  207321. }
  207322. return 0;
  207323. }
  207324. }
  207325. const StringArray AudioCDReader::getAvailableCDNames()
  207326. {
  207327. using namespace CDReaderHelpers;
  207328. StringArray results;
  207329. incUserCount();
  207330. if (initialisedOk)
  207331. {
  207332. CDDeviceInfo list[8];
  207333. const int num = FindCDDevices (list, 8);
  207334. decUserCount();
  207335. for (int i = 0; i < num; ++i)
  207336. {
  207337. String s;
  207338. if (list[i].scsiDriveLetter > 0)
  207339. s << String::charToString (list[i].scsiDriveLetter).toUpperCase() << ": ";
  207340. s << String (list[i].vendor).trim()
  207341. << ' ' << String (list[i].productId).trim()
  207342. << ' ' << String (list[i].rev).trim();
  207343. results.add (s);
  207344. }
  207345. }
  207346. return results;
  207347. }
  207348. AudioCDReader* AudioCDReader::createReaderForCD (const int deviceIndex)
  207349. {
  207350. using namespace CDReaderHelpers;
  207351. incUserCount();
  207352. if (initialisedOk)
  207353. {
  207354. CDDeviceInfo list[8];
  207355. const int num = FindCDDevices (list, 8);
  207356. if (((unsigned int) deviceIndex) < (unsigned int) num)
  207357. {
  207358. CDDeviceHandle* const handle = openHandle (&(list[deviceIndex]));
  207359. if (handle != 0)
  207360. {
  207361. CDDeviceWrapper* const d = new CDDeviceWrapper();
  207362. d->cdH = handle;
  207363. d->overlapBuffer = new CDReadBuffer(3);
  207364. return new AudioCDReader (d);
  207365. }
  207366. }
  207367. }
  207368. decUserCount();
  207369. return 0;
  207370. }
  207371. AudioCDReader::AudioCDReader (void* handle_)
  207372. : AudioFormatReader (0, "CD Audio"),
  207373. handle (handle_),
  207374. indexingEnabled (false),
  207375. lastIndex (0),
  207376. firstFrameInBuffer (0),
  207377. samplesInBuffer (0)
  207378. {
  207379. using namespace CDReaderHelpers;
  207380. jassert (handle_ != 0);
  207381. refreshTrackLengths();
  207382. sampleRate = 44100.0;
  207383. bitsPerSample = 16;
  207384. lengthInSamples = getPositionOfTrackStart (numTracks);
  207385. numChannels = 2;
  207386. usesFloatingPointData = false;
  207387. buffer.setSize (4 * bytesPerFrame, true);
  207388. }
  207389. AudioCDReader::~AudioCDReader()
  207390. {
  207391. using namespace CDReaderHelpers;
  207392. CDDeviceWrapper* const device = (CDDeviceWrapper*) handle;
  207393. delete device;
  207394. decUserCount();
  207395. }
  207396. bool AudioCDReader::readSamples (int** destSamples, int numDestChannels, int startOffsetInDestBuffer,
  207397. int64 startSampleInFile, int numSamples)
  207398. {
  207399. using namespace CDReaderHelpers;
  207400. CDDeviceWrapper* const device = (CDDeviceWrapper*) handle;
  207401. bool ok = true;
  207402. while (numSamples > 0)
  207403. {
  207404. const int bufferStartSample = firstFrameInBuffer * samplesPerFrame;
  207405. const int bufferEndSample = bufferStartSample + samplesInBuffer;
  207406. if (startSampleInFile >= bufferStartSample
  207407. && startSampleInFile < bufferEndSample)
  207408. {
  207409. const int toDo = (int) jmin ((int64) numSamples, bufferEndSample - startSampleInFile);
  207410. int* const l = destSamples[0] + startOffsetInDestBuffer;
  207411. int* const r = numDestChannels > 1 ? (destSamples[1] + startOffsetInDestBuffer) : 0;
  207412. const short* src = (const short*) buffer.getData();
  207413. src += 2 * (startSampleInFile - bufferStartSample);
  207414. for (int i = 0; i < toDo; ++i)
  207415. {
  207416. l[i] = src [i << 1] << 16;
  207417. if (r != 0)
  207418. r[i] = src [(i << 1) + 1] << 16;
  207419. }
  207420. startOffsetInDestBuffer += toDo;
  207421. startSampleInFile += toDo;
  207422. numSamples -= toDo;
  207423. }
  207424. else
  207425. {
  207426. const int framesInBuffer = buffer.getSize() / bytesPerFrame;
  207427. const int frameNeeded = (int) (startSampleInFile / samplesPerFrame);
  207428. if (firstFrameInBuffer + framesInBuffer != frameNeeded)
  207429. {
  207430. device->overlapBuffer->dataLength = 0;
  207431. device->overlapBuffer->startFrame = 0;
  207432. device->overlapBuffer->numFrames = 0;
  207433. device->jitter = false;
  207434. }
  207435. firstFrameInBuffer = frameNeeded;
  207436. lastIndex = 0;
  207437. CDReadBuffer readBuffer (framesInBuffer + 4);
  207438. readBuffer.wantsIndex = indexingEnabled;
  207439. int i;
  207440. for (i = 5; --i >= 0;)
  207441. {
  207442. readBuffer.startFrame = frameNeeded;
  207443. readBuffer.numFrames = framesInBuffer;
  207444. if (device->cdH->readAudio (&readBuffer, (device->jitter) ? device->overlapBuffer : 0))
  207445. break;
  207446. else
  207447. device->overlapBuffer->dataLength = 0;
  207448. }
  207449. if (i >= 0)
  207450. {
  207451. memcpy ((char*) buffer.getData(),
  207452. readBuffer.buffer + readBuffer.dataStartOffset,
  207453. readBuffer.dataLength);
  207454. samplesInBuffer = readBuffer.dataLength >> 2;
  207455. lastIndex = readBuffer.index;
  207456. }
  207457. else
  207458. {
  207459. int* l = destSamples[0] + startOffsetInDestBuffer;
  207460. int* r = numDestChannels > 1 ? (destSamples[1] + startOffsetInDestBuffer) : 0;
  207461. while (--numSamples >= 0)
  207462. {
  207463. *l++ = 0;
  207464. if (r != 0)
  207465. *r++ = 0;
  207466. }
  207467. // sometimes the read fails for just the very last couple of blocks, so
  207468. // we'll ignore and errors in the last half-second of the disk..
  207469. ok = startSampleInFile > (trackStarts [numTracks] - 20000);
  207470. break;
  207471. }
  207472. }
  207473. }
  207474. return ok;
  207475. }
  207476. bool AudioCDReader::isCDStillPresent() const
  207477. {
  207478. using namespace CDReaderHelpers;
  207479. TOC toc;
  207480. zerostruct (toc);
  207481. return ((CDDeviceWrapper*) handle)->cdH->readTOC (&toc, false);
  207482. }
  207483. int AudioCDReader::getNumTracks() const
  207484. {
  207485. return numTracks;
  207486. }
  207487. int AudioCDReader::getPositionOfTrackStart (int trackNum) const
  207488. {
  207489. using namespace CDReaderHelpers;
  207490. return (trackNum >= 0 && trackNum <= numTracks) ? trackStarts [trackNum] * samplesPerFrame
  207491. : 0;
  207492. }
  207493. void AudioCDReader::refreshTrackLengths()
  207494. {
  207495. using namespace CDReaderHelpers;
  207496. zeromem (trackStarts, sizeof (trackStarts));
  207497. zeromem (audioTracks, sizeof (audioTracks));
  207498. TOC toc;
  207499. zerostruct (toc);
  207500. if (((CDDeviceWrapper*)handle)->cdH->readTOC (&toc, false))
  207501. {
  207502. numTracks = 1 + toc.lastTrack - toc.firstTrack;
  207503. for (int i = 0; i <= numTracks; ++i)
  207504. {
  207505. trackStarts[i] = getAddressOf (&toc.tracks[i]);
  207506. audioTracks[i] = ((toc.tracks[i].ADR & 4) == 0);
  207507. }
  207508. }
  207509. else
  207510. {
  207511. numTracks = 0;
  207512. }
  207513. }
  207514. bool AudioCDReader::isTrackAudio (int trackNum) const
  207515. {
  207516. return (trackNum >= 0 && trackNum <= numTracks) ? audioTracks [trackNum]
  207517. : false;
  207518. }
  207519. void AudioCDReader::enableIndexScanning (bool b)
  207520. {
  207521. indexingEnabled = b;
  207522. }
  207523. int AudioCDReader::getLastIndex() const
  207524. {
  207525. return lastIndex;
  207526. }
  207527. const int framesPerIndexRead = 4;
  207528. int AudioCDReader::getIndexAt (int samplePos)
  207529. {
  207530. using namespace CDReaderHelpers;
  207531. CDDeviceWrapper* const device = (CDDeviceWrapper*) handle;
  207532. const int frameNeeded = samplePos / samplesPerFrame;
  207533. device->overlapBuffer->dataLength = 0;
  207534. device->overlapBuffer->startFrame = 0;
  207535. device->overlapBuffer->numFrames = 0;
  207536. device->jitter = false;
  207537. firstFrameInBuffer = 0;
  207538. lastIndex = 0;
  207539. CDReadBuffer readBuffer (4 + framesPerIndexRead);
  207540. readBuffer.wantsIndex = true;
  207541. int i;
  207542. for (i = 5; --i >= 0;)
  207543. {
  207544. readBuffer.startFrame = frameNeeded;
  207545. readBuffer.numFrames = framesPerIndexRead;
  207546. if (device->cdH->readAudio (&readBuffer, (false) ? device->overlapBuffer : 0))
  207547. break;
  207548. }
  207549. if (i >= 0)
  207550. return readBuffer.index;
  207551. return -1;
  207552. }
  207553. const Array <int> AudioCDReader::findIndexesInTrack (const int trackNumber)
  207554. {
  207555. using namespace CDReaderHelpers;
  207556. Array <int> indexes;
  207557. const int trackStart = getPositionOfTrackStart (trackNumber);
  207558. const int trackEnd = getPositionOfTrackStart (trackNumber + 1);
  207559. bool needToScan = true;
  207560. if (trackEnd - trackStart > 20 * 44100)
  207561. {
  207562. // check the end of the track for indexes before scanning the whole thing
  207563. needToScan = false;
  207564. int pos = jmax (trackStart, trackEnd - 44100 * 5);
  207565. bool seenAnIndex = false;
  207566. while (pos <= trackEnd - samplesPerFrame)
  207567. {
  207568. const int index = getIndexAt (pos);
  207569. if (index == 0)
  207570. {
  207571. // lead-out, so skip back a bit if we've not found any indexes yet..
  207572. if (seenAnIndex)
  207573. break;
  207574. pos -= 44100 * 5;
  207575. if (pos < trackStart)
  207576. break;
  207577. }
  207578. else
  207579. {
  207580. if (index > 0)
  207581. seenAnIndex = true;
  207582. if (index > 1)
  207583. {
  207584. needToScan = true;
  207585. break;
  207586. }
  207587. pos += samplesPerFrame * framesPerIndexRead;
  207588. }
  207589. }
  207590. }
  207591. if (needToScan)
  207592. {
  207593. CDDeviceWrapper* const device = (CDDeviceWrapper*) handle;
  207594. int pos = trackStart;
  207595. int last = -1;
  207596. while (pos < trackEnd - samplesPerFrame * 10)
  207597. {
  207598. const int frameNeeded = pos / samplesPerFrame;
  207599. device->overlapBuffer->dataLength = 0;
  207600. device->overlapBuffer->startFrame = 0;
  207601. device->overlapBuffer->numFrames = 0;
  207602. device->jitter = false;
  207603. firstFrameInBuffer = 0;
  207604. CDReadBuffer readBuffer (4);
  207605. readBuffer.wantsIndex = true;
  207606. int i;
  207607. for (i = 5; --i >= 0;)
  207608. {
  207609. readBuffer.startFrame = frameNeeded;
  207610. readBuffer.numFrames = framesPerIndexRead;
  207611. if (device->cdH->readAudio (&readBuffer, (false) ? device->overlapBuffer : 0))
  207612. break;
  207613. }
  207614. if (i < 0)
  207615. break;
  207616. if (readBuffer.index > last && readBuffer.index > 1)
  207617. {
  207618. last = readBuffer.index;
  207619. indexes.add (pos);
  207620. }
  207621. pos += samplesPerFrame * framesPerIndexRead;
  207622. }
  207623. indexes.removeValue (trackStart);
  207624. }
  207625. return indexes;
  207626. }
  207627. int AudioCDReader::getCDDBId()
  207628. {
  207629. using namespace CDReaderHelpers;
  207630. refreshTrackLengths();
  207631. if (numTracks > 0)
  207632. {
  207633. TOC toc;
  207634. zerostruct (toc);
  207635. if (((CDDeviceWrapper*) handle)->cdH->readTOC (&toc, true))
  207636. {
  207637. int n = 0;
  207638. for (int i = numTracks; --i >= 0;)
  207639. {
  207640. int j = getMSFAddressOf (&toc.tracks[i]);
  207641. while (j > 0)
  207642. {
  207643. n += (j % 10);
  207644. j /= 10;
  207645. }
  207646. }
  207647. if (n != 0)
  207648. {
  207649. const int t = getMSFAddressOf (&toc.tracks[numTracks])
  207650. - getMSFAddressOf (&toc.tracks[0]);
  207651. return ((n % 0xff) << 24) | (t << 8) | numTracks;
  207652. }
  207653. }
  207654. }
  207655. return 0;
  207656. }
  207657. void AudioCDReader::ejectDisk()
  207658. {
  207659. using namespace CDReaderHelpers;
  207660. ((CDDeviceWrapper*) handle)->cdH->openDrawer (true);
  207661. }
  207662. #endif
  207663. #if JUCE_USE_CDBURNER
  207664. static IDiscRecorder* enumCDBurners (StringArray* list, int indexToOpen, IDiscMaster** master)
  207665. {
  207666. CoInitialize (0);
  207667. IDiscMaster* dm;
  207668. IDiscRecorder* result = 0;
  207669. if (SUCCEEDED (CoCreateInstance (CLSID_MSDiscMasterObj, 0,
  207670. CLSCTX_INPROC_SERVER | CLSCTX_LOCAL_SERVER,
  207671. IID_IDiscMaster,
  207672. (void**) &dm)))
  207673. {
  207674. if (SUCCEEDED (dm->Open()))
  207675. {
  207676. IEnumDiscRecorders* drEnum = 0;
  207677. if (SUCCEEDED (dm->EnumDiscRecorders (&drEnum)))
  207678. {
  207679. IDiscRecorder* dr = 0;
  207680. DWORD dummy;
  207681. int index = 0;
  207682. while (drEnum->Next (1, &dr, &dummy) == S_OK)
  207683. {
  207684. if (indexToOpen == index)
  207685. {
  207686. result = dr;
  207687. break;
  207688. }
  207689. else if (list != 0)
  207690. {
  207691. BSTR path;
  207692. if (SUCCEEDED (dr->GetPath (&path)))
  207693. list->add ((const WCHAR*) path);
  207694. }
  207695. ++index;
  207696. dr->Release();
  207697. }
  207698. drEnum->Release();
  207699. }
  207700. if (master == 0)
  207701. dm->Close();
  207702. }
  207703. if (master != 0)
  207704. *master = dm;
  207705. else
  207706. dm->Release();
  207707. }
  207708. return result;
  207709. }
  207710. class AudioCDBurner::Pimpl : public ComBaseClassHelper <IDiscMasterProgressEvents>,
  207711. public Timer
  207712. {
  207713. public:
  207714. Pimpl (AudioCDBurner& owner_, IDiscMaster* discMaster_, IDiscRecorder* discRecorder_)
  207715. : owner (owner_), discMaster (discMaster_), discRecorder (discRecorder_), redbook (0),
  207716. listener (0), progress (0), shouldCancel (false)
  207717. {
  207718. HRESULT hr = discMaster->SetActiveDiscMasterFormat (IID_IRedbookDiscMaster, (void**) &redbook);
  207719. jassert (SUCCEEDED (hr));
  207720. hr = discMaster->SetActiveDiscRecorder (discRecorder);
  207721. //jassert (SUCCEEDED (hr));
  207722. lastState = getDiskState();
  207723. startTimer (2000);
  207724. }
  207725. ~Pimpl() {}
  207726. void releaseObjects()
  207727. {
  207728. discRecorder->Close();
  207729. if (redbook != 0)
  207730. redbook->Release();
  207731. discRecorder->Release();
  207732. discMaster->Release();
  207733. Release();
  207734. }
  207735. HRESULT __stdcall QueryCancel (boolean* pbCancel)
  207736. {
  207737. if (listener != 0 && ! shouldCancel)
  207738. shouldCancel = listener->audioCDBurnProgress (progress);
  207739. *pbCancel = shouldCancel;
  207740. return S_OK;
  207741. }
  207742. HRESULT __stdcall NotifyBlockProgress (long nCompleted, long nTotal)
  207743. {
  207744. progress = nCompleted / (float) nTotal;
  207745. shouldCancel = listener != 0 && listener->audioCDBurnProgress (progress);
  207746. return E_NOTIMPL;
  207747. }
  207748. HRESULT __stdcall NotifyPnPActivity (void) { return E_NOTIMPL; }
  207749. HRESULT __stdcall NotifyAddProgress (long /*nCompletedSteps*/, long /*nTotalSteps*/) { return E_NOTIMPL; }
  207750. HRESULT __stdcall NotifyTrackProgress (long /*nCurrentTrack*/, long /*nTotalTracks*/) { return E_NOTIMPL; }
  207751. HRESULT __stdcall NotifyPreparingBurn (long /*nEstimatedSeconds*/) { return E_NOTIMPL; }
  207752. HRESULT __stdcall NotifyClosingDisc (long /*nEstimatedSeconds*/) { return E_NOTIMPL; }
  207753. HRESULT __stdcall NotifyBurnComplete (HRESULT /*status*/) { return E_NOTIMPL; }
  207754. HRESULT __stdcall NotifyEraseComplete (HRESULT /*status*/) { return E_NOTIMPL; }
  207755. class ScopedDiscOpener
  207756. {
  207757. public:
  207758. ScopedDiscOpener (Pimpl& p) : pimpl (p) { pimpl.discRecorder->OpenExclusive(); }
  207759. ~ScopedDiscOpener() { pimpl.discRecorder->Close(); }
  207760. private:
  207761. Pimpl& pimpl;
  207762. ScopedDiscOpener (const ScopedDiscOpener&);
  207763. ScopedDiscOpener& operator= (const ScopedDiscOpener&);
  207764. };
  207765. DiskState getDiskState()
  207766. {
  207767. const ScopedDiscOpener opener (*this);
  207768. long type, flags;
  207769. HRESULT hr = discRecorder->QueryMediaType (&type, &flags);
  207770. if (FAILED (hr))
  207771. return unknown;
  207772. if (type != 0 && (flags & MEDIA_WRITABLE) != 0)
  207773. return writableDiskPresent;
  207774. if (type == 0)
  207775. return noDisc;
  207776. else
  207777. return readOnlyDiskPresent;
  207778. }
  207779. int getIntProperty (const LPOLESTR name, const int defaultReturn) const
  207780. {
  207781. ComSmartPtr<IPropertyStorage> prop;
  207782. if (FAILED (discRecorder->GetRecorderProperties (&prop)))
  207783. return defaultReturn;
  207784. PROPSPEC iPropSpec;
  207785. iPropSpec.ulKind = PRSPEC_LPWSTR;
  207786. iPropSpec.lpwstr = name;
  207787. PROPVARIANT iPropVariant;
  207788. return FAILED (prop->ReadMultiple (1, &iPropSpec, &iPropVariant))
  207789. ? defaultReturn : (int) iPropVariant.lVal;
  207790. }
  207791. bool setIntProperty (const LPOLESTR name, const int value) const
  207792. {
  207793. ComSmartPtr<IPropertyStorage> prop;
  207794. if (FAILED (discRecorder->GetRecorderProperties (&prop)))
  207795. return false;
  207796. PROPSPEC iPropSpec;
  207797. iPropSpec.ulKind = PRSPEC_LPWSTR;
  207798. iPropSpec.lpwstr = name;
  207799. PROPVARIANT iPropVariant;
  207800. if (FAILED (prop->ReadMultiple (1, &iPropSpec, &iPropVariant)))
  207801. return false;
  207802. iPropVariant.lVal = (long) value;
  207803. return SUCCEEDED (prop->WriteMultiple (1, &iPropSpec, &iPropVariant, iPropVariant.vt))
  207804. && SUCCEEDED (discRecorder->SetRecorderProperties (prop));
  207805. }
  207806. void timerCallback()
  207807. {
  207808. const DiskState state = getDiskState();
  207809. if (state != lastState)
  207810. {
  207811. lastState = state;
  207812. owner.sendChangeMessage (&owner);
  207813. }
  207814. }
  207815. AudioCDBurner& owner;
  207816. DiskState lastState;
  207817. IDiscMaster* discMaster;
  207818. IDiscRecorder* discRecorder;
  207819. IRedbookDiscMaster* redbook;
  207820. AudioCDBurner::BurnProgressListener* listener;
  207821. float progress;
  207822. bool shouldCancel;
  207823. };
  207824. AudioCDBurner::AudioCDBurner (const int deviceIndex)
  207825. {
  207826. IDiscMaster* discMaster = 0;
  207827. IDiscRecorder* discRecorder = enumCDBurners (0, deviceIndex, &discMaster);
  207828. if (discRecorder != 0)
  207829. pimpl = new Pimpl (*this, discMaster, discRecorder);
  207830. }
  207831. AudioCDBurner::~AudioCDBurner()
  207832. {
  207833. if (pimpl != 0)
  207834. pimpl.release()->releaseObjects();
  207835. }
  207836. const StringArray AudioCDBurner::findAvailableDevices()
  207837. {
  207838. StringArray devs;
  207839. enumCDBurners (&devs, -1, 0);
  207840. return devs;
  207841. }
  207842. AudioCDBurner* AudioCDBurner::openDevice (const int deviceIndex)
  207843. {
  207844. ScopedPointer<AudioCDBurner> b (new AudioCDBurner (deviceIndex));
  207845. if (b->pimpl == 0)
  207846. b = 0;
  207847. return b.release();
  207848. }
  207849. AudioCDBurner::DiskState AudioCDBurner::getDiskState() const
  207850. {
  207851. return pimpl->getDiskState();
  207852. }
  207853. bool AudioCDBurner::isDiskPresent() const
  207854. {
  207855. return getDiskState() == writableDiskPresent;
  207856. }
  207857. bool AudioCDBurner::openTray()
  207858. {
  207859. const Pimpl::ScopedDiscOpener opener (*pimpl);
  207860. return SUCCEEDED (pimpl->discRecorder->Eject());
  207861. }
  207862. AudioCDBurner::DiskState AudioCDBurner::waitUntilStateChange (int timeOutMilliseconds)
  207863. {
  207864. const int64 timeout = Time::currentTimeMillis() + timeOutMilliseconds;
  207865. DiskState oldState = getDiskState();
  207866. DiskState newState = oldState;
  207867. while (newState == oldState && Time::currentTimeMillis() < timeout)
  207868. {
  207869. newState = getDiskState();
  207870. Thread::sleep (jmin (250, (int) (timeout - Time::currentTimeMillis())));
  207871. }
  207872. return newState;
  207873. }
  207874. const Array<int> AudioCDBurner::getAvailableWriteSpeeds() const
  207875. {
  207876. Array<int> results;
  207877. const int maxSpeed = pimpl->getIntProperty (L"MaxWriteSpeed", 1);
  207878. const int speeds[] = { 1, 2, 4, 8, 12, 16, 20, 24, 32, 40, 64, 80 };
  207879. for (int i = 0; i < numElementsInArray (speeds); ++i)
  207880. if (speeds[i] <= maxSpeed)
  207881. results.add (speeds[i]);
  207882. results.addIfNotAlreadyThere (maxSpeed);
  207883. return results;
  207884. }
  207885. bool AudioCDBurner::setBufferUnderrunProtection (const bool shouldBeEnabled)
  207886. {
  207887. if (pimpl->getIntProperty (L"BufferUnderrunFreeCapable", 0) == 0)
  207888. return false;
  207889. pimpl->setIntProperty (L"EnableBufferUnderrunFree", shouldBeEnabled ? -1 : 0);
  207890. return pimpl->getIntProperty (L"EnableBufferUnderrunFree", 0) != 0;
  207891. }
  207892. int AudioCDBurner::getNumAvailableAudioBlocks() const
  207893. {
  207894. long blocksFree = 0;
  207895. pimpl->redbook->GetAvailableAudioTrackBlocks (&blocksFree);
  207896. return blocksFree;
  207897. }
  207898. const String AudioCDBurner::burn (AudioCDBurner::BurnProgressListener* listener, bool ejectDiscAfterwards,
  207899. bool performFakeBurnForTesting, int writeSpeed)
  207900. {
  207901. pimpl->setIntProperty (L"WriteSpeed", writeSpeed > 0 ? writeSpeed : -1);
  207902. pimpl->listener = listener;
  207903. pimpl->progress = 0;
  207904. pimpl->shouldCancel = false;
  207905. UINT_PTR cookie;
  207906. HRESULT hr = pimpl->discMaster->ProgressAdvise ((AudioCDBurner::Pimpl*) pimpl, &cookie);
  207907. hr = pimpl->discMaster->RecordDisc (performFakeBurnForTesting,
  207908. ejectDiscAfterwards);
  207909. String error;
  207910. if (hr != S_OK)
  207911. {
  207912. const char* e = "Couldn't open or write to the CD device";
  207913. if (hr == IMAPI_E_USERABORT)
  207914. e = "User cancelled the write operation";
  207915. else if (hr == IMAPI_E_MEDIUM_NOTPRESENT || hr == IMAPI_E_TRACKOPEN)
  207916. e = "No Disk present";
  207917. error = e;
  207918. }
  207919. pimpl->discMaster->ProgressUnadvise (cookie);
  207920. pimpl->listener = 0;
  207921. return error;
  207922. }
  207923. bool AudioCDBurner::addAudioTrack (AudioSource* audioSource, int numSamples)
  207924. {
  207925. if (audioSource == 0)
  207926. return false;
  207927. ScopedPointer<AudioSource> source (audioSource);
  207928. long bytesPerBlock;
  207929. HRESULT hr = pimpl->redbook->GetAudioBlockSize (&bytesPerBlock);
  207930. const int samplesPerBlock = bytesPerBlock / 4;
  207931. bool ok = true;
  207932. hr = pimpl->redbook->CreateAudioTrack ((long) numSamples / (bytesPerBlock * 4));
  207933. HeapBlock <byte> buffer (bytesPerBlock);
  207934. AudioSampleBuffer sourceBuffer (2, samplesPerBlock);
  207935. int samplesDone = 0;
  207936. source->prepareToPlay (samplesPerBlock, 44100.0);
  207937. while (ok)
  207938. {
  207939. {
  207940. AudioSourceChannelInfo info;
  207941. info.buffer = &sourceBuffer;
  207942. info.numSamples = samplesPerBlock;
  207943. info.startSample = 0;
  207944. sourceBuffer.clear();
  207945. source->getNextAudioBlock (info);
  207946. }
  207947. zeromem (buffer, bytesPerBlock);
  207948. AudioDataConverters::convertFloatToInt16LE (sourceBuffer.getSampleData (0, 0),
  207949. buffer, samplesPerBlock, 4);
  207950. AudioDataConverters::convertFloatToInt16LE (sourceBuffer.getSampleData (1, 0),
  207951. buffer + 2, samplesPerBlock, 4);
  207952. hr = pimpl->redbook->AddAudioTrackBlocks (buffer, bytesPerBlock);
  207953. if (FAILED (hr))
  207954. ok = false;
  207955. samplesDone += samplesPerBlock;
  207956. if (samplesDone >= numSamples)
  207957. break;
  207958. }
  207959. hr = pimpl->redbook->CloseAudioTrack();
  207960. return ok && hr == S_OK;
  207961. }
  207962. #endif
  207963. #endif
  207964. /*** End of inlined file: juce_win32_AudioCDReader.cpp ***/
  207965. /*** Start of inlined file: juce_win32_Midi.cpp ***/
  207966. // (This file gets included by juce_win32_NativeCode.cpp, rather than being
  207967. // compiled on its own).
  207968. #if JUCE_INCLUDED_FILE
  207969. using ::free;
  207970. namespace MidiConstants
  207971. {
  207972. static const int midiBufferSize = 1024 * 10;
  207973. static const int numInHeaders = 32;
  207974. static const int inBufferSize = 256;
  207975. }
  207976. class MidiInThread : public Thread
  207977. {
  207978. public:
  207979. MidiInThread (MidiInput* const input_,
  207980. MidiInputCallback* const callback_)
  207981. : Thread ("Juce Midi"),
  207982. hIn (0),
  207983. input (input_),
  207984. callback (callback_),
  207985. isStarted (false),
  207986. startTime (0),
  207987. pendingLength(0)
  207988. {
  207989. for (int i = MidiConstants::numInHeaders; --i >= 0;)
  207990. {
  207991. zeromem (&hdr[i], sizeof (MIDIHDR));
  207992. hdr[i].lpData = inData[i];
  207993. hdr[i].dwBufferLength = MidiConstants::inBufferSize;
  207994. }
  207995. };
  207996. ~MidiInThread()
  207997. {
  207998. stop();
  207999. if (hIn != 0)
  208000. {
  208001. int count = 5;
  208002. while (--count >= 0)
  208003. {
  208004. if (midiInClose (hIn) == MMSYSERR_NOERROR)
  208005. break;
  208006. Sleep (20);
  208007. }
  208008. }
  208009. }
  208010. void handle (const uint32 message, const uint32 timeStamp)
  208011. {
  208012. const int byte = message & 0xff;
  208013. if (byte < 0x80)
  208014. return;
  208015. const int numBytes = MidiMessage::getMessageLengthFromFirstByte ((uint8) byte);
  208016. const double time = timeStampToTime (timeStamp);
  208017. {
  208018. const ScopedLock sl (lock);
  208019. if (pendingLength < MidiConstants::midiBufferSize - 12)
  208020. {
  208021. char* const p = pending + pendingLength;
  208022. *(double*) p = time;
  208023. *(uint32*) (p + 8) = numBytes;
  208024. *(uint32*) (p + 12) = message;
  208025. pendingLength += 12 + numBytes;
  208026. }
  208027. else
  208028. {
  208029. jassertfalse // midi buffer overflow! You might need to increase the size..
  208030. }
  208031. }
  208032. notify();
  208033. }
  208034. void handleSysEx (MIDIHDR* const hdr, const uint32 timeStamp)
  208035. {
  208036. const int num = hdr->dwBytesRecorded;
  208037. if (num > 0)
  208038. {
  208039. const double time = timeStampToTime (timeStamp);
  208040. {
  208041. const ScopedLock sl (lock);
  208042. if (pendingLength < MidiConstants::midiBufferSize - (8 + num))
  208043. {
  208044. char* const p = pending + pendingLength;
  208045. *(double*) p = time;
  208046. *(uint32*) (p + 8) = num;
  208047. memcpy (p + 12, hdr->lpData, num);
  208048. pendingLength += 12 + num;
  208049. }
  208050. else
  208051. {
  208052. jassertfalse // midi buffer overflow! You might need to increase the size..
  208053. }
  208054. }
  208055. notify();
  208056. }
  208057. }
  208058. void writeBlock (const int i)
  208059. {
  208060. hdr[i].dwBytesRecorded = 0;
  208061. MMRESULT res = midiInPrepareHeader (hIn, &hdr[i], sizeof (MIDIHDR));
  208062. jassert (res == MMSYSERR_NOERROR);
  208063. res = midiInAddBuffer (hIn, &hdr[i], sizeof (MIDIHDR));
  208064. jassert (res == MMSYSERR_NOERROR);
  208065. }
  208066. void run()
  208067. {
  208068. MemoryBlock pendingCopy (64);
  208069. while (! threadShouldExit())
  208070. {
  208071. for (int i = 0; i < MidiConstants::numInHeaders; ++i)
  208072. {
  208073. if ((hdr[i].dwFlags & WHDR_DONE) != 0)
  208074. {
  208075. MMRESULT res = midiInUnprepareHeader (hIn, &hdr[i], sizeof (MIDIHDR));
  208076. (void) res;
  208077. jassert (res == MMSYSERR_NOERROR);
  208078. writeBlock (i);
  208079. }
  208080. }
  208081. int len;
  208082. {
  208083. const ScopedLock sl (lock);
  208084. len = pendingLength;
  208085. if (len > 0)
  208086. {
  208087. pendingCopy.ensureSize (len);
  208088. pendingCopy.copyFrom (pending, 0, len);
  208089. pendingLength = 0;
  208090. }
  208091. }
  208092. //xxx needs to figure out if blocks are broken up or not
  208093. if (len == 0)
  208094. {
  208095. wait (500);
  208096. }
  208097. else
  208098. {
  208099. const char* p = (const char*) pendingCopy.getData();
  208100. while (len > 0)
  208101. {
  208102. const double time = *(const double*) p;
  208103. const int messageLen = *(const int*) (p + 8);
  208104. const MidiMessage message ((const uint8*) (p + 12), messageLen, time);
  208105. callback->handleIncomingMidiMessage (input, message);
  208106. p += 12 + messageLen;
  208107. len -= 12 + messageLen;
  208108. }
  208109. }
  208110. }
  208111. }
  208112. void start()
  208113. {
  208114. jassert (hIn != 0);
  208115. if (hIn != 0 && ! isStarted)
  208116. {
  208117. stop();
  208118. activeMidiThreads.addIfNotAlreadyThere (this);
  208119. int i;
  208120. for (i = 0; i < MidiConstants::numInHeaders; ++i)
  208121. writeBlock (i);
  208122. startTime = Time::getMillisecondCounter();
  208123. MMRESULT res = midiInStart (hIn);
  208124. jassert (res == MMSYSERR_NOERROR);
  208125. if (res == MMSYSERR_NOERROR)
  208126. {
  208127. isStarted = true;
  208128. pendingLength = 0;
  208129. startThread (6);
  208130. }
  208131. }
  208132. }
  208133. void stop()
  208134. {
  208135. if (isStarted)
  208136. {
  208137. stopThread (5000);
  208138. midiInReset (hIn);
  208139. midiInStop (hIn);
  208140. activeMidiThreads.removeValue (this);
  208141. { const ScopedLock sl (lock); }
  208142. for (int i = MidiConstants::numInHeaders; --i >= 0;)
  208143. {
  208144. if ((hdr[i].dwFlags & WHDR_DONE) != 0)
  208145. {
  208146. int c = 10;
  208147. while (--c >= 0 && midiInUnprepareHeader (hIn, &hdr[i], sizeof (MIDIHDR)) == MIDIERR_STILLPLAYING)
  208148. Sleep (20);
  208149. jassert (c >= 0);
  208150. }
  208151. }
  208152. isStarted = false;
  208153. pendingLength = 0;
  208154. }
  208155. }
  208156. static void CALLBACK midiInCallback (HMIDIIN, UINT uMsg, DWORD_PTR dwInstance, DWORD_PTR midiMessage, DWORD_PTR timeStamp)
  208157. {
  208158. MidiInThread* const thread = reinterpret_cast <MidiInThread*> (dwInstance);
  208159. if (thread != 0 && activeMidiThreads.contains (thread))
  208160. {
  208161. if (uMsg == MIM_DATA)
  208162. thread->handle ((uint32) midiMessage, (uint32) timeStamp);
  208163. else if (uMsg == MIM_LONGDATA)
  208164. thread->handleSysEx ((MIDIHDR*) midiMessage, (uint32) timeStamp);
  208165. }
  208166. }
  208167. juce_UseDebuggingNewOperator
  208168. HMIDIIN hIn;
  208169. private:
  208170. static Array <void*, CriticalSection> activeMidiThreads;
  208171. MidiInput* input;
  208172. MidiInputCallback* callback;
  208173. bool isStarted;
  208174. uint32 startTime;
  208175. CriticalSection lock;
  208176. MIDIHDR hdr [MidiConstants::numInHeaders];
  208177. char inData [MidiConstants::numInHeaders] [MidiConstants::inBufferSize];
  208178. int pendingLength;
  208179. char pending [MidiConstants::midiBufferSize];
  208180. double timeStampToTime (uint32 timeStamp)
  208181. {
  208182. timeStamp += startTime;
  208183. const uint32 now = Time::getMillisecondCounter();
  208184. if (timeStamp > now)
  208185. {
  208186. if (timeStamp > now + 2)
  208187. --startTime;
  208188. timeStamp = now;
  208189. }
  208190. return 0.001 * timeStamp;
  208191. }
  208192. MidiInThread (const MidiInThread&);
  208193. MidiInThread& operator= (const MidiInThread&);
  208194. };
  208195. Array <void*, CriticalSection> MidiInThread::activeMidiThreads;
  208196. const StringArray MidiInput::getDevices()
  208197. {
  208198. StringArray s;
  208199. const int num = midiInGetNumDevs();
  208200. for (int i = 0; i < num; ++i)
  208201. {
  208202. MIDIINCAPS mc;
  208203. zerostruct (mc);
  208204. if (midiInGetDevCaps (i, &mc, sizeof (mc)) == MMSYSERR_NOERROR)
  208205. s.add (String (mc.szPname, sizeof (mc.szPname)));
  208206. }
  208207. return s;
  208208. }
  208209. int MidiInput::getDefaultDeviceIndex()
  208210. {
  208211. return 0;
  208212. }
  208213. MidiInput* MidiInput::openDevice (const int index, MidiInputCallback* const callback)
  208214. {
  208215. if (callback == 0)
  208216. return 0;
  208217. UINT deviceId = MIDI_MAPPER;
  208218. int n = 0;
  208219. String name;
  208220. const int num = midiInGetNumDevs();
  208221. for (int i = 0; i < num; ++i)
  208222. {
  208223. MIDIINCAPS mc;
  208224. zerostruct (mc);
  208225. if (midiInGetDevCaps (i, &mc, sizeof (mc)) == MMSYSERR_NOERROR)
  208226. {
  208227. if (index == n)
  208228. {
  208229. deviceId = i;
  208230. name = String (mc.szPname, sizeof (mc.szPname));
  208231. break;
  208232. }
  208233. ++n;
  208234. }
  208235. }
  208236. ScopedPointer <MidiInput> in (new MidiInput (name));
  208237. ScopedPointer <MidiInThread> thread (new MidiInThread (in, callback));
  208238. HMIDIIN h;
  208239. HRESULT err = midiInOpen (&h, deviceId,
  208240. (DWORD_PTR) &MidiInThread::midiInCallback,
  208241. (DWORD_PTR) (MidiInThread*) thread,
  208242. CALLBACK_FUNCTION);
  208243. if (err == MMSYSERR_NOERROR)
  208244. {
  208245. thread->hIn = h;
  208246. in->internal = thread.release();
  208247. return in.release();
  208248. }
  208249. return 0;
  208250. }
  208251. MidiInput::MidiInput (const String& name_)
  208252. : name (name_),
  208253. internal (0)
  208254. {
  208255. }
  208256. MidiInput::~MidiInput()
  208257. {
  208258. delete static_cast <MidiInThread*> (internal);
  208259. }
  208260. void MidiInput::start()
  208261. {
  208262. static_cast <MidiInThread*> (internal)->start();
  208263. }
  208264. void MidiInput::stop()
  208265. {
  208266. static_cast <MidiInThread*> (internal)->stop();
  208267. }
  208268. struct MidiOutHandle
  208269. {
  208270. int refCount;
  208271. UINT deviceId;
  208272. HMIDIOUT handle;
  208273. static Array<MidiOutHandle*> activeHandles;
  208274. juce_UseDebuggingNewOperator
  208275. };
  208276. Array<MidiOutHandle*> MidiOutHandle::activeHandles;
  208277. const StringArray MidiOutput::getDevices()
  208278. {
  208279. StringArray s;
  208280. const int num = midiOutGetNumDevs();
  208281. for (int i = 0; i < num; ++i)
  208282. {
  208283. MIDIOUTCAPS mc;
  208284. zerostruct (mc);
  208285. if (midiOutGetDevCaps (i, &mc, sizeof (mc)) == MMSYSERR_NOERROR)
  208286. s.add (String (mc.szPname, sizeof (mc.szPname)));
  208287. }
  208288. return s;
  208289. }
  208290. int MidiOutput::getDefaultDeviceIndex()
  208291. {
  208292. const int num = midiOutGetNumDevs();
  208293. int n = 0;
  208294. for (int i = 0; i < num; ++i)
  208295. {
  208296. MIDIOUTCAPS mc;
  208297. zerostruct (mc);
  208298. if (midiOutGetDevCaps (i, &mc, sizeof (mc)) == MMSYSERR_NOERROR)
  208299. {
  208300. if ((mc.wTechnology & MOD_MAPPER) != 0)
  208301. return n;
  208302. ++n;
  208303. }
  208304. }
  208305. return 0;
  208306. }
  208307. MidiOutput* MidiOutput::openDevice (int index)
  208308. {
  208309. UINT deviceId = MIDI_MAPPER;
  208310. const int num = midiOutGetNumDevs();
  208311. int i, n = 0;
  208312. for (i = 0; i < num; ++i)
  208313. {
  208314. MIDIOUTCAPS mc;
  208315. zerostruct (mc);
  208316. if (midiOutGetDevCaps (i, &mc, sizeof (mc)) == MMSYSERR_NOERROR)
  208317. {
  208318. // use the microsoft sw synth as a default - best not to allow deviceId
  208319. // to be MIDI_MAPPER, or else device sharing breaks
  208320. if (String (mc.szPname, sizeof (mc.szPname)).containsIgnoreCase ("microsoft"))
  208321. deviceId = i;
  208322. if (index == n)
  208323. {
  208324. deviceId = i;
  208325. break;
  208326. }
  208327. ++n;
  208328. }
  208329. }
  208330. for (i = MidiOutHandle::activeHandles.size(); --i >= 0;)
  208331. {
  208332. MidiOutHandle* const han = MidiOutHandle::activeHandles.getUnchecked(i);
  208333. if (han != 0 && han->deviceId == deviceId)
  208334. {
  208335. han->refCount++;
  208336. MidiOutput* const out = new MidiOutput();
  208337. out->internal = han;
  208338. return out;
  208339. }
  208340. }
  208341. for (i = 4; --i >= 0;)
  208342. {
  208343. HMIDIOUT h = 0;
  208344. MMRESULT res = midiOutOpen (&h, deviceId, 0, 0, CALLBACK_NULL);
  208345. if (res == MMSYSERR_NOERROR)
  208346. {
  208347. MidiOutHandle* const han = new MidiOutHandle();
  208348. han->deviceId = deviceId;
  208349. han->refCount = 1;
  208350. han->handle = h;
  208351. MidiOutHandle::activeHandles.add (han);
  208352. MidiOutput* const out = new MidiOutput();
  208353. out->internal = han;
  208354. return out;
  208355. }
  208356. else if (res == MMSYSERR_ALLOCATED)
  208357. {
  208358. Sleep (100);
  208359. }
  208360. else
  208361. {
  208362. break;
  208363. }
  208364. }
  208365. return 0;
  208366. }
  208367. MidiOutput::~MidiOutput()
  208368. {
  208369. MidiOutHandle* const h = static_cast <MidiOutHandle*> (internal);
  208370. if (MidiOutHandle::activeHandles.contains (h) && --(h->refCount) == 0)
  208371. {
  208372. midiOutClose (h->handle);
  208373. MidiOutHandle::activeHandles.removeValue (h);
  208374. delete h;
  208375. }
  208376. }
  208377. void MidiOutput::reset()
  208378. {
  208379. const MidiOutHandle* const h = static_cast <const MidiOutHandle*> (internal);
  208380. midiOutReset (h->handle);
  208381. }
  208382. bool MidiOutput::getVolume (float& leftVol,
  208383. float& rightVol)
  208384. {
  208385. const MidiOutHandle* const handle = static_cast <const MidiOutHandle*> (internal);
  208386. DWORD n;
  208387. if (midiOutGetVolume (handle->handle, &n) == MMSYSERR_NOERROR)
  208388. {
  208389. const unsigned short* const nn = (const unsigned short*) &n;
  208390. rightVol = nn[0] / (float) 0xffff;
  208391. leftVol = nn[1] / (float) 0xffff;
  208392. return true;
  208393. }
  208394. else
  208395. {
  208396. rightVol = leftVol = 1.0f;
  208397. return false;
  208398. }
  208399. }
  208400. void MidiOutput::setVolume (float leftVol,
  208401. float rightVol)
  208402. {
  208403. const MidiOutHandle* const handle = static_cast <MidiOutHandle*> (internal);
  208404. DWORD n;
  208405. unsigned short* const nn = (unsigned short*) &n;
  208406. nn[0] = (unsigned short) jlimit (0, 0xffff, (int) (rightVol * 0xffff));
  208407. nn[1] = (unsigned short) jlimit (0, 0xffff, (int) (leftVol * 0xffff));
  208408. midiOutSetVolume (handle->handle, n);
  208409. }
  208410. void MidiOutput::sendMessageNow (const MidiMessage& message)
  208411. {
  208412. const MidiOutHandle* const handle = static_cast <const MidiOutHandle*> (internal);
  208413. if (message.getRawDataSize() > 3
  208414. || message.isSysEx())
  208415. {
  208416. MIDIHDR h;
  208417. zerostruct (h);
  208418. h.lpData = (char*) message.getRawData();
  208419. h.dwBufferLength = message.getRawDataSize();
  208420. h.dwBytesRecorded = message.getRawDataSize();
  208421. if (midiOutPrepareHeader (handle->handle, &h, sizeof (MIDIHDR)) == MMSYSERR_NOERROR)
  208422. {
  208423. MMRESULT res = midiOutLongMsg (handle->handle, &h, sizeof (MIDIHDR));
  208424. if (res == MMSYSERR_NOERROR)
  208425. {
  208426. while ((h.dwFlags & MHDR_DONE) == 0)
  208427. Sleep (1);
  208428. int count = 500; // 1 sec timeout
  208429. while (--count >= 0)
  208430. {
  208431. res = midiOutUnprepareHeader (handle->handle, &h, sizeof (MIDIHDR));
  208432. if (res == MIDIERR_STILLPLAYING)
  208433. Sleep (2);
  208434. else
  208435. break;
  208436. }
  208437. }
  208438. }
  208439. }
  208440. else
  208441. {
  208442. midiOutShortMsg (handle->handle,
  208443. *(unsigned int*) message.getRawData());
  208444. }
  208445. }
  208446. #endif
  208447. /*** End of inlined file: juce_win32_Midi.cpp ***/
  208448. /*** Start of inlined file: juce_win32_ASIO.cpp ***/
  208449. // (This file gets included by juce_win32_NativeCode.cpp, rather than being
  208450. // compiled on its own).
  208451. #if JUCE_INCLUDED_FILE && JUCE_ASIO
  208452. #undef WINDOWS
  208453. // #define ASIO_DEBUGGING
  208454. #ifdef ASIO_DEBUGGING
  208455. #define log(a) { Logger::writeToLog (a); DBG (a) }
  208456. #else
  208457. #define log(a) {}
  208458. #endif
  208459. #ifdef ASIO_DEBUGGING
  208460. static void logError (const String& context, long error)
  208461. {
  208462. String err ("unknown error");
  208463. if (error == ASE_NotPresent)
  208464. err = "Not Present";
  208465. else if (error == ASE_HWMalfunction)
  208466. err = "Hardware Malfunction";
  208467. else if (error == ASE_InvalidParameter)
  208468. err = "Invalid Parameter";
  208469. else if (error == ASE_InvalidMode)
  208470. err = "Invalid Mode";
  208471. else if (error == ASE_SPNotAdvancing)
  208472. err = "Sample position not advancing";
  208473. else if (error == ASE_NoClock)
  208474. err = "No Clock";
  208475. else if (error == ASE_NoMemory)
  208476. err = "Out of memory";
  208477. log ("!!error: " + context + " - " + err);
  208478. }
  208479. #else
  208480. #define logError(a, b) {}
  208481. #endif
  208482. class ASIOAudioIODevice;
  208483. static ASIOAudioIODevice* volatile currentASIODev[3] = { 0, 0, 0 };
  208484. static const int maxASIOChannels = 160;
  208485. class JUCE_API ASIOAudioIODevice : public AudioIODevice,
  208486. private Timer
  208487. {
  208488. public:
  208489. Component ourWindow;
  208490. ASIOAudioIODevice (const String& name_, const CLSID classId_, const int slotNumber,
  208491. const String& optionalDllForDirectLoading_)
  208492. : AudioIODevice (name_, "ASIO"),
  208493. asioObject (0),
  208494. classId (classId_),
  208495. optionalDllForDirectLoading (optionalDllForDirectLoading_),
  208496. currentBitDepth (16),
  208497. currentSampleRate (0),
  208498. isOpen_ (false),
  208499. isStarted (false),
  208500. postOutput (true),
  208501. insideControlPanelModalLoop (false),
  208502. shouldUsePreferredSize (false)
  208503. {
  208504. name = name_;
  208505. ourWindow.addToDesktop (0);
  208506. windowHandle = ourWindow.getWindowHandle();
  208507. jassert (currentASIODev [slotNumber] == 0);
  208508. currentASIODev [slotNumber] = this;
  208509. openDevice();
  208510. }
  208511. ~ASIOAudioIODevice()
  208512. {
  208513. for (int i = 0; i < numElementsInArray (currentASIODev); ++i)
  208514. if (currentASIODev[i] == this)
  208515. currentASIODev[i] = 0;
  208516. close();
  208517. log ("ASIO - exiting");
  208518. removeCurrentDriver();
  208519. }
  208520. void updateSampleRates()
  208521. {
  208522. // find a list of sample rates..
  208523. const double possibleSampleRates[] = { 44100.0, 48000.0, 88200.0, 96000.0, 176400.0, 192000.0 };
  208524. sampleRates.clear();
  208525. if (asioObject != 0)
  208526. {
  208527. for (int index = 0; index < numElementsInArray (possibleSampleRates); ++index)
  208528. {
  208529. const long err = asioObject->canSampleRate (possibleSampleRates[index]);
  208530. if (err == 0)
  208531. {
  208532. sampleRates.add ((int) possibleSampleRates[index]);
  208533. log ("rate: " + String ((int) possibleSampleRates[index]));
  208534. }
  208535. else if (err != ASE_NoClock)
  208536. {
  208537. logError ("CanSampleRate", err);
  208538. }
  208539. }
  208540. if (sampleRates.size() == 0)
  208541. {
  208542. double cr = 0;
  208543. const long err = asioObject->getSampleRate (&cr);
  208544. log ("No sample rates supported - current rate: " + String ((int) cr));
  208545. if (err == 0)
  208546. sampleRates.add ((int) cr);
  208547. }
  208548. }
  208549. }
  208550. const StringArray getOutputChannelNames()
  208551. {
  208552. return outputChannelNames;
  208553. }
  208554. const StringArray getInputChannelNames()
  208555. {
  208556. return inputChannelNames;
  208557. }
  208558. int getNumSampleRates()
  208559. {
  208560. return sampleRates.size();
  208561. }
  208562. double getSampleRate (int index)
  208563. {
  208564. return sampleRates [index];
  208565. }
  208566. int getNumBufferSizesAvailable()
  208567. {
  208568. return bufferSizes.size();
  208569. }
  208570. int getBufferSizeSamples (int index)
  208571. {
  208572. return bufferSizes [index];
  208573. }
  208574. int getDefaultBufferSize()
  208575. {
  208576. return preferredSize;
  208577. }
  208578. const String open (const BigInteger& inputChannels,
  208579. const BigInteger& outputChannels,
  208580. double sr,
  208581. int bufferSizeSamples)
  208582. {
  208583. close();
  208584. currentCallback = 0;
  208585. if (bufferSizeSamples <= 0)
  208586. shouldUsePreferredSize = true;
  208587. if (asioObject == 0 || ! isASIOOpen)
  208588. {
  208589. log ("Warning: device not open");
  208590. const String err (openDevice());
  208591. if (asioObject == 0 || ! isASIOOpen)
  208592. return err;
  208593. }
  208594. isStarted = false;
  208595. bufferIndex = -1;
  208596. long err = 0;
  208597. long newPreferredSize = 0;
  208598. // if the preferred size has just changed, assume it's a control panel thing and use it as the new value.
  208599. minSize = 0;
  208600. maxSize = 0;
  208601. newPreferredSize = 0;
  208602. granularity = 0;
  208603. if (asioObject->getBufferSize (&minSize, &maxSize, &newPreferredSize, &granularity) == 0)
  208604. {
  208605. if (preferredSize != 0 && newPreferredSize != 0 && newPreferredSize != preferredSize)
  208606. shouldUsePreferredSize = true;
  208607. preferredSize = newPreferredSize;
  208608. }
  208609. // unfortunate workaround for certain manufacturers whose drivers crash horribly if you make
  208610. // dynamic changes to the buffer size...
  208611. shouldUsePreferredSize = shouldUsePreferredSize
  208612. || getName().containsIgnoreCase ("Digidesign");
  208613. if (shouldUsePreferredSize)
  208614. {
  208615. log ("Using preferred size for buffer..");
  208616. if ((err = asioObject->getBufferSize (&minSize, &maxSize, &preferredSize, &granularity)) == 0)
  208617. {
  208618. bufferSizeSamples = preferredSize;
  208619. }
  208620. else
  208621. {
  208622. bufferSizeSamples = 1024;
  208623. logError ("GetBufferSize1", err);
  208624. }
  208625. shouldUsePreferredSize = false;
  208626. }
  208627. int sampleRate = roundDoubleToInt (sr);
  208628. currentSampleRate = sampleRate;
  208629. currentBlockSizeSamples = bufferSizeSamples;
  208630. currentChansOut.clear();
  208631. currentChansIn.clear();
  208632. zeromem (inBuffers, sizeof (inBuffers));
  208633. zeromem (outBuffers, sizeof (outBuffers));
  208634. updateSampleRates();
  208635. if (sampleRate == 0 || (sampleRates.size() > 0 && ! sampleRates.contains (sampleRate)))
  208636. sampleRate = sampleRates[0];
  208637. jassert (sampleRate != 0);
  208638. if (sampleRate == 0)
  208639. sampleRate = 44100;
  208640. long numSources = 32;
  208641. ASIOClockSource clocks[32];
  208642. zeromem (clocks, sizeof (clocks));
  208643. asioObject->getClockSources (clocks, &numSources);
  208644. bool isSourceSet = false;
  208645. // careful not to remove this loop because it does more than just logging!
  208646. int i;
  208647. for (i = 0; i < numSources; ++i)
  208648. {
  208649. String s ("clock: ");
  208650. s += clocks[i].name;
  208651. if (clocks[i].isCurrentSource)
  208652. {
  208653. isSourceSet = true;
  208654. s << " (cur)";
  208655. }
  208656. log (s);
  208657. }
  208658. if (numSources > 1 && ! isSourceSet)
  208659. {
  208660. log ("setting clock source");
  208661. asioObject->setClockSource (clocks[0].index);
  208662. Thread::sleep (20);
  208663. }
  208664. else
  208665. {
  208666. if (numSources == 0)
  208667. {
  208668. log ("ASIO - no clock sources!");
  208669. }
  208670. }
  208671. double cr = 0;
  208672. err = asioObject->getSampleRate (&cr);
  208673. if (err == 0)
  208674. {
  208675. currentSampleRate = cr;
  208676. }
  208677. else
  208678. {
  208679. logError ("GetSampleRate", err);
  208680. currentSampleRate = 0;
  208681. }
  208682. error = String::empty;
  208683. needToReset = false;
  208684. isReSync = false;
  208685. err = 0;
  208686. bool buffersCreated = false;
  208687. if (currentSampleRate != sampleRate)
  208688. {
  208689. log ("ASIO samplerate: " + String (currentSampleRate) + " to " + String (sampleRate));
  208690. err = asioObject->setSampleRate (sampleRate);
  208691. if (err == ASE_NoClock && numSources > 0)
  208692. {
  208693. log ("trying to set a clock source..");
  208694. Thread::sleep (10);
  208695. err = asioObject->setClockSource (clocks[0].index);
  208696. if (err != 0)
  208697. {
  208698. logError ("SetClock", err);
  208699. }
  208700. Thread::sleep (10);
  208701. err = asioObject->setSampleRate (sampleRate);
  208702. }
  208703. }
  208704. if (err == 0)
  208705. {
  208706. currentSampleRate = sampleRate;
  208707. if (needToReset)
  208708. {
  208709. if (isReSync)
  208710. {
  208711. log ("Resync request");
  208712. }
  208713. log ("! Resetting ASIO after sample rate change");
  208714. removeCurrentDriver();
  208715. loadDriver();
  208716. const String error (initDriver());
  208717. if (error.isNotEmpty())
  208718. {
  208719. log ("ASIOInit: " + error);
  208720. }
  208721. needToReset = false;
  208722. isReSync = false;
  208723. }
  208724. numActiveInputChans = 0;
  208725. numActiveOutputChans = 0;
  208726. ASIOBufferInfo* info = bufferInfos;
  208727. int i;
  208728. for (i = 0; i < totalNumInputChans; ++i)
  208729. {
  208730. if (inputChannels[i])
  208731. {
  208732. currentChansIn.setBit (i);
  208733. info->isInput = 1;
  208734. info->channelNum = i;
  208735. info->buffers[0] = info->buffers[1] = 0;
  208736. ++info;
  208737. ++numActiveInputChans;
  208738. }
  208739. }
  208740. for (i = 0; i < totalNumOutputChans; ++i)
  208741. {
  208742. if (outputChannels[i])
  208743. {
  208744. currentChansOut.setBit (i);
  208745. info->isInput = 0;
  208746. info->channelNum = i;
  208747. info->buffers[0] = info->buffers[1] = 0;
  208748. ++info;
  208749. ++numActiveOutputChans;
  208750. }
  208751. }
  208752. const int totalBuffers = numActiveInputChans + numActiveOutputChans;
  208753. callbacks.sampleRateDidChange = &sampleRateChangedCallback;
  208754. if (currentASIODev[0] == this)
  208755. {
  208756. callbacks.bufferSwitch = &bufferSwitchCallback0;
  208757. callbacks.asioMessage = &asioMessagesCallback0;
  208758. callbacks.bufferSwitchTimeInfo = &bufferSwitchTimeInfoCallback0;
  208759. }
  208760. else if (currentASIODev[1] == this)
  208761. {
  208762. callbacks.bufferSwitch = &bufferSwitchCallback1;
  208763. callbacks.asioMessage = &asioMessagesCallback1;
  208764. callbacks.bufferSwitchTimeInfo = &bufferSwitchTimeInfoCallback1;
  208765. }
  208766. else if (currentASIODev[2] == this)
  208767. {
  208768. callbacks.bufferSwitch = &bufferSwitchCallback2;
  208769. callbacks.asioMessage = &asioMessagesCallback2;
  208770. callbacks.bufferSwitchTimeInfo = &bufferSwitchTimeInfoCallback2;
  208771. }
  208772. else
  208773. {
  208774. jassertfalse
  208775. }
  208776. log ("disposing buffers");
  208777. err = asioObject->disposeBuffers();
  208778. log ("creating buffers: " + String (totalBuffers) + ", " + String (currentBlockSizeSamples));
  208779. err = asioObject->createBuffers (bufferInfos,
  208780. totalBuffers,
  208781. currentBlockSizeSamples,
  208782. &callbacks);
  208783. if (err != 0)
  208784. {
  208785. currentBlockSizeSamples = preferredSize;
  208786. logError ("create buffers 2", err);
  208787. asioObject->disposeBuffers();
  208788. err = asioObject->createBuffers (bufferInfos,
  208789. totalBuffers,
  208790. currentBlockSizeSamples,
  208791. &callbacks);
  208792. }
  208793. if (err == 0)
  208794. {
  208795. buffersCreated = true;
  208796. tempBuffer.calloc (totalBuffers * currentBlockSizeSamples + 32);
  208797. int n = 0;
  208798. Array <int> types;
  208799. currentBitDepth = 16;
  208800. for (i = 0; i < jmin ((int) totalNumInputChans, maxASIOChannels); ++i)
  208801. {
  208802. if (inputChannels[i])
  208803. {
  208804. inBuffers[n] = tempBuffer + (currentBlockSizeSamples * n);
  208805. ASIOChannelInfo channelInfo;
  208806. zerostruct (channelInfo);
  208807. channelInfo.channel = i;
  208808. channelInfo.isInput = 1;
  208809. asioObject->getChannelInfo (&channelInfo);
  208810. types.addIfNotAlreadyThere (channelInfo.type);
  208811. typeToFormatParameters (channelInfo.type,
  208812. inputChannelBitDepths[n],
  208813. inputChannelBytesPerSample[n],
  208814. inputChannelIsFloat[n],
  208815. inputChannelLittleEndian[n]);
  208816. currentBitDepth = jmax (currentBitDepth, inputChannelBitDepths[n]);
  208817. ++n;
  208818. }
  208819. }
  208820. jassert (numActiveInputChans == n);
  208821. n = 0;
  208822. for (i = 0; i < jmin ((int) totalNumOutputChans, maxASIOChannels); ++i)
  208823. {
  208824. if (outputChannels[i])
  208825. {
  208826. outBuffers[n] = tempBuffer + (currentBlockSizeSamples * (numActiveInputChans + n));
  208827. ASIOChannelInfo channelInfo;
  208828. zerostruct (channelInfo);
  208829. channelInfo.channel = i;
  208830. channelInfo.isInput = 0;
  208831. asioObject->getChannelInfo (&channelInfo);
  208832. types.addIfNotAlreadyThere (channelInfo.type);
  208833. typeToFormatParameters (channelInfo.type,
  208834. outputChannelBitDepths[n],
  208835. outputChannelBytesPerSample[n],
  208836. outputChannelIsFloat[n],
  208837. outputChannelLittleEndian[n]);
  208838. currentBitDepth = jmax (currentBitDepth, outputChannelBitDepths[n]);
  208839. ++n;
  208840. }
  208841. }
  208842. jassert (numActiveOutputChans == n);
  208843. for (i = types.size(); --i >= 0;)
  208844. {
  208845. log ("channel format: " + String (types[i]));
  208846. }
  208847. jassert (n <= totalBuffers);
  208848. for (i = 0; i < numActiveOutputChans; ++i)
  208849. {
  208850. const int size = currentBlockSizeSamples * (outputChannelBitDepths[i] >> 3);
  208851. if (bufferInfos [numActiveInputChans + i].buffers[0] == 0
  208852. || bufferInfos [numActiveInputChans + i].buffers[1] == 0)
  208853. {
  208854. log ("!! Null buffers");
  208855. }
  208856. else
  208857. {
  208858. zeromem (bufferInfos[numActiveInputChans + i].buffers[0], size);
  208859. zeromem (bufferInfos[numActiveInputChans + i].buffers[1], size);
  208860. }
  208861. }
  208862. inputLatency = outputLatency = 0;
  208863. if (asioObject->getLatencies (&inputLatency, &outputLatency) != 0)
  208864. {
  208865. log ("ASIO - no latencies");
  208866. }
  208867. else
  208868. {
  208869. log ("ASIO latencies: " + String ((int) outputLatency) + ", " + String ((int) inputLatency));
  208870. }
  208871. isOpen_ = true;
  208872. log ("starting ASIO");
  208873. calledback = false;
  208874. err = asioObject->start();
  208875. if (err != 0)
  208876. {
  208877. isOpen_ = false;
  208878. log ("ASIO - stop on failure");
  208879. Thread::sleep (10);
  208880. asioObject->stop();
  208881. error = "Can't start device";
  208882. Thread::sleep (10);
  208883. }
  208884. else
  208885. {
  208886. int count = 300;
  208887. while (--count > 0 && ! calledback)
  208888. Thread::sleep (10);
  208889. isStarted = true;
  208890. if (! calledback)
  208891. {
  208892. error = "Device didn't start correctly";
  208893. log ("ASIO didn't callback - stopping..");
  208894. asioObject->stop();
  208895. }
  208896. }
  208897. }
  208898. else
  208899. {
  208900. error = "Can't create i/o buffers";
  208901. }
  208902. }
  208903. else
  208904. {
  208905. error = "Can't set sample rate: ";
  208906. error << sampleRate;
  208907. }
  208908. if (error.isNotEmpty())
  208909. {
  208910. logError (error, err);
  208911. if (asioObject != 0 && buffersCreated)
  208912. asioObject->disposeBuffers();
  208913. Thread::sleep (20);
  208914. isStarted = false;
  208915. isOpen_ = false;
  208916. close();
  208917. }
  208918. needToReset = false;
  208919. isReSync = false;
  208920. return error;
  208921. }
  208922. void close()
  208923. {
  208924. error = String::empty;
  208925. stopTimer();
  208926. stop();
  208927. if (isASIOOpen && isOpen_)
  208928. {
  208929. const ScopedLock sl (callbackLock);
  208930. isOpen_ = false;
  208931. isStarted = false;
  208932. needToReset = false;
  208933. isReSync = false;
  208934. log ("ASIO - stopping");
  208935. if (asioObject != 0)
  208936. {
  208937. Thread::sleep (20);
  208938. asioObject->stop();
  208939. Thread::sleep (10);
  208940. asioObject->disposeBuffers();
  208941. }
  208942. Thread::sleep (10);
  208943. }
  208944. }
  208945. bool isOpen()
  208946. {
  208947. return isOpen_ || insideControlPanelModalLoop;
  208948. }
  208949. int getCurrentBufferSizeSamples()
  208950. {
  208951. return currentBlockSizeSamples;
  208952. }
  208953. double getCurrentSampleRate()
  208954. {
  208955. return currentSampleRate;
  208956. }
  208957. const BigInteger getActiveOutputChannels() const
  208958. {
  208959. return currentChansOut;
  208960. }
  208961. const BigInteger getActiveInputChannels() const
  208962. {
  208963. return currentChansIn;
  208964. }
  208965. int getCurrentBitDepth()
  208966. {
  208967. return currentBitDepth;
  208968. }
  208969. int getOutputLatencyInSamples()
  208970. {
  208971. return outputLatency + currentBlockSizeSamples / 4;
  208972. }
  208973. int getInputLatencyInSamples()
  208974. {
  208975. return inputLatency + currentBlockSizeSamples / 4;
  208976. }
  208977. void start (AudioIODeviceCallback* callback)
  208978. {
  208979. if (callback != 0)
  208980. {
  208981. callback->audioDeviceAboutToStart (this);
  208982. const ScopedLock sl (callbackLock);
  208983. currentCallback = callback;
  208984. }
  208985. }
  208986. void stop()
  208987. {
  208988. AudioIODeviceCallback* const lastCallback = currentCallback;
  208989. {
  208990. const ScopedLock sl (callbackLock);
  208991. currentCallback = 0;
  208992. }
  208993. if (lastCallback != 0)
  208994. lastCallback->audioDeviceStopped();
  208995. }
  208996. bool isPlaying()
  208997. {
  208998. return isASIOOpen && (currentCallback != 0);
  208999. }
  209000. const String getLastError()
  209001. {
  209002. return error;
  209003. }
  209004. bool hasControlPanel() const
  209005. {
  209006. return true;
  209007. }
  209008. bool showControlPanel()
  209009. {
  209010. log ("ASIO - showing control panel");
  209011. Component modalWindow (String::empty);
  209012. modalWindow.setOpaque (true);
  209013. modalWindow.addToDesktop (0);
  209014. modalWindow.enterModalState();
  209015. bool done = false;
  209016. JUCE_TRY
  209017. {
  209018. // are there are devices that need to be closed before showing their control panel?
  209019. // close();
  209020. insideControlPanelModalLoop = true;
  209021. const uint32 started = Time::getMillisecondCounter();
  209022. if (asioObject != 0)
  209023. {
  209024. asioObject->controlPanel();
  209025. const int spent = (int) Time::getMillisecondCounter() - (int) started;
  209026. log ("spent: " + String (spent));
  209027. if (spent > 300)
  209028. {
  209029. shouldUsePreferredSize = true;
  209030. done = true;
  209031. }
  209032. }
  209033. }
  209034. JUCE_CATCH_ALL
  209035. insideControlPanelModalLoop = false;
  209036. return done;
  209037. }
  209038. void resetRequest() throw()
  209039. {
  209040. needToReset = true;
  209041. }
  209042. void resyncRequest() throw()
  209043. {
  209044. needToReset = true;
  209045. isReSync = true;
  209046. }
  209047. void timerCallback()
  209048. {
  209049. if (! insideControlPanelModalLoop)
  209050. {
  209051. stopTimer();
  209052. // used to cause a reset
  209053. log ("! ASIO restart request!");
  209054. if (isOpen_)
  209055. {
  209056. AudioIODeviceCallback* const oldCallback = currentCallback;
  209057. close();
  209058. open (BigInteger (currentChansIn), BigInteger (currentChansOut),
  209059. currentSampleRate, currentBlockSizeSamples);
  209060. if (oldCallback != 0)
  209061. start (oldCallback);
  209062. }
  209063. }
  209064. else
  209065. {
  209066. startTimer (100);
  209067. }
  209068. }
  209069. juce_UseDebuggingNewOperator
  209070. private:
  209071. IASIO* volatile asioObject;
  209072. ASIOCallbacks callbacks;
  209073. void* windowHandle;
  209074. CLSID classId;
  209075. const String optionalDllForDirectLoading;
  209076. String error;
  209077. long totalNumInputChans, totalNumOutputChans;
  209078. StringArray inputChannelNames, outputChannelNames;
  209079. Array<int> sampleRates, bufferSizes;
  209080. long inputLatency, outputLatency;
  209081. long minSize, maxSize, preferredSize, granularity;
  209082. int volatile currentBlockSizeSamples;
  209083. int volatile currentBitDepth;
  209084. double volatile currentSampleRate;
  209085. BigInteger currentChansOut, currentChansIn;
  209086. AudioIODeviceCallback* volatile currentCallback;
  209087. CriticalSection callbackLock;
  209088. ASIOBufferInfo bufferInfos [maxASIOChannels];
  209089. float* inBuffers [maxASIOChannels];
  209090. float* outBuffers [maxASIOChannels];
  209091. int inputChannelBitDepths [maxASIOChannels];
  209092. int outputChannelBitDepths [maxASIOChannels];
  209093. int inputChannelBytesPerSample [maxASIOChannels];
  209094. int outputChannelBytesPerSample [maxASIOChannels];
  209095. bool inputChannelIsFloat [maxASIOChannels];
  209096. bool outputChannelIsFloat [maxASIOChannels];
  209097. bool inputChannelLittleEndian [maxASIOChannels];
  209098. bool outputChannelLittleEndian [maxASIOChannels];
  209099. WaitableEvent event1;
  209100. HeapBlock <float> tempBuffer;
  209101. int volatile bufferIndex, numActiveInputChans, numActiveOutputChans;
  209102. bool isOpen_, isStarted;
  209103. bool volatile isASIOOpen;
  209104. bool volatile calledback;
  209105. bool volatile littleEndian, postOutput, needToReset, isReSync;
  209106. bool volatile insideControlPanelModalLoop;
  209107. bool volatile shouldUsePreferredSize;
  209108. void removeCurrentDriver()
  209109. {
  209110. if (asioObject != 0)
  209111. {
  209112. asioObject->Release();
  209113. asioObject = 0;
  209114. }
  209115. }
  209116. bool loadDriver()
  209117. {
  209118. removeCurrentDriver();
  209119. JUCE_TRY
  209120. {
  209121. if (CoCreateInstance (classId, 0, CLSCTX_INPROC_SERVER,
  209122. classId, (void**) &asioObject) == S_OK)
  209123. {
  209124. return true;
  209125. }
  209126. // If a class isn't registered but we have a path for it, we can fallback to
  209127. // doing a direct load of the COM object (only available via the juce_createASIOAudioIODeviceForGUID function).
  209128. if (optionalDllForDirectLoading.isNotEmpty())
  209129. {
  209130. HMODULE h = LoadLibrary (optionalDllForDirectLoading);
  209131. if (h != 0)
  209132. {
  209133. typedef HRESULT (CALLBACK* DllGetClassObjectFunc) (REFCLSID clsid, REFIID iid, LPVOID* ppv);
  209134. DllGetClassObjectFunc dllGetClassObject = (DllGetClassObjectFunc) GetProcAddress (h, "DllGetClassObject");
  209135. if (dllGetClassObject != 0)
  209136. {
  209137. IClassFactory* classFactory = 0;
  209138. HRESULT hr = dllGetClassObject (classId, IID_IClassFactory, (void**) &classFactory);
  209139. if (classFactory != 0)
  209140. {
  209141. hr = classFactory->CreateInstance (0, classId, (void**) &asioObject);
  209142. classFactory->Release();
  209143. }
  209144. return asioObject != 0;
  209145. }
  209146. }
  209147. }
  209148. }
  209149. JUCE_CATCH_ALL
  209150. asioObject = 0;
  209151. return false;
  209152. }
  209153. const String initDriver()
  209154. {
  209155. if (asioObject != 0)
  209156. {
  209157. char buffer [256];
  209158. zeromem (buffer, sizeof (buffer));
  209159. if (! asioObject->init (windowHandle))
  209160. {
  209161. asioObject->getErrorMessage (buffer);
  209162. return String (buffer, sizeof (buffer) - 1);
  209163. }
  209164. // just in case any daft drivers expect this to be called..
  209165. asioObject->getDriverName (buffer);
  209166. return String::empty;
  209167. }
  209168. return "No Driver";
  209169. }
  209170. const String openDevice()
  209171. {
  209172. // use this in case the driver starts opening dialog boxes..
  209173. Component modalWindow (String::empty);
  209174. modalWindow.setOpaque (true);
  209175. modalWindow.addToDesktop (0);
  209176. modalWindow.enterModalState();
  209177. // open the device and get its info..
  209178. log ("opening ASIO device: " + getName());
  209179. needToReset = false;
  209180. isReSync = false;
  209181. outputChannelNames.clear();
  209182. inputChannelNames.clear();
  209183. bufferSizes.clear();
  209184. sampleRates.clear();
  209185. isASIOOpen = false;
  209186. isOpen_ = false;
  209187. totalNumInputChans = 0;
  209188. totalNumOutputChans = 0;
  209189. numActiveInputChans = 0;
  209190. numActiveOutputChans = 0;
  209191. currentCallback = 0;
  209192. error = String::empty;
  209193. if (getName().isEmpty())
  209194. return error;
  209195. long err = 0;
  209196. if (loadDriver())
  209197. {
  209198. if ((error = initDriver()).isEmpty())
  209199. {
  209200. numActiveInputChans = 0;
  209201. numActiveOutputChans = 0;
  209202. totalNumInputChans = 0;
  209203. totalNumOutputChans = 0;
  209204. if (asioObject != 0
  209205. && (err = asioObject->getChannels (&totalNumInputChans, &totalNumOutputChans)) == 0)
  209206. {
  209207. log (String ((int) totalNumInputChans) + " in, " + String ((int) totalNumOutputChans) + " out");
  209208. if ((err = asioObject->getBufferSize (&minSize, &maxSize, &preferredSize, &granularity)) == 0)
  209209. {
  209210. // find a list of buffer sizes..
  209211. log (String ((int) minSize) + " " + String ((int) maxSize) + " " + String ((int) preferredSize) + " " + String ((int) granularity));
  209212. if (granularity >= 0)
  209213. {
  209214. granularity = jmax (1, (int) granularity);
  209215. for (int i = jmax ((int) minSize, (int) granularity); i < jmin (6400, (int) maxSize); i += granularity)
  209216. bufferSizes.addIfNotAlreadyThere (granularity * (i / granularity));
  209217. }
  209218. else if (granularity < 0)
  209219. {
  209220. for (int i = 0; i < 18; ++i)
  209221. {
  209222. const int s = (1 << i);
  209223. if (s >= minSize && s <= maxSize)
  209224. bufferSizes.add (s);
  209225. }
  209226. }
  209227. if (! bufferSizes.contains (preferredSize))
  209228. bufferSizes.insert (0, preferredSize);
  209229. double currentRate = 0;
  209230. asioObject->getSampleRate (&currentRate);
  209231. if (currentRate <= 0.0 || currentRate > 192001.0)
  209232. {
  209233. log ("setting sample rate");
  209234. err = asioObject->setSampleRate (44100.0);
  209235. if (err != 0)
  209236. {
  209237. logError ("setting sample rate", err);
  209238. }
  209239. asioObject->getSampleRate (&currentRate);
  209240. }
  209241. currentSampleRate = currentRate;
  209242. postOutput = (asioObject->outputReady() == 0);
  209243. if (postOutput)
  209244. {
  209245. log ("ASIO outputReady = ok");
  209246. }
  209247. updateSampleRates();
  209248. // ..because cubase does it at this point
  209249. inputLatency = outputLatency = 0;
  209250. if (asioObject->getLatencies (&inputLatency, &outputLatency) != 0)
  209251. {
  209252. log ("ASIO - no latencies");
  209253. }
  209254. log ("latencies: " + String ((int) inputLatency) + ", " + String ((int) outputLatency));
  209255. // create some dummy buffers now.. because cubase does..
  209256. numActiveInputChans = 0;
  209257. numActiveOutputChans = 0;
  209258. ASIOBufferInfo* info = bufferInfos;
  209259. int i, numChans = 0;
  209260. for (i = 0; i < jmin (2, (int) totalNumInputChans); ++i)
  209261. {
  209262. info->isInput = 1;
  209263. info->channelNum = i;
  209264. info->buffers[0] = info->buffers[1] = 0;
  209265. ++info;
  209266. ++numChans;
  209267. }
  209268. const int outputBufferIndex = numChans;
  209269. for (i = 0; i < jmin (2, (int) totalNumOutputChans); ++i)
  209270. {
  209271. info->isInput = 0;
  209272. info->channelNum = i;
  209273. info->buffers[0] = info->buffers[1] = 0;
  209274. ++info;
  209275. ++numChans;
  209276. }
  209277. callbacks.sampleRateDidChange = &sampleRateChangedCallback;
  209278. if (currentASIODev[0] == this)
  209279. {
  209280. callbacks.bufferSwitch = &bufferSwitchCallback0;
  209281. callbacks.asioMessage = &asioMessagesCallback0;
  209282. callbacks.bufferSwitchTimeInfo = &bufferSwitchTimeInfoCallback0;
  209283. }
  209284. else if (currentASIODev[1] == this)
  209285. {
  209286. callbacks.bufferSwitch = &bufferSwitchCallback1;
  209287. callbacks.asioMessage = &asioMessagesCallback1;
  209288. callbacks.bufferSwitchTimeInfo = &bufferSwitchTimeInfoCallback1;
  209289. }
  209290. else if (currentASIODev[2] == this)
  209291. {
  209292. callbacks.bufferSwitch = &bufferSwitchCallback2;
  209293. callbacks.asioMessage = &asioMessagesCallback2;
  209294. callbacks.bufferSwitchTimeInfo = &bufferSwitchTimeInfoCallback2;
  209295. }
  209296. else
  209297. {
  209298. jassertfalse
  209299. }
  209300. log ("creating buffers (dummy): " + String (numChans) + ", " + String ((int) preferredSize));
  209301. if (preferredSize > 0)
  209302. {
  209303. err = asioObject->createBuffers (bufferInfos, numChans, preferredSize, &callbacks);
  209304. if (err != 0)
  209305. {
  209306. logError ("dummy buffers", err);
  209307. }
  209308. }
  209309. long newInps = 0, newOuts = 0;
  209310. asioObject->getChannels (&newInps, &newOuts);
  209311. if (totalNumInputChans != newInps || totalNumOutputChans != newOuts)
  209312. {
  209313. totalNumInputChans = newInps;
  209314. totalNumOutputChans = newOuts;
  209315. log (String ((int) totalNumInputChans) + " in; " + String ((int) totalNumOutputChans) + " out");
  209316. }
  209317. updateSampleRates();
  209318. ASIOChannelInfo channelInfo;
  209319. channelInfo.type = 0;
  209320. for (i = 0; i < totalNumInputChans; ++i)
  209321. {
  209322. zerostruct (channelInfo);
  209323. channelInfo.channel = i;
  209324. channelInfo.isInput = 1;
  209325. asioObject->getChannelInfo (&channelInfo);
  209326. inputChannelNames.add (String (channelInfo.name));
  209327. }
  209328. for (i = 0; i < totalNumOutputChans; ++i)
  209329. {
  209330. zerostruct (channelInfo);
  209331. channelInfo.channel = i;
  209332. channelInfo.isInput = 0;
  209333. asioObject->getChannelInfo (&channelInfo);
  209334. outputChannelNames.add (String (channelInfo.name));
  209335. typeToFormatParameters (channelInfo.type,
  209336. outputChannelBitDepths[i],
  209337. outputChannelBytesPerSample[i],
  209338. outputChannelIsFloat[i],
  209339. outputChannelLittleEndian[i]);
  209340. if (i < 2)
  209341. {
  209342. // clear the channels that are used with the dummy stuff
  209343. const int bytesPerBuffer = preferredSize * (outputChannelBitDepths[i] >> 3);
  209344. zeromem (bufferInfos [outputBufferIndex + i].buffers[0], bytesPerBuffer);
  209345. zeromem (bufferInfos [outputBufferIndex + i].buffers[1], bytesPerBuffer);
  209346. }
  209347. }
  209348. outputChannelNames.trim();
  209349. inputChannelNames.trim();
  209350. outputChannelNames.appendNumbersToDuplicates (false, true);
  209351. inputChannelNames.appendNumbersToDuplicates (false, true);
  209352. // start and stop because cubase does it..
  209353. asioObject->getLatencies (&inputLatency, &outputLatency);
  209354. if ((err = asioObject->start()) != 0)
  209355. {
  209356. // ignore an error here, as it might start later after setting other stuff up
  209357. logError ("ASIO start", err);
  209358. }
  209359. Thread::sleep (100);
  209360. asioObject->stop();
  209361. }
  209362. else
  209363. {
  209364. error = "Can't detect buffer sizes";
  209365. }
  209366. }
  209367. else
  209368. {
  209369. error = "Can't detect asio channels";
  209370. }
  209371. }
  209372. }
  209373. else
  209374. {
  209375. error = "No such device";
  209376. }
  209377. if (error.isNotEmpty())
  209378. {
  209379. logError (error, err);
  209380. if (asioObject != 0)
  209381. asioObject->disposeBuffers();
  209382. removeCurrentDriver();
  209383. isASIOOpen = false;
  209384. }
  209385. else
  209386. {
  209387. isASIOOpen = true;
  209388. log ("ASIO device open");
  209389. }
  209390. isOpen_ = false;
  209391. needToReset = false;
  209392. isReSync = false;
  209393. return error;
  209394. }
  209395. void callback (const long index)
  209396. {
  209397. if (isStarted)
  209398. {
  209399. bufferIndex = index;
  209400. processBuffer();
  209401. }
  209402. else
  209403. {
  209404. if (postOutput && (asioObject != 0))
  209405. asioObject->outputReady();
  209406. }
  209407. calledback = true;
  209408. }
  209409. void processBuffer()
  209410. {
  209411. const ASIOBufferInfo* const infos = bufferInfos;
  209412. const int bi = bufferIndex;
  209413. const ScopedLock sl (callbackLock);
  209414. if (needToReset)
  209415. {
  209416. needToReset = false;
  209417. if (isReSync)
  209418. {
  209419. log ("! ASIO resync");
  209420. isReSync = false;
  209421. }
  209422. else
  209423. {
  209424. startTimer (20);
  209425. }
  209426. }
  209427. if (bi >= 0)
  209428. {
  209429. const int samps = currentBlockSizeSamples;
  209430. if (currentCallback != 0)
  209431. {
  209432. int i;
  209433. for (i = 0; i < numActiveInputChans; ++i)
  209434. {
  209435. float* const dst = inBuffers[i];
  209436. jassert (dst != 0);
  209437. const char* const src = (const char*) (infos[i].buffers[bi]);
  209438. if (inputChannelIsFloat[i])
  209439. {
  209440. memcpy (dst, src, samps * sizeof (float));
  209441. }
  209442. else
  209443. {
  209444. jassert (dst == tempBuffer + (samps * i));
  209445. switch (inputChannelBitDepths[i])
  209446. {
  209447. case 16:
  209448. convertInt16ToFloat (src, dst, inputChannelBytesPerSample[i],
  209449. samps, inputChannelLittleEndian[i]);
  209450. break;
  209451. case 24:
  209452. convertInt24ToFloat (src, dst, inputChannelBytesPerSample[i],
  209453. samps, inputChannelLittleEndian[i]);
  209454. break;
  209455. case 32:
  209456. convertInt32ToFloat (src, dst, inputChannelBytesPerSample[i],
  209457. samps, inputChannelLittleEndian[i]);
  209458. break;
  209459. case 64:
  209460. jassertfalse
  209461. break;
  209462. }
  209463. }
  209464. }
  209465. currentCallback->audioDeviceIOCallback ((const float**) inBuffers,
  209466. numActiveInputChans,
  209467. outBuffers,
  209468. numActiveOutputChans,
  209469. samps);
  209470. for (i = 0; i < numActiveOutputChans; ++i)
  209471. {
  209472. float* const src = outBuffers[i];
  209473. jassert (src != 0);
  209474. char* const dst = (char*) (infos [numActiveInputChans + i].buffers[bi]);
  209475. if (outputChannelIsFloat[i])
  209476. {
  209477. memcpy (dst, src, samps * sizeof (float));
  209478. }
  209479. else
  209480. {
  209481. jassert (src == tempBuffer + (samps * (numActiveInputChans + i)));
  209482. switch (outputChannelBitDepths[i])
  209483. {
  209484. case 16:
  209485. convertFloatToInt16 (src, dst, outputChannelBytesPerSample[i],
  209486. samps, outputChannelLittleEndian[i]);
  209487. break;
  209488. case 24:
  209489. convertFloatToInt24 (src, dst, outputChannelBytesPerSample[i],
  209490. samps, outputChannelLittleEndian[i]);
  209491. break;
  209492. case 32:
  209493. convertFloatToInt32 (src, dst, outputChannelBytesPerSample[i],
  209494. samps, outputChannelLittleEndian[i]);
  209495. break;
  209496. case 64:
  209497. jassertfalse
  209498. break;
  209499. }
  209500. }
  209501. }
  209502. }
  209503. else
  209504. {
  209505. for (int i = 0; i < numActiveOutputChans; ++i)
  209506. {
  209507. const int bytesPerBuffer = samps * (outputChannelBitDepths[i] >> 3);
  209508. zeromem (infos[numActiveInputChans + i].buffers[bi], bytesPerBuffer);
  209509. }
  209510. }
  209511. }
  209512. if (postOutput)
  209513. asioObject->outputReady();
  209514. }
  209515. static ASIOTime* bufferSwitchTimeInfoCallback0 (ASIOTime*, long index, long)
  209516. {
  209517. if (currentASIODev[0] != 0)
  209518. currentASIODev[0]->callback (index);
  209519. return 0;
  209520. }
  209521. static ASIOTime* bufferSwitchTimeInfoCallback1 (ASIOTime*, long index, long)
  209522. {
  209523. if (currentASIODev[1] != 0)
  209524. currentASIODev[1]->callback (index);
  209525. return 0;
  209526. }
  209527. static ASIOTime* bufferSwitchTimeInfoCallback2 (ASIOTime*, long index, long)
  209528. {
  209529. if (currentASIODev[2] != 0)
  209530. currentASIODev[2]->callback (index);
  209531. return 0;
  209532. }
  209533. static void bufferSwitchCallback0 (long index, long)
  209534. {
  209535. if (currentASIODev[0] != 0)
  209536. currentASIODev[0]->callback (index);
  209537. }
  209538. static void bufferSwitchCallback1 (long index, long)
  209539. {
  209540. if (currentASIODev[1] != 0)
  209541. currentASIODev[1]->callback (index);
  209542. }
  209543. static void bufferSwitchCallback2 (long index, long)
  209544. {
  209545. if (currentASIODev[2] != 0)
  209546. currentASIODev[2]->callback (index);
  209547. }
  209548. static long asioMessagesCallback0 (long selector, long value, void*, double*)
  209549. {
  209550. return asioMessagesCallback (selector, value, 0);
  209551. }
  209552. static long asioMessagesCallback1 (long selector, long value, void*, double*)
  209553. {
  209554. return asioMessagesCallback (selector, value, 1);
  209555. }
  209556. static long asioMessagesCallback2 (long selector, long value, void*, double*)
  209557. {
  209558. return asioMessagesCallback (selector, value, 2);
  209559. }
  209560. static long asioMessagesCallback (long selector, long value, const int deviceIndex)
  209561. {
  209562. switch (selector)
  209563. {
  209564. case kAsioSelectorSupported:
  209565. if (value == kAsioResetRequest
  209566. || value == kAsioEngineVersion
  209567. || value == kAsioResyncRequest
  209568. || value == kAsioLatenciesChanged
  209569. || value == kAsioSupportsInputMonitor)
  209570. return 1;
  209571. break;
  209572. case kAsioBufferSizeChange:
  209573. break;
  209574. case kAsioResetRequest:
  209575. if (currentASIODev[deviceIndex] != 0)
  209576. currentASIODev[deviceIndex]->resetRequest();
  209577. return 1;
  209578. case kAsioResyncRequest:
  209579. if (currentASIODev[deviceIndex] != 0)
  209580. currentASIODev[deviceIndex]->resyncRequest();
  209581. return 1;
  209582. case kAsioLatenciesChanged:
  209583. return 1;
  209584. case kAsioEngineVersion:
  209585. return 2;
  209586. case kAsioSupportsTimeInfo:
  209587. case kAsioSupportsTimeCode:
  209588. return 0;
  209589. }
  209590. return 0;
  209591. }
  209592. static void sampleRateChangedCallback (ASIOSampleRate) throw()
  209593. {
  209594. }
  209595. static void convertInt16ToFloat (const char* src,
  209596. float* dest,
  209597. const int srcStrideBytes,
  209598. int numSamples,
  209599. const bool littleEndian) throw()
  209600. {
  209601. const double g = 1.0 / 32768.0;
  209602. if (littleEndian)
  209603. {
  209604. while (--numSamples >= 0)
  209605. {
  209606. *dest++ = (float) (g * (short) ByteOrder::littleEndianShort (src));
  209607. src += srcStrideBytes;
  209608. }
  209609. }
  209610. else
  209611. {
  209612. while (--numSamples >= 0)
  209613. {
  209614. *dest++ = (float) (g * (short) ByteOrder::bigEndianShort (src));
  209615. src += srcStrideBytes;
  209616. }
  209617. }
  209618. }
  209619. static void convertFloatToInt16 (const float* src,
  209620. char* dest,
  209621. const int dstStrideBytes,
  209622. int numSamples,
  209623. const bool littleEndian) throw()
  209624. {
  209625. const double maxVal = (double) 0x7fff;
  209626. if (littleEndian)
  209627. {
  209628. while (--numSamples >= 0)
  209629. {
  209630. *(uint16*) dest = ByteOrder::swapIfBigEndian ((uint16) (short) roundDoubleToInt (jlimit (-maxVal, maxVal, maxVal * *src++)));
  209631. dest += dstStrideBytes;
  209632. }
  209633. }
  209634. else
  209635. {
  209636. while (--numSamples >= 0)
  209637. {
  209638. *(uint16*) dest = ByteOrder::swapIfLittleEndian ((uint16) (short) roundDoubleToInt (jlimit (-maxVal, maxVal, maxVal * *src++)));
  209639. dest += dstStrideBytes;
  209640. }
  209641. }
  209642. }
  209643. static void convertInt24ToFloat (const char* src,
  209644. float* dest,
  209645. const int srcStrideBytes,
  209646. int numSamples,
  209647. const bool littleEndian) throw()
  209648. {
  209649. const double g = 1.0 / 0x7fffff;
  209650. if (littleEndian)
  209651. {
  209652. while (--numSamples >= 0)
  209653. {
  209654. *dest++ = (float) (g * ByteOrder::littleEndian24Bit (src));
  209655. src += srcStrideBytes;
  209656. }
  209657. }
  209658. else
  209659. {
  209660. while (--numSamples >= 0)
  209661. {
  209662. *dest++ = (float) (g * ByteOrder::bigEndian24Bit (src));
  209663. src += srcStrideBytes;
  209664. }
  209665. }
  209666. }
  209667. static void convertFloatToInt24 (const float* src,
  209668. char* dest,
  209669. const int dstStrideBytes,
  209670. int numSamples,
  209671. const bool littleEndian) throw()
  209672. {
  209673. const double maxVal = (double) 0x7fffff;
  209674. if (littleEndian)
  209675. {
  209676. while (--numSamples >= 0)
  209677. {
  209678. ByteOrder::littleEndian24BitToChars ((uint32) roundDoubleToInt (jlimit (-maxVal, maxVal, maxVal * *src++)), dest);
  209679. dest += dstStrideBytes;
  209680. }
  209681. }
  209682. else
  209683. {
  209684. while (--numSamples >= 0)
  209685. {
  209686. ByteOrder::bigEndian24BitToChars ((uint32) roundDoubleToInt (jlimit (-maxVal, maxVal, maxVal * *src++)), dest);
  209687. dest += dstStrideBytes;
  209688. }
  209689. }
  209690. }
  209691. static void convertInt32ToFloat (const char* src,
  209692. float* dest,
  209693. const int srcStrideBytes,
  209694. int numSamples,
  209695. const bool littleEndian) throw()
  209696. {
  209697. const double g = 1.0 / 0x7fffffff;
  209698. if (littleEndian)
  209699. {
  209700. while (--numSamples >= 0)
  209701. {
  209702. *dest++ = (float) (g * (int) ByteOrder::littleEndianInt (src));
  209703. src += srcStrideBytes;
  209704. }
  209705. }
  209706. else
  209707. {
  209708. while (--numSamples >= 0)
  209709. {
  209710. *dest++ = (float) (g * (int) ByteOrder::bigEndianInt (src));
  209711. src += srcStrideBytes;
  209712. }
  209713. }
  209714. }
  209715. static void convertFloatToInt32 (const float* src,
  209716. char* dest,
  209717. const int dstStrideBytes,
  209718. int numSamples,
  209719. const bool littleEndian) throw()
  209720. {
  209721. const double maxVal = (double) 0x7fffffff;
  209722. if (littleEndian)
  209723. {
  209724. while (--numSamples >= 0)
  209725. {
  209726. *(uint32*) dest = ByteOrder::swapIfBigEndian ((uint32) roundDoubleToInt (jlimit (-maxVal, maxVal, maxVal * *src++)));
  209727. dest += dstStrideBytes;
  209728. }
  209729. }
  209730. else
  209731. {
  209732. while (--numSamples >= 0)
  209733. {
  209734. *(uint32*) dest = ByteOrder::swapIfLittleEndian ((uint32) roundDoubleToInt (jlimit (-maxVal, maxVal, maxVal * *src++)));
  209735. dest += dstStrideBytes;
  209736. }
  209737. }
  209738. }
  209739. static void typeToFormatParameters (const long type,
  209740. int& bitDepth,
  209741. int& byteStride,
  209742. bool& formatIsFloat,
  209743. bool& littleEndian) throw()
  209744. {
  209745. bitDepth = 0;
  209746. littleEndian = false;
  209747. formatIsFloat = false;
  209748. switch (type)
  209749. {
  209750. case ASIOSTInt16MSB:
  209751. case ASIOSTInt16LSB:
  209752. case ASIOSTInt32MSB16:
  209753. case ASIOSTInt32LSB16:
  209754. bitDepth = 16; break;
  209755. case ASIOSTFloat32MSB:
  209756. case ASIOSTFloat32LSB:
  209757. formatIsFloat = true;
  209758. bitDepth = 32; break;
  209759. case ASIOSTInt32MSB:
  209760. case ASIOSTInt32LSB:
  209761. bitDepth = 32; break;
  209762. case ASIOSTInt24MSB:
  209763. case ASIOSTInt24LSB:
  209764. case ASIOSTInt32MSB24:
  209765. case ASIOSTInt32LSB24:
  209766. case ASIOSTInt32MSB18:
  209767. case ASIOSTInt32MSB20:
  209768. case ASIOSTInt32LSB18:
  209769. case ASIOSTInt32LSB20:
  209770. bitDepth = 24; break;
  209771. case ASIOSTFloat64MSB:
  209772. case ASIOSTFloat64LSB:
  209773. default:
  209774. bitDepth = 64;
  209775. break;
  209776. }
  209777. switch (type)
  209778. {
  209779. case ASIOSTInt16MSB:
  209780. case ASIOSTInt32MSB16:
  209781. case ASIOSTFloat32MSB:
  209782. case ASIOSTFloat64MSB:
  209783. case ASIOSTInt32MSB:
  209784. case ASIOSTInt32MSB18:
  209785. case ASIOSTInt32MSB20:
  209786. case ASIOSTInt32MSB24:
  209787. case ASIOSTInt24MSB:
  209788. littleEndian = false; break;
  209789. case ASIOSTInt16LSB:
  209790. case ASIOSTInt32LSB16:
  209791. case ASIOSTFloat32LSB:
  209792. case ASIOSTFloat64LSB:
  209793. case ASIOSTInt32LSB:
  209794. case ASIOSTInt32LSB18:
  209795. case ASIOSTInt32LSB20:
  209796. case ASIOSTInt32LSB24:
  209797. case ASIOSTInt24LSB:
  209798. littleEndian = true; break;
  209799. default:
  209800. break;
  209801. }
  209802. switch (type)
  209803. {
  209804. case ASIOSTInt16LSB:
  209805. case ASIOSTInt16MSB:
  209806. byteStride = 2; break;
  209807. case ASIOSTInt24LSB:
  209808. case ASIOSTInt24MSB:
  209809. byteStride = 3; break;
  209810. case ASIOSTInt32MSB16:
  209811. case ASIOSTInt32LSB16:
  209812. case ASIOSTInt32MSB:
  209813. case ASIOSTInt32MSB18:
  209814. case ASIOSTInt32MSB20:
  209815. case ASIOSTInt32MSB24:
  209816. case ASIOSTInt32LSB:
  209817. case ASIOSTInt32LSB18:
  209818. case ASIOSTInt32LSB20:
  209819. case ASIOSTInt32LSB24:
  209820. case ASIOSTFloat32LSB:
  209821. case ASIOSTFloat32MSB:
  209822. byteStride = 4; break;
  209823. case ASIOSTFloat64MSB:
  209824. case ASIOSTFloat64LSB:
  209825. byteStride = 8; break;
  209826. default:
  209827. break;
  209828. }
  209829. }
  209830. };
  209831. class ASIOAudioIODeviceType : public AudioIODeviceType
  209832. {
  209833. public:
  209834. ASIOAudioIODeviceType()
  209835. : AudioIODeviceType ("ASIO"),
  209836. hasScanned (false)
  209837. {
  209838. CoInitialize (0);
  209839. }
  209840. ~ASIOAudioIODeviceType()
  209841. {
  209842. }
  209843. void scanForDevices()
  209844. {
  209845. hasScanned = true;
  209846. deviceNames.clear();
  209847. classIds.clear();
  209848. HKEY hk = 0;
  209849. int index = 0;
  209850. if (RegOpenKeyA (HKEY_LOCAL_MACHINE, "software\\asio", &hk) == ERROR_SUCCESS)
  209851. {
  209852. for (;;)
  209853. {
  209854. char name [256];
  209855. if (RegEnumKeyA (hk, index++, name, 256) == ERROR_SUCCESS)
  209856. {
  209857. addDriverInfo (name, hk);
  209858. }
  209859. else
  209860. {
  209861. break;
  209862. }
  209863. }
  209864. RegCloseKey (hk);
  209865. }
  209866. }
  209867. const StringArray getDeviceNames (bool /*wantInputNames*/) const
  209868. {
  209869. jassert (hasScanned); // need to call scanForDevices() before doing this
  209870. return deviceNames;
  209871. }
  209872. int getDefaultDeviceIndex (bool) const
  209873. {
  209874. jassert (hasScanned); // need to call scanForDevices() before doing this
  209875. for (int i = deviceNames.size(); --i >= 0;)
  209876. if (deviceNames[i].containsIgnoreCase ("asio4all"))
  209877. return i; // asio4all is a safe choice for a default..
  209878. #if JUCE_DEBUG
  209879. if (deviceNames.size() > 1 && deviceNames[0].containsIgnoreCase ("digidesign"))
  209880. return 1; // (the digi m-box driver crashes the app when you run
  209881. // it in the debugger, which can be a bit annoying)
  209882. #endif
  209883. return 0;
  209884. }
  209885. static int findFreeSlot()
  209886. {
  209887. for (int i = 0; i < numElementsInArray (currentASIODev); ++i)
  209888. if (currentASIODev[i] == 0)
  209889. return i;
  209890. jassertfalse; // unfortunately you can only have a finite number
  209891. // of ASIO devices open at the same time..
  209892. return -1;
  209893. }
  209894. int getIndexOfDevice (AudioIODevice* d, bool /*asInput*/) const
  209895. {
  209896. jassert (hasScanned); // need to call scanForDevices() before doing this
  209897. return d == 0 ? -1 : deviceNames.indexOf (d->getName());
  209898. }
  209899. bool hasSeparateInputsAndOutputs() const { return false; }
  209900. AudioIODevice* createDevice (const String& outputDeviceName,
  209901. const String& inputDeviceName)
  209902. {
  209903. // ASIO can't open two different devices for input and output - they must be the same one.
  209904. jassert (inputDeviceName == outputDeviceName || outputDeviceName.isEmpty() || inputDeviceName.isEmpty());
  209905. jassert (hasScanned); // need to call scanForDevices() before doing this
  209906. const int index = deviceNames.indexOf (outputDeviceName.isNotEmpty() ? outputDeviceName
  209907. : inputDeviceName);
  209908. if (index >= 0)
  209909. {
  209910. const int freeSlot = findFreeSlot();
  209911. if (freeSlot >= 0)
  209912. return new ASIOAudioIODevice (outputDeviceName, *(classIds [index]), freeSlot, String::empty);
  209913. }
  209914. return 0;
  209915. }
  209916. juce_UseDebuggingNewOperator
  209917. private:
  209918. StringArray deviceNames;
  209919. OwnedArray <CLSID> classIds;
  209920. bool hasScanned;
  209921. static bool checkClassIsOk (const String& classId)
  209922. {
  209923. HKEY hk = 0;
  209924. bool ok = false;
  209925. if (RegOpenKey (HKEY_CLASSES_ROOT, _T("clsid"), &hk) == ERROR_SUCCESS)
  209926. {
  209927. int index = 0;
  209928. for (;;)
  209929. {
  209930. WCHAR buf [512];
  209931. if (RegEnumKey (hk, index++, buf, 512) == ERROR_SUCCESS)
  209932. {
  209933. if (classId.equalsIgnoreCase (buf))
  209934. {
  209935. HKEY subKey, pathKey;
  209936. if (RegOpenKeyEx (hk, buf, 0, KEY_READ, &subKey) == ERROR_SUCCESS)
  209937. {
  209938. if (RegOpenKeyEx (subKey, _T("InprocServer32"), 0, KEY_READ, &pathKey) == ERROR_SUCCESS)
  209939. {
  209940. WCHAR pathName [1024];
  209941. DWORD dtype = REG_SZ;
  209942. DWORD dsize = sizeof (pathName);
  209943. if (RegQueryValueEx (pathKey, 0, 0, &dtype, (LPBYTE) pathName, &dsize) == ERROR_SUCCESS)
  209944. ok = File (pathName).exists();
  209945. RegCloseKey (pathKey);
  209946. }
  209947. RegCloseKey (subKey);
  209948. }
  209949. break;
  209950. }
  209951. }
  209952. else
  209953. {
  209954. break;
  209955. }
  209956. }
  209957. RegCloseKey (hk);
  209958. }
  209959. return ok;
  209960. }
  209961. void addDriverInfo (const String& keyName, HKEY hk)
  209962. {
  209963. HKEY subKey;
  209964. if (RegOpenKeyEx (hk, keyName, 0, KEY_READ, &subKey) == ERROR_SUCCESS)
  209965. {
  209966. WCHAR buf [256];
  209967. zerostruct (buf);
  209968. DWORD dtype = REG_SZ;
  209969. DWORD dsize = sizeof (buf);
  209970. if (RegQueryValueEx (subKey, _T("clsid"), 0, &dtype, (LPBYTE) buf, &dsize) == ERROR_SUCCESS)
  209971. {
  209972. if (dsize > 0 && checkClassIsOk (buf))
  209973. {
  209974. CLSID classId;
  209975. if (CLSIDFromString ((LPOLESTR) buf, &classId) == S_OK)
  209976. {
  209977. dtype = REG_SZ;
  209978. dsize = sizeof (buf);
  209979. String deviceName;
  209980. if (RegQueryValueEx (subKey, _T("description"), 0, &dtype, (LPBYTE) buf, &dsize) == ERROR_SUCCESS)
  209981. deviceName = buf;
  209982. else
  209983. deviceName = keyName;
  209984. log ("found " + deviceName);
  209985. deviceNames.add (deviceName);
  209986. classIds.add (new CLSID (classId));
  209987. }
  209988. }
  209989. RegCloseKey (subKey);
  209990. }
  209991. }
  209992. }
  209993. ASIOAudioIODeviceType (const ASIOAudioIODeviceType&);
  209994. ASIOAudioIODeviceType& operator= (const ASIOAudioIODeviceType&);
  209995. };
  209996. AudioIODeviceType* juce_createAudioIODeviceType_ASIO()
  209997. {
  209998. return new ASIOAudioIODeviceType();
  209999. }
  210000. AudioIODevice* juce_createASIOAudioIODeviceForGUID (const String& name,
  210001. void* guid,
  210002. const String& optionalDllForDirectLoading)
  210003. {
  210004. const int freeSlot = ASIOAudioIODeviceType::findFreeSlot();
  210005. if (freeSlot < 0)
  210006. return 0;
  210007. return new ASIOAudioIODevice (name, *(CLSID*) guid, freeSlot, optionalDllForDirectLoading);
  210008. }
  210009. #undef log
  210010. #endif
  210011. /*** End of inlined file: juce_win32_ASIO.cpp ***/
  210012. /*** Start of inlined file: juce_win32_DirectSound.cpp ***/
  210013. // (This file gets included by juce_win32_NativeCode.cpp, rather than being
  210014. // compiled on its own).
  210015. #if JUCE_INCLUDED_FILE && JUCE_DIRECTSOUND
  210016. END_JUCE_NAMESPACE
  210017. extern "C"
  210018. {
  210019. // Declare just the minimum number of interfaces for the DSound objects that we need..
  210020. typedef struct typeDSBUFFERDESC
  210021. {
  210022. DWORD dwSize;
  210023. DWORD dwFlags;
  210024. DWORD dwBufferBytes;
  210025. DWORD dwReserved;
  210026. LPWAVEFORMATEX lpwfxFormat;
  210027. GUID guid3DAlgorithm;
  210028. } DSBUFFERDESC;
  210029. struct IDirectSoundBuffer;
  210030. #undef INTERFACE
  210031. #define INTERFACE IDirectSound
  210032. DECLARE_INTERFACE_(IDirectSound, IUnknown)
  210033. {
  210034. STDMETHOD(QueryInterface) (THIS_ REFIID, LPVOID*) PURE;
  210035. STDMETHOD_(ULONG,AddRef) (THIS) PURE;
  210036. STDMETHOD_(ULONG,Release) (THIS) PURE;
  210037. STDMETHOD(CreateSoundBuffer) (THIS_ DSBUFFERDESC*, IDirectSoundBuffer**, LPUNKNOWN) PURE;
  210038. STDMETHOD(GetCaps) (THIS_ void*) PURE;
  210039. STDMETHOD(DuplicateSoundBuffer) (THIS_ IDirectSoundBuffer*, IDirectSoundBuffer**) PURE;
  210040. STDMETHOD(SetCooperativeLevel) (THIS_ HWND, DWORD) PURE;
  210041. STDMETHOD(Compact) (THIS) PURE;
  210042. STDMETHOD(GetSpeakerConfig) (THIS_ LPDWORD) PURE;
  210043. STDMETHOD(SetSpeakerConfig) (THIS_ DWORD) PURE;
  210044. STDMETHOD(Initialize) (THIS_ const GUID*) PURE;
  210045. };
  210046. #undef INTERFACE
  210047. #define INTERFACE IDirectSoundBuffer
  210048. DECLARE_INTERFACE_(IDirectSoundBuffer, IUnknown)
  210049. {
  210050. STDMETHOD(QueryInterface) (THIS_ REFIID, LPVOID*) PURE;
  210051. STDMETHOD_(ULONG,AddRef) (THIS) PURE;
  210052. STDMETHOD_(ULONG,Release) (THIS) PURE;
  210053. STDMETHOD(GetCaps) (THIS_ void*) PURE;
  210054. STDMETHOD(GetCurrentPosition) (THIS_ LPDWORD, LPDWORD) PURE;
  210055. STDMETHOD(GetFormat) (THIS_ LPWAVEFORMATEX, DWORD, LPDWORD) PURE;
  210056. STDMETHOD(GetVolume) (THIS_ LPLONG) PURE;
  210057. STDMETHOD(GetPan) (THIS_ LPLONG) PURE;
  210058. STDMETHOD(GetFrequency) (THIS_ LPDWORD) PURE;
  210059. STDMETHOD(GetStatus) (THIS_ LPDWORD) PURE;
  210060. STDMETHOD(Initialize) (THIS_ IDirectSound*, DSBUFFERDESC*) PURE;
  210061. STDMETHOD(Lock) (THIS_ DWORD, DWORD, LPVOID*, LPDWORD, LPVOID*, LPDWORD, DWORD) PURE;
  210062. STDMETHOD(Play) (THIS_ DWORD, DWORD, DWORD) PURE;
  210063. STDMETHOD(SetCurrentPosition) (THIS_ DWORD) PURE;
  210064. STDMETHOD(SetFormat) (THIS_ const WAVEFORMATEX*) PURE;
  210065. STDMETHOD(SetVolume) (THIS_ LONG) PURE;
  210066. STDMETHOD(SetPan) (THIS_ LONG) PURE;
  210067. STDMETHOD(SetFrequency) (THIS_ DWORD) PURE;
  210068. STDMETHOD(Stop) (THIS) PURE;
  210069. STDMETHOD(Unlock) (THIS_ LPVOID, DWORD, LPVOID, DWORD) PURE;
  210070. STDMETHOD(Restore) (THIS) PURE;
  210071. };
  210072. typedef struct typeDSCBUFFERDESC
  210073. {
  210074. DWORD dwSize;
  210075. DWORD dwFlags;
  210076. DWORD dwBufferBytes;
  210077. DWORD dwReserved;
  210078. LPWAVEFORMATEX lpwfxFormat;
  210079. } DSCBUFFERDESC;
  210080. struct IDirectSoundCaptureBuffer;
  210081. #undef INTERFACE
  210082. #define INTERFACE IDirectSoundCapture
  210083. DECLARE_INTERFACE_(IDirectSoundCapture, IUnknown)
  210084. {
  210085. STDMETHOD(QueryInterface) (THIS_ REFIID, LPVOID*) PURE;
  210086. STDMETHOD_(ULONG,AddRef) (THIS) PURE;
  210087. STDMETHOD_(ULONG,Release) (THIS) PURE;
  210088. STDMETHOD(CreateCaptureBuffer) (THIS_ DSCBUFFERDESC*, IDirectSoundCaptureBuffer**, LPUNKNOWN) PURE;
  210089. STDMETHOD(GetCaps) (THIS_ void*) PURE;
  210090. STDMETHOD(Initialize) (THIS_ const GUID*) PURE;
  210091. };
  210092. #undef INTERFACE
  210093. #define INTERFACE IDirectSoundCaptureBuffer
  210094. DECLARE_INTERFACE_(IDirectSoundCaptureBuffer, IUnknown)
  210095. {
  210096. STDMETHOD(QueryInterface) (THIS_ REFIID, LPVOID*) PURE;
  210097. STDMETHOD_(ULONG,AddRef) (THIS) PURE;
  210098. STDMETHOD_(ULONG,Release) (THIS) PURE;
  210099. STDMETHOD(GetCaps) (THIS_ void*) PURE;
  210100. STDMETHOD(GetCurrentPosition) (THIS_ LPDWORD, LPDWORD) PURE;
  210101. STDMETHOD(GetFormat) (THIS_ LPWAVEFORMATEX, DWORD, LPDWORD) PURE;
  210102. STDMETHOD(GetStatus) (THIS_ LPDWORD) PURE;
  210103. STDMETHOD(Initialize) (THIS_ IDirectSoundCapture*, DSCBUFFERDESC*) PURE;
  210104. STDMETHOD(Lock) (THIS_ DWORD, DWORD, LPVOID*, LPDWORD, LPVOID*, LPDWORD, DWORD) PURE;
  210105. STDMETHOD(Start) (THIS_ DWORD) PURE;
  210106. STDMETHOD(Stop) (THIS) PURE;
  210107. STDMETHOD(Unlock) (THIS_ LPVOID, DWORD, LPVOID, DWORD) PURE;
  210108. };
  210109. };
  210110. BEGIN_JUCE_NAMESPACE
  210111. static const String getDSErrorMessage (HRESULT hr)
  210112. {
  210113. const char* result = 0;
  210114. switch (hr)
  210115. {
  210116. case MAKE_HRESULT(1, 0x878, 10):
  210117. result = "Device already allocated";
  210118. break;
  210119. case MAKE_HRESULT(1, 0x878, 30):
  210120. result = "Control unavailable";
  210121. break;
  210122. case E_INVALIDARG:
  210123. result = "Invalid parameter";
  210124. break;
  210125. case MAKE_HRESULT(1, 0x878, 50):
  210126. result = "Invalid call";
  210127. break;
  210128. case E_FAIL:
  210129. result = "Generic error";
  210130. break;
  210131. case MAKE_HRESULT(1, 0x878, 70):
  210132. result = "Priority level error";
  210133. break;
  210134. case E_OUTOFMEMORY:
  210135. result = "Out of memory";
  210136. break;
  210137. case MAKE_HRESULT(1, 0x878, 100):
  210138. result = "Bad format";
  210139. break;
  210140. case E_NOTIMPL:
  210141. result = "Unsupported function";
  210142. break;
  210143. case MAKE_HRESULT(1, 0x878, 120):
  210144. result = "No driver";
  210145. break;
  210146. case MAKE_HRESULT(1, 0x878, 130):
  210147. result = "Already initialised";
  210148. break;
  210149. case CLASS_E_NOAGGREGATION:
  210150. result = "No aggregation";
  210151. break;
  210152. case MAKE_HRESULT(1, 0x878, 150):
  210153. result = "Buffer lost";
  210154. break;
  210155. case MAKE_HRESULT(1, 0x878, 160):
  210156. result = "Another app has priority";
  210157. break;
  210158. case MAKE_HRESULT(1, 0x878, 170):
  210159. result = "Uninitialised";
  210160. break;
  210161. case E_NOINTERFACE:
  210162. result = "No interface";
  210163. break;
  210164. case S_OK:
  210165. result = "No error";
  210166. break;
  210167. default:
  210168. return "Unknown error: " + String ((int) hr);
  210169. }
  210170. return result;
  210171. }
  210172. #define DS_DEBUGGING 1
  210173. #ifdef DS_DEBUGGING
  210174. #define CATCH JUCE_CATCH_EXCEPTION
  210175. #undef log
  210176. #define log(a) Logger::writeToLog(a);
  210177. #undef logError
  210178. #define logError(a) logDSError(a, __LINE__);
  210179. static void logDSError (HRESULT hr, int lineNum)
  210180. {
  210181. if (hr != S_OK)
  210182. {
  210183. String error ("DS error at line ");
  210184. error << lineNum << " - " << getDSErrorMessage (hr);
  210185. log (error);
  210186. }
  210187. }
  210188. #else
  210189. #define CATCH JUCE_CATCH_ALL
  210190. #define log(a)
  210191. #define logError(a)
  210192. #endif
  210193. #define DSOUND_FUNCTION(functionName, params) \
  210194. typedef HRESULT (WINAPI *type##functionName) params; \
  210195. static type##functionName ds##functionName = 0;
  210196. #define DSOUND_FUNCTION_LOAD(functionName) \
  210197. ds##functionName = (type##functionName) GetProcAddress (h, #functionName); \
  210198. jassert (ds##functionName != 0);
  210199. typedef BOOL (CALLBACK *LPDSENUMCALLBACKW) (LPGUID, LPCWSTR, LPCWSTR, LPVOID);
  210200. typedef BOOL (CALLBACK *LPDSENUMCALLBACKA) (LPGUID, LPCSTR, LPCSTR, LPVOID);
  210201. DSOUND_FUNCTION (DirectSoundCreate, (const GUID*, IDirectSound**, LPUNKNOWN))
  210202. DSOUND_FUNCTION (DirectSoundCaptureCreate, (const GUID*, IDirectSoundCapture**, LPUNKNOWN))
  210203. DSOUND_FUNCTION (DirectSoundEnumerateW, (LPDSENUMCALLBACKW, LPVOID))
  210204. DSOUND_FUNCTION (DirectSoundCaptureEnumerateW, (LPDSENUMCALLBACKW, LPVOID))
  210205. static void initialiseDSoundFunctions()
  210206. {
  210207. if (dsDirectSoundCreate == 0)
  210208. {
  210209. HMODULE h = LoadLibraryA ("dsound.dll");
  210210. DSOUND_FUNCTION_LOAD (DirectSoundCreate)
  210211. DSOUND_FUNCTION_LOAD (DirectSoundCaptureCreate)
  210212. DSOUND_FUNCTION_LOAD (DirectSoundEnumerateW)
  210213. DSOUND_FUNCTION_LOAD (DirectSoundCaptureEnumerateW)
  210214. }
  210215. }
  210216. class DSoundInternalOutChannel
  210217. {
  210218. String name;
  210219. LPGUID guid;
  210220. int sampleRate, bufferSizeSamples;
  210221. float* leftBuffer;
  210222. float* rightBuffer;
  210223. IDirectSound* pDirectSound;
  210224. IDirectSoundBuffer* pOutputBuffer;
  210225. DWORD writeOffset;
  210226. int totalBytesPerBuffer;
  210227. int bytesPerBuffer;
  210228. unsigned int lastPlayCursor;
  210229. public:
  210230. int bitDepth;
  210231. bool doneFlag;
  210232. DSoundInternalOutChannel (const String& name_,
  210233. LPGUID guid_,
  210234. int rate,
  210235. int bufferSize,
  210236. float* left,
  210237. float* right)
  210238. : name (name_),
  210239. guid (guid_),
  210240. sampleRate (rate),
  210241. bufferSizeSamples (bufferSize),
  210242. leftBuffer (left),
  210243. rightBuffer (right),
  210244. pDirectSound (0),
  210245. pOutputBuffer (0),
  210246. bitDepth (16)
  210247. {
  210248. }
  210249. ~DSoundInternalOutChannel()
  210250. {
  210251. close();
  210252. }
  210253. void close()
  210254. {
  210255. HRESULT hr;
  210256. if (pOutputBuffer != 0)
  210257. {
  210258. JUCE_TRY
  210259. {
  210260. log ("closing dsound out: " + name);
  210261. hr = pOutputBuffer->Stop();
  210262. logError (hr);
  210263. }
  210264. CATCH
  210265. JUCE_TRY
  210266. {
  210267. hr = pOutputBuffer->Release();
  210268. logError (hr);
  210269. }
  210270. CATCH
  210271. pOutputBuffer = 0;
  210272. }
  210273. if (pDirectSound != 0)
  210274. {
  210275. JUCE_TRY
  210276. {
  210277. hr = pDirectSound->Release();
  210278. logError (hr);
  210279. }
  210280. CATCH
  210281. pDirectSound = 0;
  210282. }
  210283. }
  210284. const String open()
  210285. {
  210286. log ("opening dsound out device: " + name + " rate=" + String (sampleRate)
  210287. + " bits=" + String (bitDepth) + " buf=" + String (bufferSizeSamples));
  210288. pDirectSound = 0;
  210289. pOutputBuffer = 0;
  210290. writeOffset = 0;
  210291. String error;
  210292. HRESULT hr = E_NOINTERFACE;
  210293. if (dsDirectSoundCreate != 0)
  210294. hr = dsDirectSoundCreate (guid, &pDirectSound, 0);
  210295. if (hr == S_OK)
  210296. {
  210297. bytesPerBuffer = (bufferSizeSamples * (bitDepth >> 2)) & ~15;
  210298. totalBytesPerBuffer = (3 * bytesPerBuffer) & ~15;
  210299. const int numChannels = 2;
  210300. hr = pDirectSound->SetCooperativeLevel (GetDesktopWindow(), 2 /* DSSCL_PRIORITY */);
  210301. logError (hr);
  210302. if (hr == S_OK)
  210303. {
  210304. IDirectSoundBuffer* pPrimaryBuffer;
  210305. DSBUFFERDESC primaryDesc;
  210306. zerostruct (primaryDesc);
  210307. primaryDesc.dwSize = sizeof (DSBUFFERDESC);
  210308. primaryDesc.dwFlags = 1 /* DSBCAPS_PRIMARYBUFFER */;
  210309. primaryDesc.dwBufferBytes = 0;
  210310. primaryDesc.lpwfxFormat = 0;
  210311. log ("opening dsound out step 2");
  210312. hr = pDirectSound->CreateSoundBuffer (&primaryDesc, &pPrimaryBuffer, 0);
  210313. logError (hr);
  210314. if (hr == S_OK)
  210315. {
  210316. WAVEFORMATEX wfFormat;
  210317. wfFormat.wFormatTag = WAVE_FORMAT_PCM;
  210318. wfFormat.nChannels = (unsigned short) numChannels;
  210319. wfFormat.nSamplesPerSec = sampleRate;
  210320. wfFormat.wBitsPerSample = (unsigned short) bitDepth;
  210321. wfFormat.nBlockAlign = (unsigned short) (wfFormat.nChannels * wfFormat.wBitsPerSample / 8);
  210322. wfFormat.nAvgBytesPerSec = wfFormat.nSamplesPerSec * wfFormat.nBlockAlign;
  210323. wfFormat.cbSize = 0;
  210324. hr = pPrimaryBuffer->SetFormat (&wfFormat);
  210325. logError (hr);
  210326. if (hr == S_OK)
  210327. {
  210328. DSBUFFERDESC secondaryDesc;
  210329. zerostruct (secondaryDesc);
  210330. secondaryDesc.dwSize = sizeof (DSBUFFERDESC);
  210331. secondaryDesc.dwFlags = 0x8000 /* DSBCAPS_GLOBALFOCUS */
  210332. | 0x10000 /* DSBCAPS_GETCURRENTPOSITION2 */;
  210333. secondaryDesc.dwBufferBytes = totalBytesPerBuffer;
  210334. secondaryDesc.lpwfxFormat = &wfFormat;
  210335. hr = pDirectSound->CreateSoundBuffer (&secondaryDesc, &pOutputBuffer, 0);
  210336. logError (hr);
  210337. if (hr == S_OK)
  210338. {
  210339. log ("opening dsound out step 3");
  210340. DWORD dwDataLen;
  210341. unsigned char* pDSBuffData;
  210342. hr = pOutputBuffer->Lock (0, totalBytesPerBuffer,
  210343. (LPVOID*) &pDSBuffData, &dwDataLen, 0, 0, 0);
  210344. logError (hr);
  210345. if (hr == S_OK)
  210346. {
  210347. zeromem (pDSBuffData, dwDataLen);
  210348. hr = pOutputBuffer->Unlock (pDSBuffData, dwDataLen, 0, 0);
  210349. if (hr == S_OK)
  210350. {
  210351. hr = pOutputBuffer->SetCurrentPosition (0);
  210352. if (hr == S_OK)
  210353. {
  210354. hr = pOutputBuffer->Play (0, 0, 1 /* DSBPLAY_LOOPING */);
  210355. if (hr == S_OK)
  210356. return String::empty;
  210357. }
  210358. }
  210359. }
  210360. }
  210361. }
  210362. }
  210363. }
  210364. }
  210365. error = getDSErrorMessage (hr);
  210366. close();
  210367. return error;
  210368. }
  210369. void synchronisePosition()
  210370. {
  210371. if (pOutputBuffer != 0)
  210372. {
  210373. DWORD playCursor;
  210374. pOutputBuffer->GetCurrentPosition (&playCursor, &writeOffset);
  210375. }
  210376. }
  210377. bool service()
  210378. {
  210379. if (pOutputBuffer == 0)
  210380. return true;
  210381. DWORD playCursor, writeCursor;
  210382. for (;;)
  210383. {
  210384. HRESULT hr = pOutputBuffer->GetCurrentPosition (&playCursor, &writeCursor);
  210385. if (hr == MAKE_HRESULT (1, 0x878, 150)) // DSERR_BUFFERLOST
  210386. {
  210387. pOutputBuffer->Restore();
  210388. continue;
  210389. }
  210390. if (hr == S_OK)
  210391. break;
  210392. logError (hr);
  210393. jassertfalse
  210394. return true;
  210395. }
  210396. int playWriteGap = writeCursor - playCursor;
  210397. if (playWriteGap < 0)
  210398. playWriteGap += totalBytesPerBuffer;
  210399. int bytesEmpty = playCursor - writeOffset;
  210400. if (bytesEmpty < 0)
  210401. bytesEmpty += totalBytesPerBuffer;
  210402. if (bytesEmpty > (totalBytesPerBuffer - playWriteGap))
  210403. {
  210404. writeOffset = writeCursor;
  210405. bytesEmpty = totalBytesPerBuffer - playWriteGap;
  210406. }
  210407. if (bytesEmpty >= bytesPerBuffer)
  210408. {
  210409. LPBYTE lpbuf1 = 0;
  210410. LPBYTE lpbuf2 = 0;
  210411. DWORD dwSize1 = 0;
  210412. DWORD dwSize2 = 0;
  210413. HRESULT hr = pOutputBuffer->Lock (writeOffset,
  210414. bytesPerBuffer,
  210415. (void**) &lpbuf1, &dwSize1,
  210416. (void**) &lpbuf2, &dwSize2, 0);
  210417. if (hr == MAKE_HRESULT (1, 0x878, 150)) // DSERR_BUFFERLOST
  210418. {
  210419. pOutputBuffer->Restore();
  210420. hr = pOutputBuffer->Lock (writeOffset,
  210421. bytesPerBuffer,
  210422. (void**) &lpbuf1, &dwSize1,
  210423. (void**) &lpbuf2, &dwSize2, 0);
  210424. }
  210425. if (hr == S_OK)
  210426. {
  210427. if (bitDepth == 16)
  210428. {
  210429. const float gainL = 32767.0f;
  210430. const float gainR = 32767.0f;
  210431. int* dest = (int*)lpbuf1;
  210432. const float* left = leftBuffer;
  210433. const float* right = rightBuffer;
  210434. int samples1 = dwSize1 >> 2;
  210435. int samples2 = dwSize2 >> 2;
  210436. if (left == 0)
  210437. {
  210438. while (--samples1 >= 0)
  210439. {
  210440. int r = roundToInt (gainR * *right++);
  210441. if (r < -32768)
  210442. r = -32768;
  210443. else if (r > 32767)
  210444. r = 32767;
  210445. *dest++ = (r << 16);
  210446. }
  210447. dest = (int*)lpbuf2;
  210448. while (--samples2 >= 0)
  210449. {
  210450. int r = roundToInt (gainR * *right++);
  210451. if (r < -32768)
  210452. r = -32768;
  210453. else if (r > 32767)
  210454. r = 32767;
  210455. *dest++ = (r << 16);
  210456. }
  210457. }
  210458. else if (right == 0)
  210459. {
  210460. while (--samples1 >= 0)
  210461. {
  210462. int l = roundToInt (gainL * *left++);
  210463. if (l < -32768)
  210464. l = -32768;
  210465. else if (l > 32767)
  210466. l = 32767;
  210467. l &= 0xffff;
  210468. *dest++ = l;
  210469. }
  210470. dest = (int*)lpbuf2;
  210471. while (--samples2 >= 0)
  210472. {
  210473. int l = roundToInt (gainL * *left++);
  210474. if (l < -32768)
  210475. l = -32768;
  210476. else if (l > 32767)
  210477. l = 32767;
  210478. l &= 0xffff;
  210479. *dest++ = l;
  210480. }
  210481. }
  210482. else
  210483. {
  210484. while (--samples1 >= 0)
  210485. {
  210486. int l = roundToInt (gainL * *left++);
  210487. if (l < -32768)
  210488. l = -32768;
  210489. else if (l > 32767)
  210490. l = 32767;
  210491. l &= 0xffff;
  210492. int r = roundToInt (gainR * *right++);
  210493. if (r < -32768)
  210494. r = -32768;
  210495. else if (r > 32767)
  210496. r = 32767;
  210497. *dest++ = (r << 16) | l;
  210498. }
  210499. dest = (int*)lpbuf2;
  210500. while (--samples2 >= 0)
  210501. {
  210502. int l = roundToInt (gainL * *left++);
  210503. if (l < -32768)
  210504. l = -32768;
  210505. else if (l > 32767)
  210506. l = 32767;
  210507. l &= 0xffff;
  210508. int r = roundToInt (gainR * *right++);
  210509. if (r < -32768)
  210510. r = -32768;
  210511. else if (r > 32767)
  210512. r = 32767;
  210513. *dest++ = (r << 16) | l;
  210514. }
  210515. }
  210516. }
  210517. else
  210518. {
  210519. jassertfalse
  210520. }
  210521. writeOffset = (writeOffset + dwSize1 + dwSize2) % totalBytesPerBuffer;
  210522. pOutputBuffer->Unlock (lpbuf1, dwSize1, lpbuf2, dwSize2);
  210523. }
  210524. else
  210525. {
  210526. jassertfalse
  210527. logError (hr);
  210528. }
  210529. bytesEmpty -= bytesPerBuffer;
  210530. return true;
  210531. }
  210532. else
  210533. {
  210534. return false;
  210535. }
  210536. }
  210537. };
  210538. struct DSoundInternalInChannel
  210539. {
  210540. String name;
  210541. LPGUID guid;
  210542. int sampleRate, bufferSizeSamples;
  210543. float* leftBuffer;
  210544. float* rightBuffer;
  210545. IDirectSound* pDirectSound;
  210546. IDirectSoundCapture* pDirectSoundCapture;
  210547. IDirectSoundCaptureBuffer* pInputBuffer;
  210548. public:
  210549. unsigned int readOffset;
  210550. int bytesPerBuffer, totalBytesPerBuffer;
  210551. int bitDepth;
  210552. bool doneFlag;
  210553. DSoundInternalInChannel (const String& name_,
  210554. LPGUID guid_,
  210555. int rate,
  210556. int bufferSize,
  210557. float* left,
  210558. float* right)
  210559. : name (name_),
  210560. guid (guid_),
  210561. sampleRate (rate),
  210562. bufferSizeSamples (bufferSize),
  210563. leftBuffer (left),
  210564. rightBuffer (right),
  210565. pDirectSound (0),
  210566. pDirectSoundCapture (0),
  210567. pInputBuffer (0),
  210568. bitDepth (16)
  210569. {
  210570. }
  210571. ~DSoundInternalInChannel()
  210572. {
  210573. close();
  210574. }
  210575. void close()
  210576. {
  210577. HRESULT hr;
  210578. if (pInputBuffer != 0)
  210579. {
  210580. JUCE_TRY
  210581. {
  210582. log ("closing dsound in: " + name);
  210583. hr = pInputBuffer->Stop();
  210584. logError (hr);
  210585. }
  210586. CATCH
  210587. JUCE_TRY
  210588. {
  210589. hr = pInputBuffer->Release();
  210590. logError (hr);
  210591. }
  210592. CATCH
  210593. pInputBuffer = 0;
  210594. }
  210595. if (pDirectSoundCapture != 0)
  210596. {
  210597. JUCE_TRY
  210598. {
  210599. hr = pDirectSoundCapture->Release();
  210600. logError (hr);
  210601. }
  210602. CATCH
  210603. pDirectSoundCapture = 0;
  210604. }
  210605. if (pDirectSound != 0)
  210606. {
  210607. JUCE_TRY
  210608. {
  210609. hr = pDirectSound->Release();
  210610. logError (hr);
  210611. }
  210612. CATCH
  210613. pDirectSound = 0;
  210614. }
  210615. }
  210616. const String open()
  210617. {
  210618. log ("opening dsound in device: " + name
  210619. + " rate=" + String (sampleRate) + " bits=" + String (bitDepth) + " buf=" + String (bufferSizeSamples));
  210620. pDirectSound = 0;
  210621. pDirectSoundCapture = 0;
  210622. pInputBuffer = 0;
  210623. readOffset = 0;
  210624. totalBytesPerBuffer = 0;
  210625. String error;
  210626. HRESULT hr = E_NOINTERFACE;
  210627. if (dsDirectSoundCaptureCreate != 0)
  210628. hr = dsDirectSoundCaptureCreate (guid, &pDirectSoundCapture, 0);
  210629. logError (hr);
  210630. if (hr == S_OK)
  210631. {
  210632. const int numChannels = 2;
  210633. bytesPerBuffer = (bufferSizeSamples * (bitDepth >> 2)) & ~15;
  210634. totalBytesPerBuffer = (3 * bytesPerBuffer) & ~15;
  210635. WAVEFORMATEX wfFormat;
  210636. wfFormat.wFormatTag = WAVE_FORMAT_PCM;
  210637. wfFormat.nChannels = (unsigned short)numChannels;
  210638. wfFormat.nSamplesPerSec = sampleRate;
  210639. wfFormat.wBitsPerSample = (unsigned short)bitDepth;
  210640. wfFormat.nBlockAlign = (unsigned short)(wfFormat.nChannels * (wfFormat.wBitsPerSample / 8));
  210641. wfFormat.nAvgBytesPerSec = wfFormat.nSamplesPerSec * wfFormat.nBlockAlign;
  210642. wfFormat.cbSize = 0;
  210643. DSCBUFFERDESC captureDesc;
  210644. zerostruct (captureDesc);
  210645. captureDesc.dwSize = sizeof (DSCBUFFERDESC);
  210646. captureDesc.dwFlags = 0;
  210647. captureDesc.dwBufferBytes = totalBytesPerBuffer;
  210648. captureDesc.lpwfxFormat = &wfFormat;
  210649. log ("opening dsound in step 2");
  210650. hr = pDirectSoundCapture->CreateCaptureBuffer (&captureDesc, &pInputBuffer, 0);
  210651. logError (hr);
  210652. if (hr == S_OK)
  210653. {
  210654. hr = pInputBuffer->Start (1 /* DSCBSTART_LOOPING */);
  210655. logError (hr);
  210656. if (hr == S_OK)
  210657. return String::empty;
  210658. }
  210659. }
  210660. error = getDSErrorMessage (hr);
  210661. close();
  210662. return error;
  210663. }
  210664. void synchronisePosition()
  210665. {
  210666. if (pInputBuffer != 0)
  210667. {
  210668. DWORD capturePos;
  210669. pInputBuffer->GetCurrentPosition (&capturePos, (DWORD*)&readOffset);
  210670. }
  210671. }
  210672. bool service()
  210673. {
  210674. if (pInputBuffer == 0)
  210675. return true;
  210676. DWORD capturePos, readPos;
  210677. HRESULT hr = pInputBuffer->GetCurrentPosition (&capturePos, &readPos);
  210678. logError (hr);
  210679. if (hr != S_OK)
  210680. return true;
  210681. int bytesFilled = readPos - readOffset;
  210682. if (bytesFilled < 0)
  210683. bytesFilled += totalBytesPerBuffer;
  210684. if (bytesFilled >= bytesPerBuffer)
  210685. {
  210686. LPBYTE lpbuf1 = 0;
  210687. LPBYTE lpbuf2 = 0;
  210688. DWORD dwsize1 = 0;
  210689. DWORD dwsize2 = 0;
  210690. HRESULT hr = pInputBuffer->Lock (readOffset,
  210691. bytesPerBuffer,
  210692. (void**) &lpbuf1, &dwsize1,
  210693. (void**) &lpbuf2, &dwsize2, 0);
  210694. if (hr == S_OK)
  210695. {
  210696. if (bitDepth == 16)
  210697. {
  210698. const float g = 1.0f / 32768.0f;
  210699. float* destL = leftBuffer;
  210700. float* destR = rightBuffer;
  210701. int samples1 = dwsize1 >> 2;
  210702. int samples2 = dwsize2 >> 2;
  210703. const short* src = (const short*)lpbuf1;
  210704. if (destL == 0)
  210705. {
  210706. while (--samples1 >= 0)
  210707. {
  210708. ++src;
  210709. *destR++ = *src++ * g;
  210710. }
  210711. src = (const short*)lpbuf2;
  210712. while (--samples2 >= 0)
  210713. {
  210714. ++src;
  210715. *destR++ = *src++ * g;
  210716. }
  210717. }
  210718. else if (destR == 0)
  210719. {
  210720. while (--samples1 >= 0)
  210721. {
  210722. *destL++ = *src++ * g;
  210723. ++src;
  210724. }
  210725. src = (const short*)lpbuf2;
  210726. while (--samples2 >= 0)
  210727. {
  210728. *destL++ = *src++ * g;
  210729. ++src;
  210730. }
  210731. }
  210732. else
  210733. {
  210734. while (--samples1 >= 0)
  210735. {
  210736. *destL++ = *src++ * g;
  210737. *destR++ = *src++ * g;
  210738. }
  210739. src = (const short*)lpbuf2;
  210740. while (--samples2 >= 0)
  210741. {
  210742. *destL++ = *src++ * g;
  210743. *destR++ = *src++ * g;
  210744. }
  210745. }
  210746. }
  210747. else
  210748. {
  210749. jassertfalse
  210750. }
  210751. readOffset = (readOffset + dwsize1 + dwsize2) % totalBytesPerBuffer;
  210752. pInputBuffer->Unlock (lpbuf1, dwsize1, lpbuf2, dwsize2);
  210753. }
  210754. else
  210755. {
  210756. logError (hr);
  210757. jassertfalse
  210758. }
  210759. bytesFilled -= bytesPerBuffer;
  210760. return true;
  210761. }
  210762. else
  210763. {
  210764. return false;
  210765. }
  210766. }
  210767. };
  210768. class DSoundAudioIODevice : public AudioIODevice,
  210769. public Thread
  210770. {
  210771. public:
  210772. DSoundAudioIODevice (const String& deviceName,
  210773. const int outputDeviceIndex_,
  210774. const int inputDeviceIndex_)
  210775. : AudioIODevice (deviceName, "DirectSound"),
  210776. Thread ("Juce DSound"),
  210777. isOpen_ (false),
  210778. isStarted (false),
  210779. outputDeviceIndex (outputDeviceIndex_),
  210780. inputDeviceIndex (inputDeviceIndex_),
  210781. totalSamplesOut (0),
  210782. sampleRate (0.0),
  210783. inputBuffers (1, 1),
  210784. outputBuffers (1, 1),
  210785. callback (0),
  210786. bufferSizeSamples (0)
  210787. {
  210788. if (outputDeviceIndex_ >= 0)
  210789. {
  210790. outChannels.add (TRANS("Left"));
  210791. outChannels.add (TRANS("Right"));
  210792. }
  210793. if (inputDeviceIndex_ >= 0)
  210794. {
  210795. inChannels.add (TRANS("Left"));
  210796. inChannels.add (TRANS("Right"));
  210797. }
  210798. }
  210799. ~DSoundAudioIODevice()
  210800. {
  210801. close();
  210802. }
  210803. const StringArray getOutputChannelNames()
  210804. {
  210805. return outChannels;
  210806. }
  210807. const StringArray getInputChannelNames()
  210808. {
  210809. return inChannels;
  210810. }
  210811. int getNumSampleRates()
  210812. {
  210813. return 4;
  210814. }
  210815. double getSampleRate (int index)
  210816. {
  210817. const double samps[] = { 44100.0, 48000.0, 88200.0, 96000.0 };
  210818. return samps [jlimit (0, 3, index)];
  210819. }
  210820. int getNumBufferSizesAvailable()
  210821. {
  210822. return 50;
  210823. }
  210824. int getBufferSizeSamples (int index)
  210825. {
  210826. int n = 64;
  210827. for (int i = 0; i < index; ++i)
  210828. n += (n < 512) ? 32
  210829. : ((n < 1024) ? 64
  210830. : ((n < 2048) ? 128 : 256));
  210831. return n;
  210832. }
  210833. int getDefaultBufferSize()
  210834. {
  210835. return 2560;
  210836. }
  210837. const String open (const BigInteger& inputChannels,
  210838. const BigInteger& outputChannels,
  210839. double sampleRate,
  210840. int bufferSizeSamples)
  210841. {
  210842. lastError = openDevice (inputChannels, outputChannels, sampleRate, bufferSizeSamples);
  210843. isOpen_ = lastError.isEmpty();
  210844. return lastError;
  210845. }
  210846. void close()
  210847. {
  210848. stop();
  210849. if (isOpen_)
  210850. {
  210851. closeDevice();
  210852. isOpen_ = false;
  210853. }
  210854. }
  210855. bool isOpen()
  210856. {
  210857. return isOpen_ && isThreadRunning();
  210858. }
  210859. int getCurrentBufferSizeSamples()
  210860. {
  210861. return bufferSizeSamples;
  210862. }
  210863. double getCurrentSampleRate()
  210864. {
  210865. return sampleRate;
  210866. }
  210867. int getCurrentBitDepth()
  210868. {
  210869. int i, bits = 256;
  210870. for (i = inChans.size(); --i >= 0;)
  210871. bits = jmin (bits, inChans[i]->bitDepth);
  210872. for (i = outChans.size(); --i >= 0;)
  210873. bits = jmin (bits, outChans[i]->bitDepth);
  210874. if (bits > 32)
  210875. bits = 16;
  210876. return bits;
  210877. }
  210878. const BigInteger getActiveOutputChannels() const
  210879. {
  210880. return enabledOutputs;
  210881. }
  210882. const BigInteger getActiveInputChannels() const
  210883. {
  210884. return enabledInputs;
  210885. }
  210886. int getOutputLatencyInSamples()
  210887. {
  210888. return (int) (getCurrentBufferSizeSamples() * 1.5);
  210889. }
  210890. int getInputLatencyInSamples()
  210891. {
  210892. return getOutputLatencyInSamples();
  210893. }
  210894. void start (AudioIODeviceCallback* call)
  210895. {
  210896. if (isOpen_ && call != 0 && ! isStarted)
  210897. {
  210898. if (! isThreadRunning())
  210899. {
  210900. // something gone wrong and the thread's stopped..
  210901. isOpen_ = false;
  210902. return;
  210903. }
  210904. call->audioDeviceAboutToStart (this);
  210905. const ScopedLock sl (startStopLock);
  210906. callback = call;
  210907. isStarted = true;
  210908. }
  210909. }
  210910. void stop()
  210911. {
  210912. if (isStarted)
  210913. {
  210914. AudioIODeviceCallback* const callbackLocal = callback;
  210915. {
  210916. const ScopedLock sl (startStopLock);
  210917. isStarted = false;
  210918. }
  210919. if (callbackLocal != 0)
  210920. callbackLocal->audioDeviceStopped();
  210921. }
  210922. }
  210923. bool isPlaying()
  210924. {
  210925. return isStarted && isOpen_ && isThreadRunning();
  210926. }
  210927. const String getLastError()
  210928. {
  210929. return lastError;
  210930. }
  210931. juce_UseDebuggingNewOperator
  210932. StringArray inChannels, outChannels;
  210933. int outputDeviceIndex, inputDeviceIndex;
  210934. private:
  210935. bool isOpen_;
  210936. bool isStarted;
  210937. String lastError;
  210938. OwnedArray <DSoundInternalInChannel> inChans;
  210939. OwnedArray <DSoundInternalOutChannel> outChans;
  210940. WaitableEvent startEvent;
  210941. int bufferSizeSamples;
  210942. int volatile totalSamplesOut;
  210943. int64 volatile lastBlockTime;
  210944. double sampleRate;
  210945. BigInteger enabledInputs, enabledOutputs;
  210946. AudioSampleBuffer inputBuffers, outputBuffers;
  210947. AudioIODeviceCallback* callback;
  210948. CriticalSection startStopLock;
  210949. DSoundAudioIODevice (const DSoundAudioIODevice&);
  210950. DSoundAudioIODevice& operator= (const DSoundAudioIODevice&);
  210951. const String openDevice (const BigInteger& inputChannels,
  210952. const BigInteger& outputChannels,
  210953. double sampleRate_,
  210954. int bufferSizeSamples_);
  210955. void closeDevice()
  210956. {
  210957. isStarted = false;
  210958. stopThread (5000);
  210959. inChans.clear();
  210960. outChans.clear();
  210961. inputBuffers.setSize (1, 1);
  210962. outputBuffers.setSize (1, 1);
  210963. }
  210964. void resync()
  210965. {
  210966. if (! threadShouldExit())
  210967. {
  210968. sleep (5);
  210969. int i;
  210970. for (i = 0; i < outChans.size(); ++i)
  210971. outChans.getUnchecked(i)->synchronisePosition();
  210972. for (i = 0; i < inChans.size(); ++i)
  210973. inChans.getUnchecked(i)->synchronisePosition();
  210974. }
  210975. }
  210976. public:
  210977. void run()
  210978. {
  210979. while (! threadShouldExit())
  210980. {
  210981. if (wait (100))
  210982. break;
  210983. }
  210984. const int latencyMs = (int) (bufferSizeSamples * 1000.0 / sampleRate);
  210985. const int maxTimeMS = jmax (5, 3 * latencyMs);
  210986. while (! threadShouldExit())
  210987. {
  210988. int numToDo = 0;
  210989. uint32 startTime = Time::getMillisecondCounter();
  210990. int i;
  210991. for (i = inChans.size(); --i >= 0;)
  210992. {
  210993. inChans.getUnchecked(i)->doneFlag = false;
  210994. ++numToDo;
  210995. }
  210996. for (i = outChans.size(); --i >= 0;)
  210997. {
  210998. outChans.getUnchecked(i)->doneFlag = false;
  210999. ++numToDo;
  211000. }
  211001. if (numToDo > 0)
  211002. {
  211003. const int maxCount = 3;
  211004. int count = maxCount;
  211005. for (;;)
  211006. {
  211007. for (i = inChans.size(); --i >= 0;)
  211008. {
  211009. DSoundInternalInChannel* const in = inChans.getUnchecked(i);
  211010. if ((! in->doneFlag) && in->service())
  211011. {
  211012. in->doneFlag = true;
  211013. --numToDo;
  211014. }
  211015. }
  211016. for (i = outChans.size(); --i >= 0;)
  211017. {
  211018. DSoundInternalOutChannel* const out = outChans.getUnchecked(i);
  211019. if ((! out->doneFlag) && out->service())
  211020. {
  211021. out->doneFlag = true;
  211022. --numToDo;
  211023. }
  211024. }
  211025. if (numToDo <= 0)
  211026. break;
  211027. if (Time::getMillisecondCounter() > startTime + maxTimeMS)
  211028. {
  211029. resync();
  211030. break;
  211031. }
  211032. if (--count <= 0)
  211033. {
  211034. Sleep (1);
  211035. count = maxCount;
  211036. }
  211037. if (threadShouldExit())
  211038. return;
  211039. }
  211040. }
  211041. else
  211042. {
  211043. sleep (1);
  211044. }
  211045. const ScopedLock sl (startStopLock);
  211046. if (isStarted)
  211047. {
  211048. JUCE_TRY
  211049. {
  211050. callback->audioDeviceIOCallback (const_cast <const float**> (inputBuffers.getArrayOfChannels()),
  211051. inputBuffers.getNumChannels(),
  211052. outputBuffers.getArrayOfChannels(),
  211053. outputBuffers.getNumChannels(),
  211054. bufferSizeSamples);
  211055. }
  211056. JUCE_CATCH_EXCEPTION
  211057. totalSamplesOut += bufferSizeSamples;
  211058. }
  211059. else
  211060. {
  211061. outputBuffers.clear();
  211062. totalSamplesOut = 0;
  211063. sleep (1);
  211064. }
  211065. }
  211066. }
  211067. };
  211068. class DSoundAudioIODeviceType : public AudioIODeviceType
  211069. {
  211070. public:
  211071. DSoundAudioIODeviceType()
  211072. : AudioIODeviceType ("DirectSound"),
  211073. hasScanned (false)
  211074. {
  211075. initialiseDSoundFunctions();
  211076. }
  211077. ~DSoundAudioIODeviceType()
  211078. {
  211079. }
  211080. void scanForDevices()
  211081. {
  211082. hasScanned = true;
  211083. outputDeviceNames.clear();
  211084. outputGuids.clear();
  211085. inputDeviceNames.clear();
  211086. inputGuids.clear();
  211087. if (dsDirectSoundEnumerateW != 0)
  211088. {
  211089. dsDirectSoundEnumerateW (outputEnumProcW, this);
  211090. dsDirectSoundCaptureEnumerateW (inputEnumProcW, this);
  211091. }
  211092. }
  211093. const StringArray getDeviceNames (bool wantInputNames) const
  211094. {
  211095. jassert (hasScanned); // need to call scanForDevices() before doing this
  211096. return wantInputNames ? inputDeviceNames
  211097. : outputDeviceNames;
  211098. }
  211099. int getDefaultDeviceIndex (bool /*forInput*/) const
  211100. {
  211101. jassert (hasScanned); // need to call scanForDevices() before doing this
  211102. return 0;
  211103. }
  211104. int getIndexOfDevice (AudioIODevice* device, bool asInput) const
  211105. {
  211106. jassert (hasScanned); // need to call scanForDevices() before doing this
  211107. DSoundAudioIODevice* const d = dynamic_cast <DSoundAudioIODevice*> (device);
  211108. if (d == 0)
  211109. return -1;
  211110. return asInput ? d->inputDeviceIndex
  211111. : d->outputDeviceIndex;
  211112. }
  211113. bool hasSeparateInputsAndOutputs() const { return true; }
  211114. AudioIODevice* createDevice (const String& outputDeviceName,
  211115. const String& inputDeviceName)
  211116. {
  211117. jassert (hasScanned); // need to call scanForDevices() before doing this
  211118. const int outputIndex = outputDeviceNames.indexOf (outputDeviceName);
  211119. const int inputIndex = inputDeviceNames.indexOf (inputDeviceName);
  211120. if (outputIndex >= 0 || inputIndex >= 0)
  211121. return new DSoundAudioIODevice (outputDeviceName.isNotEmpty() ? outputDeviceName
  211122. : inputDeviceName,
  211123. outputIndex, inputIndex);
  211124. return 0;
  211125. }
  211126. juce_UseDebuggingNewOperator
  211127. StringArray outputDeviceNames;
  211128. OwnedArray <GUID> outputGuids;
  211129. StringArray inputDeviceNames;
  211130. OwnedArray <GUID> inputGuids;
  211131. private:
  211132. bool hasScanned;
  211133. BOOL outputEnumProc (LPGUID lpGUID, String desc)
  211134. {
  211135. desc = desc.trim();
  211136. if (desc.isNotEmpty())
  211137. {
  211138. const String origDesc (desc);
  211139. int n = 2;
  211140. while (outputDeviceNames.contains (desc))
  211141. desc = origDesc + " (" + String (n++) + ")";
  211142. outputDeviceNames.add (desc);
  211143. if (lpGUID != 0)
  211144. outputGuids.add (new GUID (*lpGUID));
  211145. else
  211146. outputGuids.add (0);
  211147. }
  211148. return TRUE;
  211149. }
  211150. static BOOL CALLBACK outputEnumProcW (LPGUID lpGUID, LPCWSTR description, LPCWSTR, LPVOID object)
  211151. {
  211152. return ((DSoundAudioIODeviceType*) object)
  211153. ->outputEnumProc (lpGUID, String (description));
  211154. }
  211155. static BOOL CALLBACK outputEnumProcA (LPGUID lpGUID, LPCTSTR description, LPCTSTR, LPVOID object)
  211156. {
  211157. return ((DSoundAudioIODeviceType*) object)
  211158. ->outputEnumProc (lpGUID, String (description));
  211159. }
  211160. BOOL CALLBACK inputEnumProc (LPGUID lpGUID, String desc)
  211161. {
  211162. desc = desc.trim();
  211163. if (desc.isNotEmpty())
  211164. {
  211165. const String origDesc (desc);
  211166. int n = 2;
  211167. while (inputDeviceNames.contains (desc))
  211168. desc = origDesc + " (" + String (n++) + ")";
  211169. inputDeviceNames.add (desc);
  211170. if (lpGUID != 0)
  211171. inputGuids.add (new GUID (*lpGUID));
  211172. else
  211173. inputGuids.add (0);
  211174. }
  211175. return TRUE;
  211176. }
  211177. static BOOL CALLBACK inputEnumProcW (LPGUID lpGUID, LPCWSTR description, LPCWSTR, LPVOID object)
  211178. {
  211179. return ((DSoundAudioIODeviceType*) object)
  211180. ->inputEnumProc (lpGUID, String (description));
  211181. }
  211182. static BOOL CALLBACK inputEnumProcA (LPGUID lpGUID, LPCTSTR description, LPCTSTR, LPVOID object)
  211183. {
  211184. return ((DSoundAudioIODeviceType*) object)
  211185. ->inputEnumProc (lpGUID, String (description));
  211186. }
  211187. DSoundAudioIODeviceType (const DSoundAudioIODeviceType&);
  211188. DSoundAudioIODeviceType& operator= (const DSoundAudioIODeviceType&);
  211189. };
  211190. const String DSoundAudioIODevice::openDevice (const BigInteger& inputChannels,
  211191. const BigInteger& outputChannels,
  211192. double sampleRate_,
  211193. int bufferSizeSamples_)
  211194. {
  211195. closeDevice();
  211196. totalSamplesOut = 0;
  211197. sampleRate = sampleRate_;
  211198. if (bufferSizeSamples_ <= 0)
  211199. bufferSizeSamples_ = 960; // use as a default size if none is set.
  211200. bufferSizeSamples = bufferSizeSamples_ & ~7;
  211201. DSoundAudioIODeviceType dlh;
  211202. dlh.scanForDevices();
  211203. enabledInputs = inputChannels;
  211204. enabledInputs.setRange (inChannels.size(),
  211205. enabledInputs.getHighestBit() + 1 - inChannels.size(),
  211206. false);
  211207. inputBuffers.setSize (enabledInputs.countNumberOfSetBits(), bufferSizeSamples);
  211208. int i, numIns = 0;
  211209. for (i = 0; i <= enabledInputs.getHighestBit(); i += 2)
  211210. {
  211211. float* left = 0;
  211212. if (enabledInputs[i])
  211213. left = inputBuffers.getSampleData (numIns++);
  211214. float* right = 0;
  211215. if (enabledInputs[i + 1])
  211216. right = inputBuffers.getSampleData (numIns++);
  211217. if (left != 0 || right != 0)
  211218. inChans.add (new DSoundInternalInChannel (dlh.inputDeviceNames [inputDeviceIndex],
  211219. dlh.inputGuids [inputDeviceIndex],
  211220. (int) sampleRate, bufferSizeSamples,
  211221. left, right));
  211222. }
  211223. enabledOutputs = outputChannels;
  211224. enabledOutputs.setRange (outChannels.size(),
  211225. enabledOutputs.getHighestBit() + 1 - outChannels.size(),
  211226. false);
  211227. outputBuffers.setSize (enabledOutputs.countNumberOfSetBits(), bufferSizeSamples);
  211228. int numOuts = 0;
  211229. for (i = 0; i <= enabledOutputs.getHighestBit(); i += 2)
  211230. {
  211231. float* left = 0;
  211232. if (enabledOutputs[i])
  211233. left = outputBuffers.getSampleData (numOuts++);
  211234. float* right = 0;
  211235. if (enabledOutputs[i + 1])
  211236. right = outputBuffers.getSampleData (numOuts++);
  211237. if (left != 0 || right != 0)
  211238. outChans.add (new DSoundInternalOutChannel (dlh.outputDeviceNames[outputDeviceIndex],
  211239. dlh.outputGuids [outputDeviceIndex],
  211240. (int) sampleRate, bufferSizeSamples,
  211241. left, right));
  211242. }
  211243. String error;
  211244. // boost our priority while opening the devices to try to get better sync between them
  211245. const int oldThreadPri = GetThreadPriority (GetCurrentThread());
  211246. const int oldProcPri = GetPriorityClass (GetCurrentProcess());
  211247. SetThreadPriority (GetCurrentThread(), THREAD_PRIORITY_TIME_CRITICAL);
  211248. SetPriorityClass (GetCurrentProcess(), REALTIME_PRIORITY_CLASS);
  211249. for (i = 0; i < outChans.size(); ++i)
  211250. {
  211251. error = outChans[i]->open();
  211252. if (error.isNotEmpty())
  211253. {
  211254. error = "Error opening " + dlh.outputDeviceNames[i] + ": \"" + error + "\"";
  211255. break;
  211256. }
  211257. }
  211258. if (error.isEmpty())
  211259. {
  211260. for (i = 0; i < inChans.size(); ++i)
  211261. {
  211262. error = inChans[i]->open();
  211263. if (error.isNotEmpty())
  211264. {
  211265. error = "Error opening " + dlh.inputDeviceNames[i] + ": \"" + error + "\"";
  211266. break;
  211267. }
  211268. }
  211269. }
  211270. if (error.isEmpty())
  211271. {
  211272. totalSamplesOut = 0;
  211273. for (i = 0; i < outChans.size(); ++i)
  211274. outChans.getUnchecked(i)->synchronisePosition();
  211275. for (i = 0; i < inChans.size(); ++i)
  211276. inChans.getUnchecked(i)->synchronisePosition();
  211277. startThread (9);
  211278. sleep (10);
  211279. notify();
  211280. }
  211281. else
  211282. {
  211283. log (error);
  211284. }
  211285. SetThreadPriority (GetCurrentThread(), oldThreadPri);
  211286. SetPriorityClass (GetCurrentProcess(), oldProcPri);
  211287. return error;
  211288. }
  211289. AudioIODeviceType* juce_createAudioIODeviceType_DirectSound()
  211290. {
  211291. return new DSoundAudioIODeviceType();
  211292. }
  211293. #undef log
  211294. #endif
  211295. /*** End of inlined file: juce_win32_DirectSound.cpp ***/
  211296. /*** Start of inlined file: juce_win32_WASAPI.cpp ***/
  211297. // (This file gets included by juce_win32_NativeCode.cpp, rather than being
  211298. // compiled on its own).
  211299. #if JUCE_INCLUDED_FILE && JUCE_WASAPI
  211300. #if 1
  211301. const String getAudioErrorDesc (HRESULT hr)
  211302. {
  211303. const char* e = 0;
  211304. switch (hr)
  211305. {
  211306. case E_POINTER: e = "E_POINTER"; break;
  211307. case E_INVALIDARG: e = "E_INVALIDARG"; break;
  211308. case AUDCLNT_E_NOT_INITIALIZED: e = "AUDCLNT_E_NOT_INITIALIZED"; break;
  211309. case AUDCLNT_E_ALREADY_INITIALIZED: e = "AUDCLNT_E_ALREADY_INITIALIZED"; break;
  211310. case AUDCLNT_E_WRONG_ENDPOINT_TYPE: e = "AUDCLNT_E_WRONG_ENDPOINT_TYPE"; break;
  211311. case AUDCLNT_E_DEVICE_INVALIDATED: e = "AUDCLNT_E_DEVICE_INVALIDATED"; break;
  211312. case AUDCLNT_E_NOT_STOPPED: e = "AUDCLNT_E_NOT_STOPPED"; break;
  211313. case AUDCLNT_E_BUFFER_TOO_LARGE: e = "AUDCLNT_E_BUFFER_TOO_LARGE"; break;
  211314. case AUDCLNT_E_OUT_OF_ORDER: e = "AUDCLNT_E_OUT_OF_ORDER"; break;
  211315. case AUDCLNT_E_UNSUPPORTED_FORMAT: e = "AUDCLNT_E_UNSUPPORTED_FORMAT"; break;
  211316. case AUDCLNT_E_INVALID_SIZE: e = "AUDCLNT_E_INVALID_SIZE"; break;
  211317. case AUDCLNT_E_DEVICE_IN_USE: e = "AUDCLNT_E_DEVICE_IN_USE"; break;
  211318. case AUDCLNT_E_BUFFER_OPERATION_PENDING: e = "AUDCLNT_E_BUFFER_OPERATION_PENDING"; break;
  211319. case AUDCLNT_E_THREAD_NOT_REGISTERED: e = "AUDCLNT_E_THREAD_NOT_REGISTERED"; break;
  211320. case AUDCLNT_E_EXCLUSIVE_MODE_NOT_ALLOWED: e = "AUDCLNT_E_EXCLUSIVE_MODE_NOT_ALLOWED"; break;
  211321. case AUDCLNT_E_ENDPOINT_CREATE_FAILED: e = "AUDCLNT_E_ENDPOINT_CREATE_FAILED"; break;
  211322. case AUDCLNT_E_SERVICE_NOT_RUNNING: e = "AUDCLNT_E_SERVICE_NOT_RUNNING"; break;
  211323. case AUDCLNT_E_EVENTHANDLE_NOT_EXPECTED: e = "AUDCLNT_E_EVENTHANDLE_NOT_EXPECTED"; break;
  211324. case AUDCLNT_E_EXCLUSIVE_MODE_ONLY: e = "AUDCLNT_E_EXCLUSIVE_MODE_ONLY"; break;
  211325. case AUDCLNT_E_BUFDURATION_PERIOD_NOT_EQUAL: e = "AUDCLNT_E_BUFDURATION_PERIOD_NOT_EQUAL"; break;
  211326. case AUDCLNT_E_EVENTHANDLE_NOT_SET: e = "AUDCLNT_E_EVENTHANDLE_NOT_SET"; break;
  211327. case AUDCLNT_E_INCORRECT_BUFFER_SIZE: e = "AUDCLNT_E_INCORRECT_BUFFER_SIZE"; break;
  211328. case AUDCLNT_E_BUFFER_SIZE_ERROR: e = "AUDCLNT_E_BUFFER_SIZE_ERROR"; break;
  211329. case AUDCLNT_S_BUFFER_EMPTY: e = "AUDCLNT_S_BUFFER_EMPTY"; break;
  211330. case AUDCLNT_S_THREAD_ALREADY_REGISTERED: e = "AUDCLNT_S_THREAD_ALREADY_REGISTERED"; break;
  211331. default: return String::toHexString ((int) hr);
  211332. }
  211333. return e;
  211334. }
  211335. #define logFailure(hr) { if (FAILED (hr)) { DBG ("WASAPI FAIL! " + getAudioErrorDesc (hr)); jassertfalse } }
  211336. #define OK(a) wasapi_checkResult(a)
  211337. static bool wasapi_checkResult (HRESULT hr)
  211338. {
  211339. logFailure (hr);
  211340. return SUCCEEDED (hr);
  211341. }
  211342. #else
  211343. #define logFailure(hr) {}
  211344. #define OK(a) SUCCEEDED(a)
  211345. #endif
  211346. static const String wasapi_getDeviceID (IMMDevice* const device)
  211347. {
  211348. String s;
  211349. WCHAR* deviceId = 0;
  211350. if (OK (device->GetId (&deviceId)))
  211351. {
  211352. s = String (deviceId);
  211353. CoTaskMemFree (deviceId);
  211354. }
  211355. return s;
  211356. }
  211357. static EDataFlow wasapi_getDataFlow (IMMDevice* const device)
  211358. {
  211359. EDataFlow flow = eRender;
  211360. ComSmartPtr <IMMEndpoint> endPoint;
  211361. if (OK (device->QueryInterface (__uuidof (IMMEndpoint), (void**) &endPoint)))
  211362. (void) OK (endPoint->GetDataFlow (&flow));
  211363. return flow;
  211364. }
  211365. static int wasapi_refTimeToSamples (const REFERENCE_TIME& t, const double sampleRate) throw()
  211366. {
  211367. return roundDoubleToInt (sampleRate * ((double) t) * 0.0000001);
  211368. }
  211369. static void wasapi_copyWavFormat (WAVEFORMATEXTENSIBLE& dest, const WAVEFORMATEX* const src) throw()
  211370. {
  211371. memcpy (&dest, src, src->wFormatTag == WAVE_FORMAT_EXTENSIBLE ? sizeof (WAVEFORMATEXTENSIBLE)
  211372. : sizeof (WAVEFORMATEX));
  211373. }
  211374. class WASAPIDeviceBase
  211375. {
  211376. public:
  211377. WASAPIDeviceBase (const ComSmartPtr <IMMDevice>& device_, const bool useExclusiveMode_)
  211378. : device (device_),
  211379. sampleRate (0),
  211380. numChannels (0),
  211381. actualNumChannels (0),
  211382. defaultSampleRate (0),
  211383. minBufferSize (0),
  211384. defaultBufferSize (0),
  211385. latencySamples (0),
  211386. useExclusiveMode (useExclusiveMode_)
  211387. {
  211388. clientEvent = CreateEvent (0, false, false, _T("JuceWASAPI"));
  211389. ComSmartPtr <IAudioClient> tempClient (createClient());
  211390. if (tempClient == 0)
  211391. return;
  211392. REFERENCE_TIME defaultPeriod, minPeriod;
  211393. if (! OK (tempClient->GetDevicePeriod (&defaultPeriod, &minPeriod)))
  211394. return;
  211395. WAVEFORMATEX* mixFormat = 0;
  211396. if (! OK (tempClient->GetMixFormat (&mixFormat)))
  211397. return;
  211398. WAVEFORMATEXTENSIBLE format;
  211399. wasapi_copyWavFormat (format, mixFormat);
  211400. CoTaskMemFree (mixFormat);
  211401. actualNumChannels = numChannels = format.Format.nChannels;
  211402. defaultSampleRate = format.Format.nSamplesPerSec;
  211403. minBufferSize = wasapi_refTimeToSamples (minPeriod, defaultSampleRate);
  211404. defaultBufferSize = wasapi_refTimeToSamples (defaultPeriod, defaultSampleRate);
  211405. rates.addUsingDefaultSort (defaultSampleRate);
  211406. static const double ratesToTest[] = { 44100.0, 48000.0, 88200.0, 96000.0 };
  211407. for (int i = 0; i < numElementsInArray (ratesToTest); ++i)
  211408. {
  211409. if (ratesToTest[i] == defaultSampleRate)
  211410. continue;
  211411. format.Format.nSamplesPerSec = roundDoubleToInt (ratesToTest[i]);
  211412. if (SUCCEEDED (tempClient->IsFormatSupported (useExclusiveMode ? AUDCLNT_SHAREMODE_EXCLUSIVE : AUDCLNT_SHAREMODE_SHARED,
  211413. (WAVEFORMATEX*) &format, 0)))
  211414. if (! rates.contains (ratesToTest[i]))
  211415. rates.addUsingDefaultSort (ratesToTest[i]);
  211416. }
  211417. }
  211418. ~WASAPIDeviceBase()
  211419. {
  211420. device = 0;
  211421. CloseHandle (clientEvent);
  211422. }
  211423. bool isOk() const throw() { return defaultBufferSize > 0 && defaultSampleRate > 0; }
  211424. bool openClient (const double newSampleRate, const BigInteger& newChannels)
  211425. {
  211426. sampleRate = newSampleRate;
  211427. channels = newChannels;
  211428. channels.setRange (actualNumChannels, channels.getHighestBit() + 1 - actualNumChannels, false);
  211429. numChannels = channels.getHighestBit() + 1;
  211430. if (numChannels == 0)
  211431. return true;
  211432. client = createClient();
  211433. if (client != 0
  211434. && (tryInitialisingWithFormat (true, 4) || tryInitialisingWithFormat (false, 4)
  211435. || tryInitialisingWithFormat (false, 3) || tryInitialisingWithFormat (false, 2)))
  211436. {
  211437. channelMaps.clear();
  211438. for (int i = 0; i <= channels.getHighestBit(); ++i)
  211439. if (channels[i])
  211440. channelMaps.add (i);
  211441. REFERENCE_TIME latency;
  211442. if (OK (client->GetStreamLatency (&latency)))
  211443. latencySamples = wasapi_refTimeToSamples (latency, sampleRate);
  211444. (void) OK (client->GetBufferSize (&actualBufferSize));
  211445. return OK (client->SetEventHandle (clientEvent));
  211446. }
  211447. return false;
  211448. }
  211449. void closeClient()
  211450. {
  211451. if (client != 0)
  211452. client->Stop();
  211453. client = 0;
  211454. ResetEvent (clientEvent);
  211455. }
  211456. ComSmartPtr <IMMDevice> device;
  211457. ComSmartPtr <IAudioClient> client;
  211458. double sampleRate, defaultSampleRate;
  211459. int numChannels, actualNumChannels;
  211460. int minBufferSize, defaultBufferSize, latencySamples;
  211461. const bool useExclusiveMode;
  211462. Array <double> rates;
  211463. HANDLE clientEvent;
  211464. BigInteger channels;
  211465. AudioDataConverters::DataFormat dataFormat;
  211466. Array <int> channelMaps;
  211467. UINT32 actualBufferSize;
  211468. int bytesPerSample;
  211469. private:
  211470. const ComSmartPtr <IAudioClient> createClient()
  211471. {
  211472. ComSmartPtr <IAudioClient> client;
  211473. if (device != 0)
  211474. {
  211475. HRESULT hr = device->Activate (__uuidof (IAudioClient), CLSCTX_INPROC_SERVER, 0, (void**) &client);
  211476. logFailure (hr);
  211477. }
  211478. return client;
  211479. }
  211480. bool tryInitialisingWithFormat (const bool useFloat, const int bytesPerSampleToTry)
  211481. {
  211482. WAVEFORMATEXTENSIBLE format;
  211483. zerostruct (format);
  211484. if (numChannels <= 2 && bytesPerSampleToTry <= 2)
  211485. {
  211486. format.Format.wFormatTag = WAVE_FORMAT_PCM;
  211487. }
  211488. else
  211489. {
  211490. format.Format.wFormatTag = WAVE_FORMAT_EXTENSIBLE;
  211491. format.Format.cbSize = sizeof (WAVEFORMATEXTENSIBLE) - sizeof (WAVEFORMATEX);
  211492. }
  211493. format.Format.nSamplesPerSec = roundDoubleToInt (sampleRate);
  211494. format.Format.nChannels = (WORD) numChannels;
  211495. format.Format.wBitsPerSample = (WORD) (8 * bytesPerSampleToTry);
  211496. format.Format.nAvgBytesPerSec = (DWORD) (format.Format.nSamplesPerSec * numChannels * bytesPerSampleToTry);
  211497. format.Format.nBlockAlign = (WORD) (numChannels * bytesPerSampleToTry);
  211498. format.SubFormat = useFloat ? KSDATAFORMAT_SUBTYPE_IEEE_FLOAT : KSDATAFORMAT_SUBTYPE_PCM;
  211499. format.Samples.wValidBitsPerSample = format.Format.wBitsPerSample;
  211500. switch (numChannels)
  211501. {
  211502. case 1: format.dwChannelMask = SPEAKER_FRONT_CENTER; break;
  211503. case 2: format.dwChannelMask = SPEAKER_FRONT_LEFT | SPEAKER_FRONT_RIGHT; break;
  211504. case 4: format.dwChannelMask = SPEAKER_FRONT_LEFT | SPEAKER_FRONT_RIGHT | SPEAKER_BACK_LEFT | SPEAKER_BACK_RIGHT; break;
  211505. case 6: format.dwChannelMask = SPEAKER_FRONT_LEFT | SPEAKER_FRONT_RIGHT | SPEAKER_FRONT_CENTER | SPEAKER_LOW_FREQUENCY | SPEAKER_BACK_LEFT | SPEAKER_BACK_RIGHT; break;
  211506. 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;
  211507. default: break;
  211508. }
  211509. WAVEFORMATEXTENSIBLE* nearestFormat = 0;
  211510. HRESULT hr = client->IsFormatSupported (useExclusiveMode ? AUDCLNT_SHAREMODE_EXCLUSIVE : AUDCLNT_SHAREMODE_SHARED,
  211511. (WAVEFORMATEX*) &format, useExclusiveMode ? 0 : (WAVEFORMATEX**) &nearestFormat);
  211512. logFailure (hr);
  211513. if (hr == S_FALSE && format.Format.nSamplesPerSec == nearestFormat->Format.nSamplesPerSec)
  211514. {
  211515. wasapi_copyWavFormat (format, (WAVEFORMATEX*) nearestFormat);
  211516. hr = S_OK;
  211517. }
  211518. CoTaskMemFree (nearestFormat);
  211519. REFERENCE_TIME defaultPeriod = 0, minPeriod = 0;
  211520. if (useExclusiveMode)
  211521. OK (client->GetDevicePeriod (&defaultPeriod, &minPeriod));
  211522. GUID session;
  211523. if (hr == S_OK
  211524. && OK (client->Initialize (useExclusiveMode ? AUDCLNT_SHAREMODE_EXCLUSIVE : AUDCLNT_SHAREMODE_SHARED,
  211525. AUDCLNT_STREAMFLAGS_EVENTCALLBACK,
  211526. defaultPeriod, defaultPeriod, (WAVEFORMATEX*) &format, &session)))
  211527. {
  211528. actualNumChannels = format.Format.nChannels;
  211529. const bool isFloat = format.Format.wFormatTag == WAVE_FORMAT_EXTENSIBLE && format.SubFormat == KSDATAFORMAT_SUBTYPE_IEEE_FLOAT;
  211530. bytesPerSample = format.Format.wBitsPerSample / 8;
  211531. dataFormat = isFloat ? AudioDataConverters::float32LE
  211532. : (bytesPerSample == 4 ? AudioDataConverters::int32LE
  211533. : ((bytesPerSample == 3 ? AudioDataConverters::int24LE
  211534. : AudioDataConverters::int16LE)));
  211535. return true;
  211536. }
  211537. return false;
  211538. }
  211539. WASAPIDeviceBase (const WASAPIDeviceBase&);
  211540. WASAPIDeviceBase& operator= (const WASAPIDeviceBase&);
  211541. };
  211542. class WASAPIInputDevice : public WASAPIDeviceBase
  211543. {
  211544. public:
  211545. WASAPIInputDevice (const ComSmartPtr <IMMDevice>& device_, const bool useExclusiveMode_)
  211546. : WASAPIDeviceBase (device_, useExclusiveMode_),
  211547. reservoir (1, 1)
  211548. {
  211549. }
  211550. ~WASAPIInputDevice()
  211551. {
  211552. close();
  211553. }
  211554. bool open (const double newSampleRate, const BigInteger& newChannels)
  211555. {
  211556. reservoirSize = 0;
  211557. reservoirCapacity = 16384;
  211558. reservoir.setSize (actualNumChannels * reservoirCapacity * sizeof (float));
  211559. return openClient (newSampleRate, newChannels)
  211560. && (numChannels == 0 || OK (client->GetService (__uuidof (IAudioCaptureClient), (void**) &captureClient)));
  211561. }
  211562. void close()
  211563. {
  211564. closeClient();
  211565. captureClient = 0;
  211566. reservoir.setSize (0);
  211567. }
  211568. void copyBuffers (float** destBuffers, int numDestBuffers, int bufferSize, Thread& thread)
  211569. {
  211570. if (numChannels <= 0)
  211571. return;
  211572. int offset = 0;
  211573. while (bufferSize > 0)
  211574. {
  211575. if (reservoirSize > 0) // There's stuff in the reservoir, so use that...
  211576. {
  211577. const int samplesToDo = jmin (bufferSize, (int) reservoirSize);
  211578. for (int i = 0; i < numDestBuffers; ++i)
  211579. {
  211580. float* const dest = destBuffers[i] + offset;
  211581. const int srcChan = channelMaps.getUnchecked(i);
  211582. switch (dataFormat)
  211583. {
  211584. case AudioDataConverters::float32LE:
  211585. AudioDataConverters::convertFloat32LEToFloat (((uint8*) reservoir.getData()) + 4 * srcChan, dest, samplesToDo, 4 * actualNumChannels);
  211586. break;
  211587. case AudioDataConverters::int32LE:
  211588. AudioDataConverters::convertInt32LEToFloat (((uint8*) reservoir.getData()) + 4 * srcChan, dest, samplesToDo, 4 * actualNumChannels);
  211589. break;
  211590. case AudioDataConverters::int24LE:
  211591. AudioDataConverters::convertInt24LEToFloat (((uint8*) reservoir.getData()) + 3 * srcChan, dest, samplesToDo, 3 * actualNumChannels);
  211592. break;
  211593. case AudioDataConverters::int16LE:
  211594. AudioDataConverters::convertInt16LEToFloat (((uint8*) reservoir.getData()) + 2 * srcChan, dest, samplesToDo, 2 * actualNumChannels);
  211595. break;
  211596. default: jassertfalse; break;
  211597. }
  211598. }
  211599. bufferSize -= samplesToDo;
  211600. offset += samplesToDo;
  211601. reservoirSize -= samplesToDo;
  211602. }
  211603. else
  211604. {
  211605. UINT32 packetLength = 0;
  211606. if (! OK (captureClient->GetNextPacketSize (&packetLength)))
  211607. break;
  211608. if (packetLength == 0)
  211609. {
  211610. if (thread.threadShouldExit())
  211611. break;
  211612. Thread::sleep (1);
  211613. continue;
  211614. }
  211615. uint8* inputData = 0;
  211616. UINT32 numSamplesAvailable;
  211617. DWORD flags;
  211618. if (OK (captureClient->GetBuffer (&inputData, &numSamplesAvailable, &flags, 0, 0)))
  211619. {
  211620. const int samplesToDo = jmin (bufferSize, (int) numSamplesAvailable);
  211621. for (int i = 0; i < numDestBuffers; ++i)
  211622. {
  211623. float* const dest = destBuffers[i] + offset;
  211624. const int srcChan = channelMaps.getUnchecked(i);
  211625. switch (dataFormat)
  211626. {
  211627. case AudioDataConverters::float32LE:
  211628. AudioDataConverters::convertFloat32LEToFloat (inputData + 4 * srcChan, dest, samplesToDo, 4 * actualNumChannels);
  211629. break;
  211630. case AudioDataConverters::int32LE:
  211631. AudioDataConverters::convertInt32LEToFloat (inputData + 4 * srcChan, dest, samplesToDo, 4 * actualNumChannels);
  211632. break;
  211633. case AudioDataConverters::int24LE:
  211634. AudioDataConverters::convertInt24LEToFloat (inputData + 3 * srcChan, dest, samplesToDo, 3 * actualNumChannels);
  211635. break;
  211636. case AudioDataConverters::int16LE:
  211637. AudioDataConverters::convertInt16LEToFloat (inputData + 2 * srcChan, dest, samplesToDo, 2 * actualNumChannels);
  211638. break;
  211639. default: jassertfalse; break;
  211640. }
  211641. }
  211642. bufferSize -= samplesToDo;
  211643. offset += samplesToDo;
  211644. if (samplesToDo < (int) numSamplesAvailable)
  211645. {
  211646. reservoirSize = jmin ((int) (numSamplesAvailable - samplesToDo), reservoirCapacity);
  211647. memcpy ((uint8*) reservoir.getData(), inputData + bytesPerSample * actualNumChannels * samplesToDo,
  211648. bytesPerSample * actualNumChannels * reservoirSize);
  211649. }
  211650. captureClient->ReleaseBuffer (numSamplesAvailable);
  211651. }
  211652. }
  211653. }
  211654. }
  211655. ComSmartPtr <IAudioCaptureClient> captureClient;
  211656. MemoryBlock reservoir;
  211657. int reservoirSize, reservoirCapacity;
  211658. private:
  211659. WASAPIInputDevice (const WASAPIInputDevice&);
  211660. WASAPIInputDevice& operator= (const WASAPIInputDevice&);
  211661. };
  211662. class WASAPIOutputDevice : public WASAPIDeviceBase
  211663. {
  211664. public:
  211665. WASAPIOutputDevice (const ComSmartPtr <IMMDevice>& device_, const bool useExclusiveMode_)
  211666. : WASAPIDeviceBase (device_, useExclusiveMode_)
  211667. {
  211668. }
  211669. ~WASAPIOutputDevice()
  211670. {
  211671. close();
  211672. }
  211673. bool open (const double newSampleRate, const BigInteger& newChannels)
  211674. {
  211675. return openClient (newSampleRate, newChannels)
  211676. && (numChannels == 0 || OK (client->GetService (__uuidof (IAudioRenderClient), (void**) &renderClient)));
  211677. }
  211678. void close()
  211679. {
  211680. closeClient();
  211681. renderClient = 0;
  211682. }
  211683. void copyBuffers (const float** const srcBuffers, const int numSrcBuffers, int bufferSize, Thread& thread)
  211684. {
  211685. if (numChannels <= 0)
  211686. return;
  211687. int offset = 0;
  211688. while (bufferSize > 0)
  211689. {
  211690. UINT32 padding = 0;
  211691. if (! OK (client->GetCurrentPadding (&padding)))
  211692. return;
  211693. int samplesToDo = useExclusiveMode ? bufferSize
  211694. : jmin ((int) (actualBufferSize - padding), bufferSize);
  211695. if (samplesToDo <= 0)
  211696. {
  211697. if (thread.threadShouldExit())
  211698. break;
  211699. Thread::sleep (0);
  211700. continue;
  211701. }
  211702. uint8* outputData = 0;
  211703. if (OK (renderClient->GetBuffer (samplesToDo, &outputData)))
  211704. {
  211705. for (int i = 0; i < numSrcBuffers; ++i)
  211706. {
  211707. const float* const source = srcBuffers[i] + offset;
  211708. const int destChan = channelMaps.getUnchecked(i);
  211709. switch (dataFormat)
  211710. {
  211711. case AudioDataConverters::float32LE:
  211712. AudioDataConverters::convertFloatToFloat32LE (source, outputData + 4 * destChan, samplesToDo, 4 * actualNumChannels);
  211713. break;
  211714. case AudioDataConverters::int32LE:
  211715. AudioDataConverters::convertFloatToInt32LE (source, outputData + 4 * destChan, samplesToDo, 4 * actualNumChannels);
  211716. break;
  211717. case AudioDataConverters::int24LE:
  211718. AudioDataConverters::convertFloatToInt24LE (source, outputData + 3 * destChan, samplesToDo, 3 * actualNumChannels);
  211719. break;
  211720. case AudioDataConverters::int16LE:
  211721. AudioDataConverters::convertFloatToInt16LE (source, outputData + 2 * destChan, samplesToDo, 2 * actualNumChannels);
  211722. break;
  211723. default: jassertfalse; break;
  211724. }
  211725. }
  211726. renderClient->ReleaseBuffer (samplesToDo, 0);
  211727. offset += samplesToDo;
  211728. bufferSize -= samplesToDo;
  211729. }
  211730. }
  211731. }
  211732. ComSmartPtr <IAudioRenderClient> renderClient;
  211733. private:
  211734. WASAPIOutputDevice (const WASAPIOutputDevice&);
  211735. WASAPIOutputDevice& operator= (const WASAPIOutputDevice&);
  211736. };
  211737. class WASAPIAudioIODevice : public AudioIODevice,
  211738. public Thread
  211739. {
  211740. public:
  211741. WASAPIAudioIODevice (const String& deviceName,
  211742. const String& outputDeviceId_,
  211743. const String& inputDeviceId_,
  211744. const bool useExclusiveMode_)
  211745. : AudioIODevice (deviceName, "Windows Audio"),
  211746. Thread ("Juce WASAPI"),
  211747. isOpen_ (false),
  211748. isStarted (false),
  211749. outputDevice (0),
  211750. outputDeviceId (outputDeviceId_),
  211751. inputDevice (0),
  211752. inputDeviceId (inputDeviceId_),
  211753. useExclusiveMode (useExclusiveMode_),
  211754. currentBufferSizeSamples (0),
  211755. currentSampleRate (0),
  211756. callback (0)
  211757. {
  211758. }
  211759. ~WASAPIAudioIODevice()
  211760. {
  211761. close();
  211762. deleteAndZero (inputDevice);
  211763. deleteAndZero (outputDevice);
  211764. }
  211765. bool initialise()
  211766. {
  211767. double defaultSampleRateIn = 0, defaultSampleRateOut = 0;
  211768. int minBufferSizeIn = 0, defaultBufferSizeIn = 0, minBufferSizeOut = 0, defaultBufferSizeOut = 0;
  211769. latencyIn = latencyOut = 0;
  211770. Array <double> ratesIn, ratesOut;
  211771. if (createDevices())
  211772. {
  211773. jassert (inputDevice != 0 || outputDevice != 0);
  211774. if (inputDevice != 0 && outputDevice != 0)
  211775. {
  211776. defaultSampleRate = jmin (inputDevice->defaultSampleRate, outputDevice->defaultSampleRate);
  211777. minBufferSize = jmin (inputDevice->minBufferSize, outputDevice->minBufferSize);
  211778. defaultBufferSize = jmax (inputDevice->defaultBufferSize, outputDevice->defaultBufferSize);
  211779. sampleRates = inputDevice->rates;
  211780. sampleRates.removeValuesNotIn (outputDevice->rates);
  211781. }
  211782. else
  211783. {
  211784. WASAPIDeviceBase* const d = inputDevice != 0 ? (WASAPIDeviceBase*) inputDevice : (WASAPIDeviceBase*) outputDevice;
  211785. defaultSampleRate = d->defaultSampleRate;
  211786. minBufferSize = d->minBufferSize;
  211787. defaultBufferSize = d->defaultBufferSize;
  211788. sampleRates = d->rates;
  211789. }
  211790. bufferSizes.addUsingDefaultSort (defaultBufferSize);
  211791. if (minBufferSize != defaultBufferSize)
  211792. bufferSizes.addUsingDefaultSort (minBufferSize);
  211793. int n = 64;
  211794. for (int i = 0; i < 40; ++i)
  211795. {
  211796. if (n >= minBufferSize && n <= 2048 && ! bufferSizes.contains (n))
  211797. bufferSizes.addUsingDefaultSort (n);
  211798. n += (n < 512) ? 32 : (n < 1024 ? 64 : 128);
  211799. }
  211800. return true;
  211801. }
  211802. return false;
  211803. }
  211804. const StringArray getOutputChannelNames()
  211805. {
  211806. StringArray outChannels;
  211807. if (outputDevice != 0)
  211808. for (int i = 1; i <= outputDevice->actualNumChannels; ++i)
  211809. outChannels.add ("Output channel " + String (i));
  211810. return outChannels;
  211811. }
  211812. const StringArray getInputChannelNames()
  211813. {
  211814. StringArray inChannels;
  211815. if (inputDevice != 0)
  211816. for (int i = 1; i <= inputDevice->actualNumChannels; ++i)
  211817. inChannels.add ("Input channel " + String (i));
  211818. return inChannels;
  211819. }
  211820. int getNumSampleRates() { return sampleRates.size(); }
  211821. double getSampleRate (int index) { return sampleRates [index]; }
  211822. int getNumBufferSizesAvailable() { return bufferSizes.size(); }
  211823. int getBufferSizeSamples (int index) { return bufferSizes [index]; }
  211824. int getDefaultBufferSize() { return defaultBufferSize; }
  211825. int getCurrentBufferSizeSamples() { return currentBufferSizeSamples; }
  211826. double getCurrentSampleRate() { return currentSampleRate; }
  211827. int getCurrentBitDepth() { return 32; }
  211828. int getOutputLatencyInSamples() { return latencyOut; }
  211829. int getInputLatencyInSamples() { return latencyIn; }
  211830. const BigInteger getActiveOutputChannels() const { return outputDevice != 0 ? outputDevice->channels : BigInteger(); }
  211831. const BigInteger getActiveInputChannels() const { return inputDevice != 0 ? inputDevice->channels : BigInteger(); }
  211832. const String getLastError() { return lastError; }
  211833. const String open (const BigInteger& inputChannels, const BigInteger& outputChannels,
  211834. double sampleRate, int bufferSizeSamples)
  211835. {
  211836. close();
  211837. lastError = String::empty;
  211838. if (sampleRates.size() == 0 && inputDevice != 0 && outputDevice != 0)
  211839. {
  211840. lastError = "The input and output devices don't share a common sample rate!";
  211841. return lastError;
  211842. }
  211843. currentBufferSizeSamples = bufferSizeSamples <= 0 ? defaultBufferSize : jmax (bufferSizeSamples, minBufferSize);
  211844. currentSampleRate = sampleRate > 0 ? sampleRate : defaultSampleRate;
  211845. if (inputDevice != 0 && ! inputDevice->open (currentSampleRate, inputChannels))
  211846. {
  211847. lastError = "Couldn't open the input device!";
  211848. return lastError;
  211849. }
  211850. if (outputDevice != 0 && ! outputDevice->open (currentSampleRate, outputChannels))
  211851. {
  211852. close();
  211853. lastError = "Couldn't open the output device!";
  211854. return lastError;
  211855. }
  211856. if (inputDevice != 0)
  211857. ResetEvent (inputDevice->clientEvent);
  211858. if (outputDevice != 0)
  211859. ResetEvent (outputDevice->clientEvent);
  211860. startThread (8);
  211861. Thread::sleep (5);
  211862. if (inputDevice != 0 && inputDevice->client != 0)
  211863. {
  211864. latencyIn = inputDevice->latencySamples + inputDevice->actualBufferSize + inputDevice->minBufferSize;
  211865. HRESULT hr = inputDevice->client->Start();
  211866. logFailure (hr); //xxx handle this
  211867. }
  211868. if (outputDevice != 0 && outputDevice->client != 0)
  211869. {
  211870. latencyOut = outputDevice->latencySamples + outputDevice->actualBufferSize + outputDevice->minBufferSize;
  211871. HRESULT hr = outputDevice->client->Start();
  211872. logFailure (hr); //xxx handle this
  211873. }
  211874. isOpen_ = true;
  211875. return lastError;
  211876. }
  211877. void close()
  211878. {
  211879. stop();
  211880. if (inputDevice != 0)
  211881. SetEvent (inputDevice->clientEvent);
  211882. if (outputDevice != 0)
  211883. SetEvent (outputDevice->clientEvent);
  211884. stopThread (5000);
  211885. if (inputDevice != 0)
  211886. inputDevice->close();
  211887. if (outputDevice != 0)
  211888. outputDevice->close();
  211889. isOpen_ = false;
  211890. }
  211891. bool isOpen() { return isOpen_ && isThreadRunning(); }
  211892. bool isPlaying() { return isStarted && isOpen_ && isThreadRunning(); }
  211893. void start (AudioIODeviceCallback* call)
  211894. {
  211895. if (isOpen_ && call != 0 && ! isStarted)
  211896. {
  211897. if (! isThreadRunning())
  211898. {
  211899. // something's gone wrong and the thread's stopped..
  211900. isOpen_ = false;
  211901. return;
  211902. }
  211903. call->audioDeviceAboutToStart (this);
  211904. const ScopedLock sl (startStopLock);
  211905. callback = call;
  211906. isStarted = true;
  211907. }
  211908. }
  211909. void stop()
  211910. {
  211911. if (isStarted)
  211912. {
  211913. AudioIODeviceCallback* const callbackLocal = callback;
  211914. {
  211915. const ScopedLock sl (startStopLock);
  211916. isStarted = false;
  211917. }
  211918. if (callbackLocal != 0)
  211919. callbackLocal->audioDeviceStopped();
  211920. }
  211921. }
  211922. void setMMThreadPriority()
  211923. {
  211924. DynamicLibraryLoader dll ("avrt.dll");
  211925. DynamicLibraryImport (AvSetMmThreadCharacteristics, avSetMmThreadCharacteristics, HANDLE, dll, (LPCTSTR, LPDWORD))
  211926. DynamicLibraryImport (AvSetMmThreadPriority, avSetMmThreadPriority, HANDLE, dll, (HANDLE, AVRT_PRIORITY))
  211927. if (avSetMmThreadCharacteristics != 0 && avSetMmThreadPriority != 0)
  211928. {
  211929. DWORD dummy = 0;
  211930. HANDLE h = avSetMmThreadCharacteristics (_T("Pro Audio"), &dummy);
  211931. if (h != 0)
  211932. avSetMmThreadPriority (h, AVRT_PRIORITY_NORMAL);
  211933. }
  211934. }
  211935. void run()
  211936. {
  211937. setMMThreadPriority();
  211938. const int bufferSize = currentBufferSizeSamples;
  211939. HANDLE events[2];
  211940. int numEvents = 0;
  211941. if (inputDevice != 0)
  211942. events [numEvents++] = inputDevice->clientEvent;
  211943. if (outputDevice != 0)
  211944. events [numEvents++] = outputDevice->clientEvent;
  211945. const int numInputBuffers = getActiveInputChannels().countNumberOfSetBits();
  211946. const int numOutputBuffers = getActiveOutputChannels().countNumberOfSetBits();
  211947. AudioSampleBuffer ins (jmax (1, numInputBuffers), bufferSize + 32);
  211948. AudioSampleBuffer outs (jmax (1, numOutputBuffers), bufferSize + 32);
  211949. float** const inputBuffers = ins.getArrayOfChannels();
  211950. float** const outputBuffers = outs.getArrayOfChannels();
  211951. ins.clear();
  211952. while (! threadShouldExit())
  211953. {
  211954. const DWORD result = useExclusiveMode ? WaitForSingleObject (inputDevice->clientEvent, 1000)
  211955. : WaitForMultipleObjects (numEvents, events, true, 1000);
  211956. if (result == WAIT_TIMEOUT)
  211957. continue;
  211958. if (threadShouldExit())
  211959. break;
  211960. if (inputDevice != 0)
  211961. inputDevice->copyBuffers (inputBuffers, numInputBuffers, bufferSize, *this);
  211962. // Make the callback..
  211963. {
  211964. const ScopedLock sl (startStopLock);
  211965. if (isStarted)
  211966. {
  211967. JUCE_TRY
  211968. {
  211969. callback->audioDeviceIOCallback ((const float**) inputBuffers,
  211970. numInputBuffers,
  211971. outputBuffers,
  211972. numOutputBuffers,
  211973. bufferSize);
  211974. }
  211975. JUCE_CATCH_EXCEPTION
  211976. }
  211977. else
  211978. {
  211979. outs.clear();
  211980. }
  211981. }
  211982. if (useExclusiveMode && WaitForSingleObject (outputDevice->clientEvent, 1000) == WAIT_TIMEOUT)
  211983. continue;
  211984. if (outputDevice != 0)
  211985. outputDevice->copyBuffers ((const float**) outputBuffers, numOutputBuffers, bufferSize, *this);
  211986. }
  211987. }
  211988. juce_UseDebuggingNewOperator
  211989. String outputDeviceId, inputDeviceId;
  211990. String lastError;
  211991. private:
  211992. // Device stats...
  211993. WASAPIInputDevice* inputDevice;
  211994. WASAPIOutputDevice* outputDevice;
  211995. const bool useExclusiveMode;
  211996. double defaultSampleRate;
  211997. int minBufferSize, defaultBufferSize;
  211998. int latencyIn, latencyOut;
  211999. Array <double> sampleRates;
  212000. Array <int> bufferSizes;
  212001. // Active state...
  212002. bool isOpen_, isStarted;
  212003. int currentBufferSizeSamples;
  212004. double currentSampleRate;
  212005. AudioIODeviceCallback* callback;
  212006. CriticalSection startStopLock;
  212007. bool createDevices()
  212008. {
  212009. ComSmartPtr <IMMDeviceEnumerator> enumerator;
  212010. if (! OK (enumerator.CoCreateInstance (__uuidof (MMDeviceEnumerator))))
  212011. return false;
  212012. ComSmartPtr <IMMDeviceCollection> deviceCollection;
  212013. if (! OK (enumerator->EnumAudioEndpoints (eAll, DEVICE_STATE_ACTIVE, &deviceCollection)))
  212014. return false;
  212015. UINT32 numDevices = 0;
  212016. if (! OK (deviceCollection->GetCount (&numDevices)))
  212017. return false;
  212018. for (UINT32 i = 0; i < numDevices; ++i)
  212019. {
  212020. ComSmartPtr <IMMDevice> device;
  212021. if (! OK (deviceCollection->Item (i, &device)))
  212022. continue;
  212023. const String deviceId (wasapi_getDeviceID (device));
  212024. if (deviceId.isEmpty())
  212025. continue;
  212026. const EDataFlow flow = wasapi_getDataFlow (device);
  212027. if (deviceId == inputDeviceId && flow == eCapture)
  212028. inputDevice = new WASAPIInputDevice (device, useExclusiveMode);
  212029. else if (deviceId == outputDeviceId && flow == eRender)
  212030. outputDevice = new WASAPIOutputDevice (device, useExclusiveMode);
  212031. }
  212032. return (outputDeviceId.isEmpty() || (outputDevice != 0 && outputDevice->isOk()))
  212033. && (inputDeviceId.isEmpty() || (inputDevice != 0 && inputDevice->isOk()));
  212034. }
  212035. WASAPIAudioIODevice (const WASAPIAudioIODevice&);
  212036. WASAPIAudioIODevice& operator= (const WASAPIAudioIODevice&);
  212037. };
  212038. class WASAPIAudioIODeviceType : public AudioIODeviceType
  212039. {
  212040. public:
  212041. WASAPIAudioIODeviceType()
  212042. : AudioIODeviceType ("Windows Audio"),
  212043. hasScanned (false)
  212044. {
  212045. }
  212046. ~WASAPIAudioIODeviceType()
  212047. {
  212048. }
  212049. void scanForDevices()
  212050. {
  212051. hasScanned = true;
  212052. outputDeviceNames.clear();
  212053. inputDeviceNames.clear();
  212054. outputDeviceIds.clear();
  212055. inputDeviceIds.clear();
  212056. ComSmartPtr <IMMDeviceEnumerator> enumerator;
  212057. if (! OK (enumerator.CoCreateInstance (__uuidof (MMDeviceEnumerator))))
  212058. return;
  212059. const String defaultRenderer = getDefaultEndpoint (enumerator, false);
  212060. const String defaultCapture = getDefaultEndpoint (enumerator, true);
  212061. ComSmartPtr <IMMDeviceCollection> deviceCollection;
  212062. UINT32 numDevices = 0;
  212063. if (! (OK (enumerator->EnumAudioEndpoints (eAll, DEVICE_STATE_ACTIVE, &deviceCollection))
  212064. && OK (deviceCollection->GetCount (&numDevices))))
  212065. return;
  212066. for (UINT32 i = 0; i < numDevices; ++i)
  212067. {
  212068. ComSmartPtr <IMMDevice> device;
  212069. if (! OK (deviceCollection->Item (i, &device)))
  212070. continue;
  212071. const String deviceId (wasapi_getDeviceID (device));
  212072. DWORD state = 0;
  212073. if (! OK (device->GetState (&state)))
  212074. continue;
  212075. if (state != DEVICE_STATE_ACTIVE)
  212076. continue;
  212077. String name;
  212078. {
  212079. ComSmartPtr <IPropertyStore> properties;
  212080. if (! OK (device->OpenPropertyStore (STGM_READ, &properties)))
  212081. continue;
  212082. PROPVARIANT value;
  212083. PropVariantInit (&value);
  212084. if (OK (properties->GetValue (PKEY_Device_FriendlyName, &value)))
  212085. name = value.pwszVal;
  212086. PropVariantClear (&value);
  212087. }
  212088. const EDataFlow flow = wasapi_getDataFlow (device);
  212089. if (flow == eRender)
  212090. {
  212091. const int index = (deviceId == defaultRenderer) ? 0 : -1;
  212092. outputDeviceIds.insert (index, deviceId);
  212093. outputDeviceNames.insert (index, name);
  212094. }
  212095. else if (flow == eCapture)
  212096. {
  212097. const int index = (deviceId == defaultCapture) ? 0 : -1;
  212098. inputDeviceIds.insert (index, deviceId);
  212099. inputDeviceNames.insert (index, name);
  212100. }
  212101. }
  212102. inputDeviceNames.appendNumbersToDuplicates (false, false);
  212103. outputDeviceNames.appendNumbersToDuplicates (false, false);
  212104. }
  212105. const StringArray getDeviceNames (bool wantInputNames) const
  212106. {
  212107. jassert (hasScanned); // need to call scanForDevices() before doing this
  212108. return wantInputNames ? inputDeviceNames
  212109. : outputDeviceNames;
  212110. }
  212111. int getDefaultDeviceIndex (bool /*forInput*/) const
  212112. {
  212113. jassert (hasScanned); // need to call scanForDevices() before doing this
  212114. return 0;
  212115. }
  212116. int getIndexOfDevice (AudioIODevice* device, bool asInput) const
  212117. {
  212118. jassert (hasScanned); // need to call scanForDevices() before doing this
  212119. WASAPIAudioIODevice* const d = dynamic_cast <WASAPIAudioIODevice*> (device);
  212120. return d == 0 ? -1 : (asInput ? inputDeviceIds.indexOf (d->inputDeviceId)
  212121. : outputDeviceIds.indexOf (d->outputDeviceId));
  212122. }
  212123. bool hasSeparateInputsAndOutputs() const { return true; }
  212124. AudioIODevice* createDevice (const String& outputDeviceName,
  212125. const String& inputDeviceName)
  212126. {
  212127. jassert (hasScanned); // need to call scanForDevices() before doing this
  212128. const bool useExclusiveMode = false;
  212129. ScopedPointer<WASAPIAudioIODevice> device;
  212130. const int outputIndex = outputDeviceNames.indexOf (outputDeviceName);
  212131. const int inputIndex = inputDeviceNames.indexOf (inputDeviceName);
  212132. if (outputIndex >= 0 || inputIndex >= 0)
  212133. {
  212134. device = new WASAPIAudioIODevice (outputDeviceName.isNotEmpty() ? outputDeviceName
  212135. : inputDeviceName,
  212136. outputDeviceIds [outputIndex],
  212137. inputDeviceIds [inputIndex],
  212138. useExclusiveMode);
  212139. if (! device->initialise())
  212140. device = 0;
  212141. }
  212142. return device.release();
  212143. }
  212144. juce_UseDebuggingNewOperator
  212145. StringArray outputDeviceNames, outputDeviceIds;
  212146. StringArray inputDeviceNames, inputDeviceIds;
  212147. private:
  212148. bool hasScanned;
  212149. static const String getDefaultEndpoint (IMMDeviceEnumerator* const enumerator, const bool forCapture)
  212150. {
  212151. String s;
  212152. IMMDevice* dev = 0;
  212153. if (OK (enumerator->GetDefaultAudioEndpoint (forCapture ? eCapture : eRender,
  212154. eMultimedia, &dev)))
  212155. {
  212156. WCHAR* deviceId = 0;
  212157. if (OK (dev->GetId (&deviceId)))
  212158. {
  212159. s = String (deviceId);
  212160. CoTaskMemFree (deviceId);
  212161. }
  212162. dev->Release();
  212163. }
  212164. return s;
  212165. }
  212166. WASAPIAudioIODeviceType (const WASAPIAudioIODeviceType&);
  212167. WASAPIAudioIODeviceType& operator= (const WASAPIAudioIODeviceType&);
  212168. };
  212169. AudioIODeviceType* juce_createAudioIODeviceType_WASAPI()
  212170. {
  212171. return new WASAPIAudioIODeviceType();
  212172. }
  212173. #undef logFailure
  212174. #undef OK
  212175. #endif
  212176. /*** End of inlined file: juce_win32_WASAPI.cpp ***/
  212177. /*** Start of inlined file: juce_win32_CameraDevice.cpp ***/
  212178. // (This file gets included by juce_win32_NativeCode.cpp, rather than being
  212179. // compiled on its own).
  212180. #if JUCE_INCLUDED_FILE && JUCE_USE_CAMERA
  212181. class DShowCameraDeviceInteral : public ChangeBroadcaster
  212182. {
  212183. public:
  212184. DShowCameraDeviceInteral (CameraDevice* const owner_,
  212185. const ComSmartPtr <ICaptureGraphBuilder2>& captureGraphBuilder_,
  212186. const ComSmartPtr <IBaseFilter>& filter_,
  212187. int minWidth, int minHeight,
  212188. int maxWidth, int maxHeight)
  212189. : owner (owner_),
  212190. captureGraphBuilder (captureGraphBuilder_),
  212191. filter (filter_),
  212192. ok (false),
  212193. imageNeedsFlipping (false),
  212194. width (0),
  212195. height (0),
  212196. activeUsers (0),
  212197. recordNextFrameTime (false),
  212198. activeImage (0),
  212199. loadingImage (0)
  212200. {
  212201. HRESULT hr = graphBuilder.CoCreateInstance (CLSID_FilterGraph);
  212202. if (FAILED (hr))
  212203. return;
  212204. hr = captureGraphBuilder->SetFiltergraph (graphBuilder);
  212205. if (FAILED (hr))
  212206. return;
  212207. hr = graphBuilder->QueryInterface (IID_IMediaControl, (void**) &mediaControl);
  212208. if (FAILED (hr))
  212209. return;
  212210. {
  212211. ComSmartPtr <IAMStreamConfig> streamConfig;
  212212. hr = captureGraphBuilder->FindInterface (&PIN_CATEGORY_CAPTURE, 0, filter,
  212213. IID_IAMStreamConfig, (void**) &streamConfig);
  212214. if (streamConfig != 0)
  212215. {
  212216. getVideoSizes (streamConfig);
  212217. if (! selectVideoSize (streamConfig, minWidth, minHeight, maxWidth, maxHeight))
  212218. return;
  212219. }
  212220. }
  212221. hr = graphBuilder->AddFilter (filter, _T("Video Capture"));
  212222. if (FAILED (hr))
  212223. return;
  212224. hr = smartTee.CoCreateInstance (CLSID_SmartTee);
  212225. if (FAILED (hr))
  212226. return;
  212227. hr = graphBuilder->AddFilter (smartTee, _T("Smart Tee"));
  212228. if (FAILED (hr))
  212229. return;
  212230. if (! connectFilters (filter, smartTee))
  212231. return;
  212232. ComSmartPtr <IBaseFilter> sampleGrabberBase;
  212233. hr = sampleGrabberBase.CoCreateInstance (CLSID_SampleGrabber);
  212234. if (FAILED (hr))
  212235. return;
  212236. hr = sampleGrabberBase->QueryInterface (IID_ISampleGrabber, (void**) &sampleGrabber);
  212237. if (FAILED (hr))
  212238. return;
  212239. AM_MEDIA_TYPE mt;
  212240. zerostruct (mt);
  212241. mt.majortype = MEDIATYPE_Video;
  212242. mt.subtype = MEDIASUBTYPE_RGB24;
  212243. mt.formattype = FORMAT_VideoInfo;
  212244. sampleGrabber->SetMediaType (&mt);
  212245. callback = new GrabberCallback (*this);
  212246. sampleGrabber->SetCallback (callback, 1);
  212247. hr = graphBuilder->AddFilter (sampleGrabberBase, _T("Sample Grabber"));
  212248. if (FAILED (hr))
  212249. return;
  212250. ComSmartPtr <IPin> grabberInputPin;
  212251. if (! (getPin (smartTee, PINDIR_OUTPUT, &smartTeeCaptureOutputPin, "capture")
  212252. && getPin (smartTee, PINDIR_OUTPUT, &smartTeePreviewOutputPin, "preview")
  212253. && getPin (sampleGrabberBase, PINDIR_INPUT, &grabberInputPin)))
  212254. return;
  212255. hr = graphBuilder->Connect (smartTeePreviewOutputPin, grabberInputPin);
  212256. if (FAILED (hr))
  212257. return;
  212258. zerostruct (mt);
  212259. hr = sampleGrabber->GetConnectedMediaType (&mt);
  212260. VIDEOINFOHEADER* pVih = (VIDEOINFOHEADER*) (mt.pbFormat);
  212261. width = pVih->bmiHeader.biWidth;
  212262. height = pVih->bmiHeader.biHeight;
  212263. ComSmartPtr <IBaseFilter> nullFilter;
  212264. hr = nullFilter.CoCreateInstance (CLSID_NullRenderer);
  212265. hr = graphBuilder->AddFilter (nullFilter, _T("Null Renderer"));
  212266. if (connectFilters (sampleGrabberBase, nullFilter)
  212267. && addGraphToRot())
  212268. {
  212269. activeImage = new Image (Image::RGB, width, height, true);
  212270. loadingImage = new Image (Image::RGB, width, height, true);
  212271. ok = true;
  212272. }
  212273. }
  212274. ~DShowCameraDeviceInteral()
  212275. {
  212276. if (mediaControl != 0)
  212277. mediaControl->Stop();
  212278. removeGraphFromRot();
  212279. for (int i = viewerComps.size(); --i >= 0;)
  212280. ((DShowCaptureViewerComp*) viewerComps.getUnchecked(i))->ownerDeleted();
  212281. callback = 0;
  212282. graphBuilder = 0;
  212283. sampleGrabber = 0;
  212284. mediaControl = 0;
  212285. filter = 0;
  212286. captureGraphBuilder = 0;
  212287. smartTee = 0;
  212288. smartTeePreviewOutputPin = 0;
  212289. smartTeeCaptureOutputPin = 0;
  212290. asfWriter = 0;
  212291. delete activeImage;
  212292. delete loadingImage;
  212293. }
  212294. void addUser()
  212295. {
  212296. if (ok && activeUsers++ == 0)
  212297. mediaControl->Run();
  212298. }
  212299. void removeUser()
  212300. {
  212301. if (ok && --activeUsers == 0)
  212302. mediaControl->Stop();
  212303. }
  212304. void handleFrame (double /*time*/, BYTE* buffer, long /*bufferSize*/)
  212305. {
  212306. if (recordNextFrameTime)
  212307. {
  212308. const double defaultCameraLatency = 0.1;
  212309. firstRecordedTime = Time::getCurrentTime() - RelativeTime (defaultCameraLatency);
  212310. recordNextFrameTime = false;
  212311. ComSmartPtr <IPin> pin;
  212312. if (getPin (filter, PINDIR_OUTPUT, &pin))
  212313. {
  212314. ComSmartPtr <IAMPushSource> pushSource;
  212315. HRESULT hr = pin->QueryInterface (IID_IAMPushSource, (void**) &pushSource);
  212316. if (pushSource != 0)
  212317. {
  212318. REFERENCE_TIME latency = 0;
  212319. hr = pushSource->GetLatency (&latency);
  212320. firstRecordedTime = firstRecordedTime - RelativeTime ((double) latency);
  212321. }
  212322. }
  212323. }
  212324. {
  212325. const int lineStride = width * 3;
  212326. const ScopedLock sl (imageSwapLock);
  212327. {
  212328. const Image::BitmapData destData (*loadingImage, 0, 0, width, height, true);
  212329. for (int i = 0; i < height; ++i)
  212330. memcpy (destData.getLinePointer ((height - 1) - i),
  212331. buffer + lineStride * i,
  212332. lineStride);
  212333. }
  212334. imageNeedsFlipping = true;
  212335. }
  212336. if (listeners.size() > 0)
  212337. callListeners (*loadingImage);
  212338. sendChangeMessage (this);
  212339. }
  212340. void drawCurrentImage (Graphics& g, int x, int y, int w, int h)
  212341. {
  212342. if (imageNeedsFlipping)
  212343. {
  212344. const ScopedLock sl (imageSwapLock);
  212345. swapVariables (loadingImage, activeImage);
  212346. imageNeedsFlipping = false;
  212347. }
  212348. RectanglePlacement rp (RectanglePlacement::centred);
  212349. double dx = 0, dy = 0, dw = width, dh = height;
  212350. rp.applyTo (dx, dy, dw, dh, x, y, w, h);
  212351. const int rx = roundToInt (dx), ry = roundToInt (dy);
  212352. const int rw = roundToInt (dw), rh = roundToInt (dh);
  212353. g.saveState();
  212354. g.excludeClipRegion (Rectangle<int> (rx, ry, rw, rh));
  212355. g.fillAll (Colours::black);
  212356. g.restoreState();
  212357. g.drawImage (activeImage, rx, ry, rw, rh, 0, 0, width, height);
  212358. }
  212359. bool createFileCaptureFilter (const File& file)
  212360. {
  212361. removeFileCaptureFilter();
  212362. file.deleteFile();
  212363. mediaControl->Stop();
  212364. firstRecordedTime = Time();
  212365. recordNextFrameTime = true;
  212366. HRESULT hr = asfWriter.CoCreateInstance (CLSID_WMAsfWriter);
  212367. if (SUCCEEDED (hr))
  212368. {
  212369. ComSmartPtr <IFileSinkFilter> fileSink;
  212370. hr = asfWriter->QueryInterface (IID_IFileSinkFilter, (void**) &fileSink);
  212371. if (SUCCEEDED (hr))
  212372. {
  212373. hr = fileSink->SetFileName (file.getFullPathName(), 0);
  212374. if (SUCCEEDED (hr))
  212375. {
  212376. hr = graphBuilder->AddFilter (asfWriter, _T("AsfWriter"));
  212377. if (SUCCEEDED (hr))
  212378. {
  212379. ComSmartPtr <IConfigAsfWriter> asfConfig;
  212380. hr = asfWriter->QueryInterface (IID_IConfigAsfWriter, (void**) &asfConfig);
  212381. asfConfig->SetIndexMode (true);
  212382. ComSmartPtr <IWMProfileManager> profileManager;
  212383. hr = WMCreateProfileManager (&profileManager);
  212384. // This gibberish is the DirectShow profile for a video-only wmv file.
  212385. String prof ("<profile version=\"589824\" storageformat=\"1\" name=\"Quality\" description=\"Quality type for output.\"><streamconfig "
  212386. "majortype=\"{73646976-0000-0010-8000-00AA00389B71}\" streamnumber=\"1\" streamname=\"Video Stream\" inputname=\"Video409\" bitrate=\"894960\" "
  212387. "bufferwindow=\"0\" reliabletransport=\"1\" decodercomplexity=\"AU\" rfc1766langid=\"en-us\"><videomediaprops maxkeyframespacing=\"50000000\" quality=\"90\"/>"
  212388. "<wmmediatype subtype=\"{33564D57-0000-0010-8000-00AA00389B71}\" bfixedsizesamples=\"0\" btemporalcompression=\"1\" lsamplesize=\"0\"> <videoinfoheader "
  212389. "dwbitrate=\"894960\" dwbiterrorrate=\"0\" avgtimeperframe=\"100000\"><rcsource left=\"0\" top=\"0\" right=\"$WIDTH\" bottom=\"$HEIGHT\"/> <rctarget "
  212390. "left=\"0\" top=\"0\" right=\"$WIDTH\" bottom=\"$HEIGHT\"/> <bitmapinfoheader biwidth=\"$WIDTH\" biheight=\"$HEIGHT\" biplanes=\"1\" bibitcount=\"24\" "
  212391. "bicompression=\"WMV3\" bisizeimage=\"0\" bixpelspermeter=\"0\" biypelspermeter=\"0\" biclrused=\"0\" biclrimportant=\"0\"/> "
  212392. "</videoinfoheader></wmmediatype></streamconfig></profile>");
  212393. prof = prof.replace ("$WIDTH", String (width))
  212394. .replace ("$HEIGHT", String (height));
  212395. ComSmartPtr <IWMProfile> currentProfile;
  212396. hr = profileManager->LoadProfileByData ((const WCHAR*) prof, &currentProfile);
  212397. hr = asfConfig->ConfigureFilterUsingProfile (currentProfile);
  212398. if (SUCCEEDED (hr))
  212399. {
  212400. ComSmartPtr <IPin> asfWriterInputPin;
  212401. if (getPin (asfWriter, PINDIR_INPUT, &asfWriterInputPin, "Video Input 01"))
  212402. {
  212403. hr = graphBuilder->Connect (smartTeeCaptureOutputPin, asfWriterInputPin);
  212404. if (SUCCEEDED (hr)
  212405. && ok && activeUsers > 0
  212406. && SUCCEEDED (mediaControl->Run()))
  212407. {
  212408. return true;
  212409. }
  212410. }
  212411. }
  212412. }
  212413. }
  212414. }
  212415. }
  212416. removeFileCaptureFilter();
  212417. if (ok && activeUsers > 0)
  212418. mediaControl->Run();
  212419. return false;
  212420. }
  212421. void removeFileCaptureFilter()
  212422. {
  212423. mediaControl->Stop();
  212424. if (asfWriter != 0)
  212425. {
  212426. graphBuilder->RemoveFilter (asfWriter);
  212427. asfWriter = 0;
  212428. }
  212429. if (ok && activeUsers > 0)
  212430. mediaControl->Run();
  212431. }
  212432. void addListener (CameraImageListener* listenerToAdd)
  212433. {
  212434. const ScopedLock sl (listenerLock);
  212435. if (listeners.size() == 0)
  212436. addUser();
  212437. listeners.addIfNotAlreadyThere (listenerToAdd);
  212438. }
  212439. void removeListener (CameraImageListener* listenerToRemove)
  212440. {
  212441. const ScopedLock sl (listenerLock);
  212442. listeners.removeValue (listenerToRemove);
  212443. if (listeners.size() == 0)
  212444. removeUser();
  212445. }
  212446. void callListeners (Image& image)
  212447. {
  212448. const ScopedLock sl (listenerLock);
  212449. for (int i = listeners.size(); --i >= 0;)
  212450. {
  212451. CameraImageListener* l = (CameraImageListener*) listeners[i];
  212452. if (l != 0)
  212453. l->imageReceived (image);
  212454. }
  212455. }
  212456. class DShowCaptureViewerComp : public Component,
  212457. public ChangeListener
  212458. {
  212459. public:
  212460. DShowCaptureViewerComp (DShowCameraDeviceInteral* const owner_)
  212461. : owner (owner_)
  212462. {
  212463. setOpaque (true);
  212464. owner->addChangeListener (this);
  212465. owner->addUser();
  212466. owner->viewerComps.add (this);
  212467. setSize (owner_->width, owner_->height);
  212468. }
  212469. ~DShowCaptureViewerComp()
  212470. {
  212471. if (owner != 0)
  212472. {
  212473. owner->viewerComps.removeValue (this);
  212474. owner->removeUser();
  212475. owner->removeChangeListener (this);
  212476. }
  212477. }
  212478. void ownerDeleted()
  212479. {
  212480. owner = 0;
  212481. }
  212482. void paint (Graphics& g)
  212483. {
  212484. g.setColour (Colours::black);
  212485. g.setImageResamplingQuality (Graphics::lowResamplingQuality);
  212486. if (owner != 0)
  212487. owner->drawCurrentImage (g, 0, 0, getWidth(), getHeight());
  212488. else
  212489. g.fillAll (Colours::black);
  212490. }
  212491. void changeListenerCallback (void*)
  212492. {
  212493. repaint();
  212494. }
  212495. private:
  212496. DShowCameraDeviceInteral* owner;
  212497. };
  212498. bool ok;
  212499. int width, height;
  212500. Time firstRecordedTime;
  212501. VoidArray viewerComps;
  212502. private:
  212503. CameraDevice* const owner;
  212504. ComSmartPtr <ICaptureGraphBuilder2> captureGraphBuilder;
  212505. ComSmartPtr <IBaseFilter> filter;
  212506. ComSmartPtr <IBaseFilter> smartTee;
  212507. ComSmartPtr <IGraphBuilder> graphBuilder;
  212508. ComSmartPtr <ISampleGrabber> sampleGrabber;
  212509. ComSmartPtr <IMediaControl> mediaControl;
  212510. ComSmartPtr <IPin> smartTeePreviewOutputPin;
  212511. ComSmartPtr <IPin> smartTeeCaptureOutputPin;
  212512. ComSmartPtr <IBaseFilter> asfWriter;
  212513. int activeUsers;
  212514. Array <int> widths, heights;
  212515. DWORD graphRegistrationID;
  212516. CriticalSection imageSwapLock;
  212517. bool imageNeedsFlipping;
  212518. Image* loadingImage;
  212519. Image* activeImage;
  212520. bool recordNextFrameTime;
  212521. void getVideoSizes (IAMStreamConfig* const streamConfig)
  212522. {
  212523. widths.clear();
  212524. heights.clear();
  212525. int count = 0, size = 0;
  212526. streamConfig->GetNumberOfCapabilities (&count, &size);
  212527. if (size == sizeof (VIDEO_STREAM_CONFIG_CAPS))
  212528. {
  212529. for (int i = 0; i < count; ++i)
  212530. {
  212531. VIDEO_STREAM_CONFIG_CAPS scc;
  212532. AM_MEDIA_TYPE* config;
  212533. HRESULT hr = streamConfig->GetStreamCaps (i, &config, (BYTE*) &scc);
  212534. if (SUCCEEDED (hr))
  212535. {
  212536. const int w = scc.InputSize.cx;
  212537. const int h = scc.InputSize.cy;
  212538. bool duplicate = false;
  212539. for (int j = widths.size(); --j >= 0;)
  212540. {
  212541. if (w == widths.getUnchecked (j) && h == heights.getUnchecked (j))
  212542. {
  212543. duplicate = true;
  212544. break;
  212545. }
  212546. }
  212547. if (! duplicate)
  212548. {
  212549. DBG ("Camera capture size: " + String (w) + ", " + String (h));
  212550. widths.add (w);
  212551. heights.add (h);
  212552. }
  212553. deleteMediaType (config);
  212554. }
  212555. }
  212556. }
  212557. }
  212558. bool selectVideoSize (IAMStreamConfig* const streamConfig,
  212559. const int minWidth, const int minHeight,
  212560. const int maxWidth, const int maxHeight)
  212561. {
  212562. int count = 0, size = 0, bestArea = 0, bestIndex = -1;
  212563. streamConfig->GetNumberOfCapabilities (&count, &size);
  212564. if (size == sizeof (VIDEO_STREAM_CONFIG_CAPS))
  212565. {
  212566. AM_MEDIA_TYPE* config;
  212567. VIDEO_STREAM_CONFIG_CAPS scc;
  212568. for (int i = 0; i < count; ++i)
  212569. {
  212570. HRESULT hr = streamConfig->GetStreamCaps (i, &config, (BYTE*) &scc);
  212571. if (SUCCEEDED (hr))
  212572. {
  212573. if (scc.InputSize.cx >= minWidth
  212574. && scc.InputSize.cy >= minHeight
  212575. && scc.InputSize.cx <= maxWidth
  212576. && scc.InputSize.cy <= maxHeight)
  212577. {
  212578. int area = scc.InputSize.cx * scc.InputSize.cy;
  212579. if (area > bestArea)
  212580. {
  212581. bestIndex = i;
  212582. bestArea = area;
  212583. }
  212584. }
  212585. deleteMediaType (config);
  212586. }
  212587. }
  212588. if (bestIndex >= 0)
  212589. {
  212590. HRESULT hr = streamConfig->GetStreamCaps (bestIndex, &config, (BYTE*) &scc);
  212591. hr = streamConfig->SetFormat (config);
  212592. deleteMediaType (config);
  212593. return SUCCEEDED (hr);
  212594. }
  212595. }
  212596. return false;
  212597. }
  212598. static bool getPin (IBaseFilter* filter, const PIN_DIRECTION wantedDirection, IPin** result, const char* pinName = 0)
  212599. {
  212600. ComSmartPtr <IEnumPins> enumerator;
  212601. ComSmartPtr <IPin> pin;
  212602. filter->EnumPins (&enumerator);
  212603. while (enumerator->Next (1, &pin, 0) == S_OK)
  212604. {
  212605. PIN_DIRECTION dir;
  212606. pin->QueryDirection (&dir);
  212607. if (wantedDirection == dir)
  212608. {
  212609. PIN_INFO info;
  212610. zerostruct (info);
  212611. pin->QueryPinInfo (&info);
  212612. if (pinName == 0 || String (pinName).equalsIgnoreCase (String (info.achName)))
  212613. {
  212614. pin->AddRef();
  212615. *result = pin;
  212616. return true;
  212617. }
  212618. }
  212619. }
  212620. return false;
  212621. }
  212622. bool connectFilters (IBaseFilter* const first, IBaseFilter* const second) const
  212623. {
  212624. ComSmartPtr <IPin> in, out;
  212625. return getPin (first, PINDIR_OUTPUT, &out)
  212626. && getPin (second, PINDIR_INPUT, &in)
  212627. && SUCCEEDED (graphBuilder->Connect (out, in));
  212628. }
  212629. bool addGraphToRot()
  212630. {
  212631. ComSmartPtr <IRunningObjectTable> rot;
  212632. if (FAILED (GetRunningObjectTable (0, &rot)))
  212633. return false;
  212634. ComSmartPtr <IMoniker> moniker;
  212635. WCHAR buffer[128];
  212636. HRESULT hr = CreateItemMoniker (_T("!"), buffer, &moniker);
  212637. if (FAILED (hr))
  212638. return false;
  212639. graphRegistrationID = 0;
  212640. return SUCCEEDED (rot->Register (0, graphBuilder, moniker, &graphRegistrationID));
  212641. }
  212642. void removeGraphFromRot()
  212643. {
  212644. ComSmartPtr <IRunningObjectTable> rot;
  212645. if (SUCCEEDED (GetRunningObjectTable (0, &rot)))
  212646. rot->Revoke (graphRegistrationID);
  212647. }
  212648. static void deleteMediaType (AM_MEDIA_TYPE* const pmt)
  212649. {
  212650. if (pmt->cbFormat != 0)
  212651. CoTaskMemFree ((PVOID) pmt->pbFormat);
  212652. if (pmt->pUnk != 0)
  212653. pmt->pUnk->Release();
  212654. CoTaskMemFree (pmt);
  212655. }
  212656. class GrabberCallback : public ComBaseClassHelper <ISampleGrabberCB>
  212657. {
  212658. public:
  212659. GrabberCallback (DShowCameraDeviceInteral& owner_)
  212660. : owner (owner_)
  212661. {
  212662. }
  212663. STDMETHODIMP SampleCB (double /*SampleTime*/, IMediaSample* /*pSample*/)
  212664. {
  212665. return E_FAIL;
  212666. }
  212667. STDMETHODIMP BufferCB (double time, BYTE* buffer, long bufferSize)
  212668. {
  212669. owner.handleFrame (time, buffer, bufferSize);
  212670. return S_OK;
  212671. }
  212672. private:
  212673. DShowCameraDeviceInteral& owner;
  212674. GrabberCallback (const GrabberCallback&);
  212675. GrabberCallback& operator= (const GrabberCallback&);
  212676. };
  212677. ComSmartPtr <GrabberCallback> callback;
  212678. VoidArray listeners;
  212679. CriticalSection listenerLock;
  212680. DShowCameraDeviceInteral (const DShowCameraDeviceInteral&);
  212681. DShowCameraDeviceInteral& operator= (const DShowCameraDeviceInteral&);
  212682. };
  212683. CameraDevice::CameraDevice (const String& name_, int /*index*/)
  212684. : name (name_)
  212685. {
  212686. isRecording = false;
  212687. }
  212688. CameraDevice::~CameraDevice()
  212689. {
  212690. stopRecording();
  212691. delete static_cast <DShowCameraDeviceInteral*> (internal);
  212692. internal = 0;
  212693. }
  212694. Component* CameraDevice::createViewerComponent()
  212695. {
  212696. return new DShowCameraDeviceInteral::DShowCaptureViewerComp (static_cast <DShowCameraDeviceInteral*> (internal));
  212697. }
  212698. const String CameraDevice::getFileExtension()
  212699. {
  212700. return ".wmv";
  212701. }
  212702. void CameraDevice::startRecordingToFile (const File& file, int quality)
  212703. {
  212704. stopRecording();
  212705. DShowCameraDeviceInteral* const d = (DShowCameraDeviceInteral*) internal;
  212706. d->addUser();
  212707. isRecording = d->createFileCaptureFilter (file);
  212708. }
  212709. const Time CameraDevice::getTimeOfFirstRecordedFrame() const
  212710. {
  212711. DShowCameraDeviceInteral* const d = (DShowCameraDeviceInteral*) internal;
  212712. return d->firstRecordedTime;
  212713. }
  212714. void CameraDevice::stopRecording()
  212715. {
  212716. if (isRecording)
  212717. {
  212718. DShowCameraDeviceInteral* const d = (DShowCameraDeviceInteral*) internal;
  212719. d->removeFileCaptureFilter();
  212720. d->removeUser();
  212721. isRecording = false;
  212722. }
  212723. }
  212724. void CameraDevice::addListener (CameraImageListener* listenerToAdd)
  212725. {
  212726. DShowCameraDeviceInteral* const d = (DShowCameraDeviceInteral*) internal;
  212727. if (listenerToAdd != 0)
  212728. d->addListener (listenerToAdd);
  212729. }
  212730. void CameraDevice::removeListener (CameraImageListener* listenerToRemove)
  212731. {
  212732. DShowCameraDeviceInteral* const d = (DShowCameraDeviceInteral*) internal;
  212733. if (listenerToRemove != 0)
  212734. d->removeListener (listenerToRemove);
  212735. }
  212736. static ComSmartPtr <IBaseFilter> enumerateCameras (StringArray* const names,
  212737. const int deviceIndexToOpen,
  212738. String& name)
  212739. {
  212740. int index = 0;
  212741. ComSmartPtr <IBaseFilter> result;
  212742. ComSmartPtr <ICreateDevEnum> pDevEnum;
  212743. HRESULT hr = pDevEnum.CoCreateInstance (CLSID_SystemDeviceEnum);
  212744. if (SUCCEEDED (hr))
  212745. {
  212746. ComSmartPtr <IEnumMoniker> enumerator;
  212747. hr = pDevEnum->CreateClassEnumerator (CLSID_VideoInputDeviceCategory, &enumerator, 0);
  212748. if (SUCCEEDED (hr) && enumerator != 0)
  212749. {
  212750. ComSmartPtr <IBaseFilter> captureFilter;
  212751. ComSmartPtr <IMoniker> moniker;
  212752. ULONG fetched;
  212753. while (enumerator->Next (1, &moniker, &fetched) == S_OK)
  212754. {
  212755. hr = moniker->BindToObject (0, 0, IID_IBaseFilter, (void**) &captureFilter);
  212756. if (SUCCEEDED (hr))
  212757. {
  212758. ComSmartPtr <IPropertyBag> propertyBag;
  212759. hr = moniker->BindToStorage (0, 0, IID_IPropertyBag, (void**) &propertyBag);
  212760. if (SUCCEEDED (hr))
  212761. {
  212762. VARIANT var;
  212763. var.vt = VT_BSTR;
  212764. hr = propertyBag->Read (_T("FriendlyName"), &var, 0);
  212765. propertyBag = 0;
  212766. if (SUCCEEDED (hr))
  212767. {
  212768. if (names != 0)
  212769. names->add (var.bstrVal);
  212770. if (index == deviceIndexToOpen)
  212771. {
  212772. name = var.bstrVal;
  212773. result = captureFilter;
  212774. captureFilter = 0;
  212775. break;
  212776. }
  212777. ++index;
  212778. }
  212779. moniker = 0;
  212780. }
  212781. captureFilter = 0;
  212782. }
  212783. }
  212784. }
  212785. }
  212786. return result;
  212787. }
  212788. const StringArray CameraDevice::getAvailableDevices()
  212789. {
  212790. StringArray devs;
  212791. String dummy;
  212792. enumerateCameras (&devs, -1, dummy);
  212793. return devs;
  212794. }
  212795. CameraDevice* CameraDevice::openDevice (int index,
  212796. int minWidth, int minHeight,
  212797. int maxWidth, int maxHeight)
  212798. {
  212799. ComSmartPtr <ICaptureGraphBuilder2> captureGraphBuilder;
  212800. HRESULT hr = captureGraphBuilder.CoCreateInstance (CLSID_CaptureGraphBuilder2);
  212801. if (SUCCEEDED (hr))
  212802. {
  212803. String name;
  212804. const ComSmartPtr <IBaseFilter> filter (enumerateCameras (0, index, name));
  212805. if (filter != 0)
  212806. {
  212807. ScopedPointer <CameraDevice> cam (new CameraDevice (name, index));
  212808. DShowCameraDeviceInteral* const intern
  212809. = new DShowCameraDeviceInteral (cam, captureGraphBuilder, filter,
  212810. minWidth, minHeight, maxWidth, maxHeight);
  212811. cam->internal = intern;
  212812. if (intern->ok)
  212813. return cam.release();
  212814. }
  212815. }
  212816. return 0;
  212817. }
  212818. #endif
  212819. /*** End of inlined file: juce_win32_CameraDevice.cpp ***/
  212820. #endif
  212821. // Auto-link the other win32 libs that are needed by library calls..
  212822. #if (JUCE_AMALGAMATED_TEMPLATE || defined (JUCE_DLL_BUILD)) && JUCE_MSVC && ! DONT_AUTOLINK_TO_WIN32_LIBRARIES
  212823. /*** Start of inlined file: juce_win32_AutoLinkLibraries.h ***/
  212824. // Auto-links to various win32 libs that are needed by library calls..
  212825. #pragma comment(lib, "kernel32.lib")
  212826. #pragma comment(lib, "user32.lib")
  212827. #pragma comment(lib, "shell32.lib")
  212828. #pragma comment(lib, "gdi32.lib")
  212829. #pragma comment(lib, "vfw32.lib")
  212830. #pragma comment(lib, "comdlg32.lib")
  212831. #pragma comment(lib, "winmm.lib")
  212832. #pragma comment(lib, "wininet.lib")
  212833. #pragma comment(lib, "ole32.lib")
  212834. #pragma comment(lib, "oleaut32.lib")
  212835. #pragma comment(lib, "advapi32.lib")
  212836. #pragma comment(lib, "ws2_32.lib")
  212837. #pragma comment(lib, "comsupp.lib")
  212838. #pragma comment(lib, "version.lib")
  212839. #if JUCE_OPENGL
  212840. #pragma comment(lib, "OpenGL32.Lib")
  212841. #pragma comment(lib, "GlU32.Lib")
  212842. #endif
  212843. #if JUCE_QUICKTIME
  212844. #pragma comment (lib, "QTMLClient.lib")
  212845. #endif
  212846. #if JUCE_USE_CAMERA
  212847. #pragma comment (lib, "Strmiids.lib")
  212848. #pragma comment (lib, "wmvcore.lib")
  212849. #endif
  212850. /*** End of inlined file: juce_win32_AutoLinkLibraries.h ***/
  212851. #endif
  212852. END_JUCE_NAMESPACE
  212853. #endif
  212854. /*** End of inlined file: juce_win32_NativeCode.cpp ***/
  212855. #endif
  212856. #if JUCE_LINUX
  212857. /*** Start of inlined file: juce_linux_NativeCode.cpp ***/
  212858. /*
  212859. This file wraps together all the mac-specific code, so that
  212860. we can include all the native headers just once, and compile all our
  212861. platform-specific stuff in one big lump, keeping it out of the way of
  212862. the rest of the codebase.
  212863. */
  212864. #if JUCE_LINUX
  212865. BEGIN_JUCE_NAMESPACE
  212866. /* Remove this macro if you're having problems compiling the cpu affinity
  212867. calls (the API for these has changed about quite a bit in various Linux
  212868. versions, and a lot of distros seem to ship with obsolete versions)
  212869. */
  212870. #if defined (CPU_ISSET) && ! defined (SUPPORT_AFFINITIES)
  212871. #define SUPPORT_AFFINITIES 1
  212872. #endif
  212873. #define JUCE_INCLUDED_FILE 1
  212874. // Now include the actual code files..
  212875. /*** Start of inlined file: juce_posix_SharedCode.h ***/
  212876. /*
  212877. This file contains posix routines that are common to both the Linux and Mac builds.
  212878. It gets included directly in the cpp files for these platforms.
  212879. */
  212880. CriticalSection::CriticalSection() throw()
  212881. {
  212882. pthread_mutexattr_t atts;
  212883. pthread_mutexattr_init (&atts);
  212884. pthread_mutexattr_settype (&atts, PTHREAD_MUTEX_RECURSIVE);
  212885. pthread_mutex_init (&internal, &atts);
  212886. }
  212887. CriticalSection::~CriticalSection() throw()
  212888. {
  212889. pthread_mutex_destroy (&internal);
  212890. }
  212891. void CriticalSection::enter() const throw()
  212892. {
  212893. pthread_mutex_lock (&internal);
  212894. }
  212895. bool CriticalSection::tryEnter() const throw()
  212896. {
  212897. return pthread_mutex_trylock (&internal) == 0;
  212898. }
  212899. void CriticalSection::exit() const throw()
  212900. {
  212901. pthread_mutex_unlock (&internal);
  212902. }
  212903. class WaitableEventImpl
  212904. {
  212905. public:
  212906. WaitableEventImpl (const bool manualReset_)
  212907. : triggered (false),
  212908. manualReset (manualReset_)
  212909. {
  212910. pthread_cond_init (&condition, 0);
  212911. pthread_mutex_init (&mutex, 0);
  212912. }
  212913. ~WaitableEventImpl()
  212914. {
  212915. pthread_cond_destroy (&condition);
  212916. pthread_mutex_destroy (&mutex);
  212917. }
  212918. bool wait (const int timeOutMillisecs) throw()
  212919. {
  212920. pthread_mutex_lock (&mutex);
  212921. if (! triggered)
  212922. {
  212923. if (timeOutMillisecs < 0)
  212924. {
  212925. do
  212926. {
  212927. pthread_cond_wait (&condition, &mutex);
  212928. }
  212929. while (! triggered);
  212930. }
  212931. else
  212932. {
  212933. struct timeval now;
  212934. gettimeofday (&now, 0);
  212935. struct timespec time;
  212936. time.tv_sec = now.tv_sec + (timeOutMillisecs / 1000);
  212937. time.tv_nsec = (now.tv_usec + ((timeOutMillisecs % 1000) * 1000)) * 1000;
  212938. if (time.tv_nsec >= 1000000000)
  212939. {
  212940. time.tv_nsec -= 1000000000;
  212941. time.tv_sec++;
  212942. }
  212943. do
  212944. {
  212945. if (pthread_cond_timedwait (&condition, &mutex, &time) == ETIMEDOUT)
  212946. {
  212947. pthread_mutex_unlock (&mutex);
  212948. return false;
  212949. }
  212950. }
  212951. while (! triggered);
  212952. }
  212953. }
  212954. if (! manualReset)
  212955. triggered = false;
  212956. pthread_mutex_unlock (&mutex);
  212957. return true;
  212958. }
  212959. void signal() throw()
  212960. {
  212961. pthread_mutex_lock (&mutex);
  212962. triggered = true;
  212963. pthread_cond_broadcast (&condition);
  212964. pthread_mutex_unlock (&mutex);
  212965. }
  212966. void reset() throw()
  212967. {
  212968. pthread_mutex_lock (&mutex);
  212969. triggered = false;
  212970. pthread_mutex_unlock (&mutex);
  212971. }
  212972. private:
  212973. pthread_cond_t condition;
  212974. pthread_mutex_t mutex;
  212975. bool triggered;
  212976. const bool manualReset;
  212977. WaitableEventImpl (const WaitableEventImpl&);
  212978. WaitableEventImpl& operator= (const WaitableEventImpl&);
  212979. };
  212980. WaitableEvent::WaitableEvent (const bool manualReset) throw()
  212981. : internal (new WaitableEventImpl (manualReset))
  212982. {
  212983. }
  212984. WaitableEvent::~WaitableEvent() throw()
  212985. {
  212986. delete static_cast <WaitableEventImpl*> (internal);
  212987. }
  212988. bool WaitableEvent::wait (const int timeOutMillisecs) const throw()
  212989. {
  212990. return static_cast <WaitableEventImpl*> (internal)->wait (timeOutMillisecs);
  212991. }
  212992. void WaitableEvent::signal() const throw()
  212993. {
  212994. static_cast <WaitableEventImpl*> (internal)->signal();
  212995. }
  212996. void WaitableEvent::reset() const throw()
  212997. {
  212998. static_cast <WaitableEventImpl*> (internal)->reset();
  212999. }
  213000. void JUCE_CALLTYPE Thread::sleep (int millisecs)
  213001. {
  213002. struct timespec time;
  213003. time.tv_sec = millisecs / 1000;
  213004. time.tv_nsec = (millisecs % 1000) * 1000000;
  213005. nanosleep (&time, 0);
  213006. }
  213007. const juce_wchar File::separator = '/';
  213008. const String File::separatorString ("/");
  213009. const File File::getCurrentWorkingDirectory()
  213010. {
  213011. HeapBlock<char> heapBuffer;
  213012. char localBuffer [1024];
  213013. char* cwd = getcwd (localBuffer, sizeof (localBuffer) - 1);
  213014. int bufferSize = 4096;
  213015. while (cwd == 0 && errno == ERANGE)
  213016. {
  213017. heapBuffer.malloc (bufferSize);
  213018. cwd = getcwd (heapBuffer, bufferSize - 1);
  213019. bufferSize += 1024;
  213020. }
  213021. return File (String::fromUTF8 (cwd));
  213022. }
  213023. bool File::setAsCurrentWorkingDirectory() const
  213024. {
  213025. return chdir (getFullPathName().toUTF8()) == 0;
  213026. }
  213027. static bool juce_stat (const String& fileName, struct stat& info)
  213028. {
  213029. return fileName.isNotEmpty()
  213030. && (stat (fileName.toUTF8(), &info) == 0);
  213031. }
  213032. bool File::isDirectory() const
  213033. {
  213034. struct stat info;
  213035. return fullPath.isEmpty()
  213036. || (juce_stat (fullPath, info) && ((info.st_mode & S_IFDIR) != 0));
  213037. }
  213038. bool File::exists() const
  213039. {
  213040. return fullPath.isNotEmpty()
  213041. && access (fullPath.toUTF8(), F_OK) == 0;
  213042. }
  213043. bool File::existsAsFile() const
  213044. {
  213045. return exists() && ! isDirectory();
  213046. }
  213047. int64 File::getSize() const
  213048. {
  213049. struct stat info;
  213050. return juce_stat (fullPath, info) ? info.st_size : 0;
  213051. }
  213052. bool File::hasWriteAccess() const
  213053. {
  213054. if (exists())
  213055. return access (fullPath.toUTF8(), W_OK) == 0;
  213056. if ((! isDirectory()) && fullPath.containsChar (separator))
  213057. return getParentDirectory().hasWriteAccess();
  213058. return false;
  213059. }
  213060. bool File::setFileReadOnlyInternal (const bool shouldBeReadOnly) const
  213061. {
  213062. struct stat info;
  213063. const int res = stat (fullPath.toUTF8(), &info);
  213064. if (res != 0)
  213065. return false;
  213066. info.st_mode &= 0777; // Just permissions
  213067. if (shouldBeReadOnly)
  213068. info.st_mode &= ~(S_IWUSR | S_IWGRP | S_IWOTH);
  213069. else
  213070. // Give everybody write permission?
  213071. info.st_mode |= S_IWUSR | S_IWGRP | S_IWOTH;
  213072. return chmod (fullPath.toUTF8(), info.st_mode) == 0;
  213073. }
  213074. void File::getFileTimesInternal (int64& modificationTime, int64& accessTime, int64& creationTime) const
  213075. {
  213076. modificationTime = 0;
  213077. accessTime = 0;
  213078. creationTime = 0;
  213079. struct stat info;
  213080. const int res = stat (fullPath.toUTF8(), &info);
  213081. if (res == 0)
  213082. {
  213083. modificationTime = (int64) info.st_mtime * 1000;
  213084. accessTime = (int64) info.st_atime * 1000;
  213085. creationTime = (int64) info.st_ctime * 1000;
  213086. }
  213087. }
  213088. bool File::setFileTimesInternal (int64 modificationTime, int64 accessTime, int64 creationTime) const
  213089. {
  213090. struct utimbuf times;
  213091. times.actime = (time_t) (accessTime / 1000);
  213092. times.modtime = (time_t) (modificationTime / 1000);
  213093. return utime (fullPath.toUTF8(), &times) == 0;
  213094. }
  213095. bool File::deleteFile() const
  213096. {
  213097. if (! exists())
  213098. return true;
  213099. else if (isDirectory())
  213100. return rmdir (fullPath.toUTF8()) == 0;
  213101. else
  213102. return remove (fullPath.toUTF8()) == 0;
  213103. }
  213104. bool File::moveInternal (const File& dest) const
  213105. {
  213106. if (rename (fullPath.toUTF8(), dest.getFullPathName().toUTF8()) == 0)
  213107. return true;
  213108. if (hasWriteAccess() && copyInternal (dest))
  213109. {
  213110. if (deleteFile())
  213111. return true;
  213112. dest.deleteFile();
  213113. }
  213114. return false;
  213115. }
  213116. void File::createDirectoryInternal (const String& fileName) const
  213117. {
  213118. mkdir (fileName.toUTF8(), 0777);
  213119. }
  213120. void* juce_fileOpen (const File& file, bool forWriting)
  213121. {
  213122. int flags = O_RDONLY;
  213123. if (forWriting)
  213124. {
  213125. if (file.exists())
  213126. {
  213127. const int f = open (file.getFullPathName().toUTF8(), O_RDWR, 00644);
  213128. if (f != -1)
  213129. lseek (f, 0, SEEK_END);
  213130. return (void*) f;
  213131. }
  213132. else
  213133. {
  213134. flags = O_RDWR + O_CREAT;
  213135. }
  213136. }
  213137. return (void*) open (file.getFullPathName().toUTF8(), flags, 00644);
  213138. }
  213139. void juce_fileClose (void* handle)
  213140. {
  213141. if (handle != 0)
  213142. close ((int) (pointer_sized_int) handle);
  213143. }
  213144. int juce_fileRead (void* handle, void* buffer, int size)
  213145. {
  213146. if (handle != 0)
  213147. return jmax (0, (int) read ((int) (pointer_sized_int) handle, buffer, size));
  213148. return 0;
  213149. }
  213150. int juce_fileWrite (void* handle, const void* buffer, int size)
  213151. {
  213152. if (handle != 0)
  213153. return (int) write ((int) (pointer_sized_int) handle, buffer, size);
  213154. return 0;
  213155. }
  213156. int64 juce_fileSetPosition (void* handle, int64 pos)
  213157. {
  213158. if (handle != 0 && lseek ((int) (pointer_sized_int) handle, pos, SEEK_SET) == pos)
  213159. return pos;
  213160. return -1;
  213161. }
  213162. int64 FileOutputStream::getPositionInternal() const
  213163. {
  213164. if (fileHandle != 0)
  213165. return lseek ((int) (pointer_sized_int) fileHandle, 0, SEEK_CUR);
  213166. return -1;
  213167. }
  213168. void FileOutputStream::flushInternal()
  213169. {
  213170. if (fileHandle != 0)
  213171. fsync ((int) (pointer_sized_int) fileHandle);
  213172. }
  213173. const File juce_getExecutableFile()
  213174. {
  213175. Dl_info exeInfo;
  213176. dladdr ((const void*) juce_getExecutableFile, &exeInfo);
  213177. return File::getCurrentWorkingDirectory().getChildFile (String::fromUTF8 (exeInfo.dli_fname));
  213178. }
  213179. // if this file doesn't exist, find a parent of it that does..
  213180. static bool juce_doStatFS (File f, struct statfs& result)
  213181. {
  213182. for (int i = 5; --i >= 0;)
  213183. {
  213184. if (f.exists())
  213185. break;
  213186. f = f.getParentDirectory();
  213187. }
  213188. return statfs (f.getFullPathName().toUTF8(), &result) == 0;
  213189. }
  213190. int64 File::getBytesFreeOnVolume() const
  213191. {
  213192. struct statfs buf;
  213193. if (juce_doStatFS (*this, buf))
  213194. return (int64) buf.f_bsize * (int64) buf.f_bavail; // Note: this returns space available to non-super user
  213195. return 0;
  213196. }
  213197. int64 File::getVolumeTotalSize() const
  213198. {
  213199. struct statfs buf;
  213200. if (juce_doStatFS (*this, buf))
  213201. return (int64) buf.f_bsize * (int64) buf.f_blocks;
  213202. return 0;
  213203. }
  213204. const String File::getVolumeLabel() const
  213205. {
  213206. #if JUCE_MAC
  213207. struct VolAttrBuf
  213208. {
  213209. u_int32_t length;
  213210. attrreference_t mountPointRef;
  213211. char mountPointSpace [MAXPATHLEN];
  213212. } attrBuf;
  213213. struct attrlist attrList;
  213214. zerostruct (attrList);
  213215. attrList.bitmapcount = ATTR_BIT_MAP_COUNT;
  213216. attrList.volattr = ATTR_VOL_INFO | ATTR_VOL_NAME;
  213217. File f (*this);
  213218. for (;;)
  213219. {
  213220. if (getattrlist (f.getFullPathName().toUTF8(), &attrList, &attrBuf, sizeof (attrBuf), 0) == 0)
  213221. return String::fromUTF8 (((const char*) &attrBuf.mountPointRef) + attrBuf.mountPointRef.attr_dataoffset,
  213222. (int) attrBuf.mountPointRef.attr_length);
  213223. const File parent (f.getParentDirectory());
  213224. if (f == parent)
  213225. break;
  213226. f = parent;
  213227. }
  213228. #endif
  213229. return String::empty;
  213230. }
  213231. int File::getVolumeSerialNumber() const
  213232. {
  213233. return 0; // xxx
  213234. }
  213235. void juce_runSystemCommand (const String& command)
  213236. {
  213237. int result = system (command.toUTF8());
  213238. (void) result;
  213239. }
  213240. const String juce_getOutputFromCommand (const String& command)
  213241. {
  213242. // slight bodge here, as we just pipe the output into a temp file and read it...
  213243. const File tempFile (File::getSpecialLocation (File::tempDirectory)
  213244. .getNonexistentChildFile (String::toHexString (Random::getSystemRandom().nextInt()), ".tmp", false));
  213245. juce_runSystemCommand (command + " > " + tempFile.getFullPathName());
  213246. String result (tempFile.loadFileAsString());
  213247. tempFile.deleteFile();
  213248. return result;
  213249. }
  213250. class InterProcessLock::Pimpl
  213251. {
  213252. public:
  213253. Pimpl (const String& name, const int timeOutMillisecs)
  213254. : handle (0), refCount (1)
  213255. {
  213256. #if JUCE_MAC
  213257. // (don't use getSpecialLocation() to avoid the temp folder being different for each app)
  213258. const File temp (File ("~/Library/Caches/Juce").getChildFile (name));
  213259. #else
  213260. const File temp (File::getSpecialLocation (File::tempDirectory).getChildFile (name));
  213261. #endif
  213262. temp.create();
  213263. handle = open (temp.getFullPathName().toUTF8(), O_RDWR);
  213264. if (handle != 0)
  213265. {
  213266. struct flock fl;
  213267. zerostruct (fl);
  213268. fl.l_whence = SEEK_SET;
  213269. fl.l_type = F_WRLCK;
  213270. const int64 endTime = Time::currentTimeMillis() + timeOutMillisecs;
  213271. for (;;)
  213272. {
  213273. const int result = fcntl (handle, F_SETLK, &fl);
  213274. if (result >= 0)
  213275. return;
  213276. if (errno != EINTR)
  213277. {
  213278. if (timeOutMillisecs == 0
  213279. || (timeOutMillisecs > 0 && Time::currentTimeMillis() >= endTime))
  213280. break;
  213281. Thread::sleep (10);
  213282. }
  213283. }
  213284. }
  213285. closeFile();
  213286. }
  213287. ~Pimpl()
  213288. {
  213289. closeFile();
  213290. }
  213291. void closeFile()
  213292. {
  213293. if (handle != 0)
  213294. {
  213295. struct flock fl;
  213296. zerostruct (fl);
  213297. fl.l_whence = SEEK_SET;
  213298. fl.l_type = F_UNLCK;
  213299. while (! (fcntl (handle, F_SETLKW, &fl) >= 0 || errno != EINTR))
  213300. {}
  213301. close (handle);
  213302. handle = 0;
  213303. }
  213304. }
  213305. int handle, refCount;
  213306. };
  213307. InterProcessLock::InterProcessLock (const String& name_)
  213308. : name (name_)
  213309. {
  213310. }
  213311. InterProcessLock::~InterProcessLock()
  213312. {
  213313. }
  213314. bool InterProcessLock::enter (const int timeOutMillisecs)
  213315. {
  213316. const ScopedLock sl (lock);
  213317. if (pimpl == 0)
  213318. {
  213319. pimpl = new Pimpl (name, timeOutMillisecs);
  213320. if (pimpl->handle == 0)
  213321. pimpl = 0;
  213322. }
  213323. else
  213324. {
  213325. pimpl->refCount++;
  213326. }
  213327. return pimpl != 0;
  213328. }
  213329. void InterProcessLock::exit()
  213330. {
  213331. const ScopedLock sl (lock);
  213332. // Trying to release the lock too many times!
  213333. jassert (pimpl != 0);
  213334. if (pimpl != 0 && --(pimpl->refCount) == 0)
  213335. pimpl = 0;
  213336. }
  213337. /*** End of inlined file: juce_posix_SharedCode.h ***/
  213338. /*** Start of inlined file: juce_linux_Files.cpp ***/
  213339. // (This file gets included by juce_linux_NativeCode.cpp, rather than being
  213340. // compiled on its own).
  213341. #if JUCE_INCLUDED_FILE
  213342. static const short U_ISOFS_SUPER_MAGIC = 0x9660; // linux/iso_fs.h
  213343. static const short U_MSDOS_SUPER_MAGIC = 0x4d44; // linux/msdos_fs.h
  213344. static const short U_NFS_SUPER_MAGIC = 0x6969; // linux/nfs_fs.h
  213345. static const short U_SMB_SUPER_MAGIC = 0x517B; // linux/smb_fs.h
  213346. bool File::copyInternal (const File& dest) const
  213347. {
  213348. FileInputStream in (*this);
  213349. if (dest.deleteFile())
  213350. {
  213351. {
  213352. FileOutputStream out (dest);
  213353. if (out.failedToOpen())
  213354. return false;
  213355. if (out.writeFromInputStream (in, -1) == getSize())
  213356. return true;
  213357. }
  213358. dest.deleteFile();
  213359. }
  213360. return false;
  213361. }
  213362. void File::findFileSystemRoots (Array<File>& destArray)
  213363. {
  213364. destArray.add (File ("/"));
  213365. }
  213366. bool File::isOnCDRomDrive() const
  213367. {
  213368. struct statfs buf;
  213369. return statfs (getFullPathName().toUTF8(), &buf) == 0
  213370. && buf.f_type == U_ISOFS_SUPER_MAGIC;
  213371. }
  213372. bool File::isOnHardDisk() const
  213373. {
  213374. struct statfs buf;
  213375. if (statfs (getFullPathName().toUTF8(), &buf) == 0)
  213376. {
  213377. switch (buf.f_type)
  213378. {
  213379. case U_ISOFS_SUPER_MAGIC: // CD-ROM
  213380. case U_MSDOS_SUPER_MAGIC: // Probably floppy (but could be mounted FAT filesystem)
  213381. case U_NFS_SUPER_MAGIC: // Network NFS
  213382. case U_SMB_SUPER_MAGIC: // Network Samba
  213383. return false;
  213384. default:
  213385. // Assume anything else is a hard-disk (but note it could
  213386. // be a RAM disk. There isn't a good way of determining
  213387. // this for sure)
  213388. return true;
  213389. }
  213390. }
  213391. // Assume so if this fails for some reason
  213392. return true;
  213393. }
  213394. bool File::isOnRemovableDrive() const
  213395. {
  213396. jassertfalse // xxx not implemented for linux!
  213397. return false;
  213398. }
  213399. bool File::isHidden() const
  213400. {
  213401. return getFileName().startsWithChar ('.');
  213402. }
  213403. const char* juce_Argv0 = 0; // referenced from juce_Application.cpp
  213404. const File File::getSpecialLocation (const SpecialLocationType type)
  213405. {
  213406. switch (type)
  213407. {
  213408. case userHomeDirectory:
  213409. {
  213410. const char* homeDir = getenv ("HOME");
  213411. if (homeDir == 0)
  213412. {
  213413. struct passwd* const pw = getpwuid (getuid());
  213414. if (pw != 0)
  213415. homeDir = pw->pw_dir;
  213416. }
  213417. return File (String::fromUTF8 (homeDir));
  213418. }
  213419. case userDocumentsDirectory:
  213420. case userMusicDirectory:
  213421. case userMoviesDirectory:
  213422. case userApplicationDataDirectory:
  213423. return File ("~");
  213424. case userDesktopDirectory:
  213425. return File ("~/Desktop");
  213426. case commonApplicationDataDirectory:
  213427. return File ("/var");
  213428. case globalApplicationsDirectory:
  213429. return File ("/usr");
  213430. case tempDirectory:
  213431. {
  213432. File tmp ("/var/tmp");
  213433. if (! tmp.isDirectory())
  213434. {
  213435. tmp = "/tmp";
  213436. if (! tmp.isDirectory())
  213437. tmp = File::getCurrentWorkingDirectory();
  213438. }
  213439. return tmp;
  213440. }
  213441. case invokedExecutableFile:
  213442. if (juce_Argv0 != 0)
  213443. return File (String::fromUTF8 (juce_Argv0));
  213444. // deliberate fall-through...
  213445. case currentExecutableFile:
  213446. case currentApplicationFile:
  213447. return juce_getExecutableFile();
  213448. default:
  213449. jassertfalse // unknown type?
  213450. break;
  213451. }
  213452. return File::nonexistent;
  213453. }
  213454. const String File::getVersion() const
  213455. {
  213456. return String::empty; // xxx not yet implemented
  213457. }
  213458. const File File::getLinkedTarget() const
  213459. {
  213460. char buffer [4096];
  213461. size_t numChars = readlink (getFullPathName().toUTF8(),
  213462. buffer, sizeof (buffer));
  213463. if (numChars > 0 && numChars <= sizeof (buffer))
  213464. return File (String::fromUTF8 (buffer, (int) numChars));
  213465. return *this;
  213466. }
  213467. bool File::moveToTrash() const
  213468. {
  213469. if (! exists())
  213470. return true;
  213471. File trashCan ("~/.Trash");
  213472. if (! trashCan.isDirectory())
  213473. trashCan = "~/.local/share/Trash/files";
  213474. if (! trashCan.isDirectory())
  213475. return false;
  213476. return moveFileTo (trashCan.getNonexistentChildFile (getFileNameWithoutExtension(),
  213477. getFileExtension()));
  213478. }
  213479. class DirectoryIterator::NativeIterator::Pimpl
  213480. {
  213481. public:
  213482. Pimpl (const File& directory, const String& wildCard_)
  213483. : parentDir (File::addTrailingSeparator (directory.getFullPathName())),
  213484. wildCard (wildCard_),
  213485. dir (opendir (directory.getFullPathName().toUTF8()))
  213486. {
  213487. if (wildCard == "*.*")
  213488. wildCard = "*";
  213489. wildcardUTF8 = wildCard.toUTF8();
  213490. }
  213491. ~Pimpl()
  213492. {
  213493. if (dir != 0)
  213494. closedir (dir);
  213495. }
  213496. bool next (String& filenameFound,
  213497. bool* const isDir, bool* const isHidden, int64* const fileSize,
  213498. Time* const modTime, Time* const creationTime, bool* const isReadOnly)
  213499. {
  213500. if (dir == 0)
  213501. return false;
  213502. for (;;)
  213503. {
  213504. struct dirent* const de = readdir (dir);
  213505. if (de == 0)
  213506. return false;
  213507. if (fnmatch (wildcardUTF8, de->d_name, FNM_CASEFOLD) == 0)
  213508. {
  213509. filenameFound = String::fromUTF8 (de->d_name);
  213510. const String path (parentDir + filenameFound);
  213511. if (isDir != 0 || fileSize != 0 || modTime != 0 || creationTime != 0)
  213512. {
  213513. struct stat info;
  213514. const bool statOk = juce_stat (path, info);
  213515. if (isDir != 0) *isDir = statOk && ((info.st_mode & S_IFDIR) != 0);
  213516. if (fileSize != 0) *fileSize = statOk ? info.st_size : 0;
  213517. if (modTime != 0) *modTime = statOk ? (int64) info.st_mtime * 1000 : 0;
  213518. if (creationTime != 0) *creationTime = statOk ? (int64) info.st_ctime * 1000 : 0;
  213519. }
  213520. if (isHidden != 0)
  213521. *isHidden = filenameFound.startsWithChar ('.');
  213522. if (isReadOnly != 0)
  213523. *isReadOnly = access (path.toUTF8(), W_OK) != 0;
  213524. return true;
  213525. }
  213526. }
  213527. }
  213528. private:
  213529. String parentDir, wildCard;
  213530. const char* wildcardUTF8;
  213531. DIR* dir;
  213532. Pimpl (const Pimpl&);
  213533. Pimpl& operator= (const Pimpl&);
  213534. };
  213535. DirectoryIterator::NativeIterator::NativeIterator (const File& directory, const String& wildCard)
  213536. : pimpl (new DirectoryIterator::NativeIterator::Pimpl (directory, wildCard))
  213537. {
  213538. }
  213539. DirectoryIterator::NativeIterator::~NativeIterator()
  213540. {
  213541. }
  213542. bool DirectoryIterator::NativeIterator::next (String& filenameFound,
  213543. bool* const isDir, bool* const isHidden, int64* const fileSize,
  213544. Time* const modTime, Time* const creationTime, bool* const isReadOnly)
  213545. {
  213546. return pimpl->next (filenameFound, isDir, isHidden, fileSize, modTime, creationTime, isReadOnly);
  213547. }
  213548. bool PlatformUtilities::openDocument (const String& fileName, const String& parameters)
  213549. {
  213550. String cmdString (fileName.replace (" ", "\\ ",false));
  213551. cmdString << " " << parameters;
  213552. if (URL::isProbablyAWebsiteURL (fileName)
  213553. || cmdString.startsWithIgnoreCase ("file:")
  213554. || URL::isProbablyAnEmailAddress (fileName))
  213555. {
  213556. // create a command that tries to launch a bunch of likely browsers
  213557. const char* const browserNames[] = { "xdg-open", "/etc/alternatives/x-www-browser", "firefox", "mozilla", "konqueror", "opera" };
  213558. StringArray cmdLines;
  213559. for (int i = 0; i < numElementsInArray (browserNames); ++i)
  213560. cmdLines.add (String (browserNames[i]) + " " + cmdString.trim().quoted());
  213561. cmdString = cmdLines.joinIntoString (" || ");
  213562. }
  213563. const char* const argv[4] = { "/bin/sh", "-c", cmdString.toUTF8(), 0 };
  213564. const int cpid = fork();
  213565. if (cpid == 0)
  213566. {
  213567. setsid();
  213568. // Child process
  213569. execve (argv[0], (char**) argv, environ);
  213570. exit (0);
  213571. }
  213572. return cpid >= 0;
  213573. }
  213574. void File::revealToUser() const
  213575. {
  213576. if (isDirectory())
  213577. startAsProcess();
  213578. else if (getParentDirectory().exists())
  213579. getParentDirectory().startAsProcess();
  213580. }
  213581. #endif
  213582. /*** End of inlined file: juce_linux_Files.cpp ***/
  213583. /*** Start of inlined file: juce_posix_NamedPipe.cpp ***/
  213584. // (This file gets included by juce_mac_NativeCode.mm, rather than being
  213585. // compiled on its own).
  213586. #if JUCE_INCLUDED_FILE
  213587. struct NamedPipeInternal
  213588. {
  213589. String pipeInName, pipeOutName;
  213590. int pipeIn, pipeOut;
  213591. bool volatile createdPipe, blocked, stopReadOperation;
  213592. static void signalHandler (int) {}
  213593. };
  213594. void NamedPipe::cancelPendingReads()
  213595. {
  213596. while (internal != 0 && ((NamedPipeInternal*) internal)->blocked)
  213597. {
  213598. NamedPipeInternal* const intern = (NamedPipeInternal*) internal;
  213599. intern->stopReadOperation = true;
  213600. char buffer [1] = { 0 };
  213601. int bytesWritten = (int) ::write (intern->pipeIn, buffer, 1);
  213602. (void) bytesWritten;
  213603. int timeout = 2000;
  213604. while (intern->blocked && --timeout >= 0)
  213605. Thread::sleep (2);
  213606. intern->stopReadOperation = false;
  213607. }
  213608. }
  213609. void NamedPipe::close()
  213610. {
  213611. NamedPipeInternal* const intern = (NamedPipeInternal*) internal;
  213612. if (intern != 0)
  213613. {
  213614. internal = 0;
  213615. if (intern->pipeIn != -1)
  213616. ::close (intern->pipeIn);
  213617. if (intern->pipeOut != -1)
  213618. ::close (intern->pipeOut);
  213619. if (intern->createdPipe)
  213620. {
  213621. unlink (intern->pipeInName.toUTF8());
  213622. unlink (intern->pipeOutName.toUTF8());
  213623. }
  213624. delete intern;
  213625. }
  213626. }
  213627. bool NamedPipe::openInternal (const String& pipeName, const bool createPipe)
  213628. {
  213629. close();
  213630. NamedPipeInternal* const intern = new NamedPipeInternal();
  213631. internal = intern;
  213632. intern->createdPipe = createPipe;
  213633. intern->blocked = false;
  213634. intern->stopReadOperation = false;
  213635. signal (SIGPIPE, NamedPipeInternal::signalHandler);
  213636. siginterrupt (SIGPIPE, 1);
  213637. const String pipePath ("/tmp/" + File::createLegalFileName (pipeName));
  213638. intern->pipeInName = pipePath + "_in";
  213639. intern->pipeOutName = pipePath + "_out";
  213640. intern->pipeIn = -1;
  213641. intern->pipeOut = -1;
  213642. if (createPipe)
  213643. {
  213644. if ((mkfifo (intern->pipeInName.toUTF8(), 0666) && errno != EEXIST)
  213645. || (mkfifo (intern->pipeOutName.toUTF8(), 0666) && errno != EEXIST))
  213646. {
  213647. delete intern;
  213648. internal = 0;
  213649. return false;
  213650. }
  213651. }
  213652. return true;
  213653. }
  213654. int NamedPipe::read (void* destBuffer, int maxBytesToRead, int /*timeOutMilliseconds*/)
  213655. {
  213656. int bytesRead = -1;
  213657. NamedPipeInternal* const intern = (NamedPipeInternal*) internal;
  213658. if (intern != 0)
  213659. {
  213660. intern->blocked = true;
  213661. if (intern->pipeIn == -1)
  213662. {
  213663. if (intern->createdPipe)
  213664. intern->pipeIn = ::open (intern->pipeInName.toUTF8(), O_RDWR);
  213665. else
  213666. intern->pipeIn = ::open (intern->pipeOutName.toUTF8(), O_RDWR);
  213667. if (intern->pipeIn == -1)
  213668. {
  213669. intern->blocked = false;
  213670. return -1;
  213671. }
  213672. }
  213673. bytesRead = 0;
  213674. char* p = (char*) destBuffer;
  213675. while (bytesRead < maxBytesToRead)
  213676. {
  213677. const int bytesThisTime = maxBytesToRead - bytesRead;
  213678. const int numRead = (int) ::read (intern->pipeIn, p, bytesThisTime);
  213679. if (numRead <= 0 || intern->stopReadOperation)
  213680. {
  213681. bytesRead = -1;
  213682. break;
  213683. }
  213684. bytesRead += numRead;
  213685. p += bytesRead;
  213686. }
  213687. intern->blocked = false;
  213688. }
  213689. return bytesRead;
  213690. }
  213691. int NamedPipe::write (const void* sourceBuffer, int numBytesToWrite, int timeOutMilliseconds)
  213692. {
  213693. int bytesWritten = -1;
  213694. NamedPipeInternal* const intern = (NamedPipeInternal*) internal;
  213695. if (intern != 0)
  213696. {
  213697. if (intern->pipeOut == -1)
  213698. {
  213699. if (intern->createdPipe)
  213700. intern->pipeOut = ::open (intern->pipeOutName.toUTF8(), O_WRONLY);
  213701. else
  213702. intern->pipeOut = ::open (intern->pipeInName.toUTF8(), O_WRONLY);
  213703. if (intern->pipeOut == -1)
  213704. {
  213705. return -1;
  213706. }
  213707. }
  213708. const char* p = (const char*) sourceBuffer;
  213709. bytesWritten = 0;
  213710. const uint32 timeOutTime = Time::getMillisecondCounter() + timeOutMilliseconds;
  213711. while (bytesWritten < numBytesToWrite
  213712. && (timeOutMilliseconds < 0 || Time::getMillisecondCounter() < timeOutTime))
  213713. {
  213714. const int bytesThisTime = numBytesToWrite - bytesWritten;
  213715. const int numWritten = (int) ::write (intern->pipeOut, p, bytesThisTime);
  213716. if (numWritten <= 0)
  213717. {
  213718. bytesWritten = -1;
  213719. break;
  213720. }
  213721. bytesWritten += numWritten;
  213722. p += bytesWritten;
  213723. }
  213724. }
  213725. return bytesWritten;
  213726. }
  213727. #endif
  213728. /*** End of inlined file: juce_posix_NamedPipe.cpp ***/
  213729. /*** Start of inlined file: juce_linux_Network.cpp ***/
  213730. // (This file gets included by juce_linux_NativeCode.cpp, rather than being
  213731. // compiled on its own).
  213732. #if JUCE_INCLUDED_FILE
  213733. int SystemStats::getMACAddresses (int64* addresses, int maxNum, const bool littleEndian)
  213734. {
  213735. int numResults = 0;
  213736. const int s = socket (AF_INET, SOCK_DGRAM, 0);
  213737. if (s != -1)
  213738. {
  213739. char buf [1024];
  213740. struct ifconf ifc;
  213741. ifc.ifc_len = sizeof (buf);
  213742. ifc.ifc_buf = buf;
  213743. ioctl (s, SIOCGIFCONF, &ifc);
  213744. for (unsigned int i = 0; i < ifc.ifc_len / sizeof (struct ifreq); ++i)
  213745. {
  213746. struct ifreq ifr;
  213747. strcpy (ifr.ifr_name, ifc.ifc_req[i].ifr_name);
  213748. if (ioctl (s, SIOCGIFFLAGS, &ifr) == 0
  213749. && (ifr.ifr_flags & IFF_LOOPBACK) == 0
  213750. && ioctl (s, SIOCGIFHWADDR, &ifr) == 0
  213751. && numResults < maxNum)
  213752. {
  213753. int64 a = 0;
  213754. for (int j = 6; --j >= 0;)
  213755. a = (a << 8) | (uint8) ifr.ifr_hwaddr.sa_data [littleEndian ? j : (5 - j)];
  213756. *addresses++ = a;
  213757. ++numResults;
  213758. }
  213759. }
  213760. close (s);
  213761. }
  213762. return numResults;
  213763. }
  213764. bool PlatformUtilities::launchEmailWithAttachments (const String& targetEmailAddress,
  213765. const String& emailSubject,
  213766. const String& bodyText,
  213767. const StringArray& filesToAttach)
  213768. {
  213769. jassertfalse // xxx todo
  213770. return false;
  213771. }
  213772. /** A HTTP input stream that uses sockets.
  213773. */
  213774. class JUCE_HTTPSocketStream
  213775. {
  213776. public:
  213777. JUCE_HTTPSocketStream()
  213778. : readPosition (0),
  213779. socketHandle (-1),
  213780. levelsOfRedirection (0),
  213781. timeoutSeconds (15)
  213782. {
  213783. }
  213784. ~JUCE_HTTPSocketStream()
  213785. {
  213786. closeSocket();
  213787. }
  213788. bool open (const String& url,
  213789. const String& headers,
  213790. const MemoryBlock& postData,
  213791. const bool isPost,
  213792. URL::OpenStreamProgressCallback* callback,
  213793. void* callbackContext,
  213794. int timeOutMs)
  213795. {
  213796. closeSocket();
  213797. uint32 timeOutTime = Time::getMillisecondCounter();
  213798. if (timeOutMs == 0)
  213799. timeOutTime += 60000;
  213800. else if (timeOutMs < 0)
  213801. timeOutTime = 0xffffffff;
  213802. else
  213803. timeOutTime += timeOutMs;
  213804. String hostName, hostPath;
  213805. int hostPort;
  213806. if (! decomposeURL (url, hostName, hostPath, hostPort))
  213807. return false;
  213808. const struct hostent* host = 0;
  213809. int port = 0;
  213810. String proxyName, proxyPath;
  213811. int proxyPort = 0;
  213812. String proxyURL (getenv ("http_proxy"));
  213813. if (proxyURL.startsWithIgnoreCase ("http://"))
  213814. {
  213815. if (! decomposeURL (proxyURL, proxyName, proxyPath, proxyPort))
  213816. return false;
  213817. host = gethostbyname (proxyName.toUTF8());
  213818. port = proxyPort;
  213819. }
  213820. else
  213821. {
  213822. host = gethostbyname (hostName.toUTF8());
  213823. port = hostPort;
  213824. }
  213825. if (host == 0)
  213826. return false;
  213827. struct sockaddr_in address;
  213828. zerostruct (address);
  213829. memcpy (&address.sin_addr, host->h_addr, host->h_length);
  213830. address.sin_family = host->h_addrtype;
  213831. address.sin_port = htons (port);
  213832. socketHandle = socket (host->h_addrtype, SOCK_STREAM, 0);
  213833. if (socketHandle == -1)
  213834. return false;
  213835. int receiveBufferSize = 16384;
  213836. setsockopt (socketHandle, SOL_SOCKET, SO_RCVBUF, (char*) &receiveBufferSize, sizeof (receiveBufferSize));
  213837. setsockopt (socketHandle, SOL_SOCKET, SO_KEEPALIVE, 0, 0);
  213838. #if JUCE_MAC
  213839. setsockopt (socketHandle, SOL_SOCKET, SO_NOSIGPIPE, 0, 0);
  213840. #endif
  213841. if (connect (socketHandle, (struct sockaddr*) &address, sizeof (address)) == -1)
  213842. {
  213843. closeSocket();
  213844. return false;
  213845. }
  213846. const MemoryBlock requestHeader (createRequestHeader (hostName, hostPort,
  213847. proxyName, proxyPort,
  213848. hostPath, url,
  213849. headers, postData,
  213850. isPost));
  213851. size_t totalHeaderSent = 0;
  213852. while (totalHeaderSent < requestHeader.getSize())
  213853. {
  213854. if (Time::getMillisecondCounter() > timeOutTime)
  213855. {
  213856. closeSocket();
  213857. return false;
  213858. }
  213859. const int numToSend = jmin (1024, (int) (requestHeader.getSize() - totalHeaderSent));
  213860. if (send (socketHandle,
  213861. ((const char*) requestHeader.getData()) + totalHeaderSent,
  213862. numToSend, 0)
  213863. != numToSend)
  213864. {
  213865. closeSocket();
  213866. return false;
  213867. }
  213868. totalHeaderSent += numToSend;
  213869. if (callback != 0 && ! callback (callbackContext, totalHeaderSent, requestHeader.getSize()))
  213870. {
  213871. closeSocket();
  213872. return false;
  213873. }
  213874. }
  213875. const String responseHeader (readResponse (timeOutTime));
  213876. if (responseHeader.isNotEmpty())
  213877. {
  213878. //DBG (responseHeader);
  213879. StringArray lines;
  213880. lines.addLines (responseHeader);
  213881. const int statusCode = responseHeader.fromFirstOccurrenceOf (" ", false, false)
  213882. .substring (0, 3).getIntValue();
  213883. //int contentLength = findHeaderItem (lines, "Content-Length:").getIntValue();
  213884. //bool isChunked = findHeaderItem (lines, "Transfer-Encoding:").equalsIgnoreCase ("chunked");
  213885. String location (findHeaderItem (lines, "Location:"));
  213886. if (statusCode >= 300 && statusCode < 400
  213887. && location.isNotEmpty())
  213888. {
  213889. if (! location.startsWithIgnoreCase ("http://"))
  213890. location = "http://" + location;
  213891. if (levelsOfRedirection++ < 3)
  213892. return open (location, headers, postData, isPost, callback, callbackContext, timeOutMs);
  213893. }
  213894. else
  213895. {
  213896. levelsOfRedirection = 0;
  213897. return true;
  213898. }
  213899. }
  213900. closeSocket();
  213901. return false;
  213902. }
  213903. int read (void* buffer, int bytesToRead)
  213904. {
  213905. fd_set readbits;
  213906. FD_ZERO (&readbits);
  213907. FD_SET (socketHandle, &readbits);
  213908. struct timeval tv;
  213909. tv.tv_sec = timeoutSeconds;
  213910. tv.tv_usec = 0;
  213911. if (select (socketHandle + 1, &readbits, 0, 0, &tv) <= 0)
  213912. return 0; // (timeout)
  213913. const int bytesRead = jmax (0, (int) recv (socketHandle, buffer, bytesToRead, MSG_WAITALL));
  213914. readPosition += bytesRead;
  213915. return bytesRead;
  213916. }
  213917. int readPosition;
  213918. juce_UseDebuggingNewOperator
  213919. private:
  213920. int socketHandle, levelsOfRedirection;
  213921. const int timeoutSeconds;
  213922. void closeSocket()
  213923. {
  213924. if (socketHandle >= 0)
  213925. close (socketHandle);
  213926. socketHandle = -1;
  213927. }
  213928. const MemoryBlock createRequestHeader (const String& hostName,
  213929. const int hostPort,
  213930. const String& proxyName,
  213931. const int proxyPort,
  213932. const String& hostPath,
  213933. const String& originalURL,
  213934. const String& headers,
  213935. const MemoryBlock& postData,
  213936. const bool isPost)
  213937. {
  213938. String header (isPost ? "POST " : "GET ");
  213939. if (proxyName.isEmpty())
  213940. {
  213941. header << hostPath << " HTTP/1.0\r\nHost: "
  213942. << hostName << ':' << hostPort;
  213943. }
  213944. else
  213945. {
  213946. header << originalURL << " HTTP/1.0\r\nHost: "
  213947. << proxyName << ':' << proxyPort;
  213948. }
  213949. header << "\r\nUser-Agent: JUCE/"
  213950. << JUCE_MAJOR_VERSION << '.' << JUCE_MINOR_VERSION
  213951. << "\r\nConnection: Close\r\nContent-Length: "
  213952. << postData.getSize() << "\r\n"
  213953. << headers << "\r\n";
  213954. MemoryBlock mb;
  213955. mb.append (header.toUTF8(), (int) strlen (header.toUTF8()));
  213956. mb.append (postData.getData(), postData.getSize());
  213957. return mb;
  213958. }
  213959. const String readResponse (const uint32 timeOutTime)
  213960. {
  213961. int bytesRead = 0, numConsecutiveLFs = 0;
  213962. MemoryBlock buffer (1024, true);
  213963. while (numConsecutiveLFs < 2 && bytesRead < 32768
  213964. && Time::getMillisecondCounter() <= timeOutTime)
  213965. {
  213966. fd_set readbits;
  213967. FD_ZERO (&readbits);
  213968. FD_SET (socketHandle, &readbits);
  213969. struct timeval tv;
  213970. tv.tv_sec = timeoutSeconds;
  213971. tv.tv_usec = 0;
  213972. if (select (socketHandle + 1, &readbits, 0, 0, &tv) <= 0)
  213973. return String::empty; // (timeout)
  213974. buffer.ensureSize (bytesRead + 8, true);
  213975. char* const dest = (char*) buffer.getData() + bytesRead;
  213976. if (recv (socketHandle, dest, 1, 0) == -1)
  213977. return String::empty;
  213978. const char lastByte = *dest;
  213979. ++bytesRead;
  213980. if (lastByte == '\n')
  213981. ++numConsecutiveLFs;
  213982. else if (lastByte != '\r')
  213983. numConsecutiveLFs = 0;
  213984. }
  213985. const String header (String::fromUTF8 ((const char*) buffer.getData()));
  213986. if (header.startsWithIgnoreCase ("HTTP/"))
  213987. return header.trimEnd();
  213988. return String::empty;
  213989. }
  213990. static bool decomposeURL (const String& url,
  213991. String& host, String& path, int& port)
  213992. {
  213993. if (! url.startsWithIgnoreCase ("http://"))
  213994. return false;
  213995. const int nextSlash = url.indexOfChar (7, '/');
  213996. int nextColon = url.indexOfChar (7, ':');
  213997. if (nextColon > nextSlash && nextSlash > 0)
  213998. nextColon = -1;
  213999. if (nextColon >= 0)
  214000. {
  214001. host = url.substring (7, nextColon);
  214002. if (nextSlash >= 0)
  214003. port = url.substring (nextColon + 1, nextSlash).getIntValue();
  214004. else
  214005. port = url.substring (nextColon + 1).getIntValue();
  214006. }
  214007. else
  214008. {
  214009. port = 80;
  214010. if (nextSlash >= 0)
  214011. host = url.substring (7, nextSlash);
  214012. else
  214013. host = url.substring (7);
  214014. }
  214015. if (nextSlash >= 0)
  214016. path = url.substring (nextSlash);
  214017. else
  214018. path = "/";
  214019. return true;
  214020. }
  214021. static const String findHeaderItem (const StringArray& lines, const String& itemName)
  214022. {
  214023. for (int i = 0; i < lines.size(); ++i)
  214024. if (lines[i].startsWithIgnoreCase (itemName))
  214025. return lines[i].substring (itemName.length()).trim();
  214026. return String::empty;
  214027. }
  214028. };
  214029. void* juce_openInternetFile (const String& url,
  214030. const String& headers,
  214031. const MemoryBlock& postData,
  214032. const bool isPost,
  214033. URL::OpenStreamProgressCallback* callback,
  214034. void* callbackContext,
  214035. int timeOutMs)
  214036. {
  214037. JUCE_HTTPSocketStream* const s = new JUCE_HTTPSocketStream();
  214038. if (s->open (url, headers, postData, isPost,
  214039. callback, callbackContext, timeOutMs))
  214040. return s;
  214041. delete s;
  214042. return 0;
  214043. }
  214044. void juce_closeInternetFile (void* handle)
  214045. {
  214046. delete static_cast <JUCE_HTTPSocketStream*> (handle);
  214047. }
  214048. int juce_readFromInternetFile (void* handle, void* buffer, int bytesToRead)
  214049. {
  214050. JUCE_HTTPSocketStream* const s = (JUCE_HTTPSocketStream*) handle;
  214051. if (s != 0)
  214052. return s->read (buffer, bytesToRead);
  214053. return 0;
  214054. }
  214055. int64 juce_getInternetFileContentLength (void* handle)
  214056. {
  214057. JUCE_HTTPSocketStream* const s = (JUCE_HTTPSocketStream*) handle;
  214058. if (s != 0)
  214059. {
  214060. //xxx todo
  214061. jassertfalse
  214062. }
  214063. return -1;
  214064. }
  214065. int juce_seekInInternetFile (void* handle, int newPosition)
  214066. {
  214067. JUCE_HTTPSocketStream* const s = (JUCE_HTTPSocketStream*) handle;
  214068. if (s != 0)
  214069. return s->readPosition;
  214070. return 0;
  214071. }
  214072. #endif
  214073. /*** End of inlined file: juce_linux_Network.cpp ***/
  214074. /*** Start of inlined file: juce_linux_SystemStats.cpp ***/
  214075. // (This file gets included by juce_linux_NativeCode.cpp, rather than being
  214076. // compiled on its own).
  214077. #if JUCE_INCLUDED_FILE
  214078. void Logger::outputDebugString (const String& text) throw()
  214079. {
  214080. std::cerr << text << std::endl;
  214081. }
  214082. SystemStats::OperatingSystemType SystemStats::getOperatingSystemType() throw()
  214083. {
  214084. return Linux;
  214085. }
  214086. const String SystemStats::getOperatingSystemName() throw()
  214087. {
  214088. return "Linux";
  214089. }
  214090. bool SystemStats::isOperatingSystem64Bit() throw()
  214091. {
  214092. #if JUCE_64BIT
  214093. return true;
  214094. #else
  214095. //xxx not sure how to find this out?..
  214096. return false;
  214097. #endif
  214098. }
  214099. static const String getCpuInfo (const char* key, bool lastOne = false) throw()
  214100. {
  214101. String info;
  214102. char buf [256];
  214103. FILE* f = fopen ("/proc/cpuinfo", "r");
  214104. while (f != 0 && fgets (buf, sizeof(buf), f))
  214105. {
  214106. if (strncmp (buf, key, strlen (key)) == 0)
  214107. {
  214108. char* p = buf;
  214109. while (*p && *p != '\n')
  214110. ++p;
  214111. if (*p != 0)
  214112. *p = 0;
  214113. p = buf;
  214114. while (*p != 0 && *p != ':')
  214115. ++p;
  214116. if (*p != 0 && *(p + 1) != 0)
  214117. info = p + 2;
  214118. if (! lastOne)
  214119. break;
  214120. }
  214121. }
  214122. fclose (f);
  214123. return info;
  214124. }
  214125. bool SystemStats::hasMMX() throw()
  214126. {
  214127. return getCpuInfo ("flags").contains ("mmx");
  214128. }
  214129. bool SystemStats::hasSSE() throw()
  214130. {
  214131. return getCpuInfo ("flags").contains ("sse");
  214132. }
  214133. bool SystemStats::hasSSE2() throw()
  214134. {
  214135. return getCpuInfo ("flags").contains ("sse2");
  214136. }
  214137. bool SystemStats::has3DNow() throw()
  214138. {
  214139. return getCpuInfo ("flags").contains ("3dnow");
  214140. }
  214141. const String SystemStats::getCpuVendor() throw()
  214142. {
  214143. return getCpuInfo ("vendor_id");
  214144. }
  214145. int SystemStats::getCpuSpeedInMegaherz() throw()
  214146. {
  214147. const String speed (getCpuInfo ("cpu MHz"));
  214148. return (int) (speed.getFloatValue() + 0.5f);
  214149. }
  214150. int SystemStats::getMemorySizeInMegabytes() throw()
  214151. {
  214152. struct sysinfo sysi;
  214153. if (sysinfo (&sysi) == 0)
  214154. return (sysi.totalram * sysi.mem_unit / (1024 * 1024));
  214155. return 0;
  214156. }
  214157. uint32 juce_millisecondsSinceStartup() throw()
  214158. {
  214159. static unsigned int calibrate = 0;
  214160. static bool calibrated = false;
  214161. timeval t;
  214162. unsigned int ret = 0;
  214163. if (! gettimeofday (&t, 0))
  214164. {
  214165. if (! calibrated)
  214166. {
  214167. struct sysinfo sysi;
  214168. if (sysinfo (&sysi) == 0)
  214169. // Safe to assume system was not brought up earlier than 1970!
  214170. calibrate = t.tv_sec - sysi.uptime;
  214171. calibrated = true;
  214172. }
  214173. ret = 1000 * (t.tv_sec - calibrate) + (t.tv_usec / 1000);
  214174. }
  214175. return ret;
  214176. }
  214177. double Time::getMillisecondCounterHiRes() throw()
  214178. {
  214179. return getHighResolutionTicks() * 0.001;
  214180. }
  214181. int64 Time::getHighResolutionTicks() throw()
  214182. {
  214183. timeval t;
  214184. if (gettimeofday (&t, 0))
  214185. return 0;
  214186. return ((int64) t.tv_sec * (int64) 1000000) + (int64) t.tv_usec;
  214187. }
  214188. int64 Time::getHighResolutionTicksPerSecond() throw()
  214189. {
  214190. // Microseconds
  214191. return 1000000;
  214192. }
  214193. bool Time::setSystemTimeToThisTime() const throw()
  214194. {
  214195. timeval t;
  214196. t.tv_sec = millisSinceEpoch % 1000000;
  214197. t.tv_usec = millisSinceEpoch - t.tv_sec;
  214198. return settimeofday (&t, NULL) ? false : true;
  214199. }
  214200. int SystemStats::getPageSize() throw()
  214201. {
  214202. static int systemPageSize = 0;
  214203. if (systemPageSize == 0)
  214204. systemPageSize = sysconf (_SC_PAGESIZE);
  214205. return systemPageSize;
  214206. }
  214207. int SystemStats::getNumCpus() throw()
  214208. {
  214209. const int lastCpu = getCpuInfo ("processor", true).getIntValue();
  214210. return lastCpu + 1;
  214211. }
  214212. const String SystemStats::getLogonName()
  214213. {
  214214. const char* user = getenv ("USER");
  214215. if (user == 0)
  214216. {
  214217. struct passwd* const pw = getpwuid (getuid());
  214218. if (pw != 0)
  214219. user = pw->pw_name;
  214220. }
  214221. return String::fromUTF8 (user);
  214222. }
  214223. const String SystemStats::getFullUserName()
  214224. {
  214225. return getLogonName();
  214226. }
  214227. void SystemStats::initialiseStats() throw()
  214228. {
  214229. // Process starts off as root when running suid
  214230. Process::lowerPrivilege();
  214231. String s (SystemStats::getJUCEVersion());
  214232. }
  214233. void PlatformUtilities::fpuReset()
  214234. {
  214235. }
  214236. #endif
  214237. /*** End of inlined file: juce_linux_SystemStats.cpp ***/
  214238. /*** Start of inlined file: juce_linux_Threads.cpp ***/
  214239. // (This file gets included by juce_linux_NativeCode.cpp, rather than being
  214240. // compiled on its own).
  214241. #if JUCE_INCLUDED_FILE
  214242. /*
  214243. Note that a lot of methods that you'd expect to find in this file actually
  214244. live in juce_posix_SharedCode.h!
  214245. */
  214246. void JUCE_API juce_threadEntryPoint (void*);
  214247. void* threadEntryProc (void* value)
  214248. {
  214249. // New threads start off as root when running suid
  214250. Process::lowerPrivilege();
  214251. juce_threadEntryPoint (value);
  214252. return 0;
  214253. }
  214254. void* juce_createThread (void* userData)
  214255. {
  214256. pthread_t handle = 0;
  214257. if (pthread_create (&handle, 0, threadEntryProc, userData) == 0)
  214258. {
  214259. pthread_detach (handle);
  214260. return (void*) handle;
  214261. }
  214262. return 0;
  214263. }
  214264. void juce_killThread (void* handle)
  214265. {
  214266. if (handle != 0)
  214267. pthread_cancel ((pthread_t)handle);
  214268. }
  214269. void juce_setCurrentThreadName (const String& /*name*/)
  214270. {
  214271. }
  214272. Thread::ThreadID Thread::getCurrentThreadId()
  214273. {
  214274. return (ThreadID) pthread_self();
  214275. }
  214276. /*
  214277. * This is all a bit non-ideal... the trouble is that on Linux you
  214278. * need to call setpriority to affect the dynamic priority for
  214279. * non-realtime processes, but this requires the pid, which is not
  214280. * accessible from the pthread_t. We could get it by calling getpid
  214281. * once each thread has started, but then we would need a list of
  214282. * running threads etc etc.
  214283. * Also there is no such thing as IDLE priority on Linux.
  214284. * For the moment, map idle, low and normal process priorities to
  214285. * SCHED_OTHER, with the thread priority ignored for these classes.
  214286. * Map high priority processes to the lower half of the SCHED_RR
  214287. * range, and realtime to the upper half
  214288. */
  214289. // priority 1 to 10 where 5=normal, 1=low. If the handle is 0, sets the
  214290. // priority of the current thread
  214291. bool juce_setThreadPriority (void* handle, int priority)
  214292. {
  214293. struct sched_param param;
  214294. int policy, maxp, minp, pri;
  214295. if (handle == 0)
  214296. handle = (void*) pthread_self();
  214297. if (pthread_getschedparam ((pthread_t) handle, &policy, &param) == 0
  214298. && policy != SCHED_OTHER)
  214299. {
  214300. minp = sched_get_priority_min(policy);
  214301. maxp = sched_get_priority_max(policy);
  214302. pri = ((maxp - minp) / 2) * (priority - 1) / 9;
  214303. if (param.__sched_priority >= (minp + (maxp - minp) / 2))
  214304. // Realtime process priority
  214305. param.__sched_priority = minp + ((maxp - minp) / 2) + pri;
  214306. else
  214307. // High process priority
  214308. param.__sched_priority = minp + pri;
  214309. param.sched_priority = jlimit (1, 127, 1 + (priority * 126) / 11);
  214310. return pthread_setschedparam ((pthread_t) handle, policy, &param) == 0;
  214311. }
  214312. return false;
  214313. }
  214314. void Thread::setCurrentThreadAffinityMask (const uint32 affinityMask)
  214315. {
  214316. #if SUPPORT_AFFINITIES
  214317. cpu_set_t affinity;
  214318. CPU_ZERO (&affinity);
  214319. for (int i = 0; i < 32; ++i)
  214320. if ((affinityMask & (1 << i)) != 0)
  214321. CPU_SET (i, &affinity);
  214322. /*
  214323. N.B. If this line causes a compile error, then you've probably not got the latest
  214324. version of glibc installed.
  214325. If you don't want to update your copy of glibc and don't care about cpu affinities,
  214326. then you can just disable all this stuff by removing the SUPPORT_AFFINITIES macro
  214327. from the linuxincludes.h file.
  214328. */
  214329. sched_setaffinity (getpid(), sizeof (cpu_set_t), &affinity);
  214330. sched_yield();
  214331. #else
  214332. /* affinities aren't supported because either the appropriate header files weren't found,
  214333. or the SUPPORT_AFFINITIES macro was turned off in linuxheaders.h
  214334. */
  214335. jassertfalse
  214336. #endif
  214337. }
  214338. void Thread::yield()
  214339. {
  214340. sched_yield();
  214341. }
  214342. // sets the process to 0=low priority, 1=normal, 2=high, 3=realtime
  214343. void Process::setPriority (ProcessPriority prior)
  214344. {
  214345. struct sched_param param;
  214346. int policy, maxp, minp;
  214347. const int p = (int) prior;
  214348. if (p <= 1)
  214349. policy = SCHED_OTHER;
  214350. else
  214351. policy = SCHED_RR;
  214352. minp = sched_get_priority_min (policy);
  214353. maxp = sched_get_priority_max (policy);
  214354. if (p < 2)
  214355. param.__sched_priority = 0;
  214356. else if (p == 2 )
  214357. // Set to middle of lower realtime priority range
  214358. param.__sched_priority = minp + (maxp - minp) / 4;
  214359. else
  214360. // Set to middle of higher realtime priority range
  214361. param.__sched_priority = minp + (3 * (maxp - minp) / 4);
  214362. pthread_setschedparam (pthread_self(), policy, &param);
  214363. }
  214364. void Process::terminate()
  214365. {
  214366. exit (0);
  214367. }
  214368. bool JUCE_PUBLIC_FUNCTION juce_isRunningUnderDebugger()
  214369. {
  214370. static char testResult = 0;
  214371. if (testResult == 0)
  214372. {
  214373. testResult = (char) ptrace (PT_TRACE_ME, 0, 0, 0);
  214374. if (testResult >= 0)
  214375. {
  214376. ptrace (PT_DETACH, 0, (caddr_t) 1, 0);
  214377. testResult = 1;
  214378. }
  214379. }
  214380. return testResult < 0;
  214381. }
  214382. bool JUCE_CALLTYPE Process::isRunningUnderDebugger()
  214383. {
  214384. return juce_isRunningUnderDebugger();
  214385. }
  214386. void Process::raisePrivilege()
  214387. {
  214388. // If running suid root, change effective user
  214389. // to root
  214390. if (geteuid() != 0 && getuid() == 0)
  214391. {
  214392. setreuid (geteuid(), getuid());
  214393. setregid (getegid(), getgid());
  214394. }
  214395. }
  214396. void Process::lowerPrivilege()
  214397. {
  214398. // If runing suid root, change effective user
  214399. // back to real user
  214400. if (geteuid() == 0 && getuid() != 0)
  214401. {
  214402. setreuid (geteuid(), getuid());
  214403. setregid (getegid(), getgid());
  214404. }
  214405. }
  214406. #if ! JUCE_ONLY_BUILD_CORE_LIBRARY
  214407. void* PlatformUtilities::loadDynamicLibrary (const String& name)
  214408. {
  214409. return dlopen (name.toUTF8(), RTLD_LOCAL | RTLD_NOW);
  214410. }
  214411. void PlatformUtilities::freeDynamicLibrary (void* handle)
  214412. {
  214413. dlclose(handle);
  214414. }
  214415. void* PlatformUtilities::getProcedureEntryPoint (void* libraryHandle, const String& procedureName)
  214416. {
  214417. return dlsym (libraryHandle, procedureName.toCString());
  214418. }
  214419. #endif
  214420. #endif
  214421. /*** End of inlined file: juce_linux_Threads.cpp ***/
  214422. #if ! JUCE_ONLY_BUILD_CORE_LIBRARY
  214423. /*** Start of inlined file: juce_linux_Clipboard.cpp ***/
  214424. // (This file gets included by juce_linux_NativeCode.cpp, rather than being
  214425. // compiled on its own).
  214426. #if JUCE_INCLUDED_FILE
  214427. #if JUCE_DEBUG
  214428. #define JUCE_DEBUG_XERRORS 1
  214429. #endif
  214430. extern Display* display;
  214431. extern Window juce_messageWindowHandle;
  214432. static String localClipboardContent;
  214433. static Atom atom_UTF8_STRING;
  214434. static Atom atom_CLIPBOARD;
  214435. static Atom atom_TARGETS;
  214436. static void initSelectionAtoms()
  214437. {
  214438. static bool isInitialised = false;
  214439. if (! isInitialised)
  214440. {
  214441. atom_UTF8_STRING = XInternAtom (display, "UTF8_STRING", False);
  214442. atom_CLIPBOARD = XInternAtom (display, "CLIPBOARD", False);
  214443. atom_TARGETS = XInternAtom (display, "TARGETS", False);
  214444. }
  214445. }
  214446. // Read the content of a window property as either a locale-dependent string or an utf8 string
  214447. // works only for strings shorter than 1000000 bytes
  214448. static String juce_readWindowProperty (Window window, Atom prop,
  214449. Atom fmt, // XA_STRING or UTF8_STRING
  214450. bool deleteAfterReading)
  214451. {
  214452. String returnData;
  214453. char* clipData;
  214454. Atom actualType;
  214455. int actualFormat;
  214456. unsigned long numItems, bytesLeft;
  214457. if (XGetWindowProperty (display, window, prop,
  214458. 0L /* offset */, 1000000 /* length (max) */, False,
  214459. AnyPropertyType /* format */,
  214460. &actualType, &actualFormat, &numItems, &bytesLeft,
  214461. (unsigned char**) &clipData) == Success)
  214462. {
  214463. if (actualType == atom_UTF8_STRING && actualFormat == 8)
  214464. {
  214465. returnData = String::fromUTF8 (clipData, numItems);
  214466. }
  214467. else if (actualType == XA_STRING && actualFormat == 8)
  214468. {
  214469. returnData = String (clipData, numItems);
  214470. }
  214471. if (clipData != 0)
  214472. XFree (clipData);
  214473. jassert (bytesLeft == 0 || numItems == 1000000);
  214474. }
  214475. if (deleteAfterReading)
  214476. XDeleteProperty (display, window, prop);
  214477. return returnData;
  214478. }
  214479. // Send a SelectionRequest to the window owning the selection and waits for its answer (with a timeout) */
  214480. static bool juce_requestSelectionContent (String &selection_content, Atom selection, Atom requested_format)
  214481. {
  214482. Atom property_name = XInternAtom (display, "JUCE_SEL", false);
  214483. // The selection owner will be asked to set the JUCE_SEL property on the
  214484. // juce_messageWindowHandle with the selection content
  214485. XConvertSelection (display, selection, requested_format, property_name,
  214486. juce_messageWindowHandle, CurrentTime);
  214487. int timeoutMs = 200; // will wait at most for 200 ms
  214488. do
  214489. {
  214490. XEvent event;
  214491. if (XCheckTypedWindowEvent (display, juce_messageWindowHandle, SelectionNotify, &event))
  214492. {
  214493. if (event.xselection.property == property_name)
  214494. {
  214495. jassert (event.xselection.requestor == juce_messageWindowHandle);
  214496. selection_content = juce_readWindowProperty (event.xselection.requestor,
  214497. event.xselection.property,
  214498. requested_format, true);
  214499. return true;
  214500. }
  214501. else
  214502. {
  214503. return false; // the format we asked for was denied.. (event.xselection.property == None)
  214504. }
  214505. }
  214506. // not very elegant.. we could do a select() or something like that...
  214507. // however clipboard content requesting is inherently slow on x11, it
  214508. // often takes 50ms or more so...
  214509. Thread::sleep (4);
  214510. timeoutMs -= 4;
  214511. }
  214512. while (timeoutMs > 0);
  214513. DBG("timeout for juce_requestSelectionContent");
  214514. return false;
  214515. }
  214516. // Called from the event loop in juce_linux_Messaging in response to SelectionRequest events
  214517. void juce_handleSelectionRequest (XSelectionRequestEvent &evt)
  214518. {
  214519. initSelectionAtoms();
  214520. // the selection content is sent to the target window as a window property
  214521. XSelectionEvent reply;
  214522. reply.type = SelectionNotify;
  214523. reply.display = evt.display;
  214524. reply.requestor = evt.requestor;
  214525. reply.selection = evt.selection;
  214526. reply.target = evt.target;
  214527. reply.property = None; // == "fail"
  214528. reply.time = evt.time;
  214529. HeapBlock <char> data;
  214530. int propertyFormat = 0, numDataItems = 0;
  214531. if (evt.selection == XA_PRIMARY || evt.selection == atom_CLIPBOARD)
  214532. {
  214533. if (evt.target == XA_STRING)
  214534. {
  214535. // format data according to system locale
  214536. numDataItems = localClipboardContent.getNumBytesAsCString() + 1;
  214537. data.calloc (numDataItems + 1);
  214538. localClipboardContent.copyToCString (data, numDataItems);
  214539. propertyFormat = 8; // bits/item
  214540. }
  214541. else if (evt.target == atom_UTF8_STRING)
  214542. {
  214543. // translate to utf8
  214544. numDataItems = localClipboardContent.getNumBytesAsUTF8() + 1;
  214545. data.calloc (numDataItems + 1);
  214546. localClipboardContent.copyToUTF8 (data, numDataItems);
  214547. propertyFormat = 8; // bits/item
  214548. }
  214549. else if (evt.target == atom_TARGETS)
  214550. {
  214551. // another application wants to know what we are able to send
  214552. numDataItems = 2;
  214553. propertyFormat = 32; // atoms are 32-bit
  214554. data.calloc (numDataItems * 4);
  214555. Atom* atoms = reinterpret_cast<Atom*> (data.getData());
  214556. atoms[0] = atom_UTF8_STRING;
  214557. atoms[1] = XA_STRING;
  214558. }
  214559. }
  214560. else
  214561. {
  214562. DBG ("requested unsupported clipboard");
  214563. }
  214564. if (data != 0)
  214565. {
  214566. const int maxReasonableSelectionSize = 1000000;
  214567. // for very big chunks of data, we should use the "INCR" protocol , which is a pain in the *ss
  214568. if (evt.property != None && numDataItems < maxReasonableSelectionSize)
  214569. {
  214570. XChangeProperty (evt.display, evt.requestor,
  214571. evt.property, evt.target,
  214572. propertyFormat /* 8 or 32 */, PropModeReplace,
  214573. reinterpret_cast<const unsigned char*> (data.getData()), numDataItems);
  214574. reply.property = evt.property; // " == success"
  214575. }
  214576. }
  214577. XSendEvent (evt.display, evt.requestor, 0, NoEventMask, (XEvent*) &reply);
  214578. }
  214579. void SystemClipboard::copyTextToClipboard (const String& clipText)
  214580. {
  214581. initSelectionAtoms();
  214582. localClipboardContent = clipText;
  214583. XSetSelectionOwner (display, XA_PRIMARY, juce_messageWindowHandle, CurrentTime);
  214584. XSetSelectionOwner (display, atom_CLIPBOARD, juce_messageWindowHandle, CurrentTime);
  214585. }
  214586. const String SystemClipboard::getTextFromClipboard()
  214587. {
  214588. initSelectionAtoms();
  214589. /* 1) try to read from the "CLIPBOARD" selection first (the "high
  214590. level" clipboard that is supposed to be filled by ctrl-C
  214591. etc). When a clipboard manager is running, the content of this
  214592. selection is preserved even when the original selection owner
  214593. exits.
  214594. 2) and then try to read from "PRIMARY" selection (the "legacy" selection
  214595. filled by good old x11 apps such as xterm)
  214596. */
  214597. String content;
  214598. Atom selection = XA_PRIMARY;
  214599. Window selectionOwner = None;
  214600. if ((selectionOwner = XGetSelectionOwner (display, selection)) == None)
  214601. {
  214602. selection = atom_CLIPBOARD;
  214603. selectionOwner = XGetSelectionOwner (display, selection);
  214604. }
  214605. if (selectionOwner != None)
  214606. {
  214607. if (selectionOwner == juce_messageWindowHandle)
  214608. {
  214609. content = localClipboardContent;
  214610. }
  214611. else
  214612. {
  214613. // first try: we want an utf8 string
  214614. bool ok = juce_requestSelectionContent (content, selection, atom_UTF8_STRING);
  214615. if (! ok)
  214616. {
  214617. // second chance, ask for a good old locale-dependent string ..
  214618. ok = juce_requestSelectionContent (content, selection, XA_STRING);
  214619. }
  214620. }
  214621. }
  214622. return content;
  214623. }
  214624. #endif
  214625. /*** End of inlined file: juce_linux_Clipboard.cpp ***/
  214626. /*** Start of inlined file: juce_linux_Messaging.cpp ***/
  214627. // (This file gets included by juce_linux_NativeCode.cpp, rather than being
  214628. // compiled on its own).
  214629. #if JUCE_INCLUDED_FILE
  214630. #if JUCE_DEBUG && ! defined (JUCE_DEBUG_XERRORS)
  214631. #define JUCE_DEBUG_XERRORS 1
  214632. #endif
  214633. Display* display = 0; // This is also referenced from WindowDriver.cpp
  214634. Window juce_messageWindowHandle = None;
  214635. XContext windowHandleXContext; // This is referenced from Windowing.cpp
  214636. extern void juce_windowMessageReceive (XEvent* event); // Defined in Windowing.cpp
  214637. extern void juce_handleSelectionRequest (XSelectionRequestEvent &evt); // Defined in Clipboard.cpp
  214638. ScopedXLock::ScopedXLock() { XLockDisplay (display); }
  214639. ScopedXLock::~ScopedXLock() { XUnlockDisplay (display); }
  214640. class InternalMessageQueue
  214641. {
  214642. public:
  214643. InternalMessageQueue()
  214644. : bytesInSocket (0)
  214645. {
  214646. int ret = ::socketpair (AF_LOCAL, SOCK_STREAM, 0, fd);
  214647. (void) ret; jassert (ret == 0);
  214648. //setNonBlocking (fd[0]);
  214649. //setNonBlocking (fd[1]);
  214650. }
  214651. ~InternalMessageQueue()
  214652. {
  214653. close (fd[0]);
  214654. close (fd[1]);
  214655. }
  214656. void postMessage (Message* msg)
  214657. {
  214658. const int maxBytesInSocketQueue = 128;
  214659. ScopedLock sl (lock);
  214660. queue.add (msg);
  214661. if (bytesInSocket < maxBytesInSocketQueue)
  214662. {
  214663. ++bytesInSocket;
  214664. ScopedUnlock ul (lock);
  214665. const unsigned char x = 0xff;
  214666. size_t bytesWritten = write (fd[0], &x, 1);
  214667. (void) bytesWritten;
  214668. }
  214669. }
  214670. bool isEmpty() const
  214671. {
  214672. ScopedLock sl (lock);
  214673. return queue.size() == 0;
  214674. }
  214675. Message* popNextMessage()
  214676. {
  214677. ScopedLock sl (lock);
  214678. if (bytesInSocket > 0)
  214679. {
  214680. --bytesInSocket;
  214681. ScopedUnlock ul (lock);
  214682. unsigned char x;
  214683. size_t numBytes = read (fd[1], &x, 1);
  214684. (void) numBytes;
  214685. }
  214686. Message* m = queue[0];
  214687. queue.remove (0, false /* deleteObject */);
  214688. return m;
  214689. }
  214690. int getWaitHandle() const { return fd[1]; }
  214691. private:
  214692. CriticalSection lock;
  214693. OwnedArray <Message> queue;
  214694. int fd[2];
  214695. int bytesInSocket;
  214696. static bool setNonBlocking (int handle)
  214697. {
  214698. int socketFlags = fcntl (handle, F_GETFL, 0);
  214699. if (socketFlags == -1)
  214700. return false;
  214701. socketFlags |= O_NONBLOCK;
  214702. return fcntl (handle, F_SETFL, socketFlags) == 0;
  214703. }
  214704. };
  214705. struct MessageThreadFuncCall
  214706. {
  214707. enum { uniqueID = 0x73774623 };
  214708. MessageCallbackFunction* func;
  214709. void* parameter;
  214710. void* result;
  214711. CriticalSection lock;
  214712. WaitableEvent event;
  214713. };
  214714. static InternalMessageQueue* juce_internalMessageQueue = 0;
  214715. // error handling in X11
  214716. static bool errorOccurred = false;
  214717. static bool keyboardBreakOccurred = false;
  214718. static XErrorHandler oldErrorHandler = (XErrorHandler) 0;
  214719. static XIOErrorHandler oldIOErrorHandler = (XIOErrorHandler) 0;
  214720. // Usually happens when client-server connection is broken
  214721. static int ioErrorHandler (Display* display)
  214722. {
  214723. DBG ("ERROR: connection to X server broken.. terminating.");
  214724. errorOccurred = true;
  214725. if (JUCEApplication::getInstance() != 0)
  214726. Process::terminate();
  214727. return 0;
  214728. }
  214729. // A protocol error has occurred
  214730. static int errorHandler (Display* display, XErrorEvent* event)
  214731. {
  214732. #if JUCE_DEBUG_XERRORS
  214733. char errorStr[64] = { 0 };
  214734. char requestStr[64] = { 0 };
  214735. XGetErrorText (display, event->error_code, errorStr, 64);
  214736. XGetErrorDatabaseText (display, "XRequest", String (event->request_code).toCString(),
  214737. "Unknown", requestStr, 64);
  214738. DBG ("ERROR: X returned " + String (errorStr) + " for operation " + String (requestStr));
  214739. #endif
  214740. return 0;
  214741. }
  214742. // Breakin from keyboard
  214743. static void signalHandler (int sig)
  214744. {
  214745. if (sig == SIGINT)
  214746. {
  214747. keyboardBreakOccurred = true;
  214748. return;
  214749. }
  214750. static bool reentrant = false;
  214751. if (! reentrant)
  214752. {
  214753. reentrant = true;
  214754. // Illegal instruction
  214755. fflush (stdout);
  214756. Logger::outputDebugString ("ERROR: Program executed illegal instruction.. terminating");
  214757. errorOccurred = true;
  214758. if (JUCEApplication::getInstance() != 0)
  214759. Process::terminate();
  214760. }
  214761. else
  214762. {
  214763. if (JUCEApplication::getInstance() != 0)
  214764. exit(0);
  214765. }
  214766. }
  214767. void MessageManager::doPlatformSpecificInitialisation()
  214768. {
  214769. // Initialise xlib for multiple thread support
  214770. static bool initThreadCalled = false;
  214771. if (! initThreadCalled)
  214772. {
  214773. if (! XInitThreads())
  214774. {
  214775. // This is fatal! Print error and closedown
  214776. Logger::outputDebugString ("Failed to initialise xlib thread support.");
  214777. if (JUCEApplication::getInstance() != 0)
  214778. Process::terminate();
  214779. return;
  214780. }
  214781. initThreadCalled = true;
  214782. }
  214783. // This is called if the client/server connection is broken
  214784. oldIOErrorHandler = XSetIOErrorHandler (ioErrorHandler);
  214785. // This is called if a protocol error occurs
  214786. oldErrorHandler = XSetErrorHandler (errorHandler);
  214787. // Install signal handler for break-in
  214788. struct sigaction saction;
  214789. sigset_t maskSet;
  214790. sigemptyset (&maskSet);
  214791. saction.sa_handler = signalHandler;
  214792. saction.sa_mask = maskSet;
  214793. saction.sa_flags = 0;
  214794. sigaction (SIGINT, &saction, NULL);
  214795. #ifndef _DEBUG
  214796. // Setup signal handlers for various fatal errors
  214797. sigaction (SIGILL, &saction, NULL);
  214798. sigaction (SIGBUS, &saction, NULL);
  214799. sigaction (SIGFPE, &saction, NULL);
  214800. sigaction (SIGSEGV, &saction, NULL);
  214801. sigaction (SIGSYS, &saction, NULL);
  214802. #endif
  214803. // Create the internal message queue
  214804. juce_internalMessageQueue = new InternalMessageQueue();
  214805. // Try to connect to a display
  214806. String displayName (getenv ("DISPLAY"));
  214807. if (displayName.isEmpty())
  214808. displayName = ":0.0";
  214809. display = XOpenDisplay (displayName.toCString());
  214810. if (display == 0)
  214811. {
  214812. // This is not fatal! we can run headless.
  214813. return;
  214814. }
  214815. // Get defaults for various properties
  214816. int screen = DefaultScreen (display);
  214817. Window root = RootWindow (display, screen);
  214818. Visual* visual = DefaultVisual (display, screen);
  214819. // Create a context to store user data associated with Windows we
  214820. // create in WindowDriver
  214821. windowHandleXContext = XUniqueContext();
  214822. // We're only interested in client messages for this window
  214823. // which are always sent
  214824. XSetWindowAttributes swa;
  214825. swa.event_mask = NoEventMask;
  214826. // Create our message window (this will never be mapped)
  214827. juce_messageWindowHandle = XCreateWindow (display, root,
  214828. 0, 0, 1, 1, 0, 0, InputOnly,
  214829. visual, CWEventMask, &swa);
  214830. }
  214831. void MessageManager::doPlatformSpecificShutdown()
  214832. {
  214833. deleteAndZero (juce_internalMessageQueue);
  214834. if (display != 0 && ! errorOccurred)
  214835. {
  214836. XDestroyWindow (display, juce_messageWindowHandle);
  214837. XCloseDisplay (display);
  214838. // reset pointers
  214839. juce_messageWindowHandle = 0;
  214840. display = 0;
  214841. // Restore original error handlers
  214842. XSetIOErrorHandler (oldIOErrorHandler);
  214843. oldIOErrorHandler = 0;
  214844. XSetErrorHandler (oldErrorHandler);
  214845. oldErrorHandler = 0;
  214846. }
  214847. }
  214848. bool juce_postMessageToSystemQueue (void* message)
  214849. {
  214850. if (errorOccurred)
  214851. return false;
  214852. juce_internalMessageQueue->postMessage ((Message*) message);
  214853. return true;
  214854. }
  214855. void MessageManager::broadcastMessage (const String& value) throw()
  214856. {
  214857. /* TODO */
  214858. }
  214859. void* MessageManager::callFunctionOnMessageThread (MessageCallbackFunction* func,
  214860. void* parameter)
  214861. {
  214862. if (errorOccurred)
  214863. return 0;
  214864. if (! isThisTheMessageThread())
  214865. {
  214866. MessageThreadFuncCall messageCallContext;
  214867. messageCallContext.func = func;
  214868. messageCallContext.parameter = parameter;
  214869. juce_internalMessageQueue->postMessage (new Message (MessageThreadFuncCall::uniqueID,
  214870. 0, 0, &messageCallContext));
  214871. // Wait for it to complete before continuing
  214872. messageCallContext.event.wait();
  214873. return messageCallContext.result;
  214874. }
  214875. else
  214876. {
  214877. // Just call the function directly
  214878. return func (parameter);
  214879. }
  214880. }
  214881. // Wait for an event (either XEvent, or an internal Message)
  214882. static bool juce_sleepUntilEvent (const int timeoutMs)
  214883. {
  214884. if (! juce_internalMessageQueue->isEmpty())
  214885. return true;
  214886. if (display != 0)
  214887. {
  214888. ScopedXLock xlock;
  214889. if (XPending (display))
  214890. return true;
  214891. }
  214892. struct timeval tv;
  214893. tv.tv_sec = 0;
  214894. tv.tv_usec = timeoutMs * 1000;
  214895. int fd0 = juce_internalMessageQueue->getWaitHandle();
  214896. int fdmax = fd0;
  214897. fd_set readset;
  214898. FD_ZERO (&readset);
  214899. FD_SET (fd0, &readset);
  214900. if (display != 0)
  214901. {
  214902. ScopedXLock xlock;
  214903. int fd1 = XConnectionNumber (display);
  214904. FD_SET (fd1, &readset);
  214905. fdmax = jmax (fd0, fd1);
  214906. }
  214907. const int ret = select (fdmax + 1, &readset, 0, 0, &tv);
  214908. return (ret > 0); // ret <= 0 if error or timeout
  214909. }
  214910. // Handle next XEvent (if any)
  214911. static bool juce_dispatchNextXEvent()
  214912. {
  214913. if (display == 0)
  214914. return false;
  214915. XEvent evt;
  214916. {
  214917. ScopedXLock xlock;
  214918. if (! XPending (display))
  214919. return false;
  214920. XNextEvent (display, &evt);
  214921. }
  214922. if (evt.type == SelectionRequest && evt.xany.window == juce_messageWindowHandle)
  214923. {
  214924. juce_handleSelectionRequest (evt.xselectionrequest);
  214925. }
  214926. else if (evt.xany.window != juce_messageWindowHandle)
  214927. {
  214928. juce_windowMessageReceive (&evt);
  214929. }
  214930. return true;
  214931. }
  214932. // Handle next internal Message (if any)
  214933. static bool juce_dispatchNextInternalMessage()
  214934. {
  214935. ScopedPointer <Message> msg (juce_internalMessageQueue->popNextMessage());
  214936. if (msg == 0)
  214937. return false;
  214938. if (msg->intParameter1 == MessageThreadFuncCall::uniqueID)
  214939. {
  214940. // Handle callback message
  214941. MessageThreadFuncCall* const call = (MessageThreadFuncCall*) msg->pointerParameter;
  214942. call->result = (*(call->func)) (call->parameter);
  214943. call->event.signal();
  214944. }
  214945. else
  214946. {
  214947. // Handle "normal" messages
  214948. MessageManager::getInstance()->deliverMessage (msg.release());
  214949. }
  214950. return true;
  214951. }
  214952. // this function expects that it will NEVER be called simultaneously for two concurrent threads
  214953. bool juce_dispatchNextMessageOnSystemQueue (bool returnIfNoPendingMessages)
  214954. {
  214955. for (;;)
  214956. {
  214957. if (errorOccurred)
  214958. break;
  214959. if (keyboardBreakOccurred)
  214960. {
  214961. errorOccurred = true;
  214962. if (JUCEApplication::getInstance() != 0)
  214963. Process::terminate();
  214964. break;
  214965. }
  214966. static int totalEventCount = 0;
  214967. ++totalEventCount;
  214968. // The purpose here is to give either priority to XEvents or
  214969. // to internal messages This is necessary to keep a "good"
  214970. // behaviour when the cpu is overloaded
  214971. if (totalEventCount & 1)
  214972. {
  214973. if (juce_dispatchNextXEvent() || juce_dispatchNextInternalMessage())
  214974. return true;
  214975. }
  214976. else
  214977. {
  214978. if (juce_dispatchNextInternalMessage() || juce_dispatchNextXEvent())
  214979. return true;
  214980. }
  214981. if (returnIfNoPendingMessages) // early exit
  214982. break;
  214983. // the timeout is to be on the safe side, but it does not seem to be useful
  214984. juce_sleepUntilEvent (2000);
  214985. }
  214986. return false;
  214987. }
  214988. #endif
  214989. /*** End of inlined file: juce_linux_Messaging.cpp ***/
  214990. /*** Start of inlined file: juce_linux_Fonts.cpp ***/
  214991. // (This file gets included by juce_linux_NativeCode.cpp, rather than being
  214992. // compiled on its own).
  214993. #if JUCE_INCLUDED_FILE
  214994. class FreeTypeFontFace
  214995. {
  214996. public:
  214997. enum FontStyle
  214998. {
  214999. Plain = 0,
  215000. Bold = 1,
  215001. Italic = 2
  215002. };
  215003. struct FontNameIndex
  215004. {
  215005. String fileName;
  215006. int faceIndex;
  215007. };
  215008. FreeTypeFontFace (const String& familyName)
  215009. : hasSerif (false),
  215010. monospaced (false)
  215011. {
  215012. family = familyName;
  215013. }
  215014. void setFileName (const String& name, const int faceIndex, FontStyle style)
  215015. {
  215016. if (names [(int) style].fileName.isEmpty())
  215017. {
  215018. names [(int) style].fileName = name;
  215019. names [(int) style].faceIndex = faceIndex;
  215020. }
  215021. }
  215022. const String& getFamilyName() const throw() { return family; }
  215023. const String& getFileName (const int style, int& faceIndex) const throw()
  215024. {
  215025. faceIndex = names[style].faceIndex;
  215026. return names[style].fileName;
  215027. }
  215028. void setMonospaced (bool mono) throw() { monospaced = mono; }
  215029. bool getMonospaced() const throw() { return monospaced; }
  215030. void setSerif (const bool serif) throw() { hasSerif = serif; }
  215031. bool getSerif() const throw() { return hasSerif; }
  215032. private:
  215033. String family;
  215034. FontNameIndex names[4];
  215035. bool hasSerif, monospaced;
  215036. };
  215037. class FreeTypeInterface : public DeletedAtShutdown
  215038. {
  215039. public:
  215040. FreeTypeInterface()
  215041. : ftLib (0),
  215042. lastFace (0),
  215043. lastBold (false),
  215044. lastItalic (false)
  215045. {
  215046. if (FT_Init_FreeType (&ftLib) != 0)
  215047. {
  215048. ftLib = 0;
  215049. DBG ("Failed to initialize FreeType");
  215050. }
  215051. StringArray fontDirs;
  215052. fontDirs.addTokens (String::fromUTF8 (getenv ("JUCE_FONT_PATH")), ";,", String::empty);
  215053. fontDirs.removeEmptyStrings (true);
  215054. if (fontDirs.size() == 0)
  215055. {
  215056. XmlDocument fontsConfig (File ("/etc/fonts/fonts.conf"));
  215057. const ScopedPointer<XmlElement> fontsInfo (fontsConfig.getDocumentElement());
  215058. if (fontsInfo != 0)
  215059. {
  215060. forEachXmlChildElementWithTagName (*fontsInfo, e, "dir")
  215061. {
  215062. fontDirs.add (e->getAllSubText().trim());
  215063. }
  215064. }
  215065. }
  215066. if (fontDirs.size() == 0)
  215067. fontDirs.add ("/usr/X11R6/lib/X11/fonts");
  215068. for (int i = 0; i < fontDirs.size(); ++i)
  215069. enumerateFaces (fontDirs[i]);
  215070. }
  215071. ~FreeTypeInterface()
  215072. {
  215073. if (lastFace != 0)
  215074. FT_Done_Face (lastFace);
  215075. if (ftLib != 0)
  215076. FT_Done_FreeType (ftLib);
  215077. clearSingletonInstance();
  215078. }
  215079. FreeTypeFontFace* findOrCreate (const String& familyName, const bool create = false)
  215080. {
  215081. for (int i = 0; i < faces.size(); i++)
  215082. if (faces[i]->getFamilyName() == familyName)
  215083. return faces[i];
  215084. if (! create)
  215085. return NULL;
  215086. FreeTypeFontFace* newFace = new FreeTypeFontFace (familyName);
  215087. faces.add (newFace);
  215088. return newFace;
  215089. }
  215090. // Enumerate all font faces available in a given directory
  215091. void enumerateFaces (const String& path)
  215092. {
  215093. File dirPath (path);
  215094. if (path.isEmpty() || ! dirPath.isDirectory())
  215095. return;
  215096. DirectoryIterator di (dirPath, true);
  215097. while (di.next())
  215098. {
  215099. File possible (di.getFile());
  215100. if (possible.hasFileExtension ("ttf")
  215101. || possible.hasFileExtension ("pfb")
  215102. || possible.hasFileExtension ("pcf"))
  215103. {
  215104. FT_Face face;
  215105. int faceIndex = 0;
  215106. int numFaces = 0;
  215107. do
  215108. {
  215109. if (FT_New_Face (ftLib, possible.getFullPathName().toUTF8(),
  215110. faceIndex, &face) == 0)
  215111. {
  215112. if (faceIndex == 0)
  215113. numFaces = face->num_faces;
  215114. if ((face->face_flags & FT_FACE_FLAG_SCALABLE) != 0)
  215115. {
  215116. FreeTypeFontFace* const newFace = findOrCreate (face->family_name, true);
  215117. int style = (int) FreeTypeFontFace::Plain;
  215118. if ((face->style_flags & FT_STYLE_FLAG_BOLD) != 0)
  215119. style |= (int) FreeTypeFontFace::Bold;
  215120. if ((face->style_flags & FT_STYLE_FLAG_ITALIC) != 0)
  215121. style |= (int) FreeTypeFontFace::Italic;
  215122. newFace->setFileName (possible.getFullPathName(), faceIndex, (FreeTypeFontFace::FontStyle) style);
  215123. newFace->setMonospaced ((face->face_flags & FT_FACE_FLAG_FIXED_WIDTH) != 0);
  215124. // Surely there must be a better way to do this?
  215125. const String name (face->family_name);
  215126. newFace->setSerif (! (name.containsIgnoreCase ("Sans")
  215127. || name.containsIgnoreCase ("Verdana")
  215128. || name.containsIgnoreCase ("Arial")));
  215129. }
  215130. FT_Done_Face (face);
  215131. }
  215132. ++faceIndex;
  215133. }
  215134. while (faceIndex < numFaces);
  215135. }
  215136. }
  215137. }
  215138. // Create a FreeType face object for a given font
  215139. FT_Face createFT_Face (const String& fontName, const bool bold, const bool italic)
  215140. {
  215141. FT_Face face = 0;
  215142. if (fontName == lastFontName && bold == lastBold && italic == lastItalic)
  215143. {
  215144. face = lastFace;
  215145. }
  215146. else
  215147. {
  215148. if (lastFace != 0)
  215149. {
  215150. FT_Done_Face (lastFace);
  215151. lastFace = 0;
  215152. }
  215153. lastFontName = fontName;
  215154. lastBold = bold;
  215155. lastItalic = italic;
  215156. FreeTypeFontFace* const ftFace = findOrCreate (fontName);
  215157. if (ftFace != 0)
  215158. {
  215159. int style = (int) FreeTypeFontFace::Plain;
  215160. if (bold)
  215161. style |= (int) FreeTypeFontFace::Bold;
  215162. if (italic)
  215163. style |= (int) FreeTypeFontFace::Italic;
  215164. int faceIndex;
  215165. String fileName (ftFace->getFileName (style, faceIndex));
  215166. if (fileName.isEmpty())
  215167. {
  215168. style ^= (int) FreeTypeFontFace::Bold;
  215169. fileName = ftFace->getFileName (style, faceIndex);
  215170. if (fileName.isEmpty())
  215171. {
  215172. style ^= (int) FreeTypeFontFace::Bold;
  215173. style ^= (int) FreeTypeFontFace::Italic;
  215174. fileName = ftFace->getFileName (style, faceIndex);
  215175. if (! fileName.length())
  215176. {
  215177. style ^= (int) FreeTypeFontFace::Bold;
  215178. fileName = ftFace->getFileName (style, faceIndex);
  215179. }
  215180. }
  215181. }
  215182. if (! FT_New_Face (ftLib, fileName.toUTF8(), faceIndex, &lastFace))
  215183. {
  215184. face = lastFace;
  215185. // If there isn't a unicode charmap then select the first one.
  215186. if (FT_Select_Charmap (face, ft_encoding_unicode))
  215187. FT_Set_Charmap (face, face->charmaps[0]);
  215188. }
  215189. }
  215190. }
  215191. return face;
  215192. }
  215193. bool addGlyph (FT_Face face, CustomTypeface& dest, uint32 character)
  215194. {
  215195. const unsigned int glyphIndex = FT_Get_Char_Index (face, character);
  215196. const float height = (float) (face->ascender - face->descender);
  215197. const float scaleX = 1.0f / height;
  215198. const float scaleY = -1.0f / height;
  215199. Path destShape;
  215200. if (FT_Load_Glyph (face, glyphIndex, FT_LOAD_NO_SCALE | FT_LOAD_NO_BITMAP | FT_LOAD_IGNORE_TRANSFORM) != 0
  215201. || face->glyph->format != ft_glyph_format_outline)
  215202. {
  215203. return false;
  215204. }
  215205. const FT_Outline* const outline = &face->glyph->outline;
  215206. const short* const contours = outline->contours;
  215207. const char* const tags = outline->tags;
  215208. FT_Vector* const points = outline->points;
  215209. for (int c = 0; c < outline->n_contours; c++)
  215210. {
  215211. const int startPoint = (c == 0) ? 0 : contours [c - 1] + 1;
  215212. const int endPoint = contours[c];
  215213. for (int p = startPoint; p <= endPoint; p++)
  215214. {
  215215. const float x = scaleX * points[p].x;
  215216. const float y = scaleY * points[p].y;
  215217. if (p == startPoint)
  215218. {
  215219. if (FT_CURVE_TAG (tags[p]) == FT_Curve_Tag_Conic)
  215220. {
  215221. float x2 = scaleX * points [endPoint].x;
  215222. float y2 = scaleY * points [endPoint].y;
  215223. if (FT_CURVE_TAG (tags[endPoint]) != FT_Curve_Tag_On)
  215224. {
  215225. x2 = (x + x2) * 0.5f;
  215226. y2 = (y + y2) * 0.5f;
  215227. }
  215228. destShape.startNewSubPath (x2, y2);
  215229. }
  215230. else
  215231. {
  215232. destShape.startNewSubPath (x, y);
  215233. }
  215234. }
  215235. if (FT_CURVE_TAG (tags[p]) == FT_Curve_Tag_On)
  215236. {
  215237. if (p != startPoint)
  215238. destShape.lineTo (x, y);
  215239. }
  215240. else if (FT_CURVE_TAG (tags[p]) == FT_Curve_Tag_Conic)
  215241. {
  215242. const int nextIndex = (p == endPoint) ? startPoint : p + 1;
  215243. float x2 = scaleX * points [nextIndex].x;
  215244. float y2 = scaleY * points [nextIndex].y;
  215245. if (FT_CURVE_TAG (tags [nextIndex]) == FT_Curve_Tag_Conic)
  215246. {
  215247. x2 = (x + x2) * 0.5f;
  215248. y2 = (y + y2) * 0.5f;
  215249. }
  215250. else
  215251. {
  215252. ++p;
  215253. }
  215254. destShape.quadraticTo (x, y, x2, y2);
  215255. }
  215256. else if (FT_CURVE_TAG (tags[p]) == FT_Curve_Tag_Cubic)
  215257. {
  215258. if (p >= endPoint)
  215259. return false;
  215260. const int next1 = p + 1;
  215261. const int next2 = (p == (endPoint - 1)) ? startPoint : p + 2;
  215262. const float x2 = scaleX * points [next1].x;
  215263. const float y2 = scaleY * points [next1].y;
  215264. const float x3 = scaleX * points [next2].x;
  215265. const float y3 = scaleY * points [next2].y;
  215266. if (FT_CURVE_TAG (tags[next1]) != FT_Curve_Tag_Cubic
  215267. || FT_CURVE_TAG (tags[next2]) != FT_Curve_Tag_On)
  215268. return false;
  215269. destShape.cubicTo (x, y, x2, y2, x3, y3);
  215270. p += 2;
  215271. }
  215272. }
  215273. destShape.closeSubPath();
  215274. }
  215275. dest.addGlyph (character, destShape, face->glyph->metrics.horiAdvance / height);
  215276. if ((face->face_flags & FT_FACE_FLAG_KERNING) != 0)
  215277. addKerning (face, dest, character, glyphIndex);
  215278. return true;
  215279. }
  215280. void addKerning (FT_Face face, CustomTypeface& dest, const uint32 character, const uint32 glyphIndex)
  215281. {
  215282. const float height = (float) (face->ascender - face->descender);
  215283. uint32 rightGlyphIndex;
  215284. uint32 rightCharCode = FT_Get_First_Char (face, &rightGlyphIndex);
  215285. while (rightGlyphIndex != 0)
  215286. {
  215287. FT_Vector kerning;
  215288. if (FT_Get_Kerning (face, glyphIndex, rightGlyphIndex, ft_kerning_unscaled, &kerning) == 0)
  215289. {
  215290. if (kerning.x != 0)
  215291. dest.addKerningPair (character, rightCharCode, kerning.x / height);
  215292. }
  215293. rightCharCode = FT_Get_Next_Char (face, rightCharCode, &rightGlyphIndex);
  215294. }
  215295. }
  215296. // Add a glyph to a font
  215297. bool addGlyphToFont (const uint32 character, const String& fontName,
  215298. bool bold, bool italic, CustomTypeface& dest)
  215299. {
  215300. FT_Face face = createFT_Face (fontName, bold, italic);
  215301. return face != 0 && addGlyph (face, dest, character);
  215302. }
  215303. void getFamilyNames (StringArray& familyNames) const
  215304. {
  215305. for (int i = 0; i < faces.size(); i++)
  215306. familyNames.add (faces[i]->getFamilyName());
  215307. }
  215308. void getMonospacedNames (StringArray& monoSpaced) const
  215309. {
  215310. for (int i = 0; i < faces.size(); i++)
  215311. if (faces[i]->getMonospaced())
  215312. monoSpaced.add (faces[i]->getFamilyName());
  215313. }
  215314. void getSerifNames (StringArray& serif) const
  215315. {
  215316. for (int i = 0; i < faces.size(); i++)
  215317. if (faces[i]->getSerif())
  215318. serif.add (faces[i]->getFamilyName());
  215319. }
  215320. void getSansSerifNames (StringArray& sansSerif) const
  215321. {
  215322. for (int i = 0; i < faces.size(); i++)
  215323. if (! faces[i]->getSerif())
  215324. sansSerif.add (faces[i]->getFamilyName());
  215325. }
  215326. juce_DeclareSingleton_SingleThreaded_Minimal (FreeTypeInterface)
  215327. private:
  215328. FT_Library ftLib;
  215329. FT_Face lastFace;
  215330. String lastFontName;
  215331. bool lastBold, lastItalic;
  215332. OwnedArray<FreeTypeFontFace> faces;
  215333. };
  215334. juce_ImplementSingleton_SingleThreaded (FreeTypeInterface)
  215335. class FreetypeTypeface : public CustomTypeface
  215336. {
  215337. public:
  215338. FreetypeTypeface (const Font& font)
  215339. {
  215340. FT_Face face = FreeTypeInterface::getInstance()
  215341. ->createFT_Face (font.getTypefaceName(), font.isBold(), font.isItalic());
  215342. if (face == 0)
  215343. {
  215344. #if JUCE_DEBUG
  215345. String msg ("Failed to create typeface: ");
  215346. msg << font.getTypefaceName() << " " << (font.isBold() ? 'B' : ' ') << (font.isItalic() ? 'I' : ' ');
  215347. DBG (msg);
  215348. #endif
  215349. }
  215350. else
  215351. {
  215352. setCharacteristics (font.getTypefaceName(),
  215353. face->ascender / (float) (face->ascender - face->descender),
  215354. font.isBold(), font.isItalic(),
  215355. L' ');
  215356. }
  215357. }
  215358. bool loadGlyphIfPossible (juce_wchar character)
  215359. {
  215360. return FreeTypeInterface::getInstance()
  215361. ->addGlyphToFont (character, name, isBold, isItalic, *this);
  215362. }
  215363. };
  215364. const Typeface::Ptr Typeface::createSystemTypefaceFor (const Font& font)
  215365. {
  215366. return new FreetypeTypeface (font);
  215367. }
  215368. const StringArray Font::findAllTypefaceNames()
  215369. {
  215370. StringArray s;
  215371. FreeTypeInterface::getInstance()->getFamilyNames (s);
  215372. s.sort (true);
  215373. return s;
  215374. }
  215375. static const String pickBestFont (const StringArray& names,
  215376. const char* const choicesString)
  215377. {
  215378. StringArray choices;
  215379. choices.addTokens (String (choicesString), ",", String::empty);
  215380. choices.trim();
  215381. choices.removeEmptyStrings();
  215382. int i, j;
  215383. for (j = 0; j < choices.size(); ++j)
  215384. if (names.contains (choices[j], true))
  215385. return choices[j];
  215386. for (j = 0; j < choices.size(); ++j)
  215387. for (i = 0; i < names.size(); i++)
  215388. if (names[i].startsWithIgnoreCase (choices[j]))
  215389. return names[i];
  215390. for (j = 0; j < choices.size(); ++j)
  215391. for (i = 0; i < names.size(); i++)
  215392. if (names[i].containsIgnoreCase (choices[j]))
  215393. return names[i];
  215394. return names[0];
  215395. }
  215396. static const String linux_getDefaultSansSerifFontName()
  215397. {
  215398. StringArray allFonts;
  215399. FreeTypeInterface::getInstance()->getSansSerifNames (allFonts);
  215400. return pickBestFont (allFonts, "Verdana, Bitstream Vera Sans, Luxi Sans, Sans");
  215401. }
  215402. static const String linux_getDefaultSerifFontName()
  215403. {
  215404. StringArray allFonts;
  215405. FreeTypeInterface::getInstance()->getSerifNames (allFonts);
  215406. return pickBestFont (allFonts, "Bitstream Vera Serif, Times, Nimbus Roman, Serif");
  215407. }
  215408. static const String linux_getDefaultMonospacedFontName()
  215409. {
  215410. StringArray allFonts;
  215411. FreeTypeInterface::getInstance()->getMonospacedNames (allFonts);
  215412. return pickBestFont (allFonts, "Bitstream Vera Sans Mono, Courier, Sans Mono, Mono");
  215413. }
  215414. void Font::getPlatformDefaultFontNames (String& defaultSans, String& defaultSerif, String& defaultFixed)
  215415. {
  215416. defaultSans = linux_getDefaultSansSerifFontName();
  215417. defaultSerif = linux_getDefaultSerifFontName();
  215418. defaultFixed = linux_getDefaultMonospacedFontName();
  215419. }
  215420. #endif
  215421. /*** End of inlined file: juce_linux_Fonts.cpp ***/
  215422. /*** Start of inlined file: juce_linux_Windowing.cpp ***/
  215423. // (This file gets included by juce_linux_NativeCode.cpp, rather than being
  215424. // compiled on its own).
  215425. #if JUCE_INCLUDED_FILE
  215426. // These are defined in juce_linux_Messaging.cpp
  215427. extern Display* display;
  215428. extern XContext windowHandleXContext;
  215429. namespace Atoms
  215430. {
  215431. enum ProtocolItems
  215432. {
  215433. TAKE_FOCUS = 0,
  215434. DELETE_WINDOW = 1,
  215435. PING = 2
  215436. };
  215437. static Atom Protocols, ProtocolList[3], ChangeState, State,
  215438. ActiveWin, Pid, WindowType, WindowState,
  215439. XdndAware, XdndEnter, XdndLeave, XdndPosition, XdndStatus,
  215440. XdndDrop, XdndFinished, XdndSelection, XdndTypeList, XdndActionList,
  215441. XdndActionDescription, XdndActionCopy,
  215442. allowedActions[5],
  215443. allowedMimeTypes[2];
  215444. const unsigned long DndVersion = 3;
  215445. static void initialiseAtoms()
  215446. {
  215447. static bool atomsInitialised = false;
  215448. if (! atomsInitialised)
  215449. {
  215450. atomsInitialised = true;
  215451. Protocols = XInternAtom (display, "WM_PROTOCOLS", True);
  215452. ProtocolList [TAKE_FOCUS] = XInternAtom (display, "WM_TAKE_FOCUS", True);
  215453. ProtocolList [DELETE_WINDOW] = XInternAtom (display, "WM_DELETE_WINDOW", True);
  215454. ProtocolList [PING] = XInternAtom (display, "_NET_WM_PING", True);
  215455. ChangeState = XInternAtom (display, "WM_CHANGE_STATE", True);
  215456. State = XInternAtom (display, "WM_STATE", True);
  215457. ActiveWin = XInternAtom (display, "_NET_ACTIVE_WINDOW", False);
  215458. Pid = XInternAtom (display, "_NET_WM_PID", False);
  215459. WindowType = XInternAtom (display, "_NET_WM_WINDOW_TYPE", True);
  215460. WindowState = XInternAtom (display, "_NET_WM_STATE", True);
  215461. XdndAware = XInternAtom (display, "XdndAware", False);
  215462. XdndEnter = XInternAtom (display, "XdndEnter", False);
  215463. XdndLeave = XInternAtom (display, "XdndLeave", False);
  215464. XdndPosition = XInternAtom (display, "XdndPosition", False);
  215465. XdndStatus = XInternAtom (display, "XdndStatus", False);
  215466. XdndDrop = XInternAtom (display, "XdndDrop", False);
  215467. XdndFinished = XInternAtom (display, "XdndFinished", False);
  215468. XdndSelection = XInternAtom (display, "XdndSelection", False);
  215469. XdndTypeList = XInternAtom (display, "XdndTypeList", False);
  215470. XdndActionList = XInternAtom (display, "XdndActionList", False);
  215471. XdndActionCopy = XInternAtom (display, "XdndActionCopy", False);
  215472. XdndActionDescription = XInternAtom (display, "XdndActionDescription", False);
  215473. allowedMimeTypes[0] = XInternAtom (display, "text/plain", False);
  215474. allowedMimeTypes[1] = XInternAtom (display, "text/uri-list", False);
  215475. allowedActions[0] = XInternAtom (display, "XdndActionMove", False);
  215476. allowedActions[1] = XdndActionCopy;
  215477. allowedActions[2] = XInternAtom (display, "XdndActionLink", False);
  215478. allowedActions[3] = XInternAtom (display, "XdndActionAsk", False);
  215479. allowedActions[4] = XInternAtom (display, "XdndActionPrivate", False);
  215480. }
  215481. }
  215482. }
  215483. namespace Keys
  215484. {
  215485. enum MouseButtons
  215486. {
  215487. NoButton = 0,
  215488. LeftButton = 1,
  215489. MiddleButton = 2,
  215490. RightButton = 3,
  215491. WheelUp = 4,
  215492. WheelDown = 5
  215493. };
  215494. static int AltMask = 0;
  215495. static int NumLockMask = 0;
  215496. static bool numLock = false;
  215497. static bool capsLock = false;
  215498. static char keyStates [32];
  215499. static const int extendedKeyModifier = 0x10000000;
  215500. }
  215501. bool KeyPress::isKeyCurrentlyDown (const int keyCode)
  215502. {
  215503. int keysym;
  215504. if (keyCode & Keys::extendedKeyModifier)
  215505. {
  215506. keysym = 0xff00 | (keyCode & 0xff);
  215507. }
  215508. else
  215509. {
  215510. keysym = keyCode;
  215511. if (keysym == (XK_Tab & 0xff)
  215512. || keysym == (XK_Return & 0xff)
  215513. || keysym == (XK_Escape & 0xff)
  215514. || keysym == (XK_BackSpace & 0xff))
  215515. {
  215516. keysym |= 0xff00;
  215517. }
  215518. }
  215519. ScopedXLock xlock;
  215520. const int keycode = XKeysymToKeycode (display, keysym);
  215521. const int keybyte = keycode >> 3;
  215522. const int keybit = (1 << (keycode & 7));
  215523. return (Keys::keyStates [keybyte] & keybit) != 0;
  215524. }
  215525. #if JUCE_USE_XSHM
  215526. namespace XSHMHelpers
  215527. {
  215528. static int trappedErrorCode = 0;
  215529. extern "C" int errorTrapHandler (Display*, XErrorEvent* err)
  215530. {
  215531. trappedErrorCode = err->error_code;
  215532. return 0;
  215533. }
  215534. static bool isShmAvailable() throw()
  215535. {
  215536. static bool isChecked = false;
  215537. static bool isAvailable = false;
  215538. if (! isChecked)
  215539. {
  215540. isChecked = true;
  215541. int major, minor;
  215542. Bool pixmaps;
  215543. ScopedXLock xlock;
  215544. if (XShmQueryVersion (display, &major, &minor, &pixmaps))
  215545. {
  215546. trappedErrorCode = 0;
  215547. XErrorHandler oldHandler = XSetErrorHandler (errorTrapHandler);
  215548. XShmSegmentInfo segmentInfo;
  215549. zerostruct (segmentInfo);
  215550. XImage* xImage = XShmCreateImage (display, DefaultVisual (display, DefaultScreen (display)),
  215551. 24, ZPixmap, 0, &segmentInfo, 50, 50);
  215552. if ((segmentInfo.shmid = shmget (IPC_PRIVATE,
  215553. xImage->bytes_per_line * xImage->height,
  215554. IPC_CREAT | 0777)) >= 0)
  215555. {
  215556. segmentInfo.shmaddr = (char*) shmat (segmentInfo.shmid, 0, 0);
  215557. if (segmentInfo.shmaddr != (void*) -1)
  215558. {
  215559. segmentInfo.readOnly = False;
  215560. xImage->data = segmentInfo.shmaddr;
  215561. XSync (display, False);
  215562. if (XShmAttach (display, &segmentInfo) != 0)
  215563. {
  215564. XSync (display, False);
  215565. XShmDetach (display, &segmentInfo);
  215566. isAvailable = true;
  215567. }
  215568. }
  215569. XFlush (display);
  215570. XDestroyImage (xImage);
  215571. shmdt (segmentInfo.shmaddr);
  215572. }
  215573. shmctl (segmentInfo.shmid, IPC_RMID, 0);
  215574. XSetErrorHandler (oldHandler);
  215575. if (trappedErrorCode != 0)
  215576. isAvailable = false;
  215577. }
  215578. }
  215579. return isAvailable;
  215580. }
  215581. }
  215582. #endif
  215583. #if JUCE_USE_XRENDER
  215584. namespace XRender
  215585. {
  215586. typedef Status (*tXRenderQueryVersion) (Display*, int*, int*);
  215587. typedef XRenderPictFormat* (*tXrenderFindStandardFormat) (Display*, int);
  215588. typedef XRenderPictFormat* (*tXRenderFindFormat) (Display*, unsigned long, XRenderPictFormat*, int);
  215589. typedef XRenderPictFormat* (*tXRenderFindVisualFormat) (Display*, Visual*);
  215590. static tXRenderQueryVersion xRenderQueryVersion = 0;
  215591. static tXrenderFindStandardFormat xRenderFindStandardFormat = 0;
  215592. static tXRenderFindFormat xRenderFindFormat = 0;
  215593. static tXRenderFindVisualFormat xRenderFindVisualFormat = 0;
  215594. static bool isAvailable()
  215595. {
  215596. static bool hasLoaded = false;
  215597. if (! hasLoaded)
  215598. {
  215599. ScopedXLock xlock;
  215600. hasLoaded = true;
  215601. void* h = dlopen ("libXrender.so", RTLD_GLOBAL | RTLD_NOW);
  215602. if (h != 0)
  215603. {
  215604. xRenderQueryVersion = (tXRenderQueryVersion) dlsym (h, "XRenderQueryVersion");
  215605. xRenderFindStandardFormat = (tXrenderFindStandardFormat) dlsym (h, "XrenderFindStandardFormat");
  215606. xRenderFindFormat = (tXRenderFindFormat) dlsym (h, "XRenderFindFormat");
  215607. xRenderFindVisualFormat = (tXRenderFindVisualFormat) dlsym (h, "XRenderFindVisualFormat");
  215608. }
  215609. if (xRenderQueryVersion != 0
  215610. && xRenderFindStandardFormat != 0
  215611. && xRenderFindFormat != 0
  215612. && xRenderFindVisualFormat != 0)
  215613. {
  215614. int major, minor;
  215615. if (xRenderQueryVersion (display, &major, &minor))
  215616. return true;
  215617. }
  215618. xRenderQueryVersion = 0;
  215619. }
  215620. return xRenderQueryVersion != 0;
  215621. }
  215622. static XRenderPictFormat* findPictureFormat()
  215623. {
  215624. ScopedXLock xlock;
  215625. XRenderPictFormat* pictFormat = 0;
  215626. if (isAvailable())
  215627. {
  215628. pictFormat = xRenderFindStandardFormat (display, PictStandardARGB32);
  215629. if (pictFormat == 0)
  215630. {
  215631. XRenderPictFormat desiredFormat;
  215632. desiredFormat.type = PictTypeDirect;
  215633. desiredFormat.depth = 32;
  215634. desiredFormat.direct.alphaMask = 0xff;
  215635. desiredFormat.direct.redMask = 0xff;
  215636. desiredFormat.direct.greenMask = 0xff;
  215637. desiredFormat.direct.blueMask = 0xff;
  215638. desiredFormat.direct.alpha = 24;
  215639. desiredFormat.direct.red = 16;
  215640. desiredFormat.direct.green = 8;
  215641. desiredFormat.direct.blue = 0;
  215642. pictFormat = xRenderFindFormat (display,
  215643. PictFormatType | PictFormatDepth
  215644. | PictFormatRedMask | PictFormatRed
  215645. | PictFormatGreenMask | PictFormatGreen
  215646. | PictFormatBlueMask | PictFormatBlue
  215647. | PictFormatAlphaMask | PictFormatAlpha,
  215648. &desiredFormat,
  215649. 0);
  215650. }
  215651. }
  215652. return pictFormat;
  215653. }
  215654. }
  215655. #endif
  215656. namespace Visuals
  215657. {
  215658. static Visual* findVisualWithDepth (const int desiredDepth) throw()
  215659. {
  215660. ScopedXLock xlock;
  215661. Visual* visual = 0;
  215662. int numVisuals = 0;
  215663. long desiredMask = VisualNoMask;
  215664. XVisualInfo desiredVisual;
  215665. desiredVisual.screen = DefaultScreen (display);
  215666. desiredVisual.depth = desiredDepth;
  215667. desiredMask = VisualScreenMask | VisualDepthMask;
  215668. if (desiredDepth == 32)
  215669. {
  215670. desiredVisual.c_class = TrueColor;
  215671. desiredVisual.red_mask = 0x00FF0000;
  215672. desiredVisual.green_mask = 0x0000FF00;
  215673. desiredVisual.blue_mask = 0x000000FF;
  215674. desiredVisual.bits_per_rgb = 8;
  215675. desiredMask |= VisualClassMask;
  215676. desiredMask |= VisualRedMaskMask;
  215677. desiredMask |= VisualGreenMaskMask;
  215678. desiredMask |= VisualBlueMaskMask;
  215679. desiredMask |= VisualBitsPerRGBMask;
  215680. }
  215681. XVisualInfo* xvinfos = XGetVisualInfo (display,
  215682. desiredMask,
  215683. &desiredVisual,
  215684. &numVisuals);
  215685. if (xvinfos != 0)
  215686. {
  215687. for (int i = 0; i < numVisuals; i++)
  215688. {
  215689. if (xvinfos[i].depth == desiredDepth)
  215690. {
  215691. visual = xvinfos[i].visual;
  215692. break;
  215693. }
  215694. }
  215695. XFree (xvinfos);
  215696. }
  215697. return visual;
  215698. }
  215699. static Visual* findVisualFormat (const int desiredDepth, int& matchedDepth) throw()
  215700. {
  215701. Visual* visual = 0;
  215702. if (desiredDepth == 32)
  215703. {
  215704. #if JUCE_USE_XSHM
  215705. if (XSHMHelpers::isShmAvailable())
  215706. {
  215707. #if JUCE_USE_XRENDER
  215708. if (XRender::isAvailable())
  215709. {
  215710. XRenderPictFormat* pictFormat = XRender::findPictureFormat();
  215711. if (pictFormat != 0)
  215712. {
  215713. int numVisuals = 0;
  215714. XVisualInfo desiredVisual;
  215715. desiredVisual.screen = DefaultScreen (display);
  215716. desiredVisual.depth = 32;
  215717. desiredVisual.bits_per_rgb = 8;
  215718. XVisualInfo* xvinfos = XGetVisualInfo (display,
  215719. VisualScreenMask | VisualDepthMask | VisualBitsPerRGBMask,
  215720. &desiredVisual, &numVisuals);
  215721. if (xvinfos != 0)
  215722. {
  215723. for (int i = 0; i < numVisuals; ++i)
  215724. {
  215725. XRenderPictFormat* pictVisualFormat = XRender::xRenderFindVisualFormat (display, xvinfos[i].visual);
  215726. if (pictVisualFormat != 0
  215727. && pictVisualFormat->type == PictTypeDirect
  215728. && pictVisualFormat->direct.alphaMask)
  215729. {
  215730. visual = xvinfos[i].visual;
  215731. matchedDepth = 32;
  215732. break;
  215733. }
  215734. }
  215735. XFree (xvinfos);
  215736. }
  215737. }
  215738. }
  215739. #endif
  215740. if (visual == 0)
  215741. {
  215742. visual = findVisualWithDepth (32);
  215743. if (visual != 0)
  215744. matchedDepth = 32;
  215745. }
  215746. }
  215747. #endif
  215748. }
  215749. if (visual == 0 && desiredDepth >= 24)
  215750. {
  215751. visual = findVisualWithDepth (24);
  215752. if (visual != 0)
  215753. matchedDepth = 24;
  215754. }
  215755. if (visual == 0 && desiredDepth >= 16)
  215756. {
  215757. visual = findVisualWithDepth (16);
  215758. if (visual != 0)
  215759. matchedDepth = 16;
  215760. }
  215761. return visual;
  215762. }
  215763. }
  215764. class XBitmapImage : public Image
  215765. {
  215766. public:
  215767. XBitmapImage (const PixelFormat format_, const int w, const int h,
  215768. const bool clearImage, const int imageDepth_, Visual* visual)
  215769. : Image (format_, w, h),
  215770. imageDepth (imageDepth_),
  215771. gc (None)
  215772. {
  215773. jassert (format_ == RGB || format_ == ARGB);
  215774. pixelStride = (format_ == RGB) ? 3 : 4;
  215775. lineStride = ((w * pixelStride + 3) & ~3);
  215776. ScopedXLock xlock;
  215777. #if JUCE_USE_XSHM
  215778. usingXShm = false;
  215779. if ((imageDepth > 16) && XSHMHelpers::isShmAvailable())
  215780. {
  215781. zerostruct (segmentInfo);
  215782. segmentInfo.shmid = -1;
  215783. segmentInfo.shmaddr = (char *) -1;
  215784. segmentInfo.readOnly = False;
  215785. xImage = XShmCreateImage (display, visual, imageDepth, ZPixmap, 0, &segmentInfo, w, h);
  215786. if (xImage != 0)
  215787. {
  215788. if ((segmentInfo.shmid = shmget (IPC_PRIVATE,
  215789. xImage->bytes_per_line * xImage->height,
  215790. IPC_CREAT | 0777)) >= 0)
  215791. {
  215792. if (segmentInfo.shmid != -1)
  215793. {
  215794. segmentInfo.shmaddr = (char*) shmat (segmentInfo.shmid, 0, 0);
  215795. if (segmentInfo.shmaddr != (void*) -1)
  215796. {
  215797. segmentInfo.readOnly = False;
  215798. xImage->data = segmentInfo.shmaddr;
  215799. imageData = (uint8*) segmentInfo.shmaddr;
  215800. if (XShmAttach (display, &segmentInfo) != 0)
  215801. {
  215802. usingXShm = true;
  215803. }
  215804. else
  215805. {
  215806. jassertfalse
  215807. }
  215808. }
  215809. else
  215810. {
  215811. shmctl (segmentInfo.shmid, IPC_RMID, 0);
  215812. }
  215813. }
  215814. }
  215815. }
  215816. }
  215817. if (! usingXShm)
  215818. #endif
  215819. {
  215820. imageDataAllocated.malloc (lineStride * h);
  215821. imageData = imageDataAllocated;
  215822. if (format_ == ARGB && clearImage)
  215823. zeromem (imageData, h * lineStride);
  215824. xImage = (XImage*) juce_calloc (sizeof (XImage));
  215825. xImage->width = w;
  215826. xImage->height = h;
  215827. xImage->xoffset = 0;
  215828. xImage->format = ZPixmap;
  215829. xImage->data = (char*) imageData;
  215830. xImage->byte_order = ImageByteOrder (display);
  215831. xImage->bitmap_unit = BitmapUnit (display);
  215832. xImage->bitmap_bit_order = BitmapBitOrder (display);
  215833. xImage->bitmap_pad = 32;
  215834. xImage->depth = pixelStride * 8;
  215835. xImage->bytes_per_line = lineStride;
  215836. xImage->bits_per_pixel = pixelStride * 8;
  215837. xImage->red_mask = 0x00FF0000;
  215838. xImage->green_mask = 0x0000FF00;
  215839. xImage->blue_mask = 0x000000FF;
  215840. if (imageDepth == 16)
  215841. {
  215842. const int pixelStride = 2;
  215843. const int lineStride = ((w * pixelStride + 3) & ~3);
  215844. imageData16Bit.malloc (lineStride * h);
  215845. xImage->data = imageData16Bit;
  215846. xImage->bitmap_pad = 16;
  215847. xImage->depth = pixelStride * 8;
  215848. xImage->bytes_per_line = lineStride;
  215849. xImage->bits_per_pixel = pixelStride * 8;
  215850. xImage->red_mask = visual->red_mask;
  215851. xImage->green_mask = visual->green_mask;
  215852. xImage->blue_mask = visual->blue_mask;
  215853. }
  215854. if (! XInitImage (xImage))
  215855. {
  215856. jassertfalse
  215857. }
  215858. }
  215859. }
  215860. ~XBitmapImage()
  215861. {
  215862. ScopedXLock xlock;
  215863. if (gc != None)
  215864. XFreeGC (display, gc);
  215865. #if JUCE_USE_XSHM
  215866. if (usingXShm)
  215867. {
  215868. XShmDetach (display, &segmentInfo);
  215869. XFlush (display);
  215870. XDestroyImage (xImage);
  215871. shmdt (segmentInfo.shmaddr);
  215872. shmctl (segmentInfo.shmid, IPC_RMID, 0);
  215873. }
  215874. else
  215875. #endif
  215876. {
  215877. xImage->data = 0;
  215878. XDestroyImage (xImage);
  215879. }
  215880. }
  215881. void blitToWindow (Window window, int dx, int dy, int dw, int dh, int sx, int sy)
  215882. {
  215883. ScopedXLock xlock;
  215884. if (gc == None)
  215885. {
  215886. XGCValues gcvalues;
  215887. gcvalues.foreground = None;
  215888. gcvalues.background = None;
  215889. gcvalues.function = GXcopy;
  215890. gcvalues.plane_mask = AllPlanes;
  215891. gcvalues.clip_mask = None;
  215892. gcvalues.graphics_exposures = False;
  215893. gc = XCreateGC (display, window,
  215894. GCBackground | GCForeground | GCFunction | GCPlaneMask | GCClipMask | GCGraphicsExposures,
  215895. &gcvalues);
  215896. }
  215897. if (imageDepth == 16)
  215898. {
  215899. const uint32 rMask = xImage->red_mask;
  215900. const uint32 rShiftL = jmax (0, getShiftNeeded (rMask));
  215901. const uint32 rShiftR = jmax (0, -getShiftNeeded (rMask));
  215902. const uint32 gMask = xImage->green_mask;
  215903. const uint32 gShiftL = jmax (0, getShiftNeeded (gMask));
  215904. const uint32 gShiftR = jmax (0, -getShiftNeeded (gMask));
  215905. const uint32 bMask = xImage->blue_mask;
  215906. const uint32 bShiftL = jmax (0, getShiftNeeded (bMask));
  215907. const uint32 bShiftR = jmax (0, -getShiftNeeded (bMask));
  215908. const Image::BitmapData srcData (*this, 0, 0, getWidth(), getHeight());
  215909. for (int y = sy; y < sy + dh; ++y)
  215910. {
  215911. const uint8* p = srcData.getPixelPointer (sx, y);
  215912. for (int x = sx; x < sx + dw; ++x)
  215913. {
  215914. const PixelRGB* const pixel = (const PixelRGB*) p;
  215915. p += srcData.pixelStride;
  215916. XPutPixel (xImage, x, y,
  215917. (((((uint32) pixel->getRed()) << rShiftL) >> rShiftR) & rMask)
  215918. | (((((uint32) pixel->getGreen()) << gShiftL) >> gShiftR) & gMask)
  215919. | (((((uint32) pixel->getBlue()) << bShiftL) >> bShiftR) & bMask));
  215920. }
  215921. }
  215922. }
  215923. // blit results to screen.
  215924. #if JUCE_USE_XSHM
  215925. if (usingXShm)
  215926. XShmPutImage (display, (::Drawable) window, gc, xImage, sx, sy, dx, dy, dw, dh, True);
  215927. else
  215928. #endif
  215929. XPutImage (display, (::Drawable) window, gc, xImage, sx, sy, dx, dy, dw, dh);
  215930. }
  215931. juce_UseDebuggingNewOperator
  215932. private:
  215933. XImage* xImage;
  215934. const int imageDepth;
  215935. HeapBlock <char> imageData16Bit;
  215936. GC gc;
  215937. #if JUCE_USE_XSHM
  215938. XShmSegmentInfo segmentInfo;
  215939. bool usingXShm;
  215940. #endif
  215941. static int getShiftNeeded (const uint32 mask) throw()
  215942. {
  215943. for (int i = 32; --i >= 0;)
  215944. if (((mask >> i) & 1) != 0)
  215945. return i - 7;
  215946. jassertfalse
  215947. return 0;
  215948. }
  215949. };
  215950. class LinuxComponentPeer : public ComponentPeer
  215951. {
  215952. public:
  215953. LinuxComponentPeer (Component* const component, const int windowStyleFlags)
  215954. : ComponentPeer (component, windowStyleFlags),
  215955. windowH (0),
  215956. parentWindow (0),
  215957. wx (0),
  215958. wy (0),
  215959. ww (0),
  215960. wh (0),
  215961. fullScreen (false),
  215962. mapped (false),
  215963. visual (0),
  215964. depth (0)
  215965. {
  215966. // it's dangerous to create a window on a thread other than the message thread..
  215967. jassert (MessageManager::getInstance()->currentThreadHasLockedMessageManager());
  215968. repainter = new LinuxRepaintManager (this);
  215969. createWindow();
  215970. setTitle (component->getName());
  215971. }
  215972. ~LinuxComponentPeer()
  215973. {
  215974. // it's dangerous to delete a window on a thread other than the message thread..
  215975. jassert (MessageManager::getInstance()->currentThreadHasLockedMessageManager());
  215976. deleteIconPixmaps();
  215977. destroyWindow();
  215978. windowH = 0;
  215979. }
  215980. void* getNativeHandle() const
  215981. {
  215982. return (void*) windowH;
  215983. }
  215984. static LinuxComponentPeer* getPeerFor (Window windowHandle) throw()
  215985. {
  215986. XPointer peer = 0;
  215987. ScopedXLock xlock;
  215988. if (! XFindContext (display, (XID) windowHandle, windowHandleXContext, &peer))
  215989. {
  215990. if (peer != 0 && ! ComponentPeer::isValidPeer ((LinuxComponentPeer*) peer))
  215991. peer = 0;
  215992. }
  215993. return (LinuxComponentPeer*) peer;
  215994. }
  215995. void setVisible (bool shouldBeVisible)
  215996. {
  215997. ScopedXLock xlock;
  215998. if (shouldBeVisible)
  215999. XMapWindow (display, windowH);
  216000. else
  216001. XUnmapWindow (display, windowH);
  216002. }
  216003. void setTitle (const String& title)
  216004. {
  216005. setWindowTitle (windowH, title);
  216006. }
  216007. void setPosition (int x, int y)
  216008. {
  216009. setBounds (x, y, ww, wh, false);
  216010. }
  216011. void setSize (int w, int h)
  216012. {
  216013. setBounds (wx, wy, w, h, false);
  216014. }
  216015. void setBounds (int x, int y, int w, int h, bool isNowFullScreen)
  216016. {
  216017. fullScreen = isNowFullScreen;
  216018. if (windowH != 0)
  216019. {
  216020. Component::SafePointer<Component> deletionChecker (component);
  216021. wx = x;
  216022. wy = y;
  216023. ww = jmax (1, w);
  216024. wh = jmax (1, h);
  216025. ScopedXLock xlock;
  216026. // Make sure the Window manager does what we want
  216027. XSizeHints* hints = XAllocSizeHints();
  216028. hints->flags = USSize | USPosition;
  216029. hints->width = ww;
  216030. hints->height = wh;
  216031. hints->x = wx;
  216032. hints->y = wy;
  216033. if ((getStyleFlags() & (windowHasTitleBar | windowIsResizable)) == windowHasTitleBar)
  216034. {
  216035. hints->min_width = hints->max_width = hints->width;
  216036. hints->min_height = hints->max_height = hints->height;
  216037. hints->flags |= PMinSize | PMaxSize;
  216038. }
  216039. XSetWMNormalHints (display, windowH, hints);
  216040. XFree (hints);
  216041. XMoveResizeWindow (display, windowH,
  216042. wx - windowBorder.getLeft(),
  216043. wy - windowBorder.getTop(), ww, wh);
  216044. if (deletionChecker != 0)
  216045. {
  216046. updateBorderSize();
  216047. handleMovedOrResized();
  216048. }
  216049. }
  216050. }
  216051. const Rectangle<int> getBounds() const { return Rectangle<int> (wx, wy, ww, wh); }
  216052. const Point<int> getScreenPosition() const { return Point<int> (wx, wy); }
  216053. const Point<int> relativePositionToGlobal (const Point<int>& relativePosition)
  216054. {
  216055. return relativePosition + getScreenPosition();
  216056. }
  216057. const Point<int> globalPositionToRelative (const Point<int>& screenPosition)
  216058. {
  216059. return screenPosition - getScreenPosition();
  216060. }
  216061. void setMinimised (bool shouldBeMinimised)
  216062. {
  216063. if (shouldBeMinimised)
  216064. {
  216065. Window root = RootWindow (display, DefaultScreen (display));
  216066. XClientMessageEvent clientMsg;
  216067. clientMsg.display = display;
  216068. clientMsg.window = windowH;
  216069. clientMsg.type = ClientMessage;
  216070. clientMsg.format = 32;
  216071. clientMsg.message_type = Atoms::ChangeState;
  216072. clientMsg.data.l[0] = IconicState;
  216073. ScopedXLock xlock;
  216074. XSendEvent (display, root, false,
  216075. SubstructureRedirectMask | SubstructureNotifyMask,
  216076. (XEvent*) &clientMsg);
  216077. }
  216078. else
  216079. {
  216080. setVisible (true);
  216081. }
  216082. }
  216083. bool isMinimised() const
  216084. {
  216085. bool minimised = false;
  216086. unsigned char* stateProp;
  216087. unsigned long nitems, bytesLeft;
  216088. Atom actualType;
  216089. int actualFormat;
  216090. ScopedXLock xlock;
  216091. if (XGetWindowProperty (display, windowH, Atoms::State, 0, 64, False,
  216092. Atoms::State, &actualType, &actualFormat, &nitems, &bytesLeft,
  216093. &stateProp) == Success
  216094. && actualType == Atoms::State
  216095. && actualFormat == 32
  216096. && nitems > 0)
  216097. {
  216098. if (((unsigned long*) stateProp)[0] == IconicState)
  216099. minimised = true;
  216100. XFree (stateProp);
  216101. }
  216102. return minimised;
  216103. }
  216104. void setFullScreen (const bool shouldBeFullScreen)
  216105. {
  216106. Rectangle<int> r (lastNonFullscreenBounds); // (get a copy of this before de-minimising)
  216107. setMinimised (false);
  216108. if (fullScreen != shouldBeFullScreen)
  216109. {
  216110. if (shouldBeFullScreen)
  216111. r = Desktop::getInstance().getMainMonitorArea();
  216112. if (! r.isEmpty())
  216113. setBounds (r.getX(), r.getY(), r.getWidth(), r.getHeight(), shouldBeFullScreen);
  216114. getComponent()->repaint();
  216115. }
  216116. }
  216117. bool isFullScreen() const
  216118. {
  216119. return fullScreen;
  216120. }
  216121. bool isChildWindowOf (Window possibleParent) const
  216122. {
  216123. Window* windowList = 0;
  216124. uint32 windowListSize = 0;
  216125. Window parent, root;
  216126. ScopedXLock xlock;
  216127. if (XQueryTree (display, windowH, &root, &parent, &windowList, &windowListSize) != 0)
  216128. {
  216129. if (windowList != 0)
  216130. XFree (windowList);
  216131. return parent == possibleParent;
  216132. }
  216133. return false;
  216134. }
  216135. bool isFrontWindow() const
  216136. {
  216137. Window* windowList = 0;
  216138. uint32 windowListSize = 0;
  216139. bool result = false;
  216140. ScopedXLock xlock;
  216141. Window parent, root = RootWindow (display, DefaultScreen (display));
  216142. if (XQueryTree (display, root, &root, &parent, &windowList, &windowListSize) != 0)
  216143. {
  216144. for (int i = windowListSize; --i >= 0;)
  216145. {
  216146. LinuxComponentPeer* const peer = LinuxComponentPeer::getPeerFor (windowList[i]);
  216147. if (peer != 0)
  216148. {
  216149. result = (peer == this);
  216150. break;
  216151. }
  216152. }
  216153. }
  216154. if (windowList != 0)
  216155. XFree (windowList);
  216156. return result;
  216157. }
  216158. bool contains (const Point<int>& position, bool trueIfInAChildWindow) const
  216159. {
  216160. int x = position.getX();
  216161. int y = position.getY();
  216162. if (((unsigned int) x) >= (unsigned int) ww
  216163. || ((unsigned int) y) >= (unsigned int) wh)
  216164. return false;
  216165. bool inFront = false;
  216166. for (int i = 0; i < Desktop::getInstance().getNumComponents(); ++i)
  216167. {
  216168. Component* const c = Desktop::getInstance().getComponent (i);
  216169. if (inFront)
  216170. {
  216171. if (c->contains (x + wx - c->getScreenX(),
  216172. y + wy - c->getScreenY()))
  216173. {
  216174. return false;
  216175. }
  216176. }
  216177. else if (c == getComponent())
  216178. {
  216179. inFront = true;
  216180. }
  216181. }
  216182. if (trueIfInAChildWindow)
  216183. return true;
  216184. ::Window root, child;
  216185. unsigned int bw, depth;
  216186. int wx, wy, w, h;
  216187. ScopedXLock xlock;
  216188. if (! XGetGeometry (display, (::Drawable) windowH, &root,
  216189. &wx, &wy, (unsigned int*) &w, (unsigned int*) &h,
  216190. &bw, &depth))
  216191. {
  216192. return false;
  216193. }
  216194. if (! XTranslateCoordinates (display, windowH, windowH, x, y, &wx, &wy, &child))
  216195. return false;
  216196. return child == None;
  216197. }
  216198. const BorderSize getFrameSize() const
  216199. {
  216200. return BorderSize();
  216201. }
  216202. bool setAlwaysOnTop (bool alwaysOnTop)
  216203. {
  216204. if (windowH != 0)
  216205. {
  216206. const bool wasVisible = component->isVisible();
  216207. if (wasVisible)
  216208. setVisible (false); // doesn't always seem to work if the window is visible when this is done..
  216209. {
  216210. ScopedXLock xlock;
  216211. XSetWindowAttributes swa;
  216212. swa.override_redirect = alwaysOnTop ? True : False;
  216213. XChangeWindowAttributes (display, windowH, CWOverrideRedirect, &swa);
  216214. }
  216215. if (wasVisible)
  216216. setVisible (true);
  216217. }
  216218. return true;
  216219. }
  216220. void toFront (bool makeActive)
  216221. {
  216222. if (makeActive)
  216223. {
  216224. setVisible (true);
  216225. grabFocus();
  216226. }
  216227. XEvent ev;
  216228. ev.xclient.type = ClientMessage;
  216229. ev.xclient.serial = 0;
  216230. ev.xclient.send_event = True;
  216231. ev.xclient.message_type = Atoms::ActiveWin;
  216232. ev.xclient.window = windowH;
  216233. ev.xclient.format = 32;
  216234. ev.xclient.data.l[0] = 2;
  216235. ev.xclient.data.l[1] = CurrentTime;
  216236. ev.xclient.data.l[2] = 0;
  216237. ev.xclient.data.l[3] = 0;
  216238. ev.xclient.data.l[4] = 0;
  216239. {
  216240. ScopedXLock xlock;
  216241. XSendEvent (display, RootWindow (display, DefaultScreen (display)),
  216242. False,
  216243. SubstructureRedirectMask | SubstructureNotifyMask,
  216244. &ev);
  216245. XWindowAttributes attr;
  216246. XGetWindowAttributes (display, windowH, &attr);
  216247. if (attr.override_redirect)
  216248. XRaiseWindow (display, windowH);
  216249. XSync (display, False);
  216250. }
  216251. handleBroughtToFront();
  216252. }
  216253. void toBehind (ComponentPeer* other)
  216254. {
  216255. LinuxComponentPeer* const otherPeer = dynamic_cast <LinuxComponentPeer*> (other);
  216256. jassert (otherPeer != 0); // wrong type of window?
  216257. if (otherPeer != 0)
  216258. {
  216259. setMinimised (false);
  216260. Window newStack[] = { otherPeer->windowH, windowH };
  216261. ScopedXLock xlock;
  216262. XRestackWindows (display, newStack, 2);
  216263. }
  216264. }
  216265. bool isFocused() const
  216266. {
  216267. int revert;
  216268. Window focusedWindow = 0;
  216269. ScopedXLock xlock;
  216270. XGetInputFocus (display, &focusedWindow, &revert);
  216271. return focusedWindow == windowH;
  216272. }
  216273. void grabFocus()
  216274. {
  216275. XWindowAttributes atts;
  216276. ScopedXLock xlock;
  216277. if (windowH != 0
  216278. && XGetWindowAttributes (display, windowH, &atts)
  216279. && atts.map_state == IsViewable
  216280. && ! isFocused())
  216281. {
  216282. XSetInputFocus (display, windowH, RevertToParent, CurrentTime);
  216283. isActiveApplication = true;
  216284. }
  216285. }
  216286. void textInputRequired (const Point<int>&)
  216287. {
  216288. }
  216289. void repaint (int x, int y, int w, int h)
  216290. {
  216291. if (Rectangle<int>::intersectRectangles (x, y, w, h,
  216292. 0, 0,
  216293. getComponent()->getWidth(),
  216294. getComponent()->getHeight()))
  216295. {
  216296. repainter->repaint (x, y, w, h);
  216297. }
  216298. }
  216299. void performAnyPendingRepaintsNow()
  216300. {
  216301. repainter->performAnyPendingRepaintsNow();
  216302. }
  216303. static Pixmap juce_createColourPixmapFromImage (Display* display, const Image& image)
  216304. {
  216305. ScopedXLock xlock;
  216306. const int width = image.getWidth();
  216307. const int height = image.getHeight();
  216308. HeapBlock <char> colour (width * height);
  216309. int index = 0;
  216310. for (int y = 0; y < height; ++y)
  216311. for (int x = 0; x < width; ++x)
  216312. colour[index++] = static_cast<char> (image.getPixelAt (x, y).getARGB());
  216313. XImage* ximage = XCreateImage (display, CopyFromParent, 24, ZPixmap,
  216314. 0, colour.getData(),
  216315. width, height, 32, 0);
  216316. Pixmap pixmap = XCreatePixmap (display, DefaultRootWindow (display),
  216317. width, height, 24);
  216318. GC gc = XCreateGC (display, pixmap, 0, 0);
  216319. XPutImage (display, pixmap, gc, ximage, 0, 0, 0, 0, width, height);
  216320. XFreeGC (display, gc);
  216321. return pixmap;
  216322. }
  216323. static Pixmap juce_createMaskPixmapFromImage (Display* display, const Image& image)
  216324. {
  216325. ScopedXLock xlock;
  216326. const int width = image.getWidth();
  216327. const int height = image.getHeight();
  216328. const int stride = (width + 7) >> 3;
  216329. HeapBlock <char> mask;
  216330. mask.calloc (stride * height);
  216331. const bool msbfirst = (BitmapBitOrder (display) == MSBFirst);
  216332. for (int y = 0; y < height; ++y)
  216333. {
  216334. for (int x = 0; x < width; ++x)
  216335. {
  216336. const char bit = (char) (1 << (msbfirst ? (7 - (x & 7)) : (x & 7)));
  216337. const int offset = y * stride + (x >> 3);
  216338. if (image.getPixelAt (x, y).getAlpha() >= 128)
  216339. mask[offset] |= bit;
  216340. }
  216341. }
  216342. return XCreatePixmapFromBitmapData (display, DefaultRootWindow (display),
  216343. mask.getData(), width, height, 1, 0, 1);
  216344. }
  216345. void setIcon (const Image& newIcon)
  216346. {
  216347. const int dataSize = newIcon.getWidth() * newIcon.getHeight() + 2;
  216348. HeapBlock <unsigned long> data (dataSize);
  216349. int index = 0;
  216350. data[index++] = newIcon.getWidth();
  216351. data[index++] = newIcon.getHeight();
  216352. for (int y = 0; y < newIcon.getHeight(); ++y)
  216353. for (int x = 0; x < newIcon.getWidth(); ++x)
  216354. data[index++] = newIcon.getPixelAt (x, y).getARGB();
  216355. ScopedXLock xlock;
  216356. XChangeProperty (display, windowH,
  216357. XInternAtom (display, "_NET_WM_ICON", False),
  216358. XA_CARDINAL, 32, PropModeReplace,
  216359. reinterpret_cast<unsigned char*> (data.getData()), dataSize);
  216360. deleteIconPixmaps();
  216361. XWMHints* wmHints = XGetWMHints (display, windowH);
  216362. if (wmHints == 0)
  216363. wmHints = XAllocWMHints();
  216364. wmHints->flags |= IconPixmapHint | IconMaskHint;
  216365. wmHints->icon_pixmap = juce_createColourPixmapFromImage (display, newIcon);
  216366. wmHints->icon_mask = juce_createMaskPixmapFromImage (display, newIcon);
  216367. XSetWMHints (display, windowH, wmHints);
  216368. XFree (wmHints);
  216369. XSync (display, False);
  216370. }
  216371. void deleteIconPixmaps()
  216372. {
  216373. ScopedXLock xlock;
  216374. XWMHints* wmHints = XGetWMHints (display, windowH);
  216375. if (wmHints != 0)
  216376. {
  216377. if ((wmHints->flags & IconPixmapHint) != 0)
  216378. {
  216379. wmHints->flags &= ~IconPixmapHint;
  216380. XFreePixmap (display, wmHints->icon_pixmap);
  216381. }
  216382. if ((wmHints->flags & IconMaskHint) != 0)
  216383. {
  216384. wmHints->flags &= ~IconMaskHint;
  216385. XFreePixmap (display, wmHints->icon_mask);
  216386. }
  216387. XSetWMHints (display, windowH, wmHints);
  216388. XFree (wmHints);
  216389. }
  216390. }
  216391. void handleWindowMessage (XEvent* event)
  216392. {
  216393. switch (event->xany.type)
  216394. {
  216395. case 2: // 'KeyPress'
  216396. {
  216397. ScopedXLock xlock;
  216398. XKeyEvent* const keyEvent = (XKeyEvent*) &event->xkey;
  216399. updateKeyStates (keyEvent->keycode, true);
  216400. char utf8 [64];
  216401. zeromem (utf8, sizeof (utf8));
  216402. KeySym sym;
  216403. {
  216404. const char* oldLocale = ::setlocale (LC_ALL, 0);
  216405. ::setlocale (LC_ALL, "");
  216406. XLookupString (keyEvent, utf8, sizeof (utf8), &sym, 0);
  216407. ::setlocale (LC_ALL, oldLocale);
  216408. }
  216409. const juce_wchar unicodeChar = String::fromUTF8 (utf8, sizeof (utf8) - 1) [0];
  216410. int keyCode = (int) unicodeChar;
  216411. if (keyCode < 0x20)
  216412. keyCode = XKeycodeToKeysym (display, keyEvent->keycode, currentModifiers.isShiftDown() ? 1 : 0);
  216413. const ModifierKeys oldMods (currentModifiers);
  216414. bool keyPressed = false;
  216415. const bool keyDownChange = (sym != NoSymbol) && ! updateKeyModifiersFromSym (sym, true);
  216416. if ((sym & 0xff00) == 0xff00)
  216417. {
  216418. // Translate keypad
  216419. if (sym == XK_KP_Divide)
  216420. keyCode = XK_slash;
  216421. else if (sym == XK_KP_Multiply)
  216422. keyCode = XK_asterisk;
  216423. else if (sym == XK_KP_Subtract)
  216424. keyCode = XK_hyphen;
  216425. else if (sym == XK_KP_Add)
  216426. keyCode = XK_plus;
  216427. else if (sym == XK_KP_Enter)
  216428. keyCode = XK_Return;
  216429. else if (sym == XK_KP_Decimal)
  216430. keyCode = Keys::numLock ? XK_period : XK_Delete;
  216431. else if (sym == XK_KP_0)
  216432. keyCode = Keys::numLock ? XK_0 : XK_Insert;
  216433. else if (sym == XK_KP_1)
  216434. keyCode = Keys::numLock ? XK_1 : XK_End;
  216435. else if (sym == XK_KP_2)
  216436. keyCode = Keys::numLock ? XK_2 : XK_Down;
  216437. else if (sym == XK_KP_3)
  216438. keyCode = Keys::numLock ? XK_3 : XK_Page_Down;
  216439. else if (sym == XK_KP_4)
  216440. keyCode = Keys::numLock ? XK_4 : XK_Left;
  216441. else if (sym == XK_KP_5)
  216442. keyCode = XK_5;
  216443. else if (sym == XK_KP_6)
  216444. keyCode = Keys::numLock ? XK_6 : XK_Right;
  216445. else if (sym == XK_KP_7)
  216446. keyCode = Keys::numLock ? XK_7 : XK_Home;
  216447. else if (sym == XK_KP_8)
  216448. keyCode = Keys::numLock ? XK_8 : XK_Up;
  216449. else if (sym == XK_KP_9)
  216450. keyCode = Keys::numLock ? XK_9 : XK_Page_Up;
  216451. switch (sym)
  216452. {
  216453. case XK_Left:
  216454. case XK_Right:
  216455. case XK_Up:
  216456. case XK_Down:
  216457. case XK_Page_Up:
  216458. case XK_Page_Down:
  216459. case XK_End:
  216460. case XK_Home:
  216461. case XK_Delete:
  216462. case XK_Insert:
  216463. keyPressed = true;
  216464. keyCode = (sym & 0xff) | Keys::extendedKeyModifier;
  216465. break;
  216466. case XK_Tab:
  216467. case XK_Return:
  216468. case XK_Escape:
  216469. case XK_BackSpace:
  216470. keyPressed = true;
  216471. keyCode &= 0xff;
  216472. break;
  216473. default:
  216474. {
  216475. if (sym >= XK_F1 && sym <= XK_F16)
  216476. {
  216477. keyPressed = true;
  216478. keyCode = (sym & 0xff) | Keys::extendedKeyModifier;
  216479. }
  216480. break;
  216481. }
  216482. }
  216483. }
  216484. if (utf8[0] != 0 || ((sym & 0xff00) == 0 && sym >= 8))
  216485. keyPressed = true;
  216486. if (oldMods != currentModifiers)
  216487. handleModifierKeysChange();
  216488. if (keyDownChange)
  216489. handleKeyUpOrDown (true);
  216490. if (keyPressed)
  216491. handleKeyPress (keyCode, unicodeChar);
  216492. break;
  216493. }
  216494. case KeyRelease:
  216495. {
  216496. const XKeyEvent* const keyEvent = (const XKeyEvent*) &event->xkey;
  216497. updateKeyStates (keyEvent->keycode, false);
  216498. ScopedXLock xlock;
  216499. KeySym sym = XKeycodeToKeysym (display, keyEvent->keycode, 0);
  216500. const ModifierKeys oldMods (currentModifiers);
  216501. const bool keyDownChange = (sym != NoSymbol) && ! updateKeyModifiersFromSym (sym, false);
  216502. if (oldMods != currentModifiers)
  216503. handleModifierKeysChange();
  216504. if (keyDownChange)
  216505. handleKeyUpOrDown (false);
  216506. break;
  216507. }
  216508. case ButtonPress:
  216509. {
  216510. const XButtonPressedEvent* const buttonPressEvent = (const XButtonPressedEvent*) &event->xbutton;
  216511. updateKeyModifiers (buttonPressEvent->state);
  216512. bool buttonMsg = false;
  216513. const int map = pointerMap [buttonPressEvent->button - Button1];
  216514. if (map == Keys::WheelUp || map == Keys::WheelDown)
  216515. {
  216516. handleMouseWheel (0, Point<int> (buttonPressEvent->x, buttonPressEvent->y),
  216517. getEventTime (buttonPressEvent->time), 0, map == Keys::WheelDown ? -84.0f : 84.0f);
  216518. }
  216519. if (map == Keys::LeftButton)
  216520. {
  216521. currentModifiers = currentModifiers.withFlags (ModifierKeys::leftButtonModifier);
  216522. buttonMsg = true;
  216523. }
  216524. else if (map == Keys::RightButton)
  216525. {
  216526. currentModifiers = currentModifiers.withFlags (ModifierKeys::rightButtonModifier);
  216527. buttonMsg = true;
  216528. }
  216529. else if (map == Keys::MiddleButton)
  216530. {
  216531. currentModifiers = currentModifiers.withFlags (ModifierKeys::middleButtonModifier);
  216532. buttonMsg = true;
  216533. }
  216534. if (buttonMsg)
  216535. {
  216536. toFront (true);
  216537. handleMouseEvent (0, Point<int> (buttonPressEvent->x, buttonPressEvent->y), currentModifiers,
  216538. getEventTime (buttonPressEvent->time));
  216539. }
  216540. clearLastMousePos();
  216541. break;
  216542. }
  216543. case ButtonRelease:
  216544. {
  216545. const XButtonReleasedEvent* const buttonRelEvent = (const XButtonReleasedEvent*) &event->xbutton;
  216546. updateKeyModifiers (buttonRelEvent->state);
  216547. const int map = pointerMap [buttonRelEvent->button - Button1];
  216548. if (map == Keys::LeftButton)
  216549. currentModifiers = currentModifiers.withoutFlags (ModifierKeys::leftButtonModifier);
  216550. else if (map == Keys::RightButton)
  216551. currentModifiers = currentModifiers.withoutFlags (ModifierKeys::rightButtonModifier);
  216552. else if (map == Keys::MiddleButton)
  216553. currentModifiers = currentModifiers.withoutFlags (ModifierKeys::middleButtonModifier);
  216554. handleMouseEvent (0, Point<int> (buttonRelEvent->x, buttonRelEvent->y), currentModifiers,
  216555. getEventTime (buttonRelEvent->time));
  216556. clearLastMousePos();
  216557. break;
  216558. }
  216559. case MotionNotify:
  216560. {
  216561. const XPointerMovedEvent* const movedEvent = (const XPointerMovedEvent*) &event->xmotion;
  216562. updateKeyModifiers (movedEvent->state);
  216563. const Point<int> mousePos (Desktop::getMousePosition());
  216564. if (lastMousePos != mousePos)
  216565. {
  216566. lastMousePos = mousePos;
  216567. if (parentWindow != 0 && (styleFlags & windowHasTitleBar) == 0)
  216568. {
  216569. Window wRoot = 0, wParent = 0;
  216570. {
  216571. ScopedXLock xlock;
  216572. unsigned int numChildren;
  216573. Window* wChild = 0;
  216574. XQueryTree (display, windowH, &wRoot, &wParent, &wChild, &numChildren);
  216575. }
  216576. if (wParent != 0
  216577. && wParent != windowH
  216578. && wParent != wRoot)
  216579. {
  216580. parentWindow = wParent;
  216581. updateBounds();
  216582. }
  216583. else
  216584. {
  216585. parentWindow = 0;
  216586. }
  216587. }
  216588. handleMouseEvent (0, mousePos - getScreenPosition(), currentModifiers, getEventTime (movedEvent->time));
  216589. }
  216590. break;
  216591. }
  216592. case EnterNotify:
  216593. {
  216594. clearLastMousePos();
  216595. const XEnterWindowEvent* const enterEvent = (const XEnterWindowEvent*) &event->xcrossing;
  216596. if (! currentModifiers.isAnyMouseButtonDown())
  216597. {
  216598. updateKeyModifiers (enterEvent->state);
  216599. handleMouseEvent (0, Point<int> (enterEvent->x, enterEvent->y), currentModifiers, getEventTime (enterEvent->time));
  216600. }
  216601. break;
  216602. }
  216603. case LeaveNotify:
  216604. {
  216605. const XLeaveWindowEvent* const leaveEvent = (const XLeaveWindowEvent*) &event->xcrossing;
  216606. // Suppress the normal leave if we've got a pointer grab, or if
  216607. // it's a bogus one caused by clicking a mouse button when running
  216608. // in a Window manager
  216609. if (((! currentModifiers.isAnyMouseButtonDown()) && leaveEvent->mode == NotifyNormal)
  216610. || leaveEvent->mode == NotifyUngrab)
  216611. {
  216612. updateKeyModifiers (leaveEvent->state);
  216613. handleMouseEvent (0, Point<int> (leaveEvent->x, leaveEvent->y), currentModifiers, getEventTime (leaveEvent->time));
  216614. }
  216615. break;
  216616. }
  216617. case FocusIn:
  216618. {
  216619. isActiveApplication = true;
  216620. if (isFocused())
  216621. handleFocusGain();
  216622. break;
  216623. }
  216624. case FocusOut:
  216625. {
  216626. isActiveApplication = false;
  216627. if (! isFocused())
  216628. handleFocusLoss();
  216629. break;
  216630. }
  216631. case Expose:
  216632. {
  216633. // Batch together all pending expose events
  216634. XExposeEvent* exposeEvent = (XExposeEvent*) &event->xexpose;
  216635. XEvent nextEvent;
  216636. ScopedXLock xlock;
  216637. if (exposeEvent->window != windowH)
  216638. {
  216639. Window child;
  216640. XTranslateCoordinates (display, exposeEvent->window, windowH,
  216641. exposeEvent->x, exposeEvent->y, &exposeEvent->x, &exposeEvent->y,
  216642. &child);
  216643. }
  216644. repaint (exposeEvent->x, exposeEvent->y,
  216645. exposeEvent->width, exposeEvent->height);
  216646. while (XEventsQueued (display, QueuedAfterFlush) > 0)
  216647. {
  216648. XPeekEvent (display, (XEvent*) &nextEvent);
  216649. if (nextEvent.type != Expose || nextEvent.xany.window != event->xany.window)
  216650. break;
  216651. XNextEvent (display, (XEvent*) &nextEvent);
  216652. XExposeEvent* nextExposeEvent = (XExposeEvent*) &nextEvent.xexpose;
  216653. repaint (nextExposeEvent->x, nextExposeEvent->y,
  216654. nextExposeEvent->width, nextExposeEvent->height);
  216655. }
  216656. break;
  216657. }
  216658. case CirculateNotify:
  216659. case CreateNotify:
  216660. case DestroyNotify:
  216661. // Think we can ignore these
  216662. break;
  216663. case ConfigureNotify:
  216664. {
  216665. updateBounds();
  216666. updateBorderSize();
  216667. handleMovedOrResized();
  216668. // if the native title bar is dragged, need to tell any active menus, etc.
  216669. if ((styleFlags & windowHasTitleBar) != 0
  216670. && component->isCurrentlyBlockedByAnotherModalComponent())
  216671. {
  216672. Component* const currentModalComp = Component::getCurrentlyModalComponent();
  216673. if (currentModalComp != 0)
  216674. currentModalComp->inputAttemptWhenModal();
  216675. }
  216676. XConfigureEvent* const confEvent = (XConfigureEvent*) &event->xconfigure;
  216677. if (confEvent->window == windowH
  216678. && confEvent->above != 0
  216679. && isFrontWindow())
  216680. {
  216681. handleBroughtToFront();
  216682. }
  216683. break;
  216684. }
  216685. case ReparentNotify:
  216686. {
  216687. parentWindow = 0;
  216688. Window wRoot = 0;
  216689. Window* wChild = 0;
  216690. unsigned int numChildren;
  216691. {
  216692. ScopedXLock xlock;
  216693. XQueryTree (display, windowH, &wRoot, &parentWindow, &wChild, &numChildren);
  216694. }
  216695. if (parentWindow == windowH || parentWindow == wRoot)
  216696. parentWindow = 0;
  216697. updateBounds();
  216698. updateBorderSize();
  216699. handleMovedOrResized();
  216700. break;
  216701. }
  216702. case GravityNotify:
  216703. {
  216704. updateBounds();
  216705. updateBorderSize();
  216706. handleMovedOrResized();
  216707. break;
  216708. }
  216709. case MapNotify:
  216710. mapped = true;
  216711. handleBroughtToFront();
  216712. break;
  216713. case UnmapNotify:
  216714. mapped = false;
  216715. break;
  216716. case MappingNotify:
  216717. {
  216718. XMappingEvent* mappingEvent = (XMappingEvent*) &event->xmapping;
  216719. if (mappingEvent->request != MappingPointer)
  216720. {
  216721. // Deal with modifier/keyboard mapping
  216722. ScopedXLock xlock;
  216723. XRefreshKeyboardMapping (mappingEvent);
  216724. updateModifierMappings();
  216725. }
  216726. break;
  216727. }
  216728. case ClientMessage:
  216729. {
  216730. const XClientMessageEvent* const clientMsg = (const XClientMessageEvent*) &event->xclient;
  216731. if (clientMsg->message_type == Atoms::Protocols && clientMsg->format == 32)
  216732. {
  216733. const Atom atom = (Atom) clientMsg->data.l[0];
  216734. if (atom == Atoms::ProtocolList [Atoms::PING])
  216735. {
  216736. Window root = RootWindow (display, DefaultScreen (display));
  216737. event->xclient.window = root;
  216738. XSendEvent (display, root, False, NoEventMask, event);
  216739. XFlush (display);
  216740. }
  216741. else if (atom == Atoms::ProtocolList [Atoms::TAKE_FOCUS])
  216742. {
  216743. XWindowAttributes atts;
  216744. ScopedXLock xlock;
  216745. if (clientMsg->window != 0
  216746. && XGetWindowAttributes (display, clientMsg->window, &atts))
  216747. {
  216748. if (atts.map_state == IsViewable)
  216749. XSetInputFocus (display, clientMsg->window, RevertToParent, clientMsg->data.l[1]);
  216750. }
  216751. }
  216752. else if (atom == Atoms::ProtocolList [Atoms::DELETE_WINDOW])
  216753. {
  216754. handleUserClosingWindow();
  216755. }
  216756. }
  216757. else if (clientMsg->message_type == Atoms::XdndEnter)
  216758. {
  216759. handleDragAndDropEnter (clientMsg);
  216760. }
  216761. else if (clientMsg->message_type == Atoms::XdndLeave)
  216762. {
  216763. resetDragAndDrop();
  216764. }
  216765. else if (clientMsg->message_type == Atoms::XdndPosition)
  216766. {
  216767. handleDragAndDropPosition (clientMsg);
  216768. }
  216769. else if (clientMsg->message_type == Atoms::XdndDrop)
  216770. {
  216771. handleDragAndDropDrop (clientMsg);
  216772. }
  216773. else if (clientMsg->message_type == Atoms::XdndStatus)
  216774. {
  216775. handleDragAndDropStatus (clientMsg);
  216776. }
  216777. else if (clientMsg->message_type == Atoms::XdndFinished)
  216778. {
  216779. resetDragAndDrop();
  216780. }
  216781. break;
  216782. }
  216783. case SelectionNotify:
  216784. handleDragAndDropSelection (event);
  216785. break;
  216786. case SelectionClear:
  216787. case SelectionRequest:
  216788. break;
  216789. default:
  216790. #if JUCE_USE_XSHM
  216791. {
  216792. ScopedXLock xlock;
  216793. if (event->xany.type == XShmGetEventBase (display))
  216794. repainter->notifyPaintCompleted();
  216795. }
  216796. #endif
  216797. break;
  216798. }
  216799. }
  216800. void showMouseCursor (Cursor cursor) throw()
  216801. {
  216802. ScopedXLock xlock;
  216803. XDefineCursor (display, windowH, cursor);
  216804. }
  216805. void setTaskBarIcon (const Image& image)
  216806. {
  216807. ScopedXLock xlock;
  216808. taskbarImage = image.createCopy();
  216809. Screen* const screen = XDefaultScreenOfDisplay (display);
  216810. const int screenNumber = XScreenNumberOfScreen (screen);
  216811. String screenAtom ("_NET_SYSTEM_TRAY_S");
  216812. screenAtom << screenNumber;
  216813. Atom selectionAtom = XInternAtom (display, screenAtom.toUTF8(), false);
  216814. XGrabServer (display);
  216815. Window managerWin = XGetSelectionOwner (display, selectionAtom);
  216816. if (managerWin != None)
  216817. XSelectInput (display, managerWin, StructureNotifyMask);
  216818. XUngrabServer (display);
  216819. XFlush (display);
  216820. if (managerWin != None)
  216821. {
  216822. XEvent ev;
  216823. zerostruct (ev);
  216824. ev.xclient.type = ClientMessage;
  216825. ev.xclient.window = managerWin;
  216826. ev.xclient.message_type = XInternAtom (display, "_NET_SYSTEM_TRAY_OPCODE", False);
  216827. ev.xclient.format = 32;
  216828. ev.xclient.data.l[0] = CurrentTime;
  216829. ev.xclient.data.l[1] = 0 /*SYSTEM_TRAY_REQUEST_DOCK*/;
  216830. ev.xclient.data.l[2] = windowH;
  216831. ev.xclient.data.l[3] = 0;
  216832. ev.xclient.data.l[4] = 0;
  216833. XSendEvent (display, managerWin, False, NoEventMask, &ev);
  216834. XSync (display, False);
  216835. }
  216836. // For older KDE's ...
  216837. long atomData = 1;
  216838. Atom trayAtom = XInternAtom (display, "KWM_DOCKWINDOW", false);
  216839. XChangeProperty (display, windowH, trayAtom, trayAtom, 32, PropModeReplace, (unsigned char*) &atomData, 1);
  216840. // For more recent KDE's...
  216841. trayAtom = XInternAtom (display, "_KDE_NET_WM_SYSTEM_TRAY_WINDOW_FOR", false);
  216842. XChangeProperty (display, windowH, trayAtom, XA_WINDOW, 32, PropModeReplace, (unsigned char*) &windowH, 1);
  216843. // a minimum size must be specified for GNOME and Xfce, otherwise the icon is displayed with a width of 1
  216844. XSizeHints* hints = XAllocSizeHints();
  216845. hints->flags = PMinSize;
  216846. hints->min_width = 22;
  216847. hints->min_height = 22;
  216848. XSetWMNormalHints (display, windowH, hints);
  216849. XFree (hints);
  216850. }
  216851. const Image* getTaskbarIcon() const throw() { return taskbarImage; }
  216852. juce_UseDebuggingNewOperator
  216853. bool dontRepaint;
  216854. static ModifierKeys currentModifiers;
  216855. static bool isActiveApplication;
  216856. private:
  216857. class LinuxRepaintManager : public Timer
  216858. {
  216859. public:
  216860. LinuxRepaintManager (LinuxComponentPeer* const peer_)
  216861. : peer (peer_),
  216862. lastTimeImageUsed (0)
  216863. {
  216864. #if JUCE_USE_XSHM
  216865. shmCompletedDrawing = true;
  216866. useARGBImagesForRendering = XSHMHelpers::isShmAvailable();
  216867. if (useARGBImagesForRendering)
  216868. {
  216869. ScopedXLock xlock;
  216870. XShmSegmentInfo segmentinfo;
  216871. XImage* const testImage
  216872. = XShmCreateImage (display, DefaultVisual (display, DefaultScreen (display)),
  216873. 24, ZPixmap, 0, &segmentinfo, 64, 64);
  216874. useARGBImagesForRendering = (testImage->bits_per_pixel == 32);
  216875. XDestroyImage (testImage);
  216876. }
  216877. #endif
  216878. }
  216879. ~LinuxRepaintManager()
  216880. {
  216881. }
  216882. void timerCallback()
  216883. {
  216884. #if JUCE_USE_XSHM
  216885. if (! shmCompletedDrawing)
  216886. return;
  216887. #endif
  216888. if (! regionsNeedingRepaint.isEmpty())
  216889. {
  216890. stopTimer();
  216891. performAnyPendingRepaintsNow();
  216892. }
  216893. else if (Time::getApproximateMillisecondCounter() > lastTimeImageUsed + 3000)
  216894. {
  216895. stopTimer();
  216896. image = 0;
  216897. }
  216898. }
  216899. void repaint (int x, int y, int w, int h)
  216900. {
  216901. if (! isTimerRunning())
  216902. startTimer (repaintTimerPeriod);
  216903. regionsNeedingRepaint.add (x, y, w, h);
  216904. }
  216905. void performAnyPendingRepaintsNow()
  216906. {
  216907. #if JUCE_USE_XSHM
  216908. if (! shmCompletedDrawing)
  216909. {
  216910. startTimer (repaintTimerPeriod);
  216911. return;
  216912. }
  216913. #endif
  216914. peer->clearMaskedRegion();
  216915. RectangleList originalRepaintRegion (regionsNeedingRepaint);
  216916. regionsNeedingRepaint.clear();
  216917. const Rectangle<int> totalArea (originalRepaintRegion.getBounds());
  216918. if (! totalArea.isEmpty())
  216919. {
  216920. if (image == 0 || image->getWidth() < totalArea.getWidth()
  216921. || image->getHeight() < totalArea.getHeight())
  216922. {
  216923. #if JUCE_USE_XSHM
  216924. image = new XBitmapImage (useARGBImagesForRendering ? Image::ARGB
  216925. : Image::RGB,
  216926. #else
  216927. image = new XBitmapImage (Image::RGB,
  216928. #endif
  216929. (totalArea.getWidth() + 31) & ~31,
  216930. (totalArea.getHeight() + 31) & ~31,
  216931. false,
  216932. peer->depth,
  216933. peer->visual);
  216934. }
  216935. startTimer (repaintTimerPeriod);
  216936. LowLevelGraphicsSoftwareRenderer context (*image);
  216937. context.setOrigin (-totalArea.getX(), -totalArea.getY());
  216938. if (context.clipToRectangleList (originalRepaintRegion))
  216939. {
  216940. if (peer->depth == 32)
  216941. {
  216942. RectangleList::Iterator i (originalRepaintRegion);
  216943. while (i.next())
  216944. {
  216945. const Rectangle<int>& r = *i.getRectangle();
  216946. image->clear (r.getX() - totalArea.getX(), r.getY() - totalArea.getY(), r.getWidth(), r.getHeight());
  216947. }
  216948. }
  216949. peer->handlePaint (context);
  216950. }
  216951. if (! peer->maskedRegion.isEmpty())
  216952. originalRepaintRegion.subtract (peer->maskedRegion);
  216953. for (RectangleList::Iterator i (originalRepaintRegion); i.next();)
  216954. {
  216955. #if JUCE_USE_XSHM
  216956. shmCompletedDrawing = false;
  216957. #endif
  216958. const Rectangle<int>& r = *i.getRectangle();
  216959. image->blitToWindow (peer->windowH,
  216960. r.getX(), r.getY(), r.getWidth(), r.getHeight(),
  216961. r.getX() - totalArea.getX(), r.getY() - totalArea.getY());
  216962. }
  216963. }
  216964. lastTimeImageUsed = Time::getApproximateMillisecondCounter();
  216965. startTimer (repaintTimerPeriod);
  216966. }
  216967. #if JUCE_USE_XSHM
  216968. void notifyPaintCompleted() { shmCompletedDrawing = true; }
  216969. #endif
  216970. private:
  216971. enum { repaintTimerPeriod = 1000 / 100 };
  216972. LinuxComponentPeer* const peer;
  216973. ScopedPointer <XBitmapImage> image;
  216974. uint32 lastTimeImageUsed;
  216975. RectangleList regionsNeedingRepaint;
  216976. #if JUCE_USE_XSHM
  216977. bool useARGBImagesForRendering, shmCompletedDrawing;
  216978. #endif
  216979. LinuxRepaintManager (const LinuxRepaintManager&);
  216980. LinuxRepaintManager& operator= (const LinuxRepaintManager&);
  216981. };
  216982. ScopedPointer <LinuxRepaintManager> repainter;
  216983. friend class LinuxRepaintManager;
  216984. Window windowH, parentWindow;
  216985. int wx, wy, ww, wh;
  216986. ScopedPointer<Image> taskbarImage;
  216987. bool fullScreen, mapped;
  216988. Visual* visual;
  216989. int depth;
  216990. BorderSize windowBorder;
  216991. struct MotifWmHints
  216992. {
  216993. unsigned long flags;
  216994. unsigned long functions;
  216995. unsigned long decorations;
  216996. long input_mode;
  216997. unsigned long status;
  216998. };
  216999. static void updateKeyStates (const int keycode, const bool press) throw()
  217000. {
  217001. const int keybyte = keycode >> 3;
  217002. const int keybit = (1 << (keycode & 7));
  217003. if (press)
  217004. Keys::keyStates [keybyte] |= keybit;
  217005. else
  217006. Keys::keyStates [keybyte] &= ~keybit;
  217007. }
  217008. static void updateKeyModifiers (const int status) throw()
  217009. {
  217010. int keyMods = 0;
  217011. if (status & ShiftMask) keyMods |= ModifierKeys::shiftModifier;
  217012. if (status & ControlMask) keyMods |= ModifierKeys::ctrlModifier;
  217013. if (status & Keys::AltMask) keyMods |= ModifierKeys::altModifier;
  217014. currentModifiers = currentModifiers.withOnlyMouseButtons().withFlags (keyMods);
  217015. Keys::numLock = ((status & Keys::NumLockMask) != 0);
  217016. Keys::capsLock = ((status & LockMask) != 0);
  217017. }
  217018. static bool updateKeyModifiersFromSym (KeySym sym, const bool press) throw()
  217019. {
  217020. int modifier = 0;
  217021. bool isModifier = true;
  217022. switch (sym)
  217023. {
  217024. case XK_Shift_L:
  217025. case XK_Shift_R:
  217026. modifier = ModifierKeys::shiftModifier;
  217027. break;
  217028. case XK_Control_L:
  217029. case XK_Control_R:
  217030. modifier = ModifierKeys::ctrlModifier;
  217031. break;
  217032. case XK_Alt_L:
  217033. case XK_Alt_R:
  217034. modifier = ModifierKeys::altModifier;
  217035. break;
  217036. case XK_Num_Lock:
  217037. if (press)
  217038. Keys::numLock = ! Keys::numLock;
  217039. break;
  217040. case XK_Caps_Lock:
  217041. if (press)
  217042. Keys::capsLock = ! Keys::capsLock;
  217043. break;
  217044. case XK_Scroll_Lock:
  217045. break;
  217046. default:
  217047. isModifier = false;
  217048. break;
  217049. }
  217050. if (modifier != 0)
  217051. {
  217052. if (press)
  217053. currentModifiers = currentModifiers.withFlags (modifier);
  217054. else
  217055. currentModifiers = currentModifiers.withoutFlags (modifier);
  217056. }
  217057. return isModifier;
  217058. }
  217059. // Alt and Num lock are not defined by standard X
  217060. // modifier constants: check what they're mapped to
  217061. static void updateModifierMappings() throw()
  217062. {
  217063. ScopedXLock xlock;
  217064. const int altLeftCode = XKeysymToKeycode (display, XK_Alt_L);
  217065. const int numLockCode = XKeysymToKeycode (display, XK_Num_Lock);
  217066. Keys::AltMask = 0;
  217067. Keys::NumLockMask = 0;
  217068. XModifierKeymap* mapping = XGetModifierMapping (display);
  217069. if (mapping)
  217070. {
  217071. for (int i = 0; i < 8; i++)
  217072. {
  217073. if (mapping->modifiermap [i << 1] == altLeftCode)
  217074. Keys::AltMask = 1 << i;
  217075. else if (mapping->modifiermap [i << 1] == numLockCode)
  217076. Keys::NumLockMask = 1 << i;
  217077. }
  217078. XFreeModifiermap (mapping);
  217079. }
  217080. }
  217081. void removeWindowDecorations (Window wndH)
  217082. {
  217083. Atom hints = XInternAtom (display, "_MOTIF_WM_HINTS", True);
  217084. if (hints != None)
  217085. {
  217086. MotifWmHints motifHints;
  217087. zerostruct (motifHints);
  217088. motifHints.flags = 2; /* MWM_HINTS_DECORATIONS */
  217089. motifHints.decorations = 0;
  217090. ScopedXLock xlock;
  217091. XChangeProperty (display, wndH, hints, hints, 32, PropModeReplace,
  217092. (unsigned char*) &motifHints, 4);
  217093. }
  217094. hints = XInternAtom (display, "_WIN_HINTS", True);
  217095. if (hints != None)
  217096. {
  217097. long gnomeHints = 0;
  217098. ScopedXLock xlock;
  217099. XChangeProperty (display, wndH, hints, hints, 32, PropModeReplace,
  217100. (unsigned char*) &gnomeHints, 1);
  217101. }
  217102. hints = XInternAtom (display, "KWM_WIN_DECORATION", True);
  217103. if (hints != None)
  217104. {
  217105. long kwmHints = 2; /*KDE_tinyDecoration*/
  217106. ScopedXLock xlock;
  217107. XChangeProperty (display, wndH, hints, hints, 32, PropModeReplace,
  217108. (unsigned char*) &kwmHints, 1);
  217109. }
  217110. }
  217111. void addWindowButtons (Window wndH)
  217112. {
  217113. ScopedXLock xlock;
  217114. Atom hints = XInternAtom (display, "_MOTIF_WM_HINTS", True);
  217115. if (hints != None)
  217116. {
  217117. MotifWmHints motifHints;
  217118. zerostruct (motifHints);
  217119. motifHints.flags = 1 | 2; /* MWM_HINTS_FUNCTIONS | MWM_HINTS_DECORATIONS */
  217120. motifHints.decorations = 2 /* MWM_DECOR_BORDER */ | 8 /* MWM_DECOR_TITLE */ | 16; /* MWM_DECOR_MENU */
  217121. motifHints.functions = 4 /* MWM_FUNC_MOVE */;
  217122. if ((styleFlags & windowHasCloseButton) != 0)
  217123. motifHints.functions |= 32; /* MWM_FUNC_CLOSE */
  217124. if ((styleFlags & windowHasMinimiseButton) != 0)
  217125. {
  217126. motifHints.functions |= 8; /* MWM_FUNC_MINIMIZE */
  217127. motifHints.decorations |= 0x20; /* MWM_DECOR_MINIMIZE */
  217128. }
  217129. if ((styleFlags & windowHasMaximiseButton) != 0)
  217130. {
  217131. motifHints.functions |= 0x10; /* MWM_FUNC_MAXIMIZE */
  217132. motifHints.decorations |= 0x40; /* MWM_DECOR_MAXIMIZE */
  217133. }
  217134. if ((styleFlags & windowIsResizable) != 0)
  217135. {
  217136. motifHints.functions |= 2; /* MWM_FUNC_RESIZE */
  217137. motifHints.decorations |= 0x4; /* MWM_DECOR_RESIZEH */
  217138. }
  217139. XChangeProperty (display, wndH, hints, hints, 32, 0, (unsigned char*) &motifHints, 5);
  217140. }
  217141. hints = XInternAtom (display, "_NET_WM_ALLOWED_ACTIONS", True);
  217142. if (hints != None)
  217143. {
  217144. int netHints [6];
  217145. int num = 0;
  217146. netHints [num++] = XInternAtom (display, "_NET_WM_ACTION_RESIZE", (styleFlags & windowIsResizable) ? True : False);
  217147. netHints [num++] = XInternAtom (display, "_NET_WM_ACTION_FULLSCREEN", (styleFlags & windowHasMaximiseButton) ? True : False);
  217148. netHints [num++] = XInternAtom (display, "_NET_WM_ACTION_MINIMIZE", (styleFlags & windowHasMinimiseButton) ? True : False);
  217149. netHints [num++] = XInternAtom (display, "_NET_WM_ACTION_CLOSE", (styleFlags & windowHasCloseButton) ? True : False);
  217150. XChangeProperty (display, wndH, hints, XA_ATOM, 32, PropModeReplace,
  217151. (unsigned char*) &netHints, num);
  217152. }
  217153. }
  217154. void setWindowType (Window wndH)
  217155. {
  217156. int netHints [2];
  217157. int numHints = 0;
  217158. if ((styleFlags & windowIsTemporary) != 0
  217159. || ((styleFlags & windowHasDropShadow) == 0 && Desktop::canUseSemiTransparentWindows()))
  217160. {
  217161. netHints [numHints] = XInternAtom (display, "_NET_WM_WINDOW_TYPE_COMBO", True);
  217162. }
  217163. else
  217164. {
  217165. netHints [numHints] = XInternAtom (display, "_NET_WM_WINDOW_TYPE_NORMAL", True);
  217166. }
  217167. if (netHints [numHints] != 0)
  217168. ++numHints;
  217169. netHints[numHints] = XInternAtom (display, "_KDE_NET_WM_WINDOW_TYPE_OVERRIDE", True);
  217170. if (netHints [numHints] != 0)
  217171. ++numHints;
  217172. XChangeProperty (display, wndH, Atoms::WindowType, XA_ATOM, 32, PropModeReplace,
  217173. (unsigned char*) &netHints, numHints);
  217174. if ((styleFlags & windowAppearsOnTaskbar) == 0)
  217175. {
  217176. Atom skipTaskbar = XInternAtom (display, "_NET_WM_STATE_SKIP_TASKBAR", False);
  217177. XChangeProperty (display, wndH, Atoms::WindowState, XA_ATOM, 32, PropModeReplace,
  217178. (unsigned char*) &skipTaskbar, 1);
  217179. }
  217180. }
  217181. void createWindow()
  217182. {
  217183. ScopedXLock xlock;
  217184. Atoms::initialiseAtoms();
  217185. resetDragAndDrop();
  217186. // Get defaults for various properties
  217187. const int screen = DefaultScreen (display);
  217188. Window root = RootWindow (display, screen);
  217189. // Try to obtain a 32-bit visual or fallback to 24 or 16
  217190. visual = Visuals::findVisualFormat ((styleFlags & windowIsSemiTransparent) ? 32 : 24, depth);
  217191. if (visual == 0)
  217192. {
  217193. Logger::outputDebugString ("ERROR: System doesn't support 32, 24 or 16 bit RGB display.\n");
  217194. Process::terminate();
  217195. }
  217196. // Create and install a colormap suitable fr our visual
  217197. Colormap colormap = XCreateColormap (display, root, visual, AllocNone);
  217198. XInstallColormap (display, colormap);
  217199. // Set up the window attributes
  217200. XSetWindowAttributes swa;
  217201. swa.border_pixel = 0;
  217202. swa.background_pixmap = None;
  217203. swa.colormap = colormap;
  217204. swa.override_redirect = getComponent()->isAlwaysOnTop() ? True : False;
  217205. swa.event_mask = getAllEventsMask();
  217206. Window wndH = XCreateWindow (display, root,
  217207. 0, 0, 1, 1,
  217208. 0, depth, InputOutput, visual,
  217209. CWBorderPixel | CWColormap | CWBackPixmap | CWEventMask | CWOverrideRedirect,
  217210. &swa);
  217211. XGrabButton (display, AnyButton, AnyModifier, wndH, False,
  217212. ButtonPressMask | ButtonReleaseMask | EnterWindowMask | LeaveWindowMask | PointerMotionMask,
  217213. GrabModeAsync, GrabModeAsync, None, None);
  217214. // Set the window context to identify the window handle object
  217215. if (XSaveContext (display, (XID) wndH, windowHandleXContext, (XPointer) this))
  217216. {
  217217. // Failed
  217218. jassertfalse
  217219. Logger::outputDebugString ("Failed to create context information for window.\n");
  217220. XDestroyWindow (display, wndH);
  217221. wndH = 0;
  217222. }
  217223. // Set window manager hints
  217224. XWMHints* wmHints = XAllocWMHints();
  217225. wmHints->flags = InputHint | StateHint;
  217226. wmHints->input = True; // Locally active input model
  217227. wmHints->initial_state = NormalState;
  217228. XSetWMHints (display, wndH, wmHints);
  217229. XFree (wmHints);
  217230. // Set the window type
  217231. setWindowType (wndH);
  217232. // Define decoration
  217233. if ((styleFlags & windowHasTitleBar) == 0)
  217234. removeWindowDecorations (wndH);
  217235. else
  217236. addWindowButtons (wndH);
  217237. // Set window name
  217238. setWindowTitle (wndH, getComponent()->getName());
  217239. // Associate the PID, allowing to be shut down when something goes wrong
  217240. unsigned long pid = getpid();
  217241. XChangeProperty (display, wndH, Atoms::Pid, XA_CARDINAL, 32, PropModeReplace,
  217242. (unsigned char*) &pid, 1);
  217243. // Set window manager protocols
  217244. XChangeProperty (display, wndH, Atoms::Protocols, XA_ATOM, 32, PropModeReplace,
  217245. (unsigned char*) Atoms::ProtocolList, 2);
  217246. // Set drag and drop flags
  217247. XChangeProperty (display, wndH, Atoms::XdndTypeList, XA_ATOM, 32, PropModeReplace,
  217248. (const unsigned char*) Atoms::allowedMimeTypes, numElementsInArray (Atoms::allowedMimeTypes));
  217249. XChangeProperty (display, wndH, Atoms::XdndActionList, XA_ATOM, 32, PropModeReplace,
  217250. (const unsigned char*) Atoms::allowedActions, numElementsInArray (Atoms::allowedActions));
  217251. XChangeProperty (display, wndH, Atoms::XdndActionDescription, XA_STRING, 8, PropModeReplace,
  217252. (const unsigned char*) "", 0);
  217253. unsigned long dndVersion = Atoms::DndVersion;
  217254. XChangeProperty (display, wndH, Atoms::XdndAware, XA_ATOM, 32, PropModeReplace,
  217255. (const unsigned char*) &dndVersion, 1);
  217256. // Initialise the pointer and keyboard mapping
  217257. // This is not the same as the logical pointer mapping the X server uses:
  217258. // we don't mess with this.
  217259. static bool mappingInitialised = false;
  217260. if (! mappingInitialised)
  217261. {
  217262. mappingInitialised = true;
  217263. const int numButtons = XGetPointerMapping (display, 0, 0);
  217264. if (numButtons == 2)
  217265. {
  217266. pointerMap[0] = Keys::LeftButton;
  217267. pointerMap[1] = Keys::RightButton;
  217268. pointerMap[2] = pointerMap[3] = pointerMap[4] = Keys::NoButton;
  217269. }
  217270. else if (numButtons >= 3)
  217271. {
  217272. pointerMap[0] = Keys::LeftButton;
  217273. pointerMap[1] = Keys::MiddleButton;
  217274. pointerMap[2] = Keys::RightButton;
  217275. if (numButtons >= 5)
  217276. {
  217277. pointerMap[3] = Keys::WheelUp;
  217278. pointerMap[4] = Keys::WheelDown;
  217279. }
  217280. }
  217281. updateModifierMappings();
  217282. }
  217283. windowH = wndH;
  217284. }
  217285. void destroyWindow()
  217286. {
  217287. ScopedXLock xlock;
  217288. XPointer handlePointer;
  217289. if (! XFindContext (display, (XID) windowH, windowHandleXContext, &handlePointer))
  217290. XDeleteContext (display, (XID) windowH, windowHandleXContext);
  217291. XDestroyWindow (display, windowH);
  217292. // Wait for it to complete and then remove any events for this
  217293. // window from the event queue.
  217294. XSync (display, false);
  217295. XEvent event;
  217296. while (XCheckWindowEvent (display, windowH, getAllEventsMask(), &event) == True)
  217297. {}
  217298. }
  217299. static int getAllEventsMask() throw()
  217300. {
  217301. return NoEventMask | KeyPressMask | KeyReleaseMask | ButtonPressMask | ButtonReleaseMask
  217302. | EnterWindowMask | LeaveWindowMask | PointerMotionMask | KeymapStateMask
  217303. | ExposureMask | StructureNotifyMask | FocusChangeMask;
  217304. }
  217305. static int64 getEventTime (::Time t)
  217306. {
  217307. static int64 eventTimeOffset = 0x12345678;
  217308. const int64 thisMessageTime = t;
  217309. if (eventTimeOffset == 0x12345678)
  217310. eventTimeOffset = Time::currentTimeMillis() - thisMessageTime;
  217311. return eventTimeOffset + thisMessageTime;
  217312. }
  217313. static void setWindowTitle (Window xwin, const String& title)
  217314. {
  217315. XTextProperty nameProperty;
  217316. char* strings[] = { const_cast <char*> (title.toUTF8()) };
  217317. ScopedXLock xlock;
  217318. if (XStringListToTextProperty (strings, 1, &nameProperty))
  217319. {
  217320. XSetWMName (display, xwin, &nameProperty);
  217321. XSetWMIconName (display, xwin, &nameProperty);
  217322. XFree (nameProperty.value);
  217323. }
  217324. }
  217325. void updateBorderSize()
  217326. {
  217327. if ((styleFlags & windowHasTitleBar) == 0)
  217328. {
  217329. windowBorder = BorderSize (0);
  217330. }
  217331. else if (windowBorder.getTopAndBottom() == 0 && windowBorder.getLeftAndRight() == 0)
  217332. {
  217333. ScopedXLock xlock;
  217334. Atom hints = XInternAtom (display, "_NET_FRAME_EXTENTS", True);
  217335. if (hints != None)
  217336. {
  217337. unsigned char* data = 0;
  217338. unsigned long nitems, bytesLeft;
  217339. Atom actualType;
  217340. int actualFormat;
  217341. if (XGetWindowProperty (display, windowH, hints, 0, 4, False,
  217342. XA_CARDINAL, &actualType, &actualFormat, &nitems, &bytesLeft,
  217343. &data) == Success)
  217344. {
  217345. const unsigned long* const sizes = (const unsigned long*) data;
  217346. if (actualFormat == 32)
  217347. windowBorder = BorderSize ((int) sizes[2], (int) sizes[0],
  217348. (int) sizes[3], (int) sizes[1]);
  217349. XFree (data);
  217350. }
  217351. }
  217352. }
  217353. }
  217354. void updateBounds()
  217355. {
  217356. jassert (windowH != 0);
  217357. if (windowH != 0)
  217358. {
  217359. Window root, child;
  217360. unsigned int bw, depth;
  217361. ScopedXLock xlock;
  217362. if (! XGetGeometry (display, (::Drawable) windowH, &root,
  217363. &wx, &wy, (unsigned int*) &ww, (unsigned int*) &wh,
  217364. &bw, &depth))
  217365. {
  217366. wx = wy = ww = wh = 0;
  217367. }
  217368. else if (! XTranslateCoordinates (display, windowH, root, 0, 0, &wx, &wy, &child))
  217369. {
  217370. wx = wy = 0;
  217371. }
  217372. }
  217373. }
  217374. void resetDragAndDrop()
  217375. {
  217376. dragAndDropFiles.clear();
  217377. lastDropPos = Point<int> (-1, -1);
  217378. dragAndDropCurrentMimeType = 0;
  217379. dragAndDropSourceWindow = 0;
  217380. srcMimeTypeAtomList.clear();
  217381. }
  217382. void sendDragAndDropMessage (XClientMessageEvent& msg)
  217383. {
  217384. msg.type = ClientMessage;
  217385. msg.display = display;
  217386. msg.window = dragAndDropSourceWindow;
  217387. msg.format = 32;
  217388. msg.data.l[0] = windowH;
  217389. ScopedXLock xlock;
  217390. XSendEvent (display, dragAndDropSourceWindow, False, 0, (XEvent*) &msg);
  217391. }
  217392. void sendDragAndDropStatus (const bool acceptDrop, Atom dropAction)
  217393. {
  217394. XClientMessageEvent msg;
  217395. zerostruct (msg);
  217396. msg.message_type = Atoms::XdndStatus;
  217397. msg.data.l[1] = (acceptDrop ? 1 : 0) | 2; // 2 indicates that we want to receive position messages
  217398. msg.data.l[4] = dropAction;
  217399. sendDragAndDropMessage (msg);
  217400. }
  217401. void sendDragAndDropLeave()
  217402. {
  217403. XClientMessageEvent msg;
  217404. zerostruct (msg);
  217405. msg.message_type = Atoms::XdndLeave;
  217406. sendDragAndDropMessage (msg);
  217407. }
  217408. void sendDragAndDropFinish()
  217409. {
  217410. XClientMessageEvent msg;
  217411. zerostruct (msg);
  217412. msg.message_type = Atoms::XdndFinished;
  217413. sendDragAndDropMessage (msg);
  217414. }
  217415. void handleDragAndDropStatus (const XClientMessageEvent* const clientMsg)
  217416. {
  217417. if ((clientMsg->data.l[1] & 1) == 0)
  217418. {
  217419. sendDragAndDropLeave();
  217420. if (dragAndDropFiles.size() > 0)
  217421. handleFileDragExit (dragAndDropFiles);
  217422. dragAndDropFiles.clear();
  217423. }
  217424. }
  217425. void handleDragAndDropPosition (const XClientMessageEvent* const clientMsg)
  217426. {
  217427. if (dragAndDropSourceWindow == 0)
  217428. return;
  217429. dragAndDropSourceWindow = clientMsg->data.l[0];
  217430. Point<int> dropPos ((int) clientMsg->data.l[2] >> 16,
  217431. (int) clientMsg->data.l[2] & 0xffff);
  217432. dropPos -= getScreenPosition();
  217433. if (lastDropPos != dropPos)
  217434. {
  217435. lastDropPos = dropPos;
  217436. dragAndDropTimestamp = clientMsg->data.l[3];
  217437. Atom targetAction = Atoms::XdndActionCopy;
  217438. for (int i = numElementsInArray (Atoms::allowedActions); --i >= 0;)
  217439. {
  217440. if ((Atom) clientMsg->data.l[4] == Atoms::allowedActions[i])
  217441. {
  217442. targetAction = Atoms::allowedActions[i];
  217443. break;
  217444. }
  217445. }
  217446. sendDragAndDropStatus (true, targetAction);
  217447. if (dragAndDropFiles.size() == 0)
  217448. updateDraggedFileList (clientMsg);
  217449. if (dragAndDropFiles.size() > 0)
  217450. handleFileDragMove (dragAndDropFiles, dropPos);
  217451. }
  217452. }
  217453. void handleDragAndDropDrop (const XClientMessageEvent* const clientMsg)
  217454. {
  217455. if (dragAndDropFiles.size() == 0)
  217456. updateDraggedFileList (clientMsg);
  217457. const StringArray files (dragAndDropFiles);
  217458. const Point<int> lastPos (lastDropPos);
  217459. sendDragAndDropFinish();
  217460. resetDragAndDrop();
  217461. if (files.size() > 0)
  217462. handleFileDragDrop (files, lastPos);
  217463. }
  217464. void handleDragAndDropEnter (const XClientMessageEvent* const clientMsg)
  217465. {
  217466. dragAndDropFiles.clear();
  217467. srcMimeTypeAtomList.clear();
  217468. dragAndDropCurrentMimeType = 0;
  217469. const unsigned long dndCurrentVersion = static_cast <unsigned long> (clientMsg->data.l[1] & 0xff000000) >> 24;
  217470. if (dndCurrentVersion < 3 || dndCurrentVersion > Atoms::DndVersion)
  217471. {
  217472. dragAndDropSourceWindow = 0;
  217473. return;
  217474. }
  217475. dragAndDropSourceWindow = clientMsg->data.l[0];
  217476. if ((clientMsg->data.l[1] & 1) != 0)
  217477. {
  217478. Atom actual;
  217479. int format;
  217480. unsigned long count = 0, remaining = 0;
  217481. unsigned char* data = 0;
  217482. ScopedXLock xlock;
  217483. XGetWindowProperty (display, dragAndDropSourceWindow, Atoms::XdndTypeList,
  217484. 0, 0x8000000L, False, XA_ATOM, &actual, &format,
  217485. &count, &remaining, &data);
  217486. if (data != 0)
  217487. {
  217488. if (actual == XA_ATOM && format == 32 && count != 0)
  217489. {
  217490. const unsigned long* const types = (const unsigned long*) data;
  217491. for (unsigned int i = 0; i < count; ++i)
  217492. if (types[i] != None)
  217493. srcMimeTypeAtomList.add (types[i]);
  217494. }
  217495. XFree (data);
  217496. }
  217497. }
  217498. if (srcMimeTypeAtomList.size() == 0)
  217499. {
  217500. for (int i = 2; i < 5; ++i)
  217501. if (clientMsg->data.l[i] != None)
  217502. srcMimeTypeAtomList.add (clientMsg->data.l[i]);
  217503. if (srcMimeTypeAtomList.size() == 0)
  217504. {
  217505. dragAndDropSourceWindow = 0;
  217506. return;
  217507. }
  217508. }
  217509. for (int i = 0; i < srcMimeTypeAtomList.size() && dragAndDropCurrentMimeType == 0; ++i)
  217510. for (int j = 0; j < numElementsInArray (Atoms::allowedMimeTypes); ++j)
  217511. if (srcMimeTypeAtomList[i] == Atoms::allowedMimeTypes[j])
  217512. dragAndDropCurrentMimeType = Atoms::allowedMimeTypes[j];
  217513. handleDragAndDropPosition (clientMsg);
  217514. }
  217515. void handleDragAndDropSelection (const XEvent* const evt)
  217516. {
  217517. dragAndDropFiles.clear();
  217518. if (evt->xselection.property != 0)
  217519. {
  217520. StringArray lines;
  217521. {
  217522. MemoryBlock dropData;
  217523. for (;;)
  217524. {
  217525. Atom actual;
  217526. uint8* data = 0;
  217527. unsigned long count = 0, remaining = 0;
  217528. int format = 0;
  217529. ScopedXLock xlock;
  217530. if (XGetWindowProperty (display, evt->xany.window, evt->xselection.property,
  217531. dropData.getSize() / 4, 65536, 1, AnyPropertyType, &actual,
  217532. &format, &count, &remaining, &data) == Success)
  217533. {
  217534. dropData.append (data, count * format / 8);
  217535. XFree (data);
  217536. if (remaining == 0)
  217537. break;
  217538. }
  217539. else
  217540. {
  217541. XFree (data);
  217542. break;
  217543. }
  217544. }
  217545. lines.addLines (dropData.toString());
  217546. }
  217547. for (int i = 0; i < lines.size(); ++i)
  217548. dragAndDropFiles.add (URL::removeEscapeChars (lines[i].fromFirstOccurrenceOf ("file://", false, true)));
  217549. dragAndDropFiles.trim();
  217550. dragAndDropFiles.removeEmptyStrings();
  217551. }
  217552. }
  217553. void updateDraggedFileList (const XClientMessageEvent* const clientMsg)
  217554. {
  217555. dragAndDropFiles.clear();
  217556. if (dragAndDropSourceWindow != None
  217557. && dragAndDropCurrentMimeType != 0)
  217558. {
  217559. dragAndDropTimestamp = clientMsg->data.l[2];
  217560. ScopedXLock xlock;
  217561. XConvertSelection (display,
  217562. Atoms::XdndSelection,
  217563. dragAndDropCurrentMimeType,
  217564. XInternAtom (display, "JXSelectionWindowProperty", 0),
  217565. windowH,
  217566. dragAndDropTimestamp);
  217567. }
  217568. }
  217569. StringArray dragAndDropFiles;
  217570. int dragAndDropTimestamp;
  217571. Point<int> lastDropPos;
  217572. Atom dragAndDropCurrentMimeType;
  217573. Window dragAndDropSourceWindow;
  217574. Array <Atom> srcMimeTypeAtomList;
  217575. static int pointerMap[5];
  217576. static Point<int> lastMousePos;
  217577. static void clearLastMousePos() throw()
  217578. {
  217579. lastMousePos = Point<int> (0x100000, 0x100000);
  217580. }
  217581. };
  217582. ModifierKeys LinuxComponentPeer::currentModifiers;
  217583. bool LinuxComponentPeer::isActiveApplication = false;
  217584. int LinuxComponentPeer::pointerMap[5];
  217585. Point<int> LinuxComponentPeer::lastMousePos;
  217586. bool Process::isForegroundProcess()
  217587. {
  217588. return LinuxComponentPeer::isActiveApplication;
  217589. }
  217590. void ModifierKeys::updateCurrentModifiers() throw()
  217591. {
  217592. currentModifiers = LinuxComponentPeer::currentModifiers;
  217593. }
  217594. const ModifierKeys ModifierKeys::getCurrentModifiersRealtime() throw()
  217595. {
  217596. Window root, child;
  217597. int x, y, winx, winy;
  217598. unsigned int mask;
  217599. int mouseMods = 0;
  217600. ScopedXLock xlock;
  217601. if (XQueryPointer (display, RootWindow (display, DefaultScreen (display)),
  217602. &root, &child, &x, &y, &winx, &winy, &mask) != False)
  217603. {
  217604. if ((mask & Button1Mask) != 0) mouseMods |= ModifierKeys::leftButtonModifier;
  217605. if ((mask & Button2Mask) != 0) mouseMods |= ModifierKeys::middleButtonModifier;
  217606. if ((mask & Button3Mask) != 0) mouseMods |= ModifierKeys::rightButtonModifier;
  217607. }
  217608. LinuxComponentPeer::currentModifiers = LinuxComponentPeer::currentModifiers.withoutMouseButtons().withFlags (mouseMods);
  217609. return LinuxComponentPeer::currentModifiers;
  217610. }
  217611. void juce_setKioskComponent (Component* kioskModeComponent, bool enableOrDisable, bool allowMenusAndBars)
  217612. {
  217613. if (enableOrDisable)
  217614. kioskModeComponent->setBounds (Desktop::getInstance().getMainMonitorArea (false));
  217615. }
  217616. ComponentPeer* Component::createNewPeer (int styleFlags, void* /*nativeWindowToAttachTo*/)
  217617. {
  217618. return new LinuxComponentPeer (this, styleFlags);
  217619. }
  217620. // (this callback is hooked up in the messaging code)
  217621. void juce_windowMessageReceive (XEvent* event)
  217622. {
  217623. if (event->xany.window != None)
  217624. {
  217625. LinuxComponentPeer* const peer = LinuxComponentPeer::getPeerFor (event->xany.window);
  217626. if (ComponentPeer::isValidPeer (peer))
  217627. peer->handleWindowMessage (event);
  217628. }
  217629. else
  217630. {
  217631. switch (event->xany.type)
  217632. {
  217633. case KeymapNotify:
  217634. {
  217635. const XKeymapEvent* const keymapEvent = (const XKeymapEvent*) &event->xkeymap;
  217636. memcpy (Keys::keyStates, keymapEvent->key_vector, 32);
  217637. break;
  217638. }
  217639. default:
  217640. break;
  217641. }
  217642. }
  217643. }
  217644. void juce_updateMultiMonitorInfo (Array <Rectangle<int> >& monitorCoords, const bool /*clipToWorkArea*/)
  217645. {
  217646. if (display == 0)
  217647. return;
  217648. #if JUCE_USE_XINERAMA
  217649. int major_opcode, first_event, first_error;
  217650. ScopedXLock xlock;
  217651. if (XQueryExtension (display, "XINERAMA", &major_opcode, &first_event, &first_error))
  217652. {
  217653. typedef Bool (*tXineramaIsActive) (Display*);
  217654. typedef XineramaScreenInfo* (*tXineramaQueryScreens) (Display*, int*);
  217655. static tXineramaIsActive xXineramaIsActive = 0;
  217656. static tXineramaQueryScreens xXineramaQueryScreens = 0;
  217657. if (xXineramaIsActive == 0 || xXineramaQueryScreens == 0)
  217658. {
  217659. void* h = dlopen ("libXinerama.so", RTLD_GLOBAL | RTLD_NOW);
  217660. if (h != 0)
  217661. {
  217662. xXineramaIsActive = (tXineramaIsActive) dlsym (h, "XineramaIsActive");
  217663. xXineramaQueryScreens = (tXineramaQueryScreens) dlsym (h, "XineramaQueryScreens");
  217664. }
  217665. }
  217666. if (xXineramaIsActive != 0
  217667. && xXineramaQueryScreens != 0
  217668. && xXineramaIsActive (display))
  217669. {
  217670. int numMonitors = 0;
  217671. XineramaScreenInfo* const screens = xXineramaQueryScreens (display, &numMonitors);
  217672. if (screens != 0)
  217673. {
  217674. for (int i = numMonitors; --i >= 0;)
  217675. {
  217676. int index = screens[i].screen_number;
  217677. if (index >= 0)
  217678. {
  217679. while (monitorCoords.size() < index)
  217680. monitorCoords.add (Rectangle<int>());
  217681. monitorCoords.set (index, Rectangle<int> (screens[i].x_org,
  217682. screens[i].y_org,
  217683. screens[i].width,
  217684. screens[i].height));
  217685. }
  217686. }
  217687. XFree (screens);
  217688. }
  217689. }
  217690. }
  217691. if (monitorCoords.size() == 0)
  217692. #endif
  217693. {
  217694. Atom hints = XInternAtom (display, "_NET_WORKAREA", True);
  217695. if (hints != None)
  217696. {
  217697. const int numMonitors = ScreenCount (display);
  217698. for (int i = 0; i < numMonitors; ++i)
  217699. {
  217700. Window root = RootWindow (display, i);
  217701. unsigned long nitems, bytesLeft;
  217702. Atom actualType;
  217703. int actualFormat;
  217704. unsigned char* data = 0;
  217705. if (XGetWindowProperty (display, root, hints, 0, 4, False,
  217706. XA_CARDINAL, &actualType, &actualFormat, &nitems, &bytesLeft,
  217707. &data) == Success)
  217708. {
  217709. const long* const position = (const long*) data;
  217710. if (actualType == XA_CARDINAL && actualFormat == 32 && nitems == 4)
  217711. monitorCoords.add (Rectangle<int> (position[0], position[1],
  217712. position[2], position[3]));
  217713. XFree (data);
  217714. }
  217715. }
  217716. }
  217717. if (monitorCoords.size() == 0)
  217718. {
  217719. monitorCoords.add (Rectangle<int> (0, 0,
  217720. DisplayWidth (display, DefaultScreen (display)),
  217721. DisplayHeight (display, DefaultScreen (display))));
  217722. }
  217723. }
  217724. }
  217725. void Desktop::createMouseInputSources()
  217726. {
  217727. mouseSources.add (new MouseInputSource (0, true));
  217728. }
  217729. bool Desktop::canUseSemiTransparentWindows() throw()
  217730. {
  217731. int matchedDepth = 0;
  217732. const int desiredDepth = 32;
  217733. return Visuals::findVisualFormat (desiredDepth, matchedDepth) != 0
  217734. && (matchedDepth == desiredDepth);
  217735. }
  217736. const Point<int> Desktop::getMousePosition()
  217737. {
  217738. Window root, child;
  217739. int x, y, winx, winy;
  217740. unsigned int mask;
  217741. ScopedXLock xlock;
  217742. if (XQueryPointer (display,
  217743. RootWindow (display, DefaultScreen (display)),
  217744. &root, &child,
  217745. &x, &y, &winx, &winy, &mask) == False)
  217746. {
  217747. // Pointer not on the default screen
  217748. x = y = -1;
  217749. }
  217750. return Point<int> (x, y);
  217751. }
  217752. void Desktop::setMousePosition (const Point<int>& newPosition)
  217753. {
  217754. ScopedXLock xlock;
  217755. Window root = RootWindow (display, DefaultScreen (display));
  217756. XWarpPointer (display, None, root, 0, 0, 0, 0, newPosition.getX(), newPosition.getY());
  217757. }
  217758. static bool screenSaverAllowed = true;
  217759. void Desktop::setScreenSaverEnabled (const bool isEnabled) throw()
  217760. {
  217761. if (screenSaverAllowed != isEnabled)
  217762. {
  217763. screenSaverAllowed = isEnabled;
  217764. typedef void (*tXScreenSaverSuspend) (Display*, Bool);
  217765. static tXScreenSaverSuspend xScreenSaverSuspend = 0;
  217766. if (xScreenSaverSuspend == 0)
  217767. {
  217768. void* h = dlopen ("libXss.so", RTLD_GLOBAL | RTLD_NOW);
  217769. if (h != 0)
  217770. xScreenSaverSuspend = (tXScreenSaverSuspend) dlsym (h, "XScreenSaverSuspend");
  217771. }
  217772. ScopedXLock xlock;
  217773. if (xScreenSaverSuspend != 0)
  217774. xScreenSaverSuspend (display, ! isEnabled);
  217775. }
  217776. }
  217777. bool Desktop::isScreenSaverEnabled() throw()
  217778. {
  217779. return screenSaverAllowed;
  217780. }
  217781. void* MouseCursor::createMouseCursorFromImage (const Image& image, int hotspotX, int hotspotY)
  217782. {
  217783. ScopedXLock xlock;
  217784. const unsigned int imageW = image.getWidth();
  217785. const unsigned int imageH = image.getHeight();
  217786. #if JUCE_USE_XCURSOR
  217787. {
  217788. typedef XcursorBool (*tXcursorSupportsARGB) (Display*);
  217789. typedef XcursorImage* (*tXcursorImageCreate) (int, int);
  217790. typedef void (*tXcursorImageDestroy) (XcursorImage*);
  217791. typedef Cursor (*tXcursorImageLoadCursor) (Display*, const XcursorImage*);
  217792. static tXcursorSupportsARGB xXcursorSupportsARGB = 0;
  217793. static tXcursorImageCreate xXcursorImageCreate = 0;
  217794. static tXcursorImageDestroy xXcursorImageDestroy = 0;
  217795. static tXcursorImageLoadCursor xXcursorImageLoadCursor = 0;
  217796. static bool hasBeenLoaded = false;
  217797. if (! hasBeenLoaded)
  217798. {
  217799. hasBeenLoaded = true;
  217800. void* h = dlopen ("libXcursor.so", RTLD_GLOBAL | RTLD_NOW);
  217801. if (h != 0)
  217802. {
  217803. xXcursorSupportsARGB = (tXcursorSupportsARGB) dlsym (h, "XcursorSupportsARGB");
  217804. xXcursorImageCreate = (tXcursorImageCreate) dlsym (h, "XcursorImageCreate");
  217805. xXcursorImageLoadCursor = (tXcursorImageLoadCursor) dlsym (h, "XcursorImageLoadCursor");
  217806. xXcursorImageDestroy = (tXcursorImageDestroy) dlsym (h, "XcursorImageDestroy");
  217807. if (xXcursorSupportsARGB == 0 || xXcursorImageCreate == 0
  217808. || xXcursorImageLoadCursor == 0 || xXcursorImageDestroy == 0
  217809. || ! xXcursorSupportsARGB (display))
  217810. xXcursorSupportsARGB = 0;
  217811. }
  217812. }
  217813. if (xXcursorSupportsARGB != 0)
  217814. {
  217815. XcursorImage* xcImage = xXcursorImageCreate (imageW, imageH);
  217816. if (xcImage != 0)
  217817. {
  217818. xcImage->xhot = hotspotX;
  217819. xcImage->yhot = hotspotY;
  217820. XcursorPixel* dest = xcImage->pixels;
  217821. for (int y = 0; y < (int) imageH; ++y)
  217822. for (int x = 0; x < (int) imageW; ++x)
  217823. *dest++ = image.getPixelAt (x, y).getARGB();
  217824. void* result = (void*) xXcursorImageLoadCursor (display, xcImage);
  217825. xXcursorImageDestroy (xcImage);
  217826. if (result != 0)
  217827. return result;
  217828. }
  217829. }
  217830. }
  217831. #endif
  217832. Window root = RootWindow (display, DefaultScreen (display));
  217833. unsigned int cursorW, cursorH;
  217834. if (! XQueryBestCursor (display, root, imageW, imageH, &cursorW, &cursorH))
  217835. return 0;
  217836. Image im (Image::ARGB, cursorW, cursorH, true);
  217837. {
  217838. Graphics g (im);
  217839. if (imageW > cursorW || imageH > cursorH)
  217840. {
  217841. hotspotX = (hotspotX * cursorW) / imageW;
  217842. hotspotY = (hotspotY * cursorH) / imageH;
  217843. g.drawImageWithin (&image, 0, 0, imageW, imageH,
  217844. RectanglePlacement::xLeft | RectanglePlacement::yTop | RectanglePlacement::onlyReduceInSize,
  217845. false);
  217846. }
  217847. else
  217848. {
  217849. g.drawImageAt (&image, 0, 0);
  217850. }
  217851. }
  217852. const int stride = (cursorW + 7) >> 3;
  217853. HeapBlock <char> maskPlane, sourcePlane;
  217854. maskPlane.calloc (stride * cursorH);
  217855. sourcePlane.calloc (stride * cursorH);
  217856. const bool msbfirst = (BitmapBitOrder (display) == MSBFirst);
  217857. for (int y = cursorH; --y >= 0;)
  217858. {
  217859. for (int x = cursorW; --x >= 0;)
  217860. {
  217861. const char mask = (char) (1 << (msbfirst ? (7 - (x & 7)) : (x & 7)));
  217862. const int offset = y * stride + (x >> 3);
  217863. const Colour c (im.getPixelAt (x, y));
  217864. if (c.getAlpha() >= 128)
  217865. maskPlane[offset] |= mask;
  217866. if (c.getBrightness() >= 0.5f)
  217867. sourcePlane[offset] |= mask;
  217868. }
  217869. }
  217870. Pixmap sourcePixmap = XCreatePixmapFromBitmapData (display, root, sourcePlane.getData(), cursorW, cursorH, 0xffff, 0, 1);
  217871. Pixmap maskPixmap = XCreatePixmapFromBitmapData (display, root, maskPlane.getData(), cursorW, cursorH, 0xffff, 0, 1);
  217872. XColor white, black;
  217873. black.red = black.green = black.blue = 0;
  217874. white.red = white.green = white.blue = 0xffff;
  217875. void* result = (void*) XCreatePixmapCursor (display, sourcePixmap, maskPixmap, &white, &black, hotspotX, hotspotY);
  217876. XFreePixmap (display, sourcePixmap);
  217877. XFreePixmap (display, maskPixmap);
  217878. return result;
  217879. }
  217880. void MouseCursor::deleteMouseCursor (void* const cursorHandle, const bool)
  217881. {
  217882. ScopedXLock xlock;
  217883. if (cursorHandle != 0)
  217884. XFreeCursor (display, (Cursor) cursorHandle);
  217885. }
  217886. void* MouseCursor::createStandardMouseCursor (MouseCursor::StandardCursorType type)
  217887. {
  217888. unsigned int shape;
  217889. switch (type)
  217890. {
  217891. case NormalCursor: return None; // Use parent cursor
  217892. case NoCursor: return createMouseCursorFromImage (Image (Image::ARGB, 16, 16, true), 0, 0);
  217893. case WaitCursor: shape = XC_watch; break;
  217894. case IBeamCursor: shape = XC_xterm; break;
  217895. case PointingHandCursor: shape = XC_hand2; break;
  217896. case LeftRightResizeCursor: shape = XC_sb_h_double_arrow; break;
  217897. case UpDownResizeCursor: shape = XC_sb_v_double_arrow; break;
  217898. case UpDownLeftRightResizeCursor: shape = XC_fleur; break;
  217899. case TopEdgeResizeCursor: shape = XC_top_side; break;
  217900. case BottomEdgeResizeCursor: shape = XC_bottom_side; break;
  217901. case LeftEdgeResizeCursor: shape = XC_left_side; break;
  217902. case RightEdgeResizeCursor: shape = XC_right_side; break;
  217903. case TopLeftCornerResizeCursor: shape = XC_top_left_corner; break;
  217904. case TopRightCornerResizeCursor: shape = XC_top_right_corner; break;
  217905. case BottomLeftCornerResizeCursor: shape = XC_bottom_left_corner; break;
  217906. case BottomRightCornerResizeCursor: shape = XC_bottom_right_corner; break;
  217907. case CrosshairCursor: shape = XC_crosshair; break;
  217908. case DraggingHandCursor:
  217909. {
  217910. static unsigned char dragHandData[] = { 71,73,70,56,57,97,16,0,16,0,145,2,0,0,0,0,255,255,255,0,
  217911. 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,
  217912. 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 };
  217913. const int dragHandDataSize = 99;
  217914. const ScopedPointer <Image> im (ImageFileFormat::loadFrom (dragHandData, dragHandDataSize));
  217915. return createMouseCursorFromImage (*im, 8, 7);
  217916. }
  217917. case CopyingCursor:
  217918. {
  217919. static unsigned char copyCursorData[] = { 71,73,70,56,57,97,21,0,21,0,145,0,0,0,0,0,255,255,255,0,
  217920. 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,
  217921. 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,
  217922. 252,114,147,74,83,5,50,68,147,208,217,16,71,149,252,124,5,0,59,0,0 };
  217923. const int copyCursorSize = 119;
  217924. const ScopedPointer <Image> im (ImageFileFormat::loadFrom (copyCursorData, copyCursorSize));
  217925. return createMouseCursorFromImage (*im, 1, 3);
  217926. }
  217927. default:
  217928. jassertfalse;
  217929. return None;
  217930. }
  217931. ScopedXLock xlock;
  217932. return (void*) XCreateFontCursor (display, shape);
  217933. }
  217934. void MouseCursor::showInWindow (ComponentPeer* peer) const
  217935. {
  217936. LinuxComponentPeer* const lp = dynamic_cast <LinuxComponentPeer*> (peer);
  217937. if (lp != 0)
  217938. lp->showMouseCursor ((Cursor) getHandle());
  217939. }
  217940. void MouseCursor::showInAllWindows() const
  217941. {
  217942. for (int i = ComponentPeer::getNumPeers(); --i >= 0;)
  217943. showInWindow (ComponentPeer::getPeer (i));
  217944. }
  217945. Image* juce_createIconForFile (const File& file)
  217946. {
  217947. return 0;
  217948. }
  217949. Image* Image::createNativeImage (const PixelFormat format, const int imageWidth, const int imageHeight, const bool clearImage)
  217950. {
  217951. return new Image (format, imageWidth, imageHeight, clearImage);
  217952. }
  217953. #if JUCE_OPENGL
  217954. class WindowedGLContext : public OpenGLContext
  217955. {
  217956. public:
  217957. WindowedGLContext (Component* const component,
  217958. const OpenGLPixelFormat& pixelFormat_,
  217959. GLXContext sharedContext)
  217960. : renderContext (0),
  217961. embeddedWindow (0),
  217962. pixelFormat (pixelFormat_)
  217963. {
  217964. jassert (component != 0);
  217965. LinuxComponentPeer* const peer = dynamic_cast <LinuxComponentPeer*> (component->getTopLevelComponent()->getPeer());
  217966. if (peer == 0)
  217967. return;
  217968. ScopedXLock xlock;
  217969. XSync (display, False);
  217970. GLint attribs [64];
  217971. int n = 0;
  217972. attribs[n++] = GLX_RGBA;
  217973. attribs[n++] = GLX_DOUBLEBUFFER;
  217974. attribs[n++] = GLX_RED_SIZE;
  217975. attribs[n++] = pixelFormat.redBits;
  217976. attribs[n++] = GLX_GREEN_SIZE;
  217977. attribs[n++] = pixelFormat.greenBits;
  217978. attribs[n++] = GLX_BLUE_SIZE;
  217979. attribs[n++] = pixelFormat.blueBits;
  217980. attribs[n++] = GLX_ALPHA_SIZE;
  217981. attribs[n++] = pixelFormat.alphaBits;
  217982. attribs[n++] = GLX_DEPTH_SIZE;
  217983. attribs[n++] = pixelFormat.depthBufferBits;
  217984. attribs[n++] = GLX_STENCIL_SIZE;
  217985. attribs[n++] = pixelFormat.stencilBufferBits;
  217986. attribs[n++] = GLX_ACCUM_RED_SIZE;
  217987. attribs[n++] = pixelFormat.accumulationBufferRedBits;
  217988. attribs[n++] = GLX_ACCUM_GREEN_SIZE;
  217989. attribs[n++] = pixelFormat.accumulationBufferGreenBits;
  217990. attribs[n++] = GLX_ACCUM_BLUE_SIZE;
  217991. attribs[n++] = pixelFormat.accumulationBufferBlueBits;
  217992. attribs[n++] = GLX_ACCUM_ALPHA_SIZE;
  217993. attribs[n++] = pixelFormat.accumulationBufferAlphaBits;
  217994. // xxx not sure how to do fullSceneAntiAliasingNumSamples on linux..
  217995. attribs[n++] = None;
  217996. XVisualInfo* const bestVisual = glXChooseVisual (display, DefaultScreen (display), attribs);
  217997. if (bestVisual == 0)
  217998. return;
  217999. renderContext = glXCreateContext (display, bestVisual, sharedContext, GL_TRUE);
  218000. Window windowH = (Window) peer->getNativeHandle();
  218001. Colormap colourMap = XCreateColormap (display, windowH, bestVisual->visual, AllocNone);
  218002. XSetWindowAttributes swa;
  218003. swa.colormap = colourMap;
  218004. swa.border_pixel = 0;
  218005. swa.event_mask = ExposureMask | StructureNotifyMask;
  218006. embeddedWindow = XCreateWindow (display, windowH,
  218007. 0, 0, 1, 1, 0,
  218008. bestVisual->depth,
  218009. InputOutput,
  218010. bestVisual->visual,
  218011. CWBorderPixel | CWColormap | CWEventMask,
  218012. &swa);
  218013. XSaveContext (display, (XID) embeddedWindow, windowHandleXContext, (XPointer) peer);
  218014. XMapWindow (display, embeddedWindow);
  218015. XFreeColormap (display, colourMap);
  218016. XFree (bestVisual);
  218017. XSync (display, False);
  218018. }
  218019. ~WindowedGLContext()
  218020. {
  218021. makeInactive();
  218022. ScopedXLock xlock;
  218023. glXDestroyContext (display, renderContext);
  218024. XUnmapWindow (display, embeddedWindow);
  218025. XDestroyWindow (display, embeddedWindow);
  218026. }
  218027. bool makeActive() const throw()
  218028. {
  218029. jassert (renderContext != 0);
  218030. ScopedXLock xlock;
  218031. return glXMakeCurrent (display, embeddedWindow, renderContext)
  218032. && XSync (display, False);
  218033. }
  218034. bool makeInactive() const throw()
  218035. {
  218036. ScopedXLock xlock;
  218037. return (! isActive()) || glXMakeCurrent (display, None, 0);
  218038. }
  218039. bool isActive() const throw()
  218040. {
  218041. ScopedXLock xlock;
  218042. return glXGetCurrentContext() == renderContext;
  218043. }
  218044. const OpenGLPixelFormat getPixelFormat() const
  218045. {
  218046. return pixelFormat;
  218047. }
  218048. void* getRawContext() const throw()
  218049. {
  218050. return renderContext;
  218051. }
  218052. void updateWindowPosition (int x, int y, int w, int h, int)
  218053. {
  218054. ScopedXLock xlock;
  218055. XMoveResizeWindow (display, embeddedWindow,
  218056. x, y, jmax (1, w), jmax (1, h));
  218057. }
  218058. void swapBuffers()
  218059. {
  218060. ScopedXLock xlock;
  218061. glXSwapBuffers (display, embeddedWindow);
  218062. }
  218063. bool setSwapInterval (const int numFramesPerSwap)
  218064. {
  218065. // xxx needs doing..
  218066. return false;
  218067. }
  218068. int getSwapInterval() const
  218069. {
  218070. // xxx needs doing..
  218071. return 0;
  218072. }
  218073. void repaint()
  218074. {
  218075. }
  218076. juce_UseDebuggingNewOperator
  218077. GLXContext renderContext;
  218078. private:
  218079. Window embeddedWindow;
  218080. OpenGLPixelFormat pixelFormat;
  218081. WindowedGLContext (const WindowedGLContext&);
  218082. WindowedGLContext& operator= (const WindowedGLContext&);
  218083. };
  218084. OpenGLContext* OpenGLComponent::createContext()
  218085. {
  218086. ScopedPointer<WindowedGLContext> c (new WindowedGLContext (this, preferredPixelFormat,
  218087. contextToShareListsWith != 0 ? (GLXContext) contextToShareListsWith->getRawContext() : 0));
  218088. return (c->renderContext != 0) ? c.release() : 0;
  218089. }
  218090. void juce_glViewport (const int w, const int h)
  218091. {
  218092. glViewport (0, 0, w, h);
  218093. }
  218094. void OpenGLPixelFormat::getAvailablePixelFormats (Component* component,
  218095. OwnedArray <OpenGLPixelFormat>& results)
  218096. {
  218097. results.add (new OpenGLPixelFormat()); // xxx
  218098. }
  218099. #endif
  218100. bool DragAndDropContainer::performExternalDragDropOfFiles (const StringArray& files, const bool canMoveFiles)
  218101. {
  218102. jassertfalse // not implemented!
  218103. return false;
  218104. }
  218105. bool DragAndDropContainer::performExternalDragDropOfText (const String& text)
  218106. {
  218107. jassertfalse // not implemented!
  218108. return false;
  218109. }
  218110. void SystemTrayIconComponent::setIconImage (const Image& newImage)
  218111. {
  218112. if (! isOnDesktop ())
  218113. addToDesktop (0);
  218114. LinuxComponentPeer* const wp = dynamic_cast <LinuxComponentPeer*> (getPeer());
  218115. if (wp != 0)
  218116. {
  218117. wp->setTaskBarIcon (newImage);
  218118. setVisible (true);
  218119. toFront (false);
  218120. repaint();
  218121. }
  218122. }
  218123. void SystemTrayIconComponent::paint (Graphics& g)
  218124. {
  218125. LinuxComponentPeer* const wp = dynamic_cast <LinuxComponentPeer*> (getPeer());
  218126. if (wp != 0)
  218127. {
  218128. const Image* const image = wp->getTaskbarIcon();
  218129. if (image != 0)
  218130. {
  218131. g.drawImageWithin (image, 0, 0, getWidth(), getHeight(),
  218132. RectanglePlacement::xLeft | RectanglePlacement::yTop | RectanglePlacement::onlyReduceInSize,
  218133. false);
  218134. }
  218135. }
  218136. }
  218137. void SystemTrayIconComponent::setIconTooltip (const String& tooltip)
  218138. {
  218139. // xxx not yet implemented!
  218140. }
  218141. void PlatformUtilities::beep()
  218142. {
  218143. std::cout << "\a" << std::flush;
  218144. }
  218145. bool AlertWindow::showNativeDialogBox (const String& title,
  218146. const String& bodyText,
  218147. bool isOkCancel)
  218148. {
  218149. // use a non-native one for the time being..
  218150. if (isOkCancel)
  218151. return AlertWindow::showOkCancelBox (AlertWindow::NoIcon, title, bodyText);
  218152. else
  218153. AlertWindow::showMessageBox (AlertWindow::NoIcon, title, bodyText);
  218154. return true;
  218155. }
  218156. const int KeyPress::spaceKey = XK_space & 0xff;
  218157. const int KeyPress::returnKey = XK_Return & 0xff;
  218158. const int KeyPress::escapeKey = XK_Escape & 0xff;
  218159. const int KeyPress::backspaceKey = XK_BackSpace & 0xff;
  218160. const int KeyPress::leftKey = (XK_Left & 0xff) | Keys::extendedKeyModifier;
  218161. const int KeyPress::rightKey = (XK_Right & 0xff) | Keys::extendedKeyModifier;
  218162. const int KeyPress::upKey = (XK_Up & 0xff) | Keys::extendedKeyModifier;
  218163. const int KeyPress::downKey = (XK_Down & 0xff) | Keys::extendedKeyModifier;
  218164. const int KeyPress::pageUpKey = (XK_Page_Up & 0xff) | Keys::extendedKeyModifier;
  218165. const int KeyPress::pageDownKey = (XK_Page_Down & 0xff) | Keys::extendedKeyModifier;
  218166. const int KeyPress::endKey = (XK_End & 0xff) | Keys::extendedKeyModifier;
  218167. const int KeyPress::homeKey = (XK_Home & 0xff) | Keys::extendedKeyModifier;
  218168. const int KeyPress::insertKey = (XK_Insert & 0xff) | Keys::extendedKeyModifier;
  218169. const int KeyPress::deleteKey = (XK_Delete & 0xff) | Keys::extendedKeyModifier;
  218170. const int KeyPress::tabKey = XK_Tab & 0xff;
  218171. const int KeyPress::F1Key = (XK_F1 & 0xff) | Keys::extendedKeyModifier;
  218172. const int KeyPress::F2Key = (XK_F2 & 0xff) | Keys::extendedKeyModifier;
  218173. const int KeyPress::F3Key = (XK_F3 & 0xff) | Keys::extendedKeyModifier;
  218174. const int KeyPress::F4Key = (XK_F4 & 0xff) | Keys::extendedKeyModifier;
  218175. const int KeyPress::F5Key = (XK_F5 & 0xff) | Keys::extendedKeyModifier;
  218176. const int KeyPress::F6Key = (XK_F6 & 0xff) | Keys::extendedKeyModifier;
  218177. const int KeyPress::F7Key = (XK_F7 & 0xff) | Keys::extendedKeyModifier;
  218178. const int KeyPress::F8Key = (XK_F8 & 0xff) | Keys::extendedKeyModifier;
  218179. const int KeyPress::F9Key = (XK_F9 & 0xff) | Keys::extendedKeyModifier;
  218180. const int KeyPress::F10Key = (XK_F10 & 0xff) | Keys::extendedKeyModifier;
  218181. const int KeyPress::F11Key = (XK_F11 & 0xff) | Keys::extendedKeyModifier;
  218182. const int KeyPress::F12Key = (XK_F12 & 0xff) | Keys::extendedKeyModifier;
  218183. const int KeyPress::F13Key = (XK_F13 & 0xff) | Keys::extendedKeyModifier;
  218184. const int KeyPress::F14Key = (XK_F14 & 0xff) | Keys::extendedKeyModifier;
  218185. const int KeyPress::F15Key = (XK_F15 & 0xff) | Keys::extendedKeyModifier;
  218186. const int KeyPress::F16Key = (XK_F16 & 0xff) | Keys::extendedKeyModifier;
  218187. const int KeyPress::numberPad0 = (XK_KP_0 & 0xff) | Keys::extendedKeyModifier;
  218188. const int KeyPress::numberPad1 = (XK_KP_1 & 0xff) | Keys::extendedKeyModifier;
  218189. const int KeyPress::numberPad2 = (XK_KP_2 & 0xff) | Keys::extendedKeyModifier;
  218190. const int KeyPress::numberPad3 = (XK_KP_3 & 0xff) | Keys::extendedKeyModifier;
  218191. const int KeyPress::numberPad4 = (XK_KP_4 & 0xff) | Keys::extendedKeyModifier;
  218192. const int KeyPress::numberPad5 = (XK_KP_5 & 0xff) | Keys::extendedKeyModifier;
  218193. const int KeyPress::numberPad6 = (XK_KP_6 & 0xff) | Keys::extendedKeyModifier;
  218194. const int KeyPress::numberPad7 = (XK_KP_7 & 0xff)| Keys::extendedKeyModifier;
  218195. const int KeyPress::numberPad8 = (XK_KP_8 & 0xff)| Keys::extendedKeyModifier;
  218196. const int KeyPress::numberPad9 = (XK_KP_9 & 0xff)| Keys::extendedKeyModifier;
  218197. const int KeyPress::numberPadAdd = (XK_KP_Add & 0xff)| Keys::extendedKeyModifier;
  218198. const int KeyPress::numberPadSubtract = (XK_KP_Subtract & 0xff)| Keys::extendedKeyModifier;
  218199. const int KeyPress::numberPadMultiply = (XK_KP_Multiply & 0xff)| Keys::extendedKeyModifier;
  218200. const int KeyPress::numberPadDivide = (XK_KP_Divide & 0xff)| Keys::extendedKeyModifier;
  218201. const int KeyPress::numberPadSeparator = (XK_KP_Separator & 0xff)| Keys::extendedKeyModifier;
  218202. const int KeyPress::numberPadDecimalPoint = (XK_KP_Decimal & 0xff)| Keys::extendedKeyModifier;
  218203. const int KeyPress::numberPadEquals = (XK_KP_Equal & 0xff)| Keys::extendedKeyModifier;
  218204. const int KeyPress::numberPadDelete = (XK_KP_Delete & 0xff)| Keys::extendedKeyModifier;
  218205. const int KeyPress::playKey = (0xffeeff00) | Keys::extendedKeyModifier;
  218206. const int KeyPress::stopKey = (0xffeeff01) | Keys::extendedKeyModifier;
  218207. const int KeyPress::fastForwardKey = (0xffeeff02) | Keys::extendedKeyModifier;
  218208. const int KeyPress::rewindKey = (0xffeeff03) | Keys::extendedKeyModifier;
  218209. #endif
  218210. /*** End of inlined file: juce_linux_Windowing.cpp ***/
  218211. /*** Start of inlined file: juce_linux_Audio.cpp ***/
  218212. // (This file gets included by juce_linux_NativeCode.cpp, rather than being
  218213. // compiled on its own).
  218214. #if JUCE_INCLUDED_FILE && JUCE_ALSA
  218215. static const int maxNumChans = 64;
  218216. static void getDeviceSampleRates (snd_pcm_t* handle, Array <int>& rates)
  218217. {
  218218. const int ratesToTry[] = { 22050, 32000, 44100, 48000, 88200, 96000, 176400, 192000, 0 };
  218219. snd_pcm_hw_params_t* hwParams;
  218220. snd_pcm_hw_params_alloca (&hwParams);
  218221. for (int i = 0; ratesToTry[i] != 0; ++i)
  218222. {
  218223. if (snd_pcm_hw_params_any (handle, hwParams) >= 0
  218224. && snd_pcm_hw_params_test_rate (handle, hwParams, ratesToTry[i], 0) == 0)
  218225. {
  218226. rates.addIfNotAlreadyThere (ratesToTry[i]);
  218227. }
  218228. }
  218229. }
  218230. static void getDeviceNumChannels (snd_pcm_t* handle, unsigned int* minChans, unsigned int* maxChans)
  218231. {
  218232. snd_pcm_hw_params_t *params;
  218233. snd_pcm_hw_params_alloca (&params);
  218234. if (snd_pcm_hw_params_any (handle, params) >= 0)
  218235. {
  218236. snd_pcm_hw_params_get_channels_min (params, minChans);
  218237. snd_pcm_hw_params_get_channels_max (params, maxChans);
  218238. }
  218239. }
  218240. static void getDeviceProperties (const String& deviceID,
  218241. unsigned int& minChansOut,
  218242. unsigned int& maxChansOut,
  218243. unsigned int& minChansIn,
  218244. unsigned int& maxChansIn,
  218245. Array <int>& rates)
  218246. {
  218247. if (deviceID.isEmpty())
  218248. return;
  218249. snd_ctl_t* handle;
  218250. if (snd_ctl_open (&handle, deviceID.upToLastOccurrenceOf (",", false, false).toUTF8(), SND_CTL_NONBLOCK) >= 0)
  218251. {
  218252. snd_pcm_info_t* info;
  218253. snd_pcm_info_alloca (&info);
  218254. snd_pcm_info_set_stream (info, SND_PCM_STREAM_PLAYBACK);
  218255. snd_pcm_info_set_device (info, deviceID.fromLastOccurrenceOf (",", false, false).getIntValue());
  218256. snd_pcm_info_set_subdevice (info, 0);
  218257. if (snd_ctl_pcm_info (handle, info) >= 0)
  218258. {
  218259. snd_pcm_t* pcmHandle;
  218260. if (snd_pcm_open (&pcmHandle, deviceID.toUTF8(), SND_PCM_STREAM_PLAYBACK, SND_PCM_ASYNC | SND_PCM_NONBLOCK ) >= 0)
  218261. {
  218262. getDeviceNumChannels (pcmHandle, &minChansOut, &maxChansOut);
  218263. getDeviceSampleRates (pcmHandle, rates);
  218264. snd_pcm_close (pcmHandle);
  218265. }
  218266. }
  218267. snd_pcm_info_set_stream (info, SND_PCM_STREAM_CAPTURE);
  218268. if (snd_ctl_pcm_info (handle, info) >= 0)
  218269. {
  218270. snd_pcm_t* pcmHandle;
  218271. if (snd_pcm_open (&pcmHandle, deviceID.toUTF8(), SND_PCM_STREAM_CAPTURE, SND_PCM_ASYNC | SND_PCM_NONBLOCK ) >= 0)
  218272. {
  218273. getDeviceNumChannels (pcmHandle, &minChansIn, &maxChansIn);
  218274. if (rates.size() == 0)
  218275. getDeviceSampleRates (pcmHandle, rates);
  218276. snd_pcm_close (pcmHandle);
  218277. }
  218278. }
  218279. snd_ctl_close (handle);
  218280. }
  218281. }
  218282. class ALSADevice
  218283. {
  218284. public:
  218285. ALSADevice (const String& deviceID,
  218286. const bool forInput)
  218287. : handle (0),
  218288. bitDepth (16),
  218289. numChannelsRunning (0),
  218290. isInput (forInput),
  218291. sampleFormat (AudioDataConverters::int16LE)
  218292. {
  218293. failed (snd_pcm_open (&handle, deviceID.toUTF8(),
  218294. forInput ? SND_PCM_STREAM_CAPTURE : SND_PCM_STREAM_PLAYBACK,
  218295. SND_PCM_ASYNC));
  218296. }
  218297. ~ALSADevice()
  218298. {
  218299. if (handle != 0)
  218300. snd_pcm_close (handle);
  218301. }
  218302. bool setParameters (unsigned int sampleRate, int numChannels, int bufferSize)
  218303. {
  218304. if (handle == 0)
  218305. return false;
  218306. snd_pcm_hw_params_t* hwParams;
  218307. snd_pcm_hw_params_alloca (&hwParams);
  218308. if (failed (snd_pcm_hw_params_any (handle, hwParams)))
  218309. return false;
  218310. if (snd_pcm_hw_params_set_access (handle, hwParams, SND_PCM_ACCESS_RW_NONINTERLEAVED) >= 0)
  218311. isInterleaved = false;
  218312. else if (snd_pcm_hw_params_set_access (handle, hwParams, SND_PCM_ACCESS_RW_INTERLEAVED) >= 0)
  218313. isInterleaved = true;
  218314. else
  218315. {
  218316. jassertfalse
  218317. return false;
  218318. }
  218319. const int formatsToTry[] = { SND_PCM_FORMAT_FLOAT_LE, 32, AudioDataConverters::float32LE,
  218320. SND_PCM_FORMAT_FLOAT_BE, 32, AudioDataConverters::float32BE,
  218321. SND_PCM_FORMAT_S32_LE, 32, AudioDataConverters::int32LE,
  218322. SND_PCM_FORMAT_S32_BE, 32, AudioDataConverters::int32BE,
  218323. SND_PCM_FORMAT_S24_3LE, 24, AudioDataConverters::int24LE,
  218324. SND_PCM_FORMAT_S24_3BE, 24, AudioDataConverters::int24BE,
  218325. SND_PCM_FORMAT_S16_LE, 16, AudioDataConverters::int16LE,
  218326. SND_PCM_FORMAT_S16_BE, 16, AudioDataConverters::int16BE };
  218327. bitDepth = 0;
  218328. for (int i = 0; i < numElementsInArray (formatsToTry); i += 3)
  218329. {
  218330. if (snd_pcm_hw_params_set_format (handle, hwParams, (_snd_pcm_format) formatsToTry [i]) >= 0)
  218331. {
  218332. bitDepth = formatsToTry [i + 1];
  218333. sampleFormat = (AudioDataConverters::DataFormat) formatsToTry [i + 2];
  218334. break;
  218335. }
  218336. }
  218337. if (bitDepth == 0)
  218338. {
  218339. error = "device doesn't support a compatible PCM format";
  218340. DBG ("ALSA error: " + error + "\n");
  218341. return false;
  218342. }
  218343. int dir = 0;
  218344. unsigned int periods = 4;
  218345. snd_pcm_uframes_t samplesPerPeriod = bufferSize;
  218346. if (failed (snd_pcm_hw_params_set_rate_near (handle, hwParams, &sampleRate, 0))
  218347. || failed (snd_pcm_hw_params_set_channels (handle, hwParams, numChannels))
  218348. || failed (snd_pcm_hw_params_set_periods_near (handle, hwParams, &periods, &dir))
  218349. || failed (snd_pcm_hw_params_set_period_size_near (handle, hwParams, &samplesPerPeriod, &dir))
  218350. || failed (snd_pcm_hw_params (handle, hwParams)))
  218351. {
  218352. return false;
  218353. }
  218354. snd_pcm_sw_params_t* swParams;
  218355. snd_pcm_sw_params_alloca (&swParams);
  218356. snd_pcm_uframes_t boundary;
  218357. if (failed (snd_pcm_sw_params_current (handle, swParams))
  218358. || failed (snd_pcm_sw_params_get_boundary (swParams, &boundary))
  218359. || failed (snd_pcm_sw_params_set_silence_threshold (handle, swParams, 0))
  218360. || failed (snd_pcm_sw_params_set_silence_size (handle, swParams, boundary))
  218361. || failed (snd_pcm_sw_params_set_start_threshold (handle, swParams, samplesPerPeriod))
  218362. || failed (snd_pcm_sw_params_set_stop_threshold (handle, swParams, boundary))
  218363. || failed (snd_pcm_sw_params (handle, swParams)))
  218364. {
  218365. return false;
  218366. }
  218367. /*
  218368. #if JUCE_DEBUG
  218369. // enable this to dump the config of the devices that get opened
  218370. snd_output_t* out;
  218371. snd_output_stdio_attach (&out, stderr, 0);
  218372. snd_pcm_hw_params_dump (hwParams, out);
  218373. snd_pcm_sw_params_dump (swParams, out);
  218374. #endif
  218375. */
  218376. numChannelsRunning = numChannels;
  218377. return true;
  218378. }
  218379. bool write (AudioSampleBuffer& outputChannelBuffer, const int numSamples)
  218380. {
  218381. jassert (numChannelsRunning <= outputChannelBuffer.getNumChannels());
  218382. float** const data = outputChannelBuffer.getArrayOfChannels();
  218383. if (isInterleaved)
  218384. {
  218385. scratch.ensureSize (sizeof (float) * numSamples * numChannelsRunning, false);
  218386. float* interleaved = static_cast <float*> (scratch.getData());
  218387. AudioDataConverters::interleaveSamples ((const float**) data, interleaved, numSamples, numChannelsRunning);
  218388. AudioDataConverters::convertFloatToFormat (sampleFormat, interleaved, interleaved, numSamples * numChannelsRunning);
  218389. snd_pcm_sframes_t num = snd_pcm_writei (handle, interleaved, numSamples);
  218390. if (failed (num) && num != -EPIPE && num != -ESTRPIPE)
  218391. return false;
  218392. }
  218393. else
  218394. {
  218395. for (int i = 0; i < numChannelsRunning; ++i)
  218396. if (data[i] != 0)
  218397. AudioDataConverters::convertFloatToFormat (sampleFormat, data[i], data[i], numSamples);
  218398. snd_pcm_sframes_t num = snd_pcm_writen (handle, (void**) data, numSamples);
  218399. if (failed (num))
  218400. {
  218401. if (num == -EPIPE)
  218402. {
  218403. if (failed (snd_pcm_prepare (handle)))
  218404. return false;
  218405. }
  218406. else if (num != -ESTRPIPE)
  218407. return false;
  218408. }
  218409. }
  218410. return true;
  218411. }
  218412. bool read (AudioSampleBuffer& inputChannelBuffer, const int numSamples)
  218413. {
  218414. jassert (numChannelsRunning <= inputChannelBuffer.getNumChannels());
  218415. float** const data = inputChannelBuffer.getArrayOfChannels();
  218416. if (isInterleaved)
  218417. {
  218418. scratch.ensureSize (sizeof (float) * numSamples * numChannelsRunning, false);
  218419. float* interleaved = static_cast <float*> (scratch.getData());
  218420. snd_pcm_sframes_t num = snd_pcm_readi (handle, interleaved, numSamples);
  218421. if (failed (num))
  218422. {
  218423. if (num == -EPIPE)
  218424. {
  218425. if (failed (snd_pcm_prepare (handle)))
  218426. return false;
  218427. }
  218428. else if (num != -ESTRPIPE)
  218429. return false;
  218430. }
  218431. AudioDataConverters::convertFormatToFloat (sampleFormat, interleaved, interleaved, numSamples * numChannelsRunning);
  218432. AudioDataConverters::deinterleaveSamples (interleaved, data, numSamples, numChannelsRunning);
  218433. }
  218434. else
  218435. {
  218436. snd_pcm_sframes_t num = snd_pcm_readn (handle, (void**) data, numSamples);
  218437. if (failed (num) && num != -EPIPE && num != -ESTRPIPE)
  218438. return false;
  218439. for (int i = 0; i < numChannelsRunning; ++i)
  218440. if (data[i] != 0)
  218441. AudioDataConverters::convertFormatToFloat (sampleFormat, data[i], data[i], numSamples);
  218442. }
  218443. return true;
  218444. }
  218445. juce_UseDebuggingNewOperator
  218446. snd_pcm_t* handle;
  218447. String error;
  218448. int bitDepth, numChannelsRunning;
  218449. private:
  218450. const bool isInput;
  218451. bool isInterleaved;
  218452. MemoryBlock scratch;
  218453. AudioDataConverters::DataFormat sampleFormat;
  218454. bool failed (const int errorNum)
  218455. {
  218456. if (errorNum >= 0)
  218457. return false;
  218458. error = snd_strerror (errorNum);
  218459. DBG ("ALSA error: " + error + "\n");
  218460. return true;
  218461. }
  218462. };
  218463. class ALSAThread : public Thread
  218464. {
  218465. public:
  218466. ALSAThread (const String& inputId_,
  218467. const String& outputId_)
  218468. : Thread ("Juce ALSA"),
  218469. sampleRate (0),
  218470. bufferSize (0),
  218471. callback (0),
  218472. inputId (inputId_),
  218473. outputId (outputId_),
  218474. outputDevice (0),
  218475. inputDevice (0),
  218476. numCallbacks (0),
  218477. inputChannelBuffer (1, 1),
  218478. outputChannelBuffer (1, 1)
  218479. {
  218480. initialiseRatesAndChannels();
  218481. }
  218482. ~ALSAThread()
  218483. {
  218484. close();
  218485. }
  218486. void open (BigInteger inputChannels,
  218487. BigInteger outputChannels,
  218488. const double sampleRate_,
  218489. const int bufferSize_)
  218490. {
  218491. close();
  218492. error = String::empty;
  218493. sampleRate = sampleRate_;
  218494. bufferSize = bufferSize_;
  218495. inputChannelBuffer.setSize (jmax ((int) minChansIn, inputChannels.getHighestBit()) + 1, bufferSize);
  218496. inputChannelBuffer.clear();
  218497. inputChannelDataForCallback.clear();
  218498. currentInputChans.clear();
  218499. if (inputChannels.getHighestBit() >= 0)
  218500. {
  218501. for (int i = 0; i <= jmax (inputChannels.getHighestBit(), (int) minChansIn); ++i)
  218502. {
  218503. if (inputChannels[i])
  218504. {
  218505. inputChannelDataForCallback.add (inputChannelBuffer.getSampleData (i));
  218506. currentInputChans.setBit (i);
  218507. }
  218508. }
  218509. }
  218510. outputChannelBuffer.setSize (jmax ((int) minChansOut, outputChannels.getHighestBit()) + 1, bufferSize);
  218511. outputChannelBuffer.clear();
  218512. outputChannelDataForCallback.clear();
  218513. currentOutputChans.clear();
  218514. if (outputChannels.getHighestBit() >= 0)
  218515. {
  218516. for (int i = 0; i <= jmax (outputChannels.getHighestBit(), (int) minChansOut); ++i)
  218517. {
  218518. if (outputChannels[i])
  218519. {
  218520. outputChannelDataForCallback.add (outputChannelBuffer.getSampleData (i));
  218521. currentOutputChans.setBit (i);
  218522. }
  218523. }
  218524. }
  218525. if (outputChannelDataForCallback.size() > 0 && outputId.isNotEmpty())
  218526. {
  218527. outputDevice = new ALSADevice (outputId, false);
  218528. if (outputDevice->error.isNotEmpty())
  218529. {
  218530. error = outputDevice->error;
  218531. deleteAndZero (outputDevice);
  218532. return;
  218533. }
  218534. currentOutputChans.setRange (0, minChansOut, true);
  218535. if (! outputDevice->setParameters ((unsigned int) sampleRate,
  218536. jlimit ((int) minChansOut, (int) maxChansOut, currentOutputChans.getHighestBit() + 1),
  218537. bufferSize))
  218538. {
  218539. error = outputDevice->error;
  218540. deleteAndZero (outputDevice);
  218541. return;
  218542. }
  218543. }
  218544. if (inputChannelDataForCallback.size() > 0 && inputId.isNotEmpty())
  218545. {
  218546. inputDevice = new ALSADevice (inputId, true);
  218547. if (inputDevice->error.isNotEmpty())
  218548. {
  218549. error = inputDevice->error;
  218550. deleteAndZero (inputDevice);
  218551. return;
  218552. }
  218553. currentInputChans.setRange (0, minChansIn, true);
  218554. if (! inputDevice->setParameters ((unsigned int) sampleRate,
  218555. jlimit ((int) minChansIn, (int) maxChansIn, currentInputChans.getHighestBit() + 1),
  218556. bufferSize))
  218557. {
  218558. error = inputDevice->error;
  218559. deleteAndZero (inputDevice);
  218560. return;
  218561. }
  218562. }
  218563. if (outputDevice == 0 && inputDevice == 0)
  218564. {
  218565. error = "no channels";
  218566. return;
  218567. }
  218568. if (outputDevice != 0 && inputDevice != 0)
  218569. {
  218570. snd_pcm_link (outputDevice->handle, inputDevice->handle);
  218571. }
  218572. if (inputDevice != 0 && failed (snd_pcm_prepare (inputDevice->handle)))
  218573. return;
  218574. if (outputDevice != 0 && failed (snd_pcm_prepare (outputDevice->handle)))
  218575. return;
  218576. startThread (9);
  218577. int count = 1000;
  218578. while (numCallbacks == 0)
  218579. {
  218580. sleep (5);
  218581. if (--count < 0 || ! isThreadRunning())
  218582. {
  218583. error = "device didn't start";
  218584. break;
  218585. }
  218586. }
  218587. }
  218588. void close()
  218589. {
  218590. stopThread (6000);
  218591. deleteAndZero (inputDevice);
  218592. deleteAndZero (outputDevice);
  218593. inputChannelBuffer.setSize (1, 1);
  218594. outputChannelBuffer.setSize (1, 1);
  218595. numCallbacks = 0;
  218596. }
  218597. void setCallback (AudioIODeviceCallback* const newCallback) throw()
  218598. {
  218599. const ScopedLock sl (callbackLock);
  218600. callback = newCallback;
  218601. }
  218602. void run()
  218603. {
  218604. while (! threadShouldExit())
  218605. {
  218606. if (inputDevice != 0)
  218607. {
  218608. if (! inputDevice->read (inputChannelBuffer, bufferSize))
  218609. {
  218610. DBG ("ALSA: read failure");
  218611. break;
  218612. }
  218613. }
  218614. if (threadShouldExit())
  218615. break;
  218616. {
  218617. const ScopedLock sl (callbackLock);
  218618. ++numCallbacks;
  218619. if (callback != 0)
  218620. {
  218621. callback->audioDeviceIOCallback ((const float**) inputChannelDataForCallback.getRawDataPointer(),
  218622. inputChannelDataForCallback.size(),
  218623. outputChannelDataForCallback.getRawDataPointer(),
  218624. outputChannelDataForCallback.size(),
  218625. bufferSize);
  218626. }
  218627. else
  218628. {
  218629. for (int i = 0; i < outputChannelDataForCallback.size(); ++i)
  218630. zeromem (outputChannelDataForCallback[i], sizeof (float) * bufferSize);
  218631. }
  218632. }
  218633. if (outputDevice != 0)
  218634. {
  218635. failed (snd_pcm_wait (outputDevice->handle, 2000));
  218636. if (threadShouldExit())
  218637. break;
  218638. failed (snd_pcm_avail_update (outputDevice->handle));
  218639. if (! outputDevice->write (outputChannelBuffer, bufferSize))
  218640. {
  218641. DBG ("ALSA: write failure");
  218642. break;
  218643. }
  218644. }
  218645. }
  218646. }
  218647. int getBitDepth() const throw()
  218648. {
  218649. if (outputDevice != 0)
  218650. return outputDevice->bitDepth;
  218651. if (inputDevice != 0)
  218652. return inputDevice->bitDepth;
  218653. return 16;
  218654. }
  218655. juce_UseDebuggingNewOperator
  218656. String error;
  218657. double sampleRate;
  218658. int bufferSize;
  218659. BigInteger currentInputChans, currentOutputChans;
  218660. Array <int> sampleRates;
  218661. StringArray channelNamesOut, channelNamesIn;
  218662. AudioIODeviceCallback* callback;
  218663. private:
  218664. const String inputId, outputId;
  218665. ALSADevice* outputDevice;
  218666. ALSADevice* inputDevice;
  218667. int numCallbacks;
  218668. CriticalSection callbackLock;
  218669. AudioSampleBuffer inputChannelBuffer, outputChannelBuffer;
  218670. Array<float*> inputChannelDataForCallback, outputChannelDataForCallback;
  218671. unsigned int minChansOut, maxChansOut;
  218672. unsigned int minChansIn, maxChansIn;
  218673. bool failed (const int errorNum) throw()
  218674. {
  218675. if (errorNum >= 0)
  218676. return false;
  218677. error = snd_strerror (errorNum);
  218678. DBG ("ALSA error: " + error + "\n");
  218679. return true;
  218680. }
  218681. void initialiseRatesAndChannels() throw()
  218682. {
  218683. sampleRates.clear();
  218684. channelNamesOut.clear();
  218685. channelNamesIn.clear();
  218686. minChansOut = 0;
  218687. maxChansOut = 0;
  218688. minChansIn = 0;
  218689. maxChansIn = 0;
  218690. unsigned int dummy = 0;
  218691. getDeviceProperties (inputId, dummy, dummy, minChansIn, maxChansIn, sampleRates);
  218692. getDeviceProperties (outputId, minChansOut, maxChansOut, dummy, dummy, sampleRates);
  218693. unsigned int i;
  218694. for (i = 0; i < maxChansOut; ++i)
  218695. channelNamesOut.add ("channel " + String ((int) i + 1));
  218696. for (i = 0; i < maxChansIn; ++i)
  218697. channelNamesIn.add ("channel " + String ((int) i + 1));
  218698. }
  218699. };
  218700. class ALSAAudioIODevice : public AudioIODevice
  218701. {
  218702. public:
  218703. ALSAAudioIODevice (const String& deviceName,
  218704. const String& inputId_,
  218705. const String& outputId_)
  218706. : AudioIODevice (deviceName, "ALSA"),
  218707. inputId (inputId_),
  218708. outputId (outputId_),
  218709. isOpen_ (false),
  218710. isStarted (false),
  218711. internal (new ALSAThread (inputId_, outputId_))
  218712. {
  218713. }
  218714. ~ALSAAudioIODevice()
  218715. {
  218716. }
  218717. const StringArray getOutputChannelNames()
  218718. {
  218719. return internal->channelNamesOut;
  218720. }
  218721. const StringArray getInputChannelNames()
  218722. {
  218723. return internal->channelNamesIn;
  218724. }
  218725. int getNumSampleRates()
  218726. {
  218727. return internal->sampleRates.size();
  218728. }
  218729. double getSampleRate (int index)
  218730. {
  218731. return internal->sampleRates [index];
  218732. }
  218733. int getNumBufferSizesAvailable()
  218734. {
  218735. return 50;
  218736. }
  218737. int getBufferSizeSamples (int index)
  218738. {
  218739. int n = 16;
  218740. for (int i = 0; i < index; ++i)
  218741. n += n < 64 ? 16
  218742. : (n < 512 ? 32
  218743. : (n < 1024 ? 64
  218744. : (n < 2048 ? 128 : 256)));
  218745. return n;
  218746. }
  218747. int getDefaultBufferSize()
  218748. {
  218749. return 512;
  218750. }
  218751. const String open (const BigInteger& inputChannels,
  218752. const BigInteger& outputChannels,
  218753. double sampleRate,
  218754. int bufferSizeSamples)
  218755. {
  218756. close();
  218757. if (bufferSizeSamples <= 0)
  218758. bufferSizeSamples = getDefaultBufferSize();
  218759. if (sampleRate <= 0)
  218760. {
  218761. for (int i = 0; i < getNumSampleRates(); ++i)
  218762. {
  218763. if (getSampleRate (i) >= 44100)
  218764. {
  218765. sampleRate = getSampleRate (i);
  218766. break;
  218767. }
  218768. }
  218769. }
  218770. internal->open (inputChannels, outputChannels,
  218771. sampleRate, bufferSizeSamples);
  218772. isOpen_ = internal->error.isEmpty();
  218773. return internal->error;
  218774. }
  218775. void close()
  218776. {
  218777. stop();
  218778. internal->close();
  218779. isOpen_ = false;
  218780. }
  218781. bool isOpen()
  218782. {
  218783. return isOpen_;
  218784. }
  218785. int getCurrentBufferSizeSamples()
  218786. {
  218787. return internal->bufferSize;
  218788. }
  218789. double getCurrentSampleRate()
  218790. {
  218791. return internal->sampleRate;
  218792. }
  218793. int getCurrentBitDepth()
  218794. {
  218795. return internal->getBitDepth();
  218796. }
  218797. const BigInteger getActiveOutputChannels() const
  218798. {
  218799. return internal->currentOutputChans;
  218800. }
  218801. const BigInteger getActiveInputChannels() const
  218802. {
  218803. return internal->currentInputChans;
  218804. }
  218805. int getOutputLatencyInSamples()
  218806. {
  218807. return 0;
  218808. }
  218809. int getInputLatencyInSamples()
  218810. {
  218811. return 0;
  218812. }
  218813. void start (AudioIODeviceCallback* callback)
  218814. {
  218815. if (! isOpen_)
  218816. callback = 0;
  218817. internal->setCallback (callback);
  218818. if (callback != 0)
  218819. callback->audioDeviceAboutToStart (this);
  218820. isStarted = (callback != 0);
  218821. }
  218822. void stop()
  218823. {
  218824. AudioIODeviceCallback* const oldCallback = internal->callback;
  218825. start (0);
  218826. if (oldCallback != 0)
  218827. oldCallback->audioDeviceStopped();
  218828. }
  218829. bool isPlaying()
  218830. {
  218831. return isStarted && internal->error.isEmpty();
  218832. }
  218833. const String getLastError()
  218834. {
  218835. return internal->error;
  218836. }
  218837. String inputId, outputId;
  218838. private:
  218839. bool isOpen_, isStarted;
  218840. ScopedPointer<ALSAThread> internal;
  218841. };
  218842. class ALSAAudioIODeviceType : public AudioIODeviceType
  218843. {
  218844. public:
  218845. ALSAAudioIODeviceType()
  218846. : AudioIODeviceType ("ALSA"),
  218847. hasScanned (false)
  218848. {
  218849. }
  218850. ~ALSAAudioIODeviceType()
  218851. {
  218852. }
  218853. void scanForDevices()
  218854. {
  218855. if (hasScanned)
  218856. return;
  218857. hasScanned = true;
  218858. inputNames.clear();
  218859. inputIds.clear();
  218860. outputNames.clear();
  218861. outputIds.clear();
  218862. snd_ctl_t* handle;
  218863. snd_ctl_card_info_t* info;
  218864. snd_ctl_card_info_alloca (&info);
  218865. int cardNum = -1;
  218866. while (outputIds.size() + inputIds.size() <= 32)
  218867. {
  218868. snd_card_next (&cardNum);
  218869. if (cardNum < 0)
  218870. break;
  218871. if (snd_ctl_open (&handle, ("hw:" + String (cardNum)).toUTF8(), SND_CTL_NONBLOCK) >= 0)
  218872. {
  218873. if (snd_ctl_card_info (handle, info) >= 0)
  218874. {
  218875. String cardId (snd_ctl_card_info_get_id (info));
  218876. if (cardId.removeCharacters ("0123456789").isEmpty())
  218877. cardId = String (cardNum);
  218878. int device = -1;
  218879. for (;;)
  218880. {
  218881. if (snd_ctl_pcm_next_device (handle, &device) < 0 || device < 0)
  218882. break;
  218883. String id, name;
  218884. id << "hw:" << cardId << ',' << device;
  218885. bool isInput, isOutput;
  218886. if (testDevice (id, isInput, isOutput))
  218887. {
  218888. name << snd_ctl_card_info_get_name (info);
  218889. if (name.isEmpty())
  218890. name = id;
  218891. if (isInput)
  218892. {
  218893. inputNames.add (name);
  218894. inputIds.add (id);
  218895. }
  218896. if (isOutput)
  218897. {
  218898. outputNames.add (name);
  218899. outputIds.add (id);
  218900. }
  218901. }
  218902. }
  218903. }
  218904. snd_ctl_close (handle);
  218905. }
  218906. }
  218907. inputNames.appendNumbersToDuplicates (false, true);
  218908. outputNames.appendNumbersToDuplicates (false, true);
  218909. }
  218910. const StringArray getDeviceNames (bool wantInputNames) const
  218911. {
  218912. jassert (hasScanned); // need to call scanForDevices() before doing this
  218913. return wantInputNames ? inputNames : outputNames;
  218914. }
  218915. int getDefaultDeviceIndex (bool forInput) const
  218916. {
  218917. jassert (hasScanned); // need to call scanForDevices() before doing this
  218918. return 0;
  218919. }
  218920. bool hasSeparateInputsAndOutputs() const { return true; }
  218921. int getIndexOfDevice (AudioIODevice* device, bool asInput) const
  218922. {
  218923. jassert (hasScanned); // need to call scanForDevices() before doing this
  218924. ALSAAudioIODevice* d = dynamic_cast <ALSAAudioIODevice*> (device);
  218925. if (d == 0)
  218926. return -1;
  218927. return asInput ? inputIds.indexOf (d->inputId)
  218928. : outputIds.indexOf (d->outputId);
  218929. }
  218930. AudioIODevice* createDevice (const String& outputDeviceName,
  218931. const String& inputDeviceName)
  218932. {
  218933. jassert (hasScanned); // need to call scanForDevices() before doing this
  218934. const int inputIndex = inputNames.indexOf (inputDeviceName);
  218935. const int outputIndex = outputNames.indexOf (outputDeviceName);
  218936. String deviceName (outputIndex >= 0 ? outputDeviceName
  218937. : inputDeviceName);
  218938. if (inputIndex >= 0 || outputIndex >= 0)
  218939. return new ALSAAudioIODevice (deviceName,
  218940. inputIds [inputIndex],
  218941. outputIds [outputIndex]);
  218942. return 0;
  218943. }
  218944. juce_UseDebuggingNewOperator
  218945. private:
  218946. StringArray inputNames, outputNames, inputIds, outputIds;
  218947. bool hasScanned;
  218948. static bool testDevice (const String& id, bool& isInput, bool& isOutput)
  218949. {
  218950. unsigned int minChansOut = 0, maxChansOut = 0;
  218951. unsigned int minChansIn = 0, maxChansIn = 0;
  218952. Array <int> rates;
  218953. getDeviceProperties (id, minChansOut, maxChansOut, minChansIn, maxChansIn, rates);
  218954. DBG ("ALSA device: " + id
  218955. + " outs=" + String ((int) minChansOut) + "-" + String ((int) maxChansOut)
  218956. + " ins=" + String ((int) minChansIn) + "-" + String ((int) maxChansIn)
  218957. + " rates=" + String (rates.size()));
  218958. isInput = maxChansIn > 0;
  218959. isOutput = maxChansOut > 0;
  218960. return (isInput || isOutput) && rates.size() > 0;
  218961. }
  218962. ALSAAudioIODeviceType (const ALSAAudioIODeviceType&);
  218963. ALSAAudioIODeviceType& operator= (const ALSAAudioIODeviceType&);
  218964. };
  218965. AudioIODeviceType* juce_createAudioIODeviceType_ALSA()
  218966. {
  218967. return new ALSAAudioIODeviceType();
  218968. }
  218969. #endif
  218970. /*** End of inlined file: juce_linux_Audio.cpp ***/
  218971. /*** Start of inlined file: juce_linux_JackAudio.cpp ***/
  218972. // (This file gets included by juce_linux_NativeCode.cpp, rather than being
  218973. // compiled on its own).
  218974. #ifdef JUCE_INCLUDED_FILE
  218975. #if JUCE_JACK
  218976. static void* juce_libjack_handle = 0;
  218977. void* juce_load_jack_function (const char* const name)
  218978. {
  218979. if (juce_libjack_handle == 0)
  218980. return 0;
  218981. return dlsym (juce_libjack_handle, name);
  218982. }
  218983. #define JUCE_DECL_JACK_FUNCTION(return_type, fn_name, argument_types, arguments) \
  218984. typedef return_type (*fn_name##_ptr_t)argument_types; \
  218985. return_type fn_name argument_types { \
  218986. static fn_name##_ptr_t fn = 0; \
  218987. if (fn == 0) { fn = (fn_name##_ptr_t)juce_load_jack_function(#fn_name); } \
  218988. if (fn) return (*fn)arguments; \
  218989. else return 0; \
  218990. }
  218991. #define JUCE_DECL_VOID_JACK_FUNCTION(fn_name, argument_types, arguments) \
  218992. typedef void (*fn_name##_ptr_t)argument_types; \
  218993. void fn_name argument_types { \
  218994. static fn_name##_ptr_t fn = 0; \
  218995. if (fn == 0) { fn = (fn_name##_ptr_t)juce_load_jack_function(#fn_name); } \
  218996. if (fn) (*fn)arguments; \
  218997. }
  218998. 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));
  218999. JUCE_DECL_JACK_FUNCTION (int, jack_client_close, (jack_client_t *client), (client));
  219000. JUCE_DECL_JACK_FUNCTION (int, jack_activate, (jack_client_t* client), (client));
  219001. JUCE_DECL_JACK_FUNCTION (int, jack_deactivate, (jack_client_t* client), (client));
  219002. JUCE_DECL_JACK_FUNCTION (jack_nframes_t, jack_get_buffer_size, (jack_client_t* client), (client));
  219003. JUCE_DECL_JACK_FUNCTION (jack_nframes_t, jack_get_sample_rate, (jack_client_t* client), (client));
  219004. JUCE_DECL_VOID_JACK_FUNCTION (jack_on_shutdown, (jack_client_t* client, void (*function)(void* arg), void* arg), (client, function, arg));
  219005. JUCE_DECL_JACK_FUNCTION (void* , jack_port_get_buffer, (jack_port_t* port, jack_nframes_t nframes), (port, nframes));
  219006. JUCE_DECL_JACK_FUNCTION (jack_nframes_t, jack_port_get_total_latency, (jack_client_t* client, jack_port_t* port), (client, port));
  219007. 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));
  219008. JUCE_DECL_VOID_JACK_FUNCTION (jack_set_error_function, (void (*func)(const char*)), (func));
  219009. JUCE_DECL_JACK_FUNCTION (int, jack_set_process_callback, (jack_client_t* client, JackProcessCallback process_callback, void* arg), (client, process_callback, arg));
  219010. 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));
  219011. JUCE_DECL_JACK_FUNCTION (int, jack_connect, (jack_client_t* client, const char* source_port, const char* destination_port), (client, source_port, destination_port));
  219012. JUCE_DECL_JACK_FUNCTION (const char*, jack_port_name, (const jack_port_t* port), (port));
  219013. JUCE_DECL_JACK_FUNCTION (int, jack_set_port_connect_callback, (jack_client_t* client, JackPortConnectCallback connect_callback, void* arg), (client, connect_callback, arg));
  219014. JUCE_DECL_JACK_FUNCTION (jack_port_t* , jack_port_by_id, (jack_client_t* client, jack_port_id_t port_id), (client, port_id));
  219015. JUCE_DECL_JACK_FUNCTION (int, jack_port_connected, (const jack_port_t* port), (port));
  219016. JUCE_DECL_JACK_FUNCTION (int, jack_port_connected_to, (const jack_port_t* port, const char* port_name), (port, port_name));
  219017. #if JUCE_DEBUG
  219018. #define JACK_LOGGING_ENABLED 1
  219019. #endif
  219020. #if JACK_LOGGING_ENABLED
  219021. static void jack_Log (const String& s)
  219022. {
  219023. std::cerr << s << std::endl;
  219024. }
  219025. static void dumpJackErrorMessage (const jack_status_t status) throw()
  219026. {
  219027. if (status & JackServerFailed || status & JackServerError)
  219028. jack_Log ("Unable to connect to JACK server");
  219029. if (status & JackVersionError)
  219030. jack_Log ("Client's protocol version does not match");
  219031. if (status & JackInvalidOption)
  219032. jack_Log ("The operation contained an invalid or unsupported option");
  219033. if (status & JackNameNotUnique)
  219034. jack_Log ("The desired client name was not unique");
  219035. if (status & JackNoSuchClient)
  219036. jack_Log ("Requested client does not exist");
  219037. if (status & JackInitFailure)
  219038. jack_Log ("Unable to initialize client");
  219039. }
  219040. #else
  219041. #define dumpJackErrorMessage(a) {}
  219042. #define jack_Log(...) {}
  219043. #endif
  219044. #ifndef JUCE_JACK_CLIENT_NAME
  219045. #define JUCE_JACK_CLIENT_NAME "JuceJack"
  219046. #endif
  219047. class JackAudioIODevice : public AudioIODevice
  219048. {
  219049. public:
  219050. JackAudioIODevice (const String& deviceName,
  219051. const String& inputId_,
  219052. const String& outputId_)
  219053. : AudioIODevice (deviceName, "JACK"),
  219054. inputId (inputId_),
  219055. outputId (outputId_),
  219056. isOpen_ (false),
  219057. callback (0),
  219058. totalNumberOfInputChannels (0),
  219059. totalNumberOfOutputChannels (0)
  219060. {
  219061. jassert (deviceName.isNotEmpty());
  219062. jack_status_t status;
  219063. client = JUCE_NAMESPACE::jack_client_open (JUCE_JACK_CLIENT_NAME, JackNoStartServer, &status);
  219064. if (client == 0)
  219065. {
  219066. dumpJackErrorMessage (status);
  219067. }
  219068. else
  219069. {
  219070. JUCE_NAMESPACE::jack_set_error_function (errorCallback);
  219071. // open input ports
  219072. const StringArray inputChannels (getInputChannelNames());
  219073. for (int i = 0; i < inputChannels.size(); i++)
  219074. {
  219075. String inputName;
  219076. inputName << "in_" << ++totalNumberOfInputChannels;
  219077. inputPorts.add (JUCE_NAMESPACE::jack_port_register (client, inputName.toUTF8(),
  219078. JACK_DEFAULT_AUDIO_TYPE, JackPortIsInput, 0));
  219079. }
  219080. // open output ports
  219081. const StringArray outputChannels (getOutputChannelNames());
  219082. for (int i = 0; i < outputChannels.size (); i++)
  219083. {
  219084. String outputName;
  219085. outputName << "out_" << ++totalNumberOfOutputChannels;
  219086. outputPorts.add (JUCE_NAMESPACE::jack_port_register (client, outputName.toUTF8(),
  219087. JACK_DEFAULT_AUDIO_TYPE, JackPortIsOutput, 0));
  219088. }
  219089. inChans.calloc (totalNumberOfInputChannels + 2);
  219090. outChans.calloc (totalNumberOfOutputChannels + 2);
  219091. }
  219092. }
  219093. ~JackAudioIODevice()
  219094. {
  219095. close();
  219096. if (client != 0)
  219097. {
  219098. JUCE_NAMESPACE::jack_client_close (client);
  219099. client = 0;
  219100. }
  219101. }
  219102. const StringArray getChannelNames (bool forInput) const
  219103. {
  219104. StringArray names;
  219105. const char** const ports = JUCE_NAMESPACE::jack_get_ports (client, 0, 0, /* JackPortIsPhysical | */
  219106. forInput ? JackPortIsInput : JackPortIsOutput);
  219107. if (ports != 0)
  219108. {
  219109. int j = 0;
  219110. while (ports[j] != 0)
  219111. {
  219112. const String portName (ports [j++]);
  219113. if (portName.upToFirstOccurrenceOf (":", false, false) == getName())
  219114. names.add (portName.fromFirstOccurrenceOf (":", false, false));
  219115. }
  219116. free (ports);
  219117. }
  219118. return names;
  219119. }
  219120. const StringArray getOutputChannelNames() { return getChannelNames (false); }
  219121. const StringArray getInputChannelNames() { return getChannelNames (true); }
  219122. int getNumSampleRates() { return client != 0 ? 1 : 0; }
  219123. double getSampleRate (int index) { return client != 0 ? JUCE_NAMESPACE::jack_get_sample_rate (client) : 0; }
  219124. int getNumBufferSizesAvailable() { return client != 0 ? 1 : 0; }
  219125. int getBufferSizeSamples (int index) { return getDefaultBufferSize(); }
  219126. int getDefaultBufferSize() { return client != 0 ? JUCE_NAMESPACE::jack_get_buffer_size (client) : 0; }
  219127. const String open (const BigInteger& inputChannels, const BigInteger& outputChannels,
  219128. double sampleRate, int bufferSizeSamples)
  219129. {
  219130. if (client == 0)
  219131. {
  219132. lastError = "No JACK client running";
  219133. return lastError;
  219134. }
  219135. lastError = String::empty;
  219136. close();
  219137. JUCE_NAMESPACE::jack_set_process_callback (client, processCallback, this);
  219138. JUCE_NAMESPACE::jack_on_shutdown (client, shutdownCallback, this);
  219139. JUCE_NAMESPACE::jack_activate (client);
  219140. isOpen_ = true;
  219141. if (! inputChannels.isZero())
  219142. {
  219143. const char** const ports = JUCE_NAMESPACE::jack_get_ports (client, 0, 0, /* JackPortIsPhysical | */ JackPortIsOutput);
  219144. if (ports != 0)
  219145. {
  219146. const int numInputChannels = inputChannels.getHighestBit() + 1;
  219147. for (int i = 0; i < numInputChannels; ++i)
  219148. {
  219149. const String portName (ports[i]);
  219150. if (inputChannels[i] && portName.upToFirstOccurrenceOf (":", false, false) == getName())
  219151. {
  219152. int error = JUCE_NAMESPACE::jack_connect (client, ports[i], JUCE_NAMESPACE::jack_port_name ((jack_port_t*) inputPorts[i]));
  219153. if (error != 0)
  219154. jack_Log ("Cannot connect input port " + String (i) + " (" + String (ports[i]) + "), error " + String (error));
  219155. }
  219156. }
  219157. free (ports);
  219158. }
  219159. }
  219160. if (! outputChannels.isZero())
  219161. {
  219162. const char** const ports = JUCE_NAMESPACE::jack_get_ports (client, 0, 0, /* JackPortIsPhysical | */ JackPortIsInput);
  219163. if (ports != 0)
  219164. {
  219165. const int numOutputChannels = outputChannels.getHighestBit() + 1;
  219166. for (int i = 0; i < numOutputChannels; ++i)
  219167. {
  219168. const String portName (ports[i]);
  219169. if (outputChannels[i] && portName.upToFirstOccurrenceOf (":", false, false) == getName())
  219170. {
  219171. int error = JUCE_NAMESPACE::jack_connect (client, JUCE_NAMESPACE::jack_port_name ((jack_port_t*) outputPorts[i]), ports[i]);
  219172. if (error != 0)
  219173. jack_Log ("Cannot connect output port " + String (i) + " (" + String (ports[i]) + "), error " + String (error));
  219174. }
  219175. }
  219176. free (ports);
  219177. }
  219178. }
  219179. return lastError;
  219180. }
  219181. void close()
  219182. {
  219183. stop();
  219184. if (client != 0)
  219185. {
  219186. JUCE_NAMESPACE::jack_deactivate (client);
  219187. JUCE_NAMESPACE::jack_set_process_callback (client, processCallback, 0);
  219188. JUCE_NAMESPACE::jack_on_shutdown (client, shutdownCallback, 0);
  219189. }
  219190. isOpen_ = false;
  219191. }
  219192. void start (AudioIODeviceCallback* newCallback)
  219193. {
  219194. if (isOpen_ && newCallback != callback)
  219195. {
  219196. if (newCallback != 0)
  219197. newCallback->audioDeviceAboutToStart (this);
  219198. AudioIODeviceCallback* const oldCallback = callback;
  219199. {
  219200. const ScopedLock sl (callbackLock);
  219201. callback = newCallback;
  219202. }
  219203. if (oldCallback != 0)
  219204. oldCallback->audioDeviceStopped();
  219205. }
  219206. }
  219207. void stop()
  219208. {
  219209. start (0);
  219210. }
  219211. bool isOpen() { return isOpen_; }
  219212. bool isPlaying() { return callback != 0; }
  219213. int getCurrentBufferSizeSamples() { return getBufferSizeSamples (0); }
  219214. double getCurrentSampleRate() { return getSampleRate (0); }
  219215. int getCurrentBitDepth() { return 32; }
  219216. const String getLastError() { return lastError; }
  219217. const BigInteger getActiveOutputChannels() const
  219218. {
  219219. BigInteger outputBits;
  219220. for (int i = 0; i < outputPorts.size(); i++)
  219221. if (JUCE_NAMESPACE::jack_port_connected ((jack_port_t*) outputPorts [i]))
  219222. outputBits.setBit (i);
  219223. return outputBits;
  219224. }
  219225. const BigInteger getActiveInputChannels() const
  219226. {
  219227. BigInteger inputBits;
  219228. for (int i = 0; i < inputPorts.size(); i++)
  219229. if (JUCE_NAMESPACE::jack_port_connected ((jack_port_t*) inputPorts [i]))
  219230. inputBits.setBit (i);
  219231. return inputBits;
  219232. }
  219233. int getOutputLatencyInSamples()
  219234. {
  219235. int latency = 0;
  219236. for (int i = 0; i < outputPorts.size(); i++)
  219237. latency = jmax (latency, (int) JUCE_NAMESPACE::jack_port_get_total_latency (client, (jack_port_t*) outputPorts [i]));
  219238. return latency;
  219239. }
  219240. int getInputLatencyInSamples()
  219241. {
  219242. int latency = 0;
  219243. for (int i = 0; i < inputPorts.size(); i++)
  219244. latency = jmax (latency, (int) JUCE_NAMESPACE::jack_port_get_total_latency (client, (jack_port_t*) inputPorts [i]));
  219245. return latency;
  219246. }
  219247. String inputId, outputId;
  219248. private:
  219249. void process (const int numSamples)
  219250. {
  219251. int i, numActiveInChans = 0, numActiveOutChans = 0;
  219252. for (i = 0; i < totalNumberOfInputChannels; ++i)
  219253. {
  219254. jack_default_audio_sample_t* in
  219255. = (jack_default_audio_sample_t*) JUCE_NAMESPACE::jack_port_get_buffer ((jack_port_t*) inputPorts.getUnchecked(i), numSamples);
  219256. if (in != 0)
  219257. inChans [numActiveInChans++] = (float*) in;
  219258. }
  219259. for (i = 0; i < totalNumberOfOutputChannels; ++i)
  219260. {
  219261. jack_default_audio_sample_t* out
  219262. = (jack_default_audio_sample_t*) JUCE_NAMESPACE::jack_port_get_buffer ((jack_port_t*) outputPorts.getUnchecked(i), numSamples);
  219263. if (out != 0)
  219264. outChans [numActiveOutChans++] = (float*) out;
  219265. }
  219266. const ScopedLock sl (callbackLock);
  219267. if (callback != 0)
  219268. {
  219269. callback->audioDeviceIOCallback (const_cast<const float**> (inChans.getData()), numActiveInChans,
  219270. outChans, numActiveOutChans, numSamples);
  219271. }
  219272. else
  219273. {
  219274. for (i = 0; i < numActiveOutChans; ++i)
  219275. zeromem (outChans[i], sizeof (float) * numSamples);
  219276. }
  219277. }
  219278. static int processCallback (jack_nframes_t nframes, void* callbackArgument)
  219279. {
  219280. if (callbackArgument != 0)
  219281. ((JackAudioIODevice*) callbackArgument)->process (nframes);
  219282. return 0;
  219283. }
  219284. static void threadInitCallback (void* callbackArgument)
  219285. {
  219286. jack_Log ("JackAudioIODevice::initialise");
  219287. }
  219288. static void shutdownCallback (void* callbackArgument)
  219289. {
  219290. jack_Log ("JackAudioIODevice::shutdown");
  219291. JackAudioIODevice* device = (JackAudioIODevice*) callbackArgument;
  219292. if (device != 0)
  219293. {
  219294. device->client = 0;
  219295. device->close();
  219296. }
  219297. }
  219298. static void errorCallback (const char* msg)
  219299. {
  219300. jack_Log ("JackAudioIODevice::errorCallback " + String (msg));
  219301. }
  219302. bool isOpen_;
  219303. jack_client_t* client;
  219304. String lastError;
  219305. AudioIODeviceCallback* callback;
  219306. CriticalSection callbackLock;
  219307. HeapBlock <float*> inChans, outChans;
  219308. int totalNumberOfInputChannels;
  219309. int totalNumberOfOutputChannels;
  219310. VoidArray inputPorts, outputPorts;
  219311. };
  219312. class JackAudioIODeviceType : public AudioIODeviceType
  219313. {
  219314. public:
  219315. JackAudioIODeviceType()
  219316. : AudioIODeviceType ("JACK"),
  219317. hasScanned (false)
  219318. {
  219319. }
  219320. ~JackAudioIODeviceType()
  219321. {
  219322. }
  219323. void scanForDevices()
  219324. {
  219325. hasScanned = true;
  219326. inputNames.clear();
  219327. inputIds.clear();
  219328. outputNames.clear();
  219329. outputIds.clear();
  219330. if (juce_libjack_handle == 0)
  219331. {
  219332. juce_libjack_handle = dlopen ("libjack.so", RTLD_LAZY);
  219333. if (juce_libjack_handle == 0)
  219334. return;
  219335. }
  219336. // open a dummy client
  219337. jack_status_t status;
  219338. jack_client_t* client = JUCE_NAMESPACE::jack_client_open ("JuceJackDummy", JackNoStartServer, &status);
  219339. if (client == 0)
  219340. {
  219341. dumpJackErrorMessage (status);
  219342. }
  219343. else
  219344. {
  219345. // scan for output devices
  219346. const char** ports = JUCE_NAMESPACE::jack_get_ports (client, 0, 0, /* JackPortIsPhysical | */ JackPortIsOutput);
  219347. if (ports != 0)
  219348. {
  219349. int j = 0;
  219350. while (ports[j] != 0)
  219351. {
  219352. String clientName (ports[j]);
  219353. clientName = clientName.upToFirstOccurrenceOf (":", false, false);
  219354. if (clientName != String (JUCE_JACK_CLIENT_NAME)
  219355. && ! inputNames.contains (clientName))
  219356. {
  219357. inputNames.add (clientName);
  219358. inputIds.add (ports [j]);
  219359. }
  219360. ++j;
  219361. }
  219362. free (ports);
  219363. }
  219364. // scan for input devices
  219365. ports = JUCE_NAMESPACE::jack_get_ports (client, 0, 0, /* JackPortIsPhysical | */ JackPortIsInput);
  219366. if (ports != 0)
  219367. {
  219368. int j = 0;
  219369. while (ports[j] != 0)
  219370. {
  219371. String clientName (ports[j]);
  219372. clientName = clientName.upToFirstOccurrenceOf (":", false, false);
  219373. if (clientName != String (JUCE_JACK_CLIENT_NAME)
  219374. && ! outputNames.contains (clientName))
  219375. {
  219376. outputNames.add (clientName);
  219377. outputIds.add (ports [j]);
  219378. }
  219379. ++j;
  219380. }
  219381. free (ports);
  219382. }
  219383. JUCE_NAMESPACE::jack_client_close (client);
  219384. }
  219385. }
  219386. const StringArray getDeviceNames (bool wantInputNames) const
  219387. {
  219388. jassert (hasScanned); // need to call scanForDevices() before doing this
  219389. return wantInputNames ? inputNames : outputNames;
  219390. }
  219391. int getDefaultDeviceIndex (bool forInput) const
  219392. {
  219393. jassert (hasScanned); // need to call scanForDevices() before doing this
  219394. return 0;
  219395. }
  219396. bool hasSeparateInputsAndOutputs() const { return true; }
  219397. int getIndexOfDevice (AudioIODevice* device, bool asInput) const
  219398. {
  219399. jassert (hasScanned); // need to call scanForDevices() before doing this
  219400. JackAudioIODevice* d = dynamic_cast <JackAudioIODevice*> (device);
  219401. if (d == 0)
  219402. return -1;
  219403. return asInput ? inputIds.indexOf (d->inputId)
  219404. : outputIds.indexOf (d->outputId);
  219405. }
  219406. AudioIODevice* createDevice (const String& outputDeviceName,
  219407. const String& inputDeviceName)
  219408. {
  219409. jassert (hasScanned); // need to call scanForDevices() before doing this
  219410. const int inputIndex = inputNames.indexOf (inputDeviceName);
  219411. const int outputIndex = outputNames.indexOf (outputDeviceName);
  219412. if (inputIndex >= 0 || outputIndex >= 0)
  219413. return new JackAudioIODevice (outputIndex >= 0 ? outputDeviceName
  219414. : inputDeviceName,
  219415. inputIds [inputIndex],
  219416. outputIds [outputIndex]);
  219417. return 0;
  219418. }
  219419. juce_UseDebuggingNewOperator
  219420. private:
  219421. StringArray inputNames, outputNames, inputIds, outputIds;
  219422. bool hasScanned;
  219423. JackAudioIODeviceType (const JackAudioIODeviceType&);
  219424. JackAudioIODeviceType& operator= (const JackAudioIODeviceType&);
  219425. };
  219426. AudioIODeviceType* juce_createAudioIODeviceType_JACK()
  219427. {
  219428. return new JackAudioIODeviceType();
  219429. }
  219430. #else // if JACK is turned off..
  219431. AudioIODeviceType* juce_createAudioIODeviceType_JACK() { return 0; }
  219432. #endif
  219433. #endif
  219434. /*** End of inlined file: juce_linux_JackAudio.cpp ***/
  219435. /*** Start of inlined file: juce_linux_Midi.cpp ***/
  219436. // (This file gets included by juce_linux_NativeCode.cpp, rather than being
  219437. // compiled on its own).
  219438. #if JUCE_INCLUDED_FILE
  219439. #if JUCE_ALSA
  219440. static snd_seq_t* iterateDevices (const bool forInput,
  219441. StringArray& deviceNamesFound,
  219442. const int deviceIndexToOpen)
  219443. {
  219444. snd_seq_t* returnedHandle = 0;
  219445. snd_seq_t* seqHandle;
  219446. if (snd_seq_open (&seqHandle, "default", forInput ? SND_SEQ_OPEN_INPUT
  219447. : SND_SEQ_OPEN_OUTPUT, 0) == 0)
  219448. {
  219449. snd_seq_system_info_t* systemInfo;
  219450. snd_seq_client_info_t* clientInfo;
  219451. if (snd_seq_system_info_malloc (&systemInfo) == 0)
  219452. {
  219453. if (snd_seq_system_info (seqHandle, systemInfo) == 0
  219454. && snd_seq_client_info_malloc (&clientInfo) == 0)
  219455. {
  219456. int numClients = snd_seq_system_info_get_cur_clients (systemInfo);
  219457. while (--numClients >= 0 && returnedHandle == 0)
  219458. {
  219459. if (snd_seq_query_next_client (seqHandle, clientInfo) == 0)
  219460. {
  219461. snd_seq_port_info_t* portInfo;
  219462. if (snd_seq_port_info_malloc (&portInfo) == 0)
  219463. {
  219464. int numPorts = snd_seq_client_info_get_num_ports (clientInfo);
  219465. const int client = snd_seq_client_info_get_client (clientInfo);
  219466. snd_seq_port_info_set_client (portInfo, client);
  219467. snd_seq_port_info_set_port (portInfo, -1);
  219468. while (--numPorts >= 0)
  219469. {
  219470. if (snd_seq_query_next_port (seqHandle, portInfo) == 0
  219471. && (snd_seq_port_info_get_capability (portInfo)
  219472. & (forInput ? SND_SEQ_PORT_CAP_READ
  219473. : SND_SEQ_PORT_CAP_WRITE)) != 0)
  219474. {
  219475. deviceNamesFound.add (snd_seq_client_info_get_name (clientInfo));
  219476. if (deviceNamesFound.size() == deviceIndexToOpen + 1)
  219477. {
  219478. const int sourcePort = snd_seq_port_info_get_port (portInfo);
  219479. const int sourceClient = snd_seq_client_info_get_client (clientInfo);
  219480. if (sourcePort != -1)
  219481. {
  219482. snd_seq_set_client_name (seqHandle,
  219483. forInput ? "Juce Midi Input"
  219484. : "Juce Midi Output");
  219485. const int portId
  219486. = snd_seq_create_simple_port (seqHandle,
  219487. forInput ? "Juce Midi In Port"
  219488. : "Juce Midi Out Port",
  219489. forInput ? (SND_SEQ_PORT_CAP_WRITE | SND_SEQ_PORT_CAP_SUBS_WRITE)
  219490. : (SND_SEQ_PORT_CAP_READ | SND_SEQ_PORT_CAP_SUBS_READ),
  219491. SND_SEQ_PORT_TYPE_MIDI_GENERIC);
  219492. snd_seq_connect_from (seqHandle, portId, sourceClient, sourcePort);
  219493. returnedHandle = seqHandle;
  219494. }
  219495. }
  219496. }
  219497. }
  219498. snd_seq_port_info_free (portInfo);
  219499. }
  219500. }
  219501. }
  219502. snd_seq_client_info_free (clientInfo);
  219503. }
  219504. snd_seq_system_info_free (systemInfo);
  219505. }
  219506. if (returnedHandle == 0)
  219507. snd_seq_close (seqHandle);
  219508. }
  219509. deviceNamesFound.appendNumbersToDuplicates (true, true);
  219510. return returnedHandle;
  219511. }
  219512. static snd_seq_t* createDevice (const bool forInput,
  219513. const String& deviceNameToOpen)
  219514. {
  219515. snd_seq_t* seqHandle = 0;
  219516. if (snd_seq_open (&seqHandle, "default", forInput ? SND_SEQ_OPEN_INPUT
  219517. : SND_SEQ_OPEN_OUTPUT, 0) == 0)
  219518. {
  219519. snd_seq_set_client_name (seqHandle,
  219520. (deviceNameToOpen + (forInput ? " Input" : " Output")).toCString());
  219521. const int portId
  219522. = snd_seq_create_simple_port (seqHandle,
  219523. forInput ? "in"
  219524. : "out",
  219525. forInput ? (SND_SEQ_PORT_CAP_WRITE | SND_SEQ_PORT_CAP_SUBS_WRITE)
  219526. : (SND_SEQ_PORT_CAP_READ | SND_SEQ_PORT_CAP_SUBS_READ),
  219527. forInput ? SND_SEQ_PORT_TYPE_APPLICATION
  219528. : SND_SEQ_PORT_TYPE_MIDI_GENERIC);
  219529. if (portId < 0)
  219530. {
  219531. snd_seq_close (seqHandle);
  219532. seqHandle = 0;
  219533. }
  219534. }
  219535. return seqHandle;
  219536. }
  219537. class MidiOutputDevice
  219538. {
  219539. public:
  219540. MidiOutputDevice (MidiOutput* const midiOutput_,
  219541. snd_seq_t* const seqHandle_)
  219542. :
  219543. midiOutput (midiOutput_),
  219544. seqHandle (seqHandle_),
  219545. maxEventSize (16 * 1024)
  219546. {
  219547. jassert (seqHandle != 0 && midiOutput != 0);
  219548. snd_midi_event_new (maxEventSize, &midiParser);
  219549. }
  219550. ~MidiOutputDevice()
  219551. {
  219552. snd_midi_event_free (midiParser);
  219553. snd_seq_close (seqHandle);
  219554. }
  219555. void sendMessageNow (const MidiMessage& message)
  219556. {
  219557. if (message.getRawDataSize() > maxEventSize)
  219558. {
  219559. maxEventSize = message.getRawDataSize();
  219560. snd_midi_event_free (midiParser);
  219561. snd_midi_event_new (maxEventSize, &midiParser);
  219562. }
  219563. snd_seq_event_t event;
  219564. snd_seq_ev_clear (&event);
  219565. snd_midi_event_encode (midiParser,
  219566. message.getRawData(),
  219567. message.getRawDataSize(),
  219568. &event);
  219569. snd_midi_event_reset_encode (midiParser);
  219570. snd_seq_ev_set_source (&event, 0);
  219571. snd_seq_ev_set_subs (&event);
  219572. snd_seq_ev_set_direct (&event);
  219573. snd_seq_event_output (seqHandle, &event);
  219574. snd_seq_drain_output (seqHandle);
  219575. }
  219576. juce_UseDebuggingNewOperator
  219577. private:
  219578. MidiOutput* const midiOutput;
  219579. snd_seq_t* const seqHandle;
  219580. snd_midi_event_t* midiParser;
  219581. int maxEventSize;
  219582. };
  219583. const StringArray MidiOutput::getDevices()
  219584. {
  219585. StringArray devices;
  219586. iterateDevices (false, devices, -1);
  219587. return devices;
  219588. }
  219589. int MidiOutput::getDefaultDeviceIndex()
  219590. {
  219591. return 0;
  219592. }
  219593. MidiOutput* MidiOutput::openDevice (int deviceIndex)
  219594. {
  219595. MidiOutput* newDevice = 0;
  219596. StringArray devices;
  219597. snd_seq_t* const handle = iterateDevices (false, devices, deviceIndex);
  219598. if (handle != 0)
  219599. {
  219600. newDevice = new MidiOutput();
  219601. newDevice->internal = new MidiOutputDevice (newDevice, handle);
  219602. }
  219603. return newDevice;
  219604. }
  219605. MidiOutput* MidiOutput::createNewDevice (const String& deviceName)
  219606. {
  219607. MidiOutput* newDevice = 0;
  219608. snd_seq_t* const handle = createDevice (false, deviceName);
  219609. if (handle != 0)
  219610. {
  219611. newDevice = new MidiOutput();
  219612. newDevice->internal = new MidiOutputDevice (newDevice, handle);
  219613. }
  219614. return newDevice;
  219615. }
  219616. MidiOutput::~MidiOutput()
  219617. {
  219618. MidiOutputDevice* const device = (MidiOutputDevice*) internal;
  219619. delete device;
  219620. }
  219621. void MidiOutput::reset()
  219622. {
  219623. }
  219624. bool MidiOutput::getVolume (float& leftVol, float& rightVol)
  219625. {
  219626. return false;
  219627. }
  219628. void MidiOutput::setVolume (float leftVol, float rightVol)
  219629. {
  219630. }
  219631. void MidiOutput::sendMessageNow (const MidiMessage& message)
  219632. {
  219633. ((MidiOutputDevice*) internal)->sendMessageNow (message);
  219634. }
  219635. class MidiInputThread : public Thread
  219636. {
  219637. public:
  219638. MidiInputThread (MidiInput* const midiInput_,
  219639. snd_seq_t* const seqHandle_,
  219640. MidiInputCallback* const callback_)
  219641. : Thread ("Juce MIDI Input"),
  219642. midiInput (midiInput_),
  219643. seqHandle (seqHandle_),
  219644. callback (callback_)
  219645. {
  219646. jassert (seqHandle != 0 && callback != 0 && midiInput != 0);
  219647. }
  219648. ~MidiInputThread()
  219649. {
  219650. snd_seq_close (seqHandle);
  219651. }
  219652. void run()
  219653. {
  219654. const int maxEventSize = 16 * 1024;
  219655. snd_midi_event_t* midiParser;
  219656. if (snd_midi_event_new (maxEventSize, &midiParser) >= 0)
  219657. {
  219658. HeapBlock <uint8> buffer (maxEventSize);
  219659. const int numPfds = snd_seq_poll_descriptors_count (seqHandle, POLLIN);
  219660. struct pollfd* const pfd = (struct pollfd*) alloca (numPfds * sizeof (struct pollfd));
  219661. snd_seq_poll_descriptors (seqHandle, pfd, numPfds, POLLIN);
  219662. while (! threadShouldExit())
  219663. {
  219664. if (poll (pfd, numPfds, 500) > 0)
  219665. {
  219666. snd_seq_event_t* inputEvent = 0;
  219667. snd_seq_nonblock (seqHandle, 1);
  219668. do
  219669. {
  219670. if (snd_seq_event_input (seqHandle, &inputEvent) >= 0)
  219671. {
  219672. // xxx what about SYSEXes that are too big for the buffer?
  219673. const int numBytes = snd_midi_event_decode (midiParser, buffer, maxEventSize, inputEvent);
  219674. snd_midi_event_reset_decode (midiParser);
  219675. if (numBytes > 0)
  219676. {
  219677. const MidiMessage message ((const uint8*) buffer,
  219678. numBytes,
  219679. Time::getMillisecondCounter() * 0.001);
  219680. callback->handleIncomingMidiMessage (midiInput, message);
  219681. }
  219682. snd_seq_free_event (inputEvent);
  219683. }
  219684. }
  219685. while (snd_seq_event_input_pending (seqHandle, 0) > 0);
  219686. snd_seq_free_event (inputEvent);
  219687. }
  219688. }
  219689. snd_midi_event_free (midiParser);
  219690. }
  219691. };
  219692. juce_UseDebuggingNewOperator
  219693. private:
  219694. MidiInput* const midiInput;
  219695. snd_seq_t* const seqHandle;
  219696. MidiInputCallback* const callback;
  219697. };
  219698. MidiInput::MidiInput (const String& name_)
  219699. : name (name_),
  219700. internal (0)
  219701. {
  219702. }
  219703. MidiInput::~MidiInput()
  219704. {
  219705. stop();
  219706. MidiInputThread* const thread = (MidiInputThread*) internal;
  219707. delete thread;
  219708. }
  219709. void MidiInput::start()
  219710. {
  219711. ((MidiInputThread*) internal)->startThread();
  219712. }
  219713. void MidiInput::stop()
  219714. {
  219715. ((MidiInputThread*) internal)->stopThread (3000);
  219716. }
  219717. int MidiInput::getDefaultDeviceIndex()
  219718. {
  219719. return 0;
  219720. }
  219721. const StringArray MidiInput::getDevices()
  219722. {
  219723. StringArray devices;
  219724. iterateDevices (true, devices, -1);
  219725. return devices;
  219726. }
  219727. MidiInput* MidiInput::openDevice (int deviceIndex, MidiInputCallback* callback)
  219728. {
  219729. MidiInput* newDevice = 0;
  219730. StringArray devices;
  219731. snd_seq_t* const handle = iterateDevices (true, devices, deviceIndex);
  219732. if (handle != 0)
  219733. {
  219734. newDevice = new MidiInput (devices [deviceIndex]);
  219735. newDevice->internal = new MidiInputThread (newDevice, handle, callback);
  219736. }
  219737. return newDevice;
  219738. }
  219739. MidiInput* MidiInput::createNewDevice (const String& deviceName, MidiInputCallback* callback)
  219740. {
  219741. MidiInput* newDevice = 0;
  219742. snd_seq_t* const handle = createDevice (true, deviceName);
  219743. if (handle != 0)
  219744. {
  219745. newDevice = new MidiInput (deviceName);
  219746. newDevice->internal = new MidiInputThread (newDevice, handle, callback);
  219747. }
  219748. return newDevice;
  219749. }
  219750. #else
  219751. // (These are just stub functions if ALSA is unavailable...)
  219752. const StringArray MidiOutput::getDevices() { return StringArray(); }
  219753. int MidiOutput::getDefaultDeviceIndex() { return 0; }
  219754. MidiOutput* MidiOutput::openDevice (int) { return 0; }
  219755. MidiOutput* MidiOutput::createNewDevice (const String&) { return 0; }
  219756. MidiOutput::~MidiOutput() {}
  219757. void MidiOutput::reset() {}
  219758. bool MidiOutput::getVolume (float&, float&) { return false; }
  219759. void MidiOutput::setVolume (float, float) {}
  219760. void MidiOutput::sendMessageNow (const MidiMessage&) {}
  219761. MidiInput::MidiInput (const String& name_) : name (name_), internal (0) {}
  219762. MidiInput::~MidiInput() {}
  219763. void MidiInput::start() {}
  219764. void MidiInput::stop() {}
  219765. int MidiInput::getDefaultDeviceIndex() { return 0; }
  219766. const StringArray MidiInput::getDevices() { return StringArray(); }
  219767. MidiInput* MidiInput::openDevice (int, MidiInputCallback*) { return 0; }
  219768. MidiInput* MidiInput::createNewDevice (const String&, MidiInputCallback*) { return 0; }
  219769. #endif
  219770. #endif
  219771. /*** End of inlined file: juce_linux_Midi.cpp ***/
  219772. /*** Start of inlined file: juce_linux_AudioCDReader.cpp ***/
  219773. // (This file gets included by juce_linux_NativeCode.cpp, rather than being
  219774. // compiled on its own).
  219775. #if JUCE_INCLUDED_FILE && JUCE_USE_CDREADER
  219776. AudioCDReader::AudioCDReader()
  219777. : AudioFormatReader (0, "CD Audio")
  219778. {
  219779. }
  219780. const StringArray AudioCDReader::getAvailableCDNames()
  219781. {
  219782. StringArray names;
  219783. return names;
  219784. }
  219785. AudioCDReader* AudioCDReader::createReaderForCD (const int index)
  219786. {
  219787. return 0;
  219788. }
  219789. AudioCDReader::~AudioCDReader()
  219790. {
  219791. }
  219792. void AudioCDReader::refreshTrackLengths()
  219793. {
  219794. }
  219795. bool AudioCDReader::readSamples (int** destSamples, int numDestChannels, int startOffsetInDestBuffer,
  219796. int64 startSampleInFile, int numSamples)
  219797. {
  219798. return false;
  219799. }
  219800. bool AudioCDReader::isCDStillPresent() const
  219801. {
  219802. return false;
  219803. }
  219804. int AudioCDReader::getNumTracks() const
  219805. {
  219806. return 0;
  219807. }
  219808. int AudioCDReader::getPositionOfTrackStart (int trackNum) const
  219809. {
  219810. return 0;
  219811. }
  219812. bool AudioCDReader::isTrackAudio (int trackNum) const
  219813. {
  219814. return false;
  219815. }
  219816. void AudioCDReader::enableIndexScanning (bool b)
  219817. {
  219818. }
  219819. int AudioCDReader::getLastIndex() const
  219820. {
  219821. return 0;
  219822. }
  219823. const Array<int> AudioCDReader::findIndexesInTrack (const int trackNumber)
  219824. {
  219825. return Array<int>();
  219826. }
  219827. int AudioCDReader::getCDDBId()
  219828. {
  219829. return 0;
  219830. }
  219831. #endif
  219832. /*** End of inlined file: juce_linux_AudioCDReader.cpp ***/
  219833. /*** Start of inlined file: juce_linux_FileChooser.cpp ***/
  219834. // (This file gets included by juce_linux_NativeCode.cpp, rather than being
  219835. // compiled on its own).
  219836. #if JUCE_INCLUDED_FILE
  219837. void FileChooser::showPlatformDialog (Array<File>& results,
  219838. const String& title,
  219839. const File& file,
  219840. const String& filters,
  219841. bool isDirectory,
  219842. bool selectsFiles,
  219843. bool isSave,
  219844. bool warnAboutOverwritingExistingFiles,
  219845. bool selectMultipleFiles,
  219846. FilePreviewComponent* previewComponent)
  219847. {
  219848. const String separator (":");
  219849. String command ("zenity --file-selection");
  219850. if (title.isNotEmpty())
  219851. command << " --title=\"" << title << "\"";
  219852. if (file != File::nonexistent)
  219853. command << " --filename=\"" << file.getFullPathName () << "\"";
  219854. if (isDirectory)
  219855. command << " --directory";
  219856. if (isSave)
  219857. command << " --save";
  219858. if (selectMultipleFiles)
  219859. command << " --multiple --separator=\"" << separator << "\"";
  219860. command << " 2>&1";
  219861. MemoryOutputStream result;
  219862. int status = -1;
  219863. FILE* stream = popen (command.toUTF8(), "r");
  219864. if (stream != 0)
  219865. {
  219866. for (;;)
  219867. {
  219868. char buffer [1024];
  219869. const int bytesRead = fread (buffer, 1, sizeof (buffer), stream);
  219870. if (bytesRead <= 0)
  219871. break;
  219872. result.write (buffer, bytesRead);
  219873. }
  219874. status = pclose (stream);
  219875. }
  219876. if (status == 0)
  219877. {
  219878. StringArray tokens;
  219879. if (selectMultipleFiles)
  219880. tokens.addTokens (result.toUTF8(), separator, String::empty);
  219881. else
  219882. tokens.add (result.toUTF8());
  219883. for (int i = 0; i < tokens.size(); i++)
  219884. results.add (File (tokens[i]));
  219885. return;
  219886. }
  219887. //xxx ain't got one!
  219888. jassertfalse
  219889. }
  219890. #endif
  219891. /*** End of inlined file: juce_linux_FileChooser.cpp ***/
  219892. /*** Start of inlined file: juce_linux_WebBrowserComponent.cpp ***/
  219893. // (This file gets included by juce_linux_NativeCode.cpp, rather than being
  219894. // compiled on its own).
  219895. #if JUCE_INCLUDED_FILE && JUCE_WEB_BROWSER
  219896. /*
  219897. Sorry.. This class isn't implemented on Linux!
  219898. */
  219899. WebBrowserComponent::WebBrowserComponent (const bool unloadPageWhenBrowserIsHidden_)
  219900. : browser (0),
  219901. blankPageShown (false),
  219902. unloadPageWhenBrowserIsHidden (unloadPageWhenBrowserIsHidden_)
  219903. {
  219904. setOpaque (true);
  219905. }
  219906. WebBrowserComponent::~WebBrowserComponent()
  219907. {
  219908. }
  219909. void WebBrowserComponent::goToURL (const String& url,
  219910. const StringArray* headers,
  219911. const MemoryBlock* postData)
  219912. {
  219913. lastURL = url;
  219914. lastHeaders.clear();
  219915. if (headers != 0)
  219916. lastHeaders = *headers;
  219917. lastPostData.setSize (0);
  219918. if (postData != 0)
  219919. lastPostData = *postData;
  219920. blankPageShown = false;
  219921. }
  219922. void WebBrowserComponent::stop()
  219923. {
  219924. }
  219925. void WebBrowserComponent::goBack()
  219926. {
  219927. lastURL = String::empty;
  219928. blankPageShown = false;
  219929. }
  219930. void WebBrowserComponent::goForward()
  219931. {
  219932. lastURL = String::empty;
  219933. }
  219934. void WebBrowserComponent::refresh()
  219935. {
  219936. }
  219937. void WebBrowserComponent::paint (Graphics& g)
  219938. {
  219939. g.fillAll (Colours::white);
  219940. }
  219941. void WebBrowserComponent::checkWindowAssociation()
  219942. {
  219943. }
  219944. void WebBrowserComponent::reloadLastURL()
  219945. {
  219946. if (lastURL.isNotEmpty())
  219947. {
  219948. goToURL (lastURL, &lastHeaders, &lastPostData);
  219949. lastURL = String::empty;
  219950. }
  219951. }
  219952. void WebBrowserComponent::parentHierarchyChanged()
  219953. {
  219954. checkWindowAssociation();
  219955. }
  219956. void WebBrowserComponent::resized()
  219957. {
  219958. }
  219959. void WebBrowserComponent::visibilityChanged()
  219960. {
  219961. checkWindowAssociation();
  219962. }
  219963. bool WebBrowserComponent::pageAboutToLoad (const String& url)
  219964. {
  219965. return true;
  219966. }
  219967. #endif
  219968. /*** End of inlined file: juce_linux_WebBrowserComponent.cpp ***/
  219969. #endif
  219970. END_JUCE_NAMESPACE
  219971. #endif
  219972. /*** End of inlined file: juce_linux_NativeCode.cpp ***/
  219973. #endif
  219974. #if JUCE_MAC || JUCE_IPHONE
  219975. /*** Start of inlined file: juce_mac_NativeCode.mm ***/
  219976. /*
  219977. This file wraps together all the mac-specific code, so that
  219978. we can include all the native headers just once, and compile all our
  219979. platform-specific stuff in one big lump, keeping it out of the way of
  219980. the rest of the codebase.
  219981. */
  219982. #if JUCE_MAC || JUCE_IPHONE
  219983. BEGIN_JUCE_NAMESPACE
  219984. #undef Point
  219985. #define JUCE_INCLUDED_FILE 1
  219986. // Now include the actual code files..
  219987. /*** Start of inlined file: juce_mac_ObjCSuffix.h ***/
  219988. /** This suffix is used for naming all Obj-C classes that are used inside juce.
  219989. Because of the flat naming structure used by Obj-C, you can get horrible situations where
  219990. two DLLs are loaded into a host, each of which uses classes with the same names, and these get
  219991. cross-linked so that when you make a call to a class that you thought was private, it ends up
  219992. actually calling into a similarly named class in the other module's address space.
  219993. By changing this macro to a unique value, you ensure that all the obj-C classes in your app
  219994. have unique names, and should avoid this problem.
  219995. If you're using the amalgamated version, you can just set this macro to something unique before
  219996. you include juce_amalgamated.cpp.
  219997. */
  219998. #ifndef JUCE_ObjCExtraSuffix
  219999. #define JUCE_ObjCExtraSuffix 3
  220000. #endif
  220001. #define appendMacro1(a, b, c, d, e) a ## _ ## b ## _ ## c ## _ ## d ## _ ## e
  220002. #define appendMacro2(a, b, c, d, e) appendMacro1(a, b, c, d, e)
  220003. #define MakeObjCClassName(rootName) appendMacro2 (rootName, JUCE_MAJOR_VERSION, JUCE_MINOR_VERSION, JUCE_BUILDNUMBER, JUCE_ObjCExtraSuffix)
  220004. /*** End of inlined file: juce_mac_ObjCSuffix.h ***/
  220005. /*** Start of inlined file: juce_mac_Strings.mm ***/
  220006. // (This file gets included by juce_mac_NativeCode.mm, rather than being
  220007. // compiled on its own).
  220008. #if JUCE_INCLUDED_FILE
  220009. static const String nsStringToJuce (NSString* s)
  220010. {
  220011. return String::fromUTF8 ([s UTF8String]);
  220012. }
  220013. static NSString* juceStringToNS (const String& s)
  220014. {
  220015. return [NSString stringWithUTF8String: s.toUTF8()];
  220016. }
  220017. static const String convertUTF16ToString (const UniChar* utf16)
  220018. {
  220019. String s;
  220020. while (*utf16 != 0)
  220021. s += (juce_wchar) *utf16++;
  220022. return s;
  220023. }
  220024. const String PlatformUtilities::cfStringToJuceString (CFStringRef cfString)
  220025. {
  220026. String result;
  220027. if (cfString != 0)
  220028. {
  220029. CFRange range = { 0, CFStringGetLength (cfString) };
  220030. HeapBlock <UniChar> u (range.length + 1);
  220031. CFStringGetCharacters (cfString, range, u);
  220032. u[range.length] = 0;
  220033. result = convertUTF16ToString (u);
  220034. }
  220035. return result;
  220036. }
  220037. CFStringRef PlatformUtilities::juceStringToCFString (const String& s)
  220038. {
  220039. const int len = s.length();
  220040. HeapBlock <UniChar> temp (len + 2);
  220041. for (int i = 0; i <= len; ++i)
  220042. temp[i] = s[i];
  220043. return CFStringCreateWithCharacters (kCFAllocatorDefault, temp, len);
  220044. }
  220045. const String PlatformUtilities::convertToPrecomposedUnicode (const String& s)
  220046. {
  220047. #if JUCE_IPHONE
  220048. const ScopedAutoReleasePool pool;
  220049. return nsStringToJuce ([juceStringToNS (s) precomposedStringWithCanonicalMapping]);
  220050. #else
  220051. UnicodeMapping map;
  220052. map.unicodeEncoding = CreateTextEncoding (kTextEncodingUnicodeDefault,
  220053. kUnicodeNoSubset,
  220054. kTextEncodingDefaultFormat);
  220055. map.otherEncoding = CreateTextEncoding (kTextEncodingUnicodeDefault,
  220056. kUnicodeCanonicalCompVariant,
  220057. kTextEncodingDefaultFormat);
  220058. map.mappingVersion = kUnicodeUseLatestMapping;
  220059. UnicodeToTextInfo conversionInfo = 0;
  220060. String result;
  220061. if (CreateUnicodeToTextInfo (&map, &conversionInfo) == noErr)
  220062. {
  220063. const int len = s.length();
  220064. HeapBlock <UniChar> tempIn, tempOut;
  220065. tempIn.calloc (len + 2);
  220066. tempOut.calloc (len + 2);
  220067. for (int i = 0; i <= len; ++i)
  220068. tempIn[i] = s[i];
  220069. ByteCount bytesRead = 0;
  220070. ByteCount outputBufferSize = 0;
  220071. if (ConvertFromUnicodeToText (conversionInfo,
  220072. len * sizeof (UniChar), tempIn,
  220073. kUnicodeDefaultDirectionMask,
  220074. 0, 0, 0, 0,
  220075. len * sizeof (UniChar), &bytesRead,
  220076. &outputBufferSize, tempOut) == noErr)
  220077. {
  220078. result.preallocateStorage (bytesRead / sizeof (UniChar) + 2);
  220079. juce_wchar* t = result;
  220080. unsigned int i;
  220081. for (i = 0; i < bytesRead / sizeof (UniChar); ++i)
  220082. t[i] = (juce_wchar) tempOut[i];
  220083. t[i] = 0;
  220084. }
  220085. DisposeUnicodeToTextInfo (&conversionInfo);
  220086. }
  220087. return result;
  220088. #endif
  220089. }
  220090. #if ! JUCE_ONLY_BUILD_CORE_LIBRARY
  220091. void SystemClipboard::copyTextToClipboard (const String& text)
  220092. {
  220093. #if JUCE_IPHONE
  220094. [[UIPasteboard generalPasteboard] setValue: juceStringToNS (text)
  220095. forPasteboardType: @"public.text"];
  220096. #else
  220097. [[NSPasteboard generalPasteboard] declareTypes: [NSArray arrayWithObject: NSStringPboardType]
  220098. owner: nil];
  220099. [[NSPasteboard generalPasteboard] setString: juceStringToNS (text)
  220100. forType: NSStringPboardType];
  220101. #endif
  220102. }
  220103. const String SystemClipboard::getTextFromClipboard()
  220104. {
  220105. #if JUCE_IPHONE
  220106. NSString* text = [[UIPasteboard generalPasteboard] valueForPasteboardType: @"public.text"];
  220107. #else
  220108. NSString* text = [[NSPasteboard generalPasteboard] stringForType: NSStringPboardType];
  220109. #endif
  220110. return text == 0 ? String::empty
  220111. : nsStringToJuce (text);
  220112. }
  220113. #endif
  220114. #endif
  220115. /*** End of inlined file: juce_mac_Strings.mm ***/
  220116. /*** Start of inlined file: juce_mac_SystemStats.mm ***/
  220117. // (This file gets included by juce_mac_NativeCode.mm, rather than being
  220118. // compiled on its own).
  220119. #if JUCE_INCLUDED_FILE
  220120. namespace SystemStatsHelpers
  220121. {
  220122. static int64 highResTimerFrequency = 0;
  220123. static double highResTimerToMillisecRatio = 0;
  220124. #if JUCE_INTEL
  220125. static void juce_getCpuVendor (char* const v) throw()
  220126. {
  220127. int vendor[4];
  220128. zerostruct (vendor);
  220129. int dummy = 0;
  220130. asm ("mov %%ebx, %%esi \n\t"
  220131. "cpuid \n\t"
  220132. "xchg %%esi, %%ebx"
  220133. : "=a" (dummy), "=S" (vendor[0]), "=c" (vendor[2]), "=d" (vendor[1]) : "a" (0));
  220134. memcpy (v, vendor, 16);
  220135. }
  220136. static unsigned int getCPUIDWord (unsigned int& familyModel, unsigned int& extFeatures)
  220137. {
  220138. unsigned int cpu = 0;
  220139. unsigned int ext = 0;
  220140. unsigned int family = 0;
  220141. unsigned int dummy = 0;
  220142. asm ("mov %%ebx, %%esi \n\t"
  220143. "cpuid \n\t"
  220144. "xchg %%esi, %%ebx"
  220145. : "=a" (family), "=S" (ext), "=c" (dummy), "=d" (cpu) : "a" (1));
  220146. familyModel = family;
  220147. extFeatures = ext;
  220148. return cpu;
  220149. }
  220150. struct CPUFlags
  220151. {
  220152. bool hasMMX : 1;
  220153. bool hasSSE : 1;
  220154. bool hasSSE2 : 1;
  220155. bool has3DNow : 1;
  220156. };
  220157. static CPUFlags cpuFlags;
  220158. #endif
  220159. }
  220160. void SystemStats::initialiseStats() throw()
  220161. {
  220162. using namespace SystemStatsHelpers;
  220163. static bool initialised = false;
  220164. if (! initialised)
  220165. {
  220166. initialised = true;
  220167. #if JUCE_MAC
  220168. // extremely annoying: adding this line stops the apple menu items from working. Of
  220169. // course, not adding it means that carbon windows (e.g. in plugins) won't get
  220170. // any events.
  220171. //NSApplicationLoad();
  220172. [NSApplication sharedApplication];
  220173. #endif
  220174. #if JUCE_INTEL
  220175. {
  220176. unsigned int familyModel, extFeatures;
  220177. const unsigned int features = getCPUIDWord (familyModel, extFeatures);
  220178. cpuFlags.hasMMX = ((features & (1 << 23)) != 0);
  220179. cpuFlags.hasSSE = ((features & (1 << 25)) != 0);
  220180. cpuFlags.hasSSE2 = ((features & (1 << 26)) != 0);
  220181. cpuFlags.has3DNow = ((extFeatures & (1 << 31)) != 0);
  220182. }
  220183. #endif
  220184. mach_timebase_info_data_t timebase;
  220185. (void) mach_timebase_info (&timebase);
  220186. highResTimerFrequency = (int64) (1.0e9 * timebase.denom / timebase.numer);
  220187. highResTimerToMillisecRatio = timebase.numer / (1.0e6 * timebase.denom);
  220188. String s (SystemStats::getJUCEVersion());
  220189. rlimit lim;
  220190. getrlimit (RLIMIT_NOFILE, &lim);
  220191. lim.rlim_cur = lim.rlim_max = RLIM_INFINITY;
  220192. setrlimit (RLIMIT_NOFILE, &lim);
  220193. }
  220194. }
  220195. SystemStats::OperatingSystemType SystemStats::getOperatingSystemType() throw()
  220196. {
  220197. return MacOSX;
  220198. }
  220199. const String SystemStats::getOperatingSystemName() throw()
  220200. {
  220201. return "Mac OS X";
  220202. }
  220203. bool SystemStats::isOperatingSystem64Bit() throw()
  220204. {
  220205. #if JUCE_64BIT
  220206. return true;
  220207. #else
  220208. //xxx not sure how to find this out?..
  220209. return false;
  220210. #endif
  220211. }
  220212. int SystemStats::getMemorySizeInMegabytes() throw()
  220213. {
  220214. uint64 mem = 0;
  220215. size_t memSize = sizeof (mem);
  220216. int mib[] = { CTL_HW, HW_MEMSIZE };
  220217. sysctl (mib, 2, &mem, &memSize, 0, 0);
  220218. return (int) (mem / (1024 * 1024));
  220219. }
  220220. bool SystemStats::hasMMX() throw()
  220221. {
  220222. #if JUCE_INTEL
  220223. return SystemStatsHelpers::cpuFlags.hasMMX;
  220224. #else
  220225. return false;
  220226. #endif
  220227. }
  220228. bool SystemStats::hasSSE() throw()
  220229. {
  220230. #if JUCE_INTEL
  220231. return SystemStatsHelpers::cpuFlags.hasSSE;
  220232. #else
  220233. return false;
  220234. #endif
  220235. }
  220236. bool SystemStats::hasSSE2() throw()
  220237. {
  220238. #if JUCE_INTEL
  220239. return SystemStatsHelpers::cpuFlags.hasSSE2;
  220240. #else
  220241. return false;
  220242. #endif
  220243. }
  220244. bool SystemStats::has3DNow() throw()
  220245. {
  220246. #if JUCE_INTEL
  220247. return SystemStatsHelpers::cpuFlags.has3DNow;
  220248. #else
  220249. return false;
  220250. #endif
  220251. }
  220252. const String SystemStats::getCpuVendor() throw()
  220253. {
  220254. #if JUCE_INTEL
  220255. char v [16];
  220256. SystemStatsHelpers::juce_getCpuVendor (v);
  220257. return String (v, 16);
  220258. #else
  220259. return String::empty;
  220260. #endif
  220261. }
  220262. int SystemStats::getCpuSpeedInMegaherz() throw()
  220263. {
  220264. uint64 speedHz = 0;
  220265. size_t speedSize = sizeof (speedHz);
  220266. int mib[] = { CTL_HW, HW_CPU_FREQ };
  220267. sysctl (mib, 2, &speedHz, &speedSize, 0, 0);
  220268. #if JUCE_BIG_ENDIAN
  220269. if (speedSize == 4)
  220270. speedHz >>= 32;
  220271. #endif
  220272. return (int) (speedHz / 1000000);
  220273. }
  220274. int SystemStats::getNumCpus() throw()
  220275. {
  220276. #if JUCE_IPHONE || (MAC_OS_X_VERSION_MIN_REQUIRED >= MAC_OS_X_VERSION_10_5)
  220277. return (int) [[NSProcessInfo processInfo] activeProcessorCount];
  220278. #else
  220279. return MPProcessors();
  220280. #endif
  220281. }
  220282. const String SystemStats::getLogonName()
  220283. {
  220284. return nsStringToJuce (NSUserName());
  220285. }
  220286. const String SystemStats::getFullUserName()
  220287. {
  220288. return nsStringToJuce (NSFullUserName());
  220289. }
  220290. uint32 juce_millisecondsSinceStartup() throw()
  220291. {
  220292. return (uint32) (mach_absolute_time() * SystemStatsHelpers::highResTimerToMillisecRatio);
  220293. }
  220294. double Time::getMillisecondCounterHiRes() throw()
  220295. {
  220296. return mach_absolute_time() * SystemStatsHelpers::highResTimerToMillisecRatio;
  220297. }
  220298. int64 Time::getHighResolutionTicks() throw()
  220299. {
  220300. return (int64) mach_absolute_time();
  220301. }
  220302. int64 Time::getHighResolutionTicksPerSecond() throw()
  220303. {
  220304. return SystemStatsHelpers::highResTimerFrequency;
  220305. }
  220306. int64 SystemStats::getClockCycleCounter() throw()
  220307. {
  220308. return (int64) mach_absolute_time();
  220309. }
  220310. bool Time::setSystemTimeToThisTime() const throw()
  220311. {
  220312. jassertfalse
  220313. return false;
  220314. }
  220315. int SystemStats::getPageSize() throw()
  220316. {
  220317. return (int) NSPageSize();
  220318. }
  220319. void PlatformUtilities::fpuReset()
  220320. {
  220321. }
  220322. #endif
  220323. /*** End of inlined file: juce_mac_SystemStats.mm ***/
  220324. /*** Start of inlined file: juce_mac_Network.mm ***/
  220325. // (This file gets included by juce_mac_NativeCode.mm, rather than being
  220326. // compiled on its own).
  220327. #if JUCE_INCLUDED_FILE
  220328. int SystemStats::getMACAddresses (int64* addresses, int maxNum, const bool littleEndian)
  220329. {
  220330. #ifndef IFT_ETHER
  220331. #define IFT_ETHER 6
  220332. #endif
  220333. ifaddrs* addrs = 0;
  220334. int numResults = 0;
  220335. if (getifaddrs (&addrs) == 0)
  220336. {
  220337. const ifaddrs* cursor = addrs;
  220338. while (cursor != 0 && numResults < maxNum)
  220339. {
  220340. sockaddr_storage* sto = (sockaddr_storage*) cursor->ifa_addr;
  220341. if (sto->ss_family == AF_LINK)
  220342. {
  220343. const sockaddr_dl* const sadd = (const sockaddr_dl*) cursor->ifa_addr;
  220344. if (sadd->sdl_type == IFT_ETHER)
  220345. {
  220346. const uint8* const addr = ((const uint8*) sadd->sdl_data) + sadd->sdl_nlen;
  220347. uint64 a = 0;
  220348. for (int i = 6; --i >= 0;)
  220349. a = (a << 8) | addr [littleEndian ? i : (5 - i)];
  220350. *addresses++ = (int64) a;
  220351. ++numResults;
  220352. }
  220353. }
  220354. cursor = cursor->ifa_next;
  220355. }
  220356. freeifaddrs (addrs);
  220357. }
  220358. return numResults;
  220359. }
  220360. bool PlatformUtilities::launchEmailWithAttachments (const String& targetEmailAddress,
  220361. const String& emailSubject,
  220362. const String& bodyText,
  220363. const StringArray& filesToAttach)
  220364. {
  220365. #if JUCE_IPHONE
  220366. //xxx probably need to use MFMailComposeViewController
  220367. jassertfalse
  220368. return false;
  220369. #else
  220370. const ScopedAutoReleasePool pool;
  220371. String script;
  220372. script << "tell application \"Mail\"\r\n"
  220373. "set newMessage to make new outgoing message with properties {subject:\""
  220374. << emailSubject.replace ("\"", "\\\"")
  220375. << "\", content:\""
  220376. << bodyText.replace ("\"", "\\\"")
  220377. << "\" & return & return}\r\n"
  220378. "tell newMessage\r\n"
  220379. "set visible to true\r\n"
  220380. "set sender to \"sdfsdfsdfewf\"\r\n"
  220381. "make new to recipient at end of to recipients with properties {address:\""
  220382. << targetEmailAddress
  220383. << "\"}\r\n";
  220384. for (int i = 0; i < filesToAttach.size(); ++i)
  220385. {
  220386. script << "tell content\r\n"
  220387. "make new attachment with properties {file name:\""
  220388. << filesToAttach[i].replace ("\"", "\\\"")
  220389. << "\"} at after the last paragraph\r\n"
  220390. "end tell\r\n";
  220391. }
  220392. script << "end tell\r\n"
  220393. "end tell\r\n";
  220394. NSAppleScript* s = [[NSAppleScript alloc]
  220395. initWithSource: juceStringToNS (script)];
  220396. NSDictionary* error = 0;
  220397. const bool ok = [s executeAndReturnError: &error] != nil;
  220398. [s release];
  220399. return ok;
  220400. #endif
  220401. }
  220402. END_JUCE_NAMESPACE
  220403. using namespace JUCE_NAMESPACE;
  220404. #define JuceURLConnection MakeObjCClassName(JuceURLConnection)
  220405. @interface JuceURLConnection : NSObject
  220406. {
  220407. @public
  220408. NSURLRequest* request;
  220409. NSURLConnection* connection;
  220410. NSMutableData* data;
  220411. Thread* runLoopThread;
  220412. bool initialised, hasFailed, hasFinished;
  220413. int position;
  220414. int64 contentLength;
  220415. NSLock* dataLock;
  220416. }
  220417. - (JuceURLConnection*) initWithRequest: (NSURLRequest*) req withCallback: (URL::OpenStreamProgressCallback*) callback withContext: (void*) context;
  220418. - (void) dealloc;
  220419. - (void) connection: (NSURLConnection*) connection didReceiveResponse: (NSURLResponse*) response;
  220420. - (void) connection: (NSURLConnection*) connection didFailWithError: (NSError*) error;
  220421. - (void) connection: (NSURLConnection*) connection didReceiveData: (NSData*) data;
  220422. - (void) connectionDidFinishLoading: (NSURLConnection*) connection;
  220423. - (BOOL) isOpen;
  220424. - (int) read: (char*) dest numBytes: (int) num;
  220425. - (int) readPosition;
  220426. - (void) stop;
  220427. - (void) createConnection;
  220428. @end
  220429. class JuceURLConnectionMessageThread : public Thread
  220430. {
  220431. JuceURLConnection* owner;
  220432. public:
  220433. JuceURLConnectionMessageThread (JuceURLConnection* owner_)
  220434. : Thread ("http connection"),
  220435. owner (owner_)
  220436. {
  220437. }
  220438. ~JuceURLConnectionMessageThread()
  220439. {
  220440. stopThread (10000);
  220441. }
  220442. void run()
  220443. {
  220444. [owner createConnection];
  220445. while (! threadShouldExit())
  220446. {
  220447. const ScopedAutoReleasePool pool;
  220448. [[NSRunLoop currentRunLoop] runUntilDate: [NSDate dateWithTimeIntervalSinceNow: 0.01]];
  220449. }
  220450. }
  220451. };
  220452. @implementation JuceURLConnection
  220453. - (JuceURLConnection*) initWithRequest: (NSURLRequest*) req
  220454. withCallback: (URL::OpenStreamProgressCallback*) callback
  220455. withContext: (void*) context;
  220456. {
  220457. [super init];
  220458. request = req;
  220459. [request retain];
  220460. data = [[NSMutableData data] retain];
  220461. dataLock = [[NSLock alloc] init];
  220462. connection = 0;
  220463. initialised = false;
  220464. hasFailed = false;
  220465. hasFinished = false;
  220466. contentLength = -1;
  220467. runLoopThread = new JuceURLConnectionMessageThread (self);
  220468. runLoopThread->startThread();
  220469. while (runLoopThread->isThreadRunning() && ! initialised)
  220470. {
  220471. if (callback != 0)
  220472. callback (context, -1, (int) [[request HTTPBody] length]);
  220473. Thread::sleep (1);
  220474. }
  220475. return self;
  220476. }
  220477. - (void) dealloc
  220478. {
  220479. [self stop];
  220480. deleteAndZero (runLoopThread);
  220481. [connection release];
  220482. [data release];
  220483. [dataLock release];
  220484. [request release];
  220485. [super dealloc];
  220486. }
  220487. - (void) createConnection
  220488. {
  220489. connection = [[NSURLConnection alloc] initWithRequest: request
  220490. delegate: [self retain]];
  220491. if (connection == nil)
  220492. runLoopThread->signalThreadShouldExit();
  220493. }
  220494. - (void) connection: (NSURLConnection*) connection didReceiveResponse: (NSURLResponse*) response
  220495. {
  220496. [dataLock lock];
  220497. [data setLength: 0];
  220498. [dataLock unlock];
  220499. initialised = true;
  220500. contentLength = [response expectedContentLength];
  220501. }
  220502. - (void) connection: (NSURLConnection*) connection didFailWithError: (NSError*) error
  220503. {
  220504. DBG (nsStringToJuce ([error description]));
  220505. hasFailed = true;
  220506. initialised = true;
  220507. if (runLoopThread != 0)
  220508. runLoopThread->signalThreadShouldExit();
  220509. }
  220510. - (void) connection: (NSURLConnection*) connection didReceiveData: (NSData*) newData
  220511. {
  220512. [dataLock lock];
  220513. [data appendData: newData];
  220514. [dataLock unlock];
  220515. initialised = true;
  220516. }
  220517. - (void) connectionDidFinishLoading: (NSURLConnection*) connection
  220518. {
  220519. hasFinished = true;
  220520. initialised = true;
  220521. if (runLoopThread != 0)
  220522. runLoopThread->signalThreadShouldExit();
  220523. }
  220524. - (BOOL) isOpen
  220525. {
  220526. return connection != 0 && ! hasFailed;
  220527. }
  220528. - (int) readPosition
  220529. {
  220530. return position;
  220531. }
  220532. - (int) read: (char*) dest numBytes: (int) numNeeded
  220533. {
  220534. int numDone = 0;
  220535. while (numNeeded > 0)
  220536. {
  220537. int available = jmin (numNeeded, (int) [data length]);
  220538. if (available > 0)
  220539. {
  220540. [dataLock lock];
  220541. [data getBytes: dest length: available];
  220542. [data replaceBytesInRange: NSMakeRange (0, available) withBytes: nil length: 0];
  220543. [dataLock unlock];
  220544. numDone += available;
  220545. numNeeded -= available;
  220546. dest += available;
  220547. }
  220548. else
  220549. {
  220550. if (hasFailed || hasFinished)
  220551. break;
  220552. Thread::sleep (1);
  220553. }
  220554. }
  220555. position += numDone;
  220556. return numDone;
  220557. }
  220558. - (void) stop
  220559. {
  220560. [connection cancel];
  220561. if (runLoopThread != 0)
  220562. runLoopThread->stopThread (10000);
  220563. }
  220564. @end
  220565. BEGIN_JUCE_NAMESPACE
  220566. void* juce_openInternetFile (const String& url,
  220567. const String& headers,
  220568. const MemoryBlock& postData,
  220569. const bool isPost,
  220570. URL::OpenStreamProgressCallback* callback,
  220571. void* callbackContext,
  220572. int timeOutMs)
  220573. {
  220574. const ScopedAutoReleasePool pool;
  220575. NSMutableURLRequest* req = [NSMutableURLRequest
  220576. requestWithURL: [NSURL URLWithString: juceStringToNS (url)]
  220577. cachePolicy: NSURLRequestUseProtocolCachePolicy
  220578. timeoutInterval: timeOutMs <= 0 ? 60.0 : (timeOutMs / 1000.0)];
  220579. if (req == nil)
  220580. return 0;
  220581. [req setHTTPMethod: isPost ? @"POST" : @"GET"];
  220582. //[req setCachePolicy: NSURLRequestReloadIgnoringLocalAndRemoteCacheData];
  220583. StringArray headerLines;
  220584. headerLines.addLines (headers);
  220585. headerLines.removeEmptyStrings (true);
  220586. for (int i = 0; i < headerLines.size(); ++i)
  220587. {
  220588. const String key (headerLines[i].upToFirstOccurrenceOf (":", false, false).trim());
  220589. const String value (headerLines[i].fromFirstOccurrenceOf (":", false, false).trim());
  220590. if (key.isNotEmpty() && value.isNotEmpty())
  220591. [req addValue: juceStringToNS (value) forHTTPHeaderField: juceStringToNS (key)];
  220592. }
  220593. if (isPost && postData.getSize() > 0)
  220594. {
  220595. [req setHTTPBody: [NSData dataWithBytes: postData.getData()
  220596. length: postData.getSize()]];
  220597. }
  220598. JuceURLConnection* const s = [[JuceURLConnection alloc] initWithRequest: req
  220599. withCallback: callback
  220600. withContext: callbackContext];
  220601. if ([s isOpen])
  220602. return s;
  220603. [s release];
  220604. return 0;
  220605. }
  220606. void juce_closeInternetFile (void* handle)
  220607. {
  220608. JuceURLConnection* const s = (JuceURLConnection*) handle;
  220609. if (s != 0)
  220610. {
  220611. const ScopedAutoReleasePool pool;
  220612. [s stop];
  220613. [s release];
  220614. }
  220615. }
  220616. int juce_readFromInternetFile (void* handle, void* buffer, int bytesToRead)
  220617. {
  220618. JuceURLConnection* const s = (JuceURLConnection*) handle;
  220619. if (s != 0)
  220620. {
  220621. const ScopedAutoReleasePool pool;
  220622. return [s read: (char*) buffer numBytes: bytesToRead];
  220623. }
  220624. return 0;
  220625. }
  220626. int64 juce_getInternetFileContentLength (void* handle)
  220627. {
  220628. JuceURLConnection* const s = (JuceURLConnection*) handle;
  220629. if (s != 0)
  220630. return s->contentLength;
  220631. return -1;
  220632. }
  220633. int juce_seekInInternetFile (void* handle, int newPosition)
  220634. {
  220635. JuceURLConnection* const s = (JuceURLConnection*) handle;
  220636. if (s != 0)
  220637. return [s readPosition];
  220638. return 0;
  220639. }
  220640. #endif
  220641. /*** End of inlined file: juce_mac_Network.mm ***/
  220642. /*** Start of inlined file: juce_posix_NamedPipe.cpp ***/
  220643. // (This file gets included by juce_mac_NativeCode.mm, rather than being
  220644. // compiled on its own).
  220645. #if JUCE_INCLUDED_FILE
  220646. struct NamedPipeInternal
  220647. {
  220648. String pipeInName, pipeOutName;
  220649. int pipeIn, pipeOut;
  220650. bool volatile createdPipe, blocked, stopReadOperation;
  220651. static void signalHandler (int) {}
  220652. };
  220653. void NamedPipe::cancelPendingReads()
  220654. {
  220655. while (internal != 0 && ((NamedPipeInternal*) internal)->blocked)
  220656. {
  220657. NamedPipeInternal* const intern = (NamedPipeInternal*) internal;
  220658. intern->stopReadOperation = true;
  220659. char buffer [1] = { 0 };
  220660. int bytesWritten = (int) ::write (intern->pipeIn, buffer, 1);
  220661. (void) bytesWritten;
  220662. int timeout = 2000;
  220663. while (intern->blocked && --timeout >= 0)
  220664. Thread::sleep (2);
  220665. intern->stopReadOperation = false;
  220666. }
  220667. }
  220668. void NamedPipe::close()
  220669. {
  220670. NamedPipeInternal* const intern = (NamedPipeInternal*) internal;
  220671. if (intern != 0)
  220672. {
  220673. internal = 0;
  220674. if (intern->pipeIn != -1)
  220675. ::close (intern->pipeIn);
  220676. if (intern->pipeOut != -1)
  220677. ::close (intern->pipeOut);
  220678. if (intern->createdPipe)
  220679. {
  220680. unlink (intern->pipeInName.toUTF8());
  220681. unlink (intern->pipeOutName.toUTF8());
  220682. }
  220683. delete intern;
  220684. }
  220685. }
  220686. bool NamedPipe::openInternal (const String& pipeName, const bool createPipe)
  220687. {
  220688. close();
  220689. NamedPipeInternal* const intern = new NamedPipeInternal();
  220690. internal = intern;
  220691. intern->createdPipe = createPipe;
  220692. intern->blocked = false;
  220693. intern->stopReadOperation = false;
  220694. signal (SIGPIPE, NamedPipeInternal::signalHandler);
  220695. siginterrupt (SIGPIPE, 1);
  220696. const String pipePath ("/tmp/" + File::createLegalFileName (pipeName));
  220697. intern->pipeInName = pipePath + "_in";
  220698. intern->pipeOutName = pipePath + "_out";
  220699. intern->pipeIn = -1;
  220700. intern->pipeOut = -1;
  220701. if (createPipe)
  220702. {
  220703. if ((mkfifo (intern->pipeInName.toUTF8(), 0666) && errno != EEXIST)
  220704. || (mkfifo (intern->pipeOutName.toUTF8(), 0666) && errno != EEXIST))
  220705. {
  220706. delete intern;
  220707. internal = 0;
  220708. return false;
  220709. }
  220710. }
  220711. return true;
  220712. }
  220713. int NamedPipe::read (void* destBuffer, int maxBytesToRead, int /*timeOutMilliseconds*/)
  220714. {
  220715. int bytesRead = -1;
  220716. NamedPipeInternal* const intern = (NamedPipeInternal*) internal;
  220717. if (intern != 0)
  220718. {
  220719. intern->blocked = true;
  220720. if (intern->pipeIn == -1)
  220721. {
  220722. if (intern->createdPipe)
  220723. intern->pipeIn = ::open (intern->pipeInName.toUTF8(), O_RDWR);
  220724. else
  220725. intern->pipeIn = ::open (intern->pipeOutName.toUTF8(), O_RDWR);
  220726. if (intern->pipeIn == -1)
  220727. {
  220728. intern->blocked = false;
  220729. return -1;
  220730. }
  220731. }
  220732. bytesRead = 0;
  220733. char* p = (char*) destBuffer;
  220734. while (bytesRead < maxBytesToRead)
  220735. {
  220736. const int bytesThisTime = maxBytesToRead - bytesRead;
  220737. const int numRead = (int) ::read (intern->pipeIn, p, bytesThisTime);
  220738. if (numRead <= 0 || intern->stopReadOperation)
  220739. {
  220740. bytesRead = -1;
  220741. break;
  220742. }
  220743. bytesRead += numRead;
  220744. p += bytesRead;
  220745. }
  220746. intern->blocked = false;
  220747. }
  220748. return bytesRead;
  220749. }
  220750. int NamedPipe::write (const void* sourceBuffer, int numBytesToWrite, int timeOutMilliseconds)
  220751. {
  220752. int bytesWritten = -1;
  220753. NamedPipeInternal* const intern = (NamedPipeInternal*) internal;
  220754. if (intern != 0)
  220755. {
  220756. if (intern->pipeOut == -1)
  220757. {
  220758. if (intern->createdPipe)
  220759. intern->pipeOut = ::open (intern->pipeOutName.toUTF8(), O_WRONLY);
  220760. else
  220761. intern->pipeOut = ::open (intern->pipeInName.toUTF8(), O_WRONLY);
  220762. if (intern->pipeOut == -1)
  220763. {
  220764. return -1;
  220765. }
  220766. }
  220767. const char* p = (const char*) sourceBuffer;
  220768. bytesWritten = 0;
  220769. const uint32 timeOutTime = Time::getMillisecondCounter() + timeOutMilliseconds;
  220770. while (bytesWritten < numBytesToWrite
  220771. && (timeOutMilliseconds < 0 || Time::getMillisecondCounter() < timeOutTime))
  220772. {
  220773. const int bytesThisTime = numBytesToWrite - bytesWritten;
  220774. const int numWritten = (int) ::write (intern->pipeOut, p, bytesThisTime);
  220775. if (numWritten <= 0)
  220776. {
  220777. bytesWritten = -1;
  220778. break;
  220779. }
  220780. bytesWritten += numWritten;
  220781. p += bytesWritten;
  220782. }
  220783. }
  220784. return bytesWritten;
  220785. }
  220786. #endif
  220787. /*** End of inlined file: juce_posix_NamedPipe.cpp ***/
  220788. /*** Start of inlined file: juce_mac_Threads.mm ***/
  220789. // (This file gets included by juce_mac_NativeCode.mm, rather than being
  220790. // compiled on its own).
  220791. #if JUCE_INCLUDED_FILE
  220792. /*
  220793. Note that a lot of methods that you'd expect to find in this file actually
  220794. live in juce_posix_SharedCode.h!
  220795. */
  220796. void JUCE_API juce_threadEntryPoint (void*);
  220797. void* threadEntryProc (void* userData)
  220798. {
  220799. const ScopedAutoReleasePool pool;
  220800. juce_threadEntryPoint (userData);
  220801. return 0;
  220802. }
  220803. void* juce_createThread (void* userData)
  220804. {
  220805. pthread_t handle = 0;
  220806. if (pthread_create (&handle, 0, threadEntryProc, userData) == 0)
  220807. {
  220808. pthread_detach (handle);
  220809. return (void*) handle;
  220810. }
  220811. return 0;
  220812. }
  220813. void juce_killThread (void* handle)
  220814. {
  220815. if (handle != 0)
  220816. pthread_cancel ((pthread_t) handle);
  220817. }
  220818. void juce_setCurrentThreadName (const String& /*name*/)
  220819. {
  220820. }
  220821. bool juce_setThreadPriority (void* handle, int priority)
  220822. {
  220823. if (handle == 0)
  220824. handle = (void*) pthread_self();
  220825. struct sched_param param;
  220826. int policy;
  220827. pthread_getschedparam ((pthread_t) handle, &policy, &param);
  220828. param.sched_priority = jlimit (1, 127, 1 + (priority * 126) / 11);
  220829. return pthread_setschedparam ((pthread_t) handle, policy, &param) == 0;
  220830. }
  220831. Thread::ThreadID Thread::getCurrentThreadId()
  220832. {
  220833. return static_cast <ThreadID> (pthread_self());
  220834. }
  220835. void Thread::yield()
  220836. {
  220837. sched_yield();
  220838. }
  220839. void Thread::setCurrentThreadAffinityMask (const uint32 affinityMask)
  220840. {
  220841. // xxx
  220842. jassertfalse
  220843. }
  220844. bool Process::isForegroundProcess()
  220845. {
  220846. #if JUCE_MAC
  220847. return [NSApp isActive];
  220848. #else
  220849. return true; // xxx change this if more than one app is ever possible on the iPhone!
  220850. #endif
  220851. }
  220852. void Process::raisePrivilege()
  220853. {
  220854. jassertfalse
  220855. }
  220856. void Process::lowerPrivilege()
  220857. {
  220858. jassertfalse
  220859. }
  220860. void Process::terminate()
  220861. {
  220862. exit (0);
  220863. }
  220864. void Process::setPriority (ProcessPriority p)
  220865. {
  220866. // xxx
  220867. }
  220868. #endif
  220869. /*** End of inlined file: juce_mac_Threads.mm ***/
  220870. /*** Start of inlined file: juce_posix_SharedCode.h ***/
  220871. /*
  220872. This file contains posix routines that are common to both the Linux and Mac builds.
  220873. It gets included directly in the cpp files for these platforms.
  220874. */
  220875. CriticalSection::CriticalSection() throw()
  220876. {
  220877. pthread_mutexattr_t atts;
  220878. pthread_mutexattr_init (&atts);
  220879. pthread_mutexattr_settype (&atts, PTHREAD_MUTEX_RECURSIVE);
  220880. pthread_mutex_init (&internal, &atts);
  220881. }
  220882. CriticalSection::~CriticalSection() throw()
  220883. {
  220884. pthread_mutex_destroy (&internal);
  220885. }
  220886. void CriticalSection::enter() const throw()
  220887. {
  220888. pthread_mutex_lock (&internal);
  220889. }
  220890. bool CriticalSection::tryEnter() const throw()
  220891. {
  220892. return pthread_mutex_trylock (&internal) == 0;
  220893. }
  220894. void CriticalSection::exit() const throw()
  220895. {
  220896. pthread_mutex_unlock (&internal);
  220897. }
  220898. class WaitableEventImpl
  220899. {
  220900. public:
  220901. WaitableEventImpl (const bool manualReset_)
  220902. : triggered (false),
  220903. manualReset (manualReset_)
  220904. {
  220905. pthread_cond_init (&condition, 0);
  220906. pthread_mutex_init (&mutex, 0);
  220907. }
  220908. ~WaitableEventImpl()
  220909. {
  220910. pthread_cond_destroy (&condition);
  220911. pthread_mutex_destroy (&mutex);
  220912. }
  220913. bool wait (const int timeOutMillisecs) throw()
  220914. {
  220915. pthread_mutex_lock (&mutex);
  220916. if (! triggered)
  220917. {
  220918. if (timeOutMillisecs < 0)
  220919. {
  220920. do
  220921. {
  220922. pthread_cond_wait (&condition, &mutex);
  220923. }
  220924. while (! triggered);
  220925. }
  220926. else
  220927. {
  220928. struct timeval now;
  220929. gettimeofday (&now, 0);
  220930. struct timespec time;
  220931. time.tv_sec = now.tv_sec + (timeOutMillisecs / 1000);
  220932. time.tv_nsec = (now.tv_usec + ((timeOutMillisecs % 1000) * 1000)) * 1000;
  220933. if (time.tv_nsec >= 1000000000)
  220934. {
  220935. time.tv_nsec -= 1000000000;
  220936. time.tv_sec++;
  220937. }
  220938. do
  220939. {
  220940. if (pthread_cond_timedwait (&condition, &mutex, &time) == ETIMEDOUT)
  220941. {
  220942. pthread_mutex_unlock (&mutex);
  220943. return false;
  220944. }
  220945. }
  220946. while (! triggered);
  220947. }
  220948. }
  220949. if (! manualReset)
  220950. triggered = false;
  220951. pthread_mutex_unlock (&mutex);
  220952. return true;
  220953. }
  220954. void signal() throw()
  220955. {
  220956. pthread_mutex_lock (&mutex);
  220957. triggered = true;
  220958. pthread_cond_broadcast (&condition);
  220959. pthread_mutex_unlock (&mutex);
  220960. }
  220961. void reset() throw()
  220962. {
  220963. pthread_mutex_lock (&mutex);
  220964. triggered = false;
  220965. pthread_mutex_unlock (&mutex);
  220966. }
  220967. private:
  220968. pthread_cond_t condition;
  220969. pthread_mutex_t mutex;
  220970. bool triggered;
  220971. const bool manualReset;
  220972. WaitableEventImpl (const WaitableEventImpl&);
  220973. WaitableEventImpl& operator= (const WaitableEventImpl&);
  220974. };
  220975. WaitableEvent::WaitableEvent (const bool manualReset) throw()
  220976. : internal (new WaitableEventImpl (manualReset))
  220977. {
  220978. }
  220979. WaitableEvent::~WaitableEvent() throw()
  220980. {
  220981. delete static_cast <WaitableEventImpl*> (internal);
  220982. }
  220983. bool WaitableEvent::wait (const int timeOutMillisecs) const throw()
  220984. {
  220985. return static_cast <WaitableEventImpl*> (internal)->wait (timeOutMillisecs);
  220986. }
  220987. void WaitableEvent::signal() const throw()
  220988. {
  220989. static_cast <WaitableEventImpl*> (internal)->signal();
  220990. }
  220991. void WaitableEvent::reset() const throw()
  220992. {
  220993. static_cast <WaitableEventImpl*> (internal)->reset();
  220994. }
  220995. void JUCE_CALLTYPE Thread::sleep (int millisecs)
  220996. {
  220997. struct timespec time;
  220998. time.tv_sec = millisecs / 1000;
  220999. time.tv_nsec = (millisecs % 1000) * 1000000;
  221000. nanosleep (&time, 0);
  221001. }
  221002. const juce_wchar File::separator = '/';
  221003. const String File::separatorString ("/");
  221004. const File File::getCurrentWorkingDirectory()
  221005. {
  221006. HeapBlock<char> heapBuffer;
  221007. char localBuffer [1024];
  221008. char* cwd = getcwd (localBuffer, sizeof (localBuffer) - 1);
  221009. int bufferSize = 4096;
  221010. while (cwd == 0 && errno == ERANGE)
  221011. {
  221012. heapBuffer.malloc (bufferSize);
  221013. cwd = getcwd (heapBuffer, bufferSize - 1);
  221014. bufferSize += 1024;
  221015. }
  221016. return File (String::fromUTF8 (cwd));
  221017. }
  221018. bool File::setAsCurrentWorkingDirectory() const
  221019. {
  221020. return chdir (getFullPathName().toUTF8()) == 0;
  221021. }
  221022. static bool juce_stat (const String& fileName, struct stat& info)
  221023. {
  221024. return fileName.isNotEmpty()
  221025. && (stat (fileName.toUTF8(), &info) == 0);
  221026. }
  221027. bool File::isDirectory() const
  221028. {
  221029. struct stat info;
  221030. return fullPath.isEmpty()
  221031. || (juce_stat (fullPath, info) && ((info.st_mode & S_IFDIR) != 0));
  221032. }
  221033. bool File::exists() const
  221034. {
  221035. return fullPath.isNotEmpty()
  221036. && access (fullPath.toUTF8(), F_OK) == 0;
  221037. }
  221038. bool File::existsAsFile() const
  221039. {
  221040. return exists() && ! isDirectory();
  221041. }
  221042. int64 File::getSize() const
  221043. {
  221044. struct stat info;
  221045. return juce_stat (fullPath, info) ? info.st_size : 0;
  221046. }
  221047. bool File::hasWriteAccess() const
  221048. {
  221049. if (exists())
  221050. return access (fullPath.toUTF8(), W_OK) == 0;
  221051. if ((! isDirectory()) && fullPath.containsChar (separator))
  221052. return getParentDirectory().hasWriteAccess();
  221053. return false;
  221054. }
  221055. bool File::setFileReadOnlyInternal (const bool shouldBeReadOnly) const
  221056. {
  221057. struct stat info;
  221058. const int res = stat (fullPath.toUTF8(), &info);
  221059. if (res != 0)
  221060. return false;
  221061. info.st_mode &= 0777; // Just permissions
  221062. if (shouldBeReadOnly)
  221063. info.st_mode &= ~(S_IWUSR | S_IWGRP | S_IWOTH);
  221064. else
  221065. // Give everybody write permission?
  221066. info.st_mode |= S_IWUSR | S_IWGRP | S_IWOTH;
  221067. return chmod (fullPath.toUTF8(), info.st_mode) == 0;
  221068. }
  221069. void File::getFileTimesInternal (int64& modificationTime, int64& accessTime, int64& creationTime) const
  221070. {
  221071. modificationTime = 0;
  221072. accessTime = 0;
  221073. creationTime = 0;
  221074. struct stat info;
  221075. const int res = stat (fullPath.toUTF8(), &info);
  221076. if (res == 0)
  221077. {
  221078. modificationTime = (int64) info.st_mtime * 1000;
  221079. accessTime = (int64) info.st_atime * 1000;
  221080. creationTime = (int64) info.st_ctime * 1000;
  221081. }
  221082. }
  221083. bool File::setFileTimesInternal (int64 modificationTime, int64 accessTime, int64 creationTime) const
  221084. {
  221085. struct utimbuf times;
  221086. times.actime = (time_t) (accessTime / 1000);
  221087. times.modtime = (time_t) (modificationTime / 1000);
  221088. return utime (fullPath.toUTF8(), &times) == 0;
  221089. }
  221090. bool File::deleteFile() const
  221091. {
  221092. if (! exists())
  221093. return true;
  221094. else if (isDirectory())
  221095. return rmdir (fullPath.toUTF8()) == 0;
  221096. else
  221097. return remove (fullPath.toUTF8()) == 0;
  221098. }
  221099. bool File::moveInternal (const File& dest) const
  221100. {
  221101. if (rename (fullPath.toUTF8(), dest.getFullPathName().toUTF8()) == 0)
  221102. return true;
  221103. if (hasWriteAccess() && copyInternal (dest))
  221104. {
  221105. if (deleteFile())
  221106. return true;
  221107. dest.deleteFile();
  221108. }
  221109. return false;
  221110. }
  221111. void File::createDirectoryInternal (const String& fileName) const
  221112. {
  221113. mkdir (fileName.toUTF8(), 0777);
  221114. }
  221115. void* juce_fileOpen (const File& file, bool forWriting)
  221116. {
  221117. int flags = O_RDONLY;
  221118. if (forWriting)
  221119. {
  221120. if (file.exists())
  221121. {
  221122. const int f = open (file.getFullPathName().toUTF8(), O_RDWR, 00644);
  221123. if (f != -1)
  221124. lseek (f, 0, SEEK_END);
  221125. return (void*) f;
  221126. }
  221127. else
  221128. {
  221129. flags = O_RDWR + O_CREAT;
  221130. }
  221131. }
  221132. return (void*) open (file.getFullPathName().toUTF8(), flags, 00644);
  221133. }
  221134. void juce_fileClose (void* handle)
  221135. {
  221136. if (handle != 0)
  221137. close ((int) (pointer_sized_int) handle);
  221138. }
  221139. int juce_fileRead (void* handle, void* buffer, int size)
  221140. {
  221141. if (handle != 0)
  221142. return jmax (0, (int) read ((int) (pointer_sized_int) handle, buffer, size));
  221143. return 0;
  221144. }
  221145. int juce_fileWrite (void* handle, const void* buffer, int size)
  221146. {
  221147. if (handle != 0)
  221148. return (int) write ((int) (pointer_sized_int) handle, buffer, size);
  221149. return 0;
  221150. }
  221151. int64 juce_fileSetPosition (void* handle, int64 pos)
  221152. {
  221153. if (handle != 0 && lseek ((int) (pointer_sized_int) handle, pos, SEEK_SET) == pos)
  221154. return pos;
  221155. return -1;
  221156. }
  221157. int64 FileOutputStream::getPositionInternal() const
  221158. {
  221159. if (fileHandle != 0)
  221160. return lseek ((int) (pointer_sized_int) fileHandle, 0, SEEK_CUR);
  221161. return -1;
  221162. }
  221163. void FileOutputStream::flushInternal()
  221164. {
  221165. if (fileHandle != 0)
  221166. fsync ((int) (pointer_sized_int) fileHandle);
  221167. }
  221168. const File juce_getExecutableFile()
  221169. {
  221170. Dl_info exeInfo;
  221171. dladdr ((const void*) juce_getExecutableFile, &exeInfo);
  221172. return File::getCurrentWorkingDirectory().getChildFile (String::fromUTF8 (exeInfo.dli_fname));
  221173. }
  221174. // if this file doesn't exist, find a parent of it that does..
  221175. static bool juce_doStatFS (File f, struct statfs& result)
  221176. {
  221177. for (int i = 5; --i >= 0;)
  221178. {
  221179. if (f.exists())
  221180. break;
  221181. f = f.getParentDirectory();
  221182. }
  221183. return statfs (f.getFullPathName().toUTF8(), &result) == 0;
  221184. }
  221185. int64 File::getBytesFreeOnVolume() const
  221186. {
  221187. struct statfs buf;
  221188. if (juce_doStatFS (*this, buf))
  221189. return (int64) buf.f_bsize * (int64) buf.f_bavail; // Note: this returns space available to non-super user
  221190. return 0;
  221191. }
  221192. int64 File::getVolumeTotalSize() const
  221193. {
  221194. struct statfs buf;
  221195. if (juce_doStatFS (*this, buf))
  221196. return (int64) buf.f_bsize * (int64) buf.f_blocks;
  221197. return 0;
  221198. }
  221199. const String File::getVolumeLabel() const
  221200. {
  221201. #if JUCE_MAC
  221202. struct VolAttrBuf
  221203. {
  221204. u_int32_t length;
  221205. attrreference_t mountPointRef;
  221206. char mountPointSpace [MAXPATHLEN];
  221207. } attrBuf;
  221208. struct attrlist attrList;
  221209. zerostruct (attrList);
  221210. attrList.bitmapcount = ATTR_BIT_MAP_COUNT;
  221211. attrList.volattr = ATTR_VOL_INFO | ATTR_VOL_NAME;
  221212. File f (*this);
  221213. for (;;)
  221214. {
  221215. if (getattrlist (f.getFullPathName().toUTF8(), &attrList, &attrBuf, sizeof (attrBuf), 0) == 0)
  221216. return String::fromUTF8 (((const char*) &attrBuf.mountPointRef) + attrBuf.mountPointRef.attr_dataoffset,
  221217. (int) attrBuf.mountPointRef.attr_length);
  221218. const File parent (f.getParentDirectory());
  221219. if (f == parent)
  221220. break;
  221221. f = parent;
  221222. }
  221223. #endif
  221224. return String::empty;
  221225. }
  221226. int File::getVolumeSerialNumber() const
  221227. {
  221228. return 0; // xxx
  221229. }
  221230. void juce_runSystemCommand (const String& command)
  221231. {
  221232. int result = system (command.toUTF8());
  221233. (void) result;
  221234. }
  221235. const String juce_getOutputFromCommand (const String& command)
  221236. {
  221237. // slight bodge here, as we just pipe the output into a temp file and read it...
  221238. const File tempFile (File::getSpecialLocation (File::tempDirectory)
  221239. .getNonexistentChildFile (String::toHexString (Random::getSystemRandom().nextInt()), ".tmp", false));
  221240. juce_runSystemCommand (command + " > " + tempFile.getFullPathName());
  221241. String result (tempFile.loadFileAsString());
  221242. tempFile.deleteFile();
  221243. return result;
  221244. }
  221245. class InterProcessLock::Pimpl
  221246. {
  221247. public:
  221248. Pimpl (const String& name, const int timeOutMillisecs)
  221249. : handle (0), refCount (1)
  221250. {
  221251. #if JUCE_MAC
  221252. // (don't use getSpecialLocation() to avoid the temp folder being different for each app)
  221253. const File temp (File ("~/Library/Caches/Juce").getChildFile (name));
  221254. #else
  221255. const File temp (File::getSpecialLocation (File::tempDirectory).getChildFile (name));
  221256. #endif
  221257. temp.create();
  221258. handle = open (temp.getFullPathName().toUTF8(), O_RDWR);
  221259. if (handle != 0)
  221260. {
  221261. struct flock fl;
  221262. zerostruct (fl);
  221263. fl.l_whence = SEEK_SET;
  221264. fl.l_type = F_WRLCK;
  221265. const int64 endTime = Time::currentTimeMillis() + timeOutMillisecs;
  221266. for (;;)
  221267. {
  221268. const int result = fcntl (handle, F_SETLK, &fl);
  221269. if (result >= 0)
  221270. return;
  221271. if (errno != EINTR)
  221272. {
  221273. if (timeOutMillisecs == 0
  221274. || (timeOutMillisecs > 0 && Time::currentTimeMillis() >= endTime))
  221275. break;
  221276. Thread::sleep (10);
  221277. }
  221278. }
  221279. }
  221280. closeFile();
  221281. }
  221282. ~Pimpl()
  221283. {
  221284. closeFile();
  221285. }
  221286. void closeFile()
  221287. {
  221288. if (handle != 0)
  221289. {
  221290. struct flock fl;
  221291. zerostruct (fl);
  221292. fl.l_whence = SEEK_SET;
  221293. fl.l_type = F_UNLCK;
  221294. while (! (fcntl (handle, F_SETLKW, &fl) >= 0 || errno != EINTR))
  221295. {}
  221296. close (handle);
  221297. handle = 0;
  221298. }
  221299. }
  221300. int handle, refCount;
  221301. };
  221302. InterProcessLock::InterProcessLock (const String& name_)
  221303. : name (name_)
  221304. {
  221305. }
  221306. InterProcessLock::~InterProcessLock()
  221307. {
  221308. }
  221309. bool InterProcessLock::enter (const int timeOutMillisecs)
  221310. {
  221311. const ScopedLock sl (lock);
  221312. if (pimpl == 0)
  221313. {
  221314. pimpl = new Pimpl (name, timeOutMillisecs);
  221315. if (pimpl->handle == 0)
  221316. pimpl = 0;
  221317. }
  221318. else
  221319. {
  221320. pimpl->refCount++;
  221321. }
  221322. return pimpl != 0;
  221323. }
  221324. void InterProcessLock::exit()
  221325. {
  221326. const ScopedLock sl (lock);
  221327. // Trying to release the lock too many times!
  221328. jassert (pimpl != 0);
  221329. if (pimpl != 0 && --(pimpl->refCount) == 0)
  221330. pimpl = 0;
  221331. }
  221332. /*** End of inlined file: juce_posix_SharedCode.h ***/
  221333. /*** Start of inlined file: juce_mac_Files.mm ***/
  221334. // (This file gets included by juce_mac_NativeCode.mm, rather than being
  221335. // compiled on its own).
  221336. #if JUCE_INCLUDED_FILE
  221337. /*
  221338. Note that a lot of methods that you'd expect to find in this file actually
  221339. live in juce_posix_SharedCode.h!
  221340. */
  221341. bool File::copyInternal (const File& dest) const
  221342. {
  221343. const ScopedAutoReleasePool pool;
  221344. NSFileManager* fm = [NSFileManager defaultManager];
  221345. return [fm fileExistsAtPath: juceStringToNS (fullPath)]
  221346. #if defined (MAC_OS_X_VERSION_10_6) && MAC_OS_X_VERSION_MAX_ALLOWED >= MAC_OS_X_VERSION_10_6
  221347. && [fm copyItemAtPath: juceStringToNS (fullPath)
  221348. toPath: juceStringToNS (dest.getFullPathName())
  221349. error: nil];
  221350. #else
  221351. && [fm copyPath: juceStringToNS (fullPath)
  221352. toPath: juceStringToNS (dest.getFullPathName())
  221353. handler: nil];
  221354. #endif
  221355. }
  221356. void File::findFileSystemRoots (Array<File>& destArray)
  221357. {
  221358. destArray.add (File ("/"));
  221359. }
  221360. static bool isFileOnDriveType (const File& f, const char** types)
  221361. {
  221362. struct statfs buf;
  221363. if (juce_doStatFS (f, buf))
  221364. {
  221365. const String type (buf.f_fstypename);
  221366. while (*types != 0)
  221367. if (type.equalsIgnoreCase (*types++))
  221368. return true;
  221369. }
  221370. return false;
  221371. }
  221372. bool File::isOnCDRomDrive() const
  221373. {
  221374. static const char* const cdTypes[] = { "cd9660", "cdfs", "cddafs", "udf", 0 };
  221375. return isFileOnDriveType (*this, (const char**) cdTypes);
  221376. }
  221377. bool File::isOnHardDisk() const
  221378. {
  221379. static const char* const nonHDTypes[] = { "nfs", "smbfs", "ramfs", 0 };
  221380. return ! (isOnCDRomDrive() || isFileOnDriveType (*this, (const char**) nonHDTypes));
  221381. }
  221382. bool File::isOnRemovableDrive() const
  221383. {
  221384. #if JUCE_IPHONE
  221385. return false; // xxx is this possible?
  221386. #else
  221387. const ScopedAutoReleasePool pool;
  221388. BOOL removable = false;
  221389. [[NSWorkspace sharedWorkspace]
  221390. getFileSystemInfoForPath: juceStringToNS (getFullPathName())
  221391. isRemovable: &removable
  221392. isWritable: nil
  221393. isUnmountable: nil
  221394. description: nil
  221395. type: nil];
  221396. return removable;
  221397. #endif
  221398. }
  221399. static bool juce_isHiddenFile (const String& path)
  221400. {
  221401. #if JUCE_IPHONE
  221402. return File (path).getFileName().startsWithChar ('.');
  221403. #else
  221404. FSRef ref;
  221405. if (! PlatformUtilities::makeFSRefFromPath (&ref, path))
  221406. return false;
  221407. FSCatalogInfo info;
  221408. FSGetCatalogInfo (&ref, kFSCatInfoNodeFlags | kFSCatInfoFinderInfo, &info, 0, 0, 0);
  221409. if ((info.nodeFlags & kFSNodeIsDirectoryBit) != 0)
  221410. return (((FolderInfo*) &info.finderInfo)->finderFlags & kIsInvisible) != 0;
  221411. return (((FileInfo*) &info.finderInfo)->finderFlags & kIsInvisible) != 0;
  221412. #endif
  221413. }
  221414. bool File::isHidden() const
  221415. {
  221416. return juce_isHiddenFile (getFullPathName());
  221417. }
  221418. const char* juce_Argv0 = 0; // referenced from juce_Application.cpp
  221419. const File File::getSpecialLocation (const SpecialLocationType type)
  221420. {
  221421. const ScopedAutoReleasePool pool;
  221422. String resultPath;
  221423. switch (type)
  221424. {
  221425. case userHomeDirectory:
  221426. resultPath = nsStringToJuce (NSHomeDirectory());
  221427. break;
  221428. case userDocumentsDirectory:
  221429. resultPath = "~/Documents";
  221430. break;
  221431. case userDesktopDirectory:
  221432. resultPath = "~/Desktop";
  221433. break;
  221434. case userApplicationDataDirectory:
  221435. resultPath = "~/Library";
  221436. break;
  221437. case commonApplicationDataDirectory:
  221438. resultPath = "/Library";
  221439. break;
  221440. case globalApplicationsDirectory:
  221441. resultPath = "/Applications";
  221442. break;
  221443. case userMusicDirectory:
  221444. resultPath = "~/Music";
  221445. break;
  221446. case userMoviesDirectory:
  221447. resultPath = "~/Movies";
  221448. break;
  221449. case tempDirectory:
  221450. {
  221451. File tmp ("~/Library/Caches/" + juce_getExecutableFile().getFileNameWithoutExtension());
  221452. tmp.createDirectory();
  221453. return tmp.getFullPathName();
  221454. }
  221455. case invokedExecutableFile:
  221456. if (juce_Argv0 != 0)
  221457. return File (String::fromUTF8 (juce_Argv0));
  221458. // deliberate fall-through...
  221459. case currentExecutableFile:
  221460. return juce_getExecutableFile();
  221461. case currentApplicationFile:
  221462. {
  221463. const File exe (juce_getExecutableFile());
  221464. const File parent (exe.getParentDirectory());
  221465. return parent.getFullPathName().endsWithIgnoreCase ("Contents/MacOS")
  221466. ? parent.getParentDirectory().getParentDirectory()
  221467. : exe;
  221468. }
  221469. default:
  221470. jassertfalse // unknown type?
  221471. break;
  221472. }
  221473. if (resultPath.isNotEmpty())
  221474. return File (PlatformUtilities::convertToPrecomposedUnicode (resultPath));
  221475. return File::nonexistent;
  221476. }
  221477. const String File::getVersion() const
  221478. {
  221479. const ScopedAutoReleasePool pool;
  221480. String result;
  221481. NSBundle* bundle = [NSBundle bundleWithPath: juceStringToNS (getFullPathName())];
  221482. if (bundle != 0)
  221483. {
  221484. NSDictionary* info = [bundle infoDictionary];
  221485. if (info != 0)
  221486. {
  221487. NSString* name = [info valueForKey: @"CFBundleShortVersionString"];
  221488. if (name != nil)
  221489. result = nsStringToJuce (name);
  221490. }
  221491. }
  221492. return result;
  221493. }
  221494. const File File::getLinkedTarget() const
  221495. {
  221496. #if JUCE_IPHONE || (defined (MAC_OS_X_VERSION_10_5) && MAC_OS_X_VERSION_MAX_ALLOWED >= MAC_OS_X_VERSION_10_5)
  221497. NSString* dest = [[NSFileManager defaultManager] destinationOfSymbolicLinkAtPath: juceStringToNS (getFullPathName()) error: nil];
  221498. #else
  221499. NSString* dest = [[NSFileManager defaultManager] pathContentOfSymbolicLinkAtPath: juceStringToNS (getFullPathName())];
  221500. #endif
  221501. if (dest != nil)
  221502. return File (nsStringToJuce (dest));
  221503. return *this;
  221504. }
  221505. bool File::moveToTrash() const
  221506. {
  221507. if (! exists())
  221508. return true;
  221509. #if JUCE_IPHONE
  221510. return deleteFile(); //xxx is there a trashcan on the iPhone?
  221511. #else
  221512. const ScopedAutoReleasePool pool;
  221513. NSString* p = juceStringToNS (getFullPathName());
  221514. return [[NSWorkspace sharedWorkspace]
  221515. performFileOperation: NSWorkspaceRecycleOperation
  221516. source: [p stringByDeletingLastPathComponent]
  221517. destination: @""
  221518. files: [NSArray arrayWithObject: [p lastPathComponent]]
  221519. tag: nil ];
  221520. #endif
  221521. }
  221522. class DirectoryIterator::NativeIterator::Pimpl
  221523. {
  221524. public:
  221525. Pimpl (const File& directory, const String& wildCard_)
  221526. : parentDir (File::addTrailingSeparator (directory.getFullPathName())),
  221527. wildCard (wildCard_),
  221528. enumerator (0)
  221529. {
  221530. ScopedAutoReleasePool pool;
  221531. enumerator = [[[NSFileManager defaultManager] enumeratorAtPath: juceStringToNS (directory.getFullPathName())] retain];
  221532. wildcardUTF8 = wildCard.toUTF8();
  221533. }
  221534. ~Pimpl()
  221535. {
  221536. [enumerator release];
  221537. }
  221538. bool next (String& filenameFound,
  221539. bool* const isDir, bool* const isHidden, int64* const fileSize,
  221540. Time* const modTime, Time* const creationTime, bool* const isReadOnly)
  221541. {
  221542. ScopedAutoReleasePool pool;
  221543. for (;;)
  221544. {
  221545. NSString* file;
  221546. if (enumerator == 0 || (file = [enumerator nextObject]) == 0)
  221547. return false;
  221548. [enumerator skipDescendents];
  221549. filenameFound = nsStringToJuce (file);
  221550. if (fnmatch (wildcardUTF8, filenameFound.toUTF8(), FNM_CASEFOLD) != 0)
  221551. continue;
  221552. const String path (parentDir + filenameFound);
  221553. if (isDir != 0 || fileSize != 0 || modTime != 0 || creationTime != 0)
  221554. {
  221555. struct stat info;
  221556. const bool statOk = juce_stat (path, info);
  221557. if (isDir != 0) *isDir = statOk && ((info.st_mode & S_IFDIR) != 0);
  221558. if (fileSize != 0) *fileSize = statOk ? info.st_size : 0;
  221559. if (modTime != 0) *modTime = statOk ? (int64) info.st_mtime * 1000 : 0;
  221560. if (creationTime != 0) *creationTime = statOk ? (int64) info.st_ctime * 1000 : 0;
  221561. }
  221562. if (isHidden != 0)
  221563. *isHidden = juce_isHiddenFile (path);
  221564. if (isReadOnly != 0)
  221565. *isReadOnly = access (path.toUTF8(), W_OK) != 0;
  221566. return true;
  221567. }
  221568. }
  221569. private:
  221570. String parentDir, wildCard;
  221571. const char* wildcardUTF8;
  221572. NSDirectoryEnumerator* enumerator;
  221573. Pimpl (const Pimpl&);
  221574. Pimpl& operator= (const Pimpl&);
  221575. };
  221576. DirectoryIterator::NativeIterator::NativeIterator (const File& directory, const String& wildCard)
  221577. : pimpl (new DirectoryIterator::NativeIterator::Pimpl (directory, wildCard))
  221578. {
  221579. }
  221580. DirectoryIterator::NativeIterator::~NativeIterator()
  221581. {
  221582. }
  221583. bool DirectoryIterator::NativeIterator::next (String& filenameFound,
  221584. bool* const isDir, bool* const isHidden, int64* const fileSize,
  221585. Time* const modTime, Time* const creationTime, bool* const isReadOnly)
  221586. {
  221587. return pimpl->next (filenameFound, isDir, isHidden, fileSize, modTime, creationTime, isReadOnly);
  221588. }
  221589. bool juce_launchExecutable (const String& pathAndArguments)
  221590. {
  221591. const char* const argv[4] = { "/bin/sh", "-c", pathAndArguments.toUTF8(), 0 };
  221592. const int cpid = fork();
  221593. if (cpid == 0)
  221594. {
  221595. // Child process
  221596. if (execve (argv[0], (char**) argv, 0) < 0)
  221597. exit (0);
  221598. }
  221599. else
  221600. {
  221601. if (cpid < 0)
  221602. return false;
  221603. }
  221604. return true;
  221605. }
  221606. bool PlatformUtilities::openDocument (const String& fileName, const String& parameters)
  221607. {
  221608. #if JUCE_IPHONE
  221609. return [[UIApplication sharedApplication] openURL: [NSURL fileURLWithPath: juceStringToNS (fileName)]];
  221610. #else
  221611. const ScopedAutoReleasePool pool;
  221612. if (parameters.isEmpty())
  221613. {
  221614. return [[NSWorkspace sharedWorkspace] openFile: juceStringToNS (fileName)]
  221615. || [[NSWorkspace sharedWorkspace] openURL: [NSURL URLWithString: juceStringToNS (fileName)]];
  221616. }
  221617. bool ok = false;
  221618. FSRef ref;
  221619. if (PlatformUtilities::makeFSRefFromPath (&ref, fileName))
  221620. {
  221621. if (PlatformUtilities::isBundle (fileName))
  221622. {
  221623. NSMutableArray* urls = [NSMutableArray array];
  221624. StringArray docs;
  221625. docs.addTokens (parameters, true);
  221626. for (int i = 0; i < docs.size(); ++i)
  221627. [urls addObject: juceStringToNS (docs[i])];
  221628. ok = [[NSWorkspace sharedWorkspace] openURLs: urls
  221629. withAppBundleIdentifier: [[NSBundle bundleWithPath: juceStringToNS (fileName)] bundleIdentifier]
  221630. options: 0
  221631. additionalEventParamDescriptor: nil
  221632. launchIdentifiers: nil];
  221633. }
  221634. else
  221635. {
  221636. ok = juce_launchExecutable ("\"" + fileName + "\" " + parameters);
  221637. }
  221638. }
  221639. return ok;
  221640. #endif
  221641. }
  221642. void File::revealToUser() const
  221643. {
  221644. #if ! JUCE_IPHONE
  221645. if (exists())
  221646. [[NSWorkspace sharedWorkspace] selectFile: juceStringToNS (getFullPathName()) inFileViewerRootedAtPath: @""];
  221647. else if (getParentDirectory().exists())
  221648. getParentDirectory().revealToUser();
  221649. #endif
  221650. }
  221651. #if ! JUCE_IPHONE
  221652. bool PlatformUtilities::makeFSRefFromPath (FSRef* destFSRef, const String& path)
  221653. {
  221654. return FSPathMakeRef ((const UInt8*) path.toUTF8(), destFSRef, 0) == noErr;
  221655. }
  221656. const String PlatformUtilities::makePathFromFSRef (FSRef* file)
  221657. {
  221658. char path [2048];
  221659. zerostruct (path);
  221660. if (FSRefMakePath (file, (UInt8*) path, sizeof (path) - 1) == noErr)
  221661. return PlatformUtilities::convertToPrecomposedUnicode (String::fromUTF8 (path));
  221662. return String::empty;
  221663. }
  221664. #endif
  221665. OSType PlatformUtilities::getTypeOfFile (const String& filename)
  221666. {
  221667. const ScopedAutoReleasePool pool;
  221668. #if JUCE_IPHONE || (defined (MAC_OS_X_VERSION_10_5) && MAC_OS_X_VERSION_MAX_ALLOWED >= MAC_OS_X_VERSION_10_5)
  221669. NSDictionary* fileDict = [[NSFileManager defaultManager] attributesOfItemAtPath: juceStringToNS (filename) error: nil];
  221670. #else
  221671. NSDictionary* fileDict = [[NSFileManager defaultManager] fileAttributesAtPath: juceStringToNS (filename) traverseLink: NO];
  221672. #endif
  221673. //return (OSType) [fileDict objectForKey: NSFileHFSTypeCode];
  221674. return [fileDict fileHFSTypeCode];
  221675. }
  221676. bool PlatformUtilities::isBundle (const String& filename)
  221677. {
  221678. #if JUCE_IPHONE
  221679. return false; // xxx can't find a sensible way to do this without trying to open the bundle..
  221680. #else
  221681. const ScopedAutoReleasePool pool;
  221682. return [[NSWorkspace sharedWorkspace] isFilePackageAtPath: juceStringToNS (filename)];
  221683. #endif
  221684. }
  221685. #endif
  221686. /*** End of inlined file: juce_mac_Files.mm ***/
  221687. #if JUCE_IPHONE
  221688. /*** Start of inlined file: juce_iphone_MiscUtilities.mm ***/
  221689. // (This file gets included by juce_mac_NativeCode.mm, rather than being
  221690. // compiled on its own).
  221691. #if JUCE_INCLUDED_FILE
  221692. static JUCEApplication* juce_intialisingApp;
  221693. END_JUCE_NAMESPACE
  221694. @interface JuceAppStartupDelegate : NSObject <UIApplicationDelegate>
  221695. {
  221696. }
  221697. - (void) applicationDidFinishLaunching: (UIApplication*) application;
  221698. - (void) applicationWillResignActive: (UIApplication*) application;
  221699. @end
  221700. @implementation JuceAppStartupDelegate
  221701. - (void) applicationDidFinishLaunching: (UIApplication*) application
  221702. {
  221703. String dummy;
  221704. if (! juce_intialisingApp->initialiseApp (dummy))
  221705. exit (0);
  221706. }
  221707. - (void) applicationWillResignActive: (UIApplication*) application
  221708. {
  221709. JUCEApplication::shutdownAppAndClearUp();
  221710. }
  221711. @end
  221712. BEGIN_JUCE_NAMESPACE
  221713. int juce_IPhoneMain (int argc, const char* argv[], JUCEApplication* app)
  221714. {
  221715. juce_intialisingApp = app;
  221716. return UIApplicationMain (argc, const_cast<char**> (argv), nil, @"JuceAppStartupDelegate");
  221717. }
  221718. ScopedAutoReleasePool::ScopedAutoReleasePool()
  221719. {
  221720. pool = [[NSAutoreleasePool alloc] init];
  221721. }
  221722. ScopedAutoReleasePool::~ScopedAutoReleasePool()
  221723. {
  221724. [((NSAutoreleasePool*) pool) release];
  221725. }
  221726. void PlatformUtilities::beep()
  221727. {
  221728. //xxx
  221729. //AudioServicesPlaySystemSound ();
  221730. }
  221731. void PlatformUtilities::addItemToDock (const File& file)
  221732. {
  221733. }
  221734. #if ! JUCE_ONLY_BUILD_CORE_LIBRARY
  221735. END_JUCE_NAMESPACE
  221736. @interface JuceAlertBoxDelegate : NSObject
  221737. {
  221738. @public
  221739. bool clickedOk;
  221740. }
  221741. - (void) alertView: (UIAlertView*) alertView clickedButtonAtIndex: (NSInteger) buttonIndex;
  221742. @end
  221743. @implementation JuceAlertBoxDelegate
  221744. - (void) alertView: (UIAlertView*) alertView clickedButtonAtIndex: (NSInteger) buttonIndex
  221745. {
  221746. clickedOk = (buttonIndex == 0);
  221747. alertView.hidden = true;
  221748. }
  221749. @end
  221750. BEGIN_JUCE_NAMESPACE
  221751. // (This function is used directly by other bits of code)
  221752. bool juce_iPhoneShowModalAlert (const String& title,
  221753. const String& bodyText,
  221754. NSString* okButtonText,
  221755. NSString* cancelButtonText)
  221756. {
  221757. const ScopedAutoReleasePool pool;
  221758. JuceAlertBoxDelegate* callback = [[JuceAlertBoxDelegate alloc] init];
  221759. UIAlertView* alert = [[UIAlertView alloc] initWithTitle: juceStringToNS (title)
  221760. message: juceStringToNS (bodyText)
  221761. delegate: callback
  221762. cancelButtonTitle: okButtonText
  221763. otherButtonTitles: cancelButtonText, nil];
  221764. [alert retain];
  221765. [alert show];
  221766. while (! alert.hidden && alert.superview != nil)
  221767. [[NSRunLoop mainRunLoop] runUntilDate: [NSDate dateWithTimeIntervalSinceNow: 0.01]];
  221768. const bool result = callback->clickedOk;
  221769. [alert release];
  221770. [callback release];
  221771. return result;
  221772. }
  221773. bool AlertWindow::showNativeDialogBox (const String& title,
  221774. const String& bodyText,
  221775. bool isOkCancel)
  221776. {
  221777. return juce_iPhoneShowModalAlert (title, bodyText,
  221778. @"OK",
  221779. isOkCancel ? @"Cancel" : nil);
  221780. }
  221781. bool DragAndDropContainer::performExternalDragDropOfFiles (const StringArray& files, const bool canMoveFiles)
  221782. {
  221783. jassertfalse // no such thing on the iphone!
  221784. return false;
  221785. }
  221786. bool DragAndDropContainer::performExternalDragDropOfText (const String& text)
  221787. {
  221788. jassertfalse // no such thing on the iphone!
  221789. return false;
  221790. }
  221791. void Desktop::setScreenSaverEnabled (const bool isEnabled) throw()
  221792. {
  221793. [[UIApplication sharedApplication] setIdleTimerDisabled: ! isEnabled];
  221794. }
  221795. bool Desktop::isScreenSaverEnabled() throw()
  221796. {
  221797. return ! [[UIApplication sharedApplication] isIdleTimerDisabled];
  221798. }
  221799. void juce_updateMultiMonitorInfo (Array <Rectangle <int> >& monitorCoords, const bool clipToWorkArea)
  221800. {
  221801. const ScopedAutoReleasePool pool;
  221802. monitorCoords.clear();
  221803. CGRect r = clipToWorkArea ? [[UIScreen mainScreen] applicationFrame]
  221804. : [[UIScreen mainScreen] bounds];
  221805. monitorCoords.add (Rectangle<int> ((int) r.origin.x,
  221806. (int) r.origin.y,
  221807. (int) r.size.width,
  221808. (int) r.size.height));
  221809. }
  221810. #endif
  221811. #endif
  221812. /*** End of inlined file: juce_iphone_MiscUtilities.mm ***/
  221813. #else
  221814. /*** Start of inlined file: juce_mac_MiscUtilities.mm ***/
  221815. // (This file gets included by juce_mac_NativeCode.mm, rather than being
  221816. // compiled on its own).
  221817. #if JUCE_INCLUDED_FILE
  221818. ScopedAutoReleasePool::ScopedAutoReleasePool()
  221819. {
  221820. pool = [[NSAutoreleasePool alloc] init];
  221821. }
  221822. ScopedAutoReleasePool::~ScopedAutoReleasePool()
  221823. {
  221824. [((NSAutoreleasePool*) pool) release];
  221825. }
  221826. void PlatformUtilities::beep()
  221827. {
  221828. NSBeep();
  221829. }
  221830. void PlatformUtilities::addItemToDock (const File& file)
  221831. {
  221832. // check that it's not already there...
  221833. if (! juce_getOutputFromCommand ("defaults read com.apple.dock persistent-apps")
  221834. .containsIgnoreCase (file.getFullPathName()))
  221835. {
  221836. 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>"
  221837. + file.getFullPathName() + "</string><key>_CFURLStringType</key><integer>0</integer></dict></dict></dict>\"");
  221838. juce_runSystemCommand ("osascript -e \"tell application \\\"Dock\\\" to quit\"");
  221839. }
  221840. }
  221841. int PlatformUtilities::getOSXMinorVersionNumber()
  221842. {
  221843. SInt32 versionMinor = 0;
  221844. OSErr err = Gestalt (gestaltSystemVersionMinor, &versionMinor);
  221845. (void) err;
  221846. jassert (err == noErr);
  221847. return (int) versionMinor;
  221848. }
  221849. #if ! JUCE_ONLY_BUILD_CORE_LIBRARY
  221850. bool AlertWindow::showNativeDialogBox (const String& title,
  221851. const String& bodyText,
  221852. bool isOkCancel)
  221853. {
  221854. const ScopedAutoReleasePool pool;
  221855. return NSRunAlertPanel (juceStringToNS (title),
  221856. juceStringToNS (bodyText),
  221857. @"Ok",
  221858. isOkCancel ? @"Cancel" : nil,
  221859. nil) == NSAlertDefaultReturn;
  221860. }
  221861. bool DragAndDropContainer::performExternalDragDropOfFiles (const StringArray& files, const bool canMoveFiles)
  221862. {
  221863. if (files.size() == 0)
  221864. return false;
  221865. MouseInputSource* draggingSource = Desktop::getInstance().getDraggingMouseSource(0);
  221866. if (draggingSource == 0)
  221867. {
  221868. jassertfalse // This method must be called in response to a component's mouseDown or mouseDrag event!
  221869. return false;
  221870. }
  221871. Component* sourceComp = draggingSource->getComponentUnderMouse();
  221872. if (sourceComp == 0)
  221873. {
  221874. jassertfalse // This method must be called in response to a component's mouseDown or mouseDrag event!
  221875. return false;
  221876. }
  221877. const ScopedAutoReleasePool pool;
  221878. NSView* view = (NSView*) sourceComp->getWindowHandle();
  221879. if (view == 0)
  221880. return false;
  221881. NSPasteboard* pboard = [NSPasteboard pasteboardWithName: NSDragPboard];
  221882. [pboard declareTypes: [NSArray arrayWithObject: NSFilenamesPboardType]
  221883. owner: nil];
  221884. NSMutableArray* filesArray = [NSMutableArray arrayWithCapacity: 4];
  221885. for (int i = 0; i < files.size(); ++i)
  221886. [filesArray addObject: juceStringToNS (files[i])];
  221887. [pboard setPropertyList: filesArray
  221888. forType: NSFilenamesPboardType];
  221889. NSPoint dragPosition = [view convertPoint: [[[view window] currentEvent] locationInWindow]
  221890. fromView: nil];
  221891. dragPosition.x -= 16;
  221892. dragPosition.y -= 16;
  221893. [view dragImage: [[NSWorkspace sharedWorkspace] iconForFile: juceStringToNS (files[0])]
  221894. at: dragPosition
  221895. offset: NSMakeSize (0, 0)
  221896. event: [[view window] currentEvent]
  221897. pasteboard: pboard
  221898. source: view
  221899. slideBack: YES];
  221900. return true;
  221901. }
  221902. bool DragAndDropContainer::performExternalDragDropOfText (const String& text)
  221903. {
  221904. jassertfalse // not implemented!
  221905. return false;
  221906. }
  221907. bool Desktop::canUseSemiTransparentWindows() throw()
  221908. {
  221909. return true;
  221910. }
  221911. const Point<int> Desktop::getMousePosition()
  221912. {
  221913. const ScopedAutoReleasePool pool;
  221914. const NSPoint p ([NSEvent mouseLocation]);
  221915. return Point<int> (roundToInt (p.x), roundToInt ([[[NSScreen screens] objectAtIndex: 0] frame].size.height - p.y));
  221916. }
  221917. void Desktop::setMousePosition (const Point<int>& newPosition)
  221918. {
  221919. // this rubbish needs to be done around the warp call, to avoid causing a
  221920. // bizarre glitch..
  221921. CGAssociateMouseAndMouseCursorPosition (false);
  221922. CGWarpMouseCursorPosition (CGPointMake (newPosition.getX(), newPosition.getY()));
  221923. CGAssociateMouseAndMouseCursorPosition (true);
  221924. }
  221925. #if MAC_OS_X_VERSION_MIN_REQUIRED < MAC_OS_X_VERSION_10_5
  221926. class ScreenSaverDefeater : public Timer,
  221927. public DeletedAtShutdown
  221928. {
  221929. public:
  221930. ScreenSaverDefeater()
  221931. {
  221932. startTimer (10000);
  221933. timerCallback();
  221934. }
  221935. ~ScreenSaverDefeater() {}
  221936. void timerCallback()
  221937. {
  221938. if (Process::isForegroundProcess())
  221939. UpdateSystemActivity (UsrActivity);
  221940. }
  221941. };
  221942. static ScreenSaverDefeater* screenSaverDefeater = 0;
  221943. void Desktop::setScreenSaverEnabled (const bool isEnabled) throw()
  221944. {
  221945. if (isEnabled)
  221946. {
  221947. deleteAndZero (screenSaverDefeater);
  221948. }
  221949. else if (screenSaverDefeater == 0)
  221950. {
  221951. screenSaverDefeater = new ScreenSaverDefeater();
  221952. }
  221953. }
  221954. bool Desktop::isScreenSaverEnabled() throw()
  221955. {
  221956. return screenSaverDefeater == 0;
  221957. }
  221958. #else
  221959. static IOPMAssertionID screenSaverDisablerID = 0;
  221960. void Desktop::setScreenSaverEnabled (const bool isEnabled) throw()
  221961. {
  221962. if (isEnabled)
  221963. {
  221964. if (screenSaverDisablerID != 0)
  221965. {
  221966. IOPMAssertionRelease (screenSaverDisablerID);
  221967. screenSaverDisablerID = 0;
  221968. }
  221969. }
  221970. else
  221971. {
  221972. if (screenSaverDisablerID == 0)
  221973. {
  221974. #if defined (MAC_OS_X_VERSION_10_6) && MAC_OS_X_VERSION_MAX_ALLOWED >= MAC_OS_X_VERSION_10_6
  221975. IOPMAssertionCreateWithName (kIOPMAssertionTypeNoIdleSleep, kIOPMAssertionLevelOn,
  221976. CFSTR ("Juce"), &screenSaverDisablerID);
  221977. #else
  221978. IOPMAssertionCreate (kIOPMAssertionTypeNoIdleSleep, kIOPMAssertionLevelOn,
  221979. &screenSaverDisablerID);
  221980. #endif
  221981. }
  221982. }
  221983. }
  221984. bool Desktop::isScreenSaverEnabled() throw()
  221985. {
  221986. return screenSaverDisablerID == 0;
  221987. }
  221988. #endif
  221989. void juce_updateMultiMonitorInfo (Array <Rectangle<int> >& monitorCoords, const bool clipToWorkArea)
  221990. {
  221991. const ScopedAutoReleasePool pool;
  221992. monitorCoords.clear();
  221993. NSArray* screens = [NSScreen screens];
  221994. const CGFloat mainScreenBottom = [[[NSScreen screens] objectAtIndex: 0] frame].size.height;
  221995. for (unsigned int i = 0; i < [screens count]; ++i)
  221996. {
  221997. NSScreen* s = (NSScreen*) [screens objectAtIndex: i];
  221998. NSRect r = clipToWorkArea ? [s visibleFrame]
  221999. : [s frame];
  222000. monitorCoords.add (Rectangle<int> ((int) r.origin.x,
  222001. (int) (mainScreenBottom - (r.origin.y + r.size.height)),
  222002. (int) r.size.width,
  222003. (int) r.size.height));
  222004. }
  222005. jassert (monitorCoords.size() > 0);
  222006. }
  222007. #endif
  222008. #endif
  222009. /*** End of inlined file: juce_mac_MiscUtilities.mm ***/
  222010. #endif
  222011. /*** Start of inlined file: juce_mac_Debugging.mm ***/
  222012. // (This file gets included by juce_mac_NativeCode.mm, rather than being
  222013. // compiled on its own).
  222014. #if JUCE_INCLUDED_FILE
  222015. void Logger::outputDebugString (const String& text) throw()
  222016. {
  222017. std::cerr << text << std::endl;
  222018. }
  222019. bool JUCE_PUBLIC_FUNCTION juce_isRunningUnderDebugger()
  222020. {
  222021. static char testResult = 0;
  222022. if (testResult == 0)
  222023. {
  222024. struct kinfo_proc info;
  222025. int m[] = { CTL_KERN, KERN_PROC, KERN_PROC_PID, getpid() };
  222026. size_t sz = sizeof (info);
  222027. sysctl (m, 4, &info, &sz, 0, 0);
  222028. testResult = ((info.kp_proc.p_flag & P_TRACED) != 0) ? 1 : -1;
  222029. }
  222030. return testResult > 0;
  222031. }
  222032. bool JUCE_CALLTYPE Process::isRunningUnderDebugger()
  222033. {
  222034. return juce_isRunningUnderDebugger();
  222035. }
  222036. #endif
  222037. /*** End of inlined file: juce_mac_Debugging.mm ***/
  222038. #if ! JUCE_ONLY_BUILD_CORE_LIBRARY
  222039. #if JUCE_IPHONE
  222040. /*** Start of inlined file: juce_mac_Fonts.mm ***/
  222041. // (This file gets included by juce_mac_NativeCode.mm, rather than being
  222042. // compiled on its own).
  222043. #if JUCE_INCLUDED_FILE
  222044. #if MAC_OS_X_VERSION_MIN_REQUIRED < MAC_OS_X_VERSION_10_5
  222045. #define SUPPORT_10_4_FONTS 1
  222046. #define NEW_CGFONT_FUNCTIONS_UNAVAILABLE (CGFontCreateWithFontName == 0)
  222047. #if MAC_OS_X_VERSION_MAX_ALLOWED < MAC_OS_X_VERSION_10_5
  222048. #define SUPPORT_ONLY_10_4_FONTS 1
  222049. #endif
  222050. END_JUCE_NAMESPACE
  222051. @interface NSFont (PrivateHack)
  222052. - (NSGlyph) _defaultGlyphForChar: (unichar) theChar;
  222053. @end
  222054. BEGIN_JUCE_NAMESPACE
  222055. #endif
  222056. class MacTypeface : public Typeface
  222057. {
  222058. public:
  222059. MacTypeface (const Font& font)
  222060. : Typeface (font.getTypefaceName())
  222061. {
  222062. const ScopedAutoReleasePool pool;
  222063. renderingTransform = CGAffineTransformIdentity;
  222064. bool needsItalicTransform = false;
  222065. #if JUCE_IPHONE
  222066. NSString* fontName = juceStringToNS (font.getTypefaceName());
  222067. if (font.isItalic() || font.isBold())
  222068. {
  222069. NSArray* familyFonts = [UIFont fontNamesForFamilyName: juceStringToNS (font.getTypefaceName())];
  222070. for (NSString* i in familyFonts)
  222071. {
  222072. const String fn (nsStringToJuce (i));
  222073. const String afterDash (fn.fromFirstOccurrenceOf ("-", false, false));
  222074. const bool probablyBold = afterDash.containsIgnoreCase ("bold") || fn.endsWithIgnoreCase ("bold");
  222075. const bool probablyItalic = afterDash.containsIgnoreCase ("oblique")
  222076. || afterDash.containsIgnoreCase ("italic")
  222077. || fn.endsWithIgnoreCase ("oblique")
  222078. || fn.endsWithIgnoreCase ("italic");
  222079. if (probablyBold == font.isBold()
  222080. && probablyItalic == font.isItalic())
  222081. {
  222082. fontName = i;
  222083. needsItalicTransform = false;
  222084. break;
  222085. }
  222086. else if (probablyBold && (! probablyItalic) && probablyBold == font.isBold())
  222087. {
  222088. fontName = i;
  222089. needsItalicTransform = true; // not ideal, so carry on in case we find a better one
  222090. }
  222091. }
  222092. if (needsItalicTransform)
  222093. renderingTransform.c = 0.15f;
  222094. }
  222095. fontRef = CGFontCreateWithFontName ((CFStringRef) fontName);
  222096. const int ascender = abs (CGFontGetAscent (fontRef));
  222097. const float totalHeight = ascender + abs (CGFontGetDescent (fontRef));
  222098. ascent = ascender / totalHeight;
  222099. unitsToHeightScaleFactor = 1.0f / totalHeight;
  222100. fontHeightToCGSizeFactor = CGFontGetUnitsPerEm (fontRef) / totalHeight;
  222101. #else
  222102. nsFont = [NSFont fontWithName: juceStringToNS (font.getTypefaceName()) size: 1024];
  222103. if (font.isItalic())
  222104. {
  222105. NSFont* newFont = [[NSFontManager sharedFontManager] convertFont: nsFont
  222106. toHaveTrait: NSItalicFontMask];
  222107. if (newFont == nsFont)
  222108. needsItalicTransform = true; // couldn't find a proper italic version, so fake it with a transform..
  222109. nsFont = newFont;
  222110. }
  222111. if (font.isBold())
  222112. nsFont = [[NSFontManager sharedFontManager] convertFont: nsFont toHaveTrait: NSBoldFontMask];
  222113. [nsFont retain];
  222114. ascent = fabsf ((float) [nsFont ascender]);
  222115. float totalSize = ascent + fabsf ((float) [nsFont descender]);
  222116. ascent /= totalSize;
  222117. pathTransform = AffineTransform::identity.scale (1.0f / totalSize, 1.0f / totalSize);
  222118. if (needsItalicTransform)
  222119. {
  222120. pathTransform = pathTransform.sheared (-0.15f, 0.0f);
  222121. renderingTransform.c = 0.15f;
  222122. }
  222123. #if SUPPORT_ONLY_10_4_FONTS
  222124. ATSFontRef atsFont = ATSFontFindFromName ((CFStringRef) [nsFont fontName], kATSOptionFlagsDefault);
  222125. if (atsFont == 0)
  222126. atsFont = ATSFontFindFromPostScriptName ((CFStringRef) [nsFont fontName], kATSOptionFlagsDefault);
  222127. fontRef = CGFontCreateWithPlatformFont (&atsFont);
  222128. const float totalHeight = fabsf ([nsFont ascender]) + fabsf([nsFont descender]);
  222129. unitsToHeightScaleFactor = 1.0f / totalHeight;
  222130. fontHeightToCGSizeFactor = 1024.0f / totalHeight;
  222131. #else
  222132. #if SUPPORT_10_4_FONTS
  222133. if (NEW_CGFONT_FUNCTIONS_UNAVAILABLE)
  222134. {
  222135. ATSFontRef atsFont = ATSFontFindFromName ((CFStringRef) [nsFont fontName], kATSOptionFlagsDefault);
  222136. if (atsFont == 0)
  222137. atsFont = ATSFontFindFromPostScriptName ((CFStringRef) [nsFont fontName], kATSOptionFlagsDefault);
  222138. fontRef = CGFontCreateWithPlatformFont (&atsFont);
  222139. const float totalHeight = fabsf ([nsFont ascender]) + fabsf([nsFont descender]);
  222140. unitsToHeightScaleFactor = 1.0f / totalHeight;
  222141. fontHeightToCGSizeFactor = 1024.0f / totalHeight;
  222142. }
  222143. else
  222144. #endif
  222145. {
  222146. fontRef = CGFontCreateWithFontName ((CFStringRef) [nsFont fontName]);
  222147. const int totalHeight = abs (CGFontGetAscent (fontRef)) + abs (CGFontGetDescent (fontRef));
  222148. unitsToHeightScaleFactor = 1.0f / totalHeight;
  222149. fontHeightToCGSizeFactor = CGFontGetUnitsPerEm (fontRef) / (float) totalHeight;
  222150. }
  222151. #endif
  222152. #endif
  222153. }
  222154. ~MacTypeface()
  222155. {
  222156. #if ! JUCE_IPHONE
  222157. [nsFont release];
  222158. #endif
  222159. if (fontRef != 0)
  222160. CGFontRelease (fontRef);
  222161. }
  222162. float getAscent() const
  222163. {
  222164. return ascent;
  222165. }
  222166. float getDescent() const
  222167. {
  222168. return 1.0f - ascent;
  222169. }
  222170. float getStringWidth (const String& text)
  222171. {
  222172. if (fontRef == 0 || text.isEmpty())
  222173. return 0;
  222174. const int length = text.length();
  222175. HeapBlock <CGGlyph> glyphs;
  222176. createGlyphsForString (text, length, glyphs);
  222177. float x = 0;
  222178. #if SUPPORT_ONLY_10_4_FONTS
  222179. HeapBlock <NSSize> advances (length);
  222180. [nsFont getAdvancements: advances forGlyphs: reinterpret_cast <NSGlyph*> (glyphs.getData()) count: length];
  222181. for (int i = 0; i < length; ++i)
  222182. x += advances[i].width;
  222183. #else
  222184. #if SUPPORT_10_4_FONTS
  222185. if (NEW_CGFONT_FUNCTIONS_UNAVAILABLE)
  222186. {
  222187. HeapBlock <NSSize> advances (length);
  222188. [nsFont getAdvancements: advances forGlyphs: reinterpret_cast<NSGlyph*> (glyphs.getData()) count: length];
  222189. for (int i = 0; i < length; ++i)
  222190. x += advances[i].width;
  222191. }
  222192. else
  222193. #endif
  222194. {
  222195. HeapBlock <int> advances (length);
  222196. if (CGFontGetGlyphAdvances (fontRef, glyphs, length, advances))
  222197. for (int i = 0; i < length; ++i)
  222198. x += advances[i];
  222199. }
  222200. #endif
  222201. return x * unitsToHeightScaleFactor;
  222202. }
  222203. void getGlyphPositions (const String& text, Array <int>& resultGlyphs, Array <float>& xOffsets)
  222204. {
  222205. xOffsets.add (0);
  222206. if (fontRef == 0 || text.isEmpty())
  222207. return;
  222208. const int length = text.length();
  222209. HeapBlock <CGGlyph> glyphs;
  222210. createGlyphsForString (text, length, glyphs);
  222211. #if SUPPORT_ONLY_10_4_FONTS
  222212. HeapBlock <NSSize> advances (length);
  222213. [nsFont getAdvancements: advances forGlyphs: reinterpret_cast <NSGlyph*> (glyphs.getData()) count: length];
  222214. int x = 0;
  222215. for (int i = 0; i < length; ++i)
  222216. {
  222217. x += advances[i].width;
  222218. xOffsets.add (x * unitsToHeightScaleFactor);
  222219. resultGlyphs.add (reinterpret_cast <NSGlyph*> (glyphs.getData())[i]);
  222220. }
  222221. #else
  222222. #if SUPPORT_10_4_FONTS
  222223. if (NEW_CGFONT_FUNCTIONS_UNAVAILABLE)
  222224. {
  222225. HeapBlock <NSSize> advances (length);
  222226. NSGlyph* const nsGlyphs = reinterpret_cast<NSGlyph*> (glyphs.getData());
  222227. [nsFont getAdvancements: advances forGlyphs: nsGlyphs count: length];
  222228. float x = 0;
  222229. for (int i = 0; i < length; ++i)
  222230. {
  222231. x += advances[i].width;
  222232. xOffsets.add (x * unitsToHeightScaleFactor);
  222233. resultGlyphs.add (nsGlyphs[i]);
  222234. }
  222235. }
  222236. else
  222237. #endif
  222238. {
  222239. HeapBlock <int> advances (length);
  222240. if (CGFontGetGlyphAdvances (fontRef, glyphs, length, advances))
  222241. {
  222242. int x = 0;
  222243. for (int i = 0; i < length; ++i)
  222244. {
  222245. x += advances [i];
  222246. xOffsets.add (x * unitsToHeightScaleFactor);
  222247. resultGlyphs.add (glyphs[i]);
  222248. }
  222249. }
  222250. }
  222251. #endif
  222252. }
  222253. bool getOutlineForGlyph (int glyphNumber, Path& path)
  222254. {
  222255. #if JUCE_IPHONE
  222256. return false;
  222257. #else
  222258. if (nsFont == 0)
  222259. return false;
  222260. // we might need to apply a transform to the path, so it mustn't have anything else in it
  222261. jassert (path.isEmpty());
  222262. const ScopedAutoReleasePool pool;
  222263. NSBezierPath* bez = [NSBezierPath bezierPath];
  222264. [bez moveToPoint: NSMakePoint (0, 0)];
  222265. [bez appendBezierPathWithGlyph: (NSGlyph) glyphNumber
  222266. inFont: nsFont];
  222267. for (int i = 0; i < [bez elementCount]; ++i)
  222268. {
  222269. NSPoint p[3];
  222270. switch ([bez elementAtIndex: i associatedPoints: p])
  222271. {
  222272. case NSMoveToBezierPathElement:
  222273. path.startNewSubPath ((float) p[0].x, (float) -p[0].y);
  222274. break;
  222275. case NSLineToBezierPathElement:
  222276. path.lineTo ((float) p[0].x, (float) -p[0].y);
  222277. break;
  222278. case NSCurveToBezierPathElement:
  222279. 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);
  222280. break;
  222281. case NSClosePathBezierPathElement:
  222282. path.closeSubPath();
  222283. break;
  222284. default:
  222285. jassertfalse
  222286. break;
  222287. }
  222288. }
  222289. path.applyTransform (pathTransform);
  222290. return true;
  222291. #endif
  222292. }
  222293. juce_UseDebuggingNewOperator
  222294. CGFontRef fontRef;
  222295. float fontHeightToCGSizeFactor;
  222296. CGAffineTransform renderingTransform;
  222297. private:
  222298. float ascent, unitsToHeightScaleFactor;
  222299. #if JUCE_IPHONE
  222300. #else
  222301. NSFont* nsFont;
  222302. AffineTransform pathTransform;
  222303. #endif
  222304. void createGlyphsForString (const juce_wchar* const text, const int length, HeapBlock <CGGlyph>& glyphs)
  222305. {
  222306. #if SUPPORT_10_4_FONTS
  222307. #if ! SUPPORT_ONLY_10_4_FONTS
  222308. if (NEW_CGFONT_FUNCTIONS_UNAVAILABLE)
  222309. #endif
  222310. {
  222311. glyphs.malloc (sizeof (NSGlyph) * length, 1);
  222312. NSGlyph* const nsGlyphs = reinterpret_cast<NSGlyph*> (glyphs.getData());
  222313. for (int i = 0; i < length; ++i)
  222314. nsGlyphs[i] = (NSGlyph) [nsFont _defaultGlyphForChar: text[i]];
  222315. return;
  222316. }
  222317. #endif
  222318. #if ! SUPPORT_ONLY_10_4_FONTS
  222319. if (charToGlyphMapper == 0)
  222320. charToGlyphMapper = new CharToGlyphMapper (fontRef);
  222321. glyphs.malloc (length);
  222322. for (int i = 0; i < length; ++i)
  222323. glyphs[i] = (CGGlyph) charToGlyphMapper->getGlyphForCharacter (text[i]);
  222324. #endif
  222325. }
  222326. #if ! SUPPORT_ONLY_10_4_FONTS
  222327. // Reads a CGFontRef's character map table to convert unicode into glyph numbers
  222328. class CharToGlyphMapper
  222329. {
  222330. public:
  222331. CharToGlyphMapper (CGFontRef fontRef)
  222332. : segCount (0), endCode (0), startCode (0), idDelta (0),
  222333. idRangeOffset (0), glyphIndexes (0)
  222334. {
  222335. CFDataRef cmapTable = CGFontCopyTableForTag (fontRef, 'cmap');
  222336. if (cmapTable != 0)
  222337. {
  222338. const int numSubtables = getValue16 (cmapTable, 2);
  222339. for (int i = 0; i < numSubtables; ++i)
  222340. {
  222341. if (getValue16 (cmapTable, i * 8 + 4) == 0) // check for platform ID of 0
  222342. {
  222343. const int offset = getValue32 (cmapTable, i * 8 + 8);
  222344. if (getValue16 (cmapTable, offset) == 4) // check that it's format 4..
  222345. {
  222346. const int length = getValue16 (cmapTable, offset + 2);
  222347. const int segCountX2 = getValue16 (cmapTable, offset + 6);
  222348. segCount = segCountX2 / 2;
  222349. const int endCodeOffset = offset + 14;
  222350. const int startCodeOffset = endCodeOffset + 2 + segCountX2;
  222351. const int idDeltaOffset = startCodeOffset + segCountX2;
  222352. const int idRangeOffsetOffset = idDeltaOffset + segCountX2;
  222353. const int glyphIndexesOffset = idRangeOffsetOffset + segCountX2;
  222354. endCode = CFDataCreate (kCFAllocatorDefault, CFDataGetBytePtr (cmapTable) + endCodeOffset, segCountX2);
  222355. startCode = CFDataCreate (kCFAllocatorDefault, CFDataGetBytePtr (cmapTable) + startCodeOffset, segCountX2);
  222356. idDelta = CFDataCreate (kCFAllocatorDefault, CFDataGetBytePtr (cmapTable) + idDeltaOffset, segCountX2);
  222357. idRangeOffset = CFDataCreate (kCFAllocatorDefault, CFDataGetBytePtr (cmapTable) + idRangeOffsetOffset, segCountX2);
  222358. glyphIndexes = CFDataCreate (kCFAllocatorDefault, CFDataGetBytePtr (cmapTable) + glyphIndexesOffset, offset + length - glyphIndexesOffset);
  222359. }
  222360. break;
  222361. }
  222362. }
  222363. CFRelease (cmapTable);
  222364. }
  222365. }
  222366. ~CharToGlyphMapper()
  222367. {
  222368. if (endCode != 0)
  222369. {
  222370. CFRelease (endCode);
  222371. CFRelease (startCode);
  222372. CFRelease (idDelta);
  222373. CFRelease (idRangeOffset);
  222374. CFRelease (glyphIndexes);
  222375. }
  222376. }
  222377. int getGlyphForCharacter (const juce_wchar c) const
  222378. {
  222379. for (int i = 0; i < segCount; ++i)
  222380. {
  222381. if (getValue16 (endCode, i * 2) >= c)
  222382. {
  222383. const int start = getValue16 (startCode, i * 2);
  222384. if (start > c)
  222385. break;
  222386. const int delta = getValue16 (idDelta, i * 2);
  222387. const int rangeOffset = getValue16 (idRangeOffset, i * 2);
  222388. if (rangeOffset == 0)
  222389. return delta + c;
  222390. else
  222391. return getValue16 (glyphIndexes, 2 * ((rangeOffset / 2) + (c - start) - (segCount - i)));
  222392. }
  222393. }
  222394. // If we failed to find it "properly", this dodgy fall-back seems to do the trick for most fonts!
  222395. return jmax (-1, c - 29);
  222396. }
  222397. private:
  222398. int segCount;
  222399. CFDataRef endCode, startCode, idDelta, idRangeOffset, glyphIndexes;
  222400. static uint16 getValue16 (CFDataRef data, const int index)
  222401. {
  222402. return CFSwapInt16BigToHost (*(UInt16*) (CFDataGetBytePtr (data) + index));
  222403. }
  222404. static uint32 getValue32 (CFDataRef data, const int index)
  222405. {
  222406. return CFSwapInt32BigToHost (*(UInt32*) (CFDataGetBytePtr (data) + index));
  222407. }
  222408. };
  222409. ScopedPointer <CharToGlyphMapper> charToGlyphMapper;
  222410. #endif
  222411. MacTypeface (const MacTypeface&);
  222412. MacTypeface& operator= (const MacTypeface&);
  222413. };
  222414. const Typeface::Ptr Typeface::createSystemTypefaceFor (const Font& font)
  222415. {
  222416. return new MacTypeface (font);
  222417. }
  222418. const StringArray Font::findAllTypefaceNames()
  222419. {
  222420. StringArray names;
  222421. const ScopedAutoReleasePool pool;
  222422. #if JUCE_IPHONE
  222423. NSArray* fonts = [UIFont familyNames];
  222424. #else
  222425. NSArray* fonts = [[NSFontManager sharedFontManager] availableFontFamilies];
  222426. #endif
  222427. for (unsigned int i = 0; i < [fonts count]; ++i)
  222428. names.add (nsStringToJuce ((NSString*) [fonts objectAtIndex: i]));
  222429. names.sort (true);
  222430. return names;
  222431. }
  222432. void Font::getPlatformDefaultFontNames (String& defaultSans, String& defaultSerif, String& defaultFixed)
  222433. {
  222434. #if JUCE_IPHONE
  222435. defaultSans = "Helvetica";
  222436. defaultSerif = "Times New Roman";
  222437. defaultFixed = "Courier New";
  222438. #else
  222439. defaultSans = "Lucida Grande";
  222440. defaultSerif = "Times New Roman";
  222441. defaultFixed = "Monaco";
  222442. #endif
  222443. }
  222444. #endif
  222445. /*** End of inlined file: juce_mac_Fonts.mm ***/
  222446. /*** Start of inlined file: juce_mac_CoreGraphicsContext.mm ***/
  222447. // (This file gets included by juce_mac_NativeCode.mm, rather than being
  222448. // compiled on its own).
  222449. #if JUCE_INCLUDED_FILE
  222450. class CoreGraphicsImage : public Image
  222451. {
  222452. public:
  222453. CoreGraphicsImage (const PixelFormat format_,
  222454. const int imageWidth_,
  222455. const int imageHeight_,
  222456. const bool clearImage)
  222457. : Image (format_, imageWidth_, imageHeight_, clearImage)
  222458. {
  222459. CGColorSpaceRef colourSpace = (format == Image::SingleChannel) ? CGColorSpaceCreateDeviceGray()
  222460. : CGColorSpaceCreateDeviceRGB();
  222461. context = CGBitmapContextCreate (imageData, imageWidth, imageHeight, 8, lineStride,
  222462. colourSpace, getCGImageFlags (*this));
  222463. CGColorSpaceRelease (colourSpace);
  222464. }
  222465. ~CoreGraphicsImage()
  222466. {
  222467. CGContextRelease (context);
  222468. }
  222469. LowLevelGraphicsContext* createLowLevelContext();
  222470. static CGImageRef createImage (const Image& juceImage, const bool forAlpha, CGColorSpaceRef colourSpace)
  222471. {
  222472. const CoreGraphicsImage* nativeImage = dynamic_cast <const CoreGraphicsImage*> (&juceImage);
  222473. if (nativeImage != 0 && (juceImage.getFormat() == Image::SingleChannel || ! forAlpha))
  222474. {
  222475. return CGBitmapContextCreateImage (nativeImage->context);
  222476. }
  222477. else
  222478. {
  222479. const Image::BitmapData srcData (juceImage, 0, 0, juceImage.getWidth(), juceImage.getHeight());
  222480. CGDataProviderRef provider = CGDataProviderCreateWithData (0, srcData.data, srcData.lineStride * srcData.height, 0);
  222481. CGImageRef imageRef = CGImageCreate (srcData.width, srcData.height,
  222482. 8, srcData.pixelStride * 8, srcData.lineStride,
  222483. colourSpace, getCGImageFlags (juceImage), provider,
  222484. 0, true, kCGRenderingIntentDefault);
  222485. CGDataProviderRelease (provider);
  222486. return imageRef;
  222487. }
  222488. }
  222489. #if JUCE_MAC
  222490. static NSImage* createNSImage (const Image& image)
  222491. {
  222492. const ScopedAutoReleasePool pool;
  222493. NSImage* im = [[NSImage alloc] init];
  222494. [im setSize: NSMakeSize (image.getWidth(), image.getHeight())];
  222495. [im lockFocus];
  222496. CGColorSpaceRef colourSpace = CGColorSpaceCreateDeviceRGB();
  222497. CGImageRef imageRef = createImage (image, false, colourSpace);
  222498. CGColorSpaceRelease (colourSpace);
  222499. CGContextRef cg = (CGContextRef) [[NSGraphicsContext currentContext] graphicsPort];
  222500. CGContextDrawImage (cg, CGRectMake (0, 0, image.getWidth(), image.getHeight()), imageRef);
  222501. CGImageRelease (imageRef);
  222502. [im unlockFocus];
  222503. return im;
  222504. }
  222505. #endif
  222506. CGContextRef context;
  222507. private:
  222508. static CGBitmapInfo getCGImageFlags (const Image& image)
  222509. {
  222510. #if JUCE_BIG_ENDIAN
  222511. return image.getFormat() == Image::ARGB ? (kCGImageAlphaPremultipliedFirst | kCGBitmapByteOrder32Big) : kCGBitmapByteOrderDefault;
  222512. #else
  222513. return image.getFormat() == Image::ARGB ? (kCGImageAlphaPremultipliedFirst | kCGBitmapByteOrder32Little) : kCGBitmapByteOrderDefault;
  222514. #endif
  222515. }
  222516. };
  222517. Image* Image::createNativeImage (const PixelFormat format, const int imageWidth, const int imageHeight, const bool clearImage)
  222518. {
  222519. #if USE_COREGRAPHICS_RENDERING
  222520. return new CoreGraphicsImage (format == RGB ? ARGB : format, imageWidth, imageHeight, clearImage);
  222521. #else
  222522. return new Image (format, imageWidth, imageHeight, clearImage);
  222523. #endif
  222524. }
  222525. class CoreGraphicsContext : public LowLevelGraphicsContext
  222526. {
  222527. public:
  222528. CoreGraphicsContext (CGContextRef context_, const float flipHeight_)
  222529. : context (context_),
  222530. flipHeight (flipHeight_),
  222531. state (new SavedState()),
  222532. numGradientLookupEntries (0)
  222533. {
  222534. CGContextRetain (context);
  222535. CGContextSaveGState(context);
  222536. CGContextSetShouldSmoothFonts (context, true);
  222537. CGContextSetShouldAntialias (context, true);
  222538. CGContextSetBlendMode (context, kCGBlendModeNormal);
  222539. rgbColourSpace = CGColorSpaceCreateDeviceRGB();
  222540. greyColourSpace = CGColorSpaceCreateDeviceGray();
  222541. gradientCallbacks.version = 0;
  222542. gradientCallbacks.evaluate = gradientCallback;
  222543. gradientCallbacks.releaseInfo = 0;
  222544. setFont (Font());
  222545. }
  222546. ~CoreGraphicsContext()
  222547. {
  222548. CGContextRestoreGState (context);
  222549. CGContextRelease (context);
  222550. CGColorSpaceRelease (rgbColourSpace);
  222551. CGColorSpaceRelease (greyColourSpace);
  222552. }
  222553. bool isVectorDevice() const { return false; }
  222554. void setOrigin (int x, int y)
  222555. {
  222556. CGContextTranslateCTM (context, x, -y);
  222557. }
  222558. bool clipToRectangle (const Rectangle<int>& r)
  222559. {
  222560. CGContextClipToRect (context, CGRectMake (r.getX(), flipHeight - r.getBottom(), r.getWidth(), r.getHeight()));
  222561. return ! isClipEmpty();
  222562. }
  222563. bool clipToRectangleList (const RectangleList& clipRegion)
  222564. {
  222565. if (clipRegion.isEmpty())
  222566. {
  222567. CGContextClipToRect (context, CGRectMake (0, 0, 0, 0));
  222568. return false;
  222569. }
  222570. else
  222571. {
  222572. const int numRects = clipRegion.getNumRectangles();
  222573. HeapBlock <CGRect> rects (numRects);
  222574. for (int i = 0; i < numRects; ++i)
  222575. {
  222576. const Rectangle<int>& r = clipRegion.getRectangle(i);
  222577. rects[i] = CGRectMake (r.getX(), flipHeight - r.getBottom(), r.getWidth(), r.getHeight());
  222578. }
  222579. CGContextClipToRects (context, rects, numRects);
  222580. return ! isClipEmpty();
  222581. }
  222582. }
  222583. void excludeClipRectangle (const Rectangle<int>& r)
  222584. {
  222585. RectangleList remaining (getClipBounds());
  222586. remaining.subtract (r);
  222587. clipToRectangleList (remaining);
  222588. }
  222589. void clipToPath (const Path& path, const AffineTransform& transform)
  222590. {
  222591. createPath (path, transform);
  222592. CGContextClip (context);
  222593. }
  222594. void clipToImageAlpha (const Image& sourceImage, const Rectangle<int>& srcClip, const AffineTransform& transform)
  222595. {
  222596. if (! transform.isSingularity())
  222597. {
  222598. ScopedPointer<Image> imageToDelete;
  222599. const Image* singleChannelImage = &sourceImage;
  222600. if (sourceImage.getFormat() != Image::SingleChannel)
  222601. {
  222602. imageToDelete = sourceImage.createCopyOfAlphaChannel();
  222603. singleChannelImage = imageToDelete;
  222604. }
  222605. CGImageRef image = CoreGraphicsImage::createImage (*singleChannelImage, true, greyColourSpace);
  222606. flip();
  222607. AffineTransform t (AffineTransform::scale (1.0f, -1.0f).translated (0, sourceImage.getHeight()).followedBy (transform));
  222608. applyTransform (t);
  222609. CGRect r = CGRectMake (0, 0, sourceImage.getWidth(), sourceImage.getHeight());
  222610. CGContextClipToMask (context, r, image);
  222611. applyTransform (t.inverted());
  222612. flip();
  222613. CGImageRelease (image);
  222614. }
  222615. }
  222616. bool clipRegionIntersects (const Rectangle<int>& r)
  222617. {
  222618. return getClipBounds().intersects (r);
  222619. }
  222620. const Rectangle<int> getClipBounds() const
  222621. {
  222622. CGRect bounds = CGRectIntegral (CGContextGetClipBoundingBox (context));
  222623. return Rectangle<int> (roundToInt (bounds.origin.x),
  222624. roundToInt (flipHeight - (bounds.origin.y + bounds.size.height)),
  222625. roundToInt (bounds.size.width),
  222626. roundToInt (bounds.size.height));
  222627. }
  222628. bool isClipEmpty() const
  222629. {
  222630. return CGRectIsEmpty (CGContextGetClipBoundingBox (context));
  222631. }
  222632. void saveState()
  222633. {
  222634. CGContextSaveGState (context);
  222635. stateStack.add (new SavedState (*state));
  222636. }
  222637. void restoreState()
  222638. {
  222639. CGContextRestoreGState (context);
  222640. SavedState* const top = stateStack.getLast();
  222641. if (top != 0)
  222642. {
  222643. state = top;
  222644. stateStack.removeLast (1, false);
  222645. }
  222646. else
  222647. {
  222648. jassertfalse // trying to pop with an empty stack!
  222649. }
  222650. }
  222651. void setFill (const FillType& fillType)
  222652. {
  222653. state->fillType = fillType;
  222654. if (fillType.isColour())
  222655. {
  222656. CGContextSetRGBFillColor (context, fillType.colour.getFloatRed(), fillType.colour.getFloatGreen(),
  222657. fillType.colour.getFloatBlue(), fillType.colour.getFloatAlpha());
  222658. CGContextSetAlpha (context, 1.0f);
  222659. }
  222660. }
  222661. void setOpacity (float newOpacity)
  222662. {
  222663. state->fillType.setOpacity (newOpacity);
  222664. setFill (state->fillType);
  222665. }
  222666. void setInterpolationQuality (Graphics::ResamplingQuality quality)
  222667. {
  222668. CGContextSetInterpolationQuality (context, quality == Graphics::lowResamplingQuality
  222669. ? kCGInterpolationLow
  222670. : kCGInterpolationHigh);
  222671. }
  222672. void fillRect (const Rectangle<int>& r, const bool replaceExistingContents)
  222673. {
  222674. CGRect cgRect = CGRectMake (r.getX(), flipHeight - r.getBottom(), r.getWidth(), r.getHeight());
  222675. if (replaceExistingContents)
  222676. {
  222677. #if MAC_OS_X_VERSION_MAX_ALLOWED < MAC_OS_X_VERSION_10_5
  222678. CGContextClearRect (context, cgRect);
  222679. #else
  222680. #if MAC_OS_X_VERSION_MIN_REQUIRED < MAC_OS_X_VERSION_10_5
  222681. if (CGContextDrawLinearGradient == 0) // (just a way of checking whether we're running in 10.5 or later)
  222682. CGContextClearRect (context, cgRect);
  222683. else
  222684. #endif
  222685. CGContextSetBlendMode (context, kCGBlendModeCopy);
  222686. #endif
  222687. fillRect (r, false);
  222688. CGContextSetBlendMode (context, kCGBlendModeNormal);
  222689. }
  222690. else
  222691. {
  222692. if (state->fillType.isColour())
  222693. {
  222694. CGContextFillRect (context, cgRect);
  222695. }
  222696. else if (state->fillType.isGradient())
  222697. {
  222698. CGContextSaveGState (context);
  222699. CGContextClipToRect (context, cgRect);
  222700. drawGradient();
  222701. CGContextRestoreGState (context);
  222702. }
  222703. else
  222704. {
  222705. CGContextSaveGState (context);
  222706. CGContextClipToRect (context, cgRect);
  222707. drawImage (*(state->fillType.image), state->fillType.image->getBounds(), state->fillType.transform, true);
  222708. CGContextRestoreGState (context);
  222709. }
  222710. }
  222711. }
  222712. void fillPath (const Path& path, const AffineTransform& transform)
  222713. {
  222714. CGContextSaveGState (context);
  222715. if (state->fillType.isColour())
  222716. {
  222717. flip();
  222718. applyTransform (transform);
  222719. createPath (path);
  222720. if (path.isUsingNonZeroWinding())
  222721. CGContextFillPath (context);
  222722. else
  222723. CGContextEOFillPath (context);
  222724. }
  222725. else
  222726. {
  222727. createPath (path, transform);
  222728. if (path.isUsingNonZeroWinding())
  222729. CGContextClip (context);
  222730. else
  222731. CGContextEOClip (context);
  222732. if (state->fillType.isGradient())
  222733. drawGradient();
  222734. else
  222735. drawImage (*(state->fillType.image), state->fillType.image->getBounds(), state->fillType.transform, true);
  222736. }
  222737. CGContextRestoreGState (context);
  222738. }
  222739. void drawImage (const Image& sourceImage, const Rectangle<int>& srcClip,
  222740. const AffineTransform& transform, const bool fillEntireClipAsTiles)
  222741. {
  222742. jassert (sourceImage.getBounds().contains (srcClip));
  222743. CGImageRef fullImage = CoreGraphicsImage::createImage (sourceImage, false, rgbColourSpace);
  222744. CGImageRef image = fullImage;
  222745. if (srcClip != sourceImage.getBounds())
  222746. {
  222747. image = CGImageCreateWithImageInRect (fullImage, CGRectMake (srcClip.getX(), srcClip.getY(),
  222748. srcClip.getWidth(), srcClip.getHeight()));
  222749. CGImageRelease (fullImage);
  222750. }
  222751. CGContextSaveGState (context);
  222752. CGContextSetAlpha (context, state->fillType.getOpacity());
  222753. flip();
  222754. applyTransform (AffineTransform::scale (1.0f, -1.0f).translated (0, srcClip.getHeight()).followedBy (transform));
  222755. CGRect imageRect = CGRectMake (0, 0, srcClip.getWidth(), srcClip.getHeight());
  222756. if (fillEntireClipAsTiles)
  222757. {
  222758. #if JUCE_IPHONE
  222759. CGContextDrawTiledImage (context, imageRect, image);
  222760. #else
  222761. #if MAC_OS_X_VERSION_MAX_ALLOWED >= MAC_OS_X_VERSION_10_5
  222762. // There's a bug in CGContextDrawTiledImage that makes it incredibly slow
  222763. // if it's doing a transformation - it's quicker to just draw lots of images manually
  222764. if (CGContextDrawTiledImage != 0 && transform.isOnlyTranslation())
  222765. CGContextDrawTiledImage (context, imageRect, image);
  222766. else
  222767. #endif
  222768. {
  222769. // Fallback to manually doing a tiled fill on 10.4
  222770. CGRect clip = CGRectIntegral (CGContextGetClipBoundingBox (context));
  222771. const int iw = srcClip.getWidth();
  222772. const int ih = srcClip.getHeight();
  222773. int x = 0, y = 0;
  222774. while (x > clip.origin.x) x -= iw;
  222775. while (y > clip.origin.y) y -= ih;
  222776. const int right = (int) (clip.origin.x + clip.size.width);
  222777. const int bottom = (int) (clip.origin.y + clip.size.height);
  222778. while (y < bottom)
  222779. {
  222780. for (int x2 = x; x2 < right; x2 += iw)
  222781. CGContextDrawImage (context, CGRectMake (x2, y, iw, ih), image);
  222782. y += ih;
  222783. }
  222784. }
  222785. #endif
  222786. }
  222787. else
  222788. {
  222789. CGContextDrawImage (context, imageRect, image);
  222790. }
  222791. CGImageRelease (image); // (This causes a memory bug in iPhone sim 3.0 - try upgrading to a later version if you hit this)
  222792. CGContextRestoreGState (context);
  222793. }
  222794. void drawLine (double x1, double y1, double x2, double y2)
  222795. {
  222796. CGContextSetLineCap (context, kCGLineCapSquare);
  222797. CGContextSetLineWidth (context, 1.0f);
  222798. CGContextSetRGBStrokeColor (context,
  222799. state->fillType.colour.getFloatRed(), state->fillType.colour.getFloatGreen(),
  222800. state->fillType.colour.getFloatBlue(), state->fillType.colour.getFloatAlpha());
  222801. CGPoint line[] = { { (CGFloat) x1, flipHeight - (CGFloat) y1 },
  222802. { (CGFloat) x2, flipHeight - (CGFloat) y2 } };
  222803. CGContextStrokeLineSegments (context, line, 1);
  222804. }
  222805. void drawVerticalLine (const int x, double top, double bottom)
  222806. {
  222807. #if MAC_OS_X_VERSION_MIN_REQUIRED > MAC_OS_X_VERSION_10_5
  222808. CGContextFillRect (context, CGRectMake (x, flipHeight - (float) bottom, 1.0f, (float) (bottom - top)));
  222809. #else
  222810. // On Leopard, unless both co-ordinates are non-integer, it disables anti-aliasing, so nudge
  222811. // the x co-ord slightly to trick it..
  222812. CGContextFillRect (context, CGRectMake (x + 1.0f / 256.0f, flipHeight - (float) bottom, 1.0f + 1.0f / 256.0f, (float) (bottom - top)));
  222813. #endif
  222814. }
  222815. void drawHorizontalLine (const int y, double left, double right)
  222816. {
  222817. #if MAC_OS_X_VERSION_MIN_REQUIRED > MAC_OS_X_VERSION_10_5
  222818. CGContextFillRect (context, CGRectMake ((float) left, flipHeight - (y + 1.0f), (float) (right - left), 1.0f));
  222819. #else
  222820. // On Leopard, unless both co-ordinates are non-integer, it disables anti-aliasing, so nudge
  222821. // the x co-ord slightly to trick it..
  222822. CGContextFillRect (context, CGRectMake ((float) left, flipHeight - (y + (1.0f + 1.0f / 256.0f)), (float) (right - left), 1.0f + 1.0f / 256.0f));
  222823. #endif
  222824. }
  222825. void setFont (const Font& newFont)
  222826. {
  222827. if (state->font != newFont)
  222828. {
  222829. state->fontRef = 0;
  222830. state->font = newFont;
  222831. MacTypeface* mf = dynamic_cast <MacTypeface*> (state->font.getTypeface());
  222832. if (mf != 0)
  222833. {
  222834. state->fontRef = mf->fontRef;
  222835. CGContextSetFont (context, state->fontRef);
  222836. CGContextSetFontSize (context, state->font.getHeight() * mf->fontHeightToCGSizeFactor);
  222837. state->fontTransform = mf->renderingTransform;
  222838. state->fontTransform.a *= state->font.getHorizontalScale();
  222839. CGContextSetTextMatrix (context, state->fontTransform);
  222840. }
  222841. }
  222842. }
  222843. const Font getFont()
  222844. {
  222845. return state->font;
  222846. }
  222847. void drawGlyph (int glyphNumber, const AffineTransform& transform)
  222848. {
  222849. if (state->fontRef != 0 && state->fillType.isColour())
  222850. {
  222851. if (transform.isOnlyTranslation())
  222852. {
  222853. CGGlyph g = glyphNumber;
  222854. CGContextShowGlyphsAtPoint (context, transform.getTranslationX(),
  222855. flipHeight - roundToInt (transform.getTranslationY()), &g, 1);
  222856. }
  222857. else
  222858. {
  222859. CGContextSaveGState (context);
  222860. flip();
  222861. applyTransform (transform);
  222862. CGAffineTransform t = state->fontTransform;
  222863. t.d = -t.d;
  222864. CGContextSetTextMatrix (context, t);
  222865. CGGlyph g = glyphNumber;
  222866. CGContextShowGlyphsAtPoint (context, 0, 0, &g, 1);
  222867. CGContextSetTextMatrix (context, state->fontTransform);
  222868. CGContextRestoreGState (context);
  222869. }
  222870. }
  222871. else
  222872. {
  222873. Path p;
  222874. Font& f = state->font;
  222875. f.getTypeface()->getOutlineForGlyph (glyphNumber, p);
  222876. fillPath (p, AffineTransform::scale (f.getHeight() * f.getHorizontalScale(), f.getHeight())
  222877. .followedBy (transform));
  222878. }
  222879. }
  222880. private:
  222881. CGContextRef context;
  222882. const CGFloat flipHeight;
  222883. CGColorSpaceRef rgbColourSpace, greyColourSpace;
  222884. CGFunctionCallbacks gradientCallbacks;
  222885. struct SavedState
  222886. {
  222887. SavedState()
  222888. : font (1.0f), fontRef (0), fontTransform (CGAffineTransformIdentity)
  222889. {
  222890. }
  222891. SavedState (const SavedState& other)
  222892. : fillType (other.fillType), font (other.font), fontRef (other.fontRef),
  222893. fontTransform (other.fontTransform)
  222894. {
  222895. }
  222896. ~SavedState()
  222897. {
  222898. }
  222899. FillType fillType;
  222900. Font font;
  222901. CGFontRef fontRef;
  222902. CGAffineTransform fontTransform;
  222903. };
  222904. ScopedPointer <SavedState> state;
  222905. OwnedArray <SavedState> stateStack;
  222906. HeapBlock <PixelARGB> gradientLookupTable;
  222907. int numGradientLookupEntries;
  222908. static void gradientCallback (void* info, const CGFloat* inData, CGFloat* outData)
  222909. {
  222910. const CoreGraphicsContext* const g = static_cast <const CoreGraphicsContext*> (info);
  222911. const int index = roundToInt (g->numGradientLookupEntries * inData[0]);
  222912. PixelARGB colour (g->gradientLookupTable [jlimit (0, g->numGradientLookupEntries, index)]);
  222913. colour.unpremultiply();
  222914. outData[0] = colour.getRed() / 255.0f;
  222915. outData[1] = colour.getGreen() / 255.0f;
  222916. outData[2] = colour.getBlue() / 255.0f;
  222917. outData[3] = colour.getAlpha() / 255.0f;
  222918. }
  222919. CGShadingRef createGradient (const AffineTransform& transform, ColourGradient gradient)
  222920. {
  222921. numGradientLookupEntries = gradient.createLookupTable (transform, gradientLookupTable);
  222922. --numGradientLookupEntries;
  222923. CGShadingRef result = 0;
  222924. CGFunctionRef function = CGFunctionCreate (this, 1, 0, 4, 0, &gradientCallbacks);
  222925. CGPoint p1 (CGPointMake (gradient.x1, gradient.y1));
  222926. if (gradient.isRadial)
  222927. {
  222928. result = CGShadingCreateRadial (rgbColourSpace, p1, 0,
  222929. p1, hypotf (gradient.x1 - gradient.x2, gradient.y1 - gradient.y2),
  222930. function, true, true);
  222931. }
  222932. else
  222933. {
  222934. result = CGShadingCreateAxial (rgbColourSpace, p1,
  222935. CGPointMake (gradient.x2, gradient.y2),
  222936. function, true, true);
  222937. }
  222938. CGFunctionRelease (function);
  222939. return result;
  222940. }
  222941. void drawGradient()
  222942. {
  222943. flip();
  222944. applyTransform (state->fillType.transform);
  222945. CGContextSetInterpolationQuality (context, kCGInterpolationDefault); // (This is required for 10.4, where there's a crash if
  222946. // you draw a gradient with high quality interp enabled).
  222947. CGShadingRef shading = createGradient (state->fillType.transform, *(state->fillType.gradient));
  222948. CGContextSetAlpha (context, state->fillType.getOpacity());
  222949. CGContextDrawShading (context, shading);
  222950. CGShadingRelease (shading);
  222951. }
  222952. void createPath (const Path& path) const
  222953. {
  222954. CGContextBeginPath (context);
  222955. Path::Iterator i (path);
  222956. while (i.next())
  222957. {
  222958. switch (i.elementType)
  222959. {
  222960. case Path::Iterator::startNewSubPath:
  222961. CGContextMoveToPoint (context, i.x1, i.y1);
  222962. break;
  222963. case Path::Iterator::lineTo:
  222964. CGContextAddLineToPoint (context, i.x1, i.y1);
  222965. break;
  222966. case Path::Iterator::quadraticTo:
  222967. CGContextAddQuadCurveToPoint (context, i.x1, i.y1, i.x2, i.y2);
  222968. break;
  222969. case Path::Iterator::cubicTo:
  222970. CGContextAddCurveToPoint (context, i.x1, i.y1, i.x2, i.y2, i.x3, i.y3);
  222971. break;
  222972. case Path::Iterator::closePath:
  222973. CGContextClosePath (context); break;
  222974. default:
  222975. jassertfalse
  222976. break;
  222977. }
  222978. }
  222979. }
  222980. void createPath (const Path& path, const AffineTransform& transform) const
  222981. {
  222982. CGContextBeginPath (context);
  222983. Path::Iterator i (path);
  222984. while (i.next())
  222985. {
  222986. switch (i.elementType)
  222987. {
  222988. case Path::Iterator::startNewSubPath:
  222989. transform.transformPoint (i.x1, i.y1);
  222990. CGContextMoveToPoint (context, i.x1, flipHeight - i.y1);
  222991. break;
  222992. case Path::Iterator::lineTo:
  222993. transform.transformPoint (i.x1, i.y1);
  222994. CGContextAddLineToPoint (context, i.x1, flipHeight - i.y1);
  222995. break;
  222996. case Path::Iterator::quadraticTo:
  222997. transform.transformPoint (i.x1, i.y1);
  222998. transform.transformPoint (i.x2, i.y2);
  222999. CGContextAddQuadCurveToPoint (context, i.x1, flipHeight - i.y1, i.x2, flipHeight - i.y2);
  223000. break;
  223001. case Path::Iterator::cubicTo:
  223002. transform.transformPoint (i.x1, i.y1);
  223003. transform.transformPoint (i.x2, i.y2);
  223004. transform.transformPoint (i.x3, i.y3);
  223005. CGContextAddCurveToPoint (context, i.x1, flipHeight - i.y1, i.x2, flipHeight - i.y2, i.x3, flipHeight - i.y3);
  223006. break;
  223007. case Path::Iterator::closePath:
  223008. CGContextClosePath (context); break;
  223009. default:
  223010. jassertfalse
  223011. break;
  223012. }
  223013. }
  223014. }
  223015. void flip() const
  223016. {
  223017. CGContextConcatCTM (context, CGAffineTransformMake (1, 0, 0, -1, 0, flipHeight));
  223018. }
  223019. void applyTransform (const AffineTransform& transform) const
  223020. {
  223021. CGAffineTransform t;
  223022. t.a = transform.mat00;
  223023. t.b = transform.mat10;
  223024. t.c = transform.mat01;
  223025. t.d = transform.mat11;
  223026. t.tx = transform.mat02;
  223027. t.ty = transform.mat12;
  223028. CGContextConcatCTM (context, t);
  223029. }
  223030. CoreGraphicsContext (const CoreGraphicsContext&);
  223031. CoreGraphicsContext& operator= (const CoreGraphicsContext&);
  223032. };
  223033. LowLevelGraphicsContext* CoreGraphicsImage::createLowLevelContext()
  223034. {
  223035. return new CoreGraphicsContext (context, imageHeight);
  223036. }
  223037. #endif
  223038. /*** End of inlined file: juce_mac_CoreGraphicsContext.mm ***/
  223039. /*** Start of inlined file: juce_iphone_UIViewComponentPeer.mm ***/
  223040. // (This file gets included by juce_mac_NativeCode.mm, rather than being
  223041. // compiled on its own).
  223042. #if JUCE_INCLUDED_FILE
  223043. class UIViewComponentPeer;
  223044. END_JUCE_NAMESPACE
  223045. #define JuceUIView MakeObjCClassName(JuceUIView)
  223046. @interface JuceUIView : UIView <UITextFieldDelegate>
  223047. {
  223048. @public
  223049. UIViewComponentPeer* owner;
  223050. UITextField *hiddenTextField;
  223051. }
  223052. - (JuceUIView*) initWithOwner: (UIViewComponentPeer*) owner withFrame: (CGRect) frame;
  223053. - (void) dealloc;
  223054. - (void) drawRect: (CGRect) r;
  223055. - (void) touchesBegan: (NSSet*) touches withEvent: (UIEvent*) event;
  223056. - (void) touchesMoved: (NSSet*) touches withEvent: (UIEvent*) event;
  223057. - (void) touchesEnded: (NSSet*) touches withEvent: (UIEvent*) event;
  223058. - (void) touchesCancelled: (NSSet*) touches withEvent: (UIEvent*) event;
  223059. - (BOOL) becomeFirstResponder;
  223060. - (BOOL) resignFirstResponder;
  223061. - (BOOL) canBecomeFirstResponder;
  223062. - (void) asyncRepaint: (id) rect;
  223063. - (BOOL) textField: (UITextField*) textField shouldChangeCharactersInRange: (NSRange) range replacementString: (NSString*) string;
  223064. - (BOOL) textFieldShouldClear: (UITextField*) textField;
  223065. - (BOOL) textFieldShouldReturn: (UITextField*) textField;
  223066. @end
  223067. #define JuceUIWindow MakeObjCClassName(JuceUIWindow)
  223068. @interface JuceUIWindow : UIWindow
  223069. {
  223070. @private
  223071. UIViewComponentPeer* owner;
  223072. bool isZooming;
  223073. }
  223074. - (void) setOwner: (UIViewComponentPeer*) owner;
  223075. - (void) becomeKeyWindow;
  223076. @end
  223077. BEGIN_JUCE_NAMESPACE
  223078. class UIViewComponentPeer : public ComponentPeer,
  223079. public FocusChangeListener
  223080. {
  223081. public:
  223082. UIViewComponentPeer (Component* const component,
  223083. const int windowStyleFlags,
  223084. UIView* viewToAttachTo);
  223085. ~UIViewComponentPeer();
  223086. void* getNativeHandle() const;
  223087. void setVisible (bool shouldBeVisible);
  223088. void setTitle (const String& title);
  223089. void setPosition (int x, int y);
  223090. void setSize (int w, int h);
  223091. void setBounds (int x, int y, int w, int h, bool isNowFullScreen);
  223092. const Rectangle<int> getBounds() const;
  223093. const Rectangle<int> getBounds (const bool global) const;
  223094. const Point<int> getScreenPosition() const;
  223095. const Point<int> relativePositionToGlobal (const Point<int>& relativePosition);
  223096. const Point<int> globalPositionToRelative (const Point<int>& screenPosition);
  223097. void setMinimised (bool shouldBeMinimised);
  223098. bool isMinimised() const;
  223099. void setFullScreen (bool shouldBeFullScreen);
  223100. bool isFullScreen() const;
  223101. bool contains (const Point<int>& position, bool trueIfInAChildWindow) const;
  223102. const BorderSize getFrameSize() const;
  223103. bool setAlwaysOnTop (bool alwaysOnTop);
  223104. void toFront (bool makeActiveWindow);
  223105. void toBehind (ComponentPeer* other);
  223106. void setIcon (const Image& newIcon);
  223107. virtual void drawRect (CGRect r);
  223108. virtual bool canBecomeKeyWindow();
  223109. virtual bool windowShouldClose();
  223110. virtual void redirectMovedOrResized();
  223111. virtual CGRect constrainRect (CGRect r);
  223112. virtual void viewFocusGain();
  223113. virtual void viewFocusLoss();
  223114. bool isFocused() const;
  223115. void grabFocus();
  223116. void textInputRequired (const Point<int>& position);
  223117. virtual BOOL textFieldReplaceCharacters (const Range<int>& range, const String& text);
  223118. virtual BOOL textFieldShouldClear();
  223119. virtual BOOL textFieldShouldReturn();
  223120. void updateHiddenTextContent (TextInputTarget* target);
  223121. void globalFocusChanged (Component*);
  223122. void handleTouches (UIEvent* e, bool isDown, bool isUp, bool isCancel);
  223123. void repaint (int x, int y, int w, int h);
  223124. void performAnyPendingRepaintsNow();
  223125. juce_UseDebuggingNewOperator
  223126. UIWindow* window;
  223127. JuceUIView* view;
  223128. bool isSharedWindow, fullScreen, insideDrawRect;
  223129. static ModifierKeys currentModifiers;
  223130. static int64 getMouseTime (UIEvent* e)
  223131. {
  223132. return (Time::currentTimeMillis() - Time::getMillisecondCounter())
  223133. + (int64) ([e timestamp] * 1000.0);
  223134. }
  223135. Array <UITouch*> currentTouches;
  223136. };
  223137. END_JUCE_NAMESPACE
  223138. @implementation JuceUIView
  223139. - (JuceUIView*) initWithOwner: (UIViewComponentPeer*) owner_
  223140. withFrame: (CGRect) frame
  223141. {
  223142. [super initWithFrame: frame];
  223143. owner = owner_;
  223144. hiddenTextField = [[UITextField alloc] initWithFrame: CGRectMake (0, 0, 0, 0)];
  223145. [self addSubview: hiddenTextField];
  223146. hiddenTextField.delegate = self;
  223147. return self;
  223148. }
  223149. - (void) dealloc
  223150. {
  223151. [hiddenTextField removeFromSuperview];
  223152. [hiddenTextField release];
  223153. [super dealloc];
  223154. }
  223155. - (void) drawRect: (CGRect) r
  223156. {
  223157. if (owner != 0)
  223158. owner->drawRect (r);
  223159. }
  223160. bool KeyPress::isKeyCurrentlyDown (const int keyCode)
  223161. {
  223162. return false;
  223163. }
  223164. ModifierKeys UIViewComponentPeer::currentModifiers;
  223165. const ModifierKeys ModifierKeys::getCurrentModifiersRealtime() throw()
  223166. {
  223167. return UIViewComponentPeer::currentModifiers;
  223168. }
  223169. void ModifierKeys::updateCurrentModifiers() throw()
  223170. {
  223171. currentModifiers = UIViewComponentPeer::currentModifiers;
  223172. }
  223173. JUCE_NAMESPACE::Point<int> juce_lastMousePos;
  223174. - (void) touchesBegan: (NSSet*) touches withEvent: (UIEvent*) event
  223175. {
  223176. if (owner != 0)
  223177. owner->handleTouches (event, true, false, false);
  223178. }
  223179. - (void) touchesMoved: (NSSet*) touches withEvent: (UIEvent*) event
  223180. {
  223181. if (owner != 0)
  223182. owner->handleTouches (event, false, false, false);
  223183. }
  223184. - (void) touchesEnded: (NSSet*) touches withEvent: (UIEvent*) event
  223185. {
  223186. if (owner != 0)
  223187. owner->handleTouches (event, false, true, false);
  223188. }
  223189. - (void) touchesCancelled: (NSSet*) touches withEvent: (UIEvent*) event
  223190. {
  223191. if (owner != 0)
  223192. owner->handleTouches (event, false, true, true);
  223193. [self touchesEnded: touches withEvent: event];
  223194. }
  223195. - (BOOL) becomeFirstResponder
  223196. {
  223197. if (owner != 0)
  223198. owner->viewFocusGain();
  223199. return true;
  223200. }
  223201. - (BOOL) resignFirstResponder
  223202. {
  223203. if (owner != 0)
  223204. owner->viewFocusLoss();
  223205. return true;
  223206. }
  223207. - (BOOL) canBecomeFirstResponder
  223208. {
  223209. return owner != 0 && owner->canBecomeKeyWindow();
  223210. }
  223211. - (void) asyncRepaint: (id) rect
  223212. {
  223213. CGRect* r = (CGRect*) [((NSData*) rect) bytes];
  223214. [self setNeedsDisplayInRect: *r];
  223215. }
  223216. - (BOOL) textField: (UITextField*) textField shouldChangeCharactersInRange: (NSRange) range replacementString: (NSString*) text
  223217. {
  223218. return owner->textFieldReplaceCharacters (Range<int> (range.location, range.location + range.length),
  223219. nsStringToJuce (text));
  223220. }
  223221. - (BOOL) textFieldShouldClear: (UITextField*) textField
  223222. {
  223223. return owner->textFieldShouldClear();
  223224. }
  223225. - (BOOL) textFieldShouldReturn: (UITextField*) textField
  223226. {
  223227. return owner->textFieldShouldReturn();
  223228. }
  223229. @end
  223230. @implementation JuceUIWindow
  223231. - (void) setOwner: (UIViewComponentPeer*) owner_
  223232. {
  223233. owner = owner_;
  223234. isZooming = false;
  223235. }
  223236. - (void) becomeKeyWindow
  223237. {
  223238. [super becomeKeyWindow];
  223239. if (owner != 0)
  223240. owner->grabFocus();
  223241. }
  223242. @end
  223243. BEGIN_JUCE_NAMESPACE
  223244. UIViewComponentPeer::UIViewComponentPeer (Component* const component,
  223245. const int windowStyleFlags,
  223246. UIView* viewToAttachTo)
  223247. : ComponentPeer (component, windowStyleFlags),
  223248. window (0),
  223249. view (0),
  223250. isSharedWindow (viewToAttachTo != 0),
  223251. fullScreen (false),
  223252. insideDrawRect (false)
  223253. {
  223254. CGRect r = CGRectMake (0, 0, (float) component->getWidth(), (float) component->getHeight());
  223255. view = [[JuceUIView alloc] initWithOwner: this withFrame: r];
  223256. if (isSharedWindow)
  223257. {
  223258. window = [viewToAttachTo window];
  223259. [viewToAttachTo addSubview: view];
  223260. setVisible (component->isVisible());
  223261. }
  223262. else
  223263. {
  223264. r.origin.x = (float) component->getX();
  223265. r.origin.y = (float) component->getY();
  223266. r.origin.y = [[UIScreen mainScreen] bounds].size.height - (r.origin.y + r.size.height);
  223267. window = [[JuceUIWindow alloc] init];
  223268. window.frame = r;
  223269. window.opaque = component->isOpaque();
  223270. view.opaque = component->isOpaque();
  223271. window.backgroundColor = [[UIColor blackColor] colorWithAlphaComponent: 0];
  223272. view.backgroundColor = [[UIColor blackColor] colorWithAlphaComponent: 0];
  223273. [((JuceUIWindow*) window) setOwner: this];
  223274. if (component->isAlwaysOnTop())
  223275. window.windowLevel = UIWindowLevelAlert;
  223276. [window addSubview: view];
  223277. view.frame = CGRectMake (0, 0, r.size.width, r.size.height);
  223278. view.hidden = ! component->isVisible();
  223279. window.hidden = ! component->isVisible();
  223280. view.multipleTouchEnabled = YES;
  223281. }
  223282. setTitle (component->getName());
  223283. Desktop::getInstance().addFocusChangeListener (this);
  223284. }
  223285. UIViewComponentPeer::~UIViewComponentPeer()
  223286. {
  223287. Desktop::getInstance().removeFocusChangeListener (this);
  223288. view->owner = 0;
  223289. [view removeFromSuperview];
  223290. [view release];
  223291. if (! isSharedWindow)
  223292. {
  223293. [((JuceUIWindow*) window) setOwner: 0];
  223294. [window release];
  223295. }
  223296. }
  223297. void* UIViewComponentPeer::getNativeHandle() const
  223298. {
  223299. return view;
  223300. }
  223301. void UIViewComponentPeer::setVisible (bool shouldBeVisible)
  223302. {
  223303. view.hidden = ! shouldBeVisible;
  223304. if (! isSharedWindow)
  223305. window.hidden = ! shouldBeVisible;
  223306. }
  223307. void UIViewComponentPeer::setTitle (const String& title)
  223308. {
  223309. // xxx is this possible?
  223310. }
  223311. void UIViewComponentPeer::setPosition (int x, int y)
  223312. {
  223313. setBounds (x, y, component->getWidth(), component->getHeight(), false);
  223314. }
  223315. void UIViewComponentPeer::setSize (int w, int h)
  223316. {
  223317. setBounds (component->getX(), component->getY(), w, h, false);
  223318. }
  223319. void UIViewComponentPeer::setBounds (int x, int y, int w, int h, const bool isNowFullScreen)
  223320. {
  223321. fullScreen = isNowFullScreen;
  223322. w = jmax (0, w);
  223323. h = jmax (0, h);
  223324. CGRect r;
  223325. r.origin.x = (float) x;
  223326. r.origin.y = (float) y;
  223327. r.size.width = (float) w;
  223328. r.size.height = (float) h;
  223329. if (isSharedWindow)
  223330. {
  223331. //r.origin.y = [[view superview] frame].size.height - (r.origin.y + r.size.height);
  223332. if ([view frame].size.width != r.size.width
  223333. || [view frame].size.height != r.size.height)
  223334. [view setNeedsDisplay];
  223335. view.frame = r;
  223336. }
  223337. else
  223338. {
  223339. window.frame = r;
  223340. view.frame = CGRectMake (0, 0, r.size.width, r.size.height);
  223341. }
  223342. }
  223343. const Rectangle<int> UIViewComponentPeer::getBounds (const bool global) const
  223344. {
  223345. CGRect r = [view frame];
  223346. if (global && [view window] != 0)
  223347. {
  223348. r = [view convertRect: r toView: nil];
  223349. CGRect wr = [[view window] frame];
  223350. r.origin.x += wr.origin.x;
  223351. r.origin.y += wr.origin.y;
  223352. }
  223353. return Rectangle<int> ((int) r.origin.x, (int) r.origin.y,
  223354. (int) r.size.width, (int) r.size.height);
  223355. }
  223356. const Rectangle<int> UIViewComponentPeer::getBounds() const
  223357. {
  223358. return getBounds (! isSharedWindow);
  223359. }
  223360. const Point<int> UIViewComponentPeer::getScreenPosition() const
  223361. {
  223362. return getBounds (true).getPosition();
  223363. }
  223364. const Point<int> UIViewComponentPeer::relativePositionToGlobal (const Point<int>& relativePosition)
  223365. {
  223366. return relativePosition + getScreenPosition();
  223367. }
  223368. const Point<int> UIViewComponentPeer::globalPositionToRelative (const Point<int>& screenPosition)
  223369. {
  223370. return screenPosition - getScreenPosition();
  223371. }
  223372. CGRect UIViewComponentPeer::constrainRect (CGRect r)
  223373. {
  223374. if (constrainer != 0)
  223375. {
  223376. CGRect current = [window frame];
  223377. current.origin.y = [[UIScreen mainScreen] bounds].size.height - current.origin.y - current.size.height;
  223378. r.origin.y = [[UIScreen mainScreen] bounds].size.height - r.origin.y - r.size.height;
  223379. Rectangle<int> pos ((int) r.origin.x, (int) r.origin.y,
  223380. (int) r.size.width, (int) r.size.height);
  223381. Rectangle<int> original ((int) current.origin.x, (int) current.origin.y,
  223382. (int) current.size.width, (int) current.size.height);
  223383. constrainer->checkBounds (pos, original,
  223384. Desktop::getInstance().getAllMonitorDisplayAreas().getBounds(),
  223385. pos.getY() != original.getY() && pos.getBottom() == original.getBottom(),
  223386. pos.getX() != original.getX() && pos.getRight() == original.getRight(),
  223387. pos.getY() == original.getY() && pos.getBottom() != original.getBottom(),
  223388. pos.getX() == original.getX() && pos.getRight() != original.getRight());
  223389. r.origin.x = pos.getX();
  223390. r.origin.y = [[UIScreen mainScreen] bounds].size.height - r.size.height - pos.getY();
  223391. r.size.width = pos.getWidth();
  223392. r.size.height = pos.getHeight();
  223393. }
  223394. return r;
  223395. }
  223396. void UIViewComponentPeer::setMinimised (bool shouldBeMinimised)
  223397. {
  223398. // xxx
  223399. }
  223400. bool UIViewComponentPeer::isMinimised() const
  223401. {
  223402. return false;
  223403. }
  223404. void UIViewComponentPeer::setFullScreen (bool shouldBeFullScreen)
  223405. {
  223406. if (! isSharedWindow)
  223407. {
  223408. Rectangle<int> r (lastNonFullscreenBounds);
  223409. setMinimised (false);
  223410. if (fullScreen != shouldBeFullScreen)
  223411. {
  223412. if (shouldBeFullScreen)
  223413. r = Desktop::getInstance().getMainMonitorArea();
  223414. // (can't call the component's setBounds method because that'll reset our fullscreen flag)
  223415. if (r != getComponent()->getBounds() && ! r.isEmpty())
  223416. setBounds (r.getX(), r.getY(), r.getWidth(), r.getHeight(), shouldBeFullScreen);
  223417. }
  223418. }
  223419. }
  223420. bool UIViewComponentPeer::isFullScreen() const
  223421. {
  223422. return fullScreen;
  223423. }
  223424. bool UIViewComponentPeer::contains (const Point<int>& position, bool trueIfInAChildWindow) const
  223425. {
  223426. if (((unsigned int) position.getX()) >= (unsigned int) component->getWidth()
  223427. || ((unsigned int) position.getY()) >= (unsigned int) component->getHeight())
  223428. return false;
  223429. CGPoint p;
  223430. p.x = (float) position.getX();
  223431. p.y = (float) position.getY();
  223432. UIView* v = [view hitTest: p withEvent: nil];
  223433. if (trueIfInAChildWindow)
  223434. return v != nil;
  223435. return v == view;
  223436. }
  223437. const BorderSize UIViewComponentPeer::getFrameSize() const
  223438. {
  223439. BorderSize b;
  223440. if (! isSharedWindow)
  223441. {
  223442. CGRect v = [view convertRect: [view frame] toView: nil];
  223443. CGRect w = [window frame];
  223444. b.setTop ((int) (w.size.height - (v.origin.y + v.size.height)));
  223445. b.setBottom ((int) v.origin.y);
  223446. b.setLeft ((int) v.origin.x);
  223447. b.setRight ((int) (w.size.width - (v.origin.x + v.size.width)));
  223448. }
  223449. return b;
  223450. }
  223451. bool UIViewComponentPeer::setAlwaysOnTop (bool alwaysOnTop)
  223452. {
  223453. if (! isSharedWindow)
  223454. window.windowLevel = alwaysOnTop ? UIWindowLevelAlert : UIWindowLevelNormal;
  223455. return true;
  223456. }
  223457. void UIViewComponentPeer::toFront (bool makeActiveWindow)
  223458. {
  223459. if (isSharedWindow)
  223460. [[view superview] bringSubviewToFront: view];
  223461. if (window != 0 && component->isVisible())
  223462. [window makeKeyAndVisible];
  223463. }
  223464. void UIViewComponentPeer::toBehind (ComponentPeer* other)
  223465. {
  223466. UIViewComponentPeer* const otherPeer = dynamic_cast <UIViewComponentPeer*> (other);
  223467. jassert (otherPeer != 0); // wrong type of window?
  223468. if (otherPeer != 0)
  223469. {
  223470. if (isSharedWindow)
  223471. {
  223472. [[view superview] insertSubview: view belowSubview: otherPeer->view];
  223473. }
  223474. else
  223475. {
  223476. jassertfalse // don't know how to do this
  223477. }
  223478. }
  223479. }
  223480. void UIViewComponentPeer::setIcon (const Image& /*newIcon*/)
  223481. {
  223482. // to do..
  223483. }
  223484. void UIViewComponentPeer::handleTouches (UIEvent* event, const bool isDown, const bool isUp, bool isCancel)
  223485. {
  223486. NSArray* touches = [[event touchesForView: view] allObjects];
  223487. for (unsigned int i = 0; i < [touches count]; ++i)
  223488. {
  223489. UITouch* touch = [touches objectAtIndex: i];
  223490. CGPoint p = [touch locationInView: view];
  223491. const Point<int> pos ((int) p.x, (int) p.y);
  223492. juce_lastMousePos = pos + getScreenPosition();
  223493. const int64 time = getMouseTime (event);
  223494. int touchIndex = currentTouches.indexOf (touch);
  223495. if (touchIndex < 0)
  223496. {
  223497. touchIndex = currentTouches.size();
  223498. currentTouches.add (touch);
  223499. }
  223500. if (isDown)
  223501. {
  223502. currentModifiers = currentModifiers.withoutMouseButtons();
  223503. handleMouseEvent (touchIndex, pos, currentModifiers, time);
  223504. currentModifiers = currentModifiers.withoutMouseButtons().withFlags (ModifierKeys::leftButtonModifier);
  223505. }
  223506. else if (isUp)
  223507. {
  223508. currentModifiers = currentModifiers.withoutMouseButtons();
  223509. currentTouches.remove (touchIndex);
  223510. }
  223511. if (isCancel)
  223512. currentTouches.clear();
  223513. handleMouseEvent (touchIndex, pos, currentModifiers, time);
  223514. }
  223515. }
  223516. static UIViewComponentPeer* currentlyFocusedPeer = 0;
  223517. void UIViewComponentPeer::viewFocusGain()
  223518. {
  223519. if (currentlyFocusedPeer != this)
  223520. {
  223521. if (ComponentPeer::isValidPeer (currentlyFocusedPeer))
  223522. currentlyFocusedPeer->handleFocusLoss();
  223523. currentlyFocusedPeer = this;
  223524. handleFocusGain();
  223525. }
  223526. }
  223527. void UIViewComponentPeer::viewFocusLoss()
  223528. {
  223529. if (currentlyFocusedPeer == this)
  223530. {
  223531. currentlyFocusedPeer = 0;
  223532. handleFocusLoss();
  223533. }
  223534. }
  223535. void juce_HandleProcessFocusChange()
  223536. {
  223537. if (UIViewComponentPeer::isValidPeer (currentlyFocusedPeer))
  223538. {
  223539. if (Process::isForegroundProcess())
  223540. {
  223541. currentlyFocusedPeer->handleFocusGain();
  223542. ComponentPeer::bringModalComponentToFront();
  223543. }
  223544. else
  223545. {
  223546. currentlyFocusedPeer->handleFocusLoss();
  223547. // turn kiosk mode off if we lose focus..
  223548. Desktop::getInstance().setKioskModeComponent (0);
  223549. }
  223550. }
  223551. }
  223552. bool UIViewComponentPeer::isFocused() const
  223553. {
  223554. return isSharedWindow ? this == currentlyFocusedPeer
  223555. : (window != 0 && [window isKeyWindow]);
  223556. }
  223557. void UIViewComponentPeer::grabFocus()
  223558. {
  223559. if (window != 0)
  223560. {
  223561. [window makeKeyWindow];
  223562. viewFocusGain();
  223563. }
  223564. }
  223565. void UIViewComponentPeer::textInputRequired (const Point<int>&)
  223566. {
  223567. }
  223568. void UIViewComponentPeer::updateHiddenTextContent (TextInputTarget* target)
  223569. {
  223570. view->hiddenTextField.text = juceStringToNS (target->getTextInRange (Range<int> (0, target->getHighlightedRegion().getStart())));
  223571. }
  223572. BOOL UIViewComponentPeer::textFieldReplaceCharacters (const Range<int>& range, const String& text)
  223573. {
  223574. TextInputTarget* const target = findCurrentTextInputTarget();
  223575. if (target != 0)
  223576. {
  223577. const Range<int> currentSelection (target->getHighlightedRegion());
  223578. if (range.getLength() == 1 && text.isEmpty()) // (detect backspace)
  223579. if (currentSelection.isEmpty())
  223580. target->setHighlightedRegion (currentSelection.withStart (currentSelection.getStart() - 1));
  223581. target->insertTextAtCaret (text);
  223582. updateHiddenTextContent (target);
  223583. }
  223584. return NO;
  223585. }
  223586. BOOL UIViewComponentPeer::textFieldShouldClear()
  223587. {
  223588. TextInputTarget* const target = findCurrentTextInputTarget();
  223589. if (target != 0)
  223590. {
  223591. target->setHighlightedRegion (Range<int> (0, std::numeric_limits<int>::max()));
  223592. target->insertTextAtCaret (String::empty);
  223593. updateHiddenTextContent (target);
  223594. }
  223595. return YES;
  223596. }
  223597. BOOL UIViewComponentPeer::textFieldShouldReturn()
  223598. {
  223599. TextInputTarget* const target = findCurrentTextInputTarget();
  223600. if (target != 0)
  223601. {
  223602. target->insertTextAtCaret ("\n");
  223603. updateHiddenTextContent (target);
  223604. }
  223605. return YES;
  223606. }
  223607. void UIViewComponentPeer::globalFocusChanged (Component*)
  223608. {
  223609. TextInputTarget* const target = findCurrentTextInputTarget();
  223610. if (target != 0)
  223611. {
  223612. Component* comp = dynamic_cast<Component*> (target);
  223613. Point<int> pos (comp->relativePositionToOtherComponent (component, Point<int>()));
  223614. view->hiddenTextField.frame = CGRectMake (pos.getX(), pos.getY(), 0, 0);
  223615. updateHiddenTextContent (target);
  223616. [view->hiddenTextField becomeFirstResponder];
  223617. }
  223618. else
  223619. {
  223620. [view->hiddenTextField resignFirstResponder];
  223621. }
  223622. }
  223623. void UIViewComponentPeer::drawRect (CGRect r)
  223624. {
  223625. if (r.size.width < 1.0f || r.size.height < 1.0f)
  223626. return;
  223627. CGContextRef cg = UIGraphicsGetCurrentContext();
  223628. if (! component->isOpaque())
  223629. CGContextClearRect (cg, CGContextGetClipBoundingBox (cg));
  223630. CGContextConcatCTM (cg, CGAffineTransformMake (1, 0, 0, -1, 0, view.bounds.size.height));
  223631. CoreGraphicsContext g (cg, view.bounds.size.height);
  223632. insideDrawRect = true;
  223633. handlePaint (g);
  223634. insideDrawRect = false;
  223635. }
  223636. bool UIViewComponentPeer::canBecomeKeyWindow()
  223637. {
  223638. return (getStyleFlags() & JUCE_NAMESPACE::ComponentPeer::windowIgnoresKeyPresses) == 0;
  223639. }
  223640. bool UIViewComponentPeer::windowShouldClose()
  223641. {
  223642. if (! isValidPeer (this))
  223643. return YES;
  223644. handleUserClosingWindow();
  223645. return NO;
  223646. }
  223647. void UIViewComponentPeer::redirectMovedOrResized()
  223648. {
  223649. handleMovedOrResized();
  223650. }
  223651. void juce_setKioskComponent (Component* kioskModeComponent, bool enableOrDisable, bool allowMenusAndBars)
  223652. {
  223653. }
  223654. class AsyncRepaintMessage : public CallbackMessage
  223655. {
  223656. public:
  223657. UIViewComponentPeer* const peer;
  223658. const Rectangle<int> rect;
  223659. AsyncRepaintMessage (UIViewComponentPeer* const peer_, const Rectangle<int>& rect_)
  223660. : peer (peer_), rect (rect_)
  223661. {
  223662. }
  223663. void messageCallback()
  223664. {
  223665. if (ComponentPeer::isValidPeer (peer))
  223666. peer->repaint (rect.getX(), rect.getY(), rect.getWidth(), rect.getHeight());
  223667. }
  223668. };
  223669. void UIViewComponentPeer::repaint (int x, int y, int w, int h)
  223670. {
  223671. if (insideDrawRect || ! MessageManager::getInstance()->isThisTheMessageThread())
  223672. {
  223673. (new AsyncRepaintMessage (this, Rectangle<int> (x, y, w, h)))->post();
  223674. }
  223675. else
  223676. {
  223677. [view setNeedsDisplayInRect: CGRectMake ((float) x, (float) y, (float) w, (float) h)];
  223678. }
  223679. }
  223680. void UIViewComponentPeer::performAnyPendingRepaintsNow()
  223681. {
  223682. }
  223683. ComponentPeer* Component::createNewPeer (int styleFlags, void* windowToAttachTo)
  223684. {
  223685. return new UIViewComponentPeer (this, styleFlags, (UIView*) windowToAttachTo);
  223686. }
  223687. Image* juce_createIconForFile (const File& file)
  223688. {
  223689. return 0;
  223690. }
  223691. void Desktop::createMouseInputSources()
  223692. {
  223693. for (int i = 0; i < 10; ++i)
  223694. mouseSources.add (new MouseInputSource (i, false));
  223695. }
  223696. bool Desktop::canUseSemiTransparentWindows() throw()
  223697. {
  223698. return true;
  223699. }
  223700. const Point<int> Desktop::getMousePosition()
  223701. {
  223702. return juce_lastMousePos;
  223703. }
  223704. void Desktop::setMousePosition (const Point<int>&)
  223705. {
  223706. }
  223707. const int KeyPress::spaceKey = ' ';
  223708. const int KeyPress::returnKey = 0x0d;
  223709. const int KeyPress::escapeKey = 0x1b;
  223710. const int KeyPress::backspaceKey = 0x7f;
  223711. const int KeyPress::leftKey = 0x1000;
  223712. const int KeyPress::rightKey = 0x1001;
  223713. const int KeyPress::upKey = 0x1002;
  223714. const int KeyPress::downKey = 0x1003;
  223715. const int KeyPress::pageUpKey = 0x1004;
  223716. const int KeyPress::pageDownKey = 0x1005;
  223717. const int KeyPress::endKey = 0x1006;
  223718. const int KeyPress::homeKey = 0x1007;
  223719. const int KeyPress::deleteKey = 0x1008;
  223720. const int KeyPress::insertKey = -1;
  223721. const int KeyPress::tabKey = 9;
  223722. const int KeyPress::F1Key = 0x2001;
  223723. const int KeyPress::F2Key = 0x2002;
  223724. const int KeyPress::F3Key = 0x2003;
  223725. const int KeyPress::F4Key = 0x2004;
  223726. const int KeyPress::F5Key = 0x2005;
  223727. const int KeyPress::F6Key = 0x2006;
  223728. const int KeyPress::F7Key = 0x2007;
  223729. const int KeyPress::F8Key = 0x2008;
  223730. const int KeyPress::F9Key = 0x2009;
  223731. const int KeyPress::F10Key = 0x200a;
  223732. const int KeyPress::F11Key = 0x200b;
  223733. const int KeyPress::F12Key = 0x200c;
  223734. const int KeyPress::F13Key = 0x200d;
  223735. const int KeyPress::F14Key = 0x200e;
  223736. const int KeyPress::F15Key = 0x200f;
  223737. const int KeyPress::F16Key = 0x2010;
  223738. const int KeyPress::numberPad0 = 0x30020;
  223739. const int KeyPress::numberPad1 = 0x30021;
  223740. const int KeyPress::numberPad2 = 0x30022;
  223741. const int KeyPress::numberPad3 = 0x30023;
  223742. const int KeyPress::numberPad4 = 0x30024;
  223743. const int KeyPress::numberPad5 = 0x30025;
  223744. const int KeyPress::numberPad6 = 0x30026;
  223745. const int KeyPress::numberPad7 = 0x30027;
  223746. const int KeyPress::numberPad8 = 0x30028;
  223747. const int KeyPress::numberPad9 = 0x30029;
  223748. const int KeyPress::numberPadAdd = 0x3002a;
  223749. const int KeyPress::numberPadSubtract = 0x3002b;
  223750. const int KeyPress::numberPadMultiply = 0x3002c;
  223751. const int KeyPress::numberPadDivide = 0x3002d;
  223752. const int KeyPress::numberPadSeparator = 0x3002e;
  223753. const int KeyPress::numberPadDecimalPoint = 0x3002f;
  223754. const int KeyPress::numberPadEquals = 0x30030;
  223755. const int KeyPress::numberPadDelete = 0x30031;
  223756. const int KeyPress::playKey = 0x30000;
  223757. const int KeyPress::stopKey = 0x30001;
  223758. const int KeyPress::fastForwardKey = 0x30002;
  223759. const int KeyPress::rewindKey = 0x30003;
  223760. #endif
  223761. /*** End of inlined file: juce_iphone_UIViewComponentPeer.mm ***/
  223762. /*** Start of inlined file: juce_iphone_MessageManager.mm ***/
  223763. // (This file gets included by juce_mac_NativeCode.mm, rather than being
  223764. // compiled on its own).
  223765. #if JUCE_INCLUDED_FILE
  223766. struct CallbackMessagePayload
  223767. {
  223768. MessageCallbackFunction* function;
  223769. void* parameter;
  223770. void* volatile result;
  223771. bool volatile hasBeenExecuted;
  223772. };
  223773. END_JUCE_NAMESPACE
  223774. using namespace JUCE_NAMESPACE;
  223775. @interface JuceAppDelegate : NSObject <UIApplicationDelegate>
  223776. {
  223777. }
  223778. - (JuceAppDelegate*) init;
  223779. - (void) dealloc;
  223780. - (BOOL) application: (UIApplication*) application handleOpenURL: (NSURL*) url;
  223781. - (void) applicationDidBecomeActive: (NSNotification*) aNotification;
  223782. - (void) applicationDidResignActive: (NSNotification*) aNotification;
  223783. - (void) applicationWillUnhide: (NSNotification*) aNotification;
  223784. - (void) customEvent: (id) data;
  223785. - (void) performCallback: (id) info;
  223786. @end
  223787. @implementation JuceAppDelegate
  223788. - (JuceAppDelegate*) init
  223789. {
  223790. [super init];
  223791. [[UIApplication sharedApplication] setDelegate: self];
  223792. return self;
  223793. }
  223794. - (void) dealloc
  223795. {
  223796. [[UIApplication sharedApplication] setDelegate: nil];
  223797. [super dealloc];
  223798. }
  223799. - (BOOL) application: (UIApplication*) application handleOpenURL: (NSURL*) url
  223800. {
  223801. if (JUCEApplication::getInstance() != 0)
  223802. {
  223803. JUCEApplication::getInstance()->anotherInstanceStarted (nsStringToJuce ([url absoluteString]));
  223804. return YES;
  223805. }
  223806. return NO;
  223807. }
  223808. - (void) applicationDidBecomeActive: (NSNotification*) aNotification
  223809. {
  223810. juce_HandleProcessFocusChange();
  223811. }
  223812. - (void) applicationDidResignActive: (NSNotification*) aNotification
  223813. {
  223814. juce_HandleProcessFocusChange();
  223815. }
  223816. - (void) applicationWillUnhide: (NSNotification*) aNotification
  223817. {
  223818. juce_HandleProcessFocusChange();
  223819. }
  223820. - (void) customEvent: (id) n
  223821. {
  223822. NSData* data = (NSData*) n;
  223823. void* message = 0;
  223824. [data getBytes: &message length: sizeof (message)];
  223825. [data release];
  223826. if (message != 0)
  223827. MessageManager::getInstance()->deliverMessage (message);
  223828. }
  223829. - (void) performCallback: (id) info
  223830. {
  223831. if ([info isKindOfClass: [NSData class]])
  223832. {
  223833. CallbackMessagePayload* pl = (CallbackMessagePayload*) [((NSData*) info) bytes];
  223834. if (pl != 0)
  223835. {
  223836. pl->result = (*pl->function) (pl->parameter);
  223837. pl->hasBeenExecuted = true;
  223838. }
  223839. }
  223840. else
  223841. {
  223842. jassertfalse // should never get here!
  223843. }
  223844. }
  223845. @end
  223846. BEGIN_JUCE_NAMESPACE
  223847. static JuceAppDelegate* juceAppDelegate = 0;
  223848. void MessageManager::runDispatchLoop()
  223849. {
  223850. jassert (isThisTheMessageThread()); // must only be called by the message thread
  223851. runDispatchLoopUntil (-1);
  223852. }
  223853. void MessageManager::stopDispatchLoop()
  223854. {
  223855. exit (0); // iPhone apps get no mercy..
  223856. }
  223857. bool MessageManager::runDispatchLoopUntil (int millisecondsToRunFor)
  223858. {
  223859. const ScopedAutoReleasePool pool;
  223860. jassert (isThisTheMessageThread()); // must only be called by the message thread
  223861. uint32 endTime = Time::getMillisecondCounter() + millisecondsToRunFor;
  223862. NSDate* endDate = [NSDate dateWithTimeIntervalSinceNow: millisecondsToRunFor * 0.001];
  223863. while (! quitMessagePosted)
  223864. {
  223865. const ScopedAutoReleasePool pool;
  223866. [[NSRunLoop currentRunLoop] runMode: NSDefaultRunLoopMode
  223867. beforeDate: endDate];
  223868. if (millisecondsToRunFor >= 0 && Time::getMillisecondCounter() >= endTime)
  223869. break;
  223870. }
  223871. return ! quitMessagePosted;
  223872. }
  223873. static CFRunLoopRef runLoop = 0;
  223874. static CFRunLoopSourceRef runLoopSource = 0;
  223875. static Array <void*, CriticalSection>* pendingMessages = 0;
  223876. static void runLoopSourceCallback (void*)
  223877. {
  223878. if (pendingMessages != 0)
  223879. {
  223880. int numDispatched = 0;
  223881. do
  223882. {
  223883. void* const nextMessage = pendingMessages->remove (0);
  223884. if (nextMessage == 0)
  223885. return;
  223886. const ScopedAutoReleasePool pool;
  223887. MessageManager::getInstance()->deliverMessage (nextMessage);
  223888. } while (++numDispatched <= 4);
  223889. CFRunLoopSourceSignal (runLoopSource);
  223890. CFRunLoopWakeUp (runLoop);
  223891. }
  223892. }
  223893. void MessageManager::doPlatformSpecificInitialisation()
  223894. {
  223895. pendingMessages = new Array <void*, CriticalSection>();
  223896. runLoop = CFRunLoopGetCurrent();
  223897. CFRunLoopSourceContext sourceContext;
  223898. zerostruct (sourceContext);
  223899. sourceContext.perform = runLoopSourceCallback;
  223900. runLoopSource = CFRunLoopSourceCreate (kCFAllocatorDefault, 1, &sourceContext);
  223901. CFRunLoopAddSource (runLoop, runLoopSource, kCFRunLoopCommonModes);
  223902. if (juceAppDelegate == 0)
  223903. juceAppDelegate = [[JuceAppDelegate alloc] init];
  223904. }
  223905. void MessageManager::doPlatformSpecificShutdown()
  223906. {
  223907. CFRunLoopSourceInvalidate (runLoopSource);
  223908. CFRelease (runLoopSource);
  223909. runLoopSource = 0;
  223910. if (pendingMessages != 0)
  223911. {
  223912. while (pendingMessages->size() > 0)
  223913. delete ((Message*) pendingMessages->remove(0));
  223914. deleteAndZero (pendingMessages);
  223915. }
  223916. if (juceAppDelegate != 0)
  223917. {
  223918. [[NSRunLoop currentRunLoop] cancelPerformSelectorsWithTarget: juceAppDelegate];
  223919. [juceAppDelegate release];
  223920. juceAppDelegate = 0;
  223921. }
  223922. }
  223923. bool juce_postMessageToSystemQueue (void* message)
  223924. {
  223925. if (pendingMessages != 0)
  223926. {
  223927. pendingMessages->add (message);
  223928. CFRunLoopSourceSignal (runLoopSource);
  223929. CFRunLoopWakeUp (runLoop);
  223930. }
  223931. return true;
  223932. }
  223933. void MessageManager::broadcastMessage (const String& value) throw()
  223934. {
  223935. }
  223936. void* MessageManager::callFunctionOnMessageThread (MessageCallbackFunction* callback,
  223937. void* data)
  223938. {
  223939. if (isThisTheMessageThread())
  223940. {
  223941. return (*callback) (data);
  223942. }
  223943. else
  223944. {
  223945. // If a thread has a MessageManagerLock and then tries to call this method, it'll
  223946. // deadlock because the message manager is blocked from running, so can never
  223947. // call your function..
  223948. jassert (! MessageManager::getInstance()->currentThreadHasLockedMessageManager());
  223949. const ScopedAutoReleasePool pool;
  223950. CallbackMessagePayload cmp;
  223951. cmp.function = callback;
  223952. cmp.parameter = data;
  223953. cmp.result = 0;
  223954. cmp.hasBeenExecuted = false;
  223955. [juceAppDelegate performSelectorOnMainThread: @selector (performCallback:)
  223956. withObject: [NSData dataWithBytesNoCopy: &cmp
  223957. length: sizeof (cmp)
  223958. freeWhenDone: NO]
  223959. waitUntilDone: YES];
  223960. return cmp.result;
  223961. }
  223962. }
  223963. #endif
  223964. /*** End of inlined file: juce_iphone_MessageManager.mm ***/
  223965. /*** Start of inlined file: juce_mac_FileChooser.mm ***/
  223966. // (This file gets included by juce_mac_NativeCode.mm, rather than being
  223967. // compiled on its own).
  223968. #if JUCE_INCLUDED_FILE
  223969. #if JUCE_MAC
  223970. END_JUCE_NAMESPACE
  223971. using namespace JUCE_NAMESPACE;
  223972. #define JuceFileChooserDelegate MakeObjCClassName(JuceFileChooserDelegate)
  223973. #if defined (MAC_OS_X_VERSION_10_6) && MAC_OS_X_VERSION_MAX_ALLOWED >= MAC_OS_X_VERSION_10_6
  223974. @interface JuceFileChooserDelegate : NSObject <NSOpenSavePanelDelegate>
  223975. #else
  223976. @interface JuceFileChooserDelegate : NSObject
  223977. #endif
  223978. {
  223979. StringArray* filters;
  223980. }
  223981. - (JuceFileChooserDelegate*) initWithFilters: (StringArray*) filters_;
  223982. - (void) dealloc;
  223983. - (BOOL) panel: (id) sender shouldShowFilename: (NSString*) filename;
  223984. @end
  223985. @implementation JuceFileChooserDelegate
  223986. - (JuceFileChooserDelegate*) initWithFilters: (StringArray*) filters_
  223987. {
  223988. [super init];
  223989. filters = filters_;
  223990. return self;
  223991. }
  223992. - (void) dealloc
  223993. {
  223994. delete filters;
  223995. [super dealloc];
  223996. }
  223997. - (BOOL) panel: (id) sender shouldShowFilename: (NSString*) filename
  223998. {
  223999. const File f (nsStringToJuce (filename));
  224000. for (int i = filters->size(); --i >= 0;)
  224001. if (f.getFileName().matchesWildcard ((*filters)[i], true))
  224002. return true;
  224003. return f.isDirectory();
  224004. }
  224005. @end
  224006. BEGIN_JUCE_NAMESPACE
  224007. void FileChooser::showPlatformDialog (Array<File>& results,
  224008. const String& title,
  224009. const File& currentFileOrDirectory,
  224010. const String& filter,
  224011. bool selectsDirectory,
  224012. bool selectsFiles,
  224013. bool isSaveDialogue,
  224014. bool warnAboutOverwritingExistingFiles,
  224015. bool selectMultipleFiles,
  224016. FilePreviewComponent* extraInfoComponent)
  224017. {
  224018. const ScopedAutoReleasePool pool;
  224019. StringArray* filters = new StringArray();
  224020. filters->addTokens (filter.replaceCharacters (",:", ";;"), ";", String::empty);
  224021. filters->trim();
  224022. filters->removeEmptyStrings();
  224023. JuceFileChooserDelegate* delegate = [[JuceFileChooserDelegate alloc] initWithFilters: filters];
  224024. [delegate autorelease];
  224025. NSSavePanel* panel = isSaveDialogue ? [NSSavePanel savePanel]
  224026. : [NSOpenPanel openPanel];
  224027. [panel setTitle: juceStringToNS (title)];
  224028. if (! isSaveDialogue)
  224029. {
  224030. NSOpenPanel* openPanel = (NSOpenPanel*) panel;
  224031. [openPanel setCanChooseDirectories: selectsDirectory];
  224032. [openPanel setCanChooseFiles: selectsFiles];
  224033. [openPanel setAllowsMultipleSelection: selectMultipleFiles];
  224034. }
  224035. [panel setDelegate: delegate];
  224036. if (isSaveDialogue || selectsDirectory)
  224037. [panel setCanCreateDirectories: YES];
  224038. String directory, filename;
  224039. if (currentFileOrDirectory.isDirectory())
  224040. {
  224041. directory = currentFileOrDirectory.getFullPathName();
  224042. }
  224043. else
  224044. {
  224045. directory = currentFileOrDirectory.getParentDirectory().getFullPathName();
  224046. filename = currentFileOrDirectory.getFileName();
  224047. }
  224048. if ([panel runModalForDirectory: juceStringToNS (directory)
  224049. file: juceStringToNS (filename)]
  224050. == NSOKButton)
  224051. {
  224052. if (isSaveDialogue)
  224053. {
  224054. results.add (File (nsStringToJuce ([panel filename])));
  224055. }
  224056. else
  224057. {
  224058. NSOpenPanel* openPanel = (NSOpenPanel*) panel;
  224059. NSArray* urls = [openPanel filenames];
  224060. for (unsigned int i = 0; i < [urls count]; ++i)
  224061. {
  224062. NSString* f = [urls objectAtIndex: i];
  224063. results.add (File (nsStringToJuce (f)));
  224064. }
  224065. }
  224066. }
  224067. [panel setDelegate: nil];
  224068. }
  224069. #else
  224070. void FileChooser::showPlatformDialog (Array<File>& results,
  224071. const String& title,
  224072. const File& currentFileOrDirectory,
  224073. const String& filter,
  224074. bool selectsDirectory,
  224075. bool selectsFiles,
  224076. bool isSaveDialogue,
  224077. bool warnAboutOverwritingExistingFiles,
  224078. bool selectMultipleFiles,
  224079. FilePreviewComponent* extraInfoComponent)
  224080. {
  224081. const ScopedAutoReleasePool pool;
  224082. jassertfalse //xxx to do
  224083. }
  224084. #endif
  224085. #endif
  224086. /*** End of inlined file: juce_mac_FileChooser.mm ***/
  224087. /*** Start of inlined file: juce_mac_OpenGLComponent.mm ***/
  224088. // (This file gets included by juce_mac_NativeCode.mm, rather than being
  224089. // compiled on its own).
  224090. #if JUCE_INCLUDED_FILE && JUCE_OPENGL
  224091. #if JUCE_MAC
  224092. END_JUCE_NAMESPACE
  224093. #define ThreadSafeNSOpenGLView MakeObjCClassName(ThreadSafeNSOpenGLView)
  224094. @interface ThreadSafeNSOpenGLView : NSOpenGLView
  224095. {
  224096. CriticalSection* contextLock;
  224097. bool needsUpdate;
  224098. }
  224099. - (id) initWithFrame: (NSRect) frameRect pixelFormat: (NSOpenGLPixelFormat*) format;
  224100. - (bool) makeActive;
  224101. - (void) makeInactive;
  224102. - (void) reshape;
  224103. @end
  224104. @implementation ThreadSafeNSOpenGLView
  224105. - (id) initWithFrame: (NSRect) frameRect
  224106. pixelFormat: (NSOpenGLPixelFormat*) format
  224107. {
  224108. contextLock = new CriticalSection();
  224109. self = [super initWithFrame: frameRect pixelFormat: format];
  224110. if (self != nil)
  224111. [[NSNotificationCenter defaultCenter] addObserver: self
  224112. selector: @selector (_surfaceNeedsUpdate:)
  224113. name: NSViewGlobalFrameDidChangeNotification
  224114. object: self];
  224115. return self;
  224116. }
  224117. - (void) dealloc
  224118. {
  224119. [[NSNotificationCenter defaultCenter] removeObserver: self];
  224120. delete contextLock;
  224121. [super dealloc];
  224122. }
  224123. - (bool) makeActive
  224124. {
  224125. const ScopedLock sl (*contextLock);
  224126. if ([self openGLContext] == 0)
  224127. return false;
  224128. [[self openGLContext] makeCurrentContext];
  224129. if (needsUpdate)
  224130. {
  224131. [super update];
  224132. needsUpdate = false;
  224133. }
  224134. return true;
  224135. }
  224136. - (void) makeInactive
  224137. {
  224138. const ScopedLock sl (*contextLock);
  224139. [NSOpenGLContext clearCurrentContext];
  224140. }
  224141. - (void) _surfaceNeedsUpdate: (NSNotification*) notification
  224142. {
  224143. const ScopedLock sl (*contextLock);
  224144. needsUpdate = true;
  224145. }
  224146. - (void) update
  224147. {
  224148. const ScopedLock sl (*contextLock);
  224149. needsUpdate = true;
  224150. }
  224151. - (void) reshape
  224152. {
  224153. const ScopedLock sl (*contextLock);
  224154. needsUpdate = true;
  224155. }
  224156. @end
  224157. BEGIN_JUCE_NAMESPACE
  224158. class WindowedGLContext : public OpenGLContext
  224159. {
  224160. public:
  224161. WindowedGLContext (Component* const component,
  224162. const OpenGLPixelFormat& pixelFormat_,
  224163. NSOpenGLContext* sharedContext)
  224164. : renderContext (0),
  224165. pixelFormat (pixelFormat_)
  224166. {
  224167. jassert (component != 0);
  224168. NSOpenGLPixelFormatAttribute attribs [64];
  224169. int n = 0;
  224170. attribs[n++] = NSOpenGLPFADoubleBuffer;
  224171. attribs[n++] = NSOpenGLPFAAccelerated;
  224172. attribs[n++] = NSOpenGLPFAMPSafe; // NSOpenGLPFAAccelerated, NSOpenGLPFAMultiScreen, NSOpenGLPFASingleRenderer
  224173. attribs[n++] = NSOpenGLPFAColorSize;
  224174. attribs[n++] = (NSOpenGLPixelFormatAttribute) jmax (pixelFormat.redBits,
  224175. pixelFormat.greenBits,
  224176. pixelFormat.blueBits);
  224177. attribs[n++] = NSOpenGLPFAAlphaSize;
  224178. attribs[n++] = (NSOpenGLPixelFormatAttribute) pixelFormat.alphaBits;
  224179. attribs[n++] = NSOpenGLPFADepthSize;
  224180. attribs[n++] = (NSOpenGLPixelFormatAttribute) pixelFormat.depthBufferBits;
  224181. attribs[n++] = NSOpenGLPFAStencilSize;
  224182. attribs[n++] = (NSOpenGLPixelFormatAttribute) pixelFormat.stencilBufferBits;
  224183. attribs[n++] = NSOpenGLPFAAccumSize;
  224184. attribs[n++] = (NSOpenGLPixelFormatAttribute) jmax (pixelFormat.accumulationBufferRedBits,
  224185. pixelFormat.accumulationBufferGreenBits,
  224186. pixelFormat.accumulationBufferBlueBits,
  224187. pixelFormat.accumulationBufferAlphaBits);
  224188. // xxx not sure how to do fullSceneAntiAliasingNumSamples..
  224189. attribs[n++] = NSOpenGLPFASampleBuffers;
  224190. attribs[n++] = (NSOpenGLPixelFormatAttribute) 1;
  224191. attribs[n++] = NSOpenGLPFAClosestPolicy;
  224192. attribs[n++] = NSOpenGLPFANoRecovery;
  224193. attribs[n++] = (NSOpenGLPixelFormatAttribute) 0;
  224194. NSOpenGLPixelFormat* format
  224195. = [[NSOpenGLPixelFormat alloc] initWithAttributes: attribs];
  224196. view = [[ThreadSafeNSOpenGLView alloc] initWithFrame: NSMakeRect (0, 0, 100.0f, 100.0f)
  224197. pixelFormat: format];
  224198. renderContext = [[[NSOpenGLContext alloc] initWithFormat: format
  224199. shareContext: sharedContext] autorelease];
  224200. const GLint swapInterval = 1;
  224201. [renderContext setValues: &swapInterval forParameter: NSOpenGLCPSwapInterval];
  224202. [view setOpenGLContext: renderContext];
  224203. [renderContext setView: view];
  224204. [format release];
  224205. viewHolder = new NSViewComponentInternal (view, component);
  224206. }
  224207. ~WindowedGLContext()
  224208. {
  224209. makeInactive();
  224210. [renderContext clearDrawable];
  224211. viewHolder = 0;
  224212. }
  224213. bool makeActive() const throw()
  224214. {
  224215. jassert (renderContext != 0);
  224216. [view makeActive];
  224217. return isActive();
  224218. }
  224219. bool makeInactive() const throw()
  224220. {
  224221. [view makeInactive];
  224222. return true;
  224223. }
  224224. bool isActive() const throw()
  224225. {
  224226. return [NSOpenGLContext currentContext] == renderContext;
  224227. }
  224228. const OpenGLPixelFormat getPixelFormat() const { return pixelFormat; }
  224229. void* getRawContext() const throw() { return renderContext; }
  224230. void updateWindowPosition (int x, int y, int w, int h, int outerWindowHeight)
  224231. {
  224232. }
  224233. void swapBuffers()
  224234. {
  224235. [renderContext flushBuffer];
  224236. }
  224237. bool setSwapInterval (const int numFramesPerSwap)
  224238. {
  224239. [renderContext setValues: (const GLint*) &numFramesPerSwap
  224240. forParameter: NSOpenGLCPSwapInterval];
  224241. return true;
  224242. }
  224243. int getSwapInterval() const
  224244. {
  224245. GLint numFrames = 0;
  224246. [renderContext getValues: &numFrames
  224247. forParameter: NSOpenGLCPSwapInterval];
  224248. return numFrames;
  224249. }
  224250. void repaint()
  224251. {
  224252. // we need to invalidate the juce view that holds this gl view, to make it
  224253. // cause a repaint callback
  224254. NSView* v = (NSView*) viewHolder->view;
  224255. NSRect r = [v frame];
  224256. // bit of a bodge here.. if we only invalidate the area of the gl component,
  224257. // it's completely covered by the NSOpenGLView, so the OS throws away the
  224258. // repaint message, thus never causing our paint() callback, and never repainting
  224259. // the comp. So invalidating just a little bit around the edge helps..
  224260. [[v superview] setNeedsDisplayInRect: NSInsetRect (r, -2.0f, -2.0f)];
  224261. }
  224262. void* getNativeWindowHandle() const { return viewHolder->view; }
  224263. juce_UseDebuggingNewOperator
  224264. NSOpenGLContext* renderContext;
  224265. ThreadSafeNSOpenGLView* view;
  224266. private:
  224267. OpenGLPixelFormat pixelFormat;
  224268. ScopedPointer <NSViewComponentInternal> viewHolder;
  224269. WindowedGLContext (const WindowedGLContext&);
  224270. WindowedGLContext& operator= (const WindowedGLContext&);
  224271. };
  224272. OpenGLContext* OpenGLComponent::createContext()
  224273. {
  224274. ScopedPointer<WindowedGLContext> c (new WindowedGLContext (this, preferredPixelFormat,
  224275. contextToShareListsWith != 0 ? (NSOpenGLContext*) contextToShareListsWith->getRawContext() : 0));
  224276. return (c->renderContext != 0) ? c.release() : 0;
  224277. }
  224278. void* OpenGLComponent::getNativeWindowHandle() const
  224279. {
  224280. return context != 0 ? static_cast<WindowedGLContext*> (static_cast<OpenGLContext*> (context))->getNativeWindowHandle()
  224281. : 0;
  224282. }
  224283. void juce_glViewport (const int w, const int h)
  224284. {
  224285. glViewport (0, 0, w, h);
  224286. }
  224287. void OpenGLPixelFormat::getAvailablePixelFormats (Component* /*component*/,
  224288. OwnedArray <OpenGLPixelFormat>& results)
  224289. {
  224290. /* GLint attribs [64];
  224291. int n = 0;
  224292. attribs[n++] = AGL_RGBA;
  224293. attribs[n++] = AGL_DOUBLEBUFFER;
  224294. attribs[n++] = AGL_ACCELERATED;
  224295. attribs[n++] = AGL_NO_RECOVERY;
  224296. attribs[n++] = AGL_NONE;
  224297. AGLPixelFormat p = aglChoosePixelFormat (0, 0, attribs);
  224298. while (p != 0)
  224299. {
  224300. OpenGLPixelFormat* const pf = new OpenGLPixelFormat();
  224301. pf->redBits = getAGLAttribute (p, AGL_RED_SIZE);
  224302. pf->greenBits = getAGLAttribute (p, AGL_GREEN_SIZE);
  224303. pf->blueBits = getAGLAttribute (p, AGL_BLUE_SIZE);
  224304. pf->alphaBits = getAGLAttribute (p, AGL_ALPHA_SIZE);
  224305. pf->depthBufferBits = getAGLAttribute (p, AGL_DEPTH_SIZE);
  224306. pf->stencilBufferBits = getAGLAttribute (p, AGL_STENCIL_SIZE);
  224307. pf->accumulationBufferRedBits = getAGLAttribute (p, AGL_ACCUM_RED_SIZE);
  224308. pf->accumulationBufferGreenBits = getAGLAttribute (p, AGL_ACCUM_GREEN_SIZE);
  224309. pf->accumulationBufferBlueBits = getAGLAttribute (p, AGL_ACCUM_BLUE_SIZE);
  224310. pf->accumulationBufferAlphaBits = getAGLAttribute (p, AGL_ACCUM_ALPHA_SIZE);
  224311. results.add (pf);
  224312. p = aglNextPixelFormat (p);
  224313. }*/
  224314. //jassertfalse //xxx can't see how you do this in cocoa!
  224315. }
  224316. #else
  224317. END_JUCE_NAMESPACE
  224318. @interface JuceGLView : UIView
  224319. {
  224320. }
  224321. + (Class) layerClass;
  224322. @end
  224323. @implementation JuceGLView
  224324. + (Class) layerClass
  224325. {
  224326. return [CAEAGLLayer class];
  224327. }
  224328. @end
  224329. BEGIN_JUCE_NAMESPACE
  224330. class GLESContext : public OpenGLContext
  224331. {
  224332. public:
  224333. GLESContext (UIViewComponentPeer* peer,
  224334. Component* const component_,
  224335. const OpenGLPixelFormat& pixelFormat_,
  224336. const GLESContext* const sharedContext,
  224337. NSUInteger apiType)
  224338. : component (component_), pixelFormat (pixelFormat_), glLayer (0), context (0),
  224339. useDepthBuffer (pixelFormat_.depthBufferBits > 0), frameBufferHandle (0), colorBufferHandle (0),
  224340. depthBufferHandle (0), lastWidth (0), lastHeight (0)
  224341. {
  224342. view = [[JuceGLView alloc] initWithFrame: CGRectMake (0, 0, 64, 64)];
  224343. view.opaque = YES;
  224344. view.hidden = NO;
  224345. view.backgroundColor = [UIColor blackColor];
  224346. view.userInteractionEnabled = NO;
  224347. glLayer = (CAEAGLLayer*) [view layer];
  224348. [peer->view addSubview: view];
  224349. if (sharedContext != 0)
  224350. context = [[EAGLContext alloc] initWithAPI: apiType
  224351. sharegroup: [sharedContext->context sharegroup]];
  224352. else
  224353. context = [[EAGLContext alloc] initWithAPI: apiType];
  224354. createGLBuffers();
  224355. }
  224356. ~GLESContext()
  224357. {
  224358. makeInactive();
  224359. [context release];
  224360. [view removeFromSuperview];
  224361. [view release];
  224362. freeGLBuffers();
  224363. }
  224364. bool makeActive() const throw()
  224365. {
  224366. jassert (context != 0);
  224367. [EAGLContext setCurrentContext: context];
  224368. glBindFramebufferOES (GL_FRAMEBUFFER_OES, frameBufferHandle);
  224369. return true;
  224370. }
  224371. void swapBuffers()
  224372. {
  224373. glBindRenderbufferOES (GL_RENDERBUFFER_OES, colorBufferHandle);
  224374. [context presentRenderbuffer: GL_RENDERBUFFER_OES];
  224375. }
  224376. bool makeInactive() const throw()
  224377. {
  224378. return [EAGLContext setCurrentContext: nil];
  224379. }
  224380. bool isActive() const throw()
  224381. {
  224382. return [EAGLContext currentContext] == context;
  224383. }
  224384. const OpenGLPixelFormat getPixelFormat() const { return pixelFormat; }
  224385. void* getRawContext() const throw() { return glLayer; }
  224386. void updateWindowPosition (int x, int y, int w, int h, int outerWindowHeight)
  224387. {
  224388. view.frame = CGRectMake ((CGFloat) x, (CGFloat) y, (CGFloat) w, (CGFloat) h);
  224389. if (lastWidth != w || lastHeight != h)
  224390. {
  224391. lastWidth = w;
  224392. lastHeight = h;
  224393. freeGLBuffers();
  224394. createGLBuffers();
  224395. }
  224396. }
  224397. bool setSwapInterval (const int numFramesPerSwap)
  224398. {
  224399. numFrames = numFramesPerSwap;
  224400. return true;
  224401. }
  224402. int getSwapInterval() const
  224403. {
  224404. return numFrames;
  224405. }
  224406. void repaint()
  224407. {
  224408. }
  224409. void createGLBuffers()
  224410. {
  224411. makeActive();
  224412. glGenFramebuffersOES (1, &frameBufferHandle);
  224413. glGenRenderbuffersOES (1, &colorBufferHandle);
  224414. glGenRenderbuffersOES (1, &depthBufferHandle);
  224415. glBindRenderbufferOES (GL_RENDERBUFFER_OES, colorBufferHandle);
  224416. [context renderbufferStorage: GL_RENDERBUFFER_OES fromDrawable: glLayer];
  224417. GLint width, height;
  224418. glGetRenderbufferParameterivOES (GL_RENDERBUFFER_OES, GL_RENDERBUFFER_WIDTH_OES, &width);
  224419. glGetRenderbufferParameterivOES (GL_RENDERBUFFER_OES, GL_RENDERBUFFER_HEIGHT_OES, &height);
  224420. if (useDepthBuffer)
  224421. {
  224422. glBindRenderbufferOES (GL_RENDERBUFFER_OES, depthBufferHandle);
  224423. glRenderbufferStorageOES (GL_RENDERBUFFER_OES, GL_DEPTH_COMPONENT16_OES, width, height);
  224424. }
  224425. glBindRenderbufferOES (GL_RENDERBUFFER_OES, colorBufferHandle);
  224426. glBindFramebufferOES (GL_FRAMEBUFFER_OES, frameBufferHandle);
  224427. glFramebufferRenderbufferOES (GL_FRAMEBUFFER_OES, GL_COLOR_ATTACHMENT0_OES, GL_RENDERBUFFER_OES, colorBufferHandle);
  224428. if (useDepthBuffer)
  224429. glFramebufferRenderbufferOES (GL_FRAMEBUFFER_OES, GL_DEPTH_ATTACHMENT_OES, GL_RENDERBUFFER_OES, depthBufferHandle);
  224430. jassert (glCheckFramebufferStatusOES (GL_FRAMEBUFFER_OES) == GL_FRAMEBUFFER_COMPLETE_OES);
  224431. }
  224432. void freeGLBuffers()
  224433. {
  224434. if (frameBufferHandle != 0)
  224435. {
  224436. glDeleteFramebuffersOES (1, &frameBufferHandle);
  224437. frameBufferHandle = 0;
  224438. }
  224439. if (colorBufferHandle != 0)
  224440. {
  224441. glDeleteRenderbuffersOES (1, &colorBufferHandle);
  224442. colorBufferHandle = 0;
  224443. }
  224444. if (depthBufferHandle != 0)
  224445. {
  224446. glDeleteRenderbuffersOES (1, &depthBufferHandle);
  224447. depthBufferHandle = 0;
  224448. }
  224449. }
  224450. juce_UseDebuggingNewOperator
  224451. private:
  224452. Component::SafePointer<Component> component;
  224453. OpenGLPixelFormat pixelFormat;
  224454. JuceGLView* view;
  224455. CAEAGLLayer* glLayer;
  224456. EAGLContext* context;
  224457. bool useDepthBuffer;
  224458. GLuint frameBufferHandle, colorBufferHandle, depthBufferHandle;
  224459. int numFrames;
  224460. int lastWidth, lastHeight;
  224461. GLESContext (const GLESContext&);
  224462. GLESContext& operator= (const GLESContext&);
  224463. };
  224464. OpenGLContext* OpenGLComponent::createContext()
  224465. {
  224466. ScopedAutoReleasePool pool;
  224467. UIViewComponentPeer* peer = dynamic_cast <UIViewComponentPeer*> (getPeer());
  224468. if (peer != 0)
  224469. return new GLESContext (peer, this, preferredPixelFormat,
  224470. dynamic_cast <const GLESContext*> (contextToShareListsWith),
  224471. type == openGLES2 ? kEAGLRenderingAPIOpenGLES2 : kEAGLRenderingAPIOpenGLES1);
  224472. return 0;
  224473. }
  224474. void OpenGLPixelFormat::getAvailablePixelFormats (Component* /*component*/,
  224475. OwnedArray <OpenGLPixelFormat>& /*results*/)
  224476. {
  224477. }
  224478. void juce_glViewport (const int w, const int h)
  224479. {
  224480. glViewport (0, 0, w, h);
  224481. }
  224482. #endif
  224483. #endif
  224484. /*** End of inlined file: juce_mac_OpenGLComponent.mm ***/
  224485. /*** Start of inlined file: juce_mac_MouseCursor.mm ***/
  224486. // (This file gets included by juce_mac_NativeCode.mm, rather than being
  224487. // compiled on its own).
  224488. #if JUCE_INCLUDED_FILE
  224489. #if JUCE_MAC
  224490. namespace MouseCursorHelpers
  224491. {
  224492. static void* createFromImage (const Image& image, float hotspotX, float hotspotY)
  224493. {
  224494. NSImage* im = CoreGraphicsImage::createNSImage (image);
  224495. NSCursor* c = [[NSCursor alloc] initWithImage: im
  224496. hotSpot: NSMakePoint (hotspotX, hotspotY)];
  224497. [im release];
  224498. return c;
  224499. }
  224500. static void* fromWebKitFile (const char* filename, float hx, float hy)
  224501. {
  224502. FileInputStream fileStream (String ("/System/Library/Frameworks/WebKit.framework/Frameworks/WebCore.framework/Resources/") + filename);
  224503. BufferedInputStream buf (&fileStream, 4096, false);
  224504. PNGImageFormat pngFormat;
  224505. const ScopedPointer <Image> im (pngFormat.decodeImage (buf));
  224506. if (im != 0)
  224507. return createFromImage (*im, hx * im->getWidth(), hy * im->getHeight());
  224508. jassertfalse;
  224509. return 0;
  224510. }
  224511. }
  224512. void* MouseCursor::createMouseCursorFromImage (const Image& image, int hotspotX, int hotspotY)
  224513. {
  224514. return MouseCursorHelpers::createFromImage (image, (float) hotspotX, (float) hotspotY);
  224515. }
  224516. void* MouseCursor::createStandardMouseCursor (MouseCursor::StandardCursorType type)
  224517. {
  224518. const ScopedAutoReleasePool pool;
  224519. NSCursor* c = 0;
  224520. switch (type)
  224521. {
  224522. case NormalCursor: c = [NSCursor arrowCursor]; break;
  224523. case NoCursor: return createMouseCursorFromImage (Image (Image::ARGB, 8, 8, true), 0, 0);
  224524. case DraggingHandCursor: c = [NSCursor openHandCursor]; break;
  224525. case WaitCursor: c = [NSCursor arrowCursor]; break; // avoid this on the mac, let the OS provide the beachball
  224526. case IBeamCursor: c = [NSCursor IBeamCursor]; break;
  224527. case PointingHandCursor: c = [NSCursor pointingHandCursor]; break;
  224528. case LeftRightResizeCursor: c = [NSCursor resizeLeftRightCursor]; break;
  224529. case LeftEdgeResizeCursor: c = [NSCursor resizeLeftCursor]; break;
  224530. case RightEdgeResizeCursor: c = [NSCursor resizeRightCursor]; break;
  224531. case CrosshairCursor: c = [NSCursor crosshairCursor]; break;
  224532. case CopyingCursor: return MouseCursorHelpers::fromWebKitFile ("copyCursor.png", 0, 0);
  224533. case UpDownResizeCursor:
  224534. case TopEdgeResizeCursor:
  224535. case BottomEdgeResizeCursor:
  224536. return MouseCursorHelpers::fromWebKitFile ("northSouthResizeCursor.png", 0.5f, 0.5f);
  224537. case TopLeftCornerResizeCursor:
  224538. case BottomRightCornerResizeCursor:
  224539. return MouseCursorHelpers::fromWebKitFile ("northWestSouthEastResizeCursor.png", 0.5f, 0.5f);
  224540. case TopRightCornerResizeCursor:
  224541. case BottomLeftCornerResizeCursor:
  224542. return MouseCursorHelpers::fromWebKitFile ("northEastSouthWestResizeCursor.png", 0.5f, 0.5f);
  224543. case UpDownLeftRightResizeCursor:
  224544. return MouseCursorHelpers::fromWebKitFile ("moveCursor.png", 0.5f, 0.5f);
  224545. default:
  224546. jassertfalse;
  224547. break;
  224548. }
  224549. [c retain];
  224550. return c;
  224551. }
  224552. void MouseCursor::deleteMouseCursor (void* const cursorHandle, const bool isStandard)
  224553. {
  224554. [((NSCursor*) cursorHandle) release];
  224555. }
  224556. void MouseCursor::showInAllWindows() const
  224557. {
  224558. showInWindow (0);
  224559. }
  224560. void MouseCursor::showInWindow (ComponentPeer*) const
  224561. {
  224562. [((NSCursor*) getHandle()) set];
  224563. }
  224564. #else
  224565. void* MouseCursor::createMouseCursorFromImage (const Image& image, int hotspotX, int hotspotY) { return 0; }
  224566. void* MouseCursor::createStandardMouseCursor (MouseCursor::StandardCursorType type) { return 0; }
  224567. void MouseCursor::deleteMouseCursor (void* const cursorHandle, const bool isStandard) {}
  224568. void MouseCursor::showInAllWindows() const {}
  224569. void MouseCursor::showInWindow (ComponentPeer*) const {}
  224570. #endif
  224571. #endif
  224572. /*** End of inlined file: juce_mac_MouseCursor.mm ***/
  224573. /*** Start of inlined file: juce_mac_WebBrowserComponent.mm ***/
  224574. // (This file gets included by juce_mac_NativeCode.mm, rather than being
  224575. // compiled on its own).
  224576. #if JUCE_INCLUDED_FILE && JUCE_WEB_BROWSER
  224577. #if JUCE_MAC
  224578. END_JUCE_NAMESPACE
  224579. #define DownloadClickDetector MakeObjCClassName(DownloadClickDetector)
  224580. @interface DownloadClickDetector : NSObject
  224581. {
  224582. JUCE_NAMESPACE::WebBrowserComponent* ownerComponent;
  224583. }
  224584. - (DownloadClickDetector*) initWithWebBrowserOwner: (JUCE_NAMESPACE::WebBrowserComponent*) ownerComponent;
  224585. - (void) webView: (WebView*) webView decidePolicyForNavigationAction: (NSDictionary*) actionInformation
  224586. request: (NSURLRequest*) request
  224587. frame: (WebFrame*) frame
  224588. decisionListener: (id<WebPolicyDecisionListener>) listener;
  224589. @end
  224590. @implementation DownloadClickDetector
  224591. - (DownloadClickDetector*) initWithWebBrowserOwner: (JUCE_NAMESPACE::WebBrowserComponent*) ownerComponent_
  224592. {
  224593. [super init];
  224594. ownerComponent = ownerComponent_;
  224595. return self;
  224596. }
  224597. - (void) webView: (WebView*) sender decidePolicyForNavigationAction: (NSDictionary*) actionInformation
  224598. request: (NSURLRequest*) request
  224599. frame: (WebFrame*) frame
  224600. decisionListener: (id <WebPolicyDecisionListener>) listener
  224601. {
  224602. NSURL* url = [actionInformation valueForKey: @"WebActionOriginalURLKey"];
  224603. if (ownerComponent->pageAboutToLoad (nsStringToJuce ([url absoluteString])))
  224604. [listener use];
  224605. else
  224606. [listener ignore];
  224607. }
  224608. @end
  224609. BEGIN_JUCE_NAMESPACE
  224610. class WebBrowserComponentInternal : public NSViewComponent
  224611. {
  224612. public:
  224613. WebBrowserComponentInternal (WebBrowserComponent* owner)
  224614. {
  224615. webView = [[WebView alloc] initWithFrame: NSMakeRect (0, 0, 100.0f, 100.0f)
  224616. frameName: @""
  224617. groupName: @""];
  224618. setView (webView);
  224619. clickListener = [[DownloadClickDetector alloc] initWithWebBrowserOwner: owner];
  224620. [webView setPolicyDelegate: clickListener];
  224621. }
  224622. ~WebBrowserComponentInternal()
  224623. {
  224624. [webView setPolicyDelegate: nil];
  224625. [clickListener release];
  224626. setView (0);
  224627. }
  224628. void goToURL (const String& url,
  224629. const StringArray* headers,
  224630. const MemoryBlock* postData)
  224631. {
  224632. NSMutableURLRequest* r
  224633. = [NSMutableURLRequest requestWithURL: [NSURL URLWithString: juceStringToNS (url)]
  224634. cachePolicy: NSURLRequestUseProtocolCachePolicy
  224635. timeoutInterval: 30.0];
  224636. if (postData != 0 && postData->getSize() > 0)
  224637. {
  224638. [r setHTTPMethod: @"POST"];
  224639. [r setHTTPBody: [NSData dataWithBytes: postData->getData()
  224640. length: postData->getSize()]];
  224641. }
  224642. if (headers != 0)
  224643. {
  224644. for (int i = 0; i < headers->size(); ++i)
  224645. {
  224646. const String headerName ((*headers)[i].upToFirstOccurrenceOf (":", false, false).trim());
  224647. const String headerValue ((*headers)[i].fromFirstOccurrenceOf (":", false, false).trim());
  224648. [r setValue: juceStringToNS (headerValue)
  224649. forHTTPHeaderField: juceStringToNS (headerName)];
  224650. }
  224651. }
  224652. stop();
  224653. [[webView mainFrame] loadRequest: r];
  224654. }
  224655. void goBack()
  224656. {
  224657. [webView goBack];
  224658. }
  224659. void goForward()
  224660. {
  224661. [webView goForward];
  224662. }
  224663. void stop()
  224664. {
  224665. [webView stopLoading: nil];
  224666. }
  224667. void refresh()
  224668. {
  224669. [webView reload: nil];
  224670. }
  224671. private:
  224672. WebView* webView;
  224673. DownloadClickDetector* clickListener;
  224674. };
  224675. WebBrowserComponent::WebBrowserComponent (const bool unloadPageWhenBrowserIsHidden_)
  224676. : browser (0),
  224677. blankPageShown (false),
  224678. unloadPageWhenBrowserIsHidden (unloadPageWhenBrowserIsHidden_)
  224679. {
  224680. setOpaque (true);
  224681. addAndMakeVisible (browser = new WebBrowserComponentInternal (this));
  224682. }
  224683. WebBrowserComponent::~WebBrowserComponent()
  224684. {
  224685. deleteAndZero (browser);
  224686. }
  224687. void WebBrowserComponent::goToURL (const String& url,
  224688. const StringArray* headers,
  224689. const MemoryBlock* postData)
  224690. {
  224691. lastURL = url;
  224692. lastHeaders.clear();
  224693. if (headers != 0)
  224694. lastHeaders = *headers;
  224695. lastPostData.setSize (0);
  224696. if (postData != 0)
  224697. lastPostData = *postData;
  224698. blankPageShown = false;
  224699. browser->goToURL (url, headers, postData);
  224700. }
  224701. void WebBrowserComponent::stop()
  224702. {
  224703. browser->stop();
  224704. }
  224705. void WebBrowserComponent::goBack()
  224706. {
  224707. lastURL = String::empty;
  224708. blankPageShown = false;
  224709. browser->goBack();
  224710. }
  224711. void WebBrowserComponent::goForward()
  224712. {
  224713. lastURL = String::empty;
  224714. browser->goForward();
  224715. }
  224716. void WebBrowserComponent::refresh()
  224717. {
  224718. browser->refresh();
  224719. }
  224720. void WebBrowserComponent::paint (Graphics& g)
  224721. {
  224722. }
  224723. void WebBrowserComponent::checkWindowAssociation()
  224724. {
  224725. if (isShowing())
  224726. {
  224727. if (blankPageShown)
  224728. goBack();
  224729. }
  224730. else
  224731. {
  224732. if (unloadPageWhenBrowserIsHidden && ! blankPageShown)
  224733. {
  224734. // when the component becomes invisible, some stuff like flash
  224735. // carries on playing audio, so we need to force it onto a blank
  224736. // page to avoid this, (and send it back when it's made visible again).
  224737. blankPageShown = true;
  224738. browser->goToURL ("about:blank", 0, 0);
  224739. }
  224740. }
  224741. }
  224742. void WebBrowserComponent::reloadLastURL()
  224743. {
  224744. if (lastURL.isNotEmpty())
  224745. {
  224746. goToURL (lastURL, &lastHeaders, &lastPostData);
  224747. lastURL = String::empty;
  224748. }
  224749. }
  224750. void WebBrowserComponent::parentHierarchyChanged()
  224751. {
  224752. checkWindowAssociation();
  224753. }
  224754. void WebBrowserComponent::resized()
  224755. {
  224756. browser->setSize (getWidth(), getHeight());
  224757. }
  224758. void WebBrowserComponent::visibilityChanged()
  224759. {
  224760. checkWindowAssociation();
  224761. }
  224762. bool WebBrowserComponent::pageAboutToLoad (const String& url)
  224763. {
  224764. return true;
  224765. }
  224766. #else
  224767. WebBrowserComponent::WebBrowserComponent (const bool unloadPageWhenBrowserIsHidden_)
  224768. {
  224769. }
  224770. WebBrowserComponent::~WebBrowserComponent()
  224771. {
  224772. }
  224773. void WebBrowserComponent::goToURL (const String& url,
  224774. const StringArray* headers,
  224775. const MemoryBlock* postData)
  224776. {
  224777. }
  224778. void WebBrowserComponent::stop()
  224779. {
  224780. }
  224781. void WebBrowserComponent::goBack()
  224782. {
  224783. }
  224784. void WebBrowserComponent::goForward()
  224785. {
  224786. }
  224787. void WebBrowserComponent::refresh()
  224788. {
  224789. }
  224790. void WebBrowserComponent::paint (Graphics& g)
  224791. {
  224792. }
  224793. void WebBrowserComponent::checkWindowAssociation()
  224794. {
  224795. }
  224796. void WebBrowserComponent::reloadLastURL()
  224797. {
  224798. }
  224799. void WebBrowserComponent::parentHierarchyChanged()
  224800. {
  224801. }
  224802. void WebBrowserComponent::resized()
  224803. {
  224804. }
  224805. void WebBrowserComponent::visibilityChanged()
  224806. {
  224807. }
  224808. bool WebBrowserComponent::pageAboutToLoad (const String& url)
  224809. {
  224810. return true;
  224811. }
  224812. #endif
  224813. #endif
  224814. /*** End of inlined file: juce_mac_WebBrowserComponent.mm ***/
  224815. /*** Start of inlined file: juce_iphone_Audio.cpp ***/
  224816. // (This file gets included by juce_mac_NativeCode.mm, rather than being
  224817. // compiled on its own).
  224818. #if JUCE_INCLUDED_FILE
  224819. class IPhoneAudioIODevice : public AudioIODevice
  224820. {
  224821. public:
  224822. IPhoneAudioIODevice (const String& deviceName)
  224823. : AudioIODevice (deviceName, "Audio"),
  224824. audioUnit (0),
  224825. isRunning (false),
  224826. callback (0),
  224827. actualBufferSize (0),
  224828. floatData (1, 2)
  224829. {
  224830. numInputChannels = 2;
  224831. numOutputChannels = 2;
  224832. preferredBufferSize = 0;
  224833. AudioSessionInitialize (0, 0, interruptionListenerStatic, this);
  224834. updateDeviceInfo();
  224835. }
  224836. ~IPhoneAudioIODevice()
  224837. {
  224838. close();
  224839. }
  224840. const StringArray getOutputChannelNames()
  224841. {
  224842. StringArray s;
  224843. s.add ("Left");
  224844. s.add ("Right");
  224845. return s;
  224846. }
  224847. const StringArray getInputChannelNames()
  224848. {
  224849. StringArray s;
  224850. if (audioInputIsAvailable)
  224851. {
  224852. s.add ("Left");
  224853. s.add ("Right");
  224854. }
  224855. return s;
  224856. }
  224857. int getNumSampleRates()
  224858. {
  224859. return 1;
  224860. }
  224861. double getSampleRate (int index)
  224862. {
  224863. return sampleRate;
  224864. }
  224865. int getNumBufferSizesAvailable()
  224866. {
  224867. return 1;
  224868. }
  224869. int getBufferSizeSamples (int index)
  224870. {
  224871. return getDefaultBufferSize();
  224872. }
  224873. int getDefaultBufferSize()
  224874. {
  224875. return 1024;
  224876. }
  224877. const String open (const BigInteger& inputChannels,
  224878. const BigInteger& outputChannels,
  224879. double sampleRate,
  224880. int bufferSize)
  224881. {
  224882. close();
  224883. lastError = String::empty;
  224884. preferredBufferSize = (bufferSize <= 0) ? getDefaultBufferSize() : bufferSize;
  224885. // xxx set up channel mapping
  224886. activeOutputChans = outputChannels;
  224887. activeOutputChans.setRange (2, activeOutputChans.getHighestBit(), false);
  224888. numOutputChannels = activeOutputChans.countNumberOfSetBits();
  224889. monoOutputChannelNumber = activeOutputChans.findNextSetBit (0);
  224890. activeInputChans = inputChannels;
  224891. activeInputChans.setRange (2, activeInputChans.getHighestBit(), false);
  224892. numInputChannels = activeInputChans.countNumberOfSetBits();
  224893. monoInputChannelNumber = activeInputChans.findNextSetBit (0);
  224894. AudioSessionSetActive (true);
  224895. UInt32 audioCategory = kAudioSessionCategory_PlayAndRecord;
  224896. AudioSessionSetProperty (kAudioSessionProperty_AudioCategory, sizeof (audioCategory), &audioCategory);
  224897. AudioSessionAddPropertyListener (kAudioSessionProperty_AudioRouteChange, propertyChangedStatic, this);
  224898. fixAudioRouteIfSetToReceiver();
  224899. updateDeviceInfo();
  224900. Float32 bufferDuration = preferredBufferSize / sampleRate;
  224901. AudioSessionSetProperty (kAudioSessionProperty_PreferredHardwareIOBufferDuration, sizeof (bufferDuration), &bufferDuration);
  224902. actualBufferSize = preferredBufferSize;
  224903. prepareFloatBuffers();
  224904. isRunning = true;
  224905. propertyChanged (0, 0, 0); // creates and starts the AU
  224906. lastError = audioUnit != 0 ? "" : "Couldn't open the device";
  224907. return lastError;
  224908. }
  224909. void close()
  224910. {
  224911. if (isRunning)
  224912. {
  224913. isRunning = false;
  224914. AudioSessionSetActive (false);
  224915. if (audioUnit != 0)
  224916. {
  224917. AudioComponentInstanceDispose (audioUnit);
  224918. audioUnit = 0;
  224919. }
  224920. }
  224921. }
  224922. bool isOpen()
  224923. {
  224924. return isRunning;
  224925. }
  224926. int getCurrentBufferSizeSamples()
  224927. {
  224928. return actualBufferSize;
  224929. }
  224930. double getCurrentSampleRate()
  224931. {
  224932. return sampleRate;
  224933. }
  224934. int getCurrentBitDepth()
  224935. {
  224936. return 16;
  224937. }
  224938. const BigInteger getActiveOutputChannels() const
  224939. {
  224940. return activeOutputChans;
  224941. }
  224942. const BigInteger getActiveInputChannels() const
  224943. {
  224944. return activeInputChans;
  224945. }
  224946. int getOutputLatencyInSamples()
  224947. {
  224948. return 0; //xxx
  224949. }
  224950. int getInputLatencyInSamples()
  224951. {
  224952. return 0; //xxx
  224953. }
  224954. void start (AudioIODeviceCallback* callback_)
  224955. {
  224956. if (isRunning && callback != callback_)
  224957. {
  224958. if (callback_ != 0)
  224959. callback_->audioDeviceAboutToStart (this);
  224960. const ScopedLock sl (callbackLock);
  224961. callback = callback_;
  224962. }
  224963. }
  224964. void stop()
  224965. {
  224966. if (isRunning)
  224967. {
  224968. AudioIODeviceCallback* lastCallback;
  224969. {
  224970. const ScopedLock sl (callbackLock);
  224971. lastCallback = callback;
  224972. callback = 0;
  224973. }
  224974. if (lastCallback != 0)
  224975. lastCallback->audioDeviceStopped();
  224976. }
  224977. }
  224978. bool isPlaying()
  224979. {
  224980. return isRunning && callback != 0;
  224981. }
  224982. const String getLastError()
  224983. {
  224984. return lastError;
  224985. }
  224986. private:
  224987. CriticalSection callbackLock;
  224988. Float64 sampleRate;
  224989. int numInputChannels, numOutputChannels;
  224990. int preferredBufferSize;
  224991. int actualBufferSize;
  224992. bool isRunning;
  224993. String lastError;
  224994. AudioStreamBasicDescription format;
  224995. AudioUnit audioUnit;
  224996. UInt32 audioInputIsAvailable;
  224997. AudioIODeviceCallback* callback;
  224998. BigInteger activeOutputChans, activeInputChans;
  224999. AudioSampleBuffer floatData;
  225000. float* inputChannels[3];
  225001. float* outputChannels[3];
  225002. bool monoInputChannelNumber, monoOutputChannelNumber;
  225003. void prepareFloatBuffers()
  225004. {
  225005. floatData.setSize (numInputChannels + numOutputChannels, actualBufferSize);
  225006. zerostruct (inputChannels);
  225007. zerostruct (outputChannels);
  225008. for (int i = 0; i < numInputChannels; ++i)
  225009. inputChannels[i] = floatData.getSampleData (i);
  225010. for (int i = 0; i < numOutputChannels; ++i)
  225011. outputChannels[i] = floatData.getSampleData (i + numInputChannels);
  225012. }
  225013. OSStatus process (AudioUnitRenderActionFlags* ioActionFlags, const AudioTimeStamp* inTimeStamp,
  225014. UInt32 inBusNumber, UInt32 inNumberFrames, AudioBufferList* ioData)
  225015. {
  225016. OSStatus err = noErr;
  225017. if (audioInputIsAvailable)
  225018. err = AudioUnitRender (audioUnit, ioActionFlags, inTimeStamp, 1, inNumberFrames, ioData);
  225019. const ScopedLock sl (callbackLock);
  225020. if (callback != 0)
  225021. {
  225022. if (audioInputIsAvailable && numInputChannels > 0)
  225023. {
  225024. short* shortData = (short*) ioData->mBuffers[0].mData;
  225025. if (numInputChannels >= 2)
  225026. {
  225027. for (UInt32 i = 0; i < inNumberFrames; ++i)
  225028. {
  225029. inputChannels[0][i] = *shortData++ * (1.0f / 32768.0f);
  225030. inputChannels[1][i] = *shortData++ * (1.0f / 32768.0f);
  225031. }
  225032. }
  225033. else
  225034. {
  225035. if (monoInputChannelNumber > 0)
  225036. ++shortData;
  225037. for (UInt32 i = 0; i < inNumberFrames; ++i)
  225038. {
  225039. inputChannels[0][i] = *shortData++ * (1.0f / 32768.0f);
  225040. ++shortData;
  225041. }
  225042. }
  225043. }
  225044. else
  225045. {
  225046. for (int i = numInputChannels; --i >= 0;)
  225047. zeromem (inputChannels[i], sizeof (float) * inNumberFrames);
  225048. }
  225049. callback->audioDeviceIOCallback ((const float**) inputChannels, numInputChannels,
  225050. outputChannels, numOutputChannels,
  225051. (int) inNumberFrames);
  225052. short* shortData = (short*) ioData->mBuffers[0].mData;
  225053. int n = 0;
  225054. if (numOutputChannels >= 2)
  225055. {
  225056. for (UInt32 i = 0; i < inNumberFrames; ++i)
  225057. {
  225058. shortData [n++] = (short) (outputChannels[0][i] * 32767.0f);
  225059. shortData [n++] = (short) (outputChannels[1][i] * 32767.0f);
  225060. }
  225061. }
  225062. else if (numOutputChannels == 1)
  225063. {
  225064. for (UInt32 i = 0; i < inNumberFrames; ++i)
  225065. {
  225066. const short s = (short) (outputChannels[monoOutputChannelNumber][i] * 32767.0f);
  225067. shortData [n++] = s;
  225068. shortData [n++] = s;
  225069. }
  225070. }
  225071. else
  225072. {
  225073. zeromem (ioData->mBuffers[0].mData, 2 * sizeof (short) * inNumberFrames);
  225074. }
  225075. }
  225076. else
  225077. {
  225078. zeromem (ioData->mBuffers[0].mData, 2 * sizeof (short) * inNumberFrames);
  225079. }
  225080. return err;
  225081. }
  225082. void updateDeviceInfo()
  225083. {
  225084. UInt32 size = sizeof (sampleRate);
  225085. AudioSessionGetProperty (kAudioSessionProperty_CurrentHardwareSampleRate, &size, &sampleRate);
  225086. size = sizeof (audioInputIsAvailable);
  225087. AudioSessionGetProperty (kAudioSessionProperty_AudioInputAvailable, &size, &audioInputIsAvailable);
  225088. }
  225089. void propertyChanged (AudioSessionPropertyID inID, UInt32 inDataSize, const void* inPropertyValue)
  225090. {
  225091. if (! isRunning)
  225092. return;
  225093. if (inPropertyValue != 0)
  225094. {
  225095. CFDictionaryRef routeChangeDictionary = (CFDictionaryRef) inPropertyValue;
  225096. CFNumberRef routeChangeReasonRef = (CFNumberRef) CFDictionaryGetValue (routeChangeDictionary,
  225097. CFSTR (kAudioSession_AudioRouteChangeKey_Reason));
  225098. SInt32 routeChangeReason;
  225099. CFNumberGetValue (routeChangeReasonRef, kCFNumberSInt32Type, &routeChangeReason);
  225100. if (routeChangeReason == kAudioSessionRouteChangeReason_OldDeviceUnavailable)
  225101. fixAudioRouteIfSetToReceiver();
  225102. }
  225103. updateDeviceInfo();
  225104. createAudioUnit();
  225105. AudioSessionSetActive (true);
  225106. if (audioUnit != 0)
  225107. {
  225108. UInt32 formatSize = sizeof (format);
  225109. AudioUnitGetProperty (audioUnit, kAudioUnitProperty_StreamFormat, kAudioUnitScope_Output, 1, &format, &formatSize);
  225110. Float32 bufferDuration = preferredBufferSize / sampleRate;
  225111. UInt32 bufferDurationSize = sizeof (bufferDuration);
  225112. AudioSessionGetProperty (kAudioSessionProperty_CurrentHardwareIOBufferDuration, &bufferDurationSize, &bufferDurationSize);
  225113. actualBufferSize = (int) (sampleRate * bufferDuration + 0.5);
  225114. AudioOutputUnitStart (audioUnit);
  225115. }
  225116. }
  225117. void interruptionListener (UInt32 inInterruption)
  225118. {
  225119. /*if (inInterruption == kAudioSessionBeginInterruption)
  225120. {
  225121. isRunning = false;
  225122. AudioOutputUnitStop (audioUnit);
  225123. if (juce_iPhoneShowModalAlert ("Audio Interrupted",
  225124. "This could have been interrupted by another application or by unplugging a headset",
  225125. @"Resume",
  225126. @"Cancel"))
  225127. {
  225128. isRunning = true;
  225129. propertyChanged (0, 0, 0);
  225130. }
  225131. }*/
  225132. if (inInterruption == kAudioSessionEndInterruption)
  225133. {
  225134. isRunning = true;
  225135. AudioSessionSetActive (true);
  225136. AudioOutputUnitStart (audioUnit);
  225137. }
  225138. }
  225139. static OSStatus processStatic (void* inRefCon, AudioUnitRenderActionFlags* ioActionFlags, const AudioTimeStamp* inTimeStamp,
  225140. UInt32 inBusNumber, UInt32 inNumberFrames, AudioBufferList* ioData)
  225141. {
  225142. return ((IPhoneAudioIODevice*) inRefCon)->process (ioActionFlags, inTimeStamp, inBusNumber, inNumberFrames, ioData);
  225143. }
  225144. static void propertyChangedStatic (void* inClientData, AudioSessionPropertyID inID, UInt32 inDataSize, const void* inPropertyValue)
  225145. {
  225146. ((IPhoneAudioIODevice*) inClientData)->propertyChanged (inID, inDataSize, inPropertyValue);
  225147. }
  225148. static void interruptionListenerStatic (void* inClientData, UInt32 inInterruption)
  225149. {
  225150. ((IPhoneAudioIODevice*) inClientData)->interruptionListener (inInterruption);
  225151. }
  225152. void resetFormat (const int numChannels)
  225153. {
  225154. memset (&format, 0, sizeof (format));
  225155. format.mFormatID = kAudioFormatLinearPCM;
  225156. format.mFormatFlags = kLinearPCMFormatFlagIsSignedInteger | kLinearPCMFormatFlagIsPacked;
  225157. format.mBitsPerChannel = 8 * sizeof (short);
  225158. format.mChannelsPerFrame = 2;
  225159. format.mFramesPerPacket = 1;
  225160. format.mBytesPerFrame = format.mBytesPerPacket = 2 * sizeof (short);
  225161. }
  225162. bool createAudioUnit()
  225163. {
  225164. if (audioUnit != 0)
  225165. {
  225166. AudioComponentInstanceDispose (audioUnit);
  225167. audioUnit = 0;
  225168. }
  225169. resetFormat (2);
  225170. AudioComponentDescription desc;
  225171. desc.componentType = kAudioUnitType_Output;
  225172. desc.componentSubType = kAudioUnitSubType_RemoteIO;
  225173. desc.componentManufacturer = kAudioUnitManufacturer_Apple;
  225174. desc.componentFlags = 0;
  225175. desc.componentFlagsMask = 0;
  225176. AudioComponent comp = AudioComponentFindNext (0, &desc);
  225177. AudioComponentInstanceNew (comp, &audioUnit);
  225178. if (audioUnit == 0)
  225179. return false;
  225180. const UInt32 one = 1;
  225181. AudioUnitSetProperty (audioUnit, kAudioOutputUnitProperty_EnableIO, kAudioUnitScope_Input, 1, &one, sizeof (one));
  225182. AudioChannelLayout layout;
  225183. layout.mChannelBitmap = 0;
  225184. layout.mNumberChannelDescriptions = 0;
  225185. layout.mChannelLayoutTag = kAudioChannelLayoutTag_Stereo;
  225186. AudioUnitSetProperty (audioUnit, kAudioUnitProperty_AudioChannelLayout, kAudioUnitScope_Input, 0, &layout, sizeof (layout));
  225187. AudioUnitSetProperty (audioUnit, kAudioUnitProperty_AudioChannelLayout, kAudioUnitScope_Output, 0, &layout, sizeof (layout));
  225188. AURenderCallbackStruct inputProc;
  225189. inputProc.inputProc = processStatic;
  225190. inputProc.inputProcRefCon = this;
  225191. AudioUnitSetProperty (audioUnit, kAudioUnitProperty_SetRenderCallback, kAudioUnitScope_Input, 0, &inputProc, sizeof (inputProc));
  225192. AudioUnitSetProperty (audioUnit, kAudioUnitProperty_StreamFormat, kAudioUnitScope_Input, 0, &format, sizeof (format));
  225193. AudioUnitSetProperty (audioUnit, kAudioUnitProperty_StreamFormat, kAudioUnitScope_Output, 1, &format, sizeof (format));
  225194. AudioUnitInitialize (audioUnit);
  225195. return true;
  225196. }
  225197. // If the routing is set to go through the receiver (i.e. the speaker, but quiet), this re-routes it
  225198. // to make it loud. Needed because by default when using an input + output, the output is kept quiet.
  225199. static void fixAudioRouteIfSetToReceiver()
  225200. {
  225201. CFStringRef audioRoute = 0;
  225202. UInt32 propertySize = sizeof (audioRoute);
  225203. if (AudioSessionGetProperty (kAudioSessionProperty_AudioRoute, &propertySize, &audioRoute) == noErr)
  225204. {
  225205. NSString* route = (NSString*) audioRoute;
  225206. //DBG ("audio route: " + nsStringToJuce (route));
  225207. if ([route hasPrefix: @"Receiver"])
  225208. {
  225209. UInt32 audioRouteOverride = kAudioSessionOverrideAudioRoute_Speaker;
  225210. AudioSessionSetProperty (kAudioSessionProperty_OverrideAudioRoute, sizeof (audioRouteOverride), &audioRouteOverride);
  225211. }
  225212. CFRelease (audioRoute);
  225213. }
  225214. }
  225215. IPhoneAudioIODevice (const IPhoneAudioIODevice&);
  225216. IPhoneAudioIODevice& operator= (const IPhoneAudioIODevice&);
  225217. };
  225218. class IPhoneAudioIODeviceType : public AudioIODeviceType
  225219. {
  225220. public:
  225221. IPhoneAudioIODeviceType()
  225222. : AudioIODeviceType ("iPhone Audio")
  225223. {
  225224. }
  225225. ~IPhoneAudioIODeviceType()
  225226. {
  225227. }
  225228. void scanForDevices()
  225229. {
  225230. }
  225231. const StringArray getDeviceNames (bool wantInputNames) const
  225232. {
  225233. StringArray s;
  225234. s.add ("iPhone Audio");
  225235. return s;
  225236. }
  225237. int getDefaultDeviceIndex (bool forInput) const
  225238. {
  225239. return 0;
  225240. }
  225241. int getIndexOfDevice (AudioIODevice* device, bool asInput) const
  225242. {
  225243. return device != 0 ? 0 : -1;
  225244. }
  225245. bool hasSeparateInputsAndOutputs() const { return false; }
  225246. AudioIODevice* createDevice (const String& outputDeviceName,
  225247. const String& inputDeviceName)
  225248. {
  225249. if (outputDeviceName.isNotEmpty() || inputDeviceName.isNotEmpty())
  225250. {
  225251. return new IPhoneAudioIODevice (outputDeviceName.isNotEmpty() ? outputDeviceName
  225252. : inputDeviceName);
  225253. }
  225254. return 0;
  225255. }
  225256. juce_UseDebuggingNewOperator
  225257. private:
  225258. IPhoneAudioIODeviceType (const IPhoneAudioIODeviceType&);
  225259. IPhoneAudioIODeviceType& operator= (const IPhoneAudioIODeviceType&);
  225260. };
  225261. AudioIODeviceType* juce_createAudioIODeviceType_iPhoneAudio()
  225262. {
  225263. return new IPhoneAudioIODeviceType();
  225264. }
  225265. #endif
  225266. /*** End of inlined file: juce_iphone_Audio.cpp ***/
  225267. /*** Start of inlined file: juce_mac_CoreMidi.cpp ***/
  225268. // (This file gets included by juce_mac_NativeCode.mm, rather than being
  225269. // compiled on its own).
  225270. #if JUCE_INCLUDED_FILE
  225271. #if JUCE_MAC
  225272. #undef log
  225273. #define log(a) Logger::writeToLog(a)
  225274. static bool logAnyErrorsMidi (const OSStatus err, const int lineNum)
  225275. {
  225276. if (err == noErr)
  225277. return true;
  225278. log ("CoreMidi error: " + String (lineNum) + " - " + String::toHexString ((int) err));
  225279. jassertfalse
  225280. return false;
  225281. }
  225282. #undef OK
  225283. #define OK(a) logAnyErrorsMidi(a, __LINE__)
  225284. static const String getEndpointName (MIDIEndpointRef endpoint, bool isExternal)
  225285. {
  225286. String result;
  225287. CFStringRef str = 0;
  225288. MIDIObjectGetStringProperty (endpoint, kMIDIPropertyName, &str);
  225289. if (str != 0)
  225290. {
  225291. result = PlatformUtilities::cfStringToJuceString (str);
  225292. CFRelease (str);
  225293. str = 0;
  225294. }
  225295. MIDIEntityRef entity = 0;
  225296. MIDIEndpointGetEntity (endpoint, &entity);
  225297. if (entity == 0)
  225298. return result; // probably virtual
  225299. if (result.isEmpty())
  225300. {
  225301. // endpoint name has zero length - try the entity
  225302. MIDIObjectGetStringProperty (entity, kMIDIPropertyName, &str);
  225303. if (str != 0)
  225304. {
  225305. result += PlatformUtilities::cfStringToJuceString (str);
  225306. CFRelease (str);
  225307. str = 0;
  225308. }
  225309. }
  225310. // now consider the device's name
  225311. MIDIDeviceRef device = 0;
  225312. MIDIEntityGetDevice (entity, &device);
  225313. if (device == 0)
  225314. return result;
  225315. MIDIObjectGetStringProperty (device, kMIDIPropertyName, &str);
  225316. if (str != 0)
  225317. {
  225318. const String s (PlatformUtilities::cfStringToJuceString (str));
  225319. CFRelease (str);
  225320. // if an external device has only one entity, throw away
  225321. // the endpoint name and just use the device name
  225322. if (isExternal && MIDIDeviceGetNumberOfEntities (device) < 2)
  225323. {
  225324. result = s;
  225325. }
  225326. else if (! result.startsWithIgnoreCase (s))
  225327. {
  225328. // prepend the device name to the entity name
  225329. result = (s + " " + result).trimEnd();
  225330. }
  225331. }
  225332. return result;
  225333. }
  225334. static const String getConnectedEndpointName (MIDIEndpointRef endpoint)
  225335. {
  225336. String result;
  225337. // Does the endpoint have connections?
  225338. CFDataRef connections = 0;
  225339. int numConnections = 0;
  225340. MIDIObjectGetDataProperty (endpoint, kMIDIPropertyConnectionUniqueID, &connections);
  225341. if (connections != 0)
  225342. {
  225343. numConnections = (int) (CFDataGetLength (connections) / sizeof (MIDIUniqueID));
  225344. if (numConnections > 0)
  225345. {
  225346. const SInt32* pid = reinterpret_cast <const SInt32*> (CFDataGetBytePtr (connections));
  225347. for (int i = 0; i < numConnections; ++i, ++pid)
  225348. {
  225349. MIDIUniqueID uid = EndianS32_BtoN (*pid);
  225350. MIDIObjectRef connObject;
  225351. MIDIObjectType connObjectType;
  225352. OSStatus err = MIDIObjectFindByUniqueID (uid, &connObject, &connObjectType);
  225353. if (err == noErr)
  225354. {
  225355. String s;
  225356. if (connObjectType == kMIDIObjectType_ExternalSource
  225357. || connObjectType == kMIDIObjectType_ExternalDestination)
  225358. {
  225359. // Connected to an external device's endpoint (10.3 and later).
  225360. s = getEndpointName (static_cast <MIDIEndpointRef> (connObject), true);
  225361. }
  225362. else
  225363. {
  225364. // Connected to an external device (10.2) (or something else, catch-all)
  225365. CFStringRef str = 0;
  225366. MIDIObjectGetStringProperty (connObject, kMIDIPropertyName, &str);
  225367. if (str != 0)
  225368. {
  225369. s = PlatformUtilities::cfStringToJuceString (str);
  225370. CFRelease (str);
  225371. }
  225372. }
  225373. if (s.isNotEmpty())
  225374. {
  225375. if (result.isNotEmpty())
  225376. result += ", ";
  225377. result += s;
  225378. }
  225379. }
  225380. }
  225381. }
  225382. CFRelease (connections);
  225383. }
  225384. if (result.isNotEmpty())
  225385. return result;
  225386. // Here, either the endpoint had no connections, or we failed to obtain names for any of them.
  225387. return getEndpointName (endpoint, false);
  225388. }
  225389. const StringArray MidiOutput::getDevices()
  225390. {
  225391. StringArray s;
  225392. const ItemCount num = MIDIGetNumberOfDestinations();
  225393. for (ItemCount i = 0; i < num; ++i)
  225394. {
  225395. MIDIEndpointRef dest = MIDIGetDestination (i);
  225396. if (dest != 0)
  225397. {
  225398. String name (getConnectedEndpointName (dest));
  225399. if (name.isEmpty())
  225400. name = "<error>";
  225401. s.add (name);
  225402. }
  225403. else
  225404. {
  225405. s.add ("<error>");
  225406. }
  225407. }
  225408. return s;
  225409. }
  225410. int MidiOutput::getDefaultDeviceIndex()
  225411. {
  225412. return 0;
  225413. }
  225414. static MIDIClientRef globalMidiClient;
  225415. static bool hasGlobalClientBeenCreated = false;
  225416. static bool makeSureClientExists()
  225417. {
  225418. if (! hasGlobalClientBeenCreated)
  225419. {
  225420. String name ("JUCE");
  225421. if (JUCEApplication::getInstance() != 0)
  225422. name = JUCEApplication::getInstance()->getApplicationName();
  225423. CFStringRef appName = PlatformUtilities::juceStringToCFString (name);
  225424. hasGlobalClientBeenCreated = OK (MIDIClientCreate (appName, 0, 0, &globalMidiClient));
  225425. CFRelease (appName);
  225426. }
  225427. return hasGlobalClientBeenCreated;
  225428. }
  225429. class MidiPortAndEndpoint
  225430. {
  225431. public:
  225432. MidiPortAndEndpoint (MIDIPortRef port_, MIDIEndpointRef endPoint_)
  225433. : port (port_), endPoint (endPoint_)
  225434. {
  225435. }
  225436. ~MidiPortAndEndpoint()
  225437. {
  225438. if (port != 0)
  225439. MIDIPortDispose (port);
  225440. if (port == 0 && endPoint != 0) // if port == 0, it means we created the endpoint, so it's safe to delete it
  225441. MIDIEndpointDispose (endPoint);
  225442. }
  225443. MIDIPortRef port;
  225444. MIDIEndpointRef endPoint;
  225445. };
  225446. MidiOutput* MidiOutput::openDevice (int index)
  225447. {
  225448. MidiOutput* mo = 0;
  225449. if (((unsigned int) index) < (unsigned int) MIDIGetNumberOfDestinations())
  225450. {
  225451. MIDIEndpointRef endPoint = MIDIGetDestination (index);
  225452. CFStringRef pname;
  225453. if (OK (MIDIObjectGetStringProperty (endPoint, kMIDIPropertyName, &pname)))
  225454. {
  225455. log ("CoreMidi - opening out: " + PlatformUtilities::cfStringToJuceString (pname));
  225456. if (makeSureClientExists())
  225457. {
  225458. MIDIPortRef port;
  225459. if (OK (MIDIOutputPortCreate (globalMidiClient, pname, &port)))
  225460. {
  225461. mo = new MidiOutput();
  225462. mo->internal = new MidiPortAndEndpoint (port, endPoint);
  225463. }
  225464. }
  225465. CFRelease (pname);
  225466. }
  225467. }
  225468. return mo;
  225469. }
  225470. MidiOutput* MidiOutput::createNewDevice (const String& deviceName)
  225471. {
  225472. MidiOutput* mo = 0;
  225473. if (makeSureClientExists())
  225474. {
  225475. MIDIEndpointRef endPoint;
  225476. CFStringRef name = PlatformUtilities::juceStringToCFString (deviceName);
  225477. if (OK (MIDISourceCreate (globalMidiClient, name, &endPoint)))
  225478. {
  225479. mo = new MidiOutput();
  225480. mo->internal = new MidiPortAndEndpoint (0, endPoint);
  225481. }
  225482. CFRelease (name);
  225483. }
  225484. return mo;
  225485. }
  225486. MidiOutput::~MidiOutput()
  225487. {
  225488. delete (MidiPortAndEndpoint*) internal;
  225489. }
  225490. void MidiOutput::reset()
  225491. {
  225492. }
  225493. bool MidiOutput::getVolume (float& leftVol, float& rightVol)
  225494. {
  225495. return false;
  225496. }
  225497. void MidiOutput::setVolume (float leftVol, float rightVol)
  225498. {
  225499. }
  225500. void MidiOutput::sendMessageNow (const MidiMessage& message)
  225501. {
  225502. MidiPortAndEndpoint* const mpe = (MidiPortAndEndpoint*) internal;
  225503. if (message.isSysEx())
  225504. {
  225505. const int maxPacketSize = 256;
  225506. int pos = 0, bytesLeft = message.getRawDataSize();
  225507. const int numPackets = (bytesLeft + maxPacketSize - 1) / maxPacketSize;
  225508. HeapBlock <MIDIPacketList> packets;
  225509. packets.malloc (32 * numPackets + message.getRawDataSize(), 1);
  225510. packets->numPackets = numPackets;
  225511. MIDIPacket* p = packets->packet;
  225512. for (int i = 0; i < numPackets; ++i)
  225513. {
  225514. p->timeStamp = 0;
  225515. p->length = jmin (maxPacketSize, bytesLeft);
  225516. memcpy (p->data, message.getRawData() + pos, p->length);
  225517. pos += p->length;
  225518. bytesLeft -= p->length;
  225519. p = MIDIPacketNext (p);
  225520. }
  225521. if (mpe->port != 0)
  225522. MIDISend (mpe->port, mpe->endPoint, packets);
  225523. else
  225524. MIDIReceived (mpe->endPoint, packets);
  225525. }
  225526. else
  225527. {
  225528. MIDIPacketList packets;
  225529. packets.numPackets = 1;
  225530. packets.packet[0].timeStamp = 0;
  225531. packets.packet[0].length = message.getRawDataSize();
  225532. *(int*) (packets.packet[0].data) = *(const int*) message.getRawData();
  225533. if (mpe->port != 0)
  225534. MIDISend (mpe->port, mpe->endPoint, &packets);
  225535. else
  225536. MIDIReceived (mpe->endPoint, &packets);
  225537. }
  225538. }
  225539. const StringArray MidiInput::getDevices()
  225540. {
  225541. StringArray s;
  225542. const ItemCount num = MIDIGetNumberOfSources();
  225543. for (ItemCount i = 0; i < num; ++i)
  225544. {
  225545. MIDIEndpointRef source = MIDIGetSource (i);
  225546. if (source != 0)
  225547. {
  225548. String name (getConnectedEndpointName (source));
  225549. if (name.isEmpty())
  225550. name = "<error>";
  225551. s.add (name);
  225552. }
  225553. else
  225554. {
  225555. s.add ("<error>");
  225556. }
  225557. }
  225558. return s;
  225559. }
  225560. int MidiInput::getDefaultDeviceIndex()
  225561. {
  225562. return 0;
  225563. }
  225564. struct MidiPortAndCallback
  225565. {
  225566. MidiInput* input;
  225567. MidiPortAndEndpoint* portAndEndpoint;
  225568. MidiInputCallback* callback;
  225569. MemoryBlock pendingData;
  225570. int pendingBytes;
  225571. double pendingDataTime;
  225572. bool active;
  225573. void processSysex (const uint8*& d, int& size, const double time)
  225574. {
  225575. if (*d == 0xf0)
  225576. {
  225577. pendingBytes = 0;
  225578. pendingDataTime = time;
  225579. }
  225580. pendingData.ensureSize (pendingBytes + size, false);
  225581. uint8* totalMessage = (uint8*) pendingData.getData();
  225582. uint8* dest = totalMessage + pendingBytes;
  225583. while (size > 0)
  225584. {
  225585. if (pendingBytes > 0 && *d >= 0x80)
  225586. {
  225587. if (*d >= 0xfa || *d == 0xf8)
  225588. {
  225589. callback->handleIncomingMidiMessage (input, MidiMessage (*d, time));
  225590. ++d;
  225591. --size;
  225592. }
  225593. else
  225594. {
  225595. if (*d == 0xf7)
  225596. {
  225597. *dest++ = *d++;
  225598. pendingBytes++;
  225599. --size;
  225600. }
  225601. break;
  225602. }
  225603. }
  225604. else
  225605. {
  225606. *dest++ = *d++;
  225607. pendingBytes++;
  225608. --size;
  225609. }
  225610. }
  225611. if (totalMessage [pendingBytes - 1] == 0xf7)
  225612. {
  225613. callback->handleIncomingMidiMessage (input, MidiMessage (totalMessage, pendingBytes, pendingDataTime));
  225614. pendingBytes = 0;
  225615. }
  225616. else
  225617. {
  225618. callback->handlePartialSysexMessage (input, totalMessage, pendingBytes, pendingDataTime);
  225619. }
  225620. }
  225621. };
  225622. namespace CoreMidiCallbacks
  225623. {
  225624. static CriticalSection callbackLock;
  225625. static VoidArray activeCallbacks;
  225626. }
  225627. static void midiInputProc (const MIDIPacketList* pktlist,
  225628. void* readProcRefCon,
  225629. void* srcConnRefCon)
  225630. {
  225631. double time = Time::getMillisecondCounterHiRes() * 0.001;
  225632. const double originalTime = time;
  225633. MidiPortAndCallback* const mpc = (MidiPortAndCallback*) readProcRefCon;
  225634. const ScopedLock sl (CoreMidiCallbacks::callbackLock);
  225635. if (CoreMidiCallbacks::activeCallbacks.contains (mpc) && mpc->active)
  225636. {
  225637. const MIDIPacket* packet = &pktlist->packet[0];
  225638. for (unsigned int i = 0; i < pktlist->numPackets; ++i)
  225639. {
  225640. const uint8* d = (const uint8*) (packet->data);
  225641. int size = packet->length;
  225642. while (size > 0)
  225643. {
  225644. time = originalTime;
  225645. if (mpc->pendingBytes > 0 || d[0] == 0xf0)
  225646. {
  225647. mpc->processSysex (d, size, time);
  225648. }
  225649. else
  225650. {
  225651. int used = 0;
  225652. const MidiMessage m (d, size, used, 0, time);
  225653. if (used <= 0)
  225654. {
  225655. jassertfalse // malformed midi message
  225656. break;
  225657. }
  225658. else
  225659. {
  225660. mpc->callback->handleIncomingMidiMessage (mpc->input, m);
  225661. }
  225662. size -= used;
  225663. d += used;
  225664. }
  225665. }
  225666. packet = MIDIPacketNext (packet);
  225667. }
  225668. }
  225669. }
  225670. MidiInput* MidiInput::openDevice (int index, MidiInputCallback* callback)
  225671. {
  225672. MidiInput* mi = 0;
  225673. if (((unsigned int) index) < (unsigned int) MIDIGetNumberOfSources())
  225674. {
  225675. MIDIEndpointRef endPoint = MIDIGetSource (index);
  225676. if (endPoint != 0)
  225677. {
  225678. CFStringRef pname;
  225679. if (OK (MIDIObjectGetStringProperty (endPoint, kMIDIPropertyName, &pname)))
  225680. {
  225681. log ("CoreMidi - opening inp: " + PlatformUtilities::cfStringToJuceString (pname));
  225682. if (makeSureClientExists())
  225683. {
  225684. MIDIPortRef port;
  225685. ScopedPointer <MidiPortAndCallback> mpc (new MidiPortAndCallback());
  225686. mpc->active = false;
  225687. if (OK (MIDIInputPortCreate (globalMidiClient, pname, midiInputProc, mpc, &port)))
  225688. {
  225689. if (OK (MIDIPortConnectSource (port, endPoint, 0)))
  225690. {
  225691. mpc->portAndEndpoint = new MidiPortAndEndpoint (port, endPoint);
  225692. mpc->callback = callback;
  225693. mpc->pendingBytes = 0;
  225694. mpc->pendingData.ensureSize (128);
  225695. mi = new MidiInput (getDevices() [index]);
  225696. mpc->input = mi;
  225697. mi->internal = mpc;
  225698. const ScopedLock sl (CoreMidiCallbacks::callbackLock);
  225699. CoreMidiCallbacks::activeCallbacks.add (mpc.release());
  225700. }
  225701. else
  225702. {
  225703. OK (MIDIPortDispose (port));
  225704. }
  225705. }
  225706. }
  225707. }
  225708. CFRelease (pname);
  225709. }
  225710. }
  225711. return mi;
  225712. }
  225713. MidiInput* MidiInput::createNewDevice (const String& deviceName, MidiInputCallback* callback)
  225714. {
  225715. MidiInput* mi = 0;
  225716. if (makeSureClientExists())
  225717. {
  225718. ScopedPointer <MidiPortAndCallback> mpc (new MidiPortAndCallback());
  225719. mpc->active = false;
  225720. MIDIEndpointRef endPoint;
  225721. CFStringRef name = PlatformUtilities::juceStringToCFString(deviceName);
  225722. if (OK (MIDIDestinationCreate (globalMidiClient, name, midiInputProc, mpc, &endPoint)))
  225723. {
  225724. mpc->portAndEndpoint = new MidiPortAndEndpoint (0, endPoint);
  225725. mpc->callback = callback;
  225726. mpc->pendingBytes = 0;
  225727. mpc->pendingData.ensureSize (128);
  225728. mi = new MidiInput (deviceName);
  225729. mpc->input = mi;
  225730. mi->internal = mpc;
  225731. const ScopedLock sl (CoreMidiCallbacks::callbackLock);
  225732. CoreMidiCallbacks::activeCallbacks.add (mpc.release());
  225733. }
  225734. CFRelease (name);
  225735. }
  225736. return mi;
  225737. }
  225738. MidiInput::MidiInput (const String& name_)
  225739. : name (name_)
  225740. {
  225741. }
  225742. MidiInput::~MidiInput()
  225743. {
  225744. MidiPortAndCallback* const mpc = (MidiPortAndCallback*) internal;
  225745. mpc->active = false;
  225746. {
  225747. const ScopedLock sl (CoreMidiCallbacks::callbackLock);
  225748. CoreMidiCallbacks::activeCallbacks.removeValue (mpc);
  225749. }
  225750. if (mpc->portAndEndpoint->port != 0)
  225751. OK (MIDIPortDisconnectSource (mpc->portAndEndpoint->port, mpc->portAndEndpoint->endPoint));
  225752. delete mpc->portAndEndpoint;
  225753. delete mpc;
  225754. }
  225755. void MidiInput::start()
  225756. {
  225757. const ScopedLock sl (CoreMidiCallbacks::callbackLock);
  225758. ((MidiPortAndCallback*) internal)->active = true;
  225759. }
  225760. void MidiInput::stop()
  225761. {
  225762. const ScopedLock sl (CoreMidiCallbacks::callbackLock);
  225763. ((MidiPortAndCallback*) internal)->active = false;
  225764. }
  225765. #undef log
  225766. #else
  225767. MidiOutput::~MidiOutput()
  225768. {
  225769. }
  225770. void MidiOutput::reset()
  225771. {
  225772. }
  225773. bool MidiOutput::getVolume (float& leftVol, float& rightVol)
  225774. {
  225775. return false;
  225776. }
  225777. void MidiOutput::setVolume (float leftVol, float rightVol)
  225778. {
  225779. }
  225780. void MidiOutput::sendMessageNow (const MidiMessage& message)
  225781. {
  225782. }
  225783. const StringArray MidiOutput::getDevices()
  225784. {
  225785. return StringArray();
  225786. }
  225787. MidiOutput* MidiOutput::openDevice (int index)
  225788. {
  225789. return 0;
  225790. }
  225791. const StringArray MidiInput::getDevices()
  225792. {
  225793. return StringArray();
  225794. }
  225795. MidiInput* MidiInput::openDevice (int index, MidiInputCallback* callback)
  225796. {
  225797. return 0;
  225798. }
  225799. #endif
  225800. #endif
  225801. /*** End of inlined file: juce_mac_CoreMidi.cpp ***/
  225802. #else
  225803. /*** Start of inlined file: juce_mac_Fonts.mm ***/
  225804. // (This file gets included by juce_mac_NativeCode.mm, rather than being
  225805. // compiled on its own).
  225806. #if JUCE_INCLUDED_FILE
  225807. #if MAC_OS_X_VERSION_MIN_REQUIRED < MAC_OS_X_VERSION_10_5
  225808. #define SUPPORT_10_4_FONTS 1
  225809. #define NEW_CGFONT_FUNCTIONS_UNAVAILABLE (CGFontCreateWithFontName == 0)
  225810. #if MAC_OS_X_VERSION_MAX_ALLOWED < MAC_OS_X_VERSION_10_5
  225811. #define SUPPORT_ONLY_10_4_FONTS 1
  225812. #endif
  225813. END_JUCE_NAMESPACE
  225814. @interface NSFont (PrivateHack)
  225815. - (NSGlyph) _defaultGlyphForChar: (unichar) theChar;
  225816. @end
  225817. BEGIN_JUCE_NAMESPACE
  225818. #endif
  225819. class MacTypeface : public Typeface
  225820. {
  225821. public:
  225822. MacTypeface (const Font& font)
  225823. : Typeface (font.getTypefaceName())
  225824. {
  225825. const ScopedAutoReleasePool pool;
  225826. renderingTransform = CGAffineTransformIdentity;
  225827. bool needsItalicTransform = false;
  225828. #if JUCE_IPHONE
  225829. NSString* fontName = juceStringToNS (font.getTypefaceName());
  225830. if (font.isItalic() || font.isBold())
  225831. {
  225832. NSArray* familyFonts = [UIFont fontNamesForFamilyName: juceStringToNS (font.getTypefaceName())];
  225833. for (NSString* i in familyFonts)
  225834. {
  225835. const String fn (nsStringToJuce (i));
  225836. const String afterDash (fn.fromFirstOccurrenceOf ("-", false, false));
  225837. const bool probablyBold = afterDash.containsIgnoreCase ("bold") || fn.endsWithIgnoreCase ("bold");
  225838. const bool probablyItalic = afterDash.containsIgnoreCase ("oblique")
  225839. || afterDash.containsIgnoreCase ("italic")
  225840. || fn.endsWithIgnoreCase ("oblique")
  225841. || fn.endsWithIgnoreCase ("italic");
  225842. if (probablyBold == font.isBold()
  225843. && probablyItalic == font.isItalic())
  225844. {
  225845. fontName = i;
  225846. needsItalicTransform = false;
  225847. break;
  225848. }
  225849. else if (probablyBold && (! probablyItalic) && probablyBold == font.isBold())
  225850. {
  225851. fontName = i;
  225852. needsItalicTransform = true; // not ideal, so carry on in case we find a better one
  225853. }
  225854. }
  225855. if (needsItalicTransform)
  225856. renderingTransform.c = 0.15f;
  225857. }
  225858. fontRef = CGFontCreateWithFontName ((CFStringRef) fontName);
  225859. const int ascender = abs (CGFontGetAscent (fontRef));
  225860. const float totalHeight = ascender + abs (CGFontGetDescent (fontRef));
  225861. ascent = ascender / totalHeight;
  225862. unitsToHeightScaleFactor = 1.0f / totalHeight;
  225863. fontHeightToCGSizeFactor = CGFontGetUnitsPerEm (fontRef) / totalHeight;
  225864. #else
  225865. nsFont = [NSFont fontWithName: juceStringToNS (font.getTypefaceName()) size: 1024];
  225866. if (font.isItalic())
  225867. {
  225868. NSFont* newFont = [[NSFontManager sharedFontManager] convertFont: nsFont
  225869. toHaveTrait: NSItalicFontMask];
  225870. if (newFont == nsFont)
  225871. needsItalicTransform = true; // couldn't find a proper italic version, so fake it with a transform..
  225872. nsFont = newFont;
  225873. }
  225874. if (font.isBold())
  225875. nsFont = [[NSFontManager sharedFontManager] convertFont: nsFont toHaveTrait: NSBoldFontMask];
  225876. [nsFont retain];
  225877. ascent = fabsf ((float) [nsFont ascender]);
  225878. float totalSize = ascent + fabsf ((float) [nsFont descender]);
  225879. ascent /= totalSize;
  225880. pathTransform = AffineTransform::identity.scale (1.0f / totalSize, 1.0f / totalSize);
  225881. if (needsItalicTransform)
  225882. {
  225883. pathTransform = pathTransform.sheared (-0.15f, 0.0f);
  225884. renderingTransform.c = 0.15f;
  225885. }
  225886. #if SUPPORT_ONLY_10_4_FONTS
  225887. ATSFontRef atsFont = ATSFontFindFromName ((CFStringRef) [nsFont fontName], kATSOptionFlagsDefault);
  225888. if (atsFont == 0)
  225889. atsFont = ATSFontFindFromPostScriptName ((CFStringRef) [nsFont fontName], kATSOptionFlagsDefault);
  225890. fontRef = CGFontCreateWithPlatformFont (&atsFont);
  225891. const float totalHeight = fabsf ([nsFont ascender]) + fabsf([nsFont descender]);
  225892. unitsToHeightScaleFactor = 1.0f / totalHeight;
  225893. fontHeightToCGSizeFactor = 1024.0f / totalHeight;
  225894. #else
  225895. #if SUPPORT_10_4_FONTS
  225896. if (NEW_CGFONT_FUNCTIONS_UNAVAILABLE)
  225897. {
  225898. ATSFontRef atsFont = ATSFontFindFromName ((CFStringRef) [nsFont fontName], kATSOptionFlagsDefault);
  225899. if (atsFont == 0)
  225900. atsFont = ATSFontFindFromPostScriptName ((CFStringRef) [nsFont fontName], kATSOptionFlagsDefault);
  225901. fontRef = CGFontCreateWithPlatformFont (&atsFont);
  225902. const float totalHeight = fabsf ([nsFont ascender]) + fabsf([nsFont descender]);
  225903. unitsToHeightScaleFactor = 1.0f / totalHeight;
  225904. fontHeightToCGSizeFactor = 1024.0f / totalHeight;
  225905. }
  225906. else
  225907. #endif
  225908. {
  225909. fontRef = CGFontCreateWithFontName ((CFStringRef) [nsFont fontName]);
  225910. const int totalHeight = abs (CGFontGetAscent (fontRef)) + abs (CGFontGetDescent (fontRef));
  225911. unitsToHeightScaleFactor = 1.0f / totalHeight;
  225912. fontHeightToCGSizeFactor = CGFontGetUnitsPerEm (fontRef) / (float) totalHeight;
  225913. }
  225914. #endif
  225915. #endif
  225916. }
  225917. ~MacTypeface()
  225918. {
  225919. #if ! JUCE_IPHONE
  225920. [nsFont release];
  225921. #endif
  225922. if (fontRef != 0)
  225923. CGFontRelease (fontRef);
  225924. }
  225925. float getAscent() const
  225926. {
  225927. return ascent;
  225928. }
  225929. float getDescent() const
  225930. {
  225931. return 1.0f - ascent;
  225932. }
  225933. float getStringWidth (const String& text)
  225934. {
  225935. if (fontRef == 0 || text.isEmpty())
  225936. return 0;
  225937. const int length = text.length();
  225938. HeapBlock <CGGlyph> glyphs;
  225939. createGlyphsForString (text, length, glyphs);
  225940. float x = 0;
  225941. #if SUPPORT_ONLY_10_4_FONTS
  225942. HeapBlock <NSSize> advances (length);
  225943. [nsFont getAdvancements: advances forGlyphs: reinterpret_cast <NSGlyph*> (glyphs.getData()) count: length];
  225944. for (int i = 0; i < length; ++i)
  225945. x += advances[i].width;
  225946. #else
  225947. #if SUPPORT_10_4_FONTS
  225948. if (NEW_CGFONT_FUNCTIONS_UNAVAILABLE)
  225949. {
  225950. HeapBlock <NSSize> advances (length);
  225951. [nsFont getAdvancements: advances forGlyphs: reinterpret_cast<NSGlyph*> (glyphs.getData()) count: length];
  225952. for (int i = 0; i < length; ++i)
  225953. x += advances[i].width;
  225954. }
  225955. else
  225956. #endif
  225957. {
  225958. HeapBlock <int> advances (length);
  225959. if (CGFontGetGlyphAdvances (fontRef, glyphs, length, advances))
  225960. for (int i = 0; i < length; ++i)
  225961. x += advances[i];
  225962. }
  225963. #endif
  225964. return x * unitsToHeightScaleFactor;
  225965. }
  225966. void getGlyphPositions (const String& text, Array <int>& resultGlyphs, Array <float>& xOffsets)
  225967. {
  225968. xOffsets.add (0);
  225969. if (fontRef == 0 || text.isEmpty())
  225970. return;
  225971. const int length = text.length();
  225972. HeapBlock <CGGlyph> glyphs;
  225973. createGlyphsForString (text, length, glyphs);
  225974. #if SUPPORT_ONLY_10_4_FONTS
  225975. HeapBlock <NSSize> advances (length);
  225976. [nsFont getAdvancements: advances forGlyphs: reinterpret_cast <NSGlyph*> (glyphs.getData()) count: length];
  225977. int x = 0;
  225978. for (int i = 0; i < length; ++i)
  225979. {
  225980. x += advances[i].width;
  225981. xOffsets.add (x * unitsToHeightScaleFactor);
  225982. resultGlyphs.add (reinterpret_cast <NSGlyph*> (glyphs.getData())[i]);
  225983. }
  225984. #else
  225985. #if SUPPORT_10_4_FONTS
  225986. if (NEW_CGFONT_FUNCTIONS_UNAVAILABLE)
  225987. {
  225988. HeapBlock <NSSize> advances (length);
  225989. NSGlyph* const nsGlyphs = reinterpret_cast<NSGlyph*> (glyphs.getData());
  225990. [nsFont getAdvancements: advances forGlyphs: nsGlyphs count: length];
  225991. float x = 0;
  225992. for (int i = 0; i < length; ++i)
  225993. {
  225994. x += advances[i].width;
  225995. xOffsets.add (x * unitsToHeightScaleFactor);
  225996. resultGlyphs.add (nsGlyphs[i]);
  225997. }
  225998. }
  225999. else
  226000. #endif
  226001. {
  226002. HeapBlock <int> advances (length);
  226003. if (CGFontGetGlyphAdvances (fontRef, glyphs, length, advances))
  226004. {
  226005. int x = 0;
  226006. for (int i = 0; i < length; ++i)
  226007. {
  226008. x += advances [i];
  226009. xOffsets.add (x * unitsToHeightScaleFactor);
  226010. resultGlyphs.add (glyphs[i]);
  226011. }
  226012. }
  226013. }
  226014. #endif
  226015. }
  226016. bool getOutlineForGlyph (int glyphNumber, Path& path)
  226017. {
  226018. #if JUCE_IPHONE
  226019. return false;
  226020. #else
  226021. if (nsFont == 0)
  226022. return false;
  226023. // we might need to apply a transform to the path, so it mustn't have anything else in it
  226024. jassert (path.isEmpty());
  226025. const ScopedAutoReleasePool pool;
  226026. NSBezierPath* bez = [NSBezierPath bezierPath];
  226027. [bez moveToPoint: NSMakePoint (0, 0)];
  226028. [bez appendBezierPathWithGlyph: (NSGlyph) glyphNumber
  226029. inFont: nsFont];
  226030. for (int i = 0; i < [bez elementCount]; ++i)
  226031. {
  226032. NSPoint p[3];
  226033. switch ([bez elementAtIndex: i associatedPoints: p])
  226034. {
  226035. case NSMoveToBezierPathElement:
  226036. path.startNewSubPath ((float) p[0].x, (float) -p[0].y);
  226037. break;
  226038. case NSLineToBezierPathElement:
  226039. path.lineTo ((float) p[0].x, (float) -p[0].y);
  226040. break;
  226041. case NSCurveToBezierPathElement:
  226042. 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);
  226043. break;
  226044. case NSClosePathBezierPathElement:
  226045. path.closeSubPath();
  226046. break;
  226047. default:
  226048. jassertfalse
  226049. break;
  226050. }
  226051. }
  226052. path.applyTransform (pathTransform);
  226053. return true;
  226054. #endif
  226055. }
  226056. juce_UseDebuggingNewOperator
  226057. CGFontRef fontRef;
  226058. float fontHeightToCGSizeFactor;
  226059. CGAffineTransform renderingTransform;
  226060. private:
  226061. float ascent, unitsToHeightScaleFactor;
  226062. #if JUCE_IPHONE
  226063. #else
  226064. NSFont* nsFont;
  226065. AffineTransform pathTransform;
  226066. #endif
  226067. void createGlyphsForString (const juce_wchar* const text, const int length, HeapBlock <CGGlyph>& glyphs)
  226068. {
  226069. #if SUPPORT_10_4_FONTS
  226070. #if ! SUPPORT_ONLY_10_4_FONTS
  226071. if (NEW_CGFONT_FUNCTIONS_UNAVAILABLE)
  226072. #endif
  226073. {
  226074. glyphs.malloc (sizeof (NSGlyph) * length, 1);
  226075. NSGlyph* const nsGlyphs = reinterpret_cast<NSGlyph*> (glyphs.getData());
  226076. for (int i = 0; i < length; ++i)
  226077. nsGlyphs[i] = (NSGlyph) [nsFont _defaultGlyphForChar: text[i]];
  226078. return;
  226079. }
  226080. #endif
  226081. #if ! SUPPORT_ONLY_10_4_FONTS
  226082. if (charToGlyphMapper == 0)
  226083. charToGlyphMapper = new CharToGlyphMapper (fontRef);
  226084. glyphs.malloc (length);
  226085. for (int i = 0; i < length; ++i)
  226086. glyphs[i] = (CGGlyph) charToGlyphMapper->getGlyphForCharacter (text[i]);
  226087. #endif
  226088. }
  226089. #if ! SUPPORT_ONLY_10_4_FONTS
  226090. // Reads a CGFontRef's character map table to convert unicode into glyph numbers
  226091. class CharToGlyphMapper
  226092. {
  226093. public:
  226094. CharToGlyphMapper (CGFontRef fontRef)
  226095. : segCount (0), endCode (0), startCode (0), idDelta (0),
  226096. idRangeOffset (0), glyphIndexes (0)
  226097. {
  226098. CFDataRef cmapTable = CGFontCopyTableForTag (fontRef, 'cmap');
  226099. if (cmapTable != 0)
  226100. {
  226101. const int numSubtables = getValue16 (cmapTable, 2);
  226102. for (int i = 0; i < numSubtables; ++i)
  226103. {
  226104. if (getValue16 (cmapTable, i * 8 + 4) == 0) // check for platform ID of 0
  226105. {
  226106. const int offset = getValue32 (cmapTable, i * 8 + 8);
  226107. if (getValue16 (cmapTable, offset) == 4) // check that it's format 4..
  226108. {
  226109. const int length = getValue16 (cmapTable, offset + 2);
  226110. const int segCountX2 = getValue16 (cmapTable, offset + 6);
  226111. segCount = segCountX2 / 2;
  226112. const int endCodeOffset = offset + 14;
  226113. const int startCodeOffset = endCodeOffset + 2 + segCountX2;
  226114. const int idDeltaOffset = startCodeOffset + segCountX2;
  226115. const int idRangeOffsetOffset = idDeltaOffset + segCountX2;
  226116. const int glyphIndexesOffset = idRangeOffsetOffset + segCountX2;
  226117. endCode = CFDataCreate (kCFAllocatorDefault, CFDataGetBytePtr (cmapTable) + endCodeOffset, segCountX2);
  226118. startCode = CFDataCreate (kCFAllocatorDefault, CFDataGetBytePtr (cmapTable) + startCodeOffset, segCountX2);
  226119. idDelta = CFDataCreate (kCFAllocatorDefault, CFDataGetBytePtr (cmapTable) + idDeltaOffset, segCountX2);
  226120. idRangeOffset = CFDataCreate (kCFAllocatorDefault, CFDataGetBytePtr (cmapTable) + idRangeOffsetOffset, segCountX2);
  226121. glyphIndexes = CFDataCreate (kCFAllocatorDefault, CFDataGetBytePtr (cmapTable) + glyphIndexesOffset, offset + length - glyphIndexesOffset);
  226122. }
  226123. break;
  226124. }
  226125. }
  226126. CFRelease (cmapTable);
  226127. }
  226128. }
  226129. ~CharToGlyphMapper()
  226130. {
  226131. if (endCode != 0)
  226132. {
  226133. CFRelease (endCode);
  226134. CFRelease (startCode);
  226135. CFRelease (idDelta);
  226136. CFRelease (idRangeOffset);
  226137. CFRelease (glyphIndexes);
  226138. }
  226139. }
  226140. int getGlyphForCharacter (const juce_wchar c) const
  226141. {
  226142. for (int i = 0; i < segCount; ++i)
  226143. {
  226144. if (getValue16 (endCode, i * 2) >= c)
  226145. {
  226146. const int start = getValue16 (startCode, i * 2);
  226147. if (start > c)
  226148. break;
  226149. const int delta = getValue16 (idDelta, i * 2);
  226150. const int rangeOffset = getValue16 (idRangeOffset, i * 2);
  226151. if (rangeOffset == 0)
  226152. return delta + c;
  226153. else
  226154. return getValue16 (glyphIndexes, 2 * ((rangeOffset / 2) + (c - start) - (segCount - i)));
  226155. }
  226156. }
  226157. // If we failed to find it "properly", this dodgy fall-back seems to do the trick for most fonts!
  226158. return jmax (-1, c - 29);
  226159. }
  226160. private:
  226161. int segCount;
  226162. CFDataRef endCode, startCode, idDelta, idRangeOffset, glyphIndexes;
  226163. static uint16 getValue16 (CFDataRef data, const int index)
  226164. {
  226165. return CFSwapInt16BigToHost (*(UInt16*) (CFDataGetBytePtr (data) + index));
  226166. }
  226167. static uint32 getValue32 (CFDataRef data, const int index)
  226168. {
  226169. return CFSwapInt32BigToHost (*(UInt32*) (CFDataGetBytePtr (data) + index));
  226170. }
  226171. };
  226172. ScopedPointer <CharToGlyphMapper> charToGlyphMapper;
  226173. #endif
  226174. MacTypeface (const MacTypeface&);
  226175. MacTypeface& operator= (const MacTypeface&);
  226176. };
  226177. const Typeface::Ptr Typeface::createSystemTypefaceFor (const Font& font)
  226178. {
  226179. return new MacTypeface (font);
  226180. }
  226181. const StringArray Font::findAllTypefaceNames()
  226182. {
  226183. StringArray names;
  226184. const ScopedAutoReleasePool pool;
  226185. #if JUCE_IPHONE
  226186. NSArray* fonts = [UIFont familyNames];
  226187. #else
  226188. NSArray* fonts = [[NSFontManager sharedFontManager] availableFontFamilies];
  226189. #endif
  226190. for (unsigned int i = 0; i < [fonts count]; ++i)
  226191. names.add (nsStringToJuce ((NSString*) [fonts objectAtIndex: i]));
  226192. names.sort (true);
  226193. return names;
  226194. }
  226195. void Font::getPlatformDefaultFontNames (String& defaultSans, String& defaultSerif, String& defaultFixed)
  226196. {
  226197. #if JUCE_IPHONE
  226198. defaultSans = "Helvetica";
  226199. defaultSerif = "Times New Roman";
  226200. defaultFixed = "Courier New";
  226201. #else
  226202. defaultSans = "Lucida Grande";
  226203. defaultSerif = "Times New Roman";
  226204. defaultFixed = "Monaco";
  226205. #endif
  226206. }
  226207. #endif
  226208. /*** End of inlined file: juce_mac_Fonts.mm ***/
  226209. // (must go before juce_mac_CoreGraphicsContext.mm)
  226210. /*** Start of inlined file: juce_mac_CoreGraphicsContext.mm ***/
  226211. // (This file gets included by juce_mac_NativeCode.mm, rather than being
  226212. // compiled on its own).
  226213. #if JUCE_INCLUDED_FILE
  226214. class CoreGraphicsImage : public Image
  226215. {
  226216. public:
  226217. CoreGraphicsImage (const PixelFormat format_,
  226218. const int imageWidth_,
  226219. const int imageHeight_,
  226220. const bool clearImage)
  226221. : Image (format_, imageWidth_, imageHeight_, clearImage)
  226222. {
  226223. CGColorSpaceRef colourSpace = (format == Image::SingleChannel) ? CGColorSpaceCreateDeviceGray()
  226224. : CGColorSpaceCreateDeviceRGB();
  226225. context = CGBitmapContextCreate (imageData, imageWidth, imageHeight, 8, lineStride,
  226226. colourSpace, getCGImageFlags (*this));
  226227. CGColorSpaceRelease (colourSpace);
  226228. }
  226229. ~CoreGraphicsImage()
  226230. {
  226231. CGContextRelease (context);
  226232. }
  226233. LowLevelGraphicsContext* createLowLevelContext();
  226234. static CGImageRef createImage (const Image& juceImage, const bool forAlpha, CGColorSpaceRef colourSpace)
  226235. {
  226236. const CoreGraphicsImage* nativeImage = dynamic_cast <const CoreGraphicsImage*> (&juceImage);
  226237. if (nativeImage != 0 && (juceImage.getFormat() == Image::SingleChannel || ! forAlpha))
  226238. {
  226239. return CGBitmapContextCreateImage (nativeImage->context);
  226240. }
  226241. else
  226242. {
  226243. const Image::BitmapData srcData (juceImage, 0, 0, juceImage.getWidth(), juceImage.getHeight());
  226244. CGDataProviderRef provider = CGDataProviderCreateWithData (0, srcData.data, srcData.lineStride * srcData.height, 0);
  226245. CGImageRef imageRef = CGImageCreate (srcData.width, srcData.height,
  226246. 8, srcData.pixelStride * 8, srcData.lineStride,
  226247. colourSpace, getCGImageFlags (juceImage), provider,
  226248. 0, true, kCGRenderingIntentDefault);
  226249. CGDataProviderRelease (provider);
  226250. return imageRef;
  226251. }
  226252. }
  226253. #if JUCE_MAC
  226254. static NSImage* createNSImage (const Image& image)
  226255. {
  226256. const ScopedAutoReleasePool pool;
  226257. NSImage* im = [[NSImage alloc] init];
  226258. [im setSize: NSMakeSize (image.getWidth(), image.getHeight())];
  226259. [im lockFocus];
  226260. CGColorSpaceRef colourSpace = CGColorSpaceCreateDeviceRGB();
  226261. CGImageRef imageRef = createImage (image, false, colourSpace);
  226262. CGColorSpaceRelease (colourSpace);
  226263. CGContextRef cg = (CGContextRef) [[NSGraphicsContext currentContext] graphicsPort];
  226264. CGContextDrawImage (cg, CGRectMake (0, 0, image.getWidth(), image.getHeight()), imageRef);
  226265. CGImageRelease (imageRef);
  226266. [im unlockFocus];
  226267. return im;
  226268. }
  226269. #endif
  226270. CGContextRef context;
  226271. private:
  226272. static CGBitmapInfo getCGImageFlags (const Image& image)
  226273. {
  226274. #if JUCE_BIG_ENDIAN
  226275. return image.getFormat() == Image::ARGB ? (kCGImageAlphaPremultipliedFirst | kCGBitmapByteOrder32Big) : kCGBitmapByteOrderDefault;
  226276. #else
  226277. return image.getFormat() == Image::ARGB ? (kCGImageAlphaPremultipliedFirst | kCGBitmapByteOrder32Little) : kCGBitmapByteOrderDefault;
  226278. #endif
  226279. }
  226280. };
  226281. Image* Image::createNativeImage (const PixelFormat format, const int imageWidth, const int imageHeight, const bool clearImage)
  226282. {
  226283. #if USE_COREGRAPHICS_RENDERING
  226284. return new CoreGraphicsImage (format == RGB ? ARGB : format, imageWidth, imageHeight, clearImage);
  226285. #else
  226286. return new Image (format, imageWidth, imageHeight, clearImage);
  226287. #endif
  226288. }
  226289. class CoreGraphicsContext : public LowLevelGraphicsContext
  226290. {
  226291. public:
  226292. CoreGraphicsContext (CGContextRef context_, const float flipHeight_)
  226293. : context (context_),
  226294. flipHeight (flipHeight_),
  226295. state (new SavedState()),
  226296. numGradientLookupEntries (0)
  226297. {
  226298. CGContextRetain (context);
  226299. CGContextSaveGState(context);
  226300. CGContextSetShouldSmoothFonts (context, true);
  226301. CGContextSetShouldAntialias (context, true);
  226302. CGContextSetBlendMode (context, kCGBlendModeNormal);
  226303. rgbColourSpace = CGColorSpaceCreateDeviceRGB();
  226304. greyColourSpace = CGColorSpaceCreateDeviceGray();
  226305. gradientCallbacks.version = 0;
  226306. gradientCallbacks.evaluate = gradientCallback;
  226307. gradientCallbacks.releaseInfo = 0;
  226308. setFont (Font());
  226309. }
  226310. ~CoreGraphicsContext()
  226311. {
  226312. CGContextRestoreGState (context);
  226313. CGContextRelease (context);
  226314. CGColorSpaceRelease (rgbColourSpace);
  226315. CGColorSpaceRelease (greyColourSpace);
  226316. }
  226317. bool isVectorDevice() const { return false; }
  226318. void setOrigin (int x, int y)
  226319. {
  226320. CGContextTranslateCTM (context, x, -y);
  226321. }
  226322. bool clipToRectangle (const Rectangle<int>& r)
  226323. {
  226324. CGContextClipToRect (context, CGRectMake (r.getX(), flipHeight - r.getBottom(), r.getWidth(), r.getHeight()));
  226325. return ! isClipEmpty();
  226326. }
  226327. bool clipToRectangleList (const RectangleList& clipRegion)
  226328. {
  226329. if (clipRegion.isEmpty())
  226330. {
  226331. CGContextClipToRect (context, CGRectMake (0, 0, 0, 0));
  226332. return false;
  226333. }
  226334. else
  226335. {
  226336. const int numRects = clipRegion.getNumRectangles();
  226337. HeapBlock <CGRect> rects (numRects);
  226338. for (int i = 0; i < numRects; ++i)
  226339. {
  226340. const Rectangle<int>& r = clipRegion.getRectangle(i);
  226341. rects[i] = CGRectMake (r.getX(), flipHeight - r.getBottom(), r.getWidth(), r.getHeight());
  226342. }
  226343. CGContextClipToRects (context, rects, numRects);
  226344. return ! isClipEmpty();
  226345. }
  226346. }
  226347. void excludeClipRectangle (const Rectangle<int>& r)
  226348. {
  226349. RectangleList remaining (getClipBounds());
  226350. remaining.subtract (r);
  226351. clipToRectangleList (remaining);
  226352. }
  226353. void clipToPath (const Path& path, const AffineTransform& transform)
  226354. {
  226355. createPath (path, transform);
  226356. CGContextClip (context);
  226357. }
  226358. void clipToImageAlpha (const Image& sourceImage, const Rectangle<int>& srcClip, const AffineTransform& transform)
  226359. {
  226360. if (! transform.isSingularity())
  226361. {
  226362. ScopedPointer<Image> imageToDelete;
  226363. const Image* singleChannelImage = &sourceImage;
  226364. if (sourceImage.getFormat() != Image::SingleChannel)
  226365. {
  226366. imageToDelete = sourceImage.createCopyOfAlphaChannel();
  226367. singleChannelImage = imageToDelete;
  226368. }
  226369. CGImageRef image = CoreGraphicsImage::createImage (*singleChannelImage, true, greyColourSpace);
  226370. flip();
  226371. AffineTransform t (AffineTransform::scale (1.0f, -1.0f).translated (0, sourceImage.getHeight()).followedBy (transform));
  226372. applyTransform (t);
  226373. CGRect r = CGRectMake (0, 0, sourceImage.getWidth(), sourceImage.getHeight());
  226374. CGContextClipToMask (context, r, image);
  226375. applyTransform (t.inverted());
  226376. flip();
  226377. CGImageRelease (image);
  226378. }
  226379. }
  226380. bool clipRegionIntersects (const Rectangle<int>& r)
  226381. {
  226382. return getClipBounds().intersects (r);
  226383. }
  226384. const Rectangle<int> getClipBounds() const
  226385. {
  226386. CGRect bounds = CGRectIntegral (CGContextGetClipBoundingBox (context));
  226387. return Rectangle<int> (roundToInt (bounds.origin.x),
  226388. roundToInt (flipHeight - (bounds.origin.y + bounds.size.height)),
  226389. roundToInt (bounds.size.width),
  226390. roundToInt (bounds.size.height));
  226391. }
  226392. bool isClipEmpty() const
  226393. {
  226394. return CGRectIsEmpty (CGContextGetClipBoundingBox (context));
  226395. }
  226396. void saveState()
  226397. {
  226398. CGContextSaveGState (context);
  226399. stateStack.add (new SavedState (*state));
  226400. }
  226401. void restoreState()
  226402. {
  226403. CGContextRestoreGState (context);
  226404. SavedState* const top = stateStack.getLast();
  226405. if (top != 0)
  226406. {
  226407. state = top;
  226408. stateStack.removeLast (1, false);
  226409. }
  226410. else
  226411. {
  226412. jassertfalse // trying to pop with an empty stack!
  226413. }
  226414. }
  226415. void setFill (const FillType& fillType)
  226416. {
  226417. state->fillType = fillType;
  226418. if (fillType.isColour())
  226419. {
  226420. CGContextSetRGBFillColor (context, fillType.colour.getFloatRed(), fillType.colour.getFloatGreen(),
  226421. fillType.colour.getFloatBlue(), fillType.colour.getFloatAlpha());
  226422. CGContextSetAlpha (context, 1.0f);
  226423. }
  226424. }
  226425. void setOpacity (float newOpacity)
  226426. {
  226427. state->fillType.setOpacity (newOpacity);
  226428. setFill (state->fillType);
  226429. }
  226430. void setInterpolationQuality (Graphics::ResamplingQuality quality)
  226431. {
  226432. CGContextSetInterpolationQuality (context, quality == Graphics::lowResamplingQuality
  226433. ? kCGInterpolationLow
  226434. : kCGInterpolationHigh);
  226435. }
  226436. void fillRect (const Rectangle<int>& r, const bool replaceExistingContents)
  226437. {
  226438. CGRect cgRect = CGRectMake (r.getX(), flipHeight - r.getBottom(), r.getWidth(), r.getHeight());
  226439. if (replaceExistingContents)
  226440. {
  226441. #if MAC_OS_X_VERSION_MAX_ALLOWED < MAC_OS_X_VERSION_10_5
  226442. CGContextClearRect (context, cgRect);
  226443. #else
  226444. #if MAC_OS_X_VERSION_MIN_REQUIRED < MAC_OS_X_VERSION_10_5
  226445. if (CGContextDrawLinearGradient == 0) // (just a way of checking whether we're running in 10.5 or later)
  226446. CGContextClearRect (context, cgRect);
  226447. else
  226448. #endif
  226449. CGContextSetBlendMode (context, kCGBlendModeCopy);
  226450. #endif
  226451. fillRect (r, false);
  226452. CGContextSetBlendMode (context, kCGBlendModeNormal);
  226453. }
  226454. else
  226455. {
  226456. if (state->fillType.isColour())
  226457. {
  226458. CGContextFillRect (context, cgRect);
  226459. }
  226460. else if (state->fillType.isGradient())
  226461. {
  226462. CGContextSaveGState (context);
  226463. CGContextClipToRect (context, cgRect);
  226464. drawGradient();
  226465. CGContextRestoreGState (context);
  226466. }
  226467. else
  226468. {
  226469. CGContextSaveGState (context);
  226470. CGContextClipToRect (context, cgRect);
  226471. drawImage (*(state->fillType.image), state->fillType.image->getBounds(), state->fillType.transform, true);
  226472. CGContextRestoreGState (context);
  226473. }
  226474. }
  226475. }
  226476. void fillPath (const Path& path, const AffineTransform& transform)
  226477. {
  226478. CGContextSaveGState (context);
  226479. if (state->fillType.isColour())
  226480. {
  226481. flip();
  226482. applyTransform (transform);
  226483. createPath (path);
  226484. if (path.isUsingNonZeroWinding())
  226485. CGContextFillPath (context);
  226486. else
  226487. CGContextEOFillPath (context);
  226488. }
  226489. else
  226490. {
  226491. createPath (path, transform);
  226492. if (path.isUsingNonZeroWinding())
  226493. CGContextClip (context);
  226494. else
  226495. CGContextEOClip (context);
  226496. if (state->fillType.isGradient())
  226497. drawGradient();
  226498. else
  226499. drawImage (*(state->fillType.image), state->fillType.image->getBounds(), state->fillType.transform, true);
  226500. }
  226501. CGContextRestoreGState (context);
  226502. }
  226503. void drawImage (const Image& sourceImage, const Rectangle<int>& srcClip,
  226504. const AffineTransform& transform, const bool fillEntireClipAsTiles)
  226505. {
  226506. jassert (sourceImage.getBounds().contains (srcClip));
  226507. CGImageRef fullImage = CoreGraphicsImage::createImage (sourceImage, false, rgbColourSpace);
  226508. CGImageRef image = fullImage;
  226509. if (srcClip != sourceImage.getBounds())
  226510. {
  226511. image = CGImageCreateWithImageInRect (fullImage, CGRectMake (srcClip.getX(), srcClip.getY(),
  226512. srcClip.getWidth(), srcClip.getHeight()));
  226513. CGImageRelease (fullImage);
  226514. }
  226515. CGContextSaveGState (context);
  226516. CGContextSetAlpha (context, state->fillType.getOpacity());
  226517. flip();
  226518. applyTransform (AffineTransform::scale (1.0f, -1.0f).translated (0, srcClip.getHeight()).followedBy (transform));
  226519. CGRect imageRect = CGRectMake (0, 0, srcClip.getWidth(), srcClip.getHeight());
  226520. if (fillEntireClipAsTiles)
  226521. {
  226522. #if JUCE_IPHONE
  226523. CGContextDrawTiledImage (context, imageRect, image);
  226524. #else
  226525. #if MAC_OS_X_VERSION_MAX_ALLOWED >= MAC_OS_X_VERSION_10_5
  226526. // There's a bug in CGContextDrawTiledImage that makes it incredibly slow
  226527. // if it's doing a transformation - it's quicker to just draw lots of images manually
  226528. if (CGContextDrawTiledImage != 0 && transform.isOnlyTranslation())
  226529. CGContextDrawTiledImage (context, imageRect, image);
  226530. else
  226531. #endif
  226532. {
  226533. // Fallback to manually doing a tiled fill on 10.4
  226534. CGRect clip = CGRectIntegral (CGContextGetClipBoundingBox (context));
  226535. const int iw = srcClip.getWidth();
  226536. const int ih = srcClip.getHeight();
  226537. int x = 0, y = 0;
  226538. while (x > clip.origin.x) x -= iw;
  226539. while (y > clip.origin.y) y -= ih;
  226540. const int right = (int) (clip.origin.x + clip.size.width);
  226541. const int bottom = (int) (clip.origin.y + clip.size.height);
  226542. while (y < bottom)
  226543. {
  226544. for (int x2 = x; x2 < right; x2 += iw)
  226545. CGContextDrawImage (context, CGRectMake (x2, y, iw, ih), image);
  226546. y += ih;
  226547. }
  226548. }
  226549. #endif
  226550. }
  226551. else
  226552. {
  226553. CGContextDrawImage (context, imageRect, image);
  226554. }
  226555. CGImageRelease (image); // (This causes a memory bug in iPhone sim 3.0 - try upgrading to a later version if you hit this)
  226556. CGContextRestoreGState (context);
  226557. }
  226558. void drawLine (double x1, double y1, double x2, double y2)
  226559. {
  226560. CGContextSetLineCap (context, kCGLineCapSquare);
  226561. CGContextSetLineWidth (context, 1.0f);
  226562. CGContextSetRGBStrokeColor (context,
  226563. state->fillType.colour.getFloatRed(), state->fillType.colour.getFloatGreen(),
  226564. state->fillType.colour.getFloatBlue(), state->fillType.colour.getFloatAlpha());
  226565. CGPoint line[] = { { (CGFloat) x1, flipHeight - (CGFloat) y1 },
  226566. { (CGFloat) x2, flipHeight - (CGFloat) y2 } };
  226567. CGContextStrokeLineSegments (context, line, 1);
  226568. }
  226569. void drawVerticalLine (const int x, double top, double bottom)
  226570. {
  226571. #if MAC_OS_X_VERSION_MIN_REQUIRED > MAC_OS_X_VERSION_10_5
  226572. CGContextFillRect (context, CGRectMake (x, flipHeight - (float) bottom, 1.0f, (float) (bottom - top)));
  226573. #else
  226574. // On Leopard, unless both co-ordinates are non-integer, it disables anti-aliasing, so nudge
  226575. // the x co-ord slightly to trick it..
  226576. CGContextFillRect (context, CGRectMake (x + 1.0f / 256.0f, flipHeight - (float) bottom, 1.0f + 1.0f / 256.0f, (float) (bottom - top)));
  226577. #endif
  226578. }
  226579. void drawHorizontalLine (const int y, double left, double right)
  226580. {
  226581. #if MAC_OS_X_VERSION_MIN_REQUIRED > MAC_OS_X_VERSION_10_5
  226582. CGContextFillRect (context, CGRectMake ((float) left, flipHeight - (y + 1.0f), (float) (right - left), 1.0f));
  226583. #else
  226584. // On Leopard, unless both co-ordinates are non-integer, it disables anti-aliasing, so nudge
  226585. // the x co-ord slightly to trick it..
  226586. CGContextFillRect (context, CGRectMake ((float) left, flipHeight - (y + (1.0f + 1.0f / 256.0f)), (float) (right - left), 1.0f + 1.0f / 256.0f));
  226587. #endif
  226588. }
  226589. void setFont (const Font& newFont)
  226590. {
  226591. if (state->font != newFont)
  226592. {
  226593. state->fontRef = 0;
  226594. state->font = newFont;
  226595. MacTypeface* mf = dynamic_cast <MacTypeface*> (state->font.getTypeface());
  226596. if (mf != 0)
  226597. {
  226598. state->fontRef = mf->fontRef;
  226599. CGContextSetFont (context, state->fontRef);
  226600. CGContextSetFontSize (context, state->font.getHeight() * mf->fontHeightToCGSizeFactor);
  226601. state->fontTransform = mf->renderingTransform;
  226602. state->fontTransform.a *= state->font.getHorizontalScale();
  226603. CGContextSetTextMatrix (context, state->fontTransform);
  226604. }
  226605. }
  226606. }
  226607. const Font getFont()
  226608. {
  226609. return state->font;
  226610. }
  226611. void drawGlyph (int glyphNumber, const AffineTransform& transform)
  226612. {
  226613. if (state->fontRef != 0 && state->fillType.isColour())
  226614. {
  226615. if (transform.isOnlyTranslation())
  226616. {
  226617. CGGlyph g = glyphNumber;
  226618. CGContextShowGlyphsAtPoint (context, transform.getTranslationX(),
  226619. flipHeight - roundToInt (transform.getTranslationY()), &g, 1);
  226620. }
  226621. else
  226622. {
  226623. CGContextSaveGState (context);
  226624. flip();
  226625. applyTransform (transform);
  226626. CGAffineTransform t = state->fontTransform;
  226627. t.d = -t.d;
  226628. CGContextSetTextMatrix (context, t);
  226629. CGGlyph g = glyphNumber;
  226630. CGContextShowGlyphsAtPoint (context, 0, 0, &g, 1);
  226631. CGContextSetTextMatrix (context, state->fontTransform);
  226632. CGContextRestoreGState (context);
  226633. }
  226634. }
  226635. else
  226636. {
  226637. Path p;
  226638. Font& f = state->font;
  226639. f.getTypeface()->getOutlineForGlyph (glyphNumber, p);
  226640. fillPath (p, AffineTransform::scale (f.getHeight() * f.getHorizontalScale(), f.getHeight())
  226641. .followedBy (transform));
  226642. }
  226643. }
  226644. private:
  226645. CGContextRef context;
  226646. const CGFloat flipHeight;
  226647. CGColorSpaceRef rgbColourSpace, greyColourSpace;
  226648. CGFunctionCallbacks gradientCallbacks;
  226649. struct SavedState
  226650. {
  226651. SavedState()
  226652. : font (1.0f), fontRef (0), fontTransform (CGAffineTransformIdentity)
  226653. {
  226654. }
  226655. SavedState (const SavedState& other)
  226656. : fillType (other.fillType), font (other.font), fontRef (other.fontRef),
  226657. fontTransform (other.fontTransform)
  226658. {
  226659. }
  226660. ~SavedState()
  226661. {
  226662. }
  226663. FillType fillType;
  226664. Font font;
  226665. CGFontRef fontRef;
  226666. CGAffineTransform fontTransform;
  226667. };
  226668. ScopedPointer <SavedState> state;
  226669. OwnedArray <SavedState> stateStack;
  226670. HeapBlock <PixelARGB> gradientLookupTable;
  226671. int numGradientLookupEntries;
  226672. static void gradientCallback (void* info, const CGFloat* inData, CGFloat* outData)
  226673. {
  226674. const CoreGraphicsContext* const g = static_cast <const CoreGraphicsContext*> (info);
  226675. const int index = roundToInt (g->numGradientLookupEntries * inData[0]);
  226676. PixelARGB colour (g->gradientLookupTable [jlimit (0, g->numGradientLookupEntries, index)]);
  226677. colour.unpremultiply();
  226678. outData[0] = colour.getRed() / 255.0f;
  226679. outData[1] = colour.getGreen() / 255.0f;
  226680. outData[2] = colour.getBlue() / 255.0f;
  226681. outData[3] = colour.getAlpha() / 255.0f;
  226682. }
  226683. CGShadingRef createGradient (const AffineTransform& transform, ColourGradient gradient)
  226684. {
  226685. numGradientLookupEntries = gradient.createLookupTable (transform, gradientLookupTable);
  226686. --numGradientLookupEntries;
  226687. CGShadingRef result = 0;
  226688. CGFunctionRef function = CGFunctionCreate (this, 1, 0, 4, 0, &gradientCallbacks);
  226689. CGPoint p1 (CGPointMake (gradient.x1, gradient.y1));
  226690. if (gradient.isRadial)
  226691. {
  226692. result = CGShadingCreateRadial (rgbColourSpace, p1, 0,
  226693. p1, hypotf (gradient.x1 - gradient.x2, gradient.y1 - gradient.y2),
  226694. function, true, true);
  226695. }
  226696. else
  226697. {
  226698. result = CGShadingCreateAxial (rgbColourSpace, p1,
  226699. CGPointMake (gradient.x2, gradient.y2),
  226700. function, true, true);
  226701. }
  226702. CGFunctionRelease (function);
  226703. return result;
  226704. }
  226705. void drawGradient()
  226706. {
  226707. flip();
  226708. applyTransform (state->fillType.transform);
  226709. CGContextSetInterpolationQuality (context, kCGInterpolationDefault); // (This is required for 10.4, where there's a crash if
  226710. // you draw a gradient with high quality interp enabled).
  226711. CGShadingRef shading = createGradient (state->fillType.transform, *(state->fillType.gradient));
  226712. CGContextSetAlpha (context, state->fillType.getOpacity());
  226713. CGContextDrawShading (context, shading);
  226714. CGShadingRelease (shading);
  226715. }
  226716. void createPath (const Path& path) const
  226717. {
  226718. CGContextBeginPath (context);
  226719. Path::Iterator i (path);
  226720. while (i.next())
  226721. {
  226722. switch (i.elementType)
  226723. {
  226724. case Path::Iterator::startNewSubPath:
  226725. CGContextMoveToPoint (context, i.x1, i.y1);
  226726. break;
  226727. case Path::Iterator::lineTo:
  226728. CGContextAddLineToPoint (context, i.x1, i.y1);
  226729. break;
  226730. case Path::Iterator::quadraticTo:
  226731. CGContextAddQuadCurveToPoint (context, i.x1, i.y1, i.x2, i.y2);
  226732. break;
  226733. case Path::Iterator::cubicTo:
  226734. CGContextAddCurveToPoint (context, i.x1, i.y1, i.x2, i.y2, i.x3, i.y3);
  226735. break;
  226736. case Path::Iterator::closePath:
  226737. CGContextClosePath (context); break;
  226738. default:
  226739. jassertfalse
  226740. break;
  226741. }
  226742. }
  226743. }
  226744. void createPath (const Path& path, const AffineTransform& transform) const
  226745. {
  226746. CGContextBeginPath (context);
  226747. Path::Iterator i (path);
  226748. while (i.next())
  226749. {
  226750. switch (i.elementType)
  226751. {
  226752. case Path::Iterator::startNewSubPath:
  226753. transform.transformPoint (i.x1, i.y1);
  226754. CGContextMoveToPoint (context, i.x1, flipHeight - i.y1);
  226755. break;
  226756. case Path::Iterator::lineTo:
  226757. transform.transformPoint (i.x1, i.y1);
  226758. CGContextAddLineToPoint (context, i.x1, flipHeight - i.y1);
  226759. break;
  226760. case Path::Iterator::quadraticTo:
  226761. transform.transformPoint (i.x1, i.y1);
  226762. transform.transformPoint (i.x2, i.y2);
  226763. CGContextAddQuadCurveToPoint (context, i.x1, flipHeight - i.y1, i.x2, flipHeight - i.y2);
  226764. break;
  226765. case Path::Iterator::cubicTo:
  226766. transform.transformPoint (i.x1, i.y1);
  226767. transform.transformPoint (i.x2, i.y2);
  226768. transform.transformPoint (i.x3, i.y3);
  226769. CGContextAddCurveToPoint (context, i.x1, flipHeight - i.y1, i.x2, flipHeight - i.y2, i.x3, flipHeight - i.y3);
  226770. break;
  226771. case Path::Iterator::closePath:
  226772. CGContextClosePath (context); break;
  226773. default:
  226774. jassertfalse
  226775. break;
  226776. }
  226777. }
  226778. }
  226779. void flip() const
  226780. {
  226781. CGContextConcatCTM (context, CGAffineTransformMake (1, 0, 0, -1, 0, flipHeight));
  226782. }
  226783. void applyTransform (const AffineTransform& transform) const
  226784. {
  226785. CGAffineTransform t;
  226786. t.a = transform.mat00;
  226787. t.b = transform.mat10;
  226788. t.c = transform.mat01;
  226789. t.d = transform.mat11;
  226790. t.tx = transform.mat02;
  226791. t.ty = transform.mat12;
  226792. CGContextConcatCTM (context, t);
  226793. }
  226794. CoreGraphicsContext (const CoreGraphicsContext&);
  226795. CoreGraphicsContext& operator= (const CoreGraphicsContext&);
  226796. };
  226797. LowLevelGraphicsContext* CoreGraphicsImage::createLowLevelContext()
  226798. {
  226799. return new CoreGraphicsContext (context, imageHeight);
  226800. }
  226801. #endif
  226802. /*** End of inlined file: juce_mac_CoreGraphicsContext.mm ***/
  226803. /*** Start of inlined file: juce_mac_NSViewComponentPeer.mm ***/
  226804. // (This file gets included by juce_mac_NativeCode.mm, rather than being
  226805. // compiled on its own).
  226806. #if JUCE_INCLUDED_FILE
  226807. class NSViewComponentPeer;
  226808. END_JUCE_NAMESPACE
  226809. #define JuceNSView MakeObjCClassName(JuceNSView)
  226810. @interface JuceNSView : NSView<NSTextInput>
  226811. {
  226812. @public
  226813. NSViewComponentPeer* owner;
  226814. NSNotificationCenter* notificationCenter;
  226815. String* stringBeingComposed;
  226816. bool textWasInserted;
  226817. }
  226818. - (JuceNSView*) initWithOwner: (NSViewComponentPeer*) owner withFrame: (NSRect) frame;
  226819. - (void) dealloc;
  226820. - (BOOL) isOpaque;
  226821. - (void) drawRect: (NSRect) r;
  226822. - (void) mouseDown: (NSEvent*) ev;
  226823. - (void) asyncMouseDown: (NSEvent*) ev;
  226824. - (void) mouseUp: (NSEvent*) ev;
  226825. - (void) asyncMouseUp: (NSEvent*) ev;
  226826. - (void) mouseDragged: (NSEvent*) ev;
  226827. - (void) mouseMoved: (NSEvent*) ev;
  226828. - (void) mouseEntered: (NSEvent*) ev;
  226829. - (void) mouseExited: (NSEvent*) ev;
  226830. - (void) rightMouseDown: (NSEvent*) ev;
  226831. - (void) rightMouseDragged: (NSEvent*) ev;
  226832. - (void) rightMouseUp: (NSEvent*) ev;
  226833. - (void) otherMouseDown: (NSEvent*) ev;
  226834. - (void) otherMouseDragged: (NSEvent*) ev;
  226835. - (void) otherMouseUp: (NSEvent*) ev;
  226836. - (void) scrollWheel: (NSEvent*) ev;
  226837. - (BOOL) acceptsFirstMouse: (NSEvent*) ev;
  226838. - (void) frameChanged: (NSNotification*) n;
  226839. - (void) viewDidMoveToWindow;
  226840. - (void) keyDown: (NSEvent*) ev;
  226841. - (void) keyUp: (NSEvent*) ev;
  226842. // NSTextInput Methods
  226843. - (void) insertText: (id) aString;
  226844. - (void) doCommandBySelector: (SEL) aSelector;
  226845. - (void) setMarkedText: (id) aString selectedRange: (NSRange) selRange;
  226846. - (void) unmarkText;
  226847. - (BOOL) hasMarkedText;
  226848. - (long) conversationIdentifier;
  226849. - (NSAttributedString*) attributedSubstringFromRange: (NSRange) theRange;
  226850. - (NSRange) markedRange;
  226851. - (NSRange) selectedRange;
  226852. - (NSRect) firstRectForCharacterRange: (NSRange) theRange;
  226853. - (unsigned int) characterIndexForPoint: (NSPoint) thePoint;
  226854. - (NSArray*) validAttributesForMarkedText;
  226855. - (void) flagsChanged: (NSEvent*) ev;
  226856. #if MAC_OS_X_VERSION_MIN_REQUIRED < MAC_OS_X_VERSION_10_5
  226857. - (BOOL) performKeyEquivalent: (NSEvent*) ev;
  226858. #endif
  226859. - (BOOL) becomeFirstResponder;
  226860. - (BOOL) resignFirstResponder;
  226861. - (BOOL) acceptsFirstResponder;
  226862. - (void) asyncRepaint: (id) rect;
  226863. - (NSArray*) getSupportedDragTypes;
  226864. - (BOOL) sendDragCallback: (int) type sender: (id <NSDraggingInfo>) sender;
  226865. - (NSDragOperation) draggingEntered: (id <NSDraggingInfo>) sender;
  226866. - (NSDragOperation) draggingUpdated: (id <NSDraggingInfo>) sender;
  226867. - (void) draggingEnded: (id <NSDraggingInfo>) sender;
  226868. - (void) draggingExited: (id <NSDraggingInfo>) sender;
  226869. - (BOOL) prepareForDragOperation: (id <NSDraggingInfo>) sender;
  226870. - (BOOL) performDragOperation: (id <NSDraggingInfo>) sender;
  226871. - (void) concludeDragOperation: (id <NSDraggingInfo>) sender;
  226872. @end
  226873. #define JuceNSWindow MakeObjCClassName(JuceNSWindow)
  226874. #if defined (MAC_OS_X_VERSION_10_6) && MAC_OS_X_VERSION_MAX_ALLOWED >= MAC_OS_X_VERSION_10_6
  226875. @interface JuceNSWindow : NSWindow <NSWindowDelegate>
  226876. #else
  226877. @interface JuceNSWindow : NSWindow
  226878. #endif
  226879. {
  226880. @private
  226881. NSViewComponentPeer* owner;
  226882. bool isZooming;
  226883. }
  226884. - (void) setOwner: (NSViewComponentPeer*) owner;
  226885. - (BOOL) canBecomeKeyWindow;
  226886. - (void) becomeKeyWindow;
  226887. - (BOOL) windowShouldClose: (id) window;
  226888. - (NSRect) constrainFrameRect: (NSRect) frameRect toScreen: (NSScreen*) screen;
  226889. - (NSSize) windowWillResize: (NSWindow*) window toSize: (NSSize) proposedFrameSize;
  226890. - (void) zoom: (id) sender;
  226891. @end
  226892. BEGIN_JUCE_NAMESPACE
  226893. class NSViewComponentPeer : public ComponentPeer
  226894. {
  226895. public:
  226896. NSViewComponentPeer (Component* const component,
  226897. const int windowStyleFlags,
  226898. NSView* viewToAttachTo);
  226899. ~NSViewComponentPeer();
  226900. void* getNativeHandle() const;
  226901. void setVisible (bool shouldBeVisible);
  226902. void setTitle (const String& title);
  226903. void setPosition (int x, int y);
  226904. void setSize (int w, int h);
  226905. void setBounds (int x, int y, int w, int h, const bool isNowFullScreen);
  226906. const Rectangle<int> getBounds (const bool global) const;
  226907. const Rectangle<int> getBounds() const;
  226908. const Point<int> getScreenPosition() const;
  226909. const Point<int> relativePositionToGlobal (const Point<int>& relativePosition);
  226910. const Point<int> globalPositionToRelative (const Point<int>& screenPosition);
  226911. void setMinimised (bool shouldBeMinimised);
  226912. bool isMinimised() const;
  226913. void setFullScreen (bool shouldBeFullScreen);
  226914. bool isFullScreen() const;
  226915. bool contains (const Point<int>& position, bool trueIfInAChildWindow) const;
  226916. const BorderSize getFrameSize() const;
  226917. bool setAlwaysOnTop (bool alwaysOnTop);
  226918. void toFront (bool makeActiveWindow);
  226919. void toBehind (ComponentPeer* other);
  226920. void setIcon (const Image& newIcon);
  226921. const StringArray getAvailableRenderingEngines() throw();
  226922. int getCurrentRenderingEngine() throw();
  226923. void setCurrentRenderingEngine (int index) throw();
  226924. /* When you use multiple DLLs which share similarly-named obj-c classes - like
  226925. for example having more than one juce plugin loaded into a host, then when a
  226926. method is called, the actual code that runs might actually be in a different module
  226927. than the one you expect... So any calls to library functions or statics that are
  226928. made inside obj-c methods will probably end up getting executed in a different DLL's
  226929. memory space. Not a great thing to happen - this obviously leads to bizarre crashes.
  226930. To work around this insanity, I'm only allowing obj-c methods to make calls to
  226931. virtual methods of an object that's known to live inside the right module's space.
  226932. */
  226933. virtual void redirectMouseDown (NSEvent* ev);
  226934. virtual void redirectMouseUp (NSEvent* ev);
  226935. virtual void redirectMouseDrag (NSEvent* ev);
  226936. virtual void redirectMouseMove (NSEvent* ev);
  226937. virtual void redirectMouseEnter (NSEvent* ev);
  226938. virtual void redirectMouseExit (NSEvent* ev);
  226939. virtual void redirectMouseWheel (NSEvent* ev);
  226940. void sendMouseEvent (NSEvent* ev);
  226941. bool handleKeyEvent (NSEvent* ev, bool isKeyDown);
  226942. virtual bool redirectKeyDown (NSEvent* ev);
  226943. virtual bool redirectKeyUp (NSEvent* ev);
  226944. virtual void redirectModKeyChange (NSEvent* ev);
  226945. #if MAC_OS_X_VERSION_MIN_REQUIRED < MAC_OS_X_VERSION_10_5
  226946. virtual bool redirectPerformKeyEquivalent (NSEvent* ev);
  226947. #endif
  226948. virtual BOOL sendDragCallback (int type, id <NSDraggingInfo> sender);
  226949. virtual bool isOpaque();
  226950. virtual void drawRect (NSRect r);
  226951. virtual bool canBecomeKeyWindow();
  226952. virtual bool windowShouldClose();
  226953. virtual void redirectMovedOrResized();
  226954. virtual void viewMovedToWindow();
  226955. virtual NSRect constrainRect (NSRect r);
  226956. static void showArrowCursorIfNeeded();
  226957. static void updateModifiers (NSEvent* e);
  226958. static void updateKeysDown (NSEvent* ev, bool isKeyDown);
  226959. static int getKeyCodeFromEvent (NSEvent* ev)
  226960. {
  226961. const String unmodified (nsStringToJuce ([ev charactersIgnoringModifiers]));
  226962. int keyCode = unmodified[0];
  226963. if (keyCode == 0x19) // (backwards-tab)
  226964. keyCode = '\t';
  226965. else if (keyCode == 0x03) // (enter)
  226966. keyCode = '\r';
  226967. return keyCode;
  226968. }
  226969. static int64 getMouseTime (NSEvent* e)
  226970. {
  226971. return (Time::currentTimeMillis() - Time::getMillisecondCounter())
  226972. + (int64) ([e timestamp] * 1000.0);
  226973. }
  226974. static const Point<int> getMousePos (NSEvent* e, NSView* view)
  226975. {
  226976. NSPoint p = [view convertPoint: [e locationInWindow] fromView: nil];
  226977. return Point<int> (roundToInt (p.x), roundToInt ([view frame].size.height - p.y));
  226978. }
  226979. static int getModifierForButtonNumber (const NSInteger num)
  226980. {
  226981. return num == 0 ? ModifierKeys::leftButtonModifier
  226982. : (num == 1 ? ModifierKeys::rightButtonModifier
  226983. : (num == 2 ? ModifierKeys::middleButtonModifier : 0));
  226984. }
  226985. virtual void viewFocusGain();
  226986. virtual void viewFocusLoss();
  226987. bool isFocused() const;
  226988. void grabFocus();
  226989. void textInputRequired (const Point<int>& position);
  226990. void repaint (int x, int y, int w, int h);
  226991. void performAnyPendingRepaintsNow();
  226992. juce_UseDebuggingNewOperator
  226993. NSWindow* window;
  226994. JuceNSView* view;
  226995. bool isSharedWindow, fullScreen, insideDrawRect, usingCoreGraphics, recursiveToFrontCall;
  226996. static ModifierKeys currentModifiers;
  226997. static ComponentPeer* currentlyFocusedPeer;
  226998. static Array<int> keysCurrentlyDown;
  226999. };
  227000. END_JUCE_NAMESPACE
  227001. @implementation JuceNSView
  227002. - (JuceNSView*) initWithOwner: (NSViewComponentPeer*) owner_
  227003. withFrame: (NSRect) frame
  227004. {
  227005. [super initWithFrame: frame];
  227006. owner = owner_;
  227007. stringBeingComposed = 0;
  227008. textWasInserted = false;
  227009. notificationCenter = [NSNotificationCenter defaultCenter];
  227010. [notificationCenter addObserver: self
  227011. selector: @selector (frameChanged:)
  227012. name: NSViewFrameDidChangeNotification
  227013. object: self];
  227014. if (! owner_->isSharedWindow)
  227015. {
  227016. [notificationCenter addObserver: self
  227017. selector: @selector (frameChanged:)
  227018. name: NSWindowDidMoveNotification
  227019. object: owner_->window];
  227020. }
  227021. [self registerForDraggedTypes: [self getSupportedDragTypes]];
  227022. return self;
  227023. }
  227024. - (void) dealloc
  227025. {
  227026. [notificationCenter removeObserver: self];
  227027. delete stringBeingComposed;
  227028. [super dealloc];
  227029. }
  227030. - (void) drawRect: (NSRect) r
  227031. {
  227032. if (owner != 0)
  227033. owner->drawRect (r);
  227034. }
  227035. - (BOOL) isOpaque
  227036. {
  227037. return owner == 0 || owner->isOpaque();
  227038. }
  227039. - (void) mouseDown: (NSEvent*) ev
  227040. {
  227041. // In some host situations, the host will stop modal loops from working
  227042. // correctly if they're called from a mouse event, so we'll trigger
  227043. // the event asynchronously..
  227044. if (JUCEApplication::getInstance() == 0)
  227045. [self performSelectorOnMainThread: @selector (asyncMouseDown:)
  227046. withObject: ev
  227047. waitUntilDone: NO];
  227048. else
  227049. [self asyncMouseDown: ev];
  227050. }
  227051. - (void) asyncMouseDown: (NSEvent*) ev
  227052. {
  227053. if (owner != 0)
  227054. owner->redirectMouseDown (ev);
  227055. }
  227056. - (void) mouseUp: (NSEvent*) ev
  227057. {
  227058. // In some host situations, the host will stop modal loops from working
  227059. // correctly if they're called from a mouse event, so we'll trigger
  227060. // the event asynchronously..
  227061. if (JUCEApplication::getInstance() == 0)
  227062. [self performSelectorOnMainThread: @selector (asyncMouseUp:)
  227063. withObject: ev
  227064. waitUntilDone: NO];
  227065. else
  227066. [self asyncMouseUp: ev];
  227067. }
  227068. - (void) asyncMouseUp: (NSEvent*) ev
  227069. {
  227070. if (owner != 0)
  227071. owner->redirectMouseUp (ev);
  227072. }
  227073. - (void) mouseDragged: (NSEvent*) ev
  227074. {
  227075. if (owner != 0)
  227076. owner->redirectMouseDrag (ev);
  227077. }
  227078. - (void) mouseMoved: (NSEvent*) ev
  227079. {
  227080. if (owner != 0)
  227081. owner->redirectMouseMove (ev);
  227082. }
  227083. - (void) mouseEntered: (NSEvent*) ev
  227084. {
  227085. if (owner != 0)
  227086. owner->redirectMouseEnter (ev);
  227087. }
  227088. - (void) mouseExited: (NSEvent*) ev
  227089. {
  227090. if (owner != 0)
  227091. owner->redirectMouseExit (ev);
  227092. }
  227093. - (void) rightMouseDown: (NSEvent*) ev
  227094. {
  227095. [self mouseDown: ev];
  227096. }
  227097. - (void) rightMouseDragged: (NSEvent*) ev
  227098. {
  227099. [self mouseDragged: ev];
  227100. }
  227101. - (void) rightMouseUp: (NSEvent*) ev
  227102. {
  227103. [self mouseUp: ev];
  227104. }
  227105. - (void) otherMouseDown: (NSEvent*) ev
  227106. {
  227107. [self mouseDown: ev];
  227108. }
  227109. - (void) otherMouseDragged: (NSEvent*) ev
  227110. {
  227111. [self mouseDragged: ev];
  227112. }
  227113. - (void) otherMouseUp: (NSEvent*) ev
  227114. {
  227115. [self mouseUp: ev];
  227116. }
  227117. - (void) scrollWheel: (NSEvent*) ev
  227118. {
  227119. if (owner != 0)
  227120. owner->redirectMouseWheel (ev);
  227121. }
  227122. - (BOOL) acceptsFirstMouse: (NSEvent*) ev
  227123. {
  227124. return YES;
  227125. }
  227126. - (void) frameChanged: (NSNotification*) n
  227127. {
  227128. if (owner != 0)
  227129. owner->redirectMovedOrResized();
  227130. }
  227131. - (void) viewDidMoveToWindow
  227132. {
  227133. if (owner != 0)
  227134. owner->viewMovedToWindow();
  227135. }
  227136. - (void) asyncRepaint: (id) rect
  227137. {
  227138. NSRect* r = (NSRect*) [((NSData*) rect) bytes];
  227139. [self setNeedsDisplayInRect: *r];
  227140. }
  227141. - (void) keyDown: (NSEvent*) ev
  227142. {
  227143. TextInputTarget* const target = owner->findCurrentTextInputTarget();
  227144. textWasInserted = false;
  227145. if (target != 0)
  227146. [self interpretKeyEvents: [NSArray arrayWithObject: ev]];
  227147. else
  227148. deleteAndZero (stringBeingComposed);
  227149. if ((! textWasInserted) && (owner == 0 || ! owner->redirectKeyDown (ev)))
  227150. [super keyDown: ev];
  227151. }
  227152. - (void) keyUp: (NSEvent*) ev
  227153. {
  227154. if (owner == 0 || ! owner->redirectKeyUp (ev))
  227155. [super keyUp: ev];
  227156. }
  227157. - (void) insertText: (id) aString
  227158. {
  227159. // This commits multi-byte text when return is pressed, or after every keypress for western keyboards
  227160. if ([aString length] > 0)
  227161. {
  227162. TextInputTarget* const target = owner->findCurrentTextInputTarget();
  227163. if (target != 0)
  227164. {
  227165. target->insertTextAtCaret (nsStringToJuce ([aString isKindOfClass: [NSAttributedString class]] ? [aString string] : aString));
  227166. textWasInserted = true;
  227167. }
  227168. }
  227169. deleteAndZero (stringBeingComposed);
  227170. }
  227171. - (void) doCommandBySelector: (SEL) aSelector
  227172. {
  227173. }
  227174. - (void) setMarkedText: (id) aString selectedRange: (NSRange) selectionRange
  227175. {
  227176. if (stringBeingComposed == 0)
  227177. stringBeingComposed = new String();
  227178. *stringBeingComposed = nsStringToJuce ([aString isKindOfClass:[NSAttributedString class]] ? [aString string] : aString);
  227179. TextInputTarget* const target = owner->findCurrentTextInputTarget();
  227180. if (target != 0)
  227181. {
  227182. const Range<int> currentHighlight (target->getHighlightedRegion());
  227183. target->insertTextAtCaret (*stringBeingComposed);
  227184. target->setHighlightedRegion (currentHighlight.withLength (stringBeingComposed->length()));
  227185. textWasInserted = true;
  227186. }
  227187. }
  227188. - (void) unmarkText
  227189. {
  227190. if (stringBeingComposed != 0)
  227191. {
  227192. TextInputTarget* const target = owner->findCurrentTextInputTarget();
  227193. if (target != 0)
  227194. {
  227195. target->insertTextAtCaret (*stringBeingComposed);
  227196. textWasInserted = true;
  227197. }
  227198. }
  227199. deleteAndZero (stringBeingComposed);
  227200. }
  227201. - (BOOL) hasMarkedText
  227202. {
  227203. return stringBeingComposed != 0;
  227204. }
  227205. - (long) conversationIdentifier
  227206. {
  227207. return (long) (pointer_sized_int) self;
  227208. }
  227209. - (NSAttributedString*) attributedSubstringFromRange: (NSRange) theRange
  227210. {
  227211. TextInputTarget* const target = owner->findCurrentTextInputTarget();
  227212. if (target != 0)
  227213. {
  227214. const Range<int> r ((int) theRange.location,
  227215. (int) (theRange.location + theRange.length));
  227216. return [[[NSAttributedString alloc] initWithString: juceStringToNS (target->getTextInRange (r))] autorelease];
  227217. }
  227218. return nil;
  227219. }
  227220. - (NSRange) markedRange
  227221. {
  227222. return stringBeingComposed != 0 ? NSMakeRange (0, stringBeingComposed->length())
  227223. : NSMakeRange (NSNotFound, 0);
  227224. }
  227225. - (NSRange) selectedRange
  227226. {
  227227. TextInputTarget* const target = owner->findCurrentTextInputTarget();
  227228. if (target != 0)
  227229. {
  227230. const Range<int> highlight (target->getHighlightedRegion());
  227231. if (! highlight.isEmpty())
  227232. return NSMakeRange (highlight.getStart(), highlight.getLength());
  227233. }
  227234. return NSMakeRange (NSNotFound, 0);
  227235. }
  227236. - (NSRect) firstRectForCharacterRange: (NSRange) theRange
  227237. {
  227238. JUCE_NAMESPACE::Component* const comp = dynamic_cast <JUCE_NAMESPACE::Component*> (owner->findCurrentTextInputTarget());
  227239. if (comp == 0)
  227240. return NSMakeRect (0, 0, 0, 0);
  227241. const Rectangle<int> bounds (comp->getScreenBounds());
  227242. return NSMakeRect (bounds.getX(),
  227243. [[[NSScreen screens] objectAtIndex: 0] frame].size.height - bounds.getY(),
  227244. bounds.getWidth(),
  227245. bounds.getHeight());
  227246. }
  227247. - (unsigned int) characterIndexForPoint: (NSPoint) thePoint
  227248. {
  227249. return NSNotFound;
  227250. }
  227251. - (NSArray*) validAttributesForMarkedText
  227252. {
  227253. return [NSArray array];
  227254. }
  227255. - (void) flagsChanged: (NSEvent*) ev
  227256. {
  227257. if (owner != 0)
  227258. owner->redirectModKeyChange (ev);
  227259. }
  227260. #if MAC_OS_X_VERSION_MIN_REQUIRED < MAC_OS_X_VERSION_10_5
  227261. - (BOOL) performKeyEquivalent: (NSEvent*) ev
  227262. {
  227263. if (owner != 0 && owner->redirectPerformKeyEquivalent (ev))
  227264. return true;
  227265. return [super performKeyEquivalent: ev];
  227266. }
  227267. #endif
  227268. - (BOOL) becomeFirstResponder
  227269. {
  227270. if (owner != 0)
  227271. owner->viewFocusGain();
  227272. return true;
  227273. }
  227274. - (BOOL) resignFirstResponder
  227275. {
  227276. if (owner != 0)
  227277. owner->viewFocusLoss();
  227278. return true;
  227279. }
  227280. - (BOOL) acceptsFirstResponder
  227281. {
  227282. return owner != 0 && owner->canBecomeKeyWindow();
  227283. }
  227284. - (NSArray*) getSupportedDragTypes
  227285. {
  227286. return [NSArray arrayWithObjects: NSFilenamesPboardType, /*NSFilesPromisePboardType, NSStringPboardType,*/ nil];
  227287. }
  227288. - (BOOL) sendDragCallback: (int) type sender: (id <NSDraggingInfo>) sender
  227289. {
  227290. return owner != 0 && owner->sendDragCallback (type, sender);
  227291. }
  227292. - (NSDragOperation) draggingEntered: (id <NSDraggingInfo>) sender
  227293. {
  227294. if ([self sendDragCallback: 0 sender: sender])
  227295. return NSDragOperationCopy | NSDragOperationMove | NSDragOperationGeneric;
  227296. else
  227297. return NSDragOperationNone;
  227298. }
  227299. - (NSDragOperation) draggingUpdated: (id <NSDraggingInfo>) sender
  227300. {
  227301. if ([self sendDragCallback: 0 sender: sender])
  227302. return NSDragOperationCopy | NSDragOperationMove | NSDragOperationGeneric;
  227303. else
  227304. return NSDragOperationNone;
  227305. }
  227306. - (void) draggingEnded: (id <NSDraggingInfo>) sender
  227307. {
  227308. [self sendDragCallback: 1 sender: sender];
  227309. }
  227310. - (void) draggingExited: (id <NSDraggingInfo>) sender
  227311. {
  227312. [self sendDragCallback: 1 sender: sender];
  227313. }
  227314. - (BOOL) prepareForDragOperation: (id <NSDraggingInfo>) sender
  227315. {
  227316. return YES;
  227317. }
  227318. - (BOOL) performDragOperation: (id <NSDraggingInfo>) sender
  227319. {
  227320. return [self sendDragCallback: 2 sender: sender];
  227321. }
  227322. - (void) concludeDragOperation: (id <NSDraggingInfo>) sender
  227323. {
  227324. }
  227325. @end
  227326. @implementation JuceNSWindow
  227327. - (void) setOwner: (NSViewComponentPeer*) owner_
  227328. {
  227329. owner = owner_;
  227330. isZooming = false;
  227331. }
  227332. - (BOOL) canBecomeKeyWindow
  227333. {
  227334. return owner != 0 && owner->canBecomeKeyWindow();
  227335. }
  227336. - (void) becomeKeyWindow
  227337. {
  227338. [super becomeKeyWindow];
  227339. if (owner != 0)
  227340. owner->grabFocus();
  227341. }
  227342. - (BOOL) windowShouldClose: (id) window
  227343. {
  227344. return owner == 0 || owner->windowShouldClose();
  227345. }
  227346. - (NSRect) constrainFrameRect: (NSRect) frameRect toScreen: (NSScreen*) screen
  227347. {
  227348. if (owner != 0)
  227349. frameRect = owner->constrainRect (frameRect);
  227350. return frameRect;
  227351. }
  227352. - (NSSize) windowWillResize: (NSWindow*) window toSize: (NSSize) proposedFrameSize
  227353. {
  227354. if (isZooming)
  227355. return proposedFrameSize;
  227356. NSRect frameRect = [self frame];
  227357. frameRect.origin.y -= proposedFrameSize.height - frameRect.size.height;
  227358. frameRect.size = proposedFrameSize;
  227359. if (owner != 0)
  227360. frameRect = owner->constrainRect (frameRect);
  227361. return frameRect.size;
  227362. }
  227363. - (void) zoom: (id) sender
  227364. {
  227365. isZooming = true;
  227366. [super zoom: sender];
  227367. isZooming = false;
  227368. }
  227369. - (void) windowWillMove: (NSNotification*) notification
  227370. {
  227371. if (JUCE_NAMESPACE::Component::getCurrentlyModalComponent() != 0
  227372. && owner->getComponent()->isCurrentlyBlockedByAnotherModalComponent()
  227373. && (owner->getStyleFlags() & JUCE_NAMESPACE::ComponentPeer::windowHasTitleBar) != 0)
  227374. JUCE_NAMESPACE::Component::getCurrentlyModalComponent()->inputAttemptWhenModal();
  227375. }
  227376. @end
  227377. BEGIN_JUCE_NAMESPACE
  227378. ModifierKeys NSViewComponentPeer::currentModifiers;
  227379. ComponentPeer* NSViewComponentPeer::currentlyFocusedPeer = 0;
  227380. Array<int> NSViewComponentPeer::keysCurrentlyDown;
  227381. bool KeyPress::isKeyCurrentlyDown (const int keyCode)
  227382. {
  227383. if (NSViewComponentPeer::keysCurrentlyDown.contains (keyCode))
  227384. return true;
  227385. if (keyCode >= 'A' && keyCode <= 'Z'
  227386. && NSViewComponentPeer::keysCurrentlyDown.contains ((int) CharacterFunctions::toLowerCase ((juce_wchar) keyCode)))
  227387. return true;
  227388. if (keyCode >= 'a' && keyCode <= 'z'
  227389. && NSViewComponentPeer::keysCurrentlyDown.contains ((int) CharacterFunctions::toUpperCase ((juce_wchar) keyCode)))
  227390. return true;
  227391. return false;
  227392. }
  227393. void NSViewComponentPeer::updateModifiers (NSEvent* e)
  227394. {
  227395. int m = 0;
  227396. if (([e modifierFlags] & NSShiftKeyMask) != 0) m |= ModifierKeys::shiftModifier;
  227397. if (([e modifierFlags] & NSControlKeyMask) != 0) m |= ModifierKeys::ctrlModifier;
  227398. if (([e modifierFlags] & NSAlternateKeyMask) != 0) m |= ModifierKeys::altModifier;
  227399. if (([e modifierFlags] & NSCommandKeyMask) != 0) m |= ModifierKeys::commandModifier;
  227400. currentModifiers = currentModifiers.withOnlyMouseButtons().withFlags (m);
  227401. }
  227402. void NSViewComponentPeer::updateKeysDown (NSEvent* ev, bool isKeyDown)
  227403. {
  227404. updateModifiers (ev);
  227405. int keyCode = getKeyCodeFromEvent (ev);
  227406. if (keyCode != 0)
  227407. {
  227408. if (isKeyDown)
  227409. keysCurrentlyDown.addIfNotAlreadyThere (keyCode);
  227410. else
  227411. keysCurrentlyDown.removeValue (keyCode);
  227412. }
  227413. }
  227414. const ModifierKeys ModifierKeys::getCurrentModifiersRealtime() throw()
  227415. {
  227416. return NSViewComponentPeer::currentModifiers;
  227417. }
  227418. void ModifierKeys::updateCurrentModifiers() throw()
  227419. {
  227420. currentModifiers = NSViewComponentPeer::currentModifiers;
  227421. }
  227422. NSViewComponentPeer::NSViewComponentPeer (Component* const component_,
  227423. const int windowStyleFlags,
  227424. NSView* viewToAttachTo)
  227425. : ComponentPeer (component_, windowStyleFlags),
  227426. window (0),
  227427. view (0),
  227428. isSharedWindow (viewToAttachTo != 0),
  227429. fullScreen (false),
  227430. insideDrawRect (false),
  227431. #if USE_COREGRAPHICS_RENDERING
  227432. usingCoreGraphics (true),
  227433. #else
  227434. usingCoreGraphics (false),
  227435. #endif
  227436. recursiveToFrontCall (false)
  227437. {
  227438. NSRect r;
  227439. r.origin.x = 0;
  227440. r.origin.y = 0;
  227441. r.size.width = (float) component->getWidth();
  227442. r.size.height = (float) component->getHeight();
  227443. view = [[JuceNSView alloc] initWithOwner: this withFrame: r];
  227444. [view setPostsFrameChangedNotifications: YES];
  227445. if (isSharedWindow)
  227446. {
  227447. window = [viewToAttachTo window];
  227448. [viewToAttachTo addSubview: view];
  227449. setVisible (component->isVisible());
  227450. }
  227451. else
  227452. {
  227453. r.origin.x = (float) component->getX();
  227454. r.origin.y = (float) component->getY();
  227455. r.origin.y = [[[NSScreen screens] objectAtIndex: 0] frame].size.height - (r.origin.y + r.size.height);
  227456. unsigned int style = 0;
  227457. if ((windowStyleFlags & windowHasTitleBar) == 0)
  227458. style = NSBorderlessWindowMask;
  227459. else
  227460. style = NSTitledWindowMask;
  227461. if ((windowStyleFlags & windowHasMinimiseButton) != 0)
  227462. style |= NSMiniaturizableWindowMask;
  227463. if ((windowStyleFlags & windowHasCloseButton) != 0)
  227464. style |= NSClosableWindowMask;
  227465. if ((windowStyleFlags & windowIsResizable) != 0)
  227466. style |= NSResizableWindowMask;
  227467. window = [[JuceNSWindow alloc] initWithContentRect: r
  227468. styleMask: style
  227469. backing: NSBackingStoreBuffered
  227470. defer: YES];
  227471. [((JuceNSWindow*) window) setOwner: this];
  227472. [window orderOut: nil];
  227473. [window setDelegate: (JuceNSWindow*) window];
  227474. [window setOpaque: component->isOpaque()];
  227475. [window setHasShadow: ((windowStyleFlags & windowHasDropShadow) != 0)];
  227476. if (component->isAlwaysOnTop())
  227477. [window setLevel: NSFloatingWindowLevel];
  227478. [window setContentView: view];
  227479. [window setAutodisplay: YES];
  227480. [window setAcceptsMouseMovedEvents: YES];
  227481. // We'll both retain and also release this on closing because plugin hosts can unexpectedly
  227482. // close the window for us, and also tend to get cause trouble if setReleasedWhenClosed is NO.
  227483. [window setReleasedWhenClosed: YES];
  227484. [window retain];
  227485. [window setExcludedFromWindowsMenu: (windowStyleFlags & windowIsTemporary) != 0];
  227486. [window setIgnoresMouseEvents: (windowStyleFlags & windowIgnoresMouseClicks) != 0];
  227487. }
  227488. setTitle (component->getName());
  227489. }
  227490. NSViewComponentPeer::~NSViewComponentPeer()
  227491. {
  227492. view->owner = 0;
  227493. [view removeFromSuperview];
  227494. [view release];
  227495. if (! isSharedWindow)
  227496. {
  227497. [((JuceNSWindow*) window) setOwner: 0];
  227498. [window close];
  227499. [window release];
  227500. }
  227501. }
  227502. void* NSViewComponentPeer::getNativeHandle() const
  227503. {
  227504. return view;
  227505. }
  227506. void NSViewComponentPeer::setVisible (bool shouldBeVisible)
  227507. {
  227508. if (isSharedWindow)
  227509. {
  227510. [view setHidden: ! shouldBeVisible];
  227511. }
  227512. else
  227513. {
  227514. if (shouldBeVisible)
  227515. {
  227516. [window orderFront: nil];
  227517. handleBroughtToFront();
  227518. }
  227519. else
  227520. {
  227521. [window orderOut: nil];
  227522. }
  227523. }
  227524. }
  227525. void NSViewComponentPeer::setTitle (const String& title)
  227526. {
  227527. const ScopedAutoReleasePool pool;
  227528. if (! isSharedWindow)
  227529. [window setTitle: juceStringToNS (title)];
  227530. }
  227531. void NSViewComponentPeer::setPosition (int x, int y)
  227532. {
  227533. setBounds (x, y, component->getWidth(), component->getHeight(), false);
  227534. }
  227535. void NSViewComponentPeer::setSize (int w, int h)
  227536. {
  227537. setBounds (component->getX(), component->getY(), w, h, false);
  227538. }
  227539. void NSViewComponentPeer::setBounds (int x, int y, int w, int h, bool isNowFullScreen)
  227540. {
  227541. fullScreen = isNowFullScreen;
  227542. w = jmax (0, w);
  227543. h = jmax (0, h);
  227544. NSRect r;
  227545. r.origin.x = (float) x;
  227546. r.origin.y = (float) y;
  227547. r.size.width = (float) w;
  227548. r.size.height = (float) h;
  227549. if (isSharedWindow)
  227550. {
  227551. r.origin.y = [[view superview] frame].size.height - (r.origin.y + r.size.height);
  227552. if ([view frame].size.width != r.size.width
  227553. || [view frame].size.height != r.size.height)
  227554. [view setNeedsDisplay: true];
  227555. [view setFrame: r];
  227556. }
  227557. else
  227558. {
  227559. r.origin.y = [[[NSScreen screens] objectAtIndex: 0] frame].size.height - (r.origin.y + r.size.height);
  227560. [window setFrame: [window frameRectForContentRect: r]
  227561. display: true];
  227562. }
  227563. }
  227564. const Rectangle<int> NSViewComponentPeer::getBounds (const bool global) const
  227565. {
  227566. NSRect r = [view frame];
  227567. if (global && [view window] != 0)
  227568. {
  227569. r = [view convertRect: r toView: nil];
  227570. NSRect wr = [[view window] frame];
  227571. r.origin.x += wr.origin.x;
  227572. r.origin.y += wr.origin.y;
  227573. r.origin.y = [[[NSScreen screens] objectAtIndex: 0] frame].size.height - r.origin.y - r.size.height;
  227574. }
  227575. else
  227576. {
  227577. r.origin.y = [[view superview] frame].size.height - r.origin.y - r.size.height;
  227578. }
  227579. return Rectangle<int> ((int) r.origin.x, (int) r.origin.y, (int) r.size.width, (int) r.size.height);
  227580. }
  227581. const Rectangle<int> NSViewComponentPeer::getBounds() const
  227582. {
  227583. return getBounds (! isSharedWindow);
  227584. }
  227585. const Point<int> NSViewComponentPeer::getScreenPosition() const
  227586. {
  227587. return getBounds (true).getPosition();
  227588. }
  227589. const Point<int> NSViewComponentPeer::relativePositionToGlobal (const Point<int>& relativePosition)
  227590. {
  227591. return relativePosition + getScreenPosition();
  227592. }
  227593. const Point<int> NSViewComponentPeer::globalPositionToRelative (const Point<int>& screenPosition)
  227594. {
  227595. return screenPosition - getScreenPosition();
  227596. }
  227597. NSRect NSViewComponentPeer::constrainRect (NSRect r)
  227598. {
  227599. if (constrainer != 0)
  227600. {
  227601. NSRect current = [window frame];
  227602. current.origin.y = [[[NSScreen screens] objectAtIndex: 0] frame].size.height - current.origin.y - current.size.height;
  227603. r.origin.y = [[[NSScreen screens] objectAtIndex: 0] frame].size.height - r.origin.y - r.size.height;
  227604. Rectangle<int> pos ((int) r.origin.x, (int) r.origin.y,
  227605. (int) r.size.width, (int) r.size.height);
  227606. Rectangle<int> original ((int) current.origin.x, (int) current.origin.y,
  227607. (int) current.size.width, (int) current.size.height);
  227608. constrainer->checkBounds (pos, original,
  227609. Desktop::getInstance().getAllMonitorDisplayAreas().getBounds(),
  227610. pos.getY() != original.getY() && pos.getBottom() == original.getBottom(),
  227611. pos.getX() != original.getX() && pos.getRight() == original.getRight(),
  227612. pos.getY() == original.getY() && pos.getBottom() != original.getBottom(),
  227613. pos.getX() == original.getX() && pos.getRight() != original.getRight());
  227614. r.origin.x = pos.getX();
  227615. r.origin.y = [[[NSScreen screens] objectAtIndex: 0] frame].size.height - r.size.height - pos.getY();
  227616. r.size.width = pos.getWidth();
  227617. r.size.height = pos.getHeight();
  227618. }
  227619. return r;
  227620. }
  227621. void NSViewComponentPeer::setMinimised (bool shouldBeMinimised)
  227622. {
  227623. if (! isSharedWindow)
  227624. {
  227625. if (shouldBeMinimised)
  227626. [window miniaturize: nil];
  227627. else
  227628. [window deminiaturize: nil];
  227629. }
  227630. }
  227631. bool NSViewComponentPeer::isMinimised() const
  227632. {
  227633. return window != 0 && [window isMiniaturized];
  227634. }
  227635. void NSViewComponentPeer::setFullScreen (bool shouldBeFullScreen)
  227636. {
  227637. if (! isSharedWindow)
  227638. {
  227639. Rectangle<int> r (lastNonFullscreenBounds);
  227640. setMinimised (false);
  227641. if (fullScreen != shouldBeFullScreen)
  227642. {
  227643. if (shouldBeFullScreen && (getStyleFlags() & windowHasTitleBar) != 0)
  227644. {
  227645. fullScreen = true;
  227646. [window performZoom: nil];
  227647. }
  227648. else
  227649. {
  227650. if (shouldBeFullScreen)
  227651. r = Desktop::getInstance().getMainMonitorArea();
  227652. // (can't call the component's setBounds method because that'll reset our fullscreen flag)
  227653. if (r != getComponent()->getBounds() && ! r.isEmpty())
  227654. setBounds (r.getX(), r.getY(), r.getWidth(), r.getHeight(), shouldBeFullScreen);
  227655. }
  227656. }
  227657. }
  227658. }
  227659. bool NSViewComponentPeer::isFullScreen() const
  227660. {
  227661. return fullScreen;
  227662. }
  227663. bool NSViewComponentPeer::contains (const Point<int>& position, bool trueIfInAChildWindow) const
  227664. {
  227665. if (((unsigned int) position.getX()) >= (unsigned int) component->getWidth()
  227666. || ((unsigned int) position.getY()) >= (unsigned int) component->getHeight())
  227667. return false;
  227668. NSPoint p;
  227669. p.x = (float) position.getX();
  227670. p.y = (float) position.getY();
  227671. NSView* v = [view hitTest: p];
  227672. if (trueIfInAChildWindow)
  227673. return v != nil;
  227674. return v == view;
  227675. }
  227676. const BorderSize NSViewComponentPeer::getFrameSize() const
  227677. {
  227678. BorderSize b;
  227679. if (! isSharedWindow)
  227680. {
  227681. NSRect v = [view convertRect: [view frame] toView: nil];
  227682. NSRect w = [window frame];
  227683. b.setTop ((int) (w.size.height - (v.origin.y + v.size.height)));
  227684. b.setBottom ((int) v.origin.y);
  227685. b.setLeft ((int) v.origin.x);
  227686. b.setRight ((int) (w.size.width - (v.origin.x + v.size.width)));
  227687. }
  227688. return b;
  227689. }
  227690. bool NSViewComponentPeer::setAlwaysOnTop (bool alwaysOnTop)
  227691. {
  227692. if (! isSharedWindow)
  227693. {
  227694. [window setLevel: alwaysOnTop ? NSFloatingWindowLevel
  227695. : NSNormalWindowLevel];
  227696. }
  227697. return true;
  227698. }
  227699. void NSViewComponentPeer::toFront (bool makeActiveWindow)
  227700. {
  227701. if (isSharedWindow)
  227702. {
  227703. [[view superview] addSubview: view
  227704. positioned: NSWindowAbove
  227705. relativeTo: nil];
  227706. }
  227707. if (window != 0 && component->isVisible())
  227708. {
  227709. if (makeActiveWindow)
  227710. [window makeKeyAndOrderFront: nil];
  227711. else
  227712. [window orderFront: nil];
  227713. if (! recursiveToFrontCall)
  227714. {
  227715. recursiveToFrontCall = true;
  227716. Desktop::getInstance().getMainMouseSource().forceMouseCursorUpdate();
  227717. handleBroughtToFront();
  227718. recursiveToFrontCall = false;
  227719. }
  227720. }
  227721. }
  227722. void NSViewComponentPeer::toBehind (ComponentPeer* other)
  227723. {
  227724. NSViewComponentPeer* const otherPeer = dynamic_cast <NSViewComponentPeer*> (other);
  227725. jassert (otherPeer != 0); // wrong type of window?
  227726. if (otherPeer != 0)
  227727. {
  227728. if (isSharedWindow)
  227729. {
  227730. [[view superview] addSubview: view
  227731. positioned: NSWindowBelow
  227732. relativeTo: otherPeer->view];
  227733. }
  227734. else
  227735. {
  227736. [window orderWindow: NSWindowBelow
  227737. relativeTo: otherPeer->window != 0 ? [otherPeer->window windowNumber]
  227738. : nil ];
  227739. }
  227740. }
  227741. }
  227742. void NSViewComponentPeer::setIcon (const Image& /*newIcon*/)
  227743. {
  227744. // to do..
  227745. }
  227746. void NSViewComponentPeer::viewFocusGain()
  227747. {
  227748. if (currentlyFocusedPeer != this)
  227749. {
  227750. if (ComponentPeer::isValidPeer (currentlyFocusedPeer))
  227751. currentlyFocusedPeer->handleFocusLoss();
  227752. currentlyFocusedPeer = this;
  227753. handleFocusGain();
  227754. }
  227755. }
  227756. void NSViewComponentPeer::viewFocusLoss()
  227757. {
  227758. if (currentlyFocusedPeer == this)
  227759. {
  227760. currentlyFocusedPeer = 0;
  227761. handleFocusLoss();
  227762. }
  227763. }
  227764. void juce_HandleProcessFocusChange()
  227765. {
  227766. NSViewComponentPeer::keysCurrentlyDown.clear();
  227767. if (NSViewComponentPeer::isValidPeer (NSViewComponentPeer::currentlyFocusedPeer))
  227768. {
  227769. if (Process::isForegroundProcess())
  227770. {
  227771. NSViewComponentPeer::currentlyFocusedPeer->handleFocusGain();
  227772. ComponentPeer::bringModalComponentToFront();
  227773. }
  227774. else
  227775. {
  227776. NSViewComponentPeer::currentlyFocusedPeer->handleFocusLoss();
  227777. // turn kiosk mode off if we lose focus..
  227778. Desktop::getInstance().setKioskModeComponent (0);
  227779. }
  227780. }
  227781. }
  227782. bool NSViewComponentPeer::isFocused() const
  227783. {
  227784. return isSharedWindow ? this == currentlyFocusedPeer
  227785. : (window != 0 && [window isKeyWindow]);
  227786. }
  227787. void NSViewComponentPeer::grabFocus()
  227788. {
  227789. if (window != 0)
  227790. {
  227791. [window makeKeyWindow];
  227792. [window makeFirstResponder: view];
  227793. viewFocusGain();
  227794. }
  227795. }
  227796. void NSViewComponentPeer::textInputRequired (const Point<int>&)
  227797. {
  227798. }
  227799. bool NSViewComponentPeer::handleKeyEvent (NSEvent* ev, bool isKeyDown)
  227800. {
  227801. String unicode (nsStringToJuce ([ev characters]));
  227802. String unmodified (nsStringToJuce ([ev charactersIgnoringModifiers]));
  227803. int keyCode = getKeyCodeFromEvent (ev);
  227804. //DBG ("unicode: " + unicode + " " + String::toHexString ((int) unicode[0]));
  227805. //DBG ("unmodified: " + unmodified + " " + String::toHexString ((int) unmodified[0]));
  227806. if (unicode.isNotEmpty() || keyCode != 0)
  227807. {
  227808. if (isKeyDown)
  227809. {
  227810. bool used = false;
  227811. while (unicode.length() > 0)
  227812. {
  227813. juce_wchar textCharacter = unicode[0];
  227814. unicode = unicode.substring (1);
  227815. if (([ev modifierFlags] & NSCommandKeyMask) != 0)
  227816. textCharacter = 0;
  227817. used = handleKeyUpOrDown (true) || used;
  227818. used = handleKeyPress (keyCode, textCharacter) || used;
  227819. }
  227820. return used;
  227821. }
  227822. else
  227823. {
  227824. if (handleKeyUpOrDown (false))
  227825. return true;
  227826. }
  227827. }
  227828. return false;
  227829. }
  227830. bool NSViewComponentPeer::redirectKeyDown (NSEvent* ev)
  227831. {
  227832. updateKeysDown (ev, true);
  227833. bool used = handleKeyEvent (ev, true);
  227834. if (([ev modifierFlags] & NSCommandKeyMask) != 0)
  227835. {
  227836. // for command keys, the key-up event is thrown away, so simulate one..
  227837. updateKeysDown (ev, false);
  227838. used = (isValidPeer (this) && handleKeyEvent (ev, false)) || used;
  227839. }
  227840. // (If we're running modally, don't allow unused keystrokes to be passed
  227841. // along to other blocked views..)
  227842. if (Component::getCurrentlyModalComponent() != 0)
  227843. used = true;
  227844. return used;
  227845. }
  227846. bool NSViewComponentPeer::redirectKeyUp (NSEvent* ev)
  227847. {
  227848. updateKeysDown (ev, false);
  227849. return handleKeyEvent (ev, false)
  227850. || Component::getCurrentlyModalComponent() != 0;
  227851. }
  227852. void NSViewComponentPeer::redirectModKeyChange (NSEvent* ev)
  227853. {
  227854. keysCurrentlyDown.clear();
  227855. handleKeyUpOrDown (true);
  227856. updateModifiers (ev);
  227857. handleModifierKeysChange();
  227858. }
  227859. #if MAC_OS_X_VERSION_MIN_REQUIRED < MAC_OS_X_VERSION_10_5
  227860. bool NSViewComponentPeer::redirectPerformKeyEquivalent (NSEvent* ev)
  227861. {
  227862. if ([ev type] == NSKeyDown)
  227863. return redirectKeyDown (ev);
  227864. else if ([ev type] == NSKeyUp)
  227865. return redirectKeyUp (ev);
  227866. return false;
  227867. }
  227868. #endif
  227869. void NSViewComponentPeer::sendMouseEvent (NSEvent* ev)
  227870. {
  227871. updateModifiers (ev);
  227872. handleMouseEvent (0, getMousePos (ev, view), currentModifiers, getMouseTime (ev));
  227873. }
  227874. void NSViewComponentPeer::redirectMouseDown (NSEvent* ev)
  227875. {
  227876. currentModifiers = currentModifiers.withFlags (getModifierForButtonNumber ([ev buttonNumber]));
  227877. sendMouseEvent (ev);
  227878. }
  227879. void NSViewComponentPeer::redirectMouseUp (NSEvent* ev)
  227880. {
  227881. currentModifiers = currentModifiers.withoutFlags (getModifierForButtonNumber ([ev buttonNumber]));
  227882. sendMouseEvent (ev);
  227883. showArrowCursorIfNeeded();
  227884. }
  227885. void NSViewComponentPeer::redirectMouseDrag (NSEvent* ev)
  227886. {
  227887. currentModifiers = currentModifiers.withFlags (getModifierForButtonNumber ([ev buttonNumber]));
  227888. sendMouseEvent (ev);
  227889. }
  227890. void NSViewComponentPeer::redirectMouseMove (NSEvent* ev)
  227891. {
  227892. currentModifiers = currentModifiers.withoutMouseButtons();
  227893. sendMouseEvent (ev);
  227894. showArrowCursorIfNeeded();
  227895. }
  227896. void NSViewComponentPeer::redirectMouseEnter (NSEvent* ev)
  227897. {
  227898. Desktop::getInstance().getMainMouseSource().forceMouseCursorUpdate();
  227899. currentModifiers = currentModifiers.withoutMouseButtons();
  227900. sendMouseEvent (ev);
  227901. }
  227902. void NSViewComponentPeer::redirectMouseExit (NSEvent* ev)
  227903. {
  227904. currentModifiers = currentModifiers.withoutMouseButtons();
  227905. sendMouseEvent (ev);
  227906. }
  227907. void NSViewComponentPeer::redirectMouseWheel (NSEvent* ev)
  227908. {
  227909. updateModifiers (ev);
  227910. handleMouseWheel (0, getMousePos (ev, view), getMouseTime (ev),
  227911. [ev deltaX] * 10.0f, [ev deltaY] * 10.0f);
  227912. }
  227913. void NSViewComponentPeer::showArrowCursorIfNeeded()
  227914. {
  227915. MouseInputSource& mouse = Desktop::getInstance().getMainMouseSource();
  227916. if (mouse.getComponentUnderMouse() == 0
  227917. && Desktop::getInstance().findComponentAt (mouse.getScreenPosition()) == 0)
  227918. {
  227919. [[NSCursor arrowCursor] set];
  227920. }
  227921. }
  227922. BOOL NSViewComponentPeer::sendDragCallback (int type, id <NSDraggingInfo> sender)
  227923. {
  227924. NSString* bestType
  227925. = [[sender draggingPasteboard] availableTypeFromArray: [view getSupportedDragTypes]];
  227926. if (bestType == nil)
  227927. return false;
  227928. NSPoint p = [view convertPoint: [sender draggingLocation] fromView: nil];
  227929. const Point<int> pos ((int) p.x, (int) ([view frame].size.height - p.y));
  227930. StringArray files;
  227931. id list = [[sender draggingPasteboard] propertyListForType: bestType];
  227932. if (list == nil)
  227933. return false;
  227934. if ([list isKindOfClass: [NSArray class]])
  227935. {
  227936. NSArray* items = (NSArray*) list;
  227937. for (unsigned int i = 0; i < [items count]; ++i)
  227938. files.add (nsStringToJuce ((NSString*) [items objectAtIndex: i]));
  227939. }
  227940. if (files.size() == 0)
  227941. return false;
  227942. if (type == 0)
  227943. handleFileDragMove (files, pos);
  227944. else if (type == 1)
  227945. handleFileDragExit (files);
  227946. else if (type == 2)
  227947. handleFileDragDrop (files, pos);
  227948. return true;
  227949. }
  227950. bool NSViewComponentPeer::isOpaque()
  227951. {
  227952. return component == 0 || component->isOpaque();
  227953. }
  227954. void NSViewComponentPeer::drawRect (NSRect r)
  227955. {
  227956. if (r.size.width < 1.0f || r.size.height < 1.0f)
  227957. return;
  227958. CGContextRef cg = (CGContextRef) [[NSGraphicsContext currentContext] graphicsPort];
  227959. if (! component->isOpaque())
  227960. CGContextClearRect (cg, CGContextGetClipBoundingBox (cg));
  227961. #if USE_COREGRAPHICS_RENDERING
  227962. if (usingCoreGraphics)
  227963. {
  227964. CoreGraphicsContext context (cg, (float) [view frame].size.height);
  227965. insideDrawRect = true;
  227966. handlePaint (context);
  227967. insideDrawRect = false;
  227968. }
  227969. else
  227970. #endif
  227971. {
  227972. Image temp (getComponent()->isOpaque() ? Image::RGB : Image::ARGB,
  227973. (int) (r.size.width + 0.5f),
  227974. (int) (r.size.height + 0.5f),
  227975. ! getComponent()->isOpaque());
  227976. LowLevelGraphicsSoftwareRenderer context (temp);
  227977. context.setOrigin (-roundToInt (r.origin.x),
  227978. -roundToInt ([view frame].size.height - (r.origin.y + r.size.height)));
  227979. const NSRect* rects = 0;
  227980. NSInteger numRects = 0;
  227981. [view getRectsBeingDrawn: &rects count: &numRects];
  227982. RectangleList clip;
  227983. for (int i = 0; i < numRects; ++i)
  227984. {
  227985. clip.addWithoutMerging (Rectangle<int> (roundToInt (rects[i].origin.x),
  227986. roundToInt ([view frame].size.height - (rects[i].origin.y + rects[i].size.height)),
  227987. roundToInt (rects[i].size.width),
  227988. roundToInt (rects[i].size.height)));
  227989. }
  227990. if (context.clipToRectangleList (clip))
  227991. {
  227992. insideDrawRect = true;
  227993. handlePaint (context);
  227994. insideDrawRect = false;
  227995. CGColorSpaceRef colourSpace = CGColorSpaceCreateDeviceRGB();
  227996. CGImageRef image = CoreGraphicsImage::createImage (temp, false, colourSpace);
  227997. CGColorSpaceRelease (colourSpace);
  227998. CGContextDrawImage (cg, CGRectMake (r.origin.x, r.origin.y, temp.getWidth(), temp.getHeight()), image);
  227999. CGImageRelease (image);
  228000. }
  228001. }
  228002. }
  228003. const StringArray NSViewComponentPeer::getAvailableRenderingEngines() throw()
  228004. {
  228005. StringArray s;
  228006. s.add ("Software Renderer");
  228007. #if USE_COREGRAPHICS_RENDERING
  228008. s.add ("CoreGraphics Renderer");
  228009. #endif
  228010. return s;
  228011. }
  228012. int NSViewComponentPeer::getCurrentRenderingEngine() throw()
  228013. {
  228014. return usingCoreGraphics ? 1 : 0;
  228015. }
  228016. void NSViewComponentPeer::setCurrentRenderingEngine (int index) throw()
  228017. {
  228018. #if USE_COREGRAPHICS_RENDERING
  228019. if (usingCoreGraphics != (index > 0))
  228020. {
  228021. usingCoreGraphics = index > 0;
  228022. [view setNeedsDisplay: true];
  228023. }
  228024. #endif
  228025. }
  228026. bool NSViewComponentPeer::canBecomeKeyWindow()
  228027. {
  228028. return (getStyleFlags() & JUCE_NAMESPACE::ComponentPeer::windowIgnoresKeyPresses) == 0;
  228029. }
  228030. bool NSViewComponentPeer::windowShouldClose()
  228031. {
  228032. if (! isValidPeer (this))
  228033. return YES;
  228034. handleUserClosingWindow();
  228035. return NO;
  228036. }
  228037. void NSViewComponentPeer::redirectMovedOrResized()
  228038. {
  228039. handleMovedOrResized();
  228040. }
  228041. void NSViewComponentPeer::viewMovedToWindow()
  228042. {
  228043. if (isSharedWindow)
  228044. window = [view window];
  228045. }
  228046. void Desktop::createMouseInputSources()
  228047. {
  228048. mouseSources.add (new MouseInputSource (0, true));
  228049. }
  228050. void juce_setKioskComponent (Component* kioskModeComponent, bool enableOrDisable, bool allowMenusAndBars)
  228051. {
  228052. // Very annoyingly, this function has to use the old SetSystemUIMode function,
  228053. // which is in Carbon.framework. But, because there's no Cocoa equivalent, it
  228054. // is apparently still available in 64-bit apps..
  228055. if (enableOrDisable)
  228056. {
  228057. SetSystemUIMode (kUIModeAllSuppressed, allowMenusAndBars ? kUIOptionAutoShowMenuBar : 0);
  228058. kioskModeComponent->setBounds (Desktop::getInstance().getMainMonitorArea (false));
  228059. }
  228060. else
  228061. {
  228062. SetSystemUIMode (kUIModeNormal, 0);
  228063. }
  228064. }
  228065. class AsyncRepaintMessage : public CallbackMessage
  228066. {
  228067. public:
  228068. NSViewComponentPeer* const peer;
  228069. const Rectangle<int> rect;
  228070. AsyncRepaintMessage (NSViewComponentPeer* const peer_, const Rectangle<int>& rect_)
  228071. : peer (peer_), rect (rect_)
  228072. {
  228073. }
  228074. void messageCallback()
  228075. {
  228076. if (ComponentPeer::isValidPeer (peer))
  228077. peer->repaint (rect.getX(), rect.getY(), rect.getWidth(), rect.getHeight());
  228078. }
  228079. };
  228080. void NSViewComponentPeer::repaint (int x, int y, int w, int h)
  228081. {
  228082. if (insideDrawRect)
  228083. {
  228084. (new AsyncRepaintMessage (this, Rectangle<int> (x, y, w, h)))->post();
  228085. }
  228086. else
  228087. {
  228088. [view setNeedsDisplayInRect: NSMakeRect ((float) x, (float) ([view frame].size.height - (y + h)),
  228089. (float) w, (float) h)];
  228090. }
  228091. }
  228092. void NSViewComponentPeer::performAnyPendingRepaintsNow()
  228093. {
  228094. [view displayIfNeeded];
  228095. }
  228096. ComponentPeer* Component::createNewPeer (int styleFlags, void* windowToAttachTo)
  228097. {
  228098. return new NSViewComponentPeer (this, styleFlags, (NSView*) windowToAttachTo);
  228099. }
  228100. Image* juce_createIconForFile (const File& file)
  228101. {
  228102. const ScopedAutoReleasePool pool;
  228103. NSImage* image = [[NSWorkspace sharedWorkspace] iconForFile: juceStringToNS (file.getFullPathName())];
  228104. CoreGraphicsImage* result = new CoreGraphicsImage (Image::ARGB, (int) [image size].width, (int) [image size].height, true);
  228105. [NSGraphicsContext saveGraphicsState];
  228106. [NSGraphicsContext setCurrentContext: [NSGraphicsContext graphicsContextWithGraphicsPort: result->context flipped: false]];
  228107. [image drawAtPoint: NSMakePoint (0, 0)
  228108. fromRect: NSMakeRect (0, 0, [image size].width, [image size].height)
  228109. operation: NSCompositeSourceOver fraction: 1.0f];
  228110. [[NSGraphicsContext currentContext] flushGraphics];
  228111. [NSGraphicsContext restoreGraphicsState];
  228112. return result;
  228113. }
  228114. const int KeyPress::spaceKey = ' ';
  228115. const int KeyPress::returnKey = 0x0d;
  228116. const int KeyPress::escapeKey = 0x1b;
  228117. const int KeyPress::backspaceKey = 0x7f;
  228118. const int KeyPress::leftKey = NSLeftArrowFunctionKey;
  228119. const int KeyPress::rightKey = NSRightArrowFunctionKey;
  228120. const int KeyPress::upKey = NSUpArrowFunctionKey;
  228121. const int KeyPress::downKey = NSDownArrowFunctionKey;
  228122. const int KeyPress::pageUpKey = NSPageUpFunctionKey;
  228123. const int KeyPress::pageDownKey = NSPageDownFunctionKey;
  228124. const int KeyPress::endKey = NSEndFunctionKey;
  228125. const int KeyPress::homeKey = NSHomeFunctionKey;
  228126. const int KeyPress::deleteKey = NSDeleteFunctionKey;
  228127. const int KeyPress::insertKey = -1;
  228128. const int KeyPress::tabKey = 9;
  228129. const int KeyPress::F1Key = NSF1FunctionKey;
  228130. const int KeyPress::F2Key = NSF2FunctionKey;
  228131. const int KeyPress::F3Key = NSF3FunctionKey;
  228132. const int KeyPress::F4Key = NSF4FunctionKey;
  228133. const int KeyPress::F5Key = NSF5FunctionKey;
  228134. const int KeyPress::F6Key = NSF6FunctionKey;
  228135. const int KeyPress::F7Key = NSF7FunctionKey;
  228136. const int KeyPress::F8Key = NSF8FunctionKey;
  228137. const int KeyPress::F9Key = NSF9FunctionKey;
  228138. const int KeyPress::F10Key = NSF10FunctionKey;
  228139. const int KeyPress::F11Key = NSF1FunctionKey;
  228140. const int KeyPress::F12Key = NSF12FunctionKey;
  228141. const int KeyPress::F13Key = NSF13FunctionKey;
  228142. const int KeyPress::F14Key = NSF14FunctionKey;
  228143. const int KeyPress::F15Key = NSF15FunctionKey;
  228144. const int KeyPress::F16Key = NSF16FunctionKey;
  228145. const int KeyPress::numberPad0 = 0x30020;
  228146. const int KeyPress::numberPad1 = 0x30021;
  228147. const int KeyPress::numberPad2 = 0x30022;
  228148. const int KeyPress::numberPad3 = 0x30023;
  228149. const int KeyPress::numberPad4 = 0x30024;
  228150. const int KeyPress::numberPad5 = 0x30025;
  228151. const int KeyPress::numberPad6 = 0x30026;
  228152. const int KeyPress::numberPad7 = 0x30027;
  228153. const int KeyPress::numberPad8 = 0x30028;
  228154. const int KeyPress::numberPad9 = 0x30029;
  228155. const int KeyPress::numberPadAdd = 0x3002a;
  228156. const int KeyPress::numberPadSubtract = 0x3002b;
  228157. const int KeyPress::numberPadMultiply = 0x3002c;
  228158. const int KeyPress::numberPadDivide = 0x3002d;
  228159. const int KeyPress::numberPadSeparator = 0x3002e;
  228160. const int KeyPress::numberPadDecimalPoint = 0x3002f;
  228161. const int KeyPress::numberPadEquals = 0x30030;
  228162. const int KeyPress::numberPadDelete = 0x30031;
  228163. const int KeyPress::playKey = 0x30000;
  228164. const int KeyPress::stopKey = 0x30001;
  228165. const int KeyPress::fastForwardKey = 0x30002;
  228166. const int KeyPress::rewindKey = 0x30003;
  228167. #endif
  228168. /*** End of inlined file: juce_mac_NSViewComponentPeer.mm ***/
  228169. /*** Start of inlined file: juce_mac_MouseCursor.mm ***/
  228170. // (This file gets included by juce_mac_NativeCode.mm, rather than being
  228171. // compiled on its own).
  228172. #if JUCE_INCLUDED_FILE
  228173. #if JUCE_MAC
  228174. namespace MouseCursorHelpers
  228175. {
  228176. static void* createFromImage (const Image& image, float hotspotX, float hotspotY)
  228177. {
  228178. NSImage* im = CoreGraphicsImage::createNSImage (image);
  228179. NSCursor* c = [[NSCursor alloc] initWithImage: im
  228180. hotSpot: NSMakePoint (hotspotX, hotspotY)];
  228181. [im release];
  228182. return c;
  228183. }
  228184. static void* fromWebKitFile (const char* filename, float hx, float hy)
  228185. {
  228186. FileInputStream fileStream (String ("/System/Library/Frameworks/WebKit.framework/Frameworks/WebCore.framework/Resources/") + filename);
  228187. BufferedInputStream buf (&fileStream, 4096, false);
  228188. PNGImageFormat pngFormat;
  228189. const ScopedPointer <Image> im (pngFormat.decodeImage (buf));
  228190. if (im != 0)
  228191. return createFromImage (*im, hx * im->getWidth(), hy * im->getHeight());
  228192. jassertfalse;
  228193. return 0;
  228194. }
  228195. }
  228196. void* MouseCursor::createMouseCursorFromImage (const Image& image, int hotspotX, int hotspotY)
  228197. {
  228198. return MouseCursorHelpers::createFromImage (image, (float) hotspotX, (float) hotspotY);
  228199. }
  228200. void* MouseCursor::createStandardMouseCursor (MouseCursor::StandardCursorType type)
  228201. {
  228202. const ScopedAutoReleasePool pool;
  228203. NSCursor* c = 0;
  228204. switch (type)
  228205. {
  228206. case NormalCursor: c = [NSCursor arrowCursor]; break;
  228207. case NoCursor: return createMouseCursorFromImage (Image (Image::ARGB, 8, 8, true), 0, 0);
  228208. case DraggingHandCursor: c = [NSCursor openHandCursor]; break;
  228209. case WaitCursor: c = [NSCursor arrowCursor]; break; // avoid this on the mac, let the OS provide the beachball
  228210. case IBeamCursor: c = [NSCursor IBeamCursor]; break;
  228211. case PointingHandCursor: c = [NSCursor pointingHandCursor]; break;
  228212. case LeftRightResizeCursor: c = [NSCursor resizeLeftRightCursor]; break;
  228213. case LeftEdgeResizeCursor: c = [NSCursor resizeLeftCursor]; break;
  228214. case RightEdgeResizeCursor: c = [NSCursor resizeRightCursor]; break;
  228215. case CrosshairCursor: c = [NSCursor crosshairCursor]; break;
  228216. case CopyingCursor: return MouseCursorHelpers::fromWebKitFile ("copyCursor.png", 0, 0);
  228217. case UpDownResizeCursor:
  228218. case TopEdgeResizeCursor:
  228219. case BottomEdgeResizeCursor:
  228220. return MouseCursorHelpers::fromWebKitFile ("northSouthResizeCursor.png", 0.5f, 0.5f);
  228221. case TopLeftCornerResizeCursor:
  228222. case BottomRightCornerResizeCursor:
  228223. return MouseCursorHelpers::fromWebKitFile ("northWestSouthEastResizeCursor.png", 0.5f, 0.5f);
  228224. case TopRightCornerResizeCursor:
  228225. case BottomLeftCornerResizeCursor:
  228226. return MouseCursorHelpers::fromWebKitFile ("northEastSouthWestResizeCursor.png", 0.5f, 0.5f);
  228227. case UpDownLeftRightResizeCursor:
  228228. return MouseCursorHelpers::fromWebKitFile ("moveCursor.png", 0.5f, 0.5f);
  228229. default:
  228230. jassertfalse;
  228231. break;
  228232. }
  228233. [c retain];
  228234. return c;
  228235. }
  228236. void MouseCursor::deleteMouseCursor (void* const cursorHandle, const bool isStandard)
  228237. {
  228238. [((NSCursor*) cursorHandle) release];
  228239. }
  228240. void MouseCursor::showInAllWindows() const
  228241. {
  228242. showInWindow (0);
  228243. }
  228244. void MouseCursor::showInWindow (ComponentPeer*) const
  228245. {
  228246. [((NSCursor*) getHandle()) set];
  228247. }
  228248. #else
  228249. void* MouseCursor::createMouseCursorFromImage (const Image& image, int hotspotX, int hotspotY) { return 0; }
  228250. void* MouseCursor::createStandardMouseCursor (MouseCursor::StandardCursorType type) { return 0; }
  228251. void MouseCursor::deleteMouseCursor (void* const cursorHandle, const bool isStandard) {}
  228252. void MouseCursor::showInAllWindows() const {}
  228253. void MouseCursor::showInWindow (ComponentPeer*) const {}
  228254. #endif
  228255. #endif
  228256. /*** End of inlined file: juce_mac_MouseCursor.mm ***/
  228257. /*** Start of inlined file: juce_mac_NSViewComponent.mm ***/
  228258. // (This file gets included by juce_mac_NativeCode.mm, rather than being
  228259. // compiled on its own).
  228260. #if JUCE_INCLUDED_FILE
  228261. class NSViewComponentInternal : public ComponentMovementWatcher
  228262. {
  228263. Component* const owner;
  228264. NSViewComponentPeer* currentPeer;
  228265. bool wasShowing;
  228266. public:
  228267. NSView* const view;
  228268. NSViewComponentInternal (NSView* const view_, Component* const owner_)
  228269. : ComponentMovementWatcher (owner_),
  228270. owner (owner_),
  228271. currentPeer (0),
  228272. wasShowing (false),
  228273. view (view_)
  228274. {
  228275. [view_ retain];
  228276. if (owner_->isShowing())
  228277. componentPeerChanged();
  228278. }
  228279. ~NSViewComponentInternal()
  228280. {
  228281. [view removeFromSuperview];
  228282. [view release];
  228283. }
  228284. void componentMovedOrResized (Component& comp, bool wasMoved, bool wasResized)
  228285. {
  228286. ComponentMovementWatcher::componentMovedOrResized (comp, wasMoved, wasResized);
  228287. // The ComponentMovementWatcher version of this method avoids calling
  228288. // us when the top-level comp is resized, but for an NSView we need to know this
  228289. // because with inverted co-ords, we need to update the position even if the
  228290. // top-left pos hasn't changed
  228291. if (comp.isOnDesktop() && wasResized)
  228292. componentMovedOrResized (wasMoved, wasResized);
  228293. }
  228294. void componentMovedOrResized (bool /*wasMoved*/, bool /*wasResized*/)
  228295. {
  228296. Component* const topComp = owner->getTopLevelComponent();
  228297. if (topComp->getPeer() != 0)
  228298. {
  228299. const Point<int> pos (owner->relativePositionToOtherComponent (topComp, Point<int>()));
  228300. NSRect r;
  228301. r.origin.x = (float) pos.getX();
  228302. r.origin.y = (float) pos.getY();
  228303. r.size.width = (float) owner->getWidth();
  228304. r.size.height = (float) owner->getHeight();
  228305. r.origin.y = [[view superview] frame].size.height - (r.origin.y + r.size.height);
  228306. [view setFrame: r];
  228307. }
  228308. }
  228309. void componentPeerChanged()
  228310. {
  228311. NSViewComponentPeer* const peer = dynamic_cast <NSViewComponentPeer*> (owner->getPeer());
  228312. if (currentPeer != peer)
  228313. {
  228314. [view removeFromSuperview];
  228315. currentPeer = peer;
  228316. if (peer != 0)
  228317. {
  228318. [peer->view addSubview: view];
  228319. componentMovedOrResized (false, false);
  228320. }
  228321. }
  228322. [view setHidden: ! owner->isShowing()];
  228323. }
  228324. void componentVisibilityChanged (Component&)
  228325. {
  228326. componentPeerChanged();
  228327. }
  228328. juce_UseDebuggingNewOperator
  228329. private:
  228330. NSViewComponentInternal (const NSViewComponentInternal&);
  228331. NSViewComponentInternal& operator= (const NSViewComponentInternal&);
  228332. };
  228333. NSViewComponent::NSViewComponent()
  228334. {
  228335. }
  228336. NSViewComponent::~NSViewComponent()
  228337. {
  228338. }
  228339. void NSViewComponent::setView (void* view)
  228340. {
  228341. if (view != getView())
  228342. {
  228343. if (view != 0)
  228344. info = new NSViewComponentInternal ((NSView*) view, this);
  228345. else
  228346. info = 0;
  228347. }
  228348. }
  228349. void* NSViewComponent::getView() const
  228350. {
  228351. return info == 0 ? 0 : info->view;
  228352. }
  228353. void NSViewComponent::paint (Graphics& g)
  228354. {
  228355. }
  228356. #endif
  228357. /*** End of inlined file: juce_mac_NSViewComponent.mm ***/
  228358. /*** Start of inlined file: juce_mac_AppleRemote.mm ***/
  228359. // (This file gets included by juce_mac_NativeCode.mm, rather than being
  228360. // compiled on its own).
  228361. #if JUCE_INCLUDED_FILE
  228362. AppleRemoteDevice::AppleRemoteDevice()
  228363. : device (0),
  228364. queue (0),
  228365. remoteId (0)
  228366. {
  228367. }
  228368. AppleRemoteDevice::~AppleRemoteDevice()
  228369. {
  228370. stop();
  228371. }
  228372. static io_object_t getAppleRemoteDevice()
  228373. {
  228374. CFMutableDictionaryRef dict = IOServiceMatching ("AppleIRController");
  228375. io_iterator_t iter = 0;
  228376. io_object_t iod = 0;
  228377. if (IOServiceGetMatchingServices (kIOMasterPortDefault, dict, &iter) == kIOReturnSuccess
  228378. && iter != 0)
  228379. {
  228380. iod = IOIteratorNext (iter);
  228381. }
  228382. IOObjectRelease (iter);
  228383. return iod;
  228384. }
  228385. static bool createAppleRemoteInterface (io_object_t iod, void** device)
  228386. {
  228387. jassert (*device == 0);
  228388. io_name_t classname;
  228389. if (IOObjectGetClass (iod, classname) == kIOReturnSuccess)
  228390. {
  228391. IOCFPlugInInterface** cfPlugInInterface = 0;
  228392. SInt32 score = 0;
  228393. if (IOCreatePlugInInterfaceForService (iod,
  228394. kIOHIDDeviceUserClientTypeID,
  228395. kIOCFPlugInInterfaceID,
  228396. &cfPlugInInterface,
  228397. &score) == kIOReturnSuccess)
  228398. {
  228399. HRESULT hr = (*cfPlugInInterface)->QueryInterface (cfPlugInInterface,
  228400. CFUUIDGetUUIDBytes (kIOHIDDeviceInterfaceID),
  228401. device);
  228402. (void) hr;
  228403. (*cfPlugInInterface)->Release (cfPlugInInterface);
  228404. }
  228405. }
  228406. return *device != 0;
  228407. }
  228408. bool AppleRemoteDevice::start (const bool inExclusiveMode)
  228409. {
  228410. if (queue != 0)
  228411. return true;
  228412. stop();
  228413. bool result = false;
  228414. io_object_t iod = getAppleRemoteDevice();
  228415. if (iod != 0)
  228416. {
  228417. if (createAppleRemoteInterface (iod, &device) && open (inExclusiveMode))
  228418. result = true;
  228419. else
  228420. stop();
  228421. IOObjectRelease (iod);
  228422. }
  228423. return result;
  228424. }
  228425. void AppleRemoteDevice::stop()
  228426. {
  228427. if (queue != 0)
  228428. {
  228429. (*(IOHIDQueueInterface**) queue)->stop ((IOHIDQueueInterface**) queue);
  228430. (*(IOHIDQueueInterface**) queue)->dispose ((IOHIDQueueInterface**) queue);
  228431. (*(IOHIDQueueInterface**) queue)->Release ((IOHIDQueueInterface**) queue);
  228432. queue = 0;
  228433. }
  228434. if (device != 0)
  228435. {
  228436. (*(IOHIDDeviceInterface**) device)->close ((IOHIDDeviceInterface**) device);
  228437. (*(IOHIDDeviceInterface**) device)->Release ((IOHIDDeviceInterface**) device);
  228438. device = 0;
  228439. }
  228440. }
  228441. bool AppleRemoteDevice::isActive() const
  228442. {
  228443. return queue != 0;
  228444. }
  228445. static void appleRemoteQueueCallback (void* const target, const IOReturn result, void*, void*)
  228446. {
  228447. if (result == kIOReturnSuccess)
  228448. ((AppleRemoteDevice*) target)->handleCallbackInternal();
  228449. }
  228450. bool AppleRemoteDevice::open (const bool openInExclusiveMode)
  228451. {
  228452. Array <int> cookies;
  228453. CFArrayRef elements;
  228454. IOHIDDeviceInterface122** const device122 = (IOHIDDeviceInterface122**) device;
  228455. if ((*device122)->copyMatchingElements (device122, 0, &elements) != kIOReturnSuccess)
  228456. return false;
  228457. for (int i = 0; i < CFArrayGetCount (elements); ++i)
  228458. {
  228459. CFDictionaryRef element = (CFDictionaryRef) CFArrayGetValueAtIndex (elements, i);
  228460. // get the cookie
  228461. CFTypeRef object = CFDictionaryGetValue (element, CFSTR (kIOHIDElementCookieKey));
  228462. if (object == 0 || CFGetTypeID (object) != CFNumberGetTypeID())
  228463. continue;
  228464. long number;
  228465. if (! CFNumberGetValue ((CFNumberRef) object, kCFNumberLongType, &number))
  228466. continue;
  228467. cookies.add ((int) number);
  228468. }
  228469. CFRelease (elements);
  228470. if ((*(IOHIDDeviceInterface**) device)
  228471. ->open ((IOHIDDeviceInterface**) device,
  228472. openInExclusiveMode ? kIOHIDOptionsTypeSeizeDevice
  228473. : kIOHIDOptionsTypeNone) == KERN_SUCCESS)
  228474. {
  228475. queue = (*(IOHIDDeviceInterface**) device)->allocQueue ((IOHIDDeviceInterface**) device);
  228476. if (queue != 0)
  228477. {
  228478. (*(IOHIDQueueInterface**) queue)->create ((IOHIDQueueInterface**) queue, 0, 12);
  228479. for (int i = 0; i < cookies.size(); ++i)
  228480. {
  228481. IOHIDElementCookie cookie = (IOHIDElementCookie) cookies.getUnchecked(i);
  228482. (*(IOHIDQueueInterface**) queue)->addElement ((IOHIDQueueInterface**) queue, cookie, 0);
  228483. }
  228484. CFRunLoopSourceRef eventSource;
  228485. if ((*(IOHIDQueueInterface**) queue)
  228486. ->createAsyncEventSource ((IOHIDQueueInterface**) queue, &eventSource) == KERN_SUCCESS)
  228487. {
  228488. if ((*(IOHIDQueueInterface**) queue)->setEventCallout ((IOHIDQueueInterface**) queue,
  228489. appleRemoteQueueCallback, this, 0) == KERN_SUCCESS)
  228490. {
  228491. CFRunLoopAddSource (CFRunLoopGetCurrent(), eventSource, kCFRunLoopDefaultMode);
  228492. (*(IOHIDQueueInterface**) queue)->start ((IOHIDQueueInterface**) queue);
  228493. return true;
  228494. }
  228495. }
  228496. }
  228497. }
  228498. return false;
  228499. }
  228500. void AppleRemoteDevice::handleCallbackInternal()
  228501. {
  228502. int totalValues = 0;
  228503. AbsoluteTime nullTime = { 0, 0 };
  228504. char cookies [12];
  228505. int numCookies = 0;
  228506. while (numCookies < numElementsInArray (cookies))
  228507. {
  228508. IOHIDEventStruct e;
  228509. if ((*(IOHIDQueueInterface**) queue)->getNextEvent ((IOHIDQueueInterface**) queue, &e, nullTime, 0) != kIOReturnSuccess)
  228510. break;
  228511. if ((int) e.elementCookie == 19)
  228512. {
  228513. remoteId = e.value;
  228514. buttonPressed (switched, false);
  228515. }
  228516. else
  228517. {
  228518. totalValues += e.value;
  228519. cookies [numCookies++] = (char) (pointer_sized_int) e.elementCookie;
  228520. }
  228521. }
  228522. cookies [numCookies++] = 0;
  228523. //DBG (String::toHexString ((uint8*) cookies, numCookies, 1) + " " + String (totalValues));
  228524. static const char buttonPatterns[] =
  228525. {
  228526. 0x1f, 0x14, 0x12, 0x1f, 0x14, 0x12, 0,
  228527. 0x1f, 0x15, 0x12, 0x1f, 0x15, 0x12, 0,
  228528. 0x1f, 0x1d, 0x1c, 0x12, 0,
  228529. 0x1f, 0x1e, 0x1c, 0x12, 0,
  228530. 0x1f, 0x16, 0x12, 0x1f, 0x16, 0x12, 0,
  228531. 0x1f, 0x17, 0x12, 0x1f, 0x17, 0x12, 0,
  228532. 0x1f, 0x12, 0x04, 0x02, 0,
  228533. 0x1f, 0x12, 0x03, 0x02, 0,
  228534. 0x1f, 0x12, 0x1f, 0x12, 0,
  228535. 0x23, 0x1f, 0x12, 0x23, 0x1f, 0x12, 0,
  228536. 19, 0
  228537. };
  228538. int buttonNum = (int) menuButton;
  228539. int i = 0;
  228540. while (i < numElementsInArray (buttonPatterns))
  228541. {
  228542. if (strcmp (cookies, buttonPatterns + i) == 0)
  228543. {
  228544. buttonPressed ((ButtonType) buttonNum, totalValues > 0);
  228545. break;
  228546. }
  228547. i += (int) strlen (buttonPatterns + i) + 1;
  228548. ++buttonNum;
  228549. }
  228550. }
  228551. #endif
  228552. /*** End of inlined file: juce_mac_AppleRemote.mm ***/
  228553. /*** Start of inlined file: juce_mac_OpenGLComponent.mm ***/
  228554. // (This file gets included by juce_mac_NativeCode.mm, rather than being
  228555. // compiled on its own).
  228556. #if JUCE_INCLUDED_FILE && JUCE_OPENGL
  228557. #if JUCE_MAC
  228558. END_JUCE_NAMESPACE
  228559. #define ThreadSafeNSOpenGLView MakeObjCClassName(ThreadSafeNSOpenGLView)
  228560. @interface ThreadSafeNSOpenGLView : NSOpenGLView
  228561. {
  228562. CriticalSection* contextLock;
  228563. bool needsUpdate;
  228564. }
  228565. - (id) initWithFrame: (NSRect) frameRect pixelFormat: (NSOpenGLPixelFormat*) format;
  228566. - (bool) makeActive;
  228567. - (void) makeInactive;
  228568. - (void) reshape;
  228569. @end
  228570. @implementation ThreadSafeNSOpenGLView
  228571. - (id) initWithFrame: (NSRect) frameRect
  228572. pixelFormat: (NSOpenGLPixelFormat*) format
  228573. {
  228574. contextLock = new CriticalSection();
  228575. self = [super initWithFrame: frameRect pixelFormat: format];
  228576. if (self != nil)
  228577. [[NSNotificationCenter defaultCenter] addObserver: self
  228578. selector: @selector (_surfaceNeedsUpdate:)
  228579. name: NSViewGlobalFrameDidChangeNotification
  228580. object: self];
  228581. return self;
  228582. }
  228583. - (void) dealloc
  228584. {
  228585. [[NSNotificationCenter defaultCenter] removeObserver: self];
  228586. delete contextLock;
  228587. [super dealloc];
  228588. }
  228589. - (bool) makeActive
  228590. {
  228591. const ScopedLock sl (*contextLock);
  228592. if ([self openGLContext] == 0)
  228593. return false;
  228594. [[self openGLContext] makeCurrentContext];
  228595. if (needsUpdate)
  228596. {
  228597. [super update];
  228598. needsUpdate = false;
  228599. }
  228600. return true;
  228601. }
  228602. - (void) makeInactive
  228603. {
  228604. const ScopedLock sl (*contextLock);
  228605. [NSOpenGLContext clearCurrentContext];
  228606. }
  228607. - (void) _surfaceNeedsUpdate: (NSNotification*) notification
  228608. {
  228609. const ScopedLock sl (*contextLock);
  228610. needsUpdate = true;
  228611. }
  228612. - (void) update
  228613. {
  228614. const ScopedLock sl (*contextLock);
  228615. needsUpdate = true;
  228616. }
  228617. - (void) reshape
  228618. {
  228619. const ScopedLock sl (*contextLock);
  228620. needsUpdate = true;
  228621. }
  228622. @end
  228623. BEGIN_JUCE_NAMESPACE
  228624. class WindowedGLContext : public OpenGLContext
  228625. {
  228626. public:
  228627. WindowedGLContext (Component* const component,
  228628. const OpenGLPixelFormat& pixelFormat_,
  228629. NSOpenGLContext* sharedContext)
  228630. : renderContext (0),
  228631. pixelFormat (pixelFormat_)
  228632. {
  228633. jassert (component != 0);
  228634. NSOpenGLPixelFormatAttribute attribs [64];
  228635. int n = 0;
  228636. attribs[n++] = NSOpenGLPFADoubleBuffer;
  228637. attribs[n++] = NSOpenGLPFAAccelerated;
  228638. attribs[n++] = NSOpenGLPFAMPSafe; // NSOpenGLPFAAccelerated, NSOpenGLPFAMultiScreen, NSOpenGLPFASingleRenderer
  228639. attribs[n++] = NSOpenGLPFAColorSize;
  228640. attribs[n++] = (NSOpenGLPixelFormatAttribute) jmax (pixelFormat.redBits,
  228641. pixelFormat.greenBits,
  228642. pixelFormat.blueBits);
  228643. attribs[n++] = NSOpenGLPFAAlphaSize;
  228644. attribs[n++] = (NSOpenGLPixelFormatAttribute) pixelFormat.alphaBits;
  228645. attribs[n++] = NSOpenGLPFADepthSize;
  228646. attribs[n++] = (NSOpenGLPixelFormatAttribute) pixelFormat.depthBufferBits;
  228647. attribs[n++] = NSOpenGLPFAStencilSize;
  228648. attribs[n++] = (NSOpenGLPixelFormatAttribute) pixelFormat.stencilBufferBits;
  228649. attribs[n++] = NSOpenGLPFAAccumSize;
  228650. attribs[n++] = (NSOpenGLPixelFormatAttribute) jmax (pixelFormat.accumulationBufferRedBits,
  228651. pixelFormat.accumulationBufferGreenBits,
  228652. pixelFormat.accumulationBufferBlueBits,
  228653. pixelFormat.accumulationBufferAlphaBits);
  228654. // xxx not sure how to do fullSceneAntiAliasingNumSamples..
  228655. attribs[n++] = NSOpenGLPFASampleBuffers;
  228656. attribs[n++] = (NSOpenGLPixelFormatAttribute) 1;
  228657. attribs[n++] = NSOpenGLPFAClosestPolicy;
  228658. attribs[n++] = NSOpenGLPFANoRecovery;
  228659. attribs[n++] = (NSOpenGLPixelFormatAttribute) 0;
  228660. NSOpenGLPixelFormat* format
  228661. = [[NSOpenGLPixelFormat alloc] initWithAttributes: attribs];
  228662. view = [[ThreadSafeNSOpenGLView alloc] initWithFrame: NSMakeRect (0, 0, 100.0f, 100.0f)
  228663. pixelFormat: format];
  228664. renderContext = [[[NSOpenGLContext alloc] initWithFormat: format
  228665. shareContext: sharedContext] autorelease];
  228666. const GLint swapInterval = 1;
  228667. [renderContext setValues: &swapInterval forParameter: NSOpenGLCPSwapInterval];
  228668. [view setOpenGLContext: renderContext];
  228669. [renderContext setView: view];
  228670. [format release];
  228671. viewHolder = new NSViewComponentInternal (view, component);
  228672. }
  228673. ~WindowedGLContext()
  228674. {
  228675. makeInactive();
  228676. [renderContext clearDrawable];
  228677. viewHolder = 0;
  228678. }
  228679. bool makeActive() const throw()
  228680. {
  228681. jassert (renderContext != 0);
  228682. [view makeActive];
  228683. return isActive();
  228684. }
  228685. bool makeInactive() const throw()
  228686. {
  228687. [view makeInactive];
  228688. return true;
  228689. }
  228690. bool isActive() const throw()
  228691. {
  228692. return [NSOpenGLContext currentContext] == renderContext;
  228693. }
  228694. const OpenGLPixelFormat getPixelFormat() const { return pixelFormat; }
  228695. void* getRawContext() const throw() { return renderContext; }
  228696. void updateWindowPosition (int x, int y, int w, int h, int outerWindowHeight)
  228697. {
  228698. }
  228699. void swapBuffers()
  228700. {
  228701. [renderContext flushBuffer];
  228702. }
  228703. bool setSwapInterval (const int numFramesPerSwap)
  228704. {
  228705. [renderContext setValues: (const GLint*) &numFramesPerSwap
  228706. forParameter: NSOpenGLCPSwapInterval];
  228707. return true;
  228708. }
  228709. int getSwapInterval() const
  228710. {
  228711. GLint numFrames = 0;
  228712. [renderContext getValues: &numFrames
  228713. forParameter: NSOpenGLCPSwapInterval];
  228714. return numFrames;
  228715. }
  228716. void repaint()
  228717. {
  228718. // we need to invalidate the juce view that holds this gl view, to make it
  228719. // cause a repaint callback
  228720. NSView* v = (NSView*) viewHolder->view;
  228721. NSRect r = [v frame];
  228722. // bit of a bodge here.. if we only invalidate the area of the gl component,
  228723. // it's completely covered by the NSOpenGLView, so the OS throws away the
  228724. // repaint message, thus never causing our paint() callback, and never repainting
  228725. // the comp. So invalidating just a little bit around the edge helps..
  228726. [[v superview] setNeedsDisplayInRect: NSInsetRect (r, -2.0f, -2.0f)];
  228727. }
  228728. void* getNativeWindowHandle() const { return viewHolder->view; }
  228729. juce_UseDebuggingNewOperator
  228730. NSOpenGLContext* renderContext;
  228731. ThreadSafeNSOpenGLView* view;
  228732. private:
  228733. OpenGLPixelFormat pixelFormat;
  228734. ScopedPointer <NSViewComponentInternal> viewHolder;
  228735. WindowedGLContext (const WindowedGLContext&);
  228736. WindowedGLContext& operator= (const WindowedGLContext&);
  228737. };
  228738. OpenGLContext* OpenGLComponent::createContext()
  228739. {
  228740. ScopedPointer<WindowedGLContext> c (new WindowedGLContext (this, preferredPixelFormat,
  228741. contextToShareListsWith != 0 ? (NSOpenGLContext*) contextToShareListsWith->getRawContext() : 0));
  228742. return (c->renderContext != 0) ? c.release() : 0;
  228743. }
  228744. void* OpenGLComponent::getNativeWindowHandle() const
  228745. {
  228746. return context != 0 ? static_cast<WindowedGLContext*> (static_cast<OpenGLContext*> (context))->getNativeWindowHandle()
  228747. : 0;
  228748. }
  228749. void juce_glViewport (const int w, const int h)
  228750. {
  228751. glViewport (0, 0, w, h);
  228752. }
  228753. void OpenGLPixelFormat::getAvailablePixelFormats (Component* /*component*/,
  228754. OwnedArray <OpenGLPixelFormat>& results)
  228755. {
  228756. /* GLint attribs [64];
  228757. int n = 0;
  228758. attribs[n++] = AGL_RGBA;
  228759. attribs[n++] = AGL_DOUBLEBUFFER;
  228760. attribs[n++] = AGL_ACCELERATED;
  228761. attribs[n++] = AGL_NO_RECOVERY;
  228762. attribs[n++] = AGL_NONE;
  228763. AGLPixelFormat p = aglChoosePixelFormat (0, 0, attribs);
  228764. while (p != 0)
  228765. {
  228766. OpenGLPixelFormat* const pf = new OpenGLPixelFormat();
  228767. pf->redBits = getAGLAttribute (p, AGL_RED_SIZE);
  228768. pf->greenBits = getAGLAttribute (p, AGL_GREEN_SIZE);
  228769. pf->blueBits = getAGLAttribute (p, AGL_BLUE_SIZE);
  228770. pf->alphaBits = getAGLAttribute (p, AGL_ALPHA_SIZE);
  228771. pf->depthBufferBits = getAGLAttribute (p, AGL_DEPTH_SIZE);
  228772. pf->stencilBufferBits = getAGLAttribute (p, AGL_STENCIL_SIZE);
  228773. pf->accumulationBufferRedBits = getAGLAttribute (p, AGL_ACCUM_RED_SIZE);
  228774. pf->accumulationBufferGreenBits = getAGLAttribute (p, AGL_ACCUM_GREEN_SIZE);
  228775. pf->accumulationBufferBlueBits = getAGLAttribute (p, AGL_ACCUM_BLUE_SIZE);
  228776. pf->accumulationBufferAlphaBits = getAGLAttribute (p, AGL_ACCUM_ALPHA_SIZE);
  228777. results.add (pf);
  228778. p = aglNextPixelFormat (p);
  228779. }*/
  228780. //jassertfalse //xxx can't see how you do this in cocoa!
  228781. }
  228782. #else
  228783. END_JUCE_NAMESPACE
  228784. @interface JuceGLView : UIView
  228785. {
  228786. }
  228787. + (Class) layerClass;
  228788. @end
  228789. @implementation JuceGLView
  228790. + (Class) layerClass
  228791. {
  228792. return [CAEAGLLayer class];
  228793. }
  228794. @end
  228795. BEGIN_JUCE_NAMESPACE
  228796. class GLESContext : public OpenGLContext
  228797. {
  228798. public:
  228799. GLESContext (UIViewComponentPeer* peer,
  228800. Component* const component_,
  228801. const OpenGLPixelFormat& pixelFormat_,
  228802. const GLESContext* const sharedContext,
  228803. NSUInteger apiType)
  228804. : component (component_), pixelFormat (pixelFormat_), glLayer (0), context (0),
  228805. useDepthBuffer (pixelFormat_.depthBufferBits > 0), frameBufferHandle (0), colorBufferHandle (0),
  228806. depthBufferHandle (0), lastWidth (0), lastHeight (0)
  228807. {
  228808. view = [[JuceGLView alloc] initWithFrame: CGRectMake (0, 0, 64, 64)];
  228809. view.opaque = YES;
  228810. view.hidden = NO;
  228811. view.backgroundColor = [UIColor blackColor];
  228812. view.userInteractionEnabled = NO;
  228813. glLayer = (CAEAGLLayer*) [view layer];
  228814. [peer->view addSubview: view];
  228815. if (sharedContext != 0)
  228816. context = [[EAGLContext alloc] initWithAPI: apiType
  228817. sharegroup: [sharedContext->context sharegroup]];
  228818. else
  228819. context = [[EAGLContext alloc] initWithAPI: apiType];
  228820. createGLBuffers();
  228821. }
  228822. ~GLESContext()
  228823. {
  228824. makeInactive();
  228825. [context release];
  228826. [view removeFromSuperview];
  228827. [view release];
  228828. freeGLBuffers();
  228829. }
  228830. bool makeActive() const throw()
  228831. {
  228832. jassert (context != 0);
  228833. [EAGLContext setCurrentContext: context];
  228834. glBindFramebufferOES (GL_FRAMEBUFFER_OES, frameBufferHandle);
  228835. return true;
  228836. }
  228837. void swapBuffers()
  228838. {
  228839. glBindRenderbufferOES (GL_RENDERBUFFER_OES, colorBufferHandle);
  228840. [context presentRenderbuffer: GL_RENDERBUFFER_OES];
  228841. }
  228842. bool makeInactive() const throw()
  228843. {
  228844. return [EAGLContext setCurrentContext: nil];
  228845. }
  228846. bool isActive() const throw()
  228847. {
  228848. return [EAGLContext currentContext] == context;
  228849. }
  228850. const OpenGLPixelFormat getPixelFormat() const { return pixelFormat; }
  228851. void* getRawContext() const throw() { return glLayer; }
  228852. void updateWindowPosition (int x, int y, int w, int h, int outerWindowHeight)
  228853. {
  228854. view.frame = CGRectMake ((CGFloat) x, (CGFloat) y, (CGFloat) w, (CGFloat) h);
  228855. if (lastWidth != w || lastHeight != h)
  228856. {
  228857. lastWidth = w;
  228858. lastHeight = h;
  228859. freeGLBuffers();
  228860. createGLBuffers();
  228861. }
  228862. }
  228863. bool setSwapInterval (const int numFramesPerSwap)
  228864. {
  228865. numFrames = numFramesPerSwap;
  228866. return true;
  228867. }
  228868. int getSwapInterval() const
  228869. {
  228870. return numFrames;
  228871. }
  228872. void repaint()
  228873. {
  228874. }
  228875. void createGLBuffers()
  228876. {
  228877. makeActive();
  228878. glGenFramebuffersOES (1, &frameBufferHandle);
  228879. glGenRenderbuffersOES (1, &colorBufferHandle);
  228880. glGenRenderbuffersOES (1, &depthBufferHandle);
  228881. glBindRenderbufferOES (GL_RENDERBUFFER_OES, colorBufferHandle);
  228882. [context renderbufferStorage: GL_RENDERBUFFER_OES fromDrawable: glLayer];
  228883. GLint width, height;
  228884. glGetRenderbufferParameterivOES (GL_RENDERBUFFER_OES, GL_RENDERBUFFER_WIDTH_OES, &width);
  228885. glGetRenderbufferParameterivOES (GL_RENDERBUFFER_OES, GL_RENDERBUFFER_HEIGHT_OES, &height);
  228886. if (useDepthBuffer)
  228887. {
  228888. glBindRenderbufferOES (GL_RENDERBUFFER_OES, depthBufferHandle);
  228889. glRenderbufferStorageOES (GL_RENDERBUFFER_OES, GL_DEPTH_COMPONENT16_OES, width, height);
  228890. }
  228891. glBindRenderbufferOES (GL_RENDERBUFFER_OES, colorBufferHandle);
  228892. glBindFramebufferOES (GL_FRAMEBUFFER_OES, frameBufferHandle);
  228893. glFramebufferRenderbufferOES (GL_FRAMEBUFFER_OES, GL_COLOR_ATTACHMENT0_OES, GL_RENDERBUFFER_OES, colorBufferHandle);
  228894. if (useDepthBuffer)
  228895. glFramebufferRenderbufferOES (GL_FRAMEBUFFER_OES, GL_DEPTH_ATTACHMENT_OES, GL_RENDERBUFFER_OES, depthBufferHandle);
  228896. jassert (glCheckFramebufferStatusOES (GL_FRAMEBUFFER_OES) == GL_FRAMEBUFFER_COMPLETE_OES);
  228897. }
  228898. void freeGLBuffers()
  228899. {
  228900. if (frameBufferHandle != 0)
  228901. {
  228902. glDeleteFramebuffersOES (1, &frameBufferHandle);
  228903. frameBufferHandle = 0;
  228904. }
  228905. if (colorBufferHandle != 0)
  228906. {
  228907. glDeleteRenderbuffersOES (1, &colorBufferHandle);
  228908. colorBufferHandle = 0;
  228909. }
  228910. if (depthBufferHandle != 0)
  228911. {
  228912. glDeleteRenderbuffersOES (1, &depthBufferHandle);
  228913. depthBufferHandle = 0;
  228914. }
  228915. }
  228916. juce_UseDebuggingNewOperator
  228917. private:
  228918. Component::SafePointer<Component> component;
  228919. OpenGLPixelFormat pixelFormat;
  228920. JuceGLView* view;
  228921. CAEAGLLayer* glLayer;
  228922. EAGLContext* context;
  228923. bool useDepthBuffer;
  228924. GLuint frameBufferHandle, colorBufferHandle, depthBufferHandle;
  228925. int numFrames;
  228926. int lastWidth, lastHeight;
  228927. GLESContext (const GLESContext&);
  228928. GLESContext& operator= (const GLESContext&);
  228929. };
  228930. OpenGLContext* OpenGLComponent::createContext()
  228931. {
  228932. ScopedAutoReleasePool pool;
  228933. UIViewComponentPeer* peer = dynamic_cast <UIViewComponentPeer*> (getPeer());
  228934. if (peer != 0)
  228935. return new GLESContext (peer, this, preferredPixelFormat,
  228936. dynamic_cast <const GLESContext*> (contextToShareListsWith),
  228937. type == openGLES2 ? kEAGLRenderingAPIOpenGLES2 : kEAGLRenderingAPIOpenGLES1);
  228938. return 0;
  228939. }
  228940. void OpenGLPixelFormat::getAvailablePixelFormats (Component* /*component*/,
  228941. OwnedArray <OpenGLPixelFormat>& /*results*/)
  228942. {
  228943. }
  228944. void juce_glViewport (const int w, const int h)
  228945. {
  228946. glViewport (0, 0, w, h);
  228947. }
  228948. #endif
  228949. #endif
  228950. /*** End of inlined file: juce_mac_OpenGLComponent.mm ***/
  228951. /*** Start of inlined file: juce_mac_MainMenu.mm ***/
  228952. // (This file gets included by juce_mac_NativeCode.mm, rather than being
  228953. // compiled on its own).
  228954. #if JUCE_INCLUDED_FILE
  228955. class JuceMainMenuHandler;
  228956. END_JUCE_NAMESPACE
  228957. using namespace JUCE_NAMESPACE;
  228958. #define JuceMenuCallback MakeObjCClassName(JuceMenuCallback)
  228959. #if defined (MAC_OS_X_VERSION_10_6) && MAC_OS_X_VERSION_MAX_ALLOWED >= MAC_OS_X_VERSION_10_6
  228960. @interface JuceMenuCallback : NSObject <NSMenuDelegate>
  228961. #else
  228962. @interface JuceMenuCallback : NSObject
  228963. #endif
  228964. {
  228965. JuceMainMenuHandler* owner;
  228966. }
  228967. - (JuceMenuCallback*) initWithOwner: (JuceMainMenuHandler*) owner_;
  228968. - (void) dealloc;
  228969. - (void) menuItemInvoked: (id) menu;
  228970. - (void) menuNeedsUpdate: (NSMenu*) menu;
  228971. @end
  228972. BEGIN_JUCE_NAMESPACE
  228973. class JuceMainMenuHandler : private MenuBarModelListener,
  228974. private DeletedAtShutdown
  228975. {
  228976. public:
  228977. static JuceMainMenuHandler* instance;
  228978. JuceMainMenuHandler()
  228979. : currentModel (0),
  228980. lastUpdateTime (0)
  228981. {
  228982. callback = [[JuceMenuCallback alloc] initWithOwner: this];
  228983. }
  228984. ~JuceMainMenuHandler()
  228985. {
  228986. setMenu (0);
  228987. jassert (instance == this);
  228988. instance = 0;
  228989. [callback release];
  228990. }
  228991. void setMenu (MenuBarModel* const newMenuBarModel)
  228992. {
  228993. if (currentModel != newMenuBarModel)
  228994. {
  228995. if (currentModel != 0)
  228996. currentModel->removeListener (this);
  228997. currentModel = newMenuBarModel;
  228998. if (currentModel != 0)
  228999. currentModel->addListener (this);
  229000. menuBarItemsChanged (0);
  229001. }
  229002. }
  229003. void addSubMenu (NSMenu* parent, const PopupMenu& child,
  229004. const String& name, const int menuId, const int tag)
  229005. {
  229006. NSMenuItem* item = [parent addItemWithTitle: juceStringToNS (name)
  229007. action: nil
  229008. keyEquivalent: @""];
  229009. [item setTag: tag];
  229010. NSMenu* sub = createMenu (child, name, menuId, tag);
  229011. [parent setSubmenu: sub forItem: item];
  229012. [sub setAutoenablesItems: false];
  229013. [sub release];
  229014. }
  229015. void updateSubMenu (NSMenuItem* parentItem, const PopupMenu& menuToCopy,
  229016. const String& name, const int menuId, const int tag)
  229017. {
  229018. [parentItem setTag: tag];
  229019. NSMenu* menu = [parentItem submenu];
  229020. [menu setTitle: juceStringToNS (name)];
  229021. while ([menu numberOfItems] > 0)
  229022. [menu removeItemAtIndex: 0];
  229023. PopupMenu::MenuItemIterator iter (menuToCopy);
  229024. while (iter.next())
  229025. addMenuItem (iter, menu, menuId, tag);
  229026. [menu setAutoenablesItems: false];
  229027. [menu update];
  229028. }
  229029. void menuBarItemsChanged (MenuBarModel*)
  229030. {
  229031. lastUpdateTime = Time::getMillisecondCounter();
  229032. StringArray menuNames;
  229033. if (currentModel != 0)
  229034. menuNames = currentModel->getMenuBarNames();
  229035. NSMenu* menuBar = [NSApp mainMenu];
  229036. while ([menuBar numberOfItems] > 1 + menuNames.size())
  229037. [menuBar removeItemAtIndex: [menuBar numberOfItems] - 1];
  229038. int menuId = 1;
  229039. for (int i = 0; i < menuNames.size(); ++i)
  229040. {
  229041. const PopupMenu menu (currentModel->getMenuForIndex (i, menuNames [i]));
  229042. if (i >= [menuBar numberOfItems] - 1)
  229043. addSubMenu (menuBar, menu, menuNames[i], menuId, i);
  229044. else
  229045. updateSubMenu ([menuBar itemAtIndex: 1 + i], menu, menuNames[i], menuId, i);
  229046. }
  229047. }
  229048. static void flashMenuBar (NSMenu* menu)
  229049. {
  229050. if ([[menu title] isEqualToString: @"Apple"])
  229051. return;
  229052. [menu retain];
  229053. const unichar f35Key = NSF35FunctionKey;
  229054. NSString* f35String = [NSString stringWithCharacters: &f35Key length: 1];
  229055. NSMenuItem* item = [[NSMenuItem alloc] initWithTitle: @"x"
  229056. action: nil
  229057. keyEquivalent: f35String];
  229058. [item setTarget: nil];
  229059. [menu insertItem: item atIndex: [menu numberOfItems]];
  229060. [item release];
  229061. if ([menu indexOfItem: item] >= 0)
  229062. {
  229063. NSEvent* f35Event = [NSEvent keyEventWithType: NSKeyDown
  229064. location: NSZeroPoint
  229065. modifierFlags: NSCommandKeyMask
  229066. timestamp: 0
  229067. windowNumber: 0
  229068. context: [NSGraphicsContext currentContext]
  229069. characters: f35String
  229070. charactersIgnoringModifiers: f35String
  229071. isARepeat: NO
  229072. keyCode: 0];
  229073. [menu performKeyEquivalent: f35Event];
  229074. if ([menu indexOfItem: item] >= 0)
  229075. [menu removeItem: item]; // (this throws if the item isn't actually in the menu)
  229076. }
  229077. [menu release];
  229078. }
  229079. static NSMenuItem* findMenuItem (NSMenu* const menu, const ApplicationCommandTarget::InvocationInfo& info)
  229080. {
  229081. for (NSInteger i = [menu numberOfItems]; --i >= 0;)
  229082. {
  229083. NSMenuItem* m = [menu itemAtIndex: i];
  229084. if ([m tag] == info.commandID)
  229085. return m;
  229086. if ([m submenu] != 0)
  229087. {
  229088. NSMenuItem* found = findMenuItem ([m submenu], info);
  229089. if (found != 0)
  229090. return found;
  229091. }
  229092. }
  229093. return 0;
  229094. }
  229095. void menuCommandInvoked (MenuBarModel*, const ApplicationCommandTarget::InvocationInfo& info)
  229096. {
  229097. NSMenuItem* item = findMenuItem ([NSApp mainMenu], info);
  229098. if (item != 0)
  229099. flashMenuBar ([item menu]);
  229100. }
  229101. void updateMenus()
  229102. {
  229103. if (Time::getMillisecondCounter() > lastUpdateTime + 500)
  229104. menuBarItemsChanged (0);
  229105. }
  229106. void invoke (const int commandId, ApplicationCommandManager* const commandManager, const int topLevelIndex) const
  229107. {
  229108. if (currentModel != 0)
  229109. {
  229110. if (commandManager != 0)
  229111. {
  229112. ApplicationCommandTarget::InvocationInfo info (commandId);
  229113. info.invocationMethod = ApplicationCommandTarget::InvocationInfo::fromMenu;
  229114. commandManager->invoke (info, true);
  229115. }
  229116. currentModel->menuItemSelected (commandId, topLevelIndex);
  229117. }
  229118. }
  229119. MenuBarModel* currentModel;
  229120. uint32 lastUpdateTime;
  229121. void addMenuItem (PopupMenu::MenuItemIterator& iter, NSMenu* menuToAddTo,
  229122. const int topLevelMenuId, const int topLevelIndex)
  229123. {
  229124. NSString* text = juceStringToNS (iter.itemName.upToFirstOccurrenceOf ("<end>", false, true));
  229125. if (text == 0)
  229126. text = @"";
  229127. if (iter.isSeparator)
  229128. {
  229129. [menuToAddTo addItem: [NSMenuItem separatorItem]];
  229130. }
  229131. else if (iter.isSectionHeader)
  229132. {
  229133. NSMenuItem* item = [menuToAddTo addItemWithTitle: text
  229134. action: nil
  229135. keyEquivalent: @""];
  229136. [item setEnabled: false];
  229137. }
  229138. else if (iter.subMenu != 0)
  229139. {
  229140. NSMenuItem* item = [menuToAddTo addItemWithTitle: text
  229141. action: nil
  229142. keyEquivalent: @""];
  229143. [item setTag: iter.itemId];
  229144. [item setEnabled: iter.isEnabled];
  229145. NSMenu* sub = createMenu (*iter.subMenu, iter.itemName, topLevelMenuId, topLevelIndex);
  229146. [sub setDelegate: nil];
  229147. [menuToAddTo setSubmenu: sub forItem: item];
  229148. [sub release];
  229149. }
  229150. else
  229151. {
  229152. NSMenuItem* item = [menuToAddTo addItemWithTitle: text
  229153. action: @selector (menuItemInvoked:)
  229154. keyEquivalent: @""];
  229155. [item setTag: iter.itemId];
  229156. [item setEnabled: iter.isEnabled];
  229157. [item setState: iter.isTicked ? NSOnState : NSOffState];
  229158. [item setTarget: (id) callback];
  229159. NSMutableArray* info = [NSMutableArray arrayWithObject: [NSNumber numberWithUnsignedLongLong: (pointer_sized_int) (void*) iter.commandManager]];
  229160. [info addObject: [NSNumber numberWithInt: topLevelIndex]];
  229161. [item setRepresentedObject: info];
  229162. if (iter.commandManager != 0)
  229163. {
  229164. const Array <KeyPress> keyPresses (iter.commandManager->getKeyMappings()
  229165. ->getKeyPressesAssignedToCommand (iter.itemId));
  229166. if (keyPresses.size() > 0)
  229167. {
  229168. const KeyPress& kp = keyPresses.getReference(0);
  229169. if (kp.getKeyCode() != KeyPress::backspaceKey
  229170. && kp.getKeyCode() != KeyPress::deleteKey) // (adding these is annoying because it flashes the menu bar
  229171. // every time you press the key while editing text)
  229172. {
  229173. juce_wchar key = kp.getTextCharacter();
  229174. if (kp.getKeyCode() == KeyPress::backspaceKey)
  229175. key = NSBackspaceCharacter;
  229176. else if (kp.getKeyCode() == KeyPress::deleteKey)
  229177. key = NSDeleteCharacter;
  229178. else if (key == 0)
  229179. key = (juce_wchar) kp.getKeyCode();
  229180. unsigned int mods = 0;
  229181. if (kp.getModifiers().isShiftDown())
  229182. mods |= NSShiftKeyMask;
  229183. if (kp.getModifiers().isCtrlDown())
  229184. mods |= NSControlKeyMask;
  229185. if (kp.getModifiers().isAltDown())
  229186. mods |= NSAlternateKeyMask;
  229187. if (kp.getModifiers().isCommandDown())
  229188. mods |= NSCommandKeyMask;
  229189. [item setKeyEquivalent: juceStringToNS (String::charToString (key))];
  229190. [item setKeyEquivalentModifierMask: mods];
  229191. }
  229192. }
  229193. }
  229194. }
  229195. }
  229196. JuceMenuCallback* callback;
  229197. private:
  229198. NSMenu* createMenu (const PopupMenu menu,
  229199. const String& menuName,
  229200. const int topLevelMenuId,
  229201. const int topLevelIndex)
  229202. {
  229203. NSMenu* m = [[NSMenu alloc] initWithTitle: juceStringToNS (menuName)];
  229204. [m setAutoenablesItems: false];
  229205. [m setDelegate: callback];
  229206. PopupMenu::MenuItemIterator iter (menu);
  229207. while (iter.next())
  229208. addMenuItem (iter, m, topLevelMenuId, topLevelIndex);
  229209. [m update];
  229210. return m;
  229211. }
  229212. };
  229213. JuceMainMenuHandler* JuceMainMenuHandler::instance = 0;
  229214. END_JUCE_NAMESPACE
  229215. @implementation JuceMenuCallback
  229216. - (JuceMenuCallback*) initWithOwner: (JuceMainMenuHandler*) owner_
  229217. {
  229218. [super init];
  229219. owner = owner_;
  229220. return self;
  229221. }
  229222. - (void) dealloc
  229223. {
  229224. [super dealloc];
  229225. }
  229226. - (void) menuItemInvoked: (id) menu
  229227. {
  229228. NSMenuItem* item = (NSMenuItem*) menu;
  229229. if ([[item representedObject] isKindOfClass: [NSArray class]])
  229230. {
  229231. // 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
  229232. // our own components, which may have wanted to intercept it. So, rather than dispatching directly, we'll feed it back
  229233. // into the focused component and let it trigger the menu item indirectly.
  229234. NSEvent* e = [NSApp currentEvent];
  229235. if ([e type] == NSKeyDown || [e type] == NSKeyUp)
  229236. {
  229237. if (JUCE_NAMESPACE::Component::getCurrentlyFocusedComponent() != 0)
  229238. {
  229239. JUCE_NAMESPACE::NSViewComponentPeer* peer = dynamic_cast <JUCE_NAMESPACE::NSViewComponentPeer*> (JUCE_NAMESPACE::Component::getCurrentlyFocusedComponent()->getPeer());
  229240. if (peer != 0)
  229241. {
  229242. if ([e type] == NSKeyDown)
  229243. peer->redirectKeyDown (e);
  229244. else
  229245. peer->redirectKeyUp (e);
  229246. return;
  229247. }
  229248. }
  229249. }
  229250. NSArray* info = (NSArray*) [item representedObject];
  229251. owner->invoke ((int) [item tag],
  229252. (ApplicationCommandManager*) (pointer_sized_int)
  229253. [((NSNumber*) [info objectAtIndex: 0]) unsignedLongLongValue],
  229254. (int) [((NSNumber*) [info objectAtIndex: 1]) intValue]);
  229255. }
  229256. }
  229257. - (void) menuNeedsUpdate: (NSMenu*) menu;
  229258. {
  229259. if (JuceMainMenuHandler::instance != 0)
  229260. JuceMainMenuHandler::instance->updateMenus();
  229261. }
  229262. @end
  229263. BEGIN_JUCE_NAMESPACE
  229264. static NSMenu* createStandardAppMenu (NSMenu* menu, const String& appName,
  229265. const PopupMenu* extraItems)
  229266. {
  229267. if (extraItems != 0 && JuceMainMenuHandler::instance != 0 && extraItems->getNumItems() > 0)
  229268. {
  229269. PopupMenu::MenuItemIterator iter (*extraItems);
  229270. while (iter.next())
  229271. JuceMainMenuHandler::instance->addMenuItem (iter, menu, 0, -1);
  229272. [menu addItem: [NSMenuItem separatorItem]];
  229273. }
  229274. NSMenuItem* item;
  229275. // Services...
  229276. item = [[NSMenuItem alloc] initWithTitle: NSLocalizedString (@"Services", nil)
  229277. action: nil keyEquivalent: @""];
  229278. [menu addItem: item];
  229279. [item release];
  229280. NSMenu* servicesMenu = [[NSMenu alloc] initWithTitle: @"Services"];
  229281. [menu setSubmenu: servicesMenu forItem: item];
  229282. [NSApp setServicesMenu: servicesMenu];
  229283. [servicesMenu release];
  229284. [menu addItem: [NSMenuItem separatorItem]];
  229285. // Hide + Show stuff...
  229286. item = [[NSMenuItem alloc] initWithTitle: juceStringToNS ("Hide " + appName)
  229287. action: @selector (hide:) keyEquivalent: @"h"];
  229288. [item setTarget: NSApp];
  229289. [menu addItem: item];
  229290. [item release];
  229291. item = [[NSMenuItem alloc] initWithTitle: NSLocalizedString (@"Hide Others", nil)
  229292. action: @selector (hideOtherApplications:) keyEquivalent: @"h"];
  229293. [item setKeyEquivalentModifierMask: NSCommandKeyMask | NSAlternateKeyMask];
  229294. [item setTarget: NSApp];
  229295. [menu addItem: item];
  229296. [item release];
  229297. item = [[NSMenuItem alloc] initWithTitle: NSLocalizedString (@"Show All", nil)
  229298. action: @selector (unhideAllApplications:) keyEquivalent: @""];
  229299. [item setTarget: NSApp];
  229300. [menu addItem: item];
  229301. [item release];
  229302. [menu addItem: [NSMenuItem separatorItem]];
  229303. // Quit item....
  229304. item = [[NSMenuItem alloc] initWithTitle: juceStringToNS ("Quit " + appName)
  229305. action: @selector (terminate:) keyEquivalent: @"q"];
  229306. [item setTarget: NSApp];
  229307. [menu addItem: item];
  229308. [item release];
  229309. return menu;
  229310. }
  229311. // Since our app has no NIB, this initialises a standard app menu...
  229312. static void rebuildMainMenu (const PopupMenu* extraItems)
  229313. {
  229314. // this can't be used in a plugin!
  229315. jassert (JUCEApplication::getInstance() != 0);
  229316. if (JUCEApplication::getInstance() != 0)
  229317. {
  229318. const ScopedAutoReleasePool pool;
  229319. NSMenu* mainMenu = [[NSMenu alloc] initWithTitle: @"MainMenu"];
  229320. NSMenuItem* item = [mainMenu addItemWithTitle: @"Apple" action: nil keyEquivalent: @""];
  229321. NSMenu* appMenu = [[NSMenu alloc] initWithTitle: @"Apple"];
  229322. [NSApp performSelector: @selector (setAppleMenu:) withObject: appMenu];
  229323. [mainMenu setSubmenu: appMenu forItem: item];
  229324. [NSApp setMainMenu: mainMenu];
  229325. createStandardAppMenu (appMenu, JUCEApplication::getInstance()->getApplicationName(), extraItems);
  229326. [appMenu release];
  229327. [mainMenu release];
  229328. }
  229329. }
  229330. void MenuBarModel::setMacMainMenu (MenuBarModel* newMenuBarModel,
  229331. const PopupMenu* extraAppleMenuItems)
  229332. {
  229333. if (getMacMainMenu() != newMenuBarModel)
  229334. {
  229335. const ScopedAutoReleasePool pool;
  229336. if (newMenuBarModel == 0)
  229337. {
  229338. delete JuceMainMenuHandler::instance;
  229339. jassert (JuceMainMenuHandler::instance == 0); // should be zeroed in the destructor
  229340. jassert (extraAppleMenuItems == 0); // you can't specify some extra items without also supplying a model
  229341. extraAppleMenuItems = 0;
  229342. }
  229343. else
  229344. {
  229345. if (JuceMainMenuHandler::instance == 0)
  229346. JuceMainMenuHandler::instance = new JuceMainMenuHandler();
  229347. JuceMainMenuHandler::instance->setMenu (newMenuBarModel);
  229348. }
  229349. }
  229350. rebuildMainMenu (extraAppleMenuItems);
  229351. if (newMenuBarModel != 0)
  229352. newMenuBarModel->menuItemsChanged();
  229353. }
  229354. MenuBarModel* MenuBarModel::getMacMainMenu()
  229355. {
  229356. return JuceMainMenuHandler::instance != 0
  229357. ? JuceMainMenuHandler::instance->currentModel : 0;
  229358. }
  229359. void initialiseMainMenu()
  229360. {
  229361. if (JUCEApplication::getInstance() != 0) // only needed in an app
  229362. rebuildMainMenu (0);
  229363. }
  229364. #endif
  229365. /*** End of inlined file: juce_mac_MainMenu.mm ***/
  229366. /*** Start of inlined file: juce_mac_FileChooser.mm ***/
  229367. // (This file gets included by juce_mac_NativeCode.mm, rather than being
  229368. // compiled on its own).
  229369. #if JUCE_INCLUDED_FILE
  229370. #if JUCE_MAC
  229371. END_JUCE_NAMESPACE
  229372. using namespace JUCE_NAMESPACE;
  229373. #define JuceFileChooserDelegate MakeObjCClassName(JuceFileChooserDelegate)
  229374. #if defined (MAC_OS_X_VERSION_10_6) && MAC_OS_X_VERSION_MAX_ALLOWED >= MAC_OS_X_VERSION_10_6
  229375. @interface JuceFileChooserDelegate : NSObject <NSOpenSavePanelDelegate>
  229376. #else
  229377. @interface JuceFileChooserDelegate : NSObject
  229378. #endif
  229379. {
  229380. StringArray* filters;
  229381. }
  229382. - (JuceFileChooserDelegate*) initWithFilters: (StringArray*) filters_;
  229383. - (void) dealloc;
  229384. - (BOOL) panel: (id) sender shouldShowFilename: (NSString*) filename;
  229385. @end
  229386. @implementation JuceFileChooserDelegate
  229387. - (JuceFileChooserDelegate*) initWithFilters: (StringArray*) filters_
  229388. {
  229389. [super init];
  229390. filters = filters_;
  229391. return self;
  229392. }
  229393. - (void) dealloc
  229394. {
  229395. delete filters;
  229396. [super dealloc];
  229397. }
  229398. - (BOOL) panel: (id) sender shouldShowFilename: (NSString*) filename
  229399. {
  229400. const File f (nsStringToJuce (filename));
  229401. for (int i = filters->size(); --i >= 0;)
  229402. if (f.getFileName().matchesWildcard ((*filters)[i], true))
  229403. return true;
  229404. return f.isDirectory();
  229405. }
  229406. @end
  229407. BEGIN_JUCE_NAMESPACE
  229408. void FileChooser::showPlatformDialog (Array<File>& results,
  229409. const String& title,
  229410. const File& currentFileOrDirectory,
  229411. const String& filter,
  229412. bool selectsDirectory,
  229413. bool selectsFiles,
  229414. bool isSaveDialogue,
  229415. bool warnAboutOverwritingExistingFiles,
  229416. bool selectMultipleFiles,
  229417. FilePreviewComponent* extraInfoComponent)
  229418. {
  229419. const ScopedAutoReleasePool pool;
  229420. StringArray* filters = new StringArray();
  229421. filters->addTokens (filter.replaceCharacters (",:", ";;"), ";", String::empty);
  229422. filters->trim();
  229423. filters->removeEmptyStrings();
  229424. JuceFileChooserDelegate* delegate = [[JuceFileChooserDelegate alloc] initWithFilters: filters];
  229425. [delegate autorelease];
  229426. NSSavePanel* panel = isSaveDialogue ? [NSSavePanel savePanel]
  229427. : [NSOpenPanel openPanel];
  229428. [panel setTitle: juceStringToNS (title)];
  229429. if (! isSaveDialogue)
  229430. {
  229431. NSOpenPanel* openPanel = (NSOpenPanel*) panel;
  229432. [openPanel setCanChooseDirectories: selectsDirectory];
  229433. [openPanel setCanChooseFiles: selectsFiles];
  229434. [openPanel setAllowsMultipleSelection: selectMultipleFiles];
  229435. }
  229436. [panel setDelegate: delegate];
  229437. if (isSaveDialogue || selectsDirectory)
  229438. [panel setCanCreateDirectories: YES];
  229439. String directory, filename;
  229440. if (currentFileOrDirectory.isDirectory())
  229441. {
  229442. directory = currentFileOrDirectory.getFullPathName();
  229443. }
  229444. else
  229445. {
  229446. directory = currentFileOrDirectory.getParentDirectory().getFullPathName();
  229447. filename = currentFileOrDirectory.getFileName();
  229448. }
  229449. if ([panel runModalForDirectory: juceStringToNS (directory)
  229450. file: juceStringToNS (filename)]
  229451. == NSOKButton)
  229452. {
  229453. if (isSaveDialogue)
  229454. {
  229455. results.add (File (nsStringToJuce ([panel filename])));
  229456. }
  229457. else
  229458. {
  229459. NSOpenPanel* openPanel = (NSOpenPanel*) panel;
  229460. NSArray* urls = [openPanel filenames];
  229461. for (unsigned int i = 0; i < [urls count]; ++i)
  229462. {
  229463. NSString* f = [urls objectAtIndex: i];
  229464. results.add (File (nsStringToJuce (f)));
  229465. }
  229466. }
  229467. }
  229468. [panel setDelegate: nil];
  229469. }
  229470. #else
  229471. void FileChooser::showPlatformDialog (Array<File>& results,
  229472. const String& title,
  229473. const File& currentFileOrDirectory,
  229474. const String& filter,
  229475. bool selectsDirectory,
  229476. bool selectsFiles,
  229477. bool isSaveDialogue,
  229478. bool warnAboutOverwritingExistingFiles,
  229479. bool selectMultipleFiles,
  229480. FilePreviewComponent* extraInfoComponent)
  229481. {
  229482. const ScopedAutoReleasePool pool;
  229483. jassertfalse //xxx to do
  229484. }
  229485. #endif
  229486. #endif
  229487. /*** End of inlined file: juce_mac_FileChooser.mm ***/
  229488. /*** Start of inlined file: juce_mac_QuickTimeMovieComponent.mm ***/
  229489. // (This file gets included by juce_mac_NativeCode.mm, rather than being
  229490. // compiled on its own).
  229491. #if JUCE_INCLUDED_FILE && JUCE_QUICKTIME
  229492. END_JUCE_NAMESPACE
  229493. #define NonInterceptingQTMovieView MakeObjCClassName(NonInterceptingQTMovieView)
  229494. @interface NonInterceptingQTMovieView : QTMovieView
  229495. {
  229496. }
  229497. - (id) initWithFrame: (NSRect) frame;
  229498. - (BOOL) acceptsFirstMouse: (NSEvent*) theEvent;
  229499. - (NSView*) hitTest: (NSPoint) p;
  229500. @end
  229501. @implementation NonInterceptingQTMovieView
  229502. - (id) initWithFrame: (NSRect) frame
  229503. {
  229504. self = [super initWithFrame: frame];
  229505. [self setNextResponder: [self superview]];
  229506. return self;
  229507. }
  229508. - (void) dealloc
  229509. {
  229510. [super dealloc];
  229511. }
  229512. - (NSView*) hitTest: (NSPoint) point
  229513. {
  229514. return [self isControllerVisible] ? [super hitTest: point] : nil;
  229515. }
  229516. - (BOOL) acceptsFirstMouse: (NSEvent*) theEvent
  229517. {
  229518. return YES;
  229519. }
  229520. @end
  229521. BEGIN_JUCE_NAMESPACE
  229522. #define theMovie (static_cast <QTMovie*> (movie))
  229523. QuickTimeMovieComponent::QuickTimeMovieComponent()
  229524. : movie (0)
  229525. {
  229526. setOpaque (true);
  229527. setVisible (true);
  229528. QTMovieView* view = [[NonInterceptingQTMovieView alloc] initWithFrame: NSMakeRect (0, 0, 100.0f, 100.0f)];
  229529. setView (view);
  229530. [view release];
  229531. }
  229532. QuickTimeMovieComponent::~QuickTimeMovieComponent()
  229533. {
  229534. closeMovie();
  229535. setView (0);
  229536. }
  229537. bool QuickTimeMovieComponent::isQuickTimeAvailable() throw()
  229538. {
  229539. return true;
  229540. }
  229541. static QTMovie* openMovieFromStream (InputStream* movieStream, File& movieFile)
  229542. {
  229543. // unfortunately, QTMovie objects can only be created on the main thread..
  229544. jassert (MessageManager::getInstance()->isThisTheMessageThread());
  229545. QTMovie* movie = 0;
  229546. FileInputStream* const fin = dynamic_cast <FileInputStream*> (movieStream);
  229547. if (fin != 0)
  229548. {
  229549. movieFile = fin->getFile();
  229550. movie = [QTMovie movieWithFile: juceStringToNS (movieFile.getFullPathName())
  229551. error: nil];
  229552. }
  229553. else
  229554. {
  229555. MemoryBlock temp;
  229556. movieStream->readIntoMemoryBlock (temp);
  229557. const char* const suffixesToTry[] = { ".mov", ".mp3", ".avi", ".m4a" };
  229558. for (int i = 0; i < numElementsInArray (suffixesToTry); ++i)
  229559. {
  229560. movie = [QTMovie movieWithDataReference: [QTDataReference dataReferenceWithReferenceToData: [NSData dataWithBytes: temp.getData()
  229561. length: temp.getSize()]
  229562. name: [NSString stringWithUTF8String: suffixesToTry[i]]
  229563. MIMEType: @""]
  229564. error: nil];
  229565. if (movie != 0)
  229566. break;
  229567. }
  229568. }
  229569. return movie;
  229570. }
  229571. bool QuickTimeMovieComponent::loadMovie (const File& movieFile_,
  229572. const bool isControllerVisible_)
  229573. {
  229574. return loadMovie ((InputStream*) movieFile_.createInputStream(), isControllerVisible_);
  229575. }
  229576. bool QuickTimeMovieComponent::loadMovie (InputStream* movieStream,
  229577. const bool controllerVisible_)
  229578. {
  229579. closeMovie();
  229580. if (getPeer() == 0)
  229581. {
  229582. // To open a movie, this component must be visible inside a functioning window, so that
  229583. // the QT control can be assigned to the window.
  229584. jassertfalse
  229585. return false;
  229586. }
  229587. movie = openMovieFromStream (movieStream, movieFile);
  229588. [theMovie retain];
  229589. QTMovieView* view = (QTMovieView*) getView();
  229590. [view setMovie: theMovie];
  229591. [view setControllerVisible: controllerVisible_];
  229592. setLooping (looping);
  229593. return movie != nil;
  229594. }
  229595. bool QuickTimeMovieComponent::loadMovie (const URL& movieURL,
  229596. const bool isControllerVisible_)
  229597. {
  229598. // unfortunately, QTMovie objects can only be created on the main thread..
  229599. jassert (MessageManager::getInstance()->isThisTheMessageThread());
  229600. closeMovie();
  229601. if (getPeer() == 0)
  229602. {
  229603. // To open a movie, this component must be visible inside a functioning window, so that
  229604. // the QT control can be assigned to the window.
  229605. jassertfalse
  229606. return false;
  229607. }
  229608. NSURL* url = [NSURL URLWithString: juceStringToNS (movieURL.toString (true))];
  229609. NSError* err;
  229610. if ([QTMovie canInitWithURL: url])
  229611. movie = [QTMovie movieWithURL: url error: &err];
  229612. [theMovie retain];
  229613. QTMovieView* view = (QTMovieView*) getView();
  229614. [view setMovie: theMovie];
  229615. [view setControllerVisible: controllerVisible];
  229616. setLooping (looping);
  229617. return movie != nil;
  229618. }
  229619. void QuickTimeMovieComponent::closeMovie()
  229620. {
  229621. stop();
  229622. QTMovieView* view = (QTMovieView*) getView();
  229623. [view setMovie: nil];
  229624. [theMovie release];
  229625. movie = 0;
  229626. movieFile = File::nonexistent;
  229627. }
  229628. bool QuickTimeMovieComponent::isMovieOpen() const
  229629. {
  229630. return movie != nil;
  229631. }
  229632. const File QuickTimeMovieComponent::getCurrentMovieFile() const
  229633. {
  229634. return movieFile;
  229635. }
  229636. void QuickTimeMovieComponent::play()
  229637. {
  229638. [theMovie play];
  229639. }
  229640. void QuickTimeMovieComponent::stop()
  229641. {
  229642. [theMovie stop];
  229643. }
  229644. bool QuickTimeMovieComponent::isPlaying() const
  229645. {
  229646. return movie != 0 && [theMovie rate] != 0;
  229647. }
  229648. void QuickTimeMovieComponent::setPosition (const double seconds)
  229649. {
  229650. if (movie != 0)
  229651. {
  229652. QTTime t;
  229653. t.timeValue = (uint64) (100000.0 * seconds);
  229654. t.timeScale = 100000;
  229655. t.flags = 0;
  229656. [theMovie setCurrentTime: t];
  229657. }
  229658. }
  229659. double QuickTimeMovieComponent::getPosition() const
  229660. {
  229661. if (movie == 0)
  229662. return 0.0;
  229663. QTTime t = [theMovie currentTime];
  229664. return t.timeValue / (double) t.timeScale;
  229665. }
  229666. void QuickTimeMovieComponent::setSpeed (const float newSpeed)
  229667. {
  229668. [theMovie setRate: newSpeed];
  229669. }
  229670. double QuickTimeMovieComponent::getMovieDuration() const
  229671. {
  229672. if (movie == 0)
  229673. return 0.0;
  229674. QTTime t = [theMovie duration];
  229675. return t.timeValue / (double) t.timeScale;
  229676. }
  229677. void QuickTimeMovieComponent::setLooping (const bool shouldLoop)
  229678. {
  229679. looping = shouldLoop;
  229680. [theMovie setAttribute: [NSNumber numberWithBool: shouldLoop]
  229681. forKey: QTMovieLoopsAttribute];
  229682. }
  229683. bool QuickTimeMovieComponent::isLooping() const
  229684. {
  229685. return looping;
  229686. }
  229687. void QuickTimeMovieComponent::setMovieVolume (const float newVolume)
  229688. {
  229689. [theMovie setVolume: newVolume];
  229690. }
  229691. float QuickTimeMovieComponent::getMovieVolume() const
  229692. {
  229693. return movie != 0 ? [theMovie volume] : 0.0f;
  229694. }
  229695. void QuickTimeMovieComponent::getMovieNormalSize (int& width, int& height) const
  229696. {
  229697. width = 0;
  229698. height = 0;
  229699. if (movie != 0)
  229700. {
  229701. NSSize s = [[theMovie attributeForKey: QTMovieNaturalSizeAttribute] sizeValue];
  229702. width = (int) s.width;
  229703. height = (int) s.height;
  229704. }
  229705. }
  229706. void QuickTimeMovieComponent::paint (Graphics& g)
  229707. {
  229708. if (movie == 0)
  229709. g.fillAll (Colours::black);
  229710. }
  229711. bool QuickTimeMovieComponent::isControllerVisible() const
  229712. {
  229713. return controllerVisible;
  229714. }
  229715. void QuickTimeMovieComponent::goToStart()
  229716. {
  229717. setPosition (0.0);
  229718. }
  229719. void QuickTimeMovieComponent::setBoundsWithCorrectAspectRatio (const Rectangle<int>& spaceToFitWithin,
  229720. const RectanglePlacement& placement)
  229721. {
  229722. int normalWidth, normalHeight;
  229723. getMovieNormalSize (normalWidth, normalHeight);
  229724. if (normalWidth > 0 && normalHeight > 0 && ! spaceToFitWithin.isEmpty())
  229725. {
  229726. double x = 0.0, y = 0.0, w = normalWidth, h = normalHeight;
  229727. placement.applyTo (x, y, w, h,
  229728. spaceToFitWithin.getX(), spaceToFitWithin.getY(),
  229729. spaceToFitWithin.getWidth(), spaceToFitWithin.getHeight());
  229730. if (w > 0 && h > 0)
  229731. {
  229732. setBounds (roundToInt (x), roundToInt (y),
  229733. roundToInt (w), roundToInt (h));
  229734. }
  229735. }
  229736. else
  229737. {
  229738. setBounds (spaceToFitWithin);
  229739. }
  229740. }
  229741. #if ! (JUCE_MAC && JUCE_64BIT)
  229742. bool juce_OpenQuickTimeMovieFromStream (InputStream* movieStream, Movie& result, Handle& dataHandle)
  229743. {
  229744. if (movieStream == 0)
  229745. return false;
  229746. File file;
  229747. QTMovie* movie = openMovieFromStream (movieStream, file);
  229748. if (movie != nil)
  229749. result = [movie quickTimeMovie];
  229750. return movie != nil;
  229751. }
  229752. #endif
  229753. #endif
  229754. /*** End of inlined file: juce_mac_QuickTimeMovieComponent.mm ***/
  229755. /*** Start of inlined file: juce_mac_AudioCDBurner.mm ***/
  229756. // (This file gets included by juce_mac_NativeCode.mm, rather than being
  229757. // compiled on its own).
  229758. #if JUCE_INCLUDED_FILE && JUCE_USE_CDBURNER
  229759. const int kilobytesPerSecond1x = 176;
  229760. END_JUCE_NAMESPACE
  229761. #define OpenDiskDevice MakeObjCClassName(OpenDiskDevice)
  229762. @interface OpenDiskDevice : NSObject
  229763. {
  229764. @public
  229765. DRDevice* device;
  229766. NSMutableArray* tracks;
  229767. bool underrunProtection;
  229768. }
  229769. - (OpenDiskDevice*) initWithDRDevice: (DRDevice*) device;
  229770. - (void) dealloc;
  229771. - (void) addSourceTrack: (JUCE_NAMESPACE::AudioSource*) source numSamples: (int) numSamples_;
  229772. - (void) burn: (JUCE_NAMESPACE::AudioCDBurner::BurnProgressListener*) listener errorString: (JUCE_NAMESPACE::String*) error
  229773. ejectAfterwards: (bool) shouldEject isFake: (bool) peformFakeBurnForTesting speed: (int) burnSpeed;
  229774. @end
  229775. #define AudioTrackProducer MakeObjCClassName(AudioTrackProducer)
  229776. @interface AudioTrackProducer : NSObject
  229777. {
  229778. JUCE_NAMESPACE::AudioSource* source;
  229779. int readPosition, lengthInFrames;
  229780. }
  229781. - (AudioTrackProducer*) init: (int) lengthInFrames;
  229782. - (AudioTrackProducer*) initWithAudioSource: (JUCE_NAMESPACE::AudioSource*) source numSamples: (int) lengthInSamples;
  229783. - (void) dealloc;
  229784. - (void) setupTrackProperties: (DRTrack*) track;
  229785. - (void) cleanupTrackAfterBurn: (DRTrack*) track;
  229786. - (BOOL) cleanupTrackAfterVerification:(DRTrack*)track;
  229787. - (uint64_t) estimateLengthOfTrack:(DRTrack*)track;
  229788. - (BOOL) prepareTrack:(DRTrack*)track forBurn:(DRBurn*)burn
  229789. toMedia:(NSDictionary*)mediaInfo;
  229790. - (BOOL) prepareTrackForVerification:(DRTrack*)track;
  229791. - (uint32_t) produceDataForTrack:(DRTrack*)track intoBuffer:(char*)buffer
  229792. length:(uint32_t)bufferLength atAddress:(uint64_t)address
  229793. blockSize:(uint32_t)blockSize ioFlags:(uint32_t*)flags;
  229794. - (uint32_t) producePreGapForTrack:(DRTrack*)track
  229795. intoBuffer:(char*)buffer length:(uint32_t)bufferLength
  229796. atAddress:(uint64_t)address blockSize:(uint32_t)blockSize
  229797. ioFlags:(uint32_t*)flags;
  229798. - (BOOL) verifyDataForTrack:(DRTrack*)track inBuffer:(const char*)buffer
  229799. length:(uint32_t)bufferLength atAddress:(uint64_t)address
  229800. blockSize:(uint32_t)blockSize ioFlags:(uint32_t*)flags;
  229801. - (uint32_t) producePreGapForTrack:(DRTrack*)track
  229802. intoBuffer:(char*)buffer length:(uint32_t)bufferLength
  229803. atAddress:(uint64_t)address blockSize:(uint32_t)blockSize
  229804. ioFlags:(uint32_t*)flags;
  229805. @end
  229806. @implementation OpenDiskDevice
  229807. - (OpenDiskDevice*) initWithDRDevice: (DRDevice*) device_
  229808. {
  229809. [super init];
  229810. device = device_;
  229811. tracks = [[NSMutableArray alloc] init];
  229812. underrunProtection = true;
  229813. return self;
  229814. }
  229815. - (void) dealloc
  229816. {
  229817. [tracks release];
  229818. [super dealloc];
  229819. }
  229820. - (void) addSourceTrack: (JUCE_NAMESPACE::AudioSource*) source_ numSamples: (int) numSamples_
  229821. {
  229822. AudioTrackProducer* p = [[AudioTrackProducer alloc] initWithAudioSource: source_ numSamples: numSamples_];
  229823. DRTrack* t = [[DRTrack alloc] initWithProducer: p];
  229824. [p setupTrackProperties: t];
  229825. [tracks addObject: t];
  229826. [t release];
  229827. [p release];
  229828. }
  229829. - (void) burn: (JUCE_NAMESPACE::AudioCDBurner::BurnProgressListener*) listener errorString: (JUCE_NAMESPACE::String*) error
  229830. ejectAfterwards: (bool) shouldEject isFake: (bool) peformFakeBurnForTesting speed: (int) burnSpeed
  229831. {
  229832. DRBurn* burn = [DRBurn burnForDevice: device];
  229833. if (! [device acquireExclusiveAccess])
  229834. {
  229835. *error = "Couldn't open or write to the CD device";
  229836. return;
  229837. }
  229838. [device acquireMediaReservation];
  229839. NSMutableDictionary* d = [[burn properties] mutableCopy];
  229840. [d autorelease];
  229841. [d setObject: [NSNumber numberWithBool: peformFakeBurnForTesting] forKey: DRBurnTestingKey];
  229842. [d setObject: [NSNumber numberWithBool: false] forKey: DRBurnVerifyDiscKey];
  229843. [d setObject: (shouldEject ? DRBurnCompletionActionEject : DRBurnCompletionActionMount) forKey: DRBurnCompletionActionKey];
  229844. if (burnSpeed > 0)
  229845. [d setObject: [NSNumber numberWithFloat: burnSpeed * JUCE_NAMESPACE::kilobytesPerSecond1x] forKey: DRBurnRequestedSpeedKey];
  229846. if (! underrunProtection)
  229847. [d setObject: [NSNumber numberWithBool: false] forKey: DRBurnUnderrunProtectionKey];
  229848. [burn setProperties: d];
  229849. [burn writeLayout: tracks];
  229850. for (;;)
  229851. {
  229852. JUCE_NAMESPACE::Thread::sleep (300);
  229853. float progress = [[[burn status] objectForKey: DRStatusPercentCompleteKey] floatValue];
  229854. if (listener != 0 && listener->audioCDBurnProgress (progress))
  229855. {
  229856. [burn abort];
  229857. *error = "User cancelled the write operation";
  229858. break;
  229859. }
  229860. if ([[[burn status] objectForKey: DRStatusStateKey] isEqualTo: DRStatusStateFailed])
  229861. {
  229862. *error = "Write operation failed";
  229863. break;
  229864. }
  229865. else if ([[[burn status] objectForKey: DRStatusStateKey] isEqualTo: DRStatusStateDone])
  229866. {
  229867. break;
  229868. }
  229869. NSString* err = (NSString*) [[[burn status] objectForKey: DRErrorStatusKey]
  229870. objectForKey: DRErrorStatusErrorStringKey];
  229871. if ([err length] > 0)
  229872. {
  229873. *error = JUCE_NAMESPACE::String::fromUTF8 ([err UTF8String]);
  229874. break;
  229875. }
  229876. }
  229877. [device releaseMediaReservation];
  229878. [device releaseExclusiveAccess];
  229879. }
  229880. @end
  229881. @implementation AudioTrackProducer
  229882. - (AudioTrackProducer*) init: (int) lengthInFrames_
  229883. {
  229884. lengthInFrames = lengthInFrames_;
  229885. readPosition = 0;
  229886. return self;
  229887. }
  229888. - (void) setupTrackProperties: (DRTrack*) track
  229889. {
  229890. NSMutableDictionary* p = [[track properties] mutableCopy];
  229891. [p setObject:[DRMSF msfWithFrames: lengthInFrames] forKey: DRTrackLengthKey];
  229892. [p setObject:[NSNumber numberWithUnsignedShort:2352] forKey: DRBlockSizeKey];
  229893. [p setObject:[NSNumber numberWithInt:0] forKey: DRDataFormKey];
  229894. [p setObject:[NSNumber numberWithInt:0] forKey: DRBlockTypeKey];
  229895. [p setObject:[NSNumber numberWithInt:0] forKey: DRTrackModeKey];
  229896. [p setObject:[NSNumber numberWithInt:0] forKey: DRSessionFormatKey];
  229897. [track setProperties: p];
  229898. [p release];
  229899. }
  229900. - (AudioTrackProducer*) initWithAudioSource: (JUCE_NAMESPACE::AudioSource*) source_ numSamples: (int) lengthInSamples
  229901. {
  229902. AudioTrackProducer* s = [self init: (lengthInSamples + 587) / 588];
  229903. if (s != nil)
  229904. s->source = source_;
  229905. return s;
  229906. }
  229907. - (void) dealloc
  229908. {
  229909. if (source != 0)
  229910. {
  229911. source->releaseResources();
  229912. delete source;
  229913. }
  229914. [super dealloc];
  229915. }
  229916. - (void) cleanupTrackAfterBurn: (DRTrack*) track
  229917. {
  229918. }
  229919. - (BOOL) cleanupTrackAfterVerification: (DRTrack*) track
  229920. {
  229921. return true;
  229922. }
  229923. - (uint64_t) estimateLengthOfTrack: (DRTrack*) track
  229924. {
  229925. return lengthInFrames;
  229926. }
  229927. - (BOOL) prepareTrack: (DRTrack*) track forBurn: (DRBurn*) burn
  229928. toMedia: (NSDictionary*) mediaInfo
  229929. {
  229930. if (source != 0)
  229931. source->prepareToPlay (44100 / 75, 44100);
  229932. readPosition = 0;
  229933. return true;
  229934. }
  229935. - (BOOL) prepareTrackForVerification: (DRTrack*) track
  229936. {
  229937. if (source != 0)
  229938. source->prepareToPlay (44100 / 75, 44100);
  229939. return true;
  229940. }
  229941. - (uint32_t) produceDataForTrack: (DRTrack*) track intoBuffer: (char*) buffer
  229942. length: (uint32_t) bufferLength atAddress: (uint64_t) address
  229943. blockSize: (uint32_t) blockSize ioFlags: (uint32_t*) flags
  229944. {
  229945. if (source != 0)
  229946. {
  229947. const int numSamples = JUCE_NAMESPACE::jmin ((int) bufferLength / 4, (lengthInFrames * (44100 / 75)) - readPosition);
  229948. if (numSamples > 0)
  229949. {
  229950. JUCE_NAMESPACE::AudioSampleBuffer tempBuffer (2, numSamples);
  229951. JUCE_NAMESPACE::AudioSourceChannelInfo info;
  229952. info.buffer = &tempBuffer;
  229953. info.startSample = 0;
  229954. info.numSamples = numSamples;
  229955. source->getNextAudioBlock (info);
  229956. JUCE_NAMESPACE::AudioDataConverters::convertFloatToInt16LE (tempBuffer.getSampleData (0),
  229957. buffer, numSamples, 4);
  229958. JUCE_NAMESPACE::AudioDataConverters::convertFloatToInt16LE (tempBuffer.getSampleData (1),
  229959. buffer + 2, numSamples, 4);
  229960. readPosition += numSamples;
  229961. }
  229962. return numSamples * 4;
  229963. }
  229964. return 0;
  229965. }
  229966. - (uint32_t) producePreGapForTrack: (DRTrack*) track
  229967. intoBuffer: (char*) buffer length: (uint32_t) bufferLength
  229968. atAddress: (uint64_t) address blockSize: (uint32_t) blockSize
  229969. ioFlags: (uint32_t*) flags
  229970. {
  229971. zeromem (buffer, bufferLength);
  229972. return bufferLength;
  229973. }
  229974. - (BOOL) verifyDataForTrack: (DRTrack*) track inBuffer: (const char*) buffer
  229975. length: (uint32_t) bufferLength atAddress: (uint64_t) address
  229976. blockSize: (uint32_t) blockSize ioFlags: (uint32_t*) flags
  229977. {
  229978. return true;
  229979. }
  229980. @end
  229981. BEGIN_JUCE_NAMESPACE
  229982. class AudioCDBurner::Pimpl : public Timer
  229983. {
  229984. public:
  229985. Pimpl (AudioCDBurner& owner_, const int deviceIndex)
  229986. : device (0), owner (owner_)
  229987. {
  229988. DRDevice* dev = [[DRDevice devices] objectAtIndex: deviceIndex];
  229989. if (dev != 0)
  229990. {
  229991. device = [[OpenDiskDevice alloc] initWithDRDevice: dev];
  229992. lastState = getDiskState();
  229993. startTimer (1000);
  229994. }
  229995. }
  229996. ~Pimpl()
  229997. {
  229998. stopTimer();
  229999. [device release];
  230000. }
  230001. void timerCallback()
  230002. {
  230003. const DiskState state = getDiskState();
  230004. if (state != lastState)
  230005. {
  230006. lastState = state;
  230007. owner.sendChangeMessage (&owner);
  230008. }
  230009. }
  230010. DiskState getDiskState() const
  230011. {
  230012. if ([device->device isValid])
  230013. {
  230014. NSDictionary* status = [device->device status];
  230015. NSString* state = [status objectForKey: DRDeviceMediaStateKey];
  230016. if ([state isEqualTo: DRDeviceMediaStateNone])
  230017. {
  230018. if ([[status objectForKey: DRDeviceIsTrayOpenKey] boolValue])
  230019. return trayOpen;
  230020. return noDisc;
  230021. }
  230022. if ([state isEqualTo: DRDeviceMediaStateMediaPresent])
  230023. {
  230024. if ([[[status objectForKey: DRDeviceMediaInfoKey] objectForKey: DRDeviceMediaBlocksFreeKey] intValue] > 0)
  230025. return writableDiskPresent;
  230026. else
  230027. return readOnlyDiskPresent;
  230028. }
  230029. }
  230030. return unknown;
  230031. }
  230032. bool openTray() { return [device->device isValid] && [device->device ejectMedia]; }
  230033. const Array<int> getAvailableWriteSpeeds() const
  230034. {
  230035. Array<int> results;
  230036. if ([device->device isValid])
  230037. {
  230038. NSArray* speeds = [[[device->device status] objectForKey: DRDeviceMediaInfoKey] objectForKey: DRDeviceBurnSpeedsKey];
  230039. for (unsigned int i = 0; i < [speeds count]; ++i)
  230040. {
  230041. const int kbPerSec = [[speeds objectAtIndex: i] intValue];
  230042. results.add (kbPerSec / kilobytesPerSecond1x);
  230043. }
  230044. }
  230045. return results;
  230046. }
  230047. bool setBufferUnderrunProtection (const bool shouldBeEnabled)
  230048. {
  230049. if ([device->device isValid])
  230050. {
  230051. device->underrunProtection = shouldBeEnabled;
  230052. return shouldBeEnabled && [[[device->device status] objectForKey: DRDeviceCanUnderrunProtectCDKey] boolValue];
  230053. }
  230054. return false;
  230055. }
  230056. int getNumAvailableAudioBlocks() const
  230057. {
  230058. return [[[[device->device status] objectForKey: DRDeviceMediaInfoKey]
  230059. objectForKey: DRDeviceMediaBlocksFreeKey] intValue];
  230060. }
  230061. OpenDiskDevice* device;
  230062. private:
  230063. DiskState lastState;
  230064. AudioCDBurner& owner;
  230065. };
  230066. AudioCDBurner::AudioCDBurner (const int deviceIndex)
  230067. {
  230068. pimpl = new Pimpl (*this, deviceIndex);
  230069. }
  230070. AudioCDBurner::~AudioCDBurner()
  230071. {
  230072. }
  230073. AudioCDBurner* AudioCDBurner::openDevice (const int deviceIndex)
  230074. {
  230075. ScopedPointer <AudioCDBurner> b (new AudioCDBurner (deviceIndex));
  230076. if (b->pimpl->device == 0)
  230077. b = 0;
  230078. return b.release();
  230079. }
  230080. static NSArray* findDiskBurnerDevices()
  230081. {
  230082. NSMutableArray* results = [NSMutableArray array];
  230083. NSArray* devs = [DRDevice devices];
  230084. if (devs != 0)
  230085. {
  230086. int num = [devs count];
  230087. int i;
  230088. for (i = 0; i < num; ++i)
  230089. {
  230090. NSDictionary* dic = [[devs objectAtIndex: i] info];
  230091. NSString* name = [dic valueForKey: DRDeviceProductNameKey];
  230092. if (name != nil)
  230093. [results addObject: name];
  230094. }
  230095. }
  230096. return results;
  230097. }
  230098. const StringArray AudioCDBurner::findAvailableDevices()
  230099. {
  230100. NSArray* names = findDiskBurnerDevices();
  230101. StringArray s;
  230102. for (unsigned int i = 0; i < [names count]; ++i)
  230103. s.add (String::fromUTF8 ([[names objectAtIndex: i] UTF8String]));
  230104. return s;
  230105. }
  230106. AudioCDBurner::DiskState AudioCDBurner::getDiskState() const
  230107. {
  230108. return pimpl->getDiskState();
  230109. }
  230110. bool AudioCDBurner::isDiskPresent() const
  230111. {
  230112. return getDiskState() == writableDiskPresent;
  230113. }
  230114. bool AudioCDBurner::openTray()
  230115. {
  230116. return pimpl->openTray();
  230117. }
  230118. AudioCDBurner::DiskState AudioCDBurner::waitUntilStateChange (int timeOutMilliseconds)
  230119. {
  230120. const int64 timeout = Time::currentTimeMillis() + timeOutMilliseconds;
  230121. DiskState oldState = getDiskState();
  230122. DiskState newState = oldState;
  230123. while (newState == oldState && Time::currentTimeMillis() < timeout)
  230124. {
  230125. newState = getDiskState();
  230126. Thread::sleep (100);
  230127. }
  230128. return newState;
  230129. }
  230130. const Array<int> AudioCDBurner::getAvailableWriteSpeeds() const
  230131. {
  230132. return pimpl->getAvailableWriteSpeeds();
  230133. }
  230134. bool AudioCDBurner::setBufferUnderrunProtection (const bool shouldBeEnabled)
  230135. {
  230136. return pimpl->setBufferUnderrunProtection (shouldBeEnabled);
  230137. }
  230138. int AudioCDBurner::getNumAvailableAudioBlocks() const
  230139. {
  230140. return pimpl->getNumAvailableAudioBlocks();
  230141. }
  230142. bool AudioCDBurner::addAudioTrack (AudioSource* source, int numSamps)
  230143. {
  230144. if ([pimpl->device->device isValid])
  230145. {
  230146. [pimpl->device addSourceTrack: source numSamples: numSamps];
  230147. return true;
  230148. }
  230149. return false;
  230150. }
  230151. const String AudioCDBurner::burn (JUCE_NAMESPACE::AudioCDBurner::BurnProgressListener* listener,
  230152. bool ejectDiscAfterwards,
  230153. bool performFakeBurnForTesting,
  230154. int writeSpeed)
  230155. {
  230156. String error ("Couldn't open or write to the CD device");
  230157. if ([pimpl->device->device isValid])
  230158. {
  230159. error = String::empty;
  230160. [pimpl->device burn: listener
  230161. errorString: &error
  230162. ejectAfterwards: ejectDiscAfterwards
  230163. isFake: performFakeBurnForTesting
  230164. speed: writeSpeed];
  230165. }
  230166. return error;
  230167. }
  230168. #endif
  230169. #if JUCE_INCLUDED_FILE && JUCE_USE_CDREADER
  230170. void AudioCDReader::ejectDisk()
  230171. {
  230172. const ScopedAutoReleasePool p;
  230173. [[NSWorkspace sharedWorkspace] unmountAndEjectDeviceAtPath: juceStringToNS (volumeDir.getFullPathName())];
  230174. }
  230175. #endif
  230176. /*** End of inlined file: juce_mac_AudioCDBurner.mm ***/
  230177. /*** Start of inlined file: juce_mac_MessageManager.mm ***/
  230178. // (This file gets included by juce_mac_NativeCode.mm, rather than being
  230179. // compiled on its own).
  230180. #if JUCE_INCLUDED_FILE
  230181. /* When you use multiple DLLs which share similarly-named obj-c classes - like
  230182. for example having more than one juce plugin loaded into a host, then when a
  230183. method is called, the actual code that runs might actually be in a different module
  230184. than the one you expect... So any calls to library functions or statics that are
  230185. made inside obj-c methods will probably end up getting executed in a different DLL's
  230186. memory space. Not a great thing to happen - this obviously leads to bizarre crashes.
  230187. To work around this insanity, I'm only allowing obj-c methods to make calls to
  230188. virtual methods of an object that's known to live inside the right module's space.
  230189. */
  230190. class AppDelegateRedirector
  230191. {
  230192. public:
  230193. AppDelegateRedirector()
  230194. {
  230195. #if MAC_OS_X_VERSION_MIN_REQUIRED > MAC_OS_X_VERSION_10_4
  230196. runLoop = CFRunLoopGetMain();
  230197. #else
  230198. runLoop = CFRunLoopGetCurrent();
  230199. #endif
  230200. CFRunLoopSourceContext sourceContext;
  230201. zerostruct (sourceContext);
  230202. sourceContext.info = this;
  230203. sourceContext.perform = runLoopSourceCallback;
  230204. runLoopSource = CFRunLoopSourceCreate (kCFAllocatorDefault, 1, &sourceContext);
  230205. CFRunLoopAddSource (runLoop, runLoopSource, kCFRunLoopCommonModes);
  230206. }
  230207. virtual ~AppDelegateRedirector()
  230208. {
  230209. CFRunLoopRemoveSource (runLoop, runLoopSource, kCFRunLoopCommonModes);
  230210. CFRunLoopSourceInvalidate (runLoopSource);
  230211. CFRelease (runLoopSource);
  230212. while (messages.size() > 0)
  230213. delete static_cast <Message*> (messages.remove(0));
  230214. }
  230215. virtual NSApplicationTerminateReply shouldTerminate()
  230216. {
  230217. if (JUCEApplication::getInstance() != 0)
  230218. {
  230219. JUCEApplication::getInstance()->systemRequestedQuit();
  230220. return NSTerminateCancel;
  230221. }
  230222. return NSTerminateNow;
  230223. }
  230224. virtual BOOL openFile (const NSString* filename)
  230225. {
  230226. if (JUCEApplication::getInstance() != 0)
  230227. {
  230228. JUCEApplication::getInstance()->anotherInstanceStarted (nsStringToJuce (filename));
  230229. return YES;
  230230. }
  230231. return NO;
  230232. }
  230233. virtual void openFiles (NSArray* filenames)
  230234. {
  230235. StringArray files;
  230236. for (unsigned int i = 0; i < [filenames count]; ++i)
  230237. {
  230238. String filename (nsStringToJuce ((NSString*) [filenames objectAtIndex: i]));
  230239. if (filename.containsChar (' '))
  230240. filename = filename.quoted('"');
  230241. files.add (filename);
  230242. }
  230243. if (files.size() > 0 && JUCEApplication::getInstance() != 0)
  230244. {
  230245. JUCEApplication::getInstance()->anotherInstanceStarted (files.joinIntoString (" "));
  230246. }
  230247. }
  230248. virtual void focusChanged()
  230249. {
  230250. juce_HandleProcessFocusChange();
  230251. }
  230252. struct CallbackMessagePayload
  230253. {
  230254. MessageCallbackFunction* function;
  230255. void* parameter;
  230256. void* volatile result;
  230257. bool volatile hasBeenExecuted;
  230258. };
  230259. virtual void performCallback (CallbackMessagePayload* pl)
  230260. {
  230261. pl->result = (*pl->function) (pl->parameter);
  230262. pl->hasBeenExecuted = true;
  230263. }
  230264. virtual void deleteSelf()
  230265. {
  230266. delete this;
  230267. }
  230268. void postMessage (void* m)
  230269. {
  230270. messages.add (m);
  230271. CFRunLoopSourceSignal (runLoopSource);
  230272. CFRunLoopWakeUp (runLoop);
  230273. }
  230274. private:
  230275. CFRunLoopRef runLoop;
  230276. CFRunLoopSourceRef runLoopSource;
  230277. Array <void*, CriticalSection> messages;
  230278. void runLoopCallback()
  230279. {
  230280. int numDispatched = 0;
  230281. do
  230282. {
  230283. void* const nextMessage = messages.remove (0);
  230284. if (nextMessage == 0)
  230285. return;
  230286. const ScopedAutoReleasePool pool;
  230287. MessageManager::getInstance()->deliverMessage (nextMessage);
  230288. } while (++numDispatched <= 4);
  230289. CFRunLoopSourceSignal (runLoopSource);
  230290. CFRunLoopWakeUp (runLoop);
  230291. }
  230292. static void runLoopSourceCallback (void* info)
  230293. {
  230294. static_cast <AppDelegateRedirector*> (info)->runLoopCallback();
  230295. }
  230296. };
  230297. END_JUCE_NAMESPACE
  230298. using namespace JUCE_NAMESPACE;
  230299. #define JuceAppDelegate MakeObjCClassName(JuceAppDelegate)
  230300. @interface JuceAppDelegate : NSObject
  230301. {
  230302. @private
  230303. id oldDelegate;
  230304. @public
  230305. AppDelegateRedirector* redirector;
  230306. }
  230307. - (JuceAppDelegate*) init;
  230308. - (void) dealloc;
  230309. - (BOOL) application: (NSApplication*) theApplication openFile: (NSString*) filename;
  230310. - (void) application: (NSApplication*) sender openFiles: (NSArray*) filenames;
  230311. - (NSApplicationTerminateReply) applicationShouldTerminate: (NSApplication*) app;
  230312. - (void) applicationDidBecomeActive: (NSNotification*) aNotification;
  230313. - (void) applicationDidResignActive: (NSNotification*) aNotification;
  230314. - (void) applicationWillUnhide: (NSNotification*) aNotification;
  230315. - (void) performCallback: (id) info;
  230316. - (void) dummyMethod;
  230317. @end
  230318. @implementation JuceAppDelegate
  230319. - (JuceAppDelegate*) init
  230320. {
  230321. [super init];
  230322. redirector = new AppDelegateRedirector();
  230323. NSNotificationCenter* center = [NSNotificationCenter defaultCenter];
  230324. if (JUCEApplication::getInstance() != 0)
  230325. {
  230326. oldDelegate = [NSApp delegate];
  230327. [NSApp setDelegate: self];
  230328. }
  230329. else
  230330. {
  230331. oldDelegate = 0;
  230332. [center addObserver: self selector: @selector (applicationDidResignActive:)
  230333. name: NSApplicationDidResignActiveNotification object: NSApp];
  230334. [center addObserver: self selector: @selector (applicationDidBecomeActive:)
  230335. name: NSApplicationDidBecomeActiveNotification object: NSApp];
  230336. [center addObserver: self selector: @selector (applicationWillUnhide:)
  230337. name: NSApplicationWillUnhideNotification object: NSApp];
  230338. }
  230339. return self;
  230340. }
  230341. - (void) dealloc
  230342. {
  230343. if (oldDelegate != 0)
  230344. [NSApp setDelegate: oldDelegate];
  230345. redirector->deleteSelf();
  230346. [super dealloc];
  230347. }
  230348. - (NSApplicationTerminateReply) applicationShouldTerminate: (NSApplication*) app
  230349. {
  230350. return redirector->shouldTerminate();
  230351. }
  230352. - (BOOL) application: (NSApplication*) app openFile: (NSString*) filename
  230353. {
  230354. return redirector->openFile (filename);
  230355. }
  230356. - (void) application: (NSApplication*) sender openFiles: (NSArray*) filenames
  230357. {
  230358. return redirector->openFiles (filenames);
  230359. }
  230360. - (void) applicationDidBecomeActive: (NSNotification*) aNotification
  230361. {
  230362. redirector->focusChanged();
  230363. }
  230364. - (void) applicationDidResignActive: (NSNotification*) aNotification
  230365. {
  230366. redirector->focusChanged();
  230367. }
  230368. - (void) applicationWillUnhide: (NSNotification*) aNotification
  230369. {
  230370. redirector->focusChanged();
  230371. }
  230372. - (void) performCallback: (id) info
  230373. {
  230374. if ([info isKindOfClass: [NSData class]])
  230375. {
  230376. AppDelegateRedirector::CallbackMessagePayload* pl
  230377. = (AppDelegateRedirector::CallbackMessagePayload*) [((NSData*) info) bytes];
  230378. if (pl != 0)
  230379. redirector->performCallback (pl);
  230380. }
  230381. else
  230382. {
  230383. jassertfalse // should never get here!
  230384. }
  230385. }
  230386. - (void) dummyMethod {} // (used as a way of running a dummy thread)
  230387. @end
  230388. BEGIN_JUCE_NAMESPACE
  230389. static JuceAppDelegate* juceAppDelegate = 0;
  230390. void MessageManager::runDispatchLoop()
  230391. {
  230392. if (! quitMessagePosted) // check that the quit message wasn't already posted..
  230393. {
  230394. const ScopedAutoReleasePool pool;
  230395. // must only be called by the message thread!
  230396. jassert (isThisTheMessageThread());
  230397. #if JUCE_CATCH_UNHANDLED_EXCEPTIONS
  230398. @try
  230399. {
  230400. [NSApp run];
  230401. }
  230402. @catch (NSException* e)
  230403. {
  230404. // An AppKit exception will kill the app, but at least this provides a chance to log it.,
  230405. std::runtime_error ex (std::string ("NSException: ") + [[e name] UTF8String] + ", Reason:" + [[e reason] UTF8String]);
  230406. JUCEApplication::sendUnhandledException (&ex, __FILE__, __LINE__);
  230407. }
  230408. @finally
  230409. {
  230410. }
  230411. #else
  230412. [NSApp run];
  230413. #endif
  230414. }
  230415. }
  230416. void MessageManager::stopDispatchLoop()
  230417. {
  230418. quitMessagePosted = true;
  230419. [NSApp stop: nil];
  230420. [NSApp activateIgnoringOtherApps: YES]; // (if the app is inactive, it sits there and ignores the quit request until the next time it gets activated)
  230421. [NSEvent startPeriodicEventsAfterDelay: 0 withPeriod: 0.1];
  230422. }
  230423. static bool isEventBlockedByModalComps (NSEvent* e)
  230424. {
  230425. if (Component::getNumCurrentlyModalComponents() == 0)
  230426. return false;
  230427. NSWindow* const w = [e window];
  230428. if (w == 0 || [w worksWhenModal])
  230429. return false;
  230430. bool isKey = false, isInputAttempt = false;
  230431. switch ([e type])
  230432. {
  230433. case NSKeyDown:
  230434. case NSKeyUp:
  230435. isKey = isInputAttempt = true;
  230436. break;
  230437. case NSLeftMouseDown:
  230438. case NSRightMouseDown:
  230439. case NSOtherMouseDown:
  230440. isInputAttempt = true;
  230441. break;
  230442. case NSLeftMouseDragged:
  230443. case NSRightMouseDragged:
  230444. case NSLeftMouseUp:
  230445. case NSRightMouseUp:
  230446. case NSOtherMouseUp:
  230447. case NSOtherMouseDragged:
  230448. if (Desktop::getInstance().getDraggingMouseSource(0) != 0)
  230449. return false;
  230450. break;
  230451. case NSMouseMoved:
  230452. case NSMouseEntered:
  230453. case NSMouseExited:
  230454. case NSCursorUpdate:
  230455. case NSScrollWheel:
  230456. case NSTabletPoint:
  230457. case NSTabletProximity:
  230458. break;
  230459. default:
  230460. return false;
  230461. }
  230462. for (int i = ComponentPeer::getNumPeers(); --i >= 0;)
  230463. {
  230464. ComponentPeer* const peer = ComponentPeer::getPeer (i);
  230465. NSView* const compView = (NSView*) peer->getNativeHandle();
  230466. if ([compView window] == w)
  230467. {
  230468. if (isKey)
  230469. {
  230470. if (compView == [w firstResponder])
  230471. return false;
  230472. }
  230473. else
  230474. {
  230475. if (NSPointInRect ([compView convertPoint: [e locationInWindow] fromView: nil],
  230476. [compView bounds]))
  230477. return false;
  230478. }
  230479. }
  230480. }
  230481. if (isInputAttempt)
  230482. {
  230483. if (! [NSApp isActive])
  230484. [NSApp activateIgnoringOtherApps: YES];
  230485. Component* const modal = Component::getCurrentlyModalComponent (0);
  230486. if (modal != 0)
  230487. modal->inputAttemptWhenModal();
  230488. }
  230489. return true;
  230490. }
  230491. bool MessageManager::runDispatchLoopUntil (int millisecondsToRunFor)
  230492. {
  230493. const ScopedAutoReleasePool pool;
  230494. jassert (isThisTheMessageThread()); // must only be called by the message thread
  230495. uint32 endTime = Time::getMillisecondCounter() + millisecondsToRunFor;
  230496. while (! quitMessagePosted)
  230497. {
  230498. const ScopedAutoReleasePool pool2;
  230499. CFRunLoopRunInMode (kCFRunLoopDefaultMode, 0.001, true);
  230500. NSEvent* e = [NSApp nextEventMatchingMask: NSAnyEventMask
  230501. untilDate: [NSDate dateWithTimeIntervalSinceNow: 0.001]
  230502. inMode: NSDefaultRunLoopMode
  230503. dequeue: YES];
  230504. if (e != 0 && ! isEventBlockedByModalComps (e))
  230505. [NSApp sendEvent: e];
  230506. if (Time::getMillisecondCounter() >= endTime)
  230507. break;
  230508. }
  230509. return ! quitMessagePosted;
  230510. }
  230511. void MessageManager::doPlatformSpecificInitialisation()
  230512. {
  230513. if (juceAppDelegate == 0)
  230514. juceAppDelegate = [[JuceAppDelegate alloc] init];
  230515. // This launches a dummy thread, which forces Cocoa to initialise NSThreads
  230516. // correctly (needed prior to 10.5)
  230517. if (! [NSThread isMultiThreaded])
  230518. [NSThread detachNewThreadSelector: @selector (dummyMethod)
  230519. toTarget: juceAppDelegate
  230520. withObject: nil];
  230521. initialiseMainMenu();
  230522. }
  230523. void MessageManager::doPlatformSpecificShutdown()
  230524. {
  230525. if (juceAppDelegate != 0)
  230526. {
  230527. [[NSRunLoop currentRunLoop] cancelPerformSelectorsWithTarget: juceAppDelegate];
  230528. [[NSNotificationCenter defaultCenter] removeObserver: juceAppDelegate];
  230529. [juceAppDelegate release];
  230530. juceAppDelegate = 0;
  230531. }
  230532. }
  230533. bool juce_postMessageToSystemQueue (void* message)
  230534. {
  230535. juceAppDelegate->redirector->postMessage (message);
  230536. return true;
  230537. }
  230538. void MessageManager::broadcastMessage (const String& value) throw()
  230539. {
  230540. }
  230541. void* MessageManager::callFunctionOnMessageThread (MessageCallbackFunction* callback,
  230542. void* data)
  230543. {
  230544. if (isThisTheMessageThread())
  230545. {
  230546. return (*callback) (data);
  230547. }
  230548. else
  230549. {
  230550. // If a thread has a MessageManagerLock and then tries to call this method, it'll
  230551. // deadlock because the message manager is blocked from running, so can never
  230552. // call your function..
  230553. jassert (! MessageManager::getInstance()->currentThreadHasLockedMessageManager());
  230554. const ScopedAutoReleasePool pool;
  230555. AppDelegateRedirector::CallbackMessagePayload cmp;
  230556. cmp.function = callback;
  230557. cmp.parameter = data;
  230558. cmp.result = 0;
  230559. cmp.hasBeenExecuted = false;
  230560. [juceAppDelegate performSelectorOnMainThread: @selector (performCallback:)
  230561. withObject: [NSData dataWithBytesNoCopy: &cmp
  230562. length: sizeof (cmp)
  230563. freeWhenDone: NO]
  230564. waitUntilDone: YES];
  230565. return cmp.result;
  230566. }
  230567. }
  230568. #endif
  230569. /*** End of inlined file: juce_mac_MessageManager.mm ***/
  230570. /*** Start of inlined file: juce_mac_WebBrowserComponent.mm ***/
  230571. // (This file gets included by juce_mac_NativeCode.mm, rather than being
  230572. // compiled on its own).
  230573. #if JUCE_INCLUDED_FILE && JUCE_WEB_BROWSER
  230574. #if JUCE_MAC
  230575. END_JUCE_NAMESPACE
  230576. #define DownloadClickDetector MakeObjCClassName(DownloadClickDetector)
  230577. @interface DownloadClickDetector : NSObject
  230578. {
  230579. JUCE_NAMESPACE::WebBrowserComponent* ownerComponent;
  230580. }
  230581. - (DownloadClickDetector*) initWithWebBrowserOwner: (JUCE_NAMESPACE::WebBrowserComponent*) ownerComponent;
  230582. - (void) webView: (WebView*) webView decidePolicyForNavigationAction: (NSDictionary*) actionInformation
  230583. request: (NSURLRequest*) request
  230584. frame: (WebFrame*) frame
  230585. decisionListener: (id<WebPolicyDecisionListener>) listener;
  230586. @end
  230587. @implementation DownloadClickDetector
  230588. - (DownloadClickDetector*) initWithWebBrowserOwner: (JUCE_NAMESPACE::WebBrowserComponent*) ownerComponent_
  230589. {
  230590. [super init];
  230591. ownerComponent = ownerComponent_;
  230592. return self;
  230593. }
  230594. - (void) webView: (WebView*) sender decidePolicyForNavigationAction: (NSDictionary*) actionInformation
  230595. request: (NSURLRequest*) request
  230596. frame: (WebFrame*) frame
  230597. decisionListener: (id <WebPolicyDecisionListener>) listener
  230598. {
  230599. NSURL* url = [actionInformation valueForKey: @"WebActionOriginalURLKey"];
  230600. if (ownerComponent->pageAboutToLoad (nsStringToJuce ([url absoluteString])))
  230601. [listener use];
  230602. else
  230603. [listener ignore];
  230604. }
  230605. @end
  230606. BEGIN_JUCE_NAMESPACE
  230607. class WebBrowserComponentInternal : public NSViewComponent
  230608. {
  230609. public:
  230610. WebBrowserComponentInternal (WebBrowserComponent* owner)
  230611. {
  230612. webView = [[WebView alloc] initWithFrame: NSMakeRect (0, 0, 100.0f, 100.0f)
  230613. frameName: @""
  230614. groupName: @""];
  230615. setView (webView);
  230616. clickListener = [[DownloadClickDetector alloc] initWithWebBrowserOwner: owner];
  230617. [webView setPolicyDelegate: clickListener];
  230618. }
  230619. ~WebBrowserComponentInternal()
  230620. {
  230621. [webView setPolicyDelegate: nil];
  230622. [clickListener release];
  230623. setView (0);
  230624. }
  230625. void goToURL (const String& url,
  230626. const StringArray* headers,
  230627. const MemoryBlock* postData)
  230628. {
  230629. NSMutableURLRequest* r
  230630. = [NSMutableURLRequest requestWithURL: [NSURL URLWithString: juceStringToNS (url)]
  230631. cachePolicy: NSURLRequestUseProtocolCachePolicy
  230632. timeoutInterval: 30.0];
  230633. if (postData != 0 && postData->getSize() > 0)
  230634. {
  230635. [r setHTTPMethod: @"POST"];
  230636. [r setHTTPBody: [NSData dataWithBytes: postData->getData()
  230637. length: postData->getSize()]];
  230638. }
  230639. if (headers != 0)
  230640. {
  230641. for (int i = 0; i < headers->size(); ++i)
  230642. {
  230643. const String headerName ((*headers)[i].upToFirstOccurrenceOf (":", false, false).trim());
  230644. const String headerValue ((*headers)[i].fromFirstOccurrenceOf (":", false, false).trim());
  230645. [r setValue: juceStringToNS (headerValue)
  230646. forHTTPHeaderField: juceStringToNS (headerName)];
  230647. }
  230648. }
  230649. stop();
  230650. [[webView mainFrame] loadRequest: r];
  230651. }
  230652. void goBack()
  230653. {
  230654. [webView goBack];
  230655. }
  230656. void goForward()
  230657. {
  230658. [webView goForward];
  230659. }
  230660. void stop()
  230661. {
  230662. [webView stopLoading: nil];
  230663. }
  230664. void refresh()
  230665. {
  230666. [webView reload: nil];
  230667. }
  230668. private:
  230669. WebView* webView;
  230670. DownloadClickDetector* clickListener;
  230671. };
  230672. WebBrowserComponent::WebBrowserComponent (const bool unloadPageWhenBrowserIsHidden_)
  230673. : browser (0),
  230674. blankPageShown (false),
  230675. unloadPageWhenBrowserIsHidden (unloadPageWhenBrowserIsHidden_)
  230676. {
  230677. setOpaque (true);
  230678. addAndMakeVisible (browser = new WebBrowserComponentInternal (this));
  230679. }
  230680. WebBrowserComponent::~WebBrowserComponent()
  230681. {
  230682. deleteAndZero (browser);
  230683. }
  230684. void WebBrowserComponent::goToURL (const String& url,
  230685. const StringArray* headers,
  230686. const MemoryBlock* postData)
  230687. {
  230688. lastURL = url;
  230689. lastHeaders.clear();
  230690. if (headers != 0)
  230691. lastHeaders = *headers;
  230692. lastPostData.setSize (0);
  230693. if (postData != 0)
  230694. lastPostData = *postData;
  230695. blankPageShown = false;
  230696. browser->goToURL (url, headers, postData);
  230697. }
  230698. void WebBrowserComponent::stop()
  230699. {
  230700. browser->stop();
  230701. }
  230702. void WebBrowserComponent::goBack()
  230703. {
  230704. lastURL = String::empty;
  230705. blankPageShown = false;
  230706. browser->goBack();
  230707. }
  230708. void WebBrowserComponent::goForward()
  230709. {
  230710. lastURL = String::empty;
  230711. browser->goForward();
  230712. }
  230713. void WebBrowserComponent::refresh()
  230714. {
  230715. browser->refresh();
  230716. }
  230717. void WebBrowserComponent::paint (Graphics& g)
  230718. {
  230719. }
  230720. void WebBrowserComponent::checkWindowAssociation()
  230721. {
  230722. if (isShowing())
  230723. {
  230724. if (blankPageShown)
  230725. goBack();
  230726. }
  230727. else
  230728. {
  230729. if (unloadPageWhenBrowserIsHidden && ! blankPageShown)
  230730. {
  230731. // when the component becomes invisible, some stuff like flash
  230732. // carries on playing audio, so we need to force it onto a blank
  230733. // page to avoid this, (and send it back when it's made visible again).
  230734. blankPageShown = true;
  230735. browser->goToURL ("about:blank", 0, 0);
  230736. }
  230737. }
  230738. }
  230739. void WebBrowserComponent::reloadLastURL()
  230740. {
  230741. if (lastURL.isNotEmpty())
  230742. {
  230743. goToURL (lastURL, &lastHeaders, &lastPostData);
  230744. lastURL = String::empty;
  230745. }
  230746. }
  230747. void WebBrowserComponent::parentHierarchyChanged()
  230748. {
  230749. checkWindowAssociation();
  230750. }
  230751. void WebBrowserComponent::resized()
  230752. {
  230753. browser->setSize (getWidth(), getHeight());
  230754. }
  230755. void WebBrowserComponent::visibilityChanged()
  230756. {
  230757. checkWindowAssociation();
  230758. }
  230759. bool WebBrowserComponent::pageAboutToLoad (const String& url)
  230760. {
  230761. return true;
  230762. }
  230763. #else
  230764. WebBrowserComponent::WebBrowserComponent (const bool unloadPageWhenBrowserIsHidden_)
  230765. {
  230766. }
  230767. WebBrowserComponent::~WebBrowserComponent()
  230768. {
  230769. }
  230770. void WebBrowserComponent::goToURL (const String& url,
  230771. const StringArray* headers,
  230772. const MemoryBlock* postData)
  230773. {
  230774. }
  230775. void WebBrowserComponent::stop()
  230776. {
  230777. }
  230778. void WebBrowserComponent::goBack()
  230779. {
  230780. }
  230781. void WebBrowserComponent::goForward()
  230782. {
  230783. }
  230784. void WebBrowserComponent::refresh()
  230785. {
  230786. }
  230787. void WebBrowserComponent::paint (Graphics& g)
  230788. {
  230789. }
  230790. void WebBrowserComponent::checkWindowAssociation()
  230791. {
  230792. }
  230793. void WebBrowserComponent::reloadLastURL()
  230794. {
  230795. }
  230796. void WebBrowserComponent::parentHierarchyChanged()
  230797. {
  230798. }
  230799. void WebBrowserComponent::resized()
  230800. {
  230801. }
  230802. void WebBrowserComponent::visibilityChanged()
  230803. {
  230804. }
  230805. bool WebBrowserComponent::pageAboutToLoad (const String& url)
  230806. {
  230807. return true;
  230808. }
  230809. #endif
  230810. #endif
  230811. /*** End of inlined file: juce_mac_WebBrowserComponent.mm ***/
  230812. /*** Start of inlined file: juce_mac_CoreAudio.cpp ***/
  230813. // (This file gets included by juce_mac_NativeCode.mm, rather than being
  230814. // compiled on its own).
  230815. #if JUCE_INCLUDED_FILE
  230816. #ifndef JUCE_COREAUDIO_ERROR_LOGGING_ENABLED
  230817. #define JUCE_COREAUDIO_ERROR_LOGGING_ENABLED 1
  230818. #endif
  230819. #undef log
  230820. #if JUCE_COREAUDIO_LOGGING_ENABLED
  230821. #define log(a) Logger::writeToLog (a)
  230822. #else
  230823. #define log(a)
  230824. #endif
  230825. #undef OK
  230826. #if JUCE_COREAUDIO_ERROR_LOGGING_ENABLED
  230827. static bool logAnyErrors_CoreAudio (const OSStatus err, const int lineNum)
  230828. {
  230829. if (err == noErr)
  230830. return true;
  230831. Logger::writeToLog ("CoreAudio error: " + String (lineNum) + " - " + String::toHexString ((int) err));
  230832. jassertfalse
  230833. return false;
  230834. }
  230835. #define OK(a) logAnyErrors_CoreAudio (a, __LINE__)
  230836. #else
  230837. #define OK(a) (a == noErr)
  230838. #endif
  230839. class CoreAudioInternal : public Timer
  230840. {
  230841. public:
  230842. CoreAudioInternal (AudioDeviceID id)
  230843. : inputLatency (0),
  230844. outputLatency (0),
  230845. callback (0),
  230846. #if MAC_OS_X_VERSION_MIN_REQUIRED >= MAC_OS_X_VERSION_10_5
  230847. audioProcID (0),
  230848. #endif
  230849. inputDevice (0),
  230850. isSlaveDevice (false),
  230851. deviceID (id),
  230852. started (false),
  230853. sampleRate (0),
  230854. bufferSize (512),
  230855. numInputChans (0),
  230856. numOutputChans (0),
  230857. callbacksAllowed (true),
  230858. numInputChannelInfos (0),
  230859. numOutputChannelInfos (0)
  230860. {
  230861. jassert (deviceID != 0);
  230862. updateDetailsFromDevice();
  230863. AudioObjectPropertyAddress pa;
  230864. pa.mSelector = kAudioObjectPropertySelectorWildcard;
  230865. pa.mScope = kAudioObjectPropertyScopeWildcard;
  230866. pa.mElement = kAudioObjectPropertyElementWildcard;
  230867. AudioObjectAddPropertyListener (deviceID, &pa, deviceListenerProc, this);
  230868. }
  230869. ~CoreAudioInternal()
  230870. {
  230871. AudioObjectPropertyAddress pa;
  230872. pa.mSelector = kAudioObjectPropertySelectorWildcard;
  230873. pa.mScope = kAudioObjectPropertyScopeWildcard;
  230874. pa.mElement = kAudioObjectPropertyElementWildcard;
  230875. AudioObjectRemovePropertyListener (deviceID, &pa, deviceListenerProc, this);
  230876. stop (false);
  230877. delete inputDevice;
  230878. }
  230879. void allocateTempBuffers()
  230880. {
  230881. const int tempBufSize = bufferSize + 4;
  230882. audioBuffer.calloc ((numInputChans + numOutputChans) * tempBufSize);
  230883. tempInputBuffers.calloc (numInputChans + 2);
  230884. tempOutputBuffers.calloc (numOutputChans + 2);
  230885. int i, count = 0;
  230886. for (i = 0; i < numInputChans; ++i)
  230887. tempInputBuffers[i] = audioBuffer + count++ * tempBufSize;
  230888. for (i = 0; i < numOutputChans; ++i)
  230889. tempOutputBuffers[i] = audioBuffer + count++ * tempBufSize;
  230890. }
  230891. // returns the number of actual available channels
  230892. void fillInChannelInfo (const bool input)
  230893. {
  230894. int chanNum = 0;
  230895. UInt32 size;
  230896. AudioObjectPropertyAddress pa;
  230897. pa.mSelector = kAudioDevicePropertyStreamConfiguration;
  230898. pa.mScope = input ? kAudioDevicePropertyScopeInput : kAudioDevicePropertyScopeOutput;
  230899. pa.mElement = kAudioObjectPropertyElementMaster;
  230900. if (OK (AudioObjectGetPropertyDataSize (deviceID, &pa, 0, 0, &size)))
  230901. {
  230902. HeapBlock <AudioBufferList> bufList;
  230903. bufList.calloc (size, 1);
  230904. if (OK (AudioObjectGetPropertyData (deviceID, &pa, 0, 0, &size, bufList)))
  230905. {
  230906. const int numStreams = bufList->mNumberBuffers;
  230907. for (int i = 0; i < numStreams; ++i)
  230908. {
  230909. const AudioBuffer& b = bufList->mBuffers[i];
  230910. for (unsigned int j = 0; j < b.mNumberChannels; ++j)
  230911. {
  230912. String name;
  230913. {
  230914. char channelName [256];
  230915. zerostruct (channelName);
  230916. UInt32 nameSize = sizeof (channelName);
  230917. UInt32 channelNum = chanNum + 1;
  230918. pa.mSelector = kAudioDevicePropertyChannelName;
  230919. if (AudioObjectGetPropertyData (deviceID, &pa, sizeof (channelNum), &channelNum, &nameSize, channelName) == noErr)
  230920. name = String::fromUTF8 (channelName, nameSize);
  230921. }
  230922. if (input)
  230923. {
  230924. if (activeInputChans[chanNum])
  230925. {
  230926. inputChannelInfo [numInputChannelInfos].streamNum = i;
  230927. inputChannelInfo [numInputChannelInfos].dataOffsetSamples = j;
  230928. inputChannelInfo [numInputChannelInfos].dataStrideSamples = b.mNumberChannels;
  230929. ++numInputChannelInfos;
  230930. }
  230931. if (name.isEmpty())
  230932. name << "Input " << (chanNum + 1);
  230933. inChanNames.add (name);
  230934. }
  230935. else
  230936. {
  230937. if (activeOutputChans[chanNum])
  230938. {
  230939. outputChannelInfo [numOutputChannelInfos].streamNum = i;
  230940. outputChannelInfo [numOutputChannelInfos].dataOffsetSamples = j;
  230941. outputChannelInfo [numOutputChannelInfos].dataStrideSamples = b.mNumberChannels;
  230942. ++numOutputChannelInfos;
  230943. }
  230944. if (name.isEmpty())
  230945. name << "Output " << (chanNum + 1);
  230946. outChanNames.add (name);
  230947. }
  230948. ++chanNum;
  230949. }
  230950. }
  230951. }
  230952. }
  230953. }
  230954. void updateDetailsFromDevice()
  230955. {
  230956. stopTimer();
  230957. if (deviceID == 0)
  230958. return;
  230959. const ScopedLock sl (callbackLock);
  230960. Float64 sr;
  230961. UInt32 size = sizeof (Float64);
  230962. AudioObjectPropertyAddress pa;
  230963. pa.mSelector = kAudioDevicePropertyNominalSampleRate;
  230964. pa.mScope = kAudioObjectPropertyScopeWildcard;
  230965. pa.mElement = kAudioObjectPropertyElementMaster;
  230966. if (OK (AudioObjectGetPropertyData (deviceID, &pa, 0, 0, &size, &sr)))
  230967. sampleRate = sr;
  230968. UInt32 framesPerBuf;
  230969. size = sizeof (framesPerBuf);
  230970. pa.mSelector = kAudioDevicePropertyBufferFrameSize;
  230971. if (OK (AudioObjectGetPropertyData (deviceID, &pa, 0, 0, &size, &framesPerBuf)))
  230972. {
  230973. bufferSize = framesPerBuf;
  230974. allocateTempBuffers();
  230975. }
  230976. bufferSizes.clear();
  230977. pa.mSelector = kAudioDevicePropertyBufferFrameSizeRange;
  230978. if (OK (AudioObjectGetPropertyDataSize (deviceID, &pa, 0, 0, &size)))
  230979. {
  230980. HeapBlock <AudioValueRange> ranges;
  230981. ranges.calloc (size, 1);
  230982. if (OK (AudioObjectGetPropertyData (deviceID, &pa, 0, 0, &size, ranges)))
  230983. {
  230984. bufferSizes.add ((int) ranges[0].mMinimum);
  230985. for (int i = 32; i < 2048; i += 32)
  230986. {
  230987. for (int j = size / (int) sizeof (AudioValueRange); --j >= 0;)
  230988. {
  230989. if (i >= ranges[j].mMinimum && i <= ranges[j].mMaximum)
  230990. {
  230991. bufferSizes.addIfNotAlreadyThere (i);
  230992. break;
  230993. }
  230994. }
  230995. }
  230996. if (bufferSize > 0)
  230997. bufferSizes.addIfNotAlreadyThere (bufferSize);
  230998. }
  230999. }
  231000. if (bufferSizes.size() == 0 && bufferSize > 0)
  231001. bufferSizes.add (bufferSize);
  231002. sampleRates.clear();
  231003. const double possibleRates[] = { 44100.0, 48000.0, 88200.0, 96000.0, 176400.0, 192000.0 };
  231004. String rates;
  231005. pa.mSelector = kAudioDevicePropertyAvailableNominalSampleRates;
  231006. if (OK (AudioObjectGetPropertyDataSize (deviceID, &pa, 0, 0, &size)))
  231007. {
  231008. HeapBlock <AudioValueRange> ranges;
  231009. ranges.calloc (size, 1);
  231010. if (OK (AudioObjectGetPropertyData (deviceID, &pa, 0, 0, &size, ranges)))
  231011. {
  231012. for (int i = 0; i < numElementsInArray (possibleRates); ++i)
  231013. {
  231014. bool ok = false;
  231015. for (int j = size / (int) sizeof (AudioValueRange); --j >= 0;)
  231016. if (possibleRates[i] >= ranges[j].mMinimum - 2 && possibleRates[i] <= ranges[j].mMaximum + 2)
  231017. ok = true;
  231018. if (ok)
  231019. {
  231020. sampleRates.add (possibleRates[i]);
  231021. rates << possibleRates[i] << ' ';
  231022. }
  231023. }
  231024. }
  231025. }
  231026. if (sampleRates.size() == 0 && sampleRate > 0)
  231027. {
  231028. sampleRates.add (sampleRate);
  231029. rates << sampleRate;
  231030. }
  231031. log ("sr: " + rates);
  231032. inputLatency = 0;
  231033. outputLatency = 0;
  231034. UInt32 lat;
  231035. size = sizeof (lat);
  231036. pa.mSelector = kAudioDevicePropertyLatency;
  231037. pa.mScope = kAudioDevicePropertyScopeInput;
  231038. //if (AudioDeviceGetProperty (deviceID, 0, true, kAudioDevicePropertyLatency, &size, &lat) == noErr)
  231039. if (AudioObjectGetPropertyData (deviceID, &pa, 0, 0, &size, &lat) == noErr)
  231040. inputLatency = (int) lat;
  231041. pa.mScope = kAudioDevicePropertyScopeOutput;
  231042. size = sizeof (lat);
  231043. if (AudioObjectGetPropertyData (deviceID, &pa, 0, 0, &size, &lat) == noErr)
  231044. outputLatency = (int) lat;
  231045. log ("lat: " + String (inputLatency) + " " + String (outputLatency));
  231046. inChanNames.clear();
  231047. outChanNames.clear();
  231048. inputChannelInfo.calloc (numInputChans + 2);
  231049. numInputChannelInfos = 0;
  231050. outputChannelInfo.calloc (numOutputChans + 2);
  231051. numOutputChannelInfos = 0;
  231052. fillInChannelInfo (true);
  231053. fillInChannelInfo (false);
  231054. }
  231055. const StringArray getSources (bool input)
  231056. {
  231057. StringArray s;
  231058. HeapBlock <OSType> types;
  231059. const int num = getAllDataSourcesForDevice (deviceID, input, types);
  231060. for (int i = 0; i < num; ++i)
  231061. {
  231062. AudioValueTranslation avt;
  231063. char buffer[256];
  231064. avt.mInputData = &(types[i]);
  231065. avt.mInputDataSize = sizeof (UInt32);
  231066. avt.mOutputData = buffer;
  231067. avt.mOutputDataSize = 256;
  231068. UInt32 transSize = sizeof (avt);
  231069. AudioObjectPropertyAddress pa;
  231070. pa.mSelector = kAudioDevicePropertyDataSourceNameForID;
  231071. pa.mScope = input ? kAudioDevicePropertyScopeInput : kAudioDevicePropertyScopeOutput;
  231072. pa.mElement = kAudioObjectPropertyElementMaster;
  231073. if (OK (AudioObjectGetPropertyData (deviceID, &pa, 0, 0, &transSize, &avt)))
  231074. {
  231075. DBG (buffer);
  231076. s.add (buffer);
  231077. }
  231078. }
  231079. return s;
  231080. }
  231081. int getCurrentSourceIndex (bool input) const
  231082. {
  231083. OSType currentSourceID = 0;
  231084. UInt32 size = sizeof (currentSourceID);
  231085. int result = -1;
  231086. AudioObjectPropertyAddress pa;
  231087. pa.mSelector = kAudioDevicePropertyDataSource;
  231088. pa.mScope = input ? kAudioDevicePropertyScopeInput : kAudioDevicePropertyScopeOutput;
  231089. pa.mElement = kAudioObjectPropertyElementMaster;
  231090. if (deviceID != 0)
  231091. {
  231092. if (OK (AudioObjectGetPropertyData (deviceID, &pa, 0, 0, &size, &currentSourceID)))
  231093. {
  231094. HeapBlock <OSType> types;
  231095. const int num = getAllDataSourcesForDevice (deviceID, input, types);
  231096. for (int i = 0; i < num; ++i)
  231097. {
  231098. if (types[num] == currentSourceID)
  231099. {
  231100. result = i;
  231101. break;
  231102. }
  231103. }
  231104. }
  231105. }
  231106. return result;
  231107. }
  231108. void setCurrentSourceIndex (int index, bool input)
  231109. {
  231110. if (deviceID != 0)
  231111. {
  231112. HeapBlock <OSType> types;
  231113. const int num = getAllDataSourcesForDevice (deviceID, input, types);
  231114. if (((unsigned int) index) < (unsigned int) num)
  231115. {
  231116. AudioObjectPropertyAddress pa;
  231117. pa.mSelector = kAudioDevicePropertyDataSource;
  231118. pa.mScope = input ? kAudioDevicePropertyScopeInput : kAudioDevicePropertyScopeOutput;
  231119. pa.mElement = kAudioObjectPropertyElementMaster;
  231120. OSType typeId = types[index];
  231121. OK (AudioObjectSetPropertyData (deviceID, &pa, 0, 0, sizeof (typeId), &typeId));
  231122. }
  231123. }
  231124. }
  231125. const String reopen (const BigInteger& inputChannels,
  231126. const BigInteger& outputChannels,
  231127. double newSampleRate,
  231128. int bufferSizeSamples)
  231129. {
  231130. String error;
  231131. log ("CoreAudio reopen");
  231132. callbacksAllowed = false;
  231133. stopTimer();
  231134. stop (false);
  231135. activeInputChans = inputChannels;
  231136. activeInputChans.setRange (inChanNames.size(),
  231137. activeInputChans.getHighestBit() + 1 - inChanNames.size(),
  231138. false);
  231139. activeOutputChans = outputChannels;
  231140. activeOutputChans.setRange (outChanNames.size(),
  231141. activeOutputChans.getHighestBit() + 1 - outChanNames.size(),
  231142. false);
  231143. numInputChans = activeInputChans.countNumberOfSetBits();
  231144. numOutputChans = activeOutputChans.countNumberOfSetBits();
  231145. // set sample rate
  231146. AudioObjectPropertyAddress pa;
  231147. pa.mSelector = kAudioDevicePropertyNominalSampleRate;
  231148. pa.mScope = kAudioObjectPropertyScopeWildcard;
  231149. pa.mElement = kAudioObjectPropertyElementMaster;
  231150. Float64 sr = newSampleRate;
  231151. if (! OK (AudioObjectSetPropertyData (deviceID, &pa, 0, 0, sizeof (sr), &sr)))
  231152. {
  231153. error = "Couldn't change sample rate";
  231154. }
  231155. else
  231156. {
  231157. // change buffer size
  231158. UInt32 framesPerBuf = bufferSizeSamples;
  231159. pa.mSelector = kAudioDevicePropertyBufferFrameSize;
  231160. if (! OK (AudioObjectSetPropertyData (deviceID, &pa, 0, 0, sizeof (framesPerBuf), &framesPerBuf)))
  231161. {
  231162. error = "Couldn't change buffer size";
  231163. }
  231164. else
  231165. {
  231166. // Annoyingly, after changing the rate and buffer size, some devices fail to
  231167. // correctly report their new settings until some random time in the future, so
  231168. // after calling updateDetailsFromDevice, we need to manually bodge these values
  231169. // to make sure we're using the correct numbers..
  231170. updateDetailsFromDevice();
  231171. sampleRate = newSampleRate;
  231172. bufferSize = bufferSizeSamples;
  231173. if (sampleRates.size() == 0)
  231174. error = "Device has no available sample-rates";
  231175. else if (bufferSizes.size() == 0)
  231176. error = "Device has no available buffer-sizes";
  231177. else if (inputDevice != 0)
  231178. error = inputDevice->reopen (inputChannels,
  231179. outputChannels,
  231180. newSampleRate,
  231181. bufferSizeSamples);
  231182. }
  231183. }
  231184. callbacksAllowed = true;
  231185. return error;
  231186. }
  231187. bool start (AudioIODeviceCallback* cb)
  231188. {
  231189. if (! started)
  231190. {
  231191. callback = 0;
  231192. if (deviceID != 0)
  231193. {
  231194. #if MAC_OS_X_VERSION_MIN_REQUIRED < MAC_OS_X_VERSION_10_5
  231195. if (OK (AudioDeviceAddIOProc (deviceID, audioIOProc, this)))
  231196. #else
  231197. if (OK (AudioDeviceCreateIOProcID (deviceID, audioIOProc, this, &audioProcID)))
  231198. #endif
  231199. {
  231200. if (OK (AudioDeviceStart (deviceID, audioIOProc)))
  231201. {
  231202. started = true;
  231203. }
  231204. else
  231205. {
  231206. #if MAC_OS_X_VERSION_MIN_REQUIRED < MAC_OS_X_VERSION_10_5
  231207. OK (AudioDeviceRemoveIOProc (deviceID, audioIOProc));
  231208. #else
  231209. OK (AudioDeviceDestroyIOProcID (deviceID, audioProcID));
  231210. audioProcID = 0;
  231211. #endif
  231212. }
  231213. }
  231214. }
  231215. }
  231216. if (started)
  231217. {
  231218. const ScopedLock sl (callbackLock);
  231219. callback = cb;
  231220. }
  231221. if (inputDevice != 0)
  231222. return started && inputDevice->start (cb);
  231223. else
  231224. return started;
  231225. }
  231226. void stop (bool leaveInterruptRunning)
  231227. {
  231228. {
  231229. const ScopedLock sl (callbackLock);
  231230. callback = 0;
  231231. }
  231232. if (started
  231233. && (deviceID != 0)
  231234. && ! leaveInterruptRunning)
  231235. {
  231236. OK (AudioDeviceStop (deviceID, audioIOProc));
  231237. #if MAC_OS_X_VERSION_MIN_REQUIRED < MAC_OS_X_VERSION_10_5
  231238. OK (AudioDeviceRemoveIOProc (deviceID, audioIOProc));
  231239. #else
  231240. OK (AudioDeviceDestroyIOProcID (deviceID, audioProcID));
  231241. audioProcID = 0;
  231242. #endif
  231243. started = false;
  231244. { const ScopedLock sl (callbackLock); }
  231245. // wait until it's definately stopped calling back..
  231246. for (int i = 40; --i >= 0;)
  231247. {
  231248. Thread::sleep (50);
  231249. UInt32 running = 0;
  231250. UInt32 size = sizeof (running);
  231251. AudioObjectPropertyAddress pa;
  231252. pa.mSelector = kAudioDevicePropertyDeviceIsRunning;
  231253. pa.mScope = kAudioObjectPropertyScopeWildcard;
  231254. pa.mElement = kAudioObjectPropertyElementMaster;
  231255. OK (AudioObjectGetPropertyData (deviceID, &pa, 0, 0, &size, &running));
  231256. if (running == 0)
  231257. break;
  231258. }
  231259. const ScopedLock sl (callbackLock);
  231260. }
  231261. if (inputDevice != 0)
  231262. inputDevice->stop (leaveInterruptRunning);
  231263. }
  231264. double getSampleRate() const
  231265. {
  231266. return sampleRate;
  231267. }
  231268. int getBufferSize() const
  231269. {
  231270. return bufferSize;
  231271. }
  231272. void audioCallback (const AudioBufferList* inInputData,
  231273. AudioBufferList* outOutputData)
  231274. {
  231275. int i;
  231276. const ScopedLock sl (callbackLock);
  231277. if (callback != 0)
  231278. {
  231279. if (inputDevice == 0)
  231280. {
  231281. for (i = numInputChans; --i >= 0;)
  231282. {
  231283. const CallbackDetailsForChannel& info = inputChannelInfo[i];
  231284. float* dest = tempInputBuffers [i];
  231285. const float* src = ((const float*) inInputData->mBuffers[info.streamNum].mData)
  231286. + info.dataOffsetSamples;
  231287. const int stride = info.dataStrideSamples;
  231288. if (stride != 0) // if this is zero, info is invalid
  231289. {
  231290. for (int j = bufferSize; --j >= 0;)
  231291. {
  231292. *dest++ = *src;
  231293. src += stride;
  231294. }
  231295. }
  231296. }
  231297. }
  231298. if (! isSlaveDevice)
  231299. {
  231300. if (inputDevice == 0)
  231301. {
  231302. callback->audioDeviceIOCallback (const_cast<const float**> (tempInputBuffers.getData()),
  231303. numInputChans,
  231304. tempOutputBuffers,
  231305. numOutputChans,
  231306. bufferSize);
  231307. }
  231308. else
  231309. {
  231310. jassert (inputDevice->bufferSize == bufferSize);
  231311. // Sometimes the two linked devices seem to get their callbacks in
  231312. // parallel, so we need to lock both devices to stop the input data being
  231313. // changed while inside our callback..
  231314. const ScopedLock sl2 (inputDevice->callbackLock);
  231315. callback->audioDeviceIOCallback (const_cast<const float**> (inputDevice->tempInputBuffers.getData()),
  231316. inputDevice->numInputChans,
  231317. tempOutputBuffers,
  231318. numOutputChans,
  231319. bufferSize);
  231320. }
  231321. for (i = numOutputChans; --i >= 0;)
  231322. {
  231323. const CallbackDetailsForChannel& info = outputChannelInfo[i];
  231324. const float* src = tempOutputBuffers [i];
  231325. float* dest = ((float*) outOutputData->mBuffers[info.streamNum].mData)
  231326. + info.dataOffsetSamples;
  231327. const int stride = info.dataStrideSamples;
  231328. if (stride != 0) // if this is zero, info is invalid
  231329. {
  231330. for (int j = bufferSize; --j >= 0;)
  231331. {
  231332. *dest = *src++;
  231333. dest += stride;
  231334. }
  231335. }
  231336. }
  231337. }
  231338. }
  231339. else
  231340. {
  231341. for (i = jmin (numOutputChans, numOutputChannelInfos); --i >= 0;)
  231342. {
  231343. const CallbackDetailsForChannel& info = outputChannelInfo[i];
  231344. float* dest = ((float*) outOutputData->mBuffers[info.streamNum].mData)
  231345. + info.dataOffsetSamples;
  231346. const int stride = info.dataStrideSamples;
  231347. if (stride != 0) // if this is zero, info is invalid
  231348. {
  231349. for (int j = bufferSize; --j >= 0;)
  231350. {
  231351. *dest = 0.0f;
  231352. dest += stride;
  231353. }
  231354. }
  231355. }
  231356. }
  231357. }
  231358. // called by callbacks
  231359. void deviceDetailsChanged()
  231360. {
  231361. if (callbacksAllowed)
  231362. startTimer (100);
  231363. }
  231364. void timerCallback()
  231365. {
  231366. stopTimer();
  231367. log ("CoreAudio device changed callback");
  231368. const double oldSampleRate = sampleRate;
  231369. const int oldBufferSize = bufferSize;
  231370. updateDetailsFromDevice();
  231371. if (oldBufferSize != bufferSize || oldSampleRate != sampleRate)
  231372. {
  231373. callbacksAllowed = false;
  231374. stop (false);
  231375. updateDetailsFromDevice();
  231376. callbacksAllowed = true;
  231377. }
  231378. }
  231379. CoreAudioInternal* getRelatedDevice() const
  231380. {
  231381. UInt32 size = 0;
  231382. ScopedPointer <CoreAudioInternal> result;
  231383. AudioObjectPropertyAddress pa;
  231384. pa.mSelector = kAudioDevicePropertyRelatedDevices;
  231385. pa.mScope = kAudioObjectPropertyScopeWildcard;
  231386. pa.mElement = kAudioObjectPropertyElementMaster;
  231387. if (deviceID != 0
  231388. && AudioObjectGetPropertyDataSize (deviceID, &pa, 0, 0, &size) == noErr
  231389. && size > 0)
  231390. {
  231391. HeapBlock <AudioDeviceID> devs;
  231392. devs.calloc (size, 1);
  231393. if (OK (AudioObjectGetPropertyData (deviceID, &pa, 0, 0, &size, devs)))
  231394. {
  231395. for (unsigned int i = 0; i < size / sizeof (AudioDeviceID); ++i)
  231396. {
  231397. if (devs[i] != deviceID && devs[i] != 0)
  231398. {
  231399. result = new CoreAudioInternal (devs[i]);
  231400. const bool thisIsInput = inChanNames.size() > 0 && outChanNames.size() == 0;
  231401. const bool otherIsInput = result->inChanNames.size() > 0 && result->outChanNames.size() == 0;
  231402. if (thisIsInput != otherIsInput
  231403. || (inChanNames.size() + outChanNames.size() == 0)
  231404. || (result->inChanNames.size() + result->outChanNames.size()) == 0)
  231405. break;
  231406. result = 0;
  231407. }
  231408. }
  231409. }
  231410. }
  231411. return result.release();
  231412. }
  231413. juce_UseDebuggingNewOperator
  231414. int inputLatency, outputLatency;
  231415. BigInteger activeInputChans, activeOutputChans;
  231416. StringArray inChanNames, outChanNames;
  231417. Array <double> sampleRates;
  231418. Array <int> bufferSizes;
  231419. AudioIODeviceCallback* callback;
  231420. #if MAC_OS_X_VERSION_MIN_REQUIRED >= MAC_OS_X_VERSION_10_5
  231421. AudioDeviceIOProcID audioProcID;
  231422. #endif
  231423. CoreAudioInternal* inputDevice;
  231424. bool isSlaveDevice;
  231425. private:
  231426. CriticalSection callbackLock;
  231427. AudioDeviceID deviceID;
  231428. bool started;
  231429. double sampleRate;
  231430. int bufferSize;
  231431. HeapBlock <float> audioBuffer;
  231432. int numInputChans, numOutputChans;
  231433. bool callbacksAllowed;
  231434. struct CallbackDetailsForChannel
  231435. {
  231436. int streamNum;
  231437. int dataOffsetSamples;
  231438. int dataStrideSamples;
  231439. };
  231440. int numInputChannelInfos, numOutputChannelInfos;
  231441. HeapBlock <CallbackDetailsForChannel> inputChannelInfo, outputChannelInfo;
  231442. HeapBlock <float*> tempInputBuffers, tempOutputBuffers;
  231443. CoreAudioInternal (const CoreAudioInternal&);
  231444. CoreAudioInternal& operator= (const CoreAudioInternal&);
  231445. static OSStatus audioIOProc (AudioDeviceID inDevice,
  231446. const AudioTimeStamp* inNow,
  231447. const AudioBufferList* inInputData,
  231448. const AudioTimeStamp* inInputTime,
  231449. AudioBufferList* outOutputData,
  231450. const AudioTimeStamp* inOutputTime,
  231451. void* device)
  231452. {
  231453. static_cast <CoreAudioInternal*> (device)->audioCallback (inInputData, outOutputData);
  231454. return noErr;
  231455. }
  231456. static OSStatus deviceListenerProc (AudioDeviceID /*inDevice*/, UInt32 /*inLine*/, const AudioObjectPropertyAddress* pa, void* inClientData)
  231457. {
  231458. CoreAudioInternal* const intern = static_cast <CoreAudioInternal*> (inClientData);
  231459. switch (pa->mSelector)
  231460. {
  231461. case kAudioDevicePropertyBufferSize:
  231462. case kAudioDevicePropertyBufferFrameSize:
  231463. case kAudioDevicePropertyNominalSampleRate:
  231464. case kAudioDevicePropertyStreamFormat:
  231465. case kAudioDevicePropertyDeviceIsAlive:
  231466. intern->deviceDetailsChanged();
  231467. break;
  231468. case kAudioDevicePropertyBufferSizeRange:
  231469. case kAudioDevicePropertyVolumeScalar:
  231470. case kAudioDevicePropertyMute:
  231471. case kAudioDevicePropertyPlayThru:
  231472. case kAudioDevicePropertyDataSource:
  231473. case kAudioDevicePropertyDeviceIsRunning:
  231474. break;
  231475. }
  231476. return noErr;
  231477. }
  231478. static int getAllDataSourcesForDevice (AudioDeviceID deviceID, const bool input, HeapBlock <OSType>& types)
  231479. {
  231480. AudioObjectPropertyAddress pa;
  231481. pa.mSelector = kAudioDevicePropertyDataSources;
  231482. pa.mScope = kAudioObjectPropertyScopeWildcard;
  231483. pa.mElement = kAudioObjectPropertyElementMaster;
  231484. UInt32 size = 0;
  231485. if (deviceID != 0
  231486. && OK (AudioObjectGetPropertyDataSize (deviceID, &pa, 0, 0, &size)))
  231487. {
  231488. types.calloc (size, 1);
  231489. if (OK (AudioObjectGetPropertyData (deviceID, &pa, 0, 0, &size, types)))
  231490. return size / (int) sizeof (OSType);
  231491. }
  231492. return 0;
  231493. }
  231494. };
  231495. class CoreAudioIODevice : public AudioIODevice
  231496. {
  231497. public:
  231498. CoreAudioIODevice (const String& deviceName,
  231499. AudioDeviceID inputDeviceId,
  231500. const int inputIndex_,
  231501. AudioDeviceID outputDeviceId,
  231502. const int outputIndex_)
  231503. : AudioIODevice (deviceName, "CoreAudio"),
  231504. inputIndex (inputIndex_),
  231505. outputIndex (outputIndex_),
  231506. isOpen_ (false),
  231507. isStarted (false)
  231508. {
  231509. internal = 0;
  231510. CoreAudioInternal* device = 0;
  231511. if (outputDeviceId == 0 || outputDeviceId == inputDeviceId)
  231512. {
  231513. jassert (inputDeviceId != 0);
  231514. device = new CoreAudioInternal (inputDeviceId);
  231515. }
  231516. else
  231517. {
  231518. device = new CoreAudioInternal (outputDeviceId);
  231519. if (inputDeviceId != 0)
  231520. {
  231521. CoreAudioInternal* secondDevice = new CoreAudioInternal (inputDeviceId);
  231522. device->inputDevice = secondDevice;
  231523. secondDevice->isSlaveDevice = true;
  231524. }
  231525. }
  231526. internal = device;
  231527. AudioObjectPropertyAddress pa;
  231528. pa.mSelector = kAudioObjectPropertySelectorWildcard;
  231529. pa.mScope = kAudioObjectPropertyScopeWildcard;
  231530. pa.mElement = kAudioObjectPropertyElementWildcard;
  231531. AudioObjectAddPropertyListener (kAudioObjectSystemObject, &pa, hardwareListenerProc, internal);
  231532. }
  231533. ~CoreAudioIODevice()
  231534. {
  231535. AudioObjectPropertyAddress pa;
  231536. pa.mSelector = kAudioObjectPropertySelectorWildcard;
  231537. pa.mScope = kAudioObjectPropertyScopeWildcard;
  231538. pa.mElement = kAudioObjectPropertyElementWildcard;
  231539. AudioObjectRemovePropertyListener (kAudioObjectSystemObject, &pa, hardwareListenerProc, internal);
  231540. delete internal;
  231541. }
  231542. const StringArray getOutputChannelNames()
  231543. {
  231544. return internal->outChanNames;
  231545. }
  231546. const StringArray getInputChannelNames()
  231547. {
  231548. if (internal->inputDevice != 0)
  231549. return internal->inputDevice->inChanNames;
  231550. else
  231551. return internal->inChanNames;
  231552. }
  231553. int getNumSampleRates()
  231554. {
  231555. return internal->sampleRates.size();
  231556. }
  231557. double getSampleRate (int index)
  231558. {
  231559. return internal->sampleRates [index];
  231560. }
  231561. int getNumBufferSizesAvailable()
  231562. {
  231563. return internal->bufferSizes.size();
  231564. }
  231565. int getBufferSizeSamples (int index)
  231566. {
  231567. return internal->bufferSizes [index];
  231568. }
  231569. int getDefaultBufferSize()
  231570. {
  231571. for (int i = 0; i < getNumBufferSizesAvailable(); ++i)
  231572. if (getBufferSizeSamples(i) >= 512)
  231573. return getBufferSizeSamples(i);
  231574. return 512;
  231575. }
  231576. const String open (const BigInteger& inputChannels,
  231577. const BigInteger& outputChannels,
  231578. double sampleRate,
  231579. int bufferSizeSamples)
  231580. {
  231581. isOpen_ = true;
  231582. if (bufferSizeSamples <= 0)
  231583. bufferSizeSamples = getDefaultBufferSize();
  231584. lastError = internal->reopen (inputChannels, outputChannels, sampleRate, bufferSizeSamples);
  231585. isOpen_ = lastError.isEmpty();
  231586. return lastError;
  231587. }
  231588. void close()
  231589. {
  231590. isOpen_ = false;
  231591. internal->stop (false);
  231592. }
  231593. bool isOpen()
  231594. {
  231595. return isOpen_;
  231596. }
  231597. int getCurrentBufferSizeSamples()
  231598. {
  231599. return internal != 0 ? internal->getBufferSize() : 512;
  231600. }
  231601. double getCurrentSampleRate()
  231602. {
  231603. return internal != 0 ? internal->getSampleRate() : 0;
  231604. }
  231605. int getCurrentBitDepth()
  231606. {
  231607. return 32; // no way to find out, so just assume it's high..
  231608. }
  231609. const BigInteger getActiveOutputChannels() const
  231610. {
  231611. return internal != 0 ? internal->activeOutputChans : BigInteger();
  231612. }
  231613. const BigInteger getActiveInputChannels() const
  231614. {
  231615. BigInteger chans;
  231616. if (internal != 0)
  231617. {
  231618. chans = internal->activeInputChans;
  231619. if (internal->inputDevice != 0)
  231620. chans |= internal->inputDevice->activeInputChans;
  231621. }
  231622. return chans;
  231623. }
  231624. int getOutputLatencyInSamples()
  231625. {
  231626. if (internal == 0)
  231627. return 0;
  231628. // this seems like a good guess at getting the latency right - comparing
  231629. // this with a round-trip measurement, it gets it to within a few millisecs
  231630. // for the built-in mac soundcard
  231631. return internal->outputLatency + internal->getBufferSize() * 2;
  231632. }
  231633. int getInputLatencyInSamples()
  231634. {
  231635. if (internal == 0)
  231636. return 0;
  231637. return internal->inputLatency + internal->getBufferSize() * 2;
  231638. }
  231639. void start (AudioIODeviceCallback* callback)
  231640. {
  231641. if (internal != 0 && ! isStarted)
  231642. {
  231643. if (callback != 0)
  231644. callback->audioDeviceAboutToStart (this);
  231645. isStarted = true;
  231646. internal->start (callback);
  231647. }
  231648. }
  231649. void stop()
  231650. {
  231651. if (isStarted && internal != 0)
  231652. {
  231653. AudioIODeviceCallback* const lastCallback = internal->callback;
  231654. isStarted = false;
  231655. internal->stop (true);
  231656. if (lastCallback != 0)
  231657. lastCallback->audioDeviceStopped();
  231658. }
  231659. }
  231660. bool isPlaying()
  231661. {
  231662. if (internal->callback == 0)
  231663. isStarted = false;
  231664. return isStarted;
  231665. }
  231666. const String getLastError()
  231667. {
  231668. return lastError;
  231669. }
  231670. int inputIndex, outputIndex;
  231671. juce_UseDebuggingNewOperator
  231672. private:
  231673. CoreAudioInternal* internal;
  231674. bool isOpen_, isStarted;
  231675. String lastError;
  231676. static OSStatus hardwareListenerProc (AudioDeviceID /*inDevice*/, UInt32 /*inLine*/, const AudioObjectPropertyAddress* pa, void* inClientData)
  231677. {
  231678. CoreAudioInternal* const intern = static_cast <CoreAudioInternal*> (inClientData);
  231679. switch (pa->mSelector)
  231680. {
  231681. case kAudioHardwarePropertyDevices:
  231682. intern->deviceDetailsChanged();
  231683. break;
  231684. case kAudioHardwarePropertyDefaultOutputDevice:
  231685. case kAudioHardwarePropertyDefaultInputDevice:
  231686. case kAudioHardwarePropertyDefaultSystemOutputDevice:
  231687. break;
  231688. }
  231689. return noErr;
  231690. }
  231691. CoreAudioIODevice (const CoreAudioIODevice&);
  231692. CoreAudioIODevice& operator= (const CoreAudioIODevice&);
  231693. };
  231694. class CoreAudioIODeviceType : public AudioIODeviceType
  231695. {
  231696. public:
  231697. CoreAudioIODeviceType()
  231698. : AudioIODeviceType ("CoreAudio"),
  231699. hasScanned (false)
  231700. {
  231701. }
  231702. ~CoreAudioIODeviceType()
  231703. {
  231704. }
  231705. void scanForDevices()
  231706. {
  231707. hasScanned = true;
  231708. inputDeviceNames.clear();
  231709. outputDeviceNames.clear();
  231710. inputIds.clear();
  231711. outputIds.clear();
  231712. UInt32 size;
  231713. AudioObjectPropertyAddress pa;
  231714. pa.mSelector = kAudioHardwarePropertyDevices;
  231715. pa.mScope = kAudioObjectPropertyScopeWildcard;
  231716. pa.mElement = kAudioObjectPropertyElementMaster;
  231717. if (OK (AudioObjectGetPropertyDataSize (kAudioObjectSystemObject, &pa, 0, 0, &size)))
  231718. {
  231719. HeapBlock <AudioDeviceID> devs;
  231720. devs.calloc (size, 1);
  231721. if (OK (AudioObjectGetPropertyData (kAudioObjectSystemObject, &pa, 0, 0, &size, devs)))
  231722. {
  231723. static bool alreadyLogged = false;
  231724. const int num = size / (int) sizeof (AudioDeviceID);
  231725. for (int i = 0; i < num; ++i)
  231726. {
  231727. char name [1024];
  231728. size = sizeof (name);
  231729. pa.mSelector = kAudioDevicePropertyDeviceName;
  231730. if (OK (AudioObjectGetPropertyData (devs[i], &pa, 0, 0, &size, name)))
  231731. {
  231732. const String nameString (String::fromUTF8 (name, (int) strlen (name)));
  231733. if (! alreadyLogged)
  231734. log ("CoreAudio device: " + nameString);
  231735. const int numIns = getNumChannels (devs[i], true);
  231736. const int numOuts = getNumChannels (devs[i], false);
  231737. if (numIns > 0)
  231738. {
  231739. inputDeviceNames.add (nameString);
  231740. inputIds.add (devs[i]);
  231741. }
  231742. if (numOuts > 0)
  231743. {
  231744. outputDeviceNames.add (nameString);
  231745. outputIds.add (devs[i]);
  231746. }
  231747. }
  231748. }
  231749. alreadyLogged = true;
  231750. }
  231751. }
  231752. inputDeviceNames.appendNumbersToDuplicates (false, true);
  231753. outputDeviceNames.appendNumbersToDuplicates (false, true);
  231754. }
  231755. const StringArray getDeviceNames (bool wantInputNames) const
  231756. {
  231757. jassert (hasScanned); // need to call scanForDevices() before doing this
  231758. if (wantInputNames)
  231759. return inputDeviceNames;
  231760. else
  231761. return outputDeviceNames;
  231762. }
  231763. int getDefaultDeviceIndex (bool forInput) const
  231764. {
  231765. jassert (hasScanned); // need to call scanForDevices() before doing this
  231766. AudioDeviceID deviceID;
  231767. UInt32 size = sizeof (deviceID);
  231768. // if they're asking for any input channels at all, use the default input, so we
  231769. // get the built-in mic rather than the built-in output with no inputs..
  231770. AudioObjectPropertyAddress pa;
  231771. pa.mSelector = forInput ? kAudioHardwarePropertyDefaultInputDevice : kAudioHardwarePropertyDefaultOutputDevice;
  231772. pa.mScope = kAudioObjectPropertyScopeWildcard;
  231773. pa.mElement = kAudioObjectPropertyElementMaster;
  231774. if (AudioObjectGetPropertyData (kAudioObjectSystemObject, &pa, 0, 0, &size, &deviceID) == noErr)
  231775. {
  231776. if (forInput)
  231777. {
  231778. for (int i = inputIds.size(); --i >= 0;)
  231779. if (inputIds[i] == deviceID)
  231780. return i;
  231781. }
  231782. else
  231783. {
  231784. for (int i = outputIds.size(); --i >= 0;)
  231785. if (outputIds[i] == deviceID)
  231786. return i;
  231787. }
  231788. }
  231789. return 0;
  231790. }
  231791. int getIndexOfDevice (AudioIODevice* device, bool asInput) const
  231792. {
  231793. jassert (hasScanned); // need to call scanForDevices() before doing this
  231794. CoreAudioIODevice* const d = dynamic_cast <CoreAudioIODevice*> (device);
  231795. if (d == 0)
  231796. return -1;
  231797. return asInput ? d->inputIndex
  231798. : d->outputIndex;
  231799. }
  231800. bool hasSeparateInputsAndOutputs() const { return true; }
  231801. AudioIODevice* createDevice (const String& outputDeviceName,
  231802. const String& inputDeviceName)
  231803. {
  231804. jassert (hasScanned); // need to call scanForDevices() before doing this
  231805. const int inputIndex = inputDeviceNames.indexOf (inputDeviceName);
  231806. const int outputIndex = outputDeviceNames.indexOf (outputDeviceName);
  231807. String deviceName (outputDeviceName);
  231808. if (deviceName.isEmpty())
  231809. deviceName = inputDeviceName;
  231810. if (index >= 0)
  231811. return new CoreAudioIODevice (deviceName,
  231812. inputIds [inputIndex],
  231813. inputIndex,
  231814. outputIds [outputIndex],
  231815. outputIndex);
  231816. return 0;
  231817. }
  231818. juce_UseDebuggingNewOperator
  231819. private:
  231820. StringArray inputDeviceNames, outputDeviceNames;
  231821. Array <AudioDeviceID> inputIds, outputIds;
  231822. bool hasScanned;
  231823. static int getNumChannels (AudioDeviceID deviceID, bool input)
  231824. {
  231825. int total = 0;
  231826. UInt32 size;
  231827. AudioObjectPropertyAddress pa;
  231828. pa.mSelector = kAudioDevicePropertyStreamConfiguration;
  231829. pa.mScope = input ? kAudioDevicePropertyScopeInput : kAudioDevicePropertyScopeOutput;
  231830. pa.mElement = kAudioObjectPropertyElementMaster;
  231831. if (OK (AudioObjectGetPropertyDataSize (deviceID, &pa, 0, 0, &size)))
  231832. {
  231833. HeapBlock <AudioBufferList> bufList;
  231834. bufList.calloc (size, 1);
  231835. if (OK (AudioObjectGetPropertyData (deviceID, &pa, 0, 0, &size, bufList)))
  231836. {
  231837. const int numStreams = bufList->mNumberBuffers;
  231838. for (int i = 0; i < numStreams; ++i)
  231839. {
  231840. const AudioBuffer& b = bufList->mBuffers[i];
  231841. total += b.mNumberChannels;
  231842. }
  231843. }
  231844. }
  231845. return total;
  231846. }
  231847. CoreAudioIODeviceType (const CoreAudioIODeviceType&);
  231848. CoreAudioIODeviceType& operator= (const CoreAudioIODeviceType&);
  231849. };
  231850. AudioIODeviceType* juce_createAudioIODeviceType_CoreAudio()
  231851. {
  231852. return new CoreAudioIODeviceType();
  231853. }
  231854. #undef log
  231855. #endif
  231856. /*** End of inlined file: juce_mac_CoreAudio.cpp ***/
  231857. /*** Start of inlined file: juce_mac_CoreMidi.cpp ***/
  231858. // (This file gets included by juce_mac_NativeCode.mm, rather than being
  231859. // compiled on its own).
  231860. #if JUCE_INCLUDED_FILE
  231861. #if JUCE_MAC
  231862. #undef log
  231863. #define log(a) Logger::writeToLog(a)
  231864. static bool logAnyErrorsMidi (const OSStatus err, const int lineNum)
  231865. {
  231866. if (err == noErr)
  231867. return true;
  231868. log ("CoreMidi error: " + String (lineNum) + " - " + String::toHexString ((int) err));
  231869. jassertfalse
  231870. return false;
  231871. }
  231872. #undef OK
  231873. #define OK(a) logAnyErrorsMidi(a, __LINE__)
  231874. static const String getEndpointName (MIDIEndpointRef endpoint, bool isExternal)
  231875. {
  231876. String result;
  231877. CFStringRef str = 0;
  231878. MIDIObjectGetStringProperty (endpoint, kMIDIPropertyName, &str);
  231879. if (str != 0)
  231880. {
  231881. result = PlatformUtilities::cfStringToJuceString (str);
  231882. CFRelease (str);
  231883. str = 0;
  231884. }
  231885. MIDIEntityRef entity = 0;
  231886. MIDIEndpointGetEntity (endpoint, &entity);
  231887. if (entity == 0)
  231888. return result; // probably virtual
  231889. if (result.isEmpty())
  231890. {
  231891. // endpoint name has zero length - try the entity
  231892. MIDIObjectGetStringProperty (entity, kMIDIPropertyName, &str);
  231893. if (str != 0)
  231894. {
  231895. result += PlatformUtilities::cfStringToJuceString (str);
  231896. CFRelease (str);
  231897. str = 0;
  231898. }
  231899. }
  231900. // now consider the device's name
  231901. MIDIDeviceRef device = 0;
  231902. MIDIEntityGetDevice (entity, &device);
  231903. if (device == 0)
  231904. return result;
  231905. MIDIObjectGetStringProperty (device, kMIDIPropertyName, &str);
  231906. if (str != 0)
  231907. {
  231908. const String s (PlatformUtilities::cfStringToJuceString (str));
  231909. CFRelease (str);
  231910. // if an external device has only one entity, throw away
  231911. // the endpoint name and just use the device name
  231912. if (isExternal && MIDIDeviceGetNumberOfEntities (device) < 2)
  231913. {
  231914. result = s;
  231915. }
  231916. else if (! result.startsWithIgnoreCase (s))
  231917. {
  231918. // prepend the device name to the entity name
  231919. result = (s + " " + result).trimEnd();
  231920. }
  231921. }
  231922. return result;
  231923. }
  231924. static const String getConnectedEndpointName (MIDIEndpointRef endpoint)
  231925. {
  231926. String result;
  231927. // Does the endpoint have connections?
  231928. CFDataRef connections = 0;
  231929. int numConnections = 0;
  231930. MIDIObjectGetDataProperty (endpoint, kMIDIPropertyConnectionUniqueID, &connections);
  231931. if (connections != 0)
  231932. {
  231933. numConnections = (int) (CFDataGetLength (connections) / sizeof (MIDIUniqueID));
  231934. if (numConnections > 0)
  231935. {
  231936. const SInt32* pid = reinterpret_cast <const SInt32*> (CFDataGetBytePtr (connections));
  231937. for (int i = 0; i < numConnections; ++i, ++pid)
  231938. {
  231939. MIDIUniqueID uid = EndianS32_BtoN (*pid);
  231940. MIDIObjectRef connObject;
  231941. MIDIObjectType connObjectType;
  231942. OSStatus err = MIDIObjectFindByUniqueID (uid, &connObject, &connObjectType);
  231943. if (err == noErr)
  231944. {
  231945. String s;
  231946. if (connObjectType == kMIDIObjectType_ExternalSource
  231947. || connObjectType == kMIDIObjectType_ExternalDestination)
  231948. {
  231949. // Connected to an external device's endpoint (10.3 and later).
  231950. s = getEndpointName (static_cast <MIDIEndpointRef> (connObject), true);
  231951. }
  231952. else
  231953. {
  231954. // Connected to an external device (10.2) (or something else, catch-all)
  231955. CFStringRef str = 0;
  231956. MIDIObjectGetStringProperty (connObject, kMIDIPropertyName, &str);
  231957. if (str != 0)
  231958. {
  231959. s = PlatformUtilities::cfStringToJuceString (str);
  231960. CFRelease (str);
  231961. }
  231962. }
  231963. if (s.isNotEmpty())
  231964. {
  231965. if (result.isNotEmpty())
  231966. result += ", ";
  231967. result += s;
  231968. }
  231969. }
  231970. }
  231971. }
  231972. CFRelease (connections);
  231973. }
  231974. if (result.isNotEmpty())
  231975. return result;
  231976. // Here, either the endpoint had no connections, or we failed to obtain names for any of them.
  231977. return getEndpointName (endpoint, false);
  231978. }
  231979. const StringArray MidiOutput::getDevices()
  231980. {
  231981. StringArray s;
  231982. const ItemCount num = MIDIGetNumberOfDestinations();
  231983. for (ItemCount i = 0; i < num; ++i)
  231984. {
  231985. MIDIEndpointRef dest = MIDIGetDestination (i);
  231986. if (dest != 0)
  231987. {
  231988. String name (getConnectedEndpointName (dest));
  231989. if (name.isEmpty())
  231990. name = "<error>";
  231991. s.add (name);
  231992. }
  231993. else
  231994. {
  231995. s.add ("<error>");
  231996. }
  231997. }
  231998. return s;
  231999. }
  232000. int MidiOutput::getDefaultDeviceIndex()
  232001. {
  232002. return 0;
  232003. }
  232004. static MIDIClientRef globalMidiClient;
  232005. static bool hasGlobalClientBeenCreated = false;
  232006. static bool makeSureClientExists()
  232007. {
  232008. if (! hasGlobalClientBeenCreated)
  232009. {
  232010. String name ("JUCE");
  232011. if (JUCEApplication::getInstance() != 0)
  232012. name = JUCEApplication::getInstance()->getApplicationName();
  232013. CFStringRef appName = PlatformUtilities::juceStringToCFString (name);
  232014. hasGlobalClientBeenCreated = OK (MIDIClientCreate (appName, 0, 0, &globalMidiClient));
  232015. CFRelease (appName);
  232016. }
  232017. return hasGlobalClientBeenCreated;
  232018. }
  232019. class MidiPortAndEndpoint
  232020. {
  232021. public:
  232022. MidiPortAndEndpoint (MIDIPortRef port_, MIDIEndpointRef endPoint_)
  232023. : port (port_), endPoint (endPoint_)
  232024. {
  232025. }
  232026. ~MidiPortAndEndpoint()
  232027. {
  232028. if (port != 0)
  232029. MIDIPortDispose (port);
  232030. if (port == 0 && endPoint != 0) // if port == 0, it means we created the endpoint, so it's safe to delete it
  232031. MIDIEndpointDispose (endPoint);
  232032. }
  232033. MIDIPortRef port;
  232034. MIDIEndpointRef endPoint;
  232035. };
  232036. MidiOutput* MidiOutput::openDevice (int index)
  232037. {
  232038. MidiOutput* mo = 0;
  232039. if (((unsigned int) index) < (unsigned int) MIDIGetNumberOfDestinations())
  232040. {
  232041. MIDIEndpointRef endPoint = MIDIGetDestination (index);
  232042. CFStringRef pname;
  232043. if (OK (MIDIObjectGetStringProperty (endPoint, kMIDIPropertyName, &pname)))
  232044. {
  232045. log ("CoreMidi - opening out: " + PlatformUtilities::cfStringToJuceString (pname));
  232046. if (makeSureClientExists())
  232047. {
  232048. MIDIPortRef port;
  232049. if (OK (MIDIOutputPortCreate (globalMidiClient, pname, &port)))
  232050. {
  232051. mo = new MidiOutput();
  232052. mo->internal = new MidiPortAndEndpoint (port, endPoint);
  232053. }
  232054. }
  232055. CFRelease (pname);
  232056. }
  232057. }
  232058. return mo;
  232059. }
  232060. MidiOutput* MidiOutput::createNewDevice (const String& deviceName)
  232061. {
  232062. MidiOutput* mo = 0;
  232063. if (makeSureClientExists())
  232064. {
  232065. MIDIEndpointRef endPoint;
  232066. CFStringRef name = PlatformUtilities::juceStringToCFString (deviceName);
  232067. if (OK (MIDISourceCreate (globalMidiClient, name, &endPoint)))
  232068. {
  232069. mo = new MidiOutput();
  232070. mo->internal = new MidiPortAndEndpoint (0, endPoint);
  232071. }
  232072. CFRelease (name);
  232073. }
  232074. return mo;
  232075. }
  232076. MidiOutput::~MidiOutput()
  232077. {
  232078. delete (MidiPortAndEndpoint*) internal;
  232079. }
  232080. void MidiOutput::reset()
  232081. {
  232082. }
  232083. bool MidiOutput::getVolume (float& leftVol, float& rightVol)
  232084. {
  232085. return false;
  232086. }
  232087. void MidiOutput::setVolume (float leftVol, float rightVol)
  232088. {
  232089. }
  232090. void MidiOutput::sendMessageNow (const MidiMessage& message)
  232091. {
  232092. MidiPortAndEndpoint* const mpe = (MidiPortAndEndpoint*) internal;
  232093. if (message.isSysEx())
  232094. {
  232095. const int maxPacketSize = 256;
  232096. int pos = 0, bytesLeft = message.getRawDataSize();
  232097. const int numPackets = (bytesLeft + maxPacketSize - 1) / maxPacketSize;
  232098. HeapBlock <MIDIPacketList> packets;
  232099. packets.malloc (32 * numPackets + message.getRawDataSize(), 1);
  232100. packets->numPackets = numPackets;
  232101. MIDIPacket* p = packets->packet;
  232102. for (int i = 0; i < numPackets; ++i)
  232103. {
  232104. p->timeStamp = 0;
  232105. p->length = jmin (maxPacketSize, bytesLeft);
  232106. memcpy (p->data, message.getRawData() + pos, p->length);
  232107. pos += p->length;
  232108. bytesLeft -= p->length;
  232109. p = MIDIPacketNext (p);
  232110. }
  232111. if (mpe->port != 0)
  232112. MIDISend (mpe->port, mpe->endPoint, packets);
  232113. else
  232114. MIDIReceived (mpe->endPoint, packets);
  232115. }
  232116. else
  232117. {
  232118. MIDIPacketList packets;
  232119. packets.numPackets = 1;
  232120. packets.packet[0].timeStamp = 0;
  232121. packets.packet[0].length = message.getRawDataSize();
  232122. *(int*) (packets.packet[0].data) = *(const int*) message.getRawData();
  232123. if (mpe->port != 0)
  232124. MIDISend (mpe->port, mpe->endPoint, &packets);
  232125. else
  232126. MIDIReceived (mpe->endPoint, &packets);
  232127. }
  232128. }
  232129. const StringArray MidiInput::getDevices()
  232130. {
  232131. StringArray s;
  232132. const ItemCount num = MIDIGetNumberOfSources();
  232133. for (ItemCount i = 0; i < num; ++i)
  232134. {
  232135. MIDIEndpointRef source = MIDIGetSource (i);
  232136. if (source != 0)
  232137. {
  232138. String name (getConnectedEndpointName (source));
  232139. if (name.isEmpty())
  232140. name = "<error>";
  232141. s.add (name);
  232142. }
  232143. else
  232144. {
  232145. s.add ("<error>");
  232146. }
  232147. }
  232148. return s;
  232149. }
  232150. int MidiInput::getDefaultDeviceIndex()
  232151. {
  232152. return 0;
  232153. }
  232154. struct MidiPortAndCallback
  232155. {
  232156. MidiInput* input;
  232157. MidiPortAndEndpoint* portAndEndpoint;
  232158. MidiInputCallback* callback;
  232159. MemoryBlock pendingData;
  232160. int pendingBytes;
  232161. double pendingDataTime;
  232162. bool active;
  232163. void processSysex (const uint8*& d, int& size, const double time)
  232164. {
  232165. if (*d == 0xf0)
  232166. {
  232167. pendingBytes = 0;
  232168. pendingDataTime = time;
  232169. }
  232170. pendingData.ensureSize (pendingBytes + size, false);
  232171. uint8* totalMessage = (uint8*) pendingData.getData();
  232172. uint8* dest = totalMessage + pendingBytes;
  232173. while (size > 0)
  232174. {
  232175. if (pendingBytes > 0 && *d >= 0x80)
  232176. {
  232177. if (*d >= 0xfa || *d == 0xf8)
  232178. {
  232179. callback->handleIncomingMidiMessage (input, MidiMessage (*d, time));
  232180. ++d;
  232181. --size;
  232182. }
  232183. else
  232184. {
  232185. if (*d == 0xf7)
  232186. {
  232187. *dest++ = *d++;
  232188. pendingBytes++;
  232189. --size;
  232190. }
  232191. break;
  232192. }
  232193. }
  232194. else
  232195. {
  232196. *dest++ = *d++;
  232197. pendingBytes++;
  232198. --size;
  232199. }
  232200. }
  232201. if (totalMessage [pendingBytes - 1] == 0xf7)
  232202. {
  232203. callback->handleIncomingMidiMessage (input, MidiMessage (totalMessage, pendingBytes, pendingDataTime));
  232204. pendingBytes = 0;
  232205. }
  232206. else
  232207. {
  232208. callback->handlePartialSysexMessage (input, totalMessage, pendingBytes, pendingDataTime);
  232209. }
  232210. }
  232211. };
  232212. namespace CoreMidiCallbacks
  232213. {
  232214. static CriticalSection callbackLock;
  232215. static VoidArray activeCallbacks;
  232216. }
  232217. static void midiInputProc (const MIDIPacketList* pktlist,
  232218. void* readProcRefCon,
  232219. void* srcConnRefCon)
  232220. {
  232221. double time = Time::getMillisecondCounterHiRes() * 0.001;
  232222. const double originalTime = time;
  232223. MidiPortAndCallback* const mpc = (MidiPortAndCallback*) readProcRefCon;
  232224. const ScopedLock sl (CoreMidiCallbacks::callbackLock);
  232225. if (CoreMidiCallbacks::activeCallbacks.contains (mpc) && mpc->active)
  232226. {
  232227. const MIDIPacket* packet = &pktlist->packet[0];
  232228. for (unsigned int i = 0; i < pktlist->numPackets; ++i)
  232229. {
  232230. const uint8* d = (const uint8*) (packet->data);
  232231. int size = packet->length;
  232232. while (size > 0)
  232233. {
  232234. time = originalTime;
  232235. if (mpc->pendingBytes > 0 || d[0] == 0xf0)
  232236. {
  232237. mpc->processSysex (d, size, time);
  232238. }
  232239. else
  232240. {
  232241. int used = 0;
  232242. const MidiMessage m (d, size, used, 0, time);
  232243. if (used <= 0)
  232244. {
  232245. jassertfalse // malformed midi message
  232246. break;
  232247. }
  232248. else
  232249. {
  232250. mpc->callback->handleIncomingMidiMessage (mpc->input, m);
  232251. }
  232252. size -= used;
  232253. d += used;
  232254. }
  232255. }
  232256. packet = MIDIPacketNext (packet);
  232257. }
  232258. }
  232259. }
  232260. MidiInput* MidiInput::openDevice (int index, MidiInputCallback* callback)
  232261. {
  232262. MidiInput* mi = 0;
  232263. if (((unsigned int) index) < (unsigned int) MIDIGetNumberOfSources())
  232264. {
  232265. MIDIEndpointRef endPoint = MIDIGetSource (index);
  232266. if (endPoint != 0)
  232267. {
  232268. CFStringRef pname;
  232269. if (OK (MIDIObjectGetStringProperty (endPoint, kMIDIPropertyName, &pname)))
  232270. {
  232271. log ("CoreMidi - opening inp: " + PlatformUtilities::cfStringToJuceString (pname));
  232272. if (makeSureClientExists())
  232273. {
  232274. MIDIPortRef port;
  232275. ScopedPointer <MidiPortAndCallback> mpc (new MidiPortAndCallback());
  232276. mpc->active = false;
  232277. if (OK (MIDIInputPortCreate (globalMidiClient, pname, midiInputProc, mpc, &port)))
  232278. {
  232279. if (OK (MIDIPortConnectSource (port, endPoint, 0)))
  232280. {
  232281. mpc->portAndEndpoint = new MidiPortAndEndpoint (port, endPoint);
  232282. mpc->callback = callback;
  232283. mpc->pendingBytes = 0;
  232284. mpc->pendingData.ensureSize (128);
  232285. mi = new MidiInput (getDevices() [index]);
  232286. mpc->input = mi;
  232287. mi->internal = mpc;
  232288. const ScopedLock sl (CoreMidiCallbacks::callbackLock);
  232289. CoreMidiCallbacks::activeCallbacks.add (mpc.release());
  232290. }
  232291. else
  232292. {
  232293. OK (MIDIPortDispose (port));
  232294. }
  232295. }
  232296. }
  232297. }
  232298. CFRelease (pname);
  232299. }
  232300. }
  232301. return mi;
  232302. }
  232303. MidiInput* MidiInput::createNewDevice (const String& deviceName, MidiInputCallback* callback)
  232304. {
  232305. MidiInput* mi = 0;
  232306. if (makeSureClientExists())
  232307. {
  232308. ScopedPointer <MidiPortAndCallback> mpc (new MidiPortAndCallback());
  232309. mpc->active = false;
  232310. MIDIEndpointRef endPoint;
  232311. CFStringRef name = PlatformUtilities::juceStringToCFString(deviceName);
  232312. if (OK (MIDIDestinationCreate (globalMidiClient, name, midiInputProc, mpc, &endPoint)))
  232313. {
  232314. mpc->portAndEndpoint = new MidiPortAndEndpoint (0, endPoint);
  232315. mpc->callback = callback;
  232316. mpc->pendingBytes = 0;
  232317. mpc->pendingData.ensureSize (128);
  232318. mi = new MidiInput (deviceName);
  232319. mpc->input = mi;
  232320. mi->internal = mpc;
  232321. const ScopedLock sl (CoreMidiCallbacks::callbackLock);
  232322. CoreMidiCallbacks::activeCallbacks.add (mpc.release());
  232323. }
  232324. CFRelease (name);
  232325. }
  232326. return mi;
  232327. }
  232328. MidiInput::MidiInput (const String& name_)
  232329. : name (name_)
  232330. {
  232331. }
  232332. MidiInput::~MidiInput()
  232333. {
  232334. MidiPortAndCallback* const mpc = (MidiPortAndCallback*) internal;
  232335. mpc->active = false;
  232336. {
  232337. const ScopedLock sl (CoreMidiCallbacks::callbackLock);
  232338. CoreMidiCallbacks::activeCallbacks.removeValue (mpc);
  232339. }
  232340. if (mpc->portAndEndpoint->port != 0)
  232341. OK (MIDIPortDisconnectSource (mpc->portAndEndpoint->port, mpc->portAndEndpoint->endPoint));
  232342. delete mpc->portAndEndpoint;
  232343. delete mpc;
  232344. }
  232345. void MidiInput::start()
  232346. {
  232347. const ScopedLock sl (CoreMidiCallbacks::callbackLock);
  232348. ((MidiPortAndCallback*) internal)->active = true;
  232349. }
  232350. void MidiInput::stop()
  232351. {
  232352. const ScopedLock sl (CoreMidiCallbacks::callbackLock);
  232353. ((MidiPortAndCallback*) internal)->active = false;
  232354. }
  232355. #undef log
  232356. #else
  232357. MidiOutput::~MidiOutput()
  232358. {
  232359. }
  232360. void MidiOutput::reset()
  232361. {
  232362. }
  232363. bool MidiOutput::getVolume (float& leftVol, float& rightVol)
  232364. {
  232365. return false;
  232366. }
  232367. void MidiOutput::setVolume (float leftVol, float rightVol)
  232368. {
  232369. }
  232370. void MidiOutput::sendMessageNow (const MidiMessage& message)
  232371. {
  232372. }
  232373. const StringArray MidiOutput::getDevices()
  232374. {
  232375. return StringArray();
  232376. }
  232377. MidiOutput* MidiOutput::openDevice (int index)
  232378. {
  232379. return 0;
  232380. }
  232381. const StringArray MidiInput::getDevices()
  232382. {
  232383. return StringArray();
  232384. }
  232385. MidiInput* MidiInput::openDevice (int index, MidiInputCallback* callback)
  232386. {
  232387. return 0;
  232388. }
  232389. #endif
  232390. #endif
  232391. /*** End of inlined file: juce_mac_CoreMidi.cpp ***/
  232392. /*** Start of inlined file: juce_mac_CameraDevice.mm ***/
  232393. // (This file gets included by juce_mac_NativeCode.mm, rather than being
  232394. // compiled on its own).
  232395. #if JUCE_INCLUDED_FILE && JUCE_USE_CAMERA
  232396. #if ! JUCE_QUICKTIME
  232397. #error "On the Mac, cameras use Quicktime, so if you turn on JUCE_USE_CAMERA, you also need to enable JUCE_QUICKTIME"
  232398. #endif
  232399. #define QTCaptureCallbackDelegate MakeObjCClassName(QTCaptureCallbackDelegate)
  232400. class QTCameraDeviceInteral;
  232401. END_JUCE_NAMESPACE
  232402. @interface QTCaptureCallbackDelegate : NSObject
  232403. {
  232404. @public
  232405. CameraDevice* owner;
  232406. QTCameraDeviceInteral* internal;
  232407. int64 firstPresentationTime;
  232408. int64 averageTimeOffset;
  232409. }
  232410. - (QTCaptureCallbackDelegate*) initWithOwner: (CameraDevice*) owner internalDev: (QTCameraDeviceInteral*) d;
  232411. - (void) dealloc;
  232412. - (void) captureOutput: (QTCaptureOutput*) captureOutput
  232413. didOutputVideoFrame: (CVImageBufferRef) videoFrame
  232414. withSampleBuffer: (QTSampleBuffer*) sampleBuffer
  232415. fromConnection: (QTCaptureConnection*) connection;
  232416. - (void) captureOutput: (QTCaptureFileOutput*) captureOutput
  232417. didOutputSampleBuffer: (QTSampleBuffer*) sampleBuffer
  232418. fromConnection: (QTCaptureConnection*) connection;
  232419. @end
  232420. BEGIN_JUCE_NAMESPACE
  232421. class QTCameraDeviceInteral
  232422. {
  232423. public:
  232424. QTCameraDeviceInteral (CameraDevice* owner, int index)
  232425. {
  232426. const ScopedAutoReleasePool pool;
  232427. session = [[QTCaptureSession alloc] init];
  232428. NSArray* devs = [QTCaptureDevice inputDevicesWithMediaType: QTMediaTypeVideo];
  232429. device = (QTCaptureDevice*) [devs objectAtIndex: index];
  232430. input = 0;
  232431. audioInput = 0;
  232432. audioDevice = 0;
  232433. fileOutput = 0;
  232434. imageOutput = 0;
  232435. callbackDelegate = [[QTCaptureCallbackDelegate alloc] initWithOwner: owner
  232436. internalDev: this];
  232437. NSError* err = 0;
  232438. [device retain];
  232439. [device open: &err];
  232440. if (err == 0)
  232441. {
  232442. input = [[QTCaptureDeviceInput alloc] initWithDevice: device];
  232443. audioInput = [[QTCaptureDeviceInput alloc] initWithDevice: device];
  232444. [session addInput: input error: &err];
  232445. if (err == 0)
  232446. {
  232447. resetFile();
  232448. imageOutput = [[QTCaptureDecompressedVideoOutput alloc] init];
  232449. [imageOutput setDelegate: callbackDelegate];
  232450. if (err == 0)
  232451. {
  232452. [session startRunning];
  232453. return;
  232454. }
  232455. }
  232456. }
  232457. openingError = nsStringToJuce ([err description]);
  232458. DBG (openingError);
  232459. }
  232460. ~QTCameraDeviceInteral()
  232461. {
  232462. [session stopRunning];
  232463. [session removeOutput: imageOutput];
  232464. [session release];
  232465. [input release];
  232466. [device release];
  232467. [audioDevice release];
  232468. [audioInput release];
  232469. [fileOutput release];
  232470. [imageOutput release];
  232471. [callbackDelegate release];
  232472. }
  232473. void resetFile()
  232474. {
  232475. [fileOutput recordToOutputFileURL: nil];
  232476. [session removeOutput: fileOutput];
  232477. [fileOutput release];
  232478. fileOutput = [[QTCaptureMovieFileOutput alloc] init];
  232479. [session removeInput: audioInput];
  232480. [audioInput release];
  232481. audioInput = 0;
  232482. [audioDevice release];
  232483. audioDevice = 0;
  232484. [fileOutput setDelegate: callbackDelegate];
  232485. }
  232486. void addDefaultAudioInput()
  232487. {
  232488. NSError* err = nil;
  232489. audioDevice = [QTCaptureDevice defaultInputDeviceWithMediaType: QTMediaTypeSound];
  232490. if ([audioDevice open: &err])
  232491. [audioDevice retain];
  232492. else
  232493. audioDevice = nil;
  232494. if (audioDevice != 0)
  232495. {
  232496. audioInput = [[QTCaptureDeviceInput alloc] initWithDevice: audioDevice];
  232497. [session addInput: audioInput error: &err];
  232498. }
  232499. }
  232500. void addListener (CameraImageListener* listenerToAdd)
  232501. {
  232502. const ScopedLock sl (listenerLock);
  232503. if (listeners.size() == 0)
  232504. [session addOutput: imageOutput error: nil];
  232505. listeners.addIfNotAlreadyThere (listenerToAdd);
  232506. }
  232507. void removeListener (CameraImageListener* listenerToRemove)
  232508. {
  232509. const ScopedLock sl (listenerLock);
  232510. listeners.removeValue (listenerToRemove);
  232511. if (listeners.size() == 0)
  232512. [session removeOutput: imageOutput];
  232513. }
  232514. void callListeners (CIImage* frame, int w, int h)
  232515. {
  232516. CoreGraphicsImage image (Image::ARGB, w, h, false);
  232517. CIContext* cic = [CIContext contextWithCGContext: image.context options: nil];
  232518. [cic drawImage: frame inRect: CGRectMake (0, 0, w, h) fromRect: CGRectMake (0, 0, w, h)];
  232519. CGContextFlush (image.context);
  232520. const ScopedLock sl (listenerLock);
  232521. for (int i = listeners.size(); --i >= 0;)
  232522. {
  232523. CameraImageListener* l = (CameraImageListener*) listeners[i];
  232524. if (l != 0)
  232525. l->imageReceived (image);
  232526. }
  232527. }
  232528. QTCaptureDevice* device;
  232529. QTCaptureDeviceInput* input;
  232530. QTCaptureDevice* audioDevice;
  232531. QTCaptureDeviceInput* audioInput;
  232532. QTCaptureSession* session;
  232533. QTCaptureMovieFileOutput* fileOutput;
  232534. QTCaptureDecompressedVideoOutput* imageOutput;
  232535. QTCaptureCallbackDelegate* callbackDelegate;
  232536. String openingError;
  232537. VoidArray listeners;
  232538. CriticalSection listenerLock;
  232539. };
  232540. END_JUCE_NAMESPACE
  232541. @implementation QTCaptureCallbackDelegate
  232542. - (QTCaptureCallbackDelegate*) initWithOwner: (CameraDevice*) owner_
  232543. internalDev: (QTCameraDeviceInteral*) d
  232544. {
  232545. [super init];
  232546. owner = owner_;
  232547. internal = d;
  232548. firstPresentationTime = 0;
  232549. averageTimeOffset = 0;
  232550. return self;
  232551. }
  232552. - (void) dealloc
  232553. {
  232554. [super dealloc];
  232555. }
  232556. - (void) captureOutput: (QTCaptureOutput*) captureOutput
  232557. didOutputVideoFrame: (CVImageBufferRef) videoFrame
  232558. withSampleBuffer: (QTSampleBuffer*) sampleBuffer
  232559. fromConnection: (QTCaptureConnection*) connection
  232560. {
  232561. if (internal->listeners.size() > 0)
  232562. {
  232563. const ScopedAutoReleasePool pool;
  232564. internal->callListeners ([CIImage imageWithCVImageBuffer: videoFrame],
  232565. CVPixelBufferGetWidth (videoFrame),
  232566. CVPixelBufferGetHeight (videoFrame));
  232567. }
  232568. }
  232569. - (void) captureOutput: (QTCaptureFileOutput*) captureOutput
  232570. didOutputSampleBuffer: (QTSampleBuffer*) sampleBuffer
  232571. fromConnection: (QTCaptureConnection*) connection
  232572. {
  232573. const Time now (Time::getCurrentTime());
  232574. #if MAC_OS_X_VERSION_MAX_ALLOWED >= MAC_OS_X_VERSION_10_5
  232575. NSNumber* hosttime = (NSNumber*) [sampleBuffer attributeForKey: QTSampleBufferHostTimeAttribute];
  232576. #else
  232577. NSNumber* hosttime = (NSNumber*) [sampleBuffer attributeForKey: @"hostTime"];
  232578. #endif
  232579. int64 presentationTime = (hosttime != nil)
  232580. ? ((int64) AudioConvertHostTimeToNanos ([hosttime unsignedLongLongValue]) / 1000000 + 40)
  232581. : (([sampleBuffer presentationTime].timeValue * 1000) / [sampleBuffer presentationTime].timeScale + 50);
  232582. const int64 timeDiff = now.toMilliseconds() - presentationTime;
  232583. if (firstPresentationTime == 0)
  232584. {
  232585. firstPresentationTime = presentationTime;
  232586. averageTimeOffset = timeDiff;
  232587. }
  232588. else
  232589. {
  232590. averageTimeOffset = (averageTimeOffset * 120 + timeDiff * 8) / 128;
  232591. }
  232592. }
  232593. @end
  232594. BEGIN_JUCE_NAMESPACE
  232595. class QTCaptureViewerComp : public NSViewComponent
  232596. {
  232597. public:
  232598. QTCaptureViewerComp (CameraDevice* const cameraDevice, QTCameraDeviceInteral* const internal)
  232599. {
  232600. const ScopedAutoReleasePool pool;
  232601. captureView = [[QTCaptureView alloc] init];
  232602. [captureView setCaptureSession: internal->session];
  232603. setSize (640, 480); // xxx need to somehow get the movie size - how?
  232604. setView (captureView);
  232605. }
  232606. ~QTCaptureViewerComp()
  232607. {
  232608. setView (0);
  232609. [captureView setCaptureSession: nil];
  232610. [captureView release];
  232611. }
  232612. QTCaptureView* captureView;
  232613. };
  232614. CameraDevice::CameraDevice (const String& name_, int index)
  232615. : name (name_)
  232616. {
  232617. isRecording = false;
  232618. internal = new QTCameraDeviceInteral (this, index);
  232619. }
  232620. CameraDevice::~CameraDevice()
  232621. {
  232622. stopRecording();
  232623. delete static_cast <QTCameraDeviceInteral*> (internal);
  232624. internal = 0;
  232625. }
  232626. Component* CameraDevice::createViewerComponent()
  232627. {
  232628. return new QTCaptureViewerComp (this, static_cast <QTCameraDeviceInteral*> (internal));
  232629. }
  232630. const String CameraDevice::getFileExtension()
  232631. {
  232632. return ".mov";
  232633. }
  232634. void CameraDevice::startRecordingToFile (const File& file, int quality)
  232635. {
  232636. stopRecording();
  232637. QTCameraDeviceInteral* const d = static_cast <QTCameraDeviceInteral*> (internal);
  232638. d->callbackDelegate->firstPresentationTime = 0;
  232639. file.deleteFile();
  232640. // In some versions of QT (e.g. on 10.5), if you record video without audio, the speed comes
  232641. // out wrong, so we'll put some audio in there too..,
  232642. d->addDefaultAudioInput();
  232643. [d->session addOutput: d->fileOutput error: nil];
  232644. NSEnumerator* connectionEnumerator = [[d->fileOutput connections] objectEnumerator];
  232645. for (;;)
  232646. {
  232647. QTCaptureConnection* connection = [connectionEnumerator nextObject];
  232648. if (connection == 0)
  232649. break;
  232650. QTCompressionOptions* options = 0;
  232651. NSString* mediaType = [connection mediaType];
  232652. if ([mediaType isEqualToString: QTMediaTypeVideo])
  232653. options = [QTCompressionOptions compressionOptionsWithIdentifier:
  232654. quality >= 1 ? @"QTCompressionOptionsSD480SizeH264Video"
  232655. : @"QTCompressionOptions240SizeH264Video"];
  232656. else if ([mediaType isEqualToString: QTMediaTypeSound])
  232657. options = [QTCompressionOptions compressionOptionsWithIdentifier: @"QTCompressionOptionsHighQualityAACAudio"];
  232658. [d->fileOutput setCompressionOptions: options forConnection: connection];
  232659. }
  232660. [d->fileOutput recordToOutputFileURL: [NSURL fileURLWithPath: juceStringToNS (file.getFullPathName())]];
  232661. isRecording = true;
  232662. }
  232663. const Time CameraDevice::getTimeOfFirstRecordedFrame() const
  232664. {
  232665. QTCameraDeviceInteral* const d = static_cast <QTCameraDeviceInteral*> (internal);
  232666. if (d->callbackDelegate->firstPresentationTime != 0)
  232667. return Time (d->callbackDelegate->firstPresentationTime + d->callbackDelegate->averageTimeOffset);
  232668. return Time();
  232669. }
  232670. void CameraDevice::stopRecording()
  232671. {
  232672. if (isRecording)
  232673. {
  232674. static_cast <QTCameraDeviceInteral*> (internal)->resetFile();
  232675. isRecording = false;
  232676. }
  232677. }
  232678. void CameraDevice::addListener (CameraImageListener* listenerToAdd)
  232679. {
  232680. if (listenerToAdd != 0)
  232681. static_cast <QTCameraDeviceInteral*> (internal)->addListener (listenerToAdd);
  232682. }
  232683. void CameraDevice::removeListener (CameraImageListener* listenerToRemove)
  232684. {
  232685. if (listenerToRemove != 0)
  232686. static_cast <QTCameraDeviceInteral*> (internal)->removeListener (listenerToRemove);
  232687. }
  232688. const StringArray CameraDevice::getAvailableDevices()
  232689. {
  232690. const ScopedAutoReleasePool pool;
  232691. StringArray results;
  232692. NSArray* devs = [QTCaptureDevice inputDevicesWithMediaType: QTMediaTypeVideo];
  232693. for (int i = 0; i < (int) [devs count]; ++i)
  232694. {
  232695. QTCaptureDevice* dev = (QTCaptureDevice*) [devs objectAtIndex: i];
  232696. results.add (nsStringToJuce ([dev localizedDisplayName]));
  232697. }
  232698. return results;
  232699. }
  232700. CameraDevice* CameraDevice::openDevice (int index,
  232701. int minWidth, int minHeight,
  232702. int maxWidth, int maxHeight)
  232703. {
  232704. ScopedPointer <CameraDevice> d (new CameraDevice (getAvailableDevices() [index], index));
  232705. if (static_cast <QTCameraDeviceInteral*> (d->internal)->openingError.isEmpty())
  232706. return d.release();
  232707. return 0;
  232708. }
  232709. #endif
  232710. /*** End of inlined file: juce_mac_CameraDevice.mm ***/
  232711. #endif
  232712. #endif
  232713. END_JUCE_NAMESPACE
  232714. #endif
  232715. /*** End of inlined file: juce_mac_NativeCode.mm ***/
  232716. #endif
  232717. #endif